Receive Motion Alarm Notifications in Slack

Motion Sensor

In this tutorial I will show you how to make a flow in Node-RED editor that will send motion alarm triggered notifications to your Slack account. Same as before, our Node-RED app will be hosted on Bluemix. If you are not familiar with Node-RED, Bluemix platform and how to connect an ESP8266 to it, check this tutorial.

Our ESP8266 device will send MQTT messages to Bluemix, and that data will be sent to Slack over HTTP protocol.

As a motion sensor we will use one of these cheap PIR sensor modules, which are quite good and sensitive, bearing in mind their price. It has three pins, two for power supply and one data pin. Data pin outputs digital signal. Whenever sensor detects a motion in its range, data pin is set HIGH. Module should be powered with 5V. Since ESP8266 chip uses 3.3V, if you want to avoid using separate power supply for PIR sensor, you should do a small hardware modification. In order to work reliably, power supply should be applied to the pad labeled ‘H’ (see photo). Some modules have already a pin soldered to it, but some don’t and you will have to solder a jumper wire to it.

Soldered 3.3V power supply wire

Connect ground and power pins and connect data pin to one of the ESP8266’s GPIO pins.

Schematics

Our device will constantly check signal value at the GPIO pin, and only if a transition from low to high state occurs, it will publish appropriate message to Bluemix.

#include <ESP8266WiFi.h>
#include <PubSubClient.h> // https://github.com/knolleary/pubsubclient/releases/tag/v2.3

const char* ssid = "";
const char* password = "";

#define ORG "<yourOrganization>"
#define DEVICE_TYPE "ESP8266"
#define DEVICE_ID "<yourDeviceID>"
#define TOKEN "<yourToken>"

char server[] = ORG ".messaging.internetofthings.ibmcloud.com";
char topic[] = "iot-2/evt/motionSensor/fmt/json";
char authMethod[] = "use-token-auth";
char token[] = TOKEN;
char clientId[] = "d:" ORG ":" DEVICE_TYPE ":" DEVICE_ID;

#define pir_sensor 12

WiFiClient wifiClient;
PubSubClient client(server, 1883, callback, wifiClient);

const double lat = 42.444299;
const double lon = 19.236563;

String lat_str = String((int)lat) + "." + ((int)(1000000 * lat))%1000000;
String lon_str = String((int)lon) + "." + ((int)(1000000 * lon))%1000000;

void setup() {
 Serial.begin(115200);
 Serial.println();

 pinMode(pir_sensor, INPUT);
 
 Serial.print("Connecting to ");
 Serial.print(ssid);
 WiFi.begin(ssid, password);
 while (WiFi.status() != WL_CONNECTED) {
 delay(500);
 Serial.print(".");
 } 
 Serial.println("");

 Serial.print("WiFi connected, IP address: ");
 Serial.println(WiFi.localIP());

 if (!client.connected()) {
   Serial.print("Reconnecting client to ");
   Serial.println(server);
   while (!client.connect(clientId, authMethod, token)) {
   Serial.print(".");
   delay(500);
   }
   Serial.println();
   }
}

bool old_state = LOW;

void loop(){

 bool current_state = digitalRead(pir_sensor);

 if(current_state == HIGH && old_state == LOW){
   
   if (!client.connected()) {
   Serial.print("Reconnecting client to ");
   Serial.println(server);
   while (!client.connect(clientId, authMethod, token)) {
   Serial.print(".");
   delay(500);
   }
   Serial.println();
   }
  
   String payload = "{\"d\":{\"Name\":\"18FE34D81E46\"";
   payload += ",\"sensor_event\":";
   payload += "\"Motion detected\"";
   payload += ",\"lat\":";
   payload += lat_str;
   payload += ",\"lon\":";
   payload += lon_str;
   payload += "}}";

   Serial.print("Sending payload: ");
   Serial.println(payload);
   
   if (client.publish(topic, (char*) payload.c_str())) {
   Serial.println("Publish ok");
   } else {
   Serial.println("Publish failed");
   }
  
   client.loop();
 }

 old_state = current_state;
}

void callback(char* topic, byte* payload, unsigned int length) {
 Serial.println("callback invoked");
}

Configuring Slack Channel

In order to receive messages from Bluemix in your Slack account, you will have to add an integration to a channel you want to use for this purpose. I have made a channel called #sensors.

New channel

Go to channel settings and click add an app or integration.

Channel settings

Search for incoming webhooks which will allow you to receive messages from external sources.

Search for Incoming WebHooks

You have to add a new configuration.

Add configuration

Choose your channel and click add incoming webhooks integration.

Choosing a channel

You will see a page with integration settings. There is a Webhook URL that we need to use in Node-RED to send HTTP requests to Slack.

Webhook URL

Also, you can see a format of a json payload that should be used. Property text is used for message’s content. There are some others like username, icon etc. When you finish with configuration, click save settings at the bottom of the page and you should see appropriate notification in your channel.

Integration added

Node-RED Flow

Your Slack channel is ready to receive messages from external sources. Now we have to make a flow in Node-RED. Make a new app in Bluemix following the same steps from the 3rd tutorial and open Node-RED editor. Our flow consists of IoT input node that collects incoming MQTT messages, function node for message creation and node for sending HTTP requests to Slack.

Flow

Configure your IoT node.

IoT in node

Function node is used to specify all parameters of HTTP request like message content, channel name, username and icon. ESP8266 sends lat and lon values as well, which are used to deliver link to google maps with device location. This is the code in the function node:

var sensor_event = msg.payload.d.sensor_event;
var lat = msg.payload.d.lat;
var lon = msg.payload.d.lon;
var date = new Date();
var loc = "<http://maps.google.com/maps?q=loc:" + lat + "," + lon + ">";

var text = sensor_event + "!\n";
text +="Time: " + date + "\n";
text +="Location: " + loc;

msg.payload =

{
    "channel": "#sensors",
    "username": "MotionSensor",
    "text": text,
    "icon_emoji": ":exclamation:"
};

return msg;

HTTP node receives parameters and sends POST request to the URL that has been generated while configuring the Slack channel.

HTTP request node

That’s it, each time your device publishes an event, you should see a new message in your Slack channel.

Alarm notifications

Lessons of this Series

Trending

Newsletter

Subscribe to our newsletter for good news, sent out every month.

Tags