I'm trying to figure out how to get sensor data from a python script output into Highcharts. Rather than write all my code directly in javascript, I decided to save the python sensor data as a dictionary in a text file. My data.txt file looks like this:
{'outdoor_temp': 45.7, 'outdoor_humid': 91.8}
The relevant portion of my Highcharts code looks like this:
load: function () {
var series = this.series[0];
setInterval(function () {
var x = (new Date()).getTime(),
file=fopen(data.txt,0)
y = (file["outdoor_temp"]);
series.addPoint([x, y], true, true);
}, 2000);
Why doesn't this read the dictionary value stored in data.txt?
If you want to store your data in files I would recommend you use JSON. JSON is supported out of the box by both Python and JavaScript and is very easy to work with.
import json
data = {'outdoor_temp': 45.7, 'outdoor_humid': 91.8}
with open("data.json", "w") as f:
json.dump(data, f)
The created data.json file then looks like this:
{"outdoor_temp": 45.7, "outdoor_humid": 91.8}
You can then read the created file using the following Node program:
import { readFile } from "fs/promises";
// await can only be used in an async function
(async () => {
const file = await readFile("data.json", { encoding: "utf-8"});
const parsed = JSON.parse(file);
// log all data
console.log(parsed);
// log outdoor temperature
console.log(parsed.outdoor_temp)
})()
Please note: You will need to implement some error handling for the above programs yourself.
If you want to store the data and maybe do some calculations, do more visualizations etc. I recommend you use a database such as MongoDB or a timeseries database such as InfluxDB instead of single files. Grafana has integrations for them as well if you are looking for some nice visualization tool for your data.