2

I'm monitoring my sensor data and sending it online with my .py srcipt. It should run every 5min so I programed it like this:

import threading
import time 

def send_wu():

    # Read sensors
    temperature = sensor.read_temperature()
    humidity,t_old = dht.read_retry(dht.DHT22, 4)
    pressure = (sensor.read_pressure()*0.01)+13 # Correct pressure

    # Prevent wrong reading
    while pressure>1030 or pressure<1000:
        pressure=(sensor.read_pressure()*0.01)+13

    def dewpoint_approximation(T,RH):
        Td = (237.7  * gamma(T,RH)) / (17.271 - gamma(T,RH))
        return Td

    def gamma(T,RH):
        g = (17.271 * T / (237.7  + T)) + log(RH/100.0)
        return g


    dewpoint = dewpoint_approximation(temperature,humidity)


    date = "now"

    data = "http://weatherstation.wunderground.com/weatherstation/updateweatherstation.php?ID=IGRADZAGxx&PASSWORD=xxxxxx&dateutc=now&tempf={0:.1f}&baromin={1}&humidity={2}&dewptf={3}&softwaretype=Custom&action=updateraw".format(temperature*1.8+32,pressure*0.0295299830714,humidity,dewpoint*1.8+32)

    response = urllib2.urlopen(data).read()
    print time.strftime("%Y-%m-%d %H:%M:%S")+" Wunderground: "+response


    # Run every 5 min
    threading.Timer(300, send_wu).start()

It works fine for 15-20h but then it stops, here comes the interesting part. When I fire up the putty it restarts the script and runs it again. What's stoping my script from running?

EDIT:

I managed to "catch" the error:

Exception in thread Thread-317:
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 552, in __bootstrap_inner
    self.run()
  File "/usr/lib/python2.7/threading.py", line 760, in run
    self.function(*self.args, **self.kwargs)
  File "meteo_stanica.py", line 181, in posalji_wu
    response = urllib2.urlopen(data).read()
  File "/usr/lib/python2.7/urllib2.py", line 127, in urlopen
    return _opener.open(url, data, timeout)
  File "/usr/lib/python2.7/urllib2.py", line 401, in open
    response = self._open(req, data)
  File "/usr/lib/python2.7/urllib2.py", line 419, in _open
    '_open', req)
  File "/usr/lib/python2.7/urllib2.py", line 379, in _call_chain
    result = func(*args)
  File "/usr/lib/python2.7/urllib2.py", line 1211, in http_open
    return self.do_open(httplib.HTTPConnection, req)
  File "/usr/lib/python2.7/urllib2.py", line 1184, in do_open
    r = h.getresponse(buffering=True)
  File "/usr/lib/python2.7/httplib.py", line 1034, in getresponse
    response.begin()
  File "/usr/lib/python2.7/httplib.py", line 407, in begin
    version, status, reason = self._read_status()
  File "/usr/lib/python2.7/httplib.py", line 365, in _read_status
    line = self.fp.readline()
  File "/usr/lib/python2.7/socket.py", line 447, in readline
    data = self._sock.recv(self._rbufsize)
error: [Errno 110] Connection timed out

So the problem is timed out connection, I added "timeout", in 15-20h we'll see if that helps.

response = urllib2.urlopen(data, timeout=20).read()
  • Do you get any info when it stops? – Boštjan Jerko Jul 3 '15 at 10:24
  • No, on wunderground weather station page just says that PWS is not reporting. – Pas Jul 3 '15 at 10:57
  • Could you post a complete runnable example? it can still be brief, but the given snippet is not enough context. – joan Jul 3 '15 at 11:37
  • @joan I edited the question – Pas Jul 3 '15 at 12:22
  • I'd bet that you have network issues. Try installing watchdog and setting it up to ping your local gateway, or you can just have a script that runs ping (e.g. ping -D -i 300 local.gateway.ip.goes.here). Log the output of the script to a file. See if it fails around the same time you have the issues. – ifermon Jul 6 '15 at 18:31
2

Network connections will fail once in a while. Best thing to do is handle the failure. The following will handle socket errors. At the top of your file, import socket:

import socket

Then, update your code:

response = urllib2.urlopen(data).read()

with the following:

try:
    response = urllib2.urlopen(data).read()
except socket.error, exc:
    print 'socket error {}, skipping data={}'.format(exc[0], data)

As written above, you'll lose this temperature reading, but the script will keep going. You can make it try to post more than once if you want:

for i in range(3):  # try three times
    try:
        response = urllib2.urlopen(data).read()
    except socket.error, exc:
        print 'socket error {}...'.format(exc[0])
    else:
        break  # success, don't retry
else:
    print 'cannot post, skipping data={}'.format(data)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.