ClusterM / tuyanet

.NET library to interface with Tuya WiFi smart devices over LAN.
GNU General Public License v3.0
61 stars 10 forks source link

IP Addresses Change - How to Handle #8

Open lellis1936 opened 4 months ago

lellis1936 commented 4 months ago

Tuya devices IP addresses are assigned via DHCP and they VERY frequently change. This is a problem when using the local Tuya API, where documentation here shows requiring an IP address for input, e.g.

var device = new TuyaDevice(DEVICE_IP, DEVICE_KEY, DEVICE_ID, TuyaProtocolVersion.V33);

If you have a hard-coded IP adress, and it's is no longer correct, your Tuya requests will time out.

In point of fact you may substitute a hostname for the device in place of the IP. This protects your app from being affected by IP address changes. For example, in my case, the Tuya device hostname is ESP_B2BA2B (more about this name follows the sample code).

const string DEVICE_HOSTNAME = "ESP_B2BA2B";
var device = new TuyaDevice(DEVICE_HOSTNAME, DEVICE_KEY, DEVICE_ID, TuyaProtocolVersion.V33);

I found I needed to suffix the host name with a period, so my actual code was const string DEVICE_HOSTNAME = "ESP_B2BA2B.";
var device = new TuyaDevice(DEVICE_HOSTNAME, DEVICE_KEY, DEVICE_ID, TuyaProtocolVersion.V33);

If you have a domain configured for your router or your LAN, you may need to include that, e.g. const string DEVICE_HOSTNAME = "ESP_B2BA2B.local";

Getting the hostname

If you know the currently assign IP address you can get the host name as follows: nslookup

If a hostname is assigned it will appear in the nslookup response.

It might be good to include information in the WIKI about using hostnames for the local Tuya API.