I am trying to build up a dictionary / json object of sensor values in esphome. I have a sensor that sends me key / value pairs (e.g. one sensor reading could be { “temperature“: 25.1 }
, another one could be { “speed“: 50.1 }
and so forth) in very high frequency (milliseconds). What I would like to do is to collect data for these key / value pairs for a certain time span, for simplicity say ten seconds, and only then take the dictionary and post it to a web service. It would also somehow combine the readings for the same key if sent multiple times within the ten seconds time span for example by averaging them out, using a filter or whatever. So the final dictionary to be posted to the web service would then look like
{
“temperature“: 26.3,
“speed“: 52.5,
…
}
How could I achieve this - any idea / proposal?
Thanks and best regards
Dear stackoverflow community,
I found a solution to this issue. I am now using a global variable in esphome. This can be defined as follows:
globals:
- id: "my_dict"
type: std::map<std::string, std::string>
With this, I have a global map which I can use to store the key / value pairs. Adding a new key / value pair via a lambda works as simple as shown in the following (where in this example, the key is stored in the variable key
and the value is stored in the variable value
:
lambda: |-
id(my_dict)[key] = value;
Every ten seconds, I post the dictionary content to the web service and then clear the dictionary again:
interval:
- interval: 10s
then:
- http_request.post:
url: "https://<URL>"
json: |-
for ( auto item : id(my_dict) ) {
root[item.first] = item.second;
}
- lambda: |-
id(my_dict).clear();