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