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