验证中...
码云 Gitee IDE 全新上线——支持 Git 管理的轻量在线编码环境
语言: C/C++
分类: 嵌入式开发
最后更新于 2017-12-18 12:44
片段 1 片段 2 片段 3 片段 4 片段 5 片段 6
quaaquarius.c
原始数据 复制代码
/*--------------------------------------------------------------------------*/
/* Project : QuaAquarius */
/* File : quaaquarius.c */
/* Summary : The implementation of main function's file for this project */
/* Declare : Copyright(C) 2016-2017 QuaOrgin */
/* Remark : none */
/* History : v1.00 Jackie Jiang 2017/10/31 Create */
/*--------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------*/
/* */
/* Include Files */
/* */
/*--------------------------------------------------------------------------*/
#include "quaaquarius.h"
#include "libemqtt.h"
#include "cJSON.h"
#include "mqttclient.h"
#include "readcfg.h"
#include "uart.h"
#include <signal.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <time.h>
//#include<stdio.h>
#include <sys/time.h>
#include <math.h>
#include <stdlib.h>
//#include<unistd.h>
/*--------------------------------------------------------------------------*/
/* */
/* Macros Define */
/* */
/*--------------------------------------------------------------------------*/
#define cMinPeriod 5000 //10ms周期
/*--------------------------------------------------------------------------*/
/* */
/* Local Types */
/* */
/*--------------------------------------------------------------------------*/
struct timeval tv;
UINT periodCnt;
UINT flag5;
UINT flag30;
UINT flag60;
UINT flag10ms;
/*--------------------------------------------------------------------------*/
/* */
/* Global Types */
/* */
/*--------------------------------------------------------------------------*/
QUAAQUARIUSDATA g_sQuaAquariusData = {0};
/*--------------------------------------------------------------------------*/
/* */
/* Extern Global Types */
/* */
/*--------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------*/
/* */
/* Extern Functions */
/* */
/*--------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------*/
/* */
/* Functions Declare */
/* */
/*--------------------------------------------------------------------------*/
void sys_init(void);
void sys_sigroutine(int signal);
void sys_sigterm(int signal);
void sys_timer(void);
int sys_ontask_10ms(void);
int sys_ontask_1s(void);
int sys_ontask_5s(void);
int sys_ontask_30s(void);
int sys_ontask_1min(void);
void sys_final(void);
/*--------------------------------------------------------------------------*/
/* */
/* Functions Define */
/* */
/*--------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------*/
/* @(p) */
/* Name : sys_init */
/* Function : 系统初始化函数 */
/* Return : 无 */
/* Argument : 无 */
/* Create : v1.00 Jackie Jiang 2017/10/31 */
/* Update : */
/* Remark : */
/*--------------------------------------------------------------------------*/
void sys_init(void)
{
periodCnt = 0;
flag5 = 0;
flag30 = 0;
flag60 = 0;
flag10ms = 0;
read_config();//读取配置文件信息
mqttclient_init();//MQTT客户端初始化
sys_timer();//打开定时器与终端
mqttclient_subscribe();//MQTT客户端订阅TOPIC
g_sQuaAquariusData.sServer.uFlag = 0x00;
uart_open();//打开串口1、2、3
}
/*--------------------------------------------------------------------------*/
/* @(p) */
/* Name : main */
/* Function : 主函数入口 */
/* Return : 无 */
/* Argument : 无 */
/* Create : v1.00 Jackie Jiang 2017/10/31 */
/* Update : */
/* Remark : */
/*--------------------------------------------------------------------------*/
int main(int argc, char* argv[])
{
int nRetVal = 0x00;
int nDoRun = 0x01;
//1.system init
sys_init();
//2.main running
while(nDoRun != 0x00 && g_sQuaAquariusData.sServer.gpa >= 0)
{
nRetVal = mqttclient_recv();
}
//3.system final
sys_final();
return nRetVal;
}
/*--------------------------------------------------------------------------*/
/* @(p) */
/* Name : sys_sigroutine */
/* Function : 系统分时任务入口 */
/* Return : 无 */
/* Argument : 无 */
/* Create : v1.00 Jackie Jiang 2017/10/31 */
/* Update : */
/* Remark : */
/*--------------------------------------------------------------------------*/
void sys_sigroutine(int signal)
{
int nRetVal = 0x00;
switch(signal)
{
case SIGALRM:
{
/*periodCnt++;
if(periodCnt >= 500)
{
mqttclient_ping();
gettimeofday(&tv,NULL);
printf("5s task %ld %ld\n",tv.tv_sec,tv.tv_usec);
periodCnt = 0;
}*/
nRetVal = sys_ontask_10ms();
if(periodCnt % 100 == 0)
{
//nRetVal = sys_ontask_1s();
}
if(periodCnt % 500 == 0)
{
nRetVal = sys_ontask_5s();
}
if(periodCnt % 3000 == 0)
{
//nRetVal = sys_ontask_30s();
}
if(periodCnt % 6000 == 0)
{
nRetVal = sys_ontask_1min();
}
periodCnt = (periodCnt + 1 < 6000 ? periodCnt + 1 : 0);
break;
}
case SIGVTALRM:
{
/*gettimeofday(&tv,NULL);
printf("05ms vt %ld %ld\n",tv.tv_sec,tv.tv_usec);*/
break;
}
default:
{
break;
}
}
return;
}
/*--------------------------------------------------------------------------*/
/* @(p) */
/* Name : sys_sigterm */
/* Function : On 10ms'task,then do */
/* Return : int , 1 - OK */
/* Argument : none */
/* Create : v1.00 Jackie Jiang 2017/10/31 */
/* Update : */
/* Remark : */
/*--------------------------------------------------------------------------*/
void sys_sigterm(int signal)
{
printf("Goodbye!\n");
// >>>>> DISCONNECT
//关闭串口
uart_close();
//断开MQTT客户端连接
mqttclient_final();
//mqtt_disconnect(&broker);
//close_socket(&broker);
exit(0);
}
/*--------------------------------------------------------------------------*/
/* @(p) */
/* Name : sys_timer */
/* Function : On 10ms'task,then do */
/* Return : int , 1 - OK */
/* Argument : none */
/* Create : v1.00 Jackie Jiang 2017/10/31 */
/* Update : */
/* Remark : */
/*--------------------------------------------------------------------------*/
void sys_timer(void)
{
struct itimerval itv_real;
//struct itimerval itv_virtual;
struct itimerval itv_old;
signal(SIGALRM,sys_sigroutine);
//signal(SIGVTALRM,sys_sigroutine);
signal(SIGINT,sys_sigterm);
itv_real.it_value.tv_sec = 0;//当前时间计数s
itv_real.it_value.tv_usec = cMinPeriod;//当前时间计数us
itv_real.it_interval.tv_sec = 0;//时间间隔s
itv_real.it_interval.tv_usec = cMinPeriod;//时间间隔us
setitimer(ITIMER_REAL,&itv_real,&itv_old);
//itv_virtual.it_value.tv_sec = 0;/*当前时间计数*/
//itv_virtual.it_value.tv_usec = 50000;/*当前时间计数*/
//itv_virtual.it_interval.tv_sec = 0;/*时间间隔*/
//itv_virtual.it_interval.tv_usec = 50000;/*时间间隔*/
//setitimer(ITIMER_VIRTUAL,&itv_virtual,&itv_old);
}
/*--------------------------------------------------------------------------*/
/* @(p) */
/* Name : sys_ontask_10ms */
/* Function : On 10ms'task,then do */
/* Return : int , 1 - OK */
/* Argument : none */
/* Create : v1.00 Jackie Jiang 2017/10/31 */
/* Update : */
/* Remark : */
/*--------------------------------------------------------------------------*/
int sys_ontask_10ms(void)
{
int nRetVal = 0x01;
if(flag10ms >= 300)
{
//printf("10ms task------->\n");
uart1_recv();//入水水质
uart2_recv();//出水水质
uart3_recv();//放水板通讯
flag10ms = 300;
}
flag10ms++;
return nRetVal;
}
/*--------------------------------------------------------------------------*/
/* @(p) */
/* Name : sys_ontask_1s */
/* Function : On 1s'task,then do */
/* Return : int , 1 - OK */
/* Argument : none */
/* Create : v1.00 Jackie Jiang 2017/10/31 */
/* Update : */
/* Remark : */
/*--------------------------------------------------------------------------*/
int sys_ontask_1s(void)
{
int nRetVal = 0x01;
//printf("1s task------->\n");
/*if(g_sQuaAquariusData.sServer.uFlag == 0x01)
{
mqttclient_publish(cOrderType,0x02);
g_sQuaAquariusData.sServer.uFlag = 0x00;
printf("mqtt send\n");
}*/
return nRetVal;
}
/*--------------------------------------------------------------------------*/
/* @(p) */
/* Name : sys_ontask_5s */
/* Function : On 5s'task,then do */
/* Return : int , 1 - OK */
/* Argument : none */
/* Create : v1.00 Jackie Jiang 2017/10/31 */
/* Update : */
/* Remark : */
/*--------------------------------------------------------------------------*/
int sys_ontask_5s(void)
{
int nRetVal = 0x01;
if(flag5 != 0)
{
printf("5s task------->\n");
time_t timep;
time(&timep);
printf("%s",ctime(&timep));
uart1_send();//入水水质检测命令
uart2_send();//出水水质检测命令
mqttclient_ping();
}
flag5 = 1;
return nRetVal;
}
/*--------------------------------------------------------------------------*/
/* @(p) */
/* Name : sys_ontask_30s */
/* Function : On 30s'task,then do */
/* Return : int , 1 - OK */
/* Argument : none */
/* Create : v1.00 Jackie Jiang 2017/10/31 */
/* Update : */
/* Remark : */
/*--------------------------------------------------------------------------*/
int sys_ontask_30s(void)
{
int nRetVal = 0x01;
return nRetVal;
}
/*--------------------------------------------------------------------------*/
/* @(p) */
/* Name : sys_ontask_1min */
/* Function : On 1min'task,then do */
/* Return : int , 1 - OK */
/* Argument : none */
/* Create : v1.00 Jackie Jiang 2017/10/31 */
/* Update : */
/* Remark : */
/*--------------------------------------------------------------------------*/
int sys_ontask_1min(void)
{
int nRetVal = 0x01;
if(flag60 != 0)
{
printf("1min task------->\n");
time_t timep;
time(&timep);
printf("%s",ctime(&timep));
mqttclient_publish(cMessageType);//每一分钟发送一次水质信息
}
flag60 = 1;
return nRetVal;
}
/*--------------------------------------------------------------------------*/
/* @(p) */
/* NAME : sys_final */
/* FUNCTION : 系统反初始化 */
/* RETURN : none */
/* ARGUMENT : none */
/* CREATE : v0.01 ZH 2012/04/02 Create */
/* UPDATE : */
/* REMARK : */
/*--------------------------------------------------------------------------*/
void sys_final(void)
{
uart_close();//关闭串口
mqttclient_final();//断开MQTT客户端连接
}
cJSON.c
原始数据 复制代码
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754
/*
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. */
/* disable warnings about old C89 functions in MSVC */
#if !defined(_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER)
#define _CRT_SECURE_NO_DEPRECATE
#endif
#ifdef __GNUC__
#pragma GCC visibility push(default)
#endif
#if defined(_MSC_VER)
#pragma warning (push)
/* disable warning about single line comments in system headers */
#pragma warning (disable : 4001)
#endif
#include <string.h>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <float.h>
#include <limits.h>
#include <ctype.h>
#ifdef ENABLE_LOCALES
#include <locale.h>
#endif
#if defined(_MSC_VER)
#pragma warning (pop)
#endif
#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 != 6) || (CJSON_VERSION_PATCH != 0)
#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;
#if defined(_MSC_VER)
/* work around MSVC error C2322: '...' address of dillimport '...' is not static */
static void *internal_malloc(size_t size)
{
return malloc(size);
}
static void internal_free(void *pointer)
{
free(pointer);
}
static void *internal_realloc(void *pointer, size_t size)
{
return realloc(pointer, size);
}
#else
#define internal_malloc malloc
#define internal_free free
#define internal_realloc realloc
#endif
static internal_hooks global_hooks = { internal_malloc, internal_free, internal_realloc };
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("");
copy = (unsigned char*)hooks->allocate(length);
if (copy == NULL)
{
return NULL;
}
memcpy(copy, string, length);
return copy;
}
CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks)
{
if (hooks == NULL)
{
/* Reset hooks */
global_hooks.allocate = malloc;
global_hooks.deallocate = free;
global_hooks.reallocate = realloc;
return;
}
global_hooks.allocate = malloc;
if (hooks->malloc_fn != NULL)
{
global_hooks.allocate = hooks->malloc_fn;
}
global_hooks.deallocate = free;
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 == malloc) && (global_hooks.deallocate == free))
{
global_hooks.reallocate = realloc;
}
}
/* 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)
{
#ifdef ENABLE_LOCALES
struct lconv *lconv = localeconv();
return (unsigned char) lconv->decimal_point[0];
#else
return '.';
#endif
}
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))
/* 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);
if (newbuffer == NULL)
{
p->hooks.deallocate(p->buffer);
p->length = 0;
p->buffer = NULL;
return NULL;
}
}
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;
}
/* skip the UTF-8 BOM (byte order mark) if it is at the beginning of a buffer */
static parse_buffer *skip_utf8_bom(parse_buffer * const buffer)
{
if ((buffer == NULL) || (buffer->content == NULL) || (buffer->offset != 0))
{
return NULL;
}
if (can_access_at_index(buffer, 4) && (strncmp((const char*)buffer_at_offset(buffer), "\xEF\xBB\xBF", 3) == 0))
{
buffer->offset += 3;
}
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(skip_utf8_bom(&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;
}
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))
{
global_hooks.deallocate(p.buffer);
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) || (buf == NULL))
{
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 *child = NULL;
size_t size = 0;
if (array == NULL)
{
return 0;
}
child = array->child;
while(child != NULL)
{
size++;
child = child->next;
}
/* FIXME: Can overflow here. Cannot be fixed without breaking the API */
return (int)size;
}
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 *reference = NULL;
if (item == NULL)
{
return NULL;
}
reference = cJSON_New_Item(hooks);
if (reference == NULL)
{
return NULL;
}
memcpy(reference, item, sizeof(cJSON));
reference->string = NULL;
reference->type |= cJSON_IsReference;
reference->next = reference->prev = NULL;
return reference;
}
/* 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)
{
if (item == NULL)
{
return;
}
/* 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__) || (defined(__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 == NULL) || (string == NULL))
{
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__) || (defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5))))
#pragma GCC diagnostic pop
#endif
CJSON_PUBLIC(void) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item)
{
if (array == NULL)
{
return;
}
cJSON_AddItemToArray(array, create_reference(item, &global_hooks));
}
CJSON_PUBLIC(void) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item)
{
if ((object == NULL) || (string == NULL))
{
return;
}
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) || (item == 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) || (string == 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) || (numbers == NULL))
{
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) || (numbers == NULL))
{
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) || (numbers == NULL))
{
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) || (strings == NULL))
{
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;
if (json == NULL)
{
return;
}
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;
}
/* one of the arrays is longer than the other */
if (a_element != b_element) {
return false;
}
return true;
}
case cJSON_Object:
{
cJSON *a_element = NULL;
cJSON *b_element = NULL;
cJSON_ArrayForEach(a_element, a)
{
/* TODO This has O(n^2) runtime, which is horrible! */
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;
}
}
/* doing this twice, once on a and b to prevent true comparison if a subset of b
* TODO: Do this the proper way, this is just a fix for now */
cJSON_ArrayForEach(b_element, b)
{
a_element = get_object_item(a, b_element->string, case_sensitive);
if (a_element == NULL)
{
return false;
}
if (!cJSON_Compare(b_element, a_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);
}
libemqtt.c
原始数据 复制代码
/*
* This file is part of libemqtt.
*
* libemqtt is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* libemqtt 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. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with libemqtt. If not, see <http://www.gnu.org/licenses/>.
*/
/*
*
* Created by Filipe Varela on 09/10/16.
* Copyright 2009 Caixa Mágica Software. All rights reserved.
*
* Fork developed by Vicente Ruiz Rodríguez
* Copyright 2012 Vicente Ruiz Rodríguez <vruiz2.0@gmail.com>. All rights reserved.
*
*/
#include <string.h>
#include <libemqtt.h>
#define MQTT_DUP_FLAG 1<<3
#define MQTT_QOS0_FLAG 0<<1
#define MQTT_QOS1_FLAG 1<<1
#define MQTT_QOS2_FLAG 2<<1
#define MQTT_RETAIN_FLAG 1
#define MQTT_CLEAN_SESSION 1<<1
#define MQTT_WILL_FLAG 1<<2
#define MQTT_WILL_RETAIN 1<<5
#define MQTT_USERNAME_FLAG 1<<7
#define MQTT_PASSWORD_FLAG 1<<6
uint8_t mqtt_num_rem_len_bytes(const uint8_t* buf) {
uint8_t num_bytes = 1;
//printf("mqtt_num_rem_len_bytes\n");
if ((buf[1] & 0x80) == 0x80) {
num_bytes++;
if ((buf[2] & 0x80) == 0x80) {
num_bytes ++;
if ((buf[3] & 0x80) == 0x80) {
num_bytes ++;
}
}
}
return num_bytes;
}
uint16_t mqtt_parse_rem_len(const uint8_t* buf) {
uint16_t multiplier = 1;
uint16_t value = 0;
uint8_t digit;
//printf("mqtt_parse_rem_len\n");
buf++; // skip "flags" byte in fixed header
do {
digit = *buf;
value += (digit & 127) * multiplier;
multiplier *= 128;
buf++;
} while ((digit & 128) != 0);
return value;
}
uint16_t mqtt_parse_msg_id(const uint8_t* buf) {
uint8_t type = MQTTParseMessageType(buf);
uint8_t qos = MQTTParseMessageQos(buf);
uint16_t id = 0;
//printf("mqtt_parse_msg_id\n");
if(type >= MQTT_MSG_PUBLISH && type <= MQTT_MSG_UNSUBACK) {
if(type == MQTT_MSG_PUBLISH) {
if(qos != 0) {
// fixed header length + Topic (UTF encoded)
// = 1 for "flags" byte + rlb for length bytes + topic size
uint8_t rlb = mqtt_num_rem_len_bytes(buf);
uint8_t offset = *(buf+1+rlb)<<8; // topic UTF MSB
offset |= *(buf+1+rlb+1); // topic UTF LSB
offset += (1+rlb+2); // fixed header + topic size
id = *(buf+offset)<<8; // id MSB
id |= *(buf+offset+1); // id LSB
}
} else {
// fixed header length
// 1 for "flags" byte + rlb for length bytes
uint8_t rlb = mqtt_num_rem_len_bytes(buf);
id = *(buf+1+rlb)<<8; // id MSB
id |= *(buf+1+rlb+1); // id LSB
}
}
return id;
}
uint16_t mqtt_parse_pub_topic(const uint8_t* buf, uint8_t* topic) {
const uint8_t* ptr;
uint16_t topic_len = mqtt_parse_pub_topic_ptr(buf, &ptr);
//printf("mqtt_parse_pub_topic\n");
if(topic_len != 0 && ptr != NULL) {
memcpy(topic, ptr, topic_len);
}
return topic_len;
}
uint16_t mqtt_parse_pub_topic_ptr(const uint8_t* buf, const uint8_t **topic_ptr) {
uint16_t len = 0;
//printf("mqtt_parse_pub_topic_ptr\n");
if(MQTTParseMessageType(buf) == MQTT_MSG_PUBLISH) {
// fixed header length = 1 for "flags" byte + rlb for length bytes
uint8_t rlb = mqtt_num_rem_len_bytes(buf);
len = *(buf+1+rlb)<<8; // MSB of topic UTF
len |= *(buf+1+rlb+1); // LSB of topic UTF
// start of topic = add 1 for "flags", rlb for remaining length, 2 for UTF
*topic_ptr = (buf + (1+rlb+2));
} else {
*topic_ptr = NULL;
}
return len;
}
uint16_t mqtt_parse_publish_msg(const uint8_t* buf, uint8_t* msg) {
const uint8_t* ptr;
//printf("mqtt_parse_publish_msg\n");
uint16_t msg_len = mqtt_parse_pub_msg_ptr(buf, &ptr);
if(msg_len != 0 && ptr != NULL) {
memcpy(msg, ptr, msg_len);
}
return msg_len;
}
uint16_t mqtt_parse_pub_msg_ptr(const uint8_t* buf, const uint8_t **msg_ptr) {
uint16_t len = 0;
//printf("mqtt_parse_pub_msg_ptr\n");
if(MQTTParseMessageType(buf) == MQTT_MSG_PUBLISH) {
// message starts at
// fixed header length + Topic (UTF encoded) + msg id (if QoS>0)
uint8_t rlb = mqtt_num_rem_len_bytes(buf);
uint8_t offset = (*(buf+1+rlb))<<8; // topic UTF MSB
offset |= *(buf+1+rlb+1); // topic UTF LSB
offset += (1+rlb+2); // fixed header + topic size
if(MQTTParseMessageQos(buf)) {
offset += 2; // add two bytes of msg id
}
*msg_ptr = (buf + offset);
// offset is now pointing to start of message
// length of the message is remaining length - variable header
// variable header is offset - fixed header
// fixed header is 1 + rlb
// so, lom = remlen - (offset - (1+rlb))
len = mqtt_parse_rem_len(buf) - (offset-(rlb+1));
} else {
*msg_ptr = NULL;
}
return len;
}
void mqtt_init(mqtt_broker_handle_t* broker, const char* clientid) {
// Connection options
broker->alive = 300; // 300 seconds = 5 minutes
broker->seq = 1; // Sequency for message indetifiers
// Client options
memset(broker->clientid, 0, sizeof(broker->clientid));
memset(broker->username, 0, sizeof(broker->username));
memset(broker->password, 0, sizeof(broker->password));
if(clientid) {
strncpy(broker->clientid, clientid, sizeof(broker->clientid));
} else {
strcpy(broker->clientid, "emqtt");
}
// Will topic
broker->clean_session = 1;
}
void mqtt_init_auth(mqtt_broker_handle_t* broker, const char* username, const char* password) {
if(username && username[0] != '\0')
strncpy(broker->username, username, sizeof(broker->username)-1);
if(password && password[0] != '\0')
strncpy(broker->password, password, sizeof(broker->password)-1);
}
void mqtt_set_alive(mqtt_broker_handle_t* broker, uint16_t alive) {
broker->alive = alive;
}
int mqtt_connect(mqtt_broker_handle_t* broker)
{
uint8_t flags = 0x00;
uint16_t clientidlen = strlen(broker->clientid);
uint16_t usernamelen = strlen(broker->username);
uint16_t passwordlen = strlen(broker->password);
uint16_t payload_len = clientidlen + 2;
// Preparing the flags
if(usernamelen) {
payload_len += usernamelen + 2;
flags |= MQTT_USERNAME_FLAG;
}
if(passwordlen) {
payload_len += passwordlen + 2;
flags |= MQTT_PASSWORD_FLAG;
}
if(broker->clean_session) {
flags |= MQTT_CLEAN_SESSION;
}
// Variable header
uint8_t var_header[] = {
0x00,0x06,0x4d,0x51,0x49,0x73,0x64,0x70, // Protocol name: MQIsdp
0x03, // Protocol version
flags, // Connect flags
broker->alive>>8, broker->alive&0xFF, // Keep alive
};
// Fixed header
uint8_t fixedHeaderSize = 2; // Default size = one byte Message Type + one byte Remaining Length
uint8_t remainLen = sizeof(var_header)+payload_len;
if (remainLen > 127) {
fixedHeaderSize++; // add an additional byte for Remaining Length
}
uint8_t fixed_header[fixedHeaderSize];
// Message Type
fixed_header[0] = MQTT_MSG_CONNECT;
// Remaining Length
if (remainLen <= 127) {
fixed_header[1] = remainLen;
} else {
// first byte is remainder (mod) of 128, then set the MSB to indicate more bytes
fixed_header[1] = remainLen % 128;
fixed_header[1] = fixed_header[1] | 0x80;
// second byte is number of 128s
fixed_header[2] = remainLen / 128;
}
uint16_t offset = 0;
uint8_t packet[sizeof(fixed_header)+sizeof(var_header)+payload_len];
memset(packet, 0, sizeof(packet));
memcpy(packet, fixed_header, sizeof(fixed_header));
offset += sizeof(fixed_header);
memcpy(packet+offset, var_header, sizeof(var_header));
offset += sizeof(var_header);
// Client ID - UTF encoded
packet[offset++] = clientidlen>>8;
packet[offset++] = clientidlen&0xFF;
memcpy(packet+offset, broker->clientid, clientidlen);
offset += clientidlen;
if(usernamelen) {
// Username - UTF encoded
packet[offset++] = usernamelen>>8;
packet[offset++] = usernamelen&0xFF;
memcpy(packet+offset, broker->username, usernamelen);
offset += usernamelen;
}
if(passwordlen) {
// Password - UTF encoded
packet[offset++] = passwordlen>>8;
packet[offset++] = passwordlen&0xFF;
memcpy(packet+offset, broker->password, passwordlen);
offset += passwordlen;
}
// Send the packet
if(broker->send(broker->socket_info, packet, sizeof(packet)) < sizeof(packet)) {
return -1;
}
return 1;
}
int mqtt_disconnect(mqtt_broker_handle_t* broker) {
uint8_t packet[] = {
MQTT_MSG_DISCONNECT, // Message Type, DUP flag, QoS level, Retain
0x00 // Remaining length
};
// Send the packet
if(broker->send(broker->socket_info, packet, sizeof(packet)) < sizeof(packet)) {
return -1;
}
return 1;
}
int mqtt_ping(mqtt_broker_handle_t* broker) {
uint8_t packet[] = {
MQTT_MSG_PINGREQ, // Message Type, DUP flag, QoS level, Retain
0x00 // Remaining length
};
// Send the packet
if(broker->send(broker->socket_info, packet, sizeof(packet)) < sizeof(packet)) {
return -1;
}
return 1;
}
int mqtt_publish(mqtt_broker_handle_t* broker, const char* topic, const char* msg, uint8_t retain) {
return mqtt_publish_with_qos(broker, topic, msg, retain, 0, NULL);
}
int mqtt_publish_with_qos(mqtt_broker_handle_t* broker, const char* topic, const char* msg, uint8_t retain, uint8_t qos, uint16_t* message_id) {
uint16_t topiclen = strlen(topic);
uint16_t msglen = strlen(msg);
uint8_t qos_flag = MQTT_QOS0_FLAG;
uint8_t qos_size = 0; // No QoS included
if(qos == 1) {
qos_size = 2; // 2 bytes for QoS
qos_flag = MQTT_QOS1_FLAG;
}
else if(qos == 2) {
qos_size = 2; // 2 bytes for QoS
qos_flag = MQTT_QOS2_FLAG;
}
// Variable header
uint8_t var_header[topiclen+2+qos_size]; // Topic size (2 bytes), utf-encoded topic
memset(var_header, 0, sizeof(var_header));
var_header[0] = topiclen>>8;
var_header[1] = topiclen&0xFF;
memcpy(var_header+2, topic, topiclen);
if(qos_size) {
var_header[topiclen+2] = broker->seq>>8;
var_header[topiclen+3] = broker->seq&0xFF;
if(message_id) { // Returning message id
*message_id = broker->seq;
}
broker->seq++;
}
// Fixed header
// the remaining length is one byte for messages up to 127 bytes, then two bytes after that
// actually, it can be up to 4 bytes but I'm making the assumption the embedded device will only
// need up to two bytes of length (handles up to 16,383 (almost 16k) sized message)
uint8_t fixedHeaderSize = 2; // Default size = one byte Message Type + one byte Remaining Length
uint16_t remainLen = sizeof(var_header)+msglen;
if (remainLen > 127) {
fixedHeaderSize++; // add an additional byte for Remaining Length
}
uint8_t fixed_header[fixedHeaderSize];
// Message Type, DUP flag, QoS level, Retain
fixed_header[0] = MQTT_MSG_PUBLISH | qos_flag;
if(retain) {
fixed_header[0] |= MQTT_RETAIN_FLAG;
}
// Remaining Length
if (remainLen <= 127) {
fixed_header[1] = remainLen;
} else {
// first byte is remainder (mod) of 128, then set the MSB to indicate more bytes
fixed_header[1] = remainLen % 128;
fixed_header[1] = fixed_header[1] | 0x80;
// second byte is number of 128s
fixed_header[2] = remainLen / 128;
}
uint8_t packet[sizeof(fixed_header)+sizeof(var_header)+msglen];
memset(packet, 0, sizeof(packet));
memcpy(packet, fixed_header, sizeof(fixed_header));
memcpy(packet+sizeof(fixed_header), var_header, sizeof(var_header));
memcpy(packet+sizeof(fixed_header)+sizeof(var_header), msg, msglen);
// Send the packet
if(broker->send(broker->socket_info, packet, sizeof(packet)) < sizeof(packet)) {
return -1;
}
return 1;
}
int mqtt_pubrel(mqtt_broker_handle_t* broker, uint16_t message_id) {
uint8_t packet[] = {
MQTT_MSG_PUBREL | MQTT_QOS1_FLAG, // Message Type, DUP flag, QoS level, Retain
0x02, // Remaining length
message_id>>8,
message_id&0xFF
};
// Send the packet
if(broker->send(broker->socket_info, packet, sizeof(packet)) < sizeof(packet)) {
return -1;
}
return 1;
}
int mqtt_subscribe(mqtt_broker_handle_t* broker, const char* topic, uint16_t* message_id) {
uint16_t topiclen = strlen(topic);
// Variable header
uint8_t var_header[2]; // Message ID
var_header[0] = broker->seq>>8;
var_header[1] = broker->seq&0xFF;
if(message_id) { // Returning message id
*message_id = broker->seq;
}
broker->seq++;
// utf topic
uint8_t utf_topic[topiclen+3]; // Topic size (2 bytes), utf-encoded topic, QoS byte
memset(utf_topic, 0, sizeof(utf_topic));
utf_topic[0] = topiclen>>8;
utf_topic[1] = topiclen&0xFF;
memcpy(utf_topic+2, topic, topiclen);
// Fixed header
uint8_t fixed_header[] = {
MQTT_MSG_SUBSCRIBE | MQTT_QOS1_FLAG, // Message Type, DUP flag, QoS level, Retain
sizeof(var_header)+sizeof(utf_topic)
};
uint8_t packet[sizeof(var_header)+sizeof(fixed_header)+sizeof(utf_topic)];
memset(packet, 0, sizeof(packet));
memcpy(packet, fixed_header, sizeof(fixed_header));
memcpy(packet+sizeof(fixed_header), var_header, sizeof(var_header));
memcpy(packet+sizeof(fixed_header)+sizeof(var_header), utf_topic, sizeof(utf_topic));
// Send the packet
if(broker->send(broker->socket_info, packet, sizeof(packet)) < sizeof(packet)) {
return -1;
}
return 1;
}
int mqtt_unsubscribe(mqtt_broker_handle_t* broker, const char* topic, uint16_t* message_id) {
uint16_t topiclen = strlen(topic);
// Variable header
uint8_t var_header[2]; // Message ID
var_header[0] = broker->seq>>8;
var_header[1] = broker->seq&0xFF;
if(message_id) { // Returning message id
*message_id = broker->seq;
}
broker->seq++;
// utf topic
uint8_t utf_topic[topiclen+2]; // Topic size (2 bytes), utf-encoded topic
memset(utf_topic, 0, sizeof(utf_topic));
utf_topic[0] = topiclen>>8;
utf_topic[1] = topiclen&0xFF;
memcpy(utf_topic+2, topic, topiclen);
// Fixed header
uint8_t fixed_header[] = {
MQTT_MSG_UNSUBSCRIBE | MQTT_QOS1_FLAG, // Message Type, DUP flag, QoS level, Retain
sizeof(var_header)+sizeof(utf_topic)
};
uint8_t packet[sizeof(var_header)+sizeof(fixed_header)+sizeof(utf_topic)];
memset(packet, 0, sizeof(packet));
memcpy(packet, fixed_header, sizeof(fixed_header));
memcpy(packet+sizeof(fixed_header), var_header, sizeof(var_header));
memcpy(packet+sizeof(fixed_header)+sizeof(var_header), utf_topic, sizeof(utf_topic));
// Send the packet
if(broker->send(broker->socket_info, packet, sizeof(packet)) < sizeof(packet)) {
return -1;
}
return 1;
}
mqttclient.c
原始数据 复制代码
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
/*--------------------------------------------------------------------------*/
/* Project : QuaAquarius */
/* File : mqttclient.c */
/* Summary : The implementation of main function's file for this project.*/
/* Declare : Copyright(C) 2016-2017 QuaOrgin */
/* Remark : none */
/* History : v1.00 Jackie Jiang 2017/10/31 Create */
/*--------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------*/
/* */
/* Include Files */
/* */
/*--------------------------------------------------------------------------*/
#include "quaaquarius.h"
#include "libemqtt.h"
#include "cJSON.h"
#include "mqttclient.h"
#include "uart.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <linux/tcp.h>
#include <signal.h>
//#include<stdio.h>
//#include<stdlib.h>
//#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<termios.h>
#include<errno.h>
//#include<string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <time.h>
#include <sys/time.h>
/*--------------------------------------------------------------------------*/
/* */
/* Macros Define */
/* */
/*--------------------------------------------------------------------------*/
#define RCVBUFSIZE 1024
#define cKeepAlive 60
#define cWaterPointsId "WaterPointsId"
#define cTapId "TapId"
#define cOutTradeNO "OutTradeNO"
#define cVolume "Volume"
#define cCloseStatus "CloseStatus"
#define cInTOC "InTOC"
#define cInCOD "InCOD"
#define cInChromaticity "InChromaticity"
#define cInTurbidity "InTurbidity"
#define cInTemperature "InTemperature"
#define cOutTOC "OutTOC"
#define cOutCOD "OutCOD"
#define cOutChromaticity "OutChromaticity"
#define cOutTurbidity "OutTurbidity"
#define cOutTemperature "OutTemperature"
#define cVInit 0x00 //初始化
#define cVWaiting 0x01 //接收订单成功,等待按键开启
#define cVPressed 0x02 //按键按下,开始放水
#define cVReleOK 0x03 //足量放水完成
#define cVaeleInt 0x04 //按键中断放水完成
#define cVUnpressed 0x05 //按键10s内未按下,放水结束
#define cVError 0x06 //放水故障
/*--------------------------------------------------------------------------*/
/* */
/* Local Types */
/* */
/*--------------------------------------------------------------------------*/
uint8_t packet_buffer[RCVBUFSIZE];
int keepalive;
int socket_id;
int gPacket_len;
mqtt_broker_handle_t broker;
struct timeval tv;
struct itimerval value, ovalue;
/*--------------------------------------------------------------------------*/
/* */
/* Global Types */
/* */
/*--------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------*/
/* */
/* Extern Global Types */
/* */
/*--------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------*/
/* */
/* Extern Functions */
/* */
/*--------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------*/
/* */
/* Functions Declare */
/* */
/*--------------------------------------------------------------------------*/
int mqttclient_init(void);
int mqttclient_subscribe(void);
void mqttclient_publish(UINT8 pubType);
int mqttclient_recv(void);
void mqttclient_ping(void);
void mqttclient_final(void);
int read_packet(int timeout);
int send_packet(void* socket_info, const void* buf, unsigned int count);
int init_socket(mqtt_broker_handle_t* broker, const char* hostname, short port, int keepalive);
int close_socket(mqtt_broker_handle_t* broker);
//void alive(int signal);
//void term(int signal);
/*--------------------------------------------------------------------------*/
/* */
/* Functions Define */
/* */
/*--------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------*/
/* @(p) */
/* Name : mqttclient_init */
/* Function : mqtt客户端初始化 */
/* Return : 无 */
/* Argument : 无 */
/* Create : v1.00 Jackie Jiang 2017/10/31 */
/* Update : */
/* Remark : */
/*--------------------------------------------------------------------------*/
int mqttclient_init(void)
{
//int packet_length;
keepalive = cKeepAlive;
/**使用客户端ID初始化mqtt**/
mqtt_init(&broker,g_sQuaAquariusData.sConfig.uMQTTClientId);
/**使用用户名和密码进行身份认证**/
mqtt_init_auth(&broker,g_sQuaAquariusData.sConfig.uMQTTUserName,g_sQuaAquariusData.sConfig.uMQTTPassword);
/**使用IP和端口进行socket连接**/
init_socket(&broker,g_sQuaAquariusData.sConfig.uMQTTHost,g_sQuaAquariusData.sConfig.uMQTTPort,keepalive);
// >>>>> CONNECT 连接对象
mqtt_connect(&broker);
// <<<<< CONNACK 连接反馈
gPacket_len = read_packet(1);
if(gPacket_len < 0)
{
fprintf(stderr,"Error(%d) on read packet!init\n",gPacket_len);
return -1;
}
if(MQTTParseMessageType(packet_buffer) != MQTT_MSG_CONNACK)
{
fprintf(stderr,"CONNACK expected!\n");
return -2;
}
if(packet_buffer[3] != 0x00)
{
fprintf(stderr,"CONNACK failed!\n");
return -2;
}
// Signals after connect MQTT
/*value.it_value.tv_sec = 0;
value.it_value.tv_usec = 5000;
value.it_interval.tv_sec = 0;
value.it_interval.tv_usec = 5000;
setitimer(ITIMER_REAL, &value, &ovalue);*/
//signal(SIGALRM, sigroutine);
////signal(SIGALRM,alive);
//alarm(keepalive);
////signal(SIGINT,term);
/**MQTT客户端开始订阅**/
//mqttclient_subscribe();
return 0;
}
/*--------------------------------------------------------------------------*/
/* @(p) */
/* Name : mqttclient_subscribe */
/* Function : mqtt客户端订阅 */
/* Return : 无 */
/* Argument : 无 */
/* Create : v1.00 Jackie Jiang 2017/10/31 */
/* Update : */
/* Remark : */
/*--------------------------------------------------------------------------*/
int mqttclient_subscribe(void)
{
uint16_t msg_id;
uint16_t msg_id_rcv;
// >>>>> SUBSCRIBE 订阅
mqtt_subscribe(&broker,strcat(g_sQuaAquariusData.sConfig.uMQTTSubTitle,g_sQuaAquariusData.sConfig.uMQTTClientId),&msg_id);
// <<<<< SUBACK 订阅反馈
gPacket_len = read_packet(0);
g_sQuaAquariusData.sServer.gpa = gPacket_len;
printf("Sub OK %d\n",gPacket_len);
if(gPacket_len < 0)
{
fprintf(stderr,"Error(%d) on read packet!sub\n",gPacket_len);
return -1;
}
if(MQTTParseMessageType(packet_buffer) != MQTT_MSG_SUBACK)
{
fprintf(stderr,"SUBACK expected!\n");
return -2;
}
msg_id_rcv = mqtt_parse_msg_id(packet_buffer);
if(msg_id != msg_id_rcv)
{
fprintf(stderr,"%d message id was expected, but %d message id was found!\n",msg_id,msg_id_rcv);
return -3;
}
return 0;
}
/*--------------------------------------------------------------------------*/
/* @(p) */
/* Name : mqtt_init */
/* Function : mqtt客户端数据发布 */
/* Return : 无 */
/* Argument : 无 */
/* Create : v1.00 Jackie Jiang 2017/10/31 */
/* Update : */
/* Remark : */
/*--------------------------------------------------------------------------*/
void mqttclient_publish(UINT8 pubType)
{
INT8 *sendBuf;
cJSON *sendJson = cJSON_CreateObject();
switch(pubType)
{
case cOrderType://订单类型
{
cJSON_AddStringToObject(sendJson,cWaterPointsId,g_sQuaAquariusData.sCore.uWaterPointsId);//设备编号从JSON接收中取
cJSON_AddNumberToObject(sendJson,cTapId,g_sQuaAquariusData.sCore.uTapId);//水龙头编号
if(g_sQuaAquariusData.sCore.uTapId == 0x01)
{
cJSON_AddStringToObject(sendJson,cOutTradeNO,g_sQuaAquariusData.sCore.uOutTradeNOTap1);//交易编号
cJSON_AddNumberToObject(sendJson,cVolume,g_sQuaAquariusData.sRelease.uResVolumeTap1);//实际反馈水量
cJSON_AddNumberToObject(sendJson,cCloseStatus,g_sQuaAquariusData.sCore.uValveStsTap1);//放水状态
}
else if(g_sQuaAquariusData.sCore.uTapId == 0x02)
{
cJSON_AddStringToObject(sendJson,cOutTradeNO,g_sQuaAquariusData.sCore.uOutTradeNOTap2);//交易编号
cJSON_AddNumberToObject(sendJson,cVolume,g_sQuaAquariusData.sRelease.uResVolumeTap2);//实际反馈水量
cJSON_AddNumberToObject(sendJson,cCloseStatus,g_sQuaAquariusData.sCore.uValveStsTap2);//放水状态
}
cJSON_AddNumberToObject(sendJson,cInTOC,g_sQuaAquariusData.sTDS.fInTOC);//入水水质
cJSON_AddNumberToObject(sendJson,cInCOD,g_sQuaAquariusData.sTDS.fInCOD);
cJSON_AddNumberToObject(sendJson,cInChromaticity,g_sQuaAquariusData.sTDS.fInChromaticity);
cJSON_AddNumberToObject(sendJson,cInTurbidity,g_sQuaAquariusData.sTDS.fInTurbidity);
cJSON_AddNumberToObject(sendJson,cInTemperature,g_sQuaAquariusData.sTDS.fInTemperature);
cJSON_AddNumberToObject(sendJson,cOutTOC,g_sQuaAquariusData.sTDS.fOutTOC);//出水水质
cJSON_AddNumberToObject(sendJson,cOutCOD,g_sQuaAquariusData.sTDS.fOutCOD);
cJSON_AddNumberToObject(sendJson,cOutChromaticity,g_sQuaAquariusData.sTDS.fOutChromaticity);
cJSON_AddNumberToObject(sendJson,cOutTurbidity,g_sQuaAquariusData.sTDS.fOutTurbidity);
cJSON_AddNumberToObject(sendJson,cOutTemperature,g_sQuaAquariusData.sTDS.fOutTemperature);
sendBuf = cJSON_Print(sendJson);
printf("OrderType is\n%s\n",sendBuf);
mqtt_publish(&broker,g_sQuaAquariusData.sConfig.uMQTTPubOrder,sendBuf,0);
break;
}
case cMessageType://水质类型
{
cJSON_AddStringToObject(sendJson,cWaterPointsId,g_sQuaAquariusData.sConfig.uMQTTClientId);//设备编号从CONFIG接收中取
cJSON_AddNumberToObject(sendJson,cInTOC,g_sQuaAquariusData.sTDS.fInTOC);//入水水质
cJSON_AddNumberToObject(sendJson,cInCOD,g_sQuaAquariusData.sTDS.fInCOD);
cJSON_AddNumberToObject(sendJson,cInChromaticity,g_sQuaAquariusData.sTDS.fInChromaticity);
cJSON_AddNumberToObject(sendJson,cInTurbidity,g_sQuaAquariusData.sTDS.fInTurbidity);
cJSON_AddNumberToObject(sendJson,cInTemperature,g_sQuaAquariusData.sTDS.fInTemperature);
cJSON_AddNumberToObject(sendJson,cOutTOC,g_sQuaAquariusData.sTDS.fOutTOC);//出水水质
cJSON_AddNumberToObject(sendJson,cOutCOD,g_sQuaAquariusData.sTDS.fOutCOD);
cJSON_AddNumberToObject(sendJson,cOutChromaticity,g_sQuaAquariusData.sTDS.fOutChromaticity);
cJSON_AddNumberToObject(sendJson,cOutTurbidity,g_sQuaAquariusData.sTDS.fOutTurbidity);
cJSON_AddNumberToObject(sendJson,cOutTemperature,g_sQuaAquariusData.sTDS.fOutTemperature);
sendBuf = cJSON_Print(sendJson);
printf("MessageType is\n%s\n",sendBuf);
mqtt_publish(&broker,g_sQuaAquariusData.sConfig.uMQTTPubMessage,sendBuf,0);
break;
}
case cDeviceType://设备状态类型
{
cJSON_AddStringToObject(sendJson,cWaterPointsId,g_sQuaAquariusData.sConfig.uMQTTClientId);//设备编号从CONFIG接收中取
cJSON_AddNumberToObject(sendJson,cWaterPointsId,g_sQuaAquariusData.sCore.uDeviceSts);//设备状态
cJSON_AddStringToObject(sendJson,cWaterPointsId,g_sQuaAquariusData.sCore.uDeviceErr);//设备故障描述
sendBuf = cJSON_Print(sendJson);
printf("DeviceType is\n%s\n",sendBuf);
mqtt_publish(&broker,g_sQuaAquariusData.sConfig.uMQTTPubDevice,sendBuf,0);
break;
}
default:
{
break;
}
}
/*if(msgType == cOrderType)
{
cJSON_AddStringToObject(sendJson,cWaterPointsId,g_sQuaAquariusData.sCore.uWaterPointsId);
}
else
{
cJSON_AddStringToObject(sendJson,cWaterPointsId,g_sQuaAquariusData.sConfig.uMQTTClientId);
}
//cJSON_AddStringToObject(sendJson,cWaterPointsId,g_sQuaAquariusData.sCore.uWaterPointsId);
//cJSON_AddStringToObject(sendJson,cWaterPointsId,g_sQuaAquariusData.sConfig.uMQTTClientId);
if(msgType == cOrderType)
{
cJSON_AddNumberToObject(sendJson,cTapId,g_sQuaAquariusData.sCore.uTapId);
cJSON_AddStringToObject(sendJson,cOutTradeNO,g_sQuaAquariusData.sCore.uOutTradeNO);
//cJSON_AddNumberToObject(sendJson,cVolume,g_sQuaAquariusData.sRelease.uResVolume);
if(statusType == 0x01)
{
cJSON_AddNumberToObject(sendJson,cVolume,g_sQuaAquariusData.sCore.uReqVolume);
g_sQuaAquariusData.sCore.uValveSts = cValveOpening;
cJSON_AddNumberToObject(sendJson,cCloseStatus,g_sQuaAquariusData.sCore.uValveSts);
}
else if(statusType == 0x02)
{
//g_sQuaAquariusData.sRelease.uResVolume = 100;
cJSON_AddNumberToObject(sendJson,cVolume,g_sQuaAquariusData.sRelease.uResVolume);
g_sQuaAquariusData.sCore.uValveSts = cValveClosedReach;
cJSON_AddNumberToObject(sendJson,cCloseStatus,g_sQuaAquariusData.sCore.uValveSts);
}
}
cJSON_AddNumberToObject(sendJson,cInTOC,g_sQuaAquariusData.sTDS.fInTOC);
cJSON_AddNumberToObject(sendJson,cInCOD,g_sQuaAquariusData.sTDS.fInCOD);
cJSON_AddNumberToObject(sendJson,cInChromaticity,g_sQuaAquariusData.sTDS.fInChromaticity);
cJSON_AddNumberToObject(sendJson,cInTurbidity,g_sQuaAquariusData.sTDS.fInTurbidity);
cJSON_AddNumberToObject(sendJson,cInTemperature,g_sQuaAquariusData.sTDS.fInTemperature);
cJSON_AddNumberToObject(sendJson,cOutTOC,g_sQuaAquariusData.sTDS.fOutTOC);
cJSON_AddNumberToObject(sendJson,cOutCOD,g_sQuaAquariusData.sTDS.fOutCOD);
cJSON_AddNumberToObject(sendJson,cOutChromaticity,g_sQuaAquariusData.sTDS.fOutChromaticity);
cJSON_AddNumberToObject(sendJson,cOutTurbidity,g_sQuaAquariusData.sTDS.fOutTurbidity);
cJSON_AddNumberToObject(sendJson,cOutTemperature,g_sQuaAquariusData.sTDS.fOutTemperature);
sendBuf = cJSON_Print(sendJson);
printf("the send buff is\n%s\n",sendBuf);
if(msgType == cOrderType)
{
mqtt_publish(&broker,g_sQuaAquariusData.sConfig.uMQTTPubOrder,sendBuf,0);
}
else
{
mqtt_publish(&broker,g_sQuaAquariusData.sConfig.uMQTTPubMessage,sendBuf,0);
}*/
cJSON_Delete(sendJson);
}
/*--------------------------------------------------------------------------*/
/* @(p) */
/* Name : mqttclient_recv */
/* Function : mqtt客户端数据接收 */
/* Return : 无 */
/* Argument : 无 */
/* Create : v1.00 Jackie Jiang 2017/10/31 */
/* Update : */
/* Remark : */
/*--------------------------------------------------------------------------*/
int mqttclient_recv(void)
{
//开始接收数据
gPacket_len = read_packet(0);
//
if(gPacket_len == -1)
{
fprintf(stderr,"Error(%d) on read packet!recv\n",gPacket_len);
return -1;
}
else if(gPacket_len > 0)
{
printf("gPacket_len:%d\n",gPacket_len);
printf("Packet Header: 0x%x...\n",packet_buffer[0]);
if(MQTTParseMessageType(packet_buffer) == MQTT_MSG_PUBLISH)
{
uint8_t topic[80] = {0};
uint8_t msg[512] = {0};
uint16_t len;
uint8_t *recvBuf;
cJSON *recvJson;
cJSON *recvItem;
len = mqtt_parse_pub_topic(packet_buffer,topic);
topic[len] = '\0'; // for printf
len = mqtt_parse_publish_msg(packet_buffer,msg);
msg[len] = '\0'; // for printf
printf("Topic is %s\nMessage is %s\nLength is %d\n",topic,msg,len);
recvBuf = msg;
recvJson = cJSON_Parse((const char*)recvBuf);//(const char*)
/**********WaterPointsId**********/
recvItem = cJSON_GetObjectItem(recvJson,cWaterPointsId);
if (recvItem != NULL)
{
strcpy(g_sQuaAquariusData.sCore.uWaterPointsId,recvItem->valuestring);
printf("WaterPointsId is %s\n",g_sQuaAquariusData.sCore.uWaterPointsId);
}
else
{
printf("No WaterPointsId\n");
}
/**********TapId**********/
recvItem = cJSON_GetObjectItem(recvJson,cTapId);
if (recvItem != NULL)
{
g_sQuaAquariusData.sCore.uTapId = recvItem->valueint;
printf("TapId is %d\n",g_sQuaAquariusData.sCore.uTapId);
}
else
{
printf("No TapId\n");
}
/**********OutTradeNO**********/
recvItem = cJSON_GetObjectItem(recvJson,cOutTradeNO);
if (recvItem != NULL)
{
if(g_sQuaAquariusData.sCore.uTapId == 0x01)
{
strcpy(g_sQuaAquariusData.sCore.uOutTradeNOTap1,recvItem->valuestring);
printf("OutTradeNOTap1 is %s\n",g_sQuaAquariusData.sCore.uOutTradeNOTap1);
}
else if(g_sQuaAquariusData.sCore.uTapId == 0x02)
{
strcpy(g_sQuaAquariusData.sCore.uOutTradeNOTap2,recvItem->valuestring);
printf("OutTradeNOTap2 is %s\n",g_sQuaAquariusData.sCore.uOutTradeNOTap2);
}
}
else
{
printf("No OutTradeNO\n");
}
/**********Volume**********/
recvItem = cJSON_GetObjectItem(recvJson,cVolume);
if (recvItem != NULL)
{
if(g_sQuaAquariusData.sCore.uTapId == 0x01)
{
g_sQuaAquariusData.sCore.uReqVolumeTap1 = (int)recvItem->valuedouble;
printf("ReqVolumeTap1 is %d\n",g_sQuaAquariusData.sCore.uReqVolumeTap1);
g_sQuaAquariusData.sCore.uReqVolumeHTap1 = (UINT8)(g_sQuaAquariusData.sCore.uReqVolumeTap1 >> 8);
g_sQuaAquariusData.sCore.uReqVolumeLTap1 = (UINT8)(g_sQuaAquariusData.sCore.uReqVolumeTap1 & 0x00FF);
printf("%02X ",g_sQuaAquariusData.sCore.uReqVolumeHTap1);
printf("%02X\n",g_sQuaAquariusData.sCore.uReqVolumeLTap1);
}
else if(g_sQuaAquariusData.sCore.uTapId == 0x02)
{
g_sQuaAquariusData.sCore.uReqVolumeTap2 = (int)recvItem->valuedouble;
printf("ReqVolumeTap2 is %d\n",g_sQuaAquariusData.sCore.uReqVolumeTap2);
g_sQuaAquariusData.sCore.uReqVolumeHTap2 = (UINT8)(g_sQuaAquariusData.sCore.uReqVolumeTap2 >> 8);
g_sQuaAquariusData.sCore.uReqVolumeLTap2 = (UINT8)(g_sQuaAquariusData.sCore.uReqVolumeTap2 & 0x00FF);
printf("%02X ",g_sQuaAquariusData.sCore.uReqVolumeHTap2);
printf("%02X\n",g_sQuaAquariusData.sCore.uReqVolumeLTap2);
}
}
else
{
printf("No Volume\n");
}
if(strcmp(g_sQuaAquariusData.sCore.uWaterPointsId,g_sQuaAquariusData.sConfig.uMQTTClientId) == 0)
{
uart3_send();
printf("uart3_send\n");
}
//mqttclient_publish(cOrderType);
cJSON_Delete(recvJson);
}
}
else
{
printf("diaoxian\n");
}
return 0;
}
void mqttclient_ping(void)
{
mqtt_ping(&broker);
}
/*--------------------------------------------------------------------------*/
/* @(p) */
/* Name : mqttclient_final */
/* Function : mqtt客户端反初始化 */
/* Return : 无 */
/* Argument : 无 */
/* Create : v1.00 Jackie Jiang 2017/10/31 */
/* Update : */
/* Remark : */
/*--------------------------------------------------------------------------*/
void mqttclient_final(void)
{
mqtt_disconnect(&broker);
close_socket(&broker);
}
/*--------------------------------------------------------------------------*/
/* @(p) */
/* Name : read_packet */
/* Function : mqtt客户端读包 */
/* Return : 无 */
/* Argument : 无 */
/* Create : v1.00 Jackie Jiang 2017/10/31 */
/* Update : */
/* Remark : */
/*--------------------------------------------------------------------------*/
int read_packet(int timeout)
{
if(timeout > 0)
{
fd_set readfds;
struct timeval tmv;
// Initialize the file descriptor set
FD_ZERO (&readfds);
FD_SET (socket_id, &readfds);
// Initialize the timeout data structure
tmv.tv_sec = timeout;
tmv.tv_usec = 0;
// select returns 0 if timeout, 1 if input available, -1 if error
if(select(1, &readfds, NULL, NULL, &tmv))
return -2;
}
int total_bytes = 0, bytes_rcvd, packet_length;
memset(packet_buffer, 0, sizeof(packet_buffer));
if((bytes_rcvd = recv(socket_id, (packet_buffer+total_bytes), RCVBUFSIZE, 0)) <= 0) {
return -1;
}
total_bytes += bytes_rcvd; // Keep tally of total bytes
if (total_bytes < 2)
return -1;
// now we have the full fixed header in packet_buffer
// parse it for remaining length and number of bytes
uint16_t rem_len = mqtt_parse_rem_len(packet_buffer);
uint8_t rem_len_bytes = mqtt_num_rem_len_bytes(packet_buffer);
//packet_length = packet_buffer[1] + 2; // Remaining length + fixed header length
// total packet length = remaining length + byte 1 of fixed header + remaning length part of fixed header
packet_length = rem_len + rem_len_bytes + 1;
while(total_bytes < packet_length) // Reading the packet
{
if((bytes_rcvd = recv(socket_id, (packet_buffer+total_bytes), RCVBUFSIZE, 0)) <= 0)
return -1;
total_bytes += bytes_rcvd; // Keep tally of total bytes
}
return packet_length;
}
/*--------------------------------------------------------------------------*/
/* @(p) */
/* Name : send_packet */
/* Function : mqtt客户端发包 */
/* Return : 无 */
/* Argument : 无 */
/* Create : v1.00 Jackie Jiang 2017/10/31 */
/* Update : */
/* Remark : */
/*--------------------------------------------------------------------------*/
int send_packet(void* socket_info, const void* buf, unsigned int count)
{
int fd = *((int*)socket_info);
return send(fd,buf,count,0);
}
/*--------------------------------------------------------------------------*/
/* @(p) */
/* Name : mqtt_init */
/* Function : mqtt客户端初始化函数 */
/* Return : 无 */
/* Argument : 无 */
/* Create : v1.00 Jackie Jiang 2017/10/31 */
/* Update : */
/* Remark : */
/*--------------------------------------------------------------------------*/
int init_socket(mqtt_broker_handle_t* broker, const char* hostname, short port, int keepalive)
{
int flag = 1;
// Create the socket
if((socket_id = socket(PF_INET, SOCK_STREAM, 0)) < 0)
return -1;
// Disable Nagle Algorithm
if (setsockopt(socket_id, IPPROTO_TCP, TCP_NODELAY, (char*)&flag, sizeof(flag)) < 0)
return -2;
struct sockaddr_in socket_address;
// Create the stuff we need to connect
socket_address.sin_family = AF_INET;
socket_address.sin_port = htons(port);
socket_address.sin_addr.s_addr = inet_addr(hostname);
// Connect the socket
if((connect(socket_id, (struct sockaddr*)&socket_address, sizeof(socket_address))) < 0)
return -1;
// MQTT stuffs
mqtt_set_alive(broker,keepalive);
broker->socket_info = (void*)&socket_id;
broker->send = send_packet;
return 0;
}
/*--------------------------------------------------------------------------*/
/* @(p) */
/* Name : close_socket */
/* Function : mqtt客户端初始化函数 */
/* Return : 无 */
/* Argument : 无 */
/* Create : v1.00 Jackie Jiang 2017/10/31 */
/* Update : */
/* Remark : */
/*--------------------------------------------------------------------------*/
int close_socket(mqtt_broker_handle_t* broker)
{
int fd = *((int*)broker->socket_info);
return close(fd);
}
/*--------------------------------------------------------------------------*/
/* @(p) */
/* Name : mqtt_init */
/* Function : mqtt客户端初始化函数 */
/* Return : 无 */
/* Argument : 无 */
/* Create : v1.00 Jackie Jiang 2017/10/31 */
/* Update : */
/* Remark : */
/*--------------------------------------------------------------------------*/
/*void alive(int signal)
{
gettimeofday(&tv,NULL);
//printf("Timeout! Sending ping...\n");
printf("task------->%ld %ld\n",tv.tv_sec,tv.tv_usec);
//mqtt_ping(&broker);
//alarm(keepalive);
}*/
/*--------------------------------------------------------------------------*/
/* @(p) */
/* Name : mqtt_init */
/* Function : mqtt客户端初始化函数 */
/* Return : 无 */
/* Argument : 无 */
/* Create : v1.00 Jackie Jiang 2017/10/31 */
/* Update : */
/* Remark : */
/*--------------------------------------------------------------------------*/
/*void term(int signal)
{
printf("Goodbye!\n");
// >>>>> DISCONNECT
mqtt_disconnect(&broker);
close_socket(&broker);
exit(0);
}*/
readcfg.c
原始数据 复制代码
/*--------------------------------------------------------------------------*/
/* Project : QuaAquarius */
/* File : readcfg.c */
/* Summary : The implementation of main function's file for this project */
/* Declare : Copyright(C) 2016-2017 QuaOrgin */
/* Remark : none */
/* History : v1.00 Jackie Jiang 2017/10/31 Create */
/*--------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------*/
/* */
/* Include Files */
/* */
/*--------------------------------------------------------------------------*/
#include "quaaquarius.h"
#include "cJSON.h"
#include "readcfg.h"
#include <signal.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <time.h>
//#include<stdio.h>
#include <sys/time.h>
#include <math.h>
#include <stdlib.h>
//#include<unistd.h>
/*--------------------------------------------------------------------------*/
/* */
/* Macros Define */
/* */
/*--------------------------------------------------------------------------*/
#define cBufferSize 1024
#define cMQTTClientId "MQTTClientId"
#define cMQTTSubTitle "MQTTSubTitle"
#define cMQTTPubOrder "MQTTPubOrder"
#define cMQTTPubMessage "MQTTPubMessage"
#define cMQTTPubDevice "MQTTPubDevice"
#define cMQTTHost "MQTTHost"
#define cMQTTPort "MQTTPort"
#define cMQTTUserName "MQTTUserName"
#define cMQTTPassword "MQTTPassword"
#define cSerial1Port "Serial1Port"
#define cSerial2Port "Serial2Port"
#define cSerial3Port "Serial3Port"
#define cSerialBaudRate "SerialBaudRate"
#define cSerialDataBit "SerialDataBit"
#define cSerialStopBit "SerialStopBit"
/*--------------------------------------------------------------------------*/
/* */
/* Local Types */
/* */
/*--------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------*/
/* */
/* Global Types */
/* */
/*--------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------*/
/* */
/* Extern Global Types */
/* */
/*--------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------*/
/* */
/* Extern Functions */
/* */
/*--------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------*/
/* */
/* Functions Declare */
/* */
/*--------------------------------------------------------------------------*/
void read_config(void);
/*--------------------------------------------------------------------------*/
/* */
/* Functions Define */
/* */
/*--------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------*/
/* @(p) */
/* Name : read_config */
/* Function : ȡļ */
/* Return : */
/* Argument : */
/* Create : v1.00 Jackie Jiang 2017/10/31 */
/* Update : */
/* Remark : */
/*--------------------------------------------------------------------------*/
void read_config(void)
{
FILE *fp = NULL;
cJSON *cfgJson = NULL;
cJSON *cfgItem = NULL;
INT8 buffer[cBufferSize] = {0};
INT8 *cfgStr = NULL;
UINT readCnt;
if((fp = fopen("/opt/hkqy/config.json","r")) == NULL)
{
printf("Can't find the correct config file\n");
exit(1);
}
readCnt = fread(buffer,sizeof(INT8),cBufferSize,fp);
printf("readCnt is %d\n", readCnt);
fclose(fp);
cfgStr = buffer;
cfgJson = cJSON_Parse(cfgStr);
/**********MQTTClientId**********/
cfgItem = cJSON_GetObjectItem(cfgJson,cMQTTClientId);
if (cfgItem != NULL)
{
strcpy(g_sQuaAquariusData.sConfig.uMQTTClientId,cfgItem->valuestring);
printf("MQTTClientId-------> %s\n",g_sQuaAquariusData.sConfig.uMQTTClientId);
}
else
{
printf("No MQTTClientId\n");
}
/**********MQTTSubTitle**********/
cfgItem = cJSON_GetObjectItem(cfgJson,cMQTTSubTitle);
if (cfgItem != NULL)
{
strcpy(g_sQuaAquariusData.sConfig.uMQTTSubTitle,cfgItem->valuestring);
printf("MQTTSubTitle-------> %s\n",g_sQuaAquariusData.sConfig.uMQTTSubTitle);
}
else
{
printf("No MQTTSubTitle\n");
}
/**********MQTTPubOrder**********/
cfgItem = cJSON_GetObjectItem(cfgJson,cMQTTPubOrder);
if (cfgItem != NULL)
{
strcpy(g_sQuaAquariusData.sConfig.uMQTTPubOrder,cfgItem->valuestring);
printf("MQTTPubOrder-------> %s\n",g_sQuaAquariusData.sConfig.uMQTTPubOrder);
}
else
{
printf("No MQTTPubOrder\n");
}
/**********MQTTPubMessage**********/
cfgItem = cJSON_GetObjectItem(cfgJson,cMQTTPubMessage);
if (cfgItem != NULL)
{
strcpy(g_sQuaAquariusData.sConfig.uMQTTPubMessage,cfgItem->valuestring);
printf("MQTTPubMessage-----> %s\n",g_sQuaAquariusData.sConfig.uMQTTPubMessage);
}
else
{
printf("No MQTTPubMessage\n");
}
/**********MQTTPubDevice**********/
cfgItem = cJSON_GetObjectItem(cfgJson,cMQTTPubDevice);
if (cfgItem != NULL)
{
strcpy(g_sQuaAquariusData.sConfig.uMQTTPubDevice,cfgItem->valuestring);
printf("MQTTPubDevice---- -> %s\n",g_sQuaAquariusData.sConfig.uMQTTPubDevice);
}
else
{
printf("No MQTTPubDevice\n");
}
/**********MQTTHost**********/
cfgItem = cJSON_GetObjectItem(cfgJson,cMQTTHost);
if (cfgItem != NULL)
{
strcpy(g_sQuaAquariusData.sConfig.uMQTTHost,cfgItem->valuestring);
printf("MQTTHost-----------> %s\n",g_sQuaAquariusData.sConfig.uMQTTHost);
}
else
{
printf("No MQTTHost\n");
}
/**********MQTTPort**********/
cfgItem = cJSON_GetObjectItem(cfgJson,cMQTTPort);
if (cfgItem != NULL)
{
g_sQuaAquariusData.sConfig.uMQTTPort = cfgItem->valueint;
printf("MQTTPort-----------> %d\n",g_sQuaAquariusData.sConfig.uMQTTPort);
}
else
{
printf("No MQTTPort\n");
}
/**********MQTTUserName**********/
cfgItem = cJSON_GetObjectItem(cfgJson,cMQTTUserName);
if (cfgItem != NULL)
{
strcpy(g_sQuaAquariusData.sConfig.uMQTTUserName,cfgItem->valuestring);
printf("MQTTUserName-------> %s\n",g_sQuaAquariusData.sConfig.uMQTTUserName);
}
else
{
printf("No MQTTUserName\n");
}
/**********MQTTPassword**********/
cfgItem = cJSON_GetObjectItem(cfgJson,cMQTTPassword);
if (cfgItem != NULL)
{
strcpy(g_sQuaAquariusData.sConfig.uMQTTPassword,cfgItem->valuestring);
printf("MQTTPassword-------> %s\n",g_sQuaAquariusData.sConfig.uMQTTPassword);
}
else
{
printf("No MQTTPassword\n");
}
/**********Serial1Port**********/
cfgItem = cJSON_GetObjectItem(cfgJson,cSerial1Port);
if (cfgItem != NULL)
{
strcpy(g_sQuaAquariusData.sConfig.uSerial1Port,cfgItem->valuestring);
printf("Serial1Port--------> %s\n",g_sQuaAquariusData.sConfig.uSerial1Port);
}
else
{
printf("No Serial1Port\n");
}
/**********Serial2Port**********/
cfgItem = cJSON_GetObjectItem(cfgJson,cSerial2Port);
if (cfgItem != NULL)
{
strcpy(g_sQuaAquariusData.sConfig.uSerial2Port,cfgItem->valuestring);
printf("Serial2Port--------> %s\n",g_sQuaAquariusData.sConfig.uSerial2Port);
}
else
{
printf("No Serial2Port\n");
}
/**********Serial3Port**********/
cfgItem = cJSON_GetObjectItem(cfgJson,cSerial3Port);
if (cfgItem != NULL)
{
strcpy(g_sQuaAquariusData.sConfig.uSerial3Port,cfgItem->valuestring);
printf("Serial3Port--------> %s\n",g_sQuaAquariusData.sConfig.uSerial3Port);
}
else
{
printf("No Serial3Port\n");
}
/**********SerialBaudRate**********/
cfgItem = cJSON_GetObjectItem(cfgJson,cSerialBaudRate);
if (cfgItem != NULL)
{
g_sQuaAquariusData.sConfig.uSerialBaudRate = cfgItem->valueint;
printf("SerialBaudRate-----> %d\n",g_sQuaAquariusData.sConfig.uSerialBaudRate);
}
else
{
printf("No SerialBaudRate\n");
}
/**********SerialDataBit**********/
cfgItem = cJSON_GetObjectItem(cfgJson,cSerialDataBit);
if (cfgItem != NULL)
{
g_sQuaAquariusData.sConfig.uSerialDataBit = cfgItem->valueint;
printf("SerialDataBit------> %d\n",g_sQuaAquariusData.sConfig.uSerialDataBit);
}
else
{
printf("No SerialDataBit\n");
}
/**********SerialStopBit**********/
cfgItem = cJSON_GetObjectItem(cfgJson,cSerialStopBit);
if (cfgItem != NULL)
{
g_sQuaAquariusData.sConfig.uSerialStopBit = cfgItem->valueint;
printf("SerialStopBit------> %d\n",g_sQuaAquariusData.sConfig.uSerialStopBit);
}
else
{
printf("No SerialStopBit\n");
}
cJSON_Delete(cfgJson);
}
uart.c
原始数据 复制代码
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
/*--------------------------------------------------------------------------*/
/* Project : QuaAquarius */
/* File : uart.c */
/* Summary : The implementation of main function's file for this project.*/
/* Declare : Copyright(C) 2016-2017 QuaOrgin */
/* Remark : none */
/* History : v1.00 Jackie Jiang 2017/10/31 Create */
/*--------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------*/
/* */
/* Include Files */
/* */
/*--------------------------------------------------------------------------*/
#include "quaaquarius.h"
#include "libemqtt.h"
#include "cJSON.h"
#include "mqttclient.h"
#include "uart.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <errno.h>
#include <string.h>
/*--------------------------------------------------------------------------*/
/* */
/* Macros Define */
/* */
/*--------------------------------------------------------------------------*/
//#define cMinWorkVolt c50V
/*--------------------------------------------------------------------------*/
/* */
/* Local Types */
/* */
/*--------------------------------------------------------------------------*/
int uartfd1;
int uartfd2;
int uartfd3;
int fd1flg;
int fd2flg;
unsigned char uartrecvbuff1ok[20];
unsigned char uartrecvbuff2ok[20];
/*--------------------------------------------------------------------------*/
/* */
/* Global Types */
/* */
/*--------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------*/
/* */
/* Extern Global Types */
/* */
/*--------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------*/
/* */
/* Extern Functions */
/* */
/*--------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------*/
/* */
/* Functions Declare */
/* */
/*--------------------------------------------------------------------------*/
void uart_open(void);
void uart1_recv(void);
void uart2_recv(void);
void uart3_recv(void);
void uart1_send(void);
void uart2_send(void);
void uart3_send(void);
void uart_close(void);
int set_opt(int fd,int nSpeed, int nBits, char nEvent, int nStop);
/*--------------------------------------------------------------------------*/
/* */
/* Functions Define */
/* */
/*--------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------*/
/* @(p) */
/* Name : uart_open */
/* Function : 系统初始化函数 */
/* Return : 无 */
/* Argument : 无 */
/* Create : v1.00 Jackie Jiang 2017/10/31 */
/* Update : */
/* Remark : */
/*--------------------------------------------------------------------------*/
void uart_open(void)
{
int uartset1;
int uartset2;
int uartset3;
uartfd1 = open(g_sQuaAquariusData.sConfig.uSerial1Port,O_RDWR | O_NOCTTY);
uartfd2 = open(g_sQuaAquariusData.sConfig.uSerial2Port,O_RDWR | O_NOCTTY);
uartfd3 = open(g_sQuaAquariusData.sConfig.uSerial3Port,O_RDWR | O_NOCTTY);
printf("the return uartfd1 is %d\n",uartfd1);
printf("the return uartfd2 is %d\n",uartfd2);
printf("the return uartfd3 is %d\n",uartfd3);
uartset1 = set_opt(uartfd1,g_sQuaAquariusData.sConfig.uSerialBaudRate,g_sQuaAquariusData.sConfig.uSerialDataBit,'N',g_sQuaAquariusData.sConfig.uSerialStopBit);
uartset2 = set_opt(uartfd2,g_sQuaAquariusData.sConfig.uSerialBaudRate,g_sQuaAquariusData.sConfig.uSerialDataBit,'N',g_sQuaAquariusData.sConfig.uSerialStopBit);
uartset3 = set_opt(uartfd3,g_sQuaAquariusData.sConfig.uSerialBaudRate,g_sQuaAquariusData.sConfig.uSerialDataBit,'N',g_sQuaAquariusData.sConfig.uSerialStopBit);
printf("the return uartset1 is %d\n",uartset1);
printf("the return uartset2 is %d\n",uartset2);
printf("the return uartset3 is %d\n",uartset3);
fd1flg = 0;
fd2flg = 0;
}
/*--------------------------------------------------------------------------*/
/* @(p) */
/* Name : uart1_recv */
/* Function : 系统初始化函数 */
/* Return : 无 */
/* Argument : 无 */
/* Create : v1.00 Jackie Jiang 2017/10/31 */
/* Update : */
/* Remark : */
/*--------------------------------------------------------------------------*/
void uart1_recv(void)
{
//入水
int uartreadlen1;
unsigned char uartrecvbuff1[8]={0};
uartreadlen1 = read(uartfd1,uartrecvbuff1,8);
if(uartreadlen1 > 3)
{
if(uartrecvbuff1[0] == 0x55 && uartrecvbuff1[1] == 0xaa && uartrecvbuff1[2] == 0x51 && uartrecvbuff1[3] == 0x14)
{
uartrecvbuff1ok[0] = uartrecvbuff1[0];
uartrecvbuff1ok[1] = uartrecvbuff1[1];
uartrecvbuff1ok[2] = uartrecvbuff1[2];
uartrecvbuff1ok[3] = uartrecvbuff1[3];
uartrecvbuff1ok[4] = uartrecvbuff1[4];
uartrecvbuff1ok[5] = uartrecvbuff1[5];
uartrecvbuff1ok[6] = uartrecvbuff1[6];
uartrecvbuff1ok[7] = uartrecvbuff1[7];
}
else if(uartrecvbuff1[3] == 0xff && uartrecvbuff1[4] == 0x00 && uartrecvbuff1[5] == 0x00 && uartrecvbuff1[6] == 0x00)
{
uartrecvbuff1ok[16] = uartrecvbuff1[0];
uartrecvbuff1ok[17] = uartrecvbuff1[1];
uartrecvbuff1ok[18] = uartrecvbuff1[2];
uartrecvbuff1ok[19] = uartrecvbuff1[3];
g_sQuaAquariusData.sTDS.fInTemperature = (FLOAT)(uartrecvbuff1ok[16] << 8 | uartrecvbuff1ok[17]) / 100.0f;
}
else
{
uartrecvbuff1ok[8] = uartrecvbuff1[0];
uartrecvbuff1ok[9] = uartrecvbuff1[1];
uartrecvbuff1ok[10] = uartrecvbuff1[2];
uartrecvbuff1ok[11] = uartrecvbuff1[3];
uartrecvbuff1ok[12] = uartrecvbuff1[4];
uartrecvbuff1ok[13] = uartrecvbuff1[5];
uartrecvbuff1ok[14] = uartrecvbuff1[6];
uartrecvbuff1ok[15] = uartrecvbuff1[7];
g_sQuaAquariusData.sTDS.fInTOC = (FLOAT)(uartrecvbuff1ok[8] << 8 | uartrecvbuff1ok[9]) / 100.0f;
g_sQuaAquariusData.sTDS.fInCOD = (FLOAT)(uartrecvbuff1ok[10] << 8 | uartrecvbuff1ok[11]) / 100.0f;
g_sQuaAquariusData.sTDS.fInChromaticity = (FLOAT)(uartrecvbuff1ok[12] << 8 | uartrecvbuff1ok[13]) / 100.0f;
g_sQuaAquariusData.sTDS.fInTurbidity = (FLOAT)(uartrecvbuff1ok[14] << 8 | uartrecvbuff1ok[15]) / 100.0f;
printf("1--->TOC:%.2f ",g_sQuaAquariusData.sTDS.fInTOC);
printf("1--->COD:%.2f ",g_sQuaAquariusData.sTDS.fInCOD);
printf("1--->sedu:%.2f ",g_sQuaAquariusData.sTDS.fInChromaticity);
printf("1--->zhuo:%.2f\n",g_sQuaAquariusData.sTDS.fInTurbidity);
fd1flg = 1;
}
if(fd1flg == 1)
{
fd1flg = 0;
printf("%02X ",uartrecvbuff1ok[0]);
printf("%02X ",uartrecvbuff1ok[1]);
printf("%02X ",uartrecvbuff1ok[2]);
printf("%02X ",uartrecvbuff1ok[3]);
printf("%02X ",uartrecvbuff1ok[4]);
printf("%02X ",uartrecvbuff1ok[5]);
printf("%02X ",uartrecvbuff1ok[6]);
printf("%02X ",uartrecvbuff1ok[7]);
printf("%02X ",uartrecvbuff1ok[8]);
printf("%02X ",uartrecvbuff1ok[9]);
printf("%02X ",uartrecvbuff1ok[10]);
printf("%02X ",uartrecvbuff1ok[11]);
printf("%02X ",uartrecvbuff1ok[12]);
printf("%02X ",uartrecvbuff1ok[13]);
printf("%02X ",uartrecvbuff1ok[14]);
printf("%02X ",uartrecvbuff1ok[15]);
printf("%02X ",uartrecvbuff1ok[16]);
printf("%02X ",uartrecvbuff1ok[17]);
printf("%02X ",uartrecvbuff1ok[18]);
printf("%02X------>uartread1\n",uartrecvbuff1ok[19]);
}
}
}
/*--------------------------------------------------------------------------*/
/* @(p) */
/* Name : uart2_recv */
/* Function : 系统初始化函数 */
/* Return : 无 */
/* Argument : 无 */
/* Create : v1.00 Jackie Jiang 2017/10/31 */
/* Update : */
/* Remark : */
/*--------------------------------------------------------------------------*/
void uart2_recv(void)
{
//出水
int uartreadlen2;
unsigned char uartrecvbuff2[8]={0};
uartreadlen2 = read(uartfd2,uartrecvbuff2,8);
if(uartreadlen2 > 3)
{
if(uartrecvbuff2[0] == 0x55 && uartrecvbuff2[1] == 0xaa && uartrecvbuff2[2] == 0x51 && uartrecvbuff2[3] == 0x14)
{
uartrecvbuff2ok[0] = uartrecvbuff2[0];
uartrecvbuff2ok[1] = uartrecvbuff2[1];
uartrecvbuff2ok[2] = uartrecvbuff2[2];
uartrecvbuff2ok[3] = uartrecvbuff2[3];
uartrecvbuff2ok[4] = uartrecvbuff2[4];
uartrecvbuff2ok[5] = uartrecvbuff2[5];
uartrecvbuff2ok[6] = uartrecvbuff2[6];
uartrecvbuff2ok[7] = uartrecvbuff2[7];
}
else if(uartrecvbuff2[3] == 0xff && uartrecvbuff2[4] == 0x00 && uartrecvbuff2[5] == 0x00 && uartrecvbuff2[6] == 0x00)
{
uartrecvbuff2ok[16] = uartrecvbuff2[0];
uartrecvbuff2ok[17] = uartrecvbuff2[1];
uartrecvbuff2ok[18] = uartrecvbuff2[2];
uartrecvbuff2ok[19] = uartrecvbuff2[3];
g_sQuaAquariusData.sTDS.fOutTemperature = (FLOAT)(uartrecvbuff2ok[16] << 8 | uartrecvbuff2ok[17]) / 100.0f;
}
else
{
uartrecvbuff2ok[8] = uartrecvbuff2[0];
uartrecvbuff2ok[9] = uartrecvbuff2[1];
uartrecvbuff2ok[10] = uartrecvbuff2[2];
uartrecvbuff2ok[11] = uartrecvbuff2[3];
uartrecvbuff2ok[12] = uartrecvbuff2[4];
uartrecvbuff2ok[13] = uartrecvbuff2[5];
uartrecvbuff2ok[14] = uartrecvbuff2[6];
uartrecvbuff2ok[15] = uartrecvbuff2[7];
g_sQuaAquariusData.sTDS.fOutTOC = (FLOAT)(uartrecvbuff2ok[8] << 8 | uartrecvbuff2ok[9]) / 100.0f;
g_sQuaAquariusData.sTDS.fOutCOD = (FLOAT)(uartrecvbuff2ok[10] << 8 | uartrecvbuff2ok[11]) / 100.0f;
g_sQuaAquariusData.sTDS.fOutChromaticity = (FLOAT)(uartrecvbuff2ok[12] << 8 | uartrecvbuff2ok[13]) / 100.0f;
g_sQuaAquariusData.sTDS.fOutTurbidity = (FLOAT)(uartrecvbuff2ok[14] << 8 | uartrecvbuff2ok[15]) / 100.0f;
printf("2--->TOC:%.2f ",g_sQuaAquariusData.sTDS.fOutTOC);
printf("2--->COD:%.2f ",g_sQuaAquariusData.sTDS.fOutCOD);
printf("2--->sedu:%.2f ",g_sQuaAquariusData.sTDS.fOutChromaticity);
printf("2--->zhuo:%.2f\n",g_sQuaAquariusData.sTDS.fOutTurbidity);
fd2flg = 1;
}
if(fd2flg == 1)
{
fd2flg = 0;
printf("%02X ",uartrecvbuff2ok[0]);
printf("%02X ",uartrecvbuff2ok[1]);
printf("%02X ",uartrecvbuff2ok[2]);
printf("%02X ",uartrecvbuff2ok[3]);
printf("%02X ",uartrecvbuff2ok[4]);
printf("%02X ",uartrecvbuff2ok[5]);
printf("%02X ",uartrecvbuff2ok[6]);
printf("%02X ",uartrecvbuff2ok[7]);
printf("%02X ",uartrecvbuff2ok[8]);
printf("%02X ",uartrecvbuff2ok[9]);
printf("%02X ",uartrecvbuff2ok[10]);
printf("%02X ",uartrecvbuff2ok[11]);
printf("%02X ",uartrecvbuff2ok[12]);
printf("%02X ",uartrecvbuff2ok[13]);
printf("%02X ",uartrecvbuff2ok[14]);
printf("%02X ",uartrecvbuff2ok[15]);
printf("%02X ",uartrecvbuff2ok[16]);
printf("%02X ",uartrecvbuff2ok[17]);
printf("%02X ",uartrecvbuff2ok[18]);
printf("%02X------>uartread2\n",uartrecvbuff2ok[19]);
}
}
}
/*--------------------------------------------------------------------------*/
/* @(p) */
/* Name : uart3_recv */
/* Function : 系统初始化函数 */
/* Return : 无 */
/* Argument : 无 */
/* Create : v1.00 Jackie Jiang 2017/10/31 */
/* Update : */
/* Remark : */
/*--------------------------------------------------------------------------*/
void uart3_recv(void)
{
//放水板
int uartreadlen3;
unsigned char uartrecvbuff3[4]={0};
uartreadlen3 = read(uartfd3,uartrecvbuff3,4);
if(uartreadlen3 == 4)
{
if(uartrecvbuff3[0] == 0x01)
{
g_sQuaAquariusData.sCore.uTapId = (UINT)uartrecvbuff3[0];
g_sQuaAquariusData.sRelease.uResVolumeTap1 = (UINT)uartrecvbuff3[2] << 8 | uartrecvbuff3[3];
if(g_sQuaAquariusData.sRelease.uResVolumeTap1 >= g_sQuaAquariusData.sCore.uReqVolumeTap1)
{
g_sQuaAquariusData.sRelease.uResVolumeTap1 = g_sQuaAquariusData.sCore.uReqVolumeTap1;
}
g_sQuaAquariusData.sCore.uValveStsTap1 = uartrecvbuff3[1];
mqttclient_publish(cOrderType);
}
else if(uartrecvbuff3[0] == 0x02)
{
g_sQuaAquariusData.sCore.uTapId = (UINT)uartrecvbuff3[0];
g_sQuaAquariusData.sRelease.uResVolumeTap2 = (UINT)uartrecvbuff3[2] << 8 | uartrecvbuff3[3];
if(g_sQuaAquariusData.sRelease.uResVolumeTap2 >= g_sQuaAquariusData.sCore.uReqVolumeTap2)
{
g_sQuaAquariusData.sRelease.uResVolumeTap2 = g_sQuaAquariusData.sCore.uReqVolumeTap2;
}
g_sQuaAquariusData.sCore.uValveStsTap2 = uartrecvbuff3[1];
mqttclient_publish(cOrderType);
}
}
}
/*--------------------------------------------------------------------------*/
/* @(p) */
/* Name : uart1_send */
/* Function : 系统初始化函数 */
/* Return : 无 */
/* Argument : 无 */
/* Create : v1.00 Jackie Jiang 2017/10/31 */
/* Update : */
/* Remark : */
/*--------------------------------------------------------------------------*/
void uart1_send(void)
{
int uartwritelen1;
unsigned char uartwritebuff1[]={0x55,0xAA,0x03,0x0A,0x00,0xFE,0x00,0x00,0x00,0xFF};
uartwritelen1 = write(uartfd1,uartwritebuff1,10);
printf("uartwritelen1 is %d\n",uartwritelen1);
}
/*--------------------------------------------------------------------------*/
/* @(p) */
/* Name : uart2_send */
/* Function : 系统初始化函数 */
/* Return : 无 */
/* Argument : 无 */
/* Create : v1.00 Jackie Jiang 2017/10/31 */
/* Update : */
/* Remark : */
/*--------------------------------------------------------------------------*/
void uart2_send(void)
{
int uartwritelen2;
unsigned char uartwritebuff2[]={0x55,0xAA,0x03,0x0A,0x00,0xFE,0x00,0x00,0x00,0xFF};
uartwritelen2 = write(uartfd2,uartwritebuff2,10);
printf("uartwritelen2 is %d\n",uartwritelen2);
}
/*--------------------------------------------------------------------------*/
/* @(p) */
/* Name : uart3_send */
/* Function : 系统初始化函数 */
/* Return : 无 */
/* Argument : 无 */
/* Create : v1.00 Jackie Jiang 2017/10/31 */
/* Update : */
/* Remark : */
/*--------------------------------------------------------------------------*/
void uart3_send(void)
{
int uartwritelen3;
UINT8 uartwritebuff3[4];
uartwritebuff3[0] = (UINT8)g_sQuaAquariusData.sCore.uTapId;
uartwritebuff3[1] = 0x01;
if(g_sQuaAquariusData.sCore.uTapId == 0x01)
{
uartwritebuff3[2] = g_sQuaAquariusData.sCore.uReqVolumeHTap1;
uartwritebuff3[3] = g_sQuaAquariusData.sCore.uReqVolumeLTap1;
}
else if(g_sQuaAquariusData.sCore.uTapId == 0x02)
{
uartwritebuff3[2] = g_sQuaAquariusData.sCore.uReqVolumeHTap2;
uartwritebuff3[3] = g_sQuaAquariusData.sCore.uReqVolumeLTap2;
}
uartwritelen3 = write(uartfd3,uartwritebuff3,4);
printf("uartwritelen3 is %d\n",uartwritelen3);
}
/*--------------------------------------------------------------------------*/
/* @(p) */
/* Name : uart_close */
/* Function : 串口关闭 */
/* Return : 无 */
/* Argument : 无 */
/* Create : v1.00 Jackie Jiang 2017/10/31 */
/* Update : */
/* Remark : */
/*--------------------------------------------------------------------------*/
void uart_close(void)
{
close(uartfd1);
close(uartfd2);
close(uartfd3);
}
/*--------------------------------------------------------------------------*/
/* @(p) */
/* Name : set_opt */
/* Function : */
/* Return : 无 */
/* Argument : 无 */
/* Create : v1.00 Jackie Jiang 2017/10/31 */
/* Update : */
/* Remark : */
/*--------------------------------------------------------------------------*/
int set_opt(int fd,int nSpeed, int nBits, char nEvent, int nStop)
{
struct termios newtio,oldtio;
if ( tcgetattr( fd,&oldtio) != 0) {
perror("SetupSerial 1");
return -1;
}
bzero( &newtio, sizeof( newtio ) );
newtio.c_cflag |= CLOCAL | CREAD;
newtio.c_cflag &= ~CSIZE;
switch( nBits )
{
case 7:
newtio.c_cflag |= CS7;
break;
case 8:
newtio.c_cflag |= CS8;
break;
}
switch(nEvent)
{
case 'O':
newtio.c_cflag |= PARENB;
newtio.c_cflag |= PARODD;
newtio.c_iflag |= (INPCK | ISTRIP);
break;
case 'E':
newtio.c_iflag |= (INPCK | ISTRIP);
newtio.c_cflag |= PARENB;
newtio.c_cflag &= ~PARODD;
break;
case 'N':
newtio.c_cflag &= ~PARENB;
break;
}
switch(nSpeed)
{
case 2400:
cfsetispeed(&newtio,B2400);
cfsetospeed(&newtio,B2400);
break;
case 4800:
cfsetispeed(&newtio,B4800);
cfsetospeed(&newtio,B4800);
break;
case 9600:
cfsetispeed(&newtio,B9600);
cfsetospeed(&newtio,B9600);
break;
case 115200:
cfsetispeed(&newtio,B115200);
cfsetospeed(&newtio,B115200);
break;
case 460800:
cfsetispeed(&newtio,B460800);
cfsetospeed(&newtio,B460800);
break;
default:
cfsetispeed(&newtio,B9600);
cfsetospeed(&newtio,B9600);
break;
}
if(nStop == 1)
newtio.c_cflag &= ~CSTOPB;
else if ( nStop == 2 )
newtio.c_cflag |= CSTOPB;
newtio.c_cc[VTIME] = 0;
newtio.c_cc[VMIN] = 0;
tcflush(fd,TCIFLUSH);
if((tcsetattr(fd,TCSANOW,&newtio))!=0)
{
perror("com set error");
return -1;
}
// printf("set done!\n\r");
return 0;
}

评论列表( 0 )

你可以在登录后,发表评论

搜索帮助