Skip to content

Home Information - Your home, your data, organized.

Python

Added simulated API endpoints and simple "starter" response objects.

Anthony Cassandrade297c50ddd6
diff --git a/src/hi/simulator/services/hass/api/transient_models.py b/src/hi/simulator/services/hass/api/transient_models.py
new file mode 100644
index 00000000..b29bbce1
--- /dev/null
+++ b/src/hi/simulator/services/hass/api/transient_models.py
@@ -0,0 +1,84 @@
+import base64
+from dataclasses import dataclass, field
+from datetime import datetime
+import os
+import time
+from typing import Dict, List
+
+import hi.apps.common.datetimeproxy as datetimeproxy
+
+
+@dataclass
+class HassEntity:
+
+ entity_id : str
+ last_changed : datetime
+ last_reported : datetime
+ last_updated : datetime
+ state : str = "unknown"
+ attributes : Dict[ str, object ] = field( default_factory = dict )
+ context : Dict[ str, object ] = field( default_factory = dict )
+
+ def __post_init__(self):
+ self.context['id'] = self.generate_ksuid()
+ self.context['parent_id'] = None
+ self.context['user_id'] = None
+ return
+
+ def generate_ksuid(self):
+ timestamp = int(time.time()).to_bytes(4, 'big')
+ random_data = os.urandom(16)
+ raw_ksuid = timestamp + random_data
+ return base64.b64encode(raw_ksuid).decode('utf-8').replace('=', '').replace('/', '').replace('+', '')
+
+ def to_api_dict(self):
+ return {
+ 'attributes': self.attributes,
+ 'context': self.context,
+ 'entity_id': self.entity_id,
+ 'last_changed': self.last_changed,
+ 'last_reported': self.last_reported,
+ 'last_updated': self.last_updated,
+ 'state' : self.state,
+ }
+
+
+@dataclass
+class HassDevice:
+
+ friendly_name : str
+
+ def to_api_list(self) -> List[ HassEntity ]:
+ raise NotImplementedError('Subclasses must override this.')
+
+
+@dataclass
+class HassInsteonDevice( HassDevice ):
+
+ insteon_address : str
+
+
+@dataclass
+class HassInsteonLightSwitch( HassInsteonDevice ):
+
+ def entity_list(self):
+ dummy_datetime_iso = datetimeproxy.now().isoformat()
+
+ hass_entity = HassEntity(
+ entity_id = 'light.switchlinc_relay_%s' % self.insteon_address.replace( '.', '_' ),
+ attributes = {
+ 'color_mode': 'onoff',
+ 'friendly_name': self.friendly_name,
+ 'supported_color_modes': [
+ 'onoff',
+ ],
+ 'supported_features': 0,
+ },
+ last_changed = dummy_datetime_iso,
+ last_reported = dummy_datetime_iso,
+ last_updated = dummy_datetime_iso,
+ )
+ return [ hass_entity ]
+
+ def to_api_list(self):
+ return [ x.to_api_dict() for x in self.entity_list() ]
diff --git a/src/hi/simulator/services/hass/api/views.py b/src/hi/simulator/services/hass/api/views.py
index c0376df8..3880babd 100644
--- a/src/hi/simulator/services/hass/api/views.py
+++ b/src/hi/simulator/services/hass/api/views.py
@@ -1,11 +1,18 @@
from django.http import JsonResponse
from django.views.generic import View
+from .transient_models import HassInsteonLightSwitch
+
class StatesView( View ):
def get(self, request, *args, **kwargs):
- pass
+
+ hass_device = HassInsteonLightSwitch(
+ friendly_name = 'Kitchen Light',
+ insteon_address = 'F0.65.D2',
+ )
+ return JsonResponse( hass_device.to_api_list(), safe = False )
def post(self, request, *args, **kwargs):
pass
diff --git a/src/hi/simulator/services/zoneminder/api/transient_models.py b/src/hi/simulator/services/zoneminder/api/transient_models.py
new file mode 100644
index 00000000..131a64f6
--- /dev/null
+++ b/src/hi/simulator/services/zoneminder/api/transient_models.py
@@ -0,0 +1,255 @@
+from dataclasses import dataclass
+from datetime import datetime
+from typing import List
+
+import hi.apps.common.datetimeproxy as datetimeproxy
+
+
+@dataclass
+class ZmMonitor:
+
+ id : int
+ name : str
+ status : str = 'Connected'
+ type : str = 'Remote'
+ function : str = 'Modect'
+ protocol : str = 'rtsp'
+ method : str = 'rtpRtsp'
+ host : str = '192.168.100.204'
+ port : str = '554'
+ path : str = 'live3.sdp'
+ width : str = '1280'
+ height : str = '800'
+ orientation : str = 'ROTATE_0'
+
+ def to_api_dict(self):
+ return {
+ 'Monitor': {
+ 'Id': str(self.id),
+ 'Name': self.name,
+ 'Notes': '',
+ 'ServerId': '0',
+ 'StorageId': '0',
+ 'Type': self.type,
+ 'Function': self.function,
+ 'Enabled': '1',
+ 'LinkedMonitors': None,
+ 'Triggers': '',
+ 'Device': '',
+ 'Channel': '0',
+ 'Format': '0',
+ 'V4LMultiBuffer': None,
+ 'V4LCapturesPerFrame': '1',
+ 'Protocol': self.protocol,
+ 'Method': self.method,
+ 'Host': self.host,
+ 'Port': self.port,
+ 'SubPath': '',
+ 'Path': self.path,
+ 'Options': None,
+ 'User': None,
+ 'Pass': None,
+ 'Width': self.width,
+ 'Height': self.height,
+ 'Colours': '3',
+ 'Palette': '0',
+ 'Orientation': self.orientation,
+ 'Deinterlacing': '0',
+ 'DecoderHWAccelName': None,
+ 'DecoderHWAccelDevice': None,
+ 'SaveJPEGs': '3',
+ 'VideoWriter': '0',
+ 'OutputCodec': None,
+ 'OutputContainer': None,
+ 'EncoderParameters': '# Lines beginning with # are a comment \r\n# For changing quality, use the crf option\r\n# 1 is best, 51 is worst quality\r\n#crf=23',
+ 'RecordAudio': '0',
+ 'RTSPDescribe': False,
+ 'Brightness': '-1',
+ 'Contrast': '-1',
+ 'Hue': '-1',
+ 'Colour': '-1',
+ 'EventPrefix': 'Event-',
+ 'LabelFormat': '%N - %d/%m/%y %H:%M:%S',
+ 'LabelX': '0',
+ 'LabelY': '0',
+ 'LabelSize': '1',
+ 'ImageBufferCount': '20',
+ 'WarmupCount': '0',
+ 'PreEventCount': '5',
+ 'PostEventCount': '15',
+ 'StreamReplayBuffer': '0',
+ 'AlarmFrameCount': '3',
+ 'SectionLength': '600',
+ 'MinSectionLength': '10',
+ 'FrameSkip': '0',
+ 'MotionFrameSkip': '0',
+ 'AnalysisFPSLimit': '5.00',
+ 'AnalysisUpdateDelay': '0',
+ 'MaxFPS': None,
+ 'AlarmMaxFPS': None,
+ 'FPSReportInterval': '100',
+ 'RefBlendPerc': '6',
+ 'AlarmRefBlendPerc': '6',
+ 'Controllable': '0',
+ 'ControlId': None,
+ 'ControlDevice': None,
+ 'ControlAddress': None,
+ 'AutoStopTimeout': None,
+ 'TrackMotion': '0',
+ 'TrackDelay': None,
+ 'ReturnLocation': '-1',
+ 'ReturnDelay': None,
+ 'DefaultRate': '100',
+ 'DefaultScale': '100',
+ 'DefaultCodec': 'auto',
+ 'SignalCheckPoints': '0',
+ 'SignalCheckColour': '#0000BE',
+ 'WebColour': '#ec3688',
+ 'Exif': False,
+ 'Sequence': '1',
+ 'TotalEvents': '61',
+ 'TotalEventDiskSpace': '628452202',
+ 'HourEvents': '0',
+ 'HourEventDiskSpace': '0',
+ 'DayEvents': '1',
+ 'DayEventDiskSpace': '10711988',
+ 'WeekEvents': '9',
+ 'WeekEventDiskSpace': '99347346',
+ 'MonthEvents': '61',
+ 'MonthEventDiskSpace': '628452202',
+ 'ArchivedEvents': '0',
+ 'ArchivedEventDiskSpace': None,
+ 'ZoneCount': '5',
+ 'Refresh': None,
+ },
+ 'Monitor_Status': {
+ 'MonitorId': str(self.id),
+ 'Status': self.status,
+ 'CaptureFPS': '5.00',
+ 'AnalysisFPS': '5.00',
+ 'CaptureBandwidth': '159047',
+ }
+ }
+
+
+@dataclass
+class ZmStateDefinition:
+
+ monitor_id : int
+ monitor_function : str
+
+ def to_api_str(self):
+ return f'{self.monitor_id}:{self.monitor_function}:1'
+
+
+@dataclass
+class ZmState:
+
+ id : int
+ name : str
+ definition_list : List[ ZmStateDefinition ]
+ is_active : bool
+
+ def to_api_dict(self):
+ if self.is_active:
+ is_active_str = '1'
+ else:
+ is_active_str = '0'
+ return {
+ 'State': {
+ 'Id': str(self.id),
+ 'Name': self.name,
+ 'Definition': ','.join([ x.to_api_str() for x in self.definition_list ]),
+ 'IsActive': is_active_str,
+ },
+ }
+
+
+@dataclass
+class ZmEvent:
+
+ zm_monitor : ZmMonitor
+ event_id : int
+ start_datetime : datetime
+ end_datetime : datetime
+ name : str
+ cause : str
+ length_secs : float
+ total_frames : int
+ alarm_frames : int
+ total_score : int
+ average_score : int
+ max_score : int
+
+ def to_api_dict(self):
+ start_datetime_str = self.start_datetime.strftime('%Y-%m-%d %H:%M:%S')
+ if self.end_datetime:
+ end_datetime_str = self.end_datetime.strftime('%Y-%m-%d %H:%M:%S')
+ else:
+ end_datetime_str = None
+ date_str = datetimeproxy.to_date_str( self.start_datetime )
+ return {
+ 'Event': {
+ 'Id': str(self.event_id),
+ 'MonitorId': str(self.zm_monitor.id),
+ 'StorageId': '0',
+ 'SecondaryStorageId': '0',
+ 'Name': 'Event- 11091',
+ 'Cause': 'Forced Web',
+ 'StartTime': start_datetime_str,
+ 'EndTime': end_datetime_str,
+ 'Width': self.zm_monitor.width,
+ 'Height': self.zm_monitor.height,
+ 'Length': f'{self.length_secs:.2}',
+ 'Frames': str(self.total_frames),
+ 'AlarmFrames': str(self.alarm_frames),
+ 'DefaultVideo': '',
+ 'SaveJPEGs': '3',
+ 'TotScore': str(self.total_score),
+ 'AvgScore': str(self.average_score),
+ 'MaxScore': str(self.max_score),
+ 'Archived': '0',
+ 'Videoed': '0',
+ 'Uploaded': '0',
+ 'Emailed': '0',
+ 'Messaged': '0',
+ 'Executed': '0',
+ 'Notes': f'{self.cause}: ',
+ 'StateId': '2',
+ 'Orientation': self.zm_monitor.orientation,
+ 'DiskSpace': '27303821',
+ 'Scheme': 'Medium',
+ 'Locked': False,
+ 'MaxScoreFrameId': '577976',
+ 'FileSystemPath': f'/var/cache/zoneminder/events/{self.zm_monitor.id}/{date_str}/{self.event_id}',
+ }
+ }
+
+
+@dataclass
+class ZmPagination:
+
+ page : int
+
+ def to_api_dict(self):
+ return {
+ 'page': self.page,
+ 'current': self.page,
+ 'count': 1,
+ 'prevPage': False,
+ 'nextPage': False,
+ 'pageCount': 1,
+ 'order': {
+ 'Event.StartTime': 'desc'
+ },
+ 'limit': 100,
+ 'options': {
+ 'order': {
+ 'Event.StartTime': 'desc'
+ },
+ 'sort': 'StartTime',
+ 'direction': 'desc'
+ },
+ 'paramType': 'querystring',
+ 'queryScope': None,
+ }
diff --git a/src/hi/simulator/services/zoneminder/api/urls.py b/src/hi/simulator/services/zoneminder/api/urls.py
index c7bcb911..4f481ddc 100644
--- a/src/hi/simulator/services/zoneminder/api/urls.py
+++ b/src/hi/simulator/services/zoneminder/api/urls.py
@@ -4,10 +4,18 @@ from . import views
urlpatterns = [
+ re_path( r'^host/login\.json$',
+ views.HostLoginView.as_view(),
+ name = 'zm_api_host_login' ),
+
+ re_path( r'^host/getVersion\.json$',
+ views.HostVersionView.as_view(),
+ name = 'zm_api_host_version' ),
+
re_path( r'^monitors\.json$',
views.MonitorsView.as_view(),
name = 'zm_api_monitors' ),
-
+
re_path( r'^monitors/(?P<monitor_id>\d+)\.json$',
views.MonitorsView.as_view(),
name = 'zm_api_monitors_set' ),
diff --git a/src/hi/simulator/services/zoneminder/api/views.py b/src/hi/simulator/services/zoneminder/api/views.py
index 37772e15..e4bc0b79 100644
--- a/src/hi/simulator/services/zoneminder/api/views.py
+++ b/src/hi/simulator/services/zoneminder/api/views.py
@@ -1,12 +1,49 @@
+from datetime import timedelta
+
from django.http import JsonResponse
+from django.utils.decorators import method_decorator
+from django.views.decorators.csrf import csrf_exempt
from django.views.generic import View
-
+import hi.apps.common.datetimeproxy as datetimeproxy
+
+from .transient_models import ZmEvent, ZmMonitor, ZmPagination, ZmState
+
+
+@method_decorator(csrf_exempt, name='dispatch')
+class HostLoginView( View ):
+
+ def post(self, request, *args, **kwargs):
+ response_data = {
+ 'credentials': 'auth=f5b9cf48693fe8552503c8ABCD5',
+ 'append_password': 0,
+ 'version': '1.36.12',
+ 'apiversion': '1.0',
+ }
+ return JsonResponse(response_data)
+
+
+@method_decorator(csrf_exempt, name='dispatch')
+class HostVersionView( View ):
+
+ def get(self, request, *args, **kwargs):
+ response_data = {
+ 'version': '1.36.12',
+ }
+ return JsonResponse(response_data)
+
+
class MonitorsView( View ):
def get(self, request, *args, **kwargs):
- pass
-
+ zm_monitor = ZmMonitor(
+ id = 1,
+ name = 'SideCamera',
+ )
+ return JsonResponse({
+ 'monitors': [ zm_monitor.to_api_dict() ],
+ })
+
def post(self, request, *args, **kwargs):
pass
@@ -14,11 +51,49 @@ class MonitorsView( View ):
class StatesView( View ):
def get(self, request, *args, **kwargs):
- pass
+ zm_state = ZmState(
+ id = 1,
+ name = 'default',
+ definition_list = [],
+ is_active = True,
+ )
+ return JsonResponse({
+ 'states': [ zm_state.to_api_dict() ],
+ })
class EventsIndexView( View ):
def get(self, request, *args, **kwargs):
- pass
+ zm_monitor = ZmMonitor(
+ id = 1,
+ name = 'SideCamera',
+ )
+
+ start_ago_secs = 45
+ end_ago_secs = 39
+ start_datetime = datetimeproxy.now() - timedelta( seconds = start_ago_secs )
+ end_datetime = datetimeproxy.now() - timedelta( seconds = end_ago_secs )
+ zm_event = ZmEvent(
+ zm_monitor = zm_monitor,
+ event_id = 1,
+ start_datetime = start_datetime,
+ end_datetime = end_datetime,
+ name = 'Event 1',
+ cause = 'Hardcoded',
+ length_secs = 5.5,
+ total_frames = 15,
+ alarm_frames = 6,
+ total_score = 123,
+ average_score = 85,
+ max_score = 140,
+ )
+ zm_pagination = ZmPagination(
+ page = 1,
+ )
+ return JsonResponse({
+ 'events': [ zm_event.to_api_dict() ],
+ 'pagination': zm_pagination.to_api_dict(),
+
+ })