Publish iPhone presence messages to a MQTT broker

In two previous posts I explained how we can add iPhone presence detection to our Raspberry Pi 3 and how we can install and use an MQTT client to publish messages.

Now it’s time to combine these to and publish our iPhone presence to our MQTT broker.
In this post I will layout the steps needed to do this

Create a bash script ‘detect_bluetooth_presence.sh’

nano detect_bluetooth_presence.sh

Import the following code and edit the parameters

#!/bin/bash
# Script inspiration form: https://www.domoticz.com/forum/viewtopic.php?t=12570

# Set Parameters
mqttserverip='192.168.XXX.XXX'
bluetoothmac='XX:XX:XX:XX:XX:XX'
mqtttopic='home/sensors/presence/iphone'
messagefound='On'
messagenotfound='Off'
waittimebetweenchecks=10

while [ 1 ]
do
  # Actual pinging...
  result=$(l2ping -c1 -s32 -t1 "$bluetoothmac" > /dev/null && echo $messagefound || echo $messagenotfound)

  if [[ $result == $messagenotfound ]]; then
    # Try once more to connect
    result=$(l2ping -c1 -s32 -t1 "$bluetoothmac" > /dev/null && echo $messagefound || echo $messagenotfound)
  fi

  # Only send a publication if status is changed compared to last check
  if [[ $previousresult != $result ]]; then
    previousresult=$result
    mosquitto_pub -h $mqttserverip -t $mqtttopic -m $result -r
  fi
  sleep $waittimebetweenchecks
done

Now we need to set execute permissions to our script

sudo chmod a=r+w+x detect_bluetooth_presence.sh

Auto run on startup

To run this script on startup we edit our rc.local file

sudo nano /etc/rc.local

Add the line:

sudo /home/pi/detect_bluetooth_presence.sh&

Now reboot and your good to go

Advertisements

One thought on “Publish iPhone presence messages to a MQTT broker”

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