pull/5/head
zoeda 1 year ago
parent ddc735f288
commit be763065c4

5
src/.gitignore vendored

@ -0,0 +1,5 @@
.deveco/**
.vscode/**
**/.DS_Store
.remote-sync.json
.ftpconfig*

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.

@ -0,0 +1,11 @@
### 该问题是怎么引起的?
### 重现步骤
### 报错信息

@ -0,0 +1,12 @@
### 相关的Issue
### 原因(目的、解决的问题等)
### 描述(做了什么,变更了什么)
### 测试用例(新增、改动、可能影响的功能)

@ -0,0 +1,177 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS

@ -0,0 +1,42 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- Copyright (c) 2022 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.
This is the configuration file template for OpenHarmony OSS Audit Tool, please copy it to your project root dir and modify it refer to OpenHarmony/tools_oat/README.
-->
<configuration>
<oatconfig>
<licensefile></licensefile>
<policylist>
<policy name="projectPolicy" desc="">
</policy>
</policylist>
<filefilterlist>
<filefilter name="defaultFilter" desc="Files not to check">
<filteritem type="filename" name="*.png|*.pngraw|*.json" desc="Temp files"/>
</filefilter>
<filefilter name="defaultPolicyFilter" desc="Filters for compatibilitylicense header policies">
<filteritem type="filename" name="*.png|*.pngraw|*.json" desc="NoLicenseHeader"/>
</filefilter>
<filefilter name="copyrightPolicyFilter" desc="Filters for copyright header policies">
<filteritem type="filename" name="*.png|*.pngraw|*.json" desc="InvalidCopyright file"/>
</filefilter>
<filefilter name="binaryFileTypePolicyFilter" desc="Filters for binary file policies">
<filteritem type="filename" name="*.png|*.pngraw|*.json" desc="already checked"/>
</filefilter>
</filefilterlist>
</oatconfig>
</configuration>

@ -0,0 +1,26 @@
# WIFI\_IOT\_APP<a name="EN-US_TOPIC_0000001132694217"></a>
- [Introduction](#section11660541593)
- [Directory Structure](#section1464106163817)
- [Repositories Involved](#section1718733212019)
## Introduction<a name="section11660541593"></a>
The WIFI\_IOT\_APP module provides sample code for iothardware, demolink, and samgr.
## Directory Structure<a name="section1464106163817"></a>
```
applications/sample/wifi-iot/ # Sample code
└── app
├── BUILD.gn # Build script
├── demolink # Sample code for integrating demolink
├── iothardware # Sample code for LED operations
├── samgr # Sample code for the service framework
└── startup
```
## Repositories Involved<a name="section1718733212019"></a>
applications\_sample\_wifi-iot

@ -0,0 +1,26 @@
# WIFI\_IOT\_APP组件<a name="ZH-CN_TOPIC_0000001132694217"></a>
- [简介](#section11660541593)
- [目录](#section1464106163817)
- [涉及仓](#section1718733212019)
## 简介<a name="section11660541593"></a>
WIFI\_IOT\_APP组件提供了iothardware、demolink、samgr等示例代码。
## 目录<a name="section1464106163817"></a>
```
applications/sample/wifi-iot/ # sample模块目录
└── app
├── BUILD.gn # 模块构建脚本
├── demolink # demolink集成示例代码
├── iothardware # LED操作示例代码
├── samgr # 服务框架示例代码
└── startup
```
## 涉及仓<a name="section1718733212019"></a>
applications\_sample\_wifi-iot

@ -0,0 +1,18 @@
# Copyright (c) 2020-2022 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("//build/lite/config/component/lite_component.gni")
lite_component("app") {
features = [ "cloud_to_uart:cloud_uart", ]
}

@ -0,0 +1,41 @@
# Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
# 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.
static_library("cloud_uart") {
sources = [
"app_demo_iot.c",
"cjson_init.c",
"iot_hmac.c",
"iot_log.c",
"iot_main.c",
"iot_profile.c",
"iot_sta.c",
"hal_iot_gpio_ex.c",
"hisignalling_protocol.c",
]
include_dirs = [
"./",
"//utils/native/lite/include",
"//kernel/liteos_m/kal/cmsis",
"//base/iot_hardware/peripheral/interfaces/kits",
"//device/soc/hisilicon/hi3861v100/sdk_liteos/third_party/lwip_sack/include/lwip",
"//third_party/cJSON",
"//device/soc/hisilicon/hi3861v100/sdk_liteos/third_party/mbedtls/include/mbedtls",
"//foundation/communication/wifi_lite/interfaces/wifiservice",
"//device/soc/hisilicon/hi3861v100/sdk_liteos/third_party/paho.mqtt.c/include/mqtt",
"//device/soc/hisilicon/hi3861v100/sdk_liteos/third_party/libcoap/include/coap2",
]
defines = [ "WITH_LWIP" ]
}

@ -0,0 +1,507 @@
/*
* Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
* 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.
*/
#include <hi_task.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <hi_wifi_api.h>
#include <hi_mux.h>
#include <hi_io.h>
#include <hi_gpio.h>
#include "iot_config.h"
#include "iot_log.h"
#include "iot_main.h"
#include "iot_profile.h"
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_gpio.h"
#include <hi_stdlib.h>
#include <hisignalling_protocol.h>
#include <hi_uart.h>
#include <app_demo_uart.h>
#include <iot_uart.h>
#include "iot_gpio_ex.h"
/* attribute initiative to report */
#define TAKE_THE_INITIATIVE_TO_REPORT
#define TWO_SECOND (2000)
/* oc request id */
#define CN_COMMADN_INDEX "commands/request_id="
#define WECHAT_SUBSCRIBE_control "slot_num"
#define WECHAT_SUBSCRIBE_channel1 "slot_1"
#define WECHAT_SUBSCRIBE_channel2 "slot_2"
#define WECHAT_SUBSCRIBE_channel3 "slot_3"
#define WECHAT_SUBSCRIBE_channel4 "4"
#define topic_data "YT32IOSCAL/Hi38611_mqtt/data"
#define topic_event "YT32IOSCAL/Hi38611_mqtt/event"
#define topic_control "YT32IOSCAL/Hi38611_mqtt/control"
#define human_detect_io 7
int g_ligthStatus = -1;
int control_success = 0;
char *control_flag = "failed";
char *message = NULL;
UartDefConfig uartDefConfig = {0};
//int slot1 = 20,slot2 = 20, slot3 = 20, slot4 = 20;
typedef void (*FnMsgCallBack)(hi_gpio_value val);
typedef struct FunctionCallback {
hi_bool stop;
hi_u32 conLost;
hi_u32 queueID;
hi_u32 iotTaskID;
FnMsgCallBack msgCallBack;
}FunctionCallback;
FunctionCallback g_functinoCallback;
// uart
static void Uart1GpioCOnfig(void)
{
#ifdef ROBOT_BOARD
IoSetFunc(HI_IO_NAME_GPIO_5, IOT_IO_FUNC_GPIO_5_UART1_RXD);
IoSetFunc(HI_IO_NAME_GPIO_6, IOT_IO_FUNC_GPIO_6_UART1_TXD);
/* IOT_BOARD */
#elif defined (EXPANSION_BOARD)
IoSetFunc(HI_IO_NAME_GPIO_0, IOT_IO_FUNC_GPIO_0_UART1_TXD);
IoSetFunc(HI_IO_NAME_GPIO_1, IOT_IO_FUNC_GPIO_1_UART1_RXD);
#endif
}
/* CPU Sleep time Set */
unsigned int TaskMsleep(unsigned int ms)
{
if (ms <= 0) {
return HI_ERR_FAILURE;
}
return hi_sleep((hi_u32)ms);
}
static void DeviceConfigInit(hi_gpio_value val)
{
hi_io_set_func(HI_IO_NAME_GPIO_9, HI_IO_FUNC_GPIO_9_GPIO);
hi_gpio_set_dir(HI_GPIO_IDX_9, HI_GPIO_DIR_OUT);
hi_gpio_set_ouput_val(HI_GPIO_IDX_9, val);
}
static void engine_control(unsigned int IO){
IoTGpioInit(IO);
IoSetFunc(IO, 0);
IoTGpioSetDir(IO, IOT_GPIO_DIR_OUT);
IoTGpioSetOutputVal(IO, IOT_GPIO_VALUE1);
IOT_LOG_DEBUG("Engine at GPIO:%u started!\n", IO);
hi_udelay(20000);
IoTGpioSetOutputVal(IO, IOT_GPIO_VALUE0);
IOT_LOG_DEBUG("Engine at GPIO:%u stopped!\n", IO);
}
static void engine_start(unsigned int IO){
IoSetFunc(IO, 0);
IoTGpioSetDir(IO, IOT_GPIO_DIR_OUT);
IoTGpioSetOutputVal(IO, IOT_GPIO_VALUE1);
IOT_LOG_DEBUG("Engine at GPIO:%u started!\n", IO);
}
static void engine_stop(unsigned int IO){
IoSetFunc(IO, 0);
IoTGpioSetDir(IO, IOT_GPIO_DIR_OUT);
IoTGpioSetOutputVal(IO, IOT_GPIO_VALUE0);
IOT_LOG_DEBUG("Engine at GPIO:%u stopped!\n", IO);
}
static void engine_reinit(unsigned int IO){
IoTGpioInit(IO);
IoSetFunc(IO, 0);
IoTGpioSetDir(IO, IOT_GPIO_DIR_OUT);
IoTGpioSetOutputVal(IO, IOT_GPIO_VALUE0);
IOT_LOG_DEBUG("Engine at GPIO:%u initialized!\n", IO);
}
static void all_engine_reinit(){
engine_reinit(6);
engine_reinit(7);
engine_reinit(9);
engine_reinit(10);
IOT_LOG_DEBUG("All engines initialized!\n");
}
static void Sensor_init(){
IoTGpioInit(human_detect_io);
IoSetFunc(human_detect_io, 0);
IoTGpioSetDir(human_detect_io, IOT_GPIO_DIR_IN);
IOT_LOG_DEBUG("Sensor initialized!\n");
}
static int DeviceMsgCallback(FnMsgCallBack msgCallBack)
{
g_functinoCallback.msgCallBack = msgCallBack;
return 0;
}
static void wechatControlDeviceMsg(hi_gpio_value val)
{
DeviceConfigInit(val);
}
// < this is the callback function, set to the mqtt, and if any messages come, it will be called
// < The payload here is the json string
static void DemoMsgRcvCallBack(int qos, const char *topic, const char *payload)/*定义3861接收到json文件后的操作*/
{
IOT_LOG_DEBUG("RCVMSG:QOS:%d TOPIC:%s PAYLOAD:%s\r\n", qos, topic, payload);
printf(strstr(payload, WECHAT_SUBSCRIBE_control));
/* 云端下发命令后,板端的操作处理 */
if (strstr(payload, WECHAT_SUBSCRIBE_control) != NULL) {
//printf(strstr(payload, WECHAT_SUBSCRIBE_control));
all_engine_reinit();
if (strstr(payload, WECHAT_SUBSCRIBE_channel1) != NULL) {
engine_start(6);
hi_udelay(4000000);
engine_stop(6);
wechatControlDeviceMsg(HI_GPIO_VALUE1);
control_success = 1;
control_flag = payload;
}
else if (strstr(payload, WECHAT_SUBSCRIBE_channel2) != NULL) {
engine_start(7);
hi_udelay(4000000);
engine_stop(7);
wechatControlDeviceMsg(HI_GPIO_VALUE1);
control_success = 1;
control_flag = payload;
}
else if (strstr(payload, WECHAT_SUBSCRIBE_channel3) != NULL) {
engine_start(2);
hi_udelay(4000000);
engine_stop(2);
wechatControlDeviceMsg(HI_GPIO_VALUE1);
control_success = 1;
control_flag = payload;
}
else if (strstr(payload, WECHAT_SUBSCRIBE_channel4) != NULL) {
engine_start(10);
hi_udelay(4000000);
engine_stop(10);
wechatControlDeviceMsg(HI_GPIO_VALUE1);
control_success = 1;
control_flag = payload;
}
}
return HI_NULL;
}
static void DemoMsgRcvsynchronize(int qos, const char *topic, const char *payload)
{
message = payload;
}
/* publish sample */
/*hi_void IotPublishSample(int slot1, int slot2, int slot3, int slot4)
{
// reported attribute
WeChatProfile weChatProfile = {
.subscribeType = "type",
.status.subState = "state",
.status.subReport = "reported",
.status.reportVersion = "version",
.status.Token = "clientToken",
// report motor
.reportAction.subDeviceActionMotor = "slot_1",
.reportAction.motorActionStatus = slot1, // 0 : motor off
// report temperature
.reportAction.subDeviceActionTemperature = "slot_2",
.reportAction.temperatureData = slot2, // 30 :temperature data
// report humidity
.reportAction.subDeviceActionHumidity = "slot_3",
.reportAction.humidityActionData = slot3, // humidity data
// report light_intensity
.reportAction.subDeviceActionLightIntensity = "slot_4",
.reportAction.lightIntensityActionData = slot4, // 60 : light_intensity
};
// report light
if (g_ligthStatus == HI_TRUE) {
weChatProfile.reportAction.subDeviceActionLight = "light";
weChatProfile.reportAction.lightActionStatus = 1; // 1: light on
} else if (g_ligthStatus == HI_FALSE) {
weChatProfile.reportAction.subDeviceActionLight = "light";
weChatProfile.reportAction.lightActionStatus = 0; // 0: light off
} else {
weChatProfile.reportAction.subDeviceActionLight = "light";
weChatProfile.reportAction.lightActionStatus = 0; // 0: light off
}
//profile report
IoTProfilePropertyReport(CONFIG_USER_ID, &weChatProfile1);
}*/
// < this is the demo main task entry,here we will set the wifi/cjson/mqtt ready and
// < wait if any work to do in the while
//static hi_void *DemoEntry(const char *arg)
//{
//int feedback = 0;
/*6WifiStaReadyWait();
cJsonInit();
IoTMain();
/* 云端下发回调 */
//IoTSetMsgCallback(DemoMsgRcvCallBack);
/*if (control_success == 1)
{
//Uart1GpioCOnfig();
feedback = IoTUartWrite(DEMO_UART_NUM, control_flag, 7);
printf("feedback: %d", feedback);
}*/
/* 主动上报 */
/*#ifdef TAKE_THE_INITIATIVE_TO_REPORT
while (1) {
// 用户可以在这调用发布函数进行发布,需要用户自己写调用函数
IotPublishSample(slot1,slot2,slot3,slot4); // 发布例程
#endif*/
//TaskMsleep(TWO_SECOND);
//return NULL;
//}
///////////////////////////////////////////////////////////////////////////////////////////
int SetUartRecvFlag(UartRecvDef def)
{
if (def == UART_RECV_TRUE) {
uartDefConfig.g_uartReceiveFlag = HI_TRUE;
} else {
uartDefConfig.g_uartReceiveFlag = HI_FALSE;
}
return uartDefConfig.g_uartReceiveFlag;
}
int GetUartConfig(UartDefType type)
{
int receive = 0;
switch (type) {
case UART_RECEIVE_FLAG:
receive = uartDefConfig.g_uartReceiveFlag;
break;
case UART_RECVIVE_LEN:
receive = uartDefConfig.g_uartLen;
break;
default:
break;
}
return receive;
}
void ResetUartReceiveMsg(void)
{
(void)memset_s(uartDefConfig.g_receiveUartBuff, sizeof(uartDefConfig.g_receiveUartBuff),
0x0, sizeof(uartDefConfig.g_receiveUartBuff));
}
unsigned char *GetUartReceiveMsg(void)
{
return uartDefConfig.g_receiveUartBuff;
}
static hi_void *UartDemoTask(char *param)
{
hi_u8 uartBuff[UART_BUFF_SIZE] = {0};
char *recBuff = NULL;
int feedback_1 = 0;
int feedback_2 = 0;
int length = 0;
unsigned char *detect_flag = "start";
unsigned char *data_send = "jdata";
IotGpioValue value = IOT_GPIO_VALUE0;
hi_unref_param(param);
printf("Initialize uart demo successfully, please enter some datas via DEMO_UART_NUM port...\n");
Uart1GpioCOnfig();
Sensor_init();
printf("Please wait for 60 seconds for the system to start...\n");
TaskMsleep(60000);
printf("Done!\n");
for (;;)
{
int isTimeOut = 0;
IoTGpioGetInputVal(human_detect_io, &value);
if(value == IOT_GPIO_VALUE1)
{
//get from cloud and send to 3516
IoTUartWrite(DEMO_UART_NUM, detect_flag, 5);
IoTSetMsgCallback(DemoMsgRcvsynchronize);
//start to work
feedback_1 = IoTUartWrite(DEMO_UART_NUM, detect_flag, 5);//
printf("uart feedback %d\n", feedback_1);
//TaskMsleep(20);
uartDefConfig.g_uartLen = IoTUartRead(DEMO_UART_NUM, uartBuff, UART_BUFF_SIZE);
int waitCount = 0;
while (!((uartDefConfig.g_uartLen > 0) && (uartBuff[0] == 0xaa) && (uartBuff[1] == 0x55))) {
uartDefConfig.g_uartLen = IoTUartRead(DEMO_UART_NUM, uartBuff, UART_BUFF_SIZE);
TaskMsleep(50);
waitCount += 1;
if(waitCount > 400){
isTimeOut = 1;
printf("Timeout!\n");
break;
}
}
if(isTimeOut)
continue;
if (GetUartConfig(UART_RECEIVE_FLAG) == HI_FALSE) {
(void)memcpy_s(uartDefConfig.g_receiveUartBuff, uartDefConfig.g_uartLen,
uartBuff, uartDefConfig.g_uartLen);/*uartBuff中的信息放到uartDefConfig.g_receiveUartBuff*/
(void)SetUartRecvFlag(UART_RECV_TRUE);
}
printf("UART start\n");
printf("len:%d\n", uartDefConfig.g_uartLen);
recBuff = (char*)malloc(uartDefConfig.g_uartLen-3);
for (int i = 0; i<uartDefConfig.g_uartLen; i++)
{
if(i <= 2)
{
printf("0x%x ", uartBuff[i]);
}
else
{
printf("%c ", uartBuff[i]);
recBuff[i-3] = uartBuff[i];
}
}
//TaskMsleep(20); /* 20:sleep 20ms */
/*send to cloud*/
IoTProfilePropertyReport_uart(CONFIG_USER_ID, recBuff);
//printf("communicatuon completed\n");
free(recBuff);
TaskMsleep(50);
IoTSetMsgCallback(DemoMsgRcvCallBack);
while (control_success == 0)
{
TaskMsleep(50);
}
length = strlen(control_flag);
char len = length+'0';
IoTUartWrite(DEMO_UART_NUM, len, strlen(len));
TaskMsleep(10);
feedback_2 = IoTUartWrite(DEMO_UART_NUM, control_flag, length);
printf("feedback: %d\n", feedback_2);
}
TaskMsleep(50);
}
return HI_NULL;
}
/*
* This demo simply shows how to read datas from UART2 port and then echo back.
*/
/*hi_void UartTransmit(hi_void)
{
hi_u32 ret = 0;
IotUartAttribute uartAttr = {
.baudRate = 115200, /* baudRate: 115200
.dataBits = 8, /* dataBits: 8bits
.stopBits = 1, /* stop bit
.parity = 0,
};
/* Initialize uart driver
ret = IoTUartInit(DEMO_UART_NUM, &uartAttr);
if (ret != HI_ERR_SUCCESS) {
printf("Failed to init uart! Err code = %d\n", ret);
return;
}
/* Create a task to handle uart communication
osThreadAttr_t attr = {0};
attr.attr_bits = 0U;
attr.cb_mem = NULL;
attr.cb_size = 0U;
attr.stack_mem = NULL;
attr.stack_size = 8096;
attr.priority = UART_DEMO_TASK_PRIORITY;
attr.name = (hi_char*)"uart demo";
if (osThreadNew((osThreadFunc_t)UartDemoTask, NULL, &attr) == NULL) {
printf("Falied to create uart demo task!\n");
}
}*/
//SYS_RUN(UartTransmit);
///////////////////////////////////////////////////////////////////////////////////////////
// < This is the demo entry, we create a task here,
// and all the works has been done in the demo_entry
#define CN_IOT_TASK_STACKSIZE 0x1000
#define CN_IOT_TASK_PRIOR 25
#define CN_IOT_TASK_NAME "IOTDEMO"
static void AppDemoIot(void)
{
hi_u32 ret = 0;
IotUartAttribute uartAttr = {
.baudRate = 115200, /* baudRate: 115200 */
.dataBits = 8, /* dataBits: 8bits */
.stopBits = 1, /* stop bit */
.parity = 0,
};
/* Initialize uart driver */
ret = IoTUartInit(DEMO_UART_NUM, &uartAttr);
if (ret != HI_ERR_SUCCESS) {
printf("Failed to init uart! Err code = %d\n", ret);
return;
}
osThreadAttr_t attr;
IoTWatchDogDisable();
WifiStaReadyWait();
cJsonInit();
IoTMain();
attr.name = "IOTDEMO";
attr.attr_bits = 0U;
attr.cb_mem = NULL;
attr.cb_size = 0U;
attr.stack_mem = NULL;
attr.stack_size = CN_IOT_TASK_STACKSIZE;
attr.priority = CN_IOT_TASK_PRIOR;
if (osThreadNew((osThreadFunc_t)UartDemoTask, NULL, &attr) == NULL) {
printf("Falied to create uart demo task!\n");
}
}
SYS_RUN(AppDemoIot);

@ -0,0 +1,48 @@
/*
* Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
* 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 APP_DEMO_UART_H
#define APP_DEMO_UART_H
#define UART_BUFF_SIZE 1024
#define WRITE_BY_INT
#define UART_DEMO_TASK_STAK_SIZE 2048
#define UART_DEMO_TASK_PRIORITY 25
#define DEMO_UART_NUM HI_UART_IDX_1
typedef enum {
UART_RECEIVE_FLAG = 0,
UART_RECVIVE_LEN,
UART_SEND_FLAG = 2,
UART_SEND_LEN
}UartDefType;
typedef enum {
UART_RECV_TRUE = 0,
UART_RECV_FALSE,
}UartRecvDef;
typedef struct {
unsigned int uartChannel;
unsigned char g_receiveUartBuff[UART_BUFF_SIZE];
int g_uartReceiveFlag;
int g_uartLen;
}UartDefConfig;
int SetUartRecvFlag(UartRecvDef def);
int GetUartConfig(UartDefType type);
void ResetUartReceiveMsg(void);
unsigned char *GetUartReceiveMsg(void);
#endif

@ -0,0 +1,38 @@
/*
* Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
* 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.
*/
#include <stdint.h>
#include <cJSON.h>
#include <hi_mem.h>
static void *cJsonMalloc(size_t sz)
{
return hi_malloc(0, sz);
}
static void cJsonFree(const char *p)
{
hi_free(0, p);
}
void cJsonInit(void)
{
cJSON_Hooks hooks;
hooks.malloc_fn = cJsonMalloc;
hooks.free_fn = cJsonFree;
cJSON_InitHooks(&hooks);
return;
}

@ -0,0 +1,46 @@
/*
* Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
* 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.
*/
#include "iot_errno.h"
#include "iot_gpio_ex.h"
#include "hi_gpio.h"
#include "hi_io.h"
#include "hi_task.h"
#include "hi_types_base.h"
unsigned int IoSetPull(unsigned int id, IotIoPull val)
{
if (id >= HI_GPIO_IDX_MAX) {
return IOT_FAILURE;
}
return hi_io_set_pull((hi_io_name)id, (hi_io_pull)val);
}
unsigned int IoSetFunc(unsigned int id, unsigned char val)
{
if (id >= HI_GPIO_IDX_MAX) {
return IOT_FAILURE;
}
return hi_io_set_func((hi_io_name)id, val);
}
/*unsigned int TaskMsleep(unsigned int ms)
{
if (ms <= 0) {
return IOT_FAILURE;
}
return hi_sleep((hi_u32)ms);
}*/

@ -0,0 +1,286 @@
/*
* Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
* 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.
*/
#include <hi_types_base.h>
#include <hi_early_debug.h>
#include <hi_stdlib.h>
#include <hi_uart.h>
#include <hi_task.h>
#include <app_demo_uart.h>
#include <iot_uart.h>
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_gpio_ex.h"
#include "hi_io.h"
#include "iot_gpio.h"
#include "hisignalling_protocol.h"
#define LED_TEST_GPIO 9
#define LED_INTERVAL_TIME_US 300000
hi_u8 g_sendUartBuff[UART_BUFF_SIZE];
UartDefConfig recConfig = {0};
/*
* crc32 Verification implementation
*/
static const unsigned int crc32table[] = {
0x00000000L, 0x77073096L, 0xee0e612cL, 0x990951baL,
0x076dc419L, 0x706af48fL, 0xe963a535L, 0x9e6495a3L,
0x0edb8832L, 0x79dcb8a4L, 0xe0d5e91eL, 0x97d2d988L,
0x09b64c2bL, 0x7eb17cbdL, 0xe7b82d07L, 0x90bf1d91L,
0x1db71064L, 0x6ab020f2L, 0xf3b97148L, 0x84be41deL,
0x1adad47dL, 0x6ddde4ebL, 0xf4d4b551L, 0x83d385c7L,
0x136c9856L, 0x646ba8c0L, 0xfd62f97aL, 0x8a65c9ecL,
0x14015c4fL, 0x63066cd9L, 0xfa0f3d63L, 0x8d080df5L,
0x3b6e20c8L, 0x4c69105eL, 0xd56041e4L, 0xa2677172L,
0x3c03e4d1L, 0x4b04d447L, 0xd20d85fdL, 0xa50ab56bL,
0x35b5a8faL, 0x42b2986cL, 0xdbbbc9d6L, 0xacbcf940L,
0x32d86ce3L, 0x45df5c75L, 0xdcd60dcfL, 0xabd13d59L,
0x26d930acL, 0x51de003aL, 0xc8d75180L, 0xbfd06116L,
0x21b4f4b5L, 0x56b3c423L, 0xcfba9599L, 0xb8bda50fL,
0x2802b89eL, 0x5f058808L, 0xc60cd9b2L, 0xb10be924L,
0x2f6f7c87L, 0x58684c11L, 0xc1611dabL, 0xb6662d3dL,
0x76dc4190L, 0x01db7106L, 0x98d220bcL, 0xefd5102aL,
0x71b18589L, 0x06b6b51fL, 0x9fbfe4a5L, 0xe8b8d433L,
0x7807c9a2L, 0x0f00f934L, 0x9609a88eL, 0xe10e9818L,
0x7f6a0dbbL, 0x086d3d2dL, 0x91646c97L, 0xe6635c01L,
0x6b6b51f4L, 0x1c6c6162L, 0x856530d8L, 0xf262004eL,
0x6c0695edL, 0x1b01a57bL, 0x8208f4c1L, 0xf50fc457L,
0x65b0d9c6L, 0x12b7e950L, 0x8bbeb8eaL, 0xfcb9887cL,
0x62dd1ddfL, 0x15da2d49L, 0x8cd37cf3L, 0xfbd44c65L,
0x4db26158L, 0x3ab551ceL, 0xa3bc0074L, 0xd4bb30e2L,
0x4adfa541L, 0x3dd895d7L, 0xa4d1c46dL, 0xd3d6f4fbL,
0x4369e96aL, 0x346ed9fcL, 0xad678846L, 0xda60b8d0L,
0x44042d73L, 0x33031de5L, 0xaa0a4c5fL, 0xdd0d7cc9L,
0x5005713cL, 0x270241aaL, 0xbe0b1010L, 0xc90c2086L,
0x5768b525L, 0x206f85b3L, 0xb966d409L, 0xce61e49fL,
0x5edef90eL, 0x29d9c998L, 0xb0d09822L, 0xc7d7a8b4L,
0x59b33d17L, 0x2eb40d81L, 0xb7bd5c3bL, 0xc0ba6cadL,
0xedb88320L, 0x9abfb3b6L, 0x03b6e20cL, 0x74b1d29aL,
0xead54739L, 0x9dd277afL, 0x04db2615L, 0x73dc1683L,
0xe3630b12L, 0x94643b84L, 0x0d6d6a3eL, 0x7a6a5aa8L,
0xe40ecf0bL, 0x9309ff9dL, 0x0a00ae27L, 0x7d079eb1L,
0xf00f9344L, 0x8708a3d2L, 0x1e01f268L, 0x6906c2feL,
0xf762575dL, 0x806567cbL, 0x196c3671L, 0x6e6b06e7L,
0xfed41b76L, 0x89d32be0L, 0x10da7a5aL, 0x67dd4accL,
0xf9b9df6fL, 0x8ebeeff9L, 0x17b7be43L, 0x60b08ed5L,
0xd6d6a3e8L, 0xa1d1937eL, 0x38d8c2c4L, 0x4fdff252L,
0xd1bb67f1L, 0xa6bc5767L, 0x3fb506ddL, 0x48b2364bL,
0xd80d2bdaL, 0xaf0a1b4cL, 0x36034af6L, 0x41047a60L,
0xdf60efc3L, 0xa867df55L, 0x316e8eefL, 0x4669be79L,
0xcb61b38cL, 0xbc66831aL, 0x256fd2a0L, 0x5268e236L,
0xcc0c7795L, 0xbb0b4703L, 0x220216b9L, 0x5505262fL,
0xc5ba3bbeL, 0xb2bd0b28L, 0x2bb45a92L, 0x5cb36a04L,
0xc2d7ffa7L, 0xb5d0cf31L, 0x2cd99e8bL, 0x5bdeae1dL,
0x9b64c2b0L, 0xec63f226L, 0x756aa39cL, 0x026d930aL,
0x9c0906a9L, 0xeb0e363fL, 0x72076785L, 0x05005713L,
0x95bf4a82L, 0xe2b87a14L, 0x7bb12baeL, 0x0cb61b38L,
0x92d28e9bL, 0xe5d5be0dL, 0x7cdcefb7L, 0x0bdbdf21L,
0x86d3d2d4L, 0xf1d4e242L, 0x68ddb3f8L, 0x1fda836eL,
0x81be16cdL, 0xf6b9265bL, 0x6fb077e1L, 0x18b74777L,
0x88085ae6L, 0xff0f6a70L, 0x66063bcaL, 0x11010b5cL,
0x8f659effL, 0xf862ae69L, 0x616bffd3L, 0x166ccf45L,
0xa00ae278L, 0xd70dd2eeL, 0x4e048354L, 0x3903b3c2L,
0xa7672661L, 0xd06016f7L, 0x4969474dL, 0x3e6e77dbL,
0xaed16a4aL, 0xd9d65adcL, 0x40df0b66L, 0x37d83bf0L,
0xa9bcae53L, 0xdebb9ec5L, 0x47b2cf7fL, 0x30b5ffe9L,
0xbdbdf21cL, 0xcabac28aL, 0x53b39330L, 0x24b4a3a6L,
0xbad03605L, 0xcdd70693L, 0x54de5729L, 0x23d967bfL,
0xb3667a2eL, 0xc4614ab8L, 0x5d681b02L, 0x2a6f2b94L,
0xb40bbe37L, 0xc30c8ea1L, 0x5a05df1bL, 0x2d02ef8dL
};
static unsigned int crc32(const unsigned char *buf, unsigned int len)
{
unsigned int i, crc = 0xFFFFFFFF;
for (i = 0; i < len; i++) {
crc = crc32table[(crc ^ buf[i]) & 0xff] ^ (crc >> 8); /* 8: right move 8 bit */
}
return crc ^ 0xFFFFFFFF;
}
/* Log level look up table */
static const char *hisignallingLevelNames[] = {
"TRACE",
"DEBUG",
"INFO",
"WARN",
"ERROR",
"FATAL"
};
/* get hisignaling log level */
const char *HisignallingLevelNum (HisignallingLogType hisignallingLevel)
{
if (hisignallingLevel >= HISIGNALLING_LEVEL_MAX) {
return "NULL";
} else {
return hisignallingLevelNames[hisignallingLevel];
}
}
#define RIGHT_MOVE_8_BIT (8)
#define RIGHT_MOVE_16_BIT (16)
#define RIGHT_MOVE_24_BIT (24)
/* hisignal Hi3861 message package */
static hi_u32 HisignallingDataPackage(HisignallingProtocalType *buf, hi_u32 len, hi_u8 *hisignallingDataBuf)
{
hi_u32 crcCheckSend = 0;
hi_u32 packageLen = 0;
memcpy_s(hisignallingDataBuf, HISGNALLING_MSG_FRAME_HEADER_LEN,
buf->frameHeader, HISGNALLING_MSG_FRAME_HEADER_LEN);
memcpy_s(&hisignallingDataBuf[HISGNALLING_MSG_FRAME_HEADER_LEN],
len, buf->hisignallingMsgBuf, len);
memcpy_s(&hisignallingDataBuf[HISGNALLING_MSG_FRAME_HEADER_LEN + len],
HISIGNALLING_MSG_HEADER_LEN, &(buf->endOfFrame), HISIGNALLING_MSG_HEADER_LEN);
crcCheckSend = crc32(hisignallingDataBuf, (len + HISIGNALLING_MSG_HEADER_TAIL_LEN));
hisignallingDataBuf[len + HISIGNALLING_MSG_HEADER_TAIL_LEN] =
(hi_u8) ((crcCheckSend & 0xff000000)>>RIGHT_MOVE_24_BIT);
hisignallingDataBuf[len + HISIGNALLING_MSG_HEADER_TAIL_LEN + 1] = /* 1: addr offset */
(hi_u8) ((crcCheckSend & 0x00ff0000)>>RIGHT_MOVE_16_BIT);
hisignallingDataBuf[len + HISIGNALLING_MSG_HEADER_TAIL_LEN + 2] = /* 2: addr offset */
(hi_u8) ((crcCheckSend & 0x0000ff00)>>RIGHT_MOVE_8_BIT);
hisignallingDataBuf[len + HISIGNALLING_MSG_HEADER_TAIL_LEN + 3] = /* 3: addr offset */
(hi_u8)crcCheckSend;
packageLen = len + HISIGNALLING_MSG_HEADER_TAIL_LEN + HISGNALLING_MSG_CRC32_LEN;
return packageLen;
}
/* hisignal Hi3861 message recevice */
HisignallingErrorType HisignallingMsgReceive(hi_u8 *buf, hi_u32 len)
{
hi_u32 crcCheckReceived = 0;
unsigned char testBuff[7] = {0xaa, 0x55, 0x0, 0x2, 0x0, 0x8, 0xff};
if (buf == HI_NULL && len > 0) {
HISIGNALLING_LOG_FATAL("received buf is null");
return HISGNALLING_RET_VAL_MAX;
}
printf("length:%u\n", len);
/* 校验crc */
if (len > HISGNALLING_MSG_CRC32_LEN) {
crcCheckReceived = crc32(buf, len - HISGNALLING_MSG_CRC32_LEN);
if (((hi_u8)((crcCheckReceived & 0xff000000)>>RIGHT_MOVE_24_BIT) != buf[len - 4]) && /* 4: addr offset */
((hi_u8)((crcCheckReceived & 0x00ff0000)>>RIGHT_MOVE_16_BIT) != buf[len - 3]) && /* 3: addr offset */
((hi_u8)((crcCheckReceived & 0x0000ff00)>>RIGHT_MOVE_8_BIT) != buf[len - 2]) && /* 2: addr offset */
((hi_u8)crcCheckReceived != buf[len - 1])) {
HISIGNALLING_LOG_ERROR("<Hi3861>: crc32 Verification failed!");
HISIGNALLING_LOG_ERROR("<Hi3861>:crc_4=0x%x, crc_3=0x%x, crc_2=0x%x, crc_1=0x%x",
buf[len - 4], buf[len - 3], buf[len - 2], buf[len - 1]); /* 4,3,2,1 addr offset */
return HISIGNALLING_RET_VAL_ERROR;
}
}
IoTGpioSetOutputVal(LED_TEST_GPIO, 0);
usleep(LED_INTERVAL_TIME_US);
IoTGpioSetOutputVal(LED_TEST_GPIO, 1);
usleep(LED_INTERVAL_TIME_US);
/* 输出回显收到的数据 */
/*if ((buf[0] == HISIGNALLING_MSG_FRAME_HEADER_1) && (buf[1] == HISIGNALLING_MSG_FRAME_HEADER_2)) {
for (int i = 0; i < len; i++) {
HISIGNALLING_LOG_INFO("0x%x", buf[i]);
}
}*/
return HISIGNALLING_RET_VAL_CORRECT;
}
/* hisignal Hi3861 message send */
hi_u32 HisignallingMsgSend(char *buf, hi_u32 dataLen)
{
HisignallingProtocalType hisignallingMsg = {0};
hi_u8 hisignallingSendBuf[HISIGNALLING_MSG_BUFF_LEN] = {0};
hi_u32 hisignallingPackageLen = 0;
hi_u32 writeDataLen = 0;
hisignallingMsg.frameHeader[0]= HISIGNALLING_MSG_FRAME_HEADER_1;
hisignallingMsg.frameHeader[1]= HISIGNALLING_MSG_FRAME_HEADER_2;
(void)memcpy_s(hisignallingMsg.hisignallingMsgBuf, dataLen, buf, dataLen);
hisignallingMsg.endOfFrame = HISIGNALLING_MSG_FRAME_TAIL;
hisignallingPackageLen = HisignallingDataPackage(&hisignallingMsg, dataLen, hisignallingSendBuf);
if (!hisignallingPackageLen) {
HISIGNALLING_LOG_ERROR("hisignaling_data_package failed\r\n");
return HI_ERR_FAILURE;
}
if (*hisignallingSendBuf == NULL) {
HISIGNALLING_LOG_ERROR("hisignal send buf is null!\r\n");
return HI_ERR_FAILURE;
}
writeDataLen = IoTUartWrite(HI_UART_IDX_1, hisignallingSendBuf, hisignallingPackageLen);
if (!writeDataLen) {
HISIGNALLING_LOG_ERROR("hi_uart_write failed\r\n");
return HI_ERR_FAILURE;
}
return HI_ERR_SUCCESS;
}
int SetUartReceiveFlag(void)
{
return recConfig.g_uartReceiveFlag;
}
hi_void *HisignallingMsgHandle(char *param)
{
unsigned char *recBuff = NULL;
int len;
while (1) {
/*g_sendUartBuff清零*/
(void)memset_s(g_sendUartBuff, sizeof(g_sendUartBuff) / sizeof(g_sendUartBuff[0]),
0x0, sizeof(g_sendUartBuff)/sizeof(g_sendUartBuff[0]));
/*GetUartConfig得到data的flag和length*/
if (GetUartConfig(UART_RECEIVE_FLAG) == HI_TRUE) {
/* 接收数据 */
HisignallingMsgReceive(GetUartReceiveMsg(), GetUartConfig(UART_RECVIVE_LEN));
/* 回显数据组包 */
if (GetUartConfig(UART_RECVIVE_LEN) > (HISGNALLING_MSG_CRC32_LEN + HISIGNALLING_MSG_HEADER_TAIL_LEN)) {
len = GetUartConfig(UART_RECVIVE_LEN);
recBuff = GetUartReceiveMsg();
for (int i = 0; i < len ; i++ ){
HISIGNALLING_LOG_INFO("0x%x", recBuff[i]);
}
printf("end\n");
(void)memcpy_s(g_sendUartBuff,
(GetUartConfig(UART_RECVIVE_LEN) - HISGNALLING_MSG_CRC32_LEN - HISIGNALLING_MSG_HEADER_TAIL_LEN),
&recBuff[HISGNALLING_MSG_FRAME_HEADER_LEN],
(GetUartConfig(UART_RECVIVE_LEN) - HISGNALLING_MSG_CRC32_LEN - HISIGNALLING_MSG_HEADER_TAIL_LEN));
/* 接收到Hi3516DV300数据后发送回显 */
HisignallingMsgSend(g_sendUartBuff,
(GetUartConfig(UART_RECVIVE_LEN) - HISGNALLING_MSG_CRC32_LEN - HISIGNALLING_MSG_HEADER_TAIL_LEN));
}
(void)SetUartRecvFlag(UART_RECV_FALSE);
ResetUartReceiveMsg();
}
TaskMsleep(HISGNALLING_FREE_TASK_TIME);
}
}
hi_u32 HisignalingMsgTask(hi_void)
{
hi_u32 ret = 0;
IoTGpioInit(LED_TEST_GPIO);
IoTGpioSetDir(LED_TEST_GPIO, IOT_GPIO_DIR_OUT);
osThreadAttr_t hisignallingAttr = {0};
hisignallingAttr.stack_size = HISIGNALLING_MSG_TASK_STACK_SIZE;
hisignallingAttr.priority = HISIGNALLING_MSG_TASK_PRIO;
hisignallingAttr.name = (hi_char*)"hisignal msg task";
if (osThreadNew((osThreadFunc_t)HisignallingMsgHandle, NULL, &hisignallingAttr) == NULL) {
HISIGNALLING_LOG_ERROR("Failed to create hisignaling msg task\r\n");
return HI_ERR_FAILURE;
}
return HI_ERR_SUCCESS;
}
//SYS_RUN(HisignalingMsgTask);

@ -0,0 +1,207 @@
/*
* Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
* 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 HISIGNALLING_PROTOCOL_H
#define HISIGNALLING_PROTOCOL_H
#include <hi_types_base.h>
#include <stdarg.h>
#include <stdint.h>
#include <stddef.h>
#include <stdio.h>
/**
* @brief : hisignalling Macro definition
*/
#define HISIGNALLING_MSG_HEADER_LEN (1)
#define HISGNALLING_MSG_FRAME_HEADER_LEN (2)
#define HISIGNALLING_MSG_HEADER_TAIL_LEN (3)
#define HISGNALLING_MSG_CRC32_LEN (4)
#define HISIGNALLING_MSG_PAYLOAD_INDEX (5)
#define HISGNALLING_FREE_TASK_TIME (20)
#define HISIGNALLING_MSG_TASK_PRIO (28)
#define HISIGNALLING_UART_MSG_LEN (32)
#define HISIGNALLING_MSG_BUFF_LEN (512)
#define HISIGNALLING_MSG_TASK_STACK_SIZE (4096)
/* hisgnalling protocol frame header and tail */
#define HISIGNALLING_MSG_FRAME_HEADER_1 ((hi_u8)0xAA)
#define HISIGNALLING_MSG_FRAME_HEADER_2 ((hi_u8)0x55)
#define HISIGNALLING_MSG_FRAME_TAIL ((hi_u8)0xFF)
/**
* @brief Adapter plate selection
* 使使#define BOARD_SELECT_IS_EXPANSION_BOARD
* 使Robot#define BOARD_SELECT_IS_ROBOT_BOARD#define BOARD_SELECT_IS_EXPANSION_BOARD
**/
#define BOARD_SELECT_IS_EXPANSION_BOARD
#ifdef BOARD_SELECT_IS_EXPANSION_BOARD
#define EXPANSION_BOARD
#else
#define ROBOT_BOARD
#endif
/**
* @brief:this defines for the log module, and HISIGNALING_LOG_TRACE/HISIGNALING_LOG_DEBUG...
* will not participate the compile in the release version
* */
typedef enum {
HISIGNALLING_LEVEL_TRACE = 0,
HISIGNALLING_LEVEL_DEBUG,
HISIGNALLING_LEVEL_INFO,
HISIGNALLING_LEVEL_WARN,
HISIGNALLING_LEVEL_ERROR,
HISIGNALLING_LEVEL_FATAL,
HISIGNALLING_LEVEL_MAX
} HisignallingLogType;
/**
* @brief: use this function to get the hisignalling log level name
*
* @parameter[in]:level, the level to get
*
* @return: the mapped level name
* */
const char *HisignallingLevelNum (HisignallingLogType hisignallingLevel);
/**
* @brief: this is a weak function ,and you could rewrite one
*
* @param fmt: same use as the fmt for printf
*
* @param unfixed: same use for printf
*
* @return: don't care about it
*
* @attention: and the components should not call this function directly, you'd better
*
* call HISIGNALING_LOG groups
*
* */
#define HISIGNALLING_PRINT(fmt, ...) \
do \
{ \
printf(fmt, ##__VA_ARGS__); \
} while (0)
#define HISIGNALLING_LOG(level, fmt, ...) \
do \
{ \
HISIGNALLING_PRINT("<%s>, <%s>, <%d> "fmt" \r\n", \
HisignallingLevelNum((level)), __FUNCTION__, __LINE__, ##__VA_ARGS__); \
} while (0)
#define HISIGNALLING_LOG_TRACE(fmt, ...) \
do \
{ \
HISIGNALLING_LOG (HISIGNALLING_LEVEL_TRACE, fmt, ##__VA_ARGS__); \
} while (0)
#define HISIGNALLING_LOG_DEBUG(fmt, ...) \
do \
{ \
HISIGNALLING_LOG (HISIGNALLING_LEVEL_DEBUG, fmt, ##__VA_ARGS__); \
} while (0)
#define HISIGNALLING_LOG_INFO(fmt, ...) \
do \
{ \
HISIGNALLING_LOG (HISIGNALLING_LEVEL_INFO, fmt, ##__VA_ARGS__); \
} while (0)
#define HISIGNALLING_LOG_WARN(fmt, ...) \
do \
{ \
HISIGNALLING_LOG (HISIGNALLING_LEVEL_WARN, fmt, ##__VA_ARGS__); \
} while (0)
#define HISIGNALLING_LOG_ERROR(fmt, ...) \
do \
{ \
HISIGNALLING_LOG (HISIGNALLING_LEVEL_ERROR, fmt, ##__VA_ARGS__); \
} while (0)
#define HISIGNALLING_LOG_FATAL(fmt, ...) \
do \
{ \
HISIGNALLING_LOG (HISIGNALLING_LEVEL_FATAL, fmt, ##__VA_ARGS__); \
} while (0)
/**
* @brief: use this hisignalling Transmission protocol frame format
*
* @param frameHeader: Transmission protocol frame header
*
* @param hisignallingMsgBuf: Transmission protocol frame buffer
*
* @param hisigallingMsgLen: Transmission protocol frame buffer len
*
* @param endOfFrame: Transmission protocol frame tail
*
* @param hisignallingCrc32Check: Transmission protocol crc32 check
*
* */
typedef struct {
hi_u8 frameHeader[HISGNALLING_MSG_FRAME_HEADER_LEN];
hi_u8 hisignallingMsgBuf[HISIGNALLING_MSG_BUFF_LEN];
hi_u32 hisigallingMsgLen;
hi_u8 endOfFrame;
hi_u32 hisignallingCrc32Check;
}HisignallingProtocalType;
/**
* @brief: use this hisignalling return type
*
* @param HISIGNALLING_RET_VAL_CORRECT: return type is correct
*
* @param HISIGNALLING_RET_VAL_ERROR: return type is error
*
* @param HISIGNALLING_RET_VAL_ERROR: return type is unknown type
* */
typedef enum {
HISIGNALLING_RET_VAL_CORRECT = 0,
HISIGNALLING_RET_VAL_ERROR,
HISGNALLING_RET_VAL_MAX
}HisignallingErrorType;
/**
* @brief: use this hisignalling sample:Access peripheral enumeration type
*
* @param MOTOR_GO_FORWARD: peripheral motor go forward
*
* @param MOTOR_GO_BACK: peripheral motor go back
*
* @param STEERING_ENGINE_MOVEMENT/STEERING_ENGINE_AND_MOTOR_MOVEMENT/STEERING_ENGINE_AND_MOTOR_STOP
* the same use for peripheral
* */
typedef enum {
MOTOR_GO_FORWARD = 0,
MOTOR_GO_BACK,
STEERING_ENGINE_MOVEMENT,
STEERING_ENGINE_AND_MOTOR_MOVEMENT,
STEERING_ENGINE_AND_MOTOR_STOP,
TRASH_CAN_LID_OPEN,
TRASH_CAN_LID_COLSE
}HisignallingDataType;
/**
* @brief:hisignalling protocal Function declaration
**/
hi_u32 hisignallingMsgTask(hi_void);
/**
* @brief:hisignalling uart message receive API
* @param buf: uart receive buffer
* @param len: uart receive buffer len
*/
HisignallingErrorType hisignallingMsgReceive(hi_u8 *buf, hi_u32 len);
/**
* @brief:hisignalling uart send API
* @param buf: uart message send buffer
* @param len: uart message send buffer len
*/
hi_u32 hisignallingMsgSend(hi_void *buf, hi_u32 dataLen);
int SetUartReceiveFlag(void);
#endif /* HISIGNALING_PROTOCOL_H */

@ -0,0 +1,31 @@
/*
* Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
* 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 IOT_CONFIG_H
#define IOT_CONFIG_H
// <CONFIG THE LOG
/* if you need the iot log for the development , please enable it, else please comment it */
#define CONFIG_LINKLOG_ENABLE 1
// < CONFIG THE WIFI
/* Please modify the ssid and pwd for the own */
#define CONFIG_AP_SSID "Metro" // WIFI SSID
#define CONFIG_AP_PWD "12364987" // WIFI PWD
/* Tencent iot Cloud user ID , password */
#define CONFIG_USER_ID "YT32IOSCALHi38611_mqtt;12010126;41883;1663689600"
#define CONFIG_USER_PWD "b4168d5d4b65898e6984346c81ad13e1b3f112ab7ce46f65cf29455f4c9e18e8;hmacsha256"
#define CN_CLIENTID "YT32IOSCALHi38611_mqtt" // Tencent cloud ClientID format: Product ID + device name
#endif

@ -0,0 +1,398 @@
/*
* Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
* 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.
*/
/**
* @file iot_gpio_ex.h
*
* @brief Declares the extended GPIO interface functions.
*
* These functions are used for settings GPIO pulls and driver strength. \n
*
* @since 1.0
* @version 1.0
*/
#ifndef IOT_GPIO_EX_H
#define IOT_GPIO_EX_H
/**
* @brief Enumerates GPIO pull-up or pull-down settings.
*/
typedef enum {
/** No pull */
IOT_IO_PULL_NONE,
/** Pull-up */
IOT_IO_PULL_UP,
/** Pull-down */
IOT_IO_PULL_DOWN,
/** Maximum value */
IOT_IO_PULL_MAX,
} IotIoPull;
/**
* @ingroup iot_io
*
* GPIO pin ID. CNcomment:IOCNend
*/
typedef enum {
IOT_IO_NAME_GPIO_0, /* <GPIO0 */
IOT_IO_NAME_GPIO_1, /* <GPIO1 */
IOT_IO_NAME_GPIO_2, /* <GPIO2 */
IOT_IO_NAME_GPIO_3, /* <GPIO3 */
IOT_IO_NAME_GPIO_4, /* <GPIO4 */
IOT_IO_NAME_GPIO_5, /* <GPIO5 */
IOT_IO_NAME_GPIO_6, /* <GPIO6 */
IOT_IO_NAME_GPIO_7, /* <GPIO7 */
IOT_IO_NAME_GPIO_8, /* <GPIO8 */
IOT_IO_NAME_GPIO_9, /* <GPIO9 */
IOT_IO_NAME_GPIO_10, /* <GPIO10 */
IOT_IO_NAME_GPIO_11, /* <GPIO11 */
IOT_IO_NAME_GPIO_12, /* <GPIO12 */
IOT_IO_NAME_GPIO_13, /* <GPIO13 */
IOT_IO_NAME_GPIO_14, /* <GPIO14 */
IOT_IO_NAME_SFC_CSN, /* <SFC_CSN */
IOT_IO_NAME_SFC_IO1, /* <SFC_IO1 */
IOT_IO_NAME_SFC_IO2, /* <SFC_IO2 */
IOT_IO_NAME_SFC_IO0, /* <SFC_IO0 */
IOT_IO_NAME_SFC_CLK, /* <SFC_CLK */
IOT_IO_NAME_SFC_IO3, /* <SFC_IO3 */
IOT_IO_NAME_MAX,
} IotIoName;
/**
* @ingroup iot_io
*
* GPIO_0 pin function.CNcomment:GPIO_0CNend
*/
typedef enum {
IOT_IO_FUNC_GPIO_0_GPIO,
IOT_IO_FUNC_GPIO_0_UART1_TXD = 2,
IOT_IO_FUNC_GPIO_0_SPI1_CK,
IOT_IO_FUNC_GPIO_0_JTAG_TDO,
IOT_IO_FUNC_GPIO_0_PWM3_OUT,
IOT_IO_FUNC_GPIO_0_I2C1_SDA,
} IotIoFuncGpio0;
/**
* @ingroup iot_io
*
* GPIO_1 pin function.CNcomment:GPIO_1CNend
*/
typedef enum {
IOT_IO_FUNC_GPIO_1_GPIO,
IOT_IO_FUNC_GPIO_1_UART1_RXD = 2,
IOT_IO_FUNC_GPIO_1_SPI1_RXD,
IOT_IO_FUNC_GPIO_1_JTAG_TCK,
IOT_IO_FUNC_GPIO_1_PWM4_OUT,
IOT_IO_FUNC_GPIO_1_I2C1_SCL,
IOT_IO_FUNC_GPIO_1_BT_FREQ,
} IotIoFuncGpio1;
/**
* @ingroup iot_io
*
* GPIO_2 pin function.CNcomment:GPIO_2CNend
*/
typedef enum {
IOT_IO_FUNC_GPIO_2_GPIO,
IOT_IO_FUNC_GPIO_2_UART1_RTS_N = 2,
IOT_IO_FUNC_GPIO_2_SPI1_TXD,
IOT_IO_FUNC_GPIO_2_JTAG_TRSTN,
IOT_IO_FUNC_GPIO_2_PWM2_OUT,
IOT_IO_FUNC_GPIO_2_SSI_CLK = 7,
} IotIoFuncGpio2;
/**
* @ingroup iot_io
*
* GPIO_3 pin function.CNcomment:GPIO_3CNend
*/
typedef enum {
IOT_IO_FUNC_GPIO_3_GPIO,
IOT_IO_FUNC_GPIO_3_UART0_TXD,
IOT_IO_FUNC_GPIO_3_UART1_CTS_N,
IOT_IO_FUNC_GPIO_3_SPI1_CSN,
IOT_IO_FUNC_GPIO_3_JTAG_TDI,
IOT_IO_FUNC_GPIO_3_PWM5_OUT,
IOT_IO_FUNC_GPIO_3_I2C1_SDA,
IOT_IO_FUNC_GPIO_3_SSI_DATA,
} IotIoFuncGpio3;
/**
* @ingroup iot_io
*
* GPIO_4 pin function.CNcomment:GPIO_4CNend
*/
typedef enum {
IOT_IO_FUNC_GPIO_4_GPIO,
IOT_IO_FUNC_GPIO_4_UART0_RXD = 2,
IOT_IO_FUNC_GPIO_4_JTAG_TMS = 4,
IOT_IO_FUNC_GPIO_4_PWM1_OUT,
IOT_IO_FUNC_GPIO_4_I2C1_SCL,
} IotIoFuncGpio4;
/**
* @ingroup iot_io
*
* GPIO_5 pin function.CNcomment:GPIO_5CNend
*/
typedef enum {
IOT_IO_FUNC_GPIO_5_GPIO,
IOT_IO_FUNC_GPIO_5_UART1_RXD = 2,
IOT_IO_FUNC_GPIO_5_SPI0_CSN,
IOT_IO_FUNC_GPIO_5_PWM2_OUT = 5,
IOT_IO_FUNC_GPIO_5_I2S0_MCLK,
IOT_IO_FUNC_GPIO_5_BT_STATUS,
} IotIoFuncGpio5;
/**
* @ingroup iot_io
*
* GPIO_6 pin function.CNcomment:GPIO_6CNend
*/
typedef enum {
IOT_IO_FUNC_GPIO_6_GPIO,
IOT_IO_FUNC_GPIO_6_UART1_TXD = 2,
IOT_IO_FUNC_GPIO_6_SPI0_CK,
IOT_IO_FUNC_GPIO_6_PWM3_OUT = 5,
IOT_IO_FUNC_GPIO_6_I2S0_TX,
IOT_IO_FUNC_GPIO_6_COEX_SWITCH,
} IotIoFuncGpio6;
/**
* @ingroup iot_io
*
* GPIO_7 pin function.CNcomment:GPIO_7CNend
*/
typedef enum {
IOT_IO_FUNC_GPIO_7_GPIO,
IOT_IO_FUNC_GPIO_7_UART1_CTS_N = 2,
IOT_IO_FUNC_GPIO_7_SPI0_RXD,
IOT_IO_FUNC_GPIO_7_PWM0_OUT = 5,
IOT_IO_FUNC_GPIO_7_I2S0_BCLK,
IOT_IO_FUNC_GPIO_7_BT_ACTIVE,
} IotIoFuncGpio7;
/**
* @ingroup iot_io
*
* GPIO_8 pin function.CNcomment:GPIO_8CNend
*/
typedef enum {
IOT_IO_FUNC_GPIO_8_GPIO,
IOT_IO_FUNC_GPIO_8_UART1_RTS_N = 2,
IOT_IO_FUNC_GPIO_8_SPI0_TXD,
IOT_IO_FUNC_GPIO_8_PWM1_OUT = 5,
IOT_IO_FUNC_GPIO_8_I2S0_WS,
IOT_IO_FUNC_GPIO_8_WLAN_ACTIVE,
} IotIoFuncGpio8;
/**
* @ingroup iot_io
*
* GPIO_9 pin function.CNcomment:GPIO_9CNend
*/
typedef enum {
IOT_IO_FUNC_GPIO_9_GPIO,
IOT_IO_FUNC_GPIO_9_I2C0_SCL,
IOT_IO_FUNC_GPIO_9_UART2_RTS_N,
IOT_IO_FUNC_GPIO_9_SDIO_D2,
IOT_IO_FUNC_GPIO_9_SPI0_TXD,
IOT_IO_FUNC_GPIO_9_PWM0_OUT,
IOT_IO_FUNC_GPIO_9_I2S0_MCLK = 7,
} IotIoFuncGpio9;
/**
* @ingroup iot_io
*
* GPIO_10 pin function.CNcomment:GPIO_10CNend
*/
typedef enum {
IOT_IO_FUNC_GPIO_10_GPIO,
IOT_IO_FUNC_GPIO_10_I2C0_SDA,
IOT_IO_FUNC_GPIO_10_UART2_CTS_N,
IOT_IO_FUNC_GPIO_10_SDIO_D3,
IOT_IO_FUNC_GPIO_10_SPI0_CK,
IOT_IO_FUNC_GPIO_10_PWM1_OUT,
IOT_IO_FUNC_GPIO_10_I2S0_TX = 7,
} IotIoFuncGpio10;
/**
* @ingroup iot_io
*
* GPIO_11 pin function.CNcomment:GPIO_11CNend
*/
typedef enum {
IOT_IO_FUNC_GPIO_11_GPIO,
IOT_IO_FUNC_GPIO_11_UART2_TXD = 2,
IOT_IO_FUNC_GPIO_11_SDIO_CMD,
IOT_IO_FUNC_GPIO_11_SPI0_RXD,
IOT_IO_FUNC_GPIO_11_PWM2_OUT,
IOT_IO_FUNC_GPIO_11_RF_TX_EN_EXT,
IOT_IO_FUNC_GPIO_11_I2S0_RX,
} IotIoFuncGpio11;
/**
* @ingroup iot_io
*
* GPIO_12 pin function.CNcomment:GPIO_12CNend
*/
typedef enum {
IOT_IO_FUNC_GPIO_12_GPIO,
IOT_IO_FUNC_GPIO_12_UART2_RXD = 2,
IOT_IO_FUNC_GPIO_12_SDIO_CLK,
IOT_IO_FUNC_GPIO_12_SPI0_CSN,
IOT_IO_FUNC_GPIO_12_PWM3_OUT,
IOT_IO_FUNC_GPIO_12_RF_RX_EN_EXT,
IOT_IO_FUNC_GPIO_12_I2S0_BCLK,
} IotIoFuncGpio12;
/**
* @ingroup iot_io
*
* GPIO_13 pin function.CNcomment:GPIO_13CNend
*/
typedef enum {
IOT_IO_FUNC_GPIO_13_SSI_DATA,
IOT_IO_FUNC_GPIO_13_UART0_TXD,
IOT_IO_FUNC_GPIO_13_UART2_RTS_N,
IOT_IO_FUNC_GPIO_13_SDIO_D0,
IOT_IO_FUNC_GPIO_13_GPIO,
IOT_IO_FUNC_GPIO_13_PWM4_OUT,
IOT_IO_FUNC_GPIO_13_I2C0_SDA,
IOT_IO_FUNC_GPIO_13_I2S0_WS,
} IotIoFuncGpio13;
/**
* @ingroup iot_io
*
* GPIO_14 pin function.CNcomment:GPIO_14CNend
*/
typedef enum {
IOT_IO_FUNC_GPIO_14_SSI_CLK,
IOT_IO_FUNC_GPIO_14_UART0_RXD,
IOT_IO_FUNC_GPIO_14_UART2_CTS_N,
IOT_IO_FUNC_GPIO_14_SDIO_D1,
IOT_IO_FUNC_GPIO_14_GPIO,
IOT_IO_FUNC_GPIO_14_PWM5_OUT,
IOT_IO_FUNC_GPIO_14_I2C0_SCL,
} IotIoFuncGpio14;
/**
* @ingroup iot_io
*
* SFC_CSN pin function.CNcomment:SFC_CSNCNend
*/
typedef enum {
IOT_IO_FUNC_SFC_CSN_SFC_CSN,
IOT_IO_FUNC_SFC_CSN_SDIO_D2,
IOT_IO_FUNC_SFC_CSN_GPIO9,
IOT_IO_FUNC_SFC_CSN_SPI0_TXD = 4,
} IotIoFuncSfcCsn;
/**
* @ingroup iot_io
*
* SFC_DO pin function.CNcomment:SFC_DOCNend
*/
typedef enum {
IOT_IO_FUNC_SFC_IO_1_SFC_DO,
IOT_IO_FUNC_SFC_IO_1_SDIO_D3,
IOT_IO_FUNC_SFC_IO_1_GPIO10,
IOT_IO_FUNC_SFC_IO_1_SPI0_CK = 4,
} IotIoFuncSfcIo1;
/**
* @ingroup iot_io
*
* SFC_WPN pin function.CNcomment:SFC_WPNCNend
*/
typedef enum {
IOT_IO_FUNC_SFC_IO_2_SFC_WPN,
IOT_IO_FUNC_SFC_IO_2_SDIO_CMD,
IOT_IO_FUNC_SFC_IO_2_GPIO11,
IOT_IO_FUNC_SFC_IO_2_RF_TX_EN_EXT,
IOT_IO_FUNC_SFC_IO_2_SPI0_RXD,
} IotIoFuncSfcIo2;
/**
* @ingroup iot_io
*
* SFC_DI pin function.CNcomment:SFC_DICNend
*/
typedef enum {
IOT_IO_FUNC_SFC_IO_0_SFC_DI,
IOT_IO_FUNC_SFC_IO_0_SDIO_CLK,
IOT_IO_FUNC_SFC_IO_0_GPIO12,
IOT_IO_FUNC_SFC_IO_0_RF_RX_EN_EXT,
IOT_IO_FUNC_SFC_IO_0_SPI0_CSN,
} IotIoFuncSfcIo0;
/**
* @ingroup iot_io
*
* SFC_CLK pin function.CNcomment:SFC_CLKCNend
*/
typedef enum {
IOT_IO_FUNC_SFC_CLK_SFC_CLK,
IOT_IO_FUNC_SFC_CLK_SDIO_D0,
IOT_IO_FUNC_SFC_CLK_GPIO13,
IOT_IO_FUNC_SFC_CLK_SSI_DATA = 4,
} IotIoFuncSfcClk;
/**
* @ingroup iot_io
*
* SFC_HOLDN pin function.CNcomment:SFC_HOLDNCNend
*/
typedef enum {
IOT_IO_FUNC_SFC_IO_3_SFC_HOLDN,
IOT_IO_FUNC_SFC_IO_3_SDIO_D1,
IOT_IO_FUNC_SFC_IO_3_GPIO14,
IOT_IO_FUNC_SFC_IO_3_SSI_CLK = 4,
} IotIoFuncSfcIo3;
/**
* @ingroup iot_io
*
* I/O drive capability.CNcomment:IOCNend
* Note: The HI_IO_NAME_GPIO_0~HI_IO_NAME_GPIO_11 and HI_IO_NAME_GPIO_13~HI_IO_NAME_GPIO_14 driver capabilities are
* optional.The value range is HI_IO_DRIVER_STRENGTH_0~HI_IO_DRIVER_STRENGTH_3, and the other I/O ranges are
* HI_IO_DRIVER_STRENGTH_0~HI_IO_DRIVER_STRENGTH_7.CNcomment::HI_IO_NAME_GPIO_0~HI_IO_NAME_GPIO_11
* HI_IO_NAME_GPIO_13~HI_IO_NAME_GPIO_14HI_IO_DRIVER_STRENGTH_0~HI_IO_DRIVER_STRENGTH_3
* IOHI_IO_DRIVER_STRENGTH_0~HI_IO_DRIVER_STRENGTH_7CNend
*/
typedef enum {
IOT_IO_DRIVER_STRENGTH_0 = 0, /* <Drive strength level 0 (highest).CNcomment:驱动能力0级驱动能力最高CNend */
IOT_IO_DRIVER_STRENGTH_1, /* <Drive strength level 1.CNcomment:驱动能力1级CNend */
IOT_IO_DRIVER_STRENGTH_2, /* <Drive strength level 2.CNcomment:驱动能力2级CNend */
IOT_IO_DRIVER_STRENGTH_3, /* <Drive strength level 3.CNcomment:驱动能力3级CNend */
IOT_IO_DRIVER_STRENGTH_4, /* <Drive strength level 4.CNcomment:驱动能力4级CNend */
IOT_IO_DRIVER_STRENGTH_5, /* <Drive strength level 5.CNcomment:驱动能力5级CNend */
IOT_IO_DRIVER_STRENGTH_6, /* <Drive strength level 6.CNcomment:驱动能力6级CNend */
IOT_IO_DRIVER_STRENGTH_7, /* <Drive strength level 7 (lowest).CNcomment:驱动能力7级驱动能力最低CNend */
IOT_IO_DRIVER_STRENGTH_MAX,
} IotIoDriverStrength;
unsigned int IoSetPull(unsigned int id, IotIoPull val);
unsigned int IoSetFunc(unsigned int id, unsigned char val);
//unsigned int TaskMsleep(unsigned int ms);
#endif
/** @} */

@ -0,0 +1,95 @@
/*
* Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
* 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.
*/
/**
* This file make use the hmac to make mqtt pwd.
* The method is use the date string to hash the device passwd
* Take care that this implement depends on the hmac of the mbedtls
*/
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include <stdio.h>
#include "md.h"
#include "md_internal.h"
#define CN_HMAC256_LEN_MAX (65)
#define CN_HMAC256_LEN 32
#define RIGHT_MOVE_BIT_4 (4)
#define NUMBER_9 (9)
#define DECIMAL_BASE (10)
#define STRING_LEN_TIMES (2)
#define LEN_TIMES (2)
#define OFFSET (1)
// make a byte to 2 ascii hex
static int byte2hexstr(unsigned char *bufin, int len, char *bufout)
{
int i = 0;
unsigned char tmp_l = 0x0;
unsigned char tmp_h = 0;
if ((bufin == NULL)||(len <= 0)||(bufout == NULL)) {
return -1;
}
for (i = 0; i < len; i++) {
tmp_h = (bufin[i] >> RIGHT_MOVE_BIT_4) & 0X0F;
tmp_l = bufin[i] & 0x0F;
bufout[STRING_LEN_TIMES * i] = (tmp_h > NUMBER_9) ?
(tmp_h - DECIMAL_BASE + 'a'):(tmp_h +'0');
bufout[STRING_LEN_TIMES * i + OFFSET] = (tmp_l > NUMBER_9) ?
(tmp_l - DECIMAL_BASE + 'a'):(tmp_l +'0');
}
bufout[STRING_LEN_TIMES * len] = '\0';
return 0;
}
int HmacGeneratePwd(const unsigned char *content, int contentLen, const unsigned char *key,
int keyLen, unsigned char *buf)
{
int ret = -1;
mbedtls_md_context_t mbedtls_md_ctx;
const mbedtls_md_info_t *md_info;
unsigned char hash[CN_HMAC256_LEN];
if ((key == NULL)||(content == NULL)||(buf == NULL)||
(keyLen == 0)||(contentLen == 0)||
(CN_HMAC256_LEN_MAX < (CN_HMAC256_LEN * LEN_TIMES + OFFSET))) {
return ret;
}
md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA256);
if ((md_info == NULL)||((size_t)md_info->size > CN_HMAC256_LEN)) {
return ret;
}
mbedtls_md_init(&mbedtls_md_ctx);
ret = mbedtls_md_setup(&mbedtls_md_ctx, md_info, 1);
if (ret != 0) {
mbedtls_md_free(&mbedtls_md_ctx);
return ret;
}
(void)mbedtls_md_hmac_starts(&mbedtls_md_ctx, key, keyLen);
(void)mbedtls_md_hmac_update(&mbedtls_md_ctx, content, contentLen);
(void)mbedtls_md_hmac_finish(&mbedtls_md_ctx, hash);
// <transfer the hash code to the string mode
ret = byte2hexstr(hash, CN_HMAC256_LEN, (char *)buf);
if (ret != 0) {
return ret;
}
return ret;
}

@ -0,0 +1,32 @@
/*
* Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
* 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 IOT_HMAC_H
#define IOT_HMAC_H
/**
* This function used to generate the passwd for the mqtt to connect the HW IoT platform
* @param content: This is the content for the hmac,
* and usually it is the device passwd set or get from the Iot Platform
* @param content_len: The length of the content
* @param key: This is the key for the hmac, and usually it is the time used in the client_id:
* the format isyearmonthdatehour:like 1970010100
* @param key_len: The length of the key
* @param buf: used to storage the hmac code
* @param buf_len:the buf length
* @return:0 success while others failed
*/
int HmacGeneratePwd(const unsigned char *content, int contentLen, const unsigned char *key,
int keyLen, unsigned char *buf);
#endif

@ -0,0 +1,50 @@
/*
* Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
* 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.
*/
#include <iot_log.h>
static EnIotLogLevel gIoTLogLevel = EN_IOT_LOG_LEVEL_TRACE;
static const char *gIoTLogLevelNames[] = {
"TRACE",
"DEBUG",
"INFO ",
"WARN ",
"ERROR",
"FATAL"
};
int IoTLogLevelSet(EnIotLogLevel level)
{
int ret = -1;
if (level < EN_IOT_LOG_LEVEL_MAX) {
gIoTLogLevel = level;
ret = 0;
}
return ret;
}
EnIotLogLevel IoTLogLevelGet(void)
{
return gIoTLogLevel;
}
const char *IoTLogLevelGetName(EnIotLogLevel logLevel)
{
if (logLevel >= EN_IOT_LOG_LEVEL_MAX) {
return "NULL ";
} else {
return gIoTLogLevelNames[logLevel];
}
}

@ -0,0 +1,122 @@
/*
* Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
* 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 IOT_LOG_H_
#define IOT_LOG_H_
/**
* @brief:this defines for the log module,
* and IOT_LOG_TRACE/IOT_LOG_DEBUG will not participate the compile in the release version
*
*
* */
typedef enum {
// < this is used as the trace function,like the function enter and function out
EN_IOT_LOG_LEVEL_TRACE = 0,
// < this is used as the debug, you could add any debug as you wish
EN_IOT_LOG_LEVEL_DEBUG,
// < which means it is import message, and you should known
EN_IOT_LOG_LEVEL_INFO,
// < this is used as the executed result,which means the status is not what we expected
EN_IOT_LOG_LEVEL_WARN,
// < this is used as the executed result,which means the status is not what we expected
EN_IOT_LOG_LEVEL_ERROR,
// < this is used as the parameters input for the api interface, which could not accepted
EN_IOT_LOG_LEVEL_FATAL,
EN_IOT_LOG_LEVEL_MAX,
}EnIotLogLevel;
/**
* @brief:use this function to get the current output log
*
* @return: the current output mask log, defined by en_iot_log_level_t
* */
EnIotLogLevel IoTLogLevelGet(void);
/**
* @brief: use this function to get the debug level name
*
* @parameter[in]:level, the level to get
*
* @return: the mapped level name
* */
const char *IoTLogLevelGetName(EnIotLogLevel logLevel);
/**
* @brief:use this function to set the current output log
*
* @parameter[in] level:defined by en_iot_log_level_t
*
* @return: 0 success while -1 failed
* */
int IoTLogLevelSet(EnIotLogLevel level);
/*
* @brief: this is a weak function ,and you could rewrite one
*
* @param fmt: same use as the fmt for printf
*
* @param unfixed: same use for printf
*
* @return: don't care about it
*
* @attention: and the components should not call this function directly, you'd better
*
* call IOT_LOG groups
*
* */
#ifndef IOT_PRINT
#define IOT_PRINT(fmt, ...) \
do \
{ \
printf(fmt, ##__VA_ARGS__); \
}while (0)
#endif
#ifdef CONFIG_LINKLOG_ENABLE
#define IOT_LOG(level, fmt, ...) \
do \
{ \
IOT_PRINT("[%s][%s] " fmt "\r\n", \
IoTLogLevelGetName((level)), __FUNCTION__, ##__VA_ARGS__); \
} while (0)
#define IOT_LOG_TRACE(fmt, ...) \
do \
{ \
if ((EN_IOT_LOG_LEVEL_TRACE) >= IoTLogLevelGet()) \
{ \
IOT_LOG(EN_IOT_LOG_LEVEL_TRACE, fmt, ##__VA_ARGS__); \
} \
} while (0)
#define IOT_LOG_DEBUG(fmt, ...) \
do \
{ \
if ((EN_IOT_LOG_LEVEL_DEBUG) >= IoTLogLevelGet()) \
{ \
IOT_LOG(EN_IOT_LOG_LEVEL_DEBUG, fmt, ##__VA_ARGS__); \
} \
} while (0)
#else
#define IOT_LOG(level, fmt, ...)
#define IOT_LOG_TRACE(fmt, ...)
#define IOT_LOG_DEBUG(fmt, ...)
#endif
#define IOT_LOG_TRACE(fmt, ...) IOT_LOG(EN_IOT_LOG_LEVEL_TRACE, fmt, ##__VA_ARGS__)
#define IOT_LOG_INFO(fmt, ...) IOT_LOG(EN_IOT_LOG_LEVEL_INFO, fmt, ##__VA_ARGS__)
#define IOT_LOG_WARN(fmt, ...) IOT_LOG(EN_IOT_LOG_LEVEL_WARN, fmt, ##__VA_ARGS__)
#define IOT_LOG_ERROR(fmt, ...) IOT_LOG(EN_IOT_LOG_LEVEL_ERROR, fmt, ##__VA_ARGS__)
#define IOT_LOG_FATAL(fmt, ...) IOT_LOG(EN_IOT_LOG_LEVEL_FATAL, fmt, ##__VA_ARGS__)
#endif /* IOT_LOG_H_ */

@ -0,0 +1,333 @@
/*
* Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
* 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.
*/
/**
* STEPS:
* 1, CONNECT TO THE IOT SERVER
* 2, SUBSCRIBE THE DEFAULT TOPIC
* 3, WAIT FOR ANY MESSAGE COMES OR ANY MESSAGE TO SEND
*/
#include <securec.h>
#include <hi_task.h>
#include <hi_msg.h>
#include <hi_mem.h>
#include <string.h>
#include <stdbool.h>
#include "iot_config.h"
#include "iot_log.h"
#include "iot_hmac.h"
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_watchdog.h"
#include "MQTTClient.h"
#include "iot_errno.h"
#include "iot_main.h"
#include "iot_gpio.h"
// < this is the configuration head
#define CN_IOT_SERVER "tcp://106.55.124.154:1883" // Tencent iot cloud address
#define CONFIG_COMMAND_TIMEOUT 10000L
#define CN_KEEPALIVE_TIME 50
#define CN_CLEANSESSION 1
#define CN_HMAC_PWD_LEN 65 // < SHA256 IS 32 BYTES AND END APPEND '\0'
#define CN_EVENT_TIME "1970000100"
#define CN_CLIENTID_FMT "%s_0_0_%s" // < This is the cient ID format, deviceID_0_0_TIME
#define CN_QUEUE_WAITTIMEOUT 1000
#define CN_QUEUE_MSGNUM 16
#define CN_QUEUE_MSGSIZE (sizeof(hi_pvoid))
#define CN_TASK_PRIOR 28
#define CN_TASK_STACKSIZE 0X2000
#define CN_TASK_NAME "IoTMain"
#define Signal_LED_IO 12
typedef enum {
EN_IOT_MSG_PUBLISH = 0,
EN_IOT_MSG_RECV,
}EnIotMsg;
typedef struct {
EnIotMsg type;
int qos;
const char *topic;
const char *payload;
}IoTMsg_t;
typedef struct {
bool stop;
unsigned int conLost;
unsigned int queueID;
unsigned int iotTaskID;
fnMsgCallBack msgCallBack;
MQTTClient_deliveryToken tocken;
}IotAppCb_t;
static IotAppCb_t gIoTAppCb;
static const char *gDefaultSubscribeTopic[] = {
/* Tencent iot cloud topic */
"YT32IOSCAL/Hi38611_mqtt/data",
"YT32IOSCAL/Hi38611_mqtt/event",
"YT32IOSCAL/Hi38611_mqtt/control",
};
#define CN_TOPIC_SUBSCRIBE_NUM (sizeof(gDefaultSubscribeTopic) / sizeof(const char *))
static int MsgRcvCallBack(char *context, char *topic, int topicLen, MQTTClient_message *message)
{
IoTMsg_t *msg;
char *buf;
unsigned int bufSize;
int topiLen = topicLen;
if (topiLen == 0) {
topiLen = strlen(topic);
}
bufSize = topiLen + 1 + message->payloadlen + 1 + sizeof(IoTMsg_t);
buf = hi_malloc(0, bufSize);
if (buf != NULL) {
msg = (IoTMsg_t *)buf;
buf += sizeof(IoTMsg_t);
bufSize -= sizeof(IoTMsg_t);
msg->qos = message->qos;
msg->type = EN_IOT_MSG_RECV;
(void)memcpy_s(buf, bufSize, topic, topiLen);
buf[topiLen] = '\0';
msg->topic = buf;
buf += topiLen + 1;
bufSize -= (topiLen + 1);
(void)memcpy_s(buf, bufSize, message->payload, message->payloadlen);
buf[message->payloadlen] = '\0';
msg->payload = buf;
IOT_LOG_DEBUG("RCVMSG:QOS:%d TOPIC:%s PAYLOAD:%s\r\n", msg->qos, msg->topic, msg->payload);
if (IOT_SUCCESS != osMessageQueuePut(gIoTAppCb.queueID, &msg, 0, CN_QUEUE_WAITTIMEOUT)) {
IOT_LOG_ERROR("Wrie queue failed\r\n");
hi_free(0, msg);
}
}
MQTTClient_freeMessage(&message);
MQTTClient_free(topic);
return 1;
}
// < when the connect lost and this callback will be called
static void ConnLostCallBack(char *context, char *cause)
{
IOT_LOG_DEBUG("Connection lost:caused by:%s\r\n", cause == NULL? "Unknown" : cause);
return;
}
static int MqttProcessQueueMsg(MQTTClient client, IoTMsg_t *msg, MQTTClient_message pubMsg)
{
int ret = 0;
switch (msg->type) {
case EN_IOT_MSG_PUBLISH:
pubMsg.payload = (void *)msg->payload;
pubMsg.payloadlen = (int)strlen(msg->payload);
pubMsg.qos = msg->qos;
pubMsg.retained = 0;
ret = MQTTClient_publishMessage(client, msg->topic, &pubMsg, &gIoTAppCb.tocken);
if (ret != MQTTCLIENT_SUCCESS) {
IOT_LOG_ERROR("MSGSEND:failed\r\n");
}
IOT_LOG_DEBUG("MSGSEND:SUCCESS\r\n");
gIoTAppCb.tocken++;
break;
case EN_IOT_MSG_RECV:
if (gIoTAppCb.msgCallBack != NULL) {
gIoTAppCb.msgCallBack(msg->qos, msg->topic, msg->payload); /*接受信息并进行相应的操作函数体在IoTSetMsgCallback中定义*/
}
break;
default:
break;
}
}
// <use this function to deal all the comming message
static int ProcessQueueMsg(MQTTClient client)
{
unsigned int ret;
unsigned int msgSize;
IoTMsg_t *msg;
unsigned int timeout;
MQTTClient_message pubmsg = MQTTClient_message_initializer;
timeout = CN_QUEUE_WAITTIMEOUT;
do {
msg = NULL;
msgSize = sizeof(hi_pvoid);
ret = osMessageQueueGet(gIoTAppCb.queueID, &msg, &msgSize, timeout);/*得到数据存入msg*/
if (msg != NULL) {
IOT_LOG_DEBUG("QUEUEMSG:QOS:%d TOPIC:%s PAYLOAD:%s\r\n", msg->qos, msg->topic, msg->payload);
MqttProcessQueueMsg(client, msg, pubmsg);
hi_free(0, msg);
}
timeout = 0; // < continous to deal the message without wait here
} while (ret == IOT_SUCCESS);
return 0;
}
int MqttDestory(int ret, MQTTClient client)
{
if (ret != MQTTCLIENT_SUCCESS) {
MQTTClient_destroy(&client);
return -1;
}
return MQTTCLIENT_SUCCESS;
}
static void MainEntryProcess(void)
{
int rc = 0, subQos[CN_TOPIC_SUBSCRIBE_NUM] = {1};
MQTTClient client = NULL;
MQTTClient_connectOptions connOpts = MQTTClient_connectOptions_initializer;
char *clientID = CN_CLIENTID;
char *userID = CONFIG_USER_ID;
char *userPwd = hi_malloc(0, CN_HMAC_PWD_LEN);
if (userPwd == NULL) {
hi_free(0, clientID);
return;
}
userPwd = CONFIG_USER_PWD;
connOpts.keepAliveInterval = CN_KEEPALIVE_TIME;
connOpts.cleansession = CN_CLEANSESSION;
connOpts.username = userID;
connOpts.password = userPwd;
connOpts.MQTTVersion = MQTTVERSION_3_1_1;
IOT_LOG_DEBUG("CLIENTID:%s USERID:%s USERPWD:%s, IOTSERVER:%s\r\n",
clientID, userID, userPwd==NULL?"NULL" : userPwd, CN_IOT_SERVER);
rc = MQTTClient_create(&client, CN_IOT_SERVER, clientID, MQTTCLIENT_PERSISTENCE_NONE, NULL);
if (rc != MQTTCLIENT_SUCCESS) {
if (userPwd != NULL) {
hi_free(0, userPwd);
}
return;
}
rc = MQTTClient_setCallbacks(client, NULL, ConnLostCallBack, MsgRcvCallBack, NULL);
if (MqttDestory(rc, client) != MQTTCLIENT_SUCCESS) {
return;
}
rc = MQTTClient_connect(client, &connOpts);
if (MqttDestory(rc, client) != MQTTCLIENT_SUCCESS) {
return;
}
for (int i = 0; i < CN_TOPIC_SUBSCRIBE_NUM; i++) {
rc = MQTTClient_subscribeMany(client, CN_TOPIC_SUBSCRIBE_NUM,
(char *const *)gDefaultSubscribeTopic, (int *)&subQos[0]);
if (MqttDestory(rc, client) != MQTTCLIENT_SUCCESS) {
return;
}
}
IOT_LOG_DEBUG ("Connect success and Subscribe success\r\n");
IoTGpioSetOutputVal(Signal_LED_IO, IOT_GPIO_VALUE1);
while (MQTTClient_isConnected(client)) {
ProcessQueueMsg(client); // < do the job here
MQTTClient_yield(); // < make the keepalive done
}
MQTTClient_disconnect(client, CONFIG_COMMAND_TIMEOUT);
return;
}
/* MQTT processing entry */
static hi_void *MainEntry(char *arg)
{
(void)arg;
while (gIoTAppCb.stop == false) {
MainEntryProcess();
IOT_LOG_DEBUG("The connection lost and we will try another connect\r\n");
IoTGpioSetOutputVal(Signal_LED_IO, IOT_GPIO_VALUE0);
hi_sleep(1000); /* 1000: cpu sleep 1000ms */
}
return NULL;
}
static void engine_init(unsigned int IO){
IoTGpioInit(IO);
IoSetFunc(IO, 0);
IoTGpioSetDir(IO, IOT_GPIO_DIR_OUT);
IoTGpioSetOutputVal(IO, IOT_GPIO_VALUE0);
IOT_LOG_DEBUG("GPIO:%u initialized!", IO);
}
int IoTMain(void)
{
unsigned int ret = 0;
hi_task_attr attr = {0};
engine_init(6);
engine_init(7);
engine_init(9);
engine_init(10);
IoTGpioInit(Signal_LED_IO);
IoSetFunc(Signal_LED_IO, 0);
IoTGpioSetDir(Signal_LED_IO, IOT_GPIO_DIR_OUT);
IoTGpioSetOutputVal(Signal_LED_IO, IOT_GPIO_VALUE0);
gIoTAppCb.queueID = osMessageQueueNew(CN_QUEUE_MSGNUM, CN_QUEUE_MSGSIZE, NULL);
if (ret != IOT_SUCCESS) {
IOT_LOG_ERROR("Create the msg queue Failed\r\n");
}
attr.stack_size = CN_TASK_STACKSIZE;
attr.task_prio = CN_TASK_PRIOR;
attr.task_name = CN_TASK_NAME;
ret = hi_task_create(&gIoTAppCb.iotTaskID, &attr, MainEntry, NULL);
if (ret != IOT_SUCCESS) {
IOT_LOG_ERROR("Create the Main Entry Failed\r\n");
}
return 0;
}
int IoTSetMsgCallback(fnMsgCallBack msgCallback)
{
gIoTAppCb.msgCallBack = msgCallback;/*赋予函数*/
return 0;
}
int IotSendMsg(int qos, const char *topic, const char *payload)
{
int rc = -1;
IoTMsg_t *msg;
char *buf;
unsigned int bufSize;
bufSize = strlen(topic) + 1 +strlen(payload) + 1 + sizeof(IoTMsg_t);
buf = hi_malloc(0, bufSize);
if (buf != NULL) {
msg = (IoTMsg_t *)buf;
buf += sizeof(IoTMsg_t);
bufSize -= sizeof(IoTMsg_t);
msg->qos = qos;
msg->type = EN_IOT_MSG_PUBLISH;
(void)memcpy_s(buf, bufSize, topic, strlen(topic));
buf[strlen(topic)] = '\0';
msg->topic = buf;
buf += strlen(topic) + 1;
bufSize -= (strlen(topic) + 1);
(void)memcpy_s(buf, bufSize, payload, strlen(payload));
buf[strlen(payload)] = '\0';
msg->payload = buf;
IOT_LOG_DEBUG("SNDMSG:QOS:%d TOPIC:%s PAYLOAD:%s\r\n", msg->qos, msg->topic, msg->payload);
if (IOT_SUCCESS != osMessageQueuePut(gIoTAppCb.queueID, &msg, 0, CN_QUEUE_WAITTIMEOUT)) {
IOT_LOG_ERROR("Write queue failed\r\n");
hi_free(0, msg);
} else {
rc = 0;
}
}
return rc;
}

@ -0,0 +1,44 @@
/*
* Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
* 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 IOT_MAIN_H
#define IOT_MAIN_H
typedef void (*fnMsgCallBack)(int qos, const char *topic, const char *payload);
/**
* This is the iot main function. Please call this function first
*/
int IoTMain(void);
/**
* Use this function to set the message call back function, when some messages comes,
* the callback will be called, if you don't care about the message, set it to NULL
*/
int IoTSetMsgCallback(fnMsgCallBack msgCallback);
/**
* When you want to send some messages to the iot server(including the response message),
* please call this api
* @param qos: the mqtt qos,:0,1,2
* @param topic: the iot mqtt topic
* @param payload: the mqtt payload
*
* @return 0 success while others failed
*
* @instruction: if success means we write the message to the queue susccess,
* not means communicate with the server success
*/
int IotSendMsg(int qos, const char *topic, const char *payload);
#endif /* IOT_MAIN_H_ */

@ -0,0 +1,361 @@
/*
* Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
* 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.
*/
#include <hi_mem.h>
#include <cJSON.h>
#include <string.h>
#include "iot_main.h"
#include "iot_log.h"
#include "iot_config.h"
#include "iot_profile.h"
// < format the report data to json string mode
static cJSON *FormateProflleValue(IoTProfileKV_t *kv)
{
cJSON *ret = NULL;
switch (kv->type) {
case EN_IOT_DATATYPE_INT:
ret = cJSON_CreateNumber(kv->iValue);
break;
case EN_IOT_DATATYPE_LONG:
ret = cJSON_CreateNumber((double)(*(long *)kv->value));
break;
case EN_IOT_DATATYPE_STRING:
ret = cJSON_CreateString((const char *)kv->value);
break;
default:
break;
}
return ret;
}
static cJSON *MakeKvs(IoTProfileKV_t *kvlst)
{
cJSON *root;
cJSON *kv;
IoTProfileKV_t *kvInfo;
// < build a root node
root = cJSON_CreateObject();
if (root == NULL) {
cJSON_Delete(root);
root = NULL;
return root;
}
// < add all the property to the properties
kvInfo = kvlst;
while (kvInfo != NULL) {
kv = FormateProflleValue(kvInfo);
if (kv == NULL) {
if (root != NULL) {
cJSON_Delete(root);
root = NULL;
}
return root;
}
cJSON_AddItemToObject(root, kvInfo->key, kv);
kvInfo = kvInfo->nxt;
}
// < OK, now we return it
return root;
}
#define CN_PROFILE_SERVICE_KEY_SERVICEID "service_id"
#define CN_PROFILE_SERVICE_KEY_PROPERTIIES "properties"
#define CN_PROFILE_SERVICE_KEY_EVENTTIME "event_time"
#define CN_PROFILE_KEY_SERVICES "services"
static cJSON *MakeService(IoTProfileService_t *serviceInfo)
{
cJSON *root;
cJSON *serviceID;
cJSON *properties;
cJSON *eventTime;
// < build a root node
root = cJSON_CreateObject();
if (root == NULL) {
cJSON_Delete(root);
root = NULL;
return root;
}
// < add the serviceID node to the root node
serviceID = cJSON_CreateString(serviceInfo->serviceID);
if (serviceID == NULL) {
if (root != NULL) {
cJSON_Delete(root);
root = NULL;
}
return root;
}
cJSON_AddItemToObjectCS(root, CN_PROFILE_SERVICE_KEY_SERVICEID, serviceID);
// < add the properties node to the root
properties = MakeKvs(serviceInfo->serviceProperty);
if (properties == NULL) {
if (root != NULL) {
cJSON_Delete(root);
root = NULL;
}
return root;
}
cJSON_AddItemToObjectCS(root, CN_PROFILE_SERVICE_KEY_PROPERTIIES, properties);
// < add the event time (optional) to the root
if (serviceInfo->eventTime != NULL) {
eventTime = cJSON_CreateString(serviceInfo->eventTime);
if (eventTime == NULL) {
if (root != NULL) {
cJSON_Delete(root);
root = NULL;
}
return root;
}
cJSON_AddItemToObjectCS(root, CN_PROFILE_SERVICE_KEY_EVENTTIME, eventTime);
}
// < OK, now we return it
cJSON_Delete(properties);
return root;
}
static cJSON *MakeServices(IoTProfileService_t *serviceInfo)
{
cJSON *services = NULL;
cJSON *service;
IoTProfileService_t *serviceTmp;
// < create the services array node
services = cJSON_CreateArray();
if (services == NULL) {
cJSON_Delete(services);
services = NULL;
return services;
}
serviceTmp = serviceInfo;
while (serviceTmp != NULL) {
service = MakeService(serviceTmp);
if (service == NULL) {
if (services != NULL) {
cJSON_Delete(services);
services = NULL;
}
return services;
}
cJSON_AddItemToArray(services, service);
serviceTmp = serviceTmp->nxt;
}
// < now we return the services
return services;
}
// < use this function to make a topic to publish
// < if request_id is needed depends on the fmt
static char *MakeTopic(const char *fmt, const char *deviceID, const char *requestID)
{
int len;
char *ret = NULL;
len = strlen(fmt) + strlen(deviceID);
if (requestID != NULL) {
len += strlen(requestID);
}
ret = hi_malloc(0, len);
if (ret != NULL) {
if (requestID != NULL) {
(void)snprintf_s(ret, len, len, fmt, deviceID, requestID);
} else {
(void)snprintf_s(ret, len, len, fmt, deviceID);
}
}
return ret;
}
#define CN_PROFILE_CMDRESP_KEY_RETCODE "result_code"
#define CN_PROFILE_CMDRESP_KEY_RESPNAME "response_name"
#define CN_PROFILE_CMDRESP_KEY_PARAS "paras"
static char *MakeProfileCmdResp(IoTCmdResp_t *payload)
{
char *ret = NULL;
cJSON *root;
cJSON *retCode;
cJSON *respName;
cJSON *paras;
// < create the root node
root = cJSON_CreateObject();
if (root == NULL) {
cJSON_Delete(root);
return ret;
}
// < create retcode and retdesc and add it to the root
retCode = cJSON_CreateNumber(payload->retCode);
if (retCode == NULL) {
if (root != NULL) {
cJSON_Delete(root);
}
return ret;
}
cJSON_AddItemToObjectCS(root, CN_PROFILE_CMDRESP_KEY_RETCODE, retCode);
if (payload->respName != NULL) {
respName = cJSON_CreateString(payload->respName);
if (respName == NULL) {
if (root != NULL) {
cJSON_Delete(root);
}
return ret;
}
cJSON_AddItemToObjectCS(root, CN_PROFILE_CMDRESP_KEY_RESPNAME, respName);
}
if (payload->paras != NULL) {
paras = MakeKvs(payload->paras);
if (paras == NULL) {
if (root != NULL) {
cJSON_Delete(root);
}
return ret;
}
cJSON_AddItemToObjectCS(root, CN_PROFILE_CMDRESP_KEY_PARAS, paras);
}
// < OK, now we make it to a buffer
ret = cJSON_PrintUnformatted(root);
cJSON_Delete(root);
return ret;
}
static char *MakeProfilePropertyReport(IoTProfileService_t *payload)
{
char *ret = NULL;
cJSON *root;
cJSON *services;
// < create the root node
root = cJSON_CreateObject();
if (root == NULL) {
cJSON_Delete(root);
return ret;
}
// < create the services array node to the root
services = MakeServices(payload);
if (services == NULL) {
if (root != NULL) {
cJSON_Delete(root);
}
return ret;
}
cJSON_AddItemToObjectCS(root, CN_PROFILE_KEY_SERVICES, services);
// < OK, now we make it to a buffer
ret = cJSON_PrintUnformatted(root);
cJSON_Delete(root);
return ret;
}
#define WECHAT_SUBSCRIBE_TYPE "update"
#define WECHAT_SUBSCRIBE_VERSION "1.0.0"
#define WECHAT_SUBSCRIBE_TOKEN "DeviceSubscribe"
static char *MakeProfileReport(WeChatProfile *payload)
{
char *ret = NULL;
cJSON *root;
cJSON *state;
cJSON *reported;
/* create json root node */
root = cJSON_CreateObject();
if (root == NULL) {
return;
}
/* state create */
state = cJSON_CreateObject();
if (state == NULL) {
return;
}
/* reported create */
reported = cJSON_CreateObject();
if (reported == NULL) {
return;
}
/* add root object */
cJSON_AddItemToObject(root, payload->subscribeType, cJSON_CreateString(WECHAT_SUBSCRIBE_TYPE));
cJSON_AddItemToObject(root, payload->status.subState, state);
cJSON_AddItemToObject(state, payload->status.subReport, reported);
cJSON_AddItemToObject(root, payload->status.reportVersion, cJSON_CreateString(WECHAT_SUBSCRIBE_VERSION));
cJSON_AddItemToObject(root, payload->status.Token, cJSON_CreateString(WECHAT_SUBSCRIBE_TOKEN));
/* add reported item */
cJSON_AddNumberToObject(reported, payload->reportAction.subDeviceActionLight,
payload->reportAction.lightActionStatus);
cJSON_AddNumberToObject(reported, payload->reportAction.subDeviceActionMotor,
payload->reportAction.motorActionStatus);
cJSON_AddNumberToObject(reported, payload->reportAction.subDeviceActionTemperature,
payload->reportAction.temperatureData);
cJSON_AddNumberToObject(reported, payload->reportAction.subDeviceActionHumidity,
payload->reportAction.humidityActionData);
cJSON_AddNumberToObject(reported, payload->reportAction.subDeviceActionLightIntensity,
payload->reportAction.lightIntensityActionData);
ret = cJSON_PrintUnformatted(root);
cJSON_Delete(state);
cJSON_Delete(reported);
cJSON_Delete(root);
return ret;
}
#define CN_PROFILE_TOPICFMT_TOPIC "YT32IOSCAL/Hi38611_mqtt/event"
/*int IoTProfilePropertyReport(char *deviceID, WeChatProfile *payload)
{
int ret = -1;
char *topic;
char *msg;
if ((deviceID == NULL) || (payload== NULL)) {
return ret;
}
topic = MakeTopic(CN_PROFILE_TOPICFMT_TOPIC, deviceID, NULL);
if (topic == NULL) {
return;
}
msg = MakeProfileReport(payload);
if ((topic != NULL) && (msg != NULL)) {
ret = IotSendMsg(0, topic, msg);
}
hi_free(0, topic);
cJSON_free(msg);
return ret;
}*/
int IoTProfilePropertyReport_uart(char *deviceID, char *msg)
{
int ret = -1;
char *topic;
//char *msg;
if ((deviceID == NULL) || (msg == NULL)) {
return ret;
}
topic = MakeTopic(CN_PROFILE_TOPICFMT_TOPIC, deviceID, NULL);
if (topic == NULL) {
return;
}
//msg = MakeProfileReport(payload);
if ((topic != NULL) && (msg != NULL)) {
ret = IotSendMsg(0, topic, msg);
printf("send success\n");
}
hi_free(0, topic);
//cJSON_free(msg);
return ret;
}

@ -0,0 +1,95 @@
/*
* Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
* 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 IOT_PROFILE_H
#define IOT_PROFILE_H
#include <hi_types_base.h>
#include "iot_config.h"
#define OC_BEEP_STATUS_ON ((hi_u8) 0x01)
#define OC_BEEP_STATUS_OFF ((hi_u8) 0x00)
// < enum all the data type for the oc profile
typedef enum {
EN_IOT_DATATYPE_INT = 0,
EN_IOT_DATATYPE_LONG,
EN_IOT_DATATYPE_FLOAT,
EN_IOT_DATATYPE_DOUBLE,
EN_IOT_DATATYPE_STRING, // < must be ended with '\0'
EN_IOT_DATATYPE_LAST,
}IoTDataType_t;
typedef enum {
OC_LED_ON = 1,
OC_LED_OFF
}OcLedValue;
typedef struct {
void *nxt; // < ponit to the next key
const char *key;
const char *value;
hi_u32 iValue;
IoTDataType_t type;
}IoTProfileKV_t;
typedef struct {
void *nxt;
char *serviceID;
char *eventTime;
IoTProfileKV_t *serviceProperty;
}IoTProfileService_t;
typedef struct {
int retCode; // < response code, 0 success while others failed
const char *respName; // < response name
const char *requestID; // < specified by the message command
IoTProfileKV_t *paras; // < the command paras
}IoTCmdResp_t;
typedef struct {
const char *subState;
const char *subReport;
const char *reportVersion;
const char *Token;
}WeChatProfileStatus;
typedef struct {
int lightActionStatus;
int motorActionStatus;
int temperatureData;
int humidityActionData;
int lightIntensityActionData;
const char *subDeviceActionLight;
const char *subDeviceActionMotor;
const char *subDeviceActionTemperature;
const char *subDeviceActionHumidity;
const char *subDeviceActionLightIntensity;
}WeChatProfileReporte;
typedef struct {
const char *subscribeType;
WeChatProfileStatus status;
WeChatProfileReporte reportAction;
}WeChatProfile;
/**
* use this function to report the property to the iot platform
*/
//int IoTProfilePropertyReport(char *deviceID, WeChatProfile *payload);
int IoTProfilePropertyReport_uart(char *deviceID, char *msg);
void cJsonInit(void);
void WifiStaReadyWait(void);
#endif

@ -0,0 +1,269 @@
/*
* Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
* 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.
*/
// < this demo make the wifi to connect to the specified AP
#include <unistd.h>
#include <hi_wifi_api.h>
#include <lwip/ip_addr.h>
#include <lwip/netifapi.h>
#include <hi_types_base.h>
#include <hi_task.h>
#include <hi_mem.h>
#include "iot_config.h"
#include "iot_log.h"
#include "wifi_device.h"
#include "cmsis_os2.h"
#include "wifi_device_config.h"
#include "lwip/api_shell.h"
#define APP_INIT_VAP_NUM 2
#define APP_INIT_USR_NUM 2
static struct netif *gLwipNetif = NULL;
static hi_bool gScanDone = HI_FALSE;
unsigned char wifiStatus = 0;
unsigned char wifiFirstConnecting = 0;
unsigned char wifiSecondConnecting = 0;
unsigned char wifiSecondConnected = 0;
static struct netif* g_iface = NULL;
void WifiStopSta(int netId);
static int WifiStartSta(void);
int cnetId = -1;
int g_connected = 0;
#define WIFI_CONNECT_STATUS ((unsigned char)0x02)
void wifiReconnected(int netId)
{
int recnetId = netId;
if (wifiFirstConnecting == WIFI_CONNECT_STATUS) {
wifiSecondConnecting = HI_TRUE;
wifiFirstConnecting = HI_FALSE;
WifiStopSta(recnetId);
ip4_addr_t ipAddr;
ip4_addr_t ipAny;
IP4_ADDR(&ipAny, 0, 0, 0, 0);
IP4_ADDR(&ipAddr, 0, 0, 0, 0);
recnetId = WifiStartSta();
netifapi_dhcp_start(gLwipNetif);
while (0 == memcmp(&ipAddr, &ipAny, sizeof(ip4_addr_t))) {
IOT_LOG_DEBUG("<Wifi reconnecting>:Wait the DHCP READY");
netifapi_netif_get_addr(gLwipNetif, &ipAddr, NULL, NULL);
hi_sleep(1000); /* 1000: cpu sleep 1000 ms */
}
wifiSecondConnected = HI_FALSE;
wifiFirstConnecting = WIFI_CONNECT_STATUS;
wifiStatus = HI_WIFI_EVT_CONNECTED;
}
}
/* clear netif's ip, gateway and netmask */
static void StaResetAddr(struct netif *lwipNetif)
{
ip4_addr_t st_gw;
ip4_addr_t st_ipaddr;
ip4_addr_t st_netmask;
if (lwipNetif == NULL) {
IOT_LOG_ERROR("hisi_reset_addr::Null param of netdev");
return;
}
IP4_ADDR(&st_gw, 0, 0, 0, 0);
IP4_ADDR(&st_ipaddr, 0, 0, 0, 0);
IP4_ADDR(&st_netmask, 0, 0, 0, 0);
netifapi_netif_set_addr(lwipNetif, &st_ipaddr, &st_netmask, &st_gw);
}
static void WpaEventCB(const hi_wifi_event *hisiEvent)
{
if (hisiEvent == NULL)
return;
IOT_LOG_DEBUG("EVENT_TYPE:%d", hisiEvent->event);
switch (hisiEvent->event) {
case HI_WIFI_EVT_SCAN_DONE:
IOT_LOG_DEBUG("WiFi: Scan results available");
gScanDone = HI_TRUE;
break;
case HI_WIFI_EVT_CONNECTED:
IOT_LOG_DEBUG("WiFi: Connected");
netifapi_dhcp_start(gLwipNetif);
wifiStatus = HI_WIFI_EVT_CONNECTED;
if (wifiSecondConnected) {
wifiSecondConnected = HI_FALSE;
wifiFirstConnecting = WIFI_CONNECT_STATUS;
}
break;
case HI_WIFI_EVT_DISCONNECTED:
IOT_LOG_DEBUG("WiFi: Disconnected");
netifapi_dhcp_stop(gLwipNetif);
StaResetAddr(gLwipNetif);
wifiStatus = HI_WIFI_EVT_DISCONNECTED;
wifiReconnected(cnetId);
break;
case HI_WIFI_EVT_WPS_TIMEOUT:
IOT_LOG_DEBUG("WiFi: wps is timeout");
wifiStatus = HI_WIFI_EVT_WPS_TIMEOUT;
break;
default:
break;
}
}
static int StaStartConnect(void)
{
int ret;
errno_t rc;
hi_wifi_assoc_request assoc_req = {0};
/* copy SSID to assoc_req */
rc = memcpy_s(assoc_req.ssid, HI_WIFI_MAX_SSID_LEN + 1, CONFIG_AP_SSID, strlen(CONFIG_AP_SSID));
if (rc != EOK) {
return -1;
}
/*
* OPEN mode
* for WPA2-PSK mode:
* set assoc_req.auth as HI_WIFI_SECURITY_WPA2PSK,
* then memcpy(assoc_req.key, "12345678", 8).
*/
assoc_req.auth = HI_WIFI_SECURITY_WPA2PSK;
rc = memcpy_s(assoc_req.key, HI_WIFI_MAX_KEY_LEN + 1, CONFIG_AP_PWD, strlen(CONFIG_AP_PWD));
if (rc != EOK) {
return -1;
}
ret = hi_wifi_sta_connect(&assoc_req);
if (ret != HISI_OK) {
return -1;
}
return 0;
}
static void PrintLinkedInfo(WifiLinkedInfo* info)
{
int ret = 0;
if (!info) {
return;
}
static char macAddress[32] = {0};
unsigned char* mac = info->bssid;
if (snprintf_s(macAddress, sizeof(macAddress) + 1, sizeof(macAddress), "%02X:%02X:%02X:%02X:%02X:%02X",
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]) < 0) { /* mac地址从0,1,2,3,4,5位 */
return;
}
}
static void OnWifiConnectionChanged(int state, WifiLinkedInfo* info)
{
if (!info) {
return;
}
printf("%s %d, state = %d, info = \r\n", __FUNCTION__, __LINE__, state);
PrintLinkedInfo(info);
if (state == WIFI_STATE_AVALIABLE) {
g_connected = 1;
} else {
g_connected = 0;
}
}
static void OnWifiScanStateChanged(int state, int size)
{
printf("%s %d, state = %X, size = %d\r\n", __FUNCTION__, __LINE__, state, size);
}
static WifiEvent g_defaultWifiEventListener = {
.OnWifiConnectionChanged = OnWifiConnectionChanged,
.OnWifiScanStateChanged = OnWifiScanStateChanged
};
static int WifiStartSta(void)
{
WifiDeviceConfig apConfig = {0};
strcpy_s(apConfig.ssid, sizeof(CONFIG_AP_SSID), CONFIG_AP_SSID);
strcpy_s(apConfig.preSharedKey, sizeof(CONFIG_AP_PWD), CONFIG_AP_PWD);
apConfig.securityType = WIFI_SEC_TYPE_PSK;
WifiErrorCode errCode;
int netId = -1;
errCode = RegisterWifiEvent(&g_defaultWifiEventListener);
printf("RegisterWifiEvent: %d\r\n", errCode);
errCode = EnableWifi();
printf("EnableWifi: %d\r\n", errCode);
errCode = AddDeviceConfig(&apConfig, &netId);
printf("AddDeviceConfig: %d\r\n", errCode);
g_connected = 0;
errCode = ConnectTo(netId);
printf("ConnectTo(%d): %d\r\n", netId, errCode);
while (!g_connected) { // wait until connect to AP
osDelay(10); /* 10: os sleep 10ms */
}
printf("g_connected: %d\r\n", g_connected);
g_iface = netifapi_netif_find("wlan0");
if (g_iface) {
err_t ret = netifapi_dhcp_start(g_iface);
printf("netifapi_dhcp_start: %d\r\n", ret);
osDelay(100); // 100: os sleep 100ms wait DHCP server give me IP
ret = netifapi_netif_common(g_iface, dhcp_clients_info_show, NULL);
printf("netifapi_netif_common: %d\r\n", ret);
}
return netId;
}
void WifiStopSta(int netId)
{
int stopNetId = netId;
if (g_iface) {
err_t ret = netifapi_dhcp_stop(g_iface);
printf("netifapi_dhcp_stop: %d\r\n", ret);
}
WifiErrorCode errCode = Disconnect(); // disconnect with your AP
printf("Disconnect: %d\r\n", errCode);
errCode = UnRegisterWifiEvent(&g_defaultWifiEventListener);
printf("UnRegisterWifiEvent: %d\r\n", errCode);
RemoveDevice(stopNetId); // remove AP config
printf("RemoveDevice: %d\r\n", errCode);
errCode = DisableWifi();
printf("DisableWifi: %d\r\n", errCode);
}
void WifiStaReadyWait(void)
{
ip4_addr_t ipAddr;
ip4_addr_t ipAny;
IP4_ADDR(&ipAny, 0, 0, 0, 0);
IP4_ADDR(&ipAddr, 0, 0, 0, 0);
cnetId = WifiStartSta();
IOT_LOG_DEBUG("wifi sta dhcp done");
}

@ -0,0 +1,27 @@
# Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
# 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.
static_library("interconnectionClient") {
sources = [
"app_demo_uart.c",
"hal_iot_gpio_ex.c",
"hisignalling_protocol.c",
]
include_dirs = [
"./",
"//utils/native/lite/include",
"//kernel/liteos_m/kal/cmsis",
"//base/iot_hardware/peripheral/interfaces/kits",
]
}

@ -0,0 +1,86 @@
# Pegasus与Taurus串口互联通信<a name="ZH-CN_TOPIC_0000001130176841"></a>
## 硬件环境搭建
- 硬件要求Hi3861V100核心板、底板、外设扩展板或者机器人板硬件搭建如下图所示。注意这里需要跟Taurus同时使用详情可以参考[串口互联server](http://gitee.com/openharmony/device_soc_hisilicon/blob/master/hi3516dv300/sdk_linux/sample/taurus/ai_sample/interconnection_server/README.md)端。
- 外设扩展板使用的是Hi3861的GPIO0和GPIO1作为串口1复用功能请在程序初始化时注意管脚复用关系。
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E4%BA%92%E8%81%94/10.jpg)
- 注意Robot板使用的串口1复用端口是Hi3861的GPIO5和GPIO6其中GPIO6要在程序烧录启动后才能使用如果用户在还没烧录和启动之前就将串口线与硬件连接上这时Hi3861将无法烧录和重启。GPIO6TX引脚影响Hi3861烧录和启动用户在使用Robot板时先拔掉Robot上4pin串口连接线在程序烧录启动后再将4pin串口连接线插回Robot板此时串口可以正常通信。如果用户在使用Robot板的过程中觉得频繁插拔串口线麻烦用户可在串口线上做一个开关当Hi3861烧录或复位启动前关闭开关单板启动后打开开关。
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E4%BA%92%E8%81%94/11.jpg)
## 串口通信控制协议HiSignalling介绍
- 为了便于Taurus与Pegasus开发套件之间进行通信和控制定义了一套简易的HiSignalling通信控制协议数据帧格式如下表所示并提供相关参考代码大家也可以根据自己的需要使用其他协议。
| 帧头2Byte | Payload Len (2Byte) | payload | 帧尾1Byte | CRC32(4Byte) |
|---|---|---|---|---|
| 0xAA,0x55 | | | 0xFF | CRC32 |
例如一组数据帧为AA5500020003FF8ED2BEDF (十六进制不区分大小写)
- 0AA55: 帧头
- 0002 Payload Len
- 0003: Payload
- FF: 帧尾
- 8ED2BEDF: CRC32校验码
## 软件介绍
- 注意这里需要跟Taurus同时使用Taurus软件介绍详情可以参考串口互联server端。
- 1.代码目录结构及相应接口功能介绍
- UART API
| API | 接口说明 |
| ------------------------------------------------------------ | ------------------------ |
| unsigned int UartInit(WifiIotUartIdx id, const WifiIotUartAttribute *param, const WifiIotUartExtraAttr *extraAttr); | 初始化配置一个UART设备 |
| int UartRead(WifiIotUartIdx id, unsigned char *data, unsigned int dataLen) | 从UART设备中读取数据 |
| int UartWrite(WifiIotUartIdx id, const unsigned char *data, unsigned int dataLen) | 将数据写入UART设备 |
- 2.工程编译
- 将源码./vendor/hisilicon/hispark_pegasus/demo目录下的interconnection_client_demo整个文件夹及内容复制到源码./applications/sample/wifi-iot/app/下,如图。
```
.
└── applications
└── sample
└── wifi-iot
└── app
└──interconnection_client_demo
└── 代码
```
- 在hisignalling.h文件中如果是想使用硬件扩展板请将BOARD_SELECT_IS_EXPANSION_BOARD这个宏打开如果是想使用Robot板请将BOARD_SELECT_IS_ROBOT_BOARD 这个宏打开。
```
/**
* @brief Adapter plate selection
* 使用时选择打开宏,使用外设扩展板打开#define BOARD_SELECT_IS_EXPANSION_BOARD这个宏
* 使用Robot板打开#define BOARD_SELECT_IS_ROBOT_BOARD这个宏
**/
//#define BOARD_SELECT_IS_ROBOT_BOARD
#define BOARD_SELECT_IS_EXPANSION_BOARD
#ifdef BOARD_SELECT_IS_EXPANSION_BOARD
#define EXPANSION_BOARD
#else
#define ROBOT_BOARD
#endif
```
- 修改源码./applications/sample/wifi-iot/app/BUILD.gn文件在features字段中增加索引使目标模块参与编译。features字段指定业务模块的路径和目标,features字段配置如下。
```
import("//build/lite/config/component/lite_component.gni")
lite_component("app") {
features = [
"interconnection_client_demo:interconnectionClientDemo",
]
}
```
- 工程相关配置完成后,然后编译。
- 3.烧录
- 编译成功后点击DevEco Home->配置工程->hi3861->upload_port->选择对应串口端口号->选择upload_protocol->选择hiburn-serial->点击save保存在保存成功后点击upload进行烧录出现connecting, please reset device..字样复位开发板等待烧录完成。
- 烧录成功后再次点击Hi3861核心板上的“RST”复位键此时开发板的系统会运行起来。运行结果:打开串口工具,可以看到如下打印,同时3861主板灯闪亮一下。
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E4%BA%92%E8%81%94/6.png)
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E4%BA%92%E8%81%94/7.png)
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E4%BA%92%E8%81%94/8.jpg)

@ -0,0 +1,144 @@
/*
* Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
* 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.
*/
#include <hi_stdlib.h>
#include <hisignalling_protocol.h>
#include <hi_uart.h>
#include <app_demo_uart.h>
#include <iot_uart.h>
#include <hi_gpio.h>
#include <hi_io.h>
#include "iot_gpio_ex.h"
#include "ohos_init.h"
#include "cmsis_os2.h"
UartDefConfig uartDefConfig = {0};
static void Uart1GpioCOnfig(void)
{
#ifdef ROBOT_BOARD
IoSetFunc(HI_IO_NAME_GPIO_5, IOT_IO_FUNC_GPIO_5_UART1_RXD);
IoSetFunc(HI_IO_NAME_GPIO_6, IOT_IO_FUNC_GPIO_6_UART1_TXD);
/* IOT_BOARD */
#elif defined (EXPANSION_BOARD)
IoSetFunc(HI_IO_NAME_GPIO_0, IOT_IO_FUNC_GPIO_0_UART1_TXD);
IoSetFunc(HI_IO_NAME_GPIO_1, IOT_IO_FUNC_GPIO_1_UART1_RXD);
#endif
}
int SetUartRecvFlag(UartRecvDef def)
{
if (def == UART_RECV_TRUE) {
uartDefConfig.g_uartReceiveFlag = HI_TRUE;
} else {
uartDefConfig.g_uartReceiveFlag = HI_FALSE;
}
return uartDefConfig.g_uartReceiveFlag;
}
int GetUartConfig(UartDefType type)
{
int receive = 0;
switch (type) {
case UART_RECEIVE_FLAG:
receive = uartDefConfig.g_uartReceiveFlag;
break;
case UART_RECVIVE_LEN:
receive = uartDefConfig.g_uartLen;
break;
default:
break;
}
return receive;
}
void ResetUartReceiveMsg(void)
{
(void)memset_s(uartDefConfig.g_receiveUartBuff, sizeof(uartDefConfig.g_receiveUartBuff),
0x0, sizeof(uartDefConfig.g_receiveUartBuff));
}
unsigned char *GetUartReceiveMsg(void)
{
return uartDefConfig.g_receiveUartBuff;
}
static hi_void *UartDemoTask(char *param)
{
hi_u8 uartBuff[UART_BUFF_SIZE] = {0};
hi_unref_param(param);
printf("Initialize uart demo successfully, please enter some datas via DEMO_UART_NUM port...\n");
Uart1GpioCOnfig();
for (;;) {
uartDefConfig.g_uartLen = IoTUartRead(DEMO_UART_NUM, uartBuff, UART_BUFF_SIZE);
if ((uartDefConfig.g_uartLen > 0) && (uartBuff[0] == 0xaa) && (uartBuff[1] == 0x55)) {
if (GetUartConfig(UART_RECEIVE_FLAG) == HI_FALSE) {
(void)memcpy_s(uartDefConfig.g_receiveUartBuff, uartDefConfig.g_uartLen,
uartBuff, uartDefConfig.g_uartLen);/*uartBuff中的信息放到uartDefConfig.g_receiveUartBuff*/
(void)SetUartRecvFlag(UART_RECV_TRUE);
}
}
printf("len:%d\n", uartDefConfig.g_uartLen);
for (int i = 0; i<uartDefConfig.g_uartLen; i++)
{
if(i <= 2)
{
printf("0x%x ", uartBuff[i]);
}
else
{
printf("%c ", uartBuff[i]);
}
}
TaskMsleep(20); /* 20:sleep 20ms */
}
return HI_NULL;
}
/*
* This demo simply shows how to read datas from UART2 port and then echo back.
*/
hi_void UartTransmit(hi_void)
{
hi_u32 ret = 0;
IotUartAttribute uartAttr = {
.baudRate = 115200, /* baudRate: 115200 */
.dataBits = 8, /* dataBits: 8bits */
.stopBits = 1, /* stop bit */
.parity = 0,
};
/* Initialize uart driver */
ret = IoTUartInit(DEMO_UART_NUM, &uartAttr);
if (ret != HI_ERR_SUCCESS) {
printf("Failed to init uart! Err code = %d\n", ret);
return;
}
/* Create a task to handle uart communication */
osThreadAttr_t attr = {0};
attr.stack_size = UART_DEMO_TASK_STAK_SIZE;
attr.priority = UART_DEMO_TASK_PRIORITY;
attr.name = (hi_char*)"uart demo";
if (osThreadNew((osThreadFunc_t)UartDemoTask, NULL, &attr) == NULL) {
printf("Falied to create uart demo task!\n");
}
}
SYS_RUN(UartTransmit);

@ -0,0 +1,48 @@
/*
* Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
* 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 APP_DEMO_UART_H
#define APP_DEMO_UART_H
#define UART_BUFF_SIZE 1024
#define WRITE_BY_INT
#define UART_DEMO_TASK_STAK_SIZE 2048
#define UART_DEMO_TASK_PRIORITY 25
#define DEMO_UART_NUM HI_UART_IDX_1
typedef enum {
UART_RECEIVE_FLAG = 0,
UART_RECVIVE_LEN,
UART_SEND_FLAG = 2,
UART_SEND_LEN
}UartDefType;
typedef enum {
UART_RECV_TRUE = 0,
UART_RECV_FALSE,
}UartRecvDef;
typedef struct {
unsigned int uartChannel;
unsigned char g_receiveUartBuff[UART_BUFF_SIZE];
int g_uartReceiveFlag;
int g_uartLen;
}UartDefConfig;
int SetUartRecvFlag(UartRecvDef def);
int GetUartConfig(UartDefType type);
void ResetUartReceiveMsg(void);
unsigned char *GetUartReceiveMsg(void);
#endif

@ -0,0 +1,45 @@
/*
* Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
* 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.
*/
#include "iot_errno.h"
#include "hi_gpio.h"
#include "hi_io.h"
#include "hi_task.h"
#include "hi_types_base.h"
#include "iot_gpio_ex.h"
unsigned int IoSetPull(unsigned int id, IotIoPull val)
{
if (id >= HI_GPIO_IDX_MAX) {
return IOT_FAILURE;
}
return hi_io_set_pull((hi_io_name)id, (hi_io_pull)val);
}
unsigned int IoSetFunc(unsigned int id, unsigned char val) /* 复用功能 */
{
if (id >= HI_GPIO_IDX_MAX) {
return IOT_FAILURE;
}
return hi_io_set_func((hi_io_name)id, val);
}
unsigned int TaskMsleep(unsigned int ms)
{
if (ms <= 0) {
return IOT_FAILURE;
}
return hi_sleep((hi_u32)ms);
}

@ -0,0 +1,286 @@
/*
* Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
* 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.
*/
#include <hi_types_base.h>
#include <hi_early_debug.h>
#include <hi_stdlib.h>
#include <hi_uart.h>
#include <hi_task.h>
#include <app_demo_uart.h>
#include <iot_uart.h>
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_gpio_ex.h"
#include "hi_io.h"
#include "iot_gpio.h"
#include "hisignalling_protocol.h"
#define LED_TEST_GPIO 9
#define LED_INTERVAL_TIME_US 300000
hi_u8 g_sendUartBuff[UART_BUFF_SIZE];
UartDefConfig recConfig = {0};
/*
* crc32 Verification implementation
*/
static const unsigned int crc32table[] = {
0x00000000L, 0x77073096L, 0xee0e612cL, 0x990951baL,
0x076dc419L, 0x706af48fL, 0xe963a535L, 0x9e6495a3L,
0x0edb8832L, 0x79dcb8a4L, 0xe0d5e91eL, 0x97d2d988L,
0x09b64c2bL, 0x7eb17cbdL, 0xe7b82d07L, 0x90bf1d91L,
0x1db71064L, 0x6ab020f2L, 0xf3b97148L, 0x84be41deL,
0x1adad47dL, 0x6ddde4ebL, 0xf4d4b551L, 0x83d385c7L,
0x136c9856L, 0x646ba8c0L, 0xfd62f97aL, 0x8a65c9ecL,
0x14015c4fL, 0x63066cd9L, 0xfa0f3d63L, 0x8d080df5L,
0x3b6e20c8L, 0x4c69105eL, 0xd56041e4L, 0xa2677172L,
0x3c03e4d1L, 0x4b04d447L, 0xd20d85fdL, 0xa50ab56bL,
0x35b5a8faL, 0x42b2986cL, 0xdbbbc9d6L, 0xacbcf940L,
0x32d86ce3L, 0x45df5c75L, 0xdcd60dcfL, 0xabd13d59L,
0x26d930acL, 0x51de003aL, 0xc8d75180L, 0xbfd06116L,
0x21b4f4b5L, 0x56b3c423L, 0xcfba9599L, 0xb8bda50fL,
0x2802b89eL, 0x5f058808L, 0xc60cd9b2L, 0xb10be924L,
0x2f6f7c87L, 0x58684c11L, 0xc1611dabL, 0xb6662d3dL,
0x76dc4190L, 0x01db7106L, 0x98d220bcL, 0xefd5102aL,
0x71b18589L, 0x06b6b51fL, 0x9fbfe4a5L, 0xe8b8d433L,
0x7807c9a2L, 0x0f00f934L, 0x9609a88eL, 0xe10e9818L,
0x7f6a0dbbL, 0x086d3d2dL, 0x91646c97L, 0xe6635c01L,
0x6b6b51f4L, 0x1c6c6162L, 0x856530d8L, 0xf262004eL,
0x6c0695edL, 0x1b01a57bL, 0x8208f4c1L, 0xf50fc457L,
0x65b0d9c6L, 0x12b7e950L, 0x8bbeb8eaL, 0xfcb9887cL,
0x62dd1ddfL, 0x15da2d49L, 0x8cd37cf3L, 0xfbd44c65L,
0x4db26158L, 0x3ab551ceL, 0xa3bc0074L, 0xd4bb30e2L,
0x4adfa541L, 0x3dd895d7L, 0xa4d1c46dL, 0xd3d6f4fbL,
0x4369e96aL, 0x346ed9fcL, 0xad678846L, 0xda60b8d0L,
0x44042d73L, 0x33031de5L, 0xaa0a4c5fL, 0xdd0d7cc9L,
0x5005713cL, 0x270241aaL, 0xbe0b1010L, 0xc90c2086L,
0x5768b525L, 0x206f85b3L, 0xb966d409L, 0xce61e49fL,
0x5edef90eL, 0x29d9c998L, 0xb0d09822L, 0xc7d7a8b4L,
0x59b33d17L, 0x2eb40d81L, 0xb7bd5c3bL, 0xc0ba6cadL,
0xedb88320L, 0x9abfb3b6L, 0x03b6e20cL, 0x74b1d29aL,
0xead54739L, 0x9dd277afL, 0x04db2615L, 0x73dc1683L,
0xe3630b12L, 0x94643b84L, 0x0d6d6a3eL, 0x7a6a5aa8L,
0xe40ecf0bL, 0x9309ff9dL, 0x0a00ae27L, 0x7d079eb1L,
0xf00f9344L, 0x8708a3d2L, 0x1e01f268L, 0x6906c2feL,
0xf762575dL, 0x806567cbL, 0x196c3671L, 0x6e6b06e7L,
0xfed41b76L, 0x89d32be0L, 0x10da7a5aL, 0x67dd4accL,
0xf9b9df6fL, 0x8ebeeff9L, 0x17b7be43L, 0x60b08ed5L,
0xd6d6a3e8L, 0xa1d1937eL, 0x38d8c2c4L, 0x4fdff252L,
0xd1bb67f1L, 0xa6bc5767L, 0x3fb506ddL, 0x48b2364bL,
0xd80d2bdaL, 0xaf0a1b4cL, 0x36034af6L, 0x41047a60L,
0xdf60efc3L, 0xa867df55L, 0x316e8eefL, 0x4669be79L,
0xcb61b38cL, 0xbc66831aL, 0x256fd2a0L, 0x5268e236L,
0xcc0c7795L, 0xbb0b4703L, 0x220216b9L, 0x5505262fL,
0xc5ba3bbeL, 0xb2bd0b28L, 0x2bb45a92L, 0x5cb36a04L,
0xc2d7ffa7L, 0xb5d0cf31L, 0x2cd99e8bL, 0x5bdeae1dL,
0x9b64c2b0L, 0xec63f226L, 0x756aa39cL, 0x026d930aL,
0x9c0906a9L, 0xeb0e363fL, 0x72076785L, 0x05005713L,
0x95bf4a82L, 0xe2b87a14L, 0x7bb12baeL, 0x0cb61b38L,
0x92d28e9bL, 0xe5d5be0dL, 0x7cdcefb7L, 0x0bdbdf21L,
0x86d3d2d4L, 0xf1d4e242L, 0x68ddb3f8L, 0x1fda836eL,
0x81be16cdL, 0xf6b9265bL, 0x6fb077e1L, 0x18b74777L,
0x88085ae6L, 0xff0f6a70L, 0x66063bcaL, 0x11010b5cL,
0x8f659effL, 0xf862ae69L, 0x616bffd3L, 0x166ccf45L,
0xa00ae278L, 0xd70dd2eeL, 0x4e048354L, 0x3903b3c2L,
0xa7672661L, 0xd06016f7L, 0x4969474dL, 0x3e6e77dbL,
0xaed16a4aL, 0xd9d65adcL, 0x40df0b66L, 0x37d83bf0L,
0xa9bcae53L, 0xdebb9ec5L, 0x47b2cf7fL, 0x30b5ffe9L,
0xbdbdf21cL, 0xcabac28aL, 0x53b39330L, 0x24b4a3a6L,
0xbad03605L, 0xcdd70693L, 0x54de5729L, 0x23d967bfL,
0xb3667a2eL, 0xc4614ab8L, 0x5d681b02L, 0x2a6f2b94L,
0xb40bbe37L, 0xc30c8ea1L, 0x5a05df1bL, 0x2d02ef8dL
};
static unsigned int crc32(const unsigned char *buf, unsigned int len)
{
unsigned int i, crc = 0xFFFFFFFF;
for (i = 0; i < len; i++) {
crc = crc32table[(crc ^ buf[i]) & 0xff] ^ (crc >> 8); /* 8: right move 8 bit */
}
return crc ^ 0xFFFFFFFF;
}
/* Log level look up table */
static const char *hisignallingLevelNames[] = {
"TRACE",
"DEBUG",
"INFO",
"WARN",
"ERROR",
"FATAL"
};
/* get hisignaling log level */
const char *HisignallingLevelNum (HisignallingLogType hisignallingLevel)
{
if (hisignallingLevel >= HISIGNALLING_LEVEL_MAX) {
return "NULL";
} else {
return hisignallingLevelNames[hisignallingLevel];
}
}
#define RIGHT_MOVE_8_BIT (8)
#define RIGHT_MOVE_16_BIT (16)
#define RIGHT_MOVE_24_BIT (24)
/* hisignal Hi3861 message package */
static hi_u32 HisignallingDataPackage(HisignallingProtocalType *buf, hi_u32 len, hi_u8 *hisignallingDataBuf)
{
hi_u32 crcCheckSend = 0;
hi_u32 packageLen = 0;
memcpy_s(hisignallingDataBuf, HISGNALLING_MSG_FRAME_HEADER_LEN,
buf->frameHeader, HISGNALLING_MSG_FRAME_HEADER_LEN);
memcpy_s(&hisignallingDataBuf[HISGNALLING_MSG_FRAME_HEADER_LEN],
len, buf->hisignallingMsgBuf, len);
memcpy_s(&hisignallingDataBuf[HISGNALLING_MSG_FRAME_HEADER_LEN + len],
HISIGNALLING_MSG_HEADER_LEN, &(buf->endOfFrame), HISIGNALLING_MSG_HEADER_LEN);
crcCheckSend = crc32(hisignallingDataBuf, (len + HISIGNALLING_MSG_HEADER_TAIL_LEN));
hisignallingDataBuf[len + HISIGNALLING_MSG_HEADER_TAIL_LEN] =
(hi_u8) ((crcCheckSend & 0xff000000)>>RIGHT_MOVE_24_BIT);
hisignallingDataBuf[len + HISIGNALLING_MSG_HEADER_TAIL_LEN + 1] = /* 1: addr offset */
(hi_u8) ((crcCheckSend & 0x00ff0000)>>RIGHT_MOVE_16_BIT);
hisignallingDataBuf[len + HISIGNALLING_MSG_HEADER_TAIL_LEN + 2] = /* 2: addr offset */
(hi_u8) ((crcCheckSend & 0x0000ff00)>>RIGHT_MOVE_8_BIT);
hisignallingDataBuf[len + HISIGNALLING_MSG_HEADER_TAIL_LEN + 3] = /* 3: addr offset */
(hi_u8)crcCheckSend;
packageLen = len + HISIGNALLING_MSG_HEADER_TAIL_LEN + HISGNALLING_MSG_CRC32_LEN;
return packageLen;
}
/* hisignal Hi3861 message recevice */
HisignallingErrorType HisignallingMsgReceive(hi_u8 *buf, hi_u32 len)
{
hi_u32 crcCheckReceived = 0;
unsigned char testBuff[7] = {0xaa, 0x55, 0x0, 0x2, 0x0, 0x8, 0xff};
if (buf == HI_NULL && len > 0) {
HISIGNALLING_LOG_FATAL("received buf is null");
return HISGNALLING_RET_VAL_MAX;
}
printf("length:%u\n", len);
/* 校验crc */
if (len > HISGNALLING_MSG_CRC32_LEN) {
crcCheckReceived = crc32(buf, len - HISGNALLING_MSG_CRC32_LEN);
if (((hi_u8)((crcCheckReceived & 0xff000000)>>RIGHT_MOVE_24_BIT) != buf[len - 4]) && /* 4: addr offset */
((hi_u8)((crcCheckReceived & 0x00ff0000)>>RIGHT_MOVE_16_BIT) != buf[len - 3]) && /* 3: addr offset */
((hi_u8)((crcCheckReceived & 0x0000ff00)>>RIGHT_MOVE_8_BIT) != buf[len - 2]) && /* 2: addr offset */
((hi_u8)crcCheckReceived != buf[len - 1])) {
HISIGNALLING_LOG_ERROR("<Hi3861>: crc32 Verification failed!");
HISIGNALLING_LOG_ERROR("<Hi3861>:crc_4=0x%x, crc_3=0x%x, crc_2=0x%x, crc_1=0x%x",
buf[len - 4], buf[len - 3], buf[len - 2], buf[len - 1]); /* 4,3,2,1 addr offset */
return HISIGNALLING_RET_VAL_ERROR;
}
}
IoTGpioSetOutputVal(LED_TEST_GPIO, 0);
usleep(LED_INTERVAL_TIME_US);
IoTGpioSetOutputVal(LED_TEST_GPIO, 1);
usleep(LED_INTERVAL_TIME_US);
/* 输出回显收到的数据 */
/*if ((buf[0] == HISIGNALLING_MSG_FRAME_HEADER_1) && (buf[1] == HISIGNALLING_MSG_FRAME_HEADER_2)) {
for (int i = 0; i < len; i++) {
HISIGNALLING_LOG_INFO("0x%x", buf[i]);
}
}*/
return HISIGNALLING_RET_VAL_CORRECT;
}
/* hisignal Hi3861 message send */
hi_u32 HisignallingMsgSend(char *buf, hi_u32 dataLen)
{
HisignallingProtocalType hisignallingMsg = {0};
hi_u8 hisignallingSendBuf[HISIGNALLING_MSG_BUFF_LEN] = {0};
hi_u32 hisignallingPackageLen = 0;
hi_u32 writeDataLen = 0;
hisignallingMsg.frameHeader[0]= HISIGNALLING_MSG_FRAME_HEADER_1;
hisignallingMsg.frameHeader[1]= HISIGNALLING_MSG_FRAME_HEADER_2;
(void)memcpy_s(hisignallingMsg.hisignallingMsgBuf, dataLen, buf, dataLen);
hisignallingMsg.endOfFrame = HISIGNALLING_MSG_FRAME_TAIL;
hisignallingPackageLen = HisignallingDataPackage(&hisignallingMsg, dataLen, hisignallingSendBuf);
if (!hisignallingPackageLen) {
HISIGNALLING_LOG_ERROR("hisignaling_data_package failed\r\n");
return HI_ERR_FAILURE;
}
if (*hisignallingSendBuf == NULL) {
HISIGNALLING_LOG_ERROR("hisignal send buf is null!\r\n");
return HI_ERR_FAILURE;
}
writeDataLen = IoTUartWrite(HI_UART_IDX_1, hisignallingSendBuf, hisignallingPackageLen);
if (!writeDataLen) {
HISIGNALLING_LOG_ERROR("hi_uart_write failed\r\n");
return HI_ERR_FAILURE;
}
return HI_ERR_SUCCESS;
}
int SetUartReceiveFlag(void)
{
return recConfig.g_uartReceiveFlag;
}
hi_void *HisignallingMsgHandle(char *param)
{
unsigned char *recBuff = NULL;
int len;
while (1) {
/*g_sendUartBuff清零*/
(void)memset_s(g_sendUartBuff, sizeof(g_sendUartBuff) / sizeof(g_sendUartBuff[0]),
0x0, sizeof(g_sendUartBuff)/sizeof(g_sendUartBuff[0]));
/*GetUartConfig得到data的flag和length*/
if (GetUartConfig(UART_RECEIVE_FLAG) == HI_TRUE) {
/* 接收数据 */
HisignallingMsgReceive(GetUartReceiveMsg(), GetUartConfig(UART_RECVIVE_LEN));
/* 回显数据组包 */
if (GetUartConfig(UART_RECVIVE_LEN) > (HISGNALLING_MSG_CRC32_LEN + HISIGNALLING_MSG_HEADER_TAIL_LEN)) {
len = GetUartConfig(UART_RECVIVE_LEN);
recBuff = GetUartReceiveMsg();
for (int i = 0; i < len ; i++ ){
HISIGNALLING_LOG_INFO("0x%x", recBuff[i]);
}
printf("end\n");
(void)memcpy_s(g_sendUartBuff,
(GetUartConfig(UART_RECVIVE_LEN) - HISGNALLING_MSG_CRC32_LEN - HISIGNALLING_MSG_HEADER_TAIL_LEN),
&recBuff[HISGNALLING_MSG_FRAME_HEADER_LEN],
(GetUartConfig(UART_RECVIVE_LEN) - HISGNALLING_MSG_CRC32_LEN - HISIGNALLING_MSG_HEADER_TAIL_LEN));
/* 接收到Hi3516DV300数据后发送回显 */
HisignallingMsgSend(g_sendUartBuff,
(GetUartConfig(UART_RECVIVE_LEN) - HISGNALLING_MSG_CRC32_LEN - HISIGNALLING_MSG_HEADER_TAIL_LEN));
}
(void)SetUartRecvFlag(UART_RECV_FALSE);
ResetUartReceiveMsg();
}
TaskMsleep(HISGNALLING_FREE_TASK_TIME);
}
}
hi_u32 HisignalingMsgTask(hi_void)
{
hi_u32 ret = 0;
IoTGpioInit(LED_TEST_GPIO);
IoTGpioSetDir(LED_TEST_GPIO, IOT_GPIO_DIR_OUT);
osThreadAttr_t hisignallingAttr = {0};
hisignallingAttr.stack_size = HISIGNALLING_MSG_TASK_STACK_SIZE;
hisignallingAttr.priority = HISIGNALLING_MSG_TASK_PRIO;
hisignallingAttr.name = (hi_char*)"hisignal msg task";
if (osThreadNew((osThreadFunc_t)HisignallingMsgHandle, NULL, &hisignallingAttr) == NULL) {
HISIGNALLING_LOG_ERROR("Failed to create hisignaling msg task\r\n");
return HI_ERR_FAILURE;
}
return HI_ERR_SUCCESS;
}
//SYS_RUN(HisignalingMsgTask);

@ -0,0 +1,207 @@
/*
* Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
* 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 HISIGNALLING_PROTOCOL_H
#define HISIGNALLING_PROTOCOL_H
#include <hi_types_base.h>
#include <stdarg.h>
#include <stdint.h>
#include <stddef.h>
#include <stdio.h>
/**
* @brief : hisignalling Macro definition
*/
#define HISIGNALLING_MSG_HEADER_LEN (1)
#define HISGNALLING_MSG_FRAME_HEADER_LEN (2)
#define HISIGNALLING_MSG_HEADER_TAIL_LEN (3)
#define HISGNALLING_MSG_CRC32_LEN (4)
#define HISIGNALLING_MSG_PAYLOAD_INDEX (5)
#define HISGNALLING_FREE_TASK_TIME (20)
#define HISIGNALLING_MSG_TASK_PRIO (28)
#define HISIGNALLING_UART_MSG_LEN (32)
#define HISIGNALLING_MSG_BUFF_LEN (512)
#define HISIGNALLING_MSG_TASK_STACK_SIZE (4096)
/* hisgnalling protocol frame header and tail */
#define HISIGNALLING_MSG_FRAME_HEADER_1 ((hi_u8)0xAA)
#define HISIGNALLING_MSG_FRAME_HEADER_2 ((hi_u8)0x55)
#define HISIGNALLING_MSG_FRAME_TAIL ((hi_u8)0xFF)
/**
* @brief Adapter plate selection
* 使使#define BOARD_SELECT_IS_EXPANSION_BOARD
* 使Robot#define BOARD_SELECT_IS_ROBOT_BOARD#define BOARD_SELECT_IS_EXPANSION_BOARD
**/
#define BOARD_SELECT_IS_EXPANSION_BOARD
#ifdef BOARD_SELECT_IS_EXPANSION_BOARD
#define EXPANSION_BOARD
#else
#define ROBOT_BOARD
#endif
/**
* @brief:this defines for the log module, and HISIGNALING_LOG_TRACE/HISIGNALING_LOG_DEBUG...
* will not participate the compile in the release version
* */
typedef enum {
HISIGNALLING_LEVEL_TRACE = 0,
HISIGNALLING_LEVEL_DEBUG,
HISIGNALLING_LEVEL_INFO,
HISIGNALLING_LEVEL_WARN,
HISIGNALLING_LEVEL_ERROR,
HISIGNALLING_LEVEL_FATAL,
HISIGNALLING_LEVEL_MAX
} HisignallingLogType;
/**
* @brief: use this function to get the hisignalling log level name
*
* @parameter[in]:level, the level to get
*
* @return: the mapped level name
* */
const char *HisignallingLevelNum (HisignallingLogType hisignallingLevel);
/**
* @brief: this is a weak function ,and you could rewrite one
*
* @param fmt: same use as the fmt for printf
*
* @param unfixed: same use for printf
*
* @return: don't care about it
*
* @attention: and the components should not call this function directly, you'd better
*
* call HISIGNALING_LOG groups
*
* */
#define HISIGNALLING_PRINT(fmt, ...) \
do \
{ \
printf(fmt, ##__VA_ARGS__); \
} while (0)
#define HISIGNALLING_LOG(level, fmt, ...) \
do \
{ \
HISIGNALLING_PRINT("<%s>, <%s>, <%d> "fmt" \r\n", \
HisignallingLevelNum((level)), __FUNCTION__, __LINE__, ##__VA_ARGS__); \
} while (0)
#define HISIGNALLING_LOG_TRACE(fmt, ...) \
do \
{ \
HISIGNALLING_LOG (HISIGNALLING_LEVEL_TRACE, fmt, ##__VA_ARGS__); \
} while (0)
#define HISIGNALLING_LOG_DEBUG(fmt, ...) \
do \
{ \
HISIGNALLING_LOG (HISIGNALLING_LEVEL_DEBUG, fmt, ##__VA_ARGS__); \
} while (0)
#define HISIGNALLING_LOG_INFO(fmt, ...) \
do \
{ \
HISIGNALLING_LOG (HISIGNALLING_LEVEL_INFO, fmt, ##__VA_ARGS__); \
} while (0)
#define HISIGNALLING_LOG_WARN(fmt, ...) \
do \
{ \
HISIGNALLING_LOG (HISIGNALLING_LEVEL_WARN, fmt, ##__VA_ARGS__); \
} while (0)
#define HISIGNALLING_LOG_ERROR(fmt, ...) \
do \
{ \
HISIGNALLING_LOG (HISIGNALLING_LEVEL_ERROR, fmt, ##__VA_ARGS__); \
} while (0)
#define HISIGNALLING_LOG_FATAL(fmt, ...) \
do \
{ \
HISIGNALLING_LOG (HISIGNALLING_LEVEL_FATAL, fmt, ##__VA_ARGS__); \
} while (0)
/**
* @brief: use this hisignalling Transmission protocol frame format
*
* @param frameHeader: Transmission protocol frame header
*
* @param hisignallingMsgBuf: Transmission protocol frame buffer
*
* @param hisigallingMsgLen: Transmission protocol frame buffer len
*
* @param endOfFrame: Transmission protocol frame tail
*
* @param hisignallingCrc32Check: Transmission protocol crc32 check
*
* */
typedef struct {
hi_u8 frameHeader[HISGNALLING_MSG_FRAME_HEADER_LEN];
hi_u8 hisignallingMsgBuf[HISIGNALLING_MSG_BUFF_LEN];
hi_u32 hisigallingMsgLen;
hi_u8 endOfFrame;
hi_u32 hisignallingCrc32Check;
}HisignallingProtocalType;
/**
* @brief: use this hisignalling return type
*
* @param HISIGNALLING_RET_VAL_CORRECT: return type is correct
*
* @param HISIGNALLING_RET_VAL_ERROR: return type is error
*
* @param HISIGNALLING_RET_VAL_ERROR: return type is unknown type
* */
typedef enum {
HISIGNALLING_RET_VAL_CORRECT = 0,
HISIGNALLING_RET_VAL_ERROR,
HISGNALLING_RET_VAL_MAX
}HisignallingErrorType;
/**
* @brief: use this hisignalling sample:Access peripheral enumeration type
*
* @param MOTOR_GO_FORWARD: peripheral motor go forward
*
* @param MOTOR_GO_BACK: peripheral motor go back
*
* @param STEERING_ENGINE_MOVEMENT/STEERING_ENGINE_AND_MOTOR_MOVEMENT/STEERING_ENGINE_AND_MOTOR_STOP
* the same use for peripheral
* */
typedef enum {
MOTOR_GO_FORWARD = 0,
MOTOR_GO_BACK,
STEERING_ENGINE_MOVEMENT,
STEERING_ENGINE_AND_MOTOR_MOVEMENT,
STEERING_ENGINE_AND_MOTOR_STOP,
TRASH_CAN_LID_OPEN,
TRASH_CAN_LID_COLSE
}HisignallingDataType;
/**
* @brief:hisignalling protocal Function declaration
**/
hi_u32 hisignallingMsgTask(hi_void);
/**
* @brief:hisignalling uart message receive API
* @param buf: uart receive buffer
* @param len: uart receive buffer len
*/
HisignallingErrorType hisignallingMsgReceive(hi_u8 *buf, hi_u32 len);
/**
* @brief:hisignalling uart send API
* @param buf: uart message send buffer
* @param len: uart message send buffer len
*/
hi_u32 hisignallingMsgSend(hi_void *buf, hi_u32 dataLen);
int SetUartReceiveFlag(void);
#endif /* HISIGNALING_PROTOCOL_H */

@ -0,0 +1,394 @@
/*
* Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
* 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.
*/
/**
* @file iot_gpio_ex.h
*
* @brief Declares the extended GPIO interface functions.
*
* These functions are used for settings GPIO pulls and driver strength. \n
*
* @since 1.0
* @version 1.0
*/
#ifndef IOT_GPIO_EX_H
#define IOT_GPIO_EX_H
/**
* @brief Enumerates GPIO pull-up or pull-down settings.
*/
typedef enum {
/** No pull */
IOT_IO_PULL_NONE,
/** Pull-up */
IOT_IO_PULL_UP,
/** Pull-down */
IOT_IO_PULL_DOWN,
/** Maximum value */
IOT_IO_PULL_MAX,
} IotIoPull;
/**
* @ingroup iot_io
*
* GPIO pin ID. CNcomment:IOCNend
*/
typedef enum {
IOT_IO_NAME_GPIO_0, /* <GPIO0 */
IOT_IO_NAME_GPIO_1, /* <GPIO1 */
IOT_IO_NAME_GPIO_2, /* <GPIO2 */
IOT_IO_NAME_GPIO_3, /* <GPIO3 */
IOT_IO_NAME_GPIO_4, /* <GPIO4 */
IOT_IO_NAME_GPIO_5, /* <GPIO5 */
IOT_IO_NAME_GPIO_6, /* <GPIO6 */
IOT_IO_NAME_GPIO_7, /* <GPIO7 */
IOT_IO_NAME_GPIO_8, /* <GPIO8 */
IOT_IO_NAME_GPIO_9, /* <GPIO9 */
IOT_IO_NAME_GPIO_10, /* <GPIO10 */
IOT_IO_NAME_GPIO_11, /* <GPIO11 */
IOT_IO_NAME_GPIO_12, /* <GPIO12 */
IOT_IO_NAME_GPIO_13, /* <GPIO13 */
IOT_IO_NAME_GPIO_14, /* <GPIO14 */
IOT_IO_NAME_SFC_CSN, /* <SFC_CSN */
IOT_IO_NAME_SFC_IO1, /* <SFC_IO1 */
IOT_IO_NAME_SFC_IO2, /* <SFC_IO2 */
IOT_IO_NAME_SFC_IO0, /* <SFC_IO0 */
IOT_IO_NAME_SFC_CLK, /* <SFC_CLK */
IOT_IO_NAME_SFC_IO3, /* <SFC_IO3 */
IOT_IO_NAME_MAX,
} IotIoName;
/**
* @ingroup iot_io
*
* GPIO_0 pin function.CNcomment:GPIO_0CNend
*/
typedef enum {
IOT_IO_FUNC_GPIO_0_GPIO,
IOT_IO_FUNC_GPIO_0_UART1_TXD = 2,
IOT_IO_FUNC_GPIO_0_SPI1_CK,
IOT_IO_FUNC_GPIO_0_JTAG_TDO,
IOT_IO_FUNC_GPIO_0_PWM3_OUT,
IOT_IO_FUNC_GPIO_0_I2C1_SDA,
} IotIoFuncGpio0;
/**
* @ingroup iot_io
*
* GPIO_1 pin function.CNcomment:GPIO_1CNend
*/
typedef enum {
IOT_IO_FUNC_GPIO_1_GPIO,
IOT_IO_FUNC_GPIO_1_UART1_RXD = 2,
IOT_IO_FUNC_GPIO_1_SPI1_RXD,
IOT_IO_FUNC_GPIO_1_JTAG_TCK,
IOT_IO_FUNC_GPIO_1_PWM4_OUT,
IOT_IO_FUNC_GPIO_1_I2C1_SCL,
IOT_IO_FUNC_GPIO_1_BT_FREQ,
} IotIoFuncGpio1;
/**
* @ingroup iot_io
*
* GPIO_2 pin function.CNcomment:GPIO_2CNend
*/
typedef enum {
IOT_IO_FUNC_GPIO_2_GPIO,
IOT_IO_FUNC_GPIO_2_UART1_RTS_N = 2,
IOT_IO_FUNC_GPIO_2_SPI1_TXD,
IOT_IO_FUNC_GPIO_2_JTAG_TRSTN,
IOT_IO_FUNC_GPIO_2_PWM2_OUT,
IOT_IO_FUNC_GPIO_2_SSI_CLK = 7,
} IotIoFuncGpio2;
/**
* @ingroup iot_io
*
* GPIO_3 pin function.CNcomment:GPIO_3CNend
*/
typedef enum {
IOT_IO_FUNC_GPIO_3_GPIO,
IOT_IO_FUNC_GPIO_3_UART0_TXD,
IOT_IO_FUNC_GPIO_3_UART1_CTS_N,
IOT_IO_FUNC_GPIO_3_SPI1_CSN,
IOT_IO_FUNC_GPIO_3_JTAG_TDI,
IOT_IO_FUNC_GPIO_3_PWM5_OUT,
IOT_IO_FUNC_GPIO_3_I2C1_SDA,
IOT_IO_FUNC_GPIO_3_SSI_DATA,
} IotIoFuncGpio3;
/**
* @ingroup iot_io
*
* GPIO_4 pin function.CNcomment:GPIO_4CNend
*/
typedef enum {
IOT_IO_FUNC_GPIO_4_GPIO,
IOT_IO_FUNC_GPIO_4_UART0_RXD = 2,
IOT_IO_FUNC_GPIO_4_JTAG_TMS = 4,
IOT_IO_FUNC_GPIO_4_PWM1_OUT,
IOT_IO_FUNC_GPIO_4_I2C1_SCL,
} IotIoFuncGpio4;
/**
* @ingroup iot_io
*
* GPIO_5 pin function.CNcomment:GPIO_5CNend
*/
typedef enum {
IOT_IO_FUNC_GPIO_5_GPIO,
IOT_IO_FUNC_GPIO_5_UART1_RXD = 2,
IOT_IO_FUNC_GPIO_5_SPI0_CSN,
IOT_IO_FUNC_GPIO_5_PWM2_OUT = 5,
IOT_IO_FUNC_GPIO_5_I2S0_MCLK,
IOT_IO_FUNC_GPIO_5_BT_STATUS,
} IotIoFuncGpio5;
/**
* @ingroup iot_io
*
* GPIO_6 pin function.CNcomment:GPIO_6CNend
*/
typedef enum {
IOT_IO_FUNC_GPIO_6_GPIO,
IOT_IO_FUNC_GPIO_6_UART1_TXD = 2,
IOT_IO_FUNC_GPIO_6_SPI0_CK,
IOT_IO_FUNC_GPIO_6_PWM3_OUT = 5,
IOT_IO_FUNC_GPIO_6_I2S0_TX,
IOT_IO_FUNC_GPIO_6_COEX_SWITCH,
} IotIoFuncGpio6;
/**
* @ingroup iot_io
*
* GPIO_7 pin function.CNcomment:GPIO_7CNend
*/
typedef enum {
IOT_IO_FUNC_GPIO_7_GPIO,
IOT_IO_FUNC_GPIO_7_UART1_CTS_N = 2,
IOT_IO_FUNC_GPIO_7_SPI0_RXD,
IOT_IO_FUNC_GPIO_7_PWM0_OUT = 5,
IOT_IO_FUNC_GPIO_7_I2S0_BCLK,
IOT_IO_FUNC_GPIO_7_BT_ACTIVE,
} IotIoFuncGpio7;
/**
* @ingroup iot_io
*
* GPIO_8 pin function.CNcomment:GPIO_8CNend
*/
typedef enum {
IOT_IO_FUNC_GPIO_8_GPIO,
IOT_IO_FUNC_GPIO_8_UART1_RTS_N = 2,
IOT_IO_FUNC_GPIO_8_SPI0_TXD,
IOT_IO_FUNC_GPIO_8_PWM1_OUT = 5,
IOT_IO_FUNC_GPIO_8_I2S0_WS,
IOT_IO_FUNC_GPIO_8_WLAN_ACTIVE,
} IotIoFuncGpio8;
/**
* @ingroup iot_io
*
* GPIO_9 pin function.CNcomment:GPIO_9CNend
*/
typedef enum {
IOT_IO_FUNC_GPIO_9_GPIO,
IOT_IO_FUNC_GPIO_9_I2C0_SCL,
IOT_IO_FUNC_GPIO_9_UART2_RTS_N,
IOT_IO_FUNC_GPIO_9_SDIO_D2,
IOT_IO_FUNC_GPIO_9_SPI0_TXD,
IOT_IO_FUNC_GPIO_9_PWM0_OUT,
IOT_IO_FUNC_GPIO_9_I2S0_MCLK = 7,
} IotIoFuncGpio9;
/**
* @ingroup iot_io
*
* GPIO_10 pin function.CNcomment:GPIO_10CNend
*/
typedef enum {
IOT_IO_FUNC_GPIO_10_GPIO,
IOT_IO_FUNC_GPIO_10_I2C0_SDA,
IOT_IO_FUNC_GPIO_10_UART2_CTS_N,
IOT_IO_FUNC_GPIO_10_SDIO_D3,
IOT_IO_FUNC_GPIO_10_SPI0_CK,
IOT_IO_FUNC_GPIO_10_PWM1_OUT,
IOT_IO_FUNC_GPIO_10_I2S0_TX = 7,
} IotIoFuncGpio10;
/**
* @ingroup iot_io
*
* GPIO_11 pin function.CNcomment:GPIO_11CNend
*/
typedef enum {
IOT_IO_FUNC_GPIO_11_GPIO,
IOT_IO_FUNC_GPIO_11_UART2_TXD = 2,
IOT_IO_FUNC_GPIO_11_SDIO_CMD,
IOT_IO_FUNC_GPIO_11_SPI0_RXD,
IOT_IO_FUNC_GPIO_11_PWM2_OUT,
IOT_IO_FUNC_GPIO_11_RF_TX_EN_EXT,
IOT_IO_FUNC_GPIO_11_I2S0_RX,
} IotIoFuncGpio11;
/**
* @ingroup iot_io
*
* GPIO_12 pin function.CNcomment:GPIO_12CNend
*/
typedef enum {
IOT_IO_FUNC_GPIO_12_GPIO,
IOT_IO_FUNC_GPIO_12_UART2_RXD = 2,
IOT_IO_FUNC_GPIO_12_SDIO_CLK,
IOT_IO_FUNC_GPIO_12_SPI0_CSN,
IOT_IO_FUNC_GPIO_12_PWM3_OUT,
IOT_IO_FUNC_GPIO_12_RF_RX_EN_EXT,
IOT_IO_FUNC_GPIO_12_I2S0_BCLK,
} IotIoFuncGpio12;
/**
* @ingroup iot_io
*
* GPIO_13 pin function.CNcomment:GPIO_13CNend
*/
typedef enum {
IOT_IO_FUNC_GPIO_13_SSI_DATA,
IOT_IO_FUNC_GPIO_13_UART0_TXD,
IOT_IO_FUNC_GPIO_13_UART2_RTS_N,
IOT_IO_FUNC_GPIO_13_SDIO_D0,
IOT_IO_FUNC_GPIO_13_GPIO,
IOT_IO_FUNC_GPIO_13_PWM4_OUT,
IOT_IO_FUNC_GPIO_13_I2C0_SDA,
IOT_IO_FUNC_GPIO_13_I2S0_WS,
} IotIoFuncGpio13;
/**
* @ingroup iot_io
*
* GPIO_14 pin function.CNcomment:GPIO_14CNend
*/
typedef enum {
IOT_IO_FUNC_GPIO_14_SSI_CLK,
IOT_IO_FUNC_GPIO_14_UART0_RXD,
IOT_IO_FUNC_GPIO_14_UART2_CTS_N,
IOT_IO_FUNC_GPIO_14_SDIO_D1,
IOT_IO_FUNC_GPIO_14_GPIO,
IOT_IO_FUNC_GPIO_14_PWM5_OUT,
IOT_IO_FUNC_GPIO_14_I2C0_SCL,
} IotIoFuncGpio14;
/**
* @ingroup iot_io
*
* SFC_CSN pin function.CNcomment:SFC_CSNCNend
*/
typedef enum {
IOT_IO_FUNC_SFC_CSN_SFC_CSN,
IOT_IO_FUNC_SFC_CSN_SDIO_D2,
IOT_IO_FUNC_SFC_CSN_GPIO9,
IOT_IO_FUNC_SFC_CSN_SPI0_TXD = 4,
} IotIoFuncSfcCsn;
/**
* @ingroup iot_io
*
* SFC_DO pin function.CNcomment:SFC_DOCNend
*/
typedef enum {
IOT_IO_FUNC_SFC_IO_1_SFC_DO,
IOT_IO_FUNC_SFC_IO_1_SDIO_D3,
IOT_IO_FUNC_SFC_IO_1_GPIO10,
IOT_IO_FUNC_SFC_IO_1_SPI0_CK = 4,
} IotIoFuncSfcIo1;
/**
* @ingroup iot_io
*
* SFC_WPN pin function.CNcomment:SFC_WPNCNend
*/
typedef enum {
IOT_IO_FUNC_SFC_IO_2_SFC_WPN,
IOT_IO_FUNC_SFC_IO_2_SDIO_CMD,
IOT_IO_FUNC_SFC_IO_2_GPIO11,
IOT_IO_FUNC_SFC_IO_2_RF_TX_EN_EXT,
IOT_IO_FUNC_SFC_IO_2_SPI0_RXD,
} IotIoFuncSfcIo2;
/**
* @ingroup iot_io
*
* SFC_DI pin function.CNcomment:SFC_DICNend
*/
typedef enum {
IOT_IO_FUNC_SFC_IO_0_SFC_DI,
IOT_IO_FUNC_SFC_IO_0_SDIO_CLK,
IOT_IO_FUNC_SFC_IO_0_GPIO12,
IOT_IO_FUNC_SFC_IO_0_RF_RX_EN_EXT,
IOT_IO_FUNC_SFC_IO_0_SPI0_CSN,
} IotIoFuncSfcIo0;
/**
* @ingroup iot_io
*
* SFC_CLK pin function.CNcomment:SFC_CLKCNend
*/
typedef enum {
IOT_IO_FUNC_SFC_CLK_SFC_CLK,
IOT_IO_FUNC_SFC_CLK_SDIO_D0,
IOT_IO_FUNC_SFC_CLK_GPIO13,
IOT_IO_FUNC_SFC_CLK_SSI_DATA = 4,
} IotIoFuncSfcClk;
/**
* @ingroup iot_io
*
* SFC_HOLDN pin function.CNcomment:SFC_HOLDNCNend
*/
typedef enum {
IOT_IO_FUNC_SFC_IO_3_SFC_HOLDN,
IOT_IO_FUNC_SFC_IO_3_SDIO_D1,
IOT_IO_FUNC_SFC_IO_3_GPIO14,
IOT_IO_FUNC_SFC_IO_3_SSI_CLK = 4,
} IotIoFuncSfcIo3;
/**
* @ingroup iot_io
*
* I/O drive capability.CNcomment:IOCNend
* Note: The HI_IO_NAME_GPIO_0~HI_IO_NAME_GPIO_11 and HI_IO_NAME_GPIO_13~HI_IO_NAME_GPIO_14 driver capabilities are
* optional.The value range is HI_IO_DRIVER_STRENGTH_0~HI_IO_DRIVER_STRENGTH_3, and the other I/O ranges are
* HI_IO_DRIVER_STRENGTH_0~HI_IO_DRIVER_STRENGTH_7.CNcomment::HI_IO_NAME_GPIO_0~HI_IO_NAME_GPIO_11
* HI_IO_NAME_GPIO_13~HI_IO_NAME_GPIO_14HI_IO_DRIVER_STRENGTH_0~HI_IO_DRIVER_STRENGTH_3
* IOHI_IO_DRIVER_STRENGTH_0~HI_IO_DRIVER_STRENGTH_7CNend
*/
typedef enum {
IOT_IO_DRIVER_STRENGTH_0 = 0, /* <Drive strength level 0 (highest).CNcomment:驱动能力0级驱动能力最高CNend */
IOT_IO_DRIVER_STRENGTH_1, /* <Drive strength level 1.CNcomment:驱动能力1级CNend */
IOT_IO_DRIVER_STRENGTH_2, /* <Drive strength level 2.CNcomment:驱动能力2级CNend */
IOT_IO_DRIVER_STRENGTH_3, /* <Drive strength level 3.CNcomment:驱动能力3级CNend */
IOT_IO_DRIVER_STRENGTH_4, /* <Drive strength level 4.CNcomment:驱动能力4级CNend */
IOT_IO_DRIVER_STRENGTH_5, /* <Drive strength level 5.CNcomment:驱动能力5级CNend */
IOT_IO_DRIVER_STRENGTH_6, /* <Drive strength level 6.CNcomment:驱动能力6级CNend */
IOT_IO_DRIVER_STRENGTH_7, /* <Drive strength level 7 (lowest).CNcomment:驱动能力7级驱动能力最低CNend */
IOT_IO_DRIVER_STRENGTH_MAX,
} IotIoDriverStrength;
unsigned int IoSetPull(unsigned int id, IotIoPull val);
unsigned int IoSetFunc(unsigned int id, unsigned char val);
unsigned int TaskMsleep(unsigned int ms);
#endif
/** @} */

@ -0,0 +1,22 @@
# Copyright (c) 2020-2022 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.
static_library("led_example") {
sources = [ "led_example.c" ]
include_dirs = [
"//utils/native/lite/include",
"//kernel/liteos_m/kal/cmsis",
"//base/iot_hardware/peripheral/interfaces/kits",
]
}

@ -0,0 +1,83 @@
/*
* Copyright (c) 2020-2022 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.
*/
#include <stdio.h>
#include <unistd.h>
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_gpio.h"
#define LED_INTERVAL_TIME_US 300000
#define LED_TASK_STACK_SIZE 512
#define LED_TASK_PRIO 25
#define LED_TEST_GPIO 9 // for hispark_pegasus
enum LedState {
LED_ON = 0,
LED_OFF,
LED_SPARK,
};
enum LedState g_ledState = LED_SPARK;
static void *LedTask(const char *arg)
{
(void)arg;
while (1) {
switch (g_ledState) {
case LED_ON:
IoTGpioSetOutputVal(LED_TEST_GPIO, 1);
usleep(LED_INTERVAL_TIME_US);
break;
case LED_OFF:
IoTGpioSetOutputVal(LED_TEST_GPIO, 0);
usleep(LED_INTERVAL_TIME_US);
break;
case LED_SPARK:
IoTGpioSetOutputVal(LED_TEST_GPIO, 0);
usleep(LED_INTERVAL_TIME_US);
IoTGpioSetOutputVal(LED_TEST_GPIO, 1);
usleep(LED_INTERVAL_TIME_US);
break;
default:
usleep(LED_INTERVAL_TIME_US);
break;
}
}
return NULL;
}
static void LedExampleEntry(void)
{
osThreadAttr_t attr;
IoTGpioInit(LED_TEST_GPIO);
IoTGpioSetDir(LED_TEST_GPIO, IOT_GPIO_DIR_OUT);
attr.name = "LedTask";
attr.attr_bits = 0U;
attr.cb_mem = NULL;
attr.cb_size = 0U;
attr.stack_mem = NULL;
attr.stack_size = LED_TASK_STACK_SIZE;
attr.priority = LED_TASK_PRIO;
if (osThreadNew((osThreadFunc_t)LedTask, NULL, &attr) == NULL) {
printf("[LedExample] Failed to create LedTask!\n");
}
}
SYS_RUN(LedExampleEntry);

@ -0,0 +1,40 @@
# Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
# 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.
static_library("AppDemoIot") {
sources = [
"app_demo_iot.c",
"cjson_init.c",
"iot_hmac.c",
"iot_log.c",
"iot_main.c",
"iot_profile.c",
"iot_sta.c",
"hal_iot_gpio_ex.c",
]
include_dirs = [
"./",
"//utils/native/lite/include",
"//kernel/liteos_m/kal/cmsis",
"//base/iot_hardware/peripheral/interfaces/kits",
"//device/soc/hisilicon/hi3861v100/sdk_liteos/third_party/lwip_sack/include/lwip",
"//third_party/cJSON",
"//device/soc/hisilicon/hi3861v100/sdk_liteos/third_party/mbedtls/include/mbedtls",
"//foundation/communication/wifi_lite/interfaces/wifiservice",
"//device/soc/hisilicon/hi3861v100/sdk_liteos/third_party/paho.mqtt.c/include/mqtt",
"//device/soc/hisilicon/hi3861v100/sdk_liteos/third_party/libcoap/include/coap2",
]
defines = [ "WITH_LWIP" ]
}

@ -0,0 +1,226 @@
# 腾讯云的微信小程序开发及Hi3861板端互联
## 硬件环境搭建
- 硬件要求Hi3861V100核心板、扩展板硬件搭建如下图所示。
- [Hi3861V100核心板参考HiSpark_WiFi_IoT智能开发套件_原理图硬件资料\原理图\HiSpark_WiFi-IoT_Hi3861_CH340G_VER.B.pdf](http://gitee.com/hihope_iot/embedded-race-hisilicon-track-2022/blob/master/%E7%A1%AC%E4%BB%B6%E8%B5%84%E6%96%99/HiSpark_WiFi_IoT%E6%99%BA%E8%83%BD%E5%AE%B6%E5%B1%85%E5%BC%80%E5%8F%91%E5%A5%97%E4%BB%B6_%E5%8E%9F%E7%90%86%E5%9B%BE.rar)
- [扩展板参考HiSpark_WiFi_IoT智能开发套件_原理图硬件资料\原理图\HiSpark_WiFi-IoT_Hi3861_CH340G_VER.B.pdf](http://gitee.com/hihope_iot/embedded-race-hisilicon-track-2022/blob/master/%E7%A1%AC%E4%BB%B6%E8%B5%84%E6%96%99/HiSpark_WiFi_IoT%E6%99%BA%E8%83%BD%E5%AE%B6%E5%B1%85%E5%BC%80%E5%8F%91%E5%A5%97%E4%BB%B6_%E5%8E%9F%E7%90%86%E5%9B%BE.rar)
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/260.jpg)
## 软件介绍
- 1.代码目录结构及相应接口功能介绍
```
vendor_hisilicon/hispark_pegasus/demo/iottencent_demo
├── app_demo_iot.c #IoSetPull();IoSetFunc();TaskMsleep()。
├── BUILD.gn # BUILD.gn文件由三部分内容目标、源文件、头文件路径构成,开发者根据需要填写,static_library中指定业务模块的编译结果为静态库文件led_example开发者根据实际情况完成填写。
| sources中指定静态库.a所依赖的.c文件及其路径若路径中包含"//"则表示绝对路径(此处为代码根路径),若不包含"//"则表示相对路径。include_dirs中指定source所需要依赖的.h文件路径。
├── cjson_init.c #
├── iot_config.h #
├── iot_hmac.c #
├── iot_hmac.h #
├── iot_log.c #
├── iot_log.h #
├── iot_main.c #
├── iot_main.h #
├── iot_profile.c #
├── iot_sta.c #
└── iot_profile.h #
```
- 2.Mqtt协议第三方软件与腾讯云之间的通信
2.1 浏览器搜索腾讯云,在腾讯云界面创建产品和设备,登录腾讯云后搜索“物联网通信”,进入页面后,物联网通信选择立即使用。进入页面后,选择产品列表栏->创建新产品->产品名称xxx,认证方式:密钥认证,点击确定。
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8717.png)
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8720.png)
2.2 在产品列表栏进入刚刚创建的新产品->设备列表->添加设备->创建新设备:设备名称,设备备注(选填),使用物联网通信提供密钥->保存->复制保存生成的密钥->开始管理设备(可以看到设备相应信息)。
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8721.png)
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8722.png)
2.3 添加设备,同时查看设备相应信息。
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%BE%AE%E4%BF%A1%E5%B0%8F%E7%A8%8B%E5%BA%8F/800.png)
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%BE%AE%E4%BF%A1%E5%B0%8F%E7%A8%8B%E5%BA%8F/801.png)
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%BE%AE%E4%BF%A1%E5%B0%8F%E7%A8%8B%E5%BA%8F/802.png)
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%BE%AE%E4%BF%A1%E5%B0%8F%E7%A8%8B%E5%BA%8F/803.png)
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%BE%AE%E4%BF%A1%E5%B0%8F%E7%A8%8B%E5%BA%8F/804.png)
2.4 返回设备列表可以看到设备并未激活,接下来激活设备;下载[MQTT.fx-1.7.1 ](https://www.jensd.de/wordpress/?p=2746)下载完成后打开工具点击设备图标进入到设备界面配置ClientIDusername,password 等参数。
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%BE%AE%E4%BF%A1%E5%B0%8F%E7%A8%8B%E5%BA%8F/806.png)
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8730.png)
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8731.png)
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8732.png)
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8733.png)
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8734.png)
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8735.png)
2.5 完成2.3步骤后可以在腾讯云设备列表里面看到设备状态显示已激活开始腾讯云与MQTT工具之间的通信。
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8736.png)
2.6 MQTT.fx-1.7.1工具订阅腾讯云的topic腾讯云下发指令。
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8737.png)
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8738.png)
2.7 在腾讯云网页端点击“在线调试”。
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8739.png)
2.8 可以在MQTT.fx-1.7.1工具中看到腾讯云网页端发过来的消息。
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8740.png)
2.9 MQTT.fx-1.7.1工具发布腾讯云到的topic在设备影子中查看发布到腾讯云的消息。
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8741.png)
```
{
"type":"update",
"state":{
"reported":{
"light":1,
"motor":1,
"temperature":25,
"humidity":60,
"light_intensity":50
}
},
"version":0,
"clientToken":"clientToken"
}
```
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8742.png)
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8743.png)
- 3.微信小程序开发环境搭建及与腾讯云之间通信
3.1 注册申请小程序账号https://mp.weixin.qq.com/wxopen/waregister?action=step1。
3.2 登录小程序后选择IOT字样的账号在“开发”->“开发设置”页面可以看到小程序的AppID如下图所示详情请查看微信官方文档
https://developers.weixin.qq.com/miniprogram/dev/framework/quickstart/getstart.html#%E7%94%B3%E8%AF%B7%E5%B8%90%E5%8F%B7。
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8744.png)
3.3 开发者工具下载与安装https://developers.weixin.qq.com/miniprogram/dev/devtools/download.html。
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8745.png)
3.4 下载安装完成后,打开微信开发工具,导入提供的微信小程序软件包[获取微信小程序代码](https://gitee.com/leo593362220/Hi3861OpenHarmony)。并填入自己的APPID,后端服务选择微信云开发。
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%87102.jpg)
3.5 使用微信开发者工具打开工程后需要修改project.config.json文件中appid,projectname修改成自己的。
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8747.png)
3.6 获取secretId和secretKey在腾讯云->产品列表->搜索栏搜索访问密钥->访问密钥->继续使用->可以看到secretId和secretKey复制在xxxx.txt文件后面需要。
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8749.png)
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8750.png)
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8751.png)
3.7 环境ID配置并获取环境ID,复制在xxx.txt文件后面需要。
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8752.png)
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8753.png)
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8754.png)
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8755.png)![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8747.png)
3.8 需要修改app.js文件中productId腾讯云上设备信息上产品ID,deviceName腾讯云上设备信息上产品名称,secretId和secretKey(3.6步骤获取到的secretId和secretKey)env3.7步骤获取到的环境ID
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8748.png)
3.9 配置当前云环境
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8756.png)
注意:第一次部署环境,图片里面的上传并部署会变成新建并部署。
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8757.png)
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/228.jpg)
等待大概1分钟左右直到出现上传云函数成功注意上传并部署由于网络问题可能会失败看到上传云函数等字样代表上传部署成功这里以iothub-publish为例
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8758.png)
3.10 环境部署完成后,点击编译,然后真机调试会出现如下界面,上面两个都要出现
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8761.png)
- 4.Hi3861V100与微信小程序之间通信
- 将源码./vendor/hisilicon/hispark_pegasus/demo目录下的iottencent_demo整个文件夹及内容复制到源码./applications/sample/wifi-iot/app/下。
```
.
└── applications
└── sample
└── wifi-iot
└── app
└──iottencent_demo
└── 代码
```
- 配置源码./applications/sample/wifi-iot/app/iottencent_demo/iot_config.h中CONFIG_AP_SSIDCONFIG_AP_PWD为WiFi名称和WiFi密码。CONFIG_USER_ID为腾讯云设备信息上MQTT UsernameCONFIG_USER_PWD为腾讯云上设备的MQTT Password,CN_CLIENTID为腾讯云上clientID。
```
#define CONFIG_AP_SSID "XXXXXXXX" // WIFI SSID
#define CONFIG_AP_PWD "XXXXX" // WIFI PWD
/* Tencent iot Cloud user ID , password */
#define CONFIG_USER_ID "XXXXXXXXXXXXX"
#define CONFIG_USER_PWD "XXXXXXXXXXXX"
#define CN_CLIENTID "xxxxxxxx" // Tencent cloud ClientID format: Product ID + device name
```
- 更改源码./applications/sample/wifi-iot/app/iottencent_demo/iot_main.c文件中搜索g_defaultSubscribeTopic字段将腾讯云上的Topic列表中自定义Topic添加到字段里。
```
static const char *g_defaultSubscribeTopic[] = {
"76VQ4ZASTL/mqtt/data",
"76VQ4ZASTL/mqtt/event",
"76VQ4ZASTL/mqtt/control",
};
```
- 更改源码./applications/sample/wifi-iot/app/iottencent_demo/iot_profile.c文件中搜索CN_PROFILE_TOPICFMT_TOPIC字段将腾讯云上的产品名设备名称添加到字段里。
```
#define CN_PROFILE_TOPICFMT_TOPIC "$shadow/operation/xxxxx/XXXX" //xxxx为产品名和设备名称76VQ4ZASTL
```
- 修改源码./applications/sample/wifi-iot/app/BUILD.gn文件在features字段中增加索引使目标模块参与编译。features字段指定业务模块的路径和目标,features字段配置如下。
```
import("//build/lite/config/component/lite_component.gni")
lite_component("app") {
features = [
"iottencent_demo:appDemoIot",
]
}
```
- 工程相关配置完成后,然后编译。
- 5.烧录
- 编译成功后点击DevEco Home->配置工程->hi3861->upload_port->选择对应串口端口号->选择upload_protocol->选择hiburn-serial->点击save保存在保存成功后点击upload进行烧录出现connecting, please reset device..字样复位开发板等待烧录完成。烧录成功后再次点击Hi3861核心板上的“RST”复位键此时开发板的系统会运行起来。
- 注意:一定要断开MQTT工具的连接。
- 微信小程序上选择已连接Wifi,跳过配网->云端互联->看到设备互联界面->点击刷新按钮,运行结果出现如下图代表成功,点击照明,主板灯会亮。
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8762.png)

@ -0,0 +1,259 @@
/*
* Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
* 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.
*/
#include <hi_task.h>
#include <string.h>
#include <hi_wifi_api.h>
#include <hi_mux.h>
#include <hi_io.h>
#include <hi_gpio.h>
#include "iot_config.h"
#include "iot_log.h"
#include "iot_main.h"
#include "iot_profile.h"
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_gpio.h"
/* attribute initiative to report */
#define TAKE_THE_INITIATIVE_TO_REPORT
#define TWO_SECOND (2000)
/* oc request id */
#define CN_COMMADN_INDEX "commands/request_id="
#define WECHAT_SUBSCRIBE_control "chosen_slot"
#define WECHAT_SUBSCRIBE_channel1 "slot_1"
#define WECHAT_SUBSCRIBE_channel2 "slot_2"
#define WECHAT_SUBSCRIBE_channel3 "slot_3"
#define WECHAT_SUBSCRIBE_channel4 "slot_4"
#define topic_data "YT32IOSCAL/Hi38611_mqtt/data"
#define topic_event "YT32IOSCAL/Hi38611_mqtt/event"
#define topic_control "YT32IOSCAL/Hi38611_mqtt/control"
int g_ligthStatus = -1;
int slot1 = 20,slot2 = 20, slot3 = 20, slot4 = 20;
typedef void (*FnMsgCallBack)(hi_gpio_value val);
typedef struct FunctionCallback {
hi_bool stop;
hi_u32 conLost;
hi_u32 queueID;
hi_u32 iotTaskID;
FnMsgCallBack msgCallBack;
}FunctionCallback;
FunctionCallback g_functinoCallback;
/* CPU Sleep time Set */
unsigned int TaskMsleep(unsigned int ms)
{
if (ms <= 0) {
return HI_ERR_FAILURE;
}
return hi_sleep((hi_u32)ms);
}
static void DeviceConfigInit(hi_gpio_value val)
{
hi_io_set_func(HI_IO_NAME_GPIO_9, HI_IO_FUNC_GPIO_9_GPIO);
hi_gpio_set_dir(HI_GPIO_IDX_9, HI_GPIO_DIR_OUT);
hi_gpio_set_ouput_val(HI_GPIO_IDX_9, val);
}
static void engine_control(unsigned int IO){
IoTGpioInit(IO);
IoSetFunc(IO, 0);
IoTGpioSetDir(IO, IOT_GPIO_DIR_OUT);
IoTGpioSetOutputVal(IO, IOT_GPIO_VALUE1);
IOT_LOG_DEBUG("Engine at GPIO:%u started!", IO);
hi_udelay(20000);
IoTGpioSetOutputVal(IO, IOT_GPIO_VALUE0);
IOT_LOG_DEBUG("Engine at GPIO:%u stopped!", IO);
}
static void engine_start(unsigned int IO){
IoSetFunc(IO, 0);
IoTGpioSetDir(IO, IOT_GPIO_DIR_OUT);
IoTGpioSetOutputVal(IO, IOT_GPIO_VALUE1);
IOT_LOG_DEBUG("Engine at GPIO:%u started!", IO);
}
static void engine_stop(unsigned int IO){
IoSetFunc(IO, 0);
IoTGpioSetDir(IO, IOT_GPIO_DIR_OUT);
IoTGpioSetOutputVal(IO, IOT_GPIO_VALUE0);
IOT_LOG_DEBUG("Engine at GPIO:%u stopped!", IO);
}
static void engine_reinit(unsigned int IO){
IoTGpioInit(IO);
IoSetFunc(IO, 0);
IoTGpioSetDir(IO, IOT_GPIO_DIR_OUT);
IoTGpioSetOutputVal(IO, IOT_GPIO_VALUE0);
IOT_LOG_DEBUG("Engine at GPIO:%u initialized!", IO);
}
static void all_engine_reinit(){
engine_reinit(6);
engine_reinit(7);
engine_reinit(9);
engine_reinit(10);
IOT_LOG_DEBUG("All engines initialized!");
}
static int DeviceMsgCallback(FnMsgCallBack msgCallBack)
{
g_functinoCallback.msgCallBack = msgCallBack;
return 0;
}
static void wechatControlDeviceMsg(hi_gpio_value val)
{
DeviceConfigInit(val);
}
// < this is the callback function, set to the mqtt, and if any messages come, it will be called
// < The payload here is the json string
static void DemoMsgRcvCallBack(int qos, const char *topic, const char *payload)/*定义3861接收到json文件后的操作*/
{
IOT_LOG_DEBUG("RCVMSG:QOS:%d TOPIC:%s PAYLOAD:%s\r\n", qos, topic, payload);
int IO = 0;
/* 云端下发命令后,板端的操作处理 */
//if (strcmp(topic, topic_data)==0){
if (strstr(payload, WECHAT_SUBSCRIBE_control) != NULL) {
all_engine_reinit();
if (strstr(payload, WECHAT_SUBSCRIBE_channel1) != NULL) {
engine_start(6);
hi_udelay(4000000);
engine_stop(6);
slot1--;
wechatControlDeviceMsg(HI_GPIO_VALUE1);
}
else if (strstr(payload, WECHAT_SUBSCRIBE_channel2) != NULL) {
engine_start(7);
hi_udelay(4000000);
engine_stop(7);
slot2--;
wechatControlDeviceMsg(HI_GPIO_VALUE1);
}
else if (strstr(payload, WECHAT_SUBSCRIBE_channel3) != NULL) {
engine_start(2);
hi_udelay(4000000);
engine_stop(2);
slot3--;
wechatControlDeviceMsg(HI_GPIO_VALUE1);
}
else if (strstr(payload, WECHAT_SUBSCRIBE_channel4) != NULL) {
engine_start(10);
hi_udelay(4000000);
engine_stop(10);
slot4--;
wechatControlDeviceMsg(HI_GPIO_VALUE1);
}
}
//}
return HI_NULL;
}
/* publish sample */
hi_void IotPublishSample(int slot1, int slot2, int slot3, int slot4)
{
/* reported attribute */
WeChatProfile weChatProfile = {
.subscribeType = "type",
.status.subState = "state",
.status.subReport = "reported",
.status.reportVersion = "version",
.status.Token = "clientToken",
/* report motor */
.reportAction.subDeviceActionMotor = "slot_1",
.reportAction.motorActionStatus = slot1, /* 0 : motor off */
/* report temperature */
.reportAction.subDeviceActionTemperature = "slot_2",
.reportAction.temperatureData = slot2, /* 30 :temperature data */
/* report humidity */
.reportAction.subDeviceActionHumidity = "slot_3",
.reportAction.humidityActionData = slot3, /* humidity data */
/* report light_intensity */
.reportAction.subDeviceActionLightIntensity = "slot_4",
.reportAction.lightIntensityActionData = slot4, /* 60 : light_intensity */
};
/* report light */
if (g_ligthStatus == HI_TRUE) {
weChatProfile.reportAction.subDeviceActionLight = "light";
weChatProfile.reportAction.lightActionStatus = 1; /* 1: light on */
} else if (g_ligthStatus == HI_FALSE) {
weChatProfile.reportAction.subDeviceActionLight = "light";
weChatProfile.reportAction.lightActionStatus = 0; /* 0: light off */
} else {
weChatProfile.reportAction.subDeviceActionLight = "light";
weChatProfile.reportAction.lightActionStatus = 0; /* 0: light off */
}
/* profile report */
IoTProfilePropertyReport(CONFIG_USER_ID, &weChatProfile);
}
// < this is the demo main task entry,here we will set the wifi/cjson/mqtt ready and
// < wait if any work to do in the while
static hi_void *DemoEntry(const char *arg)
{
WifiStaReadyWait();
cJsonInit();
IoTMain();
/* 云端下发回调 */
IoTSetMsgCallback(DemoMsgRcvCallBack);
/* 主动上报 */
#ifdef TAKE_THE_INITIATIVE_TO_REPORT
while (1) {
/* 用户可以在这调用发布函数进行发布,需要用户自己写调用函数 */
IotPublishSample(slot1,slot2,slot3,slot4); // 发布例程
#endif
TaskMsleep(TWO_SECOND);
}
return NULL;
}
// < This is the demo entry, we create a task here,
// and all the works has been done in the demo_entry
#define CN_IOT_TASK_STACKSIZE 0x1000
#define CN_IOT_TASK_PRIOR 25
#define CN_IOT_TASK_NAME "IOTDEMO"
static void AppDemoIot(void)
{
osThreadAttr_t attr;
IoTWatchDogDisable();
attr.name = "IOTDEMO";
attr.attr_bits = 0U;
attr.cb_mem = NULL;
attr.cb_size = 0U;
attr.stack_mem = NULL;
attr.stack_size = CN_IOT_TASK_STACKSIZE;
attr.priority = CN_IOT_TASK_PRIOR;
if (osThreadNew((osThreadFunc_t)DemoEntry, NULL, &attr) == NULL) {
printf("[mqtt] Falied to create IOTDEMO!\n");
}
}
SYS_RUN(AppDemoIot);

@ -0,0 +1,38 @@
/*
* Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
* 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.
*/
#include <stdint.h>
#include <cJSON.h>
#include <hi_mem.h>
static void *cJsonMalloc(size_t sz)
{
return hi_malloc(0, sz);
}
static void cJsonFree(const char *p)
{
hi_free(0, p);
}
void cJsonInit(void)
{
cJSON_Hooks hooks;
hooks.malloc_fn = cJsonMalloc;
hooks.free_fn = cJsonFree;
cJSON_InitHooks(&hooks);
return;
}

@ -0,0 +1,46 @@
/*
* Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
* 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.
*/
#include "iot_errno.h"
#include "iot_gpio_ex.h"
#include "hi_gpio.h"
#include "hi_io.h"
#include "hi_task.h"
#include "hi_types_base.h"
unsigned int IoSetPull(unsigned int id, IotIoPull val)
{
if (id >= HI_GPIO_IDX_MAX) {
return IOT_FAILURE;
}
return hi_io_set_pull((hi_io_name)id, (hi_io_pull)val);
}
unsigned int IoSetFunc(unsigned int id, unsigned char val)
{
if (id >= HI_GPIO_IDX_MAX) {
return IOT_FAILURE;
}
return hi_io_set_func((hi_io_name)id, val);
}
/*unsigned int TaskMsleep(unsigned int ms)
{
if (ms <= 0) {
return IOT_FAILURE;
}
return hi_sleep((hi_u32)ms);
}*/

@ -0,0 +1,31 @@
/*
* Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
* 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 IOT_CONFIG_H
#define IOT_CONFIG_H
// <CONFIG THE LOG
/* if you need the iot log for the development , please enable it, else please comment it */
#define CONFIG_LINKLOG_ENABLE 1
// < CONFIG THE WIFI
/* Please modify the ssid and pwd for the own */
#define CONFIG_AP_SSID "Sidi_iPhone" // WIFI SSID
#define CONFIG_AP_PWD "12345678" // WIFI PWD
/* Tencent iot Cloud user ID , password */
#define CONFIG_USER_ID "YT32IOSCALHi38611_mqtt;12010126;41883;1663689600"
#define CONFIG_USER_PWD "b4168d5d4b65898e6984346c81ad13e1b3f112ab7ce46f65cf29455f4c9e18e8;hmacsha256"
#define CN_CLIENTID "YT32IOSCALHi38611_mqtt" // Tencent cloud ClientID format: Product ID + device name
#endif

@ -0,0 +1,398 @@
/*
* Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
* 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.
*/
/**
* @file iot_gpio_ex.h
*
* @brief Declares the extended GPIO interface functions.
*
* These functions are used for settings GPIO pulls and driver strength. \n
*
* @since 1.0
* @version 1.0
*/
#ifndef IOT_GPIO_EX_H
#define IOT_GPIO_EX_H
/**
* @brief Enumerates GPIO pull-up or pull-down settings.
*/
typedef enum {
/** No pull */
IOT_IO_PULL_NONE,
/** Pull-up */
IOT_IO_PULL_UP,
/** Pull-down */
IOT_IO_PULL_DOWN,
/** Maximum value */
IOT_IO_PULL_MAX,
} IotIoPull;
/**
* @ingroup iot_io
*
* GPIO pin ID. CNcomment:IOCNend
*/
typedef enum {
IOT_IO_NAME_GPIO_0, /* <GPIO0 */
IOT_IO_NAME_GPIO_1, /* <GPIO1 */
IOT_IO_NAME_GPIO_2, /* <GPIO2 */
IOT_IO_NAME_GPIO_3, /* <GPIO3 */
IOT_IO_NAME_GPIO_4, /* <GPIO4 */
IOT_IO_NAME_GPIO_5, /* <GPIO5 */
IOT_IO_NAME_GPIO_6, /* <GPIO6 */
IOT_IO_NAME_GPIO_7, /* <GPIO7 */
IOT_IO_NAME_GPIO_8, /* <GPIO8 */
IOT_IO_NAME_GPIO_9, /* <GPIO9 */
IOT_IO_NAME_GPIO_10, /* <GPIO10 */
IOT_IO_NAME_GPIO_11, /* <GPIO11 */
IOT_IO_NAME_GPIO_12, /* <GPIO12 */
IOT_IO_NAME_GPIO_13, /* <GPIO13 */
IOT_IO_NAME_GPIO_14, /* <GPIO14 */
IOT_IO_NAME_SFC_CSN, /* <SFC_CSN */
IOT_IO_NAME_SFC_IO1, /* <SFC_IO1 */
IOT_IO_NAME_SFC_IO2, /* <SFC_IO2 */
IOT_IO_NAME_SFC_IO0, /* <SFC_IO0 */
IOT_IO_NAME_SFC_CLK, /* <SFC_CLK */
IOT_IO_NAME_SFC_IO3, /* <SFC_IO3 */
IOT_IO_NAME_MAX,
} IotIoName;
/**
* @ingroup iot_io
*
* GPIO_0 pin function.CNcomment:GPIO_0CNend
*/
typedef enum {
IOT_IO_FUNC_GPIO_0_GPIO,
IOT_IO_FUNC_GPIO_0_UART1_TXD = 2,
IOT_IO_FUNC_GPIO_0_SPI1_CK,
IOT_IO_FUNC_GPIO_0_JTAG_TDO,
IOT_IO_FUNC_GPIO_0_PWM3_OUT,
IOT_IO_FUNC_GPIO_0_I2C1_SDA,
} IotIoFuncGpio0;
/**
* @ingroup iot_io
*
* GPIO_1 pin function.CNcomment:GPIO_1CNend
*/
typedef enum {
IOT_IO_FUNC_GPIO_1_GPIO,
IOT_IO_FUNC_GPIO_1_UART1_RXD = 2,
IOT_IO_FUNC_GPIO_1_SPI1_RXD,
IOT_IO_FUNC_GPIO_1_JTAG_TCK,
IOT_IO_FUNC_GPIO_1_PWM4_OUT,
IOT_IO_FUNC_GPIO_1_I2C1_SCL,
IOT_IO_FUNC_GPIO_1_BT_FREQ,
} IotIoFuncGpio1;
/**
* @ingroup iot_io
*
* GPIO_2 pin function.CNcomment:GPIO_2CNend
*/
typedef enum {
IOT_IO_FUNC_GPIO_2_GPIO,
IOT_IO_FUNC_GPIO_2_UART1_RTS_N = 2,
IOT_IO_FUNC_GPIO_2_SPI1_TXD,
IOT_IO_FUNC_GPIO_2_JTAG_TRSTN,
IOT_IO_FUNC_GPIO_2_PWM2_OUT,
IOT_IO_FUNC_GPIO_2_SSI_CLK = 7,
} IotIoFuncGpio2;
/**
* @ingroup iot_io
*
* GPIO_3 pin function.CNcomment:GPIO_3CNend
*/
typedef enum {
IOT_IO_FUNC_GPIO_3_GPIO,
IOT_IO_FUNC_GPIO_3_UART0_TXD,
IOT_IO_FUNC_GPIO_3_UART1_CTS_N,
IOT_IO_FUNC_GPIO_3_SPI1_CSN,
IOT_IO_FUNC_GPIO_3_JTAG_TDI,
IOT_IO_FUNC_GPIO_3_PWM5_OUT,
IOT_IO_FUNC_GPIO_3_I2C1_SDA,
IOT_IO_FUNC_GPIO_3_SSI_DATA,
} IotIoFuncGpio3;
/**
* @ingroup iot_io
*
* GPIO_4 pin function.CNcomment:GPIO_4CNend
*/
typedef enum {
IOT_IO_FUNC_GPIO_4_GPIO,
IOT_IO_FUNC_GPIO_4_UART0_RXD = 2,
IOT_IO_FUNC_GPIO_4_JTAG_TMS = 4,
IOT_IO_FUNC_GPIO_4_PWM1_OUT,
IOT_IO_FUNC_GPIO_4_I2C1_SCL,
} IotIoFuncGpio4;
/**
* @ingroup iot_io
*
* GPIO_5 pin function.CNcomment:GPIO_5CNend
*/
typedef enum {
IOT_IO_FUNC_GPIO_5_GPIO,
IOT_IO_FUNC_GPIO_5_UART1_RXD = 2,
IOT_IO_FUNC_GPIO_5_SPI0_CSN,
IOT_IO_FUNC_GPIO_5_PWM2_OUT = 5,
IOT_IO_FUNC_GPIO_5_I2S0_MCLK,
IOT_IO_FUNC_GPIO_5_BT_STATUS,
} IotIoFuncGpio5;
/**
* @ingroup iot_io
*
* GPIO_6 pin function.CNcomment:GPIO_6CNend
*/
typedef enum {
IOT_IO_FUNC_GPIO_6_GPIO,
IOT_IO_FUNC_GPIO_6_UART1_TXD = 2,
IOT_IO_FUNC_GPIO_6_SPI0_CK,
IOT_IO_FUNC_GPIO_6_PWM3_OUT = 5,
IOT_IO_FUNC_GPIO_6_I2S0_TX,
IOT_IO_FUNC_GPIO_6_COEX_SWITCH,
} IotIoFuncGpio6;
/**
* @ingroup iot_io
*
* GPIO_7 pin function.CNcomment:GPIO_7CNend
*/
typedef enum {
IOT_IO_FUNC_GPIO_7_GPIO,
IOT_IO_FUNC_GPIO_7_UART1_CTS_N = 2,
IOT_IO_FUNC_GPIO_7_SPI0_RXD,
IOT_IO_FUNC_GPIO_7_PWM0_OUT = 5,
IOT_IO_FUNC_GPIO_7_I2S0_BCLK,
IOT_IO_FUNC_GPIO_7_BT_ACTIVE,
} IotIoFuncGpio7;
/**
* @ingroup iot_io
*
* GPIO_8 pin function.CNcomment:GPIO_8CNend
*/
typedef enum {
IOT_IO_FUNC_GPIO_8_GPIO,
IOT_IO_FUNC_GPIO_8_UART1_RTS_N = 2,
IOT_IO_FUNC_GPIO_8_SPI0_TXD,
IOT_IO_FUNC_GPIO_8_PWM1_OUT = 5,
IOT_IO_FUNC_GPIO_8_I2S0_WS,
IOT_IO_FUNC_GPIO_8_WLAN_ACTIVE,
} IotIoFuncGpio8;
/**
* @ingroup iot_io
*
* GPIO_9 pin function.CNcomment:GPIO_9CNend
*/
typedef enum {
IOT_IO_FUNC_GPIO_9_GPIO,
IOT_IO_FUNC_GPIO_9_I2C0_SCL,
IOT_IO_FUNC_GPIO_9_UART2_RTS_N,
IOT_IO_FUNC_GPIO_9_SDIO_D2,
IOT_IO_FUNC_GPIO_9_SPI0_TXD,
IOT_IO_FUNC_GPIO_9_PWM0_OUT,
IOT_IO_FUNC_GPIO_9_I2S0_MCLK = 7,
} IotIoFuncGpio9;
/**
* @ingroup iot_io
*
* GPIO_10 pin function.CNcomment:GPIO_10CNend
*/
typedef enum {
IOT_IO_FUNC_GPIO_10_GPIO,
IOT_IO_FUNC_GPIO_10_I2C0_SDA,
IOT_IO_FUNC_GPIO_10_UART2_CTS_N,
IOT_IO_FUNC_GPIO_10_SDIO_D3,
IOT_IO_FUNC_GPIO_10_SPI0_CK,
IOT_IO_FUNC_GPIO_10_PWM1_OUT,
IOT_IO_FUNC_GPIO_10_I2S0_TX = 7,
} IotIoFuncGpio10;
/**
* @ingroup iot_io
*
* GPIO_11 pin function.CNcomment:GPIO_11CNend
*/
typedef enum {
IOT_IO_FUNC_GPIO_11_GPIO,
IOT_IO_FUNC_GPIO_11_UART2_TXD = 2,
IOT_IO_FUNC_GPIO_11_SDIO_CMD,
IOT_IO_FUNC_GPIO_11_SPI0_RXD,
IOT_IO_FUNC_GPIO_11_PWM2_OUT,
IOT_IO_FUNC_GPIO_11_RF_TX_EN_EXT,
IOT_IO_FUNC_GPIO_11_I2S0_RX,
} IotIoFuncGpio11;
/**
* @ingroup iot_io
*
* GPIO_12 pin function.CNcomment:GPIO_12CNend
*/
typedef enum {
IOT_IO_FUNC_GPIO_12_GPIO,
IOT_IO_FUNC_GPIO_12_UART2_RXD = 2,
IOT_IO_FUNC_GPIO_12_SDIO_CLK,
IOT_IO_FUNC_GPIO_12_SPI0_CSN,
IOT_IO_FUNC_GPIO_12_PWM3_OUT,
IOT_IO_FUNC_GPIO_12_RF_RX_EN_EXT,
IOT_IO_FUNC_GPIO_12_I2S0_BCLK,
} IotIoFuncGpio12;
/**
* @ingroup iot_io
*
* GPIO_13 pin function.CNcomment:GPIO_13CNend
*/
typedef enum {
IOT_IO_FUNC_GPIO_13_SSI_DATA,
IOT_IO_FUNC_GPIO_13_UART0_TXD,
IOT_IO_FUNC_GPIO_13_UART2_RTS_N,
IOT_IO_FUNC_GPIO_13_SDIO_D0,
IOT_IO_FUNC_GPIO_13_GPIO,
IOT_IO_FUNC_GPIO_13_PWM4_OUT,
IOT_IO_FUNC_GPIO_13_I2C0_SDA,
IOT_IO_FUNC_GPIO_13_I2S0_WS,
} IotIoFuncGpio13;
/**
* @ingroup iot_io
*
* GPIO_14 pin function.CNcomment:GPIO_14CNend
*/
typedef enum {
IOT_IO_FUNC_GPIO_14_SSI_CLK,
IOT_IO_FUNC_GPIO_14_UART0_RXD,
IOT_IO_FUNC_GPIO_14_UART2_CTS_N,
IOT_IO_FUNC_GPIO_14_SDIO_D1,
IOT_IO_FUNC_GPIO_14_GPIO,
IOT_IO_FUNC_GPIO_14_PWM5_OUT,
IOT_IO_FUNC_GPIO_14_I2C0_SCL,
} IotIoFuncGpio14;
/**
* @ingroup iot_io
*
* SFC_CSN pin function.CNcomment:SFC_CSNCNend
*/
typedef enum {
IOT_IO_FUNC_SFC_CSN_SFC_CSN,
IOT_IO_FUNC_SFC_CSN_SDIO_D2,
IOT_IO_FUNC_SFC_CSN_GPIO9,
IOT_IO_FUNC_SFC_CSN_SPI0_TXD = 4,
} IotIoFuncSfcCsn;
/**
* @ingroup iot_io
*
* SFC_DO pin function.CNcomment:SFC_DOCNend
*/
typedef enum {
IOT_IO_FUNC_SFC_IO_1_SFC_DO,
IOT_IO_FUNC_SFC_IO_1_SDIO_D3,
IOT_IO_FUNC_SFC_IO_1_GPIO10,
IOT_IO_FUNC_SFC_IO_1_SPI0_CK = 4,
} IotIoFuncSfcIo1;
/**
* @ingroup iot_io
*
* SFC_WPN pin function.CNcomment:SFC_WPNCNend
*/
typedef enum {
IOT_IO_FUNC_SFC_IO_2_SFC_WPN,
IOT_IO_FUNC_SFC_IO_2_SDIO_CMD,
IOT_IO_FUNC_SFC_IO_2_GPIO11,
IOT_IO_FUNC_SFC_IO_2_RF_TX_EN_EXT,
IOT_IO_FUNC_SFC_IO_2_SPI0_RXD,
} IotIoFuncSfcIo2;
/**
* @ingroup iot_io
*
* SFC_DI pin function.CNcomment:SFC_DICNend
*/
typedef enum {
IOT_IO_FUNC_SFC_IO_0_SFC_DI,
IOT_IO_FUNC_SFC_IO_0_SDIO_CLK,
IOT_IO_FUNC_SFC_IO_0_GPIO12,
IOT_IO_FUNC_SFC_IO_0_RF_RX_EN_EXT,
IOT_IO_FUNC_SFC_IO_0_SPI0_CSN,
} IotIoFuncSfcIo0;
/**
* @ingroup iot_io
*
* SFC_CLK pin function.CNcomment:SFC_CLKCNend
*/
typedef enum {
IOT_IO_FUNC_SFC_CLK_SFC_CLK,
IOT_IO_FUNC_SFC_CLK_SDIO_D0,
IOT_IO_FUNC_SFC_CLK_GPIO13,
IOT_IO_FUNC_SFC_CLK_SSI_DATA = 4,
} IotIoFuncSfcClk;
/**
* @ingroup iot_io
*
* SFC_HOLDN pin function.CNcomment:SFC_HOLDNCNend
*/
typedef enum {
IOT_IO_FUNC_SFC_IO_3_SFC_HOLDN,
IOT_IO_FUNC_SFC_IO_3_SDIO_D1,
IOT_IO_FUNC_SFC_IO_3_GPIO14,
IOT_IO_FUNC_SFC_IO_3_SSI_CLK = 4,
} IotIoFuncSfcIo3;
/**
* @ingroup iot_io
*
* I/O drive capability.CNcomment:IOCNend
* Note: The HI_IO_NAME_GPIO_0~HI_IO_NAME_GPIO_11 and HI_IO_NAME_GPIO_13~HI_IO_NAME_GPIO_14 driver capabilities are
* optional.The value range is HI_IO_DRIVER_STRENGTH_0~HI_IO_DRIVER_STRENGTH_3, and the other I/O ranges are
* HI_IO_DRIVER_STRENGTH_0~HI_IO_DRIVER_STRENGTH_7.CNcomment::HI_IO_NAME_GPIO_0~HI_IO_NAME_GPIO_11
* HI_IO_NAME_GPIO_13~HI_IO_NAME_GPIO_14HI_IO_DRIVER_STRENGTH_0~HI_IO_DRIVER_STRENGTH_3
* IOHI_IO_DRIVER_STRENGTH_0~HI_IO_DRIVER_STRENGTH_7CNend
*/
typedef enum {
IOT_IO_DRIVER_STRENGTH_0 = 0, /* <Drive strength level 0 (highest).CNcomment:驱动能力0级驱动能力最高CNend */
IOT_IO_DRIVER_STRENGTH_1, /* <Drive strength level 1.CNcomment:驱动能力1级CNend */
IOT_IO_DRIVER_STRENGTH_2, /* <Drive strength level 2.CNcomment:驱动能力2级CNend */
IOT_IO_DRIVER_STRENGTH_3, /* <Drive strength level 3.CNcomment:驱动能力3级CNend */
IOT_IO_DRIVER_STRENGTH_4, /* <Drive strength level 4.CNcomment:驱动能力4级CNend */
IOT_IO_DRIVER_STRENGTH_5, /* <Drive strength level 5.CNcomment:驱动能力5级CNend */
IOT_IO_DRIVER_STRENGTH_6, /* <Drive strength level 6.CNcomment:驱动能力6级CNend */
IOT_IO_DRIVER_STRENGTH_7, /* <Drive strength level 7 (lowest).CNcomment:驱动能力7级驱动能力最低CNend */
IOT_IO_DRIVER_STRENGTH_MAX,
} IotIoDriverStrength;
unsigned int IoSetPull(unsigned int id, IotIoPull val);
unsigned int IoSetFunc(unsigned int id, unsigned char val);
//unsigned int TaskMsleep(unsigned int ms);
#endif
/** @} */

@ -0,0 +1,95 @@
/*
* Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
* 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.
*/
/**
* This file make use the hmac to make mqtt pwd.
* The method is use the date string to hash the device passwd
* Take care that this implement depends on the hmac of the mbedtls
*/
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include <stdio.h>
#include "md.h"
#include "md_internal.h"
#define CN_HMAC256_LEN_MAX (65)
#define CN_HMAC256_LEN 32
#define RIGHT_MOVE_BIT_4 (4)
#define NUMBER_9 (9)
#define DECIMAL_BASE (10)
#define STRING_LEN_TIMES (2)
#define LEN_TIMES (2)
#define OFFSET (1)
// make a byte to 2 ascii hex
static int byte2hexstr(unsigned char *bufin, int len, char *bufout)
{
int i = 0;
unsigned char tmp_l = 0x0;
unsigned char tmp_h = 0;
if ((bufin == NULL)||(len <= 0)||(bufout == NULL)) {
return -1;
}
for (i = 0; i < len; i++) {
tmp_h = (bufin[i] >> RIGHT_MOVE_BIT_4) & 0X0F;
tmp_l = bufin[i] & 0x0F;
bufout[STRING_LEN_TIMES * i] = (tmp_h > NUMBER_9) ?
(tmp_h - DECIMAL_BASE + 'a'):(tmp_h +'0');
bufout[STRING_LEN_TIMES * i + OFFSET] = (tmp_l > NUMBER_9) ?
(tmp_l - DECIMAL_BASE + 'a'):(tmp_l +'0');
}
bufout[STRING_LEN_TIMES * len] = '\0';
return 0;
}
int HmacGeneratePwd(const unsigned char *content, int contentLen, const unsigned char *key,
int keyLen, unsigned char *buf)
{
int ret = -1;
mbedtls_md_context_t mbedtls_md_ctx;
const mbedtls_md_info_t *md_info;
unsigned char hash[CN_HMAC256_LEN];
if ((key == NULL)||(content == NULL)||(buf == NULL)||
(keyLen == 0)||(contentLen == 0)||
(CN_HMAC256_LEN_MAX < (CN_HMAC256_LEN * LEN_TIMES + OFFSET))) {
return ret;
}
md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA256);
if ((md_info == NULL)||((size_t)md_info->size > CN_HMAC256_LEN)) {
return ret;
}
mbedtls_md_init(&mbedtls_md_ctx);
ret = mbedtls_md_setup(&mbedtls_md_ctx, md_info, 1);
if (ret != 0) {
mbedtls_md_free(&mbedtls_md_ctx);
return ret;
}
(void)mbedtls_md_hmac_starts(&mbedtls_md_ctx, key, keyLen);
(void)mbedtls_md_hmac_update(&mbedtls_md_ctx, content, contentLen);
(void)mbedtls_md_hmac_finish(&mbedtls_md_ctx, hash);
// <transfer the hash code to the string mode
ret = byte2hexstr(hash, CN_HMAC256_LEN, (char *)buf);
if (ret != 0) {
return ret;
}
return ret;
}

@ -0,0 +1,32 @@
/*
* Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
* 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 IOT_HMAC_H
#define IOT_HMAC_H
/**
* This function used to generate the passwd for the mqtt to connect the HW IoT platform
* @param content: This is the content for the hmac,
* and usually it is the device passwd set or get from the Iot Platform
* @param content_len: The length of the content
* @param key: This is the key for the hmac, and usually it is the time used in the client_id:
* the format isyearmonthdatehour:like 1970010100
* @param key_len: The length of the key
* @param buf: used to storage the hmac code
* @param buf_len:the buf length
* @return:0 success while others failed
*/
int HmacGeneratePwd(const unsigned char *content, int contentLen, const unsigned char *key,
int keyLen, unsigned char *buf);
#endif

@ -0,0 +1,50 @@
/*
* Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
* 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.
*/
#include <iot_log.h>
static EnIotLogLevel gIoTLogLevel = EN_IOT_LOG_LEVEL_TRACE;
static const char *gIoTLogLevelNames[] = {
"TRACE",
"DEBUG",
"INFO ",
"WARN ",
"ERROR",
"FATAL"
};
int IoTLogLevelSet(EnIotLogLevel level)
{
int ret = -1;
if (level < EN_IOT_LOG_LEVEL_MAX) {
gIoTLogLevel = level;
ret = 0;
}
return ret;
}
EnIotLogLevel IoTLogLevelGet(void)
{
return gIoTLogLevel;
}
const char *IoTLogLevelGetName(EnIotLogLevel logLevel)
{
if (logLevel >= EN_IOT_LOG_LEVEL_MAX) {
return "NULL ";
} else {
return gIoTLogLevelNames[logLevel];
}
}

@ -0,0 +1,122 @@
/*
* Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
* 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 IOT_LOG_H_
#define IOT_LOG_H_
/**
* @brief:this defines for the log module,
* and IOT_LOG_TRACE/IOT_LOG_DEBUG will not participate the compile in the release version
*
*
* */
typedef enum {
// < this is used as the trace function,like the function enter and function out
EN_IOT_LOG_LEVEL_TRACE = 0,
// < this is used as the debug, you could add any debug as you wish
EN_IOT_LOG_LEVEL_DEBUG,
// < which means it is import message, and you should known
EN_IOT_LOG_LEVEL_INFO,
// < this is used as the executed result,which means the status is not what we expected
EN_IOT_LOG_LEVEL_WARN,
// < this is used as the executed result,which means the status is not what we expected
EN_IOT_LOG_LEVEL_ERROR,
// < this is used as the parameters input for the api interface, which could not accepted
EN_IOT_LOG_LEVEL_FATAL,
EN_IOT_LOG_LEVEL_MAX,
}EnIotLogLevel;
/**
* @brief:use this function to get the current output log
*
* @return: the current output mask log, defined by en_iot_log_level_t
* */
EnIotLogLevel IoTLogLevelGet(void);
/**
* @brief: use this function to get the debug level name
*
* @parameter[in]:level, the level to get
*
* @return: the mapped level name
* */
const char *IoTLogLevelGetName(EnIotLogLevel logLevel);
/**
* @brief:use this function to set the current output log
*
* @parameter[in] level:defined by en_iot_log_level_t
*
* @return: 0 success while -1 failed
* */
int IoTLogLevelSet(EnIotLogLevel level);
/*
* @brief: this is a weak function ,and you could rewrite one
*
* @param fmt: same use as the fmt for printf
*
* @param unfixed: same use for printf
*
* @return: don't care about it
*
* @attention: and the components should not call this function directly, you'd better
*
* call IOT_LOG groups
*
* */
#ifndef IOT_PRINT
#define IOT_PRINT(fmt, ...) \
do \
{ \
printf(fmt, ##__VA_ARGS__); \
}while (0)
#endif
#ifdef CONFIG_LINKLOG_ENABLE
#define IOT_LOG(level, fmt, ...) \
do \
{ \
IOT_PRINT("[%s][%s] " fmt "\r\n", \
IoTLogLevelGetName((level)), __FUNCTION__, ##__VA_ARGS__); \
} while (0)
#define IOT_LOG_TRACE(fmt, ...) \
do \
{ \
if ((EN_IOT_LOG_LEVEL_TRACE) >= IoTLogLevelGet()) \
{ \
IOT_LOG(EN_IOT_LOG_LEVEL_TRACE, fmt, ##__VA_ARGS__); \
} \
} while (0)
#define IOT_LOG_DEBUG(fmt, ...) \
do \
{ \
if ((EN_IOT_LOG_LEVEL_DEBUG) >= IoTLogLevelGet()) \
{ \
IOT_LOG(EN_IOT_LOG_LEVEL_DEBUG, fmt, ##__VA_ARGS__); \
} \
} while (0)
#else
#define IOT_LOG(level, fmt, ...)
#define IOT_LOG_TRACE(fmt, ...)
#define IOT_LOG_DEBUG(fmt, ...)
#endif
#define IOT_LOG_TRACE(fmt, ...) IOT_LOG(EN_IOT_LOG_LEVEL_TRACE, fmt, ##__VA_ARGS__)
#define IOT_LOG_INFO(fmt, ...) IOT_LOG(EN_IOT_LOG_LEVEL_INFO, fmt, ##__VA_ARGS__)
#define IOT_LOG_WARN(fmt, ...) IOT_LOG(EN_IOT_LOG_LEVEL_WARN, fmt, ##__VA_ARGS__)
#define IOT_LOG_ERROR(fmt, ...) IOT_LOG(EN_IOT_LOG_LEVEL_ERROR, fmt, ##__VA_ARGS__)
#define IOT_LOG_FATAL(fmt, ...) IOT_LOG(EN_IOT_LOG_LEVEL_FATAL, fmt, ##__VA_ARGS__)
#endif /* IOT_LOG_H_ */

@ -0,0 +1,325 @@
/*
* Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
* 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.
*/
/**
* STEPS:
* 1, CONNECT TO THE IOT SERVER
* 2, SUBSCRIBE THE DEFAULT TOPIC
* 3, WAIT FOR ANY MESSAGE COMES OR ANY MESSAGE TO SEND
*/
#include <securec.h>
#include <hi_task.h>
#include <hi_msg.h>
#include <hi_mem.h>
#include <string.h>
#include <stdbool.h>
#include "iot_config.h"
#include "iot_log.h"
#include "iot_hmac.h"
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_watchdog.h"
#include "MQTTClient.h"
#include "iot_errno.h"
#include "iot_main.h"
#include "iot_gpio.h"
// < this is the configuration head
#define CN_IOT_SERVER "tcp://106.55.124.154:1883" // Tencent iot cloud address
#define CONFIG_COMMAND_TIMEOUT 10000L
#define CN_KEEPALIVE_TIME 50
#define CN_CLEANSESSION 1
#define CN_HMAC_PWD_LEN 65 // < SHA256 IS 32 BYTES AND END APPEND '\0'
#define CN_EVENT_TIME "1970000100"
#define CN_CLIENTID_FMT "%s_0_0_%s" // < This is the cient ID format, deviceID_0_0_TIME
#define CN_QUEUE_WAITTIMEOUT 1000
#define CN_QUEUE_MSGNUM 16
#define CN_QUEUE_MSGSIZE (sizeof(hi_pvoid))
#define CN_TASK_PRIOR 28
#define CN_TASK_STACKSIZE 0X2000
#define CN_TASK_NAME "IoTMain"
typedef enum {
EN_IOT_MSG_PUBLISH = 0,
EN_IOT_MSG_RECV,
}EnIotMsg;
typedef struct {
EnIotMsg type;
int qos;
const char *topic;
const char *payload;
}IoTMsg_t;
typedef struct {
bool stop;
unsigned int conLost;
unsigned int queueID;
unsigned int iotTaskID;
fnMsgCallBack msgCallBack;
MQTTClient_deliveryToken tocken;
}IotAppCb_t;
static IotAppCb_t gIoTAppCb;
static const char *gDefaultSubscribeTopic[] = {
/* Tencent iot cloud topic */
"YT32IOSCAL/Hi38611_mqtt/data",
"YT32IOSCAL/Hi38611_mqtt/event",
"YT32IOSCAL/Hi38611_mqtt/control",
};
#define CN_TOPIC_SUBSCRIBE_NUM (sizeof(gDefaultSubscribeTopic) / sizeof(const char *))
static int MsgRcvCallBack(char *context, char *topic, int topicLen, MQTTClient_message *message)
{
IoTMsg_t *msg;
char *buf;
unsigned int bufSize;
int topiLen = topicLen;
if (topiLen == 0) {
topiLen = strlen(topic);
}
bufSize = topiLen + 1 + message->payloadlen + 1 + sizeof(IoTMsg_t);
buf = hi_malloc(0, bufSize);
if (buf != NULL) {
msg = (IoTMsg_t *)buf;
buf += sizeof(IoTMsg_t);
bufSize -= sizeof(IoTMsg_t);
msg->qos = message->qos;
msg->type = EN_IOT_MSG_RECV;
(void)memcpy_s(buf, bufSize, topic, topiLen);
buf[topiLen] = '\0';
msg->topic = buf;
buf += topiLen + 1;
bufSize -= (topiLen + 1);
(void)memcpy_s(buf, bufSize, message->payload, message->payloadlen);
buf[message->payloadlen] = '\0';
msg->payload = buf;
IOT_LOG_DEBUG("RCVMSG:QOS:%d TOPIC:%s PAYLOAD:%s\r\n", msg->qos, msg->topic, msg->payload);
if (IOT_SUCCESS != osMessageQueuePut(gIoTAppCb.queueID, &msg, 0, CN_QUEUE_WAITTIMEOUT)) {
IOT_LOG_ERROR("Wrie queue failed\r\n");
hi_free(0, msg);
}
}
MQTTClient_freeMessage(&message);
MQTTClient_free(topic);
return 1;
}
// < when the connect lost and this callback will be called
static void ConnLostCallBack(char *context, char *cause)
{
IOT_LOG_DEBUG("Connection lost:caused by:%s\r\n", cause == NULL? "Unknown" : cause);
return;
}
static int MqttProcessQueueMsg(MQTTClient client, IoTMsg_t *msg, MQTTClient_message pubMsg)
{
int ret = 0;
switch (msg->type) {
case EN_IOT_MSG_PUBLISH:
pubMsg.payload = (void *)msg->payload;
pubMsg.payloadlen = (int)strlen(msg->payload);
pubMsg.qos = msg->qos;
pubMsg.retained = 0;
ret = MQTTClient_publishMessage(client, msg->topic, &pubMsg, &gIoTAppCb.tocken);
if (ret != MQTTCLIENT_SUCCESS) {
IOT_LOG_ERROR("MSGSEND:failed\r\n");
}
IOT_LOG_DEBUG("MSGSEND:SUCCESS\r\n");
gIoTAppCb.tocken++;
break;
case EN_IOT_MSG_RECV:
if (gIoTAppCb.msgCallBack != NULL) {
gIoTAppCb.msgCallBack(msg->qos, msg->topic, msg->payload); /*接受信息并进行相应的操作函数体在IoTSetMsgCallback中定义*/
}
break;
default:
break;
}
}
// <use this function to deal all the comming message
static int ProcessQueueMsg(MQTTClient client)
{
unsigned int ret;
unsigned int msgSize;
IoTMsg_t *msg;
unsigned int timeout;
MQTTClient_message pubmsg = MQTTClient_message_initializer;
timeout = CN_QUEUE_WAITTIMEOUT;
do {
msg = NULL;
msgSize = sizeof(hi_pvoid);
ret = osMessageQueueGet(gIoTAppCb.queueID, &msg, &msgSize, timeout);/*得到数据存入msg*/
if (msg != NULL) {
IOT_LOG_DEBUG("QUEUEMSG:QOS:%d TOPIC:%s PAYLOAD:%s\r\n", msg->qos, msg->topic, msg->payload);
MqttProcessQueueMsg(client, msg, pubmsg);
hi_free(0, msg);
}
timeout = 0; // < continous to deal the message without wait here
} while (ret == IOT_SUCCESS);
return 0;
}
int MqttDestory(int ret, MQTTClient client)
{
if (ret != MQTTCLIENT_SUCCESS) {
MQTTClient_destroy(&client);
return -1;
}
return MQTTCLIENT_SUCCESS;
}
static void MainEntryProcess(void)
{
int rc = 0, subQos[CN_TOPIC_SUBSCRIBE_NUM] = {1};
MQTTClient client = NULL;
MQTTClient_connectOptions connOpts = MQTTClient_connectOptions_initializer;
char *clientID = CN_CLIENTID;
char *userID = CONFIG_USER_ID;
char *userPwd = hi_malloc(0, CN_HMAC_PWD_LEN);
if (userPwd == NULL) {
hi_free(0, clientID);
return;
}
userPwd = CONFIG_USER_PWD;
connOpts.keepAliveInterval = CN_KEEPALIVE_TIME;
connOpts.cleansession = CN_CLEANSESSION;
connOpts.username = userID;
connOpts.password = userPwd;
connOpts.MQTTVersion = MQTTVERSION_3_1_1;
IOT_LOG_DEBUG("CLIENTID:%s USERID:%s USERPWD:%s, IOTSERVER:%s\r\n",
clientID, userID, userPwd==NULL?"NULL" : userPwd, CN_IOT_SERVER);
rc = MQTTClient_create(&client, CN_IOT_SERVER, clientID, MQTTCLIENT_PERSISTENCE_NONE, NULL);
if (rc != MQTTCLIENT_SUCCESS) {
if (userPwd != NULL) {
hi_free(0, userPwd);
}
return;
}
rc = MQTTClient_setCallbacks(client, NULL, ConnLostCallBack, MsgRcvCallBack, NULL);
if (MqttDestory(rc, client) != MQTTCLIENT_SUCCESS) {
return;
}
rc = MQTTClient_connect(client, &connOpts);
if (MqttDestory(rc, client) != MQTTCLIENT_SUCCESS) {
return;
}
for (int i = 0; i < CN_TOPIC_SUBSCRIBE_NUM; i++) {
rc = MQTTClient_subscribeMany(client, CN_TOPIC_SUBSCRIBE_NUM,
(char *const *)gDefaultSubscribeTopic, (int *)&subQos[0]);
if (MqttDestory(rc, client) != MQTTCLIENT_SUCCESS) {
return;
}
}
IOT_LOG_DEBUG ("Connect success and Subscribe success\r\n");
while (MQTTClient_isConnected(client)) {
ProcessQueueMsg(client); // < do the job here
MQTTClient_yield(); // < make the keepalive done
}
MQTTClient_disconnect(client, CONFIG_COMMAND_TIMEOUT);
return;
}
/* MQTT processing entry */
static hi_void *MainEntry(char *arg)
{
(void)arg;
while (gIoTAppCb.stop == false) {
MainEntryProcess();
IOT_LOG_DEBUG("The connection lost and we will try another connect\r\n");
hi_sleep(1000); /* 1000: cpu sleep 1000ms */
}
return NULL;
}
static void engine_init(unsigned int IO){
IoTGpioInit(IO);
IoSetFunc(IO, 0);
IoTGpioSetDir(IO, IOT_GPIO_DIR_OUT);
IoTGpioSetOutputVal(IO, IOT_GPIO_VALUE0);
IOT_LOG_DEBUG("GPIO:%u initialized!", IO);
}
int IoTMain(void)
{
unsigned int ret = 0;
hi_task_attr attr = {0};
engine_init(6);
engine_init(7);
engine_init(9);
engine_init(10);
gIoTAppCb.queueID = osMessageQueueNew(CN_QUEUE_MSGNUM, CN_QUEUE_MSGSIZE, NULL);
if (ret != IOT_SUCCESS) {
IOT_LOG_ERROR("Create the msg queue Failed\r\n");
}
attr.stack_size = CN_TASK_STACKSIZE;
attr.task_prio = CN_TASK_PRIOR;
attr.task_name = CN_TASK_NAME;
ret = hi_task_create(&gIoTAppCb.iotTaskID, &attr, MainEntry, NULL);
if (ret != IOT_SUCCESS) {
IOT_LOG_ERROR("Create the Main Entry Failed\r\n");
}
return 0;
}
int IoTSetMsgCallback(fnMsgCallBack msgCallback)
{
gIoTAppCb.msgCallBack = msgCallback;/*赋予函数*/
return 0;
}
int IotSendMsg(int qos, const char *topic, const char *payload)
{
int rc = -1;
IoTMsg_t *msg;
char *buf;
unsigned int bufSize;
bufSize = strlen(topic) + 1 +strlen(payload) + 1 + sizeof(IoTMsg_t);
buf = hi_malloc(0, bufSize);
if (buf != NULL) {
msg = (IoTMsg_t *)buf;
buf += sizeof(IoTMsg_t);
bufSize -= sizeof(IoTMsg_t);
msg->qos = qos;
msg->type = EN_IOT_MSG_PUBLISH;
(void)memcpy_s(buf, bufSize, topic, strlen(topic));
buf[strlen(topic)] = '\0';
msg->topic = buf;
buf += strlen(topic) + 1;
bufSize -= (strlen(topic) + 1);
(void)memcpy_s(buf, bufSize, payload, strlen(payload));
buf[strlen(payload)] = '\0';
msg->payload = buf;
IOT_LOG_DEBUG("SNDMSG:QOS:%d TOPIC:%s PAYLOAD:%s\r\n", msg->qos, msg->topic, msg->payload);
if (IOT_SUCCESS != osMessageQueuePut(gIoTAppCb.queueID, &msg, 0, CN_QUEUE_WAITTIMEOUT)) {
IOT_LOG_ERROR("Write queue failed\r\n");
hi_free(0, msg);
} else {
rc = 0;
}
}
return rc;
}

@ -0,0 +1,44 @@
/*
* Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
* 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 IOT_MAIN_H
#define IOT_MAIN_H
typedef void (*fnMsgCallBack)(int qos, const char *topic, const char *payload);
/**
* This is the iot main function. Please call this function first
*/
int IoTMain(void);
/**
* Use this function to set the message call back function, when some messages comes,
* the callback will be called, if you don't care about the message, set it to NULL
*/
int IoTSetMsgCallback(fnMsgCallBack msgCallback);
/**
* When you want to send some messages to the iot server(including the response message),
* please call this api
* @param qos: the mqtt qos,:0,1,2
* @param topic: the iot mqtt topic
* @param payload: the mqtt payload
*
* @return 0 success while others failed
*
* @instruction: if success means we write the message to the queue susccess,
* not means communicate with the server success
*/
int IotSendMsg(int qos, const char *topic, const char *payload);
#endif /* IOT_MAIN_H_ */

@ -0,0 +1,336 @@
/*
* Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
* 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.
*/
#include <hi_mem.h>
#include <cJSON.h>
#include <string.h>
#include "iot_main.h"
#include "iot_log.h"
#include "iot_config.h"
#include "iot_profile.h"
// < format the report data to json string mode
static cJSON *FormateProflleValue(IoTProfileKV_t *kv)
{
cJSON *ret = NULL;
switch (kv->type) {
case EN_IOT_DATATYPE_INT:
ret = cJSON_CreateNumber(kv->iValue);
break;
case EN_IOT_DATATYPE_LONG:
ret = cJSON_CreateNumber((double)(*(long *)kv->value));
break;
case EN_IOT_DATATYPE_STRING:
ret = cJSON_CreateString((const char *)kv->value);
break;
default:
break;
}
return ret;
}
static cJSON *MakeKvs(IoTProfileKV_t *kvlst)
{
cJSON *root;
cJSON *kv;
IoTProfileKV_t *kvInfo;
// < build a root node
root = cJSON_CreateObject();
if (root == NULL) {
cJSON_Delete(root);
root = NULL;
return root;
}
// < add all the property to the properties
kvInfo = kvlst;
while (kvInfo != NULL) {
kv = FormateProflleValue(kvInfo);
if (kv == NULL) {
if (root != NULL) {
cJSON_Delete(root);
root = NULL;
}
return root;
}
cJSON_AddItemToObject(root, kvInfo->key, kv);
kvInfo = kvInfo->nxt;
}
// < OK, now we return it
return root;
}
#define CN_PROFILE_SERVICE_KEY_SERVICEID "service_id"
#define CN_PROFILE_SERVICE_KEY_PROPERTIIES "properties"
#define CN_PROFILE_SERVICE_KEY_EVENTTIME "event_time"
#define CN_PROFILE_KEY_SERVICES "services"
static cJSON *MakeService(IoTProfileService_t *serviceInfo)
{
cJSON *root;
cJSON *serviceID;
cJSON *properties;
cJSON *eventTime;
// < build a root node
root = cJSON_CreateObject();
if (root == NULL) {
cJSON_Delete(root);
root = NULL;
return root;
}
// < add the serviceID node to the root node
serviceID = cJSON_CreateString(serviceInfo->serviceID);
if (serviceID == NULL) {
if (root != NULL) {
cJSON_Delete(root);
root = NULL;
}
return root;
}
cJSON_AddItemToObjectCS(root, CN_PROFILE_SERVICE_KEY_SERVICEID, serviceID);
// < add the properties node to the root
properties = MakeKvs(serviceInfo->serviceProperty);
if (properties == NULL) {
if (root != NULL) {
cJSON_Delete(root);
root = NULL;
}
return root;
}
cJSON_AddItemToObjectCS(root, CN_PROFILE_SERVICE_KEY_PROPERTIIES, properties);
// < add the event time (optional) to the root
if (serviceInfo->eventTime != NULL) {
eventTime = cJSON_CreateString(serviceInfo->eventTime);
if (eventTime == NULL) {
if (root != NULL) {
cJSON_Delete(root);
root = NULL;
}
return root;
}
cJSON_AddItemToObjectCS(root, CN_PROFILE_SERVICE_KEY_EVENTTIME, eventTime);
}
// < OK, now we return it
cJSON_Delete(properties);
return root;
}
static cJSON *MakeServices(IoTProfileService_t *serviceInfo)
{
cJSON *services = NULL;
cJSON *service;
IoTProfileService_t *serviceTmp;
// < create the services array node
services = cJSON_CreateArray();
if (services == NULL) {
cJSON_Delete(services);
services = NULL;
return services;
}
serviceTmp = serviceInfo;
while (serviceTmp != NULL) {
service = MakeService(serviceTmp);
if (service == NULL) {
if (services != NULL) {
cJSON_Delete(services);
services = NULL;
}
return services;
}
cJSON_AddItemToArray(services, service);
serviceTmp = serviceTmp->nxt;
}
// < now we return the services
return services;
}
// < use this function to make a topic to publish
// < if request_id is needed depends on the fmt
static char *MakeTopic(const char *fmt, const char *deviceID, const char *requestID)
{
int len;
char *ret = NULL;
len = strlen(fmt) + strlen(deviceID);
if (requestID != NULL) {
len += strlen(requestID);
}
ret = hi_malloc(0, len);
if (ret != NULL) {
if (requestID != NULL) {
(void)snprintf_s(ret, len, len, fmt, deviceID, requestID);
} else {
(void)snprintf_s(ret, len, len, fmt, deviceID);
}
}
return ret;
}
#define CN_PROFILE_CMDRESP_KEY_RETCODE "result_code"
#define CN_PROFILE_CMDRESP_KEY_RESPNAME "response_name"
#define CN_PROFILE_CMDRESP_KEY_PARAS "paras"
static char *MakeProfileCmdResp(IoTCmdResp_t *payload)
{
char *ret = NULL;
cJSON *root;
cJSON *retCode;
cJSON *respName;
cJSON *paras;
// < create the root node
root = cJSON_CreateObject();
if (root == NULL) {
cJSON_Delete(root);
return ret;
}
// < create retcode and retdesc and add it to the root
retCode = cJSON_CreateNumber(payload->retCode);
if (retCode == NULL) {
if (root != NULL) {
cJSON_Delete(root);
}
return ret;
}
cJSON_AddItemToObjectCS(root, CN_PROFILE_CMDRESP_KEY_RETCODE, retCode);
if (payload->respName != NULL) {
respName = cJSON_CreateString(payload->respName);
if (respName == NULL) {
if (root != NULL) {
cJSON_Delete(root);
}
return ret;
}
cJSON_AddItemToObjectCS(root, CN_PROFILE_CMDRESP_KEY_RESPNAME, respName);
}
if (payload->paras != NULL) {
paras = MakeKvs(payload->paras);
if (paras == NULL) {
if (root != NULL) {
cJSON_Delete(root);
}
return ret;
}
cJSON_AddItemToObjectCS(root, CN_PROFILE_CMDRESP_KEY_PARAS, paras);
}
// < OK, now we make it to a buffer
ret = cJSON_PrintUnformatted(root);
cJSON_Delete(root);
return ret;
}
static char *MakeProfilePropertyReport(IoTProfileService_t *payload)
{
char *ret = NULL;
cJSON *root;
cJSON *services;
// < create the root node
root = cJSON_CreateObject();
if (root == NULL) {
cJSON_Delete(root);
return ret;
}
// < create the services array node to the root
services = MakeServices(payload);
if (services == NULL) {
if (root != NULL) {
cJSON_Delete(root);
}
return ret;
}
cJSON_AddItemToObjectCS(root, CN_PROFILE_KEY_SERVICES, services);
// < OK, now we make it to a buffer
ret = cJSON_PrintUnformatted(root);
cJSON_Delete(root);
return ret;
}
#define WECHAT_SUBSCRIBE_TYPE "update"
#define WECHAT_SUBSCRIBE_VERSION "1.0.0"
#define WECHAT_SUBSCRIBE_TOKEN "DeviceSubscribe"
static char *MakeProfileReport(WeChatProfile *payload)
{
char *ret = NULL;
cJSON *root;
cJSON *state;
cJSON *reported;
/* create json root node */
root = cJSON_CreateObject();
if (root == NULL) {
return;
}
/* state create */
state = cJSON_CreateObject();
if (state == NULL) {
return;
}
/* reported create */
reported = cJSON_CreateObject();
if (reported == NULL) {
return;
}
/* add root object */
cJSON_AddItemToObject(root, payload->subscribeType, cJSON_CreateString(WECHAT_SUBSCRIBE_TYPE));
cJSON_AddItemToObject(root, payload->status.subState, state);
cJSON_AddItemToObject(state, payload->status.subReport, reported);
cJSON_AddItemToObject(root, payload->status.reportVersion, cJSON_CreateString(WECHAT_SUBSCRIBE_VERSION));
cJSON_AddItemToObject(root, payload->status.Token, cJSON_CreateString(WECHAT_SUBSCRIBE_TOKEN));
/* add reported item */
cJSON_AddNumberToObject(reported, payload->reportAction.subDeviceActionLight,
payload->reportAction.lightActionStatus);
cJSON_AddNumberToObject(reported, payload->reportAction.subDeviceActionMotor,
payload->reportAction.motorActionStatus);
cJSON_AddNumberToObject(reported, payload->reportAction.subDeviceActionTemperature,
payload->reportAction.temperatureData);
cJSON_AddNumberToObject(reported, payload->reportAction.subDeviceActionHumidity,
payload->reportAction.humidityActionData);
cJSON_AddNumberToObject(reported, payload->reportAction.subDeviceActionLightIntensity,
payload->reportAction.lightIntensityActionData);
ret = cJSON_PrintUnformatted(root);
cJSON_Delete(state);
cJSON_Delete(reported);
cJSON_Delete(root);
return ret;
}
#define CN_PROFILE_TOPICFMT_TOPIC "YT32IOSCAL/Hi38611_mqtt/data"
int IoTProfilePropertyReport(char *deviceID, WeChatProfile *payload)
{
int ret = -1;
char *topic;
char *msg;
if ((deviceID == NULL) || (payload== NULL)) {
return ret;
}
topic = MakeTopic(CN_PROFILE_TOPICFMT_TOPIC, deviceID, NULL);
if (topic == NULL) {
return;
}
msg = MakeProfileReport(payload);
if ((topic != NULL) && (msg != NULL)) {
ret = IotSendMsg(0, topic, msg);
}
hi_free(0, topic);
cJSON_free(msg);
return ret;
}

@ -0,0 +1,94 @@
/*
* Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
* 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 IOT_PROFILE_H
#define IOT_PROFILE_H
#include <hi_types_base.h>
#include "iot_config.h"
#define OC_BEEP_STATUS_ON ((hi_u8) 0x01)
#define OC_BEEP_STATUS_OFF ((hi_u8) 0x00)
// < enum all the data type for the oc profile
typedef enum {
EN_IOT_DATATYPE_INT = 0,
EN_IOT_DATATYPE_LONG,
EN_IOT_DATATYPE_FLOAT,
EN_IOT_DATATYPE_DOUBLE,
EN_IOT_DATATYPE_STRING, // < must be ended with '\0'
EN_IOT_DATATYPE_LAST,
}IoTDataType_t;
typedef enum {
OC_LED_ON = 1,
OC_LED_OFF
}OcLedValue;
typedef struct {
void *nxt; // < ponit to the next key
const char *key;
const char *value;
hi_u32 iValue;
IoTDataType_t type;
}IoTProfileKV_t;
typedef struct {
void *nxt;
char *serviceID;
char *eventTime;
IoTProfileKV_t *serviceProperty;
}IoTProfileService_t;
typedef struct {
int retCode; // < response code, 0 success while others failed
const char *respName; // < response name
const char *requestID; // < specified by the message command
IoTProfileKV_t *paras; // < the command paras
}IoTCmdResp_t;
typedef struct {
const char *subState;
const char *subReport;
const char *reportVersion;
const char *Token;
}WeChatProfileStatus;
typedef struct {
int lightActionStatus;
int motorActionStatus;
int temperatureData;
int humidityActionData;
int lightIntensityActionData;
const char *subDeviceActionLight;
const char *subDeviceActionMotor;
const char *subDeviceActionTemperature;
const char *subDeviceActionHumidity;
const char *subDeviceActionLightIntensity;
}WeChatProfileReporte;
typedef struct {
const char *subscribeType;
WeChatProfileStatus status;
WeChatProfileReporte reportAction;
}WeChatProfile;
/**
* use this function to report the property to the iot platform
*/
int IoTProfilePropertyReport(char *deviceID, WeChatProfile *payload);
void cJsonInit(void);
void WifiStaReadyWait(void);
#endif

@ -0,0 +1,269 @@
/*
* Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
* 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.
*/
// < this demo make the wifi to connect to the specified AP
#include <unistd.h>
#include <hi_wifi_api.h>
#include <lwip/ip_addr.h>
#include <lwip/netifapi.h>
#include <hi_types_base.h>
#include <hi_task.h>
#include <hi_mem.h>
#include "iot_config.h"
#include "iot_log.h"
#include "wifi_device.h"
#include "cmsis_os2.h"
#include "wifi_device_config.h"
#include "lwip/api_shell.h"
#define APP_INIT_VAP_NUM 2
#define APP_INIT_USR_NUM 2
static struct netif *gLwipNetif = NULL;
static hi_bool gScanDone = HI_FALSE;
unsigned char wifiStatus = 0;
unsigned char wifiFirstConnecting = 0;
unsigned char wifiSecondConnecting = 0;
unsigned char wifiSecondConnected = 0;
static struct netif* g_iface = NULL;
void WifiStopSta(int netId);
static int WifiStartSta(void);
int cnetId = -1;
int g_connected = 0;
#define WIFI_CONNECT_STATUS ((unsigned char)0x02)
void wifiReconnected(int netId)
{
int recnetId = netId;
if (wifiFirstConnecting == WIFI_CONNECT_STATUS) {
wifiSecondConnecting = HI_TRUE;
wifiFirstConnecting = HI_FALSE;
WifiStopSta(recnetId);
ip4_addr_t ipAddr;
ip4_addr_t ipAny;
IP4_ADDR(&ipAny, 0, 0, 0, 0);
IP4_ADDR(&ipAddr, 0, 0, 0, 0);
recnetId = WifiStartSta();
netifapi_dhcp_start(gLwipNetif);
while (0 == memcmp(&ipAddr, &ipAny, sizeof(ip4_addr_t))) {
IOT_LOG_DEBUG("<Wifi reconnecting>:Wait the DHCP READY");
netifapi_netif_get_addr(gLwipNetif, &ipAddr, NULL, NULL);
hi_sleep(1000); /* 1000: cpu sleep 1000 ms */
}
wifiSecondConnected = HI_FALSE;
wifiFirstConnecting = WIFI_CONNECT_STATUS;
wifiStatus = HI_WIFI_EVT_CONNECTED;
}
}
/* clear netif's ip, gateway and netmask */
static void StaResetAddr(struct netif *lwipNetif)
{
ip4_addr_t st_gw;
ip4_addr_t st_ipaddr;
ip4_addr_t st_netmask;
if (lwipNetif == NULL) {
IOT_LOG_ERROR("hisi_reset_addr::Null param of netdev");
return;
}
IP4_ADDR(&st_gw, 0, 0, 0, 0);
IP4_ADDR(&st_ipaddr, 0, 0, 0, 0);
IP4_ADDR(&st_netmask, 0, 0, 0, 0);
netifapi_netif_set_addr(lwipNetif, &st_ipaddr, &st_netmask, &st_gw);
}
static void WpaEventCB(const hi_wifi_event *hisiEvent)
{
if (hisiEvent == NULL)
return;
IOT_LOG_DEBUG("EVENT_TYPE:%d", hisiEvent->event);
switch (hisiEvent->event) {
case HI_WIFI_EVT_SCAN_DONE:
IOT_LOG_DEBUG("WiFi: Scan results available");
gScanDone = HI_TRUE;
break;
case HI_WIFI_EVT_CONNECTED:
IOT_LOG_DEBUG("WiFi: Connected");
netifapi_dhcp_start(gLwipNetif);
wifiStatus = HI_WIFI_EVT_CONNECTED;
if (wifiSecondConnected) {
wifiSecondConnected = HI_FALSE;
wifiFirstConnecting = WIFI_CONNECT_STATUS;
}
break;
case HI_WIFI_EVT_DISCONNECTED:
IOT_LOG_DEBUG("WiFi: Disconnected");
netifapi_dhcp_stop(gLwipNetif);
StaResetAddr(gLwipNetif);
wifiStatus = HI_WIFI_EVT_DISCONNECTED;
wifiReconnected(cnetId);
break;
case HI_WIFI_EVT_WPS_TIMEOUT:
IOT_LOG_DEBUG("WiFi: wps is timeout");
wifiStatus = HI_WIFI_EVT_WPS_TIMEOUT;
break;
default:
break;
}
}
static int StaStartConnect(void)
{
int ret;
errno_t rc;
hi_wifi_assoc_request assoc_req = {0};
/* copy SSID to assoc_req */
rc = memcpy_s(assoc_req.ssid, HI_WIFI_MAX_SSID_LEN + 1, CONFIG_AP_SSID, strlen(CONFIG_AP_SSID));
if (rc != EOK) {
return -1;
}
/*
* OPEN mode
* for WPA2-PSK mode:
* set assoc_req.auth as HI_WIFI_SECURITY_WPA2PSK,
* then memcpy(assoc_req.key, "12345678", 8).
*/
assoc_req.auth = HI_WIFI_SECURITY_WPA2PSK;
rc = memcpy_s(assoc_req.key, HI_WIFI_MAX_KEY_LEN + 1, CONFIG_AP_PWD, strlen(CONFIG_AP_PWD));
if (rc != EOK) {
return -1;
}
ret = hi_wifi_sta_connect(&assoc_req);
if (ret != HISI_OK) {
return -1;
}
return 0;
}
static void PrintLinkedInfo(WifiLinkedInfo* info)
{
int ret = 0;
if (!info) {
return;
}
static char macAddress[32] = {0};
unsigned char* mac = info->bssid;
if (snprintf_s(macAddress, sizeof(macAddress) + 1, sizeof(macAddress), "%02X:%02X:%02X:%02X:%02X:%02X",
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]) < 0) { /* mac地址从0,1,2,3,4,5位 */
return;
}
}
static void OnWifiConnectionChanged(int state, WifiLinkedInfo* info)
{
if (!info) {
return;
}
printf("%s %d, state = %d, info = \r\n", __FUNCTION__, __LINE__, state);
PrintLinkedInfo(info);
if (state == WIFI_STATE_AVALIABLE) {
g_connected = 1;
} else {
g_connected = 0;
}
}
static void OnWifiScanStateChanged(int state, int size)
{
printf("%s %d, state = %X, size = %d\r\n", __FUNCTION__, __LINE__, state, size);
}
static WifiEvent g_defaultWifiEventListener = {
.OnWifiConnectionChanged = OnWifiConnectionChanged,
.OnWifiScanStateChanged = OnWifiScanStateChanged
};
static int WifiStartSta(void)
{
WifiDeviceConfig apConfig = {0};
strcpy_s(apConfig.ssid, sizeof(CONFIG_AP_SSID), CONFIG_AP_SSID);
strcpy_s(apConfig.preSharedKey, sizeof(CONFIG_AP_PWD), CONFIG_AP_PWD);
apConfig.securityType = WIFI_SEC_TYPE_PSK;
WifiErrorCode errCode;
int netId = -1;
errCode = RegisterWifiEvent(&g_defaultWifiEventListener);
printf("RegisterWifiEvent: %d\r\n", errCode);
errCode = EnableWifi();
printf("EnableWifi: %d\r\n", errCode);
errCode = AddDeviceConfig(&apConfig, &netId);
printf("AddDeviceConfig: %d\r\n", errCode);
g_connected = 0;
errCode = ConnectTo(netId);
printf("ConnectTo(%d): %d\r\n", netId, errCode);
while (!g_connected) { // wait until connect to AP
osDelay(10); /* 10: os sleep 10ms */
}
printf("g_connected: %d\r\n", g_connected);
g_iface = netifapi_netif_find("wlan0");
if (g_iface) {
err_t ret = netifapi_dhcp_start(g_iface);
printf("netifapi_dhcp_start: %d\r\n", ret);
osDelay(100); // 100: os sleep 100ms wait DHCP server give me IP
ret = netifapi_netif_common(g_iface, dhcp_clients_info_show, NULL);
printf("netifapi_netif_common: %d\r\n", ret);
}
return netId;
}
void WifiStopSta(int netId)
{
int stopNetId = netId;
if (g_iface) {
err_t ret = netifapi_dhcp_stop(g_iface);
printf("netifapi_dhcp_stop: %d\r\n", ret);
}
WifiErrorCode errCode = Disconnect(); // disconnect with your AP
printf("Disconnect: %d\r\n", errCode);
errCode = UnRegisterWifiEvent(&g_defaultWifiEventListener);
printf("UnRegisterWifiEvent: %d\r\n", errCode);
RemoveDevice(stopNetId); // remove AP config
printf("RemoveDevice: %d\r\n", errCode);
errCode = DisableWifi();
printf("DisableWifi: %d\r\n", errCode);
}
void WifiStaReadyWait(void)
{
ip4_addr_t ipAddr;
ip4_addr_t ipAny;
IP4_ADDR(&ipAny, 0, 0, 0, 0);
IP4_ADDR(&ipAddr, 0, 0, 0, 0);
cnetId = WifiStartSta();
IOT_LOG_DEBUG("wifi sta dhcp done");
}

@ -0,0 +1,39 @@
# Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
# 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.
static_library("appDemoIot") {
sources = [
"app_demo_iot.c",
"cjson_init.c",
"iot_hmac.c",
"iot_log.c",
"iot_main.c",
"iot_profile.c",
"iot_sta.c",
]
include_dirs = [
"./",
"//utils/native/lite/include",
"//kernel/liteos_m/kal/cmsis",
"//base/iot_hardware/peripheral/interfaces/kits",
"//device/soc/hisilicon/hi3861v100/sdk_liteos/third_party/lwip_sack/include/lwip",
"//third_party/cJSON",
"//device/soc/hisilicon/hi3861v100/sdk_liteos/third_party/mbedtls/include/mbedtls",
"//foundation/communication/wifi_lite/interfaces/wifiservice",
"//device/soc/hisilicon/hi3861v100/sdk_liteos/third_party/paho.mqtt.c/include/mqtt",
"//device/soc/hisilicon/hi3861v100/sdk_liteos/third_party/libcoap/include/coap2",
]
defines = [ "WITH_LWIP" ]
}

@ -0,0 +1,226 @@
# 腾讯云的微信小程序开发及Hi3861板端互联
## 硬件环境搭建
- 硬件要求Hi3861V100核心板、扩展板硬件搭建如下图所示。
- [Hi3861V100核心板参考HiSpark_WiFi_IoT智能开发套件_原理图硬件资料\原理图\HiSpark_WiFi-IoT_Hi3861_CH340G_VER.B.pdf](http://gitee.com/hihope_iot/embedded-race-hisilicon-track-2022/blob/master/%E7%A1%AC%E4%BB%B6%E8%B5%84%E6%96%99/HiSpark_WiFi_IoT%E6%99%BA%E8%83%BD%E5%AE%B6%E5%B1%85%E5%BC%80%E5%8F%91%E5%A5%97%E4%BB%B6_%E5%8E%9F%E7%90%86%E5%9B%BE.rar)
- [扩展板参考HiSpark_WiFi_IoT智能开发套件_原理图硬件资料\原理图\HiSpark_WiFi-IoT_Hi3861_CH340G_VER.B.pdf](http://gitee.com/hihope_iot/embedded-race-hisilicon-track-2022/blob/master/%E7%A1%AC%E4%BB%B6%E8%B5%84%E6%96%99/HiSpark_WiFi_IoT%E6%99%BA%E8%83%BD%E5%AE%B6%E5%B1%85%E5%BC%80%E5%8F%91%E5%A5%97%E4%BB%B6_%E5%8E%9F%E7%90%86%E5%9B%BE.rar)
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/260.jpg)
## 软件介绍
- 1.代码目录结构及相应接口功能介绍
```
vendor_hisilicon/hispark_pegasus/demo/iottencent_demo
├── app_demo_iot.c #IoSetPull();IoSetFunc();TaskMsleep()。
├── BUILD.gn # BUILD.gn文件由三部分内容目标、源文件、头文件路径构成,开发者根据需要填写,static_library中指定业务模块的编译结果为静态库文件led_example开发者根据实际情况完成填写。
| sources中指定静态库.a所依赖的.c文件及其路径若路径中包含"//"则表示绝对路径(此处为代码根路径),若不包含"//"则表示相对路径。include_dirs中指定source所需要依赖的.h文件路径。
├── cjson_init.c #
├── iot_config.h #
├── iot_hmac.c #
├── iot_hmac.h #
├── iot_log.c #
├── iot_log.h #
├── iot_main.c #
├── iot_main.h #
├── iot_profile.c #
├── iot_sta.c #
└── iot_profile.h #
```
- 2.Mqtt协议第三方软件与腾讯云之间的通信
2.1 浏览器搜索腾讯云,在腾讯云界面创建产品和设备,登录腾讯云后搜索“物联网通信”,进入页面后,物联网通信选择立即使用。进入页面后,选择产品列表栏->创建新产品->产品名称xxx,认证方式:密钥认证,点击确定。
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8717.png)
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8720.png)
2.2 在产品列表栏进入刚刚创建的新产品->设备列表->添加设备->创建新设备:设备名称,设备备注(选填),使用物联网通信提供密钥->保存->复制保存生成的密钥->开始管理设备(可以看到设备相应信息)。
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8721.png)
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8722.png)
2.3 添加设备,同时查看设备相应信息。
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%BE%AE%E4%BF%A1%E5%B0%8F%E7%A8%8B%E5%BA%8F/800.png)
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%BE%AE%E4%BF%A1%E5%B0%8F%E7%A8%8B%E5%BA%8F/801.png)
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%BE%AE%E4%BF%A1%E5%B0%8F%E7%A8%8B%E5%BA%8F/802.png)
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%BE%AE%E4%BF%A1%E5%B0%8F%E7%A8%8B%E5%BA%8F/803.png)
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%BE%AE%E4%BF%A1%E5%B0%8F%E7%A8%8B%E5%BA%8F/804.png)
2.4 返回设备列表可以看到设备并未激活,接下来激活设备;下载[MQTT.fx-1.7.1 ](https://www.jensd.de/wordpress/?p=2746)下载完成后打开工具点击设备图标进入到设备界面配置ClientIDusername,password 等参数。
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%BE%AE%E4%BF%A1%E5%B0%8F%E7%A8%8B%E5%BA%8F/806.png)
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8730.png)
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8731.png)
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8732.png)
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8733.png)
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8734.png)
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8735.png)
2.5 完成2.3步骤后可以在腾讯云设备列表里面看到设备状态显示已激活开始腾讯云与MQTT工具之间的通信。
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8736.png)
2.6 MQTT.fx-1.7.1工具订阅腾讯云的topic腾讯云下发指令。
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8737.png)
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8738.png)
2.7 在腾讯云网页端点击“在线调试”。
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8739.png)
2.8 可以在MQTT.fx-1.7.1工具中看到腾讯云网页端发过来的消息。
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8740.png)
2.9 MQTT.fx-1.7.1工具发布腾讯云到的topic在设备影子中查看发布到腾讯云的消息。
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8741.png)
```
{
"type":"update",
"state":{
"reported":{
"light":1,
"motor":1,
"temperature":25,
"humidity":60,
"light_intensity":50
}
},
"version":0,
"clientToken":"clientToken"
}
```
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8742.png)
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8743.png)
- 3.微信小程序开发环境搭建及与腾讯云之间通信
3.1 注册申请小程序账号https://mp.weixin.qq.com/wxopen/waregister?action=step1。
3.2 登录小程序后选择IOT字样的账号在“开发”->“开发设置”页面可以看到小程序的AppID如下图所示详情请查看微信官方文档
https://developers.weixin.qq.com/miniprogram/dev/framework/quickstart/getstart.html#%E7%94%B3%E8%AF%B7%E5%B8%90%E5%8F%B7。
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8744.png)
3.3 开发者工具下载与安装https://developers.weixin.qq.com/miniprogram/dev/devtools/download.html。
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8745.png)
3.4 下载安装完成后,打开微信开发工具,导入提供的微信小程序软件包[获取微信小程序代码](https://gitee.com/leo593362220/Hi3861OpenHarmony)。并填入自己的APPID,后端服务选择微信云开发。
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%87102.jpg)
3.5 使用微信开发者工具打开工程后需要修改project.config.json文件中appid,projectname修改成自己的。
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8747.png)
3.6 获取secretId和secretKey在腾讯云->产品列表->搜索栏搜索访问密钥->访问密钥->继续使用->可以看到secretId和secretKey复制在xxxx.txt文件后面需要。
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8749.png)
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8750.png)
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8751.png)
3.7 环境ID配置并获取环境ID,复制在xxx.txt文件后面需要。
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8752.png)
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8753.png)
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8754.png)
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8755.png)![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8747.png)
3.8 需要修改app.js文件中productId腾讯云上设备信息上产品ID,deviceName腾讯云上设备信息上产品名称,secretId和secretKey(3.6步骤获取到的secretId和secretKey)env3.7步骤获取到的环境ID
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8748.png)
3.9 配置当前云环境
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8756.png)
注意:第一次部署环境,图片里面的上传并部署会变成新建并部署。
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8757.png)
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/228.jpg)
等待大概1分钟左右直到出现上传云函数成功注意上传并部署由于网络问题可能会失败看到上传云函数等字样代表上传部署成功这里以iothub-publish为例
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8758.png)
3.10 环境部署完成后,点击编译,然后真机调试会出现如下界面,上面两个都要出现
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8761.png)
- 4.Hi3861V100与微信小程序之间通信
- 将源码./vendor/hisilicon/hispark_pegasus/demo目录下的iottencent_demo整个文件夹及内容复制到源码./applications/sample/wifi-iot/app/下。
```
.
└── applications
└── sample
└── wifi-iot
└── app
└──iottencent_demo
└── 代码
```
- 配置源码./applications/sample/wifi-iot/app/iottencent_demo/iot_config.h中CONFIG_AP_SSIDCONFIG_AP_PWD为WiFi名称和WiFi密码。CONFIG_USER_ID为腾讯云设备信息上MQTT UsernameCONFIG_USER_PWD为腾讯云上设备的MQTT Password,CN_CLIENTID为腾讯云上clientID。
```
#define CONFIG_AP_SSID "XXXXXXXX" // WIFI SSID
#define CONFIG_AP_PWD "XXXXX" // WIFI PWD
/* Tencent iot Cloud user ID , password */
#define CONFIG_USER_ID "XXXXXXXXXXXXX"
#define CONFIG_USER_PWD "XXXXXXXXXXXX"
#define CN_CLIENTID "xxxxxxxx" // Tencent cloud ClientID format: Product ID + device name
```
- 更改源码./applications/sample/wifi-iot/app/iottencent_demo/iot_main.c文件中搜索g_defaultSubscribeTopic字段将腾讯云上的Topic列表中自定义Topic添加到字段里。
```
static const char *g_defaultSubscribeTopic[] = {
"76VQ4ZASTL/mqtt/data",
"76VQ4ZASTL/mqtt/event",
"76VQ4ZASTL/mqtt/control",
};
```
- 更改源码./applications/sample/wifi-iot/app/iottencent_demo/iot_profile.c文件中搜索CN_PROFILE_TOPICFMT_TOPIC字段将腾讯云上的产品名设备名称添加到字段里。
```
#define CN_PROFILE_TOPICFMT_TOPIC "$shadow/operation/xxxxx/XXXX" //xxxx为产品名和设备名称76VQ4ZASTL
```
- 修改源码./applications/sample/wifi-iot/app/BUILD.gn文件在features字段中增加索引使目标模块参与编译。features字段指定业务模块的路径和目标,features字段配置如下。
```
import("//build/lite/config/component/lite_component.gni")
lite_component("app") {
features = [
"iottencent_demo:appDemoIot",
]
}
```
- 工程相关配置完成后,然后编译。
- 5.烧录
- 编译成功后点击DevEco Home->配置工程->hi3861->upload_port->选择对应串口端口号->选择upload_protocol->选择hiburn-serial->点击save保存在保存成功后点击upload进行烧录出现connecting, please reset device..字样复位开发板等待烧录完成。烧录成功后再次点击Hi3861核心板上的“RST”复位键此时开发板的系统会运行起来。
- 注意:一定要断开MQTT工具的连接。
- 微信小程序上选择已连接Wifi,跳过配网->云端互联->看到设备互联界面->点击刷新按钮,运行结果出现如下图代表成功,点击照明,主板灯会亮。
![输入图片说明](https://gitee.com/asd1122/tupian/raw/master/%E5%9B%BE%E7%89%87/%E5%9B%BE%E7%89%8762.png)

@ -0,0 +1,178 @@
/*
* Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
* 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.
*/
#include <hi_task.h>
#include <string.h>
#include <hi_wifi_api.h>
#include <hi_mux.h>
#include <hi_io.h>
#include <hi_gpio.h>
#include "iot_config.h"
#include "iot_log.h"
#include "iot_main.h"
#include "iot_profile.h"
#include "ohos_init.h"
#include "cmsis_os2.h"
/* attribute initiative to report */
#define TAKE_THE_INITIATIVE_TO_REPORT
#define ONE_SECOND (1000)
/* oc request id */
#define CN_COMMADN_INDEX "commands/request_id="
#define WECHAT_SUBSCRIBE_LIGHT "light"
#define WECHAT_SUBSCRIBE_LIGHT_ON_STATE "1"
#define WECHAT_SUBSCRIBE_LIGHT_OFF_STATE "0"
int g_ligthStatus = -1;
typedef void (*FnMsgCallBack)(hi_gpio_value val);
typedef struct FunctionCallback {
hi_bool stop;
hi_u32 conLost;
hi_u32 queueID;
hi_u32 iotTaskID;
FnMsgCallBack msgCallBack;
}FunctionCallback;
FunctionCallback g_functinoCallback;
/* CPU Sleep time Set */
unsigned int TaskMsleep(unsigned int ms)
{
if (ms <= 0) {
return HI_ERR_FAILURE;
}
return hi_sleep((hi_u32)ms);
}
static void DeviceConfigInit(hi_gpio_value val)
{
hi_io_set_func(HI_IO_NAME_GPIO_9, HI_IO_FUNC_GPIO_9_GPIO);
hi_gpio_set_dir(HI_GPIO_IDX_9, HI_GPIO_DIR_OUT);
hi_gpio_set_ouput_val(HI_GPIO_IDX_9, val);
}
static int DeviceMsgCallback(FnMsgCallBack msgCallBack)
{
g_functinoCallback.msgCallBack = msgCallBack;
return 0;
}
static void wechatControlDeviceMsg(hi_gpio_value val)
{
DeviceConfigInit(val);
}
// < this is the callback function, set to the mqtt, and if any messages come, it will be called
// < The payload here is the json string
static void DemoMsgRcvCallBack(int qos, const char *topic, const char *payload)
{
IOT_LOG_DEBUG("RCVMSG:QOS:%d TOPIC:%s PAYLOAD:%s\r\n", qos, topic, payload);
/* 云端下发命令后,板端的操作处理 */
if (strstr(payload, WECHAT_SUBSCRIBE_LIGHT) != NULL) {
if (strstr(payload, WECHAT_SUBSCRIBE_LIGHT_OFF_STATE) != NULL) {
wechatControlDeviceMsg(HI_GPIO_VALUE1);
g_ligthStatus = HI_FALSE;
} else {
wechatControlDeviceMsg(HI_GPIO_VALUE0);
g_ligthStatus = HI_TRUE;
}
}
return HI_NULL;
}
/* publish sample */
hi_void IotPublishSample(void)
{
/* reported attribute */
WeChatProfile weChatProfile = {
.subscribeType = "type",
.status.subState = "state",
.status.subReport = "reported",
.status.reportVersion = "version",
.status.Token = "clientToken",
/* report motor */
.reportAction.subDeviceActionMotor = "motor",
.reportAction.motorActionStatus = 0, /* 0 : motor off */
/* report temperature */
.reportAction.subDeviceActionTemperature = "temperature",
.reportAction.temperatureData = 30, /* 30 :temperature data */
/* report humidity */
.reportAction.subDeviceActionHumidity = "humidity",
.reportAction.humidityActionData = 70, /* humidity data */
/* report light_intensity */
.reportAction.subDeviceActionLightIntensity = "light_intensity",
.reportAction.lightIntensityActionData = 60, /* 60 : light_intensity */
};
/* report light */
if (g_ligthStatus == HI_TRUE) {
weChatProfile.reportAction.subDeviceActionLight = "light";
weChatProfile.reportAction.lightActionStatus = 1; /* 1: light on */
} else if (g_ligthStatus == HI_FALSE) {
weChatProfile.reportAction.subDeviceActionLight = "light";
weChatProfile.reportAction.lightActionStatus = 0; /* 0: light off */
} else {
weChatProfile.reportAction.subDeviceActionLight = "light";
weChatProfile.reportAction.lightActionStatus = 0; /* 0: light off */
}
/* profile report */
IoTProfilePropertyReport(CONFIG_USER_ID, &weChatProfile);
}
// < this is the demo main task entry,here we will set the wifi/cjson/mqtt ready and
// < wait if any work to do in the while
static hi_void *DemoEntry(const char *arg)
{
WifiStaReadyWait();
cJsonInit();
IoTMain();
/* 云端下发回调 */
IoTSetMsgCallback(DemoMsgRcvCallBack);
/* 主动上报 */
#ifdef TAKE_THE_INITIATIVE_TO_REPORT
while (1) {
/* 用户可以在这调用发布函数进行发布,需要用户自己写调用函数 */
IotPublishSample(); // 发布例程
#endif
TaskMsleep(ONE_SECOND);
}
return NULL;
}
// < This is the demo entry, we create a task here,
// and all the works has been done in the demo_entry
#define CN_IOT_TASK_STACKSIZE 0x1000
#define CN_IOT_TASK_PRIOR 25
#define CN_IOT_TASK_NAME "IOTDEMO"
static void AppDemoIot(void)
{
osThreadAttr_t attr;
IoTWatchDogDisable();
attr.name = "IOTDEMO";
attr.attr_bits = 0U;
attr.cb_mem = NULL;
attr.cb_size = 0U;
attr.stack_mem = NULL;
attr.stack_size = CN_IOT_TASK_STACKSIZE;
attr.priority = CN_IOT_TASK_PRIOR;
if (osThreadNew((osThreadFunc_t)DemoEntry, NULL, &attr) == NULL) {
printf("[mqtt] Falied to create IOTDEMO!\n");
}
}
SYS_RUN(AppDemoIot);

@ -0,0 +1,38 @@
/*
* Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
* 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.
*/
#include <stdint.h>
#include <cJSON.h>
#include <hi_mem.h>
static void *cJsonMalloc(size_t sz)
{
return hi_malloc(0, sz);
}
static void cJsonFree(const char *p)
{
hi_free(0, p);
}
void cJsonInit(void)
{
cJSON_Hooks hooks;
hooks.malloc_fn = cJsonMalloc;
hooks.free_fn = cJsonFree;
cJSON_InitHooks(&hooks);
return;
}

@ -0,0 +1,31 @@
/*
* Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
* 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 IOT_CONFIG_H
#define IOT_CONFIG_H
// <CONFIG THE LOG
/* if you need the iot log for the development , please enable it, else please comment it */
#define CONFIG_LINKLOG_ENABLE 1
// < CONFIG THE WIFI
/* Please modify the ssid and pwd for the own */
#define CONFIG_AP_SSID "Sidi_iPhone" // WIFI SSID
#define CONFIG_AP_PWD "12345678" // WIFI PWD
/* Tencent iot Cloud user ID , password */
#define CONFIG_USER_ID "YT32IOSCALHi38611_mqtt;12010126;41883;1663689600"
#define CONFIG_USER_PWD "b4168d5d4b65898e6984346c81ad13e1b3f112ab7ce46f65cf29455f4c9e18e8;hmacsha256"
#define CN_CLIENTID "YT32IOSCALHi38611_mqtt" // Tencent cloud ClientID format: Product ID + device name
#endif

@ -0,0 +1,95 @@
/*
* Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
* 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.
*/
/**
* This file make use the hmac to make mqtt pwd.
* The method is use the date string to hash the device passwd
* Take care that this implement depends on the hmac of the mbedtls
*/
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include <stdio.h>
#include "md.h"
#include "md_internal.h"
#define CN_HMAC256_LEN_MAX (65)
#define CN_HMAC256_LEN 32
#define RIGHT_MOVE_BIT_4 (4)
#define NUMBER_9 (9)
#define DECIMAL_BASE (10)
#define STRING_LEN_TIMES (2)
#define LEN_TIMES (2)
#define OFFSET (1)
// make a byte to 2 ascii hex
static int byte2hexstr(unsigned char *bufin, int len, char *bufout)
{
int i = 0;
unsigned char tmp_l = 0x0;
unsigned char tmp_h = 0;
if ((bufin == NULL)||(len <= 0)||(bufout == NULL)) {
return -1;
}
for (i = 0; i < len; i++) {
tmp_h = (bufin[i] >> RIGHT_MOVE_BIT_4) & 0X0F;
tmp_l = bufin[i] & 0x0F;
bufout[STRING_LEN_TIMES * i] = (tmp_h > NUMBER_9) ?
(tmp_h - DECIMAL_BASE + 'a'):(tmp_h +'0');
bufout[STRING_LEN_TIMES * i + OFFSET] = (tmp_l > NUMBER_9) ?
(tmp_l - DECIMAL_BASE + 'a'):(tmp_l +'0');
}
bufout[STRING_LEN_TIMES * len] = '\0';
return 0;
}
int HmacGeneratePwd(const unsigned char *content, int contentLen, const unsigned char *key,
int keyLen, unsigned char *buf)
{
int ret = -1;
mbedtls_md_context_t mbedtls_md_ctx;
const mbedtls_md_info_t *md_info;
unsigned char hash[CN_HMAC256_LEN];
if ((key == NULL)||(content == NULL)||(buf == NULL)||
(keyLen == 0)||(contentLen == 0)||
(CN_HMAC256_LEN_MAX < (CN_HMAC256_LEN * LEN_TIMES + OFFSET))) {
return ret;
}
md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA256);
if ((md_info == NULL)||((size_t)md_info->size > CN_HMAC256_LEN)) {
return ret;
}
mbedtls_md_init(&mbedtls_md_ctx);
ret = mbedtls_md_setup(&mbedtls_md_ctx, md_info, 1);
if (ret != 0) {
mbedtls_md_free(&mbedtls_md_ctx);
return ret;
}
(void)mbedtls_md_hmac_starts(&mbedtls_md_ctx, key, keyLen);
(void)mbedtls_md_hmac_update(&mbedtls_md_ctx, content, contentLen);
(void)mbedtls_md_hmac_finish(&mbedtls_md_ctx, hash);
// <transfer the hash code to the string mode
ret = byte2hexstr(hash, CN_HMAC256_LEN, (char *)buf);
if (ret != 0) {
return ret;
}
return ret;
}

@ -0,0 +1,32 @@
/*
* Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
* 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 IOT_HMAC_H
#define IOT_HMAC_H
/**
* This function used to generate the passwd for the mqtt to connect the HW IoT platform
* @param content: This is the content for the hmac,
* and usually it is the device passwd set or get from the Iot Platform
* @param content_len: The length of the content
* @param key: This is the key for the hmac, and usually it is the time used in the client_id:
* the format isyearmonthdatehour:like 1970010100
* @param key_len: The length of the key
* @param buf: used to storage the hmac code
* @param buf_len:the buf length
* @return:0 success while others failed
*/
int HmacGeneratePwd(const unsigned char *content, int contentLen, const unsigned char *key,
int keyLen, unsigned char *buf);
#endif

@ -0,0 +1,50 @@
/*
* Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
* 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.
*/
#include <iot_log.h>
static EnIotLogLevel gIoTLogLevel = EN_IOT_LOG_LEVEL_TRACE;
static const char *gIoTLogLevelNames[] = {
"TRACE",
"DEBUG",
"INFO ",
"WARN ",
"ERROR",
"FATAL"
};
int IoTLogLevelSet(EnIotLogLevel level)
{
int ret = -1;
if (level < EN_IOT_LOG_LEVEL_MAX) {
gIoTLogLevel = level;
ret = 0;
}
return ret;
}
EnIotLogLevel IoTLogLevelGet(void)
{
return gIoTLogLevel;
}
const char *IoTLogLevelGetName(EnIotLogLevel logLevel)
{
if (logLevel >= EN_IOT_LOG_LEVEL_MAX) {
return "NULL ";
} else {
return gIoTLogLevelNames[logLevel];
}
}

@ -0,0 +1,122 @@
/*
* Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
* 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 IOT_LOG_H_
#define IOT_LOG_H_
/**
* @brief:this defines for the log module,
* and IOT_LOG_TRACE/IOT_LOG_DEBUG will not participate the compile in the release version
*
*
* */
typedef enum {
// < this is used as the trace function,like the function enter and function out
EN_IOT_LOG_LEVEL_TRACE = 0,
// < this is used as the debug, you could add any debug as you wish
EN_IOT_LOG_LEVEL_DEBUG,
// < which means it is import message, and you should known
EN_IOT_LOG_LEVEL_INFO,
// < this is used as the executed result,which means the status is not what we expected
EN_IOT_LOG_LEVEL_WARN,
// < this is used as the executed result,which means the status is not what we expected
EN_IOT_LOG_LEVEL_ERROR,
// < this is used as the parameters input for the api interface, which could not accepted
EN_IOT_LOG_LEVEL_FATAL,
EN_IOT_LOG_LEVEL_MAX,
}EnIotLogLevel;
/**
* @brief:use this function to get the current output log
*
* @return: the current output mask log, defined by en_iot_log_level_t
* */
EnIotLogLevel IoTLogLevelGet(void);
/**
* @brief: use this function to get the debug level name
*
* @parameter[in]:level, the level to get
*
* @return: the mapped level name
* */
const char *IoTLogLevelGetName(EnIotLogLevel logLevel);
/**
* @brief:use this function to set the current output log
*
* @parameter[in] level:defined by en_iot_log_level_t
*
* @return: 0 success while -1 failed
* */
int IoTLogLevelSet(EnIotLogLevel level);
/*
* @brief: this is a weak function ,and you could rewrite one
*
* @param fmt: same use as the fmt for printf
*
* @param unfixed: same use for printf
*
* @return: don't care about it
*
* @attention: and the components should not call this function directly, you'd better
*
* call IOT_LOG groups
*
* */
#ifndef IOT_PRINT
#define IOT_PRINT(fmt, ...) \
do \
{ \
printf(fmt, ##__VA_ARGS__); \
}while (0)
#endif
#ifdef CONFIG_LINKLOG_ENABLE
#define IOT_LOG(level, fmt, ...) \
do \
{ \
IOT_PRINT("[%s][%s] " fmt "\r\n", \
IoTLogLevelGetName((level)), __FUNCTION__, ##__VA_ARGS__); \
} while (0)
#define IOT_LOG_TRACE(fmt, ...) \
do \
{ \
if ((EN_IOT_LOG_LEVEL_TRACE) >= IoTLogLevelGet()) \
{ \
IOT_LOG(EN_IOT_LOG_LEVEL_TRACE, fmt, ##__VA_ARGS__); \
} \
} while (0)
#define IOT_LOG_DEBUG(fmt, ...) \
do \
{ \
if ((EN_IOT_LOG_LEVEL_DEBUG) >= IoTLogLevelGet()) \
{ \
IOT_LOG(EN_IOT_LOG_LEVEL_DEBUG, fmt, ##__VA_ARGS__); \
} \
} while (0)
#else
#define IOT_LOG(level, fmt, ...)
#define IOT_LOG_TRACE(fmt, ...)
#define IOT_LOG_DEBUG(fmt, ...)
#endif
#define IOT_LOG_TRACE(fmt, ...) IOT_LOG(EN_IOT_LOG_LEVEL_TRACE, fmt, ##__VA_ARGS__)
#define IOT_LOG_INFO(fmt, ...) IOT_LOG(EN_IOT_LOG_LEVEL_INFO, fmt, ##__VA_ARGS__)
#define IOT_LOG_WARN(fmt, ...) IOT_LOG(EN_IOT_LOG_LEVEL_WARN, fmt, ##__VA_ARGS__)
#define IOT_LOG_ERROR(fmt, ...) IOT_LOG(EN_IOT_LOG_LEVEL_ERROR, fmt, ##__VA_ARGS__)
#define IOT_LOG_FATAL(fmt, ...) IOT_LOG(EN_IOT_LOG_LEVEL_FATAL, fmt, ##__VA_ARGS__)
#endif /* IOT_LOG_H_ */

@ -0,0 +1,315 @@
/*
* Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
* 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.
*/
/**
* STEPS:
* 1, CONNECT TO THE IOT SERVER
* 2, SUBSCRIBE THE DEFAULT TOPIC
* 3, WAIT FOR ANY MESSAGE COMES OR ANY MESSAGE TO SEND
*/
#include <securec.h>
#include <hi_task.h>
#include <hi_msg.h>
#include <hi_mem.h>
#include <string.h>
#include <stdbool.h>
#include "iot_config.h"
#include "iot_log.h"
#include "iot_hmac.h"
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_watchdog.h"
#include "MQTTClient.h"
#include "iot_errno.h"
#include "iot_main.h"
// < this is the configuration head
#define CN_IOT_SERVER "tcp://106.55.124.154:1883" // Tencent iot cloud address
#define CONFIG_COMMAND_TIMEOUT 10000L
#define CN_KEEPALIVE_TIME 50
#define CN_CLEANSESSION 1
#define CN_HMAC_PWD_LEN 65 // < SHA256 IS 32 BYTES AND END APPEND '\0'
#define CN_EVENT_TIME "1970000100"
#define CN_CLIENTID_FMT "%s_0_0_%s" // < This is the cient ID format, deviceID_0_0_TIME
#define CN_QUEUE_WAITTIMEOUT 1000
#define CN_QUEUE_MSGNUM 16
#define CN_QUEUE_MSGSIZE (sizeof(hi_pvoid))
#define CN_TASK_PRIOR 28
#define CN_TASK_STACKSIZE 0X2000
#define CN_TASK_NAME "IoTMain"
typedef enum {
EN_IOT_MSG_PUBLISH = 0,
EN_IOT_MSG_RECV,
}EnIotMsg;
typedef struct {
EnIotMsg type;
int qos;
const char *topic;
const char *payload;
}IoTMsg_t;
typedef struct {
bool stop;
unsigned int conLost;
unsigned int queueID;
unsigned int iotTaskID;
fnMsgCallBack msgCallBack;
MQTTClient_deliveryToken tocken;
}IotAppCb_t;
static IotAppCb_t gIoTAppCb;
static const char *gDefaultSubscribeTopic[] = {
/* Tencent iot cloud topic */
"YT32IOSCAL/Hi38611_mqtt/data",
"YT32IOSCAL/Hi38611_mqtt/event",
"YT32IOSCAL/Hi38611_mqtt/control",
};
//#define CN_TOPIC_SUBSCRIBE_NUM (sizeof(gDefaultSubscribeTopic) / sizeof(const char *))
#define CN_TOPIC_SUBSCRIBE_NUM 3
static int MsgRcvCallBack(char *context, char *topic, int topicLen, MQTTClient_message *message)
{
IoTMsg_t *msg;
char *buf;
unsigned int bufSize;
int topiLen = topicLen;
if (topiLen == 0) {
topiLen = strlen(topic);
}
bufSize = topiLen + 1 + message->payloadlen + 1 + sizeof(IoTMsg_t);
buf = hi_malloc(0, bufSize);
if (buf != NULL) {
msg = (IoTMsg_t *)buf;
buf += sizeof(IoTMsg_t);
bufSize -= sizeof(IoTMsg_t);
msg->qos = message->qos;
msg->type = EN_IOT_MSG_RECV;
(void)memcpy_s(buf, bufSize, topic, topiLen);
buf[topiLen] = '\0';
msg->topic = buf;
buf += topiLen + 1;
bufSize -= (topiLen + 1);
(void)memcpy_s(buf, bufSize, message->payload, message->payloadlen);
buf[message->payloadlen] = '\0';
msg->payload = buf;
IOT_LOG_DEBUG("RCVMSG:QOS:%d TOPIC:%s PAYLOAD:%s\r\n", msg->qos, msg->topic, msg->payload);
if (IOT_SUCCESS != osMessageQueuePut(gIoTAppCb.queueID, &msg, 0, CN_QUEUE_WAITTIMEOUT)) {
IOT_LOG_ERROR("Wrie queue failed\r\n");
hi_free(0, msg);
}
}
MQTTClient_freeMessage(&message);
MQTTClient_free(topic);
return 1;
}
// < when the connect lost and this callback will be called
static void ConnLostCallBack(char *context, char *cause)
{
IOT_LOG_DEBUG("Connection lost:caused by:%s\r\n", cause == NULL? "Unknown" : cause);
return;
}
static int MqttProcessQueueMsg(MQTTClient client, IoTMsg_t *msg, MQTTClient_message pubMsg)
{
int ret = 0;
switch (msg->type) {
case EN_IOT_MSG_PUBLISH:
pubMsg.payload = (void *)msg->payload;
pubMsg.payloadlen = (int)strlen(msg->payload);
pubMsg.qos = msg->qos;
pubMsg.retained = 0;
ret = MQTTClient_publishMessage(client, msg->topic, &pubMsg, &gIoTAppCb.tocken);
if (ret != MQTTCLIENT_SUCCESS) {
IOT_LOG_ERROR("MSGSEND:failed\r\n");
}
IOT_LOG_DEBUG("MSGSEND:SUCCESS\r\n");
gIoTAppCb.tocken++;
break;
case EN_IOT_MSG_RECV:
if (gIoTAppCb.msgCallBack != NULL) {
gIoTAppCb.msgCallBack(msg->qos, msg->topic, msg->payload);
}
break;
default:
break;
}
}
// <use this function to deal all the comming message
static int ProcessQueueMsg(MQTTClient client)
{
unsigned int ret;
unsigned int msgSize;
IoTMsg_t *msg;
unsigned int timeout;
MQTTClient_message pubmsg = MQTTClient_message_initializer;
timeout = CN_QUEUE_WAITTIMEOUT;
do {
msg = NULL;
msgSize = sizeof(hi_pvoid);
ret = osMessageQueueGet(gIoTAppCb.queueID, &msg, &msgSize, timeout);
if (msg != NULL) {
IOT_LOG_DEBUG("QUEUEMSG:QOS:%d TOPIC:%s PAYLOAD:%s\r\n", msg->qos, msg->topic, msg->payload);
MqttProcessQueueMsg(client, msg, pubmsg);
hi_free(0, msg);
}
timeout = 0; // < continous to deal the message without wait here
} while (ret == IOT_SUCCESS);
return 0;
}
int MqttDestory(int ret, MQTTClient client)
{
if (ret != MQTTCLIENT_SUCCESS) {
MQTTClient_destroy(&client);
return -1;
}
return MQTTCLIENT_SUCCESS;
}
static void MainEntryProcess(void)
{
int rc = 0, subQos[CN_TOPIC_SUBSCRIBE_NUM] = {1};
MQTTClient client = NULL;
MQTTClient_connectOptions connOpts = MQTTClient_connectOptions_initializer;
char *clientID = CN_CLIENTID;
char *userID = CONFIG_USER_ID;
char *userPwd = hi_malloc(0, CN_HMAC_PWD_LEN);
if (userPwd == NULL) {
hi_free(0, clientID);
return;
}
userPwd = CONFIG_USER_PWD;
connOpts.keepAliveInterval = CN_KEEPALIVE_TIME;
connOpts.cleansession = CN_CLEANSESSION;
connOpts.username = userID;
connOpts.password = userPwd;
connOpts.MQTTVersion = MQTTVERSION_3_1_1;
IOT_LOG_DEBUG("CLIENTID:%s USERID:%s USERPWD:%s, IOTSERVER:%s\r\n",
clientID, userID, userPwd==NULL?"NULL" : userPwd, CN_IOT_SERVER);
rc = MQTTClient_create(&client, CN_IOT_SERVER, clientID, MQTTCLIENT_PERSISTENCE_NONE, NULL);
if (rc != MQTTCLIENT_SUCCESS) {
if (userPwd != NULL) {
hi_free(0, userPwd);
}
return;
}
rc = MQTTClient_setCallbacks(client, NULL, ConnLostCallBack, MsgRcvCallBack, NULL);
if (MqttDestory(rc, client) != MQTTCLIENT_SUCCESS) {
return;
}
rc = MQTTClient_connect(client, &connOpts);
if (MqttDestory(rc, client) != MQTTCLIENT_SUCCESS) {
return;
}
for (int i = 0; i < CN_TOPIC_SUBSCRIBE_NUM; i++) {
rc = MQTTClient_subscribeMany(client, CN_TOPIC_SUBSCRIBE_NUM,
(char *const *)gDefaultSubscribeTopic, (int *)&subQos[0]);
if (MqttDestory(rc, client) != MQTTCLIENT_SUCCESS) {
return;
}
}
IOT_LOG_DEBUG ("Connect success and Subscribe success\r\n");
while (MQTTClient_isConnected(client)) {
ProcessQueueMsg(client); // < do the job here
MQTTClient_yield(); // < make the keepalive done
}
MQTTClient_disconnect(client, CONFIG_COMMAND_TIMEOUT);
return;
}
/* MQTT processing entry */
static hi_void *MainEntry(char *arg)
{
(void)arg;
while (gIoTAppCb.stop == false) {
MainEntryProcess();
IOT_LOG_DEBUG("The connection lost and we will try another connect\r\n");
hi_sleep(1000); /* 1000: cpu sleep 1000ms */
}
return NULL;
}
int IoTMain(void)
{
unsigned int ret = 0;
hi_task_attr attr = {0};
gIoTAppCb.queueID = osMessageQueueNew(CN_QUEUE_MSGNUM, CN_QUEUE_MSGSIZE, NULL);
if (ret != IOT_SUCCESS) {
IOT_LOG_ERROR("Create the msg queue Failed\r\n");
}
attr.stack_size = CN_TASK_STACKSIZE;
attr.task_prio = CN_TASK_PRIOR;
attr.task_name = CN_TASK_NAME;
ret = hi_task_create(&gIoTAppCb.iotTaskID, &attr, MainEntry, NULL);
if (ret != IOT_SUCCESS) {
IOT_LOG_ERROR("Create the Main Entry Failed\r\n");
}
return 0;
}
int IoTSetMsgCallback(fnMsgCallBack msgCallback)
{
gIoTAppCb.msgCallBack = msgCallback;
return 0;
}
int IotSendMsg(int qos, const char *topic, const char *payload)
{
int rc = -1;
IoTMsg_t *msg;
char *buf;
unsigned int bufSize;
bufSize = strlen(topic) + 1 +strlen(payload) + 1 + sizeof(IoTMsg_t);
buf = hi_malloc(0, bufSize);
if (buf != NULL) {
msg = (IoTMsg_t *)buf;
buf += sizeof(IoTMsg_t);
bufSize -= sizeof(IoTMsg_t);
msg->qos = qos;
msg->type = EN_IOT_MSG_PUBLISH;
(void)memcpy_s(buf, bufSize, topic, strlen(topic));
buf[strlen(topic)] = '\0';
msg->topic = buf;
buf += strlen(topic) + 1;
bufSize -= (strlen(topic) + 1);
(void)memcpy_s(buf, bufSize, payload, strlen(payload));
buf[strlen(payload)] = '\0';
msg->payload = buf;
IOT_LOG_DEBUG("SNDMSG:QOS:%d TOPIC:%s PAYLOAD:%s\r\n", msg->qos, msg->topic, msg->payload);
if (IOT_SUCCESS != osMessageQueuePut(gIoTAppCb.queueID, &msg, 0, CN_QUEUE_WAITTIMEOUT)) {
IOT_LOG_ERROR("Write queue failed\r\n");
hi_free(0, msg);
} else {
rc = 0;
}
}
return rc;
}

@ -0,0 +1,44 @@
/*
* Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
* 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 IOT_MAIN_H
#define IOT_MAIN_H
typedef void (*fnMsgCallBack)(int qos, const char *topic, const char *payload);
/**
* This is the iot main function. Please call this function first
*/
int IoTMain(void);
/**
* Use this function to set the message call back function, when some messages comes,
* the callback will be called, if you don't care about the message, set it to NULL
*/
int IoTSetMsgCallback(fnMsgCallBack msgCallback);
/**
* When you want to send some messages to the iot server(including the response message),
* please call this api
* @param qos: the mqtt qos,:0,1,2
* @param topic: the iot mqtt topic
* @param payload: the mqtt payload
*
* @return 0 success while others failed
*
* @instruction: if success means we write the message to the queue susccess,
* not means communicate with the server success
*/
int IotSendMsg(int qos, const char *topic, const char *payload);
#endif /* IOT_MAIN_H_ */

@ -0,0 +1,336 @@
/*
* Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
* 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.
*/
#include <hi_mem.h>
#include <cJSON.h>
#include <string.h>
#include "iot_main.h"
#include "iot_log.h"
#include "iot_config.h"
#include "iot_profile.h"
// < format the report data to json string mode
static cJSON *FormateProflleValue(IoTProfileKV_t *kv)
{
cJSON *ret = NULL;
switch (kv->type) {
case EN_IOT_DATATYPE_INT:
ret = cJSON_CreateNumber(kv->iValue);
break;
case EN_IOT_DATATYPE_LONG:
ret = cJSON_CreateNumber((double)(*(long *)kv->value));
break;
case EN_IOT_DATATYPE_STRING:
ret = cJSON_CreateString((const char *)kv->value);
break;
default:
break;
}
return ret;
}
static cJSON *MakeKvs(IoTProfileKV_t *kvlst)
{
cJSON *root;
cJSON *kv;
IoTProfileKV_t *kvInfo;
// < build a root node
root = cJSON_CreateObject();
if (root == NULL) {
cJSON_Delete(root);
root = NULL;
return root;
}
// < add all the property to the properties
kvInfo = kvlst;
while (kvInfo != NULL) {
kv = FormateProflleValue(kvInfo);
if (kv == NULL) {
if (root != NULL) {
cJSON_Delete(root);
root = NULL;
}
return root;
}
cJSON_AddItemToObject(root, kvInfo->key, kv);
kvInfo = kvInfo->nxt;
}
// < OK, now we return it
return root;
}
#define CN_PROFILE_SERVICE_KEY_SERVICEID "service_id"
#define CN_PROFILE_SERVICE_KEY_PROPERTIIES "properties"
#define CN_PROFILE_SERVICE_KEY_EVENTTIME "event_time"
#define CN_PROFILE_KEY_SERVICES "services"
static cJSON *MakeService(IoTProfileService_t *serviceInfo)
{
cJSON *root;
cJSON *serviceID;
cJSON *properties;
cJSON *eventTime;
// < build a root node
root = cJSON_CreateObject();
if (root == NULL) {
cJSON_Delete(root);
root = NULL;
return root;
}
// < add the serviceID node to the root node
serviceID = cJSON_CreateString(serviceInfo->serviceID);
if (serviceID == NULL) {
if (root != NULL) {
cJSON_Delete(root);
root = NULL;
}
return root;
}
cJSON_AddItemToObjectCS(root, CN_PROFILE_SERVICE_KEY_SERVICEID, serviceID);
// < add the properties node to the root
properties = MakeKvs(serviceInfo->serviceProperty);
if (properties == NULL) {
if (root != NULL) {
cJSON_Delete(root);
root = NULL;
}
return root;
}
cJSON_AddItemToObjectCS(root, CN_PROFILE_SERVICE_KEY_PROPERTIIES, properties);
// < add the event time (optional) to the root
if (serviceInfo->eventTime != NULL) {
eventTime = cJSON_CreateString(serviceInfo->eventTime);
if (eventTime == NULL) {
if (root != NULL) {
cJSON_Delete(root);
root = NULL;
}
return root;
}
cJSON_AddItemToObjectCS(root, CN_PROFILE_SERVICE_KEY_EVENTTIME, eventTime);
}
// < OK, now we return it
cJSON_Delete(properties);
return root;
}
static cJSON *MakeServices(IoTProfileService_t *serviceInfo)
{
cJSON *services = NULL;
cJSON *service;
IoTProfileService_t *serviceTmp;
// < create the services array node
services = cJSON_CreateArray();
if (services == NULL) {
cJSON_Delete(services);
services = NULL;
return services;
}
serviceTmp = serviceInfo;
while (serviceTmp != NULL) {
service = MakeService(serviceTmp);
if (service == NULL) {
if (services != NULL) {
cJSON_Delete(services);
services = NULL;
}
return services;
}
cJSON_AddItemToArray(services, service);
serviceTmp = serviceTmp->nxt;
}
// < now we return the services
return services;
}
// < use this function to make a topic to publish
// < if request_id is needed depends on the fmt
static char *MakeTopic(const char *fmt, const char *deviceID, const char *requestID)
{
int len;
char *ret = NULL;
len = strlen(fmt) + strlen(deviceID);
if (requestID != NULL) {
len += strlen(requestID);
}
ret = hi_malloc(0, len);
if (ret != NULL) {
if (requestID != NULL) {
(void)snprintf_s(ret, len, len, fmt, deviceID, requestID);
} else {
(void)snprintf_s(ret, len, len, fmt, deviceID);
}
}
return ret;
}
#define CN_PROFILE_CMDRESP_KEY_RETCODE "result_code"
#define CN_PROFILE_CMDRESP_KEY_RESPNAME "response_name"
#define CN_PROFILE_CMDRESP_KEY_PARAS "paras"
static char *MakeProfileCmdResp(IoTCmdResp_t *payload)
{
char *ret = NULL;
cJSON *root;
cJSON *retCode;
cJSON *respName;
cJSON *paras;
// < create the root node
root = cJSON_CreateObject();
if (root == NULL) {
cJSON_Delete(root);
return ret;
}
// < create retcode and retdesc and add it to the root
retCode = cJSON_CreateNumber(payload->retCode);
if (retCode == NULL) {
if (root != NULL) {
cJSON_Delete(root);
}
return ret;
}
cJSON_AddItemToObjectCS(root, CN_PROFILE_CMDRESP_KEY_RETCODE, retCode);
if (payload->respName != NULL) {
respName = cJSON_CreateString(payload->respName);
if (respName == NULL) {
if (root != NULL) {
cJSON_Delete(root);
}
return ret;
}
cJSON_AddItemToObjectCS(root, CN_PROFILE_CMDRESP_KEY_RESPNAME, respName);
}
if (payload->paras != NULL) {
paras = MakeKvs(payload->paras);
if (paras == NULL) {
if (root != NULL) {
cJSON_Delete(root);
}
return ret;
}
cJSON_AddItemToObjectCS(root, CN_PROFILE_CMDRESP_KEY_PARAS, paras);
}
// < OK, now we make it to a buffer
ret = cJSON_PrintUnformatted(root);
cJSON_Delete(root);
return ret;
}
static char *MakeProfilePropertyReport(IoTProfileService_t *payload)
{
char *ret = NULL;
cJSON *root;
cJSON *services;
// < create the root node
root = cJSON_CreateObject();
if (root == NULL) {
cJSON_Delete(root);
return ret;
}
// < create the services array node to the root
services = MakeServices(payload);
if (services == NULL) {
if (root != NULL) {
cJSON_Delete(root);
}
return ret;
}
cJSON_AddItemToObjectCS(root, CN_PROFILE_KEY_SERVICES, services);
// < OK, now we make it to a buffer
ret = cJSON_PrintUnformatted(root);
cJSON_Delete(root);
return ret;
}
#define WECHAT_SUBSCRIBE_TYPE "update"
#define WECHAT_SUBSCRIBE_VERSION "1.0.0"
#define WECHAT_SUBSCRIBE_TOKEN "DeviceSubscribe"
static char *MakeProfileReport(WeChatProfile *payload)
{
char *ret = NULL;
cJSON *root;
cJSON *state;
cJSON *reported;
/* create json root node */
root = cJSON_CreateObject();
if (root == NULL) {
return;
}
/* state create */
state = cJSON_CreateObject();
if (state == NULL) {
return;
}
/* reported create */
reported = cJSON_CreateObject();
if (reported == NULL) {
return;
}
/* add root object */
cJSON_AddItemToObject(root, payload->subscribeType, cJSON_CreateString(WECHAT_SUBSCRIBE_TYPE));
cJSON_AddItemToObject(root, payload->status.subState, state);
cJSON_AddItemToObject(state, payload->status.subReport, reported);
cJSON_AddItemToObject(root, payload->status.reportVersion, cJSON_CreateString(WECHAT_SUBSCRIBE_VERSION));
cJSON_AddItemToObject(root, payload->status.Token, cJSON_CreateString(WECHAT_SUBSCRIBE_TOKEN));
/* add reported item */
cJSON_AddNumberToObject(reported, payload->reportAction.subDeviceActionLight,
payload->reportAction.lightActionStatus);
cJSON_AddNumberToObject(reported, payload->reportAction.subDeviceActionMotor,
payload->reportAction.motorActionStatus);
cJSON_AddNumberToObject(reported, payload->reportAction.subDeviceActionTemperature,
payload->reportAction.temperatureData);
cJSON_AddNumberToObject(reported, payload->reportAction.subDeviceActionHumidity,
payload->reportAction.humidityActionData);
cJSON_AddNumberToObject(reported, payload->reportAction.subDeviceActionLightIntensity,
payload->reportAction.lightIntensityActionData);
ret = cJSON_PrintUnformatted(root);
cJSON_Delete(state);
cJSON_Delete(reported);
cJSON_Delete(root);
return ret;
}
#define CN_PROFILE_TOPICFMT_TOPIC "$shadow/operation/19VUBHD786/mqtt"
int IoTProfilePropertyReport(char *deviceID, WeChatProfile *payload)
{
int ret = -1;
char *topic;
char *msg;
if ((deviceID == NULL) || (payload== NULL)) {
return ret;
}
topic = MakeTopic(CN_PROFILE_TOPICFMT_TOPIC, deviceID, NULL);
if (topic == NULL) {
return;
}
msg = MakeProfileReport(payload);
if ((topic != NULL) && (msg != NULL)) {
ret = IotSendMsg(0, topic, msg);
}
hi_free(0, topic);
cJSON_free(msg);
return ret;
}

@ -0,0 +1,94 @@
/*
* Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
* 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 IOT_PROFILE_H
#define IOT_PROFILE_H
#include <hi_types_base.h>
#include "iot_config.h"
#define OC_BEEP_STATUS_ON ((hi_u8) 0x01)
#define OC_BEEP_STATUS_OFF ((hi_u8) 0x00)
// < enum all the data type for the oc profile
typedef enum {
EN_IOT_DATATYPE_INT = 0,
EN_IOT_DATATYPE_LONG,
EN_IOT_DATATYPE_FLOAT,
EN_IOT_DATATYPE_DOUBLE,
EN_IOT_DATATYPE_STRING, // < must be ended with '\0'
EN_IOT_DATATYPE_LAST,
}IoTDataType_t;
typedef enum {
OC_LED_ON = 1,
OC_LED_OFF
}OcLedValue;
typedef struct {
void *nxt; // < ponit to the next key
const char *key;
const char *value;
hi_u32 iValue;
IoTDataType_t type;
}IoTProfileKV_t;
typedef struct {
void *nxt;
char *serviceID;
char *eventTime;
IoTProfileKV_t *serviceProperty;
}IoTProfileService_t;
typedef struct {
int retCode; // < response code, 0 success while others failed
const char *respName; // < response name
const char *requestID; // < specified by the message command
IoTProfileKV_t *paras; // < the command paras
}IoTCmdResp_t;
typedef struct {
const char *subState;
const char *subReport;
const char *reportVersion;
const char *Token;
}WeChatProfileStatus;
typedef struct {
int lightActionStatus;
int motorActionStatus;
int temperatureData;
int humidityActionData;
int lightIntensityActionData;
const char *subDeviceActionLight;
const char *subDeviceActionMotor;
const char *subDeviceActionTemperature;
const char *subDeviceActionHumidity;
const char *subDeviceActionLightIntensity;
}WeChatProfileReporte;
typedef struct {
const char *subscribeType;
WeChatProfileStatus status;
WeChatProfileReporte reportAction;
}WeChatProfile;
/**
* use this function to report the property to the iot platform
*/
int IoTProfilePropertyReport(char *deviceID, WeChatProfile *payload);
void cJsonInit(void);
void WifiStaReadyWait(void);
#endif

@ -0,0 +1,269 @@
/*
* Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
* 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.
*/
// < this demo make the wifi to connect to the specified AP
#include <unistd.h>
#include <hi_wifi_api.h>
#include <lwip/ip_addr.h>
#include <lwip/netifapi.h>
#include <hi_types_base.h>
#include <hi_task.h>
#include <hi_mem.h>
#include "iot_config.h"
#include "iot_log.h"
#include "wifi_device.h"
#include "cmsis_os2.h"
#include "wifi_device_config.h"
#include "lwip/api_shell.h"
#define APP_INIT_VAP_NUM 2
#define APP_INIT_USR_NUM 2
static struct netif *gLwipNetif = NULL;
static hi_bool gScanDone = HI_FALSE;
unsigned char wifiStatus = 0;
unsigned char wifiFirstConnecting = 0;
unsigned char wifiSecondConnecting = 0;
unsigned char wifiSecondConnected = 0;
static struct netif* g_iface = NULL;
void WifiStopSta(int netId);
static int WifiStartSta(void);
int cnetId = -1;
int g_connected = 0;
#define WIFI_CONNECT_STATUS ((unsigned char)0x02)
void wifiReconnected(int netId)
{
int recnetId = netId;
if (wifiFirstConnecting == WIFI_CONNECT_STATUS) {
wifiSecondConnecting = HI_TRUE;
wifiFirstConnecting = HI_FALSE;
WifiStopSta(recnetId);
ip4_addr_t ipAddr;
ip4_addr_t ipAny;
IP4_ADDR(&ipAny, 0, 0, 0, 0);
IP4_ADDR(&ipAddr, 0, 0, 0, 0);
recnetId = WifiStartSta();
netifapi_dhcp_start(gLwipNetif);
while (0 == memcmp(&ipAddr, &ipAny, sizeof(ip4_addr_t))) {
IOT_LOG_DEBUG("<Wifi reconnecting>:Wait the DHCP READY");
netifapi_netif_get_addr(gLwipNetif, &ipAddr, NULL, NULL);
hi_sleep(1000); /* 1000: cpu sleep 1000 ms */
}
wifiSecondConnected = HI_FALSE;
wifiFirstConnecting = WIFI_CONNECT_STATUS;
wifiStatus = HI_WIFI_EVT_CONNECTED;
}
}
/* clear netif's ip, gateway and netmask */
static void StaResetAddr(struct netif *lwipNetif)
{
ip4_addr_t st_gw;
ip4_addr_t st_ipaddr;
ip4_addr_t st_netmask;
if (lwipNetif == NULL) {
IOT_LOG_ERROR("hisi_reset_addr::Null param of netdev");
return;
}
IP4_ADDR(&st_gw, 0, 0, 0, 0);
IP4_ADDR(&st_ipaddr, 0, 0, 0, 0);
IP4_ADDR(&st_netmask, 0, 0, 0, 0);
netifapi_netif_set_addr(lwipNetif, &st_ipaddr, &st_netmask, &st_gw);
}
static void WpaEventCB(const hi_wifi_event *hisiEvent)
{
if (hisiEvent == NULL)
return;
IOT_LOG_DEBUG("EVENT_TYPE:%d", hisiEvent->event);
switch (hisiEvent->event) {
case HI_WIFI_EVT_SCAN_DONE:
IOT_LOG_DEBUG("WiFi: Scan results available");
gScanDone = HI_TRUE;
break;
case HI_WIFI_EVT_CONNECTED:
IOT_LOG_DEBUG("WiFi: Connected");
netifapi_dhcp_start(gLwipNetif);
wifiStatus = HI_WIFI_EVT_CONNECTED;
if (wifiSecondConnected) {
wifiSecondConnected = HI_FALSE;
wifiFirstConnecting = WIFI_CONNECT_STATUS;
}
break;
case HI_WIFI_EVT_DISCONNECTED:
IOT_LOG_DEBUG("WiFi: Disconnected");
netifapi_dhcp_stop(gLwipNetif);
StaResetAddr(gLwipNetif);
wifiStatus = HI_WIFI_EVT_DISCONNECTED;
wifiReconnected(cnetId);
break;
case HI_WIFI_EVT_WPS_TIMEOUT:
IOT_LOG_DEBUG("WiFi: wps is timeout");
wifiStatus = HI_WIFI_EVT_WPS_TIMEOUT;
break;
default:
break;
}
}
static int StaStartConnect(void)
{
int ret;
errno_t rc;
hi_wifi_assoc_request assoc_req = {0};
/* copy SSID to assoc_req */
rc = memcpy_s(assoc_req.ssid, HI_WIFI_MAX_SSID_LEN + 1, CONFIG_AP_SSID, strlen(CONFIG_AP_SSID));
if (rc != EOK) {
return -1;
}
/*
* OPEN mode
* for WPA2-PSK mode:
* set assoc_req.auth as HI_WIFI_SECURITY_WPA2PSK,
* then memcpy(assoc_req.key, "12345678", 8).
*/
assoc_req.auth = HI_WIFI_SECURITY_WPA2PSK;
rc = memcpy_s(assoc_req.key, HI_WIFI_MAX_KEY_LEN + 1, CONFIG_AP_PWD, strlen(CONFIG_AP_PWD));
if (rc != EOK) {
return -1;
}
ret = hi_wifi_sta_connect(&assoc_req);
if (ret != HISI_OK) {
return -1;
}
return 0;
}
static void PrintLinkedInfo(WifiLinkedInfo* info)
{
int ret = 0;
if (!info) {
return;
}
static char macAddress[32] = {0};
unsigned char* mac = info->bssid;
if (snprintf_s(macAddress, sizeof(macAddress) + 1, sizeof(macAddress), "%02X:%02X:%02X:%02X:%02X:%02X",
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]) < 0) { /* mac地址从0,1,2,3,4,5位 */
return;
}
}
static void OnWifiConnectionChanged(int state, WifiLinkedInfo* info)
{
if (!info) {
return;
}
printf("%s %d, state = %d, info = \r\n", __FUNCTION__, __LINE__, state);
PrintLinkedInfo(info);
if (state == WIFI_STATE_AVALIABLE) {
g_connected = 1;
} else {
g_connected = 0;
}
}
static void OnWifiScanStateChanged(int state, int size)
{
printf("%s %d, state = %X, size = %d\r\n", __FUNCTION__, __LINE__, state, size);
}
static WifiEvent g_defaultWifiEventListener = {
.OnWifiConnectionChanged = OnWifiConnectionChanged,
.OnWifiScanStateChanged = OnWifiScanStateChanged
};
static int WifiStartSta(void)
{
WifiDeviceConfig apConfig = {0};
strcpy_s(apConfig.ssid, sizeof(CONFIG_AP_SSID), CONFIG_AP_SSID);
strcpy_s(apConfig.preSharedKey, sizeof(CONFIG_AP_PWD), CONFIG_AP_PWD);
apConfig.securityType = WIFI_SEC_TYPE_PSK;
WifiErrorCode errCode;
int netId = -1;
errCode = RegisterWifiEvent(&g_defaultWifiEventListener);
printf("RegisterWifiEvent: %d\r\n", errCode);
errCode = EnableWifi();
printf("EnableWifi: %d\r\n", errCode);
errCode = AddDeviceConfig(&apConfig, &netId);
printf("AddDeviceConfig: %d\r\n", errCode);
g_connected = 0;
errCode = ConnectTo(netId);
printf("ConnectTo(%d): %d\r\n", netId, errCode);
while (!g_connected) { // wait until connect to AP
osDelay(10); /* 10: os sleep 10ms */
}
printf("g_connected: %d\r\n", g_connected);
g_iface = netifapi_netif_find("wlan0");
if (g_iface) {
err_t ret = netifapi_dhcp_start(g_iface);
printf("netifapi_dhcp_start: %d\r\n", ret);
osDelay(100); // 100: os sleep 100ms wait DHCP server give me IP
ret = netifapi_netif_common(g_iface, dhcp_clients_info_show, NULL);
printf("netifapi_netif_common: %d\r\n", ret);
}
return netId;
}
void WifiStopSta(int netId)
{
int stopNetId = netId;
if (g_iface) {
err_t ret = netifapi_dhcp_stop(g_iface);
printf("netifapi_dhcp_stop: %d\r\n", ret);
}
WifiErrorCode errCode = Disconnect(); // disconnect with your AP
printf("Disconnect: %d\r\n", errCode);
errCode = UnRegisterWifiEvent(&g_defaultWifiEventListener);
printf("UnRegisterWifiEvent: %d\r\n", errCode);
RemoveDevice(stopNetId); // remove AP config
printf("RemoveDevice: %d\r\n", errCode);
errCode = DisableWifi();
printf("DisableWifi: %d\r\n", errCode);
}
void WifiStaReadyWait(void)
{
ip4_addr_t ipAddr;
ip4_addr_t ipAny;
IP4_ADDR(&ipAny, 0, 0, 0, 0);
IP4_ADDR(&ipAddr, 0, 0, 0, 0);
cnetId = WifiStartSta();
IOT_LOG_DEBUG("wifi sta dhcp done");
}

@ -0,0 +1,36 @@
# Copyright (c) 2020-2022 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.
static_library("example_samgr") {
sources = [
"//test/xts/acts/distributed_schedule_lite/samgr_hal/utils/samgr_maintenance.c",
"bootstrap_example.c",
"broadcast_example.c",
"feature_example.c",
"maintenance_example.c",
"service_example.c",
"service_recovery_example.c",
"specified_task_example.c",
"task_example.c",
]
include_dirs = [
"//utils/native/lite/include",
"//kernel/liteos_m/components/cmsis",
"//foundation/distributedschedule/samgr_lite/interfaces/kits/samgr",
"//foundation/distributedschedule/samgr_lite/interfaces/kits/communication/broadcast",
"//foundation/distributedschedule/samgr_lite/samgr/adapter",
"//foundation/distributedschedule/samgr_lite/samgr/source",
"//test/xts/acts/distributed_schedule_lite/samgr_hal/utils",
]
}

@ -0,0 +1,241 @@
/*
* Copyright (c) 2020-2022 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.
*/
#include "example.h"
#include <stdint.h>
#include <feature.h>
#include <securec.h>
#include <ohos_init.h>
#include <samgr_lite.h>
#include <cmsis_os.h>
#include "time_adapter.h"
typedef struct BootTestExample {
Service service;
Feature feature;
} BootTestExample;
static const char *GetName(Service *service);
static BOOL Initialize(Service *service, Identity identity);
static BOOL MessageHandle(Service *service, Request *msg);
static TaskConfig GetTaskConfig(Service *service);
static const char *FEATURE_GetName(Feature *feature);
static void FEATURE_OnInitialize(Feature *feature, Service *parent, Identity identity);
static void FEATURE_OnStop(Feature *feature, Identity identity);
static BOOL FEATURE_OnMessage(Feature *feature, Request *request);
static BootTestExample g_example[] = {
{
.service = {GetName, Initialize, MessageHandle, GetTaskConfig},
.feature = {FEATURE_GetName, FEATURE_OnInitialize, FEATURE_OnStop, FEATURE_OnMessage}
}, {
.service = {GetName, Initialize, MessageHandle, GetTaskConfig},
.feature = {FEATURE_GetName, FEATURE_OnInitialize, FEATURE_OnStop, FEATURE_OnMessage}
}, {
.service = {GetName, Initialize, MessageHandle, GetTaskConfig},
.feature = {FEATURE_GetName, FEATURE_OnInitialize, FEATURE_OnStop, FEATURE_OnMessage}
}, {
.service = {GetName, Initialize, MessageHandle, GetTaskConfig},
.feature = {FEATURE_GetName, FEATURE_OnInitialize, FEATURE_OnStop, FEATURE_OnMessage}
}
};
static uint32_t g_initIndex = 0;
static const char *FEATURE_GetName(Feature *feature)
{
// test cases service 0
if (feature == &g_example[0].feature) {
return BOOT_SYS_FEATURE1;
}
// test cases service 1
if (feature == &g_example[1].feature) {
return BOOT_SYS_FEATURE2;
}
// test cases service 2
if (feature == &g_example[2].feature) {
return BOOT_SYSEX_FEATURE1;
}
// test cases service 3
if (feature == &g_example[3].feature) {
return BOOT_SYSEX_FEATURE2;
}
return NULL;
}
static void FEATURE_OnInitialize(Feature *feature, Service *parent, Identity identity)
{
(void)identity;
printf("[Boot Test][TaskID:%u][Step:%u][Reg Finish S:%s, F:%s]Time: %llu!\n",
(int)osThreadGetId(), g_initIndex++, parent->GetName(parent), feature->GetName(feature),
SAMGR_GetProcessTime());
}
static void FEATURE_OnStop(Feature *feature, Identity identity)
{
(void)feature;
(void)identity;
}
static BOOL FEATURE_OnMessage(Feature *feature, Request *request)
{
printf("[Boot Test][TaskID:%u][Step:%u][F:%s] msgId<%d> \n",
(int)osThreadGetId(), g_initIndex++, feature->GetName(feature), request->msgId);
return FALSE;
}
static const char *GetName(Service *service)
{
// test cases service 0
if (service == &g_example[0].service) {
return BOOT_SYS_SERVICE1;
}
// test cases service 1
if (service == &g_example[1].service) {
return BOOT_SYS_SERVICE2;
}
// test cases service 2
if (service == &g_example[2].service) {
return BOOT_SYSEX_SERVICE1;
}
// test cases service 3
if (service == &g_example[3].service) {
return BOOT_SYSEX_SERVICE2;
}
return NULL;
}
static BOOL Initialize(Service *service, Identity identity)
{
(void)identity;
printf("[Boot Test][TaskID:%u][Step:%u][Reg Finish S:%s]Time: %llu!\n",
(int)osThreadGetId(), g_initIndex++, service->GetName(service), SAMGR_GetProcessTime());
return TRUE;
}
static BOOL MessageHandle(Service *service, Request *msg)
{
printf("[Boot Test][TaskID:%u][Step:%u][S:%s] msgId<%d> \n",
(int)osThreadGetId(), g_initIndex++, service->GetName(service), msg->msgId);
return FALSE;
}
static TaskConfig GetTaskConfig(Service *service)
{
(void)service;
TaskConfig config = {LEVEL_HIGH, PRI_ABOVE_NORMAL,
0x400, 2, SHARED_TASK};
return config;
}
static void MInit(void)
{
printf("[Boot Test][TaskID:%u][Step:%u][CORE INIT]Time: %llu!\n",
(int)osThreadGetId(), g_initIndex++, SAMGR_GetProcessTime());
}
static void MRun(void)
{
printf("[Boot Test][TaskID:%u][Step:%u][SYS RUN]Time: %llu!\n",
(int)osThreadGetId(), g_initIndex++, SAMGR_GetProcessTime());
}
static void SInit(BootTestExample *demo)
{
SAMGR_GetInstance()->RegisterService(&demo->service);
// test cases service 2
printf((demo < &g_example[2]) ?
"[Boot Test][TaskID:%u][Step:%u][SYS Reg S:%s]Time: %llu!\n" :
"[Boot Test][TaskID:%u][Step:%u][SYSEX Reg S:%s]Time: %llu!\n",
(int)osThreadGetId(), g_initIndex++, demo->service.GetName(&demo->service), SAMGR_GetProcessTime());
}
static void FInit(BootTestExample *demo)
{
SAMGR_GetInstance()->RegisterFeature(demo->service.GetName(&demo->service), &demo->feature);
// test cases service 2
printf((demo < &g_example[2]) ?
"[Boot Test][TaskID:%u][Step:%u][SYS Reg S:%s, F:%s]Time: %llu!\n" :
"[Boot Test][TaskID:%u][Step:%u][SYSEX Reg S:%s, F:%s]Time: %llu!\n",
(int)osThreadGetId(), g_initIndex++, demo->service.GetName(&demo->service),
demo->feature.GetName(&demo->feature), SAMGR_GetProcessTime());
}
static void S1Init(void)
{
// test cases service 0
SInit(&g_example[0]);
}
static void S2Init(void)
{
// test cases service 1
SInit(&g_example[1]);
}
static void F1Init(void)
{
// test cases feature 0
FInit(&g_example[0]);
}
static void F2Init(void)
{
// test cases feature 1
FInit(&g_example[1]);
}
static void S3Init(void)
{
// test cases service 2
SInit(&g_example[2]);
}
static void S4Init(void)
{
// test cases service 3
SInit(&g_example[3]);
}
static void F3Init(void)
{
// test cases feature 2
FInit(&g_example[2]);
}
static void F4Init(void)
{
// test cases feature 3
FInit(&g_example[3]);
}
CORE_INIT(MInit);
SYS_RUN(MRun);
// init pri first
SYS_SERVICE_INIT_PRI(S1Init, 0);
// init pri second
SYS_SERVICE_INIT_PRI(S2Init, 1);
// init pri first
SYS_FEATURE_INIT_PRI(F1Init, 0);
// init pri second
SYS_FEATURE_INIT_PRI(F2Init, 1);
// init pri first
SYSEX_SERVICE_INIT_PRI(S3Init, 0);
// init pri second
SYSEX_SERVICE_INIT_PRI(S4Init, 1);
// init pri first
SYSEX_FEATURE_INIT_PRI(F3Init, 0);
// init pri second
SYSEX_FEATURE_INIT_PRI(F4Init, 1);

@ -0,0 +1,241 @@
/*
* Copyright (c) 2020-2022 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.
*/
#include <stdint.h>
#include "samgr_lite.h"
#include "broadcast_interface.h"
#include <ohos_init.h>
#include <securec.h>
#include <los_base.h>
#include <cmsis_os.h>
#include "time_adapter.h"
#define TEST_LEN 10
#define WAIT_PUB_PROC 1000
#define BROADCAST_TEST_SERVICE "broadcast test"
static uint32_t g_callbackStep = 0;
static void C1Callback(Consumer *consumer, const Topic *topic, const Request *request)
{
(void)consumer;
(void)topic;
printf("[Broadcast Test][TaskID:%u][Step:%u][C1 Callback]c1 is being called data is :%s \n",
(int)osThreadGetId(), g_callbackStep++, (char *)request->data);
}
static void C2Callback(Consumer *consumer, const Topic *topic, const Request *request)
{
(void)consumer;
(void)topic;
printf("[Broadcast Test][TaskID:%u][Step:%u][C2 Callback]c2 is being called data is :%s \n",
(int)osThreadGetId(), g_callbackStep++, (char *)request->data);
}
static BOOL Equal(const Consumer *current, const Consumer *other)
{
return (current->Notify == other->Notify);
}
static const char *GetName(Service *service)
{
(void)service;
return BROADCAST_TEST_SERVICE;
};
static Identity g_identity = { -1, -1, NULL};
static volatile uint32_t g_broadcastStep = 0;
static BOOL Initialize(Service *service, Identity identity)
{
g_identity = identity;
(void)service;
printf("[Broadcast Test][TaskID:%u][Step:%u][Reg Finish S:%s]Time: %llu!\n",
(int)osThreadGetId(), g_broadcastStep++, BROADCAST_TEST_SERVICE, SAMGR_GetProcessTime());
return TRUE;
};
static BOOL MessageHandle(Service *service, Request *msg)
{
printf("[Broadcast Test][TaskID:%u] msgId<%d>: %s \n", (int)osThreadGetId(), msg->msgId, (char *)msg->data);
(void)service;
return FALSE;
};
static TaskConfig GetTaskConfig(Service *service)
{
TaskConfig config = {LEVEL_HIGH, PRI_ABOVE_NORMAL, 0x800, 20, SHARED_TASK};
(void)service;
return config;
};
static Service g_testService = {GetName, Initialize, MessageHandle, GetTaskConfig};
static void Init(void)
{
SAMGR_GetInstance()->RegisterService(&g_testService);
printf("[Broadcast Test][TaskID:%u][Step:%u][Reg S:%s]Time: %llu!\n",
(int)osThreadGetId(), g_broadcastStep++, BROADCAST_TEST_SERVICE, SAMGR_GetProcessTime());
}
SYSEX_SERVICE_INIT(Init);
static PubSubInterface *CASE_GetIUnknown(void)
{
PubSubInterface *fapi = NULL;
printf("[Broadcast Test][TaskID:%u][Step:%u][GetIUnknown S:%s]: BEGIN\n",
(int)osThreadGetId(), g_broadcastStep++, BROADCAST_TEST_SERVICE);
IUnknown *iUnknown = SAMGR_GetInstance()->GetFeatureApi(BROADCAST_SERVICE, PUB_SUB_FEATURE);
if (iUnknown == NULL) {
printf("[Broadcast Test][TaskID:%u][Step:%u][GetDefaultFeatureApi S:%s]Error is NULL!\n",
(int)osThreadGetId(), g_broadcastStep++, BROADCAST_TEST_SERVICE);
goto END;
}
int result = iUnknown->QueryInterface(iUnknown, DEFAULT_VERSION, (void **)&fapi);
if (result != 0 || fapi == NULL) {
printf("[Broadcast Test][TaskID:%u][Step:%u][QueryInterface S:%s]Error is NULL!\n",
(int)osThreadGetId(), g_broadcastStep++, BROADCAST_TEST_SERVICE);
goto END;
}
printf("[Broadcast Test][TaskID:%u][Step:%u][GetIUnknown S:%s]Success\n",
(int)osThreadGetId(), g_broadcastStep++, BROADCAST_TEST_SERVICE);
END:
printf("[Broadcast Test][TaskID:%u][Step:%u][GetIUnknown S:%s]: END\n",
(int)osThreadGetId(), g_broadcastStep++, BROADCAST_TEST_SERVICE);
return fapi;
}
static uint32_t g_addTopicStep = 0;
static uint32_t g_unsubscribeTopicStep = 0;
static void CASE_AddAndUnsubscribeTopic(PubSubInterface *fapi)
{
Subscriber *subscriber = &fapi->subscriber;
Provider *provider = &fapi->provider;
static Consumer c1 = {.identity = &g_identity, .Notify = C1Callback, .Equal = Equal};
static Consumer c2 = {.identity = &g_identity, .Notify = C2Callback, .Equal = Equal};
// add topic test
printf("[Topic Test][TaskID:%u][Step:%u][Add Topic]: BEGIN\n", (int)osThreadGetId(), g_addTopicStep++);
Topic topic0 = 0;
subscriber->AddTopic((IUnknown *)fapi, &topic0);
subscriber->Subscribe((IUnknown *)fapi, &topic0, &c1);
subscriber->Subscribe((IUnknown *)fapi, &topic0, &c2);
provider->Publish((IUnknown *)fapi, &topic0, (uint8_t *) "==>111<==", TEST_LEN);
Topic topic1 = 0x10000;
subscriber->AddTopic((IUnknown *)fapi, &topic1);
subscriber->Subscribe((IUnknown *)fapi, &topic1, &c1);
subscriber->Subscribe((IUnknown *)fapi, &topic1, &c2);
provider->Publish((IUnknown *)fapi, &topic1, (uint8_t *) "==>444<==", TEST_LEN);
printf("[Topic Test][TaskID:%u][Step:%u][Add Topic]: Success!\n", (int)osThreadGetId(), g_addTopicStep++);
printf("[Topic Test][TaskID:%u][Step:%u][Add Topic]: END\n", (int)osThreadGetId(), g_addTopicStep++);
// unsubscribe topic0 test
printf("[Topic Test][TaskID:%u][Step:%u][Unsubscribe Topic]: BEGIN\n", (int)osThreadGetId(),
g_unsubscribeTopicStep++);
LOS_Msleep(WAIT_PUB_PROC);
subscriber->Unsubscribe((IUnknown *)fapi, &topic0, &c1);
provider->Publish((IUnknown *)fapi, &topic0, (uint8_t *) "@@@222@@@", TEST_LEN);
LOS_Msleep(WAIT_PUB_PROC);
subscriber->Unsubscribe((IUnknown *)fapi, &topic0, &c2);
provider->Publish((IUnknown *)fapi, &topic0, (uint8_t *) "@@@333@@@", TEST_LEN);
provider->Publish((IUnknown *)fapi, &topic1, (uint8_t *) "@@@444@@@", TEST_LEN);
printf("[Topic Test][TaskID:%u][Step:%u][Unsubscribe Topic]: Success!\n",
(int)osThreadGetId(), g_unsubscribeTopicStep++);
printf("[Topic Test][TaskID:%u][Step:%u][Unsubscribe Topic]: END\n", (int)osThreadGetId(),
g_unsubscribeTopicStep++);
}
static uint32_t g_modifyConsumerStep = 0;
static void CASE_ModifyConsumer(PubSubInterface *fapi)
{
Subscriber *subscriber = &fapi->subscriber;
Provider *provider = &fapi->provider;
static Consumer c1 = {.identity = &g_identity, .Notify = C1Callback, .Equal = Equal};
static Consumer c2 = {.identity = &g_identity, .Notify = C2Callback, .Equal = Equal};
// modify consumer test
printf("[Topic Test][TaskID:%u][Step:%u][Modify Consumer]: BEGIN\n", (int)osThreadGetId(),
g_modifyConsumerStep++);
Topic topic2 = 0x100;
subscriber->AddTopic((IUnknown *)fapi, &topic2);
subscriber->Subscribe((IUnknown *)fapi, &topic2, &c1);
provider->Publish((IUnknown *)fapi, &topic2, (uint8_t *) "==>555<==", TEST_LEN);
LOS_Msleep(WAIT_PUB_PROC);
subscriber->ModifyConsumer((IUnknown *)fapi, &topic2, &c1, &c2);
provider->Publish((IUnknown *)fapi, &topic2, (uint8_t *) "@@@555@@@", TEST_LEN);
printf("[Topic Test][TaskID:%u][Step:%u][Modify Consumer]: Success!\n", (int)osThreadGetId(),
g_modifyConsumerStep++);
printf("[Topic Test][TaskID:%u][Step:%u][Modify Consumer]: END\n", (int)osThreadGetId(),
g_modifyConsumerStep++);
}
static uint32_t g_reUnsubscribeTopic = 0;
static void CASE_ReUnsubscribeTopic(PubSubInterface *fapi)
{
Subscriber *subscriber = &fapi->subscriber;
Provider *provider = &fapi->provider;
static Consumer c1 = {.identity = &g_identity, .Notify = C1Callback, .Equal = Equal};
printf("[Topic Test][TaskID:%u][Step:%u][ReUnsubscribe Topic]: BEGIN\n", (int)osThreadGetId(),
g_reUnsubscribeTopic++);
Topic topic3 = 0x1000;
subscriber->AddTopic((IUnknown *)fapi, &topic3);
subscriber->Subscribe((IUnknown *)fapi, &topic3, &c1);
provider->Publish((IUnknown *)fapi, &topic3, (uint8_t *) "==>666<==", TEST_LEN);
LOS_Msleep(WAIT_PUB_PROC);
Consumer *retConsumer = subscriber->Unsubscribe((IUnknown *)fapi, &topic3, &c1);
if (retConsumer == NULL) {
printf("[Topic Test][TaskID:%u][Step:%u][ReUnsubscribe Topic]: Unsubscribe Topic lead to NULL return value\n",
(int)osThreadGetId(), g_reUnsubscribeTopic++);
}
retConsumer = subscriber->Unsubscribe((IUnknown *)fapi, &topic3, &c1);
if (retConsumer == NULL) {
printf("[Topic Test][TaskID:%u][Step:%u][ReUnsubscribe Topic]: ReUnsubscribe Topic lead to NULL return value\n",
(int)osThreadGetId(), g_reUnsubscribeTopic++);
}
provider->Publish((IUnknown *)fapi, &topic3, (uint8_t *) "@@@666@@@", TEST_LEN);
printf("[Topic Test][TaskID:%u][Step:%u][ReUnsubscribe Topic]: Success!\n",
(int)osThreadGetId(), g_reUnsubscribeTopic++);
printf("[Topic Test][TaskID:%u][Step:%u][ReUnsubscribe Topic]: END\n", (int)osThreadGetId(),
g_reUnsubscribeTopic++);
}
static void CASE_ReleaseIUnknown(PubSubInterface *fapi)
{
printf("[Broadcast Test][TaskID:%u][Step:%u][ReleaseIUnknown S:%s]: BEGIN\n",
(int)osThreadGetId(), g_broadcastStep++, BROADCAST_TEST_SERVICE);
int32 ref = fapi->Release((IUnknown *)fapi);
if (ref <= 0) {
printf("[Broadcast Test][TaskID:%u][Step:%u][ReleaseIUnknown S:%s]Error ref is %d!\n",
(int)osThreadGetId(), g_broadcastStep++, BROADCAST_TEST_SERVICE, ref);
goto END;
}
printf("[Broadcast Test][TaskID:%u][Step:%u][ReleaseIUnknown S:%s]Success\n",
(int)osThreadGetId(), g_broadcastStep++, BROADCAST_TEST_SERVICE);
END:
printf("[Broadcast Test][TaskID:%u][Step:%u][ReleaseIUnknown S:%s]: END\n",
(int)osThreadGetId(), g_broadcastStep++, BROADCAST_TEST_SERVICE);
}
static void RunTestCase(void)
{
PubSubInterface *fapi = CASE_GetIUnknown();
CASE_AddAndUnsubscribeTopic(fapi);
CASE_ModifyConsumer(fapi);
CASE_ReUnsubscribeTopic(fapi);
CASE_ReleaseIUnknown(fapi);
}
LAYER_INITCALL_DEF(RunTestCase, test, "test");

@ -0,0 +1,36 @@
/*
* Copyright (c) 2020-2022 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 LITE_EXAMPLE_H
#define LITE_EXAMPLE_H
#define EXAMPLE_SERVICE "example"
#define EXAMPLE_FEATURE "example"
#define BOOT_SYS_SERVICE1 "sys_s1"
#define BOOT_SYS_SERVICE2 "sys_s2"
#define BOOT_SYS_FEATURE1 "sys_f1"
#define BOOT_SYS_FEATURE2 "sys_f2"
#define BOOT_SYSEX_SERVICE1 "sysex_s1"
#define BOOT_SYSEX_SERVICE2 "sysex_s2"
#define BOOT_SYSEX_FEATURE1 "sysex_f1"
#define BOOT_SYSEX_FEATURE2 "sysex_f2"
#define TASK_SERVICE1 "task_s1"
#define TASK_SERVICE2 "task_s2"
#define TASK_SERVICE3 "task_s3"
#define TASK_SERVICE4 "task_s4"
#endif // LITE_EXAMPLE_H

@ -0,0 +1,320 @@
/*
* Copyright (c) 2020-2022 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.
*/
#include "example.h"
#include <stdint.h>
#include <ohos_init.h>
#include <securec.h>
#include <los_base.h>
#include <cmsis_os.h>
#include <samgr_maintenance.h>
#include "iunknown.h"
#include "feature.h"
#include "service.h"
#include "samgr_lite.h"
#include "time_adapter.h"
#define WAIT_FEATURE_PROC 1000
enum MessageId {
MSG_PROC,
MSG_TIME_PROC,
};
struct Payload {
int id;
const char *name;
int value;
};
typedef struct DemoApi {
INHERIT_IUNKNOWN;
BOOL (*AsyncCall)(IUnknown *iUnknown, const char *buff);
BOOL (*AsyncTimeCall)(IUnknown *iUnknown);
BOOL (*SyncCall)(IUnknown *iUnknown, struct Payload *payload);
BOOL (*AsyncCallBack)(IUnknown *iUnknown, const char *buff, Handler handler);
} DemoApi;
typedef struct DemoFeature {
INHERIT_FEATURE;
INHERIT_IUNKNOWNENTRY(DemoApi);
Identity identity;
} DemoFeature;
static BOOL AsyncCall(IUnknown *iUnknown, const char *body);
static BOOL AsyncTimeCall(IUnknown *iUnknown);
static BOOL SyncCall(IUnknown *iUnknown, struct Payload *payload);
static BOOL AsyncCallBack(IUnknown *iUnknown, const char *body, Handler handler);
static const char *FEATURE_GetName(Feature *feature);
static void FEATURE_OnInitialize(Feature *feature, Service *parent, Identity identity);
static void FEATURE_OnStop(Feature *feature, Identity identity);
static BOOL FEATURE_OnMessage(Feature *feature, Request *request);
static DemoFeature g_example = {
.GetName = FEATURE_GetName,
.OnInitialize = FEATURE_OnInitialize,
.OnStop = FEATURE_OnStop,
.OnMessage = FEATURE_OnMessage,
DEFAULT_IUNKNOWN_ENTRY_BEGIN,
.AsyncCall = AsyncCall,
.AsyncTimeCall = AsyncTimeCall,
.SyncCall = SyncCall,
.AsyncCallBack = AsyncCallBack,
DEFAULT_IUNKNOWN_ENTRY_END,
.identity = {-1, -1, NULL},
};
static uint32_t g_regStep = 0;
static const char *FEATURE_GetName(Feature *feature)
{
(void)feature;
return EXAMPLE_FEATURE;
}
static void FEATURE_OnInitialize(Feature *feature, Service *parent, Identity identity)
{
DemoFeature *demoFeature = (DemoFeature *)feature;
demoFeature->identity = identity;
printf("[Register Test][TaskID:%u][Step:%u][Reg Finish S:%s, F:%s]Time: %llu!\n",
(int)osThreadGetId(), g_regStep++, parent->GetName(parent), feature->GetName(feature),
SAMGR_GetProcessTime());
}
static void FEATURE_OnStop(Feature *feature, Identity identity)
{
(void)feature;
(void)identity;
g_example.identity.queueId = NULL;
g_example.identity.featureId = -1;
g_example.identity.serviceId = -1;
}
static volatile uint32 g_asyncStep = 0;
static BOOL FEATURE_OnMessage(Feature *feature, Request *request)
{
(void)feature;
if (request->msgId == MSG_PROC) {
printf("[LPC Test][TaskID:%u][Step:%u][OnMessage: S:%s, F:%s] msgId<MSG_PROC> %s \n",
(int)osThreadGetId(), g_asyncStep++, EXAMPLE_SERVICE, feature->GetName(feature),
(char *)request->data);
Response response = {.data = "Yes, you did!", .len = 0};
SAMGR_SendResponse(request, &response);
return TRUE;
} else {
if (request->msgId == MSG_TIME_PROC) {
LOS_Msleep(WAIT_FEATURE_PROC * 11); // sleep 11 seconds
printf("[LPC Test][TaskID:%u][OnMessage: S:%s, F:%s] Time Message Get Value<%s>!",
(int)osThreadGetId(), EXAMPLE_SERVICE, feature->GetName(feature),
request->msgValue ? "TRUE" : "FALSE");
AsyncTimeCall(GET_IUNKNOWN(g_example));
return FALSE;
}
}
printf("[LPC Test][TaskID:%u][Step:%u][OnMessage S:%s, F:%s] Inner Error! \n",
(int)osThreadGetId(), g_asyncStep++, EXAMPLE_SERVICE, feature->GetName(feature));
return FALSE;
}
static BOOL SyncCall(IUnknown *iUnknown, struct Payload *payload)
{
(void)iUnknown;
if (payload != NULL && payload->id >= 0 && payload->name != NULL) {
printf("[LPC Test][TaskID:%u][Step:%u][SyncCall API] Id:%d, name:%s, value:%d \n",
(int)osThreadGetId(), g_asyncStep++, payload->id, payload->name, payload->value);
return TRUE;
}
printf("[LPC Test][TaskID:%u][Step:%u][SyncCall API] Input Error! \n", (int)osThreadGetId(), g_asyncStep++);
return FALSE;
}
static BOOL AsyncCall(IUnknown *iUnknown, const char *body)
{
Request request = {.msgId = MSG_PROC, .msgValue = 0};
request.len = (uint32_t)(strlen(body) + 1);
request.data = malloc(request.len);
if (request.data == NULL) {
return FALSE;
}
if (strcpy_s(request.data, request.len, body) != EOK) {
free(request.data);
return FALSE;
}
DemoFeature *feature = GET_OBJECT(iUnknown, DemoFeature, iUnknown);
printf("[LPC Test][TaskID:%u][Step:%u][AsyncCall API] Send request! \n", (int)osThreadGetId(), g_asyncStep++);
return SAMGR_SendRequest(&feature->identity, &request, NULL);
}
static BOOL AsyncTimeCall(IUnknown *iUnknown)
{
static int8 cnt = 0;
cnt = (cnt + 1) % 2; // mod 2 to get async status
Request request = {.msgId = MSG_TIME_PROC, .msgValue = cnt};
DemoFeature *feature = GET_OBJECT(iUnknown, DemoFeature, iUnknown);
return SAMGR_SendRequest(&feature->identity, &request, NULL);
}
static BOOL AsyncCallBack(IUnknown *iUnknown, const char *body, Handler handler)
{
Request request = {.msgId = MSG_PROC, .msgValue = 0};
request.len = (uint32_t)(strlen(body) + 1);
request.data = malloc(request.len);
if (request.data == NULL) {
return FALSE;
}
if (strcpy_s(request.data, request.len, body) != EOK) {
free(request.data);
return FALSE;
}
DemoFeature *feature = GET_OBJECT(iUnknown, DemoFeature, iUnknown);
printf("[LPC Test][TaskID:%u][Step:%u][AsyncCallBack API] Send request! \n",
(int)osThreadGetId(), g_asyncStep++);
return SAMGR_SendRequest(&feature->identity, &request, handler);
}
static void Init(void)
{
SAMGR_GetInstance()->RegisterFeature(EXAMPLE_SERVICE, (Feature *)&g_example);
SAMGR_GetInstance()->RegisterFeatureApi(EXAMPLE_SERVICE, EXAMPLE_FEATURE, GET_IUNKNOWN(g_example));
printf("[Register Test][TaskID:%u][Step:%u][Reg S:%s, F:%s]Time: %llu!\n",
(int)osThreadGetId(), g_regStep++, EXAMPLE_SERVICE, EXAMPLE_FEATURE, SAMGR_GetProcessTime());
}
SYSEX_FEATURE_INIT(Init);
static uint32_t g_discoverStep = 0;
static DemoApi *CASE_GetIUnknown(void)
{
DemoApi *demoApi = NULL;
printf("[Discover Test][TaskID:%u][Step:%u][GetIUnknown S:%s, F:%s]: BEGIN\n",
(int)osThreadGetId(), g_discoverStep++, EXAMPLE_SERVICE, EXAMPLE_FEATURE);
IUnknown *iUnknown = SAMGR_GetInstance()->GetFeatureApi(EXAMPLE_SERVICE, EXAMPLE_FEATURE);
if (iUnknown == NULL) {
printf("[Discover Test][TaskID:%u][Step:%u][GetFeatureApi S:%s, F:%s]Error is NULL!\n",
(int)osThreadGetId(), g_discoverStep++, EXAMPLE_SERVICE, EXAMPLE_FEATURE);
goto END;
}
int result = iUnknown->QueryInterface(iUnknown, DEFAULT_VERSION, (void **)&demoApi);
if (result != 0 || demoApi == NULL) {
printf("[Discover Test][TaskID:%u][Step:%u][QueryInterface S:%s, F:%s]Error is NULL!\n",
(int)osThreadGetId(), g_discoverStep++, EXAMPLE_SERVICE, EXAMPLE_FEATURE);
goto END;
}
printf("[Discover Test][TaskID:%u][Step:%u][GetIUnknown S:%s, F:%s]Success\n",
(int)osThreadGetId(), g_discoverStep++, EXAMPLE_SERVICE, EXAMPLE_FEATURE);
END:
printf("[Discover Test][TaskID:%u][Step:%u][GetIUnknown S:%s, F:%s]: END\n",
(int)osThreadGetId(), g_discoverStep++, EXAMPLE_SERVICE, EXAMPLE_FEATURE);
return demoApi;
}
static void CASE_SyncCall(DemoApi *demoApi)
{
if (demoApi->SyncCall == NULL) {
return;
}
printf("[LPC Test][TaskID:%u][Step:%u][SyncCall]: BEGIN! \n", (int)osThreadGetId(), g_asyncStep++);
struct Payload payload = {
.id = 0,
.name = "I want to sync call good result!",
.value = 1
};
if (!demoApi->SyncCall((IUnknown *)demoApi, &payload)) {
printf("[LPC Test][TaskID:%u][Step:%u][SyncCall]Error return false! \n",
(int)osThreadGetId(), g_asyncStep++);
goto END;
}
printf("[LPC Test][TaskID:%u][Step:%u][SyncCall]Success!\n",
(int)osThreadGetId(), g_asyncStep++);
END:
printf("[LPC Test][TaskID:%u][Step:%u][SyncCall]: END\n",
(int)osThreadGetId(), g_asyncStep++);
}
static void CASE_AsyncCall(DemoApi *demoApi)
{
if (demoApi->AsyncCall == NULL) {
return;
}
printf("[LPC Test][TaskID:%u][Step:%u][AsyncCall]: BEGIN! \n", (int)osThreadGetId(), g_asyncStep++);
uint32 count = g_asyncStep;
demoApi->AsyncCall((IUnknown *)demoApi, "I want to async call good result!");
LOS_Msleep(WAIT_FEATURE_PROC);
if (count == g_asyncStep) {
printf("[LPC Test][TaskID:%u][Step:%u][AsyncCall] result is failed! \n", (int)osThreadGetId(),
g_asyncStep++);
goto END;
}
printf("[LPC Test][TaskID:%u][Step:%u][AsyncCall]Success! \n", (int)osThreadGetId(), g_asyncStep++);
END:
printf("[LPC Test][TaskID:%u][Step:%u][AsyncCall]: END! \n", (int)osThreadGetId(), g_asyncStep++);
}
static void CASE_AsyncTimeCall(DemoApi *demoApi)
{
if (demoApi->AsyncCall == NULL) {
return;
}
demoApi->AsyncTimeCall((IUnknown *)demoApi);
}
void AsyncHandler(const Request *request, const Response *response)
{
(void)request;
printf("[LPC Test][TaskID:%u][Step:%u][AsyncCallBack]Success! Response:%s \n",
(int)osThreadGetId(), g_asyncStep++, (char *)response->data);
printf("[LPC Test][TaskID:%u][Step:%u][AsyncCallBack]: END! \n", (int)osThreadGetId(), g_asyncStep++);
}
static void CASE_AsyncCallBack(DemoApi *demoApi)
{
if (demoApi->AsyncCallBack == NULL) {
return;
}
printf("[LPC Test][TaskID:%u][Step:%u][AsyncCallBack]: BEGIN! \n", (int)osThreadGetId(), g_asyncStep++);
demoApi->AsyncCallBack((IUnknown *)demoApi, "I want to async call callback good result!", AsyncHandler);
printf("[LPC Test][TaskID:%u][Step:%u][AsyncCallBack]Wait for response! \n",
(int)osThreadGetId(), g_asyncStep++);
}
static void CASE_ReleaseIUnknown(DemoApi *demoApi)
{
printf("[Discover Test][TaskID:%u][Step:%u][ReleaseIUnknown S:%s, F:%s]: BEGIN\n",
(int)osThreadGetId(), g_discoverStep++, EXAMPLE_SERVICE, EXAMPLE_FEATURE);
int32 ref = demoApi->Release((IUnknown *)demoApi);
if (ref <= 0) {
printf("[Discover Test][TaskID:%u][Step:%u][ReleaseIUnknown S:%s, F:%s]Error ref is %d!\n",
(int)osThreadGetId(), g_discoverStep++, EXAMPLE_SERVICE, EXAMPLE_FEATURE, ref);
goto END;
}
printf("[Discover Test][TaskID:%u][Step:%u][ReleaseIUnknown S:%s, F:%s]Success\n",
(int)osThreadGetId(), g_discoverStep++, EXAMPLE_SERVICE, EXAMPLE_FEATURE);
END:
printf("[Discover Test][TaskID:%u][Step:%u][ReleaseIUnknown S:%s, F:%s]: END\n",
(int)osThreadGetId(), g_discoverStep++, EXAMPLE_SERVICE, EXAMPLE_FEATURE);
}
static void RunTestCase(void)
{
DemoApi *demoApi = CASE_GetIUnknown();
CASE_SyncCall(demoApi);
CASE_AsyncCall(demoApi);
CASE_AsyncCallBack(demoApi);
CASE_AsyncTimeCall(demoApi);
CASE_ReleaseIUnknown(demoApi);
}
LAYER_INITCALL_DEF(RunTestCase, test, "test");

@ -0,0 +1,179 @@
/*
* Copyright (c) 2020-2022 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.
*/
#include <stdint.h>
#include <securec.h>
#include <ohos_init.h>
#include <cmsis_os.h>
#include <samgr_maintenance.h>
#include "service.h"
#include "feature.h"
#include "samgr_lite.h"
#define MAINTEN_SERVICE1 "mntn_s1"
#define MAINTEN_SERVICE2 "mntn_s2"
#define MAINTEN_SERVICE3 "mntn_s3"
#define MAINTEN_SERVICE4 "mntn_s4"
#define MAINTEN_FEATURE1 "mntn_f1"
#define MAINTEN_FEATURE2 "mntn_f2"
static const char *GetName(Service *service);
static BOOL Initialize(Service *service, Identity identity);
static BOOL MessageHandle(Service *service, Request *msg);
static TaskConfig GetTaskConfig(Service *service);
static const char *FEATURE_GetName(Feature *feature);
static void FEATURE_OnInitialize(Feature *feature, Service *parent, Identity identity);
static void FEATURE_OnStop(Feature *feature, Identity identity);
static BOOL FEATURE_OnMessage(Feature *feature, Request *request);
Service g_maintenExample1 = {GetName, Initialize, MessageHandle, GetTaskConfig};
Service g_maintenExample2 = {GetName, Initialize, MessageHandle, GetTaskConfig};
Service g_maintenExample3 = {GetName, Initialize, MessageHandle, GetTaskConfig};
Service g_maintenExample4 = {GetName, Initialize, MessageHandle, GetTaskConfig};
Feature g_maintenFeature1 = {FEATURE_GetName, FEATURE_OnInitialize, FEATURE_OnStop, FEATURE_OnMessage};
Feature g_maintenFeature2 = {FEATURE_GetName, FEATURE_OnInitialize, FEATURE_OnStop, FEATURE_OnMessage};
IUnknownEntry g_demoApi = {DEFAULT_IUNKNOWN_ENTRY_BEGIN, DEFAULT_IUNKNOWN_ENTRY_END};
static const char *FEATURE_GetName(Feature *feature)
{
if (feature == &g_maintenFeature1) {
return MAINTEN_FEATURE1;
}
if (feature == &g_maintenFeature2) {
return MAINTEN_FEATURE2;
}
return NULL;
}
static void FEATURE_OnInitialize(Feature *feature, Service *parent, Identity identity)
{
(void)feature;
(void)parent;
(void)identity;
}
static void FEATURE_OnStop(Feature *feature, Identity identity)
{
(void)feature;
(void)identity;
}
static BOOL FEATURE_OnMessage(Feature *feature, Request *request)
{
(void)feature;
(void)request;
return FALSE;
}
static const char *GetName(Service *service)
{
if (service == &g_maintenExample1) {
return MAINTEN_SERVICE1;
}
if (service == &g_maintenExample2) {
return MAINTEN_SERVICE2;
}
if (service == &g_maintenExample3) {
return MAINTEN_SERVICE3;
}
if (service == &g_maintenExample4) {
return MAINTEN_SERVICE4;
}
return NULL;
}
static BOOL Initialize(Service *service, Identity identity)
{
(void)identity;
(void)service;
return TRUE;
}
static BOOL MessageHandle(Service *service, Request *msg)
{
(void)service;
(void)msg;
return FALSE;
}
static TaskConfig GetTaskConfig(Service *service)
{
(void)service;
TaskConfig config = {LEVEL_HIGH, PRI_NORMAL,
0x800, 16, SHARED_TASK};
if (service == &g_maintenExample4) {
config.priority = PRI_ABOVE_NORMAL;
config.stackSize = 0x400;
}
return config;
}
static void SInit(Service *service)
{
if (service == &g_maintenExample4) {
printf("[Maintenance Test][Before App Service Init]Print Uninitialized App Service\n");
SAMGR_PrintServices();
}
SAMGR_GetInstance()->RegisterService(service);
}
static void FInit(Feature *feature)
{
if (feature == &g_maintenFeature1) {
SAMGR_GetInstance()->RegisterFeature(MAINTEN_SERVICE1, feature);
SAMGR_GetInstance()->RegisterFeatureApi(MAINTEN_SERVICE1, MAINTEN_FEATURE1, GET_IUNKNOWN(g_demoApi));
}
if (feature == &g_maintenFeature2) {
SAMGR_GetInstance()->RegisterFeature(MAINTEN_SERVICE2, feature);
SAMGR_GetInstance()->RegisterDefaultFeatureApi(MAINTEN_SERVICE2, GET_IUNKNOWN(g_demoApi));
}
}
static void S1Init(void)
{
SInit(&g_maintenExample1);
}
static void S2Init(void)
{
SInit(&g_maintenExample2);
}
static void S3Init(void)
{
SInit(&g_maintenExample3);
}
static void S4Init(void)
{
SInit(&g_maintenExample4);
}
static void F1Init(void)
{
FInit(&g_maintenFeature1);
}
static void F2Init(void)
{
FInit(&g_maintenFeature2);
}
SYSEX_SERVICE_INIT(S1Init);
SYSEX_SERVICE_INIT(S2Init);
SYSEX_SERVICE_INIT(S3Init);
SYSEX_SERVICE_INIT(S4Init);
SYSEX_FEATURE_INIT(F1Init);
SYSEX_FEATURE_INIT(F2Init);

@ -0,0 +1,187 @@
/*
* Copyright (c) 2020-2022 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.
*/
#include "example.h"
#include <stdint.h>
#include <ohos_init.h>
#include <securec.h>
#include <los_base.h>
#include <cmsis_os.h>
#include "iunknown.h"
#include "feature.h"
#include "service.h"
#include "samgr_lite.h"
#include "time_adapter.h"
typedef struct DefaultFeatureApi {
INHERIT_IUNKNOWN;
void (*SyncCall)(IUnknown *iUnknown);
} DefaultFeatureApi;
typedef struct ExampleService {
INHERIT_SERVICE;
INHERIT_IUNKNOWNENTRY(DefaultFeatureApi);
Identity identity;
} ExampleService;
static const char *GetName(Service *service)
{
(void)service;
return EXAMPLE_SERVICE;
}
static uint32_t g_regStep = 0;
static BOOL Initialize(Service *service, Identity identity)
{
ExampleService *example = (ExampleService *)service;
example->identity = identity;
printf("[Register Test][TaskID:%u][Step:%u][Reg Finish S:%s]Time: %llu!\n",
(int)osThreadGetId(), g_regStep++, service->GetName(service), SAMGR_GetProcessTime());
return TRUE;
}
static BOOL MessageHandle(Service *service, Request *msg)
{
printf("[LPC Test][TaskID:%u] msgId<%d>: %s \n", (int)osThreadGetId(), msg->msgId, (char *)msg->data);
(void)service;
return FALSE;
}
static TaskConfig GetTaskConfig(Service *service)
{
(void)service;
TaskConfig config = {LEVEL_HIGH, PRI_BELOW_NORMAL,
0x800, 20, SHARED_TASK};
return config;
}
static volatile uint32 g_asyncStep = 0;
static void SyncCall(IUnknown *iUnknown)
{
(void)iUnknown;
printf("[LPC Test][TaskID:%u][Step:%u][SyncCall API] Default Success!\n", (int)osThreadGetId(),
g_asyncStep++);
}
static ExampleService g_example = {
.GetName = GetName,
.Initialize = Initialize,
.MessageHandle = MessageHandle,
.GetTaskConfig = GetTaskConfig,
DEFAULT_IUNKNOWN_ENTRY_BEGIN,
.SyncCall = SyncCall,
DEFAULT_IUNKNOWN_ENTRY_END,
};
static void Init(void)
{
SAMGR_GetInstance()->RegisterService((Service *)&g_example);
SAMGR_GetInstance()->RegisterDefaultFeatureApi(EXAMPLE_SERVICE, GET_IUNKNOWN(g_example));
printf("[Register Test][TaskID:%u][Step:%u][Reg S:%s]Time: %llu!\n",
(int)osThreadGetId(), g_regStep++, EXAMPLE_SERVICE, SAMGR_GetProcessTime());
}
SYSEX_SERVICE_INIT(Init);
static uint32_t g_discoverStep = 0;
static DefaultFeatureApi *CASE_GetIUnknown(void)
{
DefaultFeatureApi *demoApi = NULL;
printf("[Discover Test][TaskID:%u][Step:%u][GetIUnknown S:%s]: BEGIN\n",
(int)osThreadGetId(), g_discoverStep++, EXAMPLE_SERVICE);
IUnknown *iUnknown = SAMGR_GetInstance()->GetDefaultFeatureApi(EXAMPLE_SERVICE);
if (iUnknown == NULL) {
printf("[Discover Test][TaskID:%u][Step:%u][GetDefaultFeatureApi S:%s]Error is NULL!\n",
(int)osThreadGetId(), g_discoverStep++, EXAMPLE_SERVICE);
goto END;
}
int result = iUnknown->QueryInterface(iUnknown, DEFAULT_VERSION, (void **)&demoApi);
if (result != 0 || demoApi == NULL) {
printf("[Discover Test][TaskID:%u][Step:%u][QueryInterface S:%s]Error is NULL!\n",
(int)osThreadGetId(), g_discoverStep++, EXAMPLE_SERVICE);
goto END;
}
printf("[Discover Test][TaskID:%u][Step:%u][GetIUnknown S:%s]Success\n",
(int)osThreadGetId(), g_discoverStep++, EXAMPLE_SERVICE);
END:
printf("[Discover Test][TaskID:%u][Step:%u][GetIUnknown S:%s]: END\n",
(int)osThreadGetId(), g_discoverStep++, EXAMPLE_SERVICE);
return demoApi;
}
static void CASE_SyncCall(DefaultFeatureApi *defaultApi)
{
printf("[LPC Test][TaskID:%u][Step:%u][DefaultFeature SyncCall]: BEGIN\n", (int)osThreadGetId(),
g_asyncStep++);
defaultApi->SyncCall((IUnknown *)defaultApi);
printf("[LPC Test][TaskID:%u][Step:%u][DefaultFeature SyncCall]: END\n", (int)osThreadGetId(),
g_asyncStep++);
}
static void CASE_ReleaseIUnknown(DefaultFeatureApi *demoApi)
{
printf("[Discover Test][TaskID:%u][Step:%u][ReleaseIUnknown S:%s]: BEGIN\n",
(int)osThreadGetId(), g_discoverStep++, EXAMPLE_SERVICE);
int32 ref = demoApi->Release((IUnknown *)demoApi);
if (ref <= 0) {
printf("[Discover Test][TaskID:%u][Step:%u][ReleaseIUnknown S:%s]Error ref is %d!\n",
(int)osThreadGetId(), g_discoverStep++, EXAMPLE_SERVICE, ref);
goto END;
}
printf("[Discover Test][TaskID:%u][Step:%u][ReleaseIUnknown S:%s]Success\n",
(int)osThreadGetId(), g_discoverStep++, EXAMPLE_SERVICE);
END:
printf("[Discover Test][TaskID:%u][Step:%u][ReleaseIUnknown S:%s]: END\n",
(int)osThreadGetId(), g_discoverStep++, EXAMPLE_SERVICE);
}
static void CASE_RegisterInvalidService(void)
{
Service service = {.GetName = NULL, .GetTaskConfig = NULL, .Initialize = NULL, .MessageHandle = NULL};
BOOL ret = SAMGR_GetInstance()->RegisterService(&service);
printf("Register Invalid Service %s\n", ret ? "TRUE" : "FALSE");
Feature feature = {.GetName = NULL, .OnInitialize = NULL, .OnMessage = NULL, .OnStop = NULL};
ret = SAMGR_GetInstance()->RegisterFeature(EXAMPLE_SERVICE, &feature);
printf("Register Invalid Feature %s\n", ret ? "TRUE" : "FALSE");
IUnknownEntry entry = {
.ver = DEFAULT_VERSION,
.ref = 1,
.iUnknown = {
.QueryInterface = NULL,
.Release = NULL,
.AddRef = NULL
}
};
ret = SAMGR_GetInstance()->RegisterDefaultFeatureApi(EXAMPLE_SERVICE, GET_IUNKNOWN(entry));
printf("Register Invalid Default Api %s\n", ret ? "TRUE" : "FALSE");
ret = SAMGR_GetInstance()->RegisterFeatureApi(EXAMPLE_SERVICE, EXAMPLE_FEATURE "2", GET_IUNKNOWN(entry));
printf("Register Invalid " EXAMPLE_FEATURE "2 Api %s\n", ret ? "TRUE" : "FALSE");
}
static void RunTestCase(void)
{
DefaultFeatureApi *defaultApi = CASE_GetIUnknown();
CASE_RegisterInvalidService();
CASE_SyncCall(defaultApi);
CASE_ReleaseIUnknown(defaultApi);
}
LAYER_INITCALL_DEF(RunTestCase, test, "test");

@ -0,0 +1,119 @@
/*
* Copyright (c) 2020-2022 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.
*/
#include <los_base.h>
#include <securec.h>
#include <ohos_init.h>
#include <cmsis_os.h>
#include "service.h"
#include "samgr_lite.h"
#define TIME_UNLIMITED_CASE 0
#define WAIT_BOOT_PROC ((1000) * (11))
#define TEST_SYS_SERVICE1 "tst_sys1"
#define TEST_SYS_SERVICE2 "tst_sys2"
#define TEST_APP_SERVICE1 "tst_app1"
#define TEST_APP_SERVICE2 "tst_app2"
static const char *GetName(Service *service);
static BOOL Initialize(Service *service, Identity identity);
static BOOL MessageHandle(Service *service, Request *msg);
static TaskConfig GetTaskConfig(Service *service);
static Service g_testSys1 = {GetName, Initialize, MessageHandle, GetTaskConfig};
static Service g_testSys2 = {GetName, Initialize, MessageHandle, GetTaskConfig};
static Service g_testApp1 = {GetName, Initialize, MessageHandle, GetTaskConfig};
static Service g_testApp2 = {GetName, Initialize, MessageHandle, GetTaskConfig};
static const char *GetName(Service *service)
{
if (service == &g_testSys1) {
return TEST_SYS_SERVICE1;
}
if (service == &g_testSys2) {
return TEST_SYS_SERVICE2;
}
if (service == &g_testApp1) {
return TEST_APP_SERVICE1;
}
if (service == &g_testApp2) {
return TEST_APP_SERVICE2;
}
return NULL;
}
static BOOL Initialize(Service *service, Identity identity)
{
(void)identity;
if (service == &g_testSys1 || service == &g_testApp1) {
printf("[Recovery Test][Initialize]Time Out Case Running\n");
LOS_Msleep(WAIT_BOOT_PROC);
return TRUE;
}
#if TIME_UNLIMITED_CASE
if (service == &g_testSys2 || service == &g_testApp2) {
printf("[Recovery Test][Initialize]Time Unlimited Case Running\n\n");
while (1) {
(void)identity;
}
return TRUE;
}
#endif
return TRUE;
}
static BOOL MessageHandle(Service *service, Request *msg)
{
(void)service;
(void)msg;
return FALSE;
}
static TaskConfig GetTaskConfig(Service *service)
{
(void)service;
TaskConfig config = {LEVEL_HIGH, PRI_NORMAL,
0x400, 16, SHARED_TASK};
return config;
}
static void SInit(Service *demo)
{
SAMGR_GetInstance()->RegisterService(demo);
}
static void SS1Init(void)
{
SInit(&g_testSys1);
}
static void SS2Init(void)
{
SInit(&g_testSys2);
}
static void AS1Init(void)
{
SInit(&g_testApp1);
}
static void AS2Init(void)
{
SInit(&g_testApp2);
}
SYS_SERVICE_INIT(SS1Init);
SYS_SERVICE_INIT(SS2Init);
SYSEX_SERVICE_INIT(AS1Init);
SYSEX_SERVICE_INIT(AS2Init);

@ -0,0 +1,227 @@
/*
* Copyright (c) 2020-2022 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.
*/
#include <stdint.h>
#include <securec.h>
#include <ohos_init.h>
#include <cmsis_os.h>
#include "service.h"
#include "samgr_lite.h"
#include "time_adapter.h"
#define TOTAL_SPEC_TASK_NUM 19
static const char *g_specTaskService[] = {
"ltsk_s1", "ltsk_s2", "ltsk_s3",
"otsk_s1", "otsk_s2", "otsk_s3", "otsk_s4",
"otsk_s5", "otsk_s6", "otsk_s7", "otsk_s8",
"otsk_s9", "otsk_s10", "otsk_s11", "otsk_s12",
"otsk_s13", "otsk_s14", "otsk_s15", "otsk_s16",
};
static const char *g_specServiceName1[] = {
"l6tsk_s1", "l6tsk_s2"
};
static const char *g_specServiceName2[] = {
"l7tsk_s1", "l7tsk_s2", "l7tsk_s3"
};
static const char *g_specServiceName3[] = {
"l8tsk_s1", "l8tsk_s2", "l8tsk_s3", "l8tsk_s4"
};
static const char *GetName(Service *service);
static const char *GetSpec1Name(Service *service);
static const char *GetSpec2Name(Service *service);
static const char *GetSpec3Name(Service *service);
static BOOL Initialize(Service *service, Identity identity);
static BOOL MessageHandle(Service *service, Request *msg);
static TaskConfig GetLowTagTaskConfig(Service *service);
static TaskConfig GetHighTagTaskConfig(Service *service);
static TaskConfig GetSpec1TagTaskConfig(Service *service);
static TaskConfig GetSpec2TagTaskConfig(Service *service);
static TaskConfig GetSpec3TagTaskConfig(Service *service);
static Service g_example[] = {
{GetName, Initialize, MessageHandle, GetLowTagTaskConfig},
{GetName, Initialize, MessageHandle, GetLowTagTaskConfig},
{GetName, Initialize, MessageHandle, GetLowTagTaskConfig},
{GetName, Initialize, MessageHandle, GetHighTagTaskConfig},
{GetName, Initialize, MessageHandle, GetHighTagTaskConfig},
{GetName, Initialize, MessageHandle, GetHighTagTaskConfig},
{GetName, Initialize, MessageHandle, GetHighTagTaskConfig},
{GetName, Initialize, MessageHandle, GetHighTagTaskConfig},
{GetName, Initialize, MessageHandle, GetHighTagTaskConfig},
{GetName, Initialize, MessageHandle, GetHighTagTaskConfig},
{GetName, Initialize, MessageHandle, GetHighTagTaskConfig},
{GetName, Initialize, MessageHandle, GetHighTagTaskConfig},
{GetName, Initialize, MessageHandle, GetHighTagTaskConfig},
{GetName, Initialize, MessageHandle, GetHighTagTaskConfig},
{GetName, Initialize, MessageHandle, GetHighTagTaskConfig},
{GetName, Initialize, MessageHandle, GetHighTagTaskConfig},
{GetName, Initialize, MessageHandle, GetHighTagTaskConfig},
{GetName, Initialize, MessageHandle, GetHighTagTaskConfig},
{GetName, Initialize, MessageHandle, GetHighTagTaskConfig}
};
static Service g_exampleSpec1[] = {
{GetSpec1Name, Initialize, MessageHandle, GetSpec1TagTaskConfig},
{GetSpec1Name, Initialize, MessageHandle, GetSpec1TagTaskConfig}
};
static Service g_exampleSpec2[] = {
{GetSpec2Name, Initialize, MessageHandle, GetSpec2TagTaskConfig},
{GetSpec2Name, Initialize, MessageHandle, GetSpec2TagTaskConfig},
{GetSpec2Name, Initialize, MessageHandle, GetSpec2TagTaskConfig}
};
static Service g_exampleSpec3[] = {
{GetSpec3Name, Initialize, MessageHandle, GetSpec3TagTaskConfig},
{GetSpec3Name, Initialize, MessageHandle, GetSpec3TagTaskConfig},
{GetSpec3Name, Initialize, MessageHandle, GetSpec3TagTaskConfig},
{GetSpec3Name, Initialize, MessageHandle, GetSpec3TagTaskConfig}
};
static uint32_t g_initIndex = 0;
static const char *GetName(Service *service)
{
int i;
for (i = 0; i < TOTAL_SPEC_TASK_NUM; ++i) {
if (service == &g_example[i]) {
return g_specTaskService[i];
}
}
return NULL;
}
static const char *GetSpec1Name(Service *service)
{
int i;
// g_exampleSpec1 has 2 services
for (i = 0; i < 2; ++i) {
if (service == &g_exampleSpec1[i]) {
return g_specServiceName1[i];
}
}
return NULL;
}
static const char *GetSpec2Name(Service *service)
{
int i;
// g_exampleSpec2 has 3 services
for (i = 0; i < 3; ++i) {
if (service == &g_exampleSpec2[i]) {
return g_specServiceName2[i];
}
}
return NULL;
}
static const char *GetSpec3Name(Service *service)
{
int i;
// g_exampleSpec3 has 4 services
for (i = 0; i < 4; ++i) {
if (service == &g_exampleSpec3[i]) {
return g_specServiceName3[i];
}
}
return NULL;
}
static BOOL Initialize(Service *service, Identity identity)
{
(void)identity;
printf("[Specified Task Test][TaskID:%u][Step:%u][Reg Finish S:%s]Time: %llu!\n",
(int)osThreadGetId(), g_initIndex++, service->GetName(service), SAMGR_GetProcessTime());
return TRUE;
}
static BOOL MessageHandle(Service *service, Request *msg)
{
printf("[Specified Task Test][TaskID:%u][Step:%u][S:%s] msgId<%d> \n",
(int)osThreadGetId(), g_initIndex++, service->GetName(service), msg->msgId);
return FALSE;
}
static TaskConfig GetLowTagTaskConfig(Service *service)
{
(void)service;
int16 customLevelLow = LEVEL_CUSTOM_BEGIN + 1;
TaskConfig config = {customLevelLow, PRI_NORMAL,
0x400, 16, SPECIFIED_TASK};
return config;
}
static TaskConfig GetHighTagTaskConfig(Service *service)
{
(void)service;
int16 customLevelHigh = LEVEL_CUSTOM_BEGIN + 2; // Custom level 2
TaskConfig config = {customLevelHigh, PRI_NORMAL,
0x400, 16, SPECIFIED_TASK};
return config;
}
static TaskConfig GetSpec1TagTaskConfig(Service *service)
{
(void)service;
int16 customLevelSpec1 = LEVEL_CUSTOM_BEGIN + 3; // Custom level 3
TaskConfig config = {customLevelSpec1, PRI_NORMAL,
0x400, 16, SPECIFIED_TASK};
return config;
}
static TaskConfig GetSpec2TagTaskConfig(Service *service)
{
(void)service;
int16 customLevelSpec2 = LEVEL_CUSTOM_BEGIN + 4; // Custom level 4
TaskConfig config = {customLevelSpec2, PRI_NORMAL,
0x400, 16, SPECIFIED_TASK};
return config;
}
static TaskConfig GetSpec3TagTaskConfig(Service *service)
{
(void)service;
int16 customLevelSpec3 = LEVEL_CUSTOM_BEGIN + 5; // Custom level 5
TaskConfig config = {customLevelSpec3, PRI_NORMAL,
0x400, 16, SPECIFIED_TASK};
return config;
}
static void SInit(Service *demo)
{
SAMGR_GetInstance()->RegisterService(demo);
printf("[Specified Task Test][TaskID:%u][Step:%u][SYSEX Reg S:%s]Time: %llu!\n",
(int)osThreadGetId(), g_initIndex++, demo->GetName(demo), SAMGR_GetProcessTime());
}
static void SSInit(void)
{
int i;
for (i = 0; i < TOTAL_SPEC_TASK_NUM; ++i) {
SInit(&g_example[i]);
}
// g_exampleSpec1 has 2 services
for (i = 0; i < 2; ++i) {
SInit(&g_exampleSpec1[i]);
}
// g_exampleSpec2 has 3 services
for (i = 0; i < 3; ++i) {
SInit(&g_exampleSpec2[i]);
}
// g_exampleSpec3 has 4 services
for (i = 0; i < 4; ++i) {
SInit(&g_exampleSpec3[i]);
}
}
SYSEX_SERVICE_INIT(SSInit);

@ -0,0 +1,123 @@
/*
* Copyright (c) 2020-2022 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.
*/
#include "example.h"
#include <stdint.h>
#include <feature.h>
#include <securec.h>
#include <ohos_init.h>
#include <samgr_lite.h>
#include <cmsis_os.h>
#include "time_adapter.h"
static const char *GetName(Service *service);
static BOOL Initialize(Service *service, Identity identity);
static BOOL MessageHandle(Service *service, Request *msg);
static TaskConfig GetTaskConfig(Service *service);
static Service g_example[] = {
{GetName, Initialize, MessageHandle, GetTaskConfig},
{GetName, Initialize, MessageHandle, GetTaskConfig},
{GetName, Initialize, MessageHandle, GetTaskConfig},
{GetName, Initialize, MessageHandle, GetTaskConfig}
};
static int g_initIndex = 0;
static const char *GetName(Service *service)
{
// test cases demo 0
if (service == &g_example[0]) {
return TASK_SERVICE1;
}
// test cases demo 1
if (service == &g_example[1]) {
return TASK_SERVICE2;
}
// test cases demo 2
if (service == &g_example[2]) {
return TASK_SERVICE3;
}
// test cases demo 3
if (service == &g_example[3]) {
return TASK_SERVICE4;
}
return NULL;
}
static BOOL Initialize(Service *service, Identity identity)
{
(void)identity;
printf("[Task Test][TaskID:%u][Step:%u][Reg Finish S:%s]Time: %llu!\n",
(int)osThreadGetId(), g_initIndex++, service->GetName(service), SAMGR_GetProcessTime());
return TRUE;
}
static BOOL MessageHandle(Service *service, Request *msg)
{
printf("[Task Test][TaskID:%u][Step:%u][S:%s] msgId<%d> \n",
(int)osThreadGetId(), g_initIndex++, service->GetName(service), msg->msgId);
return FALSE;
}
static TaskConfig GetTaskConfig(Service *service)
{
TaskConfig config = {LEVEL_HIGH, PRI_NORMAL,
0x800, 5, SHARED_TASK};
// test cases demo 0
if (service == &g_example[0]) {
config.taskFlags = SINGLE_TASK;
}
// test cases demo 3
if (service == &g_example[3]) {
config.priority = PRI_ABOVE_NORMAL;
}
return config;
}
static void SInit(Service *demo)
{
SAMGR_GetInstance()->RegisterService(demo);
printf("[Task Test][TaskID:%u][Step:%u][SYSEX Reg S:%s]Time: %llu!\n",
(int)osThreadGetId(), g_initIndex++, demo->GetName(demo), SAMGR_GetProcessTime());
}
static void S1Init(void)
{
// test cases demo 0
SInit(&g_example[0]);
}
static void S2Init(void)
{
// test cases demo 1
SInit(&g_example[1]);
}
static void S3Init(void)
{
// test cases demo 2
SInit(&g_example[2]);
}
static void S4Init(void)
{
// test cases demo 3
SInit(&g_example[3]);
}
SYSEX_SERVICE_INIT(S1Init);
SYSEX_SERVICE_INIT(S2Init);
SYSEX_SERVICE_INIT(S3Init);
SYSEX_SERVICE_INIT(S4Init);

Binary file not shown.

After

Width:  |  Height:  |  Size: 163 KiB

@ -0,0 +1,90 @@
[
{
"return-x-y":[199, 1262],
"recent-x-y":[500, 1262],
"home-x-y":[350, 1262],
"recent_del-x-y":[350, 1140],
"permisson_ok-x-y":[495, 690],
"permisson_no-x-y":[241, 690],
"shot_cmd":[""],
"cmp_cmd-level":["", 443200]
},
{
"app_name": "launcher",
"entry": "",
"all_actions": [[2, "shot_cmd"], [2, "cmp_cmd-level"]]
},
{
"app_name": "settings",
"entry": "aa start -a com.ohos.settings.MainAbility -b com.ohos.settings",
"all_actions": [
[3, "shot_cmd", "settings"], [3, "cmp_cmd-level"], [3, 400, 120], [3, 400, 120], [20, 400, 80], [3, 400, 80],
[3, "shot_cmd", "keyboard"], [3, "recent-x-y"], [3, "recent_del-x-y"], [3, "recent-x-y"], [3, "recent_del-x-y"], [3, "cmp_cmd-level", 200000]
]
},
{
"app_name": "photos",
"entry": "aa start -a com.ohos.photos.MainAbility -b com.ohos.photos",
"all_actions": [[2, "permisson_ok-x-y"], [2, "permisson_ok-x-y"], [2, "recent-x-y"], [2, "recent_del-x-y"], [2, "recent-x-y"], [2, "recent_del-x-y"]]
},
{
"app_name": "photos",
"entry": "aa start -a com.ohos.photos.MainAbility -b com.ohos.photos",
"all_actions": [[2, "shot_cmd"], [2, "recent-x-y"], [2, "recent_del-x-y"], [2, "cmp_cmd-level"], [2, "recent-x-y"], [2, "recent_del-x-y"]]
},
{
"app_name": "distributedcalc",
"entry": "aa start -a com.example.distributedcalc.default -b com.example.distributedcalc",
"all_actions": [[2, "permisson_ok-x-y"], [2, "permisson_ok-x-y"], [2, "shot_cmd"], [2, "recent-x-y"], [2, "recent_del-x-y"], [2, "cmp_cmd-level", 3686400], [2, "recent-x-y"], [2, "recent_del-x-y"]]
},
{
"app_name": "camera",
"entry": "aa start -a com.ohos.camera.MainAbility -b com.ohos.camera",
"all_actions": [
[2, "permisson_ok-x-y"], [2, "permisson_ok-x-y"], [2, "permisson_ok-x-y"], [2, "permisson_ok-x-y"], [2, "permisson_ok-x-y"],
[2, "recent-x-y"], [2, "recent_del-x-y"], [2, "recent-x-y"], [2, "recent_del-x-y"]
]
},
{
"app_name": "camera",
"entry": "aa start -a com.ohos.camera.MainAbility -b com.ohos.camera",
"all_actions": [[2, "shot_cmd"], [2, "recent-x-y"], [2, "recent_del-x-y"], [2, "recent-x-y"], [2, "recent_del-x-y"], [2, "cmp_cmd-level", 3686400]]
},
{
"app_name": "contacts",
"entry": "aa start -a com.ohos.contacts.MainAbility -b com.ohos.contacts",
"all_actions": [
[2, "permisson_ok-x-y"], [2, "permisson_ok-x-y"], [2, "permisson_ok-x-y"], [2, "permisson_ok-x-y"],
[2, "recent-x-y"], [2, "recent_del-x-y"], [2, "recent-x-y"], [2, "recent_del-x-y"]
]
},
{
"app_name": "contacts",
"entry": "aa start -a com.ohos.contacts.MainAbility -b com.ohos.contacts",
"all_actions": [[2, "shot_cmd"], [2, "recent-x-y"], [2, "recent_del-x-y"], [2, "cmp_cmd-level", 3686400], [2, "recent-x-y"], [2, "recent_del-x-y"]]
},
{
"app_name": "music",
"entry": "aa start -a com.ohos.distributedmusicplayer.MainAbility -b com.ohos.distributedmusicplayer",
"all_actions": [[2, "permisson_ok-x-y"], [2, "permisson_ok-x-y"], [2, "recent-x-y"], [2, "recent_del-x-y"], [2, "recent-x-y"], [2, "recent_del-x-y"]]
},
{
"app_name": "music",
"entry": "aa start -a com.ohos.distributedmusicplayer.MainAbility -b com.ohos.distributedmusicplayer",
"all_actions": [[2, "permisson_ok-x-y"], [2, "shot_cmd"], [2, "recent-x-y"], [2, "recent_del-x-y"], [2, "recent-x-y"], [2, "recent_del-x-y"], [2, "cmp_cmd-level", 3686400]]
},
{
"app_name": "mms",
"entry": "aa start -a com.ohos.mms.MainAbility -b com.ohos.mms",
"all_actions": [
[2, "permisson_ok-x-y"], [2, "permisson_ok-x-y"], [2, "permisson_ok-x-y"],
[2, "shot_cmd"], [2, "recent-x-y"], [2, "recent_del-x-y"], [2, "recent-x-y"], [2, "recent_del-x-y"], [2, "cmp_cmd-level", 3686400]
]
},
{
"app_name": "note",
"entry": "aa start -a com.ohos.note.MainAbility -b com.ohos.note",
"all_actions": [[2, "shot_cmd"], [2, "recent-x-y"], [2, "recent_del-x-y"], [2, "recent-x-y"], [2, "recent_del-x-y"], [2, "cmp_cmd-level", 3686400]]
}
]

Binary file not shown.

After

Width:  |  Height:  |  Size: 316 KiB

@ -0,0 +1,136 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2022 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.
from ast import parse
import json
import sys
import os
import time
import argparse
import re
def EnterCmd(mycmd, waittime = 0, printresult = 1):
if mycmd == "":
return
with os.popen(mycmd) as p:
result = p.readlines()
if printresult == 1:
print(result)
sys.stdout.flush()
if waittime != 0:
time.sleep(waittime)
return result
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='manual to this script')
parser.add_argument('--config', type=str, default = './app_capture_screen_test_config.json')
parser.add_argument('--anwser_path', type=str, default = 'screenshot\\RK\\')
parser.add_argument('--save_path', type=str, default = './report/screenshot_1/')
args = parser.parse_args()
with open(args.config) as f:
all_app = json.load(f)
cmp_status = 0
global_pos = all_app[0]
return_cmd = "hdc_std shell input -M -m {} {} -c 0".format(global_pos['return-x-y'][0], global_pos['return-x-y'][1])
recent_cmd = "hdc_std shell input -M -m {} {} -c 0".format(global_pos['recent-x-y'][0], global_pos['recent-x-y'][1])
home_cmd = "hdc_std shell input -M -m {} {} -c 0".format(global_pos['home-x-y'][0], global_pos['home-x-y'][1])
recent_del_cmd = "hdc_std shell input -M -m {} {} -c 0".format(global_pos['recent_del-x-y'][0], global_pos['recent_del-x-y'][1])
os.system("hdc_std kill")
os.system("hdc_std start")
EnterCmd("hdc_std list targets", 1)
EnterCmd("hdc_std list targets", 1)
EnterCmd("hdc_std list targets", 1)
EnterCmd("hdc_std shell rm -rf /data/screen_test/train_set")
EnterCmd("hdc_std shell mkdir -p /data/screen_test/train_set")
EnterCmd("hdc_std file send {} {}".format(os.path.join(os.path.dirname(args.config), "printscreen"), "/data/screen_test/"))
EnterCmd("hdc_std shell chmod 777 /data/screen_test/printscreen")
for single_app in all_app[1:]:
print(single_app['entry'])
print(single_app['all_actions'])
sys.stdout.flush()
call_app_cmd = "hdc_std shell " + single_app['entry']
send_file_cmd = "hdc_std file send {} {}"
capture_screen_cmd = "hdc_std shell /data/screen_test/printscreen -f /data/screen_test/{}"
recv_file_cmd = "hdc_std file recv /data/screen_test/{} {}"
cmp_cmd = "hdc_std shell \"cmp -l /data/screen_test/{} /data/screen_test/train_set/{} | wc -l\""
if single_app['entry'] != "":
EnterCmd(call_app_cmd, 3)
for single_action in single_app['all_actions']:
#shot_cmd is stable, different to other cmd,so handle it specialy
if type(single_action[1]) == str and single_action[1] == 'shot_cmd':
if len(single_action) == 3:
pic_name = single_action[2] + ".png"
raw_pic_name = single_action[2] + ".pngraw"
else:
pic_name = single_app['app_name'] + ".png"
raw_pic_name = single_app['app_name'] + ".pngraw"
EnterCmd(capture_screen_cmd.format(pic_name), 1)
EnterCmd(recv_file_cmd.format(pic_name, args.save_path), 1)
EnterCmd(recv_file_cmd.format(raw_pic_name, args.save_path), 1)
next_cmd = ""
#cmp_cmd-level is stable, different to other cmd,so handle it specialy
elif type(single_action[1]) == str and single_action[1] == 'cmp_cmd-level':
next_cmd = ""
print(send_file_cmd.format(os.path.join(args.anwser_path, raw_pic_name), "/data/screen_test/train_set"))
sys.stdout.flush()
EnterCmd(send_file_cmd.format(os.path.join(args.anwser_path, raw_pic_name), "/data/screen_test/train_set"))
new_cmp_cmd = cmp_cmd.format(raw_pic_name, raw_pic_name)
if len(single_action) == 3:
tolerance = single_action[2]
else:
tolerance = global_pos['cmp_cmd-level'][1]
p = EnterCmd(new_cmp_cmd, single_action[0])
num = re.findall(r'[-+]?\d+', p[0])
if type(num) == list and len(num) > 0 and int(num[0]) < tolerance:
print("{} screenshot check is ok!\n\n".format(raw_pic_name))
else:
print("ERROR:{} screenshot check is abnarmal!\n\n".format(raw_pic_name))
cmp_status = cmp_status + 1
sys.stdout.flush()
#other cmd handle
elif type(single_action[1]) == str:
if single_action[1] not in single_app.keys():
target_ = global_pos[single_action[1]]
else:
target_ = single_app[single_action[1]]
#this cmd is real cmd,and have a except answer
if type(target_[0]) == str:
next_cmd = ""
p = EnterCmd(target_[0], single_action[0])
result = "".join(p)
if len(target_) > 1:
findsome = result.find(target_[1], 0, len(result))
if findsome != -1:
print("\"{}\" execut result success!\n\n".format(target_[0]))
else:
print("ERROR:\"{}\" execut result failed!\n\n".format(target_[0]))
cmp_status = cmp_status + 1
sys.stdout.flush()
#this cmd only is a name of x,y postion, to get x,y an click it
else:
next_cmd = "hdc_std shell input -M -m {} {} -c 0".format(target_[0], target_[1])
#input x,y postion, to click it
else:
next_cmd = "hdc_std shell input -M -m {} {} -c 0".format(single_action[1], single_action[2])
EnterCmd(next_cmd, single_action[0])
if cmp_status != 0:
print("ERROR:screenshot check is abnarmal {}".format(cmp_status))
print("End of check, test failed!")
else:
print("screenshot check is ok {}".format(cmp_status))
print("End of check, test succeeded!")
sys.stdout.flush()
sys.exit(cmp_status)

Binary file not shown.

After

Width:  |  Height:  |  Size: 174 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 135 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 164 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 278 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 128 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 132 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 129 KiB

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save