Controlling CE-COM2 with Python Code
The below code is used to control a CE-COM2 device. The code watches for the device to come online, configures the port, sends and receives strings, and reports faults detected on ports.
from mojo import context
context.log.info('Sample Python program')
#Create objects for the controller (idevice) and touch panel (AMX-11241)
CE_COM2 = context.devices.get("tsCE_COM2")
dvTP = context.devices.get("AMX-11241")
#Create a variable to access just the serial port
serialPort1 = CE_COM2.serial[0]
#This creates a buffer for incoming serial strings, if a string is longer than 64 characters
#it will trigger multiple events, this allows building the string until a delimiter is reached
serialBuffer = ""
#As long as the idevice is online it will set the baud rate of the serial port
if(CE_COM2.isOnline()):
context.log.info("tsCE_COM2 online, setting baud rate.")
serialPort1.setCommParams("9600",8,1,"NONE","232")
#If the CE-COM2 comes online after the script is running, this function will set the baud rate of the
#serial port
def ceOnline(event):
context.log.info("tsCE_COM2 online, setting baud rate.")
serialPort1.setCommParams("9600",8,1,"NONE","232")
CE_COM2.online(ceOnline)
#This function processes incoming strings utilizing the serialBuffer variable declared above
#Once a carriage return is seen in the string it prints what has been received
def receiveString(event):
global serialBuffer
serialBuffer += event.arguments['data'].decode()
if (serialBuffer.find("\r") >= 0):
print(f"Full string: {serialBuffer}")
serialBuffer = ""
serialPort1.receive.listen(receiveString)
#An example of sending an ASCII string from the serial port
def sendASCII(event):
serialPort1.send("ASCII string\r".encode())
dvTP.port[1].button[1].watch(sendASCII)
#An example of sending a hexadecimal string from the serial port
def sendHEX(event):
serialPort1.send("\x02 \x68 \x65 \x6c \x6c \x6f \x03 \x0d".encode())
dvTP.port[1].button[2].watch(sendHEX)
#An example of sending a mixed hex/ASCII string from the serial port
def sendMIX(event):
serialPort1.send("\x02 Mixed string \x03 \r".encode())
dvTP.port[1].button[3].watch(sendMIX)
#This function is triggered by a fault detection in the serial port, it will print out the error
def receiveFault(event):
context.log.info(f"Serial port fault: {event.arguments['value']}")
serialPort1.fault.listen(receiveFault)
#Leave this as the last line in the Python script
#This keeps the script running with a no-op loop,
#maintaining the Mojo environment and access to the globals() dictionary
#For additional information search for the following article:
# Using context.run in MUSE Python Code
context.run(globals())