Change python code for use of Influxdb v2

Hello, for several years now, I've been using a small Python script to read data from my Growatt inverter and then send the data to a database (Influxdb v1.8). Now that I'd like to switch to Influxdb v2, I need to modify the script to use the organization name and token. Since I don't have enough Python knowledge (yet), I'm wondering if anyone here can help.

Here is my code:
```
#!/usr/bin/env python3

import time
import os

from configparser import RawConfigParser
from influxdb import InfluxDBClient
from pymodbus.client.sync import ModbusSerialClient as ModbusClient

from growatt import Growatt

settings = RawConfigParser()
settings.read(os.path.dirname(os.path.realpath(__file__)) + '/solarmon.cfg')

interval = settings.getint('query', 'interval', fallback=1)
offline_interval = settings.getint('query', 'offline_interval', fallback=60)
error_interval = settings.getint('query', 'error_interval', fallback=60)

db_name = settings.get('influx', 'db_name', fallback='inverter')
measurement = settings.get('influx', 'measurement', fallback='inverter')

# Clients
print('Setup InfluxDB Client... ', end='')
influx = InfluxDBClient(host=settings.get('influx', 'host', fallback='localhost'),
                        port=settings.getint('influx', 'port', fallback=8086),
                        username=settings.get('influx', 'username', fallback=None),
                        password=settings.get('influx', 'password', fallback=None),
                        database=db_name)
influx.create_database(db_name)
print('Done!')

print('Setup Serial Connection... ', end='')
port = settings.get('solarmon', 'port', fallback='/dev/ttyUSB1')
client = ModbusClient(method='rtu', port=port, baudrate=9600, stopbits=1, parity='N', bytesize=8, timeout=1)
client.connect()
print('Dome!')

print('Loading inverters... ')
inverters = []
for section in settings.sections():
    if not section.startswith('inverters.'):
        continue

    name = section[10:]
    unit = int(settings.get(section, 'unit'))
    measurement = settings.get(section, 'measurement')
    growatt = Growatt(client, name, unit)
    growatt.print_info()
    inverters.append({
        'error_sleep': 0,
        'growatt': growatt,
        'measurement': measurement
    })
print('Done!')

while True:
    online = False
    for inverter in inverters:
        # If this inverter errored then we wait a bit before trying again
        if inverter['error_sleep'] > 0:
            inverter['error_sleep'] -= interval
            continue

        growatt = inverter['growatt']
        try:
            now = time.time()
            info = growatt.read()

            if info is None:
                continue

            # Mark that at least one inverter is online so we should continue collecting data
            online = True

            points = [{
                'time': int(now),
                'measurement': inverter['measurement'],
                "fields": info
            }]

            print(growatt.name)
            print(points)

            if not influx.write_points(points, time_precision='s'):
                print("Failed to write to DB!")
        except Exception as err:
            print(growatt.name)
            print(err)
            inverter['error_sleep'] = error_interval

    if online:
        time.sleep(interval)
    else:
        # If all the inverters are not online because no power is being generated then we sleep for 1 min
        time.sleep(offline_interval)
```

This is the config file:

```
[influx]
host = 192.168.2.806
port = 8086
username =
password =
db_name = inverter

[query]
interval = 1
offline_interval = 60
error_interval = 60

[solarmon]
port = /dev/ttyUSB0

[inverters.main]
unit = 0
measurement = inverter
```

I don’t know what the v2 InfluxDBClient requires exactly. And it’s not best practise to store credentials in a file by the way (but you’re doing that already, and this code is probably only running on client machines, all behind a router’s fire wall). But I would try the changes below. The gist of it is simply to replace username with org_name, and password with token, in both the code and config file:


influx = InfluxDBClient(host=,
                        port=,
                        org_name=settings.get('influx', 'org_name', fallback=None),
                        token=settings.get('influx', 'token', fallback=None),
                        database=,)

solarmon.cfg

[influx]
host = 192.168.2.806
port = 8086
org_name =
token =
db_name = inverter

Hi James,
I tried it as you described, but I get an error that the influxdbclient cannot be loaded. Could it be that I’m still using the influxdbclient from version 1? And how do I tell which one it is?

Hi Nico,
I’m not sure how cloud DB services are implemented, but is the URL the same for v2? Quite often for APIs, after an upgrade on their side, to use the new one you’d have to bump the end point to example.com/api/v2.

Otherwise, there’s no other way than double checking their API docs I’m afraid. The version of their library you have installed could be checked by looking at influxdb.__version__ in Python, or pip freeze from the command line.