import paho.mqtt.client as mqtt
from django.conf import settings
from .utils import parse_proto
from .signals import mqtt_message_received


# *******************************************************
from channels.layers import get_channel_layer, channel_layers
from asgiref.sync import async_to_sync

def send_websocket_message(message):
    channel_layer = get_channel_layer()
    async_to_sync(channel_layer.group_send)(
        "chat_mqtt",
        {"type": "chat.message", "message": message}
    )

# *******************************************************

def on_connect(mqtt_client, userdata, flags, rc):
    if rc == 0:
        print('Connected successfully')
        mqtt_client.subscribe('django/mqtt')
    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 = parse_proto(msg.payload)
    data = msg.payload
    send_websocket_message(data)


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()