]> www.average.org Git - loctrkd.git/blob - loctrkd/beesure.py
beesure: location info parser
[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 class MetaPkt(type):
164     """
165     For each class corresponding to a message, automatically create
166     two nested classes `In` and `Out` that also inherit from their
167     "nest". Class attribute `IN_KWARGS` defined in the "nest" is
168     copied to the `In` nested class under the name `KWARGS`, and
169     likewise, `OUT_KWARGS` of the nest class is copied as `KWARGS`
170     to the nested class `Out`. In addition, method `encode` is
171     defined in both classes equal to `in_encode()` and `out_encode()`
172     respectively.
173     """
174
175     if TYPE_CHECKING:
176
177         def __getattr__(self, name: str) -> Any:
178             pass
179
180         def __setattr__(self, name: str, value: Any) -> None:
181             pass
182
183     def __new__(
184         cls: Type["MetaPkt"],
185         name: str,
186         bases: Tuple[type, ...],
187         attrs: Dict[str, Any],
188     ) -> "MetaPkt":
189         newcls = super().__new__(cls, name, bases, attrs)
190         newcls.In = super().__new__(
191             cls,
192             name + ".In",
193             (newcls,) + bases,
194             {
195                 "KWARGS": newcls.IN_KWARGS,
196                 "decode": newcls.in_decode,
197                 "encode": newcls.in_encode,
198             },
199         )
200         newcls.Out = super().__new__(
201             cls,
202             name + ".Out",
203             (newcls,) + bases,
204             {
205                 "KWARGS": newcls.OUT_KWARGS,
206                 "decode": newcls.out_decode,
207                 "encode": newcls.out_encode,
208             },
209         )
210         return newcls
211
212
213 class Respond(Enum):
214     NON = 0  # Incoming, no response needed
215     INL = 1  # Birirectional, use `inline_response()`
216     EXT = 2  # Birirectional, use external responder
217
218
219 class BeeSurePkt(metaclass=MetaPkt):
220     RESPOND = Respond.NON  # Do not send anything back by default
221     PROTO: str
222     IN_KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = ()
223     OUT_KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = ()
224     KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = ()
225     In: Type["BeeSurePkt"]
226     Out: Type["BeeSurePkt"]
227
228     if TYPE_CHECKING:
229
230         def __getattr__(self, name: str) -> Any:
231             pass
232
233         def __setattr__(self, name: str, value: Any) -> None:
234             pass
235
236     def __init__(self, *args: Any, **kwargs: Any):
237         """
238         Construct the object _either_ from (length, payload),
239         _or_ from the values of individual fields
240         """
241         assert not args or (len(args) == 4 and not kwargs)
242         if args:  # guaranteed to be two arguments at this point
243             self.vendor, self.imei, self.datalength, self.payload = args
244             try:
245                 self.decode(*self.payload)
246             except error as e:
247                 raise DecodeError(e, obj=self)
248         else:
249             for kw, typ, dfl in self.KWARGS:
250                 setattr(self, kw, typ(kwargs.pop(kw, dfl)))
251             if kwargs:
252                 raise ValueError(
253                     self.__class__.__name__ + " stray kwargs " + str(kwargs)
254                 )
255
256     def __repr__(self) -> str:
257         return "{}({})".format(
258             self.__class__.__name__,
259             ", ".join(
260                 "{}={}".format(
261                     k,
262                     'bytes.fromhex("{}")'.format(v.hex())
263                     if isinstance(v, bytes)
264                     else v.__repr__(),
265                 )
266                 for k, v in self.__dict__.items()
267                 if not k.startswith("_")
268             ),
269         )
270
271     def decode(self, *args: str) -> None:
272         ...
273
274     def in_decode(self, *args: str) -> None:
275         # Overridden in subclasses, otherwise do not decode payload
276         return
277
278     def out_decode(self, *args: str) -> None:
279         # Overridden in subclasses, otherwise do not decode payload
280         return
281
282     def encode(self) -> str:
283         ...
284
285     def in_encode(self) -> str:
286         # Necessary to emulate terminal, which is not implemented
287         raise NotImplementedError(
288             self.__class__.__name__ + ".encode() not implemented"
289         )
290
291     def out_encode(self) -> str:
292         # Overridden in subclasses, otherwise command verb only
293         return self.PROTO
294
295     @property
296     def packed(self) -> bytes:
297         buffer = self.encode().encode()
298         return f"[LT*0000000000*{len(buffer):04X}*".encode() + buffer + b"]"
299
300
301 class UNKNOWN(BeeSurePkt):
302     PROTO = "UNKNOWN"
303
304
305 class LK(BeeSurePkt):
306     PROTO = "LK"
307     RESPOND = Respond.INL
308
309     def in_decode(self, *args: str) -> None:
310         numargs = len(args)
311         if numargs > 1:
312             self.step = args[1]
313         if numargs > 2:
314             self.tumbling_number = args[2]
315         if numargs > 3:
316             self.battery_percentage = args[3]
317
318     def in_encode(self) -> str:
319         return "LK"
320
321
322 class CONFIG(BeeSurePkt):
323     PROTO = "CONFIG"
324
325
326 class ICCID(BeeSurePkt):
327     PROTO = "ICCID"
328
329
330 class _LOC_DATA(BeeSurePkt):
331     def in_decode(self, *args: str) -> None:
332         p = SimpleNamespace()
333         _id = lambda x: x
334         for (obj, attr, func), val in zip(
335             (
336                 (p, "verb", _id),
337                 (p, "date", _id),
338                 (p, "time", _id),
339                 (self, "gps_valid", lambda x: x == "A"),
340                 (p, "lat", float),
341                 (p, "nors", lambda x: 1 if x == "N" else -1),
342                 (p, "lon", float),
343                 (p, "eorw", lambda x: 1 if x == "E" else -1),
344                 (self, "speed", float),
345                 (self, "direction", float),
346                 (self, "altitude", float),
347                 (self, "num_of_sats", int),
348                 (self, "gsm_strength_percentage", int),
349                 (self, "battery_percentage", int),
350                 (self, "pedometer", int),
351                 (self, "tubmling_times", int),
352                 (self, "device_status", lambda x: int(x, 16)),
353                 (self, "base_stations_number", int),
354                 (self, "connect_base_station_number", int),
355                 (self, "mcc", int),
356                 (self, "mnc", int),
357             ),
358             args[:21],
359         ):
360             setattr(obj, attr, func(val))  # type: ignore
361         rest_args = args[21:]
362         # (area_id, cell_id, strength)*
363         self.base_stations = [
364             tuple(int(el) for el in rest_args[i * 3 : 3 + i * 3])
365             for i in range(self.base_stations_number)
366         ]
367         rest_args = rest_args[3 * self.base_stations_number :]
368         self.wifi_aps_number = int(rest_args[0])
369         # (SSID, MAC, strength)*
370         self.wifi_aps = [
371             (
372                 rest_args[1 + i * 3],
373                 rest_args[2 + i * 3],
374                 int(rest_args[3 + i * 3]),
375             )
376             for i in range(self.wifi_aps_number)
377         ]
378         rest_args = rest_args[1 + 3 * self.wifi_aps_number :]
379         self.positioning_accuracy = float(rest_args[0])
380         self.devtime = (
381             datetime.strptime(
382                 p.date + p.time,
383                 "%d%m%y%H%M%S",
384             )
385             .replace(tzinfo=timezone.utc)
386             .astimezone(tz=timezone.utc)
387         )
388         self.latitude = p.lat * p.nors
389         self.longitude = p.lon * p.eorw
390
391
392 class UD(_LOC_DATA):
393     PROTO = "UD"
394
395
396 class UD2(_LOC_DATA):
397     PROTO = "UD2"
398
399
400 class TKQ(BeeSurePkt):
401     PROTO = "TKQ"
402     RESPOND = Respond.INL
403
404
405 class TKQ2(BeeSurePkt):
406     PROTO = "TKQ2"
407     RESPOND = Respond.INL
408
409
410 class AL(_LOC_DATA):
411     PROTO = "AL"
412     RESPOND = Respond.INL
413
414
415 # Build dicts protocol number -> class and class name -> protocol number
416 CLASSES = {}
417 PROTOS = {}
418 if True:  # just to indent the code, sorry!
419     for cls in [
420         cls
421         for name, cls in globals().items()
422         if isclass(cls)
423         and issubclass(cls, BeeSurePkt)
424         and not name.startswith("_")
425     ]:
426         if hasattr(cls, "PROTO"):
427             CLASSES[cls.PROTO] = cls
428             PROTOS[cls.__name__] = cls.PROTO
429
430
431 def class_by_prefix(
432     prefix: str,
433 ) -> Union[Type[BeeSurePkt], List[Tuple[str, str]]]:
434     lst = [
435         (name, proto)
436         for name, proto in PROTOS.items()
437         if name.upper().startswith(prefix.upper())
438     ]
439     if len(lst) != 1:
440         return lst
441     _, proto = lst[0]
442     return CLASSES[proto]
443
444
445 def proto_handled(proto: str) -> bool:
446     return proto.startswith(PROTO_PREFIX)
447
448
449 def proto_name(obj: Union[MetaPkt, BeeSurePkt]) -> str:
450     return PROTO_PREFIX + (
451         obj.__class__.__name__ if isinstance(obj, BeeSurePkt) else obj.__name__
452     )
453
454
455 def proto_of_message(packet: bytes) -> str:
456     return PROTO_PREFIX + packet[20:-1].split(b",")[0].decode()
457
458
459 def imei_from_packet(packet: bytes) -> Optional[str]:
460     toskip, _, imei, _ = _framestart(packet)
461     if toskip == 0 and imei != "":
462         return imei
463     return None
464
465
466 def is_goodbye_packet(packet: bytes) -> bool:
467     return False
468
469
470 def inline_response(packet: bytes) -> Optional[bytes]:
471     proto = packet[20:-1].split(b",")[0].decode()
472     if proto in CLASSES:
473         cls = CLASSES[proto]
474         if cls.RESPOND is Respond.INL:
475             return cls.Out().packed
476     return None
477
478
479 def probe_buffer(buffer: bytes) -> bool:
480     return bool(RE.search(buffer))
481
482
483 def parse_message(packet: bytes, is_incoming: bool = True) -> BeeSurePkt:
484     """From a packet (without framing bytes) derive the XXX.In object"""
485     toskip, vendor, imei, datalength = _framestart(packet)
486     payload = packet[20:-1].decode().split(",")
487     proto = payload[0] if len(payload) > 0 else ""
488     if proto not in CLASSES:
489         cause: Union[DecodeError, ValueError, IndexError] = ValueError(
490             f"Proto {proto} is unknown"
491         )
492     else:
493         try:
494             if is_incoming:
495                 return CLASSES[proto].In(vendor, imei, datalength, payload)
496             else:
497                 return CLASSES[proto].Out(vendor, imei, datalength, payload)
498         except (DecodeError, ValueError, IndexError) as e:
499             cause = e
500     if is_incoming:
501         retobj = UNKNOWN.In(vendor, imei, datalength, payload)
502     else:
503         retobj = UNKNOWN.Out(vendor, imei, datalength, payload)
504     retobj.PROTO = proto  # Override class attr with object attr
505     retobj.cause = cause
506     return retobj