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 MAXBUFFER: int = 65557 # Theoretical max buffer 65536 + 21
47 RE = re.compile(b"\[(\w\w)\*(\d{10})\*([0-9a-fA-F]{4})\*")
50 def _framestart(buffer: bytes) -> Tuple[int, str, str, int]:
52 Find the start of the frame in the buffer.
53 If found, return (offset, vendorId, imei, datalen) tuple.
54 If not found, set -1 as the value of `offset`
56 mo = RE.search(buffer)
70 def __init__(self) -> None:
72 self.imei: Optional[str] = None
75 def recv(self, segment: bytes) -> List[Union[bytes, str]]:
77 Process next segment of the stream. Return successfully deframed
78 packets as `bytes` and error messages as `str`.
81 self.buffer += segment
82 if len(self.buffer) > MAXBUFFER:
83 # We are receiving junk. Let's drop it or we run out of memory.
85 return [f"More than {MAXBUFFER} unparseable data, dropping"]
86 msgs: List[Union[bytes, str]] = []
88 if not self.datalen: # we have not seen packet start yet
89 toskip, _, imei, datalen = _framestart(self.buffer)
90 if toskip < 0: # No frames, continue reading
92 if toskip > 0: # Should not happen, report
94 f"Skipping {toskip} bytes of undecodable data"
95 f' "{self.buffer[:toskip][:64]=!r}"'
97 self.buffer = self.buffer[toskip:]
98 # From this point, buffer starts with a packet header
101 if self.imei != imei:
103 f"Packet's imei {imei} mismatches"
104 f" previous value {self.imei}, old value kept"
106 self.datalen = datalen
107 if len(self.buffer) < self.datalen + 21: # Incomplete packet
109 # At least one complete packet is present in the buffer
110 if chr(self.buffer[self.datalen + 20]) == "]":
111 msgs.append(self.buffer[: self.datalen + 21])
114 f"Packet does not end with ']'"
115 f" at {self.datalen+20}: {self.buffer=!r}"
117 self.buffer = self.buffer[self.datalen + 21 :]
121 def close(self) -> bytes:
129 def enframe(buffer: bytes, imei: Optional[str] = None) -> bytes:
130 assert imei is not None and len(imei) == 10
131 off, vid, _, dlen = _framestart(buffer)
133 return f"[{vid:2s}*{imei:10s}*{dlen:04X}*".encode() + buffer[20:]
136 ### Parser/Constructor ###
139 class DecodeError(Exception):
140 def __init__(self, e: Exception, **kwargs: Any) -> None:
142 for k, v in kwargs.items():
146 def maybe(typ: type) -> Callable[[Any], Any]:
147 return lambda x: None if x is None else typ(x)
150 def intx(x: Union[str, int]) -> int:
151 if isinstance(x, str):
156 def boolx(x: Union[str, bool]) -> bool:
157 if isinstance(x, str):
158 if x.upper() in ("ON", "TRUE", "1"):
160 if x.upper() in ("OFF", "FALSE", "0"):
162 raise ValueError(str(x) + " could not be parsed as a Boolean")
166 def l3str(x: Union[str, List[str]]) -> List[str]:
167 if isinstance(x, str):
171 if len(lx) != 3 or not all(isinstance(el, str) for el in x):
172 raise ValueError(str(lx) + " is not a list of three strings")
176 def pblist(x: Union[str, List[Tuple[str, str]]]) -> List[Tuple[str, str]]:
177 if isinstance(x, str):
179 def splitpair(s: str) -> Tuple[str, str]:
183 lx = [splitpair(el) for el in x.split(",")]
187 raise ValueError(str(lx) + " has too many elements (max 5)")
192 NON = 0 # Incoming, no response needed
193 INL = 1 # Birirectional, use `inline_response()`
194 EXT = 2 # Birirectional, use external responder
197 class BeeSurePkt(ProtoClass):
198 RESPOND = Respond.NON # Do not send anything back by default
199 IN_KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = ()
200 OUT_KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = ()
201 KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = ()
202 In: Type["BeeSurePkt"]
203 Out: Type["BeeSurePkt"]
207 def __getattr__(self, name: str) -> Any:
210 def __setattr__(self, name: str, value: Any) -> None:
213 def __init__(self, *args: Any, **kwargs: Any):
215 Construct the object _either_ from (length, payload),
216 _or_ from the values of individual fields
218 self.payload: Union[List[str], bytes]
219 assert not args or (len(args) == 4 and not kwargs)
220 if args: # guaranteed to be two arguments at this point
221 self.vendor, self.imei, self.datalength, self.payload = args
223 if isinstance(self.payload, list):
224 self.decode(*self.payload)
226 self.decode(self.payload)
228 raise DecodeError(e, obj=self)
230 for kw, typ, dfl in self.KWARGS:
231 setattr(self, kw, typ(kwargs.pop(kw, dfl)))
234 self.__class__.__name__ + " stray kwargs " + str(kwargs)
237 def __repr__(self) -> str:
238 return "{}({})".format(
239 self.__class__.__name__,
243 'bytes.fromhex("{}")'.format(v.hex())
244 if isinstance(v, bytes)
247 for k, v in self.__dict__.items()
248 if not k.startswith("_")
252 def decode(self, *args: Any) -> None:
255 def in_decode(self, *args: str) -> None:
256 # Overridden in subclasses, otherwise do not decode payload
259 def out_decode(self, *args: str) -> None:
260 # Overridden in subclasses, otherwise do not decode payload
263 def encode(self) -> str:
266 def in_encode(self) -> str:
267 # Necessary to emulate terminal, which is not implemented
268 raise NotImplementedError(
269 self.__class__.__name__ + ".encode() not implemented"
272 def out_encode(self) -> str:
273 # Overridden in subclasses, otherwise command verb only
277 def PROTO(self) -> str:
279 proto, _ = self.__class__.__name__.split(".")
281 proto = self.__class__.__name__
285 def packed(self) -> bytes:
287 payload = self.PROTO + "," + data if data else self.PROTO
288 return f"[LT*0000000000*{len(payload):04X}*{payload}]".encode()
291 class UNKNOWN(BeeSurePkt):
295 class _LOC_DATA(BeeSurePkt):
296 def in_decode(self, *args: str) -> None:
297 p = SimpleNamespace()
299 for (obj, attr, func), val in zip(
303 (self, "gps_valid", lambda x: x == "A"),
305 (p, "nors", lambda x: 1 if x == "N" else -1),
307 (p, "eorw", lambda x: 1 if x == "E" else -1),
308 (self, "speed", float),
309 (self, "direction", float),
310 (self, "altitude", float),
311 (self, "num_of_sats", int),
312 (self, "gsm_strength_percentage", int),
313 (self, "battery_percentage", int),
314 (self, "pedometer", int),
315 (self, "tubmling_times", int),
316 (self, "device_status", lambda x: int(x, 16)),
317 (self, "base_stations_number", int),
318 (self, "connect_base_station_number", int),
324 setattr(obj, attr, func(val)) # type: ignore
325 rest_args = args[20:]
326 # (area_id, cell_id, strength)*
327 self.base_stations = [
328 tuple(int(el) for el in rest_args[i * 3 : 3 + i * 3])
329 for i in range(self.base_stations_number)
331 rest_args = rest_args[3 * self.base_stations_number :]
332 self.wifi_aps_number = int(rest_args[0])
333 # (SSID, MAC, strength)*
336 rest_args[1 + i * 3],
337 rest_args[2 + i * 3],
338 int(rest_args[3 + i * 3]),
340 for i in range(self.wifi_aps_number)
342 rest_args = rest_args[1 + 3 * self.wifi_aps_number :]
343 self.positioning_accuracy = float(rest_args[0])
349 # .replace(tzinfo=timezone.utc)
350 # .astimezone(tz=timezone.utc)
352 self.latitude = p.lat * p.nors
353 self.longitude = p.lon * p.eorw
357 RESPOND = Respond.INL
360 class CONFIG(BeeSurePkt):
364 class CR(BeeSurePkt):
368 class FLOWER(BeeSurePkt):
369 OUT_KWARGS = (("number", int, 1),)
371 def out_encode(self) -> str:
373 return str(self.number)
376 class ICCID(BeeSurePkt):
380 class LK(BeeSurePkt):
381 RESPOND = Respond.INL
383 def in_decode(self, *args: str) -> None:
388 self.tumbling_number = args[1]
390 self.battery_percentage = args[2]
392 def in_encode(self) -> str:
396 class MESSAGE(BeeSurePkt):
397 OUT_KWARGS = (("message", str, ""),)
399 def out_encode(self) -> str:
400 return str(self.message.encode("utf_16_be").hex())
403 class _PHB(BeeSurePkt):
404 OUT_KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = (
405 ("entries", pblist, []),
408 def out_encode(self) -> str:
409 self.entries: List[Tuple[str, str]]
412 ",".join((num, name.encode("utf_16_be").hex()))
413 for name, num in self.entries
426 class POWEROFF(BeeSurePkt):
430 class RESET(BeeSurePkt):
434 class SOS(BeeSurePkt):
435 OUT_KWARGS = (("phonenumbers", l3str, ["", "", ""]),)
437 def out_encode(self) -> str:
438 self.phonenumbers: List[str]
439 return ",".join(self.phonenumbers)
442 class _SET_PHONE(BeeSurePkt):
443 OUT_KWARGS = (("phonenumber", str, ""),)
445 def out_encode(self) -> str:
446 self.phonenumber: str
447 return self.phonenumber
450 class SOS1(_SET_PHONE):
454 class SOS2(_SET_PHONE):
458 class SOS3(_SET_PHONE):
462 class TK(BeeSurePkt):
463 RESPOND = Respond.INL
465 def in_decode(self, *args: Any) -> None:
466 assert len(args) == 1 and isinstance(args[0], bytes)
469 .replace(b"}*", b"*")
470 .replace(b"},", b",")
471 .replace(b"}[", b"[")
472 .replace(b"}]", b"]")
473 .replace(b"}}", b"}")
476 def out_encode(self) -> str:
477 return "1" # 0 - receive failure, 1 - receive success
480 class TKQ(BeeSurePkt):
481 RESPOND = Respond.INL
484 class TKQ2(BeeSurePkt):
485 RESPOND = Respond.INL
492 class UD2(_LOC_DATA):
496 # Build dicts protocol number -> class and class name -> protocol number
498 if True: # just to indent the code, sorry!
501 for name, cls in globals().items()
503 and issubclass(cls, BeeSurePkt)
504 and not name.startswith("_")
506 CLASSES[cls.__name__] = cls
511 ) -> Union[Type[BeeSurePkt], List[str]]:
512 if prefix.startswith(PROTO_PREFIX):
513 pname = prefix[len(PROTO_PREFIX) :].upper()
515 raise KeyError(pname)
516 lst = [name for name in CLASSES.keys() if name.upper().startswith(pname)]
518 if len(lst) == 1: # unique prefix match
519 return CLASSES[proto]
520 if proto == pname: # exact match
521 return CLASSES[proto]
525 def proto_handled(proto: str) -> bool:
526 return proto.startswith(PROTO_PREFIX)
529 def proto_name(obj: Union[Type[BeeSurePkt], BeeSurePkt]) -> str:
530 return PROTO_PREFIX + (
531 obj.__class__.__name__ if isinstance(obj, BeeSurePkt) else obj.__name__
535 def proto_of_message(packet: bytes) -> str:
536 return PROTO_PREFIX + packet[20:-1].split(b",")[0].decode()
539 def imei_from_packet(packet: bytes) -> Optional[str]:
540 toskip, _, imei, _ = _framestart(packet)
541 if toskip == 0 and imei != "":
546 def is_goodbye_packet(packet: bytes) -> bool:
550 def inline_response(packet: bytes) -> Optional[bytes]:
551 proto = packet[20:-1].split(b",")[0].decode()
554 if cls.RESPOND is Respond.INL:
555 return cls.Out().packed
559 def probe_buffer(buffer: bytes) -> bool:
560 return bool(RE.search(buffer))
563 def parse_message(packet: bytes, is_incoming: bool = True) -> BeeSurePkt:
564 """From a packet (without framing bytes) derive the XXX.In object"""
565 toskip, vendor, imei, datalength = _framestart(packet)
567 splits = packet[20:-1].decode().split(",")
568 proto = splits[0] if len(splits) > 0 else ""
569 payload: Union[List[str], bytes] = splits[1:]
570 except UnicodeDecodeError:
571 bsplits = packet[20:-1].split(b",", 1)
572 if len(bsplits) == 2:
573 proto = bsplits[0].decode("ascii")
575 if proto not in CLASSES:
576 cause: Union[DecodeError, ValueError, IndexError] = ValueError(
577 f"Proto {proto} is unknown"
582 return CLASSES[proto].In(vendor, imei, datalength, payload)
584 return CLASSES[proto].Out(vendor, imei, datalength, payload)
585 except (DecodeError, ValueError, IndexError) as e:
588 retobj = UNKNOWN.In(vendor, imei, datalength, payload)
590 retobj = UNKNOWN.Out(vendor, imei, datalength, payload)
591 retobj.proto = proto # Override class attr with object attr
596 def exposed_protos() -> List[Tuple[str, bool]]:
598 (proto_name(UD), True),
599 (proto_name(UD2), False),