added alarm to httpsensor on timeout

This commit is contained in:
avollkopf 2023-01-22 16:37:10 +01:00
parent 4ddc9690ef
commit 47e3bcb529
13 changed files with 42 additions and 21 deletions

View file

@ -1,3 +1,3 @@
__version__ = "4.1.0.rc2" __version__ = "4.1.0.rc3"
__codename__ = "Groundhog Day" __codename__ = "Groundhog Day"

View file

@ -34,7 +34,7 @@ class DashboardController:
return {'elements': [], 'pathes': []} return {'elements': [], 'pathes': []}
async def add_content(self, dashboard_id, data): async def add_content(self, dashboard_id, data):
print(data) #print(data)
self.path = self.cbpi.config_folder.get_dashboard_path("cbpi_dashboard_" + str(dashboard_id)+ ".json") self.path = self.cbpi.config_folder.get_dashboard_path("cbpi_dashboard_" + str(dashboard_id)+ ".json")
with open(self.path, 'w') as outfile: with open(self.path, 'w') as outfile:
json.dump(data, outfile, indent=4, sort_keys=True) json.dump(data, outfile, indent=4, sort_keys=True)

View file

@ -45,7 +45,7 @@ class NotificationController:
async def _call_listener(self, title, message, type, action): async def _call_listener(self, title, message, type, action):
for id, method in self.listener.items(): for id, method in self.listener.items():
print(id, method) #print(id, method)
asyncio.create_task(method(self.cbpi, title, message, type, action )) asyncio.create_task(method(self.cbpi, title, message, type, action ))

View file

@ -40,7 +40,6 @@ class SatelliteController:
#not sure if required like done in the old routine #not sure if required like done in the old routine
async def cancel_tasks(tasks): async def cancel_tasks(tasks):
for task in tasks: for task in tasks:
print("3232")
if task.done(): if task.done():
continue continue
task.cancel() task.cancel()

View file

@ -2,19 +2,34 @@
import asyncio import asyncio
from aiohttp import web from aiohttp import web
from cbpi.api import * from cbpi.api import *
import time
import re import re
import random import logging
from cbpi.api.dataclasses import NotificationAction, NotificationType
cache = {} cache = {}
@parameters([Property.Text(label="Key", configurable=True, description="Http Key")]) @parameters([Property.Text(label="Key", configurable=True, description="Http Key"),
Property.Number(label="Timeout", configurable="True",unit="sec",description="Timeout in seconds to send notification (default:60)")
])
class HTTPSensor(CBPiSensor): class HTTPSensor(CBPiSensor):
def __init__(self, cbpi, id, props): def __init__(self, cbpi, id, props):
super(HTTPSensor, self).__init__(cbpi, id, props) super(HTTPSensor, self).__init__(cbpi, id, props)
self.running = True self.running = True
self.value = 0 self.value = 0
self.timeout=int(self.props.get("Timeout", 60))
self.starttime = time.time()
self.notificationsend = False
self.nextchecktime=self.starttime+self.timeout
async def Confirm(self, **kwargs):
self.nextchecktime = time.time() + self.timeout
self.notificationsend = False
pass
async def message(self):
self.cbpi.notify("HTTPSensor Timeout", "Sensor " + str(self.id) + " did not respond", NotificationType.WARNING, action=[NotificationAction("OK", self.Confirm)])
pass
async def run(self): async def run(self):
''' '''
@ -22,12 +37,19 @@ class HTTPSensor(CBPiSensor):
In this example the code is executed every second In this example the code is executed every second
''' '''
while self.running is True: while self.running is True:
currenttime=time.time()
if currenttime > self.nextchecktime and self.notificationsend == False:
await self.message()
self.notificationsend=True
try: try:
cache_value = cache.pop(self.props.get("Key"), None) cache_value = cache.pop(self.props.get("Key"), None)
if cache_value is not None: if cache_value is not None:
self.value = float(cache_value) self.value = float(cache_value)
self.push_update(self.value) self.push_update(self.value)
self.nextchecktime = currenttime + self.timeout
self.notificationsend = False
except Exception as e: except Exception as e:
logging.error(e)
pass pass
await asyncio.sleep(1) await asyncio.sleep(1)

View file

@ -247,7 +247,7 @@ class ActorHttpEndpoints():
""" """
actor_id = request.match_info['id'] actor_id = request.match_info['id']
data = await request.json() data = await request.json()
print(data) #print(data)
await self.controller.call_action(actor_id, data.get("action"), data.get("parameter")) await self.controller.call_action(actor_id, data.get("action"), data.get("parameter"))
return web.Response(status=204) return web.Response(status=204)

View file

@ -69,7 +69,7 @@ class DashBoardHttpEndpoints:
data = await request.json() data = await request.json()
dashboard_id = int(request.match_info['id']) dashboard_id = int(request.match_info['id'])
await self.cbpi.dashboard.add_content(dashboard_id, data) await self.cbpi.dashboard.add_content(dashboard_id, data)
print("##### SAVE") #print("##### SAVE")
return web.Response(status=204) return web.Response(status=204)
@request_mapping(path="/{id:\d+}/content", method="DELETE", auth_required=False) @request_mapping(path="/{id:\d+}/content", method="DELETE", auth_required=False)

View file

@ -58,7 +58,7 @@ class FermenterRecipeHttpEndpoints():
description: successful operation description: successful operation
""" """
data = await request.json() data = await request.json()
print(data) #print(data)
return web.json_response(dict(id=await self.controller.create(data.get("name")))) return web.json_response(dict(id=await self.controller.create(data.get("name"))))
@ -90,7 +90,7 @@ class FermenterRecipeHttpEndpoints():
data = await request.json() data = await request.json()
name = request.match_info['name'] name = request.match_info['name']
await self.controller.save(name, data) await self.controller.save(name, data)
print(data) #print(data)
return web.Response(status=204) return web.Response(status=204)
@request_mapping(path="/{name}", method="DELETE", auth_required=False) @request_mapping(path="/{name}", method="DELETE", auth_required=False)

View file

@ -239,7 +239,7 @@ class LogHttpEndpoints:
data = await request.json() data = await request.json()
result = await self.cbpi.log.get_data(data) result = await self.cbpi.log.get_data(data)
print("JSON") #print("JSON")
print(json.dumps(result, cls=ComplexEncoder)) #print(json.dumps(result, cls=ComplexEncoder))
print("JSON----") #print("JSON----")
return web.json_response(result, dumps=json_dumps) return web.json_response(result, dumps=json_dumps)

View file

@ -35,6 +35,6 @@ class NotificationHttpEndpoints:
notification_id = request.match_info['id'] notification_id = request.match_info['id']
action_id = request.match_info['action_id'] action_id = request.match_info['action_id']
print(notification_id, action_id) #print(notification_id, action_id)
self.cbpi.notification.notify_callback(notification_id, action_id) self.cbpi.notification.notify_callback(notification_id, action_id)
return web.Response(status=204) return web.Response(status=204)

View file

@ -57,7 +57,7 @@ class RecipeHttpEndpoints():
description: successful operation description: successful operation
""" """
data = await request.json() data = await request.json()
print(data) #print(data)
return web.json_response(dict(id=await self.controller.create(data.get("name")))) return web.json_response(dict(id=await self.controller.create(data.get("name"))))
@ -89,7 +89,7 @@ class RecipeHttpEndpoints():
data = await request.json() data = await request.json()
name = request.match_info['name'] name = request.match_info['name']
await self.controller.save(name, data) await self.controller.save(name, data)
print(data) #print(data)
return web.Response(status=204) return web.Response(status=204)
@request_mapping(path="/{name}", method="DELETE", auth_required=False) @request_mapping(path="/{name}", method="DELETE", auth_required=False)

View file

@ -224,7 +224,7 @@ class SensorHttpEndpoints():
""" """
sensor_id = request.match_info['id'] sensor_id = request.match_info['id']
data = await request.json() data = await request.json()
print(data) #print(data)
await self.controller.call_action(sensor_id, data.get("action"), data.get("parameter")) await self.controller.call_action(sensor_id, data.get("action"), data.get("parameter"))
return web.Response(status=204) return web.Response(status=204)

View file

@ -13,10 +13,10 @@ class ComplexEncoder(JSONEncoder):
elif isinstance(obj, datetime.datetime): elif isinstance(obj, datetime.datetime):
return obj.__str__() return obj.__str__()
elif isinstance(obj, Timestamp): elif isinstance(obj, Timestamp):
print("TIMe") #print("TIMe")
return obj.__str__() return obj.__str__()
else: else:
print(type(obj)) #print(type(obj))
raise TypeError() raise TypeError()
except Exception as e: except Exception as e: