summaryrefslogtreecommitdiffstats
path: root/content/posts/mosquitto-and-nodemcu.md
blob: 0e3ee16658284cb564f2fbd4e57b8aacedb08b05 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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()
```