Stop python script aborting when there is no internet connection

1.6k views Asked by At

I have a python script running on a revPi which uses Azure IOT SDK. The script basically accepts a bunch of modbus registers from a .json file, adds a few properties and sends it to Azure IOT hub for analysis.

The script is currently too dependent on network connection and due to infrastructure limitations, the connectivity is unreliable and often causes the script to die/abort often. How can I make the script to function on this poor internet connection? The main libraries being used are pymodbus and iothub_client.

1

There are 1 answers

4
Madison Courto On BEST ANSWER

As per Checking network connection I'd suggest something like this;

   import urllib2

    if(internet_on())
        CallFunction()
    else
        internet_on()

    def internet_on():
        try:
            urllib2.urlopen('http://216.58.192.142', timeout=1)
            return True
        except urllib2.URLError as err: 
            return False

"216.58.192.142" is a google address but you could use anything reliable such as Azure as this is where you are sending your data.

It may be more sensible to use a while loop or add a thread sleep to stop it checking so often.

Hope this helps.