diff --git a/arc_design_contest/2018/HUST_SmartLamp/README.md b/arc_design_contest/2018/HUST_SmartLamp/README.md
new file mode 100644
index 00000000..e9bee5e8
--- /dev/null
+++ b/arc_design_contest/2018/HUST_SmartLamp/README.md
@@ -0,0 +1,62 @@
+----
+**Smart-Lamp**
+====
+----
+# **Content**
+* [Introduction](#introduction)
+ * [Function](#function)
+ * [System Architecture](#architecture)
+* [System Config](#config)
+ * [Hardware](#hardware)
+ * [Software](#software)
+ * [Hardware Connection](#connection)
+* [User Manual](#usermanual)
+* [Video](#video)
+----
+# **Introduction**
+This project designed a smart lamp which was based on ARC EM Starter Kit. The lamp can detect whether the user is using to turn on or off, automatically connect the server to report the real-time status, and manually and automatically adjust the brightness, remotely be controled by the APP console, record the user's usage time. The follow-up will add the functions of detecting the unhealthy work schedule of the user and correcting the user's incorrect sitting habits, which can help the user to effectively get rid of the health hazards brought by the high pressure of modern life, develop a good working habit, and keep your body and eyes healthy.
+## **Function**
+* **automatic switch**
+When the human body is located at a distance of about 15cm from the infrared transceiver port and keeps the occlusion time for more than 3 seconds, the lamp can normally illuminate and enter the auto dimming mode by default. Similarly, the lamp will automatically turn off 3 seconds after the person leaves the lamp, avoiding the occasional behavioral instability of the user and causing the desk lamp to be frequently turned off.
+* **automatic sign in**
+After restarting the lamp and the network, the lamp can automatically re-launch within 5 seconds.
+* **automatic adjust brightness**
+The lamp can realize stepless natural dimming in 8 different light intensity ranges, and there is no phenomenon that the user feels uncomfortable due to the light intensity jump and stroboscopic. In the automatic dimming mode, the lamp can adapt to the change of light intensity in the environment, and adjust the brightness in time, with better sensitivity.
+* **remote control**
+The APP can support the frequent operation of the user, and there is no problem of wrong operation or invalid operation under the high-intensity round-trip conversion test.
+## **System Architecture**
+
+
+----
+# **System Config**
+## **Hardware**
+* EMSK V2.2 ARCEM7D Starter Kit
+* ESP8266 WIFI
+* Infrared Ray Sensor
+* Touchpad
+* CM3232 Ambient Light Sensor
+


+
+## **Software**
+* ARC GNU Toolchain
+* embARC Open Software Platform (OSP) 201709
+* Serial Port Terminal eg. XCOM
+* APP for Android
+* Mini Program of Wechat
+## **Hardware Connection**
+
+* ESP8266 connected to UART1 through PMOD1 of ARC EMSK
+* CM3232 connected to I2C through PMOD3 of ARC EMSK
+* Touchpad connected to UART emulator through PMOD3 of ARC EMSK
+* Infrared Ray Sensor connected to GPIO through PMOD2 of ARC EMSK
+
+----
+# **User Manual**
+* The user configures the current network for the lamp through the APP and connects to the server.
+* In the automatic control mode, the lamp can enter the automatic dimming while the user is nearby, which will automatically adjust the brightness according to the ambient light intensity.
+* In manual control mode, the user can manually adjust the brightness of the lamp through the touchpad button and exit the automatic mode.
+* The user can remotely control via mobile client
+
+----
+# **[Video](https://v.youku.com/v_show/id_XMzcxMzE0NzA0NA==.html?spm=a2h3j.8428770.3416059.1) **
+----
diff --git a/arc_design_contest/2018/HUST_SmartLamp/doc/ICC312UP.pptx b/arc_design_contest/2018/HUST_SmartLamp/doc/ICC312UP.pptx
new file mode 100644
index 00000000..a6527766
Binary files /dev/null and b/arc_design_contest/2018/HUST_SmartLamp/doc/ICC312UP.pptx differ
diff --git "a/arc_design_contest/2018/HUST_SmartLamp/doc/Synopsys ARC\346\235\257\347\224\265\345\255\220\350\256\276\350\256\241\347\253\236\350\265\233\346\212\200\346\234\257\350\256\272\346\226\207-\345\215\216\344\270\255\347\247\221\346\212\200\345\244\247\345\255\246ICC312UP\351\230\237.docx" "b/arc_design_contest/2018/HUST_SmartLamp/doc/Synopsys ARC\346\235\257\347\224\265\345\255\220\350\256\276\350\256\241\347\253\236\350\265\233\346\212\200\346\234\257\350\256\272\346\226\207-\345\215\216\344\270\255\347\247\221\346\212\200\345\244\247\345\255\246ICC312UP\351\230\237.docx"
new file mode 100644
index 00000000..49182eed
Binary files /dev/null and "b/arc_design_contest/2018/HUST_SmartLamp/doc/Synopsys ARC\346\235\257\347\224\265\345\255\220\350\256\276\350\256\241\347\253\236\350\265\233\346\212\200\346\234\257\350\256\272\346\226\207-\345\215\216\344\270\255\347\247\221\346\212\200\345\244\247\345\255\246ICC312UP\351\230\237.docx" differ
diff --git a/arc_design_contest/2018/HUST_SmartLamp/pictures/all.jpg b/arc_design_contest/2018/HUST_SmartLamp/pictures/all.jpg
new file mode 100644
index 00000000..e2979747
Binary files /dev/null and b/arc_design_contest/2018/HUST_SmartLamp/pictures/all.jpg differ
diff --git a/arc_design_contest/2018/HUST_SmartLamp/pictures/cm3232.jpg b/arc_design_contest/2018/HUST_SmartLamp/pictures/cm3232.jpg
new file mode 100644
index 00000000..25c94993
Binary files /dev/null and b/arc_design_contest/2018/HUST_SmartLamp/pictures/cm3232.jpg differ
diff --git a/arc_design_contest/2018/HUST_SmartLamp/pictures/esp8266.jpg b/arc_design_contest/2018/HUST_SmartLamp/pictures/esp8266.jpg
new file mode 100644
index 00000000..9f49265e
Binary files /dev/null and b/arc_design_contest/2018/HUST_SmartLamp/pictures/esp8266.jpg differ
diff --git a/arc_design_contest/2018/HUST_SmartLamp/pictures/ir.jpg b/arc_design_contest/2018/HUST_SmartLamp/pictures/ir.jpg
new file mode 100644
index 00000000..7adbc411
Binary files /dev/null and b/arc_design_contest/2018/HUST_SmartLamp/pictures/ir.jpg differ
diff --git a/arc_design_contest/2018/HUST_SmartLamp/pictures/system.png b/arc_design_contest/2018/HUST_SmartLamp/pictures/system.png
new file mode 100644
index 00000000..d88fc73f
Binary files /dev/null and b/arc_design_contest/2018/HUST_SmartLamp/pictures/system.png differ
diff --git a/arc_design_contest/2018/HUST_SmartLamp/pictures/touchpad.jpg b/arc_design_contest/2018/HUST_SmartLamp/pictures/touchpad.jpg
new file mode 100644
index 00000000..a9f87312
Binary files /dev/null and b/arc_design_contest/2018/HUST_SmartLamp/pictures/touchpad.jpg differ
diff --git a/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/.cproject b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/.cproject
new file mode 100644
index 00000000..c1886b9d
--- /dev/null
+++ b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/.cproject
@@ -0,0 +1,109 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/.project b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/.project
new file mode 100644
index 00000000..cba380da
--- /dev/null
+++ b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/.project
@@ -0,0 +1,54 @@
+
+
+ FreeRTOS
+
+
+
+
+
+ org.eclipse.cdt.managedbuilder.core.genmakebuilder
+ clean,full,incremental,
+
+
+
+
+ org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder
+ full,incremental,
+
+
+
+
+
+ org.eclipse.cdt.core.cnature
+ org.eclipse.cdt.core.ccnature
+ org.eclipse.cdt.managedbuilder.core.managedBuildNature
+ org.eclipse.cdt.managedbuilder.core.ScannerConfigNature
+
+
+
+ board
+ 2
+ C:/embarc_osp-master/board
+
+
+ device
+ 2
+ C:/embarc_osp-master/device
+
+
+ inc
+ 2
+ C:/embarc_osp-master/inc
+
+
+ options
+ 2
+ C:/embarc_osp-master/options
+
+
+ os
+ 2
+ C:/embarc_osp-master/os
+
+
+
diff --git a/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/FreeRTOSConfig.h b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/FreeRTOSConfig.h
new file mode 100644
index 00000000..d23d36d6
--- /dev/null
+++ b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/FreeRTOSConfig.h
@@ -0,0 +1,167 @@
+/*
+ FreeRTOS V8.0.0 - Copyright (C) 2014 Real Time Engineers Ltd.
+ All rights reserved
+
+ VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
+
+ ***************************************************************************
+ * *
+ * FreeRTOS provides completely free yet professionally developed, *
+ * robust, strictly quality controlled, supported, and cross *
+ * platform software that has become a de facto standard. *
+ * *
+ * Help yourself get started quickly and support the FreeRTOS *
+ * project by purchasing a FreeRTOS tutorial book, reference *
+ * manual, or both from: http://www.FreeRTOS.org/Documentation *
+ * *
+ * Thank you! *
+ * *
+ ***************************************************************************
+
+ This file is part of the FreeRTOS distribution.
+
+ FreeRTOS is free software; you can redistribute it and/or modify it under
+ the terms of the GNU General Public License (version 2) as published by the
+ Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.
+
+ >>! NOTE: The modification to the GPL is included to allow you to distribute
+ >>! a combined work that includes FreeRTOS without being obliged to provide
+ >>! the source code for proprietary components outside of the FreeRTOS
+ >>! kernel.
+
+ FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY
+ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+ FOR A PARTICULAR PURPOSE. Full license text is available from the following
+ link: http://www.freertos.org/a00114.html
+
+ 1 tab == 4 spaces!
+
+ ***************************************************************************
+ * *
+ * Having a problem? Start by reading the FAQ "My application does *
+ * not run, what could be wrong?" *
+ * *
+ * http://www.FreeRTOS.org/FAQHelp.html *
+ * *
+ ***************************************************************************
+
+ http://www.FreeRTOS.org - Documentation, books, training, latest versions,
+ license and Real Time Engineers Ltd. contact details.
+
+ http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
+ including FreeRTOS+Trace - an indispensable productivity tool, a DOS
+ compatible FAT file system, and our tiny thread aware UDP/IP stack.
+
+ http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to High
+ Integrity Systems to sell under the OpenRTOS brand. Low cost OpenRTOS
+ licenses offer ticketed support, indemnification and middleware.
+
+ http://www.SafeRTOS.com - High Integrity Systems also provide a safety
+ engineered and independently SIL3 certified version for use in safety and
+ mission critical applications that require provable dependability.
+
+ 1 tab == 4 spaces!
+*/
+
+#ifndef FREERTOS_CONFIG_H
+#define FREERTOS_CONFIG_H
+
+#include
+/*-----------------------------------------------------------
+ * Application specific definitions.
+ *
+ * These definitions should be adjusted for your particular hardware and
+ * application requirements.
+ *
+ * THESE PARAMETERS ARE DESCRIBED WITHIN THE 'CONFIGURATION' SECTION OF THE
+ * FreeRTOS API DOCUMENTATION AVAILABLE ON THE FreeRTOS.org WEB SITE.
+ *
+ * See http://www.freertos.org/a00110.html.
+ *----------------------------------------------------------*/
+#define configUSE_PORT_OPTIMISED_TASK_SELECTION 0 //1ⷽѡһҪе
+ //һӲǰָʹõ
+ //MCUûЩӲָĻ˺ӦΪ0
+
+#define configUSE_PREEMPTION 1
+#define configUSE_TIME_SLICING 1 //1ʹʱƬ(Ĭʽʹܵ)
+#define configUSE_IDLE_HOOK 0
+#define configUSE_TICK_HOOK 0
+#define configCPU_CLOCK_HZ ( ( unsigned long ) BOARD_CPU_CLOCK )
+#define configTICK_RATE_HZ ( ( TickType_t ) 1000 )
+#define configMAX_PRIORITIES ( 32 )
+#define configMINIMAL_STACK_SIZE ( ( unsigned short ) 130 )
+#define configSUPPORT_DYNAMIC_ALLOCATION 1 //ֶ֧̬ڴ
+#define configTOTAL_HEAP_SIZE ( ( size_t ) ( 30 * 1024 ) )
+#define configMAX_TASK_NAME_LEN ( 32 )
+//#define configUSE_TRACE_FACILITY 0
+#define configUSE_16_BIT_TICKS 0
+#define configIDLE_SHOULD_YIELD 1
+#define configUSE_MUTEXES 1
+
+/* Co-routine definitions. */
+#define configUSE_CO_ROUTINES 0
+#define configMAX_CO_ROUTINE_PRIORITIES ( 2 )
+
+
+/* Set the following definitions to 1 to include the API function, or zero
+to exclude the API function. */
+
+//#define INCLUDE_vTaskPrioritySet 1
+//#define INCLUDE_uxTaskPriorityGet 1
+//#define INCLUDE_vTaskDelete 1
+//#define INCLUDE_vTaskCleanUpResources 0
+//#define INCLUDE_vTaskSuspend 1
+//#define INCLUDE_vTaskDelayUntil 1
+//#define INCLUDE_vTaskDelay 1
+//#define INCLUDE_xTaskGetCurrentTaskHandle 1
+
+/***************************************************************************************************************/
+/* FreeRTOSʱйصѡ */
+/***************************************************************************************************************/
+#define configUSE_TIMERS 1 //Ϊ1ʱʱ
+#define configTIMER_TASK_PRIORITY 25//(configMAX_PRIORITIES-1) 18 //ʱȼ smartconfigȼ19ڴй¶
+#define configTIMER_QUEUE_LENGTH 32 //ʱг
+#define configTIMER_TASK_STACK_DEPTH (configMINIMAL_STACK_SIZE*3) //ʱջС
+
+/***************************************************************************************************************/
+/* FreeRTOSѡѡ */
+/***************************************************************************************************************/
+#define INCLUDE_xTaskGetSchedulerState 1
+#define INCLUDE_vTaskPrioritySet 1
+#define INCLUDE_uxTaskPriorityGet 1
+#define INCLUDE_vTaskDelete 1
+#define INCLUDE_vTaskCleanUpResources 1//0
+#define INCLUDE_vTaskSuspend 1
+#define INCLUDE_vTaskDelayUntil 1
+#define INCLUDE_vTaskDelay 1
+#define INCLUDE_eTaskGetState 1
+#define INCLUDE_xTimerPendFunctionCall 1
+
+/***************************************************************************************************************/
+/* FreeRTOSжйصѡ */
+/***************************************************************************************************************/
+#if 0
+#ifdef __NVIC_PRIO_BITS
+ #define configPRIO_BITS __NVIC_PRIO_BITS
+#else
+ #define configPRIO_BITS 4
+#endif
+#endif
+
+#define configLIBRARY_LOWEST_INTERRUPT_PRIORITY 15 //жȼ
+#define configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY 5 //ϵͳɹжȼ
+#define configKERNEL_INTERRUPT_PRIORITY ( configLIBRARY_LOWEST_INTERRUPT_PRIORITY << (8 - configPRIO_BITS) )
+#define configMAX_SYSCALL_INTERRUPT_PRIORITY ( configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY << (8 - configPRIO_BITS) )
+
+/***************************************************************************************************************/
+/* FreeRTOSжϷйصѡ */
+/***************************************************************************************************************/
+//#define xPortPendSVHandler PendSV_Handler
+//#define vPortSVCHandler SVC_Handler
+
+#define configUSE_TRACE_FACILITY 1 //Ϊ1ÿӻٵ
+#define configUSE_STATS_FORMATTING_FUNCTIONS 1 //configUSE_TRACE_FACILITYͬʱΪ1ʱ3
+ //prvWriteNameToBuffer(),vTaskList(),
+
+
+#endif /* FREERTOS_CONFIG_H */
diff --git a/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/Cjson/cJSON.c b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/Cjson/cJSON.c
new file mode 100644
index 00000000..698c7c50
--- /dev/null
+++ b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/Cjson/cJSON.c
@@ -0,0 +1,2661 @@
+/*
+ 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.
+*/
+
+/* cJSON */
+/* JSON parser in C. */
+
+#ifdef __GNUC__
+#pragma GCC visibility push(default)
+#endif
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include "task_config.h"
+
+
+#ifdef __GNUC__
+#pragma GCC visibility pop
+#endif
+
+#include "cJSON.h"
+
+/* define our own boolean type */
+#define true ((cJSON_bool)1)
+#define false ((cJSON_bool)0)
+
+typedef struct
+{
+ const unsigned char *json;
+ size_t position;
+} error;
+static error global_error = { NULL, 0 };
+
+CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void)
+{
+ return (const char*) (global_error.json + global_error.position);
+}
+
+/* This is a safeguard to prevent copy-pasters from using incompatible C and header files */
+#if (CJSON_VERSION_MAJOR != 1) || (CJSON_VERSION_MINOR != 5) || (CJSON_VERSION_PATCH != 4)
+#error cJSON.h and cJSON.c have different versions. Make sure that both have the same.
+#endif
+
+CJSON_PUBLIC(const char*) cJSON_Version(void)
+{
+ static char version[15];
+ sprintf(version, "%i.%i.%i", CJSON_VERSION_MAJOR, CJSON_VERSION_MINOR, CJSON_VERSION_PATCH);
+
+ return version;
+}
+
+/* Case insensitive string comparison, doesn't consider two NULL pointers equal though */
+static int case_insensitive_strcmp(const unsigned char *string1, const unsigned char *string2)
+{
+ if ((string1 == NULL) || (string2 == NULL))
+ {
+ return 1;
+ }
+
+ if (string1 == string2)
+ {
+ return 0;
+ }
+
+ for(; tolower(*string1) == tolower(*string2); (void)string1++, string2++)
+ {
+ if (*string1 == '\0')
+ {
+ return 0;
+ }
+ }
+
+ return tolower(*string1) - tolower(*string2);
+}
+
+typedef struct internal_hooks
+{
+ void *(*allocate)(size_t size);
+ void (*deallocate)(void *pointer);
+ void *(*reallocate)(void *pointer, size_t size);
+} internal_hooks;
+
+//Ӧϵͳڴ
+void* vPortrealloc_hh(void* ptr, size_t newsize)
+{
+ uint8_t *puc = ( uint8_t * ) ptr;
+ uint8_t *new_p;
+ if(puc!=NULL&&newsize>0)
+ {
+ new_p = pvPortMalloc(newsize);
+ if(new_p)
+ {
+ memcmp(new_p,puc, newsize);
+ }
+ vPortFree(puc);
+ }
+
+ return new_p;
+
+}
+//static internal_hooks global_hooks = { malloc, free, realloc };
+static internal_hooks global_hooks = { pvPortMalloc, vPortFree, vPortrealloc_hh };
+
+
+
+static unsigned char* cJSON_strdup(const unsigned char* string, const internal_hooks * const hooks)
+{
+ size_t length = 0;
+ unsigned char *copy = NULL;
+
+ if (string == NULL)
+ {
+ return NULL;
+ }
+
+ length = strlen((const char*)string) + sizeof("");
+ if (!(copy = (unsigned char*)hooks->allocate(length)))
+ {
+ return NULL;
+ }
+ memcpy(copy, string, length);
+
+ return copy;
+}
+
+CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks)
+{
+ if (hooks == NULL)
+ {
+ /* Reset hooks */
+ global_hooks.allocate = pvPortMalloc;
+ global_hooks.deallocate = vPortFree;
+ global_hooks.reallocate = vPortrealloc_hh;
+ return;
+ }
+
+ global_hooks.allocate = pvPortMalloc;
+ if (hooks->malloc_fn != NULL)
+ {
+ global_hooks.allocate = hooks->malloc_fn;
+ }
+
+ global_hooks.deallocate = vPortFree;
+ if (hooks->free_fn != NULL)
+ {
+ global_hooks.deallocate = hooks->free_fn;
+ }
+
+ /* use realloc only if both free and malloc are used */
+ global_hooks.reallocate = NULL;
+ if ((global_hooks.allocate == pvPortMalloc) && (global_hooks.deallocate == vPortFree))
+ {
+ global_hooks.reallocate = vPortrealloc_hh;
+ }
+}
+
+/* Internal constructor. */
+static cJSON *cJSON_New_Item(const internal_hooks * const hooks)
+{
+ cJSON* node = (cJSON*)hooks->allocate(sizeof(cJSON));
+ if (node)
+ {
+ memset(node, '\0', sizeof(cJSON));
+ }
+
+ return node;
+}
+
+/* Delete a cJSON structure. */
+CJSON_PUBLIC(void) cJSON_Delete(cJSON *item)
+{
+ cJSON *next = NULL;
+ while (item != NULL)
+ {
+ next = item->next;
+ if (!(item->type & cJSON_IsReference) && (item->child != NULL))
+ {
+ cJSON_Delete(item->child);
+ }
+ if (!(item->type & cJSON_IsReference) && (item->valuestring != NULL))
+ {
+ global_hooks.deallocate(item->valuestring);
+ }
+ if (!(item->type & cJSON_StringIsConst) && (item->string != NULL))
+ {
+ global_hooks.deallocate(item->string);
+ }
+ global_hooks.deallocate(item);
+ item = next;
+ }
+}
+
+/* get the decimal point character of the current locale */
+static unsigned char get_decimal_point(void)
+{
+ struct lconv *lconv = localeconv();
+ return (unsigned char) lconv->decimal_point[0];
+}
+
+typedef struct
+{
+ const unsigned char *content;
+ size_t length;
+ size_t offset;
+ size_t depth; /* How deeply nested (in arrays/objects) is the input at the current offset. */
+ internal_hooks hooks;
+} parse_buffer;
+
+/* check if the given size is left to read in a given parse buffer (starting with 1) */
+#define can_read(buffer, size) ((buffer != NULL) && (((buffer)->offset + size) <= (buffer)->length))
+#define cannot_read(buffer, size) (!can_read(buffer, size))
+/* check if the buffer can be accessed at the given index (starting with 0) */
+#define can_access_at_index(buffer, index) ((buffer != NULL) && (((buffer)->offset + index) < (buffer)->length))
+#define cannot_access_at_index(buffer, index) (!can_access_at_index(buffer, index))
+/* get a pointer to the buffer at the position */
+#define buffer_at_offset(buffer) ((buffer)->content + (buffer)->offset)
+
+/* Parse the input text to generate a number, and populate the result into item. */
+static cJSON_bool parse_number(cJSON * const item, parse_buffer * const input_buffer)
+{
+ double number = 0;
+ unsigned char *after_end = NULL;
+ unsigned char number_c_string[64];
+ unsigned char decimal_point = get_decimal_point();
+ size_t i = 0;
+
+ if ((input_buffer == NULL) || (input_buffer->content == NULL))
+ {
+ return false;
+ }
+
+ /* copy the number into a temporary buffer and replace '.' with the decimal point
+ * of the current locale (for strtod)
+ * This also takes care of '\0' not necessarily being available for marking the end of the input */
+ for (i = 0; (i < (sizeof(number_c_string) - 1)) && can_access_at_index(input_buffer, i); i++)
+ {
+ switch (buffer_at_offset(input_buffer)[i])
+ {
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9':
+ case '+':
+ case '-':
+ case 'e':
+ case 'E':
+ number_c_string[i] = buffer_at_offset(input_buffer)[i];
+ break;
+
+ case '.':
+ number_c_string[i] = decimal_point;
+ break;
+
+ default:
+ goto loop_end;
+ }
+ }
+loop_end:
+ number_c_string[i] = '\0';
+
+ number = strtod((const char*)number_c_string, (char**)&after_end);
+ if (number_c_string == after_end)
+ {
+ return false; /* parse_error */
+ }
+
+ item->valuedouble = number;
+
+ /* use saturation in case of overflow */
+ if (number >= INT_MAX)
+ {
+ item->valueint = INT_MAX;
+ }
+ else if (number <= INT_MIN)
+ {
+ item->valueint = INT_MIN;
+ }
+ else
+ {
+ item->valueint = (int)number;
+ }
+
+ item->type = cJSON_Number;
+
+ input_buffer->offset += (size_t)(after_end - number_c_string);
+ return true;
+}
+
+/* don't ask me, but the original cJSON_SetNumberValue returns an integer or double */
+CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number)
+{
+ if (number >= INT_MAX)
+ {
+ object->valueint = INT_MAX;
+ }
+ else if (number <= INT_MIN)
+ {
+ object->valueint = INT_MIN;
+ }
+ else
+ {
+ object->valueint = (int)number;
+ }
+
+ return object->valuedouble = number;
+}
+
+typedef struct
+{
+ unsigned char *buffer;
+ size_t length;
+ size_t offset;
+ size_t depth; /* current nesting depth (for formatted printing) */
+ cJSON_bool noalloc;
+ cJSON_bool format; /* is this print a formatted print */
+ internal_hooks hooks;
+} printbuffer;
+
+/* realloc printbuffer if necessary to have at least "needed" bytes more */
+static unsigned char* ensure(printbuffer * const p, size_t needed)
+{
+ unsigned char *newbuffer = NULL;
+ size_t newsize = 0;
+
+ if ((p == NULL) || (p->buffer == NULL))
+ {
+ return NULL;
+ }
+
+ if ((p->length > 0) && (p->offset >= p->length))
+ {
+ /* make sure that offset is valid */
+ return NULL;
+ }
+
+ if (needed > INT_MAX)
+ {
+ /* sizes bigger than INT_MAX are currently not supported */
+ return NULL;
+ }
+
+ needed += p->offset + 1;
+ if (needed <= p->length)
+ {
+ return p->buffer + p->offset;
+ }
+
+ if (p->noalloc)
+ {
+ return NULL;
+ }
+
+ /* calculate new buffer size */
+ if (needed > (INT_MAX / 2))
+ {
+ /* overflow of int, use INT_MAX if possible */
+ if (needed <= INT_MAX)
+ {
+ newsize = INT_MAX;
+ }
+ else
+ {
+ return NULL;
+ }
+ }
+ else
+ {
+ newsize = needed * 2;
+ }
+
+ if (p->hooks.reallocate != NULL)
+ {
+ /* reallocate with realloc if available */
+ newbuffer = (unsigned char*)p->hooks.reallocate(p->buffer, newsize);
+ }
+ else
+ {
+ /* otherwise reallocate manually */
+ newbuffer = (unsigned char*)p->hooks.allocate(newsize);
+ if (!newbuffer)
+ {
+ p->hooks.deallocate(p->buffer);
+ p->length = 0;
+ p->buffer = NULL;
+
+ return NULL;
+ }
+ if (newbuffer)
+ {
+ memcpy(newbuffer, p->buffer, p->offset + 1);
+ }
+ p->hooks.deallocate(p->buffer);
+ }
+ p->length = newsize;
+ p->buffer = newbuffer;
+
+ return newbuffer + p->offset;
+}
+
+/* calculate the new length of the string in a printbuffer and update the offset */
+static void update_offset(printbuffer * const buffer)
+{
+ const unsigned char *buffer_pointer = NULL;
+ if ((buffer == NULL) || (buffer->buffer == NULL))
+ {
+ return;
+ }
+ buffer_pointer = buffer->buffer + buffer->offset;
+
+ buffer->offset += strlen((const char*)buffer_pointer);
+}
+
+/* Render the number nicely from the given item into a string. */
+static cJSON_bool print_number(const cJSON * const item, printbuffer * const output_buffer)
+{
+ unsigned char *output_pointer = NULL;
+ double d = item->valuedouble;
+ int length = 0;
+ size_t i = 0;
+ unsigned char number_buffer[26]; /* temporary buffer to print the number into */
+ unsigned char decimal_point = get_decimal_point();
+ double test;
+
+ if (output_buffer == NULL)
+ {
+ return false;
+ }
+
+ /* This checks for NaN and Infinity */
+ if ((d * 0) != 0)
+ {
+ length = sprintf((char*)number_buffer, "null");
+ }
+ else
+ {
+ /* Try 15 decimal places of precision to avoid nonsignificant nonzero digits */
+ length = sprintf((char*)number_buffer, "%1.15g", d);
+
+ /* Check whether the original double can be recovered */
+ if ((sscanf((char*)number_buffer, "%lg", &test) != 1) || ((double)test != d))
+ {
+ /* If not, print with 17 decimal places of precision */
+ length = sprintf((char*)number_buffer, "%1.17g", d);
+ }
+ }
+
+ /* sprintf failed or buffer overrun occured */
+ if ((length < 0) || (length > (int)(sizeof(number_buffer) - 1)))
+ {
+ return false;
+ }
+
+ /* reserve appropriate space in the output */
+ output_pointer = ensure(output_buffer, (size_t)length);
+ if (output_pointer == NULL)
+ {
+ return false;
+ }
+
+ /* copy the printed number to the output and replace locale
+ * dependent decimal point with '.' */
+ for (i = 0; i < ((size_t)length); i++)
+ {
+ if (number_buffer[i] == decimal_point)
+ {
+ output_pointer[i] = '.';
+ continue;
+ }
+
+ output_pointer[i] = number_buffer[i];
+ }
+ output_pointer[i] = '\0';
+
+ output_buffer->offset += (size_t)length;
+
+ return true;
+}
+
+/* parse 4 digit hexadecimal number */
+static unsigned parse_hex4(const unsigned char * const input)
+{
+ unsigned int h = 0;
+ size_t i = 0;
+
+ for (i = 0; i < 4; i++)
+ {
+ /* parse digit */
+ if ((input[i] >= '0') && (input[i] <= '9'))
+ {
+ h += (unsigned int) input[i] - '0';
+ }
+ else if ((input[i] >= 'A') && (input[i] <= 'F'))
+ {
+ h += (unsigned int) 10 + input[i] - 'A';
+ }
+ else if ((input[i] >= 'a') && (input[i] <= 'f'))
+ {
+ h += (unsigned int) 10 + input[i] - 'a';
+ }
+ else /* invalid */
+ {
+ return 0;
+ }
+
+ if (i < 3)
+ {
+ /* shift left to make place for the next nibble */
+ h = h << 4;
+ }
+ }
+
+ return h;
+}
+
+/* converts a UTF-16 literal to UTF-8
+ * A literal can be one or two sequences of the form \uXXXX */
+static unsigned char utf16_literal_to_utf8(const unsigned char * const input_pointer, const unsigned char * const input_end, unsigned char **output_pointer)
+{
+ long unsigned int codepoint = 0;
+ unsigned int first_code = 0;
+ const unsigned char *first_sequence = input_pointer;
+ unsigned char utf8_length = 0;
+ unsigned char utf8_position = 0;
+ unsigned char sequence_length = 0;
+ unsigned char first_byte_mark = 0;
+
+ if ((input_end - first_sequence) < 6)
+ {
+ /* input ends unexpectedly */
+ goto fail;
+ }
+
+ /* get the first utf16 sequence */
+ first_code = parse_hex4(first_sequence + 2);
+
+ /* check that the code is valid */
+ if (((first_code >= 0xDC00) && (first_code <= 0xDFFF)))
+ {
+ goto fail;
+ }
+
+ /* UTF16 surrogate pair */
+ if ((first_code >= 0xD800) && (first_code <= 0xDBFF))
+ {
+ const unsigned char *second_sequence = first_sequence + 6;
+ unsigned int second_code = 0;
+ sequence_length = 12; /* \uXXXX\uXXXX */
+
+ if ((input_end - second_sequence) < 6)
+ {
+ /* input ends unexpectedly */
+ goto fail;
+ }
+
+ if ((second_sequence[0] != '\\') || (second_sequence[1] != 'u'))
+ {
+ /* missing second half of the surrogate pair */
+ goto fail;
+ }
+
+ /* get the second utf16 sequence */
+ second_code = parse_hex4(second_sequence + 2);
+ /* check that the code is valid */
+ if ((second_code < 0xDC00) || (second_code > 0xDFFF))
+ {
+ /* invalid second half of the surrogate pair */
+ goto fail;
+ }
+
+
+ /* calculate the unicode codepoint from the surrogate pair */
+ codepoint = 0x10000 + (((first_code & 0x3FF) << 10) | (second_code & 0x3FF));
+ }
+ else
+ {
+ sequence_length = 6; /* \uXXXX */
+ codepoint = first_code;
+ }
+
+ /* encode as UTF-8
+ * takes at maximum 4 bytes to encode:
+ * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */
+ if (codepoint < 0x80)
+ {
+ /* normal ascii, encoding 0xxxxxxx */
+ utf8_length = 1;
+ }
+ else if (codepoint < 0x800)
+ {
+ /* two bytes, encoding 110xxxxx 10xxxxxx */
+ utf8_length = 2;
+ first_byte_mark = 0xC0; /* 11000000 */
+ }
+ else if (codepoint < 0x10000)
+ {
+ /* three bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx */
+ utf8_length = 3;
+ first_byte_mark = 0xE0; /* 11100000 */
+ }
+ else if (codepoint <= 0x10FFFF)
+ {
+ /* four bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx 10xxxxxx */
+ utf8_length = 4;
+ first_byte_mark = 0xF0; /* 11110000 */
+ }
+ else
+ {
+ /* invalid unicode codepoint */
+ goto fail;
+ }
+
+ /* encode as utf8 */
+ for (utf8_position = (unsigned char)(utf8_length - 1); utf8_position > 0; utf8_position--)
+ {
+ /* 10xxxxxx */
+ (*output_pointer)[utf8_position] = (unsigned char)((codepoint | 0x80) & 0xBF);
+ codepoint >>= 6;
+ }
+ /* encode first byte */
+ if (utf8_length > 1)
+ {
+ (*output_pointer)[0] = (unsigned char)((codepoint | first_byte_mark) & 0xFF);
+ }
+ else
+ {
+ (*output_pointer)[0] = (unsigned char)(codepoint & 0x7F);
+ }
+
+ *output_pointer += utf8_length;
+
+ return sequence_length;
+
+fail:
+ return 0;
+}
+
+/* Parse the input text into an unescaped cinput, and populate item. */
+static cJSON_bool parse_string(cJSON * const item, parse_buffer * const input_buffer)
+{
+ const unsigned char *input_pointer = buffer_at_offset(input_buffer) + 1;
+ const unsigned char *input_end = buffer_at_offset(input_buffer) + 1;
+ unsigned char *output_pointer = NULL;
+ unsigned char *output = NULL;
+
+ /* not a string */
+ if (buffer_at_offset(input_buffer)[0] != '\"')
+ {
+ goto fail;
+ }
+
+ {
+ /* calculate approximate size of the output (overestimate) */
+ size_t allocation_length = 0;
+ size_t skipped_bytes = 0;
+ while (((size_t)(input_end - input_buffer->content) < input_buffer->length) && (*input_end != '\"'))
+ {
+ /* is escape sequence */
+ if (input_end[0] == '\\')
+ {
+ if ((size_t)(input_end + 1 - input_buffer->content) >= input_buffer->length)
+ {
+ /* prevent buffer overflow when last input character is a backslash */
+ goto fail;
+ }
+ skipped_bytes++;
+ input_end++;
+ }
+ input_end++;
+ }
+ if (((size_t)(input_end - input_buffer->content) >= input_buffer->length) || (*input_end != '\"'))
+ {
+ goto fail; /* string ended unexpectedly */
+ }
+
+ /* This is at most how much we need for the output */
+ allocation_length = (size_t) (input_end - buffer_at_offset(input_buffer)) - skipped_bytes;
+ output = (unsigned char*)input_buffer->hooks.allocate(allocation_length + sizeof(""));
+ if (output == NULL)
+ {
+ goto fail; /* allocation failure */
+ }
+ }
+
+ output_pointer = output;
+ /* loop through the string literal */
+ while (input_pointer < input_end)
+ {
+ if (*input_pointer != '\\')
+ {
+ *output_pointer++ = *input_pointer++;
+ }
+ /* escape sequence */
+ else
+ {
+ unsigned char sequence_length = 2;
+ if ((input_end - input_pointer) < 1)
+ {
+ goto fail;
+ }
+
+ switch (input_pointer[1])
+ {
+ case 'b':
+ *output_pointer++ = '\b';
+ break;
+ case 'f':
+ *output_pointer++ = '\f';
+ break;
+ case 'n':
+ *output_pointer++ = '\n';
+ break;
+ case 'r':
+ *output_pointer++ = '\r';
+ break;
+ case 't':
+ *output_pointer++ = '\t';
+ break;
+ case '\"':
+ case '\\':
+ case '/':
+ *output_pointer++ = input_pointer[1];
+ break;
+
+ /* UTF-16 literal */
+ case 'u':
+ sequence_length = utf16_literal_to_utf8(input_pointer, input_end, &output_pointer);
+ if (sequence_length == 0)
+ {
+ /* failed to convert UTF16-literal to UTF-8 */
+ goto fail;
+ }
+ break;
+
+ default:
+ goto fail;
+ }
+ input_pointer += sequence_length;
+ }
+ }
+
+ /* zero terminate the output */
+ *output_pointer = '\0';
+
+ item->type = cJSON_String;
+ item->valuestring = (char*)output;
+
+ input_buffer->offset = (size_t) (input_end - input_buffer->content);
+ input_buffer->offset++;
+
+ return true;
+
+fail:
+ if (output != NULL)
+ {
+ input_buffer->hooks.deallocate(output);
+ }
+
+ if (input_pointer != NULL)
+ {
+ input_buffer->offset = (size_t)(input_pointer - input_buffer->content);
+ }
+
+ return false;
+}
+
+/* Render the cstring provided to an escaped version that can be printed. */
+static cJSON_bool print_string_ptr(const unsigned char * const input, printbuffer * const output_buffer)
+{
+ const unsigned char *input_pointer = NULL;
+ unsigned char *output = NULL;
+ unsigned char *output_pointer = NULL;
+ size_t output_length = 0;
+ /* numbers of additional characters needed for escaping */
+ size_t escape_characters = 0;
+
+ if (output_buffer == NULL)
+ {
+ return false;
+ }
+
+ /* empty string */
+ if (input == NULL)
+ {
+ output = ensure(output_buffer, sizeof("\"\""));
+ if (output == NULL)
+ {
+ return false;
+ }
+ strcpy((char*)output, "\"\"");
+
+ return true;
+ }
+
+ /* set "flag" to 1 if something needs to be escaped */
+ for (input_pointer = input; *input_pointer; input_pointer++)
+ {
+ switch (*input_pointer)
+ {
+ case '\"':
+ case '\\':
+ case '\b':
+ case '\f':
+ case '\n':
+ case '\r':
+ case '\t':
+ /* one character escape sequence */
+ escape_characters++;
+ break;
+ default:
+ if (*input_pointer < 32)
+ {
+ /* UTF-16 escape sequence uXXXX */
+ escape_characters += 5;
+ }
+ break;
+ }
+ }
+ output_length = (size_t)(input_pointer - input) + escape_characters;
+
+ output = ensure(output_buffer, output_length + sizeof("\"\""));
+ if (output == NULL)
+ {
+ return false;
+ }
+
+ /* no characters have to be escaped */
+ if (escape_characters == 0)
+ {
+ output[0] = '\"';
+ memcpy(output + 1, input, output_length);
+ output[output_length + 1] = '\"';
+ output[output_length + 2] = '\0';
+
+ return true;
+ }
+
+ output[0] = '\"';
+ output_pointer = output + 1;
+ /* copy the string */
+ for (input_pointer = input; *input_pointer != '\0'; (void)input_pointer++, output_pointer++)
+ {
+ if ((*input_pointer > 31) && (*input_pointer != '\"') && (*input_pointer != '\\'))
+ {
+ /* normal character, copy */
+ *output_pointer = *input_pointer;
+ }
+ else
+ {
+ /* character needs to be escaped */
+ *output_pointer++ = '\\';
+ switch (*input_pointer)
+ {
+ case '\\':
+ *output_pointer = '\\';
+ break;
+ case '\"':
+ *output_pointer = '\"';
+ break;
+ case '\b':
+ *output_pointer = 'b';
+ break;
+ case '\f':
+ *output_pointer = 'f';
+ break;
+ case '\n':
+ *output_pointer = 'n';
+ break;
+ case '\r':
+ *output_pointer = 'r';
+ break;
+ case '\t':
+ *output_pointer = 't';
+ break;
+ default:
+ /* escape and print as unicode codepoint */
+ sprintf((char*)output_pointer, "u%04x", *input_pointer);
+ output_pointer += 4;
+ break;
+ }
+ }
+ }
+ output[output_length + 1] = '\"';
+ output[output_length + 2] = '\0';
+
+ return true;
+}
+
+/* Invoke print_string_ptr (which is useful) on an item. */
+static cJSON_bool print_string(const cJSON * const item, printbuffer * const p)
+{
+ return print_string_ptr((unsigned char*)item->valuestring, p);
+}
+
+/* Predeclare these prototypes. */
+static cJSON_bool parse_value(cJSON * const item, parse_buffer * const input_buffer);
+static cJSON_bool print_value(const cJSON * const item, printbuffer * const output_buffer);
+static cJSON_bool parse_array(cJSON * const item, parse_buffer * const input_buffer);
+static cJSON_bool print_array(const cJSON * const item, printbuffer * const output_buffer);
+static cJSON_bool parse_object(cJSON * const item, parse_buffer * const input_buffer);
+static cJSON_bool print_object(const cJSON * const item, printbuffer * const output_buffer);
+
+/* Utility to jump whitespace and cr/lf */
+static parse_buffer *buffer_skip_whitespace(parse_buffer * const buffer)
+{
+ if ((buffer == NULL) || (buffer->content == NULL))
+ {
+ return NULL;
+ }
+
+ while (can_access_at_index(buffer, 0) && (buffer_at_offset(buffer)[0] <= 32))
+ {
+ buffer->offset++;
+ }
+
+ if (buffer->offset == buffer->length)
+ {
+ buffer->offset--;
+ }
+
+ return buffer;
+}
+
+/* Parse an object - create a new root, and populate. */
+CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated)
+{
+ parse_buffer buffer = { 0, 0, 0, 0, { 0, 0, 0 } };
+ cJSON *item = NULL;
+
+ /* reset error position */
+ global_error.json = NULL;
+ global_error.position = 0;
+
+ if (value == NULL)
+ {
+ goto fail;
+ }
+
+ buffer.content = (const unsigned char*)value;
+ buffer.length = strlen((const char*)value) + sizeof("");
+ buffer.offset = 0;
+ buffer.hooks = global_hooks;
+
+ item = cJSON_New_Item(&global_hooks);
+ if (item == NULL) /* memory fail */
+ {
+ goto fail;
+ }
+
+ if (!parse_value(item, buffer_skip_whitespace(&buffer)))
+ {
+ /* parse failure. ep is set. */
+ goto fail;
+ }
+
+ /* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */
+ if (require_null_terminated)
+ {
+ buffer_skip_whitespace(&buffer);
+ if ((buffer.offset >= buffer.length) || buffer_at_offset(&buffer)[0] != '\0')
+ {
+ goto fail;
+ }
+ }
+ if (return_parse_end)
+ {
+ *return_parse_end = (const char*)buffer_at_offset(&buffer);
+ }
+
+ return item;
+
+fail:
+ if (item != NULL)
+ {
+ cJSON_Delete(item);
+ }
+
+ if (value != NULL)
+ {
+ error local_error;
+ local_error.json = (const unsigned char*)value;
+ local_error.position = 0;
+
+ if (buffer.offset < buffer.length)
+ {
+ local_error.position = buffer.offset;
+ }
+ else if (buffer.length > 0)
+ {
+ local_error.position = buffer.length - 1;
+ }
+
+ if (return_parse_end != NULL)
+ {
+ *return_parse_end = (const char*)local_error.json + local_error.position;
+ }
+ else
+ {
+ global_error = local_error;
+ }
+ }
+
+ return NULL;
+}
+
+/* Default options for cJSON_Parse */
+CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value)
+{
+ return cJSON_ParseWithOpts(value, 0, 0);
+}
+
+#define cjson_min(a, b) ((a < b) ? a : b)
+
+static unsigned char *print(const cJSON * const item, cJSON_bool format, const internal_hooks * const hooks)
+{
+ printbuffer buffer[1];
+ unsigned char *printed = NULL;
+
+ memset(buffer, 0, sizeof(buffer));
+
+ /* create buffer */
+ buffer->buffer = (unsigned char*) hooks->allocate(256);
+ buffer->format = format;
+ buffer->hooks = *hooks;
+ if (buffer->buffer == NULL)
+ {
+ goto fail;
+ }
+
+ /* print the value */
+ if (!print_value(item, buffer))
+ {
+ goto fail;
+ }
+ update_offset(buffer);
+
+ /* check if reallocate is available */
+ if (hooks->reallocate != NULL)
+ {
+ printed = (unsigned char*) hooks->reallocate(buffer->buffer, buffer->length);
+ buffer->buffer = NULL;
+ if (printed == NULL)
+ {
+ goto fail;
+ }
+ }
+ else /* otherwise copy the JSON over to a new buffer */
+ {
+ printed = (unsigned char*) hooks->allocate(buffer->offset + 1);
+ if (printed == NULL)
+ {
+ goto fail;
+ }
+ memcpy(printed, buffer->buffer, cjson_min(buffer->length, buffer->offset + 1));
+ printed[buffer->offset] = '\0'; /* just to be sure */
+
+ /* free the buffer */
+ hooks->deallocate(buffer->buffer);
+ }
+
+ return printed;
+
+fail:
+ if (buffer->buffer != NULL)
+ {
+ hooks->deallocate(buffer->buffer);
+ }
+
+ if (printed != NULL)
+ {
+ hooks->deallocate(printed);
+ }
+
+ return NULL;
+}
+
+/* Render a cJSON item/entity/structure to text. */
+CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item)
+{
+ return (char*)print(item, true, &global_hooks);
+}
+
+CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item)
+{
+ return (char*)print(item, false, &global_hooks);
+}
+
+CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt)
+{
+ printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } };
+
+ if (prebuffer < 0)
+ {
+ return NULL;
+ }
+
+ p.buffer = (unsigned char*)global_hooks.allocate((size_t)prebuffer);
+ if (!p.buffer)
+ {
+ return NULL;
+ }
+
+ p.length = (size_t)prebuffer;
+ p.offset = 0;
+ p.noalloc = false;
+ p.format = fmt;
+ p.hooks = global_hooks;
+
+ if (!print_value(item, &p))
+ {
+ return NULL;
+ }
+
+ return (char*)p.buffer;
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buf, const int len, const cJSON_bool fmt)
+{
+ printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } };
+
+ if (len < 0)
+ {
+ return false;
+ }
+
+ p.buffer = (unsigned char*)buf;
+ p.length = (size_t)len;
+ p.offset = 0;
+ p.noalloc = true;
+ p.format = fmt;
+ p.hooks = global_hooks;
+
+ return print_value(item, &p);
+}
+
+/* Parser core - when encountering text, process appropriately. */
+static cJSON_bool parse_value(cJSON * const item, parse_buffer * const input_buffer)
+{
+ if ((input_buffer == NULL) || (input_buffer->content == NULL))
+ {
+ return false; /* no input */
+ }
+
+ /* parse the different types of values */
+ /* null */
+ if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), "null", 4) == 0))
+ {
+ item->type = cJSON_NULL;
+ input_buffer->offset += 4;
+ return true;
+ }
+ /* false */
+ if (can_read(input_buffer, 5) && (strncmp((const char*)buffer_at_offset(input_buffer), "false", 5) == 0))
+ {
+ item->type = cJSON_False;
+ input_buffer->offset += 5;
+ return true;
+ }
+ /* true */
+ if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), "true", 4) == 0))
+ {
+ item->type = cJSON_True;
+ item->valueint = 1;
+ input_buffer->offset += 4;
+ return true;
+ }
+ /* string */
+ if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '\"'))
+ {
+ return parse_string(item, input_buffer);
+ }
+ /* number */
+ if (can_access_at_index(input_buffer, 0) && ((buffer_at_offset(input_buffer)[0] == '-') || ((buffer_at_offset(input_buffer)[0] >= '0') && (buffer_at_offset(input_buffer)[0] <= '9'))))
+ {
+ return parse_number(item, input_buffer);
+ }
+ /* array */
+ if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '['))
+ {
+ return parse_array(item, input_buffer);
+ }
+ /* object */
+ if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '{'))
+ {
+ return parse_object(item, input_buffer);
+ }
+
+
+ return false;
+}
+
+/* Render a value to text. */
+static cJSON_bool print_value(const cJSON * const item, printbuffer * const output_buffer)
+{
+ unsigned char *output = NULL;
+
+ if ((item == NULL) || (output_buffer == NULL))
+ {
+ return false;
+ }
+
+ switch ((item->type) & 0xFF)
+ {
+ case cJSON_NULL:
+ output = ensure(output_buffer, 5);
+ if (output == NULL)
+ {
+ return false;
+ }
+ strcpy((char*)output, "null");
+ return true;
+
+ case cJSON_False:
+ output = ensure(output_buffer, 6);
+ if (output == NULL)
+ {
+ return false;
+ }
+ strcpy((char*)output, "false");
+ return true;
+
+ case cJSON_True:
+ output = ensure(output_buffer, 5);
+ if (output == NULL)
+ {
+ return false;
+ }
+ strcpy((char*)output, "true");
+ return true;
+
+ case cJSON_Number:
+ return print_number(item, output_buffer);
+
+ case cJSON_Raw:
+ {
+ size_t raw_length = 0;
+ if (item->valuestring == NULL)
+ {
+ if (!output_buffer->noalloc)
+ {
+ output_buffer->hooks.deallocate(output_buffer->buffer);
+ }
+ return false;
+ }
+
+ raw_length = strlen(item->valuestring) + sizeof("");
+ output = ensure(output_buffer, raw_length);
+ if (output == NULL)
+ {
+ return false;
+ }
+ memcpy(output, item->valuestring, raw_length);
+ return true;
+ }
+
+ case cJSON_String:
+ return print_string(item, output_buffer);
+
+ case cJSON_Array:
+ return print_array(item, output_buffer);
+
+ case cJSON_Object:
+ return print_object(item, output_buffer);
+
+ default:
+ return false;
+ }
+}
+
+/* Build an array from input text. */
+static cJSON_bool parse_array(cJSON * const item, parse_buffer * const input_buffer)
+{
+ cJSON *head = NULL; /* head of the linked list */
+ cJSON *current_item = NULL;
+
+ if (input_buffer->depth >= CJSON_NESTING_LIMIT)
+ {
+ return false; /* to deeply nested */
+ }
+ input_buffer->depth++;
+
+ if (buffer_at_offset(input_buffer)[0] != '[')
+ {
+ /* not an array */
+ goto fail;
+ }
+
+ input_buffer->offset++;
+ buffer_skip_whitespace(input_buffer);
+ if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ']'))
+ {
+ /* empty array */
+ goto success;
+ }
+
+ /* check if we skipped to the end of the buffer */
+ if (cannot_access_at_index(input_buffer, 0))
+ {
+ input_buffer->offset--;
+ goto fail;
+ }
+
+ /* step back to character in front of the first element */
+ input_buffer->offset--;
+ /* loop through the comma separated array elements */
+ do
+ {
+ /* allocate next item */
+ cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks));
+ if (new_item == NULL)
+ {
+ goto fail; /* allocation failure */
+ }
+
+ /* attach next item to list */
+ if (head == NULL)
+ {
+ /* start the linked list */
+ current_item = head = new_item;
+ }
+ else
+ {
+ /* add to the end and advance */
+ current_item->next = new_item;
+ new_item->prev = current_item;
+ current_item = new_item;
+ }
+
+ /* parse next value */
+ input_buffer->offset++;
+ buffer_skip_whitespace(input_buffer);
+ if (!parse_value(current_item, input_buffer))
+ {
+ goto fail; /* failed to parse value */
+ }
+ buffer_skip_whitespace(input_buffer);
+ }
+ while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ','));
+
+ if (cannot_access_at_index(input_buffer, 0) || buffer_at_offset(input_buffer)[0] != ']')
+ {
+ goto fail; /* expected end of array */
+ }
+
+success:
+ input_buffer->depth--;
+
+ item->type = cJSON_Array;
+ item->child = head;
+
+ input_buffer->offset++;
+
+ return true;
+
+fail:
+ if (head != NULL)
+ {
+ cJSON_Delete(head);
+ }
+
+ return false;
+}
+
+/* Render an array to text */
+static cJSON_bool print_array(const cJSON * const item, printbuffer * const output_buffer)
+{
+ unsigned char *output_pointer = NULL;
+ size_t length = 0;
+ cJSON *current_element = item->child;
+
+ if (output_buffer == NULL)
+ {
+ return false;
+ }
+
+ /* Compose the output array. */
+ /* opening square bracket */
+ output_pointer = ensure(output_buffer, 1);
+ if (output_pointer == NULL)
+ {
+ return false;
+ }
+
+ *output_pointer = '[';
+ output_buffer->offset++;
+ output_buffer->depth++;
+
+ while (current_element != NULL)
+ {
+ if (!print_value(current_element, output_buffer))
+ {
+ return false;
+ }
+ update_offset(output_buffer);
+ if (current_element->next)
+ {
+ length = (size_t) (output_buffer->format ? 2 : 1);
+ output_pointer = ensure(output_buffer, length + 1);
+ if (output_pointer == NULL)
+ {
+ return false;
+ }
+ *output_pointer++ = ',';
+ if(output_buffer->format)
+ {
+ *output_pointer++ = ' ';
+ }
+ *output_pointer = '\0';
+ output_buffer->offset += length;
+ }
+ current_element = current_element->next;
+ }
+
+ output_pointer = ensure(output_buffer, 2);
+ if (output_pointer == NULL)
+ {
+ return false;
+ }
+ *output_pointer++ = ']';
+ *output_pointer = '\0';
+ output_buffer->depth--;
+
+ return true;
+}
+
+/* Build an object from the text. */
+static cJSON_bool parse_object(cJSON * const item, parse_buffer * const input_buffer)
+{
+ cJSON *head = NULL; /* linked list head */
+ cJSON *current_item = NULL;
+
+ if (input_buffer->depth >= CJSON_NESTING_LIMIT)
+ {
+ return false; /* to deeply nested */
+ }
+ input_buffer->depth++;
+
+ if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '{'))
+ {
+ goto fail; /* not an object */
+ }
+
+ input_buffer->offset++;
+ buffer_skip_whitespace(input_buffer);
+ if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '}'))
+ {
+ goto success; /* empty object */
+ }
+
+ /* check if we skipped to the end of the buffer */
+ if (cannot_access_at_index(input_buffer, 0))
+ {
+ input_buffer->offset--;
+ goto fail;
+ }
+
+ /* step back to character in front of the first element */
+ input_buffer->offset--;
+ /* loop through the comma separated array elements */
+ do
+ {
+ /* allocate next item */
+ cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks));
+ if (new_item == NULL)
+ {
+ goto fail; /* allocation failure */
+ }
+
+ /* attach next item to list */
+ if (head == NULL)
+ {
+ /* start the linked list */
+ current_item = head = new_item;
+ }
+ else
+ {
+ /* add to the end and advance */
+ current_item->next = new_item;
+ new_item->prev = current_item;
+ current_item = new_item;
+ }
+
+ /* parse the name of the child */
+ input_buffer->offset++;
+ buffer_skip_whitespace(input_buffer);
+ if (!parse_string(current_item, input_buffer))
+ {
+ goto fail; /* faile to parse name */
+ }
+ buffer_skip_whitespace(input_buffer);
+
+ /* swap valuestring and string, because we parsed the name */
+ current_item->string = current_item->valuestring;
+ current_item->valuestring = NULL;
+
+ if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != ':'))
+ {
+ goto fail; /* invalid object */
+ }
+
+ /* parse the value */
+ input_buffer->offset++;
+ buffer_skip_whitespace(input_buffer);
+ if (!parse_value(current_item, input_buffer))
+ {
+ goto fail; /* failed to parse value */
+ }
+ buffer_skip_whitespace(input_buffer);
+ }
+ while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ','));
+
+ if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '}'))
+ {
+ goto fail; /* expected end of object */
+ }
+
+success:
+ input_buffer->depth--;
+
+ item->type = cJSON_Object;
+ item->child = head;
+
+ input_buffer->offset++;
+ return true;
+
+fail:
+ if (head != NULL)
+ {
+ cJSON_Delete(head);
+ }
+
+ return false;
+}
+
+/* Render an object to text. */
+static cJSON_bool print_object(const cJSON * const item, printbuffer * const output_buffer)
+{
+ unsigned char *output_pointer = NULL;
+ size_t length = 0;
+ cJSON *current_item = item->child;
+
+ if (output_buffer == NULL)
+ {
+ return false;
+ }
+
+ /* Compose the output: */
+ length = (size_t) (output_buffer->format ? 2 : 1); /* fmt: {\n */
+ output_pointer = ensure(output_buffer, length + 1);
+ if (output_pointer == NULL)
+ {
+ return false;
+ }
+
+ *output_pointer++ = '{';
+ output_buffer->depth++;
+ if (output_buffer->format)
+ {
+ *output_pointer++ = '\n';
+ }
+ output_buffer->offset += length;
+
+ while (current_item)
+ {
+ if (output_buffer->format)
+ {
+ size_t i;
+ output_pointer = ensure(output_buffer, output_buffer->depth);
+ if (output_pointer == NULL)
+ {
+ return false;
+ }
+ for (i = 0; i < output_buffer->depth; i++)
+ {
+ *output_pointer++ = '\t';
+ }
+ output_buffer->offset += output_buffer->depth;
+ }
+
+ /* print key */
+ if (!print_string_ptr((unsigned char*)current_item->string, output_buffer))
+ {
+ return false;
+ }
+ update_offset(output_buffer);
+
+ length = (size_t) (output_buffer->format ? 2 : 1);
+ output_pointer = ensure(output_buffer, length);
+ if (output_pointer == NULL)
+ {
+ return false;
+ }
+ *output_pointer++ = ':';
+ if (output_buffer->format)
+ {
+ *output_pointer++ = '\t';
+ }
+ output_buffer->offset += length;
+
+ /* print value */
+ if (!print_value(current_item, output_buffer))
+ {
+ return false;
+ }
+ update_offset(output_buffer);
+
+ /* print comma if not last */
+ length = (size_t) ((output_buffer->format ? 1 : 0) + (current_item->next ? 1 : 0));
+ output_pointer = ensure(output_buffer, length + 1);
+ if (output_pointer == NULL)
+ {
+ return false;
+ }
+ if (current_item->next)
+ {
+ *output_pointer++ = ',';
+ }
+
+ if (output_buffer->format)
+ {
+ *output_pointer++ = '\n';
+ }
+ *output_pointer = '\0';
+ output_buffer->offset += length;
+
+ current_item = current_item->next;
+ }
+
+ output_pointer = ensure(output_buffer, output_buffer->format ? (output_buffer->depth + 1) : 2);
+ if (output_pointer == NULL)
+ {
+ return false;
+ }
+ if (output_buffer->format)
+ {
+ size_t i;
+ for (i = 0; i < (output_buffer->depth - 1); i++)
+ {
+ *output_pointer++ = '\t';
+ }
+ }
+ *output_pointer++ = '}';
+ *output_pointer = '\0';
+ output_buffer->depth--;
+
+ return true;
+}
+
+/* Get Array size/item / object item. */
+CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array)
+{
+ cJSON *c = array->child;
+ size_t i = 0;
+ while(c)
+ {
+ i++;
+ c = c->next;
+ }
+
+ /* FIXME: Can overflow here. Cannot be fixed without breaking the API */
+
+ return (int)i;
+}
+
+static cJSON* get_array_item(const cJSON *array, size_t index)
+{
+ cJSON *current_child = NULL;
+
+ if (array == NULL)
+ {
+ return NULL;
+ }
+
+ current_child = array->child;
+ while ((current_child != NULL) && (index > 0))
+ {
+ index--;
+ current_child = current_child->next;
+ }
+
+ return current_child;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index)
+{
+ if (index < 0)
+ {
+ return NULL;
+ }
+
+ return get_array_item(array, (size_t)index);
+}
+
+static cJSON *get_object_item(const cJSON * const object, const char * const name, const cJSON_bool case_sensitive)
+{
+ cJSON *current_element = NULL;
+
+ if ((object == NULL) || (name == NULL))
+ {
+ return NULL;
+ }
+
+ current_element = object->child;
+ if (case_sensitive)
+ {
+ while ((current_element != NULL) && (strcmp(name, current_element->string) != 0))
+ {
+ current_element = current_element->next;
+ }
+ }
+ else
+ {
+ while ((current_element != NULL) && (case_insensitive_strcmp((const unsigned char*)name, (const unsigned char*)(current_element->string)) != 0))
+ {
+ current_element = current_element->next;
+ }
+ }
+
+ return current_element;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string)
+{
+ return get_object_item(object, string, false);
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string)
+{
+ return get_object_item(object, string, true);
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string)
+{
+ return cJSON_GetObjectItem(object, string) ? 1 : 0;
+}
+
+/* Utility for array list handling. */
+static void suffix_object(cJSON *prev, cJSON *item)
+{
+ prev->next = item;
+ item->prev = prev;
+}
+
+/* Utility for handling references. */
+static cJSON *create_reference(const cJSON *item, const internal_hooks * const hooks)
+{
+ cJSON *ref = cJSON_New_Item(hooks);
+ if (!ref)
+ {
+ return NULL;
+ }
+ memcpy(ref, item, sizeof(cJSON));
+ ref->string = NULL;
+ ref->type |= cJSON_IsReference;
+ ref->next = ref->prev = NULL;
+ return ref;
+}
+
+/* Add item to array/object. */
+CJSON_PUBLIC(void) cJSON_AddItemToArray(cJSON *array, cJSON *item)
+{
+ cJSON *child = NULL;
+
+ if ((item == NULL) || (array == NULL))
+ {
+ return;
+ }
+
+ child = array->child;
+
+ if (child == NULL)
+ {
+ /* list is empty, start new one */
+ array->child = item;
+ }
+ else
+ {
+ /* append to the end */
+ while (child->next)
+ {
+ child = child->next;
+ }
+ suffix_object(child, item);
+ }
+}
+
+CJSON_PUBLIC(void) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item)
+{
+ /* call cJSON_AddItemToObjectCS for code reuse */
+ cJSON_AddItemToObjectCS(object, (char*)cJSON_strdup((const unsigned char*)string, &global_hooks), item);
+ /* remove cJSON_StringIsConst flag */
+ item->type &= ~cJSON_StringIsConst;
+}
+
+#if defined (__clang__) || ((__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5))))
+#pragma GCC diagnostic push
+#endif
+#ifdef __GNUC__
+#pragma GCC diagnostic ignored "-Wcast-qual"
+#endif
+
+/* Add an item to an object with constant string as key */
+CJSON_PUBLIC(void) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item)
+{
+ if (!item)
+ {
+ return;
+ }
+ if (!(item->type & cJSON_StringIsConst) && item->string)
+ {
+ global_hooks.deallocate(item->string);
+ }
+ item->string = (char*)string;
+ item->type |= cJSON_StringIsConst;
+ cJSON_AddItemToArray(object, item);
+}
+#if defined (__clang__) || ((__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5))))
+#pragma GCC diagnostic pop
+#endif
+
+CJSON_PUBLIC(void) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item)
+{
+ cJSON_AddItemToArray(array, create_reference(item, &global_hooks));
+}
+
+CJSON_PUBLIC(void) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item)
+{
+ cJSON_AddItemToObject(object, string, create_reference(item, &global_hooks));
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item)
+{
+ if ((parent == NULL) || (item == NULL))
+ {
+ return NULL;
+ }
+
+ if (item->prev != NULL)
+ {
+ /* not the first element */
+ item->prev->next = item->next;
+ }
+ if (item->next != NULL)
+ {
+ /* not the last element */
+ item->next->prev = item->prev;
+ }
+
+ if (item == parent->child)
+ {
+ /* first element */
+ parent->child = item->next;
+ }
+ /* make sure the detached item doesn't point anywhere anymore */
+ item->prev = NULL;
+ item->next = NULL;
+
+ return item;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which)
+{
+ if (which < 0)
+ {
+ return NULL;
+ }
+
+ return cJSON_DetachItemViaPointer(array, get_array_item(array, (size_t)which));
+}
+
+CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which)
+{
+ cJSON_Delete(cJSON_DetachItemFromArray(array, which));
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string)
+{
+ cJSON *to_detach = cJSON_GetObjectItem(object, string);
+
+ return cJSON_DetachItemViaPointer(object, to_detach);
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string)
+{
+ cJSON *to_detach = cJSON_GetObjectItemCaseSensitive(object, string);
+
+ return cJSON_DetachItemViaPointer(object, to_detach);
+}
+
+CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string)
+{
+ cJSON_Delete(cJSON_DetachItemFromObject(object, string));
+}
+
+CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string)
+{
+ cJSON_Delete(cJSON_DetachItemFromObjectCaseSensitive(object, string));
+}
+
+/* Replace array/object items with new ones. */
+CJSON_PUBLIC(void) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem)
+{
+ cJSON *after_inserted = NULL;
+
+ if (which < 0)
+ {
+ return;
+ }
+
+ after_inserted = get_array_item(array, (size_t)which);
+ if (after_inserted == NULL)
+ {
+ cJSON_AddItemToArray(array, newitem);
+ return;
+ }
+
+ newitem->next = after_inserted;
+ newitem->prev = after_inserted->prev;
+ after_inserted->prev = newitem;
+ if (after_inserted == array->child)
+ {
+ array->child = newitem;
+ }
+ else
+ {
+ newitem->prev->next = newitem;
+ }
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement)
+{
+ if ((parent == NULL) || (replacement == NULL))
+ {
+ return false;
+ }
+
+ if (replacement == item)
+ {
+ return true;
+ }
+
+ replacement->next = item->next;
+ replacement->prev = item->prev;
+
+ if (replacement->next != NULL)
+ {
+ replacement->next->prev = replacement;
+ }
+ if (replacement->prev != NULL)
+ {
+ replacement->prev->next = replacement;
+ }
+ if (parent->child == item)
+ {
+ parent->child = replacement;
+ }
+
+ item->next = NULL;
+ item->prev = NULL;
+ cJSON_Delete(item);
+
+ return true;
+}
+
+CJSON_PUBLIC(void) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem)
+{
+ if (which < 0)
+ {
+ return;
+ }
+
+ cJSON_ReplaceItemViaPointer(array, get_array_item(array, (size_t)which), newitem);
+}
+
+static cJSON_bool replace_item_in_object(cJSON *object, const char *string, cJSON *replacement, cJSON_bool case_sensitive)
+{
+ if (replacement == NULL)
+ {
+ return false;
+ }
+
+ /* replace the name in the replacement */
+ if (!(replacement->type & cJSON_StringIsConst) && (replacement->string != NULL))
+ {
+ cJSON_free(replacement->string);
+ }
+ replacement->string = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks);
+ replacement->type &= ~cJSON_StringIsConst;
+
+ cJSON_ReplaceItemViaPointer(object, get_object_item(object, string, case_sensitive), replacement);
+
+ return true;
+}
+
+CJSON_PUBLIC(void) cJSON_ReplaceItemInObject(cJSON *object, const char *string, cJSON *newitem)
+{
+ replace_item_in_object(object, string, newitem, false);
+}
+
+CJSON_PUBLIC(void) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object, const char *string, cJSON *newitem)
+{
+ replace_item_in_object(object, string, newitem, true);
+}
+
+/* Create basic types: */
+CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void)
+{
+ cJSON *item = cJSON_New_Item(&global_hooks);
+ if(item)
+ {
+ item->type = cJSON_NULL;
+ }
+
+ return item;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void)
+{
+ cJSON *item = cJSON_New_Item(&global_hooks);
+ if(item)
+ {
+ item->type = cJSON_True;
+ }
+
+ return item;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void)
+{
+ cJSON *item = cJSON_New_Item(&global_hooks);
+ if(item)
+ {
+ item->type = cJSON_False;
+ }
+
+ return item;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool b)
+{
+ cJSON *item = cJSON_New_Item(&global_hooks);
+ if(item)
+ {
+ item->type = b ? cJSON_True : cJSON_False;
+ }
+
+ return item;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num)
+{
+ cJSON *item = cJSON_New_Item(&global_hooks);
+ if(item)
+ {
+ item->type = cJSON_Number;
+ item->valuedouble = num;
+
+ /* use saturation in case of overflow */
+ if (num >= INT_MAX)
+ {
+ item->valueint = INT_MAX;
+ }
+ else if (num <= INT_MIN)
+ {
+ item->valueint = INT_MIN;
+ }
+ else
+ {
+ item->valueint = (int)num;
+ }
+ }
+
+ return item;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string)
+{
+ cJSON *item = cJSON_New_Item(&global_hooks);
+ if(item)
+ {
+ item->type = cJSON_String;
+ item->valuestring = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks);
+ if(!item->valuestring)
+ {
+ cJSON_Delete(item);
+ return NULL;
+ }
+ }
+
+ return item;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw)
+{
+ cJSON *item = cJSON_New_Item(&global_hooks);
+ if(item)
+ {
+ item->type = cJSON_Raw;
+ item->valuestring = (char*)cJSON_strdup((const unsigned char*)raw, &global_hooks);
+ if(!item->valuestring)
+ {
+ cJSON_Delete(item);
+ return NULL;
+ }
+ }
+
+ return item;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void)
+{
+ cJSON *item = cJSON_New_Item(&global_hooks);
+ if(item)
+ {
+ item->type=cJSON_Array;
+ }
+
+ return item;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void)
+{
+ cJSON *item = cJSON_New_Item(&global_hooks);
+ if (item)
+ {
+ item->type = cJSON_Object;
+ }
+
+ return item;
+}
+
+/* Create Arrays: */
+CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count)
+{
+ size_t i = 0;
+ cJSON *n = NULL;
+ cJSON *p = NULL;
+ cJSON *a = NULL;
+
+ if (count < 0)
+ {
+ return NULL;
+ }
+
+ a = cJSON_CreateArray();
+ for(i = 0; a && (i < (size_t)count); i++)
+ {
+ n = cJSON_CreateNumber(numbers[i]);
+ if (!n)
+ {
+ cJSON_Delete(a);
+ return NULL;
+ }
+ if(!i)
+ {
+ a->child = n;
+ }
+ else
+ {
+ suffix_object(p, n);
+ }
+ p = n;
+ }
+
+ return a;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count)
+{
+ size_t i = 0;
+ cJSON *n = NULL;
+ cJSON *p = NULL;
+ cJSON *a = NULL;
+
+ if (count < 0)
+ {
+ return NULL;
+ }
+
+ a = cJSON_CreateArray();
+
+ for(i = 0; a && (i < (size_t)count); i++)
+ {
+ n = cJSON_CreateNumber((double)numbers[i]);
+ if(!n)
+ {
+ cJSON_Delete(a);
+ return NULL;
+ }
+ if(!i)
+ {
+ a->child = n;
+ }
+ else
+ {
+ suffix_object(p, n);
+ }
+ p = n;
+ }
+
+ return a;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count)
+{
+ size_t i = 0;
+ cJSON *n = NULL;
+ cJSON *p = NULL;
+ cJSON *a = NULL;
+
+ if (count < 0)
+ {
+ return NULL;
+ }
+
+ a = cJSON_CreateArray();
+
+ for(i = 0; a && (i < (size_t)count); i++)
+ {
+ n = cJSON_CreateNumber(numbers[i]);
+ if(!n)
+ {
+ cJSON_Delete(a);
+ return NULL;
+ }
+ if(!i)
+ {
+ a->child = n;
+ }
+ else
+ {
+ suffix_object(p, n);
+ }
+ p = n;
+ }
+
+ return a;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char **strings, int count)
+{
+ size_t i = 0;
+ cJSON *n = NULL;
+ cJSON *p = NULL;
+ cJSON *a = NULL;
+
+ if (count < 0)
+ {
+ return NULL;
+ }
+
+ a = cJSON_CreateArray();
+
+ for (i = 0; a && (i < (size_t)count); i++)
+ {
+ n = cJSON_CreateString(strings[i]);
+ if(!n)
+ {
+ cJSON_Delete(a);
+ return NULL;
+ }
+ if(!i)
+ {
+ a->child = n;
+ }
+ else
+ {
+ suffix_object(p,n);
+ }
+ p = n;
+ }
+
+ return a;
+}
+
+/* Duplication */
+CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse)
+{
+ cJSON *newitem = NULL;
+ cJSON *child = NULL;
+ cJSON *next = NULL;
+ cJSON *newchild = NULL;
+
+ /* Bail on bad ptr */
+ if (!item)
+ {
+ goto fail;
+ }
+ /* Create new item */
+ newitem = cJSON_New_Item(&global_hooks);
+ if (!newitem)
+ {
+ goto fail;
+ }
+ /* Copy over all vars */
+ newitem->type = item->type & (~cJSON_IsReference);
+ newitem->valueint = item->valueint;
+ newitem->valuedouble = item->valuedouble;
+ if (item->valuestring)
+ {
+ newitem->valuestring = (char*)cJSON_strdup((unsigned char*)item->valuestring, &global_hooks);
+ if (!newitem->valuestring)
+ {
+ goto fail;
+ }
+ }
+ if (item->string)
+ {
+ newitem->string = (item->type&cJSON_StringIsConst) ? item->string : (char*)cJSON_strdup((unsigned char*)item->string, &global_hooks);
+ if (!newitem->string)
+ {
+ goto fail;
+ }
+ }
+ /* If non-recursive, then we're done! */
+ if (!recurse)
+ {
+ return newitem;
+ }
+ /* Walk the ->next chain for the child. */
+ child = item->child;
+ while (child != NULL)
+ {
+ newchild = cJSON_Duplicate(child, true); /* Duplicate (with recurse) each item in the ->next chain */
+ if (!newchild)
+ {
+ goto fail;
+ }
+ if (next != NULL)
+ {
+ /* If newitem->child already set, then crosswire ->prev and ->next and move on */
+ next->next = newchild;
+ newchild->prev = next;
+ next = newchild;
+ }
+ else
+ {
+ /* Set newitem->child and move to it */
+ newitem->child = newchild;
+ next = newchild;
+ }
+ child = child->next;
+ }
+
+ return newitem;
+
+fail:
+ if (newitem != NULL)
+ {
+ cJSON_Delete(newitem);
+ }
+
+ return NULL;
+}
+
+CJSON_PUBLIC(void) cJSON_Minify(char *json)
+{
+ unsigned char *into = (unsigned char*)json;
+ while (*json)
+ {
+ if (*json == ' ')
+ {
+ json++;
+ }
+ else if (*json == '\t')
+ {
+ /* Whitespace characters. */
+ json++;
+ }
+ else if (*json == '\r')
+ {
+ json++;
+ }
+ else if (*json=='\n')
+ {
+ json++;
+ }
+ else if ((*json == '/') && (json[1] == '/'))
+ {
+ /* double-slash comments, to end of line. */
+ while (*json && (*json != '\n'))
+ {
+ json++;
+ }
+ }
+ else if ((*json == '/') && (json[1] == '*'))
+ {
+ /* multiline comments. */
+ while (*json && !((*json == '*') && (json[1] == '/')))
+ {
+ json++;
+ }
+ json += 2;
+ }
+ else if (*json == '\"')
+ {
+ /* string literals, which are \" sensitive. */
+ *into++ = (unsigned char)*json++;
+ while (*json && (*json != '\"'))
+ {
+ if (*json == '\\')
+ {
+ *into++ = (unsigned char)*json++;
+ }
+ *into++ = (unsigned char)*json++;
+ }
+ *into++ = (unsigned char)*json++;
+ }
+ else
+ {
+ /* All other characters. */
+ *into++ = (unsigned char)*json++;
+ }
+ }
+
+ /* and null-terminate. */
+ *into = '\0';
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item)
+{
+ if (item == NULL)
+ {
+ return false;
+ }
+
+ return (item->type & 0xFF) == cJSON_Invalid;
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item)
+{
+ if (item == NULL)
+ {
+ return false;
+ }
+
+ return (item->type & 0xFF) == cJSON_False;
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item)
+{
+ if (item == NULL)
+ {
+ return false;
+ }
+
+ return (item->type & 0xff) == cJSON_True;
+}
+
+
+CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item)
+{
+ if (item == NULL)
+ {
+ return false;
+ }
+
+ return (item->type & (cJSON_True | cJSON_False)) != 0;
+}
+CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item)
+{
+ if (item == NULL)
+ {
+ return false;
+ }
+
+ return (item->type & 0xFF) == cJSON_NULL;
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item)
+{
+ if (item == NULL)
+ {
+ return false;
+ }
+
+ return (item->type & 0xFF) == cJSON_Number;
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item)
+{
+ if (item == NULL)
+ {
+ return false;
+ }
+
+ return (item->type & 0xFF) == cJSON_String;
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item)
+{
+ if (item == NULL)
+ {
+ return false;
+ }
+
+ return (item->type & 0xFF) == cJSON_Array;
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item)
+{
+ if (item == NULL)
+ {
+ return false;
+ }
+
+ return (item->type & 0xFF) == cJSON_Object;
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item)
+{
+ if (item == NULL)
+ {
+ return false;
+ }
+
+ return (item->type & 0xFF) == cJSON_Raw;
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive)
+{
+ if ((a == NULL) || (b == NULL) || ((a->type & 0xFF) != (b->type & 0xFF)) || cJSON_IsInvalid(a))
+ {
+ return false;
+ }
+
+ /* check if type is valid */
+ switch (a->type & 0xFF)
+ {
+ case cJSON_False:
+ case cJSON_True:
+ case cJSON_NULL:
+ case cJSON_Number:
+ case cJSON_String:
+ case cJSON_Raw:
+ case cJSON_Array:
+ case cJSON_Object:
+ break;
+
+ default:
+ return false;
+ }
+
+ /* identical objects are equal */
+ if (a == b)
+ {
+ return true;
+ }
+
+ switch (a->type & 0xFF)
+ {
+ /* in these cases and equal type is enough */
+ case cJSON_False:
+ case cJSON_True:
+ case cJSON_NULL:
+ return true;
+
+ case cJSON_Number:
+ if (a->valuedouble == b->valuedouble)
+ {
+ return true;
+ }
+ return false;
+
+ case cJSON_String:
+ case cJSON_Raw:
+ if ((a->valuestring == NULL) || (b->valuestring == NULL))
+ {
+ return false;
+ }
+ if (strcmp(a->valuestring, b->valuestring) == 0)
+ {
+ return true;
+ }
+
+ return false;
+
+ case cJSON_Array:
+ {
+ cJSON *a_element = a->child;
+ cJSON *b_element = b->child;
+
+ for (; (a_element != NULL) && (b_element != NULL);)
+ {
+ if (!cJSON_Compare(a_element, b_element, case_sensitive))
+ {
+ return false;
+ }
+
+ a_element = a_element->next;
+ b_element = b_element->next;
+ }
+
+ return true;
+ }
+
+ case cJSON_Object:
+ {
+ cJSON *a_element = NULL;
+ cJSON_ArrayForEach(a_element, a)
+ {
+ /* TODO This has O(n^2) runtime, which is horrible! */
+ cJSON *b_element = get_object_item(b, a_element->string, case_sensitive);
+ if (b_element == NULL)
+ {
+ return false;
+ }
+
+ if (!cJSON_Compare(a_element, b_element, case_sensitive))
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ default:
+ return false;
+ }
+}
+
+CJSON_PUBLIC(void *) cJSON_malloc(size_t size)
+{
+ return global_hooks.allocate(size);
+}
+
+CJSON_PUBLIC(void) cJSON_free(void *object)
+{
+ global_hooks.deallocate(object);
+}
diff --git a/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/Cjson/cJSON.h b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/Cjson/cJSON.h
new file mode 100644
index 00000000..f2c293bd
--- /dev/null
+++ b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/Cjson/cJSON.h
@@ -0,0 +1,263 @@
+/*
+ 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_CJSON_H_
+#define CJSON_CJSON_H_
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/* project version */
+#define CJSON_VERSION_MAJOR 1
+#define CJSON_VERSION_MINOR 5
+#define CJSON_VERSION_PATCH 4
+
+#include
+
+/* 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
+{
+ void *(*malloc_fn)(size_t sz);
+ void (*free_fn)(void *ptr);
+} cJSON_Hooks;
+
+typedef int cJSON_bool;
+
+#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 2 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
+
+*/
+
+/* 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 __stdcall
+#elif defined(CJSON_EXPORT_SYMBOLS)
+#define CJSON_PUBLIC(type) __declspec(dllexport) type __stdcall
+#elif defined(CJSON_IMPORT_SYMBOLS)
+#define CJSON_PUBLIC(type) __declspec(dllimport) type __stdcall
+#endif
+#else /* !WIN32 */
+#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
+
+/* 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);
+/* 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 *c);
+
+/* Returns the number of items in an array (or object). */
+CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array);
+/* Retrieve item number "item" 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);
+
+/* 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);
+
+/* These utilities create an Array of count items. */
+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 **strings, int count);
+
+/* Append item to the specified array/object. */
+CJSON_PUBLIC(void) cJSON_AddItemToArray(cJSON *array, cJSON *item);
+CJSON_PUBLIC(void) 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(void) 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(void) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item);
+CJSON_PUBLIC(void) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item);
+
+/* Remove/Detatch 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(void) 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(void) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem);
+CJSON_PUBLIC(void) cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem);
+CJSON_PUBLIC(void) 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);
+
+
+/* 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. If not, then cJSON_GetErrorPtr() does the job. */
+CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated);
+
+CJSON_PUBLIC(void) cJSON_Minify(char *json);
+
+/* Macros for creating things quickly. */
+#define cJSON_AddNullToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateNull())
+#define cJSON_AddTrueToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateTrue())
+#define cJSON_AddFalseToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateFalse())
+#define cJSON_AddBoolToObject(object,name,b) cJSON_AddItemToObject(object, name, cJSON_CreateBool(b))
+#define cJSON_AddNumberToObject(object,name,n) cJSON_AddItemToObject(object, name, cJSON_CreateNumber(n))
+#define cJSON_AddStringToObject(object,name,s) cJSON_AddItemToObject(object, name, cJSON_CreateString(s))
+#define cJSON_AddRawToObject(object,name,s) cJSON_AddItemToObject(object, name, cJSON_CreateRaw(s))
+
+/* 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))
+
+/* 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
diff --git a/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/ESP8266/ESP8266.c b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/ESP8266/ESP8266.c
new file mode 100644
index 00000000..5b7a43cd
--- /dev/null
+++ b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/ESP8266/ESP8266.c
@@ -0,0 +1,603 @@
+/*
+ * ESP8266.c
+ *
+ * Created on: 201853
+ * Author: Administrator
+ */
+
+
+#include "ESP8266.h"
+
+
+#include "malloc.h"
+#include "string.h"
+#include "timer.h"
+
+#include "usart3task.h"
+#include "usart1task.h"
+#include "usart4task.h"
+#include "strpos.h"
+#include "package.h"
+
+#include "task_config.h"
+//#include "suart.h"
+//#include "touch.h"
+//#include "iwdg.h"
+#define delay_ms vTaskDelay
+#define ESP8266_PRINT_RECEIVE 0//Ƿӡյ
+#define WIFI_TRYTIMES 10//ԶȡwifiģִϢ
+
+TaskHandle_t smart_config_Handler;
+TaskHandle_t connect_to_server_Handler;
+
+TimerHandle_t OneShot_config60_Handle; //ζʱ60s
+TimerHandle_t OneShot_config10_Handle; //ζʱ10s
+TimerHandle_t OneShot_config1MS_Handle;//1msʱ
+
+QueueHandle_t connect_to_server_Queue;
+
+char IP_buf[16]="121.42.180.30";//"";
+char portnum[11]="8181"; //Զ˿"11192"; //uint8_t* portnum="8086"; 9124 Ĭ϶˿Ӧ9123 ֱ9124ԺDzе
+//const char* IP_tbl[12]={"1","2","3","4","5","6","7","8","9",".","0"};
+
+//8266 smart config
+//ȹ˴3smartconfig
+//ⴥذҲҪУ˳ģʽ
+void smartconfig_task(void *pvParameters)
+{
+ uint8_t time=100;
+ BaseType_t err;
+ uint8_t wificonfig_flag = 0;//ãǽյʼwifi ͬʱǷóɹ
+// uint8_t pos_temp;
+ usart_task_data USART3_task_data;//USART3task֡
+ #if ESP8266_PRINT_RECEIVE//Դ3յ
+ uint8_t* buffer;
+ #endif
+ //
+ dprintf("smart_config start!\r\n");
+// vTaskSuspendAll();
+//
+// vTaskResume(smart_config__Handler);
+// vTaskResume(FREE_ERRORMEM_Handler);
+// vTaskResume(USART3_Handler);
+// vTaskResume(USART3_send_Handler);
+// //дذ ģⴥذ
+// vTaskResume(Task1Task_Handler);
+// vTaskResume(Keyprocess_Handler);
+// start_config_task();
+
+
+
+
+ //ӦҪλǸλûжԶеڴfreeԲܼĸλҪݽfreeڴ
+ //ȰѴ3ݽ꣬ٿʼ
+
+ {
+// quit_trans();
+// if(send_cmd_wait_ack("AT","OK",10,1))
+// {
+// printf("8266 at ok\r\n");
+//
+// }
+ free_usart3_rn_other_queue();
+ while((!send_cmd_wait_ack("AT","OK",WIFI_TRYTIMES,1))&&--time)//WIFIģǷ
+ {
+ quit_trans();//˳
+ send_cmd_wait_ack("AT+CIPMODE=0","OK",WIFI_TRYTIMES,1); //رģʽ
+ delay_ms(10);
+ }
+ if(time==0)
+ {
+ goto stop_smartconfig;
+ }
+
+ free_usart3_rn_other_queue();
+ send_cmd_wait_ack("AT+CWMODE=1","OK",WIFI_TRYTIMES,1);//Ϊstationģ
+
+ time=3;
+ free_usart3_rn_other_queue();
+ while((!send_cmd_wait_ack("AT+CWSTOPSMART","OK",WIFI_TRYTIMES,1))&&--time);//˳smartconfig
+
+ time=10;
+ free_usart3_rn_other_queue();
+ while((!send_cmd_wait_ack("AT+CWSTARTSMART","OK",WIFI_TRYTIMES,1))&&--time);//ⷢǷɹ
+ if(time==0)
+ {
+ goto stop_smartconfig;
+ }
+
+
+ //60sʱʱ䵽Զ˳ģʽ
+ err = xTimerStart(OneShot_config60_Handle,100);
+ configASSERT(err);
+// goto stop_smartconfig;//
+ while(1)
+ {
+
+ //ȼû get wifi info ־
+ if(wificonfig_flag==0)
+ {
+ if(xQueueReceive(USART3_Task_rn_other_Queue,&USART3_task_data,0/*portMAX_DELAY*/))//յ֡
+ {//ܳreceive˶Сûнеfree ʹ60sĶʱĵͶʱȼֹ߽ȣ
+ //ʵԼwifiϢssidpasssword
+ if(0xff!=findpos((uint8_t*)"get",3,USART3_task_data.pstr,USART3_task_data.len))
+ {
+ wificonfig_flag=1;
+ }
+ else if(0xff!=findpos((uint8_t*)"wifi",4,USART3_task_data.pstr,USART3_task_data.len))
+ {
+ wificonfig_flag=1;
+ }
+ else if(0xff!=findpos((uint8_t*)"info",4,USART3_task_data.pstr,USART3_task_data.len))
+ {
+ wificonfig_flag=1;
+ }
+
+ #if ESP8266_PRINT_RECEIVE//Դ3յ
+ buffer=pvPortMalloc(USART3_task_data.len+1);
+ memcpy(buffer,USART3_task_data.pstr,USART3_task_data.len);
+ buffer[USART3_task_data.len]=0;
+ dprintf("smartU3RD:%2d:%s\r\n",USART3_task_data.len,buffer);
+ vPortFree(buffer);
+ #endif
+
+ vPortFree(USART3_task_data.pstr);
+ if(wificonfig_flag==1)//get wifi info 10sʱҹر60sʱ
+ {
+ err = xTimerStop(OneShot_config60_Handle,100);
+ configASSERT(err);
+ err = xTimerStart(OneShot_config10_Handle,100);
+ configASSERT(err);
+ free_usart3_rn_other_queue();
+ }
+ }
+
+ }
+
+ //wifi sta Ƿ22ã10sʱرwifiģʽ
+ else if(wificonfig_flag==1)
+ {
+ if(check_consta()==2)//wifiɹ
+ {
+ err = xTimerStop(OneShot_config10_Handle,100);
+ configASSERT(err);
+ dprintf("connect to wifi\r\n");
+ free_usart3_rn_other_queue();
+
+ send_cmd_wait_ack("AT+CWAUTOCONN=1","OK",WIFI_TRYTIMES,1);//Զ
+ goto stop_smartconfig;
+// stop_config_task(1);
+ }
+ }
+
+ delay_ms(20);//ʱ
+ }
+
+
+ stop_smartconfig://wifiģʽ дɺȽϺ
+ stop_config_task(wificonfig_flag);
+
+// vTaskDelay(SMARTCONFIG_TASK_delay);
+ }
+}
+
+
+
+void connect_to_server(void *pvParameters)
+{
+ uint8_t temp;
+ dprintf("start connect to server\r\n");
+ while(1)
+ {
+ if(xQueueReceive(connect_to_server_Queue,&temp,portMAX_DELAY))//յ
+ {
+ dprintf("start connect to server\r\n");
+// delay_ms(30);
+ if(temp)//ǷҪϿǰ
+ {
+ disconnect_TCP();
+// delay_ms(30);
+ }
+ connect_to_server_process();
+
+
+ }
+// printf(" end of connetced to server\r\n");
+// vTaskDelay(pack2server_delay);
+// vTaskDelete(connect_to_server_Handler);//delete
+ vTaskSuspend(connect_to_server_Handler);
+ }
+
+
+
+}
+//ӷ ԭatk_8266_In_trans
+uint8_t connect_to_server_process(void )// ݶݾǷҪϿԭ Ȼӷ
+{
+ char *t;
+ BaseType_t err;
+ uint16_t temp;
+ free_usart3_rn_other_queue();
+ free_usart3_server_queue();
+ vTaskSuspend(USART3_app_Handler);
+
+ t=pvPortMalloc(64);
+ sprintf(t,"AT+CIPSTART=\"TCP\",\"%s\",%s",(uint8_t*)IP_buf,(uint8_t*)portnum);
+
+ send_cmd_wait_ack(t,"OK",WIFI_TRYTIMES*3,1);//ӵ
+ delay_ms(100);
+ vPortFree(t);
+ free_usart3_rn_other_queue();
+ if(check_consta()==3)//ûлִ?
+ {
+ touch_flag|=(0x0001<<14);//
+ free_usart3_rn_other_queue();
+ delay_ms(50);
+ printf("connetced to server\r\n");
+ pkt_serial = 1;
+ vTaskResume(USART3_app_Handler);
+
+ temp = 0x0000;
+ err=xQueueSend(pack2server_queue,&temp,10);
+
+ temp = 0x0001;
+ err=xQueueSend(pack2server_queue,&temp,10);
+ if(err==errQUEUE_FULL) //Ϣ֡
+ {
+
+ printf("pack2server_Queue0001ݷʧ!\r\n");
+ }
+// wifi2server(0x0001);
+// vTaskResume(USART3_app_Handler);
+ return 1;
+ }
+
+ return 0;
+}
+
+
+//Ͽ
+void disconnect_TCP(void)
+{
+ free_usart3_rn_other_queue();
+ send_cmd_wait_ack("AT+CIPCLOSE","OK",WIFI_TRYTIMES,1); //ϿԭTCP
+}
+
+//0ûյڴӦ
+//1յڴӦ
+//Ҫ\r\nСڻbuffij
+//ģʽ⣺1һӦIJִһָfree_usart3_rn_other_queue2ֻܶԱһĿӦ𣺶ԱʱджԱ
+uint8_t check_cmd(char*str)
+{
+
+ usart_task_data USART3_task_data;//USART3task֡
+ uint8_t ret = 0xff;
+ #if ESP8266_PRINT_RECEIVE//Դ3յ
+ uint8_t* buffer;
+ #endif
+
+ //3ͶǷΪգŽв
+// if(!uxQueueMessagesWaiting(USART3_Send_Queue))
+ {
+ if(xQueueReceive(USART3_Task_rn_other_Queue,&USART3_task_data,0/*portMAX_DELAY*/))//յ֡
+ {
+// if(USART3_task_data.type==USART_RN)
+ {
+
+ ret = findpos((uint8_t*)str,strlen(str),USART3_task_data.pstr,USART3_task_data.len);
+ #if ESP8266_PRINT_RECEIVE//Դ3յ
+ buffer=pvPortMalloc(USART3_task_data.len+1);
+ memcpy(buffer,USART3_task_data.pstr,USART3_task_data.len);
+ buffer[USART3_task_data.len]=0;
+ dprintf("ret:%d\tcmd:%2d:%s\tU3RD:%2d:%s\r\n",ret,strlen(str),str,USART3_task_data.len,buffer);
+ vPortFree(buffer);
+ #endif
+ vPortFree(USART3_task_data.pstr);
+ }
+
+ }
+ }
+ return !(ret==0xff);
+}
+
+//1 յڴӦ 0ָͺûڴӦ
+//ʱwaittime*10ms лʱ
+//rnǷβ\R\N
+
+void send_cmd(char*cmd,uint8_t rn)
+{
+ usart_task_data USART3_send_data;//USART3send
+ uint8_t*p;
+ BaseType_t err;
+
+ if(rn)
+ USART3_send_data.type = USART_RN;
+ else
+ USART3_send_data.type = USART_DIRECT;
+
+ USART3_send_data.len = strlen(cmd);
+ p = pvPortMalloc(USART3_send_data.len);
+ memcpy(p,cmd,USART3_send_data.len);
+ USART3_send_data.pstr = p;
+
+ err=xQueueSend(USART3_Send_Queue,&USART3_send_data,10);
+ if(err==errQUEUE_FULL) //Ϣ֡
+ {
+ //ʧҪfreeڴ
+ vPortFree(USART3_send_data.pstr);
+ dprintf("USART3_Send_QueueָRNʧ!\r\n");
+ }
+}
+
+uint8_t send_cmd_wait_ack(char *cmd,char *ack,uint16_t waittime,uint8_t rn)
+{
+ uint8_t ret = 0;
+
+ send_cmd(cmd,rn);
+
+ //ȴͶΪ
+// while(uxQueueMessagesWaiting(USART3_Send_Queue))
+// {
+// vTaskDelay(10);//л
+//
+// }
+
+ while(--waittime)
+ {
+ if(check_cmd(ack))
+ {
+ ret = 1;
+ break;
+ }
+ vTaskDelay(10);//л
+ }
+ if(!waittime) ret = 0;
+ return ret;
+}
+
+
+
+//1 ˳ɹ0˳ʧ
+uint8_t quit_trans(void)
+{
+ uint8_t i;
+
+
+ uart3->uart_write("+",1);
+ delay_ms(15); //ڴ֡ʱ(10ms)
+
+ uart3->uart_write("+",1);
+ delay_ms(15); //ڴ֡ʱ(10ms)
+
+ uart3->uart_write("+",1);
+ delay_ms(100); //ȴ500ms
+
+ for(i=0;i<6;i++)
+ {
+ if(send_cmd_wait_ack("+","+",3,0))
+ return 1;
+ }
+
+ return send_cmd_wait_ack("+","+",10,0);
+}
+
+
+//wifi״̬ ǰȷ˳
+//ֵ:0,1, 2,IP 3 4ʧȥ 5δӵWiFi 7,ûбִ 8ûнв
+uint8_t check_consta(void)
+{
+ uint8_t ret = 8,i;
+ usart_task_data USART3_task_data;//USART3task֡
+ #if ESP8266_PRINT_RECEIVE//Դ3յ
+ uint8_t* buffer;
+ #endif
+
+ free_usart3_rn_other_queue();
+// if(!quit_trans()) return 7;//˳ʧ
+
+ send_cmd("AT+CIPSTATUS",1);
+
+// delay_ms(60);
+ for(i=0;i<30;i++)//10Σȷȫݽ
+ {
+
+ delay_ms(60);//Ҫнմʱ
+ if(xQueueReceive(USART3_Task_rn_other_Queue,&USART3_task_data,0/*portMAX_DELAY*/))//յ֡
+ {
+ #if ESP8266_PRINT_RECEIVE//Դ3յ
+ buffer=pvPortMalloc(USART3_task_data.len+1);
+ memcpy(buffer,USART3_task_data.pstr,USART3_task_data.len);
+ buffer[USART3_task_data.len]=0;
+ dprintf("staU3RD:%2d:%s\r\n",USART3_task_data.len,buffer);
+ vPortFree(buffer);
+ #endif
+
+ if(0xff!=findpos((uint8_t*)"STATUS:0",8,USART3_task_data.pstr,USART3_task_data.len))
+ {
+ vPortFree(USART3_task_data.pstr);
+ return 0;
+ }
+ else if(0xff!=findpos((uint8_t*)"STATUS:1",8,USART3_task_data.pstr,USART3_task_data.len))
+ {
+ vPortFree(USART3_task_data.pstr);
+ return 1;
+ }
+ else if(0xff!=findpos((uint8_t*)"STATUS:2",8,USART3_task_data.pstr,USART3_task_data.len))
+ {
+ vPortFree(USART3_task_data.pstr);
+ return 2;
+ }
+ else if(0xff!=findpos((uint8_t*)"STATUS:3",8,USART3_task_data.pstr,USART3_task_data.len))
+ {
+ vPortFree(USART3_task_data.pstr);
+ return 3;
+ }
+ else if(0xff!=findpos((uint8_t*)"STATUS:4",8,USART3_task_data.pstr,USART3_task_data.len))
+ {
+ vPortFree(USART3_task_data.pstr);
+ return 4;
+ }
+ else if(0xff!=findpos((uint8_t*)"STATUS:5",8,USART3_task_data.pstr,USART3_task_data.len))
+ {
+ vPortFree(USART3_task_data.pstr);
+ return 5;
+ }
+ else
+ {
+ vPortFree(USART3_task_data.pstr);
+ ret = 7;//û״̬
+
+ }
+
+
+
+ }
+ }
+
+ return ret;
+}
+//غ
+//Ѵ3 \r\nݽ꣬freeڴ棬Ա¿ʼ
+void free_usart3_rn_other_queue(void)
+{
+ usart_task_data USART3_task_data;//USART3task֡
+
+ #if ESP8266_PRINT_RECEIVE//Դ3յ
+ uint8_t* buffer;
+ #endif
+
+// while(uxQueueMessagesWaiting(USART3_Send_Queue))//ȴͶΪ
+// {
+// delay_ms(10);
+// }
+
+ while(uxQueueMessagesWaiting(USART3_Task_rn_other_Queue))//սն
+ {
+ if(xQueueReceive(USART3_Task_rn_other_Queue,&USART3_task_data,0/*portMAX_DELAY*/))//յ֡
+ {
+ #if ESP8266_PRINT_RECEIVE//Դ3յ
+ buffer=pvPortMalloc(USART3_task_data.len+1);
+ memcpy(buffer,USART3_task_data.pstr,USART3_task_data.len);
+ buffer[USART3_task_data.len]=0;
+ dprintf("freeU3RD:%2d:%s\r\n",USART3_task_data.len,buffer);
+ vPortFree(buffer);
+ #endif
+ vPortFree(USART3_task_data.pstr);
+// printf("freeU3RD:success\r\n");
+ }
+ delay_ms(10);
+ }
+
+}
+
+//free
+void free_usart3_server_queue(void)
+{
+ usart_task_data USART3_task_data;//USART3task֡
+
+ while(uxQueueMessagesWaiting( USART3_Task_server_Queue))//սն
+ {
+ if(xQueueReceive( USART3_Task_server_Queue,&USART3_task_data,0/*portMAX_DELAY*/))//յ֡
+ {
+ vPortFree(USART3_task_data.pstr);
+ }
+ }
+}
+
+
+//ʱص ʱرյģʽʧ
+void OneShot60_10Callback(TimerHandle_t xTimer) //ζʱص
+{
+ uint32_t timer_ID;
+ configASSERT(xTimer);
+
+ timer_ID = (uint32_t) pvTimerGetTimerID(xTimer);
+
+ //ʱ
+
+ switch(timer_ID)
+ {
+ case WIFI_TIM60S_ID:
+ dprintf("60s failed\r\n");
+ stop_config_task(0);
+ break;
+ case WIFI_TIM10S_ID:
+ dprintf("10s failed\r\n");
+ stop_config_task(0);
+ break;
+ default:configASSERT(0);
+ break;
+ }
+
+}
+
+void start_config_task(void)
+{
+ set_rtc_sec(0);
+ vTaskSuspend(USART1_Handler);
+ vTaskSuspend(USART1_app_Handler);
+ vTaskSuspend(USART3_app_Handler);
+
+ touch_flag&=(~(0x0001<<4));//
+ touch_flag&=(~(0x0001<<14));
+ touch_flag&=(~(0x0001<<7));//Ϊص״̬
+ touch_flag&=0xfff0;//¼ƹλΪ0
+
+ xTimerStop(period40or5_0002_Handle,10);
+ free_usart3_server_queue();
+ xTaskCreate((TaskFunction_t )smartconfig_task,
+ (const char* )"smartconfig_task",
+ (uint16_t )SMARTCONFIG_TASK_SIZE,
+ (void* )NULL,
+ (UBaseType_t )SMARTCONFIG_TASK_PRIO,
+ (TaskHandle_t* )&smart_config_Handler);
+
+}
+
+void stop_config_task(uint8_t ifsuccess)
+{
+ uint8_t temp;
+ BaseType_t err;
+ dprintf("stop config\r\n");
+ set_rtc_sec(0);
+ pkt_serial = 0;//ĸ
+
+ touch_flag&=(~(0x0001<<5));//ֹͣwifiset
+ mcu_sendcmd2touch(Wifi_Quit);
+// delay_ms(100);
+// mcu_sendcmd2touch(Power_On);
+ touch_process_poweron();
+
+ delay_ms(50);//ģִɣá
+ free_usart3_rn_other_queue();//ҪжϽյ
+
+ vTaskResume(USART3_app_Handler);
+ vTaskResume(USART1_app_Handler);
+ vTaskResume(USART1_Handler);
+
+
+
+ //ذ
+
+
+ //ӳɹ߲
+ if(ifsuccess)
+ {
+ dprintf("stop config 1\r\n");
+ vTaskResume(connect_to_server_Handler);
+
+// connect_to_server();
+ temp = 0;
+ err=xQueueSend(connect_to_server_Queue,&temp,10);
+ if(err==errQUEUE_FULL) //Ϣ֡
+ {
+
+ dprintf("connect_to_server_Queue0ݷʧ!\r\n");
+ }
+ }
+ xTimerChangePeriod(period40or5_0002_Handle,PKG0002_5S_TICKS,10);
+ xTimerStart(period40or5_0002_Handle,10);
+ vTaskDelete(smart_config_Handler);//delete
+}
+
+
diff --git a/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/ESP8266/ESP8266.h b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/ESP8266/ESP8266.h
new file mode 100644
index 00000000..5ff278d6
--- /dev/null
+++ b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/ESP8266/ESP8266.h
@@ -0,0 +1,68 @@
+/*
+ * ESP8266.h
+ *
+ * Created on: 201853
+ * Author: Administrator
+ */
+
+#ifndef ESP8266_ESP8266_H_
+#define ESP8266_ESP8266_H_
+
+#ifndef __ESP8266_H__
+#define __ESP8266_H__
+
+
+#include "FreeRTOS.h" //FreeRTOSʹ
+#include "task.h"
+#include "queue.h"
+#include "semphr.h"
+#include "timers.h"
+
+
+
+extern char IP_buf[16];
+extern char portnum[11];
+
+void smartconfig_task(void *pvParameters);
+void connect_to_server(void *pvParameters);
+uint8_t connect_to_server_process(void );
+void disconnect_TCP(void);
+void OneShot60_10Callback(TimerHandle_t xTimer); //ζʱص
+uint8_t send_cmd_wait_ack(char *cmd,char *ack,uint16_t waittime,uint8_t rn);
+uint8_t check_cmd(char*str);
+void send_cmd(char*cmd,uint8_t rn);
+uint8_t quit_trans(void);
+void free_usart3_rn_other_queue(void);
+void free_usart3_server_queue(void);
+void stop_config_task(uint8_t ifsuccess);
+void start_config_task(void);
+uint8_t check_consta(void);
+
+#if 0
+void atk_8266_init(void);
+
+
+void atk_8266_at_response(uint8_t mode);
+uint8_t* atk_8266_check_cmd(uint8_t *str);
+uint8_t* atk_8266_check_cmd2(uint8_t *str);
+uint8_t atk_8266_apsta_check(void);
+uint8_t atk_8266_send_data(uint8_t *data,uint8_t *ack,u16 waittime);
+uint8_t atk_8266_send_cmd(uint8_t *cmd,uint8_t *ack,u16 waittime);
+uint8_t atk_8266_quit_trans(void);
+uint8_t atk_8266_consta_check(void);
+void atk_8266_get_wanip(uint8_t* ipbuf);
+void atk_8266_test(void);
+uint8_t ATK8266_SMART(void);
+uint8_t atk_8266_In_trans(void);
+uint8_t atk_8266_disconnect(void);
+uint8_t atk_8266_connectTCP(void);
+void atk_8266_In_trans1(void);
+uint8_t atk_8266_In_trans2(void);//ģʽʵ
+
+#endif
+
+#endif
+
+
+
+#endif /* ESP8266_ESP8266_H_ */
diff --git a/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/bright/bright.c b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/bright/bright.c
new file mode 100644
index 00000000..249f357c
--- /dev/null
+++ b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/bright/bright.c
@@ -0,0 +1,237 @@
+/*
+ * bright.c
+ *
+ * Created on: 2018524
+ * Author: Administrator
+ */
+
+#include "bright.h"
+#include "cm3232.h"
+#include "package.h"
+#include "usart4task.h"
+//
+#include "string.h"
+#include "stdlib.h"
+//#include "sys.h"
+#include "timer.h"
+
+
+uint16_t compare_pre,compare_target;
+bright_mode_enum bright_change_mode = LIGHT_SWITCH;
+uint16_t auto_cm3232_count;//cm3232Ҫʱ
+uint8_t autobright_direction;
+TimerHandle_t period_Bright_Handle;
+
+//180
+//uint8_t compare_set[9] = {0,1,2,3,4,5,6,8,10};//洢
+uint8_t compare_set[9] = {0,1,4,7,10,15,20,24,30};
+//uint8_t compare_set[9] = {0,6,12,18,48,60,74,86,98};
+/*
+#define LIGHT_SWITCH 0//лλ л
+#define LIGHT_DIRECT 1//ֱӵijλ
+#define LIGHT_AUTO 2
+#define LIGHT_SLEEP 3
+*/
+//Ƶƹ
+//mode:0 ֱӵָλ
+//1 Զ
+//2 ˯ߵ
+void bright_mode(bright_mode_enum mode,uint8_t light)
+{
+ switch(mode)
+ {
+ case LIGHT_SWITCH:bright_switch_process(light);
+ break;
+ case LIGHT_DIRECT:bright_direct_process(light);
+ break;
+ case LIGHT_AUTO:bright_auto_process(light);
+ break;
+ case LIGHT_SLEEP:
+ break;
+ default:break;
+ }
+
+}
+
+//1msһ
+#define TIME_PER Bright_TICKS
+//ÿڵռձ 1
+#define COMPARE_PER 1
+void bright_switch_process(uint8_t light)
+{
+ xTimerStop(period_Bright_Handle,10);
+ bright_change_mode = LIGHT_SWITCH;
+ compare_pre = compare_pwm;
+// if(compare_pre%COMPARE_PER)
+// {
+// compare_pre--;
+// TIM_SetCompare1(TIM3,compare_pre);
+// }
+ compare_target = compare_set[light];
+ xTimerStart(period_Bright_Handle,10);
+}
+
+//ֱӵڵӦλ
+void bright_direct_process(uint8_t light)
+{
+ xTimerStop(period_Bright_Handle,10);
+ bright_change_mode = LIGHT_DIRECT;
+ compare_pwm = compare_set[light];
+
+}
+
+//Զ
+#define AUTO_COMPARE_MAX 0x8500
+#define AUTO_COMPARE_MIN 0x7000
+void bright_auto_process(uint8_t light)
+{
+ (void)light;
+ xTimerStop(period_Bright_Handle,10);
+ bright_change_mode = LIGHT_AUTO;
+ auto_cm3232_count = 0;
+ autobright_direction=0;
+ xTimerStart(period_Bright_Handle,10);
+}
+
+void period_Bright_Callback(TimerHandle_t xTimer)
+{
+ switch (bright_change_mode)
+ {
+ case LIGHT_SWITCH:
+ {
+ compare_pre = compare_pwm;
+ if(compare_targetcompare_pre)
+ {
+ compare_pre+=COMPARE_PER;
+ compare_pwm = compare_pre;
+ }
+ else//ڵĿռձ
+ {
+ xTimerStop(period_Bright_Handle,0);
+ }
+ }
+ break;
+
+ case LIGHT_DIRECT:
+ break;
+ case LIGHT_AUTO :
+ {
+ if(!(auto_cm3232_count%40))//2
+ {
+// if(!(auto_cm3232_count%cm3232_time[1][CM3232_TIME]))
+ {
+ uint32_t cm3232_light = CM3232_Read(0x50);
+ auto_cm3232_count = 0;
+// dprintf("tim cm3232 %4x\r\n",cm3232_light);
+ if(cm3232_light>AUTO_COMPARE_MAX)
+ {
+ autobright_direction=2;
+ }
+ else if(cm3232_lightcompare_set[8]) compare_pre=compare_set[8];
+ brightchange_send2server_touch(compare_pre);
+ }
+ else if(autobright_direction==2)//С
+ {
+ if(compare_pre)
+ {
+ if((--compare_pre)==0) compare_pre=0;
+ }
+ brightchange_send2server_touch(compare_pre);
+ }
+ else//
+ {
+
+ }
+ }
+
+ auto_cm3232_count++;
+ }
+ break;
+ case LIGHT_SLEEP:
+ {
+
+ }
+ break;
+ default:break;
+ }
+
+}
+
+//ռձȱ仯ǷҪеλл,ʹذ
+void brightchange_send2server_touch(uint32_t compare_temp)
+{
+ uint8_t i,touch_temp = 0xff;
+
+
+ compare_pwm = compare_temp;
+
+ for(i=0;i<9;i++)
+ {
+ if(compare_temp==compare_set[i])
+ {
+ touch_temp = i;
+ break;
+ }
+ }
+
+ if(touch_temp!=0xff)
+ {
+
+ if(touch_temp!=(touch_flag&0x000f))
+ {
+// dprintf("touch_temp = %d\r\n",touch_temp);
+ if(touch_temp)
+ {
+ if(touch_flag&(0x0001<<14))//״̬
+ {
+ //ƴذ嵽
+ mcu_sendcmd2touch(0xf0|((touch_temp&0x0f)-1));
+ }
+ else
+ {
+ //ƴذ嵽
+ mcu_sendcmd2touch(0xe0|((touch_temp&0x0f)-1));
+ }
+ }
+ else//0 wifi
+ {
+ mcu_sendcmd2touch(0xea);
+ }
+
+ touch_flag&=0xfff0;
+ touch_flag|=(touch_temp&0x0f);//¼ƹλ
+ //
+ //0002
+ sendpack2server(0x0002);
+// dprintf("timer is complete %d\r\n",i);
+ }
+
+
+
+
+ }
+}
+
+//end bright.c
+
diff --git a/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/bright/bright.h b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/bright/bright.h
new file mode 100644
index 00000000..e8aa5cc3
--- /dev/null
+++ b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/bright/bright.h
@@ -0,0 +1,33 @@
+/*
+ * bright.h
+ *
+ * Created on: 2018524
+ * Author: Administrator
+ */
+
+#ifndef BRIGHT_BRIGHT_H_
+#define BRIGHT_BRIGHT_H_
+
+#include "app_config.h"
+#include "task_config.h"
+
+
+typedef enum
+{
+ LIGHT_SWITCH ,//лλ л
+ LIGHT_DIRECT ,//ֱӵijλ
+ LIGHT_AUTO ,
+ LIGHT_SLEEP ,
+
+}bright_mode_enum;
+
+extern uint8_t compare_set[9];
+void bright_mode(bright_mode_enum mode,uint8_t light);
+void bright_switch_process(uint8_t light);
+void bright_direct_process(uint8_t light);
+void bright_auto_process(uint8_t light);
+void period_Bright_Callback(TimerHandle_t xTimer);
+void brightchange_send2server_touch(uint32_t compare_temp);
+
+
+#endif /* BRIGHT_BRIGHT_H_ */
diff --git a/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/cm3232/cm3232.c b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/cm3232/cm3232.c
new file mode 100644
index 00000000..4b113119
--- /dev/null
+++ b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/cm3232/cm3232.c
@@ -0,0 +1,71 @@
+#include "cm3232.h"
+
+#include "i2c.h"
+
+//#include "comm.h"
+//#include "suart.h"
+#include "timer.h"
+//#include "touch.h"
+#include "stdlib.h"
+
+
+
+const uint8_t Slave_Address=0x10;
+const uint8_t Slave_Address_Write=0x20;
+const uint8_t Slave_Address_Read=0x21;
+
+uint16_t cm3232_time[2][3] = {0x00,0x04,0x08,100,200,400};
+void CM3232_Init(void)
+{
+ I2CC_Init();
+// CM3232_Write(0x00,0x08);//0x08-400ms 0x00-100ms 0x04-200ms
+ CM3232_Write(0x00,cm3232_time[0][CM3232_TIME]);
+}
+
+
+uint16_t CM3232_Read(uint8_t Command)
+{
+ uint8_t templ=0;
+ uint8_t temph=0;
+ uint16_t temp=0;
+ I2C_Start();
+ I2C_Send_Byte(Slave_Address_Write);
+ I2C_Wait_Ack();
+ I2C_Send_Byte(Command);
+ I2C_Wait_Ack();
+ I2C_Start();
+ I2C_Send_Byte(Slave_Address_Read);
+ I2C_Wait_Ack();
+ templ=I2C_Read_Byte(0);
+ temph=I2C_Read_Byte(1);
+ I2C_Stop();
+ temp=temph;
+ temp=(temp<<8)+templ;
+ return temp;
+}
+
+void CM3232_Write(uint8_t Command,uint8_t Data)
+{
+ I2C_Start();
+ I2C_Send_Byte(Slave_Address_Write);
+ I2C_Wait_Ack();
+ I2C_Send_Byte(Command);
+ I2C_Wait_Ack();
+ I2C_Send_Byte(Data);
+ I2C_Wait_Ack();
+ I2C_Stop();
+}
+
+uint16_t CM3232_Bright(uint8_t data)
+{
+ uint8_t t;
+ uint16_t temp=0;
+ for(t=0;t> 8) ^ m_CRC32Table[(nCRC32 & 0xFF) ^ pBuffer[i]];
+ }
+ nCRC32 ^= 0xFFFFFFFF;
+
+ return nCRC32;
+
+}
+
+
+
+
+
+
+
diff --git a/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/crc32/crc32.h b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/crc32/crc32.h
new file mode 100644
index 00000000..bd7db0cc
--- /dev/null
+++ b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/crc32/crc32.h
@@ -0,0 +1,22 @@
+/*
+ * crc32.h
+ *
+ * Created on: 201853
+ * Author: Administrator
+ */
+
+#ifndef CRC32_CRC32_H_
+#define CRC32_CRC32_H_
+
+#include "embARC.h"
+#include "embARC_debug.h"
+
+
+extern uint32_t Get_Crc32(uint8_t *pBuffer, uint16_t nBufLen);
+//void crc32_init(void);
+//u32 STM32_crc32_byte(u8 *pBuff, u32 len);
+//u32 stm32_crc32(u32 *pBuff, u32 len);
+//u32 crc32(u32 *ptr, u32 len);
+//u32 crc32_byte(u8 *ptr, u32 len);
+
+#endif /* CRC32_CRC32_H_ */
diff --git a/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/encrypt/encrypt.c b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/encrypt/encrypt.c
new file mode 100644
index 00000000..af21615c
--- /dev/null
+++ b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/encrypt/encrypt.c
@@ -0,0 +1,81 @@
+/*
+ * encrypt.c
+ *
+ * Created on: 201853
+ * Author: Administrator
+ */
+
+#include "encrypt.h"
+//
+#include "string.h"
+#include "stdlib.h"
+//#include "sys.h"
+
+
+
+//device_idܷʽ
+//32λkey4ֽڵdevice id
+int key = 0x0F123A67;
+//64λkey,յ8ֽ
+long long key64 = 0xA00FAB123AABFF78;
+
+//a???????(???????????,?????) ;CD 47 F1 63
+//b???????,????;
+//c?????????,?????K???bin??,????
+//d????K???CRC32??, ?????????;
+//e??? FE 58 DC 56
+
+int key_result = 0x0E692d32;
+
+//
+int decrypt(long long data)
+{
+ long long l = data ^ key64;
+ int deviceId = (int)l;
+
+// printf("orignal device id: %d\n", deviceId);
+ int enc = (int)(l >> 32);
+ int dec =enc ^ key_result;
+// printf("ܺdecrypted device id: %d\n", dec);
+ if(dec == deviceId)
+ {
+
+// printf("compare sucess\n");
+ return dec;
+ }
+ else
+
+ return -1;//ʧ
+}
+
+
+/*
+long long encrypt(int deviceId)
+{
+ long long ret = deviceId;
+ long long enc = deviceId ^ key;
+
+ return ((ret |= (enc<<32)) ^ key64);
+}
+*/
+void device_id_encrypt(uint32_t deviceId,uint8_t*result)
+{
+
+ long long ret = deviceId;
+ long long enc = deviceId ^ key;
+ long long temp;
+
+ uint8_t i;
+
+ temp=((ret |= (enc<<32)) ^ key64);
+
+ for(i=0;i<8;i++)
+ {
+ *( result +i)=(uint8_t)(temp>>((7-i)*8));
+
+ }
+
+}
+
+//end encrpyt.c
+
diff --git a/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/encrypt/encrypt.h b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/encrypt/encrypt.h
new file mode 100644
index 00000000..5431f023
--- /dev/null
+++ b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/encrypt/encrypt.h
@@ -0,0 +1,14 @@
+/*
+ * encrypt.h
+ *
+ * Created on: 201853
+ * Author: Administrator
+ */
+
+#ifndef ENCRYPT_ENCRYPT_H_
+#define ENCRYPT_ENCRYPT_H_
+#include "stdint.h"
+
+void device_id_encrypt(uint32_t deviceId,uint8_t*result);
+
+#endif /* ENCRYPT_ENCRYPT_H_ */
diff --git a/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/fifo/fifo.c b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/fifo/fifo.c
new file mode 100644
index 00000000..3ee753f2
--- /dev/null
+++ b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/fifo/fifo.c
@@ -0,0 +1,78 @@
+/*
+ * fifo.c
+ *
+ * Created on: 2018517
+ * Author: Administrator
+ */
+
+#include "fifo.h"
+
+
+
+//fifoʼ
+void init_fifo(fifo_struct*fifo2init,uint16_t totallen,uint8_t*fifo_data)
+{
+ fifo2init->total_len = totallen;
+ fifo2init->pstr = fifo_data;
+
+ reset_fifo(fifo2init);
+}
+
+//дݵFIFOУģʽݻḲδľ
+uint8_t write_fifo(fifo_struct*fifo2write,uint8_t*byte,uint16_t len)
+{
+ uint16_t i;
+ for(i=0;ipstr[fifo2write->write_pos] = *(byte+i);
+ if(++fifo2write->write_pos>=fifo2write->total_len)
+ {
+ fifo2write->write_pos = 0;
+ }
+ if(fifo2write->now_len < fifo2write->total_len)
+ {
+ fifo2write->now_len++;
+ }
+ }
+ if(fifo2write->now_len == fifo2write->total_len) return 0;//
+ else return 1;
+
+}
+//ȡFIFO
+uint8_t read_fifo(fifo_struct*fifo2read,uint8_t*byte,uint16_t len)
+{
+ uint16_t i;
+ for(i=0;inow_len)
+ {
+ *(byte+i) = fifo2read->pstr[fifo2read->read_pos];
+ if(++fifo2read->read_pos>=fifo2read->total_len)
+ {
+ fifo2read->read_pos = 0;
+ }
+ fifo2read->now_len--;
+ }
+ else
+ {
+ break;
+ }
+ }
+ if(i>=len) return 1;
+ else return 0;//ȡݳFIFOݸ
+
+}
+
+//fifo
+void reset_fifo(fifo_struct*fifo2clear)
+{
+ fifo2clear->now_len = 0;
+ fifo2clear->read_pos= 0;
+ fifo2clear->write_pos=0;
+
+}
+
+
+
+//end fifo.c
+
diff --git a/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/fifo/fifo.h b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/fifo/fifo.h
new file mode 100644
index 00000000..d095e044
--- /dev/null
+++ b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/fifo/fifo.h
@@ -0,0 +1,21 @@
+/*
+ * fifo.h
+ *
+ * Created on: 2018517
+ * Author: Administrator
+ */
+
+#ifndef FIFO_FIFO_H_
+#define FIFO_FIFO_H_
+
+#include "stdio.h"
+
+#include "app_config.h"
+
+void init_fifo(fifo_struct*fifo2init,uint16_t totallen,uint8_t*fifo_data);
+uint8_t write_fifo(fifo_struct*fifo2write,uint8_t*byte,uint16_t len);
+uint8_t read_fifo(fifo_struct*fifo2read,uint8_t*byte,uint16_t len);
+void reset_fifo(fifo_struct*fifo2clear);
+
+
+#endif /* FIFO_FIFO_H_ */
diff --git a/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/initsys/initsys.c b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/initsys/initsys.c
new file mode 100644
index 00000000..951dbae3
--- /dev/null
+++ b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/initsys/initsys.c
@@ -0,0 +1,129 @@
+/*
+ * initsys.c
+ *
+ * Created on: 201854
+ * Author: Administrator
+ */
+
+#include "initsys.h"
+//
+#include "string.h"
+#include "stdlib.h"
+
+#include "malloc.h"
+#include "timer.h"
+
+#include "usart3task.h"
+#include "usart1task.h"//printf
+#include "encrypt.h"
+
+#include "task_config.h"
+
+//ض
+uint8_t DEVICE_ID[8];
+SYS_CONFIG sys_config;
+
+
+void init_system(void)
+{
+ sys_config_init();
+ default_sys_config();//ʱʹãʵʴflashȡ
+ ALL_TIM_init();
+ set_rtc_sec(0);//ʼrtcʱ
+ device_id_encrypt(sys_config.device_id,DEVICE_ID);
+}
+
+void default_sys_config(void)
+{
+ uint8_t i;
+
+ sys_config.pkt_version = 0x00010000;
+
+ //̨־λ
+ sys_config.boot_flag = 0x66;//ҪbootMCUʱı־λMCU
+ //Ƿʼflash
+ sys_config .flash_init = 0x55;
+
+ //ħص
+ //MP3ĸ
+ //̨ư汾 ID
+ sys_config .device_id =1000000+8; //Ĭid flashв +5 MP3
+
+ sys_config.LAMP_MODEL[0]=0X00; //̨ͺ
+ sys_config.LAMP_MODEL[1]=0X00;
+ sys_config.LAMP_MODEL[2]=0X00;
+ sys_config.LAMP_MODEL[3]=0X01;
+
+ sys_config.LAMP_HV[0] =0x00; //̨Ӳ汾
+ sys_config.LAMP_HV[1] =0x00;
+ sys_config.LAMP_HV[2] =0x01;
+ sys_config.LAMP_HV[3] =0x00;
+
+ sys_config. LAMP_SV[0]=0x08; //̨汾
+ sys_config. LAMP_SV[1]=0x00;
+ sys_config. LAMP_SV[2]=0x01;
+ sys_config. LAMP_SV[3]=0x00;
+
+ sys_config. M_SERIAL[0]=0X00; //ħк
+ sys_config. M_SERIAL[1]=0X00;
+ sys_config. M_SERIAL[2]=0X00;
+ sys_config. M_SERIAL[3]=0X00;
+ sys_config. M_SERIAL[4]=0X03;
+ sys_config. M_SERIAL[5]=0X00;
+ sys_config. M_SERIAL[6]=0X00;
+ sys_config. M_SERIAL[7]=0X00;
+
+ sys_config. S_HW[0]=0x00; //ħӲ汾
+ sys_config. S_HW[1]=0x00;
+ sys_config. S_HW[2]=0x01;
+ sys_config. S_HW[3]=0x00;
+
+ sys_config. S_SW[0]=0x00; //ħ汾
+ sys_config. S_SW[1]=0x08;
+ sys_config. S_SW[2]=0x00;
+ sys_config. S_SW[3]=0x00;
+
+ sys_config. S_SERIAL[0]=0X87; //ħк
+ sys_config. S_SERIAL[1]=0X65;
+ sys_config. S_SERIAL[2]=0X43;
+ sys_config. S_SERIAL[3]=0X21;
+ sys_config. S_SERIAL[4]=0X0F;
+ sys_config. S_SERIAL[5]=0XED;
+ sys_config. S_SERIAL[6]=0XCB;
+ sys_config. S_SERIAL[7]=0XA9;
+
+ sys_config.WIFI_SW [0]=0x08;//wifi汾
+ sys_config.WIFI_SW [1]=0x00;
+ sys_config.WIFI_SW [2]=0x01;
+ sys_config.WIFI_SW [3]=0x00;
+
+ //̨ƵıǶʱ
+ sys_config .ANGLE_ALARM1 =20; //ǰ Ĭ20
+ sys_config .ANGLE_ALARM2 =30; // Ĭ30
+ sys_config .ALERT_TIME1 =5 ; //״αʱ䣬Ĭ5s
+ sys_config .ALERT_TIME2 =180;//ظ
+ sys_config .MUTE_START =0; //ĬϾʼʱ0:00
+ sys_config .MUTE_END =420;//ĬϾʱ7:00
+ sys_config .SLEEP_START =0; //ĬϾʼʱ0:00
+ sys_config .SLEEP_END =1440;//ĬϾʱ24:00
+
+ //MP3 IDʼ
+ for(i=0;i<80;i++)
+ {
+ sys_config.MP3_ID[i]=0;
+ }
+ sys_config.MP3_STA=1;
+
+// write_sys_config();
+}
+
+void sys_config_init(void)
+{
+ #if 1
+ default_sys_config();//ʱʹãʵʴflashȡ
+ #else
+ //ʵʹôflashȡ
+ #endif
+}
+//end initsys.c
+
diff --git a/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/initsys/initsys.h b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/initsys/initsys.h
new file mode 100644
index 00000000..fc97fbdd
--- /dev/null
+++ b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/initsys/initsys.h
@@ -0,0 +1,26 @@
+/*
+ * initsys.h
+ *
+ * Created on: 201854
+ * Author: Administrator
+ */
+
+#ifndef INITSYS_INITSYS_H_
+#define INITSYS_INITSYS_H_
+
+#include "app_config.h"
+
+#include "FreeRTOS.h" //FreeRTOSʹ
+#include "task.h"
+#include "queue.h"
+#include "semphr.h"
+#include "timers.h"
+
+extern uint8_t DEVICE_ID[8];
+
+void init_system(void);
+void sys_config_init(void);
+void default_sys_config(void);
+
+
+#endif /* INITSYS_INITSYS_H_ */
diff --git a/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/irf/irf.c b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/irf/irf.c
new file mode 100644
index 00000000..20880f84
--- /dev/null
+++ b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/irf/irf.c
@@ -0,0 +1,939 @@
+/*
+ * irf.c
+ *
+ * Created on: 2018527
+ * Author: Administrator
+ */
+
+#include "bright.h"
+#include "irf.h"
+#include "package.h"
+#include "usart4task.h"
+#include "app_config.h"
+#include "task_config.h"
+//
+#include "string.h"
+#include "stdlib.h"
+//#include "sys.h"
+#include "timer.h"
+
+#include "embARC.h"
+
+TaskHandle_t IRF_app_Handler;//
+TaskHandle_t MP3_TASK_Handler;//
+QueueHandle_t SuperSound_Queue;//MP3
+
+#define adc_delay() delay_us(1)
+
+#define EMSK_IRF_PORT DEV_GPIO_PORT_A
+#define GPIO_IRF_MASK 0x00080000 //portA19PinJ310
+#define EMSK_GPIO_CHECK_EXP_NORTN(EXPR) CHECK_EXP_NOERCD(EXPR, error_exit)
+DEV_GPIO * irf;
+DEV_GPIO * svs1;
+DEV_GPIO * adc;
+DEV_GPIO * mp3;
+//sound
+supersound_struct supersound_ctr1;
+
+//mp3
+
+#define EMSK_GPIOMP3_PORT DEV_GPIO_PORT_A
+#define GPIO_GPIOMP3_MASK 0X0000F000 //portA20-21PinJ47-8
+#define GPIO_GPIOMP3_LOW (0)
+#define GPIO_GPIOMP3_HIGH (1)
+#define GPIO_MP3_MASK1 0X00001000 //portA12PinJ27
+#define GPIO_MP3_MASK2 0X00002000 //portA13PinJ28
+#define GPIO_MP3_MASK3 0X00004000 //portA14PinJ29
+#define GPIO_MP3_MASK4 0X00008000 //portA15PinJ210
+
+//irf
+STUDY_STRUCT study_ctr;
+
+unsigned long ch1_temp[11],ch2_temp[11];
+
+void mp3_init(void)
+{
+ io_pmod_config(2,0,0); //ʼPMOD2ãʹPMOD2ӳ䵽AC
+ mp3 = gpio_get_dev(EMSK_GPIOMP3_PORT);
+ EMSK_GPIO_CHECK_EXP_NORTN(mp3 != NULL);
+ if (adc->gpio_open(GPIO_GPIOMP3_MASK) == E_OPNED)
+ {
+ adc->gpio_control(GPIO_CMD_SET_BIT_DIR_OUTPUT, (void *)(GPIO_MP3_MASK1)); //SCL OUT
+ adc->gpio_control(GPIO_CMD_SET_BIT_DIR_OUTPUT, (void *)(GPIO_MP3_MASK2)); //DI out
+ adc->gpio_control(GPIO_CMD_SET_BIT_DIR_OUTPUT, (void *)(GPIO_MP3_MASK3)); //DO in
+ adc->gpio_control(GPIO_CMD_SET_BIT_DIR_OUTPUT, (void *)(GPIO_MP3_MASK4)); //DRY IN
+ adc->gpio_control(GPIO_CMD_DIS_BIT_INT, (void *)(GPIO_GPIOMP3_MASK));
+ }
+ mp3->gpio_write((GPIO_GPIOMP3_MASK),GPIO_GPIOMP3_MASK);
+ error_exit:
+ return;
+}
+
+
+
+void mp3_play_in(uint8_t mp3_num)
+{
+ switch(mp3_num)
+ {
+ case 1:
+ mp3->gpio_write((~GPIO_MP3_MASK1),GPIO_MP3_MASK1);
+ vTaskDelay(200);
+ mp3->gpio_write((GPIO_MP3_MASK1),GPIO_MP3_MASK1);
+ break;
+ case 2:
+ mp3->gpio_write((~GPIO_MP3_MASK2),GPIO_MP3_MASK2);
+ vTaskDelay(200);
+ mp3->gpio_write((GPIO_MP3_MASK2),GPIO_MP3_MASK2);
+ break;
+ case 3:
+ mp3->gpio_write((~GPIO_MP3_MASK3),GPIO_MP3_MASK3);
+ vTaskDelay(200);
+ mp3->gpio_write((GPIO_MP3_MASK3),GPIO_MP3_MASK3);
+ break;
+ case 4:
+ mp3->gpio_write((~GPIO_MP3_MASK4),GPIO_MP3_MASK4);
+ vTaskDelay(200);
+ mp3->gpio_write((GPIO_MP3_MASK4),GPIO_MP3_MASK4);
+ break;
+ }
+}
+
+void mp3_play(uint8_t mp3_num)
+{
+#if 0
+ mp3_play_in(mp3_num);
+#else
+
+ xQueueSend(SuperSound_Queue,&mp3_num,10);
+#endif
+}
+
+void MP3_task(void *pvParameters)
+{
+ uint8_t mp3_temp;
+ while(1)
+ {
+ if(xQueueReceive(SuperSound_Queue,&mp3_temp,0))
+ {
+ mp3_play_in(mp3_temp);
+// dprintf("mp3 task %d\r\n",mp3_temp);
+ vTaskDelay(3000);
+ }
+ else
+ {
+ vTaskDelay(MP3_TASK_delay);
+ }
+ }
+}
+
+
+//adc
+void supersound_ctr_init(supersound_struct*ctr)
+{
+ ctr->tim_start = 0;
+ ctr->tim_stop = 0;
+ ctr->flag = SOUND_FLAG_IDEL;
+ ctr->count = 0;
+ ctr->tim_result = 0;
+ ctr->tim_ctr_start = 0;
+ ctr->tim_ctr_stop = 0;
+}
+void study_ctr_init(void)
+{
+ study_ctr.up = 3100;
+ study_ctr.forward = 2600;
+ study_ctr.noperson = 3800;
+// study_ctr.nearby = 0;
+ study_ctr.ch1 = 0;//up
+ study_ctr.ch2 = 0;//forward
+ study_ctr.startstudy=0;
+ study_ctr.time = 0;
+ study_ctr.flag = 0;
+ study_ctr.timeflag = 0;
+}
+//忿 PB5
+void irf_init(void)
+{
+#if 0
+ irf = gpio_get_dev(EMSK_IRF_PORT);
+ if (irf->gpio_open(GPIO_IRF_MASK) == E_OPNED)
+ {
+ irf->gpio_control(GPIO_CMD_SET_BIT_DIR_INPUT, (void *)(GPIO_IRF_MASK));
+ irf->gpio_control(GPIO_CMD_DIS_BIT_INT, (void *)(GPIO_IRF_MASK));
+ }
+ irf->gpio_write(GPIO_IRF_MASK,GPIO_IRF_MASK);
+#endif
+
+#if 0
+ //ʼ
+ supersound_ctr_init(&supersound_ctr1);
+ //ioʼ
+ supersound_IOinit_1();
+#endif
+#if 1//adc
+ study_ctr_init();
+ adc_io_init();
+ //MP3 IO ʼ
+ mp3_init();
+#endif
+
+}
+
+//**صһٴδIRF
+#define IRF_TRI_LEVEL 2*5//2S
+
+//80Ƿʼ˴ڽ
+void IRF_app_task(void *pvParameters)
+{
+// uint32_t io_temp;//
+ TickType_t xLastWakeTime;
+ uint8_t adc_count=0;
+ uint8_t irf_flag = 0;
+ uint8_t irf_noflag = 0;
+ uint8_t study_error = 0;
+ /* ȡǰϵͳʱ */
+ xLastWakeTime = xTaskGetTickCount();
+ dprintf("IRF start\r\n");
+// vTaskDelay(2000);
+ while(1)
+ {
+#if 0
+ irf->gpio_read(&io_temp,GPIO_IRF_MASK);
+// io_temp = IRF_IN1;
+
+ if(!(touch_flag&(0x0001<<10)))//ûΪ
+ {
+ if(touch_flag&(0x0001<<7))//ǰǿ
+ {
+ if(io_temp)//뿪
+ {
+ irf_flag++;
+ if((irf_flag&0x7f)>IRF_TRI_LEVEL)
+ {
+ irf_flag = 0;
+ mcu_sendcmd2touch(Power_Off);
+ touch_process_poweroff();//ص
+ touch_flag&=(~(0x0001<<10));//¼
+ }
+ }
+ else
+ {
+ irf_flag = 0;
+ }
+ }
+ else//ǰǹص
+ {
+ if(!io_temp)//˿
+ {
+ irf_flag++;
+ if((irf_flag&0x7f)>IRF_TRI_LEVEL)
+ {
+ irf_flag = 0;
+ mcu_sendcmd2touch( Power_On);
+ touch_process_poweron();//
+ touch_flag&=(~(0x0001<<10));//¼
+ }
+ }
+ else
+ {
+ irf_flag = 0;
+ }
+ }
+ }
+ else
+ {
+ if(!(touch_flag&(0x0001<<7)))//ǰǹص
+ {
+// irf_flag++;
+// if((irf_flag&0x7f)>IRF_TRI_LEVEL*2)//Ϊ6s,ҹصƺٴδIRF
+// {
+// touch_flag&=(~(0x0001<<10));//¼
+// }
+ if(io_temp)//뿪
+ {
+ touch_flag&=(~(0x0001<<10));//¼
+ }
+ }
+ else
+ {
+ irf_flag = 0;
+ }
+ }
+
+
+#endif
+ //sound
+#if 0
+ switch(supersound_ctr1.flag)
+ {
+ case SOUND_FLAG_IDEL://
+ if((supersound_ctr1.count++)%10==0)//10*100msһ
+ {
+ supersound_tri_start_process_1();
+ }
+ break;
+
+ case SOUND_FLAG_TRI_START:
+ supersound_measure_falied_1();
+// printf("SOUND_FLAG_TRI_START\r\n");
+ break;
+ case SOUND_FLAG_PEDG_START://ûյ
+ supersound_measure_falied_1();
+// printf("SOUND_FLAG_PEDG_START\r\n");
+ break;
+
+ case SOUND_FLAG_NEDG_STOP://ɲ
+ supersound_measure_done_1();
+ break;
+ default:break;
+ }
+#endif
+#if 0//sound
+ if((supersound_ctr1.count++)%5==0)//10*100msһ
+ {
+ supersound_ctr1.count = 1;
+ supersound_tri_start_process_1();
+ vTaskSuspendAll();
+// taskENTER_CRITICAL();
+ while(1)
+ {
+ if(supersound_ctr1.flag==SOUND_FLAG_TRI_START)
+ {
+ if(supersound_echo_read_1())
+ {
+ supersound_ctr1.flag=SOUND_FLAG_PEDG_START;
+ supersound_ctr1.tim_start = board_get_cur_us();
+ }
+ }
+ else if(supersound_ctr1.flag==SOUND_FLAG_PEDG_START)
+ {
+ if(!supersound_echo_read_1())
+ {
+ supersound_ctr1.flag=SOUND_FLAG_NEDG_STOP;
+ supersound_ctr1.tim_stop = board_get_cur_us();
+
+ //done
+ supersound_measure_done_1();
+ break;
+
+ }
+ }
+
+ if(supersound_ctr1.flag!=SOUND_FLAG_NEDG_STOP)
+ {
+ supersound_ctr1.tim_ctr_stop = board_get_cur_us();
+ if(
+ ((supersound_ctr1.tim_ctr_stop-supersound_ctr1.tim_ctr_start)>8000))
+ {
+ supersound_measure_falied_1();
+ break;
+ }
+ }
+
+
+
+ }
+ xTaskResumeAll();
+// taskEXIT_CRITICAL();
+// printf("sound: %d\r\n",supersound_ctr1.tim_result);
+#if 1
+ if(supersound_ctr1.flag==SOUND_FLAG_NEDG_STOP)
+ {
+ /*
+ char say_str_temp[30];
+ sprintf(say_str_temp,"ss=%d",supersound_ctr1.tim_result);
+ say2server(say_did,say_str_temp);
+ */
+
+ xQueueSend(SuperSound_Queue,&(supersound_ctr1.tim_result),10);
+// printf("sound %d\r\n",supersound_ctr1.tim_result);
+ }
+
+#endif
+
+ }
+#endif
+#if 0//adc
+// adc_count++;
+// delay_us(300);
+// dprintf("%d",adc_count);
+// vTaskSuspendAll();
+ if(++adc_count%10==0)
+ {
+#if 0
+ if(adc_count%20==0)
+ {
+ adc_count=0;
+ dprintf("ch2=%d\r\n",ReadData2_7705());
+ }
+ else if(adc_count==10)
+ {
+ dprintf("ch1=%d\r\n",ReadData1_7705());
+ }
+#else
+ adc_count=0;
+// vTaskDelay(400);
+ study_ctr.ch1 = ReadData1_7705();
+ vTaskDelay(100);
+ study_ctr.ch2 = ReadData2_7705();
+ printf("ch1=%d ",study_ctr.ch1);
+ printf("ch2=%d\r\n",study_ctr.ch2);
+#endif
+
+ }
+// xTaskResumeAll();
+
+
+#endif
+ if(!study_ctr.startstudy)
+ {
+ study_ctr.timeflag=0;
+ study_ctr.time = 0;
+ }
+
+ if(study_ctr.startstudy||!(touch_flag&(0x0001<<7)))
+ {
+#if 1//study
+
+ study_ctr.ch1 = ReadData1_7705();
+ vTaskDelay(100);
+ study_ctr.ch2 = ReadData2_7705();
+
+
+ ch1_temp[adc_count] = study_ctr.ch1;
+ ch2_temp[adc_count] = study_ctr.ch2;
+ if(++adc_count>10)
+ {
+#if 1
+ dprintf("ch1:");
+ for(adc_count = 0;adc_count<11;adc_count++)
+ {
+ dprintf("%d\t",ch1_temp[adc_count]);
+ }
+ dprintf("\r\n");
+ dprintf("ch2:");
+ for(adc_count = 0;adc_count<11;adc_count++)
+ {
+ dprintf("%d\t",ch2_temp[adc_count]);
+ }
+ dprintf("\r\n");
+#else
+ printf("ch1=%d\tch2=%d\r\n",study_ctr.ch1 ,study_ctr.ch2);
+#endif
+ adc_count=0;
+ }
+ if(study_ctr.startstudy&&(touch_flag&(0x0001<<7)))
+ {
+// dprintf("test 01\r\n");
+// touch_flag|=(0x0001<<10);
+ if(study_check(1)==STUDY_FLAG_FORWARD)//
+ {
+// dprintf("test 02\r\n");
+ study_error++;
+ irf_noflag=0;
+// dprintf("irf_flag %d\r\n",study_error);
+ if(study_error>10)//IRF_TRI_LEVEL)
+ {
+// dprintf("test 03\r\n");
+ study_error = 0;
+ study_ctr.flag = 1;
+ study_ctr.time_pre = get_rtc_sec();
+ dprintf("study error\r\n");
+ mp3_play(2);
+
+ }
+ }
+ else
+ {
+ if(study_ctr.timeflag==0)
+ {
+ study_ctr.time = get_rtc_sec();
+ study_ctr.timeflag = 1;
+ }
+
+ if(get_rtc_sec()-study_ctr.time_pre==6) study_ctr.flag = 0;
+
+
+// dprintf("test 04\r\n");
+ irf_noflag++;
+ if(irf_noflag>3)
+ {
+ irf_noflag = 0;
+ study_error = 0;
+ }
+ }
+
+ if((study_ctr.timeflag)&&((get_rtc_sec()-study_ctr.time)>50)&&!((get_rtc_sec()-study_ctr.time)%60))
+ {
+ mp3_play(3);//Ϣ
+ dprintf("study time 60\r\n");
+ vTaskDelay(1000);
+ }
+
+ }
+
+#endif
+
+#if 1//
+
+ //adc жǷ̨Ƹ пƺԶص
+
+
+ if(!(touch_flag&(0x0001<<10)))//ûΪ
+ {
+ if(touch_flag&(0x0001<<7))//ǰǿ
+ {
+ if(study_check(0)==STUDY_FLAG_NOPERSON)//뿪
+ {
+ irf_flag++;
+ if((irf_flag&0x7f)>IRF_TRI_LEVEL)
+ {
+ irf_flag = 0;
+ mcu_sendcmd2touch(Power_Off);
+ touch_process_poweroff();//ص
+ touch_flag&=(~(0x0001<<10));//¼
+ }
+ }
+ else
+ {
+ irf_flag = 0;
+ }
+ }
+ else//ǰǹص
+ {
+ if(study_check(0)==STUDY_FLAG_PERSON)//˿
+ {
+ irf_flag++;
+ if((irf_flag&0x7f)>IRF_TRI_LEVEL)
+ {
+ irf_flag = 0;
+ server_control_light(0x28);
+ mp3_play(1);//ӭʹ
+ study_ctr.startstudy = 1;
+// mcu_sendcmd2touch( Power_On);
+// touch_process_poweron();//
+ touch_flag&=(~(0x0001<<10));//¼
+ }
+ }
+ else
+ {
+ irf_flag = 0;
+ }
+ }
+ }
+ else//Ϊˣʼѧϰģʽ
+ {
+ if(!(touch_flag&(0x0001<<7)))//ǰǹص
+ {
+// irf_flag++;
+// if((irf_flag&0x7f)>IRF_TRI_LEVEL*2)//Ϊ6s,ҹصƺٴδIRF
+// {
+// touch_flag&=(~(0x0001<<10));//¼
+// }
+ if(study_check(0)==STUDY_FLAG_NOPERSON)//뿪
+ {
+ touch_flag&=(~(0x0001<<10));//¼
+ }
+ }
+ else
+ {
+ irf_flag = 0;
+ }
+ }
+#endif
+ }
+ else
+ {
+ study_ctr.time = 0;
+ study_ctr.timeflag=0;
+
+ }
+
+// printf("100ms = %d\r\n",board_get_cur_us());
+ vTaskDelayUntil(&xLastWakeTime, 200);
+// vTaskDelay(200);//100msһΣ̫Ƶ
+ }
+
+}
+
+#if 0
+//
+void supersound_exit_IRQHandler_1(void *ptr)
+{
+// printf("i'm coming in\r\n");
+ if(supersound_ctr1.flag==SOUND_FLAG_TRI_START)
+ {
+ supersound_ctr1.flag=SOUND_FLAG_PEDG_START;
+ supersound_ctr1.tim_start = board_get_cur_us();
+ supersound_exit_config_1(0);
+ }
+ else if(supersound_ctr1.flag==SOUND_FLAG_PEDG_START)
+ {
+ supersound_ctr1.flag=SOUND_FLAG_NEDG_STOP;
+ supersound_ctr1.tim_stop = board_get_cur_us();
+ supersound_exit_config_1(1);
+ }
+}
+
+void supersound_tri_start_process_1(void)
+{
+
+ supersound_ctr1.tim_start = 0;
+ supersound_ctr1.tim_stop = 0;
+ supersound_ctr1.flag=SOUND_FLAG_TRI_START;
+ supersound_tri_config_1(1);
+ vTaskDelay(1);
+ supersound_tri_config_1(0);
+#if 0
+ supersound_exit_config_1(1);
+#else
+ supersound_ctr1.tim_ctr_start = board_get_cur_us();//Ʋʱ
+#endif
+
+}
+
+
+
+void supersound_measure_done_1(void)
+{
+// supersound_measure_falied_1();
+ if(supersound_ctr1.tim_stop>supersound_ctr1.tim_start)
+ {
+ supersound_ctr1.tim_result=supersound_ctr1.tim_stop-supersound_ctr1.tim_start;
+// printf("sound %d\r\n",supersound_ctr1.tim_result);
+ }
+// else
+// {
+// supersound_ctr1.tim_result=supersound_ctr1.tim_stop+(0xffffffffffffffff-supersound_ctr1.tim_start);
+// printf("sound %d\r\n",supersound_ctr1.tim_result);
+// }
+}
+
+void supersound_measure_falied_1(void)
+{
+ supersound_ctr1.flag=SOUND_FLAG_IDEL;
+ supersound_ctr1.count = 1;
+
+ //رⲿж
+
+}
+#endif
+
+#define EMSK_GPIOADC_PORT DEV_GPIO_PORT_A
+#define GPIO_GPIOADC_MASK 0X00F00000 //portA20-21PinJ47-8
+#define GPIO_GPIOADC_LOW (0)
+#define GPIO_GPIOADC_HIGH (1)
+#define GPIO_SCL_MASK 0X00100000 //portA20PinJ47
+#define GPIO_DI_MASK 0X00200000 //portA21PinJ48
+#define GPIO_DO_MASK 0X00400000 //portA22PinJ49
+#define GPIO_DRY_MASK 0X00800000 //portA23PinJ410
+
+
+//DEV_GPIO_BIT_ISR bit_svs1_isr;
+//DEV_GPIO_INT_CFG int_svs1_cfg;
+
+//IO init
+void adc_io_init(void)
+{
+ io_pmod_config(4,0,0); //ʼPMOD4ãʹPMOD4ӳ䵽AC
+ adc = gpio_get_dev(EMSK_GPIOADC_PORT);
+ EMSK_GPIO_CHECK_EXP_NORTN(adc != NULL);
+ if (adc->gpio_open(GPIO_GPIOADC_MASK) == E_OPNED)
+ {
+ adc->gpio_control(GPIO_CMD_SET_BIT_DIR_OUTPUT, (void *)(GPIO_SCL_MASK)); //SCL OUT
+ adc->gpio_control(GPIO_CMD_SET_BIT_DIR_OUTPUT, (void *)(GPIO_DI_MASK)); //DI out
+ adc->gpio_control(GPIO_CMD_SET_BIT_DIR_INPUT, (void *)(GPIO_DO_MASK)); //DO in
+ adc->gpio_control(GPIO_CMD_SET_BIT_DIR_INPUT, (void *)(GPIO_DRY_MASK)); //DRY IN
+ adc->gpio_control(GPIO_CMD_DIS_BIT_INT, (void *)(GPIO_GPIOADC_MASK));
+ }
+ error_exit:
+ return;
+
+
+}
+
+#if 0
+void supersound_IOinit_1(void)
+{
+ io_pmod_config(4,0,0);
+
+ svs1 = gpio_get_dev(EMSK_GPIOSVS1_PORT);
+
+EMSK_GPIO_CHECK_EXP_NORTN(svs1 != NULL);
+if (svs1->gpio_open(GPIO_SVS1_MASK) == E_OPNED) {
+ svs1->gpio_control(GPIO_CMD_SET_BIT_DIR_OUTPUT, (void *)(GPIO_SVS1OUT_MASK));
+ svs1->gpio_control(GPIO_CMD_SET_BIT_DIR_INPUT, (void *)(GPIO_SVS1IN_MASK));
+ svs1->gpio_control(GPIO_CMD_DIS_BIT_INT, (void *)(GPIO_SVS1_MASK));
+}
+int_svs1_cfg.int_bit_mask = GPIO_SVS1IN_MASK;
+int_svs1_cfg.int_bit_type = GPIO_SVS1IN_MASK;
+int_svs1_cfg.int_bit_polarity = GPIO_SVS1IN_MASK;//
+int_svs1_cfg.int_bit_debounce = (~GPIO_SVS1IN_MASK);
+svs1->gpio_control(GPIO_CMD_SET_BIT_INT_CFG, &int_svs1_cfg);
+bit_svs1_isr.int_bit_ofs = 20;
+bit_svs1_isr.int_bit_handler = supersound_exit_IRQHandler_1;
+svs1->gpio_control(GPIO_CMD_SET_BIT_ISR, &bit_svs1_isr);
+//svs1->gpio_control(GPIO_CMD_ENA_BIT_INT, (void *)GPIO_SVS1IN_MASK); //ʹ
+svs1->gpio_write((~GPIO_SVS1OUT_MASK),GPIO_SVS1OUT_MASK);//Ĭϵ͵ƽ
+int_pri_set(INTNO_GPIO, 30);
+error_exit:
+return;
+ //tri ΪIO Ĭϵ͵ƽ
+
+ //exit ΪⲿжϣΪش ʹ
+
+}
+
+//ȡechoֵΪ1 Ϊ0
+uint8_t supersound_echo_read_1(void)
+{
+ uint32_t temp_svs1;
+ svs1->gpio_read(&temp_svs1, GPIO_SVS1IN_MASK);
+ temp_svs1 = temp_svs1 & GPIO_SVS1IN_MASK;
+ temp_svs1 = temp_svs1 >> 20;
+ return (uint8_t)temp_svs1;
+}
+
+void supersound_exit_config_1(uint8_t edg)
+{
+#if 1
+ svs1->gpio_control(GPIO_CMD_DIS_BIT_INT, (void *)GPIO_SVS1IN_MASK);//ʧ
+
+ if(edg)//
+ {
+ int_svs1_cfg.int_bit_mask = GPIO_SVS1IN_MASK;
+ int_svs1_cfg.int_bit_type = GPIO_SVS1IN_MASK;
+ int_svs1_cfg.int_bit_polarity = GPIO_SVS1IN_MASK;//
+ int_svs1_cfg.int_bit_debounce = (~GPIO_SVS1IN_MASK);
+ svs1->gpio_control(GPIO_CMD_SET_BIT_INT_CFG, &int_svs1_cfg);
+ }
+ else//½
+ {
+ int_svs1_cfg.int_bit_mask = GPIO_SVS1IN_MASK;
+ int_svs1_cfg.int_bit_type = GPIO_SVS1IN_MASK;
+ int_svs1_cfg.int_bit_polarity = 0;//½
+ int_svs1_cfg.int_bit_debounce = (~GPIO_SVS1IN_MASK);
+ svs1->gpio_control(GPIO_CMD_SET_BIT_INT_CFG, &int_svs1_cfg);
+ }
+
+ svs1->gpio_control(GPIO_CMD_ENA_BIT_INT, (void *)GPIO_SVS1IN_MASK);//ʹ
+#endif
+}
+
+void supersound_tri_config_1(uint8_t level)
+{
+#if 1
+ if(level)//ߵƽ
+ {
+ svs1->gpio_write(GPIO_SVS1OUT_MASK,GPIO_SVS1OUT_MASK);
+ }
+ else//͵ƽ
+ {
+ svs1->gpio_write((~GPIO_SVS1OUT_MASK),GPIO_SVS1OUT_MASK);
+ }
+#endif
+}
+#endif
+//adc
+
+/******AD7705дһֽ******/
+void WriteByte7705(uint8_t dat)
+{
+ uint8_t i;
+ for (i=0; i<8; i++)
+ {
+ adc_io_process(ADC_IO_SCL,0);
+ adc_delay();
+ if(dat & 0x80)
+ {adc_io_process(ADC_IO_DI,1);}
+ else
+ adc_io_process(ADC_IO_DI,0);
+ adc_delay();
+ adc_io_process(ADC_IO_SCL,1);
+ adc_delay();
+ dat=dat<<1;
+ }
+}
+/****** AD7705һֽ ******/
+unsigned long ReadWord7705()
+{
+ unsigned long read_dat=0;
+ unsigned char i;
+ for(i=0;i<16;i++)
+ {
+ read_dat=read_dat<<1;
+ adc_io_process(ADC_IO_SCL,0);
+ adc_delay();
+ if(adc_io_process(ADC_IO_DO,0)==1)
+ {read_dat++;}
+ adc_delay();
+ adc_io_process(ADC_IO_SCL,1);
+ adc_delay();
+// vTaskDelay(5);
+ }
+ return read_dat;
+}
+
+/******ad7705ͨŶ˿ڸλ******/
+void reset7705()
+{
+ unsigned char i;
+ adc_io_process(ADC_IO_DI,1);
+ for(i=0;i<36;i++)
+ {
+ adc_io_process(ADC_IO_SCL,0);
+ adc_delay();
+ adc_io_process(ADC_IO_SCL,1);
+ adc_delay();
+ }
+}
+
+/******AD7705ͨ1ʼ******/
+void ad7705_init1()
+{
+ reset7705();
+ WriteByte7705(0x20);//дͨżĴ,ѡͨ1,һβΪдʱӼĴ
+ WriteByte7705(0x01);//дʱӼĴ,Ƶ,Ƶ25Hz
+ WriteByte7705(0x10);//дͨżĴ,ѡͨ1
+ WriteByte7705(0x44);//дüĴ4,,ǻģʽ,˲ͬ,1ͨУ
+}
+/******AD7705ͨ2ʼ******/
+void ad7705_init2()
+{
+ reset7705();
+ WriteByte7705(0x21);//дͨżĴ,ѡͨ2,һβΪдʱӼĴ
+ WriteByte7705(0x01);//дʱӼĴ,Ƶ,Ƶ25Hz
+ WriteByte7705(0x11);//дͨżĴ,ѡͨ2
+ WriteByte7705(0x44);//дüĴ4,,ǻģʽ,˲ͬ,2ͨУ
+}
+
+/******ȡAD7705ͨ1תݺ******/
+unsigned int ReadData1_7705()
+{
+ unsigned int value;
+ uint8_t adc_while=0;
+ ad7705_init1();
+ reset7705();
+ for(adc_while=0;adc_while<30;adc_while++)
+ {
+ if(!adc_io_process(ADC_IO_DRY,0)) break;
+ // vTaskDelay(10);
+ }
+// while(adc_io_process(ADC_IO_DRY,0)); //ȴת
+#if 0
+ {
+// vTaskDelay(20);
+ adc_while++;
+ if(adc_while>250) break;
+ }
+#endif
+ WriteByte7705(0x38); //дͨżĴ,һβΪݼĴ
+ value=5000*ReadWord7705()/65535;
+ return value;
+}
+/******ȡAD7705ͨ2תݺ******/
+unsigned int ReadData2_7705()
+{
+ unsigned int value;
+ uint8_t adc_while;
+ ad7705_init2();
+ reset7705();
+
+ for(adc_while=0;adc_while<30;adc_while++)
+ {
+ if(!adc_io_process(ADC_IO_DRY,0)) break;
+// vTaskDelay(10);
+ }
+// while(adc_io_process(ADC_IO_DRY,0));
+ //ȴת
+#if 0
+ {
+// vTaskDelay(20);
+ adc_while++;
+ if(adc_while>250) break;
+ }
+#endif
+ WriteByte7705(0x39);//дͨżĴ,һβΪݼĴ
+ value=5000*ReadWord7705()/65535;
+ return value;
+}
+
+//IO set
+uint8_t adc_io_process(ADC_IO_ENUM io,uint8_t highorlow)
+{
+ uint32_t temp_adc;
+
+
+ switch(io)
+ {
+ case ADC_IO_SCL://out
+ if(highorlow)
+ {
+ adc->gpio_write((GPIO_SCL_MASK), GPIO_SCL_MASK);
+ }
+ else
+ {
+ adc->gpio_write((~GPIO_SCL_MASK), GPIO_SCL_MASK);
+ }
+ break;
+ case ADC_IO_DI://out
+ if(highorlow)
+ {
+ adc->gpio_write((GPIO_DI_MASK), GPIO_DI_MASK);
+ }
+ else
+ {
+ adc->gpio_write((~GPIO_DI_MASK), GPIO_DI_MASK);
+ }
+ break;
+ case ADC_IO_DO://in
+ adc->gpio_read(&temp_adc, GPIO_DO_MASK);
+ temp_adc = temp_adc & GPIO_DO_MASK;
+ temp_adc = temp_adc >> 22;
+ return (uint8_t)temp_adc;
+ //get io level
+ break;
+
+ case ADC_IO_DRY://in
+ adc->gpio_read(&temp_adc, GPIO_DRY_MASK);
+ temp_adc = temp_adc & GPIO_DRY_MASK;
+ temp_adc = temp_adc >> 23;
+ return (uint8_t)temp_adc;
+ //get io level
+ break;
+
+ }
+ return 0;
+}
+
+
+#define AUTO_SWITCH_ADC 3810
+STUDY_FLAG_ENUM study_check(uint8_t study)
+{
+ if(study_ctr.ch2<4200&&study_ctr.ch1<4200)
+ {
+ if(study)
+ {
+ if(/*study_ctr.ch2valuestring;
+
+ #if 1
+ if(strncmp(m, "WELCOME", 7) == 0)
+ {
+ //ֹ豸״̬δȵdz
+ // checkout();
+ // //ָֹ
+ // delay_ms(500);
+ // checkin();
+ }
+
+ //豸û¼ͻӭϢ
+ else if(strncmp(m, "login", 5) == 0)
+ {
+ char *from_id = cJSON_GetObjectItem(jsonObj, "ID")->valuestring;
+ char new_content[] = "Welcome new user!";
+ say2server(from_id, new_content);
+ }
+ //0004ķ
+ else if(strncmp(m, "checked", 7) == 0)// ػSEND OK
+ {
+ xTimerStop(OneShot_CanServer_Handle,10);
+ xSemaphoreGive(SendenableMutexSemaphore); //ͷź
+ }
+ //0004ķأʾ
+ else if(strncmp(m, "connected", 9) == 0)//
+ {
+ disconnect_process();
+ }
+ //checkinɹ
+ else if(strncmp(m, "checkinok", 9) == 0)//
+ {
+ touch_flag|=(0x0001<<14);//
+ }
+ //յsayִָӦӦظ
+ else if(strncmp(m, "say", 3) == 0/* && millis() - lastSayTime > 10*/)
+ {
+
+ char *content = cJSON_GetObjectItem(jsonObj, "C")->valuestring;
+ char *from_id = cJSON_GetObjectItem(jsonObj, "ID")->valuestring;
+ char *user_name = cJSON_GetObjectItem(jsonObj, "NAME")->valuestring;//ȡǰû
+
+ dprintf("re say:%s:%s\r\n",user_name,content);
+ // lastSayTime = millis();
+
+ if(strlen(content)==1)//
+ {
+ if((content[0]>('0'-1))&&(content[0]<('8'+1)))
+ {
+ uint8_t touch_light_temp = content[0]-'0';
+ char say2server_temp[20];
+ server_control_light(0x20|touch_light_temp);
+ sprintf(say2server_temp,"light mode: %1d",touch_flag&0x000f);
+ say2server(from_id, say2server_temp);
+ }
+ else
+ {
+ say2server(from_id, "invalid cmd");
+ }
+
+ }
+ else//
+ {
+
+ if(strncmp(content, "offOn", 5) == 0)
+ {
+ uint8_t touch_light_temp = 4;
+ char say2server_temp[20];
+ server_control_light(0x20|touch_light_temp);
+ sprintf(say2server_temp,"light mode:on %1d",touch_flag&0x000f);
+ say2server(from_id, say2server_temp);
+
+ }
+ else if(strncmp(content, "play", 4) == 0)
+ {
+
+ char say2server_temp[20];
+ server_control_light(0x10);
+ sprintf(say2server_temp,"light mode: auto");
+ say2server(from_id, say2server_temp);
+ }
+ else if(strncmp(content, "stop", 4) == 0)
+ {
+ char say2server_temp[20];
+ server_control_light(0x00);
+ sprintf(say2server_temp,"light mode: off");
+ say2server(from_id, say2server_temp);
+
+ }
+ else if(strncmp(content, "minus", 5) == 0)
+ {
+ char say2server_temp[20];
+ uint8_t touch_light_temp = touch_flag&0x000f;
+ if(touch_light_temp)
+ {
+ touch_flag&=0xfff0;
+ touch_light_temp--;
+ touch_flag|=(touch_light_temp);
+ }
+
+ server_control_light(0x20|touch_light_temp);
+ sprintf(say2server_temp,"light mode:minus %1d",touch_flag&0x000f);
+ say2server(from_id, say2server_temp);
+
+ }
+ else if(strncmp(content, "plus", 4) == 0)
+ {
+ char say2server_temp[20];
+ uint8_t touch_light_temp = touch_flag&0x000f;
+ if(touch_light_temp<8)
+ {
+ touch_flag&=0xfff0;
+ touch_light_temp++;
+ touch_flag|=(touch_light_temp);
+ }
+
+ server_control_light(0x20|touch_light_temp);
+ sprintf(say2server_temp,"light mode:plus %1d",touch_flag&0x000f);
+ say2server(from_id, say2server_temp);
+
+ }
+ else
+ {
+ char new_content[] = "invalid cmd";
+ //do something here....
+
+ say2server(from_id, new_content);
+
+ }
+ }
+ }
+ #endif
+ if(jsonObj)
+ cJSON_Delete(jsonObj);
+ return 1;
+}
+
+
+//İ֡Ȼͺ
+void pack2server(void *pvParameters)
+{
+ uint16_t packtype;
+ while(1)
+ {
+ if(xQueueReceive(pack2server_queue,&packtype,0))//յportMAX_DELAY
+ {
+ wifi2server(packtype);
+ }
+
+ vTaskDelay(pack2server_delay);
+ }
+}
+
+//÷ݰ ⲿ
+void sendpack2server(uint16_t package_num)
+{
+ uint16_t temp = package_num;
+ BaseType_t err;
+ err=xQueueSend(pack2server_queue,&temp,0);
+ if(err==errQUEUE_FULL) //Ϣ֡
+ {
+
+ dprintf("pack2server_Queue%4xݷʧ!\r\n",temp);
+ }
+}
+
+void say2server(char*toid,char*msg)
+{
+ sprintf(say_did,"%s",toid);
+ sprintf(say_content,"%s",msg);
+ wifi2server(0x0003);
+}
+
+//wifi֡֡
+//Э֡Ȼ3ķͶ
+void wifi2server(uint16_t data_type)
+{
+ uint8_t* p;
+ uint16_t len=0;
+ uint8_t if_send=1,i;
+ usart_task_data USART3_send_data;//USART3send
+ BaseType_t err;
+
+ len = 150;//
+ // dprintf("wifi2server\r\n");
+ p = pvPortMalloc(len);
+ configASSERT(p);
+ memset(p,0,len);
+ switch(data_type)
+ {
+ case 0x0000://checkout
+ {
+ sprintf((char*)p,"{\"M\":\"checkout\",\"ID\":\"%s\",\"K\":\"%s\"}\n", DEVICEID, APIKEY);
+ len=strlen((char*)p);
+ }
+ break;
+ case 0x0001://checkin
+ {
+
+ sprintf((char*)p,"{\"M\":\"checkin\",\"ID\":\"%s\",\"K\":\"%s\"}\n", DEVICEID, APIKEY);
+ len=strlen((char*)p);
+ }
+ break;
+ case 0x0002://value
+ {
+ float update_value_rtc,update_value_cm3232,update_value_touch;
+
+ //ǿ λ
+ if(!(touch_flag&(0x0001<<14)))
+ if_send =0;//
+ //ϴһ
+ update_value_rtc =(float) get_rtc_sec();
+ update_value_cm3232 = (float)CM3232_Read(0x50);
+ update_value_touch = (float)(touch_flag&0x000f);
+
+ //{"M":"update","ID":"xxxx","V":{"xxxx":"0","xxxx":"44","xxxx":"31"}}
+ if(study_ctr.startstudy)
+ {
+ sprintf((char*)p,"{\"M\":\"update\",\"ID\":\"%s\",\"V\":{\"%s\":\"%f\",\"%s\":\"%f\",\"%s\":\"%f\",\"%s\":\"%f\",\"%s\":\"%f\"}}\n",
+ update_did,
+ update_id_rtc, update_value_rtc,
+ update_id_cm3232,update_value_cm3232,
+ update_id_touch,update_value_touch,
+ update_id_time,(float)(get_rtc_sec()-study_ctr.time),
+ update_id_flag,(float)study_ctr.ch1);
+
+ }
+ else
+ {
+ sprintf((char*)p,"{\"M\":\"update\",\"ID\":\"%s\",\"V\":{\"%s\":\"%f\",\"%s\":\"%f\",\"%s\":\"%f\"}}\n",
+ update_did, update_id_rtc, update_value_rtc,update_id_cm3232,update_value_cm3232,update_id_touch,update_value_touch);
+ }
+ len=strlen((char*)p);
+ }
+ break;
+ case 0x0003://say
+ {
+ //sayǰ״̬
+ if(!(touch_flag&(0x0001<<14)))
+ if_send =0;//
+ sprintf((char*)p,"{\"M\":\"say\",\"ID\":\"%s\",\"C\":\"%s\"}\n", say_did, say_content);//idһfromID
+ len=strlen((char*)p);
+ }
+ break;
+ case 0x0004://check state
+ {
+
+ sprintf((char*)p,"{\"M\":\"status\"}\n");//
+ len=strlen((char*)p);
+ }
+ break;
+
+ default:
+ if_send = 0;
+ break;
+ }
+ if(if_send)
+ {
+
+ USART3_send_data.type = USART_SERVER;
+ USART3_send_data.len = len;
+ USART3_send_data.pstr = p;
+ #if 0//ԷǷȷ
+ dprintf("dat2server %4x:",data_type);
+ for(i=0; i1)
+ {
+ checkpkg_count = 0;
+ temp = 0x0004;//check
+ err=xQueueSend(pack2server_queue,&temp,0);//
+ }
+
+ //Ͱ2
+ temp = 0x0002;
+ err=xQueueSend(pack2server_queue,&temp,0);//ʱУܽʱ
+
+// wifi2server(0x0002);
+
+ if(err==errQUEUE_FULL) //Ϣ֡
+ {
+
+ dprintf("pack2server_Queueڷ0002ݷʧ!\r\n");
+ }
+ // wifi2server(0x0002);
+ }
+ else//
+ {
+ uint8_t temp = 0;
+ err=xQueueSend(connect_to_server_Queue,&temp,0);
+ if(err==errQUEUE_FULL) //Ϣ֡
+ {
+
+ dprintf("connect_to_server_Queue1ݷʧ!\r\n");
+ }
+ vTaskResume(connect_to_server_Handler);
+
+ }
+#endif
+}
+
+void disconnect_process(void)
+{
+// u8 temp = 0;
+ touch_flag&=(~(0x0001<<4));//
+ touch_flag&=(~(0x0001<<14));
+ if(touch_flag&(0x0001<<7))//״̬
+ {
+ mcu_sendcmd2touch(Wifi_Off);
+ }
+// xQueueSend(connect_to_server_Queue,&temp,0);
+// vTaskResume(connect_to_server_Handler);
+ xTimerChangePeriod(period40or5_0002_Handle,PKG0002_5S_TICKS,10);//ı䶨ʱ
+// xTimerStop(period40or5_0002_Handle,10);
+ dprintf("disconnect to server\r\n");
+}
+//end package.c
+
diff --git a/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/package/package.h b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/package/package.h
new file mode 100644
index 00000000..3be7202d
--- /dev/null
+++ b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/package/package.h
@@ -0,0 +1,39 @@
+/*
+ * package.h
+ *
+ * Created on: 201853
+ * Author: Administrator
+ */
+
+#ifndef PACKAGE_PACKAGE_H_
+#define PACKAGE_PACKAGE_H_
+
+#ifndef __PACKAGE_H
+#define __PACKAGE_H
+#include "embARC.h"
+#include "embARC_debug.h"
+
+#include "app_config.h"
+
+#include "FreeRTOS.h" //FreeRTOSʹ
+#include "task.h"
+#include "queue.h"
+#include "semphr.h"
+#include "timers.h"
+
+extern uint16_t pkt_serial; //Ͱ
+extern char say_did[30];
+
+void usart3_app_task(void *pvParameters);
+void sendpack2server(uint16_t package_num);
+void pack2server(void *pvParameters);
+void wifi2server(uint16_t data_type);
+uint8_t serverdata_process(usart_task_data usart3_app_temp);
+void period40or5_0002_Callback(TimerHandle_t xTimer);
+void disconnect_process(void);
+void say2server(char*toid,char*msg);
+#endif
+
+
+
+#endif /* PACKAGE_PACKAGE_H_ */
diff --git a/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/strpos/strpos.c b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/strpos/strpos.c
new file mode 100644
index 00000000..71f1c4f5
--- /dev/null
+++ b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/strpos/strpos.c
@@ -0,0 +1,75 @@
+/*
+ * strpos.c
+ *
+ * Created on: 201853
+ * Author: Administrator
+ */
+
+#include "strpos.h"
+//
+#include "string.h"
+#include "stdlib.h"
+//#include "sys.h"
+
+
+
+
+//ʼλͽλ
+uint8_t server_start[4] = {'{','"','M','"'};//{"M"
+uint8_t server_stop [2] = {'"','}'};//"}
+uint8_t rn_stop[2] = {0x0d,0x0a};
+uint8_t test_data[]={0x00,0x01,0x02,0xff,0xaa,0x55,0x01,0x07,0x08,0x0d,0x0a,0x32,0x97,0x25,0xEE};
+
+//Ѱ֡ʼ ־
+//ضԱλõʼַ 00 01 02 ff aa 55 00 07 08 3
+//ַܳҪС255
+uint8_t findpos(uint8_t*pstr1,uint8_t len1,uint8_t *pstr2,uint8_t len2)//1DZ־λ2ԭʼ
+{
+ uint8_t i,j;
+ if(!(len2SRܱĪĴ
+//uint8_t USART_RX_BUF[USART_REC_LEN]; //ջ,USART_REC_LENֽ.
+uint8_t usart_data_all[USART1_NUM][USART1_PER_LEN];//1buff
+uint8_t usart_buff_flag=1;//Щ鱻ʹˣ´ĸд Ĭʹõһ
+//uint8_t buff_now=0;//ǰʹõĻ
+usart_dat usart1_data;
+uint8_t usart1_time_out=0;//1ճʱʱ
+//״̬
+//bit15 ɱ־
+//bit14 յ0x0d
+//bit13~0 յЧֽĿ
+uint16_t USART_RX_STA=0; //״̬
+//
+TaskHandle_t USART1_Handler;
+TaskHandle_t USART1_app_Handler;
+QueueHandle_t Dprintf_Queue;
+//SemaphoreHandle_t xMutex;
+void occupy_buff(void);
+uint32_t uart1_init(uint32_t bound)
+{
+ occupy_buff();
+ uart1 = uart_get_dev(DW_UART_1_ID);
+
+ if (uart1 == NULL) {
+ EMBARC_PRINTF("Failed to get device of uart0 for blueteeth.\r\n");
+ return -1;
+ }
+
+ if (uart1->uart_open(bound) == E_OPNED) {
+ uart1->uart_control(UART_CMD_SET_BAUD, (void *)(bound));
+ EMBARC_PRINTF("ble_uart open succeed\r\n");
+ }
+
+ DEV_BUFFER_INIT(&uart1_uart_int_buffer, &uart1_rx_buffer, 1);
+ if (uart1->uart_control(UART_CMD_SET_RXINT_BUF, (void *) & uart1_uart_int_buffer) != E_OK) {
+ EMBARC_PRINTF("ble_isr_buffer config error\r\n");
+ return -1;
+ }
+
+// if (uart1->uart_control(UART_CMD_SET_RXCB, (void *) & USART1_IRQHandler) != E_OK) {
+// EMBARC_PRINTF("ble_isr config error\r\n");
+// return -1;
+// }
+
+ int_handler_install(INTNO_UART1, USART1_IRQHandler);
+ int_pri_set(INTNO_UART1, (-1));
+
+ if (uart1->uart_control(UART_CMD_SET_RXINT, (void *)(1)) != E_OK) {
+ EMBARC_PRINTF("Enable ble interrupt error\r\n");
+ return -1;
+ }
+
+ return 0;
+}
+
+
+//ҵδʹõĻbuff
+//0-USART1_NUM-1ʾӦʹ
+//USART1_NUMʾûплbuff
+//浽 buff_now
+void occupy_buff(void)
+{
+ uint8_t i,ret=USART1_NUM;
+ for(i=0;iuart_read(&Res, 1); //ȡյ
+// printf("%d\r\n",Res);
+
+
+ usart1_time_out=0x80;// //
+// if(USART_RX_STA==0) //ʹܶʱ7ж
+// {
+// TIM_Cmd(TIM7,ENABLE);//ʹܶʱ7
+// }
+
+ if(usart1_data.buff_nowUSART1_PER_LEN-1)
+ {
+ usart1_time_out=0x00;//һݣٽгʱʱ´յټʱ
+ usart1_data.len=USART_RX_STA&0x7fff;
+ xQueueSendFromISR(USART1_Queue,&usart1_data,&xHigherPriorityTaskWoken);//з
+ USART_RX_STA = 0;
+ occupy_buff();
+ portYIELD_FROM_ISR();//ҪĻһл
+ }
+
+ #if 0
+ usart_data usart1_temp;
+ if(USART_GetITStatus(USART1, USART_IT_RXNE) != RESET) //ж(յݱ0x0d 0x0aβ)
+ {
+ Res =USART_ReceiveData(USART1); //ȡյ
+
+ if((USART_RX_STA&0x8000)==0)//δ
+ {
+ if(USART_RX_STA&0x4000)//յ0x0d
+ {
+ if(Res!=0x0a)USART_RX_STA=0;//մ,¿ʼ
+ else USART_RX_STA|=0x8000; //
+ }
+ else //ûյ0X0D
+ {
+ if(Res==0x0d)USART_RX_STA|=0x4000;
+ else
+ {
+ USART_RX_BUF[USART_RX_STA&0X3FFF]=Res ;
+ USART_RX_STA++;
+ if(USART_RX_STA>(USART_REC_LEN-1))USART_RX_STA=0;//ݴ,¿ʼ
+ }
+ }
+ }
+ }
+#endif
+ #if 0
+ //зͽյ
+ if((USART_RX_STA&0x8000)&&(Message_Queue!=NULL))
+ {
+ xQueueSendFromISR(Message_Queue,USART_RX_BUF,&xHigherPriorityTaskWoken);//з
+
+ USART_RX_STA=0;
+ memset(USART_RX_BUF,0,USART_REC_LEN);//ݽջUSART_RX_BUF,һݽ
+
+ portYIELD_FROM_ISR(xHigherPriorityTaskWoken);//ҪĻһл
+ }
+ #endif
+ //зͽյ taskݴ洢ַͳȽfreeڴIJ
+ #if 0
+ if((USART_RX_STA&0x8000)&&(USART1_Queue!=NULL))
+ {
+ usart1_temp.plen = USART_RX_STA&0X3FFF;
+ usart1_temp.pstr=pvPortMalloc(usart1_temp.plen);
+ memcpy(usart1_temp.pstr,USART_RX_BUF,usart1_temp.plen);
+
+ xQueueSendFromISR(USART1_Queue,&usart1_temp,&xHigherPriorityTaskWoken);//з
+
+ USART_RX_STA=0;
+// memset(USART_RX_BUF,0,USART_REC_LEN);//ݽջUSART_RX_BUF,һݽ
+
+ portYIELD_FROM_ISR(xHigherPriorityTaskWoken);//ҪĻһл
+ }
+ #endif
+}
+#endif
+
+
+QueueHandle_t USART1_Task_Queue;//taskݶ Ƿְõһ֡һ֡
+USART_TASK_PROCESS usart1_task_process=USART_DATA_IDEL;//ݴ̱
+uint8_t usart1_task_time_out=0;//1 taskճʱʱ
+uint16_t server_data_remain;//server dataжûиƹ
+usart_dat usart1_temp;//յײ㴮ڻݶ
+usart_task_data usart1_task_temp;//͵usart1task
+
+void USART1_task(void *pvParameters)
+{
+
+ uint8_t temp_pos;//ݴ־λλϢ
+ uint8_t data_num_remain=0;//ǰ.ʣݳ Ҫѽյusart1_temp.lenݴ
+
+ //洢һݵij 洢ĵַ
+// uint16_t data_num_last=0;
+ uint8_t* data_p;//洢ݵĵַ ڴʱݰϢӦĴСڴ
+ uint8_t* data_temp;//ײ㴮ָ
+ BaseType_t err;
+ dprintf("USART1_task success\r\n");
+
+ //֡־λ
+// printf("start:%d\r\n", findpos(server_start,4,test_data,11));
+// printf("posrn:%d\r\n", findpos(rn_stop,2,test_data,11));
+// printf("stop:%d\r\n", findpos(server_stop,4,test_data,15));
+
+ while(1)
+ {
+
+ if(xQueueReceive(USART1_Queue,&usart1_temp,0))//յײ㴮
+// if(xQueueReceive(USART1_Queue,&usart1_temp,portMAX_DELAY))//յײ㴮
+ {
+
+
+
+ data_num_remain = usart1_temp.len;
+ data_temp = usart_data_all[usart1_temp.buff_now];
+
+ switch(usart1_task_process)
+ {
+ case USART_DATA_IDEL:
+ {
+
+// data_num_last=0;//¼ݶ
+ CHECK_BUFF:while(data_num_remain)
+ {
+ temp_pos = 0xff;//findpos(server_start,4,data_temp,data_num_remain);//1Ĭϲݣֻ\r\nβ
+ if(temp_pos==0xff)//ûзݵʼ־ Ϊͨ
+ {
+ temp_pos=findpos(rn_stop,2,data_temp,data_num_remain);
+// printf("usart1task test:%d\r\n",temp_pos);
+ if(temp_pos==0xFF)//û\r\n
+ {
+
+ /*
+ if(usart1_temp.len==USART1_PER_LEN)
+ //ȫޱǵݣҺ滹ޱݣȴ\R\N֡ȴһ֡ݵ\R\N
+ //ҲΪЧݹֱӶ ĬbuffΪ200 \r\nݲᳬ200 ֱӶޱ ʼµĽܴ
+ //Ƿserver_stop ,?
+ {
+
+ }
+ else//ݳСbuff Ϊݽֱӷ͵֡
+ {
+
+ }
+ */
+ //ûserver_start\r\n ֱӷͳȥ
+
+ data_p=pvPortMalloc(data_num_remain);//\r\nȥֻǰ
+ memcpy(data_p,data_temp,data_num_remain);
+ usart1_task_temp.len = data_num_remain;
+ usart1_task_temp.pstr=data_p;
+ usart1_task_temp.type=USART_OTHER;
+ err=xQueueSend(USART1_Task_Queue,&usart1_task_temp,10);
+ if(err==errQUEUE_FULL) //Ϣ֡
+ {
+ //ʧҪfreeڴ
+ vPortFree(usart1_task_temp.pstr);
+ dprintf("USART1_Task_QueueݷOTHERʧ!\r\n");
+ }
+
+ data_num_remain = 0;
+
+ break;
+ }
+ else//Ѱҵ\r\n ͵ǰ֡жϻbuffʣǷϣûдϾͼ USART_DATA_IDEL Ĵ
+ {
+ if(temp_pos)
+ {
+ data_p=pvPortMalloc(temp_pos);//\r\nȥֻǰ
+ memcpy(data_p,data_temp,temp_pos);
+ usart1_task_temp.len = temp_pos;
+ usart1_task_temp.pstr=data_p;
+ usart1_task_temp.type=USART_RN;
+ err=xQueueSend(USART1_Task_Queue,&usart1_task_temp,10);
+ if(err==errQUEUE_FULL) //Ϣ֡
+ {
+ //ʧҪfreeڴ
+ vPortFree(usart1_task_temp.pstr);
+ dprintf("USART1_Task_QueueݷRNʧ!\r\n");
+ }
+ }
+ data_num_remain-=temp_pos+2;
+ data_temp+=temp_pos+2;
+
+ }
+ }
+ else if(temp_pos==0x00)//ʼλþʼ־
+ {
+ server_data_remain = ((data_temp[4])<<8)+data_temp[5];//һ֡ݳ
+ if(data_num_remain>5)//ٰϢȻͲܼ
+ {
+ if(server_data_remain>data_num_remain)//һ֡ԽҪ֡
+ {
+ //ڴ棬ϢڴУȴһ
+ //server֡ʼ־ͽ־
+ usart1_task_time_out=0x80;
+ data_p=pvPortMalloc(server_data_remain);
+ usart1_task_temp.len = server_data_remain;
+ usart1_task_temp.pstr=data_p;
+ memcpy(data_p,data_temp,data_num_remain);
+ data_p+=data_num_remain;
+ server_data_remain-=data_num_remain;//֡Ҫij
+ usart1_task_process = USART_DATA_SERVER_START;//SERVER֡Ľ
+ data_num_remain = 0;
+ break;
+ }
+ else//һ֡server һ
+ {
+ //жϽλǷȷִв
+ if(strsame(server_stop,data_temp+server_data_remain-4,4))//֤ʧܣǷݵotherݷĴǶ
+ {
+
+ data_p=pvPortMalloc(server_data_remain);
+ usart1_task_temp.len = server_data_remain;
+ usart1_task_temp.pstr=data_p;
+ usart1_task_temp.type=USART_SERVER;
+ memcpy(data_p,data_temp,server_data_remain);
+ err=xQueueSend(USART1_Task_Queue,&usart1_task_temp,10);
+ if(err==errQUEUE_FULL) //Ϣ֡
+ {
+ //ʧҪfreeڴ
+ vPortFree(usart1_task_temp.pstr);
+ dprintf("USART1_Task_Queueݷ͵һ֡serverʧ!\r\n");
+ }
+ }
+// else//ݲԣҪfreeڴ
+// {
+// vPortFree(usart1_task_temp.pstr);
+// }
+ }
+
+// else
+ //ǷԣҪ
+ {
+ data_num_remain-=server_data_remain;
+ data_temp+=server_data_remain;
+ }
+ }
+ else//ʼ6λ ֱӶ
+ {
+ data_num_remain = 0;
+ break;
+ }
+
+ }
+ else//ʼλм ҲǷ֮ǰ ʼλþʼ־
+ {
+ data_num_remain-=temp_pos;
+ data_temp+=temp_pos;
+ }
+ }
+ //ݣͷbuffռ
+ release_buff(usart1_temp.buff_now);//ͷbuffռ״̬
+ }
+ break;
+ case USART_DATA_SERVER_START:
+ {
+// while(data_num_remain)
+ {
+ if(server_data_remain>data_num_remain)//֡
+ {
+ usart1_task_time_out=0x80;
+ memcpy(data_p,data_temp,data_num_remain);
+ data_p+=data_num_remain;
+ server_data_remain-=data_num_remain;//֡Ҫij
+ usart1_task_process = USART_DATA_SERVER_START;//SERVER֡Ľ
+ data_num_remain = 0;
+ break;
+ }
+ else//һڽ֡
+ {
+ usart1_task_time_out=0x00;
+ usart1_task_process = USART_DATA_IDEL;
+ memcpy(data_p,data_temp,server_data_remain);
+ if(strsame(server_stop,usart1_task_temp.pstr+usart1_task_temp.len-4,4))
+ {
+ usart1_task_temp.type=USART_SERVER;
+ err=xQueueSend(USART1_Task_Queue,&usart1_task_temp,10);
+ if(err==errQUEUE_FULL) //Ϣ֡
+ {
+ //ʧҪfreeڴ
+ vPortFree(usart1_task_temp.pstr);
+ dprintf("USART1_Task_QueueݷͶһ֡serverʧ!\r\n");
+ }
+ }
+ else//ݲԣҪfreeڴ
+ {
+ vPortFree(usart1_task_temp.pstr);
+ }
+ data_num_remain-=server_data_remain;
+ data_temp+=server_data_remain;
+
+ {//֡ϻûд
+ if(data_num_remain)
+ {//ٴݼ
+ goto CHECK_BUFF;//һЧbuff
+// data_num_remain =0;//
+ }
+ }
+ }
+ }
+ //ݣͷbuffռ
+ release_buff(usart1_temp.buff_now);//ͷbuffռ״̬
+ }
+ break;
+// case USART_DATA_NORMAL_START:
+// {
+//
+// }
+// break;
+// case USART_DATA_WAIT:
+// {
+//
+// }
+// break;
+
+ }
+ }
+
+ vTaskDelay(USART1_task_delay); //ʱ10msҲ10ʱӽ
+ }
+}
+
+
+#if 0 //1ҪͷŶڴ ֻմ\R\N п֡
+//ֵź
+SemaphoreHandle_t BinarySemaphore_free; //ֵź
+
+
+//USART1_taskлڶ֡ݳִҪfree ڴIJ
+void FREE_ERRORMEM_task(void *pvParameters)
+{
+ BaseType_t err;
+ printf("FREE_ERRORMEM_task success\r\n");
+ while(1)
+ {
+ if(BinarySemaphore_free!=NULL)
+ {
+ err=xSemaphoreTake(BinarySemaphore_free,portMAX_DELAY); //ȡź
+// err=xSemaphoreTake(BinarySemaphore_free,0); //ȡź
+ if(err==pdTRUE) //ȡźɹ
+ {
+ usart1_task_process = USART_DATA_IDEL;
+ vPortFree(usart1_task_temp.pstr);//жfreeҪⲿtaskнв
+ printf("free_mem sucess!\r\n");
+ }
+ else if(err==pdFALSE)
+ {
+ vTaskDelay(FREE_ERRORMEM_delay); //ʱ10msҲ10ʱӽ
+ }
+ }
+ //ʱ10msҲ10ʱӽ
+ }
+}
+
+
+
+
+#endif
+
+//1 APP㴦 ***Թܣش
+void usart1_app_task(void *pvParameters)
+{
+// TickType_t xLastWakeTime;
+// const TickType_t yFrequency = 10;
+
+ usart_task_data usart1_app_temp;//USART3_task ķ֡
+ uint8_t* buffer;
+ BaseType_t err;
+
+ dprintf("usart1_app_task start!\r\n");
+// xLastWakeTime = xTaskGetTickCount();
+ while(1)
+ {
+ if(xQueueReceive(Dprintf_Queue,&usart1_app_temp,0))
+ {
+ printf("%s",usart1_app_temp.pstr);
+ vPortFree(usart1_app_temp.pstr);
+ }
+
+
+ if(xQueueReceive(USART1_Task_Queue,&usart1_app_temp,0))//յ
+ {
+ buffer=pvPortMalloc(usart1_app_temp.len+1);
+ memcpy(buffer,usart1_app_temp.pstr,usart1_app_temp.len);
+ buffer[usart1_app_temp.len]=0;
+ printf("U1:%s\r\n",buffer);//ʹprintf ǵ
+ if(findpos("AT+L",4,usart1_app_temp.pstr,usart1_app_temp.len)!=0XFF)
+ {
+ compare_pwm = compare_set[usart1_app_temp.pstr[4]-'0'];
+/*
+ switch(usart1_app_temp.pstr[4])
+ {
+ case '0':
+ compare_pwm = compare_set[0];
+// senddata_by_usart4((uint8_t*)"1\r\n",3);
+ break;
+ case '1':
+ compare_pwm = compare_set[3];
+// senddata_by_usart4((uint8_t*)"a\r\n",3);
+ break;
+ case '2':
+ compare_pwm = compare_set[5];
+// senddata_by_usart4((uint8_t*)"5\r\n",3);
+ break;
+ case '3':
+ compare_pwm = compare_set[8];
+// senddata_by_usart4((uint8_t*)"9\r\n",3);
+ break;
+ }
+ */
+// senddata_by_usart4((uint8_t*)"hello usart5\r\n",14);
+ }
+ else if(findpos("AT+GMR",6,usart1_app_temp.pstr,usart1_app_temp.len)!=0XFF)
+ {
+ uint8_t temp = 1;
+ err=xQueueSend(connect_to_server_Queue,&temp,10);
+ if(err==errQUEUE_FULL) //Ϣ֡
+ {
+ printf("connect_to_server_Queue1ݷʧ!\r\n");
+ }
+ vTaskResume(connect_to_server_Handler);
+ }
+
+ else if(findpos("AT+R",4,usart1_app_temp.pstr,usart1_app_temp.len)!=0XFF)
+ {
+ //right
+ uint8_t temp;
+ unsigned long adc_temp;
+ //noperson up
+ server_control_light(0x23);
+ study_ctr.up = ReadData1_7705();
+ for(temp=0;temp<20;temp++)
+ {
+ adc_temp = ReadData1_7705();
+ dprintf("%d temp2 = %d\t",temp,adc_temp);
+ if(adc_tempSRܱĪĴ
+
+void occupy_buff3(void);
+uint32_t uart3_init(uint32_t bound)
+{
+ occupy_buff3();
+ uart3 = uart_get_dev(DW_UART_0_ID);
+
+ if (uart3 == NULL) {
+ EMBARC_PRINTF("Failed to get device of uart0 for blueteeth.\r\n");
+ return -1;
+ }
+
+ if (uart3->uart_open(bound) == E_OPNED) {
+ uart3->uart_control(UART_CMD_SET_BAUD, (void *)(bound));
+ EMBARC_PRINTF("ble_uart open succeed\r\n");
+ }
+
+ DEV_BUFFER_INIT(&esp8266_uart_int_buffer, &esp8266_rx_buffer, 1);
+ if (uart3->uart_control(UART_CMD_SET_RXINT_BUF, (void *) & esp8266_uart_int_buffer) != E_OK) {
+ EMBARC_PRINTF("ble_isr_buffer config error\r\n");
+ return -1;
+ }
+
+// if (uart3->uart_control(UART_CMD_SET_RXCB, (void *) & USART3_IRQHandler) != E_OK) {
+// EMBARC_PRINTF("ble_isr config error\r\n");
+// return -1;
+// }
+
+ int_handler_install(INTNO_UART0, USART3_IRQHandler);
+ int_pri_set(INTNO_UART0, (-2));
+
+ if (uart3->uart_control(UART_CMD_SET_RXINT, (void *)(1)) != E_OK) {
+ EMBARC_PRINTF("Enable ble interrupt error\r\n");
+ return -1;
+ }
+
+ return 0;
+}
+
+
+//ҵδʹõĻbuff
+//0-USART3_NUM-1ʾӦʹ
+//USART3_NUMʾûплbuff
+//浽 buff_now
+void occupy_buff3(void)
+{
+ uint8_t i,ret=USART3_NUM;
+ for(i=0;iuart_read(&Res3, 1); //ȡյ
+
+
+ usart3_time_out=0x80;// //
+// if(USART_RX_STA==0) //ʹܶʱ7ж
+// {
+// TIM_Cmd(TIM7,ENABLE);//ʹܶʱ7
+// }
+#if 1
+ if(usart3_data.buff_nowUSART3_PER_LEN-1)
+ {
+ usart3_time_out=0x00;//һݣٽгʱʱ´յټʱ
+ usart3_data.len=USART3_RX_STA&0x7fff;
+ xQueueSendFromISR(USART3_Queue,&usart3_data,&xHigherPriorityTaskWoken);//з
+ USART3_RX_STA = 0;
+ occupy_buff3();
+ portYIELD_FROM_ISR();//ҪĻһл
+ }
+
+#endif
+}
+#endif
+
+
+//QueueHandle_t USART3_Task_Queue;//taskݶ Ƿְõһ֡һ֡
+QueueHandle_t USART3_Task_server_Queue;//洢
+QueueHandle_t USART3_Task_rn_other_Queue;//洢\r\nݺûиʽ
+USART_TASK_PROCESS USART3_task_process=USART_DATA_IDEL;//ݴ̱
+uint8_t usart3_task_time_out=0;//1 taskճʱʱ
+uint16_t server_data_remain3;//server dataжûиƹ
+usart_dat USART3_temp;//յײ㴮ڻݶ
+usart_task_data USART3_task_temp;//͵USART3task
+
+void USART3_task(void *pvParameters)
+{
+
+ uint8_t temp_pos3;//ݴ־λλϢ
+ uint8_t data_num_remain3=0;//ǰ.ʣݳ ҪѽյUSART3_temp.lenݴ
+
+ //洢һݵij 洢ĵַ
+// uint16_t data_num_last=0;
+ uint8_t* data_p3;//洢ݵĵַ ڴʱݰϢӦĴСڴ
+ uint8_t* data_temp3;//ײ㴮ָ
+ BaseType_t err;
+ dprintf("USART3_task success\r\n");
+
+ //֡־λ
+// printf("start:%d\r\n", findpos(server_start,4,test_data,11));
+// printf("posrn:%d\r\n", findpos(rn_stop,2,test_data,11));
+// printf("stop:%d\r\n", findpos(server_stop,4,test_data,15));
+// vTaskSuspend(NULL);
+ while(1)
+ {
+// if(xQueueReceive(USART3_Queue,&USART3_temp,0))//յײ㴮
+ if(xQueueReceive(USART3_Queue,&USART3_temp,portMAX_DELAY))//յײ㴮
+ {
+
+// printf("hhhhhhhhhhhhh");
+
+ data_num_remain3 = USART3_temp.len;
+ data_temp3 = usart3_data_all[USART3_temp.buff_now];
+
+ switch(USART3_task_process)
+ {
+ case USART_DATA_IDEL:
+ {
+// dprintf("u3re\r\n");
+
+// data_num_last=0;//¼ݶ
+ CHECK_BUFF:while(data_num_remain3)
+ {
+ temp_pos3 = findpos(server_start,4,data_temp3,data_num_remain3);
+ if(temp_pos3==0xff)//ûзݵʼ־ Ϊͨ
+ {
+ temp_pos3=findpos(rn_stop,2,data_temp3,data_num_remain3);
+// printf("USART3task test:%d\r\n",temp_pos);
+ if(temp_pos3==0xFF)//û\r\n
+ {
+
+ /*
+ if(USART3_temp.len==USART3_PER_LEN)
+ //ȫޱǵݣҺ滹ޱݣȴ\R\N֡ȴһ֡ݵ\R\N
+ //ҲΪЧݹֱӶ ĬbuffΪ200 \r\nݲᳬ200 ֱӶޱ ʼµĽܴ
+ //Ƿserver_stop ,?
+ {
+
+ }
+ else//ݳСbuff Ϊݽֱӷ͵֡
+ {
+
+ }
+ */
+ //ûserver_start\r\n ֱӷͳȥ
+// if(data_num_remain3<50)//ʱֱӷ
+ {
+// if(data_num_remain3>0)
+ {
+ data_p3=pvPortMalloc(data_num_remain3);//\r\nȥֻǰ
+ memcpy(data_p3,data_temp3,data_num_remain3);
+ USART3_task_temp.len = data_num_remain3;
+ USART3_task_temp.pstr=data_p3;
+ USART3_task_temp.type=USART_OTHER;
+ err=xQueueSend(USART3_Task_rn_other_Queue,&USART3_task_temp,10);
+ if(err==errQUEUE_FULL) //Ϣ֡
+ {
+ //ʧҪfreeڴ
+ vPortFree(USART3_task_temp.pstr);
+ dprintf("USART3_Task_rn_other_QueueݷOTHERʧ!\r\n");
+ }
+ }
+ }
+
+ data_num_remain3 = 0;
+
+ break;
+ }
+ else//Ѱҵ\r\n ͵ǰ֡жϻbuffʣǷϣûдϾͼ USART_DATA_IDEL Ĵ
+ {
+ if(temp_pos3>0)
+ {
+ data_p3=pvPortMalloc(temp_pos3);//\r\nȥֻǰ
+ memcpy(data_p3,data_temp3,temp_pos3);
+ USART3_task_temp.len = temp_pos3;
+ USART3_task_temp.pstr=data_p3;
+ USART3_task_temp.type=USART_RN;
+ err=xQueueSend(USART3_Task_rn_other_Queue,&USART3_task_temp,10);
+ if(err==errQUEUE_FULL) //Ϣ֡
+ {
+ //ʧҪfreeڴ
+ vPortFree(USART3_task_temp.pstr);
+ dprintf("USART3_Task_rn_other_QueueݷRNʧ!\r\n");
+ }
+ }
+ data_num_remain3-=temp_pos3+2;
+ data_temp3+=temp_pos3+2;
+
+ }
+ }
+ else if(temp_pos3==0x00)//ʼλþʼ־
+ {
+ temp_pos3 = findpos(server_stop,2,data_temp3,data_num_remain3);
+ if(0xff!=temp_pos3)
+ {
+ data_p3=pvPortMalloc(temp_pos3+3);//
+ memcpy(data_p3,data_temp3,temp_pos3+3);
+ data_p3[temp_pos3+2] = 0;
+ USART3_task_temp.len = temp_pos3+3;
+ USART3_task_temp.pstr=data_p3;
+ USART3_task_temp.type=USART_SERVER;
+ err=xQueueSend(USART3_Task_server_Queue,&USART3_task_temp,10);
+ if(err==errQUEUE_FULL) //Ϣ֡
+ {
+ //ʧҪfreeڴ
+ vPortFree(USART3_task_temp.pstr);
+ dprintf("USART3_Task_rn_other_Queueݷserverʧ!\r\n");
+ }
+ data_num_remain3-=temp_pos3+2;
+ data_temp3+=temp_pos3+2;
+
+ }
+ else
+ {
+ data_p3=pvPortMalloc(data_num_remain3);
+ memcpy(data_p3,data_temp3,data_num_remain3);
+ USART3_task_temp.len = data_num_remain3;
+ USART3_task_temp.pstr=data_p3;
+ USART3_task_temp.type=USART_OTHER;
+ err=xQueueSend(USART3_Task_rn_other_Queue,&USART3_task_temp,10);
+ data_num_remain3 = 0;
+
+ if(err==errQUEUE_FULL) //Ϣ֡
+ {
+ //ʧҪfreeڴ
+ vPortFree(USART3_task_temp.pstr);
+ dprintf("USART3_Task_rn_other_QueueݷOTHERʧ!\r\n");
+ }
+ break;
+ }
+
+
+ }
+ else//ʼλм ҲǷ֮ǰ ʼλþʼ־
+ {
+ {
+ data_p3=pvPortMalloc(temp_pos3);
+ memcpy(data_p3,data_temp3,temp_pos3);
+ USART3_task_temp.len = temp_pos3;
+ USART3_task_temp.pstr=data_p3;
+ USART3_task_temp.type=USART_OTHER;
+ err=xQueueSend(USART3_Task_rn_other_Queue,&USART3_task_temp,10);
+ if(err==errQUEUE_FULL) //Ϣ֡
+ {
+ //ʧҪfreeڴ
+ vPortFree(USART3_task_temp.pstr);
+ dprintf("USART3_Task_rn_other_QueueݷOTHERʧ!\r\n");
+ }
+ }
+
+ data_num_remain3-=temp_pos3;
+ data_temp3+=temp_pos3;
+ }
+ }
+ //ݣͷbuffռ
+ release_buff3(USART3_temp.buff_now);//ͷbuffռ״̬
+ }
+ break;
+
+
+ }
+ }
+
+ vTaskDelay(50); //ʱ10msҲ10ʱӽUSART3_task_delay
+ }
+}
+
+//ֵź
+SemaphoreHandle_t BinarySemaphore_free; //ֵź
+
+
+//USART3_taskлڶ֡ݳִҪfree ڴIJ
+void FREE_ERRORMEM_task(void *pvParameters)
+{
+ BaseType_t err;
+ dprintf("FREE_ERRORMEM_task success\r\n");
+ while(1)
+ {
+ if(BinarySemaphore_free!=NULL)
+ {
+ err=xSemaphoreTake(BinarySemaphore_free,portMAX_DELAY); //ȡź
+// err=xSemaphoreTake(BinarySemaphore_free,0); //ȡź
+ if(err==pdTRUE) //ȡźɹ
+ {
+ USART3_task_process = USART_DATA_IDEL;
+ vPortFree(USART3_task_temp.pstr);//жfreeҪⲿtaskнв
+ dprintf("free_mem sucess!\r\n");
+ }
+ else if(err==pdFALSE)
+ {
+ vTaskDelay(FREE_ERRORMEM_delay); //ʱ10msҲ10ʱӽ
+ }
+ }
+ //ʱ10msҲ10ʱӽ
+ }
+}
+
+//ͶУݷŵͶУз
+
+
+QueueHandle_t USART3_Send_Queue;//3Ͷ
+//3Ϣ
+void USART3_send_task(void *pvParameters)
+{
+ usart_task_data usart3_send_temp;
+ char at_cipsend[30];
+
+ dprintf("usart3_send start\r\n");
+ while(1)
+ {
+ if(xQueueReceive(USART3_Send_Queue,&usart3_send_temp, 0))
+// if(xQueueReceive(USART3_Send_Queue,&usart3_send_temp, portMAX_DELAY))//ͶҪ
+ {
+ if(usart3_send_temp.type ==USART_SERVER)
+ {
+ if(touch_flag&(0x0001<<14))
+ {
+ if(xSemaphoreTake(SendenableMutexSemaphore,portMAX_DELAY))//һһûյִͻҲ һʱʱԶͷţܷ
+ {
+ xTimerStart(OneShot_CanServer_Handle,10);
+ }
+ }
+
+ {
+ //dprintf("send server\r\n");
+ sprintf(at_cipsend,"AT+CIPSEND=%d\r\n",usart3_send_temp.len);
+ u3_senddata((uint8_t*)at_cipsend,strlen(at_cipsend));
+ vTaskDelay(50); //busy 150
+ free_usart3_rn_other_queue();//
+ u3_senddata(usart3_send_temp.pstr,usart3_send_temp.len);
+ }
+ }
+ else if(usart3_send_temp.type ==USART_RN)
+ {
+ u3_senddata(usart3_send_temp.pstr,usart3_send_temp.len);
+ if(usart3_send_temp.type ==USART_RN) u3_senddata((uint8_t*)"\r\n",2);
+
+ }
+ vPortFree(usart3_send_temp.pstr);
+ #if 0
+
+
+ //жͣǷݷ͵
+ //ҪӷģָҪں油\R\N
+ if(usart3_send_temp.type ==USART_SERVER)
+ {
+ //ȴź
+ if(touch_flag&(0x0001<<14))
+ {
+// while(!u3cansend);
+ if(xSemaphoreTake(SendenableMutexSemaphore,portMAX_DELAY)) //ȡź
+ {
+
+ }
+ }
+
+ dprintf("send server\r\n");
+ sprintf(at_cipsend,"AT+CIPSEND=%d\r\n",usart3_send_temp.len);
+ u3_senddata((uint8_t*)at_cipsend,strlen(at_cipsend));
+ vTaskDelay(150);
+ free_usart3_rn_other_queue();//
+
+ }
+
+
+// taskENTER_CRITICAL(); //ٽ
+ u3_senddata(usart3_send_temp.pstr,usart3_send_temp.len);
+
+// taskEXIT_CRITICAL(); //˳ٽ
+ if(usart3_send_temp.type ==USART_RN) u3_senddata((uint8_t*)"\r\n",2);
+ vPortFree(usart3_send_temp.pstr);
+// if(usart3_send_temp.type ==USART_SERVER) //vTaskDelay(100); //ݷҪʱϳ
+// check_msg_queue();
+ u3cansend=0;
+ #endif
+ }
+ vTaskDelay(USART3_SEND_delay );
+ }
+
+}
+
+void CanServer_Callback(TimerHandle_t xTimer)
+{
+ xSemaphoreGive(SendenableMutexSemaphore); //ͷź
+}
+
+#define U3toU1 0
+
+ //3senddata
+void u3_senddata(uint8_t *data,uint16_t length)
+{
+ uint16_t j;
+// i=length; //˴ηݵij
+// PTK_SERIAL++;
+// RTC_ONLINE=RTC_SEC;
+ uart3 ->uart_write(data,length);
+}
+
+
+
+
+
+
+//end USART3task.c
+
diff --git a/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/usart3task/usart3task.h b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/usart3task/usart3task.h
new file mode 100644
index 00000000..6e0d28b5
--- /dev/null
+++ b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/usart3task/usart3task.h
@@ -0,0 +1,64 @@
+/*
+ * usart3task.h
+ *
+ * Created on: 201853
+ * Author: Administrator
+ */
+
+#ifndef USART3TASK_USART3TASK_H_
+#define USART3TASK_USART3TASK_H_
+
+#include "stdio.h"
+#include "task_config.h"
+#include "app_config.h"
+//ʹucos,ͷļ.
+#if 1
+#include "FreeRTOS.h" //FreeRTOSʹ
+#include "task.h"
+#include "queue.h"
+#include "semphr.h"
+#endif
+//////////////////////////////////////////////////////////////////////////////////
+//////////////////////////////////////////////////////////////////////////////////
+
+//#define USART_REC_LEN 200 //ֽ 200
+
+
+
+extern TaskHandle_t FREE_ERRORMEM_Handler;
+extern TaskHandle_t USART3_Handler;
+extern TaskHandle_t USART3_send_Handler;
+
+
+extern uint8_t usart3_data_all[USART3_NUM][USART3_PER_LEN];//1buff
+extern uint16_t USART3_RX_STA; //״̬
+extern uint8_t usart3_buff_flag;//Щ鱻ʹˣ´ĸд
+extern uint8_t usart3_time_out;//1ճʱʱ
+extern uint8_t usart3_task_time_out;//1 taskճʱʱ
+
+extern QueueHandle_t USART3_Queue;
+//extern QueueHandle_t USART3_Task_Queue;
+extern QueueHandle_t USART3_Task_server_Queue;//洢
+extern QueueHandle_t USART3_Task_rn_other_Queue;//洢\r\nݺûиʽ
+extern QueueHandle_t USART3_Send_Queue;//3Ͷ
+extern SemaphoreHandle_t BinarySemaphore_free; //ֵź
+
+extern usart_dat usart3_data;
+extern USART_TASK_PROCESS usart3_task_process;//ݴ̱
+extern usart_task_data usart3_task_temp;//͵usart3task
+extern DEV_UART *uart3;
+//봮жϽգ벻Ҫעº궨
+uint32_t uart3_init(uint32_t bound);
+void release_buff3(uint8_t buff_num);
+void occupy_buff3(void);
+void USART3_task(void *pvParameters);
+void USART3_IRQHandler(void);
+//USART1_taskлڶ֡ݳִҪfree ڴIJ
+void FREE_ERRORMEM_task(void *pvParameters);
+
+void u3_senddata(uint8_t *data,uint16_t length);
+void USART3_send_task(void *pvParameters);
+void CanServer_Callback(TimerHandle_t xTimer);
+
+
+#endif /* USART3TASK_USART3TASK_H_ */
diff --git a/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/usart4task/usart4task.c b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/usart4task/usart4task.c
new file mode 100644
index 00000000..f5e47cb6
--- /dev/null
+++ b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/usart4task/usart4task.c
@@ -0,0 +1,638 @@
+/*
+ * usart4task.c
+ *
+ * Created on: 2018516
+ * Author: Administrator
+ */
+
+#include "usart4task.h"
+#include "usart1task.h"//printf
+#include "ESP8266.h"
+//#include "bright.h"
+#include "fifo.h"
+#include "timer.h"
+#include "task_config.h"
+#include "package.h"
+#include "bright.h"
+#include "irf.h"
+
+//#include "timer.h"
+//#include "key.h"
+#include "malloc.h"
+#include "string.h"
+
+
+//
+#include "stdlib.h"
+
+#include "strpos.h"
+//ģڲз֡IJֱFIFOĻbuffÿηFIFOյݸӦòֱӴЩ
+//ذ崮
+#define delay_ms vTaskDelay
+#define CMD_WAIT_MAX 5
+#define EMSK_GPIO_CHECK_EXP_NORTN(EXPR) CHECK_EXP_NOERCD(EXPR, error_exit)
+#define BTN_ACTIVE_LOW (0)
+
+uint8_t usart4_fifo_data[USART4_FIFO_LEN];
+uint8_t usart4_send_data[USART4_SEND_LEN];
+fifo_struct usart4_fifo;//4ݴ洢FIFO fifo
+fifo_struct usart4_send_fifo;
+suart_struct uart4_ctr;//ģ4ĿƲ
+suart_send_struct send_ctr4;
+
+//봥ذͨſ
+uint8_t wait_cmd=0,wait_cmd_count=0;
+uint16_t touch_flag=0;//¼ذIJͬλģʽȫִ洢ƹλwifi״̬ ̨ƿ״̬wifiset״̬״̬
+
+TaskHandle_t USART4_app_Handler;//
+TimerHandle_t period_waittouch_Handle;
+QueueHandle_t USART4_Queue;
+QueueHandle_t USART4_Send_Queue;
+DEV_GPIO * uart4;
+
+
+void suart_var_init(suart_struct* re_ctr)
+{
+ re_ctr->byte = 0;
+ re_ctr->bytenum = 0;
+ re_ctr->count = 0;
+ re_ctr->flag = 0;
+ re_ctr->timeout = 0;
+// sd_ctr->bit_flag = 0;
+// sd_ctr->byte_now = 0;
+}
+
+void suart_send_var_init(suart_send_struct* sd_ctr)
+{
+ sd_ctr->bit_flag = 0;
+ sd_ctr->byte_now = 0;
+ sd_ctr->send_flag = 0;
+ sd_ctr->tim_count = 0;
+}
+
+
+#define EMSK_GPIOUART4_PORT DEV_GPIO_PORT_A
+#define GPIO_UART4_MASK 0x00030000 //portA16-17PinJ37-8
+#define GPIO_UART4_LOW (0)
+#define GPIO_UART4IN_MASK 0X00010000 //portA16PinJ37
+#define GPIO_UART4OUT_MASK 0X00020000 //portA17PinJ38
+
+
+
+//һbyte
+void EXTI1_IRQHandler(void *ptr)
+{
+ uart4->gpio_control(GPIO_CMD_DIS_BIT_INT, (void *)GPIO_UART4IN_MASK);
+ uart4_ctr.count=0;
+ uart4_ctr.byte = 0;
+ uart4_ctr.flag = 1;
+
+// BaseType_t xHigherPriorityTaskWoken;
+
+// uart4_ctr.flag = 0;
+ #if 1//ʱ
+ /*
+ uint32_t temp;
+ delay_us(104+52);
+ uart4_ctr.count=0;
+ uart4_ctr.byte = 0;
+ printf("i'm coming in!\r\n");
+ for(uart4_ctr.count=0;uart4_ctr.count<8;uart4_ctr.count++)
+ {
+ uart4->gpio_read(&temp, GPIO_UART4IN_MASK);
+ uart4_ctr.byte |= (temp<<(uart4_ctr.count));
+ delay_us(104);
+ }
+// delay_us(104);
+ write_fifo(&usart4_fifo,&uart4_ctr.byte,1);
+ uart4_ctr.timeout = 0x80;
+ uart4_ctr.bytenum++;//Ҫжж֡
+
+// EXTI_ClearITPendingBit(EXTI_Line1);
+ * */
+
+ #else//ʱ
+ {
+ TIM_Cmd(TIM4,ENABLE);
+ #if 1
+
+ #else//Ƶʱ
+ while(!(uart4_ctr.flag));//ڶʱпⲿжϣЧ
+
+ write_fifo(&usart4_fifo,&uart4_ctr.byte,1);
+ uart4_ctr.timeout = 0x80;
+ uart4_ctr.bytenum++;//Ҫжж֡
+ if(uart4_ctr.bytenum>USART4_FIFO_LEN)
+ {
+ xQueueSendFromISR(USART4_Queue,&uart4_ctr.bytenum,&xHigherPriorityTaskWoken);//з
+ uart4_ctr.bytenum = 0;
+ portYIELD_FROM_ISR(xHigherPriorityTaskWoken);//ҪĻһл
+ }
+
+ TIM_Cmd(TIM4,DISABLE);
+ EXTI_ClearITPendingBit(EXTI_Line1);
+ #endif
+ }
+ #endif
+
+}
+
+uint8_t senddata_by_usart4(uint8_t*str,uint8_t len)//ⲿ÷ͺ
+{
+ usart_task_data USART4_send_data;//USART3send
+ uint8_t*p;
+ BaseType_t err;
+
+ USART4_send_data.type = USART_DIRECT;
+
+ USART4_send_data.len = len;
+ p = pvPortMalloc(USART4_send_data.len);
+ memcpy(p,str,USART4_send_data.len);
+ USART4_send_data.pstr = p;
+
+ err=xQueueSend(USART4_Send_Queue,&USART4_send_data,0);
+ if(err==errQUEUE_FULL) //Ϣ֡
+ {
+ //ʧҪfreeڴ
+ vPortFree(USART4_send_data.pstr);
+ dprintf("USART4_Send_Queueݷʧ!\r\n");
+ return 0;
+ }
+ else return 1;
+}
+
+void u4app_send(uint8_t*str,uint8_t len)//ڲú
+{
+ #define DELAY_1bit 90
+ #define DELAY_1bit2 92
+ #if 1//͵fifo
+ write_fifo(&usart4_send_fifo,str,len);
+// TIM_Cmd(TIM5,ENABLE);
+
+ #else//ʱ
+ uint8_t i,j,data;
+// taskENTER_CRITICAL(); //ٽ
+ for(i=0;igpio_write((~GPIO_UART4OUT_MASK), GPIO_UART4OUT_MASK);
+ data = str[i];
+// printf("1\r\n");
+ delay_us(DELAY_1bit2);
+// printf("1\r\n");
+ for(j=0;j<8;j++)
+ {
+ //PBout(0) =(data&0x01);
+ uart4->gpio_write(((data&0x01)<<17), GPIO_UART4OUT_MASK);
+// uart4->gpio_write(GPIO_UART4OUT_MASK, GPIO_UART4OUT_MASK);
+ data=data>>1;
+ delay_us(DELAY_1bit);
+ }
+ //PBout(0) = 1;
+ uart4->gpio_write(GPIO_UART4OUT_MASK, GPIO_UART4OUT_MASK);
+ delay_us(DELAY_1bit2);
+ }
+// taskEXIT_CRITICAL(); //˳ٽ
+ #endif
+}
+
+void usart4_init(void)
+{
+ DEV_GPIO_BIT_ISR bit_isr;
+ DEV_GPIO_INT_CFG int_cfg;
+
+ init_fifo(&usart4_fifo,USART4_FIFO_LEN,usart4_fifo_data);//ʼ4 Ľfifo
+ init_fifo(&usart4_send_fifo,USART4_SEND_LEN,usart4_send_data);//ʼ4 Ľfifo
+ suart_var_init(&uart4_ctr);
+ suart_send_var_init(&send_ctr4);
+
+ uart4 = gpio_get_dev(EMSK_GPIOUART4_PORT);
+
+ EMSK_GPIO_CHECK_EXP_NORTN(uart4 != NULL);
+ if (uart4->gpio_open(GPIO_UART4_MASK) == E_OPNED) {
+ uart4->gpio_control(GPIO_CMD_SET_BIT_DIR_OUTPUT, (void *)(GPIO_UART4OUT_MASK));
+ uart4->gpio_control(GPIO_CMD_SET_BIT_DIR_INPUT, (void *)(GPIO_UART4IN_MASK));
+ uart4->gpio_control(GPIO_CMD_DIS_BIT_INT, (void *)(GPIO_UART4_MASK));
+ }
+ int_cfg.int_bit_mask = GPIO_UART4IN_MASK;
+ int_cfg.int_bit_type = GPIO_UART4IN_MASK;
+ int_cfg.int_bit_polarity = BTN_ACTIVE_LOW;
+ int_cfg.int_bit_debounce = (~GPIO_UART4IN_MASK);
+ uart4->gpio_control(GPIO_CMD_SET_BIT_INT_CFG, &int_cfg);
+ bit_isr.int_bit_ofs = 16;
+ bit_isr.int_bit_handler = EXTI1_IRQHandler;
+ uart4->gpio_control(GPIO_CMD_SET_BIT_ISR, &bit_isr);
+ uart4->gpio_control(GPIO_CMD_ENA_BIT_INT, (void *)GPIO_UART4IN_MASK);
+ uart4->gpio_write(GPIO_UART4OUT_MASK,GPIO_UART4OUT_MASK);
+error_exit:
+ return;
+}
+
+
+
+
+void USART4_app_task(void *pvParameters)
+{
+ uint8_t nlen=0;
+ uint8_t* p;
+ uint8_t* buffer;
+ usart_task_data usart_send4;
+ BaseType_t err;
+
+ dprintf("usart4_app_task start!\r\n");
+ while(1)
+ {
+ if(xQueueReceive(USART4_Queue,&nlen,0))//
+ {
+ uint8_t i;
+ p = pvPortMalloc(nlen);
+ read_fifo(&usart4_fifo,p,nlen);
+
+ #if 0//Դ
+ buffer = pvPortMalloc(nlen+1);
+ memcpy(buffer , p , nlen);
+ buffer[nlen] = 0;
+ dprintf("u4re %d:%x\r\n",nlen,buffer[0]);
+ vPortFree(buffer);
+// dprintf("u4fifo:");
+// for(nlen=0;nlen0)//Խ˯ģʽ ҪжħǷҴ״̬
+ {
+
+ }
+ else//鵵˳˯ģʽ
+ {
+ touch_flag&=(~(0x0001<<9));
+
+ }
+
+ //¼wifi״̬
+ if(wifi)
+ {
+ touch_flag|=(0x0001<<4);
+ }
+ else
+ {
+ touch_flag&=(~(0x0001<<4));
+ }
+
+ //0002
+// sendpack2server(0x0002);
+ sprintf(say2server_temp,"light mode:touch %1d",touch_flag&0x000f);
+ say2server(say_did, say2server_temp);
+ //wifi
+ if(touch_flag&(0x0001<<14))
+ {
+// dprintf("try send wifi on\r\n");
+ mcu_sendcmd2touch(Wifi_On);
+ }
+ else
+ {
+ mcu_sendcmd2touch(Wifi_Off);
+ }
+ }
+}
+
+//ʱڷͰƣȴذӦ
+void period_waittouch_Callback(TimerHandle_t xTimer) //
+{
+ dprintf("wait_touch run:%d\r\n",wait_cmd_count);
+ if(wait_cmd_count>1)
+ {
+ wait_cmd_count--;
+ senddata_by_usart4(&wait_cmd,1);
+ }
+ else
+ {
+ //رնʱ
+ wait_cmd_count = 0;
+ xTimerStop(period_waittouch_Handle,0);
+ }
+}
+
+//ذ巢
+void mcu_sendcmd2touch(uint8_t cmd)
+{
+// uint8_t temp;
+// temp = cmd;
+// senddata_by_usart4(&temp,1);
+ senddata_by_usart4(&cmd,1);
+}
+
+//32Ƶƹʹذ壬벻ͬģʽ 8003[22] Ӧ
+void server_control_light(uint8_t mode)
+{
+ if(mode)//
+ {
+ if(mode&0x10)//Զ
+ {
+ mcu_sendcmd2touch(Power_On|0x10);//ңwifi
+ touch_process_poweron();
+
+ }
+ else if(mode&0x20)//λ ﵥдƵIJ˳Զģʽ
+ {
+ //ƴذ嵽
+ mcu_sendcmd2touch(0xf0|((mode&0x0f)-1));
+
+ //ǿ
+ touch_flag|=(0x0001<<7);
+ //ڵƹӦλ
+ touch_flag&=0xfff0;
+ touch_flag|=(mode&0x0f);//¼ƹλ
+ bright_mode(LIGHT_SWITCH,touch_flag&0x000F);
+
+ //жǷ˯ģʽ
+ if((mode&0x0f)<4)//Խ˯ģʽ ҪжħǷҴ״̬
+ {
+
+ }
+ else//鵵˳˯ģʽ
+ {
+ touch_flag&=(~(0x0001<<9));
+
+ }
+
+ //¼wifi״̬
+ touch_flag|=(0x0001<<4);
+
+ //0002
+ sendpack2server(0x0002);
+ }
+ }
+ else//power off 0x00
+ {
+ mcu_sendcmd2touch(Power_Off);
+ touch_process_poweroff();
+ }
+}
+
+//end USART4task.c
diff --git a/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/usart4task/usart4task.h b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/usart4task/usart4task.h
new file mode 100644
index 00000000..aaa132e4
--- /dev/null
+++ b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/app/usart4task/usart4task.h
@@ -0,0 +1,64 @@
+/*
+ * usart4task.h
+ *
+ * Created on: 2018516
+ * Author: Administrator
+ */
+
+#ifndef USART4TASK_USART4TASK_H_
+#define USART4TASK_USART4TASK_H_
+
+#include "stdio.h"
+
+
+#include "task_config.h"
+#include "app_config.h"
+//ʹucos,ͷļ.
+#if 1
+#include "FreeRTOS.h" //FreeRTOSʹ
+#include "task.h"
+#include "queue.h"
+#include "semphr.h"
+#endif
+//////////////////////////////////////////////////////////////////////////////////
+//////////////////////////////////////////////////////////////////////////////////
+
+//#define USART_REC_LEN 200 //ֽ 200
+//#define EN_USART4_RX 0
+#define USART4_FIFO_LEN 50//4ĽFIFOС
+#define USART4_SEND_LEN 50//fifoС
+
+extern suart_struct uart4_ctr;//ģ4ĿƲ
+extern fifo_struct usart4_send_fifo;
+extern suart_send_struct send_ctr4;
+extern fifo_struct usart4_fifo;//4ݴ洢FIFO fifo
+extern QueueHandle_t USART4_Queue;
+extern QueueHandle_t USART4_Send_Queue;
+
+extern TaskHandle_t USART4_app_Handler;//
+extern TimerHandle_t period_waittouch_Handle;
+
+extern void usart4_init(void);
+void USART4_app_task(void *pvParameters);
+uint8_t senddata_by_usart4(uint8_t*str,uint8_t len);//ⲿ÷ͺ
+void suart_var_init(suart_struct* re_ctr);
+void period_waittouch_Callback(TimerHandle_t xTimer);
+void EXTI1_IRQHandler(void *ptr);
+void mcu_sendcmd2touch(uint8_t cmd);
+void server_control_light(uint8_t mode);
+//APPݴ
+void touch_process(uint8_t touch_cmd);
+void touch_process_poweroff(void);//poweroffĴ
+void touch_process_poweron(void);//poweronĴ Զ
+void touch_process_lightswitch(uint8_t light,uint8_t wifi);//ֱӵijλ
+
+#define EMSK_GPIOUART4_PORT DEV_GPIO_PORT_A
+#define GPIO_UART4_MASK 0x00030000 //portA16-17PinJ37-8
+#define GPIO_UART4_LOW (0)
+#define GPIO_UART4IN_MASK 0X00010000 //portA16PinJ37
+#define GPIO_UART4OUT_MASK 0X00020000 //portA17PinJ38
+extern DEV_GPIO * uart4;
+
+
+
+#endif /* USART4TASK_USART4TASK_H_ */
diff --git a/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/appinc/app_config.h b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/appinc/app_config.h
new file mode 100644
index 00000000..4095364c
--- /dev/null
+++ b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/appinc/app_config.h
@@ -0,0 +1,419 @@
+/*
+ * app_config.h
+ *
+ * Created on: 201853
+ * Author: Administrator
+ */
+
+#ifndef APPINC_APP_CONFIG_H_
+#define APPINC_APP_CONFIG_H_
+
+//ͷļ
+#include "embARC.h"
+#include "embARC_debug.h"
+//////////////////////////////////////////////////////////////////////////////////
+//////////////////////////////////////////////////////////////////////////////////
+/*******************궨***************************/
+//ú궨
+#define ASSERT_PRINTF_ENABLE 1//Եdprintfʹ
+
+//궨
+#define RX_LEN_DATA 1024*2//1024//ӷչ̼һεĹ̼
+
+#define SYS_CONFIG_START_ADDR 518144 //ϵͳsys_config 洢ڷflashеʼַ
+#define MCU_BIN_LENGTH_ADDR 522240 //MCU̼ȴ洢flashеʼַλ 4
+#define POWER_ON_VOICE_ADDR MCU_BIN_LENGTH_ADDR+4 //MP3mcuflag 1 sys_config ˱־
+
+//ذ尴
+#define Bright_0 0xEA//wifiƺ͵ԴƣλΪ0
+#define Bright_1 0xe0//ȵ
+#define Bright_2 0xe1
+#define Bright_3 0xe2
+#define Bright_4 0xe3
+#define Bright_5 0xe4
+#define Bright_6 0xe5
+#define Bright_7 0xe6
+#define Bright_8 0xe7
+
+#define Power_On 0xe8 //ذĵԴ
+#define Power_Off 0xc0
+#define Wifi_Set 0xca//Դ
+#define Wifi_Quit 0xc8
+#define Wifi_On 0xde//WiFiõ
+#define Wifi_Off 0xce
+#define TOUCH_ON 0xc0 //ذ岻Ӧ
+#define TOUCH_OFF 0x80
+#define Boot_Start 0xcc
+#define Boot_End 0xc8
+//
+//receiveеϢָ룬Ҫfree
+//Ϣ
+#define KEYMSG_Q_NUM 2 //Ϣе
+#define USART1_Q_NUM 4 //1г USART1_NUM ײ㻺
+#define USART1_TASK_Q_NUM 4 //1֡ݶг
+#define USART3_Q_NUM 8 //3г USART3_NUM ײ㻺
+#define USART3_TASK_SERVER_Q_NUM 10 //3֡SERVERݶг
+#define USART3_TASK_RN_OTHER_Q_NUM 10 //3֡\R\Nûбǵ ݶг
+#define USART3_Send_Q_NUM 10 //3Ͷ
+#define pack2server_Q_NUM 5 //İ֡
+#define connect_to_server_Q_NUM 1 //ӷ
+#define USART4_Q_NUM 10
+#define USART4SEND_Q_NUM 10
+#define USART5_Q_NUM 10
+#define USART5SEND_Q_NUM 10
+#define SuperSound_Q_NUM 4
+#define Dprintf_Q_NUM 10
+
+//ڻ
+#define EN_USART1_RX 1 //ʹܣ1/ֹ01
+#define USART1_PER_LEN 50 //ÿbuffС
+#define USART1_NUM USART1_Q_NUM //ܹbuff 8Ϊõu8ı
+
+#define EN_USART3_RX 1 //ʹܣ1/ֹ01
+#define USART3_PER_LEN 200 //ÿbuffС
+#define USART3_NUM USART3_Q_NUM//ܹbuff 8Ϊõu8ı
+
+#define USART4_PER_LEN 50 //ÿbuffС
+#define USART4_NUM USART4_Q_NUM//ܹbuff 8Ϊõu8ı
+#define USART5_NUM USART5_Q_NUM//ܹbuff 8Ϊõu8ı
+
+//extern u8 usart3_data_all[USART3_NUM][USART3_PER_LEN];//3ײ㻺buff
+
+/******************ʱغ궨********************/
+//wifiʹõʱ
+//60sʱ
+//TIM60
+#define WIFI_TIM60S_TICKS 60*1000/portTICK_PERIOD_MS
+//TIM_ID
+#define WIFI_TIM60S_ID 1
+
+//10sʱ
+//TIM10
+#define WIFI_TIM10S_TICKS 10*1000/portTICK_PERIOD_MS
+//TIM_ID
+#define WIFI_TIM10S_ID 2
+
+//ʱͰ0002 40s5s
+//ticks
+#define PKG0002_40S_TICKS 40*1000/portTICK_PERIOD_MS
+#define PKG0002_5S_TICKS 5*1000/portTICK_PERIOD_MS
+//TIM_ID
+#define PKG0002_TIM_ID 3
+
+
+
+//ⴥذִźŶʱ 50MS
+//ticks
+#define WAIT_TOUCH_TICKS 250/portTICK_PERIOD_MS
+//TIM_ID
+#define WAIT_TOUCH_ID 4
+
+#define WIFI_1MS_TICKS 1/portTICK_PERIOD_MS
+#define WIFI_TIM1MS_ID 5
+
+//ʱʹܷ5s
+//ticks
+#define CanServer_TICKS 5*1000/portTICK_PERIOD_MS
+//TIM_ID
+#define CanServer_ID 6
+
+//ʱڵƹ
+//ticks
+#define Bright_TICKS 10/portTICK_PERIOD_MS//200 -10 66-30
+//TIM_ID
+#define Bright_ID 7
+#define Bright_bei 3
+/******************غ궨********************/
+//ʼ
+//ȼ
+#define START_TASK_PRIO 1
+//ջС
+#define START_STK_SIZE 128
+
+//
+//ȼ
+#define TASK1_TASK_PRIO 2//2
+//ջС
+#define TASK1_STK_SIZE 128
+//м ms
+#define task1_task_delay 20//
+
+//
+//ȼ
+#define KEYPROCESS_TASK_PRIO 3//3
+//ջС
+#define KEYPROCESS_STK_SIZE 256
+//м ms
+#define Keyprocess_task_delay 20//
+
+
+//1 ݷ֡ ֡
+//ȼ
+#define USART1_TASK_PRIO 28
+//ջС
+#define USART1_STK_SIZE 128
+//м ms
+#define USART1_task_delay 50//м ms
+
+//1֡ݴ
+//ȼ
+#define USART1_APP_PRIO 13//Ƚȼ 13
+//ջС
+#define USART1_APP_SIZE 256
+//м ms
+#define USART1_APP_delay 100//м ms
+
+
+
+//8266 smartconfig
+//ȼ
+#define SMARTCONFIG_TASK_PRIO 19//ڴ3ʹذȼͿԣʱֻ⼸ִ19
+//ջС
+#define SMARTCONFIG_TASK_SIZE 256
+//м ms
+#define SMARTCONFIG_TASK_delay 50//м ms
+
+//8266 connect t0 server
+//ȼ
+#define connect_to_server_PRIO 18//smart18
+//ջС
+#define connect_to_server_SIZE 256
+//м ms
+#define connect_to_server_delay 50//м ms
+
+
+//3 ݷ֡ ֡
+//ȼ
+#define USART3_TASK_PRIO 29
+//ջС
+#define USART3_STK_SIZE 128
+//м ms
+#define USART3_task_delay 50//м ms
+
+//3 պݳʱΪݴ freeڴ棬ʼidelģʽ
+//ȼ
+#define FREE_ERRORMEM_PRIO 30
+//ջС
+#define FREE_ERRORMEM_SIZE 96
+//м ms
+#define FREE_ERRORMEM_delay 50//м ms
+
+//3ݷ
+//ȼ
+#define USART3_SEND_PRIO 20//Ƚȼ20
+//ջС
+#define USART3_SEND_SIZE 256+256
+//м ms
+#define USART3_SEND_delay 50//м ms
+
+//3ݴ
+//ȼ
+#define USART3_APP_PRIO 14//Ƚȼ14
+//ջС
+#define USART3_APP_SIZE 256
+//м ms
+#define USART3_APP_delay 50//м ms
+
+
+//ݴ
+//ȼ
+#define pack2server_PRIO 13//Ƚȼ13
+//ջС
+#define pack2server_SIZE 256
+//м ms
+#define pack2server_delay 50
+
+//4
+//ȼ
+#define USART4_APP_PRIO 27//13
+//ջС
+#define USART4_APP_SIZE 256
+//м ms
+#define USART4_APP_delay 30//м ms
+
+//5
+//ȼ
+#define USART5_APP_PRIO 15//15
+//ջС
+#define USART5_APP_SIZE 256
+//м ms
+#define USART5_APP_delay 50//м ms
+
+//
+//ȼ
+#define IRF_APP_PRIO 15//10 4
+//ջС
+#define IRF_APP_SIZE 256
+//м ms
+#define IRF_APP_delay 100//м ms
+
+//MP3
+//ȼ
+#define MP3_TASK_PRIO 10//10 4
+//ջС
+#define MP3_TASK_SIZE 128
+//м ms
+#define MP3_TASK_delay 100//м ms
+/**************״̬ö*****************************/
+//ڷ֡ݵ
+typedef enum
+{
+ USART_RN, //յ\r\n
+ USART_SERVER, //յ·Эʽ
+ USART_DIRECT, //ֱӷ͵ݣ˳+
+ USART_OTHER, //ʽԵ
+
+}USART_DATA_TYPE;
+//tasḵ֡֡
+typedef enum
+{
+ USART_DATA_NORMAL_START,//ͨ֡ʼ
+ USART_DATA_NORMAL_STOP, //ͨ֡
+ USART_DATA_RN_STOP, //\r\n֡
+ USART_DATA_SERVER_START,//յЭʼ
+ USART_DATA_SERVER_STOP, //յЭĽ
+ USART_DATA_WAIT,//ȴһbuffݽ֡
+ USART_DATA_IDEL,//ûյ
+}USART_TASK_PROCESS;
+/**************ṹ*******************************/
+//taskԴݷ֡Ľ
+typedef struct
+{
+ uint8_t* pstr;//ݴ洢λ
+ uint32_t len;//ܳ
+ USART_DATA_TYPE type;//֡õݵ
+}usart_task_data;
+
+//ݴ ڶ
+typedef struct
+{
+ uint8_t buff_now;//ݴ洢
+ uint8_t len;//ݳ
+}usart_dat;
+
+//FIFOṹ
+typedef struct
+{
+ uint8_t* pstr;//洢
+ uint16_t total_len;//FIFOܴС
+ uint16_t now_len;//ǰFIFOݸ
+ uint16_t read_pos;
+ uint16_t write_pos;
+}fifo_struct;
+
+//ģöʱƽһbyteĿƱ
+typedef struct
+{
+ uint8_t flag;
+ uint8_t count;
+ uint8_t byte;
+ uint8_t timeout;
+ uint8_t bytenum;
+}suart_struct;
+//ģöʱƷһbyteĿƱ
+typedef struct
+{
+ uint8_t bit_flag;//byteĵڼλ
+ uint8_t byte_now;//ǰ͵ݻ
+ uint8_t send_flag;
+ uint8_t tim_count;
+}suart_send_struct;
+
+//
+typedef enum
+{
+ SOUND_FLAG_IDEL,
+ SOUND_FLAG_TRI_START,
+ SOUND_FLAG_PEDG_START,
+ SOUND_FLAG_NEDG_STOP
+}SOUND_FLAG_ENUM;
+
+typedef struct
+{
+ uint64_t tim_start;
+ uint64_t tim_stop;
+ uint64_t tim_result;
+ uint64_t tim_ctr_start;
+ uint64_t tim_ctr_stop;
+
+ SOUND_FLAG_ENUM flag;
+ uint8_t count;
+
+
+}supersound_struct;
+
+//ϵͳṹ
+//ӽṹԱʱռÿռС
+//flash ҪȡflashڽṹĴȷ
+#pragma pack (4)
+typedef struct
+{
+ //
+ uint8_t boot_flag;//0x66 ҪΪ0x00 bootҪ
+
+ //Ƿʼflash
+ uint8_t flash_init;// ʼɴ洢һ0x55
+
+ //ħص
+ uint8_t modou_update;//ڹģʽڽģʽ 0 /r/n ģʽ || 1: ħģʽ
+ uint8_t angle_correct_plus;//ҽǶ
+// uint8_t last_LR_angle; //һεУ
+ uint8_t power_on_add_voice;//ǷţMP3ɣ̼
+
+ //MP3ĸ
+ uint8_t MP3_STA; //MP3ĸ״̬
+ uint8_t MP3_NUM; //ڸµMP3Ŀ
+ uint8_t NEW_MP3_ID[4]; //Ҫµ
+ uint8_t MP3_ID[80]; //MP3
+ uint8_t MP3_LEN[4]; //ǰMP3ļ
+
+ //̨ư汾 ID µ°汾Լ̼С
+ uint8_t bin_receive_flag;//binļ״̬0δܣ1 ڽܣ2
+
+ uint8_t S_HW[4]; //ID3ݰ
+ uint8_t S_SW[4]; //
+ uint8_t S_SERIAL[8]; //
+ uint8_t angle_correct; //
+ uint8_t LAMP_MODEL[4]; //̨ͺ
+ uint8_t NEW_S_SW[4]; //ħµ汾
+ uint8_t NEW_M_SW[4]; //̨Ƶµ汾
+ uint8_t FW_LEN[4]; //µĹ̼ij
+
+ uint8_t LAMP_HV[4]; //̨Ӳ汾
+ uint8_t LAMP_SV[4]; //̨汾
+ uint8_t M_SERIAL[8]; //̨к
+ //uint8_t MODOU_HV[4]; //ħӲ汾
+ //uint8_t MODOU_SV[4]; //ħ汾
+
+ uint8_t WIFI_SW[4];//wifi汾
+
+ //̨ƵıǶʱ
+ uint8_t ANGLE_ALARM1 ; //ǰ Ĭ20
+ uint8_t ANGLE_ALARM2 ; // Ĭ30
+ uint8_t ALERT_TIME1 ; //״αʱ䣬Ĭ5s
+ uint8_t ALERT_TIME2 ;//ظ180
+
+ uint16_t MUTE_START ;//ĬϾʼʱ0:00
+ uint16_t MUTE_END ;//ĬϾʱ7:00 420
+
+
+ uint32_t pkt_version;//Э汾
+
+ uint32_t mcu_bin_len; //mcu̼ij
+ uint32_t modo_bin_len;//ħ̼
+
+ uint32_t device_id;//flashȡ̨id
+
+ uint32_t SLEEP_START;
+ uint32_t SLEEP_END;
+
+
+}SYS_CONFIG;
+extern SYS_CONFIG sys_config;
+
+
+
+
+
+
+#endif /* APPINC_APP_CONFIG_H_ */
diff --git a/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/appinc/task_config.h b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/appinc/task_config.h
new file mode 100644
index 00000000..794e1300
--- /dev/null
+++ b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/appinc/task_config.h
@@ -0,0 +1,51 @@
+/*
+ * task_config.h
+ *
+ * Created on: 201853
+ * Author: Administrator
+ */
+
+#ifndef TASK_CONFIG_H_
+#define TASK_CONFIG_H_
+
+
+#include "../app/usart3task/usart3task.h"//printf
+#include "app_config.h"
+
+#include "FreeRTOS.h" //FreeRTOSʹ
+#include "task.h"
+#include "queue.h"
+#include "semphr.h"
+#include "timers.h"
+#include "usart1task.h"//printf
+
+extern uint16_t touch_flag;//ذģʽ
+
+extern SemaphoreHandle_t SendenableMutexSemaphore; //ź
+
+extern QueueHandle_t pack2server_queue;
+extern QueueHandle_t connect_to_server_Queue;
+
+//ļеõ
+extern TaskHandle_t Task1Task_Handler;
+extern TaskHandle_t Keyprocess_Handler;
+
+extern TaskHandle_t USART3_app_Handler;
+extern TaskHandle_t pack2server_Handler;
+extern TaskHandle_t smart_config_Handler;
+extern TaskHandle_t connect_to_server_Handler;
+
+extern TimerHandle_t OneShot_config60_Handle; //ζʱ60s
+extern TimerHandle_t OneShot_config10_Handle; //ζʱ10s
+extern TimerHandle_t period40or5_0002_Handle; //ʱ0002
+extern TimerHandle_t OneShot_config1MS_Handle;
+extern TimerHandle_t OneShot_CanServer_Handle; //ص²ٸ
+extern TimerHandle_t period_Bright_Handle; //ڵƹ
+
+void check_msg_queue(void);
+
+
+
+
+
+#endif /* TASK_CONFIG_H_ */
diff --git a/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/complete/main.c b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/complete/main.c
new file mode 100644
index 00000000..10f2fbc9
--- /dev/null
+++ b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/complete/main.c
@@ -0,0 +1,218 @@
+/* ------------------------------------------
+ * Copyright (c) 2017, Synopsys, Inc. All rights reserved.
+
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+
+ * 1) Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+
+ * 2) Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation and/or
+ * other materials provided with the distribution.
+
+ * 3) Neither the name of the Synopsys, Inc., nor the names of its contributors may
+ * be used to endorse or promote products derived from this software without
+ * specific prior written permission.
+
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+--------------------------------------------- */
+
+/**
+ * \defgroup EMBARC_APP_FREERTOS_KERNEL embARC FreeRTOS Kernel Example
+ * \ingroup EMBARC_APPS_TOTAL
+ * \ingroup EMBARC_APPS_OS_FREERTOS
+ * \brief embARC Example for testing FreeRTOS task switch and interrupt/exception handling
+ *
+ * \details
+ * ### Extra Required Tools
+ *
+ * ### Extra Required Peripherals
+ *
+ * ### Design Concept
+ * This example is designed to show the functionality of FreeRTOS.
+ *
+ * ### Usage Manual
+ * Test case for show how FreeRTOS is working by task switching and interrupt/exception processing.
+ * 
+ *
+ * ### Extra Comments
+ *
+ */
+
+/**
+ * \file
+ * \ingroup EMBARC_APP_FREERTOS_KERNEL
+ * \brief main source file of the freertos demo
+ */
+
+/**
+ * \addtogroup EMBARC_APP_FREERTOS_KERNEL
+ * @{
+ */
+
+#include "embARC.h"
+#include "embARC_debug.h"
+#include
+
+static void task1(void *par);
+static void task2(void *par);
+static void task3(void *par);
+
+#define TSK_PRIOR_1 (configMAX_PRIORITIES-1)
+#define TSK_PRIOR_2 (configMAX_PRIORITIES-2)
+#define TSK_PRIOR_3 (configMAX_PRIORITIES-3)
+
+// Semaphores
+static SemaphoreHandle_t sem1_id;
+
+// Queues
+static QueueHandle_t dtq1_id;
+
+// Task IDs
+static TaskHandle_t task1_handle = NULL;
+static TaskHandle_t task2_handle = NULL;
+static TaskHandle_t task3_handle = NULL;
+
+/**
+ * \brief call FreeRTOS API, create and start tasks
+ */
+int main(void)
+{
+
+ vTaskSuspendAll();
+
+ // Create Tasks
+ if (xTaskCreate(task1, "task1", 128, (void *)1, TSK_PRIOR_1, &task1_handle)
+ != pdPASS) { /*!< FreeRTOS xTaskCreate() API function */
+ EMBARC_PRINTF("Create task1 Failed\r\n");
+ return -1;
+ }
+ else
+ {
+ EMBARC_PRINTF("Create task1 Successfully\r\n");
+ }
+
+ if (xTaskCreate(task2, "task2", 128, (void *)2, TSK_PRIOR_2, &task2_handle)
+ != pdPASS) { /*!< FreeRTOS xTaskCreate() API function */
+ EMBARC_PRINTF("Create task2 Failed\r\n");
+ return -1;
+ }
+ else
+ {
+ EMBARC_PRINTF("Create task2 Successfully\r\n");
+ }
+
+ if (xTaskCreate(task3, "task3", 128, (void *)3, TSK_PRIOR_3, &task3_handle)
+ != pdPASS) { /*!< FreeRTOS xTaskCreate() API function */
+ EMBARC_PRINTF("Create task3 Failed\r\n");
+ return -1;
+ }
+ else
+ {
+ EMBARC_PRINTF("Create task3 Successfully\r\n");
+ }
+
+ // Create Semaphores
+ sem1_id = xSemaphoreCreateBinary();
+ xSemaphoreGive(sem1_id);
+
+ // Create Queues
+ dtq1_id = xQueueCreate(8, sizeof(uint32_t));
+
+ xTaskResumeAll();
+
+ vTaskSuspend(NULL);
+
+ return 0;
+}
+
+static void task1(void *par)
+{
+ uint32_t led_val = 0;
+
+ static portTickType xLastWakeTime;
+ const portTickType xFrequency = pdMS_TO_TICKS(10);
+
+ // 使用当前时间初始化变量xLastWakeTime ,注意这和vTaskDelay()函数不同
+ xLastWakeTime = xTaskGetTickCount();
+
+ while (1)
+ {
+ /* 调用系统延时函数,周期性阻塞10ms */
+ vTaskDelayUntil( &xLastWakeTime,xFrequency );
+
+ xQueuePeek(dtq1_id, (void *)(&led_val), portMAX_DELAY);
+
+ if(led_val >= 0x0100)
+ {
+ xSemaphoreGive(sem1_id);
+ }
+ }
+}
+
+static void task2(void *par)
+{
+ uint32_t led_val = 0x0001;
+
+ static portTickType xLastWakeTime;
+ const portTickType xFrequency = pdMS_TO_TICKS(100);
+
+ // 使用当前时间初始化变量xLastWakeTime ,注意这和vTaskDelay()函数不同
+ xLastWakeTime = xTaskGetTickCount();
+
+ while (1)
+ {
+ /* 调用系统延时函数,周期性阻塞100ms */
+ vTaskDelayUntil( &xLastWakeTime,xFrequency );
+
+ xQueueSend(dtq1_id, (void *)(&led_val), portMAX_DELAY);
+ led_val <<= 1;
+
+ if( sem1_id != NULL )
+ {
+ /*如果信号量无效,则最多等待10个系统节拍周期。*/
+ if( xSemaphoreTake( sem1_id, ( TickType_t ) 10 ) == pdTRUE )
+ {
+ xQueueReset(dtq1_id);
+ led_val = 0x0001;
+ }
+ }
+ }
+}
+
+static void task3(void *par)
+{
+ uint32_t led_val = 0;
+
+ static portTickType xLastWakeTime;
+ const portTickType xFrequency = pdMS_TO_TICKS(200);
+
+ // 使用当前时间初始化变量xLastWakeTime ,注意这和vTaskDelay()函数不同
+ xLastWakeTime = xTaskGetTickCount();
+
+ while (1)
+ {
+ /* 调用系统延时函数,周期性阻塞200ms */
+ vTaskDelayUntil( &xLastWakeTime,xFrequency );
+
+ xQueueReceive(dtq1_id, (void *)(&led_val), portMAX_DELAY);
+
+ led_write(led_val, BOARD_LED_MASK);
+
+ EMBARC_PRINTF("\r\n The led_val is 0x%x \r\n",led_val);
+ }
+
+}
+
+/** @} */
\ No newline at end of file
diff --git a/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/hardware/i2c/i2c.c b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/hardware/i2c/i2c.c
new file mode 100644
index 00000000..ef2d9f30
--- /dev/null
+++ b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/hardware/i2c/i2c.c
@@ -0,0 +1,212 @@
+/*
+ * i2c.c
+ *
+ * Created on: 2018523
+ * Author: Administrator
+ */
+
+#include "i2c.h"
+#include "timer.h"
+
+
+#define TASK_CRITICAL 0//Ƿٽʱ
+
+#define I2C_PORT DEV_GPIO_PORT_C
+#define GPIO_I2C_MASK 0x00030000 //portA16-17PinJ37-8
+#define GPIO_I2C_LOW (0)
+#define GPIO_I2CSDA_MASK 0X00010000 //portA16PinJ37
+#define GPIO_I2CSCL_MASK 0X00020000 //portA17PinJ38
+
+ #if TASK_CRITICAL
+#include "task_config.h"
+ #endif
+
+DEV_GPIO * iic_cm3232;
+
+void I2CC_Init(void)
+{
+ uint32_t temp = 0;
+// GPIO_InitTypeDef GPIO_InitStructure;
+// RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);
+//
+// GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6|GPIO_Pin_7; //PC12 11
+// GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
+// GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; //
+// GPIO_Init(GPIOC, &GPIO_InitStructure);
+ iic_cm3232 = gpio_get_dev(I2C_PORT);
+
+// EMSK_GPIO_CHECK_EXP_NORTN(uart4 != NULL);
+ if (iic_cm3232->gpio_open(GPIO_I2C_MASK) == E_OPNED) {
+ iic_cm3232->gpio_control(GPIO_CMD_SET_BIT_DIR_OUTPUT, (void *)(GPIO_I2CSCL_MASK));
+ iic_cm3232->gpio_control(GPIO_CMD_SET_BIT_DIR_INPUT, (void *)(GPIO_I2CSDA_MASK));
+ iic_cm3232->gpio_control(GPIO_CMD_DIS_BIT_INT, (void *)(GPIO_I2C_MASK));
+ }
+ iic_cm3232->gpio_write(GPIO_I2CSCL_MASK,GPIO_I2CSCL_MASK);
+// iic_cm3232->gpio_write(GPIO_I2CSDA_MASK,GPIO_I2CSDA_MASK);
+ iic_cm3232->gpio_read(&temp,GPIO_I2CSDA_MASK);
+// printf("%d",temp);
+
+// I2C_SCL=1;
+// I2C_SDA=1;
+}
+
+void I2C_Start(void)
+{
+ #if TASK_CRITICAL
+ taskENTER_CRITICAL(); //ٽ
+ #endif
+ iic_cm3232->gpio_control(GPIO_CMD_SET_BIT_DIR_OUTPUT, (void *)(GPIO_I2CSDA_MASK)); //sda
+ iic_cm3232->gpio_write(GPIO_I2CSDA_MASK,GPIO_I2CSDA_MASK); // I2C_SDA=1;
+ iic_cm3232->gpio_write(GPIO_I2CSCL_MASK,GPIO_I2CSCL_MASK); // I2C_SCL=1;
+ delay_us(4);
+ iic_cm3232->gpio_write((~GPIO_I2CSDA_MASK),GPIO_I2CSDA_MASK); // I2C_SDA=0;
+ delay_us(4);
+ iic_cm3232->gpio_write((~GPIO_I2CSCL_MASK),GPIO_I2CSCL_MASK); // I2C_SCL=0;
+ #if TASK_CRITICAL
+ taskEXIT_CRITICAL(); //˳ٽ
+ #endif
+}
+
+void I2C_Stop(void)
+{
+ #if TASK_CRITICAL
+ taskENTER_CRITICAL(); //ٽ
+ #endif
+ iic_cm3232->gpio_control(GPIO_CMD_SET_BIT_DIR_OUTPUT, (void *)(GPIO_I2CSDA_MASK));
+ iic_cm3232->gpio_write((~GPIO_I2CSCL_MASK),GPIO_I2CSCL_MASK); // I2C_SCL=0;
+ iic_cm3232->gpio_write((~GPIO_I2CSDA_MASK),GPIO_I2CSDA_MASK); // I2C_SDA=0;
+ delay_us(4);
+ iic_cm3232->gpio_write(GPIO_I2CSCL_MASK,GPIO_I2CSCL_MASK); // I2C_SCL=1;
+ iic_cm3232->gpio_write(GPIO_I2CSDA_MASK,GPIO_I2CSDA_MASK); // I2C_SDA=1;
+ delay_us(4);
+ #if TASK_CRITICAL
+ taskEXIT_CRITICAL(); //˳ٽ
+ #endif
+}
+
+uint8_t I2C_Wait_Ack(void)
+{
+ uint8_t ucErrTime=0;
+ uint32_t temp=1;
+ #if TASK_CRITICAL
+ taskENTER_CRITICAL(); //ٽ
+ #endif
+ iic_cm3232->gpio_control(GPIO_CMD_SET_BIT_DIR_OUTPUT, (void *)(GPIO_I2CSDA_MASK));
+ iic_cm3232->gpio_write(GPIO_I2CSDA_MASK,GPIO_I2CSDA_MASK); // I2C_SDA=1;
+ delay_us(1);
+ iic_cm3232->gpio_write(GPIO_I2CSCL_MASK,GPIO_I2CSCL_MASK); // I2C_SCL=1;
+ delay_us(1);
+ #if TASK_CRITICAL
+ taskEXIT_CRITICAL(); //˳ٽ
+ #endif
+ iic_cm3232->gpio_control(GPIO_CMD_SET_BIT_DIR_INPUT, (void *)(GPIO_I2CSDA_MASK));
+ iic_cm3232->gpio_read(&temp,GPIO_I2CSDA_MASK);
+ temp = temp & GPIO_I2CSDA_MASK;
+ temp = temp >> 16;
+
+ while(temp)
+ {
+ ucErrTime++;
+ if(ucErrTime>250)
+ {
+ I2C_Stop();
+ return 1;
+ }
+ iic_cm3232->gpio_read(&temp,GPIO_I2CSDA_MASK);
+ temp = (~temp) & GPIO_I2CSDA_MASK;
+ temp = temp >> GPIO_I2CSDA_MASK;
+ printf("wait_read_loop:%d\r\n",temp);
+ }
+ iic_cm3232->gpio_write((~GPIO_I2CSCL_MASK),GPIO_I2CSCL_MASK); // I2C_SCL=0;
+ return 0;
+}
+
+void I2C_Ack(void)
+{
+ #if TASK_CRITICAL
+ taskENTER_CRITICAL(); //ٽ
+ #endif
+ iic_cm3232->gpio_write((~GPIO_I2CSCL_MASK),GPIO_I2CSCL_MASK); // I2C_SCL=0;
+ iic_cm3232->gpio_control(GPIO_CMD_SET_BIT_DIR_OUTPUT, (void *)(GPIO_I2CSDA_MASK));
+ iic_cm3232->gpio_write((~GPIO_I2CSDA_MASK),GPIO_I2CSDA_MASK); // I2C_SDA=0;
+ delay_us(2);
+ iic_cm3232->gpio_write(GPIO_I2CSCL_MASK,GPIO_I2CSCL_MASK); // I2C_SCL=1;
+ delay_us(2);
+ iic_cm3232->gpio_write((~GPIO_I2CSCL_MASK),GPIO_I2CSCL_MASK); // I2C_SCL=0;
+ #if TASK_CRITICAL
+ taskEXIT_CRITICAL(); //˳ٽ
+ #endif
+}
+
+void I2C_NAck(void)
+{
+ #if TASK_CRITICAL
+ taskENTER_CRITICAL(); //ٽ
+ #endif
+ iic_cm3232->gpio_write((~GPIO_I2CSCL_MASK),GPIO_I2CSCL_MASK); // I2C_SCL=0;
+ iic_cm3232->gpio_control(GPIO_CMD_SET_BIT_DIR_OUTPUT, (void *)(GPIO_I2CSDA_MASK));
+ iic_cm3232->gpio_write(GPIO_I2CSDA_MASK,GPIO_I2CSDA_MASK); // I2C_SDA=1;
+ delay_us(2);
+ iic_cm3232->gpio_write(GPIO_I2CSCL_MASK,GPIO_I2CSCL_MASK); // I2C_SCL=1;
+ delay_us(2);
+ iic_cm3232->gpio_write((~GPIO_I2CSCL_MASK),GPIO_I2CSCL_MASK); // I2C_SCL=0;
+ #if TASK_CRITICAL
+ taskEXIT_CRITICAL(); //˳ٽ
+ #endif
+}
+
+void I2C_Send_Byte(uint8_t txd)
+{
+ uint8_t t;
+ #if TASK_CRITICAL
+ taskENTER_CRITICAL(); //ٽ
+ #endif
+ iic_cm3232->gpio_control(GPIO_CMD_SET_BIT_DIR_OUTPUT, (void *)(GPIO_I2CSDA_MASK));
+ iic_cm3232->gpio_write((~GPIO_I2CSCL_MASK),GPIO_I2CSCL_MASK); // I2C_SCL=0;
+ for(t=0;t<8;t++)
+ {
+ iic_cm3232->gpio_write((((txd&0x80)>>7)<<16),GPIO_I2CSDA_MASK);
+ txd<<=1;
+ delay_us(2);
+ iic_cm3232->gpio_write(GPIO_I2CSCL_MASK,GPIO_I2CSCL_MASK); // I2C_SCL=1;
+ delay_us(2);
+ iic_cm3232->gpio_write((~GPIO_I2CSCL_MASK),GPIO_I2CSCL_MASK); // I2C_SCL=0;
+ delay_us(2);
+ }
+ #if TASK_CRITICAL
+ taskEXIT_CRITICAL(); //˳ٽ
+ #endif
+}
+
+uint8_t I2C_Read_Byte(unsigned char ack)
+{
+ unsigned char i,receive=0;
+ uint32_t temp=0;
+ #if TASK_CRITICAL
+ taskENTER_CRITICAL(); //ٽ
+ #endif
+ iic_cm3232->gpio_control(GPIO_CMD_SET_BIT_DIR_INPUT, (void *)(GPIO_I2CSDA_MASK));
+ for(i=0;i<8;i++)
+ {
+ iic_cm3232->gpio_write((~GPIO_I2CSCL_MASK),GPIO_I2CSCL_MASK); // I2C_SCL=0;
+ delay_us(2);
+ iic_cm3232->gpio_write(GPIO_I2CSCL_MASK,GPIO_I2CSCL_MASK); // I2C_SCL=1;
+ receive<<=1;
+ iic_cm3232->gpio_read(&temp,GPIO_I2CSDA_MASK);
+ temp = temp & GPIO_I2CSDA_MASK;
+ temp = temp >> 16;
+// printf("wait_read:%d\r\n",temp);
+ receive += temp;
+ delay_us(1);
+ }
+ #if TASK_CRITICAL
+ taskEXIT_CRITICAL(); //˳ٽ
+ #endif
+ if(!ack)
+ I2C_NAck();
+ else
+ I2C_Ack();
+ return receive;
+}
+
+
diff --git a/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/hardware/i2c/i2c.h b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/hardware/i2c/i2c.h
new file mode 100644
index 00000000..ef24207b
--- /dev/null
+++ b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/hardware/i2c/i2c.h
@@ -0,0 +1,33 @@
+/*
+ * i2c.h
+ *
+ * Created on: 2018523
+ * Author: Administrator
+ */
+
+#include "task_config.h"
+#include "app_config.h"
+
+#ifndef I2C_I2C_H_
+#define I2C_I2C_H_
+
+//IOд
+
+
+//IO
+//#define I2C_SCL PCout(7) //SCL
+//#define I2C_SDA PCout(6) //SDA
+//#define READ_SDA PCin(6) //??SDA
+
+//I2C
+void I2CC_Init(void); //???I2C?IO?
+void I2C_Start(void); //??I2C????
+void I2C_Stop(void); //??I2C????
+void I2C_Send_Byte(uint8_t txd); //I2C??????
+uint8_t I2C_Read_Byte(unsigned char ack);//I2C??????
+uint8_t I2C_Wait_Ack(void); //I2C??ACK??
+void I2C_Ack(void); //I2C??ACK??
+void I2C_NAck(void); //I2C???ACK??
+
+
+#endif /* I2C_I2C_H_ */
diff --git a/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/hardware/timer/timer.c b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/hardware/timer/timer.c
new file mode 100644
index 00000000..2223d9ec
--- /dev/null
+++ b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/hardware/timer/timer.c
@@ -0,0 +1,492 @@
+/*
+ * timer.c
+ *
+ * Created on: 201859
+ * Author: Administrator
+ */
+
+#include "timer.h"
+#include "string.h"
+#include "FreeRTOS.h"
+#include "task.h"
+#include "queue.h"
+
+#include "usart1task.h"
+#include "usart3task.h"
+#include "usart4task.h"
+#include "bright.h"
+#include "fifo.h"
+
+#include "app_config.h"
+
+#include "embARC.h"
+#include "embARC_debug.h"
+
+
+#define COUNT2 (BOARD_CPU_CLOCK/1000)
+#define COUNT (BOARD_CPU_CLOCK/(1000*Bright_bei))
+
+#define EMSK_PWM_PORT DEV_GPIO_PORT_A
+#define GPIO_PWM_MASK 0X00040000 //portA19PinJ39
+
+#define HARD_TIME1 1
+
+volatile static int t0 = 0;
+volatile static int second = 0;
+uint32_t temp_re =0;
+
+volatile unsigned long long FreeRTOSRunTimeTicks;
+uint32_t RTC_SEC=0;//ͬʱ
+uint16_t rtc_1000ms=0;
+uint16_t rtc_1ms=0;
+uint32_t RTC_SEC2=0;
+uint16_t compare_pwm=0;
+uint16_t compare_now=0;
+DEV_GPIO * gpio_pwm;
+uint32_t secsoft = 0;
+uint16_t cnt_sec = 0;
+//ʼTIM3ʹΪFreeRTOSʱͳṩʱ
+//void ConfigureTimeForRunTimeStats(void)
+//{
+// //ʱ3ʼʱʱΪ72MƵϵΪ72-1Զʱ3Ƶ
+// //Ϊ72M/72=1MԶװΪ50-1ôʱھ50us
+// FreeRTOSRunTimeTicks=0;
+// TIM3_Int_Init(50-1,72-1); //ʼTIM3
+//}
+
+void wifi_tim7(void)
+{
+ TIM7_Int_Init();//ʱ1ms
+}
+
+
+//ʼжʱ
+void ALL_TIM_init(void)
+{
+ uint8_t i;
+ TIM7_Int_Init();
+ //ʼλϢ
+// for(i=0;i<9;i++)
+// {
+// compare_set[i] = Bright_bei*compare_set[i];
+// }
+#if 0
+ ConfigureTimeForRunTimeStats();//ϵͳFreeRTOSʱͳṩʱ
+ TIM7_Int_Init(750-1,480-1);//ʱ1ms ڽݳʱ ײպtask֡ʱж
+ TIM2_Int_Init(5000-1,7200-1); //ʼʱ2500ms ԤRTCʱ
+#endif
+}
+
+//ϵͳRTCʱ
+void set_rtc_sec(uint32_t rtc_time)
+{
+ RTC_SEC = rtc_time;
+ rtc_1000ms=0;
+}
+uint32_t get_rtc_sec(void)
+{
+ return RTC_SEC;
+}
+
+void delay_us(uint32_t us)
+{
+
+ uint64_t start_us, us_delayed;
+ us_delayed = (uint64_t)us;
+ start_us = board_get_cur_us();
+// taskENTER_CRITICAL();
+ while ((board_get_cur_us() - start_us) < us_delayed);
+// taskEXIT_CRITICAL();
+}
+//
+
+//
+void TIM7_Int_Init(void)
+{
+ //ʼӲʱ
+#if 0
+ int_disable(INTNO_TIMER1);
+ timer_stop(TIMER_1);
+ int_handler_install(INTNO_TIMER1, timer0_isr);
+ int_pri_set(INTNO_TIMER1, 32);
+ int_enable(INTNO_TIMER1);
+ timer_start(TIMER_1, TIMER_CTRL_IE | TIMER_CTRL_NH, COUNT);
+#endif
+ //ʼʱ
+
+}
+
+void timer0_isr(void *ptr)
+{
+#if 0
+ secsoft++;
+ if(secsoft==10000)
+ {
+ cnt_sec++;
+ printf("%d\r\n",cnt_sec);
+ secsoft=0;
+ }
+#endif
+#if HARD_TIME1
+
+
+ compare_now++;
+ if(compare_nowgpio_write((~GPIO_PWM_MASK),GPIO_PWM_MASK);// gpio low;
+ }
+ }
+ else
+ {
+ compare_now = 0;
+ if(compare_pwm)
+ {
+ gpio_pwm->gpio_write(GPIO_PWM_MASK,GPIO_PWM_MASK);// gpio high;
+ }
+ else
+ {
+ gpio_pwm->gpio_write((~GPIO_PWM_MASK),GPIO_PWM_MASK);// gpio low;
+ }
+
+ }
+//send
+#if 1
+ //suart4 send fifo
+ if(usart4_send_fifo.now_len&&(!send_ctr4.send_flag))
+ {
+ //read send fifo get 1 byte
+ read_fifo(&usart4_send_fifo,&(send_ctr4.byte_now),1);
+ send_ctr4.send_flag=1;
+ send_ctr4.bit_flag=0;
+ }
+ //suart4 send
+ if(send_ctr4.send_flag&&(!(send_ctr4.tim_count%(6))))
+ {
+ if(send_ctr4.bit_flag==0)
+ {
+ uart4->gpio_write((~GPIO_UART4OUT_MASK), GPIO_UART4OUT_MASK);
+ }
+ else if(send_ctr4.bit_flag<9)
+ {
+ uart4->gpio_write((((send_ctr4.byte_now>>(send_ctr4.bit_flag-1))&0x01)<<17), GPIO_UART4OUT_MASK);
+ }
+ else //if(send_ctr4.bit_flag==9)
+ {
+ uart4->gpio_write(GPIO_UART4OUT_MASK, GPIO_UART4OUT_MASK);
+// send_ctr4.bit_flag=0;
+ send_ctr4.send_flag=0;
+ }
+ send_ctr4.bit_flag++;
+
+ }
+ send_ctr4.tim_count++;
+ if(send_ctr4.tim_count>59) send_ctr4.tim_count = 0;
+#endif
+#if 1//receive
+
+ if(uart4_ctr.flag)
+ {
+ if(uart4_ctr.count>(8)&&uart4_ctr.count<(52))//9 15 21 27 33 39 45 51
+ {
+ if(!(((uart4_ctr.count)%(6))-3))
+// if(uart4_ctr.count==9||uart4_ctr.count==15)
+ {
+// uint32_t
+ temp_re =0;
+ uart4->gpio_read(&temp_re, GPIO_UART4IN_MASK);
+ temp_re = temp_re & GPIO_UART4IN_MASK;
+ temp_re = temp_re >> 16;
+ uart4_ctr.byte |= (temp_re<<((uart4_ctr.count-(9))/(6)));
+ }
+ }
+ uart4_ctr.count++;
+ if(uart4_ctr.count>51)
+ {
+ write_fifo(&usart4_fifo,&uart4_ctr.byte,1);
+ uart4_ctr.timeout = 0x80;
+ uart4_ctr.bytenum++;//
+ uart4_ctr.flag = 0;
+ uart4_ctr.count = 0;
+ uart4->gpio_control(GPIO_CMD_ENA_BIT_INT, (void *)GPIO_UART4IN_MASK);
+ }
+ }
+#endif
+#endif
+ timer_int_clear(TIMER_1); //TIM0жϱ־
+}
+
+//ʱ7жϷ
+void softtimer(TimerHandle_t xTimer)
+{
+ BaseType_t xHigherPriorityTaskWoken;
+
+
+ //rtc_1000ms
+ rtc_1000ms++;
+
+ if(rtc_1000ms>999)
+ {
+ rtc_1000ms = 0;
+ RTC_SEC++;
+// printf("%d\r\n",RTC_SEC);
+ }
+#if HARD_TIME1
+ if((rtc_1000ms==0)&&(RTC_SEC==2))
+ {
+ int_disable(INTNO_TIMER1);
+ timer_stop(TIMER_1);
+ int_handler_install(INTNO_TIMER1, timer0_isr);
+ int_pri_set(INTNO_TIMER1, (-2));
+ int_enable(INTNO_TIMER1);
+ timer_start(TIMER_1, TIMER_CTRL_IE | TIMER_CTRL_NH, COUNT);
+ }
+#else
+
+ compare_now++;
+ if(compare_nowgpio_write((~GPIO_PWM_MASK),GPIO_PWM_MASK);// gpio low;
+ }
+ }
+ else
+ {
+ compare_now = 0;
+ if(compare_pwm)
+ {
+ gpio_pwm->gpio_write(GPIO_PWM_MASK,GPIO_PWM_MASK);// gpio high;
+ }
+ else
+ {
+ gpio_pwm->gpio_write((~GPIO_PWM_MASK),GPIO_PWM_MASK);// gpio low;
+ }
+
+ }
+
+
+#endif
+#if 1
+ //ײݳʱ
+ if(usart1_time_out&0x80)
+ {
+ usart1_time_out++;
+ if((usart1_time_out&0x7f)>9)
+ {
+ usart1_time_out = 0;
+ usart1_data.len=USART_RX_STA&0x7fff;
+ if(usart1_data.len)
+ {
+ xQueueSend(USART1_Queue,&usart1_data,0);//з
+ USART_RX_STA = 0;
+ occupy_buff();
+// portYIELD_FROM_ISR();//ҪĻһл
+ }
+ }
+ }
+#endif
+ if(usart3_time_out&0x80)
+ {
+ usart3_time_out++;
+ if((usart3_time_out&0x7f)>9)
+ {
+ usart3_time_out = 0;
+ usart3_data.len=(uint8_t)(USART3_RX_STA&0x7fff);
+ if(usart3_data.len)
+ {
+ xQueueSend(USART3_Queue,&usart3_data,0);//з
+ USART3_RX_STA = 0;
+ occupy_buff3();
+// portYIELD_FROM_ISR();//ҪĻһл
+ }
+ }
+ }
+
+ if(uart4_ctr.timeout&0x80)
+ {
+ uart4_ctr.timeout++;
+ if((uart4_ctr.timeout&0x7f)>20)
+ {
+ uart4_ctr.timeout = 0;
+ //͵
+ if(uart4_ctr.bytenum)
+ {
+ xQueueSend(USART4_Queue,&uart4_ctr.bytenum,0);//з
+ uart4_ctr.bytenum = 0;
+// portYIELD_FROM_ISR(xHigherPriorityTaskWoken);//ҪĻһл
+ }
+ }
+ }
+
+#if 1
+ //usart3taskݳʱ
+ if(usart3_task_time_out&0x80)
+ {
+ usart3_task_time_out++;
+ if((usart3_task_time_out&0x7f)>50)//֡ʧܣ
+ {
+ usart3_task_time_out = 0;
+
+ //ͷŶֵź ͬ
+ if(BinarySemaphore_free!=NULL)//յݣҶֵźЧ
+ {
+ xSemaphoreGive(BinarySemaphore_free); //ͷŶֵź
+// portYIELD_FROM_ISR();//ҪĻһл
+ }
+// usart1_task_process = USART_DATA_IDEL;
+// vPortFree(usart1_task_temp.pstr);//жfreeҪⲿtaskнв
+// usart1_task_temp.type = USART_OTHER;
+ //ݣѵǰݴΪһ֡OTHERݷͳȥ
+
+ }
+ }
+
+// USART3_RX_STA|=1<<15; //ǽ
+// if(USART3_RX_BUF[20]==0x80&&USART3_RX_BUF[21]==0x03&&USART3_RX_BUF[22]==0x24)
+// {
+// light4_flag=1;
+// USART3_RX_STA=0;
+// }
+#endif
+// timer_int_clear(TIMER_0); //TIM0жϱ־
+// TIM_Cmd(TIM7, DISABLE); //رTIM7
+#if !HARD_TIME1
+#if 1//send
+ //suart4 send fifo
+ if(usart4_send_fifo.now_len&&(!send_ctr4.send_flag))
+ {
+ //read send fifo get 1 byte
+ read_fifo(&usart4_send_fifo,&(send_ctr4.byte_now),1);
+ send_ctr4.send_flag=1;
+ send_ctr4.bit_flag=0;
+ }
+ //suart4 send
+ if(send_ctr4.send_flag&&(rtc_1000ms%2==0))
+ {
+ if(send_ctr4.bit_flag==0)
+ {
+ uart4->gpio_write((~GPIO_UART4OUT_MASK), GPIO_UART4OUT_MASK);
+ }
+ else if(send_ctr4.bit_flag<9)
+ {
+ uart4->gpio_write((((send_ctr4.byte_now>>(send_ctr4.bit_flag-1))&0x01)<<17), GPIO_UART4OUT_MASK);
+ }
+ else //if(send_ctr4.bit_flag==9)
+ {
+ uart4->gpio_write(GPIO_UART4OUT_MASK, GPIO_UART4OUT_MASK);
+// send_ctr4.bit_flag=0;
+ send_ctr4.send_flag=0;
+ }
+ send_ctr4.bit_flag++;
+ }
+#endif
+#if 1//receive
+// uart4_ctr.count=0;
+// uart4_ctr.byte = 0;
+// uart4_ctr.flag = 1;
+ if(uart4_ctr.flag)
+ {
+ if(uart4_ctr.count>2&&uart4_ctr.count<18)//3 5 7 9 11 13 15 17
+ {
+ if(uart4_ctr.count%2)
+ {
+ uint32_t temp =0;
+ uart4->gpio_read(&temp, GPIO_UART4IN_MASK);
+ temp = temp & GPIO_UART4IN_MASK;
+ temp = temp >> 16;
+ uart4_ctr.byte |= (temp<<((uart4_ctr.count-3)/2));
+ }
+ }
+ uart4_ctr.count++;
+ if(uart4_ctr.count>17)
+ {
+ write_fifo(&usart4_fifo,&uart4_ctr.byte,1);
+ uart4_ctr.timeout = 0x80;
+ uart4_ctr.bytenum++;//
+ uart4_ctr.flag = 0;
+ uart4_ctr.count = 0;
+ uart4->gpio_control(GPIO_CMD_ENA_BIT_INT, (void *)GPIO_UART4IN_MASK);
+ }
+ }
+#endif
+#endif
+
+}
+
+void pwm_gpio_int(void)
+{
+ gpio_pwm = gpio_get_dev(EMSK_PWM_PORT);
+ if (gpio_pwm->gpio_open(GPIO_PWM_MASK) == E_OPNED) {
+ gpio_pwm->gpio_control(GPIO_CMD_SET_BIT_DIR_OUTPUT, (void *)(GPIO_PWM_MASK));
+ gpio_pwm->gpio_control(GPIO_CMD_DIS_BIT_INT, (void *)(GPIO_PWM_MASK));
+ }
+ gpio_pwm->gpio_write((~GPIO_PWM_MASK),GPIO_PWM_MASK);
+}
+#if 0
+void timertest_int(void)
+{
+ gpio_pwm = gpio_get_dev(EMSK_PWM_PORT);
+
+// EMSK_GPIO_CHECK_EXP_NORTN(gpio_pwm != NULL);
+//printf("11\r\n");
+ if (gpio_pwm->gpio_open(GPIO_PWM_MASK) == E_OPNED) {
+ gpio_pwm->gpio_control(GPIO_CMD_SET_BIT_DIR_OUTPUT, (void *)(GPIO_PWM_MASK));
+ gpio_pwm->gpio_control(GPIO_CMD_DIS_BIT_INT, (void *)(GPIO_PWM_MASK));
+ }
+ gpio_pwm->gpio_write((~GPIO_PWM_MASK),GPIO_PWM_MASK);
+ int_disable(INTNO_TIMER1);
+ timer_stop(TIMER_1);
+ int_handler_install(INTNO_TIMER1, timertest_isr);
+ int_pri_set(INTNO_TIMER1, 8);
+ int_enable(INTNO_TIMER1);
+ timer_start(TIMER_1, TIMER_CTRL_IE | TIMER_CTRL_NH, COUNT2);
+}
+
+
+void timertest_isr(void)
+{
+// BaseType_t xHigherPriorityTaskWoken;
+
+
+ compare_now++;
+ if(compare_now<10)
+ {
+ if(compare_pwm==compare_now)
+ {
+ gpio_pwm->gpio_write((~GPIO_PWM_MASK),GPIO_PWM_MASK);// gpio low;
+ }
+ }
+ else
+ {
+ compare_now = 0;
+ if(compare_pwm)
+ {
+ gpio_pwm->gpio_write(GPIO_PWM_MASK,GPIO_PWM_MASK);// gpio high;
+ }
+ else
+ {
+ gpio_pwm->gpio_write((~GPIO_PWM_MASK),GPIO_PWM_MASK);// gpio low;
+ }
+
+ }
+
+
+
+ //rtc_1000ms
+ rtc_1ms++;
+
+ if(rtc_1ms>999)
+ {
+ rtc_1ms = 0;
+ RTC_SEC2++;
+// if(RTC_SEC2>999)
+// {
+// printf("%d\r\n",RTC_SEC2);
+// RTC_SEC2=0;
+// }
+ }
+ timer_int_clear(TIMER_1); //TIM0жϱ־
+}
+#endif
diff --git a/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/hardware/timer/timer.h b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/hardware/timer/timer.h
new file mode 100644
index 00000000..d8126745
--- /dev/null
+++ b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/hardware/timer/timer.h
@@ -0,0 +1,32 @@
+/*
+ * timer.h
+ *
+ * Created on: 201859
+ * Author: Administrator
+ */
+#include "stdint.h"
+#include "task_config.h"
+#ifndef HARDWARE_TIMER_TIMER_H_
+#define HARDWARE_TIMER_TIMER_H_
+
+extern uint16_t compare_pwm;
+
+void ALL_TIM_init(void);
+
+void TIM3_Int_Init(uint16_t arr,uint16_t psc);
+void TIM2_Int_Init(uint16_t arr,uint16_t psc);
+void TIM7_Int_Init(void);
+
+//extern uint32_t RTC_SEC;
+extern volatile unsigned long long FreeRTOSRunTimeTicks;
+void ConfigureTimeForRunTimeStats(void);
+void wifi_tim7(void);
+void softtimer(TimerHandle_t xTimer);
+void timer0_isr(void *ptr);
+void set_rtc_sec(uint32_t rtc_time);
+void delay_us(uint32_t us);
+uint32_t get_rtc_sec(void);
+void pwm_gpio_int(void);
+//extern void timertest_int(void);
+//void timertest_isr(void);
+#endif /* HARDWARE_TIMER_TIMER_H_ */
diff --git a/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/main.c b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/main.c
new file mode 100644
index 00000000..6082ae24
--- /dev/null
+++ b/arc_design_contest/2018/HUST_SmartLamp/src/FreeRTOS/main.c
@@ -0,0 +1,768 @@
+/* ------------------------------------------
+ * Copyright (c) 2017, Synopsys, Inc. All rights reserved.
+
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+
+ * 1) Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+
+ * 2) Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation and/or
+ * other materials provided with the distribution.
+
+ * 3) Neither the name of the Synopsys, Inc., nor the names of its contributors may
+ * be used to endorse or promote products derived from this software without
+ * specific prior written permission.
+
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+--------------------------------------------- */
+
+/**
+ * \defgroup EMBARC_APP_FREERTOS_KERNEL embARC FreeRTOS Kernel Example
+ * \ingroup EMBARC_APPS_TOTAL
+ * \ingroup EMBARC_APPS_OS_FREERTOS
+ * \brief embARC Example for testing FreeRTOS task switch and interrupt/exception handling
+ *
+ * \details
+ * ### Extra Required Tools
+ *
+ * ### Extra Required Peripherals
+ *
+ * ### Design Concept
+ * This example is designed to show the functionality of FreeRTOS.
+ *
+ * ### Usage Manual
+ * Test case for show how FreeRTOS is working by task switching and interrupt/exception processing.
+ * 
+ *
+ * ### Extra Comments
+ *
+ */
+
+/**
+ * \file
+ * \ingroup EMBARC_APP_FREERTOS_KERNEL
+ * \brief main source file of the freertos demo
+ */
+
+/**
+ * \addtogroup EMBARC_APP_FREERTOS_KERNEL
+ * @{
+ */
+
+#include "embARC.h"
+#include "embARC_debug.h"
+#include
+#include "FreeRTOS.h"
+#include "stdint.h"
+
+
+#include "timer.h"
+
+#include "malloc.h"
+#include "string.h"
+
+#include "FreeRTOS.h"
+#include "task.h"
+#include "queue.h"
+#include "semphr.h"
+#include "timers.h"
+
+//
+#include "stdlib.h"
+
+#include "cm3232.h"
+#include "usart1task.h"
+#include "usart3task.h"
+#include "usart4task.h"
+#include "ESP8266.h"
+#include "package.h"
+#include "initsys.h"
+#include "bright.h"
+#include "irf.h"
+
+#include "task_config.h"
+#include "app_config.h"
+
+//看门狗实现:在低等级任务中,标记事件标志组。最高等级任务检测到所有任务正常执行,就喂狗�#include "sys.h"
+
+
+//看门狗实现:在低等级任务中,标记事件标志组。最高等级任务检测到所有任务正常执行,就喂狗。 看门狗时间根据实际运行情况来
+ /*
+ 低级任务标记:
+ xEventGroupSetBits(xCreatedEventGroup, TASK_BIT_3);
+ 高级任务检测:
+ uxBits = xEventGroupWaitBits(xCreatedEventGroup,
+ TASK_BIT_ALL,
+ pdTRUE,
+ pdTRUE,
+ xTicksToWait);
+
+ if((uxBits & TASK_BIT_ALL) == TASK_BIT_ALL)
+ {
+ IWDG_Feed();
+ printf("五个用户任务都正常运行\r\n");
+ }
+ else
+*/
+//#include "strpos.h"//测试
+/************************************************
+************************************************/
+/*******************任务参数*******************/
+////任务优先级
+//#define START_TASK_PRIO 1//宏定义在app_config.h中
+////任务堆栈大小
+//#define START_STK_SIZE 256
+//任务句柄
+TaskHandle_t StartTask_Handler;//在main中定义
+//任务函数
+//void start_task(void *pvParameters);//在任务函数所在文件和头文件定义
+
+
+
+////任务优先级
+//#define TASK1_TASK_PRIO 2
+////任务堆栈大小
+//#define TASK1_STK_SIZE 256
+//任务句柄
+TaskHandle_t Task1Task_Handler;
+//任务函数
+void task1_task(void *pvParameters);
+//#define task1_task_delay 20//
+
+
+
+////任务优先级
+//#define KEYPROCESS_TASK_PRIO 3
+////任务堆栈大小
+//#define KEYPROCESS_STK_SIZE 256
+//任务句柄
+TaskHandle_t Keyprocess_Handler;
+//任务函数
+void Keyprocess_task(void *pvParameters);
+//#define Keyprocess_task_delay 20//
+uint8_t KEY_Scan(void);//键盘扫描
+
+////任务优先级
+//#define USART1_TASK_PRIO 30
+////任务堆栈大小
+//#define USART1_STK_SIZE 256
+//任务句柄
+//TaskHandle_t USART1_Handler;
+//任务函数
+//void USART1_task(void *pvParameters);
+//#define USART1_task_delay 10//任务运行间隔 ms
+
+//TaskHandle_t FREE_ERRORMEM_Handler;
+//TaskHandle_t smart_config__Handler;
+
+
+/**********************队列****************************/
+QueueHandle_t Key_Queue; //按键值消息队列句柄
+
+
+uint8_t KEY_Scan(void)
+{
+ static uint8_t key_up=1;//按键按松开标志
+ uint32_t KEY;
+// if(mode)key_up=1; //支持连按
+ KEY=button_read(EMSK_BUTTON_MASK);
+ if(key_up&&KEY)
+ {
+ vTaskDelay(10);//去抖动
+ key_up=0;
+ if(KEY==0x01)return 0x01;
+ else if(KEY==0x02)return 0x02;
+ else if(KEY==0x04)return 0x04;
+ }else if(KEY==0x00)key_up=1;
+ return 0;// 无按键按下
+}
+
+char InfoBuffer[1000]; //保存测试信息的数组
+
+void check_task_state(void)
+{
+#if 1
+ //优先级与堆栈使用情况
+ memset(InfoBuffer,0,1000); //信息缓冲区清零
+#if 1
+ printf("/************* vTaskList() *************/\r\n");
+ printf("/******R ready B block S suspend D delete*******/\r\n");
+ printf("name\t\t\t\tflag\tprio\tleast\tnum\r\n");
+ vTaskList(InfoBuffer); //获取所有任务的信息
+ printf("%s\r\n",InfoBuffer); //通过串口打印所有任务的信息
+#endif
+ printf("/**************************end**************************/\r\n");
+ //任务运行时间情况
+#if 0
+ memset(InfoBuffer,0,1000); //信息缓冲区清零
+ vTaskGetRunTimeStats(InfoBuffer); //获取任务运行时间信息
+ printf("任务名\t\t\t运行时间\t运行所占百分比\r\n");
+ printf("%s\r\n",InfoBuffer);
+#endif
+#endif
+}
+
+//查询Message_Queue队列中的总队列数量和剩余队列数量
+void check_msg_queue(void)
+{
+ uint8_t *p;
+ uint8_t msgq_remain_size; //消息队列剩余大小
+ uint8_t msgq_total_size; //消息队列总大小
+ uint32_t freemem;
+
+ taskENTER_CRITICAL(); //进入临界区
+
+ //任务相关
+ check_task_state();
+
+ msgq_remain_size=uxQueueSpacesAvailable(USART1_Queue);//得到队列剩余大小
+ msgq_total_size=uxQueueMessagesWaiting(USART1_Queue)+uxQueueSpacesAvailable(USART1_Queue);//得到队列总大小,总大小=使用+剩余的。
+ p=pvPortMalloc(30); //申请内存 sprintf的字符数一定不能超过30,不然内存炸了
+
+ sprintf((char*)p,"USART1_Q:%d/%d",msgq_remain_size,msgq_total_size); //显示DATA_Msg剩余大小/总大小
+ printf("%s\r\n",p);
+ #if 1 //
+ msgq_remain_size=uxQueueSpacesAvailable(USART1_Task_Queue);//得到队列剩余大小
+ msgq_total_size=uxQueueMessagesWaiting(USART1_Task_Queue)+uxQueueSpacesAvailable(USART1_Task_Queue);//得到队列总大小,总大小=使用+剩余的。
+ sprintf((char*)p,"USART1_tsak_Q:%d/%d",msgq_remain_size,msgq_total_size); //显示DATA_Msg剩余大小/总大小
+ printf("%s\r\n",p);
+
+ msgq_remain_size=uxQueueSpacesAvailable(USART3_Queue);//得到队列剩余大小
+msgq_total_size=uxQueueMessagesWaiting(USART3_Queue)+uxQueueSpacesAvailable(USART3_Queue);//得到队列总大小,总大小=使用+剩余的。
+ sprintf((char*)p,"USART3_Queue:%d/%d",msgq_remain_size,msgq_total_size); //显示DATA_Msg剩余大小/总大小
+printf("%s\r\n",p);
+
+ msgq_remain_size=uxQueueSpacesAvailable(USART3_Send_Queue);//得到队列剩余大小
+ msgq_total_size=uxQueueMessagesWaiting(USART3_Send_Queue)+uxQueueSpacesAvailable(USART3_Send_Queue);//得到队列总大小,总大小=使用+剩余的。
+ sprintf((char*)p,"u3_Send_Q:%d/%d",msgq_remain_size,msgq_total_size); //显示DATA_Msg剩余大小/总大小
+ printf("%s\r\n",p);
+
+ msgq_remain_size=uxQueueSpacesAvailable(USART3_Task_rn_other_Queue);//得到队列剩余大小
+ msgq_total_size=uxQueueMessagesWaiting(USART3_Task_rn_other_Queue)+uxQueueSpacesAvailable(USART3_Task_rn_other_Queue);//得到队列总大小,总大小=使用+剩余的。
+ sprintf((char*)p,"rn_other_Q:%d/%d",msgq_remain_size,msgq_total_size); //显示DATA_Msg剩余大小/总大小
+ printf("%s\r\n",p);
+
+ msgq_remain_size=uxQueueSpacesAvailable(USART3_Task_server_Queue);//得到队列剩余大小
+ msgq_total_size=uxQueueMessagesWaiting(USART3_Task_server_Queue)+uxQueueSpacesAvailable(USART3_Task_server_Queue);//得到队列总大小,总大小=使用+剩余的。
+ sprintf((char*)p,"u3server_Q:%d/%d",msgq_remain_size,msgq_total_size); //显示DATA_Msg剩余大小/总大小
+ printf("%s\r\n",p);
+
+ msgq_remain_size=uxQueueSpacesAvailable(USART4_Queue);//得到队列剩余大小
+msgq_total_size=uxQueueMessagesWaiting(USART4_Queue)+uxQueueSpacesAvailable(USART4_Queue);//得到队列总大小,总大小=使用+剩余的。
+ sprintf((char*)p,"U4_Queue:%d/%d",msgq_remain_size,msgq_total_size); //显示DATA_Msg剩余大小/总大小
+dprintf("%s\r\n",p);
+
+ msgq_remain_size=uxQueueSpacesAvailable(USART4_Send_Queue);//得到队列剩余大小
+msgq_total_size=uxQueueMessagesWaiting(USART4_Send_Queue)+uxQueueSpacesAvailable(USART4_Send_Queue);//得到队列总大小,总大小=使用+剩余的。
+ sprintf((char*)p,"U4_Send_Q:%d/%d",msgq_remain_size,msgq_total_size); //显示DATA_Msg剩余大小/总大小
+dprintf("%s\r\n",p);
+ #endif
+
+ freemem=xPortGetFreeHeapSize(); //获取剩余内存大小
+ sprintf((char*)p,"freemem:%d",freemem); //显示DATA_Msg剩余大小
+ printf("%s\r\n",p);
+
+ vPortFree(p); //释放内存
+
+
+ taskEXIT_CRITICAL(); //退出临界区
+}
+
+void start_task();//(void *pvParameters);
+
+int main(void)
+{
+
+// supersound_IOinit_1();
+ uart1_init(115200); //初始化串口
+ uart3_init(115200);
+ pwm_gpio_int();
+ usart4_init();
+ init_system(); //初始化系统
+// timertest_int();
+ CM3232_Init();
+ irf_init();
+ // vTaskSuspendAll();//super sound
+// taskENTER_CRITICAL(); //进入临界区 adc
+ //创建开始任务
+#if 0
+ xTaskCreate((TaskFunction_t )start_task, //任务函数
+ (const char* )"start_task", //任务名称
+ (uint16_t )START_STK_SIZE, //任务堆栈大小
+ (void* )NULL, //传递给任务函数的参数
+ (UBaseType_t )START_TASK_PRIO, //任务优先级
+ (TaskHandle_t* )&StartTask_Handler); //任务句柄
+#else
+ start_task();
+// user_idel();
+#endif
+// taskEXIT_CRITICAL(); //退出临界区
+// xTaskResumeAll();
+#if 1
+ vTaskStartScheduler();
+#else
+// while(1)
+ {
+// vTaskSuspend(NULL);
+ }//开启任务调度
+#endif
+}
+#define SUSPEND 0
+//开始任务任务函数
+void start_task()//(void *pvParameters)
+{
+#if SUSPEND
+ vTaskSuspendAll();//super sound
+#else
+ taskENTER_CRITICAL(); //进入临界区 adc
+#endif
+
+ //创建消息队列
+ Key_Queue=xQueueCreate(KEYMSG_Q_NUM,sizeof(uint8_t)); //创建消息Key_Queue
+ USART1_Queue=xQueueCreate(USART1_Q_NUM,sizeof(usart_dat));//底层串口1缓冲数据Queue
+ USART1_Task_Queue=xQueueCreate(USART1_TASK_Q_NUM,sizeof(usart_task_data));
+ USART3_Queue=xQueueCreate(USART3_Q_NUM,sizeof(usart_dat));//底层串口3缓冲数据Queue
+// printf("%d",USART3_Queue);
+ USART3_Task_server_Queue=xQueueCreate(USART3_TASK_SERVER_Q_NUM ,sizeof(usart_task_data));//串口3分帧数据:服务器数据
+ USART3_Task_rn_other_Queue=xQueueCreate(USART3_TASK_RN_OTHER_Q_NUM ,sizeof(usart_task_data));//串口3分帧数据:\r\n数据和没有标记的数据
+ USART3_Send_Queue = xQueueCreate(USART3_Send_Q_NUM ,sizeof(usart_task_data));
+ pack2server_queue = xQueueCreate(pack2server_Q_NUM ,sizeof(uint16_t));
+ connect_to_server_Queue = xQueueCreate(connect_to_server_Q_NUM ,sizeof(uint8_t));
+ USART4_Queue = xQueueCreate(USART4_Q_NUM,sizeof(uint8_t));
+ USART4_Send_Queue = xQueueCreate(USART4SEND_Q_NUM ,sizeof(usart_task_data));
+ SuperSound_Queue = xQueueCreate(SuperSound_Q_NUM ,sizeof(uint8_t));
+#if ASSERT_PRINTF_ENABLE
+ Dprintf_Queue = xQueueCreate(Dprintf_Q_NUM,sizeof(usart_task_data));
+#endif
+// USART5_Queue = xQueueCreate(USART5_Q_NUM,sizeof(u8));
+// USART5_Send_Queue = xQueueCreate(USART5SEND_Q_NUM ,sizeof(usart_task_data));
+
+ //创建二值信号量
+ BinarySemaphore_free=xSemaphoreCreateBinary();
+
+ /* 创建互斥信号量 */
+ SendenableMutexSemaphore=xSemaphoreCreateMutex();
+ #if ASSERT_PRINTF_ENABLE
+// xMutex = xSemaphoreCreateMutex();
+
+ #endif
+
+ //定时器
+ //创建wifi单次定时器
+ OneShot_config60_Handle=xTimerCreate((const char* )"OneShotTimer60s",
+ (TickType_t ) WIFI_TIM60S_TICKS ,
+ (UBaseType_t )pdFALSE,//单次定时器
+ (void* ) WIFI_TIM60S_ID,
+ (TimerCallbackFunction_t) OneShot60_10Callback);
+ OneShot_config10_Handle=xTimerCreate((const char* )"OneShotTimer10s",
+ (TickType_t ) WIFI_TIM10S_TICKS ,
+ (UBaseType_t )pdFALSE,//单次定时器
+ (void* ) WIFI_TIM10S_ID,
+ (TimerCallbackFunction_t) OneShot60_10Callback);
+ //延时启动发送服务器数据功能
+ OneShot_CanServer_Handle=xTimerCreate((const char* )"OneShotCanServer",
+ (TickType_t ) CanServer_TICKS ,
+ (UBaseType_t )pdFALSE,//单次定时器
+ (void* ) CanServer_ID,
+ (TimerCallbackFunction_t) CanServer_Callback);
+
+
+ //定时发送0002包
+ period40or5_0002_Handle=xTimerCreate((const char* )"period40or5_0002",
+ (TickType_t ) PKG0002_5S_TICKS ,//测试时5s一次
+ (UBaseType_t )pdTRUE,//周期定时器
+ (void* ) PKG0002_TIM_ID,
+ (TimerCallbackFunction_t)period40or5_0002_Callback);
+//软件定时器wifi timer
+#if 1
+ OneShot_config1MS_Handle=xTimerCreate((const char* )"wifi_timer",
+ (TickType_t ) WIFI_1MS_TICKS ,//测试时5s一次
+ (UBaseType_t )pdTRUE,//周期定时器
+ (void* ) WIFI_TIM1MS_ID,
+ (TimerCallbackFunction_t)softtimer);
+ period_waittouch_Handle=xTimerCreate((const char* )"period_waittouch",
+ (TickType_t ) WAIT_TOUCH_TICKS ,//测试时5s一次
+ (UBaseType_t )pdTRUE,//周期定时器
+ (void* ) WAIT_TOUCH_ID,
+ (TimerCallbackFunction_t)period_waittouch_Callback);
+ //调节灯光亮度定时器
+ period_Bright_Handle=xTimerCreate((const char* )"period_Bright",
+ (TickType_t ) Bright_TICKS ,//周期
+ (UBaseType_t )pdTRUE,//周期定时器
+ (void* ) Bright_ID,
+ (TimerCallbackFunction_t)period_Bright_Callback);
+
+
+#endif
+ //创建TASK1任务
+ xTaskCreate((TaskFunction_t )task1_task,
+ (const char* )"task1_task",
+ (uint16_t )TASK1_STK_SIZE,
+ (void* )NULL,
+ (UBaseType_t )TASK1_TASK_PRIO,
+ (TaskHandle_t* )&Task1Task_Handler);
+ //创建TASK2任务
+ xTaskCreate((TaskFunction_t )Keyprocess_task,
+ (const char* )"keyprocess_task",
+ (uint16_t )KEYPROCESS_STK_SIZE,
+ (void* )NULL,
+ (UBaseType_t )KEYPROCESS_TASK_PRIO,
+ (TaskHandle_t* )&Keyprocess_Handler);
+
+ //串口1数据,task处理任务 分帧操作
+ xTaskCreate((TaskFunction_t )USART1_task,
+ (const char* )"USART1_task",
+ (uint16_t )USART1_STK_SIZE,
+ (void* )NULL,
+ (UBaseType_t )USART1_TASK_PRIO,
+ (TaskHandle_t* )&USART1_Handler);
+ //串口1 APP层处理任务
+ xTaskCreate((TaskFunction_t )usart1_app_task,
+ (const char* )"usart1_app_task",
+ (uint16_t )USART1_APP_SIZE,
+ (void* )NULL,
+ (UBaseType_t )USART1_APP_PRIO,
+ (TaskHandle_t* )&USART1_app_Handler);
+
+ //串口3数据,task处理任务 分帧操作
+ xTaskCreate((TaskFunction_t )USART3_task,
+ (const char* )"USART3_task",
+ (uint16_t )USART3_STK_SIZE,
+ (void* )NULL,
+ (UBaseType_t )USART3_TASK_PRIO,
+ (TaskHandle_t* )&USART3_Handler);
+
+ //free串口3接收错误内存
+ xTaskCreate((TaskFunction_t )FREE_ERRORMEM_task,
+ (const char* )"FREE_ERRORMEM_task",
+ (uint16_t )FREE_ERRORMEM_SIZE,
+ (void* )NULL,
+ (UBaseType_t )FREE_ERRORMEM_PRIO,
+ (TaskHandle_t* )&FREE_ERRORMEM_Handler);
+
+ //串口3发送数据,task处理任务
+ xTaskCreate((TaskFunction_t )USART3_send_task,
+ (const char* )"USART3_send_task",
+ (uint16_t )USART3_SEND_SIZE,
+ (void* )NULL,
+ (UBaseType_t )USART3_SEND_PRIO,
+ (TaskHandle_t* )&USART3_send_Handler);
+
+ //串口3 APP层处理任务
+ xTaskCreate((TaskFunction_t )usart3_app_task,
+ (const char* )"usart3_app_task",
+ (uint16_t )USART3_APP_SIZE,
+ (void* )NULL,
+ (UBaseType_t )USART3_APP_PRIO,
+ (TaskHandle_t* )&USART3_app_Handler);
+
+ //串口4 APP层处理任务
+ xTaskCreate((TaskFunction_t )USART4_app_task,
+ (const char* )"usart4_app_task",
+ (uint16_t )USART4_APP_SIZE,
+ (void* )NULL,
+ (UBaseType_t )USART4_APP_PRIO,
+ (TaskHandle_t* )&USART4_app_Handler);
+ //串口5 APP层处理任务
+// xTaskCreate((TaskFunction_t )USART5_app_task,
+// (const char* )"usart5_app_task",
+// (uint16_t )USART5_APP_SIZE,
+// (void* )NULL,
+// (UBaseType_t )USART5_APP_PRIO,
+// (TaskHandle_t* )&USART5_app_Handler);
+// irf_init();
+ //irf APP层处理任务
+ xTaskCreate((TaskFunction_t )IRF_app_task,
+ (const char* )"IRF_app_task",
+ (uint16_t )IRF_APP_SIZE,
+ (void* )NULL,
+ (UBaseType_t )IRF_APP_PRIO,
+ (TaskHandle_t* )&IRF_app_Handler);
+ //mp3播放控制
+ xTaskCreate((TaskFunction_t )MP3_task,
+ (const char* )"MP3_task",
+ (uint16_t )MP3_TASK_SIZE,
+ (void* )NULL,
+ (UBaseType_t )MP3_TASK_PRIO,
+ (TaskHandle_t* )&MP3_TASK_Handler);
+ //发送给服务器的包进行组包
+ xTaskCreate((TaskFunction_t )pack2server,
+ (const char* )"pack2server",
+ (uint16_t )pack2server_SIZE,
+ (void* )NULL,
+ (UBaseType_t )pack2server_PRIO,
+ (TaskHandle_t* )&pack2server_Handler);
+ xTaskCreate((TaskFunction_t )connect_to_server,
+ (const char* )"connect_to_server",
+ (uint16_t )connect_to_server_SIZE,
+ (void* )NULL,
+ (UBaseType_t )connect_to_server_PRIO,
+ (TaskHandle_t* )&connect_to_server_Handler);
+ vTaskSuspend(connect_to_server_Handler);
+
+#if 0
+ //wifi配置任务
+ xTaskCreate((TaskFunction_t )smartconfig_task,
+ (const char* )"smartconfig_task",
+ (uint16_t )SMARTCONFIG_TASK_SIZE,
+ (void* )NULL,
+ (UBaseType_t )SMARTCONFIG_TASK_PRIO,
+ (TaskHandle_t* )&smart_config_Handler);
+
+ vTaskDelete(smart_config_Handler);
+#endif
+ //任务相关初始化 初始化系统
+ mcu_sendcmd2touch(TOUCH_ON);//开启触控板
+
+ xTimerStart(period40or5_0002_Handle,10);//定时连接服务器和发送0002包
+
+ vTaskDelete(StartTask_Handler); //删除开始任务
+#if !SUSPEND
+ taskEXIT_CRITICAL(); //退出临界区
+#else
+ xTaskResumeAll();
+#endif
+}
+
+//task1任务函数
+void task1_task(void *pvParameters)
+{
+ uint8_t key,i=0;
+ BaseType_t err;
+ TickType_t xLastWakeTime;
+ const TickType_t xFrequency = 10;
+
+ /* 获取当前的系统时间 */
+ xTimerStart(OneShot_config1MS_Handle,1);
+ xLastWakeTime = xTaskGetTickCount();
+
+ printf("task1 success\r\n");
+ while(1)
+ {
+ vTaskDelay(10);
+ key=KEY_Scan(); //扫描按键
+
+ if((Key_Queue!=NULL)&&(key)) //消息队列Key_Queue创建成功,并且按键被按下
+ {
+// if(key) printf("key:%d\r\n",key);
+ err=xQueueSend(Key_Queue,&key,10);
+ if(err==errQUEUE_FULL) //发送按键值
+ {
+ printf("队列Key_Queue已满,数据发送失败!\r\n");
+ }
+ }
+ i++;
+ if(i==50)
+ led_write(0x00,EMSK_LED_MASK);
+ if(i==100)
+ {
+ i=0;
+ led_write(0x01,EMSK_LED_MASK);
+ }
+// vTaskDelay(task1_task_delay); //延时10ms,也就是10个时钟节拍
+ /* vTaskDelayUntil是绝对延迟,vTaskDelay是相对延迟。*/
+ vTaskDelayUntil(&xLastWakeTime, xFrequency);
+ }
+}
+
+#define CORRECT_COUNT 20
+//Keyprocess_task函数
+void Keyprocess_task(void *pvParameters)
+{
+ uint8_t num=0,num_up=0,key;
+ uint8_t* buffer;
+ uint8_t temp;
+ BaseType_t err;
+ unsigned long adc_temp;
+// usart_data usart1_temp;
+// usart_dat usart1_temp;
+ usart_task_data usart1_task_temp;
+ eTaskState state_test;
+ printf("Keyprocess_task success\r\n");
+ while(1)
+ {
+ if(Key_Queue!=NULL)
+ {
+ if(xQueueReceive(Key_Queue,&key,portMAX_DELAY))//请求消息Key_Queue
+ {
+ switch(key)
+ {
+ case 0x01: //KEY_UP控制LED1
+ num_up++;
+ led_write((num_up%8),EMSK_LED_MASK);
+ check_msg_queue();//检usart_Queue队列的容量
+
+ //noperson
+ server_control_light(0x21);
+ study_ctr.noperson = ReadData2_7705();
+ for(temp=0;temp
+
+ obj_emsk_22
+
+
+
+
+
+
+
+
diff --git a/arc_design_contest/2018/README.md b/arc_design_contest/2018/README.md
deleted file mode 100644
index e69de29b..00000000