Created
March 13, 2023 11:20
-
-
Save jsjolund/a9365494e61dd6c59e1f96ef865c7664 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# kairosdb-downloader | |
# This Python code is an example of how to download metrics from KairosDB and plot them using matplotlib. Run it with: | |
# python plot_kairosdb.py | |
import json | |
from datetime import datetime | |
import matplotlib.dates as md | |
import matplotlib.pyplot as plt | |
import numpy as np | |
import requests | |
URL: str = 'http://kairosdb.icedc.se/api/v1/datapoints/query' | |
# Generated by the KairosDB web interface at http://kairosdb.icedc.se | |
# by selecting the metrics, tags, and aggregators you want to use | |
# and then clicking "Show Query" | |
QUERY = { | |
"metrics": [ | |
{ | |
"tags": { | |
"pod": [ | |
"3" | |
], | |
"deviceType": [ | |
"str" | |
], | |
"deviceNumber": [ | |
"1", | |
] | |
}, | |
"name": "humidity", | |
"aggregators": [ | |
{ | |
"name": "avg", | |
"sampling": { | |
"value": "1", | |
"unit": "seconds" | |
}, | |
"align_start_time": True | |
} | |
] | |
} | |
], | |
"plugins": [], | |
"cache_time": 0, | |
"start_relative": { | |
"value": "20", | |
"unit": "minutes" | |
} | |
} | |
def main() -> None: | |
# Sends a POST request to KairosDB with the QUERY in the body | |
res = requests.post( | |
URL, | |
data=json.dumps(QUERY), | |
headers={'Content-Type': 'application/json'}, | |
timeout=5 | |
).json() | |
# The values are in the format [[ms_timestamp, value], [ms_timestamp, value], ...] | |
res_values = res['queries'][0]['results'][0]['values'] | |
# Extract the timestamps and convert to seconds since epoch | |
timestamps = [x[0]/1000 for x in res_values] | |
# Convert the timestamps to datetime objects | |
dates = [datetime.fromtimestamp(ts) for ts in timestamps] | |
datenums = md.date2num(dates) | |
# Extract the values | |
values = [x[1] for x in res_values] | |
# Set the x-axis to be the formatted dates | |
plt.subplots_adjust(bottom=0.2) | |
plt.xticks(rotation=25) | |
ax = plt.gca() | |
xfmt = md.DateFormatter('%Y-%m-%d %H:%M:%S') | |
ax.xaxis.set_major_formatter(xfmt) | |
# Plot the values | |
plt.plot(datenums, values) | |
plt.show() | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment