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
46 PMODNAME = __name__.split(".")[-1]
51 MAXBUFFER: int = 65557 # Theoretical max buffer 65536 + 21
52 RE = re.compile(b"\[(\w\w)\*(\d{10})\*([0-9a-fA-F]{4})\*")
55 def _framestart(buffer: bytes) -> Tuple[int, str, str, int]:
57 Find the start of the frame in the buffer.
58 If found, return (offset, vendorId, imei, datalen) tuple.
59 If not found, set -1 as the value of `offset`
61 mo = RE.search(buffer)
75 def __init__(self) -> None:
77 self.imei: Optional[str] = None
80 def recv(self, segment: bytes) -> List[Union[bytes, str]]:
82 Process next segment of the stream. Return successfully deframed
83 packets as `bytes` and error messages as `str`.
86 self.buffer += segment
87 if len(self.buffer) > MAXBUFFER:
88 # We are receiving junk. Let's drop it or we run out of memory.
90 return [f"More than {MAXBUFFER} unparseable data, dropping"]
91 msgs: List[Union[bytes, str]] = []
93 if not self.datalen: # we have not seen packet start yet
94 toskip, _, imei, datalen = _framestart(self.buffer)
95 if toskip < 0: # No frames, continue reading
97 if toskip > 0: # Should not happen, report
99 f"Skipping {toskip} bytes of undecodable data"
100 f' "{self.buffer[:toskip][:64]=!r}"'
102 self.buffer = self.buffer[toskip:]
103 # From this point, buffer starts with a packet header
104 if self.imei is None:
106 if self.imei != imei:
108 f"Packet's imei {imei} mismatches"
109 f" previous value {self.imei}, old value kept"
111 self.datalen = datalen
112 if len(self.buffer) < self.datalen + 21: # Incomplete packet
114 # At least one complete packet is present in the buffer
115 if chr(self.buffer[self.datalen + 20]) == "]":
116 msgs.append(self.buffer[: self.datalen + 21])
119 f"Packet does not end with ']'"
120 f" at {self.datalen+20}: {self.buffer[:64]=!r}"
122 self.buffer = self.buffer[self.datalen + 21 :]
126 def close(self) -> bytes:
134 def enframe(buffer: bytes, imei: Optional[str] = None) -> bytes:
135 assert imei is not None and len(imei) == 10
136 off, vid, _, dlen = _framestart(buffer)
138 return f"[{vid:2s}*{imei:10s}*{dlen:04X}*".encode() + buffer[20:]
141 ### Parser/Constructor ###
145 def __init__(self, f: Callable[[Any], str]) -> None:
148 def __get__(self, obj: Any, owner: Any) -> str:
152 class DecodeError(Exception):
153 def __init__(self, e: Exception, **kwargs: Any) -> None:
155 for k, v in kwargs.items():
159 def maybe(typ: type) -> Callable[[Any], Any]:
160 return lambda x: None if x is None else typ(x)
163 def intx(x: Union[str, int]) -> int:
164 if isinstance(x, str):
169 def boolx(x: Union[str, bool]) -> bool:
170 if isinstance(x, str):
171 if x.upper() in ("ON", "TRUE", "1"):
173 if x.upper() in ("OFF", "FALSE", "0"):
175 raise ValueError(str(x) + " could not be parsed as a Boolean")
179 def l3str(x: Union[str, List[str]]) -> List[str]:
180 if isinstance(x, str):
184 if len(lx) != 3 or not all(isinstance(el, str) for el in x):
185 raise ValueError(str(lx) + " is not a list of three strings")
189 def pblist(x: Union[str, List[Tuple[str, str]]]) -> List[Tuple[str, str]]:
190 if isinstance(x, str):
192 def splitpair(s: str) -> Tuple[str, str]:
196 lx = [splitpair(el) for el in x.split(",")]
200 raise ValueError(str(lx) + " has too many elements (max 5)")
205 NON = 0 # Incoming, no response needed
206 INL = 1 # Birirectional, use `inline_response()`
207 EXT = 2 # Birirectional, use external responder
210 class BeeSurePkt(ProtoClass):
212 RESPOND = Respond.NON # Do not send anything back by default
213 IN_KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = ()
214 OUT_KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = ()
215 KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = ()
216 In: Type["BeeSurePkt"]
217 Out: Type["BeeSurePkt"]
221 def __getattr__(self, name: str) -> Any:
224 def __setattr__(self, name: str, value: Any) -> None:
227 def __init__(self, *args: Any, **kwargs: Any):
229 Construct the object _either_ from (length, payload),
230 _or_ from the values of individual fields
232 self.payload: Union[List[str], bytes]
233 assert not args or (len(args) == 4 and not kwargs)
234 if args: # guaranteed to be two arguments at this point
235 self.vendor, self.imei, self.datalength, self.payload = args
237 if isinstance(self.payload, list):
238 self.decode(*self.payload)
240 self.decode(self.payload)
242 raise DecodeError(e, obj=self)
244 for kw, typ, dfl in self.KWARGS:
245 setattr(self, kw, typ(kwargs.pop(kw, dfl)))
248 self.__class__.__name__ + " stray kwargs " + str(kwargs)
251 def __repr__(self) -> str:
252 return "{}({})".format(
253 self.__class__.__name__,
257 'bytes.fromhex("{}")'.format(v.hex())
258 if isinstance(v, bytes)
261 for k, v in self.__dict__.items()
262 if not k.startswith("_")
266 def decode(self, *args: Any) -> None:
269 def in_decode(self, *args: str) -> None:
270 # Overridden in subclasses, otherwise do not decode payload
273 def out_decode(self, *args: str) -> None:
274 # Overridden in subclasses, otherwise do not decode payload
277 def encode(self) -> str:
280 def in_encode(self) -> str:
281 # Necessary to emulate terminal, which is not implemented
282 raise NotImplementedError(
283 self.__class__.__name__ + ".encode() not implemented"
286 def out_encode(self) -> str:
287 # Overridden in subclasses, otherwise command verb only
291 def PROTO(cls: "BeeSurePkt") -> str:
292 """Name of the class without possible .In / .Out suffix"""
295 proto, _ = cls.__name__.split(".")
301 def proto_name(cls) -> str:
302 """Name of the command as used externally"""
303 return PROTO_PREFIX + cls.PROTO[:16]
306 def packed(self) -> bytes:
308 payload = self.PROTO + "," + data if data else self.PROTO
309 return f"[LT*0000000000*{len(payload):04X}*{payload}]".encode()
312 class UNKNOWN(BeeSurePkt):
316 class _SET_PHONE(BeeSurePkt):
317 OUT_KWARGS = (("phonenumber", str, ""),)
319 def out_encode(self) -> str:
320 self.phonenumber: str
321 return self.phonenumber
324 class _LOC_DATA(BeeSurePkt):
325 def in_decode(self, *args: str) -> None:
326 p = SimpleNamespace()
328 for (obj, attr, func), val in zip(
332 (self, "gps_valid", lambda x: x == "A"),
334 (p, "nors", lambda x: 1 if x == "N" else -1),
336 (p, "eorw", lambda x: 1 if x == "E" else -1),
337 (self, "speed", float),
338 (self, "direction", float),
339 (self, "altitude", float),
340 (self, "num_of_sats", int),
341 (self, "gsm_strength_percentage", int),
342 (self, "battery_percentage", int),
343 (self, "pedometer", int),
344 (self, "tubmling_times", int),
345 (self, "device_status", lambda x: int(x, 16)),
346 (self, "gsm_cells_number", int),
347 (self, "connect_base_station_number", int),
353 setattr(obj, attr, func(val)) # type: ignore
354 rest_args = args[20:]
355 # (area_id, cell_id, strength)*
356 self.gsm_cells: List[Tuple[int, int, int]] = [
357 tuple(int(el) for el in rest_args[i * 3 : 3 + i * 3]) # type: ignore
358 for i in range(self.gsm_cells_number)
360 rest_args = rest_args[3 * self.gsm_cells_number :]
361 self.wifi_aps_number = int(rest_args[0])
362 # (SSID, MAC, strength)*
365 rest_args[1 + i * 3],
366 rest_args[2 + i * 3],
367 int(rest_args[3 + i * 3]),
369 for i in range(self.wifi_aps_number)
371 rest_args = rest_args[1 + 3 * self.wifi_aps_number :]
372 self.positioning_accuracy = float(rest_args[0])
378 # .replace(tzinfo=timezone.utc)
379 # .astimezone(tz=timezone.utc)
381 self.latitude = p.lat * p.nors
382 self.longitude = p.lon * p.eorw
384 def rectified(self) -> Report:
385 # self.gps_valid is supposed to mean it, but it does not. Perfectly
386 # good looking coordinates, with ten satellites, still get 'V'.
387 # I suspect that in reality, 'A' means "hint data is absent".
388 if self.gps_valid or self.num_of_sats > 3:
390 devtime=str(self.devtime),
391 battery_percentage=self.battery_percentage,
392 accuracy=self.positioning_accuracy,
393 altitude=self.altitude,
395 direction=self.direction,
396 latitude=self.latitude,
397 longitude=self.longitude,
401 devtime=str(self.devtime),
402 battery_percentage=self.battery_percentage,
405 gsm_cells=self.gsm_cells,
406 wifi_aps=self.wifi_aps,
411 RESPOND = Respond.INL
414 class CALL(_SET_PHONE):
418 class CENTER(_SET_PHONE):
422 class CONFIG(BeeSurePkt):
426 class CR(BeeSurePkt):
430 class FIND(BeeSurePkt):
434 class FLOWER(BeeSurePkt):
435 OUT_KWARGS = (("number", int, 1),)
437 def out_encode(self) -> str:
439 return str(self.number)
442 class ICCID(BeeSurePkt):
446 class LK(BeeSurePkt):
447 RESPOND = Respond.INL
449 def in_decode(self, *args: str) -> None:
454 self.tumbling_number = args[1]
456 self.battery_percentage = args[2]
458 def in_encode(self) -> str:
462 class LZ(BeeSurePkt):
463 OUT_KWARGS = (("language", int, 1), ("timezone", int, 0))
465 def out_encode(self) -> str:
466 return f"{self.language},{self.timezone}"
469 class MESSAGE(BeeSurePkt):
470 OUT_KWARGS = (("message", str, ""),)
472 def out_encode(self) -> str:
473 return str(self.message.encode("utf_16_be").hex())
476 class MONITOR(BeeSurePkt):
480 class _PHB(BeeSurePkt):
481 OUT_KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = (
482 ("entries", pblist, []),
485 def out_encode(self) -> str:
486 self.entries: List[Tuple[str, str]]
489 ",".join((num, name.encode("utf_16_be").hex()))
490 for name, num in self.entries
503 class POWEROFF(BeeSurePkt):
507 class RESET(BeeSurePkt):
511 class SOS(BeeSurePkt):
512 OUT_KWARGS = (("phonenumbers", l3str, ["", "", ""]),)
514 def out_encode(self) -> str:
515 self.phonenumbers: List[str]
516 return ",".join(self.phonenumbers)
519 class SOS1(_SET_PHONE):
523 class SOS2(_SET_PHONE):
527 class SOS3(_SET_PHONE):
531 class TK(BeeSurePkt):
533 RESPOND = Respond.INL
535 def in_decode(self, *args: Any) -> None:
536 assert len(args) == 1 and isinstance(args[0], bytes)
539 .replace(b"}*", b"*")
540 .replace(b"},", b",")
541 .replace(b"}[", b"[")
542 .replace(b"}]", b"]")
543 .replace(b"}}", b"}")
546 def out_encode(self) -> str:
547 return "1" # 0 - receive failure, 1 - receive success
550 class TKQ(BeeSurePkt):
551 RESPOND = Respond.INL
554 class TKQ2(BeeSurePkt):
555 RESPOND = Respond.INL
562 class UD2(_LOC_DATA):
566 class UPLOAD(BeeSurePkt):
567 OUT_KWARGS = (("interval", int, 600),)
569 def out_encode(self) -> str:
570 return str(self.interval)
573 # Build dicts protocol number -> class and class name -> protocol number
575 if True: # just to indent the code, sorry!
578 for name, cls in globals().items()
580 and issubclass(cls, BeeSurePkt)
581 and not name.startswith("_")
583 CLASSES[cls.__name__] = cls
588 ) -> Union[Type[BeeSurePkt], List[str]]:
589 if prefix.startswith(PROTO_PREFIX):
590 pname = prefix[len(PROTO_PREFIX) :].upper()
592 raise KeyError(pname)
593 lst = [name for name in CLASSES.keys() if name.upper().startswith(pname)]
595 if len(lst) == 1: # unique prefix match
596 return CLASSES[proto]
597 if proto == pname: # exact match
598 return CLASSES[proto]
602 def proto_handled(proto: str) -> bool:
603 return proto.startswith(PROTO_PREFIX)
606 def _local_proto(packet: bytes) -> str:
608 return packet[20:-1].split(b",")[0].decode()
609 except UnicodeDecodeError:
613 def proto_of_message(packet: bytes) -> str:
614 return PROTO_PREFIX + _local_proto(packet)
617 def imei_from_packet(packet: bytes) -> Optional[str]:
618 toskip, _, imei, _ = _framestart(packet)
619 if toskip == 0 and imei != "":
624 def is_goodbye_packet(packet: bytes) -> bool:
628 def inline_response(packet: bytes) -> Optional[bytes]:
629 proto = _local_proto(packet)
632 if cls.RESPOND is Respond.INL:
633 return cls.Out().packed
637 def probe_buffer(buffer: bytes) -> bool:
638 return bool(RE.search(buffer))
641 def parse_message(packet: bytes, is_incoming: bool = True) -> BeeSurePkt:
642 """From a packet (without framing bytes) derive the XXX.In object"""
643 toskip, vendor, imei, datalength = _framestart(packet)
644 bsplits = packet[20:-1].split(b",", 1)
646 proto = bsplits[0].decode("ascii")
647 except UnicodeDecodeError:
648 proto = str(bsplits[0])
649 if len(bsplits) == 2:
654 cls = CLASSES[proto].In if is_incoming else CLASSES[proto].Out
656 # Some people encode their SSIDs in non-utf8
659 else rest.decode("Windows-1252").split(",")
662 return cls(vendor, imei, datalength, payload)
663 except (DecodeError, ValueError, IndexError) as e:
664 cause: Union[DecodeError, ValueError, IndexError] = e
667 cause = ValueError(f"Proto {proto} is unknown")
669 retobj = UNKNOWN.In(vendor, imei, datalength, payload)
671 retobj = UNKNOWN.Out(vendor, imei, datalength, payload)
672 retobj.proto = proto # Override class attr with object attr
677 def exposed_protos() -> List[Tuple[str, bool]]:
679 (cls.proto_name(), False)
680 for cls in CLASSES.values()
681 if hasattr(cls, "rectified")
685 def make_response(cmd: str, imei: str, **kwargs: Any) -> Optional[BeeSurePkt]:
686 if cmd == "poweroff":
687 return POWEROFF.Out()
688 elif cmd == "refresh":
690 elif cmd == "message":
691 return MESSAGE.Out(message=kwargs.get("txt", "Hello"))