添加硬件端固件示例代码

This commit is contained in:
kerwincui
2021-07-04 17:59:55 +08:00
parent e747bd935e
commit 224282d561
23 changed files with 5549 additions and 3 deletions

View File

@@ -1,3 +1,3 @@
cmake_minimum_required(VERSION 3.5) cmake_minimum_required(VERSION 3.5)
include($ENV{IDF_PATH}/tools/cmake/project.cmake) include($ENV{IDF_PATH}/tools/cmake/project.cmake)
project(empty-project) project(demo)

View File

@@ -1,2 +1,2 @@
PROJECT_NAME := empty_project PROJECT_NAME := demo
include $(IDF_PATH)/make/project.mk include $(IDF_PATH)/make/project.mk

View File

@@ -0,0 +1,3 @@
set(COMPONENT_SRCS "cJSON_Utils.c" "cJSON.c")
set(COMPONENT_ADD_INCLUDEDIRS ". include")
register_component()

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,285 @@
/*
Copyright (c) 2009-2017 Dave Gamble and cJSON contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef cJSON__h
#define cJSON__h
#ifdef __cplusplus
extern "C"
{
#endif
#if !defined(__WINDOWS__) && (defined(WIN32) || defined(WIN64) || defined(_MSC_VER) || defined(_WIN32))
#define __WINDOWS__
#endif
#ifdef __WINDOWS__
/* When compiling for windows, we specify a specific calling convention to avoid issues where we are being called from a project with a different default calling convention. For windows you have 3 define options:
CJSON_HIDE_SYMBOLS - Define this in the case where you don't want to ever dllexport symbols
CJSON_EXPORT_SYMBOLS - Define this on library build when you want to dllexport symbols (default)
CJSON_IMPORT_SYMBOLS - Define this if you want to dllimport symbol
For *nix builds that support visibility attribute, you can define similar behavior by
setting default visibility to hidden by adding
-fvisibility=hidden (for gcc)
or
-xldscope=hidden (for sun cc)
to CFLAGS
then using the CJSON_API_VISIBILITY flag to "export" the same symbols the way CJSON_EXPORT_SYMBOLS does
*/
#define CJSON_CDECL __cdecl
#define CJSON_STDCALL __stdcall
/* export symbols by default, this is necessary for copy pasting the C and header file */
#if !defined(CJSON_HIDE_SYMBOLS) && !defined(CJSON_IMPORT_SYMBOLS) && !defined(CJSON_EXPORT_SYMBOLS)
#define CJSON_EXPORT_SYMBOLS
#endif
#if defined(CJSON_HIDE_SYMBOLS)
#define CJSON_PUBLIC(type) type CJSON_STDCALL
#elif defined(CJSON_EXPORT_SYMBOLS)
#define CJSON_PUBLIC(type) __declspec(dllexport) type CJSON_STDCALL
#elif defined(CJSON_IMPORT_SYMBOLS)
#define CJSON_PUBLIC(type) __declspec(dllimport) type CJSON_STDCALL
#endif
#else /* !__WINDOWS__ */
#define CJSON_CDECL
#define CJSON_STDCALL
#if (defined(__GNUC__) || defined(__SUNPRO_CC) || defined (__SUNPRO_C)) && defined(CJSON_API_VISIBILITY)
#define CJSON_PUBLIC(type) __attribute__((visibility("default"))) type
#else
#define CJSON_PUBLIC(type) type
#endif
#endif
/* project version */
#define CJSON_VERSION_MAJOR 1
#define CJSON_VERSION_MINOR 7
#define CJSON_VERSION_PATCH 14
#include <stddef.h>
/* cJSON Types: */
#define cJSON_Invalid (0)
#define cJSON_False (1 << 0)
#define cJSON_True (1 << 1)
#define cJSON_NULL (1 << 2)
#define cJSON_Number (1 << 3)
#define cJSON_String (1 << 4)
#define cJSON_Array (1 << 5)
#define cJSON_Object (1 << 6)
#define cJSON_Raw (1 << 7) /* raw json */
#define cJSON_IsReference 256
#define cJSON_StringIsConst 512
/* The cJSON structure: */
typedef struct cJSON
{
/* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */
struct cJSON *next;
struct cJSON *prev;
/* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */
struct cJSON *child;
/* The type of the item, as above. */
int type;
/* The item's string, if type==cJSON_String and type == cJSON_Raw */
char *valuestring;
/* writing to valueint is DEPRECATED, use cJSON_SetNumberValue instead */
int valueint;
/* The item's number, if type==cJSON_Number */
double valuedouble;
/* The item's name string, if this item is the child of, or is in the list of subitems of an object. */
char *string;
} cJSON;
typedef struct cJSON_Hooks
{
/* malloc/free are CDECL on Windows regardless of the default calling convention of the compiler, so ensure the hooks allow passing those functions directly. */
void *(CJSON_CDECL *malloc_fn)(size_t sz);
void (CJSON_CDECL *free_fn)(void *ptr);
} cJSON_Hooks;
typedef int cJSON_bool;
/* Limits how deeply nested arrays/objects can be before cJSON rejects to parse them.
* This is to prevent stack overflows. */
#ifndef CJSON_NESTING_LIMIT
#define CJSON_NESTING_LIMIT 1000
#endif
/* returns the version of cJSON as a string */
CJSON_PUBLIC(const char*) cJSON_Version(void);
/* Supply malloc, realloc and free functions to cJSON */
CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks);
/* Memory Management: the caller is always responsible to free the results from all variants of cJSON_Parse (with cJSON_Delete) and cJSON_Print (with stdlib free, cJSON_Hooks.free_fn, or cJSON_free as appropriate). The exception is cJSON_PrintPreallocated, where the caller has full responsibility of the buffer. */
/* Supply a block of JSON, and this returns a cJSON object you can interrogate. */
CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value);
CJSON_PUBLIC(cJSON *) cJSON_ParseWithLength(const char *value, size_t buffer_length);
/* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */
/* If you supply a ptr in return_parse_end and parsing fails, then return_parse_end will contain a pointer to the error so will match cJSON_GetErrorPtr(). */
CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated);
CJSON_PUBLIC(cJSON *) cJSON_ParseWithLengthOpts(const char *value, size_t buffer_length, const char **return_parse_end, cJSON_bool require_null_terminated);
/* Render a cJSON entity to text for transfer/storage. */
CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item);
/* Render a cJSON entity to text for transfer/storage without any formatting. */
CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item);
/* Render a cJSON entity to text using a buffered strategy. prebuffer is a guess at the final size. guessing well reduces reallocation. fmt=0 gives unformatted, =1 gives formatted */
CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt);
/* Render a cJSON entity to text using a buffer already allocated in memory with given length. Returns 1 on success and 0 on failure. */
/* NOTE: cJSON is not always 100% accurate in estimating how much memory it will use, so to be safe allocate 5 bytes more than you actually need */
CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format);
/* Delete a cJSON entity and all subentities. */
CJSON_PUBLIC(void) cJSON_Delete(cJSON *item);
/* Returns the number of items in an array (or object). */
CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array);
/* Retrieve item number "index" from array "array". Returns NULL if unsuccessful. */
CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index);
/* Get item "string" from object. Case insensitive. */
CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string);
CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string);
CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string);
/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */
CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void);
/* Check item type and return its value */
CJSON_PUBLIC(char *) cJSON_GetStringValue(const cJSON * const item);
CJSON_PUBLIC(double) cJSON_GetNumberValue(const cJSON * const item);
/* These functions check the type of an item */
CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item);
/* These calls create a cJSON item of the appropriate type. */
CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void);
CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void);
CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void);
CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean);
CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num);
CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string);
/* raw json */
CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw);
CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void);
CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void);
/* Create a string where valuestring references a string so
* it will not be freed by cJSON_Delete */
CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string);
/* Create an object/array that only references it's elements so
* they will not be freed by cJSON_Delete */
CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child);
CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child);
/* These utilities create an Array of count items.
* The parameter count cannot be greater than the number of elements in the number array, otherwise array access will be out of bounds.*/
CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count);
CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count);
CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count);
CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char *const *strings, int count);
/* Append item to the specified array/object. */
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item);
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item);
/* Use this when string is definitely const (i.e. a literal, or as good as), and will definitely survive the cJSON object.
* WARNING: When this function was used, make sure to always check that (item->type & cJSON_StringIsConst) is zero before
* writing to `item->string` */
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item);
/* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new cJSON, but don't want to corrupt your existing cJSON. */
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item);
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item);
/* Remove/Detach items from Arrays/Objects. */
CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item);
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which);
CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which);
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string);
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string);
CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string);
CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string);
/* Update array items. */
CJSON_PUBLIC(cJSON_bool) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem); /* Shifts pre-existing items to the right. */
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement);
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem);
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem);
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object,const char *string,cJSON *newitem);
/* Duplicate a cJSON item */
CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse);
/* Duplicate will create a new, identical cJSON item to the one you pass, in new memory that will
* need to be released. With recurse!=0, it will duplicate any children connected to the item.
* The item->next and ->prev pointers are always zero on return from Duplicate. */
/* Recursively compare two cJSON items for equality. If either a or b is NULL or invalid, they will be considered unequal.
* case_sensitive determines if object keys are treated case sensitive (1) or case insensitive (0) */
CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive);
/* Minify a strings, remove blank characters(such as ' ', '\t', '\r', '\n') from strings.
* The input pointer json cannot point to a read-only address area, such as a string constant,
* but should point to a readable and writable adress area. */
CJSON_PUBLIC(void) cJSON_Minify(char *json);
/* Helper functions for creating and adding items to an object at the same time.
* They return the added item or NULL on failure. */
CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name);
CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name);
CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name);
CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean);
CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number);
CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string);
CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw);
CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name);
CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name);
/* When assigning an integer value, it needs to be propagated to valuedouble too. */
#define cJSON_SetIntValue(object, number) ((object) ? (object)->valueint = (object)->valuedouble = (number) : (number))
/* helper for the cJSON_SetNumberValue macro */
CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number);
#define cJSON_SetNumberValue(object, number) ((object != NULL) ? cJSON_SetNumberHelper(object, (double)number) : (number))
/* Change the valuestring of a cJSON_String object, only takes effect when type of object is cJSON_String */
CJSON_PUBLIC(char*) cJSON_SetValuestring(cJSON *object, const char *valuestring);
/* Macro for iterating over an array or object */
#define cJSON_ArrayForEach(element, array) for(element = (array != NULL) ? (array)->child : NULL; element != NULL; element = element->next)
/* malloc/free objects using the malloc/free functions that have been set with cJSON_InitHooks */
CJSON_PUBLIC(void *) cJSON_malloc(size_t size);
CJSON_PUBLIC(void) cJSON_free(void *object);
#ifdef __cplusplus
}
#endif
#endif

View File

@@ -0,0 +1,85 @@
/*
Copyright (c) 2009-2017 Dave Gamble and cJSON contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef cJSON_Utils__h
#define cJSON_Utils__h
#ifdef __cplusplus
extern "C"
{
#endif
#include "cJSON.h"
/* Implement RFC6901 (https://tools.ietf.org/html/rfc6901) JSON Pointer spec. */
CJSON_PUBLIC(cJSON *) cJSONUtils_GetPointer(cJSON * const object, const char *pointer);
CJSON_PUBLIC(cJSON *) cJSONUtils_GetPointerCaseSensitive(cJSON * const object, const char *pointer);
/* Implement RFC6902 (https://tools.ietf.org/html/rfc6902) JSON Patch spec. */
/* NOTE: This modifies objects in 'from' and 'to' by sorting the elements by their key */
CJSON_PUBLIC(cJSON *) cJSONUtils_GeneratePatches(cJSON * const from, cJSON * const to);
CJSON_PUBLIC(cJSON *) cJSONUtils_GeneratePatchesCaseSensitive(cJSON * const from, cJSON * const to);
/* Utility for generating patch array entries. */
CJSON_PUBLIC(void) cJSONUtils_AddPatchToArray(cJSON * const array, const char * const operation, const char * const path, const cJSON * const value);
/* Returns 0 for success. */
CJSON_PUBLIC(int) cJSONUtils_ApplyPatches(cJSON * const object, const cJSON * const patches);
CJSON_PUBLIC(int) cJSONUtils_ApplyPatchesCaseSensitive(cJSON * const object, const cJSON * const patches);
/*
// Note that ApplyPatches is NOT atomic on failure. To implement an atomic ApplyPatches, use:
//int cJSONUtils_AtomicApplyPatches(cJSON **object, cJSON *patches)
//{
// cJSON *modme = cJSON_Duplicate(*object, 1);
// int error = cJSONUtils_ApplyPatches(modme, patches);
// if (!error)
// {
// cJSON_Delete(*object);
// *object = modme;
// }
// else
// {
// cJSON_Delete(modme);
// }
//
// return error;
//}
// Code not added to library since this strategy is a LOT slower.
*/
/* Implement RFC7386 (https://tools.ietf.org/html/rfc7396) JSON Merge Patch spec. */
/* target will be modified by patch. return value is new ptr for target. */
CJSON_PUBLIC(cJSON *) cJSONUtils_MergePatch(cJSON *target, const cJSON * const patch);
CJSON_PUBLIC(cJSON *) cJSONUtils_MergePatchCaseSensitive(cJSON *target, const cJSON * const patch);
/* generates a patch to move from -> to */
/* NOTE: This modifies objects in 'from' and 'to' by sorting the elements by their key */
CJSON_PUBLIC(cJSON *) cJSONUtils_GenerateMergePatch(cJSON * const from, cJSON * const to);
CJSON_PUBLIC(cJSON *) cJSONUtils_GenerateMergePatchCaseSensitive(cJSON * const from, cJSON * const to);
/* Given a root object and a target object, construct a pointer from one to the other. */
CJSON_PUBLIC(char *) cJSONUtils_FindPointerFromObjectTo(const cJSON * const object, const cJSON * const target);
/* Sorts the members of the object into alphabetical order. */
CJSON_PUBLIC(void) cJSONUtils_SortObject(cJSON * const object);
CJSON_PUBLIC(void) cJSONUtils_SortObjectCaseSensitive(cJSON * const object);
#ifdef __cplusplus
}
#endif
#endif

View File

@@ -1,4 +1,4 @@
set(COMPONENT_SRCS "example1.c") set(COMPONENT_SRCS "example.c")
set(COMPONENT_ADD_INCLUDEDIRS ". include") set(COMPONENT_ADD_INCLUDEDIRS ". include")
register_component() register_component()

View File

@@ -0,0 +1,7 @@
#include "example.h"
#include <stdio.h>
void example()
{
printf("example\n");
}

View File

@@ -0,0 +1,9 @@
#ifndef _IOT_EXAMPLE_H_
#define _IOT_EXAMPLE_H_
void example();
#endif

View File

@@ -0,0 +1,4 @@
set(COMPONENT_SRCS "main.c" "mqtt.c" "wifi.c")
set(COMPONENT_ADD_INCLUDEDIRS ". include")
register_component()

View File

@@ -0,0 +1,22 @@
/******************************************************************************
* author: kerwincui
* create: 2021-06-08
* email164770707@qq.com
* source:https://github.com/kerwincui/wumei-smart
******************************************************************************/
#ifndef _MQTT_H_
#define _MQTT_H_
#include <stdio.h>
#include <string.h>
#include "esp_log.h"
#include "mqtt_client.h"
#include "cJSON.h"
#include "cJSON_Utils.h"
char owner_id[64]; // 用户ID
char device_num[13]; // 设备编号mac地址
void mqtt_start(void);
#endif

View File

@@ -0,0 +1,21 @@
/******************************************************************************
* author: kerwincui
* create: 2021-06-08
* email164770707@qq.com
* source:https://github.com/kerwincui/wumei-smart
*****************************************************************************/
#ifndef _WIFI_H_
#define _WIFI_H_
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include "esp_wifi.h"
#include "esp_log.h"
#include <string.h>
char ssid[33]; // wifi的SSID
char pwd[65]; // wifi的密码
void wifi_start(void);
#endif

View File

@@ -0,0 +1,35 @@
#include <stdio.h>
#include "nvs_flash.h"
#include "esp_event.h"
#include "example.h"
#include "mqtt.h"
#include "wifi.h"
/******************************************************************************
* FunctionName : app_main
* Description : entry of user application, init user function here
* Author : kerwincui
* SourceCode : https://gitee.com/kerwincui/wumei-smart
*******************************************************************************/
void app_main()
{
printf("Docking wumei-smart system demo \n");
// 初始化NVS
esp_err_t ret = nvs_flash_init();
if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
ESP_ERROR_CHECK(nvs_flash_erase());
ret = nvs_flash_init();
}
ESP_ERROR_CHECK( ret );
// 创建默认时间循环
ESP_ERROR_CHECK(esp_event_loop_create_default());
//连接wifi
wifi_start();
// 启动mqtt
mqtt_start();
}

View File

@@ -0,0 +1,395 @@
/******************************************************************************
* author: kerwincui
* create: 2021-06-08
* email164770707@qq.com
* source:https://github.com/kerwincui/wumei-smart
******************************************************************************/
#include "mqtt.h"
// 配置连接mqtt的broken
#define BROKEN_URL "mqtt://wumei.live:1884"
#define BROKEN_ADMIN "admin"
#define BROKEN_PWD "admin123"
char owner_id[64]="1"; // 用户ID,后端查看默认为amdin,ID为1
char device_num[13]="7EAFA1049ADA"; // 设备编号,唯一标识
static const char *TAG = "MQTT";
static esp_mqtt_client_handle_t mqtt_client=NULL;
static char *update_status_topic;
static char *get_status_topic;
static char *update_setting_topic;
static char *get_setting_topic;
// 发布设备状态
static void publishStatus(void){
cJSON *status = cJSON_CreateObject();
cJSON_AddStringToObject(status,"deviceNum","7CDFA1049ADA");
cJSON_AddNumberToObject(status,"relayStatus",1);
cJSON_AddNumberToObject(status,"lightStatus",1);
cJSON_AddNumberToObject(status,"isOnline",1);
cJSON_AddNumberToObject(status,"rssi",-80);
cJSON_AddNumberToObject(status,"deviceTemperature",0.0);
cJSON_AddNumberToObject(status,"airTemperature",0.0);
cJSON_AddNumberToObject(status,"airHumidity",0.0);
cJSON_AddNumberToObject(status,"triggerSource",0);
cJSON_AddNumberToObject(status,"brightness",100);
cJSON_AddNumberToObject(status,"lightInterval",300);
cJSON_AddNumberToObject(status,"lightMode",0);
cJSON_AddNumberToObject(status,"fadeTime",300);
cJSON_AddNumberToObject(status,"red",255);
cJSON_AddNumberToObject(status,"green",255);
cJSON_AddNumberToObject(status,"blue",255);
char *status_msg = cJSON_Print(status);
//释放内存
cJSON_Delete(status);
ESP_LOGI(TAG,"public status msg: %s",status_msg);
int msg_id=esp_mqtt_client_publish(mqtt_client,"status",status_msg,0,1,0);
ESP_LOGI(TAG, "sent publish device status, msg_id=%d",msg_id);
}
//发布设备配置
static void publishSetting(void){
cJSON *setting = cJSON_CreateObject();
cJSON_AddStringToObject(setting,"deviceNum",device_num);
cJSON_AddNumberToObject(setting,"isAlarm",1);
cJSON_AddNumberToObject(setting,"isRadar",1);
cJSON_AddNumberToObject(setting,"isHost",0);
cJSON_AddNumberToObject(setting,"isRfControl",1);
cJSON_AddNumberToObject(setting,"rfOneFunc",1);
cJSON_AddNumberToObject(setting,"rfTwoFunc",2);
cJSON_AddNumberToObject(setting,"rfThreeFunc",3);
cJSON_AddNumberToObject(setting,"rfFourFunc",4);
cJSON_AddStringToObject(setting,"ownerId",owner_id);
cJSON_AddNumberToObject(setting,"isReset",0);
cJSON_AddNumberToObject(setting,"isAp",0);
cJSON_AddNumberToObject(setting,"isRfLearn",0);
cJSON_AddNumberToObject(setting,"isRfClear",0);
cJSON_AddNumberToObject(setting,"isSmartConfig",0);
cJSON_AddNumberToObject(setting,"radarInterval",15);
cJSON_AddNumberToObject(setting,"isWifiOffline",0);
cJSON_AddNumberToObject(setting,"isOpenCertifi",0);
char *setting_msg = cJSON_Print(setting);
//释放内存
cJSON_Delete(setting);
ESP_LOGI(TAG,"publish setting msg: %s",setting_msg);
int msg_id=esp_mqtt_client_publish(mqtt_client,"setting",setting_msg,0,1,0);
ESP_LOGI(TAG, "sent publish device setting, msg_id=%d",msg_id);
}
// 更新设备状态
static void updateStatus(esp_mqtt_event_handle_t event,char *topic){
//将字符串格式的json数据转化为JSON对象格式
cJSON *root = cJSON_Parse(event->data);
if(root == NULL) { printf("parse error\n"); }
cJSON *value_relay = cJSON_GetObjectItem(root, "relayStatus");
char *relay = cJSON_Print(value_relay);
uint8_t relay_status=atoi(relay);
//继电器
if(relay_status==1){
//TODO 打开继电器
}else{
//TODO 关闭继电器
}
free(relay);
cJSON *value_light = cJSON_GetObjectItem(root, "lightStatus");
char *light = cJSON_Print(value_light);
uint8_t light_status=atoi(light);
//彩灯
if(light_status==1){
//TODO 打开灯
}else{
//TODO 关闭灯
}
free(light);
cJSON *value_trigger = cJSON_GetObjectItem(root, "triggerSource");
char *trigger = cJSON_Print(value_trigger);
free(trigger);
cJSON *value_brightness = cJSON_GetObjectItem(root, "brightness");
char *bright = cJSON_Print(value_brightness);
free(bright);
cJSON *value_interval = cJSON_GetObjectItem(root, "lightInterval");
char *interval = cJSON_Print(value_interval);
free(interval);
cJSON *value_mode = cJSON_GetObjectItem(root, "lightMode");
char *mode = cJSON_Print(value_mode);
free(mode);
cJSON *value_fade = cJSON_GetObjectItem(root, "fadeTime");
char *fade = cJSON_Print(value_fade);
free(fade);
cJSON *value_red = cJSON_GetObjectItem(root, "red");
char *red_string = cJSON_Print(value_red);
free(red_string);
cJSON *value_green = cJSON_GetObjectItem(root, "green");
char *green_string = cJSON_Print(value_green);
free(green_string);
cJSON *value_blue = cJSON_GetObjectItem(root, "blue");
char *blue_string = cJSON_Print(value_blue);
free(blue_string);
cJSON_Delete(root);
}
//更新设备配置
static void updateSetting(esp_mqtt_event_handle_t event,char *topic){
//将字符串格式的json数据转化为JSON对象格式
cJSON *root = cJSON_Parse(event->data);
if(root == NULL) { printf("parse error\n"); }
cJSON *value_reset = cJSON_GetObjectItem(root, "isReset");
char *reset = cJSON_Print(value_reset);
if(strcmp(reset, "1") == 0){
// 设备重启
fflush(stdout);
esp_restart();
}
free(reset);
cJSON *value_rf_learn = cJSON_GetObjectItem(root, "isRfLearn");
char *rf_learning = cJSON_Print(value_rf_learn);
if(strcmp(rf_learning, "1") == 0){
//TODO 遥控配对
}
free(rf_learning);
cJSON *value_rf_clear = cJSON_GetObjectItem(root, "isRfClear");
char *rf_clear = cJSON_Print(value_rf_clear);
if(strcmp(rf_clear, "1") == 0){
//TODO 遥控清码
}
free(rf_clear);
cJSON *value_ap = cJSON_GetObjectItem(root, "isAp");
char *ap = cJSON_Print(value_ap);
if(strcmp(ap, "1") == 0){
//TODO 打开AP
}
free(ap);
cJSON *value_alarm = cJSON_GetObjectItem(root, "isAlarm");
char *alarm = cJSON_Print(value_alarm);
free(alarm);
cJSON *value_radar = cJSON_GetObjectItem(root, "isRadar");
char *radar = cJSON_Print(value_radar);
free(radar);
cJSON *value_host = cJSON_GetObjectItem(root, "isHost");
char *host = cJSON_Print(value_host);
free(host);
cJSON *value_rf = cJSON_GetObjectItem(root, "isRfControl");
char *rf = cJSON_Print(value_rf);
free(rf);
cJSON *value_rf_one = cJSON_GetObjectItem(root, "rfOneFunc");
char *rf_one = cJSON_Print(value_rf_one);
free(rf_one);
cJSON *value_rf_two = cJSON_GetObjectItem(root, "rfTwoFunc");
char *rf_two = cJSON_Print(value_rf_two);
free(rf_two);
cJSON *value_rf_three = cJSON_GetObjectItem(root, "rfThreeFunc");
char *rf_three = cJSON_Print(value_rf_three);
free(rf_three);
cJSON *value_rf_four = cJSON_GetObjectItem(root, "rfFourFunc");
char *rf_four = cJSON_Print(value_rf_four);
free(rf_four);
cJSON_Delete(root);
}
static void mqtt_subscribe_event(esp_mqtt_event_handle_t event)
{
char topic[32];
ESP_LOGI(TAG,"event topic:%.*s\r", event->topic_len, event->topic);
ESP_LOGI(TAG,"event data:%.*s\r\n",event->data_len, event->data);
sprintf(topic,"%.*s", event->topic_len, event->topic);
if (strcmp(topic, update_status_topic) == 0)
{
//更新设备状态
updateStatus(event,topic);
// 发布设备状态
publishStatus();
} else if (strcmp(topic, get_status_topic) == 0)
{
publishStatus();
}else if(strcmp(topic,update_setting_topic) == 0){
// 更新设备配置
updateSetting(event,topic);
// 发布设备配置
publishSetting();
}
else if(strcmp(topic, get_setting_topic) == 0)
{
publishSetting();
}
}
static esp_err_t mqtt_event_handler_cb(esp_mqtt_event_handle_t event)
{
int msg_id;
switch (event->event_id) {
case MQTT_EVENT_CONNECTED:
ESP_LOGI(TAG, "MQTT_EVENT_CONNECTED");
//-----------------------------------订阅消息----------------------------------------
// 订阅更新设备状态
msg_id = esp_mqtt_client_subscribe(mqtt_client, update_status_topic, 1);
ESP_LOGI(TAG, "sent subscribe set status successful, msg_id=%d,topic=%s", msg_id,update_status_topic);
// 订阅获取设备状态
msg_id = esp_mqtt_client_subscribe(mqtt_client, get_status_topic, 1);
ESP_LOGI(TAG, "sent subscribe get status successful, msg_id=%d,topic=%s", msg_id,get_status_topic);
// 订阅更新设备配置
msg_id = esp_mqtt_client_subscribe(mqtt_client, update_setting_topic, 1);
ESP_LOGI(TAG, "sent subscribe set setting successful, msg_id=%d,topic=%s", msg_id,update_setting_topic);
// 订阅获取设备配置
msg_id = esp_mqtt_client_subscribe(mqtt_client, get_setting_topic, 1);
ESP_LOGI(TAG, "sent subscribe get setting successful, msg_id=%d,topic=%s", msg_id,get_setting_topic);
//-----------------------------------发布消息--------------------------------------
//发布设备信息
cJSON *device_info = cJSON_CreateObject();
cJSON_AddStringToObject(device_info,"deviceNum",device_num);
cJSON_AddNumberToObject(device_info,"categoryId",1);
cJSON_AddStringToObject(device_info,"firmwareVersion","1.0");
cJSON_AddStringToObject(device_info,"ownerId",owner_id);
char *device_msg = cJSON_Print(device_info);
//释放内存
cJSON_Delete(device_info);
ESP_LOGI(TAG,"device msg: %s",device_msg);
msg_id=esp_mqtt_client_publish(mqtt_client,"device_info",device_msg,0,1,0);
ESP_LOGI(TAG, "sent publish device info, msg_id=%d",msg_id);
break;
case MQTT_EVENT_DISCONNECTED:
ESP_LOGI(TAG, "MQTT_EVENT_DISCONNECTED");
break;
case MQTT_EVENT_SUBSCRIBED:
ESP_LOGI(TAG, "MQTT_EVENT_SUBSCRIBED, msg_id=%d", event->msg_id);
break;
case MQTT_EVENT_UNSUBSCRIBED:
ESP_LOGI(TAG, "MQTT_EVENT_UNSUBSCRIBED, msg_id=%d", event->msg_id);
break;
case MQTT_EVENT_PUBLISHED:
ESP_LOGI(TAG, "MQTT_EVENT_PUBLISHED, msg_id=%d", event->msg_id);
break;
case MQTT_EVENT_DATA:
ESP_LOGI(TAG, "MQTT_EVENT_DATA");
//订阅事件处理
mqtt_subscribe_event(event);
break;
case MQTT_EVENT_ERROR:
ESP_LOGI(TAG, "MQTT_EVENT_ERROR");
break;
default:
ESP_LOGI(TAG, "Other event id:%d", event->event_id);
break;
}
return ESP_OK;
}
static void mqtt_event_handler(void *handler_args, esp_event_base_t base, int32_t event_id, void *event_data) {
ESP_LOGD(TAG, "Event dispatched from event loop base=%s, event_id=%d", base, event_id);
mqtt_event_handler_cb(event_data);
}
// 配置订阅主题
static void config_topic(){
static char *update_status_path="status/set/";
static char *get_status_path="status/get/";
static char *update_setting_path="setting/set/";
static char *get_setting_path="setting/get/";
// 更新状态
update_status_topic=(char *)malloc(strlen(update_status_path)+strlen(device_num)+1);
if(update_status_topic==NULL){
ESP_LOGD(TAG, "failed to apply for memory");
}
strcpy(update_status_topic,update_status_path);
strcat(update_status_topic,device_num);
ESP_LOGI(TAG,"update_status_topic:%s",update_status_topic);
// 获取状态
get_status_topic=(char *)malloc(strlen(get_status_path)+strlen(device_num)+1);
if(get_status_topic==NULL){
ESP_LOGD(TAG, "failed to apply for memory");
}
strcpy(get_status_topic,get_status_path);
strcat(get_status_topic,device_num);
ESP_LOGI(TAG,"get_status_topic:%s",get_status_topic);
// 更新配置
update_setting_topic=(char *)malloc(strlen(update_setting_path)+strlen(device_num)+1);
if(update_setting_topic==NULL){
ESP_LOGD(TAG, "failed to apply for memory");
}
strcpy(update_setting_topic,update_setting_path);
strcat(update_setting_topic,device_num);
ESP_LOGI(TAG,"update_setting_topic:%s",update_setting_topic);
// 获取配置
get_setting_topic=(char *)malloc(strlen(get_setting_path)+strlen(device_num)+1);
if(get_setting_topic==NULL){
ESP_LOGD(TAG, "failed to apply for memory");
}
strcpy(get_setting_topic,get_setting_path);
strcat(get_setting_topic,device_num);
ESP_LOGI(TAG,"get_setting_topic:%s",get_setting_topic);
}
//启动mqtt
void mqtt_start(void)
{
// esp_log_level_set("*", ESP_LOG_INFO);
esp_log_level_set("MQTT_CLIENT", ESP_LOG_VERBOSE);
esp_log_level_set("MQTT", ESP_LOG_VERBOSE);
esp_log_level_set("TRANSPORT_TCP", ESP_LOG_VERBOSE);
esp_log_level_set("TRANSPORT_SSL", ESP_LOG_VERBOSE);
esp_log_level_set("TRANSPORT", ESP_LOG_VERBOSE);
esp_log_level_set("OUTBOX", ESP_LOG_VERBOSE);
// 配置订阅的主题
config_topic();
// 遗嘱消息
cJSON *root = cJSON_CreateObject();
cJSON_AddStringToObject(root,"deviceNum",device_num);
cJSON_AddNumberToObject(root,"isOnline",0);
char *will_msg = cJSON_Print(root);
//释放内存
cJSON_Delete(root);
ESP_LOGI(TAG,"last will: %s", will_msg);
esp_mqtt_client_config_t mqtt_cfg = {
.uri = BROKEN_URL,
.username = BROKEN_ADMIN,
.password = BROKEN_PWD,
//设置遗嘱
.lwt_topic="offline",
.lwt_msg=will_msg,
.lwt_msg_len=strlen(will_msg),
.lwt_qos=1,
.lwt_retain=0,
//断开前等待的时间,3秒
.keepalive=3,
};
mqtt_client = esp_mqtt_client_init(&mqtt_cfg);
esp_mqtt_client_register_event(mqtt_client, ESP_EVENT_ANY_ID, mqtt_event_handler, mqtt_client);
esp_mqtt_client_start(mqtt_client);
}

View File

@@ -0,0 +1,96 @@
/******************************************************************************
* author: kerwincui
* create: 2021-06-08
* email164770707@qq.com
* source:https://github.com/kerwincui/wumei-smart
******************************************************************************/
#include "wifi.h"
#define LISTEN_INTERVAL 3 //站监听AP信标的间隔。监听间隔的单位是一个信标间隔。例如如果信标间隔为100 ms侦听间隔为3则站侦听信标的间隔为300 ms。
#define WIFI_CONNECTED_BIT BIT0
#define WIFI_FAIL_BIT BIT1
char ssid[33]="tp-six"; // wifi的SSID
char pwd[65]="clh15108665817"; // wifi的密码
static const char *TAG = "WIFI";
static EventGroupHandle_t s_wifi_event_group;
static esp_event_handler_instance_t instance_any_id;
static esp_event_handler_instance_t instance_got_ip;
// 回调函数
static void station_event_handler(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data)
{
printf("station event handler begin \n\n\n");
if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) {
esp_wifi_connect();
} else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) {
esp_wifi_connect();
} else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
ip_event_got_ip_t* event = (ip_event_got_ip_t*) event_data;
ESP_LOGI(TAG, "got ip: " IPSTR, IP2STR(&event->ip_info.ip));
xEventGroupSetBits(s_wifi_event_group, WIFI_CONNECTED_BIT);
}
}
//站点模式初始化
static void wifi_station_init(void)
{
esp_netif_create_default_wifi_sta();
ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &station_event_handler, NULL, &instance_any_id));
ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &station_event_handler, NULL, &instance_got_ip));
wifi_config_t wifi_config = {
.sta = {
.listen_interval = LISTEN_INTERVAL,
/* 设置密码意味着工作站将连接到包括WEP/WPA在内的所有安全模式。但是这些模式已被弃用不建议使用。
* 如果您的接入点不支持WPA2可以通过在下面的行注释来启用这些模式 */
//.threshold.authmode = WIFI_AUTH_WPA2_PSK,
//PMF功能
.pmf_cfg = {
.capable = true,
.required = false
},
},
};
// wifi配置赋值
strcpy((char *)wifi_config.sta.ssid,(char *)ssid);
strcpy((char *)wifi_config.sta.password,(char *)pwd);
ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config));
}
//启动wifi站点
void wifi_start(void)
{
s_wifi_event_group = xEventGroupCreate();
ESP_ERROR_CHECK(esp_netif_init());
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
ESP_LOGI(TAG, "ESP_WIFI_MODE_STA");
wifi_station_init();
ESP_ERROR_CHECK(esp_wifi_start());
//STATION模式等待建立连接或者超过连接最大次数后连接失败比特位是通过事件处理程序设置
EventBits_t bits = xEventGroupWaitBits(s_wifi_event_group,
WIFI_CONNECTED_BIT | WIFI_FAIL_BIT,
pdFALSE,
pdFALSE,
portMAX_DELAY);
if (bits & WIFI_CONNECTED_BIT) {
ESP_LOGI(TAG, "connected to ap SSID:%s password:%s",ssid, pwd);
} else if (bits & WIFI_FAIL_BIT) {
ESP_LOGI(TAG, "Failed to connect to SSID:%s, password:%s", ssid, pwd);
} else {
ESP_LOGE(TAG, "UNEXPECTED EVENT");
}
}