from lora import LoRa
import time
from librpiplc import rpiplc

def main():
    rpiplc.init("RPIPLC_V6", "RPIPLC_21")
    rpiplc.pin_mode("I0.12", rpiplc.INPUT)
    rpiplc.pin_mode("EXP1_RST", rpiplc.OUTPUT)

    # Perform hardware reset of the LoRa module
    rpiplc.digital_write("EXP1_RST", 1)
    print("Hardware reset of LoRa module performed.")
    time.sleep(2)  # Wait 2 seconds to ensure the module resets

    debug = True
    serial_port = "/dev/ttySC0"
    timeout = 5000
    lora = LoRa(serial_port, timeout, timeout, debug)

    # Configure 'radio' parameters after creating the lora object
    lora._ser_write_read_verify("radio set freq 868100000", "ok")
    lora._ser_write_read_verify("radio set sf sf12", "ok")
    lora._ser_write_read_verify("radio set bw 125", "ok")
    lora._ser_write_read_verify("radio set cr 4/5", "ok")
    lora._ser_write_read_verify("radio set prlen 8", "ok")
    lora._ser_write_read_verify("radio set crc on", "ok")
    lora._ser_write_read_verify("radio set iqi off", "ok")

    while True:
        # Read value from the pin
        read_value = rpiplc.analog_read("I0.12")
        read_value_string = str(read_value)
        print("The I0.12 is reading: {}".format(read_value_string))
        # Send data
        try:
            tx_data = read_value_string  # Data to send
            lora.send_str(tx_data)
            print("Data sent: {}".format(tx_data))
        except Exception as e:
            print(f"Error sending data: {e}")
        time.sleep(10)  # Wait 10 seconds before sending again

if __name__ == "__main__":
    main()
