0

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.

Inception
  • 365
  • 3
  • 21
  • Write a bash script to check the internet connection is available. Also, try to run your python script using the bash script – yogesh10 Sep 19 '18 at 05:38
  • 1
    Sorround the statement or code block in `try: except: Exception, e` to catch the network exceptions and do whatever you want in catch/except section. – Krishna Sep 19 '18 at 05:44

1 Answers1

1

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.

Madison Courto
  • 765
  • 7
  • 20
  • Thank you. I have a main function likewise: `if __name__ == '__main__': test_function()` So would it make sense to put an if condition inside the above if statement and call the main function only if internet is available? – Inception Sep 19 '18 at 07:36
  • if test_function requires the internet connection check then yes. – Madison Courto Sep 19 '18 at 07:40
  • test_function is the main loop which has several network calls in it. Would it make sense to check the internet before each function call is made and proceed only if there is active internet? – Inception Sep 19 '18 at 08:00
  • Yes I’d say so. – Madison Courto Sep 19 '18 at 08:07