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