Skip to content

Commit

Permalink
Misc changes
Browse files Browse the repository at this point in the history
Added timestamp to last event states
Reconnect to Camect when error reported
Logging changes
  • Loading branch information
FlyingDiver committed Oct 23, 2021
1 parent 4c689db commit d55d391
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 15 deletions.
2 changes: 1 addition & 1 deletion camect.indigoPlugin/Contents/Info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<plist version="1.0">
<dict>
<key>PluginVersion</key>
<string>0.0.7</string>
<string>0.0.8</string>
<key>ServerApiVersion</key>
<string>2.0</string>
<key>IwsApiVersion</key>
Expand Down
5 changes: 5 additions & 0 deletions camect.indigoPlugin/Contents/Server Plugin/Devices.xml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@
<TriggerLabel>Last Event</TriggerLabel>
<ControlPageLabel>Last Event</ControlPageLabel>
</State>
<State id="last_event_time">
<ValueType >String</ValueType>
<TriggerLabel>Last Event Time</TriggerLabel>
<ControlPageLabel>Last Event Time</ControlPageLabel>
</State>
<State id="last_event_type">
<ValueType >String</ValueType>
<TriggerLabel>Last Event Type</TriggerLabel>
Expand Down
17 changes: 10 additions & 7 deletions camect.indigoPlugin/Contents/Server Plugin/camect.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,46 +31,49 @@ def __init__(self, hub_name, hub_devID, address, port, username, password, callb
self._ws_uri = "wss://{}:{}/api/event_ws".format(address, port)

self.authorization = "Basic " + base64.b64encode("{}:{}".format(self.username, self.password).encode()).decode()

self.logger.threaddebug("{}: Camect object initialized, hubID = {}, auth = {}, callback = {}".format(self.hub_name, self.hub_devID, self.authorization, self.callback))

################################################################################
# Minimal Websocket Client
################################################################################

def ws_client():

self.logger.debug("{}: Connecting to '{}'".format(self.hub_name, self._ws_uri))
self.logger.threaddebug("{}: Connecting to '{}'".format(self.hub_name, self._ws_uri))

ws = websocket.WebSocketApp(self._ws_uri, header={'Authorization': self.authorization},
self.ws = websocket.WebSocketApp(self._ws_uri, header={'Authorization': self.authorization},
on_message = on_message,
on_error = on_error,
on_close = on_close,
on_open = on_open)

ws.run_forever(ping_interval=5, sslopt={"cert_reqs": ssl.CERT_NONE, "check_hostname": False})
self.ws.run_forever(ping_interval=5, sslopt={"cert_reqs": ssl.CERT_NONE, "check_hostname": False})

def on_message(ws, message):
self.logger.threaddebug("{}: websocket on_message: {}".format(self.hub_name, message))
self.callback({"name": self.hub_name, "devID": self.hub_devID, "event": "message", "message": message})

def on_error(ws, error):
self.logger.debug("{}: websocket on_error: {}".format(self.hub_name, error))
self.logger.threaddebug("{}: websocket on_error: {}".format(self.hub_name, error))
self.callback({"name": self.hub_name, "devID": self.hub_devID, "event": "error", "error": error})

def on_open(ws):
self.logger.debug("{}: websocket on_open".format(self.hub_name))
self.logger.threaddebug("{}: websocket on_open".format(self.hub_name))
self.callback({"name": self.hub_name, "devID": self.hub_devID, "event": "status", "status": "Connected"})

def on_close(ws):
self.logger.debug("{}: websocket on_close".format(self.hub_name))
self.logger.threaddebug("{}: websocket on_close".format(self.hub_name))
self.callback({"name": self.hub_name, "devID": self.hub_devID, "event": "status", "status": "Disconnected"})

################################################################################

# start up the websocket receiver thread

self.logger.debug("{}: Starting websocket thread".format(self.hub_name))
self.logger.threaddebug("{}: Starting websocket thread".format(self.hub_name))
self.thread = threading.Thread(target=ws_client).start()

self.callback({"name": self.hub_name, "devID": self.hub_devID, "event": "status", "status": "Created"})

def __del__(self):
self.ws.close()
Expand Down
20 changes: 13 additions & 7 deletions camect.indigoPlugin/Contents/Server Plugin/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@
# -*- coding: utf-8 -*-
####################

TS_FORMAT = "%Y-%m-%d %H:%M:%S"

import logging
import indigo
import json
import time
from datetime import datetime, date, time

import requests
requests.packages.urllib3.disable_warnings(requests.packages.urllib3.exceptions.InsecureRequestWarning)
Expand Down Expand Up @@ -102,7 +104,11 @@ def deviceStopComm(self, device):


def callBack(self, info):
self.logger.theaddebug(u"{}: callBack device: {}, type: {}, info: {}".format(info["name"], info["devID"], info["event"], info))
if not info:
self.logger.warning(u"Camect callBack info is None")
return

self.logger.threaddebug(u"Camect callBack info: {}".format(info))
device = indigo.devices[info['devID']]

if info['event'] == 'status':
Expand All @@ -111,8 +117,10 @@ def callBack(self, info):
return

elif info['event'] == 'error':
self.logger.debug(u"{}: Camect Error: {}".format(device.name, info['error']))
device.updateStateOnServer(key="status", value=info['error'])
self.logger.warning(u"{}: Restarting Device, error: {}".format(device.name, info['error']))
indigo.device.enable(device.id, value=False)
self.sleep(2)
indigo.device.enable(device.id, value=True)
return

elif info['event'] != 'message':
Expand All @@ -128,6 +136,7 @@ def callBack(self, info):

key_value_list = [
{'key':'last_event', 'value':info['message']},
{'key':'last_event_time', 'value':datetime.now().strftime(TS_FORMAT)},
{'key':'last_event_type', 'value':event['type']}
]
device.updateStatesOnServer(key_value_list)
Expand Down Expand Up @@ -277,19 +286,16 @@ def snapshotCameraCommand(self, pluginAction):
if not snapshotName or (len(snapshotName) == 0):
snapshotName = "snapshot-{}".format(camera['id'])

start = time.time()
self.logger.debug(u"{}: snapshotCameraCommand, camera: {} ({})".format(camect.name, camera['name'], camera['id']))

image = self.camects[camectID].snapshot_camera(camera['id'], camera['width'], camera['height'])
self.logger.debug(u"{}: snapshotCameraCommand fetch completed @ {}".format(camect.name, (time.time() - start)))
savepath = "{}/{}/{}.jpg".format(indigo.server.getInstallFolderPath(), snapshotPath, snapshotName)
try:
f = open(savepath, 'wb')
f.write(image)
f.close
except Exception as err:
self.logger.warning(u"Error writing image file: {}, err: {}".format(savepath, err))
self.logger.debug(u"{}: snapshotCameraCommand write completed @ {} to {}".format(camect.name, (time.time() - start), savepath))


def disableAlertsCommand(self, pluginAction):
Expand Down

0 comments on commit d55d391

Please sign in to comment.