toucan-2e735c
it seems that the mqtt_connect_auth (maybe also the mqtt_connect) does not reconnect once it loses the connection. for example when the broker (server/service) is restarted. the SUCCESS output of the mqtt_connect_auth always stays TRUE.
 
there is no way for me to check if Im disconnected. I thought about checking for a FALSE on MQTT_SEND, but as long as I am not sending anything, SUCCESS of MQTT_SEND will always be FALSE. means, I never encounter a change.
 
any idiomatic way to handle this? Im using the common practice of using contact/coil MQTT_CONNECTED to connect as long as NC contact MQTT_CONNECTED is false. which works great, except disconnects are not handled at all.
Reply 0 0
toucan-2e735c
Im looking at the implementation of the FB MQTT_CONNECT and I see the following code:
// Call MQTT loop every scan cycle after a successfull connection
if (__GET_VAR(data__->SUCCESS))
{
mqtt_loop();
}
mqtt_loop() will be called whenever SUCCESS is true. the PubSubClient lib at https://github.com/knolleary/pubsubclient/blob/master/src/PubSubClient.cpp#L370 returns true if client is connected or false if not (possible to initiate another process of connecting again).
 
so, does this mean the examples I see with the MQTT_CONNECTED contact/coil is not the idiomatic way?

if (__GET_VAR(data__->CONNECT))
{
// Make sure strings are NULL terminated
__GET_VAR(data__->BROKER).body[__GET_VAR(data__->BROKER).len] = '\0';
uint8_t mqtt_connected = connect_mqtt(__GET_VAR(data__->BROKER).body, __GET_VAR(data__->PORT));
__SET_VAR(data__->,SUCCESS,,mqtt_connected);
}
// Call MQTT loop every scan cycle after a successfull connection
if (__GET_VAR(data__->SUCCESS))
{
mqtt_loop();
}
here you can see that connect_mqtt is always called. shouldnt it be first a check on mqtt_loop, if returns false, try to connect_mqtt()?
Reply 0 0
toucan-2e735c
something like this:
  if (__GET_VAR(data__->CONNECT))
  {
    // Make sure strings are NULL terminated
    __GET_VAR(data__->BROKER).body[__GET_VAR(data__->BROKER).len] = '\0';
    __GET_VAR(data__->USER).body[__GET_VAR(data__->USER).len] = '\0';
    __GET_VAR(data__->PASSWORD).body[__GET_VAR(data__->PASSWORD).len] = '\0';

    uint8_t mqtt_connected = connect_mqtt_auth(__GET_VAR(data__->BROKER).body, __GET_VAR(data__->PORT), __GET_VAR(data__->USER).body, __GET_VAR(data__->PASSWORD).body);
    __SET_VAR(data__->,SUCCESS,,mqtt_connected);
  }

  // Call MQTT loop to check if we are still connected!
  SET_VAR(data__->,CONNECT,mqtt_loop());
 
maybe even better: provide another output leg (eg. called CONNECTED) so one can work with it in LD if it ever becomes FALSE.
Reply 0 0
thiagoralves
Good catch. It seems that the code for the MQTT blocks need to be modified to handle this. If you want to take a look, the Arduino code for the blocks is here and the C runtime counterpart code is here. My suggestion would be to modify the void mqtt_loop() function to actually return an integer informing if MQTT is still connected or not. If it is, then we just need to update the variable inside the CONNECT blocks.
Reply 0 0
thiagoralves
I wrote my response before seeing your other posts. Setting CONNECT to the output of mqtt_loop does not work because CONNECT is an input variable. Its contents will be replaced on the next cycle with whatever the user sent to the block. In fact, the CONNECT input is a trigger from the user to initiate a connection, so any time it is TRUE, the connect API must be called.
 
I haven't checked the MQTT API to verify this, but if mqtt_loop() indeed returns the state of the connection, then maybe the best approach is to update the SUCCESS output (perhaps it would be even better to rename it to CONNECTED) with the return of mqtt_loop(). Then if something happens, the user can catch the FALSE signal on SUCCESS and trigger CONNECT input again.
Reply 0 0
toucan-2e735c
yeah I already updated the code before reading your latest post and basically did the same thing.
 
but it is tricky:
when I stop the broker (and setSocketTimeout being 15 seconds default in the upstream library) the device freezes and nothing works anymore, because the 15 seconds never reach, and every cycle a new CONNECT (which is now true due to the NC contact) freezes again, because a connection init is also set to 15 seconds timeout.
 
basically, once I stop the remote mqtt broker the device freezes. gotta investigate this further. maybe I can come up with a solution to this.
Reply 0 0
thiagoralves
Might be possible that one of the functions you're now calling is a blocking function. Since everything runs sequentially, if any of the calls block, the whole system stops until the call is finished. As I said, I'm not an expert with the MQTT API, so maybe the mqtt_loop() is blocking if the user is not connected, or something else.
Reply 0 0
toucan-2e735c
there is only one solution to all of this.
 
cooperative multitasking 😃
Reply 0 0
thiagoralves
This is not ideal. The runtime is single threaded due to limitations on other platforms. Given the cyclic nature of PLCs, the best scenario is to make non-blocking calls.
Reply 0 0
toucan-2e735c
I've found an MQTT library that is async (https://github.com/marvinroger/async-mqtt-client) but it is only for the esp8266 and esp32. I think this is fine since afaik there are no other boards with wifi capability on the supported list of boards in openplc (https://autonomylogic.com/docs/2-4-physical-addressing/) plus it seems that the code is only supporting ESP boards currently anyway (see code block below). but Im not sure about modbus TCP (EtherClient). this library does not support ethernet.
 
#ifdef MBTCP_ETHERNET
#ifdef BOARD_ESP32
    WiFiClient wifiClient;
#else
    EthernetClient wifiClient;
#endif
#else
    WiFiClient wifiClient;
#endif
 
if you think it's worth giving a shot, I can eventually come up with a PR.
 
waiting for your decision.
Reply 0 0
thiagoralves
There are several WiFi and Ethernet boards on the list of supported devices (Raspberry Pico W, Arduino Nano IoT, just to name a few). The define you mentioned is specific for Ethernet on the ESP32, where it needs to use WifiClient instead of EthernetClient. We need to find a library that works with the Arduino API, so it is not tied to any board type
Reply 0 0
toucan-2e735c
Im not aware of any async MQTT library that is arduino API compatible. which is unfortunate, because it makes the MQTT FB pretty much useless to work with right now. one little wifi disconnect or even worse (crashed mqtt broker) makes the whole PLC freeze.
 
I think a better option would be to remove the MQTT FB and let the user use his own library of choice in the arduino sketch.
that way one can still use PubSubClient.h if needed but can utilize libraries like TaskScheduler.h for cooperative multitasking (to avoid delay(). and, who wants to work with millis() anyway?).
 
in general, it makes no sense to have a blocking library in a PLC runtime that is fundamentally sequential in its nature.
 
because that was my experience with OpenPLC (and Im new to all this). when I discovered this "bug", my initial thought was:
"wait. you wanna tell me the moment the MQTT broker goes down, my whole machinery will stop working?"
 
and hence why I have to ask this: why would you put a blocking call into a PLC runtime? what was the motivation behind it?
Reply 0 0
thiagoralves
and hence why I have to ask this: why would you put a blocking call into a PLC runtime? what was the motivation behind it?
I did not, at least not intentionally. From my tests it was working just fine. Took a quick look at the PubSubClient.cpp code you referenced above and indeed there aren't any blocking calls except connect that can take up to MQTT_CONNECTION_TIMEOUT for an unresponsive server. Ideally, this call should be yielded to avoid blocking on the waiting for connection, but unfortunately that's not how the library implements it. In any case, once it is connected, there are no more blocking calls, so I think it is an affordable pain for Arduino-grade hardware.
 
What I believe is happening in your case is that you're not treating the block response properly, falling into a reconnect loop on your PLC program, freezing the runtime. Ideally, if the SUCCESS becomes false in the middle of a program execution, you should go into an error routine, or something else, like trying to reconnect every 5 minutes, instead of trying to reconnect in a loop. This will give you 15 seconds of block time once, or every now and then. I know it is not ideal, but it is what we have for now.
 
To make it even better, the ideal scenario would be to implement a platform-agnostic multitasking on the runtime. I've been looking at this for a while, but never had the time to implement it. If you want to dive in, you're more than welcome! Main candidates in my opinion are https://github.com/pstolarz/CoopThreads/tree/master and https://gitlab.com/airbornemint/arduino-protothreads . If I were to choose, I would pick Arduino-Protothreads for sure. It is a bit more limited in the sense that you can't keep local variables, but it works very well and has just 2 bytes (yeah, T-W-O bytes) of overhead per thread. CoopThreads is more like a full fledged cooperative multitasking scheduler that works with whatever, but it requires stack size allocation, and I don't like that.
 
If you want to take a look at implementing Arduino-Protothreads on the OpenPLC runtime for the Arduino, I'll be happy to support you with whatever I can. The only catch is that, as I said before, all local variables will have to be accounted for (either make them static or keep track of them before they vanish on a PT_YIELD() call), and that libraries that call delay() will have to be modified to call PT_SLEEP() instead. The code surrounding thread creation and yielding is quite simple. Take a look at https://gitlab.com/airbornemint/arduino-protothreads/-/blob/main/examples/Button/Button.ino?ref_type=heads
Reply 0 0
toucan-2e735c
What I believe is happening in your case is that you're not treating the block response properly, falling into a reconnect loop on your PLC program, freezing the runtime. Ideally, if the SUCCESS becomes false in the middle of a program execution, you should go into an error routine, or something else, like trying to reconnect every 5 minutes,
I worked with local variables TIMEOUT, START_TIME, CURRENT_TIME internally, to keep time. basically a simple millis() equivalent in arduino. but still, once I call mqtt_connect() it is over. it will block until 15 seconds are over. that means, I can't even do timekeeping since it won't let me that far. and so I gave up on the idea and wrote my reply to you.
 
yes, platform-agnostic multitasking is my thought as well. I will check out the links you provided. how many modules/libraries in the openplc editor are we talking about? like I said, I just started with OpenPLC and Im trying to understand the project structure. for example I see redundant files in matiec and editor and it is a bit confusing having to edit multiple files for the same thing.
 
and what is your estimate on this?
Reply 0 0
thiagoralves
Yes, the v3 architecture is a mess, with a bunch of duplicated files. You can forget this for now, especially since everything is being remade for v4. I would say for you to focus on the actual runtime source code here https://github.com/thiagoralves/editor/blob/openplc-master/arduino/examples/Baremetal/Baremetal.ino
 
The runtime source code for the Arduino platform will be moved pretty much unchanged to v4, so your modifications there to include some cooperative multitasking will benefit both v3 and v4. I would begin by simply including the arduino-protothreads library and changing the scheduler to actually call all threads instead of just cycling between them. This will probably not give you any benefit at first, because the code that runs on each "thread" does not call PT_YIELD() or PT_SLEEP(). So the threads will be running until completion the same way they were before. Next step is to find evident delays or sleep areas in the code that can be replaced with PT_YIELD() or PT_SLEEP(). I don't think there are many in the runtime source code. Finally, for this particular problem you're facing, you could modify the PubSub code to actually call PT_SLEEP() in all the delay portions, making it suitable for the protothreads architecture. It would be even better if there was a way to link the arduino API delay() call with PT_SLEEP() somehow.
 
Anyway, those are just brainstorming ideas. Once you start implementing something you'll probably get a better picture of how it can be done.
Reply 0 0
Reply