From 5ceef03839600c8ef6fa8e8325c33df575cd6a6e Mon Sep 17 00:00:00 2001 From: damon92 Date: Thu, 28 Mar 2019 12:57:23 +0900 Subject: [PATCH] add ln path; add discovery --- register_service.sh | 1 + src/discoverymgr/README.md | 32 - src/discoverymgr/configure.go | 17 + src/discoverymgr/discovery_init.go | 100 +++ src/discoverymgr/example_discoveryOutput.json | 97 --- src/discoverymgr/src/commons/logger/logger.go | 64 -- src/discoverymgr/src/discovery/build_public_ocf.sh | 23 - .../src/discovery/build_samsung_ocf.sh | 30 - src/discoverymgr/src/discovery/discovery.go | 754 --------------------- src/discoverymgr/src/discovery/iotivity | 1 - src/discoverymgr/src/main/main.go | 63 -- src/discoverymgr/test/device_discovery_test.go | 55 ++ src/discoverymgr/types.go | 18 + src/orchestration/main.go | 3 +- src/restapi/v1/restapi.go | 12 + vendor/vendor | 1 + 16 files changed, 206 insertions(+), 1065 deletions(-) create mode 100644 src/discoverymgr/configure.go create mode 100644 src/discoverymgr/discovery_init.go delete mode 100644 src/discoverymgr/example_discoveryOutput.json delete mode 100644 src/discoverymgr/src/commons/logger/logger.go delete mode 100644 src/discoverymgr/src/discovery/build_public_ocf.sh delete mode 100644 src/discoverymgr/src/discovery/build_samsung_ocf.sh delete mode 100644 src/discoverymgr/src/discovery/discovery.go delete mode 160000 src/discoverymgr/src/discovery/iotivity delete mode 100644 src/discoverymgr/src/main/main.go create mode 100644 src/discoverymgr/test/device_discovery_test.go create mode 100644 src/discoverymgr/types.go create mode 120000 vendor/vendor diff --git a/register_service.sh b/register_service.sh index 8117826..76b07cc 100755 --- a/register_service.sh +++ b/register_service.sh @@ -13,6 +13,7 @@ BASE_DIR=$( cd "$(dirname "$0")" ; pwd ) export GOARCH=amd64 export GOPATH=$GOPATH:$BASE_DIR:$BASE_DIR/vendor +ln -sf $BASE_DIR/vendor $BASE_DIR/vendor/src # go build -tags $ZMQ_VERSION -a -o $BASE_DIR/bin/$SERVICE_BIN orchestration || exit 1 go build -a -ldflags '-extldflags "-static"' -o $BASE_DIR/bin/$SERVICE_BIN orchestration diff --git a/src/discoverymgr/README.md b/src/discoverymgr/README.md index 66dfaba..e69de29 100644 --- a/src/discoverymgr/README.md +++ b/src/discoverymgr/README.md @@ -1,32 +0,0 @@ -Requirement -======================== -Python 2.7 Dependency (from Scons in IoTivity) - -Build -======================== -Tested Env -- go version go1.11.5 linux/amd64 -- Ubuntu18.04, 64bit - -run . build.sh -run ./simplediscovery - -by default, the program is client-server entity and will discovery itself. -and Add discovered data to "discoveryOutput.json" - -Function -======================== -- OCF Server-Client Init -- Register OCF Platform/Device Information -- - can be set by user Or use default information -- Discovery -- - Multicast Or Unicast -- - Unicast can not get more than one platform/device information from a device -- Save as json format file "discoveryOutput.json" -- Also Wrapped createResource API, but not used in this version. - -Todo -======================= -- manage discovered information as map, not json file. -- - device manager will get discovered info and give it to main as desired format -- Devide files, clean up codes, write docs diff --git a/src/discoverymgr/configure.go b/src/discoverymgr/configure.go new file mode 100644 index 0000000..166edd6 --- /dev/null +++ b/src/discoverymgr/configure.go @@ -0,0 +1,17 @@ +package discoverymgr + +const ( + //Watchout about the length of each values mdns constraints + appName = "OrchestrationAgent" + serviceType = "_orchestration._tcp" + domain = "local." + servicePort = 42425 + localAddrFilter = "127.0.0.1" + maxTXTSize = (400 / 4) +) + +// ExitChan is orchestration agent exit chan +var ExitChan chan int + +// ServiceIdx is for unique service ID +// var ServiceIdx uint64 diff --git a/src/discoverymgr/discovery_init.go b/src/discoverymgr/discovery_init.go new file mode 100644 index 0000000..2472e63 --- /dev/null +++ b/src/discoverymgr/discovery_init.go @@ -0,0 +1,100 @@ +//Package discoverymgr wraps main functions of IoTivity/ocstack with golang to use Discovery functions in go project. +package discoverymgr + +import ( + "context" + "fmt" + "log" + "time" + + "github.com/grandcat/zeroconf" +) + +var gServer *zeroconf.Server + +func setServiceNames(ServiceNames []string) { + if len(ServiceNames) > maxTXTSize { + fmt.Println("TXT Size is Too much for mDNS TXT - 400B") + return + } + gServer.SetText(ServiceNames) +} + +//RegisterDevice register orchestration service +func RegisterDevice(ServiceNames []string, ret chan error) { + server, err := zeroconf.Register(appName, serviceType, domain, servicePort, ServiceNames, nil) + if err != nil { + ret <- err + return + } + fmt.Println("[Discoverymgr][RegisterDevice] Orchestraition Service Registered") + gServer = server + defer server.Shutdown() + + ExitChan = make(chan int, 1) + ret <- nil + + select { + case <-ExitChan: + fmt.Println("Orchestration Agent has been terminated") + } +} + +//DeviceList retune device list +func DeviceList() ([]DeviceReturnInfo, error) { + domain := "local" + + resolver, err := zeroconf.NewResolver(nil) + if err != nil { + return nil, err + } + + var data = make(map[string][]string) //data[appname] + entries := make(chan *zeroconf.ServiceEntry) + go func(results <-chan *zeroconf.ServiceEntry) { + for entry := range results { + deviceIP := entry.AddrIPv4[0].String() + fmt.Println("[Discoverymgr] Discoverd Device::" + deviceIP) + ServiceNames := make([]string, len(entry.Text)) + + ServiceNames = entry.Text + + if deviceIP == localAddrFilter { + fmt.Println("Filtering local Addr 127.0.0.1") + continue + } + data[deviceIP] = ServiceNames + } + }(entries) + + ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*time.Duration(100)) + defer cancel() + err = resolver.Browse(ctx, serviceType, domain, entries) + if err != nil { + return nil, err + } + <-ctx.Done() + + var ret []DeviceReturnInfo + for key, value := range data { + ret = append(ret, DeviceReturnInfo{ + DeviceIP: key, + ServiceNames: value}) + } + + return ret, nil +} + +//InitDiscovery deploy Orchestration service +func InitDiscovery() { + + registerCh := make(chan error) + //@ToDo []sting Will be retrieved from configuremgr + //setServiceNames(ServiceNames) + ServiceNames := []string{"Distributed Web Engine", "Television", "Soundbox"} + go RegisterDevice(ServiceNames, registerCh) + if err := <-registerCh; err != nil { + log.Println("[Fail] " + err.Error()) + } + +} diff --git a/src/discoverymgr/example_discoveryOutput.json b/src/discoverymgr/example_discoveryOutput.json deleted file mode 100644 index 31a50c5..0000000 --- a/src/discoverymgr/example_discoveryOutput.json +++ /dev/null @@ -1,97 +0,0 @@ -[ - { - "Port": 34980, - "Endpoint": "10.113.175.92", - "Resources": [ - { - "URI": "/oic/d", - "Types": [ - "oic.wk.d", - "oic.d.airconditioner" - ] - }, - { - "URI": "/introspection", - "Types": [ - "oic.wk.introspection" - ] - }, - { - "URI": "/temperatures/vs/0", - "Types": [ - "x.com.samsung.da.temperatures" - ] - }, - { - "URI": "/airflow/vs/0", - "Types": [ - "x.com.samsung.da.wind" - ] - }, - { - "URI": "/power/vs/0", - "Types": [ - "x.com.samsung.da.operation" - ] - }, - { - "URI": "/temperature/desired/0", - "Types": [ - "oic.r.temperature" - ] - }, - { - "URI": "/temperature/current/0", - "Types": [ - "oic.r.temperature" - ] - }, - { - "URI": "/mode/vs/0", - "Types": [ - "x.com.samsung.da.mode" - ] - } - ] - }, - { - "Port": 48962, - "Endpoint": "10.113.175.92", - "Resources": [ - { - "URI": "/oic/d", - "Types": [ - "oic.wk.d", - "oic.d.tv", - "oic.d.edge" - ] - }, - { - "URI": "/introspection", - "Types": [ - "oic.wk.introspection" - ] - } - ] - }, - { - "Port": 41136, - "Endpoint": "10.113.175.92", - "Resources": [ - { - "URI": "/oic/d", - "Types": [ - "oic.wk.d", - "oic.d.tv", - "oic.d.edge" - ] - }, - { - "URI": "/introspection", - "Types": [ - "oic.wk.introspection" - ] - } - ] - } -] \ No newline at end of file diff --git a/src/discoverymgr/src/commons/logger/logger.go b/src/discoverymgr/src/commons/logger/logger.go deleted file mode 100644 index 761b7e8..0000000 --- a/src/discoverymgr/src/commons/logger/logger.go +++ /dev/null @@ -1,64 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Samsung Electronics All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - *******************************************************************************/ - -// Package commons/logger implements log stream. -package logger - -import ( - "log" - "os" - "path" - "runtime" - "strconv" - "strings" -) - -var loggers [3]*log.Logger -var logFlag int - -// init initializes package global value. -func init() { - logFlag = log.Ldate | log.Ltime - loggers[0] = log.New(os.Stdout, "[INFO][DISCOVERY]", logFlag) - loggers[1] = log.New(os.Stdout, "[DEBUG][DISCOVERY]", logFlag) - loggers[2] = log.New(os.Stdout, "[ERROR][DISCOVERY]", logFlag) -} - -const ( - INFO = iota - DEBUG - ERROR -) - -// Logging prints log stream on standard output with file name and function name, line. -func Logging(level int, msgs ...string) { - pc, file, line, _ := runtime.Caller(1) - _, fileName := path.Split(file) - parts := strings.Split(runtime.FuncForPC(pc).Name(), ".") - pl := len(parts) - funcName := parts[pl-1] - - packageName := "" - if parts[pl-2][0] == '(' { - funcName = parts[pl-2] + "." + funcName - packageName = strings.Join(parts[0:pl-2], ".") - } else { - packageName = strings.Join(parts[0:pl-1], ".") - } - - loggers[level].Println(packageName, fileName, funcName, ":", strconv.Itoa(line), msgs) -} diff --git a/src/discoverymgr/src/discovery/build_public_ocf.sh b/src/discoverymgr/src/discovery/build_public_ocf.sh deleted file mode 100644 index d7753d3..0000000 --- a/src/discoverymgr/src/discovery/build_public_ocf.sh +++ /dev/null @@ -1,23 +0,0 @@ -#!/bin/sh - -dir_name="./iotivity" -arch=$(uname -m) -if test -d $dir_name -then -echo -e "\n\033[33m"Already exist IoTivity, Pulling latest"\033[0m" -cd ./src/discovery && git pull && cd ../../ -else -echo -e "\n\033[33m"Start cloning IoTivity"\033[0m" -cd ./src/discovery && git clone https://gerrit.iotivity.org/gerrit/iotivity -cd iotivity -git clone https://github.com/intel/tinycbor.git extlibs/tinycbor/tinycbor -b v0.5.1 -git clone https://github.com/ARMmbed/mbedtls.git extlibs/mbedtls/mbedtls -b mbedtls-2.4.2 -cd .. -echo -e "\n\033[33m"Succeed cloning IoTivity"\033[0m" -fi - -echo -e "\n\033[33m"Start building of IoTivity"\033[0m" - -cd iotivity && scons resource/csdk LOGGING=1 DEBUG=1 SECURED=0 WITH_TCP=1 && cd .. - -echo -e "\n\033[33m"Succeed building of IoTivity"\033[0m" diff --git a/src/discoverymgr/src/discovery/build_samsung_ocf.sh b/src/discoverymgr/src/discovery/build_samsung_ocf.sh deleted file mode 100644 index 95e8247..0000000 --- a/src/discoverymgr/src/discovery/build_samsung_ocf.sh +++ /dev/null @@ -1,30 +0,0 @@ -#!/bin/sh - -dir_name="./IoTivity" -arch=$(uname -m) -if test -d $dir_name -then -echo -e "\n\033[33m"Already exist IoTivity, Pulling latest"\033[0m" -cd ./src/discovery && git pull && cd ../../ -else -echo -e "\n\033[33m"Start cloning IoTivity"\033[0m" -cd ./src/discovery &&git clone -b 1.2-rel git@github.sec.samsung.net:RS7-IOTIVITY/IoTivity.git -cd IoTivity && git cherry-pick bcbce32c6e458e08f18761ab017153a697d67d92 && cd .. -rm -rf ./IoTivity/extlibs/gtest/gtest-1.7.0 - -GCC_VERSION=$(gcc -dumpversion) - -if [ $GCC_VERSION -ge 7 ] -then -cp ./IoTivity/resource/include/OCUtilities.h ./IoTivity/resource/include/OCUtilities_ori.h -sed -e s/\#include\ \/\#include\ \\\n\#include\ \/g ./IoTivity/resource/include/OCUtilities_ori.h > ./IoTivity/resource/include/OCUtilities.h -fi - -echo -e "\n\033[33m"Succeed cloning IoTivity"\033[0m" -fi - -echo -e "\n\033[33m"Start building of IoTivity"\033[0m" - -cd IoTivity && scons resource/csdk LOGGING=1 DEBUG=1 SECURED=0 WITH_TCP=1 && cd .. - -echo -e "\n\033[33m"Succeed building of IoTivity"\033[0m" diff --git a/src/discoverymgr/src/discovery/discovery.go b/src/discoverymgr/src/discovery/discovery.go deleted file mode 100644 index f72627a..0000000 --- a/src/discoverymgr/src/discovery/discovery.go +++ /dev/null @@ -1,754 +0,0 @@ -//Package discovery wraps main functions of IoTivity/ocstack with golang to use Discovery functions in go project. -package discovery - -/* - -#include -#include -#include -#include -#include -#include - -extern void cgo_discoverycallback(OCClientResponse * clientResponse); - -static int DuplicateString(char** targetString, const char* sourceString) -{ - if(!sourceString) - { - return false; - } - else - { - *targetString = (char *) malloc(strlen(sourceString) + 1); - - if(*targetString) - { - strncpy(*targetString, sourceString, (strlen(sourceString) + 1)); - return true; - } - } - return false; -} - -static void DeletePlatformInfo(OCPlatformInfo *platformInfo) -{ - free (platformInfo->manufacturerName); - free (platformInfo->platformID); - free (platformInfo->manufacturerUrl); - free (platformInfo->modelNumber); - free (platformInfo->dateOfManufacture); - free (platformInfo->platformVersion); - free (platformInfo->operatingSystemVersion); - free (platformInfo->hardwareVersion); - free (platformInfo->firmwareVersion); - free (platformInfo->supportUrl); - free (platformInfo->systemTime); -} - -static void DeleteDeviceInfo(OCDeviceInfo *deviceInfo) -{ - free (deviceInfo->deviceName); - free (deviceInfo->specVersion); - OCFreeOCStringLL (deviceInfo->dataModelVersions); -} - -static OCStackResult SetPlatformInfo(const char* platformID, const char *manufacturerName, - const char *manufacturerUrl, const char *modelNumber, const char *dateOfManufacture, - const char *platformVersion, const char* operatingSystemVersion, const char* hardwareVersion, - const char *firmwareVersion, const char* supportUrl, const char* systemTime) -{ - - OCPlatformInfo platformInfo; - - if(manufacturerName != NULL && (strlen(manufacturerName) > MAX_PLATFORM_NAME_LENGTH)) - { - return OC_STACK_INVALID_PARAM; - } - if(manufacturerUrl != NULL && (strlen(manufacturerUrl) > MAX_PLATFORM_URL_LENGTH)) - { - return OC_STACK_INVALID_PARAM; - } - DuplicateString(&platformInfo.platformID, platformID); - DuplicateString(&platformInfo.manufacturerName, manufacturerName); - DuplicateString(&platformInfo.manufacturerUrl, manufacturerUrl); - DuplicateString(&platformInfo.modelNumber, modelNumber); - DuplicateString(&platformInfo.dateOfManufacture, dateOfManufacture); - DuplicateString(&platformInfo.platformVersion, platformVersion); - DuplicateString(&platformInfo.operatingSystemVersion, operatingSystemVersion); - DuplicateString(&platformInfo.hardwareVersion, hardwareVersion); - DuplicateString(&platformInfo.firmwareVersion, firmwareVersion); - DuplicateString(&platformInfo.supportUrl, supportUrl); - DuplicateString(&platformInfo.systemTime, systemTime); - - int ret; - ret = OCSetPlatformInfo(platformInfo); - DeletePlatformInfo(&platformInfo); - return ret; - -} - -static OCStackResult SetDeviceInfo(const char* deviceName, const char* specVersion, const char* dataModelVersions, const char* types) -{ - OCDeviceInfo deviceInfo; - DuplicateString(&deviceInfo.deviceName, deviceName); - DuplicateString(&deviceInfo.specVersion, specVersion); - OCFreeOCStringLL(deviceInfo.dataModelVersions); - deviceInfo.dataModelVersions = OCCreateOCStringLL(dataModelVersions); - OCFreeOCStringLL(deviceInfo.types); - deviceInfo.types = OCCreateOCStringLL(types); - - int ret; - ret = OCSetDeviceInfo(deviceInfo); - DeleteDeviceInfo(&deviceInfo); - return ret; -} - -static OCStackResult cCreateResource( - void * handle, - const char * resourceTypeName, - const char * resourceInterfaceName, - const char * URI, - void * entityHandler, - void * callbackParam, - uint8_t resourceProperties) -{ - OCResourceHandle handler; - handler = (OCResourceHandle *)handle; - return OCCreateResource(&handler, resourceTypeName, resourceInterfaceName, URI, NULL,NULL, resourceProperties); -} - - -static OCStackApplicationResult discoverycallback(void *context, OCDoHandle handle, OCClientResponse * clientResponse) -{ - - cgo_discoverycallback(clientResponse); - - return OC_STACK_KEEP_TRANSACTION; -} - -static OCStackResult cDoResource(void * handle, - OCMethod method, - const char * requestURI, - OCPayload * payload) -{ - OCCallbackData callbackData; - callbackData.cb = discoverycallback; - callbackData.context = handle; - callbackData.cd = (void*)0; - - return OCDoResource((void*)0, method, requestURI, (void*)0, payload, CT_DEFAULT, OC_LOW_QOS, &callbackData, (void*)0, 0); -} - -*/ -import "C" - -import ( - "commons/logger" - "encoding/json" - "fmt" - "io/ioutil" - "os" - "runtime" - "strconv" - "sync" - "time" - "unsafe" -) - -//struct copy from OCF-------------------- -type OCMode int - -const ( - OC_SERVER OCMode = iota - OC_CLIENT_SERVER - OC_GATEWAY -) - -type OCTransportFlags int - -const ( - OC_DEFAULT_FLAGS OCTransportFlags = iota - OC_FLAG_SECURE - OC_IP_USE_V6 - OC_IP_USE_V4 - OC_MULTICAST - OC_SCOPE_INTERFACE - OC_SCOPE_LINK - OC_SCOPE_REALM - OC_SCOPE_ADMIN - OC_SCOPE_SITE - OC_SCOPE_ORG - OC_SCOPE_GLOBAL -) - -type OCTransportAdapter int - -const ( - OC_DEFAULT_ADAPTER OCTransportAdapter = iota - OC_ADAPTER_IP - OC_ADAPTER_GATT_BTLE - OC_ADAPTER_RFCOMM_BTEDR - OC_ADAPTER_TCP - OC_ADAPTER_NFC -) - -type OCPlatformInfo struct { - PlatformID string - ManufacturerName string - ManufacturerURL string - ModelNumber string - DateOfManufacture string - PlatformVersion string - OperatingSystemVersion string - HardwareVersion string - FirmwareVersion string - SupportURL string - SystemTime string -} - -type OCDeviceInfo struct { - DeviceName string - Types string - SpecVersion string - DataModelVersions string -} - -//-------------------- struct copy from OCF - -type Attribute struct { - DataType string - Values interface{} -} - -type Payload struct { - URI string - ResourceTypes []string - Intfs []string - Attr map[string]Attribute -} - -type Resource struct { - URI string - Types []string - Interfaces []string - Port int - Endpoint string -} - -func newResource() *Resource { - ret := new(Resource) - ret.Types = make([]string, 0) - ret.Interfaces = make([]string, 0) - - return ret -} - -func (r Resource) GetURI() string { - return r.URI -} - -func (r Resource) GetTypes() []string { - return r.Types -} - -func (r Resource) GetInterfaces() []string { - return r.Interfaces -} - -func (r Resource) GetEndpoint() string { - return r.Endpoint -} - -func (r Resource) GetPort() int { - return r.Port -} - -type response struct { - resources []Resource - payload Payload - wg sync.WaitGroup -} - -func newResponse() *response { - ret := new(response) - ret.resources = make([]Resource, 0) - ret.payload = Payload{} - - return ret -} - -type resourcesJSON struct { - URI string - Types []string -} - -type edgeJSON struct { - Port int - Endpoint string - Resources []resourcesJSON -} - -func newEdgeJSON() *edgeJSON { - ret := new(edgeJSON) - ret.Resources = make([]resourcesJSON, 0) - return ret -} - -const ( - multicastDiscoveryURL = "coap://224.0.1.187:5683/oic/res" - DiscoveryOutputJSON = "discoveryOutput.json" - presenceSecond = 30 -) - -type DiscoveryType int - -const ( - MULTICAST DiscoveryType = iota - UNICAST -) - -var mutex = &sync.Mutex{} -var isExitedProcess chan bool -var requests map[int32]*response - -func init() { - isExitedProcess = make(chan bool) - requests = make(map[int32]*response) -} - -//@TODO open default setting or not along with Tizen / LF -// 이 package의 ocf 인증 없이 디바이스(ex. TV)가 ocf 인증을 받을 수 있는가? -func getDefaultPlatformInfo() *OCPlatformInfo { - var platformInfo OCPlatformInfo - dateOfManufacture := "2016-01-15" - firmwareVersion := "myFirmwareVersion" - manufacturerName := "myName" - operatingSystemVersion := "myOS" - hardwareVersion := "myHardwareVersion" - platformID := "0A3E0D6F-DBF5-404E-8719-D6880042463A" - modelNumber := "myModelNumber" - platformVersion := "myPlatformVersion" - systemTime := "2015-05-15T11.04" - - platformInfo.DateOfManufacture = dateOfManufacture - platformInfo.FirmwareVersion = firmwareVersion - platformInfo.ManufacturerName = manufacturerName - platformInfo.OperatingSystemVersion = operatingSystemVersion - platformInfo.HardwareVersion = hardwareVersion - platformInfo.PlatformID = platformID - platformInfo.ModelNumber = modelNumber - platformInfo.PlatformVersion = platformVersion - platformInfo.SystemTime = systemTime - - return &platformInfo -} -func getDefaultDeviceInfo() *OCDeviceInfo { - var deviceInfo OCDeviceInfo - - specVersion := "core.1.1.0" - dataModelVersions := "res.1.1.0,sh.1.1.0" - deviceName := "myDeviceName" - types := "oic.d.edge" - - deviceInfo.DeviceName = deviceName - deviceInfo.SpecVersion = specVersion - deviceInfo.DataModelVersions = dataModelVersions - deviceInfo.Types = types - - return &deviceInfo -} -func SetPlatformInfo(platformInfo *OCPlatformInfo) { - logger.Logging(logger.DEBUG, "IN") - defer logger.Logging(logger.DEBUG, "OUT") - - cPlatformID := C.CString(platformInfo.PlatformID) - defer C.free(unsafe.Pointer(cPlatformID)) - - cManufacturerName := C.CString(platformInfo.ManufacturerName) - defer C.free(unsafe.Pointer(cManufacturerName)) - - cManufacturerURL := C.CString(platformInfo.ManufacturerURL) - defer C.free(unsafe.Pointer(cManufacturerURL)) - - cModelNumber := C.CString(platformInfo.ModelNumber) - defer C.free(unsafe.Pointer(cModelNumber)) - - cDateOfManufacture := C.CString(platformInfo.DateOfManufacture) - defer C.free(unsafe.Pointer(cDateOfManufacture)) - - cPlatformVersion := C.CString(platformInfo.PlatformVersion) - defer C.free(unsafe.Pointer(cPlatformVersion)) - - cOperatingSystemVersion := C.CString(platformInfo.OperatingSystemVersion) - defer C.free(unsafe.Pointer(cOperatingSystemVersion)) - - cHardwareVersion := C.CString(platformInfo.HardwareVersion) - defer C.free(unsafe.Pointer(cHardwareVersion)) - - cFirmwareVersion := C.CString(platformInfo.FirmwareVersion) - defer C.free(unsafe.Pointer(cFirmwareVersion)) - - cSupportURL := C.CString(platformInfo.SupportURL) - defer C.free(unsafe.Pointer(cSupportURL)) - - cSystemTime := C.CString(platformInfo.SystemTime) - defer C.free(unsafe.Pointer(cSystemTime)) - - ret := C.SetPlatformInfo(cPlatformID, - cManufacturerName, - cManufacturerURL, - cModelNumber, - cDateOfManufacture, - cPlatformVersion, - cOperatingSystemVersion, - cHardwareVersion, - cFirmwareVersion, - cSupportURL, - cSystemTime) - if ret != C.OC_STACK_OK { - logger.Logging(logger.DEBUG, "ERROR::"+strconv.Itoa(int(ret))) - } -} - -func SetDeviceInfo(deviceInfo *OCDeviceInfo) { - logger.Logging(logger.DEBUG, "IN") - defer logger.Logging(logger.DEBUG, "OUT") - - cDeviceName := C.CString(deviceInfo.DeviceName) - defer C.free(unsafe.Pointer(cDeviceName)) - - cSpecVersion := C.CString(deviceInfo.SpecVersion) - defer C.free(unsafe.Pointer(cSpecVersion)) - - cDataModelVersions := C.CString(deviceInfo.DataModelVersions) - defer C.free(unsafe.Pointer(cDataModelVersions)) - - cTypes := C.CString(deviceInfo.Types) - defer C.free(unsafe.Pointer(cTypes)) - - ret := C.SetDeviceInfo(cDeviceName, cSpecVersion, cDataModelVersions, cTypes) - if ret != C.OC_STACK_OK { - logger.Logging(logger.DEBUG, "ERROR::"+strconv.Itoa(int(ret))) - } -} - -func runProcess() { - go func() { - for { - select { - case <-isExitedProcess: - break - default: - C.OCProcess() - time.Sleep(100 * time.Millisecond) - runtime.Gosched() - } - } - }() -} - -//Stop terminates oCProcess goroutine -func Stop() { - isExitedProcess <- true -} - -func Init(ipAddr string, port uint16, mode OCMode) { - logger.Logging(logger.DEBUG, "IN") - defer logger.Logging(logger.DEBUG, "OUT") - - cipAddr := C.CString(ipAddr) - defer C.free(unsafe.Pointer(cipAddr)) - cport := C.uint16_t(port) - cmode := C.OCMode(mode) - - ret := C.OCInit(cipAddr, cport, cmode) - if ret != C.OC_STACK_OK { - logger.Logging(logger.DEBUG, "ERROR::"+strconv.Itoa(int(ret))) - } -} - -func Init1(mode OCMode, serverFlags OCTransportFlags, clientFlags OCTransportFlags) { - logger.Logging(logger.DEBUG, "IN") - defer logger.Logging(logger.DEBUG, "OUT") - cmode := C.OCMode(mode) - cserverFlags := C.OCTransportFlags(serverFlags) - cclientFlags := C.OCTransportFlags(clientFlags) - - ret := C.OCInit1(cmode, cserverFlags, cclientFlags) - if ret != C.OC_STACK_OK { - logger.Logging(logger.DEBUG, "ERROR::"+strconv.Itoa(int(ret))) - } -} - -func Init2(mode OCMode, serverFlags OCTransportFlags, clientFlags OCTransportFlags, transportType OCTransportAdapter) { - logger.Logging(logger.DEBUG, "IN") - defer logger.Logging(logger.DEBUG, "OUT") - cmode := C.OCMode(mode) - cserverFlags := C.OCTransportFlags(serverFlags) - cclientFlags := C.OCTransportFlags(clientFlags) - ctransportType := C.OCTransportAdapter(transportType) - - ret := C.OCInit2(cmode, cserverFlags, cclientFlags, ctransportType) - if ret != C.OC_STACK_OK { - logger.Logging(logger.DEBUG, "ERROR::"+strconv.Itoa(int(ret))) - } -} - -//Start do server-client init, set device/platform info, run oCProcess -func Start(platformInfo *OCPlatformInfo, deviceInfo *OCDeviceInfo) { - Init1(2, 0, 0) - - if platformInfo == nil { - platformInfo = getDefaultPlatformInfo() - } - SetPlatformInfo(platformInfo) - if deviceInfo == nil { - deviceInfo = getDefaultDeviceInfo() - } - SetDeviceInfo(deviceInfo) - - C.OCStartPresence(C.uint32_t(presenceSecond)) - - runProcess() -} - -//Discovery discovers resources via multicast/unicast -func Discovery(discoveryType DiscoveryType, query string, ips ...string) { - logger.Logging(logger.DEBUG, "IN") - defer logger.Logging(logger.DEBUG, "OUT") - - var URI string - - switch discoveryType { - case MULTICAST: - URI = multicastDiscoveryURL - logger.Logging(logger.DEBUG, "MULTICAST URI", URI) - - if len(query) > 0 { - URI += "?rt=" + query - } - discoveryImpl(URI) - - case UNICAST: - for _, ip := range ips { - URI = "coap://" + ip + ":5683/oic/res" - logger.Logging(logger.DEBUG, "UNICAST URI", URI) - - if len(query) > 0 { - URI += "?rt=" + query - } - discoveryImpl(URI) - } - } - -} - -func discoveryImpl(URI string) { - logger.Logging(logger.DEBUG, "IN") - defer logger.Logging(logger.DEBUG, "OUT") - - cHandle := C.int(0) - - cStr := C.CString(URI) - defer C.free(unsafe.Pointer(cStr)) - - ret := C.cDoResource(unsafe.Pointer(&cHandle), C.OC_REST_DISCOVER, cStr, nil) - if ret != C.OC_STACK_OK { - logger.Logging(logger.DEBUG, "ERROR::"+strconv.Itoa(int(ret))) - } -} - -//CreateResource creates ocf resource. it uses default entity handler. -func CreateResource(handle unsafe.Pointer, - resourceTypeName string, - resourceInterfaceName string, - URI string, - resourceProperties uint8) { - logger.Logging(logger.DEBUG, "IN") - defer logger.Logging(logger.DEBUG, "OUT") - - cresourceTypeName := C.CString(resourceTypeName) - defer C.free(unsafe.Pointer(cresourceTypeName)) - cresourceInterfaceName := C.CString(resourceInterfaceName) - defer C.free(unsafe.Pointer(cresourceInterfaceName)) - cURI := C.CString(URI) - defer C.free(unsafe.Pointer(cURI)) - cresourceProperties := C.uint8_t(resourceProperties) - - ret := C.cCreateResource(handle, cresourceTypeName, cresourceInterfaceName, cURI, nil, nil, cresourceProperties) - if ret != C.OC_STACK_OK { - logger.Logging(logger.DEBUG, "ERROR::"+strconv.Itoa(int(ret))) - } - -} - -//export cgo_discoverycallback -func cgo_discoverycallback(clientResponse *C.OCClientResponse) { - logger.Logging(logger.DEBUG, "IN") - defer logger.Logging(logger.DEBUG, "OUT") - cliResp := newResponse() - if clientResponse.result != C.OC_STACK_OK { - logger.Logging(logger.DEBUG, "clientResponse.result != C.OC_STACK_OK, result is "+strconv.Itoa(int(clientResponse.result))) - return - } else { - logger.Logging(logger.DEBUG, "clientResponse.result == C.OC_STACK_OK") - } - - if clientResponse.payload == nil { - logger.Logging(logger.ERROR, "clientResponse.payload is nil") - return - } - - payload := (*C.OCDiscoveryPayload)(unsafe.Pointer(clientResponse.payload)) - if payload == nil { - logger.Logging(logger.ERROR, "OCDiscoveryPayload is null") - return - } - - if payload.resources == nil { - logger.Logging(logger.ERROR, "OCDiscoveryPayload.resources is nil") - return - } - - resource := (*C.OCResourcePayload)(unsafe.Pointer(payload.resources)) - fmt.Println(resource) - if resource == nil { - logger.Logging(logger.ERROR, "OCResourcePayload is nil") - return - } - - addr := string(C.GoBytes(unsafe.Pointer(&clientResponse.devAddr.addr), 66)[:]) - endpoint := "" - for idx := range addr { - if _, err := strconv.Atoi(string([]rune(addr)[idx])); err == nil { - endpoint += string([]rune(addr)[idx]) - } else if string([]rune(addr)[idx]) == "." { - endpoint += string([]rune(addr)[idx]) - } else { - break - } - } - port := int(clientResponse.devAddr.port) - - for { - if resource == nil { - logger.Logging(logger.DEBUG, "clientResponse.OCResourcePayload == nil") - break - } - - URI := C.GoString(resource.uri) - if (URI == "/oic/sec/pstat") || - (URI == "/oic/sec/doxm") || - (URI == "/oic/sec/sp") || - (URI == "/oic/sec/acl2") || - (URI == "/oic/sec/cred") || - (URI == "/oic/p") { - resource = resource.next - // logger.Logging(logger.DEBUG, "Unnecessary URI "+URI) - continue - } - - r := Resource{} - r.URI = URI - r.Endpoint = endpoint - r.Port = port - C.fflush(C.stdout) - - t := resource.types - for { - if t == nil { - break - } - r.Types = append(r.Types, C.GoString(t.value)) - - t = t.next - } - - i := resource.interfaces - for { - if i == nil { - break - } - r.Interfaces = append(r.Interfaces, C.GoString(i.value)) - - i = i.next - } - - cliResp.resources = append(cliResp.resources, r) - logger.Logging(logger.DEBUG, "new device::"+r.GetEndpoint()+":"+strconv.Itoa(r.GetPort())) - resource = resource.next - } - - mutex.Lock() - defer mutex.Unlock() - edgeJSONWriter(cliResp.resources) -} - -func convertResourceToEdge(resources []Resource) *edgeJSON { - logger.Logging(logger.DEBUG, "IN") - defer logger.Logging(logger.DEBUG, "OUT") - edgeData := newEdgeJSON() - edgeData.Port = resources[0].GetPort() - edgeData.Endpoint = resources[0].GetEndpoint() - - r := new(resourcesJSON) - for _, res := range resources { - r.URI = res.URI - r.Types = make([]string, len(res.Types)) - copy(r.Types, res.Types) - edgeData.Resources = append(edgeData.Resources, *r) - } - - return edgeData -} - -func edgeJSONWriter(resources []Resource) { - logger.Logging(logger.DEBUG, "IN") - defer logger.Logging(logger.DEBUG, "OUT") - - f, err := os.OpenFile(DiscoveryOutputJSON, os.O_CREATE|os.O_WRONLY, 0644) - if err != nil { - logger.Logging(logger.DEBUG, "OpenFile err::"+err.Error()) - return - } - defer f.Close() - - data, err := ioutil.ReadFile(DiscoveryOutputJSON) - if err != nil { - logger.Logging(logger.DEBUG, "ioutil.ReadFile err::"+err.Error()) - return - } - - datalen := len(data) - logger.Logging(logger.DEBUG, "output file data size::"+strconv.Itoa(datalen)) - - var existingData []edgeJSON - - if datalen != 0 { - err = json.Unmarshal(data, &existingData) - if err != nil { - logger.Logging(logger.DEBUG, "json.Unmarshal err::"+err.Error()) - return - } - - for _, edge := range existingData { - if edge.Port == resources[0].GetPort() && edge.Endpoint == resources[0].GetEndpoint() { - logger.Logging(logger.DEBUG, "Discovered Resource is Repeated") - return - } - } - - } - edgeJSONData := convertResourceToEdge(resources) - newData := append(existingData, *edgeJSONData) - newDataJSON, _ := json.MarshalIndent(newData, "", " ") - - logger.Logging(logger.DEBUG, "newDataJSON size::"+strconv.Itoa(len(newDataJSON))) - - _, err = f.Write(newDataJSON) - if err != nil { - logger.Logging(logger.DEBUG, "iotuil err::"+err.Error()) - return - } -} diff --git a/src/discoverymgr/src/discovery/iotivity b/src/discoverymgr/src/discovery/iotivity deleted file mode 160000 index 2d7a352..0000000 --- a/src/discoverymgr/src/discovery/iotivity +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 2d7a35274cb19a48b82edc1357ebe6da1e3e0f01 diff --git a/src/discoverymgr/src/main/main.go b/src/discoverymgr/src/main/main.go deleted file mode 100644 index e56d4a6..0000000 --- a/src/discoverymgr/src/main/main.go +++ /dev/null @@ -1,63 +0,0 @@ -package main - -import ( - "discovery" - "time" -) - -func setPlatformInfo() *discovery.OCPlatformInfo { - var platformInfo discovery.OCPlatformInfo - dateOfManufacture := "2016-01-15" - firmwareVersion := "myFirmwareVersion" - manufacturerName := "myName" - operatingSystemVersion := "myOS" - hardwareVersion := "myHardwareVersion" - platformID := "0A3E0D6F-DBF5-404E-8719-D6880042463A" - modelNumber := "myModelNumber" - platformVersion := "myPlatformVersion" - systemTime := "2015-05-15T11.04" - - platformInfo.DateOfManufacture = dateOfManufacture - platformInfo.FirmwareVersion = firmwareVersion - platformInfo.ManufacturerName = manufacturerName - platformInfo.OperatingSystemVersion = operatingSystemVersion - platformInfo.HardwareVersion = hardwareVersion - platformInfo.PlatformID = platformID - platformInfo.ModelNumber = modelNumber - platformInfo.PlatformVersion = platformVersion - platformInfo.SystemTime = systemTime - - return &platformInfo -} -func setDeviceInfo() *discovery.OCDeviceInfo { - var deviceInfo discovery.OCDeviceInfo - - specVersion := "core.1.1.0" - dataModelVersions := "res.1.1.0,sh.1.1.0" - deviceName := "myDeviceName" - types := "oic.d.edge" - - deviceInfo.DeviceName = deviceName - deviceInfo.SpecVersion = specVersion - deviceInfo.DataModelVersions = dataModelVersions - deviceInfo.Types = types - - return &deviceInfo -} -func main() { - /*Use Default Info*/ - // discovery.OCStart(nil, nil) - /*Set Platform Device Info*/ - platformInfo := setPlatformInfo() - deviceInfo := setDeviceInfo() - discovery.Start(platformInfo, deviceInfo) - - /*Multicast*/ - discovery.Discovery(0, "", "") - /*Unicast*/ - // discovery.Discovery(1,"","10.113.175.92") - - time.Sleep(10000 * time.Millisecond) - - discovery.Stop() -} diff --git a/src/discoverymgr/test/device_discovery_test.go b/src/discoverymgr/test/device_discovery_test.go new file mode 100644 index 0000000..b999c67 --- /dev/null +++ b/src/discoverymgr/test/device_discovery_test.go @@ -0,0 +1,55 @@ +package test + +import ( + dm "discoverymgr" + "testing" +) + +var data = dm.AppReturnInfo{ + AppName: "GreetWorldApp", + DeviceList: []dm.DeviceReturnInfo{ + { + DeviceID: 1, + DeviceName: "hello world#1", + Status: "started", + DeviceIP: "10.113.175.144", + }, + { + DeviceID: 2, + DeviceName: "hello world#2", + Status: "progressing", + DeviceIP: "10.113.175.144", + }, + }, +} + +func TestDeviceList(t *testing.T) { + registerCh := make(chan error) + ServiceNames := []string{"Distributed Web Engine", "Television", "Soundbox"} + go RegisterDevice(ServiceNames, registerCh) + if err := <-registerCh; err != nil { + t.Error("fail") + } + + ret, err := dm.DeviceList() + if err != nil { + t.Error("fail") + return + } + t.Log(ret) + if len(ret) != 1 { + t.Error("fail") + } + + ExitChan <- 1 + + ret, err = dm.DeviceList() + if err != nil { + t.Error("fail") + return + } + t.Log(ret) + if len(ret) != 0 { + t.Error("fail") + } +} diff --git a/src/discoverymgr/types.go b/src/discoverymgr/types.go new file mode 100644 index 0000000..a92958c --- /dev/null +++ b/src/discoverymgr/types.go @@ -0,0 +1,18 @@ +//Package discoverymgr wraps main functions of IoTivity/ocstack with golang to use Discovery functions in go project. +package discoverymgr + +// SimpleResponse structure +type SimpleResponse struct { + Return string `json:"Return"` +} + +//DeviceReturnList structure +type DeviceReturnList struct { + ListOfDevices []DeviceReturnInfo `json:"ListOfDevices"` +} + +// DeviceReturnInfo structure +type DeviceReturnInfo struct { + DeviceIP string `json:"DeviceIP"` + ServiceNames []string `json:"ServiceNames"` +} diff --git a/src/orchestration/main.go b/src/orchestration/main.go index 9b3446c..1395b47 100644 --- a/src/orchestration/main.go +++ b/src/orchestration/main.go @@ -11,6 +11,7 @@ package main import ( "devicemgr" + "discoverymgr" "log" "net/http" restapi "restapi/v1" @@ -22,7 +23,7 @@ func main() { devicemgr.InitDeviceMgr() servicemgr.InitServiceMap() - + discoverymgr.InitDiscovery() router := restapi.NewRouter() log.Fatal(http.ListenAndServe(":9090", router)) diff --git a/src/restapi/v1/restapi.go b/src/restapi/v1/restapi.go index a6afa65..3b57d19 100644 --- a/src/restapi/v1/restapi.go +++ b/src/restapi/v1/restapi.go @@ -11,6 +11,7 @@ package v1 import ( "devicemgr" + "discoverymgr" "encoding/json" "errors" "log" @@ -67,6 +68,17 @@ func APIV1DiscoverymgrDevicesDeviceIDGet(w http.ResponseWriter, r *http.Request) // APIV1DiscoverymgrDevicesGet function func APIV1DiscoverymgrDevicesGet(w http.ResponseWriter, r *http.Request) { log.Printf("[%s] APIV1DiscoverymgrDevicesGet", logPrefix) + ret, err := discoverymgr.DeviceList() + if err != nil { + writeJSONResponse(w, nil, http.StatusBadRequest) + } + + json, err := json.Marshal(ret) + if err == nil { + writeJSONResponse(w, json, http.StatusOK) + } else { + writeJSONResponse(w, nil, http.StatusBadRequest) + } } // APIV1ServicemgrServicesDelete function diff --git a/vendor/vendor b/vendor/vendor new file mode 120000 index 0000000..60b27ce --- /dev/null +++ b/vendor/vendor @@ -0,0 +1 @@ +/home/damon/share/1_working/tmp/edge-home-orchestration-go/vendor \ No newline at end of file -- 2.7.4