Code: Select all
import syslog
import random
syslog.syslog('Processing started')
error = (random.random() >= 0.5)
if error:
syslog.syslog(syslog.LOG_ERR, 'Processing NOT started')
Code: Select all
#
# George
# georgelza@gmail.com
#
# Lets try our hand at Python
#
from envirophat import weather
import requests
import time
import csv
import httplib, urllib
import logging
import logging.handlers
# constants
URL = 'https://corlysis.com:8086/write'
READING_DATA_PERIOD_MS = 5000.0
SENDING_PERIOD = 2
MAX_LINES_HISTORY = 1000
db="environmental"
token="a99bcfd4xxxxxxxxxxxxx152f"
csvfile = "/home/pi/projects/source/corlysis/temp.csv"
barometric = 0
logger = logging.getLogger('myRead_Barometric_EnviroPhat')
logger.setLevel(logging.INFO)
handler = logging.handlers.SysLogHandler('/dev/log')
formatter = logging.Formatter('Python: { "loggerName":"%(name)s", "message":"%(message)s"}')
handler.formatter = formatter
logger.addHandler(handler)
def main():
corlysis_params = {"db": DB, "u": "token", "p": TOKEN, "precision": "ms"}
payload = ""
counter = 1
problem_counter = 0
# infinite loop
while True:
unix_time_ms = int(time.time()*1000)
timeC = time.strftime("%Y") + "/" + time.strftime("%m") + "/" + time.strftime("%d") + " " + time.strftime(
"%H") + ':' + time.strftime("%M") + ':' + time.strftime('%S')
try:
# read sensor data and convert it to line protocol
barometric = weather.pressure()
barometric = round(barometric, 2)
barometric = barometric / 100
except Exception, e:
# Build up 'data' to be used as a array to write to Syslogd
data = ["Exception, Read weather.pressure: ", e]
# Write message to SysLog
logger.info(data)
#End Try
line = "sensors_data pressure={} {}\n".format(barometric, unix_time_ms)
data = ["Study EnviroPhat", timeC, barometric ]
with open(csvfile, "a") as output:
writer = csv.writer(output, delimiter=",", lineterminator='\n')
writer.writerow(data)
# End with
params = urllib.urlencode({'field3': barometric,'key': 'SFF0xxxxxxx0I4YE'}) # use your API key generated in the thingspeak channels for the value of 'key'
headers = {"Content-typZZe": "application/x-www-form-urlencoded", "Accept": "text/plain"}
conn = httplib.HTTPConnection("api.thingspeak.com:80")
try:
conn.request("POST", "/update", params, headers)
response = conn.getresponse()
print response.status, response.reason
data = response.read()
conn.close()
except Exception, e:
# Build up 'data' to be used as a array to write to Syslogd
data = ["Exception, Post to api.thingspeak: ", e]
# Write message to SysLog
logger.info(data)
#End Try
payload += line
if counter % SENDING_PERIOD == 0:
try:
# try to send data to cloud
r = requests.post(URL, params=corlysis_params, data=payload)
if r.status_code != 204:
raise Exception("data not written")
payload = ""
except Exception, e:
problem_counter += 1
# Build up 'data' to be used as a array to write to Syslogd
data = ["Exception, Cannot write to InfluxDB: ", e]
# Write message to SysLog
logger.info(data)
if problem_counter == MAX_LINES_HISTORY:
problem_counter = 0
payload = ""
# End Try
counter += 1
# wait for selected time
time_diff_ms = int(time.time()*1000) - unix_time_ms
print(time_diff_ms)
if time_diff_ms < READING_DATA_PERIOD_MS:
time.sleep((READING_DATA_PERIOD_MS - time_diff_ms)/1000.0)
if __name__ == "__main__":
main()
DougieLawson wrote: ↑Thu Nov 23, 2017 8:09 amPlease edit your post.
Add [code] at the top
and [/code] at the bottom.
My instinct is that it's somehow getting stuck there as you roll past midnight. Similar to 'Tnext=Tnow+N' where that may lead to a 'Tnext' which can never be an actual time.georgelza wrote: ↑Thu Nov 23, 2017 8:08 amCode: Select all
time_diff_ms = int(time.time()*1000) - unix_time_ms print(time_diff_ms) if time_diff_ms < READING_DATA_PERIOD_MS: time.sleep((READING_DATA_PERIOD_MS - time_diff_ms)/1000.0)
If the exception thrown by a failing network connection is not caught then the script will terminate because python does not know how to recover from an uncaught exception - exceptions must be handled by the programmer
Rhadamanthys wrote: ↑Thu Nov 23, 2017 5:27 pmYour scripts die every midnight on 2 RPis, your router restarts every midnight but you are pretty confident there's no correlation...
Rather than waiting another night to see if the issue moves with restart, what about simply pulling the dsl cable off the router to see how the scripts like the missing internet.
supervisor: I understand it gives up on repeated errors
Rhadamanthys wrote: ↑Thu Nov 23, 2017 5:51 pmJust learned a bit about supervisor.
For debugging, what prevents you from running your script in the Python shell?
Gives you error messages right away without any overhead code for error logging