User Tools

Site Tools


doc:appunti:hardware:iot

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
Next revisionBoth sides next revision
doc:appunti:hardware:iot [2021/01/20 12:35] – [Configuring MQTT on Tasmota] niccolodoc:appunti:hardware:iot [2021/01/20 17:09] – [Tasmota and Tuya-Convert] niccolo
Line 1: Line 1:
-====== IoT - Internet of Things ====== +====== Internet of ThingsTeckin Smart Plug SP22 ======
- +
-===== Teckin Smart Plug SP22 =====+
  
 Di queste prese intelligenti marchiate **Teckin** ne esistono almeno due versioni. Le più vecchie si basano sul chip **ESP** Di queste prese intelligenti marchiate **Teckin** ne esistono almeno due versioni. Le più vecchie si basano sul chip **ESP**
Line 21: Line 19:
   * Appena si **rimuove una device dalla app**, il Cloud invia al device stesso l'**istruzione di reset**. Il dispositivo **resetta tutta la sua configurazione** ed entra immediatamente in pairing mode. Se il device non è on-line al momento della sua rimozione dalla app, l'istruzione di reset viene comunque inviata appena esso torna on-line.   * Appena si **rimuove una device dalla app**, il Cloud invia al device stesso l'**istruzione di reset**. Il dispositivo **resetta tutta la sua configurazione** ed entra immediatamente in pairing mode. Se il device non è on-line al momento della sua rimozione dalla app, l'istruzione di reset viene comunque inviata appena esso torna on-line.
  
- +===== Smart Life App =====
-==== Smart Life App ====+
  
 The QR code printed on the plug itseld points to [[http://e.tuya.com/smartlife]], here you can download the 76.7 Mb **smartlife.apk**. We prefered to download it from the Google Play, searching the **Smart Life - Smart Living** app by Volcano Technology Limited, at the URL **[[https://play.google.com/store/apps/details?id=com.tuya.smartlife]]**. Strangely enough, the Google Play app is only 40.35 Mb... The QR code printed on the plug itseld points to [[http://e.tuya.com/smartlife]], here you can download the 76.7 Mb **smartlife.apk**. We prefered to download it from the Google Play, searching the **Smart Life - Smart Living** app by Volcano Technology Limited, at the URL **[[https://play.google.com/store/apps/details?id=com.tuya.smartlife]]**. Strangely enough, the Google Play app is only 40.35 Mb...
  
-=== Pairing the smart plug with the App and WiFi ===+==== Pairing the smart plug with the App and WiFi ====
  
   - Plug the SP22 into an electricity outlet.   - Plug the SP22 into an electricity outlet.
Line 39: Line 36:
   - The procedure on the smartphone should terminate with the message **Successfully Added** (**Aggiunto con successo**).   - The procedure on the smartphone should terminate with the message **Successfully Added** (**Aggiunto con successo**).
  
-=== After the pairing ===+==== After the pairing ====
  
   * The SP22 connect to the WiFi network, getting an IP address from the local DHCP server. You can view the request into the DHCP server log, coming from a **Tuya Smart Inc.** MAC address (prefix d4:a6:51). In my case the device presented itself with the name **TY_WR**.   * The SP22 connect to the WiFi network, getting an IP address from the local DHCP server. You can view the request into the DHCP server log, coming from a **Tuya Smart Inc.** MAC address (prefix d4:a6:51). In my case the device presented itself with the name **TY_WR**.
Line 47: Line 44:
   * The SP22 can be switched on/off from the smartphone.   * The SP22 can be switched on/off from the smartphone.
  
-=== How the app communicates witht the device ===+==== How the app communicates witht the device ====
  
   * If the Smart Plug has internet connectivity, it gets **commands from the cloud server**.   * If the Smart Plug has internet connectivity, it gets **commands from the cloud server**.
Line 54: Line 51:
   * With default configuration, the SP22 remembers its last status (on or off) when it recovers from a power failure.   * With default configuration, the SP22 remembers its last status (on or off) when it recovers from a power failure.
  
-=== How the app communicates witht the cloud ===+==== How the app communicates witht the cloud ====
  
   * It seems that the app does not make DNS calls to resolve for the cloud server name, at least in my case I cannot detect **any DNS requests**, even after a smartphone reboot. The app communicates on port **TCP/8883** (Secure MQTT) with an **Amazon AWS** server,IP address 18.194.10.142.   * It seems that the app does not make DNS calls to resolve for the cloud server name, at least in my case I cannot detect **any DNS requests**, even after a smartphone reboot. The app communicates on port **TCP/8883** (Secure MQTT) with an **Amazon AWS** server,IP address 18.194.10.142.
  
-==== How to create a Tuya Developer Account ====+===== How to create a Tuya Developer Account =====
  
 To use the TinyTuya library we need the **device local key**. This key is assigned by the **Tuya Cloud** to your device when you do the **pairing** with the **Smart Life** app. The key will be valid and can be **used locally** to control your device even if the Tuya cloud is unavailable, but you cannot move the device into another network; in that case you need to obtain a new local key from Tuya cloud. To use the TinyTuya library we need the **device local key**. This key is assigned by the **Tuya Cloud** to your device when you do the **pairing** with the **Smart Life** app. The key will be valid and can be **used locally** to control your device even if the Tuya cloud is unavailable, but you cannot move the device into another network; in that case you need to obtain a new local key from Tuya cloud.
Line 188: Line 185:
 State (bool, true is ON) True State (bool, true is ON) True
 </code> </code>
-==== Tasmota and Tuya-Convert ====+ 
 +===== Tasmota and Tuya-Convert =====
  
 La soluzione **Tuya Cloud** è ovviamente **non accettabile** se si vuole avere il controllo dei device al di fuori del circolo vizioso **Smart Life app** - **Tuya Cloud**. Purtroppo sostituire il firmware originale con Tasmota pare che sia diventato impossibile. Anzitutto sembra che Teckin si sia impegnata a rendere impossibile il funzionamento di Tuya-Convert (tool per il flash del firmware Tasmota), almeno a giudicare dalla **[[https://github.com/ct-Open-Source/tuya-convert/issues/197|issue 197]]**. Poi, cosa ancora più grave, sembra proprio che le nuove versioni di SP22 siano basate su chip Realtek non compatibile con Tasmota, vedere questa **[[https://tasmota.github.io/docs/devices/Teckin-SP22/|pagina informativa]]**. La soluzione **Tuya Cloud** è ovviamente **non accettabile** se si vuole avere il controllo dei device al di fuori del circolo vizioso **Smart Life app** - **Tuya Cloud**. Purtroppo sostituire il firmware originale con Tasmota pare che sia diventato impossibile. Anzitutto sembra che Teckin si sia impegnata a rendere impossibile il funzionamento di Tuya-Convert (tool per il flash del firmware Tasmota), almeno a giudicare dalla **[[https://github.com/ct-Open-Source/tuya-convert/issues/197|issue 197]]**. Poi, cosa ancora più grave, sembra proprio che le nuove versioni di SP22 siano basate su chip Realtek non compatibile con Tasmota, vedere questa **[[https://tasmota.github.io/docs/devices/Teckin-SP22/|pagina informativa]]**.
Line 194: Line 192:
   * **[[https://tasmota.github.io/docs/Tuya-Convert/|Tuya-Convert intro]]**   * **[[https://tasmota.github.io/docs/Tuya-Convert/|Tuya-Convert intro]]**
   * **[[https://github.com/ct-Open-Source/tuya-convert|Tuya-Convert download and help]]**   * **[[https://github.com/ct-Open-Source/tuya-convert|Tuya-Convert download and help]]**
- 
-===== Sonoff Basic R2 ===== 
- 
-Il vantaggio di quesi **power switch intelligenti** marchiati **Sonoff**, è che sono facilmente programmabili con il firmware **[[https://tasmota.github.io/docs/|Tasmota]]**. Tasmota è un progetto **free ed open source** che consente di realizzare la propria infrastruttura **IoT** totalmente indipendente da qualunque architettura cloud di terze parti. In pratica è possibile gestire i dispositivi basati sul **chip ESP8266** utilizzando protocolli aperti (**MQTT**) e creando il proprio server cloud, ad esempio con il broker MQTT **mosquitto**, ed utilizzando i più vari MQTT client, come ad esempio **[[https://www.home-assistant.io/|Home Assistant]]**. 
- 
-{{.:sonoff:sonoff-basic-r2-case.jpg?340|Sonoff Basic R2: Opening the case}} 
- 
-To **open the plastic case** of the Sonoff Basic R2 you have to unlock the four **snap fit joints**: there are two on each of the long edges. 
- 
-{{.:sonoff:sonoff-basic-r2-components.jpg?340|Sonoff Basic R2: Components }} 
-{{.:sonoff:sonoff-basic-r2-pcb.jpg?340|Sonoff Basic R2: PCB}} 
- 
-{{.:sonoff:sonoff-basic-rf-r2-power-v1.3.jpg?260|Sonoff Basic: RF R2 Power V1.3}} 
-{{.:sonoff:sonoff-basic-r2-antenna.jpg?200|Sonoff Basic R2: ESP8285 chip and antenna}} 
- 
-==== Tools required to flash the Tasmota firmware ==== 
- 
-  - **Pin headers** to be soldered on the Sonoff Basic PCB. 
-  - An **USB to serial adapter**. 
-  - The **esptool.py** flashing tool (Python program). 
-  - The **tasmota.bin** firmware to be uploaded (flashed) into the Sonoff Basic. 
- 
-You can download the **esptool.py** form the **[[https://github.com/espressif/esptool/|esptool GitHub repository]]**, I used version 3.0. You can install it or just extract the archive and run it from the extract directory. 
- 
-The Tasmota firmware can be downloaded from the **[[https://github.com/arendst/Tasmota/|Tasmota GitHub repository]]**, I used the **tasmota.bin** version 9.2.0 found into the **[[https://github.com/arendst/Tasmota/releases/tag/v9.2.0|download page]]**. 
-==== Flashing the Tasmota firmware ==== 
- 
-To flash the Tasmota firmware I used a **GNU/Linux** computer and an **USB to serial** adapter based on the **CP210x** chip. With the help of a multimeter I verified that the adapter provides the **3.3 Volt** power on the proper pin: this current is used to power the Sonoff device during the flash. 
- 
-  - **Disconnect** the Sonoff Basic from **AC power**. 
-  - **Connect** the USB to **serial adapter** to the **Sonoff serial**, all the 4 wires are required: **3.3 Volt**, **TX**, **RX** and **GND**. The TX line of the adapter is connected to the RX line of Sonoff, and vice-versa. 
-  - **Execute each step** of the flashing procedure in this manner: 
-    * **Connect** the USB adapter to the computer **while holding down** the push button of the Sonoff device. Keeping the button pressed for 7 seconds is sufficient. Keeping the button pressed while power-on is required to put the device into a special programming mode. 
-    * **Execute** the required **esptool.py command** on the PC. 
-    * **Disconnect** the USB adapter from the PC. 
- 
-This is the concise list of commands I used (remember: **each command** is executed after the Sonoff device is **booted in programming mode** as explained above!): 
- 
-<code> 
-./esptool.py --port /dev/ttyUSB0 flash_id 
-./esptool.py --port /dev/ttyUSB0 read_flash 0x00000 0x100000 sonoff-r2-1mb.orig.bin 
-./esptool.py --port /dev/ttyUSB0 erase_flash 
-./esptool.py --port /dev/ttyUSB0 write_flash -fs 1MB -fm dout 0x0 tasmota.bin 
-</code> 
- 
-Running the command **%%./esptool.py -h%%** you get the explanation of each command, this is a summary of what I used: 
- 
-^ flash_id     | Read SPI flash manufacturer and device ID  | 
-^ read_flash   | Read SPI flash content  | 
-^ erase_flash  | Perform Chip Erase on SPI flash  | 
-^ write_flash  | Write a binary blob to flash  | 
- 
-Here it is the output generated by the **write_flash** command: 
- 
-<code> 
-./esptool.py --port /dev/ttyUSB0 write_flash -fs 1MB -fm dout 0x0 tasmota.bin 
-esptool.py v3.0 
-Serial port /dev/ttyUSB0 
-Connecting.... 
-Detecting chip type... ESP8266 
-Chip is ESP8285 
-Features: WiFi, Embedded Flash 
-Crystal is 26MHz 
-MAC: c8:2b:96:ee:b8:3c 
-Uploading stub... 
-Running stub... 
-Stub running... 
-Configuring flash size... 
-Compressed 600960 bytes to 428969... 
-Wrote 600960 bytes (428969 compressed) at 0x00000000 in 37.9 seconds (effective 127.0 kbit/s)... 
-Hash of data verified. 
-Leaving... 
-Hard resetting via RTS pin... 
-</code> 
- 
-After the **write_flash** command you can **power-cycle** the Sonoff device by unplugging and plugging the USB adapter again, this time **without holding the Sonoff button**. The LED on the Sonoff flashes in blue, the device starts into **Access Point mode** and stays this way for about **three minutes**, connect a smartphone or the notebook to it (search for an ESSID like **tasmota-xxxx**) and browse the address **%%http://192.168.1.4/%%**. Here you have to configure the WiFi parameters to let the Sonoff Basic connect to your WiFi network; you can specify **two different ESSID**, that the Tasmota firmware will search to connect to. 
- 
-**NOTICE** :!: I had some **problems connecting to the Sonoff Access Point** using the smartphone and using the notebook: sometimes the IP address were not assigned, other times the host 192.168.4.1 were not reachable. One time I succeded by setting the IP address manually (in the range 192.168.4.x), another time I succeded by enabling the WiFi option //Allow lower bitrates// (GNU/Linux Wicd Network Manager). 
- 
-^ AP1 SSId/Password  | ESSID and password of the first Access Point  | 
-^ AP2 SSId/Password  | ESSID and password of the second Access Point  | 
-^ Hostname  | The name used when registering to the DHCP server. Defaults to **%%%s-%04d%%** which means the name you will configure into **MQTT topic** (see below), followed by a **four digits decimal number**. The number is derived from the 13 least significant bits of the MAC address.  | 
-^ CORS Domain  | If empty (default) Tasmota allows HTTP requests only from the connecting client. You can specify an asterisk to allow the sharing of resources with any domains, or you can specify just one URL (e.g. **%%http://host.domain.tld%%**) which will be the only one domain allowed to share Tasmota HTTP resources.  | 
- 
-=== Hardware Module Configuration === 
- 
-After WiFi configuration, you can reboot the Tasmota device, wait unitll **it gets an address from your WiFi Access Point** and **complete the configuration**; you have to tell to the Tasmota firmware what hardware it can control. 
- 
-  * **Configure** the device **name and template**. Choose a name to identify this device and select the appropriate template. The template tells the firmware how to use the hardware (the relay and the LED): just use the default **Sonoff Basic (1)**. 
-    * **Configuration** => **Configure Template** => **Based on** => **Sonoff Basic (1)** 
-  * **Protect** the **web access** with a password (beware that it uses plain http, so password can be sniffed along the network): 
-    * **Configuration** => **Configure Other** => **Web Admin Password** 
-  * **Disable** the **[[https://tasmota.github.io/docs/Securing-your-IoT-from-hacking/#disable-unsecured-fallback-wifi-wifimanager|Access Point mode if WiFi AP is missing]]**. If the device is unable to connect to the two configured WiFi networks, it enters automatically into the **WifiConfig Access Point mode**, allowing a WiFi client to connect and make configuration (this is the **[[https://tasmota.github.io/docs/Commands/#wificonfig|WifiConfig mode 2]]**). This is can be a security threat if you have not set the **web access password**. You can go further in securing the device by changing the WifiConfig mode: 
-    * Connecto to the web interface, **Main Menu** => **Console** and enter the command **WifiConfig 5**. This means //wait until selected AP is available again without rebooting//. Beware that the //6 short presses// of the button (see below) will revert to WifiConfig 2. 
- 
-=== Button Reset === 
- 
-If you have trouble connecting to a Tasmota device and the device have a button, you have at least two methods to try to recover. 
- 
-^ 6 short presses  | Press the button six times very quickly (be rapid enough to prevent the relay switch to toggle). Tasmota changes to **[[https://tasmota.github.io/docs/Commands/#wificonfig|WifiConfig 2 mode]]**, i.e. it starts the Wi-Fi Manager Access Point (with web server at 192.168.4.1) for 3 minutes, then reboot. This button behaviour can be disabled using **[[https://tasmota.github.io/docs/Commands/#setoption1|SetOption1 1]]**. The WifiConfig mode 2 remains permanent unless you reconfigure it, this means that if the device is unable to find one of the two Access Points it knowns, it switches into the Access Point mode allowing WiFi clients to connect.   | 
-^ Long press for 40 seconds  | Tasmota will reset to firmware defaults and restart.  | 
-===== Controlling Tasmota via MQTT ===== 
- 
-MQTT is a client/server protocol, it allows a **client** to **send messages** to other clients which are **subscribed** to a common topic. The server acts as a **broker** for this publish/subscribe mechanism. 
- 
-**WARNING**: Commands over MQTT are sent in clear-text, including passwords. You must trust your network against traffic sniffing! Using TLS in Tasmota is disabled by default, because it requires too much memory; see the page **[[https://tasmota.github.io/docs/TLS/|TLS Secured MQTT]]**. 
-==== Installing a MQTT Broker ==== 
- 
-On a GNU/Linux Debian host (version 10 Buster) I installed the following packages: 
- 
-  * **mosquitto** 
-  * **mosquitto-clients** 
- 
-The daemon **mosquitto** is running and listening on port **TCP/1883**. The traffic on this port is **unencrypted** so although passwords are usually used, beware when you open the firewall, etc. 
- 
-With default configuration, the mosquitto broker is **open to everyone**, just try to **subscribe** to a topic and - from another terminal - **publish** something on the same topic: 
- 
-<code> 
-mosquitto_sub -h mqtt.server.tld -t my_topic 
-</code> 
- 
-<code> 
-mosquitto_pub -h mqtt.server.tld -t my_topic -m "Hello, world!" 
-</code> 
- 
-On the first terminal you will get the message ''Hello, world!''. 
- 
-==== Configuring MQTT on Tasmota ==== 
- 
-From the Tasmota **Main menu** => **Configuration** => **Configure MQTT**: 
- 
-^ Host      | Hostname or IP address of the MQTT server.  | 
-^ Port      | Default is 1883, which is MQTT TCP unencrypted.  | 
-^ Client    | Default is **%%DVES_%06X%%**, where %06X means the last 3 bytes of MAC address, in hex.  | 
-^ User      | Username for authenticating on the MQTT broker, default is **DVES_USER**.  | 
-^ Password  | Password for authenticating on the MQTT broker.  | 
-^ Topic     | Default is **%%tasmota_%06X%%**, where %06X means the last 3 bytes of MAC address, in hex.  | 
-^ Full Topic  | Default is **%%%prefix%/%topic%/%%**  | 
- 
-From the Tasmota **Main menu** => **Configuration** => **Configure other**: 
- 
-^ MQTT enable     | Checkbox to enable the service.  | 
-^ Device Name     | Default is //Tasmota// | 
-^ Friendly Name 1 | Used by the autodiscovery feature, default is //Tasmota// | 
- 
-Here it is an example to **publish** an MQTT message asking the Sonoff device to **toggle the switch**: 
- 
-<code> 
-mosquitto_pub -h mqtt.server.tld  -t 'cmnd/tasmota_EEB73A/Power' -m 'TOGGLE' 
-</code> 
- 
-**NOTICE**: If you use a non-existent topic (e.g. a **wrong device name**), **no error is reported**. 
- 
-Obviously the device understands the **TOGGLE**, **ON** and **OFF** messages. If you are **subscribed** to the proper MQTT topic, you will **receive a message** for each toggle: 
- 
-<code> 
-mosquitto_sub -h mqtt.server.tld -t "stat/tasmota_EEB73A/RESULT" 
-{"POWER":"OFF"} 
-{"POWER":"ON"} 
-</code> 
- 
-=== Password protect the Mosquitto broker === 
- 
-Default Debian installation of the **mosquitto** server does not require a password from the connecting client. 
- 
-**/etc/mosquitto/acls** 
- 
-<file> 
-user username1 
-topic write gateway/+/event/+ 
-topic read gateway/+/command/+ 
- 
-user username2 
-topic readwrite gateway/+/event/+ 
-</file> 
- 
-**/etc/mosquitto/conf.d/auth.conf** 
- 
-<file> 
-allow_anonymous false 
-password_file /etc/mosquitto/passwd 
-acl_file /etc/mosquitto/acls 
-</file> 
- 
-To manage a password file you can use the **mosquitto_passwd** tool, this command will set an **username** with a **passowrd** (asked interactively) into the **password file** (add a **%%-c%%** option to create the password file): 
- 
-<code> 
-mosquitto_passwd /etc/mosquitto/passwd username 
-</code> 
- 
-The file will contains **sha512** hashes. 
- 
-Now you have to specify the correct **username** and **password** when you execute **mosquitto_pub**, otherwise the command will fail: 
- 
-<code> 
-mosquitto_pub -h mqtt.server.tld -u 'username' -P 'WrongPassword' -t 'cmnd/smart-cable/Power' -m 'TOGGLE' 
-Connection Refused: not authorised. 
-Error: The connection was refused. 
-</code> 
- 
-===== Controlling Tasmota via HTTP GET ===== 
- 
-The Tasmota firmware exposes an open, //admin mode//, web interface to configure and control the device status (this default can be changed). It is advisable to set a password from **Main menu** => **Configuration** => **Configure Other** => **Web Admin Password**. The default username is **admin**. 
- 
-**WARNING**: Commands over HTTP are sent in clear-text, including passwords. You must trust your network against traffic sniffing! 
- 
-Suppose that your Tasmota device has IP address **10.0.0.114**, username **admin** and password **MySecret**, you can remotely control it on the command line using GET commands, e.g. using **wget**: 
- 
-<code bash> 
-# Control the relay status: Toggle, switch it On, switch it Off. 
-wget -q -O /dev/null 'http://10.0.0.114/cm?user=admin&password=MySecret&cmnd=Power%20Toggle' 
-wget -q -O /dev/null 'http://10.0.0.114/cm?user=admin&password=MySecret&cmnd=Power%20On' 
-wget -q -O /dev/null 'http://10.0.0.114/cm?user=admin&password=MySecret&cmnd=Power%20Off' 
-</code> 
- 
-If you want to read the relay status after the command, read the output of the GET request (a JSON string): 
- 
-<code bash> 
-wget -q -O - 'http://10.0.0.114/cm?user=admin&password=MySecret&cmnd=Power' 
-{"POWER":"ON"} 
-</code> 
-===== Web References ===== 
- 
-  * **[[https://www.hivemq.com/mqtt-essentials/|MQTT Essentials]]** 
-  * **[[https://tasmota.github.io/docs/MQTT/|Tasmota MQTT]]**