question on how to proceed with MQTT and Django

I have a django app that saves and displays sensor data from an IoT network. Everything is in sync mode (e.g.: call a sensor via requests, get it’s data, write it into the database).

Now I want to implement sensors which have data that can only be accessed using MQTT.

How would that in general be done in a smart way? I am using huey for timed processes / services but no general asgi implementation. Also the informations regarding the sensors (address, credentials …) is stored in the django database. My sensors should be pulled every minute or so, nothing close to real time or time dependent

I generally see three ways how to do proceed and I hope for some input:

  1. Create a service, that collects the data from MQTT and directly accesed the django database and writes results into it (using postgres, so multiple connections should not be an issue here)
  2. Crate a service that collects the data from MQTT and has its own little database - expose the data using a tiny local API like fastAPI and call it from within django in timed tasks
  3. implement a whole MQTT reader into my django project that starts up with it.

I lean torward 2, but only because I think 1 is messy and 3 is not what django is supposed to handle. Am I missing something? How would ones approach this task?

If I had to do something along these lines (which I have actually), I would write a “listener script” as a custom Django management command. That script would be the MQTT endpoint and be able to save data to the Django database using the ORM. I would then control that script using something like a systems service file, or supervisord or runit.

Yes, I’d do similar to @KenWhitesell suggests as well. A management command run periodically with (say) a systemd timer is simple and straightforward.

This works great. Thanks!

1 Like