kiln-controller-max31856/watcher.py

86 wiersze
2.6 KiB
Python
Czysty Zwykły widok Historia

#!/usr/bin/env python
import requests
import json
import time
import datetime
2022-05-22 18:49:21 +00:00
import logging
# this monitors your kiln stats every N seconds
2022-05-22 19:06:38 +00:00
# if X checks fail, an alert is sent to a slack channel
# configure an incoming web hook on the slack channel
# set slack_hook_url to that
2022-05-22 19:06:38 +00:00
logging.basicConfig(level=logging.INFO)
2022-05-22 18:49:21 +00:00
log = logging.getLogger(__name__)
2022-05-22 18:49:21 +00:00
class Watcher(object):
def __init__(self,kiln_url,slack_hook_url,bad_check_limit=6,temp_error_limit=10,sleepfor=10):
self.kiln_url = kiln_url
self.slack_hook_url = slack_hook_url
self.bad_check_limit = bad_check_limit
self.temp_error_limit = temp_error_limit
self.sleepfor = sleepfor
self.bad_checks = 0
self.stats = {}
def get_stats(self):
try:
r = requests.get(self.kiln_url,timeout=1)
return r.json()
except requests.exceptions.Timeout:
log.error("network timeout. check kiln_url and port.")
return {}
except requests.exceptions.ConnectionError:
log.error("network connection error. check kiln_url and port.")
return {}
2022-05-22 18:49:21 +00:00
except:
return {}
def send_alert(self,msg):
2022-05-22 19:06:38 +00:00
log.error("sending alert: %s" % msg)
2022-05-22 18:49:21 +00:00
try:
r = requests.post(self.slack_hook_url, json={'text': msg })
except:
pass
def has_errors(self):
if 'time' not in self.stats:
2022-05-22 19:06:38 +00:00
log.error("no data")
2022-05-22 18:49:21 +00:00
return True
if 'err' in self.stats:
if abs(self.stats['err']) > self.temp_error_limit:
2022-05-22 19:06:38 +00:00
log.error("temp out of whack %0.2f" % self.stats['err'])
2022-05-22 18:49:21 +00:00
return True
return False
def run(self):
2022-05-22 19:06:38 +00:00
log.info("started watching %s" % self.kiln_url)
2022-05-22 18:49:21 +00:00
while(True):
self.stats = self.get_stats()
if self.has_errors():
self.bad_checks = self.bad_checks + 1
else:
2022-07-06 11:43:59 +00:00
try:
log.info("OK temp=%0.2f target=%0.2f error=%0.2f" % (self.stats['ispoint'],self.stats['setpoint'],self.stats['err']))
except:
pass
2022-05-22 18:49:21 +00:00
if self.bad_checks >= self.bad_check_limit:
msg = "error kiln needs help. %s" % json.dumps(self.stats,indent=2, sort_keys=True)
self.send_alert(msg)
self.bad_checks = 0
time.sleep(self.sleepfor)
if __name__ == "__main__":
2022-05-22 18:49:21 +00:00
watcher = Watcher(
2022-05-23 14:21:19 +00:00
kiln_url = "http://192.168.1.84:8081/api/stats",
slack_hook_url = "you must add this",
2022-05-22 18:49:21 +00:00
bad_check_limit = 6,
temp_error_limit = 10,
sleepfor = 10 )
2022-05-22 18:49:21 +00:00
watcher.run()