• Elasticsearch 和 Arduino:一起变得更好!


    作者:Enrico Zimuel

    使用 Arduino IoT 设备与 Elasticsearch 和 Elastic Cloud 进行通信的简单方法

    在 Elastic®,我们不断寻找简化搜索体验的新方法,并开始关注物联网世界。 来自物联网的数据收集可能非常具有挑战性,尤其是当我们拥有数千台设备时。

    Elasticsearch® 对于收集、探索、可视化和发现数据非常有用 - 对于来自多个设备的所有数据。 Elastic 的分布式特性使其能够轻松处理来自数百万台设备的请求。

    感谢与物联网领域非常受欢迎的品牌 Arduino 的合作,我们测试了一些设备,并开发了一个实验性开源库,可以以非常简单的方式将 Arduino 板连接到 Elasticsearch。

    什么是 Arduino?

    Arduino 是全球开源硬件和软件领域的领导者,拥有超过 3000 万活跃用户! 该品牌旨在帮助各类创客创建自己的互动项目,随着用户面临新的挑战,该品牌不断成长和适应,并扩展到物联网、可穿戴设备、3D 打印和嵌入式环境。 它还开设了专门的专业业务部门,以支持公司成为各自领域的创新者,采用定制且用户友好的方法,避免供应商锁定,并利用 360° 生态系统,做好从原型设计到大规模生产的准备。

    Arduino 专业版

    在 Arduino Pro 的高性能技术解决方案中,你会发现低功耗且安全的模块系统,例如 Portenta H7,它可以使用高级语言和 AI 进行编程,同时在其可定制的上执行低延迟操作硬件和最新的 Portenta C33,凭借一系列精简且经济高效的功能,使物联网比以往任何时候都更容易访问。

    此外,Arduino Pro 的工业级产品适合整个 Arduino 生态系统,其中包括云服务、无数软件库和社区共享的即用型草图,当然还有满足任何需求的各种组件。 其中包括 MKR WiFi 1010Nano RP2040 板等流行产品 —— 创客运动名副其实的基石。

    Elasticsearch 和 Arduino

    我们开发了一个研发项目来提供一个在 Arduino 模块上运行的简单 Elasticsearch 客户端库(用 C++ 编写)。 没错:现在你可以直接从 Arduino 板与 Elasticsearch 集群通信!

    我们使用 Portenta H7、MKR WiFi 1010 和 NANO RP2040 Connect 测试了该库。 任何具有 Wi-Fi 或以太网连接的 Arduino 板都可以使用该库。

    我们使用 Elastic Cloud 作为数据库,从相邻设备收集所有数据并提供平均温度的详细信息。 这是控制工程应用中的典型场景。

    想了解更多? 以下是包含所有详细信息的简单教程。

    使用案例:监控多个物联网设备的温度

    我们为一家需要管理位于意大利的多个物联网设备的公司设计了一个用例。 每个设备将来自传感器的数据(例如温度)发送到 Elastic Cloud。 使用 Elastic Cloud,该公司可以管理任何规模的物联网设备,而无需管理专用基础设施。 此外,该公司还需要根据相邻设备的平均温度来调整每个设备的一些内部参数,范围为 100 公里,这是控制工程应用中的典型场景。

    使用 Elasticsearch,我们可以使用过滤聚合多重匹配地理空间向量搜索 (kNN)语义搜索机器学习等搜索功能提供多种反馈。

    在此用例中,我们使用平均聚合 (average aggregation) 和地理距离 (geo-distance) 来检索 100 公里之间的所有设备。

    使用 Elastic Cloud 中提供的 UI Kibana®,我们可以轻松创建仪表板来监控来自所有设备的数据。 由于我们还有地理数据,因此我们可以在地图中表示这些信息。

    这是用不同颜色代表不同温度(蓝色是冷,绿色是热)创建的 heat map

    Elastic Cloud 设置

    第一步是拥有 Elastic Cloud 帐户。 如果你没有,可以在此处注册试用(无需信用卡)。 登录后,你可以创建新部署,选择要使用的 Elasticsearch 实例的大小。

    创建部署后,你需要检索端点 URL 并生成 Elasticsearch 的 API 密钥。 你可以阅读本指南来获取此信息。 对于高级用例,你还可以创建用于不同设备的 API 密钥组,并更改 API 策略以仅允许使用特定索引。

    如果你想有自己的本地部署,请参阅文章 “如何在 Linux,MacOS 及 Windows 上进行安装 Elasticsearch”

    准备Elasticsearch索引

    我们需要创建一个索引来存储来自 Arduino 板的数据。 我们想要存储温度值、使用地理位置(纬度和经度)的设备位置、设备标识符名称和时间戳。

    我们可以通过向 Elasticsearch 发出以下 HTTP 请求来创建索引 “temperature”:

    1. PUT /temperature
    2. {
    3. "mappings": {
    4. "properties": {
    5. "temperature": { "type": "float" },
    6. "timestamp": { "type": "date" },
    7. "location": { "type": "geo_point" },
    8. "device-id": { "type": "keyword" }
    9. }
    10. }
    11. }

    要发送此 HTTP 请求,你可以使用 Elastic Cloud 中 Kibana 的 Dev Tools

    我们希望存储每次设备发送数据时操作的时间戳。 这可以使用 Elasticsearch 的摄取管道 (ingest pipeline) 功能来完成。 摄取管道是 Elasticsearch 在索引(存储)文档之前执行的操作。 例如,管道可以根据某些计算分配特定文档字段的值。

    在我们的例子中,我们只需要存储时间戳,我们就可以创建一个 “set-timestamp” 管道:

    1. PUT _ingest/pipeline/set-timestamp
    2. {
    3. "description": "sets the timestamp",
    4. "processors": [
    5. {
    6. "set": {
    7. "field": "timestamp",
    8. "value": "{{{_ingest.timestamp}}}"
    9. }
    10. }
    11. ]
    12. }

    使用这个管道,我们可以将数据发送到 Elasticsearch,如下所示:

    1. POST /temperature/_doc?pipeline=set-timestamp
    2. {
    3. "temperature": 21.45,
    4. "device-id": "H7-001",
    5. "location": {
    6. "type": "Point",
    7. "coordinates": [12.4923, 41.8903]
    8. }
    9. }

    这里的 device-id H7-001 是 Arduino 板的名称,location 是用12.4923(经度)和41.8903(纬度)表示的地理点,这是罗马斗兽场(意大利)的位置。

    请注意,我们没有指定时间戳值,因为这是使用 “set-timestamp” 管道(在 URL 中指定为查询字符串)自动生成的。

    地理距离查询

    要检索 100 公里以内设备的平均温度,我们可以使用以下 Elasticsearch 查询:

    1. GET /temperature/_search
    2. {
    3. "query": {
    4. "bool": {
    5. "must": {
    6. "match_all": {}
    7. },
    8. "filter": {
    9. "geo_distance": {
    10. "distance": "100km",
    11. "location": [12.4923, 41.8903]
    12. }
    13. }
    14. }
    15. },
    16. "aggs": {
    17. "avg_temp": { "avg": { "field": "temperature" } }
    18. }
    19. }

    该查询将返回一个 “avg_temp” 聚合字段,其中包含 100 公里半径内所有设备的平均温度。

    Arduino 的 Elasticsearch 客户端的使用

    终于到了展示一些 Arduino 代码的时候了! 在这里,我们报告了一个简单的草图,它将温度值发送到 Elastic Cloud,执行地理距离查询获取平均温度,然后等待 30 秒。

    此处报告的代码可在 GitHub 存储库 elastic/elasticsearch-arduinoexamples 文件夹中在线获取。 该草图使用 elasticsearch_config.h 文件,如下所示:

    1. #define WIFI_SECRET_SSID ""
    2. #define WIFI_SECRET_PASS ""
    3. #define ELASTIC_ENDPOINT ""
    4. #define ELASTIC_PORT 443
    5. #define ELASTIC_CLOUD_API_KEY ""
    6. #define DEVICE_GEO_LON 12.4923
    7. #define DEVICE_GEO_LAT 41.8903
    8. #define DEVICE_ID "x"
    9. #define DEVICE_GEO_DISTANCE "50km"

    在我们的示例中,我们使用 Wi-Fi 连接将 Arduino 板连接到互联网。

    WIFI_SECRET_SSID 和 WIFI_SECRET_PASS 是要使用的 SSID 网络的名称和 Wi-Fi 密码。

    ELASTIC_ENDPOINT 是 Elastic Cloud 端点的 URL,ELASTIC_PORT 是 443,因为 Elastic Cloud 使用 TLS (https)。 ELASTIC_CLOUD_API_KEY 是要在 Elastic Cloud 管理界面中生成的 API 密钥。

    该文件还包含与 Arduino 设备相关的其他信息。 我们有地理查询的经度 (DEVICE_GEO_LON) 和纬度 (DEVICE_GEO_LAT)、ID (DEVICE_ID) 和距离 (DEVICE_GEO_DISTANCE)。

    填写完前面的信息后,我们可以看一下设计,报告如下。

    1. #include <ArduinoJson.h>
    2. #include <WiFi.h>
    3. #include <WiFiSSLClient.h>
    4. #include "ESClient.h"
    5. #include "elasticsearch_config.h"
    6. // WiFi settings
    7. char ssid[] = WIFI_SECRET_SSID;
    8. char pass[] = WIFI_SECRET_PASS;
    9. // Elastic settings
    10. char serverAddress[] = ELASTIC_ENDPOINT;
    11. int serverPort = ELASTIC_PORT;
    12. WiFiSSLClient wifi;
    13. ESClient client = ESClient(wifi, serverAddress, serverPort);
    14. int status = WL_IDLE_STATUS;
    15. void setup() {
    16. Serial.begin(9600);
    17. Serial.println("Started");
    18. while (status != WL_CONNECTED) {
    19. Serial.print("Attempting to connect to Network named: ");
    20. Serial.println(ssid);
    21. // Connect to WPA/WPA2 network:
    22. status = WiFi.begin(ssid, pass);
    23. }
    24. // print the SSID of the network you're attached to:
    25. Serial.print("SSID: ");
    26. Serial.println(WiFi.SSID());
    27. // print your WiFi shield's IP address:
    28. IPAddress ip = WiFi.localIP();
    29. Serial.print("IP Address: ");
    30. Serial.println(ip);
    31. client.setElasticCloudApiKey(ELASTIC_CLOUD_API_KEY);
    32. }
    33. void loop() {
    34. float temperature;
    35. // Set the temperature from a sensor (removing the randomness)
    36. temperature = random(10,30) + random(0,100)/100.00;
    37. // Prepare the JSON with temperature and geopoint for Elasticsearch
    38. StaticJsonDocument<200> doc;
    39. doc["temperature"] = temperature;
    40. doc["device-id"] = DEVICE_ID;
    41. doc["location"]["type"] = "Point";
    42. doc["location"]["coordinates"][0] = DEVICE_GEO_LON;
    43. doc["location"]["coordinates"][1] = DEVICE_GEO_LAT;
    44. String temp;
    45. serializeJson(doc, temp);
    46. Serial.println("Sending to Elasticsearch:");
    47. Serial.println(temp);
    48. ESResponse indexResult;
    49. // Send the temperature to Elastic Cloud
    50. indexResult = client.index("temperature", temp, "pipeline=set-timestamp");
    51. DynamicJsonDocument result(1024);
    52. deserializeJson(result, indexResult.body);
    53. if (result["result"] == "created") {
    54. Serial.println("Created with _id: " + result["_id"].as<String>());
    55. } else {
    56. Serial.println("Error sending data: " + indexResult.body);
    57. }
    58. StaticJsonDocument<512> query;
    59. query["query"]["bool"]["filter"]["geo_distance"]["distance"] = DEVICE_GEO_DISTANCE;
    60. query["query"]["bool"]["filter"]["geo_distance"]["location"][0] = DEVICE_GEO_LON;
    61. query["query"]["bool"]["filter"]["geo_distance"]["location"][1] = DEVICE_GEO_LAT;
    62. query["aggs"]["avg_temp"]["avg"]["field"] = "temperature";
    63. query["size"] = 0;
    64. String search;
    65. serializeJson(query, search);
    66. Serial.println("Geo-location query:");
    67. Serial.println(search);
    68. ESResponse searchResult;
    69. // Send the temperature to Elastic Cloud
    70. searchResult = client.search("temperature", search);
    71. DynamicJsonDocument avg(512);
    72. deserializeJson(avg, searchResult.body);
    73. float avgTemp = avg["aggregations"]["avg_temp"]["value"];
    74. int numDevices = avg["hits"]["total"]["value"];
    75. Serial.println("Average temperature of " + String(numDevices) + " devices in " + DEVICE_GEO_DISTANCE + ": " + String(avgTemp));
    76. Serial.println("Wait 30 seconds");
    77. delay(30000);
    78. }

    此设计需要 Wi-Fi、WiFiSSLClient(用于使用 TLS 进行连接)进行互联网连接、用于连接 Elasticsearch 的 EsClient 以及用于序列化和反序列化 Json 数据结构的 ArduinoJson 库。

    在 setup() 函数中,我们启动 Wi-Fi 连接,并使用 client.setElasticCloudApiKey(ELASTIC_CLOUD_API_KEY) 函数调用设置 Elastic Cloud 的 API 密钥。

    客户端对象在主区域中初始化,传递 Wi-Fi 对象、服务器地址(端点)和 HTTP 端口。

    在 loop() 函数中,我们有将温度发送到 Elastic Cloud 的代码。 这里的温度只是一个 10 到 30 之间的随机浮点数; 通常它来自连接到 Arduino 板的传感器。

    为了准备发送到 Elasticsearch 的文档,我们使用了 ArduinoJson 库。

    我们使用以下代码创建一个 “doc” 对象:

    1. StaticJsonDocument<200> doc;
    2. doc["temperature"] = temperature;
    3. doc["device-id"] = DEVICE_ID;
    4. doc["location"]["type"] = "Point";
    5. doc["location"]["coordinates"][0] = DEVICE_GEO_LON;
    6. doc["location"]["coordinates"][1] = DEVICE_GEO_LAT;

    该对象被序列化为 JSON 字符串,如下所示:

    1. String temp;
    2. serializeJson(doc, temp);

    最后,可以使用索引 API 将存储在 “temp” 变量中的文档发送到 Elasticsearch,如下所示:

    1. ESResponse indexResult;
    2. indexResult = client.index("temperature", temp, "pipeline=set-timestamp");

    此 API 使用 “set-timestamp” 管道在索引 “temp” 中添加 “temp” 文档。 结果存储在 “indexResult” 变量中,该变量是一个结构类型,如下所示:

    1. struct ESResponse {
    2. int statusCode;
    3. String body;
    4. };

    “statusCode” 是响应的 HTTP 状态代码,“body” 是响应正文。 如果响应包含值为 “created” 的 “result” 字段,则索引操作成功。

    为了获取半径 100 公里内设备的平均温度,我们使用了以下地理距离查询,使用 ArduinoJson 表示。

    1. StaticJsonDocument<512> query;
    2. query["query"]["bool"]["filter"]["geo_distance"]["distance"] = DEVICE_GEO_DISTANCE;
    3. query["query"]["bool"]["filter"]["geo_distance"]["location"][0] = DEVICE_GEO_LON;
    4. query["query"]["bool"]["filter"]["geo_distance"]["location"][1] = DEVICE_GEO_LAT;
    5. query["aggs"]["avg_temp"]["avg"]["field"] = "temperature";
    6. query["size"] = 0;
    7. String search;
    8. serializeJson(query, search);
    9. ESResponse searchResult;
    10. searchResult = client.search("temperature", search);
    11. DynamicJsonDocument avg(512);
    12. deserializeJson(avg, searchResult.body);
    13. float avgTemp = avg["aggregations"]["avg_temp"]["value"];
    14. int numDevices = avg["hits"]["total"]["value"];

    搜索的响应包含平均温度作为聚合值。 此外,我们可以使用 Elasticsearch 的 JSON 响应中的 ['hits']['total']['value'] 字段来检索查询检索到的设备数量。

    结论

    由于与 Arduino 的合作,我们开发了一个非常简单的库,允许直接从 Arduino 板使用 Elasticsearch。 只需几行代码,我们就可以将数据发送到 Elasticsearch 并使用地理定位等执行复杂的阐述。

    我们迫不及待地想看看 Arduino 用户将使用 Elasticsearch 设计出哪些其他创意用例。 例如,如果你对生成式人工智能感兴趣,你将享受 Elastic 的所有最新功能。

    不要再等待了 —— 尝试一下 Elastic Cloudelasticsearch-arduino 库。

    致谢

    我要感谢 Arduino 的所有员工,是他们使这个研发项目成为可能。 特别感谢 Giampaolo Mancini 在开发 elasticsearch-arduino 库方面的帮助和协作。 此外,我还要感谢 Arduino 的 Andrea Richetta 和 Stefano Implicito 使这次合作成为可能。

    本文中描述的任何特性或功能的发布和时间安排均由 Elastic 自行决定。 当前不可用的任何特性或功能可能无法按时交付或根本无法交付。

  • 相关阅读:
    ChatGPT 可以联网了!浏览器插件下载
    深入解析Kotlin类与对象:构造、伴生、单例全面剖析
    js中的this举例介绍
    把握出租车行驶的数据脉搏 :出租车轨迹数据给你答案!
    智慧幼儿园信息管理系统的设计与实现
    面试前“啃完”这份Java架构全栈知识点,金九银十过五关斩六将!
    Airflow用于ETL的四种基本运行模式, 2022-11-20
    最新全自动磁环电感线圈绕法跟磁环绕线后产品工艺流程介绍
    数字人扫描对虚拟人三维动画宣传片制作有何作用?
    技术杂记:nginx进程的view和kill / linux命令
  • 原文地址:https://blog.csdn.net/UbuntuTouch/article/details/133792686