MQTT intermittent with ESP32-CAM modules

I have two locations where I run ESP32-CAM WiFi modules. The one uses Home Assistant and the other uses Node Red. In both instances Mosquitto is the broker and they both run on Raspberry Pis. I have built a new module and run it without issues on the Node Red set up. When I take it over to the other site, with a different router, it has difficulty connecting to MQTT. This is a different location and router. The software is smart enough to work out which location it is at and sets the username and passwords accordingly. The odd thing is that it works some times. It transfers good data, but then it will go several minutes or hours without connecting to MQTT again. The failure to connect message is always “rc=2”. On closer investigation it appears that some of the other modules also fail to connect but much less frequently. There are 6 of these modules in the system. I’ve tried looking in the HA Mosquitto log but I can’t see anything obvious.
Can someone give me clues of how to investigate this further? I have tried different routers but that has no effect. I have tried the same software in different ESP32-CAM modules but that doesn’t make any difference. I’ve tried cutting back the code to minimum operation and it still does it. Cpuld it be a problem with the Arduino “include files”?
I’m stumped!!