casambi-bt-revamped 0.3.7.dev4__tar.gz → 0.3.7.dev6__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (24) hide show
  1. {casambi_bt_revamped-0.3.7.dev4/src/casambi_bt_revamped.egg-info → casambi_bt_revamped-0.3.7.dev6}/PKG-INFO +2 -2
  2. {casambi_bt_revamped-0.3.7.dev4 → casambi_bt_revamped-0.3.7.dev6}/README.md +1 -1
  3. {casambi_bt_revamped-0.3.7.dev4 → casambi_bt_revamped-0.3.7.dev6}/setup.cfg +1 -1
  4. {casambi_bt_revamped-0.3.7.dev4 → casambi_bt_revamped-0.3.7.dev6}/src/CasambiBt/_casambi.py +10 -6
  5. {casambi_bt_revamped-0.3.7.dev4 → casambi_bt_revamped-0.3.7.dev6}/src/CasambiBt/_client.py +116 -72
  6. {casambi_bt_revamped-0.3.7.dev4 → casambi_bt_revamped-0.3.7.dev6}/src/CasambiBt/_network.py +0 -1
  7. {casambi_bt_revamped-0.3.7.dev4 → casambi_bt_revamped-0.3.7.dev6}/src/CasambiBt/_unit.py +1 -22
  8. {casambi_bt_revamped-0.3.7.dev4 → casambi_bt_revamped-0.3.7.dev6/src/casambi_bt_revamped.egg-info}/PKG-INFO +2 -2
  9. {casambi_bt_revamped-0.3.7.dev4 → casambi_bt_revamped-0.3.7.dev6}/src/casambi_bt_revamped.egg-info/SOURCES.txt +0 -1
  10. casambi_bt_revamped-0.3.7.dev4/src/CasambiBt/_client_android_parser.py +0 -215
  11. {casambi_bt_revamped-0.3.7.dev4 → casambi_bt_revamped-0.3.7.dev6}/LICENSE +0 -0
  12. {casambi_bt_revamped-0.3.7.dev4 → casambi_bt_revamped-0.3.7.dev6}/pyproject.toml +0 -0
  13. {casambi_bt_revamped-0.3.7.dev4 → casambi_bt_revamped-0.3.7.dev6}/src/CasambiBt/__init__.py +0 -0
  14. {casambi_bt_revamped-0.3.7.dev4 → casambi_bt_revamped-0.3.7.dev6}/src/CasambiBt/_cache.py +0 -0
  15. {casambi_bt_revamped-0.3.7.dev4 → casambi_bt_revamped-0.3.7.dev6}/src/CasambiBt/_constants.py +0 -0
  16. {casambi_bt_revamped-0.3.7.dev4 → casambi_bt_revamped-0.3.7.dev6}/src/CasambiBt/_discover.py +0 -0
  17. {casambi_bt_revamped-0.3.7.dev4 → casambi_bt_revamped-0.3.7.dev6}/src/CasambiBt/_encryption.py +0 -0
  18. {casambi_bt_revamped-0.3.7.dev4 → casambi_bt_revamped-0.3.7.dev6}/src/CasambiBt/_keystore.py +0 -0
  19. {casambi_bt_revamped-0.3.7.dev4 → casambi_bt_revamped-0.3.7.dev6}/src/CasambiBt/_operation.py +0 -0
  20. {casambi_bt_revamped-0.3.7.dev4 → casambi_bt_revamped-0.3.7.dev6}/src/CasambiBt/errors.py +0 -0
  21. {casambi_bt_revamped-0.3.7.dev4 → casambi_bt_revamped-0.3.7.dev6}/src/CasambiBt/py.typed +0 -0
  22. {casambi_bt_revamped-0.3.7.dev4 → casambi_bt_revamped-0.3.7.dev6}/src/casambi_bt_revamped.egg-info/dependency_links.txt +0 -0
  23. {casambi_bt_revamped-0.3.7.dev4 → casambi_bt_revamped-0.3.7.dev6}/src/casambi_bt_revamped.egg-info/requires.txt +0 -0
  24. {casambi_bt_revamped-0.3.7.dev4 → casambi_bt_revamped-0.3.7.dev6}/src/casambi_bt_revamped.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: casambi-bt-revamped
3
- Version: 0.3.7.dev4
3
+ Version: 0.3.7.dev6
4
4
  Summary: Enhanced Casambi Bluetooth client library with switch event support
5
5
  Home-page: https://github.com/rankjie/casambi-bt
6
6
  Author: rankjie
@@ -46,7 +46,7 @@ Have a look at `demo.py` for a small example.
46
46
 
47
47
  ### Switch Event Support
48
48
 
49
- This fork adds support for receiving switch button events:
49
+ This library now supports receiving switch button events:
50
50
 
51
51
  ```python
52
52
  from CasambiBt import Casambi
@@ -25,7 +25,7 @@ Have a look at `demo.py` for a small example.
25
25
 
26
26
  ### Switch Event Support
27
27
 
28
- This fork adds support for receiving switch button events:
28
+ This library now supports receiving switch button events:
29
29
 
30
30
  ```python
31
31
  from CasambiBt import Casambi
@@ -1,6 +1,6 @@
1
1
  [metadata]
2
2
  name = casambi-bt-revamped
3
- version = 0.3.7.dev4
3
+ version = 0.3.7.dev6
4
4
  author = rankjie
5
5
  author_email = rankjie@gmail.com
6
6
  description = Enhanced Casambi Bluetooth client library with switch event support
@@ -423,14 +423,14 @@ class Casambi:
423
423
  f"Handling switch event: unit_id={data.get('unit_id')}, "
424
424
  f"button={data.get('button')}, event={data.get('event')}"
425
425
  )
426
-
426
+
427
427
  # Notify listeners
428
- for h in self._switchEventCallbacks:
428
+ for switch_handler in self._switchEventCallbacks:
429
429
  try:
430
- h(data)
430
+ switch_handler(data)
431
431
  except Exception:
432
432
  self._logger.error(
433
- f"Exception occurred in switchEventCallback {h}.",
433
+ f"Exception occurred in switchEventCallback {switch_handler}.",
434
434
  exc_info=True,
435
435
  )
436
436
  else:
@@ -457,7 +457,9 @@ class Casambi:
457
457
  self._unitChangedCallbacks.remove(handler)
458
458
  self._logger.debug(f"Removed unit changed handler {handler}")
459
459
 
460
- def registerSwitchEventHandler(self, handler: Callable[[dict[str, Any]], None]) -> None:
460
+ def registerSwitchEventHandler(
461
+ self, handler: Callable[[dict[str, Any]], None]
462
+ ) -> None:
461
463
  """Register a new handler for switch events.
462
464
 
463
465
  This handler is called whenever a switch event is received.
@@ -474,7 +476,9 @@ class Casambi:
474
476
  self._switchEventCallbacks.append(handler)
475
477
  self._logger.debug(f"Registered switch event handler {handler}")
476
478
 
477
- def unregisterSwitchEventHandler(self, handler: Callable[[dict[str, Any]], None]) -> None:
479
+ def unregisterSwitchEventHandler(
480
+ self, handler: Callable[[dict[str, Any]], None]
481
+ ) -> None:
478
482
  """Unregister an existing switch event handler.
479
483
 
480
484
  :param handler: The handler to unregister.
@@ -1,7 +1,7 @@
1
1
  import asyncio
2
2
  import logging
3
3
  import struct
4
- from binascii import b2a_hex as b2a
4
+ from binascii import b2a_hex as b2a, hexlify
5
5
  from collections.abc import Callable
6
6
  from enum import IntEnum, unique
7
7
  from hashlib import sha256
@@ -33,12 +33,6 @@ from .errors import ( # noqa: E402
33
33
  UnsupportedProtocolVersion,
34
34
  )
35
35
 
36
- # Import Android parser for comparison
37
- try:
38
- from ._client_android_parser import AndroidPacketParser
39
- except ImportError:
40
- AndroidPacketParser = None
41
-
42
36
 
43
37
  @unique
44
38
  class IncommingPacketType(IntEnum):
@@ -420,36 +414,34 @@ class CasambiClient:
420
414
  ) -> None:
421
415
  # TODO: Check incoming counter and direction flag
422
416
  self._inPacketCount += 1
423
-
424
- # Store raw encrypted packet for Android parser analysis
417
+
418
+ # Store raw encrypted packet for reference
425
419
  raw_encrypted_packet = data[:]
426
420
 
427
- # Android parser comparison - disabled as protocols are incompatible
428
- android_switch_event = None
429
- # The Android parser expects a completely different packet format than what
430
- # this implementation uses. Logging disabled to reduce noise.
421
+ # Log raw encrypted packet with special marker for easy filtering
422
+ self._logger.info(f"[CASAMBI_RAW_PACKET] Encrypted #{self._inPacketCount}: {b2a(raw_encrypted_packet)}")
431
423
 
432
424
  try:
433
- decrypted_data = self._encryptor.decryptAndVerify(data, data[:4] + self._nonce[4:])
425
+ decrypted_data = self._encryptor.decryptAndVerify(
426
+ data, data[:4] + self._nonce[4:]
427
+ )
434
428
  except InvalidSignature:
435
429
  # We only drop packets with invalid signature here instead of going into an error state
436
430
  self._logger.error(f"Invalid signature for packet {b2a(data)}!")
437
431
  return
438
-
439
- # Protocol analysis: Current implementation vs Android
440
- # These are fundamentally different protocols:
441
- # - Current: Type 0x07 + message-based protocol (0x10/0x08 messages)
442
- # - Android: Complex header with command types 29-36 for buttons
443
- # No conversion possible - they're incompatible formats
444
- android_switch_event = None
445
432
 
446
433
  packetType = decrypted_data[0]
447
434
  self._logger.debug(f"Incoming data of type {packetType}: {b2a(decrypted_data)}")
435
+
436
+ # Log decrypted packet with special marker
437
+ self._logger.info(f"[CASAMBI_DECRYPTED] Type={packetType} #{self._inPacketCount}: {b2a(decrypted_data)}")
448
438
 
449
439
  if packetType == IncommingPacketType.UnitState:
450
440
  self._parseUnitStates(decrypted_data[1:])
451
441
  elif packetType == IncommingPacketType.SwitchEvent:
452
- self._parseSwitchEvent(decrypted_data[1:], self._inPacketCount, raw_encrypted_packet, android_switch_event)
442
+ self._parseSwitchEvent(
443
+ decrypted_data[1:], self._inPacketCount, raw_encrypted_packet
444
+ )
453
445
  elif packetType == IncommingPacketType.NetworkConfig:
454
446
  # We don't care about the config the network thinks it has.
455
447
  # We assume that cloud config and local config match.
@@ -503,29 +495,45 @@ class CasambiClient:
503
495
  f"Ran out of data while parsing unit state! Remaining data {b2a(data[oldPos:])} in {b2a(data)}."
504
496
  )
505
497
 
506
- def _parseSwitchEvent(self, data: bytes, packet_seq: int = None, raw_packet: bytes = None, android_switch_event: dict = None) -> None:
507
- """Parse switch event packet which contains multiple message types"""
508
- self._logger.info(f"Parsing incoming switch event packet #{packet_seq}... Data: {b2a(data)}")
498
+ def _parseSwitchEvent(
499
+ self, data: bytes, packet_seq: int = None, raw_packet: bytes = None
500
+ ) -> None:
501
+ """Parse switch event packet which contains multiple message types."""
502
+ self._logger.info(
503
+ f"Parsing incoming switch event packet #{packet_seq}... Data: {b2a(data)}"
504
+ )
509
505
 
506
+ # Log complete packet structure with marker
507
+ self._logger.info(f"[CASAMBI_SWITCH_PACKET] Full data #{packet_seq}: hex={b2a(data)} len={len(data)}")
508
+
510
509
  # Special handling for message type 0x29 - not a switch event
511
510
  if len(data) >= 1 and data[0] == 0x29:
512
- self._logger.debug(f"Ignoring message type 0x29 (not a switch event): {b2a(data)}")
511
+ self._logger.debug(
512
+ f"Ignoring message type 0x29 (not a switch event): {b2a(data)}"
513
+ )
513
514
  return
514
515
 
515
516
  pos = 0
516
517
  oldPos = 0
517
518
  switch_events_found = 0
518
-
519
+ all_messages_found = []
520
+
519
521
  try:
520
522
  while pos <= len(data) - 3:
521
523
  oldPos = pos
522
-
524
+
523
525
  # Parse message header
524
526
  message_type = data[pos]
525
527
  flags = data[pos + 1]
526
528
  length = ((data[pos + 2] >> 4) & 15) + 1
527
529
  parameter = data[pos + 2] # Full byte, not just lower 4 bits
528
530
  pos += 3
531
+
532
+ # Log every message found with detailed structure
533
+ self._logger.info(
534
+ f"[CASAMBI_MSG_FOUND] At pos={oldPos}: type=0x{message_type:02x} flags=0x{flags:02x} "
535
+ f"len={length} param=0x{parameter:02x}"
536
+ )
529
537
 
530
538
  # Sanity check: message type should be reasonable
531
539
  if message_type > 0x80:
@@ -547,6 +555,21 @@ class CasambiClient:
547
555
  # Extract the payload
548
556
  payload = data[pos : pos + length]
549
557
  pos += length
558
+
559
+ # Log the payload
560
+ self._logger.info(
561
+ f"[CASAMBI_MSG_PAYLOAD] Type 0x{message_type:02x} payload: {b2a(payload)} "
562
+ f"(bytes {oldPos+3} to {oldPos+3+length-1})"
563
+ )
564
+
565
+ # Track all messages
566
+ all_messages_found.append({
567
+ 'type': message_type,
568
+ 'pos': oldPos,
569
+ 'flags': flags,
570
+ 'param': parameter,
571
+ 'payload': b2a(payload)
572
+ })
550
573
 
551
574
  # Process based on message type
552
575
  if message_type == 0x08 or message_type == 0x10: # Switch/button events
@@ -554,15 +577,19 @@ class CasambiClient:
554
577
  # Extract button ID - try both upper and lower nibbles
555
578
  button_lower = parameter & 0x0F
556
579
  button_upper = (parameter >> 4) & 0x0F
557
-
580
+
558
581
  # Use upper 4 bits if lower 4 bits are 0, otherwise use lower 4 bits
559
582
  if button_lower == 0 and button_upper != 0:
560
583
  button = button_upper
561
- self._logger.debug(f"EVO button extraction: parameter=0x{parameter:02x}, using upper nibble, button={button}")
584
+ self._logger.debug(
585
+ f"EVO button extraction: parameter=0x{parameter:02x}, using upper nibble, button={button}"
586
+ )
562
587
  else:
563
588
  button = button_lower
564
- self._logger.debug(f"EVO button extraction: parameter=0x{parameter:02x}, using lower nibble, button={button}")
565
-
589
+ self._logger.debug(
590
+ f"EVO button extraction: parameter=0x{parameter:02x}, using lower nibble, button={button}"
591
+ )
592
+
566
593
  # For type 0x10 messages, we need to pass additional data beyond the declared payload
567
594
  if message_type == 0x10:
568
595
  # Extend to include at least 10 bytes from message start for state byte
@@ -570,11 +597,20 @@ class CasambiClient:
570
597
  full_message_data = data[oldPos:extended_end]
571
598
  else:
572
599
  full_message_data = data
573
- self._processSwitchMessage(message_type, flags, button, payload, full_message_data, oldPos, packet_seq, raw_packet, android_switch_event)
600
+ self._processSwitchMessage(
601
+ message_type,
602
+ flags,
603
+ button,
604
+ payload,
605
+ full_message_data,
606
+ oldPos,
607
+ packet_seq,
608
+ raw_packet,
609
+ )
574
610
  elif message_type == 0x29:
575
611
  # This shouldn't happen due to check above, but just in case
576
- self._logger.debug(f"Ignoring embedded type 0x29 message")
577
- elif message_type in [0x00, 0x06, 0x09, 0x1f, 0x2a]:
612
+ self._logger.debug("Ignoring embedded type 0x29 message")
613
+ elif message_type in [0x00, 0x06, 0x09, 0x1F, 0x2A]:
578
614
  # Known non-switch message types - log at debug level
579
615
  self._logger.debug(
580
616
  f"Non-switch message type 0x{message_type:02x}: flags=0x{flags:02x}, "
@@ -594,12 +630,33 @@ class CasambiClient:
594
630
  f"Ran out of data while parsing switch event packet! "
595
631
  f"Remaining data {b2a(data[oldPos:])} in {b2a(data)}."
596
632
  )
597
-
633
+
634
+ # Log summary of all messages found
635
+ self._logger.info(
636
+ f"[CASAMBI_PARSE_SUMMARY] Packet #{packet_seq}: Found {len(all_messages_found)} messages, "
637
+ f"{switch_events_found} switch events"
638
+ )
639
+ for i, msg in enumerate(all_messages_found):
640
+ self._logger.info(
641
+ f"[CASAMBI_MSG_{i+1}] Type=0x{msg['type']:02x} Pos={msg['pos']} "
642
+ f"Flags=0x{msg['flags']:02x} Param=0x{msg['param']:02x} Payload={msg['payload']}"
643
+ )
644
+
598
645
  if switch_events_found == 0:
599
646
  self._logger.debug(f"No switch events found in packet: {b2a(data)}")
600
647
 
601
- def _processSwitchMessage(self, message_type: int, flags: int, button: int, payload: bytes, full_data: bytes, start_pos: int, packet_seq: int = None, raw_packet: bytes = None, android_switch_event: dict = None) -> None:
602
- """Process a switch/button message (types 0x08 or 0x10)"""
648
+ def _processSwitchMessage(
649
+ self,
650
+ message_type: int,
651
+ flags: int,
652
+ button: int,
653
+ payload: bytes,
654
+ full_data: bytes,
655
+ start_pos: int,
656
+ packet_seq: int = None,
657
+ raw_packet: bytes = None,
658
+ ) -> None:
659
+ """Process a switch/button message (types 0x08 or 0x10)."""
603
660
  if not payload:
604
661
  self._logger.error("Switch message has empty payload")
605
662
  return
@@ -608,14 +665,14 @@ class CasambiClient:
608
665
  if message_type == 0x10 and len(payload) >= 3:
609
666
  # Type 0x10: unit_id is at payload[2]
610
667
  unit_id = payload[2]
611
- extra_data = payload[3:] if len(payload) > 3 else b''
668
+ extra_data = payload[3:] if len(payload) > 3 else b""
612
669
  else:
613
670
  # Standard parsing for other message types
614
671
  unit_id = payload[0]
615
- extra_data = b''
672
+ extra_data = b""
616
673
  if len(payload) > 2:
617
674
  extra_data = payload[2:]
618
-
675
+
619
676
  # Extract action based on message type (action SHOULD be different for press vs release)
620
677
  if message_type == 0x10 and len(payload) > 1:
621
678
  # Type 0x10: action is at payload[1]
@@ -627,7 +684,7 @@ class CasambiClient:
627
684
  action = None
628
685
 
629
686
  event_string = "unknown"
630
-
687
+
631
688
  # Different interpretation based on message type
632
689
  if message_type == 0x08:
633
690
  # Type 0x08: Use bit 1 of action for press/release
@@ -647,10 +704,12 @@ class CasambiClient:
647
704
  event_string = "button_release"
648
705
  elif state_byte == 0x09:
649
706
  event_string = "button_hold"
650
- elif state_byte == 0x0c:
707
+ elif state_byte == 0x0C:
651
708
  event_string = "button_release_after_hold"
652
709
  else:
653
- self._logger.debug(f"Type 0x10: Unknown state byte 0x{state_byte:02x} at message pos {state_pos}")
710
+ self._logger.debug(
711
+ f"Type 0x10: Unknown state byte 0x{state_byte:02x} at message pos {state_pos}"
712
+ )
654
713
  # Fallback: check if extra_data starts with 0x12 (indicates release)
655
714
  if len(extra_data) >= 1 and extra_data[0] == 0x12:
656
715
  event_string = "button_release"
@@ -660,10 +719,14 @@ class CasambiClient:
660
719
  # Fallback when message is too short
661
720
  if len(extra_data) >= 1 and extra_data[0] == 0x12:
662
721
  event_string = "button_release"
663
- self._logger.debug(f"Type 0x10: Using extra_data pattern for release detection")
722
+ self._logger.debug(
723
+ "Type 0x10: Using extra_data pattern for release detection"
724
+ )
664
725
  else:
665
726
  # Cannot determine state
666
- self._logger.warning(f"Type 0x10 message missing state info, unit_id={unit_id}, payload={b2a(payload)}")
727
+ self._logger.warning(
728
+ f"Type 0x10 message missing state info, unit_id={unit_id}, payload={b2a(payload)}"
729
+ )
667
730
  event_string = "unknown"
668
731
 
669
732
  action_display = f"{action:#04x}" if action is not None else "N/A"
@@ -672,31 +735,14 @@ class CasambiClient:
672
735
  f"Switch event (type 0x{message_type:02x}): button={button}, unit_id={unit_id}, "
673
736
  f"action={action_display} ({event_string}), flags=0x{flags:02x}"
674
737
  )
675
-
676
- # Include Android parser comparison if available
677
- android_comparison = None
678
- if android_switch_event:
679
- android_comparison = {
680
- 'unit_id': android_switch_event['unit_id'],
681
- 'button': android_switch_event['button'],
682
- 'state': android_switch_event['state'],
683
- 'param_p': android_switch_event['param_p'],
684
- 'param_s': android_switch_event['param_s'],
685
- 'android_log': android_switch_event['android_log']
686
- }
687
- # Log differences
688
- if android_switch_event['unit_id'] != unit_id:
689
- self._logger.warning(f"Unit ID mismatch: current={unit_id}, android={android_switch_event['unit_id']}")
690
- if android_switch_event['button'] != button:
691
- self._logger.warning(f"Button mismatch: current={button}, android={android_switch_event['button']}")
692
-
693
- # Extract controlling unit if present
694
- controlling_unit = None
695
- # This is redundant since we already return early if unit_id_echo != unit_id
696
- # Removing to avoid confusion
697
-
698
- # Filter out all type 0x08 messages
738
+
739
+ # Log detailed info about type 0x08 messages before filtering
699
740
  if message_type == 0x08:
741
+ self._logger.info(
742
+ f"[CASAMBI_TYPE08_FILTERED] Type 0x08 event detected: button={button}, unit_id={unit_id}, "
743
+ f"action={action_display}, event={event_string}, flags=0x{flags:02x}, "
744
+ f"payload={hexlify(payload).decode()}, extra_data={hexlify(extra_data).decode() if extra_data else 'none'}"
745
+ )
700
746
  self._logger.debug(
701
747
  f"Filtering out type 0x08 event: button={button}, unit_id={unit_id}, "
702
748
  f"action={action_display}, flags=0x{flags:02x}"
@@ -713,13 +759,11 @@ class CasambiClient:
713
759
  "event": event_string,
714
760
  "flags": flags,
715
761
  "extra_data": extra_data,
716
- "controlling_unit": controlling_unit,
717
762
  "packet_sequence": packet_seq,
718
763
  "raw_packet": b2a(raw_packet) if raw_packet else None,
719
764
  "decrypted_data": b2a(full_data),
720
765
  "message_position": start_pos,
721
766
  "payload_hex": b2a(payload),
722
- "android_comparison": android_comparison,
723
767
  },
724
768
  )
725
769
 
@@ -382,7 +382,6 @@ class Network:
382
382
  unitTypeJson["mode"],
383
383
  unitTypeJson["stateLength"],
384
384
  controls,
385
- unitTypeJson.get("pushButtonCount"),
386
385
  )
387
386
 
388
387
  # Chache unit type
@@ -75,7 +75,6 @@ class UnitType:
75
75
  :ivar model: The model name of this unit type.
76
76
  :ivar manufacturer: The manufacturer of this unit type.
77
77
  :ivar controls: The different types of controls this unit type is capable of.
78
- :ivar pushButtonCount: The number of push buttons this unit type has (optional).
79
78
  """
80
79
 
81
80
  id: int
@@ -84,7 +83,6 @@ class UnitType:
84
83
  mode: str
85
84
  stateLength: int
86
85
  controls: list[UnitControl]
87
- pushButtonCount: int | None = None
88
86
 
89
87
  def get_control(self, controlType: UnitControlType) -> UnitControl | None:
90
88
  """Return the control description if the unit type supports the given type of control.
@@ -113,7 +111,6 @@ class UnitState:
113
111
  self._colorsource: ColorSource | None = None
114
112
  self._xy: tuple[float, float] | None = None
115
113
  self._slider: int | None = None
116
- self._onoff: bool | None = None
117
114
 
118
115
  def _check_range(
119
116
  self, value: int | float, min: int | float, max: int | float
@@ -272,20 +269,8 @@ class UnitState:
272
269
  def slider(self) -> None:
273
270
  self.slider = None
274
271
 
275
- @property
276
- def onoff(self) -> bool | None:
277
- return self._onoff
278
-
279
- @onoff.setter
280
- def onoff(self, value: bool) -> None:
281
- self._onoff = value
282
-
283
- @onoff.deleter
284
- def onoff(self) -> None:
285
- self._onoff = None
286
-
287
272
  def __repr__(self) -> str:
288
- return f"UnitState(dimmer={self.dimmer}, vertical={self._vertical}, rgb={self.rgb.__repr__()}, white={self.white}, temperature={self.temperature}, colorsource={self.colorsource}, xy={self.xy}, slider={self.slider}, onoff={self.onoff})"
273
+ return f"UnitState(dimmer={self.dimmer}, vertical={self._vertical}, rgb={self.rgb.__repr__()}, white={self.white}, temperature={self.temperature}, colorsource={self.colorsource}, xy={self.xy}, slider={self.slider})"
289
274
 
290
275
 
291
276
  # TODO: Make unit immutable (refactor state, on, online out of it)
@@ -323,8 +308,6 @@ class Unit:
323
308
  @property
324
309
  def is_on(self) -> bool:
325
310
  """Determine whether the unit is turned on."""
326
- if self.unitType.get_control(UnitControlType.ONOFF) and self._state:
327
- return self._on and self._state.onoff is True
328
311
  if self.unitType.get_control(UnitControlType.DIMMER) and self._state:
329
312
  return (
330
313
  self._on and self._state.dimmer is not None and self._state.dimmer > 0
@@ -402,8 +385,6 @@ class Unit:
402
385
  elif c.type == UnitControlType.SLIDER and state.slider is not None:
403
386
  scale = UnitState.SLIDER_RESOLUTION - c.length
404
387
  scaledValue = state.slider >> scale
405
- elif c.type == UnitControlType.ONOFF and state.onoff is not None:
406
- scaledValue = 1 if state.onoff else 0
407
388
 
408
389
  # Use default if unsupported type or unset value in state
409
390
  else:
@@ -496,8 +477,6 @@ class Unit:
496
477
  elif c.type == UnitControlType.SLIDER:
497
478
  scale = UnitState.SLIDER_RESOLUTION - c.length
498
479
  self._state.slider = cInt << scale
499
- elif c.type == UnitControlType.ONOFF:
500
- self._state.onoff = cInt != 0
501
480
  elif c.type == UnitControlType.UNKOWN:
502
481
  # Might be useful for implementing more state types
503
482
  _LOGGER.debug(
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: casambi-bt-revamped
3
- Version: 0.3.7.dev4
3
+ Version: 0.3.7.dev6
4
4
  Summary: Enhanced Casambi Bluetooth client library with switch event support
5
5
  Home-page: https://github.com/rankjie/casambi-bt
6
6
  Author: rankjie
@@ -46,7 +46,7 @@ Have a look at `demo.py` for a small example.
46
46
 
47
47
  ### Switch Event Support
48
48
 
49
- This fork adds support for receiving switch button events:
49
+ This library now supports receiving switch button events:
50
50
 
51
51
  ```python
52
52
  from CasambiBt import Casambi
@@ -6,7 +6,6 @@ src/CasambiBt/__init__.py
6
6
  src/CasambiBt/_cache.py
7
7
  src/CasambiBt/_casambi.py
8
8
  src/CasambiBt/_client.py
9
- src/CasambiBt/_client_android_parser.py
10
9
  src/CasambiBt/_constants.py
11
10
  src/CasambiBt/_discover.py
12
11
  src/CasambiBt/_encryption.py
@@ -1,215 +0,0 @@
1
- """
2
- Android App Compatible Parser for Casambi Switch Events
3
-
4
- This module implements the exact parsing logic from the decompiled Android app
5
- to compare with our current implementation.
6
- """
7
-
8
- import struct
9
- from typing import Dict, Any, Optional, Tuple
10
- import logging
11
-
12
- logger = logging.getLogger(__name__)
13
-
14
-
15
- class AndroidPacketParser:
16
- """Parser that follows the exact Android app implementation"""
17
-
18
- @staticmethod
19
- def parse_packet_header(data: bytes, pos: int = 0) -> Tuple[Dict[str, Any], int]:
20
- """
21
- Parse packet header according to Android app C1775b.Q method (lines 230-243)
22
-
23
- Returns: (header_dict, new_position)
24
- """
25
- if len(data) - pos < 9:
26
- raise ValueError("Insufficient data for packet header")
27
-
28
- # Read header (2 bytes)
29
- unsigned_short = struct.unpack_from('>H', data, pos)[0]
30
- pos += 2
31
-
32
- # Extract flags from header
33
- has_origin_handle = (unsigned_short & 64) != 0 # bit 6
34
- is_unique = (unsigned_short & 128) != 0 # bit 7
35
- has_session = (unsigned_short & 256) != 0 # bit 8
36
- has_origin_handle_alt = (unsigned_short & 512) != 0 # bit 9
37
- flag_1024 = (unsigned_short & 1024) != 0 # bit 10
38
-
39
- # Read command type (1 byte) - this is the EnumC1777d ordinal
40
- command_type = data[pos] & 0xFF
41
- pos += 1
42
-
43
- # Read origin (2 bytes)
44
- origin = struct.unpack_from('>H', data, pos)[0]
45
- pos += 2
46
-
47
- # Read target (2 bytes)
48
- target = struct.unpack_from('>H', data, pos)[0]
49
- pos += 2
50
-
51
- # Extract lifetime from header bits 11-14
52
- lifetime = (unsigned_short >> 11) & 15
53
-
54
- # Read age (2 bytes)
55
- age = struct.unpack_from('>H', data, pos)[0]
56
- pos += 2
57
-
58
- # Read optional origin handle if flag is set
59
- origin_handle = None
60
- if has_origin_handle_alt:
61
- origin_handle = data[pos] & 0xFF
62
- pos += 1
63
-
64
- # Extract payload length from header bits 0-5
65
- payload_length = unsigned_short & 63
66
-
67
- header = {
68
- 'header_raw': unsigned_short,
69
- 'command_type': command_type,
70
- 'origin': origin,
71
- 'target': target,
72
- 'lifetime': lifetime,
73
- 'age': age,
74
- 'origin_handle': origin_handle,
75
- 'payload_length': payload_length,
76
- 'flags': {
77
- 'has_origin_handle': has_origin_handle,
78
- 'is_unique': is_unique,
79
- 'has_session': has_session,
80
- 'has_origin_handle_alt': has_origin_handle_alt,
81
- 'flag_1024': flag_1024
82
- }
83
- }
84
-
85
- return header, pos
86
-
87
- @staticmethod
88
- def parse_switch_event(header: Dict[str, Any], payload: bytes) -> Optional[Dict[str, Any]]:
89
- """
90
- Parse switch event according to Android app logic (lines 271-280)
91
-
92
- The Android app checks:
93
- - target & 0xFF == 6 (lower byte of target must be 6)
94
- - command_type ordinal must be between 29-36 (FunctionButtonEvent0-7)
95
- - payload must have at least 3 bytes
96
- """
97
- target_type = header['target'] & 0xFF
98
- target_unit_id = header['target'] >> 8
99
- command_type = header['command_type']
100
-
101
- # Check if this is a switch event
102
- if target_type != 6:
103
- return None
104
-
105
- # Check if command type is in range for button events (29-36)
106
- if command_type < 29 or command_type > 36:
107
- return None
108
-
109
- # Check payload length
110
- if len(payload) < 3:
111
- logger.warning(f"Switch event payload too short: {len(payload)} bytes")
112
- return None
113
-
114
- # Parse according to Android logic
115
- first_byte = payload[0]
116
- button_index = command_type - 29 # 0-7
117
-
118
- # Extract parameters from first byte
119
- param_p = (first_byte >> 3) & 15 # bits 3-6
120
- param_s = first_byte & 7 # bits 0-2
121
- state = 1 if (first_byte & 128) else 0 # bit 7
122
-
123
- return {
124
- 'unit_id': target_unit_id,
125
- 'button': button_index,
126
- 'state': state, # 1 = pressed, 0 = released
127
- 'param_p': param_p,
128
- 'param_s': param_s,
129
- 'target_type': target_type,
130
- 'command_type': command_type,
131
- 'payload_hex': payload.hex(),
132
- 'android_log': f"Unit {target_unit_id} Switch event: #{button_index} (P{param_p} S{param_s}) = {state}"
133
- }
134
-
135
- @staticmethod
136
- def parse_complete_packet(data: bytes) -> Dict[str, Any]:
137
- """Parse a complete packet and extract switch events if present"""
138
- try:
139
- header, payload_start = AndroidPacketParser.parse_packet_header(data)
140
-
141
- # Read payload
142
- payload_length = header['payload_length']
143
- if len(data) - payload_start < payload_length:
144
- raise ValueError(f"Insufficient data for payload: need {payload_length}, have {len(data) - payload_start}")
145
-
146
- payload = data[payload_start:payload_start + payload_length]
147
-
148
- # Try to parse as switch event
149
- switch_event = AndroidPacketParser.parse_switch_event(header, payload)
150
-
151
- return {
152
- 'header': header,
153
- 'payload': payload.hex(),
154
- 'switch_event': switch_event
155
- }
156
-
157
- except Exception as e:
158
- logger.error(f"Failed to parse packet: {e}")
159
- return {'error': str(e), 'data': data.hex()}
160
-
161
-
162
- # Command type constants from EnumC1777d
163
- class FunctionType:
164
- """Function type constants from Android app"""
165
- BUTTON_EVENT_0 = 29
166
- BUTTON_EVENT_1 = 30
167
- BUTTON_EVENT_2 = 31
168
- BUTTON_EVENT_3 = 32
169
- BUTTON_EVENT_4 = 33
170
- BUTTON_EVENT_5 = 34
171
- BUTTON_EVENT_6 = 35
172
- BUTTON_EVENT_7 = 36
173
-
174
-
175
- def compare_with_current_parser(data: bytes, current_parser_result: Dict[str, Any]) -> Dict[str, Any]:
176
- """Compare Android parser results with current implementation"""
177
- android_result = AndroidPacketParser.parse_complete_packet(data)
178
-
179
- comparison = {
180
- 'android_parser': android_result,
181
- 'current_parser': current_parser_result,
182
- 'differences': []
183
- }
184
-
185
- # Compare results
186
- if android_result.get('switch_event') and current_parser_result:
187
- android_evt = android_result['switch_event']
188
-
189
- # Check unit_id
190
- if android_evt['unit_id'] != current_parser_result.get('unit_id'):
191
- comparison['differences'].append({
192
- 'field': 'unit_id',
193
- 'android': android_evt['unit_id'],
194
- 'current': current_parser_result.get('unit_id')
195
- })
196
-
197
- # Check button
198
- if android_evt['button'] != current_parser_result.get('button'):
199
- comparison['differences'].append({
200
- 'field': 'button',
201
- 'android': android_evt['button'],
202
- 'current': current_parser_result.get('button')
203
- })
204
-
205
- # Map Android state to current event names
206
- android_event = 'button_press' if android_evt['state'] == 1 else 'button_release'
207
- if android_event != current_parser_result.get('event'):
208
- comparison['differences'].append({
209
- 'field': 'event',
210
- 'android': android_event,
211
- 'current': current_parser_result.get('event'),
212
- 'note': 'Android only has press/release, no hold detection'
213
- })
214
-
215
- return comparison