Building an IoT based realtime attendance system for Slack using Zapier

In this tutorial, we’ll see how to build an IoT based realtime attendance system that sends a message to a Slack channel upon detecting an access card.

We’ll use Ably’s MQTT adapter to communicate with the IoT device and Zapier to send messages to Slack. Ably Integrations provide a way to trigger events and to stream data from Ably’s pub/sub channels.

Prerequisites

For this tutorial, we’ll be using the following hardware components:

  1. Adafruit Feather HUZZAH ESP866 – WiFi enabled board that works with the Arduino software
  2. MFRC522 RFID sensor
  3. Breadboard
  4. Jump wires

and the following software components:

  1. The Arduino IDE
  2. An account with Ably (free or paid)
  3. An account with Zapier (free or paid)
  4. An account with Slack (free or paid)

Step 1 – Connecting the Adafruit HUZZAH ESP8266 board with RFID-MFRC522

The Adafruit Feather Huzzah ESP8266 board comes with an in-built WiFi component that enables it to communicate with other entities over the internet. To connect this board with the RFID component, you’ll need to set it up with the following pin wiring:


Circuit diagram

MFRC522 – Huzzah Pins

  • RST – 4
  • SDA – 5
  • MOSI – 13
  • MISO – 12
  • SCK – 14
  • 3V – 3.3V
  • GNDGND

Caution: Do not connect the power source of the MFRC522 board to the 5V power output on the Feather Huzzah (BATT or USB) as it might fry the reader. Be sure to connect it to 3.3V.

Step 2 – Code to publish messages to Ably over MQTT

In this step, we’ll start writing the code to publish messages to Ably via MQTT when the RFID sensor detects an access card.

Fire up your Arduino IDE and create a new Sketch file. To begin with, you’ll need to add the correct board that you will use so that all the essential libraries are accessible (like WiFi etc).

From your Arduino’s ‘Tools’ menu, go to ‘Board’ → ‘Boards Manager’ and search for ESP8266 and install it.


Boards Manager

Next, you need to include the libraries needed for this app. You can do this by going into Arduino’s ‘Sketch’ menu.

Sketch → Include library → Manage libraries.

Search for MFRC522 and install it. You need this library to enable the communication between the IoT board and the RFID sensor. This library comes with the SPI library as well that you need to set up a serial communication protocol to communicate with any peripheral devices, in this case the RFID sensor.

The last thing that’s needed is an MQTT library. You can use one of the libraries from Arduino’s library manager, but for this tutorial we’ll use the one by Joel Gaehwiler. Search for MQTT, check if you can find the one by Joel and install it.

All these libraries come with a few example sketches that you check out. We’ll write our app from scratch.

In your sketch file, start by including the libraries as follows:

#include <SPI.h>
#include <MFRC522.h>
#include <ESP8266WiFi.h>
#include <MQTT.h>

Next, define the RST and SS pins per the wiring in the previous step, as shown below:

#define RST_PIN   4
#define SS_PIN    5

Next, define the WiFi name and password so the board can connect to the internet using these credentials. Add the following:

const char ssid[] = "<YOUR WIFI NAME>";
const char pass[] = "<YOUR WIFI PASSWORD>";

Don’t forget to replace the credentials in the above statement with your own.

Next, instantiate the libraries so they can be used in the code. Add the following:

MFRC522 mfrc522(SS_PIN, RST_PIN);
WiFiClientSecure net;
MQTTClient client;

Each sketch file comes with two default methods – a setup() method that needs to contain instructions to set the IoT board up with everything that’s need for the app to run, like connection to WiFi, connection to any external hardware components, etc, and a loop() method that runs continuously checking for any changes in the external environment of the IoT device and perform some actions based on that.

Inside the default setup() method of your sketch, add the following:

void setup() {
  Serial.begin(9600);  // Initialize serial communications with the PC
  SPI.begin();         // Init SPI bus
  mfrc522.PCD_Init();  // Init MFRC522 card
  WiFi.begin(ssid, pass); // Init WiFi library's network settings
  client.begin("mqtt.ably.io", 8883, net); // Init communication with the MQTT broker
  client.setOptions(30, true, 1000); // Set client options: int keepAlive, bool cleanSession, int timeout
  connect(); // Call a function to establish connection with the WiFi and the MQTT broker
 }

Each statement is explained by the comment next to it. We’ll define the connect() method next. In this step, you’ll require an Ably API Key, so log into your Ably account, in your apps dashboard, select an existing app or create a new one, then go to the “API Keys” tab to get your Ably API Key.

You’ll notice that the API Key string is separated into two parts by a colon (:). The first part will be the username and the second part will be the password when you try to connect to the Ably MQTT broker. We’ll see this next.

After the setup() method, define the connect() method as shown below:

void connect() {
  Serial.print("Connecting to WiFi..."); // Helpful log in the serial monitor
  while (WiFi.status() != WL_CONNECTED) { //Check if the WiFi is connected yet, print a series of dots until it is
    Serial.print(".");
    delay(1000);
  }
  Serial.print("\nConnecting to Ably MQTT broker...");
  while (!client.connect("<YOUR-CLIENT-ID>", "<FIRST-HALF-OF-YOUR-ABLY-API-KEY>", "<SECOND-HALF-OF-YOUR-ABLY-API-KEY>")) {
    Serial.print("."); //Print dots in the serial monitor while it connects to the Ably MQTT broker
    delay(1000);
  }
  Serial.println("\nConnected to Ably MQTT broker!");
}

Next, in the default loop() method, add the following:

void loop() {
  client.loop(); // This function returns a boolean that indicates if the loop has been successful
  delay(1000);

  // check if card is detected
  if ( ! mfrc522.PICC_IsNewCardPresent() || ! mfrc522.PICC_ReadCardSerial() ) {
    return;
  }

  Serial.println("Card detected!"); //Print to the serial monitor when a card is detected
  char UIDstr[32] = "";
  array_to_string(mfrc522.uid.uidByte, mfrc522.uid.size, UIDstr); // call a method to convert byte array to array_to_string

  // check which employee the UID belongs to
  if( UIDstr == "BD 31 16 8B"){
    client.publish("standup", "Srushtika"); // publish the name of the employee to the standup channel on Ably
    delay(10000); // prevent multiple publishes by delaying the return to the loop.
    return;
  }
}

//method to convert a byte array to a string
void array_to_string(byte array[], unsigned int len, char buffer[]){
    for (unsigned int i = 0; i < len; i++){
      byte nib1 = (array[i] >> 4) & 0x0F;
      byte nib2 = (array[i] >> 0) & 0x0F;
      buffer[i*2+0] = nib1  < 0xA ? '0' + nib1  : 'A' + nib1  - 0xA;
      buffer[i*2+1] = nib2  < 0xA ? '0' + nib2  : 'A' + nib2  - 0xA;
    }
    buffer[len*2] = '\0';
}

Every access card can be identified by a unique identifier, called UID. As you can see, in the above code, I’ve included a simple UID check with a specific UID. In practice, you can have a switch case to match the UIDs with the employee names.

Go ahead and verify that the sketch has no errors by clicking on the ‘tick’ button in the Arduino IDE. Assuming everything is good, connect your board to your computer with its USB cable and upload the sketch to it by clicking on the ‘right arrow’ button. Open the serial monitor (search icon button on the top right) to check the logs.

If you have a connection error for the MFRC522 component, it’s most likely due to a loose connection. The best solution would be to solder the jump wires to the board and the RFID component.

You can check out the full source code for this app on GitHub.

Now, we can very easily verify if the message was successfully published to Ably using the dev console in the Ably dashboard. Open it up, subscribe to the same channel to which you are publishing the messages, in this case “standup” and you should see the logs coming through whenever you present the access card in front of the RFID reader.


Ably dev console

You’ll notice from the logs in the dev console that the data payload of the message is not in fact the same string message you published from your Arduino IDE. This is due to MQTT being a binary protocol, the messages published are in fact encoded and need to be decoded at the recipient client side in order to get the actual message contents out.

For the Integrations, Ably does this automatically so the contents can be directly sent over the integrating application, in this case, Zapier.

Step 3 – Triggering a Zapier endpoint from Ably via Webhooks

In this step, we’ll see how to create a Zapier endpoint and set up an Integrations rule in Ably to trigger the Zap whenever a message is published from the IoT device.

Log into you Zapier account and click on “Make a zap”. The trigger app needs to be “Webhooks by Zapier”.


Zapier setup

The action needs to be “Catch a Raw Hook”, so choose that and continue. In the next screen Zapier will give you a URL, which is the webhook endpoint needed by Ably, so that it can trigger that URL when a message is published on a channel. Copy that out.


Zapier Webhooks endpoint

In another tab, log into your Ably account, go to the Apps Dashboard. In the “Integrations” tab, click:

“New Integration rule” → “Webhook” → “Zapier”


Zapier events Webhook rule

Next, you’ll see a screen to set this Integrations rule up. In the URL field, paste the Zapier endpoint that you copied before. You can add in any optional headers if you like, we won’t be needing any for this app. Fill in the channel filter field with “standup” as this is the channel we are publishing the messages into. This makes sure that whenever a message is published on this channel, the specified webhook endpoint on Zapier will be triggered. Make sure to uncheck the “enveloped” option, as we just want the data payload to go through directly, without any metadata. After this is done, go ahead and create the rule.


New Integration rule settings

The final step before going back to Zapier is to run a quick test to see if everything works fine. Click on “Test rule”, then “Run test”. If successful, it should say so as shown below:


Test Integrations rule

Now, go back to Zapier to finish setting up the Zap. Click on “Test and continue” to finish up the first part of the Zap. In the second part, we want to send a message to Slack, so choose that app and fill in the details as shown in the screenshot below. Feel free to customize the message as you like.


Set up Slack app


Customize slack messages

That’s it, your Zap is all set up. It’s time to test it out.

Step 4 – Testing out the app and further reading

In this final step, we’ll test our application out. So upload the sketch file to your board once again and place the access card near the RFID sensor. This should now result in a message in the Slack channel that you set up as shown below. Simple and easy!


Customize slack messages

Further reading

  1. Check out the full source code for this app
  2. Learn more about the Arduino ecosystem
  3. Find out more about Ably Integrations.
  4. Learn more about Ably features by stepping through our other Ably tutorials
  5. Get in touch if you need help