How do I implement serial communication? Can UART be used in a way that does not collide with REPL/webREPL?
How do I set up a listener for incoming messages from the serial port?
The ASCII-commands end all with <CR>. That means it has to read from serial until <CR> (=x0D) is received and than send this text line to MQTT.
Here is my current code. So far. Any hints are welcome:
Code: Select all
import network import time from umqtt.simple import MQTTClient from machine import Pin from machine import UART # WLAN setup wlan_ssid = 'mySSID' wlan_pass = 'myPassword' wlan = network.WLAN(network.STA_IF) wlan.active(True) if not wlan.isconnected(): print('connecting to network...') wlan.connect(wlan_ssid, wlan_pass) while not wlan.isconnected(): pass print('Network: ', wlan.ifconfig()) # Serial setup uart = UART(0, 9600) uart.init(9600, bits=8, parity=None, stop=1) # MQTT setup mqttserver = '192.168.1.XX' mqttport = 1883 mqttuser = b'mqtt' mqttpswd = b'myMQTTpassword' mqtt_pubtopic = 'device/pup' mqtt_subtopic = b'device/sub' mqttclient = MQTTClient("umqtt_client", mqttserver, mqttport, mqttuser ,mqttpswd) # funtion for sending to mqtt def mqtt_pub(topic, payload): mqttclient.publish(topic, payload) def mqtt_callback(topic, msg): mqtt_pub(mqtt_pubtopic+'/testecho', msg) # here comes the code to send to serial port ## #this does not work: ## print('got MQTT message:', topic, msg) ## uart.write(msg) ## msg = uart.readline() ## mqtt_pub(mqtt_pubtopic+'/ans', msg) mqttclient.connect() mqttclient.set_callback(mqtt_callback) mqttclient.subscribe(mqtt_subtopic) message = 'booting '+name mqtt_pub(mqtt_pubtopic, message) print("MQTT: Connected to %s, subscribed to %s topic" % (mqttserver, mqtt_subtopic)) while True: # Non-blocking wait for message mqttclient.check_msg() heartbeat = not Pin(2, Pin.IN).value() time.sleep_ms(50) Pin(2, Pin.OUT).value( heartbeat ) time.sleep_ms(450) # here could follow other code