warhammerkid / bluetti_mqtt

MQTT interface for Bluetti power stations
MIT License
139 stars 52 forks source link

How to get output power information for AC200MAX? #118

Open shurubura opened 1 month ago

shurubura commented 1 month ago

I'm not a pro, so creating the code with chatGPT

I have this code:

import asyncio
import signal
from bleak import BleakClient
from openpyxl import Workbook
from datetime import datetime
import re

# Адреса вашого пристрою Bluetti
DEVICE_ADDRESS = "6C9D629C-8755-D05B-FC20-3802D7F0F97B"

# Ініціалізуємо зупиняючу подію
stop_event = asyncio.Event()

def signal_handler(signal, frame):
    print("Signal received, stopping...")
    stop_event.set()

async def read_bluetti_data(client, characteristic_uuid):
    try:
        data = await client.read_gatt_char(characteristic_uuid)
        # Декодуємо дані як текст, якщо це можливо
        try:
            decoded_data = data.decode('utf-8')
        except UnicodeDecodeError:
            decoded_data = data.hex()
        # Видаляємо або замінюємо недопустимі символи
        cleaned_data = re.sub(r'[\x00-\x1f\x7f-\x9f]', ' ', decoded_data)
        return cleaned_data
    except Exception as e:
        print(f"Failed to read characteristic {characteristic_uuid}: {e}")
        return None

async def collect_data():
    async with BleakClient(DEVICE_ADDRESS) as client:
        services = await client.get_services()
        characteristics = [char.uuid for service in services for char in service.characteristics]

        # Фільтруємо характеристики, які не дозволяють читання
        readable_characteristics = []
        for char in characteristics:
            data = await read_bluetti_data(client, char)
            if data is not None:
                readable_characteristics.append(char)

        print(f"Readable characteristics: {readable_characteristics}")

        wb = Workbook()
        ws = wb.active
        ws.append(["Time"] + readable_characteristics)

        while not stop_event.is_set():
            row = [datetime.now().strftime("%Y-%m-%d %H:%M:%S")]
            for char in readable_characteristics:
                data = await read_bluetti_data(client, char)
                row.append(data if data is not None else "N/A")
            ws.append(row)
            wb.save("bluetti_data_filtered_characteristics.xlsx")
            await asyncio.sleep(1)

if __name__ == "__main__":
    signal.signal(signal.SIGINT, signal_handler)
    asyncio.run(collect_data())

And this is the output:

bluetti_env/bluetti_data_collection.py:35: FutureWarning: This method will be removed future version, use the services property instead.
  services = await client.get_services()
Failed to read characteristic 0000ff01-0000-1000-8000-00805f9b34fb: Failed to read characteristic 30: Error Domain=CBATTErrorDomain Code=2 "Reading is not permitted." UserInfo={NSLocalizedDescription=Reading is not permitted.}
Failed to read characteristic 0000ff02-0000-1000-8000-00805f9b34fb: Failed to read characteristic 33: Error Domain=CBATTErrorDomain Code=2 "Reading is not permitted." UserInfo={NSLocalizedDescription=Reading is not permitted.}
Failed to read characteristic 0000ff03-0000-1000-8000-00805f9b34fb: Failed to read characteristic 35: Error Domain=CBATTErrorDomain Code=2 "Reading is not permitted." UserInfo={NSLocalizedDescription=Reading is not permitted.}
Failed to read characteristic 0000ff04-0000-1000-8000-00805f9b34fb: Failed to read characteristic 37: Error Domain=CBATTErrorDomain Code=2 "Reading is not permitted." UserInfo={NSLocalizedDescription=Reading is not permitted.}
Readable characteristics: ['00002a23-0000-1000-8000-00805f9b34fb', '00002a24-0000-1000-8000-00805f9b34fb', '00002a25-0000-1000-8000-00805f9b34fb', '00002a26-0000-1000-8000-00805f9b34fb', '00002a27-0000-1000-8000-00805f9b34fb', '00002a28-0000-1000-8000-00805f9b34fb', '00002a29-0000-1000-8000-00805f9b34fb', 'f7bf3564-fb6d-4e53-88a4-5e37e0326063', '984227f3-34fc-4045-a5d0-2c581f81a153']

What should I do to get output power information every second?

mpapirkovskyy commented 1 month ago

It depends on your goal. This tool runs almost perfectly with Home Assistant via MQTT integration. You need MQTT broker, but after setup all data gets reported there on regular interval. You can listen MQTT broker also for your other needs using any MQTT client.

If you really want to do it with code, take a look at logger_cli code, it does almost what you want, but writes output to file. https://github.com/warhammerkid/bluetti_mqtt/blob/main/bluetti_mqtt/logger_cli.py#L54

mpapirkovskyy commented 1 month ago

Here's an example of what you get in Home Assistant after setting it up:

image

Plus ability to control your bluetti from dashboard (enable/disable AC and DC outputs), and create automations based on data from device.