import logging import math from sense_hat import ACTION_HELD, ACTION_RELEASED, SenseHat logger = logging.getLogger(__name__) class Selector: def __init__(self, send_data): self.stick = SenseHat().stick self.temperature = None self.mode = None self.switch = None self.preset_modes = [] self.send_data = send_data self.switch_held = False self.default_data = {"temperature": None, "mode": None, "switch": None} self.stick.direction_middle = self.toggle self.stick.direction_up = self.increase_temperature self.stick.direction_down = self.decrease_temperature self.stick.direction_right = self.next_mode self.stick.direction_left = self.prev_mode @property def ha_options(self): return { "temperature": { "p": "sensor", "value_template": "{{ value_json.temperature }}", "unique_id": "oin_temp", "device_class": "temperature", "entity_category": "diagnostic", "icon": "mdi:thermostat", "unit_of_measurement": "°C", }, "mode": { "p": "sensor", "name": "Mode", "value_template": "{{ value_json.mode }}", "unique_id": "oin_mode", "entity_category": "diagnostic", "icon": "mdi:thermostat-auto", }, "switch": { "p": "sensor", "name": "Switch", "value_template": "{{ value_json.switch }}", "unique_id": "oin_switch", "entity_category": "diagnostic", "icon": "mdi:thermostat-auto", }, } def increase_temperature(self, event): if event.action != ACTION_RELEASED and self.temperature is not None: self.callback(temperature=math.floor(self.temperature * 2) / 2 + 0.5) def decrease_temperature(self, event): if event.action != ACTION_RELEASED and self.temperature is not None: self.callback(temperature=math.ceil(self.temperature * 2) / 2 - 0.5) def next_mode(self, event): if event.action != ACTION_RELEASED and self.mode is not None: self.callback( mode=self.preset_modes[ (self.preset_modes.index(self.mode) + 1) % len(self.preset_modes) ] ) def prev_mode(self, event): if event.action != ACTION_RELEASED and self.mode is not None: self.callback( mode=self.preset_modes[ (self.preset_modes.index(self.mode) - 1) % len(self.preset_modes) ] ) def toggle(self, event): if not self.switch_held and event.action == ACTION_HELD: self.switch_held = True self.callback(switch="off" if self.switch else "heat") elif self.switch_held and event.action == ACTION_RELEASED: self.switch_held = False def callback(self, **kwargs): self.send_data(self.default_data | kwargs)