Lightweight MQTT Publish works on esp8266

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: 92
Joined: Mon Feb 09, 2015 1:09 am

Lightweight MQTT Publish works on esp8266

Post by slzatz » Mon Mar 28, 2016 1:03 pm

Andrew published a simple script in the WiPy section ... mqtt#p6545 to do MQTT publish and just wanted to note that it works on the esp8266 with just updating to the current version of micropython code available in the git repository.

Code: Select all

# Borrowed from Andrew

import network
import lwip
from time import sleep

def mtStr(s):
  return bytes([len(s) >> 8, len(s) & 255]) + s.encode('utf-8')

def mtPacket(cmd, variable, payload):
  return bytes([cmd, len(variable) + len(payload)]) + variable + payload

def mtpConnect(name):
  return mtPacket(
       mtStr("MQTT") + # protocol name
       b'\x04' +       # protocol level
       b'\x00' +       # connect flag
       b'\xFF\xFF',    # keepalive

def mtpDisconnect():
  return bytes([0b11100000, 0b00000000])

def mtpPub(topic, data):
  return  mtPacket(0b00110001, mtStr(topic), data)

wlan = network.WLAN(network.STA_IF)    
wlan.connect('essid', 'password') 
print('Connected =',wlan.isconnected())      

s = lwip.socket()
s.connect('xx.xx...', 1883)
s.send(mtpPub("topic...", b'message'))

Posts: 1136
Joined: Fri Feb 28, 2014 2:05 pm

Re: Lightweight MQTT Publish works on esp8266

Post by pfalcon » Tue Mar 29, 2016 6:48 am

Thanks for sharing. That's the whole idea of MicroPython - power of Python language and our (MicroPython's) adherence to standard APIs makes developing and porting many things very easy. As a small comment, you don't need to do "import lwip", just use standard "socket" module. You can also test and debug your code on desktop version of MicroPython (and usually, Python3) - that's another benefit of MicroPython.
Awesome MicroPython list
Pycopy - A better MicroPython
MicroPython standard library for all ports and forks -
More up to date docs -

Post Reply