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