Debian Codegraph @

aranet4/aranetctl.py

raw
1 import argparse
2 import csv
3 from dataclasses import asdict
4 import datetime
5 from pathlib import Path
6 import sys
7 from time import sleep
8
9 import requests
10
11 from aranet4 import client
12
13 def parse_args(ctl_args):
14 parser = argparse.ArgumentParser()
15 parser.add_argument("device_mac", nargs="?", help="Aranet Bluetooth Address")
16 parser.add_argument(
17 "--scan", action="store_true", help="Scan for Aranet devices"
18 )
19 current = parser.add_argument_group("Options for current reading")
20 current.add_argument(
21 "-u", "--url", metavar="URL", help="Remote url for current value push"
22 )
23 parser.add_argument(
24 "-r", "--records", action="store_true", help="Fetch historical log records"
25 )
26 history = parser.add_argument_group("Filter History Log Records")
27 history.add_argument(
28 "-s",
29 "--start",
30 metavar="DATE",
31 type=datetime.datetime.fromisoformat,
32 help="Records range start (UTC time, example: 2019-09-29T14:00:00",
33 )
34 history.add_argument(
35 "-e",
36 "--end",
37 metavar="DATE",
38 type=datetime.datetime.fromisoformat,
39 help="Records range end (UTC time, example: 2019-09-30T14:00:00",
40 )
41 history.add_argument(
42 "-o", "--output", metavar="FILE", type=Path, help="Save records to a file"
43 )
44 history.add_argument(
45 "-w",
46 "--wait",
47 action="store_true",
48 default=False,
49 help="Wait until new data point available",
50 )
51 history.add_argument(
52 "-l", "--last", metavar="COUNT", type=int, help="Get <COUNT> last records"
53 )
54 history.add_argument(
55 "--xt",
56 dest="temp",
57 default=True,
58 action="store_false",
59 help="Don't get temperature records",
60 )
61 history.add_argument(
62 "--xh",
63 dest="humi",
64 default=True,
65 action="store_false",
66 help="Don't get humidity records",
67 )
68 history.add_argument(
69 "--xp",
70 dest="pres",
71 default=True,
72 action="store_false",
73 help="Don't get pressure records",
74 )
75 history.add_argument(
76 "--xc",
77 dest="co2",
78 default=True,
79 action="store_false",
80 help="Don't get co2 records",
81 )
82 settings = parser.add_argument_group("Change device settings")
83 settings.add_argument(
84 "--set-interval",
85 dest="set_interval",
86 metavar="MINUTES",
87 type=int,
88 help="Change update interval"
89 )
90 settings.add_argument(
91 "--set-integrations",
92 dest="set_integrations",
93 type=str,
94 choices=["on", "off"],
95 help="Toggle Smart Home Integrations"
96 )
97 settings.add_argument(
98 "--set-range",
99 dest="set_btrange",
100 type=str,
101 choices=["normal", "extended"],
102 help="Change bluetooth range"
103 )
104
105 return parser.parse_args(ctl_args)
106
107
108 def print_records(records):
109 """Format log records to be printed to screen"""
110 char_repeat = 34
111 if records.filter.incl_co2:
112 char_repeat += 9
113 if records.filter.incl_temperature:
114 char_repeat += 7
115 if records.filter.incl_humidity:
116 char_repeat += 8
117 if records.filter.incl_pressure:
118 char_repeat += 11
119 if records.filter.incl_rad_dose_rate:
120 char_repeat += 11
121 if records.filter.incl_rad_dose:
122 char_repeat += 11
123 if records.filter.incl_rad_dose_total:
124 char_repeat += 12
125 if records.filter.incl_radon_concentration:
126 char_repeat += 8
127 print("-" * char_repeat)
128 print(f"{'Device Name':<15}: {records.name:>20}")
129 print(f"{'Device Version':<15}: {records.version:>20}")
130 print("-" * char_repeat)
131 print(f"{'id': ^4} | {'date': ^25} |", end="")
132 if records.filter.incl_co2:
133 print(f" {'co2':^6} |", end="")
134 if records.filter.incl_temperature:
135 print(" temp |", end="")
136 if records.filter.incl_humidity:
137 print(" humid |", end="")
138 if records.filter.incl_pressure:
139 print(" pressure |", end="")
140 if records.filter.incl_rad_dose:
141 print(" rad_dose |", end="")
142 if records.filter.incl_rad_dose_rate:
143 print(" rad_rate |", end="")
144 if records.filter.incl_rad_dose_total:
145 print(" rad_total |", end="")
146 if records.filter.incl_radon_concentration:
147 print(f" {'radon':^5} |", end="")
148 print("")
149 print("-" * char_repeat)
150
151 for record_id, line in enumerate(records.value, start=records.filter.begin):
152 print(f"{record_id:>4d} | {line.date.isoformat()} |", end="")
153 if records.filter.incl_co2:
154 print(f" {line.co2:>6d} |", end="")
155 if records.filter.incl_temperature:
156 print(f" {line.temperature:>4.1f} |", end="")
157 if records.filter.incl_humidity:
158 print(f" {line.humidity:>5.1f} |", end="")
159 if records.filter.incl_pressure:
160 print(f" {line.pressure:>8.1f} |", end="")
161 if records.filter.incl_rad_dose:
162 print(f" {line.rad_dose/1000:>8.3f} |", end="")
163 if records.filter.incl_rad_dose_rate:
164 print(f" {line.rad_dose_rate/1000:>8.3f} |", end="")
165 if records.filter.incl_rad_dose_total:
166 print(f" {line.rad_dose_total/1000000:>9.4f} |", end="")
167 if records.filter.incl_radon_concentration:
168 print(f" {line.radon_concentration:>5d} |", end="")
169 print("")
170 print("-" * char_repeat)
171
172
173 def store_scan_result(advertisement):
174 global found
175 if not advertisement.device:
176 return
177
178 found[advertisement.device.address] = advertisement
179
180 def write_csv(filename, log_data):
181 """
182 Output `client.Record` dataclass to csv file
183 :param filename: file name
184 :param log_data: `client.Record` data object
185 """
186 with open(file=filename, mode="w", encoding="utf-8", newline="") as csv_file:
187 fieldnames = ["date"]
188 if log_data.filter.incl_co2:
189 fieldnames.append("co2")
190 if log_data.filter.incl_temperature:
191 fieldnames.append("temperature")
192 if log_data.filter.incl_humidity:
193 fieldnames.append("humidity")
194 if log_data.filter.incl_pressure:
195 fieldnames.append("pressure")
196 if log_data.filter.incl_rad_dose:
197 fieldnames.append("rad_dose")
198 if log_data.filter.incl_rad_dose_rate:
199 fieldnames.append("rad_dose_rate")
200 if log_data.filter.incl_rad_dose_total:
201 fieldnames.append("rad_dose_total")
202 if log_data.filter.incl_radon_concentration:
203 fieldnames.append("radon_concentration")
204 writer = csv.DictWriter(csv_file, fieldnames=fieldnames, extrasaction="ignore")
205
206 writer.writeheader()
207
208 for line in log_data.value:
209 writer.writerow(asdict(line))
210
211
212 def post_data(url, current):
213 # get current measurement minute
214 now = datetime.datetime.now(datetime.timezone.utc).replace(microsecond=0)
215 delta_ago = datetime.timedelta(seconds=current.ago)
216 t = now - delta_ago
217 t = t.replace(second=0) # epoch, floored to minutes
218 data = current.toDict()
219 data["time"] = t.timestamp()
220 r = requests.post(
221 url=url,
222 data=data,
223 timeout=300
224 )
225 print(f"Pushing data: {r.text}")
226
227
228 def wait_for_new_record(address):
229 current_vals = client.get_current_readings(address)
230 wait_time = current_vals.interval - current_vals.ago
231 for secs in range(wait_time, 0, -1):
232 sleep(1)
233 print(f"Next data point in {secs}...", end="\r")
234
235
236 def main(argv):
237 global found
238 found = {}
239 args = parse_args(argv)
240
241 if args.scan:
242 print("Looking for Aranet devices...")
243 devices = client.find_nearby(store_scan_result)
244 print(f"Scan finished. Found {len(devices)}")
245 print()
246 for _, advertisement in found.items():
247 if advertisement.readings:
248 print(advertisement.readings.toString(advertisement))
249 else:
250 print("=======================================")
251 print(f" Name: {advertisement.device.name}")
252 print(f" Address: {advertisement.device.address}")
253 print(f" RSSI: {advertisement.rssi} dBm")
254 print()
255 print()
256
257 return
258
259 if not args.device_mac:
260 print("Device address not specified")
261 return
262
263 if args.records:
264 if args.wait:
265 wait_for_new_record(args.device_mac)
266 records = client.get_all_records(args.device_mac, vars(args), True)
267 print_records(records)
268 if args.output:
269 write_csv(args.output, records)
270 else:
271 settings = {}
272
273 if args.set_interval:
274 settings["interval"] = args.set_interval
275
276 if args.set_integrations:
277 settings["integrations"] = args.set_integrations
278
279 if args.set_btrange:
280 settings["range"] = args.set_btrange
281
282 if settings:
283 result = client.set_settings(args.device_mac, settings, True)
284 for k in result:
285 val = settings[k]
286 ret = "SUCCESS" if result[k] else "FAILED"
287 print(f"Set {k} to \"{val}\": {ret}")
288 else:
289 current = client.get_current_readings(args.device_mac)
290 print(current.toString())
291 if args.url:
292 post_data(args.url, current)
293
294
295 def entry_point():
296 main(argv=sys.argv[1:])
297
298
299 if __name__ == "__main__":
300 entry_point()