70 Commits

Author SHA1 Message Date
Cédric Verstraeten
a7815a692c Merge pull request #2 from kerberos-io/fix/only-close-open-server-response
Fix server response closing
2025-01-19 10:37:10 +01:00
Cedric Verstraeten
d80b15daf0 Merge branch 'master' into fix/only-close-open-server-response 2025-01-19 10:28:29 +01:00
Cedric Verstraeten
9ca534b5bb correct workflow structure 2025-01-19 10:19:22 +01:00
Cedric Verstraeten
ede8b81fc8 Update Device.go 2025-01-19 09:58:53 +01:00
Cédric Verstraeten
76463bb61a Merge pull request #1 from kerberos-io/fix/call-method-do-memleak
Call method do memleak
2025-01-18 09:21:06 +01:00
Cedric Verstraeten
ca27d2a9d8 Merge branch 'master' into fix/call-method-do-memleak 2025-01-18 09:12:21 +01:00
Cedric Verstraeten
f3f03cc827 add pr description workflow 2025-01-18 09:12:05 +01:00
Cedric Verstraeten
542f83433b Update Device.go 2025-01-18 09:09:33 +01:00
Cedric Verstraeten
6fc6d9a99e reuse main http client + resolved memory leak (close previous response) before creating new one. 2025-01-16 21:43:28 +01:00
Cedric Verstraeten
ee8a919932 support for latest hikivision ONVIF 19.12 2024-08-21 16:07:06 +02:00
Cedric Verstraeten
d1b78fa51a make array of relayoutputs and digitalinputs 2024-08-20 09:00:32 +02:00
Cedric Verstraeten
4c9f12fc97 add 2023-12-25 21:31:14 +01:00
Cédric Verstraeten
04f0dfbc03 Delete Imaging/types.go 2023-12-25 21:29:06 +01:00
Cedric Verstraeten
add8ae2bad Revert "disable imaging"
This reverts commit 6c5db5fed6.
2023-12-25 21:26:55 +01:00
Cedric Verstraeten
6c5db5fed6 disable imaging 2023-12-25 21:21:12 +01:00
Cedric Verstraeten
ba8bcf19bb inputs method added 2023-12-25 20:57:16 +01:00
Cedric Verstraeten
8902e4e789 upgrade onvif library 2023-12-18 20:16:21 +01:00
Cedric Verstraeten
71b6d48393 diz memory leak + import 2023-12-06 20:38:25 +01:00
Cedric Verstraeten
bb5a87b253 Merge remote-tracking branch 'upstream/master' 2023-12-06 19:45:28 +01:00
Edward
217f1231c5 Merge pull request #38 from sunjirui/imaging-setting-change
The Parameters in ImagingSettings20 becomes optional
2023-09-21 14:52:22 +08:00
Cedric Verstraeten
7903bf2710 makes presets an array, we have more than a single preset 2023-08-30 11:01:24 +02:00
Cedric Verstraeten
c037b63bad Fix for ONVIF preset (json) 2023-08-24 12:36:15 +02:00
sunjirui
b424ee7bfe changed ImagingSettings20 2023-08-07 19:18:45 +08:00
Edward
88cd86f4fc Merge pull request #31 from stefan-kiss/ptz-profiles-fix
changed Preset field to slice in GetPresetsResponse
2023-05-02 02:11:51 +08:00
Edward
03ecb66210 Merge pull request #27 from tarancss/fix-memleak-and-events
Fix memory leak and events
2023-05-02 02:10:33 +08:00
Cédric Verstraeten
23e1c0b1bc Update onvif.go 2023-01-25 14:10:53 +01:00
Cedric Verstraeten
9d65ca2b49 add new types for independent zoom and pan tilt 2022-12-23 08:55:22 +01:00
Kiss Stefan
5c4360a924 changed Preset field to slice in GetPresetsResponse 2022-12-11 14:00:19 +02:00
tarancss
1a23395c53 remove debug logs 2022-09-17 01:24:52 +02:00
tarancss
8677b3be7e fix memory leak and events 2022-09-17 01:18:56 +02:00
tarancss
4f0536a933 fix subscribe response 2022-08-14 18:15:33 +02:00
Edward
bc3226e9ec Merge pull request #22 from jfsmig/fixes-ws-discovery-20220510
Misc. fixes in the WS discovery
2022-07-26 14:39:05 +08:00
Edward
d8d0fc383a Merge pull request #21 from spring-lab/master
fix ptz.types.SetPreset.PresetToken is optional
2022-07-26 14:31:40 +08:00
Jean-Francois Smigielski
9e25a0109e api: use juju/errors and zerolog 2022-05-11 10:05:57 +02:00
Jean-Francois Smigielski
47d91cba88 networking: use juju/errors and zerolog 2022-05-11 10:05:57 +02:00
Jean-Francois Smigielski
72a3540cc3 Let the example code use the generated SDK methods
Also introduces zerolog for pretty traces and juju/errors to annotate the errors
and track their origin.
2022-05-11 10:05:57 +02:00
Jean-Francois Smigielski
7d78e6b76e Provide a sdk package with 1 call per method
Modify the template in ./sdk/codegen/main.go

Use "go generate" from ./sdk/{ptz,media,device} to regenerate the files.
2022-05-11 10:05:57 +02:00
Jean-Francois Smigielski
6f1154fc4d ws-discovery: Return an error instead of printing & ignoring 2022-05-10 13:21:27 +02:00
Jean-Francois Smigielski
9b5df9ac2c Avoid non-error debug on stdout 2022-05-09 09:13:30 +02:00
Jean-Francois Smigielski
2569cf83bf Use a random ssource port in ws-discovery 2022-05-09 00:58:06 +02:00
Spring
be3347f029 fix ptz.types.SetPreset.PresetToken is optional 2022-04-24 09:53:18 +08:00
Edward
d42cc336c6 Merge pull request #19 from use-go/dependabot/go_modules/github.com/gin-gonic/gin-1.7.0
Bump github.com/gin-gonic/gin from 1.6.2 to 1.7.0
2022-03-23 12:44:13 +08:00
dependabot[bot]
9bf3bd8446 Bump github.com/gin-gonic/gin from 1.6.2 to 1.7.0
Bumps [github.com/gin-gonic/gin](https://github.com/gin-gonic/gin) from 1.6.2 to 1.7.0.
- [Release notes](https://github.com/gin-gonic/gin/releases)
- [Changelog](https://github.com/gin-gonic/gin/blob/master/CHANGELOG.md)
- [Commits](https://github.com/gin-gonic/gin/compare/v1.6.2...v1.7.0)

---
updated-dependencies:
- dependency-name: github.com/gin-gonic/gin
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-03-23 04:42:17 +00:00
Edward
33a083305c Merge pull request #18 from yjkhtddx/master
more services
2022-03-23 12:40:56 +08:00
Edward
2c358f683b Merge pull request #11 from GreenLightning/fix
Fix panic during SendProbe
2022-03-23 12:40:15 +08:00
刘跃龙
1bfeb9b57d fix:get Extension services 2021-10-25 10:59:11 +08:00
刘跃龙
c5e512ad1a fix:get Extension services 2021-10-25 10:55:46 +08:00
Green Lightning
07eeae0187 Fix panic during SendProbe
If ListenPacket returns an error, c is nil and the deferred call to
c.Close() will panic.

Fix this by returning early from the method.
2021-07-26 14:22:05 +02:00
cedricve
37d8a71395 rename imports 2021-06-04 21:51:49 +02:00
Edward
af24622015 Merge pull request #8 from kikimor/http_custom
External httpClient support
2021-04-24 11:15:02 +08:00
kikimor
2fb044d81c endpoint nat support 2021-03-06 23:56:46 +05:00
kikimor
51ae55e8a0 External httpClient support 2021-02-24 21:58:44 +05:00
eamon
6a2c796805 fix case 2021-01-31 16:12:54 +08:00
Edward
48daf5acb5 Rename license to LICENSE 2021-01-31 16:01:46 +08:00
Edward
d85a0742b9 Create license 2021-01-31 16:00:28 +08:00
Edward
24a85afc84 Merge pull request #4 from GreenLightning/master
Do not log "i/o timeout" errors
2021-01-29 19:37:38 +08:00
Green Lightning
c8ac58ebd7 Require Go 1.15 2020-10-23 11:51:21 +02:00
Green Lightning
4ec21b20e0 Do not log "i/o timeout" errors 2020-10-21 00:09:00 +02:00
Edward
4e696ec65a Merge pull request #3 from GreenLightning/fix-auth
Fix authentication
2020-08-17 18:39:23 +08:00
Green Lightning
e1345d5e6b Fix authentication
Because time.Now() is called twice, it may return different results on a
slow machine, causing an invalid authentication header to be generated.
2020-08-16 17:31:35 +02:00
Edward
918ce541d2 Update README.md 2020-05-26 10:39:28 +08:00
Edward
15e268c1b7 Update README.md 2020-05-09 16:06:23 +08:00
Edward
dce0d0faad add an example by testing 2020-05-01 22:58:49 +08:00
Edward
be84cab1fe add SendSoapWithTimeout 2020-05-01 22:58:33 +08:00
Edward
c10b8ca105 update mod 2020-05-01 22:42:53 +08:00
Edward
e6593ad04f introduce iso8601_duration directly 2020-05-01 22:42:40 +08:00
Edward
702fded39b Update README.md 2020-05-01 22:35:50 +08:00
Edward
298c2dabb9 Update README.md 2020-04-29 11:09:08 +08:00
Edward
bedd8886e4 Update README.md 2020-04-29 11:08:05 +08:00
Edward
ddb7588318 Update README.md 2020-04-29 11:07:53 +08:00
69 changed files with 9685 additions and 1339 deletions

7
.github/dependabot.yml vendored Normal file
View File

@@ -0,0 +1,7 @@
version: 2
updates:
# Maintain dependencies for Go modules
- package-ecosystem: "gomod"
directory: "/"
schedule:
interval: "weekly"

19
.github/workflows/pr-description.yml vendored Normal file
View File

@@ -0,0 +1,19 @@
name: Autofill PR description
on: pull_request
jobs:
openai-pr-description:
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v4
- name: Autofill PR description if empty using OpenAI
uses: cedricve/azureopenai-pr-description@master
with:
github_token: ${{ secrets.TOKEN }}
openai_api_key: ${{ secrets.OPENAI_API_KEY }}
azure_openai_api_key: ${{ secrets.AZURE_OPENAI_API_KEY }}
azure_openai_endpoint: ${{ secrets.AZURE_OPENAI_ENDPOINT }}
azure_openai_version: ${{ secrets.AZURE_OPENAI_VERSION }}
overwrite_description: true

3
.gitignore vendored Normal file
View File

@@ -0,0 +1,3 @@
*.iml
.idea/
.vscode/

View File

@@ -27,7 +27,9 @@
"go.testTimeout": "10s",
"go.formatTool": "goimports",
"cSpell.allowCompoundWords": true,
"editor.codeActionsOnSave": {"source.organizeImports": true},
"editor.codeActionsOnSave": {
"source.organizeImports": "explicit"
},
"cSpell.words": [
"wsdiscovery"
]

415
Device.go
View File

@@ -1,27 +1,32 @@
package onvif
import (
"bytes"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"reflect"
"strconv"
"strings"
"github.com/kerberos-io/onvif/networking"
"github.com/kerberos-io/onvif/xsd/onvif"
"github.com/beevik/etree"
"github.com/use-go/onvif/device"
"github.com/use-go/onvif/gosoap"
"github.com/use-go/onvif/networking"
wsdiscovery "github.com/use-go/onvif/ws-discovery"
"github.com/kerberos-io/onvif/device"
"github.com/kerberos-io/onvif/gosoap"
)
//Xlmns XML Scheam
// Xlmns XML Scheam
var Xlmns = map[string]string{
"onvif": "http://www.onvif.org/ver10/schema",
"tds": "http://www.onvif.org/ver10/device/wsdl",
"trt": "http://www.onvif.org/ver10/media/wsdl",
"tr2": "http://www.onvif.org/ver20/media/wsdl",
"tev": "http://www.onvif.org/ver10/events/wsdl",
"tptz": "http://www.onvif.org/ver20/ptz/wsdl",
"timg": "http://www.onvif.org/ver20/imaging/wsdl",
@@ -34,9 +39,12 @@ var Xlmns = map[string]string{
"wsntw": "http://docs.oasis-open.org/wsn/bw-2",
"wsrf-rw": "http://docs.oasis-open.org/wsrf/rw-2",
"wsaw": "http://www.w3.org/2006/05/addressing/wsdl",
"tt": "http://www.onvif.org/ver10/recording/wsdl",
"wsse": "http://docs.oasis-open.org/wss/2004/01/oasis-200401",
"wsu": "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd",
}
//DeviceType alias for int
// DeviceType alias for int
type DeviceType int
// Onvif Device Tyoe
@@ -45,6 +53,8 @@ const (
NVS
NVA
NVT
ContentType = "Content-Type"
)
func (devType DeviceType) String() string {
@@ -63,8 +73,9 @@ func (devType DeviceType) String() string {
}
}
//deviceInfo struct contains general information about ONVIF device
type deviceInfo struct {
// DeviceInfo struct contains general information about ONVIF device
type DeviceInfo struct {
Name string
Manufacturer string
Model string
FirmwareVersion string
@@ -72,22 +83,63 @@ type deviceInfo struct {
HardwareId string
}
//Device for a new device of onvif and deviceInfo
//struct represents an abstract ONVIF device.
//It contains methods, which helps to communicate with ONVIF device
// Device for a new device of onvif and DeviceInfo
// struct represents an abstract ONVIF device.
// It contains methods, which helps to communicate with ONVIF device
type Device struct {
xaddr string
login string
password string
endpoints map[string]string
info deviceInfo
params DeviceParams
endpoints map[string]string
info DeviceInfo
digestClient *DigestClient
}
//GetServices return available endpoints
type DeviceParams struct {
Xaddr string
EndpointRefAddress string
Username string
Password string
HttpClient *http.Client
AuthMode string
}
// GetServices return available endpoints
func (dev *Device) GetServices() map[string]string {
return dev.endpoints
}
// GetServices return available endpoints
func (dev *Device) GetDeviceInfo() DeviceInfo {
return dev.info
}
// SetDeviceInfoFromScopes goes through the scopes and sets the device info fields for supported categories (currently name and hardware).
// See 7.3.2.2 Scopes in the ONVIF Core Specification (https://www.onvif.org/specs/core/ONVIF-Core-Specification.pdf).
func (dev *Device) SetDeviceInfoFromScopes(scopes []string) {
newInfo := dev.info
supportedScopes := []struct {
category string
setField func(s string)
}{
{category: "name", setField: func(s string) { newInfo.Name = s }},
{category: "hardware", setField: func(s string) { newInfo.Model = s }},
}
for _, s := range scopes {
for _, supp := range supportedScopes {
fullScope := fmt.Sprintf("onvif://www.onvif.org/%s/", supp.category)
scopeValue, matchesScope := strings.CutPrefix(s, fullScope)
if matchesScope {
unescaped, err := url.QueryUnescape(scopeValue)
if err != nil {
continue
}
supp.setField(unescaped)
}
}
}
dev.info = newInfo
}
func readResponse(resp *http.Response) string {
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
@@ -96,59 +148,7 @@ func readResponse(resp *http.Response) string {
return string(b)
}
//GetAvailableDevicesAtSpecificEthernetInterface ...
func GetAvailableDevicesAtSpecificEthernetInterface(interfaceName string) []Device {
/*
Call an ws-discovery Probe Message to Discover NVT type Devices
*/
devices := wsdiscovery.SendProbe(interfaceName, nil, []string{"dn:" + NVT.String()}, map[string]string{"dn": "http://www.onvif.org/ver10/network/wsdl"})
nvtDevices := make([]Device, 0)
////fmt.Println(devices)
for _, j := range devices {
doc := etree.NewDocument()
if err := doc.ReadFromString(j); err != nil {
fmt.Errorf("%s", err.Error())
return nil
}
////fmt.Println(j)
endpoints := doc.Root().FindElements("./Body/ProbeMatches/ProbeMatch/XAddrs")
for _, xaddr := range endpoints {
//fmt.Println(xaddr.Tag,strings.Split(strings.Split(xaddr.Text(), " ")[0], "/")[2] )
xaddr := strings.Split(strings.Split(xaddr.Text(), " ")[0], "/")[2]
fmt.Println(xaddr)
c := 0
for c = 0; c < len(nvtDevices); c++ {
if nvtDevices[c].xaddr == xaddr {
fmt.Println(nvtDevices[c].xaddr, "==", xaddr)
break
}
}
if c < len(nvtDevices) {
continue
}
dev, err := NewDevice(strings.Split(xaddr, " ")[0])
//fmt.Println(dev)
if err != nil {
fmt.Println("Error", xaddr)
fmt.Println(err)
continue
} else {
////fmt.Println(dev)
nvtDevices = append(nvtDevices, *dev)
}
}
////fmt.Println(j)
//nvtDevices[i] = NewDevice()
}
return nvtDevices
}
func (dev *Device) getSupportedServices(resp *http.Response) {
//resp, err := dev.CallMethod(device.GetCapabilities{Category:"All"})
//if err != nil {
// log.Println(err.Error())
//return
//} else {
doc := etree.NewDocument()
data, _ := ioutil.ReadAll(resp.Body)
@@ -159,28 +159,33 @@ func (dev *Device) getSupportedServices(resp *http.Response) {
}
services := doc.FindElements("./Envelope/Body/GetCapabilitiesResponse/Capabilities/*/XAddr")
for _, j := range services {
////fmt.Println(j.Text())
////fmt.Println(j.Parent().Tag)
dev.addEndpoint(j.Parent().Tag, j.Text())
}
//}
extensionServices := doc.FindElements("./Envelope/Body/GetCapabilitiesResponse/Capabilities/Extension/*/XAddr")
for _, j := range extensionServices {
dev.addEndpoint(j.Parent().Tag, j.Text())
}
}
//NewDevice function construct a ONVIF Device entity
func NewDevice(xaddr string) (*Device, error) {
// NewDevice function construct a ONVIF Device entity
func NewDevice(params DeviceParams) (*Device, error) {
dev := new(Device)
dev.xaddr = xaddr
dev.params = params
dev.endpoints = make(map[string]string)
dev.addEndpoint("Device", "http://"+xaddr+"/onvif/device_service")
dev.addEndpoint("Device", "http://"+dev.params.Xaddr+"/onvif/device_service")
getCapabilities := device.GetCapabilities{Category: "All"}
if dev.params.HttpClient == nil {
dev.params.HttpClient = new(http.Client)
}
dev.digestClient = NewDigestClient(dev.params.HttpClient, dev.params.Username, dev.params.Password)
getCapabilities := device.GetCapabilities{Category: []onvif.CapabilityCategory{"All"}}
resp, err := dev.CallMethod(getCapabilities)
//fmt.Println(resp.Request.Host)
//fmt.Println(readResponse(resp))
if err != nil || resp.StatusCode != http.StatusOK {
//panic(errors.New("camera is not available at " + xaddr + " or it does not support ONVIF services"))
return nil, errors.New("camera is not available at " + xaddr + " or it does not support ONVIF services")
return nil, errors.New("camera is not available at " + dev.params.Xaddr + " or it does not support ONVIF services")
}
dev.getSupportedServices(resp)
@@ -188,28 +193,30 @@ func NewDevice(xaddr string) (*Device, error) {
}
func (dev *Device) addEndpoint(Key, Value string) {
//use lowCaseKey
//make key having ability to handle Mixed Case for Different vendor devcie (e.g. Events EVENTS, events)
lowCaseKey := strings.ToLower(Key)
// Replace host with host from device params.
if u, err := url.Parse(Value); err == nil {
u.Host = dev.params.Xaddr
Value = u.String()
}
dev.endpoints[lowCaseKey] = Value
if lowCaseKey == strings.ToLower(MediaWebService) {
// Media2 uses the same endpoint but different XML name space
dev.endpoints[strings.ToLower(Media2WebService)] = Value
}
}
//Authenticate function authenticate client in the ONVIF device.
//Function takes <username> and <password> params.
//You should use this function to allow authorized requests to the ONVIF Device
//To change auth data call this function again.
func (dev *Device) Authenticate(username, password string) {
dev.login = username
dev.password = password
}
//GetEndpoint returns specific ONVIF service endpoint address
// GetEndpoint returns specific ONVIF service endpoint address
func (dev *Device) GetEndpoint(name string) string {
return dev.endpoints[name]
}
func buildMethodSOAP(msg string) (gosoap.SoapMessage, error) {
func (dev *Device) buildMethodSOAP(msg string) (gosoap.SoapMessage, error) {
doc := etree.NewDocument()
if err := doc.ReadFromString(msg); err != nil {
//log.Println("Got error")
@@ -220,13 +227,12 @@ func buildMethodSOAP(msg string) (gosoap.SoapMessage, error) {
soap := gosoap.NewEmptySOAP()
soap.AddBodyContent(element)
//soap.AddRootNamespace("onvif", "http://www.onvif.org/ver10/device/wsdl")
return soap, nil
}
//getEndpoint functions get the target service endpoint in a better way
func (dev Device) getEndpoint(endpoint string) (string, error) {
// getEndpoint functions get the target service endpoint in a better way
func (dev *Device) getEndpoint(endpoint string) (string, error) {
// common condition, endpointMark in map we use this.
if endpointURL, bFound := dev.endpoints[endpoint]; bFound {
@@ -246,8 +252,8 @@ func (dev Device) getEndpoint(endpoint string) (string, error) {
return endpointURL, errors.New("target endpoint service not found")
}
//CallMethod functions call an method, defined <method> struct.
//You should use Authenticate method to call authorized requests.
// CallMethod functions call an method, defined <method> struct.
// You should use Authenticate method to call authorized requests.
func (dev Device) CallMethod(method interface{}) (*http.Response, error) {
pkgPath := strings.Split(reflect.TypeOf(method).PkgPath(), "/")
pkg := strings.ToLower(pkgPath[len(pkgPath)-1])
@@ -259,43 +265,206 @@ func (dev Device) CallMethod(method interface{}) (*http.Response, error) {
return dev.callMethodDo(endpoint, method)
}
//CallMethod functions call an method, defined <method> struct with authentication data
// CallMethod functions call an method, defined <method> struct with authentication data
func (dev Device) callMethodDo(endpoint string, method interface{}) (*http.Response, error) {
/*
Converting <method> struct to xml string representation
*/
output, err := xml.MarshalIndent(method, " ", " ")
if err != nil {
//log.Printf("error: %v\n", err.Error())
return nil, err
}
//fmt.Println(gosoap.SoapMessage(string(output)).StringIndent())
/*
Build an SOAP request with <method>
*/
soap, err := buildMethodSOAP(string(output))
soap, err := dev.buildMethodSOAP(string(output))
if err != nil {
//log.Printf("error: %v\n", err.Error())
return nil, err
}
//fmt.Println(soap.StringIndent())
/*
Adding namespaces and WS-Security headers
*/
soap.AddRootNamespaces(Xlmns)
//fmt.Println(soap.StringIndent())
//Header handling
soap.AddAction()
//Auth Handling
if dev.login != "" && dev.password != "" {
soap.AddWSSecurity(dev.login, dev.password)
if dev.params.Username != "" && dev.params.Password != "" {
soap.AddWSSecurity(dev.params.Username, dev.params.Password)
}
//fmt.Println(soap.StringIndent())
/*
Sending request and returns the response
*/
return networking.SendSoap(endpoint, soap.String())
servResp, err := networking.SendSoap(dev.params.HttpClient, endpoint, soap.String())
if err != nil {
// Close server response body to reuse the connection
if servResp != nil {
servResp.Body.Close()
}
servResp, err = networking.SendSoapWithDigest(dev.params.HttpClient, endpoint, soap.String(), dev.params.Username, dev.params.Password)
}
return servResp, err
}
func (dev *Device) GetDeviceParams() DeviceParams {
return dev.params
}
func (dev *Device) GetEndpointByRequestStruct(requestStruct interface{}) (string, error) {
pkgPath := strings.Split(reflect.TypeOf(requestStruct).Elem().PkgPath(), "/")
pkg := strings.ToLower(pkgPath[len(pkgPath)-1])
endpoint, err := dev.getEndpoint(pkg)
if err != nil {
return "", err
}
return endpoint, err
}
/*func (dev *Device) SendSoap(endpoint string, xmlRequestBody string) (resp *http.Response, err error) {
soap := gosoap.NewEmptySOAP()
soap.AddStringBodyContent(xmlRequestBody)
soap.AddRootNamespaces(Xlmns)
if dev.params.AuthMode == UsernameTokenAuth || dev.params.AuthMode == Both {
soap.AddWSSecurity(dev.params.Username, dev.params.Password)
}
if dev.params.AuthMode == DigestAuth || dev.params.AuthMode == Both {
resp, err = dev.digestClient.Do(http.MethodPost, endpoint, soap.String())
} else {
var req *http.Request
req, err = createHttpRequest(http.MethodPost, endpoint, soap.String())
if err != nil {
return nil, err
}
resp, err = dev.params.HttpClient.Do(req)
}
return resp, err
}*/
// CallMethod functions call an method, defined <method> struct with authentication data
func (dev Device) SendSoap(endpoint string, xmlRequestBody string) (*http.Response, error) {
soap := gosoap.NewEmptySOAP()
soap.AddStringBodyContent(xmlRequestBody)
soap.AddRootNamespaces(Xlmns)
soap.AddAction()
//Auth Handling
if dev.params.Username != "" && dev.params.Password != "" {
soap.AddWSSecurity(dev.params.Username, dev.params.Password)
}
servResp, err := networking.SendSoap(dev.params.HttpClient, endpoint, soap.String())
if err != nil {
// Close server response body to reuse the connection
if servResp != nil {
servResp.Body.Close()
}
servResp, err = networking.SendSoapWithDigest(dev.params.HttpClient, endpoint, soap.String(), dev.params.Username, dev.params.Password)
}
return servResp, err
}
func createHttpRequest(httpMethod string, endpoint string, soap string) (req *http.Request, err error) {
req, err = http.NewRequest(httpMethod, endpoint, bytes.NewBufferString(soap))
if err != nil {
return nil, err
}
req.Header.Set(ContentType, "application/soap+xml; charset=utf-8")
return req, nil
}
func (dev *Device) CallOnvifFunction(serviceName, functionName string, data []byte) (interface{}, error) {
function, err := FunctionByServiceAndFunctionName(serviceName, functionName)
if err != nil {
return nil, err
}
request, err := createRequest(function, data)
if err != nil {
return nil, fmt.Errorf("fail to create '%s' request for the web service '%s', %v", functionName, serviceName, err)
}
endpoint, err := dev.GetEndpointByRequestStruct(request)
if err != nil {
return nil, err
}
requestBody, err := xml.Marshal(request)
if err != nil {
return nil, err
}
xmlRequestBody := string(requestBody)
servResp, err := dev.SendSoap(endpoint, xmlRequestBody)
if err != nil {
return nil, fmt.Errorf("fail to send the '%s' request for the web service '%s', %v", functionName, serviceName, err)
}
defer servResp.Body.Close()
rsp, err := ioutil.ReadAll(servResp.Body)
if err != nil {
return nil, err
}
responseEnvelope, err := createResponse(function, rsp)
if err != nil {
return nil, fmt.Errorf("fail to create '%s' response for the web service '%s', %v", functionName, serviceName, err)
}
if servResp.StatusCode == http.StatusUnauthorized {
return nil, fmt.Errorf("fail to verify the authentication for the function '%s' of web service '%s'. Onvif error: %s",
functionName, serviceName, responseEnvelope.Body.Fault.String())
} else if servResp.StatusCode == http.StatusBadRequest {
return nil, fmt.Errorf("invalid request for the function '%s' of web service '%s'. Onvif error: %s",
functionName, serviceName, responseEnvelope.Body.Fault.String())
} else if servResp.StatusCode > http.StatusNoContent {
return nil, fmt.Errorf("fail to execute the request for the function '%s' of web service '%s'. Onvif error: %s",
functionName, serviceName, responseEnvelope.Body.Fault.String())
}
return responseEnvelope.Body.Content, nil
}
func createRequest(function Function, data []byte) (interface{}, error) {
request := function.Request()
if len(data) > 0 {
err := json.Unmarshal(data, request)
if err != nil {
return nil, err
}
}
return request, nil
}
func createResponse(function Function, data []byte) (*gosoap.SOAPEnvelope, error) {
response := function.Response()
responseEnvelope := gosoap.NewSOAPEnvelope(response)
err := xml.Unmarshal(data, responseEnvelope)
if err != nil {
return nil, err
}
return responseEnvelope, nil
}
// SendGetSnapshotRequest sends the Get request to retrieve the snapshot from the Onvif camera
// The parameter url is come from the "GetSnapshotURI" command.
func (dev *Device) SendGetSnapshotRequest(url string) (resp *http.Response, err error) {
soap := gosoap.NewEmptySOAP()
soap.AddRootNamespaces(Xlmns)
if dev.params.AuthMode == UsernameTokenAuth {
soap.AddWSSecurity(dev.params.Username, dev.params.Password)
var req *http.Request
req, err = createHttpRequest(http.MethodGet, url, soap.String())
if err != nil {
return nil, err
}
// Basic auth might work for some camera
req.SetBasicAuth(dev.params.Username, dev.params.Password)
resp, err = dev.params.HttpClient.Do(req)
} else if dev.params.AuthMode == DigestAuth || dev.params.AuthMode == Both {
soap.AddWSSecurity(dev.params.Username, dev.params.Password)
resp, err = dev.digestClient.Do(http.MethodGet, url, soap.String())
} else {
var req *http.Request
req, err = createHttpRequest(http.MethodGet, url, soap.String())
if err != nil {
return nil, err
}
resp, err = dev.params.HttpClient.Do(req)
}
return resp, err
}

24
Device_test.go Normal file
View File

@@ -0,0 +1,24 @@
package onvif
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestDevice_SetDeviceInfoFromScopes(t *testing.T) {
const (
name = "DeviceName"
hardware = "M9000"
)
scopes := []string{
"onvif://www.onvif.org/Profile/Streaming",
"onvif://www.onvif.org/SomethingElse/value",
"onvif://www.onvif.org/name/" + name,
"onvif://www.onvif.org/hardware/" + hardware,
}
device := Device{}
device.SetDeviceInfoFromScopes(scopes)
assert.Equal(t, device.info.Name, name)
assert.Equal(t, device.info.Model, hardware)
}

21
LICENSE Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2018 Yakovlev Dmitry, Zhorzh Palanjyan,Crazybber
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -1,25 +1,20 @@
# onvif[golang]
# Onvif library
Simple management of onvif IP-devices cameras. onvif is an implementation of ONVIF protocol for managing onvif IP devices. The purpose of this library is convenient and easy management of IP cameras and other devices that support ONVIF standard.
## Installation
## Overview
To install the library, use **go get**:
```go
go get github.com/use-go/onvif
```
This repository is forked from: [use-go/onvif](https://github.com/use-go/onvif)
## Supported services
The following services are fully implemented:
The following services are implemented:
- Device
- Media
- PTZ
- Imaging
- Event
- Discovery
## Using
@@ -35,7 +30,7 @@ The following services are fully implemented:
If there is a device on the network at the address *192.168.13.42*, and its ONVIF services use the *1234* port, then you can connect to the device in the following way:
```go
dev, err := onvif.NewDevice("192.168.13.42:1234")
dev, err := onvif.NewDevice(onvif.DeviceParams{Xaddr: "192.168.13.42:1234"})
```
*The ONVIF port may differ depending on the device , to find out which port to use, you can go to the web interface of the device. **Usually this is 80 port.***
@@ -45,8 +40,7 @@ dev, err := onvif.NewDevice("192.168.13.42:1234")
If any function of the ONVIF services requires authentication, you must use the `Authenticate` method.
```go
device := onvif.NewDevice("192.168.13.42:1234")
device.Authenticate("username", "password")
device := onvif.NewDevice(onvif.DeviceParams{Xaddr: "192.168.13.42:1234", Username: "username", Password: password})
```
#### Defining Data Types
@@ -91,11 +85,10 @@ To perform any function of one of the ONVIF services whose structure has been de
```go
createUsers := device.CreateUsers{User: onvif.User{Username:"admin", Password:"qwerty", UserLevel:"User"}}
device := onvif.NewDevice("192.168.13.42:1234")
device := onvif.NewDevice(onvif.DeviceParams{Xaddr: "192.168.13.42:1234", Username: "username", Password: password})
device.Authenticate("username", "password")
resp, err := dev.CallMethod(createUsers)
```
## Great Thanks
Modified from: [goonvif](https://github.com/yakovlevdmv/goonvif)
## Development
See [here](docs/Development.md)

47
analytics/common.go Normal file
View File

@@ -0,0 +1,47 @@
package analytics
import "github.com/kerberos-io/onvif/xsd"
type Parameters struct {
SimpleItemDescription []SimpleItemDescription `json:",omitempty"`
ElementItemDescription []ElementItemDescription `json:",omitempty"`
Extension *xsd.String `json:",omitempty"`
}
type SimpleItemDescription struct {
Name string `json:",omitempty" xml:",attr"`
Type string `json:",omitempty" xml:",attr"`
Value string `json:",omitempty" xml:",attr"`
}
type ElementItemDescription struct {
Name string `json:",omitempty" xml:",attr"`
Value string `json:",omitempty" xml:",attr"`
}
type Messages struct {
IsProperty *xsd.Boolean `json:",omitempty" xml:",attr"`
Source *Source `json:",omitempty"`
Key *Key `json:",omitempty"`
Data *Data `json:",omitempty"`
Extension *xsd.String `json:",omitempty"`
ParentTopic *xsd.String `json:",omitempty"`
}
type Source struct {
SimpleItemDescription []SimpleItemDescription `json:",omitempty"`
ElementItemDescription []ElementItemDescription `json:",omitempty"`
Extension *xsd.String `json:",omitempty"`
}
type Key struct {
SimpleItemDescription []SimpleItemDescription `json:",omitempty"`
ElementItemDescription []ElementItemDescription `json:",omitempty"`
Extension *xsd.String `json:",omitempty"`
}
type Data struct {
SimpleItemDescription []SimpleItemDescription `json:",omitempty"`
ElementItemDescription []ElementItemDescription `json:",omitempty"`
Extension *xsd.String `json:",omitempty"`
}

117
analytics/function.go Normal file
View File

@@ -0,0 +1,117 @@
// -*- Mode: Go; indent-tabs-mode: t -*-
//
// Copyright (C) 2022 Intel Corporation
//
// SPDX-License-Identifier: Apache-2.0
// Code generated by gen_commands.py DO NOT EDIT.
package analytics
type CreateAnalyticsModulesFunction struct{}
func (_ *CreateAnalyticsModulesFunction) Request() interface{} {
return &CreateAnalyticsModules{}
}
func (_ *CreateAnalyticsModulesFunction) Response() interface{} {
return &CreateAnalyticsModulesResponse{}
}
type CreateRulesFunction struct{}
func (_ *CreateRulesFunction) Request() interface{} {
return &CreateRules{}
}
func (_ *CreateRulesFunction) Response() interface{} {
return &CreateRulesResponse{}
}
type DeleteAnalyticsModulesFunction struct{}
func (_ *DeleteAnalyticsModulesFunction) Request() interface{} {
return &DeleteAnalyticsModules{}
}
func (_ *DeleteAnalyticsModulesFunction) Response() interface{} {
return &DeleteAnalyticsModulesResponse{}
}
type DeleteRulesFunction struct{}
func (_ *DeleteRulesFunction) Request() interface{} {
return &DeleteRules{}
}
func (_ *DeleteRulesFunction) Response() interface{} {
return &DeleteRulesResponse{}
}
type GetAnalyticsModuleOptionsFunction struct{}
func (_ *GetAnalyticsModuleOptionsFunction) Request() interface{} {
return &GetAnalyticsModuleOptions{}
}
func (_ *GetAnalyticsModuleOptionsFunction) Response() interface{} {
return &GetAnalyticsModuleOptionsResponse{}
}
type GetAnalyticsModulesFunction struct{}
func (_ *GetAnalyticsModulesFunction) Request() interface{} {
return &GetAnalyticsModules{}
}
func (_ *GetAnalyticsModulesFunction) Response() interface{} {
return &GetAnalyticsModulesResponse{}
}
type GetRuleOptionsFunction struct{}
func (_ *GetRuleOptionsFunction) Request() interface{} {
return &GetRuleOptions{}
}
func (_ *GetRuleOptionsFunction) Response() interface{} {
return &GetRuleOptionsResponse{}
}
type GetRulesFunction struct{}
func (_ *GetRulesFunction) Request() interface{} {
return &GetRules{}
}
func (_ *GetRulesFunction) Response() interface{} {
return &GetRulesResponse{}
}
type GetSupportedAnalyticsModulesFunction struct{}
func (_ *GetSupportedAnalyticsModulesFunction) Request() interface{} {
return &GetSupportedAnalyticsModules{}
}
func (_ *GetSupportedAnalyticsModulesFunction) Response() interface{} {
return &GetSupportedAnalyticsModulesResponse{}
}
type GetSupportedRulesFunction struct{}
func (_ *GetSupportedRulesFunction) Request() interface{} {
return &GetSupportedRules{}
}
func (_ *GetSupportedRulesFunction) Response() interface{} {
return &GetSupportedRulesResponse{}
}
type ModifyAnalyticsModulesFunction struct{}
func (_ *ModifyAnalyticsModulesFunction) Request() interface{} {
return &ModifyAnalyticsModules{}
}
func (_ *ModifyAnalyticsModulesFunction) Response() interface{} {
return &ModifyAnalyticsModulesResponse{}
}
type ModifyRulesFunction struct{}
func (_ *ModifyRulesFunction) Request() interface{} {
return &ModifyRules{}
}
func (_ *ModifyRulesFunction) Response() interface{} {
return &ModifyRulesResponse{}
}

View File

@@ -1,78 +1,217 @@
package analytics
//go:generate python3 ../python/gen_commands.py
import (
"github.com/use-go/onvif/xsd"
"github.com/use-go/onvif/xsd/onvif"
"github.com/kerberos-io/onvif/xsd"
"github.com/kerberos-io/onvif/xsd/onvif"
)
// GetSupportedAnalyticsModules and its properties are defined in the Onvif specification:
// https://www.onvif.org/ver20/analytics/wsdl/analytics.wsdl#op.GetSupportedAnalyticsModules
type GetSupportedAnalyticsModules struct {
XMLName string `xml:"tan:GetSupportedAnalyticsModules"`
ConfigurationToken onvif.ReferenceToken `xml:"tan:ConfigurationToken"`
}
type GetSupportedAnalyticsModulesResponse struct {
SupportedAnalyticsModules SupportedAnalyticsModules
}
type SupportedAnalyticsModules struct {
Limit *xsd.Int `json:",omitempty"`
AnalyticsModuleContentSchemaLocation *xsd.String `json:",omitempty"`
AnalyticsModuleDescription []AnalyticsModuleDescription `json:",omitempty"`
}
type AnalyticsModuleDescription struct {
Name string `xml:"Name,attr"`
Fixed bool `xml:"fixed,attr"`
MaxInstances int `xml:"maxInstances,attr"`
Parameters *Parameters `json:",omitempty"`
Messages *Messages `json:",omitempty"`
}
// CreateAnalyticsModules and its properties are defined in the Onvif specification:
// https://www.onvif.org/ver20/analytics/wsdl/analytics.wsdl#op.CreateAnalyticsModules
type CreateAnalyticsModules struct {
XMLName string `xml:"tev:CreateAnalyticsModules"`
ConfigurationToken onvif.ReferenceToken `xml:"tan:ConfigurationToken"`
AnalyticsModule []onvif.ConfigRequest `xml:"tan:AnalyticsModule"`
}
type CreateAnalyticsModulesResponse struct{}
// DeleteAnalyticsModules and its properties are defined in the Onvif specification:
// https://www.onvif.org/ver20/analytics/wsdl/analytics.wsdl#op.DeleteAnalyticsModules
type DeleteAnalyticsModules struct {
XMLName string `xml:"tan:DeleteAnalyticsModules"`
ConfigurationToken onvif.ReferenceToken `xml:"tan:ConfigurationToken"`
AnalyticsModuleName []xsd.String `xml:"tan:AnalyticsModuleName"`
}
type DeleteAnalyticsModulesResponse struct{}
// GetAnalyticsModules and its properties are defined in the Onvif specification:
// https://www.onvif.org/ver20/analytics/wsdl/analytics.wsdl#op.GetAnalyticsModules
type GetAnalyticsModules struct {
XMLName string `xml:"tan:GetAnalyticsModules"`
ConfigurationToken onvif.ReferenceToken `xml:"tan:ConfigurationToken"`
}
type GetAnalyticsModulesResponse struct {
AnalyticsModule []onvif.Config
}
// GetAnalyticsModuleOptions and its properties are defined in the Onvif specification:
// https://www.onvif.org/ver20/analytics/wsdl/analytics.wsdl#op.GetAnalyticsModuleOptions
type GetAnalyticsModuleOptions struct {
XMLName string `xml:"tan:GetAnalyticsModuleOptions"`
Type xsd.QName `xml:"tan:Type,omitempty"`
ConfigurationToken onvif.ReferenceToken `xml:"tan:ConfigurationToken"`
}
type GetAnalyticsModuleOptionsResponse struct {
Options []AnalyticsModuleOptions
}
type AnalyticsModuleOptions struct {
RuleType string `json:",omitempty" xml:",attr"`
Name string `json:",omitempty" xml:",attr"`
Type string `json:",omitempty" xml:",attr"`
AnalyticsModule string `json:",omitempty" xml:",attr"`
IntRange *IntRange `json:",omitempty"`
StringItems *StringItems `json:",omitempty"`
}
type IntRange struct {
Min int
Max int
}
type StringItems struct {
Item []string
}
// ModifyAnalyticsModules and its properties are defined in the Onvif specification:
// https://www.onvif.org/ver20/analytics/wsdl/analytics.wsdl#op.ModifyAnalyticsModules
type ModifyAnalyticsModules struct {
XMLName string `xml:"tan:ModifyAnalyticsModules"`
ConfigurationToken onvif.ReferenceToken `xml:"tan:ConfigurationToken"`
AnalyticsModule []onvif.ConfigRequest `xml:"tan:AnalyticsModule"`
}
type ModifyAnalyticsModulesResponse struct{}
// GetSupportedRules and its properties are defined in the Onvif specification:
// https://www.onvif.org/ver20/analytics/wsdl/analytics.wsdl#op.GetSupportedRules
type GetSupportedRules struct {
XMLName string `xml:"tan:GetSupportedRules"`
ConfigurationToken onvif.ReferenceToken `xml:"tan:ConfigurationToken"`
}
type CreateRules struct {
XMLName string `xml:"tan:CreateRules"`
ConfigurationToken onvif.ReferenceToken `xml:"tan:ConfigurationToken"`
Rule onvif.Config `xml:"tan:Rule"`
type GetSupportedRulesResponse struct {
SupportedRules SupportedRules
}
type DeleteRules struct {
XMLName string `xml:"tan:DeleteRules"`
ConfigurationToken onvif.ReferenceToken `xml:"tan:ConfigurationToken"`
RuleName xsd.String `xml:"tan:RuleName"`
type SupportedRules struct {
Limit *xsd.Int `json:",omitempty"`
RuleContentSchemaLocation *xsd.String `json:",omitempty"`
RuleDescription []RuleDescription
}
type RuleDescription struct {
Name *xsd.String `json:",omitempty" xml:",attr"`
Fixed *xsd.Boolean `json:",omitempty" xml:"fixed,attr"`
MaxInstances *xsd.Int `json:",omitempty" xml:"maxInstances,attr"`
Parameters Parameters
Messages Messages `json:",omitempty"`
}
// GetRules and its properties are defined in the Onvif specification:
// https://www.onvif.org/ver20/analytics/wsdl/analytics.wsdl#op.GetRules
type GetRules struct {
XMLName string `xml:"tan:GetRules"`
ConfigurationToken onvif.ReferenceToken `xml:"tan:ConfigurationToken"`
}
type GetRulesResponse struct {
Rule []onvif.Config
}
// CreateRules and its properties are defined in the Onvif specification:
// https://www.onvif.org/ver20/analytics/wsdl/analytics.wsdl#op.CreateRules
type CreateRules struct {
XMLName string `xml:"tan:CreateRules"`
ConfigurationToken onvif.ReferenceToken `xml:"tan:ConfigurationToken"`
Rule []onvif.ConfigRequest `xml:"tan:Rule"`
}
type ItemListExtension xsd.AnyType
type CreateRulesResponse struct{}
// DeleteRules and its properties are defined in the Onvif specification:
// https://www.onvif.org/ver20/analytics/wsdl/analytics.wsdl#op.DeleteRules
type DeleteRules struct {
XMLName string `xml:"tan:DeleteRules"`
ConfigurationToken onvif.ReferenceToken `xml:"tan:ConfigurationToken"`
RuleName []xsd.String `xml:"tan:RuleName"`
}
type DeleteRulesResponse struct{}
// GetRuleOptions and its properties are defined in the Onvif specification:
// https://www.onvif.org/ver20/analytics/wsdl/analytics.wsdl#op.GetRuleOptions
type GetRuleOptions struct {
XMLName string `xml:"tan:GetRuleOptions"`
RuleType xsd.QName `xml:"tan:RuleType"`
ConfigurationToken onvif.ReferenceToken `xml:"tan:ConfigurationToken"`
}
type ModifyRules struct {
XMLName string `xml:"tan:ModifyRules"`
ConfigurationToken onvif.ReferenceToken `xml:"tan:ConfigurationToken"`
Rule onvif.Config `xml:"tan:Rule"`
type GetRuleOptionsResponse struct {
RuleOptions []RuleOptions
}
type RuleOptions struct {
RuleType *xsd.String `json:",omitempty"`
Name *xsd.String `json:",omitempty" xml:",attr"`
Type *xsd.String `json:",omitempty" xml:",attr"`
MinOccurs *xsd.String `json:",omitempty" xml:"minOccurs,attr"`
MaxOccurs *xsd.String `json:",omitempty" xml:"maxOccurs,attr"`
AnalyticsModule *xsd.String `json:",omitempty"`
IntRange *IntRange `json:",omitempty"`
StringItems *StringItems `json:",omitempty"`
PolygonOptions *PolygonOptions `json:",omitempty"`
MotionRegionConfigOptions *MotionRegionConfigOptions `json:",omitempty"`
StringList *xsd.String `json:",omitempty"`
}
type PolygonOptions struct {
VertexLimits VertexLimits
}
type VertexLimits struct {
Min int
Max int
}
type MotionRegionConfigOptions struct {
DisarmSupport bool
PolygonSupport bool
PolygonLimits VertexLimits
}
// ModifyRules and its properties are defined in the Onvif specification:
// https://www.onvif.org/ver20/analytics/wsdl/analytics.wsdl#op.ModifyRules
type ModifyRules struct {
XMLName string `xml:"tan:ModifyRules"`
ConfigurationToken onvif.ReferenceToken `xml:"tan:ConfigurationToken"`
Rule []onvif.ConfigRequest `xml:"tan:Rule"`
}
type ModifyRulesResponse struct{}
type GetServiceCapabilities struct {
XMLName string `xml:"tan:GetServiceCapabilities"`
}
type GetSupportedAnalyticsModules struct {
XMLName string `xml:"tan:GetSupportedAnalyticsModules"`
ConfigurationToken onvif.ReferenceToken `xml:"tan:ConfigurationToken"`
}
type GetAnalyticsModuleOptions struct {
XMLName string `xml:"tan:GetAnalyticsModuleOptions"`
Type xsd.QName `xml:"tan:Type"`
ConfigurationToken onvif.ReferenceToken `xml:"tan:ConfigurationToken"`
}
type CreateAnalyticsModules struct {
XMLName string `xml:"tev:CreateAnalyticsModules"`
ConfigurationToken onvif.ReferenceToken `xml:"tan:ConfigurationToken"`
AnalyticsModule onvif.Config `xml:"tan:AnalyticsModule"`
}
type DeleteAnalyticsModules struct {
XMLName string `xml:"tan:DeleteAnalyticsModules"`
ConfigurationToken onvif.ReferenceToken `xml:"tan:ConfigurationToken"`
AnalyticsModuleName xsd.String `xml:"tan:AnalyticsModuleName"`
}
type GetAnalyticsModules struct {
XMLName string `xml:"tan:GetAnalyticsModules"`
ConfigurationToken onvif.ReferenceToken `xml:"tan:ConfigurationToken"`
}
type ModifyAnalyticsModules struct {
XMLName string `xml:"tan:ModifyAnalyticsModules"`
ConfigurationToken onvif.ReferenceToken `xml:"tan:ConfigurationToken"`
AnalyticsModule onvif.Config `xml:"tan:AnalyticsModule"`
}

View File

@@ -12,10 +12,10 @@ import (
"github.com/beevik/etree"
"github.com/gin-gonic/gin"
"github.com/use-go/onvif"
"github.com/use-go/onvif/gosoap"
"github.com/use-go/onvif/networking"
wsdiscovery "github.com/use-go/onvif/ws-discovery"
"github.com/kerberos-io/onvif"
"github.com/kerberos-io/onvif/gosoap"
"github.com/kerberos-io/onvif/networking"
wsdiscovery "github.com/kerberos-io/onvif/ws-discovery"
)
func RunApi() {
@@ -50,7 +50,8 @@ func RunApi() {
interfaceName := context.GetHeader("interface")
var response = "["
devices := wsdiscovery.SendProbe(interfaceName, nil, []string{"dn:NetworkVideoTransmitter"}, map[string]string{"dn": "http://www.onvif.org/ver10/network/wsdl"})
// TODO: Handle this error.
devices, _ := wsdiscovery.SendProbe(interfaceName, nil, []string{"dn:NetworkVideoTransmitter"}, map[string]string{"dn": "http://www.onvif.org/ver10/network/wsdl"})
for _, j := range devices {
doc := etree.NewDocument()
@@ -121,6 +122,8 @@ func callNecessaryMethod(serviceName, methodName, acceptedData, username, passwo
switch strings.ToLower(serviceName) {
case "device":
methodStruct, err = getDeviceStructByName(methodName)
case "deviceio":
methodStruct, err = getDeviceStructByName(methodName)
case "ptz":
methodStruct, err = getPTZStructByName(methodName)
case "media":
@@ -147,9 +150,9 @@ func callNecessaryMethod(serviceName, methodName, acceptedData, username, passwo
soap.AddRootNamespaces(onvif.Xlmns)
soap.AddWSSecurity(username, password)
servResp, err := networking.SendSoap(endpoint, soap.String())
servResp, err := networking.SendSoap(new(http.Client), endpoint, soap.String())
if err != nil {
return "", err
servResp, err = networking.SendSoapWithDigest(new(http.Client), endpoint, soap.String(), username, password)
}
rsp, err := ioutil.ReadAll(servResp.Body)
@@ -161,7 +164,7 @@ func callNecessaryMethod(serviceName, methodName, acceptedData, username, passwo
}
func getEndpoint(service, xaddr string) (string, error) {
dev, err := onvif.NewDevice(xaddr)
dev, err := onvif.NewDevice(onvif.DeviceParams{Xaddr: xaddr})
if err != nil {
return "", err
}

View File

@@ -3,9 +3,9 @@ package api
import (
"errors"
"github.com/use-go/onvif/device"
"github.com/use-go/onvif/media"
"github.com/use-go/onvif/ptz"
"github.com/kerberos-io/onvif/device"
"github.com/kerberos-io/onvif/media"
"github.com/kerberos-io/onvif/ptz"
)
func getPTZStructByName(name string) (interface{}, error) {
@@ -201,6 +201,8 @@ func getDeviceStructByName(name string) (interface{}, error) {
return &device.SetClientCertificateMode{}, nil
case "GetRelayOutputs":
return &device.GetRelayOutputs{}, nil
case "GetDigitalInputs":
return &device.GetDigitalInputs{}, nil
case "SetRelayOutputSettings":
return &device.SetRelayOutputSettings{}, nil
case "SetRelayOutputState":

132
cmd/camera-example/main.go Normal file
View File

@@ -0,0 +1,132 @@
package main
import (
"encoding/json"
"encoding/xml"
"fmt"
"io/ioutil"
"net/http"
"github.com/kerberos-io/onvif"
"github.com/kerberos-io/onvif/gosoap"
"github.com/kerberos-io/onvif/networking"
"github.com/gin-gonic/gin"
)
func main() {
RunApi()
}
func RunApi() {
router := gin.Default()
router.POST("/:service/:function", func(c *gin.Context) {
c.Header("Access-Control-Allow-Origin", "*")
//c.Header("Access-Control-Allow-Headers", "access-control-allow-origin, access-control-allow-headers")
serviceName := c.Param("service")
functionName := c.Param("function")
username := c.GetHeader("username")
pass := c.GetHeader("password")
xaddr := c.GetHeader("xaddr")
acceptedData, err := c.GetRawData()
if err != nil {
fmt.Println(err)
}
dev, err := onvif.NewDevice(onvif.DeviceParams{
Xaddr: xaddr,
Username: username,
Password: pass,
})
message, err := CallOnvifFunction(dev, serviceName, functionName, string(acceptedData))
if err != nil {
c.XML(http.StatusBadRequest, err.Error())
} else {
c.String(http.StatusOK, message)
}
})
router.Run()
}
func CallOnvifFunction(dev *onvif.Device, serviceName, functionName, acceptedData string) (string, error) {
function, err := functionByServiceAndFunctionName(serviceName, functionName)
if err != nil {
return "", err
}
request := function.Request()
if len(acceptedData) > 0 {
err = json.Unmarshal([]byte(acceptedData), request)
if err != nil {
return "", err
}
}
requestBody, err := xml.Marshal(request)
if err != nil {
return "", err
}
endpoint, err := dev.GetEndpointByRequestStruct(request)
if err != nil {
return "", err
}
soap := gosoap.NewEmptySOAP()
soap.AddStringBodyContent(string(requestBody))
soap.AddRootNamespaces(onvif.Xlmns)
soap.AddWSSecurity(dev.GetDeviceParams().Username, dev.GetDeviceParams().Password)
servResp, err := networking.SendSoap(new(http.Client), endpoint, soap.String())
if err != nil {
return "", err
}
rsp, err := ioutil.ReadAll(servResp.Body)
if err != nil {
return "", err
}
responseEnvelope := gosoap.NewSOAPEnvelope(function.Response())
err = xml.Unmarshal(rsp, responseEnvelope)
if err != nil {
return "", err
}
if responseEnvelope.Body.Fault != nil {
jsonData, err := json.Marshal(responseEnvelope.Body.Fault)
if err != nil {
return "", err
}
return string(jsonData), nil
} else {
jsonData, err := json.Marshal(responseEnvelope.Body.Content)
if err != nil {
return "", err
}
return string(jsonData), nil
}
}
func functionByServiceAndFunctionName(serviceName, functionName string) (onvif.Function, error) {
var function onvif.Function
var exist bool
switch serviceName {
case onvif.DeviceWebService:
function, exist = onvif.DeviceFunctionMap[functionName]
if !exist {
return nil, fmt.Errorf("the web service '%s'not support the function '%s'", serviceName, functionName)
}
case onvif.MediaWebService:
function, exist = onvif.MediaFunctionMap[functionName]
if !exist {
return nil, fmt.Errorf("the web service '%s' not support the function '%s'", serviceName, functionName)
}
default:
return nil, fmt.Errorf("not support the web service '%s'", serviceName)
}
return function, nil
}

9
constant.go Normal file
View File

@@ -0,0 +1,9 @@
package onvif
// Onvif Auth Mode
const (
DigestAuth = "digest"
UsernameTokenAuth = "usernametoken"
Both = "both"
NoAuth = "none"
)

828
device/function.go Normal file
View File

@@ -0,0 +1,828 @@
// -*- Mode: Go; indent-tabs-mode: t -*-
//
// Copyright (C) 2022 Intel Corporation
//
// SPDX-License-Identifier: Apache-2.0
// Code generated by gen_commands.py DO NOT EDIT.
package device
type AddIPAddressFilterFunction struct{}
func (_ *AddIPAddressFilterFunction) Request() interface{} {
return &AddIPAddressFilter{}
}
func (_ *AddIPAddressFilterFunction) Response() interface{} {
return &AddIPAddressFilterResponse{}
}
type AddScopesFunction struct{}
func (_ *AddScopesFunction) Request() interface{} {
return &AddScopes{}
}
func (_ *AddScopesFunction) Response() interface{} {
return &AddScopesResponse{}
}
type CreateCertificateFunction struct{}
func (_ *CreateCertificateFunction) Request() interface{} {
return &CreateCertificate{}
}
func (_ *CreateCertificateFunction) Response() interface{} {
return &CreateCertificateResponse{}
}
type CreateDot1XConfigurationFunction struct{}
func (_ *CreateDot1XConfigurationFunction) Request() interface{} {
return &CreateDot1XConfiguration{}
}
func (_ *CreateDot1XConfigurationFunction) Response() interface{} {
return &CreateDot1XConfigurationResponse{}
}
type CreateStorageConfigurationFunction struct{}
func (_ *CreateStorageConfigurationFunction) Request() interface{} {
return &CreateStorageConfiguration{}
}
func (_ *CreateStorageConfigurationFunction) Response() interface{} {
return &CreateStorageConfigurationResponse{}
}
type CreateUsersFunction struct{}
func (_ *CreateUsersFunction) Request() interface{} {
return &CreateUsers{}
}
func (_ *CreateUsersFunction) Response() interface{} {
return &CreateUsersResponse{}
}
type DeleteCertificatesFunction struct{}
func (_ *DeleteCertificatesFunction) Request() interface{} {
return &DeleteCertificates{}
}
func (_ *DeleteCertificatesFunction) Response() interface{} {
return &DeleteCertificatesResponse{}
}
type DeleteDot1XConfigurationFunction struct{}
func (_ *DeleteDot1XConfigurationFunction) Request() interface{} {
return &DeleteDot1XConfiguration{}
}
func (_ *DeleteDot1XConfigurationFunction) Response() interface{} {
return &DeleteDot1XConfigurationResponse{}
}
type DeleteGeoLocationFunction struct{}
func (_ *DeleteGeoLocationFunction) Request() interface{} {
return &DeleteGeoLocation{}
}
func (_ *DeleteGeoLocationFunction) Response() interface{} {
return &DeleteGeoLocationResponse{}
}
type DeleteStorageConfigurationFunction struct{}
func (_ *DeleteStorageConfigurationFunction) Request() interface{} {
return &DeleteStorageConfiguration{}
}
func (_ *DeleteStorageConfigurationFunction) Response() interface{} {
return &DeleteStorageConfigurationResponse{}
}
type DeleteUsersFunction struct{}
func (_ *DeleteUsersFunction) Request() interface{} {
return &DeleteUsers{}
}
func (_ *DeleteUsersFunction) Response() interface{} {
return &DeleteUsersResponse{}
}
type GetAccessPolicyFunction struct{}
func (_ *GetAccessPolicyFunction) Request() interface{} {
return &GetAccessPolicy{}
}
func (_ *GetAccessPolicyFunction) Response() interface{} {
return &GetAccessPolicyResponse{}
}
type GetCACertificatesFunction struct{}
func (_ *GetCACertificatesFunction) Request() interface{} {
return &GetCACertificates{}
}
func (_ *GetCACertificatesFunction) Response() interface{} {
return &GetCACertificatesResponse{}
}
type GetCapabilitiesFunction struct{}
func (_ *GetCapabilitiesFunction) Request() interface{} {
return &GetCapabilities{}
}
func (_ *GetCapabilitiesFunction) Response() interface{} {
return &GetCapabilitiesResponse{}
}
type GetCertificateInformationFunction struct{}
func (_ *GetCertificateInformationFunction) Request() interface{} {
return &GetCertificateInformation{}
}
func (_ *GetCertificateInformationFunction) Response() interface{} {
return &GetCertificateInformationResponse{}
}
type GetCertificatesFunction struct{}
func (_ *GetCertificatesFunction) Request() interface{} {
return &GetCertificates{}
}
func (_ *GetCertificatesFunction) Response() interface{} {
return &GetCertificatesResponse{}
}
type GetCertificatesStatusFunction struct{}
func (_ *GetCertificatesStatusFunction) Request() interface{} {
return &GetCertificatesStatus{}
}
func (_ *GetCertificatesStatusFunction) Response() interface{} {
return &GetCertificatesStatusResponse{}
}
type GetClientCertificateModeFunction struct{}
func (_ *GetClientCertificateModeFunction) Request() interface{} {
return &GetClientCertificateMode{}
}
func (_ *GetClientCertificateModeFunction) Response() interface{} {
return &GetClientCertificateModeResponse{}
}
type GetDNSFunction struct{}
func (_ *GetDNSFunction) Request() interface{} {
return &GetDNS{}
}
func (_ *GetDNSFunction) Response() interface{} {
return &GetDNSResponse{}
}
type GetDPAddressesFunction struct{}
func (_ *GetDPAddressesFunction) Request() interface{} {
return &GetDPAddresses{}
}
func (_ *GetDPAddressesFunction) Response() interface{} {
return &GetDPAddressesResponse{}
}
type GetDeviceInformationFunction struct{}
func (_ *GetDeviceInformationFunction) Request() interface{} {
return &GetDeviceInformation{}
}
func (_ *GetDeviceInformationFunction) Response() interface{} {
return &GetDeviceInformationResponse{}
}
type GetDiscoveryModeFunction struct{}
func (_ *GetDiscoveryModeFunction) Request() interface{} {
return &GetDiscoveryMode{}
}
func (_ *GetDiscoveryModeFunction) Response() interface{} {
return &GetDiscoveryModeResponse{}
}
type GetDot11CapabilitiesFunction struct{}
func (_ *GetDot11CapabilitiesFunction) Request() interface{} {
return &GetDot11Capabilities{}
}
func (_ *GetDot11CapabilitiesFunction) Response() interface{} {
return &GetDot11CapabilitiesResponse{}
}
type GetDot11StatusFunction struct{}
func (_ *GetDot11StatusFunction) Request() interface{} {
return &GetDot11Status{}
}
func (_ *GetDot11StatusFunction) Response() interface{} {
return &GetDot11StatusResponse{}
}
type GetDot1XConfigurationFunction struct{}
func (_ *GetDot1XConfigurationFunction) Request() interface{} {
return &GetDot1XConfiguration{}
}
func (_ *GetDot1XConfigurationFunction) Response() interface{} {
return &GetDot1XConfigurationResponse{}
}
type GetDot1XConfigurationsFunction struct{}
func (_ *GetDot1XConfigurationsFunction) Request() interface{} {
return &GetDot1XConfigurations{}
}
func (_ *GetDot1XConfigurationsFunction) Response() interface{} {
return &GetDot1XConfigurationsResponse{}
}
type GetDynamicDNSFunction struct{}
func (_ *GetDynamicDNSFunction) Request() interface{} {
return &GetDynamicDNS{}
}
func (_ *GetDynamicDNSFunction) Response() interface{} {
return &GetDynamicDNSResponse{}
}
type GetEndpointReferenceFunction struct{}
func (_ *GetEndpointReferenceFunction) Request() interface{} {
return &GetEndpointReference{}
}
func (_ *GetEndpointReferenceFunction) Response() interface{} {
return &GetEndpointReferenceResponse{}
}
type GetGeoLocationFunction struct{}
func (_ *GetGeoLocationFunction) Request() interface{} {
return &GetGeoLocation{}
}
func (_ *GetGeoLocationFunction) Response() interface{} {
return &GetGeoLocationResponse{}
}
type GetHostnameFunction struct{}
func (_ *GetHostnameFunction) Request() interface{} {
return &GetHostname{}
}
func (_ *GetHostnameFunction) Response() interface{} {
return &GetHostnameResponse{}
}
type GetIPAddressFilterFunction struct{}
func (_ *GetIPAddressFilterFunction) Request() interface{} {
return &GetIPAddressFilter{}
}
func (_ *GetIPAddressFilterFunction) Response() interface{} {
return &GetIPAddressFilterResponse{}
}
type GetNTPFunction struct{}
func (_ *GetNTPFunction) Request() interface{} {
return &GetNTP{}
}
func (_ *GetNTPFunction) Response() interface{} {
return &GetNTPResponse{}
}
type GetNetworkDefaultGatewayFunction struct{}
func (_ *GetNetworkDefaultGatewayFunction) Request() interface{} {
return &GetNetworkDefaultGateway{}
}
func (_ *GetNetworkDefaultGatewayFunction) Response() interface{} {
return &GetNetworkDefaultGatewayResponse{}
}
type GetNetworkInterfacesFunction struct{}
func (_ *GetNetworkInterfacesFunction) Request() interface{} {
return &GetNetworkInterfaces{}
}
func (_ *GetNetworkInterfacesFunction) Response() interface{} {
return &GetNetworkInterfacesResponse{}
}
type GetNetworkProtocolsFunction struct{}
func (_ *GetNetworkProtocolsFunction) Request() interface{} {
return &GetNetworkProtocols{}
}
func (_ *GetNetworkProtocolsFunction) Response() interface{} {
return &GetNetworkProtocolsResponse{}
}
type GetPkcs10RequestFunction struct{}
func (_ *GetPkcs10RequestFunction) Request() interface{} {
return &GetPkcs10Request{}
}
func (_ *GetPkcs10RequestFunction) Response() interface{} {
return &GetPkcs10RequestResponse{}
}
type GetRelayOutputsFunction struct{}
func (_ *GetRelayOutputsFunction) Request() interface{} {
return &GetRelayOutputs{}
}
func (_ *GetRelayOutputsFunction) Response() interface{} {
return &GetRelayOutputsResponse{}
}
type GetDigitalInputsFunction struct{}
func (_ *GetDigitalInputsFunction) Request() interface{} {
return &GetDigitalInputs{}
}
func (_ *GetDigitalInputsFunction) Response() interface{} {
return &GetDigitalInputsResponse{}
}
type GetRemoteDiscoveryModeFunction struct{}
func (_ *GetRemoteDiscoveryModeFunction) Request() interface{} {
return &GetRemoteDiscoveryMode{}
}
func (_ *GetRemoteDiscoveryModeFunction) Response() interface{} {
return &GetRemoteDiscoveryModeResponse{}
}
type GetRemoteUserFunction struct{}
func (_ *GetRemoteUserFunction) Request() interface{} {
return &GetRemoteUser{}
}
func (_ *GetRemoteUserFunction) Response() interface{} {
return &GetRemoteUserResponse{}
}
type GetScopesFunction struct{}
func (_ *GetScopesFunction) Request() interface{} {
return &GetScopes{}
}
func (_ *GetScopesFunction) Response() interface{} {
return &GetScopesResponse{}
}
type GetServiceCapabilitiesFunction struct{}
func (_ *GetServiceCapabilitiesFunction) Request() interface{} {
return &GetServiceCapabilities{}
}
func (_ *GetServiceCapabilitiesFunction) Response() interface{} {
return &GetServiceCapabilitiesResponse{}
}
type GetServicesFunction struct{}
func (_ *GetServicesFunction) Request() interface{} {
return &GetServices{}
}
func (_ *GetServicesFunction) Response() interface{} {
return &GetServicesResponse{}
}
type GetStorageConfigurationFunction struct{}
func (_ *GetStorageConfigurationFunction) Request() interface{} {
return &GetStorageConfiguration{}
}
func (_ *GetStorageConfigurationFunction) Response() interface{} {
return &GetStorageConfigurationResponse{}
}
type GetStorageConfigurationsFunction struct{}
func (_ *GetStorageConfigurationsFunction) Request() interface{} {
return &GetStorageConfigurations{}
}
func (_ *GetStorageConfigurationsFunction) Response() interface{} {
return &GetStorageConfigurationsResponse{}
}
type GetSystemBackupFunction struct{}
func (_ *GetSystemBackupFunction) Request() interface{} {
return &GetSystemBackup{}
}
func (_ *GetSystemBackupFunction) Response() interface{} {
return &GetSystemBackupResponse{}
}
type GetSystemDateAndTimeFunction struct{}
func (_ *GetSystemDateAndTimeFunction) Request() interface{} {
return &GetSystemDateAndTime{}
}
func (_ *GetSystemDateAndTimeFunction) Response() interface{} {
return &GetSystemDateAndTimeResponse{}
}
type GetSystemLogFunction struct{}
func (_ *GetSystemLogFunction) Request() interface{} {
return &GetSystemLog{}
}
func (_ *GetSystemLogFunction) Response() interface{} {
return &GetSystemLogResponse{}
}
type GetSystemSupportInformationFunction struct{}
func (_ *GetSystemSupportInformationFunction) Request() interface{} {
return &GetSystemSupportInformation{}
}
func (_ *GetSystemSupportInformationFunction) Response() interface{} {
return &GetSystemSupportInformationResponse{}
}
type GetSystemUrisFunction struct{}
func (_ *GetSystemUrisFunction) Request() interface{} {
return &GetSystemUris{}
}
func (_ *GetSystemUrisFunction) Response() interface{} {
return &GetSystemUrisResponse{}
}
type GetUsersFunction struct{}
func (_ *GetUsersFunction) Request() interface{} {
return &GetUsers{}
}
func (_ *GetUsersFunction) Response() interface{} {
return &GetUsersResponse{}
}
type GetWsdlUrlFunction struct{}
func (_ *GetWsdlUrlFunction) Request() interface{} {
return &GetWsdlUrl{}
}
func (_ *GetWsdlUrlFunction) Response() interface{} {
return &GetWsdlUrlResponse{}
}
type GetZeroConfigurationFunction struct{}
func (_ *GetZeroConfigurationFunction) Request() interface{} {
return &GetZeroConfiguration{}
}
func (_ *GetZeroConfigurationFunction) Response() interface{} {
return &GetZeroConfigurationResponse{}
}
type LoadCACertificatesFunction struct{}
func (_ *LoadCACertificatesFunction) Request() interface{} {
return &LoadCACertificates{}
}
func (_ *LoadCACertificatesFunction) Response() interface{} {
return &LoadCACertificatesResponse{}
}
type LoadCertificateWithPrivateKeyFunction struct{}
func (_ *LoadCertificateWithPrivateKeyFunction) Request() interface{} {
return &LoadCertificateWithPrivateKey{}
}
func (_ *LoadCertificateWithPrivateKeyFunction) Response() interface{} {
return &LoadCertificateWithPrivateKeyResponse{}
}
type LoadCertificatesFunction struct{}
func (_ *LoadCertificatesFunction) Request() interface{} {
return &LoadCertificates{}
}
func (_ *LoadCertificatesFunction) Response() interface{} {
return &LoadCertificatesResponse{}
}
type RemoveIPAddressFilterFunction struct{}
func (_ *RemoveIPAddressFilterFunction) Request() interface{} {
return &RemoveIPAddressFilter{}
}
func (_ *RemoveIPAddressFilterFunction) Response() interface{} {
return &RemoveIPAddressFilterResponse{}
}
type RemoveScopesFunction struct{}
func (_ *RemoveScopesFunction) Request() interface{} {
return &RemoveScopes{}
}
func (_ *RemoveScopesFunction) Response() interface{} {
return &RemoveScopesResponse{}
}
type RestoreSystemFunction struct{}
func (_ *RestoreSystemFunction) Request() interface{} {
return &RestoreSystem{}
}
func (_ *RestoreSystemFunction) Response() interface{} {
return &RestoreSystemResponse{}
}
type ScanAvailableDot11NetworksFunction struct{}
func (_ *ScanAvailableDot11NetworksFunction) Request() interface{} {
return &ScanAvailableDot11Networks{}
}
func (_ *ScanAvailableDot11NetworksFunction) Response() interface{} {
return &ScanAvailableDot11NetworksResponse{}
}
type SendAuxiliaryCommandFunction struct{}
func (_ *SendAuxiliaryCommandFunction) Request() interface{} {
return &SendAuxiliaryCommand{}
}
func (_ *SendAuxiliaryCommandFunction) Response() interface{} {
return &SendAuxiliaryCommandResponse{}
}
type SetAccessPolicyFunction struct{}
func (_ *SetAccessPolicyFunction) Request() interface{} {
return &SetAccessPolicy{}
}
func (_ *SetAccessPolicyFunction) Response() interface{} {
return &SetAccessPolicyResponse{}
}
type SetCertificatesStatusFunction struct{}
func (_ *SetCertificatesStatusFunction) Request() interface{} {
return &SetCertificatesStatus{}
}
func (_ *SetCertificatesStatusFunction) Response() interface{} {
return &SetCertificatesStatusResponse{}
}
type SetClientCertificateModeFunction struct{}
func (_ *SetClientCertificateModeFunction) Request() interface{} {
return &SetClientCertificateMode{}
}
func (_ *SetClientCertificateModeFunction) Response() interface{} {
return &SetClientCertificateModeResponse{}
}
type SetDNSFunction struct{}
func (_ *SetDNSFunction) Request() interface{} {
return &SetDNS{}
}
func (_ *SetDNSFunction) Response() interface{} {
return &SetDNSResponse{}
}
type SetDPAddressesFunction struct{}
func (_ *SetDPAddressesFunction) Request() interface{} {
return &SetDPAddresses{}
}
func (_ *SetDPAddressesFunction) Response() interface{} {
return &SetDPAddressesResponse{}
}
type SetDiscoveryModeFunction struct{}
func (_ *SetDiscoveryModeFunction) Request() interface{} {
return &SetDiscoveryMode{}
}
func (_ *SetDiscoveryModeFunction) Response() interface{} {
return &SetDiscoveryModeResponse{}
}
type SetDot1XConfigurationFunction struct{}
func (_ *SetDot1XConfigurationFunction) Request() interface{} {
return &SetDot1XConfiguration{}
}
func (_ *SetDot1XConfigurationFunction) Response() interface{} {
return &SetDot1XConfigurationResponse{}
}
type SetDynamicDNSFunction struct{}
func (_ *SetDynamicDNSFunction) Request() interface{} {
return &SetDynamicDNS{}
}
func (_ *SetDynamicDNSFunction) Response() interface{} {
return &SetDynamicDNSResponse{}
}
type SetGeoLocationFunction struct{}
func (_ *SetGeoLocationFunction) Request() interface{} {
return &SetGeoLocation{}
}
func (_ *SetGeoLocationFunction) Response() interface{} {
return &SetGeoLocationResponse{}
}
type SetHostnameFunction struct{}
func (_ *SetHostnameFunction) Request() interface{} {
return &SetHostname{}
}
func (_ *SetHostnameFunction) Response() interface{} {
return &SetHostnameResponse{}
}
type SetHostnameFromDHCPFunction struct{}
func (_ *SetHostnameFromDHCPFunction) Request() interface{} {
return &SetHostnameFromDHCP{}
}
func (_ *SetHostnameFromDHCPFunction) Response() interface{} {
return &SetHostnameFromDHCPResponse{}
}
type SetIPAddressFilterFunction struct{}
func (_ *SetIPAddressFilterFunction) Request() interface{} {
return &SetIPAddressFilter{}
}
func (_ *SetIPAddressFilterFunction) Response() interface{} {
return &SetIPAddressFilterResponse{}
}
type SetNTPFunction struct{}
func (_ *SetNTPFunction) Request() interface{} {
return &SetNTP{}
}
func (_ *SetNTPFunction) Response() interface{} {
return &SetNTPResponse{}
}
type SetNetworkDefaultGatewayFunction struct{}
func (_ *SetNetworkDefaultGatewayFunction) Request() interface{} {
return &SetNetworkDefaultGateway{}
}
func (_ *SetNetworkDefaultGatewayFunction) Response() interface{} {
return &SetNetworkDefaultGatewayResponse{}
}
type SetNetworkInterfacesFunction struct{}
func (_ *SetNetworkInterfacesFunction) Request() interface{} {
return &SetNetworkInterfaces{}
}
func (_ *SetNetworkInterfacesFunction) Response() interface{} {
return &SetNetworkInterfacesResponse{}
}
type SetNetworkProtocolsFunction struct{}
func (_ *SetNetworkProtocolsFunction) Request() interface{} {
return &SetNetworkProtocols{}
}
func (_ *SetNetworkProtocolsFunction) Response() interface{} {
return &SetNetworkProtocolsResponse{}
}
type SetRelayOutputSettingsFunction struct{}
func (_ *SetRelayOutputSettingsFunction) Request() interface{} {
return &SetRelayOutputSettings{}
}
func (_ *SetRelayOutputSettingsFunction) Response() interface{} {
return &SetRelayOutputSettingsResponse{}
}
type SetRelayOutputStateFunction struct{}
func (_ *SetRelayOutputStateFunction) Request() interface{} {
return &SetRelayOutputState{}
}
func (_ *SetRelayOutputStateFunction) Response() interface{} {
return &SetRelayOutputStateResponse{}
}
type SetRemoteDiscoveryModeFunction struct{}
func (_ *SetRemoteDiscoveryModeFunction) Request() interface{} {
return &SetRemoteDiscoveryMode{}
}
func (_ *SetRemoteDiscoveryModeFunction) Response() interface{} {
return &SetRemoteDiscoveryModeResponse{}
}
type SetRemoteUserFunction struct{}
func (_ *SetRemoteUserFunction) Request() interface{} {
return &SetRemoteUser{}
}
func (_ *SetRemoteUserFunction) Response() interface{} {
return &SetRemoteUserResponse{}
}
type SetScopesFunction struct{}
func (_ *SetScopesFunction) Request() interface{} {
return &SetScopes{}
}
func (_ *SetScopesFunction) Response() interface{} {
return &SetScopesResponse{}
}
type SetStorageConfigurationFunction struct{}
func (_ *SetStorageConfigurationFunction) Request() interface{} {
return &SetStorageConfiguration{}
}
func (_ *SetStorageConfigurationFunction) Response() interface{} {
return &SetStorageConfigurationResponse{}
}
type SetSystemDateAndTimeFunction struct{}
func (_ *SetSystemDateAndTimeFunction) Request() interface{} {
return &SetSystemDateAndTime{}
}
func (_ *SetSystemDateAndTimeFunction) Response() interface{} {
return &SetSystemDateAndTimeResponse{}
}
type SetSystemFactoryDefaultFunction struct{}
func (_ *SetSystemFactoryDefaultFunction) Request() interface{} {
return &SetSystemFactoryDefault{}
}
func (_ *SetSystemFactoryDefaultFunction) Response() interface{} {
return &SetSystemFactoryDefaultResponse{}
}
type SetUserFunction struct{}
func (_ *SetUserFunction) Request() interface{} {
return &SetUser{}
}
func (_ *SetUserFunction) Response() interface{} {
return &SetUserResponse{}
}
type SetZeroConfigurationFunction struct{}
func (_ *SetZeroConfigurationFunction) Request() interface{} {
return &SetZeroConfiguration{}
}
func (_ *SetZeroConfigurationFunction) Response() interface{} {
return &SetZeroConfigurationResponse{}
}
type StartFirmwareUpgradeFunction struct{}
func (_ *StartFirmwareUpgradeFunction) Request() interface{} {
return &StartFirmwareUpgrade{}
}
func (_ *StartFirmwareUpgradeFunction) Response() interface{} {
return &StartFirmwareUpgradeResponse{}
}
type StartSystemRestoreFunction struct{}
func (_ *StartSystemRestoreFunction) Request() interface{} {
return &StartSystemRestore{}
}
func (_ *StartSystemRestoreFunction) Response() interface{} {
return &StartSystemRestoreResponse{}
}
type SystemRebootFunction struct{}
func (_ *SystemRebootFunction) Request() interface{} {
return &SystemReboot{}
}
func (_ *SystemRebootFunction) Response() interface{} {
return &SystemRebootResponse{}
}
type UpgradeSystemFirmwareFunction struct{}
func (_ *UpgradeSystemFirmwareFunction) Request() interface{} {
return &UpgradeSystemFirmware{}
}
func (_ *UpgradeSystemFirmwareFunction) Response() interface{} {
return &UpgradeSystemFirmwareResponse{}
}

View File

@@ -1,8 +1,10 @@
package device
//go:generate python3 ../python/gen_commands.py
import (
"github.com/use-go/onvif/xsd"
"github.com/use-go/onvif/xsd/onvif"
"github.com/kerberos-io/onvif/xsd"
"github.com/kerberos-io/onvif/xsd/onvif"
)
type Service struct {
@@ -36,28 +38,24 @@ type NetworkCapabilities struct {
}
type SecurityCapabilities struct {
TLS1_0 xsd.Boolean `xml:"TLS1_0,attr"`
TLS1_1 xsd.Boolean `xml:"TLS1_1,attr"`
TLS1_2 xsd.Boolean `xml:"TLS1_2,attr"`
OnboardKeyGeneration xsd.Boolean `xml:"OnboardKeyGeneration,attr"`
AccessPolicyConfig xsd.Boolean `xml:"AccessPolicyConfig,attr"`
DefaultAccessPolicy xsd.Boolean `xml:"DefaultAccessPolicy,attr"`
Dot1X xsd.Boolean `xml:"Dot1X,attr"`
RemoteUserHandling xsd.Boolean `xml:"RemoteUserHandling,attr"`
X_509Token xsd.Boolean `xml:"X_509Token,attr"`
SAMLToken xsd.Boolean `xml:"SAMLToken,attr"`
KerberosToken xsd.Boolean `xml:"KerberosToken,attr"`
UsernameToken xsd.Boolean `xml:"UsernameToken,attr"`
HttpDigest xsd.Boolean `xml:"HttpDigest,attr"`
RELToken xsd.Boolean `xml:"RELToken,attr"`
SupportedEAPMethods EAPMethodTypes `xml:"SupportedEAPMethods,attr"`
MaxUsers int `xml:"MaxUsers,attr"`
MaxUserNameLength int `xml:"MaxUserNameLength,attr"`
MaxPasswordLength int `xml:"MaxPasswordLength,attr"`
}
type EAPMethodTypes struct {
Types []int
TLS1_0 xsd.Boolean `xml:"TLS1_0,attr"`
TLS1_1 xsd.Boolean `xml:"TLS1_1,attr"`
TLS1_2 xsd.Boolean `xml:"TLS1_2,attr"`
OnboardKeyGeneration xsd.Boolean `xml:"OnboardKeyGeneration,attr"`
AccessPolicyConfig xsd.Boolean `xml:"AccessPolicyConfig,attr"`
DefaultAccessPolicy xsd.Boolean `xml:"DefaultAccessPolicy,attr"`
Dot1X xsd.Boolean `xml:"Dot1X,attr"`
RemoteUserHandling xsd.Boolean `xml:"RemoteUserHandling,attr"`
X_509Token xsd.Boolean `xml:"X_509Token,attr"`
SAMLToken xsd.Boolean `xml:"SAMLToken,attr"`
KerberosToken xsd.Boolean `xml:"KerberosToken,attr"`
UsernameToken xsd.Boolean `xml:"UsernameToken,attr"`
HttpDigest xsd.Boolean `xml:"HttpDigest,attr"`
RELToken xsd.Boolean `xml:"RELToken,attr"`
SupportedEAPMethods onvif.IntAttrList `xml:"SupportedEAPMethods,attr"`
MaxUsers int `xml:"MaxUsers,attr"`
MaxUserNameLength int `xml:"MaxUserNameLength,attr"`
MaxPasswordLength int `xml:"MaxPasswordLength,attr"`
}
type SystemCapabilities struct {
@@ -73,6 +71,7 @@ type SystemCapabilities struct {
HttpSupportInformation xsd.Boolean `xml:"HttpSupportInformation,attr"`
StorageConfiguration xsd.Boolean `xml:"StorageConfiguration,attr"`
MaxStorageConfigurations int `xml:"MaxStorageConfigurations,attr"`
StorageTypesSupported onvif.StringAttrList `xml:"StorageTypesSupported,attr"`
GeoLocationEntries int `xml:"GeoLocationEntries,attr"`
AutoGeo onvif.StringAttrList `xml:"AutoGeo,attr"`
}
@@ -83,11 +82,23 @@ type MiscCapabilities struct {
type StorageConfiguration struct {
onvif.DeviceEntity
Data StorageConfigurationData `xml:"tds:Data"`
Data struct {
Type xsd.String `xml:"type,attr"`
Region string
LocalPath xsd.AnyURI
StorageUri xsd.AnyURI
User struct {
UserName xsd.String
Password xsd.String `json:",omitempty"`
Extension xsd.AnyType `json:",omitempty"`
}
Extension xsd.AnyURI `json:",omitempty"`
}
}
type StorageConfigurationData struct {
Type xsd.String `xml:"type,attr"`
Region string `xml:"tds:Region,omitempty"`
LocalPath xsd.AnyURI `xml:"tds:LocalPath"`
StorageUri xsd.AnyURI `xml:"tds:StorageUri"`
User UserCredential `xml:"tds:User"`
@@ -131,12 +142,14 @@ type GetDeviceInformationResponse struct {
HardwareId string
}
// SetSystemDateAndTime and its properties are defined in the Onvif specification:
// https://www.onvif.org/ver10/device/wsdl/devicemgmt.wsdl#op.SetSystemDateAndTime
type SetSystemDateAndTime struct {
XMLName string `xml:"tds:SetSystemDateAndTime"`
DateTimeType onvif.SetDateTimeType `xml:"tds:DateTimeType"`
DaylightSavings xsd.Boolean `xml:"tds:DaylightSavings"`
TimeZone onvif.TimeZone `xml:"tds:TimeZone"`
UTCDateTime onvif.DateTime `xml:"tds:UTCDateTime"`
XMLName string `xml:"tds:SetSystemDateAndTime,omitempty"`
DateTimeType *onvif.SetDateTimeType `xml:"tds:DateTimeType,omitempty"`
DaylightSavings *xsd.Boolean `xml:"tds:DaylightSavings,omitempty"`
TimeZone *onvif.TimeZone `xml:"tds:TimeZone,omitempty"`
UTCDateTime *onvif.DateTimeRequest `xml:"tds:UTCDateTime,omitempty"`
}
type SetSystemDateAndTimeResponse struct {
@@ -150,6 +163,8 @@ type GetSystemDateAndTimeResponse struct {
SystemDateAndTime onvif.SystemDateTime
}
// SetSystemFactoryDefault and its properties are defined in the Onvif specification:
// https://www.onvif.org/ver10/device/wsdl/devicemgmt.wsdl#op.SetSystemFactoryDefault
type SetSystemFactoryDefault struct {
XMLName string `xml:"tds:SetSystemFactoryDefault"`
FactoryDefault onvif.FactoryDefaultType `xml:"tds:FactoryDefault"`
@@ -167,6 +182,8 @@ type UpgradeSystemFirmwareResponse struct {
Message string
}
// SystemReboot and its properties are defined in the Onvif specification:
// https://www.onvif.org/ver10/device/wsdl/devicemgmt.wsdl#op.SystemReboot
type SystemReboot struct {
XMLName string `xml:"tds:SystemReboot"`
}
@@ -175,7 +192,7 @@ type SystemRebootResponse struct {
Message string
}
//TODO: one or more repetitions
// TODO: one or more repetitions
type RestoreSystem struct {
XMLName string `xml:"tds:RestoreSystem"`
BackupFiles onvif.BackupFile `xml:"tds:BackupFiles"`
@@ -214,37 +231,40 @@ type GetScopes struct {
}
type GetScopesResponse struct {
Scopes onvif.Scope
Scopes []onvif.Scope
}
//TODO: one or more scopes
// SetScopes and its properties are defined in the Onvif specification:
// https://www.onvif.org/ver10/device/wsdl/devicemgmt.wsdl#op.SetScopes
type SetScopes struct {
XMLName string `xml:"tds:SetScopes"`
Scopes xsd.AnyURI `xml:"tds:Scopes"`
XMLName string `xml:"tds:SetScopes"`
Scopes []xsd.AnyURI `xml:"tds:Scopes"`
}
type SetScopesResponse struct {
}
//TODO: list of scopes
// AddScopes and its properties are defined in the Onvif specification:
// https://www.onvif.org/ver10/device/wsdl/devicemgmt.wsdl#op.AddScopes
type AddScopes struct {
XMLName string `xml:"tds:AddScopes"`
ScopeItem xsd.AnyURI `xml:"tds:ScopeItem"`
XMLName string `xml:"tds:AddScopes"`
ScopeItem []xsd.AnyURI `xml:"tds:ScopeItem"`
}
type AddScopesResponse struct {
}
//TODO: One or more repetitions
type RemoveScopes struct {
XMLName string `xml:"tds:RemoveScopes"`
ScopeItem xsd.AnyURI `xml:"onvif:ScopeItem"`
XMLName string `xml:"tds:RemoveScopes"`
ScopeItem []xsd.AnyURI `xml:"tds:ScopeItem"`
}
type RemoveScopesResponse struct {
ScopeItem xsd.AnyURI
}
// GetDiscoveryMode and its properties are defined in the Onvif specification:
// https://www.onvif.org/ver10/device/wsdl/devicemgmt.wsdl#op.GetDiscoveryMode
type GetDiscoveryMode struct {
XMLName string `xml:"tds:GetDiscoveryMode"`
}
@@ -253,6 +273,8 @@ type GetDiscoveryModeResponse struct {
DiscoveryMode onvif.DiscoveryMode
}
// SetDiscoveryMode and its properties are defined in the Onvif specification:
// https://www.onvif.org/ver10/device/wsdl/devicemgmt.wsdl#op.SetDiscoveryMode
type SetDiscoveryMode struct {
XMLName string `xml:"tds:SetDiscoveryMode"`
DiscoveryMode onvif.DiscoveryMode `xml:"tds:DiscoveryMode"`
@@ -322,30 +344,34 @@ type GetUsers struct {
}
type GetUsersResponse struct {
User onvif.User
User []onvif.User
}
//TODO: List of users
// CreateUsers and its properties are defined in the Onvif specification:
// https://www.onvif.org/ver10/device/wsdl/devicemgmt.wsdl#op.CreateUsers
type CreateUsers struct {
XMLName string `xml:"tds:CreateUsers"`
User onvif.User `xml:"tds:User,omitempty"`
XMLName string `xml:"tds:CreateUsers"`
User []onvif.UserRequest `xml:"tds:User,omitempty"`
}
type CreateUsersResponse struct {
}
//TODO: one or more Username
// DeleteUsers and its properties are defined in the Onvif specification:
// https://www.onvif.org/ver10/device/wsdl/devicemgmt.wsdl#op.DeleteUsers
type DeleteUsers struct {
XMLName xsd.String `xml:"tds:DeleteUsers"`
Username xsd.String `xml:"tds:Username"`
XMLName xsd.String `xml:"tds:DeleteUsers"`
Username []xsd.String `xml:"tds:Username"`
}
type DeleteUsersResponse struct {
}
// SetUser and its properties are defined in the Onvif specification:
// https://www.onvif.org/ver10/device/wsdl/devicemgmt.wsdl#op.SetUser
type SetUser struct {
XMLName string `xml:"tds:SetUser"`
User onvif.User `xml:"tds:User"`
XMLName string `xml:"tds:SetUser"`
User []onvif.UserRequest `xml:"tds:User"`
}
type SetUserResponse struct {
@@ -360,8 +386,8 @@ type GetWsdlUrlResponse struct {
}
type GetCapabilities struct {
XMLName string `xml:"tds:GetCapabilities"`
Category onvif.CapabilityCategory `xml:"tds:Category"`
XMLName string `xml:"tds:GetCapabilities"`
Category []onvif.CapabilityCategory `xml:"tds:Category"`
}
type GetCapabilitiesResponse struct {
@@ -402,10 +428,10 @@ type GetDNSResponse struct {
}
type SetDNS struct {
XMLName string `xml:"tds:SetDNS"`
FromDHCP xsd.Boolean `xml:"tds:FromDHCP"`
SearchDomain xsd.Token `xml:"tds:SearchDomain"`
DNSManual onvif.IPAddress `xml:"tds:DNSManual"`
XMLName string `xml:"tds:SetDNS"`
FromDHCP *xsd.Boolean `xml:"tds:FromDHCP,omitempty"`
SearchDomain *xsd.Token `xml:"tds:SearchDomain,omitempty"`
DNSManual *onvif.IPAddress `xml:"tds:DNSManual,omitempty"`
}
type SetDNSResponse struct {
@@ -455,9 +481,9 @@ type GetNetworkInterfacesResponse struct {
}
type SetNetworkInterfaces struct {
XMLName string `xml:"tds:SetNetworkInterfaces"`
InterfaceToken onvif.ReferenceToken `xml:"tds:InterfaceToken"`
NetworkInterface onvif.NetworkInterfaceSetConfiguration `xml:"tds:NetworkInterface"`
XMLName string `xml:"tds:SetNetworkInterfaces"`
InterfaceToken *onvif.ReferenceToken `xml:"tds:InterfaceToken,omitempty"`
NetworkInterface *onvif.NetworkInterfaceSetConfiguration `xml:"tds:NetworkInterface,omitempty"`
}
type SetNetworkInterfacesResponse struct {
@@ -469,12 +495,12 @@ type GetNetworkProtocols struct {
}
type GetNetworkProtocolsResponse struct {
NetworkProtocols onvif.NetworkProtocol
NetworkProtocols []onvif.NetworkProtocolResponse
}
type SetNetworkProtocols struct {
XMLName string `xml:"tds:SetNetworkProtocols"`
NetworkProtocols onvif.NetworkProtocol `xml:"tds:NetworkProtocols"`
XMLName string `xml:"tds:SetNetworkProtocols"`
NetworkProtocols []onvif.NetworkProtocolRequest `xml:"tds:NetworkProtocols"`
}
type SetNetworkProtocolsResponse struct {
@@ -490,8 +516,8 @@ type GetNetworkDefaultGatewayResponse struct {
type SetNetworkDefaultGateway struct {
XMLName string `xml:"tds:SetNetworkDefaultGateway"`
IPv4Address onvif.IPv4Address `xml:"tds:IPv4Address"`
IPv6Address onvif.IPv6Address `xml:"tds:IPv6Address"`
IPv4Address onvif.IPv4Address `xml:"tds:IPv4Address,omitempty"`
IPv6Address onvif.IPv6Address `xml:"tds:IPv6Address,omitempty"`
}
type SetNetworkDefaultGatewayResponse struct {
@@ -530,11 +556,11 @@ type SetIPAddressFilter struct {
type SetIPAddressFilterResponse struct {
}
//This operation adds an IP filter address to a device.
//If the device supports device access control based on
//IP filtering rules (denied or accepted ranges of IP addresses),
//the device shall support adding of IP filtering addresses through
//the AddIPAddressFilter command.
// This operation adds an IP filter address to a device.
// If the device supports device access control based on
// IP filtering rules (denied or accepted ranges of IP addresses),
// the device shall support adding of IP filtering addresses through
// the AddIPAddressFilter command.
type AddIPAddressFilter struct {
XMLName string `xml:"tds:AddIPAddressFilter"`
IPAddressFilter onvif.IPAddressFilter `xml:"tds:IPAddressFilter"`
@@ -545,7 +571,7 @@ type AddIPAddressFilterResponse struct {
type RemoveIPAddressFilter struct {
XMLName string `xml:"tds:RemoveIPAddressFilter"`
IPAddressFilter onvif.IPAddressFilter `xml:"onvif:IPAddressFilter"`
IPAddressFilter onvif.IPAddressFilter `xml:"IPAddressFilter"`
}
type RemoveIPAddressFilterResponse struct {
@@ -603,7 +629,7 @@ type SetCertificatesStatus struct {
type SetCertificatesStatusResponse struct {
}
//TODO: List of CertificateID
// TODO: List of CertificateID
type DeleteCertificates struct {
XMLName string `xml:"tds:DeleteCertificates"`
CertificateID xsd.Token `xml:"tds:CertificateID"`
@@ -612,7 +638,7 @@ type DeleteCertificates struct {
type DeleteCertificatesResponse struct {
}
//TODO: Откуда onvif:data = cid:21312413412
// TODO: Откуда onvif:data = cid:21312413412
type GetPkcs10Request struct {
XMLName string `xml:"tds:GetPkcs10Request"`
CertificateID xsd.Token `xml:"tds:CertificateID"`
@@ -624,7 +650,7 @@ type GetPkcs10RequestResponse struct {
Pkcs10Request onvif.BinaryData
}
//TODO: one or more NTVCertificate
// TODO: one or more NTVCertificate
type LoadCertificates struct {
XMLName string `xml:"tds:LoadCertificates"`
NVTCertificate onvif.Certificate `xml:"tds:NVTCertificate"`
@@ -654,7 +680,15 @@ type GetRelayOutputs struct {
}
type GetRelayOutputsResponse struct {
RelayOutputs onvif.RelayOutput
RelayOutputs []onvif.RelayOutput
}
type GetDigitalInputs struct {
XMLName string `xml:"tmd:GetDigitalInputs"`
}
type GetDigitalInputsResponse struct {
DigitalInputs []onvif.DigitalInput
}
type SetRelayOutputSettings struct {
@@ -692,7 +726,7 @@ type GetCACertificatesResponse struct {
CACertificate onvif.Certificate
}
//TODO: one or more CertificateWithPrivateKey
// TODO: one or more CertificateWithPrivateKey
type LoadCertificateWithPrivateKey struct {
XMLName string `xml:"tds:LoadCertificateWithPrivateKey"`
CertificateWithPrivateKey onvif.CertificateWithPrivateKey `xml:"tds:CertificateWithPrivateKey"`
@@ -751,7 +785,7 @@ type GetDot1XConfigurationsResponse struct {
Dot1XConfiguration onvif.Dot1XConfiguration
}
//TODO: Zero or more Dot1XConfigurationToken
// TODO: Zero or more Dot1XConfigurationToken
type DeleteDot1XConfiguration struct {
XMLName string `xml:"tds:DeleteDot1XConfiguration"`
Dot1XConfigurationToken onvif.ReferenceToken `xml:"tds:Dot1XConfigurationToken"`
@@ -821,12 +855,12 @@ type GetStorageConfigurations struct {
}
type GetStorageConfigurationsResponse struct {
StorageConfigurations StorageConfiguration
StorageConfigurations []StorageConfiguration
}
type CreateStorageConfiguration struct {
XMLName string `xml:"tds:CreateStorageConfiguration"`
StorageConfiguration StorageConfigurationData
XMLName string `xml:"tds:CreateStorageConfiguration"`
StorageConfiguration StorageConfigurationData `xml:"tds:StorageConfiguration"`
}
type CreateStorageConfigurationResponse struct {
@@ -843,8 +877,11 @@ type GetStorageConfigurationResponse struct {
}
type SetStorageConfiguration struct {
XMLName string `xml:"tds:SetStorageConfiguration"`
StorageConfiguration StorageConfiguration `xml:"tds:StorageConfiguration"`
XMLName string `xml:"tds:SetStorageConfiguration"`
StorageConfiguration struct {
Token xsd.String `xml:"token,attr"`
Data StorageConfigurationData `xml:"tds:Data"`
} `xml:"tds:StorageConfiguration"`
}
type SetStorageConfigurationResponse struct {
@@ -866,7 +903,7 @@ type GetGeoLocationResponse struct {
Location onvif.LocationEntity
}
//TODO: one or more Location
// TODO: one or more Location
type SetGeoLocation struct {
XMLName string `xml:"tds:SetGeoLocation"`
Location onvif.LocationEntity `xml:"tds:Location"`

828
deviceio/function.go Normal file
View File

@@ -0,0 +1,828 @@
// -*- Mode: Go; indent-tabs-mode: t -*-
//
// Copyright (C) 2022 Intel Corporation
//
// SPDX-License-Identifier: Apache-2.0
// Code generated by gen_commands.py DO NOT EDIT.
package deviceio
type AddIPAddressFilterFunction struct{}
func (_ *AddIPAddressFilterFunction) Request() interface{} {
return &AddIPAddressFilter{}
}
func (_ *AddIPAddressFilterFunction) Response() interface{} {
return &AddIPAddressFilterResponse{}
}
type AddScopesFunction struct{}
func (_ *AddScopesFunction) Request() interface{} {
return &AddScopes{}
}
func (_ *AddScopesFunction) Response() interface{} {
return &AddScopesResponse{}
}
type CreateCertificateFunction struct{}
func (_ *CreateCertificateFunction) Request() interface{} {
return &CreateCertificate{}
}
func (_ *CreateCertificateFunction) Response() interface{} {
return &CreateCertificateResponse{}
}
type CreateDot1XConfigurationFunction struct{}
func (_ *CreateDot1XConfigurationFunction) Request() interface{} {
return &CreateDot1XConfiguration{}
}
func (_ *CreateDot1XConfigurationFunction) Response() interface{} {
return &CreateDot1XConfigurationResponse{}
}
type CreateStorageConfigurationFunction struct{}
func (_ *CreateStorageConfigurationFunction) Request() interface{} {
return &CreateStorageConfiguration{}
}
func (_ *CreateStorageConfigurationFunction) Response() interface{} {
return &CreateStorageConfigurationResponse{}
}
type CreateUsersFunction struct{}
func (_ *CreateUsersFunction) Request() interface{} {
return &CreateUsers{}
}
func (_ *CreateUsersFunction) Response() interface{} {
return &CreateUsersResponse{}
}
type DeleteCertificatesFunction struct{}
func (_ *DeleteCertificatesFunction) Request() interface{} {
return &DeleteCertificates{}
}
func (_ *DeleteCertificatesFunction) Response() interface{} {
return &DeleteCertificatesResponse{}
}
type DeleteDot1XConfigurationFunction struct{}
func (_ *DeleteDot1XConfigurationFunction) Request() interface{} {
return &DeleteDot1XConfiguration{}
}
func (_ *DeleteDot1XConfigurationFunction) Response() interface{} {
return &DeleteDot1XConfigurationResponse{}
}
type DeleteGeoLocationFunction struct{}
func (_ *DeleteGeoLocationFunction) Request() interface{} {
return &DeleteGeoLocation{}
}
func (_ *DeleteGeoLocationFunction) Response() interface{} {
return &DeleteGeoLocationResponse{}
}
type DeleteStorageConfigurationFunction struct{}
func (_ *DeleteStorageConfigurationFunction) Request() interface{} {
return &DeleteStorageConfiguration{}
}
func (_ *DeleteStorageConfigurationFunction) Response() interface{} {
return &DeleteStorageConfigurationResponse{}
}
type DeleteUsersFunction struct{}
func (_ *DeleteUsersFunction) Request() interface{} {
return &DeleteUsers{}
}
func (_ *DeleteUsersFunction) Response() interface{} {
return &DeleteUsersResponse{}
}
type GetAccessPolicyFunction struct{}
func (_ *GetAccessPolicyFunction) Request() interface{} {
return &GetAccessPolicy{}
}
func (_ *GetAccessPolicyFunction) Response() interface{} {
return &GetAccessPolicyResponse{}
}
type GetCACertificatesFunction struct{}
func (_ *GetCACertificatesFunction) Request() interface{} {
return &GetCACertificates{}
}
func (_ *GetCACertificatesFunction) Response() interface{} {
return &GetCACertificatesResponse{}
}
type GetCapabilitiesFunction struct{}
func (_ *GetCapabilitiesFunction) Request() interface{} {
return &GetCapabilities{}
}
func (_ *GetCapabilitiesFunction) Response() interface{} {
return &GetCapabilitiesResponse{}
}
type GetCertificateInformationFunction struct{}
func (_ *GetCertificateInformationFunction) Request() interface{} {
return &GetCertificateInformation{}
}
func (_ *GetCertificateInformationFunction) Response() interface{} {
return &GetCertificateInformationResponse{}
}
type GetCertificatesFunction struct{}
func (_ *GetCertificatesFunction) Request() interface{} {
return &GetCertificates{}
}
func (_ *GetCertificatesFunction) Response() interface{} {
return &GetCertificatesResponse{}
}
type GetCertificatesStatusFunction struct{}
func (_ *GetCertificatesStatusFunction) Request() interface{} {
return &GetCertificatesStatus{}
}
func (_ *GetCertificatesStatusFunction) Response() interface{} {
return &GetCertificatesStatusResponse{}
}
type GetClientCertificateModeFunction struct{}
func (_ *GetClientCertificateModeFunction) Request() interface{} {
return &GetClientCertificateMode{}
}
func (_ *GetClientCertificateModeFunction) Response() interface{} {
return &GetClientCertificateModeResponse{}
}
type GetDNSFunction struct{}
func (_ *GetDNSFunction) Request() interface{} {
return &GetDNS{}
}
func (_ *GetDNSFunction) Response() interface{} {
return &GetDNSResponse{}
}
type GetDPAddressesFunction struct{}
func (_ *GetDPAddressesFunction) Request() interface{} {
return &GetDPAddresses{}
}
func (_ *GetDPAddressesFunction) Response() interface{} {
return &GetDPAddressesResponse{}
}
type GetDeviceInformationFunction struct{}
func (_ *GetDeviceInformationFunction) Request() interface{} {
return &GetDeviceInformation{}
}
func (_ *GetDeviceInformationFunction) Response() interface{} {
return &GetDeviceInformationResponse{}
}
type GetDiscoveryModeFunction struct{}
func (_ *GetDiscoveryModeFunction) Request() interface{} {
return &GetDiscoveryMode{}
}
func (_ *GetDiscoveryModeFunction) Response() interface{} {
return &GetDiscoveryModeResponse{}
}
type GetDot11CapabilitiesFunction struct{}
func (_ *GetDot11CapabilitiesFunction) Request() interface{} {
return &GetDot11Capabilities{}
}
func (_ *GetDot11CapabilitiesFunction) Response() interface{} {
return &GetDot11CapabilitiesResponse{}
}
type GetDot11StatusFunction struct{}
func (_ *GetDot11StatusFunction) Request() interface{} {
return &GetDot11Status{}
}
func (_ *GetDot11StatusFunction) Response() interface{} {
return &GetDot11StatusResponse{}
}
type GetDot1XConfigurationFunction struct{}
func (_ *GetDot1XConfigurationFunction) Request() interface{} {
return &GetDot1XConfiguration{}
}
func (_ *GetDot1XConfigurationFunction) Response() interface{} {
return &GetDot1XConfigurationResponse{}
}
type GetDot1XConfigurationsFunction struct{}
func (_ *GetDot1XConfigurationsFunction) Request() interface{} {
return &GetDot1XConfigurations{}
}
func (_ *GetDot1XConfigurationsFunction) Response() interface{} {
return &GetDot1XConfigurationsResponse{}
}
type GetDynamicDNSFunction struct{}
func (_ *GetDynamicDNSFunction) Request() interface{} {
return &GetDynamicDNS{}
}
func (_ *GetDynamicDNSFunction) Response() interface{} {
return &GetDynamicDNSResponse{}
}
type GetEndpointReferenceFunction struct{}
func (_ *GetEndpointReferenceFunction) Request() interface{} {
return &GetEndpointReference{}
}
func (_ *GetEndpointReferenceFunction) Response() interface{} {
return &GetEndpointReferenceResponse{}
}
type GetGeoLocationFunction struct{}
func (_ *GetGeoLocationFunction) Request() interface{} {
return &GetGeoLocation{}
}
func (_ *GetGeoLocationFunction) Response() interface{} {
return &GetGeoLocationResponse{}
}
type GetHostnameFunction struct{}
func (_ *GetHostnameFunction) Request() interface{} {
return &GetHostname{}
}
func (_ *GetHostnameFunction) Response() interface{} {
return &GetHostnameResponse{}
}
type GetIPAddressFilterFunction struct{}
func (_ *GetIPAddressFilterFunction) Request() interface{} {
return &GetIPAddressFilter{}
}
func (_ *GetIPAddressFilterFunction) Response() interface{} {
return &GetIPAddressFilterResponse{}
}
type GetNTPFunction struct{}
func (_ *GetNTPFunction) Request() interface{} {
return &GetNTP{}
}
func (_ *GetNTPFunction) Response() interface{} {
return &GetNTPResponse{}
}
type GetNetworkDefaultGatewayFunction struct{}
func (_ *GetNetworkDefaultGatewayFunction) Request() interface{} {
return &GetNetworkDefaultGateway{}
}
func (_ *GetNetworkDefaultGatewayFunction) Response() interface{} {
return &GetNetworkDefaultGatewayResponse{}
}
type GetNetworkInterfacesFunction struct{}
func (_ *GetNetworkInterfacesFunction) Request() interface{} {
return &GetNetworkInterfaces{}
}
func (_ *GetNetworkInterfacesFunction) Response() interface{} {
return &GetNetworkInterfacesResponse{}
}
type GetNetworkProtocolsFunction struct{}
func (_ *GetNetworkProtocolsFunction) Request() interface{} {
return &GetNetworkProtocols{}
}
func (_ *GetNetworkProtocolsFunction) Response() interface{} {
return &GetNetworkProtocolsResponse{}
}
type GetPkcs10RequestFunction struct{}
func (_ *GetPkcs10RequestFunction) Request() interface{} {
return &GetPkcs10Request{}
}
func (_ *GetPkcs10RequestFunction) Response() interface{} {
return &GetPkcs10RequestResponse{}
}
type GetRelayOutputsFunction struct{}
func (_ *GetRelayOutputsFunction) Request() interface{} {
return &GetRelayOutputs{}
}
func (_ *GetRelayOutputsFunction) Response() interface{} {
return &GetRelayOutputsResponse{}
}
type GetDigitalInputsFunction struct{}
func (_ *GetDigitalInputsFunction) Request() interface{} {
return &GetDigitalInputs{}
}
func (_ *GetDigitalInputsFunction) Response() interface{} {
return &GetDigitalInputsResponse{}
}
type GetRemoteDiscoveryModeFunction struct{}
func (_ *GetRemoteDiscoveryModeFunction) Request() interface{} {
return &GetRemoteDiscoveryMode{}
}
func (_ *GetRemoteDiscoveryModeFunction) Response() interface{} {
return &GetRemoteDiscoveryModeResponse{}
}
type GetRemoteUserFunction struct{}
func (_ *GetRemoteUserFunction) Request() interface{} {
return &GetRemoteUser{}
}
func (_ *GetRemoteUserFunction) Response() interface{} {
return &GetRemoteUserResponse{}
}
type GetScopesFunction struct{}
func (_ *GetScopesFunction) Request() interface{} {
return &GetScopes{}
}
func (_ *GetScopesFunction) Response() interface{} {
return &GetScopesResponse{}
}
type GetServiceCapabilitiesFunction struct{}
func (_ *GetServiceCapabilitiesFunction) Request() interface{} {
return &GetServiceCapabilities{}
}
func (_ *GetServiceCapabilitiesFunction) Response() interface{} {
return &GetServiceCapabilitiesResponse{}
}
type GetServicesFunction struct{}
func (_ *GetServicesFunction) Request() interface{} {
return &GetServices{}
}
func (_ *GetServicesFunction) Response() interface{} {
return &GetServicesResponse{}
}
type GetStorageConfigurationFunction struct{}
func (_ *GetStorageConfigurationFunction) Request() interface{} {
return &GetStorageConfiguration{}
}
func (_ *GetStorageConfigurationFunction) Response() interface{} {
return &GetStorageConfigurationResponse{}
}
type GetStorageConfigurationsFunction struct{}
func (_ *GetStorageConfigurationsFunction) Request() interface{} {
return &GetStorageConfigurations{}
}
func (_ *GetStorageConfigurationsFunction) Response() interface{} {
return &GetStorageConfigurationsResponse{}
}
type GetSystemBackupFunction struct{}
func (_ *GetSystemBackupFunction) Request() interface{} {
return &GetSystemBackup{}
}
func (_ *GetSystemBackupFunction) Response() interface{} {
return &GetSystemBackupResponse{}
}
type GetSystemDateAndTimeFunction struct{}
func (_ *GetSystemDateAndTimeFunction) Request() interface{} {
return &GetSystemDateAndTime{}
}
func (_ *GetSystemDateAndTimeFunction) Response() interface{} {
return &GetSystemDateAndTimeResponse{}
}
type GetSystemLogFunction struct{}
func (_ *GetSystemLogFunction) Request() interface{} {
return &GetSystemLog{}
}
func (_ *GetSystemLogFunction) Response() interface{} {
return &GetSystemLogResponse{}
}
type GetSystemSupportInformationFunction struct{}
func (_ *GetSystemSupportInformationFunction) Request() interface{} {
return &GetSystemSupportInformation{}
}
func (_ *GetSystemSupportInformationFunction) Response() interface{} {
return &GetSystemSupportInformationResponse{}
}
type GetSystemUrisFunction struct{}
func (_ *GetSystemUrisFunction) Request() interface{} {
return &GetSystemUris{}
}
func (_ *GetSystemUrisFunction) Response() interface{} {
return &GetSystemUrisResponse{}
}
type GetUsersFunction struct{}
func (_ *GetUsersFunction) Request() interface{} {
return &GetUsers{}
}
func (_ *GetUsersFunction) Response() interface{} {
return &GetUsersResponse{}
}
type GetWsdlUrlFunction struct{}
func (_ *GetWsdlUrlFunction) Request() interface{} {
return &GetWsdlUrl{}
}
func (_ *GetWsdlUrlFunction) Response() interface{} {
return &GetWsdlUrlResponse{}
}
type GetZeroConfigurationFunction struct{}
func (_ *GetZeroConfigurationFunction) Request() interface{} {
return &GetZeroConfiguration{}
}
func (_ *GetZeroConfigurationFunction) Response() interface{} {
return &GetZeroConfigurationResponse{}
}
type LoadCACertificatesFunction struct{}
func (_ *LoadCACertificatesFunction) Request() interface{} {
return &LoadCACertificates{}
}
func (_ *LoadCACertificatesFunction) Response() interface{} {
return &LoadCACertificatesResponse{}
}
type LoadCertificateWithPrivateKeyFunction struct{}
func (_ *LoadCertificateWithPrivateKeyFunction) Request() interface{} {
return &LoadCertificateWithPrivateKey{}
}
func (_ *LoadCertificateWithPrivateKeyFunction) Response() interface{} {
return &LoadCertificateWithPrivateKeyResponse{}
}
type LoadCertificatesFunction struct{}
func (_ *LoadCertificatesFunction) Request() interface{} {
return &LoadCertificates{}
}
func (_ *LoadCertificatesFunction) Response() interface{} {
return &LoadCertificatesResponse{}
}
type RemoveIPAddressFilterFunction struct{}
func (_ *RemoveIPAddressFilterFunction) Request() interface{} {
return &RemoveIPAddressFilter{}
}
func (_ *RemoveIPAddressFilterFunction) Response() interface{} {
return &RemoveIPAddressFilterResponse{}
}
type RemoveScopesFunction struct{}
func (_ *RemoveScopesFunction) Request() interface{} {
return &RemoveScopes{}
}
func (_ *RemoveScopesFunction) Response() interface{} {
return &RemoveScopesResponse{}
}
type RestoreSystemFunction struct{}
func (_ *RestoreSystemFunction) Request() interface{} {
return &RestoreSystem{}
}
func (_ *RestoreSystemFunction) Response() interface{} {
return &RestoreSystemResponse{}
}
type ScanAvailableDot11NetworksFunction struct{}
func (_ *ScanAvailableDot11NetworksFunction) Request() interface{} {
return &ScanAvailableDot11Networks{}
}
func (_ *ScanAvailableDot11NetworksFunction) Response() interface{} {
return &ScanAvailableDot11NetworksResponse{}
}
type SendAuxiliaryCommandFunction struct{}
func (_ *SendAuxiliaryCommandFunction) Request() interface{} {
return &SendAuxiliaryCommand{}
}
func (_ *SendAuxiliaryCommandFunction) Response() interface{} {
return &SendAuxiliaryCommandResponse{}
}
type SetAccessPolicyFunction struct{}
func (_ *SetAccessPolicyFunction) Request() interface{} {
return &SetAccessPolicy{}
}
func (_ *SetAccessPolicyFunction) Response() interface{} {
return &SetAccessPolicyResponse{}
}
type SetCertificatesStatusFunction struct{}
func (_ *SetCertificatesStatusFunction) Request() interface{} {
return &SetCertificatesStatus{}
}
func (_ *SetCertificatesStatusFunction) Response() interface{} {
return &SetCertificatesStatusResponse{}
}
type SetClientCertificateModeFunction struct{}
func (_ *SetClientCertificateModeFunction) Request() interface{} {
return &SetClientCertificateMode{}
}
func (_ *SetClientCertificateModeFunction) Response() interface{} {
return &SetClientCertificateModeResponse{}
}
type SetDNSFunction struct{}
func (_ *SetDNSFunction) Request() interface{} {
return &SetDNS{}
}
func (_ *SetDNSFunction) Response() interface{} {
return &SetDNSResponse{}
}
type SetDPAddressesFunction struct{}
func (_ *SetDPAddressesFunction) Request() interface{} {
return &SetDPAddresses{}
}
func (_ *SetDPAddressesFunction) Response() interface{} {
return &SetDPAddressesResponse{}
}
type SetDiscoveryModeFunction struct{}
func (_ *SetDiscoveryModeFunction) Request() interface{} {
return &SetDiscoveryMode{}
}
func (_ *SetDiscoveryModeFunction) Response() interface{} {
return &SetDiscoveryModeResponse{}
}
type SetDot1XConfigurationFunction struct{}
func (_ *SetDot1XConfigurationFunction) Request() interface{} {
return &SetDot1XConfiguration{}
}
func (_ *SetDot1XConfigurationFunction) Response() interface{} {
return &SetDot1XConfigurationResponse{}
}
type SetDynamicDNSFunction struct{}
func (_ *SetDynamicDNSFunction) Request() interface{} {
return &SetDynamicDNS{}
}
func (_ *SetDynamicDNSFunction) Response() interface{} {
return &SetDynamicDNSResponse{}
}
type SetGeoLocationFunction struct{}
func (_ *SetGeoLocationFunction) Request() interface{} {
return &SetGeoLocation{}
}
func (_ *SetGeoLocationFunction) Response() interface{} {
return &SetGeoLocationResponse{}
}
type SetHostnameFunction struct{}
func (_ *SetHostnameFunction) Request() interface{} {
return &SetHostname{}
}
func (_ *SetHostnameFunction) Response() interface{} {
return &SetHostnameResponse{}
}
type SetHostnameFromDHCPFunction struct{}
func (_ *SetHostnameFromDHCPFunction) Request() interface{} {
return &SetHostnameFromDHCP{}
}
func (_ *SetHostnameFromDHCPFunction) Response() interface{} {
return &SetHostnameFromDHCPResponse{}
}
type SetIPAddressFilterFunction struct{}
func (_ *SetIPAddressFilterFunction) Request() interface{} {
return &SetIPAddressFilter{}
}
func (_ *SetIPAddressFilterFunction) Response() interface{} {
return &SetIPAddressFilterResponse{}
}
type SetNTPFunction struct{}
func (_ *SetNTPFunction) Request() interface{} {
return &SetNTP{}
}
func (_ *SetNTPFunction) Response() interface{} {
return &SetNTPResponse{}
}
type SetNetworkDefaultGatewayFunction struct{}
func (_ *SetNetworkDefaultGatewayFunction) Request() interface{} {
return &SetNetworkDefaultGateway{}
}
func (_ *SetNetworkDefaultGatewayFunction) Response() interface{} {
return &SetNetworkDefaultGatewayResponse{}
}
type SetNetworkInterfacesFunction struct{}
func (_ *SetNetworkInterfacesFunction) Request() interface{} {
return &SetNetworkInterfaces{}
}
func (_ *SetNetworkInterfacesFunction) Response() interface{} {
return &SetNetworkInterfacesResponse{}
}
type SetNetworkProtocolsFunction struct{}
func (_ *SetNetworkProtocolsFunction) Request() interface{} {
return &SetNetworkProtocols{}
}
func (_ *SetNetworkProtocolsFunction) Response() interface{} {
return &SetNetworkProtocolsResponse{}
}
type SetRelayOutputSettingsFunction struct{}
func (_ *SetRelayOutputSettingsFunction) Request() interface{} {
return &SetRelayOutputSettings{}
}
func (_ *SetRelayOutputSettingsFunction) Response() interface{} {
return &SetRelayOutputSettingsResponse{}
}
type SetRelayOutputStateFunction struct{}
func (_ *SetRelayOutputStateFunction) Request() interface{} {
return &SetRelayOutputState{}
}
func (_ *SetRelayOutputStateFunction) Response() interface{} {
return &SetRelayOutputStateResponse{}
}
type SetRemoteDiscoveryModeFunction struct{}
func (_ *SetRemoteDiscoveryModeFunction) Request() interface{} {
return &SetRemoteDiscoveryMode{}
}
func (_ *SetRemoteDiscoveryModeFunction) Response() interface{} {
return &SetRemoteDiscoveryModeResponse{}
}
type SetRemoteUserFunction struct{}
func (_ *SetRemoteUserFunction) Request() interface{} {
return &SetRemoteUser{}
}
func (_ *SetRemoteUserFunction) Response() interface{} {
return &SetRemoteUserResponse{}
}
type SetScopesFunction struct{}
func (_ *SetScopesFunction) Request() interface{} {
return &SetScopes{}
}
func (_ *SetScopesFunction) Response() interface{} {
return &SetScopesResponse{}
}
type SetStorageConfigurationFunction struct{}
func (_ *SetStorageConfigurationFunction) Request() interface{} {
return &SetStorageConfiguration{}
}
func (_ *SetStorageConfigurationFunction) Response() interface{} {
return &SetStorageConfigurationResponse{}
}
type SetSystemDateAndTimeFunction struct{}
func (_ *SetSystemDateAndTimeFunction) Request() interface{} {
return &SetSystemDateAndTime{}
}
func (_ *SetSystemDateAndTimeFunction) Response() interface{} {
return &SetSystemDateAndTimeResponse{}
}
type SetSystemFactoryDefaultFunction struct{}
func (_ *SetSystemFactoryDefaultFunction) Request() interface{} {
return &SetSystemFactoryDefault{}
}
func (_ *SetSystemFactoryDefaultFunction) Response() interface{} {
return &SetSystemFactoryDefaultResponse{}
}
type SetUserFunction struct{}
func (_ *SetUserFunction) Request() interface{} {
return &SetUser{}
}
func (_ *SetUserFunction) Response() interface{} {
return &SetUserResponse{}
}
type SetZeroConfigurationFunction struct{}
func (_ *SetZeroConfigurationFunction) Request() interface{} {
return &SetZeroConfiguration{}
}
func (_ *SetZeroConfigurationFunction) Response() interface{} {
return &SetZeroConfigurationResponse{}
}
type StartFirmwareUpgradeFunction struct{}
func (_ *StartFirmwareUpgradeFunction) Request() interface{} {
return &StartFirmwareUpgrade{}
}
func (_ *StartFirmwareUpgradeFunction) Response() interface{} {
return &StartFirmwareUpgradeResponse{}
}
type StartSystemRestoreFunction struct{}
func (_ *StartSystemRestoreFunction) Request() interface{} {
return &StartSystemRestore{}
}
func (_ *StartSystemRestoreFunction) Response() interface{} {
return &StartSystemRestoreResponse{}
}
type SystemRebootFunction struct{}
func (_ *SystemRebootFunction) Request() interface{} {
return &SystemReboot{}
}
func (_ *SystemRebootFunction) Response() interface{} {
return &SystemRebootResponse{}
}
type UpgradeSystemFirmwareFunction struct{}
func (_ *UpgradeSystemFirmwareFunction) Request() interface{} {
return &UpgradeSystemFirmware{}
}
func (_ *UpgradeSystemFirmwareFunction) Response() interface{} {
return &UpgradeSystemFirmwareResponse{}
}

921
deviceio/types.go Normal file
View File

@@ -0,0 +1,921 @@
package deviceio
//go:generate python3 ../python/gen_commands.py
import (
"github.com/kerberos-io/onvif/xsd"
"github.com/kerberos-io/onvif/xsd/onvif"
)
type Service struct {
Namespace xsd.AnyURI
XAddr xsd.AnyURI
Capabilities
Version onvif.OnvifVersion
}
type Capabilities struct {
Any string
}
type DeviceServiceCapabilities struct {
Network NetworkCapabilities
Security SecurityCapabilities
System SystemCapabilities
Misc MiscCapabilities
}
type NetworkCapabilities struct {
IPFilter xsd.Boolean `xml:"IPFilter,attr"`
ZeroConfiguration xsd.Boolean `xml:"ZeroConfiguration,attr"`
IPVersion6 xsd.Boolean `xml:"IPVersion6,attr"`
DynDNS xsd.Boolean `xml:"DynDNS,attr"`
Dot11Configuration xsd.Boolean `xml:"Dot11Configuration,attr"`
Dot1XConfigurations int `xml:"Dot1XConfigurations,attr"`
HostnameFromDHCP xsd.Boolean `xml:"HostnameFromDHCP,attr"`
NTP int `xml:"NTP,attr"`
DHCPv6 xsd.Boolean `xml:"DHCPv6,attr"`
}
type SecurityCapabilities struct {
TLS1_0 xsd.Boolean `xml:"TLS1_0,attr"`
TLS1_1 xsd.Boolean `xml:"TLS1_1,attr"`
TLS1_2 xsd.Boolean `xml:"TLS1_2,attr"`
OnboardKeyGeneration xsd.Boolean `xml:"OnboardKeyGeneration,attr"`
AccessPolicyConfig xsd.Boolean `xml:"AccessPolicyConfig,attr"`
DefaultAccessPolicy xsd.Boolean `xml:"DefaultAccessPolicy,attr"`
Dot1X xsd.Boolean `xml:"Dot1X,attr"`
RemoteUserHandling xsd.Boolean `xml:"RemoteUserHandling,attr"`
X_509Token xsd.Boolean `xml:"X_509Token,attr"`
SAMLToken xsd.Boolean `xml:"SAMLToken,attr"`
KerberosToken xsd.Boolean `xml:"KerberosToken,attr"`
UsernameToken xsd.Boolean `xml:"UsernameToken,attr"`
HttpDigest xsd.Boolean `xml:"HttpDigest,attr"`
RELToken xsd.Boolean `xml:"RELToken,attr"`
SupportedEAPMethods onvif.IntAttrList `xml:"SupportedEAPMethods,attr"`
MaxUsers int `xml:"MaxUsers,attr"`
MaxUserNameLength int `xml:"MaxUserNameLength,attr"`
MaxPasswordLength int `xml:"MaxPasswordLength,attr"`
}
type SystemCapabilities struct {
DiscoveryResolve xsd.Boolean `xml:"DiscoveryResolve,attr"`
DiscoveryBye xsd.Boolean `xml:"DiscoveryBye,attr"`
RemoteDiscovery xsd.Boolean `xml:"RemoteDiscovery,attr"`
SystemBackup xsd.Boolean `xml:"SystemBackup,attr"`
SystemLogging xsd.Boolean `xml:"SystemLogging,attr"`
FirmwareUpgrade xsd.Boolean `xml:"FirmwareUpgrade,attr"`
HttpFirmwareUpgrade xsd.Boolean `xml:"HttpFirmwareUpgrade,attr"`
HttpSystemBackup xsd.Boolean `xml:"HttpSystemBackup,attr"`
HttpSystemLogging xsd.Boolean `xml:"HttpSystemLogging,attr"`
HttpSupportInformation xsd.Boolean `xml:"HttpSupportInformation,attr"`
StorageConfiguration xsd.Boolean `xml:"StorageConfiguration,attr"`
MaxStorageConfigurations int `xml:"MaxStorageConfigurations,attr"`
StorageTypesSupported onvif.StringAttrList `xml:"StorageTypesSupported,attr"`
GeoLocationEntries int `xml:"GeoLocationEntries,attr"`
AutoGeo onvif.StringAttrList `xml:"AutoGeo,attr"`
}
type MiscCapabilities struct {
AuxiliaryCommands onvif.StringAttrList `xml:"AuxiliaryCommands,attr"`
}
type StorageConfiguration struct {
onvif.DeviceEntity
Data struct {
Type xsd.String `xml:"type,attr"`
Region string
LocalPath xsd.AnyURI
StorageUri xsd.AnyURI
User struct {
UserName xsd.String
Password xsd.String `json:",omitempty"`
Extension xsd.AnyType `json:",omitempty"`
}
Extension xsd.AnyURI `json:",omitempty"`
}
}
type StorageConfigurationData struct {
Type xsd.String `xml:"type,attr"`
Region string `xml:"tds:Region,omitempty"`
LocalPath xsd.AnyURI `xml:"tds:LocalPath"`
StorageUri xsd.AnyURI `xml:"tds:StorageUri"`
User UserCredential `xml:"tds:User"`
Extension xsd.AnyURI `xml:"tds:Extension"`
}
type UserCredential struct {
UserName xsd.String `xml:"tds:UserName"`
Password xsd.String `xml:"tds:Password"`
Extension xsd.AnyType `xml:"tds:Extension"`
}
//Device main types
type GetServices struct {
XMLName string `xml:"tds:GetServices"`
IncludeCapability xsd.Boolean `xml:"tds:IncludeCapability"`
}
type GetServicesResponse struct {
Service Service
}
type GetServiceCapabilities struct {
XMLName string `xml:"tds:GetServiceCapabilities"`
}
type GetServiceCapabilitiesResponse struct {
Capabilities DeviceServiceCapabilities
}
type GetDeviceInformation struct {
XMLName string `xml:"tds:GetDeviceInformation"`
}
type GetDeviceInformationResponse struct {
Manufacturer string
Model string
FirmwareVersion string
SerialNumber string
HardwareId string
}
// SetSystemDateAndTime and its properties are defined in the Onvif specification:
// https://www.onvif.org/ver10/device/wsdl/devicemgmt.wsdl#op.SetSystemDateAndTime
type SetSystemDateAndTime struct {
XMLName string `xml:"tds:SetSystemDateAndTime,omitempty"`
DateTimeType *onvif.SetDateTimeType `xml:"tds:DateTimeType,omitempty"`
DaylightSavings *xsd.Boolean `xml:"tds:DaylightSavings,omitempty"`
TimeZone *onvif.TimeZone `xml:"tds:TimeZone,omitempty"`
UTCDateTime *onvif.DateTimeRequest `xml:"tds:UTCDateTime,omitempty"`
}
type SetSystemDateAndTimeResponse struct {
}
type GetSystemDateAndTime struct {
XMLName string `xml:"tds:GetSystemDateAndTime"`
}
type GetSystemDateAndTimeResponse struct {
SystemDateAndTime onvif.SystemDateTime
}
// SetSystemFactoryDefault and its properties are defined in the Onvif specification:
// https://www.onvif.org/ver10/device/wsdl/devicemgmt.wsdl#op.SetSystemFactoryDefault
type SetSystemFactoryDefault struct {
XMLName string `xml:"tds:SetSystemFactoryDefault"`
FactoryDefault onvif.FactoryDefaultType `xml:"tds:FactoryDefault"`
}
type SetSystemFactoryDefaultResponse struct {
}
type UpgradeSystemFirmware struct {
XMLName string `xml:"tds:UpgradeSystemFirmware"`
Firmware onvif.AttachmentData `xml:"tds:Firmware"`
}
type UpgradeSystemFirmwareResponse struct {
Message string
}
// SystemReboot and its properties are defined in the Onvif specification:
// https://www.onvif.org/ver10/device/wsdl/devicemgmt.wsdl#op.SystemReboot
type SystemReboot struct {
XMLName string `xml:"tds:SystemReboot"`
}
type SystemRebootResponse struct {
Message string
}
// TODO: one or more repetitions
type RestoreSystem struct {
XMLName string `xml:"tds:RestoreSystem"`
BackupFiles onvif.BackupFile `xml:"tds:BackupFiles"`
}
type RestoreSystemResponse struct {
}
type GetSystemBackup struct {
XMLName string `xml:"tds:GetSystemBackup"`
}
type GetSystemBackupResponse struct {
BackupFiles onvif.BackupFile
}
type GetSystemLog struct {
XMLName string `xml:"tds:GetSystemLog"`
LogType onvif.SystemLogType `xml:"tds:LogType"`
}
type GetSystemLogResponse struct {
SystemLog onvif.SystemLog
}
type GetSystemSupportInformation struct {
XMLName string `xml:"tds:GetSystemSupportInformation"`
}
type GetSystemSupportInformationResponse struct {
SupportInformation onvif.SupportInformation
}
type GetScopes struct {
XMLName string `xml:"tds:GetScopes"`
}
type GetScopesResponse struct {
Scopes []onvif.Scope
}
// SetScopes and its properties are defined in the Onvif specification:
// https://www.onvif.org/ver10/device/wsdl/devicemgmt.wsdl#op.SetScopes
type SetScopes struct {
XMLName string `xml:"tds:SetScopes"`
Scopes []xsd.AnyURI `xml:"tds:Scopes"`
}
type SetScopesResponse struct {
}
// AddScopes and its properties are defined in the Onvif specification:
// https://www.onvif.org/ver10/device/wsdl/devicemgmt.wsdl#op.AddScopes
type AddScopes struct {
XMLName string `xml:"tds:AddScopes"`
ScopeItem []xsd.AnyURI `xml:"tds:ScopeItem"`
}
type AddScopesResponse struct {
}
type RemoveScopes struct {
XMLName string `xml:"tds:RemoveScopes"`
ScopeItem []xsd.AnyURI `xml:"tds:ScopeItem"`
}
type RemoveScopesResponse struct {
ScopeItem xsd.AnyURI
}
// GetDiscoveryMode and its properties are defined in the Onvif specification:
// https://www.onvif.org/ver10/device/wsdl/devicemgmt.wsdl#op.GetDiscoveryMode
type GetDiscoveryMode struct {
XMLName string `xml:"tds:GetDiscoveryMode"`
}
type GetDiscoveryModeResponse struct {
DiscoveryMode onvif.DiscoveryMode
}
// SetDiscoveryMode and its properties are defined in the Onvif specification:
// https://www.onvif.org/ver10/device/wsdl/devicemgmt.wsdl#op.SetDiscoveryMode
type SetDiscoveryMode struct {
XMLName string `xml:"tds:SetDiscoveryMode"`
DiscoveryMode onvif.DiscoveryMode `xml:"tds:DiscoveryMode"`
}
type SetDiscoveryModeResponse struct {
}
type GetRemoteDiscoveryMode struct {
XMLName string `xml:"tds:GetRemoteDiscoveryMode"`
}
type GetRemoteDiscoveryModeResponse struct {
RemoteDiscoveryMode onvif.DiscoveryMode
}
type SetRemoteDiscoveryMode struct {
XMLName string `xml:"tds:SetRemoteDiscoveryMode"`
RemoteDiscoveryMode onvif.DiscoveryMode `xml:"tds:RemoteDiscoveryMode"`
}
type SetRemoteDiscoveryModeResponse struct {
}
type GetDPAddresses struct {
XMLName string `xml:"tds:GetDPAddresses"`
}
type GetDPAddressesResponse struct {
DPAddress onvif.NetworkHost
}
type SetDPAddresses struct {
XMLName string `xml:"tds:SetDPAddresses"`
DPAddress onvif.NetworkHost `xml:"tds:DPAddress"`
}
type SetDPAddressesResponse struct {
}
type GetEndpointReference struct {
XMLName string `xml:"tds:GetEndpointReference"`
}
type GetEndpointReferenceResponse struct {
GUID string
}
type GetRemoteUser struct {
XMLName string `xml:"tds:GetRemoteUser"`
}
type GetRemoteUserResponse struct {
RemoteUser onvif.RemoteUser
}
type SetRemoteUser struct {
XMLName string `xml:"tds:SetRemoteUser"`
RemoteUser onvif.RemoteUser `xml:"tds:RemoteUser"`
}
type SetRemoteUserResponse struct {
}
type GetUsers struct {
XMLName string `xml:"tds:GetUsers"`
}
type GetUsersResponse struct {
User []onvif.User
}
// CreateUsers and its properties are defined in the Onvif specification:
// https://www.onvif.org/ver10/device/wsdl/devicemgmt.wsdl#op.CreateUsers
type CreateUsers struct {
XMLName string `xml:"tds:CreateUsers"`
User []onvif.UserRequest `xml:"tds:User,omitempty"`
}
type CreateUsersResponse struct {
}
// DeleteUsers and its properties are defined in the Onvif specification:
// https://www.onvif.org/ver10/device/wsdl/devicemgmt.wsdl#op.DeleteUsers
type DeleteUsers struct {
XMLName xsd.String `xml:"tds:DeleteUsers"`
Username []xsd.String `xml:"tds:Username"`
}
type DeleteUsersResponse struct {
}
// SetUser and its properties are defined in the Onvif specification:
// https://www.onvif.org/ver10/device/wsdl/devicemgmt.wsdl#op.SetUser
type SetUser struct {
XMLName string `xml:"tds:SetUser"`
User []onvif.UserRequest `xml:"tds:User"`
}
type SetUserResponse struct {
}
type GetWsdlUrl struct {
XMLName string `xml:"tds:GetWsdlUrl"`
}
type GetWsdlUrlResponse struct {
WsdlUrl xsd.AnyURI
}
type GetCapabilities struct {
XMLName string `xml:"tds:GetCapabilities"`
Category []onvif.CapabilityCategory `xml:"tds:Category"`
}
type GetCapabilitiesResponse struct {
Capabilities onvif.Capabilities
}
type GetHostname struct {
XMLName string `xml:"tds:GetHostname"`
}
type GetHostnameResponse struct {
HostnameInformation onvif.HostnameInformation
}
type SetHostname struct {
XMLName string `xml:"tds:SetHostname"`
Name xsd.Token `xml:"tds:Name"`
}
type SetHostnameResponse struct {
}
type SetHostnameFromDHCP struct {
XMLName string `xml:"tds:SetHostnameFromDHCP"`
FromDHCP xsd.Boolean `xml:"tds:FromDHCP"`
}
type SetHostnameFromDHCPResponse struct {
RebootNeeded xsd.Boolean
}
type GetDNS struct {
XMLName string `xml:"tds:GetDNS"`
}
type GetDNSResponse struct {
DNSInformation onvif.DNSInformation
}
type SetDNS struct {
XMLName string `xml:"tds:SetDNS"`
FromDHCP *xsd.Boolean `xml:"tds:FromDHCP,omitempty"`
SearchDomain *xsd.Token `xml:"tds:SearchDomain,omitempty"`
DNSManual *onvif.IPAddress `xml:"tds:DNSManual,omitempty"`
}
type SetDNSResponse struct {
}
type GetNTP struct {
XMLName string `xml:"tds:GetNTP"`
}
type GetNTPResponse struct {
NTPInformation onvif.NTPInformation
}
type SetNTP struct {
XMLName string `xml:"tds:SetNTP"`
FromDHCP xsd.Boolean `xml:"tds:FromDHCP"`
NTPManual onvif.NetworkHost `xml:"tds:NTPManual"`
}
type SetNTPResponse struct {
}
type GetDynamicDNS struct {
XMLName string `xml:"tds:GetDynamicDNS"`
}
type GetDynamicDNSResponse struct {
DynamicDNSInformation onvif.DynamicDNSInformation
}
type SetDynamicDNS struct {
XMLName string `xml:"tds:SetDynamicDNS"`
Type onvif.DynamicDNSType `xml:"tds:Type"`
Name onvif.DNSName `xml:"tds:Name"`
TTL xsd.Duration `xml:"tds:TTL"`
}
type SetDynamicDNSResponse struct {
}
type GetNetworkInterfaces struct {
XMLName string `xml:"tds:GetNetworkInterfaces"`
}
type GetNetworkInterfacesResponse struct {
NetworkInterfaces onvif.NetworkInterface
}
type SetNetworkInterfaces struct {
XMLName string `xml:"tds:SetNetworkInterfaces"`
InterfaceToken *onvif.ReferenceToken `xml:"tds:InterfaceToken,omitempty"`
NetworkInterface *onvif.NetworkInterfaceSetConfiguration `xml:"tds:NetworkInterface,omitempty"`
}
type SetNetworkInterfacesResponse struct {
RebootNeeded xsd.Boolean
}
type GetNetworkProtocols struct {
XMLName string `xml:"tds:GetNetworkProtocols"`
}
type GetNetworkProtocolsResponse struct {
NetworkProtocols []onvif.NetworkProtocolResponse
}
type SetNetworkProtocols struct {
XMLName string `xml:"tds:SetNetworkProtocols"`
NetworkProtocols []onvif.NetworkProtocolRequest `xml:"tds:NetworkProtocols"`
}
type SetNetworkProtocolsResponse struct {
}
type GetNetworkDefaultGateway struct {
XMLName string `xml:"tds:GetNetworkDefaultGateway"`
}
type GetNetworkDefaultGatewayResponse struct {
NetworkGateway onvif.NetworkGateway
}
type SetNetworkDefaultGateway struct {
XMLName string `xml:"tds:SetNetworkDefaultGateway"`
IPv4Address onvif.IPv4Address `xml:"tds:IPv4Address,omitempty"`
IPv6Address onvif.IPv6Address `xml:"tds:IPv6Address,omitempty"`
}
type SetNetworkDefaultGatewayResponse struct {
}
type GetZeroConfiguration struct {
XMLName string `xml:"tds:GetZeroConfiguration"`
}
type GetZeroConfigurationResponse struct {
ZeroConfiguration onvif.NetworkZeroConfiguration
}
type SetZeroConfiguration struct {
XMLName string `xml:"tds:SetZeroConfiguration"`
InterfaceToken onvif.ReferenceToken `xml:"tds:InterfaceToken"`
Enabled xsd.Boolean `xml:"tds:Enabled"`
}
type SetZeroConfigurationResponse struct {
}
type GetIPAddressFilter struct {
XMLName string `xml:"tds:GetIPAddressFilter"`
}
type GetIPAddressFilterResponse struct {
IPAddressFilter onvif.IPAddressFilter
}
type SetIPAddressFilter struct {
XMLName string `xml:"tds:SetIPAddressFilter"`
IPAddressFilter onvif.IPAddressFilter `xml:"tds:IPAddressFilter"`
}
type SetIPAddressFilterResponse struct {
}
// This operation adds an IP filter address to a device.
// If the device supports device access control based on
// IP filtering rules (denied or accepted ranges of IP addresses),
// the device shall support adding of IP filtering addresses through
// the AddIPAddressFilter command.
type AddIPAddressFilter struct {
XMLName string `xml:"tds:AddIPAddressFilter"`
IPAddressFilter onvif.IPAddressFilter `xml:"tds:IPAddressFilter"`
}
type AddIPAddressFilterResponse struct {
}
type RemoveIPAddressFilter struct {
XMLName string `xml:"tds:RemoveIPAddressFilter"`
IPAddressFilter onvif.IPAddressFilter `xml:"IPAddressFilter"`
}
type RemoveIPAddressFilterResponse struct {
}
type GetAccessPolicy struct {
XMLName string `xml:"tds:GetAccessPolicy"`
}
type GetAccessPolicyResponse struct {
PolicyFile onvif.BinaryData
}
type SetAccessPolicy struct {
XMLName string `xml:"tds:SetAccessPolicy"`
PolicyFile onvif.BinaryData `xml:"tds:PolicyFile"`
}
type SetAccessPolicyResponse struct {
}
type CreateCertificate struct {
XMLName string `xml:"tds:CreateCertificate"`
CertificateID xsd.Token `xml:"tds:CertificateID,omitempty"`
Subject string `xml:"tds:Subject,omitempty"`
ValidNotBefore xsd.DateTime `xml:"tds:ValidNotBefore,omitempty"`
ValidNotAfter xsd.DateTime `xml:"tds:ValidNotAfter,omitempty"`
}
type CreateCertificateResponse struct {
NvtCertificate onvif.Certificate
}
type GetCertificates struct {
XMLName string `xml:"tds:GetCertificates"`
}
type GetCertificatesResponse struct {
NvtCertificate onvif.Certificate
}
type GetCertificatesStatus struct {
XMLName string `xml:"tds:GetCertificatesStatus"`
}
type GetCertificatesStatusResponse struct {
CertificateStatus onvif.CertificateStatus
}
type SetCertificatesStatus struct {
XMLName string `xml:"tds:SetCertificatesStatus"`
CertificateStatus onvif.CertificateStatus `xml:"tds:CertificateStatus"`
}
type SetCertificatesStatusResponse struct {
}
// TODO: List of CertificateID
type DeleteCertificates struct {
XMLName string `xml:"tds:DeleteCertificates"`
CertificateID xsd.Token `xml:"tds:CertificateID"`
}
type DeleteCertificatesResponse struct {
}
// TODO: Откуда onvif:data = cid:21312413412
type GetPkcs10Request struct {
XMLName string `xml:"tds:GetPkcs10Request"`
CertificateID xsd.Token `xml:"tds:CertificateID"`
Subject xsd.String `xml:"tds:Subject"`
Attributes onvif.BinaryData `xml:"tds:Attributes"`
}
type GetPkcs10RequestResponse struct {
Pkcs10Request onvif.BinaryData
}
// TODO: one or more NTVCertificate
type LoadCertificates struct {
XMLName string `xml:"tds:LoadCertificates"`
NVTCertificate onvif.Certificate `xml:"tds:NVTCertificate"`
}
type LoadCertificatesResponse struct {
}
type GetClientCertificateMode struct {
XMLName string `xml:"tds:GetClientCertificateMode"`
}
type GetClientCertificateModeResponse struct {
Enabled xsd.Boolean
}
type SetClientCertificateMode struct {
XMLName string `xml:"tds:SetClientCertificateMode"`
Enabled xsd.Boolean `xml:"tds:Enabled"`
}
type SetClientCertificateModeResponse struct {
}
type GetRelayOutputs struct {
XMLName string `xml:"tds:GetRelayOutputs"`
}
type GetRelayOutputsResponse struct {
RelayOutputs []onvif.RelayOutput
}
type GetDigitalInputs struct {
XMLName string `xml:"tmd:GetDigitalInputs"`
}
type GetDigitalInputsResponse struct {
DigitalInputs []onvif.DigitalInput
}
type SetRelayOutputSettings struct {
XMLName string `xml:"tds:SetRelayOutputSettings"`
RelayOutputToken onvif.ReferenceToken `xml:"tds:RelayOutputToken"`
Properties onvif.RelayOutputSettings `xml:"tds:Properties"`
}
type SetRelayOutputSettingsResponse struct {
}
type SetRelayOutputState struct {
XMLName string `xml:"tds:SetRelayOutputState"`
RelayOutputToken onvif.ReferenceToken `xml:"tds:RelayOutputToken"`
LogicalState onvif.RelayLogicalState `xml:"tds:LogicalState"`
}
type SetRelayOutputStateResponse struct {
}
type SendAuxiliaryCommand struct {
XMLName string `xml:"tds:SendAuxiliaryCommand"`
AuxiliaryCommand onvif.AuxiliaryData `xml:"tds:AuxiliaryCommand"`
}
type SendAuxiliaryCommandResponse struct {
AuxiliaryCommandResponse onvif.AuxiliaryData
}
type GetCACertificates struct {
XMLName string `xml:"tds:GetCACertificates"`
}
type GetCACertificatesResponse struct {
CACertificate onvif.Certificate
}
// TODO: one or more CertificateWithPrivateKey
type LoadCertificateWithPrivateKey struct {
XMLName string `xml:"tds:LoadCertificateWithPrivateKey"`
CertificateWithPrivateKey onvif.CertificateWithPrivateKey `xml:"tds:CertificateWithPrivateKey"`
}
type LoadCertificateWithPrivateKeyResponse struct {
}
type GetCertificateInformation struct {
XMLName string `xml:"tds:GetCertificateInformation"`
CertificateID xsd.Token `xml:"tds:CertificateID"`
}
type GetCertificateInformationResponse struct {
CertificateInformation onvif.CertificateInformation
}
type LoadCACertificates struct {
XMLName string `xml:"tds:LoadCACertificates"`
CACertificate onvif.Certificate `xml:"tds:CACertificate"`
}
type LoadCACertificatesResponse struct {
}
type CreateDot1XConfiguration struct {
XMLName string `xml:"tds:CreateDot1XConfiguration"`
Dot1XConfiguration onvif.Dot1XConfiguration `xml:"tds:Dot1XConfiguration"`
}
type CreateDot1XConfigurationResponse struct {
}
type SetDot1XConfiguration struct {
XMLName string `xml:"tds:SetDot1XConfiguration"`
Dot1XConfiguration onvif.Dot1XConfiguration `xml:"tds:Dot1XConfiguration"`
}
type SetDot1XConfigurationResponse struct {
}
type GetDot1XConfiguration struct {
XMLName string `xml:"tds:GetDot1XConfiguration"`
Dot1XConfigurationToken onvif.ReferenceToken `xml:"tds:Dot1XConfigurationToken"`
}
type GetDot1XConfigurationResponse struct {
Dot1XConfiguration onvif.Dot1XConfiguration
}
type GetDot1XConfigurations struct {
XMLName string `xml:"tds:GetDot1XConfigurations"`
}
type GetDot1XConfigurationsResponse struct {
Dot1XConfiguration onvif.Dot1XConfiguration
}
// TODO: Zero or more Dot1XConfigurationToken
type DeleteDot1XConfiguration struct {
XMLName string `xml:"tds:DeleteDot1XConfiguration"`
Dot1XConfigurationToken onvif.ReferenceToken `xml:"tds:Dot1XConfigurationToken"`
}
type DeleteDot1XConfigurationResponse struct {
}
type GetDot11Capabilities struct {
XMLName string `xml:"tds:GetDot11Capabilities"`
}
type GetDot11CapabilitiesResponse struct {
Capabilities onvif.Dot11Capabilities
}
type GetDot11Status struct {
XMLName string `xml:"tds:GetDot11Status"`
InterfaceToken onvif.ReferenceToken `xml:"tds:InterfaceToken"`
}
type GetDot11StatusResponse struct {
Status onvif.Dot11Status
}
type ScanAvailableDot11Networks struct {
XMLName string `xml:"tds:ScanAvailableDot11Networks"`
InterfaceToken onvif.ReferenceToken `xml:"tds:InterfaceToken"`
}
type ScanAvailableDot11NetworksResponse struct {
Networks onvif.Dot11AvailableNetworks
}
type GetSystemUris struct {
XMLName string `xml:"tds:GetSystemUris"`
}
type GetSystemUrisResponse struct {
SystemLogUris onvif.SystemLogUriList
SupportInfoUri xsd.AnyURI
SystemBackupUri xsd.AnyURI
Extension xsd.AnyType
}
type StartFirmwareUpgrade struct {
XMLName string `xml:"tds:StartFirmwareUpgrade"`
}
type StartFirmwareUpgradeResponse struct {
UploadUri xsd.AnyURI
UploadDelay xsd.Duration
ExpectedDownTime xsd.Duration
}
type StartSystemRestore struct {
XMLName string `xml:"tds:StartSystemRestore"`
}
type StartSystemRestoreResponse struct {
UploadUri xsd.AnyURI
ExpectedDownTime xsd.Duration
}
type GetStorageConfigurations struct {
XMLName string `xml:"tds:GetStorageConfigurations"`
}
type GetStorageConfigurationsResponse struct {
StorageConfigurations []StorageConfiguration
}
type CreateStorageConfiguration struct {
XMLName string `xml:"tds:CreateStorageConfiguration"`
StorageConfiguration StorageConfigurationData `xml:"tds:StorageConfiguration"`
}
type CreateStorageConfigurationResponse struct {
Token onvif.ReferenceToken
}
type GetStorageConfiguration struct {
XMLName string `xml:"tds:GetStorageConfiguration"`
Token onvif.ReferenceToken `xml:"tds:Token"`
}
type GetStorageConfigurationResponse struct {
StorageConfiguration StorageConfiguration
}
type SetStorageConfiguration struct {
XMLName string `xml:"tds:SetStorageConfiguration"`
StorageConfiguration struct {
Token xsd.String `xml:"token,attr"`
Data StorageConfigurationData `xml:"tds:Data"`
} `xml:"tds:StorageConfiguration"`
}
type SetStorageConfigurationResponse struct {
}
type DeleteStorageConfiguration struct {
XMLName string `xml:"tds:DeleteStorageConfiguration"`
Token onvif.ReferenceToken `xml:"tds:Token"`
}
type DeleteStorageConfigurationResponse struct {
}
type GetGeoLocation struct {
XMLName string `xml:"tds:GetGeoLocation"`
}
type GetGeoLocationResponse struct {
Location onvif.LocationEntity
}
// TODO: one or more Location
type SetGeoLocation struct {
XMLName string `xml:"tds:SetGeoLocation"`
Location onvif.LocationEntity `xml:"tds:Location"`
}
type SetGeoLocationResponse struct {
}
type DeleteGeoLocation struct {
XMLName string `xml:"tds:DeleteGeoLocation"`
Location onvif.LocationEntity `xml:"tds:Location"`
}
type DeleteGeoLocationResponse struct {
}

111
digestclient.go Normal file
View File

@@ -0,0 +1,111 @@
package onvif
import (
"crypto/md5"
"crypto/rand"
"encoding/hex"
"fmt"
"io"
"net/http"
"strings"
)
// DigestClient represents an HTTP client used for making requests authenticated
// with http digest authentication.
type DigestClient struct {
client *http.Client
username string
password string
snonce string
realm string
qop string
nonceCount uint32
}
// NewDigestClient returns a DigestClient that wraps a given standard library http Client with the given username and password
func NewDigestClient(stdClient *http.Client, username string, password string) *DigestClient {
return &DigestClient{
client: stdClient,
username: username,
password: password,
}
}
func (dc *DigestClient) Do(httpMethod string, endpoint string, soap string) (*http.Response, error) {
req, err := createHttpRequest(httpMethod, endpoint, soap)
if err != nil {
return nil, err
}
if dc.snonce != "" {
req.Header.Set("Authorization", dc.getDigestAuth(req.Method, req.URL.String()))
}
// Attempt the request using the underlying client
resp, err := dc.client.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusUnauthorized {
return resp, nil
}
dc.getDigestParts(resp)
// We will need to return the response from another request, so defer a close on this one
defer resp.Body.Close()
req, err = createHttpRequest(httpMethod, endpoint, soap)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", dc.getDigestAuth(req.Method, req.URL.String()))
authedResp, err := dc.client.Do(req)
if err != nil {
return nil, err
}
return authedResp, nil
}
func (dc *DigestClient) getDigestParts(resp *http.Response) {
result := map[string]string{}
authHeader := resp.Header.Get("WWW-Authenticate")
if len(authHeader) > 0 {
wantedHeaders := []string{"nonce", "realm", "qop"}
responseHeaders := strings.Split(authHeader, ",")
for _, r := range responseHeaders {
for _, w := range wantedHeaders {
if strings.Contains(r, w) {
result[w] = strings.Split(r, `"`)[1]
}
}
}
}
dc.snonce = result["nonce"]
dc.realm = result["realm"]
dc.qop = result["qop"]
dc.nonceCount = 0
}
func getMD5(text string) string {
hasher := md5.New()
hasher.Write([]byte(text))
return hex.EncodeToString(hasher.Sum(nil))
}
func getCnonce() string {
b := make([]byte, 8)
io.ReadFull(rand.Reader, b)
return fmt.Sprintf("%x", b)[:16]
}
func (dc *DigestClient) getDigestAuth(method string, uri string) string {
ha1 := getMD5(dc.username + ":" + dc.realm + ":" + dc.password)
ha2 := getMD5(method + ":" + uri)
cnonce := getCnonce()
dc.nonceCount++
response := getMD5(fmt.Sprintf("%s:%s:%v:%s:%s:%s", ha1, dc.snonce, dc.nonceCount, cnonce, dc.qop, ha2))
authorization := fmt.Sprintf(`Digest username="%s", realm="%s", nonce="%s", uri="%s", cnonce="%s", nc="%v", qop="%s", response="%s"`,
dc.username, dc.realm, dc.snonce, uri, cnonce, dc.nonceCount, dc.qop, response)
return authorization
}

2
doc.go
View File

@@ -1,2 +1,2 @@
//Package onvif is developed to provide an ONVIF client implementation on Go programming language
// Package onvif is developed to provide an ONVIF client implementation on Go programming language
package onvif

34
docs/Development.md Normal file
View File

@@ -0,0 +1,34 @@
# Development
## Onvif Command Support
Each of the following Onvif Web services has its own directory:
- [Analytics](../analytics)
- [Device](../device)
- [Event](../event)
- [Imaging](../imaging)
- [Media](../media)
- [Media2](../media2)
- [PTZ](../ptz)
Inside each directory there is:
- `types.go`: contains the struct definitions for each onvif command and response
- `function.go`: contains the auto-generated types that implement the `Function` interface providing `Request()` and `Response()` type mappings.
At the root level there is:
- [names.go](../names.go): contains the auto-generated constant names of all the commands
- [mappings.go](../mappings.go): contains the auto-generated mappings for each Onvif WebService from function name to function datatype
### Adding support for additional commands
> **Note:** Currently, the python script looks for types that end with `Response` and work backwards from there.
> This is to prevent creating commands for every struct type defined there, and only the ones that are actually commands.
> It also skips any types ending with `FaultResponse`, as there typically are no `Fault` commands, only responses.
For the respective web service the command belongs to, add the command and response struct definitions
into `<web-service-name>/types.go`, and then run:
```shell
python3 python/gen_commands.py
```
> **Note:** You can also typically run the generator within your IDE thanks to the `//go:generate` lines
> towards the top of the `types.go` files.

99
event/function.go Normal file
View File

@@ -0,0 +1,99 @@
// -*- Mode: Go; indent-tabs-mode: t -*-
//
// Copyright (C) 2022 Intel Corporation
//
// SPDX-License-Identifier: Apache-2.0
// Code generated by gen_commands.py DO NOT EDIT.
package event
type CreatePullPointSubscriptionFunction struct{}
func (_ *CreatePullPointSubscriptionFunction) Request() interface{} {
return &CreatePullPointSubscription{}
}
func (_ *CreatePullPointSubscriptionFunction) Response() interface{} {
return &CreatePullPointSubscriptionResponse{}
}
type GetEventPropertiesFunction struct{}
func (_ *GetEventPropertiesFunction) Request() interface{} {
return &GetEventProperties{}
}
func (_ *GetEventPropertiesFunction) Response() interface{} {
return &GetEventPropertiesResponse{}
}
type GetServiceCapabilitiesFunction struct{}
func (_ *GetServiceCapabilitiesFunction) Request() interface{} {
return &GetServiceCapabilities{}
}
func (_ *GetServiceCapabilitiesFunction) Response() interface{} {
return &GetServiceCapabilitiesResponse{}
}
type PullMessagesFunction struct{}
func (_ *PullMessagesFunction) Request() interface{} {
return &PullMessages{}
}
func (_ *PullMessagesFunction) Response() interface{} {
return &PullMessagesResponse{}
}
type RenewFunction struct{}
func (_ *RenewFunction) Request() interface{} {
return &Renew{}
}
func (_ *RenewFunction) Response() interface{} {
return &RenewResponse{}
}
type SeekFunction struct{}
func (_ *SeekFunction) Request() interface{} {
return &Seek{}
}
func (_ *SeekFunction) Response() interface{} {
return &SeekResponse{}
}
type SetSynchronizationPointFunction struct{}
func (_ *SetSynchronizationPointFunction) Request() interface{} {
return &SetSynchronizationPoint{}
}
func (_ *SetSynchronizationPointFunction) Response() interface{} {
return &SetSynchronizationPointResponse{}
}
type SubscribeFunction struct{}
func (_ *SubscribeFunction) Request() interface{} {
return &Subscribe{}
}
func (_ *SubscribeFunction) Response() interface{} {
return &SubscribeResponse{}
}
type SubscriptionReferenceFunction struct{}
func (_ *SubscriptionReferenceFunction) Request() interface{} {
return &SubscriptionReference{}
}
func (_ *SubscriptionReferenceFunction) Response() interface{} {
return &SubscriptionReferenceResponse{}
}
type UnsubscribeFunction struct{}
func (_ *UnsubscribeFunction) Request() interface{} {
return &Unsubscribe{}
}
func (_ *UnsubscribeFunction) Response() interface{} {
return &UnsubscribeResponse{}
}

View File

@@ -1,131 +0,0 @@
package event
import (
"github.com/use-go/onvif/xsd"
)
//GetServiceCapabilities action
type GetServiceCapabilities struct {
XMLName string `xml:"tev:GetServiceCapabilities"`
}
//GetServiceCapabilitiesResponse type
type GetServiceCapabilitiesResponse struct {
Capabilities Capabilities
}
//SubscriptionPolicy action
type SubscriptionPolicy struct { //tev http://www.onvif.org/ver10/events/wsdl
ChangedOnly xsd.Boolean `xml:"ChangedOnly,attr"`
}
//Subscribe action for subscribe event topic
type Subscribe struct { //http://docs.oasis-open.org/wsn/b-2.xsd
XMLName struct{} `xml:"wsnt:Subscribe"`
ConsumerReference EndpointReferenceType `xml:"wsnt:ConsumerReference"`
Filter FilterType `xml:"wsnt:Filter"`
SubscriptionPolicy SubscriptionPolicy `xml:"wsnt:SubscriptionPolicy"`
InitialTerminationTime TerminationTime `xml:"wsnt:InitialTerminationTime"`
}
//SubscribeResponse message for subscribe event topic
type SubscribeResponse struct { //http://docs.oasis-open.org/wsn/b-2.xsd
ConsumerReference EndpointReferenceType `xml:"wsnt:ConsumerReference"`
CurrentTime CurrentTime `xml:"wsnt:CurrentTime"`
TerminationTime TerminationTime `xml:"wsnt:TerminationTime"`
}
//Renew action for refresh event topic subscription
type Renew struct { //http://docs.oasis-open.org/wsn/b-2.xsd
TerminationTime AbsoluteOrRelativeTimeType `xml:"wsnt:TerminationTime"`
}
//RenewResponse for Renew action
type RenewResponse struct { //http://docs.oasis-open.org/wsn/b-2.xsd
TerminationTime TerminationTime `xml:"wsnt:TerminationTime"`
CurrentTime CurrentTime `xml:"wsnt:CurrentTime"`
}
//Unsubscribe action for Unsubscribe event topic
type Unsubscribe struct { //http://docs.oasis-open.org/wsn/b-2.xsd
Any string
}
//UnsubscribeResponse message for Unsubscribe event topic
type UnsubscribeResponse struct { //http://docs.oasis-open.org/wsn/b-2.xsd
Any string
}
//CreatePullPointSubscription action
//BUG(r) Bad AbsoluteOrRelativeTimeType type
type CreatePullPointSubscription struct {
XMLName string `xml:"tev:CreatePullPointSubscription"`
Filter FilterType `xml:"tev:Filter"`
InitialTerminationTime AbsoluteOrRelativeTimeType `xml:"wsnt:InitialTerminationTime"`
SubscriptionPolicy SubscriptionPolicy `xml:"wsnt:sSubscriptionPolicy"`
}
//CreatePullPointSubscriptionResponse action
type CreatePullPointSubscriptionResponse struct {
SubscriptionReference EndpointReferenceType
CurrentTime CurrentTime
TerminationTime TerminationTime
}
//GetEventProperties action
type GetEventProperties struct {
XMLName string `xml:"tev:GetEventProperties"`
}
//GetEventPropertiesResponse action
type GetEventPropertiesResponse struct {
TopicNamespaceLocation xsd.AnyURI
FixedTopicSet FixedTopicSet
TopicSet TopicSet
TopicExpressionDialect TopicExpressionDialect
MessageContentFilterDialect xsd.AnyURI
ProducerPropertiesFilterDialect xsd.AnyURI
MessageContentSchemaLocation xsd.AnyURI
}
//Port type PullPointSubscription
//PullMessages Action
type PullMessages struct {
XMLName string `xml:"tev:PullMessages"`
Timeout xsd.Duration `xml:"tev:Timeout"`
MessageLimit xsd.Int `xml:"tev:MessageLimit"`
}
//PullMessagesResponse response type
type PullMessagesResponse struct {
CurrentTime CurrentTime
TerminationTime TerminationTime
NotificationMessage NotificationMessage
}
//PullMessagesFaultResponse response type
type PullMessagesFaultResponse struct {
MaxTimeout xsd.Duration
MaxMessageLimit xsd.Int
}
//Seek action
type Seek struct {
XMLName string `xml:"tev:Seek"`
UtcTime xsd.DateTime `xml:"tev:UtcTime"`
Reverse xsd.Boolean `xml:"tev:Reverse"`
}
//SeekResponse action
type SeekResponse struct {
}
//SetSynchronizationPoint action
type SetSynchronizationPoint struct {
XMLName string `xml:"tev:SetSynchronizationPoint"`
}
//SetSynchronizationPointResponse action
type SetSynchronizationPointResponse struct {
}

View File

@@ -0,0 +1,22 @@
package topic
import "github.com/kerberos-io/onvif/xsd"
type MessageDescription struct {
IsProperty xsd.Boolean `xml:"IsProperty,attr"`
Source Source `json:",omitempty" xml:",omitempty"`
Data Data `json:",omitempty" xml:",omitempty"`
}
type Source struct {
SimpleItemDescription []SimpleItemDescription `json:",omitempty" xml:",omitempty"`
}
type Data struct {
SimpleItemDescription []SimpleItemDescription `json:",omitempty" xml:",omitempty"`
}
type SimpleItemDescription struct {
Name xsd.AnyType `xml:"Name,attr"`
Type xsd.AnyType `xml:"Type,attr"`
}

63
event/topic/ruleengine.go Normal file
View File

@@ -0,0 +1,63 @@
package topic
import "github.com/kerberos-io/onvif/xsd"
type RuleEngine struct {
Topic *xsd.Boolean `xml:"topic,attr"`
MotionRegionDetector *MotionRegionDetector `json:",omitempty" xml:",omitempty"`
CellMotionDetector *CellMotionDetector `json:",omitempty" xml:",omitempty"`
TamperDetector *TamperDetector `json:",omitempty" xml:",omitempty"`
Recognition *Recognition `json:",omitempty" xml:",omitempty"`
CountAggregation *CountAggregation `json:",omitempty" xml:",omitempty"`
}
type MotionRegionDetector struct {
Topic *xsd.Boolean `xml:"topic,attr"`
Motion *Motion `json:"Motion" xml:"Motion"`
}
type CellMotionDetector struct {
Topic *xsd.Boolean `xml:"topic,attr"`
Motion *Motion
}
type Motion struct {
Topic *xsd.Boolean `xml:"topic,attr"`
MessageDescription *MessageDescription `json:",omitempty" xml:",omitempty"`
}
type TamperDetector struct {
Topic *xsd.Boolean `xml:"topic,attr"`
Tamper *Tamper
}
type Tamper struct {
Topic *xsd.Boolean `xml:"topic,attr"`
MessageDescription *MessageDescription `json:",omitempty" xml:",omitempty"`
}
type Recognition struct {
Topic *xsd.Boolean `xml:"topic,attr"`
Face *Face `json:",omitempty" xml:",omitempty"`
LicensePlate *Face `json:",omitempty" xml:",omitempty"`
}
type Face struct {
Topic *xsd.Boolean `xml:"topic,attr"`
MessageDescription *MessageDescription `json:",omitempty" xml:",omitempty"`
}
type LicensePlate struct {
Topic *xsd.Boolean `xml:"topic,attr"`
MessageDescription *MessageDescription `json:",omitempty" xml:",omitempty"`
}
type CountAggregation struct {
Topic *xsd.Boolean `xml:"topic,attr"`
Counter *Counter `json:",omitempty" xml:",omitempty"`
}
type Counter struct {
Topic *xsd.Boolean `xml:"topic,attr"`
MessageDescription *MessageDescription `json:",omitempty" xml:",omitempty"`
}

92
event/type_test.go Normal file
View File

@@ -0,0 +1,92 @@
package event
import (
"encoding/xml"
"testing"
"github.com/kerberos-io/onvif/xsd"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
var eventPropertiesData = []byte(`
<tev:GetEventPropertiesResponse>
<tev:TopicNamespaceLocation>http://www.onvif.org/onvif/ver10/topics/topicns.xml</tev:TopicNamespaceLocation>
<wsnt:FixedTopicSet>true</wsnt:FixedTopicSet>
<wstop:TopicSet>
<tns1:UserAlarm wstop:topic="true">
<tnshik:IllegalAccess wstop:topic="true"/>
</tns1:UserAlarm>
<tns1:RuleEngine wstop:topic="true">
<CellMotionDetector wstop:topic="true">
<Motion wstop:topic="true">
<tt:MessageDescription IsProperty="true">
<tt:Source>
<tt:SimpleItemDescription Name="VideoSourceConfigurationToken" Type="tt:ReferenceToken"/>
<tt:SimpleItemDescription Name="VideoAnalyticsConfigurationToken" Type="tt:ReferenceToken"/>
<tt:SimpleItemDescription Name="Rule" Type="xs:string"/>
</tt:Source>
<tt:Data>
<tt:SimpleItemDescription Name="IsMotion" Type="xs:boolean"/>
</tt:Data>
</tt:MessageDescription>
</Motion>
</CellMotionDetector>
<TamperDetector wstop:topic="true">
<Tamper wstop:topic="true">
<tt:MessageDescription IsProperty="true">
<tt:Source>
<tt:SimpleItemDescription Name="VideoSourceConfigurationToken" Type="tt:ReferenceToken"/>
<tt:SimpleItemDescription Name="VideoAnalyticsConfigurationToken" Type="tt:ReferenceToken"/>
<tt:SimpleItemDescription Name="Rule" Type="xs:string"/>
</tt:Source>
<tt:Data>
<tt:SimpleItemDescription Name="IsTamper" Type="xs:boolean"/>
</tt:Data>
</tt:MessageDescription>
</Tamper>
</TamperDetector>
</tns1:RuleEngine>
</wstop:TopicSet>
<tev:MessageContentFilterDialect>http://www.onvif.org/ver10/tev/messageContentFilter/ItemFilter</tev:MessageContentFilterDialect>
<tev:MessageContentSchemaLocation>http://www.onvif.org/onvif/ver10/schema/onvif.xsd</tev:MessageContentSchemaLocation>
</tev:GetEventPropertiesResponse>
`)
var eventRenewResponse = []byte(`
<tev:RenewResponse>
<wsnt:TerminationTime>2023-11-25T18:08:15Z</wsnt:TerminationTime>
<wsnt:CurrentTime>2023-11-24T14:50:25Z</wsnt:CurrentTime>
</tev:RenewResponse>
`)
func TestEventPropertiesUnmarshalXML(t *testing.T) {
res := GetEventPropertiesResponse{}
err := xml.Unmarshal(eventPropertiesData, &res)
require.NoError(t, err)
assert.Equal(t, FixedTopicSet(true), *res.FixedTopicSet)
assert.Equal(t, xsd.AnyURI("http://www.onvif.org/ver10/tev/messageContentFilter/ItemFilter"), *res.MessageContentFilterDialect)
assert.Equal(t, xsd.AnyURI("http://www.onvif.org/onvif/ver10/schema/onvif.xsd"), *res.MessageContentSchemaLocation)
userAlarm, exists := map[string]interface{}(*res.TopicSet)["tns1:UserAlarm"]
assert.True(t, exists)
_, exists = (userAlarm).(map[string]interface{})["tnshik:IllegalAccess"]
assert.True(t, exists)
ruleEngine, exists := map[string]interface{}(*res.TopicSet)["tns1:RuleEngine"]
assert.True(t, exists)
tamperDetector, exists := (ruleEngine).(map[string]interface{})["TamperDetector"]
assert.True(t, exists)
tamper, exists := (tamperDetector).(map[string]interface{})["Tamper"]
assert.True(t, exists)
_, exists = (tamper).(map[string]interface{})["tt:MessageDescription"]
assert.True(t, exists)
}
func TestRenewFunction_Response(t *testing.T) {
res := RenewResponse{}
err := xml.Unmarshal(eventRenewResponse, &res)
require.NoError(t, err)
assert.NotNil(t, res.TerminationTime)
assert.NotNil(t, res.CurrentTime)
assert.Equal(t, xsd.String("2023-11-25T18:08:15Z"), *res.TerminationTime)
assert.Equal(t, xsd.String("2023-11-24T14:50:25Z"), *res.CurrentTime)
}

View File

@@ -1,121 +1,176 @@
package event
//go:generate python3 ../python/gen_commands.py
import (
"github.com/use-go/onvif/xsd"
"encoding/xml"
"fmt"
"reflect"
mv "github.com/clbanning/mxj/v2"
"github.com/kerberos-io/onvif/event/topic"
"github.com/kerberos-io/onvif/xsd"
)
//Address Alias
// Address Alias
type Address xsd.String
//CurrentTime alias
// CurrentTime alias
type CurrentTime xsd.DateTime //wsnt http://docs.oasis-open.org/wsn/b-2.xsd
//TerminationTime alias
// TerminationTime alias
type TerminationTime xsd.DateTime //wsnt http://docs.oasis-open.org/wsn/b-2.xsd
//FixedTopicSet alias
// FixedTopicSet alias
type FixedTopicSet xsd.Boolean //wsnt http://docs.oasis-open.org/wsn/b-2.xsd
//Documentation alias
// Documentation alias
type Documentation xsd.AnyType //wstop http://docs.oasis-open.org/wsn/t-1.xsd
//TopicExpressionDialect alias
// TopicExpressionDialect alias
type TopicExpressionDialect xsd.AnyURI
//Message alias
// Message alias
type Message xsd.AnyType
//ActionType for AttributedURIType
// ActionType for AttributedURIType
type ActionType AttributedURIType
//AttributedURIType in ws-addr
// AttributedURIType in ws-addr
type AttributedURIType xsd.AnyURI //wsa https://www.w3.org/2005/08/addressing/ws-addr.xsd
//AbsoluteOrRelativeTimeType <xsd:union memberTypes="xsd:dateTime xsd:duration"/>
// AbsoluteOrRelativeTimeType <xsd:union memberTypes="xsd:dateTime xsd:duration"/>
type AbsoluteOrRelativeTimeType struct { //wsnt http://docs.oasis-open.org/wsn/b-2.xsd
xsd.DateTime
xsd.Duration
}
//EndpointReferenceType in ws-addr
// EndpointReferenceType in ws-addr
type EndpointReferenceType struct { //wsa http://www.w3.org/2005/08/addressing/ws-addr.xsd
Address AttributedURIType `xml:"wsnt:Address"`
ReferenceParameters ReferenceParametersType `xml:"wsnt:ReferenceParameters"`
Metadata MetadataType `xml:"wsnt:Metadata"`
Address AttributedURIType `xml:"wsa:Address"`
ReferenceParameters *ReferenceParametersType
Metadata *MetadataType `xml:"Metadata"`
}
// FilterType struct
type FilterType struct {
TopicExpression TopicExpressionType `xml:"wsnt:TopicExpression"`
MessageContent QueryExpressionType `xml:"wsnt:MessageContent"`
TopicExpression *TopicExpressionType `xml:"wsnt:TopicExpression,omitempty"`
MessageContent *QueryExpressionType `xml:"wsnt:MessageContent,omitempty"`
}
//EndpointReference alais
// EndpointReference alias
type EndpointReference EndpointReferenceType
//ReferenceParametersType in ws-addr
// ReferenceParametersType in ws-addr
type ReferenceParametersType struct { //wsa https://www.w3.org/2005/08/addressing/ws-addr.xsd
//Here can be anyAttribute
}
//Metadata in ws-addr
// Metadata in ws-addr
type Metadata MetadataType //wsa https://www.w3.org/2005/08/addressing/ws-addr.xsd
//MetadataType in ws-addr
// MetadataType in ws-addr
type MetadataType struct { //wsa https://www.w3.org/2005/08/addressing/ws-addr.xsd
//Here can be anyAttribute
}
//TopicSet alias
type TopicSet TopicSetType //wstop http://docs.oasis-open.org/wsn/t-1.xsd
// TopicSet alias
type TopicSet map[string]interface{} //wstop http://docs.oasis-open.org/wsn/t-1.xsd
//TopicSetType alias
type TopicSetType struct { //wstop http://docs.oasis-open.org/wsn/t-1.xsd
ExtensibleDocumented
//here can be any element
type Node struct {
XMLName xml.Name
Content []byte `xml:",innerxml"`
}
//ExtensibleDocumented struct
func (n *TopicSet) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
node := Node{}
err := d.DecodeElement(&node, &start)
if err != nil {
return err
}
wrapper := "root" // The TopicSet is an array, we need to wrap with a tag for XML parsing
c := fmt.Sprintf("<%s>%s</%s>", wrapper, node.Content, wrapper)
result, err := mv.NewMapXmlSeq([]byte(c))
if err != nil {
return err
}
if result[wrapper] != nil && reflect.ValueOf(result[wrapper]).Kind() == reflect.Map {
*n = (result[wrapper]).(map[string]interface{})
}
return nil
}
// TopicSetType alias
type TopicSetType struct { //wstop http://docs.oasis-open.org/wsn/t-1.xsd
//ExtensibleDocumented
//here can be any element
RuleEngine *topic.RuleEngine `json:"tns:RuleEngine,omitempty" xml:",omitempty"`
}
// ExtensibleDocumented struct
type ExtensibleDocumented struct { //wstop http://docs.oasis-open.org/wsn/t-1.xsd
Documentation Documentation //к xsd-документе documentation с маленькой буквы начинается
//here can be anyAttribute
}
//ProducerReference Alias
// ProducerReference Alias
type ProducerReference EndpointReferenceType
//SubscriptionReference Alias
// SubscriptionReference Alias
type SubscriptionReference EndpointReferenceType
//NotificationMessageHolderType Alias
// NotificationMessageHolderType Alias
type NotificationMessageHolderType struct {
SubscriptionReference SubscriptionReference //wsnt http://docs.oasis-open.org/wsn/b-2.xsd
Topic Topic
ProducerReference ProducerReference
Message Message
Message MessageBody
}
//NotificationMessage Alias
type MessageBody struct {
Message MessageDescription
}
type MessageDescription struct {
PropertyOperation xsd.AnyType `xml:"PropertyOperation,attr"`
Source Source `json:",omitempty" xml:",omitempty"`
Data Data `json:",omitempty" xml:",omitempty"`
}
type Source struct {
SimpleItem []SimpleItem `json:",omitempty" xml:",omitempty"`
}
type Data struct {
SimpleItem []SimpleItem `json:",omitempty" xml:",omitempty"`
}
type SimpleItem struct {
Name xsd.AnyType `xml:"Name,attr"`
Value xsd.AnyType `xml:"Value,attr"`
}
// NotificationMessage Alias
type NotificationMessage NotificationMessageHolderType //wsnt http://docs.oasis-open.org/wsn/b-2.xsd
//QueryExpressionType struct for wsnt:MessageContent
// QueryExpressionType struct for wsnt:MessageContent
type QueryExpressionType struct { //wsnt http://docs.oasis-open.org/wsn/b-2.xsd
Dialect xsd.AnyURI `xml:"Dialect,attr"`
MessageKind xsd.String `xml:",chardata"` // boolean(ncex:Producer="15")
}
//MessageContentType Alias
// MessageContentType Alias
type MessageContentType QueryExpressionType
//QueryExpression Alias
// QueryExpression Alias
type QueryExpression QueryExpressionType
//TopicExpressionType struct for wsnt:TopicExpression
// TopicExpressionType struct for wsnt:TopicExpression
type TopicExpressionType struct { //wsnt http://docs.oasis-open.org/wsn/b-2.xsd
Dialect xsd.AnyURI `xml:"Dialect,attr"`
Dialect xsd.String `xml:"Dialect,attr"`
TopicKinds xsd.String `xml:",chardata"`
}
//Topic Alias
// Topic Alias
type Topic TopicExpressionType
// Capabilities of event
@@ -128,50 +183,190 @@ type Capabilities struct { //tev
PersistentNotificationStorage xsd.Boolean `xml:"PersistentNotificationStorage,attr"`
}
//ResourceUnknownFault response type
// ResourceUnknownFault response type
type ResourceUnknownFault struct {
}
//InvalidFilterFault response type
// InvalidFilterFault response type
type InvalidFilterFault struct {
}
//TopicExpressionDialectUnknownFault response type
// TopicExpressionDialectUnknownFault response type
type TopicExpressionDialectUnknownFault struct {
}
//InvalidTopicExpressionFault response type
// InvalidTopicExpressionFault response type
type InvalidTopicExpressionFault struct {
}
//TopicNotSupportedFault response type
// TopicNotSupportedFault response type
type TopicNotSupportedFault struct {
}
//InvalidProducerPropertiesExpressionFault response type
// InvalidProducerPropertiesExpressionFault response type
type InvalidProducerPropertiesExpressionFault struct {
}
//InvalidMessageContentExpressionFault response type
// InvalidMessageContentExpressionFault response type
type InvalidMessageContentExpressionFault struct {
}
//UnacceptableInitialTerminationTimeFault response type
// UnacceptableInitialTerminationTimeFault response type
type UnacceptableInitialTerminationTimeFault struct {
}
//UnrecognizedPolicyRequestFault response type
// UnrecognizedPolicyRequestFault response type
type UnrecognizedPolicyRequestFault struct {
}
//UnsupportedPolicyRequestFault response type
// UnsupportedPolicyRequestFault response type
type UnsupportedPolicyRequestFault struct {
}
//NotifyMessageNotSupportedFault response type
// NotifyMessageNotSupportedFault response type
type NotifyMessageNotSupportedFault struct {
}
//SubscribeCreationFailedFault response type
// SubscribeCreationFailedFault response type
type SubscribeCreationFailedFault struct {
}
// GetServiceCapabilities action
type GetServiceCapabilities struct {
XMLName string `xml:"tev:GetServiceCapabilities"`
}
// GetServiceCapabilitiesResponse type
type GetServiceCapabilitiesResponse struct {
Capabilities Capabilities
}
// SubscriptionPolicy action
type SubscriptionPolicy struct { //tev http://www.onvif.org/ver10/events/wsdl
ChangedOnly xsd.Boolean `xml:"ChangedOnly,attr"`
string
}
// Subscribe action for subscribe event topic
type Subscribe struct { //http://docs.oasis-open.org/wsn/b-2.xsd
XMLName struct{} `xml:"wsnt:Subscribe"`
ConsumerReference *EndpointReferenceType `xml:"wsnt:ConsumerReference"`
Filter *FilterType `xml:"wsnt:Filter"`
SubscriptionPolicy *xsd.String `xml:"wsnt:SubscriptionPolicy"`
TerminationTime *xsd.String `xml:"wsnt:TerminationTime"`
}
// SubscribeResponse message for subscribe event topic
type SubscribeResponse struct { //http://docs.oasis-open.org/wsn/b-2.xsd
SubscriptionReference SubscriptionReferenceResponse
CurrentTime *xsd.String
TerminationTime *xsd.String
}
// Renew action for refresh event topic subscription
type Renew struct { //http://docs.oasis-open.org/wsn/b-2.xsd
XMLName string `xml:"wsnt:Renew"`
TerminationTime xsd.String `xml:"wsnt:TerminationTime"`
}
// RenewResponse for Renew action
type RenewResponse struct { //http://docs.oasis-open.org/wsn/b-2.xsd
TerminationTime *xsd.String
CurrentTime *xsd.String
}
// Unsubscribe action for Unsubscribe event topic
type Unsubscribe struct { //http://docs.oasis-open.org/wsn/b-2.xsd
XMLName string `xml:"tev:Unsubscribe"`
Any string
}
// UnsubscribeResponse message for Unsubscribe event topic
type UnsubscribeResponse struct { //http://docs.oasis-open.org/wsn/b-2.xsd
Any string
}
// CreatePullPointSubscription action
// BUG(r) Bad AbsoluteOrRelativeTimeType type
type CreatePullPointSubscription struct {
XMLName string `xml:"tev:CreatePullPointSubscription,omitempty"`
Filter *FilterType `xml:"tev:Filter,omitempty"`
InitialTerminationTime *xsd.String `xml:"tev:InitialTerminationTime,omitempty"`
SubscriptionPolicy *xsd.String `xml:"tev:SubscriptionPolicy,omitempty"`
}
// CreatePullPointSubscriptionResponse action
type CreatePullPointSubscriptionResponse struct {
SubscriptionReference SubscriptionReferenceResponse
CurrentTime CurrentTime
TerminationTime TerminationTime
}
type SubscriptionReferenceResponse struct {
Address AttributedURIType
ReferenceParameters *ReferenceParametersType
Metadata *MetadataType
}
// GetEventProperties action
type GetEventProperties struct {
XMLName string `xml:"tev:GetEventProperties"`
}
// GetEventPropertiesResponse action
type GetEventPropertiesResponse struct {
TopicNamespaceLocation *xsd.AnyURI `json:",omitempty" xml:",omitempty"`
FixedTopicSet *FixedTopicSet `json:",omitempty" xml:",omitempty"`
TopicSet *TopicSet `json:",omitempty" xml:",omitempty"`
TopicExpressionDialect *TopicExpressionDialect `json:",omitempty" xml:",omitempty"`
MessageContentFilterDialect *xsd.AnyURI `json:",omitempty" xml:",omitempty"`
ProducerPropertiesFilterDialect *xsd.AnyURI `json:",omitempty" xml:",omitempty"`
MessageContentSchemaLocation *xsd.AnyURI `json:",omitempty" xml:",omitempty"`
}
//Port type PullPointSubscription
// PullMessages Action
type PullMessages struct {
XMLName string `xml:"tev:PullMessages"`
Timeout xsd.Duration `xml:"tev:Timeout"`
MessageLimit xsd.Int `xml:"tev:MessageLimit"`
}
// PullMessagesResponse response type
type PullMessagesResponse struct {
CurrentTime *xsd.String `json:",omitempty" xml:",omitempty"`
TerminationTime *xsd.String `json:",omitempty" xml:",omitempty"`
NotificationMessage []NotificationMessage `json:",omitempty" xml:",omitempty"`
}
// PullMessagesFaultResponse response type
type PullMessagesFaultResponse struct {
MaxTimeout xsd.Duration
MaxMessageLimit xsd.Int
}
// Seek action
type Seek struct {
XMLName string `xml:"tev:Seek"`
UtcTime xsd.DateTime `xml:"tev:UtcTime"`
Reverse xsd.Boolean `xml:"tev:Reverse"`
}
// SeekResponse action
type SeekResponse struct {
}
// SetSynchronizationPoint action
type SetSynchronizationPoint struct {
XMLName string `xml:"tev:SetSynchronizationPoint"`
}
// SetSynchronizationPointResponse action
type SetSynchronizationPointResponse struct {
}
// Notify type
type Notify struct {
NotificationMessage []NotificationMessage `json:",omitempty" xml:",omitempty"`
}

View File

@@ -6,10 +6,10 @@ import (
"log"
"net/http"
goonvif "github.com/use-go/onvif"
"github.com/use-go/onvif/device"
"github.com/use-go/onvif/gosoap"
"github.com/use-go/onvif/xsd/onvif"
goonvif "github.com/kerberos-io/onvif"
"github.com/kerberos-io/onvif/device"
"github.com/kerberos-io/onvif/gosoap"
"github.com/kerberos-io/onvif/xsd/onvif"
)
const (
@@ -27,21 +27,27 @@ func readResponse(resp *http.Response) string {
func main() {
//Getting an camera instance
dev, err := goonvif.NewDevice("192.168.13.14:80")
dev, err := goonvif.NewDevice(goonvif.DeviceParams{
Xaddr: "192.168.13.14:80",
Username: login,
Password: password,
HttpClient: new(http.Client),
})
if err != nil {
panic(err)
}
//Authorization
dev.Authenticate(login, password)
//Preparing commands
UserLevel := onvif.UserLevel("User")
systemDateAndTyme := device.GetSystemDateAndTime{}
getCapabilities := device.GetCapabilities{Category: "All"}
createUser := device.CreateUsers{User: onvif.User{
Username: "TestUser",
Password: "TestPassword",
UserLevel: "User",
},
createUser := device.CreateUsers{
User: []onvif.UserRequest{
{
Username: "TestUser",
Password: "TestPassword",
UserLevel: &UserLevel,
},
},
}
//Commands execution
@@ -51,6 +57,7 @@ func main() {
} else {
fmt.Println(readResponse(systemDateAndTymeResponse))
}
getCapabilities := device.GetCapabilities{Category: []onvif.CapabilityCategory{"All"}}
getCapabilitiesResponse, err := dev.CallMethod(getCapabilities)
if err != nil {
log.Println(err)
@@ -62,7 +69,7 @@ func main() {
log.Println(err)
} else {
/*
You could use https://github.com/use-go/onvif/gosoap for pretty printing response
You could use https://github.com/kerberos-io/onvif/gosoap for pretty printing response
*/
fmt.Println(gosoap.SoapMessage(readResponse(createUserResponse)).StringIndent())
}

View File

@@ -0,0 +1,28 @@
package main
import (
"github.com/kerberos-io/onvif"
"github.com/kerberos-io/onvif/media2"
"io/ioutil"
"log"
)
func main() {
dev, err := onvif.NewDevice(onvif.DeviceParams{
Xaddr: "192.168.12.148", // BOSCH
Username: "administrator",
Password: "Password1!",
AuthMode: onvif.UsernameTokenAuth,
})
if err != nil {
log.Fatalln("fail to new device:", err)
}
res, err := dev.CallMethod(media2.GetAnalyticsConfigurations{})
if err != nil {
log.Fatalln("fail to CallMethod:", err)
}
bs, _ := ioutil.ReadAll(res.Body)
log.Printf(">> Result: %+v \n %s", res.StatusCode, bs)
}

View File

@@ -0,0 +1,28 @@
package main
import (
"github.com/kerberos-io/onvif"
"github.com/kerberos-io/onvif/media2"
"io/ioutil"
"log"
)
func main() {
dev, err := onvif.NewDevice(onvif.DeviceParams{
Xaddr: "192.168.12.148", // BOSCH
Username: "administrator",
Password: "Password1!",
AuthMode: onvif.UsernameTokenAuth,
})
if err != nil {
log.Fatalln("fail to new device:", err)
}
res, err := dev.CallMethod(media2.GetProfiles{})
if err != nil {
log.Fatalln("fail to CallMethod:", err)
}
bs, _ := ioutil.ReadAll(res.Body)
log.Printf(">> Result: %+v \n %s", res.StatusCode, bs)
}

View File

@@ -0,0 +1,83 @@
package main
import (
"encoding/json"
"io/ioutil"
"log"
"path"
"regexp"
"strings"
"testing"
"github.com/beevik/etree"
"github.com/kerberos-io/onvif"
"github.com/kerberos-io/onvif/device"
wsdiscovery "github.com/kerberos-io/onvif/ws-discovery"
)
func TestGetAvailableDevicesAtSpecificEthernetInterface(t *testing.T) {
// client()
// runDiscovery("en0")
s, _ := wsdiscovery.GetAvailableDevicesAtSpecificEthernetInterface("en0")
log.Printf("%v", s)
}
func client() {
dev, err := onvif.NewDevice(onvif.DeviceParams{Xaddr: "192.168.3.10", Username: "admin", Password: "zsyy12345"})
if err != nil {
panic(err)
}
log.Printf("output %+v", dev.GetServices())
res, _ := dev.CallMethod(device.GetUsers{})
bs, _ := ioutil.ReadAll(res.Body)
log.Printf("output %+v %s", res.StatusCode, bs)
}
// Host host
type Host struct {
URL string `json:"url"`
Name string `json:"name"`
}
func runDiscovery(interfaceName string) {
var hosts []*Host
devices, _ := wsdiscovery.SendProbe(interfaceName, nil, []string{"dn:NetworkVideoTransmitter"}, map[string]string{"dn": "http://www.onvif.org/ver10/network/wsdl"})
for _, j := range devices {
doc := etree.NewDocument()
if err := doc.ReadFromString(j); err != nil {
log.Printf("error %s", err)
} else {
endpoints := doc.Root().FindElements("./Body/ProbeMatches/ProbeMatch/XAddrs")
scopes := doc.Root().FindElements("./Body/ProbeMatches/ProbeMatch/Scopes")
flag := false
host := &Host{}
for _, xaddr := range endpoints {
xaddr := strings.Split(strings.Split(xaddr.Text(), " ")[0], "/")[2]
host.URL = xaddr
}
if flag {
break
}
for _, scope := range scopes {
re := regexp.MustCompile(`onvif:\/\/www\.onvif\.org\/name\/[A-Za-z0-9-]+`)
match := re.FindStringSubmatch(scope.Text())
host.Name = path.Base(match[0])
}
hosts = append(hosts, host)
}
}
bys, _ := json.Marshal(hosts)
log.Printf("done %s", bys)
}

View File

@@ -0,0 +1,87 @@
package main
import (
"github.com/kerberos-io/onvif"
"github.com/kerberos-io/onvif/event"
"github.com/kerberos-io/onvif/xsd"
"io/ioutil"
"log"
)
// Geovision
// Request:
// <tev:CreatePullPointSubscription>
// <tev:InitialTerminationTime>PT120S</tev:InitialTerminationTime>
// </tev:CreatePullPointSubscription>
// Response:
// <tev:CreatePullPointSubscriptionResponse>
// <tev:SubscriptionReference>
// <wsa5:Address>http://192.168.12.149:80/onvif/events</wsa5:Address>
// </tev:SubscriptionReference>
// <wsnt:CurrentTime>2021-12-02T02:02:15Z</wsnt:CurrentTime>
// <wsnt:TerminationTime>2021-12-02T02:04:15Z</wsnt:TerminationTime>
// </tev:CreatePullPointSubscriptionResponse>
//
// Test Summary:
// 1. TerminationTime = CurrentTime+InitialTerminationTime
// 2. but always return http://192.168.12.149:80/onvif/events
// 3. We can pulling the event without creating the pull point, and the unsubscribe is not supported
// BOSCH
// Request:
// <tev:CreatePullPointSubscription>
// <tev:InitialTerminationTime>PT1H</tev:InitialTerminationTime>
// </tev:CreatePullPointSubscription>
// Response:
// <tev:CreatePullPointSubscriptionResponse>
// <tev:SubscriptionReference>
// <wsa5:Address>http://192.168.12.148/Web_Service?Idx=1</wsa5:Address>
// </tev:SubscriptionReference>
// <wsnt:CurrentTime>2021-12-02T02:59:30Z</wsnt:CurrentTime>
// <wsnt:TerminationTime>2021-12-02T03:00:30Z</wsnt:TerminationTime>
// </tev:CreatePullPointSubscriptionResponse>
//
// Test Summary
// 1. The TerminationTime always increase one minute
// 2. The SubscriptionReference Address will change when create another PullPoint
// === Hikvision ===
// Request:
// <tev:CreatePullPointSubscription>
// <tev:InitialTerminationTime>PT120S</tev:InitialTerminationTime>
// </tev:CreatePullPointSubscription>
// Response:
// <tev:CreatePullPointSubscriptionResponse>
// <tev:SubscriptionReference>
// <wsa:Address>http://192.168.12.123/onvif/Events/PullSubManager_2021-12-02T06:04:46Z_0</wsa:Address>
// </tev:SubscriptionReference>
// <wsnt:CurrentTime>2021-12-02T06:04:46Z</wsnt:CurrentTime>
// <wsnt:TerminationTime>2021-12-02T06:06:46Z</wsnt:TerminationTime>
// </tev:CreatePullPointSubscriptionResponse>
//
// Test Summary:
// 1. TerminationTime = CurrentTime+InitialTerminationTime
// 2. The pull point will drop after exceeding the termination time
func main() {
dev, err := onvif.NewDevice(onvif.DeviceParams{
//Xaddr: "192.168.12.148", // BOSCH
//Xaddr: "192.168.12.149", // Geovision
Xaddr: "192.168.12.123", //Hikvision
Username: "administrator",
Password: "Password1!",
AuthMode: onvif.UsernameTokenAuth,
})
if err != nil {
log.Fatalln("fail to new device:", err)
}
initialTerminationTime := xsd.String("PT120S")
res, err := dev.CallMethod(event.CreatePullPointSubscription{InitialTerminationTime: &initialTerminationTime})
if err != nil {
log.Fatalln("fail to CallMethod:", err)
}
bs, _ := ioutil.ReadAll(res.Body)
log.Printf(">> Result: %+v \n %s", res.StatusCode, bs)
}

View File

@@ -0,0 +1,28 @@
package main
import (
"github.com/kerberos-io/onvif"
"github.com/kerberos-io/onvif/event"
"io/ioutil"
"log"
)
func main() {
dev, err := onvif.NewDevice(onvif.DeviceParams{
Xaddr: "192.168.12.148", // BOSCH
//Xaddr: "192.168.12.149", // Geovision
Username: "administrator",
Password: "Password1!",
})
if err != nil {
log.Fatalln("fail to new device:", err)
}
// CreateUsers
res, err := dev.CallMethod(event.GetEventProperties{})
if err != nil {
log.Fatalln("fail to CallMethod:", err)
}
bs, _ := ioutil.ReadAll(res.Body)
log.Printf(">> Result: %+v \n %s", res.StatusCode, bs)
}

View File

@@ -0,0 +1,92 @@
package main
import (
"encoding/xml"
"github.com/kerberos-io/onvif"
"github.com/kerberos-io/onvif/event"
"github.com/kerberos-io/onvif/xsd"
"io/ioutil"
"log"
)
// === Geovision ===
// Request:
// <tev:PullMessages>
// <tev:Timeout>PT20S</tev:Timeout>
// <tev:MessageLimit>10</tev:MessageLimit>
// </tev:PullMessages>
// Response:
// <tev:PullMessagesResponse>
// <tev:CurrentTime>2021-12-02T02:42:30Z</tev:CurrentTime>
// <tev:TerminationTime>2021-12-02T02:42:50Z</tev:TerminationTime>
// <wsnt:NotificationMessage> ... </wsnt:NotificationMessage>
// </tev:PullMessagesResponse>
//
// Test Summary:
// 1. the TerminationTime = CurrentTime+Timeout
// 2. even current time exceed the TerminationTime, the pull point still alive
// === BOSCH ===
// Request:
// <tev:PullMessages>
// <tev:Timeout>PT20S</tev:Timeout>
// <tev:MessageLimit>10</tev:MessageLimit>
// </tev:PullMessages>
// Response:
// <tev:PullMessagesResponse>
// <tev:CurrentTime>2021-12-02T03:06:39Z</tev:CurrentTime>
// <tev:TerminationTime>2021-12-02T03:07:39Z</tev:TerminationTime>
// <wsnt:NotificationMessage> ... </wsnt:NotificationMessage>
// </tev:PullMessagesResponse>
//
// Test Summary:
// the TerminationTime increase one minute
// === Hikvisiion ===
// Request:
//
// Response:
// <tev:PullMessagesResponse><tev:CurrentTime>2021-12-02T06:08:35Z</tev:CurrentTime>
//
// <tev:TerminationTime>2021-12-02T06:18:40Z</tev:TerminationTime>
// <wsnt:NotificationMessage><wsnt:Topic Dialect="http://www.onvif.org/ver10/tev/topicExpression/ConcreteSet">tns1:RuleEngine/CellMotionDetector/Motion</wsnt:Topic>
// ...
// </wsnt:NotificationMessage>
// </tev:PullMessagesResponse>
//
// Test Summary:
//
// the TerminationTime increase ten minutes
func main() {
dev, err := onvif.NewDevice(onvif.DeviceParams{
Xaddr: "192.168.12.148", // BOSCH
//Xaddr: "192.168.12.149", // Geovision
//Xaddr: "192.168.12.123", //Hikvision
Username: "administrator",
Password: "Password1!",
AuthMode: onvif.UsernameTokenAuth,
})
if err != nil {
log.Fatalln("fail to new device:", err)
}
pullMessage := event.PullMessages{
Timeout: xsd.Duration("PT5S"),
MessageLimit: 10,
}
endPoint := "http://192.168.12.148/Web_Service?Idx=0" // BOSCH
//endPoint := "http://192.168.12.149:80/onvif/events" // Geovision
//endPoint := "http://192.168.12.123/onvif/Events/PullSubManager_2021-12-02T06:07:58Z_0"
requestBody, err := xml.Marshal(pullMessage)
if err != nil {
log.Fatalln(err)
}
res, err := dev.SendSoap(endPoint, string(requestBody))
if err != nil {
log.Fatalln("fail to CallMethod:", err)
}
bs, _ := ioutil.ReadAll(res.Body)
log.Printf(">> Result: %+v \n %s", res.StatusCode, bs)
}

View File

@@ -0,0 +1,94 @@
package main
import (
"encoding/xml"
"github.com/kerberos-io/onvif"
"github.com/kerberos-io/onvif/event"
"github.com/kerberos-io/onvif/xsd"
"io/ioutil"
"log"
)
// === Geovision ===
// Request:
// <tev:PullMessages>
// <tev:Timeout>PT20S</tev:Timeout>
// <tev:MessageLimit>10</tev:MessageLimit>
// </tev:PullMessages>
// Response:
// <tev:PullMessagesResponse>
// <tev:CurrentTime>2021-12-02T02:42:30Z</tev:CurrentTime>
// <tev:TerminationTime>2021-12-02T02:42:50Z</tev:TerminationTime>
// <wsnt:NotificationMessage> ... </wsnt:NotificationMessage>
// </tev:PullMessagesResponse>
//
// Test Summary:
// 1. the TerminationTime = CurrentTime+Timeout
// 2. even current time exceed the TerminationTime, the pull point still alive
// === BOSCH ===
// Request:
// <wsnt:Renew>
// <wsnt:TerminationTime>
// 2021-12-03T15:50:03Z
// </wsnt:TerminationTime>
// </wsnt:Renew>
// Response:
// <wsnt:RenewResponse>
// <wsnt:TerminationTime>
// 2021-12-03T15:50:03Z
// </wsnt:TerminationTime>
// <wsnt:CurrentTime>
// 2021-12-02T03:36:04Z
// </wsnt:CurrentTime>
// </wsnt:RenewResponse>
//
// Test Summary:
// 1. the response's TerminationTime equal request's TerminationTime
// 2. But the subscription still live for one minute
// === Hikvision ===
// Request:
// <wsnt:Renew><wsnt:TerminationTime>2021-12-02T18:30:53Z</wsnt:TerminationTime></wsnt:Renew>
// Response:
// <wsnt:RenewResponse>
// <wsnt:TerminationTime>2021-12-02T18:30:53Z</wsnt:TerminationTime>
// <wsnt:CurrentTime>2021-12-02T06:31:57Z</wsnt:CurrentTime>
// </wsnt:RenewResponse>
//
// Test Summary:
// 1. the subscription's termination time will update if the request's TerminationTime greater than the curren time
func main() {
dev, err := onvif.NewDevice(onvif.DeviceParams{
Xaddr: "192.168.12.148", // BOSCH
//Xaddr: "192.168.12.149", // Geovision
//Xaddr: "192.168.12.123", //Hikvision
Username: "administrator",
Password: "Password1!",
AuthMode: onvif.UsernameTokenAuth,
})
if err != nil {
log.Fatalln("fail to new device:", err)
}
terminationTime := xsd.String("PT120S")
renew := event.Renew{
TerminationTime: terminationTime,
}
endPoint := "http://192.168.12.148/Web_Service?Idx=0" // BOSCH
//endPoint := "http://192.168.12.149:80/onvif/events" // Geovision
//endPoint := "http://192.168.12.123:80/onvif/Events/SubManager__0" // Hikvision
requestBody, err := xml.Marshal(renew)
if err != nil {
log.Fatalln(err)
}
res, err := dev.SendSoap(endPoint, string(requestBody))
if err != nil {
log.Fatalln("fail to CallMethod:", err)
}
bs, _ := ioutil.ReadAll(res.Body)
log.Printf(">> Result: %+v \n %s", res.StatusCode, bs)
}

View File

@@ -0,0 +1,110 @@
package main
import (
"github.com/kerberos-io/onvif"
"github.com/kerberos-io/onvif/event"
"github.com/kerberos-io/onvif/xsd"
"io/ioutil"
"log"
)
// === Geovision ===
// Request:
// <wsnt:Subscribe>
// <wsnt:TerminationTime>2021-12-02T10:10:16Z</wsnt:TerminationTime>
// </wsnt:Subscribe>
// Response:
// <SOAP-ENV:Fault>
// <SOAP-ENV:Code>
// <SOAP-ENV:Value>
// SOAP-ENV:Sender
// </SOAP-ENV:Value>
// </SOAP-ENV:Code>
// <SOAP-ENV:Reason>
// <SOAP-ENV:Text xml:lang="en">
// Validation constraint violation: invalid value in element 'wsnt:TerminationTime'
// </SOAP-ENV:Text>
// </SOAP-ENV:Reason>
// </SOAP-ENV:Fault>
//
// Test Summary:
// 1. The time pattern 2021-12-02T10:20:15Z and PT1H not work and always return error
// 2. If not provide the time, camera return the error: ' fail to CallMethod: Post "http://192.168.12.149/onvif/events": net/http: HTTP/1.x transport connection broken: unexpected EOF'
// 3. Geovision might not support the BaseNotification
// === BOSCH ===
// Request:
// <wsnt:Subscribe>
// <wsnt:ConsumerReference>
// <wsa:Address>http://192.168.12.112:8080/ping</wsa:Address>
// </wsnt:ConsumerReference>
// <wsnt:TerminationTime>
// 2021-12-01T15:50:03Z
// </wsnt:TerminationTime>
// </wsnt:Subscribe>
// Response:
// <wsnt:SubscribeResponse>
// <wsnt:SubscriptionReference>
// <wsa5:Address>http://192.168.12.148/Web_Service?Idx=1</wsa5:Address>
// </wsnt:SubscriptionReference>
// <wsnt:CurrentTime>2021-12-02T03:21:13Z</wsnt:CurrentTime>
// <wsnt:TerminationTime>2021-12-02T03:22:13Z</wsnt:TerminationTime>
// </wsnt:SubscribeResponse>
//
// Test Summary
// 1. The TerminationTime always increase one minute
// 2. The SubscriptionReference Address will change when create another PullPoint
// Hikvision
// Request:
// <wsnt:Subscribe>
// <wsnt:ConsumerReference>
// <wsa:Address>http://192.168.12.112:8080/ping</wsa:Address>
// </wsnt:ConsumerReference>
// <wsnt:TerminationTime>2021-12-03T15:50:03Z</wsnt:TerminationTime>
// </wsnt:Subscribe>
// Response:
// <wsnt:SubscribeResponse>
// <wsnt:SubscriptionReference>
// <wsa:Address>http:///onvif/Events/SubManager_2021-12-02T06:21:11Z_1</wsa:Address>
// </wsnt:SubscriptionReference>
// <wsnt:CurrentTime>2021-12-02T06:21:11Z</wsnt:CurrentTime>
// <wsnt:TerminationTime>2021-12-02T06:22:11Z</wsnt:TerminationTime>
// </wsnt:SubscribeResponse>
//
// Test Summary
// 1. Regardless of the request's TerminationTime, the response TerminationTime always increase one minute
// 2. The SubscriptionReference Address will change when create another PullPoint
// 3. The response's reference address is invalid, renew request will fail
func main() {
dev, err := onvif.NewDevice(onvif.DeviceParams{
Xaddr: "192.168.12.148", // BOSCH
//Xaddr: "192.168.12.149", // Geovision
//Xaddr: "192.168.12.123", //Hikvision
Username: "administrator",
Password: "Password1!",
AuthMode: onvif.UsernameTokenAuth,
})
if err != nil {
log.Fatalln("fail to new device:", err)
}
consumerAddress := event.AttributedURIType("http://192.168.12.112:8080/ping")
//terminationTime:= xsd.String("2021-12-03T15:50:03Z")
terminationTime := xsd.String("PT180S")
res, err := dev.CallMethod(event.Subscribe{
ConsumerReference: &event.EndpointReferenceType{
Address: consumerAddress,
},
TerminationTime: &terminationTime,
},
)
if err != nil {
log.Fatalln("fail to CallMethod:", err)
}
log.Printf(">> Status Code: %+v \n", res.StatusCode)
bs, _ := ioutil.ReadAll(res.Body)
log.Printf(">> Result: %+v \n %s", res.StatusCode, bs)
}

View File

@@ -0,0 +1,75 @@
package main
import (
"encoding/xml"
"github.com/kerberos-io/onvif"
"github.com/kerberos-io/onvif/event"
"io/ioutil"
"log"
)
// === Geovision ===
// Request:
// <tev:Unsubscribe />
// Response:
// <SOAP-ENV:Fault>
// <SOAP-ENV:Code>
// <SOAP-ENV:Value>SOAP-ENV:Sender</SOAP-ENV:Value>
// </SOAP-ENV:Code>
// <SOAP-ENV:Reason>
// <SOAP-ENV:Text xml:lang="en">
// Method 'tev:Unsubscribe' not implemented: method name or namespace not recognized
// </SOAP-ENV:Text>
// </SOAP-ENV:Reason>
// </SOAP-ENV:Fault>
//
// Test Summary: Geovision might not support unsubscribe
// === BOSCH ===
// Request:
// <tev:Unsubscribe />
// Response:
// <SOAP-ENV:Fault>
// <SOAP-ENV:Code><SOAP-ENV:Value>SOAP-ENV:Receiver</SOAP-ENV:Value><SOAP-ENV:Subcode><SOAP-ENV:Value>ter:Action</SOAP-ENV:Value></SOAP-ENV:Subcode></SOAP-ENV:Code>
// <SOAP-ENV:Reason><SOAP-ENV:Text xml:lang="en">Action Failed</SOAP-ENV:Text></SOAP-ENV:Reason>
// <SOAP-ENV:Node>http://www.w3.org/2003/05/soap-envelope/node/ultimateReceiver</SOAP-ENV:Node><SOAP-ENV:Role>http://www.w3.org/2003/05/soap-envelope/node/ultimateReceiver</SOAP-ENV:Role>
// </SOAP-ENV:Fault>
//
// Test Summary: BOSCH might not support unsubscribe
// === Hikvision
// Request:
// <tev:Unsubscribe />
// Response:
// <wsnt:UnsubscribeResponse/>
func main() {
dev, err := onvif.NewDevice(onvif.DeviceParams{
//Xaddr: "192.168.12.148", // BOSCH
//Xaddr: "192.168.12.149", // Geovision
Xaddr: "192.168.12.123", //Hikvision
Username: "administrator",
Password: "Password1!",
AuthMode: onvif.UsernameTokenAuth,
})
if err != nil {
log.Fatalln("fail to new device:", err)
}
unsubscribe := event.Unsubscribe{}
//endPoint:= "http://192.168.12.148/Web_Service?Idx=0" // BOSCH
//endPoint := "http://192.168.12.149:80/onvif/events" // Geovision
endPoint := "http://192.168.12.123/onvif/Events/PullSubManager_2021-12-02T06:13:45Z_0" // Hikvision
requestBody, err := xml.Marshal(unsubscribe)
if err != nil {
log.Fatalln(err)
}
res, err := dev.SendSoap(endPoint, string(requestBody))
if err != nil {
log.Fatalln("fail to CallMethod:", err)
}
bs, _ := ioutil.ReadAll(res.Body)
log.Printf(">> Result: %+v \n %s", res.StatusCode, bs)
}

27
examples/getusers/main.go Normal file
View File

@@ -0,0 +1,27 @@
package main
import (
"github.com/kerberos-io/onvif"
"github.com/kerberos-io/onvif/device"
"io/ioutil"
"log"
)
func main() {
dev, err := onvif.NewDevice(onvif.DeviceParams{
Xaddr: "192.168.12.149",
Username: "administrator",
Password: "Password1!",
})
if err != nil {
log.Fatalln("fail to new device:", err)
}
// CreateUsers
res, err := dev.CallMethod(device.GetUsers{})
if err != nil {
log.Fatalln("fail to CallMethod:", err)
}
bs, _ := ioutil.ReadAll(res.Body)
log.Printf(">> Result: %+v \n %s", res.StatusCode, bs)
}

36
functionmap.go Normal file
View File

@@ -0,0 +1,36 @@
package onvif
import (
"fmt"
)
func FunctionByServiceAndFunctionName(serviceName, functionName string) (Function, error) {
var functionMap map[string]Function
switch serviceName {
case DeviceWebService:
functionMap = DeviceFunctionMap
case MediaWebService:
functionMap = MediaFunctionMap
case Media2WebService:
functionMap = Media2FunctionMap
case PTZWebService:
functionMap = PTZFunctionMap
case EventWebService:
functionMap = EventFunctionMap
case AnalyticsWebService:
functionMap = AnalyticsFunctionMap
case ImagingWebService:
functionMap = ImagingFunctionMap
case RecordingWebService:
functionMap = RecordingFunctionMap
default:
return nil, fmt.Errorf("the web service '%s' is not supported", serviceName)
}
if function, found := functionMap[functionName]; !found {
return nil, fmt.Errorf("the web service '%s' does not support the function '%s'", serviceName, functionName)
} else {
return function, nil
}
}

45
go.mod
View File

@@ -1,12 +1,43 @@
module github.com/use-go/onvif
module github.com/kerberos-io/onvif
go 1.14
go 1.20
require (
github.com/beevik/etree v1.1.0
github.com/beevik/etree v1.2.0
github.com/clbanning/mxj/v2 v2.7.0
github.com/elgs/gostrgen v0.0.0-20161222160715-9d61ae07eeae
github.com/gin-gonic/gin v1.6.2
github.com/gofrs/uuid v3.2.0+incompatible
github.com/yakovlevdmv/Golang-iso8601-duration v0.0.0-20180403125811-e5db0413b903
golang.org/x/net v0.0.0-20200425230154-ff2c4b7c35a0
github.com/gin-gonic/gin v1.9.1
github.com/google/uuid v1.4.0
github.com/icholy/digest v0.1.23
github.com/juju/errors v1.0.0
github.com/stretchr/testify v1.8.4
golang.org/x/net v0.19.0
)
require (
github.com/bytedance/sonic v1.9.1 // indirect
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/gabriel-vasile/mimetype v1.4.2 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.14.0 // indirect
github.com/goccy/go-json v0.10.2 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.2.4 // indirect
github.com/leodido/go-urn v1.2.4 // indirect
github.com/mattn/go-isatty v0.0.19 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.0.8 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.11 // indirect
golang.org/x/arch v0.3.0 // indirect
golang.org/x/crypto v0.16.0 // indirect
golang.org/x/sys v0.15.0 // indirect
golang.org/x/text v0.14.0 // indirect
google.golang.org/protobuf v1.30.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

133
go.sum
View File

@@ -1,61 +1,100 @@
github.com/beevik/etree v1.1.0 h1:T0xke/WvNtMoCqgzPhkX2r4rjY3GDZFi+FjpRZY2Jbs=
github.com/beevik/etree v1.1.0/go.mod h1:r8Aw8JqVegEf0w2fDnATrX9VpkMcyFeM0FhwO62wh+A=
github.com/beevik/etree v1.2.0 h1:l7WETslUG/T+xOPs47dtd6jov2Ii/8/OjCldk5fYfQw=
github.com/beevik/etree v1.2.0/go.mod h1:aiPf89g/1k3AShMVAzriilpcE4R/Vuor90y83zVZWFc=
github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM=
github.com/bytedance/sonic v1.9.1 h1:6iJ6NqdoxCDr6mbY8h18oSO+cShGSMRGCEo7F2h0x8s=
github.com/bytedance/sonic v1.9.1/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U=
github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY=
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 h1:qSGYFH7+jGhDF8vLC+iwCD4WpbV1EBDSzWkJODFLams=
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk=
github.com/clbanning/mxj/v2 v2.7.0 h1:WA/La7UGCanFe5NpHF0Q3DNtnCsVoxbPKuyBNHWRyME=
github.com/clbanning/mxj/v2 v2.7.0/go.mod h1:hNiWqW14h+kc+MdF9C6/YoRfjEJoR3ou6tn/Qo+ve2s=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/elgs/gostrgen v0.0.0-20161222160715-9d61ae07eeae h1:3KvK2DmA7TxQ6PZ2f0rWbdqjgJhRcqgbY70bBeE4clI=
github.com/elgs/gostrgen v0.0.0-20161222160715-9d61ae07eeae/go.mod h1:wruC5r2gHdr/JIUs5Rr1V45YtsAzKXZxAnn/5rPC97g=
github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU=
github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA=
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
github.com/gin-gonic/gin v1.6.2 h1:88crIK23zO6TqlQBt+f9FrPJNKm9ZEr7qjp9vl/d5TM=
github.com/gin-gonic/gin v1.6.2/go.mod h1:75u5sXoLsGZoRN5Sgbi1eraJ4GU3++wFwWzhwvtwp4M=
github.com/go-playground/assert/v2 v2.0.1 h1:MsBgLAaY856+nPRTKrp3/OZK38U/wa0CcBYNjji3q3A=
github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.13.0 h1:HyWk6mgj5qFqCT5fjGBuRArbVDfE4hi8+e8ceBS/t7Q=
github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8=
github.com/go-playground/universal-translator v0.17.0 h1:icxd5fm+REJzpZx7ZfpaD876Lmtgy7VtROAbHHXk8no=
github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA=
github.com/go-playground/validator/v10 v10.2.0 h1:KgJ0snyC2R9VXYN2rneOtQcw5aHQB1Vv0sFl1UcHBOY=
github.com/go-playground/validator/v10 v10.2.0/go.mod h1:uOYAAleCW8F/7oMFd6aG0GOhaH6EGOAJShg8Id5JGkI=
github.com/gofrs/uuid v3.2.0+incompatible h1:y12jRkkFxsd7GpqdSZ+/KCs/fJbqpEXSGd4+jfEaewE=
github.com/gofrs/uuid v3.2.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM=
github.com/golang/protobuf v1.3.3 h1:gyjaxf+svBWX08ZjK86iN9geUJF0H6gp2IRKX6Nf6/I=
github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw=
github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg=
github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU=
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.14.0 h1:vgvQWe3XCz3gIeFDm/HnTIbj6UGmg/+t63MyGU2n5js=
github.com/go-playground/validator/v10 v10.14.0/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU=
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/json-iterator/go v1.1.9 h1:9yzud/Ht36ygwatGx56VwCZtlI/2AD15T1X2sjSuGns=
github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
github.com/leodido/go-urn v1.2.0 h1:hpXL4XnriNwQ/ABnpepYM/1vCLWNDfUNts8dX3xTG6Y=
github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII=
github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY=
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc=
github.com/google/uuid v1.4.0 h1:MtMxsa51/r9yyhkyLsVeVt0B+BGQZzpQiTQ4eHZ8bc4=
github.com/google/uuid v1.4.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/icholy/digest v0.1.23 h1:4hX2pIloP0aDx7RJW0JewhPPy3R8kU+vWKdxPsCCGtY=
github.com/icholy/digest v0.1.23/go.mod h1:QNrsSGQ5v7v9cReDI0+eyjsXGUoRSUZQHeQ5C4XLa0Y=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/juju/errors v1.0.0 h1:yiq7kjCLll1BiaRuNY53MGI0+EQ3rF6GB+wvboZDefM=
github.com/juju/errors v1.0.0/go.mod h1:B5x9thDqx0wIMH3+aLIMP9HjItInYWObRovoCFM5Qe8=
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/klauspost/cpuid/v2 v2.2.4 h1:acbojRNwl3o09bUq+yDCtZFc1aiwaAAxtcn8YkZXnvk=
github.com/klauspost/cpuid/v2 v2.2.4/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY=
github.com/kr/pretty v0.2.1 h1:Fmg33tUaq4/8ym9TJN1x7sLJnHVwhP33CNkpYV/7rwI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q=
github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4=
github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA=
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 h1:Esafd1046DLDQ0W1YjYsBW+p8U2u7vzgW2SQVmlNazg=
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/pelletier/go-toml/v2 v2.0.8 h1:0ctb6s9mE31h0/lhu+J6OPmVeDxJn+kYnJc2jZR9tGQ=
github.com/pelletier/go-toml/v2 v2.0.8/go.mod h1:vuYfssBdrU2XDZ9bYydBu6t+6a6PYNcZljzZR9VXg+4=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/ugorji/go v1.1.7 h1:/68gy2h+1mWMrwZFeD1kQialdSzAb432dtpeJ42ovdo=
github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw=
github.com/ugorji/go/codec v1.1.7 h1:2SvQaVZ1ouYrrKKwoSk2pzd4A9evlKJb9oTL+OaLUSs=
github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY=
github.com/yakovlevdmv/Golang-iso8601-duration v0.0.0-20180403125811-e5db0413b903 h1:W1Y09qPuFslSd+3famnSJpy4c3My7Gp1cgk5x4ZlbfU=
github.com/yakovlevdmv/Golang-iso8601-duration v0.0.0-20180403125811-e5db0413b903/go.mod h1:9o96byDMk+osDZqiIS2a7E7y0cWmg4rRTjQRWVHpFWE=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/net v0.0.0-20200425230154-ff2c4b7c35a0 h1:Jcxah/M+oLZ/R4/z5RzfPzGbPXnVDPkEDtf2JnuxN+U=
golang.org/x/net v0.0.0-20200425230154-ff2c4b7c35a0/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd h1:xhmwyvizuTgC2qz7ZlMluP20uW+C3Rm0FD/WLDX8884=
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
github.com/ugorji/go/codec v1.2.11 h1:BMaWp1Bb6fHwEtbplGBGJ498wD+LKlNSl25MjdZY4dU=
github.com/ugorji/go/codec v1.2.11/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
golang.org/x/arch v0.3.0 h1:02VY4/ZcO/gBOH6PUaoiptASxtXU10jazRCP865E97k=
golang.org/x/arch v0.3.0/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
golang.org/x/crypto v0.16.0 h1:mMMrFzRSCF0GvB7Ne27XVtVAaXLrPmgPC7/v0tkwHaY=
golang.org/x/crypto v0.16.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4=
golang.org/x/net v0.19.0 h1:zTwKpTd2XuCqf8huc7Fo2iSy+4RHPd10s4KzeTnVr1c=
golang.org/x/net v0.19.0/go.mod h1:CfAk/cbD4CthTvqiEl8NpboMuiuOYsAr/7NOjZJtv1U=
golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc=
golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.30.0 h1:kPPoIgf3TsEvrm0PFe15JQ+570QVxYzEvvHqChK+cng=
google.golang.org/protobuf v1.30.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gotest.tools/v3 v3.5.1 h1:EENdUnS3pdur5nybKYIh2Vfgc8IUNBjxDPSjtiJcOzU=
rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=

121
gosoap/envelope.go Normal file
View File

@@ -0,0 +1,121 @@
package gosoap
import (
"encoding/xml"
"fmt"
)
type SOAPEnvelope struct {
XMLName xml.Name `xml:"http://www.w3.org/2003/05/soap-envelope Envelope"`
Header SOAPHeader
Body SOAPBody
}
type SOAPHeader struct {
XMLName xml.Name `xml:"http://www.w3.org/2003/05/soap-envelope Header"`
Headers []interface{}
}
type SOAPBody struct {
XMLName xml.Name `xml:"http://www.w3.org/2003/05/soap-envelope Body"`
Fault *SOAPFault `xml:",omitempty"`
Content interface{} `xml:",omitempty"`
}
type SOAPFault struct {
XMLName xml.Name `xml:"http://www.w3.org/2003/05/soap-envelope Fault"`
Code SOAPFaultCode `xml:",omitempty"`
Reason SOAPFaultReason `xml:",omitempty"`
Detail SOAPFaultDetail `xml:",omitempty"`
}
// UnmarshalXML the response body
// https://github.com/faceterteam/onvif4go/blob/master/soap/types.go#L46
// https://play.golang.org/p/FRzdAFrXZ1
func (b *SOAPBody) UnmarshalXML(d *xml.Decoder, _ xml.StartElement) error {
if b.Content == nil {
return xml.UnmarshalError("Content must be a pointer to a struct")
}
var (
token xml.Token
err error
consumed bool
)
Loop:
for {
if token, err = d.Token(); err != nil {
return err
}
if token == nil {
break
}
switch se := token.(type) {
case xml.StartElement:
if consumed {
return xml.UnmarshalError("Found multiple elements inside SOAP body; not wrapped-document/literal WS-I compliant")
} else if se.Name.Space == "http://www.w3.org/2003/05/soap-envelope" && se.Name.Local == "Fault" {
b.Fault = &SOAPFault{}
b.Content = nil
err = d.DecodeElement(b.Fault, &se)
if err != nil {
return err
}
consumed = true
} else {
if err = d.DecodeElement(b.Content, &se); err != nil {
return err
}
consumed = true
}
case xml.EndElement:
break Loop
}
}
return nil
}
type SOAPFaultCode struct {
Value string `xml:"Value"`
Subcode SOAPFaultSubCode `xml:"Subcode,omitempty"`
}
type SOAPFaultSubCode struct {
Value string `xml:"Value"`
Subcode *SOAPFaultSubCode `xml:"Subcode,omitempty"`
}
type SOAPFaultReason struct {
Text string `xml:"Text"`
}
type SOAPFaultDetail struct {
Text string `xml:"Text"`
}
func (fault *SOAPFault) String() string {
msg := fmt.Sprintf("fault reason: %s, fault detail: %s, fault code: %v %v ",
fault.Reason.Text, fault.Detail.Text, fault.Code.Value, fault.Code.Subcode.Value)
if fault.Code.Subcode.Subcode != nil {
msg += fault.Code.Subcode.Subcode.Value
}
return msg
}
func NewSOAPEnvelope(content interface{}) *SOAPEnvelope {
return &SOAPEnvelope{
Body: SOAPBody{
Content: content,
},
}
}

View File

@@ -81,7 +81,9 @@ func (msg *SoapMessage) AddStringBodyContent(data string) {
}
//doc.FindElement("./Envelope/Body").AddChild(element)
bodyTag := doc.Root().SelectElement("Body")
bodyTag.AddChild(element)
if element != nil {
bodyTag.AddChild(element)
}
//doc.IndentTabs()
res, _ := doc.WriteToString()

View File

@@ -36,7 +36,7 @@ func NewAction(key, value string) Action {
/** Generating Nonce sequence **/
auth := Action{
// Created: time.Now().UTC().Format(time.RFC3339Nano),
// Created: time.Now().UTC().Format(time.RFC3339Nano),
}
return auth

View File

@@ -9,15 +9,19 @@ import (
"github.com/elgs/gostrgen"
)
/*************************
/*
************************
WS-Security types
*************************/
************************
*/
const (
passwordType = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest"
encodingType = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary"
)
//Security type :XMLName xml.Name `xml:"http://purl.org/rss/1.0/modules/content/ encoded"`
// Security type :XMLName xml.Name `xml:"http://purl.org/rss/1.0/modules/content/ encoded"`
type Security struct {
//XMLName xml.Name `xml:"wsse:Security"`
XMLName xml.Name `xml:"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd Security"`
@@ -55,39 +59,38 @@ type wsAuth struct {
</Security>
*/
//NewSecurity get a new security
// NewSecurity get a new security
func NewSecurity(username, passwd string) Security {
/** Generating Nonce sequence **/
charsToGenerate := 32
charSet := gostrgen.Lower | gostrgen.Digit
nonceSeq, _ := gostrgen.RandGen(charsToGenerate, charSet, "", "")
created := time.Now().UTC().Format(time.RFC3339Nano)
auth := Security{
Auth: wsAuth{
Username: username,
Password: password{
Type: passwordType,
Password: generateToken(username, nonceSeq, time.Now().UTC(), passwd),
Password: generateToken(username, nonceSeq, created, passwd),
},
Nonce: nonce{
Type: encodingType,
Nonce: nonceSeq,
},
Created: time.Now().UTC().Format(time.RFC3339Nano),
Created: created,
},
}
return auth
}
//Digest = B64ENCODE( SHA1( B64DECODE( Nonce ) + Date + Password ) )
func generateToken(Username string, Nonce string, Created time.Time, Password string) string {
// Digest = B64ENCODE( SHA1( B64DECODE( Nonce ) + Date + Password ) )
func generateToken(Username string, Nonce string, Created string, Password string) string {
sDec, _ := base64.StdEncoding.DecodeString(Nonce)
hasher := sha1.New()
//hasher.Write([]byte((base64.StdEncoding.EncodeToString([]byte(Nonce)) + Created.Format(time.RFC3339) + Password)))
hasher.Write([]byte(string(sDec) + Created.Format(time.RFC3339Nano) + Password))
hasher.Write([]byte(string(sDec) + Created + Password))
return base64.StdEncoding.EncodeToString(hasher.Sum(nil))
}

108
imaging/function.go Normal file
View File

@@ -0,0 +1,108 @@
// -*- Mode: Go; indent-tabs-mode: t -*-
//
// Copyright (C) 2022 Intel Corporation
//
// SPDX-License-Identifier: Apache-2.0
// Code generated by gen_commands.py DO NOT EDIT.
package imaging
type GetCurrentPresetFunction struct{}
func (_ *GetCurrentPresetFunction) Request() interface{} {
return &GetCurrentPreset{}
}
func (_ *GetCurrentPresetFunction) Response() interface{} {
return &GetCurrentPresetResponse{}
}
type GetImagingSettingsFunction struct{}
func (_ *GetImagingSettingsFunction) Request() interface{} {
return &GetImagingSettings{}
}
func (_ *GetImagingSettingsFunction) Response() interface{} {
return &GetImagingSettingsResponse{}
}
type GetMoveOptionsFunction struct{}
func (_ *GetMoveOptionsFunction) Request() interface{} {
return &GetMoveOptions{}
}
func (_ *GetMoveOptionsFunction) Response() interface{} {
return &GetMoveOptionsResponse{}
}
type GetOptionsFunction struct{}
func (_ *GetOptionsFunction) Request() interface{} {
return &GetOptions{}
}
func (_ *GetOptionsFunction) Response() interface{} {
return &GetOptionsResponse{}
}
type GetPresetsFunction struct{}
func (_ *GetPresetsFunction) Request() interface{} {
return &GetPresets{}
}
func (_ *GetPresetsFunction) Response() interface{} {
return &GetPresetsResponse{}
}
type GetServiceCapabilitiesFunction struct{}
func (_ *GetServiceCapabilitiesFunction) Request() interface{} {
return &GetServiceCapabilities{}
}
func (_ *GetServiceCapabilitiesFunction) Response() interface{} {
return &GetServiceCapabilitiesResponse{}
}
type GetStatusFunction struct{}
func (_ *GetStatusFunction) Request() interface{} {
return &GetStatus{}
}
func (_ *GetStatusFunction) Response() interface{} {
return &GetStatusResponse{}
}
type MoveFunction struct{}
func (_ *MoveFunction) Request() interface{} {
return &Move{}
}
func (_ *MoveFunction) Response() interface{} {
return &MoveResponse{}
}
type SetCurrentPresetFunction struct{}
func (_ *SetCurrentPresetFunction) Request() interface{} {
return &SetCurrentPreset{}
}
func (_ *SetCurrentPresetFunction) Response() interface{} {
return &SetCurrentPresetResponse{}
}
type SetImagingSettingsFunction struct{}
func (_ *SetImagingSettingsFunction) Request() interface{} {
return &SetImagingSettings{}
}
func (_ *SetImagingSettingsFunction) Response() interface{} {
return &SetImagingSettingsResponse{}
}
type StopFunction struct{}
func (_ *StopFunction) Request() interface{} {
return &Stop{}
}
func (_ *StopFunction) Response() interface{} {
return &StopResponse{}
}

View File

@@ -1,19 +1,29 @@
package imaging
//go:generate python3 ../python/gen_commands.py
import (
"github.com/use-go/onvif/xsd"
"github.com/use-go/onvif/xsd/onvif"
"github.com/kerberos-io/onvif/xsd"
"github.com/kerberos-io/onvif/xsd/onvif"
)
type GetServiceCapabilities struct {
XMLName string `xml:"timg:GetServiceCapabilities"`
}
// todo: fill in response type
type GetServiceCapabilitiesResponse struct {
}
type GetImagingSettings struct {
XMLName string `xml:"timg:GetImagingSettings"`
VideoSourceToken onvif.ReferenceToken `xml:"timg:VideoSourceToken"`
}
type GetImagingSettingsResponse struct {
ImagingSettings onvif.ImagingSettings20 `xml:"timg:ImagingSettings"`
}
type SetImagingSettings struct {
XMLName string `xml:"timg:SetImagingSettings"`
VideoSourceToken onvif.ReferenceToken `xml:"timg:VideoSourceToken"`
@@ -21,44 +31,78 @@ type SetImagingSettings struct {
ForcePersistence xsd.Boolean `xml:"timg:ForcePersistence"`
}
type SetImagingSettingsResponse struct {
}
type GetOptions struct {
XMLName string `xml:"timg:GetOptions"`
VideoSourceToken onvif.ReferenceToken `xml:"timg:VideoSourceToken"`
}
// todo: fill in response type
type GetOptionsResponse struct {
}
type Move struct {
XMLName string `xml:"timg:Move"`
VideoSourceToken onvif.ReferenceToken `xml:"timg:VideoSourceToken"`
Focus onvif.FocusMove `xml:"timg:Focus"`
}
// todo: fill in response type
type MoveResponse struct {
}
type GetMoveOptions struct {
XMLName string `xml:"timg:GetMoveOptions"`
VideoSourceToken onvif.ReferenceToken `xml:"timg:VideoSourceToken"`
}
// todo: fill in response type
type GetMoveOptionsResponse struct {
}
type Stop struct {
XMLName string `xml:"timg:Stop"`
VideoSourceToken onvif.ReferenceToken `xml:"timg:VideoSourceToken"`
}
// todo: fill in response type
type StopResponse struct {
}
type GetStatus struct {
XMLName string `xml:"timg:GetStatus"`
VideoSourceToken onvif.ReferenceToken `xml:"timg:VideoSourceToken"`
}
// todo: fill in response type
type GetStatusResponse struct {
}
type GetPresets struct {
XMLName string `xml:"timg:GetPresets"`
VideoSourceToken onvif.ReferenceToken `xml:"timg:VideoSourceToken"`
}
// todo: fill in response type
type GetPresetsResponse struct {
}
type GetCurrentPreset struct {
XMLName string `xml:"timg:GetCurrentPreset"`
VideoSourceToken onvif.ReferenceToken `xml:"timg:VideoSourceToken"`
}
// todo: fill in response type
type GetCurrentPresetResponse struct {
}
type SetCurrentPreset struct {
XMLName string `xml:"timg:SetCurrentPreset"`
VideoSourceToken onvif.ReferenceToken `xml:"timg:VideoSourceToken"`
PresetToken onvif.ReferenceToken `xml:"timg:PresetToken"`
}
type SetCurrentPresetResponse struct {
}

6
interfaces.go Normal file
View File

@@ -0,0 +1,6 @@
package onvif
type Function interface {
Request() interface{}
Response() interface{}
}

300
mappings.go Normal file
View File

@@ -0,0 +1,300 @@
// -*- Mode: Go; indent-tabs-mode: t -*-
//
// Copyright (C) 2022 Intel Corporation
//
// SPDX-License-Identifier: Apache-2.0
// Code generated by gen_commands.py DO NOT EDIT.
package onvif
import (
"github.com/kerberos-io/onvif/analytics"
"github.com/kerberos-io/onvif/device"
"github.com/kerberos-io/onvif/event"
"github.com/kerberos-io/onvif/imaging"
"github.com/kerberos-io/onvif/media"
"github.com/kerberos-io/onvif/media2"
"github.com/kerberos-io/onvif/ptz"
"github.com/kerberos-io/onvif/recording"
)
var AnalyticsFunctionMap = map[string]Function{
CreateAnalyticsModules: &analytics.CreateAnalyticsModulesFunction{},
CreateRules: &analytics.CreateRulesFunction{},
DeleteAnalyticsModules: &analytics.DeleteAnalyticsModulesFunction{},
DeleteRules: &analytics.DeleteRulesFunction{},
GetAnalyticsModuleOptions: &analytics.GetAnalyticsModuleOptionsFunction{},
GetAnalyticsModules: &analytics.GetAnalyticsModulesFunction{},
GetRuleOptions: &analytics.GetRuleOptionsFunction{},
GetRules: &analytics.GetRulesFunction{},
GetSupportedAnalyticsModules: &analytics.GetSupportedAnalyticsModulesFunction{},
GetSupportedRules: &analytics.GetSupportedRulesFunction{},
ModifyAnalyticsModules: &analytics.ModifyAnalyticsModulesFunction{},
ModifyRules: &analytics.ModifyRulesFunction{},
}
var DeviceFunctionMap = map[string]Function{
AddIPAddressFilter: &device.AddIPAddressFilterFunction{},
AddScopes: &device.AddScopesFunction{},
CreateCertificate: &device.CreateCertificateFunction{},
CreateDot1XConfiguration: &device.CreateDot1XConfigurationFunction{},
CreateStorageConfiguration: &device.CreateStorageConfigurationFunction{},
CreateUsers: &device.CreateUsersFunction{},
DeleteCertificates: &device.DeleteCertificatesFunction{},
DeleteDot1XConfiguration: &device.DeleteDot1XConfigurationFunction{},
DeleteGeoLocation: &device.DeleteGeoLocationFunction{},
DeleteStorageConfiguration: &device.DeleteStorageConfigurationFunction{},
DeleteUsers: &device.DeleteUsersFunction{},
GetAccessPolicy: &device.GetAccessPolicyFunction{},
GetCACertificates: &device.GetCACertificatesFunction{},
GetCapabilities: &device.GetCapabilitiesFunction{},
GetCertificateInformation: &device.GetCertificateInformationFunction{},
GetCertificates: &device.GetCertificatesFunction{},
GetCertificatesStatus: &device.GetCertificatesStatusFunction{},
GetClientCertificateMode: &device.GetClientCertificateModeFunction{},
GetDNS: &device.GetDNSFunction{},
GetDPAddresses: &device.GetDPAddressesFunction{},
GetDeviceInformation: &device.GetDeviceInformationFunction{},
GetDiscoveryMode: &device.GetDiscoveryModeFunction{},
GetDot11Capabilities: &device.GetDot11CapabilitiesFunction{},
GetDot11Status: &device.GetDot11StatusFunction{},
GetDot1XConfiguration: &device.GetDot1XConfigurationFunction{},
GetDot1XConfigurations: &device.GetDot1XConfigurationsFunction{},
GetDynamicDNS: &device.GetDynamicDNSFunction{},
GetEndpointReference: &device.GetEndpointReferenceFunction{},
GetGeoLocation: &device.GetGeoLocationFunction{},
GetHostname: &device.GetHostnameFunction{},
GetIPAddressFilter: &device.GetIPAddressFilterFunction{},
GetNTP: &device.GetNTPFunction{},
GetNetworkDefaultGateway: &device.GetNetworkDefaultGatewayFunction{},
GetNetworkInterfaces: &device.GetNetworkInterfacesFunction{},
GetNetworkProtocols: &device.GetNetworkProtocolsFunction{},
GetPkcs10Request: &device.GetPkcs10RequestFunction{},
GetRelayOutputs: &device.GetRelayOutputsFunction{},
GetDigitalInputs: &device.GetDigitalInputsFunction{},
GetRemoteDiscoveryMode: &device.GetRemoteDiscoveryModeFunction{},
GetRemoteUser: &device.GetRemoteUserFunction{},
GetScopes: &device.GetScopesFunction{},
GetServiceCapabilities: &device.GetServiceCapabilitiesFunction{},
GetServices: &device.GetServicesFunction{},
GetStorageConfiguration: &device.GetStorageConfigurationFunction{},
GetStorageConfigurations: &device.GetStorageConfigurationsFunction{},
GetSystemBackup: &device.GetSystemBackupFunction{},
GetSystemDateAndTime: &device.GetSystemDateAndTimeFunction{},
GetSystemLog: &device.GetSystemLogFunction{},
GetSystemSupportInformation: &device.GetSystemSupportInformationFunction{},
GetSystemUris: &device.GetSystemUrisFunction{},
GetUsers: &device.GetUsersFunction{},
GetWsdlUrl: &device.GetWsdlUrlFunction{},
GetZeroConfiguration: &device.GetZeroConfigurationFunction{},
LoadCACertificates: &device.LoadCACertificatesFunction{},
LoadCertificateWithPrivateKey: &device.LoadCertificateWithPrivateKeyFunction{},
LoadCertificates: &device.LoadCertificatesFunction{},
RemoveIPAddressFilter: &device.RemoveIPAddressFilterFunction{},
RemoveScopes: &device.RemoveScopesFunction{},
RestoreSystem: &device.RestoreSystemFunction{},
ScanAvailableDot11Networks: &device.ScanAvailableDot11NetworksFunction{},
SendAuxiliaryCommand: &device.SendAuxiliaryCommandFunction{},
SetAccessPolicy: &device.SetAccessPolicyFunction{},
SetCertificatesStatus: &device.SetCertificatesStatusFunction{},
SetClientCertificateMode: &device.SetClientCertificateModeFunction{},
SetDNS: &device.SetDNSFunction{},
SetDPAddresses: &device.SetDPAddressesFunction{},
SetDiscoveryMode: &device.SetDiscoveryModeFunction{},
SetDot1XConfiguration: &device.SetDot1XConfigurationFunction{},
SetDynamicDNS: &device.SetDynamicDNSFunction{},
SetGeoLocation: &device.SetGeoLocationFunction{},
SetHostname: &device.SetHostnameFunction{},
SetHostnameFromDHCP: &device.SetHostnameFromDHCPFunction{},
SetIPAddressFilter: &device.SetIPAddressFilterFunction{},
SetNTP: &device.SetNTPFunction{},
SetNetworkDefaultGateway: &device.SetNetworkDefaultGatewayFunction{},
SetNetworkInterfaces: &device.SetNetworkInterfacesFunction{},
SetNetworkProtocols: &device.SetNetworkProtocolsFunction{},
SetRelayOutputSettings: &device.SetRelayOutputSettingsFunction{},
SetRelayOutputState: &device.SetRelayOutputStateFunction{},
SetRemoteDiscoveryMode: &device.SetRemoteDiscoveryModeFunction{},
SetRemoteUser: &device.SetRemoteUserFunction{},
SetScopes: &device.SetScopesFunction{},
SetStorageConfiguration: &device.SetStorageConfigurationFunction{},
SetSystemDateAndTime: &device.SetSystemDateAndTimeFunction{},
SetSystemFactoryDefault: &device.SetSystemFactoryDefaultFunction{},
SetUser: &device.SetUserFunction{},
SetZeroConfiguration: &device.SetZeroConfigurationFunction{},
StartFirmwareUpgrade: &device.StartFirmwareUpgradeFunction{},
StartSystemRestore: &device.StartSystemRestoreFunction{},
SystemReboot: &device.SystemRebootFunction{},
UpgradeSystemFirmware: &device.UpgradeSystemFirmwareFunction{},
}
var EventFunctionMap = map[string]Function{
CreatePullPointSubscription: &event.CreatePullPointSubscriptionFunction{},
GetEventProperties: &event.GetEventPropertiesFunction{},
GetServiceCapabilities: &event.GetServiceCapabilitiesFunction{},
PullMessages: &event.PullMessagesFunction{},
Renew: &event.RenewFunction{},
Seek: &event.SeekFunction{},
SetSynchronizationPoint: &event.SetSynchronizationPointFunction{},
Subscribe: &event.SubscribeFunction{},
SubscriptionReference: &event.SubscriptionReferenceFunction{},
Unsubscribe: &event.UnsubscribeFunction{},
}
var ImagingFunctionMap = map[string]Function{
GetCurrentPreset: &imaging.GetCurrentPresetFunction{},
GetImagingSettings: &imaging.GetImagingSettingsFunction{},
GetMoveOptions: &imaging.GetMoveOptionsFunction{},
GetOptions: &imaging.GetOptionsFunction{},
GetPresets: &imaging.GetPresetsFunction{},
GetServiceCapabilities: &imaging.GetServiceCapabilitiesFunction{},
GetStatus: &imaging.GetStatusFunction{},
Move: &imaging.MoveFunction{},
SetCurrentPreset: &imaging.SetCurrentPresetFunction{},
SetImagingSettings: &imaging.SetImagingSettingsFunction{},
Stop: &imaging.StopFunction{},
}
var MediaFunctionMap = map[string]Function{
AddAudioDecoderConfiguration: &media.AddAudioDecoderConfigurationFunction{},
AddAudioEncoderConfiguration: &media.AddAudioEncoderConfigurationFunction{},
AddAudioOutputConfiguration: &media.AddAudioOutputConfigurationFunction{},
AddAudioSourceConfiguration: &media.AddAudioSourceConfigurationFunction{},
AddMetadataConfiguration: &media.AddMetadataConfigurationFunction{},
AddPTZConfiguration: &media.AddPTZConfigurationFunction{},
AddVideoAnalyticsConfiguration: &media.AddVideoAnalyticsConfigurationFunction{},
AddVideoEncoderConfiguration: &media.AddVideoEncoderConfigurationFunction{},
AddVideoSourceConfiguration: &media.AddVideoSourceConfigurationFunction{},
CreateOSD: &media.CreateOSDFunction{},
CreateProfile: &media.CreateProfileFunction{},
DeleteOSD: &media.DeleteOSDFunction{},
DeleteProfile: &media.DeleteProfileFunction{},
GetAudioDecoderConfiguration: &media.GetAudioDecoderConfigurationFunction{},
GetAudioDecoderConfigurationOptions: &media.GetAudioDecoderConfigurationOptionsFunction{},
GetAudioDecoderConfigurations: &media.GetAudioDecoderConfigurationsFunction{},
GetAudioEncoderConfiguration: &media.GetAudioEncoderConfigurationFunction{},
GetAudioEncoderConfigurationOptions: &media.GetAudioEncoderConfigurationOptionsFunction{},
GetAudioEncoderConfigurations: &media.GetAudioEncoderConfigurationsFunction{},
GetAudioOutputConfiguration: &media.GetAudioOutputConfigurationFunction{},
GetAudioOutputConfigurationOptions: &media.GetAudioOutputConfigurationOptionsFunction{},
GetAudioOutputConfigurations: &media.GetAudioOutputConfigurationsFunction{},
GetAudioOutputs: &media.GetAudioOutputsFunction{},
GetAudioSourceConfiguration: &media.GetAudioSourceConfigurationFunction{},
GetAudioSourceConfigurationOptions: &media.GetAudioSourceConfigurationOptionsFunction{},
GetAudioSourceConfigurations: &media.GetAudioSourceConfigurationsFunction{},
GetAudioSources: &media.GetAudioSourcesFunction{},
GetCompatibleAudioDecoderConfigurations: &media.GetCompatibleAudioDecoderConfigurationsFunction{},
GetCompatibleAudioEncoderConfigurations: &media.GetCompatibleAudioEncoderConfigurationsFunction{},
GetCompatibleAudioOutputConfigurations: &media.GetCompatibleAudioOutputConfigurationsFunction{},
GetCompatibleAudioSourceConfigurations: &media.GetCompatibleAudioSourceConfigurationsFunction{},
GetCompatibleMetadataConfigurations: &media.GetCompatibleMetadataConfigurationsFunction{},
GetCompatibleVideoAnalyticsConfigurations: &media.GetCompatibleVideoAnalyticsConfigurationsFunction{},
GetCompatibleVideoEncoderConfigurations: &media.GetCompatibleVideoEncoderConfigurationsFunction{},
GetCompatibleVideoSourceConfigurations: &media.GetCompatibleVideoSourceConfigurationsFunction{},
GetGuaranteedNumberOfVideoEncoderInstances: &media.GetGuaranteedNumberOfVideoEncoderInstancesFunction{},
GetMetadataConfiguration: &media.GetMetadataConfigurationFunction{},
GetMetadataConfigurationOptions: &media.GetMetadataConfigurationOptionsFunction{},
GetMetadataConfigurations: &media.GetMetadataConfigurationsFunction{},
GetOSD: &media.GetOSDFunction{},
GetOSDOptions: &media.GetOSDOptionsFunction{},
GetOSDs: &media.GetOSDsFunction{},
GetProfile: &media.GetProfileFunction{},
GetProfiles: &media.GetProfilesFunction{},
GetServiceCapabilities: &media.GetServiceCapabilitiesFunction{},
GetSnapshotUri: &media.GetSnapshotUriFunction{},
GetStreamUri: &media.GetStreamUriFunction{},
GetVideoAnalyticsConfiguration: &media.GetVideoAnalyticsConfigurationFunction{},
GetVideoAnalyticsConfigurations: &media.GetVideoAnalyticsConfigurationsFunction{},
GetVideoEncoderConfiguration: &media.GetVideoEncoderConfigurationFunction{},
GetVideoEncoderConfigurationOptions: &media.GetVideoEncoderConfigurationOptionsFunction{},
GetVideoEncoderConfigurations: &media.GetVideoEncoderConfigurationsFunction{},
GetVideoSourceConfiguration: &media.GetVideoSourceConfigurationFunction{},
GetVideoSourceConfigurationOptions: &media.GetVideoSourceConfigurationOptionsFunction{},
GetVideoSourceConfigurations: &media.GetVideoSourceConfigurationsFunction{},
GetVideoSourceModes: &media.GetVideoSourceModesFunction{},
GetVideoSources: &media.GetVideoSourcesFunction{},
RemoveAudioDecoderConfiguration: &media.RemoveAudioDecoderConfigurationFunction{},
RemoveAudioEncoderConfiguration: &media.RemoveAudioEncoderConfigurationFunction{},
RemoveAudioOutputConfiguration: &media.RemoveAudioOutputConfigurationFunction{},
RemoveAudioSourceConfiguration: &media.RemoveAudioSourceConfigurationFunction{},
RemoveMetadataConfiguration: &media.RemoveMetadataConfigurationFunction{},
RemovePTZConfiguration: &media.RemovePTZConfigurationFunction{},
RemoveVideoAnalyticsConfiguration: &media.RemoveVideoAnalyticsConfigurationFunction{},
RemoveVideoEncoderConfiguration: &media.RemoveVideoEncoderConfigurationFunction{},
RemoveVideoSourceConfiguration: &media.RemoveVideoSourceConfigurationFunction{},
SetAudioDecoderConfiguration: &media.SetAudioDecoderConfigurationFunction{},
SetAudioEncoderConfiguration: &media.SetAudioEncoderConfigurationFunction{},
SetAudioOutputConfiguration: &media.SetAudioOutputConfigurationFunction{},
SetAudioSourceConfiguration: &media.SetAudioSourceConfigurationFunction{},
SetMetadataConfiguration: &media.SetMetadataConfigurationFunction{},
SetOSD: &media.SetOSDFunction{},
SetSynchronizationPoint: &media.SetSynchronizationPointFunction{},
SetVideoAnalyticsConfiguration: &media.SetVideoAnalyticsConfigurationFunction{},
SetVideoEncoderConfiguration: &media.SetVideoEncoderConfigurationFunction{},
SetVideoSourceConfiguration: &media.SetVideoSourceConfigurationFunction{},
SetVideoSourceMode: &media.SetVideoSourceModeFunction{},
StartMulticastStreaming: &media.StartMulticastStreamingFunction{},
StopMulticastStreaming: &media.StopMulticastStreamingFunction{},
}
var Media2FunctionMap = map[string]Function{
AddConfiguration: &media2.AddConfigurationFunction{},
GetAnalyticsConfigurations: &media2.GetAnalyticsConfigurationsFunction{},
GetProfiles: &media2.GetProfilesFunction{},
RemoveConfiguration: &media2.RemoveConfigurationFunction{},
}
var PTZFunctionMap = map[string]Function{
AbsoluteMove: &ptz.AbsoluteMoveFunction{},
ContinuousMove: &ptz.ContinuousMoveFunction{},
CreatePresetTour: &ptz.CreatePresetTourFunction{},
GeoMove: &ptz.GeoMoveFunction{},
GetCompatibleConfigurations: &ptz.GetCompatibleConfigurationsFunction{},
GetConfiguration: &ptz.GetConfigurationFunction{},
GetConfigurationOptions: &ptz.GetConfigurationOptionsFunction{},
GetConfigurations: &ptz.GetConfigurationsFunction{},
GetNode: &ptz.GetNodeFunction{},
GetNodes: &ptz.GetNodesFunction{},
GetPresetTour: &ptz.GetPresetTourFunction{},
GetPresetTourOptions: &ptz.GetPresetTourOptionsFunction{},
GetPresetTours: &ptz.GetPresetToursFunction{},
GetPresets: &ptz.GetPresetsFunction{},
GetServiceCapabilities: &ptz.GetServiceCapabilitiesFunction{},
GetStatus: &ptz.GetStatusFunction{},
GotoHomePosition: &ptz.GotoHomePositionFunction{},
GotoPreset: &ptz.GotoPresetFunction{},
ModifyPresetTour: &ptz.ModifyPresetTourFunction{},
OperatePresetTour: &ptz.OperatePresetTourFunction{},
RelativeMove: &ptz.RelativeMoveFunction{},
RemovePreset: &ptz.RemovePresetFunction{},
RemovePresetTour: &ptz.RemovePresetTourFunction{},
SendAuxiliaryCommand: &ptz.SendAuxiliaryCommandFunction{},
SetConfiguration: &ptz.SetConfigurationFunction{},
SetHomePosition: &ptz.SetHomePositionFunction{},
SetPreset: &ptz.SetPresetFunction{},
Stop: &ptz.StopFunction{},
}
var RecordingFunctionMap = map[string]Function{
CreateRecording: &recording.CreateRecordingFunction{},
CreateRecordingJob: &recording.CreateRecordingJobFunction{},
CreateTrack: &recording.CreateTrackFunction{},
DeleteRecording: &recording.DeleteRecordingFunction{},
DeleteRecordingJob: &recording.DeleteRecordingJobFunction{},
DeleteTrack: &recording.DeleteTrackFunction{},
ExportRecordedData: &recording.ExportRecordedDataFunction{},
GetExportRecordedDataState: &recording.GetExportRecordedDataStateFunction{},
GetRecordingConfiguration: &recording.GetRecordingConfigurationFunction{},
GetRecordingJobConfiguration: &recording.GetRecordingJobConfigurationFunction{},
GetRecordingJobState: &recording.GetRecordingJobStateFunction{},
GetRecordingJobs: &recording.GetRecordingJobsFunction{},
GetRecordingOptions: &recording.GetRecordingOptionsFunction{},
GetRecordings: &recording.GetRecordingsFunction{},
GetServiceCapabilities: &recording.GetServiceCapabilitiesFunction{},
GetTrackConfiguration: &recording.GetTrackConfigurationFunction{},
SetRecordingConfiguration: &recording.SetRecordingConfigurationFunction{},
SetRecordingJobConfiguration: &recording.SetRecordingJobConfigurationFunction{},
SetRecordingJobMode: &recording.SetRecordingJobModeFunction{},
SetTrackConfiguration: &recording.SetTrackConfigurationFunction{},
StopExportRecordedData: &recording.StopExportRecordedDataFunction{},
}

720
media/function.go Normal file
View File

@@ -0,0 +1,720 @@
// -*- Mode: Go; indent-tabs-mode: t -*-
//
// Copyright (C) 2022 Intel Corporation
//
// SPDX-License-Identifier: Apache-2.0
// Code generated by gen_commands.py DO NOT EDIT.
package media
type AddAudioDecoderConfigurationFunction struct{}
func (_ *AddAudioDecoderConfigurationFunction) Request() interface{} {
return &AddAudioDecoderConfiguration{}
}
func (_ *AddAudioDecoderConfigurationFunction) Response() interface{} {
return &AddAudioDecoderConfigurationResponse{}
}
type AddAudioEncoderConfigurationFunction struct{}
func (_ *AddAudioEncoderConfigurationFunction) Request() interface{} {
return &AddAudioEncoderConfiguration{}
}
func (_ *AddAudioEncoderConfigurationFunction) Response() interface{} {
return &AddAudioEncoderConfigurationResponse{}
}
type AddAudioOutputConfigurationFunction struct{}
func (_ *AddAudioOutputConfigurationFunction) Request() interface{} {
return &AddAudioOutputConfiguration{}
}
func (_ *AddAudioOutputConfigurationFunction) Response() interface{} {
return &AddAudioOutputConfigurationResponse{}
}
type AddAudioSourceConfigurationFunction struct{}
func (_ *AddAudioSourceConfigurationFunction) Request() interface{} {
return &AddAudioSourceConfiguration{}
}
func (_ *AddAudioSourceConfigurationFunction) Response() interface{} {
return &AddAudioSourceConfigurationResponse{}
}
type AddMetadataConfigurationFunction struct{}
func (_ *AddMetadataConfigurationFunction) Request() interface{} {
return &AddMetadataConfiguration{}
}
func (_ *AddMetadataConfigurationFunction) Response() interface{} {
return &AddMetadataConfigurationResponse{}
}
type AddPTZConfigurationFunction struct{}
func (_ *AddPTZConfigurationFunction) Request() interface{} {
return &AddPTZConfiguration{}
}
func (_ *AddPTZConfigurationFunction) Response() interface{} {
return &AddPTZConfigurationResponse{}
}
type AddVideoAnalyticsConfigurationFunction struct{}
func (_ *AddVideoAnalyticsConfigurationFunction) Request() interface{} {
return &AddVideoAnalyticsConfiguration{}
}
func (_ *AddVideoAnalyticsConfigurationFunction) Response() interface{} {
return &AddVideoAnalyticsConfigurationResponse{}
}
type AddVideoEncoderConfigurationFunction struct{}
func (_ *AddVideoEncoderConfigurationFunction) Request() interface{} {
return &AddVideoEncoderConfiguration{}
}
func (_ *AddVideoEncoderConfigurationFunction) Response() interface{} {
return &AddVideoEncoderConfigurationResponse{}
}
type AddVideoSourceConfigurationFunction struct{}
func (_ *AddVideoSourceConfigurationFunction) Request() interface{} {
return &AddVideoSourceConfiguration{}
}
func (_ *AddVideoSourceConfigurationFunction) Response() interface{} {
return &AddVideoSourceConfigurationResponse{}
}
type CreateOSDFunction struct{}
func (_ *CreateOSDFunction) Request() interface{} {
return &CreateOSD{}
}
func (_ *CreateOSDFunction) Response() interface{} {
return &CreateOSDResponse{}
}
type CreateProfileFunction struct{}
func (_ *CreateProfileFunction) Request() interface{} {
return &CreateProfile{}
}
func (_ *CreateProfileFunction) Response() interface{} {
return &CreateProfileResponse{}
}
type DeleteOSDFunction struct{}
func (_ *DeleteOSDFunction) Request() interface{} {
return &DeleteOSD{}
}
func (_ *DeleteOSDFunction) Response() interface{} {
return &DeleteOSDResponse{}
}
type DeleteProfileFunction struct{}
func (_ *DeleteProfileFunction) Request() interface{} {
return &DeleteProfile{}
}
func (_ *DeleteProfileFunction) Response() interface{} {
return &DeleteProfileResponse{}
}
type GetAudioDecoderConfigurationFunction struct{}
func (_ *GetAudioDecoderConfigurationFunction) Request() interface{} {
return &GetAudioDecoderConfiguration{}
}
func (_ *GetAudioDecoderConfigurationFunction) Response() interface{} {
return &GetAudioDecoderConfigurationResponse{}
}
type GetAudioDecoderConfigurationOptionsFunction struct{}
func (_ *GetAudioDecoderConfigurationOptionsFunction) Request() interface{} {
return &GetAudioDecoderConfigurationOptions{}
}
func (_ *GetAudioDecoderConfigurationOptionsFunction) Response() interface{} {
return &GetAudioDecoderConfigurationOptionsResponse{}
}
type GetAudioDecoderConfigurationsFunction struct{}
func (_ *GetAudioDecoderConfigurationsFunction) Request() interface{} {
return &GetAudioDecoderConfigurations{}
}
func (_ *GetAudioDecoderConfigurationsFunction) Response() interface{} {
return &GetAudioDecoderConfigurationsResponse{}
}
type GetAudioEncoderConfigurationFunction struct{}
func (_ *GetAudioEncoderConfigurationFunction) Request() interface{} {
return &GetAudioEncoderConfiguration{}
}
func (_ *GetAudioEncoderConfigurationFunction) Response() interface{} {
return &GetAudioEncoderConfigurationResponse{}
}
type GetAudioEncoderConfigurationOptionsFunction struct{}
func (_ *GetAudioEncoderConfigurationOptionsFunction) Request() interface{} {
return &GetAudioEncoderConfigurationOptions{}
}
func (_ *GetAudioEncoderConfigurationOptionsFunction) Response() interface{} {
return &GetAudioEncoderConfigurationOptionsResponse{}
}
type GetAudioEncoderConfigurationsFunction struct{}
func (_ *GetAudioEncoderConfigurationsFunction) Request() interface{} {
return &GetAudioEncoderConfigurations{}
}
func (_ *GetAudioEncoderConfigurationsFunction) Response() interface{} {
return &GetAudioEncoderConfigurationsResponse{}
}
type GetAudioOutputConfigurationFunction struct{}
func (_ *GetAudioOutputConfigurationFunction) Request() interface{} {
return &GetAudioOutputConfiguration{}
}
func (_ *GetAudioOutputConfigurationFunction) Response() interface{} {
return &GetAudioOutputConfigurationResponse{}
}
type GetAudioOutputConfigurationOptionsFunction struct{}
func (_ *GetAudioOutputConfigurationOptionsFunction) Request() interface{} {
return &GetAudioOutputConfigurationOptions{}
}
func (_ *GetAudioOutputConfigurationOptionsFunction) Response() interface{} {
return &GetAudioOutputConfigurationOptionsResponse{}
}
type GetAudioOutputConfigurationsFunction struct{}
func (_ *GetAudioOutputConfigurationsFunction) Request() interface{} {
return &GetAudioOutputConfigurations{}
}
func (_ *GetAudioOutputConfigurationsFunction) Response() interface{} {
return &GetAudioOutputConfigurationsResponse{}
}
type GetAudioOutputsFunction struct{}
func (_ *GetAudioOutputsFunction) Request() interface{} {
return &GetAudioOutputs{}
}
func (_ *GetAudioOutputsFunction) Response() interface{} {
return &GetAudioOutputsResponse{}
}
type GetAudioSourceConfigurationFunction struct{}
func (_ *GetAudioSourceConfigurationFunction) Request() interface{} {
return &GetAudioSourceConfiguration{}
}
func (_ *GetAudioSourceConfigurationFunction) Response() interface{} {
return &GetAudioSourceConfigurationResponse{}
}
type GetAudioSourceConfigurationOptionsFunction struct{}
func (_ *GetAudioSourceConfigurationOptionsFunction) Request() interface{} {
return &GetAudioSourceConfigurationOptions{}
}
func (_ *GetAudioSourceConfigurationOptionsFunction) Response() interface{} {
return &GetAudioSourceConfigurationOptionsResponse{}
}
type GetAudioSourceConfigurationsFunction struct{}
func (_ *GetAudioSourceConfigurationsFunction) Request() interface{} {
return &GetAudioSourceConfigurations{}
}
func (_ *GetAudioSourceConfigurationsFunction) Response() interface{} {
return &GetAudioSourceConfigurationsResponse{}
}
type GetAudioSourcesFunction struct{}
func (_ *GetAudioSourcesFunction) Request() interface{} {
return &GetAudioSources{}
}
func (_ *GetAudioSourcesFunction) Response() interface{} {
return &GetAudioSourcesResponse{}
}
type GetCompatibleAudioDecoderConfigurationsFunction struct{}
func (_ *GetCompatibleAudioDecoderConfigurationsFunction) Request() interface{} {
return &GetCompatibleAudioDecoderConfigurations{}
}
func (_ *GetCompatibleAudioDecoderConfigurationsFunction) Response() interface{} {
return &GetCompatibleAudioDecoderConfigurationsResponse{}
}
type GetCompatibleAudioEncoderConfigurationsFunction struct{}
func (_ *GetCompatibleAudioEncoderConfigurationsFunction) Request() interface{} {
return &GetCompatibleAudioEncoderConfigurations{}
}
func (_ *GetCompatibleAudioEncoderConfigurationsFunction) Response() interface{} {
return &GetCompatibleAudioEncoderConfigurationsResponse{}
}
type GetCompatibleAudioOutputConfigurationsFunction struct{}
func (_ *GetCompatibleAudioOutputConfigurationsFunction) Request() interface{} {
return &GetCompatibleAudioOutputConfigurations{}
}
func (_ *GetCompatibleAudioOutputConfigurationsFunction) Response() interface{} {
return &GetCompatibleAudioOutputConfigurationsResponse{}
}
type GetCompatibleAudioSourceConfigurationsFunction struct{}
func (_ *GetCompatibleAudioSourceConfigurationsFunction) Request() interface{} {
return &GetCompatibleAudioSourceConfigurations{}
}
func (_ *GetCompatibleAudioSourceConfigurationsFunction) Response() interface{} {
return &GetCompatibleAudioSourceConfigurationsResponse{}
}
type GetCompatibleMetadataConfigurationsFunction struct{}
func (_ *GetCompatibleMetadataConfigurationsFunction) Request() interface{} {
return &GetCompatibleMetadataConfigurations{}
}
func (_ *GetCompatibleMetadataConfigurationsFunction) Response() interface{} {
return &GetCompatibleMetadataConfigurationsResponse{}
}
type GetCompatibleVideoAnalyticsConfigurationsFunction struct{}
func (_ *GetCompatibleVideoAnalyticsConfigurationsFunction) Request() interface{} {
return &GetCompatibleVideoAnalyticsConfigurations{}
}
func (_ *GetCompatibleVideoAnalyticsConfigurationsFunction) Response() interface{} {
return &GetCompatibleVideoAnalyticsConfigurationsResponse{}
}
type GetCompatibleVideoEncoderConfigurationsFunction struct{}
func (_ *GetCompatibleVideoEncoderConfigurationsFunction) Request() interface{} {
return &GetCompatibleVideoEncoderConfigurations{}
}
func (_ *GetCompatibleVideoEncoderConfigurationsFunction) Response() interface{} {
return &GetCompatibleVideoEncoderConfigurationsResponse{}
}
type GetCompatibleVideoSourceConfigurationsFunction struct{}
func (_ *GetCompatibleVideoSourceConfigurationsFunction) Request() interface{} {
return &GetCompatibleVideoSourceConfigurations{}
}
func (_ *GetCompatibleVideoSourceConfigurationsFunction) Response() interface{} {
return &GetCompatibleVideoSourceConfigurationsResponse{}
}
type GetGuaranteedNumberOfVideoEncoderInstancesFunction struct{}
func (_ *GetGuaranteedNumberOfVideoEncoderInstancesFunction) Request() interface{} {
return &GetGuaranteedNumberOfVideoEncoderInstances{}
}
func (_ *GetGuaranteedNumberOfVideoEncoderInstancesFunction) Response() interface{} {
return &GetGuaranteedNumberOfVideoEncoderInstancesResponse{}
}
type GetMetadataConfigurationFunction struct{}
func (_ *GetMetadataConfigurationFunction) Request() interface{} {
return &GetMetadataConfiguration{}
}
func (_ *GetMetadataConfigurationFunction) Response() interface{} {
return &GetMetadataConfigurationResponse{}
}
type GetMetadataConfigurationOptionsFunction struct{}
func (_ *GetMetadataConfigurationOptionsFunction) Request() interface{} {
return &GetMetadataConfigurationOptions{}
}
func (_ *GetMetadataConfigurationOptionsFunction) Response() interface{} {
return &GetMetadataConfigurationOptionsResponse{}
}
type GetMetadataConfigurationsFunction struct{}
func (_ *GetMetadataConfigurationsFunction) Request() interface{} {
return &GetMetadataConfigurations{}
}
func (_ *GetMetadataConfigurationsFunction) Response() interface{} {
return &GetMetadataConfigurationsResponse{}
}
type GetOSDFunction struct{}
func (_ *GetOSDFunction) Request() interface{} {
return &GetOSD{}
}
func (_ *GetOSDFunction) Response() interface{} {
return &GetOSDResponse{}
}
type GetOSDOptionsFunction struct{}
func (_ *GetOSDOptionsFunction) Request() interface{} {
return &GetOSDOptions{}
}
func (_ *GetOSDOptionsFunction) Response() interface{} {
return &GetOSDOptionsResponse{}
}
type GetOSDsFunction struct{}
func (_ *GetOSDsFunction) Request() interface{} {
return &GetOSDs{}
}
func (_ *GetOSDsFunction) Response() interface{} {
return &GetOSDsResponse{}
}
type GetProfileFunction struct{}
func (_ *GetProfileFunction) Request() interface{} {
return &GetProfile{}
}
func (_ *GetProfileFunction) Response() interface{} {
return &GetProfileResponse{}
}
type GetProfilesFunction struct{}
func (_ *GetProfilesFunction) Request() interface{} {
return &GetProfiles{}
}
func (_ *GetProfilesFunction) Response() interface{} {
return &GetProfilesResponse{}
}
type GetServiceCapabilitiesFunction struct{}
func (_ *GetServiceCapabilitiesFunction) Request() interface{} {
return &GetServiceCapabilities{}
}
func (_ *GetServiceCapabilitiesFunction) Response() interface{} {
return &GetServiceCapabilitiesResponse{}
}
type GetSnapshotUriFunction struct{}
func (_ *GetSnapshotUriFunction) Request() interface{} {
return &GetSnapshotUri{}
}
func (_ *GetSnapshotUriFunction) Response() interface{} {
return &GetSnapshotUriResponse{}
}
type GetStreamUriFunction struct{}
func (_ *GetStreamUriFunction) Request() interface{} {
return &GetStreamUri{}
}
func (_ *GetStreamUriFunction) Response() interface{} {
return &GetStreamUriResponse{}
}
type GetVideoAnalyticsConfigurationFunction struct{}
func (_ *GetVideoAnalyticsConfigurationFunction) Request() interface{} {
return &GetVideoAnalyticsConfiguration{}
}
func (_ *GetVideoAnalyticsConfigurationFunction) Response() interface{} {
return &GetVideoAnalyticsConfigurationResponse{}
}
type GetVideoAnalyticsConfigurationsFunction struct{}
func (_ *GetVideoAnalyticsConfigurationsFunction) Request() interface{} {
return &GetVideoAnalyticsConfigurations{}
}
func (_ *GetVideoAnalyticsConfigurationsFunction) Response() interface{} {
return &GetVideoAnalyticsConfigurationsResponse{}
}
type GetVideoEncoderConfigurationFunction struct{}
func (_ *GetVideoEncoderConfigurationFunction) Request() interface{} {
return &GetVideoEncoderConfiguration{}
}
func (_ *GetVideoEncoderConfigurationFunction) Response() interface{} {
return &GetVideoEncoderConfigurationResponse{}
}
type GetVideoEncoderConfigurationOptionsFunction struct{}
func (_ *GetVideoEncoderConfigurationOptionsFunction) Request() interface{} {
return &GetVideoEncoderConfigurationOptions{}
}
func (_ *GetVideoEncoderConfigurationOptionsFunction) Response() interface{} {
return &GetVideoEncoderConfigurationOptionsResponse{}
}
type GetVideoEncoderConfigurationsFunction struct{}
func (_ *GetVideoEncoderConfigurationsFunction) Request() interface{} {
return &GetVideoEncoderConfigurations{}
}
func (_ *GetVideoEncoderConfigurationsFunction) Response() interface{} {
return &GetVideoEncoderConfigurationsResponse{}
}
type GetVideoSourceConfigurationFunction struct{}
func (_ *GetVideoSourceConfigurationFunction) Request() interface{} {
return &GetVideoSourceConfiguration{}
}
func (_ *GetVideoSourceConfigurationFunction) Response() interface{} {
return &GetVideoSourceConfigurationResponse{}
}
type GetVideoSourceConfigurationOptionsFunction struct{}
func (_ *GetVideoSourceConfigurationOptionsFunction) Request() interface{} {
return &GetVideoSourceConfigurationOptions{}
}
func (_ *GetVideoSourceConfigurationOptionsFunction) Response() interface{} {
return &GetVideoSourceConfigurationOptionsResponse{}
}
type GetVideoSourceConfigurationsFunction struct{}
func (_ *GetVideoSourceConfigurationsFunction) Request() interface{} {
return &GetVideoSourceConfigurations{}
}
func (_ *GetVideoSourceConfigurationsFunction) Response() interface{} {
return &GetVideoSourceConfigurationsResponse{}
}
type GetVideoSourceModesFunction struct{}
func (_ *GetVideoSourceModesFunction) Request() interface{} {
return &GetVideoSourceModes{}
}
func (_ *GetVideoSourceModesFunction) Response() interface{} {
return &GetVideoSourceModesResponse{}
}
type GetVideoSourcesFunction struct{}
func (_ *GetVideoSourcesFunction) Request() interface{} {
return &GetVideoSources{}
}
func (_ *GetVideoSourcesFunction) Response() interface{} {
return &GetVideoSourcesResponse{}
}
type RemoveAudioDecoderConfigurationFunction struct{}
func (_ *RemoveAudioDecoderConfigurationFunction) Request() interface{} {
return &RemoveAudioDecoderConfiguration{}
}
func (_ *RemoveAudioDecoderConfigurationFunction) Response() interface{} {
return &RemoveAudioDecoderConfigurationResponse{}
}
type RemoveAudioEncoderConfigurationFunction struct{}
func (_ *RemoveAudioEncoderConfigurationFunction) Request() interface{} {
return &RemoveAudioEncoderConfiguration{}
}
func (_ *RemoveAudioEncoderConfigurationFunction) Response() interface{} {
return &RemoveAudioEncoderConfigurationResponse{}
}
type RemoveAudioOutputConfigurationFunction struct{}
func (_ *RemoveAudioOutputConfigurationFunction) Request() interface{} {
return &RemoveAudioOutputConfiguration{}
}
func (_ *RemoveAudioOutputConfigurationFunction) Response() interface{} {
return &RemoveAudioOutputConfigurationResponse{}
}
type RemoveAudioSourceConfigurationFunction struct{}
func (_ *RemoveAudioSourceConfigurationFunction) Request() interface{} {
return &RemoveAudioSourceConfiguration{}
}
func (_ *RemoveAudioSourceConfigurationFunction) Response() interface{} {
return &RemoveAudioSourceConfigurationResponse{}
}
type RemoveMetadataConfigurationFunction struct{}
func (_ *RemoveMetadataConfigurationFunction) Request() interface{} {
return &RemoveMetadataConfiguration{}
}
func (_ *RemoveMetadataConfigurationFunction) Response() interface{} {
return &RemoveMetadataConfigurationResponse{}
}
type RemovePTZConfigurationFunction struct{}
func (_ *RemovePTZConfigurationFunction) Request() interface{} {
return &RemovePTZConfiguration{}
}
func (_ *RemovePTZConfigurationFunction) Response() interface{} {
return &RemovePTZConfigurationResponse{}
}
type RemoveVideoAnalyticsConfigurationFunction struct{}
func (_ *RemoveVideoAnalyticsConfigurationFunction) Request() interface{} {
return &RemoveVideoAnalyticsConfiguration{}
}
func (_ *RemoveVideoAnalyticsConfigurationFunction) Response() interface{} {
return &RemoveVideoAnalyticsConfigurationResponse{}
}
type RemoveVideoEncoderConfigurationFunction struct{}
func (_ *RemoveVideoEncoderConfigurationFunction) Request() interface{} {
return &RemoveVideoEncoderConfiguration{}
}
func (_ *RemoveVideoEncoderConfigurationFunction) Response() interface{} {
return &RemoveVideoEncoderConfigurationResponse{}
}
type RemoveVideoSourceConfigurationFunction struct{}
func (_ *RemoveVideoSourceConfigurationFunction) Request() interface{} {
return &RemoveVideoSourceConfiguration{}
}
func (_ *RemoveVideoSourceConfigurationFunction) Response() interface{} {
return &RemoveVideoSourceConfigurationResponse{}
}
type SetAudioDecoderConfigurationFunction struct{}
func (_ *SetAudioDecoderConfigurationFunction) Request() interface{} {
return &SetAudioDecoderConfiguration{}
}
func (_ *SetAudioDecoderConfigurationFunction) Response() interface{} {
return &SetAudioDecoderConfigurationResponse{}
}
type SetAudioEncoderConfigurationFunction struct{}
func (_ *SetAudioEncoderConfigurationFunction) Request() interface{} {
return &SetAudioEncoderConfiguration{}
}
func (_ *SetAudioEncoderConfigurationFunction) Response() interface{} {
return &SetAudioEncoderConfigurationResponse{}
}
type SetAudioOutputConfigurationFunction struct{}
func (_ *SetAudioOutputConfigurationFunction) Request() interface{} {
return &SetAudioOutputConfiguration{}
}
func (_ *SetAudioOutputConfigurationFunction) Response() interface{} {
return &SetAudioOutputConfigurationResponse{}
}
type SetAudioSourceConfigurationFunction struct{}
func (_ *SetAudioSourceConfigurationFunction) Request() interface{} {
return &SetAudioSourceConfiguration{}
}
func (_ *SetAudioSourceConfigurationFunction) Response() interface{} {
return &SetAudioSourceConfigurationResponse{}
}
type SetMetadataConfigurationFunction struct{}
func (_ *SetMetadataConfigurationFunction) Request() interface{} {
return &SetMetadataConfiguration{}
}
func (_ *SetMetadataConfigurationFunction) Response() interface{} {
return &SetMetadataConfigurationResponse{}
}
type SetOSDFunction struct{}
func (_ *SetOSDFunction) Request() interface{} {
return &SetOSD{}
}
func (_ *SetOSDFunction) Response() interface{} {
return &SetOSDResponse{}
}
type SetSynchronizationPointFunction struct{}
func (_ *SetSynchronizationPointFunction) Request() interface{} {
return &SetSynchronizationPoint{}
}
func (_ *SetSynchronizationPointFunction) Response() interface{} {
return &SetSynchronizationPointResponse{}
}
type SetVideoAnalyticsConfigurationFunction struct{}
func (_ *SetVideoAnalyticsConfigurationFunction) Request() interface{} {
return &SetVideoAnalyticsConfiguration{}
}
func (_ *SetVideoAnalyticsConfigurationFunction) Response() interface{} {
return &SetVideoAnalyticsConfigurationResponse{}
}
type SetVideoEncoderConfigurationFunction struct{}
func (_ *SetVideoEncoderConfigurationFunction) Request() interface{} {
return &SetVideoEncoderConfiguration{}
}
func (_ *SetVideoEncoderConfigurationFunction) Response() interface{} {
return &SetVideoEncoderConfigurationResponse{}
}
type SetVideoSourceConfigurationFunction struct{}
func (_ *SetVideoSourceConfigurationFunction) Request() interface{} {
return &SetVideoSourceConfiguration{}
}
func (_ *SetVideoSourceConfigurationFunction) Response() interface{} {
return &SetVideoSourceConfigurationResponse{}
}
type SetVideoSourceModeFunction struct{}
func (_ *SetVideoSourceModeFunction) Request() interface{} {
return &SetVideoSourceMode{}
}
func (_ *SetVideoSourceModeFunction) Response() interface{} {
return &SetVideoSourceModeResponse{}
}
type StartMulticastStreamingFunction struct{}
func (_ *StartMulticastStreamingFunction) Request() interface{} {
return &StartMulticastStreaming{}
}
func (_ *StartMulticastStreamingFunction) Response() interface{} {
return &StartMulticastStreamingResponse{}
}
type StopMulticastStreamingFunction struct{}
func (_ *StopMulticastStreamingFunction) Request() interface{} {
return &StopMulticastStreaming{}
}
func (_ *StopMulticastStreamingFunction) Response() interface{} {
return &StopMulticastStreamingResponse{}
}

View File

@@ -1,8 +1,10 @@
package media
//go:generate python3 ../python/gen_commands.py
import (
"github.com/use-go/onvif/xsd"
"github.com/use-go/onvif/xsd/onvif"
"github.com/kerberos-io/onvif/xsd"
"github.com/kerberos-io/onvif/xsd/onvif"
)
type Capabilities struct {
@@ -72,6 +74,8 @@ type CreateProfileResponse struct {
Profile onvif.Profile
}
// GetProfile and its properties are defined in the Onvif specification:
// https://www.onvif.org/ver10/media/wsdl/media.wsdl#op.GetProfile
type GetProfile struct {
XMLName string `xml:"trt:GetProfile"`
ProfileToken onvif.ReferenceToken `xml:"trt:ProfileToken"`
@@ -290,6 +294,8 @@ type GetVideoAnalyticsConfigurationsResponse struct {
Configurations onvif.VideoAnalyticsConfiguration
}
// GetMetadataConfigurations and its properties are defined in the Onvif specification:
// https://www.onvif.org/ver10/media/wsdl/media.wsdl#op.GetMetadataConfigurations
type GetMetadataConfigurations struct {
XMLName string `xml:"trt:GetMetadataConfigurations"`
}
@@ -323,6 +329,8 @@ type GetVideoSourceConfigurationResponse struct {
Configuration onvif.VideoSourceConfiguration
}
// GetVideoEncoderConfiguration and its properties are defined in the Onvif specification:
// https://www.onvif.org/ver10/media/wsdl/media.wsdl#op.GetVideoEncoderConfiguration
type GetVideoEncoderConfiguration struct {
XMLName string `xml:"trt:GetVideoEncoderConfiguration"`
ConfigurationToken onvif.ReferenceToken `xml:"trt:ConfigurationToken"`
@@ -359,6 +367,8 @@ type GetVideoAnalyticsConfigurationResponse struct {
Configuration onvif.VideoAnalyticsConfiguration
}
// GetMetadataConfiguration and its properties are defined in the Onvif specification:
// https://www.onvif.org/ver10/media/wsdl/media.wsdl#op.GetMetadataConfiguration
type GetMetadataConfiguration struct {
XMLName string `xml:"trt:GetMetadataConfiguration"`
ConfigurationToken onvif.ReferenceToken `xml:"trt:ConfigurationToken"`
@@ -431,6 +441,8 @@ type GetCompatibleVideoAnalyticsConfigurationsResponse struct {
Configurations onvif.VideoAnalyticsConfiguration
}
// GetCompatibleMetadataConfigurations and its properties are defined in the Onvif specification:
// https://www.onvif.org/ver10/media/wsdl/media.wsdl#op.GetCompatibleMetadataConfigurations
type GetCompatibleMetadataConfigurations struct {
XMLName string `xml:"trt:GetCompatibleMetadataConfigurations"`
ProfileToken onvif.ReferenceToken `xml:"trt:ProfileToken"`
@@ -468,9 +480,9 @@ type SetVideoSourceConfigurationResponse struct {
}
type SetVideoEncoderConfiguration struct {
XMLName string `xml:"trt:SetVideoEncoderConfiguration"`
Configuration onvif.VideoEncoderConfiguration `xml:"trt:Configuration"`
ForcePersistence xsd.Boolean `xml:"trt:ForcePersistence"`
XMLName string `xml:"trt:SetVideoEncoderConfiguration"`
Configuration *onvif.VideoEncoderConfigurationRequest `xml:"trt:Configuration,omitempty"`
ForcePersistence *xsd.Boolean `xml:"trt:ForcePersistence,omitempty"`
}
type SetVideoEncoderConfigurationResponse struct {
@@ -503,10 +515,12 @@ type SetVideoAnalyticsConfiguration struct {
type SetVideoAnalyticsConfigurationResponse struct {
}
// SetMetadataConfiguration and its properties are defined in the Onvif specification:
// https://www.onvif.org/ver10/media/wsdl/media.wsdl#op.SetMetadataConfiguration
type SetMetadataConfiguration struct {
XMLName string `xml:"trt:GetDeviceInformation"`
Configuration onvif.MetadataConfiguration `xml:"trt:Configuration"`
ForcePersistence xsd.Boolean `xml:"trt:ForcePersistence"`
XMLName string `xml:"trt:SetMetadataConfiguration"`
Configuration onvif.MetadataConfigurationRequest `xml:"trt:Configuration"`
ForcePersistence xsd.Boolean `xml:"trt:ForcePersistence"`
}
type SetMetadataConfigurationResponse struct {
@@ -540,6 +554,8 @@ type GetVideoSourceConfigurationOptionsResponse struct {
Options onvif.VideoSourceConfigurationOptions
}
// GetVideoEncoderConfigurationOptions and its properties are defined in the Onvif specification:
// https://www.onvif.org/ver10/media/wsdl/media.wsdl#op.GetVideoEncoderConfigurationOptions
type GetVideoEncoderConfigurationOptions struct {
XMLName string `xml:"trt:GetVideoEncoderConfigurationOptions"`
ProfileToken onvif.ReferenceToken `xml:"trt:ProfileToken"`
@@ -612,10 +628,12 @@ type GetGuaranteedNumberOfVideoEncoderInstancesResponse struct {
MPEG4 int
}
// GetStreamUri and its properties are defined in the Onvif specification:
// https://www.onvif.org/ver10/media/wsdl/media.wsdl#op.GetStreamUri
type GetStreamUri struct {
XMLName string `xml:"trt:GetStreamUri"`
StreamSetup onvif.StreamSetup `xml:"trt:StreamSetup"`
ProfileToken onvif.ReferenceToken `xml:"trt:ProfileToken"`
XMLName string `xml:"trt:GetStreamUri"`
StreamSetup *onvif.StreamSetup `xml:"trt:StreamSetup"`
ProfileToken *onvif.ReferenceToken `xml:"trt:ProfileToken"`
}
type GetStreamUriResponse struct {

45
media2/function.go Normal file
View File

@@ -0,0 +1,45 @@
// -*- Mode: Go; indent-tabs-mode: t -*-
//
// Copyright (C) 2022 Intel Corporation
//
// SPDX-License-Identifier: Apache-2.0
// Code generated by gen_commands.py DO NOT EDIT.
package media2
type AddConfigurationFunction struct{}
func (_ *AddConfigurationFunction) Request() interface{} {
return &AddConfiguration{}
}
func (_ *AddConfigurationFunction) Response() interface{} {
return &AddConfigurationResponse{}
}
type GetAnalyticsConfigurationsFunction struct{}
func (_ *GetAnalyticsConfigurationsFunction) Request() interface{} {
return &GetAnalyticsConfigurations{}
}
func (_ *GetAnalyticsConfigurationsFunction) Response() interface{} {
return &GetAnalyticsConfigurationsResponse{}
}
type GetProfilesFunction struct{}
func (_ *GetProfilesFunction) Request() interface{} {
return &GetProfiles{}
}
func (_ *GetProfilesFunction) Response() interface{} {
return &GetProfilesResponse{}
}
type RemoveConfigurationFunction struct{}
func (_ *RemoveConfigurationFunction) Request() interface{} {
return &RemoveConfiguration{}
}
func (_ *RemoveConfigurationFunction) Response() interface{} {
return &RemoveConfigurationResponse{}
}

93
media2/types.go Normal file
View File

@@ -0,0 +1,93 @@
package media2
//go:generate python3 ../python/gen_commands.py
import (
"github.com/kerberos-io/onvif/xsd"
"github.com/kerberos-io/onvif/xsd/onvif"
)
type GetProfiles struct {
XMLName string `xml:"tr2:GetProfiles"`
}
type GetProfilesResponse struct {
Profiles []Profile
}
type Profile struct {
Token string `xml:"token,attr"`
Fixed bool `xml:"fixed,attr"`
Name string
}
type GetAnalyticsConfigurations struct {
XMLName string `xml:"tr2:GetAnalyticsConfigurations"`
}
type GetAnalyticsConfigurationsResponse struct {
Configurations []Configurations
}
type Configurations struct {
onvif.ConfigurationEntity
AnalyticsEngineConfiguration *AnalyticsEngineConfiguration `json:",omitempty"`
RuleEngineConfiguration *RuleEngineConfiguration `json:",omitempty"`
}
type AnalyticsEngineConfiguration struct {
AnalyticsModule []AnalyticsModule
}
type AnalyticsModule struct {
Name string `xml:",attr"`
Type string `xml:",attr"`
Parameters Parameters
}
type RuleEngineConfiguration struct {
Rule []Rule `json:",omitempty"`
}
type Rule struct {
Name string `xml:",attr"`
Type string `xml:",attr"`
Parameters Parameters
}
type Parameters struct {
SimpleItem []SimpleItem `json:",omitempty"`
ElementItem []ElementItem `json:",omitempty"`
}
type SimpleItem struct {
Name string `xml:",attr"`
Value string `xml:",attr"`
}
type ElementItem struct {
Name string `xml:",attr"`
}
type AddConfiguration struct {
XMLName string `xml:"tr2:AddConfiguration"`
ProfileToken string `xml:"tr2:ProfileToken"`
Name string `xml:"tr2:Name,omitempty"`
Configuration []Configuration
}
type AddConfigurationResponse struct{}
type RemoveConfiguration struct {
XMLName string `xml:"tr2:RemoveConfiguration"`
ProfileToken string `xml:"tr2:ProfileToken"`
Configuration []Configuration
}
type RemoveConfigurationResponse struct{}
type Configuration struct {
XMLName xsd.String `xml:"tr2:Configuration"`
Type *xsd.String `xml:"tr2:Type,omitempty"`
Token *xsd.String `xml:"tr2:Token,omitempty"`
}

134
media2/types_test.go Normal file
View File

@@ -0,0 +1,134 @@
package media2
import (
"encoding/xml"
"fmt"
"testing"
"github.com/kerberos-io/onvif/xsd"
"github.com/kerberos-io/onvif/xsd/onvif"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestUnmarshalGetProfilesResponse(t *testing.T) {
profile1Name := "H26x_L1S1"
profile1Token := "profile_1"
profile1Fixed := false
profile2Name := "JPEG_L1S3"
profile2Token := "profile_2"
profile2Fixed := true
GetProfilesResponseData := fmt.Sprintf(`
<tms:GetProfilesResponse>
<tms:Profiles token="%s" fixed="%t"><tms:Name>%s</tms:Name></tms:Profiles>
<tms:Profiles token="%s" fixed="%t"><tms:Name>%s</tms:Name></tms:Profiles>
</tms:GetProfilesResponse>
`, profile1Token, profile1Fixed, profile1Name, profile2Token, profile2Fixed, profile2Name)
getProfilesResponse := &GetProfilesResponse{}
err := xml.Unmarshal([]byte(GetProfilesResponseData), getProfilesResponse)
require.NoError(t, err)
assert.Equal(t, getProfilesResponse.Profiles[0].Token, profile1Token)
assert.Equal(t, getProfilesResponse.Profiles[0].Fixed, profile1Fixed)
assert.Equal(t, getProfilesResponse.Profiles[0].Name, profile1Name)
assert.Equal(t, getProfilesResponse.Profiles[1].Token, profile2Token)
assert.Equal(t, getProfilesResponse.Profiles[1].Fixed, profile2Fixed)
assert.Equal(t, getProfilesResponse.Profiles[1].Name, profile2Name)
}
func TestUnmarshalGetAnalyticsConfigurationsResponse(t *testing.T) {
configToken := onvif.ReferenceToken("token_1")
configName := onvif.Name("Analytics_1")
useCount := 0
analyticsModuleName := "Viproc"
analyticsModuleType := "tt:Viproc"
analyticsModuleItemName := "AnalysisType"
analyticsModuleItemValue := "Intelligent Video Analytics"
ruleName := "The Min ObjectHeight"
ruleType := "tt:ObjectInField"
ruleItemName := "MaxObjectHeight"
ruleItemValue := "100"
responseData := fmt.Sprintf(`
<tms:GetAnalyticsConfigurationsResponse>
<tms:Configurations token="%s">
<tt:Name>%s</tt:Name>
<tt:UseCount>%d</tt:UseCount>
<tt:AnalyticsEngineConfiguration>
<tt:AnalyticsModule Name="%s" Type="%s">
<tt:Parameters>
<tt:SimpleItem Name="%s" Value="%s"></tt:SimpleItem>
</tt:Parameters>
</tt:AnalyticsModule>
</tt:AnalyticsEngineConfiguration>
<tt:RuleEngineConfiguration>
<tt:Rule Name="%s" Type="%s">
<tt:Parameters>
<tt:SimpleItem Name="%s" Value="%s"></tt:SimpleItem>
</tt:Parameters>
</tt:Rule>
</tt:RuleEngineConfiguration>
</tms:Configurations>
</tms:GetAnalyticsConfigurationsResponse>
`, configToken, configName, useCount, analyticsModuleName, analyticsModuleType, analyticsModuleItemName, analyticsModuleItemValue,
ruleName, ruleType, ruleItemName, ruleItemValue)
response := &GetAnalyticsConfigurationsResponse{}
err := xml.Unmarshal([]byte(responseData), response)
require.NoError(t, err)
assert.Equal(t, response.Configurations[0].Token, configToken)
assert.Equal(t, response.Configurations[0].Name, configName)
assert.Equal(t, response.Configurations[0].AnalyticsEngineConfiguration.AnalyticsModule[0].Name, analyticsModuleName)
assert.Equal(t, response.Configurations[0].AnalyticsEngineConfiguration.AnalyticsModule[0].Type, analyticsModuleType)
assert.Equal(t, response.Configurations[0].AnalyticsEngineConfiguration.AnalyticsModule[0].Parameters.SimpleItem[0].Name, analyticsModuleItemName)
assert.Equal(t, response.Configurations[0].AnalyticsEngineConfiguration.AnalyticsModule[0].Parameters.SimpleItem[0].Value, analyticsModuleItemValue)
assert.Equal(t, response.Configurations[0].RuleEngineConfiguration.Rule[0].Name, ruleName)
assert.Equal(t, response.Configurations[0].RuleEngineConfiguration.Rule[0].Type, ruleType)
assert.Equal(t, response.Configurations[0].RuleEngineConfiguration.Rule[0].Parameters.SimpleItem[0].Name, ruleItemName)
assert.Equal(t, response.Configurations[0].RuleEngineConfiguration.Rule[0].Parameters.SimpleItem[0].Value, ruleItemValue)
}
func TestMarshalAddConfigurationRequest(t *testing.T) {
analyticsType := xsd.String("Analytics")
analyticsToken := xsd.String("AnalyticsToken")
request := AddConfiguration{
ProfileToken: "profile_1",
Configuration: []Configuration{
{
Type: &analyticsType,
Token: &analyticsToken,
},
},
}
expected := fmt.Sprintf("<tr2:AddConfiguration><tr2:ProfileToken>%s</tr2:ProfileToken><tr2:Configuration><tr2:Type>%s</tr2:Type><tr2:Token>%s</tr2:Token></tr2:Configuration></tr2:AddConfiguration>",
request.ProfileToken, *request.Configuration[0].Type, *request.Configuration[0].Token)
data, err := xml.Marshal(request)
require.NoError(t, err)
assert.Equal(t, expected, string(data))
}
func TestMarshalRemoveConfigurationRequest(t *testing.T) {
analyticsType := xsd.String("Analytics")
analyticsToken := xsd.String("AnalyticsToken")
request := RemoveConfiguration{
ProfileToken: "profile_1",
Configuration: []Configuration{
{
Type: &analyticsType,
Token: &analyticsToken,
},
},
}
expected := fmt.Sprintf("<tr2:RemoveConfiguration><tr2:ProfileToken>%s</tr2:ProfileToken><tr2:Configuration><tr2:Type>%s</tr2:Type><tr2:Token>%s</tr2:Token></tr2:Configuration></tr2:RemoveConfiguration>",
request.ProfileToken, *request.Configuration[0].Type, *request.Configuration[0].Token)
data, err := xml.Marshal(request)
require.NoError(t, err)
assert.Equal(t, expected, string(data))
}

298
names.go Normal file
View File

@@ -0,0 +1,298 @@
// -*- Mode: Go; indent-tabs-mode: t -*-
//
// Copyright (C) 2022 Intel Corporation
//
// SPDX-License-Identifier: Apache-2.0
// Code generated by gen_commands.py DO NOT EDIT.
package onvif
// Onvif WebService
const (
AnalyticsWebService = "Analytics"
DeviceWebService = "Device"
EventWebService = "Event"
ImagingWebService = "Imaging"
MediaWebService = "Media"
Media2WebService = "Media2"
PTZWebService = "PTZ"
RecordingWebService = "Recording"
)
// WebService - Analytics
const (
CreateAnalyticsModules = "CreateAnalyticsModules"
CreateRules = "CreateRules"
DeleteAnalyticsModules = "DeleteAnalyticsModules"
DeleteRules = "DeleteRules"
GetAnalyticsModuleOptions = "GetAnalyticsModuleOptions"
GetAnalyticsModules = "GetAnalyticsModules"
GetRuleOptions = "GetRuleOptions"
GetRules = "GetRules"
GetSupportedAnalyticsModules = "GetSupportedAnalyticsModules"
GetSupportedRules = "GetSupportedRules"
ModifyAnalyticsModules = "ModifyAnalyticsModules"
ModifyRules = "ModifyRules"
)
// WebService - Device
const (
AddIPAddressFilter = "AddIPAddressFilter"
AddScopes = "AddScopes"
CreateCertificate = "CreateCertificate"
CreateDot1XConfiguration = "CreateDot1XConfiguration"
CreateStorageConfiguration = "CreateStorageConfiguration"
CreateUsers = "CreateUsers"
DeleteCertificates = "DeleteCertificates"
DeleteDot1XConfiguration = "DeleteDot1XConfiguration"
DeleteGeoLocation = "DeleteGeoLocation"
DeleteStorageConfiguration = "DeleteStorageConfiguration"
DeleteUsers = "DeleteUsers"
GetAccessPolicy = "GetAccessPolicy"
GetCACertificates = "GetCACertificates"
GetCapabilities = "GetCapabilities"
GetCertificateInformation = "GetCertificateInformation"
GetCertificates = "GetCertificates"
GetCertificatesStatus = "GetCertificatesStatus"
GetClientCertificateMode = "GetClientCertificateMode"
GetDNS = "GetDNS"
GetDPAddresses = "GetDPAddresses"
GetDeviceInformation = "GetDeviceInformation"
GetDiscoveryMode = "GetDiscoveryMode"
GetDot11Capabilities = "GetDot11Capabilities"
GetDot11Status = "GetDot11Status"
GetDot1XConfiguration = "GetDot1XConfiguration"
GetDot1XConfigurations = "GetDot1XConfigurations"
GetDynamicDNS = "GetDynamicDNS"
GetEndpointReference = "GetEndpointReference"
GetGeoLocation = "GetGeoLocation"
GetHostname = "GetHostname"
GetIPAddressFilter = "GetIPAddressFilter"
GetNTP = "GetNTP"
GetNetworkDefaultGateway = "GetNetworkDefaultGateway"
GetNetworkInterfaces = "GetNetworkInterfaces"
GetNetworkProtocols = "GetNetworkProtocols"
GetPkcs10Request = "GetPkcs10Request"
GetRelayOutputs = "GetRelayOutputs"
GetDigitalInputs = "GetDigitalInputs"
GetRemoteDiscoveryMode = "GetRemoteDiscoveryMode"
GetRemoteUser = "GetRemoteUser"
GetScopes = "GetScopes"
GetServiceCapabilities = "GetServiceCapabilities"
GetServices = "GetServices"
GetStorageConfiguration = "GetStorageConfiguration"
GetStorageConfigurations = "GetStorageConfigurations"
GetSystemBackup = "GetSystemBackup"
GetSystemDateAndTime = "GetSystemDateAndTime"
GetSystemLog = "GetSystemLog"
GetSystemSupportInformation = "GetSystemSupportInformation"
GetSystemUris = "GetSystemUris"
GetUsers = "GetUsers"
GetWsdlUrl = "GetWsdlUrl"
GetZeroConfiguration = "GetZeroConfiguration"
LoadCACertificates = "LoadCACertificates"
LoadCertificateWithPrivateKey = "LoadCertificateWithPrivateKey"
LoadCertificates = "LoadCertificates"
RemoveIPAddressFilter = "RemoveIPAddressFilter"
RemoveScopes = "RemoveScopes"
RestoreSystem = "RestoreSystem"
ScanAvailableDot11Networks = "ScanAvailableDot11Networks"
SendAuxiliaryCommand = "SendAuxiliaryCommand"
SetAccessPolicy = "SetAccessPolicy"
SetCertificatesStatus = "SetCertificatesStatus"
SetClientCertificateMode = "SetClientCertificateMode"
SetDNS = "SetDNS"
SetDPAddresses = "SetDPAddresses"
SetDiscoveryMode = "SetDiscoveryMode"
SetDot1XConfiguration = "SetDot1XConfiguration"
SetDynamicDNS = "SetDynamicDNS"
SetGeoLocation = "SetGeoLocation"
SetHostname = "SetHostname"
SetHostnameFromDHCP = "SetHostnameFromDHCP"
SetIPAddressFilter = "SetIPAddressFilter"
SetNTP = "SetNTP"
SetNetworkDefaultGateway = "SetNetworkDefaultGateway"
SetNetworkInterfaces = "SetNetworkInterfaces"
SetNetworkProtocols = "SetNetworkProtocols"
SetRelayOutputSettings = "SetRelayOutputSettings"
SetRelayOutputState = "SetRelayOutputState"
SetRemoteDiscoveryMode = "SetRemoteDiscoveryMode"
SetRemoteUser = "SetRemoteUser"
SetScopes = "SetScopes"
SetStorageConfiguration = "SetStorageConfiguration"
SetSystemDateAndTime = "SetSystemDateAndTime"
SetSystemFactoryDefault = "SetSystemFactoryDefault"
SetUser = "SetUser"
SetZeroConfiguration = "SetZeroConfiguration"
StartFirmwareUpgrade = "StartFirmwareUpgrade"
StartSystemRestore = "StartSystemRestore"
SystemReboot = "SystemReboot"
UpgradeSystemFirmware = "UpgradeSystemFirmware"
)
// WebService - Event
const (
CreatePullPointSubscription = "CreatePullPointSubscription"
GetEventProperties = "GetEventProperties"
PullMessages = "PullMessages"
Renew = "Renew"
Seek = "Seek"
SetSynchronizationPoint = "SetSynchronizationPoint"
Subscribe = "Subscribe"
SubscriptionReference = "SubscriptionReference"
Unsubscribe = "Unsubscribe"
)
// WebService - Imaging
const (
GetCurrentPreset = "GetCurrentPreset"
GetImagingSettings = "GetImagingSettings"
GetMoveOptions = "GetMoveOptions"
GetOptions = "GetOptions"
GetPresets = "GetPresets"
GetStatus = "GetStatus"
Move = "Move"
SetCurrentPreset = "SetCurrentPreset"
SetImagingSettings = "SetImagingSettings"
Stop = "Stop"
)
// WebService - Media
const (
AddAudioDecoderConfiguration = "AddAudioDecoderConfiguration"
AddAudioEncoderConfiguration = "AddAudioEncoderConfiguration"
AddAudioOutputConfiguration = "AddAudioOutputConfiguration"
AddAudioSourceConfiguration = "AddAudioSourceConfiguration"
AddMetadataConfiguration = "AddMetadataConfiguration"
AddPTZConfiguration = "AddPTZConfiguration"
AddVideoAnalyticsConfiguration = "AddVideoAnalyticsConfiguration"
AddVideoEncoderConfiguration = "AddVideoEncoderConfiguration"
AddVideoSourceConfiguration = "AddVideoSourceConfiguration"
CreateOSD = "CreateOSD"
CreateProfile = "CreateProfile"
DeleteOSD = "DeleteOSD"
DeleteProfile = "DeleteProfile"
GetAudioDecoderConfiguration = "GetAudioDecoderConfiguration"
GetAudioDecoderConfigurationOptions = "GetAudioDecoderConfigurationOptions"
GetAudioDecoderConfigurations = "GetAudioDecoderConfigurations"
GetAudioEncoderConfiguration = "GetAudioEncoderConfiguration"
GetAudioEncoderConfigurationOptions = "GetAudioEncoderConfigurationOptions"
GetAudioEncoderConfigurations = "GetAudioEncoderConfigurations"
GetAudioOutputConfiguration = "GetAudioOutputConfiguration"
GetAudioOutputConfigurationOptions = "GetAudioOutputConfigurationOptions"
GetAudioOutputConfigurations = "GetAudioOutputConfigurations"
GetAudioOutputs = "GetAudioOutputs"
GetAudioSourceConfiguration = "GetAudioSourceConfiguration"
GetAudioSourceConfigurationOptions = "GetAudioSourceConfigurationOptions"
GetAudioSourceConfigurations = "GetAudioSourceConfigurations"
GetAudioSources = "GetAudioSources"
GetCompatibleAudioDecoderConfigurations = "GetCompatibleAudioDecoderConfigurations"
GetCompatibleAudioEncoderConfigurations = "GetCompatibleAudioEncoderConfigurations"
GetCompatibleAudioOutputConfigurations = "GetCompatibleAudioOutputConfigurations"
GetCompatibleAudioSourceConfigurations = "GetCompatibleAudioSourceConfigurations"
GetCompatibleMetadataConfigurations = "GetCompatibleMetadataConfigurations"
GetCompatibleVideoAnalyticsConfigurations = "GetCompatibleVideoAnalyticsConfigurations"
GetCompatibleVideoEncoderConfigurations = "GetCompatibleVideoEncoderConfigurations"
GetCompatibleVideoSourceConfigurations = "GetCompatibleVideoSourceConfigurations"
GetGuaranteedNumberOfVideoEncoderInstances = "GetGuaranteedNumberOfVideoEncoderInstances"
GetMetadataConfiguration = "GetMetadataConfiguration"
GetMetadataConfigurationOptions = "GetMetadataConfigurationOptions"
GetMetadataConfigurations = "GetMetadataConfigurations"
GetOSD = "GetOSD"
GetOSDOptions = "GetOSDOptions"
GetOSDs = "GetOSDs"
GetProfile = "GetProfile"
GetProfiles = "GetProfiles"
GetSnapshotUri = "GetSnapshotUri"
GetStreamUri = "GetStreamUri"
GetVideoAnalyticsConfiguration = "GetVideoAnalyticsConfiguration"
GetVideoAnalyticsConfigurations = "GetVideoAnalyticsConfigurations"
GetVideoEncoderConfiguration = "GetVideoEncoderConfiguration"
GetVideoEncoderConfigurationOptions = "GetVideoEncoderConfigurationOptions"
GetVideoEncoderConfigurations = "GetVideoEncoderConfigurations"
GetVideoSourceConfiguration = "GetVideoSourceConfiguration"
GetVideoSourceConfigurationOptions = "GetVideoSourceConfigurationOptions"
GetVideoSourceConfigurations = "GetVideoSourceConfigurations"
GetVideoSourceModes = "GetVideoSourceModes"
GetVideoSources = "GetVideoSources"
RemoveAudioDecoderConfiguration = "RemoveAudioDecoderConfiguration"
RemoveAudioEncoderConfiguration = "RemoveAudioEncoderConfiguration"
RemoveAudioOutputConfiguration = "RemoveAudioOutputConfiguration"
RemoveAudioSourceConfiguration = "RemoveAudioSourceConfiguration"
RemoveMetadataConfiguration = "RemoveMetadataConfiguration"
RemovePTZConfiguration = "RemovePTZConfiguration"
RemoveVideoAnalyticsConfiguration = "RemoveVideoAnalyticsConfiguration"
RemoveVideoEncoderConfiguration = "RemoveVideoEncoderConfiguration"
RemoveVideoSourceConfiguration = "RemoveVideoSourceConfiguration"
SetAudioDecoderConfiguration = "SetAudioDecoderConfiguration"
SetAudioEncoderConfiguration = "SetAudioEncoderConfiguration"
SetAudioOutputConfiguration = "SetAudioOutputConfiguration"
SetAudioSourceConfiguration = "SetAudioSourceConfiguration"
SetMetadataConfiguration = "SetMetadataConfiguration"
SetOSD = "SetOSD"
SetVideoAnalyticsConfiguration = "SetVideoAnalyticsConfiguration"
SetVideoEncoderConfiguration = "SetVideoEncoderConfiguration"
SetVideoSourceConfiguration = "SetVideoSourceConfiguration"
SetVideoSourceMode = "SetVideoSourceMode"
StartMulticastStreaming = "StartMulticastStreaming"
StopMulticastStreaming = "StopMulticastStreaming"
)
// WebService - Media2
const (
AddConfiguration = "AddConfiguration"
GetAnalyticsConfigurations = "GetAnalyticsConfigurations"
RemoveConfiguration = "RemoveConfiguration"
)
// WebService - PTZ
const (
AbsoluteMove = "AbsoluteMove"
ContinuousMove = "ContinuousMove"
CreatePresetTour = "CreatePresetTour"
GeoMove = "GeoMove"
GetCompatibleConfigurations = "GetCompatibleConfigurations"
GetConfiguration = "GetConfiguration"
GetConfigurationOptions = "GetConfigurationOptions"
GetConfigurations = "GetConfigurations"
GetNode = "GetNode"
GetNodes = "GetNodes"
GetPresetTour = "GetPresetTour"
GetPresetTourOptions = "GetPresetTourOptions"
GetPresetTours = "GetPresetTours"
GotoHomePosition = "GotoHomePosition"
GotoPreset = "GotoPreset"
ModifyPresetTour = "ModifyPresetTour"
OperatePresetTour = "OperatePresetTour"
RelativeMove = "RelativeMove"
RemovePreset = "RemovePreset"
RemovePresetTour = "RemovePresetTour"
SetConfiguration = "SetConfiguration"
SetHomePosition = "SetHomePosition"
SetPreset = "SetPreset"
)
// WebService - Recording
const (
CreateRecording = "CreateRecording"
CreateRecordingJob = "CreateRecordingJob"
CreateTrack = "CreateTrack"
DeleteRecording = "DeleteRecording"
DeleteRecordingJob = "DeleteRecordingJob"
DeleteTrack = "DeleteTrack"
ExportRecordedData = "ExportRecordedData"
GetExportRecordedDataState = "GetExportRecordedDataState"
GetRecordingConfiguration = "GetRecordingConfiguration"
GetRecordingJobConfiguration = "GetRecordingJobConfiguration"
GetRecordingJobState = "GetRecordingJobState"
GetRecordingJobs = "GetRecordingJobs"
GetRecordingOptions = "GetRecordingOptions"
GetRecordings = "GetRecordings"
GetTrackConfiguration = "GetTrackConfiguration"
SetRecordingConfiguration = "SetRecordingConfiguration"
SetRecordingJobConfiguration = "SetRecordingJobConfiguration"
SetRecordingJobMode = "SetRecordingJobMode"
SetTrackConfiguration = "SetTrackConfiguration"
StopExportRecordedData = "StopExportRecordedData"
)

View File

@@ -1,17 +1,91 @@
package networking
import (
"net/http"
"bytes"
"fmt"
"io"
"net/http"
"github.com/beevik/etree"
"github.com/icholy/digest"
"github.com/juju/errors"
)
func SendSoap(endpoint, message string) (*http.Response, error) {
httpClient := new(http.Client)
// SendSoap send soap message
func SendSoap(httpClient *http.Client, endpoint, message string) (*http.Response, error) {
resp, err := httpClient.Post(endpoint, "application/soap+xml; charset=utf-8", bytes.NewBufferString(message))
if err != nil {
return resp, errors.Annotate(err, "Post")
}
// if resp.StatusCode is 4xx,5xx, return error
if resp.StatusCode >= 400 && resp.StatusCode < 600 {
return resp, errors.Errorf("Server error: %d: %s", resp.StatusCode, resp.Status)
}
return resp, nil
}
func SendSoapWithDigest(httpClient *http.Client, endpoint, message, username, password string) (*http.Response, error) {
doc := etree.NewDocument()
if err := doc.ReadFromString(message); err != nil {
return nil, err
}
e := doc.FindElement("./Envelope/Header/Security")
if e != nil {
bodyTag := doc.Root().SelectElement("Header")
bodyTag.RemoveChild(e)
data, err := doc.WriteToString()
if err != nil {
return nil, err
}
message = data
}
req, err := http.NewRequest("POST", endpoint, bytes.NewBufferString(message))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/soap+xml; charset=utf-8")
resp, err := httpClient.Do(req)
if err != nil {
return resp, errors.Annotate(err, "Post with digest")
}
if resp.StatusCode != http.StatusUnauthorized {
return resp, err
}
return resp,nil
}
wwwAuth := resp.Header.Get("WWW-Authenticate")
chal, err := digest.ParseChallenge(wwwAuth)
if err != nil {
return resp, fmt.Errorf("fail to parse challenge: %w", err)
}
cred, err := digest.Digest(chal, digest.Options{
Method: "POST",
URI: req.URL.RequestURI(),
Username: username,
Password: password,
})
if err != nil {
return resp, fmt.Errorf("fail to build digest: %w", err)
}
// Readout body to close the connection
resp.Body.Close()
req.Header.Add("Authorization", cred.String())
req.Body = io.NopCloser((bytes.NewBufferString(message)))
resp, err = httpClient.Do(req)
if err != nil {
return nil, errors.Annotate(err, "Post with digest")
}
if resp.StatusCode >= 400 && resp.StatusCode < 600 {
return resp, errors.Errorf("Post with digest error: %d: %s", resp.StatusCode, resp.Status)
}
return resp, nil
}

261
ptz/function.go Normal file
View File

@@ -0,0 +1,261 @@
// -*- Mode: Go; indent-tabs-mode: t -*-
//
// Copyright (C) 2022 Intel Corporation
//
// SPDX-License-Identifier: Apache-2.0
// Code generated by gen_commands.py DO NOT EDIT.
package ptz
type AbsoluteMoveFunction struct{}
func (_ *AbsoluteMoveFunction) Request() interface{} {
return &AbsoluteMove{}
}
func (_ *AbsoluteMoveFunction) Response() interface{} {
return &AbsoluteMoveResponse{}
}
type ContinuousMoveFunction struct{}
func (_ *ContinuousMoveFunction) Request() interface{} {
return &ContinuousMove{}
}
func (_ *ContinuousMoveFunction) Response() interface{} {
return &ContinuousMoveResponse{}
}
type CreatePresetTourFunction struct{}
func (_ *CreatePresetTourFunction) Request() interface{} {
return &CreatePresetTour{}
}
func (_ *CreatePresetTourFunction) Response() interface{} {
return &CreatePresetTourResponse{}
}
type GeoMoveFunction struct{}
func (_ *GeoMoveFunction) Request() interface{} {
return &GeoMove{}
}
func (_ *GeoMoveFunction) Response() interface{} {
return &GeoMoveResponse{}
}
type GetCompatibleConfigurationsFunction struct{}
func (_ *GetCompatibleConfigurationsFunction) Request() interface{} {
return &GetCompatibleConfigurations{}
}
func (_ *GetCompatibleConfigurationsFunction) Response() interface{} {
return &GetCompatibleConfigurationsResponse{}
}
type GetConfigurationFunction struct{}
func (_ *GetConfigurationFunction) Request() interface{} {
return &GetConfiguration{}
}
func (_ *GetConfigurationFunction) Response() interface{} {
return &GetConfigurationResponse{}
}
type GetConfigurationOptionsFunction struct{}
func (_ *GetConfigurationOptionsFunction) Request() interface{} {
return &GetConfigurationOptions{}
}
func (_ *GetConfigurationOptionsFunction) Response() interface{} {
return &GetConfigurationOptionsResponse{}
}
type GetConfigurationsFunction struct{}
func (_ *GetConfigurationsFunction) Request() interface{} {
return &GetConfigurations{}
}
func (_ *GetConfigurationsFunction) Response() interface{} {
return &GetConfigurationsResponse{}
}
type GetNodeFunction struct{}
func (_ *GetNodeFunction) Request() interface{} {
return &GetNode{}
}
func (_ *GetNodeFunction) Response() interface{} {
return &GetNodeResponse{}
}
type GetNodesFunction struct{}
func (_ *GetNodesFunction) Request() interface{} {
return &GetNodes{}
}
func (_ *GetNodesFunction) Response() interface{} {
return &GetNodesResponse{}
}
type GetPresetTourFunction struct{}
func (_ *GetPresetTourFunction) Request() interface{} {
return &GetPresetTour{}
}
func (_ *GetPresetTourFunction) Response() interface{} {
return &GetPresetTourResponse{}
}
type GetPresetTourOptionsFunction struct{}
func (_ *GetPresetTourOptionsFunction) Request() interface{} {
return &GetPresetTourOptions{}
}
func (_ *GetPresetTourOptionsFunction) Response() interface{} {
return &GetPresetTourOptionsResponse{}
}
type GetPresetToursFunction struct{}
func (_ *GetPresetToursFunction) Request() interface{} {
return &GetPresetTours{}
}
func (_ *GetPresetToursFunction) Response() interface{} {
return &GetPresetToursResponse{}
}
type GetPresetsFunction struct{}
func (_ *GetPresetsFunction) Request() interface{} {
return &GetPresets{}
}
func (_ *GetPresetsFunction) Response() interface{} {
return &GetPresetsResponse{}
}
type GetServiceCapabilitiesFunction struct{}
func (_ *GetServiceCapabilitiesFunction) Request() interface{} {
return &GetServiceCapabilities{}
}
func (_ *GetServiceCapabilitiesFunction) Response() interface{} {
return &GetServiceCapabilitiesResponse{}
}
type GetStatusFunction struct{}
func (_ *GetStatusFunction) Request() interface{} {
return &GetStatus{}
}
func (_ *GetStatusFunction) Response() interface{} {
return &GetStatusResponse{}
}
type GotoHomePositionFunction struct{}
func (_ *GotoHomePositionFunction) Request() interface{} {
return &GotoHomePosition{}
}
func (_ *GotoHomePositionFunction) Response() interface{} {
return &GotoHomePositionResponse{}
}
type GotoPresetFunction struct{}
func (_ *GotoPresetFunction) Request() interface{} {
return &GotoPreset{}
}
func (_ *GotoPresetFunction) Response() interface{} {
return &GotoPresetResponse{}
}
type ModifyPresetTourFunction struct{}
func (_ *ModifyPresetTourFunction) Request() interface{} {
return &ModifyPresetTour{}
}
func (_ *ModifyPresetTourFunction) Response() interface{} {
return &ModifyPresetTourResponse{}
}
type OperatePresetTourFunction struct{}
func (_ *OperatePresetTourFunction) Request() interface{} {
return &OperatePresetTour{}
}
func (_ *OperatePresetTourFunction) Response() interface{} {
return &OperatePresetTourResponse{}
}
type RelativeMoveFunction struct{}
func (_ *RelativeMoveFunction) Request() interface{} {
return &RelativeMove{}
}
func (_ *RelativeMoveFunction) Response() interface{} {
return &RelativeMoveResponse{}
}
type RemovePresetFunction struct{}
func (_ *RemovePresetFunction) Request() interface{} {
return &RemovePreset{}
}
func (_ *RemovePresetFunction) Response() interface{} {
return &RemovePresetResponse{}
}
type RemovePresetTourFunction struct{}
func (_ *RemovePresetTourFunction) Request() interface{} {
return &RemovePresetTour{}
}
func (_ *RemovePresetTourFunction) Response() interface{} {
return &RemovePresetTourResponse{}
}
type SendAuxiliaryCommandFunction struct{}
func (_ *SendAuxiliaryCommandFunction) Request() interface{} {
return &SendAuxiliaryCommand{}
}
func (_ *SendAuxiliaryCommandFunction) Response() interface{} {
return &SendAuxiliaryCommandResponse{}
}
type SetConfigurationFunction struct{}
func (_ *SetConfigurationFunction) Request() interface{} {
return &SetConfiguration{}
}
func (_ *SetConfigurationFunction) Response() interface{} {
return &SetConfigurationResponse{}
}
type SetHomePositionFunction struct{}
func (_ *SetHomePositionFunction) Request() interface{} {
return &SetHomePosition{}
}
func (_ *SetHomePositionFunction) Response() interface{} {
return &SetHomePositionResponse{}
}
type SetPresetFunction struct{}
func (_ *SetPresetFunction) Request() interface{} {
return &SetPreset{}
}
func (_ *SetPresetFunction) Response() interface{} {
return &SetPresetResponse{}
}
type StopFunction struct{}
func (_ *StopFunction) Request() interface{} {
return &Stop{}
}
func (_ *StopFunction) Response() interface{} {
return &StopResponse{}
}

View File

@@ -1,8 +1,10 @@
package ptz
//go:generate python3 ../python/gen_commands.py
import (
"github.com/use-go/onvif/xsd"
"github.com/use-go/onvif/xsd/onvif"
"github.com/kerberos-io/onvif/xsd"
"github.com/kerberos-io/onvif/xsd/onvif"
)
type Capabilities struct {
@@ -28,7 +30,7 @@ type GetNodes struct {
}
type GetNodesResponse struct {
PTZNode onvif.PTZNode
PTZNode []onvif.PTZNode
}
type GetNode struct {
@@ -41,8 +43,8 @@ type GetNodeResponse struct {
}
type GetConfiguration struct {
XMLName string `xml:"tptz:GetConfiguration"`
ProfileToken onvif.ReferenceToken `xml:"tptz:ProfileToken"`
XMLName string `xml:"tptz:GetConfiguration"`
PTZConfigurationToken onvif.ReferenceToken `xml:"tptz:PTZConfigurationToken"`
}
type GetConfigurationResponse struct {
@@ -54,7 +56,7 @@ type GetConfigurations struct {
}
type GetConfigurationsResponse struct {
PTZConfiguration onvif.PTZConfiguration
PTZConfiguration []onvif.PTZConfiguration
}
type SetConfiguration struct {
@@ -67,8 +69,8 @@ type SetConfigurationResponse struct {
}
type GetConfigurationOptions struct {
XMLName string `xml:"tptz:GetConfigurationOptions"`
ProfileToken onvif.ReferenceToken `xml:"tptz:ProfileToken"`
XMLName string `xml:"tptz:GetConfigurationOptions"`
ConfigurationToken onvif.ReferenceToken `xml:"tptz:ConfigurationToken"`
}
type GetConfigurationOptionsResponse struct {
@@ -91,14 +93,14 @@ type GetPresets struct {
}
type GetPresetsResponse struct {
Preset onvif.PTZPreset
Preset []onvif.PTZPreset
}
type SetPreset struct {
XMLName string `xml:"tptz:SetPreset"`
ProfileToken onvif.ReferenceToken `xml:"tptz:ProfileToken"`
PresetName xsd.String `xml:"tptz:PresetName"`
PresetToken onvif.ReferenceToken `xml:"tptz:PresetToken"`
XMLName string `xml:"tptz:SetPreset"`
ProfileToken *onvif.ReferenceToken `xml:"tptz:ProfileToken,omitempty"`
PresetName *xsd.String `xml:"tptz:PresetName,omitempty"`
PresetToken *onvif.ReferenceToken `xml:"tptz:PresetToken,omitempty"`
}
type SetPresetResponse struct {
@@ -115,19 +117,19 @@ type RemovePresetResponse struct {
}
type GotoPreset struct {
XMLName string `xml:"tptz:GotoPreset"`
ProfileToken onvif.ReferenceToken `xml:"tptz:ProfileToken"`
PresetToken onvif.ReferenceToken `xml:"tptz:PresetToken"`
Speed onvif.PTZSpeed `xml:"tptz:Speed"`
XMLName string `xml:"tptz:GotoPreset,omitempty"`
ProfileToken *onvif.ReferenceToken `xml:"tptz:ProfileToken,omitempty"`
PresetToken *onvif.ReferenceToken `xml:"tptz:PresetToken,omitempty"`
Speed *onvif.PTZSpeed `xml:"tptz:Speed,omitempty"`
}
type GotoPresetResponse struct {
}
type GotoHomePosition struct {
XMLName string `xml:"tptz:GotoHomePosition"`
ProfileToken onvif.ReferenceToken `xml:"tptz:ProfileToken"`
Speed onvif.PTZSpeed `xml:"tptz:Speed"`
XMLName string `xml:"tptz:GotoHomePosition"`
ProfileToken *onvif.ReferenceToken `xml:"tptz:ProfileToken,omitempty"`
Speed *onvif.PTZSpeed `xml:"tptz:Speed,omitempty"`
}
type GotoHomePositionResponse struct {
@@ -142,10 +144,10 @@ type SetHomePositionResponse struct {
}
type ContinuousMove struct {
XMLName string `xml:"tptz:ContinuousMove"`
ProfileToken onvif.ReferenceToken `xml:"tptz:ProfileToken"`
Velocity onvif.PTZSpeed `xml:"tptz:Velocity"`
Timeout xsd.Duration `xml:"tptz:Timeout"`
XMLName string `xml:"tptz:ContinuousMove"`
ProfileToken *onvif.ReferenceToken `xml:"tptz:ProfileToken,omitempty"`
Velocity onvif.PTZSpeed `xml:"tptz:Velocity,omitempty"`
Timeout *xsd.Duration `xml:"tptz:Timeout,omitempty"`
}
type ContinuousMoveResponse struct {
@@ -154,8 +156,8 @@ type ContinuousMoveResponse struct {
type RelativeMove struct {
XMLName string `xml:"tptz:RelativeMove"`
ProfileToken onvif.ReferenceToken `xml:"tptz:ProfileToken"`
Translation onvif.PTZVector `xml:"tptz:Translation"`
Speed onvif.PTZSpeed `xml:"tptz:Speed"`
Translation Vector `json:",omitempty" xml:"tptz:Translation,omitempty"`
Speed Speed `json:",omitempty" xml:"tptz:Speed,omitempty"`
}
type RelativeMoveResponse struct {
@@ -177,6 +179,16 @@ type AbsoluteMove struct {
Speed onvif.PTZSpeed `xml:"tptz:Speed"`
}
type Vector struct {
PanTilt *onvif.Vector2D `json:",omitempty" xml:"onvif:PanTilt,omitempty"`
Zoom *onvif.Vector1D `json:",omitempty" xml:"onvif:Zoom,omitempty"`
}
type Speed struct {
PanTilt *onvif.Vector2D `json:",omitempty" xml:"onvif:PanTilt,omitempty"`
Zoom *onvif.Vector1D `json:",omitempty" xml:"onvif:Zoom,omitempty"`
}
type AbsoluteMoveResponse struct {
}

11
python/Makefile Normal file
View File

@@ -0,0 +1,11 @@
# Copyright (C) 2022 Intel Corporation
#
# SPDX-License-Identifier: Apache-2.0
.PHONY: gen
gen:
python3 gen_commands.py
which go
go fmt ../...

149
python/gen_commands.py Executable file
View File

@@ -0,0 +1,149 @@
#!/usr/bin/env python3
import dataclasses
import pathlib
import re
import subprocess
# license header to use for generated go files
HEADER = '''\
// -*- Mode: Go; indent-tabs-mode: t -*-
//
// Copyright (C) 2022 Intel Corporation
//
// SPDX-License-Identifier: Apache-2.0
// Code generated by gen_commands.py DO NOT EDIT.
'''
BASE_MODULE_NAME = 'github.com/kerberos-io/onvif'
SERVICE_NAMES = [
'analytics',
'device',
'event',
'imaging',
'media',
'media2',
'ptz',
'recording',
]
@dataclasses.dataclass
class FunctionsGenerator:
service_name: str
input_file: pathlib.Path
output_file: pathlib.Path
commands = []
@staticmethod
def make_function(cmd):
return '''\
type %sFunction struct{}
func (_ *%sFunction) Request() interface{} {
\treturn &%s{}
}
func (_ *%sFunction) Response() interface{} {
\treturn &%sResponse{}
}
''' % (cmd, cmd, cmd, cmd, cmd)
def run(self):
self.commands = []
with open(self.input_file) as f:
with open(self.output_file, 'w') as w:
w.write(HEADER)
w.write(f'package {self.service_name}\n\n')
while line := f.readline():
if m := re.search(r'type ([^ ]+)Response struct', line):
cmd = m.group(1)
if cmd.endswith('Fault'):
continue # skip Fault responses
self.commands.append(cmd)
self.commands = sorted(self.commands)
for cmd in self.commands:
print(f'{self.service_name}.{cmd}')
w.write(FunctionsGenerator.make_function(cmd))
def write_func_map(self, w):
w.write('var %sFunctionMap = map[string]Function{\n' % self.proper_name)
for cmd in self.commands:
w.write('\t%s: &%s.%sFunction{},\n' % (cmd, self.service_name, cmd))
w.write('}\n\n')
@property
def proper_name(self):
return (self.service_name[0].upper() + self.service_name[1:]).replace('Ptz', 'PTZ')
@dataclasses.dataclass
class MainGenerator:
root_dir: pathlib.Path
generators = []
unique_cmds = set()
def _generate_mappings(self):
with open(self.root_dir.joinpath('mappings.go'), 'w') as w:
w.write(HEADER)
w.write('package onvif\n\n')
w.write('import (\n')
for service_name in SERVICE_NAMES:
w.write(f'\t"{BASE_MODULE_NAME}/{service_name}"\n')
w.write(')\n\n')
for generator in self.generators:
generator.write_func_map(w)
def _generate_names(self):
with open(self.root_dir.joinpath('names.go'), 'w') as w:
w.write(HEADER)
w.write('package onvif\n\n')
w.write('// Onvif WebService\n')
w.write('const (\n')
for gen in self.generators:
w.write(f'\t{gen.proper_name}WebService = "{gen.proper_name}"\n')
w.write(')\n\n')
for gen in self.generators:
w.write(f'// WebService - {gen.proper_name}\n')
w.write('const (\n')
for cmd in gen.commands:
if cmd not in self.unique_cmds:
w.write(f'\t{cmd} = "{cmd}"\n')
self.unique_cmds.add(cmd)
w.write(')\n\n')
def run(self):
for service_name in SERVICE_NAMES:
gen = FunctionsGenerator(service_name,
self.root_dir.joinpath(f'{service_name}/types.go'),
self.root_dir.joinpath(f'{service_name}/function.go'))
gen.run()
self.generators.append(gen)
self._generate_mappings()
self._generate_names()
def main():
root_dir = pathlib.Path(__file__).parent.parent.resolve()
main_gen = MainGenerator(root_dir)
main_gen.run()
print('\n\nFormatting generated files...')
try:
subprocess.check_call(['go', 'fmt', str(root_dir) + "/..."])
except OSError as e:
print(f"\n\033[31;1mError occurred while trying to format generated files: {e}\033[0m")
print("\033[33;1mPlease run 'go fmt ./...' manually to cleanup generated code formatting!\033[0m")
if __name__ == '__main__':
main()

198
recording/function.go Normal file
View File

@@ -0,0 +1,198 @@
// -*- Mode: Go; indent-tabs-mode: t -*-
//
// Copyright (C) 2022 Intel Corporation
//
// SPDX-License-Identifier: Apache-2.0
// Code generated by gen_commands.py DO NOT EDIT.
package recording
type CreateRecordingFunction struct{}
func (_ *CreateRecordingFunction) Request() interface{} {
return &CreateRecording{}
}
func (_ *CreateRecordingFunction) Response() interface{} {
return &CreateRecordingResponse{}
}
type CreateRecordingJobFunction struct{}
func (_ *CreateRecordingJobFunction) Request() interface{} {
return &CreateRecordingJob{}
}
func (_ *CreateRecordingJobFunction) Response() interface{} {
return &CreateRecordingJobResponse{}
}
type CreateTrackFunction struct{}
func (_ *CreateTrackFunction) Request() interface{} {
return &CreateTrack{}
}
func (_ *CreateTrackFunction) Response() interface{} {
return &CreateTrackResponse{}
}
type DeleteRecordingFunction struct{}
func (_ *DeleteRecordingFunction) Request() interface{} {
return &DeleteRecording{}
}
func (_ *DeleteRecordingFunction) Response() interface{} {
return &DeleteRecordingResponse{}
}
type DeleteRecordingJobFunction struct{}
func (_ *DeleteRecordingJobFunction) Request() interface{} {
return &DeleteRecordingJob{}
}
func (_ *DeleteRecordingJobFunction) Response() interface{} {
return &DeleteRecordingJobResponse{}
}
type DeleteTrackFunction struct{}
func (_ *DeleteTrackFunction) Request() interface{} {
return &DeleteTrack{}
}
func (_ *DeleteTrackFunction) Response() interface{} {
return &DeleteTrackResponse{}
}
type ExportRecordedDataFunction struct{}
func (_ *ExportRecordedDataFunction) Request() interface{} {
return &ExportRecordedData{}
}
func (_ *ExportRecordedDataFunction) Response() interface{} {
return &ExportRecordedDataResponse{}
}
type GetExportRecordedDataStateFunction struct{}
func (_ *GetExportRecordedDataStateFunction) Request() interface{} {
return &GetExportRecordedDataState{}
}
func (_ *GetExportRecordedDataStateFunction) Response() interface{} {
return &GetExportRecordedDataStateResponse{}
}
type GetRecordingConfigurationFunction struct{}
func (_ *GetRecordingConfigurationFunction) Request() interface{} {
return &GetRecordingConfiguration{}
}
func (_ *GetRecordingConfigurationFunction) Response() interface{} {
return &GetRecordingConfigurationResponse{}
}
type GetRecordingJobConfigurationFunction struct{}
func (_ *GetRecordingJobConfigurationFunction) Request() interface{} {
return &GetRecordingJobConfiguration{}
}
func (_ *GetRecordingJobConfigurationFunction) Response() interface{} {
return &GetRecordingJobConfigurationResponse{}
}
type GetRecordingJobStateFunction struct{}
func (_ *GetRecordingJobStateFunction) Request() interface{} {
return &GetRecordingJobState{}
}
func (_ *GetRecordingJobStateFunction) Response() interface{} {
return &GetRecordingJobStateResponse{}
}
type GetRecordingJobsFunction struct{}
func (_ *GetRecordingJobsFunction) Request() interface{} {
return &GetRecordingJobs{}
}
func (_ *GetRecordingJobsFunction) Response() interface{} {
return &GetRecordingJobsResponse{}
}
type GetRecordingOptionsFunction struct{}
func (_ *GetRecordingOptionsFunction) Request() interface{} {
return &GetRecordingOptions{}
}
func (_ *GetRecordingOptionsFunction) Response() interface{} {
return &GetRecordingOptionsResponse{}
}
type GetRecordingsFunction struct{}
func (_ *GetRecordingsFunction) Request() interface{} {
return &GetRecordings{}
}
func (_ *GetRecordingsFunction) Response() interface{} {
return &GetRecordingsResponse{}
}
type GetServiceCapabilitiesFunction struct{}
func (_ *GetServiceCapabilitiesFunction) Request() interface{} {
return &GetServiceCapabilities{}
}
func (_ *GetServiceCapabilitiesFunction) Response() interface{} {
return &GetServiceCapabilitiesResponse{}
}
type GetTrackConfigurationFunction struct{}
func (_ *GetTrackConfigurationFunction) Request() interface{} {
return &GetTrackConfiguration{}
}
func (_ *GetTrackConfigurationFunction) Response() interface{} {
return &GetTrackConfigurationResponse{}
}
type SetRecordingConfigurationFunction struct{}
func (_ *SetRecordingConfigurationFunction) Request() interface{} {
return &SetRecordingConfiguration{}
}
func (_ *SetRecordingConfigurationFunction) Response() interface{} {
return &SetRecordingConfigurationResponse{}
}
type SetRecordingJobConfigurationFunction struct{}
func (_ *SetRecordingJobConfigurationFunction) Request() interface{} {
return &SetRecordingJobConfiguration{}
}
func (_ *SetRecordingJobConfigurationFunction) Response() interface{} {
return &SetRecordingJobConfigurationResponse{}
}
type SetRecordingJobModeFunction struct{}
func (_ *SetRecordingJobModeFunction) Request() interface{} {
return &SetRecordingJobMode{}
}
func (_ *SetRecordingJobModeFunction) Response() interface{} {
return &SetRecordingJobModeResponse{}
}
type SetTrackConfigurationFunction struct{}
func (_ *SetTrackConfigurationFunction) Request() interface{} {
return &SetTrackConfiguration{}
}
func (_ *SetTrackConfigurationFunction) Response() interface{} {
return &SetTrackConfigurationResponse{}
}
type StopExportRecordedDataFunction struct{}
func (_ *StopExportRecordedDataFunction) Request() interface{} {
return &StopExportRecordedData{}
}
func (_ *StopExportRecordedDataFunction) Response() interface{} {
return &StopExportRecordedDataResponse{}
}

793
recording/types.go Normal file
View File

@@ -0,0 +1,793 @@
package recording
import (
"encoding/xml"
"github.com/kerberos-io/onvif/xsd"
"github.com/kerberos-io/onvif/xsd/onvif"
)
// TrackType type
type TrackType string
const (
// TrackTypeVideo const
TrackTypeVideo TrackType = "Video"
// TrackTypeAudio const
TrackTypeAudio TrackType = "Audio"
// TrackTypeMetadata const
TrackTypeMetadata TrackType = "Metadata"
// Placeholder for future extension.
// TrackTypeExtended const
TrackTypeExtended TrackType = "Extended"
)
// EncodingTypes type
type EncodingTypes []string
// GetServiceCapabilities type
type GetServiceCapabilities struct {
XMLName xml.Name `xml:"tt:GetServiceCapabilities"`
}
// GetServiceCapabilitiesResponse type
type GetServiceCapabilitiesResponse struct {
XMLName xml.Name `xml:"GetServiceCapabilitiesResponse"`
// The capabilities for the recording service is returned in the Capabilities element.
Capabilities Capabilities `xml:"Capabilities,omitempty"`
}
// CreateRecording type
type CreateRecording struct {
XMLName xml.Name `xml:"tt:CreateRecording"`
// Initial configuration for the recording.
RecordingConfiguration RecordingConfiguration `xml:"tt:RecordingConfiguration,omitempty"`
}
// RecordingConfiguration type
type RecordingConfiguration struct {
// Information about the source of the recording.
Source RecordingSourceInformation `xml:"tt:Source,omitempty"`
// Informative description of the source.
Content onvif.Description `xml:"tt:Content,omitempty"`
// Sspecifies the maximum time that data in any track within the
// recording shall be stored. The device shall delete any data older than the maximum retention
// time. Such data shall not be accessible anymore. If the MaximumRetentionPeriod is set to 0,
// the device shall not limit the retention time of stored data, except by resource constraints.
// Whatever the value of MaximumRetentionTime, the device may automatically delete
// recordings to free up storage space for new recordings.
MaximumRetentionTime xsd.Duration `xml:"tt:MaximumRetentionTime,omitempty"`
}
// RecordingSourceInformation type
type RecordingSourceInformation struct {
//
// Identifier for the source chosen by the client that creates the structure.
// This identifier is opaque to the device. Clients may use any type of URI for this field. A device shall support at least 128 characters.
SourceId xsd.AnyURI `xml:"tt:SourceId,omitempty"`
// Informative user readable name of the source, e.g. "Camera23". A device shall support at least 20 characters.
Name xsd.Name `xml:"tt:Name,omitempty"`
// Informative description of the physical location of the source, e.g. the coordinates on a map.
Location onvif.Description `xml:"tt:Location,omitempty"`
// Informative description of the source.
Description onvif.Description `xml:"tt:Description,omitempty"`
// URI provided by the service supplying data to be recorded. A device shall support at least 128 characters.
Address xsd.AnyURI `xml:"tt:Address,omitempty"`
}
// CreateRecordingResponse type
type CreateRecordingResponse struct {
XMLName xml.Name `xml:"CreateRecordingResponse"`
// The reference to the created recording.
RecordingToken RecordingReference `xml:"RecordingToken,omitempty"`
}
// DeleteRecording type
type DeleteRecording struct {
XMLName xml.Name `xml:"tt:DeleteRecording"`
// The reference of the recording to be deleted.
RecordingToken RecordingReference `xml:"tt:RecordingToken,omitempty"`
}
// DeleteRecordingResponse type
type DeleteRecordingResponse struct {
XMLName xml.Name `xml:"DeleteRecordingResponse"`
}
// GetRecordings type
type GetRecordings struct {
XMLName xml.Name `xml:"tt:GetRecordings"`
}
// GetRecordingsResponse type
type GetRecordingsResponse struct {
XMLName xml.Name `xml:"GetRecordingsResponse"`
// List of recording items.
RecordingItem []GetRecordingsResponseItem
}
// GetRecordingsResponseItem type
type GetRecordingsResponseItem struct {
// Token of the recording.
RecordingToken RecordingReference
// Configuration of the recording.
Configuration struct {
Source struct {
SourceId xsd.AnyURI
Name xsd.Name
Location xsd.String
Description xsd.String
Address xsd.AnyURI
}
Content xsd.String
MaximumRetentionTime xsd.Duration
}
// List of tracks.
Tracks GetTracksResponseList
}
// GetTracksResponseList type
type GetTracksResponseList struct {
// Configuration of a track.
Track []GetTracksResponseItem
}
// GetTracksResponseItem type
type GetTracksResponseItem struct {
// Token of the track.
TrackToken TrackReference
// Configuration of the track.
Configuration struct {
TrackType TrackType
Description xsd.String
}
}
// TrackConfiguration type
type TrackConfiguration struct {
// Type of the track. It shall be equal to the strings “Video”,
// “Audio” or “Metadata”. The track shall only be able to hold data of that type.
TrackType TrackType `xml:"tt:TrackType,omitempty"`
// Informative description of the track.
Description onvif.Description `xml:"tt:Description,omitempty"`
}
// SetRecordingConfiguration type
type SetRecordingConfiguration struct {
XMLName xml.Name `xml:"tt:SetRecordingConfiguration"`
// Token of the recording that shall be changed.
RecordingToken RecordingReference `xml:"tt:RecordingToken,omitempty"`
// The new configuration.
RecordingConfiguration RecordingConfiguration `xml:"tt:RecordingConfiguration,omitempty"`
}
// SetRecordingConfigurationResponse type
type SetRecordingConfigurationResponse struct {
XMLName xml.Name `xml:"SetRecordingConfigurationResponse"`
}
// GetRecordingConfiguration type
type GetRecordingConfiguration struct {
XMLName xml.Name `xml:"tt:GetRecordingConfiguration"`
// Token of the configuration to be retrieved.
RecordingToken RecordingReference `xml:"tt:RecordingToken,omitempty"`
}
// GetRecordingConfigurationResponse type
type GetRecordingConfigurationResponse struct {
XMLName xml.Name `xml:"GetRecordingConfigurationResponse"`
// Configuration of the recording.
RecordingConfiguration RecordingConfiguration `xml:"RecordingConfiguration,omitempty"`
}
// CreateTrack type
type CreateTrack struct {
XMLName xml.Name `xml:"tt:CreateTrack"`
// Identifies the recording to which a track shall be added.
RecordingToken RecordingReference `xml:"tt:RecordingToken,omitempty"`
// The configuration of the new track.
TrackConfiguration TrackConfiguration `xml:"tt:TrackConfiguration,omitempty"`
}
// CreateTrackResponse type
type CreateTrackResponse struct {
XMLName xml.Name `xml:"CreateTrackResponse"`
// The TrackToken shall identify the newly created track. The
// TrackToken shall be unique within the recoding to which
// the new track belongs.
TrackToken TrackReference `xml:"TrackToken,omitempty"`
}
// DeleteTrack type
type DeleteTrack struct {
XMLName xml.Name `xml:"tt:DeleteTrack"`
// Token of the recording the track belongs to.
RecordingToken RecordingReference `xml:"tt:RecordingToken,omitempty"`
// Token of the track to be deleted.
TrackToken TrackReference `xml:"tt:TrackToken,omitempty"`
}
// DeleteTrackResponse type
type DeleteTrackResponse struct {
XMLName xml.Name `xml:"DeleteTrackResponse"`
}
// GetTrackConfiguration type
type GetTrackConfiguration struct {
XMLName xml.Name `xml:"tt:GetTrackConfiguration"`
// Token of the recording the track belongs to.
RecordingToken RecordingReference `xml:"tt:RecordingToken,omitempty"`
// Token of the track.
TrackToken TrackReference `xml:"tt:TrackToken,omitempty"`
}
// GetTrackConfigurationResponse type
type GetTrackConfigurationResponse struct {
XMLName xml.Name `xml:"GetTrackConfigurationResponse"`
// Configuration of the track.
TrackConfiguration TrackConfiguration `xml:"TrackConfiguration,omitempty"`
}
// SetTrackConfiguration type
type SetTrackConfiguration struct {
XMLName xml.Name `xml:"tt:SetTrackConfiguration"`
// Token of the recording the track belongs to.
RecordingToken RecordingReference `xml:"tt:RecordingToken,omitempty"`
// Token of the track to be modified.
TrackToken TrackReference `xml:"tt:TrackToken,omitempty"`
// New configuration for the track.
TrackConfiguration TrackConfiguration `xml:"tt:TrackConfiguration,omitempty"`
}
// SetTrackConfigurationResponse type
type SetTrackConfigurationResponse struct {
XMLName xml.Name `xml:"SetTrackConfigurationResponse"`
}
// CreateRecordingJob type
type CreateRecordingJob struct {
XMLName xml.Name `xml:"tt:CreateRecordingJob"`
// The initial configuration of the new recording job.
JobConfiguration RecordingJobConfiguration `xml:"tt:JobConfiguration,omitempty"`
}
// CreateRecordingJobResponse type
type CreateRecordingJobResponse struct {
XMLName xml.Name `xml:"CreateRecordingJobResponse"`
// The JobToken shall identify the created recording job.
JobToken RecordingJobReference `xml:"JobToken,omitempty"`
//
// The JobConfiguration structure shall be the configuration as it is used by the device. This may be different from the
// JobConfiguration passed to CreateRecordingJob.
JobConfiguration RecordingJobConfiguration `xml:"JobConfiguration,omitempty"`
}
// RecordingJobReference type
type RecordingJobReference ReferenceToken
// RecordingJobConfiguration type
type RecordingJobConfiguration struct {
// Identifies the recording to which this job shall store the received data.
RecordingToken RecordingReference `xml:"tt:RecordingToken,omitempty"`
// The mode of the job. If it is idle, nothing shall happen. If it is active, the device shall try
// to obtain data from the receivers. A client shall use GetRecordingJobState to determine if data transfer is really taking place.
// The only valid values for Mode shall be “Idle” and “Active”.
Mode RecordingJobMode `xml:"tt:Mode,omitempty"`
// This shall be a non-negative number. If there are multiple recording jobs that store data to
// the same track, the device will only store the data for the recording job with the highest
// priority. The priority is specified per recording job, but the device shall determine the priority
// of each track individually. If there are two recording jobs with the same priority, the device
// shall record the data corresponding to the recording job that was activated the latest.
Priority int32 `xml:"tt:Priority,omitempty"`
// Source of the recording.
Source []RecordingJobSource `xml:"tt:Source,omitempty"`
Extension RecordingJobConfigurationExtension `xml:"tt:Extension,omitempty"`
// This attribute adds an additional requirement for activating the recording job.
// If this optional field is provided the job shall only record if the schedule exists and is active.
//
ScheduleToken string `xml:"tt:ScheduleToken,attr,omitempty"`
}
// RecordingJobConfigurationExtension type
type RecordingJobConfigurationExtension struct {
}
// RecordingJobSource type
type RecordingJobSource struct {
// This field shall be a reference to the source of the data. The type of the source
// is determined by the attribute Type in the SourceToken structure. If Type is
// http://www.onvif.org/ver10/schema/Receiver, the token is a ReceiverReference. In this case
// the device shall receive the data over the network. If Type is
// http://www.onvif.org/ver10/schema/Profile, the token identifies a media profile, instructing the
// device to obtain data from a profile that exists on the local device.
SourceToken SourceReference `xml:"tt:SourceToken,omitempty"`
// If this field is TRUE, and if the SourceToken is omitted, the device
// shall create a receiver object (through the receiver service) and assign the
// ReceiverReference to the SourceToken field. When retrieving the RecordingJobConfiguration
// from the device, the AutoCreateReceiver field shall never be present.
AutoCreateReceiver bool `xml:"tt:AutoCreateReceiver,omitempty"`
// List of tracks associated with the recording.
Tracks []RecordingJobTrack `xml:"tt:Tracks,omitempty"`
Extension RecordingJobSourceExtension `xml:"tt:Extension,omitempty"`
}
// RecordingJobTrack type
type RecordingJobTrack struct {
// If the received RTSP stream contains multiple tracks of the same type, the
// SourceTag differentiates between those Tracks. This field can be ignored in case of recording a local source.
SourceTag string `xml:"tt:SourceTag,omitempty"`
// The destination is the tracktoken of the track to which the device shall store the
// received data.
Destination TrackReference `xml:"tt:Destination,omitempty"`
}
// RecordingJobSourceExtension type
type RecordingJobSourceExtension struct {
}
// RecordingJobMode type
type RecordingJobMode string
// RecordingJobState type
type RecordingJobState string
// ModeOfOperation type
type ModeOfOperation string
// DeleteRecordingJob type
type DeleteRecordingJob struct {
XMLName xml.Name `xml:"tt:DeleteRecordingJob"`
// The token of the job to be deleted.
JobToken RecordingJobReference `xml:"tt:JobToken,omitempty"`
}
// DeleteRecordingJobResponse type
type DeleteRecordingJobResponse struct {
XMLName xml.Name `xml:"DeleteRecordingJobResponse"`
}
// GetRecordingJobs type
type GetRecordingJobs struct {
XMLName xml.Name `xml:"tt:GetRecordingJobs"`
}
// GetRecordingJobsResponse type
type GetRecordingJobsResponse struct {
XMLName xml.Name `xml:"GetRecordingJobsResponse"`
// List of recording jobs.
JobItem []GetRecordingJobsResponseItem `xml:"JobItem,omitempty"`
}
// GetRecordingJobsResponseItem type
type GetRecordingJobsResponseItem struct {
JobToken RecordingJobReference `xml:"JobToken,omitempty"`
JobConfiguration RecordingJobConfiguration `xml:"JobConfiguration,omitempty"`
}
// SetRecordingJobConfiguration type
type SetRecordingJobConfiguration struct {
XMLName xml.Name `xml:"tt:SetRecordingJobConfiguration"`
// Token of the job to be modified.
JobToken RecordingJobReference `xml:"tt:JobToken,omitempty"`
// New configuration of the recording job.
JobConfiguration RecordingJobConfiguration `xml:"tt:JobConfiguration,omitempty"`
}
// SetRecordingJobConfigurationResponse type
type SetRecordingJobConfigurationResponse struct {
XMLName xml.Name `xml:"SetRecordingJobConfigurationResponse"`
// The JobConfiguration structure shall be the configuration
// as it is used by the device. This may be different from the JobConfiguration passed to SetRecordingJobConfiguration.
JobConfiguration RecordingJobConfiguration `xml:"JobConfiguration,omitempty"`
}
// GetRecordingJobConfiguration type
type GetRecordingJobConfiguration struct {
XMLName xml.Name `xml:"tt:GetRecordingJobConfiguration"`
// Token of the recording job.
JobToken RecordingJobReference `xml:"tt:JobToken,omitempty"`
}
// GetRecordingJobConfigurationResponse type
type GetRecordingJobConfigurationResponse struct {
XMLName xml.Name `xml:"GetRecordingJobConfigurationResponse"`
// Current configuration of the recording job.
JobConfiguration RecordingJobConfiguration `xml:"JobConfiguration,omitempty"`
}
// SetRecordingJobMode type
type SetRecordingJobMode struct {
XMLName xml.Name `xml:"tt:SetRecordingJobMode"`
// Token of the recording job.
JobToken RecordingJobReference `xml:"tt:JobToken,omitempty"`
// The new mode for the recording job.
Mode RecordingJobMode `xml:"tt:Mode,omitempty"`
}
// SetRecordingJobModeResponse type
type SetRecordingJobModeResponse struct {
XMLName xml.Name `xml:"SetRecordingJobModeResponse"`
}
// GetRecordingJobState type
type GetRecordingJobState struct {
XMLName xml.Name `xml:"tt:GetRecordingJobState"`
// Token of the recording job.
JobToken RecordingJobReference `xml:"tt:JobToken,omitempty"`
}
// GetRecordingJobStateResponse type
type GetRecordingJobStateResponse struct {
XMLName xml.Name `xml:"GetRecordingJobStateResponse"`
// The current state of the recording job.
State RecordingJobStateInformation `xml:"State,omitempty"`
}
// RecordingJobStateInformation type
type RecordingJobStateInformation struct {
// Identification of the recording that the recording job records to.
RecordingToken RecordingReference `xml:"tt:RecordingToken,omitempty"`
// Holds the aggregated state over the whole RecordingJobInformation structure.
State RecordingJobState `xml:"tt:State,omitempty"`
// Identifies the data source of the recording job.
Sources []RecordingJobStateSource `xml:"tt:Sources,omitempty"`
Extension RecordingJobStateInformationExtension `xml:"tt:Extension,omitempty"`
}
// RecordingJobStateInformationExtension type
type RecordingJobStateInformationExtension struct {
}
// RecordingJobStateSource type
type RecordingJobStateSource struct {
// Identifies the data source of the recording job.
SourceToken SourceReference `xml:"tt:SourceToken,omitempty"`
// Holds the aggregated state over all substructures of RecordingJobStateSource.
State RecordingJobState `xml:"tt:State,omitempty"`
// List of track items.
Tracks RecordingJobStateTracks `xml:"tt:Tracks,omitempty"`
}
// RecordingJobStateTracks type
type RecordingJobStateTracks struct {
Track []RecordingJobStateTrack `xml:"tt:Track,omitempty"`
}
// RecordingJobStateTrack type
type RecordingJobStateTrack struct {
// Identifies the track of the data source that provides the data.
SourceTag string `xml:"tt:SourceTag,omitempty"`
// Indicates the destination track.
Destination TrackReference `xml:"tt:Destination,omitempty"`
// Optionally holds an implementation defined string value that describes the error.
// The string should be in the English language.
Error string `xml:"tt:Error,omitempty"`
// Provides the job state of the track. The valid
// values of state shall be “Idle”, “Active” and “Error”. If state equals “Error”, the Error field may be filled in with an implementation defined value.
State RecordingJobState `xml:"tt:State,omitempty"`
}
// GetRecordingOptions type
type GetRecordingOptions struct {
XMLName xml.Name `xml:"tt:GetRecordingOptions"`
// Token of the recording.
RecordingToken RecordingReference `xml:"tt:RecordingToken,omitempty"`
}
// GetRecordingOptionsResponse type
type GetRecordingOptionsResponse struct {
XMLName xml.Name `xml:"GetRecordingOptionsResponse"`
// Configuration of the recording.
Options RecordingOptions `xml:"Options,omitempty"`
}
// ExportRecordedData type
type ExportRecordedData struct {
XMLName xml.Name `xml:"tt:ExportRecordedData"`
// Optional parameter that specifies start time for the exporting.
StartPoint string `xml:"tt:StartPoint,omitempty"`
// Optional parameter that specifies end time for the exporting.
EndPoint string `xml:"tt:EndPoint,omitempty"`
// Indicates the selection criterion on the existing recordings. .
SearchScope SearchScope `xml:"tt:SearchScope,omitempty"`
// Indicates which export file format to be used.
FileFormat string `xml:"tt:FileFormat,omitempty"`
// Indicates the target storage and relative directory path.
StorageDestination StorageReferencePath `xml:"tt:StorageDestination,omitempty"`
}
// StorageReferencePath type
type StorageReferencePath struct {
// identifier of an existing Storage Configuration.
StorageToken ReferenceToken `xml:"tt:StorageToken,omitempty"`
// gives the relative directory path on the storage
RelativePath string `xml:"tt:RelativePath,omitempty"`
Extension StorageReferencePathExtension `xml:"tt:Extension,omitempty"`
}
// StorageReferencePathExtension type
type StorageReferencePathExtension struct {
}
// ExportRecordedDataResponse type
type ExportRecordedDataResponse struct {
XMLName xml.Name `xml:"ExportRecordedDataResponse"`
// Unique operation token for client to associate the relevant events.
OperationToken ReferenceToken `xml:"OperationToken,omitempty"`
// List of exported file names. The device can also use AsyncronousOperationStatus event to publish this list.
FileNames []string `xml:"FileNames,omitempty"`
Extension struct {
} `xml:"Extension,omitempty"`
}
// StopExportRecordedData type
type StopExportRecordedData struct {
XMLName xml.Name `xml:"tt:StopExportRecordedData"`
// Unique ExportRecordedData operation token
OperationToken ReferenceToken `xml:"tt:OperationToken,omitempty"`
}
// StopExportRecordedDataResponse type
type StopExportRecordedDataResponse struct {
XMLName xml.Name `xml:"StopExportRecordedDataResponse"`
// Progress percentage of ExportRecordedData operation.
Progress float32 `xml:"Progress,omitempty"`
FileProgressStatus ArrayOfFileProgress `xml:"FileProgressStatus,omitempty"`
}
// ArrayOfFileProgress type
type ArrayOfFileProgress struct {
// Exported file name and export progress information
FileProgress []FileProgress `xml:"tt:FileProgress,omitempty"`
Extension ArrayOfFileProgressExtension `xml:"tt:Extension,omitempty"`
}
// FileProgress type
type FileProgress struct {
// Exported file name
FileName string `xml:"tt:FileName,omitempty"`
// Normalized percentage completion for uploading the exported file
Progress float32 `xml:"tt:Progress,omitempty"`
}
// ArrayOfFileProgressExtension type
type ArrayOfFileProgressExtension struct {
}
// GetExportRecordedDataState type
type GetExportRecordedDataState struct {
XMLName xml.Name `xml:"tt:GetExportRecordedDataState"`
// Unique ExportRecordedData operation token
OperationToken ReferenceToken `xml:"tt:OperationToken,omitempty"`
}
// GetExportRecordedDataStateResponse type
type GetExportRecordedDataStateResponse struct {
XMLName xml.Name `xml:"GetExportRecordedDataStateResponse"`
// Progress percentage of ExportRecordedData operation.
Progress float32 `xml:"Progress,omitempty"`
FileProgressStatus ArrayOfFileProgress `xml:"FileProgressStatus,omitempty"`
}
// Capabilities type
type Capabilities struct {
// Indication if the device supports dynamic creation and deletion of recordings
DynamicRecordings bool `xml:"tt:DynamicRecordings,attr,omitempty"`
// Indication if the device supports dynamic creation and deletion of tracks
DynamicTracks bool `xml:"tt:DynamicTracks,attr,omitempty"`
// Indication which encodings are supported for recording. The list may contain one or more enumeration values of tt:VideoEncoding and tt:AudioEncoding. For encodings that are neither defined in tt:VideoEncoding nor tt:AudioEncoding the device shall use the defintions. Note, that a device without audio support shall not return audio encodings.
Encoding EncodingTypes `xml:"tt:Encoding,attr,omitempty"`
// Maximum supported bit rate for all tracks of a recording in kBit/s.
MaxRate float32 `xml:"tt:MaxRate,attr,omitempty"`
// Maximum supported bit rate for all recordings in kBit/s.
MaxTotalRate float32 `xml:"tt:MaxTotalRate,attr,omitempty"`
// Maximum number of recordings supported. (Integer values only.)
MaxRecordings float32 `xml:"tt:MaxRecordings,attr,omitempty"`
// Maximum total number of supported recording jobs by the device.
MaxRecordingJobs int32 `xml:"tt:MaxRecordingJobs,attr,omitempty"`
// Indication if the device supports the GetRecordingOptions command.
Options bool `xml:"tt:Options,attr,omitempty"`
// Indication if the device supports recording metadata.
MetadataRecording bool `xml:"tt:MetadataRecording,attr,omitempty"`
//
// Indication that the device supports ExportRecordedData command for the listed export file formats.
// The list shall return at least one export file format value. The value of 'ONVIF' refers to
// ONVIF Export File Format specification.
//
SupportedExportFileFormats onvif.StringAttrList `xml:"tt:SupportedExportFileFormats,attr,omitempty"`
}
// RecordingOptions type
type RecordingOptions struct {
Job JobOptions `xml:"tt:Job,omitempty"`
Track TrackOptions `xml:"tt:Track,omitempty"`
}
// JobOptions type
type JobOptions struct {
// Number of spare jobs that can be created for the recording.
Spare int32 `xml:"tt:Spare,attr,omitempty"`
// A device that supports recording of a restricted set of Media/Media2 Service Profiles returns the list of profiles that can be recorded on the given Recording.
CompatibleSources onvif.StringAttrList `xml:"tt:CompatibleSources,attr,omitempty"`
}
// TrackOptions type
type TrackOptions struct {
// Total spare number of tracks that can be added to this recording.
SpareTotal int32 `xml:"tt:SpareTotal,attr,omitempty"`
// Number of spare Video tracks that can be added to this recording.
SpareVideo int32 `xml:"tt:SpareVideo,attr,omitempty"`
// Number of spare Aduio tracks that can be added to this recording.
SpareAudio int32 `xml:"tt:SpareAudio,attr,omitempty"`
// Number of spare Metadata tracks that can be added to this recording.
SpareMetadata int32 `xml:"tt:SpareMetadata,attr,omitempty"`
}
// SearchScope type
type SearchScope struct {
// A list of sources that are included in the scope. If this list is included, only data from one of these sources shall be searched.
IncludedSources []SourceReference `xml:"tt:IncludedSources,omitempty"`
// A list of recordings that are included in the scope. If this list is included, only data from one of these recordings shall be searched.
IncludedRecordings []RecordingReference `xml:"tt:IncludedRecordings,omitempty"`
// An xpath expression used to specify what recordings to search. Only those recordings with an RecordingInformation structure that matches the filter shall be searched.
RecordingInformationFilter XPathExpression `xml:"tt:RecordingInformationFilter,omitempty"`
// Extension point
Extension SearchScopeExtension `xml:"tt:Extension,omitempty"`
}
// XPathExpression type
type XPathExpression string
// SourceReference type
type SourceReference struct {
Token ReferenceToken `xml:"tt:Token,omitempty"`
Type xsd.AnyURI `xml:"tt:Type,attr,omitempty"`
}
// RecordingReference type
type RecordingReference ReferenceToken
// TrackReference type
type TrackReference ReferenceToken
// ReferenceToken type
type ReferenceToken string
// SearchScopeExtension type
type SearchScopeExtension struct {
}

View File

@@ -9,86 +9,171 @@ package wsdiscovery
* permission of Palanjyan Zhorzhik
*******************************************************/
// Copyright (C) 2022 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
import (
"errors"
"fmt"
"log"
"net"
"net/http"
"net/url"
"os"
"strings"
"time"
"github.com/gofrs/uuid"
"github.com/beevik/etree"
"github.com/google/uuid"
"github.com/kerberos-io/onvif"
"golang.org/x/net/ipv4"
)
const bufSize = 8192
const (
bufSize = 8192
)
//SendProbe to device
func SendProbe(interfaceName string, scopes, types []string, namespaces map[string]string) []string {
// Creating UUID Version 4
uuidV4 := uuid.Must(uuid.NewV4())
//fmt.Printf("UUIDv4: %s\n", uuidV4)
// GetAvailableDevicesAtSpecificEthernetInterface sends a ws-discovery Probe Message via
// UDP multicast to Discover NVT type Devices
func GetAvailableDevicesAtSpecificEthernetInterface(interfaceName string) ([]onvif.Device, error) {
types := []string{"dn:NetworkVideoTransmitter"}
namespaces := map[string]string{"dn": "http://www.onvif.org/ver10/network/wsdl", "ds": "http://www.onvif.org/ver10/device/wsdl"}
probeSOAP := buildProbeMessage(uuidV4.String(), scopes, types, namespaces)
//probeSOAP = `<?xml version="1.0" encoding="UTF-8"?>
//<Envelope xmlns="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://schemas.xmlsoap.org/ws/2004/08/addressing">
//<Header>
//<a:Action mustUnderstand="1">http://schemas.xmlsoap.org/ws/2005/04/discovery/Probe</a:Action>
//<a:MessageID>uuid:78a2ed98-bc1f-4b08-9668-094fcba81e35</a:MessageID><a:ReplyTo>
//<a:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address>
//</a:ReplyTo><a:To mustUnderstand="1">urn:schemas-xmlsoap-org:ws:2005:04:discovery</a:To>
//</Header>
//<Body><Probe xmlns="http://schemas.xmlsoap.org/ws/2005/04/discovery">
//<d:Types xmlns:d="http://schemas.xmlsoap.org/ws/2005/04/discovery" xmlns:dp0="http://www.onvif.org/ver10/network/wsdl">dp0:NetworkVideoTransmitter</d:Types>
//</Probe>
//</Body>
//</Envelope>`
probeResponses, err := SendProbe(interfaceName, nil, types, namespaces)
if err != nil {
return nil, fmt.Errorf("failed to probe: %w", err)
}
return sendUDPMulticast(probeSOAP.String(), interfaceName)
nvtDevices, err := DevicesFromProbeResponses(probeResponses)
if err != nil {
return nil, fmt.Errorf("failed to discover Onvif devices: %w", err)
}
return nvtDevices, nil
}
func sendUDPMulticast(msg string, interfaceName string) []string {
var result []string
data := []byte(msg)
iface, err := net.InterfaceByName(interfaceName)
if err != nil {
fmt.Println(err)
}
group := net.IPv4(239, 255, 255, 250)
func DevicesFromProbeResponses(probeResponses []string) ([]onvif.Device, error) {
nvtDevices := make([]onvif.Device, 0)
xaddrSet := make(map[string]struct{})
for _, j := range probeResponses {
doc := etree.NewDocument()
if err := doc.ReadFromString(j); err != nil {
return nil, err
}
c, err := net.ListenPacket("udp4", "0.0.0.0:1024")
probeMatches := doc.Root().FindElements("./Body/ProbeMatches/ProbeMatch")
for _, probeMatch := range probeMatches {
var xaddr string
if address := probeMatch.FindElement("./XAddrs"); address != nil {
u, err := url.Parse(address.Text())
if err != nil {
// TODO: Add logger for fmt.Printf("Invalid XAddrs: %s\n", address.Text())
continue
}
xaddr = u.Host
}
if _, dupe := xaddrSet[xaddr]; dupe {
// TODO: Add logger for fmt.Printf("Skipping duplicate XAddr: %s\n", xaddr)
continue
}
var endpointRefAddress string
if ref := probeMatch.FindElement("./EndpointReference/Address"); ref != nil {
uuidElements := strings.Split(ref.Text(), ":")
endpointRefAddress = uuidElements[len(uuidElements)-1]
}
dev, err := onvif.NewDevice(onvif.DeviceParams{
Xaddr: xaddr,
EndpointRefAddress: endpointRefAddress,
HttpClient: &http.Client{
Timeout: 2 * time.Second,
},
})
if err != nil {
// TODO: Add logger for fmt.Printf("Failed to connect to camera at %s: %s\n", xaddr, err.Error())
continue
}
var scopes []string
ref := probeMatch.FindElement("./Scopes")
if ref != nil {
scopes = strings.Split(ref.Text(), " ")
}
dev.SetDeviceInfoFromScopes(scopes)
xaddrSet[xaddr] = struct{}{}
nvtDevices = append(nvtDevices, *dev)
// TODO: Add logger for fmt.Printf("Onvif WS-Discovery: Find Xaddr: %-25s EndpointRefAddress: %s\n", xaddr, string(endpointRefAddress))
}
}
return nvtDevices, nil
}
// SendProbe to device
func SendProbe(interfaceName string, scopes, types []string, namespaces map[string]string) ([]string, error) {
probeSOAP := BuildProbeMessage(uuid.NewString(), scopes, types, namespaces)
return SendUDPMulticast(probeSOAP.String(), interfaceName)
}
func SendUDPMulticast(msg string, interfaceName string) ([]string, error) {
var responses []string
data := []byte(msg)
c, err := net.ListenPacket("udp4", "0.0.0.0:0")
if err != nil {
fmt.Println(err)
return nil, err
}
defer c.Close()
p := ipv4.NewPacketConn(c)
if err := p.JoinGroup(iface, &net.UDPAddr{IP: group}); err != nil {
fmt.Println(err)
}
dst := &net.UDPAddr{IP: group, Port: 3702}
for _, ifi := range []*net.Interface{iface} {
if err := p.SetMulticastInterface(ifi); err != nil {
fmt.Println(err)
}
p.SetMulticastTTL(2)
if _, err := p.WriteTo(data, nil, dst); err != nil {
fmt.Println(err)
// 239.255.255.250 port 3702 is the multicast address and port used by ws-discovery
group := net.IPv4(239, 255, 255, 250)
dest := &net.UDPAddr{IP: group, Port: 3702}
var iface *net.Interface
if interfaceName == "" {
iface = nil
} else {
iface, err = net.InterfaceByName(interfaceName)
if err != nil {
return nil, fmt.Errorf("failed to call InterfaceByName for interface %q: %w", interfaceName, err)
}
}
if err := p.SetReadDeadline(time.Now().Add(time.Second * 1)); err != nil {
log.Fatal(err)
if err = p.JoinGroup(iface, &net.UDPAddr{IP: group}); err != nil {
return nil, fmt.Errorf("failed to JoinGroup for ws-discovery: %w", err)
}
if iface != nil {
if err = p.SetMulticastInterface(iface); err != nil {
return nil, fmt.Errorf("failed to SetMulticastInterface for interface %q: %w", interfaceName, err)
}
if err = p.SetMulticastTTL(2); err != nil {
return nil, fmt.Errorf("failed to SetMulticastTTL: %w", err)
}
}
if _, err = p.WriteTo(data, nil, dest); err != nil {
return nil, fmt.Errorf("failed to write to ws-discovery multicast address %s: %w", dest.String(), err)
}
if err = p.SetReadDeadline(time.Now().Add(time.Second * 1)); err != nil {
return nil, fmt.Errorf("failed to set read deadline: %w", err)
}
b := make([]byte, bufSize)
// keep reading from the PacketConn until the read deadline expires or an error occurs
for {
b := make([]byte, bufSize)
n, _, _, err := p.ReadFrom(b)
if err != nil {
fmt.Println(err)
// ErrDeadlineExceeded is expected once the read timeout is expired
if !errors.Is(err, os.ErrDeadlineExceeded) {
return nil, fmt.Errorf("unexpected error occurred while reading ws-discovery responses: %w", err)
}
break
}
result = append(result, string(b[0:n]))
responses = append(responses, string(b[0:n]))
}
return result
return responses, nil
}

View File

@@ -0,0 +1,56 @@
package wsdiscovery
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestDevicesFromProbeResponses(t *testing.T) {
probeResponses := []string{
`<env:Envelope>
<env:Header></env:Header>
<env:Body>
<d:ProbeMatches>
<d:ProbeMatch>
<wsadis:EndpointReference>
<wsadis:Address>urn:uuid:cea94000-fb96-11b3-8260-686dbc5cb15d</wsadis:Address>
</wsadis:EndpointReference>
<d:Types>dn:NetworkVideoTransmitter tds:Device</d:Types>
<d:Scopes>onvif://www.onvif.org/type/video_encoder onvif://www.onvif.org/Profile/Streaming onvif://www.onvif.org/MAC/68:6d:bc:5c:b1:5d onvif://www.onvif.org/hardware/DFI6256TE http:123</d:Scopes>
<d:XAddrs>http://192.168.12.123/onvif/device_service</d:XAddrs>
<d:MetadataVersion>10</d:MetadataVersion>
</d:ProbeMatch>
</d:ProbeMatches>
</env:Body>
</env:Envelope>`,
`<SOAP-ENV:Envelope>
<SOAP-ENV:Header></SOAP-ENV:Header>
<SOAP-ENV:Body>
<wsdd:ProbeMatches>
<wsdd:ProbeMatch>
<wsa:EndpointReference>
<wsa:Address>uuid:3fa1fe68-b915-4053-a3e1-c006c3afec0e</wsa:Address>
<wsa:ReferenceProperties>
</wsa:ReferenceProperties>
<wsa:PortType>ttl</wsa:PortType>
</wsa:EndpointReference>
<wsdd:Types>tdn:NetworkVideoTransmitter</wsdd:Types>
<wsdd:Scopes>onvif://www.onvif.org/name/TP-IPC onvif://www.onvif.org/hardware/MODEL onvif://www.onvif.org/Profile/Streaming onvif://www.onvif.org/location/ShenZhen onvif://www.onvif.org/type/NetworkVideoTransmitter </wsdd:Scopes>
<wsdd:XAddrs>http://192.168.12.128:2020/onvif/device_service</wsdd:XAddrs>
<wsdd:MetadataVersion>1</wsdd:MetadataVersion>
</wsdd:ProbeMatch>
</wsdd:ProbeMatches>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>`,
}
devices, err := DevicesFromProbeResponses(probeResponses)
require.NoError(t, err)
require.Equal(t, 2, len(devices))
assert.Equal(t, devices[0].GetDeviceParams().Xaddr, "192.168.12.123")
assert.Equal(t, devices[0].GetDeviceParams().EndpointRefAddress, "cea94000-fb96-11b3-8260-686dbc5cb15d")
assert.Equal(t, devices[1].GetDeviceParams().Xaddr, "192.168.12.128:2020")
assert.Equal(t, devices[1].GetDeviceParams().EndpointRefAddress, "3fa1fe68-b915-4053-a3e1-c006c3afec0e")
}

View File

@@ -4,25 +4,44 @@ import (
"strings"
"github.com/beevik/etree"
"github.com/use-go/onvif/gosoap"
"github.com/kerberos-io/onvif/gosoap"
)
func buildProbeMessage(uuidV4 string, scopes, types []string, nmsp map[string]string) gosoap.SoapMessage {
//Список namespace
// BuildProbeMessage generates a SOAP ws-discovery Probe message
//
// Example Message:
//
// <?xml version="1.0" encoding="UTF-8"?>
// <soap-env:Envelope xmlns:soap-env="http://www.w3.org/2003/05/soap-envelope"
// xmlns:a="http://schemas.xmlsoap.org/ws/2004/08/addressing"
// xmlns:d="http://schemas.xmlsoap.org/ws/2005/04/discovery"
// xmlns:dn="http://www.onvif.org/ver10/network/wsdl"
// xmlns:soap-enc="http://www.w3.org/2003/05/soap-encoding">
// <soap-env:Header>
// <a:Action mustUnderstand="1">http://schemas.xmlsoap.org/ws/2005/04/discovery/Probe</a:Action>
// <a:MessageID>uuid:a277f13a-ecae-4492-9d6a-218982122d1c</a:MessageID>
// <a:To mustUnderstand="1">urn:schemas-xmlsoap-org:ws:2005:04:discovery</a:To>
// </soap-env:Header>
// <soap-env:Body>
// <d:Probe>
// <d:Types>dn:NetworkVideoTransmitter</d:Types>
// </d:Probe>
// </soap-env:Body>
// </soap-env:Envelope>
func BuildProbeMessage(uuidV4 string, scopes, types []string, nmsp map[string]string) gosoap.SoapMessage {
// Namespace List
namespaces := make(map[string]string)
namespaces["a"] = "http://schemas.xmlsoap.org/ws/2004/08/addressing"
//namespaces["d"] = "http://schemas.xmlsoap.org/ws/2005/04/discovery"
namespaces["d"] = "http://schemas.xmlsoap.org/ws/2005/04/discovery"
namespaces["dn"] = "http://www.onvif.org/ver10/network/wsdl"
probeMessage := gosoap.NewEmptySOAP()
probeMessage.AddRootNamespaces(namespaces)
//if len(nmsp) != 0 {
// probeMessage.AddRootNamespaces(nmsp)
//}
if len(nmsp) != 0 {
probeMessage.AddRootNamespaces(nmsp)
}
//fmt.Println(probeMessage.String())
//Содержимое Head
// Probe Header
var headerContent []*etree.Element
action := etree.NewElement("a:Action")
@@ -32,49 +51,25 @@ func buildProbeMessage(uuidV4 string, scopes, types []string, nmsp map[string]st
msgID := etree.NewElement("a:MessageID")
msgID.SetText("uuid:" + uuidV4)
replyTo := etree.NewElement("a:ReplyTo")
replyTo.CreateElement("a:Address").SetText("http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous")
to := etree.NewElement("a:To")
to.SetText("urn:schemas-xmlsoap-org:ws:2005:04:discovery")
to.CreateAttr("mustUnderstand", "1")
headerContent = append(headerContent, action, msgID, replyTo, to)
headerContent = append(headerContent, action, msgID, to)
probeMessage.AddHeaderContents(headerContent)
//Содержимое Body
probe := etree.NewElement("Probe")
probe.CreateAttr("xmlns", "http://schemas.xmlsoap.org/ws/2005/04/discovery")
// Probe Body
probe := etree.NewElement("d:Probe")
if len(types) != 0 {
typesTag := etree.NewElement("d:Types")
if len(nmsp) != 0 {
for key, value := range nmsp {
typesTag.CreateAttr("xmlns:"+key, value)
}
}
typesTag.CreateAttr("xmlns:d", "http://schemas.xmlsoap.org/ws/2005/04/discovery")
//typesTag.CreateAttr("xmlns:dp0", "http://www.onvif.org/ver10/network/wsdl")
var typesString string
for _, j := range types {
typesString += j
typesString += " "
}
typesTag.SetText(strings.TrimSpace(typesString))
typesTag.SetText(strings.Join(types, " "))
probe.AddChild(typesTag)
}
if len(scopes) != 0 {
scopesTag := etree.NewElement("d:Scopes")
var scopesString string
for _, j := range scopes {
scopesString += j
scopesString += " "
}
scopesTag.SetText(strings.TrimSpace(scopesString))
scopesTag.SetText(strings.Join(scopes, " "))
probe.AddChild(scopesTag)
}

View File

@@ -11,7 +11,7 @@ import (
"strings"
"time"
iso8601 "github.com/yakovlevdmv/Golang-iso8601-duration"
"github.com/kerberos-io/onvif/xsd/iso8601"
)
/*
@@ -29,128 +29,127 @@ type AnySimpleType string
***********************************************************/
/*
The string datatype represents character strings in XML.
The ·value space· of string is the set of finite-length sequences of characters.
String has the following constraining facets:
• length
• minLength
• maxLength
• pattern
• enumeration
• whiteSpace
The string datatype represents character strings in XML.
The ·value space· of string is the set of finite-length sequences of characters.
String has the following constraining facets:
• length
• minLength
• maxLength
• pattern
• enumeration
• whiteSpace
More info: https://www.w3.org/TR/xmlschema-2/#string
More info: https://www.w3.org/TR/xmlschema-2/#string
//TODO: valid/invalid character declaration and process restrictions
//TODO: valid/invalid character declaration and process restrictions
*/
type String string
/*
Construct an instance of xsd String type
Construct an instance of xsd String type
*/
func (tp String) NewString(data string) String {
return String(data)
}
/*
Boolean has the ·value space· required to support the mathematical concept of binary-valued logic: {true, false}.
Boolean has the following ·constraining facets·:
• pattern
• whiteSpace
Boolean has the ·value space· required to support the mathematical concept of binary-valued logic: {true, false}.
Boolean has the following ·constraining facets·:
• pattern
• whiteSpace
More info: https://www.w3.org/TR/xmlschema-2/#boolean
More info: https://www.w3.org/TR/xmlschema-2/#boolean
//TODO: process restrictions
//TODO: process restrictions
*/
type Boolean bool
/*
Construct an instance of xsd Boolean type
Construct an instance of xsd Boolean type
*/
func (tp Boolean) NewBool(data bool) Boolean {
return Boolean(data)
}
/*
Float is patterned after the IEEE single-precision 32-bit floating point type
Float has the following ·constraining facets·:
• pattern
• enumeration
• whiteSpace
• maxInclusive
• maxExclusive
• minInclusive
• minExclusive
Float is patterned after the IEEE single-precision 32-bit floating point type
Float has the following ·constraining facets·:
• pattern
• enumeration
• whiteSpace
• maxInclusive
• maxExclusive
• minInclusive
• minExclusive
More info: https://www.w3.org/TR/xmlschema-2/#float
More info: https://www.w3.org/TR/xmlschema-2/#float
//TODO: process restrictions
//TODO: process restrictions
*/
type Float float32
/*
Construct an instance of xsd Float type
Construct an instance of xsd Float type
*/
func (tp Float) NewFloat(data float32) Float {
return Float(data)
}
/*
The double datatype is patterned after the IEEE double-precision 64-bit floating point type
Double has the following ·constraining facets·:
• pattern
• enumeration
• whiteSpace
• maxInclusive
• maxExclusive
• minInclusive
• minExclusive
The double datatype is patterned after the IEEE double-precision 64-bit floating point type
Double has the following ·constraining facets·:
• pattern
• enumeration
• whiteSpace
• maxInclusive
• maxExclusive
• minInclusive
• minExclusive
More info: https://www.w3.org/TR/xmlschema-2/#double
More info: https://www.w3.org/TR/xmlschema-2/#double
//TODO: process restrictions
//TODO: process restrictions
*/
type Double float64
/*
Construct an instance of xsd Double type
Construct an instance of xsd Double type
*/
func (tp Double) NewDouble(data float64) Double {
return Double(data)
}
/*
The type decimal represents a decimal number of arbitrary precision.
Schema processors vary in the number of significant digits they support,
but a conforming processor must support a minimum of 18 significant digits.
The format of xsd:decimal is a sequence of digits optionally preceded by a sign ("+" or "-")
and optionally containing a period. The value may start or end with a period.
If the fractional part is 0 then the period and trailing zeros may be omitted.
Leading and trailing zeros are permitted, but they are not considered significant.
That is, the decimal values 3.0 and 3.0000 are considered equal.
The type decimal represents a decimal number of arbitrary precision.
Schema processors vary in the number of significant digits they support,
but a conforming processor must support a minimum of 18 significant digits.
The format of xsd:decimal is a sequence of digits optionally preceded by a sign ("+" or "-")
and optionally containing a period. The value may start or end with a period.
If the fractional part is 0 then the period and trailing zeros may be omitted.
Leading and trailing zeros are permitted, but they are not considered significant.
That is, the decimal values 3.0 and 3.0000 are considered equal.
Source: http://www.datypic.com/sc/xsd/t-xsd_decimal.html
Source: http://www.datypic.com/sc/xsd/t-xsd_decimal.html
Decimal has the following ·constraining facets·:
• totalDigits
• fractionDigits
• pattern
• whiteSpace
• enumeration
• maxInclusive
• maxExclusive
• minInclusive
• minExclusive
Decimal has the following ·constraining facets·:
• totalDigits
• fractionDigits
• pattern
• whiteSpace
• enumeration
• maxInclusive
• maxExclusive
• minInclusive
• minExclusive
More info: https://www.w3.org/TR/xmlschema-2/#decimal
//TODO: process restrictions, valid/invalid characters(commas are not permitted; the decimal separator must be a period)
More info: https://www.w3.org/TR/xmlschema-2/#decimal
//TODO: process restrictions, valid/invalid characters(commas are not permitted; the decimal separator must be a period)
*/
type Decimal string
/*
Construct an instance of xsd Decimal type
Construct an instance of xsd Decimal type
*/
func (tp Decimal) NewDecimal(data string) Decimal {
return Decimal(data)
@@ -180,11 +179,11 @@ func (tp Decimal) NewDecimal(data string) Decimal {
TODO: Look at time.Duration go type
*/
//Duration alias for AnySimpleType
// Duration alias for AnySimpleType
type Duration AnySimpleType
/*
Construct an instance of xsd duration type
Construct an instance of xsd duration type
*/
func (tp Duration) NewDateTime(years, months, days, hours, minutes, seconds string) Duration {
i, err := iso8601.NewDuration(
@@ -206,199 +205,192 @@ func (tp Duration) NewDateTime(years, months, days, hours, minutes, seconds stri
}
/*
DateTime values may be viewed as objects with integer-valued year, month, day, hour
and minute properties, a decimal-valued second property, and a boolean timezoned property.
DateTime values may be viewed as objects with integer-valued year, month, day, hour
and minute properties, a decimal-valued second property, and a boolean timezoned property.
The ·lexical space· of dateTime consists of finite-length sequences of characters of the form:
The ·lexical space· of dateTime consists of finite-length sequences of characters of the form:
'-'? yyyy '-' mm '-' dd 'T' hh ':' mm ':' ss ('.' s+)? (zzzzzz)?,
'-'? yyyy '-' mm '-' dd 'T' hh ':' mm ':' ss ('.' s+)? (zzzzzz)?,
DateTime has the following ·constraining facets·:
DateTime has the following ·constraining facets·:
• pattern
• enumeration
• whiteSpace
• maxInclusive
• maxExclusive
• minInclusive
• minExclusive
• pattern
• enumeration
• whiteSpace
• maxInclusive
• maxExclusive
• minInclusive
• minExclusive
More info: https://www.w3.org/TR/xmlschema-2/#dateTime
More info: https://www.w3.org/TR/xmlschema-2/#dateTime
TODO: decide good type for time with proper format
TODO: process restrictions
TODO: decide good type for time with proper format
TODO: process restrictions
*/
type DateTime AnySimpleType
/*
Construct an instance of xsd dateTime type
*/
func (tp DateTime) NewDateTime(time time.Time) DateTime {
return DateTime(time.Format("2002-10-10T12:00:00-05:00"))
type DateTime struct {
Time Time
Date Date
}
/*
Time represents an instant of time that recurs every day.
The ·value space· of time is the space of time of day values
as defined in § 5.3 of [ISO 8601]. Specifically, it is a set
of zero-duration daily time instances.
Time represents an instant of time that recurs every day.
The ·value space· of time is the space of time of day values
as defined in § 5.3 of [ISO 8601]. Specifically, it is a set
of zero-duration daily time instances.
Time has the following ·constraining facets·:
Time has the following ·constraining facets·:
• pattern
• enumeration
• whiteSpace
• maxInclusive
• maxExclusive
• minInclusive
• minExclusive
• pattern
• enumeration
• whiteSpace
• maxInclusive
• maxExclusive
• minInclusive
• minExclusive
More info: https://www.w3.org/TR/xmlschema-2/#time
More info: https://www.w3.org/TR/xmlschema-2/#time
TODO: process restrictions
TODO: process restrictions
*/
type Time AnySimpleType
type Time struct {
Hour Int
Minute Int
Second Int
}
/*
Construct an instance of xsd time type
*/
func (tp DateTime) NewTime(time time.Time) DateTime {
return DateTime(time.Format("15:04:05"))
/*
The ·value space· of date consists of top-open intervals of
exactly one day in length on the timelines of dateTime, beginning
on the beginning moment of each day (in each timezone),
i.e. '00:00:00', up to but not including '24:00:00'
(which is identical with '00:00:00' of the next day).
For nontimezoned values, the top-open intervals disjointly
cover the nontimezoned timeline, one per day. For timezoned
values, the intervals begin at every minute and therefore overlap.
*/
type Date struct {
Year Int
Month Int
Day Int
}
/*
The ·value space· of date consists of top-open intervals of
exactly one day in length on the timelines of dateTime, beginning
on the beginning moment of each day (in each timezone),
i.e. '00:00:00', up to but not including '24:00:00'
(which is identical with '00:00:00' of the next day).
For nontimezoned values, the top-open intervals disjointly
cover the nontimezoned timeline, one per day. For timezoned
values, the intervals begin at every minute and therefore overlap.
*/
type Date AnySimpleType
The type xsd:gYearMonth represents a specific month of a specific
year. The letter g signifies "Gregorian." The format of
xsd:gYearMonth is CCYY-MM. No left truncation is allowed on
either part. To represents years later than 9999, additional
digits can be added to the left of the year value.
To represent years before 0001, a preceding minus sign ("-")
is permitted.
/*
Construct an instance of xsd date type
*/
func (tp Date) NewDate(time time.Time) Date {
return Date(time.Format("2004-04-12-05:00"))
}
Source: http://www.datypic.com/sc/xsd/t-xsd_gYearMonth.html
/*
The type xsd:gYearMonth represents a specific month of a specific
year. The letter g signifies "Gregorian." The format of
xsd:gYearMonth is CCYY-MM. No left truncation is allowed on
either part. To represents years later than 9999, additional
digits can be added to the left of the year value.
To represent years before 0001, a preceding minus sign ("-")
is permitted.
Source: http://www.datypic.com/sc/xsd/t-xsd_gYearMonth.html
More info: https://www.w3.org/TR/xmlschema-2/#gYearMonth
More info: https://www.w3.org/TR/xmlschema-2/#gYearMonth
*/
type GYearMonth AnySimpleType
/*
Construct an instance of xsd GYearMonth type
Construct an instance of xsd GYearMonth type
*/
func (tp GYearMonth) NewGYearMonth(time time.Time) GYearMonth {
return GYearMonth(fmt.Sprintf("", time.Year(), "-", time.Month()))
return GYearMonth(fmt.Sprint("", time.Year(), "-", time.Month()))
//return GYearMonth(time.Format("2004-04-05:00"))
}
/*
The type xsd:gYear represents a specific calendar year.
The letter g signifies "Gregorian." The format of xsd:gYear
is CCYY. No left truncation is allowed. To represent years
later than 9999, additional digits can be added to the left
of the year value. To represent years before 0001, a preceding
minus sign ("-") is allowed.
The type xsd:gYear represents a specific calendar year.
The letter g signifies "Gregorian." The format of xsd:gYear
is CCYY. No left truncation is allowed. To represent years
later than 9999, additional digits can be added to the left
of the year value. To represent years before 0001, a preceding
minus sign ("-") is allowed.
Source: http://www.datypic.com/sc/xsd/t-xsd_gYear.html
Source: http://www.datypic.com/sc/xsd/t-xsd_gYear.html
More info: https://www.w3.org/TR/xmlschema-2/#gYear
More info: https://www.w3.org/TR/xmlschema-2/#gYear
*/
type GYear AnySimpleType
/*
Construct an instance of xsd GYear type
Construct an instance of xsd GYear type
*/
func (tp GYear) NewGYear(time time.Time) GYear {
return GYear(fmt.Sprintf("", time.Year()))
return GYear(fmt.Sprint("", time.Year()))
//return GYearMonth(time.Format("2004-04-05:00"))
}
/*
The type xsd:gMonthDay represents a specific day that recurs
every year. The letter g signifies "Gregorian." xsd:gMonthDay
can be used to say, for example, that your birthday is on the
14th of April every year. The format of xsd:gMonthDay is --MM-DD.
The type xsd:gMonthDay represents a specific day that recurs
every year. The letter g signifies "Gregorian." xsd:gMonthDay
can be used to say, for example, that your birthday is on the
14th of April every year. The format of xsd:gMonthDay is --MM-DD.
Source: http://www.datypic.com/sc/xsd/t-xsd_gMonthDay.html
Source: http://www.datypic.com/sc/xsd/t-xsd_gMonthDay.html
More info: https://www.w3.org/TR/xmlschema-2/#gMonthDay
More info: https://www.w3.org/TR/xmlschema-2/#gMonthDay
*/
type GMonthDay AnySimpleType
/*
Construct an instance of xsd GMonthDay type
Construct an instance of xsd GMonthDay type
*/
func (tp GMonthDay) NewGMonthDay(time time.Time) GMonthDay {
return GMonthDay(fmt.Sprintf("--", time.Month(), "-", time.Day()))
return GMonthDay(fmt.Sprint("--", time.Month(), "-", time.Day()))
}
/*
The type xsd:gDay represents a day that recurs every month.
The letter g signifies "Gregorian." xsd:gDay can be used to say,
for example, that checks are paid on the 5th of each month.
To represent a duration of days, use the duration type instead.
The format of gDay is ---DD.
The type xsd:gDay represents a day that recurs every month.
The letter g signifies "Gregorian." xsd:gDay can be used to say,
for example, that checks are paid on the 5th of each month.
To represent a duration of days, use the duration type instead.
The format of gDay is ---DD.
Source: http://www.datypic.com/sc/xsd/t-xsd_gDay.html
Source: http://www.datypic.com/sc/xsd/t-xsd_gDay.html
More info: https://www.w3.org/TR/xmlschema-2/#gDay
More info: https://www.w3.org/TR/xmlschema-2/#gDay
*/
type GDay AnySimpleType
/*
Construct an instance of xsd GDay type
Construct an instance of xsd GDay type
*/
func (tp GDay) NewGDay(time time.Time) GDay {
return GDay(fmt.Sprintf("---", time.Day()))
return GDay(fmt.Sprint("---", time.Day()))
}
/*
The type xsd:gMonth represents a specific month that recurs
every year. The letter g signifies "Gregorian." xsd:gMonth
can be used to indicate, for example, that fiscal year-end
processing occurs in September of every year. To represent
a duration of months, use the duration type instead. The format
of xsd:gMonth is --MM.
The type xsd:gMonth represents a specific month that recurs
every year. The letter g signifies "Gregorian." xsd:gMonth
can be used to indicate, for example, that fiscal year-end
processing occurs in September of every year. To represent
a duration of months, use the duration type instead. The format
of xsd:gMonth is --MM.
Source: http://www.datypic.com/sc/xsd/t-xsd_gMonth.html
Source: http://www.datypic.com/sc/xsd/t-xsd_gMonth.html
More info: https://www.w3.org/TR/xmlschema-2/#gMonth
More info: https://www.w3.org/TR/xmlschema-2/#gMonth
*/
type GMonth AnySimpleType
func (tp GMonth) NewGMonth(time time.Time) GMonth {
return GMonth(fmt.Sprintf("--", time.Month()))
return GMonth(fmt.Sprint("--", time.Month()))
}
/*
The xsd:hexBinary type represents binary data as a sequence
of binary octets. It uses hexadecimal encoding, where each
binary octet is a two-character hexadecimal number.
Lowercase and uppercase letters A through F are permitted.
For example, 0FB8 and 0fb8 are two equal xsd:hexBinary
representations consisting of two octets.
The xsd:hexBinary type represents binary data as a sequence
of binary octets. It uses hexadecimal encoding, where each
binary octet is a two-character hexadecimal number.
Lowercase and uppercase letters A through F are permitted.
For example, 0FB8 and 0fb8 are two equal xsd:hexBinary
representations consisting of two octets.
Source: http://www.datypic.com/sc/xsd/t-xsd_hexBinary.html
Source: http://www.datypic.com/sc/xsd/t-xsd_hexBinary.html
More info: https://www.w3.org/TR/xmlschema-2/#hexBinary
More info: https://www.w3.org/TR/xmlschema-2/#hexBinary
*/
type HexBinary AnySimpleType
@@ -407,19 +399,19 @@ func (tp HexBinary) NewHexBinary(data []byte) HexBinary {
}
/*
base64Binary represents Base64-encoded arbitrary binary data.
The ·value space· of base64Binary is the set of finite-length sequences of binary octets.
For base64Binary data the entire binary stream is encoded using the Base64 Alphabet in [RFC 2045].
base64Binary represents Base64-encoded arbitrary binary data.
The ·value space· of base64Binary is the set of finite-length sequences of binary octets.
For base64Binary data the entire binary stream is encoded using the Base64 Alphabet in [RFC 2045].
base64Binary has the following ·constraining facets·:
• length
• minLength
• maxLength
• pattern
• enumeration
• whiteSpace
base64Binary has the following ·constraining facets·:
• length
• minLength
• maxLength
• pattern
• enumeration
• whiteSpace
More info: https://www.w3.org/TR/xmlschema-2/#base64Binary
More info: https://www.w3.org/TR/xmlschema-2/#base64Binary
*/
type Base64Binary AnySimpleType
@@ -428,21 +420,21 @@ func (tp Base64Binary) NewBase64Binary(data []byte) Base64Binary {
}
/*
anyURI represents a Uniform Resource Identifier Reference (URI).
An anyURI value can be absolute or relative, and may have an optional
fragment identifier (i.e., it may be a URI Reference).
This type should be used to specify the intention that the
value fulfills the role of a URI as defined by [RFC 2396], as amended by [RFC 2732].
anyURI represents a Uniform Resource Identifier Reference (URI).
An anyURI value can be absolute or relative, and may have an optional
fragment identifier (i.e., it may be a URI Reference).
This type should be used to specify the intention that the
value fulfills the role of a URI as defined by [RFC 2396], as amended by [RFC 2732].
anyURI has the following ·constraining facets·:
• length
• minLength
• maxLength
• pattern
• enumeration
• whiteSpace
anyURI has the following ·constraining facets·:
• length
• minLength
• maxLength
• pattern
• enumeration
• whiteSpace
More info: https://www.w3.org/TR/xmlschema-2/#anyURI
More info: https://www.w3.org/TR/xmlschema-2/#anyURI
*/
type AnyURI AnySimpleType
@@ -451,19 +443,19 @@ func (tp AnyURI) NewAnyURI(data url.URL) AnyURI {
}
/*
QName represents XML qualified names. The ·value space· of QName is the set of tuples
{namespace name, local part}, where namespace name is an anyURI and local part is an NCName.
The ·lexical space· of QName is the set of strings that ·match· the QName production of [Namespaces in XML].
QName represents XML qualified names. The ·value space· of QName is the set of tuples
{namespace name, local part}, where namespace name is an anyURI and local part is an NCName.
The ·lexical space· of QName is the set of strings that ·match· the QName production of [Namespaces in XML].
QName has the following ·constraining facets·:
• length
• minLength
• maxLength
• pattern
• enumeration
• whiteSpace
QName has the following ·constraining facets·:
• length
• minLength
• maxLength
• pattern
• enumeration
• whiteSpace
More info: https://www.w3.org/TR/xmlschema-2/#QName
More info: https://www.w3.org/TR/xmlschema-2/#QName
*/
type QName AnySimpleType
@@ -486,7 +478,7 @@ func (tp QName) NewQName(prefix, local string) QName {
type NormalizedString String
//TODO: check normalization
// TODO: check normalization
func (tp NormalizedString) NewNormalizedString(data string) (NormalizedString, error) {
if strings.ContainsAny(data, "\r\n\t<>&") {
return NormalizedString(""), errors.New("String " + data + " contains forbidden symbols")
@@ -522,7 +514,7 @@ func (tp Language) NewLanguage(data Token) (Language, error) {
type NMTOKEN Token
//TODO: check for valid symbols: https://www.w3.org/TR/xml/#NT-Nmtoken
// TODO: check for valid symbols: https://www.w3.org/TR/xml/#NT-Nmtoken
func (tp NMTOKEN) NewNMTOKEN(data string) NMTOKEN {
return NMTOKEN(data)
}
@@ -539,19 +531,19 @@ func (tp NMTOKENS) NewNMTOKENS(data []NMTOKEN) NMTOKENS {
type Name Token
//TODO: implements https://www.w3.org/TR/xml/#NT-Name
// TODO: implements https://www.w3.org/TR/xml/#NT-Name
func (tp Name) NewName(data Token) Name {
return Name(data)
}
type NCName Name
//TODO: https://www.w3.org/TR/REC-xml/#NT-Name and https://www.w3.org/TR/xml-names/#NT-NCName
// TODO: https://www.w3.org/TR/REC-xml/#NT-Name and https://www.w3.org/TR/xml-names/#NT-NCName
func (tp NCName) NewNCName(data Name) NCName {
return NCName(data)
}
//TODO: improve next types to correspond to XMLSchema
// TODO: improve next types to correspond to XMLSchema
type ID NCName
func (tp ID) NewID(data NCName) ID {

View File

@@ -0,0 +1,104 @@
package iso8601
import (
"errors"
"regexp"
)
//Duration of iso8601
type Duration struct {
years string //= number of years
months string //= number of months
days string //= number of days
// Time section
hours string //= the number of hours
minutes string //= the number of minutes
seconds string //= the number of seconds
}
//NewDuration return duration
func NewDuration(years, months, days, hours, minutes, seconds string) (*Duration, error) {
// Pattern for Years, Months, Days, Hours and Minutes components
pattern1 := "^$|[0-9]+"
// Pattern for Seconds component
pattern2 := "^$|[0-9]+(\\.[0-9]+)?"
matched, err := regexp.MatchString(pattern1, years)
if err != nil {
return nil, err
} else if !matched {
return nil, errors.New("years value = " + years + " does not match pattern " + pattern1)
}
matched, err = regexp.MatchString(pattern1, months)
if err != nil {
return nil, err
} else if !matched {
return nil, errors.New("months value = " + months + " does not match pattern " + pattern1)
}
matched, err = regexp.MatchString(pattern1, days)
if err != nil {
return nil, err
} else if !matched {
return nil, errors.New("months value = " + days + " does not match pattern " + pattern1)
}
matched, err = regexp.MatchString(pattern1, hours)
if err != nil {
return nil, err
} else if !matched {
return nil, errors.New("months value = " + hours + " does not match pattern " + pattern1)
}
matched, err = regexp.MatchString(pattern1, minutes)
if err != nil {
return nil, err
} else if !matched {
return nil, errors.New("months value = " + minutes + " does not match pattern " + pattern1)
}
matched, err = regexp.MatchString(pattern2, seconds)
if err != nil {
return nil, err
} else if !matched {
return nil, errors.New("years value = " + seconds + " does not match pattern " + pattern2)
}
return &Duration{years: years, months: months, hours: hours, days: days, minutes: minutes, seconds: seconds}, nil
}
//ISO8601Duration to string
func (duration Duration) ISO8601Duration() string {
var result string
result += "P" // time duration designator
//years
if duration.years != "" {
result += duration.years + "Y"
}
if duration.months != "" {
result += duration.months + "M"
}
if duration.days != "" {
result += duration.days + "D"
}
if duration.hours != "" && duration.minutes != "" && duration.seconds != "" {
result += "T"
if duration.hours != "" {
result += duration.hours + "H"
}
if duration.minutes != "" {
result += duration.minutes + "M"
}
if duration.seconds != "" {
result += duration.seconds + "S"
}
}
if len(result) == 1 {
result += "T0S"
}
return result
}

File diff suppressed because it is too large Load Diff