Python - Monitor Domoticz IP address

From Domoticz
Jump to: navigation, search


This script queries the current device for its IP address and records it to a Virtual Text Sensor within Domoticz. It has been useful in environments with headless devices (e.g. Raspberry Pi Zero) where fixed IP addresses are unavailable and the device's IP address is subject to change. The IP address record will only update within Domoticz if it has changed from the stored value.

This script will create 1 Virtual Sensor to monitor the IP address of this device:

  • IP Address

Dependencies - hardware / software / operating system

  • Linux
  • Python


  • Within Domoticz open the Setup > Hardware screen
  • Create 1 Virtual Sensor with the "Text" Type named:
    • IP Address
  • Within Domoticz open the Setup > Devices screen and note the IDX of the new Virtual Sensor added, you'll need this in the Python script
  • Create a new file within /domoticz/scripts/python/ called
  • Change the permissions on to allow it to run from crontab
  • Edit the file
  • Copy and paste the contents of the Python script section below
  • Change the following fields:
    • domoticzserver (to match your IP address or localhost)
    • switchid (the IDX of the Virtual Sensor)
  • Save changes and run the Python script, if successful after a moment it will display your IP address
  • Within Domoticz open the Utility tab and check that data is being recorded

Python script


import datetime
import os
import urllib2
import json


def log(message):
  print message

def domoticzrequest (url):
  request = urllib2.Request(url)
  response = urllib2.urlopen(request)

domoticzurl = "http://" + domoticzserver + "/json.htm?type=devices&rid=" + switchid
json_object = json.loads(domoticzrequest(domoticzurl))
if json_object["status"] == "OK":
  if json_object["result"][0]["idx"] == switchid:
    existing_ipv4 = json_object["result"][0]["Data"]

# change eth0 to wlan0 for WiFi connections
ipv4 = os.popen('ip addr show eth0').read().split("inet ")[1].split("/")[0]
if ipv4 == existing_ipv4:
  log ("%H:%M:%S") + "- " + device + ": " + ipv4 + ", status unchanged")
  log ("%H:%M:%S") + "- " + device + ": " + ipv4 + ", status updated")
  domoticzrequest("http://" + domoticzserver + "/json.htm?type=command&param=udevice&idx=" + switchid + "&nvalue=0&svalue=" + ipv4)