Does anyone have a working example of using paho MQTT library in Ignition?
In the script console, I can successfully subscribe to a feed and read its value changes.
However, the behavior is unstable. That is, sometimes when I execute the script, sometimes it connects and other times it doesn’t.
Just wanted to see if anyone else has a working example they’d be willing to share.
So far I’ve gotten this to work quite reliably from the script console for subscribing to a feed.
However when I try to put it as a gateway script, the tag does not update like it does when running from the script console. Any clues you can offer are appreciated!
What do you mean by “gateway script”?
Where are you defining it and where are you running it from?
I’m trying to put it as a gateway startup script. Its that exact code but in the gateway events, start up script.
I’m not familiar with the paho API. does
loop_forever() actually block the calling thread and loop forever?
If it does, this isn’t going to be something you can do in a startup script.
What you’re doing is also dangerous because you’re going to leak these client objects every time the project starts and accumulate connected clients.
You’re going to have to store each connected client instance in
system.util.globals() or something like that so that you can try to remove it and shut it down in a shutdown script.
You’ll also need to at least run
client.loop_forever() inside a
system.util.invokeAsync call so you don’t block your project from starting up.
@pturmel probably has some sage advice on the complications of managing python objects like this…
Does it not have any way to gracefully end the loop_forever() ? It isn’t really safe in java to just kill threads, and you must have a mechanism to replace threads whenever the code changes. system.util.getGlobals() provides a reliable place to store a reference to your thread, but there must be a way to interrupt() the infinite loop when new code starts up. (Java has an interrupt mechanism, but it requires cooperation from the target thread.)
If client.disconnect() is called, it will break out of the loop.
Actually for testing, I am trying the below HTTP GET script as a gateway timer. It works perfect in the script console but once I make it a timer script nothing happens and it doesn’t show up in the gateway scripts log section even after saving.
So I think I’m missing a step somewhere…but can’t quite see what.
You can as well define a memory tag that the user sets/resets manually. Check the tag in timer loop, the timer loop will run if the tag is set and client is connected and skip when its reset or client closes. I don’t know your actual problem you are trying to solve, but this will simulate the sript playground condition.
Does anybody know if there’s successful story using paho MQTT library (pretty much a standard MQTT library for python software developers these days) within the ignition’s Gateway Event Scripts?