×
Community Blog Building a Simple Entry-Exit Monitoring System on Alibaba Cloud IoT Platform

Building a Simple Entry-Exit Monitoring System on Alibaba Cloud IoT Platform

In this article, we'll implement a simple entry-exit monitoring example based on Alibaba Cloud's IoT Platform.

By Qing Tian

In this article, we mainly describe how to use Raspberry Pi to quickly connect to Alibaba Cloud IoT Platform and implement a simple visitor entry-exit monitoring scenario where a photo of a visitor is taken and sent to the DingTalk chat group.

Scenario

Deploy a Raspberry Pi and an infrared sensor at the company gate to monitor visitors entering and exiting the gate, take photos of visitors and send photos to the DingTalk chat bot.

1

Preparation

Hardware

  • Raspberry Pi
  • HC-SR501 human infrared sensor
  • Raspberry Pi camera
  • Three female-to-female DuPont wires

Alibaba Cloud Environment

Procedures

1. Cloud-Side Development

1.1 IoT Platform

Log on to the Alibaba Cloud IoT Platform Console and go to the IoT Platform Control Panel.

1.1.1.  Create a New Product

Go to Device Management and create a product (either Basic or Premium). In this example, a Basic product can meet the basic requirements. Three topics are automatically created. We need to use /ProductName/${deviceName}/update as the topic for reporting device alert messages.

2

1.1.2.  Manage Devices

Add a device to the product and take note of the device trituple, which will be used later when we write device code in Section 2.3. The device trituple is the unique identifier of the device.

3

1.1.3.  Create a Rule Engine

By configuring forwarding rules, the rule engine can process message data reported from the device and forward the data to other Alibaba Cloud services such as RDS, TBS, and Function Compute. Pay attention to the JSON data format change after the data from the device is processed by the rule engine. The following figure shows the evolution of the Basic product.

4

The JSON data format that we define for reporting messages from the device is:

{
    'photo': 'xxxxxxx.jpg'
}

Create a rule and choose JSON for the data format. Write SQL statements that process the data.

SELECT deviceName() deviceName, photo FROM "/a1O4b4XcICc/+/update"

After the configuration is made, we can perform simulated debugging to check whether the rule is correct:

5

Configure data forwarding and forward data to Function Compute. Select the service and function that we will be created in step 1.3 later.

6

1.2 Object Storage Service

Because photos on the device need to be displayed in the DingTalk chat group, we can store these photos on OSS.

1.2.1.  Create a Bucket

Create a bucket to store photos sent from the device. For the read/write permission, select Public Read. Then create the photo directory in the bucket.

1.3 Function Compute

We can create a function to forward the JSON data that has been forwarded from the rule engine on the IoT Platform to the interface of the DingTalk chat bot. By doing this, we can implement the message notification in the DingTalk chat group.

1.3.1.  Create a Service

Create a service. If we also want to record or backtrack function execution logs, we need to enable Log Service and configure log warehouses.

1.3.2.  Create a Function

Use a blank template to create a function. No triggers are required. Choose Python 2.7 as the runtime environment.

1.3.3.  Write Function Code

# -*- coding: utf-8 -*-

import logging
import json
import requests

# Send messages to the DingTalk group
def post(data):
    webhook_url='https://oapi.dingtalk.com/robot/send?access_token=${Token}' #the URL to the webhook of the DingTalk group chat bot
    headers = {'Content-Type': 'application/json; charset=utf-8'}
    post_data = json.dumps(data)
    try:
        response = requests.post(webhook_url, headers=headers, data=post_data)
        logging.info('Send success')
    except requests.exceptions.HTTPError as exc:
        logging.error("Send Error,HTTP error: %d, reason: %s" % (exc.response.status_code, exc.response.reason))
        raise
    except requests.exceptions.ConnectionError:
        logging.error("Send Error, HTTP connection error!")
        raise
    else:
        result = response.json()
        logging.info('Send Error:%s' % result)
        if result['errcode']:
            error_data = {"msgtype": "text", "text": {"content": "Send Error, reason:%s" % result['errmsg']}, "at": {"isAtAll": True}}
            logging.error("Send Error:%s" % error_data)
            requests.post(webhook_url, headers=headers, data=json.dumps(error_data))
        return result

# Send markdown messages to DingTalk
def post_markdown(title,text):
    data = {
        "msgtype": "markdown",
        "markdown": {
            "title": title,
            "text": text
        },
        "at": {
            "atMobiles": [],
            "isAtAll": False
        }
    }
    post(data)

 # Function Compute entry
def handler(event, context):
    logger = logging.getLogger()
    evt = json.loads(event)
    #OSS endpoint url
    post_markdown('alert','![ screenshot](https://${bucket}.oss-cn-hangzhou.aliyuncs.com/photo/%s)' % evt.get('photo',''))
    logger.info('photo name is %s', evt.get('photo',''))
    return 'OK'

2. Device-Side Development

When the HC-SR501 module detects the motion of a person, it generates high level output and triggers the camera to take a photo. At the same time, it stores a photo file to OSS and sends a message to /ProductName/${deviceName}/update message queue on the IoT Platform.

2.1 Hardware Installation

1.  Properly connect the camera.

2.  Connect the VCC pin of the HC-SR501 human infrared senor module to the 5V pin (pin 4), the I/O pin to pin 18, and the GND pin to pin 6.

7

2.2 Environment Preparation

We use Python 2.7 as the programming language on Raspberry Pi.

(1) pip install aliyun-python-sdk-iot-client
(2) pip install oss2
(3) mkdir py-demo (project program file)
(4) cd py-demo
(5) mkdir photo (temporary directory of local photos)
(6) vim monitor.py

2.3 Code Development

monitor.py contains the following code:

# -*- coding: utf-8 -*-

import json
import uuid
import logging
from time import sleep
from picamera import PiCamera
import RPi.GPIO as GPIO
import oss2
import aliyunsdkiotclient.AliyunIotMqttClient as iot

# Define parameters
options = {
    'productKey': '${productKey}',  # one element of the device identity trituple
    'deviceName': '${deviceName}',  # one element of the device identity trituple
    'deviceSecret': '${deviceSecret}',  # one element of the device identity trituple
    'port': 1883,  # iot mqtt port
    'host': 'iot-as-mqtt.cn-shanghai.aliyuncs.com',  # iot mqtt endpoint
    'endpoint': 'http://oss-cn-hangzhou.aliyuncs.com',  # oss endpoint
    'ak': '${ak}',
    'sk': '${sk}',
    'bucket': '${bucket}',  # oss bucket
    'ir_pin': 24  # the pin number to read data from the infrared sensor module
}

topic = '/' + options['productKey'] + '/' + options['deviceName'] + '/user/test'

# Take photos, store them on OSS and send notifications
def takephoto2oss(client):

    # Take photos
    photo_filename = str(uuid.uuid1()) + ".jpg"
    print('take photo :' + photo_filename)
    camera.capture('photo/' + photo_filename)

    # Store photos to OSS
    print('save photo to oss :' + photo_filename)
    bucket.put_object_from_file(
        'photo/' + photo_filename, 'photo/' + photo_filename)

    # Send messages
    payload_json = {
        'photo': photo_filename
    }
    print('send data to iot server: ' + str(payload_json))
    client.publish(topic, payload = str(payload_json))


def on_connect(client, userdata, flags_dict, rc):
    print("Connected with result code " + str(rc))


def on_disconnect(client, userdata, flags_dict, rc):
    print("Disconnected.")


if __name__ == '__main__':
    # GPIO initialization
    GPIO.setmode(GPIO.BCM)
    GPIO.setwarnings(False)
    GPIO.setup(options['ir_pin'], GPIO.IN)

    # Camera initialization
    camera = PiCamera()
    camera.resolution = (640, 480)
    camera.vflip = True
    camera.hflip = True

    # OSS initialization
    auth = oss2. Auth(options['ak'], options['sk'])
    bucket = oss2. Bucket(auth, options['endpoint'], options['bucket'])

    # IoT MQTT initialization
    client = iot.getAliyunIotMqttClient(options['productKey'], options['deviceName'], options['deviceSecret'], secure_mode = 3)
    client.on_connect = on_connect
    client.connect(host=options['productKey'] + '.' + options['host'], port=options['port'], keepalive = 60)

    while True:
        # Trigger alerts when the input is high level signals
        if GPIO.input(options['ir_pin']) == True:
            print " Someone is coming!"
            takephoto2oss(client)
        else:
            continue
        sleep(3)

3. Test Run

3.1 Run on the Device Side

Run the program under the py-demo file

python monitor.py

3.2 View Messages on the Cloud

View the device status in the device information page.

8

We can see how many messages are published in the Device Topic List.

9

Message logs are available in Premium products. This example uses a Basic product, which does not provide the logging feature.

3.3 Receive the Messages from the DingTalk Group Chat Bot

When someone is entering or exiting the gate, the chat box pushes messages to the DingTalk group.

10

3.4 Make Subsequent Improvements

If you are interested, you can further combine this example with Alibaba Cloud Face Recognition services and relays to implement work attendance tracking and gate access control.

Summary

With the IoT Platform and other Alibaba Cloud offerings, you can quickly create a set of IoT products and services based on integration of cloud, edge, and end. Developers can focus on the business layer, without having to spend too much time on the underlying layer and communication. This can significantly reduce the development cycle, implement fast product R&D and iteration and reduce development cost.

0 0 0
Share on

GXIC

18 posts | 3 followers

You may also like

Comments