summaryrefslogtreecommitdiff
path: root/prilohy/web/mqttagregator.py
blob: 71c9ca57b8cd0b4219d95974c52f73e8520ab297 (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
import json
import time
import numpy as np
import paho.mqtt.client as mqtt
import pandas as pd
import plotly.express as px


cols = ['temp', 'pres', 'humi', 'gas', 'rsrp', 'rsrq', 'snr', 'enerest', 'band', 'txp', 'dlpl', 'ltemode']

#dg = pd.DataFrame(columns=['lati', 'long', 'alti', 'rssi', 'snr', 'rttt', 'temp', 'humi', 'pres', 'voc'], dtype=float)
dg = pd.DataFrame(columns=cols, dtype=float)

def on_connect(client, userdata, flags, reason_code):
    client.subscribe("nrf/dk/#")


inx = 0
def on_message(client, userdata, msg):
    global inx
    col = msg.topic[msg.topic.rfind('/')+1:]
    if col == 'temp':
        inx += 1
    val = msg.payload.decode('utf-8')
    val = float(val)
    dg.at[inx, col] = val

mqttc = mqtt.Client()
mqttc.on_connect = on_connect
mqttc.on_message = on_message

mqttc.connect("mikehanus.xyz", 1883, 60)

mqttc.loop_start()


while True:
    time.sleep(1)
    if len(dg.index) > 1:
        with open('save.csv', 'a') as f:
            for inx in dg.index[:-1]:
                s = dg.loc[inx]
                d = s.to_dict()
                d['time'] = int(time.time())
                sj = json.dumps(d)
                print(sj)
                f.write(sj + '\n')
                dg.drop(index=inx, inplace=True)

mqttc.loop_stop()