diff --git a/UAV_softbus_client/README.md b/UAV_softbus_client/README.md new file mode 100644 index 0000000000000000000000000000000000000000..899d496e4eaac281ee381ae995d3d5cf23cc8a9a --- /dev/null +++ b/UAV_softbus_client/README.md @@ -0,0 +1,40 @@ +# UAV_softbus_client + +#### 介绍 +本仓库通过软总线的基础通信功能,调用MAVSDK控制无人机,实现了同一组网下使用OpenHarmony设备操控无人机起飞,悬停和降落的功能。 + +#### 软件架构 +软件架构说明 + + +#### 安装教程 + +1. 安装分布式软总线:https://gitee.com/src-openeuler/dsoftbus +2. 安装mavlink/MAVSDK:https://github.com/mavlink/MAVSDK +3. 运行build.sh脚本:./build.sh +4. 启动分布式软总线服务端:softbus_server_main +5. 启动mavlink:mavlink-router +6. 启动无人机软总线客户端:cd out && ./softbus_client + +#### 使用说明 + +1. xxxx +2. xxxx +3. xxxx + +#### 参与贡献 + +1. Fork 本仓库 +2. 新建 Feat_xxx 分支 +3. 提交代码 +4. 新建 Pull Request + + +#### 特技 + +1. 使用 Readme\_XXX.md 来支持不同的语言,例如 Readme\_en.md, Readme\_zh.md +2. Gitee 官方博客 [blog.gitee.com](https://blog.gitee.com) +3. 你可以 [https://gitee.com/explore](https://gitee.com/explore) 这个地址来了解 Gitee 上的优秀开源项目 +4. [GVP](https://gitee.com/gvp) 全称是 Gitee 最有价值开源项目,是综合评定出的优秀开源项目 +5. Gitee 官方提供的使用手册 [https://gitee.com/help](https://gitee.com/help) +6. Gitee 封面人物是一档用来展示 Gitee 会员风采的栏目 [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/) diff --git a/UAV_softbus_client/devicemanager/devicemanager b/UAV_softbus_client/devicemanager/devicemanager new file mode 100644 index 0000000000000000000000000000000000000000..2dcd4e05b4cb5bdc794bce93f637d87325e88161 Binary files /dev/null and b/UAV_softbus_client/devicemanager/devicemanager differ diff --git a/UAV_softbus_client/hichain/hichain_main b/UAV_softbus_client/hichain/hichain_main new file mode 100644 index 0000000000000000000000000000000000000000..f1b79ebb9e641be7b2b15f05a40ab1149f8fbe66 Binary files /dev/null and b/UAV_softbus_client/hichain/hichain_main differ diff --git a/UAV_softbus_client/hichain/hichain_main.c b/UAV_softbus_client/hichain/hichain_main.c new file mode 100644 index 0000000000000000000000000000000000000000..acc0a127affd7451115b6f6f403ac592bd7f8aa4 --- /dev/null +++ b/UAV_softbus_client/hichain/hichain_main.c @@ -0,0 +1,639 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#define APP_ID "hichain_test" +#define SESSION_NAME "com.huawei.devicegroupmanage.test" +#define DEFAULT_CAPABILITY "osdCapability" +#define PUBLISH_ID 100 + +#define DEFAULT_GROUP_NAME "dsoftbus" +#define DEFAULT_PIN_CODE "123456" +#define MAX_UDID_LEN 65 +#define MAX_GROUP_LEN 65 +#define ERR_RET -1 + +#define FIELD_ETH_IP "ETH_IP" +#define FIELD_ETH_PORT "ETH_PORT" +#define FIELD_WLAN_IP "WIFI_IP" +#define FIELD_WLAN_PORT "WIFI_PORT" + +enum { + DEVICE_DISCOVERY = 0, + DEVICE_JOINING, + DEVICE_ONLINE, +}DeviceStatus; + +char *g_deviceStatus[] = { + "discovery", + "joining", + "online", +}; + +typedef struct DeviceList { + struct DeviceList *next; + DeviceInfo device; + int status; + int64_t requestId; +} DeviceList; +DeviceList *g_deviceListHead = NULL; + +static const DeviceGroupManager *g_hichainGmInstance = NULL; +static char g_udid[MAX_UDID_LEN]; +static char g_groupId[MAX_GROUP_LEN]; +static int64_t g_requestId = 1; + +static const char *GetStringFromJson(const cJSON *obj, const char *key) +{ + cJSON *item; + + if (obj == NULL || key == NULL) + return NULL; + + item = cJSON_GetObjectItemCaseSensitive(obj, key); + if (item != NULL && cJSON_IsString(item)) { + return cJSON_GetStringValue(item); + } else { + int len = cJSON_GetArraySize(obj); + for (int i = 0; i < len; i++) { + item = cJSON_GetArrayItem(obj, i); + if (cJSON_IsObject(item)) { + const char *value = GetStringFromJson(item, key); + if (value != NULL) + return value; + } + } + } + return NULL; +} + +static int HichainSaveGroupID(const char *param) +{ + cJSON *msg = cJSON_Parse(param); + const char *value = NULL; + + if (msg == NULL) { + printf("HichainSaveGroupID: cJSON_Parse fail\n"); + return ERR_RET; + } + + value = GetStringFromJson(msg, FIELD_GROUP_ID); + if (value == NULL) { + printf("HichainSaveGroupID:GetStringFromJson fail\n"); + cJSON_Delete(msg); + return ERR_RET; + } + + memcpy_s(g_groupId, MAX_GROUP_LEN, value, strlen(value)); + printf("HichainSaveGroupID:groupID=%s\n", g_groupId); + + cJSON_Delete(msg); + return 0; +} + +static void HiChainGmOnFinish(int64_t requestId, int operationCode, const char *returnData) +{ + if (operationCode == GROUP_CREATE && returnData != NULL) { + printf("create new group finish:requestId=%lld, returnData=%s\n", requestId, returnData); + HichainSaveGroupID(returnData); + } else if (operationCode == MEMBER_JOIN) { + DeviceList *node = g_deviceListHead; + + printf("member join finish:requestId=%lld, returnData=%s\n", requestId, returnData); + while (node) { + if (node->requestId != requestId) { + node = node->next; + continue; + } + node->status = DEVICE_ONLINE; + break; + } + } else { + printf("CB:requestId=%lld, operationCode=%d, returnData=%s\n", requestId, operationCode, returnData); + } +} + +static void HiChainGmOnError(int64_t requestId, int operationCode, int errorCode, const char *errorReturn) +{ + DeviceList *node = g_deviceListHead; + + printf("CB:requestId=%lld, operationCode=%d, errorCode=%d, errorReturn=%s\n", requestId, operationCode, errorCode, errorReturn); + while (node) { + if (node->requestId != requestId) { + node = node->next; + continue; + } + node->status = DEVICE_DISCOVERY; + break; + } +} + +static char *HiChainGmOnRuest(int64_t requestId, int operationCode, const char *reqParams) +{ + cJSON *msg = cJSON_CreateObject(); + char *param = NULL; + + printf("CB:requestId=%lld, operationCode=%d, reqParams=%s", requestId, operationCode, reqParams); + + if (operationCode != MEMBER_JOIN) { + return NULL; + } + + if (msg == NULL) { + printf("HiChainGmOnRuest: cJSON_CreateObject fail\n"); + } + + if (cJSON_AddNumberToObject(msg, FIELD_CONFIRMATION, REQUEST_ACCEPTED) == NULL || + cJSON_AddStringToObject(msg, FIELD_PIN_CODE, DEFAULT_PIN_CODE) == NULL || + cJSON_AddStringToObject(msg, FIELD_DEVICE_ID, g_udid) == NULL) { + printf("HiChainGmOnRuest: cJSON_AddToObject fail\n"); + cJSON_Delete(msg); + return NULL; + } + + param = cJSON_PrintUnformatted(msg); + cJSON_Delete(msg); + return param; +} + +static const DeviceAuthCallback g_groupManagerCallback = { + .onRequest = HiChainGmOnRuest, + .onError = HiChainGmOnError, + .onFinish = HiChainGmOnFinish, +}; + +static int HichainGmRegCallback(void) +{ + return g_hichainGmInstance->regCallback(APP_ID, &g_groupManagerCallback); +} + +static void HichainGmUnRegCallback(void) +{ + g_hichainGmInstance->unRegCallback(APP_ID); +} + +static int HichainGmGetGroupInfo(char **groupVec, uint32_t *num) +{ + cJSON *msg = cJSON_CreateObject(); + char *param = NULL; + int ret = ERR_RET; + + if (msg == NULL) { + printf("HichainGmGetGroupInfo: cJSON_CreateObject fail\n"); + return ret; + } + + if (cJSON_AddNumberToObject(msg, FIELD_GROUP_TYPE, PEER_TO_PEER_GROUP) == NULL || + cJSON_AddStringToObject(msg, FIELD_GROUP_NAME, DEFAULT_GROUP_NAME) == NULL || + cJSON_AddNumberToObject(msg, FIELD_GROUP_VISIBILITY, GROUP_VISIBILITY_PUBLIC) == NULL) { + printf("HichainGmGetGroupInfo: cJSON_AddToObject fail\n"); + goto err_cJSON_Delete; + } + param = cJSON_PrintUnformatted(msg); + if (param == NULL) { + printf("HichainGmGetGroupInfo: cJSON_PrintUnformatted fail\n"); + goto err_cJSON_Delete; + } + + ret = g_hichainGmInstance->getGroupInfo(ANY_OS_ACCOUNT, APP_ID, param, groupVec, num); + if (ret != 0) { + printf("getGroupInfo fail:%d", ret); + goto err_getGroupInfo; + } + +err_getGroupInfo: + cJSON_free(param); +err_cJSON_Delete: + cJSON_Delete(msg); + return ret; +} + +static void HichainGmDestroyGroupInfo(char **groupVec) +{ + g_hichainGmInstance->destroyInfo(groupVec); +} + +static int HichainGmCreatGroup(void) +{ + cJSON *msg = cJSON_CreateObject(); + char *param = NULL; + int ret = ERR_RET; + + if (msg == NULL) + return ret; + + if (cJSON_AddNumberToObject(msg, FIELD_GROUP_TYPE, PEER_TO_PEER_GROUP) == NULL || + cJSON_AddStringToObject(msg, FIELD_DEVICE_ID, g_udid) == NULL || + cJSON_AddStringToObject(msg, FIELD_GROUP_NAME, DEFAULT_GROUP_NAME) == NULL || + cJSON_AddNumberToObject(msg, FIELD_USER_TYPE, 0) == NULL || + cJSON_AddNumberToObject(msg, FIELD_GROUP_VISIBILITY, GROUP_VISIBILITY_PUBLIC) == NULL || + cJSON_AddNumberToObject(msg, FIELD_EXPIRE_TIME, EXPIRE_TIME_MAX) == NULL) { + printf("HichainGmCreatGroup: cJSON_AddToObject fail\n"); + cJSON_Delete(msg); + return ret; + } + param = cJSON_PrintUnformatted(msg); + if (param == NULL) { + printf("HichainGmCreatGroup: cJSON_PrintUnformatted fail\n"); + cJSON_Delete(msg); + return ret; + } + + ret = g_hichainGmInstance->createGroup(ANY_OS_ACCOUNT, g_requestId++, APP_ID, param); + + cJSON_free(param); + cJSON_Delete(msg); + return ret; +} + +static bool HichainIsDeviceInGroup(const char *groupId, const char *devId) +{ + return g_hichainGmInstance->isDeviceInGroup(ANY_OS_ACCOUNT, APP_ID, groupId, devId); +} + +static int HichainGmAddMemberToGroup(DeviceInfo *device, const char *groupId) +{ + cJSON *msg = cJSON_CreateObject(); + cJSON *addr = NULL; + char *param = NULL; + int ret = ERR_RET; + + if (msg == NULL) { + printf("HichainGmAddMemberToGroup: cJSON_CreateObject1 fail\n"); + return ret; + } + + addr = cJSON_CreateObject(); + if (addr == NULL) { + printf("HichainGmAddMemberToGroup: cJSON_CreateObject2 fail\n"); + goto err_cJSON_CreateObject; + } + + for (unsigned int i = 0; i < device->addrNum; i++) { + if (device->addr[i].type == CONNECTION_ADDR_ETH) { + if (cJSON_AddStringToObject(addr, FIELD_ETH_IP, device->addr[i].info.ip.ip) == NULL || + cJSON_AddNumberToObject(addr, FIELD_ETH_PORT, device->addr[i].info.ip.port) == NULL) { + printf("HichainGmAddMemberToGroup: cJSON_AddToObject1 fail\n"); + goto err_cJSON_AddToObject; + } + } else if (device->addr[i].type == CONNECTION_ADDR_WLAN) { + if (cJSON_AddStringToObject(addr, FIELD_WLAN_IP, device->addr[i].info.ip.ip) == NULL || + cJSON_AddNumberToObject(addr, FIELD_WLAN_PORT, device->addr[i].info.ip.port) == NULL) { + printf("HichainGmAddMemberToGroup: cJSON_AddToObject2 fail\n"); + goto err_cJSON_AddToObject; + } + } else { + printf("unsupport connection type:%d\n", device->addr[i].type); + goto err_cJSON_AddToObject; + } + } + + param = cJSON_PrintUnformatted(addr); + if (param == NULL) { + printf("HichainGmAddMemberToGroup: cJSON_PrintUnformatted1 fail\n"); + goto err_cJSON_AddToObject; + } + + if (cJSON_AddStringToObject(msg, FIELD_GROUP_ID, groupId) == NULL || + cJSON_AddNumberToObject(msg, FIELD_GROUP_TYPE, PEER_TO_PEER_GROUP) == NULL || + cJSON_AddStringToObject(msg, FIELD_PIN_CODE, DEFAULT_PIN_CODE) == NULL || + cJSON_AddStringToObject(msg, FIELD_DEVICE_ID, g_udid) == NULL || + cJSON_AddStringToObject(msg, FIELD_GROUP_NAME, DEFAULT_GROUP_NAME) == NULL || + cJSON_AddBoolToObject(msg, FIELD_IS_ADMIN, false) == NULL || + cJSON_AddStringToObject(msg, FIELD_CONNECT_PARAMS, param) == NULL) { + printf("HichainGmAddMemberToGroup: cJSON_AddToObject4 fail\n"); + goto err_cJSON_AddToObject1; + } + + cJSON_free(param); + param = cJSON_PrintUnformatted(msg); + if (param == NULL) { + printf("HichainGmAddMemberToGroup: cJSON_PrintUnformatted fail\n"); + goto err_cJSON_CreateObject; + } + + ret = g_hichainGmInstance->addMemberToGroup(ANY_OS_ACCOUNT, g_requestId++, APP_ID, param); + if (ret != 0) { + printf("addMemberToGroup fail:%d\n", ret); + } + +err_cJSON_AddToObject1: + cJSON_free(param); +err_cJSON_AddToObject: + cJSON_Delete(addr); +err_cJSON_CreateObject: + cJSON_Delete(msg); + return ret; +} + +static int HichainInit(void) +{ + char *groupVec = NULL; + uint32_t num; + int ret; + + ret = InitDeviceAuthService(); + if (ret != 0) { + printf("InitDeviceAuthService fail:%d\n", ret); + return ret; + } + + g_hichainGmInstance = GetGmInstance(); + if (g_hichainGmInstance == NULL) { + printf("GetGmInstance fail\n"); + ret = ERR_RET; + goto err_GetGmInstance; + } + + ret = HichainGmRegCallback(); + if (ret != 0) { + printf("HichainGmregCallback fail.:%d\n", ret); + goto err_HichainGmRegCallback; + } + + ret = HichainGmGetGroupInfo(&groupVec, &num); + if (ret != 0) { + printf("HichainGmGetGroupInfo fail:%d\n", ret); + goto err_HichainGmGetGroupInfo; + } + + if (num == 0) { + ret = HichainGmCreatGroup(); + if (ret) { + printf("HichainGmCreatGroup fail:%d\n", ret); + goto err_HichainGmCreatGroup; + } + } else { + printf("HichainGmGetGroupInfo:num=%u\n", num); + HichainSaveGroupID(groupVec); + HichainGmDestroyGroupInfo(&groupVec); + } + + return 0; + +err_HichainGmCreatGroup: +err_HichainGmGetGroupInfo: + HichainGmUnRegCallback(); +err_HichainGmRegCallback: +err_GetGmInstance: + DestroyDeviceAuthService(); + return ret; +} + +static void CheckDeviceStatus(void) +{ + DeviceList *node = g_deviceListHead; + char *groupVec = NULL; + uint32_t num; + int ret; + + ret = HichainGmGetGroupInfo(&groupVec, &num); + if (ret != 0 || num == 0) { + printf("HichainGmGetGroupInfo fail\n"); + return; + } + + ret = HichainSaveGroupID(groupVec); + if (ret != 0) + goto err_HichainSaveGroupID; + + while (node) { + if (HichainIsDeviceInGroup(g_groupId, node->device.devId)) { + node->status = DEVICE_ONLINE; + } + node = node->next; + } + +err_HichainSaveGroupID: + HichainGmDestroyGroupInfo(&groupVec); +} + +static bool CheckDeviceExist(const DeviceInfo *device) +{ + DeviceList *node = g_deviceListHead; + + while (node) { + if (strcmp(device->devId, node->device.devId) == 0) { + return true; + } + node = node->next; + } + return false; +} + +static void SaveDeviceInfo(const DeviceInfo *device) +{ + DeviceList *node = malloc(sizeof(DeviceList)); + + if (node == NULL) { + printf("SaveDeviceInfo: malloc fail\n"); + return; + } + + node->device = *device; + node->requestId = ERR_RET; + node->status = DEVICE_DISCOVERY; + if (g_deviceListHead == NULL) { + node->next = NULL; + } else { + node->next = g_deviceListHead; + } + g_deviceListHead = node; +} + +static DeviceList *GetDeviceInfo(int idx) +{ + DeviceList *node = g_deviceListHead; + while (node) { + if (--idx == 0) { + return node; + } + node = node->next; + } + return NULL; +} + +static void FreeDeviceInfo() +{ + while (g_deviceListHead) { + DeviceList *node = g_deviceListHead->next; + free(g_deviceListHead); + g_deviceListHead = node; + } +} + +static void ListDevice(void) +{ + DeviceList *node = g_deviceListHead; + int input, num = 0; + + if (node == NULL) { + printf("Get no device!\n"); + return; + } + + CheckDeviceStatus(); + while (node) { + printf("\n%d: devName=%s\n", ++num, node->device.devName); + printf("\tdevId=%s\n", node->device.devId); + printf("\tstatus=%s\n", g_deviceStatus[node->status]); + node = node->next; + } + + printf("Input num to auth:"); + scanf_s("%d", &input); + if (input <= 0 || input >num) { + printf("error input num\n"); + return; + } + + node = GetDeviceInfo(input); + if (node == NULL) { + printf("GetDeviceInfo fail\n"); + return; + } + + if (node->status == DEVICE_DISCOVERY) { + node->requestId = g_requestId; + node->status = DEVICE_JOINING; + int ret = HichainGmAddMemberToGroup(&node->device, g_groupId); + if (ret) { + printf("HichainGmAddMemberToGroup fail:%d\n", ret); + node->requestId = ERR_RET; + node->status = DEVICE_DISCOVERY; + return; + } + } +} + +static void PublishSuccess(int publishId) +{ + printf("CB: publish %d done\n", publishId); +} + +static void PublishFailed(int publishId, PublishFailReason reason) +{ + printf("CB: publish %d failed, reason=%d\n", publishId, (int)reason); +} + +static int PublishServiceInterface(void) +{ + PublishInfo info = { + .publishId = PUBLISH_ID, + .mode = DISCOVER_MODE_PASSIVE, + .medium = COAP, + .freq = LOW, + .capability = DEFAULT_CAPABILITY, + .capabilityData = NULL, + .dataLen = 0, + }; + IPublishCallback cb = { + .OnPublishSuccess = PublishSuccess, + .OnPublishFail = PublishFailed, + }; + return PublishService(APP_ID, &info, &cb); +} + +static void DeviceFound(const DeviceInfo *device) +{ + printf("CB: devName=%s", device->devName); + + if (CheckDeviceExist(device)) { + printf("device:%s udid:%s is already in List\n", device->devName, device->devId); + return; + } + SaveDeviceInfo(device); +} + +static void DiscoverySuccess(int subscribeId) +{ + printf("CB: discover subscribeId=%d\n", subscribeId); +} + +static void DiscoveryFailed(int subscribeId, DiscoveryFailReason reason) +{ + printf("CB: discover subscribeId=%d fail, reason=%d\n", subscribeId, (int)reason); +} + +static int DiscoveryInterface() +{ + SubscribeInfo info = { + .subscribeId = PUBLISH_ID, + .mode = DISCOVER_MODE_ACTIVE, + .medium = COAP, + .freq = LOW, + .isSameAccount = false, + .isWakeRemote = false, + .capability = DEFAULT_CAPABILITY, + .capabilityData = NULL, + .dataLen = 0, + }; + IDiscoveryCallback cb = { + .OnDeviceFound = DeviceFound, + .OnDiscoverFailed = DiscoveryFailed, + .OnDiscoverySuccess = DiscoverySuccess, + }; + return StartDiscovery(APP_ID, &info, &cb); +} + +int main() +{ + int ret; + bool loop = true; + + ret = GetDevUdid(g_udid, MAX_UDID_LEN); + if (ret) { + printf("GetDevUdid fail:%d\n", ret); + return ret; + } + + ret = HichainInit(); + if (ret) { + printf("HichainInit fail\n"); + return ret; + } + + ret = PublishServiceInterface(); + if (ret) { + printf("PublishService fail, ret=%d\n", ret); + goto err_PublishServiceInterface; + } + + ret = DiscoveryInterface(); + if (ret != 0) { + printf("DiscoveryInterface fail\n"); + goto err_DiscoveryInterface; + } + + while (loop) { + printf("\nInput l to list device; Input s to stop:"); + while (true) { + char c = getchar(); + if (c == 'l') { + ListDevice(); + continue; + } else if (c == 's') { + loop = false; + break; + } else if (c == '\n') { + break; + } else { + continue; + } + } + } + + StopDiscovery(APP_ID, PUBLISH_ID); + FreeDeviceInfo(); +err_DiscoveryInterface: + UnPublishService(APP_ID, PUBLISH_ID); +err_PublishServiceInterface: + HichainGmUnRegCallback(); + return ret; + +} diff --git a/UAV_softbus_client/hichain/hichain_main_OH b/UAV_softbus_client/hichain/hichain_main_OH new file mode 100644 index 0000000000000000000000000000000000000000..8121cb8880ece46a843d937348b2925d6a64ae29 Binary files /dev/null and b/UAV_softbus_client/hichain/hichain_main_OH differ diff --git a/UAV_softbus_client/softbus_sample/build.sh b/UAV_softbus_client/softbus_sample/build.sh new file mode 100644 index 0000000000000000000000000000000000000000..9a992a9f39a7ecb1997d8005aa75a332da37c7db --- /dev/null +++ b/UAV_softbus_client/softbus_sample/build.sh @@ -0,0 +1,4 @@ +#! /bin/bash +mkdir out +# 编译softbus_client +g++ --std=c++17 -I./include -I/usr/local/include/mavsdk/ -lsoftbus_client.z -lboundscheck -lmavsdk softbus_client_main.cpp vehicle.cpp -o out/softbus_client \ No newline at end of file diff --git a/UAV_softbus_client/softbus_sample/include/discovery_service.h b/UAV_softbus_client/softbus_sample/include/discovery_service.h new file mode 100644 index 0000000000000000000000000000000000000000..6df0583f8524eb09008c94e60af16c7ad4dd4c23 --- /dev/null +++ b/UAV_softbus_client/softbus_sample/include/discovery_service.h @@ -0,0 +1,150 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef DISCOVERY_SERVICE_H +#define DISCOVERY_SERVICE_H + +#include "softbus_common.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif + +/** + * @brief Indicates the maximum length of the device address in IDiscoveryCallback. + * + */ +#define CONNECT_ADDR_LEN 46 + +/** + * @brief Enumerates error codes for service publishing failures. + * + * The error codes are returned to the caller through IPublishCallback. + * + */ +typedef enum { + /* Unsupported medium */ + PUBLISH_FAIL_REASON_NOT_SUPPORT_MEDIUM = 1, + /* internal error */ + PUBLISH_FAIL_REASON_INTERNAL = 2, + /* Unknown reason */ + PUBLISH_FAIL_REASON_UNKNOWN = 0xFF +} PublishFailReason; + +/** + * @brief Defines the callbacks for successful and failed service publishing. + * + */ +typedef struct { + /** Callback for successful publishing */ + void (*OnPublishSuccess)(int publishId); + /** Callback for failed publishing */ + void (*OnPublishFail)(int publishId, PublishFailReason reason); +} IPublishCallback; + +/** + * @brief Enumerates error codes for service subscription failures. + * + * The error codes are returned to the caller through IDiscoveryCallback. + * + */ +typedef enum { + /* Unsupported medium */ + DISCOVERY_FAIL_REASON_NOT_SUPPORT_MEDIUM = 1, + /* internal error */ + DISCOVERY_FAIL_REASON_INTERNAL = 2, + /* Unknown error */ + DISCOVERY_FAIL_REASON_UNKNOWN = 0xFF +} DiscoveryFailReason; + +/** + * @brief Defines a callback for service subscription. + * + * Three types of callbacks are available. + * + */ +typedef struct { + /** Callback that is invoked when a device is found */ + void (*OnDeviceFound)(const DeviceInfo *device); + /** Callback for a subscription failure */ + void (*OnDiscoverFailed)(int subscribeId, DiscoveryFailReason failReason); + /** Callback for a subscription success */ + void (*OnDiscoverySuccess)(int subscribeId); +} IDiscoveryCallback; + +/** + * @brief Publishes a specified service. + * + * Peer devices in the same LAN as the device that publishes this service can discover this service as needed. + * The service is identified by publicId and pkgName. + * + * @param pkgName Indicates the pointer to the service package name, which can contain a maximum of 64 bytes. + * @param info Indicates the pointer to the service publishing information. For details, see {@link PublishInfo}. + * @param cb Indicates the pointer to the service publishing callback {@link IPublishCallback}. + * @return Returns SOFTBUS_INVALID_PARAM if any parameter is null or invalid. + * @return Returns SOFTBUS_DISCOVER_NOT_INIT if the Intelligent Soft Bus client fails to be initialized. + * @return Returns SOFTBUS_LOCK_ERR if the mutex fails to be locked. + * @return Returns SOFTBUS_OK if the service is successfully published. + */ +int PublishService(const char *pkgName, const PublishInfo *info, const IPublishCallback *cb); + +/** + * @brief Unpublishes a specified service. + * + * @param pkgName Indicates the pointer to the service package name, which can contain a maximum of 64 bytes. + * @param publishId Indicates the service ID. + * @return Returns SOFTBUS_INVALID_PARAM if pkgName is invalid. + * @return Returns SOFTBUS_DISCOVER_NOT_INIT if the Intelligent Soft Bus client fails to be initialized. + * @return Returns SOFTBUS_OK if the service is successfully unpublished. + */ +int UnPublishService(const char *pkgName, int publishId); + +/** + * @brief Subscribes to a specified service. + * + * Information about the device that publishes the service will be reported to the device that subscribes to + * the service. + * The service is identified by subscribeId and pkgName. + * + * @param pkgName Indicates the pointer to the service package name, which can contain a maximum of 64 bytes. + * @param info Indicates the pointer to the service subscription information. For details, see {@link SubscribeInfo}. + * @param cb Indicates the service subscription callback {@link IDiscoveryCallback}. + * @return Returns SOFTBUS_INVALID_PARAM if any parameter is null or invalid. + * @return Returns SOFTBUS_DISCOVER_NOT_INIT if the Intelligent Soft Bus client fails to be initialized. + * @return Returns SOFTBUS_LOCK_ERR if the mutex fails to be locked. + * @return Returns SOFTBUS_OK if the service subscription is successful. + */ +int StartDiscovery(const char *pkgName, const SubscribeInfo *info, const IDiscoveryCallback *cb); + +/** + * @brief Unsubscribes from a specified service. + * + * @param pkgName Indicates the pointer to the service package name, which can contain a maximum of 64 bytes. + * @param subscribeId Indicates the service ID. + * @return Returns SOFTBUS_INVALID_PARAM if pkgName is invalid. + * @return Returns SOFTBUS_DISCOVER_NOT_INIT if the Intelligent Soft Bus client fails to be initialized. + * @return Returns SOFTBUS_OK if the service unsubscription is successful. + */ +int StopDiscovery(const char *pkgName, int subscribeId); + +#ifdef __cplusplus +#if __cplusplus +} +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#endif /* DISCOVERY_SERVICE_H */ diff --git a/UAV_softbus_client/softbus_sample/include/session.h b/UAV_softbus_client/softbus_sample/include/session.h new file mode 100644 index 0000000000000000000000000000000000000000..a590c04645cd5d35810b9ea817a6ef2165a7aa6c --- /dev/null +++ b/UAV_softbus_client/softbus_sample/include/session.h @@ -0,0 +1,434 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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. + */ + +/** + * @addtogroup Softbus + * @{ + * + * @brief Provides high-speed, secure communication between devices. + * + * This module implements unified distributed communication capability management between + * nearby devices, and provides link-independent device discovery and transmission interfaces + * to support service publishing and data transmission. + * + * @since 1.0 + * @version 1.0 +*/ + +/** + * @file session.h + * + * @brief Declares unified data transmission interfaces. + * + * This file provides data transmission capabilities, including creating and removing a session server, + * opening and closing sessions, receiving data, and querying basic session information. \n + * After multiple nearby devices are discovered and networked, these interfaces can be used to + * transmit data across devices. \n + * + * @since 1.0 + * @version 1.0 + */ +#ifndef SESSION_H +#define SESSION_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif +/** + * @brief business type of session + * + * @since 1.0 + * @version 1.0 + */ +typedef enum { + TYPE_MESSAGE = 1, + TYPE_BYTES, + TYPE_FILE, + TYPE_STREAM, + TYPE_BUTT, +} SessionType; + +typedef enum { + INVALID = -1, + /* + * Send any segment of a frame each time. + */ + RAW_STREAM, + /* + * Send a whole video frame each time. + */ + COMMON_VIDEO_STREAM, + /* + * Send a whole audio frame each time. + */ + COMMON_AUDIO_STREAM, + /* + * Slice frame mode. + */ + VIDEO_SLICE_STREAM, +} StreamType; + +typedef enum { + LINK_TYPE_WIFI_WLAN_5G = 1, + LINK_TYPE_WIFI_WLAN_2G = 2, + LINK_TYPE_WIFI_P2P = 3, + LINK_TYPE_BR = 4, + LINK_TYPE_MAX = 4, +} LinkType; + +/** + * @brief session attribute. + * + * control the attribute of session. + * + * @since 1.0 + * @version 1.0 + */ +typedef struct { + /** @brief dataType{@link SessionType} */ + int dataType; + int linkTypeNum; + LinkType linkType[LINK_TYPE_MAX]; + union { + struct StreamAttr { + int streamType; + } streamAttr; + } attr; +} SessionAttribute; + +typedef struct { + char *buf; + int bufLen; +} StreamData; + +typedef struct { + int type; + int64_t value; +} TV; + +typedef struct { + int frameType; + int64_t timeStamp; + int seqNum; + int seqSubNum; + int level; + int bitMap; + int tvCount; + TV *tvList; +} StreamFrameInfo; + +typedef enum { + QOS_IMPROVE = 0, + QOS_RECOVER = 1 +} QosQuality; + +typedef enum { + TRANS_STREAM_QUALITY_EVENT = 1, + TRANS_CHANNEL_QUALITY_EVENT, + TRANS_CAN_DELAY_EVENT, + TRANS_CANT_DELAY_EVENT, + QOS_EVENT_MAX +} QosEvent; + +typedef enum { + WIFI_CHANNEL_QUALITY = 1, + FRAME_REALTIME_STATUS = 2, + BANDWIDTH_ESTIMATE_VALUE = 3, + JITTER_DETECTION_VALUE = 4, + STREAM_TRAFFIC_STASTICS = 5, +} TransEnumEventType; + +typedef struct { + int32_t channel; + int32_t score; +} WifiChannelQuality; + +typedef struct { + int32_t streamId; + int32_t seqNum; + int32_t level; + int32_t transStatus; + int32_t interval; +} FrameStatus; + +typedef struct { + uint32_t trend; + uint32_t rate; /* kbps */ +} BandwidthDetection; + +typedef struct { + int32_t jitterLevel; + uint32_t bufferTime; /* ms */ +} JitterEstimation; + +typedef struct { + uint64_t statisticsGotTime; /* time point that stream traficc statistics are obtained (ms) */ + uint64_t periodRecvBits; + uint32_t pktNum; + uint32_t periodRecvPkts; + uint32_t periodRecvPktLoss; + uint32_t periodRecvRate; /* kbps */ + uint64_t periodRecvRateBps; /* bps */ + uint32_t periodRtt; /* ms */ + uint32_t periodRecvPktLossHighPrecision; /* for example when lost rate is 1.10%, then 110 will returned */ + uint32_t periodSendLostPkts; + uint32_t periodSendPkts; + uint32_t periodSendPktLossHighPrecision; /* for example when lost rate is 1.10%, then 110 will returned */ + uint64_t periodSendBits; + uint64_t periodSendRateBps; /* bps */ +} StreamStatistics; + +typedef struct { + TransEnumEventType type; + union { + WifiChannelQuality wifiChannelInfo; + FrameStatus frameStatusInfo; + BandwidthDetection bandwidthInfo; + JitterEstimation jitterInfo; + StreamStatistics appStatistics; + } info; +} QosTv; + +/** + * @brief Defines session callbacks. + * + * When a session is opened or closed, or there is data to process, the related callback is invoked. + * + * @since 1.0 + * @version 1.0 + */ +typedef struct { + /** + * @brief Called when a session is opened. + * + * This function can be used to verify the session or initialize resources related to the session. + * + * @param sessionId Indicates the session ID. + * @param result 0 if the session is opened successfully, returns an error code otherwise. + * @return Returns 0 if the session connection is accepted; returns a non-zero value + * otherwise (you do not need to call {@link CloseSession} to close the session). + * @since 1.0 + * @version 1.0 + */ + int (*OnSessionOpened)(int sessionId, int result); + + /** + * @brief Called when a session is closed. + * + * This function can be used to release resources related to the session. + * You do not need to call {@link CloseSession}. + * + * @param sessionId Indicates the session ID. + * @since 1.0 + * @version 1.0 + */ + void (*OnSessionClosed)(int sessionId); + + /** + * @brief Called when data is received. + * + * This function is used to notify that data is received. + * + * @param sessionId Indicates the session ID. + * @param data Indicates the pointer to the data received. + * @param dataLen Indicates the length of the data received. + * @since 1.0 + * @version 1.0 + */ + void (*OnBytesReceived)(int sessionId, const void *data, unsigned int dataLen); + + /** + * @brief Called when message is received. + * + * This function is used to notify that message is received. + * + * @param sessionId Indicates the session ID. + * @param data Indicates the pointer to the message data received. + * @param dataLen Indicates the length of the message received. + * @since 1.0 + * @version 1.0 + */ + void (*OnMessageReceived)(int sessionId, const void *data, unsigned int dataLen); + + void (*OnStreamReceived)(int sessionId, const StreamData *data, const StreamData *ext, + const StreamFrameInfo *param); + + /** + * @brief Called when QoS information is retrieved. + * + * This function is used to notify that QoS information is retrieved. + * + * @param sessionId Indicates the session ID. + * @param eventId Indicates the type of QoS information, e.g., channel quality and stream quality + * @param tvCount Indicates the number of structure returned in the fourth parameters, i.e., tvList. + * @param tvList Indicates the detailed information of data transmission. + * @since 1.0 + * @version 1.0 + */ + void (*OnQosEvent)(int sessionId, int eventId, int tvCount, const QosTv *tvList); +} ISessionListener; + +typedef struct { + int (*OnReceiveFileStarted)(int sessionId, const char *files, int fileCnt); + int (*OnReceiveFileProcess)(int sessionId, const char *firstFile, uint64_t bytesUpload, uint64_t bytesTotal); + void (*OnReceiveFileFinished)(int sessionId, const char *files, int fileCnt); + void (*OnFileTransError)(int sessionId); +} IFileReceiveListener; + +typedef struct { + int (*OnSendFileProcess)(int sessionId, uint64_t bytesUpload, uint64_t bytesTotal); + int (*OnSendFileFinished)(int sessionId, const char *firstFile); + void (*OnFileTransError)(int sessionId); +} IFileSendListener; + +/** + * @brief Creates a session server based on a package name and session name. + * + * A maximum of 18 session servers can be created. + * + * @param pkgName Indicates the pointer to the package name, which can be used to check whether the + * session server is in this package. The value cannot be empty and can contain a maximum of 64 characters. + * @param sessionName Indicates the pointer to the session name, which is the unique ID of the session server. + * The value cannot be empty and can contain a maximum of 64 characters. + * @param listener Indicates the pointer to the session callback structure, which cannot be empty. + * @return Returns 0 if the operation is successful; returns -1 otherwise. + * @see RemoveSessionServer + * @since 1.0 + * @version 1.0 + */ +int CreateSessionServer(const char *pkgName, const char *sessionName, const ISessionListener *listener); + +/** + * @brief Removes a session server based on a package name and session name. + * + * @param pkgName Indicates the pointer to the name of the registered package, which can be used to check + * whether the session server is in this package. The value cannot be empty and can contain a maximum of 64 characters. + * @param sessionName Indicates the pointer to the session name. The value cannot be empty and can contain + * a maximum of 64 characters. + * @return Returns 0 if the operation is successful, returns -1 otherwise. + * @see CreateSessionServer + * @since 1.0 + * @version 1.0 + */ +int RemoveSessionServer(const char *pkgName, const char *sessionName); + +/** + * @brief Initiate a session open request, which is an asynchronous process. + * + * The session connection is opened based on the service name to trigger the first packet interaction process. + * According to the {@link OnSessionOpened} Notify the user whether the session is successfully opened. + * Data can be transmitted only after the session is successfully opened. + * + * @param mySessionName local session name. + * @param peerSessionName remote session name. + * @param peerDeviceId remote device id. + * @param groupId group id. + * @param attr session attribute {@link SessionAttribute}. + * @return return sessionId if the session is opened successfully, returns an error code otherwise. + * @since 1.0 + * @version 1.0 + */ +int OpenSession(const char *mySessionName, const char *peerSessionName, const char *peerDeviceId, + const char *groupId, const SessionAttribute* attr); + +/** + * @brief Closes a connected session based on a session ID. + * + * @param sessionId Indicates the session ID. + * @return no return value. + * @since 1.0 + * @version 1.0 + */ +void CloseSession(int sessionId); + +/** + * @brief Sends data based on a session ID. + * + * @param sessionId Indicates the session ID. + * @param data Indicates the pointer to the data to send, which cannot be NULL. + * @param len Indicates the length of the data to send. The maximum length cannot exceed 984 characters. + * @return Returns 0 if the function is called successfully; returns -1 otherwise. + * @since 1.0 + * @version 1.0 + */ +int SendBytes(int sessionId, const void *data, unsigned int len); + +/** + * @brief Sends message based on a session ID. + * + * @param sessionId Indicates the session ID. + * @param data Indicates the pointer to the message data to send, which cannot be NULL. + * @param len Indicates the length of the message to send. + * @return Returns 0 if the function is called successfully, returns an error code otherwise. + * @since 1.0 + * @version 1.0 + */ +int SendMessage(int sessionId, const void *data, unsigned int len); + +int SendStream(int sessionId, const StreamData *data, const StreamData *ext, const StreamFrameInfo *param); + +/** + * @brief Obtains the session name registered by the local device based on the session ID. + * + * @param sessionId Indicates the session ID. + * @param sessionName Indicates the pointer to the buffer for storing the session name. + * @param len Indicates the length of the buffer. + * @return Returns 0 if the operation is successful; returns -1 otherwise. + * @since 1.0 + * @version 1.0 + */ +int GetMySessionName(int sessionId, char *sessionName, unsigned int len); + +/** + * @brief Obtains the session name registered by the peer device based on the session ID. + * + * @param sessionId Indicates the session ID. + * @param sessionName Indicates the pointer to the buffer for storing the session name. + * @param len Indicates the length of the buffer. + * @return Returns 0 if the operation is successful; returns -1 otherwise. + * @since 1.0 + * @version 1.0 + */ +int GetPeerSessionName(int sessionId, char *sessionName, unsigned int len); + +/** + * @brief Obtains the peer device ID based on a session ID. + * + * @param sessionId Indicates the session ID. + * @param devId Indicates the pointer to the buffer for storing the device ID. + * @param len Indicates the length of the buffer. + * @return Returns 0 if the operation is successful; returns -1 otherwise. + * @since 1.0 + * @version 1.0 + */ +int GetPeerDeviceId(int sessionId, char *devId, unsigned int len); + +int GetSessionSide(int sessionId); + +int SetFileReceiveListener(const char *pkgName, const char *sessionName, + const IFileReceiveListener *recvListener, const char *rootDir); + +int SetFileSendListener(const char *pkgName, const char *sessionName, const IFileSendListener *sendListener); + +int SendFile(int sessionId, const char *sFileList[], const char *dFileList[], uint32_t fileCnt); + +int32_t QosReport(int32_t sessionId, int32_t appType, int32_t quality); + +#ifdef __cplusplus +} +#endif +#endif // SESSION_H diff --git a/UAV_softbus_client/softbus_sample/include/softbus_bus_center.h b/UAV_softbus_client/softbus_sample/include/softbus_bus_center.h new file mode 100644 index 0000000000000000000000000000000000000000..f26b925baacb1eb7dce57807a273835aae14f92b --- /dev/null +++ b/UAV_softbus_client/softbus_sample/include/softbus_bus_center.h @@ -0,0 +1,649 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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. + */ + +/** + * @addtogroup Softbus + * @{ + * + * @brief Provides high-speed, secure communication between devices. + * + * This module implements unified distributed communication capability management between nearby devices, and provides + * link-independent device discovery and transmission interfaces to support service publishing and data transmission. + * + * @since 1.0 + * @version 1.0 + */ + +/** + * @file softbus_bus_center.h + * + * @brief Declares functions and constants for the bus center of the Intelligent Soft Bus. + * + * The functions are used to perform + * the following operations: \n + *
    + *
  • Adding a device to and removing a device from a LNN
  • + *
  • Listening for device online, offline, and information change events
  • + * + * @since 1.0 + * @version 1.0 + */ + +#ifndef SOFTBUS_BUS_CENTER_H +#define SOFTBUS_BUS_CENTER_H + +#include +#include + +#include "softbus_common.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Indicates the length of a device name buffer, including the terminating null character \0. + * + * @since 1.0 + * @version 1.0 + */ +#define DEVICE_NAME_BUF_LEN 128 + +/** + * @brief Indicates the mask bit for a device online event. + * If you want to receive such events, set the mask bit in {@link INodeStateCb.events}. + * + * @since 1.0 + * @version 1.0 + */ +#define EVENT_NODE_STATE_ONLINE 0x1 + +/** + * @brief Indicates the mask bit for a device offline event. + * If you want to receive such events, set the mask bit in {@link INodeStateCb.events}. + * + * @since 1.0 + * @version 1.0 + */ +#define EVENT_NODE_STATE_OFFLINE 0x02 + +/** + * @brief Indicates the mask bit for a peer device information change event. + * If you want to receive such events, set the mask bit in {@link INodeStateCb.events}. + * + * @since 1.0 + * @version 1.0 + */ +#define EVENT_NODE_STATE_INFO_CHANGED 0x04 + +/** + * @brief Indicates mask bits for {@link INodeStateCb.events}. + * + * @since 1.0 + * @version 1.0 + */ +#define EVENT_NODE_STATE_MASK 0x07 + +/** + * @brief The maximum length of meta node bypass info {@link MetaNodeConfigInfo.bypassInfo}. + * + * @since 1.0 + * @version 1.0 + */ +#define META_NODE_BYPASS_INFO_LEN 64 + +/** + * @brief The maximum of meta node {@link MetaNodeConfigInfo.bypassInfo}. + * + * @since 1.0 + * @version 1.0 + */ +#define MAX_META_NODE_NUM 3 + +/** + * @brief Enumerates keys for an online device. + * The key can be obtained via {@link GetNodeKeyInfo}. + * + * @since 1.0 + * @version 1.0 + */ +typedef enum { + NODE_KEY_UDID = 0, /**< UDID in string format*/ + NODE_KEY_UUID, /**< UUID in string format */ +} NodeDeviceInfoKey; + +/** + * @brief Enumerates accuracy for time synchronize among device. + * + * @since 1.0 + * @version 1.0 + */ +typedef enum { + LOW_ACCURACY = 10, + NORMAL_ACCURACY, + HIGH_ACCURACY, + SUPER_HIGH_ACCURACY, + UNAVAIL_ACCURACY = 0xFFFF, +} TimeSyncAccuracy; + +/** + * @brief Enumerates time synchronize period among device. + * + * @since 1.0 + * @version 1.0 + */ +typedef enum { + SHORT_PERIOD = 0, + NORMAL_PERIOD, + LONG_PERIOD, +} TimeSyncPeriod; + +/** + * @brief Enumerates time synchronize flag. + * + * @since 1.0 + * @version 1.0 + */ +typedef enum { + NODE_SPECIFIC = 0, + ALL_LNN, + WRITE_RTC, +} TimeSyncFlag; + +/** + * @brief Defines the basic information about a device. + * + * @since 1.0 + * @version 1.0 + */ +typedef struct { + char networkId[NETWORK_ID_BUF_LEN]; /**< Device ID */ + char deviceName[DEVICE_NAME_BUF_LEN]; /**< Device name */ + uint16_t deviceTypeId; +} NodeBasicInfo; + +/** + * @brief Enumerates device information change types. For details, see {@link INodeStateCb.onNodeBasicInfoChanged}. + * + * @since 1.0 + * @version 1.0 + */ +typedef enum { + TYPE_NETWORK_ID = 0, /**< Network ID change */ + TYPE_DEVICE_NAME, /**< Device name change */ +} NodeBasicInfoType; + +/** + * @brief time synchronize result. + * + * @since 1.0 + * @version 1.0 + */ +typedef struct { + int32_t millisecond; + int32_t microsecond; + TimeSyncAccuracy accuracy; +} TimeSyncResult; + +/** + * @brief time synchronize result info. + * + * @since 1.0 + * @version 1.0 + */ +typedef struct { + TimeSyncResult result; + TimeSyncFlag flag; + union { + char targetNetworkId[NETWORK_ID_BUF_LEN]; + char masterNetworkId[NETWORK_ID_BUF_LEN]; + } target; +} TimeSyncResultInfo; + +/** + * @brief Enumerates error codes for service publishing failures. + * + * The error codes are returned to the caller through IPublishCallback. + * + */ +typedef enum { + /* publish success */ + PUBLISH_LNN_SUCCESS = 0, + /* Unsupported medium */ + PUBLISH_LNN_NOT_SUPPORT_MEDIUM = 1, + /* internal error */ + PUBLISH_LNN_INTERNAL = 2, + /* Unknown reason */ + PUBLISH_LNN_UNKNOWN = 0xFF +} PublishResult; + +/** + * @brief Enumerates error codes for service subscription failures. + * + * The error codes are returned to the caller through IDiscoveryCallback. + * + */ +typedef enum { + /* refresh success */ + REFRESH_LNN_SUCCESS = 0, + /* Unsupported medium */ + REFRESH_LNN_NOT_SUPPORT_MEDIUM = 1, + /* internal error */ + REFRESH_LNN_INTERNAL = 2, + /* Unknown error */ + REFRESH_LNN_UNKNOWN = 0xFF +} RefreshResult; + +/** + * @brief Defines the callbacks for successful and failed service publishing. + * + */ +typedef struct { + /** Callback for publish result */ + void (*OnPublishResult)(int publishId, PublishResult reason); +} IPublishCb; + +/** + * @brief Defines a callback for service subscription. + * + * Three types of callbacks are available. + * + */ +typedef struct { + /** Callback that is invoked when a device is found */ + void (*OnDeviceFound)(const DeviceInfo *device); + /** Callback for a subscription result */ + void (*OnDiscoverResult)(int32_t refreshId, RefreshResult reason); +} IRefreshCallback; + +/** + * @brief Defines a callback that is invoked when the device state or information changes. + * For details, see {@link RegNodeDeviceStateCb}. + * + * @since 1.0 + * @version 1.0 + */ +typedef struct { + /** + * Mask of an event that is listened for. + * The event can be received only if the corresponding mask bit is set and the callback is specified. + */ + uint32_t events; + /** + * @brief Called when a specified device gets online. + * + * @param info Indicates the pointer to the basic information about the device. + * For details, see {@link NodeBasicInfo}. + * + * @since 1.0 + * @version 1.0 + */ + void (*onNodeOnline)(NodeBasicInfo *info); + /** + * @brief Called when a specified device gets offline. + * + * @param info Indicates the pointer to the basic information about the device. + * For details, see {@link NodeBasicInfo}. + * + * @since 1.0 + * @version 1.0 + */ + void (*onNodeOffline)(NodeBasicInfo *info); + /** + * @brief Called when the basic information of a device changes. + * + * @param type Indicates the device type. For details, see {@link NodeBasicInfoType}. + * @param info Indicates the pointer to the new basic information of the device. + * For details, see {@link NodeBasicInfo}. + * + * @since 1.0 + * @version 1.0 + */ + void (*onNodeBasicInfoChanged)(NodeBasicInfoType type, NodeBasicInfo *info); +} INodeStateCb; + +/** + * @brief Defines a callback that is invoked when the time synchronize has result. + * + * @since 1.0 + * @version 1.0 + */ +typedef struct { + /** + * @brief Called when the time synchronize has result. + * + * @param info Contains the time synchronize result info, see {@link TimeSyncResultInfo}. + * @param retCode Indicates the result code. Value 0 indicates that the time synchronize is successful and + * result is valid, and any other value indicates the opposite. + * + * @since 1.0 + * @version 1.0 + */ + void (*onTimeSyncResult)(const TimeSyncResultInfo *info, int32_t retCode); +} ITimeSyncCb; + +/** + * @brief Defines a meta node configuration, see {@link ActiveMetaNode}. + * + * @since 1.0 + * @version 1.0 + */ +typedef struct { + char udid[UDID_BUF_LEN]; + char deviceName[DEVICE_NAME_BUF_LEN]; + uint16_t deviceTypeId; + uint8_t addrNum; + ConnectionAddr addr[CONNECTION_ADDR_MAX]; + char bypassInfo[META_NODE_BYPASS_INFO_LEN]; +} MetaNodeConfigInfo; + +/** + * @brief Defines a meta node infomation, see {@link GetAllMetaNodeInfo}. + * + * @since 1.0 + * @version 1.0 + */ +typedef struct { + char metaNodeId[NETWORK_ID_BUF_LEN]; + bool isOnline; + MetaNodeConfigInfo configInfo; +} MetaNodeInfo; + +/** + * @brief Called when a device is added to a LNN via {@link JoinLNN}. + * + * @param addr Indicates the pointer to the address of the peer device. + * @param networkId Indicates the pointer to the network ID of the device if it is successfully added to the LNN. + * This parameter makes no sense if the device fails to be added to the LNN. + * @param retCode Indicates the result code. Value 0 indicates that the device is successfully added to the LNN, + * and any other value indicates the opposite. + * + * @since 1.0 + * @version 1.0 + */ +typedef void (*OnJoinLNNResult)(ConnectionAddr *addr, const char *networkId, int32_t retCode); + +/** + * @brief Called when a device is removed from a LNN via {@link LeaveLNN}. + * + * @param networkId Indicates the pointer to the network ID of the device. + * @param retCode Indicates the result code. Value 0 indicates that the device is successfully + * removed from the LNN, and any other value indicates the opposite. + * + * @since 1.0 + * @version 1.0 + */ +typedef void (*OnLeaveLNNResult)(const char *networkId, int32_t retCode); + +/** + * @brief Adds the current device to the LNN where a specified device resides. + * + * @param pkgName Indicates the pointer to the caller ID, for example, the package name. + * For the same caller, the value of this parameter must be the same for all functions. + * @param target Indicates the pointer to the address of the specified device. For details, see {@link ConnectionAddr}. + * @param cb Indicates the callback for the result. If you set this parameter to NULL, you will not receive the result. + * + * @return Returns 0 if the request to add the device is accepted, and the result can be obtained from the + * callback; returns any other value if the device fails to be added to the network, in which case you will not receive + * the result. + * + * @since 1.0 + * @version 1.0 + */ +int32_t JoinLNN(const char *pkgName, ConnectionAddr *target, OnJoinLNNResult cb); + +/** + * @brief Removes the current device from the LNN. + * + * @param networkId Indicates the pointer to the network ID that is returned + * after the device is added to the LNN via {@link JoinLNN}. + * @param cb Indicates the callback for the result. If you set this parameter to NULL, + * you will not receive the result. + * + * @return Returns 0 if the request to remove the device is accepted, and the result can be obtained from the + * callback; returns any other value if the device fails to be removed from the network, in which case you will not + * receive the result. + * + * @since 1.0 + * @version 1.0 + */ +int32_t LeaveLNN(const char *pkgName, const char *networkId, OnLeaveLNNResult cb); + +/** + * @brief Registers a callback for device state changes. + * + * @param pkgName Indicates the pointer to the caller ID, for example, the package name. + * For the same caller, the value of this parameter must be the same for all functions. + * @param callback Indicates the pointer to the callback to register. For details, see {@link INodeStateCb}. + * + * @return Returns 0 if the registration is successful; returns any other value otherwise. + * + * @since 1.0 + * @version 1.0 + */ +int32_t RegNodeDeviceStateCb(const char *pkgName, INodeStateCb *callback); + +/** + * @brief Unregisters a callback for device state changes. + * + * @param callback Indicates the pointer to the callback to unregister. For details, see {@link INodeStateCb}. + * + * @return Returns 0 if the unregistration is successful; returns any other value otherwise. + * + * @since 1.0 + * @version 1.0 + */ +int32_t UnregNodeDeviceStateCb(INodeStateCb *callback); + +/** + * @brief Obtains basic information about all the online devices. + * + * @param pkgName Indicates the pointer to the caller ID, for example, the package name. + * For the same caller, the value of this parameter must be the same for all functions. + * @param info Indicates the double pointer to the memory that stores the obtained basic information. + * @param infoNum Indicates the pointer to the number of devices. + * + * @return Returns 0 if the basic information is obtained, in which case info and infoNum are + * valid; returns any other value otherwise. + * + * @since 1.0 + * @version 1.0 + */ +int32_t GetAllNodeDeviceInfo(const char *pkgName, NodeBasicInfo **info, int32_t *infoNum); + +/** + * @brief Releases the memory returned by {@link GetAllNodeDeviceInfo}. + * + * @param info Indicates the pointer to the memory returned by {@link GetAllNodeDeviceInfo}. + * + * @since 1.0 + * @version 1.0 + */ +void FreeNodeInfo(NodeBasicInfo *info); + +/** + * @brief Obtains basic information about the current device. + * + * @param pkgName Indicates the pointer to the caller ID, for example, the package name. + * For the same caller, the value of this parameter must be the same for all functions. + * @param info Indicates the double pointer to the memory that stores the obtained basic information. + * + * @return Returns 0 if the basic information is obtained, in which case info is valid; + * returns any other value otherwise. + * + * @since 1.0 + * @version 1.0 + */ +int32_t GetLocalNodeDeviceInfo(const char *pkgName, NodeBasicInfo *info); + +/** + * @brief Obtains a specified {@link NodeDeviceInfoKey} of an online device. + * + * @param pkgName Indicates the pointer to the caller ID, for example, the package name. + * For the same caller, the value of this parameter must be the same for all functions. + * @param networkId Indicates the pointer to the network ID of the device. + * @param key Indicates the key to be obtained. + * @param info Indicates the pointer to the buffer that stores the obtained key. + * @param infoLen Indicates the buffer length. + * + * @return Returns 0 if the {@link NodeDeviceInfoKey} is obtained, in which case info is valid; + * returns any other value otherwise. + * + * @since 1.0 + * @version 1.0 + */ +int32_t GetNodeKeyInfo(const char *pkgName, const char *networkId, + NodeDeviceInfoKey key, uint8_t *info, int32_t infoLen); + +/** + * @brief Start the time synchronize with specific target node. + * + * @param pkgName Indicates the pointer to the caller ID, for example, the package name. + * For the same caller, the value of this parameter must be the same for all functions. + * @param targetNetworkId Indicates the pointer to the address of the specified device. + * @param accuracy Time synchronize accuracy. + * @param period Time synchronize period + * @param cb Indicates the callback for the result. + * + * @return Returns 0 if the request is accepted, and the result can be obtained from the + * callback; returns any other value if the request fails, in which case you will not receive + * the result. + * + * @since 1.0 + * @version 1.0 + */ +int32_t StartTimeSync(const char *pkgName, const char *targetNetworkId, TimeSyncAccuracy accuracy, + TimeSyncPeriod period, ITimeSyncCb *cb); + +/** + * @brief Stop the time synchronize with specific target node. + * + * @param pkgName Indicates the pointer to the caller ID, for example, the package name. + * For the same caller, the value of this parameter must be the same for all functions. + * @param targetNetworkId Indicates the pointer to the address of the specified device. + * + * @return Returns 0 if the request is removed; returns any other value if the request fails. + * + * @since 1.0 + * @version 1.0 + */ +int32_t StopTimeSync(const char *pkgName, const char *targetNetworkId); + +/** + * @brief Publishes a specified service. + * + * Peer devices in the same LAN as the device that publishes this service can discover this service as needed. + * The service is identified by publicId and pkgName. + * + * @param pkgName Indicates the pointer to the service package name, which can contain a maximum of 64 bytes. + * @param info Indicates the pointer to the service publishing information. For details, see {@link PublishInfo}. + * @param cb Indicates the pointer to the service publishing callback {@link IPublishCallback}. + * @return Returns SOFTBUS_INVALID_PARAM if any parameter is null or invalid. + * @return Returns SOFTBUS_DISCOVER_NOT_INIT if the Intelligent Soft Bus client fails to be initialized. + * @return Returns SOFTBUS_LOCK_ERR if the mutex fails to be locked. + * @return Returns SOFTBUS_OK if the service is successfully published. + */ +int32_t PublishLNN(const char *pkgName, const PublishInfo *info, const IPublishCb *cb); + +/** + * @brief stoppublishes a specified service. + * + * @param pkgName Indicates the pointer to the service package name, which can contain a maximum of 64 bytes. + * @param publishId Indicates the service ID. + * @return Returns SOFTBUS_INVALID_PARAM if pkgName is invalid. + * @return Returns SOFTBUS_DISCOVER_NOT_INIT if the Intelligent Soft Bus client fails to be initialized. + * @return Returns SOFTBUS_OK if the service is successfully unpublished. + */ +int32_t StopPublishLNN(const char *pkgName, int32_t publishId); + +/** + * @brief Subscribes to a specified service. + * + * Information about the device that publishes the service will be reported to the device that subscribes to + * the service. + * The service is identified by subscribeId and pkgName. + * + * @param pkgName Indicates the pointer to the service package name, which can contain a maximum of 64 bytes. + * @param info Indicates the pointer to the service subscription information. For details, see {@link RefreshInfo}. + * @param cb Indicates the service subscription callback {@link IRefreshCallback}. + * @return Returns SOFTBUS_INVALID_PARAM if any parameter is null or invalid. + * @return Returns SOFTBUS_DISCOVER_NOT_INIT if the Intelligent Soft Bus client fails to be initialized. + * @return Returns SOFTBUS_LOCK_ERR if the mutex fails to be locked. + * @return Returns SOFTBUS_OK if the service subscription is successful. + */ +int32_t RefreshLNN(const char *pkgName, const SubscribeInfo *info, const IRefreshCallback *cb); + +/** + * @brief Unsubscribes from a specified service. + * + * @param pkgName Indicates the pointer to the service package name, which can contain a maximum of 64 bytes. + * @param refreshId Indicates the service ID. + * @return Returns SOFTBUS_INVALID_PARAM if pkgName is invalid. + * @return Returns SOFTBUS_DISCOVER_NOT_INIT if the Intelligent Soft Bus client fails to be initialized. + * @return Returns SOFTBUS_OK if the service unsubscription is successful. + */ +int32_t StopRefreshLNN(const char *pkgName, int32_t refreshId); + +/** + * @brief Active meta node. The meta node online status will be notified by {@link INodeStateCb} + * + * @param pkgName Indicates the pointer to the caller ID, for example, the package name. + * For the same caller, the value of this parameter must be the same for all functions. + * @param info Meta node configuration infomation, see {@link MetaNodeConfigInfo}. + * @param metaNodeId Save meta node ID when it is activated successfully, its buffer length must be not + * less then NETWORK_ID_BUF_LEN + * + * @return Returns 0 if the meta node is activated; returns any other value if the request fails. + * + * @since 1.0 + * @version 1.0 + */ +int32_t ActiveMetaNode(const char *pkgName, const MetaNodeConfigInfo *info, char *metaNodeId); + +/** + * @brief Deactive meta node. The meta node will be removed. + * + * @param pkgName Indicates the pointer to the caller ID, for example, the package name. + * For the same caller, the value of this parameter must be the same for all functions. + * @param metaNodeId The meta node ID which deactivated, it's obtained by {@link ActiveMetaNode}. + * + * @return Returns 0 if the meta node is deactivated; returns any other value if the request fails. + * + * @since 1.0 + * @version 1.0 + */ +int32_t DeactiveMetaNode(const char *pkgName, const char *metaNodeId); + +/** + * @brief Get all meta node by {@link ActiveMetaNode}. + * + * @param pkgName Indicates the pointer to the caller ID, for example, the package name. + * For the same caller, the value of this parameter must be the same for all functions. + * @param infos The buffer for save meta node info. + * @param infoNum The infos buffer num which maximum is {@link MAX_META_NODE_NUM}. + * + * @return Returns 0 if the call is success; returns any other value if it fails. + * + * @since 1.0 + * @version 1.0 + */ +int32_t GetAllMetaNodeInfo(const char *pkgName, MetaNodeInfo *infos, int32_t *infoNum); + +#ifdef __cplusplus +} +#endif + +#endif +/** @} */ \ No newline at end of file diff --git a/UAV_softbus_client/softbus_sample/include/softbus_common.h b/UAV_softbus_client/softbus_sample/include/softbus_common.h new file mode 100644 index 0000000000000000000000000000000000000000..0a00e608a199c56d41fe5f5fd3dc903753a5753f --- /dev/null +++ b/UAV_softbus_client/softbus_sample/include/softbus_common.h @@ -0,0 +1,386 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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. + */ + +/** + * @addtogroup SoftBus + * @{ + * + * @brief Provides high-speed, secure communication between devices. + * + * This module implements unified distributed communication capability management between nearby devices, and provides + * link-independent device discovery and transmission interfaces to support service publishing and data transmission. + * + * @since 1.0 + * @version 1.0 + */ + +/** + * @file softbus_common.h + * + * @brief Declares common APIs for the Intelligent Soft Bus. + * + * This file provides common functions and constants for each submodule of the Intelligent Soft Bus, including: \n + * + *
      + *
    • Constants such as the network ID length
    • + *
    • Functions such as that for initializing the Intelligent Soft Bus client
    • + *
    + * + * @since 1.0 + * @version 1.0 + */ + +#ifndef SOFTBUS_CLIENT_COMMON_H +#define SOFTBUS_CLIENT_COMMON_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Indicates the length of the Bluetooth device MAC address in string format, + * including the terminating null character \0. + * + * @since 1.0 + * @version 1.0 + */ +#define BT_MAC_LEN 18 + +/** + * @brief Indicates the length of the network ID string, including the terminating null character \0. + * + * @since 1.0 + * @version 1.0 + */ +#define NETWORK_ID_BUF_LEN 65 + +/** + * @brief Indicates the length of the UDID string, including the terminating null character \0. + * + * @since 1.0 + * @version 1.0 + */ +#define UDID_BUF_LEN 65 + +/** + * @brief Indicates the length of the UDID hash value. + * + * @since 1.0 + * @version 1.0 + */ +#define UDID_HASH_LEN 32 + +/** + * @brief Indicates the length of the UUID string, including the terminating null character \0. + * + * @since 1.0 + * @version 1.0 + */ +#define UUID_BUF_LEN 65 + +/** + * @brief Indicates the maximum length of an IP address in string format, + * including the terminating null character \0. IPv6 addresses are supported. + * + * @since 1.0 + * @version 1.0 + */ +#define IP_STR_MAX_LEN 46 + +/** + * @brief Indicates the maximum length of the account hash code in IDiscoveryCallback. + * + */ +#define MAX_ACCOUNT_HASH_LEN 96 + +/** + * @brief Indicates the maximum length of the capability data in PublishInfo and SubscribeInfo. + * + */ +#define MAX_CAPABILITYDATA_LEN 513 + +/** + * @brief Indicates the maximum length of the custom data in IDiscoveryCallback. + * + */ +#define DISC_MAX_CUST_DATA_LEN 219 + +/** + * @brief Indicates the maximum number of capabilities contained in the bitmap in IDiscoveryCallback. + * + */ +#define DISC_MAX_CAPABILITY_NUM 2 + +/** + * @brief Indicates the maximum length of the device name in IDiscoveryCallback. + * + */ +#define DISC_MAX_DEVICE_NAME_LEN 65 + +/** + * @brief Indicates the maximum length of the device ID in IDiscoveryCallback. + * + */ +#define DISC_MAX_DEVICE_ID_LEN 96 + +/** + * @brief Enumerates {@link ConnectionAddr} types of a device that is added to a LNN. + * + * @since 1.0 + * @version 1.0 + */ +typedef enum { + CONNECTION_ADDR_WLAN = 0, /**< WLAN */ + CONNECTION_ADDR_BR, /**< BR */ + CONNECTION_ADDR_BLE, /**< BLE */ + CONNECTION_ADDR_ETH, /**< Ethernet */ + CONNECTION_ADDR_MAX /**< Invalid type */ +} ConnectionAddrType; +/** + * @brief Defines the address of a device that is added to a LNN. + * For details, see {@link ConnectionAddr}. + * + * @since 1.0 + * @version 1.0 + */ +typedef struct { + /**< Address type. This field is used to explain the info field. */ + ConnectionAddrType type; + /**< Connection address information */ + union { + /**< BR address */ + struct BrAddr { + char brMac[BT_MAC_LEN]; /**< BR MAC address in string format */ + } br; + /**< BLE address */ + struct BleAddr { + char bleMac[BT_MAC_LEN]; /**< BLE MAC address in string format */ + uint8_t udidHash[UDID_HASH_LEN]; /**< udid hash value */ + } ble; + /**< IPv4 or IPv6 address */ + struct IpAddr { + /** + * IP address in string format. It can be an IPv4 address written in dotted decimal notation + * or an IPv6 address written in hexadecimal colon-separated notation. + */ + char ip[IP_STR_MAX_LEN]; + uint16_t port; /**< Port number represented by the host byte order */ + } ip; + } info; + char peerUid[MAX_ACCOUNT_HASH_LEN]; +} ConnectionAddr; + +/** + * @brief Enumerates the modes in which services are published. + * + */ +typedef enum { + /* Passive */ + DISCOVER_MODE_PASSIVE = 0x55, + /* Proactive */ + DISCOVER_MODE_ACTIVE = 0xAA +} DiscoverMode; + +/** + * @brief Enumerates media, such as Bluetooth, Wi-Fi, and USB, used for publishing services. + * + * Currently, only COAP is supported. + * When AUTO is selected, all the supported media will be called automatically. + */ +typedef enum { + /** Automatic medium selection */ + AUTO = 0, + /** Bluetooth */ + BLE = 1, + /** Wi-Fi */ + COAP = 2, + /** USB */ + USB = 3, + /** HiLink */ + COAP1 = 4, + MEDIUM_BUTT +} ExchanageMedium; + +/** + * @brief Enumerates frequencies for publishing services. + * + * This enumeration applies only to Bluetooth and is not supported currently. + */ +typedef enum { + /** Low */ + LOW = 0, + /** Medium */ + MID = 1, + /** High */ + HIGH = 2, + /** Super-high */ + SUPER_HIGH = 3, + FREQ_BUTT +} ExchangeFreq; + +/** + * @brief Enumerates supported capabilities published by a device. + * + */ +typedef enum { + /** MeeTime */ + HICALL_CAPABILITY_BITMAP = 0, + /** Video reverse connection in the smart domain */ + PROFILE_CAPABILITY_BITMAP = 1, + /** Gallery in Vision */ + HOMEVISIONPIC_CAPABILITY_BITMAP = 2, + /** cast+ */ + CASTPLUS_CAPABILITY_BITMAP, + /** Input method in Vision */ + AA_CAPABILITY_BITMAP, + /** Device virtualization tool package */ + DVKIT_CAPABILITY_BITMAP, + /** Distributed middleware */ + DDMP_CAPABILITY_BITMAP, + /** Osd capability */ + OSD_CAPABILITY_BITMAP +} DataBitMap; + +/** + * @brief Defines the mapping between supported capabilities and bitmaps. + * + */ +typedef struct { + /** Bitmaps. For details, see {@link DataBitMap}. */ + DataBitMap bitmap; + /** Capability. For details, see {@link g_capabilityMap}. */ + char *capability; +} CapabilityMap; + +/** + * @brief Defines the mapping between supported capabilities and bitmaps. + * + */ +static const CapabilityMap g_capabilityMap[] = { + {HICALL_CAPABILITY_BITMAP, (char *)"hicall"}, + {PROFILE_CAPABILITY_BITMAP, (char *)"profile"}, + {HOMEVISIONPIC_CAPABILITY_BITMAP, (char *)"homevisionPic"}, + {CASTPLUS_CAPABILITY_BITMAP, (char *)"castPlus"}, + {AA_CAPABILITY_BITMAP, (char *)"aaCapability"}, + {DVKIT_CAPABILITY_BITMAP, (char *)"dvKit"}, + {DDMP_CAPABILITY_BITMAP, (char *)"ddmpCapability"}, + {OSD_CAPABILITY_BITMAP, (char *)"osdCapability"}, +}; + +/** + * @brief Defines service publishing information. + * + */ +typedef struct { + /** Service ID */ + int publishId; + /** Discovery mode for service publishing. For details, see {@link Discovermode}. */ + DiscoverMode mode; + /** Service publishing medium. For details, see {@link ExchanageMedium}. */ + ExchanageMedium medium; + /** Service publishing frequency. For details, see {@link ExchangeFre}. */ + ExchangeFreq freq; + /** Service publishing capabilities. For details, see {@link g_capabilityMap}. */ + const char *capability; + /** Capability data for service publishing */ + unsigned char *capabilityData; + /** Maximum length of the capability data for service publishing (512 bytes) */ + unsigned int dataLen; +} PublishInfo; + +/** + * @brief Defines service subscription information. + * + */ +typedef struct { + /** Service ID */ + int subscribeId; + /** Discovery mode for service subscription. For details, see {@link Discovermode}. */ + DiscoverMode mode; + /** Service subscription medium. For details, see {@link ExchanageMedium}. */ + ExchanageMedium medium; + /** Service subscription frequency. For details, see {@link ExchangeFre}. */ + ExchangeFreq freq; + /** only find the device with the same account */ + bool isSameAccount; + /** find the sleeping devices */ + bool isWakeRemote; + /** Service subscription capability. For details, see {@link g_capabilityMap}. */ + const char *capability; + /** Capability data for service subscription */ + unsigned char *capabilityData; + /** Maximum length of the capability data for service subscription (512 bytes) */ + unsigned int dataLen; +} SubscribeInfo; + +/** + * @brief Enumerates device types. + * + */ +typedef enum { + /* Smart speaker */ + SMART_SPEAKER = 0x00, + /* PC */ + DESKTOP_PC, + /* Laptop */ + LAPTOP, + /* Mobile phone */ + SMART_PHONE, + /* Tablet */ + SMART_PAD, + /* Smart watch */ + SMART_WATCH, + /* Smart car */ + SMART_CAR, + /* Kids' watch */ + CHILDREN_WATCH, + /* Smart TV */ + SMART_TV, +} DeviceType; + +/** + * @brief Defines the device information returned by IDiscoveryCallback. + * + */ +typedef struct { + /** Device ID. Its maximum length is specified by {@link DISC_MAX_DEVICE_ID_LEN}. */ + char devId[DISC_MAX_DEVICE_ID_LEN]; + /** Account hash code. Its maximum length is specified by {@link MAX_ACCOUNT_HASH_LEN}. */ + char accountHash[MAX_ACCOUNT_HASH_LEN]; + /** Device type. For details, see {@link DeviceType}. */ + DeviceType devType; + /** Device name. Its maximum length is specified by {@link DISC_MAX_DEVICE_NAME_LEN}. */ + char devName[DISC_MAX_DEVICE_NAME_LEN]; + /** Number of available connections */ + unsigned int addrNum; + /** Connection information. For details, see {@link ConnectAddr}. */ + ConnectionAddr addr[CONNECTION_ADDR_MAX]; + /** Number of capabilities */ + unsigned int capabilityBitmapNum; + /** Device capability bitmap. + * The maximum number of capabilities in the bitmap is specified by {@link DISC_MAX_CAPABILITY_NUM}. + */ + unsigned int capabilityBitmap[DISC_MAX_CAPABILITY_NUM]; + /** Custom data. Its length is specified by {@link DISC_MAX_CUST_DATA_LEN}. */ + char custData[DISC_MAX_CUST_DATA_LEN]; +} DeviceInfo; +#ifdef __cplusplus +} +#endif +#endif +/** @} */ diff --git a/UAV_softbus_client/softbus_sample/include/softbus_errcode.h b/UAV_softbus_client/softbus_sample/include/softbus_errcode.h new file mode 100644 index 0000000000000000000000000000000000000000..4dd89ae3121b44abdceef724f252566fb62e7773 --- /dev/null +++ b/UAV_softbus_client/softbus_sample/include/softbus_errcode.h @@ -0,0 +1,206 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef SOFTBUS_ERROR_CODE_H +#define SOFTBUS_ERROR_CODE_H + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif + +enum SoftBusErrNo { + SOFTBUS_PUBLIC_ERR_BASE = (-13000), + + SOFTBUS_FRAMEWORK_ERR_BASE = (-12000), + SOFTBUS_INVALID_PKGNAME, + SOFTBUS_FUNC_NOT_SUPPORT, + SOFTBUS_SERVER_NOT_INIT, + + SOFTBUS_TRANS_ERR_BASE = (-11000), + + SOFTBUS_TRANS_INVALID_SESSION_ID, + SOFTBUS_TRANS_INVALID_SESSION_NAME, + SOFTBUS_TRANS_INVALID_CHANNEL_TYPE, + SOFTBUS_TRANS_INVALID_CLOSE_CHANNEL_ID, + SOFTBUS_TRANS_SESSION_REPEATED, + SOFTBUS_TRANS_SESSION_CNT_EXCEEDS_LIMIT, + SOFTBUS_TRANS_SESSIONSERVER_NOT_CREATED, + SOFTBUS_TRANS_SESSION_OPENING, + SOFTBUS_TRANS_GET_LANE_INFO_ERR, + SOFTBUS_TRANS_INVALID_DATA_LENGTH, + SOFTBUS_TRANS_FUNC_NOT_SUPPORT, + SOFTBUS_TRANS_OPEN_AUTH_CHANNANEL_FAILED, + SOFTBUS_TRANS_GET_P2P_INFO_FAILED, + SOFTBUS_TRANS_OPEN_AUTH_CONN_FAILED, + + SOFTBUS_TRANS_PROXY_PACKMSG_ERR, + SOFTBUS_TRANS_PROXY_SENDMSG_ERR, + SOFTBUS_TRANS_PROXY_SEND_CHANNELID_INVALID, + SOFTBUS_TRANS_PROXY_CHANNLE_STATUS_INVALID, + SOFTBUS_TRANS_PROXY_DEL_CHANNELID_INVALID, + SOFTBUS_TRANS_PROXY_SESS_ENCRYPT_ERR, + SOFTBUS_TRANS_PROXY_INVALID_SLICE_HEAD, + SOFTBUS_TRANS_PROXY_ASSEMBLE_PACK_NO_INVALID, + SOFTBUS_TRANS_PROXY_ASSEMBLE_PACK_EXCEED_LENGTH, + SOFTBUS_TRANS_PROXY_ASSEMBLE_PACK_DATA_NULL, + + SOFTBUS_TRANS_UDP_CLOSE_CHANNELID_INVALID, + SOFTBUS_TRANS_UDP_SERVER_ADD_CHANNEL_FAILED, + SOFTBUS_TRANS_UDP_CLIENT_ADD_CHANNEL_FAILED, + SOFTBUS_TRANS_UDP_SERVER_NOTIFY_APP_OPEN_FAILED, + SOFTBUS_TRANS_UDP_CLIENT_NOTIFY_APP_OPEN_FAILED, + SOFTBUS_TRANS_UDP_START_STREAM_SERVER_FAILED, + SOFTBUS_TRANS_UDP_START_STREAM_CLIENT_FAILED, + SOFTBUS_TRANS_UDP_SEND_STREAM_FAILED, + + SOFTBUS_TRANS_QOS_REPORT_FAILED, + SOFTBUS_TRANS_QOS_REPORT_TOO_FREQUENT, + + SOFTBUS_AUTH_ERR_BASE = (-9000), + SOFTBUS_AUTH_VERIFIED, + SOFTBUS_AUTH_VERIFYING, + SOFTBUS_AUTH_SYNC_DEVID_FAILED, + SOFTBUS_AUTH_UNPACK_DEVID_FAILED, + SOFTBUS_AUTH_HICHAIN_PROCESS_FAILED, + SOFTBUS_AUTH_HICHAIN_AUTH_DEVICE_FAILED, + SOFTBUS_AUTH_HICHAIN_AUTH_ERROR, + SOFTBUS_AUTH_TIMEOUT, + SOFTBUS_AUTH_EXISTED, + SOFTBUS_AUTH_NOT_EXISTED, + + SOFTBUS_NETWORK_ERR_BASE = (-7000), + SOFTBUS_NETWORK_CONN_FSM_DEAD, + SOFTBUS_NETWORK_JOIN_CANCELED, + SOFTBUS_NETWORK_JOIN_LEAVING, + SOFTBUS_NETWORK_JOIN_TIMEOUT, + SOFTBUS_NETWORK_UNPACK_DEV_INFO_FAILED, + SOFTBUS_NETWORK_DEV_NOT_TRUST, + SOFTBUS_NETWORK_LEAVE_OFFLINE, + SOFTBUS_NETWORK_AUTH_DISCONNECT, + SOFTBUS_NETWORK_TIME_SYNC_HANDSHAKE_ERR, // time sync channel pipe broken + SOFTBUS_NETWORK_TIME_SYNC_HANDSHAKE_TIMEOUT, // timeout during handshake + SOFTBUS_NETWORK_TIME_SYNC_TIMEOUT, // timeout during sync + SOFTBUS_NETWORK_TIME_SYNC_INTERFERENCE, // interference + SOFTBUS_NETWORK_HEARTBEAT_REPEATED, + SOFTBUS_NETWORK_HEARTBEAT_UNTRUSTED, + SOFTBUS_NETWORK_NODE_OFFLINE, + + SOFTBUS_CONN_ERR_BASE = (-5000), + SOFTBUS_CONN_FAIL, + SOFTBUS_CONN_MANAGER_TYPE_NOT_SUPPORT, + SOFTBUS_CONN_MANAGER_OP_NOT_SUPPORT, + SOFTBUS_CONN_MANAGER_PKT_LEN_INVALID, + SOFTBUS_CONN_MANAGER_LIST_NOT_INIT, + SOFTBUS_CONN_INVALID_CONN_TYPE, + SOFTBUS_CONNECTION_BASE, + SOFTBUS_CONNECTION_ERR_CLOSED, + SOFTBUS_CONNECTION_ERR_DRIVER_CONGEST, + SOFTBUS_CONNECTION_ERR_SOFTBUS_CONGEST, + SOFTBUS_CONNECTION_ERR_CONNID_INVALID, + SOFTBUS_CONNECTION_ERR_SENDQUEUE_FULL, + SOFTBUS_BRCONNECTION_POSTBYTES_ERROR, + SOFTBUS_BRCONNECTION_GETCONNINFO_ERROR, + SOFTBUS_BRCONNECTION_STRNCPY_ERROR, + SOFTBUS_BRCONNECTION_PACKJSON_ERROR, + SOFTBUS_BRCONNECTION_CONNECTDEVICE_MALLOCFAIL, + SOFTBUS_BRCONNECTION_CONNECTDEVICE_GETSOCKETIDFAIL, + SOFTBUS_BRCONNECTION_DISCONNECT_NOTFIND, + SOFTBUS_TCPCONNECTION_SOCKET_ERR, + SOFTBUS_BLECONNECTION_REG_GATTS_CALLBACK_FAIL, + SOFTBUS_BLECONNECTION_ADD_SERVICE_FAIL, + SOFTBUS_BLECONNECTION_ADD_CHAR_FAIL, + SOFTBUS_BLECONNECTION_ADD_DES_FAIL, + SOFTBUS_BLECONNECTION_NOT_INIT, + SOFTBUS_BLECONNECTION_NOT_START, + SOFTBUS_BLECONNECTION_GETCONNINFO_ERROR, + SOFTBUS_BLECONNECTION_MTU_OVERFLOW_ERROR, + SOFTBUS_BLECONNECTION_MUTEX_LOCK_ERROR, + SOFTBUS_BLECONNECTION_GATT_CLIENT_NOT_SUPPORT, + SOFTBUS_GATTC_INTERFACE_FAILED, + SOFTBUS_BLEGATTC_NONT_INIT, + SOFTBUS_BLEGATTC_NOT_READY, + SOFTBUS_GATTC_DUPLICATE_PARAM, + SOFTBUS_GATTC_NONE_PARAM, + SOFTBUS_BLEGATTC_NODE_NOT_EXIST, + + SOFTBUS_DISCOVER_ERR_BASE = (-3000), + + SOFTBUS_DISCOVER_NOT_INIT, + SOFTBUS_DISCOVER_INVALID_PKGNAME, + SOFTBUS_DISCOVER_SERVER_NO_PERMISSION, + SOFTBUS_DISCOVER_MANAGER_NOT_INIT, + SOFTBUS_DISCOVER_MANAGER_ITEM_NOT_CREATE, + SOFTBUS_DISCOVER_MANAGER_INFO_NOT_CREATE, + SOFTBUS_DISCOVER_MANAGER_INFO_NOT_DELETE, + SOFTBUS_DISCOVER_MANAGER_INNERFUNCTION_FAIL, + SOFTBUS_DISCOVER_MANAGER_CAPABILITY_INVALID, + SOFTBUS_DISCOVER_MANAGER_DUPLICATE_PARAM, + SOFTBUS_DISCOVER_MANAGER_INVALID_PARAM, + SOFTBUS_DISCOVER_MANAGER_INVALID_MEDIUM, + SOFTBUS_DISCOVER_MANAGER_INVALID_PKGNAME, + SOFTBUS_DISCOVER_MANAGER_INVALID_MODULE, + SOFTBUS_DISCOVER_COAP_NOT_INIT, + SOFTBUS_DISCOVER_COAP_INIT_FAIL, + SOFTBUS_DISCOVER_COAP_MERGE_CAP_FAIL, + SOFTBUS_DISCOVER_COAP_CANCEL_CAP_FAIL, + SOFTBUS_DISCOVER_COAP_REGISTER_CAP_FAIL, + SOFTBUS_DISCOVER_COAP_SET_FILTER_CAP_FAIL, + SOFTBUS_DISCOVER_COAP_REGISTER_DEVICE_FAIL, + SOFTBUS_DISCOVER_COAP_START_PUBLISH_FAIL, + SOFTBUS_DISCOVER_COAP_STOP_PUBLISH_FAIL, + SOFTBUS_DISCOVER_COAP_START_DISCOVER_FAIL, + SOFTBUS_DISCOVER_COAP_STOP_DISCOVER_FAIL, + + SOFTBUS_COMMOM_ERR_BASE = (-1000), + SOFTBUS_TIMOUT, + SOFTBUS_INVALID_PARAM, + SOFTBUS_MEM_ERR, + SOFTBUS_NOT_IMPLEMENT, + SOFTBUS_NO_URI_QUERY_KEY, + SOFTBUS_NO_INIT, + SOFTBUS_PARSE_JSON_ERR, + SOFTBUS_PERMISSION_DENIED, + SOFTBUS_MALLOC_ERR, + SOFTBUS_ENCRYPT_ERR, + SOFTBUS_DECRYPT_ERR, + SOFTBUS_INVALID_SESS_OPCODE, + SOFTBUS_INVALID_NUM, + SOFTBUS_SERVER_NAME_REPEATED, + SOFTBUS_TCP_SOCKET_ERR, + SOFTBUS_LOCK_ERR, + SOFTBUS_GET_REMOTE_UUID_ERR, + SOFTBUS_NO_ENOUGH_DATA, + SOFTBUS_INVALID_DATA_HEAD, + SOFTBUS_INVALID_FD, + SOFTBUS_FILE_ERR, + SOFTBUS_DATA_NOT_ENOUGH, + SOFTBUS_SLICE_ERROR, + SOFTBUS_ALREADY_EXISTED, + SOFTBUS_GET_CONFIG_VAL_ERR, + SOFTBUS_PEER_PROC_ERR, + SOFTBUS_NOT_FIND, + + SOFTBUS_ERR = (-1), + SOFTBUS_OK = 0, +}; + +#ifdef __cplusplus +#if __cplusplus +} +#endif /* __cplusplus */ +#endif /* __cplusplus */ +#endif /* SOFTBUS_ERRCODE_H */ diff --git a/UAV_softbus_client/softbus_sample/include/vehicle.h b/UAV_softbus_client/softbus_sample/include/vehicle.h new file mode 100644 index 0000000000000000000000000000000000000000..38346ab4313bc9b96fa200fc4d5be8cfb761152e --- /dev/null +++ b/UAV_softbus_client/softbus_sample/include/vehicle.h @@ -0,0 +1,61 @@ +#ifndef _VEHICLE +#define _VEHICLE + +#include +#include +#include +#include +#include +#include +#include +#include + +struct TelemetryLite { +public: + TelemetryLite(); + void dump(); + std::string toJson(); + +public: + uint64_t UniqueID; + uint64_t TimeStamp; + double Longitude; + double Latitude; + double PlatformHeight; + double Yaw; + double Pitch; + double Roll; + double VFov; + double HFov; + double FocalLength35mmEq; + std::string ImgPath; + std::string DateTime; +}; + +class Vechile{ +public: + Vechile(const char *connection_url); + int arm(); + int disarm(); + int takeoff(); + int land(); + void reboot(); + int hover(); + bool isArmed(); + void printVehicleInfo(); + void printHealthInfo(); + TelemetryLite& readTelemetry(); + +private: + mavsdk::ConnectionResult connect(const char *connection_url); + +private: + mavsdk::Mavsdk _mavsdk; + mavsdk::ConnectionResult _connection_result; + std::shared_ptr _system; + mavsdk::Telemetry _telemetry; + mavsdk::Action _action; + TelemetryLite _tl; +}; + +#endif diff --git a/UAV_softbus_client/softbus_sample/prepare_env.sh b/UAV_softbus_client/softbus_sample/prepare_env.sh new file mode 100644 index 0000000000000000000000000000000000000000..2a407ee5776f56a0162c98d1fba5d9ab6a526500 --- /dev/null +++ b/UAV_softbus_client/softbus_sample/prepare_env.sh @@ -0,0 +1,12 @@ +#! /bin/bash + +cd + +# 下载mavsdk-sample代码仓,里面有mavsdk和mavlink-routerd的安装包 +git clone https://gitee.com/galaxy_32/mavsdk-sample.git + +# install mavsdk和mavlink +cd mavsdk-sample +chmod +x install.sh +sed -i "29,30s/^/#/" install.sh # 注释最后两行编译的功能 +./install.sh \ No newline at end of file diff --git a/UAV_softbus_client/softbus_sample/softbus_client_main.cpp b/UAV_softbus_client/softbus_sample/softbus_client_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7b9d5425aa5708f9a13f36e057714a83d59857d8 --- /dev/null +++ b/UAV_softbus_client/softbus_sample/softbus_client_main.cpp @@ -0,0 +1,331 @@ +#include +#include +#include +#include "securec.h" +#include "discovery_service.h" +#include "softbus_bus_center.h" +#include "session.h" +#include "vehicle.h" + +#define PACKAGE_NAME "softbus_sample" +#define LOCAL_SESSION_NAME "session_test" +#define TARGET_SESSION_NAME "hwpad" +#define DEFAULT_CAPABILITY "osdCapability" +#define DEFAULT_SESSION_GROUP "group_test" +#define DEFAULT_PUBLISH_ID 123 + +static int g_sessionId; +Vechile g_vehicle("udp://127.0.0.1:10000"); + +/*创建会话*/ +static int SessionOpened(int sessionId, int result) +{ + printf("CB: session %d open fail:%d\n", sessionId, result); + if (result == 0) + { + g_sessionId = sessionId; + } + + return result; +} + +static void SessionClosed(int sessionId) +{ + printf("CB: session %d closed\n", sessionId); +} + +static void ByteRecived(int sessionId, const void *data, unsigned int dataLen) +{ + printf("CB: session %d received %u bytes data=%s\n", sessionId, dataLen, (const char *)data); + /*根据接收到的信息调用MAVSDK,实现相应的无人机动作*/ + if (strncmp((const char *)data, "takeoff", dataLen) == 0) + { + g_vehicle.takeoff(); + } + else if (strncmp((const char *)data, "land", dataLen) == 0) + { + g_vehicle.land(); + } + else if (strncmp((const char *)data, "hover", dataLen) == 0) + { + g_vehicle.hover(); + } + else + { + printf("CB unknown cmd: %s\n", (const char *)data); + } +} + +static void MessageReceived(int sessionId, const void *data, unsigned int dataLen) +{ + printf("CB: session %d received %u bytes message=%s\n", sessionId, dataLen, (const char *)data); +} + +static int CreateSessionServerInterface(void) +{ + const ISessionListener sessionCB = { + .OnSessionOpened = SessionOpened, + .OnSessionClosed = SessionClosed, + .OnBytesReceived = ByteRecived, + .OnMessageReceived = MessageReceived, + }; + + return CreateSessionServer(PACKAGE_NAME, LOCAL_SESSION_NAME, &sessionCB); +} + +static void RemoveSessionServerInterface(void) +{ + int ret = RemoveSessionServer(PACKAGE_NAME, LOCAL_SESSION_NAME); + if (ret) + { + printf("RemoveSessionServer fail:%d\n", ret); + } +} +/*发布能力*/ +static void PublishSuccess(int publishId) +{ + printf("CB: publish %d done\n", publishId); +} + +static void PublishFailed(int publishId, PublishFailReason reason) +{ + printf("CB: publish %d failed, reason=%d\n", publishId, (int)reason); +} + +static int PublishServiceInterface() +{ + PublishInfo info = { + .publishId = DEFAULT_PUBLISH_ID, + .mode = DISCOVER_MODE_PASSIVE, + .medium = COAP, + .freq = LOW, + .capability = DEFAULT_CAPABILITY, + .capabilityData = NULL, + .dataLen = 0, + }; + IPublishCallback cb = { + .OnPublishSuccess = PublishSuccess, + .OnPublishFail = PublishFailed, + }; + return PublishService(PACKAGE_NAME, &info, &cb); +} + +static void UnPublishServiceInterface(void) +{ + int ret = UnPublishService(PACKAGE_NAME, DEFAULT_PUBLISH_ID); + if (ret != 0) + { + printf("UnPublishService fail:%d\n", ret); + } +} +/*发现设备*/ +static void DeviceFound(const DeviceInfo *device) +{ + unsigned int i; + printf("CB: Device has found\n"); + printf("\tdevId=%s\n", device->devId); + printf("\tdevName=%s\n", device->devName); + printf("\tdevType=%d\n", device->devType); + printf("\taddrNum=%d\n", device->addrNum); + for (i = 0; i < device->addrNum; i++) + { + printf("\t\taddr%d:type=%d,", i + 1, device->addr[i].type); + switch (device->addr[i].type) + { + case CONNECTION_ADDR_WLAN: + case CONNECTION_ADDR_ETH: + printf("ip=%s,port=%d,", device->addr[i].info.ip.ip, device->addr[i].info.ip.port); + break; + default: + break; + } + printf("peerUid=%s\n", device->addr[i].peerUid); + } + printf("\tcapabilityBitmapNum=%d\n", device->capabilityBitmapNum); + for (i = 0; i < device->addrNum; i++) + { + printf("\t\tcapabilityBitmap[%d]=0x%x\n", i + 1, device->capabilityBitmap[i]); + } + printf("\tcustData=%s\n", device->custData); +} + +static void DiscoverySuccess(int subscribeId) +{ + printf("CB: discover subscribeId=%d\n", subscribeId); +} + +static void DiscoveryFailed(int subscribeId, DiscoveryFailReason reason) +{ + printf("CB: discover subscribeId=%d failed, reason=%d\n", subscribeId, (int)reason); +} + +static int DiscoveryInterface(void) +{ + SubscribeInfo info = { + .subscribeId = DEFAULT_PUBLISH_ID, + .mode = DISCOVER_MODE_ACTIVE, + .medium = COAP, + .freq = LOW, + .isSameAccount = false, + .isWakeRemote = false, + .capability = DEFAULT_CAPABILITY, + .capabilityData = NULL, + .dataLen = 0, + }; + IDiscoveryCallback cb = { + .OnDeviceFound = DeviceFound, + .OnDiscoverFailed = DiscoveryFailed, + .OnDiscoverySuccess = DiscoverySuccess, + }; + return StartDiscovery(PACKAGE_NAME, &info, &cb); +} + +static void StopDiscoveryInterface(void) +{ + int ret = StopDiscovery(PACKAGE_NAME, DEFAULT_PUBLISH_ID); + if (ret) + { + printf("StopDiscovery fail:%d\n", ret); + } +} +/*获取节点信息*/ +static int GetAllNodeDeviceInfoInterface(NodeBasicInfo **dev) +{ + int ret, num; + + ret = GetAllNodeDeviceInfo(PACKAGE_NAME, dev, &num); + if (ret) + { + printf("GetAllNodeDeviceInfo fail:%d\n", ret); + return -1; + } + + printf("return %d Node\n", num); + return num; +} + +static void FreeNodeInfoInterface(NodeBasicInfo *dev) +{ + FreeNodeInfo(dev); +} +/*创建对端连接*/ +static int OpenSessionInterface(const char *peerNetworkId) +{ + SessionAttribute attr = { + .dataType = TYPE_BYTES, + .linkTypeNum = 1, + .attr = {RAW_STREAM}, + }; + attr.linkType[0] = LINK_TYPE_WIFI_WLAN_2G; + + return OpenSession(LOCAL_SESSION_NAME, TARGET_SESSION_NAME, peerNetworkId, DEFAULT_SESSION_GROUP, &attr); +} + +static void CloseSessionInterface(int sessionId) +{ + CloseSession(sessionId); +} +/*发送数据*/ +static void commnunicate(void) +{ + NodeBasicInfo *dev = NULL; + char cData[] = "hello world test"; + int dev_num, sessionId, input, ret; + int timeout = 5; + + dev_num = GetAllNodeDeviceInfoInterface(&dev); + if (dev_num <= 0) + { + return; + } + + for (int i = 0; i < dev_num; i++) + { + char devId[UDID_BUF_LEN]; + printf("deviceName=%s\n", i + 1, dev[i].deviceName); + printf("\tnetworkId=%s\n", dev[i].networkId); + if (GetNodeKeyInfo(PACKAGE_NAME, dev[i].networkId, NODE_KEY_UDID, (uint8_t *)devId, UDID_BUF_LEN) == 0) + { + printf("\tdevId=%s\n", devId); + } + printf("\tType=%d\n", dev[i].deviceTypeId); + } + + printf("\nInput Node num to commnunication:"); + scanf_s("%d", &input); + if (input <= 0 || input > dev_num) + { + printf("error input num\n"); + goto err_input; + } + + g_sessionId = -1; + sessionId = OpenSessionInterface(dev[input - 1].networkId); + if (sessionId < 0) + { + printf("OpenSessionInterface fail, ret=%d\n", sessionId); + goto err_OpenSessionInterface; + } + while (true) + { + sleep(1); + } + + CloseSessionInterface(sessionId); +err_OpenSessionInterface: +err_input: + FreeNodeInfoInterface(dev); +} + +int main(int argc, char **argv) +{ + bool loop = true; + int ret; + + ret = CreateSessionServerInterface(); + if (ret) + { + printf("CreateSessionServer fail, ret=%d\n", ret); + return ret; + } + + ret = PublishServiceInterface(); + if (ret) + { + printf("PublishService fail, ret=%d\n", ret); + goto err_PublishServiceInterface; + } + + ret = DiscoveryInterface(); + if (ret) + { + printf("DiscoveryInterface fail, ret=%d\n", ret); + goto err_DiscoveryInterface; + } + + while (loop) + { + printf("\nInput c to commnuication, Input s to stop:"); + char op = getchar(); + switch (op) + { + case 'c': + commnunicate(); + continue; + case 's': + loop = false; + break; + case '\n': + break; + default: + continue; + } + } + + StopDiscoveryInterface(); +err_DiscoveryInterface: + UnPublishServiceInterface(); +err_PublishServiceInterface: + RemoveSessionServerInterface(); + return 0; +} diff --git a/UAV_softbus_client/softbus_sample/softbus_trans_permission.json b/UAV_softbus_client/softbus_sample/softbus_trans_permission.json new file mode 100644 index 0000000000000000000000000000000000000000..8a882a93f3a201f6269f92d18a4c75cbd6ce80ae --- /dev/null +++ b/UAV_softbus_client/softbus_sample/softbus_trans_permission.json @@ -0,0 +1,171 @@ +[ + { + "SESSION_NAME": "DBinderService", + "DEVID": "NETWORKID", + "APP_INFO": [ + { + "TYPE": "native_app", + "UID": "1000", + "PKG_NAME": "DBinderService", + "ACTIONS": "create,open" + } + ] + }, + { + "SESSION_NAME": "DBinder.*", + "REGEXP": "true", + "DEVID": "NETWORKID", + "SEC_LEVEL": "public", + "APP_INFO": [ + { + "TYPE": "granted_app", + "PKG_NAME": "DBinderBus", + "ACTIONS": "create,open" + } + ] + }, + { + "SESSION_NAME": "DistributedFileService.*", + "REGEXP": "true", + "DEVID": "UUID", + "APP_INFO": [ + { + "TYPE": "native_app", + "UID": "1000", + "ACTIONS": "create,open" + } + ] + }, + { + "SESSION_NAME": "distributeddata-default", + "REGEXP": "true", + "DEVID": "UUID", + "SEC_LEVEL": "public", + "APP_INFO": [ + { + "TYPE": "normal_app", + "PKG_NAME": "ohos.distributeddata", + "ACTIONS": "create,open" + } + ] + }, + { + "SESSION_NAME": "objectstoreDB-*", + "REGEXP": "true", + "DEVID": "UDID", + "SEC_LEVEL": "public", + "APP_INFO": [ + { + "TYPE": "normal_app", + "PKG_NAME": "ohos.objectstore", + "ACTIONS": "create,open" + } + ] + }, + { + "SESSION_NAME": "ohos.distributedschedule.dms.*", + "REGEXP": "true", + "DEVID": "UUID", + "APP_INFO": [ + { + "PKG_NAME": "dms", + "TYPE": "system_app", + "ACTIONS": "create,open" + } + ] + }, + { + "SESSION_NAME": "com.huawei.dmsdp.*", + "REGEXP": "true", + "DEVID": "UDID", + "APP_INFO": [ + { + "TYPE": "system_app", + "PKG_NAME": "com.huawei.dmsdp", + "ACTIONS": "create,open" + } + ] + }, + { + "SESSION_NAME": "com.huawei.devicegroupmanage", + "DEVID": "UDID", + "APP_INFO": [ + { + "PKG_NAME": "com.huawei.devicegroupmanage", + "TYPE": "system_app", + "ACTIONS": "create,open" + } + ] + }, + { + "SESSION_NAME": "ohos.distributedhardware.devicemanager.*", + "REGEXP": "true", + "DEVID": "UUID", + "APP_INFO": [ + { + "PKG_NAME": "ohos.distributedhardware.devicemanager", + "TYPE": "system_app", + "ACTIONS": "create,open" + } + ] + }, + { + "SESSION_NAME": "ohos.dhardware.*", + "REGEXP": "true", + "DEVID": "NETWORKID", + "SEC_LEVEL": "public", + "APP_INFO": [ + { + "PKG_NAME": "ohos.dhardware", + "TYPE": "system_app", + "ACTIONS": "create,open" + } + ] + }, + { + "SESSION_NAME": "security.dpms_channel", + "DEVID": "NETWORKID", + "APP_INFO": [ + { + "TYPE": "system_app", + "PKG_NAME": "ohos.security.distributed_permission", + "ACTIONS": "create,open" + } + ] + }, + { + "SESSION_NAME": "device.security.level", + "DEVID": "UDID", + "APP_INFO": [ + { + "TYPE": "native_app", + "UID": "1000", + "PKG_NAME": "ohos.dslm", + "ACTIONS": "create,open" + } + ] + }, + { + "SESSION_NAME": "ohos.security.atm_channel", + "DEVID": "NETWORKID", + "APP_INFO": [ + { + "TYPE": "system_app", + "PKG_NAME": "ohos.security.distributed_access_token", + "ACTIONS": "create,open" + } + ] + }, + { + "SESSION_NAME": "session_test", + "DEVID": "UDID", + "APP_INFO": [ + { + "PKG_NAME": "softbus_sample", + "TYPE": "normal_app", + "ACTIONS": "create,open" + } + ] + } +] + diff --git a/UAV_softbus_client/softbus_sample/vehicle.cpp b/UAV_softbus_client/softbus_sample/vehicle.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2625365f40bf25c4ac734b38d7b61134e89639dc --- /dev/null +++ b/UAV_softbus_client/softbus_sample/vehicle.cpp @@ -0,0 +1,254 @@ +#include "vehicle.h" +#include +#include +#include +#include +#include + +using namespace mavsdk; +using std::chrono::seconds; +using std::this_thread::sleep_for; + +static void halt(int eno){ + exit(eno); +} + +static std::shared_ptr get_system(Mavsdk& mavsdk){ + std::cout << "Waiting to discover system...\n"; + auto prom = std::promise>{}; + auto fut = prom.get_future(); + + // We wait for new systems to be discovered, once we find one that has an + // autopilot, we decide to use it. + Mavsdk::NewSystemHandle handle = mavsdk.subscribe_on_new_system([&mavsdk, &prom, &handle]() { + auto system = mavsdk.systems().back(); + + if (system->has_autopilot()) { + std::cout << "Discovered autopilot\n"; + + // Unsubscribe again as we only want to find one system. + mavsdk.unsubscribe_on_new_system(handle); + prom.set_value(system); + } + }); + + // We usually receive heartbeats at 1Hz, therefore we should find a + // system after around 3 seconds max, surely. + if (fut.wait_for(seconds(3)) == std::future_status::timeout) { + std::cerr << "No autopilot found.\n"; + halt(1); + } + + // Get discovered system now. + return fut.get(); +} + +mavsdk::ConnectionResult Vechile::connect(const char *connection_url){ + _connection_result = _mavsdk.add_any_connection(connection_url); + if (_connection_result != ConnectionResult::Success) { + std::cerr << "Connection failed: " << _connection_result << std::endl; + halt(1); + } + return _connection_result; +} + +Vechile::Vechile(const char *connection_url) + :_mavsdk(), + _connection_result(connect(connection_url)), + _system(get_system(_mavsdk)), + _telemetry(Telemetry{_system}), + _action(Action{_system}){ + + // We want to listen to the altitude of the drone at 1 Hz. + const auto set_rate_result = _telemetry.set_rate_position(1.0); + if (set_rate_result != Telemetry::Result::Success) { + std::cerr << "Setting rate failed: " << set_rate_result << std::endl; + halt(3); + } + + // Set up callback to monitor altitude while the vehicle is in flight + _telemetry.subscribe_position([this](Telemetry::Position position) { + _tl.Latitude = position.latitude_deg; + _tl.Longitude = position.longitude_deg; + _tl.PlatformHeight = position.relative_altitude_m; + }); + + _telemetry.subscribe_attitude_euler([this](Telemetry::EulerAngle eulerAngle){ + _tl.TimeStamp = eulerAngle.timestamp_us; + _tl.Pitch = eulerAngle.pitch_deg; + _tl.Yaw = eulerAngle.yaw_deg; + _tl.Roll = eulerAngle.roll_deg; + }); +} + +void Vechile::printHealthInfo() +{ + // std::stringstream ss; + // ss << "####### Vehicle Health info ####### " << std::endl; + // ss << "is_gyrometer_calibration_ok: " << _telemetry.health().is_gyrometer_calibration_ok << std::endl; + // ss << "is_accelerometer_calibration_ok: " << _telemetry.health().is_accelerometer_calibration_ok << std::endl; + // ss << "is_magnetometer_calibration_ok: " << _telemetry.health().is_magnetometer_calibration_ok << std::endl; + // ss << "is_local_position_ok: " << _telemetry.health().is_local_position_ok << std::endl; + // ss << "is_global_position_ok: " << _telemetry.health().is_global_position_ok << std::endl; + // ss << "is_home_position_ok: " << _telemetry.health().is_home_position_ok << std::endl; + // ss << "is_armable: " << _telemetry.health().is_armable << std::endl; + + std::cout << _telemetry.health() << std::endl; +} + +int Vechile::arm(){ + // // Check until vehicle is ready to arm + // _telemetry.health().is_armable = 1; + // while (_telemetry.health_all_ok() != true) { + // std::cout << "Vehicle is getting ready to arm\n"; + // sleep_for(seconds(1)); + // } + // _telemetry.health().is_armable= true; + // _telemetry.health().is_local_position_ok = true; + // _telemetry.health().is_global_position_ok = true; + // _telemetry.health().is_home_position_ok = true; + + + // Arm vehicle + std::cout << "Arming...\n"; + const Action::Result arm_result = _action.arm(); + + if (arm_result != Action::Result::Success) { + std::cerr << "Arming failed: " << arm_result << '\n'; + return -1; + } + + return 0; +} + +int Vechile::disarm(){ + // Disarm vehicle + std::cout << "Disarming..." << std::endl; + const Action::Result disarm_result = _action.disarm(); + + if (disarm_result != Action::Result::Success) { + std::cerr << "Disarm failed: " << disarm_result << '\n'; + return -1; + } + + return 0; +} + +int Vechile::takeoff(){ + arm(); + // Take off + std::cout << "Taking off...\n"; + const Action::Result takeoff_result = _action.takeoff(); + if (takeoff_result != Action::Result::Success) { + std::cerr << "Takeoff failed: " << takeoff_result << '\n'; + return -1; + } + + // Let it hover for a bit before landing again. + sleep_for(seconds(1)); + return 0; +} + +int Vechile::hover(){ + // Take off + std::cout << "hovering...\n"; + const Action::Result hover_result = _action.hold(); + if (hover_result != Action::Result::Success) { + std::cerr << "hover failed: " << hover_result << '\n'; + return -1; + } + + // Let it hover for a bit before landing again. + sleep_for(seconds(1)); + return 0; +} + +int Vechile::land(){ + std::cout << "Landing...\n"; + const Action::Result land_result = _action.land(); + if (land_result != Action::Result::Success) { + std::cerr << "Land failed: " << land_result << '\n'; + return -1; + } + + // Check if vehicle is still in air + while (_telemetry.in_air()) { + std::cout << "Vehicle is landing...\n"; + sleep_for(seconds(1)); + } + std::cout << "Landed!\n"; + disarm(); + return 0; +} + +bool Vechile::isArmed() { + return _telemetry.armed(); +} + +void Vechile::printVehicleInfo() { + std::stringstream ss; + if (_action.get_maximum_speed().first == Action::Result::Success) { + ss << "maximum spped: " << _action.get_maximum_speed().second << std::endl; + } + if (_action.get_return_to_launch_altitude().first == Action::Result::Success) { + ss << "return to launch altitude: " << _action.get_return_to_launch_altitude().second << std::endl; + } + if (_action.get_takeoff_altitude().first == Action::Result::Success) { + ss << "takeoff altitude: " << _action.get_takeoff_altitude().second << std::endl; + } + ss << _tl.toJson() << std::endl; + std::cout << ss.str(); +} + +TelemetryLite::TelemetryLite() + :UniqueID(0),TimeStamp(0), Longitude(0), Latitude(0), + PlatformHeight(0), Yaw(0), Pitch(0), Roll(0), + VFov(0), HFov(0), FocalLength35mmEq(0){ +} + +void TelemetryLite::dump(){ + std::cout << toJson() << std::endl; +} + +std::string TelemetryLite::toJson(){ + std::stringstream ss; + ss << "{"; + ss << "\"geometry\": {"; + ss << "\"coordinates\": ["; + ss << "9.8072370660407,"; + ss << "172.80638454222"; + ss << "],"; + ss << "\"type\": \"Point\""; + ss << "},"; + ss << "\"type\": \"Feature\","; + ss << "\"properties\": {"; + ss << "\"timestamp\":" << TimeStamp << ","; + ss << "\"x\":" << Longitude << ","; + ss << "\"y\":" << Latitude << ","; + ss << "\"z\":" << PlatformHeight << ","; + ss << "\"yaw\":" << Yaw << ","; + ss << "\"pitch\":" << Pitch << ","; + ss << "\"roll\":" << Roll << ","; + ss << "\"fovX\":" << VFov << ","; + ss << "\"fovY\":" << HFov << ","; + ss << "\"CameraID\": 1"; + ss << "}"; + ss << "}"; + return ss.str(); +} + +TelemetryLite& Vechile::readTelemetry(){ +#if 0 + std::stringstream strtime; + std::time_t currenttime = std::time(0); + char tAll[255]; + std::strftime(tAll, sizeof(tAll), "%Y/%m/%d %H:%M", std::localtime(¤ttime)); + strtime << tAll; + _tl.DateTime = strtime.str(); + _tl.UniqueID++; +#endif + struct timeval tv; + gettimeofday(&tv, 0); + _tl.TimeStamp = tv.tv_sec * 1000 + tv.tv_usec / 1000; + return _tl; +} diff --git "a/dsoftbus/OhOeCommunication/\345\210\206\345\270\203\345\274\217\350\275\257\346\200\273\347\272\277\351\200\232\344\277\241Demo.md" b/dsoftbus/OhOeCommunication/README.md similarity index 100% rename from "dsoftbus/OhOeCommunication/\345\210\206\345\270\203\345\274\217\350\275\257\346\200\273\347\272\277\351\200\232\344\277\241Demo.md" rename to dsoftbus/OhOeCommunication/README.md diff --git a/dsoftbus/OhOeCommunication/softbus_client_sample/entry/src/main/ets/Application/AbilityStage.ts b/dsoftbus/OhOeCommunication/softbus_client_sample/entry/src/main/ets/Application/AbilityStage.ts new file mode 100644 index 0000000000000000000000000000000000000000..1c9fcaafa50d6605b274c4a54a4b6225bc9bc1d0 --- /dev/null +++ b/dsoftbus/OhOeCommunication/softbus_client_sample/entry/src/main/ets/Application/AbilityStage.ts @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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. + */ +import AbilityStage from "@ohos.application.AbilityStage" + +export default class MyAbilityStage extends AbilityStage { + onCreate() { + console.log("[Demo] MyAbilityStage onCreate") + } +} \ No newline at end of file diff --git a/dsoftbus/OhOeCommunication/softbus_client_sample/entry/src/main/ets/MainAbility/MainAbility.ts b/dsoftbus/OhOeCommunication/softbus_client_sample/entry/src/main/ets/MainAbility/MainAbility.ts new file mode 100644 index 0000000000000000000000000000000000000000..f870382553ec44243fad1ac3a9b36fb22acb9d33 --- /dev/null +++ b/dsoftbus/OhOeCommunication/softbus_client_sample/entry/src/main/ets/MainAbility/MainAbility.ts @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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. + */ +import Ability from '@ohos.application.Ability' + +export default class MainAbility extends Ability { + onCreate(want, launchParam) { + console.log("[Demo] MainAbility onCreate") + globalThis.abilityWant = want; + } + + onDestroy() { + console.log("[Demo] MainAbility onDestroy") + } + + onWindowStageCreate(windowStage) { + // Main window is created, set main page for this ability + console.log("[Demo] MainAbility onWindowStageCreate") + + windowStage.setUIContent(this.context, "pages/index", null) + } + + onWindowStageDestroy() { + // Main window is destroyed, release UI related resources + console.log("[Demo] MainAbility onWindowStageDestroy") + } + + onForeground() { + // Ability has brought to foreground + console.log("[Demo] MainAbility onForeground") + } + + onBackground() { + // Ability has back to background + console.log("[Demo] MainAbility onBackground") + } +}; diff --git a/dsoftbus/OhOeCommunication/softbus_client_sample/entry/src/main/ets/common/model/constant.ets b/dsoftbus/OhOeCommunication/softbus_client_sample/entry/src/main/ets/common/model/constant.ets new file mode 100644 index 0000000000000000000000000000000000000000..3c23b04b4e4208fd5d9e12e6a3c85224926684d8 --- /dev/null +++ b/dsoftbus/OhOeCommunication/softbus_client_sample/entry/src/main/ets/common/model/constant.ets @@ -0,0 +1,9 @@ +export const INTERVAL_DISTANCE = 5 + +export const INTERVAL_NUM = INTERVAL_DISTANCE + 1 + +export const IMAGE_OF_ROW = 5 + +export const AI_ANALYSIS_RESULT = 'AI分析结果' + +export const SITUATION_PERCEPTION_REALTIME = '实时事态感知' \ No newline at end of file diff --git a/dsoftbus/OhOeCommunication/softbus_client_sample/entry/src/main/ets/common/model/imagesData.ets b/dsoftbus/OhOeCommunication/softbus_client_sample/entry/src/main/ets/common/model/imagesData.ets new file mode 100644 index 0000000000000000000000000000000000000000..bb498b0658e42bebcf92ed6756c7fd3c2050e314 --- /dev/null +++ b/dsoftbus/OhOeCommunication/softbus_client_sample/entry/src/main/ets/common/model/imagesData.ets @@ -0,0 +1,47 @@ +import fileio from '@ohos.fileio' +import hilog from '@ohos.hilog'; + + +export default class ImageData { + getAIImageData(callback) { + //刚进入页面获取文件夹内容 + let dirPath = '/data/storage/el2/base/haps/entry/files/ai_analysis/' + let imageFiles = [] + hilog.info(0, "SoftBusClient", "[INFO] Start to get images form: %s", dirPath) + this.readImages(dirPath, imageFiles) + + hilog.info(0, "SoftBusClient", "[INFO] New imageFiles length: %d", imageFiles.length) + // return imageFiles + callback(imageFiles) + } + + getSituationImageData(callback) { + //刚进入页面获取文件夹内容 + let dirPath = '/data/storage/el2/base/haps/entry/files/situation_awareness/' + let imageFiles = [] + hilog.info(0, "SoftBusClient", "[INFO] Start to get images form: %s", dirPath) + this.readImages(dirPath, imageFiles) + + hilog.info(0, "SoftBusClient", "[INFO] New imageFiles length: %d", imageFiles.length) + // return imageFiles + callback(imageFiles) + } + + readImages(dirPath, imageFiles) { + let dir = fileio.opendirSync(dirPath); // dir 管理目录 + hilog.debug(0, "SoftBusClient", "[INFO] Read dir: %s", JSON.stringify(dir)) + this.inquireFiles(dirPath, dir, imageFiles); + } + + inquireFiles(dirPath, dir, imageFiles) { + let dirent = dir.readSync(); // 读取下一个目录项 + if (dirent && dirent.isFile()) { + let formatImageFile = "file://" + dirPath + dirent.name + hilog.debug(0, "SoftBusClient", "[INFO] Get images file: %s", formatImageFile) + imageFiles.push(formatImageFile) + this.inquireFiles(dirPath, dir, imageFiles); // 循环获取下一个目录 + } else { + dir.closeSync(); // 关闭目录,释放dir中的文件描述 + } + } +} diff --git a/dsoftbus/OhOeCommunication/softbus_client_sample/entry/src/main/ets/common/model/screenInfo.ets b/dsoftbus/OhOeCommunication/softbus_client_sample/entry/src/main/ets/common/model/screenInfo.ets new file mode 100644 index 0000000000000000000000000000000000000000..59476af70e881b6285ea3c54943b0051095b1d7d --- /dev/null +++ b/dsoftbus/OhOeCommunication/softbus_client_sample/entry/src/main/ets/common/model/screenInfo.ets @@ -0,0 +1,28 @@ +import display from '@ohos.display' +import hilog from '@ohos.hilog'; +import { INTERVAL_NUM, INTERVAL_DISTANCE, IMAGE_OF_ROW } from '../../common/model/constant' + +export default class ScreenInfo { + //获取屏幕信息,获取屏幕尺寸 + getScreenInfo(callback) { + hilog.debug(0, "SoftBusClient", `[INFO] Start to obtain all the display`) + let displayClass = null + display.getAllDisplay((err, data) => { + if (err.code) { + hilog.error(0, "SoftBusClient", `[ERROR] Failed to obtain all the display objects: ${JSON.stringify(err)}`) + return; + } + + hilog.debug(0, "SoftBusClient", `[INFO] data = ${JSON.stringify(data)}`) + displayClass = data[0]; + hilog.debug(0, "SoftBusClient", `[INFO] displayClass = ${JSON.stringify(displayClass)}`) + let displayWidth = displayClass.width + hilog.info(0, "SoftBusClient", `[INFO] displayWidth = ${displayWidth}`) + let displayHeight = displayClass.height + hilog.info(0, "SoftBusClient", `[INFO] displayHeight = ${displayHeight}`) + let screenWidth = displayWidth > displayHeight ? displayHeight : displayWidth + callback((screenWidth - INTERVAL_DISTANCE * INTERVAL_NUM) / IMAGE_OF_ROW) + }) + } +} + diff --git a/dsoftbus/OhOeCommunication/softbus_client_sample/entry/src/main/ets/pages/AIImages.ets b/dsoftbus/OhOeCommunication/softbus_client_sample/entry/src/main/ets/pages/AIImages.ets new file mode 100644 index 0000000000000000000000000000000000000000..4423d1c422ffe1fb3744afdbac90d80d19abe282 --- /dev/null +++ b/dsoftbus/OhOeCommunication/softbus_client_sample/entry/src/main/ets/pages/AIImages.ets @@ -0,0 +1,121 @@ +import hilog from '@ohos.hilog'; +import router from '@ohos.router'; +import ImageData from '../common/model/imagesData' +import ScreenInfo from '../common/model/screenInfo' +import { INTERVAL_DISTANCE, AI_ANALYSIS_RESULT } from '../common/model/constant' + + +@Entry +@Component +export default struct AIImages { + @State imageBgColor: ResourceStr = $r('app.color.transparent') + @State imageIsClick: boolean = false + @State imageIndex: number = 0 + @State photoData: Array = [] + private swiperController: SwiperController = new SwiperController() + private imageData: ImageData = new ImageData() + private screenInfo: ScreenInfo = new ScreenInfo() + + build() { + Stack() { + if (this.imageIsClick) { + Column() { + Swiper(this.swiperController) { + ForEach(this.photoData, (item: string) => { + Image(item).width('100%').height('100%') + .objectFit(ImageFit.Contain).padding(8) + .onClick(() => { + this.imageIsClick = false + }) + }, item => item) + } + .cachedCount(1) + .indicator(false) //是否开启导航点指示器,默认开启true + .index(this.imageIndex) + .loop(false) // 默认开启循环播放 + .duration(100) + .vertical(false) // 默认横向切换 + .itemSpace(0) + .curve(Curve.FastOutSlowIn) // 动画曲线 + .onChange((index: number) => { + console.info(index.toString()) + this.imageIndex = index + console.info(`ypt---Swiper index = ${index}`) + }) + } + .width('100%') + .height('100%') + .zIndex(6) + .backgroundColor(Color.White) + } + Grid() { + ForEach(this.photoData, item => { + GridItem() { + Image(item) + .objectFit(ImageFit.Cover) + .width('100%') + .height('12%') + .onClick(() => { + this.imageIsClick = true + this.imageIndex = this.photoData.indexOf(item) + console.info(`ypt---index = ${this.photoData.indexOf(item)}`) + }) + } + }) + } + .width('100%') + .height('90%') + .margin({ top: '10%' }) + .columnsTemplate('1fr 1fr 1fr 1fr') + .columnsGap(5) + .rowsGap(5) + .onScrollIndex((first: number) => { + console.info(first.toString()) + }) + .width('100%') + .height('90%') + + Row() { + Image($r('app.media.back')) + .width(32) + .height(32) + .borderRadius(32) + .objectFit(ImageFit.Cover) + .margin({ left: 8 }) + .backgroundColor(this.imageBgColor) + .onClick(() => { + this.imageBgColor = $r('app.color.transparent_grey') + router.back() + }) + } + .width('100%') + .height('8%') + .zIndex(3) + .offset({ y: '-45%' }) + .justifyContent(FlexAlign.Start) + } + } + + aboutToAppear() { + let self + self = this + //判断从哪来的 + let router_params = router.getParams() + if (router_params["from"] == AI_ANALYSIS_RESULT) { + //首次进入获取图片 + self.imageData.getAIImageData(callback => { + self.photoData = callback + self.photoData.reserve() + }) + } else { + self.imageData.getSituationImageData(callback => { + self.photoData = callback + self.photoData.reserve() + }) + } + } + + aboutToDisappear() { + router.clear() + } +} \ No newline at end of file diff --git a/dsoftbus/OhOeCommunication/softbus_client_sample/entry/src/main/ets/pages/index.ets b/dsoftbus/OhOeCommunication/softbus_client_sample/entry/src/main/ets/pages/index.ets new file mode 100644 index 0000000000000000000000000000000000000000..6ee49669876d6e5365b88f34427a1d69b66b3a32 --- /dev/null +++ b/dsoftbus/OhOeCommunication/softbus_client_sample/entry/src/main/ets/pages/index.ets @@ -0,0 +1,335 @@ +import router from '@ohos.router'; +import prompt from '@ohos.prompt'; +import hilog from '@ohos.hilog'; +import softbus_client_run from 'libsoftbus_client_run.so' +import { AI_ANALYSIS_RESULT, SITUATION_PERCEPTION_REALTIME } from '../common/model/constant' + +var thisOld + +@Entry +@Component +struct Index { + @State sessionServerInitState: string = "null" + @State sessionConnectState: string = "null" + @State sendDataState: string = '' + @State pictureFile: string = '' + @State hasNewAIImage: boolean = false + @State hasNewSAImage: boolean = false + @State isLoading: boolean = false + @State deviceInfoArray: Array = [] + @State deviceIndex: number = undefined + + callbackPictureSave(fileName) { + hilog.info(0, "SoftBusClient", "[INFO] Image file received: %s", fileName) + if (fileName.search("ai_analysis") != -1) { + thisOld.hasNewAIImage = true + } else { + if (fileName.search("situation_awareness") != -1) { + thisOld.hasNewSAImage = true + } + } + } + + build() { + Stack() { + Column() { + Row() { + if (thisOld.hasNewAIImage) { + Text($r('app.string.hasNewImage')) + .fontSize(16) + .fontColor($r('app.color.white')) + .onClick(() => { + thisOld.hasNewAIImage = false + router.push({ + url: 'pages/AIImages', + params: { "from": AI_ANALYSIS_RESULT } + }) + }) + } + if (thisOld.hasNewSAImage) { + Text($r('app.string.hasNewSAImage')) + .fontSize(16) + .fontColor($r('app.color.white')) + .onClick(() => { + thisOld.hasNewSAImage = false + router.push({ + url: 'pages/AIImages', + params: { "from": SITUATION_PERCEPTION_REALTIME } + }) + }) + } + } + .justifyContent(FlexAlign.Center) + .width('100%') + .height('8%') + .padding(10) + .backgroundColor($r('app.color.transparent_grey')) + + Row() { + Button({ type: ButtonType.Circle, stateEffect: true }) { + if (this.isLoading) { + LoadingProgress() + .color(Color.White) + .width(70) + .height(70) + } else { + Image($r('app.media.refresh')) + .width(48) + .height(48) + .objectFit(ImageFit.Fill) + } + } + .width(64).height(64) + .backgroundColor($r('app.color.transparent')) + .onClick(() => { + this.isLoading = true + this.deviceInfoArray.length = 0 + this.deviceIndex = undefined + this.sessionConnectState = softbus_client_run.sessionConnect() + this.isLoading = false + this.parseDeviceInfo(this.sessionConnectState) + }) + } + .width('90%') + .height('8%') + .justifyContent(FlexAlign.Start) + + Column() { + Text('终端:' + this.deviceInfoArray.length.toString()) + .fontColor($r('app.color.white')) + .fontSize(16) + List() { + ForEach(this.deviceInfoArray, (items) => { + ListItem() { + Row() { + Column() { + Image($r('app.media.phone')) + .width(42) + .height(42) + .objectFit(ImageFit.Cover) + .onClick(() => { + this.deviceIndex = this.deviceInfoArray.indexOf(items) + }) + Text(items[0]).maxLines(2).fontColor($r('app.color.white')) + .fontSize(16) + .textAlign(TextAlign.Center) + .margin({ left: 12 }) + } + + if (this.deviceIndex == this.deviceInfoArray.indexOf(items)) { + Text(items[1]) + .fontColor($r('app.color.white')) + .fontSize(20) + .textAlign(TextAlign.Start) + .margin({ left: 12 }) + } + } + .width('100%') + .margin(8) + } + }) + }.padding(2).height('82%') + } + .alignItems(HorizontalAlign.Start) + .margin({ top: 20 }) + .width('72%') + .height('48%') + + Row() { + Column() { + Text('无人机控制:') + .fontSize(24) + .margin(5) + .fontColor($r('app.color.white')) + Button($r('app.string.UAV_take_off'), { type: ButtonType.Normal }) + .borderRadius(8) + .fontSize(24) + .height('18%') + .width('60%') + .backgroundColor($r('app.color.button_color')) + .margin(5) + .onClick(() => { + let sendResult = softbus_client_run.sendData("UAV", "takeoff", 7) + if (sendResult == 0) { + this.sendDataState = "Send Successful" + } else { + this.sendDataState = "Send Failed" + } + prompt.showToast({ + message: this.sendDataState, + bottom: '20px' + }) + }) + Button($r('app.string.UAV_hover'), { type: ButtonType.Normal }) + .borderRadius(8) + .fontSize(24) + .height('18%') + .width('60%') + .backgroundColor($r('app.color.button_color')) + .margin(5) + .onClick(() => { + let sendResult = softbus_client_run.sendData("UAV", "hover", 5) + if (sendResult == 0) { + this.sendDataState = "Send Successful" + } else { + this.sendDataState = "Send Failed" + } + prompt.showToast({ + message: this.sendDataState, + bottom: '20px' + }) + }) + Button($r('app.string.UAV_land'), { type: ButtonType.Normal }) + .borderRadius(8) + .fontSize(24) + .height('18%') + .width('60%') + .backgroundColor($r('app.color.button_color')) + .margin(5) + .onClick(() => { + let sendResult = softbus_client_run.sendData("UAV", "land", 4) + if (sendResult == 0) { + this.sendDataState = "Send Successful" + } else { + this.sendDataState = "Send Failed" + } + prompt.showToast({ + message: this.sendDataState, + bottom: '20px' + }) + }) + } + .justifyContent(FlexAlign.SpaceEvenly) + .width('50%') + .height('100%') + + Column() { + Text('机器狗控制:') + .fontSize(24) + .margin(5) + .fontColor($r('app.color.white')) + Button($r('app.string.Robot_dog_up'), { type: ButtonType.Normal }) + .borderRadius(8) + .fontSize(24) + .height('18%') + .width('30%') + .backgroundColor($r('app.color.button_color')) + .margin(5) + .onClick(() => { + let sendResult = softbus_client_run.sendData("Robot_dog", "forward", 7) + if (sendResult == 0) { + this.sendDataState = "Send Successful" + } else { + this.sendDataState = "Send Failed" + } + prompt.showToast({ + message: this.sendDataState, + bottom: '20px' + }) + }) + Row() { + Button($r('app.string.Robot_dog_left'), { type: ButtonType.Normal }) + .borderRadius(8) + .fontSize(24) + .height('60%') + .width('30%') + .backgroundColor($r('app.color.button_color')) + .margin(5) + .onClick(() => { + let sendResult = softbus_client_run.sendData("Robot_dog", "left", 4) + if (sendResult == 0) { + this.sendDataState = "Send Successful" + } else { + this.sendDataState = "Send Failed" + } + prompt.showToast({ + message: this.sendDataState, + bottom: '20px' + }) + }) + Button($r('app.string.Robot_dog_right'), { type: ButtonType.Normal }) + .borderRadius(8) + .fontSize(24) + .height('60%') + .width('30%') + .backgroundColor($r('app.color.button_color')) + .margin(5) + .onClick(() => { + let sendResult = softbus_client_run.sendData("Robot_dog", "right", 5) + if (sendResult == 0) { + this.sendDataState = "Send Successful" + } else { + this.sendDataState = "Send Failed" + } + prompt.showToast({ + message: this.sendDataState, + bottom: '20px' + }) + }) + } + .justifyContent(FlexAlign.SpaceEvenly) + .width('100%') + .height('30%') + Button($r('app.string.Robot_dog_down'), { type: ButtonType.Normal }) + .borderRadius(8) + .fontSize(24) + .height('18%') + .width('30%') + .backgroundColor($r('app.color.button_color')) + .margin(5) + .onClick(() => { + let sendResult = softbus_client_run.sendData("Robot_dog", "backward", 8) + if (sendResult == 0) { + this.sendDataState = "Send Successful" + } else { + this.sendDataState = "Send Failed" + } + prompt.showToast({ + message: this.sendDataState, + bottom: '20px' + }) + }) + } + .justifyContent(FlexAlign.SpaceEvenly) + .width('50%') + .height('100%') + } + .height('34%') + .width('100%') + .justifyContent(FlexAlign.SpaceEvenly) + .padding({ bottom: 8 }) + .backgroundColor('#07309E') + } + .width('100%') + .height('100%') + .backgroundImage($r('app.media.background')) + .backgroundImageSize({ width: '100%', height: '75%' }) + } + } + + aboutToAppear() { + //进入页面初始化 + thisOld = this + this.sessionServerInitState = softbus_client_run.sessionServerInit(this.callbackPictureSave) + prompt.showToast({ + message: this.sessionServerInitState, + bottom: '20px' + }) + } + + aboutToDisappear() { + //关闭 + softbus_client_run.sessionDisconnect() + } + + parseDeviceInfo(deviceInfo: string) { + let deviceInfoArrayTemp = deviceInfo.split(';') + deviceInfoArrayTemp.pop() + deviceInfoArrayTemp.forEach(element => { + let startIndex = element.indexOf(': ') + let endIndex = element.indexOf('\nipAddress') + let deviceName = element.substring(startIndex + 1, endIndex) + this.deviceInfoArray.push([deviceName, element]) + }); + } +} \ No newline at end of file diff --git a/dsoftbus/OhOeCommunication/softbus_client_sample/entry/src/main/ets/pages/videoPlay.ets b/dsoftbus/OhOeCommunication/softbus_client_sample/entry/src/main/ets/pages/videoPlay.ets new file mode 100644 index 0000000000000000000000000000000000000000..65fc09e1693abbf3f6ede9d692c4c285048ad526 --- /dev/null +++ b/dsoftbus/OhOeCommunication/softbus_client_sample/entry/src/main/ets/pages/videoPlay.ets @@ -0,0 +1,102 @@ +import router from '@ohos.router'; +import hilog from '@ohos.hilog'; + + +@Entry +@Component +export default struct VideoPlay { + @State imageBgColor: ResourceStr = $r('app.color.transparent') + @State muted: boolean = false + @State autoPlay: boolean = true + @State controls: boolean = true //控制栏 + myVideoController: VideoController = new VideoController() + @State pause: boolean = false + + build() { + //操作 + Column() { + Row() { + Image($r('app.media.back')) + .width(32) + .height(32) + .borderRadius(32) + .objectFit(ImageFit.Cover) + .margin({ left: 8 }) + .backgroundColor(this.imageBgColor) + .onClick(() => { + this.imageBgColor = $r('app.color.transparent_grey') + router.back() + }) + } + .width('100%') + .height('6%') + .backgroundColor($r('app.color.transparent_grey')) + .justifyContent(FlexAlign.Start) + + Video({ + src: $rawfile('fire_detection.mp4'), // 视频播放源的路径 + controller: this.myVideoController // 控制器 + }) + .muted(this.muted) // 是否静音 + .autoPlay(this.autoPlay) // 是否自动播放 + .controls(this.controls) // 控制视频播放的控制栏是否显示 + .objectFit(ImageFit.Contain) // 视频显示模式 + .loop(false) // 是否单个视频循环播放 + .width('100%') + .aspectRatio(1.33) + .onClick(() => { + //点击视频调出控制栏 + this.controls = !this.controls + }) + .onStart(() => { + // 播放时触发该事件 + hilog.info(0, "SoftBusClient", "[INFO] the video start play") + }) + .onPause(() => { + // 暂停时触发该事件 + hilog.info(0, "SoftBusClient", "[INFO] [INFO] the video pause play") + }) + .onFinish(() => { + // 播放结束时触发该事件 + }) + + Row() { + Button({ type: ButtonType.Circle }) { + Image(this.pause ? $r('app.media.play_circle') : $r('app.media.pause_circle')) + } + .height('60%') + .backgroundColor($r('app.color.transparent_grey')) + .onClick(() => { + this.pause = !this.pause + this.pause ? this.myVideoController.pause() : this.myVideoController.start() + }) + + Button({ type: ButtonType.Circle }) { + Image($r('app.media.full_screen')).rotate({ + angle: -45 + }) + } + .height('60%') + .backgroundColor($r('app.color.transparent_grey')) + .onClick(() => { + this.myVideoController.requestFullscreen(true) + }) + } + .justifyContent(FlexAlign.SpaceBetween) + .width('100%') + .height('8%') + .backgroundColor($r('app.color.transparent_grey')) + } + .width('100%') + .height('100%') + } + + aboutToAppear() { + //进入之后就全屏播放 + this.myVideoController.start() + } + + aboutToDisappear() { + router.clear(); + } +} \ No newline at end of file