aboutsummaryrefslogtreecommitdiffstats
path: root/scripts/mqtt_listener.py
blob: 6c617a5f35549214b284f31ffd612c3aadcd401b (plain) (blame)
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#!/usr/bin/env python3
''' Listen for mqtt-events, and trigger for some '''

import os
import json
from datetime import datetime
import paho.mqtt.client as mqtt

import common

mqtt_server = os.environ['el_mqtt_server']
mqtt_port = int(os.environ['el_mqtt_port'])
keepalive = int(os.environ['el_mqtt_keepalive'])
mqtt_topic = os.environ['el_mqtt_topic']
mqtt_user = os.environ['el_mqtt_user']
mqtt_pass = os.environ['el_mqtt_pass']

tempsensors = [ 'Bad Temp',
                'Barnerom Temp',
                'Isobod Temp',
                'Kjøkken Temp Matskap',
                'Kontor Temp',
                'Loft Temp',
                'Soverom Temp',
                'Stue Temp Display',
                'Stue Temp Stuebord',
                'Stue Temp Teleskap',
                'Toalett motion',
                'Utebod Temp',
                'Vaskerom Temp']

# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))

    # Subscribing in on_connect() means that if we lose the connection and
    # reconnect then subscriptions will be renewed.
    client.subscribe(mqtt_topic)

# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
    name = msg.topic.split('/')[1]
    data = json.loads(msg.payload)

    if name == 'HAN' and 'current' in data:
        sql = """INSERT INTO mqtt_han
                    (name,
                     current,
                     power,
                     voltage,
                     linkquality,
                     time)
                 VALUES(%s,%s,%s,%s,%s,%s)"""
        values = (name,
                  data['current'],
                  data['power'],
                  data['voltage'],
                  data['linkquality'],
                  datetime.utcnow())

    elif name in tempsensors and 'temperature' in data:
        data['humidity'] = data['humidity'] if 'humidity' in data else None
        data['voltage'] = data['voltage'] if 'voltage' in data else None
        sql = """INSERT INTO mqtt_temps
                        (sensor_id,
                         temperature,
                         humidity,
                         battery,
                         linkquality,
                         voltage,
                         time)
                 SELECT sensors.id, %s, %s, %s, %s, %s, %s
                    FROM sensors
                    WHERE sensors.name = %s"""
        values = (data['temperature'],
                  data['humidity'],
                  data['battery'],
                  data['linkquality'],
                  data['voltage'],
                  datetime.utcnow(),
                  name)

    else:
        return

    common.dbi(sql, values, verbose=True)


# mqtt
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

client.username_pw_set(mqtt_user, password=mqtt_pass)

client.connect(mqtt_server, mqtt_port, keepalive)

# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
client.loop_forever()