-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
47 lines (39 loc) · 2.08 KB
/
main.py
File metadata and controls
47 lines (39 loc) · 2.08 KB
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
from __init__ import *
import datetime
import json
import colorama
# on message function to execute when a message
# comes in on the broker
def on_message(client, userdata, msg):
data = json.loads((msg.payload).decode('utf-8'))
# create a data point for the influx database from the received mqtt data
try:
if ((x for x in ["MAC", "IP"]) not in data.keys()) and data["Room"].lower() != "unknown":
point = Point(data["Room"])
for key in data.keys():
if (key.lower() != "room") and (key.lower() != "timestamp"):
point = point.field(str(key).lower(), float(data[key]))
point.time(data["Timestamp"], WritePrecision.NS)
else:
print(f"[{datetime.datetime.now()}UTC]: {colorama.Fore.YELLOW}[ALERT]{colorama.Fore.RESET} got wrong format {data}")
except:
print(f"[{datetime.datetime.now()}UTC]: {colorama.Fore.YELLOW}[ALERT]{colorama.Fore.RESET} got wrong format {data}")
# write the data to the database
try:
write_api.write(bucket, organization, point)
if debug:
print(f"[{datetime.datetime.now()}UTC]: {colorama.Fore.BLUE}[STATUS]{colorama.Fore.RESET} written data > {str(data)}")
except Exception as e:
if debug:
print(f"[{datetime.datetime.now()}UTC]: {colorama.Fore.YELLOW}[ALERT]{colorama.Fore.RESET} can't write to influxdb, reason:", (json.loads(e.body))["message"])
if __name__ == "__main__":
try:
print(f"\nDEBUG MODE [{colorama.Fore.GREEN}{'ON' if debug == 1 else 'OFF'}{colorama.Fore.RESET}]")
client.on_message = on_message
client.connect(host_address, topic, debug_mode=debug, keep_alive=5, disconnect_endpoint=disconnect_endpoint)
except KeyboardInterrupt:
# if manually stopped through a keyboardinterupt, give message
print(f"\n[{datetime.datetime.now()}UTC]: {colorama.Fore.YELLOW}[ALERT]{colorama.Fore.RESET} Manually stopped")
except Exception as e:
# else show error
print(f"[{datetime.datetime.now()}UTC]: {colorama.Fore.RED}[Error]{colorama.Fore.RESET} {e}")