#!/usr/bin/env python3
import time
import paho.mqtt.client as mqtt  # pip install paho-mqtt

# --- НАСТРОЙКИ ПОД СЕБЯ ---
MQTT_HOST = "192.168.xx.xx"   # брокер (или возьми из secrets)
MQTT_PORT = 1883
MQTT_USER = "xxxx"
MQTT_PASS = "xxxx"

DEVICE_NAME = "can_pcf8574_bridge"   # esphome.name
TOPIC_PCF_20 = f"{DEVICE_NAME}/number/pcf_0x20/command"
TOPIC_PCF_21 = f"{DEVICE_NAME}/number/pcf_0x21/command"

# задержка между публикациями (в секундах)
DELAY = 0.1   # 0.1 c = 100 мс

# диапазоны из твоего YAML
PCF_20_MIN, PCF_20_MAX = 7, 7
PCF_21_MIN, PCF_21_MAX = 0, 4


def on_connect(client, userdata, flags, rc, properties=None):
    print("Connected with result code", rc)


def main():
    #client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
    client = mqtt.Client()  # для paho-mqtt < 2.0.0
    client.username_pw_set(MQTT_USER, MQTT_PASS)
    client.on_connect = on_connect

    client.connect(MQTT_HOST, MQTT_PORT, keepalive=60)
    client.loop_start()

    try:
        # бесконечный цикл перебора значений
        while True:
            # двойной цикл: перебираем сначала pcf_0x21, внутри него pcf_0x20
            for v21 in range(PCF_21_MIN, PCF_21_MAX + 1):
                # установить значение number.pcf_0x21
                client.publish(TOPIC_PCF_21, payload=str(v21), qos=0, retain=False)
                print(f"Set pcf_0x21 = {v21}")
                time.sleep(DELAY)

                for v20 in range(PCF_20_MIN, PCF_20_MAX + 1):
                    # установить значение number.pcf_0x20
                    client.publish(TOPIC_PCF_20, payload=str(v20), qos=0, retain=False)
                    print(f"   Set pcf_0x20 = {v20}")
                    time.sleep(DELAY)

    except KeyboardInterrupt:
        print("Interrupted by user")

    finally:
        client.loop_stop()
        client.disconnect()


if __name__ == "__main__":
    main()