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 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
271 if isinstance(self.payload, list):
272 self.decode(*self.payload)
274 self.decode(self.payload)
276 raise DecodeError(e, obj=self)
278 for kw, typ, dfl in self.KWARGS:
279 setattr(self, kw, typ(kwargs.pop(kw, dfl)))
282 self.__class__.__name__ + " stray kwargs " + str(kwargs)
285 def __repr__(self) -> str:
286 return "{}({})".format(
287 self.__class__.__name__,
291 'bytes.fromhex("{}")'.format(v.hex())
292 if isinstance(v, bytes)
295 for k, v in self.__dict__.items()
296 if not k.startswith("_")
300 def decode(self, *args: Any) -> None:
303 def in_decode(self, *args: str) -> None:
304 # Overridden in subclasses, otherwise do not decode payload
307 def out_decode(self, *args: str) -> None:
308 # Overridden in subclasses, otherwise do not decode payload
311 def encode(self) -> str:
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"
320 def out_encode(self) -> str:
321 # Overridden in subclasses, otherwise command verb only
325 def PROTO(self) -> str:
327 proto, _ = self.__class__.__name__.split(".")
329 proto = self.__class__.__name__
333 def packed(self) -> bytes:
335 payload = self.PROTO + "," + data if data else self.PROTO
336 return f"[LT*0000000000*{len(payload):04X}*{payload}]".encode()
339 class UNKNOWN(BeeSurePkt):
343 class LK(BeeSurePkt):
344 RESPOND = Respond.INL
346 def in_decode(self, *args: str) -> None:
351 self.tumbling_number = args[1]
353 self.battery_percentage = args[2]
355 def in_encode(self) -> str:
359 class CONFIG(BeeSurePkt):
363 class ICCID(BeeSurePkt):
367 class _LOC_DATA(BeeSurePkt):
368 def in_decode(self, *args: str) -> None:
369 p = SimpleNamespace()
371 for (obj, attr, func), val in zip(
375 (self, "gps_valid", lambda x: x == "A"),
377 (p, "nors", lambda x: 1 if x == "N" else -1),
379 (p, "eorw", lambda x: 1 if x == "E" else -1),
380 (self, "speed", float),
381 (self, "direction", float),
382 (self, "altitude", float),
383 (self, "num_of_sats", int),
384 (self, "gsm_strength_percentage", int),
385 (self, "battery_percentage", int),
386 (self, "pedometer", int),
387 (self, "tubmling_times", int),
388 (self, "device_status", lambda x: int(x, 16)),
389 (self, "base_stations_number", int),
390 (self, "connect_base_station_number", int),
396 setattr(obj, attr, func(val)) # type: ignore
397 rest_args = args[20:]
398 # (area_id, cell_id, strength)*
399 self.base_stations = [
400 tuple(int(el) for el in rest_args[i * 3 : 3 + i * 3])
401 for i in range(self.base_stations_number)
403 rest_args = rest_args[3 * self.base_stations_number :]
404 self.wifi_aps_number = int(rest_args[0])
405 # (SSID, MAC, strength)*
408 rest_args[1 + i * 3],
409 rest_args[2 + i * 3],
410 int(rest_args[3 + i * 3]),
412 for i in range(self.wifi_aps_number)
414 rest_args = rest_args[1 + 3 * self.wifi_aps_number :]
415 self.positioning_accuracy = float(rest_args[0])
421 # .replace(tzinfo=timezone.utc)
422 # .astimezone(tz=timezone.utc)
424 self.latitude = p.lat * p.nors
425 self.longitude = p.lon * p.eorw
432 class UD2(_LOC_DATA):
436 class TKQ(BeeSurePkt):
437 RESPOND = Respond.INL
440 class TKQ2(BeeSurePkt):
441 RESPOND = Respond.INL
445 RESPOND = Respond.INL
448 class CR(BeeSurePkt):
452 class FLOWER(BeeSurePkt):
453 OUT_KWARGS = (("number", int, 1),)
455 def out_encode(self) -> str:
457 return str(self.number)
460 class _PHB(BeeSurePkt):
461 OUT_KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = (
462 ("entries", pblist, []),
465 def out_encode(self) -> str:
466 self.entries: List[Tuple[str, str]]
469 ",".join((num, name.encode("utf_16_be").hex()))
470 for name, num in self.entries
483 class POWEROFF(BeeSurePkt):
487 class RESET(BeeSurePkt):
491 class SOS(BeeSurePkt):
492 OUT_KWARGS = (("phonenumbers", l3str, ["", "", ""]),)
494 def out_encode(self) -> str:
495 self.phonenumbers: List[str]
496 return ",".join(self.phonenumbers)
499 class _SET_PHONE(BeeSurePkt):
500 OUT_KWARGS = (("phonenumber", str, ""),)
502 def out_encode(self) -> str:
503 self.phonenumber: str
504 return self.phonenumber
507 class SOS1(_SET_PHONE):
511 class SOS2(_SET_PHONE):
515 class SOS3(_SET_PHONE):
519 class TK(BeeSurePkt):
520 RESPOND = Respond.INL
522 def in_decode(self, *args: Any) -> None:
523 assert len(args) == 1 and isinstance(args[0], bytes)
526 .replace(b"}*", b"*")
527 .replace(b"},", b",")
528 .replace(b"}[", b"[")
529 .replace(b"}]", b"]")
530 .replace(b"}}", b"}")
533 def out_encode(self) -> str:
534 return "1" # 0 - receive failure, 1 - receive success
537 # Build dicts protocol number -> class and class name -> protocol number
539 if True: # just to indent the code, sorry!
542 for name, cls in globals().items()
544 and issubclass(cls, BeeSurePkt)
545 and not name.startswith("_")
547 CLASSES[cls.__name__] = cls
552 ) -> Union[Type[BeeSurePkt], List[str]]:
553 if prefix.startswith(PROTO_PREFIX):
554 pname = prefix[len(PROTO_PREFIX) :].upper()
556 raise KeyError(pname)
557 lst = [name for name in CLASSES.keys() if name.upper().startswith(pname)]
559 if len(lst) == 1: # unique prefix match
560 return CLASSES[proto]
561 if proto == pname: # exact match
562 return CLASSES[proto]
566 def proto_handled(proto: str) -> bool:
567 return proto.startswith(PROTO_PREFIX)
570 def proto_name(obj: Union[MetaPkt, BeeSurePkt]) -> str:
571 return PROTO_PREFIX + (
572 obj.__class__.__name__ if isinstance(obj, BeeSurePkt) else obj.__name__
576 def proto_of_message(packet: bytes) -> str:
577 return PROTO_PREFIX + packet[20:-1].split(b",")[0].decode()
580 def imei_from_packet(packet: bytes) -> Optional[str]:
581 toskip, _, imei, _ = _framestart(packet)
582 if toskip == 0 and imei != "":
587 def is_goodbye_packet(packet: bytes) -> bool:
591 def inline_response(packet: bytes) -> Optional[bytes]:
592 proto = packet[20:-1].split(b",")[0].decode()
595 if cls.RESPOND is Respond.INL:
596 return cls.Out().packed
600 def probe_buffer(buffer: bytes) -> bool:
601 return bool(RE.search(buffer))
604 def parse_message(packet: bytes, is_incoming: bool = True) -> BeeSurePkt:
605 """From a packet (without framing bytes) derive the XXX.In object"""
606 toskip, vendor, imei, datalength = _framestart(packet)
608 splits = packet[20:-1].decode().split(",")
609 proto = splits[0] if len(splits) > 0 else ""
610 payload: Union[List[str], bytes] = splits[1:]
611 except UnicodeDecodeError:
612 bsplits = packet[20:-1].split(b",", 1)
613 if len(bsplits) == 2:
614 proto = bsplits[0].decode("ascii")
616 if proto not in CLASSES:
617 cause: Union[DecodeError, ValueError, IndexError] = ValueError(
618 f"Proto {proto} is unknown"
623 return CLASSES[proto].In(vendor, imei, datalength, payload)
625 return CLASSES[proto].Out(vendor, imei, datalength, payload)
626 except (DecodeError, ValueError, IndexError) as e:
629 retobj = UNKNOWN.In(vendor, imei, datalength, payload)
631 retobj = UNKNOWN.Out(vendor, imei, datalength, payload)
632 retobj.proto = proto # Override class attr with object attr
637 def exposed_protos() -> List[Tuple[str, bool]]:
639 (proto_name(UD), True),
640 (proto_name(UD2), False),