I have the same problem I have resorted to pinging my router and if no response, I reboot.
Here is my code. It's a process that reads from a Xbee radio, logs the data and every 10 minutes it Tails the log file and uploads it to my server.
I need to to run unattended 24/365.
The following code runs when the system is started and runs as Root.
For some reason, I think Python kills the network AND ttyUSB0.
The climate monitor runs 24/365 and broadcasts Temp / Humidity every minute.
#! /usr/bin/python3.2
import os
import serial
import time
from ftplib import FTP
import string
import re
ser = serial.Serial('/dev/ttyUSB0',timeout=600)
ser.open()
print("Starting Climate Sensor Logger\n\r")
linectr = 0
while 1:
data = ser.readline()
if (len(data) == 0) :
os.system('reboot -n')
# remove embedded nulls
data = data.translate(None, '\0\n\r')
tm = time.strftime('%x %X %p')
ln = tm + " " + data + "\r\n"
print ln
fo = open("Web.txt","a")
fo.write(ln);
fo.close()
linectr += 1
if linectr > 29:
linectr = 0
# open raw input file and count lines
counter = 0
counter2 = 0
print("Processing Climate measurements")
f = open("Web.txt")
for line in f:
counter += 1
f.close()
# tail 4320 lines (1440 readings)
f = open ("Web.txt")
if counter > 4320:
counter -= 4320
for line in f:
counter2 += 1
if counter2 > counter:
break
# write remainder of file to output with XML header
fo = open ("out.txt","w")
fo.write("<?xml version=""1.0"" encoding=""UTF-8)"" ?>\r")
# clean up lines for Javascript
for line in f:
line = line.replace("\0","")
line = line.replace("\n","")
line = line + "\r"
# write tail 4320 readings
fo.write(line)
f.close()
fo.close()
# Ready to upload to web server
try:
print("Uploading file to web server")
fl = open("Upload.log","a")
ln = "\r\nAttempting Upload at :" + tm + " "
fl.write(ln)
print("Ping Router")
ret = os.system("ping -c 3 -W 1000 192.168.0.1")
if ret != 0:
print "Network is down"
fl.write("Network down, Reboot")
fl.close()
os.system('reboot -n')
print("Network is up")
fl.write("Network OK")
fl.close()
ftp = FTP('pcranwell.com');
ftp.login('userid','password');
file = open('out.txt','rb');
ftp.cwd('public_html/PB/data');
ftp.storbinary('STOR ' + 'Web.txt', open('out.txt', 'rb'));
ftp.close();
print("FTP transfer finished")
except:
print("Transfer Failed")
finally:
print("Continue")
dmesg? How is RPI connected to the network? Via a router? What's in the router's logs? If you re-plug the ethernet cable to RPI, will it bring it back to the network? – abolotnov Feb 25 at 16:00