1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# -*- 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()