Python plugin: Unifi Video from Ubiquiti

Python and python framework

Moderator: leecollings

Post Reply
gysmo38
Posts: 50
Joined: Saturday 01 February 2014 13:42
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

Python plugin: Unifi Video from Ubiquiti

Post by gysmo38 »

Hello,

I made a plugin to activate or deactivate motion record from Domoticz.

You need to have a Unifi server and activate API access from user information.

In attachements to zip files for cam logo.

Code: Select all

# UnifiVideo Plugin
# Author:     Gysmo, 2017
# Version: 0.1
#   
# v0.1 : Initial release
"""
<plugin key="UVC" version="0.1" name="UVC_Plugin" author="gysmo" wikilink="http://www.domoticz.com/wiki/Plugins/UnifiVideo.html" externallink="http://video.ubnt.com">
    <params>
		<param field="Address" label="IP Address" width="200px" required="true" />
        <param field="Port" label="Port" width="200px" required="true" default="7080" />
		<param field="Mode1" label="APIKey" width="200px" required="true" />
		<param field="Mode6" label="Debug" width="75px">
            <options>
                <option label="True" value="Debug"/>
                <option label="False" value="Normal"  default="true" />
            </options>
        </param>
    </params>
</plugin>
"""
import Domoticz
import time
import base64
import json
from urllib.parse import urlencode
from urllib.request import Request, urlopen, HTTPError

unifiCameras = []

class BasePlugin:
	enabled = False
	def __init__(self):
		#self.var = 123
		return

	def onStart(self):
		Domoticz.Log("onStart called")
		if ("myPlugin"     not in Images):
			Domoticz.Image('cam_g3.zip').Create()
		if ("myPluginAlt1" not in Images):
			Domoticz.Image('cam_g3_dome.zip').Create()
		if Parameters["Mode6"] == "Debug":
			Domoticz.Debugging(1)
		self.unifiInitInfos()
		if (len(Devices) == 0):
			# Create Camera motion switch
			for cam in unifiCameras:
				Domoticz.Log("Creating camera " + cam['name'])
				OptionsMode = {"LevelActions": "|","LevelNames": "Off|Record on motion","LevelOffHidden": "false","SelectorStyle": "1"}
				if (cam['model'] == 'UVC G3'):
					model = 'UVC'
				elif (cam['model'] == 'UVC G3 Dome'):
					model = 'UVCDome'
				Domoticz.Device(Name=cam['name'], Unit=cam['dom_id'], TypeName="Selector Switch", Image=Images[model].ID, Options=OptionsMode, Used=1).Create()

	def onStop(self):
		Domoticz.Log("onStop called")

	def onConnect(self, Status, Description):
		Domoticz.Log("onConnect called")

	def onMessage(self, Data, Status, Extra):
		Domoticz.Log("onMessage called")

	def onCommand(self, Unit, Command, Level, Hue):
		Domoticz.Log("onCommand called for Unit " + str(Unit) + ": Parameter '" + str(Command) + "', Level: " + str(Level))
		if (Level == 0):
			self.unifiSetRecording("Off",Unit)
			Devices[Unit].Update(0, str(0))
		elif (Level == 10):
			self.unifiSetRecording("Motion",Unit)
			Devices[Unit].Update(1, str(10))


	def onNotification(self, Name, Subject, Text, Status, Priority, Sound, ImageFile):
		Domoticz.Log("Notification: " + Name + "," + Subject + "," + Text + "," + Status + "," + str(Priority) + "," + Sound + "," + ImageFile)

	def onDisconnect(self):
		Domoticz.Log("onDisconnect called")

	def onHeartbeat(self):
		Domoticz.Log("onHeartbeat called")

# Function define for script
	def unifiSetRecording(self,mode,domID):
		camID = ""
		for cam in unifiCameras:
			if (cam['dom_id'] == domID):
				camID = cam['unifi_id']
				name = cam['name']
		url = "http://"+Parameters["Address"]+":"+Parameters["Port"]+"/api/2.0/camera/"+camID+"?apiKey="+Parameters["Mode1"]
		headers = {'Content-Type': 'application/json'}
		if (mode == "Off"):
			post_fields = bytes('{"name":"'+name+'","recordingSettings":{"motionRecordEnabled":"false"}}','utf-8')
		elif (mode == "Motion"):
			post_fields = bytes('{"name":"'+name+'","recordingSettings":{"motionRecordEnabled":"true","channel":"0"}}','utf-8')
		request = Request(url=url,data=post_fields,headers=headers,method='PUT')
		try:
			nvrResponse = urlopen(request)
			dataResponse = nvrResponse.read().decode()
			jsonResponse = json.loads(dataResponse)
			Domoticz.Debug("Update camera OK")
		except HTTPError as e:
			Domoticz.Debug("Update camera Error: " + str(e))
		return True

	def unifiInitInfos(self):
		url = "http://"+Parameters["Address"]+":"+Parameters["Port"]+"/api/2.0/camera/?apiKey="+Parameters["Mode1"]
		headers = {'Content-Type': 'application/json'}
		request = Request(url=url)
		try:
			nvrResponse = urlopen(request)
		except HTTPError as e:
			Domoticz.Debug("Error code" + str(e))
		dataResponse = nvrResponse.read().decode()
		jsonResponse = json.loads(dataResponse)
		Domoticz.Debug("Found "+ str(len(jsonResponse["data"]))+" camera(s)")
		#INIT CAMERAS
		dom_id = 1
		for cam in jsonResponse["data"]:
			unifiCamera = {}
			unifiCamera['name'] = cam["name"]
			unifiCamera['unifi_id'] = cam["_id"]
			unifiCamera['dom_id'] = dom_id
			unifiCamera['model'] = cam["model"]
			unifiCameras.append(unifiCamera)
			dom_id = dom_id + 1
		return True


global _plugin
_plugin = BasePlugin()

def onStart():
	global _plugin
	_plugin.onStart()

def onStop():
	global _plugin
	_plugin.onStop()

def onConnect(Status, Description):
	global _plugin
	_plugin.onConnect(Status, Description)

def onMessage(Data, Status, Extra):
	global _plugin
	_plugin.onMessage(Data, Status, Extra)

def onCommand(Unit, Command, Level, Hue):
	global _plugin
	_plugin.onCommand(Unit, Command, Level, Hue)

def onNotification(Name, Subject, Text, Status, Priority, Sound, ImageFile):
	global _plugin
	_plugin.onNotification(Name, Subject, Text, Status, Priority, Sound, ImageFile)

def onDisconnect():
	global _plugin
	_plugin.onDisconnect()

def onHeartbeat():
	global _plugin
	_plugin.onHeartbeat()

# Generic helper functions
def DumpConfigToLog():
	for x in Parameters:
		if Parameters[x] != "":
			Domoticz.Debug( "'" + x + "':'" + str(Parameters[x]) + "'")
	Domoticz.Debug("Device count: " + str(len(Devices)))
	for x in Devices:
		Domoticz.Debug("Device:           " + str(x) + " - " + str(Devices[x]))
		Domoticz.Debug("Device ID:       '" + str(Devices[x].ID) + "'")
		Domoticz.Debug("Device Name:     '" + Devices[x].Name + "'")
		Domoticz.Debug("Device nValue:    " + str(Devices[x].nValue))
		Domoticz.Debug("Device sValue:   '" + Devices[x].sValue + "'")
		Domoticz.Debug("Device LastLevel: " + str(Devices[x].LastLevel))
	return

Enjoy

Fred
Attachments
cam_g3.zip
(8.79 KiB) Downloaded 167 times
cam_g3_dome.zip
(16.07 KiB) Downloaded 110 times
maomanna
Posts: 94
Joined: Monday 30 November 2015 16:21
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

Re: Python plugin: Unifi Video from Ubiquiti

Post by maomanna »

wauw! great work!

This is what my wife and I were talking about since yesterday.

is it possible to turn off the live view as well?
maomanna
Posts: 94
Joined: Monday 30 November 2015 16:21
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

Re: Python plugin: Unifi Video from Ubiquiti

Post by maomanna »

gysmo38 wrote:Hello,

I made a plugin to activate or deactivate motion record from Domoticz.

You need to have a Unifi server and activate API access from user information.

In attachements to zip files for cam logo.

....

Enjoy

Fred

I get these errors:
2017-05-28 20:29:29.689 (Unifi cams) Initialized version 0.1, author 'gysmo'
2017-05-28 20:29:29.690 (Unifi cams) onStart called
2017-05-28 20:29:29.693 (Unifi cams) Debug log level set to: 'true'.
2017-05-28 20:29:29.700 Error: (Unifi cams) 'onStart' failed 'RemoteDisconnected'.
2017-05-28 20:29:29.700 Error: (Unifi cams) ----> Line 136 in /domoticz/plugins/unifi/plugin.py, function onStart
2017-05-28 20:29:29.700 Error: (Unifi cams) ----> Line 44 in /domoticz/plugins/unifi/plugin.py, function onStart
2017-05-28 20:29:29.700 Error: (Unifi cams) ----> Line 114 in /domoticz/plugins/unifi/plugin.py, function unifiInitInfos
2017-05-28 20:29:29.700 Error: (Unifi cams) ----> Line 163 in /usr/lib/python3.5/urllib/request.py, function urlopen
2017-05-28 20:29:29.700 Error: (Unifi cams) ----> Line 466 in /usr/lib/python3.5/urllib/request.py, function open
2017-05-28 20:29:29.700 Error: (Unifi cams) ----> Line 484 in /usr/lib/python3.5/urllib/request.py, function _open
2017-05-28 20:29:29.700 Error: (Unifi cams) ----> Line 444 in /usr/lib/python3.5/urllib/request.py, function _call_chain
2017-05-28 20:29:29.700 Error: (Unifi cams) ----> Line 1282 in /usr/lib/python3.5/urllib/request.py, function http_open
2017-05-28 20:29:29.700 Error: (Unifi cams) ----> Line 1260 in /usr/lib/python3.5/urllib/request.py, function do_open
2017-05-28 20:29:29.700 Error: (Unifi cams) ----> Line 1214 in /usr/lib/python3.5/http/client.py, function getresponse
2017-05-28 20:29:29.700 Error: (Unifi cams) ----> Line 297 in /usr/lib/python3.5/http/client.py, function begin
2017-05-28 20:29:29.700 Error: (Unifi cams) ----> Line 266 in /usr/lib/python3.5/http/client.py, function _read_status
It doens't make a new device as well.
gysmo38
Posts: 50
Joined: Saturday 01 February 2014 13:42
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

Re: Python plugin: Unifi Video from Ubiquiti

Post by gysmo38 »

Hello,

Which type of camera do you have?

Do you put zip files in the plugin directory?


For live video, I will check if I can add this feature.

Thank you for testing, it is a first version, I will find what going wrong for you.
maomanna
Posts: 94
Joined: Monday 30 November 2015 16:21
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

Re: Python plugin: Unifi Video from Ubiquiti

Post by maomanna »

i have the Unifi G3 (https://www.ubnt.com/unifi-video/unifi-video-camera-g3/)

files are in the correct directories
maomanna
Posts: 94
Joined: Monday 30 November 2015 16:21
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

Re: Python plugin: Unifi Video from Ubiquiti

Post by maomanna »

gysmo38 wrote:Hello,

Which type of camera do you have?

Do you put zip files in the plugin directory?


For live video, I will check if I can add this feature.

Thank you for testing, it is a first version, I will find what going wrong for you.
Hey Gysmo,

Did you find some time to troubleshoot?
gysmo38
Posts: 50
Joined: Saturday 01 February 2014 13:42
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

Re: Python plugin: Unifi Video from Ubiquiti

Post by gysmo38 »

Can you try this code?

Code: Select all

# UnifiVideo Plugin
# Author:     Gysmo, 2017
# Version: 0.1
#   
# v0.1 : Initial release
"""
<plugin key="UVC" version="0.1" name="UVC_Plugin" author="gysmo" wikilink="http://www.domoticz.com/wiki/Plugins/UnifiVideo.html" externallink="http://video.ubnt.com">
    <params>
		<param field="Address" label="IP Address" width="200px" required="true" />
        <param field="Port" label="Port" width="200px" required="true" default="7080" />
		<param field="Mode1" label="APIKey" width="200px" required="true" />
		<param field="Mode6" label="Debug" width="75px">
            <options>
                <option label="True" value="Debug"/>
                <option label="False" value="Normal"  default="true" />
            </options>
        </param>
    </params>
</plugin>
"""
import Domoticz
import time
import base64
import json
from urllib.parse import urlencode
from urllib.request import Request, urlopen, HTTPError

unifiCameras = []

class BasePlugin:
	enabled = False
	def __init__(self):
		#self.var = 123
		return

	def onStart(self):
		Domoticz.Log("onStart called")
		if ("myPlugin"     not in Images):
			Domoticz.Image('cam_g3.zip').Create()
		if ("myPluginAlt1" not in Images):
			Domoticz.Image('cam_g3_dome.zip').Create()
		if Parameters["Mode6"] == "Debug":
			Domoticz.Debugging(1)
		self.unifiInitInfos()
		if (len(Devices) == 0):
			# Create Camera motion switch
			for cam in unifiCameras:
				Domoticz.Log("Creating camera " + cam['name'])
				OptionsMode = {"LevelActions": "|","LevelNames": "Off|Record on motion","LevelOffHidden": "false","SelectorStyle": "1"}
				if (cam['model'] == 'UVC G3'):
					model = 'UVC'
				elif (cam['model'] == 'UVC G3 Dome'):
					model = 'UVCDome'
				else:
					model = 'UVC'
				Domoticz.Device(Name=cam['name'], Unit=cam['dom_id'], TypeName="Selector Switch", Image=Images[model].ID, Options=OptionsMode, Used=1).Create()

	def onStop(self):
		Domoticz.Log("onStop called")

	def onConnect(self, Status, Description):
		Domoticz.Log("onConnect called")

	def onMessage(self, Data, Status, Extra):
		Domoticz.Log("onMessage called")

	def onCommand(self, Unit, Command, Level, Hue):
		Domoticz.Log("onCommand called for Unit " + str(Unit) + ": Parameter '" + str(Command) + "', Level: " + str(Level))
		if (Level == 0):
			self.unifiSetRecording("Off",Unit)
			Devices[Unit].Update(0, str(0))
		elif (Level == 10):
			self.unifiSetRecording("Motion",Unit)
			Devices[Unit].Update(1, str(10))


	def onNotification(self, Name, Subject, Text, Status, Priority, Sound, ImageFile):
		Domoticz.Log("Notification: " + Name + "," + Subject + "," + Text + "," + Status + "," + str(Priority) + "," + Sound + "," + ImageFile)

	def onDisconnect(self):
		Domoticz.Log("onDisconnect called")

	def onHeartbeat(self):
		Domoticz.Log("onHeartbeat called")

# Function define for script
	def unifiSetRecording(self,mode,domID):
		camID = ""
		for cam in unifiCameras:
			if (cam['dom_id'] == domID):
				camID = cam['unifi_id']
				name = cam['name']
		url = "http://"+Parameters["Address"]+":"+Parameters["Port"]+"/api/2.0/camera/"+camID+"?apiKey="+Parameters["Mode1"]
		headers = {'Content-Type': 'application/json'}
		if (mode == "Off"):
			post_fields = bytes('{"name":"'+name+'","recordingSettings":{"motionRecordEnabled":"false"}}','utf-8')
		elif (mode == "Motion"):
			post_fields = bytes('{"name":"'+name+'","recordingSettings":{"motionRecordEnabled":"true","channel":"0"}}','utf-8')
		request = Request(url=url,data=post_fields,headers=headers,method='PUT')
		try:
			nvrResponse = urlopen(request)
			dataResponse = nvrResponse.read().decode()
			jsonResponse = json.loads(dataResponse)
			Domoticz.Debug("Update camera OK")
		except HTTPError as e:
			Domoticz.Debug("Update camera Error: " + str(e))
		return True

	def unifiInitInfos(self):
		url = "http://"+Parameters["Address"]+":"+Parameters["Port"]+"/api/2.0/camera/?apiKey="+Parameters["Mode1"]
		headers = {'Content-Type': 'application/json'}
		request = Request(url=url)
		try:
			nvrResponse = urlopen(request)
		except HTTPError as e:
			Domoticz.Debug("Error code" + str(e))
		dataResponse = nvrResponse.read().decode()
		jsonResponse = json.loads(dataResponse)
		Domoticz.Debug("Found "+ str(len(jsonResponse["data"]))+" camera(s)")
		#INIT CAMERAS
		dom_id = 1
		for cam in jsonResponse["data"]:
			unifiCamera = {}
			unifiCamera['name'] = cam["name"]
			unifiCamera['unifi_id'] = cam["_id"]
			unifiCamera['dom_id'] = dom_id
			unifiCamera['model'] = cam["model"]
			unifiCameras.append(unifiCamera)
			dom_id = dom_id + 1
		return True


global _plugin
_plugin = BasePlugin()

def onStart():
	global _plugin
	_plugin.onStart()

def onStop():
	global _plugin
	_plugin.onStop()

def onConnect(Status, Description):
	global _plugin
	_plugin.onConnect(Status, Description)

def onMessage(Data, Status, Extra):
	global _plugin
	_plugin.onMessage(Data, Status, Extra)

def onCommand(Unit, Command, Level, Hue):
	global _plugin
	_plugin.onCommand(Unit, Command, Level, Hue)

def onNotification(Name, Subject, Text, Status, Priority, Sound, ImageFile):
	global _plugin
	_plugin.onNotification(Name, Subject, Text, Status, Priority, Sound, ImageFile)

def onDisconnect():
	global _plugin
	_plugin.onDisconnect()

def onHeartbeat():
	global _plugin
	_plugin.onHeartbeat()

# Generic helper functions
def DumpConfigToLog():
	for x in Parameters:
		if Parameters[x] != "":
			Domoticz.Debug( "'" + x + "':'" + str(Parameters[x]) + "'")
	Domoticz.Debug("Device count: " + str(len(Devices)))
	for x in Devices:
		Domoticz.Debug("Device:           " + str(x) + " - " + str(Devices[x]))
		Domoticz.Debug("Device ID:       '" + str(Devices[x].ID) + "'")
		Domoticz.Debug("Device Name:     '" + Devices[x].Name + "'")
		Domoticz.Debug("Device nValue:    " + str(Devices[x].nValue))
		Domoticz.Debug("Device sValue:   '" + Devices[x].sValue + "'")
		Domoticz.Debug("Device LastLevel: " + str(Devices[x].LastLevel))
	return
maomanna
Posts: 94
Joined: Monday 30 November 2015 16:21
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

Re: Python plugin: Unifi Video from Ubiquiti

Post by maomanna »

Code: Select all

2017-06-14 20:44:41.359 (unifi nvr) Debug log level set to: 'true'.
2017-06-14 20:44:41.362 Error: (unifi nvr) 'onStart' failed 'URLError'.
2017-06-14 20:44:41.362 Error: (unifi nvr) ----> Line 138 in /domoticz/plugins/unifi/plugin.py, function onStart
2017-06-14 20:44:41.362 Error: (unifi nvr) ----> Line 44 in /domoticz/plugins/unifi/plugin.py, function onStart
2017-06-14 20:44:41.362 Error: (unifi nvr) ----> Line 116 in /domoticz/plugins/unifi/plugin.py, function unifiInitInfos
2017-06-14 20:44:41.362 Error: (unifi nvr) ----> Line 163 in /usr/lib/python3.5/urllib/request.py, function urlopen
2017-06-14 20:44:41.362 Error: (unifi nvr) ----> Line 466 in /usr/lib/python3.5/urllib/request.py, function open
2017-06-14 20:44:41.362 Error: (unifi nvr) ----> Line 484 in /usr/lib/python3.5/urllib/request.py, function _open
2017-06-14 20:44:41.362 Error: (unifi nvr) ----> Line 444 in /usr/lib/python3.5/urllib/request.py, function _call_chain
2017-06-14 20:44:41.362 Error: (unifi nvr) ----> Line 1282 in /usr/lib/python3.5/urllib/request.py, function http_open
2017-06-14 20:44:41.362 Error: (unifi nvr) ----> Line 1260 in /usr/lib/python3.5/urllib/request.py, function do_open
looks like the same error
gysmo38
Posts: 50
Joined: Saturday 01 February 2014 13:42
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

Re: Python plugin: Unifi Video from Ubiquiti

Post by gysmo38 »

Hello,

I take time to understand your problem.

I have got same error if the ip address or port are not correct.

For ip address you need to put your local ip address and for port it is 7080 (default port for API)

Can you check and try again?


Thank you
maomanna
Posts: 94
Joined: Monday 30 November 2015 16:21
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

Re: Python plugin: Unifi Video from Ubiquiti

Post by maomanna »

it seems to work now!

i guess it had something to do with port 7080.

I normally use the https (7443) port.
Derik
Posts: 1601
Joined: Friday 18 October 2013 23:33
Target OS: Raspberry Pi / ODroid
Domoticz version: BETA
Location: Arnhem/Nijmegen Nederland
Contact:

Re: Python plugin: Unifi Video from Ubiquiti

Post by Derik »

Dear all...
See not a lot info about this brand on the forum..
Only are there perhaps people that have a wifi camera from UniFi working in Domoticz?
and i mean out of the box visible in the camera section??
So i can use the pictures ...
Perhaps talkbalk is not working only that is not a problem for me.
Xu4: Beta Extreme antenna RFXcomE,WU Fi Ping ip P1 Gen5 PVOutput Harmony HUE SolarmanPv OTG Winddelen Alive ESP Buienradar MySensors WOL Winddelen counting RPi: Beta SMAspot RFlinkTest Domoticz ...Different backups
DoMoAD
Posts: 13
Joined: Friday 11 May 2018 14:24
Target OS: Raspberry Pi / ODroid
Domoticz version: BETA
Location: Netherlands
Contact:

Re: Python plugin: Unifi Video from Ubiquiti

Post by DoMoAD »

I used the exact code as published above. I put the zip file in de plugin directory. When i select UVC in Hardware my totale domoticz crashes. Is this plugin not working anymore with the beta domoticz?
angelosan
Posts: 2
Joined: Sunday 09 February 2014 19:17
Target OS: Raspberry Pi / ODroid
Domoticz version: 4.796
Location: Italy
Contact:

Re: Python plugin: Unifi Video from Ubiquiti

Post by angelosan »

Hello,
I have add "Full Time" selector


Code: Select all

# UnifiVideo Plugin
# Author:     Gysmo, 2017
# Version: 0.1
#   
# v0.1 : Initial release
# v0.2 : add Full Time - Angelo Santaniello
"""
<plugin key="UVC" version="0.2" name="UVC_Plugin" author="gysmo" wikilink="http://www.domoticz.com/wiki/Plugins/UnifiVideo.html" externallink="http://video.ubnt.com">
    <params>
		<param field="Address" label="IP Address" width="200px" required="true" />
        <param field="Port" label="Port" width="200px" required="true" default="7080" />
		<param field="Mode1" label="APIKey" width="200px" required="true" />
		<param field="Mode6" label="Debug" width="75px">
            <options>
                <option label="True" value="Debug"/>
                <option label="False" value="Normal"  default="true" />
            </options>
        </param>
    </params>
</plugin>
"""
import Domoticz
import time
import base64
import json
from urllib.parse import urlencode
from urllib.request import Request, urlopen, HTTPError

unifiCameras = []

class BasePlugin:
	enabled = False
	def __init__(self):
		#self.var = 123
		return

	def onStart(self):
		Domoticz.Log("onStart called")
		if ("myPlugin"     not in Images):
			Domoticz.Image('cam_g3.zip').Create()
		if ("myPluginAlt1" not in Images):
			Domoticz.Image('cam_g3_dome.zip').Create()
		if Parameters["Mode6"] == "Debug":
			Domoticz.Debugging(1)
		self.unifiInitInfos()
		if (len(Devices) == 0):
			# Create Camera motion switch
			for cam in unifiCameras:
				Domoticz.Log("Creating camera " + cam['name'])
				OptionsMode = {"LevelActions": "|","LevelNames": "Off|Record on motion|Record Always","LevelOffHidden": "false","SelectorStyle": "1"}
				if (cam['model'] == 'UVC G3'):
					model = 'UVC'
				elif (cam['model'] == 'UVC G3 Dome'):
					model = 'UVCDome'
				Domoticz.Device(Name=cam['name'], Unit=cam['dom_id'], TypeName="Selector Switch", Image=Images[model].ID, Options=OptionsMode, Used=1).Create()

	def onStop(self):
		Domoticz.Log("onStop called")

	def onConnect(self, Status, Description):
		Domoticz.Log("onConnect called")

	def onMessage(self, Data, Status, Extra):
		Domoticz.Log("onMessage called")

	def onCommand(self, Unit, Command, Level, Hue):
		Domoticz.Log("onCommand called for Unit " + str(Unit) + ": Parameter '" + str(Command) + "', Level: " + str(Level))
		if (Level == 0):
			self.unifiSetRecording("Off",Unit)
			Devices[Unit].Update(0, str(0))
		elif (Level == 10):
			self.unifiSetRecording("Motion",Unit)
			Devices[Unit].Update(1, str(10))
		elif (Level == 20):
			self.unifiSetRecording("Always",Unit)
			Devices[Unit].Update(1, str(20))
			
			

	def onNotification(self, Name, Subject, Text, Status, Priority, Sound, ImageFile):
		Domoticz.Log("Notification: " + Name + "," + Subject + "," + Text + "," + Status + "," + str(Priority) + "," + Sound + "," + ImageFile)

	def onDisconnect(self):
		Domoticz.Log("onDisconnect called")

	def onHeartbeat(self):
		Domoticz.Log("onHeartbeat called")

# Function define for script
	def unifiSetRecording(self,mode,domID):
		camID = ""
		for cam in unifiCameras:
			if (cam['dom_id'] == domID):
				camID = cam['unifi_id']
				name = cam['name']
		url = "http://"+Parameters["Address"]+":"+Parameters["Port"]+"/api/2.0/camera/"+camID+"?apiKey="+Parameters["Mode1"]
		headers = {'Content-Type': 'application/json'}
		if (mode == "Off"):
			post_fields = bytes('{"name":"'+name+'","recordingSettings":{"motionRecordEnabled":"false","fullTimeRecordEnabled":"false"}}','utf-8')
		elif (mode == "Motion"):
			post_fields = bytes('{"name":"'+name+'","recordingSettings":{"motionRecordEnabled":"true","fullTimeRecordEnabled":"false","prePaddingSecs":"15","postPaddingSecs":"15","channel":"0"}}','utf-8')
		elif (mode == "Always"):
			post_fields = bytes('{"name":"'+name+'","recordingSettings":{"motionRecordEnabled":"false","fullTimeRecordEnabled":"true","prePaddingSecs":"0","postPaddingSecs":"0","channel":"0"}}','utf-8')
			
		request = Request(url=url,data=post_fields,headers=headers,method='PUT')		
		try:
			nvrResponse = urlopen(request)
			dataResponse = nvrResponse.read().decode()
			jsonResponse = json.loads(dataResponse)
			Domoticz.Debug("Update camera OK")
		except HTTPError as e:
			Domoticz.Debug("Update camera Error: " + str(e))
		return True

	def unifiInitInfos(self):
		url = "http://"+Parameters["Address"]+":"+Parameters["Port"]+"/api/2.0/camera/?apiKey="+Parameters["Mode1"]
		headers = {'Content-Type': 'application/json'}
		request = Request(url=url)
		try:
			nvrResponse = urlopen(request)
		except HTTPError as e:
			Domoticz.Debug("Error code" + str(e))
		dataResponse = nvrResponse.read().decode()
		jsonResponse = json.loads(dataResponse)
		Domoticz.Debug("Found "+ str(len(jsonResponse["data"]))+" camera(s)")
		#INIT CAMERAS
		dom_id = 1
		for cam in jsonResponse["data"]:
			unifiCamera = {}
			unifiCamera['name'] = cam["name"]
			unifiCamera['unifi_id'] = cam["_id"]
			unifiCamera['dom_id'] = dom_id
			unifiCamera['model'] = cam["model"]
			unifiCameras.append(unifiCamera)
			dom_id = dom_id + 1
		return True


global _plugin
_plugin = BasePlugin()

def onStart():
	global _plugin
	_plugin.onStart()

def onStop():
	global _plugin
	_plugin.onStop()

def onConnect(Status, Description):
	global _plugin
	_plugin.onConnect(Status, Description)

def onMessage(Data, Status, Extra):
	global _plugin
	_plugin.onMessage(Data, Status, Extra)

def onCommand(Unit, Command, Level, Hue):
	global _plugin
	_plugin.onCommand(Unit, Command, Level, Hue)

def onNotification(Name, Subject, Text, Status, Priority, Sound, ImageFile):
	global _plugin
	_plugin.onNotification(Name, Subject, Text, Status, Priority, Sound, ImageFile)

def onDisconnect():
	global _plugin
	_plugin.onDisconnect()

def onHeartbeat():
	global _plugin
	_plugin.onHeartbeat()

# Generic helper functions
def DumpConfigToLog():
	for x in Parameters:
		if Parameters[x] != "":
			Domoticz.Debug( "'" + x + "':'" + str(Parameters[x]) + "'")
	Domoticz.Debug("Device count: " + str(len(Devices)))
	for x in Devices:
		Domoticz.Debug("Device:           " + str(x) + " - " + str(Devices[x]))
		Domoticz.Debug("Device ID:       '" + str(Devices[x].ID) + "'")
		Domoticz.Debug("Device Name:     '" + Devices[x].Name + "'")
		Domoticz.Debug("Device nValue:    " + str(Devices[x].nValue))
		Domoticz.Debug("Device sValue:   '" + Devices[x].sValue + "'")
		Domoticz.Debug("Device LastLevel: " + str(Devices[x].LastLevel))
	return


DoMoAD
Posts: 13
Joined: Friday 11 May 2018 14:24
Target OS: Raspberry Pi / ODroid
Domoticz version: BETA
Location: Netherlands
Contact:

Re: Python plugin: Unifi Video from Ubiquiti

Post by DoMoAD »

I found the problem. I had to CHMOD 755 the plugin.py file. Now it's working fine.
mindwipe
Posts: 1
Joined: Tuesday 06 November 2018 23:26
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

Re: Python plugin: Unifi Video from Ubiquiti

Post by mindwipe »

I'm using your script but having problems with that the domoticz service crashes a couple of times a day and i can't find out why.
Please help me how i can debug this.
leby
Posts: 98
Joined: Monday 28 July 2014 9:58
Target OS: Raspberry Pi / ODroid
Domoticz version: 2020.2
Location: Stockholm
Contact:

Re: Python plugin: Unifi Video from Ubiquiti

Post by leby »

Hi @gysmo38 is this project closed? I'm looking for integration of Unifi Protect to be used as motion detectors.
Regards
/lennart
Post Reply

Who is online

Users browsing this forum: No registered users and 1 guest