#---IMPORTS
from libpmux import *
from pathlib import Path
import subprocess
import serial, sys



#---CONSTANTS
ETC_TIBBO_PYTHON_DIR = "/etc/tibbo/python"
PYSERIAL_PRECHECK_TXT_FILENAME = "pyserial_precheck.txt"
PYSERIAL_PRECHECK_TXT_FPATH = ETC_TIBBO_PYTHON_DIR + "/" + PYSERIAL_PRECHECK_TXT_FILENAME

INSTALLED = "installed"
PYSERIAL_PATTERN = "pyserial"
TPD_PATTERN = "tpd"

TTYNUM_ONE = 1



#---TPD PRESENCE CHECK
lsmod_cmd=["lsmod"]
lsmod_output = subprocess.run(lsmod_cmd, capture_output=True, text=True)

print("\r\n")
if (TPD_PATTERN in lsmod_output.stdout):
   print("---:TIBBO:-:PRECHECK:\tmodule '" + TPD_PATTERN + "' is loaded...PASSED")
else:
   print("---:TIBBO:-:PRECHECK:\tmodule '" + TPD_PATTERN + "' is *NOT* loaded...FAILED")
   print("---:TIBBO:-:INFO:\tPlease load module '" + TPD_PATTERN + "' and Reboot the device")
   print("\r\n")
      
   sys.exit()



#---SET TTYS
#***NOTE:
#  On the LTPP3(G2), ttyS0 is the debug serial port, which cannot be used.
#  The first usable serial port is ttyS1.
ttySx = "/dev/ttyS" + str(TTYNUM_ONE)


#install prerequisites:
# pip3 install pyserial


#Set PINS
p=pmux()                                                             # Create pinmux driver inst>
p.set(pmux_type.SERIAL,TTYNUM_ONE,pmux_pin_func.UART_TX, PL_IO.NUM_9)    # Map the TX line of ttyS1 to pin 9 of the LTPP3(G2)
p.set(pmux_type.SERIAL,TTYNUM_ONE,pmux_pin_func.UART_RX, PL_IO.NUM_8)    # Map the RX line of ttyS1 to pin 8 of the LTPP3(G2)
p.set(pmux_type.SERIAL,TTYNUM_ONE,pmux_pin_func.UART_RTS, PL_IO.NUM_0)   # Map the RTS line of ttyS1 to pin 0 of the LTPP3(G2)
p.set(pmux_type.SERIAL,TTYNUM_ONE,pmux_pin_func.UART_CTS, PL_IO.NUM_16)   # Map the CTS line of ttyS1 to pin 16 of the LTPP3(G2)

#PRINT MESSAGES
SEND_MSG=b"Hello. This serial port will echo your input."
ser = serial.Serial(ttySx,115200)                                    # Open a serial port with a baudrate of 115,200
print("---:TIBBO:-:STATUS:\tusing port:" + ser.name)                 # Print the serial port being used
print(b"---:TIBBO:-:SENDING: " + SEND_MSG )

#TX
ser.write(SEND_MSG)                                                  # Send a greeting through the serial port

#RX
print("\r\n")
while True:
   while ser.in_waiting == 0 : pass
   s = ser.read(ser.in_waiting)                                      # Assign the contents of the RX buffer to the variable "s"
   print(b"---:TIBBO:-:RECEIVED: " + s)                              # Print the contents of the variable "s"
   ser.write(s)                                                      # Write the contents of the variable "s" to the serial port