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