raspberry pi_如何使用Raspberry Pi测量温度并将其发送到AWS IoT

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 update
sudo apt-get upgrade
sudo apt-get install nodejs

openssl x509 -in ./CA-roots/VeriSign-Class\ 3-Public-Primary-Certification-Authority-G5.pem -inform PEM -out root-CA.crt
chmod 775 root-CA.crt

npm 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!

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

翻译自: https://www.freecodecamp.org/news/how-to-measure-temperature-and-send-it-to-aws-iot-using-a-raspberry-pi-d6f7b196ec35/

raspberry pi

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值