Commit 92faa681 authored by Nikita Yurishev's avatar Nikita Yurishev

added new influxdb logic

parent b8409151
...@@ -2,11 +2,12 @@ ...@@ -2,11 +2,12 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
import logging as log import logging as log
import time
import hid import hid
import sys import sys
import socket import socket
from influxWriter import InfluxWriter #from influxWriter import InfluxWriter
from influxConnection import InfluxConnection
CO2_USB_MFG = 'Holtek' CO2_USB_MFG = 'Holtek'
CO2_USB_PRD = 'USB-zyTemp' CO2_USB_PRD = 'USB-zyTemp'
...@@ -47,8 +48,8 @@ class ZyTemp(): ...@@ -47,8 +48,8 @@ class ZyTemp():
self._magic_table = _CO2MON_MAGIC_TABLE self._magic_table = _CO2MON_MAGIC_TABLE
self._magic_table_int = list_to_longint(_CO2MON_MAGIC_TABLE) self._magic_table_int = list_to_longint(_CO2MON_MAGIC_TABLE)
self.influx_writer = InfluxWriter() # Создаем объект для работы с InfluxDB #self.influx_writer = InfluxWriter()
self.influx_writer = InfluxConnection() # Создаем объект для работы с InfluxDB
if decrypt: if decrypt:
self.h.send_feature_report(self._magic_table) self.h.send_feature_report(self._magic_table)
else: else:
...@@ -63,7 +64,11 @@ class ZyTemp(): ...@@ -63,7 +64,11 @@ class ZyTemp():
if all(value is not None for value in values.values()): if all(value is not None for value in values.values()):
sensor_id = socket.gethostname() sensor_id = socket.gethostname()
print(f"{sensor_id}: {values}") print(f"{sensor_id}: {values}")
self.influx_writer.write_data(sensor_id, values) # Записываем данные в InfluxDB #Проверка записи в InfluxDB
try:
self.influx_writer.write_data(sensor_id, values) # Записываем данные в InfluxDB
except Exception as e:
l.error("failed to write data into InfluxDB: {e} ")
sys.exit(0) sys.exit(0)
#! #!
def run_once(self, decrypt=False): def run_once(self, decrypt=False):
...@@ -127,7 +132,6 @@ def get_hiddev(): ...@@ -127,7 +132,6 @@ def get_hiddev():
path_str = path.decode('utf-8') path_str = path.decode('utf-8')
l.info(f'Found CO2 sensor at intf. {intf}, {path_str}, VID={vid:04x}, PID={pid:04x}') l.info(f'Found CO2 sensor at intf. {intf}, {path_str}, VID={vid:04x}, PID={pid:04x}')
p.append(path) p.append(path)
if not p: if not p:
l.error('No device found') l.error('No device found')
return None return None
......
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import configparser
from influxdb import InfluxDBClient from influxdb import InfluxDBClient
import time import time
class InfluxWriter: class InfluxConnection:
def __init__(self): def __init__(self):
# Чтение конфигурации из файла config.ini # Конфиги
config = configparser.ConfigParser() self.INFLUXDB_URL = 'http://localhost:8086'
config.read('config.ini') self.INFLUXDB_DB = ''
self.INFLUXDB_USER = ''
self.INFLUXDB_PASSWORD = ''
self.INFLUXDB_URL = config.get('influxdb', 'url') # Разделение URL на хост и порт
self.INFLUXDB_DB = config.get('influxdb', 'database') url_parts = self.INFLUXDB_URL.split('://')[1].split(':')
self.INFLUXDB_USER = config.get('influxdb', 'username') host = url_parts[0]
self.INFLUXDB_PASSWORD = config.get('influxdb', 'password') port = int(url_parts[1]) if len(url_parts) > 1 else 8086
# Подключение к InfluxDB # Подключение к InfluxDB
self.client = InfluxDBClient( self.client = InfluxDBClient(
host=self.INFLUXDB_URL.split(':')[1].strip('/'), host=host,
port=int(self.INFLUXDB_URL.split(':')[2]), port=port,
username=self.INFLUXDB_USER, username=self.INFLUXDB_USER,
password=self.INFLUXDB_PASSWORD, password=self.INFLUXDB_PASSWORD,
database=self.INFLUXDB_DB database=self.INFLUXDB_DB
) )
# Создание базы данных (если её нет)
self.client.create_database(self.INFLUXDB_DB)
def write_data(self, sensor_id, values): def write_data(self, sensor_id, values):
json_body = [ json_body = [
{ {
...@@ -30,11 +34,15 @@ class InfluxWriter: ...@@ -30,11 +34,15 @@ class InfluxWriter:
"tags": { "tags": {
"sensor_id": sensor_id "sensor_id": sensor_id
}, },
"time": int(time.time() * 1000), "time": int(time.time() * 1000), # Текущая метка времени в миллисекундах
"fields": values "fields": values
} }
] ]
self.client.write_points(json_body, database=self.INFLUXDB_DB) try:
self.client.write_points(json_body, database=self.INFLUXDB_DB)
print("Successfully wrote data to InfluxDB")
except Exception as e:
print(f"Failed to write data to InfluxDB: {e}")
def __del__(self): def __del__(self):
self.client.close() self.client.close()
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment