1
0
mirror of https://github.com/mjg59/python-broadlink.git synced 2024-11-23 15:21:25 +01:00
python-broadlink/broadlink/light.py

75 lines
2.4 KiB
Python
Raw Normal View History

"""Support for lights."""
2020-09-17 05:41:32 +02:00
import json
from typing import Union
from .device import device
from .exceptions import check_error
class lb1(device):
"""Controls a Broadlink LB1."""
state_dict = []
effect_map_dict = {
2020-11-05 20:25:33 +01:00
"lovely color": 0,
"flashlight": 1,
"lightning": 2,
"color fading": 3,
"color breathing": 4,
"multicolor breathing": 5,
"color jumping": 6,
"multicolor jumping": 7,
2020-09-17 05:41:32 +02:00
}
def __init__(self, *args, **kwargs) -> None:
"""Initialize the controller."""
device.__init__(self, *args, **kwargs)
self.type = "SmartBulb"
2020-11-05 20:25:33 +01:00
def send_command(self, command: str, type: str = "set") -> None:
2020-09-17 05:41:32 +02:00
"""Send a command to the device."""
2020-11-05 20:25:33 +01:00
packet = bytearray(16 + (int(len(command) / 16) + 1) * 16)
packet[0x00] = 0x0C + len(command) & 0xFF
packet[0x02] = 0xA5
packet[0x03] = 0xA5
packet[0x04] = 0x5A
packet[0x05] = 0x5A
packet[0x08] = 0x02 if type == "set" else 0x01 # 0x01 => query, # 0x02 => set
packet[0x09] = 0x0B
packet[0x0A] = len(command)
packet[0x0E:] = map(ord, command)
2020-09-17 05:41:32 +02:00
2020-11-05 20:25:33 +01:00
checksum = sum(packet, 0xBEAF) & 0xFFFF
packet[0x06] = checksum & 0xFF # Checksum 1 position
2020-09-17 05:41:32 +02:00
packet[0x07] = checksum >> 8 # Checksum 2 position
2020-11-05 20:25:33 +01:00
response = self.send_packet(0x6A, packet)
2020-09-17 05:41:32 +02:00
check_error(response[0x36:0x38])
2020-09-20 11:16:49 +02:00
payload = self.decrypt(response[0x38:])
2020-09-17 05:41:32 +02:00
2020-11-05 20:25:33 +01:00
responseLength = int(payload[0x0A]) | (int(payload[0x0B]) << 8)
2020-09-17 05:41:32 +02:00
if responseLength > 0:
2020-11-05 20:25:33 +01:00
self.state_dict = json.loads(payload[0x0E : 0x0E + responseLength])
2020-09-17 05:41:32 +02:00
def set_json(self, jsonstr: str) -> str:
"""Send a command to the device and return state."""
reconvert = json.loads(jsonstr)
2020-11-05 20:25:33 +01:00
if "bulb_sceneidx" in reconvert.keys():
reconvert["bulb_sceneidx"] = self.effect_map_dict.get(
reconvert["bulb_sceneidx"], 255
)
2020-09-17 05:41:32 +02:00
self.send_command(json.dumps(reconvert))
return json.dumps(self.state_dict)
def set_state(self, state: Union[str, int]) -> None:
"""Set the state of the device."""
cmd = '{"pwr":%d}' % (1 if state == "ON" or state == 1 else 0)
self.send_command(cmd)
def get_state(self) -> dict:
"""Return the state of the device."""
cmd = "{}"
self.send_command(cmd)
return self.state_dict