收集大量数据,使用托管及 Serverless 架构,以便您不会在此过程中烧毁。
> 在本教程中,我们将使用运行 MongooseOS 的 WiFi 微控制器 ESP8266 构建一个气象站。通过使用基于 Google Cloud IoT Core 之上的 MQTT 协议来安全地发送数据,然后使用 Firebase Cloud Functions(基于事件的方式)处理数据,并将原始数据保存在 BigQuery,同时在 Firebase 实时数据库中更新设备当前状态。然后可以通过 DataStudio 及 Firebase Hosting 上托管的简单 WebApp 访问数据。
好的,互联网上已经有很多关于『如何建立气象台』的玩法,也有很多方法可以做到。这是一个简单的项目,我将尝试专注于构建端到端解决方案,从数据收集到数据分析。所有这些都将使用托管的 Google Cloud 服务,来概述如何构建完整的 IoT 解决方案。 最后,您可以构建出一个数据的报告,并通过网络进行访问。如下图所示:
我们的最后 WebAPP 访问地址:https://weather-station-iot-170004.firebaseapp.com
Data Studio 报告: https://datastudio.google.com/reporting/0B0w5dnm9bD8sdy1OR1lZQ0l4Vmc
架构图如下所示:
为了易于开发,我将使用已经具有 Cloud IoT Core 连接器(connector)的 MongooseOS,并帮助配置证书、WiFi配置和其他自定义配置的设备的过程。
我们将学习以下的内容:
说了这么多内容,让我们开始 🚀。
Google 最近推出了公开的 beta 版本 Cloud IoT Core,这是一种托管服务,可以使用通用协议(MQTT 和 HTTP)与您的 IoT 设备进行安全通信,并以简单的方式管理这些设备。 基本上,通过这项服务,您可以与许多其他 Google 服务连接,以便于处理、存储和分析设备生成的所有数据。在这里,我们可以看到使用 Cloud IoT Core 的推荐架构的例子。
Cloud IoT Core 有一个设备注册的(registry of devices)的概念,其中我们的项目我们将组合一系列类似的设备并与此注册表关联。要开始使用 Google Cloud,您可以在 Cloud Console Web 界面上完成所有操作,但是命令行工具是一个更强大的工具,它是我选择在此项目中使用的工具。
要使用 gcloud
命令行工具,请按照此处的说明进行下载并安装。
Installing Cloud SDK | Cloud SDK Documentation | Google Cloud Platform
安装完 SDK 后,您应该安装测试版工具来访问 Cloud IoT Core 命令。此外,您应该在本教程中验证和创建一个要使用的项目,使用您要为此项目的名称,用于替换 YOUR_PROJECT_NAME
:
# Install beta components:
gcloud components install beta
# Authenticate with Google Cloud:
gcloud auth login
# Create cloud project — choose your unique project name:
gcloud projects create YOUR_PROJECT_NAME
# Set current project
gcloud config set project YOUR_PROJECT_NAME
现在,在 Cloud IoT Core 方面,您首先应该配置一些与 Cloud PubSub 相关的组件,Cloud PubSub 是 Cloud IoT Core 使用的主要组件之一。在下面的命令中,您将执行以下操作:
# Add permissions for IoT Core
gcloud projects add-iam-policy-binding YOUR_PROJECT_NAME --member=serviceAccount:cloud-iot@system.gserviceaccount.com --role=roles/pubsub.publisher
# Create PubSub topic for device data:
gcloud beta pubsub topics create telemetry-topic
# Create PubSub subscription for device data:
gcloud beta pubsub subscriptions create --topic telemetry-topic telemetry-subscription
# Create device registry:
gcloud beta iot registries create weather-station-registry --region us-central1 --event-pubsub-topic=telemetry-topic
如果您访问 Google Cloud Console,您可以验证它是否已创建和配置。
对于这个项目,我将使用最新的 ESP32 WiFi 微控制器。对于那些不了解它的人来说,它是来自 ExpressIf 的相关成功的 ESP8266 WiFi 微控制器的升级版。但它拥有更多功能,如内置蓝牙低功耗、双核心处理器时钟频率为 240MHz、触摸传感器和支持闪存加密,所以没有人可以访问您的代码。一个地狱式的升级。
该项目也适用于 ESP8266,因此这里提供的代码和原理图可以在两个微控制器上运行。该项目的电路非常简单,只需将温度(DHT)传感器连接到 ESP32/ESP8266,如下图所示:
为了对开发板编程,我们将使用 MongooseOS,这是一个操作系统,具有许多很棒的功能,并且可以用于商业胜任。它支持一些微控制器,如 CC3200,ESP32 和 ESP8266。其中一个很酷的功能是使用 Javascript 快速原型化嵌入式应用程序的可能性,并且它有一个名为 mos 的工具,使得编程、配置和配置在支持的开发板上变得非常简单。
要使用它,我们需要从官方网站下载并安装。 按照 https://mongoose-os.com/docs/quickstart/setup.html 上的安装说明进行操作。
安装工具后,下载在此链接的 Github 仓库上的项目代码:Build a Weather station using Google Cloud IoT Core and Mongoose OS,以便您可以在设备上构建和部署它。
这个仓库包含了三个子项目:
这里有一些 firmware 项目的描述:
要对硬件编程,请进入 firmware 文件夹,并运行以下说明来烧录固件,在 Cloud IoT Core 上配置 WiFi 并配置设备:
mos build --arch esp32
或者 mos build --arch esp8266
。此命令来构建我们硬件的固件。mos flash
来刷新固件。mos wifi your_ssid your_pass
在您的设备上配置 WiFi。mos gcp-iot-setup --gcp-project YOUR_PROJECT_NAME --gcp-region us-central1 --gcp-registry YOUR_REGISTRY
就这样,您的设备将开始向 Cloud IoT Core 发送数据。这些项目配置为每分钟发送数据,您可以在 fs/init.js
文件中进行更改,也可以创建自定义配置变量来更改时间。我会把这作为一个 homework。 您可以使用 mos console
工具查看设备上发生的情况。您会看到它尝试与 mqtt.googleapis.com 连接。
$ mos console
Using port /dev/cu.SLAB_USBtoUART
[Oct 15 18:17:47.230] pm open,type:2 0
[Oct 15 18:17:47.234] mgos_sntp_ev SNTP reply from 192.99.2.8: time 1508102268.124028, local 15.317275, delta 1508102252.806753
[Oct 15 18:17:47.448] mgos_mqtt_ev MQTT CONNACK 4
[Oct 15 18:17:47.455] mgos_mqtt_ev MQTT Disconnect
[Oct 15 18:17:47.463] mqtt_global_reconnec MQTT connecting after 2017 ms
[Oct 15 18:17:48.167] Info: {"hum":34,"temp":30,"free_ram":35.593750,"total_ram":51.218750}
[Oct 15 18:17:49.487] mgos_mqtt_global_con MQTT connecting to mqtt.googleapis.com:8883
要查看 PubSub 上的数据,您可以使用 gcloud
命令来查询我们创建的订阅:
$ gcloud beta pubsub subscriptions pull --auto-ack telemetry-subscription
┌───────────────────────────────────────────────────────────┬─────────────────┬─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│ DATA │ MESSAGE_ID │ ATTRIBUTES │
├───────────────────────────────────────────────────────────┼─────────────────┼─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤
│ {"hum":35,"temp":32,"free_ram":167344,"total_ram":253928} │ 158362578982703 │ deviceId=esp32_02455C deviceNumId=2799497560622332 deviceRegistryId=weather-station-registry deviceRegistryLocation=us-central1 projectId=weather-station-iot-170004 subFolder= │
└───────────────────────────────────────────────────────────┴─────────────────┴─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
如果您在控制台上看到数据,您可以开始庆祝,我们走在正确的路上 🎉🏆
直接从官方网站了解 BigQuery 的定义:
> BigQuery 是 Google 的低成本、完全可管理的 PB 级可扩展数据存储服务。BigQuery是独立的,没有要管理的基础设施,并且随着数据扩展,您不需要数据库管理员。
在这里,我们将使用它来存储我们收集的所有传感器数据,以运行一些查询,并在以后使用 Data Studio 构建报告。我们将创建一个数据集和一个表存储我们的数据。要执行此操作,请打开 BigQuery Web UI,然后按照以下说明进行操作:
现在为了在 BigQuery 中插入数据,我们将使用 Firebase Cloud Functions,可以配置为基于许多不同的触发器和事件执行。其中一个触发器是在 PubSub 主题中插入的新数据,因此我们将监听与我们的设备注册表关联的主题,并收集到达的每个数据,我们执行一个在 BigQuery 中存储数据的功能,并在 Firebase 实时数据库里维护最后的设备数据。
Firebase 实时数据库是一种非常有用的维护实时数据的技术,可在所有连接的客户端之间实现自由和自动同步。即使 Google 也推荐它来保持物联网设备的实时状态,见:https://cloud.google.com/solutions/iot-overview,就像我们在这里看到的一样。
我们的函数的代码可以在上面看到,它基本上对 PubSub 事件做出反应并插入 BigQuery,同时进行更新。
Firebase 命令行工具需要 Node.JS 和 npm,您可以按照 https://nodejs.org/ 上的说明进行安装,安装 Node.js 也将安装 npm。
一旦安装了 Node 和 NPM,运行以下命令来安装Firebase CLI。
npm install -g firebase-tools
现在要使用我们的项目配置 firebase 并部署函数,在项目根文件夹中,按照以上说明进行操作:
firebase login
,与 Google 进行身份验证并设置命令行工具firebase init
将本地项目与您的 Firebase 项目关联。firebase functions:config:set
bigquery.datasetname="weather_station_iot"
bigquery.tablename="raw_data”
firebase deploy
以在 public 文件夹中部署 “函数” 和“Webapp”。
通过部署函数,您可以设置所有设置来摄取设备发送的遥测数据,并存储在两个存储解决方案中。您可以在 Firebase 控制台上看到所有部署的资源。
如下是上述功能的代码:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const bigquery = require('@google-cloud/bigquery')();
const cors = require('cors')({ origin: true });
admin.initializeApp(functions.config().firebase);
const db = admin.database();
/**
* Receive data from pubsub, then
* Write telemetry raw data to bigquery
* Maintain last data on firebase realtime database
*/
exports.receiveTelemetry = functions.pubsub
.topic('telemetry-topic')
.onPublish(event => {
const attributes = event.data.attributes;
const message = event.data.json;
const deviceId = attributes['deviceId'];
const data = {
humidity: message.hum,
temp: message.temp,
deviceId: deviceId,
timestamp: event.timestamp
};
if (
message.hum < 0 ||
message.hum > 100 ||
message.temp > 100 ||
message.temp < -50
) {
// Validate and do nothing
return;
}
return Promise.all([
insertIntoBigquery(data),
updateCurrentDataFirebase(data)
]);
});
/**
* Maintain last status in firebase
*/
function updateCurrentDataFirebase(data) {
return db.ref(`/devices/${data.deviceId}`).set({
humidity: data.humidity,
temp: data.temp,
lastTimestamp: data.timestamp
});
}
/**
* Store all the raw data in bigquery
*/
function insertIntoBigquery(data) {
// TODO: Make sure you set the `bigquery.datasetname` Google Cloud environment variable.
const dataset = bigquery.dataset(functions.config().bigquery.datasetname);
// TODO: Make sure you set the `bigquery.tablename` Google Cloud environment variable.
const table = dataset.table(functions.config().bigquery.tablename);
return table.insert(data);
}
/**
* Query bigquery with the last 7 days of data
* HTTPS endpoint to be used by the webapp
*/
exports.getReportData = functions.https.onRequest((req, res) => {
const table = '`weather-station-iot-170004.weather_station_iot.raw_data`';
const query = `
SELECT
TIMESTAMP_TRUNC(data.timestamp, HOUR, 'America/Cuiaba') data_hora,
avg(data.temp) as avg_temp,
avg(data.humidity) as avg_hum,
min(data.temp) as min_temp,
max(data.temp) as max_temp,
min(data.humidity) as min_hum,
max(data.humidity) as max_hum,
count(*) as data_points
FROM ${table} data
WHERE data.timestamp between timestamp_sub(current_timestamp, INTERVAL 7 DAY) and current_timestamp()
group by data_hora
order by data_hora
`;
return bigquery
.query({
query: query,
useLegacySql: false
})
.then(result => {
const rows = result[0];
cors(req, res, () => {
res.json(rows);
});
});
});
firebase-tools
还有一个内置服务器,您可以在刚刚运行 firebase 服务的项目文件夹上启动它,默认情况下将启动端口 5000 上的 Web 服务器。
webapp 可以直接在公共目录中看到,逻辑在 public/app.js
,前端在 public/index.html
。这是非常基本的,只有 Javascript,Web Material Component 和 Chart.JS的图表。
如果所有这些都正确设置,那么您可以再次庆祝,因为您开发了 IoT 的端到端解决方案,而无需触摸高级服务器设置。
Data Studio 是一个非常直观的工具,我不会在这里进行探索,所以这个教程变得不那么广泛,但是让你知道,Data Studio 有一个 BigQuery 连接器,所以只需导入你的表格,并使用这个真棒工具提供的不同的可视化。转到 datastudio.google.com 体验。
这是本教程的所有内容,希望您对 Google Cloud IoT Core 感兴趣,这是一个非常棒的服务,您可以使用它来实现强大的功能。该帖子比我玩法的要长一些,但我相信 Google Cloud Platform 上有很多工具。
该项目的代码可以在我的 Github 上找到:https://github.com/alvarowolfx/weather-station-gcp-mongoose-os,以下是一些有趣的链接及内容:
观光\评论区