]> www.average.org Git - loctrkd.git/blob - loctrkd/beesure.py
beesure: implment MESSAGE command
[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 def pblist(x: Union[str, List[Tuple[str, str]]]) -> List[Tuple[str, str]]:
175     if isinstance(x, str):
176
177         def splitpair(s: str) -> Tuple[str, str]:
178             a, b = s.split(":")
179             return a, b
180
181         lx = [splitpair(el) for el in x.split(",")]
182     else:
183         lx = x
184     if len(lx) > 5:
185         raise ValueError(str(lx) + " has too many elements (max 5)")
186     return lx
187
188
189 class MetaPkt(type):
190     """
191     For each class corresponding to a message, automatically create
192     two nested classes `In` and `Out` that also inherit from their
193     "nest". Class attribute `IN_KWARGS` defined in the "nest" is
194     copied to the `In` nested class under the name `KWARGS`, and
195     likewise, `OUT_KWARGS` of the nest class is copied as `KWARGS`
196     to the nested class `Out`. In addition, method `encode` is
197     defined in both classes equal to `in_encode()` and `out_encode()`
198     respectively.
199     """
200
201     if TYPE_CHECKING:
202
203         def __getattr__(self, name: str) -> Any:
204             pass
205
206         def __setattr__(self, name: str, value: Any) -> None:
207             pass
208
209     def __new__(
210         cls: Type["MetaPkt"],
211         name: str,
212         bases: Tuple[type, ...],
213         attrs: Dict[str, Any],
214     ) -> "MetaPkt":
215         newcls = super().__new__(cls, name, bases, attrs)
216         newcls.In = super().__new__(
217             cls,
218             name + ".In",
219             (newcls,) + bases,
220             {
221                 "KWARGS": newcls.IN_KWARGS,
222                 "decode": newcls.in_decode,
223                 "encode": newcls.in_encode,
224             },
225         )
226         newcls.Out = super().__new__(
227             cls,
228             name + ".Out",
229             (newcls,) + bases,
230             {
231                 "KWARGS": newcls.OUT_KWARGS,
232                 "decode": newcls.out_decode,
233                 "encode": newcls.out_encode,
234             },
235         )
236         return newcls
237
238
239 class Respond(Enum):
240     NON = 0  # Incoming, no response needed
241     INL = 1  # Birirectional, use `inline_response()`
242     EXT = 2  # Birirectional, use external responder
243
244
245 class BeeSurePkt(metaclass=MetaPkt):
246     RESPOND = Respond.NON  # Do not send anything back by default
247     IN_KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = ()
248     OUT_KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = ()
249     KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = ()
250     In: Type["BeeSurePkt"]
251     Out: Type["BeeSurePkt"]
252
253     if TYPE_CHECKING:
254
255         def __getattr__(self, name: str) -> Any:
256             pass
257
258         def __setattr__(self, name: str, value: Any) -> None:
259             pass
260
261     def __init__(self, *args: Any, **kwargs: Any):
262         """
263         Construct the object _either_ from (length, payload),
264         _or_ from the values of individual fields
265         """
266         self.payload: Union[List[str], bytes]
267         assert not args or (len(args) == 4 and not kwargs)
268         if args:  # guaranteed to be two arguments at this point
269             self.vendor, self.imei, self.datalength, self.payload = args
270             try:
271                 if isinstance(self.payload, list):
272                     self.decode(*self.payload)
273                 else:
274                     self.decode(self.payload)
275             except error as e:
276                 raise DecodeError(e, obj=self)
277         else:
278             for kw, typ, dfl in self.KWARGS:
279                 setattr(self, kw, typ(kwargs.pop(kw, dfl)))
280             if kwargs:
281                 raise ValueError(
282                     self.__class__.__name__ + " stray kwargs " + str(kwargs)
283                 )
284
285     def __repr__(self) -> str:
286         return "{}({})".format(
287             self.__class__.__name__,
288             ", ".join(
289                 "{}={}".format(
290                     k,
291                     'bytes.fromhex("{}")'.format(v.hex())
292                     if isinstance(v, bytes)
293                     else v.__repr__(),
294                 )
295                 for k, v in self.__dict__.items()
296                 if not k.startswith("_")
297             ),
298         )
299
300     def decode(self, *args: Any) -> None:
301         ...
302
303     def in_decode(self, *args: str) -> None:
304         # Overridden in subclasses, otherwise do not decode payload
305         return
306
307     def out_decode(self, *args: str) -> None:
308         # Overridden in subclasses, otherwise do not decode payload
309         return
310
311     def encode(self) -> str:
312         ...
313
314     def in_encode(self) -> str:
315         # Necessary to emulate terminal, which is not implemented
316         raise NotImplementedError(
317             self.__class__.__name__ + ".encode() not implemented"
318         )
319
320     def out_encode(self) -> str:
321         # Overridden in subclasses, otherwise command verb only
322         return ""
323
324     @property
325     def PROTO(self) -> str:
326         try:
327             proto, _ = self.__class__.__name__.split(".")
328         except ValueError:
329             proto = self.__class__.__name__
330         return proto
331
332     @property
333     def packed(self) -> bytes:
334         data = self.encode()
335         payload = self.PROTO + "," + data if data else self.PROTO
336         return f"[LT*0000000000*{len(payload):04X}*{payload}]".encode()
337
338
339 class UNKNOWN(BeeSurePkt):
340     pass
341
342
343 class _LOC_DATA(BeeSurePkt):
344     def in_decode(self, *args: str) -> None:
345         p = SimpleNamespace()
346         _id = lambda x: x
347         for (obj, attr, func), val in zip(
348             (
349                 (p, "date", _id),
350                 (p, "time", _id),
351                 (self, "gps_valid", lambda x: x == "A"),
352                 (p, "lat", float),
353                 (p, "nors", lambda x: 1 if x == "N" else -1),
354                 (p, "lon", float),
355                 (p, "eorw", lambda x: 1 if x == "E" else -1),
356                 (self, "speed", float),
357                 (self, "direction", float),
358                 (self, "altitude", float),
359                 (self, "num_of_sats", int),
360                 (self, "gsm_strength_percentage", int),
361                 (self, "battery_percentage", int),
362                 (self, "pedometer", int),
363                 (self, "tubmling_times", int),
364                 (self, "device_status", lambda x: int(x, 16)),
365                 (self, "base_stations_number", int),
366                 (self, "connect_base_station_number", int),
367                 (self, "mcc", int),
368                 (self, "mnc", int),
369             ),
370             args[:20],
371         ):
372             setattr(obj, attr, func(val))  # type: ignore
373         rest_args = args[20:]
374         # (area_id, cell_id, strength)*
375         self.base_stations = [
376             tuple(int(el) for el in rest_args[i * 3 : 3 + i * 3])
377             for i in range(self.base_stations_number)
378         ]
379         rest_args = rest_args[3 * self.base_stations_number :]
380         self.wifi_aps_number = int(rest_args[0])
381         # (SSID, MAC, strength)*
382         self.wifi_aps = [
383             (
384                 rest_args[1 + i * 3],
385                 rest_args[2 + i * 3],
386                 int(rest_args[3 + i * 3]),
387             )
388             for i in range(self.wifi_aps_number)
389         ]
390         rest_args = rest_args[1 + 3 * self.wifi_aps_number :]
391         self.positioning_accuracy = float(rest_args[0])
392         self.devtime = (
393             datetime.strptime(
394                 p.date + p.time,
395                 "%d%m%y%H%M%S",
396             )
397             # .replace(tzinfo=timezone.utc)
398             # .astimezone(tz=timezone.utc)
399         )
400         self.latitude = p.lat * p.nors
401         self.longitude = p.lon * p.eorw
402
403
404 class AL(_LOC_DATA):
405     RESPOND = Respond.INL
406
407
408 class CONFIG(BeeSurePkt):
409     pass
410
411
412 class CR(BeeSurePkt):
413     pass
414
415
416 class FLOWER(BeeSurePkt):
417     OUT_KWARGS = (("number", int, 1),)
418
419     def out_encode(self) -> str:
420         self.number: int
421         return str(self.number)
422
423
424 class ICCID(BeeSurePkt):
425     pass
426
427
428 class LK(BeeSurePkt):
429     RESPOND = Respond.INL
430
431     def in_decode(self, *args: str) -> None:
432         numargs = len(args)
433         if numargs > 0:
434             self.step = args[0]
435         if numargs > 1:
436             self.tumbling_number = args[1]
437         if numargs > 2:
438             self.battery_percentage = args[2]
439
440     def in_encode(self) -> str:
441         return "LK"
442
443
444 class MESSAGE(BeeSurePkt):
445     OUT_KWARGS = (("message", str, ""),)
446
447     def out_encode(self) -> str:
448         return str(self.message.encode("utf_16_be").hex())
449
450
451 class _PHB(BeeSurePkt):
452     OUT_KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = (
453         ("entries", pblist, []),
454     )
455
456     def out_encode(self) -> str:
457         self.entries: List[Tuple[str, str]]
458         return ",".join(
459             [
460                 ",".join((num, name.encode("utf_16_be").hex()))
461                 for name, num in self.entries
462             ]
463         )
464
465
466 class PHB(_PHB):
467     pass
468
469
470 class PHB2(_PHB):
471     pass
472
473
474 class POWEROFF(BeeSurePkt):
475     pass
476
477
478 class RESET(BeeSurePkt):
479     pass
480
481
482 class SOS(BeeSurePkt):
483     OUT_KWARGS = (("phonenumbers", l3str, ["", "", ""]),)
484
485     def out_encode(self) -> str:
486         self.phonenumbers: List[str]
487         return ",".join(self.phonenumbers)
488
489
490 class _SET_PHONE(BeeSurePkt):
491     OUT_KWARGS = (("phonenumber", str, ""),)
492
493     def out_encode(self) -> str:
494         self.phonenumber: str
495         return self.phonenumber
496
497
498 class SOS1(_SET_PHONE):
499     pass
500
501
502 class SOS2(_SET_PHONE):
503     pass
504
505
506 class SOS3(_SET_PHONE):
507     pass
508
509
510 class TK(BeeSurePkt):
511     RESPOND = Respond.INL
512
513     def in_decode(self, *args: Any) -> None:
514         assert len(args) == 1 and isinstance(args[0], bytes)
515         self.amr_data = (
516             args[0]
517             .replace(b"}*", b"*")
518             .replace(b"},", b",")
519             .replace(b"}[", b"[")
520             .replace(b"}]", b"]")
521             .replace(b"}}", b"}")
522         )
523
524     def out_encode(self) -> str:
525         return "1"  # 0 - receive failure, 1 - receive success
526
527
528 class TKQ(BeeSurePkt):
529     RESPOND = Respond.INL
530
531
532 class TKQ2(BeeSurePkt):
533     RESPOND = Respond.INL
534
535
536 class UD(_LOC_DATA):
537     pass
538
539
540 class UD2(_LOC_DATA):
541     pass
542
543
544 # Build dicts protocol number -> class and class name -> protocol number
545 CLASSES = {}
546 if True:  # just to indent the code, sorry!
547     for cls in [
548         cls
549         for name, cls in globals().items()
550         if isclass(cls)
551         and issubclass(cls, BeeSurePkt)
552         and not name.startswith("_")
553     ]:
554         CLASSES[cls.__name__] = cls
555
556
557 def class_by_prefix(
558     prefix: str,
559 ) -> Union[Type[BeeSurePkt], List[str]]:
560     if prefix.startswith(PROTO_PREFIX):
561         pname = prefix[len(PROTO_PREFIX) :].upper()
562     else:
563         raise KeyError(pname)
564     lst = [name for name in CLASSES.keys() if name.upper().startswith(pname)]
565     for proto in lst:
566         if len(lst) == 1:  # unique prefix match
567             return CLASSES[proto]
568         if proto == pname:  # exact match
569             return CLASSES[proto]
570     return lst
571
572
573 def proto_handled(proto: str) -> bool:
574     return proto.startswith(PROTO_PREFIX)
575
576
577 def proto_name(obj: Union[MetaPkt, BeeSurePkt]) -> str:
578     return PROTO_PREFIX + (
579         obj.__class__.__name__ if isinstance(obj, BeeSurePkt) else obj.__name__
580     )
581
582
583 def proto_of_message(packet: bytes) -> str:
584     return PROTO_PREFIX + packet[20:-1].split(b",")[0].decode()
585
586
587 def imei_from_packet(packet: bytes) -> Optional[str]:
588     toskip, _, imei, _ = _framestart(packet)
589     if toskip == 0 and imei != "":
590         return imei
591     return None
592
593
594 def is_goodbye_packet(packet: bytes) -> bool:
595     return False
596
597
598 def inline_response(packet: bytes) -> Optional[bytes]:
599     proto = packet[20:-1].split(b",")[0].decode()
600     if proto in CLASSES:
601         cls = CLASSES[proto]
602         if cls.RESPOND is Respond.INL:
603             return cls.Out().packed
604     return None
605
606
607 def probe_buffer(buffer: bytes) -> bool:
608     return bool(RE.search(buffer))
609
610
611 def parse_message(packet: bytes, is_incoming: bool = True) -> BeeSurePkt:
612     """From a packet (without framing bytes) derive the XXX.In object"""
613     toskip, vendor, imei, datalength = _framestart(packet)
614     try:
615         splits = packet[20:-1].decode().split(",")
616         proto = splits[0] if len(splits) > 0 else ""
617         payload: Union[List[str], bytes] = splits[1:]
618     except UnicodeDecodeError:
619         bsplits = packet[20:-1].split(b",", 1)
620         if len(bsplits) == 2:
621             proto = bsplits[0].decode("ascii")
622             payload = bsplits[1]
623     if proto not in CLASSES:
624         cause: Union[DecodeError, ValueError, IndexError] = ValueError(
625             f"Proto {proto} is unknown"
626         )
627     else:
628         try:
629             if is_incoming:
630                 return CLASSES[proto].In(vendor, imei, datalength, payload)
631             else:
632                 return CLASSES[proto].Out(vendor, imei, datalength, payload)
633         except (DecodeError, ValueError, IndexError) as e:
634             cause = e
635     if is_incoming:
636         retobj = UNKNOWN.In(vendor, imei, datalength, payload)
637     else:
638         retobj = UNKNOWN.Out(vendor, imei, datalength, payload)
639     retobj.proto = proto  # Override class attr with object attr
640     retobj.cause = cause
641     return retobj
642
643
644 def exposed_protos() -> List[Tuple[str, bool]]:
645     return [
646         (proto_name(UD), True),
647         (proto_name(UD2), False),
648     ]