博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
raspberry pi_如何使用Raspberry Pi测量温度并将其发送到AWS IoT
阅读量:2525 次
发布时间:2019-05-11

本文共 5255 字,大约阅读时间需要 17 分钟。

raspberry pi

What if you want to self-correct the temperature in your office? Or what if you are curious to understand your office environment using IoT sensors?

如果要自我校正办公室的温度怎么办? 或者,如果您想了解使用物联网传感器的办公环境怎么办?

If this sounds interesting to you, please read on.

如果您觉得这很有趣,请继续阅读。

To begin with, we need to set up a temperature reading sensor. We connect it to an Arduino which connects to a RaspberryPi.

首先,我们需要设置一个温度读数传感器。 我们将其连接到Arduino,后者连接到RaspberryPi。

The next step is to set up AWS IoT SDK on your Raspberry Pi.

下一步是在Raspberry Pi上设置AWS IoT SDK。

设置东西 (Setup the Thing)

  1. Create a thing in AWS IoT:

    在AWS IoT中创建事物:

2. Create a single thing to begin with:

2.首先创建一个东西:

3. Create a thing of a particular type. We are using RaspberryPi here (the types are made up by you).

3.创建特定类型的事物。 我们在这里使用RaspberryPi(类型由您决定)。

4.Create a certificate for your Thing to communicate with AWS:

4.为您的Thing创建证书以与AWS通信:

5. Download the certificates, a root certificate authority (CA), activate the Thing, and attach the policy.

5.下载证书,根证书颁发机构(CA),激活Thing并附加策略。

6. The policy code is here. It may seem a bit permissive, but it is OK for the demo App.

6.政策代码在这里。 似乎有些宽容,但对于演示应用程序来说还可以。

设置您的RaspberryPi (Setup your RaspberryPi)

Before you start the setup, please copy all certificates and all root CA files over to the RaspberryPI (scp might help you). You also need to install Node.js if you don’t have it already.

在开始设置之前,请将所有证书和所有根CA文件复制到RaspberryPI(scp可能会帮助您)。 如果还没有的话,还需要安装Node.js。

You will also need to install the AWS IoT device SDK.

您还需要安装AWS IoT设备SDK。

sudo apt-get updatesudo apt-get upgradesudo apt-get install nodejsopenssl x509 -in ./CA-roots/VeriSign-Class\ 3-Public-Primary-Certification-Authority-G5.pem -inform PEM -out root-CA.crtchmod 775 root-CA.crtnpm install aws-iot-device-sdk

Here is the code that reads the data from the serial port and sends temperature readings using the AWS IoT device SDK. The code is based on the examples from Amazon.

这是使用AWS IoT设备SDK从串行端口读取数据并发送温度读数的代码。 该代码基于Amazon的示例。

'use strict';console.log('Running...');const SerialPort = require('serialport');const Readline = require('@serialport/parser-readline')const portName = '/dev/ttyACM0';const port = new SerialPort(portName, (err) => {	if (err) {		return console.log('Error: ', err.message);	}});const deviceModule = require('aws-iot-device-sdk').device;const parser = port.pipe(new Readline({ delimiter: '\r\n' }));const rePattern = new RegExp(/C: (.+)F:(.+)/);parser.on('data', (data) => {	const arrMatches = data.match(rePattern);	if(arrMatches && arrMatches.length >= 1) {		const readingInC = arrMatches[1].trim();		console.log(readingInC);		sendDataToTheNube(readingInC);	}});const defaults = {	protocol: 'mqtts',	privateKey: './iot/f5b0580f5c-private.pem.key',	clientCert: './iot/f5b0580f5c-certificate.pem.crt',	caCert: './iot/root-CA.crt',	testMode: 1,	/* milliseconds */	baseReconnectTimeMs: 4000,	/* seconds */	keepAlive: 300,	/* milliseconds */	delay: 4000,	thingName: 'cuttlefish-hub-01',	clientId: 'nouser' + (Math.floor((Math.random() * 100000) + 1)),	Debug: false,	Host: 'a7773lj8lvoid9a.iot.ap-southeast-2.amazonaws.com',	region: 'ap-southeast-2'};function sendDataToTheNube(readingInC) {	const device = deviceModule({	      keyPath: defaults.privateKey,	      certPath: defaults.clientCert,	      caPath: defaults.caCert,	      clientId: defaults.clientId,	      region: defaults.region,	      baseReconnectTimeMs: defaults.baseReconnectTimeMs,	      keepalive: defaults.keepAlive,	      protocol: defaults.Protocol,	      port: defaults.Port,	      host: defaults.Host,	      debug: defaults.Debug	});	device.publish(`temperature/${defaults.thingName}`, JSON.stringify({		temperature: readingInC	}));}

So now what can you do with that data?

那么,现在您可以使用这些数据做什么呢?

You can write a Lambda that enqueues the data for processing. It may look like this:

您可以编写一个Lambda来排队处理数据。 它可能看起来像这样:

require("source-map-support").install();import { Callback, Handler } from "aws-lambda";import { baseHandler } from "../shared/lambda";import logger from "../shared/logger";import {Models} from "../shared/models";import {QueueWriter} from "./queue-writer";const handler: Handler = baseHandler((event: any, callback: Callback) => {    logger.json("Event:", event);    const writer = new QueueWriter();    const { temperature, sensorId } = event;    const reading: Models.Readings.TemperatureReading = {        temperature,        sensorId,    };    writer.enqueue(reading)        .then(() => callback())        .catch(callback);});export { handler };

And your serverless.com file may look like this:

您的serverless.com文件可能如下所示:

functions:    sensorReadings:        name: ${self:provider.stage}-${self:service}-sensor-readings        handler: sensor-readings/index.handler        description: Gets triggered by AWS IoT        timeout: 180        environment:            READING_QUEUE_NAME: ${self:provider.stage}_${self:custom.productName}_reading            READING_DL_QUEUE_NAME: ${self:provider.stage}_${self:custom.productName}_reading_dl        tags:            service: ${self:service}        events:             - iot:                sql: "SELECT * FROM '#'"

I hope this post has saved you some time setting up your device. Thanks for reading!

希望这篇文章为您节省了一些时间来设置设备。 谢谢阅读!

翻译自:

raspberry pi

转载地址:http://wcwzd.baihongyu.com/

你可能感兴趣的文章
Lambda表达式语法进一步巩固
查看>>
Vue基础安装(精华)
查看>>
Git 提交修改内容和查看被修改的内容
查看>>
PAT - 1008. 数组元素循环右移问题 (20)
查看>>
请求出现 Nginx 413 Request Entity Too Large错误的解决方法
查看>>
配置php_memcache访问网站的步骤
查看>>
hibernate的id生成策略
查看>>
树莓派3B+学习笔记:5、安装vim
查看>>
[Spfa][bfs] Jzoj P5781 秘密通道
查看>>
企业帐号进行IPA的打包、分发、下载安装的详细流程(转载)
查看>>
《项目架构那点儿事》——快速构建Junit用例
查看>>
{"errmsg":"invalid weapp pagepath hint: [IunP8a07243949]","errcode":40165}微信的坑
查看>>
DB2V9.5数据库使用pdf
查看>>
Java Bigdecimal使用
查看>>
SQL注入之绕过WAF和Filter
查看>>
jquery validate使用方法
查看>>
DataNode 工作机制
查看>>
windows系统下安装MySQL
查看>>
错误提示总结
查看>>
实验二+070+胡阳洋
查看>>