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":

bash 复制代码
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" 管道:

sql 复制代码
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,如下所示:

sql 复制代码
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 查询:

bash 复制代码
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 文件,如下所示:

arduino 复制代码
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)。

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

scss 复制代码
1.  #include <ArduinoJson.h>
2.  #include <WiFi.h>
3.  #include <WiFiSSLClient.h>
4.  #include "ESClient.h" 
5.  #include "elasticsearch_config.h"

7.  // WiFi settings
8.  char ssid[] = WIFI_SECRET_SSID;
9.  char pass[] = WIFI_SECRET_PASS;

11.  // Elastic settings
12.  char serverAddress[] = ELASTIC_ENDPOINT;
13.  int serverPort = ELASTIC_PORT;

15.  WiFiSSLClient wifi;

17.  ESClient client = ESClient(wifi, serverAddress, serverPort); 
18.  int status = WL_IDLE_STATUS;

20.  void setup() {
21.    Serial.begin(9600);
22.    Serial.println("Started");

24.    while (status != WL_CONNECTED) {
25.      Serial.print("Attempting to connect to Network named: ");
26.      Serial.println(ssid);

28.      // Connect to WPA/WPA2 network:
29.      status = WiFi.begin(ssid, pass);
30.    }

32.    // print the SSID of the network you're attached to:
33.    Serial.print("SSID: ");
34.    Serial.println(WiFi.SSID());

36.    // print your WiFi shield's IP address:
37.    IPAddress ip = WiFi.localIP();
38.    Serial.print("IP Address: ");
39.    Serial.println(ip);

41.    client.setElasticCloudApiKey(ELASTIC_CLOUD_API_KEY);
42.  }

44.  void loop() {

46.    float temperature;
47.    // Set the temperature from a sensor (removing the randomness)
48.    temperature = random(10,30) + random(0,100)/100.00;

50.    // Prepare the JSON with temperature and geopoint for Elasticsearch
51.    StaticJsonDocument<200> doc;
52.    doc["temperature"] = temperature;
53.    doc["device-id"] = DEVICE_ID;
54.    doc["location"]["type"] = "Point";
55.    doc["location"]["coordinates"][0] = DEVICE_GEO_LON;
56.    doc["location"]["coordinates"][1] = DEVICE_GEO_LAT;

58.    String temp;
59.    serializeJson(doc, temp);

61.    Serial.println("Sending to Elasticsearch:");
62.    Serial.println(temp);
63.    ESResponse indexResult;
64.    // Send the temperature to Elastic Cloud
65.    indexResult = client.index("temperature", temp, "pipeline=set-timestamp");

67.    DynamicJsonDocument result(1024);
68.    deserializeJson(result, indexResult.body);

70.    if (result["result"] == "created") {
71.      Serial.println("Created with _id: " + result["_id"].as<String>());
72.    } else {
73.      Serial.println("Error sending data: " + indexResult.body);

75.    }

77.    StaticJsonDocument<512> query;
78.    query["query"]["bool"]["filter"]["geo_distance"]["distance"] = DEVICE_GEO_DISTANCE;
79.    query["query"]["bool"]["filter"]["geo_distance"]["location"][0] = DEVICE_GEO_LON;
80.    query["query"]["bool"]["filter"]["geo_distance"]["location"][1] = DEVICE_GEO_LAT;
81.    query["aggs"]["avg_temp"]["avg"]["field"] = "temperature";
82.    query["size"] = 0;

84.    String search;
85.    serializeJson(query, search);
86.    Serial.println("Geo-location query:");
87.    Serial.println(search);

89.    ESResponse searchResult;
90.    // Send the temperature to Elastic Cloud
91.    searchResult = client.search("temperature", search);

93.    DynamicJsonDocument avg(512);
94.    deserializeJson(avg, searchResult.body);
95.    float avgTemp = avg["aggregations"]["avg_temp"]["value"];
96.    int numDevices = avg["hits"]["total"]["value"];
97.    Serial.println("Average temperature of " + String(numDevices) + " devices in " + DEVICE_GEO_DISTANCE + ": " + String(avgTemp));

99.    Serial.println("Wait 30 seconds");
100.    delay(30000);
101.  }

此设计需要 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" 对象:

css 复制代码
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 字符串,如下所示:

ini 复制代码
1.  String temp;
2.  serializeJson(doc, temp);

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

ini 复制代码
1.  ESResponse indexResult;
2.  indexResult = client.index("temperature", temp, "pipeline=set-timestamp");

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

markdown 复制代码
1.  struct ESResponse {
2.      int statusCode;
3.      String body;
4.  };

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

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

scss 复制代码
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;

8.  String search;
9.  serializeJson(query, search);

11.  ESResponse searchResult;
12.  searchResult = client.search("temperature", search);

14.  DynamicJsonDocument avg(512);
15.  deserializeJson(avg, searchResult.body);
16.  float avgTemp = avg["aggregations"]["avg_temp"]["value"];
17.  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 自行决定。 当前不可用的任何特性或功能可能无法按时交付或根本无法交付。

相关推荐
工作中的程序员3 分钟前
ES 索引或索引模板
大数据·数据库·elasticsearch
Lill_bin12 小时前
深入理解ElasticSearch集群:架构、高可用性与数据一致性
大数据·分布式·elasticsearch·搜索引擎·zookeeper·架构·全文检索
RwTo14 小时前
Elasticsearch 聚合搜索
大数据·elasticsearch·搜索引擎·全文检索
求学小火龙15 小时前
ElasticSearch介绍+使用
java·大数据·elasticsearch
檀越剑指大厂15 小时前
【Elasticsearch系列六】系统命令API
大数据·elasticsearch·搜索引擎
bug菌¹21 小时前
滚雪球学SpringCloud[5.1讲]: Spring Cloud Config详解
spring·elasticsearch·spring cloud
Li小李同学Li21 小时前
git学习【持续更新中。。。】
git·学习·elasticsearch
nangonghen1 天前
通过logstash同步elasticsearch数据
大数据·elasticsearch
檀越剑指大厂1 天前
【Elasticsearch系列四】ELK Stack
大数据·elk·elasticsearch
2401_840192271 天前
ELFK日志分析平台,架构和通信
elk·elasticsearch·架构