Introduced cover support
This commit is contained in:
208
custom_components/localtuya/cover.py
Normal file
208
custom_components/localtuya/cover.py
Normal file
@@ -0,0 +1,208 @@
|
||||
"""
|
||||
Simple platform to control LOCALLY Tuya cover devices.
|
||||
|
||||
Sample config yaml
|
||||
|
||||
switch:
|
||||
- platform: localtuya
|
||||
host: 192.168.0.123
|
||||
local_key: 1234567891234567
|
||||
device_id: 123456789123456789abcd
|
||||
name: Cover guests
|
||||
protocol_version: 3.3
|
||||
id: 1
|
||||
|
||||
"""
|
||||
import logging
|
||||
import requests
|
||||
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.components.cover import (
|
||||
CoverDevice,
|
||||
PLATFORM_SCHEMA,
|
||||
SUPPORT_CLOSE,
|
||||
SUPPORT_OPEN,
|
||||
SUPPORT_STOP,
|
||||
)
|
||||
|
||||
"""from . import DATA_TUYA, TuyaDevice"""
|
||||
"""from homeassistant.components.cover import CoverDevice, PLATFORM_SCHEMA"""
|
||||
from homeassistant.const import (CONF_HOST, CONF_ID, CONF_FRIENDLY_NAME, CONF_ICON, CONF_NAME)
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
from time import time, sleep
|
||||
from threading import Lock
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
DEFAULT_NAME = 'localtuyacover'
|
||||
|
||||
REQUIREMENTS = ['pytuya==7.0.7']
|
||||
|
||||
CONF_DEVICE_ID = 'device_id'
|
||||
CONF_LOCAL_KEY = 'local_key'
|
||||
CONF_PROTOCOL_VERSION = 'protocol_version'
|
||||
|
||||
DEFAULT_ID = '1'
|
||||
DEFAULT_PROTOCOL_VERSION = 3.3
|
||||
|
||||
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
|
||||
vol.Optional(CONF_ICON): cv.icon,
|
||||
vol.Required(CONF_HOST): cv.string,
|
||||
vol.Required(CONF_DEVICE_ID): cv.string,
|
||||
vol.Required(CONF_LOCAL_KEY): cv.string,
|
||||
vol.Required(CONF_NAME): cv.string,
|
||||
vol.Required(CONF_PROTOCOL_VERSION, default=DEFAULT_PROTOCOL_VERSION): vol.Coerce(float),
|
||||
vol.Optional(CONF_ID, default=DEFAULT_ID): cv.string,
|
||||
})
|
||||
|
||||
|
||||
|
||||
|
||||
def setup_platform(hass, config, add_entities, discovery_info=None):
|
||||
"""Set up Tuya cover devices."""
|
||||
from . import pytuya
|
||||
|
||||
covers = []
|
||||
localtuyadevice = pytuya.CoverDevice(config.get(CONF_DEVICE_ID), config.get(CONF_HOST), config.get(CONF_LOCAL_KEY))
|
||||
localtuyadevice.set_version(float(config.get(CONF_PROTOCOL_VERSION)))
|
||||
|
||||
cover_device = TuyaCoverCache(localtuyadevice)
|
||||
covers.append(
|
||||
TuyaDevice(
|
||||
cover_device,
|
||||
config.get(CONF_NAME),
|
||||
config.get(CONF_ICON),
|
||||
config.get(CONF_ID),
|
||||
)
|
||||
)
|
||||
print('Setup localtuya cover [{}] with device ID [{}] '.format(config.get(CONF_NAME), config.get(CONF_ID)))
|
||||
|
||||
add_entities(covers)
|
||||
|
||||
|
||||
class TuyaCoverCache:
|
||||
"""Cache wrapper for pytuya.CoverDevice"""
|
||||
|
||||
def __init__(self, device):
|
||||
"""Initialize the cache."""
|
||||
self._cached_status = ''
|
||||
self._cached_status_time = 0
|
||||
self._device = device
|
||||
self._lock = Lock()
|
||||
|
||||
def __get_status(self):
|
||||
for i in range(20):
|
||||
try:
|
||||
status = self._device.status()
|
||||
return status
|
||||
except ConnectionError:
|
||||
if i+1 == 3:
|
||||
raise ConnectionError("Failed to update status.")
|
||||
|
||||
def set_status(self, state, switchid):
|
||||
"""Change the Tuya switch status and clear the cache."""
|
||||
self._cached_status = ''
|
||||
self._cached_status_time = 0
|
||||
for i in range(20):
|
||||
try:
|
||||
return self._device.set_status(state, switchid)
|
||||
except ConnectionError:
|
||||
if i+1 == 5:
|
||||
raise ConnectionError("Failed to set status.")
|
||||
|
||||
def status(self):
|
||||
"""Get state of Tuya switch and cache the results."""
|
||||
self._lock.acquire()
|
||||
try:
|
||||
now = time()
|
||||
if not self._cached_status or now - self._cached_status_time > 30:
|
||||
sleep(0.5)
|
||||
self._cached_status = self.__get_status()
|
||||
self._cached_status_time = time()
|
||||
return self._cached_status
|
||||
finally:
|
||||
self._lock.release()
|
||||
|
||||
class TuyaDevice(CoverDevice):
|
||||
"""Tuya cover devices."""
|
||||
|
||||
def __init__(self, device, name, icon, switchid):
|
||||
self._device = device
|
||||
self._name = name
|
||||
self._icon = icon
|
||||
self._switch_id = switchid
|
||||
#self.entity_id = ENTITY_ID_FORMAT.format(_device.object_id())
|
||||
self._status = self._device.status()
|
||||
self._state = self._status['dps'][self._switch_id]
|
||||
print('Initialized tuya cover [{}] with switch status [{}] and state [{}]'.format(self._name, self._status, self._state))
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
"""Get name of Tuya switch."""
|
||||
return self._name
|
||||
|
||||
@property
|
||||
def supported_features(self):
|
||||
"""Flag supported features."""
|
||||
supported_features = SUPPORT_OPEN | SUPPORT_CLOSE | SUPPORT_STOP
|
||||
return supported_features
|
||||
|
||||
@property
|
||||
def icon(self):
|
||||
"""Return the icon."""
|
||||
return self._icon
|
||||
|
||||
@property
|
||||
def is_opening(self):
|
||||
#self.update()
|
||||
state = self._state
|
||||
#print('is_opening() : state [{}]'.format(state))
|
||||
if state == 'on':
|
||||
return True
|
||||
return False
|
||||
|
||||
@property
|
||||
def is_closing(self):
|
||||
#self.update()
|
||||
state = self._state
|
||||
#print('is_closing() : state [{}]'.format(state))
|
||||
if state == 'off':
|
||||
return True
|
||||
return False
|
||||
|
||||
@property
|
||||
def is_closed(self):
|
||||
"""Return if the cover is closed or not."""
|
||||
#self.update()
|
||||
state = self._state
|
||||
#print('is_closed() : state [{}]'.format(state))
|
||||
if state == 'off':
|
||||
return False
|
||||
if state == 'on':
|
||||
return True
|
||||
return None
|
||||
|
||||
def open_cover(self, **kwargs):
|
||||
"""Open the cover."""
|
||||
self._device.set_status('on', self._switch_id)
|
||||
# self._state = 'on'
|
||||
# self._device._device.open_cover()
|
||||
|
||||
def close_cover(self, **kwargs):
|
||||
"""Close cover."""
|
||||
self._device.set_status('off', self._switch_id)
|
||||
# self._state = 'off'
|
||||
# self._device._device.close_cover()
|
||||
|
||||
def stop_cover(self, **kwargs):
|
||||
"""Stop the cover."""
|
||||
self._device.set_status('stop', self._switch_id)
|
||||
# self._state = 'stop'
|
||||
# self._device._device.stop_cover()
|
||||
|
||||
def update(self):
|
||||
"""Get state of Tuya switch."""
|
||||
self._status = self._device.status()
|
||||
self._state = self._status['dps'][self._switch_id]
|
||||
#print('update() : state [{}]'.format(self._state))
|
288
custom_components/localtuya/light.py
Normal file
288
custom_components/localtuya/light.py
Normal file
@@ -0,0 +1,288 @@
|
||||
"""
|
||||
Simple platform to control LOCALLY Tuya switch devices.
|
||||
|
||||
Sample config yaml
|
||||
|
||||
switch:
|
||||
- platform: localtuya
|
||||
host: 192.168.0.1
|
||||
local_key: 1234567891234567
|
||||
device_id: 12345678912345671234
|
||||
name: tuya_01
|
||||
protocol_version: 3.3
|
||||
"""
|
||||
import voluptuous as vol
|
||||
from homeassistant.const import (CONF_HOST, CONF_ID, CONF_SWITCHES, CONF_FRIENDLY_NAME, CONF_ICON, CONF_NAME)
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
from time import time, sleep
|
||||
from threading import Lock
|
||||
import logging
|
||||
from homeassistant.components.light import (
|
||||
ATTR_BRIGHTNESS,
|
||||
ATTR_COLOR_TEMP,
|
||||
ATTR_HS_COLOR,
|
||||
ENTITY_ID_FORMAT,
|
||||
SUPPORT_BRIGHTNESS,
|
||||
SUPPORT_COLOR,
|
||||
SUPPORT_COLOR_TEMP,
|
||||
Light,
|
||||
PLATFORM_SCHEMA
|
||||
)
|
||||
from homeassistant.util import color as colorutil
|
||||
import socket
|
||||
|
||||
REQUIREMENTS = ['pytuya==7.0.4']
|
||||
|
||||
CONF_DEVICE_ID = 'device_id'
|
||||
CONF_LOCAL_KEY = 'local_key'
|
||||
CONF_PROTOCOL_VERSION = 'protocol_version'
|
||||
# IMPORTANT, id is used as key for state and turning on and off, 1 was fine switched apparently but my bulbs need 20, other feature attributes count up from this, e.g. 21 mode, 22 brightnes etc, see my pytuya modification.
|
||||
DEFAULT_ID = '1'
|
||||
DEFAULT_PROTOCOL_VERSION = 3.3
|
||||
MIN_MIRED = 153
|
||||
MAX_MIRED = 370
|
||||
UPDATE_RETRY_LIMIT = 3
|
||||
|
||||
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
|
||||
vol.Optional(CONF_ICON): cv.icon,
|
||||
vol.Required(CONF_HOST): cv.string,
|
||||
vol.Required(CONF_DEVICE_ID): cv.string,
|
||||
vol.Required(CONF_LOCAL_KEY): cv.string,
|
||||
vol.Required(CONF_NAME): cv.string,
|
||||
vol.Required(CONF_PROTOCOL_VERSION, default=DEFAULT_PROTOCOL_VERSION): vol.Coerce(float),
|
||||
vol.Optional(CONF_ID, default=DEFAULT_ID): cv.string,
|
||||
})
|
||||
log = logging.getLogger(__name__)
|
||||
log.setLevel(level=logging.DEBUG) # Debug hack!
|
||||
|
||||
|
||||
def setup_platform(hass, config, add_devices, discovery_info=None):
|
||||
"""Set up of the Tuya switch."""
|
||||
from . import pytuya
|
||||
|
||||
lights = []
|
||||
pytuyadevice = pytuya.BulbDevice(config.get(CONF_DEVICE_ID), config.get(CONF_HOST), config.get(CONF_LOCAL_KEY))
|
||||
pytuyadevice.set_version(float(config.get(CONF_PROTOCOL_VERSION)))
|
||||
|
||||
bulb_device = TuyaCache(pytuyadevice)
|
||||
lights.append(
|
||||
TuyaDevice(
|
||||
bulb_device,
|
||||
config.get(CONF_NAME),
|
||||
config.get(CONF_ICON),
|
||||
config.get(CONF_ID)
|
||||
)
|
||||
)
|
||||
|
||||
add_devices(lights)
|
||||
|
||||
class TuyaCache:
|
||||
"""Cache wrapper for pytuya.BulbDevice"""
|
||||
|
||||
def __init__(self, device):
|
||||
"""Initialize the cache."""
|
||||
self._cached_status = ''
|
||||
self._cached_status_time = 0
|
||||
self._device = device
|
||||
self._lock = Lock()
|
||||
|
||||
def __get_status(self, switchid):
|
||||
for _ in range(UPDATE_RETRY_LIMIT):
|
||||
try:
|
||||
status = self._device.status()['dps'][switchid]
|
||||
return status
|
||||
except ConnectionError:
|
||||
pass
|
||||
except socket.timeout:
|
||||
pass
|
||||
log.warn(
|
||||
"Failed to get status after {} tries".format(UPDATE_RETRY_LIMIT))
|
||||
|
||||
def set_status(self, state, switchid):
|
||||
"""Change the Tuya switch status and clear the cache."""
|
||||
self._cached_status = ''
|
||||
self._cached_status_time = 0
|
||||
for _ in range(UPDATE_RETRY_LIMIT):
|
||||
try:
|
||||
return self._device.set_status(state, switchid)
|
||||
except ConnectionError:
|
||||
pass
|
||||
except socket.timeout:
|
||||
pass
|
||||
log.warn(
|
||||
"Failed to set status after {} tries".format(UPDATE_RETRY_LIMIT))
|
||||
|
||||
def status(self, switchid):
|
||||
"""Get state of Tuya switch and cache the results."""
|
||||
self._lock.acquire()
|
||||
try:
|
||||
now = time()
|
||||
if not self._cached_status or now - self._cached_status_time > 30:
|
||||
sleep(0.5)
|
||||
self._cached_status = self.__get_status(switchid)
|
||||
self._cached_status_time = time()
|
||||
return self._cached_status
|
||||
finally:
|
||||
self._lock.release()
|
||||
|
||||
def cached_status(self):
|
||||
return self._cached_status
|
||||
|
||||
def support_color(self):
|
||||
return self._device.support_color()
|
||||
|
||||
def support_color_temp(self):
|
||||
return self._device.support_color_temp()
|
||||
|
||||
def brightness(self):
|
||||
for _ in range(UPDATE_RETRY_LIMIT):
|
||||
try:
|
||||
return self._device.brightness()
|
||||
except ConnectionError:
|
||||
pass
|
||||
except socket.timeout:
|
||||
pass
|
||||
log.warn(
|
||||
"Failed to get brightness after {} tries".format(UPDATE_RETRY_LIMIT))
|
||||
|
||||
def color_temp(self):
|
||||
for _ in range(UPDATE_RETRY_LIMIT):
|
||||
try:
|
||||
return self._device.colourtemp()
|
||||
except ConnectionError:
|
||||
pass
|
||||
except socket.timeout:
|
||||
pass
|
||||
log.warn(
|
||||
"Failed to get color temp after {} tries".format(UPDATE_RETRY_LIMIT))
|
||||
|
||||
def set_brightness(self, brightness):
|
||||
for _ in range(UPDATE_RETRY_LIMIT):
|
||||
try:
|
||||
return self._device.set_brightness(brightness)
|
||||
except ConnectionError:
|
||||
pass
|
||||
except socket.timeout:
|
||||
pass
|
||||
log.warn(
|
||||
"Failed to set brightness after {} tries".format(UPDATE_RETRY_LIMIT))
|
||||
|
||||
def set_color_temp(self, color_temp):
|
||||
for _ in range(UPDATE_RETRY_LIMIT):
|
||||
try:
|
||||
return self._device.set_colourtemp(color_temp)
|
||||
except ConnectionError:
|
||||
pass
|
||||
except socket.timeout:
|
||||
pass
|
||||
log.warn(
|
||||
"Failed to set color temp after {} tries".format(UPDATE_RETRY_LIMIT))
|
||||
|
||||
def state(self):
|
||||
self._device.state();
|
||||
|
||||
def turn_on(self):
|
||||
self._device.turn_on();
|
||||
|
||||
def turn_off(self):
|
||||
self._device.turn_off();
|
||||
|
||||
class TuyaDevice(Light):
|
||||
"""Representation of a Tuya switch."""
|
||||
|
||||
def __init__(self, device, name, icon, bulbid):
|
||||
"""Initialize the Tuya switch."""
|
||||
self._device = device
|
||||
self._name = name
|
||||
self._state = False
|
||||
self._brightness = 127
|
||||
self._color_temp = 127
|
||||
self._icon = icon
|
||||
self._bulb_id = bulbid
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
"""Get name of Tuya switch."""
|
||||
return self._name
|
||||
|
||||
@property
|
||||
def is_on(self):
|
||||
"""Check if Tuya switch is on."""
|
||||
return self._state
|
||||
|
||||
@property
|
||||
def icon(self):
|
||||
"""Return the icon."""
|
||||
return self._icon
|
||||
|
||||
def update(self):
|
||||
"""Get state of Tuya switch."""
|
||||
status = self._device.status(self._bulb_id)
|
||||
self._state = status
|
||||
try:
|
||||
brightness = int(self._device.brightness())
|
||||
if brightness > 254:
|
||||
brightness = 255
|
||||
if brightness < 25:
|
||||
brightness = 25
|
||||
self._brightness = brightness
|
||||
except TypeError:
|
||||
pass
|
||||
self._color_temp = self._device.color_temp()
|
||||
|
||||
@property
|
||||
def brightness(self):
|
||||
"""Return the brightness of the light."""
|
||||
return self._brightness
|
||||
|
||||
# @property
|
||||
# def hs_color(self):
|
||||
# """Return the hs_color of the light."""
|
||||
# return (self._device.color_hsv()[0],self._device.color_hsv()[1])
|
||||
|
||||
@property
|
||||
def color_temp(self):
|
||||
"""Return the color_temp of the light."""
|
||||
try:
|
||||
return int(MAX_MIRED - (((MAX_MIRED - MIN_MIRED) / 255) * self._color_temp))
|
||||
except TypeError:
|
||||
pass
|
||||
|
||||
@property
|
||||
def min_mireds(self):
|
||||
"""Return color temperature min mireds."""
|
||||
return MIN_MIRED
|
||||
|
||||
@property
|
||||
def max_mireds(self):
|
||||
"""Return color temperature max mireds."""
|
||||
return MAX_MIRED
|
||||
|
||||
def turn_on(self, **kwargs):
|
||||
"""Turn on or control the light."""
|
||||
log.debug("Turning on, state: " + str(self._device.cached_status()))
|
||||
if not self._device.cached_status():
|
||||
self._device.set_status(True, self._bulb_id)
|
||||
if ATTR_BRIGHTNESS in kwargs:
|
||||
converted_brightness = int(kwargs[ATTR_BRIGHTNESS])
|
||||
if converted_brightness <= 25:
|
||||
converted_brightness = 25
|
||||
self._device.set_brightness(converted_brightness)
|
||||
if ATTR_HS_COLOR in kwargs:
|
||||
raise ValueError(" TODO implement RGB from HS")
|
||||
if ATTR_COLOR_TEMP in kwargs:
|
||||
color_temp = int(255 - (255 / (MAX_MIRED - MIN_MIRED)) * (int(kwargs[ATTR_COLOR_TEMP]) - MIN_MIRED))
|
||||
self._device.set_color_temp(color_temp)
|
||||
|
||||
def turn_off(self, **kwargs):
|
||||
"""Turn Tuya switch off."""
|
||||
self._device.set_status(False, self._bulb_id)
|
||||
|
||||
@property
|
||||
def supported_features(self):
|
||||
"""Flag supported features."""
|
||||
supports = SUPPORT_BRIGHTNESS
|
||||
#if self._device.support_color():
|
||||
# supports = supports | SUPPORT_COLOR
|
||||
supports = supports | SUPPORT_COLOR_TEMP
|
||||
return supports
|
File diff suppressed because it is too large
Load Diff
@@ -1,168 +1,175 @@
|
||||
"""
|
||||
Simple platform to control **SOME** Tuya switch devices.
|
||||
|
||||
For more details about this platform, please refer to the documentation at
|
||||
https://home-assistant.io/components/switch.tuya/
|
||||
"""
|
||||
import voluptuous as vol
|
||||
from homeassistant.components.switch import SwitchDevice, PLATFORM_SCHEMA
|
||||
from homeassistant.const import (CONF_NAME, CONF_HOST, CONF_ID, CONF_SWITCHES, CONF_FRIENDLY_NAME, CONF_ICON)
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
from time import time
|
||||
from threading import Lock
|
||||
|
||||
REQUIREMENTS = ['pytuya==7.0.4']
|
||||
|
||||
CONF_DEVICE_ID = 'device_id'
|
||||
CONF_LOCAL_KEY = 'local_key'
|
||||
|
||||
DEFAULT_ID = '1'
|
||||
|
||||
ATTR_CURRENT = 'current'
|
||||
ATTR_CURRENT_CONSUMPTION = 'current_consumption'
|
||||
ATTR_VOLTAGE = 'voltage'
|
||||
|
||||
SWITCH_SCHEMA = vol.Schema({
|
||||
vol.Optional(CONF_ID, default=DEFAULT_ID): cv.string,
|
||||
vol.Optional(CONF_FRIENDLY_NAME): cv.string,
|
||||
})
|
||||
|
||||
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
|
||||
vol.Optional(CONF_NAME): cv.string,
|
||||
vol.Optional(CONF_ICON): cv.icon,
|
||||
vol.Required(CONF_HOST): cv.string,
|
||||
vol.Required(CONF_DEVICE_ID): cv.string,
|
||||
vol.Required(CONF_LOCAL_KEY): cv.string,
|
||||
vol.Optional(CONF_ID, default=DEFAULT_ID): cv.string,
|
||||
vol.Optional(CONF_SWITCHES, default={}):
|
||||
vol.Schema({cv.slug: SWITCH_SCHEMA}),
|
||||
})
|
||||
|
||||
|
||||
def setup_platform(hass, config, add_devices, discovery_info=None):
|
||||
"""Set up of the Tuya switch."""
|
||||
import pytuya
|
||||
|
||||
devices = config.get(CONF_SWITCHES)
|
||||
switches = []
|
||||
|
||||
outlet_device = TuyaCache(
|
||||
pytuya.OutletDevice(
|
||||
config.get(CONF_DEVICE_ID),
|
||||
config.get(CONF_HOST),
|
||||
config.get(CONF_LOCAL_KEY)
|
||||
)
|
||||
)
|
||||
|
||||
for object_id, device_config in devices.items():
|
||||
switches.append(
|
||||
TuyaDevice(
|
||||
outlet_device,
|
||||
device_config.get(CONF_FRIENDLY_NAME, object_id),
|
||||
device_config.get(CONF_ICON),
|
||||
device_config.get(CONF_ID)
|
||||
)
|
||||
)
|
||||
|
||||
name = config.get(CONF_NAME)
|
||||
if name:
|
||||
switches.append(
|
||||
TuyaDevice(
|
||||
outlet_device,
|
||||
name,
|
||||
config.get(CONF_ICON),
|
||||
config.get(CONF_ID)
|
||||
)
|
||||
)
|
||||
|
||||
add_devices(switches)
|
||||
|
||||
class TuyaCache:
|
||||
"""Cache wrapper for pytuya.OutletDevice"""
|
||||
|
||||
def __init__(self, device):
|
||||
"""Initialize the cache."""
|
||||
self._cached_status = ''
|
||||
self._cached_status_time = 0
|
||||
self._device = device
|
||||
self._lock = Lock()
|
||||
|
||||
def __get_status(self):
|
||||
for i in range(3):
|
||||
try:
|
||||
status = self._device.status()
|
||||
return status
|
||||
except ConnectionError:
|
||||
if i+1 == 3:
|
||||
raise ConnectionError("Failed to update status.")
|
||||
|
||||
def set_status(self, state, switchid):
|
||||
"""Change the Tuya switch status and clear the cache."""
|
||||
self._cached_status = ''
|
||||
self._cached_status_time = 0
|
||||
return self._device.set_status(state, switchid)
|
||||
|
||||
def status(self):
|
||||
"""Get state of Tuya switch and cache the results."""
|
||||
self._lock.acquire()
|
||||
try:
|
||||
now = time()
|
||||
if not self._cached_status or now - self._cached_status_time > 20:
|
||||
self._cached_status = self.__get_status()
|
||||
self._cached_status_time = time()
|
||||
return self._cached_status
|
||||
finally:
|
||||
self._lock.release()
|
||||
|
||||
class TuyaDevice(SwitchDevice):
|
||||
"""Representation of a Tuya switch."""
|
||||
|
||||
def __init__(self, device, name, icon, switchid):
|
||||
"""Initialize the Tuya switch."""
|
||||
self._device = device
|
||||
self._name = name
|
||||
self._state = False
|
||||
self._icon = icon
|
||||
self._switchid = switchid
|
||||
self._status = self._device.status()
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
"""Get name of Tuya switch."""
|
||||
return self._name
|
||||
|
||||
@property
|
||||
def is_on(self):
|
||||
"""Check if Tuya switch is on."""
|
||||
return self._state
|
||||
|
||||
@property
|
||||
def device_state_attributes(self):
|
||||
attrs = {}
|
||||
try:
|
||||
attrs[ATTR_CURRENT] = "{}".format(self._status['dps']['104'])
|
||||
attrs[ATTR_CURRENT_CONSUMPTION] = "{}".format(self._status['dps']['105']/10)
|
||||
attrs[ATTR_VOLTAGE] = "{}".format(self._status['dps']['106']/10)
|
||||
except KeyError:
|
||||
pass
|
||||
return attrs
|
||||
|
||||
@property
|
||||
def icon(self):
|
||||
"""Return the icon."""
|
||||
return self._icon
|
||||
|
||||
def turn_on(self, **kwargs):
|
||||
"""Turn Tuya switch on."""
|
||||
self._device.set_status(True, self._switchid)
|
||||
|
||||
def turn_off(self, **kwargs):
|
||||
"""Turn Tuya switch off."""
|
||||
self._device.set_status(False, self._switchid)
|
||||
|
||||
def update(self):
|
||||
"""Get state of Tuya switch."""
|
||||
status = self._device.status()
|
||||
self._status= status
|
||||
self._state = status['dps'][self._switchid]
|
||||
|
||||
"""
|
||||
Simple platform to control LOCALLY Tuya switch devices.
|
||||
|
||||
Sample config yaml
|
||||
|
||||
switch:
|
||||
- platform: localtuya
|
||||
host: 192.168.0.1
|
||||
local_key: 1234567891234567
|
||||
device_id: 12345678912345671234
|
||||
name: tuya_01
|
||||
protocol_version: 3.3
|
||||
"""
|
||||
import voluptuous as vol
|
||||
from homeassistant.components.switch import SwitchDevice, PLATFORM_SCHEMA
|
||||
from homeassistant.const import (CONF_HOST, CONF_ID, CONF_SWITCHES, CONF_FRIENDLY_NAME, CONF_ICON, CONF_NAME)
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
from time import time, sleep
|
||||
from threading import Lock
|
||||
|
||||
REQUIREMENTS = ['pytuya==7.0.7']
|
||||
|
||||
CONF_DEVICE_ID = 'device_id'
|
||||
CONF_LOCAL_KEY = 'local_key'
|
||||
CONF_PROTOCOL_VERSION = 'protocol_version'
|
||||
CONF_CURRENT = 'current'
|
||||
CONF_CURRENT_CONSUMPTION = 'current_consumption'
|
||||
CONF_VOLTAGE = 'voltage'
|
||||
|
||||
DEFAULT_ID = '1'
|
||||
DEFAULT_PROTOCOL_VERSION = 3.3
|
||||
|
||||
ATTR_CURRENT = 'current'
|
||||
ATTR_CURRENT_CONSUMPTION = 'current_consumption'
|
||||
ATTR_VOLTAGE = 'voltage'
|
||||
|
||||
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
|
||||
vol.Optional(CONF_ICON): cv.icon,
|
||||
vol.Required(CONF_HOST): cv.string,
|
||||
vol.Required(CONF_DEVICE_ID): cv.string,
|
||||
vol.Required(CONF_LOCAL_KEY): cv.string,
|
||||
vol.Required(CONF_NAME): cv.string,
|
||||
vol.Required(CONF_PROTOCOL_VERSION, default=DEFAULT_PROTOCOL_VERSION): vol.Coerce(float),
|
||||
vol.Optional(CONF_ID, default=DEFAULT_ID): cv.string,
|
||||
vol.Optional(CONF_CURRENT, default='4'): cv.string,
|
||||
vol.Optional(CONF_CURRENT_CONSUMPTION, default='5'): cv.string,
|
||||
vol.Optional(CONF_VOLTAGE, default='6'): cv.string,
|
||||
})
|
||||
|
||||
|
||||
def setup_platform(hass, config, add_devices, discovery_info=None):
|
||||
"""Set up of the Tuya switch."""
|
||||
from . import pytuya
|
||||
|
||||
switches = []
|
||||
pytuyadevice = pytuya.OutletDevice(config.get(CONF_DEVICE_ID), config.get(CONF_HOST), config.get(CONF_LOCAL_KEY))
|
||||
pytuyadevice.set_version(float(config.get(CONF_PROTOCOL_VERSION)))
|
||||
|
||||
outlet_device = TuyaCache(pytuyadevice)
|
||||
switches.append(
|
||||
TuyaDevice(
|
||||
outlet_device,
|
||||
config.get(CONF_NAME),
|
||||
config.get(CONF_ICON),
|
||||
config.get(CONF_ID),
|
||||
config.get(CONF_CURRENT),
|
||||
config.get(CONF_CURRENT_CONSUMPTION),
|
||||
config.get(CONF_VOLTAGE)
|
||||
)
|
||||
)
|
||||
#print('Setup localtuya switch [{}] with device ID [{}] '.format(config.get(CONF_NAME), config.get(CONF_ID)))
|
||||
|
||||
add_devices(switches)
|
||||
|
||||
class TuyaCache:
|
||||
"""Cache wrapper for pytuya.OutletDevice"""
|
||||
|
||||
def __init__(self, device):
|
||||
"""Initialize the cache."""
|
||||
self._cached_status = ''
|
||||
self._cached_status_time = 0
|
||||
self._device = device
|
||||
self._lock = Lock()
|
||||
|
||||
def __get_status(self):
|
||||
for i in range(20):
|
||||
try:
|
||||
status = self._device.status()
|
||||
return status
|
||||
except ConnectionError:
|
||||
if i+1 == 3:
|
||||
raise ConnectionError("Failed to update status.")
|
||||
|
||||
def set_status(self, state, switchid):
|
||||
"""Change the Tuya switch status and clear the cache."""
|
||||
self._cached_status = ''
|
||||
self._cached_status_time = 0
|
||||
for i in range(20):
|
||||
try:
|
||||
return self._device.set_status(state, switchid)
|
||||
except ConnectionError:
|
||||
if i+1 == 5:
|
||||
raise ConnectionError("Failed to set status.")
|
||||
|
||||
def status(self):
|
||||
"""Get state of Tuya switch and cache the results."""
|
||||
self._lock.acquire()
|
||||
try:
|
||||
now = time()
|
||||
if not self._cached_status or now - self._cached_status_time > 30:
|
||||
sleep(0.5)
|
||||
self._cached_status = self.__get_status()
|
||||
self._cached_status_time = time()
|
||||
return self._cached_status
|
||||
finally:
|
||||
self._lock.release()
|
||||
|
||||
class TuyaDevice(SwitchDevice):
|
||||
"""Representation of a Tuya switch."""
|
||||
|
||||
def __init__(self, device, name, icon, switchid, attr_current, attr_consumption, attr_voltage):
|
||||
"""Initialize the Tuya switch."""
|
||||
self._device = device
|
||||
self._name = name
|
||||
self._icon = icon
|
||||
self._switch_id = switchid
|
||||
self._attr_current = attr_current
|
||||
self._attr_consumption = attr_consumption
|
||||
self._attr_voltage = attr_voltage
|
||||
self._status = self._device.status()
|
||||
self._state = self._status['dps'][self._switch_id]
|
||||
print('Initialized tuya switch [{}] with switch status [{}] and state [{}]'.format(self._name, self._status, self._state))
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
"""Get name of Tuya switch."""
|
||||
return self._name
|
||||
|
||||
@property
|
||||
def is_on(self):
|
||||
"""Check if Tuya switch is on."""
|
||||
return self._state
|
||||
|
||||
@property
|
||||
def device_state_attributes(self):
|
||||
attrs = {}
|
||||
try:
|
||||
attrs[ATTR_CURRENT] = "{}".format(self._status['dps'][self._attr_current])
|
||||
#print('attrs[ATTR_CURRENT]: [{}]'.format(attrs[ATTR_CURRENT]))
|
||||
attrs[ATTR_CURRENT_CONSUMPTION] = "{}".format(self._status['dps'][self._attr_consumption]/10)
|
||||
#print('attrs[ATTR_CURRENT_CONSUMPTION]: [{}]'.format(attrs[ATTR_CURRENT_CONSUMPTION]))
|
||||
attrs[ATTR_VOLTAGE] = "{}".format(self._status['dps'][self._attr_voltage]/10)
|
||||
#print('attrs[ATTR_VOLTAGE]: [{}]'.format(attrs[ATTR_VOLTAGE]))
|
||||
|
||||
except KeyError:
|
||||
pass
|
||||
return attrs
|
||||
|
||||
@property
|
||||
def icon(self):
|
||||
"""Return the icon."""
|
||||
return self._icon
|
||||
|
||||
def turn_on(self, **kwargs):
|
||||
"""Turn Tuya switch on."""
|
||||
self._device.set_status(True, self._switch_id)
|
||||
|
||||
def turn_off(self, **kwargs):
|
||||
"""Turn Tuya switch off."""
|
||||
self._device.set_status(False, self._switch_id)
|
||||
|
||||
def update(self):
|
||||
"""Get state of Tuya switch."""
|
||||
self._status = self._device.status()
|
||||
self._state = self._status['dps'][self._switch_id]
|
||||
|
Reference in New Issue
Block a user