/
mqtt_receiver.py
50 lines (43 loc) · 1.4 KB
/
mqtt_receiver.py
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
"""
https://github.com/binarybucks/mqttitude
phone app sends to mosquitto broker
we subscribe on that broker and send http to update.py
"""
import json, restkit, logging
import paho.mqtt.client
logging.basicConfig(level=logging.INFO, format="%(asctime)-15s %(message)s")
log = logging.getLogger()
config = json.load(open('priv.json'))
updateServer = restkit.Resource("http://bang:9033/update")
client = paho.mqtt.client.Client("map-receiver")
client.connect("localhost")
log.info('connected to %s', client._host)
# need more auth here, to be able to read
client.subscribe("/mqttitude/#", 0)
def on_message(mosq, obj, msg):
payload = json.loads(msg.payload)
log.info("got message %r %r", msg.topic, payload)
try:
userFromTopic = config['mqttTopic'][msg.topic]
except KeyError:
log.warn("ignoring unknown topic")
return
if 'lon' not in payload:
log.info("ignoring")
return
record = {
"timestamp" : int(payload['tst']),
"user" : userFromTopic,
"longitude" : float(payload['lon']),
"latitude" : float(payload['lat']),
"source" : "mqttitude",
}
for attr in ['alt', 'batt', 'acc']:
if attr in payload:
record[attr] = payload[attr]
log.info(repr(record))
updateServer.post(payload=json.dumps(record))
log.info("posted message")
client.on_message = on_message
while True:
client.loop()