Publishing IoT IP Addresses to MQTT

I have been playing around with using ESP8266’s as endpoints around the house for collecting temperature, turning the sprinkler pump on, texting me when the doorbell is pressed, etc.  One of the challenges when doing setup/testing is getting the IP address of them when they first come online.

I am running dnsmasq on a raspberry pi, which provides both local DNS and DHCP services.  This is in no way novel, as it is a pretty vanilla configuration.  What I wanted to share is a small script that monitors for updates to the dnsmasq log, watches for new client releases/renewals and then posts those to the MQTT service.  There are lots of things you can do with it from there, but I usually just subscribe to the topic via terminal or mqtttool on my iPhone.

#!/usr/bin/python
from pygtail import Pygtail
import sys
import re
import time
import paho.mqtt.client as mqtt

client = mqtt.Client()
client.username_pw_set("xxxxxx","xxxxxx")

while (1):
 for line in Pygtail("/var/log/dnsmasq.log"):
   isItACK = re.search(r'DHCPACK',line)                #see if its an ACK
   if isItACK:
     newInput = re.sub(r'^.*DHCPACK\(eth0\).', "", line) #strip everything before mac address
     newInput = newInput.rstrip()                        #strip newlines
     client.connect("xxxxxx.widgetninja.net",1883)       #connect to mqtt
     client.publish("/network/DHCP",newInput)            #publish to mqtt
     client.disconnect                                   #hang up
     #sys.stdout.write(newInput)                         #debugging
 time.sleep(10)

Hope this helps save you some time trying to find the ip address of that new device, be it something you made or otherwise just added to your network.

mqtt

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s