title: MQTT and Nodemcu date: 2015-07-04 18:00 tags: nodemcu,mqtt,archlinux,graphite This blog should provide a technical walkthrough to get an mqtt environment running. It connects an [ESP8266 Microcontroller](http://s.click.aliexpress.com/e/qjiYvjiQb?af=130085010) uC to the MQTT server and transfers the messages into graphite messages ## Install Mosquitto on arch ```bash user: gpg --recv-keys 779B22DFB3E717B7 # use "keyserver http://http-keys.gnupg.net" if --recv-keys didn't work user: yaourt mosquitto root: echo user mosqitto >> /etc/mosquitto/mosquitto.conf root: systemctl start mosquitto ``` ## ESP8266 uC With nodemcu on the most current version (as of 2015-07-04) of nodemcu and upload: ```lua -- connect to wifi ident="123211" m = mqtt.Client(ident,120) mqtt_host="10.0.0.1" mqtt_port=1883 m:connect(mqtt_host,mqtt_port,0,function(conn) print("connected") end) function send_temperature() status,temp,humi,temp_decimial,humi_decimial = dht.read(4) m:publish(string.format("/temperature/%s",ident),string.format("%.2f",temp),0,0) m:publish(string.format("/humidity/%s",ident),string.format("%.2f",humi),0,0) end tmr.stop(1) tmr.alarm(1,1000,1,send_temperature) ``` ## Python mqtt Subscriber Subscribes temperature and humidity infos and sends it to graphite ```python #!/usr/bin/env python # pip install paho-mqtt import paho.mqtt.client as mqtt graphite_host='heidi.shack' def on_connect(client, userdata, flags, rc): print("Connected with result code " + str(rc)) client.subscribe("/temperature/#") client.subscribe("/humidity/#") import socket def to_graphite(path,data,ts=None,host='localhost',port=2003): if not ts: ts = datetime.now().timestamp() sock = socket.socket() data="{} {} {}\n".format(path,data,ts) try: sock.connect((host, port)) sock.sendall(data.encode()) sock.close() print("sent '{}'".format(data.strip())) except Exception as e: print(e) print("cannot send message '{}'".format(data)) def on_message(client, userdata, msg): t = msg.topic print(msg.topic + " " + str(msg.payload)) if t.startswith('/temperature') or t.startswith('/humidity'): typ=t.split('/')[1] ident=t.split('/')[-1] to_graphite("sensors.temp.id.{}.{}".format(ident,typ),float(msg.payload),int(msg.timestamp),host=graphite_host) client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect("heidi.shack", 1883, 60) client.loop_forever() ```