[
  {
    "path": ".github/ISSUE_TEMPLATE/bug_report.md",
    "content": "---\nname: Bug report\nabout: Create a report to help us improve\ntitle: ''\nlabels: ''\nassignees: ''\n---\n\n**!!! Please Read This First !!!**\nIf you are having difficulty controlling a specific device, please verify that the device works with tuya-cli prior to opening an issue here.  If you are unable to control the device via tuya-cli it will not be possible to control it with tuya-mqtt.  If the device is working with tuya-cli, please post your working commands and the equivalent commands for tuya-mqtt.\n\n**Describe the bug**\nA clear and concise description of what the bug is.\n\n**To Reproduce**\nSteps to reproduce the behavior:\n1. Go to '...'\n2. Click on '....'\n3. Scroll down to '....'\n4. See error\n\n**Expected behavior**\nA clear and concise description of what you expected to happen.\n\n**Screenshots**\nIf applicable, add screenshots to help explain your problem.\n\n**Desktop (please complete the following information):**\n - OS: [e.g. iOS]\n - Browser [e.g. chrome, safari]\n - Version [e.g. 22]\n\n**Smartphone (please complete the following information):**\n - Device: [e.g. iPhone6]\n - OS: [e.g. iOS8.1]\n - Browser [e.g. stock browser, safari]\n - Version [e.g. 22]\n\n**Additional context**\nAdd any other context about the problem here.\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/feature_request.md",
    "content": "---\nname: Feature request\nabout: Suggest an idea for this project\ntitle: ''\nlabels: ''\nassignees: ''\n\n---\n\n**!!! Please Read This First !!!**\nFeature requiest for this project are not being accepted at this time as this project is in maintainance mode only.\n"
  },
  {
    "path": ".gitignore",
    "content": "old/\ntest/\nconfig.json\n.vscode/\n.bak\n\n# Logs\nlogs\n*.log\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\n\n# Runtime data\npids\n*.pid\n*.seed\n*.pid.lock\n\n# Directory for instrumented libs generated by jscoverage/JSCover\nlib-cov\n\n# Coverage directory used by tools like istanbul\ncoverage\n\n# nyc test coverage\n.nyc_output\n\n# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)\n.grunt\n\n# Bower dependency directory (https://bower.io/)\nbower_components\n\n# node-waf configuration\n.lock-wscript\n\n# Compiled binary addons (https://nodejs.org/api/addons.html)\nbuild/Release\n\n# Dependency directories\nnode_modules/\njspm_packages/\n\n# TypeScript v1 declaration files\ntypings/\n\n# Optional npm cache directory\n.npm\n\n# Optional eslint cache\n.eslintcache\n\n# Optional REPL history\n.node_repl_history\n\n# Output of 'npm pack'\n*.tgz\n\n# Yarn Integrity file\n.yarn-integrity\n\n# dotenv environment variables file\n.env\n\n# next.js build output\n.next\n\n# vuepress build output\n.vuepress/dist\n\n# Serverless directories\n.serverless\n"
  },
  {
    "path": "CHANGELOG.md",
    "content": "# Changelog\r\nAll notable changes to this project will be documented in this file.\r\n\r\nThe format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).\r\n\r\n## [3.0.0]\r\nThe 3.0.0 release is a major refactor of the project with significant changes from previous version.  Only major additions and changes are listed below.\r\n### Added\r\n- Added templating engine for mapping device DPS value to friendly topics\r\n- Added pre-defined template for common devices\r\n- Command topics for DPS keys\r\n\r\n### Changed\r\n- Configuration for devices is now via devices.conf file (based on output format of 'tuya-cli wizard' command)\r\n- Default device presents only raw DPS data\r\n- Commands sent only via MQTT messages to command topics\r\n- Updates all libraries to latest version\r\n\r\n### Removed\r\n- Topic based configuraiton has been removed\r\n\r\n## [2.1.0]\r\n### Added\r\n- Added ability to update validate communicaton with device and update state topic by issuing { \"schema\": true } command\r\n- Added support for protocol 3.3 either via automatic device discovery or manual specification when using IP address\r\n\r\n### Changed\r\n- Can specify \"discover\" instead of IP address to automatically find device (only works if device on same IP subnet as system running this script).  This mode will also automatically detect 3.1 and 3.3 protocol devices\r\n- Can manually specific protocol via ver3.1/ver3.3 in topic line after tuya/\r\n- Bump Tuyapi version to v5.3.x\r\n- Bump MQTT version to v4.x.x\r\n- Moved openHAB config to it's own document since many users use this with other tools\r\n- Verious other fixes and cleanups\r\n\r\n## [2.0.1]\r\n### Added\r\n- Added capability to set multiple dps values over MQTT-Command\r\n- Custom Set-Function for TuyAPI-Class (added error handling for \"index [1] not found\" error)\r\n\r\n### Changed\r\n- MQTT-Topic no longer requires a device type\r\n- Updated TuyAPI to v4.x.x\r\n\r\n### Removed\r\n- remove device type from topic\r\n\r\n## [2.0.0]\r\n### Added\r\n- support for OH MQTT-Binding 2.4\r\n- default QoS of 2, if not set through config.json\r\n\r\n### Changed\r\n- Updated TuyAPI to v3.x.x\r\n- Constant off states after start #11\r\n\r\n### Removed\r\n- custom set function for TuyAPI\r\n\r\n## [1.0.0]\r\n### Added\r\n- Add ability to connect to protected MQTT server\r\n- Added seperate configuration file\r\n\r\n### Changed\r\n- TuyAPI repository not found\r\n\r\n### Removed\r\n"
  },
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2018 TheAgentK\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "# tuya-mqtt\n\n# !!!! Important Note !!!!\nThis project is currently in maintainance mode.  No further enhancements to this project are planned and will not be planned for the future unless someone out there is interested in becoming the new maintainer.  Please do not open issues to request new features, new device support, etc, as they will likely be closed with no comment.  I will try to support existing functionality, but even this will likely be on a very limited basis.  If you are interested in maintaining this project, please post [here](https://github.com/rospogrigio/localtuya/issues/194).\n\nI have decided to step away from this project as I've made the personal decision to rid myself of any Tuya Wifi based devices (I'm down to only 4 at this point, and they are all easy to replace or at least flash with Tasmota).  This decision was made due to the fact that Tuya continues to make it more and more difficult to control their devices locally.  While I don't blame them for this, these devices were only interesting to me because of this local control and thus I can no longer meet my personal goals with Tuya devices (at least the Wifi ones) so I will no longer be purchasing/using them going forward.\n\n# About\nThis project is a bridge that allows locally controlling IOT devices manufactured by Tuya Inc., and sold under many different brands, via simple MQTT topics.  It effectively translate the Tuya protocol to easy to use topics.\n\nUsing this script requires obtaining the device ID and local keys for each of your devices after they are configured via the Tuya/Smart Life or other Tuya compatible app (there are many).  With this information it is possible to communicate locally with Tuya devices using Tuya protocol version 3.1 and 3.3 without using the Tuya Cloud service, however, getting the keys requires signing up for a Tuya IOT developer account or using one of several other alternative methods (such as dumping the memory of a Tuya based app running on Android).\n\nTo acquire keys for your device please see the instructions at the TuyAPI project (on which this script is based) available at the [TuyAPI GitHub site](https://github.com/codetheweb/tuyapi/blob/master/docs/SETUP.md).\n\n**Acquiring device keys is outside the scope of this project!** Issues opened regarding acquiring keys will likely be closed without comment. Please verify that your device can be queried and controlled via tuya-cli before opening any issue.  If your device can't be controlled by tuya-cli then it cannot be used with this project.\n\n**!!!!!!!!!! Important information regarding the 3.0 release !!!!!!!!!!**\\\nThe 3.0.0 release (Oct 17th, 2020) is a major refactor of the tuya-mqtt project and, as such, is a breaking release for all users of previous versions.  Almost everything about the project is different, including configuration method, topic names, etc.  Upgrading users should carefully read the instructions below and assume they are starting over from scratch.\n\n## Installation\nDownload this project to your system into any directory (example below uses /opt/tuya-mqtt) and install tuyapi from the same folder that the tuya-mqtt.js is in\n```\n// switch to opt directory\ncd /opt\n\n// clone this project\ngit clone https://github.com/TheAgentK/tuya-mqtt\n\n// change directory to the project directory\ncd tuya-mqtt\n\n//installs this project along with codetheweb/tuyapi project\nnpm install\n```\n\n## Configuration\nTuya-mqtt has two different configuration files.  The first is config.json, a simple file which contains settings for connection to the MQTT broker.  The second is devices.conf, a JSON5 formatted file which defines the Tuya devices that the script should connect to and expose via MQTT.  This file uses the same basic format as the \"tuya-cli wizard\" outputs when used to acquire the device keys, so it can be used as the basis for your tuya-mqtt device configuration.\n\n### Setting up config.json:\n```\ncp config.json.sample config.json\n```\nEdit config.json with your MQTT broker settings and save:\n```\nnano config.json \n```\n\n### Setting up devices.conf:\nIf you use the \"tuya-cli wizard\" method to acquire your device keys you can leverage the output of this tool as the start of your devices.conf file.  Otherwise, you want to create a file using a formate like this:\n```\n[\n  {\n    name: 'Tuya Device 1',\n    id: '86435357d8b123456789',\n    key: '8b2a69c9876543210'\n  },\n  {\n    name: 'Tuya Device 2',\n    id: 'eb532eea7d12345678abc',\n    key: '899810012345678'\n  }\n]\n```\nNote that, because the format is JSON5, which is a superset of JSON, you can use standard, strict JSON syntax, or the more forgiving JSON5 format, or even mix and match in the same file.\n\nBy default tuya-mqtt will attempt to find the device and automatically detect the Tuya protocol version, however, this only works if the system running tuya-mqtt is on the same network/subnet as the devices being controlled.  If this is not the case, or if automatic detection fails for some other reason, it is possible to specify the IP address and protocol manually by adding the \"ip:\" property to the devices.conf file.  Note that if the IP address is specified manually it is required to also manually specify the protocol version using the \"version:\" parameter as either \"3.1\" or \"3.3\".  The easiest way to determine the protocol version is to try controlling the device with tuya-cli and try each version to see which one works.\n\nWhile the above syntax may be enough to create a working tuya-mqtt install with raw DPS values accessible via DPS topics, the full functionality of tuya-mqtt 3.0 is only unlocked by configuring device types to get.  Please see the full [DEVICES](docs/DEVICES.md) documentation for details.\n\n### Starting tuya-mqtt\n```\nnode tuya-mqtt.js\n```\nTo enable debugging output (required when opening an issue):\n```\nDEBUG=tuya-mqtt:* tuya-mqtt.js\n```\n\n### Updating devices.conf with new and/or changed devices:\nAfter adding or changing devices to your Tuya account the devices.conf file can be automatically updated with all new devices and name/key changes by using the merge-devices.js script.  Create a file named new-devices.conf with the new \"tuya-cli wizard\" output then run ```node merge-devices.js```.  A dated backup of the original devices.conf file will be created automatically before changes are made.  Devices are only added and updated, never removed.  The resulting devices.conf file will be neatly formatted and sorted alphabetically by device name.\n\nTo prevent device entries from being updated by the merge script, add property \"allowMerge: false\" to the device definition in the devices.conf file.\n\n### Usage Overview\nTuya devices work by mapping device functions to various values stored in data points (referred to as DPS values) which are referenced via an index number, referred to as the DPS key.  For example, a simple on/off switch may have a single DPS value, stored in DPS kep 1 (DPS1).  This value is likely to have a setting of true/false representing the on/off state of the device.  The device state can be read via DPS1, and, for values that can be changed (some DPS values are read-only), sending true/false to DPS1 will turn the device on/off.  A simple dimmer might have the same DPS1 value, but an additional DPS2 value from 1-255 representing the state of the dimmer.  More complex devices use more DPS keys with various values representing the states and control functions of the device.\n\nThe tuya-mqtt script provides access to these DPS keys and their values via MQTT, allowing any tool that can use MQTT to monitor and control these devices via a local network connection.  In addition to providing access to the raw DPS data, there is also a template engine that allows those DPS values to be mapped to device specific topics, called \"friendly topics\", allowing for consistent mapping even between devices that use different DPS keys for the same functions.  These friendly topics also support various transforms and other functions that make it easier for other devices to communicate with Tuya devices without a detailed understanding of the data formats Tuya devices use.\n\n### MQTT Topic Overview\nThe top level topics are created using the device name or ID as the primary identifier.  If the device name is available, it will be converted to lowercase and any spaces replace with underscores('_') characters so, for example, if the device as the name \"Kitchen Table\", the top level topic would be:\n```\ntuya/kitchen_table/\n```\nIf the device name was not available in the devices.conf file, tuya-mqtt falls back to using the device ID for the top level topic:\n```\ntuya/86435357d8b123456789/\n```\nAll additional state/command topics are then built below this level. You can view the connectivity status of the device using the status topic, which reports online/offline based on whether tuya-mqtt has an active connection to the device or not.  The script monitors both the device socket connection for errors and also device heartbeats, to report proper status. \n```\ntuya/kitchen_table/state --> online/offline\n```\nYou can also trigger the device to send an immediate update of all known device DPS topics by sending the message \"get-states\" to the command topic (this topic exist for all devices):\n```\ntuya/kitchen_table/command <-- get-states\n```\nAs noted above, tuya-mqtt supports two distinct topic types for interfacing with and controlling devices. For all devices, the DPS topics are always published and commands are accepted, however, friendly topics are the generally recommended approach but require you to use a pre-defined device template or create a customer template for your device when using the generic device.\n\nIf you do create a template for your device, please feel free to share it with the community as adding additional pre-defined devices is desired for future versions of tuya-mqtt.  There is a templates section of the project that you can submit a PR for your templates.\n\nIf you would like to use the raw DPS topics, please jump to the [DPS topics](#dps-topics) section of this document.\n\n## Friendly Topics\nFriendly topics are only available when using a pre-defined device template or, for the generic device, when you have defined a custom template for your device.  Friendly topics use the tuya-mqtt templating engine to map raw Tuya DPS key values to easy to consume topics and transform the data where needed.\n\nAnother advantage of friendly topics is that not all devices respond to schema requests (i.e. a request to report all DPS topics the device uses).  Because of this, it's not always possible for tuya-mqtt to know which DPS topics to acquire state information from during initial startup.  With a defined template the required DPS keys for each friendly topic are configured and tuya-mqtt will always query these DPS key values during initial connection to the device and report their state appropriately.\n\nFor more details on using friendly topics, please read the [DEVICES](docs/DEVICES.md) documentation which discusses how to configure supported devices or define a custom template.\n\n## DPS Topics\nControlling devices directly via DPS topics requires enough knowledge of the device to know which topics accept what values.  Described below are two different methods for interfacing with DPS values, the JSON DPS topic, and the individual DPS key topics.\n\n### DPS JSON topic\nThe JSON DPS topic allows controlling Tuya devices by sending Tuya native style JSON messages to the command topic, and by monitoring for Tuya style JSON replies on the state topic.  You can get more details on this format by reading the [TuyAPI documentation](https://codetheweb.github.io/tuyapi/index.html), but, for example, to turn off a dimmer switch you could issue a MQTT message containing the JSON value ```{dps: 1, set: false}``` to the DPS/command topic for the device.  If you wanted to turn the dimmer on, and set brightness to 50%, you could issue separate messages ```{dps: 1, set: true}``` and then ```{dps: 2, set: 128}```, or, the Tuya JSON protocol also allows setting multiple values in a single set command using the format ```{'multiple': true, 'data': {'1': true, '2': 128}}```.  JSON state and commands should use the DPS/state and DPS/command topics respectively.  Below is an example of the topics:\n```\ntuya/dimmer_device/DPS/state\ntuya/dimmer_device/DPS/command\n```\n### DPS Key topics\nIn addition to the JSON DPS topic, it's also possible to use the DPS key topics.  DPS key topics allow you to monitor and send simple bool/number/string values directly to DPS keys without having to use the Tuya JSON format, the conversion to Tuya JSON is handled by tuya-mqtt.  Using the example from above, turning on the dimmer and setting brightness to 50% you would simply issue the message \"true\" to DPS/1/command and the message \"128\" to DPS/2/command.\n```\ntuya/dimmer_device/DPS/1/state    --> true/false for on/off state\ntuya/dimmer_device/DPS/2/command  <-- 1-255 for brightness state\ntuya/dimmer_device/DPS/1/state    --> accept true/false for turning device on/off\ntuya/dimmer_device/DPS/2/command  <-- accepts 1-255 for controlling brightness level\n```\n**!!! Important Note !!!**\nWhen sending commands directly to DPS values there are no limitation on what values are sent as tuya-mqtt has no way to know what are valid vs invalid for any given DPS key.  Sending values that are out-of-range or of different types than the DPS key expects can cause unpredictable behavior of your device, from causing timeouts, to reboots, to hanging the device.  While I've never seen a device fail to recover after a restart, please keep this in mind when sending commands to your device.\n\n## Issues\nNot all Tuya protocols are supported.  For example, some devices use protocol 3.2 which currently remains unsupported by the TuyAPI project due to lack of enough information to reverse engineer the protocol.  If you are unable to control your devices with tuya-mqtt please verify that you can query and control them with tuya-cli first.  If tuya-cli works, then this script should also work, if it doesn't then this script will not work either.\n\n## Integration with other Home Automation tools\nopenHAB examples are [here](docs/openHAB.md).\n\n## Contributors\n- [TheAgentK](https://github.com/TheAgentK)\n- [tsightler](https://github.com/tsightler)\n- [Tycale](https://github.com/Tycale)\n- [crashdummymch](https://github.com/crashdummymch)\n- [GadgetAngel](https://github.com/GadgetAngel)\n- [dkrahmer](https://github.com/dkrahmer)\n\n## Related Projects:\n- https://github.com/codetheweb/tuyapi\n- https://github.com/unparagoned/njsTuya\n- https://github.com/clach04/python-tuya\n- https://github.com/Marcus-L/m4rcus.TuyaCore\n- Specs: https://docs.tuya.com/en/cloudapi/cloud_access.html\n\n[![forthebadge](https://forthebadge.com/images/badges/made-with-javascript.svg)](https://forthebadge.com)\n[![forthebadge](https://forthebadge.com/images/badges/built-with-love.svg)](https://forthebadge.com)\n"
  },
  {
    "path": "config.json.sample",
    "content": "{\r\n    \"host\": \"localhost\",\r\n    \"port\": 1883,\r\n    \"topic\": \"tuya/\",\r\n    \"mqtt_user\": \"\",\r\n    \"mqtt_pass\": \"\"\r\n}\r\n"
  },
  {
    "path": "devices/generic-device.js",
    "content": "const TuyaDevice = require('./tuya-device')\nconst debug = require('debug')('tuya-mqtt:device')\nconst utils = require('../lib/utils')\n\nclass GenericDevice extends TuyaDevice {\n    async init() {\n        this.deviceData.mdl = 'Generic Device'\n\n        // Check if custom template in device config\n        if (this.config.hasOwnProperty('template')) {\n            // Map generic DPS topics to device specific topic names\n            this.deviceTopics = this.config.template\n        } else {\n            // Try to get schema to at least know what DPS keys to get initial update\n            const result = await this.device.get({\"schema\": true})\n            if (!utils.isJsonString(result)) {\n                if (result === 'Schema for device not available') {\n                    debug('Device id '+this.config.id+' failed schema discovery and no custom template defined')\n                    debug('Cannot get initial DPS state data for device '+this.options.name+' but data updates will be publish')\n                }\n            }\n        }\n\n        // Get initial states and start publishing topics\n        this.getStates()\n    }\n}\n\nmodule.exports = GenericDevice"
  },
  {
    "path": "devices/rgbtw-light.js",
    "content": "const TuyaDevice = require('./tuya-device')\nconst debug = require('debug')('tuya-mqtt:device-detect')\nconst debugDiscovery = require('debug')('tuya-mqtt:discovery')\nconst utils = require('../lib/utils')\n\nclass RGBTWLight extends TuyaDevice {\n    async init() {\n        // If no manual config try to detect device settings\n        if (!this.config.dpsPower) { \n            await this.guessLightInfo()\n        }\n\n        // If detection failed and no manual config return without initializing\n        if (!this.guess.dpsPower && !this.config.dpsPower) {\n            debug('Automatic discovery of Tuya bulb settings failed and no manual configuration') \n            return\n        }     \n\n        // Set device specific variables\n        this.config.dpsPower = this.config.dpsPower ? this.config.dpsPower : this.guess.dpsPower\n        this.config.dpsMode = this.config.dpsMode ? this.config.dpsMode : this.guess.dpsMode\n        this.config.dpsWhiteValue = this.config.dpsWhiteValue ? this.config.dpsWhiteValue : this.guess.dpsWhiteValue\n        this.config.whiteValueScale = this.config.whiteValueScale ? this.config.whiteValueScale : this.guess.whiteValueScale\n        this.config.dpsColorTemp = this.config.dpsColorTemp ? this.config.dpsColorTemp : this.guess.dpsColorTemp\n        this.config.minColorTemp = this.config.minColorTemp ? this.config.minColorTemp : 154 // ~6500K\n        this.config.maxColorTemp = this.config.maxColorTemp ? this.config.maxColorTemp : 400 // ~2500K\n        this.config.colorTempScale = this.config.colorTempScale ? this.config.colorTempScale : this.guess.colorTempScale\n        this.config.dpsColor = this.config.dpsColor ? this.config.dpsColor : this.guess.dpsColor\n        this.config.colorType = this.config.colorType ? this.config.colorType : this.guess.colorType\n\n        this.deviceData.mdl = 'RGBTW Light'\n        this.isRgbtwLight = true\n\n        // Set white value transform math\n        let whiteValueStateMath\n        let whiteValueCommandMath\n        if (this.config.whiteValueScale === 255) {\n            // Devices with brightness scale of 255 seem to not allow values\n            // less then 25 (10%) without producing timeout errors.\n            whiteValueStateMath = '/2.3-10.86'\n            whiteValueCommandMath = '*2.3+25'\n        } else {\n            // For other scale (usually 1000), 10-1000 seems OK.\n            whiteValueStateMath = '/('+this.config.whiteValueScale+'/100)'\n            whiteValueCommandMath = '*('+this.config.whiteValueScale+'/100)'\n        }\n\n        // Map generic DPS topics to device specific topic names\n        this.deviceTopics = {\n            state: {\n                key: this.config.dpsPower,\n                type: 'bool'\n            },\n            white_brightness_state: { \n                key: this.config.dpsWhiteValue,\n                type: 'int',\n                topicMin: 0,\n                topicMax: 100,\n                stateMath: whiteValueStateMath,\n                commandMath: whiteValueCommandMath\n            },\n            hs_state: {\n                key: this.config.dpsColor,\n                type: this.config.colorType,\n                components: 'h,s'\n            },\n            color_brightness_state: {\n                key: this.config.dpsColor,\n                type: this.config.colorType,\n                components: 'b'\n            },\n            hsb_state: {\n                key: this.config.dpsColor,\n                type: this.config.colorType,\n                components: 'h,s,b'\n            },\n            mode_state: {\n                key: this.config.dpsMode,\n                type: 'str'\n            }\n        }\n\n        // If device supports Color Temperature add color temp device topic\n        if (this.config.dpsColorTemp) {\n            // Values used for tranforming from 1-255 scale to mireds range\n            const rangeFactor = (this.config.maxColorTemp-this.config.minColorTemp)/100\n            const scaleFactor = this.config.colorTempScale/100\n            const tuyaMaxColorTemp = this.config.maxColorTemp/rangeFactor*scaleFactor\n\n            this.deviceTopics.color_temp_state = {\n                key: this.config.dpsColorTemp,\n                type: 'int',\n                topicMin: this.config.minColorTemp,\n                topicMax: this.config.maxColorTemp,\n                stateMath: '/'+scaleFactor+'*-'+rangeFactor+'+'+this.config.maxColorTemp,\n                commandMath: '/'+rangeFactor+'*-'+scaleFactor+'+'+tuyaMaxColorTemp\n            }\n        }\n\n        // Send home assistant discovery data and give it a second before sending state updates\n        this.initDiscovery()\n        await utils.sleep(1)\n\n        // Get initial states and start publishing topics\n        this.getStates()\n    }\n\n    initDiscovery() {\n        const configTopic = 'homeassistant/light/'+this.config.id+'/config'\n\n        const discoveryData = {\n            name: (this.config.name) ? this.config.name : this.config.id,\n            state_topic: this.baseTopic+'state',\n            command_topic: this.baseTopic+'command',\n            brightness_state_topic: this.baseTopic+'color_brightness_state',\n            brightness_command_topic: this.baseTopic+'color_brightness_command',\n            brightness_scale: 100,\n            hs_state_topic: this.baseTopic+'hs_state',\n            hs_command_topic: this.baseTopic+'hs_command',\n            white_value_state_topic: this.baseTopic+'white_brightness_state',\n            white_value_command_topic: this.baseTopic+'white_brightness_command',\n            white_value_scale: 100,\n            availability_topic: this.baseTopic+'status',\n            payload_available: 'online',\n            payload_not_available: 'offline',\n            unique_id: this.config.id,\n            device: this.deviceData\n        }\n\n        if (this.config.dpsColorTemp) {\n            discoveryData.color_temp_state_topic = this.baseTopic+'color_temp_state'\n            discoveryData.color_temp_command_topic = this.baseTopic+'color_temp_command'\n            discoveryData.min_mireds = this.config.minColorTemp\n            discoveryData.max_mireds = this.config.maxColorTemp\n        }\n\n        debugDiscovery('Home Assistant config topic: '+configTopic)\n        debugDiscovery(discoveryData)\n        this.publishMqtt(configTopic, JSON.stringify(discoveryData))\n    }\n\n    async guessLightInfo() {\n        this.guess = new Object()\n        debug('Attempting to detect light capabilites and DPS values...')\n        debug('Querying DPS 2 for white/color mode setting...')\n\n        // Check if DPS 2 contains typical values for RGBTW light\n        const mode2 = await this.device.get({\"dps\": 2})\n        const mode21 = await this.device.get({\"dps\": 21})\n        if (mode2 && (mode2 === 'white' || mode2 === 'colour' || mode2.toString().includes('scene'))) {\n            debug('Detected likely Tuya color bulb at DPS 1-5, checking more details...')\n            this.guess = {'dpsPower': 1, 'dpsMode': 2, 'dpsWhiteValue': 3, 'whiteValueScale': 255, 'dpsColorTemp': 4, 'colorTempScale': 255, 'dpsColor': 5}\n        } else if (mode21 && (mode21 === 'white' || mode21 === 'colour' || mode21.toString().includes('scene'))) {\n            debug('Detected likely Tuya color bulb at DPS 20-24, checking more details...')\n            this.guess = {'dpsPower': 20, 'dpsMode': 21, 'dpsWhiteValue': 22, 'whiteValueScale': 1000, 'dpsColorTemp': 23, 'colorTempScale': 1000, 'dpsColor': 24}\n        }\n\n        if (this.guess.dpsPower) {\n            debug('Attempting to detect if bulb supports color temperature...')\n            const colorTemp = await this.device.get({\"dps\": this.guess.dpsColorTemp})\n            if (colorTemp !== '' && colorTemp >= 0 && colorTemp <= this.guess.colorTempScale) {\n                debug('Detected likely color temperature support')\n            } else {\n                debug('No color temperature support detected')\n                this.guess.dpsColorTemp = 0\n            }\n            debug('Attempting to detect Tuya color format used by device...')\n            const color = await this.device.get({\"dps\": this.guess.dpsColor})\n            if (this.guess.dpsPower === 1) {\n                this.guess.colorType = (color && color.length === 12) ? 'hsb' : 'hsbhex'\n            } else {\n                this.guess.colorType = (color && color.length === 14) ? 'hsbhex' : 'hsb'\n            }\n            debug ('Detected Tuya color format '+this.guess.colorType.toUpperCase())\n        }\n    }\n}\n\nmodule.exports = RGBTWLight"
  },
  {
    "path": "devices/simple-dimmer.js",
    "content": "const TuyaDevice = require('./tuya-device')\nconst debug = require('debug')('tuya-mqtt:device')\nconst debugDiscovery = require('debug')('tuya-mqtt:discovery')\nconst utils = require('../lib/utils')\n\nclass SimpleDimmer extends TuyaDevice {\n    async init() {\n        // Set device specific variables\n        this.config.dpsPower = this.config.dpsPower ? this.config.dpsPower : 1\n        this.config.dpsBrightness = this.config.dpsBrightness ? this.config.dpsBrightness : 2\n        this.config.brightnessScale = this.config.brightnessScale ? this.config.brightnessScale : 255\n\n        this.deviceData.mdl = 'Dimmer Switch'\n\n        // Set white value transform math\n        let brightnessStateMath\n        let brightnessCommandMath\n        if (this.config.brightnessScale === 255) {\n            // Devices with brightness scale of 255 seem to not allow values\n            // less then 25 (10%) without producing timeout errors.\n            brightnessStateMath = '/2.3-10.86'\n            brightnessCommandMath = '*2.3+25'\n        } else {\n            // For other scale (usually 1000), 10-1000 seems OK.\n            brightnessStateMath = '/('+this.config.brightnessScale+'/100)'\n            brightnessCommandMath = '*('+this.config.brightnessScale+'/100)'\n        }\n\n        // Map generic DPS topics to device specific topic names\n        this.deviceTopics = {\n            state: {\n                key: this.config.dpsPower,\n                type: 'bool'\n            },\n            brightness_state: { \n                key: this.config.dpsBrightness,\n                type: 'int',\n                topicMin: 0,\n                topicMax: 100,\n                stateMath: brightnessStateMath,\n                commandMath: brightnessCommandMath\n            }\n        }\n\n        // Send home assistant discovery data and give it a second before sending state updates\n        this.initDiscovery()\n        await utils.sleep(1)\n\n        // Get initial states and start publishing topics\n        this.getStates()\n    }\n\n    initDiscovery() {\n        const configTopic = 'homeassistant/light/'+this.config.id+'/config'\n\n        const discoveryData = {\n            name: (this.config.name) ? this.config.name : this.config.id,\n            state_topic: this.baseTopic+'state',\n            command_topic: this.baseTopic+'command',\n            brightness_state_topic: this.baseTopic+'brightness_state',\n            brightness_command_topic: this.baseTopic+'brightness_command',\n            brightness_scale: 100,\n            availability_topic: this.baseTopic+'status',\n            payload_available: 'online',\n            payload_not_available: 'offline',\n            unique_id: this.config.id,\n            device: this.deviceData\n        }\n\n        debugDiscovery('Home Assistant config topic: '+configTopic)\n        debugDiscovery(discoveryData)\n        this.publishMqtt(configTopic, JSON.stringify(discoveryData))\n    }\n}\n\nmodule.exports = SimpleDimmer"
  },
  {
    "path": "devices/simple-switch.js",
    "content": "const TuyaDevice = require('./tuya-device')\nconst debug = require('debug')('tuya-mqtt:device')\nconst debugDiscovery = require('debug')('tuya-mqtt:discovery')\nconst utils = require('../lib/utils')\n\nclass SimpleSwitch extends TuyaDevice {\n    async init() {\n        // Set device specific variables\n        this.config.dpsPower = this.config.dpsPower ? this.config.dpsPower : 1\n\n        this.deviceData.mdl = 'Switch/Socket'\n\n        // Map generic DPS topics to device specific topic names\n        this.deviceTopics = {\n            state: {\n                key: this.config.dpsPower,\n                type: 'bool'\n            }\n        }\n\n        // Send home assistant discovery data and give it a second before sending state updates\n        this.initDiscovery()\n        await utils.sleep(1)\n\n        // Get initial states and start publishing topics\n        this.getStates()\n    }\n\n    initDiscovery() {\n        const configTopic = 'homeassistant/switch/'+this.config.id+'/config'\n\n        const discoveryData = {\n            name: (this.config.name) ? this.config.name : this.config.id,\n            state_topic: this.baseTopic+'state',\n            command_topic: this.baseTopic+'command',\n            availability_topic: this.baseTopic+'status',\n            payload_available: 'online',\n            payload_not_available: 'offline',\n            unique_id: this.config.id,\n            device: this.deviceData\n        }\n\n        debugDiscovery('Home Assistant config topic: '+configTopic)\n        debugDiscovery(discoveryData)\n        this.publishMqtt(configTopic, JSON.stringify(discoveryData))\n    }\n}\n\nmodule.exports = SimpleSwitch"
  },
  {
    "path": "devices/tuya-device.js",
    "content": "const TuyAPI = require('tuyapi')\nconst { evaluate } = require('mathjs')\nconst utils = require('../lib/utils')\nconst debug = require('debug')('tuya-mqtt:tuyapi')\nconst debugState = require('debug')('tuya-mqtt:state')\nconst debugCommand = require('debug')('tuya-mqtt:command')\nconst debugError = require('debug')('tuya-mqtt:error')\n\nclass TuyaDevice {\n    constructor(deviceInfo) {\n        this.config = deviceInfo.configDevice\n        this.mqttClient = deviceInfo.mqttClient\n        this.topic = deviceInfo.topic\n\n        // Build TuyAPI device options from device config info\n        this.options = {\n            id: this.config.id,\n            key: this.config.key\n        }\n        if (this.config.name) { this.options.name = this.config.name.toLowerCase().replace(/\\s|\\+|#|\\//g,'_') }\n        if (this.config.ip) { \n            this.options.ip = this.config.ip\n            if (this.config.version) {\n                this.options.version = this.config.version\n            } else {\n                this.options.version = '3.1'\n            }\n        }\n\n        // Set default device data for Home Assistant device registry\n        // Values may be overridden by individual devices\n        this.deviceData = { \n            ids: [ this.config.id ],\n            name: (this.config.name) ? this.config.name : this.config.id,\n            mf: 'Tuya'\n        }\n\n        // Initialize properties to hold cached device state data\n        this.dps = {}\n        this.color = {'h': 0, 's': 0, 'b': 0}\n\n        // Device friendly topics\n        this.deviceTopics = {}\n\n        // Missed heartbeat monitor\n        this.heartbeatsMissed = 0\n        this.reconnecting = false\n\n        // Build the MQTT topic for this device (friendly name or device id)\n        if (this.options.name) {\n            this.baseTopic = this.topic + this.options.name + '/'\n        } else {\n            this.baseTopic = this.topic + this.options.id + '/'\n        }\n\n        // Create the new Tuya Device\n        this.device = new TuyAPI(JSON.parse(JSON.stringify(this.options)))\n\n        // Listen for device data and call update DPS function if valid\n        this.device.on('data', (data) => {\n            if (typeof data === 'object') {\n                debug('Received JSON data from device '+this.options.id+' ->', JSON.stringify(data.dps))\n                this.updateState(data)\n            } else {\n                if (data !== 'json obj data unvalid') {\n                    debug('Received string data from device '+this.options.id+' ->', data.replace(/[^a-zA-Z0-9 ]/g, ''))\n                }\n            }\n        })\n\n        // Attempt to find/connect to device and start heartbeat monitor\n        this.connectDevice()\n        this.monitorHeartbeat()\n\n        // On connect perform device specific init\n        this.device.on('connected', async () => {\n            // Sometimes TuyAPI reports connection even on socket error\n            // Wait one second to check if device is really connected before initializing\n            await utils.sleep(1)\n            if (this.device.isConnected()) {\n                debug('Connected to device ' + this.toString())\n                this.heartbeatsMissed = 0\n                this.publishMqtt(this.baseTopic+'status', 'online')\n                this.init()\n            }\n        })\n\n        // On disconnect perform device specific disconnect\n        this.device.on('disconnected', async () => {\n            this.connected = false\n            this.publishMqtt(this.baseTopic+'status', 'offline')\n            debug('Disconnected from device ' + this.toString())\n            await utils.sleep(5)\n            this.reconnect()\n        })\n\n        // On connect error call reconnect\n        this.device.on('error', async (err) => {\n            debugError(err)\n            await utils.sleep(1)\n            this.reconnect()\n        })\n\n        // On heartbeat reset heartbeat timer\n        this.device.on('heartbeat', () => {\n            this.heartbeatsMissed = 0\n        })\n    }\n\n    // Get and update cached values of all configured/known dps value for device\n    async getStates() {\n        // Suppress topic updates while syncing device state with cached state\n        this.connected = false\n        for (let topic in this.deviceTopics) {\n            const key = this.deviceTopics[topic].key\n            if (!this.dps[key]) { this.dps[key] = {} }\n            try {\n                this.dps[key].val = await this.device.get({\"dps\": key})\n                this.dps[key].updated = true\n            } catch {\n                debugError('Could not get value for device DPS key '+key)\n            }\n        }\n        this.connected = true\n        // Force topic update now that all states are fully syncronized\n        this.publishTopics()\n    }\n\n    // Update cached DPS values on data updates\n    updateState(data) {\n        if (typeof data.dps != 'undefined') {\n            // Update cached device state data\n            for (let key in data.dps) {\n                // Only update if the received value is different from previous value\n                if (this.dps[key] !== data.dps[key]) {\n                    this.dps[key] = {\n                        'val': data.dps[key],\n                        'updated': true\n                    }\n                }\n                if (this.isRgbtwLight) {\n                    if (this.config.hasOwnProperty('dpsColor') && this.config.dpsColor == key) {\n                        this.updateColorState(data.dps[key])\n                    } else if (this.config.hasOwnProperty('dpsMode') && this.config.dpsMode == key) {\n                        // If color/white mode is changing, force sending color state\n                        // Allows overriding saturation value to 0% for white mode for the HSB device topics\n                        this.dps[this.config.dpsColor].updated = true\n                    }\n                }\n            }\n            if (this.connected) {\n                this.publishTopics()\n            }\n        }\n    }\n\n    // Publish device specific state topics\n    publishTopics() {\n        // Don't publish if device is not connected\n        if (!this.connected) return\n\n        // Loop through and publish all device specific topics\n        for (let topic in this.deviceTopics) {\n            const deviceTopic = this.deviceTopics[topic]\n            const key = deviceTopic.key\n            // Only publish values if different from previous value\n            if (this.dps[key] && this.dps[key].updated) {\n                const state = this.getTopicState(deviceTopic, this.dps[key].val)\n                if (state) { \n                    this.publishMqtt(this.baseTopic + topic, state, true)\n                }\n            }\n        }\n\n        // Publish Generic Dps Topics\n        this.publishDpsTopics()\n    }\n\n    // Publish all dps-values to topic\n    publishDpsTopics() {\n        try {\n            if (!Object.keys(this.dps).length) { return }\n\n            const dpsTopic = this.baseTopic + 'dps'\n            // Publish DPS JSON data if not empty\n            let data = {}\n            for (let key in this.dps) {\n                // Only publish values if different from previous value\n                if (this.dps[key].updated) {\n                    data[key] = this.dps[key].val\n                }\n            }\n            data = JSON.stringify(data)\n            const dpsStateTopic = dpsTopic + '/state'\n            debugState('MQTT DPS JSON: ' + dpsStateTopic + ' -> ', data)\n            this.publishMqtt(dpsStateTopic, data, false)\n\n            // Publish dps/<#>/state value for each device DPS\n            for (let key in this.dps) {\n                // Only publish values if different from previous value\n                if (this.dps[key].updated) {\n                    const dpsKeyTopic = dpsTopic + '/' + key + '/state'\n                    const data = this.dps.hasOwnProperty(key) ? this.dps[key].val.toString() : 'None'\n                    debugState('MQTT DPS'+key+': '+dpsKeyTopic+' -> ', data)\n                    this.publishMqtt(dpsKeyTopic, data, false)\n                    this.dps[key].updated = false\n                }\n            }\n        } catch (e) {\n            debugError(e);\n        }\n    }\n    \n    // Get the friendly topic state based on configured DPS value type\n    getTopicState(deviceTopic, value) {\n        let state\n        switch (deviceTopic.type) {\n            case 'bool':\n                state = value ? 'ON' : 'OFF'\n                break;\n            case 'int':\n            case 'float':\n                state = this.parseNumberState(value, deviceTopic)\n                break;\n            case 'hsb':\n            case 'hsbhex':\n                // Return comma separate array of component values for specific topic\n                state = new Array()\n                const components = deviceTopic.components.split(',')\n                for (let i in components) {\n                    // If light is in white mode always report saturation 0%, otherwise report actual value\n                    state.push((components[i] === 's' && this.dps[this.config.dpsMode].val === 'white') ? 0 : this.color[components[i]])\n                }\n                state = (state.join(','))\n                break;\n            case 'str':\n                state = value ? value : ''\n                break;\n        }\n        return state\n    }\n\n    // Parse the received state numeric value based on deviceTopic rules\n    parseNumberState(value, deviceTopic) {\n        // Check if it's a number and it's not outside of defined range\n        if (isNaN(value)) {\n            return ''\n        }\n\n        // Perform any required math transforms before returing command value\n        switch (deviceTopic.type) {\n            case 'int':\n                value = (deviceTopic.stateMath) ? parseInt(Math.round(evaluate(value+deviceTopic.stateMath))) : parseInt(value)\n                break;\n            case 'float':\n                value = (deviceTopic.stateMath) ? parseFloat(evaluate(value+deviceTopic.stateMath)) : parseFloat(value)\n                break;\n            }\n\n        return value.toString()\n    }\n    \n    // Initial processing of MQTT commands for all command topics\n    processCommand(message, commandTopic) {\n        let command\n        if (utils.isJsonString(message)) {\n            debugCommand('Received MQTT command message is a JSON string')\n            command = JSON.parse(message);\n        } else {\n            debugCommand('Received MQTT command message is a text string')\n            command = message.toLowerCase()\n        }\n\n        // If get-states command, then updates all states and re-publish topics\n        if (commandTopic === 'command' && command === 'get-states') {\n            // Handle \"get-states\" command to update device state\n            debugCommand('Received command: ', command)\n            this.getStates()\n        } else {\n            // Call device specific command topic handler\n            this.processDeviceCommand(command, commandTopic) \n        }\n    }   \n\n    // Process MQTT commands for all device command topics\n    processDeviceCommand(command, commandTopic) {\n        // Determine state topic from command topic to find proper template\n        const stateTopic = commandTopic.replace('command', 'state')\n        const deviceTopic = this.deviceTopics.hasOwnProperty(stateTopic) ? this.deviceTopics[stateTopic] : ''\n\n        if (deviceTopic) {\n            debugCommand('Device '+this.options.id+' received command topic: '+commandTopic+', message: '+command)\n            let commandResult = this.sendTuyaCommand(command, deviceTopic)\n            if (!commandResult) {\n                debugCommand('Command topic '+this.baseTopic+commandTopic+' received invalid value: '+command)\n            }\n        } else {\n            debugCommand('Invalid command topic '+this.baseTopic+commandTopic+' for device id: '+this.config.id)\n            return\n        }\n    }\n    \n    // Process Tuya JSON commands via DPS command topic\n    processDpsCommand(message) {\n        if (utils.isJsonString(message)) {\n            const command = JSON.parse(message)\n            debugCommand('Parsed Tuya JSON command: '+JSON.stringify(command))\n            this.set(command)\n        } else {\n            debugCommand('DPS command topic requires Tuya style JSON value')\n        }\n    }\n\n    // Process text based Tuya commands via DPS key command topics\n    processDpsKeyCommand(message, dpsKey) {\n        if (utils.isJsonString(message)) {\n            debugCommand('Individual DPS command topics do not accept JSON values')\n        } else {\n            const dpsMessage = this.parseDpsMessage(message)\n            debugCommand('Received command for DPS'+dpsKey+': ', message)\n            const command = {\n                dps: dpsKey,\n                set: dpsMessage\n            }\n            this.set(command)\n        }\n    }\n\n    // Parse string message into boolean and number types\n    parseDpsMessage(message) {\n        if (typeof message === 'boolean' ) {\n            return message;\n        } else if (message === 'true' || message === 'false') {\n            return (message === 'true') ? true : false\n        } else if (!isNaN(message)) {\n            return Number(message)\n        } else {\n            return message\n        }\n    }\n\n    // Set state based on command topic\n    sendTuyaCommand(message, deviceTopic) {\n        let command = message.toLowerCase()\n        const tuyaCommand = new Object()\n        tuyaCommand.dps = deviceTopic.key\n        switch (deviceTopic.type) {\n            case 'bool':\n                if (command === 'toggle') {\n                    tuyaCommand.set = !this.dps[tuyaCommand.dps].val\n                } else {\n                    command = this.parseBoolCommand(command)\n                    if (typeof command.set === 'boolean') {\n                        tuyaCommand.set = command.set\n                    } else {\n                        tuyaCommand.set = '!!!INVALID!!!'\n                    }\n                }\n                break;\n            case 'int':\n            case 'float':\n                tuyaCommand.set = this.parseNumberCommand(command, deviceTopic)\n                break;\n            case 'hsb':\n                this.updateCommandColor(command, deviceTopic.components)\n                tuyaCommand.set = this.parseTuyaHsbColor()\n                break;\n            case 'hsbhex':\n                this.updateCommandColor(command, deviceTopic.components)\n                tuyaCommand.set = this.parseTuyaHsbHexColor()\n                break;\n            default:\n                // If type is not one of the above just use the raw string as is\n                tuyaCommand.set = message\n        }\n        if (tuyaCommand.set === '!!!INVALID!!!') {\n            return false\n        } else {\n            if (this.isRgbtwLight) {\n                this.setLight(deviceTopic, tuyaCommand)\n            } else {\n                this.set(tuyaCommand)\n            }\n            return true\n        }\n    }\n\n    // Convert simple bool commands to true/false\n    parseBoolCommand(command) {\n        switch(command) {\n            case 'on':\n            case 'off':\n            case '0':\n            case '1':\n            case 'true':\n            case 'false':\n                return {\n                    set: (command === 'on' || command === '1' || command === 'true' || command === 1) ? true : false\n                }\n            default:\n                return command\n        }\n    }\n\n    // Validate/transform set interger values \n    parseNumberCommand(command, deviceTopic) {\n        let value = undefined\n        const invalid = '!!!INVALID!!!'\n\n        // Check if it's a number and it's not outside of defined range\n        if (isNaN(command)) {\n            return invalid\n        } else if (deviceTopic.hasOwnProperty('topicMin') && command < deviceTopic.topicMin) {\n            debugError('Received command value \"'+command+'\" that is less than the configured minimum value')\n            debugError('Overriding command with minimum value '+deviceTopic.topicMin)\n            command = deviceTopic.topicMin\n        } else if (deviceTopic.hasOwnProperty('topicMax') && command > deviceTopic.topicMax) {\n            debugError('Received command value \"'+command+'\" that is greater than the configured maximum value')\n            debugError('Overriding command with maximum value: '+deviceTopic.topicMax)\n            command = deviceTopic.topicMax\n        }\n\n        // Perform any required math transforms before returing command value\n        switch (deviceTopic.type) {\n            case 'int':\n                if (deviceTopic.commandMath) {\n                    value = parseInt(Math.round(evaluate(command+deviceTopic.commandMath)))\n                } else {\n                    value = parseInt(command)\n                }\n                break;\n            case 'float':\n                if (deviceTopic.commandMath) {\n                    value = parseFloat(evaluate(command+deviceTopic.commandMath))\n                } else {\n                    value = parseFloat(command)\n                }\n                break;\n            }\n\n        return value\n    }\n\n    // Takes Tuya color value in HSB or HSBHEX format and updates cached HSB color state for device\n    // Credit homebridge-tuya project for HSB/HSBHEX conversion code\n    updateColorState(value) {\n        let h, s, b\n        if (this.config.colorType === 'hsbhex') {\n            [, h, s, b] = (value || '0000000000ffff').match(/^.{6}([0-9a-f]{4})([0-9a-f]{2})([0-9a-f]{2})$/i) || [0, '0', 'ff', 'ff'];\n            this.color.h = parseInt(h, 16)\n            this.color.s = Math.round(parseInt(s, 16) / 2.55) // Convert saturation to 100 scale\n            this.color.b = Math.round(parseInt(b, 16) / 2.55) // Convert brightness to 100 scale\n        } else {\n            [, h, s, b] = (value || '000003e803e8').match(/^([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{4})$/i) || [0, '0', '3e8', '3e8']\n            // Convert from Hex to Decimal and cache values\n            this.color.h = parseInt(h, 16)\n            this.color.s = Math.round(parseInt(s, 16) / 10)   // Convert saturation to 100 Scale\n            this.color.b = Math.round(parseInt(b, 16) / 10)   // Convert brightness to 100 scale\n        }\n\n        // Initialize the command color values with existing color state\n        if (!this.hasOwnProperty('cmdColor')) {\n            this.cmdColor = {\n                'h': this.color.h,\n                's': this.color.s,\n                'b': this.color.b\n            }\n        }\n    }\n\n    // Caches color updates when HSB components have separate device topics\n    // cmdColor property always contains the desired HSB color state based on received \n    // command topic messages vs actual device color state, which may be pending\n    updateCommandColor(value, components) {\n        // Update any HSB component with a changed value\n        components = components.split(',')\n        const values = value.split(',')\n        for (let i in components) {\n            this.cmdColor[components[i]] = Math.round(values[i])\n        }\n    }\n\n    // Returns Tuya HSB format value from current cmdColor HSB values\n    // Credit homebridge-tuya project for HSB conversion code\n    parseTuyaHsbColor() {\n        let {h, s, b} = this.cmdColor\n        const hexColor = h.toString(16).padStart(4, '0') + (10 * s).toString(16).padStart(4, '0') + (10 * b).toString(16).padStart(4, '0')\n        return hexColor\n    }\n\n    // Returns Tuya HSBHEX format value from current cmdColor HSB values\n    // Credit homebridge-tuya project for HSBHEX conversion code\n    parseTuyaHsbHexColor() {\n        let {h, s, b} = this.cmdColor\n        const hsb = h.toString(16).padStart(4, '0') + Math.round(2.55 * s).toString(16).padStart(2, '0') + Math.round(2.55 * b).toString(16).padStart(2, '0');\n        h /= 60;\n        s /= 100;\n        b *= 2.55;\n        const\n            i = Math.floor(h),\n            f = h - i,\n            p = b * (1 - s),\n            q = b * (1 - s * f),\n            t = b * (1 - s * (1 - f)),\n            rgb = (() => {\n                switch (i % 6) {\n                    case 0:\n                        return [b, t, p];\n                    case 1:\n                        return [q, b, p];\n                    case 2:\n                        return [p, b, t];\n                    case 3:\n                        return [p, q, b];\n                    case 4:\n                        return [t, p, b];\n                    case 5:\n                        return [b, p, q];\n                }\n            })().map(c => Math.round(c).toString(16).padStart(2, '0')),\n            hex = rgb.join('');\n\n        return hex + hsb;\n    }\n\n    // Set white/colour mode based on received commands\n    async setLight(topic, command) {\n        let targetMode = undefined\n        \n        if (topic.key === this.config.dpsWhiteValue || topic.key === this.config.dpsColorTemp) {\n            // If setting white level or color temperature, light should be in white mode\n            targetMode = 'white'\n        } else if (topic.key === this.config.dpsColor) {\n            // Split device topic HSB components into array\n            const components = topic.components.split(',')\n\n            // If device topic inlucdes saturation check for changes\n            if (components.includes('s')) {\n                if (this.cmdColor.s < 10) {\n                    // Saturation changed to < 10% = white mode\n                    targetMode = 'white'\n                } else {\n                    // Saturation changed to >= 10% = color mode\n                    targetMode = 'colour'\n                }\n            } else {\n                // For other cases stay in existing mode\n                targetMode = this.dps[this.config.dpsMode].val\n            }\n        }\n\n        // Send the issued command\n        this.set(command)\n\n        // Make sure the bulb stays in the correct mode\n        if (targetMode) {\n            command = {\n                dps: this.config.dpsMode,\n                set: targetMode\n            }\n            this.set(command)\n        }\n    }\n\n    // Simple function to help debug output \n    toString() {\n        return this.config.name+' (' +(this.options.ip ? this.options.ip+', ' : '')+this.options.id+', '+this.options.key+')'\n    }\n\n    set(command) {\n        debug('Set device '+this.options.id+' -> '+JSON.stringify(command))\n        return new Promise((resolve, reject) => {\n            this.device.set(command).then((result) => {\n                resolve(result)\n            })\n        })\n    }\n\n    // Search for and connect to device\n    connectDevice() {\n        // Find device on network\n        debug('Search for device id '+this.options.id)\n        this.device.find().then(() => {\n            debug('Found device id '+this.options.id)\n            // Attempt connection to device\n            this.device.connect().catch((error) => {\n                debugError(error.message)\n                this.reconnect()\n            })\n        }).catch(async (error) => {\n            debugError(error.message)\n            debugError('Will attempt to find device again in 60 seconds')\n            await utils.sleep(60)\n            this.connectDevice()\n        })\n    }\n\n    // Retry connection every 10 seconds if unable to connect\n    async reconnect() {\n        if (!this.reconnecting) {\n            this.reconnecting = true\n            debugError('Error connecting to device id '+this.options.id+'...retry in 10 seconds.')\n            await utils.sleep(10)\n            this.connectDevice()\n            this.reconnecting = false\n        }\n    }\n\n    // Republish device discovery/state data (used for Home Assistant state topic)\n    async republish() {\n        const status = (this.device.isConnected()) ? 'online' : 'offline'\n        this.publishMqtt(this.baseTopic+'status', status)\n        await utils.sleep(1)\n        this.init()\n    }\n    \n    // Simple function to monitor heartbeats to determine if \n    monitorHeartbeat() {\n        setInterval(async () => {\n            if (this.connected) {\n                if (this.heartbeatsMissed > 3) {\n                    debugError('Device id '+this.options.id+' not responding to heartbeats...disconnecting')\n                    this.device.disconnect()\n                    await utils.sleep(1)\n                    this.connectDevice()\n                } else if (this.heartbeatsMissed > 0) {\n                    const errMessage = this.heartbeatsMissed > 1 ? \" heartbeats\" : \" heartbeat\"\n                    debugError('Device id '+this.options.id+' has missed '+this.heartbeatsMissed+errMessage)                \n                }\n                this.heartbeatsMissed++\n            }\n        }, 10000)\n    }\n\n    // Publish MQTT\n    publishMqtt(topic, message, isDebug) {\n        if (isDebug) { debugState(topic, message) }\n        this.mqttClient.publish(topic, message, { qos: 1 });\n    }\n}\n\nmodule.exports = TuyaDevice\n"
  },
  {
    "path": "docs/DEVICES.md",
    "content": "# tuya-mqtt - Devices\nThe most powerful feature in tuya-mqtt is the ability to configure devices to use friendly topics.  For some devices there exist pre-defined device templates which makes using those devices quite easy, simply add the type information to the devices.conf file and tuya-mqtt automatically creates friendly topics for that device.\n\nFriendly topics make it easy to communicate with the device in a standard way and thus integrating into various Home Automation platforms.  The topic style generally follows that used by the Home Assistant MQTT integration components and the pre-defined devices automatically send Home Assistant style MQTT discovery messages during startup to make integration with Home Assistant, or other platforms which understand Home Assistant MQTT discovery, even easier.\n\nIf the device does not have a pre-defined device template, it's possible to create a template using the [generic device template](#generic-device-templates) feature.\n\n## Pre-defined Device Templates\nPre-defined device templates (except for the Generic Device) will always expose friendly topics for the given device in a consistent manner.  Currently the following pre-defined device templates are available:\n\n| Device Type | Descrition |\n| --- | --- |\n| SimpleSwitch | Supports simple on/off devices |\n| SimpleDimmer | Supports simple devices with on/on and brightness |\n| RGBTWLight | Supports color/white lights with optional color temerature support |\n| GenericDevice | Allows defining a custom template for any device |\n\nTo use a device template, simply add the \"type\" option to the devices.conf similar to the following example:\n```\n[\n  {\n    name: 'Tuya Device 1',\n    id: '86435357d8b123456789',\n    key: '8b2a69c9876543210',\n    type: 'RGBTWLight'\n  }\n]\n```\nOnce the device type is defined tuya-mqtt will attempt to create friendly topics for that device type on connection to the device.  Each device type defines specific defaults for DPS values which are typical for common Tuya devices and some, like RGBTWLight, have logic to attempt to detect different variation by querying the device.  The goal is that, in most cases, simply adding the type is all that is needed, however, in many cases it is also possible to override the manual settings for the device.  The device friendly topics and options for each device are documented below.\n\n### SimpleSwitch\nSimple devices that support only on/off.\n| Topic | Description | Values |\n| --- | --- | --- |\n| state | Power state | on/off |\n| command | Set power state | on/off, 0/1, true/false |\n\nManual configuration options:\n| Option | Description | Default |\n| --- | --- | --- |\n| dpsPower | DPS key for power state | 1 |\n\n### SimpleDimmer\nSimple device with on/off and brightness functions (dimmer switches or lights)\n| Topic | Description | Values |\n| --- | --- | --- |\n| state | Power state | on/off |\n| command | Set power state | on/off, 0/1, true/false |\n| brightness_state | Brightness in % | 0-100 |\n| brightness_command | set brightness in % | 0-100 |\n\nManual configuration options:\n| Option | Description | Default |\n| --- | --- | --- |\n| dpsPower | DPS key for power state | 1 |\n| dpsBrightness | DPS key for brightness state | 2 |\n| brightnessScale | Scale for brightness DPS value | 255 |\n\n### RGBTWLight\nThe RGBTWLight device support Tuya color lights (bulbs and LEDs). Tuya lights operate in either white or color mode.  The RGBTWLight device automatically switches between modes on certain conditions as documented below:\n| Condition | Mode |\n| --- | --- |\n| Changes white brightness | white |\n| Changes to color temperature (for device with color temp support) | white |\n| Saturation < 10 % | white |\n| Saturation >= 10 % | color |\n| All other changes | current mode |\n\nThis means changing the hue of the light will only switch to color mode if saturation is also >= 10%.  Some lights automatically attempt to switch to color mode when any HSB value is updated however, if the saturation setting remains < 10%, tuya-mqtt will force the light back to white mode in this case.  This can cause a very quick flicker when chaning hue or color brightness while the saturation remains below the 10% threshold.  I expect this not to be a common issue and implemented this in an attempt to make all tuya lights behave in a consistent way.\n\nWhen the bulb is in white mode, saturation values in the friendly topics are always reported as 0%.  This is true even if the mode is toggled manually from color to white mode using the mode_command topic or the Tuya/SmartLife app.  When the light is toggled back to color mode, saturation will be reported at the correct level.  This is done primarly as a means to indicate color state to automation platforms that don't have a concept of white/color mode, otherwise a light in white mode may still be represented with a color icon in the platforms UI.\n\nNot all devices support color temperature and the script attempts to detect this capability and enables the color temperature topics only when found.  Color temperature topics report in Mireds (commonly used by automation tools) and the default range supports roughly 2500K-6500K.  This works reasonably well for most available Tuya devices, even if they are not exactly in this range, but, if you know a devices specific color range, the limits can be manually specified to more accurately reflect the exact color temperature.\n\nTuya bulbs store their HSB color value in a single DPS key using a custom format.  Some bulbs use a 14 character format, referred to as HSBHEX, which represents the saturation and brightness values from 0-255 as 2 character hex, while the others use a 12 character format, referred to as HSB, which still uses hex values, but stores saturation and brightness values from 0-1000 as 4 character hex.  The code attempts to autodetect the format used by the bulb and perform the proper conversion in all cases, but this can be overridden for cases where the dection method fails.\n\n| Topic | Description | Values |\n| --- | --- | --- |\n| state | Power state | on/off |\n| command | Set power state | on/off, 0/1, true/false |\n| white_brightness_state | White mode brightness in % | 0-100 |\n| white_brightness_command | Set white mode brightness in % | 0-100 |\n| color_brightness_state | Color mode brightness in % | 0-100 |\n| color_brightness_command | Set white mode brightness in % | 0-100 |\n| hs_state | Hue, saturation % | H,S (Hue 0-360, Saturation 0-100) |\n| hs_command | Set hue, saturation % | H,S (Hue 0-360, Saturation 0-100) |\n| hsb_state | Hue, saturation %, brightness % | H,S,B (Hue 0-360, Saturation 0-100, Brightness 0-100) |\n| hsb_command | Set hue, saturation %, brightness % | H,S,B (Hue 0-360, Saturation 0-100, Brightness 0-100) |\n| mode_state | White/Color mode | 'white', 'colour' (some devices also support scenes here) |\n| mode_command | Set white/color mode | 'white', 'colour' (some devices also support scenes here) |\n| color_temp_state | Color temperature in mireds (only available if device support color temp) | 154-400 (defult range, can be overridden) |\n| color_temp_command | Set color temperature in mireds (only available if device support color temp)  | 154-400 (defult range, can be overridden) |\n\nManual configuration options:\n| Option | Description | Default (common detected values) |\n| --- | --- | --- |\n| dpsPower | DPS key for power state | Auto Detect (1,20) |\n| dpsMode | DPS key for white/color mode state | Auto Detect (2,21) |\n| dpsWhiteValue | DPS key for white mode brightness | Auto Detect (3,22) |\n| whiteValueScale | White mode brightness DPS scale | Auto Detect (255, 1000) |\n| dpsColorTemp | DPS key for color temperature | Auto Detect (4,23) |\n| minColorTemp | Min color temperature in Mireds | 154 (~6500K) |\n| maxColorTemp | Max color temperature in Mireds | 400 (~2500K) |\n| colorTempScale | Color temperature DPS key scale | Auto Detect (255, 1000) |\n| dpsColor | DPS key for HSB color values | Auto Detect (5,24) |\n| colorType | Tuya color format for color DPS key | Auto Detect (hsb, hsbhex) |\n\nTo use the manual configuration options simply add them to device.conf file after defining the device type like the following example:\n```\n[\n  {\n    name: 'Tuya Device 1',\n    id: '86435357d8b123456789',\n    key: '8b2a69c9876543210',\n    type: 'RGBTWLight',\n    dpsPower: 31,\n    dpsMode: 32,\n    dpsWhiteValue: 33,\n    whiteValueScale: 255,\n    dpsColorTemp: 34,\n    minColorTemp: 165,\n    maxColorTemp: 385,\n    colorTempScale: 255,\n    dpsColor: 34,\n    colorType: 'hsbhex'\n  }\n]\n```\n\n## Generic Device Templates\nIf a pre-defined device tempate does not exist for the device, or does not expose all capabilities of the device, there are still mulitple options available to control the devices.  One method is to use the DPS topics directly to control the device using either native Tuya JSON commands or via the DPS key values by using the DPS key topics (see [DPS Topics](TOPICS.md#dps-topics)).  The second method is to create a template for your device to map DPS key values to friendly topics.  The GenericDevice type allows you to manually create a template for any device using the same templating engine as the pre-defined device templates.  Once you've created a tempalte for your device, it can be re-used with other, similar devices and you can submit your template to the tuya-mqtt project for other to use, or even for inclusion at a pre-defined device template in the future.\n\nCreating a device template is relatively straightforward, but first you must know what DPS keys your devices uses.  The GenericDevice attempts to query all device DPS states on startup, but some devices to not respond to this command, however, the generic device will ALWAYS report any DPS topics from which it receives upated.  The easiest way to determine how your device uses it's DPS topics is to connect to the MQTT broker via a tool like MQTT Explorer or mosquitto_sub, and watch the topics as you manipulate the device with the Tuya/Smartlife app.\n\nOnce you have a reasonable idea of how the device uses it's DPS key values, you can create a template.  A simple template for a dimmer looks something like this:\n```\n[\n  {\n    name: 'Tuya Device 1',\n    id: '86435357d8b123456789',\n    key: '8b2a69c9876543210',\n    template: {\n      state: {\n        key: 1,\n        type: 'bool'\n      },\n      brightness_state: { \n        key: 2,\n        type: 'int',\n        topicMin: 1,\n        topicMax: 100,\n        stateMath: '/2.55',\n        commandMath: '*2.55'\n      }\n    }\n  }\n]\n```\nThe template above defines two topics \"state\" and \"brightness_state\", and the template engine automatically creates the corresponding command topics, in this case specifically \"command\" and \"brightness_command\".\n\nThe \"state\" topic maps to DPS key 1, and uses a bool (true/false) value in the DPS key.  Now you will be able to see \"on/off\" state in the state topic instead of having to read the true/false value from the DPS/1 topic\n\nThe the \"brightness_state\" topic maps to DPS key 2, and this value defines the brightness using an integer in the 1-255 scale.  We define the value as an integer (type: 'int') and the stateMath and commandMath values allow transforming the raw DPS value into a more friendly value that will be presented in the topic.  In this case the raw DPS value will be divided by 2.55 before being published to the state, and and received commands will be mulitpled by that same value, converting the 1-255 to a simple 1-100 scale.  Note that the topicMin and topicMax values set the minimum and maximum values that the state topic will report and that the command topic will accept.  These values are \"post-math\" for state topics, and \"pre-math\" for command topics.\n\nThe following tables define the available template value types and their options:\n\n### Boolean values\n| option | value |\n| --- | --- |\n| type | 'bool' |\n| key | DPS key of the value |\n\n### Integer values\n| option | value |\n| --- | --- |\n| type | 'int' |\n| key | DPS key of the value |\n| topicMin | Minumum value allowed for the command topic |\n| topicMax | Maximum value allowed for the command topic | \n| stateMath | Simple math applied to the DPS key value before being published to state topic |\n| commandMath | Simple math applied to command value before being set to DPS key |\n\n### Floating point values\n| option | value |\n| --- | --- |\n| type | 'float' |\n| key | DPS key of the value |\n| topicMin | Minumum value allowed for the command topic |\n| topicMax | Maximum value allowed for the command topic | \n| stateMath | Simple math applied to the DPS key value before being published to state topic |\n| commandMath | Simple math applied to command value before being set to DPS key |\n\n### String values\n| option | value |\n| --- | --- |\n| type | 'str' |\n| key | DPS key of the value |\n\n### Tuya HSB values (newer style Tuya, 12 character color value)\n| option | value |\n| --- | --- |\n| type | 'hsb' |\n| key | DPS key of the value |\n| components | Comma separated list of HSB components that should be included in this topic |\n\n### Tuya HSBHEX values (older style Tuya 14 character color value)\n| option | value |\n| --- | --- |\n| type | 'hsbhex' |\n| key | DPS key of the value |\n| components | Comma separated list of HSB components that should be included in this topic |\n\nUsing these value types you can define templates for a wide range of devices.  Additional types and options are likely to be included in future versions of tuya-mqtt.\n"
  },
  {
    "path": "docs/openHAB.md",
    "content": ":exclamation: There is a greate Step-By-Step guide from user HolgiHab at openhab community ([Step-By-Step Guide](\nhttps://community.openhab.org/t/step-by-step-guide-for-adding-tuya-bulbs-smart-life-to-oh2-using-tuya-mqtt-js-by-agentk/59371)). This guide is not only for light bulbs, but also applies to sockets. :exclamation:\n\n## Example items for OpenHAB 1.x Bindings (still works with OH > 2.4 but only if legacy 1.x MQTT bindings are enabled)\n### simple switch on/off\n```\n\nSwitch tuya_kitchen_coffeemachine_mqtt \"Steckdose Kaffeemaschine\" <socket> (<GROUPS>) [\"Switchable\"] {\n    mqtt=\"<[broker:tuya/<tuyAPI-id>/<tuyAPI-key>/<tuyAPI-ip>/state:state:default:.*],\n          >[broker:tuya/<tuyAPI-id>/<tuyAPI-key>/<tuyAPI-ip>/command/on:command:ON:true],\n          >[broker:tuya/<tuyAPI-id>/<tuyAPI-key>/<tuyAPI-ip>/command/off:command:OFF:false]\"\n}\n\nSwitch tuya_livingroom_ledstrip_tv \"LED Regal\" <lightbulb> (<GROUPS>) [\"Lighting\"] {\n    mqtt=\"<[broker:tuya/<tuyAPI-id>/<tuyAPI-key>/<tuyAPI-ip>/state:state:default:.*],\n          >[broker:tuya/<tuyAPI-id>/<tuyAPI-key>/<tuyAPI-ip>/command/on:command:ON:true],\n          >[broker:tuya/<tuyAPI-id>/<tuyAPI-key>/<tuyAPI-ip>/command/off:command:OFF:false]\"\n}\n\n```\n\n### change color of lightbulb\n```\n\n# .items\nGroup gTuyaLivingColor \"Tuya color group\" <lightbulb>\nColor tuya_livingroom_colorpicker \"Stehlampe farbe\" (LivingDining)\n\nString tuya_livingroom_ledstrip_tv_color \"Set color [%s]\" (gTuyaLivingColor, LivingDining) {\n    mqtt=\">[broker:tuya/<tuyAPI-id>/<tuyAPI-key>/<tuyAPI-ip>/color:command:*:default]\"\n}\n\n\n\n# .rules\nimport org.openhab.core.library.types.HSBType;\n\nrule \"Set HSB value of item RGBLed to RGB color value\"\n    when\n        Item tuya_livingroom_colorpicker received command\n    then\n        var appName = \"Colorpicker.livingroom\"\n        var color = receivedCommand.toString;\n\n        // get all colors and send it via mqtt if light ist enabled\n        gTuyaLivingColor.members.forEach[ i |\n            var name = i.name;\n            var stateName = name.toString.split(\"_color\").get(0);\n            var stateItem = gTuyaLights.allMembers.filter [ conf | conf.name.contains(stateName.toString) ].head;\n\n            if(stateItem.state == ON){\n                logInfo(appName, name + \" change to color: \" + color);\n                i.sendCommand(color);\n                Thread::sleep(400);\n            }\n        ]\n    end\n\n```\n\n## Example items for OpenHAB 2.4 Bindings\n### simple switch on/off\n\nWith OpenHAB 2.X MQTT bindings you can add devices using a generic MQTT Thing via PaperUI or \nconfiguration files.  For PaperUI simply at the generic MQTT Thing and set the state and\ncommand topics as follows:\n```\n\n    tuya/<tuyAPI-id>/<tuyAPI-key>/<tuyAPI-ip>/state\n\n    tuya/<tuyAPI-id>/<tuyAPI-key>/<tuyAPI-ip>/command\n\n```\n\nIf you prefer using configuration files vs PaperUI, it should look something like this:\nSee also OpenHAB 2.X MQTT binding [documentation](https://www.openhab.org/v2.4/addons/bindings/mqtt.generic/)\n\n```\n\nBridge mqtt:broker:myUnsecureBroker [ host=\"localhost\", secure=false ]\n{\n\n    Thing mqtt:topic:myCustomMQTT {\n    Channels:\n        Type switch : tuya_kitchen_coffeemachine_mqtt_channel \"Kitchen Coffee Machine MQTT Channel\" [\n            stateTopic=\"tuya/<tuyAPI-id>/<tuyAPI-key>/<tuyAPI-ip>/state\",\n            commandTopic=\"tuya/<tuyAPI-id>/<tuyAPI-key>/<tuyAPI-ip>/command\",\n\n            // optional custom mqtt-payloads for ON and OFF\n            on=\"{ \\\"dps\\\": 1, \\\"set\\\": true }\",\n            off=\"0\"\n        ]\n    }\n\n}\n\n# *.item Example\nSwitch tuya_kitchen_coffeemachine_mqtt \"Kitchen Coffee Machine Switch\" <socket> (gKitchen, gTuya) [\"Switchable\"] {\n    channel=\"mqtt:topic:myUnsecureBroker:myCustomMQTT:tuya_kitchen_coffeemachine_mqtt_channel\"\n}\n\n```\n\nFor one RGB bulb you would need a separate channel with the command topic set to\n`tuya/<tuyAPI-id>/<tuyAPI-key>/<tuyAPI-ip>/color` and link that to your color item.\n\n```\n\nBridge mqtt:broker:myUnsecureBroker [ host=\"localhost\", secure=false ]\n{\n    Thing mqtt:topic:myCustomMQTT {\n    Channels:\n        Type colorHSB : livingroom_floorlamp_1_color \"Livingroom floorlamp color MQTT Channel\" [\n            stateTopic=\"tuya/05200399bcddc2e02ec9/b58cf92e8bc5c899/192.168.178.49/state\",\n            commandTopic=\"tuya/05200399bcddc2e02ec9/b58cf92e8bc5c899/192.168.178.49/color\"\n        ]\n    }\n}\n\n# *.item Example\nColor tuya_livingroom_colorpicker \"Floorlamp colorpicker\" (gLivingroom){\n    channel=\"mqtt:topic:myUnsecureBroker:myCustomMQTT:livingroom_floorlamp_1_color\"\n}\n\n```\n\n#### Basic UI sitemap\n```\n\nSwitch item=tuya_kitchen_coffeemachine_mqtt\n\n# turn the color bulb off or on\nSwitch item=tuya_livingroom_colorpicker label=\"RGB lamp [%s]\" \n\n# pick the color level to send to the color bulb via MQTT color Channel\nSlider item=tuya_livingroom_colorpicker label=\"RGB lamp level [%s]\" minValue=0 maxValue=100 step=1\n\n# color picked and sent via MQTT Color channel\nColorpicker item=tuya_livingroom_colorpicker label=\"RGB lamp color [%s]\" icon=\"colorpicker\" sendFrequency=30000\n\n\n```\n"
  },
  {
    "path": "lib/utils.js",
    "content": "class Utils\n{\n\n    // Check if data is JSON or not\n    isJsonString(data) {\n        try {\n            const parsedData = JSON.parse(data)\n            if (parsedData && typeof parsedData === \"object\") {\n                return parsedData\n            }\n        }\n        catch (e) { }\n\n        return false\n    }\n\n    // Simple sleep function for various required delays\n    sleep(sec) {\n        return new Promise(res => setTimeout(res, sec*1000))\n    }\n\n    msSleep(ms) {\n        return new Promise(res => setTimeout(res, ms))\n    }\n\n}\n\nmodule.exports = new Utils()"
  },
  {
    "path": "merge-devices.js",
    "content": "#!/usr/bin/env node\nconst fs = require('fs');\nconst json5 = require('json5');\nconst utils = require('./lib/utils');\n\n// Setup Exit Handlers\nprocess.on('exit', processExit.bind(0));\nprocess.on('SIGINT', processExit.bind(0));\nprocess.on('SIGTERM', processExit.bind(0));\nprocess.on('uncaughtException', processExit.bind(1));\n\nasync function processExit(exitCode) {\n    if (exitCode || exitCode === 0)\n        console.error('Exit code: ' + exitCode)\n    process.exit();\n}\n\n// Main code function\nconst main = async() => {\n    const date = new Date();\n    const dateTimeStr = date.getFullYear() + '-' + (\"0\" + (date.getMonth() + 1)).slice(-2) + '-' + (\"0\" + date.getDate()).slice(-2) + '_' + (\"0\" + date.getHours()).slice(-2) + (\"0\" + date.getMinutes()).slice(-2) + (\"0\" + date.getSeconds()).slice(-2);\n    const configDevicesFilename = 'devices.conf';\n    const configDevicesBackupFilename = `${configDevicesFilename}_${dateTimeStr}.bak`;\n    const configNewDevicesFilename = `new-${configDevicesFilename}`;\n\n    let configDevices;\n    let configNewDevices;\n\n    try {\n        console.log(`Loading ${configNewDevicesFilename}...`);\n        configNewDevices = fs.readFileSync(`./${configNewDevicesFilename}`, 'utf8');\n        configNewDevices = json5.parse(configNewDevices);\n    }\n    catch (e) {\n        console.error(`Could not parse new devices config file [${configNewDevicesFilename}]!`);\n        console.error(e);\n        process.exit(1);\n    }\n\n    try {\n        console.log(`Loading ${configDevicesFilename}...`);\n        configDevices = fs.readFileSync(`./${configDevicesFilename}`, 'utf8');\n        configDevices = json5.parse(configDevices);\n    }\n    catch (e) {\n        console.error(`Could not parse devices config file [${configDevicesFilename}]!`);\n        console.error(e);\n        process.exit(1);\n    }\n\n    try {\n        console.log(`Backing up devices config file [${configDevicesFilename}] to [${configDevicesBackupFilename}]...`);\n        fs.copyFileSync(`./${configDevicesFilename}`, `./${configDevicesBackupFilename}`);\n    }\n    catch (e) {\n        console.error(`Could not make backup of devices config file [${configDevicesFilename}] to [${configDevicesBackupFilename}].`);\n        console.error(e);\n        process.exit(1);\n    }\n\n    console.log('Indexing devices...');\n\n    // Create a dictionary for faster lookups with many devices\n    const configDevicesDictionary = {};\n    for (let configDevice of configDevices) {\n        configDevicesDictionary[configDevice.id] = configDevice;\n    }\n\n    console.log('Merging devices...');\n\n    // Add new devices and update existing devices\n    for (let configNewDevice of configNewDevices) {\n        let configDevice = configDevicesDictionary[configNewDevice.id];\n        if (configDevice == null) {\n            // Add new device\n            console.log(`Adding device: ${configNewDevice.name} (id: ${configNewDevice.id})...`);\n            configDevices.push(configNewDevice);\n            configDevicesDictionary[configNewDevice.id] = configNewDevice;\n            continue;\n        }\n\n        if (configDevice.allowMerge === false)\n            continue; // No merge updates allowed for this device\n        \n        // Update existing device\n        if (configDevice.name !== configNewDevice.name) {\n            console.log(`Updating device name: '${configDevice.name}' to '${configNewDevice.name}' (device id: ${configDevice.key})...`);\n            configDevice.name = configNewDevice.name;\n        }\n        if (configDevice.key !== configNewDevice.key) {\n            console.log(`Updating device key for: '${configDevice.name}' (device id: ${configDevice.key})...`);\n            configDevice.key = configNewDevice.key;\n        }\n    }\n\n    // Sort the devices by name\n    configDevices.sort((a, b) => a.name < b.name ? -1 : 1);\n    const configDevicesJson = json5.stringify(configDevices, { space: '    ', quote: '\"' });\n\n    //console.log(configDevicesJson);\n\n    try {\n        console.log(`Saving devices config file [${configDevicesFilename}]...`);\n        fs.writeFileSync(`./${configDevicesFilename}`, configDevicesJson, { encoding: 'utf8' });\n    }\n    catch (e) {\n        console.error(`Could not write devices config file [${configDevicesFilename}]!`)\n        console.error(e)\n        process.exit(1)\n    }\n\n    console.log('Done!');\n}\n\n// Call the main code\nmain();"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"tuya-mqtt\",\n  \"version\": \"3.0.4\",\n  \"description\": \"Control Tuya devices locally via MQTT\",\n  \"homepage\": \"https://github.com/TheAgentK/tuya-mqtt#readme\",\n  \"main\": \"tuya-mqtt.js\",\n  \"scripts\": {\n    \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\"\n  },\n  \"author\": {\n    \"name\": \"TheAgentK\",\n    \"email\": \"lulattsch22@googlemail.com\"\n  },\n  \"license\": \"ISC\",\n  \"dependencies\": {\n    \"@tuyapi/cli\": \"^1.15.0\",\n    \"color-convert\": \"^2.0.1\",\n    \"debug\": \"^4.3.1\",\n    \"json5\": \"^2.1.3\",\n    \"mqtt\": \"^4.2.6\",\n    \"supports-color\": \"^8.1.0\",\n    \"tuyapi\": \"^6.1.4\",\n    \"mathjs\": \"8.1.1\"\n  },\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git://github.com/TheAgentK/tuya-mqtt.git\"\n  }\n}\n"
  },
  {
    "path": "tuya-mqtt.js",
    "content": "#!/usr/bin/env node\nconst fs = require('fs')\nconst mqtt = require('mqtt')\nconst json5 = require('json5')\nconst debug = require('debug')('tuya-mqtt:info')\nconst debugCommand = require('debug')('tuya-mqtt:command')\nconst debugError = require('debug')('tuya-mqtt:error')\nconst SimpleSwitch = require('./devices/simple-switch')\nconst SimpleDimmer = require('./devices/simple-dimmer')\nconst RGBTWLight = require('./devices/rgbtw-light')\nconst GenericDevice = require('./devices/generic-device')\nconst utils = require('./lib/utils')\n\nvar CONFIG = undefined\nvar tuyaDevices = new Array()\n\n// Setup Exit Handlers\nprocess.on('exit', processExit.bind(0))\nprocess.on('SIGINT', processExit.bind(0))\nprocess.on('SIGTERM', processExit.bind(0))\nprocess.on('uncaughtException', processExit.bind(1))\n\n// Disconnect from and publish offline status for all devices on exit\nasync function processExit(exitCode) {\n    for (let tuyaDevice of tuyaDevices) {\n        tuyaDevice.device.disconnect()\n    }\n    if (exitCode || exitCode === 0) debug('Exit code: '+exitCode)\n    await utils.sleep(1)\n    process.exit()\n}\n\n// Get new deivce based on configured type\nfunction getDevice(configDevice, mqttClient) {\n    const deviceInfo = {\n        configDevice: configDevice,\n        mqttClient: mqttClient,\n        topic: CONFIG.topic\n    }\n    switch (configDevice.type) {\n        case 'SimpleSwitch':\n            return new SimpleSwitch(deviceInfo)\n            break;\n        case 'SimpleDimmer':\n            return new SimpleDimmer(deviceInfo)\n            break;\n        case 'RGBTWLight':\n            return new RGBTWLight(deviceInfo)\n            break;\n    }\n    return new GenericDevice(deviceInfo)\n}\n\nfunction initDevices(configDevices, mqttClient) {\n    for (let configDevice of configDevices) {\n        const newDevice = getDevice(configDevice, mqttClient)\n        tuyaDevices.push(newDevice)\n    }\n}\n\n// Republish devices 2x with 30 seconds sleep if restart of HA is detected\nasync function republishDevices() {\n    for (let i = 0; i < 2; i++) {\n        debug('Resending device config/state in 30 seconds')\n        await utils.sleep(30)\n        for (let device of tuyaDevices) {\n            device.republish()\n        }\n        await utils.sleep(2)\n    }\n}\n\n// Main code function\nconst main = async() => {\n    let configDevices\n    let mqttClient\n\n    try {\n        CONFIG = require('./config')\n    } catch (e) {\n        console.error('Configuration file not found!')\n        debugError(e)\n        process.exit(1)\n    }\n\n    if (typeof CONFIG.qos == 'undefined') {\n        CONFIG.qos = 1\n    }\n    if (typeof CONFIG.retain == 'undefined') {\n        CONFIG.retain = false\n    }\n\n    try {\n        configDevices = fs.readFileSync('./devices.conf', 'utf8')\n        configDevices = json5.parse(configDevices)\n    } catch (e) {\n        console.error('Devices file not found!')\n        debugError(e)\n        process.exit(1)\n    }\n\n    if (!configDevices.length) {\n        console.error('No devices found in devices file!')\n        process.exit(1)\n    }\n\n    mqttClient = mqtt.connect({\n        host: CONFIG.host,\n        port: CONFIG.port,\n        username: CONFIG.mqtt_user,\n        password: CONFIG.mqtt_pass,\n    })\n\n    mqttClient.on('connect', function (err) {\n        debug('Connection established to MQTT server')\n        let topic = CONFIG.topic + '#'\n        mqttClient.subscribe(topic)\n        mqttClient.subscribe('homeassistant/status')\n        mqttClient.subscribe('hass/status')\n        initDevices(configDevices, mqttClient)\n    })\n\n    mqttClient.on('reconnect', function (error) {\n        if (mqttClient.connected) {\n            debug('Connection to MQTT server lost. Attempting to reconnect...')\n        } else {\n            debug('Unable to connect to MQTT server')\n        }\n    })\n\n    mqttClient.on('error', function (error) {\n        debug('Unable to connect to MQTT server', error)\n    })\n\n    mqttClient.on('message', function (topic, message) {\n        try {\n            message = message.toString()\n            const splitTopic = topic.split('/')\n            const topicLength = splitTopic.length\n            const commandTopic = splitTopic[topicLength - 1]\n            const deviceTopicLevel = splitTopic[1]\n\n            if (topic === 'homeassistant/status' || topic === 'hass/status' ) {\n                debug('Home Assistant state topic '+topic+' received message: '+message)\n                if (message === 'online') {\n                    republishDevices()\n                }\n            } else if (commandTopic.includes('command')) {\n                // If it looks like a valid command topic try to process it\n                debugCommand('Received MQTT message -> ', JSON.stringify({\n                    topic: topic,\n                    message: message\n                }))\n\n                // Use device topic level to find matching device\n                const device = tuyaDevices.find(d => d.options.name === deviceTopicLevel || d.options.id === deviceTopicLevel)\n                switch (topicLength) {\n                    case 3:\n                        device.processCommand(message, commandTopic)\n                        break;\n                    case 4:\n                        device.processDpsCommand(message)\n                        break;\n                    case 5:\n                        const dpsKey = splitTopic[topicLength-2]\n                        device.processDpsKeyCommand(message, dpsKey)\n                        break;\n                }\n            }\n        } catch (e) {\n            debugError(e)\n        }\n    })\n}\n\n// Call the main code\nmain()"
  }
]