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
43 MAXBUFFER: int = 65557 # Theoretical max buffer 65536 + 21
44 RE = re.compile(b"\[(\w\w)\*(\d{10})\*([0-9a-fA-F]{4})\*")
47 def _framestart(buffer: bytes) -> Tuple[int, str, str, int]:
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`
53 mo = RE.search(buffer)
67 def __init__(self) -> None:
69 self.imei: Optional[str] = None
72 def recv(self, segment: bytes) -> List[Union[bytes, str]]:
74 Process next segment of the stream. Return successfully deframed
75 packets as `bytes` and error messages as `str`.
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.
82 return [f"More than {MAXBUFFER} unparseable data, dropping"]
83 msgs: List[Union[bytes, str]] = []
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
89 if toskip > 0: # Should not happen, report
91 f"Skipping {toskip} bytes of undecodable data"
92 f' "{self.buffer[:toskip][:64]=!r}"'
94 self.buffer = self.buffer[toskip:]
95 # From this point, buffer starts with a packet header
100 f"Packet's imei {imei} mismatches"
101 f" previous value {self.imei}, old value kept"
103 self.datalen = datalen
104 if len(self.buffer) < self.datalen + 21: # Incomplete packet
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])
111 f"Packet does not end with ']'"
112 f" at {self.datalen+20}: {self.buffer=!r}"
114 self.buffer = self.buffer[self.datalen + 21 :]
118 def close(self) -> bytes:
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)
130 return f"[{vid:2s}*{imei:10s}*{dlen:04X}*".encode() + buffer[20:]
133 ### Parser/Constructor ###
136 class DecodeError(Exception):
137 def __init__(self, e: Exception, **kwargs: Any) -> None:
139 for k, v in kwargs.items():
143 def maybe(typ: type) -> Callable[[Any], Any]:
144 return lambda x: None if x is None else typ(x)
147 def intx(x: Union[str, int]) -> int:
148 if isinstance(x, str):
153 def boolx(x: Union[str, bool]) -> bool:
154 if isinstance(x, str):
155 if x.upper() in ("ON", "TRUE", "1"):
157 if x.upper() in ("OFF", "FALSE", "0"):
159 raise ValueError(str(x) + " could not be parsed as a Boolean")
163 def l3str(x: Union[str, List[str]]) -> List[str]:
164 if isinstance(x, str):
168 if len(lx) != 3 or not all(isinstance(el, str) for el in x):
169 raise ValueError(str(lx) + " is not a list of three strings")
175 For each class corresponding to a message, automatically create
176 two nested classes `In` and `Out` that also inherit from their
177 "nest". Class attribute `IN_KWARGS` defined in the "nest" is
178 copied to the `In` nested class under the name `KWARGS`, and
179 likewise, `OUT_KWARGS` of the nest class is copied as `KWARGS`
180 to the nested class `Out`. In addition, method `encode` is
181 defined in both classes equal to `in_encode()` and `out_encode()`
187 def __getattr__(self, name: str) -> Any:
190 def __setattr__(self, name: str, value: Any) -> None:
194 cls: Type["MetaPkt"],
196 bases: Tuple[type, ...],
197 attrs: Dict[str, Any],
199 newcls = super().__new__(cls, name, bases, attrs)
200 newcls.In = super().__new__(
205 "KWARGS": newcls.IN_KWARGS,
206 "decode": newcls.in_decode,
207 "encode": newcls.in_encode,
210 newcls.Out = super().__new__(
215 "KWARGS": newcls.OUT_KWARGS,
216 "decode": newcls.out_decode,
217 "encode": newcls.out_encode,
224 NON = 0 # Incoming, no response needed
225 INL = 1 # Birirectional, use `inline_response()`
226 EXT = 2 # Birirectional, use external responder
229 class BeeSurePkt(metaclass=MetaPkt):
230 RESPOND = Respond.NON # Do not send anything back by default
231 IN_KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = ()
232 OUT_KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = ()
233 KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = ()
234 In: Type["BeeSurePkt"]
235 Out: Type["BeeSurePkt"]
239 def __getattr__(self, name: str) -> Any:
242 def __setattr__(self, name: str, value: Any) -> None:
245 def __init__(self, *args: Any, **kwargs: Any):
247 Construct the object _either_ from (length, payload),
248 _or_ from the values of individual fields
250 assert not args or (len(args) == 4 and not kwargs)
251 if args: # guaranteed to be two arguments at this point
252 self.vendor, self.imei, self.datalength, self.payload = args
254 self.decode(*self.payload)
256 raise DecodeError(e, obj=self)
258 for kw, typ, dfl in self.KWARGS:
259 setattr(self, kw, typ(kwargs.pop(kw, dfl)))
262 self.__class__.__name__ + " stray kwargs " + str(kwargs)
265 def __repr__(self) -> str:
266 return "{}({})".format(
267 self.__class__.__name__,
271 'bytes.fromhex("{}")'.format(v.hex())
272 if isinstance(v, bytes)
275 for k, v in self.__dict__.items()
276 if not k.startswith("_")
280 def decode(self, *args: str) -> None:
283 def in_decode(self, *args: str) -> None:
284 # Overridden in subclasses, otherwise do not decode payload
287 def out_decode(self, *args: str) -> None:
288 # Overridden in subclasses, otherwise do not decode payload
291 def encode(self) -> str:
294 def in_encode(self) -> str:
295 # Necessary to emulate terminal, which is not implemented
296 raise NotImplementedError(
297 self.__class__.__name__ + ".encode() not implemented"
300 def out_encode(self) -> str:
301 # Overridden in subclasses, otherwise command verb only
305 def PROTO(self) -> str:
307 proto, _ = self.__class__.__name__.split(".")
309 proto = self.__class__.__name__
313 def packed(self) -> bytes:
315 payload = self.PROTO + "," + data if data else self.PROTO
316 return f"[LT*0000000000*{len(payload):04X}*{payload}]".encode()
319 class UNKNOWN(BeeSurePkt):
323 class LK(BeeSurePkt):
324 RESPOND = Respond.INL
326 def in_decode(self, *args: str) -> None:
331 self.tumbling_number = args[2]
333 self.battery_percentage = args[3]
335 def in_encode(self) -> str:
339 class CONFIG(BeeSurePkt):
343 class ICCID(BeeSurePkt):
347 class _LOC_DATA(BeeSurePkt):
348 def in_decode(self, *args: str) -> None:
349 p = SimpleNamespace()
351 for (obj, attr, func), val in zip(
356 (self, "gps_valid", lambda x: x == "A"),
358 (p, "nors", lambda x: 1 if x == "N" else -1),
360 (p, "eorw", lambda x: 1 if x == "E" else -1),
361 (self, "speed", float),
362 (self, "direction", float),
363 (self, "altitude", float),
364 (self, "num_of_sats", int),
365 (self, "gsm_strength_percentage", int),
366 (self, "battery_percentage", int),
367 (self, "pedometer", int),
368 (self, "tubmling_times", int),
369 (self, "device_status", lambda x: int(x, 16)),
370 (self, "base_stations_number", int),
371 (self, "connect_base_station_number", int),
377 setattr(obj, attr, func(val)) # type: ignore
378 rest_args = args[21:]
379 # (area_id, cell_id, strength)*
380 self.base_stations = [
381 tuple(int(el) for el in rest_args[i * 3 : 3 + i * 3])
382 for i in range(self.base_stations_number)
384 rest_args = rest_args[3 * self.base_stations_number :]
385 self.wifi_aps_number = int(rest_args[0])
386 # (SSID, MAC, strength)*
389 rest_args[1 + i * 3],
390 rest_args[2 + i * 3],
391 int(rest_args[3 + i * 3]),
393 for i in range(self.wifi_aps_number)
395 rest_args = rest_args[1 + 3 * self.wifi_aps_number :]
396 self.positioning_accuracy = float(rest_args[0])
402 # .replace(tzinfo=timezone.utc)
403 # .astimezone(tz=timezone.utc)
405 self.latitude = p.lat * p.nors
406 self.longitude = p.lon * p.eorw
413 class UD2(_LOC_DATA):
417 class TKQ(BeeSurePkt):
418 RESPOND = Respond.INL
421 class TKQ2(BeeSurePkt):
422 RESPOND = Respond.INL
426 RESPOND = Respond.INL
429 class CR(BeeSurePkt):
433 class FLOWER(BeeSurePkt):
434 OUT_KWARGS = (("number", int, 1),)
436 def out_encode(self) -> str:
438 return str(self.number)
441 class POWEROFF(BeeSurePkt):
445 class RESET(BeeSurePkt):
449 class SOS(BeeSurePkt):
450 OUT_KWARGS = (("phonenumbers", l3str, ["", "", ""]),)
452 def out_encode(self) -> str:
453 self.phonenumbers: List[str]
454 return ",".join(self.phonenumbers)
457 class _SET_PHONE(BeeSurePkt):
458 OUT_KWARGS = (("phonenumber", str, ""),)
460 def out_encode(self) -> str:
461 self.phonenumber: str
462 return self.phonenumber
465 class SOS1(_SET_PHONE):
469 class SOS2(_SET_PHONE):
473 class SOS3(_SET_PHONE):
477 # Build dicts protocol number -> class and class name -> protocol number
479 if True: # just to indent the code, sorry!
482 for name, cls in globals().items()
484 and issubclass(cls, BeeSurePkt)
485 and not name.startswith("_")
487 CLASSES[cls.__name__] = cls
492 ) -> Union[Type[BeeSurePkt], List[str]]:
493 if prefix.startswith(PROTO_PREFIX):
494 pname = prefix[len(PROTO_PREFIX) :].upper()
496 raise KeyError(pname)
497 lst = [name for name in CLASSES.keys() if name.upper().startswith(pname)]
499 if len(lst) == 1: # unique prefix match
500 return CLASSES[proto]
501 if proto == pname: # exact match
502 return CLASSES[proto]
506 def proto_handled(proto: str) -> bool:
507 return proto.startswith(PROTO_PREFIX)
510 def proto_name(obj: Union[MetaPkt, BeeSurePkt]) -> str:
511 return PROTO_PREFIX + (
512 obj.__class__.__name__ if isinstance(obj, BeeSurePkt) else obj.__name__
516 def proto_of_message(packet: bytes) -> str:
517 return PROTO_PREFIX + packet[20:-1].split(b",")[0].decode()
520 def imei_from_packet(packet: bytes) -> Optional[str]:
521 toskip, _, imei, _ = _framestart(packet)
522 if toskip == 0 and imei != "":
527 def is_goodbye_packet(packet: bytes) -> bool:
531 def inline_response(packet: bytes) -> Optional[bytes]:
532 proto = packet[20:-1].split(b",")[0].decode()
535 if cls.RESPOND is Respond.INL:
536 return cls.Out().packed
540 def probe_buffer(buffer: bytes) -> bool:
541 return bool(RE.search(buffer))
544 def parse_message(packet: bytes, is_incoming: bool = True) -> BeeSurePkt:
545 """From a packet (without framing bytes) derive the XXX.In object"""
546 toskip, vendor, imei, datalength = _framestart(packet)
547 payload = packet[20:-1].decode().split(",")
548 proto = payload[0] if len(payload) > 0 else ""
549 if proto not in CLASSES:
550 cause: Union[DecodeError, ValueError, IndexError] = ValueError(
551 f"Proto {proto} is unknown"
556 return CLASSES[proto].In(vendor, imei, datalength, payload)
558 return CLASSES[proto].Out(vendor, imei, datalength, payload)
559 except (DecodeError, ValueError, IndexError) as e:
562 retobj = UNKNOWN.In(vendor, imei, datalength, payload)
564 retobj = UNKNOWN.Out(vendor, imei, datalength, payload)
565 retobj.proto = proto # Override class attr with object attr