BHT-6000 Thermostat (tuya) support

In 0.88 the custom component is not working anymore, the temperature is doubled again…
I’ve tried to create the localtuya dir and rename the old file in climate.py, but the temperature is still wrong

Wait… Which component? I refer to the localtuya (the one with local readings) and not to the modified tuya.py. The localtuya works with the modification in folder structure, see previous post (I have two devices correctly working in hass 0.88.1). I’m not using anymore the modified tuya.py so I didn’t watch if it still works or what is needed to get it work.
The localtuya is a custom_components, the tuya.py is an overlay to the existing hass support. Maybe is sufficient to follow the previous post (naming the directory tuya) or maybe a complete climate overlay is needed (refer to https://developers.home-assistant.io/blog/2019/02/19/the-great-migration.html). Probably hass is not loading the modified tuya and uses the official one, take a look to the logs

Thank you Fraschi, I’m not using the local component… sorry

I was using your component in home assistant 0.88. 2 with the new configuration folder all is good but now platform not found in home assistant 0.89.1

1 Like

try this climate.yaml (9.0 KB) (rename to climate.py)
It’s not fully tested but seems to work in 89.1
The problem was on the imports, some homeassistant climate const where moved in recent updates.

As already told, when issues happens provide hass version and relevant log output, and at least a thanks is apreciated, when the problem gets solved as in past. Helping in that way is unpleasant.

1 Like

I try now wait 5 minute and I will give you a response

All is good thank you @Fraschi

1 Like

Thank you! I’m very appreciate that. It’s working again for me as well! :wink:

1 Like

No news about tuya component update no localtuya for read temperature in good way in Google???

Have you see https://github.com/klausahrenberg/ThermostatBecaWifi

Bye

Tiziano

1 Like

Cool, I’ve seen other modded firmware but not this, I’m waiting for a second device to make some try. Probably for the bht-6000 some byte addresses must be changed. Thanks

Lo has podido solucionar?
Como lo has echo?

Que puedo hacer con este?
No se como en el HA poner la temperatura normal. Sale el doble. Y como puedo hacer para que cuando baje de una temperatura determinada me encienda un interruptor?
Hice lo que pones en un tutorías pero nada. No me funciona. Échame un cable porfa

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.

  1. 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.
  2. 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)

1 Like

@Fraschi thanks for an answer.

I supposed You have switched to FW change method. :wink: 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. :wink:

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