mongoose-iot

This post on freecodecamp.org is not maintained. The most up to date version is on Medium: https://medium.com/free-code-camp/gcp-cloudiotcore-esp32-mongooseos-1st-5c88d8134ac7

freecodecamp.org上的该帖子未维护。 最新版本是在Medium上: https : //medium.com/free-code-camp/gcp-cloudiotcore-esp32-mongooseos-1st-5c88d8134ac7

This post is a step-by-step tutorial for newbies to Google Cloud Platform-Cloud IoT Core. The devices are ESP32 Wifi chips running Mongoose OS. To go through his tutorial, the concepts and then the setup of a simple IoT system measuring weather data are described.

本文是针对Google Cloud Platform-Cloud IoT Core的新手的分步教程。 这些设备是运行Mongoose OS的 ESP32 Wifi芯片 。 为了完成他的教程,先介绍了概念,然后介绍了一个简单的物联网系统( 用于测量天气数据)的设置。

Live demo is here: https://hello-cloud-iot-core.firebaseapp.com/

现场演示在这里: https : //hello-cloud-iot-core.firebaseapp.com/

GitHub for last section (Logging, storing and visualizing weather data with Firebase) is here: https://github.com/olivierlourme/iot-store-display

GitHub的最后一部分 (使用Firebase记录,存储和可视化天气数据) 在这里: https://github.com/olivierlourme/iot-store-display

This post is completed by a second one: see here.

这篇文章由第二篇完成:请参见此处 。

介绍 (Introduction)

1)历史 (1) History)

In a previous 3-post series [link, link, link], we used an ESP8266 Wifi chip to regularly measure luminosity and feed a database with the obtained data. The data set was ultimately lively plotted to a web app (see live plot here: [link]). We massively used Firebase products (Realtime Database, Cloud Functions, SDK and Hosting) to meet our goals.

在之前的三篇文章[ link , link , link ]中,我们使用ESP8266 Wifi芯片来定期测量亮度,并将获得的数据馈入数据库。 最终将数据集生动地绘制到Web应用程序中(请参见此处的实时图:[ 链接 ])。 我们大量使用Firebase产品 (实时数据库,云功能,SDK和托管)来实现我们的目标。

This project works fine, it draws very little power and we enjoyed developing it — but:

该项目运行良好,消耗的功率很小,我们很喜欢开发它,但是:

  • This project was okay to handle just a few connected sensors. Setting up a set of a hundred sensors would require a lot of (rigorous) manual intervention and monitoring them would be challenging as well. Indeed, there is no central place where we can manage our system.

    这个项目可以处理几个连接的传感器 。 设置一组一百个传感器将需要大量(严格)的手动干预,而对它们的监视也将具有挑战性。 确实,没有可以管理系统的中心位置。

  • Arduino IDE and Arduino core for ESP8266 were great for discovering ESP8266 but they are quickly insufficient: The IDE file management is really basic, there is only one program in the chip, and there is no Operating System providing useful APIs for IoT.

    用于ESP8266的 Arduino IDEArduino核心非常适合发现ESP8266,但它们很快就不足 :IDE文件管理确实很基础,芯片中只有一个程序, 没有操作系统 为IoT提供有用的API

  • FirebaseArduino library, allowing an ESP8266 to push data to a Firebase Realtime Database, was experimental. Some features like authentication should be improved. For now, the “secret” type authentication we used gives ESP8266 admin rights over the whole database!

    FirebaseArduino 是实验性的 ,它允许ESP8266将数据推送到Firebase实时数据库。 诸如身份验证之类的某些功能应加以改进。 现在,我们使用的“秘密”类型身份验证为ESP8266授予了整个数据库的管理员权限!

  • Eventually, ESP8266 SPI flash memory was not designed to be encrypted. In our first post [link], we showed how easy it was to recover a Wifi password when reading this memory.

    最终, ESP8266 SPI闪存未设计为加密 。 在我们的第一篇文章[ 链接 ]中,我们显示了读取此内存时恢复Wifi密码是多么容易。

In a word, this past project couldn’t be used in an industrial context. It was more a prototype for a Proof of Concept. We learnt a lot with it but today we’d like to develop a professional and fully secured solution capable of managing in a simple way a lot of connected sensors.

一言以蔽之,这个过去的项目无法在工业环境中使用。 它更是概念验证的原型。 我们从中学到了很多,但是今天我们想开发一种专业且完全安全的解决方案,能够以简单的方式管理许多连接的传感器

This is why we decided to:

这就是为什么我们决定:

  • investigate Google Cloud Platform-Cloud IoT Core [link] to manage our system : devices setup, provision, authentication and monitoring;

    调查Google Cloud Platform-Cloud IoT Core [ 链接 ] 管理我们的系统:设备设置,设置,身份验证和监控;

  • move from ESP8266 to ESP32, which offers memory encryption;

    从ESP8266移至提供内存加密的ESP32 ;

  • run Mongoose OS [link] in our ESP32s. This OS accepts programs written in Javascript(JS) and provides a lot of APIs to deal with time, MQTT protocol, sensors, provisioning, etc. It is easy to interface with the main IoT platforms, including Google Cloud Platform-Cloud IoT Core.

    在我们的ESP32中运行Mongoose OS [ link ]。 该OS接受用Javascript(JS)编写的程序,并提供许多API来处理时间,MQTT协议,传感器,配置等。它很容易与主要的IoT平台(包括Google Cloud Platform-Cloud IoT Core)交互。

2)关于ESP32 Wifi芯片的一句话 (2) A word about ESP32 Wifi chip)

ESP32 Wifi chip is a successor of the famous ESP8266 we described here: [link]. Compared to it, every feature is enhanced (speed up to 240 MHz, two cores, 520 kiB RAM, number of GPIOs, variety of peripherals, etc.) and there are some new ones (Bluetooth: legacy/BLE, 4 MiB-flash memory encryption capability, cryptographic hardware acceleration: AES, SHA-2, RSA, ECC, RNG). There are a lot of resources on the web concerning ESP32. The following one deals with the ESP32 DEVKIT V1 development board that we will use and gives its pinout: [link].

ESP32 Wifi芯片是我们在此处描述的著名ESP8266的后继产品:[ link ]。 与之相比,每个功能都得到了增强(速度高达240 MHz,两个内核,520 kiB RAM,GPIO数量,各种外设等),并且还有一些新功能(蓝牙:legacy / BLE, 4 MiB-flash)内存加密功能加密硬件加速 :AES,SHA-2,RSA,ECC,RNG)。 Web上有很多关于ESP32的资源。 以下是我们将使用的ESP32 DEVKIT V1开发板的详细说明:[ link ]。

There is also this extensive resource concerning the wide variety of ESP32 chips and development kits : http://esp32.net/ . On their home page, searching for “ESP32 DevKit” or “GeekCreit” leads to a link to the schematic of our ESP32 DEVKIT V1. This development board embeds an official Espressif ESP32-WROOM-32 chip and costs about 6€ at Banggood.

关于广泛的ESP32芯片和开发套件,也有大量资源可供参考: http ://esp32.net/。 在他们的主页上,搜索“ ESP32 DevKit”或“ GeekCreit”会指向我们ESP32 DEVKIT V1的原理图的链接。 该开发板嵌入了官方的Espressif ESP32-WROOM-32芯片,在Banggood的售价约为6欧元。

通过用例说明基本的物联网概念 (Basic IoT concepts explained through our use case)

So, what will be our playground for test all these new tools?

那么,我们将如何测试所有这些新工具?

To illustrate IoT concepts through Cloud IoT Core, we chose to build a weather station reporting humidity and temperature from different places.

为了通过Cloud IoT Core阐述IoT概念,我们选择构建一个气象站 ,以报告不同地点的湿度和温度

For simplicity we’ll handle only 2 places: inside our house (“indoor”) and outside our house (“outdoor”). It’s up to you to deal with many more places.

为简单起见,我们仅处理2个地方:房屋内部(“室内”)和房屋外部(“室外”)。 由您决定要处理更多地方。

1)项目硬件:ESP32&DHT22 (1) Project hardware : ESP32 & DHT22)

At each of theses places, we’ll install a connected sensor (“a device”) constituted by a DHT22 humidity/temperature sensor (description: [link], datasheet: [link], 4€ at Banggood) connected to an ESP32 DEVKIT V1 development board. DHT22 observes a kind of “1-Wire” protocol. Each ESP32 will house Mongoose OS for operating system. Its installation on an ESP32, a Hello, World! and a test with a DHT22 are given in the following section below.

在上述每个位置,我们将安装由DHT22 湿度/温度传感器组成的连接传感器( “设备” )(描述:[ 链接 ],数据表:[ 链接 ],4欧元,Banggood) 连接到ESP32 DEVKIT V1开发板。 DHT22遵循一种“ 1-Wire”协议。 每个ESP32将装有用于操作系统的Mongoose OS 。 它安装在ESP32上,您好,世界! 下面的部分将对DHT22进行测试。

Just below are given DHT22 specifications. Afterwards, we think the accuracy figures are a bit optimistic but that’s not our concern today.

以下是DHT22的规格。 之后,我们认为准确度数据有些乐观,但这并不是我们今天关注的问题。

We can already build the following assembly twice (one for indoor and one for outdoor). For now, power will come from the USB connector connected to our host machine. In production, power may come from a power bank.

我们已经可以构建以下组件两次(一个用于室内,一个用于室外)。 目前,电源将来自连接到主机的USB连接器。 在生产中,电源可能来自移动电源。

That’s all for hardware! The rest of the project uses serverless solutions from Google. We describe them now…

硬件就这些了! 该项目的其余部分使用Google提供的无服务器解决方案 。 我们现在描述它们…

2)项目架构:Cloud IoT Core和Firebase (2) Project architecture : Cloud IoT Core & Firebase)

All this “Project architecture” section is theoretical, there is no step to perform. Its aim is to introduce vocabulary and notions related to IoT, more specifically when this domain involves Google Cloud solutions.

所有这些“项目体系结构”部分都是理论上的,没有步骤要执行。 其目的是介绍与物联网相关的词汇和概念,尤其是在涉及Google Cloud解决方案的领域中。

Here is the general architecture of our project:

这是我们项目的一般架构:

Note: There is no gateway between our devices and Cloud IoT Core because they “speak” MQTT.

注意:我们的设备与Cloud IoT Core之间没有网关 ,因为它们“说” MQTT。

Note: Devices can also communicate with Cloud IoT Core via its HTTP bridge. As it is less performant than the MQTT bridge (see a comparison : [link]), we will disallow this communication later during registry configuration. Limiting access just to what is necessary is a good practice.

注意:设备还可以通过其HTTP桥与Cloud IoT Core进行通信。 由于它的性能不如MQTT桥 (请参见比较:[ 链接 ]),因此稍后将在注册表配置期间禁止这种通信。 将访问限制在必要的范围内是一种好习惯。

Let’s explain this architecture in three sections:

让我们分三部分来说明此体系结构:

  • “From Devices to Cloud Pub/Sub” describes the classical Google IoT architecture.
    “从设备到云发布/订阅”描述了经典的Google IoT架构。
  • “From Cloud Pub/Sub to data storage and visualization”, describes the choices we made to exploit data.
    “从Cloud Pub / Sub到数据存储和可视化”,描述了我们为利用数据所做的选择。
  • “Additional config and state topics” completes this architecture presentation.
    “其他配置和状态主题”完成了此体系结构演示。

From Devices to Cloud Pub/Sub

从设备到云发布/订阅

  • Cloud IoT Core
    云物联网核心

Cloud IoT Core is the Google Cloud Platform service to which each of our registered devices will send temperature/humidity data. When such a data is sent, we say that the device publishes a telemetry event (sometimes also called a “telemetry message”).

Cloud IoT Core是Google Cloud Platform服务,我们每个注册的设备都将向其发送温度/湿度数据。 发送此类数据后,我们说该设备发布了一个遥测事件 (有时也称为“遥测消息”)。

Note: Pricing is detailed here : [link]. For small projects with a few devices, there’s little chance you get charged.

注意:此处详细介绍了定价:[ 链接 ]。 对于带有少量设备的小型项目,您几乎没有机会付费。

  • MQTT

    MQTT

This publication is done through a MQTT connection. MQTT is a publish/subscribe-based message protocol; most of the time it lies over TCP [link] (or better: over TLS, itself being over TCP). The telemetry message has to be published by the device (a MQTT client) to the Cloud Iot Core “MQTT bridge” (a MQTT server) in a MQTT topic whose name imperatively respects this format:

该发布是通过MQTT连接完成的 。 MQTT是基于发布/订阅的消息协议; 大多数情况下,它位于TCP [ link ]上(或者更好:位于TLS上,本身位于TCP上)。 遥测消息必须由设备(MQTT客户端)在MQTT主题中发布到Cloud Iot Core“ MQTT桥”(MQTT服务器),其名称必须遵循以下格式:

/devices/{device-id}/events

Note: Sub-folders in the topic name are possible. We won’t need this feature here but see [link], as it can sometimes be useful.

注意:主题名称中的子文件夹是可能的。 我们在这里不需要此功能,但请参阅[ link ],因为有时它会很有用。

{device-id} is unique to each device. In our case, Mongoose OS creates it from the last 3 bytes of the MAC address of the ESP32. For example it could be esp32_ABB3B4.

{device-id}对于每个设备都是唯一的。 在我们的案例中,Mongoose OS从ESP32的MAC地址的后3个字节创建它。 例如,它可能是esp32_ABB3B4

  • Quality of Service (QoS)

    服务质量(QoS)

The MQTT specification describes three Quality of Service (QoS) levels, when publishing to a topic ([link]):

当发布到主题([ link ])时,MQTT规范描述了三个服务质量(QoS)级别:

> QoS 0, the message is delivered at most once;

> QoS 0,消息最多传递一次;

> QoS 1, the message is delivered at least once;

> QoS 1,消息至少传递一次;

> QoS 2, the message is delivered exactly once.

> QoS 2,消息仅发送一次。

Cloud IoT Core does not support QoS 2. And QoS 1 is better than QoS 0. So QoS 1 is the one we will adopt. Mongoose OS can do that.

Cloud IoT Core不支持QoS2。并且QoS 1优于QoS0。因此,我们将采用QoS 1 。 猫鼬操作系统可以做到这一点。

  • Security

    安全

Concerning security, in our Mongoose OS/Cloud IoT Core context, MQTT communications are made over TLS ([link]), so (1) the device is assured to be connected to Cloud IoT Core MQTT server (CA’s certificates are stored in Mongoose OS ca.pem file), (2) the data exchange will be private and (3) data integrity will be checked. On the other way, device authentication ([link]) with Cloud IoT Core is performed with a per-device public/private key authentication using JSON Web Tokens (JWT). The device performs the signature part of the JWT with its private key and Cloud IoT Core validates it using the related public key. Mongoose OS tools handles this keys generation and distribution, we’ll see that soon in the section called “Device registration within the Cloud IoT Core project” lying a few paragraphs below. In this section, we’ll see also how to store securely the private key on the device by performing memory encryption (preventing as well reverse engineering).

关于安全性 ,在我们的Mongoose OS / Cloud IoT Core环境中,MQTT通信是通过TLS ([ 链接 ])进行的,因此(1)确保将设备连接到Cloud IoT Core MQTT服务器(CA的证书存储在Mongoose OS中) ca.pem文件),(2)数据交换将是私有的,(3)数据完整性将得到检查。 另一方面,通过JSON Web令牌(JWT)对每个设备的公/私钥身份验证执行Cloud IoT Core的设备身份验证 ([ 链接 ] ) 。 该设备使用其私钥执行JWT的签名部分,Cloud IoT Core使用相关的公钥对其进行验证。 Mongoose OS工具负责处理此密钥的生成和分发,我们很快会在下面的几段“云IoT核心核心项目中的设备注册”部分中看到。 在本节中,我们还将看到如何通过执行内存加密(防止反向工程)将私钥安全地存储在设备上。

Note: Beyond JWT device authentication, for additional security, it’s possible to impose TLS from Cloud IoT Core to devices (so each device has also a public key certificate, etc.). It is an option we won’t use but it’s described here for Mongoose OS side (see “mutual TLS”) and here for Cloud Iot Core side. It’s good to know that AWS IoT imposes this mutual TLS, unconditionally ([link]).

注意:除了JWT设备身份验证之外,为了提高安全性,还可以从Cloud IoT Core向设备强加TLS(因此,每个设备也具有公共密钥证书等)。 这是一个我们不会使用的选项,但此处在Mongoose OS方面(请参阅“相互TLS”)和在 Cloud Iot Core方面进行了介绍。 很高兴知道,AWS IoT无条件地强加了这种相互TLS([ 链接 ])。

  • Registry

    登记处

Devices sharing the same purpose are regrouped within a registry.

具有相同目的的设备将在注册表中重新分组。

  • Cloud Pub/Sub

    云发布/订阅

Telemetry data from all devices belonging to the same registry is then forwarded to a Cloud Pub/Sub topic (Cloud Pub/Sub is a GCP product [link], not specifically a Cloud IoT Core one). The name of the Cloud Pub/Sub topic follows this pattern:

然后,来自属于同一注册表的所有设备的遥测数据将转发到Cloud Pub / Sub主题 (Cloud Pub / Sub是GCP产品[ 链接 ],而不是Cloud IoT Core的一种)。 Cloud Pub / Sub主题的名称遵循以下模式:

projects/id-of-google-cloud-project/topics/name-of-telemetry-topic

So, if we call our Google Cloud project hello-cloud-iot-core, if we choose weather-telemetry-topic for the name of our Pub/Sub telemetry topic and if finally our registry is called weather-devices-registry, we’ll get sooner or later that kind of view in Google Cloud Console :

因此,如果我们将Google Cloud项目hello-cloud-iot-core ,如果我们选择weather-telemetry-topic作为发布/ Sub遥测主题的名称,并且如果最终我们的注册表称为weather-devices-registry ,则迟早会在Google Cloud Console中获得这种视图:

But no stress, everything will be explained step by step to reach that.

但是没有压力,将逐步解释一切。

Note: As it is said here ([link]), each message in the Cloud Pub/Sub topic contains a copy of the telemetry message published by the device but also some message attributes, the most important being probably deviceID, allowing us to match some received data with the device that published it.

注意:就像这里所说的那样[[ link ]),Cloud Pub / Sub主题中的每条消息都包含该设备发布的遥测消息的副本,还包含一些消息属性 ,最重要的可能是deviceID ,使我们能够进行匹配一些通过发布它的设备收到的数据。

Note: We talk a lot about Pub(lish), but where is the Sub(scribe)? In fact, we’ll create quickly with Google Cloud Command Line Interface a Cloud Pub/Sub subscription (a “pull” one) in order to view the messages published to the telemetry topic. Later in this post, we’ll create a Firebase Cloud Function reacting to each publication and this will automatically create another subscription (a “push” one this time).

注意:我们谈论了很多Pub(lish) ,但是Sub(scribe)在哪里? 实际上,我们将使用Google Cloud Command Line Interface快速创建Cloud Pub / Sub订阅(“拉”订阅),以查看发布到遥测主题的消息。 在本文的稍后部分,我们将创建一个Firebase Cloud Function来对每个发布做出React,这将自动创建另一个订阅(这次是“推送”)。

From Cloud Pub/Sub to data storage and visualization

从Cloud Pub / Sub到数据存储和可视化

We’re following the right part of the project architecture diagram given at the beginning of this post:

我们正在遵循本文开头给出的项目架构图的正确部分:

A publication to the Cloud Pub/Sub topic will trigger a Firebase Cloud Function that will itself fulfill a Firebase Realtime Database with the new data. A web app hosted by Firebase Hosting will lively plot data from the Firebase Realtime Database, in the same way as we did in a previous post: [link].

到Cloud Pub / Sub主题的发布将触发Firebase Cloud Function ,该功能本身将使用新数据满足Firebase Realtime数据库的需求。 由Firebase Hosting托管的 Web应用程序将以与上一篇文章相同的方式生动地绘制Firebase Realtime数据库中的数据:[ 链接 ]。

There are other options in the Google ecosystem to store/treat/visualize data. Alvaro Viebrantz’s really good post [link] that helped us uses Big Query ([link]) and Data Studio ([link]).

Google生态系统中还有其他选项可以存储/处理/可视化数据。 Alvaro Viebrantz的非常好的帖子[ link ]帮助我们使用了Big Query ([ link ])和Data Studio ([ link ])。

Additional “config” and “state” topics

其他“配置”和“状态”主题

On the project architecture diagram given at the beginning of this post, we see besides telemetry two other data flows: Config ([link]) and State ([link]):

在本文开头给出的项目架构图上,除了遥测之外,我们还看到其他两个数据流: Config ([ link ])和State ([ link ]):

Indeed, the Cloud IoT Core service may publish configuration update messages to a special topic the device has subscribed to ([link]). It is useful when we need the device to go to a new state, e.g. by updating a parameter of its associated sensor, by changing a deep sleep period, moving a servomotor, etc.

确实,Cloud IoT Core服务可以将配置更新消息发布到设备已订阅的特殊主题([ link ])。 当我们需要设备进入新状态时非常有用, 例如通过更新其关联传感器的参数,更改深睡眠时间,移动伺服电机等。

For efficiency, there shouldn’t be more than one message of that type per second per device. Such a message is an arbitrary user-defined blob (we’ll use JSON), up to 64 kiB. At last, the name of this special MQTT topic is imperatively:

为了提高效率,每台设备每秒不应有超过该类型的消息。 这样的消息是任意的用户定义的Blob(我们将使用JSON),最大为64 kiB。 最后,这个特殊的MQTT主题的名称必须为:

/devices/{device-id}/config

On the other hand, a device may publish to a special topic — that Cloud IoT Core has automatically subscribed to — messages concerning its state ([link]), e.g. quantity of RAM available, state of a button, etc. It is often used to see if the previous config message sent to the device had the desired effect.

另一方面,设备可能会发布到特定主题(Cloud IoT Core已自动订阅该主题) 有关其状态 ([ 链接 ])的消息 例如可用RAM数量,按钮状态等。它经常被使用查看先前发送到设备的配置消息是否达到了预期的效果。

For efficiency, this kind of publication shouldn’t be done more than once per second per device. Such a message is an arbitrary user-defined blob (we’ll use JSON), up to 64 kiB. At last, the topic to which the device publishes its state data has imperatively this name:

为了提高效率,这种发布每个设备每秒不应进行超过一次。 这样的消息是任意的用户定义的Blob(我们将使用JSON),最大为64 kiB。 最后,设备向其发布状态数据的主题强制具有以下名称:

/devices/{device-id}/state

Note: Sending commands to devices is also possible from Cloud IoT Core: see [link] but we won’t illustrate it.

注意:也可以从Cloud IoT Core向设备发送命令 :请参阅[ 链接 ],但我们不会对其进行说明。

But for the moment, we will focus on telemetry. After this journey, in a “coming soon” post we will show how to handle config and state special topics.

但是目前,我们将专注于遥测。 在此过程之后,在“即将到来”文章中,我们将展示如何处理configstate特殊主题。

UPDATE March 29, 2019: This post about config and state special topics is out: [link].

更新2019年3月29日:关于configstate特殊主题的帖子已发布:[ 链接 ]。

在设备上安装Mongoose OS (Mongoose OS installation on devices)

1)Mongoose OS的简短说明 (1) A short description of Mongoose OS)

Mongoose OS ([link], [link]) is a smart IoT-oriented OS, runnable on several chips, including ESP8266 and ESP32. Mongoose OS is in partnership with the major actors in IoT ([link]). It comes with a development tool called mos, working either in a UI or with a Command Line Terminal (like cmd.exe in Windows). In either cases, we’ll write mos commands. There is also a device management app called mDash but we didn’t try it. Numerous APIs dealing with most of the network and sensor protocols are provided. Programs can be written in both C/C++ and JS.

Mongoose OS ([ link ],[ link ])是一款面向物联网的智能操作系统,可在多种芯片上运行,包括ESP8266和ESP32。 猫鼬OS是在合作与物联网的主要参与者([ 链接 ])。 它带有一个称为mos的开发工具,该工具可以在UI或命令行终端(例如Windows中的cmd.exe )中运行。 无论哪种情况,我们都会编写mos命令。 还有一个名为mDash的设备管理应用程序,但我们没有尝试过。 提供了处理大多数网络和传感器协议的大量API。 程序可以用C / C ++和JS编写。

At last, there is a 12-tutorial series on YouTube, really useful:

最后,YouTube上共有12个教程,非常有用:

Note: We used Mongoose OS Community Edition, which is free, licensed under Apache 2.0.

注意:我们使用了免费的Mongoose OS Community Edition,该版本在Apache 2.0下获得了许可。

2)在ESP32上安装Mongoose OS (2) Mongoose OS installation on ESP32)

This installation has to be performed on each device.

必须在每个设备上执行此安装。

We head to the developers section of Mongoose OS web site ([link]) in order to perform the first seven steps of the list given in this resource:

我们进入Mongoose OS网站的开发人员部分 ([ link ]),以执行此资源中给出的列表的前七个步骤

Step #1, Step #2 and Step #3 are trivial. At Step #3 don’t forget to connect the device to the host machine via a USB cable.

步骤#1步骤#2步骤#3都很简单。 在步骤3,请不要忘记通过USB电缆将设备连接到主机。

For Step #4 “Create new app”, we choose to call the app app1. When mos clone https://github.com/mongoose-os-apps/demo-js app1 indicated on the web site is completed, mos tool automatically goes to the just created app1/ folder.

对于第4步 “创建新应用”,我们选择调用应用app1 。 当网站上指示的mos clone https://github.com/mongoose-os-apps/demo-js app1完成时,mos工具将自动转到刚刚创建的app1/文件夹。

In app1/fs/ folder, there is a source file called init.js. It is a demo file capable to communicate with different IoT platforms (if they are configured of course). We will basically test it and soon simplify it for our purposes.

app1/fs/文件夹中,有一个名为init.js的源文件。 它是一个演示文件,能够与不同的IoT平台进行通信(如果已配置)。 我们将对其进行基本测试,并很快将其简化以达到我们的目的。

Step #5 “Build app firmware” is launched with mos build command (add --arch esp32 to this command if you launch it from a Command Line Terminal, not from mos tool). It may take a while but normally we have to perform this build only once. After it, we have many more files. One called app1/build/fw.zip contains the binaries of the OS and init.js. It will be flashed to ESP32 in the next step.

使用mos build命令启动步骤#5 “构建应用程序固件”(如果从命令行终端而不是mos工具启动,请在此命令中添加--arch esp32 )。 可能需要一段时间,但通常我们只需要执行一次此构建。 之后,我们还有更多文件。 一个名为app1/build/fw.zip的文件包含操作系统和init.js的二进制文件。 下一步,它将刷入ESP32。

Step #6 “Flash firmware” is launched with mos flash command. It has normally to be done just once. Even if later we change some files (like init.js for instance), we will use a mos put command to upload a file from the host machine to the local device’s file system. Of course this command is only available after the flash process.

使用mos flash命令启动步骤#6 “ Flash固件”。 通常只需要执行一次。 即使稍后我们更改了一些文件(例如init.js ),我们也将使用mos put命令将文件从主机上传到本地设备的文件系统 。 当然,此命令仅在刷新过程之后可用。

Note: Firmware flash step can be tricky with a brand new ESP32. With our ESP32 DEVKIT V1, we had messages in console (that’s a first good point!) reporting issues about failing to connect to ESP32 ROM. Retrying to flash by pressing the BOOT button (closed to USB connector) finally turned out to a successful flash. Though, be ready to wait for one minute or two.

注意:使用全新的ESP32固件更新步骤可能会比较棘手。 使用ESP32 DEVKIT V1,我们在控制台中有了消息(这是第一个好处!),报告有关无法连接ESP32 ROM的问题。 最终,通过按下BOOT按钮(靠近USB接口)重试闪光,结果成功闪光。 但是,请等待一两分钟。

Then, the device automatically reboots and executes init.js. We obtained every second the following information in mos console (or in any serial terminal @115200 bds) :

然后,设备自动重启并执行init.js 我们每秒在mos控制台(或任何串行终端@ 115200 bds)中获得以下信息:

In Step #7 we connect ESP32 to our wifi network (we use mos tool):

步骤#7中,我们将ESP32连接到我们的wifi网络(我们使用mos工具):

mos wifi WIFI_NETWORK_NAME WIFI_PASSWORD

The device will reboot by itself after getting an IP address and synchronizing time by contacting a SNTP server. We then ping our device to check its internet connexion.

获取IP地址并通过联系SNTP服务器同步时间后,设备将自行重启。 然后,我们ping设备以检查其Internet连接。

Note: We get device information (IP address for instance) by hitting CTRL+i in mos tool, or by typing mos call Sys.GetInfo.

注意:我们可以通过在mos工具中按CTRL + i或通过键入mos call Sys.GetInfo来获取设备信息(例如IP地址)。

Note: We reset the device by hitting CTRL+u in mos tool, or by typing mos call Sys.Reboot.

注意:我们可以通过在mos工具中按CTRL + u或通过键入mos call Sys.Reboot

Note: Steps #5, #6 and #7 could be the beginning of a “provisioning script”, useful if we have many devices to setup. It is optional to rerun Step #5 if all devices are the same, e.g. only ESP32.

注意:步骤#5,#6和#7可能是“配置脚本”的开始,如果我们要设置许多设备,则很有用。 如果所有设备都相同( 例如仅ESP32),则可以重新运行第5步。

3)ESP32“您好,世界!” Mongoose OS编写程序 (3) ESP32 “Hello, World!” program with Mongoose OS)

To get used to Mongoose OS JS programming style and mos tool, let’s write a small program whose aim is to make the blue built-in LED blink and print messages on console. This led is connected to GPIO2 pin of ESP32 DEVKIT V1 (see Assembly Diagram at the beginning of this post). On our host machine, let’s replace the content of app1/fs/init.js by this one:

为了适应Mongoose OS JS编程风格和mos工具,让我们编写一个小程序,其目的是使内置的蓝色LED闪烁并在控制台上打印消息。 LED 连接到 ESP32 DEVKIT V1的GPIO2引脚 (请参阅本文开头的组装图)。 在我们的主机上,让我们用以下内容替换app1/fs/init.js的内容:

/*ESP32 DEVKIT V1 - Mongoose OSBuilt-in LED blink and console logThis blue LED is connected to GPIO2.See: - https://mongoose-os.com/docs/mos/api/core/mgos_timers.h.md
*/load('api_config.js');
load('api_gpio.js');
load('api_timer.js');let pin = 2;GPIO.set_mode(pin, GPIO.MODE_OUTPUT);// Call every 2 seconds
Timer.set(2000, Timer.REPEAT, function() {let value = GPIO.toggle(pin);print(value ? 'Tick' : 'Tock');
}, null);

From mos tool or from a Command Line Terminal, we upload this file to Mongoose OS file system and finally we reboot the device:

从mos工具或命令行终端,我们将此文件上传到Mongoose OS文件系统,最后重新启动设备:

mos put fs/init.js
mos call Sys.Reboot

The blue led should blink and we should see alternatively Tick and Tock printed on console.

蓝色LED会闪烁,我们应该看到或者TickTock印在控制台。

4)使用Mongoose OS进行DHT22测试 (4) DHT22 test with Mongoose OS)

At the beginning of this post, there is an Assembly Diagram showing how to connect DHT22 sensor with ESP32 DEVKIT V1. We chose to connect DHT22 data pin to GPIO0 of ESP32 DEVKIT V1.

在本文的开头,有一个组装图,显示了如何将DHT22传感器与ESP32 DEVKIT V1连接。 我们选择将DHT22数据引脚连接 到ESP32 DEVKIT V1的GPIO0

So, here is another short init.js program. This one prints periodically to serial console DHT22 measures (temperature and humidity - as an object in JSON, no MQTT publication yet):

因此,这是另一个简短的init.js程序。 该代码定期打印到串行控制台DHT22度量值(温度和湿度-作为JSON中的对象,尚无MQTT发布):

/*ESP32 DEVKIT V1 - Mongoose OSDHT22 sensor measures are sent to console.DHT22 data pin is connnected to GPIO0.See: - https://mongoose-os.com/docs/quickstart/develop-in-js.md- https://mongoose-os.com/docs/mos/api/drivers/dht.md
*/load('api_config.js');
load('api_dht.js');
load('api_timer.js');let pin = 0;
let dht = DHT.create(pin, DHT.DHT22);Timer.set(5000, true, function() { // timer period is in mslet msg = JSON.stringify({temperature: dht.getTemp(), humidity: dht.getHumidity()});print(msg);
}, null);

Then:

然后:

mos put fs/init.js
mos call Sys.Reboot

And this is the related console we get after uploading the init.js program and rebooting the device. Humidity is in % and temperature is in Celsius degrees:

这是上载init.js程序并重新启动设备后获得的相关控制台。 湿度以%为单位,温度以摄氏度为单位:

Numbers seem to have a long decimal part but this will be fixed later within a Cloud Function.

数字似乎有一个长的小数部分,但是稍后将在Cloud Function中解决此问题。

Note: For pedagogical purposes, we chose all over this post explicit long key names like temperature or humidity. This will have consequences on the volume of data stored later in a NoSQL database (Firebase Realtime Database) as those keys will be repeated for each measure. Shorter key names could be a good idea.

注意:出于教学目的,我们在本文中均选择了明确的长键名称,例如temperaturehumidity 。 这将对以后存储在NoSQL数据库(Firebase实时数据库)中的数据量产生影响,因为对于每个度量将重复这些键。 较短的键名可能是一个好主意。

5)让我们将数据发布到MQTT遥测主题 (5) Let’s publish data to the MQTT telemetry topic)

This is our last program, the one ready to work with Cloud IoT Core! On the previous program, we just add a publication to the telemetry topic we already talked about: /devices/{device-id}/events.

这是我们的最后一个程序,准备与Cloud IoT Core一起使用! 在之前的程序中,我们只是将出版物添加到我们已经讨论过的遥测主题中: /devices/{device-id}/events

Note that messages are published in JSON as it will facilitate later their content retrieval with the Firebase Cloud Function reacting to messages publication.

请注意,消息以JSON发布,因为它将通过Firebase Cloud Function对消息发布做出React,方便以后的内容检索。

/*ESP32 DEVKIT V1 - Mongoose OSDHT22 sensor measures are sent to console.DHT22 data pin is connnected to GPIO0.Publishes weather data to the appropriate topic.See: - https://mongoose-os.com/docs/quickstart/develop-in-js.md- https://mongoose-os.com/docs/mos/api/drivers/dht.md- https://mongoose-os.com/docs/mos/api/net/mqtt.md
*/load('api_config.js');
load('api_dht.js');
load('api_timer.js');
load('api_mqtt.js');// Telemetry topic must have this name:
let topic = '/devices/' + Cfg.get('device.id') + '/events';let pin = 0;
let dht = DHT.create(pin, DHT.DHT22);Timer.set(5000, true, function() { // timer period is in mslet msg = JSON.stringify({temperature: dht.getTemp(), humidity: dht.getHumidity()});// Publish message with a QoS 1// MQTT.pub() returns 1 in case of success, 0 otherwise.let ok = MQTT.pub(topic, msg, 1); print(ok, msg);
}, null);

We name this file init.js, upload it to Mongoose file system, then provoke a reset:

我们将此文件init.js ,将其上传到Mongoose文件系统,然后引发重置:

mos put fs/init.js
mos call Sys.Reboot

Note: These commands could be appended to the “provisioning script” we mentioned earlier.

注意:这些命令可以附加到我们前面提到的“配置脚本”中。

When running, this last program prints data to console but it fails to publish data to the MQTT bridge of Cloud IoT Core (MQTT.pub() returns 0):

在运行时,该最后一个程序将数据打印到控制台,但是无法将数据发布到Cloud IoT Core的MQTT桥( MQTT.pub()返回0):

Indeed, we haven’t set up any Google Cloud project yet, neither a fortiori registered a single device to it. Let’s do it now!

实际上,我们还没有建立任何Google Cloud项目,也没有Fortiori向其注册单个设备。 让我们现在就开始做吧!

Cloud IoT Core项目设置 (Cloud IoT Core project setup)

1)安装Google Cloud SDK (1) Google Cloud SDK installation)

Firstly we need to install Google Cloud SDK because we will have to type some gcloud commands in a Command Line Terminal. At the time of writing, it requires Python 2.7. It won’t work with Python 3.5. The Google Cloud SDK download page ([link]) offers versions of the SDK with Python bundled inside (if you’re sure you don’t have Python already installed and don’ t want to handle this Python point).

首先,我们需要安装Google Cloud SDK,因为我们必须在命令行终端中键入一些gcloud 命令 。 在撰写本文时,它需要Python 2.7。 它不适用于Python 3.5。 Google Cloud SDK下载页面([ 链接 ])提供了捆绑了Python的SDK版本(如果您确定尚未安装Python并且不想处理此Python问题)。

Then, Cloud IoT Core requires some Beta versions of gcloud commands. So in a Command Line Terminal, from any folder, we type:

然后,Cloud IoT Core需要一些gcloud命令的Beta版本 。 因此,在命令行终端的任何文件夹中,我们键入:

gcloud components install beta

These two previous steps have to be done just one time!

前面的两个步骤必须完成一次!

Note: Most of the following actions on Google IoT Core can be performed in three ways:

注意:可以通过三种方式在Google IoT Core上执行以下大多数操作:

  • with Google Cloud Console (on the web)

    使用Google Cloud Console (在网络上)

  • with some APIs in different languages, and

    带有一些不同语言的API ,以及

  • with Command Line Interface in a terminal, typing gcloud commands.

    在终端中使用命令行界面输入gcloud命令。

We will use the latter to configure things and we’ll check facts with Google Cloud Console (on the web).

我们将使用后者来配置事物,并通过Google Cloud Console(在网络上)检查事实。

2)Google Cloud专案设定 (2) Google Cloud project setup)

We follow now this guide from Mongoose OS web site : [link].

我们现在遵循Mongoose OS网站上的本指南:[ 链接 ]。

# Commands indicated in this grey frame have to be done just once to configure the Google Cloud project! They can be performed from any folder.# Get authenticated with Google Cloud
gcloud auth login# Create cloud project. We chose hello-cloud-iot-core as PROJECT_ID
gcloud projects create hello-cloud-iot-core# Give Cloud IoT Core permission to publish to Pub/Sub topics
gcloud projects add-iam-policy-binding hello-cloud-iot-core --member=serviceAccount:cloud-iot@system.gserviceaccount.com --role=roles/pubsub.publisher# Set default project for gcloud
gcloud config set project hello-cloud-iot-core# Create Pub/Sub topic for device telemetry
gcloud beta pubsub topics create weather-telemetry-topic# Create a Pub/Sub subscription to the just created topic
gcloud beta pubsub subscriptions create --topic weather-telemetry-topic weather-telemetry-subscription# Create devices registry (we call it weather-devices-registry)# Precise Pub/Sub topic name for event notifications# Disallow device connections to the HTTP bridge
gcloud beta iot registries create weather-devices-registry --region europe-west1 --no-enable-http-config --event-notification-config=topic=weather-telemetry-topic# Say 'yes' to enable API (if prompted).# But the last command may not work all the same# if you don't enable billing.# So, follow the link to enable billing and retry last command.# It should end up to "Created registry [weather-devices-registry]."

3)Cloud IoT Core项目中的设备注册 (3) Device registration within the Cloud IoT Core project)

Let’s now register the devices to the project! One at a time of course. mos tool is really helpful for this task. From mos tool launched in its UI or from Command Line Terminal, placed in our app1 folder, we type the following command (project id and registry name are involved, as you see):

现在让我们将设备注册到项目中! 当然一次一个。 mos工具对于此任务确实很有帮助。 从在用户界面中启动的mos工具或从位于app1文件夹中的命令行终端,键入以下命令(如所见,涉及项目ID和注册表名称):

# Register device with Cloud IoT Core (do it for each device!)
mos gcp-iot-setup --gcp-project hello-cloud-iot-core --gcp-region europe-west1 --gcp-registry weather-devices-registry

Note: This command could be the last one of the “provisioning script” we mentioned already twice.

注意:此命令可能是我们两次提到的“配置脚本”的最后一个。

This command is a mos command that will itself use gcloud commands. The device about to be registered must be connected via the serial port to our host computer because some information will be uploaded to it just like keys, MQTT bridge address, etc.

此命令是mos命令,其本身将使用gcloud命令。 必须将要注册的设备通过串行端口连接到我们的主机,因为一些信息(例如密钥,MQTT桥地址等)将上传到该计算机。

Indeed, we see on mos console that two keys (one private, one public) are generated. We can inspect them in app1 project folder. The private one is for ESP32 and the public one is for Google IoT Core. They are used during the authentication process involving the JSON Web Token we mentioned earlier.

实际上,我们在mos控制台上看到生成了两个密钥(一个私有,一个公共) 。 我们可以在app1项目文件夹中检查它们。 私有的用于ESP32,公共的用于Google IoT核心。 它们在涉及我们前面提到的JSON Web令牌的身份验证过程中使用。

Note concerning security: The private key shouldn’t be stored in plain text in ESP32 flash memory. This is why we describe in the post following this one ([link]) how to encrypt this memory. Also, the private key file shouldn’t be stored in plain text on the host development computer. At least, protect access to its content with a password.

有关安全性的注意事项: 私钥不应以纯文本格式存储在ESP32闪存中 。 这就是为什么我们在此后的文章([ link ])中描述如何加密此内存的原因。 另外, 私钥文件不应以纯文本格式存储在主机开发计算机上 。 至少要用密码保护对内容的访问。

When the device reboots, we see in the console that it successfully connects to the Google MQTT bridge and publishes telemetry messages (MQTT.pub() returns 1):

设备重启后,我们在控制台中看到它已成功连接到Google MQTT桥并发布了遥测消息( MQTT.pub()返回1):

4)在Google Cloud Console中检查项目设置 (4) Checking the project setup in Google Cloud Console)

We head to https://console.cloud.google.com/iot/ to check that everything was well configured:

我们前往https://console.cloud.google.com/iot/检查所有配置是否正确:

Clicking on the Registry ID weather-devices-registry reaches another screen. Clicking on “Devices” on this new screen lists provisioned devices and gives details like the last time they were seen (but this is not a live update, we have to refresh the page):

单击注册表ID weather-devices-registry进入另一个屏幕。 单击此新屏幕上的“设备”,将列出已配置的设备,并提供详细信息,例如上次被查看的设备(但这不是实时更新,我们必须刷新页面):

Clicking on the Telemetry Pub/Sub topic name goes to Pub/Sub console to show the subscription we created before, i.e. the one related to the telemetry topic:

单击遥测发布/订阅主题名称,进入发布/订阅控制台以显示我们之前创建的订阅, 与遥测主题相关的订阅:

5)最后查看一些遥测数据 (5) Viewing at last some telemetry data)

Now it would be nice to see the data that devices are publishing. For this, we have the subscription we already created. From any folder of the host computer, we type:

现在,很高兴看到设备正在发布的数据。 为此,我们已经创建了订阅。 在主机的任何文件夹中,键入:

gcloud beta pubsub subscriptions pull --auto-ack weather-telemetry-subscription --limit=2

This command ([link]) pulls until 2 Pub/Sub messages from our weather-telemetry-subscription subscription. We can see data in JSON, messages ids and a list of attributes for each message. Among them the deviceId attribute is present. Unfortunately there are no timestamps, we’ll see how to get them later.

此命令([ link ])从我们的weather-telemetry-subscription订阅中拉出2条 Pub / Sub消息。 我们可以看到JSON中的数据,消息ID和每个消息的属性列表。 其中存在deviceId属性。 不幸的是,没有时间戳记,我们将在以后看到如何获取它们。

If you have reached this milestone, congrats! We’re now ready to write a Firebase Cloud Function reacting to each publication to the Pub/Sub telemetry topic!

如果您达到了这个里程碑,那么恭喜! 现在,我们准备编写一个Firebase Cloud Function,以对发布/订阅遥测主题的每个出版物做出React!

使用Firebase记录,存储和可视化天气数据 (Logging, storing and visualizing weather data with Firebase)

1)简介 (1) Introduction)

We’re now tackling this part of the project:

我们现在要处理项目的这一部分:

On that diagram, we see that our project needs 3 Firebase products :

在该图上,我们看到我们的项目需要3种Firebase产品:

A Firebase Cloud Function (more exactly “a Cloud Function for Firebase”) must react to any publication to the telemetry topic in order to store the weather data of this publication to a Firebase Realtime Database. This storage allows weather data persistence and is used to feed a web app hosted by Firebase Hosting. This web app draws live plots of this weather data across time.

Firebase云功能 (更确切地说是“ Firebase的云功能”)必须对遥测主题的任何发布做出React,以便将该发布的天气数据存储到Firebase实时数据库中 。 该存储可以使天气数据持久化,并用于提供由Firebase Hosting托管的Web应用程序。 该网络应用程序绘制了该天气数据随时间变化的实时图。

The good new is that it’s possible to configure all these products with one command.

好消息是,可以用一个命令配置所有这些产品。

2)Firebase配置,GitHub存储库 (2) Firebase configuration, GitHub repository)

We are still working on the same Google Cloud project called hello-cloud-iot-core. Firebase will just “enhance” this project with its products.

我们仍在从事名为hello-cloud-iot-core的同一Google Cloud项目。 Firebase只会通过其产品“增强”该项目。

We made a GitHub repository for the Firebase aspects of our project:

我们为项目的Firebase方面创建了GitHub存储库:

olivierlourme/iot-store-displayContribute to olivierlourme/iot-store-display development by creating an account on GitHub.github.com

olivierlourme / iot-store-display 通过在GitHub上创建一个帐户来为olivierlourme / iot-store-display开发做出贡献。 github.com

Clone this repository in your favorite development folder and head to the newly created directory:

将此存储库克隆到您喜欢的开发文件夹中,然后转到新创建的目录:

c:\_app>git clone https://github.com/olivierlourme/iot-store-display
c:\_app>cd iot-store-display

Global Firebase configuration

全局Firebase配置

Note: We suppose you have Firebase tools installed (i.e. Node.js installed and npm install -g firebase-tools was run, see [link] for details).

注意:我们假设您已安装Firebase工具 ( 即,npm install -g firebase-tools Node.js并已npm install -g firebase-tools ,有关详细信息,请参见[ 链接 ])。

Let’s perform the Firebase initializations:

让我们执行Firebase初始化:

c:\_app\iot-store-display>firebase init

First step is to choose Firebase products we want to use:

第一步是选择我们要使用的Firebase产品:

We are then prompted to associate the current directory (iot-store-display) with one of the listed Firebase projects. The problem is that our project hello-cloud-iot-core doesn’t appear in the list because before being a Firebase project it’s also a Google Cloud project! Read Doug Stevenson’s posts for relationships between Firebase and Google Cloud: [link] and [link].

然后提示我们将当前目录( iot-store-display )与列出的Firebase项目之一相关联。 问题在于我们的项目hello-cloud-iot-core没有出现在列表中,因为在成为Firebase项目之前,它也是Google Cloud项目! 阅读Doug Stevenson的文章,了解Firebase与Google Cloud之间的关系:[ 链接 ]和[ 链接 ]。

To overcome this, first we hit CTRL+C to stop this initialization process and then we go to Firebase Console at https://console.firebase.google.com. We choose “Add a project”:

为了克服这个问题,我们首先按CTRL + C停止此初始化过程,然后转到https://console.firebase.google.com上的Firebase控制台 。 我们选择“添加项目”:

And we can see our project (with Google Cloud logo) and choose it:

我们可以看到我们的项目(带有Google Cloud徽标)并选择它:

Note: You might then be asked to confirm Firebase billing plan if the Google Cloud project itself has a billing plan.

注意:如果Google Cloud项目本身具有结算计划,则可能会要求您确认Firebase结算计划。

Great! We restart the Firebase initialization with firebase init command and this time our Google Cloud project hello-cloud-iot-core is listed. We choose it:

大! 我们使用firebase init命令重新启动Firebase初始化,这一次列出了我们的Google Cloud项目hello-cloud-iot-core 。 我们选择它:

Note: If you still don’t see your project you might be logged to Firebase without the correct Google account. In this case, type firebase logout followed by firebase login.

注意:如果仍然看不到您的项目,则可能没有正确的Google帐户就登录到Firebase。 在这种情况下,键入firebase logout然后键入firebase login

Realtime Database configuration

实时数据库配置

Then the wizard asks a single question about the Realtime Database and its rules: the name of the file where they will be saved. We maintain the default name. It’s more practical to have these rules in a file lying in the project directory than to go to Firebase Console as we did in past posts. We will detail these rules later.

然后,向导会询问有关实时数据库及其规则的单个问题:将其保存在其中的文件的名称。 我们保留默认名称。 将这些规则保存在项目目录中的文件中比在过去的帖子中访问Firebase Console更为实际。 稍后我们将详细介绍这些规则。

Cloud Functions configuration

云功能配置

Here are the answers we made to the wizard concerning Functions Setup:

这是我们对向导进行的有关“功能设置”的答案:

Of course, we choose not to overwrite the functions/index.js file obtained from GitHub.

当然,我们选择不覆盖从GitHub获得的functions/index.js文件。

Firebase Hosting configuration

Firebase托管配置

And here are the answers we made to the wizard concerning Hosting Setup:

以下是我们对向导进行的有关主机设置的答案:

Of course we choose not to overwrite the public/index.html file obtained from GitHub.

当然,我们选择不覆盖从GitHub获得的public/index.html文件。

Deploying (not now!)

部署(现在不行!)

Later, if we want to deploy some updates we made to our 3 products, we can type globally:

以后,如果我们要部署对3种产品所做的一些更新,则可以全局键入:

c:\_app\iot-store-display>firebase deploy

But if we want to deploy only, respectively:

但是,如果我们只想分别部署:

  • updated database rules,
    更新的数据库规则,
  • updated cloud functions,
    更新了云功能,
  • updated web app,
    更新的网络应用程序,

we type, respectively:

我们分别输入:

firebase deploy --only database
firebase deploy --only functions
firebase serve --only hosting (local deployment) OR firebase deploy --only hosting (remote deployment)

3)发布/订阅触发云功能 (3) Pub/Sub trigger Cloud Function)

Introduction

介绍

In a past post, we explained that we could write Firebase Cloud Functions triggered on some events happening to some of the Google products.

在过去的文章中,我们解释了我们可以编写在某些Google产品发生的某些事件上触发的Firebase Cloud Functions

Post 2 of 3. Our IoT journey through ESP8266, Firebase and Plotly.jsA Firebase Cloud Function appends a timestamp to each value pushed to a Firebase Realtime Database.medium.com

第2页,共3页。我们的ESP8266,Firebase和Plotly.js的物联网之旅 Firebase Cloud函数将时间戳记附加到推送到Firebase实时数据库的每个值。 medium.com

Cloud Pub/Sub is one of these products and so it is possible to trigger a function each time a message is published to a Pub/Sub topic : [link].

Cloud Pub / Sub是这些产品之一,因此每次将消息发布到Pub / Sub主题:[ 链接 ]时,都可以触发功能。

So if the Firebase Cloud Function is triggered on each publication to the weather-telemetry-topic topic, watching its log will allow us to watch the telemetry topic’s activity.

因此,如果在每个发布到weather-telemetry-topic主题上触发了Firebase Cloud Function,则观看其日志将使我们能够观看遥测主题的活动。

The code of the Cloud Function has to store each new published data to the Firebase Realtime Database associated with our project.

Cloud Function的代码必须将每个新发布的数据存储到与我们的项目关联的Firebase实时数据库。

Cloud Function source code

云功能源代码

The beginning of the source code looks like this:

源代码的开头看起来像这样:

exports.detectTelemetryEvents = functions.pubsub.topic('weather-telemetry-topic').onPublish((message, context) => {...

The full Cloud Function source code lies in the file named index.js. This file is in the functions folder of our iot-store-display directory on GitHub. It is fully commented, so run and study it, it’s short and not complicated.

完整的Cloud Function源代码位于名为index.js的文件中。 该文件位于GitHub上 iot-store-display目录的functions文件夹中。 它已被完全注释,因此请运行并研究它,它简短而又不复杂。

Cloud Function deployment

云功能部署

It’s time to deploy the Cloud Function:

现在是时候部署云功能了:

c:\_app\iot-store-display>firebase deploy --only functions

Cloud Function validation

云功能验证

Once Cloud Function is deployed, we can watch the Cloud Function logs and among other things, we’ll see the results of the console.log(`Device=${deviceId}...) we wrote at the end of index.js.

部署Cloud Function后,我们可以查看Cloud Function日志,除其他外,我们console.log(`Device=${deviceId}...)看到在index.js末尾编写的console.log(`Device=${deviceId}...)的结果。 。

Where to see those logs? We have two opportunities:

在哪里可以看到这些日志? 我们有两个机会:

  • in Firebase Console (https://console.firebase.google.com):

    在Firebase控制台( https://console.firebase.google.com )中:

  • in Google Cloud Console (https://console.cloud.google.com/functions/):

    在Google Cloud Console( https://console.cloud.google.com/functions/ )中:

We prefer this latter solution, as logs are clearer:

我们更喜欢后一种解决方案,因为日志更加清晰:

Concerning storage, here is what lies in Firebase Realtime Database after each device has made 2 telemetry data publication. Data is of course sorted by device as we specified it in index.js:

关于存储,这是每个设备发布两次遥测数据后,Firebase Realtime Database中的内容。 数据当然是按照我们在index.js指定的设备排序的:

Note: Don’t forget to delete your Cloud Function on Google servers if you don’t use it, otherwise you might either reach the invocation quota or pay for service you don’t use, as indicated here: [link]. Function deletion is to be performed on Google Cloud Console (see “Delete”, 3 screenshots above).

注意:如果您不使用Google Cloud Function不要忘记在其上删除它,否则,您可能会达到调用配额或为不使用的服务付费,如此处所示:[ link ]。 功能删除将在Google Cloud Console上执行(请参见“删除”,上面的3个屏幕截图)。

Note: The Cloud Function has admin rights over the database, whatever is the content of the database.rules.json file. At this step, the database.rules.json file can still be very restrictive. Don’t forget to deploy them, once edited.

注意:无论database.rules.json文件的内容如何,​​Cloud Function都具有对该数据库的管理员权限。 在这一步, database.rules.json文件仍然非常严格。 一旦编辑,别忘了部署它们。

{"rules": {".read": false,".write": false}
}

4)使用Firebase和plotlys.js的Web应用程序可视化天气数据 (4) A web app using Firebase and plotlys.js to visualize weather data)

Introduction

介绍

Note: We’re now building a “homemade” (and satisfying) data visualization solution. For enhanced UI (dashboard, etc.), maybe you should investigate Data Studio we already mentioned elsewhere in this post.

注意:我们现在正在构建一个“自制的”(令人满意的)数据可视化解决方案。 对于增强的UI(仪表板等),也许您应该研究本文中其他地方已经提到的Data Studio。

We focus on building a small web app, hosted by Firebase Hosting. This web app lively plots the data stored in the Firebase Realtime Database. We used plotly (https://plot.ly/javascript/) for the plotting library. We are familiar with that work as we already undertook a similar one in a previous post:

我们专注于构建Firebase Hosting托管 的小型Web应用程序。 该Web应用程序生动地绘制了Firebase实时数据库中存储的数据。 我们将plotly ( https://plot.ly/javascript/ )用于绘图库。 我们熟悉这项工作,因为我们在上一篇文章中已经进行过类似的工作:

Post 3 of 3. Our IoT journey through ESP8266, Firebase and Plotly.jsA web app hosted by Firebase Hosting susbscribes to the data stream coming from a Firebase Realtime Database and plot…medium.com

第3篇,共3篇。我们通过ESP8266,Firebase和Plotly.js进行的物联网之旅 由Firebase Hosting托管的Web应用程序怀疑来自Firebase Realtime Database和plot的数据流… medium.com

What’s different today is that we have to:

今天的不同之处在于我们必须:

  • draw several charts: temperature vs time and humidity vs time,

    绘制几张图表:温度时间,湿度时间,

  • inside each chart, we have one plot per device.
    在每个图表中,每个设备只有一个图。

Database rules & devices-ids node

数据库规则和设备-ids节点

Concerning the database rules, what should be now the database.rules.json file? The device-telemetry node needs to be read by the web app. And if you looked attentively at the Realtime Database screenshot given a few screenshots before, there is another node called devices-ids.

关于数据库规则, database.rules.json文件现在应该是什么? Web应用程序需要读取 device-telemetry节点。 而且,如果您仔细查看了实时数据库的屏幕快照(之前给出了一些屏幕截图),那么还有另一个节点称为devices-ids

You need to create manually in the Firebase Console this devices-ids node and fill it appropriately for the web app to work properly. It is a simple mean to declare to the web app the devices we want plots for and also to give aliases to the devices. Its role and necessity are fully explained in comments of the public/script.js file given in GitHub.

您需要在Firebase控制台中手动创建此devices-ids节点,并对其进行适当填充,以使网络应用正常运行。 这是向Web应用程序声明我们想要绘制的设备并为设备提供别名的简单方法。 在GitHub中给出的public/script.js文件的注释中充分说明了其作用和必要性。

Note: An improvement could be a form (accessed through authentication) that, once fulfilled, calls a script to generate this devices-ids node.

注意:可以改进一种形式(通过身份验证访问),该形式一旦完成,就调用脚本来生成此devices-ids节点。

This devices-ids node also needs to be read by the web app. So the database.rules.json file should eventually become:

devices-ids节点也需要由Web应用读取。 因此, database.rules.json文件最终应变为:

{"rules": {"devices-ids": {".read": true,".write": false},"devices-telemetry": {".read": true,".write": false}}
}

These new rules, once edited and saved, must be deployed with:

一旦编辑并保存了这些新规则,则必须将其部署为:

c:\_app\iot-store-display>firebase deploy --only database

Web app source code

网络应用程序源代码

The web app source code lies in the public directory of our hello-cloud-iot-core folder or in GitHub. The content of the folder, especially script.js, is fully commented so you know where to study (and improve!) it.

Web应用程序源代码位于hello-cloud-iot-core文件夹的public目录中或GitHub中 。 该文件夹的内容,特别是script.js ,已被完全注释,因此您知道在哪里学习(和改进!)。

Note: we have only two devices for this demo but the source code is okay for x devices as long as you declare them in the devices-ids node.

注意:此演示中只有两个设备,但是只要您在devices-ids节点中声明了x个设备的源代码就可以了。

Web app local deployment and validation

Web应用程序本地部署和验证

For testing purposes, Firebase Hosting can launch a local live server:

为了进行测试,Firebase Hosting可以启动本地实时服务器:

c:\_app\iot-store-display>firebase serve --only hosting

We head to http://localhost:5000 and we’re happy to get this:

We head to http://localhost:5000 and we're happy to get this:

Web app remote deployment

Web app remote deployment

At last, Firebase offers us the hosting of our web app and an access to it via https:

At last, Firebase offers us the hosting of our web app and an access to it via https:

c:\_app\iot-store-display>firebase deploy --only hosting

We quickly get the public URL of our web app : https://hello-cloud-iot-core.firebaseapp.com

We quickly get the public URL of our web app : https://hello-cloud-iot-core.firebaseapp.com

Note: If you have your own domain, you can connect your Firebase web app to it. See [link].

Note: If you have your own domain, you can connect your Firebase web app to it. See [ link ].

结论 (Conclusion)

In this post we discovered how to combine ESP32, Mongoose OS and Cloud IoT Core, obtaining a serious, secure and professional IoT project. Now that we know, it can go really fast to provision 10, 100… 1000 devices acquiring weather data all over an area, as long as they can get a Wifi connection. Now, devices are centrally managed, it is easy to provision and monitor them. But we can go further!

In this post we discovered how to combine ESP32 , Mongoose OS and Cloud IoT Core, obtaining a serious, secure and professional IoT project . Now that we know, it can go really fast to provision 10, 100… 1000 devices acquiring weather data all over an area, as long as they can get a Wifi connection. Now, devices are centrally managed, it is easy to provision and monitor them. But we can go further!

Indeed, in addition to this post, there is a second one ([link]). Inside it:

Indeed, in addition to this post, there is a second one ([ link ]). Inside it:

  • We’ll focus on ESP32 flash memory encryption, to achieve a fully secured system.

    We'll focus on ESP32 flash memory encryption , to achieve a fully secured system.

  • We’ll see how to use the config special topic, allowing us to trig an action on the device from the Google Cloud Console.

    We'll see how to use the config special topic, allowing us to trig an action on the device from the Google Cloud Console .

  • We’ll see how to use the state special topic, allowing the device to communicate to Google Cloud Console informations about its current state.

    We'll see how to use the state special topic, allowing the device to communicate to Google Cloud Console informations about its current state .

We hope you enjoyed this really long post and that you learnt something! Don’t hesitate to ping me if you have any questions or improvement suggestions…

We hope you enjoyed this really long post and that you learnt something! Don't hesitate to ping me if you have any questions or improvement suggestions…

翻译自: https://www.freecodecamp.org/news/gcp-cloudiotcore-esp32-mongooseos-1st-5c88d8134ac7/

mongoose-iot

mongoose-iot_如何使用带有ESP32和Mongoose OS的GCP-Cloud IoT核心版查看天气相关推荐

  1. 2023年的在线工具箱系统源码拥有上百款工具,是每位站长必备的利器。该系统带有后台版本,具备自适应模板和优化修复版,让使用起来更加便捷和高效。

    简介:这是2023年最新的站长必备在线工具箱系统源码,包含上百款工具,带有后台版本和自适应模板,还有优化修复版.虽然系统没有那么花里胡哨,但是它贵在简洁大方,全工具都可以在线运行使用,且源码全针对SE ...

  2. 详细!基于ESP32的智能门禁系统(华为云iot+微信小程序)

    git地址:智能门禁(云IOT+微信小程序) 开关门效果 设备侧 产品创建 创建产品 创建产品,协议类型选择MQTT,数据格式选择JSON,其他参数自定 设备注册 找到所属产品,认证类型选择密钥,单击 ...

  3. ESP32 WIFI MESH学习笔记9-百度IOT接入(服务器部分)

    系列文章目录 文章目录 系列文章目录 前言 一.百度IOT-Core 二.Core计费 三.IOT-Core设置 四.设备测试 前言 接入DFROBOT 的公用IOT服务还是比容易,但服务也较为简单, ...

  4. 【ESP32学习笔记】#通用篇#(1)简介及资料

    目录 一.简介 1.ESP32 系列芯片型号 2.CPU 和存储 3.时钟和定时器 4.高级外设接口 5.功能框图 二.资料 1.官方文档 2.开发框架 ESP-IDF 3.其他参考 4.云框架 三. ...

  5. raspberry pi_如何启动新的Raspberry Pi

    raspberry pi 如果您一直遵循本系列教程,那么您已经选择并购买了Raspberry Pi开发板和外围设备,现在就可以开始使用它了. 在第三篇文章中,让我们看一下如何启动它. 与您的笔记本电脑 ...

  6. micropython入门教程-【ESP8266】MicroPython的快速入门教程

    ESP8266版本的MicroPython和pybaord版本的有不少区别,无论从使用习惯还是API上,都有许多不同.下面以ESP-MP-01开发板为例,介绍使用方法.这个方法也可以用在NodeMcu ...

  7. windows使用WiFi-direct连接手机等设备

    在网上搜了蛮久,都是叫你下visual studio然后再加载"Wi-Fi Direct sample"这个实例项目调试运行.微软在这里提供了一个例子,不过没有打包好.我就直接打包 ...

  8. 前端笔记之NodeJS(四)MongoDB数据库Mongoose自制接口MVC架构思想|实战

    一.MongoDB数据库 1.1 NoSQL简介 随着互联网web2.0网站的兴起,传统的SQL数据库(关系数据库)在应付web2.0网站,特别是超大规模和高并发的SNS(social network ...

  9. MongoDB的Mongoose简介

    by Nick Karnik 尼克·卡尼克(Nick Karnik) MongoDB的Mongoose简介 (Introduction to Mongoose for MongoDB) Mongoos ...

最新文章

  1. url模块和querystring模块
  2. Spring 5.3 正式GA,维护至2024年,4.3版本年末结束维护
  3. MySQL: ERROR 1040: Too many connections”的异常情况1
  4. 《Linux内核设计的艺术:图解Linux操作系统架构设计与实现原理》——2.15 本章小结...
  5. kafka记录及面试题
  6. 程序异常是python语言基本控制结构_计算机二级python 知识点篇(程序的控制结构)...
  7. java 轻量级文件数据库_Java:如何创建轻量级数据库微服务
  8. 天天讲路由,那 Linux 路由到底咋实现的!?
  9. dataguard备库的数据文件的迁移
  10. ren命令linux,Linux mren命令
  11. 智能优化算法应用:基于灰狼算法的二维Otsu图像阈值分割-附代码
  12. IDEA 顶部导航栏(Main Menu)不见了怎么办?
  13. 极坐标xy的转换_极坐标与直角坐标的转化
  14. Python3爬取美女妹子图片
  15. 正则表达式高级学习技巧
  16. Android 网络小说阅读APP实现详解
  17. anchor base和anchor free, 小物体检测, YOLO V1-3 9000 V4 V5 的区别,yolov5-8, yolox创新点
  18. 国内9大免费CDN汇总,除了加速乐,你还用过哪些?
  19. 2021年山东省安全员C证考试资料及山东省安全员C证找解析
  20. websocket配置

热门文章

  1. MySQL—常用指令总结
  2. 定时器控件timer winform 114869229
  3. java演练 数组的逆序文字玩法 你是猪才怪
  4. git-比对不同-diff
  5. 1910140852linux安装g
  6. python-pygame声音模块的使用
  7. Laravel Collection 常用方法(1)
  8. 关于js字符串替换的一道笔试题目
  9. slim框架中防止crsf攻击时,用到的函数hash_equals
  10. Android Calender