0

I have a Python script that runs fine on boot to detect the status of a wifi connection and write an HTML IMG tag to file dependent on the script result.

I want this to run "constantly" and I know this can be acheived by using a CRON job but the most frequent running of the script would be 1 min and I would like to know within seconds of the result changing.

I have tried many variations of the bellow code but it dosen't ever seem to run. (I remove the WiFi dongle and it should change. If I remove it and reboot the correct result is displayed.)

PYTHON:

import time, urllib2

def internet_on():
    try:
        response=urllib2.urlopen('http://64.233.160.94',timeout=1)
        return '<img class="right" src="networkon.png" width="32" height="32">'
    except urllib2.URLError as err: pass
    return '<img class="right" src="networkoff.png" width="32" height="32">'

output = internet_on()    
f = open('/var/www/html/viv/wifiout.html', 'w')
print >> f, output
f.close()

time.sleep(1)

while True:
    internet_on()

HTML:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Vivarium Enviroment Control Centre</title>
<link rel="stylesheet" href="style.css">
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script type="text/javascript">
    function updateTime() {
        var currentTime = new Date();
        var hours = currentTime.getHours();
        var minutes = currentTime.getMinutes();
        var seconds = currentTime.getSeconds();
        if (minutes < 10){
            minutes = "0" + minutes;
        }
        if (seconds < 10){
            seconds = "0" + seconds;
        }
        var v = hours + ":" + minutes + ":" + seconds + " ";
        if(hours > 11){
            v+="PM";
        } else {
            v+="AM"
        }
        setTimeout("updateTime()",1000);
        document.getElementById('time').innerHTML=v;
    }

  $("document").ready(function(){
        updateTime();

        setInterval(function(){
          $("#wifi").load('wifiout.html');
        },1000);
      });

function changeStatus() {
    var image = document.getElementById('lightStatus');
    if (image.src.match("lightoff")) {
        image.src = "lighton.png";
    } else {
        image.src = "lightoff.png";
    }
}
</script>
</head>
<body>
<div id="topbar">
    <span id="time"></span>
    <span id="wifi"></span>
    <img id="lightStatus" class="right" onclick="changeStatus()" src="lightoff.png" width="32" height="32">
</div>
</body>
</html>

ERROR THROWN AFTER RUNNING FOR A WHILE APPLYING THE ACCEPTED ANSWER

pi@Vivarium:~ $ sudo python /home/pi/Desktop/wifi.py Traceback (most recent call last): File "/home/pi/Desktop/wifi.py", line 17, in internet_on() File "/home/pi/Desktop/wifi.py", line 8, in internet_on urllib2.urlopen('http://64.233.160.94',timeout=1) File "/usr/lib/python2.7/urllib2.py", line 154, in urlopen return opener.open(url, data, timeout) File "/usr/lib/python2.7/urllib2.py", line 437, in open response = meth(req, response) File "/usr/lib/python2.7/urllib2.py", line 550, in http_response 'http', request, response, code, msg, hdrs) File "/usr/lib/python2.7/urllib2.py", line 469, in error result = self._call_chain(*args) File "/usr/lib/python2.7/urllib2.py", line 409, in _call_chain result = func(*args) File "/usr/lib/python2.7/urllib2.py", line 656, in http_error_302 return self.parent.open(new, timeout=req.timeout) File "/usr/lib/python2.7/urllib2.py", line 437, in open response = meth(req, response) File "/usr/lib/python2.7/urllib2.py", line 550, in http_response 'http', request, response, code, msg, hdrs) File "/usr/lib/python2.7/urllib2.py", line 469, in error result = self._call_chain(*args) File "/usr/lib/python2.7/urllib2.py", line 409, in _call_chain result = func(*args) File "/usr/lib/python2.7/urllib2.py", line 656, in http_error_302 return self.parent.open(new, timeout=req.timeout) File "/usr/lib/python2.7/urllib2.py", line 431, in open response = self._open(req, data) File "/usr/lib/python2.7/urllib2.py", line 449, in _open '_open', req) File "/usr/lib/python2.7/urllib2.py", line 409, in _call_chain result = func(*args) File "/usr/lib/python2.7/urllib2.py", line 1227, in http_open return self.do_open(httplib.HTTPConnection, req) File "/usr/lib/python2.7/urllib2.py", line 1200, in do_open r = h.getresponse(buffering=True) File "/usr/lib/python2.7/httplib.py", line 1073, in getresponse response.begin() File "/usr/lib/python2.7/httplib.py", line 415, in begin version, status, reason = self._read_status() File "/usr/lib/python2.7/httplib.py", line 371, in _read_status line = self.fp.readline(_MAXLINE + 1) File "/usr/lib/python2.7/socket.py", line 476, in readline data = self._sock.recv(self._rbufsize) socket.timeout: timed out

Sauced Apples
  • 1,163
  • 2
  • 14
  • 37
  • Sorry 100% forgot to mention that. I have updated the code to reflect the changes. (In Chrome Inspect I can see the JQuery running every second) – Sauced Apples Apr 04 '16 at 12:53
  • Your while loop never outputs/saves/does anything that would alert you. So far as I see it is likely checking the status but not telling you – Lost Apr 04 '16 at 12:58

3 Answers3

3

I think your problem is that you're not writing the new HTML in the loop, you only write it once when you initially run the script. Try something like this

import time, urllib2

HTML = '<img class="right" src="{}" width="32" height="32">'

def internet_on():

    try:
        urllib2.urlopen('http://64.233.160.94',timeout=1)
        status_image = 'networkon.png'
    except urllib2.URLError as err:
        status_image = 'networkoff.png'

    with open('/var/www/html/viv/wifiout.html', 'w') as f:
        f.write(HTML.format(status_image))

while True:
    internet_on()
    time.sleep(1)
John
  • 13,197
  • 7
  • 51
  • 101
  • Hi, John. I tried this but unfortunately it is not writing the result to the HTML file. – Sauced Apples Apr 04 '16 at 13:12
  • Strange, it's Working on My Computer ® ... any chance it's a permissions issue? Also how is JQuery getting the HTML? Are you serving it out over Apache or something? – John Apr 04 '16 at 13:19
  • It's running on a Raspberry Pi. Possibly a perms issue so I will check that now but I've ran these type of scripts before with no issue on the same setup. – Sauced Apples Apr 04 '16 at 13:21
  • Try running as super user. Are you getting any error? – Chris Apr 04 '16 at 13:24
  • I have it working. It seems to detect the wifi usb being removed almost instantly but is taking ~10/15 secs to notice that it has come back. – Sauced Apples Apr 04 '16 at 13:28
  • @John after a few mins the script is cutting out and if ran through SSH displays errors. Would you have any idea? I have edited my question to show the errors. – Sauced Apples Apr 04 '16 at 14:37
  • iirc `socket.timeout` is an exception, I'm not sure whether it indicates a downed connection in your scenerio or not but you'll probably want to catch it and either continue trying to see if the connection is up or assume that it it down and act accordingly. – John Apr 04 '16 at 15:05
2

Yeah, you're only running the second half of your code (from assigning output to time.sleep(1) the first time, the rest of the time it's passed over because it's not under the function definition. Move all of your code under the function. No need to return anything, just perform it all in the function. Time.sleep(1) is only one second, if you're doing it once per minute make it 60.

import time, urllib2

def internet_on():
    try:
        response=urllib2.urlopen('http://64.233.160.94',timeout=1)
        output = '<img class="right" src="networkon.png" width="32" height="32">'
    except urllib2.URLError as err: pass
    output = '<img class="right" src="networkoff.png" width="32" height="32">'


    f = open('/var/www/html/viv/wifiout.html', 'w')
    print >> f, output
    f.close()
    time.sleep(60)

while True:
    internet_on()
Chris
  • 15,819
  • 3
  • 24
  • 37
0

Try this. Just put the script on autostart and tune the time.sleep in the endless loop.

import time, urllib2

def internet_on():
    try:
        response=urllib2.urlopen('http://64.233.160.94',timeout=10)
        return '<img class="right" src="networkon.png" width="32" height="32">'
    except urllib2.URLError as err:
        return '<img class="right" src="networkoff.png" width="32" height="32">'

output = internet_on()
f = open('/var/www/html/viv/wifiout.html', 'w')
print >> f, output
f.close()


while True:
    time.sleep(30)
    internet_on()
barrenec
  • 1
  • 1