]> www.average.org Git - loctrkd.git/blob - loctrkd/beesure.py
beesure: consider valid if enough satellites
[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     BINARY = False
211     RESPOND = Respond.NON  # Do not send anything back by default
212     IN_KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = ()
213     OUT_KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = ()
214     KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = ()
215     In: Type["BeeSurePkt"]
216     Out: Type["BeeSurePkt"]
217
218     if TYPE_CHECKING:
219
220         def __getattr__(self, name: str) -> Any:
221             pass
222
223         def __setattr__(self, name: str, value: Any) -> None:
224             pass
225
226     def __init__(self, *args: Any, **kwargs: Any):
227         """
228         Construct the object _either_ from (length, payload),
229         _or_ from the values of individual fields
230         """
231         self.payload: Union[List[str], bytes]
232         assert not args or (len(args) == 4 and not kwargs)
233         if args:  # guaranteed to be two arguments at this point
234             self.vendor, self.imei, self.datalength, self.payload = args
235             try:
236                 if isinstance(self.payload, list):
237                     self.decode(*self.payload)
238                 else:
239                     self.decode(self.payload)
240             except error as e:
241                 raise DecodeError(e, obj=self)
242         else:
243             for kw, typ, dfl in self.KWARGS:
244                 setattr(self, kw, typ(kwargs.pop(kw, dfl)))
245             if kwargs:
246                 raise ValueError(
247                     self.__class__.__name__ + " stray kwargs " + str(kwargs)
248                 )
249
250     def __repr__(self) -> str:
251         return "{}({})".format(
252             self.__class__.__name__,
253             ", ".join(
254                 "{}={}".format(
255                     k,
256                     'bytes.fromhex("{}")'.format(v.hex())
257                     if isinstance(v, bytes)
258                     else v.__repr__(),
259                 )
260                 for k, v in self.__dict__.items()
261                 if not k.startswith("_")
262             ),
263         )
264
265     def decode(self, *args: Any) -> None:
266         ...
267
268     def in_decode(self, *args: str) -> None:
269         # Overridden in subclasses, otherwise do not decode payload
270         return
271
272     def out_decode(self, *args: str) -> None:
273         # Overridden in subclasses, otherwise do not decode payload
274         return
275
276     def encode(self) -> str:
277         ...
278
279     def in_encode(self) -> str:
280         # Necessary to emulate terminal, which is not implemented
281         raise NotImplementedError(
282             self.__class__.__name__ + ".encode() not implemented"
283         )
284
285     def out_encode(self) -> str:
286         # Overridden in subclasses, otherwise command verb only
287         return ""
288
289     @classproperty
290     def PROTO(cls: "BeeSurePkt") -> str:
291         """Name of the class without possible .In / .Out suffix"""
292         proto: str
293         try:
294             proto, _ = cls.__name__.split(".")
295         except ValueError:
296             proto = cls.__name__
297         return proto
298
299     @classmethod
300     def proto_name(cls) -> str:
301         """Name of the command as used externally"""
302         return PROTO_PREFIX + cls.PROTO[:16]
303
304     @property
305     def packed(self) -> bytes:
306         data = self.encode()
307         payload = self.PROTO + "," + data if data else self.PROTO
308         return f"[LT*0000000000*{len(payload):04X}*{payload}]".encode()
309
310
311 class UNKNOWN(BeeSurePkt):
312     pass
313
314
315 class _LOC_DATA(BeeSurePkt):
316     def in_decode(self, *args: str) -> None:
317         p = SimpleNamespace()
318         _id = lambda x: x
319         for (obj, attr, func), val in zip(
320             (
321                 (p, "date", _id),
322                 (p, "time", _id),
323                 (self, "gps_valid", lambda x: x == "A"),
324                 (p, "lat", float),
325                 (p, "nors", lambda x: 1 if x == "N" else -1),
326                 (p, "lon", float),
327                 (p, "eorw", lambda x: 1 if x == "E" else -1),
328                 (self, "speed", float),
329                 (self, "direction", float),
330                 (self, "altitude", float),
331                 (self, "num_of_sats", int),
332                 (self, "gsm_strength_percentage", int),
333                 (self, "battery_percentage", int),
334                 (self, "pedometer", int),
335                 (self, "tubmling_times", int),
336                 (self, "device_status", lambda x: int(x, 16)),
337                 (self, "gsm_cells_number", int),
338                 (self, "connect_base_station_number", int),
339                 (self, "mcc", int),
340                 (self, "mnc", int),
341             ),
342             args[:20],
343         ):
344             setattr(obj, attr, func(val))  # type: ignore
345         rest_args = args[20:]
346         # (area_id, cell_id, strength)*
347         self.gsm_cells: List[Tuple[int, int, int]] = [
348             tuple(int(el) for el in rest_args[i * 3 : 3 + i * 3])  # type: ignore
349             for i in range(self.gsm_cells_number)
350         ]
351         rest_args = rest_args[3 * self.gsm_cells_number :]
352         self.wifi_aps_number = int(rest_args[0])
353         # (SSID, MAC, strength)*
354         self.wifi_aps = [
355             (
356                 rest_args[1 + i * 3],
357                 rest_args[2 + i * 3],
358                 int(rest_args[3 + i * 3]),
359             )
360             for i in range(self.wifi_aps_number)
361         ]
362         rest_args = rest_args[1 + 3 * self.wifi_aps_number :]
363         self.positioning_accuracy = float(rest_args[0])
364         self.devtime = (
365             datetime.strptime(
366                 p.date + p.time,
367                 "%d%m%y%H%M%S",
368             )
369             # .replace(tzinfo=timezone.utc)
370             # .astimezone(tz=timezone.utc)
371         )
372         self.latitude = p.lat * p.nors
373         self.longitude = p.lon * p.eorw
374
375     def rectified(self) -> Report:
376         # self.gps_valid is supposed to mean it, but it does not. Perfectly
377         # good looking coordinates, with ten satellites, still get 'V'.
378         # I suspect that in reality, 'A' means "hint data is absent".
379         if self.gps_valid or self.num_of_sats > 3:
380             return CoordReport(
381                 devtime=str(self.devtime),
382                 battery_percentage=self.battery_percentage,
383                 accuracy=self.positioning_accuracy,
384                 altitude=self.altitude,
385                 speed=self.speed,
386                 direction=self.direction,
387                 latitude=self.latitude,
388                 longitude=self.longitude,
389             )
390         else:
391             return HintReport(
392                 devtime=str(self.devtime),
393                 battery_percentage=self.battery_percentage,
394                 mcc=self.mcc,
395                 mnc=self.mnc,
396                 gsm_cells=self.gsm_cells,
397                 wifi_aps=self.wifi_aps,
398             )
399
400
401 class AL(_LOC_DATA):
402     RESPOND = Respond.INL
403
404
405 class CONFIG(BeeSurePkt):
406     pass
407
408
409 class CR(BeeSurePkt):
410     pass
411
412
413 class FLOWER(BeeSurePkt):
414     OUT_KWARGS = (("number", int, 1),)
415
416     def out_encode(self) -> str:
417         self.number: int
418         return str(self.number)
419
420
421 class ICCID(BeeSurePkt):
422     pass
423
424
425 class LK(BeeSurePkt):
426     RESPOND = Respond.INL
427
428     def in_decode(self, *args: str) -> None:
429         numargs = len(args)
430         if numargs > 0:
431             self.step = args[0]
432         if numargs > 1:
433             self.tumbling_number = args[1]
434         if numargs > 2:
435             self.battery_percentage = args[2]
436
437     def in_encode(self) -> str:
438         return "LK"
439
440
441 class MESSAGE(BeeSurePkt):
442     OUT_KWARGS = (("message", str, ""),)
443
444     def out_encode(self) -> str:
445         return str(self.message.encode("utf_16_be").hex())
446
447
448 class _PHB(BeeSurePkt):
449     OUT_KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = (
450         ("entries", pblist, []),
451     )
452
453     def out_encode(self) -> str:
454         self.entries: List[Tuple[str, str]]
455         return ",".join(
456             [
457                 ",".join((num, name.encode("utf_16_be").hex()))
458                 for name, num in self.entries
459             ]
460         )
461
462
463 class PHB(_PHB):
464     pass
465
466
467 class PHB2(_PHB):
468     pass
469
470
471 class POWEROFF(BeeSurePkt):
472     pass
473
474
475 class RESET(BeeSurePkt):
476     pass
477
478
479 class SOS(BeeSurePkt):
480     OUT_KWARGS = (("phonenumbers", l3str, ["", "", ""]),)
481
482     def out_encode(self) -> str:
483         self.phonenumbers: List[str]
484         return ",".join(self.phonenumbers)
485
486
487 class _SET_PHONE(BeeSurePkt):
488     OUT_KWARGS = (("phonenumber", str, ""),)
489
490     def out_encode(self) -> str:
491         self.phonenumber: str
492         return self.phonenumber
493
494
495 class SOS1(_SET_PHONE):
496     pass
497
498
499 class SOS2(_SET_PHONE):
500     pass
501
502
503 class SOS3(_SET_PHONE):
504     pass
505
506
507 class TK(BeeSurePkt):
508     BINARY = True
509     RESPOND = Respond.INL
510
511     def in_decode(self, *args: Any) -> None:
512         assert len(args) == 1 and isinstance(args[0], bytes)
513         self.amr_data = (
514             args[0]
515             .replace(b"}*", b"*")
516             .replace(b"},", b",")
517             .replace(b"}[", b"[")
518             .replace(b"}]", b"]")
519             .replace(b"}}", b"}")
520         )
521
522     def out_encode(self) -> str:
523         return "1"  # 0 - receive failure, 1 - receive success
524
525
526 class TKQ(BeeSurePkt):
527     RESPOND = Respond.INL
528
529
530 class TKQ2(BeeSurePkt):
531     RESPOND = Respond.INL
532
533
534 class UD(_LOC_DATA):
535     pass
536
537
538 class UD2(_LOC_DATA):
539     pass
540
541
542 # Build dicts protocol number -> class and class name -> protocol number
543 CLASSES = {}
544 if True:  # just to indent the code, sorry!
545     for cls in [
546         cls
547         for name, cls in globals().items()
548         if isclass(cls)
549         and issubclass(cls, BeeSurePkt)
550         and not name.startswith("_")
551     ]:
552         CLASSES[cls.__name__] = cls
553
554
555 def class_by_prefix(
556     prefix: str,
557 ) -> Union[Type[BeeSurePkt], List[str]]:
558     if prefix.startswith(PROTO_PREFIX):
559         pname = prefix[len(PROTO_PREFIX) :].upper()
560     else:
561         raise KeyError(pname)
562     lst = [name for name in CLASSES.keys() if name.upper().startswith(pname)]
563     for proto in lst:
564         if len(lst) == 1:  # unique prefix match
565             return CLASSES[proto]
566         if proto == pname:  # exact match
567             return CLASSES[proto]
568     return lst
569
570
571 def proto_handled(proto: str) -> bool:
572     return proto.startswith(PROTO_PREFIX)
573
574
575 def proto_of_message(packet: bytes) -> str:
576     return PROTO_PREFIX + packet[20:-1].split(b",")[0].decode()
577
578
579 def imei_from_packet(packet: bytes) -> Optional[str]:
580     toskip, _, imei, _ = _framestart(packet)
581     if toskip == 0 and imei != "":
582         return imei
583     return None
584
585
586 def is_goodbye_packet(packet: bytes) -> bool:
587     return False
588
589
590 def inline_response(packet: bytes) -> Optional[bytes]:
591     proto = packet[20:-1].split(b",")[0].decode()
592     if proto in CLASSES:
593         cls = CLASSES[proto]
594         if cls.RESPOND is Respond.INL:
595             return cls.Out().packed
596     return None
597
598
599 def probe_buffer(buffer: bytes) -> bool:
600     return bool(RE.search(buffer))
601
602
603 def parse_message(packet: bytes, is_incoming: bool = True) -> BeeSurePkt:
604     """From a packet (without framing bytes) derive the XXX.In object"""
605     toskip, vendor, imei, datalength = _framestart(packet)
606     bsplits = packet[20:-1].split(b",", 1)
607     try:
608         proto = bsplits[0].decode("ascii")
609     except UnicodeDecodeError:
610         proto = str(bsplits[0])
611     if len(bsplits) == 2:
612         rest = bsplits[1]
613     else:
614         rest = b""
615     if proto in CLASSES:
616         cls = CLASSES[proto].In if is_incoming else CLASSES[proto].Out
617         payload = (
618             # Some people encode their SSIDs in non-utf8
619             rest
620             if cls.BINARY
621             else rest.decode("Windows-1252").split(",")
622         )
623         try:
624             return cls(vendor, imei, datalength, payload)
625         except (DecodeError, ValueError, IndexError) as e:
626             cause: Union[DecodeError, ValueError, IndexError] = e
627     else:
628         payload = rest
629         cause = ValueError(f"Proto {proto} is unknown")
630     if is_incoming:
631         retobj = UNKNOWN.In(vendor, imei, datalength, payload)
632     else:
633         retobj = UNKNOWN.Out(vendor, imei, datalength, payload)
634     retobj.proto = proto  # Override class attr with object attr
635     retobj.cause = cause
636     return retobj
637
638
639 def exposed_protos() -> List[Tuple[str, bool]]:
640     return [
641         (cls.proto_name(), False)
642         for cls in CLASSES.values()
643         if hasattr(cls, "rectified")
644     ]