influxWriter.py 1.29 KB
# -*- coding: utf-8 -*-
import configparser
from influxdb import InfluxDBClient
import time

class InfluxWriter:
    def __init__(self):
        # Чтение конфигурации из файла config.ini
        config = configparser.ConfigParser()
        config.read('config.ini')

        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')

        # Подключение к InfluxDB
        self.client = InfluxDBClient(
            host=self.INFLUXDB_URL.split(':')[1].strip('/'),
            port=int(self.INFLUXDB_URL.split(':')[2]),
            username=self.INFLUXDB_USER,
            password=self.INFLUXDB_PASSWORD,
            database=self.INFLUXDB_DB
        )

    def write_data(self, sensor_id, values):
        json_body = [
            {
                "measurement": "sensor_data",
                "tags": {
                    "sensor_id": sensor_id
                },
                "time": int(time.time() * 1000), 
                "fields": values
            }
        ]
        self.client.write_points(json_body, database=self.INFLUXDB_DB)

    def __del__(self):
        self.client.close()