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

added new influxdb logic

parent b8409151
......@@ -2,11 +2,12 @@
#!/usr/bin/env python3
import logging as log
import time
import hid
import sys
import socket
from influxWriter import InfluxWriter
#from influxWriter import InfluxWriter
from influxConnection import InfluxConnection
CO2_USB_MFG = 'Holtek'
CO2_USB_PRD = 'USB-zyTemp'
......@@ -47,8 +48,8 @@ class ZyTemp():
self._magic_table = _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:
self.h.send_feature_report(self._magic_table)
else:
......@@ -63,7 +64,11 @@ class ZyTemp():
if all(value is not None for value in values.values()):
sensor_id = socket.gethostname()
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)
#!
def run_once(self, decrypt=False):
......@@ -127,7 +132,6 @@ def get_hiddev():
path_str = path.decode('utf-8')
l.info(f'Found CO2 sensor at intf. {intf}, {path_str}, VID={vid:04x}, PID={pid:04x}')
p.append(path)
if not p:
l.error('No device found')
return None
......
# -*- coding: utf-8 -*-
import configparser
from influxdb import InfluxDBClient
import time
class InfluxWriter:
class InfluxConnection:
def __init__(self):
# Чтение конфигурации из файла config.ini
config = configparser.ConfigParser()
config.read('config.ini')
# Конфиги
self.INFLUXDB_URL = 'http://localhost:8086'
self.INFLUXDB_DB = ''
self.INFLUXDB_USER = ''
self.INFLUXDB_PASSWORD = ''
self.INFLUXDB_URL = config.get('influxdb', 'url')
self.INFLUXDB_DB = config.get('influxdb', 'database')
self.INFLUXDB_USER = config.get('influxdb', 'username')
self.INFLUXDB_PASSWORD = config.get('influxdb', 'password')
# Разделение URL на хост и порт
url_parts = self.INFLUXDB_URL.split('://')[1].split(':')
host = url_parts[0]
port = int(url_parts[1]) if len(url_parts) > 1 else 8086
# Подключение к InfluxDB
self.client = InfluxDBClient(
host=self.INFLUXDB_URL.split(':')[1].strip('/'),
port=int(self.INFLUXDB_URL.split(':')[2]),
host=host,
port=port,
username=self.INFLUXDB_USER,
password=self.INFLUXDB_PASSWORD,
database=self.INFLUXDB_DB
)
# Создание базы данных (если её нет)
self.client.create_database(self.INFLUXDB_DB)
def write_data(self, sensor_id, values):
json_body = [
{
......@@ -30,11 +34,15 @@ class InfluxWriter:
"tags": {
"sensor_id": sensor_id
},
"time": int(time.time() * 1000),
"time": int(time.time() * 1000), # Текущая метка времени в миллисекундах
"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):
self.client.close()
\ No newline at end of file
self.client.close()
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