Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integrate Paho MQTT with Django

I am doing a project which use Django and MQTT. There is a situation that I want to re-subscribe all topics relating to models in database when my Django web server reconnect to the broker after disconnecting for some reason. I have the model Room as below:

class Room(models.Model):
    building    = models.ForeignKey(Building, on_delete= models.CASCADE)
    number      = models.PositiveIntegerField()
    available   = models.BooleanField(default=True)
    power       = models.BooleanField(default=False)

class Meta:
    ordering = ['building', 'number']
    unique_together = ['building', 'number']

def __str__(self):
    return f"{self.building.bid}/{self.number}"

def get_mqtt_topic(self):
    return f"{self.building.bid}/{self.number}"

The method get_mqtt_topic() will return the MQTT topic associated to the room. MQTT client code mqtt/client.py:

import paho.mqtt.client as mqtt
from .tasks import *
from .models import Room
def on_connect(client, userdata, flags, rc):
   print("Connecting to CloudMQTT broker: "+ mqtt.connack_string(rc))
   room_mqtt = [(room.get_mqtt_topic(), 1) for room in Room.objects.all()]
   client.subscribe(room_mqtt)

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

Because I put the code below in init.py to run mqtt client in a different thread from the django app.

from mqtt.client import client

client.loop_start()

so I got this error: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

like image 611
Q.Nguyen Avatar asked Sep 04 '18 11:09

Q.Nguyen


1 Answers

I have the same error, my provisional solution is to import inside on_connect method.

import paho.mqtt.client as mqtt
from .tasks import *
def on_connect(client, userdata, flags, rc):
    from .models import Room
    print("Connecting to CloudMQTT broker: "+ mqtt.connack_string(rc))
    room_mqtt = [(room.get_mqtt_topic(), 1) for room in Room.objects.all()]
    client.subscribe(room_mqtt)

client = mqtt.Client()
client.on_connect = on_connect
like image 187
Gonzalo Avatar answered Sep 22 '22 03:09

Gonzalo