阿里云物联网平台IoT Studio调用人脸识别服务示例

  1. 云栖社区>
  2. 博客>
  3. 正文

阿里云物联网平台IoT Studio调用人脸识别服务示例

taro_秋刀鱼 2020-03-30 12:38:39 浏览874
展开阅读全文

概述

目前IoT Studio服务开发模块提供了云市场人脸识别API的调用模块,但是还没有直接调用阿里云人脸识别API的方法,本文从设备端开始上传图片到oss服务,然后通过上行消息传递图片URL,使用NodeJS节点进行阿里云人脸识别服务的调用,将调用的结果通过云数据库MySQL进行存储。

Step By Step


一、设备端开发

1、pom.xml

    <dependencies>
        <dependency>
            <groupId>org.eclipse.paho</groupId>
            <artifactId>org.eclipse.paho.client.mqttv3</artifactId>
            <version>1.1.0</version>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>23.0</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.62</version>
        </dependency>

        <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>3.8.0</version>
        </dependency>
    </dependencies>

2、Device Code Sample

import com.alibaba.taro.AliyunIoTSignUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class FaceDemoUpload {

    public static String productKey = "a1o9N******";
    public static String deviceName = "d******";
    public static String deviceSecret = "7Ukl6Ka80nIEXhUwCmw7XrUC********";
    public static String regionId = "cn-shanghai";

    // 物模型-属性上报topic
    private static String pubTopic = "/sys/" + productKey + "/" + deviceName + "/thing/event/property/post";
    // 自定义topic,在产品Topic列表位置定义
    private static String subTopic = "/sys/" + productKey + "/" + deviceName + "/thing/event/property/post_reply";

    private static MqttClient mqttClient;

    public static void main(String[] args) {

        initAliyunIoTClient();
        ScheduledExecutorService scheduledThreadPool = new ScheduledThreadPoolExecutor(1,
                new ThreadFactoryBuilder().setNameFormat("thread-runner-%d").build());

        scheduledThreadPool.scheduleAtFixedRate(() -> postDeviceProperties(), 10, 5, TimeUnit.SECONDS);

        try {
            mqttClient.subscribe(subTopic); // 订阅Topic
        } catch (MqttException e) {
            System.out.println("error:" + e.getMessage());
            e.printStackTrace();
        }

        // 设置订阅监听
        mqttClient.setCallback(new MqttCallback() {
            @Override
            public void connectionLost(Throwable throwable) {
                System.out.println("connection Lost");

            }

            @Override
            public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
                System.out.println("Sub message");
                System.out.println("Topic : " + s);
                System.out.println(new String(mqttMessage.getPayload())); //打印输出消息payLoad
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

            }
        });

    }

    /**
     * 初始化 Client 对象
     */
    private static void initAliyunIoTClient() {

        try {
            // 构造连接需要的参数
            String clientId = "java" + System.currentTimeMillis();
            Map<String, String> params = new HashMap<>(16);
            params.put("productKey", productKey);
            params.put("deviceName", deviceName);
            params.put("clientId", clientId);
            String timestamp = String.valueOf(System.currentTimeMillis());
            params.put("timestamp", timestamp);
            // cn-shanghai
            String targetServer = "tcp://" + productKey + ".iot-as-mqtt." + regionId + ".aliyuncs.com:1883";

            String mqttclientId = clientId + "|securemode=3,signmethod=hmacsha1,timestamp=" + timestamp + "|";
            String mqttUsername = deviceName + "&" + productKey;
            String mqttPassword = AliyunIoTSignUtil.sign(params, deviceSecret, "hmacsha1");

            connectMqtt(targetServer, mqttclientId, mqttUsername, mqttPassword);

        } catch (Exception e) {
            System.out.println("initAliyunIoTClient error " + e.getMessage());
        }
    }

    public static void connectMqtt(String url, String clientId, String mqttUsername, String mqttPassword) throws Exception {

        MemoryPersistence persistence = new MemoryPersistence();
        mqttClient = new MqttClient(url, clientId, persistence);
        MqttConnectOptions connOpts = new MqttConnectOptions();
        // MQTT 3.1.1
        connOpts.setMqttVersion(4);
        connOpts.setAutomaticReconnect(false);
        connOpts.setConnectionTimeout(10);
//        connOpts.setCleanSession(true);
        connOpts.setCleanSession(false);

        connOpts.setUserName(mqttUsername);
        connOpts.setPassword(mqttPassword.toCharArray());
        connOpts.setKeepAliveInterval(60);

        mqttClient.connect(connOpts);
    }

    /**
     * 汇报属性
     */
    private static void postDeviceProperties() {

        try {
            //上报数据
            //高级版 物模型-属性上报payload
            System.out.println("上报属性值");

            //上传本地图片
            // Request body  C:\Users\Administrator\Desktop\timg.jpg
            String pic_path = "C:\\Users\\Administrator\\Desktop\\timg.jpg";//本地图片的路径

            String picURL = uploadPicToOss(pic_path);

            String payloadJson = "{\"params\":{\"textdata\":\"" + picURL + "\"}}";
            MqttMessage message = new MqttMessage(payloadJson.getBytes("utf-8"));
            message.setQos(1);
            mqttClient.publish(pubTopic, message);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }


    public static String uploadPicToOss(String filePath) {
        // Endpoint以上海为例,其它Region请按实际情况填写。
        String endpoint = "http://oss-cn-shanghai.aliyuncs.com";
        String bucketName = "taro******";  // bucket名称
        String key = "pic/timg.jpg";   // 文件路径及名称
        // 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号。
        String accessKeyId = "LTAIOZZg********";
        String accessKeySecret = "v7CjUJCMk7j9aKduMA************";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 创建PutObjectRequest对象。
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, new File(filePath));

        // 如果需要上传时设置存储类型与访问权限,请参考以下示例代码。
        ObjectMetadata metadata = new ObjectMetadata();

        // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
        metadata.setObjectAcl(CannedAccessControlList.PublicRead);
        putObjectRequest.setMetadata(metadata);

        // 上传文件。
        ossClient.putObject(putObjectRequest);

        // 关闭OSSClient。
        ossClient.shutdown();

        return "https://" + bucketName + ".oss-cn-shanghai.aliyuncs.com/" + key; // 返回图片在OSS中公网可以直接访问的URL
    }
}

参考链接:基于开源JAVA MQTT Client连接阿里云IoT

二、服务开发模块搭建

1、设备触发
_

2、Node.js 脚本
_

/**
* @param {Object} payload 上一节点的输出
* @param {Object} node 指定某个节点的输出
* @param {Object} query 服务流第一个节点的输出
* @param {Object} context  { appKey, appSecret }
*/

module.exports = async function (payload, node, query, context) {

  const Core = require('@alicloud/pop-core');

  var client = new Core({
    accessKeyId: 'LTAIOZZg********',
    accessKeySecret: 'v7CjUJCMk7j9aKduMA************',
    endpoint: 'https://face.cn-shanghai.aliyuncs.com',
    apiVersion: '2018-12-03'
  });

  var params = {
    "ImageUrl": query.props.textdata.value
  }

  var requestOption = {
    method: 'POST'
  };

    var result = await client.request('GetFaceAttribute', params, requestOption);
    return result;
}

参考链接:阿里云新版人脸识别 NODEJS 使用示例教程

三、云数据库MySQL

_

数据库建表语句:

/*------- CREATE SQL---------*/
CREATE TABLE `iotface1` (
  `face_num` INT DEFAULT NULL,
  `gender` INT DEFAULT NULL,
  `glass` INT DEFAULT NULL,
  `expression` INT DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8

参考链接: IoT Studio服务开发MySQL数据流转示例Demo

部署运行

_

四、运行测试

1、设备端日志
_

2、节点日志
_

3、数据库输入插入查询
_

参考链接

IoT Studio服务开发MySQL数据流转示例Demo
阿里云物联网平台博客综述
阿里云新版人脸识别综述

网友评论

登录后评论
0/500
评论