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