1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414 |
- #include <sys/time.h>
- #include <sys/timeb.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <sys/ioctl.h>
- #include <sys/socket.h>
- #include <sys/ipc.h>
- #include <sys/shm.h>
- #include <sys/shm.h>
- #include <sys/mman.h>
- #include <linux/wireless.h>
- #include <linux/sockios.h>
- #include <linux/socket.h>
- #include <arpa/inet.h>
- #include <netinet/in.h>
- #include <unistd.h>
- #include <stdarg.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <fcntl.h>
- #include <termios.h>
- #include <errno.h>
- #include <errno.h>
- #include <string.h>
- #include <time.h>
- #include <ctype.h>
- #include <ifaddrs.h>
- #include "libwebsockets.h"
- #include <lws_config.h>
- #include "hashmap.h"
- #include "SystemLogMessage.h"
- #include "ShareMemory.h"
- #include <pthread.h>
- #include "MessageHandler.h"
- #include "sqlite3.h"
- #if 0
- #define DEBUG_INFO(format, args...) StoreLogMsg("[%s:%d][%s][Info] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
- #define DEBUG_WARN(format, args...) StoreLogMsg("[%s:%d][%s][Warn] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
- #define DEBUG_ERROR(format, args...) StoreLogMsg("[%s:%d][%s][Error] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
- #endif
- #define Debug
- //#define ARRAY_SIZE(A) (sizeof(A) / sizeof(A[0]))
- #define PASS 1
- #define FAIL -1
- typedef enum boolean { FALSE, TRUE } BOOL;
- struct lws *wsi_client;
- struct lws_context *context;
- static int sendbuffer = 0;
- extern int server_sign;
- //extern int server_pending;
- //extern struct OCPP16Data *ShmOCPP16Data;
- extern void CheckSystemValue(void);
- //extern int TransactionMessageAttemptsGet(void);
- extern int FirstHeartBeatResponse(void);
- extern void OCPP_get_TableAuthlocalAllData(void);
- pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
- pthread_mutex_t lock_sentData = PTHREAD_MUTEX_INITIALIZER;
- //struct json_object *parsed_json;
- //extern struct node Node;
- //==========================================
- // Function prototype
- //==========================================
- void trim(char *s);
- int mystrcmp(char *p1,char *p2);
- void substr(char *dest, const char* src, unsigned int start, unsigned int cnt);
- void getSubStr(char *dest, char* src, char *split, int idx);
- void split(char **arr, char *str, const char *del);
- int strpos(char *source, char *substr, int skip);
- int strposs(char *source, char *substr, int idx);
- char *random_uuid( char buf[37] );
- static int OCPP16Callback(struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len);
- char * strchr(const char *p, int ch);
- void* processTransactionQueue(void* data);
- void ReceivedMessage(void *in, size_t len);
- struct StartTime
- {
- unsigned int connect;
- unsigned int bootNotification;
- }startTime;
- #if 0
- unsigned char *SendBuffer;
- int SendBufLen=(1024*4);//(1024*3);
- #endif
- int SendBufLen=(1024*4);//(1024*3);
- unsigned char SendBuffer[1024*4]={0};
- static int ConnectionEstablished=0;
- static int TransactionQueueInterval = 10;//3; // TransactionMessageAttempts
- static int TransactionQueueNum = 0;
- int defaultWaitingTime = 10; //10 second
- extern int BootNotificationInterval;
- //char guid[37];
- //map_t hashMap;
- //data_struct_t* mapItem; --- remove for temporally
- //data_struct_t mapItem[0]={0};
- sqlite3 *db;
- char *errMsg = NULL;
- static char *createsql = "CREATE TABLE IF NOT EXISTS log_buffer("
- "idx integer primary key,"
- "user_id text,"
- "cmd_sn text,"
- "charger_id text,"
- "gun_type text,"
- "gun_no text,"
- "rfid_no text,"
- "stime text,"
- "etime text,"
- "time_len text,"
- "s_soc text,"
- "e_soc text,"
- "stop_reason text,"
- "power text,"
- "meter_before text,"
- "meter_after text,"
- "charge_price text,"
- "reserve text,"
- "surplus_before text,"
- "surplus_after text,"
- "service_price text,"
- "is_pay text,"
- "charge_strategy text,"
- "charge_parameter text,"
- "vin text,"
- "vehicle_no text,"
- "start_method text,"
- "card_type text,"
- "is_upload text,"
- "guid text UNIQUE,"
- "is_buf2OK text);";
- #if 0
- static char *createsChargingRecordsql = "CREATE TABLE IF NOT EXISTS ChargingRecord("
- "idx integer primary key,"
- "gun_type text,"
- "connectorId text,"
- "idTag text,"
- "transactionId text,"
- "stime text,"
- "etime text,"
- "time_len text,"
- "s_soc text,"
- "e_soc text,"
- "stop_reason text,"
- "power text,"
- "meter_before text,"
- "meter_after text,"
- "reservationId text,"
- "guid text UNIQUE);";
- //"is_buf2OK text);";
- #endif
- static char *sqlOcppAuthCache = "create table if not exists ocpp_auth_cache (idx integer primary key,"
- "idtag text UNIQUE,"
- "parent_idtag text,"
- "expir_date text,"
- "status text);";
- static char *sqlOcppAuthLocal = "create table if not exists ocpp_auth_local (idx integer primary key,"
- "idtag text UNIQUE,"
- "parent_idtag text,"
- "expir_date text,"
- "status text,"
- "version text);";
- #if 0
- static char *sqlInitialOcppAuthLocal = "insert or replace into ocpp_auth_local(idtag, parent_idtag, expir_date, status, version) values('PaHdImHiOnNG','none','2099-12-31T23:59:59.999Z','Accepted','0')";
- #endif
- int DiffTimeb(struct timeb ST, struct timeb ET)
- {
- //return milli-second
- unsigned int StartTime,StopTime;
- StartTime=(unsigned int)ST.time;
- StopTime=(unsigned int)ET.time;
- return (StopTime-StartTime)*1000+ET.millitm-ST.millitm;
- }
- //=================================
- // Common routine
- //=================================
- void trim(char *s)
- {
- int i=0, j, k, l=0;
- while((s[i]==' ')||(s[i]=='\t')||(s[i]=='\n'))
- i++;
- j = strlen(s)-1;
- while((s[j]==' ')||(s[j]=='\t')||(s[j]=='\n'))
- j--;
- if(i==0 && j==strlen(s)-1) { }
- else if(i==0) s[j+1] = '\0';
- else {
- for(k=i; k<=j; k++) s[l++] = s[k];
- s[l] = '\0';
- }
- }
- int mystrcmp(char *p1,char *p2)
- {
- while(*p1==*p2)
- {
- if(*p1=='\0' || *p2=='\0')
- break;
- p1++;
- p2++;
- }
- if(*p1=='\0' && *p2=='\0')
- return(PASS);
- else
- return(FAIL);
- }
- void substr(char *dest, const char* src, unsigned int start, unsigned int cnt)
- {
- strncpy(dest, src + start, cnt);
- dest[cnt] = 0;
- }
- void getSubStr(char *dest, char* src, char *split, int idx)
- {
- int start = (strposs(src,",",idx)+1);
- int cnt = (strposs(src,",",idx+1)-2)-(strposs(src,",",idx)+1);
- strncpy(dest, src + start, cnt);
- dest[cnt] = 0;
- }
- void split(char **arr, char *str, const char *del)
- {
- char *s = strtok(str, del);
- while(s != NULL)
- {
- *arr++ = s;
- s = strtok(NULL, del);
- }
- }
- int strpos(char *source, char *substr, int skip)
- {
- char stack[strlen(source)];
- strncpy(stack, source+skip, strlen(source)-skip);
- char *p = strstr(stack, substr);
- if (p)
- return p - stack+skip;
- return -1;
- }
- int strposs(char *source, char *substr, int idx)
- {
- char stack[strlen(source)];
- int result=0;
- int count=0;
- while(count<=idx)
- {
- memset(stack,0,sizeof stack);
- strncpy(stack, source+result, strlen(source)-result);
- int loc = strcspn(stack, substr);
- if(loc>0)
- result += (loc+1);
- else
- result = -1;
- count++;
- }
- return result;
- }
- char *random_uuid( char buf[37] )
- {
- const char *c = "89ab";
- char *p = buf;
- int n;
- for( n = 0; n < 16; ++n )
- {
- int b = rand()%255;
- switch( n )
- {
- case 6:
- sprintf(p, "4%x", b%15 );
- break;
- case 8:
- sprintf(p, "%c%x", c[rand()%strlen(c)], b%15 );
- break;
- default:
- sprintf(p, "%02x", b);
- break;
- }
- p += 2;
- switch( n )
- {
- case 3:
- case 5:
- case 7:
- case 9:
- *p++ = '-';
- break;
- }
- }
- *p = 0;
- return buf;
- }
- //==========================================
- // Web socket tranceive routine
- //==========================================
- int SendData(struct lws *wsi)
- {
- int n;
- int len;
- unsigned char out[LWS_SEND_BUFFER_PRE_PADDING + 4096 + LWS_SEND_BUFFER_POST_PADDING] = {0};
- len = strlen((char *)SendBuffer);
- if(len == 0)
- return 0;
- memcpy (out + LWS_SEND_BUFFER_PRE_PADDING, SendBuffer, len );
- DEBUG_INFO("out + LWS_SEND_BUFFER_PRE_PADDING = %s\n", out + LWS_SEND_BUFFER_PRE_PADDING);
- n = lws_write(wsi, out + LWS_SEND_BUFFER_PRE_PADDING, len, LWS_WRITE_TEXT);
- memset(SendBuffer, 0, len);
- return n;
- }
- static int OCPP16Callback(struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len)
- {
- switch (reason)
- {
- case LWS_CALLBACK_PROTOCOL_INIT:
- #ifdef SystemLogMessage
- DEBUG_INFO("LWS_CALLBACK_PROTOCOL_INIT\n");
- #endif
- break;
- case LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH:
- #ifdef SystemLogMessage
- DEBUG_INFO("LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH\n");
- #endif
- break;
- case LWS_CALLBACK_CLOSED_CLIENT_HTTP:
- #ifdef SystemLogMessage
- DEBUG_INFO("LWS_CALLBACK_CLOSED_CLIENT_HTTP\n");
- #endif
- break;
- case LWS_CALLBACK_WSI_DESTROY:
- #ifdef SystemLogMessage
- DEBUG_INFO("LWS_CALLBACK_WSI_DESTROY\n");
- #endif
- server_sign = FALSE;
- break;
- case LWS_CALLBACK_LOCK_POLL:
- #ifdef SystemLogMessage
- //DEBUG_INFO("LWS_CALLBACK_LOCK_POLL\n");
- #endif
- break;
- case LWS_CALLBACK_ADD_POLL_FD:
- #ifdef SystemLogMessage
- DEBUG_INFO("LWS_CALLBACK_ADD_POLL_FD\n");
- #endif
- break;
- case LWS_CALLBACK_DEL_POLL_FD:
- #ifdef SystemLogMessage
- DEBUG_INFO("LWS_CALLBACK_DEL_POLL_FD\n");
- #endif
- break;
- case LWS_CALLBACK_UNLOCK_POLL:
- #ifdef SystemLogMessage
- //DEBUG_INFO("LWS_CALLBACK_UNLOCK_POLL\n");
- #endif
- break;
- case LWS_CALLBACK_CHANGE_MODE_POLL_FD:
- #ifdef SystemLogMessage
- //DEBUG_INFO("LWS_CALLBACK_CHANGE_MODE_POLL_FD\n");
- #endif
- break;
- case LWS_CALLBACK_WSI_CREATE:
- #ifdef SystemLogMessage
- DEBUG_INFO("LWS_CALLBACK_WSI_CREATE\n");
- #endif
- break;
- case LWS_CALLBACK_GET_THREAD_ID:
- //#ifdef SystemLogMessage
- //DEBUG_INFO("LWS_CALLBACK_GET_THREAD_ID\n");
- //#endif
- break;
- case LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER:
- #ifdef SystemLogMessage
- DEBUG_INFO("LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER\n");
- #endif
- break;
- case LWS_CALLBACK_CLIENT_ESTABLISHED://3
- #ifdef SystemLogMessage
- DEBUG_INFO("LWS_CALLBACK_CLIENT_ESTABLISHED\n");
- #endif
- //connected
- ConnectionEstablished=1;
- break;
- case LWS_CALLBACK_CLIENT_CONNECTION_ERROR://1
- #ifdef Debug
- DEBUG_ERROR("LWS_CALLBACK_CLIENT_CONNECTION_ERROR:%s\n",in);
- #endif
- #ifdef SystemLogMessage
- DEBUG_ERROR("LWS_CALLBACK_CLIENT_CONNECTION_ERROR\n");
- #endif
- //disconnected
- ConnectionEstablished=0;
- break;
- case LWS_CALLBACK_CLOSED://4
- #ifdef SystemLogMessage
- DEBUG_INFO("LWS_CALLBACK_CLOSED\n");
- ConnectionEstablished=0;
- #endif
- //disconnected
- break;
- case LWS_CALLBACK_CLIENT_WRITEABLE://10
- //if(need to send message and its relevant data already store into SendBuffer)
- #ifdef SystemLogMessage
- DEBUG_INFO("LWS_CALLBACK_CLIENT_WRITEABLE\n");
- #endif
- SendData(wsi);
- break;
- case LWS_CALLBACK_CLIENT_RECEIVE://8
- ((char *)in)[len] = '\0';
- #ifdef SystemLogMessage
- DEBUG_INFO("LWS_CALLBACK_CLIENT_RECEIVE, RX length: %d\n", (int)len);
- //DEBUG_INFO("Message: %s\n", (char *)in);
- #endif
- ReceivedMessage(in, len);
- break;
- default:
- #ifdef Debug
- DEBUG_INFO("OCPP16Callback:reason=%d\n", reason);
- #endif
- break;
- }
- return 0;
- }
- static struct lws_protocols protocols[] = {
- {
- "ocpp1.6",
- OCPP16Callback,
- 10240,
- 10240,
- },
- {
- "ocpp1.6",
- OCPP16Callback,
- 10240,
- 10240,
- },
- {
- NULL, NULL, 0 // End of list
- }
- };
- int ConnectWsServer()
- {
- int result = PASS;
- struct lws_context_creation_info ContextInfo;
- struct lws_client_connect_info ConnInfo;
- int use_ssl=0;
- //lws_set_log_level(LLL_PARSER | LLL_HEADER, NULL);
- if(context!=NULL)
- lws_context_destroy(context);
- memset(&ContextInfo, 0, sizeof(struct lws_context_creation_info));
- ContextInfo.port = CONTEXT_PORT_NO_LISTEN;
- ContextInfo.iface = NULL;
- ContextInfo.ssl_private_key_password = NULL;
- ContextInfo.ssl_cert_filepath = NULL;
- ContextInfo.ssl_private_key_filepath = NULL;
- ContextInfo.ssl_ca_filepath = "/root/cacert.pem";
- ContextInfo.ssl_cipher_list = NULL; //use default one
- ContextInfo.gid = -1;
- ContextInfo.uid = -1;
- if(use_ssl)
- ContextInfo.options |= LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT;
- ContextInfo.protocols = protocols;
- ContextInfo.timeout_secs = 9999;//30;
- //if(ping pong enabled)
- ContextInfo.ws_ping_pong_interval = 30;//0 for none, else interval in seconds
- context = lws_create_context(&ContextInfo);
- if (context == NULL)
- {
- #ifdef SystemLogMessage
- DEBUG_ERROR("lws_create_context NG");
- #endif
- result = FAIL;
- }
- memset(&ConnInfo,0,sizeof(struct lws_client_connect_info));
- // fill up below information
- ConnInfo.context = context;
- ConnInfo.address=(const char *)GetOcppServerURL();//"172.17.40.13";//"192.168.137.1";//"192.168.201.202";//"172.1.0.109";//"172.17.40.13";//"192.168.201.202";//"192.168.10.125";
- ConnInfo.port = GetOcppPort();//2012;//8080;
- ConnInfo.path=(const char *)GetOcppPath();//"/ocpp/RDTEST103";//"/ocpp/OCTT_1";//"/RDTEST103";//"/0591201511030003";//"/RDTEST103";
- ConnInfo.host=lws_canonical_hostname(context);
- ConnInfo.origin="origin";
- ConnInfo.protocol = protocols[1].name;
- ConnInfo.ietf_version_or_minus_one = -1;
- if(use_ssl)
- ConnInfo.ssl_connection = LCCSCF_USE_SSL | LCCSCF_ALLOW_SELFSIGNED | LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK;;
- wsi_client = lws_client_connect_via_info(&ConnInfo);
- if (!wsi_client)
- {
- #ifdef SystemLogMessage
- DEBUG_ERROR("lws_client_connect_via_info NG");
- #endif
- result = FAIL;
- }
- return result;
- }
- #if 0
- struct _node {
- char uuid[37];
- char data[2000];
- struct _node *next;//struct node *next;
- }node;
- typedef struct _node *pnode;
- struct _node staticNodeArray[100]={0};
- #endif
- //void createq();
- int showfront(char *uuid, char *data);
- int addq(char *uuid, char *data) ;
- int delq();
- int sentqueue();
- #if 0
- int storequeue();
- int readfiletoqueue();
- #endif
- void CheckTransactionPacket(char *uuid);
- int queue_operation(int type, char *frontUUID, char *frontData);
- #if 0
- pnode front, rear;
- void createq() {
- //front = rear = (pnode)malloc(sizeof(node)); --- remove temporally
- //front->next = rear->next = NULL;
- front = rear = NULL;
- }
- #endif
- int showfront(char *uuid, char *data) {
- FILE *fp;
- int result = FALSE; // 1: TRUE 0:FALSE
- char str[1200]={0};
- char sstr[50]={ 0 };//sstr[200]={ 0 };
- int c = 0;
- char *loc;
- char rmFileCmd[100]={0};
- struct stat stats;
- stat("../Storage/OCPP", &stats);
- // Check for directory existence
- if (S_ISDIR(stats.st_mode) == 1)
- {
- DEBUG_INFO("\n OCPP directory exist \n");
- }
- else
- {
- DEBUG_INFO("\n OCPP directory not exist, create dir \n");
- sprintf(rmFileCmd,"mkdir -p %s","../Storage/OCPP");
- system(rmFileCmd);
- }
- memset(&rmFileCmd, 0, sizeof rmFileCmd);
- if((access("../Storage/OCPP/TransactionRelatedQueue",F_OK))!=-1)
- {
- DEBUG_INFO("TransactionRelatedQueue exist.\n");
- }
- else
- {
- DEBUG_INFO("TransactionRelatedQueue not exist\n");
- FILE *log = fopen("../Storage/OCPP/TransactionRelatedQueue", "w+");
- if(log == NULL)
- {
- DEBUG_INFO("Can't Create File TransactionRelatedQueue \n");
- return 0;
- }
- else
- {
- fclose(log);
- }
- }
- //opening file for reading
- fp = fopen("../Storage/OCPP/TransactionRelatedQueue" , "r");
- if(fp == NULL) {
- DEBUG_INFO("Error opening TransactionRelatedQueue file");
- return FALSE;
- }
- printf("test\n");
- if( fgets (str, 1200, fp)!=NULL ) {
- /* writing content to stdout */
- if (str[0] == '\n')
- {
- DEBUG_INFO("It is a blank line");
- fclose(fp);
- memset(&rmFileCmd, 0, sizeof rmFileCmd);
- sprintf(rmFileCmd,"rm -f %s","../Storage/OCPP/TransactionRelatedQueue");
- system(rmFileCmd);
- result = FALSE;
- return result;
- }
- else
- {
- puts(str);
- /*********************uuid***************/
- loc = strstr(str, "\"");
- memset(sstr ,0, sizeof(sstr) );
- c = 0;
- while (loc[1+c] != '\"')
- {
- sstr[c] = loc[1+c];
- c++;
- }
- sstr[c] = '\0';
- DEBUG_INFO("\n uuid:%s", sstr);
- DEBUG_INFO("\n data:%s", str);
- strcpy(uuid,sstr);
- strcpy(data,str);
- result = TRUE;
- }
- //return 1;
- }
- else
- {
- DEBUG_INFO("queue is null\n");
- strcpy(uuid,"");
- strcpy(data,"");
- result = FALSE;
- //return 0;
- }
- fclose(fp);
- return result;
- #if 0
- pnode p;
- p = front;
- if(p)
- {
- //printf("姓å? %s ?»è©± %s\n", p->name, p->phone);
- printf("\n uuid:%s", p->uuid);
- printf("\n data:%s", p->data);
- strcpy(uuid,p->uuid);
- strcpy(data,p->data);
- return 1;
- }
- else
- {
- printf("queue is null\n");
- strcpy(uuid,"");
- strcpy(data,"");
- return 0;
- }
- #endif
- }
- int addq(char *uuid, char *data) {
- FILE *outfile;
- char rmFileCmd[100]={0};
- struct stat stats;
- stat("../Storage/OCPP", &stats);
- DEBUG_INFO("addq\n");
- // Check for directory existence
- if (S_ISDIR(stats.st_mode) == 1)
- {
- DEBUG_INFO("\n OCPP directory exist \n");
- }
- else
- {
- DEBUG_INFO("\n OCPP directory not exist, create dir \n");
- sprintf(rmFileCmd,"mkdir -p %s","../Storage/OCPP");
- system(rmFileCmd);
- }
- memset(&rmFileCmd, 0, sizeof rmFileCmd);
- if((access("../Storage/OCPP/TransactionRelatedQueue",F_OK))!=-1)
- {
- DEBUG_INFO("TransactionRelatedQueue exist.\n");
- }
- else
- {
- DEBUG_INFO("TransactionRelatedQueue not exist\n");
- FILE *log = fopen("../Storage/OCPP/TransactionRelatedQueue", "w+");
- if(log == NULL)
- {
- DEBUG_INFO("Can't Create File TransactionRelatedQueue \n");
- return 0;
- }
- else
- {
- fclose(log);
- }
- }
- // open file for writing
- outfile = fopen ("../Storage/OCPP/TransactionRelatedQueue", "a");
- DEBUG_INFO("data=%s\n",data);
- fputs(data, outfile);
- fputs("\n", outfile);
- fclose (outfile);
- TransactionQueueNum = TransactionQueueNum + 1;
- return 0;
- #if 0
- //pnode p = (pnode )malloc(sizeof(node)); --- remove temporally
- int nodeCurrentFreeIndex =0;
- for (int i = 0; i < 100; i++) // Worst case 100+1
- if (staticNodeArray[i].uuid[0] == 0) // Worst case 100
- nodeCurrentFreeIndex = i;
- pnode p = &staticNodeArray[nodeCurrentFreeIndex];
- memset(p, 0, sizeof(node));
- if(p)
- {
- strcpy(p->uuid, uuid);
- strcpy(p->data, data);
- //printf("請輸?¥å???");
- //scanf("%s", p->name);
- //printf("請輸?¥é›»è©?");
- //scanf("%s", p->phone);
- p->next = NULL;
- if(rear)
- {
- rear->next = p;
- rear = p;
- }
- else
- {
- front = rear = p;
- }
- }
- else
- {
- printf("?¡æ??–å?記憶體空?“新增è??™\n");
- }
- #endif
- }
- int delq() {
- char tempfile[] = "../Storage/OCPP/temp.json";
- FILE *infile;
- FILE *outfile;
- int resultRename=0;
- char filename[60]={0};
- char rmFileCmd[100]={0};
- struct stat stats;
- stat("../Storage/OCPP", &stats);
- // Check for directory existence
- if (S_ISDIR(stats.st_mode) == 1)
- {
- DEBUG_INFO("\n OCPP directory exist \n");
- }
- else
- {
- DEBUG_INFO("\n OCPP directory not exist, create dir \n");
- sprintf(rmFileCmd,"mkdir -p %s","../Storage/OCPP");
- system(rmFileCmd);
- }
- memset(&rmFileCmd, 0, sizeof rmFileCmd);
- if((access("../Storage/OCPP/TransactionRelatedQueue",F_OK))!=-1)
- {
- DEBUG_INFO("TransactionRelatedQueue exist.\n");
- }
- else
- {
- DEBUG_INFO("TransactionRelatedQueue not exist\n");
- FILE *log = fopen("../Storage/OCPP/TransactionRelatedQueue", "w+");
- if(log == NULL)
- {
- DEBUG_INFO("log is NULL\n");
- return 0;
- }
- else
- {
- fclose(log);
- }
- }
- // open file for writing
- strcpy(filename, "../Storage/OCPP/TransactionRelatedQueue");
- infile = fopen ("../Storage/OCPP/TransactionRelatedQueue", "r");
- outfile = fopen (tempfile, "w");
- //DEBUG_INFO("feof(infile) =%d\n",feof(infile));
- int c;
- c = fgetc(infile);
- //printf("file c:%d\n",c);
- rewind(infile);
- if(c == EOF)
- {
- DEBUG_INFO("TransactionRelatedQueue is NULL\n");
- fclose(infile);
- fclose(outfile);
- sprintf(rmFileCmd,"rm -f %s",tempfile);
- system(rmFileCmd);
- }
- else
- {
- char buf[1200]={0};
- int i = 0;
- //DEBUG_INFO("Orignal File is not NULL\n");
- while (fgets(buf, sizeof(buf), infile) != NULL)
- {
- //printf("Orignal File get strings \n");
- buf[strlen(buf) - 1] = '\0'; // eat the newline fgets() stores
- if(i==0)
- {
- TransactionQueueNum = TransactionQueueNum - 1;
- }
- if(i != 0)
- fprintf(outfile,"%s\n", buf);
- i = i + 1;
- }
- fclose(infile);
- fclose(outfile);
- sprintf(rmFileCmd,"rm -f %s",filename);
- system(rmFileCmd);
- resultRename = rename(tempfile, filename);
- if(resultRename == 0)
- {
- DEBUG_INFO("TransactionRelatedQueue file renamed successfully");
- }
- else
- {
- DEBUG_INFO("Error: unable to rename the TransactionRelatedQueue file");
- }
- }
- return 0;
- #if 0
- pnode p;
- if(front)
- {
- p = front;
- if(front->next)
- front = front->next;
- else
- front = rear = NULL;
- printf("delete uuid: %s data: %s\n", p->uuid, p->data);
- //free(p); --- remove temporally
- //new
- memset(p, 0, sizeof(node));
- p=NULL;
- }
- else
- {
- printf("queue is Empty\n");
- printf("\n delete: queue is null");
- }
- return 0;
- #endif
- }
- int showqueue() {
- char rmFileCmd[100]={0};
- struct stat stats;
- stat("../Storage/OCPP", &stats);
- // Check for directory existence
- if (S_ISDIR(stats.st_mode) == 1)
- {
- DEBUG_INFO("\n OCPP directory exist \n");
- }
- else
- {
- DEBUG_INFO("\n OCPP directory not exist, create dir \n");
- sprintf(rmFileCmd,"mkdir -p %s","../Storage/OCPP");
- system(rmFileCmd);
- }
- memset(&rmFileCmd, 0, sizeof rmFileCmd);
- if((access("../Storage/OCPP/TransactionRelatedQueue",F_OK))!=-1)
- {
- DEBUG_INFO("TransactionRelatedQueue exist.\n");
- }
- else
- {
- DEBUG_INFO("TransactionRelatedQueue not exist\n");
- FILE *log = fopen("../Storage/OCPP/TransactionRelatedQueue", "w+");
- if(log == NULL)
- {
- DEBUG_INFO("log is NULL\n");
- return 0;
- }
- else
- {
- fclose(log);
- }
- }
- FILE *fp = fopen("../Storage/OCPP/TransactionRelatedQueue", "r");
- char line[1200]={0};
- // check if file exist (and you can open it) or not
- if (fp == NULL) {
- DEBUG_INFO("can open file TransactionRelatedQueue!");
- return 0;
- }
- while(fgets(line, sizeof line, fp) != NULL) {
- DEBUG_INFO("%s\n", line);
- }
- fclose(fp);
- return 0;
- #if 0
- pnode p;
- p = front;
- while(p)
- {
- printf("uuid: %s data: %s\n", p->uuid, p->data);
- p = p->next;
- }
- return 0;
- #endif
- }
- int sentqueue()
- {
- FILE *fp;
- int result = FALSE; // 1: TRUE 0:FALSE
- char str[1200]={0};
- char rmFileCmd[100]={0};
- struct stat stats;
- DEBUG_INFO("sentqueue\n");
- stat("../Storage/OCPP", &stats);
- // Check for directory existence
- if(S_ISDIR(stats.st_mode) == 1)
- {
- DEBUG_INFO("\n OCPP directory exist \n");
- }
- else
- {
- DEBUG_INFO("\n OCPP directory not exist, create dir \n");
- sprintf(rmFileCmd,"mkdir -p %s","../Storage/OCPP");
- system(rmFileCmd);
- }
- memset(&rmFileCmd, 0, sizeof rmFileCmd);
- // opening file for reading
- fp = fopen("../Storage/OCPP/TransactionRelatedQueue" , "r");
- if(fp == NULL) {
- DEBUG_INFO("Error opening file");
- return FALSE;
- }
- if( fgets (str, 1200, fp)!=NULL ) {
- //writing content to stdout
- //puts(str);
- DEBUG_INFO("\n uuid:%s", "");
- DEBUG_INFO("\n data:%s", str);
- LWS_Send(str);
- result = TRUE;
- //return 1;
- }
- else
- {
- DEBUG_INFO("queue is null\n");
- result = FALSE;
- //return 0;
- }
- fclose(fp);
- DEBUG_INFO("sentqueue end\n");
- return result;
- #if 0
- pnode p;
- p = front;
- printf("sentqueue\n");
- while(p)
- {
- printf("uuid: %s data: %s\n", p->uuid, p->data);
- LWS_Send(p->data);
- p = p->next;
- }
- printf("sentqueue end\n");
- return 0;
- #endif
- }
- #if 0
- int storequeue(){
- //write queue to flash
- unsigned int i,Chk;
- unsigned char *ptr = NULL;
- int fd,wrd;
- // Save factory default setting value to flash backup setting block
- fd = open("./Storage/OCPP/queue.txt", O_RDWR);
- if (fd < 0)
- {
- #ifdef SystemLogMessage
- DEBUG_ERROR("open ./Storage/OCPP/queue.txt NG");
- #endif
- //free(ptr);
- return 0;
- }
- wrd=write(fd, &front, sizeof(node));
- if(wrd!=(sizeof(node)))
- {
- #ifdef SystemLogMessage
- DEBUG_ERROR("write ./Storage/OCPP/queue.txt NG");
- #endif
- //free(ptr);
- return 0;
- }
- close(fd);
- close(wrd);
- return 0;
- }
- int readfiletoqueue(){
- FILE *infile;
- //pnode p = (pnode )malloc(sizeof(node));
- struct _node Pnode;
- memset(&Pnode, 0, sizeof(node));
- // Open person.dat for reading
- infile = fopen ("./Storage/OCPP/queue.txt", "r");
- if (infile == NULL)
- {
- fprintf(stderr, "\nError opening file\n");
- exit (1);
- }
- // read file contents till end of file
- while(fread(&Pnode, sizeof(node), 1, infile))
- printf ("uuid = %s name = %s\n", Pnode.uuid,
- Pnode.data);
- // close file
- fclose (infile);
- // free(p);
- return 0;
- }
- #endif
- //
- void* processTransactionQueue(void* data) {
- char frontUUID[100] ={0};
- char frontData[1200] ={0};
- int queueNotEmpty = 0;
- while(1)
- {
- if(FirstHeartBeatResponse() == 1)
- {
- memset(frontUUID, 0, sizeof(frontUUID));
- memset(frontData, 0, sizeof(frontData));
- queueNotEmpty = 0;
- queueNotEmpty = queue_operation(1,frontUUID, frontData);//showfront(frontUUID, frontData); ---> remove temporally
- //showfront();
- if(queueNotEmpty == 1)
- {
- DEBUG_INFO("processTransactionQueue queue is not empty!\n");
- sendbuffer = 1;
- }
- if(TransactionQueueNum != 0)
- {
- TransactionQueueInterval = 1;
- }
- else
- {
- TransactionQueueInterval = 10;
- }
- //TransactionQueueInterval = TransactionMessageAttemptsGet();
- sleep(TransactionQueueInterval); // sleep for 30 seconds
- }
- }
- pthread_exit(NULL); // ���}�l�����
- return 0;
- }
- void CheckTransactionPacket(char *uuid)
- {
- char frontUUID[100]={0};
- char frontData[1200]={0};
- int queueNotEmpty = 0;
- int cmpResult = 0;
- queue_operation(0,"","");//showqueue(); ---> remove temporally
- queueNotEmpty = queue_operation(1,frontUUID, frontData);//showfront(frontUUID, frontData); ---> remove temporally
- if(queueNotEmpty == 1)
- {
- cmpResult = strcmp(frontUUID, uuid);
- //cmpResult = strcmp(frontData, uuid);
- if (cmpResult == 0)
- {
- DEBUG_INFO("TransactionPacket Compare All right!\n");
- queue_operation(2,"","");//delq(); ---> remove temporally
- }
- }
- }
- /* type: 0 (showqueue ); type: 1(showfront); type: 2(delq) type: 3 (sentqueue) type: 4 (addq) type: 5(store queue to /Storage/OCPP/ )*/
- int queue_operation(int type, char *frontUUID, char *frontData)
- {
- pthread_mutex_unlock(&lock_sentData);
- pthread_mutex_lock(&lock_sentData);
- int result=0;
- if(type == 0) // show items in queue
- result = showqueue();
- else if(type == 1) // show first item
- result = showfront(frontUUID, frontData);
- else if(type == 2) // delete item
- result = delq();
- else if(type == 3) // sent items in queue
- result = sentqueue();
- else if(type == 4) // add items to the queue
- result = addq(frontUUID, frontData);
- pthread_mutex_unlock(&lock_sentData);
- return result;
- }
- char * strchr(const char *p, int ch)
- {
- char c;
- c = ch;
- for (;; ++p) {
- if (*p == c)
- return ((char *)p);
- if (*p == '\0')
- return (NULL);
- }
- /* NOTREACHED */
- return NULL;
- }
- int removeMessageSentFile(void)
- {
- char rmFileCmd[100]={0};
- struct stat stats;
- //
- stat("../Storage/OCPP", &stats);
- // Check for directory existence
- if (S_ISDIR(stats.st_mode) == 1)
- {
- DEBUG_INFO("\n OCPP directory exist \n");
- }
- else
- {
- DEBUG_INFO("\n directory not exist, create dir \n");
- sprintf(rmFileCmd,"mkdir -p %s","../Storage/OCPP");
- system(rmFileCmd);
- }
- memset(&rmFileCmd, 0, sizeof rmFileCmd);
- if((access("../Storage/OCPP/MessageSent",F_OK))!=-1)
- {
- DEBUG_INFO("MessageSent file exist.\n");
- sprintf(rmFileCmd,"rm -f %s","../Storage/OCPP/MessageSent");
- system(rmFileCmd);
- }
- memset(&rmFileCmd, 0, sizeof rmFileCmd);
- return 0;
- }
- #define SystemLogMessage
- //================================================
- // Main process
- //================================================
- int main(void)
- {
- pthread_t t;
- #ifdef SystemLogMessage
- DEBUG_INFO("Initialization...\n");
- #endif
- if(ProcessShareMemory()== FAIL)
- {
- return FAIL;
- }
- //Create Process: Resend Transaction
- pthread_create(&t, NULL, processTransactionQueue, NULL); //
- sqlite3_config(SQLITE_CONFIG_URI,1);
- if(sqlite3_open("file:/../Storage/OCPP/charger.db", &db))
- {
- #ifdef Debug
- DEBUG_INFO( "Can't open database: %s\n", sqlite3_errmsg(db));
- #endif
- sqlite3_close( db );
- exit(0);
- }
- else
- {
- #ifdef Debug
- DEBUG_INFO( "Opened database successfully\n");
- #endif
- }
- //Table log buffer
- int rc =sqlite3_exec(db, createsql, 0, 0, &errMsg);
- if (SQLITE_OK != rc)
- {
- #ifdef Debug
- DEBUG_INFO( "Create log buffer table error message: %s\n", errMsg);
- #endif
- return 0;
- }
- else
- {
- #ifdef Debug
- DEBUG_INFO( "Opened log buffer table successfully\n");
- #endif
- }
- //Table OcppAuthCache
- rc =sqlite3_exec(db, sqlOcppAuthCache, 0, 0, &errMsg);
- if (SQLITE_OK != rc)
- {
- #ifdef Debug
- DEBUG_INFO( "Create OcppAuthCache error message: %s\n", errMsg);
- #endif
- return 0;
- }
- else
- {
- #ifdef Debug
- DEBUG_INFO( "Opened OcppAuthCache table successfully\n");
- #endif
- }
- // Table OcppAuthLocal
- rc =sqlite3_exec(db, sqlOcppAuthLocal, 0, 0, &errMsg);
- if (SQLITE_OK != rc)
- {
- #ifdef Debug
- DEBUG_INFO( "Create Table OcppAuthLocal error %s\n",errMsg);
- #endif
- return 0;
- }
- else
- {
- #ifdef Debug
- DEBUG_INFO( "Opened OcppAuthLocal table successfully\n");
- #endif
- }
- initialConfigurationTable();
- removeMessageSentFile();
- //queryAllData();
- OCPP_get_TableAuthlocalAllData();
- for(;;)
- {
- while(ConnectionEstablished==0)
- {
- if((time((time_t*)NULL)-startTime.connect)>=60)
- {
- #ifdef Debug
- DEBUG_INFO("Execute ConnectWsServer\n");
- #endif
- ConnectWsServer();
- startTime.connect=time((time_t*)NULL);
- }
- lws_service(context, 10000);//timeout_ms
- }
- if(( (BootNotificationInterval != 0 && ((time((time_t*)NULL)-startTime.bootNotification)>=BootNotificationInterval) ) || ((time((time_t*)NULL)-startTime.bootNotification)>=defaultWaitingTime) ) && ((server_sign == FALSE)/*|| (server_pending == TRUE)*/))
- {
- //hashmapForMessageNew();
- sendBootNotificationRequest();
- startTime.bootNotification=time((time_t*)NULL);
- }
- if(server_sign == TRUE)
- {
- if(sendbuffer == 1)
- {
- queue_operation(3, "", "");//sentqueue(); ---> remove temporally
- sendbuffer = 0;
- //queue_operation(5,"", "");
- }
- // Check System Value
- CheckSystemValue();
- }
- lws_service(context, 100);//timeout_ms
- }
- pthread_join(t, NULL); // ���ݤl��������槹��
- //hashmapForMessageFree();
- return FAIL;
- }
|