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
25 from .protomodule import ProtoClass
45 MAXBUFFER: int = 65557 # Theoretical max buffer 65536 + 21
46 RE = re.compile(b"\[(\w\w)\*(\d{10})\*([0-9a-fA-F]{4})\*")
49 def _framestart(buffer: bytes) -> Tuple[int, str, str, int]:
51 Find the start of the frame in the buffer.
52 If found, return (offset, vendorId, imei, datalen) tuple.
53 If not found, set -1 as the value of `offset`
55 mo = RE.search(buffer)
69 def __init__(self) -> None:
71 self.imei: Optional[str] = None
74 def recv(self, segment: bytes) -> List[Union[bytes, str]]:
76 Process next segment of the stream. Return successfully deframed
77 packets as `bytes` and error messages as `str`.
80 self.buffer += segment
81 if len(self.buffer) > MAXBUFFER:
82 # We are receiving junk. Let's drop it or we run out of memory.
84 return [f"More than {MAXBUFFER} unparseable data, dropping"]
85 msgs: List[Union[bytes, str]] = []
87 if not self.datalen: # we have not seen packet start yet
88 toskip, _, imei, datalen = _framestart(self.buffer)
89 if toskip < 0: # No frames, continue reading
91 if toskip > 0: # Should not happen, report
93 f"Skipping {toskip} bytes of undecodable data"
94 f' "{self.buffer[:toskip][:64]=!r}"'
96 self.buffer = self.buffer[toskip:]
97 # From this point, buffer starts with a packet header
100 if self.imei != imei:
102 f"Packet's imei {imei} mismatches"
103 f" previous value {self.imei}, old value kept"
105 self.datalen = datalen
106 if len(self.buffer) < self.datalen + 21: # Incomplete packet
108 # At least one complete packet is present in the buffer
109 if chr(self.buffer[self.datalen + 20]) == "]":
110 msgs.append(self.buffer[: self.datalen + 21])
113 f"Packet does not end with ']'"
114 f" at {self.datalen+20}: {self.buffer=!r}"
116 self.buffer = self.buffer[self.datalen + 21 :]
120 def close(self) -> bytes:
128 def enframe(buffer: bytes, imei: Optional[str] = None) -> bytes:
129 assert imei is not None and len(imei) == 10
130 off, vid, _, dlen = _framestart(buffer)
132 return f"[{vid:2s}*{imei:10s}*{dlen:04X}*".encode() + buffer[20:]
135 ### Parser/Constructor ###
138 class DecodeError(Exception):
139 def __init__(self, e: Exception, **kwargs: Any) -> None:
141 for k, v in kwargs.items():
145 def maybe(typ: type) -> Callable[[Any], Any]:
146 return lambda x: None if x is None else typ(x)
149 def intx(x: Union[str, int]) -> int:
150 if isinstance(x, str):
155 def boolx(x: Union[str, bool]) -> bool:
156 if isinstance(x, str):
157 if x.upper() in ("ON", "TRUE", "1"):
159 if x.upper() in ("OFF", "FALSE", "0"):
161 raise ValueError(str(x) + " could not be parsed as a Boolean")
165 def l3str(x: Union[str, List[str]]) -> List[str]:
166 if isinstance(x, str):
170 if len(lx) != 3 or not all(isinstance(el, str) for el in x):
171 raise ValueError(str(lx) + " is not a list of three strings")
175 def pblist(x: Union[str, List[Tuple[str, str]]]) -> List[Tuple[str, str]]:
176 if isinstance(x, str):
178 def splitpair(s: str) -> Tuple[str, str]:
182 lx = [splitpair(el) for el in x.split(",")]
186 raise ValueError(str(lx) + " has too many elements (max 5)")
191 NON = 0 # Incoming, no response needed
192 INL = 1 # Birirectional, use `inline_response()`
193 EXT = 2 # Birirectional, use external responder
196 class BeeSurePkt(ProtoClass):
197 RESPOND = Respond.NON # Do not send anything back by default
198 IN_KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = ()
199 OUT_KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = ()
200 KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = ()
201 In: Type["BeeSurePkt"]
202 Out: Type["BeeSurePkt"]
206 def __getattr__(self, name: str) -> Any:
209 def __setattr__(self, name: str, value: Any) -> None:
212 def __init__(self, *args: Any, **kwargs: Any):
214 Construct the object _either_ from (length, payload),
215 _or_ from the values of individual fields
217 self.payload: Union[List[str], bytes]
218 assert not args or (len(args) == 4 and not kwargs)
219 if args: # guaranteed to be two arguments at this point
220 self.vendor, self.imei, self.datalength, self.payload = args
222 if isinstance(self.payload, list):
223 self.decode(*self.payload)
225 self.decode(self.payload)
227 raise DecodeError(e, obj=self)
229 for kw, typ, dfl in self.KWARGS:
230 setattr(self, kw, typ(kwargs.pop(kw, dfl)))
233 self.__class__.__name__ + " stray kwargs " + str(kwargs)
236 def __repr__(self) -> str:
237 return "{}({})".format(
238 self.__class__.__name__,
242 'bytes.fromhex("{}")'.format(v.hex())
243 if isinstance(v, bytes)
246 for k, v in self.__dict__.items()
247 if not k.startswith("_")
251 def decode(self, *args: Any) -> None:
254 def in_decode(self, *args: str) -> None:
255 # Overridden in subclasses, otherwise do not decode payload
258 def out_decode(self, *args: str) -> None:
259 # Overridden in subclasses, otherwise do not decode payload
262 def encode(self) -> str:
265 def in_encode(self) -> str:
266 # Necessary to emulate terminal, which is not implemented
267 raise NotImplementedError(
268 self.__class__.__name__ + ".encode() not implemented"
271 def out_encode(self) -> str:
272 # Overridden in subclasses, otherwise command verb only
276 def PROTO(self) -> str:
278 proto, _ = self.__class__.__name__.split(".")
280 proto = self.__class__.__name__
284 def packed(self) -> bytes:
286 payload = self.PROTO + "," + data if data else self.PROTO
287 return f"[LT*0000000000*{len(payload):04X}*{payload}]".encode()
290 class UNKNOWN(BeeSurePkt):
294 class _LOC_DATA(BeeSurePkt):
295 def in_decode(self, *args: str) -> None:
296 p = SimpleNamespace()
298 for (obj, attr, func), val in zip(
302 (self, "gps_valid", lambda x: x == "A"),
304 (p, "nors", lambda x: 1 if x == "N" else -1),
306 (p, "eorw", lambda x: 1 if x == "E" else -1),
307 (self, "speed", float),
308 (self, "direction", float),
309 (self, "altitude", float),
310 (self, "num_of_sats", int),
311 (self, "gsm_strength_percentage", int),
312 (self, "battery_percentage", int),
313 (self, "pedometer", int),
314 (self, "tubmling_times", int),
315 (self, "device_status", lambda x: int(x, 16)),
316 (self, "base_stations_number", int),
317 (self, "connect_base_station_number", int),
323 setattr(obj, attr, func(val)) # type: ignore
324 rest_args = args[20:]
325 # (area_id, cell_id, strength)*
326 self.base_stations = [
327 tuple(int(el) for el in rest_args[i * 3 : 3 + i * 3])
328 for i in range(self.base_stations_number)
330 rest_args = rest_args[3 * self.base_stations_number :]
331 self.wifi_aps_number = int(rest_args[0])
332 # (SSID, MAC, strength)*
335 rest_args[1 + i * 3],
336 rest_args[2 + i * 3],
337 int(rest_args[3 + i * 3]),
339 for i in range(self.wifi_aps_number)
341 rest_args = rest_args[1 + 3 * self.wifi_aps_number :]
342 self.positioning_accuracy = float(rest_args[0])
348 # .replace(tzinfo=timezone.utc)
349 # .astimezone(tz=timezone.utc)
351 self.latitude = p.lat * p.nors
352 self.longitude = p.lon * p.eorw
354 def rectified(self) -> Dict[str, Any]: # JSON-able dict
358 "devtime": str(self.devtime),
359 "battery_percentage": self.battery_percentage,
360 "accuracy": self.positioning_accuracy,
361 "altitude": self.altitude,
363 "direction": self.direction,
364 "latitude": self.latitude,
365 "longitude": self.longitude,
369 "type": "approximate_location",
370 "devtime": str(self.devtime),
371 "battery_percentage": self.battery_percentage,
374 "base_stations": self.base_stations,
375 "wifi_aps": self.wifi_aps,
380 RESPOND = Respond.INL
383 class CONFIG(BeeSurePkt):
387 class CR(BeeSurePkt):
391 class FLOWER(BeeSurePkt):
392 OUT_KWARGS = (("number", int, 1),)
394 def out_encode(self) -> str:
396 return str(self.number)
399 class ICCID(BeeSurePkt):
403 class LK(BeeSurePkt):
404 RESPOND = Respond.INL
406 def in_decode(self, *args: str) -> None:
411 self.tumbling_number = args[1]
413 self.battery_percentage = args[2]
415 def in_encode(self) -> str:
419 class MESSAGE(BeeSurePkt):
420 OUT_KWARGS = (("message", str, ""),)
422 def out_encode(self) -> str:
423 return str(self.message.encode("utf_16_be").hex())
426 class _PHB(BeeSurePkt):
427 OUT_KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = (
428 ("entries", pblist, []),
431 def out_encode(self) -> str:
432 self.entries: List[Tuple[str, str]]
435 ",".join((num, name.encode("utf_16_be").hex()))
436 for name, num in self.entries
449 class POWEROFF(BeeSurePkt):
453 class RESET(BeeSurePkt):
457 class SOS(BeeSurePkt):
458 OUT_KWARGS = (("phonenumbers", l3str, ["", "", ""]),)
460 def out_encode(self) -> str:
461 self.phonenumbers: List[str]
462 return ",".join(self.phonenumbers)
465 class _SET_PHONE(BeeSurePkt):
466 OUT_KWARGS = (("phonenumber", str, ""),)
468 def out_encode(self) -> str:
469 self.phonenumber: str
470 return self.phonenumber
473 class SOS1(_SET_PHONE):
477 class SOS2(_SET_PHONE):
481 class SOS3(_SET_PHONE):
485 class TK(BeeSurePkt):
486 RESPOND = Respond.INL
488 def in_decode(self, *args: Any) -> None:
489 assert len(args) == 1 and isinstance(args[0], bytes)
492 .replace(b"}*", b"*")
493 .replace(b"},", b",")
494 .replace(b"}[", b"[")
495 .replace(b"}]", b"]")
496 .replace(b"}}", b"}")
499 def out_encode(self) -> str:
500 return "1" # 0 - receive failure, 1 - receive success
503 class TKQ(BeeSurePkt):
504 RESPOND = Respond.INL
507 class TKQ2(BeeSurePkt):
508 RESPOND = Respond.INL
515 class UD2(_LOC_DATA):
519 # Build dicts protocol number -> class and class name -> protocol number
521 if True: # just to indent the code, sorry!
524 for name, cls in globals().items()
526 and issubclass(cls, BeeSurePkt)
527 and not name.startswith("_")
529 CLASSES[cls.__name__] = cls
534 ) -> Union[Type[BeeSurePkt], List[str]]:
535 if prefix.startswith(PROTO_PREFIX):
536 pname = prefix[len(PROTO_PREFIX) :].upper()
538 raise KeyError(pname)
539 lst = [name for name in CLASSES.keys() if name.upper().startswith(pname)]
541 if len(lst) == 1: # unique prefix match
542 return CLASSES[proto]
543 if proto == pname: # exact match
544 return CLASSES[proto]
548 def proto_handled(proto: str) -> bool:
549 return proto.startswith(PROTO_PREFIX)
552 def proto_name(obj: Union[Type[BeeSurePkt], BeeSurePkt]) -> str:
553 return PROTO_PREFIX + (
554 obj.__class__.__name__ if isinstance(obj, BeeSurePkt) else obj.__name__
558 def proto_of_message(packet: bytes) -> str:
559 return PROTO_PREFIX + packet[20:-1].split(b",")[0].decode()
562 def imei_from_packet(packet: bytes) -> Optional[str]:
563 toskip, _, imei, _ = _framestart(packet)
564 if toskip == 0 and imei != "":
569 def is_goodbye_packet(packet: bytes) -> bool:
573 def inline_response(packet: bytes) -> Optional[bytes]:
574 proto = packet[20:-1].split(b",")[0].decode()
577 if cls.RESPOND is Respond.INL:
578 return cls.Out().packed
582 def probe_buffer(buffer: bytes) -> bool:
583 return bool(RE.search(buffer))
586 def parse_message(packet: bytes, is_incoming: bool = True) -> BeeSurePkt:
587 """From a packet (without framing bytes) derive the XXX.In object"""
588 toskip, vendor, imei, datalength = _framestart(packet)
590 splits = packet[20:-1].decode().split(",")
591 proto = splits[0] if len(splits) > 0 else ""
592 payload: Union[List[str], bytes] = splits[1:]
593 except UnicodeDecodeError:
594 bsplits = packet[20:-1].split(b",", 1)
595 if len(bsplits) == 2:
596 proto = bsplits[0].decode("ascii")
598 if proto not in CLASSES:
599 cause: Union[DecodeError, ValueError, IndexError] = ValueError(
600 f"Proto {proto} is unknown"
605 return CLASSES[proto].In(vendor, imei, datalength, payload)
607 return CLASSES[proto].Out(vendor, imei, datalength, payload)
608 except (DecodeError, ValueError, IndexError) as e:
611 retobj = UNKNOWN.In(vendor, imei, datalength, payload)
613 retobj = UNKNOWN.Out(vendor, imei, datalength, payload)
614 retobj.proto = proto # Override class attr with object attr
619 def exposed_protos() -> List[Tuple[str, bool]]:
621 (proto_name(cls), False)
622 for cls in CLASSES.values()
623 if hasattr(cls, "rectified")