RS232-MQTT-Bridge on ESP-01

All ESP8266 boards running MicroPython.
Official boards are the Adafruit Huzzah and Feather boards.
Target audience: MicroPython users with an ESP8266 board.
Post Reply
Posts: 1
Joined: Tue Dec 22, 2020 11:35 pm

RS232-MQTT-Bridge on ESP-01

Post by jugl » Wed Dec 23, 2020 12:04 am

I want to use an ESP8266 (if possible an ESP-01) as a bridge to connect an RS232 capable device to my network via MQTT. The goal is to send an RS232 ASCII-command to the ESP via MQTT, the ESP sends it via serial connection to the device and receives its answer from the serial port, finally this answer is returned to the network as an MQTT message. The device can also send an error message without prior command, thus I need to listen to the port all time.
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)
if not wlan.isconnected():
    print('connecting to network...')
    wlan.connect(wlan_ssid, wlan_pass)
    while not wlan.isconnected():
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)

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
    heartbeat = not Pin(2, Pin.IN).value()
    Pin(2, Pin.OUT).value( heartbeat )
    # here could follow other code 

User avatar
Posts: 2272
Joined: Sat May 09, 2015 4:13 pm
Location: Rhineland, Europe

Re: RS232-MQTT-Bridge on ESP-01

Post by Roberthh » Wed Dec 23, 2020 3:22 pm

You can use uos.dupterm() to deassgin UART0 form the REPL. See: ... ht=dupterm

Post Reply