Skip to content

Commit 720349e

Browse files
committed
influxdb integration
1 parent 833a2df commit 720349e

File tree

5 files changed

+46
-104
lines changed

5 files changed

+46
-104
lines changed

.github/workflows/main.yml

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,29 +23,30 @@ jobs:
2323
pip install pyinstaller
2424
pip install pythonnet
2525
pip install rich
26+
pip install influxdb-client
2627
2728
- name: Get Latest .DLL files
2829
id: get_release
2930
run: |
3031
$response = Invoke-RestMethod -Uri "https://api.github.com/repos/LibreHardwareMonitor/LibreHardwareMonitor/releases/latest"
3132
$asset = $response.assets | Where-Object { $_.name -like "*LibreHardwareMonitor*.zip" }
3233
"zip_url=$($asset.browser_download_url)" | Out-File -FilePath $env:GITHUB_ENV -Append
33-
- name: 📥 Download and extract DLLs
34+
- name: Download and extract DLLs
3435
run: |
3536
curl -L -o LibreHardwareMonitor.zip $env:zip_url
3637
Expand-Archive -Path LibreHardwareMonitor.zip -DestinationPath libre_cli
3738
38-
- name: 🛠️ Build with PyInstaller
39+
- name: Build with PyInstaller
3940
run: |
4041
python -m PyInstaller --onefile --name "LibreMonitor" `
4142
.\main.py `
4243
--add-binary ".\libre_cli\LibreHardwareMonitorLib.dll;libre_cli" `
4344
--add-binary ".\libre_cli\Aga.Controls.dll;libre_cli" `
4445
--add-binary ".\libre_cli\HidSharp.dll;libre_cli"
45-
- name: 🏷️ Set version tag
46+
- name: Set version tag
4647
run: |
4748
echo "VERSION=$(git rev-parse --short HEAD)" >> $env:GITHUB_ENV
48-
- name: 📤 Upload artifact
49+
- name: Upload artifact
4950
uses: actions/[email protected]
5051
with:
5152
name: LibreMonitor

influxdb/__init__.py

Whitespace-only changes.

influxdb/influx.py

Lines changed: 22 additions & 96 deletions
Original file line numberDiff line numberDiff line change
@@ -1,100 +1,26 @@
1-
"""
2-
Example script that will dump all the info out of the dll and print it out
3-
"""
4-
from libre_cli.libre_hardware_monitor_reporter import LibreHardwareMonitorReporter
5-
import time
6-
import argparse
7-
import requests
1+
from influxdb_client import InfluxDBClient, Point
2+
from influxdb_client.client.write_api import SYNCHRONOUS
3+
import datetime
84

9-
def send_to_influxdb(data, influx_url, token, org, bucket):
10-
"""
11-
Sends sensor data to an InfluxDBv2 server.
12-
"""
13-
headers = {
14-
"Authorization": f"Token {token}",
15-
"Content-Type": "text/plain; charset=utf-8"
16-
}
17-
# This will take the payload from here and format it into an InfluxDB request
18-
#payload = ""
19-
#for sensor in data:
20-
# Format data in InfluxDB line protocol
21-
# payload += f"{sensor[0]},type={sensor[1]}, value={sensor[2]}\n"
22-
# payload += f"{sensor.Hardware.Name},type={sensor.Name} value={sensor.Value}\n"
5+
class influx_manager:
6+
def __init__(self,url,token,org,bucket):
7+
self.url = url
8+
self.token = token
9+
self.org = org
10+
self.bucket = bucket
2311

24-
# Convert the data to line protocol
25-
lines = []
12+
# Initialize client
13+
self.client = InfluxDBClient(url=self.url, token=self.token, org=self.org)
14+
self.write_api = self.client.write_api(write_options=SYNCHRONOUS)
2615

27-
for sensor_name, metric_name, value in data:
28-
try:
29-
metric_clean = metric_name.replace(" ", "_").lower()
30-
sensor_name_clean = sensor_name.replace(" ", "_").lower()
31-
line = f"sensor_metrics,sensor_name={sensor_name_clean} {metric_clean}={float(value)}"
32-
lines.append(line)
33-
except ValueError:
34-
print(f"Skipping invalid value: {value} for {metric_name}")
16+
def write_data(self,data_point):
17+
# POINT DATA HERE
18+
point = Point(data_point[0]) \
19+
.tag("component", data_point[1]) \
20+
.tag("sensor", data_point[2]) \
21+
.field("value", data_point[3]) \
22+
.time(datetime.datetime.utcnow())
23+
self.write_api.write(bucket=self.bucket, org=self.org, record=point)
3524

36-
payload = "\n".join(lines)
37-
38-
try:
39-
response = requests.post(
40-
f"{influx_url}/api/v2/write?org={org}&bucket={bucket}&precision=s",
41-
headers=headers,
42-
data=payload
43-
)
44-
if response.status_code == 204:
45-
print("Data successfully written to InfluxDB.")
46-
else:
47-
print(f"Failed to write to InfluxDB: {response.status_code} - {response.text}")
48-
except Exception as e:
49-
print(f"Error sending data to InfluxDB: {e}")
50-
51-
if __name__ == "__main__":
52-
try :
53-
parser = argparse.ArgumentParser(description='Check to see if any flags are present')
54-
parser.add_argument('-t', action='store_true', help='If -t is present, will continue indefintely')
55-
# InfluxDB stuff
56-
parser.add_argument('--influx-url', type=str, help='InfluxDBv2 server URL')
57-
parser.add_argument('--token', type=str, help='InfluxDBv2 authentication token')
58-
parser.add_argument('--org', type=str, help='InfluxDBv2 organization')
59-
parser.add_argument('--bucket', type=str, help='InfluxDBv2 bucket')
60-
# Parse the arguments
61-
args = parser.parse_args()
62-
# Access the value of the -t argument
63-
print("Starting LibreHardwareMonitor...")
64-
LibreHardwareMonitorReport = LibreHardwareMonitorReporter()
65-
# If arg.t is present, report indefintely
66-
if args.t :
67-
while True :
68-
LibreHardwareMonitorReport.get_sensor_data()
69-
for i in LibreHardwareMonitorReport.results:
70-
print(i)
71-
time.sleep(10)
72-
# Send data to InfluxDB if credentials are provided
73-
if args.influx_url and args.token and args.org and args.bucket:
74-
send_to_influxdb(
75-
LibreHardwareMonitorReport.results,
76-
args.influx_url,
77-
args.token,
78-
args.org,
79-
args.bucket
80-
)
81-
else :
82-
LibreHardwareMonitorReport.get_sensor_data()
83-
for i in LibreHardwareMonitorReport.results:
84-
print(i)
85-
# Send data to InfluxDB if credentials are provided
86-
if args.influx_url and args.token and args.org and args.bucket:
87-
send_to_influxdb(
88-
LibreHardwareMonitorReport.results,
89-
args.influx_url,
90-
args.token,
91-
args.org,
92-
args.bucket
93-
)
94-
print("Completed")
95-
96-
except KeyboardInterrupt:
97-
# When being shut down, close the handle
98-
LibreHardwareMonitorReport.handler.Close()
99-
print("LibreHardwareMonitor closed.")
100-
print("Exiting...")
25+
def exit(self):
26+
self.client.close()

main.py

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@
66
# For Windows key press detection
77
import msvcrt
88

9+
# For Influx Integration
10+
from influxdb.influx import influx_manager
11+
912
# For the rich table output integration
1013
from rich.console import Console
1114
from rich.table import Table
@@ -117,7 +120,7 @@ def make_table(sensor_data, filters=None):
117120
# Setting up Rich Console and Argparse for future use
118121
console = Console()
119122
parser = argparse.ArgumentParser(description='Check to see if any flags are present')
120-
123+
use_influx = False
121124
# InfluxDB stuff
122125
parser.add_argument('--influx-url', type=str, help='InfluxDBv2 server URL')
123126
parser.add_argument('--token', type=str, help='InfluxDBv2 authentication token')
@@ -149,7 +152,12 @@ def make_table(sensor_data, filters=None):
149152
"Storage": args.Storage if args.Storage else False,
150153
"quit": False,
151154
}
152-
155+
# If InfluxDB arguments are present :
156+
influx_man = False
157+
if (args.influx_url and args.token and args.org and args.bucket):
158+
use_influx = True
159+
influx_man = influx_manager(args.influx_url, args.token, args.org, args.bucket)
160+
153161
# TLDR; if there is any hardware filter, then set those values in the LibreHardwareMonitorReporter init
154162
# If no hardware filter args are present, then just init all of them (which is recommended)
155163
if(args.CPU or args.GPU or args.Memory or args.Motherboard or args.Controller or args.Network or args.Storage):
@@ -186,7 +194,10 @@ def make_table(sensor_data, filters=None):
186194
console.log("Fetched sensor data:")
187195
try :
188196
for filter_type, device, sensor, value in sensor_data:
189-
print(f" {filter_type} | {device} | {sensor} | {float(value):.2f}")
197+
print(f" {filter_type} | {device} | {sensor} | {float(value):.2f}")
198+
if influx_man:
199+
influx_man.write_data([filter_type,device,sensor,float(value)])
200+
190201
except KeyboardInterrupt :
191202
print("Exiting on user request...")
192203
time.sleep(time_refresh)
@@ -195,6 +206,9 @@ def make_table(sensor_data, filters=None):
195206
with Live(make_table([],filters), refresh_per_second=1, console=console, screen=True) as live:
196207
while not filters["quit"]:
197208
sensor_data = LibreHardwareMonitorReport.get_sensor_data()
209+
if influx_man:
210+
for filter_type, device, sensor, value in sensor_data:
211+
influx_man.write_data([filter_type,device,sensor,float(value)])
198212
live.update(make_table(sensor_data, filters))
199213
refresh_event.wait(timeout=time_refresh)
200214
refresh_event.clear()

requirements.txt

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
pythonnet
2-
rich
2+
rich
3+
influxdb-client

0 commit comments

Comments
 (0)