lnk commit front code

This commit is contained in:
lnk
2025-01-16 16:17:01 +08:00
commit 1776a2bf0d
587 changed files with 257079 additions and 0 deletions

9
json/CVS/Entries Normal file
View File

@@ -0,0 +1,9 @@
/rdkafka.h/1.1/Mon Nov 19 08:13:25 2018//
/rdkafkacpp.h/1.1/Mon Nov 19 08:13:25 2018//
/kafka_producer.h/1.2/Mon Nov 26 02:31:00 2018//
/save2json.h/1.5/Sun Dec 23 12:39:52 2018//
/mms_json_inter.h/1.5/Tue Dec 25 13:31:25 2018//
/kafka_producer.cpp/1.6/Sat Jan 12 14:56:04 2019//
/create_json.cpp/1.17/Tue Apr 23 07:29:30 2019//
/save2json.cpp/1.21/Tue Oct 27 08:51:07 2020//
D

8
json/CVS/Entries.Extra Normal file
View File

@@ -0,0 +1,8 @@
/rdkafka.h////*////
/rdkafkacpp.h////*////
/kafka_producer.h////*////
/save2json.h////*////
/mms_json_inter.h////*////
/kafka_producer.cpp////*////
/create_json.cpp////*////
/save2json.cpp////*////

View File

@@ -0,0 +1,8 @@
/rdkafka.h////*////
/rdkafkacpp.h////*////
/kafka_producer.h////*////
/save2json.h////*////
/mms_json_inter.h////*////
/kafka_producer.cpp////*////
/save2json.cpp////*////
/create_json.cpp////*////

9
json/CVS/Entries.Old Normal file
View File

@@ -0,0 +1,9 @@
/rdkafka.h/1.1/Mon Nov 19 08:13:25 2018//
/rdkafkacpp.h/1.1/Mon Nov 19 08:13:25 2018//
/kafka_producer.h/1.2/Mon Nov 26 02:31:00 2018//
/save2json.h/1.5/Sun Dec 23 12:39:52 2018//
/mms_json_inter.h/1.5/Tue Dec 25 13:31:25 2018//
/kafka_producer.cpp/1.6/Sat Jan 12 14:56:04 2019//
/save2json.cpp/1.20/Wed Apr 17 00:47:35 2019//
/create_json.cpp/1.16/Tue Apr 23 07:25:19 2019//
D

1
json/CVS/Repository Normal file
View File

@@ -0,0 +1 @@
jspqfe/src/pt61850netd_pqfe/source/json

1
json/CVS/Root Normal file
View File

@@ -0,0 +1 @@
:ext:lizhongming@10.0.0.2:/JoyProject

0
json/CVS/Template Normal file
View File

759
json/cjson.c Normal file
View File

@@ -0,0 +1,759 @@
/*
Copyright (c) 2009 Dave Gamble
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. */
#include <string.h>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <float.h>
#include <limits.h>
#include <ctype.h>
#include "cjson.h"
//lnk2024-11-14
#include <pthread.h>
static const char *global_ep;
const char *cJSON_GetErrorPtr(void) {return global_ep;}
static int cJSON_strcasecmp(const char *s1,const char *s2)
{
if (!s1) return (s1==s2)?0:1;if (!s2) return 1;
for(; tolower(*s1) == tolower(*s2); ++s1, ++s2) if(*s1 == 0) return 0;
return tolower(*(const unsigned char *)s1) - tolower(*(const unsigned char *)s2);
}
static void *(*cJSON_malloc)(size_t sz) = malloc;
static void (*cJSON_free)(void *ptr) = free;
static char* cJSON_strdup(const char* str)
{
size_t len;
char* copy;
len = strlen(str) + 1;
if (!(copy = (char*)cJSON_malloc(len))) return 0;
memcpy(copy,str,len);
return copy;
}
void cJSON_InitHooks(cJSON_Hooks* hooks)
{
if (!hooks) { /* Reset hooks */
cJSON_malloc = malloc;
cJSON_free = free;
return;
}
cJSON_malloc = (hooks->malloc_fn)?hooks->malloc_fn:malloc;
cJSON_free = (hooks->free_fn)?hooks->free_fn:free;
}
/* Internal constructor. */
static cJSON *cJSON_New_Item(void)
{
cJSON* node = (cJSON*)cJSON_malloc(sizeof(cJSON));
if (node) memset(node,0,sizeof(cJSON));
return node;
}
/* Delete a cJSON structure. */
void cJSON_Delete(cJSON *c)
{
cJSON *next;
while (c)
{
next=c->next;
if (!(c->type&cJSON_IsReference) && c->child) cJSON_Delete(c->child);
if (!(c->type&cJSON_IsReference) && c->valuestring) cJSON_free(c->valuestring);
if (!(c->type&cJSON_StringIsConst) && c->string) cJSON_free(c->string);
cJSON_free(c);
c=next;
}
}
/* Parse the input text to generate a number, and populate the result into item. */
static const char *parse_number(cJSON *item,const char *num)
{
double n=0,sign=1,scale=0;int subscale=0,signsubscale=1;
if (*num=='-') sign=-1,num++; /* Has sign? */
if (*num=='0') num++; /* is zero */
if (*num>='1' && *num<='9') do n=(n*10.0)+(*num++ -'0'); while (*num>='0' && *num<='9'); /* Number? */
if (*num=='.' && num[1]>='0' && num[1]<='9') {num++; do n=(n*10.0)+(*num++ -'0'),scale--; while (*num>='0' && *num<='9');} /* Fractional part? */
if (*num=='e' || *num=='E') /* Exponent? */
{ num++;if (*num=='+') num++; else if (*num=='-') signsubscale=-1,num++; /* With sign? */
while (*num>='0' && *num<='9') subscale=(subscale*10)+(*num++ - '0'); /* Number? */
}
n=sign*n*pow(10.0,(scale+subscale*signsubscale)); /* number = +/- number.fraction * 10^+/- exponent */
item->valuedouble=n;
item->valueint=(int)n;
item->type=cJSON_Number;
return num;
}
static int pow2gt (int x) { --x; x|=x>>1; x|=x>>2; x|=x>>4; x|=x>>8; x|=x>>16; return x+1; }
typedef struct {char *buffer; int length; int offset; } printbuffer;
static char* ensure(printbuffer *p,int needed)
{
char *newbuffer;int newsize;
if (!p || !p->buffer) return 0;
needed+=p->offset;
if (needed<=p->length) return p->buffer+p->offset;
newsize=pow2gt(needed);
newbuffer=(char*)cJSON_malloc(newsize);
if (!newbuffer) {cJSON_free(p->buffer);p->length=0,p->buffer=0;return 0;}
if (newbuffer) memcpy(newbuffer,p->buffer,p->length);
cJSON_free(p->buffer);
p->length=newsize;
p->buffer=newbuffer;
return newbuffer+p->offset;
}
static int update(printbuffer *p)
{
char *str;
if (!p || !p->buffer) return 0;
str=p->buffer+p->offset;
return p->offset+strlen(str);
}
/* Render the number nicely from the given item into a string. */
static char *print_number(cJSON *item,printbuffer *p)
{
char *str=0;
double d=item->valuedouble;
if (d==0)
{
if (p) str=ensure(p,2);
else str=(char*)cJSON_malloc(2); /* special case for 0. */
if (str) strcpy(str,"0");
}
else if (fabs(((double)item->valueint)-d)<=DBL_EPSILON && d<=INT_MAX && d>=INT_MIN)
{
if (p) str=ensure(p,21);
else str=(char*)cJSON_malloc(21); /* 2^64+1 can be represented in 21 chars. */
if (str) sprintf(str,"%d",item->valueint);
}
else
{
if (p) str=ensure(p,64);
else str=(char*)cJSON_malloc(64); /* This is a nice tradeoff. */
if (str)
{
if (d*0!=0) sprintf(str,"null"); /* This checks for NaN and Infinity */
else if (fabs(floor(d)-d)<=DBL_EPSILON && fabs(d)<1.0e60) sprintf(str,"%.0f",d);
else if (fabs(d)<1.0e-6 || fabs(d)>1.0e9) sprintf(str,"%e",d);
else sprintf(str,"%f",d);
}
}
return str;
}
static unsigned parse_hex4(const char *str)
{
unsigned h=0;
if (*str>='0' && *str<='9') h+=(*str)-'0'; else if (*str>='A' && *str<='F') h+=10+(*str)-'A'; else if (*str>='a' && *str<='f') h+=10+(*str)-'a'; else return 0;
h=h<<4;str++;
if (*str>='0' && *str<='9') h+=(*str)-'0'; else if (*str>='A' && *str<='F') h+=10+(*str)-'A'; else if (*str>='a' && *str<='f') h+=10+(*str)-'a'; else return 0;
h=h<<4;str++;
if (*str>='0' && *str<='9') h+=(*str)-'0'; else if (*str>='A' && *str<='F') h+=10+(*str)-'A'; else if (*str>='a' && *str<='f') h+=10+(*str)-'a'; else return 0;
h=h<<4;str++;
if (*str>='0' && *str<='9') h+=(*str)-'0'; else if (*str>='A' && *str<='F') h+=10+(*str)-'A'; else if (*str>='a' && *str<='f') h+=10+(*str)-'a'; else return 0;
return h;
}
/* Parse the input text into an unescaped cstring, and populate item. */
static const unsigned char firstByteMark[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC };
static const char *parse_string(cJSON *item,const char *str,const char **ep)
{
const char *ptr=str+1,*end_ptr=str+1;char *ptr2;char *out;int len=0;unsigned uc,uc2;
if (*str!='\"') {*ep=str;return 0;} /* not a string! */
while (*end_ptr!='\"' && *end_ptr && ++len) if (*end_ptr++ == '\\') end_ptr++; /* Skip escaped quotes. */
out=(char*)cJSON_malloc(len+1); /* This is how long we need for the string, roughly. */
if (!out) return 0;
item->valuestring=out; /* assign here so out will be deleted during cJSON_Delete() later */
item->type=cJSON_String;
ptr=str+1;ptr2=out;
while (ptr < end_ptr)
{
if (*ptr!='\\') *ptr2++=*ptr++;
else
{
ptr++;
switch (*ptr)
{
case 'b': *ptr2++='\b'; break;
case 'f': *ptr2++='\f'; break;
case 'n': *ptr2++='\n'; break;
case 'r': *ptr2++='\r'; break;
case 't': *ptr2++='\t'; break;
case 'u': /* transcode utf16 to utf8. */
uc=parse_hex4(ptr+1);ptr+=4; /* get the unicode char. */
if (ptr >= end_ptr) {*ep=str;return 0;} /* invalid */
if ((uc>=0xDC00 && uc<=0xDFFF) || uc==0) {*ep=str;return 0;} /* check for invalid. */
if (uc>=0xD800 && uc<=0xDBFF) /* UTF16 surrogate pairs. */
{
if (ptr+6 > end_ptr) {*ep=str;return 0;} /* invalid */
if (ptr[1]!='\\' || ptr[2]!='u') {*ep=str;return 0;} /* missing second-half of surrogate. */
uc2=parse_hex4(ptr+3);ptr+=6;
if (uc2<0xDC00 || uc2>0xDFFF) {*ep=str;return 0;} /* invalid second-half of surrogate. */
uc=0x10000 + (((uc&0x3FF)<<10) | (uc2&0x3FF));
}
len=4;if (uc<0x80) len=1;else if (uc<0x800) len=2;else if (uc<0x10000) len=3; ptr2+=len;
switch (len) {
case 4: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6;
case 3: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6;
case 2: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6;
case 1: *--ptr2 =(uc | firstByteMark[len]);
}
ptr2+=len;
break;
default: *ptr2++=*ptr; break;
}
ptr++;
}
}
*ptr2=0;
if (*ptr=='\"') ptr++;
return ptr;
}
/* Render the cstring provided to an escaped version that can be printed. */
static char *print_string_ptr(const char *str,printbuffer *p)
{
const char *ptr;char *ptr2,*out;int len=0,flag=0;unsigned char token;
if (!str)
{
if (p) out=ensure(p,3);
else out=(char*)cJSON_malloc(3);
if (!out) return 0;
strcpy(out,"\"\"");
return out;
}
for (ptr=str;*ptr;ptr++) flag|=((*ptr>0 && *ptr<32)||(*ptr=='\"')||(*ptr=='\\'))?1:0;
if (!flag)
{
len=ptr-str;
if (p) out=ensure(p,len+3);
else out=(char*)cJSON_malloc(len+3);
if (!out) return 0;
ptr2=out;*ptr2++='\"';
strcpy(ptr2,str);
ptr2[len]='\"';
ptr2[len+1]=0;
return out;
}
ptr=str;while ((token=*ptr) && ++len) {if (strchr("\"\\\b\f\n\r\t",token)) len++; else if (token<32) len+=5;ptr++;}
if (p) out=ensure(p,len+3);
else out=(char*)cJSON_malloc(len+3);
if (!out) return 0;
ptr2=out;ptr=str;
*ptr2++='\"';
while (*ptr)
{
if ((unsigned char)*ptr>31 && *ptr!='\"' && *ptr!='\\') *ptr2++=*ptr++;
else
{
*ptr2++='\\';
switch (token=*ptr++)
{
case '\\': *ptr2++='\\'; break;
case '\"': *ptr2++='\"'; break;
case '\b': *ptr2++='b'; break;
case '\f': *ptr2++='f'; break;
case '\n': *ptr2++='n'; break;
case '\r': *ptr2++='r'; break;
case '\t': *ptr2++='t'; break;
default: sprintf(ptr2,"u%04x",token);ptr2+=5; break; /* escape and print */
}
}
}
*ptr2++='\"';*ptr2++=0;
return out;
}
/* Invote print_string_ptr (which is useful) on an item. */
static char *print_string(cJSON *item,printbuffer *p) {return print_string_ptr(item->valuestring,p);}
/* Predeclare these prototypes. */
static const char *parse_value(cJSON *item,const char *value,const char **ep);
static char *print_value(cJSON *item,int depth,int fmt,printbuffer *p);
static const char *parse_array(cJSON *item,const char *value,const char **ep);
static char *print_array(cJSON *item,int depth,int fmt,printbuffer *p);
static const char *parse_object(cJSON *item,const char *value,const char **ep);
static char *print_object(cJSON *item,int depth,int fmt,printbuffer *p);
/* Utility to jump whitespace and cr/lf */
static const char *skip(const char *in) {while (in && *in && (unsigned char)*in<=32) in++; return in;}
/* Parse an object - create a new root, and populate. */
cJSON *cJSON_ParseWithOpts(const char *value,const char **return_parse_end,int require_null_terminated)
{
const char *end=0,**ep=return_parse_end?return_parse_end:&global_ep;
cJSON *c=cJSON_New_Item();
*ep=0;
if (!c) return 0; /* memory fail */
end=parse_value(c,skip(value),ep);
if (!end) {cJSON_Delete(c);return 0;} /* parse failure. ep is set. */
/* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */
if (require_null_terminated) {end=skip(end);if (*end) {cJSON_Delete(c);*ep=end;return 0;}}
if (return_parse_end) *return_parse_end=end;
return c;
}
/* Default options for cJSON_Parse */
cJSON *cJSON_Parse(const char *value) {return cJSON_ParseWithOpts(value,0,0);}
/* Render a cJSON item/entity/structure to text. */
char *cJSON_Print(cJSON *item) {return print_value(item,0,1,0);}
char *cJSON_PrintUnformatted(cJSON *item) {return print_value(item,0,0,0);}
char *cJSON_PrintBuffered(cJSON *item,int prebuffer,int fmt)
{
printbuffer p;
p.buffer=(char*)cJSON_malloc(prebuffer);
p.length=prebuffer;
p.offset=0;
return print_value(item,0,fmt,&p);
}
/* Parser core - when encountering text, process appropriately. */
static const char *parse_value(cJSON *item,const char *value,const char **ep)
{
if (!value) return 0; /* Fail on null. */
if (!strncmp(value,"null",4)) { item->type=cJSON_NULL; return value+4; }
if (!strncmp(value,"false",5)) { item->type=cJSON_False; return value+5; }
if (!strncmp(value,"true",4)) { item->type=cJSON_True; item->valueint=1; return value+4; }
if (*value=='\"') { return parse_string(item,value,ep); }
if (*value=='-' || (*value>='0' && *value<='9')) { return parse_number(item,value); }
if (*value=='[') { return parse_array(item,value,ep); }
if (*value=='{') { return parse_object(item,value,ep); }
*ep=value;return 0; /* failure. */
}
/* Render a value to text. */
static char *print_value(cJSON *item,int depth,int fmt,printbuffer *p)
{
char *out=0;
if (!item) return 0;
if (p)
{
switch ((item->type)&255)
{
case cJSON_NULL: {out=ensure(p,5); if (out) strcpy(out,"null"); break;}
case cJSON_False: {out=ensure(p,6); if (out) strcpy(out,"false"); break;}
case cJSON_True: {out=ensure(p,5); if (out) strcpy(out,"true"); break;}
case cJSON_Number: out=print_number(item,p);break;
case cJSON_String: out=print_string(item,p);break;
case cJSON_Array: out=print_array(item,depth,fmt,p);break;
case cJSON_Object: out=print_object(item,depth,fmt,p);break;
}
}
else
{
switch ((item->type)&255)
{
case cJSON_NULL: out=cJSON_strdup("null"); break;
case cJSON_False: out=cJSON_strdup("false");break;
case cJSON_True: out=cJSON_strdup("true"); break;
case cJSON_Number: out=print_number(item,0);break;
case cJSON_String: out=print_string(item,0);break;
case cJSON_Array: out=print_array(item,depth,fmt,0);break;
case cJSON_Object: out=print_object(item,depth,fmt,0);break;
}
}
return out;
}
/* Build an array from input text. */
static const char *parse_array(cJSON *item,const char *value,const char **ep)
{
cJSON *child;
if (*value!='[') {*ep=value;return 0;} /* not an array! */
item->type=cJSON_Array;
value=skip(value+1);
if (*value==']') return value+1; /* empty array. */
item->child=child=cJSON_New_Item();
if (!item->child) return 0; /* memory fail */
value=skip(parse_value(child,skip(value),ep)); /* skip any spacing, get the value. */
if (!value) return 0;
while (*value==',')
{
cJSON *new_item;
if (!(new_item=cJSON_New_Item())) return 0; /* memory fail */
child->next=new_item;new_item->prev=child;child=new_item;
value=skip(parse_value(child,skip(value+1),ep));
if (!value) return 0; /* memory fail */
}
if (*value==']') return value+1; /* end of array */
*ep=value;return 0; /* malformed. */
}
/* Render an array to text */
static char *print_array(cJSON *item,int depth,int fmt,printbuffer *p)
{
char **entries;
char *out=0,*ptr,*ret;int len=5;
cJSON *child=item->child;
int numentries=0,i=0,fail=0;
size_t tmplen=0;
/* How many entries in the array? */
while (child) numentries++,child=child->next;
/* Explicitly handle numentries==0 */
if (!numentries)
{
if (p) out=ensure(p,3);
else out=(char*)cJSON_malloc(3);
if (out) strcpy(out,"[]");
return out;
}
if (p)
{
/* Compose the output array. */
i=p->offset;
ptr=ensure(p,1);if (!ptr) return 0; *ptr='['; p->offset++;
child=item->child;
while (child && !fail)
{
print_value(child,depth+1,fmt,p);
p->offset=update(p);
if (child->next) {len=fmt?2:1;ptr=ensure(p,len+1);if (!ptr) return 0;*ptr++=',';if(fmt)*ptr++=' ';*ptr=0;p->offset+=len;}
child=child->next;
}
ptr=ensure(p,2);if (!ptr) return 0; *ptr++=']';*ptr=0;
out=(p->buffer)+i;
}
else
{
/* Allocate an array to hold the values for each */
entries=(char**)cJSON_malloc(numentries*sizeof(char*));
if (!entries) return 0;
memset(entries,0,numentries*sizeof(char*));
/* Retrieve all the results: */
child=item->child;
while (child && !fail)
{
ret=print_value(child,depth+1,fmt,0);
entries[i++]=ret;
if (ret) len+=strlen(ret)+2+(fmt?1:0); else fail=1;
child=child->next;
}
/* If we didn't fail, try to malloc the output string */
if (!fail) out=(char*)cJSON_malloc(len);
/* If that fails, we fail. */
if (!out) fail=1;
/* Handle failure. */
if (fail)
{
for (i=0;i<numentries;i++) if (entries[i]) cJSON_free(entries[i]);
cJSON_free(entries);
return 0;
}
/* Compose the output array. */
*out='[';
ptr=out+1;*ptr=0;
for (i=0;i<numentries;i++)
{
tmplen=strlen(entries[i]);memcpy(ptr,entries[i],tmplen);ptr+=tmplen;
if (i!=numentries-1) {*ptr++=',';if(fmt)*ptr++=' ';*ptr=0;}
cJSON_free(entries[i]);
}
cJSON_free(entries);
*ptr++=']';*ptr++=0;
}
return out;
}
/* Build an object from the text. */
static const char *parse_object(cJSON *item,const char *value,const char **ep)
{
cJSON *child;
if (*value!='{') {*ep=value;return 0;} /* not an object! */
item->type=cJSON_Object;
value=skip(value+1);
if (*value=='}') return value+1; /* empty array. */
item->child=child=cJSON_New_Item();
if (!item->child) return 0;
value=skip(parse_string(child,skip(value),ep));
if (!value) return 0;
child->string=child->valuestring;child->valuestring=0;
if (*value!=':') {*ep=value;return 0;} /* fail! */
value=skip(parse_value(child,skip(value+1),ep)); /* skip any spacing, get the value. */
if (!value) return 0;
while (*value==',')
{
cJSON *new_item;
if (!(new_item=cJSON_New_Item())) return 0; /* memory fail */
child->next=new_item;new_item->prev=child;child=new_item;
value=skip(parse_string(child,skip(value+1),ep));
if (!value) return 0;
child->string=child->valuestring;child->valuestring=0;
if (*value!=':') {*ep=value;return 0;} /* fail! */
value=skip(parse_value(child,skip(value+1),ep)); /* skip any spacing, get the value. */
if (!value) return 0;
}
if (*value=='}') return value+1; /* end of array */
*ep=value;return 0; /* malformed. */
}
/* Render an object to text. */
static char *print_object(cJSON *item,int depth,int fmt,printbuffer *p)
{
char **entries=0,**names=0;
char *out=0,*ptr,*ret,*str;int len=7,i=0,j;
cJSON *child=item->child;
int numentries=0,fail=0;
size_t tmplen=0;
/* Count the number of entries. */
while (child) numentries++,child=child->next;
/* Explicitly handle empty object case */
if (!numentries)
{
if (p) out=ensure(p,fmt?depth+4:3);
else out=(char*)cJSON_malloc(fmt?depth+4:3);
if (!out) return 0;
ptr=out;*ptr++='{';
if (fmt) {*ptr++='\n';for (i=0;i<depth;i++) *ptr++='\t';}
*ptr++='}';*ptr++=0;
return out;
}
if (p)
{
/* Compose the output: */
i=p->offset;
len=fmt?2:1; ptr=ensure(p,len+1); if (!ptr) return 0;
*ptr++='{'; if (fmt) *ptr++='\n'; *ptr=0; p->offset+=len;
child=item->child;depth++;
while (child)
{
if (fmt)
{
ptr=ensure(p,depth); if (!ptr) return 0;
for (j=0;j<depth;j++) *ptr++='\t';
p->offset+=depth;
}
print_string_ptr(child->string,p);
p->offset=update(p);
len=fmt?2:1;
ptr=ensure(p,len); if (!ptr) return 0;
*ptr++=':';if (fmt) *ptr++='\t';
p->offset+=len;
print_value(child,depth,fmt,p);
p->offset=update(p);
len=(fmt?1:0)+(child->next?1:0);
ptr=ensure(p,len+1); if (!ptr) return 0;
if (child->next) *ptr++=',';
if (fmt) *ptr++='\n';*ptr=0;
p->offset+=len;
child=child->next;
}
ptr=ensure(p,fmt?(depth+1):2); if (!ptr) return 0;
if (fmt) for (i=0;i<depth-1;i++) *ptr++='\t';
*ptr++='}';*ptr=0;
out=(p->buffer)+i;
}
else
{
/* Allocate space for the names and the objects */
entries=(char**)cJSON_malloc(numentries*sizeof(char*));
if (!entries) return 0;
names=(char**)cJSON_malloc(numentries*sizeof(char*));
if (!names) {cJSON_free(entries);return 0;}
memset(entries,0,sizeof(char*)*numentries);
memset(names,0,sizeof(char*)*numentries);
/* Collect all the results into our arrays: */
child=item->child;depth++;if (fmt) len+=depth;
while (child && !fail)
{
names[i]=str=print_string_ptr(child->string,0);
entries[i++]=ret=print_value(child,depth,fmt,0);
if (str && ret) len+=strlen(ret)+strlen(str)+2+(fmt?2+depth:0); else fail=1;
child=child->next;
}
/* Try to allocate the output string */
if (!fail) out=(char*)cJSON_malloc(len);
if (!out) fail=1;
/* Handle failure */
if (fail)
{
for (i=0;i<numentries;i++) {if (names[i]) cJSON_free(names[i]);if (entries[i]) cJSON_free(entries[i]);}
cJSON_free(names);cJSON_free(entries);
return 0;
}
/* Compose the output: */
*out='{';ptr=out+1;if (fmt)*ptr++='\n';*ptr=0;
for (i=0;i<numentries;i++)
{
if (fmt) for (j=0;j<depth;j++) *ptr++='\t';
tmplen=strlen(names[i]);memcpy(ptr,names[i],tmplen);ptr+=tmplen;
*ptr++=':';if (fmt) *ptr++='\t';
strcpy(ptr,entries[i]);ptr+=strlen(entries[i]);
if (i!=numentries-1) *ptr++=',';
if (fmt) *ptr++='\n';*ptr=0;
cJSON_free(names[i]);cJSON_free(entries[i]);
}
cJSON_free(names);cJSON_free(entries);
if (fmt) for (i=0;i<depth-1;i++) *ptr++='\t';
*ptr++='}';*ptr++=0;
}
return out;
}
/* Get Array size/item / object item. */
int cJSON_GetArraySize(cJSON *array) {cJSON *c=array->child;int i=0;while(c)i++,c=c->next;return i;}
cJSON *cJSON_GetArrayItem(cJSON *array,int item) {cJSON *c=array?array->child:0;while (c && item>0) item--,c=c->next; return c;}
cJSON *cJSON_GetObjectItem(cJSON *object,const char *string) {cJSON *c=object?object->child:0;while (c && cJSON_strcasecmp(c->string,string)) c=c->next; return c;}
int cJSON_HasObjectItem(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(cJSON *item) {cJSON *ref=cJSON_New_Item();if (!ref) return 0;memcpy(ref,item,sizeof(cJSON));ref->string=0;ref->type|=cJSON_IsReference;ref->next=ref->prev=0;return ref;}
/* Add item to array/object. */
void cJSON_AddItemToArray(cJSON *array, cJSON *item) {cJSON *c=array->child;if (!item) return; if (!c) {array->child=item;} else {while (c && c->next) c=c->next; suffix_object(c,item);}}
void cJSON_AddItemToObject(cJSON *object,const char *string,cJSON *item) {if (!item) return; if (item->string) cJSON_free(item->string);item->string=cJSON_strdup(string);cJSON_AddItemToArray(object,item);}
void cJSON_AddItemToObjectCS(cJSON *object,const char *string,cJSON *item) {if (!item) return; if (!(item->type&cJSON_StringIsConst) && item->string) cJSON_free(item->string);item->string=(char*)string;item->type|=cJSON_StringIsConst;cJSON_AddItemToArray(object,item);}
void cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item) {cJSON_AddItemToArray(array,create_reference(item));}
void cJSON_AddItemReferenceToObject(cJSON *object,const char *string,cJSON *item) {cJSON_AddItemToObject(object,string,create_reference(item));}
cJSON *cJSON_DetachItemFromArray(cJSON *array,int which) {cJSON *c=array->child;while (c && which>0) c=c->next,which--;if (!c) return 0;
if (c->prev) c->prev->next=c->next;if (c->next) c->next->prev=c->prev;if (c==array->child) array->child=c->next;c->prev=c->next=0;return c;}
void cJSON_DeleteItemFromArray(cJSON *array,int which) {cJSON_Delete(cJSON_DetachItemFromArray(array,which));}
cJSON *cJSON_DetachItemFromObject(cJSON *object,const char *string) {int i=0;cJSON *c=object->child;while (c && cJSON_strcasecmp(c->string,string)) i++,c=c->next;if (c) return cJSON_DetachItemFromArray(object,i);return 0;}
void cJSON_DeleteItemFromObject(cJSON *object,const char *string) {cJSON_Delete(cJSON_DetachItemFromObject(object,string));}
/* Replace array/object items with new ones. */
void cJSON_InsertItemInArray(cJSON *array,int which,cJSON *newitem) {cJSON *c=array->child;while (c && which>0) c=c->next,which--;if (!c) {cJSON_AddItemToArray(array,newitem);return;}
newitem->next=c;newitem->prev=c->prev;c->prev=newitem;if (c==array->child) array->child=newitem; else newitem->prev->next=newitem;}
void cJSON_ReplaceItemInArray(cJSON *array,int which,cJSON *newitem) {cJSON *c=array->child;while (c && which>0) c=c->next,which--;if (!c) return;
newitem->next=c->next;newitem->prev=c->prev;if (newitem->next) newitem->next->prev=newitem;
if (c==array->child) array->child=newitem; else newitem->prev->next=newitem;c->next=c->prev=0;cJSON_Delete(c);}
void cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem){int i=0;cJSON *c=object->child;while(c && cJSON_strcasecmp(c->string,string))i++,c=c->next;if(c){newitem->string=cJSON_strdup(string);cJSON_ReplaceItemInArray(object,i,newitem);}}
/* Create basic types: */
cJSON *cJSON_CreateNull(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_NULL;return item;}
cJSON *cJSON_CreateTrue(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_True;return item;}
cJSON *cJSON_CreateFalse(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_False;return item;}
cJSON *cJSON_CreateBool(int b) {cJSON *item=cJSON_New_Item();if(item)item->type=b?cJSON_True:cJSON_False;return item;}
cJSON *cJSON_CreateNumber(double num) {cJSON *item=cJSON_New_Item();if(item){item->type=cJSON_Number;item->valuedouble=num;item->valueint=(int)num;}return item;}
cJSON *cJSON_CreateString(const char *string) {cJSON *item=cJSON_New_Item();if(item){item->type=cJSON_String;item->valuestring=cJSON_strdup(string);if(!item->valuestring){cJSON_Delete(item);return 0;}}return item;}
cJSON *cJSON_CreateArray(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_Array;return item;}
cJSON *cJSON_CreateObject(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_Object;return item;}
/* Create Arrays: */
cJSON *cJSON_CreateIntArray(const int *numbers,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && i<count;i++){n=cJSON_CreateNumber(numbers[i]);if(!n){cJSON_Delete(a);return 0;}if(!i)a->child=n;else suffix_object(p,n);p=n;}return a;}
cJSON *cJSON_CreateFloatArray(const float *numbers,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && i<count;i++){n=cJSON_CreateNumber(numbers[i]);if(!n){cJSON_Delete(a);return 0;}if(!i)a->child=n;else suffix_object(p,n);p=n;}return a;}
cJSON *cJSON_CreateDoubleArray(const double *numbers,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && i<count;i++){n=cJSON_CreateNumber(numbers[i]);if(!n){cJSON_Delete(a);return 0;}if(!i)a->child=n;else suffix_object(p,n);p=n;}return a;}
cJSON *cJSON_CreateStringArray(const char **strings,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && i<count;i++){n=cJSON_CreateString(strings[i]);if(!n){cJSON_Delete(a);return 0;}if(!i)a->child=n;else suffix_object(p,n);p=n;}return a;}
/* Duplication */
cJSON *cJSON_Duplicate(cJSON *item,int recurse)
{
cJSON *newitem,*cptr,*nptr=0,*newchild;
/* Bail on bad ptr */
if (!item) return 0;
/* Create new item */
newitem=cJSON_New_Item();
if (!newitem) return 0;
/* Copy over all vars */
newitem->type=item->type&(~cJSON_IsReference),newitem->valueint=item->valueint,newitem->valuedouble=item->valuedouble;
if (item->valuestring) {newitem->valuestring=cJSON_strdup(item->valuestring); if (!newitem->valuestring) {cJSON_Delete(newitem);return 0;}}
if (item->string) {newitem->string=cJSON_strdup(item->string); if (!newitem->string) {cJSON_Delete(newitem);return 0;}}
/* If non-recursive, then we're done! */
if (!recurse) return newitem;
/* Walk the ->next chain for the child. */
cptr=item->child;
while (cptr)
{
newchild=cJSON_Duplicate(cptr,1); /* Duplicate (with recurse) each item in the ->next chain */
if (!newchild) {cJSON_Delete(newitem);return 0;}
if (nptr) {nptr->next=newchild,newchild->prev=nptr;nptr=newchild;} /* If newitem->child already set, then crosswire ->prev and ->next and move on */
else {newitem->child=newchild;nptr=newchild;} /* Set newitem->child and move to it */
cptr=cptr->next;
}
return newitem;
}
void cJSON_Minify(char *json)
{
char *into=json;
while (*json)
{
if (*json==' ') json++;
else if (*json=='\t') json++; /* Whitespace characters. */
else if (*json=='\r') json++;
else if (*json=='\n') json++;
else if (*json=='/' && json[1]=='/') while (*json && *json!='\n') json++; /* double-slash comments, to end of line. */
else if (*json=='/' && json[1]=='*') {while (*json && !(*json=='*' && json[1]=='/')) json++;json+=2;} /* multiline comments. */
else if (*json=='\"'){*into++=*json++;while (*json && *json!='\"'){if (*json=='\\') *into++=*json++;*into++=*json++;}*into++=*json++;} /* string literals, which are \" sensitive. */
else *into++=*json++; /* All other characters. */
}
*into=0; /* and null-terminate. */
}

153
json/cjson.h Normal file
View File

@@ -0,0 +1,153 @@
/*
Copyright (c) 2009 Dave Gamble
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef cJSON__h
#define cJSON__h
#ifdef __cplusplus
extern "C"
{
#endif
/* cJSON Types: */
#define cJSON_False (1 << 0)
#define cJSON_True (1 << 1)
#define cJSON_NULL (1 << 2)
#define cJSON_Number (1 << 3)
#define cJSON_String (1 << 4)
#define cJSON_Array (1 << 5)
#define cJSON_Object (1 << 6)
#define cJSON_IsReference 256
#define cJSON_StringIsConst 512
/* The cJSON structure: */
typedef struct cJSON {
struct cJSON *next,*prev; /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */
struct cJSON *child; /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */
int type; /* The type of the item, as above. */
char *valuestring; /* The item's string, if type==cJSON_String */
int valueint; /* The item's number, if type==cJSON_Number */
double valuedouble; /* The item's number, if type==cJSON_Number */
char *string; /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */
} cJSON;
typedef struct cJSON_Hooks {
void *(*malloc_fn)(size_t sz);
void (*free_fn)(void *ptr);
} cJSON_Hooks;
/* Supply malloc, realloc and free functions to cJSON */
extern void cJSON_InitHooks(cJSON_Hooks* hooks);
/* Supply a block of JSON, and this returns a cJSON object you can interrogate. Call cJSON_Delete when finished. */
extern cJSON *cJSON_Parse(const char *value);
/* Render a cJSON entity to text for transfer/storage. Free the char* when finished. */
extern char *cJSON_Print(cJSON *item);
/* Render a cJSON entity to text for transfer/storage without any formatting. Free the char* when finished. */
extern char *cJSON_PrintUnformatted(cJSON *item);
/* Render a cJSON entity to text using a buffered strategy. prebuffer is a guess at the final size. guessing well reduces reallocation. fmt=0 gives unformatted, =1 gives formatted */
extern char *cJSON_PrintBuffered(cJSON *item,int prebuffer,int fmt);
/* Delete a cJSON entity and all subentities. */
extern void cJSON_Delete(cJSON *c);
/* Returns the number of items in an array (or object). */
extern int cJSON_GetArraySize(cJSON *array);
/* Retrieve item number "item" from array "array". Returns NULL if unsuccessful. */
extern cJSON *cJSON_GetArrayItem(cJSON *array,int item);
/* Get item "string" from object. Case insensitive. */
extern cJSON *cJSON_GetObjectItem(cJSON *object,const char *string);
extern int cJSON_HasObjectItem(cJSON *object,const char *string);
/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */
extern const char *cJSON_GetErrorPtr(void);
/* These calls create a cJSON item of the appropriate type. */
extern cJSON *cJSON_CreateNull(void);
extern cJSON *cJSON_CreateTrue(void);
extern cJSON *cJSON_CreateFalse(void);
extern cJSON *cJSON_CreateBool(int b);
extern cJSON *cJSON_CreateNumber(double num);
extern cJSON *cJSON_CreateString(const char *string);
extern cJSON *cJSON_CreateArray(void);
extern cJSON *cJSON_CreateObject(void);
/* These utilities create an Array of count items. */
extern cJSON *cJSON_CreateIntArray(const int *numbers,int count);
extern cJSON *cJSON_CreateFloatArray(const float *numbers,int count);
extern cJSON *cJSON_CreateDoubleArray(const double *numbers,int count);
extern cJSON *cJSON_CreateStringArray(const char **strings,int count);
/* Append item to the specified array/object. */
extern void cJSON_AddItemToArray(cJSON *array, cJSON *item);
extern void cJSON_AddItemToObject(cJSON *object,const char *string,cJSON *item);
extern void cJSON_AddItemToObjectCS(cJSON *object,const char *string,cJSON *item); /* Use this when string is definitely const (i.e. a literal, or as good as), and will definitely survive the cJSON object */
/* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new cJSON, but don't want to corrupt your existing cJSON. */
extern void cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item);
extern void cJSON_AddItemReferenceToObject(cJSON *object,const char *string,cJSON *item);
/* Remove/Detatch items from Arrays/Objects. */
extern cJSON *cJSON_DetachItemFromArray(cJSON *array,int which);
extern void cJSON_DeleteItemFromArray(cJSON *array,int which);
extern cJSON *cJSON_DetachItemFromObject(cJSON *object,const char *string);
extern void cJSON_DeleteItemFromObject(cJSON *object,const char *string);
/* Update array items. */
extern void cJSON_InsertItemInArray(cJSON *array,int which,cJSON *newitem); /* Shifts pre-existing items to the right. */
extern void cJSON_ReplaceItemInArray(cJSON *array,int which,cJSON *newitem);
extern void cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem);
/* Duplicate a cJSON item */
extern cJSON *cJSON_Duplicate(cJSON *item,int recurse);
/* Duplicate will create a new, identical cJSON item to the one you pass, in new memory that will
need to be released. With recurse!=0, it will duplicate any children connected to the item.
The item->next and ->prev pointers are always zero on return from Duplicate. */
/* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */
/* If you supply a ptr in return_parse_end and parsing fails, then return_parse_end will contain a pointer to the error. If not, then cJSON_GetErrorPtr() does the job. */
extern cJSON *cJSON_ParseWithOpts(const char *value,const char **return_parse_end,int require_null_terminated);
extern void cJSON_Minify(char *json);
/* Macros for creating things quickly. */
#define cJSON_AddNullToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateNull())
#define cJSON_AddTrueToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateTrue())
#define cJSON_AddFalseToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateFalse())
#define cJSON_AddBoolToObject(object,name,b) cJSON_AddItemToObject(object, name, cJSON_CreateBool(b))
#define cJSON_AddNumberToObject(object,name,n) cJSON_AddItemToObject(object, name, cJSON_CreateNumber(n))
#define cJSON_AddStringToObject(object,name,s) cJSON_AddItemToObject(object, name, cJSON_CreateString(s))
/* When assigning an integer value, it needs to be propagated to valuedouble too. */
#define cJSON_SetIntValue(object,val) ((object)?(object)->valueint=(object)->valuedouble=(val):(val))
#define cJSON_SetNumberValue(object,val) ((object)?(object)->valueint=(object)->valuedouble=(val):(val))
/* Macro for iterating over an array */
#define cJSON_ArrayForEach(pos, head) for(pos = (head)->child; pos != NULL; pos = pos->next)
#ifdef __cplusplus
}
#endif
#endif

3573
json/create_json.cpp Normal file

File diff suppressed because it is too large Load Diff

249
json/kafka_producer.cpp Normal file
View File

@@ -0,0 +1,249 @@
#include <iostream>
#include <string>
#include <cstdlib>
#include <cstdio>
#include <csignal>
#include <cstring>
#include <apr_strings.h>
#include "kafka_producer.h"
#define CONFIG_PATH "../etc"
#ifndef WIN32
#define nullptr NULL
#endif
extern int SEND_FLAG;
extern char* PROTOCOL;
extern char* MECHANISMS;
extern char* KEYTAB_FILE;
extern char* SERVICE_NAME;
extern char* PRINCIPAL;
extern char* DOMAIN_NAME;
class MyHashPartitionerCb : public RdKafka::PartitionerCb {
public:
int32_t partitioner_cb (const RdKafka::Topic *topic, const std::string *key,
int32_t partition_cnt, void *msg_opaque) {
int n = atoi(key->c_str());
int part_id = (n % partition_cnt);
printf("MyHashPartitionerCb key n=%d,partition_cnt=%d,partition_id=%d \n",n,partition_cnt,part_id);
return part_id;
}
private:
//static inline unsigned int djb_hash (const char *str, size_t len) {
// unsigned int hash = 5381;
// for (size_t i = 0 ; i < len ; i++)
// hash = ((hash << 5) + hash) + str[i];
// return hash;
//}
};
class ProducerDeliveryReportCb : public RdKafka::DeliveryReportCb {
public: void dr_cb(RdKafka::Message& message) {
if (message.err())
printf("Message delivery failed: topic=%s error=%s\n", message.topic_name().c_str(), message.errstr().c_str());
else
printf("Message delivery sucess: topic=%s \n", message.topic_name().c_str());
}
};
FeKafkaProducer::FeKafkaProducer()
{
}
FeKafkaProducer::~FeKafkaProducer()
{
}
bool FeKafkaProducer::init(const std::string &brokerlist, const bool &async, const int &size)
{
std::string errstr;
this->topics_.clear();
#ifdef __GNUC__
conf_ = (RdKafka::Conf::create(RdKafka::Conf::CONF_GLOBAL));
tconf_ = (RdKafka::Conf::create(RdKafka::Conf::CONF_TOPIC));
#endif
if (conf_ == nullptr || tconf_== nullptr)
{
return false;
}
#ifdef __GNUC__
static MyHashPartitionerCb hash_partitioner;
if (tconf_->set("partitioner_cb", &hash_partitioner, errstr) != RdKafka::Conf::CONF_OK) {
std::cerr << errstr << std::endl;
return false;
}
static ProducerDeliveryReportCb producerDELIVER;
if (conf_->set("dr_cb", &producerDELIVER, errstr) != RdKafka::Conf::CONF_OK) {
std::cerr << errstr << std::endl;
return false;
}
#endif
//std::string broker(host);
//broker.append(":").append(std::to_string((long long)port));
conf_->set("metadata.broker.list", brokerlist, errstr);
if (strcmp(PROTOCOL, "sasl_plaintext") == 0) {
conf_->set("security.protocol", PROTOCOL, errstr);
conf_->set("sasl.mechanisms", MECHANISMS, errstr);
std::string kinit = "/usr/bin/kinit -kt \"";
kinit.append(KEYTAB_FILE);
kinit.append("\" ");
kinit.append(PRINCIPAL);
conf_->set("sasl.kerberos.kinit.cmd", kinit, errstr);
conf_->set("sasl.kerberos.keytab", KEYTAB_FILE, errstr);
conf_->set("sasl.kerberos.service.name", SERVICE_NAME, errstr);
conf_->set("sasl.kerberos.principal", PRINCIPAL, errstr);
conf_->set("sasl.kerberos.domain.name", DOMAIN_NAME, errstr);
printf("kafka sasl PROTOCOL=%s,MECHANISMS=%s,kinit=%s,KEYTAB_FILE=%s,SERVICE_NAME=%s,PRINCIPAL=%s,DOMAIN_NAME=%s \n", PROTOCOL, MECHANISMS, kinit.c_str(), KEYTAB_FILE, SERVICE_NAME, PRINCIPAL, DOMAIN_NAME);
}
if (async)
{
char size_str[256];
conf_->set("producer.type", "async", errstr);
//conf_->set("queue.buffering.max.messages", std::to_string((long long)size).c_str(), errstr);
memset(size_str,0,256);
apr_snprintf(size_str,sizeof(size_str),"%i",size);
conf_->set("queue.buffering.max.messages", size_str, errstr);
{
//const char* api_version_request = "false";
//const char* api_version_fallback = "0.8.2.0";
//conf_->set("api.version.request", api_version_request, errstr) ;
//conf_->set("broker.version.fallback", api_version_fallback, errstr);
}
}
else
{
conf_->set("producer.type", "sync", errstr);
}
#ifdef __GNUC__
producer_ = RdKafka::Producer::create(conf_, errstr);
if (!producer_)
{
std::cerr << "Failed to create producer: " << errstr << std::endl;
return false;
}
#endif
return true;
}
int FeKafkaProducer::send(const char *data, const int &size, const std::string &topic,
const int &partition, const std::string *key,const int &timeout)
{
RdKafka::Topic *tpk = get_topic(topic);
//std::cout<<"send data "<<data<<std::endl;
if (tpk == nullptr) {
printf("FIRST: get topic(%s) failed, to create at once \n",topic.c_str());
bool ret = create_topic(topic);
if(ret) {
printf("create topic OK \n");
tpk = get_topic(topic);
if (tpk == nullptr) {
printf("SECOND: get topic(%s) failed! but create topic seemed OK, what ??? ",topic.c_str());
return -1;
}
}
else {
printf("create topic Failed \n");
return -1;
}
}
RdKafka::ErrorCode resp =
producer_->produce(tpk, partition,
RdKafka::Producer::RK_MSG_COPY /* Copy payload */,
const_cast<char*>(data), size,
key->c_str(),key->size(), NULL);
///*NULL*/ key, NULL);
if (resp != RdKafka::ERR_NO_ERROR)
{
#ifdef __GNUC__
std::cerr << "% Produce failed: " <<
RdKafka::err2str(resp) << std::endl;
#endif
return -1;
}
producer_->poll(timeout);
return size;
}
int FeKafkaProducer::send_batch(const std::vector<std::pair<const char *, const int &> > &data,
const std::string &topic, const int &partition, const int &timeout)
{
return 0;
}
bool FeKafkaProducer::create_topic(const std::string &topic)
{
std::string errstr;
if (topic.empty() || producer_== nullptr || tconf_== nullptr)
{
printf("(topic.empty() || producer_== nullptr || tconf_== nullptr) \n");
return false;
}
if (this->get_topic(topic) != nullptr)
{
printf("if (this->get_topic(topic) != nullptr) \n");
return false;
}
#ifdef __GNUC__
RdKafka::Topic* tpk = (RdKafka::Topic::create(producer_, topic, tconf_, errstr));
if (!tpk)
{
std::cerr << "Failed to create topic: " << errstr << std::endl;
return false;
}
topics_.insert(make_pair(topic, tpk));
#endif
return true;
}
RdKafka::Topic *FeKafkaProducer::get_topic(const std::string &topic)
{
std::map<std::string, RdKafka::Topic*>::iterator it = topics_.find(topic);
if(it != topics_.end())
{
return it->second;
}
return nullptr;
}
void FeKafkaProducer::read_config(const char *path)
{
}
void FeKafkaProducer::close()
{
while (producer_->outq_len() > 0)
{
std::cerr << "Waiting for " << producer_->outq_len() << std::endl;
producer_->poll(1000);
}
#ifdef __GNUC__
RdKafka::wait_destroyed(1000);
#endif
}

43
json/kafka_producer.h Normal file
View File

@@ -0,0 +1,43 @@
#ifndef _FEKAFKA_PRODUCER_
#define _FEKAFKA_PRODUCER_
#include <string>
#include <vector>
#include <map>
#include <memory>
#include "rdkafkacpp.h"
class FeKafkaProducer
{
public:
FeKafkaProducer();
~FeKafkaProducer();
public:
bool init(const std::string &brokerlist, const bool &async = true, const int &size = 0x7fffffff);
int send(const char *data,
const int &size,
const std::string &topic,
const int &partition = 0,
const std::string *key = NULL,
const int &timeout = 0);
int send_batch(const std::vector<std::pair<const char *, const int &> > &data,
const std::string &topic,
const int &partition = 0,
const int &timeout = 0);
bool create_topic(const std::string &topic);
void close();
private:
void read_config(const char *path);
RdKafka::Topic* get_topic(const std::string &topic);
private:
RdKafka::Producer* producer_;
RdKafka::Conf* conf_;
RdKafka::Conf* tconf_;
std::map<std::string, RdKafka::Topic*> topics_;
};
#endif // _KAFKA_PRODUCER_

143
json/mms_json_inter.h Normal file
View File

@@ -0,0 +1,143 @@
/**
* @file: $RCSfile: mms_json_inter.h,v $
* @brief: $IEC 61850 Protocol
*
* @version: $Revision: 1.5 $
* @date: $Date: 2018/12/25 13:31:25 $
* @author: $Author: lizhongming $
* @state: $State: Exp $
*
* @latest: $Id: mms_json_inter.h,v 1.5 2018/12/25 13:31:25 lizhongming Exp $
*
*/
#ifndef MMS_JSON_INTER_92327hyhy0923r_H
#define MMS_JSON_INTER_92327hyhy0923r_H
#ifdef __cplusplus
#include <QString>
#include <QList>
#include <QMutex>
#include <QMap>
#define STAT_DATA_BASE_NODE_ID 100 //<2F><>̬<EFBFBD><CCAC>ͳ<EFBFBD><CDB3><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
#define THREE_SECS_DATA_BASE_NODE_ID 200 // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ݡ<EFBFBD>ʵʱ<CAB5><CAB1><EFBFBD><EFBFBD>
#define SOE_COMTRADE_BASE_NODE_ID 300 // soe ¼<><C2BC>
#define HIS_DATA_BASE_NODE_ID 400 //<2F><>ʷ<EFBFBD><CAB7><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
class json_block_data //jsonƴ<6E>Ӳ<EFBFBD><D3B2><EFBFBD><EFBFBD><EFBFBD>
{
public:
int monitorId; //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ID
int func_type; //<2F><>Ӧ(#define<6E><EFBFBD><EAB6A8><EFBFBD><EFBFBD>100 <20><> 400)<29><><EFBFBD><EFBFBD>ѡ<EFBFBD><D1A1>
int flag; //<2F>޳<EFBFBD><DEB3><EFBFBD><EFBFBD>ǣ<EFBFBD>1<EFBFBD><31><EFBFBD>޳<EFBFBD><DEB3><EFBFBD>0<EFBFBD>޳<EFBFBD><DEB3><EFBFBD>Ĭ<EFBFBD><C4AC><EFBFBD>޳<EFBFBD> <09><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ρ<EFBFBD><CEA1><EFBFBD>˲<EFBFBD><CBB2><EFBFBD><EFBFBD><EFBFBD><EFBFBD>δ<EFBFBD><CEB4><EFBFBD>·װ<C2B7>ô<EFBFBD><C3B4><EFBFBD>ȡ<EFBFBD><C8A1><EFBFBD><EFBFBD><EFBFBD><EFBFBD>2018-11-21 19:32:38
long long time; //ʱ<><CAB1><EFBFBD><EFBFBD>(<28><><EFBFBD><EFBFBD>)
double voltage_level; //CZY 2023-08-23 <20><>ѹ<EFBFBD>ȼ<EFBFBD>(<28><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>double<6C><65><EFBFBD><EFBFBD>)
QString mp_id; //char<61>ͼ<EFBFBD><CDBC><EFBFBD><EFBFBD><EFBFBD>
QString dev_type;//<2F><EFBFBD><E8B1B8><EFBFBD><EFBFBD>
QMap<QString, double> mms_str_map; //<2F><><EFBFBD><EFBFBD>ֵ(61850<35><30><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>, <20><><EFBFBD><EFBFBD>ֵ)
/*
json_block_data() //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʹ<EFBFBD>ã<EFBFBD> zl 2018-11-22 09:03:30 ----<2D><><EFBFBD>Բ<EFBFBD><D4B2>Գ<EFBFBD>ֵ<EFBFBD><D6B5>
{
monitorId = 7501; //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ID
partitionSize = 3; //kafka<6B><61><EFBFBD>ͷ<EFBFBD><CDB7><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
func_type = 100; //<2F><>Ӧ(#define<6E><EFBFBD><EAB6A8><EFBFBD><EFBFBD>100 <20><> 400)<29><><EFBFBD><EFBFBD>ѡ<EFBFBD><D1A1>
data_type = 1; //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
flag = 0; //<2F>޳<EFBFBD><DEB3><EFBFBD><EFBFBD><EFBFBD>
time = 1546099200000; //ʱ<><CAB1><EFBFBD><EFBFBD>(<28><><EFBFBD><EFBFBD>) <20><><EFBFBD><EFBFBD>2018-12-30??00:00:00
//connectLineCount = 1; //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>·<EFBFBD><C2B7>
//triggerLineCount = 1; //<2F>Ѵ<EFBFBD><D1B4><EFBFBD><EFBFBD><EFBFBD>·<EFBFBD><C2B7>
mms_str_map.insert("MMXU4$MX$PhVDev$phsA$cVal$mag$f", 123.4567890); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʹ<EFBFBD>ã<EFBFBD> zl 2018-11-22 10:46:15
mms_str_map.insert("MHAI2$MX$HRPhV$phsAHar[0]$ang$f", 200.1234567); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʹ<EFBFBD>ã<EFBFBD> zl 2018-11-22 10:46:15
mms_str_map.insert("MHAI2$MX$HRPhV$phsAHar[47]$ang$f", 300.1234567); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʹ<EFBFBD>ã<EFBFBD> zl 2018-11-22 10:46:15
mms_str_map.insert("MHAI2$MX$HRPhV$phsAHar[48]$ang$f", 300.1234567); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʹ<EFBFBD>ã<EFBFBD> zl 2018-11-22 10:46:15
mms_str_map.insert("MMXU4$MX$PhVDev$phsB$cVal$mag$f", 123.4567890); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʹ<EFBFBD>ã<EFBFBD> zl 2018-11-22 10:46:15
mms_str_map.insert("MHAI2$MX$HRPhV$phsBHar[0]$ang$f", 200.1234567); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʹ<EFBFBD>ã<EFBFBD> zl 2018-11-22 10:46:15
mms_str_map.insert("MHAI2$MX$HRPhV$phsBar[47]$ang$f", 300.1234567); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʹ<EFBFBD>ã<EFBFBD> zl 2018-11-22 10:46:15
mms_str_map.insert("MHAI2$MX$HRPhV$phsBar[48]$ang$f", 300.1234567); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʹ<EFBFBD>ã<EFBFBD> zl 2018-11-22 10:46:15
mms_str_map.insert("MMXU4$MX$PhVDev$phsC$cVal$mag$f", 123.4567890); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʹ<EFBFBD>ã<EFBFBD> zl 2018-11-22 10:46:15
mms_str_map.insert("MHAI2$MX$HRPhV$phsCHar[0]$ang$f", 200.1234567); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʹ<EFBFBD>ã<EFBFBD> zl 2018-11-22 10:46:15
mms_str_map.insert("MHAI2$MX$HRPhV$phsCHar[47]$ang$f", 300.1234567); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʹ<EFBFBD>ã<EFBFBD> zl 2018-11-22 10:46:15
mms_str_map.insert("MHAI2$MX$HRPhV$phsCHar[48]$ang$f", 300.1234567); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʹ<EFBFBD>ã<EFBFBD> zl 2018-11-22 10:46:15
}
*/
};
class Ckafka_data_t //kafka<6B><61><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ݽṹ<DDBD><E1B9B9>
{
public:
int monitor_id; //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ID
QString strTopic; //kafka<6B><61><EFBFBD><EFBFBD>topic
QString strText; //kafka<6B><61><EFBFBD>͵<EFBFBD>json<6F>ַ<EFBFBD><D6B7><EFBFBD>
QString mp_id; //char<61><72><EFBFBD><EFBFBD>id
};
class oss_data_t //oss<73><73><EFBFBD>ͷ<EFBFBD><CDB7><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ݽṹ<DDBD><E1B9B9> zw 2023-9-22 <20><><EFBFBD><EFBFBD>
{
public:
QString filename; //<2F>Ʊ<EFBFBD><C6B1><EFBFBD>·<EFBFBD><C2B7>
QString savename; //<2F><><EFBFBD>ر<EFBFBD><D8B1><EFBFBD>·<EFBFBD><C2B7>
QString data; //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
//<2F><>־ͨ<D6BE>ò<EFBFBD><C3B2><EFBFBD>
QString log_name; //<2F>ն<EFBFBD>id<69><64><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>id
QString id; //<2F>ն<EFBFBD>id<69><64><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>id
QString time; //ʱ<><CAB1>
//match_log
int base_mat_num;
int adv_mat_num;
int base_act_num;
int adv_act_num;
//reason_log
int list_num;
};
//extern QMutex kafka_data_list_mutex;
//extern QList<kafka_data_t> kafka_data_list;
/* ʹ<><CAB9>ʾ<EFBFBD><CABE><EFBFBD><EFBFBD><EFBFBD>
Ckafka_data_t data;
data.patition_id = 0;
data.strText = QString("{a=1,b=2}");
kafka_data_list_mutex.lock();
kafka_data_list.append(data);
kafka_data_list_mutex.unlock();
*/
int transfer_json_block_data(json_block_data *data);
void errorlog_pgsql(char* id, QString time, QString filename);
QString errorlog_num_pgsql(QString monitorId, QString datatime, QString filename, int count);
QString errorlog_datamatch_pgsql(QString id, QString time, int BASE_MAT_NUM, int ADV_MAT_NUM, int BASE_ACT_NUM, int ADV_ACT_NUM, QString filename);
#endif /* __cplusplus */
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
int transfer_json_qvvr_data(unsigned int func_type,int monitor_id,float mag,float dur,long long start_tm,long long end_tm,int dis_kind, char* uuid_cfg, char* uuid_dat, char* mp_id, char* Qvvr_rptname, char* devtype);
void processGGIO_start_data_end(char* mp_id, char* fullname, double v,long long time,char* devtype,int monitor_id);
//void errorlog_num(CDataValue* pDataValue, double value, int monitorId, double UL, int maxcount);
//void errorlog_num_json(int monitorId);
void Set_xml_databaseinfo(char* MODEL_ID, char* TMNL_TYPE, char* TMNL_FACTORY, char* FILE_NAME, int year, int month, int day, int hour, int minute, int second);//zw<7A>޸<EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ú<EFBFBD><C3BA><EFBFBD>
void Set_xml_nodeinfo();//zw<7A>޸<EFBFBD>
char* Get_xmlpath(char* devtype);
char* Get_IED(char* devtype);
char* Get_LDevice(char* devtype);
void errorlog_json(char* id, char* ip, int port, int type, char* error_type, char* ERROR_DES, char* ERROR_PARAM);
void SoeRptSql(char* id, int state, char* rpt);
void connectlog_pgsql(char* id,char* datetime,int status);
#ifdef __cplusplus
}
#endif
#endif //MMS_JSON_INTER_92327hyhy0923r_H

10128
json/rdkafka.h Normal file

File diff suppressed because it is too large Load Diff

424
json/rdkafka_mock.h Normal file
View File

@@ -0,0 +1,424 @@
/*
* librdkafka - Apache Kafka C library
*
* Copyright (c) 2019-2022, Magnus Edenhill
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _RDKAFKA_MOCK_H_
#define _RDKAFKA_MOCK_H_
#ifndef _RDKAFKA_H_
#error "rdkafka_mock.h must be included after rdkafka.h"
#endif
#ifdef __cplusplus
extern "C" {
#if 0
} /* Restore indent */
#endif
#endif
/**
* @name Mock cluster
*
* Provides a mock Kafka cluster with a configurable number of brokers
* that support a reasonable subset of Kafka protocol operations,
* error injection, etc.
*
* There are two ways to use the mock clusters, the most simple approach
* is to configure `test.mock.num.brokers` (to e.g. 3) on the rd_kafka_t
* in an existing application, which will replace the configured
* `bootstrap.servers` with the mock cluster brokers.
* This approach is convenient to easily test existing applications.
*
* The second approach is to explicitly create a mock cluster on an
* rd_kafka_t instance by using rd_kafka_mock_cluster_new().
*
* Mock clusters provide localhost listeners that can be used as the bootstrap
* servers by multiple rd_kafka_t instances.
*
* Currently supported functionality:
* - Producer
* - Idempotent Producer
* - Transactional Producer
* - Low-level consumer
* - High-level balanced consumer groups with offset commits
* - Topic Metadata and auto creation
*
* @remark This is an experimental public API that is NOT covered by the
* librdkafka API or ABI stability guarantees.
*
*
* @warning THIS IS AN EXPERIMENTAL API, SUBJECT TO CHANGE OR REMOVAL.
*
* @{
*/
typedef struct rd_kafka_mock_cluster_s rd_kafka_mock_cluster_t;
/**
* @brief Create new mock cluster with \p broker_cnt brokers.
*
* The broker ids will start at 1 up to and including \p broker_cnt.
*
* The \p rk instance is required for internal book keeping but continues
* to operate as usual.
*/
RD_EXPORT
rd_kafka_mock_cluster_t *rd_kafka_mock_cluster_new(rd_kafka_t *rk,
int broker_cnt);
/**
* @brief Destroy mock cluster.
*/
RD_EXPORT
void rd_kafka_mock_cluster_destroy(rd_kafka_mock_cluster_t *mcluster);
/**
* @returns the rd_kafka_t instance for a cluster as passed to
* rd_kafka_mock_cluster_new().
*/
RD_EXPORT rd_kafka_t *
rd_kafka_mock_cluster_handle(const rd_kafka_mock_cluster_t *mcluster);
/**
* @returns the rd_kafka_mock_cluster_t instance as created by
* setting the `test.mock.num.brokers` configuration property,
* or NULL if no such instance.
*/
RD_EXPORT rd_kafka_mock_cluster_t *
rd_kafka_handle_mock_cluster(const rd_kafka_t *rk);
/**
* @returns the mock cluster's bootstrap.servers list
*/
RD_EXPORT const char *
rd_kafka_mock_cluster_bootstraps(const rd_kafka_mock_cluster_t *mcluster);
/**
* @brief Clear the cluster's error state for the given \p ApiKey.
*/
RD_EXPORT
void rd_kafka_mock_clear_request_errors(rd_kafka_mock_cluster_t *mcluster,
int16_t ApiKey);
/**
* @brief Push \p cnt errors in the \p ... va-arg list onto the cluster's
* error stack for the given \p ApiKey.
*
* \p ApiKey is the Kafka protocol request type, e.g., ProduceRequest (0).
*
* The following \p cnt protocol requests matching \p ApiKey will fail with the
* provided error code and removed from the stack, starting with
* the first error code, then the second, etc.
*
* Passing \c RD_KAFKA_RESP_ERR__TRANSPORT will make the mock broker
* disconnect the client which can be useful to trigger a disconnect on certain
* requests.
*/
RD_EXPORT
void rd_kafka_mock_push_request_errors(rd_kafka_mock_cluster_t *mcluster,
int16_t ApiKey,
size_t cnt,
...);
/**
* @brief Same as rd_kafka_mock_push_request_errors() but takes
* an array of errors.
*/
RD_EXPORT void
rd_kafka_mock_push_request_errors_array(rd_kafka_mock_cluster_t *mcluster,
int16_t ApiKey,
size_t cnt,
const rd_kafka_resp_err_t *errors);
/**
* @brief Push \p cnt errors and RTT tuples in the \p ... va-arg list onto
* the broker's error stack for the given \p ApiKey.
*
* \p ApiKey is the Kafka protocol request type, e.g., ProduceRequest (0).
*
* Each entry is a tuple of:
* rd_kafka_resp_err_t err - error to return (or 0)
* int rtt_ms - response RTT/delay in milliseconds (or 0)
*
* The following \p cnt protocol requests matching \p ApiKey will fail with the
* provided error code and removed from the stack, starting with
* the first error code, then the second, etc.
*
* @remark The broker errors take precedence over the cluster errors.
*/
RD_EXPORT rd_kafka_resp_err_t
rd_kafka_mock_broker_push_request_error_rtts(rd_kafka_mock_cluster_t *mcluster,
int32_t broker_id,
int16_t ApiKey,
size_t cnt,
...);
/**
* @brief Get the count of errors in the broker's error stack for
* the given \p ApiKey.
*
* @param mcluster the mock cluster.
* @param broker_id id of the broker in the cluster.
* @param ApiKey is the Kafka protocol request type, e.g., ProduceRequest (0).
* @param cntp pointer for receiving the count.
*
* @returns \c RD_KAFKA_RESP_ERR_NO_ERROR if the count was retrieved,
* \c RD_KAFKA_RESP_ERR__UNKNOWN_BROKER if there was no broker with this id,
* \c RD_KAFKA_RESP_ERR__INVALID_ARG if some of the parameters are not valid.
*/
RD_EXPORT rd_kafka_resp_err_t
rd_kafka_mock_broker_error_stack_cnt(rd_kafka_mock_cluster_t *mcluster,
int32_t broker_id,
int16_t ApiKey,
size_t *cntp);
/**
* @brief Set the topic error to return in protocol requests.
*
* Currently only used for TopicMetadataRequest and AddPartitionsToTxnRequest.
*/
RD_EXPORT
void rd_kafka_mock_topic_set_error(rd_kafka_mock_cluster_t *mcluster,
const char *topic,
rd_kafka_resp_err_t err);
/**
* @brief Creates a topic.
*
* This is an alternative to automatic topic creation as performed by
* the client itself.
*
* @remark The Topic Admin API (CreateTopics) is not supported by the
* mock broker.
*/
RD_EXPORT rd_kafka_resp_err_t
rd_kafka_mock_topic_create(rd_kafka_mock_cluster_t *mcluster,
const char *topic,
int partition_cnt,
int replication_factor);
/**
* @brief Sets the partition leader.
*
* The topic will be created if it does not exist.
*
* \p broker_id needs to be an existing broker, or -1 to make the
* partition leader-less.
*/
RD_EXPORT rd_kafka_resp_err_t
rd_kafka_mock_partition_set_leader(rd_kafka_mock_cluster_t *mcluster,
const char *topic,
int32_t partition,
int32_t broker_id);
/**
* @brief Sets the partition's preferred replica / follower.
*
* The topic will be created if it does not exist.
*
* \p broker_id does not need to point to an existing broker.
*/
RD_EXPORT rd_kafka_resp_err_t
rd_kafka_mock_partition_set_follower(rd_kafka_mock_cluster_t *mcluster,
const char *topic,
int32_t partition,
int32_t broker_id);
/**
* @brief Sets the partition's preferred replica / follower low and high
* watermarks.
*
* The topic will be created if it does not exist.
*
* Setting an offset to -1 will revert back to the leader's corresponding
* watermark.
*/
RD_EXPORT rd_kafka_resp_err_t
rd_kafka_mock_partition_set_follower_wmarks(rd_kafka_mock_cluster_t *mcluster,
const char *topic,
int32_t partition,
int64_t lo,
int64_t hi);
/**
* @brief Disconnects the broker and disallows any new connections.
* This does NOT trigger leader change.
*
* @param mcluster Mock cluster instance.
* @param broker_id Use -1 for all brokers, or >= 0 for a specific broker.
*/
RD_EXPORT rd_kafka_resp_err_t
rd_kafka_mock_broker_set_down(rd_kafka_mock_cluster_t *mcluster,
int32_t broker_id);
/**
* @brief Makes the broker accept connections again.
* This does NOT trigger leader change.
*
* @param mcluster Mock cluster instance.
* @param broker_id Use -1 for all brokers, or >= 0 for a specific broker.
*/
RD_EXPORT rd_kafka_resp_err_t
rd_kafka_mock_broker_set_up(rd_kafka_mock_cluster_t *mcluster,
int32_t broker_id);
/**
* @brief Set broker round-trip-time delay in milliseconds.
*
* @param mcluster Mock cluster instance.
* @param broker_id Use -1 for all brokers, or >= 0 for a specific broker.
*/
RD_EXPORT rd_kafka_resp_err_t
rd_kafka_mock_broker_set_rtt(rd_kafka_mock_cluster_t *mcluster,
int32_t broker_id,
int rtt_ms);
/**
* @brief Sets the broker's rack as reported in Metadata to the client.
*
* @param mcluster Mock cluster instance.
* @param broker_id Use -1 for all brokers, or >= 0 for a specific broker.
*/
RD_EXPORT rd_kafka_resp_err_t
rd_kafka_mock_broker_set_rack(rd_kafka_mock_cluster_t *mcluster,
int32_t broker_id,
const char *rack);
/**
* @brief Explicitly sets the coordinator. If this API is not a standard
* hashing scheme will be used.
*
* @param key_type "transaction" or "group"
* @param key The transactional.id or group.id
* @param broker_id The new coordinator, does not have to be a valid broker.
*/
RD_EXPORT rd_kafka_resp_err_t
rd_kafka_mock_coordinator_set(rd_kafka_mock_cluster_t *mcluster,
const char *key_type,
const char *key,
int32_t broker_id);
/**
* @brief Set the allowed ApiVersion range for \p ApiKey.
*
* Set \p MinVersion and \p MaxVersion to -1 to disable the API
* completely.
*
* \p MaxVersion MUST not exceed the maximum implemented value,
* see rdkafka_mock_handlers.c.
*
* @param ApiKey Protocol request type/key
* @param MinVersion Minimum version supported (or -1 to disable).
* @param MinVersion Maximum version supported (or -1 to disable).
*/
RD_EXPORT rd_kafka_resp_err_t
rd_kafka_mock_set_apiversion(rd_kafka_mock_cluster_t *mcluster,
int16_t ApiKey,
int16_t MinVersion,
int16_t MaxVersion);
/**
* @name Represents a request to the mock cluster along with a timestamp.
*/
typedef struct rd_kafka_mock_request_s rd_kafka_mock_request_t;
RD_EXPORT
rd_kafka_mock_request_t *
rd_kafka_mock_request_new(int32_t id, int16_t api_key, rd_ts_t timestamp);
RD_EXPORT
void rd_kafka_mock_start_request_tracking(rd_kafka_mock_cluster_t *mcluster);
RD_EXPORT
void rd_kafka_mock_stop_request_tracking(rd_kafka_mock_cluster_t *mcluster);
/**
* @brief Destroy a rd_kafka_mock_request_t * and deallocate memory.
*/
RD_EXPORT void rd_kafka_mock_request_destroy(rd_kafka_mock_request_t *mreq);
/**
* @brief Get the broker id to which \p mreq was sent.
*/
RD_EXPORT int32_t rd_kafka_mock_request_id(rd_kafka_mock_request_t *mreq);
/**
* @brief Get the ApiKey with which \p mreq was sent.
*/
RD_EXPORT int16_t rd_kafka_mock_request_api_key(rd_kafka_mock_request_t *mreq);
/**
* @brief Get the timestamp at which \p mreq was sent.
*/
RD_EXPORT rd_ts_t
rd_kafka_mock_request_timestamp(rd_kafka_mock_request_t *mreq);
/**
* @brief Get the list of requests sent to this mock cluster.
*
* @param cntp is set to the count of requests.
* @return List of rd_kafka_mock_request_t *.
* @remark each element of the returned array must be freed with
* rd_kafka_mock_request_destroy, and the list itself must be freed too.
*/
RD_EXPORT rd_kafka_mock_request_t **
rd_kafka_mock_get_requests(rd_kafka_mock_cluster_t *mcluster, size_t *cntp);
/**
* @brief Clear the list of requests sent to this mock broker.
*/
RD_EXPORT void rd_kafka_mock_clear_requests(rd_kafka_mock_cluster_t *mcluster);
/**@}*/
#ifdef __cplusplus
}
#endif
#endif /* _RDKAFKA_MOCK_H_ */

3771
json/rdkafkacpp.h Normal file

File diff suppressed because it is too large Load Diff

2452
json/save2json.cpp Normal file

File diff suppressed because it is too large Load Diff

345
json/save2json.h Normal file
View File

@@ -0,0 +1,345 @@
/**
* @file: $RCSfile: save2json.h,v $
* @brief: $IEC 61850 Protocol
*
* @version: $Revision: 1.5 $
* @date: $Date: 2018/12/23 12:39:52 $
* @author: $Author: lizhongming $
* @state: $State: Exp $
*
* @latest: $Id: save2json.h,v 1.5 2018/12/23 12:39:52 lizhongming Exp $
*
*/
#ifndef SAVE2DB_8ue3hy0923r_H
#define SAVE2DB_8ue3hy0923r_H
#ifdef __cplusplus
extern "C" {
#endif
extern int g_front_seg_index;
#ifdef __cplusplus
}
#endif
#ifdef __cplusplus
#include <string>
#include <vector>
#include <map>
#include <list>
#include <QThread>
//lnk20250106
#include "../include/rocketmq/SimpleProducer.h"
#include <QTcpServer>
#include <QTcpSocket>
#include <QMutex>
#include <QMutexLocker>
#include <QDebug>
#include <QTimer>
#include <QCoreApplication>
#include <QStringList>
#include <iostream>
extern int G_TEST_NUM;
extern void ledger(const char* terminal_id = NULL,QIODevice* outputDevice = NULL);
extern int TEST_PORT;
//////////////////////////////////////////////////////////////////////////////
//struct json_pair_info
//{
// string topic; //<Topic name="HISDATA" desc="<22><>ʷ<EFBFBD><CAB7><EFBFBD><EFBFBD>"> "RTDATA" ʵʱ<CAB5><CAB1><EFBFBD><EFBFBD> "RTDATASOE"ʵʱSOE<4F>¼<EFBFBD> <20><>
// string data_type; //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ͣ<EFBFBD>01/04:<3A><>̬/<2F>ٲ<EFBFBD><D9B2><EFBFBD>̬<EFBFBD><CCAC>02/05:<3A><><EFBFBD><EFBFBD>/<2F>ٲ<EFBFBD><D9B2><EFBFBD><EFBFBD>䣬03/06:<3A><>̬/<2F>ٲ<EFBFBD><D9B2><EFBFBD>̬
// string item; //<Item name="V" desc="<22><>ѹ" type="4" > <20><>"I" "PQ" <20><>
// string sequence; //"A" <20><> "B" <20><> "C" <20><> "T"
// string name; //json<6F><6E>key
// int type; //6-ֵ<><D6B5><EFBFBD><EFBFBD><EFBFBD><EFBFBD>9-ʵʱSOE<4F>¼<EFBFBD>
// string mms_ref; //mms<6D><73>ַ<EFBFBD>ַ<EFBFBD><D6B7><EFBFBD>
// float coeff; //Coefficient:<3A><><EFBFBD><EFBFBD>ϵ<EFBFBD><CFB5>
// unsigned short PltFlag; //0xffff
//};
/////////////////////////////////////////////////////////////////////////////
class KafkaSendThread : public QThread
{
// Q_OBJECT
//public:
protected:
void run();
};
//WW 2023-08-22 <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ݿ<EFBFBD><DDBF>̺߳<DFB3>WebSocket<65>߳<EFBFBD>
class SQLExcuteThread : public QThread
{
protected:
void run();
};
class WebSocketThread : public QThread
{
protected:
void run();
};
//lnk20241029
class WebhttpThread : public QThread
{
protected:
void run();
};
class httpThread : public QThread
{
protected:
void run();
};
//lnk20241202
/*class mqtestThread : public QThread
{
protected:
void run();
};*/
//lnk20250106
//ʹ<><CAB9>telnet 127.0.0.1 12345<34><35><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
class Worker : public QObject
{
Q_OBJECT
public:
Worker(QObject *parent = NULL) : QObject(parent), server(NULL), TEST_NUM(G_TEST_NUM) {}
~Worker() {
if (server) {
server->close();
delete server;
}
}
public slots:
void startServer() {
server = new QTcpServer();
connect(server, SIGNAL(newConnection()), this, SLOT(onNewConnection()));
if (!server->listen(QHostAddress::Any, TEST_PORT)) {
std::cout << "Server failed to start!" << std::endl;
qDebug() << "Server failed to start!";
delete server;
server = NULL;
emit serverError();
return;
} else {
std::cout << "Server is running on port " << TEST_PORT << std::endl;
qDebug() << QString("Server is running on port %1").arg(TEST_PORT);
}
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʱ<EFBFBD><CAB1>
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(doPeriodicTask()));
timer->start(60000); // ÿ60<36><EFBFBD><EBB4A5>һ<EFBFBD><D2BB>
std::cout << "Timer started, event loop running in thread: " << QThread::currentThreadId() << std::endl;
qDebug() << "Timer started, event loop running in thread:" << QThread::currentThreadId();
}
void setTestNum(int num) {
QMutexLocker locker(&mutex);
TEST_NUM = num;
}
private slots:
void doPeriodicTask() {
QMutexLocker locker(&mutex);
std::cout << "Executing TEST_NUM is " << TEST_NUM << std::endl;
qDebug() << "doPeriodicTask() called. TEST_NUM = " << TEST_NUM;
if (TEST_NUM != 0) {
qDebug() << "Executing rocketmq_test_300()";
std::cout << "Executing rocketmq_test_300()\n";
rocketmq_test_300(TEST_NUM, g_front_seg_index);
}
}
void onNewConnection() {
if (!server) return;
QTcpSocket *clientSocket = server->nextPendingConnection();
qDebug() << "New connection established!";
std::cout << "New connection established!\n";
connect(clientSocket, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
// <20><><EFBFBD>ͻ<EFBFBD><CDBB>˷<EFBFBD><CBB7><EFBFBD><EFBFBD><EFBFBD>ʾ<EFBFBD><CABE>
if (clientSocket) {
std::cout << "clientSocket OK\n";
clientSocket->write("Welcome to the test shell. Type 'help' for available commands.\n> ");
clientSocket->flush(); // ȷ<><C8B7><EFBFBD><EFBFBD>Ϣ<EFBFBD><CFA2><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
}
}
void onReadyRead() {
QTcpSocket *clientSocket = qobject_cast<QTcpSocket *>(sender());
std::cout << "onReadyRead\n";
if (!clientSocket) {
std::cout << "Invalid socket\n";
return;
}
std::cout << "read all\n";
QByteArray data = clientSocket->readAll();
QString command = QString::fromUtf8(data).trimmed(); // <20><>ȡ<EFBFBD><C8A1><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ȥ<EEB2A2><C8A5>ǰ<EFBFBD><C7B0><EFBFBD>ո<EFBFBD>
qDebug() << "Received command:" << command;
std::cout << "Received command: " << command.toStdString() << "\n";
// <20><><EFBFBD>ͻ<EFBFBD><CDBB>˷<EFBFBD><CBB7>͡<EFBFBD>ָ<EFBFBD><D6B8><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EBA1B1><EFBFBD><EFBFBD>
clientSocket->write("Received command\n> ");
clientSocket->flush();
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʾ<EFBFBD><CABE>ʾ<EFBFBD><CABE>
clientSocket->write("test_shell> ");
clientSocket->flush(); // ȷ<><C8B7><EFBFBD><EFBFBD>ʾ<EFBFBD><CABE><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʾ
// <20><><EFBFBD><EFBFBD> TEST_NUM
if (command.startsWith("TEST_NUM=")) {
bool ok;
int num = command.mid(9).toInt(&ok); // <20><>ȡ<EFBFBD>Ⱥź<C8BA><C5BA><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ֲ<EFBFBD><D6B2><EFBFBD>
if (ok) {
setTestNum(num); // <20><><EFBFBD><EFBFBD> TEST_NUM
clientSocket->write("TEST_NUM updated\n> ");
std::cout << "TEST_NUM updated\n";
} else {
clientSocket->write("Invalid number\n> ");
std::cout << "Invalid number\n";
}
}
// <20><><EFBFBD><EFBFBD> rc <20><><EFBFBD><EFBFBD>
else if (command.startsWith("rc")) {
qDebug() << "Executing rocketmq_test_rc()";
std::cout << "Executing rocketmq_test_rc()\n";
rocketmq_test_rc(); // <20><><EFBFBD><EFBFBD> rc <20><><EFBFBD><EFBFBD>
clientSocket->write("Executed rocketmq_test_rc\n> ");
}
// <20><><EFBFBD><EFBFBD> rt <20><><EFBFBD><EFBFBD>
else if (command.startsWith("rt")) {
qDebug() << "Executing rocketmq_test_rt()";
std::cout << "Executing rocketmq_test_rt()\n";
rocketmq_test_rt(); // <20><><EFBFBD><EFBFBD> rt <20><><EFBFBD><EFBFBD>
clientSocket->write("Executed rocketmq_test_rt\n> ");
}
// <20><><EFBFBD><EFBFBD> ud <20><><EFBFBD><EFBFBD>
else if (command.startsWith("ud")) {
qDebug() << "Executing rocketmq_test_ud()";
std::cout << "Executing rocketmq_test_ud()\n";
rocketmq_test_ud(); // <20><><EFBFBD><EFBFBD> ud <20><><EFBFBD><EFBFBD>
clientSocket->write("Executed rocketmq_test_ud\n> ");
}
else if (command.startsWith("set")) {
qDebug() << "Executing rocketmq_test_set()";
std::cout << "Executing rocketmq_test_set()\n";
rocketmq_test_set(); // <20><><EFBFBD><EFBFBD> set <20><><EFBFBD><EFBFBD>
clientSocket->write("Executed rocketmq_test_set\n> ");
}
else if (command.startsWith("ledger")) {
qDebug() << "Executing ledger()";
std::cout << "Executing ledger()\n";
// <20><>ȡ<EFBFBD><C8A1><EFBFBD><EFBFBD>
QStringList parts = command.split(" "); // <20><><EFBFBD>ݿո<DDBF><D5B8>ָ<EFBFBD><D6B8><EFBFBD><EFBFBD><EFBFBD>
if (parts.size() > 1) { // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>а<EFBFBD><D0B0><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> id<69>ţ<EFBFBD>
QString terminalId = parts[1];
std::cout << "Calling ledger with terminal_id: " << terminalId.toStdString() << std::endl;
// <20>޸ģ<DEB8><C4A3><EFBFBD><EFBFBD><EFBFBD> ledger ʱ<><CAB1><EFBFBD><EFBFBD> clientSocket <20><>Ϊ<EFBFBD><CEAA><EFBFBD><EFBFBD><EFBFBD>
ledger(terminalId.toStdString().c_str(), clientSocket); // <20><><EFBFBD>ô<EFBFBD><C3B4><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> ledger<65><72><EFBFBD><EFBFBD><EFBFBD><EFBFBD> clientSocket
clientSocket->write("Executed ledger with terminal_id\n> ");
} else {
std::cout << "Calling ledger without parameters\n";
// <20>޸ģ<DEB8><C4A3><EFBFBD><EFBFBD><EFBFBD><EFBFBD>޲<EFBFBD><DEB2><EFBFBD><EFBFBD><EFBFBD> ledger<65><72><EFBFBD><EFBFBD><EFBFBD><EFBFBD> clientSocket
ledger(NULL, clientSocket); // <20><><EFBFBD><EFBFBD><EFBFBD>޲<EFBFBD><DEB2><EFBFBD><EFBFBD><EFBFBD> ledger<65><72><EFBFBD><EFBFBD><EFBFBD><EFBFBD> clientSocket
clientSocket->write("Executed ledger without parameters\n> ");
}
}
// <20><><EFBFBD><EFBFBD>δ֪<CEB4><D6AA><EFBFBD><EFBFBD>
else {
clientSocket->write("Unknown command\n> ");
}
clientSocket->flush();
}
signals:
void serverError();
private:
QTcpServer *server;
QTimer *timer;
int TEST_NUM;
QMutex mutex;
};
//lnk20241213
class mqconsumerThread : public QThread
{
protected:
void run();
};
class OnTimerThread : public QThread//<2F><>ʱ<EFBFBD>߳<EFBFBD>
{
protected:
void run();
};
//WW 2023-08-22 end
/////////////////////////////////////////////////////////////////////////
extern "C" {
#endif
//lnk20250106<30><36><EFBFBD><EFBFBD>̨<EFBFBD>˽ṹ
typedef struct terminal terminal;
typedef struct monitor monitor;
struct monitor // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>̨<EFBFBD><CCA8>
{
char monitor_id[64];
char terminal_code[64];
char monitor_name[64];
char logical_device_seq[64];
char voltage_level[64];
char terminal_connect[64];
char timestamp[64];
char status[255];
};
struct terminal // <20>ն<EFBFBD>̨<EFBFBD><CCA8>
{
char terminal_id[64];
char terminal_code[64];
char org_name[64];
char maint_name[64];
char station_name[64];
char tmnl_factory[64];
char tmnl_status[64];
char dev_type[64];
char dev_key[255];
char dev_series[255];
char addr_str[64];
char port[64];
char timestamp[64];
monitor line[10]; // <20><><EFBFBD><EFBFBD> 10 <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
};
#ifdef __cplusplus
}
#endif
/////////////////////////////////////////////////////////////////////////////
#endif //SAVE2DB_8ue3hy0923r_H