@ -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,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,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,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,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,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,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,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,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,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,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,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,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,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,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);
|
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]]
|
||||
}
|
||||
|
||||
]
|
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)
|
After Width: | Height: | Size: 174 KiB |
After Width: | Height: | Size: 135 KiB |
After Width: | Height: | Size: 164 KiB |
After Width: | Height: | Size: 278 KiB |
After Width: | Height: | Size: 128 KiB |
After Width: | Height: | Size: 132 KiB |
After Width: | Height: | Size: 1.2 MiB |
After Width: | Height: | Size: 129 KiB |