]> www.average.org Git - loctrkd.git/blob - loctrkd/beesure.py
Cleanup some of the types
[loctrkd.git] / loctrkd / beesure.py
1 """
2 Implementation of the protocol "beesure" used by some watch-trackers
3 https://www.4p-touch.com/beesure-gps-setracker-server-protocol.html
4 """
5
6 from datetime import datetime, timezone
7 from enum import Enum
8 from inspect import isclass
9 import re
10 from struct import error, pack, unpack
11 from time import time
12 from typing import (
13     Any,
14     Callable,
15     Dict,
16     List,
17     Optional,
18     Tuple,
19     Type,
20     TYPE_CHECKING,
21     Union,
22 )
23 from types import SimpleNamespace
24
25 from .protomodule import ProtoClass
26 from .common import (
27     CoordReport,
28     HintReport,
29     StatusReport,
30     Report,
31 )
32
33 __all__ = (
34     "Stream",
35     "class_by_prefix",
36     "enframe",
37     "exposed_protos",
38     "inline_response",
39     "proto_handled",
40     "parse_message",
41     "probe_buffer",
42     "DecodeError",
43     "Respond",
44 )
45
46 PROTO_PREFIX = "BS:"
47
48 ### Deframer ###
49
50 MAXBUFFER: int = 65557  # Theoretical max buffer 65536 + 21
51 RE = re.compile(b"\[(\w\w)\*(\d{10})\*([0-9a-fA-F]{4})\*")
52
53
54 def _framestart(buffer: bytes) -> Tuple[int, str, str, int]:
55     """
56     Find the start of the frame in the buffer.
57     If found, return (offset, vendorId, imei, datalen) tuple.
58     If not found, set -1 as the value of `offset`
59     """
60     mo = RE.search(buffer)
61     return (
62         (
63             mo.start(),
64             mo.group(1).decode(),
65             mo.group(2).decode(),
66             int(mo.group(3), 16),
67         )
68         if mo
69         else (-1, "", "", 0)
70     )
71
72
73 class Stream:
74     def __init__(self) -> None:
75         self.buffer = b""
76         self.imei: Optional[str] = None
77         self.datalen: int = 0
78
79     def recv(self, segment: bytes) -> List[Union[bytes, str]]:
80         """
81         Process next segment of the stream. Return successfully deframed
82         packets as `bytes` and error messages as `str`.
83         """
84         when = time()
85         self.buffer += segment
86         if len(self.buffer) > MAXBUFFER:
87             # We are receiving junk. Let's drop it or we run out of memory.
88             self.buffer = b""
89             return [f"More than {MAXBUFFER} unparseable data, dropping"]
90         msgs: List[Union[bytes, str]] = []
91         while True:
92             if not self.datalen:  # we have not seen packet start yet
93                 toskip, _, imei, datalen = _framestart(self.buffer)
94                 if toskip < 0:  # No frames, continue reading
95                     break
96                 if toskip > 0:  # Should not happen, report
97                     msgs.append(
98                         f"Skipping {toskip} bytes of undecodable data"
99                         f' "{self.buffer[:toskip][:64]=!r}"'
100                     )
101                     self.buffer = self.buffer[toskip:]
102                     # From this point, buffer starts with a packet header
103                 if self.imei is None:
104                     self.imei = imei
105                 if self.imei != imei:
106                     msgs.append(
107                         f"Packet's imei {imei} mismatches"
108                         f" previous value {self.imei}, old value kept"
109                     )
110                 self.datalen = datalen
111             if len(self.buffer) < self.datalen + 21:  # Incomplete packet
112                 break
113             # At least one complete packet is present in the buffer
114             if chr(self.buffer[self.datalen + 20]) == "]":
115                 msgs.append(self.buffer[: self.datalen + 21])
116             else:
117                 msgs.append(
118                     f"Packet does not end with ']'"
119                     f" at {self.datalen+20}: {self.buffer=!r}"
120                 )
121             self.buffer = self.buffer[self.datalen + 21 :]
122             self.datalen = 0
123         return msgs
124
125     def close(self) -> bytes:
126         ret = self.buffer
127         self.buffer = b""
128         self.imei = None
129         self.datalen = 0
130         return ret
131
132
133 def enframe(buffer: bytes, imei: Optional[str] = None) -> bytes:
134     assert imei is not None and len(imei) == 10
135     off, vid, _, dlen = _framestart(buffer)
136     assert off == 0
137     return f"[{vid:2s}*{imei:10s}*{dlen:04X}*".encode() + buffer[20:]
138
139
140 ### Parser/Constructor ###
141
142
143 class classproperty:
144     def __init__(self, f: Callable[[Any], str]) -> None:
145         self.f = f
146
147     def __get__(self, obj: Any, owner: Any) -> str:
148         return self.f(owner)
149
150
151 class DecodeError(Exception):
152     def __init__(self, e: Exception, **kwargs: Any) -> None:
153         super().__init__(e)
154         for k, v in kwargs.items():
155             setattr(self, k, v)
156
157
158 def maybe(typ: type) -> Callable[[Any], Any]:
159     return lambda x: None if x is None else typ(x)
160
161
162 def intx(x: Union[str, int]) -> int:
163     if isinstance(x, str):
164         x = int(x, 0)
165     return x
166
167
168 def boolx(x: Union[str, bool]) -> bool:
169     if isinstance(x, str):
170         if x.upper() in ("ON", "TRUE", "1"):
171             return True
172         if x.upper() in ("OFF", "FALSE", "0"):
173             return False
174         raise ValueError(str(x) + " could not be parsed as a Boolean")
175     return x
176
177
178 def l3str(x: Union[str, List[str]]) -> List[str]:
179     if isinstance(x, str):
180         lx = x.split(",")
181     else:
182         lx = x
183     if len(lx) != 3 or not all(isinstance(el, str) for el in x):
184         raise ValueError(str(lx) + " is not a list of three strings")
185     return lx
186
187
188 def pblist(x: Union[str, List[Tuple[str, str]]]) -> List[Tuple[str, str]]:
189     if isinstance(x, str):
190
191         def splitpair(s: str) -> Tuple[str, str]:
192             a, b = s.split(":")
193             return a, b
194
195         lx = [splitpair(el) for el in x.split(",")]
196     else:
197         lx = x
198     if len(lx) > 5:
199         raise ValueError(str(lx) + " has too many elements (max 5)")
200     return lx
201
202
203 class Respond(Enum):
204     NON = 0  # Incoming, no response needed
205     INL = 1  # Birirectional, use `inline_response()`
206     EXT = 2  # Birirectional, use external responder
207
208
209 class BeeSurePkt(ProtoClass):
210     RESPOND = Respond.NON  # Do not send anything back by default
211     IN_KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = ()
212     OUT_KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = ()
213     KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = ()
214     In: Type["BeeSurePkt"]
215     Out: Type["BeeSurePkt"]
216
217     if TYPE_CHECKING:
218
219         def __getattr__(self, name: str) -> Any:
220             pass
221
222         def __setattr__(self, name: str, value: Any) -> None:
223             pass
224
225     def __init__(self, *args: Any, **kwargs: Any):
226         """
227         Construct the object _either_ from (length, payload),
228         _or_ from the values of individual fields
229         """
230         self.payload: Union[List[str], bytes]
231         assert not args or (len(args) == 4 and not kwargs)
232         if args:  # guaranteed to be two arguments at this point
233             self.vendor, self.imei, self.datalength, self.payload = args
234             try:
235                 if isinstance(self.payload, list):
236                     self.decode(*self.payload)
237                 else:
238                     self.decode(self.payload)
239             except error as e:
240                 raise DecodeError(e, obj=self)
241         else:
242             for kw, typ, dfl in self.KWARGS:
243                 setattr(self, kw, typ(kwargs.pop(kw, dfl)))
244             if kwargs:
245                 raise ValueError(
246                     self.__class__.__name__ + " stray kwargs " + str(kwargs)
247                 )
248
249     def __repr__(self) -> str:
250         return "{}({})".format(
251             self.__class__.__name__,
252             ", ".join(
253                 "{}={}".format(
254                     k,
255                     'bytes.fromhex("{}")'.format(v.hex())
256                     if isinstance(v, bytes)
257                     else v.__repr__(),
258                 )
259                 for k, v in self.__dict__.items()
260                 if not k.startswith("_")
261             ),
262         )
263
264     def decode(self, *args: Any) -> None:
265         ...
266
267     def in_decode(self, *args: str) -> None:
268         # Overridden in subclasses, otherwise do not decode payload
269         return
270
271     def out_decode(self, *args: str) -> None:
272         # Overridden in subclasses, otherwise do not decode payload
273         return
274
275     def encode(self) -> str:
276         ...
277
278     def in_encode(self) -> str:
279         # Necessary to emulate terminal, which is not implemented
280         raise NotImplementedError(
281             self.__class__.__name__ + ".encode() not implemented"
282         )
283
284     def out_encode(self) -> str:
285         # Overridden in subclasses, otherwise command verb only
286         return ""
287
288     @classproperty
289     def PROTO(cls: "BeeSurePkt") -> str:
290         """Name of the class without possible .In / .Out suffix"""
291         proto: str
292         try:
293             proto, _ = cls.__name__.split(".")
294         except ValueError:
295             proto = cls.__name__
296         return proto
297
298     @classmethod
299     def proto_name(cls) -> str:
300         """Name of the command as used externally"""
301         return PROTO_PREFIX + cls.PROTO[:16]
302
303     @property
304     def packed(self) -> bytes:
305         data = self.encode()
306         payload = self.PROTO + "," + data if data else self.PROTO
307         return f"[LT*0000000000*{len(payload):04X}*{payload}]".encode()
308
309
310 class UNKNOWN(BeeSurePkt):
311     pass
312
313
314 class _LOC_DATA(BeeSurePkt):
315     def in_decode(self, *args: str) -> None:
316         p = SimpleNamespace()
317         _id = lambda x: x
318         for (obj, attr, func), val in zip(
319             (
320                 (p, "date", _id),
321                 (p, "time", _id),
322                 (self, "gps_valid", lambda x: x == "A"),
323                 (p, "lat", float),
324                 (p, "nors", lambda x: 1 if x == "N" else -1),
325                 (p, "lon", float),
326                 (p, "eorw", lambda x: 1 if x == "E" else -1),
327                 (self, "speed", float),
328                 (self, "direction", float),
329                 (self, "altitude", float),
330                 (self, "num_of_sats", int),
331                 (self, "gsm_strength_percentage", int),
332                 (self, "battery_percentage", int),
333                 (self, "pedometer", int),
334                 (self, "tubmling_times", int),
335                 (self, "device_status", lambda x: int(x, 16)),
336                 (self, "gsm_cells_number", int),
337                 (self, "connect_base_station_number", int),
338                 (self, "mcc", int),
339                 (self, "mnc", int),
340             ),
341             args[:20],
342         ):
343             setattr(obj, attr, func(val))  # type: ignore
344         rest_args = args[20:]
345         # (area_id, cell_id, strength)*
346         self.gsm_cells: List[Tuple[int, int, int]] = [
347             tuple(int(el) for el in rest_args[i * 3 : 3 + i * 3])  # type: ignore
348             for i in range(self.gsm_cells_number)
349         ]
350         rest_args = rest_args[3 * self.gsm_cells_number :]
351         self.wifi_aps_number = int(rest_args[0])
352         # (SSID, MAC, strength)*
353         self.wifi_aps = [
354             (
355                 rest_args[1 + i * 3],
356                 rest_args[2 + i * 3],
357                 int(rest_args[3 + i * 3]),
358             )
359             for i in range(self.wifi_aps_number)
360         ]
361         rest_args = rest_args[1 + 3 * self.wifi_aps_number :]
362         self.positioning_accuracy = float(rest_args[0])
363         self.devtime = (
364             datetime.strptime(
365                 p.date + p.time,
366                 "%d%m%y%H%M%S",
367             )
368             # .replace(tzinfo=timezone.utc)
369             # .astimezone(tz=timezone.utc)
370         )
371         self.latitude = p.lat * p.nors
372         self.longitude = p.lon * p.eorw
373
374     def rectified(self) -> Report:
375         if self.gps_valid:
376             return CoordReport(
377                 devtime=str(self.devtime),
378                 battery_percentage=self.battery_percentage,
379                 accuracy=self.positioning_accuracy,
380                 altitude=self.altitude,
381                 speed=self.speed,
382                 direction=self.direction,
383                 latitude=self.latitude,
384                 longitude=self.longitude,
385             )
386         else:
387             return HintReport(
388                 devtime=str(self.devtime),
389                 battery_percentage=self.battery_percentage,
390                 mcc=self.mcc,
391                 mnc=self.mnc,
392                 gsm_cells=self.gsm_cells,
393                 wifi_aps=self.wifi_aps,
394             )
395
396
397 class AL(_LOC_DATA):
398     RESPOND = Respond.INL
399
400
401 class CONFIG(BeeSurePkt):
402     pass
403
404
405 class CR(BeeSurePkt):
406     pass
407
408
409 class FLOWER(BeeSurePkt):
410     OUT_KWARGS = (("number", int, 1),)
411
412     def out_encode(self) -> str:
413         self.number: int
414         return str(self.number)
415
416
417 class ICCID(BeeSurePkt):
418     pass
419
420
421 class LK(BeeSurePkt):
422     RESPOND = Respond.INL
423
424     def in_decode(self, *args: str) -> None:
425         numargs = len(args)
426         if numargs > 0:
427             self.step = args[0]
428         if numargs > 1:
429             self.tumbling_number = args[1]
430         if numargs > 2:
431             self.battery_percentage = args[2]
432
433     def in_encode(self) -> str:
434         return "LK"
435
436
437 class MESSAGE(BeeSurePkt):
438     OUT_KWARGS = (("message", str, ""),)
439
440     def out_encode(self) -> str:
441         return str(self.message.encode("utf_16_be").hex())
442
443
444 class _PHB(BeeSurePkt):
445     OUT_KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = (
446         ("entries", pblist, []),
447     )
448
449     def out_encode(self) -> str:
450         self.entries: List[Tuple[str, str]]
451         return ",".join(
452             [
453                 ",".join((num, name.encode("utf_16_be").hex()))
454                 for name, num in self.entries
455             ]
456         )
457
458
459 class PHB(_PHB):
460     pass
461
462
463 class PHB2(_PHB):
464     pass
465
466
467 class POWEROFF(BeeSurePkt):
468     pass
469
470
471 class RESET(BeeSurePkt):
472     pass
473
474
475 class SOS(BeeSurePkt):
476     OUT_KWARGS = (("phonenumbers", l3str, ["", "", ""]),)
477
478     def out_encode(self) -> str:
479         self.phonenumbers: List[str]
480         return ",".join(self.phonenumbers)
481
482
483 class _SET_PHONE(BeeSurePkt):
484     OUT_KWARGS = (("phonenumber", str, ""),)
485
486     def out_encode(self) -> str:
487         self.phonenumber: str
488         return self.phonenumber
489
490
491 class SOS1(_SET_PHONE):
492     pass
493
494
495 class SOS2(_SET_PHONE):
496     pass
497
498
499 class SOS3(_SET_PHONE):
500     pass
501
502
503 class TK(BeeSurePkt):
504     RESPOND = Respond.INL
505
506     def in_decode(self, *args: Any) -> None:
507         assert len(args) == 1 and isinstance(args[0], bytes)
508         self.amr_data = (
509             args[0]
510             .replace(b"}*", b"*")
511             .replace(b"},", b",")
512             .replace(b"}[", b"[")
513             .replace(b"}]", b"]")
514             .replace(b"}}", b"}")
515         )
516
517     def out_encode(self) -> str:
518         return "1"  # 0 - receive failure, 1 - receive success
519
520
521 class TKQ(BeeSurePkt):
522     RESPOND = Respond.INL
523
524
525 class TKQ2(BeeSurePkt):
526     RESPOND = Respond.INL
527
528
529 class UD(_LOC_DATA):
530     pass
531
532
533 class UD2(_LOC_DATA):
534     pass
535
536
537 # Build dicts protocol number -> class and class name -> protocol number
538 CLASSES = {}
539 if True:  # just to indent the code, sorry!
540     for cls in [
541         cls
542         for name, cls in globals().items()
543         if isclass(cls)
544         and issubclass(cls, BeeSurePkt)
545         and not name.startswith("_")
546     ]:
547         CLASSES[cls.__name__] = cls
548
549
550 def class_by_prefix(
551     prefix: str,
552 ) -> Union[Type[BeeSurePkt], List[str]]:
553     if prefix.startswith(PROTO_PREFIX):
554         pname = prefix[len(PROTO_PREFIX) :].upper()
555     else:
556         raise KeyError(pname)
557     lst = [name for name in CLASSES.keys() if name.upper().startswith(pname)]
558     for proto in lst:
559         if len(lst) == 1:  # unique prefix match
560             return CLASSES[proto]
561         if proto == pname:  # exact match
562             return CLASSES[proto]
563     return lst
564
565
566 def proto_handled(proto: str) -> bool:
567     return proto.startswith(PROTO_PREFIX)
568
569
570 def proto_of_message(packet: bytes) -> str:
571     return PROTO_PREFIX + packet[20:-1].split(b",")[0].decode()
572
573
574 def imei_from_packet(packet: bytes) -> Optional[str]:
575     toskip, _, imei, _ = _framestart(packet)
576     if toskip == 0 and imei != "":
577         return imei
578     return None
579
580
581 def is_goodbye_packet(packet: bytes) -> bool:
582     return False
583
584
585 def inline_response(packet: bytes) -> Optional[bytes]:
586     proto = packet[20:-1].split(b",")[0].decode()
587     if proto in CLASSES:
588         cls = CLASSES[proto]
589         if cls.RESPOND is Respond.INL:
590             return cls.Out().packed
591     return None
592
593
594 def probe_buffer(buffer: bytes) -> bool:
595     return bool(RE.search(buffer))
596
597
598 def parse_message(packet: bytes, is_incoming: bool = True) -> BeeSurePkt:
599     """From a packet (without framing bytes) derive the XXX.In object"""
600     toskip, vendor, imei, datalength = _framestart(packet)
601     try:
602         splits = packet[20:-1].decode().split(",")
603         proto = splits[0] if len(splits) > 0 else ""
604         payload: Union[List[str], bytes] = splits[1:]
605     except UnicodeDecodeError:
606         bsplits = packet[20:-1].split(b",", 1)
607         if len(bsplits) == 2:
608             proto = bsplits[0].decode("ascii")
609             payload = bsplits[1]
610     if proto not in CLASSES:
611         cause: Union[DecodeError, ValueError, IndexError] = ValueError(
612             f"Proto {proto} is unknown"
613         )
614     else:
615         try:
616             if is_incoming:
617                 return CLASSES[proto].In(vendor, imei, datalength, payload)
618             else:
619                 return CLASSES[proto].Out(vendor, imei, datalength, payload)
620         except (DecodeError, ValueError, IndexError) as e:
621             cause = e
622     if is_incoming:
623         retobj = UNKNOWN.In(vendor, imei, datalength, payload)
624     else:
625         retobj = UNKNOWN.Out(vendor, imei, datalength, payload)
626     retobj.proto = proto  # Override class attr with object attr
627     retobj.cause = cause
628     return retobj
629
630
631 def exposed_protos() -> List[Tuple[str, bool]]:
632     return [
633         (cls.proto_name(), False)
634         for cls in CLASSES.values()
635         if hasattr(cls, "rectified")
636     ]