AirSend duo

This commit is contained in:
Devmel Apps
2022-11-16 12:59:19 +01:00
parent 1513a864dc
commit bb072fd573
7 changed files with 318 additions and 305 deletions
+57 -97
View File
@@ -1,78 +1,47 @@
"""AirSend switches."""
import logging
import json
from typing import Any
from requests import get, post
from .device import Device
from homeassistant.components.cover import CoverEntity
from homeassistant.core import HomeAssistant
from homeassistant.helpers.typing import ConfigType
from homeassistant.helpers.entity import async_generate_entity_id
from homeassistant.components.hassio import (
async_get_addon_discovery_info,
async_get_addon_info,
)
from homeassistant.components.cover import (
CoverEntity,
)
from . import (
DOMAIN,
)
_LOGGER = logging.getLogger(DOMAIN)
from homeassistant.const import CONF_DEVICES, CONF_INTERNAL_URL
async def async_setup_platform(hass : HomeAssistant, config : ConfigType, async_add_entities, discovery_info=None):
addons_url = ""
try:
addon_info: dict = await async_get_addon_info(hass, 'local_airsend')
ip = addon_info["ip_address"]
if ip:
addons_url = "http://"+str(ip)+":33863/"
# _LOGGER.warning("Addon '%s'", addon_info)
except:
pass
from . import DOMAIN
async def async_setup_platform(
hass: HomeAssistant, config: ConfigType, async_add_entities, discovery_info=None
) -> None:
if discovery_info is None:
return
for name, options in discovery_info.items():
if options['type'] == 4098:
id = ""
apiKey = ""
spurl = ""
channel = {}
try:
id = options['id']
except KeyError:
pass
try:
apiKey = options['apiKey']
except KeyError:
pass
try:
spurl = options['spurl']
except KeyError:
pass
try:
channel = options['channel']
except KeyError:
pass
entity = AirSendCover(hass, name, id, options['type'], apiKey, addons_url, spurl, channel)
for name, options in discovery_info[CONF_DEVICES].items():
device = Device(name, options, discovery_info[CONF_INTERNAL_URL])
if device.is_cover:
entity = AirSendCover(
hass,
device,
)
async_add_entities([entity])
return
class AirSendCover(CoverEntity):
"""Representation of an AirSend Cover."""
def __init__(self, hass : HomeAssistant, name : str, id: str, type : int, apikey : str, addons_url : str, spurl : str, channel : dict):
def __init__(
self,
hass: HomeAssistant,
device: Device,
) -> None:
"""Initialize a cover device."""
self._name = name
self._id = id
self._type = type
self._apikey = apikey
self._addons_url = addons_url
self._spurl = spurl
self._channel = channel
uname = DOMAIN+name
self._device = device
uname = DOMAIN + device.name
self._unique_id = "_".join(x for x in uname)
self._state = False
self._closed = False
if device.is_cover_with_position:
self._attr_current_cover_position = 50
@property
def unique_id(self):
@@ -91,7 +60,7 @@ class AirSendCover(CoverEntity):
@property
def name(self):
"""Return the name of the device if any."""
return self._name
return self._device.name
@property
def extra_state_attributes(self):
@@ -106,51 +75,42 @@ class AirSendCover(CoverEntity):
@property
def is_closed(self):
"""Return if the cover is closed."""
return not self._state
return not self._closed
def open_cover(self, **kwargs: Any) -> None:
"""Open the cover."""
note = {"method":1,"type":0,"value": "UP"}
url = "https://airsend.cloud/device/"+str(self._id)+"/command/5/"
payload = '{"wait": true, "channel":'+json.dumps(self._channel)+', "thingnotes":{"notes":['+json.dumps(note)+']}}'
self._action(url, payload, False)
note = {"method": 1, "type": 0, "value": "UP"}
if self._device.transfer(note):
self._closed = False
if self._device.is_cover_with_position:
self._attr_current_cover_position = 100
self.schedule_update_ha_state()
def close_cover(self, **kwargs: Any) -> None:
"""Close cover."""
note = {"method":1,"type":0,"value": "DOWN"}
url = "https://airsend.cloud/device/"+str(self._id)+"/command/4/"
payload = '{"wait": true, "channel":'+json.dumps(self._channel)+', "thingnotes":{"notes":['+json.dumps(note)+']}}'
self._action(url, payload, False)
note = {"method": 1, "type": 0, "value": "DOWN"}
if self._device.transfer(note):
self._closed = True
if self._device.is_cover_with_position:
self._attr_current_cover_position = 0
self.schedule_update_ha_state()
def stop_cover(self, **kwargs):
"""Stop the cover."""
note = {"method":1,"type":0,"value": "STOP"}
url = "https://airsend.cloud/device/"+str(self._id)+"/command/3/"
payload = '{"wait": true, "channel":'+json.dumps(self._channel)+', "thingnotes":{"notes":['+json.dumps(note)+']}}'
self._action(url, payload, False)
note = {"method": 1, "type": 0, "value": "STOP"}
if self._device.transfer(note):
self._closed = False
if self._device.is_cover_with_position:
self._attr_current_cover_position = 50
self.schedule_update_ha_state()
def _action(self, cloud_url : str, payload : str, new_state : bool):
status_code = 404
if self._addons_url and self._spurl:
headers = {"Authorization": "Bearer "+self._spurl, "content-type": "application/json", "User-Agent": "hass_airsend"}
try:
response = post(self._addons_url+"airsend/transfer", headers=headers, data=payload, timeout=6)
status_code = 500
jdata = json.loads(response.text)
if jdata["type"] < 0x100:
status_code = response.status_code
except:
pass
if status_code != 200 and self._apikey and cloud_url:
headers = {"Authorization": "Bearer "+self._apikey, "content-type": "application/json", "User-Agent": "hass_airsend"}
try:
response = get(cloud_url, headers=headers, timeout=10)
status_code = response.status_code
except:
pass
if status_code == 200:
self._state = new_state
def set_cover_position(self, **kwargs):
"""Move the cover to a specific position."""
position = int(kwargs["position"])
note = {"method": 1, "type": 9, "value": position}
if self._device.transfer(note):
self._attr_current_cover_position = position
self._closed = False
if self._attr_current_cover_position == 0:
self._closed = True
self.schedule_update_ha_state()
else:
_LOGGER.error("action error : "+str(status_code))
raise Exception("action error : "+str(status_code))