1.整体架构

基于阿里云的Serverless架构

2.阿里云产品

IoT平台:​​https://www.aliyun.com/product/iot​​

函数计算:​​https://www.aliyun.com/product/fc​​

表格存储:​​https://www.aliyun.com/product/ots​​

OSS存储:​​https://www.aliyun.com/product/oss​​

人脸识别:​​https://data.aliyun.com/product/face​​

3.设备采购

名称

图片

购买

摄像头

淘宝

树莓派

淘宝

4.树莓派设备端开发

4.1 Enable Camera

4.2 目录结构

  1. 在/home/pi目录下创建 iot文件夹,
  2. 在/home/pi/iot创建 photos文件夹,iot.cfg配置文件,iot.py文件

4.3 Python3程序

4.3.1 安装依赖

pip3 install oss2
pip3 install picamera
pip3 install aliyun-python-sdk-iot-client

4.3.2 iot.cfg配置文件

[IOT]
productKey = xxx
deviceName = xxx
deviceSecret = xxx[OSS]
ossAccessKey = xxx
ossAccessKeySecret = xxx
ossEndpoint = xxx
ossBucketId = xxx

4.3.3 iot.py应用程序

#!/usr/bin/python3
# -*- coding: utf-8 -*-
import oss2
from picamera import PiCamera
import time
import aliyunsdkiotclient.AliyunIotMqttClient as AliyunIot
import configparserconfig = configparser.ConfigParser()
config.read('iot.cfg')# IoT
PRODUCE_KEY = config['IOT']['productKey']
DEVICE_NAME = config['IOT']['deviceName']
DEVICE_SECRET = config['IOT']['deviceSecret']HOST = PRODUCE_KEY + '.iot-as-mqtt.cn-shanghai.aliyuncs.com'
SUBSCRIBE_TOPIC = "/" + PRODUCE_KEY + "/" + DEVICE_NAME + "/control";
# oss
OSS_AK = config['OSS']['ossAccessKey']
OSS_AK_SECRET = config['OSS']['ossAccessKeySecret']
OSS_ENDPOINT = config['OSS']['ossEndpoint']
OSS_BUCKET_ID = config['OSS']['ossBucketId']auth = oss2.Auth(OSS_AK, OSS_AK_SECRET)
bucket = oss2.Bucket(auth, OSS_ENDPOINT, OSS_BUCKET_ID)camera = PiCamera()
camera.resolution = (720,480)# Take a photo first, then upload photo to oss
def take_photo():ticks = int(time.time())fileName = 'raspi%s.jpg' % ticksfilePath = '/home/pi/iot/photos/%s' % fileName# take a photocamera.capture(filePath)# upload to ossbucket.put_object_from_file('piPhotos/'+fileName, filePath)def on_connect(client, userdata, flags, rc):print('subscribe '+SUBSCRIBE_TOPIC)client.subscribe(topic=SUBSCRIBE_TOPIC)def on_message(client, userdata, msg):print('receive message topic :'+ msg.topic)print(str(msg.payload))take_photo()if __name__ == '__main__':client = AliyunIot.getAliyunIotMqttClient(PRODUCE_KEY,DEVICE_NAME, DEVICE_SECRET, secure_mode=3)client.on_connect = on_connectclient.on_message = on_messageclient.connect(host=HOST, port=1883, keepalive=60)# loopclient.loop_forever()

5.函数计算开发

5.1 index.js应用程序

const request = require('request');
const url = require('url');
const crypto = require('crypto');
const TableStore = require('tablestore');
const co = require('co');
const RPCClient = require('@alicloud/pop-core').RPCClient;const config = require("./config");//iot client
const iotClient = new RPCClient({accessKeyId: config.accessKeyId,secretAccessKey: config.secretAccessKey,endpoint: config.iotEndpoint,apiVersion: config.iotApiVersion
});
//ots client
const otsClient = new TableStore.Client({accessKeyId: config.accessKeyId,secretAccessKey: config.secretAccessKey,endpoint: config.otsEndpoint,instancename: config.otsInstance,maxRetries: 20
});const options = {url: config.dtplusUrl,method: 'POST',headers: {'Accept': 'application/json','Content-type': 'application/json'}
};module.exports.handler = function(event, context, callback) {var eventJson = JSON.parse(event.toString());try {var imgUrl = config.ossEndpoint + eventJson.events[0].oss.object.key;options.body = JSON.stringify({ type: 0, image_url: imgUrl });options.headers.Date = new Date().toUTCString();options.headers.Authorization = makeDataplusSignature(options);request.post(options, function(error, response, body) {console.log('face/attribute response body' + body)const msg = parseBody(imgUrl, body)//saveToOTS(msg, callback);});} catch (err) {callback(null, err);}
};parseBody = function(imgUrl, body) {body = JSON.parse(body);//face_rect [left, top, width, height],const idx = parseInt(10 * Math.random() % 4);const age = (parseInt(body.age[0])) + "岁";const expression = (body.expression[0] == "1") ? config.happy[idx] : config.normal[idx];const gender = (body.gender[0] == "1") ? "帅哥" : "靓女";const glass = (body.glass[0] == "1") ? "戴眼镜" : "火眼金睛";return {'imgUrl': imgUrl,'gender': gender,'faceRect': body.face_rect.join(','),'glass': glass,'age': age,'expression': expression};
}//pub msg to WebApp by IoT
iotPubToWeb = function(payload, cb) {co(function*() {try {//创建设备var iotResponse = yield iotClient.request('Pub', {ProductKey: config.productKey,TopicFullName: config.topicFullName,MessageContent: new Buffer(JSON.stringify(payload)).toString('base64'),Qos: 0});} catch (err) {console.log('iotPubToWeb err' + JSON.stringify(err))}cb(null, payload);});
}saveToOTS = function(msg, cb) {var ots_data = {tableName: config.tableName,condition: new TableStore.Condition(TableStore.RowExistenceExpectation.IGNORE, null),primaryKey: [{ deviceId: "androidPhoto" }, { id: TableStore.PK_AUTO_INCR }],attributeColumns: [{ 'imgUrl': msg.imgUrl },{ 'gender': msg.gender },{ 'faceRect': msg.faceRect },{ 'glass': msg.glass },{ 'age': msg.age },{ 'expression': msg.expression }],returnContent: { returnType: TableStore.ReturnType.Primarykey }}otsClient.putRow(ots_data, function(err, data) {iotPubToWeb(msg, cb);});
}makeDataplusSignature = function(options) {const md5Body = crypto.createHash('md5').update(new Buffer(options.body)).digest('base64');const stringToSign = "POST\napplication/json\n" + md5Body + "\napplication/json\n" + options.headers.Date + "\n/face/attribute"// step2: 加密 [Signature = Base64( HMAC-SHA1( AccessSecret, UTF-8-Encoding-Of(StringToSign) ) )]const signature = crypto.createHmac('sha1', config.secretAccessKey).update(stringToSign).digest('base64');return "Dataplus " + config.accessKeyId + ":" + signature;
}

5.2 config.js配置文件

module.exports = {accessKeyId: '账号ak',secretAccessKey: '账号ak secret',iotEndpoint: 'https://iot.cn-shanghai.aliyuncs.com',iotApiVersion: '2018-01-20',productKey: 'web大屏产品pk',topicFullName: 'web大屏订阅识别结果的topic',//可选,如果不保存结果,不需要otsotsEndpoint: 'ots接入点',otsInstance: 'ots实例',tableName: 'ots结果存储表',
}

6. Web端App开发

<!DOCTYPE html>
<html><head><meta charset="UTF-8"><title>阿里云IoT</title><style type="text/css">body {line-height: 1.6;font-family: Arial, Helvetica, sans-serif;margin: 0;padding: 0;background: url(http://iot-face.oss-cn-shanghai.aliyuncs.com/iot-face-yq.png) no-repeat;background-color: #202124;}.face-msg {display: inline;font-size: 32px;color: #5FFFF8;padding: 30px 160px 0px 60px;}</style>
</head><body><div style="padding: 190px 10px 0px 360px;"><div class="face-msg" id='glass' style="color: #5FFFF8"></div><div class="face-msg" id='gender' style="color: #FF5FE5"></div><div class="face-msg" id='age' style="color: #FFDD5F"></div><div class="face-msg" id='expression' style="color: #FC4D4D"></div></div><!-- --><div style="position: relative;padding: 145px 10px 0px 165px;"><div style="position: absolute;"><canvas id="myCanvas" width="720px" height="480px"></canvas></div><img id='imageUrl' src="" width="720px" height="480px" /></div><script type="text/javascript" src="http://iot-face.oss-cn-shanghai.aliyuncs.com/zepto.min.js"></script><script src="http://iot-face.oss-cn-shanghai.aliyuncs.com/mqttws31.min.js" type="text/javascript"></script><script type="text/javascript">$(document).ready(function() {initMqtt();});var client;function initMqtt() {//模拟设备参数var mqttClientId = Math.random().toString(36).substr(2);client = new Paho.MQTT.Client("public.iot-as-mqtt.cn-shanghai.aliyuncs.com", 443, mqttClientId);// set callback handlersvar options = {useSSL: false,userName: '替换iotId',password: '替换iot token',keepAliveInterval: 60,onSuccess: onConnect,onFailure: function(e) {console.log(e);}};client.onConnectionLost = onConnectionLost;client.onMessageDelivered = onMessageDelivered;client.onMessageArrived = onMessageArrived;// connect the clientclient.connect(options);}// called when the client connectsfunction onConnect() {// Once a connection has been made, make a subscriptionclient.subscribe("替换订阅数据更新topic");}// called when the client loses its connectionfunction onConnectionLost(responseObject) {if (responseObject.errorCode !== 0) {console.error("onConnectionLost:", responseObject);}}function onMessageArrived(message) {fillData(JSON.parse(message.payloadString))}function onMessageDelivered(message) {console.log("onMessageDelivered: [" + message.destinationName + "] --- " + message.payloadString);}function fillData(data) {$("#age").html(data.age);$("#expression").html(data.expression);$("#gender").html(data.gender);$("#glass").html(data.glass);$("#imageUrl").attr("src", data.imgUrl);var rect = data.faceRect.split(","); //"270,22,202,287"var canvas = document.getElementById("myCanvas");var ctx = canvas.getContext("2d");ctx.clearRect(0, 0, canvas.width, canvas.height);ctx.strokeStyle = '#03A9F4';ctx.lineWidth = 2;ctx.beginPath();ctx.rect(rect[0], rect[1], rect[2], rect[3]);ctx.stroke();};</script>
</body></html>

7. 拍照指令触发器

/*** package.json 添加依赖:"@alicloud/pop-core": "1.5.2"*/
const co = require('co');
const RPCClient = require('@alicloud/pop-core').RPCClient;const options = {accessKey: "替换ak",accessKeySecret: "替换ak Secret",
};//1.初始化client
const client = new RPCClient({accessKeyId: options.accessKey,secretAccessKey: options.accessKeySecret,endpoint: 'https://iot.cn-shanghai.aliyuncs.com',apiVersion: '2018-01-20'
});const params = {ProductKey: "a1p35XsaOS7",TopicFullName: "相机指令topic",MessageContent: new Buffer('{"action":"takephoto"}').toString('base64'),Qos: "0"
};co(function*() {try {//3.发起API调用const response = yield client.request('Pub', params);console.log(JSON.stringify(response));} catch (err) {console.log(err);}
});

物联网平台产品介绍详情:​​https://www.aliyun.com/product/iot/iot_instc_public_cn​​

阿里云物联网平台客户交流群

树莓派+阿里云IoT人脸识别场景实战——业务系统架构类相关推荐

  1. LoRaWAN设备接入阿里云IoT企业物联网平台实战——实践类

    传送门:5个视频讲解,30个场景案例汇总 LoRaWAN设备接入阿里云IoT企业物联网平台实战 随着 IoT 物联网的高速发展,低功耗,远距离,抗干扰的低功耗广域网快速崛起,LoRa与NB-IoT就是 ...

  2. 阿里云 aliyun 人脸识别(1:N) java spring 小程序 小程序上传多图 阿里云oss

    前段时间开发一个小程序需要使用到阿里云(1:N)人脸识别的服务,查询资料发现网上并没有详细的教程,而官方的api文档也写得很简略,于是就有了如下教程,希望能帮助到大家. 目录 服务开通 人脸识别服务开 ...

  3. Java spring boot 阿里云调用人脸识别接口,本地sdk上传到阿里云调用api

    Java spring boot 阿里云调用人脸识别接口 没有写测试类,工具类如下,有access_key_id和access_key_secret传参调用就可使用 代码如下: pom.xml依赖 & ...

  4. 解密阿里云IoT物联网平台MQTT Access Server核心架构

    MQTT是基于TCP/IP协议栈构建的异步通信消息协议,是一种轻量级的发布.订阅信息传输协议.MQTT已逐渐成为IoT领域最热门的协议,也是国内外各大物联网平台最主流的传输协议,阿里云IoT物联网平台 ...

  5. 树莓派+百度云打造人脸识别门禁系统

    先注册一个百度云账号: 然后点击左上角的百度云进入首页: 在首页中选择产品,人工智能,人脸识别,点击进入: 选择立即使用: 在以下页面中由于没用应用,因此点击创建应用,然后直接写上应用名和应用描述就行 ...

  6. 阿里云存储表格存储TableStore-高并发IM系统架构优化实践

    文章地址:https://yq.aliyun.com/articles/66461?utm_campaign=66461&utm_medium=images&utm_source=os ...

  7. python 智能识别 商品_阿里云货架商品识别与管理Python SDK使用示例-阿里云开发者社区...

    概述 货架商品识别与管理(Retail Image Recognition)是基于深度学习.图像检测.图像识别等技术,为新零售品牌商/经销商提供AI商品识别能力的阿里云产品:适用于货架商品识别.陈列识 ...

  8. 关于使用阿里云服务调用识别身份证图片、营业执照的信息抓取接口的简单实现

    1:识别身份证你可以选择用   阿里开放平台提供或者百度开放平台的识别 同理用哪个就要去注册个帐号.自行百度. 再此,使用的是阿里云的人脸识别. 传送门: https://market.aliyun. ...

  9. 阿里云IoT戴高:IoT场景化的本质是打造数智空间

    简介:IoT数智引擎,全面助力空间数智化升级! 在2021云栖大会IoT云端一体硬件与应用创新峰会上,阿里云IoT通用业务总经理戴高表示,每个人.每个企业.每个组织每天都在无数的空间中穿梭,因此IoT ...

最新文章

  1. ADO与ADO.NET的区别与介绍
  2. Hadoop之Hadoop基础知识
  3. 微信应用号(小程序)资源汇总(1010更新)
  4. 【COCOS2DX-LUA 脚本开发之十二】利用AssetsManager实现在线更新资源文件
  5. ubuntu安装atat
  6. angular 使用jsMind
  7. @huangcheng: Fedora 9 GDM开启XDMCP
  8. Python将头像照片转换为漫画,采用GAN深度学习,无噪点
  9. 国外程序员真实生活曝光,谷歌的工资竟这么高
  10. 【转】几个期货基本面因子的研究
  11. C#语言实例源码系列-异或算法加密解密
  12. linux 可道云_Aria2+KodExplorer可道云实现离线下载
  13. 小米5s Plus安装类原生系统
  14. 必须收藏!这13个优秀React JS框架,没用过就很离谱!
  15. win10打印服务器纸规格没有显示,win10系统打印机设置纸张大小的操作方法
  16. [NOIP 2005 T2] 过河 (动态规划+简单数论)
  17. 删除maven仓库中的lastUpdated
  18. vue-i18n及ElementUI国际化配置步骤
  19. Ubuntu 18.04.3 双屏显示其中一个屏幕黑屏无法使用的问题 显卡驱动安装问题
  20. 数明SLM27517能驱动MOSFET和IGBT功率开关 低侧栅极驱动器兼容UCC27517

热门文章

  1. Day- 14-常用API
  2. 提示:吃鱼进补也要对症
  3. 学习笔记2-ES6/TypeScript/JavaScript内存优化
  4. 清朝历代皇帝 庙号、谥号、姓名、生卒年、在位时间、年号
  5. 零基础PHP7.4安装curl扩展
  6. 女生适不适合软件测试?从薪资、就业、学习、工作难度和加班多方面解读女生适不适合软件测试这一工作
  7. win7 UAC bypass
  8. 支付宝手续费收款的一个坑
  9. leetcode-数学题
  10. 简单的福彩双色球生成器