-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathmain.py
More file actions
65 lines (51 loc) · 2.68 KB
/
Copy pathmain.py
File metadata and controls
65 lines (51 loc) · 2.68 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import argparse, time, sys
from logger import EnvLogger
def parse_args():
ap = argparse.ArgumentParser(add_help=False)
ap.add_argument("-h", "--host", required=True, help="the MQTT host to connect to")
ap.add_argument("-p", "--port", type=int, default=1883, help="the port on the MQTT host to connect to")
ap.add_argument("-U", "--username", default=None, help="the MQTT username to connect with")
ap.add_argument("-P", "--password", default=None, help="the password to connect with")
ap.add_argument("--prefix", default="", help="the topic prefix to use when publishing readings, i.e. 'lounge/enviroplus'")
ap.add_argument("--client-id", default="", help="the MQTT client identifier to use when connecting")
ap.add_argument("--interval", type=int, default=5, help="the duration in seconds between updates")
ap.add_argument("--delay", type=int, default=15, help="the duration in seconds to allow the sensors to stabilise before starting to publish readings")
ap.add_argument("--use-pms5003", action="store_true", help="if set, PM readings will be taken from the PMS5003 sensor")
ap.add_argument("-r", "--retain", action='store_true', help="tell MQTT broker to retain the last message")
ap.add_argument("--help", action="help", help="print this help message and exit")
return vars(ap.parse_args())
def main():
args = parse_args()
# Initialise the logger
logger = EnvLogger(
client_id=args["client_id"],
host=args["host"],
port=args["port"],
username=args["username"],
password=args["password"],
prefix=args["prefix"],
use_pms5003=args["use_pms5003"],
num_samples=args["interval"],
retain=args["retain"],
)
# Take readings without publishing them for the specified delay period,
# to allow the sensors time to warm up and stabilise
publish_start_time = time.time() + args["delay"]
while time.time() < publish_start_time:
logger.update(publish_readings=False)
time.sleep(1)
# Start taking readings and publishing them at the specified interval
next_sample_time = time.time()
next_publish_time = time.time() + args["interval"]
while True:
if logger.connection_error is not None:
sys.exit(f"Connecting to the MQTT server failed: {logger.connection_error}")
should_publish = time.time() >= next_publish_time
if should_publish:
next_publish_time += args["interval"]
logger.update(publish_readings=should_publish)
next_sample_time += 1
sleep_duration = max(next_sample_time - time.time(), 0)
time.sleep(sleep_duration)
if __name__ == "__main__":
main()