there is a news for this component? don’t work for me
with HA 99.2
Hello to all and specially to @Fraschi.
@Fraschi did a lot of work with this plugin. Thanks to him.
Unfortunatelly ATM custom component doesn’t work with HA 0.99.2.
As I can see from the code there are some caveats.
- Plugin uses old climate integration constants. I have modified STATE_HEAT to HVAC_MODE_HEAT and so in. Some constans doesn’t have analogs in new version. for example STATE_ECO. Now You need to use PRESET_ECO with mode HVAC_MODE_HEAT.
- Plugin require pytuya package. It is not included in HASSIO 0.99.2. Maybe it can be included in customized_components/localtuya. I didn’t test it ATM.
I can try to help @Fraschi if he need so but I’m not a python programmer.
Cheers.
Yes, I know. Actually I’ve modded my devices by changing the firmware (https://github.com/klausahrenberg/ThermostatBecaWifi), so I will not update that plugin anymore.
With the mod i can use the device as a full supported mqtt thermostat, it’s much simplier and I will not have the migration/compatibility problem anymore.
In previous migration I’ve made some copy/paste from other (already migrated) thermostat in home assistant climate. Usually the best is change the code (the latest i’ve provided) by matching it with the “generic thermostat” or similiar devices (https://github.com/home-assistant/home-assistant/tree/dev/homeassistant/components/generic_thermostat)
@Fraschi thanks for an answer.
I supposed You have switched to FW change method. I think about too.
Did You soldered wires to your thermostats or used OTA method? https://github.com/ct-Open-Source/tuya-convert.
I’ve soldered wires, didn’t know about ota on stock devices
OK guys,
Update: I don’t understand how to attach files. May some help me with that?
Update1 I have posted climate.py file content.
Update2 I forgot I have hardcoded protocol version. Have updated a code.
Update3 Author of pytuya has updated a component to version 7.0.5. So no more need to “hack” HASSIO. You can just install a component and use it.
I have modified plugin. It’s a very early alfa vetrsion. I don’t promise I will continue a development.
I don’t know how it will work in reallife. I change parameters over HA and ai see a result from Thermostat. But i’m sure I don’t know all scenarios.
Caveats:
It need pytuya 7.0.4. It is not released on pypi.org. So it cannot be installed automatically by HA. Workaround on HA installed under Linux:
git clone https://github.com/clach04/python-tuya
pip install ./python-tuya
b. Workaround under HASSIO:
It’s hard. You need to enter hassos (ssh://hassio_host:22222) and start login session (just write login and press enter)
Welcome on Hass.io CLI.
For more details use 'help' and 'exit' to close.
If you need access to host system use 'login'.
hassio > login
# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
42d6e813ec54 homeassistant/armv7-hassio-dns:1 "coredns -conf /conf…" 45 hours ago Up 45 hours hassio_dns
e98e4d35b482 homeassistant/armv7-hassio-supervisor "/bin/entry.sh pytho…" 45 hours ago Up 45 hours hassos_supervisor
097576cb9fd6 homeassistant/armv7-addon-ssh:6.4 "/run.sh" 5 days ago Up 5 days 0.0.0.0:22->22/tcp addon_core_ssh
c495238ac9e3 homeassistant/raspberrypi3-homeassistant:0.99.2 "/bin/entry.sh pytho…" 5 days ago Up 15 minutes homeassistant
# docker exec -it c495238ac9e3 /bin/bash
bash-5.0# git clone https://github.com/clach04/python-tuya
bash-5.0# pip install ./python-tuya
bash-5.0# pip list|grep pytuya
pytuya 7.0.4
bash-5.0#
In theory it’s all. At least it works on my site.
!!!Attention!!!
After HASSIO update I think pytuya 7.0.4 will be uninstalled. So it’s better to disable thermostat in configuration, update hassio, install pytuya 7.0.4 and re-enable thermostat in configuration.
Next:
Create directory structure
/config/custom_components/localtuya
place files into it:
__init__.py - empty file
climate.py
climate.py file content:
"""
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 logging
import asyncio
from homeassistant.components.climate.const import (
ATTR_PRESET_MODE,
ATTR_PRESET_MODES,
SUPPORT_TARGET_TEMPERATURE,
SUPPORT_PRESET_MODE,
HVAC_MODE_HEAT,
HVAC_MODE_OFF,
HVAC_MODE_AUTO,
PRESET_AWAY,
PRESET_NONE
)
from homeassistant.components.climate import (PLATFORM_SCHEMA, ENTITY_ID_FORMAT, ClimateDevice)
from homeassistant.const import (CONF_NAME, CONF_HOST, CONF_ID, PRECISION_WHOLE, TEMP_CELSIUS, TEMP_FAHRENHEIT , ATTR_TEMPERATURE)
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from time import time
from time import sleep
from threading import Lock
REQUIREMENTS = ['pytuya==7.0.4']
_LOGGER = logging.getLogger(__name__)
CONF_DEVICE_ID = 'device_id'
CONF_LOCAL_KEY = 'local_key'
CONF_MIN_TEMP = 'min_temp'
CONF_MAX_TEMP = 'max_temp'
CONF_PROTOCOL_VERSION = 'protocol_version'
DEVICE_TYPE = 'climate'
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Optional(CONF_NAME): cv.string,
vol.Required(CONF_HOST): cv.string,
vol.Required(CONF_DEVICE_ID): cv.string,
vol.Required(CONF_LOCAL_KEY): cv.string,
vol.Optional(CONF_MIN_TEMP): vol.Coerce(float),
vol.Optional(CONF_MAX_TEMP): vol.Coerce(float),
vol.Optional(CONF_PROTOCOL_VERSION): vol.Coerce(float)
})
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up of the Tuya switch."""
import pytuya
name = config.get(CONF_NAME)
dev_id = config.get(CONF_DEVICE_ID)
host = config.get(CONF_HOST)
local_key = config.get(CONF_LOCAL_KEY)
min_temp = config.get(CONF_MIN_TEMP)
max_temp = config.get(CONF_MAX_TEMP)
protocol_version = config.get(CONF_PROTOCOL_VERSION)
climate = []
climate_device = TuyaCache(
pytuya.OutletDevice(
config.get(CONF_DEVICE_ID),
config.get(CONF_HOST),
config.get(CONF_LOCAL_KEY)
),
protocol_version
)
climate.append(
TuyaClimate(
climate_device,
config.get(CONF_NAME),
None,
None,
None,
None,
TEMP_CELSIUS,
min_temp,
max_temp,
protocol_version
)
)
async_add_entities(climate)
class TuyaCache:
def __init__(self, device, protocol_version):
"""Initialize the cache."""
self._cached_status = ''
self._cached_status_time = 0
self._device = device
self._protocol_version = protocol_version
self._lock = Lock()
def __get_status(self):
for i in range(5):
try:
self._device.set_version(self._protocol_version)
status = self._device.status()
_LOGGER.debug("Debug LocalTuya: " + str(status))
return status
except ConnectionError:
if i+1 == 5:
_LOGGER.warning("Failed to update status")
raise ConnectionError("Failed to update status.")
def set_status(self, state, switchid):
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()
_LOGGER.debug("UPDATING status")
self._device.set_version(self._protocol_version)
self._cached_status = self.__get_status()
self._cached_status_time = time()
return self._cached_status
finally:
self._lock.release()
class TuyaClimate(ClimateDevice):
"""Representation of a Tuya switch."""
def __init__(self, device, name, target_temperature, current_temperature, hvac_mode, preset_mode, unit_of_measurement, min_temp, max_temp, protocol_version):
"""Initialize the Tuya switch."""
self._device = device
self._name = name
self._lock = Lock()
self._target_temperature = target_temperature
self._current_temperature = current_temperature
self._hvac_mode = hvac_mode
self._preset_mode = preset_mode
self._unit_of_measurement = unit_of_measurement
self._min_temp = min_temp
self._max_temp = max_temp
self._support_flags = SUPPORT_TARGET_TEMPERATURE | SUPPORT_PRESET_MODE
self._temp_precision = 0.5
self._hvac_modes = [HVAC_MODE_HEAT, HVAC_MODE_AUTO, HVAC_MODE_OFF]
self._preset_modes = [PRESET_AWAY, PRESET_NONE]
status = self._device.status()
@property
def min_temp(self):
"""Return the minimum temperature."""
if self._min_temp:
return self._min_temp
# get default temp from super class
return super().min_temp
@property
def max_temp(self):
"""Return the maximum temperature."""
if self._max_temp:
return self._max_temp
# Get default temp from super class
return super().max_temp
@property
def hvac_modes(self):
"""Return the list of available operation modes."""
return self._hvac_modes
@property
def name(self):
"""Get name of Tuya switch."""
return self._name
@property
def current_temperature(self):
"""Return the sensor temperature."""
return self._current_temperature
@property
def hvac_mode(self):
"""Return current operation."""
return self._hvac_mode
@property
def preset_modes(self):
"""Return the list of available preset modes."""
return self._preset_modes
@property
def preset_mode(self):
"""Return preset status."""
return self._preset_mode
@property
def target_temperature(self):
"""Return the temperature we try to reach."""
return self._target_temperature
@property
def temperature_unit(self):
"""Return the unit of measurement."""
return self._unit_of_measurement
@property
def supported_features(self):
"""Return the list of supported features."""
return self._support_flags
async def async_turn_on(self, **kwargs):
"""Turn Tuya switch on."""
self._lock.acquire()
self._device.set_status(True, '1')
self._lock.release()
async def async_turn_off(self, **kwargs):
"""Turn Tuya switch off."""
self._lock.acquire()
self._device.set_status(False, '1')
self._lock.release()
async def async_set_temperature(self, **kwargs):
while True:
try:
self._lock.acquire()
temperature = int(float(kwargs[ATTR_TEMPERATURE])*2)
_LOGGER.debug("Set Temperature: " + str(temperature))
if ATTR_TEMPERATURE in kwargs:
self._device.set_status(temperature, '2')
sleep(1)
self._lock.release()
except:
_LOGGER.warning("Set Temperature Retry")
continue
break
async def async_set_hvac_mode(self, hvac_mode):
"""Set operation mode."""
self._lock.acquire()
if hvac_mode == HVAC_MODE_HEAT:
self._device.set_status(True, '1')
self._device.set_status( '1' , '4')
elif hvac_mode == HVAC_MODE_AUTO:
self._device.set_status(True, '1')
self._device.set_status( '0' , '4')
elif hvac_mode == HVAC_MODE_OFF:
self._device.set_status(False, '1')
else:
_LOGGER.error("Unrecognized operation mode: %s", hvac_mode)
return
sleep(1)
self.schedule_update_ha_state()
self._lock.release()
async def async_set_preset_mode(self, preset_mode):
"""Set eco preset."""
self._lock.acquire()
if preset_mode == PRESET_AWAY:
self._device.set_status( True , '5')
elif preset_mode == PRESET_NONE:
self._device.set_status( False , '5')
else:
_LOGGER.error("Unrecognized preset mode: %s", preset_mode)
return
sleep(1)
self.schedule_update_ha_state()
self._lock.release()
async def async_update(self):
"""Get state of Tuya switch."""
_LOGGER.debug("UPDATING")
try:
status = self._device.status()
self._target_temperature = float(status['dps']['2']) /2
self._current_temperature = float(status['dps']['3']) /2
self._state = status['dps']['1']
auto_manual = status['dps']['4']
eco_mode = status['dps']['5']
on_off = status['dps']['1']
_LOGGER.debug("Device: " + str(status['devId']))
if on_off == False:
self._hvac_mode = HVAC_MODE_OFF
if on_off == True and auto_manual == '0':
self._hvac_mode = HVAC_MODE_AUTO
if on_off == True and auto_manual == '1':
self._hvac_mode = HVAC_MODE_HEAT
if eco_mode == True:
self._preset_mode = PRESET_AWAY
else:
self._preset_mode = PRESET_NONE
except:
_LOGGER.debug("Update Fail, maybe device busy")
modify Your configuration.yaml with this parameters:
climate:
- platform: localtuya
host: 192.168.x.x (your thermostat IP)
local_key: thermostat local_key
device_id: thermostat local_id
name: thermostat name
scan_interval: 5
min_temp: 5
max_temp: 35
protocol_version: 3.3
That should work. Maybe some of You still have old FW and software for thermostat. In that case You can user protocol version 3.1 and You DON’T need pytuya 7.0.4. You can skip steps to install this version. But You need to change requirements in climate.py file
# change this
REQUIREMENTS = ['pytuya==7.0.4']
# to this
REQUIREMENTS = ['pytuya==7.0.2']
That’s the config for the mqtt way, change the topic accordingly to your setup:
climate:
- platform: mqtt
name: Camera
value_template: >-
{% set values = {'false':'auto','true':'heat'} %}
{{ values[value] if value in values.keys() else value }}
modes:
- "heat"
- "auto"
- "off"
initial: 5
mode_command_topic: "termostato/camera/mode"
temperature_command_topic: "termostato/camera/desiredTemperature"
mode_state_topic: "termostato/camera/state"
mode_state_template: "{% if value_json.actualTemperature > value_json.desiredTemperature %}
off
{% else %}
{% if value_json.manualMode == true %}
heat
{% else %}
auto
{% endif %}
{% endif %}"
current_temperature_topic: "termostato/camera/state"
current_temperature_template: "{{ value_json.actualTemperature }}"
temperature_state_topic: "termostato/camera/state"
temperature_state_template: "{{ value_json.desiredTemperature }}"
min_temp: 5
max_temp: 35
temp_step: 0.5
wow, very Thanks
sorry if I ask you, were you able to configure the rest as well? how to switch the thermostat on and off? and its other functions as locked and ecomode? and the weekly programming? Thanks
In order: lock, screen, eco
- platform: mqtt
name: "Lock Termostato Camera"
state_topic: 'termostato/camera/state'
value_template: "{{ value_json.locked }}"
command_topic: 'termostato/camera/locked'
payload_on: "true"
payload_off: "false"
state_on: true
state_off: false
qos: 0
retain: false
- platform: mqtt
name: "Schermo Termostato Camera"
state_topic: 'termostato/camera/state'
value_template: "{{ value_json.deviceOn }}"
command_topic: 'termostato/camera/deviceOn'
payload_on: "true"
payload_off: "false"
state_on: true
state_off: false
qos: 0
retain: false
- platform: mqtt
name: "Eco Mode Termostato Camera"
state_topic: 'termostato/camera/state'
value_template: "{{ value_json.ecoMode }}"
command_topic: 'termostato/camera/ecoMode'
payload_on: "true"
payload_off: "false"
state_on: true
state_off: false
qos: 0
retain: false
Binary sensor for on/off status:
- platform: template
sensors:
termostato_camera:
friendly_name: "Stato Termostato Camera"
value_template: "{{ (state_attr('climate.camera','current_temperature')) < (state_attr('climate.camera','temperature')) }}"
Temperature Report Sensors: current and desidered
- platform: template
sensors:
temperatura_camera:
friendly_name: "Temperatura Camera"
unit_of_measurement: '°C'
value_template: "{{ (state_attr('climate.camera','current_temperature')) }}"
temperatura_termostato_camera:
friendly_name: "Termostato Camera"
unit_of_measurement: '°C'
value_template: "{{ (state_attr('climate.camera','temperature')) }}"
That’s all I’ve configured, To manually turn on/off the thermostat internal relay maybe a workaround is possible: Make a template switch that sets the temperature to max temp / min temp.
Thank you, I don’t know why on 3 thermostats one makes a fuss, when ravvio home assistant lights up and goes off and I have to switch it on manually again.I prvatyo to reset it and ring it but nothing. Thanks cmq for everything.
I’ve similar problem on hass restart (temperature setting was wrong). Probably is something related to mqtt retain. Try to make an automation that sets correct desidered value on hass restart.
Sorry, to get the configuration working with that config,
climate:
- platform: mqtt
name: Camera
value_template: >-
{% set values = {'false':'auto','true':'heat'} %}
{{ values[value] if value in values.keys() else value }}
modes:
- "heat"
- "auto"
- "off"
initial: 5
mode_command_topic: "termostato/camera/mode"
temperature_command_topic: "termostato/camera/desiredTemperature"
mode_state_topic: "termostato/camera/state"
mode_state_template: "{% if value_json.actualTemperature > value_json.desiredTemperature %}
off
{% else %}
{% if value_json.manualMode == true %}
heat
{% else %}
auto
{% endif %}
{% endif %}"
current_temperature_topic: "termostato/camera/state"
current_temperature_template: "{{ value_json.actualTemperature }}"
temperature_state_topic: "termostato/camera/state"
temperature_state_template: "{{ value_json.desiredTemperature }}"
min_temp: 5
max_temp: 35
temp_step: 0.5
You have to add that automations:
- alias: 'hvac_auto camera'
trigger:
platform: mqtt
topic: termostato/camera/mode
payload: 'auto'
action:
service: mqtt.publish
data_template:
topic: 'termostato/camera/manualMode'
payload: 'false'
- alias: 'hvac_man camera'
trigger:
platform: mqtt
topic: termostato/camera/mode
payload: 'heat'
action:
service: mqtt.publish
data_template:
topic: 'termostato/camera/manualMode'
payload: 'true'
- alias: 'hvac_off camera'
trigger:
platform: mqtt
topic: termostato/camera/mode
payload: 'off'
action:
- service: mqtt.publish
data_template:
topic: 'termostato/camera/manualMode'
payload: 'true'
- service: mqtt.publish
data_template:
topic: 'termostato/camera/desiredTemperature'
payload: '5'
About schedules and other mqtt commands refer to https://github.com/klausahrenberg/WThermostatBeca
but keep in mind that where the mqtt command is:
<YOUR_TOPIC>/schedules/0
it means
<YOUR_TOPIC>/schedules
and 0
as PayLoad for readings
for setting the schedules the Payload is in Json Format
Hey, awesome work, if that really works!
But I can’t get the custom component to work. I’ve created all the files and edited the climate.py file.
How do I get that custom component to show up in my lovelace UI though? I am struggleing with that atm.
Your climate.py file has a syntax error at the end. “_LOGGER.debug(“Update Fail, maybe device busy”)” rather than “_LOGGER.debug(“Update Fail, maybe device busy”)```”
Thanks, fixed that.
I didn’t get your custom component to work though! Does it work for you?
I managed to flash my thermostat with a custom sonoff software and made a mqtt climate component.
Well, yes it does. But, as many people before me and i’m sure after me, I have soldered thermostate and changed firmware. There is one fatal caveat using thermostat with original firmware.
You cannot close internetl access for it. Because there is only one way it cat get current time - by connection to tuya servers. You cannot set NTP server or somethong similar on it.
So, it’s better to change firmware and.
Hi, can you explain your setup to flash the new firmware?
I have a BHT-6000 but I’m not able to put It in programming mode with serial method.
I followed klausahrenberg flashing page but It doesn’t work for my device.
Esptool Is unable to connect.
As I remember I’ve followed the setup in https://github.com/klausahrenberg/WThermostatBeca/blob/2df063b09bcd5a56616c81802e1ade4b8fc4e5db/Flashing.md
Before soldering try the solderless option, I’ve read some good report about that.
For the solder-way try with a different ftdi converter, as I remember, I had some issues with one of mine.