"""

行空板控制Home Assistant中的设备

作者：DouDad
Email:1545148519@qq.com
日期：2024-9-28

"""

import requests


class DEVICE:	
    def __init__(self, HASS_URL, ACCESS_TOKEN):       
        self.HASS_URL = HASS_URL
        self.ACCESS_TOKEN = ACCESS_TOKEN
	
    def control(self, entity_id, command, domain='cover'):
        url = f"{self.HASS_URL}/api/services/{domain}/{command}"
        payload = {"entity_id": entity_id}
        headers = {
            'Authorization': f'Bearer {self.ACCESS_TOKEN}',
            'Content-Type': 'application/json'
        }
        response = requests.post(url, json=payload, headers=headers)
        if response.status_code == 200:
            print(f"命令 '{command}' 已发送至设备'{entity_id}'")
        else:
            print(f"错误: {response.status_code} - {response.text}")

class HA:
    class COVER(DEVICE):
        def __init__(self, HASS_URL, ACCESS_TOKEN):
            super().__init__(HASS_URL, ACCESS_TOKEN)

        def up(self):
            super().control('cover.kejia_mzn_6408_airer', 'open_cover')
        
        def down(self):
            super().control('cover.kejia_mzn_6408_airer', 'close_cover')
        
        def stop(self):
            super().control('cover.kejia_mzn_6408_airer', 'stop_cover')
        
        def light_on(self):
            super().control('light.kejia_mzn_6408_light', 'turn_on', domain='light')
        
        def light_off(self):
            super().control('light.kejia_mzn_6408_light', 'turn_off', domain='light')	
	
    class FAN(DEVICE):
        def __init__(self, HASS_URL, ACCESS_TOKEN):
            super().__init__(HASS_URL, ACCESS_TOKEN)
	
        def on(self):
            super().control('fan.dmaker_p9_2068_fan', 'turn_on')
        
        def off(self):
            super().control('fan.dmaker_p9_2068_fan', 'turn_off')	
	
    def __init__(self, HASS_URL='http://192.168.123.253:8123', ACCESS_TOKEN='eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJiOWJhMDM0YjYyODQ0MGQ2YmYxNmMyM2Q2NzkyN2RiYyIsImlhdCI6MTcyNzMzNjE2NCwiZXhwIjoyMDQyNjk2MTY0fQ.umXZPcX7FbPZ6EOIIgBPXh5rtgbbEfOaLbuiQoGdBKM'):
        self.cover = self.COVER(HASS_URL, ACCESS_TOKEN)
        self.fan = self.FAN(HASS_URL, ACCESS_TOKEN)

if __name__ == "__main__":
    ha = HA()
    ha.cover.light_on()
    ha.cover.light_off()
    ha.cover.down()
    ha.cover.stop()
    ha.cover.up()