2 Implementation of the protocol "beesure" used by some watch-trackers
3 https://www.4p-touch.com/beesure-gps-setracker-server-protocol.html
6 from datetime import datetime, timezone
8 from inspect import isclass
10 from struct import error, pack, unpack
23 from types import SimpleNamespace
44 MAXBUFFER: int = 65557 # Theoretical max buffer 65536 + 21
45 RE = re.compile(b"\[(\w\w)\*(\d{10})\*([0-9a-fA-F]{4})\*")
48 def _framestart(buffer: bytes) -> Tuple[int, str, str, int]:
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`
54 mo = RE.search(buffer)
68 def __init__(self) -> None:
70 self.imei: Optional[str] = None
73 def recv(self, segment: bytes) -> List[Union[bytes, str]]:
75 Process next segment of the stream. Return successfully deframed
76 packets as `bytes` and error messages as `str`.
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.
83 return [f"More than {MAXBUFFER} unparseable data, dropping"]
84 msgs: List[Union[bytes, str]] = []
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
90 if toskip > 0: # Should not happen, report
92 f"Skipping {toskip} bytes of undecodable data"
93 f' "{self.buffer[:toskip][:64]=!r}"'
95 self.buffer = self.buffer[toskip:]
96 # From this point, buffer starts with a packet header
101 f"Packet's imei {imei} mismatches"
102 f" previous value {self.imei}, old value kept"
104 self.datalen = datalen
105 if len(self.buffer) < self.datalen + 21: # Incomplete packet
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])
112 f"Packet does not end with ']'"
113 f" at {self.datalen+20}: {self.buffer=!r}"
115 self.buffer = self.buffer[self.datalen + 21 :]
119 def close(self) -> bytes:
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)
131 return f"[{vid:2s}*{imei:10s}*{dlen:04X}*".encode() + buffer[20:]
134 ### Parser/Constructor ###
137 class DecodeError(Exception):
138 def __init__(self, e: Exception, **kwargs: Any) -> None:
140 for k, v in kwargs.items():
144 def maybe(typ: type) -> Callable[[Any], Any]:
145 return lambda x: None if x is None else typ(x)
148 def intx(x: Union[str, int]) -> int:
149 if isinstance(x, str):
154 def boolx(x: Union[str, bool]) -> bool:
155 if isinstance(x, str):
156 if x.upper() in ("ON", "TRUE", "1"):
158 if x.upper() in ("OFF", "FALSE", "0"):
160 raise ValueError(str(x) + " could not be parsed as a Boolean")
164 def l3str(x: Union[str, List[str]]) -> List[str]:
165 if isinstance(x, str):
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")
174 def pblist(x: Union[str, List[Tuple[str, str]]]) -> List[Tuple[str, str]]:
175 if isinstance(x, str):
177 def splitpair(s: str) -> Tuple[str, str]:
181 lx = [splitpair(el) for el in x.split(",")]
185 raise ValueError(str(lx) + " has too many elements (max 5)")
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()`
203 def __getattr__(self, name: str) -> Any:
206 def __setattr__(self, name: str, value: Any) -> None:
210 cls: Type["MetaPkt"],
212 bases: Tuple[type, ...],
213 attrs: Dict[str, Any],
215 newcls = super().__new__(cls, name, bases, attrs)
216 newcls.In = super().__new__(
221 "KWARGS": newcls.IN_KWARGS,
222 "decode": newcls.in_decode,
223 "encode": newcls.in_encode,
226 newcls.Out = super().__new__(
231 "KWARGS": newcls.OUT_KWARGS,
232 "decode": newcls.out_decode,
233 "encode": newcls.out_encode,
240 NON = 0 # Incoming, no response needed
241 INL = 1 # Birirectional, use `inline_response()`
242 EXT = 2 # Birirectional, use external responder
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"]
255 def __getattr__(self, name: str) -> Any:
258 def __setattr__(self, name: str, value: Any) -> None:
261 def __init__(self, *args: Any, **kwargs: Any):
263 Construct the object _either_ from (length, payload),
264 _or_ from the values of individual fields
266 assert not args or (len(args) == 4 and not kwargs)
267 if args: # guaranteed to be two arguments at this point
268 self.vendor, self.imei, self.datalength, self.payload = args
270 self.decode(*self.payload)
272 raise DecodeError(e, obj=self)
274 for kw, typ, dfl in self.KWARGS:
275 setattr(self, kw, typ(kwargs.pop(kw, dfl)))
278 self.__class__.__name__ + " stray kwargs " + str(kwargs)
281 def __repr__(self) -> str:
282 return "{}({})".format(
283 self.__class__.__name__,
287 'bytes.fromhex("{}")'.format(v.hex())
288 if isinstance(v, bytes)
291 for k, v in self.__dict__.items()
292 if not k.startswith("_")
296 def decode(self, *args: str) -> None:
299 def in_decode(self, *args: str) -> None:
300 # Overridden in subclasses, otherwise do not decode payload
303 def out_decode(self, *args: str) -> None:
304 # Overridden in subclasses, otherwise do not decode payload
307 def encode(self) -> str:
310 def in_encode(self) -> str:
311 # Necessary to emulate terminal, which is not implemented
312 raise NotImplementedError(
313 self.__class__.__name__ + ".encode() not implemented"
316 def out_encode(self) -> str:
317 # Overridden in subclasses, otherwise command verb only
321 def PROTO(self) -> str:
323 proto, _ = self.__class__.__name__.split(".")
325 proto = self.__class__.__name__
329 def packed(self) -> bytes:
331 payload = self.PROTO + "," + data if data else self.PROTO
332 return f"[LT*0000000000*{len(payload):04X}*{payload}]".encode()
335 class UNKNOWN(BeeSurePkt):
339 class LK(BeeSurePkt):
340 RESPOND = Respond.INL
342 def in_decode(self, *args: str) -> None:
347 self.tumbling_number = args[2]
349 self.battery_percentage = args[3]
351 def in_encode(self) -> str:
355 class CONFIG(BeeSurePkt):
359 class ICCID(BeeSurePkt):
363 class _LOC_DATA(BeeSurePkt):
364 def in_decode(self, *args: str) -> None:
365 p = SimpleNamespace()
367 for (obj, attr, func), val in zip(
372 (self, "gps_valid", lambda x: x == "A"),
374 (p, "nors", lambda x: 1 if x == "N" else -1),
376 (p, "eorw", lambda x: 1 if x == "E" else -1),
377 (self, "speed", float),
378 (self, "direction", float),
379 (self, "altitude", float),
380 (self, "num_of_sats", int),
381 (self, "gsm_strength_percentage", int),
382 (self, "battery_percentage", int),
383 (self, "pedometer", int),
384 (self, "tubmling_times", int),
385 (self, "device_status", lambda x: int(x, 16)),
386 (self, "base_stations_number", int),
387 (self, "connect_base_station_number", int),
393 setattr(obj, attr, func(val)) # type: ignore
394 rest_args = args[21:]
395 # (area_id, cell_id, strength)*
396 self.base_stations = [
397 tuple(int(el) for el in rest_args[i * 3 : 3 + i * 3])
398 for i in range(self.base_stations_number)
400 rest_args = rest_args[3 * self.base_stations_number :]
401 self.wifi_aps_number = int(rest_args[0])
402 # (SSID, MAC, strength)*
405 rest_args[1 + i * 3],
406 rest_args[2 + i * 3],
407 int(rest_args[3 + i * 3]),
409 for i in range(self.wifi_aps_number)
411 rest_args = rest_args[1 + 3 * self.wifi_aps_number :]
412 self.positioning_accuracy = float(rest_args[0])
418 # .replace(tzinfo=timezone.utc)
419 # .astimezone(tz=timezone.utc)
421 self.latitude = p.lat * p.nors
422 self.longitude = p.lon * p.eorw
429 class UD2(_LOC_DATA):
433 class TKQ(BeeSurePkt):
434 RESPOND = Respond.INL
437 class TKQ2(BeeSurePkt):
438 RESPOND = Respond.INL
442 RESPOND = Respond.INL
445 class CR(BeeSurePkt):
449 class FLOWER(BeeSurePkt):
450 OUT_KWARGS = (("number", int, 1),)
452 def out_encode(self) -> str:
454 return str(self.number)
457 class _PHB(BeeSurePkt):
458 OUT_KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = (
459 ("entries", pblist, []),
462 def out_encode(self) -> str:
463 self.entries: List[Tuple[str, str]]
466 ",".join((num, name.encode("utf_16_be").hex()))
467 for name, num in self.entries
480 class POWEROFF(BeeSurePkt):
484 class RESET(BeeSurePkt):
488 class SOS(BeeSurePkt):
489 OUT_KWARGS = (("phonenumbers", l3str, ["", "", ""]),)
491 def out_encode(self) -> str:
492 self.phonenumbers: List[str]
493 return ",".join(self.phonenumbers)
496 class _SET_PHONE(BeeSurePkt):
497 OUT_KWARGS = (("phonenumber", str, ""),)
499 def out_encode(self) -> str:
500 self.phonenumber: str
501 return self.phonenumber
504 class SOS1(_SET_PHONE):
508 class SOS2(_SET_PHONE):
512 class SOS3(_SET_PHONE):
516 # Build dicts protocol number -> class and class name -> protocol number
518 if True: # just to indent the code, sorry!
521 for name, cls in globals().items()
523 and issubclass(cls, BeeSurePkt)
524 and not name.startswith("_")
526 CLASSES[cls.__name__] = cls
531 ) -> Union[Type[BeeSurePkt], List[str]]:
532 if prefix.startswith(PROTO_PREFIX):
533 pname = prefix[len(PROTO_PREFIX) :].upper()
535 raise KeyError(pname)
536 lst = [name for name in CLASSES.keys() if name.upper().startswith(pname)]
538 if len(lst) == 1: # unique prefix match
539 return CLASSES[proto]
540 if proto == pname: # exact match
541 return CLASSES[proto]
545 def proto_handled(proto: str) -> bool:
546 return proto.startswith(PROTO_PREFIX)
549 def proto_name(obj: Union[MetaPkt, BeeSurePkt]) -> str:
550 return PROTO_PREFIX + (
551 obj.__class__.__name__ if isinstance(obj, BeeSurePkt) else obj.__name__
555 def proto_of_message(packet: bytes) -> str:
556 return PROTO_PREFIX + packet[20:-1].split(b",")[0].decode()
559 def imei_from_packet(packet: bytes) -> Optional[str]:
560 toskip, _, imei, _ = _framestart(packet)
561 if toskip == 0 and imei != "":
566 def is_goodbye_packet(packet: bytes) -> bool:
570 def inline_response(packet: bytes) -> Optional[bytes]:
571 proto = packet[20:-1].split(b",")[0].decode()
574 if cls.RESPOND is Respond.INL:
575 return cls.Out().packed
579 def probe_buffer(buffer: bytes) -> bool:
580 return bool(RE.search(buffer))
583 def parse_message(packet: bytes, is_incoming: bool = True) -> BeeSurePkt:
584 """From a packet (without framing bytes) derive the XXX.In object"""
585 toskip, vendor, imei, datalength = _framestart(packet)
586 payload = packet[20:-1].decode().split(",")
587 proto = payload[0] if len(payload) > 0 else ""
588 if proto not in CLASSES:
589 cause: Union[DecodeError, ValueError, IndexError] = ValueError(
590 f"Proto {proto} is unknown"
595 return CLASSES[proto].In(vendor, imei, datalength, payload)
597 return CLASSES[proto].Out(vendor, imei, datalength, payload)
598 except (DecodeError, ValueError, IndexError) as e:
601 retobj = UNKNOWN.In(vendor, imei, datalength, payload)
603 retobj = UNKNOWN.Out(vendor, imei, datalength, payload)
604 retobj.proto = proto # Override class attr with object attr
609 def exposed_protos() -> List[Tuple[str, bool]]:
611 (proto_name(UD), True),
612 (proto_name(UD2), False),