Through a simple example, this paper mainly introduces how to use raspberry PI to quickly access the Alibaba Cloud iot Platform, and achieve a simple monitoring personnel in and out and take photos to send the nail group scene

scenario

The raspberry PI and infrared sensor are arranged at the entrance of the gate of the company to realize the automatic photographing and sending of the nail group robots when the entrance and exit personnel come in and out

To prepare

Material preparation

  • Raspberry pie
  • Hc-sr501 human infrared sensor
  • Raspberry PI CAM
  • Female to female Dupont line three

Ali Cloud environment preparation

  • Internet of Things Platform
  • Object storage OSS
  • Function to calculate
  • Log Service (optional)

steps

1 Cloud Development

1.1 Internet of Things platform

Log in to ali Cloud console and enter the Control panel of iot platform

1.1.1 Creating a Product

Enter device management, create a product, select the basic version or advanced version can be used in this exampleBasic versionYou can meet the basic requirements.



The system will automatically create 3 topics that we need to use/ProductName/${deviceName}/updateIs used as the Topic for sending device alarm messages.

1.1.2 Device Management

Add devices to the product and get the device’s three-tuple, which is required when writing the device code in Section 2.3. Device triples are unique identifiers for devices

1.1.3 Creating a Rule Engine

The significance of setting the rule engine lies in that the message data sent by the device can be forwarded to other services of Ali Cloud by configuring forwarding rules, such as RDS, TBS and function calculation. We need to pay attention to the changes in the JSON data format from the device side to the rule engine after processing. The following is the evolution of the basic version:



The format of the JSON we send to the device side message is:

{
    'photo': 'xxxxxxx.jpg'
}Copy the code

Create a new rule and select JSON as the data format. Write SQL to process data

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

After the configuration is complete, we can debug the simulation to check whether the rule is correct:



Next, configure data forwarding to forward the data to the FC function calculation. Select the services and functions created in step 1.3, respectively.

1.2 Object Storage

Since photos taken on the device side need to be displayed in the pins, storing photos on OSS is a solution.

1.2.1 new bucket

Create a new bucket for storing photos sent to the device. Read and write permissions select public read and then create the photo directory in the bucket.

1.3 Function Calculation

The JSON data forwarded by the rule engine of the Internet of Things platform is forwarded to the nail robot interface by establishing a function to realize message notification in the nail group

1.3.1 Creating a Service

If you need to log the execution of a newly created service and trace functions, enable the log service and configure the log warehouse.

1.3.2 Creating a Function

Create a new function using a blank template, without triggers, and choose PYTHon2.7

1.3.3 Function code
# -*- coding: utf-8 -*-

import logging
import json
import requests

# pin message sending implementation
def post(data):
    webhook_url='https://oapi.dingtalk.com/robot/send?access_token=${Token}' # pin swarm robot webhook URL
    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 a pin markdown message
def post_markdown(title,text):
    data = {
        "msgtype": "markdown"."markdown": {
            "title": title,
            "text": text
        },
        "at": {
            "atMobiles": []."isAtAll": False
        }
    }
    post(data)

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

2 Device side development

When the HC-SR501 module senses someone moving, it will output a high level and trigger the camera to take a photo, store the photo file to the OSS and send a message to the /ProductName/${deviceName}/update message queue of the IOT platform

2.1 Hardware Installation

  1. Connect the camera
  2. Connect the VCC pin of hc-sr501 human infrared sensor to 5v, that is, pin4, I/O pin to pin18, and GND pin to ground pin6

2.2 Environment Preparation

We use python2.7 as the development language on raspberry PI.

PIP install aliyun-python-sdK-iot-client 2. PIP install oss2 3.cdPy -demo 5. mkdir photo (temporary directory for local photos) 6. vim monitor.pyCopy the code

2.3 Code Development

Monitor.py contains the following contents:

# -*- 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

# parameter definition
options = {
    'productKey': '${productKey}'.Device id triplet
    'deviceName': '${deviceName}'.Device id triplet
    'deviceSecret': '${deviceSecret}'.Device id triplet
    '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 human body infrared sensor is set to read pin label
}

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

Take a photo to save oss and send a notification
def takephoto2oss(client):

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

    # to save the 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)

    Initialize the camera
    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:
        # Alarm when high level signal is input
        if GPIO.input(options['ir_pin']) == True:
            print " Someone is coming!"
            takephoto2oss(client)
        else:
            continue
        sleep(3)Copy the code

3 Test Run

3.1 Running on the device

Run it in the py-demo folder

python monitor.pyCopy the code

3.2 Viewing Incoming Messages on the Cloud

The device interface is displayed to observe the device status



In the Topic list for the device, you can also see the number of published messages



premiumThe product also provides message logging, which in this case isBasic version, does not have this function.

3.3 Results of nailing group robots

When someone comes in and out of the door, the Tacks can receive a notification from the robot

3.4 Follow-up Improvement

If you are interested, you can further combine the face recognition service of Ali Cloud, and then cooperate with the relay to achieve the function of personnel attendance and access control

conclusion

Through the IOT ali cloud platform, combining with ali cloud with other products and services, users can quickly build a set of cloud based edge end of IOT products, developers can focus on the development of the business level, and don’t have to spend too much energy on the bottom and communication, greatly reduce the development cycle, has realized the rapid development of the product and iteration, saving the cost of development.