import paho.mqtt.client as mqtt
from django.conf import settings
from .utils import parse_proto
from chat.consumers import send_websocket_message
from django.core.cache import cache
from device_data_op.models import TableXproAllDevinfo


def on_connect(mqtt_client, userdata, flags, rc):
    if rc == 0:
        print('Connected successfully')
        mqtt_client.subscribe(settings.MQTT_SUBSCRIBE_LIST)
    else:
        print('Bad connection. Code:', rc)


def on_message(mqtt_client, userdata, msg):
    # 接收mqtt消息的代码 
    # mqtt_message_received.send(sender=None, message=msg.payload)
    # print(f'Received message on topic: {msg.topic} with payload: {msg.payload}')
    data, device_name = parse_proto(msg.payload)
    # data = msg.payload.decode('utf-8')
    print(f'Received message on topic: {msg.topic} with payload: {data}')
    if len(data) == 0:
        return
    send_message(data, device_name)


def send_message(data: dict, device_name: str):
    """
    发送 websocket 消息
    """
    
    send_websocket_message(data)
    dev_info = TableXproAllDevinfo.objects.filter(dev_name=device_name).first()
    if dev_info is None:
        print('dev_info is None')
        return
    
    if "TCP" in dev_info.comunitate_mode.upper():
        name = dev_info.tcp_port
    elif "UDP" in dev_info.comunitate_mode.upper():
        name = dev_info.udp_port_src
    else:
        return
    send_websocket_message(data, group_name=f'chat_{name}')

    # cmds = data.get('CMDS')
    # if cmds is None:
    #     return
    # if cmds[0] == '$':
    #     send_websocket_message(data, group_name="chat_acu7m5")
    # else:
    #     send_websocket_message(data, group_name="chat_hwf")


client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.username_pw_set(settings.MQTT_USER, settings.MQTT_PASSWORD)
client.connect(
    host=settings.MQTT_SERVER,
    port=settings.MQTT_PORT,
    keepalive=settings.MQTT_KEEPALIVE
)
print('start mqtt')
client.loop_start()
