浏览代码

2023-02-18 / Simon_Xue [DD360Tcc_V2.23]

Action:
1. [Add] Gun status into unkown status will soft reset.
2. [Add] Gun status into Fault when gun temperature is 255.
3. [Mod] Charging finish trasmit target current and voltage are zero.
4. [Mod] LCM parking pay information. (Parking fee support ten thousand.)
Simon Xue 2 年之前
父节点
当前提交
37a71decd6
共有 74 个文件被更改,包括 38880 次插入38663 次删除
  1. 196 196
      EVSE/Projects/DD360Tcci/Apps/CSU/Ethernet.c
  2. 939 939
      EVSE/Projects/DD360Tcci/Apps/CSU/OCPP.c
  3. 214 214
      EVSE/Projects/DD360Tcci/Apps/CSU/Primary.c
  4. 818 818
      EVSE/Projects/DD360Tcci/Apps/CSU/RFID.c
  5. 215 215
      EVSE/Projects/DD360Tcci/Apps/CSU/SelfTest.c
  6. 71 71
      EVSE/Projects/DD360Tcci/Apps/CSU/WatchDog.c
  7. 77 77
      EVSE/Projects/DD360Tcci/Apps/CSU/ZipFile.c
  8. 5256 5030
      EVSE/Projects/DD360Tcci/Apps/CSU/main.c
  9. 116 116
      EVSE/Projects/DD360Tcci/Apps/CSU/main.h
  10. 618 618
      EVSE/Projects/DD360Tcci/Apps/Config.h
  11. 1266 1266
      EVSE/Projects/DD360Tcci/Apps/DataBase/DataBase.c
  12. 37 37
      EVSE/Projects/DD360Tcci/Apps/DataBase/DataBase.h
  13. 628 628
      EVSE/Projects/DD360Tcci/Apps/Define/define.c
  14. 6549 6549
      EVSE/Projects/DD360Tcci/Apps/Define/define.h
  15. 124 124
      EVSE/Projects/DD360Tcci/Apps/Log/log.c
  16. 14 14
      EVSE/Projects/DD360Tcci/Apps/Log/log.h
  17. 251 251
      EVSE/Projects/DD360Tcci/Apps/ModuleChkSysTask/Module_ChkSysTask.c
  18. 63 63
      EVSE/Projects/DD360Tcci/Apps/ModuleChkSysTask/Module_ChkSysTask.h
  19. 3292 3271
      EVSE/Projects/DD360Tcci/Apps/ModuleDoComm/DoComm.c
  20. 358 358
      EVSE/Projects/DD360Tcci/Apps/ModuleDoComm/DoComm.h
  21. 918 918
      EVSE/Projects/DD360Tcci/Apps/ModuleEvComm/AbnormalCCS.c
  22. 251 251
      EVSE/Projects/DD360Tcci/Apps/ModuleEvComm/AbnormalCHA.c
  23. 420 420
      EVSE/Projects/DD360Tcci/Apps/ModuleEvComm/AbnormalGBT.c
  24. 292 292
      EVSE/Projects/DD360Tcci/Apps/ModuleEvComm/AbnormalState.c
  25. 205 205
      EVSE/Projects/DD360Tcci/Apps/ModuleEvComm/Ev_Comm.c
  26. 66 66
      EVSE/Projects/DD360Tcci/Apps/ModuleEvComm/Ev_Comm.h
  27. 776 776
      EVSE/Projects/DD360Tcci/Apps/ModuleEvComm/Module_EvRxComm.c
  28. 1380 1380
      EVSE/Projects/DD360Tcci/Apps/ModuleEvComm/Module_EvTxComm.c
  29. 422 422
      EVSE/Projects/DD360Tcci/Apps/ModuleEventLog/Module_EventLogging.c
  30. 492 492
      EVSE/Projects/DD360Tcci/Apps/ModuleInternalComm/AcPlug.c
  31. 284 284
      EVSE/Projects/DD360Tcci/Apps/ModuleInternalComm/FanBoard.c
  32. 315 315
      EVSE/Projects/DD360Tcci/Apps/ModuleInternalComm/LEDlight.c
  33. 126 126
      EVSE/Projects/DD360Tcci/Apps/ModuleInternalComm/Module_InternalComm.c
  34. 111 111
      EVSE/Projects/DD360Tcci/Apps/ModuleInternalComm/Module_InternalComm.h
  35. 2488 2488
      EVSE/Projects/DD360Tcci/Apps/ModuleInternalComm/Module_InternalCommOrg.c
  36. 1914 1913
      EVSE/Projects/DD360Tcci/Apps/ModuleInternalComm/RelayBoard.c
  37. 1188 1188
      EVSE/Projects/DD360Tcci/Apps/ModuleInternalComm/internalComm.c
  38. 251 251
      EVSE/Projects/DD360Tcci/Apps/ModuleInternalComm/internalComm.h
  39. 2061 2056
      EVSE/Projects/DD360Tcci/Apps/ModuleLcmCtrl/Module_LcmControl.c
  40. 367 367
      EVSE/Projects/DD360Tcci/Apps/ModuleLcmCtrl/Module_LcmControl.h
  41. 315 315
      EVSE/Projects/DD360Tcci/Apps/ModuleLcmCtrl/cbmp.c
  42. 54 54
      EVSE/Projects/DD360Tcci/Apps/ModuleLcmCtrl/cbmp.h
  43. 494 494
      EVSE/Projects/DD360Tcci/Apps/ModulePrimary/Module_PrimaryComm.c
  44. 35 35
      EVSE/Projects/DD360Tcci/Apps/ModulePrimary/Module_PrimaryComm.h
  45. 595 595
      EVSE/Projects/DD360Tcci/Apps/ModuleUpdateFW/Module_UpdateFW.c
  46. 10 10
      EVSE/Projects/DD360Tcci/Apps/Readme.md
  47. 10 10
      EVSE/Projects/DD360Tcci/Apps/Script/SearchIP.sh
  48. 2 2
      EVSE/Projects/DD360Tcci/Apps/Script/copy_from_d.sh
  49. 2 2
      EVSE/Projects/DD360Tcci/Apps/Script/copy_to_d.sh
  50. 187 187
      EVSE/Projects/DD360Tcci/Apps/Script/createDefine.sh
  51. 15 15
      EVSE/Projects/DD360Tcci/Apps/Script/init.sh
  52. 47 47
      EVSE/Projects/DD360Tcci/Apps/Script/kill.sh
  53. 23 23
      EVSE/Projects/DD360Tcci/Apps/Script/replaceOtherDD360Project.sh
  54. 194 194
      EVSE/Projects/DD360Tcci/Apps/SelectGun/SelectGun.c
  55. 112 112
      EVSE/Projects/DD360Tcci/Apps/SelectGun/SelectGun.h
  56. 1090 1175
      EVSE/Projects/DD360Tcci/Apps/ShareMemory/shmMem.c
  57. 72 72
      EVSE/Projects/DD360Tcci/Apps/ShareMemory/shmMem.h
  58. 107 60
      EVSE/Projects/DD360Tcci/Apps/common.c
  59. 15 13
      EVSE/Projects/DD360Tcci/Apps/common.h
  60. 二进制
      EVSE/Projects/DD360Tcci/Images/ramdisk.gz
  61. 二进制
      EVSE/Projects/DD360Tcci/output/Module_ChkSysTask
  62. 二进制
      EVSE/Projects/DD360Tcci/output/Module_DoComm
  63. 二进制
      EVSE/Projects/DD360Tcci/output/Module_EvComm
  64. 二进制
      EVSE/Projects/DD360Tcci/output/Module_EventLogging
  65. 二进制
      EVSE/Projects/DD360Tcci/output/Module_InternalComm
  66. 二进制
      EVSE/Projects/DD360Tcci/output/Module_LcmControl
  67. 二进制
      EVSE/Projects/DD360Tcci/output/Module_PrimaryComm
  68. 二进制
      EVSE/Projects/DD360Tcci/output/Module_UpdateFW
  69. 二进制
      EVSE/Projects/DD360Tcci/output/ReadCmdline
  70. 10 10
      EVSE/Projects/DD360Tcci/output/SearchIP.sh
  71. 15 15
      EVSE/Projects/DD360Tcci/output/init.sh
  72. 47 47
      EVSE/Projects/DD360Tcci/output/kill.sh
  73. 二进制
      EVSE/Projects/DD360Tcci/output/main
  74. 二进制
      EVSE/rootfs/root/Module_Firewall

+ 196 - 196
EVSE/Projects/DD360Tcci/Apps/CSU/Ethernet.c

@@ -1,196 +1,196 @@
-#include <stdio.h>      /*標準輸入輸出定義*/
-#include <stdlib.h>     /*標準函數庫定義*/
-#include <string.h>
-#include <stdint.h>
-
-#include "../Config.h"
-#include "../Log/log.h"
-#include "../Define/define.h"
-#include "../ShareMemory/shmMem.h"
-
-#include "../common.h"
-
-//------------------------------------------------------------------------------
-static void InitialDHCP(void)
-{
-    char tmpbuf[256] = {0};
-    struct SysConfigData *pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
-
-    system("pgrep -f \"udhcpc -i eth0\" | xargs kill");
-    sprintf(tmpbuf, "/sbin/udhcpc -i eth0 -x hostname:CSU3_%s -s /root/dhcp_script/eth0.script > /dev/null &",
-            pSysConfig->SystemId);
-
-    system(tmpbuf);
-}
-
-void GetMacAddress(void)
-{
-    uint8_t index = 0;
-    struct SysConfigData *pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
-
-    for (index = 0; index < 2; index++) {
-        int fd;
-        struct ifreq ifr;
-        char tarEth[5];
-        char Mac[18];
-
-        sprintf(tarEth, "eth%d", index);
-        fd = socket(AF_INET, SOCK_DGRAM, 0);
-
-        ifr.ifr_addr.sa_family = AF_INET;
-        strncpy(ifr.ifr_name, tarEth, IFNAMSIZ - 1);
-
-        ioctl(fd, SIOCGIFHWADDR, &ifr);
-        close(fd);
-
-        sprintf(Mac, "%.2x:%.2x:%.2x:%.2x:%.2x:%.2x",
-                ifr.ifr_hwaddr.sa_data[0],
-                ifr.ifr_hwaddr.sa_data[1],
-                ifr.ifr_hwaddr.sa_data[2],
-                ifr.ifr_hwaddr.sa_data[3],
-                ifr.ifr_hwaddr.sa_data[4],
-                ifr.ifr_hwaddr.sa_data[5]
-               );
-
-        if (index == 0) {
-            strcpy((char *) pSysConfig->Eth0Interface.EthMacAddress, Mac);
-        } else {
-            strcpy((char *) pSysConfig->Eth1Interface.EthMacAddress, Mac);
-        }
-    }
-}
-
-static int isRouteFail(void)
-{
-    int result = YES;
-    FILE *fp;
-    char buf[512];
-
-    fp = popen("route -n", "r");
-    if (fp != NULL) {
-        while (fgets(buf, sizeof(buf), fp) != NULL) {
-            if (strstr(buf, "eth0") != NULL) {
-                result = NO;
-            }
-        }
-    }
-    pclose(fp);
-
-    return result;
-}
-
-static int isReachableInternet(void)
-{
-    int result = FAIL;
-    int idx = 0;
-    FILE *fp;
-    char cmd[256] = {0};
-    char buf[512] = {0};
-    char tmp[512] = {0};
-    char *valid_Internet[2] = {"8.8.8.8", "180.76.76.76"};
-    struct SysConfigData *pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
-    struct AlarmCodeData *pAlarmCode = (struct AlarmCodeData *)GetShmAlarmCodeData();
-
-    strcpy(cmd, "ifconfig eth0");
-    fp = popen(cmd, "r");
-
-    if (fp != NULL) {
-        while (fgets(buf, sizeof(buf), fp) != NULL) {
-            if (strstr(buf, "inet addr:") > 0) {
-                sscanf(buf, "%*s%s", tmp);
-                substr(tmp, tmp, strspn(tmp, "addr:"), strlen(tmp) - strspn(tmp, "addr:"));
-
-                if (strcmp(tmp, (char *)pSysConfig->Eth0Interface.EthIpAddress) != EQUAL) {
-                    strcpy((char *) pSysConfig->Eth0Interface.EthIpAddress, tmp);
-                }
-            }
-        }
-    }
-
-    pclose(fp);
-
-    if (pAlarmCode->AlarmEvents.bits.DisconnectedFromDo == NORMAL) {
-        result = FAIL;
-    } else {
-        result = PASS;
-    }
-
-    return result;
-
-}
-
-void InitEthernet(void)
-{
-    char tmpbuf[256];
-    bool ethResult = false;
-    uint8_t cnt_pingDNS_Fail = 0;
-
-    struct SysConfigData *pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
-    struct SysInfoData *pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
-    struct InfoCodeData *pInfoCode = (struct InfoCodeData *)GetShmInfoCodeData();
-
-    system("ifconfig eth0 down");// eth0 down
-    system("ifconfig eth1 down");// eth1 down
-    sleep(2);
-
-    // /sbin/ifconfig eth0 192.168.1.10 netmask 255.255.255.0 down
-    system("echo 1 > /sys/class/gpio/gpio110/value");//reset PHY
-    sleep(2);
-
-    //Init Eth0 for internet
-    memset(tmpbuf, 0, 256);
-    sprintf(tmpbuf, "/sbin/ifconfig eth0 %s netmask %s up",
-            pSysConfig->Eth0Interface.EthIpAddress,
-            pSysConfig->Eth0Interface.EthSubmaskAddress);
-    //sprintf(tmpbuf,"/sbin/ifconfig eth0 192.168.100.10 netmask 255.255.255.0 up");
-    system(tmpbuf);
-    log_info("%s",tmpbuf);
-    memset(tmpbuf, 0, 256);
-    sprintf(tmpbuf, "route add default gw %s eth0 ",
-            pSysConfig->Eth0Interface.EthGatewayAddress);
-    //sprintf(tmpbuf,"route add default gw 192.168.100.1 eth0 ");
-    system(tmpbuf);
-    //system("ifconfig lo up");
-    //  /sbin/ifconfig eth0 192.168.1.10 netmask 255.255.255.0 up
-
-    //Init Eth1 for administrator tool
-    memset(tmpbuf, 0, 256);
-    sprintf(tmpbuf, "/sbin/ifconfig eth1 %s netmask %s up",
-            pSysConfig->Eth1Interface.EthIpAddress,
-            pSysConfig->Eth1Interface.EthSubmaskAddress);
-    log_info("%s",tmpbuf);
-    system(tmpbuf);
-
-    system("/sbin/ifconfig lo up");
-
-    //Run DHCP client if enabled
-    system("killall udhcpc");
-    system("rm -rf /etc/resolv.conf");
-    system("echo nameserver 8.8.8.8 > /etc/resolv.conf");       //Google DNS server
-    system("echo nameserver 180.76.76.76 > /etc/resolv.conf");  //Baidu DNS server
-    //system("/sbin/ifconfig eth0 down;/sbin/ifconfig eth0 up");
-
-    if (pSysConfig->Eth0Interface.EthDhcpClient == 0) {
-        sprintf(tmpbuf, "/sbin/udhcpc -i eth0 -x hostname:CSU3_%s -s /root/dhcp_script/eth0.script > /dev/null &",
-                pSysConfig->SystemId);
-        system(tmpbuf);
-    }
-
-    //Upgrade system id to /etc/hostname
-    sprintf(tmpbuf, "echo %s > /etc/hostname", pSysConfig->SystemId);
-    system(tmpbuf);
-
-    pid_t pid = fork();
-    if (pid == 0) {
-        //log_info("InitEthernet = %d", pid);
-
-        for (;;) {
-
-            isReachableInternet();
-            sleep(5);
-            continue;
-        }
-    }
-
-    log_info("Initial Ethernet OK");
-}
+#include <stdio.h>      /*標準輸入輸出定義*/
+#include <stdlib.h>     /*標準函數庫定義*/
+#include <string.h>
+#include <stdint.h>
+
+#include "../Config.h"
+#include "../Log/log.h"
+#include "../Define/define.h"
+#include "../ShareMemory/shmMem.h"
+
+#include "../common.h"
+
+//------------------------------------------------------------------------------
+static void InitialDHCP(void)
+{
+    char tmpbuf[256] = {0};
+    struct SysConfigData *pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
+
+    system("pgrep -f \"udhcpc -i eth0\" | xargs kill");
+    sprintf(tmpbuf, "/sbin/udhcpc -i eth0 -x hostname:CSU3_%s -s /root/dhcp_script/eth0.script > /dev/null &",
+            pSysConfig->SystemId);
+
+    system(tmpbuf);
+}
+
+void GetMacAddress(void)
+{
+    uint8_t index = 0;
+    struct SysConfigData *pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
+
+    for (index = 0; index < 2; index++) {
+        int fd;
+        struct ifreq ifr;
+        char tarEth[5];
+        char Mac[18];
+
+        sprintf(tarEth, "eth%d", index);
+        fd = socket(AF_INET, SOCK_DGRAM, 0);
+
+        ifr.ifr_addr.sa_family = AF_INET;
+        strncpy(ifr.ifr_name, tarEth, IFNAMSIZ - 1);
+
+        ioctl(fd, SIOCGIFHWADDR, &ifr);
+        close(fd);
+
+        sprintf(Mac, "%.2x:%.2x:%.2x:%.2x:%.2x:%.2x",
+                ifr.ifr_hwaddr.sa_data[0],
+                ifr.ifr_hwaddr.sa_data[1],
+                ifr.ifr_hwaddr.sa_data[2],
+                ifr.ifr_hwaddr.sa_data[3],
+                ifr.ifr_hwaddr.sa_data[4],
+                ifr.ifr_hwaddr.sa_data[5]
+               );
+
+        if (index == 0) {
+            strcpy((char *) pSysConfig->Eth0Interface.EthMacAddress, Mac);
+        } else {
+            strcpy((char *) pSysConfig->Eth1Interface.EthMacAddress, Mac);
+        }
+    }
+}
+
+static int isRouteFail(void)
+{
+    int result = YES;
+    FILE *fp;
+    char buf[512];
+
+    fp = popen("route -n", "r");
+    if (fp != NULL) {
+        while (fgets(buf, sizeof(buf), fp) != NULL) {
+            if (strstr(buf, "eth0") != NULL) {
+                result = NO;
+            }
+        }
+    }
+    pclose(fp);
+
+    return result;
+}
+
+static int isReachableInternet(void)
+{
+    int result = FAIL;
+    int idx = 0;
+    FILE *fp;
+    char cmd[256] = {0};
+    char buf[512] = {0};
+    char tmp[512] = {0};
+    char *valid_Internet[2] = {"8.8.8.8", "180.76.76.76"};
+    struct SysConfigData *pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
+    struct AlarmCodeData *pAlarmCode = (struct AlarmCodeData *)GetShmAlarmCodeData();
+
+    strcpy(cmd, "ifconfig eth0");
+    fp = popen(cmd, "r");
+
+    if (fp != NULL) {
+        while (fgets(buf, sizeof(buf), fp) != NULL) {
+            if (strstr(buf, "inet addr:") > 0) {
+                sscanf(buf, "%*s%s", tmp);
+                substr(tmp, tmp, strspn(tmp, "addr:"), strlen(tmp) - strspn(tmp, "addr:"));
+
+                if (strcmp(tmp, (char *)pSysConfig->Eth0Interface.EthIpAddress) != EQUAL) {
+                    strcpy((char *) pSysConfig->Eth0Interface.EthIpAddress, tmp);
+                }
+            }
+        }
+    }
+
+    pclose(fp);
+
+    if (pAlarmCode->AlarmEvents.bits.DisconnectedFromDo == NORMAL) {
+        result = FAIL;
+    } else {
+        result = PASS;
+    }
+
+    return result;
+
+}
+
+void InitEthernet(void)
+{
+    char tmpbuf[256];
+    bool ethResult = false;
+    uint8_t cnt_pingDNS_Fail = 0;
+
+    struct SysConfigData *pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
+    struct SysInfoData *pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
+    struct InfoCodeData *pInfoCode = (struct InfoCodeData *)GetShmInfoCodeData();
+
+    system("ifconfig eth0 down");// eth0 down
+    system("ifconfig eth1 down");// eth1 down
+    sleep(2);
+
+    // /sbin/ifconfig eth0 192.168.1.10 netmask 255.255.255.0 down
+    system("echo 1 > /sys/class/gpio/gpio110/value");//reset PHY
+    sleep(2);
+
+    //Init Eth0 for internet
+    memset(tmpbuf, 0, 256);
+    sprintf(tmpbuf, "/sbin/ifconfig eth0 %s netmask %s up",
+            pSysConfig->Eth0Interface.EthIpAddress,
+            pSysConfig->Eth0Interface.EthSubmaskAddress);
+    //sprintf(tmpbuf,"/sbin/ifconfig eth0 192.168.100.10 netmask 255.255.255.0 up");
+    system(tmpbuf);
+    log_info("%s",tmpbuf);
+    memset(tmpbuf, 0, 256);
+    sprintf(tmpbuf, "route add default gw %s eth0 ",
+            pSysConfig->Eth0Interface.EthGatewayAddress);
+    //sprintf(tmpbuf,"route add default gw 192.168.100.1 eth0 ");
+    system(tmpbuf);
+    //system("ifconfig lo up");
+    //  /sbin/ifconfig eth0 192.168.1.10 netmask 255.255.255.0 up
+
+    //Init Eth1 for administrator tool
+    memset(tmpbuf, 0, 256);
+    sprintf(tmpbuf, "/sbin/ifconfig eth1 %s netmask %s up",
+            pSysConfig->Eth1Interface.EthIpAddress,
+            pSysConfig->Eth1Interface.EthSubmaskAddress);
+    log_info("%s",tmpbuf);
+    system(tmpbuf);
+
+    system("/sbin/ifconfig lo up");
+
+    //Run DHCP client if enabled
+    system("killall udhcpc");
+    system("rm -rf /etc/resolv.conf");
+    system("echo nameserver 8.8.8.8 > /etc/resolv.conf");       //Google DNS server
+    system("echo nameserver 180.76.76.76 > /etc/resolv.conf");  //Baidu DNS server
+    //system("/sbin/ifconfig eth0 down;/sbin/ifconfig eth0 up");
+
+    if (pSysConfig->Eth0Interface.EthDhcpClient == 0) {
+        sprintf(tmpbuf, "/sbin/udhcpc -i eth0 -x hostname:CSU3_%s -s /root/dhcp_script/eth0.script > /dev/null &",
+                pSysConfig->SystemId);
+        system(tmpbuf);
+    }
+
+    //Upgrade system id to /etc/hostname
+    sprintf(tmpbuf, "echo %s > /etc/hostname", pSysConfig->SystemId);
+    system(tmpbuf);
+
+    pid_t pid = fork();
+    if (pid == 0) {
+        //log_info("InitEthernet = %d", pid);
+
+        for (;;) {
+
+            isReachableInternet();
+            sleep(5);
+            continue;
+        }
+    }
+
+    log_info("Initial Ethernet OK");
+}

+ 939 - 939
EVSE/Projects/DD360Tcci/Apps/CSU/OCPP.c

@@ -1,939 +1,939 @@
-#include <stdio.h>      /*標準輸入輸出定義*/
-#include <stdlib.h>     /*標準函數庫定義*/
-#include <string.h>
-#include <stdint.h>
-#include <time.h>
-#include <unistd.h>
-
-//------------------------------------------------------------------------------
-int opcc_chk_reserve_expired(byte gun_index)
-{
-    int result = NO;
-    struct tm expiredDate;
-    struct timeb expiredTime;
-
-    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
-        if (sscanf((char *) ShmOCPP16Data->ReserveNow[gun_index].ExpiryDate,
-                   "%4d-%2d-%2dT%2d:%2d:%2d", &expiredDate.tm_year,
-                   &expiredDate.tm_mon, &expiredDate.tm_mday, &expiredDate.tm_hour,
-                   &expiredDate.tm_min, &expiredDate.tm_sec) == 6) {
-            expiredDate.tm_year -= 1900;
-            expiredDate.tm_mon -= 1;
-
-            expiredTime.time = mktime(&expiredDate);
-            if (!CheckTimeOut(expiredTime)) {
-                result = YES;
-            }
-        }
-    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
-        if (sscanf((char *) ShmOCPP20Data->ReserveNow[gun_index].expiryDateTime,
-                   "%4d-%2d-%2dT%2d:%2d:%2d", &expiredDate.tm_year,
-                   &expiredDate.tm_mon, &expiredDate.tm_mday, &expiredDate.tm_hour,
-                   &expiredDate.tm_min, &expiredDate.tm_sec) == 6) {
-            expiredDate.tm_year -= 1900;
-            expiredDate.tm_mon -= 1;
-
-            expiredTime.time = mktime(&expiredDate);
-            if (!CheckTimeOut(expiredTime)) {
-                result = YES;
-            }
-        }
-    }
-
-    return result;
-}
-
-//===============================================
-// OCPP routine
-//===============================================
-void ocpp_process_start()
-{
-    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
-        system("/root/OcppBackend &");
-    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
-        system("/root/OcppBackend20 &");
-    }
-}
-
-void ocpp_auto_response_BootNotification()
-{
-    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
-        if (ShmOCPP16Data->SpMsg.bits.BootNotificationConf == YES) {
-            ShmOCPP16Data->SpMsg.bits.BootNotificationConf = NO;
-        }
-    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
-        if (ShmOCPP20Data->SpMsg.bits.BootNotificationConf == YES) {
-            ShmOCPP20Data->SpMsg.bits.BootNotificationConf = NO;
-        }
-    }
-}
-
-bool ocpp_is_resPass_StartTransationConf(byte gun_index)
-{
-    bool result = false;
-
-    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
-        result = ShmOCPP16Data->CpMsg.bits[gun_index].StartTransactionConf;
-    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
-        result = ShmOCPP20Data->CpMsg.bits[gun_index].TransactionEventConf;
-    }
-
-    return result;
-}
-
-void ocpp_auto_response_StartTransationConf(byte gun_index)
-{
-    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
-        if (ShmOCPP16Data->CpMsg.bits[gun_index].StartTransactionConf) {
-            ShmOCPP16Data->CpMsg.bits[gun_index].StartTransactionConf = NO;
-        }
-    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
-        if (ShmOCPP20Data->CpMsg.bits[gun_index].TransactionEventConf) {
-            ShmOCPP20Data->CpMsg.bits[gun_index].TransactionEventConf = NO;
-        }
-    }
-}
-
-void ocpp_auto_response_ReserveConf(byte gun_index)
-{
-    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
-        ShmOCPP16Data->CsMsg.bits[gun_index].ReserveNowConf = YES;
-    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
-        ShmOCPP20Data->CsMsg.bits[gun_index].ReserveNowConf = YES;
-    }
-}
-
-bool ocpp_chk_authrization_cmd()
-{
-    char buf2[16] = "";
-    memset(buf2, 0, ARRAY_SIZE(buf2));
-
-    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
-        sprintf(buf2, "%s",   ShmOCPP16Data->Authorize.ResponseIdTagInfo.Status);
-    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
-        sprintf(buf2, "%s",   ShmOCPP20Data->Authorize.Response_idTokenInfo.status);
-    }
-    // 因為無法得知實際的長度,所以只能用搜尋的方式
-    if (strcmp(buf2, "Accepted") == EQUAL) {
-        return true;
-    }
-
-    return false;
-}
-
-bool opcc_sub_get_reset_req()
-{
-    bool result = false;
-
-    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
-        result = ShmOCPP16Data->MsMsg.bits.ResetReq;
-    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
-        result = ShmOCPP20Data->MsMsg.bits.ResetReq;
-    }
-
-    return result;
-}
-
-void ocpp_sub_run_reset(bool canReset)
-{
-    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
-        if (canReset && strcmp((char *)ShmOCPP16Data->Reset.Type, "Hard") == EQUAL) {
-            DEBUG_ERROR_MSG("****** Hard Reboot ****** \n");
-            sprintf((char *)ShmOCPP16Data->Reset.ResponseStatus, "Accepted");
-            ShmOCPP16Data->MsMsg.bits.ResetReq = NO;
-            ShmOCPP16Data->MsMsg.bits.ResetConf = YES;
-            sleep(3);
-            system("reboot -f");
-        } else if (canReset && strcmp((char *)ShmOCPP16Data->Reset.Type, "Soft") == EQUAL) {
-            DEBUG_ERROR_MSG("****** Soft Reboot ****** \n");
-            sprintf((char *)ShmOCPP16Data->Reset.ResponseStatus, "Accepted");
-            ShmOCPP16Data->MsMsg.bits.ResetReq = NO;
-            ShmOCPP16Data->MsMsg.bits.ResetConf = YES;
-            sleep(3);
-            KillAllTask();
-            system("/usr/bin/run_evse_restart.sh");
-        }
-    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
-        if (canReset && strcmp((char *)ShmOCPP20Data->Reset.type, "Immediate") == EQUAL) {
-            DEBUG_ERROR_MSG("****** Hard Reboot ****** \n");
-            sprintf((char *)ShmOCPP20Data->Reset.Response_status, "Accepted");
-            ShmOCPP20Data->MsMsg.bits.ResetReq = NO;
-            ShmOCPP20Data->MsMsg.bits.ResetConf = YES;
-            sleep(3);
-            system("reboot -f");
-        } else if (canReset && strcmp((char *)ShmOCPP20Data->Reset.type, "OnIdle") == EQUAL) {
-            DEBUG_ERROR_MSG("****** Soft Reboot ****** \n");
-            sprintf((char *)ShmOCPP20Data->Reset.Response_status, "Accepted");
-            ShmOCPP20Data->MsMsg.bits.ResetReq = NO;
-            ShmOCPP20Data->MsMsg.bits.ResetConf = YES;
-            sleep(3);
-            KillAllTask();
-            system("/usr/bin/run_evse_restart.sh");
-        }
-    }
-}
-
-void ocpp_chk_reset_cmd()
-{
-    if (opcc_sub_get_reset_req()) {
-        bool canReset = true;
-
-        if (ShmSysConfigAndInfo->SysWarningInfo.Level != 2) {
-            for (byte _index = 0; _index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; _index++) {
-                if (chargingInfo[_index]->SystemStatus != S_IDLE &&
-                        chargingInfo[_index]->SystemStatus != S_RESERVATION &&
-                        chargingInfo[_index]->SystemStatus != S_MAINTAIN) {
-                    canReset = false;
-                    if (chargingInfo[_index]->SystemStatus >= S_REASSIGN &&
-                            chargingInfo[_index]->SystemStatus < S_TERMINATING) {
-                        // Reset 系統先停止充電
-                        ChargingTerminalProcess(_index);
-                    }
-                }
-            }
-        }
-
-        if (canReset) {
-            // Reset -> change status to maintain.
-            for (byte _index = 0; _index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; _index++) {
-                setChargerMode(_index, MODE_MAINTAIN);
-            }
-            ChangeLcmByIndex(_LCM_FIX);
-        }
-
-        ocpp_sub_run_reset(canReset);
-    }
-}
-
-void ocpp_chk_reserved_cmd(byte gunIndex)
-{
-    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
-        if (chargingInfo[gunIndex]->SystemStatus == S_IDLE &&
-                ShmOCPP16Data->CsMsg.bits[gunIndex].ReserveNowReq == YES) {
-            ShmOCPP16Data->CsMsg.bits[gunIndex].ReserveNowReq = NO;
-            if (opcc_chk_reserve_expired(gunIndex)) {
-                PRINTF_FUNC("***************ChkOcppStatus : OcppReservedStatus******************** \n");
-                DEBUG_ERROR_MSG("***************ChkOcppStatus : OcppReservedStatus******************** \n");
-                chargingInfo[gunIndex]->ReservationId = ShmOCPP16Data->ReserveNow[gunIndex].ReservationId;
-                chargingInfo[gunIndex]->SystemStatus = S_RESERVATION;
-            }
-            ShmOCPP16Data->CsMsg.bits[gunIndex].ReserveNowConf = YES;
-        }
-
-        if (chargingInfo[gunIndex]->SystemStatus == S_RESERVATION &&
-                ShmOCPP16Data->CsMsg.bits[gunIndex].CancelReservationReq == YES) {
-            ShmOCPP16Data->CsMsg.bits[gunIndex].CancelReservationReq = NO;
-            if (opcc_chk_reserve_expired(gunIndex)) {
-                PRINTF_FUNC("***************ChkOcppStatus : Cancel OcppReservedStatus******************** \n");
-                DEBUG_ERROR_MSG("***************ChkOcppStatus : Cancel OcppReservedStatus******************** \n");
-                chargingInfo[gunIndex]->ReservationId = 0;
-                chargingInfo[gunIndex]->SystemStatus = S_IDLE;
-            }
-            ShmOCPP16Data->CsMsg.bits[gunIndex].CancelReservationConf = YES;
-        }
-    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
-        if (chargingInfo[gunIndex]->SystemStatus == S_IDLE &&
-                ShmOCPP20Data->CsMsg.bits[gunIndex].ReserveNowReq == YES) {
-            ShmOCPP20Data->CsMsg.bits[gunIndex].ReserveNowReq = NO;
-            if (opcc_chk_reserve_expired(gunIndex)) {
-                PRINTF_FUNC("***************ChkOcppStatus : OcppReservedStatus******************** \n");
-                DEBUG_ERROR_MSG("***************ChkOcppStatus : OcppReservedStatus******************** \n");
-                chargingInfo[gunIndex]->ReservationId = ShmOCPP20Data->ReserveNow[gunIndex].id;
-                chargingInfo[gunIndex]->SystemStatus = S_RESERVATION;
-            }
-            ShmOCPP20Data->CsMsg.bits[gunIndex].ReserveNowConf = YES;
-        }
-
-        if (chargingInfo[gunIndex]->SystemStatus == S_RESERVATION &&
-                ShmOCPP20Data->CsMsg.bits[gunIndex].CancelReservationReq == YES) {
-            ShmOCPP20Data->CsMsg.bits[gunIndex].CancelReservationReq = NO;
-            if (opcc_chk_reserve_expired(gunIndex)) {
-                PRINTF_FUNC("***************ChkOcppStatus : Cancel OcppReservedStatus******************** \n");
-                DEBUG_ERROR_MSG("***************ChkOcppStatus : Cancel OcppReservedStatus******************** \n");
-                chargingInfo[gunIndex]->ReservationId = 0;
-                chargingInfo[gunIndex]->SystemStatus = S_IDLE;
-            }
-            ShmOCPP20Data->CsMsg.bits[gunIndex].CancelReservationConf = YES;
-        }
-    }
-}
-
-void ocpp_chk_availability_cmd(byte gunIndex)
-{
-    byte type = 0; // 0 : none, 1 : operative, 2 inoperative
-
-    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
-        if (ShmOCPP16Data->CsMsg.bits[gunIndex].ChangeAvailabilityReq == YES) {
-            PRINTF_FUNC("***************ChkOcppStatus : OcppChangeAvailability******************** \n");
-            DEBUG_ERROR_MSG("***************ChkOcppStatus : OcppChangeAvailability******************** \n");
-            ShmOCPP16Data->CsMsg.bits[gunIndex].ChangeAvailabilityReq = NO;
-            if (strcmp((char *)ShmOCPP16Data->ChangeAvailability[gunIndex].Type, "Operative") == EQUAL) {
-                if (isDb_ready) {
-                    DB_Update_Operactive(localDb, gunIndex, true);
-                }
-
-                type = 1;
-            } else if (strcmp((char *)ShmOCPP16Data->ChangeAvailability[gunIndex].Type, "Inoperative") == EQUAL) {
-                if (isDb_ready) {
-                    DB_Update_Operactive(localDb, gunIndex, false);
-                }
-
-                type = 2;
-            }
-        }
-    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
-        if (ShmOCPP20Data->CsMsg.bits[gunIndex].ChangeAvailabilityReq == YES) {
-            PRINTF_FUNC("***************ChkOcppStatus : OcppChangeAvailability******************** \n");
-            DEBUG_ERROR_MSG("***************ChkOcppStatus : OcppChangeAvailability******************** \n");
-            ShmOCPP20Data->CsMsg.bits[gunIndex].ChangeAvailabilityReq = NO;
-            if (strcmp((char *)ShmOCPP20Data->ChangeAvailability[gunIndex].operationalStatus, "Operative") == EQUAL) {
-                if (isDb_ready) {
-                    DB_Update_Operactive(localDb, gunIndex, true);
-                }
-
-                type = 1;
-            } else if (strcmp((char *)ShmOCPP20Data->ChangeAvailability[gunIndex].operationalStatus, "Inoperative") == EQUAL) {
-                if (isDb_ready) {
-                    DB_Update_Operactive(localDb, gunIndex, false);
-                }
-
-                type = 2;
-            }
-        }
-    }
-
-    if (type == 1) {
-        chargingInfo[gunIndex]->IsAvailable = YES;
-        if (chargingInfo[gunIndex]->SystemStatus == S_IDLE ||
-                chargingInfo[gunIndex]->SystemStatus == S_RESERVATION ||
-                chargingInfo[gunIndex]->SystemStatus == S_MAINTAIN) {
-            setChargerMode(gunIndex, MODE_IDLE);
-        }
-    } else if (type == 2) {
-        chargingInfo[gunIndex]->IsAvailable = NO;
-        if (chargingInfo[gunIndex]->SystemStatus == S_IDLE ||
-                chargingInfo[gunIndex]->SystemStatus == S_RESERVATION ||
-                chargingInfo[gunIndex]->SystemStatus == S_MAINTAIN) {
-            setChargerMode(gunIndex, MODE_MAINTAIN);
-        }
-    }
-}
-
-void ocpp_chk_unlock_cmd(byte gunIndex)
-{
-    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
-        if (ShmOCPP16Data->CsMsg.bits[gunIndex].UnlockConnectorReq == YES) {
-            ShmOCPP16Data->CsMsg.bits[gunIndex].UnlockConnectorReq = NO;
-            if (chargingInfo[gunIndex]->SystemStatus >= S_REASSIGN_CHECK &&
-                    chargingInfo[gunIndex]->SystemStatus <= S_CHARGING) {
-                // Unlocked - 充電中,需停止充電
-                strcpy((char *)ShmOCPP16Data->StopTransaction[gunIndex].StopReason, "UnlockCommand");
-                ChargingTerminalProcess(gunIndex);
-            }
-            strcpy((char *)ShmOCPP16Data->UnlockConnector[gunIndex].ResponseStatus, "Unlocked");
-            ShmOCPP16Data->CsMsg.bits[gunIndex].UnlockConnectorConf = YES;
-        }
-    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
-        if (ShmOCPP20Data->CsMsg.bits[gunIndex].UnlockConnectorReq == YES) {
-            ShmOCPP20Data->CsMsg.bits[gunIndex].UnlockConnectorReq = NO;
-            if (chargingInfo[gunIndex]->SystemStatus >= S_REASSIGN_CHECK &&
-                    chargingInfo[gunIndex]->SystemStatus <= S_CHARGING) {
-                // Unlocked - 充電中,需停止充電
-                strcpy((char *)ShmOCPP20Data->TransactionEvent[gunIndex].transactionInfo.stoppedReason, "UnlockCommand");
-                ChargingTerminalProcess(gunIndex);
-            }
-            strcpy((char *)ShmOCPP20Data->UnlockConnector[gunIndex].Response_status, "Unlocked");
-            ShmOCPP20Data->CsMsg.bits[gunIndex].UnlockConnectorConf = YES;
-        }
-    }
-}
-
-bool ocpp_chk_remoteStop_cmd(byte gunIndex)
-{
-    byte acDirIndex = ShmSysConfigAndInfo->SysConfig.AcConnectorCount;
-
-    // 有 AC 槍的話
-    if (acDirIndex > 0 && gunIndex > 0) {
-        gunIndex += acDirIndex;
-    }
-
-    bool result = false;
-
-    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
-        result = ShmOCPP16Data->CsMsg.bits[gunIndex].RemoteStopTransactionReq;
-    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
-        result = ShmOCPP20Data->CsMsg.bits[gunIndex].RequestStopTransactionReq;
-    }
-
-    if (result) {
-        DEBUG_INFO_MSG("Remote Stop by OCPP (%d) \n", gunIndex);
-        if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
-            strcpy((char *)ShmOCPP16Data->StopTransaction[gunIndex].StopReason, "Remote");
-            ShmOCPP16Data->CsMsg.bits[gunIndex].RemoteStopTransactionReq = NO;
-        } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
-            strcpy((char *)ShmOCPP20Data->TransactionEvent[gunIndex].transactionInfo.stoppedReason, "Remote");
-            ShmOCPP20Data->CsMsg.bits[gunIndex].RequestStopTransactionReq = NO;
-        }
-    }
-
-    return result;
-}
-
-bool ocpp_sub_get_remote_start_transaction_req(byte gun_index)
-{
-    bool result = false;
-
-    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
-        result = ShmOCPP16Data->CsMsg.bits[gun_index].RemoteStartTransactionReq;
-    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
-        result = ShmOCPP20Data->CsMsg.bits[gun_index].RequestStartTransactionReq;
-    }
-
-    if (result) {
-        strcpy((char *)ShmOCPP16Data->StartTransaction[gun_index].IdTag,
-               (char *)ShmOCPP16Data->RemoteStartTransaction[gun_index].IdTag);
-    }
-
-    return result;
-}
-
-void ocpp_sub_set_remote_start_transaction_req(byte gunIndex, bool result)
-{
-    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
-        ShmOCPP16Data->CsMsg.bits[gunIndex].RemoteStartTransactionReq = result;
-    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
-        ShmOCPP20Data->CsMsg.bits[gunIndex].RequestStartTransactionReq = result;
-    }
-}
-/*
-void ocpp_chk_remoteStart_cmd()
-{
-    if (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == _OFFLINE_POLICY_NO_CHARGING)
-    {}
-    else if (!isDetectPlugin()) {
-        // 如果有 AC 槍,則固定是第 2 把槍,所以索引固定為 1
-        byte acDirIndex = ShmSysConfigAndInfo->SysConfig.AcConnectorCount;
-
-        for (byte ac_index = 0; ac_index < ShmSysConfigAndInfo->SysConfig.AcConnectorCount; ac_index++) {
-            if (ocpp_sub_get_remote_start_transaction_req(acDirIndex)) {
-                if (ac_chargingInfo[ac_index]->SystemStatus == S_IDLE ||
-                        ac_chargingInfo[ac_index]->SystemStatus == S_RESERVATION) {
-                    ac_chargingInfo[ac_index]->RemoteStartFlag = YES;
-                    ShmSysConfigAndInfo->SysInfo.OrderCharging = YES;
-                    //ShmSysConfigAndInfo->SysInfo.OrderCharging = DEFAULT_AC_INDEX;
-                    //ShmOCPP16Data->CsMsg.bits[ShmSysConfigAndInfo->SysConfig.TotalConnectorCount + ac_index].RemoteStartTransactionReq = NO;
-                    DetectPluginStart(acDirIndex);
-                    return;
-                }
-                ocpp_sub_set_remote_start_transaction_req(acDirIndex, NO);
-            }
-        }
-
-        byte threeGunIndex = 0;
-        byte dcIndex = 0;
-        bool isGunUsingStatus = false;
-        byte scheduleIndex = 0;
-
-        for (byte _index = 0; _index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; _index++) {
-            // 如果有 AC 槍,且 DC 槍也有兩把
-            if (acDirIndex == 1 && _index == 1) {
-                threeGunIndex = 1;
-            }
-
-            if (ocpp_sub_get_remote_start_transaction_req(_index + threeGunIndex)) {
-                dcIndex = _index;
-            }
-
-            if (chargingInfo[_index]->SystemStatus != S_IDLE) {
-                isGunUsingStatus = true;
-            }
-
-            if (chargingInfo[_index]->schedule.isTriggerStart) {
-                scheduleIndex = _index;
-            }
-        }
-
-        // 如果是雙槍單模,只認閒置狀態的槍,如果有預約~ 則預約也算被使用
-        if (isGunUsingStatus && ShmSysConfigAndInfo->SysInfo.IsAlternatvieConf) {
-            if (dcIndex == 0) {
-                threeGunIndex = 0;
-            }
-
-            ocpp_sub_set_remote_start_transaction_req(dcIndex + threeGunIndex, NO);
-            return;
-        }
-
-        if (dcIndex == 0) {
-            threeGunIndex = 0;
-        }
-
-        if (ocpp_sub_get_remote_start_transaction_req(dcIndex + threeGunIndex)) {
-            if (chargingInfo[dcIndex]->SystemStatus == S_IDLE ||
-                    chargingInfo[dcIndex]->SystemStatus == S_RESERVATION) {
-                chargingInfo[dcIndex]->RemoteStartFlag = YES;
-                ShmSysConfigAndInfo->SysInfo.OrderCharging = YES;
-                //ShmSysConfigAndInfo->SysInfo.OrderCharging = gun_index;
-                DetectPluginStart(dcIndex);
-            }
-            ocpp_sub_set_remote_start_transaction_req(dcIndex + threeGunIndex, NO);
-        } else if (chargingInfo[scheduleIndex]->schedule.isTriggerStart) {
-            if (chargingInfo[scheduleIndex]->SystemStatus == S_IDLE ||
-                    chargingInfo[scheduleIndex]->SystemStatus == S_RESERVATION) {
-                chargingInfo[scheduleIndex]->RemoteStartFlag = YES;
-                ShmSysConfigAndInfo->SysInfo.OrderCharging = YES;
-                DetectPluginStart(scheduleIndex);
-            }
-            chargingInfo[scheduleIndex]->schedule.isTriggerStart = NO;
-        }
-    }
-}
-*/
-void ocpp_chk_update_cmd()
-{
-    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
-        if (ShmOCPP16Data->MsMsg.bits.UpdateFirmwareReq == YES) {
-            ShmOCPP16Data->MsMsg.bits.UpdateFirmwareReq = NO;
-
-            if (strcmp((char *)ShmOCPP16Data->FirmwareStatusNotification.Status, "Downloaded") == EQUAL) {
-                DEBUG_INFO_MSG("Backend : update start. \n");
-                sleep(2);
-                strcpy((char *)ShmOCPP16Data->FirmwareStatusNotification.Status, "");
-                strcpy((char *)ShmOCPP16Data->FirmwareStatusNotification.Status, "Installing");
-                ShmOCPP16Data->SpMsg.bits.FirmwareStatusNotificationReq = YES;
-                KillTask();
-
-                for (byte _index = 0; _index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; _index++) {
-                    setChargerMode(_index, MODE_UPDATE);
-                }
-                for (byte _index = 0; _index < ShmSysConfigAndInfo->SysConfig.AcConnectorCount; _index++) {
-                    ac_chargingInfo[_index]->SystemStatus = MODE_UPDATE;
-                }
-
-                byte updateResult = CheckUpdateProcess();
-
-                if (updateResult == PASS) {
-                    DEBUG_INFO_MSG("Backend : update complete. \n");
-                    strcpy((char *)ShmOCPP16Data->FirmwareStatusNotification.Status, "Installed");
-                } else if (updateResult == MODELNAME_FAIL) {
-                    DEBUG_INFO_MSG("Backend : model name is none match. \n");
-                    strcpy((char *)ShmOCPP16Data->FirmwareStatusNotification.Status, "InstallationFailed");
-                    ShmOCPP16Data->SpMsg.bits.FirmwareStatusNotificationReq = YES;
-                    sleep(5);
-                    KillAllTask();
-                    system("/usr/bin/run_evse_restart.sh");
-                    return;
-                } else {
-                    DEBUG_INFO_MSG("Backend : update fail. \n");
-                    strcpy((char *)ShmOCPP16Data->FirmwareStatusNotification.Status, "InstallationFailed");
-                }
-
-                strcpy((char *)ShmOCPP16Data->FirmwareStatusNotification.Status, "Installed");
-                ShmOCPP16Data->SpMsg.bits.FirmwareStatusNotificationReq = YES;
-                sleep(5);
-                system("reboot -f");
-            }
-        }
-    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
-        if (ShmOCPP20Data->MsMsg.bits.UpdateFirmwareReq == YES) {
-            ShmOCPP20Data->MsMsg.bits.UpdateFirmwareReq = NO;
-
-            if (strcmp((char *)ShmOCPP20Data->FirmwareStatusNotification.status, "Downloaded") == EQUAL) {
-                DEBUG_INFO_MSG("Backend : update start. \n");
-                sleep(2);
-                strcpy((char *)ShmOCPP20Data->FirmwareStatusNotification.status, "");
-                strcpy((char *)ShmOCPP20Data->FirmwareStatusNotification.status, "Installing");
-                ShmOCPP20Data->SpMsg.bits.FirmwareStatusNotificationReq = YES;
-                KillTask();
-
-                for (byte _index = 0; _index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; _index++) {
-                    setChargerMode(_index, MODE_UPDATE);
-                }
-                for (byte _index = 0; _index < ShmSysConfigAndInfo->SysConfig.AcConnectorCount; _index++) {
-                    ac_chargingInfo[_index]->SystemStatus = MODE_UPDATE;
-                }
-
-                byte updateResult = CheckUpdateProcess();
-
-                if (updateResult == PASS) {
-                    DEBUG_INFO_MSG("Backend : update complete. \n");
-                    strcpy((char *)ShmOCPP20Data->FirmwareStatusNotification.status, "Installed");
-                } else if (updateResult == MODELNAME_FAIL) {
-                    DEBUG_INFO_MSG("Backend : model name is none match. \n");
-                    strcpy((char *)ShmOCPP20Data->FirmwareStatusNotification.status, "InstallationFailed");
-                    ShmOCPP20Data->SpMsg.bits.FirmwareStatusNotificationReq = YES;
-                    sleep(5);
-                    KillAllTask();
-                    system("/usr/bin/run_evse_restart.sh");
-                    return;
-                } else {
-                    DEBUG_INFO_MSG("Backend : update fail. \n");
-                    strcpy((char *)ShmOCPP20Data->FirmwareStatusNotification.status, "InstallationFailed");
-                }
-
-                strcpy((char *)ShmOCPP20Data->FirmwareStatusNotification.status, "Installed");
-                ShmOCPP20Data->SpMsg.bits.FirmwareStatusNotificationReq = YES;
-                sleep(5);
-                system("reboot -f");
-            }
-        }
-    }
-}
-
-bool ocpp_chk_invalid_id_cmd(byte gunIndex)
-{
-    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
-        if (strstr((char *) ShmOCPP16Data->ConfigurationTable.CoreProfile[StopTransactionOnInvalidId].ItemData, "TRUE")) {
-            if (strcmp((char *)ShmOCPP16Data->StartTransaction[gunIndex].ResponseIdTagInfo.Status, "Blocked") == EQUAL ||
-                    strcmp((char *)ShmOCPP16Data->StartTransaction[gunIndex].ResponseIdTagInfo.Status, "Expired") == EQUAL ||
-                    strcmp((char *)ShmOCPP16Data->StartTransaction[gunIndex].ResponseIdTagInfo.Status, "Invalid") == EQUAL) {
-                return true;
-            }
-        }
-    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
-        if (strstr((char *) ShmOCPP20Data->ControllerComponentVariable[TxCtrlr_StopTxOnInvalidId].variableAttribute[0].value, "TRUE")) {
-            if (strcmp((char *)ShmOCPP20Data->TransactionEvent[gunIndex].Response_idTokenInfo.status, "Blocked") == EQUAL ||
-                    strcmp((char *)ShmOCPP20Data->TransactionEvent[gunIndex].Response_idTokenInfo.status, "Expired") == EQUAL ||
-                    strcmp((char *)ShmOCPP20Data->TransactionEvent[gunIndex].Response_idTokenInfo.status, "Invalid") == EQUAL ||
-                    strcmp((char *)ShmOCPP20Data->TransactionEvent[gunIndex].Response_idTokenInfo.status, "NoCredit") == EQUAL ||
-                    strcmp((char *)ShmOCPP20Data->TransactionEvent[gunIndex].Response_idTokenInfo.status, "NotAllowedTypeEVSE") == EQUAL ||
-                    strcmp((char *)ShmOCPP20Data->TransactionEvent[gunIndex].Response_idTokenInfo.status, "NotAtThisLocation") == EQUAL ||
-                    strcmp((char *)ShmOCPP20Data->TransactionEvent[gunIndex].Response_idTokenInfo.status, "NotAtThisTime") == EQUAL ||
-                    strcmp((char *)ShmOCPP20Data->TransactionEvent[gunIndex].Response_idTokenInfo.status, "Unknown") == EQUAL) {
-                return true;
-            }
-        }
-    }
-
-    return false;
-}
-
-bool ocpp_chk_profileConf_cmd(byte _index)
-{
-    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
-        if (ShmOCPP16Data->CSUMsg.bits[_index].ChargingProfileConf == YES) {
-            ShmOCPP16Data->CSUMsg.bits[_index].ChargingProfileConf = NO;
-            return true;
-        }
-    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
-        if (ShmOCPP20Data->CSUMsg.bits[_index].ChargingProfileConf == YES) {
-            ShmOCPP20Data->CSUMsg.bits[_index].ChargingProfileConf = NO;
-            return true;
-        }
-    }
-
-    return false;
-}
-
-void ocpp_lift_profileReq_cmd(byte gunIndex)
-{
-    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
-        if (ShmOCPP16Data->CSUMsg.bits[gunIndex].ChargingProfileConf == NO) {
-            if (ShmOCPP16Data->CSUMsg.bits[gunIndex].ChargingProfileReq == NO) {
-                ShmOCPP16Data->CSUMsg.bits[gunIndex].ChargingProfileReq = YES;
-            }
-        }
-    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
-        if (ShmOCPP20Data->CSUMsg.bits[gunIndex].ChargingProfileConf == NO) {
-            if (ShmOCPP20Data->CSUMsg.bits[gunIndex].ChargingProfileReq == NO) {
-                ShmOCPP20Data->CSUMsg.bits[gunIndex].ChargingProfileReq = YES;
-            }
-        }
-    }
-}
-
-void ocpp_set_startTransation_cmd(byte gunIndex)
-{
-    byte _OcppGunIndex = gunIndex;
-
-    // 如果有 AC 槍,而現在是 DC 第二把槍進入充電
-    if (ShmSysConfigAndInfo->SysConfig.AcConnectorCount == 1 && gunIndex == 1) {
-        _OcppGunIndex = 2;
-    }
-
-    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
-        if (strcmp((char *)chargingInfo[gunIndex]->StartUserId, "") == EQUAL) {
-            strcpy((char *)ShmOCPP16Data->StartTransaction[_OcppGunIndex].IdTag, (char *)ShmOCPP16Data->StartTransaction[_OcppGunIndex].IdTag);
-        } else {
-            strcpy((char *)ShmOCPP16Data->StartTransaction[_OcppGunIndex].IdTag, (char *)chargingInfo[gunIndex]->StartUserId);
-        }
-
-        PRINTF_FUNC("IdTag = %s \n", ShmOCPP16Data->StartTransaction[_OcppGunIndex].IdTag);
-        ShmOCPP16Data->CpMsg.bits[_OcppGunIndex].StartTransactionReq = YES;
-    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
-        if (strcmp((char *)chargingInfo[gunIndex]->StartUserId, "") == EQUAL) {
-            strcpy((char *)ShmOCPP20Data->TransactionEvent[_OcppGunIndex].idToken.idToken, (char *)ShmOCPP20Data->TransactionEvent[_OcppGunIndex].idToken.idToken);
-        } else {
-            strcpy((char *)ShmOCPP20Data->TransactionEvent[_OcppGunIndex].idToken.idToken, (char *)chargingInfo[gunIndex]->StartUserId);
-        }
-
-        PRINTF_FUNC("IdTag = %s \n", ShmOCPP20Data->TransactionEvent[_OcppGunIndex].idToken.idToken);
-        ShmOCPP20Data->CpMsg.bits[_OcppGunIndex].TransactionEventReq = YES;
-    }
-}
-
-void ocpp_set_stopTransation_cmd(byte gunIndex)
-{
-    byte _OcppGunIndex = gunIndex;
-
-    // 如果有 AC 槍,而現在是 DC 第二把槍進入充電
-    if (ShmSysConfigAndInfo->SysConfig.AcConnectorCount == 1 && gunIndex == 1) {
-        _OcppGunIndex = 2;
-    }
-
-    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
-        if (strcmp((char *)chargingInfo[gunIndex]->StartUserId, "") == EQUAL) {
-            strcpy((char *)ShmOCPP16Data->StopTransaction[_OcppGunIndex].IdTag, (char *)ShmOCPP16Data->StopTransaction[_OcppGunIndex].IdTag);
-        } else {
-            strcpy((char *)ShmOCPP16Data->StopTransaction[_OcppGunIndex].IdTag, (char *)chargingInfo[gunIndex]->StartUserId);
-        }
-
-        PRINTF_FUNC("IdTag = %s \n", ShmOCPP16Data->StopTransaction[_OcppGunIndex].IdTag);
-        ShmOCPP16Data->CpMsg.bits[_OcppGunIndex].StopTransactionReq = YES;
-    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
-        if (strcmp((char *)chargingInfo[gunIndex]->StartUserId, "") == EQUAL) {
-            strcpy((char *)ShmOCPP20Data->TransactionEvent[_OcppGunIndex].idToken.idToken, (char *)ShmOCPP20Data->TransactionEvent[_OcppGunIndex].idToken.idToken);
-        } else {
-            strcpy((char *)ShmOCPP20Data->TransactionEvent[_OcppGunIndex].idToken.idToken, (char *)chargingInfo[gunIndex]->StartUserId);
-        }
-
-        PRINTF_FUNC("IdTag = %s \n", ShmOCPP20Data->TransactionEvent[_OcppGunIndex].idToken.idToken);
-        ShmOCPP20Data->CpMsg.bits[_OcppGunIndex].TransactionEventReq = YES;
-    }
-}
-
-void ocpp_set_errorCode_cmd(byte gunIndex, char *errString)
-{
-    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
-        strcpy((char *)ShmOCPP16Data->StatusNotification[gunIndex].ErrorCode, errString);
-    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
-
-    }
-}
-
-void ocpp_set_stopReason_by_cmd(byte gunIndex, char *reason)
-{
-    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
-        if (strcmp((char *)ShmOCPP16Data->StopTransaction[gunIndex].StopReason, "") == EQUAL) {
-            strcpy((char *)ShmOCPP16Data->StopTransaction[gunIndex].StopReason, reason);
-        }
-    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
-        if (strcmp((char *)ShmOCPP20Data->TransactionEvent[gunIndex].transactionInfo.stoppedReason, "") == EQUAL) {
-            strcpy((char *)ShmOCPP20Data->TransactionEvent[gunIndex].transactionInfo.stoppedReason, reason);
-        }
-    }
-}
-
-void ocpp_set_authorizeReq_cmd(byte value)
-{
-    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
-        ShmOCPP16Data->SpMsg.bits.AuthorizeReq = value;
-    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
-        ShmOCPP20Data->SpMsg.bits.AuthorizeReq = value;
-    }
-}
-
-void ocpp_set_authorizeConf_cmd(byte value)
-{
-    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
-        ShmOCPP16Data->SpMsg.bits.AuthorizeConf = value;
-    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
-        ShmOCPP20Data->SpMsg.bits.AuthorizeConf = value;
-    }
-}
-
-void ocpp_set_errCode_cmd(byte gunIndex)
-{
-    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
-        if (strcmp((char *)chargingInfo[gunIndex]->ConnectorAlarmCode, "") != EQUAL) {
-            strcpy((char *)ShmOCPP16Data->StatusNotification[gunIndex].ErrorCode, "InternalError");
-            strcpy((char *)ShmOCPP16Data->StatusNotification[gunIndex].VendorErrorCode, (char *)chargingInfo[gunIndex]->ConnectorAlarmCode);
-        } else if (strcmp((char *)chargingInfo[gunIndex]->EvConnAlarmCode, "") != EQUAL) {
-            strcpy((char *)ShmOCPP16Data->StatusNotification[gunIndex].ErrorCode, "OtherError");
-            strcpy((char *)ShmOCPP16Data->StatusNotification[gunIndex].VendorErrorCode, (char *)chargingInfo[gunIndex]->EvConnAlarmCode);
-        }
-    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
-
-    }
-}
-
-void ocpp_clear_errorCode_cmd(byte gunIndex)
-{
-    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
-        if (strcmp((char *)ShmOCPP16Data->StatusNotification[gunIndex].ErrorCode, "NoError") != EQUAL) {
-            strcpy((char *)ShmOCPP16Data->StatusNotification[gunIndex].ErrorCode, "NoError");
-        }
-
-        if (strcmp((char *)ShmOCPP16Data->StatusNotification[gunIndex].VendorErrorCode, "") != EQUAL) {
-            strcpy((char *)ShmOCPP16Data->StatusNotification[gunIndex].VendorErrorCode, "");
-        }
-    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
-
-    }
-}
-
-void ocpp_clear_idTag_cmd(byte gun_index)
-{
-    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
-        strcpy((char *)ShmOCPP16Data->StartTransaction[gun_index].ResponseIdTagInfo.Status, "");
-    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
-        strcpy((char *)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "");
-    }
-}
-
-void ocpp_clear_stopReason(byte gun_index)
-{
-    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
-        strcpy((char *)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "");
-    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
-        strcpy((char *)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "");
-    }
-}
-
-unsigned short _ocpp_get_connect_timeout()
-{
-    uint16_t result = (TIMEOUT_SPEC_HANDSHAKING / 1000);
-
-    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
-        if (strcmp((char *)ShmOCPP16Data->ConfigurationTable.CoreProfile[ConnectionTimeOut].ItemData, "") != 0) {
-            result = atoi((char *)ShmOCPP16Data->ConfigurationTable.CoreProfile[ConnectionTimeOut].ItemData);
-        }
-    }
-
-    else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
-        if (strcmp((char *)ShmOCPP20Data->ControllerComponentVariable[TxCtrlr_EVConnectionTimeOut].variableAttribute[0].value, "") != 0) {
-            result = atoi((char *)ShmOCPP20Data->ControllerComponentVariable[TxCtrlr_EVConnectionTimeOut].variableAttribute[0].value);
-        }
-    }
-
-    return result;
-}
-
-bool _ocpp_get_disconnect_policy()
-{
-    bool result = false;
-
-    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
-        if (strcmp((char *)ShmOCPP16Data->ConfigurationTable.CoreProfile[AllowOfflineTxForUnknownId].ItemData, "TRUE") == EQUAL &&
-                strcmp((char *)ShmOCPP16Data->ConfigurationTable.CoreProfile[LocalAuthorizeOffline].ItemData, "TRUE") == EQUAL) {
-            result = true;
-        }
-    }
-
-    else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
-        if (strcmp((char *)ShmOCPP20Data->ControllerComponentVariable[LocalAuthorizeOffline].variableAttribute[0].value, "") == EQUAL &&
-                strcmp((char *)ShmOCPP20Data->ControllerComponentVariable[AuthCtrlr_LocalAuthorizeOffline].variableAttribute[0].value, "") == EQUAL) {
-            result = true;
-        }
-    }
-
-    return result;
-}
-
-bool ocpp_get_authorize_conf()
-{
-    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
-        return ShmOCPP16Data->SpMsg.bits.AuthorizeConf;
-    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
-        return ShmOCPP20Data->SpMsg.bits.AuthorizeConf;
-    }
-
-    return false;
-}
-
-bool ocpp_get_startTransation_req(byte gunIndex)
-{
-    bool result = false;
-
-    // 如果有 AC 槍,而現在是 DC 第二把槍進入充電
-    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
-        result = ShmOCPP16Data->CpMsg.bits[gunIndex].StartTransactionReq;
-    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
-        result = ShmOCPP20Data->CpMsg.bits[gunIndex].TransactionEventReq;
-    }
-
-    return result;
-}
-
-void ocpp_chargingProfile_process(byte _index)
-{
-    int _time = 0;
-    int _startCount = NO_DEFINE;
-    int _maxCount = 0;
-
-    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
-        if (strcmp((char *)ShmOCPP16Data->SmartChargingProfile[_index].ChargingProfileKind, "Absolute") == EQUAL &&
-                ShmOCPP16Data->SmartChargingProfile[_index].ChargingProfileId == YES) {
-            _time = GetStartScheduleTime(ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.StartSchedule);
-            _maxCount = ARRAY_SIZE(ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.ChargingSchedulePeriod);
-            _startCount = NO_DEFINE;
-
-            for (byte _count = 0; _count < _maxCount; _count++) {
-                // 預設最小輸出電流 (MIN_OUTPUT_CUR) A
-                if (_time >= ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.ChargingSchedulePeriod[_count].StartPeriod) {
-                    if ((_count == 0 && ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.ChargingSchedulePeriod[_count].Limit >= MIN_OUTPUT_CUR) ||
-                            ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.ChargingSchedulePeriod[_count].Limit > MIN_OUTPUT_CUR) {
-                        _startCount = _count;
-                    }
-                }
-            }
-
-            PRINTF_FUNC("Gun_%d, Get Profile - Profile Index = %d \n", _index, _startCount);
-            if (_startCount < _maxCount) {
-                PRINTF_FUNC("Profile Limit = %f \n", ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.ChargingSchedulePeriod[_startCount].Limit);
-                chargingInfo[_index]->ChargingProfilePower = ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.ChargingSchedulePeriod[_startCount].Limit * AC_OUTPUT_VOL * ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.ChargingSchedulePeriod[_startCount].NumberPhases;
-                if (chargingInfo[_index]->EvBatterytargetVoltage > 0 &&
-                        chargingInfo[_index]->PresentChargingVoltage > 0) {
-                    chargingInfo[_index]->ChargingProfileCurrent = (chargingInfo[_index]->ChargingProfilePower / chargingInfo[_index]->PresentChargingVoltage) * 10;
-                } else {
-                    chargingInfo[_index]->ChargingProfileCurrent = 0;
-                }
-            } else {
-                chargingInfo[_index]->ChargingProfilePower = -1;
-                chargingInfo[_index]->ChargingProfileCurrent = -1;
-            }
-        } else {
-            chargingInfo[_index]->ChargingProfilePower = -1;
-            chargingInfo[_index]->ChargingProfileCurrent = -1;
-        }
-    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
-        if (strcmp((char *)ShmOCPP20Data->SmartChargingProfile[_index].chargingProfileKind, "Absolute") == EQUAL &&
-                ShmOCPP20Data->SmartChargingProfile[_index].id == YES) {
-            _time = GetStartScheduleTime(ShmOCPP20Data->SmartChargingProfile[_index].chargingSchedule[0].startSchedule);
-            _maxCount = ARRAY_SIZE(ShmOCPP20Data->SmartChargingProfile[_index].chargingSchedule[0].chargingSchedulePeriod);
-            _startCount = NO_DEFINE;
-
-            for (byte _count = 0; _count < _maxCount; _count++) {
-                // 預設最小輸出電流 (MIN_OUTPUT_CUR) A
-                if (_time >= ShmOCPP20Data->SmartChargingProfile[_index].chargingSchedule[0].chargingSchedulePeriod[_count].startPeriod) {
-                    if ((_count == 0 && ShmOCPP20Data->SmartChargingProfile[_index].chargingSchedule[0].chargingSchedulePeriod[_count].limit >= MIN_OUTPUT_CUR) ||
-                            ShmOCPP20Data->SmartChargingProfile[_index].chargingSchedule[0].chargingSchedulePeriod[_count].limit > MIN_OUTPUT_CUR) {
-                        _startCount = _count;
-                    }
-                }
-            }
-
-            PRINTF_FUNC("Gun_%d, Get Profile - Profile Index = %d \n", _index, _startCount);
-            if (_startCount < _maxCount) {
-                PRINTF_FUNC("Profile Limit = %f \n", ShmOCPP20Data->SmartChargingProfile[_index].chargingSchedule[0].chargingSchedulePeriod[_startCount].limit);
-                chargingInfo[_index]->ChargingProfilePower = ShmOCPP20Data->SmartChargingProfile[_index].chargingSchedule[0].chargingSchedulePeriod[_startCount].limit * AC_OUTPUT_VOL;
-                if (chargingInfo[_index]->EvBatterytargetVoltage > 0 && chargingInfo[_index]->PresentChargingVoltage > 0) {
-                    chargingInfo[_index]->ChargingProfileCurrent = (chargingInfo[_index]->ChargingProfilePower / chargingInfo[_index]->PresentChargingVoltage) * 10;
-                } else {
-                    chargingInfo[_index]->ChargingProfileCurrent = 0;
-                }
-            } else {
-                chargingInfo[_index]->ChargingProfilePower = -1;
-                chargingInfo[_index]->ChargingProfileCurrent = -1;
-            }
-        } else {
-            chargingInfo[_index]->ChargingProfilePower = -1;
-            chargingInfo[_index]->ChargingProfileCurrent = -1;
-        }
-    } else {
-        chargingInfo[_index]->ChargingProfilePower = -1;
-        chargingInfo[_index]->ChargingProfileCurrent = -1;
-    }
-
-    PRINTF_FUNC("Profile : ChargingProfilePower = %f \n", chargingInfo[_index]->ChargingProfilePower);
-    PRINTF_FUNC("Profile : ChargingProfileCurrent = %f \n", chargingInfo[_index]->ChargingProfileCurrent);
-}
+#include <stdio.h>      /*標準輸入輸出定義*/
+#include <stdlib.h>     /*標準函數庫定義*/
+#include <string.h>
+#include <stdint.h>
+#include <time.h>
+#include <unistd.h>
+
+//------------------------------------------------------------------------------
+int opcc_chk_reserve_expired(byte gun_index)
+{
+    int result = NO;
+    struct tm expiredDate;
+    struct timeb expiredTime;
+
+    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
+        if (sscanf((char *) ShmOCPP16Data->ReserveNow[gun_index].ExpiryDate,
+                   "%4d-%2d-%2dT%2d:%2d:%2d", &expiredDate.tm_year,
+                   &expiredDate.tm_mon, &expiredDate.tm_mday, &expiredDate.tm_hour,
+                   &expiredDate.tm_min, &expiredDate.tm_sec) == 6) {
+            expiredDate.tm_year -= 1900;
+            expiredDate.tm_mon -= 1;
+
+            expiredTime.time = mktime(&expiredDate);
+            if (!CheckTimeOut(expiredTime)) {
+                result = YES;
+            }
+        }
+    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
+        if (sscanf((char *) ShmOCPP20Data->ReserveNow[gun_index].expiryDateTime,
+                   "%4d-%2d-%2dT%2d:%2d:%2d", &expiredDate.tm_year,
+                   &expiredDate.tm_mon, &expiredDate.tm_mday, &expiredDate.tm_hour,
+                   &expiredDate.tm_min, &expiredDate.tm_sec) == 6) {
+            expiredDate.tm_year -= 1900;
+            expiredDate.tm_mon -= 1;
+
+            expiredTime.time = mktime(&expiredDate);
+            if (!CheckTimeOut(expiredTime)) {
+                result = YES;
+            }
+        }
+    }
+
+    return result;
+}
+
+//===============================================
+// OCPP routine
+//===============================================
+void ocpp_process_start()
+{
+    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
+        system("/root/OcppBackend &");
+    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
+        system("/root/OcppBackend20 &");
+    }
+}
+
+void ocpp_auto_response_BootNotification()
+{
+    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
+        if (ShmOCPP16Data->SpMsg.bits.BootNotificationConf == YES) {
+            ShmOCPP16Data->SpMsg.bits.BootNotificationConf = NO;
+        }
+    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
+        if (ShmOCPP20Data->SpMsg.bits.BootNotificationConf == YES) {
+            ShmOCPP20Data->SpMsg.bits.BootNotificationConf = NO;
+        }
+    }
+}
+
+bool ocpp_is_resPass_StartTransationConf(byte gun_index)
+{
+    bool result = false;
+
+    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
+        result = ShmOCPP16Data->CpMsg.bits[gun_index].StartTransactionConf;
+    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
+        result = ShmOCPP20Data->CpMsg.bits[gun_index].TransactionEventConf;
+    }
+
+    return result;
+}
+
+void ocpp_auto_response_StartTransationConf(byte gun_index)
+{
+    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
+        if (ShmOCPP16Data->CpMsg.bits[gun_index].StartTransactionConf) {
+            ShmOCPP16Data->CpMsg.bits[gun_index].StartTransactionConf = NO;
+        }
+    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
+        if (ShmOCPP20Data->CpMsg.bits[gun_index].TransactionEventConf) {
+            ShmOCPP20Data->CpMsg.bits[gun_index].TransactionEventConf = NO;
+        }
+    }
+}
+
+void ocpp_auto_response_ReserveConf(byte gun_index)
+{
+    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
+        ShmOCPP16Data->CsMsg.bits[gun_index].ReserveNowConf = YES;
+    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
+        ShmOCPP20Data->CsMsg.bits[gun_index].ReserveNowConf = YES;
+    }
+}
+
+bool ocpp_chk_authrization_cmd()
+{
+    char buf2[16] = "";
+    memset(buf2, 0, ARRAY_SIZE(buf2));
+
+    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
+        sprintf(buf2, "%s",   ShmOCPP16Data->Authorize.ResponseIdTagInfo.Status);
+    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
+        sprintf(buf2, "%s",   ShmOCPP20Data->Authorize.Response_idTokenInfo.status);
+    }
+    // 因為無法得知實際的長度,所以只能用搜尋的方式
+    if (strcmp(buf2, "Accepted") == EQUAL) {
+        return true;
+    }
+
+    return false;
+}
+
+bool opcc_sub_get_reset_req()
+{
+    bool result = false;
+
+    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
+        result = ShmOCPP16Data->MsMsg.bits.ResetReq;
+    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
+        result = ShmOCPP20Data->MsMsg.bits.ResetReq;
+    }
+
+    return result;
+}
+
+void ocpp_sub_run_reset(bool canReset)
+{
+    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
+        if (canReset && strcmp((char *)ShmOCPP16Data->Reset.Type, "Hard") == EQUAL) {
+            DEBUG_ERROR_MSG("****** Hard Reboot ****** \n");
+            sprintf((char *)ShmOCPP16Data->Reset.ResponseStatus, "Accepted");
+            ShmOCPP16Data->MsMsg.bits.ResetReq = NO;
+            ShmOCPP16Data->MsMsg.bits.ResetConf = YES;
+            sleep(3);
+            system("reboot -f");
+        } else if (canReset && strcmp((char *)ShmOCPP16Data->Reset.Type, "Soft") == EQUAL) {
+            DEBUG_ERROR_MSG("****** Soft Reboot ****** \n");
+            sprintf((char *)ShmOCPP16Data->Reset.ResponseStatus, "Accepted");
+            ShmOCPP16Data->MsMsg.bits.ResetReq = NO;
+            ShmOCPP16Data->MsMsg.bits.ResetConf = YES;
+            sleep(3);
+            KillAllTask();
+            system("/usr/bin/run_evse_restart.sh");
+        }
+    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
+        if (canReset && strcmp((char *)ShmOCPP20Data->Reset.type, "Immediate") == EQUAL) {
+            DEBUG_ERROR_MSG("****** Hard Reboot ****** \n");
+            sprintf((char *)ShmOCPP20Data->Reset.Response_status, "Accepted");
+            ShmOCPP20Data->MsMsg.bits.ResetReq = NO;
+            ShmOCPP20Data->MsMsg.bits.ResetConf = YES;
+            sleep(3);
+            system("reboot -f");
+        } else if (canReset && strcmp((char *)ShmOCPP20Data->Reset.type, "OnIdle") == EQUAL) {
+            DEBUG_ERROR_MSG("****** Soft Reboot ****** \n");
+            sprintf((char *)ShmOCPP20Data->Reset.Response_status, "Accepted");
+            ShmOCPP20Data->MsMsg.bits.ResetReq = NO;
+            ShmOCPP20Data->MsMsg.bits.ResetConf = YES;
+            sleep(3);
+            KillAllTask();
+            system("/usr/bin/run_evse_restart.sh");
+        }
+    }
+}
+
+void ocpp_chk_reset_cmd()
+{
+    if (opcc_sub_get_reset_req()) {
+        bool canReset = true;
+
+        if (ShmSysConfigAndInfo->SysWarningInfo.Level != 2) {
+            for (byte _index = 0; _index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; _index++) {
+                if (chargingInfo[_index]->SystemStatus != S_IDLE &&
+                        chargingInfo[_index]->SystemStatus != S_RESERVATION &&
+                        chargingInfo[_index]->SystemStatus != S_MAINTAIN) {
+                    canReset = false;
+                    if (chargingInfo[_index]->SystemStatus >= S_REASSIGN &&
+                            chargingInfo[_index]->SystemStatus < S_TERMINATING) {
+                        // Reset 系統先停止充電
+                        ChargingTerminalProcess(_index);
+                    }
+                }
+            }
+        }
+
+        if (canReset) {
+            // Reset -> change status to maintain.
+            for (byte _index = 0; _index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; _index++) {
+                setChargerMode(_index, MODE_MAINTAIN);
+            }
+            ChangeLcmByIndex(_LCM_FIX);
+        }
+
+        ocpp_sub_run_reset(canReset);
+    }
+}
+
+void ocpp_chk_reserved_cmd(byte gunIndex)
+{
+    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
+        if (chargingInfo[gunIndex]->SystemStatus == S_IDLE &&
+                ShmOCPP16Data->CsMsg.bits[gunIndex].ReserveNowReq == YES) {
+            ShmOCPP16Data->CsMsg.bits[gunIndex].ReserveNowReq = NO;
+            if (opcc_chk_reserve_expired(gunIndex)) {
+                PRINTF_FUNC("***************ChkOcppStatus : OcppReservedStatus******************** \n");
+                DEBUG_ERROR_MSG("***************ChkOcppStatus : OcppReservedStatus******************** \n");
+                chargingInfo[gunIndex]->ReservationId = ShmOCPP16Data->ReserveNow[gunIndex].ReservationId;
+                chargingInfo[gunIndex]->SystemStatus = S_RESERVATION;
+            }
+            ShmOCPP16Data->CsMsg.bits[gunIndex].ReserveNowConf = YES;
+        }
+
+        if (chargingInfo[gunIndex]->SystemStatus == S_RESERVATION &&
+                ShmOCPP16Data->CsMsg.bits[gunIndex].CancelReservationReq == YES) {
+            ShmOCPP16Data->CsMsg.bits[gunIndex].CancelReservationReq = NO;
+            if (opcc_chk_reserve_expired(gunIndex)) {
+                PRINTF_FUNC("***************ChkOcppStatus : Cancel OcppReservedStatus******************** \n");
+                DEBUG_ERROR_MSG("***************ChkOcppStatus : Cancel OcppReservedStatus******************** \n");
+                chargingInfo[gunIndex]->ReservationId = 0;
+                chargingInfo[gunIndex]->SystemStatus = S_IDLE;
+            }
+            ShmOCPP16Data->CsMsg.bits[gunIndex].CancelReservationConf = YES;
+        }
+    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
+        if (chargingInfo[gunIndex]->SystemStatus == S_IDLE &&
+                ShmOCPP20Data->CsMsg.bits[gunIndex].ReserveNowReq == YES) {
+            ShmOCPP20Data->CsMsg.bits[gunIndex].ReserveNowReq = NO;
+            if (opcc_chk_reserve_expired(gunIndex)) {
+                PRINTF_FUNC("***************ChkOcppStatus : OcppReservedStatus******************** \n");
+                DEBUG_ERROR_MSG("***************ChkOcppStatus : OcppReservedStatus******************** \n");
+                chargingInfo[gunIndex]->ReservationId = ShmOCPP20Data->ReserveNow[gunIndex].id;
+                chargingInfo[gunIndex]->SystemStatus = S_RESERVATION;
+            }
+            ShmOCPP20Data->CsMsg.bits[gunIndex].ReserveNowConf = YES;
+        }
+
+        if (chargingInfo[gunIndex]->SystemStatus == S_RESERVATION &&
+                ShmOCPP20Data->CsMsg.bits[gunIndex].CancelReservationReq == YES) {
+            ShmOCPP20Data->CsMsg.bits[gunIndex].CancelReservationReq = NO;
+            if (opcc_chk_reserve_expired(gunIndex)) {
+                PRINTF_FUNC("***************ChkOcppStatus : Cancel OcppReservedStatus******************** \n");
+                DEBUG_ERROR_MSG("***************ChkOcppStatus : Cancel OcppReservedStatus******************** \n");
+                chargingInfo[gunIndex]->ReservationId = 0;
+                chargingInfo[gunIndex]->SystemStatus = S_IDLE;
+            }
+            ShmOCPP20Data->CsMsg.bits[gunIndex].CancelReservationConf = YES;
+        }
+    }
+}
+
+void ocpp_chk_availability_cmd(byte gunIndex)
+{
+    byte type = 0; // 0 : none, 1 : operative, 2 inoperative
+
+    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
+        if (ShmOCPP16Data->CsMsg.bits[gunIndex].ChangeAvailabilityReq == YES) {
+            PRINTF_FUNC("***************ChkOcppStatus : OcppChangeAvailability******************** \n");
+            DEBUG_ERROR_MSG("***************ChkOcppStatus : OcppChangeAvailability******************** \n");
+            ShmOCPP16Data->CsMsg.bits[gunIndex].ChangeAvailabilityReq = NO;
+            if (strcmp((char *)ShmOCPP16Data->ChangeAvailability[gunIndex].Type, "Operative") == EQUAL) {
+                if (isDb_ready) {
+                    DB_Update_Operactive(localDb, gunIndex, true);
+                }
+
+                type = 1;
+            } else if (strcmp((char *)ShmOCPP16Data->ChangeAvailability[gunIndex].Type, "Inoperative") == EQUAL) {
+                if (isDb_ready) {
+                    DB_Update_Operactive(localDb, gunIndex, false);
+                }
+
+                type = 2;
+            }
+        }
+    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
+        if (ShmOCPP20Data->CsMsg.bits[gunIndex].ChangeAvailabilityReq == YES) {
+            PRINTF_FUNC("***************ChkOcppStatus : OcppChangeAvailability******************** \n");
+            DEBUG_ERROR_MSG("***************ChkOcppStatus : OcppChangeAvailability******************** \n");
+            ShmOCPP20Data->CsMsg.bits[gunIndex].ChangeAvailabilityReq = NO;
+            if (strcmp((char *)ShmOCPP20Data->ChangeAvailability[gunIndex].operationalStatus, "Operative") == EQUAL) {
+                if (isDb_ready) {
+                    DB_Update_Operactive(localDb, gunIndex, true);
+                }
+
+                type = 1;
+            } else if (strcmp((char *)ShmOCPP20Data->ChangeAvailability[gunIndex].operationalStatus, "Inoperative") == EQUAL) {
+                if (isDb_ready) {
+                    DB_Update_Operactive(localDb, gunIndex, false);
+                }
+
+                type = 2;
+            }
+        }
+    }
+
+    if (type == 1) {
+        chargingInfo[gunIndex]->IsAvailable = YES;
+        if (chargingInfo[gunIndex]->SystemStatus == S_IDLE ||
+                chargingInfo[gunIndex]->SystemStatus == S_RESERVATION ||
+                chargingInfo[gunIndex]->SystemStatus == S_MAINTAIN) {
+            setChargerMode(gunIndex, MODE_IDLE);
+        }
+    } else if (type == 2) {
+        chargingInfo[gunIndex]->IsAvailable = NO;
+        if (chargingInfo[gunIndex]->SystemStatus == S_IDLE ||
+                chargingInfo[gunIndex]->SystemStatus == S_RESERVATION ||
+                chargingInfo[gunIndex]->SystemStatus == S_MAINTAIN) {
+            setChargerMode(gunIndex, MODE_MAINTAIN);
+        }
+    }
+}
+
+void ocpp_chk_unlock_cmd(byte gunIndex)
+{
+    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
+        if (ShmOCPP16Data->CsMsg.bits[gunIndex].UnlockConnectorReq == YES) {
+            ShmOCPP16Data->CsMsg.bits[gunIndex].UnlockConnectorReq = NO;
+            if (chargingInfo[gunIndex]->SystemStatus >= S_REASSIGN_CHECK &&
+                    chargingInfo[gunIndex]->SystemStatus <= S_CHARGING) {
+                // Unlocked - 充電中,需停止充電
+                strcpy((char *)ShmOCPP16Data->StopTransaction[gunIndex].StopReason, "UnlockCommand");
+                ChargingTerminalProcess(gunIndex);
+            }
+            strcpy((char *)ShmOCPP16Data->UnlockConnector[gunIndex].ResponseStatus, "Unlocked");
+            ShmOCPP16Data->CsMsg.bits[gunIndex].UnlockConnectorConf = YES;
+        }
+    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
+        if (ShmOCPP20Data->CsMsg.bits[gunIndex].UnlockConnectorReq == YES) {
+            ShmOCPP20Data->CsMsg.bits[gunIndex].UnlockConnectorReq = NO;
+            if (chargingInfo[gunIndex]->SystemStatus >= S_REASSIGN_CHECK &&
+                    chargingInfo[gunIndex]->SystemStatus <= S_CHARGING) {
+                // Unlocked - 充電中,需停止充電
+                strcpy((char *)ShmOCPP20Data->TransactionEvent[gunIndex].transactionInfo.stoppedReason, "UnlockCommand");
+                ChargingTerminalProcess(gunIndex);
+            }
+            strcpy((char *)ShmOCPP20Data->UnlockConnector[gunIndex].Response_status, "Unlocked");
+            ShmOCPP20Data->CsMsg.bits[gunIndex].UnlockConnectorConf = YES;
+        }
+    }
+}
+
+bool ocpp_chk_remoteStop_cmd(byte gunIndex)
+{
+    byte acDirIndex = ShmSysConfigAndInfo->SysConfig.AcConnectorCount;
+
+    // 有 AC 槍的話
+    if (acDirIndex > 0 && gunIndex > 0) {
+        gunIndex += acDirIndex;
+    }
+
+    bool result = false;
+
+    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
+        result = ShmOCPP16Data->CsMsg.bits[gunIndex].RemoteStopTransactionReq;
+    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
+        result = ShmOCPP20Data->CsMsg.bits[gunIndex].RequestStopTransactionReq;
+    }
+
+    if (result) {
+        DEBUG_INFO_MSG("Remote Stop by OCPP (%d) \n", gunIndex);
+        if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
+            strcpy((char *)ShmOCPP16Data->StopTransaction[gunIndex].StopReason, "Remote");
+            ShmOCPP16Data->CsMsg.bits[gunIndex].RemoteStopTransactionReq = NO;
+        } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
+            strcpy((char *)ShmOCPP20Data->TransactionEvent[gunIndex].transactionInfo.stoppedReason, "Remote");
+            ShmOCPP20Data->CsMsg.bits[gunIndex].RequestStopTransactionReq = NO;
+        }
+    }
+
+    return result;
+}
+
+bool ocpp_sub_get_remote_start_transaction_req(byte gun_index)
+{
+    bool result = false;
+
+    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
+        result = ShmOCPP16Data->CsMsg.bits[gun_index].RemoteStartTransactionReq;
+    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
+        result = ShmOCPP20Data->CsMsg.bits[gun_index].RequestStartTransactionReq;
+    }
+
+    if (result) {
+        strcpy((char *)ShmOCPP16Data->StartTransaction[gun_index].IdTag,
+               (char *)ShmOCPP16Data->RemoteStartTransaction[gun_index].IdTag);
+    }
+
+    return result;
+}
+
+void ocpp_sub_set_remote_start_transaction_req(byte gunIndex, bool result)
+{
+    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
+        ShmOCPP16Data->CsMsg.bits[gunIndex].RemoteStartTransactionReq = result;
+    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
+        ShmOCPP20Data->CsMsg.bits[gunIndex].RequestStartTransactionReq = result;
+    }
+}
+/*
+void ocpp_chk_remoteStart_cmd()
+{
+    if (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == _OFFLINE_POLICY_NO_CHARGING)
+    {}
+    else if (!isDetectPlugin()) {
+        // 如果有 AC 槍,則固定是第 2 把槍,所以索引固定為 1
+        byte acDirIndex = ShmSysConfigAndInfo->SysConfig.AcConnectorCount;
+
+        for (byte ac_index = 0; ac_index < ShmSysConfigAndInfo->SysConfig.AcConnectorCount; ac_index++) {
+            if (ocpp_sub_get_remote_start_transaction_req(acDirIndex)) {
+                if (ac_chargingInfo[ac_index]->SystemStatus == S_IDLE ||
+                        ac_chargingInfo[ac_index]->SystemStatus == S_RESERVATION) {
+                    ac_chargingInfo[ac_index]->RemoteStartFlag = YES;
+                    ShmSysConfigAndInfo->SysInfo.OrderCharging = YES;
+                    //ShmSysConfigAndInfo->SysInfo.OrderCharging = DEFAULT_AC_INDEX;
+                    //ShmOCPP16Data->CsMsg.bits[ShmSysConfigAndInfo->SysConfig.TotalConnectorCount + ac_index].RemoteStartTransactionReq = NO;
+                    DetectPluginStart(acDirIndex);
+                    return;
+                }
+                ocpp_sub_set_remote_start_transaction_req(acDirIndex, NO);
+            }
+        }
+
+        byte threeGunIndex = 0;
+        byte dcIndex = 0;
+        bool isGunUsingStatus = false;
+        byte scheduleIndex = 0;
+
+        for (byte _index = 0; _index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; _index++) {
+            // 如果有 AC 槍,且 DC 槍也有兩把
+            if (acDirIndex == 1 && _index == 1) {
+                threeGunIndex = 1;
+            }
+
+            if (ocpp_sub_get_remote_start_transaction_req(_index + threeGunIndex)) {
+                dcIndex = _index;
+            }
+
+            if (chargingInfo[_index]->SystemStatus != S_IDLE) {
+                isGunUsingStatus = true;
+            }
+
+            if (chargingInfo[_index]->schedule.isTriggerStart) {
+                scheduleIndex = _index;
+            }
+        }
+
+        // 如果是雙槍單模,只認閒置狀態的槍,如果有預約~ 則預約也算被使用
+        if (isGunUsingStatus && ShmSysConfigAndInfo->SysInfo.IsAlternatvieConf) {
+            if (dcIndex == 0) {
+                threeGunIndex = 0;
+            }
+
+            ocpp_sub_set_remote_start_transaction_req(dcIndex + threeGunIndex, NO);
+            return;
+        }
+
+        if (dcIndex == 0) {
+            threeGunIndex = 0;
+        }
+
+        if (ocpp_sub_get_remote_start_transaction_req(dcIndex + threeGunIndex)) {
+            if (chargingInfo[dcIndex]->SystemStatus == S_IDLE ||
+                    chargingInfo[dcIndex]->SystemStatus == S_RESERVATION) {
+                chargingInfo[dcIndex]->RemoteStartFlag = YES;
+                ShmSysConfigAndInfo->SysInfo.OrderCharging = YES;
+                //ShmSysConfigAndInfo->SysInfo.OrderCharging = gun_index;
+                DetectPluginStart(dcIndex);
+            }
+            ocpp_sub_set_remote_start_transaction_req(dcIndex + threeGunIndex, NO);
+        } else if (chargingInfo[scheduleIndex]->schedule.isTriggerStart) {
+            if (chargingInfo[scheduleIndex]->SystemStatus == S_IDLE ||
+                    chargingInfo[scheduleIndex]->SystemStatus == S_RESERVATION) {
+                chargingInfo[scheduleIndex]->RemoteStartFlag = YES;
+                ShmSysConfigAndInfo->SysInfo.OrderCharging = YES;
+                DetectPluginStart(scheduleIndex);
+            }
+            chargingInfo[scheduleIndex]->schedule.isTriggerStart = NO;
+        }
+    }
+}
+*/
+void ocpp_chk_update_cmd()
+{
+    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
+        if (ShmOCPP16Data->MsMsg.bits.UpdateFirmwareReq == YES) {
+            ShmOCPP16Data->MsMsg.bits.UpdateFirmwareReq = NO;
+
+            if (strcmp((char *)ShmOCPP16Data->FirmwareStatusNotification.Status, "Downloaded") == EQUAL) {
+                DEBUG_INFO_MSG("Backend : update start. \n");
+                sleep(2);
+                strcpy((char *)ShmOCPP16Data->FirmwareStatusNotification.Status, "");
+                strcpy((char *)ShmOCPP16Data->FirmwareStatusNotification.Status, "Installing");
+                ShmOCPP16Data->SpMsg.bits.FirmwareStatusNotificationReq = YES;
+                KillTask();
+
+                for (byte _index = 0; _index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; _index++) {
+                    setChargerMode(_index, MODE_UPDATE);
+                }
+                for (byte _index = 0; _index < ShmSysConfigAndInfo->SysConfig.AcConnectorCount; _index++) {
+                    ac_chargingInfo[_index]->SystemStatus = MODE_UPDATE;
+                }
+
+                byte updateResult = CheckUpdateProcess();
+
+                if (updateResult == PASS) {
+                    DEBUG_INFO_MSG("Backend : update complete. \n");
+                    strcpy((char *)ShmOCPP16Data->FirmwareStatusNotification.Status, "Installed");
+                } else if (updateResult == MODELNAME_FAIL) {
+                    DEBUG_INFO_MSG("Backend : model name is none match. \n");
+                    strcpy((char *)ShmOCPP16Data->FirmwareStatusNotification.Status, "InstallationFailed");
+                    ShmOCPP16Data->SpMsg.bits.FirmwareStatusNotificationReq = YES;
+                    sleep(5);
+                    KillAllTask();
+                    system("/usr/bin/run_evse_restart.sh");
+                    return;
+                } else {
+                    DEBUG_INFO_MSG("Backend : update fail. \n");
+                    strcpy((char *)ShmOCPP16Data->FirmwareStatusNotification.Status, "InstallationFailed");
+                }
+
+                strcpy((char *)ShmOCPP16Data->FirmwareStatusNotification.Status, "Installed");
+                ShmOCPP16Data->SpMsg.bits.FirmwareStatusNotificationReq = YES;
+                sleep(5);
+                system("reboot -f");
+            }
+        }
+    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
+        if (ShmOCPP20Data->MsMsg.bits.UpdateFirmwareReq == YES) {
+            ShmOCPP20Data->MsMsg.bits.UpdateFirmwareReq = NO;
+
+            if (strcmp((char *)ShmOCPP20Data->FirmwareStatusNotification.status, "Downloaded") == EQUAL) {
+                DEBUG_INFO_MSG("Backend : update start. \n");
+                sleep(2);
+                strcpy((char *)ShmOCPP20Data->FirmwareStatusNotification.status, "");
+                strcpy((char *)ShmOCPP20Data->FirmwareStatusNotification.status, "Installing");
+                ShmOCPP20Data->SpMsg.bits.FirmwareStatusNotificationReq = YES;
+                KillTask();
+
+                for (byte _index = 0; _index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; _index++) {
+                    setChargerMode(_index, MODE_UPDATE);
+                }
+                for (byte _index = 0; _index < ShmSysConfigAndInfo->SysConfig.AcConnectorCount; _index++) {
+                    ac_chargingInfo[_index]->SystemStatus = MODE_UPDATE;
+                }
+
+                byte updateResult = CheckUpdateProcess();
+
+                if (updateResult == PASS) {
+                    DEBUG_INFO_MSG("Backend : update complete. \n");
+                    strcpy((char *)ShmOCPP20Data->FirmwareStatusNotification.status, "Installed");
+                } else if (updateResult == MODELNAME_FAIL) {
+                    DEBUG_INFO_MSG("Backend : model name is none match. \n");
+                    strcpy((char *)ShmOCPP20Data->FirmwareStatusNotification.status, "InstallationFailed");
+                    ShmOCPP20Data->SpMsg.bits.FirmwareStatusNotificationReq = YES;
+                    sleep(5);
+                    KillAllTask();
+                    system("/usr/bin/run_evse_restart.sh");
+                    return;
+                } else {
+                    DEBUG_INFO_MSG("Backend : update fail. \n");
+                    strcpy((char *)ShmOCPP20Data->FirmwareStatusNotification.status, "InstallationFailed");
+                }
+
+                strcpy((char *)ShmOCPP20Data->FirmwareStatusNotification.status, "Installed");
+                ShmOCPP20Data->SpMsg.bits.FirmwareStatusNotificationReq = YES;
+                sleep(5);
+                system("reboot -f");
+            }
+        }
+    }
+}
+
+bool ocpp_chk_invalid_id_cmd(byte gunIndex)
+{
+    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
+        if (strstr((char *) ShmOCPP16Data->ConfigurationTable.CoreProfile[StopTransactionOnInvalidId].ItemData, "TRUE")) {
+            if (strcmp((char *)ShmOCPP16Data->StartTransaction[gunIndex].ResponseIdTagInfo.Status, "Blocked") == EQUAL ||
+                    strcmp((char *)ShmOCPP16Data->StartTransaction[gunIndex].ResponseIdTagInfo.Status, "Expired") == EQUAL ||
+                    strcmp((char *)ShmOCPP16Data->StartTransaction[gunIndex].ResponseIdTagInfo.Status, "Invalid") == EQUAL) {
+                return true;
+            }
+        }
+    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
+        if (strstr((char *) ShmOCPP20Data->ControllerComponentVariable[TxCtrlr_StopTxOnInvalidId].variableAttribute[0].value, "TRUE")) {
+            if (strcmp((char *)ShmOCPP20Data->TransactionEvent[gunIndex].Response_idTokenInfo.status, "Blocked") == EQUAL ||
+                    strcmp((char *)ShmOCPP20Data->TransactionEvent[gunIndex].Response_idTokenInfo.status, "Expired") == EQUAL ||
+                    strcmp((char *)ShmOCPP20Data->TransactionEvent[gunIndex].Response_idTokenInfo.status, "Invalid") == EQUAL ||
+                    strcmp((char *)ShmOCPP20Data->TransactionEvent[gunIndex].Response_idTokenInfo.status, "NoCredit") == EQUAL ||
+                    strcmp((char *)ShmOCPP20Data->TransactionEvent[gunIndex].Response_idTokenInfo.status, "NotAllowedTypeEVSE") == EQUAL ||
+                    strcmp((char *)ShmOCPP20Data->TransactionEvent[gunIndex].Response_idTokenInfo.status, "NotAtThisLocation") == EQUAL ||
+                    strcmp((char *)ShmOCPP20Data->TransactionEvent[gunIndex].Response_idTokenInfo.status, "NotAtThisTime") == EQUAL ||
+                    strcmp((char *)ShmOCPP20Data->TransactionEvent[gunIndex].Response_idTokenInfo.status, "Unknown") == EQUAL) {
+                return true;
+            }
+        }
+    }
+
+    return false;
+}
+
+bool ocpp_chk_profileConf_cmd(byte _index)
+{
+    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
+        if (ShmOCPP16Data->CSUMsg.bits[_index].ChargingProfileConf == YES) {
+            ShmOCPP16Data->CSUMsg.bits[_index].ChargingProfileConf = NO;
+            return true;
+        }
+    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
+        if (ShmOCPP20Data->CSUMsg.bits[_index].ChargingProfileConf == YES) {
+            ShmOCPP20Data->CSUMsg.bits[_index].ChargingProfileConf = NO;
+            return true;
+        }
+    }
+
+    return false;
+}
+
+void ocpp_lift_profileReq_cmd(byte gunIndex)
+{
+    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
+        if (ShmOCPP16Data->CSUMsg.bits[gunIndex].ChargingProfileConf == NO) {
+            if (ShmOCPP16Data->CSUMsg.bits[gunIndex].ChargingProfileReq == NO) {
+                ShmOCPP16Data->CSUMsg.bits[gunIndex].ChargingProfileReq = YES;
+            }
+        }
+    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
+        if (ShmOCPP20Data->CSUMsg.bits[gunIndex].ChargingProfileConf == NO) {
+            if (ShmOCPP20Data->CSUMsg.bits[gunIndex].ChargingProfileReq == NO) {
+                ShmOCPP20Data->CSUMsg.bits[gunIndex].ChargingProfileReq = YES;
+            }
+        }
+    }
+}
+
+void ocpp_set_startTransation_cmd(byte gunIndex)
+{
+    byte _OcppGunIndex = gunIndex;
+
+    // 如果有 AC 槍,而現在是 DC 第二把槍進入充電
+    if (ShmSysConfigAndInfo->SysConfig.AcConnectorCount == 1 && gunIndex == 1) {
+        _OcppGunIndex = 2;
+    }
+
+    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
+        if (strcmp((char *)chargingInfo[gunIndex]->StartUserId, "") == EQUAL) {
+            strcpy((char *)ShmOCPP16Data->StartTransaction[_OcppGunIndex].IdTag, (char *)ShmOCPP16Data->StartTransaction[_OcppGunIndex].IdTag);
+        } else {
+            strcpy((char *)ShmOCPP16Data->StartTransaction[_OcppGunIndex].IdTag, (char *)chargingInfo[gunIndex]->StartUserId);
+        }
+
+        PRINTF_FUNC("IdTag = %s \n", ShmOCPP16Data->StartTransaction[_OcppGunIndex].IdTag);
+        ShmOCPP16Data->CpMsg.bits[_OcppGunIndex].StartTransactionReq = YES;
+    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
+        if (strcmp((char *)chargingInfo[gunIndex]->StartUserId, "") == EQUAL) {
+            strcpy((char *)ShmOCPP20Data->TransactionEvent[_OcppGunIndex].idToken.idToken, (char *)ShmOCPP20Data->TransactionEvent[_OcppGunIndex].idToken.idToken);
+        } else {
+            strcpy((char *)ShmOCPP20Data->TransactionEvent[_OcppGunIndex].idToken.idToken, (char *)chargingInfo[gunIndex]->StartUserId);
+        }
+
+        PRINTF_FUNC("IdTag = %s \n", ShmOCPP20Data->TransactionEvent[_OcppGunIndex].idToken.idToken);
+        ShmOCPP20Data->CpMsg.bits[_OcppGunIndex].TransactionEventReq = YES;
+    }
+}
+
+void ocpp_set_stopTransation_cmd(byte gunIndex)
+{
+    byte _OcppGunIndex = gunIndex;
+
+    // 如果有 AC 槍,而現在是 DC 第二把槍進入充電
+    if (ShmSysConfigAndInfo->SysConfig.AcConnectorCount == 1 && gunIndex == 1) {
+        _OcppGunIndex = 2;
+    }
+
+    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
+        if (strcmp((char *)chargingInfo[gunIndex]->StartUserId, "") == EQUAL) {
+            strcpy((char *)ShmOCPP16Data->StopTransaction[_OcppGunIndex].IdTag, (char *)ShmOCPP16Data->StopTransaction[_OcppGunIndex].IdTag);
+        } else {
+            strcpy((char *)ShmOCPP16Data->StopTransaction[_OcppGunIndex].IdTag, (char *)chargingInfo[gunIndex]->StartUserId);
+        }
+
+        PRINTF_FUNC("IdTag = %s \n", ShmOCPP16Data->StopTransaction[_OcppGunIndex].IdTag);
+        ShmOCPP16Data->CpMsg.bits[_OcppGunIndex].StopTransactionReq = YES;
+    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
+        if (strcmp((char *)chargingInfo[gunIndex]->StartUserId, "") == EQUAL) {
+            strcpy((char *)ShmOCPP20Data->TransactionEvent[_OcppGunIndex].idToken.idToken, (char *)ShmOCPP20Data->TransactionEvent[_OcppGunIndex].idToken.idToken);
+        } else {
+            strcpy((char *)ShmOCPP20Data->TransactionEvent[_OcppGunIndex].idToken.idToken, (char *)chargingInfo[gunIndex]->StartUserId);
+        }
+
+        PRINTF_FUNC("IdTag = %s \n", ShmOCPP20Data->TransactionEvent[_OcppGunIndex].idToken.idToken);
+        ShmOCPP20Data->CpMsg.bits[_OcppGunIndex].TransactionEventReq = YES;
+    }
+}
+
+void ocpp_set_errorCode_cmd(byte gunIndex, char *errString)
+{
+    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
+        strcpy((char *)ShmOCPP16Data->StatusNotification[gunIndex].ErrorCode, errString);
+    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
+
+    }
+}
+
+void ocpp_set_stopReason_by_cmd(byte gunIndex, char *reason)
+{
+    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
+        if (strcmp((char *)ShmOCPP16Data->StopTransaction[gunIndex].StopReason, "") == EQUAL) {
+            strcpy((char *)ShmOCPP16Data->StopTransaction[gunIndex].StopReason, reason);
+        }
+    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
+        if (strcmp((char *)ShmOCPP20Data->TransactionEvent[gunIndex].transactionInfo.stoppedReason, "") == EQUAL) {
+            strcpy((char *)ShmOCPP20Data->TransactionEvent[gunIndex].transactionInfo.stoppedReason, reason);
+        }
+    }
+}
+
+void ocpp_set_authorizeReq_cmd(byte value)
+{
+    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
+        ShmOCPP16Data->SpMsg.bits.AuthorizeReq = value;
+    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
+        ShmOCPP20Data->SpMsg.bits.AuthorizeReq = value;
+    }
+}
+
+void ocpp_set_authorizeConf_cmd(byte value)
+{
+    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
+        ShmOCPP16Data->SpMsg.bits.AuthorizeConf = value;
+    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
+        ShmOCPP20Data->SpMsg.bits.AuthorizeConf = value;
+    }
+}
+
+void ocpp_set_errCode_cmd(byte gunIndex)
+{
+    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
+        if (strcmp((char *)chargingInfo[gunIndex]->ConnectorAlarmCode, "") != EQUAL) {
+            strcpy((char *)ShmOCPP16Data->StatusNotification[gunIndex].ErrorCode, "InternalError");
+            strcpy((char *)ShmOCPP16Data->StatusNotification[gunIndex].VendorErrorCode, (char *)chargingInfo[gunIndex]->ConnectorAlarmCode);
+        } else if (strcmp((char *)chargingInfo[gunIndex]->EvConnAlarmCode, "") != EQUAL) {
+            strcpy((char *)ShmOCPP16Data->StatusNotification[gunIndex].ErrorCode, "OtherError");
+            strcpy((char *)ShmOCPP16Data->StatusNotification[gunIndex].VendorErrorCode, (char *)chargingInfo[gunIndex]->EvConnAlarmCode);
+        }
+    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
+
+    }
+}
+
+void ocpp_clear_errorCode_cmd(byte gunIndex)
+{
+    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
+        if (strcmp((char *)ShmOCPP16Data->StatusNotification[gunIndex].ErrorCode, "NoError") != EQUAL) {
+            strcpy((char *)ShmOCPP16Data->StatusNotification[gunIndex].ErrorCode, "NoError");
+        }
+
+        if (strcmp((char *)ShmOCPP16Data->StatusNotification[gunIndex].VendorErrorCode, "") != EQUAL) {
+            strcpy((char *)ShmOCPP16Data->StatusNotification[gunIndex].VendorErrorCode, "");
+        }
+    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
+
+    }
+}
+
+void ocpp_clear_idTag_cmd(byte gun_index)
+{
+    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
+        strcpy((char *)ShmOCPP16Data->StartTransaction[gun_index].ResponseIdTagInfo.Status, "");
+    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
+        strcpy((char *)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "");
+    }
+}
+
+void ocpp_clear_stopReason(byte gun_index)
+{
+    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
+        strcpy((char *)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "");
+    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
+        strcpy((char *)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "");
+    }
+}
+
+unsigned short _ocpp_get_connect_timeout()
+{
+    uint16_t result = (TIMEOUT_SPEC_HANDSHAKING / 1000);
+
+    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
+        if (strcmp((char *)ShmOCPP16Data->ConfigurationTable.CoreProfile[ConnectionTimeOut].ItemData, "") != 0) {
+            result = atoi((char *)ShmOCPP16Data->ConfigurationTable.CoreProfile[ConnectionTimeOut].ItemData);
+        }
+    }
+
+    else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
+        if (strcmp((char *)ShmOCPP20Data->ControllerComponentVariable[TxCtrlr_EVConnectionTimeOut].variableAttribute[0].value, "") != 0) {
+            result = atoi((char *)ShmOCPP20Data->ControllerComponentVariable[TxCtrlr_EVConnectionTimeOut].variableAttribute[0].value);
+        }
+    }
+
+    return result;
+}
+
+bool _ocpp_get_disconnect_policy()
+{
+    bool result = false;
+
+    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
+        if (strcmp((char *)ShmOCPP16Data->ConfigurationTable.CoreProfile[AllowOfflineTxForUnknownId].ItemData, "TRUE") == EQUAL &&
+                strcmp((char *)ShmOCPP16Data->ConfigurationTable.CoreProfile[LocalAuthorizeOffline].ItemData, "TRUE") == EQUAL) {
+            result = true;
+        }
+    }
+
+    else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
+        if (strcmp((char *)ShmOCPP20Data->ControllerComponentVariable[LocalAuthorizeOffline].variableAttribute[0].value, "") == EQUAL &&
+                strcmp((char *)ShmOCPP20Data->ControllerComponentVariable[AuthCtrlr_LocalAuthorizeOffline].variableAttribute[0].value, "") == EQUAL) {
+            result = true;
+        }
+    }
+
+    return result;
+}
+
+bool ocpp_get_authorize_conf()
+{
+    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
+        return ShmOCPP16Data->SpMsg.bits.AuthorizeConf;
+    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
+        return ShmOCPP20Data->SpMsg.bits.AuthorizeConf;
+    }
+
+    return false;
+}
+
+bool ocpp_get_startTransation_req(byte gunIndex)
+{
+    bool result = false;
+
+    // 如果有 AC 槍,而現在是 DC 第二把槍進入充電
+    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
+        result = ShmOCPP16Data->CpMsg.bits[gunIndex].StartTransactionReq;
+    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
+        result = ShmOCPP20Data->CpMsg.bits[gunIndex].TransactionEventReq;
+    }
+
+    return result;
+}
+
+void ocpp_chargingProfile_process(byte _index)
+{
+    int _time = 0;
+    int _startCount = NO_DEFINE;
+    int _maxCount = 0;
+
+    if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16) {
+        if (strcmp((char *)ShmOCPP16Data->SmartChargingProfile[_index].ChargingProfileKind, "Absolute") == EQUAL &&
+                ShmOCPP16Data->SmartChargingProfile[_index].ChargingProfileId == YES) {
+            _time = GetStartScheduleTime(ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.StartSchedule);
+            _maxCount = ARRAY_SIZE(ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.ChargingSchedulePeriod);
+            _startCount = NO_DEFINE;
+
+            for (byte _count = 0; _count < _maxCount; _count++) {
+                // 預設最小輸出電流 (MIN_OUTPUT_CUR) A
+                if (_time >= ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.ChargingSchedulePeriod[_count].StartPeriod) {
+                    if ((_count == 0 && ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.ChargingSchedulePeriod[_count].Limit >= MIN_OUTPUT_CUR) ||
+                            ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.ChargingSchedulePeriod[_count].Limit > MIN_OUTPUT_CUR) {
+                        _startCount = _count;
+                    }
+                }
+            }
+
+            PRINTF_FUNC("Gun_%d, Get Profile - Profile Index = %d \n", _index, _startCount);
+            if (_startCount < _maxCount) {
+                PRINTF_FUNC("Profile Limit = %f \n", ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.ChargingSchedulePeriod[_startCount].Limit);
+                chargingInfo[_index]->ChargingProfilePower = ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.ChargingSchedulePeriod[_startCount].Limit * AC_OUTPUT_VOL * ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.ChargingSchedulePeriod[_startCount].NumberPhases;
+                if (chargingInfo[_index]->EvBatterytargetVoltage > 0 &&
+                        chargingInfo[_index]->PresentChargingVoltage > 0) {
+                    chargingInfo[_index]->ChargingProfileCurrent = (chargingInfo[_index]->ChargingProfilePower / chargingInfo[_index]->PresentChargingVoltage) * 10;
+                } else {
+                    chargingInfo[_index]->ChargingProfileCurrent = 0;
+                }
+            } else {
+                chargingInfo[_index]->ChargingProfilePower = -1;
+                chargingInfo[_index]->ChargingProfileCurrent = -1;
+            }
+        } else {
+            chargingInfo[_index]->ChargingProfilePower = -1;
+            chargingInfo[_index]->ChargingProfileCurrent = -1;
+        }
+    } else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20) {
+        if (strcmp((char *)ShmOCPP20Data->SmartChargingProfile[_index].chargingProfileKind, "Absolute") == EQUAL &&
+                ShmOCPP20Data->SmartChargingProfile[_index].id == YES) {
+            _time = GetStartScheduleTime(ShmOCPP20Data->SmartChargingProfile[_index].chargingSchedule[0].startSchedule);
+            _maxCount = ARRAY_SIZE(ShmOCPP20Data->SmartChargingProfile[_index].chargingSchedule[0].chargingSchedulePeriod);
+            _startCount = NO_DEFINE;
+
+            for (byte _count = 0; _count < _maxCount; _count++) {
+                // 預設最小輸出電流 (MIN_OUTPUT_CUR) A
+                if (_time >= ShmOCPP20Data->SmartChargingProfile[_index].chargingSchedule[0].chargingSchedulePeriod[_count].startPeriod) {
+                    if ((_count == 0 && ShmOCPP20Data->SmartChargingProfile[_index].chargingSchedule[0].chargingSchedulePeriod[_count].limit >= MIN_OUTPUT_CUR) ||
+                            ShmOCPP20Data->SmartChargingProfile[_index].chargingSchedule[0].chargingSchedulePeriod[_count].limit > MIN_OUTPUT_CUR) {
+                        _startCount = _count;
+                    }
+                }
+            }
+
+            PRINTF_FUNC("Gun_%d, Get Profile - Profile Index = %d \n", _index, _startCount);
+            if (_startCount < _maxCount) {
+                PRINTF_FUNC("Profile Limit = %f \n", ShmOCPP20Data->SmartChargingProfile[_index].chargingSchedule[0].chargingSchedulePeriod[_startCount].limit);
+                chargingInfo[_index]->ChargingProfilePower = ShmOCPP20Data->SmartChargingProfile[_index].chargingSchedule[0].chargingSchedulePeriod[_startCount].limit * AC_OUTPUT_VOL;
+                if (chargingInfo[_index]->EvBatterytargetVoltage > 0 && chargingInfo[_index]->PresentChargingVoltage > 0) {
+                    chargingInfo[_index]->ChargingProfileCurrent = (chargingInfo[_index]->ChargingProfilePower / chargingInfo[_index]->PresentChargingVoltage) * 10;
+                } else {
+                    chargingInfo[_index]->ChargingProfileCurrent = 0;
+                }
+            } else {
+                chargingInfo[_index]->ChargingProfilePower = -1;
+                chargingInfo[_index]->ChargingProfileCurrent = -1;
+            }
+        } else {
+            chargingInfo[_index]->ChargingProfilePower = -1;
+            chargingInfo[_index]->ChargingProfileCurrent = -1;
+        }
+    } else {
+        chargingInfo[_index]->ChargingProfilePower = -1;
+        chargingInfo[_index]->ChargingProfileCurrent = -1;
+    }
+
+    PRINTF_FUNC("Profile : ChargingProfilePower = %f \n", chargingInfo[_index]->ChargingProfilePower);
+    PRINTF_FUNC("Profile : ChargingProfileCurrent = %f \n", chargingInfo[_index]->ChargingProfileCurrent);
+}

+ 214 - 214
EVSE/Projects/DD360Tcci/Apps/CSU/Primary.c

@@ -1,214 +1,214 @@
-#include <stdio.h>      /*標準輸入輸出定義*/
-#include <stdlib.h>     /*標準函數庫定義*/
-#include <string.h>
-#include <stdint.h>
-
-#include "../Config.h"
-#include "../Log/log.h"
-#include "../Define/define.h"
-#include "../ShareMemory/shmMem.h"
-
-#include "../SelectGun/SelectGun.h"
-#include "main.h"
-#include "../timeout.h"
-struct SysInfoData *pSysInfo = NULL;
-struct ChargingInfoData *pDcChargingInfo = NULL;
-struct SysConfigData *pSysConfig = NULL;
-//------------------------------------------------------------------------------
-
-//------------------------------------------------------------------------------
-void ChangeLCM(uint8_t page)
-{
-    pSysInfo->SystemPage = page;
-}
-// ***********************************
-// Enter LCM Page
-// ***********************************
-void CheckLeftButton()
-{
-    pSysInfo->CurGunSelected = LEFT_GUN_NUM;
-    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(pSysInfo->CurGunSelected);
-    if(pSysInfo->SystemPage == _PAGE_SELECT_GUN) {
-    	pSysInfo->SystemPage = _PAGE_BILL;
-    	return;
-    }
-    if(pDcChargingInfo->SystemStatus == S_IDLE) {
-    	pSysInfo->SystemPage = _PAGE_SELECT_GUN;
-    }
-}
-void CheckRightButton()
-{
-    pSysInfo->CurGunSelected = RIGHT_GUN_NUM;
-    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(pSysInfo->CurGunSelected);
-    if(pSysInfo->SystemPage == _PAGE_SELECT_GUN) {
-    	pSysInfo->SystemPage = _PAGE_BILL;
-    	return;
-    }
-    if(pDcChargingInfo->SystemStatus == S_IDLE) {
-		pSysInfo->SystemPage = _PAGE_SELECT_GUN;
-	}
-}
-void CheckPrimaryWarm(void)
-{
-    uint8_t i = 0;
-    uint8_t Rtn = 0;
-    struct WARNING_CODE_INFO *pSysWarning = (struct WARNING_CODE_INFO *)GetShmSysWarningInfo();
-    struct PrimaryMcuData *ShmPrimaryMcuData = (struct PrimaryMcuData *)GetShmPrimaryMcuData();
-    struct AlarmCodeData *pAlarmCode = (struct AlarmCodeData *)GetShmAlarmCodeData();
-    DcCommonInfo *ShmDcCommonData = (DcCommonInfo *)GetShmDcCommonData();
-    if (pSysWarning->WarningCount > 0) {
-        Rtn = 0;
-        for (i = 0; i < pSysWarning->WarningCount; i++) {
-            if (memcmp(&pSysWarning->WarningCode[i][0], "042251", 6) == 0) {
-                EmcOccureByString("042251");
-                ShmDcCommonData->PowerAlarmState.StatusBit.EmergencyStop = YES;
-                Rtn = 1;
-            } else if (memcmp(&pSysWarning->WarningCode[i][0], "042252", 6) == 0) {
-                ShmDcCommonData->PowerAlarmState.StatusBit.DoorOpen = YES;
-                EmcOccureByString("042252");
-                Rtn = 1;
-            } else if (memcmp(&pSysWarning->WarningCode[i][0], "042327", 6) == 0) {
-                ShmDcCommonData->PowerAlarmState.StatusBit.DcInputOVP = YES;
-                EmcOccureByString("042327");
-                Rtn = 1;
-            } else if (memcmp(&pSysWarning->WarningCode[i][0], "042328", 6) == 0) {
-			   ShmDcCommonData->PowerAlarmState.StatusBit.DcInputUVP = YES;
-			   EmcOccureByString("042328");
-			   Rtn = 1;
-		    } else if (memcmp(&pSysWarning->WarningCode[i][0], "042200", 6) == 0) {
-                ShmDcCommonData->PowerAlarmState.StatusBit.SystemL1InputOVP = YES;
-                EmcOccureByString("042200");
-                Rtn = 1;
-            } else if (memcmp(&pSysWarning->WarningCode[i][0], "042201", 6) == 0) {
-                ShmDcCommonData->PowerAlarmState.StatusBit.SystemL2InputOVP = YES;
-                EmcOccureByString("042201");
-                Rtn = 1;
-            } else if (memcmp(&pSysWarning->WarningCode[i][0], "042202", 6) == 0) {
-                ShmDcCommonData->PowerAlarmState.StatusBit.SystemL3InputOVP = YES;
-                EmcOccureByString("042202");
-                Rtn = 1;
-            } else if (memcmp(&pSysWarning->WarningCode[i][0], "042267", 6) == 0) {
-                ShmDcCommonData->PowerAlarmState.StatusBit.PsuFailure = YES;
-                EmcOccureByString("042267");
-                Rtn = 1;
-            } else if (memcmp(&pSysWarning->WarningCode[i][0], "012304", 6) == 0) {
-                EmcOccureByString("012304");
-                Rtn = 1;
-            }
-        }
-
-        if (Rtn == 0) {
-            ShmDcCommonData->PowerAlarmState.StatusBit.EmergencyStop = NO;
-            ShmDcCommonData->PowerAlarmState.StatusBit.DoorOpen = NO;
-            ShmDcCommonData->PowerAlarmState.StatusBit.DcInputOVP = NO;
-            ShmDcCommonData->PowerAlarmState.StatusBit.DcInputUVP = NO;
-            ShmDcCommonData->PowerAlarmState.StatusBit.SystemL1InputOVP = NO;
-            ShmDcCommonData->PowerAlarmState.StatusBit.SystemL2InputOVP = NO;
-            ShmDcCommonData->PowerAlarmState.StatusBit.SystemL3InputOVP = NO;
-            ShmDcCommonData->PowerAlarmState.StatusBit.PsuFailure = NO;
-            ReleaseEmsOccureByString(0, "042251");
-            ReleaseEmsOccureByString(0, "042252");
-            ReleaseEmsOccureByString(0, "042200");
-            ReleaseEmsOccureByString(0, "042327");
-            ReleaseEmsOccureByString(0, "042328");
-            ReleaseEmsOccureByString(0, "042201");
-            ReleaseEmsOccureByString(0, "042202");
-            ReleaseEmsOccureByString(0, "042267");
-            ReleaseEmsOccureByString(0, "012304");
-        }
-    } else {
-        ShmDcCommonData->PowerAlarmState.StatusBit.EmergencyStop = NO;
-        ShmDcCommonData->PowerAlarmState.StatusBit.DoorOpen = NO;
-        ShmDcCommonData->PowerAlarmState.StatusBit.DcInputOVP = NO;
-        ShmDcCommonData->PowerAlarmState.StatusBit.DcInputUVP = NO;
-        ShmDcCommonData->PowerAlarmState.StatusBit.SystemL1InputOVP = NO;
-        ShmDcCommonData->PowerAlarmState.StatusBit.SystemL2InputOVP = NO;
-        ShmDcCommonData->PowerAlarmState.StatusBit.SystemL3InputOVP = NO;
-        ShmDcCommonData->PowerAlarmState.StatusBit.PsuFailure = NO;
-        ReleaseEmsOccureByString(0, "042251");
-        ReleaseEmsOccureByString(0, "042252");
-        ReleaseEmsOccureByString(0, "042200");
-        ReleaseEmsOccureByString(0, "042327");
-        ReleaseEmsOccureByString(0, "042328");
-        ReleaseEmsOccureByString(0, "042201");
-        ReleaseEmsOccureByString(0, "042202");
-        ReleaseEmsOccureByString(0, "042267");
-        ReleaseEmsOccureByString(0, "012304");
-    }
-
-    if (ShmPrimaryMcuData->InputDet.bits.EmergencyButton == ABNORMAL) {
-        pAlarmCode->AlarmEvents.bits.EmergencyStopTrip = YES;
-        EmcOccureByString("012251");
-    } else {
-        ReleaseEmsOccureByString(0, "012251");
-    }
-
-    if (ShmPrimaryMcuData->InputDet.bits.AcMainBreakerDetec == ABNORMAL) {
-        pAlarmCode->AlarmEvents.bits.MainPowerBreakerTrip = YES;
-        EmcOccureByString("012238");
-    } else {
-        ReleaseEmsOccureByString(0, "012238");
-    }
-
-    if (ShmPrimaryMcuData->InputDet.bits.SpdDetec == ABNORMAL) {
-        pAlarmCode->AlarmEvents.bits.SpdTrip = YES;
-    } else {
-        pAlarmCode->AlarmEvents.bits.SpdTrip = NO;
-    }
-
-    if (ShmPrimaryMcuData->InputDet.bits.DoorOpen == ABNORMAL) {
-        pAlarmCode->AlarmEvents.bits.DoorOpen = YES;
-        EmcOccureByString("012252");
-    } else {
-        ReleaseEmsOccureByString(0, "012252");
-    }
-}
-void ChkPrimaryStatus(void)
-{
-    static bool leftBtnPush = false;
-    static bool rightBtnPush = false;
-    pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
-    struct PrimaryMcuData *ShmPrimaryMcuData = (struct PrimaryMcuData *)GetShmPrimaryMcuData();
-    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(pSysInfo->CurGunSelected);
-    pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
-
-    // Check Primary Board status
-    CheckPrimaryWarm();
-    if ((pDcChargingInfo->SystemStatus == S_IDLE || pDcChargingInfo->SystemStatus == S_RESERVATION)
-            && pSysConfig->OfflinePolicy == _OFFLINE_POLICY_NO_CHARGING) {
-        log_info("Offline policy no charge");
-        return;;
-    }
-
-    // Show Version
-    if (ShmPrimaryMcuData->InputDet.bits.Button1 == BTN_PRESS &&
-            ShmPrimaryMcuData->InputDet.bits.Button2 == BTN_PRESS )
-        pSysConfig->ShowInformation = YES;
-    else
-        pSysConfig->ShowInformation = NO;
-    if (pSysConfig->ShowInformation)
-        return;
-    return;
-    // Press Left Button
-    if (ShmPrimaryMcuData->InputDet.bits.Button1 == BTN_PRESS && !leftBtnPush ) {
-    	if (pSysInfo->SystemPage >= _PAGE_ADD_FRIEND && pSysInfo->SystemPage <= _PAGE_PLUGIN) {
-    		log_info("Authorize Process can't select gun");
-    		return;
-    	}
-        leftBtnPush = true;
-        CheckLeftButton();
-        log_info("left btn down...............................%x %x %x",
-                pSysInfo->CurGunSelected,pDcChargingInfo->SystemStatus,pSysInfo->SystemPage);
-    } else if (ShmPrimaryMcuData->InputDet.bits.Button1 == BTN_RELEASE && leftBtnPush) {
-        leftBtnPush = false;
-    }
-    // Press Right Button
-    if (ShmPrimaryMcuData->InputDet.bits.Button2 == BTN_PRESS && !rightBtnPush ) {
-        rightBtnPush = true;
-        CheckRightButton();
-        log_info("right btn down...............................%x %x %x",
-               pSysInfo->CurGunSelected,pDcChargingInfo->SystemStatus, pSysInfo->SystemPage);
-    } else if (ShmPrimaryMcuData->InputDet.bits.Button2 == BTN_RELEASE && rightBtnPush) {
-        rightBtnPush = false;
-    }
-}
+#include <stdio.h>      /*標準輸入輸出定義*/
+#include <stdlib.h>     /*標準函數庫定義*/
+#include <string.h>
+#include <stdint.h>
+
+#include "../Config.h"
+#include "../Log/log.h"
+#include "../Define/define.h"
+#include "../ShareMemory/shmMem.h"
+
+#include "../SelectGun/SelectGun.h"
+#include "main.h"
+#include "../timeout.h"
+struct SysInfoData *pSysInfo = NULL;
+struct ChargingInfoData *pDcChargingInfo = NULL;
+struct SysConfigData *pSysConfig = NULL;
+//------------------------------------------------------------------------------
+
+//------------------------------------------------------------------------------
+void ChangeLCM(uint8_t page)
+{
+    pSysInfo->SystemPage = page;
+}
+// ***********************************
+// Enter LCM Page
+// ***********************************
+void CheckLeftButton()
+{
+    pSysInfo->CurGunSelected = LEFT_GUN_NUM;
+    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(pSysInfo->CurGunSelected);
+    if(pSysInfo->SystemPage == _PAGE_SELECT_GUN) {
+    	pSysInfo->SystemPage = _PAGE_BILL;
+    	return;
+    }
+    if(pDcChargingInfo->SystemStatus == S_IDLE) {
+    	pSysInfo->SystemPage = _PAGE_SELECT_GUN;
+    }
+}
+void CheckRightButton()
+{
+    pSysInfo->CurGunSelected = RIGHT_GUN_NUM;
+    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(pSysInfo->CurGunSelected);
+    if(pSysInfo->SystemPage == _PAGE_SELECT_GUN) {
+    	pSysInfo->SystemPage = _PAGE_BILL;
+    	return;
+    }
+    if(pDcChargingInfo->SystemStatus == S_IDLE) {
+		pSysInfo->SystemPage = _PAGE_SELECT_GUN;
+	}
+}
+void CheckPrimaryWarm(void)
+{
+    uint8_t i = 0;
+    uint8_t Rtn = 0;
+    struct WARNING_CODE_INFO *pSysWarning = (struct WARNING_CODE_INFO *)GetShmSysWarningInfo();
+    struct PrimaryMcuData *ShmPrimaryMcuData = (struct PrimaryMcuData *)GetShmPrimaryMcuData();
+    struct AlarmCodeData *pAlarmCode = (struct AlarmCodeData *)GetShmAlarmCodeData();
+    DcCommonInfo *ShmDcCommonData = (DcCommonInfo *)GetShmDcCommonData();
+    if (pSysWarning->WarningCount > 0) {
+        Rtn = 0;
+        for (i = 0; i < pSysWarning->WarningCount; i++) {
+            if (memcmp(&pSysWarning->WarningCode[i][0], "042251", 6) == 0) {
+                EmcOccureByString("042251");
+                ShmDcCommonData->PowerAlarmState.StatusBit.EmergencyStop = YES;
+                Rtn = 1;
+            } else if (memcmp(&pSysWarning->WarningCode[i][0], "042252", 6) == 0) {
+                ShmDcCommonData->PowerAlarmState.StatusBit.DoorOpen = YES;
+                EmcOccureByString("042252");
+                Rtn = 1;
+            } else if (memcmp(&pSysWarning->WarningCode[i][0], "042327", 6) == 0) {
+                ShmDcCommonData->PowerAlarmState.StatusBit.DcInputOVP = YES;
+                EmcOccureByString("042327");
+                Rtn = 1;
+            } else if (memcmp(&pSysWarning->WarningCode[i][0], "042328", 6) == 0) {
+			   ShmDcCommonData->PowerAlarmState.StatusBit.DcInputUVP = YES;
+			   EmcOccureByString("042328");
+			   Rtn = 1;
+		    } else if (memcmp(&pSysWarning->WarningCode[i][0], "042200", 6) == 0) {
+                ShmDcCommonData->PowerAlarmState.StatusBit.SystemL1InputOVP = YES;
+                EmcOccureByString("042200");
+                Rtn = 1;
+            } else if (memcmp(&pSysWarning->WarningCode[i][0], "042201", 6) == 0) {
+                ShmDcCommonData->PowerAlarmState.StatusBit.SystemL2InputOVP = YES;
+                EmcOccureByString("042201");
+                Rtn = 1;
+            } else if (memcmp(&pSysWarning->WarningCode[i][0], "042202", 6) == 0) {
+                ShmDcCommonData->PowerAlarmState.StatusBit.SystemL3InputOVP = YES;
+                EmcOccureByString("042202");
+                Rtn = 1;
+            } else if (memcmp(&pSysWarning->WarningCode[i][0], "042267", 6) == 0) {
+                ShmDcCommonData->PowerAlarmState.StatusBit.PsuFailure = YES;
+                EmcOccureByString("042267");
+                Rtn = 1;
+            } else if (memcmp(&pSysWarning->WarningCode[i][0], "012304", 6) == 0) {
+                EmcOccureByString("012304");
+                Rtn = 1;
+            }
+        }
+
+        if (Rtn == 0) {
+            ShmDcCommonData->PowerAlarmState.StatusBit.EmergencyStop = NO;
+            ShmDcCommonData->PowerAlarmState.StatusBit.DoorOpen = NO;
+            ShmDcCommonData->PowerAlarmState.StatusBit.DcInputOVP = NO;
+            ShmDcCommonData->PowerAlarmState.StatusBit.DcInputUVP = NO;
+            ShmDcCommonData->PowerAlarmState.StatusBit.SystemL1InputOVP = NO;
+            ShmDcCommonData->PowerAlarmState.StatusBit.SystemL2InputOVP = NO;
+            ShmDcCommonData->PowerAlarmState.StatusBit.SystemL3InputOVP = NO;
+            ShmDcCommonData->PowerAlarmState.StatusBit.PsuFailure = NO;
+            ReleaseEmsOccureByString(0, "042251");
+            ReleaseEmsOccureByString(0, "042252");
+            ReleaseEmsOccureByString(0, "042200");
+            ReleaseEmsOccureByString(0, "042327");
+            ReleaseEmsOccureByString(0, "042328");
+            ReleaseEmsOccureByString(0, "042201");
+            ReleaseEmsOccureByString(0, "042202");
+            ReleaseEmsOccureByString(0, "042267");
+            ReleaseEmsOccureByString(0, "012304");
+        }
+    } else {
+        ShmDcCommonData->PowerAlarmState.StatusBit.EmergencyStop = NO;
+        ShmDcCommonData->PowerAlarmState.StatusBit.DoorOpen = NO;
+        ShmDcCommonData->PowerAlarmState.StatusBit.DcInputOVP = NO;
+        ShmDcCommonData->PowerAlarmState.StatusBit.DcInputUVP = NO;
+        ShmDcCommonData->PowerAlarmState.StatusBit.SystemL1InputOVP = NO;
+        ShmDcCommonData->PowerAlarmState.StatusBit.SystemL2InputOVP = NO;
+        ShmDcCommonData->PowerAlarmState.StatusBit.SystemL3InputOVP = NO;
+        ShmDcCommonData->PowerAlarmState.StatusBit.PsuFailure = NO;
+        ReleaseEmsOccureByString(0, "042251");
+        ReleaseEmsOccureByString(0, "042252");
+        ReleaseEmsOccureByString(0, "042200");
+        ReleaseEmsOccureByString(0, "042327");
+        ReleaseEmsOccureByString(0, "042328");
+        ReleaseEmsOccureByString(0, "042201");
+        ReleaseEmsOccureByString(0, "042202");
+        ReleaseEmsOccureByString(0, "042267");
+        ReleaseEmsOccureByString(0, "012304");
+    }
+
+    if (ShmPrimaryMcuData->InputDet.bits.EmergencyButton == ABNORMAL) {
+        pAlarmCode->AlarmEvents.bits.EmergencyStopTrip = YES;
+        EmcOccureByString("012251");
+    } else {
+        ReleaseEmsOccureByString(0, "012251");
+    }
+
+    if (ShmPrimaryMcuData->InputDet.bits.AcMainBreakerDetec == ABNORMAL) {
+        pAlarmCode->AlarmEvents.bits.MainPowerBreakerTrip = YES;
+        EmcOccureByString("012238");
+    } else {
+        ReleaseEmsOccureByString(0, "012238");
+    }
+
+    if (ShmPrimaryMcuData->InputDet.bits.SpdDetec == ABNORMAL) {
+        pAlarmCode->AlarmEvents.bits.SpdTrip = YES;
+    } else {
+        pAlarmCode->AlarmEvents.bits.SpdTrip = NO;
+    }
+
+    if (ShmPrimaryMcuData->InputDet.bits.DoorOpen == ABNORMAL) {
+        pAlarmCode->AlarmEvents.bits.DoorOpen = YES;
+        EmcOccureByString("012252");
+    } else {
+        ReleaseEmsOccureByString(0, "012252");
+    }
+}
+void ChkPrimaryStatus(void)
+{
+    static bool leftBtnPush = false;
+    static bool rightBtnPush = false;
+    pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
+    struct PrimaryMcuData *ShmPrimaryMcuData = (struct PrimaryMcuData *)GetShmPrimaryMcuData();
+    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(pSysInfo->CurGunSelected);
+    pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
+
+    // Check Primary Board status
+    CheckPrimaryWarm();
+    if ((pDcChargingInfo->SystemStatus == S_IDLE || pDcChargingInfo->SystemStatus == S_RESERVATION)
+            && pSysConfig->OfflinePolicy == _OFFLINE_POLICY_NO_CHARGING) {
+        log_info("Offline policy no charge");
+        return;;
+    }
+
+    // Show Version
+    if (ShmPrimaryMcuData->InputDet.bits.Button1 == BTN_PRESS &&
+            ShmPrimaryMcuData->InputDet.bits.Button2 == BTN_PRESS )
+        pSysConfig->ShowInformation = YES;
+    else
+        pSysConfig->ShowInformation = NO;
+    if (pSysConfig->ShowInformation)
+        return;
+    return;
+    // Press Left Button
+    if (ShmPrimaryMcuData->InputDet.bits.Button1 == BTN_PRESS && !leftBtnPush ) {
+    	if (pSysInfo->SystemPage >= _PAGE_ADD_FRIEND && pSysInfo->SystemPage <= _PAGE_PLUGIN) {
+    		log_info("Authorize Process can't select gun");
+    		return;
+    	}
+        leftBtnPush = true;
+        CheckLeftButton();
+        log_info("left btn down...............................%x %x %x",
+                pSysInfo->CurGunSelected,pDcChargingInfo->SystemStatus,pSysInfo->SystemPage);
+    } else if (ShmPrimaryMcuData->InputDet.bits.Button1 == BTN_RELEASE && leftBtnPush) {
+        leftBtnPush = false;
+    }
+    // Press Right Button
+    if (ShmPrimaryMcuData->InputDet.bits.Button2 == BTN_PRESS && !rightBtnPush ) {
+        rightBtnPush = true;
+        CheckRightButton();
+        log_info("right btn down...............................%x %x %x",
+               pSysInfo->CurGunSelected,pDcChargingInfo->SystemStatus, pSysInfo->SystemPage);
+    } else if (ShmPrimaryMcuData->InputDet.bits.Button2 == BTN_RELEASE && rightBtnPush) {
+        rightBtnPush = false;
+    }
+}

+ 818 - 818
EVSE/Projects/DD360Tcci/Apps/CSU/RFID.c

@@ -1,818 +1,818 @@
-#include <stdio.h>      /*標準輸入輸出定義*/
-#include <stdlib.h>     /*標準函數庫定義*/
-#include <string.h>
-#include <stdint.h>
-
-#include "../Config.h"
-#include "../Log/log.h"
-#include "../Define/define.h"
-#include "../ShareMemory/shmMem.h"
-#include "../SelectGun/SelectGun.h"
-#include "../DataBase/DataBase.h"
-#include <math.h>
-#include "main.h"
-#include "../timeout.h"
-static DcCommonInfo *ShmDcCommonData 			= NULL;
-static SelectGunInfo *ShmSelectGunInfo          = NULL;
-static struct SysInfoData *pSysInfo 			= NULL;
-#define PREAUTHMONEY	888
-bool isDb_ready;
-static RecordTransactionInfo LocalTransactionInfo;
-//------------------------------------------------------------------------------
-static char *rfidPortName = "/dev/ttyS2";
-
-static bool isCardScan = false;
-
-//------------------------------------------------------------------------------
-int checkRemoteStart(int gunIndex)
-{
-    if (ShmDcCommonData->is_RemoteStart[gunIndex] ||
-        ShmDcCommonData->TransactionInfo[gunIndex].LineStatus == _LINE_PAY_INVOICE ||
-        ShmDcCommonData->TransactionInfo[gunIndex].LineStatus == _LINE_PAY_DONATE) {
-        return TRUE;
-    }
-    return FALSE;
-}
-static bool canStartCharging(void)
-{
-    uint8_t index = 0;
-    char buf2[16] = "";
-    memset(buf2, 0, ARRAY_SIZE(buf2));
-    struct OCPP16Data *ShmOCPP16Data = (struct OCPP16Data *)GetShmOCPP16Data();
-
-    for (index = 0; index < strlen((char *)ShmOCPP16Data->Authorize.ResponseIdTagInfo.Status); index++) {
-        sprintf(buf2 + (index - 1) * 2, "%02X", ShmOCPP16Data->Authorize.ResponseIdTagInfo.Status[index]);
-    }
-    sprintf(buf2, "%s", ShmOCPP16Data->Authorize.ResponseIdTagInfo.Status);
-
-    // 因為無法得知實際的長度,所以只能用搜尋的方式
-    if (strcmp(buf2, "Accepted") == EQUAL) {
-        return true;
-    }
-
-    return false;
-}
-
-bool isAutorCompleteHandle(/*uint8_t *authorizeIndex*/)
-{
-   // uint8_t i = 0;
-    struct SysConfigData *pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
-    //struct ChargingInfoData *pDcChargingInfo = NULL;
-    //struct SysInfoData *pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
-
-    // 透過後臺停止充電的判斷
-    if (isAuthorizedComplete()) {
-        // 判斷後台回覆狀態
-        if (canStartCharging() == false) {
-            strcpy((char *)pSysConfig->UserId, "");
-            ClearAuthorizedFlag();
-        }
-        return true;
-    }
-    return false;
-/*
-        if (*(authorizeIndex) != NO_DEFINE) {
-            pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(*(authorizeIndex));
-
-            if (pSysConfig->OfflinePolicy == _OFFLINE_POLICY_LOCAL_LIST &&
-                    strcmp((char *)pDcChargingInfo->StartUserId, "") != EQUAL) {
-                // 先找 AC
-                if (*(authorizeIndex) == DEFAULT_AC_INDEX) {
-                    AcChargingTerminalProcess();
-                } else {
-                    ChargingTerminalProcess(*(authorizeIndex));
-                }
-            }
-
-            strcpy((char *)pSysConfig->UserId, "");
-            *(authorizeIndex) = NO_DEFINE;
-        }
-
-        ClearAuthorizedFlag();
-
-    } else if (pSysConfig->OfflinePolicy == _OFFLINE_POLICY_LOCAL_LIST) {
-        // 白名單驗證
-        for (i = 0; i < 10; i++) {
-            if (strcmp((char *)pSysConfig->LocalWhiteCard[i], "") == EQUAL) {
-                continue;
-            }
-
-            if (strcmp((char *)pSysConfig->LocalWhiteCard[i], (char *)pSysConfig->UserId) == EQUAL) {
-                ChargingTerminalProcess(*(authorizeIndex));
-                strcpy((char *)pSysConfig->UserId, "");
-                ClearAuthorizedFlag();
-
-                break;
-            }
-        }
-    }*/
-}
-
-void showDeductInfo(RecordTransactionInfo* transactionInfo)
-{
-    char ApprovalNo[10];
-    char vemdata[65];
-    char cardno[21];
-    char sn[37];
-    memset(ApprovalNo,'\0',sizeof(ApprovalNo));
-    memset(vemdata,'\0',sizeof(vemdata));
-    memset(cardno,'\0',sizeof(cardno));
-    memset(sn,'\0',sizeof(sn));
-    memcpy(ApprovalNo,&transactionInfo->pCreditCard.ApprovalNo[0],9);
-    memcpy(vemdata,&transactionInfo->pCreditCard.VemData[0],64);
-    memcpy(cardno,&transactionInfo->pCreditCard.CardNo[0],20);
-    log_info("Gun[%d] TransactionId:%d DeductResult:%d IsDonateInvoice:%d Amount:%f Approva Num:[%s] VemData:[%s] CardNo:[%s]",
-    		transactionInfo->ConnectorID,
-            transactionInfo->TransactionId,
-            transactionInfo->DeductResult,
-            transactionInfo->IsDonateInvoice,
-            transactionInfo->Amount,
-            ApprovalNo,
-            vemdata,
-            cardno);
-}
-
-bool RfidStopCharging(void)
-{
-    //當前沒有選槍
-    struct SysConfigData *pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
-    struct SysInfoData *pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
-    if (getConfirmSelectedGun(pSysInfo->CurGunSelected) == FAIL ) {
-        strcpy((char *)pSysConfig->UserId, "");
-        return false;
-    }
-    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(pSysInfo->CurGunSelected);
-    if (pDcChargingInfo->isRemoteStart) {
-
-    } else {
-        if (strcmp((char *)pSysConfig->UserId, (char *)pDcChargingInfo->StartUserId) == EQUAL) {
-
-            ChargingTerminalProcess(pSysInfo->CurGunSelected);
-            strcpy((char *)pSysConfig->UserId, "");
-            log_info("index = %d, card number = %s, UserId = %s ",
-                     pSysInfo->CurGunSelected,
-                     pDcChargingInfo->StartUserId,
-                     pSysConfig->UserId);
-            return true;
-        } else {
-        	strcpy((char *)pSysConfig->UserId, "");
-            return false;
-        }
-    }
-    return false;
-}
-static void UserScanFunction(int gunIndex)
-{
-
-    struct SysConfigData *pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
-    struct SysInfoData *pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
-    //struct ChargingInfoData *pAcChargingInfo =  (struct ChargingInfoData *)GetAcChargingInfoData(0);
-    struct ChargingInfoData *pDcChargingInfo = NULL;
-    ShmDcCommonData = (DcCommonInfo*)GetShmDcCommonData();
-
-    // 當前非驗證的狀態
-    if (IsAuthorizingMode()) {
-        isAutorCompleteHandle(/*&_authorizeIndex*/);
-    }
-
-    // 先判斷現在是否可以提供刷卡
-    // 1. 如果當前沒有槍是閒置狀態,則無提供刷卡功能
-    // 2. 停止充電
-    //if (pSysInfo->PageIndex == _LCM_ERROR) {
-    if (pSysInfo->SystemPage == _PAGE_MAINTAIN) {
-        strcpy((char *)pSysConfig->UserId, "");
-        return;
-    }
-
-    if (strlen((char *)pSysConfig->UserId) <= 0) {
-        return;
-    }
-
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-
-    if ( (pSysInfo->SystemPage == _PAGE_AUTHORIZE ||
-    		pSysInfo->SystemPage == _PAGE_SENSING)) {
-            log_info("// LCM => Authorizing");
-            confirmSelGun(gunIndex);
-            setSelGunWaitToAuthor(gunIndex);
-            StartSystemTimeoutDet(Timeout_Authorizing);
-            AuthorizingStart();
-			pDcChargingInfo->SystemStatus = S_AUTHORIZING;
-
-            // LCM => Authorizing
-            //pSysInfo->SystemPage = _PAGE_AUTHORIZE;
-            // 進入確認卡號狀態
-
-    } else {
-        //strcpy((char *)pSysConfig->UserId, "");
-    }
-
-    return;
-}
-
-bool GetIsCardScan(void)
-{
-    return isCardScan;
-}
-
-void SetIsCardScan(bool value)
-{
-    isCardScan = value;
-}
-void AuthorizeToCharge(int gunIndex)
-{
-    struct SysConfigData *pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
-    struct SysInfoData *pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
-    struct ChargingInfoData* pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(gunIndex);
-    ShmDcCommonData = (DcCommonInfo *)GetShmDcCommonData();
-
-
-    if (pDcChargingInfo->SystemStatus == S_RESERVATION) {
-        if (strcmp((char*)pSysConfig->UserId, (char*)ShmDcCommonData->pGunInfo[gunIndex].ReservationID) != EQUAL) {
-            log_info("LCM => Authorize fail");
-            ShmDcCommonData->TradeCancel = TRUE;
-            ShmDcCommonData->PreAuth_Config = _CREDITCARD_CANCEL;
-            ShmDcCommonData->PreAuth_Result = 0;
-            pSysInfo->SystemPage = _PAGE_AUTHORIZE_FAIL;
-            strcpy((char*)pSysConfig->UserId, "");
-            ClearAuthorizedFlag();
-            return;
-        }
-    }
-    if(isAuthorizedComplete())
-    {
-        if (canStartCharging()) {
-            DetectPluginStart(gunIndex);
-            if (ShmDcCommonData->AuthPass_flag[gunIndex] == TRUE &&
-                ShmDcCommonData->TradeCancel == FALSE) {
-                pSysInfo->SystemPage = _PAGE_PLUGIN;
-            }
-
-        } else {
-            struct ChargingInfoData* pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(gunIndex);
-            log_info("LCM => Authorize fail");
-            ShmDcCommonData->TradeCancel = TRUE;
-            ShmDcCommonData->PreAuth_Config = _CREDITCARD_CANCEL;
-            ShmDcCommonData->PreAuth_Result = 0;
-            if (!pDcChargingInfo->RemoteStartFlag || !pDcChargingInfo->isRemoteStart)
-                pSysInfo->SystemPage = _PAGE_AUTHORIZE_FAIL;
-            strcpy((char *)pSysConfig->UserId, "");
-        }
-        ClearAuthorizedFlag();
-    }
-}
-void ScannerCardProcess(int gunIndex)
-{
-    //struct SysConfigData *pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
-    struct SysInfoData *pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
-    struct WARNING_CODE_INFO *pSysWarning = (struct WARNING_CODE_INFO *)GetShmSysWarningInfo();
-    struct ChargingInfoData *pDcChargingInfo = NULL;
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-
-    if (!isDetectPlugin(gunIndex) && (pSysInfo->SystemPage == _PAGE_SENSING ||
-    		pSysInfo->SystemPage == _PAGE_AUTHORIZE ) &&
-    		(pDcChargingInfo->SystemStatus == S_IDLE || pDcChargingInfo->SystemStatus == S_RESERVATION )&&
-            pSysWarning->Level != WARN_LV_ER ) {
-    	//setSelGunWaitToAuthor(gunIndex);
-        isCardScan = true;
-        // 處理刷卡及驗證卡號的動作
-        UserScanFunction(gunIndex);
-    }
-
-    if (pDcChargingInfo->SystemStatus == S_AUTHORIZING && pSysInfo->SystemPage == _PAGE_SENSING &&
-        !ShmDcCommonData->is_RemoteStart[gunIndex] ) {
-        AuthorizeToCharge(gunIndex);
-    } else if (pSysInfo->SystemPage == _PAGE_AUTHORIZE_FAIL) {
-        StartSystemTimeoutDet(Timeout_VerifyFail);
-        isCardScan = false;
-    } else {
-        isCardScan = false;
-    }
-}
-void storePayResult(uint8_t gunIndex)
-{
-    memset(&LocalTransactionInfo, 0x00, sizeof(RecordTransactionInfo));
-
-    memcpy(&LocalTransactionInfo, &ShmDcCommonData->TransactionInfo[gunIndex] ,sizeof(RecordTransactionInfo));
-
-}
-void getPayResult(uint8_t gunIndex)
-{
-    memcpy(&ShmDcCommonData->TransactionInfo[gunIndex], &LocalTransactionInfo, sizeof(RecordTransactionInfo));
-}
-
-void storeParkingPayResult(uint8_t gunIndex)
-{
-    memset(&LocalTransactionInfo, 0x00, sizeof(RecordTransactionInfo));
-    memcpy(&LocalTransactionInfo, &ShmDcCommonData->ParkingInfo[gunIndex] ,sizeof(RecordTransactionInfo));
-
-}
-void getParkingPayResult(uint8_t gunIndex)
-{
-    //memcpy(&ShmDcCommonData->ParkingInfo[gunIndex], &LocalTransactionInfo, sizeof(RecordTransactionInfo));
-    memcpy( ShmDcCommonData->ParkingInfo[gunIndex].OccupancySN, LocalTransactionInfo.OccupancySN, 36);
-}
-void WritePayResult(int result ,uint8_t gunIndex)
-{
-    if (result == TRUE)
-        ShmDcCommonData->TransactionInfo[gunIndex].DeductResult = _DEDUCT_COMPLETE_PASS;
-    else
-        ShmDcCommonData->TransactionInfo[gunIndex].DeductResult = _DEDUCT_COMPLETE_FAIL;
-
-    log_info("Gun[%d] TransactionId:%d DeductResult:%d IsDonateInvoice:%d Amount:%f VemData:%s Approve No:%s",
-        gunIndex, ShmDcCommonData->TransactionInfo[gunIndex].TransactionId,
-        ShmDcCommonData->TransactionInfo[gunIndex].DeductResult,
-        ShmDcCommonData->TransactionInfo[gunIndex].IsDonateInvoice,
-        ShmDcCommonData->TransactionInfo[gunIndex].Amount,
-        ShmDcCommonData->TransactionInfo[gunIndex].pCreditCard.VemData,
-        ShmDcCommonData->TransactionInfo[gunIndex].pCreditCard.ApprovalNo);
-}
-
-void PreAuthCompleteToCardReader(int fd,uint8_t gunIndex)
-{
-    struct SysConfigData* pSysConfig = (struct SysConfigData*)GetShmSysConfigData();
-	int result = 0;
-
-    storePayResult(gunIndex);
-    if (ShmDcCommonData->TransactionInfo[gunIndex].Amount > 0 && ShmDcCommonData->TransactionInfo[gunIndex].Amount < 1 &&
-        ShmDcCommonData->pGunInfo[gunIndex].ParkingStatus == 0) {
-        log_info("final cost less 1 : %f", ShmDcCommonData->TransactionInfo[gunIndex].Amount);
-        ShmDcCommonData->TransactionInfo[gunIndex].Amount = 1;
-    }
-
-	result = CreditCardPreAuthComplete(fd,(int)LocalTransactionInfo.Amount, &pSysConfig->ModelName[0],
-											&ShmDcCommonData->TransactionInfo[gunIndex].pCreditCard.VemData[0],
-											&ShmDcCommonData->TransactionInfo[gunIndex]);
-    getPayResult(gunIndex);
-
-    //sleep(10);
-	if (result > 0 ) {
-		log_info("Credit Card Spend Money:%.1f", ShmDcCommonData->TransactionInfo[gunIndex].Amount);
-		pSysInfo->SystemPage = _PAGE_COMPLETE;
-        ShmDcCommonData->TransactionInfo[gunIndex].DeductResult = _DEDUCT_COMPLETE_PASS;
-		WritePayResult(TRUE,gunIndex);
-        ShmDcCommonData->PayPass_flag[gunIndex] = TRUE;
-	} else {
-		log_info("PAYING FAIL");
-		ShmDcCommonData->PayPass_flag[gunIndex] = FALSE;
-		pSysInfo->SystemPage = _PAGE_PAYFAIL;
-        ShmDcCommonData->TransactionInfo[gunIndex].DeductResult = _DEDUCT_COMPLETE_FAIL;
-		WritePayResult(FALSE,gunIndex);
-	}
-    ShmDcCommonData->TransactionInfo[gunIndex].IsUpload = FALSE;
-    //getPayResult(gunIndex);
-
-    UpdateDeductInfoStatus(gunIndex, &ShmDcCommonData->TransactionInfo[gunIndex]);
-
-    ShmDcCommonData->PreAuth_Result = result;
-}
-int CreditCardCancelPreAuth(int fd, uint8_t gunIndex)
-{
-    if (ShmDcCommonData->pGunInfo[gunIndex].ParkingStatus) {
-        return;
-    }
-    struct SysConfigData* pSysConfig = (struct SysConfigData*)GetShmSysConfigData();
-    storePayResult(gunIndex);
-
-    ShmDcCommonData->PreAuth_Result = CreditCardPreAuthCancel(fd, PREAUTHMONEY, &pSysConfig->ModelName[0],
-                                    &LocalTransactionInfo.pCreditCard.ApprovalNo[0],
-                                    &LocalTransactionInfo.pCreditCard.CardNo[0],
-                                    &LocalTransactionInfo.pCreditCard.VemData[0]);
-    //sleep(10);
-    if (ShmDcCommonData->PreAuth_Result >= 0) {
-        strcpy((char*)pSysConfig->UserId, "");
-        //ShmDcCommonData->PayFinish[gunIndex] = TRUE;
-        log_info("Gun%d Card Reader PreAuth Cancel Success",gunIndex);
-        LocalTransactionInfo.DeductResult = _DEDUCT_CANCEL;
-    } else if (ShmDcCommonData->PreAuth_Result < 0) {
-        log_info("Gun%d Card Reader PreAuth Cancel Failure",gunIndex);
-        LocalTransactionInfo.DeductResult = _DEDUCT_PREAUTH;
-    }
-    LocalTransactionInfo.IsUpload = FALSE;
-    getPayResult(gunIndex);
-
-    UpdateDeductInfoStatus(gunIndex, &LocalTransactionInfo);
-
-    memset(&ShmDcCommonData->TransactionInfo[gunIndex], 0x00, sizeof(RecordTransactionInfo));
-    ShmDcCommonData->PreAuth_Config = _CREDITCARD_IDLE;
-    return ShmDcCommonData->PreAuth_Result;
-}
-
-void ReDeductProcess(int fd)
-{
-    struct SysConfigData* pSysConfig = (struct SysConfigData*)GetShmSysConfigData();
-    int j;
-    int result;
-    int rededuct_gunIndex[128];
-    RecordTransactionInfo deductInfo[128];
-    int rededuct_num = 0;
-    // 充電費補扣款
-    rededuct_num = DB_GetMultiReDeductInfo(&rededuct_gunIndex[0], &deductInfo[0]);
-
-    if (rededuct_num == 0) {
-        //log_info("No Rededuct Information");
-    } else {
-        ShmDcCommonData->CreditCardUpload = TRUE;
-        pSysInfo->SystemPage = _PAGE_PAYING;
-        log_info("Rededuct Total Number:%d", rededuct_num);
-        for (j = rededuct_num-1; j >= 0 ; j--) {
-            sleep(10);
-
-            log_info("Start Rededuct item [%d]",j);
-            if (deductInfo[j].isIntoCharge == FALSE ||
-                (deductInfo[j].Energy == 0 && deductInfo[j].Amount == 0) ||
-                (deductInfo[j].LineStatus == _LINE_PAY_DONATE || deductInfo[j].LineStatus == _LINE_PAY_INVOICE)) {
-                // 未進入充電或度數等於零
-                result = CreditCardPreAuthCancel(fd, PREAUTHMONEY, &pSysConfig->ModelName[0],
-                    &deductInfo[j].pCreditCard.ApprovalNo[0],
-                    &deductInfo[j].pCreditCard.CardNo[0],
-                    &deductInfo[j].pCreditCard.VemData[0]);
-                sleep(10);
-                if (result > 0) {
-                    deductInfo[j].DeductResult = _DEDUCT_CANCEL;
-                    log_info("Backgroud PreAuthCancel OK");
-                }
-            } else {
-                // 度數大於零
-                if (deductInfo[j].Amount == 0 && deductInfo[j].Energy > 0) {
-                    log_info("Error Close Charging recount amount:%.1f",deductInfo[j].Amount);
-                    continue;
-                }
-                result = CreditCardPreAuthComplete(fd, (int)deductInfo[j].Amount, &pSysConfig->ModelName[0],
-                    &deductInfo[j].pCreditCard.VemData[0],
-                    &ShmDcCommonData->TransactionInfo[0].pCreditCard);
-                if (result > 0) {
-                    deductInfo[j].DeductResult = _DEDUCT_COMPLETE_PASS;
-                    log_info("Backgroud PreAuthComplete OK");
-                } else if (result < 0) {
-                    deductInfo[j].DeductResult = _DEDUCT_COMPLETE_FAIL;
-                    log_info("Backgroud ID:%d Amount:%d VemData:%s PreAuthComplete fail",
-                        deductInfo[j].TransactionId,
-                        (int)deductInfo[j].Amount,
-                        deductInfo[j].pCreditCard.VemData);
-                }
-            }
-            deductInfo[j].IsUpload = FALSE;
-            deductInfo[j].RedeductTime++;
-            UpdateDeductInfoStatus(rededuct_gunIndex[j], &deductInfo[j]);
-        }
-    }
-    // 佔位費補扣款
-    /*
-    rededuct_num = DB_GetParkingDeductResult(&rededuct_gunIndex[0], &deductInfo[0]);
-
-    if (rededuct_num == 0) {
-        log_info("No Parking Rededuct Information");
-    } else {
-        ShmDcCommonData->CreditCardUpload = TRUE;
-        pSysInfo->SystemPage = _PAGE_PAYING;
-        log_info("Parking Rededuct Total Number:%d", rededuct_num);
-        for (j = rededuct_num-1; j >= 0 ; j--) {
-            sleep(3);
-
-            log_info("Start Parking Rededuct item [%d]",j);
-
-            result = CreditCardPreAuthComplete(fd, (int)deductInfo[j].Amount, &pSysConfig->ModelName[0],
-                &deductInfo[j].pCreditCard.VemData[0],
-                &ShmDcCommonData->ParkingInfo[0].pCreditCard);
-            if (result > 0) {
-                deductInfo[j].DeductResult = _DEDUCT_COMPLETE_PASS;
-                log_info("Backgroud Parking PreAuthComplete OK");
-            } else if (result < 0) {
-                deductInfo[j].DeductResult = _DEDUCT_COMPLETE_FAIL;
-                log_info("Backgroud Parking ID:%d Amount:%d VemData:%s PreAuthComplete fail",
-                    deductInfo[j].TransactionId,
-                    (int)deductInfo[j].Amount,
-                    deductInfo[j].pCreditCard.VemData);
-            }
-            
-            deductInfo[j].IsUpload = FALSE;
-            deductInfo[j].RedeductTime++;
-            UpdateParkingDeductInfo(rededuct_gunIndex[j], &deductInfo[j]);
-        }
-    }
-    */
-    ShmDcCommonData->RoutineReduct = TRUE;
-}
-static int InitialRfidPort(void)
-{
-    int fd = open(rfidPortName, O_RDWR);
-    struct termios tios;
-    struct AlarmCodeData *pAlarmCode = (struct AlarmCodeData *)GetShmAlarmCodeData();
-
-    if (fd != FAIL) {
-        ioctl (fd, TCGETS, &tios);
-        tios.c_cflag = B115200 | CS8 | CLOCAL | CREAD;
-        tios.c_lflag = 0;
-        tios.c_iflag = 0;
-        tios.c_oflag = 0;
-        tios.c_cc[VMIN] = 0;
-        tios.c_cc[VTIME] = (uint8_t) 1;
-        tios.c_lflag = 0;
-        tcflush(fd, TCIFLUSH);
-        ioctl(fd, TCSETS, &tios);
-    }
-
-    if (fd < 0) {
-        pAlarmCode->AlarmEvents.bits.RfidModuleCommFail = 1;
-    }
-
-    return fd;
-}
-void RemoteStartCancelPreAuth(int sel_gun)
-{
-    log_info("Remote start need to cancel PreAuth");
-    memcpy(&ShmDcCommonData->RedeductBill, &ShmDcCommonData->TransactionInfo[sel_gun], sizeof(RecordTransactionInfo));
-    memset(&ShmDcCommonData->TransactionInfo[sel_gun], 0x00, sizeof(RecordTransactionInfo));
-    ShmDcCommonData->TransactionInfo[sel_gun].LineStatus = ShmDcCommonData->RedeductBill.LineStatus;
-}
-void PreAuthCreditCard(int fd, uint8_t gunIndex)
-{
-    struct SysConfigData* pSysConfig = (struct SysConfigData*)GetShmSysConfigData();
-    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);;
-    int result = 0;
-    storePayResult(gunIndex);
-    if (ShmDcCommonData->pGunInfo[gunIndex].ParkingStatus)
-        result = CreditCardPreAuth(fd, LocalTransactionInfo.Amount,&pSysConfig->ModelName[0], &LocalTransactionInfo.pCreditCard);
-    else
-        result = CreditCardPreAuth(fd, PREAUTHMONEY,&pSysConfig->ModelName[0], &LocalTransactionInfo.pCreditCard);
-    ShmDcCommonData->PreAuth_Result = result;
-    pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(gunIndex);
-    {
-        if (!checkRemoteStart(gunIndex)) {
-            if (!ShmDcCommonData->TradeCancel)
-                StopSystemTimeoutDet();
-            if (ShmDcCommonData->TradeCancel == FALSE && result > 0) {
-                pSysInfo->SystemPage = _PAGE_SENSING;
-            }
-        }
-
-        if (result > 0 && strcmp((char*)LocalTransactionInfo.pCreditCard.CardNo, "") != 0) {
-            log_info("Gun%d PreAuth card:%s", gunIndex, LocalTransactionInfo.pCreditCard.CardNo);
-            LocalTransactionInfo.DeductResult = _DEDUCT_PREAUTH;
-            LocalTransactionInfo.IsUpload = FALSE;
-            LocalTransactionInfo.ConnectorID = ShmDcCommonData->ConnectorID[gunIndex];
-            //log_info("Gun%d Line Status:%d", LocalTransactionInfo.LineStatus);
-            if (ShmDcCommonData->pGunInfo[gunIndex].ParkingStatus)
-                InsertParkingDeductInfo(ShmDcCommonData->ConnectorID[gunIndex], &LocalTransactionInfo);
-            else {
-                ShmDcCommonData->AuthPass_flag[gunIndex] = TRUE;
-                strncpy((char*)pSysConfig->UserId, (char*)LocalTransactionInfo.pCreditCard.CardNo, 20);
-                InsertDeductInfo(ShmDcCommonData->ConnectorID[gunIndex], &LocalTransactionInfo);
-            }
-            getPayResult(gunIndex);
-            //log_info("Gun%d PreAuth OK",gunIndex);
-        } else if (result < 0) {
-            if (ShmDcCommonData->TradeCancel == FALSE && !checkRemoteStart(gunIndex))
-                pSysInfo->SystemPage = _PAGE_AUTHORIZE_FAIL;
-            ShmDcCommonData->AuthPass_flag[gunIndex] = FALSE;
-            memset(&LocalTransactionInfo.pCreditCard, 0, sizeof(TransInfo));
-            log_info("Gun%d PreAuth Fail",gunIndex);
-        }
-        ShmDcCommonData->PreAuth_Config = _CREDITCARD_IDLE;
-    }
-}
-void CreateRfidFork(void)
-{
-    pid_t rfidRecPid;
-    int donate = 0;
-    rfidRecPid = fork();
-    int sel_gun = 0;
-    int linestatus = 0;
-    if (rfidRecPid == 0) {
-        //char localTime[128] = {0};
-        struct timeb SeqEndTime;
-        struct tm *tm;
-        pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
-        int fd = -1;
-        int isContinue = 1;
-        //RFID rfid = {0};
-        //RecordTransactionInfo deduct;
-        fd = InitialRfidPort();
-        struct SysConfigData *pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
-        ShmDcCommonData = (DcCommonInfo *)GetShmDcCommonData();
-        ShmSelectGunInfo = (SelectGunInfo *)GetShmSelectGunInfo();
-        struct ChargingInfoData *pDcChargingInfo = NULL;
-        if (DeductDB_Open() != PASS) {
-            isDb_ready = false;
-            log_info("DeductDB_Open Fail");
-            return;
-        } else {
-            isDb_ready = true;
-            //InsertDeductInfo(0, &ShmDcCommonData->TransactionInfo);
-        }
-        if (ParkingDB_Open() != PASS) {
-            isDb_ready = false;
-            log_info("ParkingDB_Open Fail");
-            return;
-        } else {
-            isDb_ready = true;
-            //InsertDeductInfo(0, &ShmDcCommonData->TransactionInfo);
-        }
-        int gunIndex;
-        //int uploadIndex = 0;
-        //int ReAuthComplete_Index = 0;
-        //log_info("RFID fork Child's PID is %d", getpid());
-        int result;
-        int is_idle = TRUE;
-        while (isContinue) {
-        	result = 0;
-            usleep(500000);
-            ftime(&SeqEndTime);
-            SeqEndTime.time = time(NULL);
-            tm = localtime(&SeqEndTime.time);
-
-            if (ShmDcCommonData->DebugFlag == TRUE ||
-                ShmDcCommonData->is_RemoteStart[pSysInfo->CurGunSelected] == TRUE ||
-                ShmDcCommonData->is_AutoStart[pSysInfo->CurGunSelected] == TRUE) {
-                ShmDcCommonData->PreAuth_Config = _CREDITCARD_IDLE;
-                ShmDcCommonData->PreAuth_Result = 0;
-            }
-
-            is_idle = TRUE;
-			for (gunIndex = 0; gunIndex < pSysConfig->TotalConnectorCount; gunIndex++) {
-				pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-
-                // 檢查電樁狀態是否為idle狀態
-				if (pDcChargingInfo->SystemStatus != S_IDLE ) {
-					is_idle = FALSE;
-				}
-                // 檢查使用者是否進行線上支付操作並且線下支付已完成
-                // 需進行取消預授權
-                if (checkRemoteStart(gunIndex) && ShmDcCommonData->AuthPass_flag[gunIndex] &&
-                    !ShmDcCommonData->PayPass_flag[gunIndex]) {
-                    RemoteStartCancelPreAuth(gunIndex);
-                    ShmDcCommonData->AuthPass_flag[gunIndex] = FALSE;
-                }
-
-                if (ShmDcCommonData->StopCharge[gunIndex] == TRUE && pDcChargingInfo->Replug_flag == TRUE) {
-                    // Remote Start of AutoStart ByPass Credit Card Reader
-                    if (ShmDcCommonData->DebugFlag == TRUE ||
-                        ShmDcCommonData->is_RemoteStart[gunIndex] == TRUE ||
-                        ShmDcCommonData->is_AutoStart[gunIndex] == TRUE) {
-                        continue;
-                    }
-                    log_info("Gun %d Not Into Charging cancel Trade",gunIndex);
-            
-                    StopGunInfoTimeoutDet(gunIndex);
-                    ShmDcCommonData->TradeCancel = TRUE;
-                    pSysInfo->SystemPage = _PAGE_SENSING;
-                    StartSystemTimeoutDet(Timeout_TradeCancel);
-                    CreditCardCancelPreAuth(fd, gunIndex);
-                    pSysInfo->CurGunSelected = gunIndex;
-                    pSysInfo->SystemPage = _PAGE_PLUGOUT;
-                    StopSystemTimeoutDet();
-                    ShmDcCommonData->StopCharge[gunIndex] = FALSE;
-                } else {
-                    if (ShmDcCommonData->StopCharge[gunIndex] && ShmDcCommonData->finalcost_flag[gunIndex] &&
-                        ShmDcCommonData->PreAuth_Config != _CREDITCARD_CANCEL) {
-
-                        pSysInfo->CurGunSelected = gunIndex;
-                        StopGunInfoTimeoutDet(gunIndex); //Timeout_FinalCost
-
-                        // Remote Start of AutoStart ByPass Credit Card Reader
-                        if (ShmDcCommonData->DebugFlag == TRUE || checkRemoteStart(gunIndex) ||
-                            ShmDcCommonData->is_AutoStart[gunIndex]) {
-                            if (ShmDcCommonData->is_AutoStart[gunIndex]) {
-                                ShmDcCommonData->PayPass_flag[gunIndex] = TRUE;
-                            }
-                            ShmDcCommonData->StopCharge[gunIndex] = FALSE;
-                            continue;
-                        }
-
-                        // 實際扣款
-                        if (ShmDcCommonData->TransactionInfo[gunIndex].Amount < 1) {
-                            log_info("Final Cost less 1 , Cancel Trade!!");
-                            if (CreditCardCancelPreAuth(fd, gunIndex) > 0) {
-                                pSysInfo->SystemPage = _PAGE_COMPLETE;
-                                ShmDcCommonData->PayPass_flag[gunIndex] = TRUE;
-                            } else {
-                                pSysInfo->SystemPage = _PAGE_PAYFAIL;
-                                ShmDcCommonData->PayPass_flag[gunIndex] = FALSE;
-                            }
-                        } else {
-                            ShmDcCommonData->PreAuth_Config = _CREDITCARD_PREAUTHCOMPLETE;
-                            PreAuthCompleteToCardReader(fd, gunIndex);
-                             ShmDcCommonData->PreAuth_Config = _CREDITCARD_IDLE;
-                        }
-                        ShmDcCommonData->StopCharge[gunIndex] = FALSE;
-                    }
-                }
-			} // for
-            if (ShmDcCommonData->PreAuth_Config == _CREDITCARD_SALE /*&& ShmDcCommonData->pGunInfo[pSysInfo->CurGunSelected].isParking*/) {
-                sel_gun = pSysInfo->CurGunSelected;
-                ShmDcCommonData->PreAuth_Result = 0;
-                storeParkingPayResult(sel_gun);
-                
-                ShmDcCommonData->PreAuth_Result = CreditCardSale(fd,(int)ShmDcCommonData->ParkingInfo[sel_gun].Amount,
-                                                &pSysConfig->ModelName[0],
-                                                &ShmDcCommonData->ParkingInfo[sel_gun].pCreditCard);
-                StopSystemTimeoutDet(); //Timeout_ScanCard
-                getParkingPayResult(sel_gun);
-                if (ShmDcCommonData->PreAuth_Result > 0 ) {
-                    log_info("Gun%d Parking Fee Sale Success",sel_gun);
-                    pSysInfo->SystemPage = _PAGE_PLUGIN;
-                    ShmDcCommonData->ParkingInfo[sel_gun].IsUpload = FALSE;
-                    //ShmDcCommonData->pGunInfo[sel_gun].GetParkingBill = FALSE;
-                    ShmDcCommonData->ParkingInfo[sel_gun].DeductResult = _DEDUCT_SALE_PASS;
-                    InsertParkingDeductInfo(ShmDcCommonData->ConnectorID[sel_gun], &ShmDcCommonData->ParkingInfo[sel_gun]);
-                } else {
-                    log_info("Gun%d Parking Fee Sale Fail",sel_gun);
-                    if (!ShmDcCommonData->TradeCancel) {
-                        pSysInfo->SystemPage = _PAGE_AUTHORIZE_FAIL;
-                    }
-                }
-                ShmDcCommonData->PreAuth_Result = 0;
-                ShmDcCommonData->PreAuth_Config = _CREDITCARD_IDLE;
-            } else if(ShmDcCommonData->PreAuth_Config == _CREDITCARD_CANCEL) {
-                // 取消預授權
-                CreditCardCancelPreAuth(fd,pSysInfo->CurGunSelected);
-            } else if (ShmDcCommonData->PreAuth_Config == _CREDITCARD_PREAUTH ) {
-                // 預授權
-                sel_gun = pSysInfo->CurGunSelected;
-                if (ShmDcCommonData->pGunInfo[sel_gun].isParking) {
-                    log_info("In Parking Status can't enable PreAuth function");
-                    pSysInfo->SystemPage = _PAGE_AUTHORIZE_FAIL;
-                    ShmDcCommonData->AuthPass_flag[gunIndex] = FALSE;
-                    ShmDcCommonData->PreAuth_Config = _CREDITCARD_IDLE;
-                } else
-                    PreAuthCreditCard(fd,sel_gun);
-                // 佔位費預授權並扣款
-                /*
-                if (ShmDcCommonData->PreAuth_Result > 0 ) {
-                        log_info("Gun%d Parking Fee PreAuthComplete Success",sel_gun);
-                        pSysInfo->SystemPage = _PAGE_PLUGIN;
-                        StartSystemTimeoutDet(Timeout_ReturnViewPage);
-                } else {
-                    log_info("Gun%d Parking Fee PreAuthComplete Fail",sel_gun);
-                    if (!ShmDcCommonData->TradeCancel) {
-                        pSysInfo->SystemPage = _PAGE_AUTHORIZE_FAIL;
-                        StartSystemTimeoutDet(Timeout_VerifyFail);
-                    }
-                }
-                
-                if (ShmDcCommonData->pGunInfo[sel_gun].ParkingStatus && ShmDcCommonData->PreAuth_Result > 0 &&
-                    !ShmDcCommonData->TradeCancel && ShmDcCommonData->PreAuth_Config != _CREDITCARD_CANCEL ) {
-                    ShmDcCommonData->PreAuth_Result = 0;
-                    sleep(10);
-                    PreAuthCompleteToCardReader(fd, sel_gun);
-                    if (ShmDcCommonData->PreAuth_Result > 0 ) {
-                        log_info("Gun%d Parking Fee PreAuthComplete Success",sel_gun);
-                        pSysInfo->SystemPage = _PAGE_PLUGIN;
-                        StartSystemTimeoutDet(Timeout_ReturnViewPage);
-                    } else {
-                        log_info("Gun%d Parking Fee PreAuthComplete Fail",sel_gun);
-                        if (!ShmDcCommonData->TradeCancel) {
-                            pSysInfo->SystemPage = _PAGE_AUTHORIZE_FAIL;
-                            StartSystemTimeoutDet(Timeout_VerifyFail);
-                        }
-                    }
-                    ShmDcCommonData->PreAuth_Result = 0;
-                }*/
-            }
-
-            // 每30分鐘檢查補扣款
-            if (tm->tm_min %30 == 0 && tm->tm_sec == 0) {
-                ShmDcCommonData->RoutineReduct = FALSE;
-            }
-
-            if ((is_idle == TRUE &&
-                pSysInfo->SystemPage == _PAGE_IDLE  &&
-                ShmDcCommonData->RoutineReduct == FALSE) || ShmDcCommonData->Exe_ReDeduct) {
-
-                ReDeductProcess(fd);
-                pSysInfo->SystemPage = _PAGE_IDLE;
-                ShmDcCommonData->CreditCardUpload = FALSE;
-                ShmDcCommonData->Exe_ReDeduct = 0;
-            }
-
-            // 每日晚上11點30分結帳
-            if (is_idle == TRUE && pSysInfo->SystemPage == _PAGE_IDLE  &&
-                ((tm->tm_hour == 15 && tm->tm_min > 30  && ShmDcCommonData->RoutineSettlement == FALSE) ||
-                    ShmDcCommonData->UnionSettlement)) {
-                StopSystemTimeoutDet();
-                if (ShmDcCommonData->UnionSettlement)
-                    ShmDcCommonData->UnionSettlement = 0;
-                else
-                    ShmDcCommonData->RoutineSettlement = TRUE;
-                ShmDcCommonData->CreditCardUpload = TRUE;
-                pSysInfo->SystemPage = _PAGE_PAYING;
-                 
-                result = CreditCardUnionSettlement(fd, &pSysConfig->ModelName[0], &LocalTransactionInfo.pCreditCard);
-                if (result > 0) {
-                    log_info("CreditCardUnionSettlement OK");
-                }
-                else
-                    log_info("CreditCardUnionSettlement FAIL");
-                sleep(90);
-                pSysInfo->SystemPage = _PAGE_IDLE;
-
-                ShmDcCommonData->CreditCardUpload = FALSE;
-            }
-            if (tm->tm_hour == 16 && tm->tm_min == 0) {
-                ShmDcCommonData->RoutineSettlement = FALSE;
-            }
-        }
-    }
-}
-
+#include <stdio.h>      /*標準輸入輸出定義*/
+#include <stdlib.h>     /*標準函數庫定義*/
+#include <string.h>
+#include <stdint.h>
+
+#include "../Config.h"
+#include "../Log/log.h"
+#include "../Define/define.h"
+#include "../ShareMemory/shmMem.h"
+#include "../SelectGun/SelectGun.h"
+#include "../DataBase/DataBase.h"
+#include <math.h>
+#include "main.h"
+#include "../timeout.h"
+static DcCommonInfo *ShmDcCommonData 			= NULL;
+static SelectGunInfo *ShmSelectGunInfo          = NULL;
+static struct SysInfoData *pSysInfo 			= NULL;
+#define PREAUTHMONEY	888
+bool isDb_ready;
+static RecordTransactionInfo LocalTransactionInfo;
+//------------------------------------------------------------------------------
+static char *rfidPortName = "/dev/ttyS2";
+
+static bool isCardScan = false;
+
+//------------------------------------------------------------------------------
+int checkRemoteStart(int gunIndex)
+{
+    if (ShmDcCommonData->is_RemoteStart[gunIndex] ||
+        ShmDcCommonData->TransactionInfo[gunIndex].LineStatus == _LINE_PAY_INVOICE ||
+        ShmDcCommonData->TransactionInfo[gunIndex].LineStatus == _LINE_PAY_DONATE) {
+        return TRUE;
+    }
+    return FALSE;
+}
+static bool canStartCharging(void)
+{
+    uint8_t index = 0;
+    char buf2[16] = "";
+    memset(buf2, 0, ARRAY_SIZE(buf2));
+    struct OCPP16Data *ShmOCPP16Data = (struct OCPP16Data *)GetShmOCPP16Data();
+
+    for (index = 0; index < strlen((char *)ShmOCPP16Data->Authorize.ResponseIdTagInfo.Status); index++) {
+        sprintf(buf2 + (index - 1) * 2, "%02X", ShmOCPP16Data->Authorize.ResponseIdTagInfo.Status[index]);
+    }
+    sprintf(buf2, "%s", ShmOCPP16Data->Authorize.ResponseIdTagInfo.Status);
+
+    // 因為無法得知實際的長度,所以只能用搜尋的方式
+    if (strcmp(buf2, "Accepted") == EQUAL) {
+        return true;
+    }
+
+    return false;
+}
+
+bool isAutorCompleteHandle(/*uint8_t *authorizeIndex*/)
+{
+   // uint8_t i = 0;
+    struct SysConfigData *pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
+    //struct ChargingInfoData *pDcChargingInfo = NULL;
+    //struct SysInfoData *pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
+
+    // 透過後臺停止充電的判斷
+    if (isAuthorizedComplete()) {
+        // 判斷後台回覆狀態
+        if (canStartCharging() == false) {
+            strcpy((char *)pSysConfig->UserId, "");
+            ClearAuthorizedFlag();
+        }
+        return true;
+    }
+    return false;
+/*
+        if (*(authorizeIndex) != NO_DEFINE) {
+            pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(*(authorizeIndex));
+
+            if (pSysConfig->OfflinePolicy == _OFFLINE_POLICY_LOCAL_LIST &&
+                    strcmp((char *)pDcChargingInfo->StartUserId, "") != EQUAL) {
+                // 先找 AC
+                if (*(authorizeIndex) == DEFAULT_AC_INDEX) {
+                    AcChargingTerminalProcess();
+                } else {
+                    ChargingTerminalProcess(*(authorizeIndex));
+                }
+            }
+
+            strcpy((char *)pSysConfig->UserId, "");
+            *(authorizeIndex) = NO_DEFINE;
+        }
+
+        ClearAuthorizedFlag();
+
+    } else if (pSysConfig->OfflinePolicy == _OFFLINE_POLICY_LOCAL_LIST) {
+        // 白名單驗證
+        for (i = 0; i < 10; i++) {
+            if (strcmp((char *)pSysConfig->LocalWhiteCard[i], "") == EQUAL) {
+                continue;
+            }
+
+            if (strcmp((char *)pSysConfig->LocalWhiteCard[i], (char *)pSysConfig->UserId) == EQUAL) {
+                ChargingTerminalProcess(*(authorizeIndex));
+                strcpy((char *)pSysConfig->UserId, "");
+                ClearAuthorizedFlag();
+
+                break;
+            }
+        }
+    }*/
+}
+
+void showDeductInfo(RecordTransactionInfo* transactionInfo)
+{
+    char ApprovalNo[10];
+    char vemdata[65];
+    char cardno[21];
+    char sn[37];
+    memset(ApprovalNo,'\0',sizeof(ApprovalNo));
+    memset(vemdata,'\0',sizeof(vemdata));
+    memset(cardno,'\0',sizeof(cardno));
+    memset(sn,'\0',sizeof(sn));
+    memcpy(ApprovalNo,&transactionInfo->pCreditCard.ApprovalNo[0],9);
+    memcpy(vemdata,&transactionInfo->pCreditCard.VemData[0],64);
+    memcpy(cardno,&transactionInfo->pCreditCard.CardNo[0],20);
+    log_info("Gun[%d] TransactionId:%d DeductResult:%d IsDonateInvoice:%d Amount:%f Approva Num:[%s] VemData:[%s] CardNo:[%s]",
+    		transactionInfo->ConnectorID,
+            transactionInfo->TransactionId,
+            transactionInfo->DeductResult,
+            transactionInfo->IsDonateInvoice,
+            transactionInfo->Amount,
+            ApprovalNo,
+            vemdata,
+            cardno);
+}
+
+bool RfidStopCharging(void)
+{
+    //當前沒有選槍
+    struct SysConfigData *pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
+    struct SysInfoData *pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
+    if (getConfirmSelectedGun(pSysInfo->CurGunSelected) == FAIL ) {
+        strcpy((char *)pSysConfig->UserId, "");
+        return false;
+    }
+    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(pSysInfo->CurGunSelected);
+    if (pDcChargingInfo->isRemoteStart) {
+
+    } else {
+        if (strcmp((char *)pSysConfig->UserId, (char *)pDcChargingInfo->StartUserId) == EQUAL) {
+
+            ChargingTerminalProcess(pSysInfo->CurGunSelected);
+            strcpy((char *)pSysConfig->UserId, "");
+            log_info("index = %d, card number = %s, UserId = %s ",
+                     pSysInfo->CurGunSelected,
+                     pDcChargingInfo->StartUserId,
+                     pSysConfig->UserId);
+            return true;
+        } else {
+        	strcpy((char *)pSysConfig->UserId, "");
+            return false;
+        }
+    }
+    return false;
+}
+static void UserScanFunction(int gunIndex)
+{
+
+    struct SysConfigData *pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
+    struct SysInfoData *pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
+    //struct ChargingInfoData *pAcChargingInfo =  (struct ChargingInfoData *)GetAcChargingInfoData(0);
+    struct ChargingInfoData *pDcChargingInfo = NULL;
+    ShmDcCommonData = (DcCommonInfo*)GetShmDcCommonData();
+
+    // 當前非驗證的狀態
+    if (IsAuthorizingMode()) {
+        isAutorCompleteHandle(/*&_authorizeIndex*/);
+    }
+
+    // 先判斷現在是否可以提供刷卡
+    // 1. 如果當前沒有槍是閒置狀態,則無提供刷卡功能
+    // 2. 停止充電
+    //if (pSysInfo->PageIndex == _LCM_ERROR) {
+    if (pSysInfo->SystemPage == _PAGE_MAINTAIN) {
+        strcpy((char *)pSysConfig->UserId, "");
+        return;
+    }
+
+    if (strlen((char *)pSysConfig->UserId) <= 0) {
+        return;
+    }
+
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+
+    if ( (pSysInfo->SystemPage == _PAGE_AUTHORIZE ||
+    		pSysInfo->SystemPage == _PAGE_SENSING)) {
+            log_info("// LCM => Authorizing");
+            confirmSelGun(gunIndex);
+            setSelGunWaitToAuthor(gunIndex);
+            StartSystemTimeoutDet(Timeout_Authorizing);
+            AuthorizingStart();
+			pDcChargingInfo->SystemStatus = S_AUTHORIZING;
+
+            // LCM => Authorizing
+            //pSysInfo->SystemPage = _PAGE_AUTHORIZE;
+            // 進入確認卡號狀態
+
+    } else {
+        //strcpy((char *)pSysConfig->UserId, "");
+    }
+
+    return;
+}
+
+bool GetIsCardScan(void)
+{
+    return isCardScan;
+}
+
+void SetIsCardScan(bool value)
+{
+    isCardScan = value;
+}
+void AuthorizeToCharge(int gunIndex)
+{
+    struct SysConfigData *pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
+    struct SysInfoData *pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
+    struct ChargingInfoData* pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(gunIndex);
+    ShmDcCommonData = (DcCommonInfo *)GetShmDcCommonData();
+
+
+    if (pDcChargingInfo->SystemStatus == S_RESERVATION) {
+        if (strcmp((char*)pSysConfig->UserId, (char*)ShmDcCommonData->pGunInfo[gunIndex].ReservationID) != EQUAL) {
+            log_info("LCM => Authorize fail");
+            ShmDcCommonData->TradeCancel = TRUE;
+            ShmDcCommonData->PreAuth_Config = _CREDITCARD_CANCEL;
+            ShmDcCommonData->PreAuth_Result = 0;
+            pSysInfo->SystemPage = _PAGE_AUTHORIZE_FAIL;
+            strcpy((char*)pSysConfig->UserId, "");
+            ClearAuthorizedFlag();
+            return;
+        }
+    }
+    if(isAuthorizedComplete())
+    {
+        if (canStartCharging()) {
+            DetectPluginStart(gunIndex);
+            if (ShmDcCommonData->AuthPass_flag[gunIndex] == TRUE &&
+                ShmDcCommonData->TradeCancel == FALSE) {
+                pSysInfo->SystemPage = _PAGE_PLUGIN;
+            }
+
+        } else {
+            struct ChargingInfoData* pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(gunIndex);
+            log_info("LCM => Authorize fail");
+            ShmDcCommonData->TradeCancel = TRUE;
+            ShmDcCommonData->PreAuth_Config = _CREDITCARD_CANCEL;
+            ShmDcCommonData->PreAuth_Result = 0;
+            if (!pDcChargingInfo->RemoteStartFlag || !pDcChargingInfo->isRemoteStart)
+                pSysInfo->SystemPage = _PAGE_AUTHORIZE_FAIL;
+            strcpy((char *)pSysConfig->UserId, "");
+        }
+        ClearAuthorizedFlag();
+    }
+}
+void ScannerCardProcess(int gunIndex)
+{
+    //struct SysConfigData *pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
+    struct SysInfoData *pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
+    struct WARNING_CODE_INFO *pSysWarning = (struct WARNING_CODE_INFO *)GetShmSysWarningInfo();
+    struct ChargingInfoData *pDcChargingInfo = NULL;
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+
+    if (!isDetectPlugin(gunIndex) && (pSysInfo->SystemPage == _PAGE_SENSING ||
+    		pSysInfo->SystemPage == _PAGE_AUTHORIZE ) &&
+    		(pDcChargingInfo->SystemStatus == S_IDLE || pDcChargingInfo->SystemStatus == S_RESERVATION )&&
+            pSysWarning->Level != WARN_LV_ER ) {
+    	//setSelGunWaitToAuthor(gunIndex);
+        isCardScan = true;
+        // 處理刷卡及驗證卡號的動作
+        UserScanFunction(gunIndex);
+    }
+
+    if (pDcChargingInfo->SystemStatus == S_AUTHORIZING && pSysInfo->SystemPage == _PAGE_SENSING &&
+        !ShmDcCommonData->is_RemoteStart[gunIndex] ) {
+        AuthorizeToCharge(gunIndex);
+    } else if (pSysInfo->SystemPage == _PAGE_AUTHORIZE_FAIL) {
+        StartSystemTimeoutDet(Timeout_VerifyFail);
+        isCardScan = false;
+    } else {
+        isCardScan = false;
+    }
+}
+void storePayResult(uint8_t gunIndex)
+{
+    memset(&LocalTransactionInfo, 0x00, sizeof(RecordTransactionInfo));
+
+    memcpy(&LocalTransactionInfo, &ShmDcCommonData->TransactionInfo[gunIndex] ,sizeof(RecordTransactionInfo));
+
+}
+void getPayResult(uint8_t gunIndex)
+{
+    memcpy(&ShmDcCommonData->TransactionInfo[gunIndex], &LocalTransactionInfo, sizeof(RecordTransactionInfo));
+}
+
+void storeParkingPayResult(uint8_t gunIndex)
+{
+    memset(&LocalTransactionInfo, 0x00, sizeof(RecordTransactionInfo));
+    memcpy(&LocalTransactionInfo, &ShmDcCommonData->ParkingInfo[gunIndex] ,sizeof(RecordTransactionInfo));
+
+}
+void getParkingPayResult(uint8_t gunIndex)
+{
+    //memcpy(&ShmDcCommonData->ParkingInfo[gunIndex], &LocalTransactionInfo, sizeof(RecordTransactionInfo));
+    memcpy( ShmDcCommonData->ParkingInfo[gunIndex].OccupancySN, LocalTransactionInfo.OccupancySN, 36);
+}
+void WritePayResult(int result ,uint8_t gunIndex)
+{
+    if (result == TRUE)
+        ShmDcCommonData->TransactionInfo[gunIndex].DeductResult = _DEDUCT_COMPLETE_PASS;
+    else
+        ShmDcCommonData->TransactionInfo[gunIndex].DeductResult = _DEDUCT_COMPLETE_FAIL;
+
+    log_info("Gun[%d] TransactionId:%d DeductResult:%d IsDonateInvoice:%d Amount:%f VemData:%s Approve No:%s",
+        gunIndex, ShmDcCommonData->TransactionInfo[gunIndex].TransactionId,
+        ShmDcCommonData->TransactionInfo[gunIndex].DeductResult,
+        ShmDcCommonData->TransactionInfo[gunIndex].IsDonateInvoice,
+        ShmDcCommonData->TransactionInfo[gunIndex].Amount,
+        ShmDcCommonData->TransactionInfo[gunIndex].pCreditCard.VemData,
+        ShmDcCommonData->TransactionInfo[gunIndex].pCreditCard.ApprovalNo);
+}
+
+void PreAuthCompleteToCardReader(int fd,uint8_t gunIndex)
+{
+    struct SysConfigData* pSysConfig = (struct SysConfigData*)GetShmSysConfigData();
+	int result = 0;
+
+    storePayResult(gunIndex);
+    if (ShmDcCommonData->TransactionInfo[gunIndex].Amount > 0 && ShmDcCommonData->TransactionInfo[gunIndex].Amount < 1 &&
+        ShmDcCommonData->pGunInfo[gunIndex].ParkingStatus == 0) {
+        log_info("final cost less 1 : %f", ShmDcCommonData->TransactionInfo[gunIndex].Amount);
+        ShmDcCommonData->TransactionInfo[gunIndex].Amount = 1;
+    }
+
+	result = CreditCardPreAuthComplete(fd,(int)LocalTransactionInfo.Amount, &pSysConfig->ModelName[0],
+											&ShmDcCommonData->TransactionInfo[gunIndex].pCreditCard.VemData[0],
+											&ShmDcCommonData->TransactionInfo[gunIndex]);
+    getPayResult(gunIndex);
+
+    //sleep(10);
+	if (result > 0 ) {
+		log_info("Credit Card Spend Money:%.1f", ShmDcCommonData->TransactionInfo[gunIndex].Amount);
+		pSysInfo->SystemPage = _PAGE_COMPLETE;
+        ShmDcCommonData->TransactionInfo[gunIndex].DeductResult = _DEDUCT_COMPLETE_PASS;
+		WritePayResult(TRUE,gunIndex);
+        ShmDcCommonData->PayPass_flag[gunIndex] = TRUE;
+	} else {
+		log_info("PAYING FAIL");
+		ShmDcCommonData->PayPass_flag[gunIndex] = FALSE;
+		pSysInfo->SystemPage = _PAGE_PAYFAIL;
+        ShmDcCommonData->TransactionInfo[gunIndex].DeductResult = _DEDUCT_COMPLETE_FAIL;
+		WritePayResult(FALSE,gunIndex);
+	}
+    ShmDcCommonData->TransactionInfo[gunIndex].IsUpload = FALSE;
+    //getPayResult(gunIndex);
+
+    UpdateDeductInfoStatus(gunIndex, &ShmDcCommonData->TransactionInfo[gunIndex]);
+
+    ShmDcCommonData->PreAuth_Result = result;
+}
+int CreditCardCancelPreAuth(int fd, uint8_t gunIndex)
+{
+    if (ShmDcCommonData->pGunInfo[gunIndex].ParkingStatus) {
+        return;
+    }
+    struct SysConfigData* pSysConfig = (struct SysConfigData*)GetShmSysConfigData();
+    storePayResult(gunIndex);
+
+    ShmDcCommonData->PreAuth_Result = CreditCardPreAuthCancel(fd, PREAUTHMONEY, &pSysConfig->ModelName[0],
+                                    &LocalTransactionInfo.pCreditCard.ApprovalNo[0],
+                                    &LocalTransactionInfo.pCreditCard.CardNo[0],
+                                    &LocalTransactionInfo.pCreditCard.VemData[0]);
+    //sleep(10);
+    if (ShmDcCommonData->PreAuth_Result >= 0) {
+        strcpy((char*)pSysConfig->UserId, "");
+        //ShmDcCommonData->PayFinish[gunIndex] = TRUE;
+        log_info("Gun%d Card Reader PreAuth Cancel Success",gunIndex);
+        LocalTransactionInfo.DeductResult = _DEDUCT_CANCEL;
+    } else if (ShmDcCommonData->PreAuth_Result < 0) {
+        log_info("Gun%d Card Reader PreAuth Cancel Failure",gunIndex);
+        LocalTransactionInfo.DeductResult = _DEDUCT_PREAUTH;
+    }
+    LocalTransactionInfo.IsUpload = FALSE;
+    getPayResult(gunIndex);
+
+    UpdateDeductInfoStatus(gunIndex, &LocalTransactionInfo);
+
+    memset(&ShmDcCommonData->TransactionInfo[gunIndex], 0x00, sizeof(RecordTransactionInfo));
+    ShmDcCommonData->PreAuth_Config = _CREDITCARD_IDLE;
+    return ShmDcCommonData->PreAuth_Result;
+}
+
+void ReDeductProcess(int fd)
+{
+    struct SysConfigData* pSysConfig = (struct SysConfigData*)GetShmSysConfigData();
+    int j;
+    int result;
+    int rededuct_gunIndex[128];
+    RecordTransactionInfo deductInfo[128];
+    int rededuct_num = 0;
+    // 充電費補扣款
+    rededuct_num = DB_GetMultiReDeductInfo(&rededuct_gunIndex[0], &deductInfo[0]);
+
+    if (rededuct_num == 0) {
+        //log_info("No Rededuct Information");
+    } else {
+        ShmDcCommonData->CreditCardUpload = TRUE;
+        pSysInfo->SystemPage = _PAGE_PAYING;
+        log_info("Rededuct Total Number:%d", rededuct_num);
+        for (j = rededuct_num-1; j >= 0 ; j--) {
+            sleep(10);
+
+            log_info("Start Rededuct item [%d]",j);
+            if (deductInfo[j].isIntoCharge == FALSE ||
+                (deductInfo[j].Energy == 0 && deductInfo[j].Amount == 0) ||
+                (deductInfo[j].LineStatus == _LINE_PAY_DONATE || deductInfo[j].LineStatus == _LINE_PAY_INVOICE)) {
+                // 未進入充電或度數等於零
+                result = CreditCardPreAuthCancel(fd, PREAUTHMONEY, &pSysConfig->ModelName[0],
+                    &deductInfo[j].pCreditCard.ApprovalNo[0],
+                    &deductInfo[j].pCreditCard.CardNo[0],
+                    &deductInfo[j].pCreditCard.VemData[0]);
+                sleep(10);
+                if (result > 0) {
+                    deductInfo[j].DeductResult = _DEDUCT_CANCEL;
+                    log_info("Backgroud PreAuthCancel OK");
+                }
+            } else {
+                // 度數大於零
+                if (deductInfo[j].Amount == 0 && deductInfo[j].Energy > 0) {
+                    log_info("Error Close Charging recount amount:%.1f",deductInfo[j].Amount);
+                    continue;
+                }
+                result = CreditCardPreAuthComplete(fd, (int)deductInfo[j].Amount, &pSysConfig->ModelName[0],
+                    &deductInfo[j].pCreditCard.VemData[0],
+                    &ShmDcCommonData->TransactionInfo[0].pCreditCard);
+                if (result > 0) {
+                    deductInfo[j].DeductResult = _DEDUCT_COMPLETE_PASS;
+                    log_info("Backgroud PreAuthComplete OK");
+                } else if (result < 0) {
+                    deductInfo[j].DeductResult = _DEDUCT_COMPLETE_FAIL;
+                    log_info("Backgroud ID:%d Amount:%d VemData:%s PreAuthComplete fail",
+                        deductInfo[j].TransactionId,
+                        (int)deductInfo[j].Amount,
+                        deductInfo[j].pCreditCard.VemData);
+                }
+            }
+            deductInfo[j].IsUpload = FALSE;
+            deductInfo[j].RedeductTime++;
+            UpdateDeductInfoStatus(rededuct_gunIndex[j], &deductInfo[j]);
+        }
+    }
+    // 佔位費補扣款
+    /*
+    rededuct_num = DB_GetParkingDeductResult(&rededuct_gunIndex[0], &deductInfo[0]);
+
+    if (rededuct_num == 0) {
+        log_info("No Parking Rededuct Information");
+    } else {
+        ShmDcCommonData->CreditCardUpload = TRUE;
+        pSysInfo->SystemPage = _PAGE_PAYING;
+        log_info("Parking Rededuct Total Number:%d", rededuct_num);
+        for (j = rededuct_num-1; j >= 0 ; j--) {
+            sleep(3);
+
+            log_info("Start Parking Rededuct item [%d]",j);
+
+            result = CreditCardPreAuthComplete(fd, (int)deductInfo[j].Amount, &pSysConfig->ModelName[0],
+                &deductInfo[j].pCreditCard.VemData[0],
+                &ShmDcCommonData->ParkingInfo[0].pCreditCard);
+            if (result > 0) {
+                deductInfo[j].DeductResult = _DEDUCT_COMPLETE_PASS;
+                log_info("Backgroud Parking PreAuthComplete OK");
+            } else if (result < 0) {
+                deductInfo[j].DeductResult = _DEDUCT_COMPLETE_FAIL;
+                log_info("Backgroud Parking ID:%d Amount:%d VemData:%s PreAuthComplete fail",
+                    deductInfo[j].TransactionId,
+                    (int)deductInfo[j].Amount,
+                    deductInfo[j].pCreditCard.VemData);
+            }
+            
+            deductInfo[j].IsUpload = FALSE;
+            deductInfo[j].RedeductTime++;
+            UpdateParkingDeductInfo(rededuct_gunIndex[j], &deductInfo[j]);
+        }
+    }
+    */
+    ShmDcCommonData->RoutineReduct = TRUE;
+}
+static int InitialRfidPort(void)
+{
+    int fd = open(rfidPortName, O_RDWR);
+    struct termios tios;
+    struct AlarmCodeData *pAlarmCode = (struct AlarmCodeData *)GetShmAlarmCodeData();
+
+    if (fd != FAIL) {
+        ioctl (fd, TCGETS, &tios);
+        tios.c_cflag = B115200 | CS8 | CLOCAL | CREAD;
+        tios.c_lflag = 0;
+        tios.c_iflag = 0;
+        tios.c_oflag = 0;
+        tios.c_cc[VMIN] = 0;
+        tios.c_cc[VTIME] = (uint8_t) 1;
+        tios.c_lflag = 0;
+        tcflush(fd, TCIFLUSH);
+        ioctl(fd, TCSETS, &tios);
+    }
+
+    if (fd < 0) {
+        pAlarmCode->AlarmEvents.bits.RfidModuleCommFail = 1;
+    }
+
+    return fd;
+}
+void RemoteStartCancelPreAuth(int sel_gun)
+{
+    log_info("Remote start need to cancel PreAuth");
+    memcpy(&ShmDcCommonData->RedeductBill, &ShmDcCommonData->TransactionInfo[sel_gun], sizeof(RecordTransactionInfo));
+    memset(&ShmDcCommonData->TransactionInfo[sel_gun], 0x00, sizeof(RecordTransactionInfo));
+    ShmDcCommonData->TransactionInfo[sel_gun].LineStatus = ShmDcCommonData->RedeductBill.LineStatus;
+}
+void PreAuthCreditCard(int fd, uint8_t gunIndex)
+{
+    struct SysConfigData* pSysConfig = (struct SysConfigData*)GetShmSysConfigData();
+    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);;
+    int result = 0;
+    storePayResult(gunIndex);
+    if (ShmDcCommonData->pGunInfo[gunIndex].ParkingStatus)
+        result = CreditCardPreAuth(fd, LocalTransactionInfo.Amount,&pSysConfig->ModelName[0], &LocalTransactionInfo.pCreditCard);
+    else
+        result = CreditCardPreAuth(fd, PREAUTHMONEY,&pSysConfig->ModelName[0], &LocalTransactionInfo.pCreditCard);
+    ShmDcCommonData->PreAuth_Result = result;
+    pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(gunIndex);
+    {
+        if (!checkRemoteStart(gunIndex)) {
+            if (!ShmDcCommonData->TradeCancel)
+                StopSystemTimeoutDet();
+            if (ShmDcCommonData->TradeCancel == FALSE && result > 0) {
+                pSysInfo->SystemPage = _PAGE_SENSING;
+            }
+        }
+
+        if (result > 0 && strcmp((char*)LocalTransactionInfo.pCreditCard.CardNo, "") != 0) {
+            log_info("Gun%d PreAuth card:%s", gunIndex, LocalTransactionInfo.pCreditCard.CardNo);
+            LocalTransactionInfo.DeductResult = _DEDUCT_PREAUTH;
+            LocalTransactionInfo.IsUpload = FALSE;
+            LocalTransactionInfo.ConnectorID = ShmDcCommonData->ConnectorID[gunIndex];
+            //log_info("Gun%d Line Status:%d", LocalTransactionInfo.LineStatus);
+            if (ShmDcCommonData->pGunInfo[gunIndex].ParkingStatus)
+                InsertParkingDeductInfo(ShmDcCommonData->ConnectorID[gunIndex], &LocalTransactionInfo);
+            else {
+                ShmDcCommonData->AuthPass_flag[gunIndex] = TRUE;
+                strncpy((char*)pSysConfig->UserId, (char*)LocalTransactionInfo.pCreditCard.CardNo, 20);
+                InsertDeductInfo(ShmDcCommonData->ConnectorID[gunIndex], &LocalTransactionInfo);
+            }
+            getPayResult(gunIndex);
+            //log_info("Gun%d PreAuth OK",gunIndex);
+        } else if (result < 0) {
+            if (ShmDcCommonData->TradeCancel == FALSE && !checkRemoteStart(gunIndex))
+                pSysInfo->SystemPage = _PAGE_AUTHORIZE_FAIL;
+            ShmDcCommonData->AuthPass_flag[gunIndex] = FALSE;
+            memset(&LocalTransactionInfo.pCreditCard, 0, sizeof(TransInfo));
+            log_info("Gun%d PreAuth Fail",gunIndex);
+        }
+        ShmDcCommonData->PreAuth_Config = _CREDITCARD_IDLE;
+    }
+}
+void CreateRfidFork(void)
+{
+    pid_t rfidRecPid;
+    int donate = 0;
+    rfidRecPid = fork();
+    int sel_gun = 0;
+    int linestatus = 0;
+    if (rfidRecPid == 0) {
+        //char localTime[128] = {0};
+        struct timeb SeqEndTime;
+        struct tm *tm;
+        pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
+        int fd = -1;
+        int isContinue = 1;
+        //RFID rfid = {0};
+        //RecordTransactionInfo deduct;
+        fd = InitialRfidPort();
+        struct SysConfigData *pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
+        ShmDcCommonData = (DcCommonInfo *)GetShmDcCommonData();
+        ShmSelectGunInfo = (SelectGunInfo *)GetShmSelectGunInfo();
+        struct ChargingInfoData *pDcChargingInfo = NULL;
+        if (DeductDB_Open() != PASS) {
+            isDb_ready = false;
+            log_info("DeductDB_Open Fail");
+            return;
+        } else {
+            isDb_ready = true;
+            //InsertDeductInfo(0, &ShmDcCommonData->TransactionInfo);
+        }
+        if (ParkingDB_Open() != PASS) {
+            isDb_ready = false;
+            log_info("ParkingDB_Open Fail");
+            return;
+        } else {
+            isDb_ready = true;
+            //InsertDeductInfo(0, &ShmDcCommonData->TransactionInfo);
+        }
+        int gunIndex;
+        //int uploadIndex = 0;
+        //int ReAuthComplete_Index = 0;
+        //log_info("RFID fork Child's PID is %d", getpid());
+        int result;
+        int is_idle = TRUE;
+        while (isContinue) {
+        	result = 0;
+            usleep(500000);
+            ftime(&SeqEndTime);
+            SeqEndTime.time = time(NULL);
+            tm = localtime(&SeqEndTime.time);
+
+            if (ShmDcCommonData->DebugFlag == TRUE ||
+                ShmDcCommonData->is_RemoteStart[pSysInfo->CurGunSelected] == TRUE ||
+                ShmDcCommonData->is_AutoStart[pSysInfo->CurGunSelected] == TRUE) {
+                ShmDcCommonData->PreAuth_Config = _CREDITCARD_IDLE;
+                ShmDcCommonData->PreAuth_Result = 0;
+            }
+
+            is_idle = TRUE;
+			for (gunIndex = 0; gunIndex < pSysConfig->TotalConnectorCount; gunIndex++) {
+				pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+
+                // 檢查電樁狀態是否為idle狀態
+				if (pDcChargingInfo->SystemStatus != S_IDLE ) {
+					is_idle = FALSE;
+				}
+                // 檢查使用者是否進行線上支付操作並且線下支付已完成
+                // 需進行取消預授權
+                if (checkRemoteStart(gunIndex) && ShmDcCommonData->AuthPass_flag[gunIndex] &&
+                    !ShmDcCommonData->PayPass_flag[gunIndex]) {
+                    RemoteStartCancelPreAuth(gunIndex);
+                    ShmDcCommonData->AuthPass_flag[gunIndex] = FALSE;
+                }
+
+                if (ShmDcCommonData->StopCharge[gunIndex] == TRUE && pDcChargingInfo->Replug_flag == TRUE) {
+                    // Remote Start of AutoStart ByPass Credit Card Reader
+                    if (ShmDcCommonData->DebugFlag == TRUE ||
+                        ShmDcCommonData->is_RemoteStart[gunIndex] == TRUE ||
+                        ShmDcCommonData->is_AutoStart[gunIndex] == TRUE) {
+                        continue;
+                    }
+                    log_info("Gun %d Not Into Charging cancel Trade",gunIndex);
+            
+                    StopGunInfoTimeoutDet(gunIndex);
+                    ShmDcCommonData->TradeCancel = TRUE;
+                    pSysInfo->SystemPage = _PAGE_SENSING;
+                    StartSystemTimeoutDet(Timeout_TradeCancel);
+                    CreditCardCancelPreAuth(fd, gunIndex);
+                    pSysInfo->CurGunSelected = gunIndex;
+                    pSysInfo->SystemPage = _PAGE_PLUGOUT;
+                    StopSystemTimeoutDet();
+                    ShmDcCommonData->StopCharge[gunIndex] = FALSE;
+                } else {
+                    if (ShmDcCommonData->StopCharge[gunIndex] && ShmDcCommonData->finalcost_flag[gunIndex] &&
+                        ShmDcCommonData->PreAuth_Config != _CREDITCARD_CANCEL) {
+
+                        pSysInfo->CurGunSelected = gunIndex;
+                        StopGunInfoTimeoutDet(gunIndex); //Timeout_FinalCost
+
+                        // Remote Start of AutoStart ByPass Credit Card Reader
+                        if (ShmDcCommonData->DebugFlag == TRUE || checkRemoteStart(gunIndex) ||
+                            ShmDcCommonData->is_AutoStart[gunIndex]) {
+                            if (ShmDcCommonData->is_AutoStart[gunIndex]) {
+                                ShmDcCommonData->PayPass_flag[gunIndex] = TRUE;
+                            }
+                            ShmDcCommonData->StopCharge[gunIndex] = FALSE;
+                            continue;
+                        }
+
+                        // 實際扣款
+                        if (ShmDcCommonData->TransactionInfo[gunIndex].Amount < 1) {
+                            log_info("Final Cost less 1 , Cancel Trade!!");
+                            if (CreditCardCancelPreAuth(fd, gunIndex) > 0) {
+                                pSysInfo->SystemPage = _PAGE_COMPLETE;
+                                ShmDcCommonData->PayPass_flag[gunIndex] = TRUE;
+                            } else {
+                                pSysInfo->SystemPage = _PAGE_PAYFAIL;
+                                ShmDcCommonData->PayPass_flag[gunIndex] = FALSE;
+                            }
+                        } else {
+                            ShmDcCommonData->PreAuth_Config = _CREDITCARD_PREAUTHCOMPLETE;
+                            PreAuthCompleteToCardReader(fd, gunIndex);
+                             ShmDcCommonData->PreAuth_Config = _CREDITCARD_IDLE;
+                        }
+                        ShmDcCommonData->StopCharge[gunIndex] = FALSE;
+                    }
+                }
+			} // for
+            if (ShmDcCommonData->PreAuth_Config == _CREDITCARD_SALE /*&& ShmDcCommonData->pGunInfo[pSysInfo->CurGunSelected].isParking*/) {
+                sel_gun = pSysInfo->CurGunSelected;
+                ShmDcCommonData->PreAuth_Result = 0;
+                storeParkingPayResult(sel_gun);
+                
+                ShmDcCommonData->PreAuth_Result = CreditCardSale(fd,(int)ShmDcCommonData->ParkingInfo[sel_gun].Amount,
+                                                &pSysConfig->ModelName[0],
+                                                &ShmDcCommonData->ParkingInfo[sel_gun].pCreditCard);
+                StopSystemTimeoutDet(); //Timeout_ScanCard
+                getParkingPayResult(sel_gun);
+                if (ShmDcCommonData->PreAuth_Result > 0 ) {
+                    log_info("Gun%d Parking Fee Sale Success",sel_gun);
+                    pSysInfo->SystemPage = _PAGE_PLUGIN;
+                    ShmDcCommonData->ParkingInfo[sel_gun].IsUpload = FALSE;
+                    //ShmDcCommonData->pGunInfo[sel_gun].GetParkingBill = FALSE;
+                    ShmDcCommonData->ParkingInfo[sel_gun].DeductResult = _DEDUCT_SALE_PASS;
+                    InsertParkingDeductInfo(ShmDcCommonData->ConnectorID[sel_gun], &ShmDcCommonData->ParkingInfo[sel_gun]);
+                } else {
+                    log_info("Gun%d Parking Fee Sale Fail",sel_gun);
+                    if (!ShmDcCommonData->TradeCancel) {
+                        pSysInfo->SystemPage = _PAGE_AUTHORIZE_FAIL;
+                    }
+                }
+                ShmDcCommonData->PreAuth_Result = 0;
+                ShmDcCommonData->PreAuth_Config = _CREDITCARD_IDLE;
+            } else if(ShmDcCommonData->PreAuth_Config == _CREDITCARD_CANCEL) {
+                // 取消預授權
+                CreditCardCancelPreAuth(fd,pSysInfo->CurGunSelected);
+            } else if (ShmDcCommonData->PreAuth_Config == _CREDITCARD_PREAUTH ) {
+                // 預授權
+                sel_gun = pSysInfo->CurGunSelected;
+                if (ShmDcCommonData->pGunInfo[sel_gun].isParking) {
+                    log_info("In Parking Status can't enable PreAuth function");
+                    pSysInfo->SystemPage = _PAGE_AUTHORIZE_FAIL;
+                    ShmDcCommonData->AuthPass_flag[gunIndex] = FALSE;
+                    ShmDcCommonData->PreAuth_Config = _CREDITCARD_IDLE;
+                } else
+                    PreAuthCreditCard(fd,sel_gun);
+                // 佔位費預授權並扣款
+                /*
+                if (ShmDcCommonData->PreAuth_Result > 0 ) {
+                        log_info("Gun%d Parking Fee PreAuthComplete Success",sel_gun);
+                        pSysInfo->SystemPage = _PAGE_PLUGIN;
+                        StartSystemTimeoutDet(Timeout_ReturnViewPage);
+                } else {
+                    log_info("Gun%d Parking Fee PreAuthComplete Fail",sel_gun);
+                    if (!ShmDcCommonData->TradeCancel) {
+                        pSysInfo->SystemPage = _PAGE_AUTHORIZE_FAIL;
+                        StartSystemTimeoutDet(Timeout_VerifyFail);
+                    }
+                }
+                
+                if (ShmDcCommonData->pGunInfo[sel_gun].ParkingStatus && ShmDcCommonData->PreAuth_Result > 0 &&
+                    !ShmDcCommonData->TradeCancel && ShmDcCommonData->PreAuth_Config != _CREDITCARD_CANCEL ) {
+                    ShmDcCommonData->PreAuth_Result = 0;
+                    sleep(10);
+                    PreAuthCompleteToCardReader(fd, sel_gun);
+                    if (ShmDcCommonData->PreAuth_Result > 0 ) {
+                        log_info("Gun%d Parking Fee PreAuthComplete Success",sel_gun);
+                        pSysInfo->SystemPage = _PAGE_PLUGIN;
+                        StartSystemTimeoutDet(Timeout_ReturnViewPage);
+                    } else {
+                        log_info("Gun%d Parking Fee PreAuthComplete Fail",sel_gun);
+                        if (!ShmDcCommonData->TradeCancel) {
+                            pSysInfo->SystemPage = _PAGE_AUTHORIZE_FAIL;
+                            StartSystemTimeoutDet(Timeout_VerifyFail);
+                        }
+                    }
+                    ShmDcCommonData->PreAuth_Result = 0;
+                }*/
+            }
+
+            // 每30分鐘檢查補扣款
+            if (tm->tm_min %30 == 0 && tm->tm_sec == 0) {
+                ShmDcCommonData->RoutineReduct = FALSE;
+            }
+
+            if ((is_idle == TRUE &&
+                pSysInfo->SystemPage == _PAGE_IDLE  &&
+                ShmDcCommonData->RoutineReduct == FALSE) || ShmDcCommonData->Exe_ReDeduct) {
+
+                ReDeductProcess(fd);
+                pSysInfo->SystemPage = _PAGE_IDLE;
+                ShmDcCommonData->CreditCardUpload = FALSE;
+                ShmDcCommonData->Exe_ReDeduct = 0;
+            }
+
+            // 每日晚上11點30分結帳
+            if (is_idle == TRUE && pSysInfo->SystemPage == _PAGE_IDLE  &&
+                ((tm->tm_hour == 15 && tm->tm_min > 30  && ShmDcCommonData->RoutineSettlement == FALSE) ||
+                    ShmDcCommonData->UnionSettlement)) {
+                StopSystemTimeoutDet();
+                if (ShmDcCommonData->UnionSettlement)
+                    ShmDcCommonData->UnionSettlement = 0;
+                else
+                    ShmDcCommonData->RoutineSettlement = TRUE;
+                ShmDcCommonData->CreditCardUpload = TRUE;
+                pSysInfo->SystemPage = _PAGE_PAYING;
+                 
+                result = CreditCardUnionSettlement(fd, &pSysConfig->ModelName[0], &LocalTransactionInfo.pCreditCard);
+                if (result > 0) {
+                    log_info("CreditCardUnionSettlement OK");
+                }
+                else
+                    log_info("CreditCardUnionSettlement FAIL");
+                sleep(90);
+                pSysInfo->SystemPage = _PAGE_IDLE;
+
+                ShmDcCommonData->CreditCardUpload = FALSE;
+            }
+            if (tm->tm_hour == 16 && tm->tm_min == 0) {
+                ShmDcCommonData->RoutineSettlement = FALSE;
+            }
+        }
+    }
+}
+

+ 215 - 215
EVSE/Projects/DD360Tcci/Apps/CSU/SelfTest.c

@@ -1,215 +1,215 @@
-#include <stdio.h>      /*標準輸入輸出定義*/
-#include <stdlib.h>     /*標準函數庫定義*/
-#include <string.h>
-#include <stdint.h>
-
-#include "../Config.h"
-#include "../Log/log.h"
-#include "../Define/define.h"
-#include "../ShareMemory/shmMem.h"
-
-#include "main.h"
-#include "../timeout.h"
-
-//------------------------------------------------------------------------------
-extern void ChkPrimaryStatus(void);
-
-//------------------------------------------------------------------------------
-void SelfTestRun(void)
-{
-    bool evInitFlag = false;
-    bool isRelayBypass = false;
-    uint8_t index = 0;
-    struct SysConfigData *pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
-    struct SysInfoData *pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
-    struct WARNING_CODE_INFO *pSysWarning = (struct WARNING_CODE_INFO *)GetShmSysWarningInfo();
-
-    struct PsuData *ShmPsuData = (struct PsuData *)GetShmPsuData();
-    struct CHAdeMOData *ShmCHAdeMOData = (struct CHAdeMOData *)GetShmCHAdeMOData();
-    struct GBTData *ShmGBTData = (struct GBTData *)GetShmGBTData();
-    struct CcsData *ShmCcsData = (struct CcsData *)GetShmCcsData();
-
-    struct PrimaryMcuData *ShmPrimaryMcuData = (struct PrimaryMcuData *)GetShmPrimaryMcuData();
-    struct FanModuleData *ShmFanModuleData = (struct FanModuleData *)GetShmFanModuleData();
-    struct RelayModuleData *ShmRelayModuleData = (struct RelayModuleData *)GetShmRelayModuleData();
-    struct ChargingInfoData *pDcChargingInfo = NULL;
-    struct ChargingInfoData *pAcChargingInfo = NULL;
-
-    for(int i = 0; i < pSysConfig->TotalConnectorCount; i++)
-    {
-        pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(i);
-        if(pDcChargingInfo->PantographFlag == YES)
-        {
-            isRelayBypass = true;
-        }
-    }
-
-    StartSystemTimeoutDet(Timeout_SelftestChk);
-    pSysInfo->SelfTestSeq = _STEST_VERSION;
-
-    while (pSysInfo->SelfTestSeq != _STEST_COMPLETE) {
-        if (pSysInfo->SelfTestSeq == _STEST_COMPLETE) { //自檢完成
-            return;
-        }
-        
-        ChkPrimaryStatus(); //確認硬體有無錯誤,如急停按鈕或門有打開
-
-        if (pSysWarning->Level == WARN_LV_ER) {
-            pSysInfo->SelfTestSeq = _STEST_FAIL;
-            return;
-        }
-
-        if (pSysConfig->TotalConnectorCount <= 0) {
-            pSysInfo->SelfTestSeq = _STEST_FAIL;
-            return;
-        }
-
-        if (ShmPsuData->Work_Step == _NO_WORKING ||
-                pSysInfo->SelfTestSeq == _STEST_FAIL) {
-            pSysInfo->SelfTestSeq = _STEST_FAIL;
-            return;
-        }
-
-        switch (pSysInfo->SelfTestSeq) {
-        case _STEST_VERSION:
-            if(isRelayBypass == YES && ShmRelayModuleData->SelfTest_Comp != YES)
-            {
-                log_info("Relay Board Bypass");
-                ShmRelayModuleData->SelfTest_Comp = YES;
-            }
-            if ((strlen((char *)pSysInfo->RelayModuleFwRev) != 0 ||
-                    pSysInfo->RelayModuleFwRev[0] != '\0') &&
-                    (ShmRelayModuleData->SelfTest_Comp != YES)
-               ) {
-                //log_info("Relay Board FW Rev = %s", pSysInfo->RelayModuleFwRev);
-                ShmRelayModuleData->SelfTest_Comp = YES;
-            }
-
-#if !defined NO_FAN_BOARD && !defined DD360ComBox
-            if ((strlen((char *)pSysInfo->FanModuleFwRev) != 0 ||
-                    pSysInfo->FanModuleFwRev[0] != '\0') &&
-                    (ShmFanModuleData->SelfTest_Comp != YES)
-               ) {
-                //log_info("Fan Board FW Rev = %s", pSysInfo->FanModuleFwRev);
-                ShmFanModuleData->SelfTest_Comp = YES;
-            }
-#else
-            ShmFanModuleData->SelfTest_Comp = YES;
-#endif //NO_FAN_BOARD
-
-            if ((strlen((char *)ShmPrimaryMcuData->version) != 0 ||
-                    ShmPrimaryMcuData->version[0] != '\0') &&
-                    (ShmPrimaryMcuData->SelfTest_Comp != YES)
-               ) {
-                log_info("Primary Board Pass");
-                ShmPrimaryMcuData->SelfTest_Comp = YES;
-            }
-
-            // EV 小板
-            if (!evInitFlag) {
-                evInitFlag = YES;
-                for (index = 0; index < pSysConfig->TotalConnectorCount; index++) {
-                    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);
-
-                    //log_info("index = %d, charging index = %d, type = %d\r\n",
-                    //         index,
-                    //         chargingInfo[index]->type_index,
-                    //         chargingInfo[index]->Type);
-                    if (pDcChargingInfo->Type == _Type_Chademo) {
-                        if ((strlen((char *)ShmCHAdeMOData->evse[pDcChargingInfo->type_index].version) != 0 ||
-                                ShmCHAdeMOData->evse[pDcChargingInfo->type_index].version[0] != '\0')
-                                //&& (ShmCHAdeMOData->evse[pDcChargingInfo->type_index].SelfTest_Comp != YES)
-                           ) {
-                            //log_info("CHAdeMO[%d] FW Rev = %s",
-                            //         pDcChargingInfo->type_index,
-                            //         ShmCHAdeMOData->evse[pDcChargingInfo->type_index].version);
-                            ShmCHAdeMOData->evse[pDcChargingInfo->type_index].SelfTest_Comp = YES;
-                        } else {
-                            //log_info("chademo fw lose...... %s \n", ShmCHAdeMOData->evse[pDcChargingInfo->type_index].version);
-                            evInitFlag = NO;
-                        }
-                    } else if (pDcChargingInfo->Type == _Type_GB) {
-                        if ((strlen((char *)ShmGBTData->evse[pDcChargingInfo->type_index].version) != 0 ||
-                                ShmGBTData->evse[pDcChargingInfo->type_index].version[0] != '\0')
-                                //&& (ShmGBTData->evse[pDcChargingInfo->type_index].SelfTest_Comp != YES)
-                           ) {
-                            //log_info("GBT[%d] FW Rev = %s",
-                            //         pDcChargingInfo->type_index,
-                            //         ShmGBTData->evse[pDcChargingInfo->type_index].version);
-                            ShmGBTData->evse[pDcChargingInfo->type_index].SelfTest_Comp = YES;
-                        } else {
-                            //log_info("GBT fw lose...... %s \n", ShmCHAdeMOData->evse[pDcChargingInfo->type_index].version);
-                            evInitFlag = NO;
-                        }
-                    } else if (pDcChargingInfo->Type == _Type_CCS_2) {
-                        if (ShmCcsData->CommProtocol == _CCS_COMM_V2GMessage_DIN70121) {
-                            if ((strlen((char *)ShmCcsData->V2GMessage_DIN70121[pDcChargingInfo->type_index].version) != 0 ||
-                                    ShmCcsData->V2GMessage_DIN70121[pDcChargingInfo->type_index].version[0] != '\0')
-                                    /*&&(ShmCcsData->V2GMessage_DIN70121[pDcChargingInfo->type_index].SelfTest_Comp != YES)*/
-                               ) {
-                                //log_info("CCS[%d] FW Rev = %s",
-                                //         pDcChargingInfo->type_index,
-                                //         ShmCcsData->V2GMessage_DIN70121[pDcChargingInfo->type_index].version);
-                                ShmCcsData->V2GMessage_DIN70121[pDcChargingInfo->type_index].SelfTest_Comp = YES;
-                            } else {
-                                //log_info("CCS[%d] ccs fw lose...... %s \n",
-                                //         chargingInfo[index]->type_index,
-                                //         ShmCcsData->V2GMessage_DIN70121[chargingInfo[index]->type_index].version);
-                                evInitFlag = NO;
-                            }
-                        }
-                    }
-                }
-
-                for (index = 0; index < pSysConfig->AcConnectorCount; index++) {
-                    pAcChargingInfo = (struct ChargingInfoData *)GetAcChargingInfoData(index);
-
-                    if (pAcChargingInfo->Type == _Type_AC) {
-                        if ((strlen((char *)pAcChargingInfo->version) != 0 ||
-                                pAcChargingInfo->version[0] != '\0')
-                                && (pAcChargingInfo->SelfTest_Comp != YES)
-                           ) {
-                            //log_info("AC connector[%d] FW Rev = %s", index, pAcChargingInfo->version);
-                            pAcChargingInfo->SelfTest_Comp = YES;
-                        } else {
-                            evInitFlag = NO;
-                        }
-                    }
-                }
-            }
-
-            if (ShmFanModuleData->SelfTest_Comp &&
-                    ShmRelayModuleData->SelfTest_Comp &&
-                    ShmPrimaryMcuData->SelfTest_Comp &&
-                    evInitFlag
-               ) {
-                pSysInfo->SelfTestSeq = _STEST_AC_CONTACTOR;
-            }
-            break;
-
-        case _STEST_AC_CONTACTOR:
-            //ShmPsuData->Work_Step = _TEST_COMPLETE;
-            // 因為 30KW 以下沒有 Relay feedback 功能,所以暫時先直接跳過
-            pSysInfo->SelfTestSeq = _STEST_PSU_DETECT;
-            //log_info("Waiting for DO communication");
-            break;
-
-        case _STEST_PSU_DETECT:
-            pSysInfo->SelfTestSeq = _STEST_PSU_CAP;
-            break;
-
-        case _STEST_PSU_CAP:
-            // 此測試是要確認當前總輸出能力
-            // 如果沒有 PSU 模組請 bypass
-
-            //check the power limit from DO
-            pSysInfo->SelfTestSeq = _STEST_COMPLETE;
-            pSysInfo->BootingStatus = BOOT_COMPLETE;
-            log_info("Successful Self Test");
-            break;
-
-        }
-
-        usleep(100000);
-    }
-}
+#include <stdio.h>      /*標準輸入輸出定義*/
+#include <stdlib.h>     /*標準函數庫定義*/
+#include <string.h>
+#include <stdint.h>
+
+#include "../Config.h"
+#include "../Log/log.h"
+#include "../Define/define.h"
+#include "../ShareMemory/shmMem.h"
+
+#include "main.h"
+#include "../timeout.h"
+
+//------------------------------------------------------------------------------
+extern void ChkPrimaryStatus(void);
+
+//------------------------------------------------------------------------------
+void SelfTestRun(void)
+{
+    bool evInitFlag = false;
+    bool isRelayBypass = false;
+    uint8_t index = 0;
+    struct SysConfigData *pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
+    struct SysInfoData *pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
+    struct WARNING_CODE_INFO *pSysWarning = (struct WARNING_CODE_INFO *)GetShmSysWarningInfo();
+
+    struct PsuData *ShmPsuData = (struct PsuData *)GetShmPsuData();
+    struct CHAdeMOData *ShmCHAdeMOData = (struct CHAdeMOData *)GetShmCHAdeMOData();
+    struct GBTData *ShmGBTData = (struct GBTData *)GetShmGBTData();
+    struct CcsData *ShmCcsData = (struct CcsData *)GetShmCcsData();
+
+    struct PrimaryMcuData *ShmPrimaryMcuData = (struct PrimaryMcuData *)GetShmPrimaryMcuData();
+    struct FanModuleData *ShmFanModuleData = (struct FanModuleData *)GetShmFanModuleData();
+    struct RelayModuleData *ShmRelayModuleData = (struct RelayModuleData *)GetShmRelayModuleData();
+    struct ChargingInfoData *pDcChargingInfo = NULL;
+    struct ChargingInfoData *pAcChargingInfo = NULL;
+
+    for(int i = 0; i < pSysConfig->TotalConnectorCount; i++)
+    {
+        pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(i);
+        if(pDcChargingInfo->PantographFlag == YES)
+        {
+            isRelayBypass = true;
+        }
+    }
+
+    StartSystemTimeoutDet(Timeout_SelftestChk);
+    pSysInfo->SelfTestSeq = _STEST_VERSION;
+
+    while (pSysInfo->SelfTestSeq != _STEST_COMPLETE) {
+        if (pSysInfo->SelfTestSeq == _STEST_COMPLETE) { //自檢完成
+            return;
+        }
+        
+        ChkPrimaryStatus(); //確認硬體有無錯誤,如急停按鈕或門有打開
+
+        if (pSysWarning->Level == WARN_LV_ER) {
+            pSysInfo->SelfTestSeq = _STEST_FAIL;
+            return;
+        }
+
+        if (pSysConfig->TotalConnectorCount <= 0) {
+            pSysInfo->SelfTestSeq = _STEST_FAIL;
+            return;
+        }
+
+        if (ShmPsuData->Work_Step == _NO_WORKING ||
+                pSysInfo->SelfTestSeq == _STEST_FAIL) {
+            pSysInfo->SelfTestSeq = _STEST_FAIL;
+            return;
+        }
+
+        switch (pSysInfo->SelfTestSeq) {
+        case _STEST_VERSION:
+            if(isRelayBypass == YES && ShmRelayModuleData->SelfTest_Comp != YES)
+            {
+                log_info("Relay Board Bypass");
+                ShmRelayModuleData->SelfTest_Comp = YES;
+            }
+            if ((strlen((char *)pSysInfo->RelayModuleFwRev) != 0 ||
+                    pSysInfo->RelayModuleFwRev[0] != '\0') &&
+                    (ShmRelayModuleData->SelfTest_Comp != YES)
+               ) {
+                //log_info("Relay Board FW Rev = %s", pSysInfo->RelayModuleFwRev);
+                ShmRelayModuleData->SelfTest_Comp = YES;
+            }
+
+#if !defined NO_FAN_BOARD && !defined DD360ComBox
+            if ((strlen((char *)pSysInfo->FanModuleFwRev) != 0 ||
+                    pSysInfo->FanModuleFwRev[0] != '\0') &&
+                    (ShmFanModuleData->SelfTest_Comp != YES)
+               ) {
+                //log_info("Fan Board FW Rev = %s", pSysInfo->FanModuleFwRev);
+                ShmFanModuleData->SelfTest_Comp = YES;
+            }
+#else
+            ShmFanModuleData->SelfTest_Comp = YES;
+#endif //NO_FAN_BOARD
+
+            if ((strlen((char *)ShmPrimaryMcuData->version) != 0 ||
+                    ShmPrimaryMcuData->version[0] != '\0') &&
+                    (ShmPrimaryMcuData->SelfTest_Comp != YES)
+               ) {
+                log_info("Primary Board Pass");
+                ShmPrimaryMcuData->SelfTest_Comp = YES;
+            }
+
+            // EV 小板
+            if (!evInitFlag) {
+                evInitFlag = YES;
+                for (index = 0; index < pSysConfig->TotalConnectorCount; index++) {
+                    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);
+
+                    //log_info("index = %d, charging index = %d, type = %d\r\n",
+                    //         index,
+                    //         chargingInfo[index]->type_index,
+                    //         chargingInfo[index]->Type);
+                    if (pDcChargingInfo->Type == _Type_Chademo) {
+                        if ((strlen((char *)ShmCHAdeMOData->evse[pDcChargingInfo->type_index].version) != 0 ||
+                                ShmCHAdeMOData->evse[pDcChargingInfo->type_index].version[0] != '\0')
+                                //&& (ShmCHAdeMOData->evse[pDcChargingInfo->type_index].SelfTest_Comp != YES)
+                           ) {
+                            //log_info("CHAdeMO[%d] FW Rev = %s",
+                            //         pDcChargingInfo->type_index,
+                            //         ShmCHAdeMOData->evse[pDcChargingInfo->type_index].version);
+                            ShmCHAdeMOData->evse[pDcChargingInfo->type_index].SelfTest_Comp = YES;
+                        } else {
+                            //log_info("chademo fw lose...... %s \n", ShmCHAdeMOData->evse[pDcChargingInfo->type_index].version);
+                            evInitFlag = NO;
+                        }
+                    } else if (pDcChargingInfo->Type == _Type_GB) {
+                        if ((strlen((char *)ShmGBTData->evse[pDcChargingInfo->type_index].version) != 0 ||
+                                ShmGBTData->evse[pDcChargingInfo->type_index].version[0] != '\0')
+                                //&& (ShmGBTData->evse[pDcChargingInfo->type_index].SelfTest_Comp != YES)
+                           ) {
+                            //log_info("GBT[%d] FW Rev = %s",
+                            //         pDcChargingInfo->type_index,
+                            //         ShmGBTData->evse[pDcChargingInfo->type_index].version);
+                            ShmGBTData->evse[pDcChargingInfo->type_index].SelfTest_Comp = YES;
+                        } else {
+                            //log_info("GBT fw lose...... %s \n", ShmCHAdeMOData->evse[pDcChargingInfo->type_index].version);
+                            evInitFlag = NO;
+                        }
+                    } else if (pDcChargingInfo->Type == _Type_CCS_2) {
+                        if (ShmCcsData->CommProtocol == _CCS_COMM_V2GMessage_DIN70121) {
+                            if ((strlen((char *)ShmCcsData->V2GMessage_DIN70121[pDcChargingInfo->type_index].version) != 0 ||
+                                    ShmCcsData->V2GMessage_DIN70121[pDcChargingInfo->type_index].version[0] != '\0')
+                                    /*&&(ShmCcsData->V2GMessage_DIN70121[pDcChargingInfo->type_index].SelfTest_Comp != YES)*/
+                               ) {
+                                //log_info("CCS[%d] FW Rev = %s",
+                                //         pDcChargingInfo->type_index,
+                                //         ShmCcsData->V2GMessage_DIN70121[pDcChargingInfo->type_index].version);
+                                ShmCcsData->V2GMessage_DIN70121[pDcChargingInfo->type_index].SelfTest_Comp = YES;
+                            } else {
+                                //log_info("CCS[%d] ccs fw lose...... %s \n",
+                                //         chargingInfo[index]->type_index,
+                                //         ShmCcsData->V2GMessage_DIN70121[chargingInfo[index]->type_index].version);
+                                evInitFlag = NO;
+                            }
+                        }
+                    }
+                }
+
+                for (index = 0; index < pSysConfig->AcConnectorCount; index++) {
+                    pAcChargingInfo = (struct ChargingInfoData *)GetAcChargingInfoData(index);
+
+                    if (pAcChargingInfo->Type == _Type_AC) {
+                        if ((strlen((char *)pAcChargingInfo->version) != 0 ||
+                                pAcChargingInfo->version[0] != '\0')
+                                && (pAcChargingInfo->SelfTest_Comp != YES)
+                           ) {
+                            //log_info("AC connector[%d] FW Rev = %s", index, pAcChargingInfo->version);
+                            pAcChargingInfo->SelfTest_Comp = YES;
+                        } else {
+                            evInitFlag = NO;
+                        }
+                    }
+                }
+            }
+
+            if (ShmFanModuleData->SelfTest_Comp &&
+                    ShmRelayModuleData->SelfTest_Comp &&
+                    ShmPrimaryMcuData->SelfTest_Comp &&
+                    evInitFlag
+               ) {
+                pSysInfo->SelfTestSeq = _STEST_AC_CONTACTOR;
+            }
+            break;
+
+        case _STEST_AC_CONTACTOR:
+            //ShmPsuData->Work_Step = _TEST_COMPLETE;
+            // 因為 30KW 以下沒有 Relay feedback 功能,所以暫時先直接跳過
+            pSysInfo->SelfTestSeq = _STEST_PSU_DETECT;
+            //log_info("Waiting for DO communication");
+            break;
+
+        case _STEST_PSU_DETECT:
+            pSysInfo->SelfTestSeq = _STEST_PSU_CAP;
+            break;
+
+        case _STEST_PSU_CAP:
+            // 此測試是要確認當前總輸出能力
+            // 如果沒有 PSU 模組請 bypass
+
+            //check the power limit from DO
+            pSysInfo->SelfTestSeq = _STEST_COMPLETE;
+            pSysInfo->BootingStatus = BOOT_COMPLETE;
+            log_info("Successful Self Test");
+            break;
+
+        }
+
+        usleep(100000);
+    }
+}

+ 71 - 71
EVSE/Projects/DD360Tcci/Apps/CSU/WatchDog.c

@@ -1,71 +1,71 @@
-#include <stdio.h>      /*標準輸入輸出定義*/
-#include <stdlib.h>     /*標準函數庫定義*/
-#include <string.h>
-#include <stdint.h>
-
-#include "../Config.h"
-#include "../Log/log.h"
-#include "../Define/define.h"
-#include "../ShareMemory/shmMem.h"
-
-int wtdFd = -1;
-struct StatusCodeData           *ShmStatusCodeData;
-
-void CreateWatchdog(void);
-void TryCloseWatchdog(void);
-void TryFeedWatchdog(void);
-
-int InitWatchDog()
-{
-    int fd;
-    int timeout = 180;
-
-    system("/usr/bin/fuser -k /dev/watchdog");
-    sleep(1);
-    system("echo V > /dev/watchdog");
-    sleep(1);
-    fd=open("/dev/watchdog", O_RDWR);
-
-    if(fd<=0)
-    {
-        log_info("Open watchdog fd:%d",fd);
-        log_error("System watch dog initial fail.\n");
-    }
-    ioctl(fd, _IOWR('W', 6, int), &timeout);
-
-    return fd;
-}
-
-void CreateWatchdog(void)
-{
-    wtdFd = InitWatchDog();
-
-    ShmStatusCodeData = (struct StatusCodeData*)GetShmStatusCodeData();
-    if(wtdFd < 0)
-    {
-        log_info("Watchdog Initial Fail");
-        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed = 1;
-    }
-    else
-    {
-        log_info("Watchdog Initial Success (%d)",wtdFd);
-    }
-}
-
-void TryCloseWatchdog(void)
-{
-    if(wtdFd > 0)
-    {
-        write(wtdFd, "V", 1);
-        close(wtdFd);
-    }
-}
-
-void TryFeedWatchdog(void)
-{
-    if(wtdFd > 0)
-    {
-        write(wtdFd, "a", 1);
-    }
-}
-
+#include <stdio.h>      /*標準輸入輸出定義*/
+#include <stdlib.h>     /*標準函數庫定義*/
+#include <string.h>
+#include <stdint.h>
+
+#include "../Config.h"
+#include "../Log/log.h"
+#include "../Define/define.h"
+#include "../ShareMemory/shmMem.h"
+
+int wtdFd = -1;
+struct StatusCodeData           *ShmStatusCodeData;
+
+void CreateWatchdog(void);
+void TryCloseWatchdog(void);
+void TryFeedWatchdog(void);
+
+int InitWatchDog()
+{
+    int fd;
+    int timeout = 180;
+
+    system("/usr/bin/fuser -k /dev/watchdog");
+    sleep(1);
+    system("echo V > /dev/watchdog");
+    sleep(1);
+    fd=open("/dev/watchdog", O_RDWR);
+
+    if(fd<=0)
+    {
+        log_info("Open watchdog fd:%d",fd);
+        log_error("System watch dog initial fail.\n");
+    }
+    ioctl(fd, _IOWR('W', 6, int), &timeout);
+
+    return fd;
+}
+
+void CreateWatchdog(void)
+{
+    wtdFd = InitWatchDog();
+
+    ShmStatusCodeData = (struct StatusCodeData*)GetShmStatusCodeData();
+    if(wtdFd < 0)
+    {
+        log_info("Watchdog Initial Fail");
+        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed = 1;
+    }
+    else
+    {
+        log_info("Watchdog Initial Success (%d)",wtdFd);
+    }
+}
+
+void TryCloseWatchdog(void)
+{
+    if(wtdFd > 0)
+    {
+        write(wtdFd, "V", 1);
+        close(wtdFd);
+    }
+}
+
+void TryFeedWatchdog(void)
+{
+    if(wtdFd > 0)
+    {
+        write(wtdFd, "a", 1);
+    }
+}
+

+ 77 - 77
EVSE/Projects/DD360Tcci/Apps/CSU/ZipFile.c

@@ -1,77 +1,77 @@
-#include <stdio.h>      /*標準輸入輸出定義*/
-#include <stdlib.h>     /*標準函數庫定義*/
-#include <string.h>
-#include <stdint.h>
-
-#include <sys/types.h>
-#include <dirent.h>
-
-#include "../Config.h"
-#include "../Log/log.h"
-#include "../Define/define.h"
-#include "../ShareMemory/shmMem.h"
-
-//------------------------------------------------------------------------------
-void zipLogFiles(void)
-{
-    const char *logPath = "/Storage/SystemLog";
-
-    // 獲取目錄
-    DIR *pDir = opendir(logPath);
-    if (pDir != NULL) {
-        struct timeb csuTime;
-        struct tm *tmCSU;
-
-        ftime(&csuTime);
-        tmCSU = localtime(&csuTime.time);
-//      log_info("Time : %04d-%02d-%02d %02d:%02d:%02d \n", tmCSU->tm_year + 1900,
-//          tmCSU->tm_mon + 1, tmCSU->tm_mday, tmCSU->tm_hour, tmCSU->tm_min,
-//          tmCSU->tm_sec);
-
-        // Read items inside the folder
-        struct dirent *pEntry = NULL;
-        while ((pEntry = readdir(pDir)) != NULL) {
-            if (strcmp(pEntry->d_name, ".") != 0 &&
-                    strcmp(pEntry->d_name, "..") != 0 &&
-                    strncmp(pEntry->d_name, "[", 1) == 0 &&
-                    strstr(pEntry->d_name, "tar") < 0) {
-                char yearC[5];
-                unsigned short year = 0;
-                char monthC[3];
-                unsigned short month = 0;
-
-                yearC[4] = '\0';
-                strncpy(yearC, pEntry->d_name + 1, 4);
-                monthC[2] = '\0';
-                strncpy(monthC, pEntry->d_name + 6, 2);
-
-                year = atoi(yearC);
-                month = atoi(monthC);
-
-                if (year != 0) {
-                    if (year < tmCSU->tm_year + 1900 ||
-                            (year >= tmCSU->tm_year + 1900 && month < tmCSU->tm_mon + 1)) {
-                        log_info("tar file name : %s \n", pEntry->d_name);
-                        char file[256];
-
-                        memset(file, 0x00, sizeof(file));
-                        strcat(file, "tar zcvf ");
-                        strcat(file, logPath);
-                        strncat(file, "/", 1);
-                        strcat(file, pEntry->d_name);
-                        strcat(file, ".tar");
-                        strncat(file, " ", 1);
-                        strcat(file, logPath);
-                        strncat(file, "/", 1);
-                        strcat(file, pEntry->d_name);
-                        log_info("zip = %s \n", file);
-                        system(file);
-                    }
-                }
-            }
-        }
-    }
-
-    // Close folder
-    closedir(pDir);
-}
+#include <stdio.h>      /*標準輸入輸出定義*/
+#include <stdlib.h>     /*標準函數庫定義*/
+#include <string.h>
+#include <stdint.h>
+
+#include <sys/types.h>
+#include <dirent.h>
+
+#include "../Config.h"
+#include "../Log/log.h"
+#include "../Define/define.h"
+#include "../ShareMemory/shmMem.h"
+
+//------------------------------------------------------------------------------
+void zipLogFiles(void)
+{
+    const char *logPath = "/Storage/SystemLog";
+
+    // 獲取目錄
+    DIR *pDir = opendir(logPath);
+    if (pDir != NULL) {
+        struct timeb csuTime;
+        struct tm *tmCSU;
+
+        ftime(&csuTime);
+        tmCSU = localtime(&csuTime.time);
+//      log_info("Time : %04d-%02d-%02d %02d:%02d:%02d \n", tmCSU->tm_year + 1900,
+//          tmCSU->tm_mon + 1, tmCSU->tm_mday, tmCSU->tm_hour, tmCSU->tm_min,
+//          tmCSU->tm_sec);
+
+        // Read items inside the folder
+        struct dirent *pEntry = NULL;
+        while ((pEntry = readdir(pDir)) != NULL) {
+            if (strcmp(pEntry->d_name, ".") != 0 &&
+                    strcmp(pEntry->d_name, "..") != 0 &&
+                    strncmp(pEntry->d_name, "[", 1) == 0 &&
+                    strstr(pEntry->d_name, "tar") < 0) {
+                char yearC[5];
+                unsigned short year = 0;
+                char monthC[3];
+                unsigned short month = 0;
+
+                yearC[4] = '\0';
+                strncpy(yearC, pEntry->d_name + 1, 4);
+                monthC[2] = '\0';
+                strncpy(monthC, pEntry->d_name + 6, 2);
+
+                year = atoi(yearC);
+                month = atoi(monthC);
+
+                if (year != 0) {
+                    if (year < tmCSU->tm_year + 1900 ||
+                            (year >= tmCSU->tm_year + 1900 && month < tmCSU->tm_mon + 1)) {
+                        log_info("tar file name : %s \n", pEntry->d_name);
+                        char file[256];
+
+                        memset(file, 0x00, sizeof(file));
+                        strcat(file, "tar zcvf ");
+                        strcat(file, logPath);
+                        strncat(file, "/", 1);
+                        strcat(file, pEntry->d_name);
+                        strcat(file, ".tar");
+                        strncat(file, " ", 1);
+                        strcat(file, logPath);
+                        strncat(file, "/", 1);
+                        strcat(file, pEntry->d_name);
+                        log_info("zip = %s \n", file);
+                        system(file);
+                    }
+                }
+            }
+        }
+    }
+
+    // Close folder
+    closedir(pDir);
+}

+ 5256 - 5030
EVSE/Projects/DD360Tcci/Apps/CSU/main.c

@@ -1,5030 +1,5256 @@
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <sys/time.h>
-#include <sys/timeb.h>
-#include <sys/types.h>
-#include <sys/ioctl.h>
-#include <sys/socket.h>
-#include <sys/ipc.h>
-#include <sys/shm.h>
-#include <sys/mman.h>
-#include <linux/wireless.h>
-#include <arpa/inet.h>
-#include <netinet/in.h>
-
-#include <unistd.h>
-#include <stdarg.h>
-#include <stdio.h>      /*標準輸入輸出定義*/
-#include <stdlib.h>     /*標準函數庫定義*/
-#include <unistd.h>     /*Unix 標準函數定義*/
-#include <fcntl.h>      /*檔控制定義*/
-#include <termios.h>    /*PPSIX 終端控制定義*/
-#include <errno.h>      /*錯誤號定義*/
-#include <errno.h>
-#include <string.h>
-#include <stdint.h>
-#include <time.h>
-#include <ctype.h>
-#include <ifaddrs.h>
-#include <math.h>
-#include <stdbool.h>
-#include <dirent.h>
-#include <signal.h>
-
-#include "../Config.h"
-#include "main.h"
-#include "../common.h"
-#include "../timeout.h"
-
-#include "../Log/log.h"
-#include "../DataBase/DataBase.h"
-#include "../Define/define.h"
-#include "../ShareMemory/shmMem.h"
-#include "../SelectGun/SelectGun.h"
-
-//------------------------------------------------------------------------------
-static struct SysInfoData *pSysInfo = NULL;
-static struct SysConfigData *pSysConfig = NULL;
-static struct WARNING_CODE_INFO *pSysWarning = NULL;
-
-static struct AlarmCodeData *pAlarmCode = NULL;
-static struct FaultCodeData *pFaultCode = NULL;
-static struct InfoCodeData  *pInfoCode = NULL;
-
-static struct PsuData *ShmPsuData = NULL;
-static struct CHAdeMOData *ShmCHAdeMOData = NULL;
-static struct GBTData *ShmGBTData = NULL;
-static struct CcsData *ShmCcsData = NULL;
-static struct PrimaryMcuData *ShmPrimaryMcuData = NULL;
-static struct FanModuleData *ShmFanModuleData = NULL;
-static struct RelayModuleData *ShmRelayModuleData = NULL;
-static struct LedModuleData *ShmLedModuleData = NULL;
-static struct OCPP16Data *ShmOCPP16Data = NULL;
-static struct OCPP20Data* ShmOCPP20Data = NULL;
-static DcCommonInfo *ShmDcCommonData = NULL;
-
-static struct ChargingInfoData *pDcChargingInfo = NULL;
-static struct ChargingInfoData *pAcChargingInfo = NULL;
-
-static struct timeb startChargingTime[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
-static struct timeb endChargingTime[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
-
-static SelectGunInfo *ShmSelectGunInfo = NULL; //Jerry add
-static EvBoardErrMsg gEvBoardErr = {0};
-static ChillerTempErr gChillerTempErr = {0};
-
-struct SysConfigAndInfo         *ShmSysConfigAndInfo;
-struct StatusCodeData           *ShmStatusCodeData;
-#define DERATING_TARGET_LEVEL 5
-// for initial index to check EV board type is correct
-uint8_t bd0_1_status = 0;
-uint8_t bd0_2_status = 0;
-uint8_t bd1_1_status = 0;
-uint8_t bd1_2_status = 0;
-
-char *fwVersion = "V2.22.00.0000.00"; // Phihong version
-char* DebugVersion = "V2.22.00";      // Software debug version
-//sqlite3 *localDb;
-bool isDb_ready;
-
-//------------------------------------------------------------------------------
-void ClearDetectPluginFlag(int gunIndex);
-
-long long DiffTimebWithNow(struct timeb ST);
-uint8_t DetectBitValue(uint8_t _byte, uint8_t _bit);
-void SetBitValue(uint8_t *_byte, uint8_t _bit, uint8_t value);
-unsigned long GetTimeoutValue(struct timeval _sour_time);
-unsigned long GetClockTimeoutValue(struct timespec _start_time);
-void GetClockTime(struct timespec *_now_time, void *null);
-void gpio_set_value(unsigned int gpio, unsigned int value);
-void InformOcppErrOccur(uint8_t codeType);
-
-void RecordAlarmCode(uint8_t gunIndex, char *code);
-void ReleaseAlarmCode(uint8_t gunIndex);
-void ResetChargerAlarmCode(uint8_t gunIndex, char *code);
-void AdjustChargerCurrent(void);
-void UpdateErrorCodeToOcpp(uint8_t index);
-
-//------------------------------------------------------------------------------
-//Primary.c
-extern void ChkPrimaryStatus(void);
-
-//RFID.c
-extern void CreateRfidFork(void);
-extern void ScannerCardProcess(int gunIndex);
-extern bool RfidStopCharging(void);
-extern bool GetIsCardScan(void);
-extern void SetIsCardScan(bool value);
-
-//SelfTest.c
-extern void SelfTestRun(void);
-
-//UpgradeFW.c
-/*extern void CheckFwUpdateFunction(void);*/
-
-//Ethernet.c
-extern void InitEthernet(void);
-extern void GetMacAddress(void);
-
-//WatchDog.c
-extern void CreateWatchdog(void);
-extern void TryCloseWatchdog(void);
-extern void TryFeedWatchdog(void);
-
-//ZipFile.c
-extern void zipLogFiles(void);
-
-//------------------------------------------------------------------------------
-//--- share memory value ---
-//------------------------------------------------------------------------------
-static void changeLcmPage(uint8_t index)
-{
-    pSysInfo->SystemPage = index;
-}
-
-static uint8_t getCurLcmPage(void)
-{
-    return pSysInfo->SystemPage;
-}
-
-static void systemPageRestoreInit(void)
-{
-    int is_idle = TRUE;
-    int gunIndex;
-    for (gunIndex = 0; gunIndex < pSysConfig->TotalConnectorCount; gunIndex++) {
-        pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(gunIndex);
-        // 檢查電樁狀態是否為idle狀態
-        if ((pDcChargingInfo->SystemStatus >= S_AUTHORIZING &&
-            pDcChargingInfo->SystemStatus <= S_RESERVATION) ||
-            (pDcChargingInfo->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
-            pDcChargingInfo->SystemStatus <= S_CCS_PRECHARGE_ST0)) {
-            is_idle = FALSE;
-        }
-    }
-    if (is_idle)
-        pSysInfo->SystemPage = _PAGE_IDLE;
-    else
-        pSysInfo->SystemPage = _PAGE_SELECT_GUN;
-}
-
-//------------------------------------------------------------------------------
-void destroySelGun(uint8_t curGun)
-{
-    uint8_t i = 0;
-    uint8_t totalGun = pSysConfig->TotalConnectorCount;
-
-    //for status timeout
-    if (curGun == DESTROY_ALL_SEL) {
-        ShmSelectGunInfo->SelGunInfo.RightGun = SEL_GUN_RELEASE;
-        ShmSelectGunInfo->SelGunInfo.LeftGun = SEL_GUN_RELEASE;
-        log_info("destroy all gun = %d, %d",
-                 ShmSelectGunInfo->SelGunInfo.LeftGun,
-                 ShmSelectGunInfo->SelGunInfo.RightGun);
-        for (i = 0; i < totalGun; i++) {
-            StopGunInfoTimeoutDet(i);
-            memset(&ShmSelectGunInfo->PricesInfo[i], 0, sizeof(PricesInfo));
-        }
-        pSysInfo->CurGunSelected = 0;
-        strcpy((char *)pSysConfig->UserId, "");
-        //changeLcmPage(_LCM_VIEW);
-        return;
-    }
-
-    //for charging timeout or complete
-    if ((curGun == LEFT_GUN_NUM) && (ShmSelectGunInfo->SelGunInfo.LeftGun != SEL_GUN_RELEASE)) {
-        if (ShmSelectGunInfo->SelGunInfo.LeftGun == SEL_GUN_CONFIRM ||
-                ShmSelectGunInfo->SelGunInfo.LeftGun == SEL_GUN_ATHOR) {
-            //changeLcmPage(_PAGE_SELECT_GUN);
-        }
-        ShmSelectGunInfo->SelGunInfo.LeftGun = SEL_GUN_RELEASE;
-        StopGunInfoTimeoutDet(LEFT_GUN_NUM);
-        if (ShmOCPP16Data->SpMsg.bits.AuthorizeConf != NO) {
-            ClearAuthorizedFlag();
-        }
-
-        log_info("destroy left gun, cur page = %d", getCurLcmPage());
-        if (getCurLcmPage() == pSysInfo->SystemPage) {
-            log_info("clear left balance");
-            memset(&ShmSelectGunInfo->PricesInfo[curGun], 0, sizeof(PricesInfo));
-            ShmSelectGunInfo->PricesInfo[curGun].Balance = FAIL_BALANCE_PRICES;
-        }
-    }
-
-    if ((curGun == RIGHT_GUN_NUM) && (ShmSelectGunInfo->SelGunInfo.RightGun != SEL_GUN_RELEASE)) {
-        if (ShmSelectGunInfo->SelGunInfo.RightGun == SEL_GUN_CONFIRM ||
-                ShmSelectGunInfo->SelGunInfo.RightGun == SEL_GUN_ATHOR) {
-            //changeLcmPage(_PAGE_SELECT_GUN);
-        }
-        ShmSelectGunInfo->SelGunInfo.RightGun = SEL_GUN_RELEASE;
-        StopGunInfoTimeoutDet(RIGHT_GUN_NUM);
-        if (ShmOCPP16Data->SpMsg.bits.AuthorizeConf != NO) {
-            ClearAuthorizedFlag();
-        }
-
-        log_info("destroy right gun, cur page = %d", getCurLcmPage());
-        if (getCurLcmPage() == pSysInfo->SystemPage) {
-            log_info("clear right balance");
-            memset(&ShmSelectGunInfo->PricesInfo[curGun], 0, sizeof(PricesInfo));
-            ShmSelectGunInfo->PricesInfo[curGun].Balance = FAIL_BALANCE_PRICES;
-        }
-    }
-}
-
-static int waitRightGunPlugIt(uint8_t curGun)
-{
-
-    if ((curGun == RIGHT_GUN_NUM) && (ShmSelectGunInfo->SelGunInfo.RightGun == SEL_GUN_ATHOR)) {
-        return PASS;
-    }
-
-    return FAIL;
-}
-
-static int waitLeftGunPlugIt(uint8_t curGun)
-{
-
-    if ((curGun == LEFT_GUN_NUM) && (ShmSelectGunInfo->SelGunInfo.LeftGun == SEL_GUN_ATHOR)) {
-        return PASS;
-    }
-
-    return FAIL;
-}
-
-void setSelGunWaitToAuthor(uint8_t curSel)
-{
-    if (curSel == LEFT_GUN_NUM && ShmSelectGunInfo->SelGunInfo.LeftGun == SEL_GUN_CONFIRM) {
-        ShmSelectGunInfo->SelGunInfo.LeftGun = SEL_GUN_ATHOR;
-        //log_info("setSelGunWaitToAuthor left");
-        StopGunInfoTimeoutDet(curSel);
-    } else if (curSel == RIGHT_GUN_NUM && ShmSelectGunInfo->SelGunInfo.RightGun == SEL_GUN_CONFIRM) {
-        ShmSelectGunInfo->SelGunInfo.RightGun = SEL_GUN_ATHOR;
-        //log_info("setSelGunWaitToAuthor right");
-        StopGunInfoTimeoutDet(curSel);
-    }
-}
-
-int getConfirmSelectedGun(uint8_t curSel)
-{
-    if (((curSel == LEFT_GUN_NUM) && (ShmSelectGunInfo->SelGunInfo.LeftGun >= SEL_GUN_CONFIRM)) ||
-            ((curSel == RIGHT_GUN_NUM) && (ShmSelectGunInfo->SelGunInfo.RightGun >= SEL_GUN_CONFIRM))) {
-        return PASS;
-    }
-
-    return FAIL;
-}
-
-void confirmSelGun(uint8_t selGun)
-{
-    if (selGun == LEFT_GUN_NUM) {
-        ShmSelectGunInfo->SelGunInfo.LeftGun = SEL_GUN_CONFIRM;
-        //printf("confirmSelGun left");
-    } else if (selGun == RIGHT_GUN_NUM) {
-        ShmSelectGunInfo->SelGunInfo.RightGun = SEL_GUN_CONFIRM;
-        //printf("confirmSelGun right");
-    }
-    //changeLcmPage(_PAGE_PLUGIN);
-
-    //StartGunInfoTimeoutDet(selGun, Timeout_SelectGun);
-    //StartSystemTimeoutDet(Timeout_ReturnViewPage);
-}
-
-static void GetFirmwareVersion(void)
-{
-    // Get CSU root file system version
-    sprintf((char *)pSysInfo->CsuRootFsFwRev, fwVersion);
-    sprintf((char*)ShmDcCommonData->DebugVersion, DebugVersion);
-    uint8_t count = 0, chademo = 0, ccs = 0, gb = 0;
-    for (uint8_t idx = 0; idx < 3; idx++) {
-        if (pSysConfig->ModelName[7 + idx] == 'J') {
-            chademo++;
-            count++;
-        } else if (pSysConfig->ModelName[7 + idx] == 'G') {
-            gb++;
-            count++;
-        } else if (pSysConfig->ModelName[7 + idx] == 'U' ||
-                   pSysConfig->ModelName[7 + idx] == 'V' ||
-                   pSysConfig->ModelName[7 + idx] == 'E') {
-            ccs++;
-            count++;
-        }
-    }
-
-    if (count == 1) {
-        if (chademo > 0) {
-            pSysInfo->CsuRootFsFwRev[7] = '1';
-        } else if (ccs > 0) {
-            pSysInfo->CsuRootFsFwRev[7] = '2';
-        } else if (gb > 0) {
-            pSysInfo->CsuRootFsFwRev[7] = '3';
-        }
-    } else {
-        if (chademo > 0 && ccs > 0) {
-            pSysInfo->CsuRootFsFwRev[7] = '4';
-        } else if (chademo > 0 && gb > 0) {
-            pSysInfo->CsuRootFsFwRev[7] = '5';
-        } else if (ccs > 0 && gb > 0) {
-            pSysInfo->CsuRootFsFwRev[7] = '6';
-        }
-    }
-
-    // Get network option from model name
-    switch (pSysConfig->ModelName[10]) {
-    case 'B':
-    case 'U':
-        //Blue tooth
-        pSysInfo->CsuRootFsFwRev[9] = '3';
-        break;
-    case 'W':
-        // WIFI
-        pSysInfo->CsuRootFsFwRev[9] = '1';
-        break;
-    case 'T':
-        // 3G/4G
-        pSysInfo->CsuRootFsFwRev[9] = '2';
-        break;
-    case 'D': //DS60-120 add
-        pSysInfo->CsuRootFsFwRev[9] = '5';
-        break;
-    default:
-        // LAN
-        pSysInfo->CsuRootFsFwRev[9] = '0';
-        break;
-    }
-    // Get rating power from model name
-    memcpy(&pSysInfo->CsuRootFsFwRev[10], &pSysConfig->ModelName[4], 0x03);
-
-    // Get IEC or UL
-    char _buf[3] = {0};
-    memcpy(_buf, &pSysConfig->ModelName[2], 2);
-
-    if (strcmp(_buf, "YE") == EQUAL || strcmp(_buf, "YC") == EQUAL) {
-        pSysInfo->ChargerType = _CHARGER_TYPE_IEC;
-        log_info("IEC model");
-    } else if (strcmp(_buf, "WU") == EQUAL) {
-        pSysInfo->ChargerType = _CHARGER_TYPE_UL;
-        log_info("UL model");
-    }
-}
-
-static void checkGunOTPState(uint8_t gunIndex)
-{
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-
-    //水冷機溫度檢測
-    if (((ShmDcCommonData->ChillerValve.MultiChillerGun & 0x80) >> 7) == YES) {
-        if (pDcChargingInfo->ChillerTemp != UNDEFINED_TEMP) {
-            if (pDcChargingInfo->ChillerTemp >= GUN_OTP_VALUE) {
-                if (((gunIndex == 0) &&
-                        ((strncmp((char *)&pSysConfig->ModelName[7], "V", 1) == 0) ||
-                         (strncmp((char *)&pSysConfig->ModelName[7], "F", 1) == 0)))
-                         ||
-                    ((gunIndex == 1) &&
-                        ((strncmp((char *)&pSysConfig->ModelName[9], "V", 1) == 0) ||
-                         (strncmp((char *)&pSysConfig->ModelName[9], "F", 1) == 0)))
-                   ) {
-                    RecordAlarmCode(gunIndex, "012323");
-                    ShmDcCommonData->ChillerTempErr[gunIndex].StatusBit.ChillerOTP = YES;
-                }
-                else
-                {
-                    ShmDcCommonData->ChillerTempErr[gunIndex].StatusBit.ChillerOTP = NO;
-                }
-            } else if (pDcChargingInfo->ChillerTemp != 0 &&
-                       pDcChargingInfo->ChillerTemp < GUN_OTP_RECOVERY) {
-                //ResetChargerAlarmCode(gunIndex, "012323");
-                ShmDcCommonData->ChillerTempErr[gunIndex].StatusBit.ChillerOTP = NO;
-            }
-            ShmDcCommonData->ChillerTempErr[gunIndex].StatusBit.ChillerTempSensorFail = NO;
-        } else {
-            // 沒接上 Sensor or 異常
-            //RecordAlarmCode(gunIndex, "011038");
-            //ResetChargerAlarmCode(gunIndex, "012323");
-            ShmDcCommonData->ChillerTempErr[gunIndex].StatusBit.ChillerOTP = NO;
-            if (((gunIndex == 0) &&
-                    ((strncmp((char *)&pSysConfig->ModelName[7], "V", 1) == 0) ||
-                     (strncmp((char *)&pSysConfig->ModelName[7], "F", 1) == 0)))
-                     ||
-                ((gunIndex == 1) &&
-                    ((strncmp((char *)&pSysConfig->ModelName[9], "V", 1) == 0) ||
-                     (strncmp((char *)&pSysConfig->ModelName[9], "F", 1) == 0)))
-               ) {
-                ShmDcCommonData->ChillerTempErr[gunIndex].StatusBit.ChillerTempSensorFail = YES;
-            }
-            else
-            {
-                ShmDcCommonData->ChillerTempErr[gunIndex].StatusBit.ChillerTempSensorFail = NO;
-            }
-        }
-
-        if(pFaultCode->FaultEvents.bits.CcsLiquidChillerWaterLevelFault == YES)
-        {
-            RecordAlarmCode(gunIndex, "011037");
-        }
-    }
-
-    switch (pDcChargingInfo->Type) {
-    case _Type_Chademo:
-        if (pDcChargingInfo->ConnectorTemp != UNDEFINED_TEMP) {
-            if (pDcChargingInfo->ConnectorTemp >= GUN_OTP_VALUE) {
-                RecordAlarmCode(gunIndex, "012229");
-                ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaConnectOTP = YES;
-            } else if (pDcChargingInfo->ConnectorTemp != 0 &&
-                       pDcChargingInfo->ConnectorTemp < GUN_OTP_RECOVERY) {
-                //ResetChargerAlarmCode(gunIndex, "012229");
-                ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaConnectOTP = NO;
-            }
-            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaConnectTempSensorFail = NO;
-        } else {
-            // 沒接上 Sensor or 異常
-            //RecordAlarmCode(gunIndex, "011018");
-            //ResetChargerAlarmCode(gunIndex, "012229");
-            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaConnectOTP = NO;
-            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaConnectTempSensorFail = YES;
-            if  ((gunIndex == 0) &&
-                    (strncmp((char *)&pSysConfig->ModelName[7], "J", 1) == 0)) {
-            	ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaConnectOTP = NO;
-            	ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaConnectTempSensorFail = NO;
-            } else if ((gunIndex == 1) &&
-                    ((strncmp((char *)&pSysConfig->ModelName[9], "J", 1) == 0) )) {
-            	ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaConnectOTP = NO;
-            	ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaConnectTempSensorFail = NO;
-            }
-        }
-        break;
-
-    case _Type_CCS_2:
-        // CCS 不管甚麼輸出都會有槍溫偵測!!~
-        if (pDcChargingInfo->ConnectorTemp != UNDEFINED_TEMP) {
-            //ResetChargerAlarmCode(gunIndex, "011019");
-
-            if (pDcChargingInfo->ConnectorTemp >= GUN_OTP_VALUE) {
-                RecordAlarmCode(gunIndex, "012230");
-                ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSConnectOTP = YES;
-            } else if (pDcChargingInfo->ConnectorTemp != 0 &&
-                       pDcChargingInfo->ConnectorTemp < GUN_OTP_RECOVERY) {
-                //ResetChargerAlarmCode(gunIndex, "012230");
-                ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSConnectOTP = NO;
-            }
-            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSConnectTempSensorFail = NO;
-            //ResetChargerAlarmCode(gunIndex, "011019");
-        } else {
-            // 沒接上 Sensor or 異常
-            //RecordAlarmCode(gunIndex, "011019");
-            //ResetChargerAlarmCode(gunIndex, "012230");
-            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSConnectOTP = NO;
-            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSConnectTempSensorFail = YES;
-        }
-        break;
-
-    case _Type_GB:
-        if (pDcChargingInfo->ConnectorTemp != UNDEFINED_TEMP) {
-            if (pDcChargingInfo->ConnectorTemp >= GUN_OTP_VALUE) {
-                RecordAlarmCode(gunIndex, "012231");
-                ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTConnectOTP = YES;
-            } else if (pDcChargingInfo->ConnectorTemp != 0 &&
-                       pDcChargingInfo->ConnectorTemp < GUN_OTP_RECOVERY) {
-                //ResetChargerAlarmCode(gunIndex, "012231");
-                ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTConnectOTP = NO;
-            }
-            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTConnectTempSensorFail = NO;
-        } else {
-            // 沒接上 Sensor or 異常
-            //RecordAlarmCode(gunIndex, "011020");
-            //ResetChargerAlarmCode(gunIndex, "012231");
-            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTConnectOTP = NO;
-            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTConnectTempSensorFail = YES;
-        }
-        break;
-    }
-}
-
-static void collectError(uint8_t gunIndex)
-{
-    gEvBoardErr.GunErrMessage |= ShmDcCommonData->ConnectErrList[gunIndex].GunErrMessage;
-    gChillerTempErr.TempErrMsg |= ShmDcCommonData->ChillerTempErr[gunIndex].TempErrMsg;
-}
-
-static void checkGBTAlarmState(uint8_t gunType)
-{
-    // GFD Trip
-    if (DetectBitValue(gEvBoardErr.GunErrMessage >> (8 * gunType), 0)) {
-        pAlarmCode->AlarmEvents.bits.GbGfdTrip = YES;
-    } else {
-        pAlarmCode->AlarmEvents.bits.GbGfdTrip = NO;
-    }
-
-    // UVP
-    if (DetectBitValue(gEvBoardErr.GunErrMessage >> (8 * gunType), 1)) {
-        pAlarmCode->AlarmEvents.bits.GbtOutputUVPFail = YES;
-    } else {
-        pAlarmCode->AlarmEvents.bits.GbtOutputUVPFail = NO;
-    }
-
-    // OTP
-    if (DetectBitValue(gEvBoardErr.GunErrMessage >> (8 * gunType), 2)) {
-        pAlarmCode->AlarmEvents.bits.GbConnectorOTP = YES;
-    } else {
-        pAlarmCode->AlarmEvents.bits.GbConnectorOTP = NO;
-    }
-
-    // OVP
-    if (DetectBitValue(gEvBoardErr.GunErrMessage >> (8 * gunType), 3)) {
-        pAlarmCode->AlarmEvents.bits.SystemGbOutputOVP = YES;
-    } else {
-        pAlarmCode->AlarmEvents.bits.SystemGbOutputOVP = NO;
-    }
-
-    // GFD Warning
-    if (DetectBitValue(gEvBoardErr.GunErrMessage >> (8 * gunType), 4)) {
-        pAlarmCode->AlarmEvents.bits.GbGroundfaultWarning = YES;
-    } else {
-        pAlarmCode->AlarmEvents.bits.GbGroundfaultWarning = NO;
-    }
-
-    // Relay Welding
-    if (DetectBitValue(gEvBoardErr.GunErrMessage >> (8 * gunType), 5)) {
-        pFaultCode->FaultEvents.bits.GbOutputRelayWelding = YES;
-    } else {
-        pFaultCode->FaultEvents.bits.GbOutputRelayWelding = NO;
-    }
-
-    // Relay Driving
-    if (DetectBitValue(gEvBoardErr.GunErrMessage >> (8 * gunType), 6)) {
-        pFaultCode->FaultEvents.bits.GbOutputRelayDrivingFault = YES;
-    } else {
-        pFaultCode->FaultEvents.bits.GbOutputRelayDrivingFault = NO;
-    }
-
-    // Connect temp Sensor broken
-    if (DetectBitValue(gEvBoardErr.GunErrMessage >> (8 * gunType), 7)) {
-        pFaultCode->FaultEvents.bits.GbConnectorTempSensorBroken = YES;
-    } else {
-        pFaultCode->FaultEvents.bits.GbConnectorTempSensorBroken = NO;
-    }
-}
-
-static void checkCCSAlarmState(uint8_t gunType)
-{
-    // GFD Trip
-    if (DetectBitValue(gEvBoardErr.GunErrMessage >> (8 * gunType), 0)) {
-        pAlarmCode->AlarmEvents.bits.CcsGfdTrip = YES;
-    } else {
-        pAlarmCode->AlarmEvents.bits.CcsGfdTrip = NO;
-    }
-
-    // UVP
-    if (DetectBitValue(gEvBoardErr.GunErrMessage >> (8 * gunType), 1)) {
-        pAlarmCode->AlarmEvents.bits.CcsOutputUVPFail = YES;
-    } else {
-        pAlarmCode->AlarmEvents.bits.CcsOutputUVPFail = NO;
-    }
-
-    // OTP
-    if (DetectBitValue(gEvBoardErr.GunErrMessage >> (8 * gunType), 2)) {
-        pAlarmCode->AlarmEvents.bits.CcsConnectorOTP = YES;
-    } else {
-        pAlarmCode->AlarmEvents.bits.CcsConnectorOTP = NO;
-    }
-
-    // OVP
-    if (DetectBitValue(gEvBoardErr.GunErrMessage >> (8 * gunType), 3)) {
-        pAlarmCode->AlarmEvents.bits.SystemCcsOutputOVP = YES;
-    } else {
-        pAlarmCode->AlarmEvents.bits.SystemCcsOutputOVP = NO;
-    }
-
-    // GFD Warning
-    if (DetectBitValue(gEvBoardErr.GunErrMessage >> (8 * gunType), 4)) {
-        pAlarmCode->AlarmEvents.bits.CcsGroundfaultWarning = YES;
-    } else {
-        pAlarmCode->AlarmEvents.bits.CcsGroundfaultWarning = NO;
-    }
-
-    // Relay Welding
-    if (DetectBitValue(gEvBoardErr.GunErrMessage >> (8 * gunType), 5)) {
-        pFaultCode->FaultEvents.bits.CcsOutputRelayWelding = YES;
-    } else {
-        pFaultCode->FaultEvents.bits.CcsOutputRelayWelding = NO;
-    }
-
-    // Relay Driving
-    if (DetectBitValue(gEvBoardErr.GunErrMessage >> (8 * gunType), 6)) {
-        pFaultCode->FaultEvents.bits.CcsOutputRelayDrivingFault = YES;
-    } else {
-        pFaultCode->FaultEvents.bits.CcsOutputRelayDrivingFault = NO;
-    }
-
-    // Connect temp Sensor broken
-    if (DetectBitValue(gEvBoardErr.GunErrMessage >> (8 * gunType), 7)) {
-        pFaultCode->FaultEvents.bits.CcsConnectorTempSensorBroken = YES;
-    } else {
-        pFaultCode->FaultEvents.bits.CcsConnectorTempSensorBroken = NO;
-    }
-}
-
-static void checkChaDeMoAlarmState(uint8_t gunType)
-{
-    // GFD Trip
-    if (DetectBitValue(gEvBoardErr.GunErrMessage >> (8 * gunType), 0)) {
-        pAlarmCode->AlarmEvents.bits.ChademoGfdTrip = YES;
-    } else {
-        pAlarmCode->AlarmEvents.bits.ChademoGfdTrip = NO;
-    }
-
-    // UVP
-    if (DetectBitValue(gEvBoardErr.GunErrMessage >> (8 * gunType), 1)) {
-        pAlarmCode->AlarmEvents.bits.ChademoOutputUVPFail = YES;
-    } else {
-        pAlarmCode->AlarmEvents.bits.ChademoOutputUVPFail = NO;
-    }
-
-    // OTP
-    if (DetectBitValue(gEvBoardErr.GunErrMessage >> (8 * gunType), 2)) {
-        pAlarmCode->AlarmEvents.bits.ChademoConnectorOTP = YES;
-    } else {
-        pAlarmCode->AlarmEvents.bits.ChademoConnectorOTP = NO;
-    }
-
-    // OVP
-    if (DetectBitValue(gEvBoardErr.GunErrMessage >> (8 * gunType), 3)) {
-        pAlarmCode->AlarmEvents.bits.SystemChademoOutputOVP = YES;
-    } else {
-        pAlarmCode->AlarmEvents.bits.SystemChademoOutputOVP = NO;
-    }
-
-    // GFD Warning
-    if (DetectBitValue(gEvBoardErr.GunErrMessage >> (8 * gunType), 4)) {
-        pAlarmCode->AlarmEvents.bits.ChademoGroundWarning = YES;
-    } else {
-        pAlarmCode->AlarmEvents.bits.ChademoGroundWarning = NO;
-    }
-
-    // Relay Welding
-    if (DetectBitValue(gEvBoardErr.GunErrMessage >> (8 * gunType), 5)) {
-        pFaultCode->FaultEvents.bits.ChademoOutputRelayWelding = YES;
-    } else {
-        pFaultCode->FaultEvents.bits.ChademoOutputRelayWelding = NO;
-    }
-
-    // Relay Driving
-    if (DetectBitValue(gEvBoardErr.GunErrMessage >> (8 * gunType), 6)) {
-        pFaultCode->FaultEvents.bits.ChademoOutputRelayDrivingFault = YES;
-    } else {
-        pFaultCode->FaultEvents.bits.ChademoOutputRelayDrivingFault = NO;
-    }
-
-    // Connect temp Sensor broken
-    if (DetectBitValue(gEvBoardErr.GunErrMessage >> (8 * gunType), 7)) {
-        pFaultCode->FaultEvents.bits.ChademoConnectorTempSensorBroken = YES;
-    } else {
-        pFaultCode->FaultEvents.bits.ChademoConnectorTempSensorBroken = NO;
-    }
-}
-
-static void checkChillerAlarmState(void)
-{
-    if (DetectBitValue(gChillerTempErr.TempErrMsg, 0)) {
-        pAlarmCode->AlarmEvents.bits.SystemChillerOTP = YES;
-    } else {
-        pAlarmCode->AlarmEvents.bits.SystemChillerOTP = NO;
-    }
-
-    if (DetectBitValue(gChillerTempErr.TempErrMsg, 1)) {
-        pFaultCode->FaultEvents.bits.ChillerTempSensorBroken = YES;
-    } else {
-        pFaultCode->FaultEvents.bits.ChillerTempSensorBroken = NO;
-    }
-}
-
-static void checkEvBoardAlarmState(uint8_t gunType)
-{
-    switch (gunType) {
-    case _Type_Chademo:
-        checkChaDeMoAlarmState(gunType);
-        break;
-
-    case _Type_CCS_2:
-        checkCCSAlarmState(gunType);
-        break;
-
-    case _Type_GB:
-        checkGBTAlarmState(gunType);
-        break;
-    }
-}
-
-unsigned long GetTimeoutValue(struct timeval _sour_time)
-{
-    struct timeval _end_time;
-    gettimeofday(&_end_time, NULL);
-
-    return 1000000 * (_end_time.tv_sec - _sour_time.tv_sec) + _end_time.tv_usec - _sour_time.tv_usec;
-}
-
-void GetClockTime(struct timespec *_now_time, void *null)
-{
-    clock_gettime(CLOCK_MONOTONIC, _now_time);
-}
-
-// return value unit: 1us
-unsigned long GetClockTimeoutValue(struct timespec _start_time)
-{
-    struct timespec ts_end;
-    unsigned long ret = 0;
-
-    clock_gettime(CLOCK_MONOTONIC, &ts_end);
-
-    ret = ((unsigned long)(ts_end.tv_sec - _start_time.tv_sec) * 1000000) + ((unsigned long)((ts_end.tv_nsec / 1000) - (_start_time.tv_nsec/ 1000)));
-
-    return ret;
-}
-
-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;
-    return (StopTime - StartTime);
-}
-
-bool CheckTimeOut(struct timeb ST)
-{
-    struct timeb ET;
-    unsigned int StartTime, StopTime;
-
-    ftime(&ET);
-    StartTime = (unsigned int) ST.time;
-    StopTime = (unsigned int) ET.time;
-    return (StopTime > StartTime) ? YES : NO;
-}
-
-void setChargerMode(uint8_t gunIndex, uint8_t mode)
-{
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-
-    pDcChargingInfo->SystemStatus = mode;
-
-}
-
-long long DiffTimebWithNow(struct timeb ST)
-{
-    //return milli-second
-    struct timeb ET;
-    long long StartTime, StopTime;
-
-    ftime(&ET);
-    StartTime = (long long)ST.time;
-    StopTime = (long long)ET.time;
-
-    return ((StopTime - StartTime) * 1000) + (ET.millitm - ST.millitm);
-}
-
-//==========================================
-// Log
-//==========================================
-void CheckFwSlotStatusLog(void)
-{
-    if (bd0_1_status == 0 && bd0_2_status == 1) {
-        log_info("Connector 1 : Chademo");
-    } else if (bd0_1_status == 1 && bd0_2_status == 0) {
-        log_info("Connector 1 : CCS");
-    } else if (bd0_1_status == 1 && bd0_2_status == 1) {
-        log_info("Connector 1 : GB");
-    }
-
-    if (bd1_1_status == 0 && bd1_2_status == 1) {
-        log_info("Connector 2 : Chademo");
-    } else if (bd1_1_status == 1 && bd1_2_status == 0) {
-        log_info("Connector 2 : CCS");
-    } else if (bd1_1_status == 1 && bd1_2_status == 1) {
-        log_info("Connector 2 : GB");
-    }
-}
-
-void CheckHwSlotStatusLog(uint8_t index)
-{
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);
-
-    if (pDcChargingInfo->Type == _Type_Chademo) {
-        log_info("Hw check : Connector %d, Type : Chademo, Evboard_id = %d ",
-                 index, pDcChargingInfo->Evboard_id);
-    } else if (pDcChargingInfo->Type == _Type_CCS_2) {
-        log_info("Hw check : Connector %d, Type : CCS, Evboard_id = %d ",
-                 index, pDcChargingInfo->Evboard_id);
-    } else if (pDcChargingInfo->Type == _Type_GB) {
-        log_info("Hw check : Connector %d, Type : GB, Evboard_id = %d ",
-                 index, pDcChargingInfo->Evboard_id);
-    }
-}
-
-//=================================
-// LCM Page
-//=================================
-void ChangeLcmByIndex(uint8_t page_index)
-{
-    if (pSysWarning->Level != WARN_LV_ER
-       ) {
-        pSysInfo->PageIndex = page_index;
-        //log_info("LCM index:%d",pSysInfo->PageIndex);
-    }
-}
-
-//======================================================
-// Peripheral initial
-//======================================================
-void InitGPIO()
-{
-    /*****************0~3, 4 bank, bank x 32+ num*********************/
-    /***************************************************************/
-    /*************** GPIO 0 ***************************************/
-    /***************************************************************/
-    /* GPMC_AD8         =>  GPIO0_22 *//*ID BD1_1*/
-    system("echo 22 > /sys/class/gpio/export");
-    system("echo \"in\" > /sys/class/gpio/gpio22/direction");
-    /* GPMC_AD9         =>  GPIO0_23 *//*ID BD1_2*/
-    system("echo 23 > /sys/class/gpio/export");
-    system("echo \"in\" > /sys/class/gpio/gpio23/direction");
-    /* GPMC_AD10        =>  GPIO0_26 *//*IO BD1_1*/
-    system("echo 26 > /sys/class/gpio/export");
-    system("echo \"out\" > /sys/class/gpio/gpio26/direction");
-    system("echo 1 > /sys/class/gpio/gpio26/value");
-    /* GPMC_AD11        =>  GPIO0_27 *//*IO BD1_2*/
-    system("echo 27 > /sys/class/gpio/export");
-    system("echo \"in\" > /sys/class/gpio/gpio27/direction");
-    /* RMII1_REF_CLK        =>  GPIO0_29 *//*USB 0 OCP detection*/
-    system("echo 29 > /sys/class/gpio/export");
-    system("echo \"in\" > /sys/class/gpio/gpio29/direction");
-    /*XDMA_EVENT_INTR0  =>  GPIO0_19 *//*AM_RFID_RST*/
-    system("echo 19 > /sys/class/gpio/export");
-    system("echo \"out\" > /sys/class/gpio/gpio19/direction");
-    system("echo 1 > /sys/class/gpio/gpio19/value");
-    /*XDMA_EVENT_INTR1  =>  GPIO0_20 *//*AM_RFID_ICC*/
-    system("echo 20 > /sys/class/gpio/export");
-    system("echo \"in\" > /sys/class/gpio/gpio20/direction");
-    /***************************************************************/
-    /*************** GPIO 1 ***************************************/
-    /***************************************************************/
-    /* GPMC_AD12    =>  GPIO1_12 *//*ID BD2_1*/
-    system("echo 44 > /sys/class/gpio/export");
-    system("echo \"in\" > /sys/class/gpio/gpio44/direction");
-    /* GPMC_AD13    =>  GPIO1_13 *//*ID BD2_2*/
-    system("echo 45 > /sys/class/gpio/export");
-    system("echo \"in\" > /sys/class/gpio/gpio45/direction");
-    /* GPMC_AD14    =>  GPIO1_14 *//*IO BD2_1*/
-    system("echo 46 > /sys/class/gpio/export");
-    system("echo \"out\" > /sys/class/gpio/gpio46/direction");
-    system("echo 0 > /sys/class/gpio/gpio46/value");
-    /* GPMC_AD15    =>  GPIO1_15 *//*IO BD2_2*/
-    system("echo 47 > /sys/class/gpio/export");
-    system("echo \"in\" > /sys/class/gpio/gpio47/direction");
-    /***************************************************************/
-    /*************** GPIO 2 ***************************************/
-    /***************************************************************/
-    /*LCD_AC_BIAS_EN    =>  GPIO2_25*//*RS-485 for module DE control*/
-    system("echo 89 > /sys/class/gpio/export");
-    system("echo \"out\" > /sys/class/gpio/gpio89/direction");
-    system("echo 1 > /sys/class/gpio/gpio89/value");
-    /*LCD_HSYNC     =>  GPIO2_23*//*RS-485 for module RE control*/
-    system("echo 87 > /sys/class/gpio/export");
-    system("echo \"out\" > /sys/class/gpio/gpio87/direction");
-    system("echo 0 > /sys/class/gpio/gpio87/value");
-    /*LCD_PCLK      =>  GPIO2_24*//*CCS communication board 1 proximity*/
-    system("echo 88 > /sys/class/gpio/export");
-    system("echo \"in\" > /sys/class/gpio/gpio88/direction");
-    /*LCD_VSYNC     =>  GPIO2_22*//*CCS communication board 2 proximity*/
-    system("echo 86 > /sys/class/gpio/export");
-    system("echo \"in\" > /sys/class/gpio/gpio86/direction");
-    /***************************************************************/
-    /*************** GPIO 3 ***************************************/
-    /***************************************************************/
-    /*MCASP0_FSX        =>  GPIO3_15*//*Emergency Stop button detect*/
-    system("echo 111 > /sys/class/gpio/export");
-    system("echo \"in\" > /sys/class/gpio/gpio111/direction");
-    /*MCASP0_ACLKR  =>  GPIO3_18*//*USB1 OCP detect*/
-    system("echo 114 > /sys/class/gpio/export");
-    system("echo \"in\" > /sys/class/gpio/gpio114/direction");
-    /*MCASP0_AHCLKR =>  GPIO3_17*//*Emergency IO for AM3352 and STM32F407*/
-    system("echo 113 > /sys/class/gpio/export");
-    system("echo \"in\" > /sys/class/gpio/gpio113/direction");
-    /*MCASP0_ACLKX  =>  GPIO3_14*//*Ethernet PHY reset*/
-    system("echo 110 > /sys/class/gpio/export");
-    system("echo \"out\" > /sys/class/gpio/gpio110/direction");
-    system("echo 0 > /sys/class/gpio/gpio110/value");
-    /* MCASP0_FSR       =>  GPIO3_19 *//*SMR Enable control_1 for Pskill_1*/
-    system("echo 115 > /sys/class/gpio/export");
-    system("echo \"out\" > /sys/class/gpio/gpio115/direction");
-    system("echo 0 > /sys/class/gpio/gpio115/value");
-    /* MCASP0_AXR0  =>  GPIO3_16 *//*CSU board function OK indicator.*/
-    system("echo 112 > /sys/class/gpio/export");
-    system("echo \"out\" > /sys/class/gpio/gpio112/direction");
-    system("echo 1 > /sys/class/gpio/gpio112/value");
-    /* MCASP0_AXR1  =>  GPIO3_20 *//*SMR Enable control_2 for Pskill_2*/
-    system("echo 116 > /sys/class/gpio/export");
-    system("echo \"out\" > /sys/class/gpio/gpio116/direction");
-    system("echo 0 > /sys/class/gpio/gpio116/value");
-
-    log_info("Initial GPIO OK");
-
-    return ;
-
-}
-
-int LoadSysConfigAndInfo()
-{
-    int fd, wrd;
-    unsigned char *buf;
-    unsigned int ChkSum, ChkSumOrg;
-
-    if ((buf = malloc(MtdBlockSize)) == NULL) {
-
-        log_error("malloc buffer NG,rebooting..");
-
-        if (pAlarmCode != NULL) {
-            pAlarmCode->AlarmEvents.bits.CsuInitFailed = 1;
-        }
-        sleep(5);
-        system("reboot -f");
-        sleep(5);
-        system("reboot -f");
-    }
-    memset(buf, 0, MtdBlockSize);
-
-    //================================================
-    // Load configuration from mtdblock10
-    //================================================
-    system("nanddump /dev/mtd10 -f /mnt/EvseConfig.bin");
-    fd = open("/mnt/EvseConfig.bin", O_RDWR);
-    if (fd < 0) {
-        free(buf);
-
-        log_error("open mtdblock10 NG,rebooting..");
-
-        if (pAlarmCode != NULL) {
-            pAlarmCode->AlarmEvents.bits.CsuInitFailed = 1;
-        }
-        sleep(5);
-        system("reboot -f");
-        sleep(5);
-        system("reboot -f");
-    }
-    wrd = read(fd, buf, MtdBlockSize);
-    close(fd);
-    if (wrd < MtdBlockSize) {
-        free(buf);
-
-        log_error("read SysConfigData data NG,rebooting..");
-
-        if (pAlarmCode != NULL) {
-            pAlarmCode->AlarmEvents.bits.CsuInitFailed = 1;
-        }
-        sleep(5);
-        system("reboot -f");
-        sleep(5);
-        system("reboot -f");
-    }
-
-    ChkSum = 0;
-    for (wrd = ARRAY_SIZE(pSysConfig->CsuBootLoadFwRev); wrd < MtdBlockSize - 4; wrd++) {
-        ChkSum += buf[wrd];
-    }
-    memcpy(&ChkSumOrg, buf + (MtdBlockSize - 4), sizeof(ChkSumOrg));
-    memcpy(&pSysConfig->ModelName, buf + (ARRAY_SIZE(pSysConfig->CsuBootLoadFwRev)), ARRAY_SIZE(pSysConfig->ModelName));
-    memcpy(&pSysConfig->SerialNumber, buf + (ARRAY_SIZE(pSysConfig->CsuBootLoadFwRev) + ARRAY_SIZE(pSysConfig->ModelName) + ARRAY_SIZE(pSysConfig->AcModelName)), ARRAY_SIZE(pSysConfig->SerialNumber));
-
-    //================================================
-    // Load configuration from mtdblock11
-    //================================================
-    if (ChkSum != ChkSumOrg) {
-        log_error("Primary SysConfigData checksum NG, read backup");
-        system("nanddump /dev/mtd11 -f /mnt/EvseConfig.bin");
-        fd = open("/mnt/EvseConfig.bin", O_RDWR);
-        if (fd < 0) {
-            free(buf);
-
-            log_error("open mtdblock11 (backup) NG,rebooting..");
-
-            if (pAlarmCode != NULL) {
-                pAlarmCode->AlarmEvents.bits.CsuInitFailed = 1;
-            }
-            sleep(5);
-            system("reboot -f");
-            sleep(5);
-            system("reboot -f");
-        }
-        memset(buf, 0, MtdBlockSize);
-        wrd = read(fd, buf, MtdBlockSize);
-        close(fd);
-        if (wrd < MtdBlockSize) {
-            free(buf);
-
-            log_error("read backup SysConfigData data NG,rebooting..");
-
-            if (pAlarmCode != NULL) {
-                pAlarmCode->AlarmEvents.bits.CsuInitFailed = 1;
-            }
-            sleep(5);
-            system("reboot -f");
-            sleep(5);
-            system("reboot -f");
-        }
-
-        ChkSum = 0;
-        for (wrd = ARRAY_SIZE(pSysConfig->CsuBootLoadFwRev); wrd < MtdBlockSize - 4; wrd++) {
-            ChkSum += buf[wrd];
-        }
-        memcpy(&ChkSumOrg, buf + (MtdBlockSize - 4), sizeof(ChkSumOrg));
-
-        //================================================
-        // Load configuration from mtdblock12 (Factory default)
-        //================================================
-        if (ChkSum != ChkSumOrg) {
-            log_warn("backup SysConfigData checksum NG, read Factory default");
-            system("nanddump /dev/mtd12 -f /mnt/EvseConfig.bin");
-            fd = open("/mnt/EvseConfig.bin", O_RDWR);
-            if (fd < 0) {
-                log_error("open mtdblock12 (Factory default) NG,rebooting..");
-
-                free(buf);
-                if (pAlarmCode != NULL) {
-                    pAlarmCode->AlarmEvents.bits.CsuInitFailed = 1;
-                }
-                sleep(5);
-                system("reboot -f");
-                sleep(5);
-                system("reboot -f");
-            }
-            memset(buf, 0, MtdBlockSize);
-            wrd = read(fd, buf, MtdBlockSize);
-            close(fd);
-            if (wrd < MtdBlockSize) {
-                log_error("read factory default  SysConfigData data NG,rebooting..");
-
-                free(buf);
-                if (pAlarmCode != NULL) {
-                    pAlarmCode->AlarmEvents.bits.CsuInitFailed = 1;
-                }
-                sleep(5);
-                system("reboot -f");
-                sleep(5);
-                system("reboot -f");
-            }
-
-            ChkSum = 0;
-            for (wrd = ARRAY_SIZE(pSysConfig->CsuBootLoadFwRev); wrd < MtdBlockSize - 4; wrd++) {
-                ChkSum += buf[wrd];
-            }
-            memcpy(&ChkSumOrg, buf + (MtdBlockSize - 4), sizeof(ChkSumOrg));
-            memcpy(buf + (ARRAY_SIZE(pSysConfig->CsuBootLoadFwRev)), &pSysConfig->ModelName, ARRAY_SIZE(pSysConfig->ModelName));
-            memcpy(buf + (ARRAY_SIZE(pSysConfig->CsuBootLoadFwRev) + ARRAY_SIZE(pSysConfig->ModelName) + ARRAY_SIZE(pSysConfig->AcModelName)), &pSysConfig->SerialNumber, ARRAY_SIZE(pSysConfig->SerialNumber));
-
-            if (ChkSum != ChkSumOrg) {
-                log_warn("factory default  SysConfigData checksum NG, restore factory default");
-                free(buf);
-                system("cd /root;./FactoryConfig -m");
-                system("rm -f /Storage/OCPP/OCPPConfiguration");
-                system("sync");
-                sleep(5);
-                system("reboot -f");
-                sleep(5);
-                system("reboot -f");
-
-                return FAIL;
-            }
-        }
-    }
-
-    //load OK
-    memcpy(pSysConfig, buf, sizeof(struct SysConfigData));
-    free(buf);
-
-    system("rm -f /mnt/EvseConfig.bin");
-
-    // SysConfig in flash is empty (0xffffffff)
-    if ((strlen((char *)pSysConfig->ModelName) > ARRAY_SIZE(pSysConfig->ModelName)) ||
-            (strlen((char *)pSysConfig->SerialNumber) > ARRAY_SIZE(pSysConfig->SerialNumber)) ||
-            (strlen((char *)pSysConfig->SystemId) > ARRAY_SIZE(pSysConfig->SystemId)) ||
-            (pSysConfig->Eth0Interface.EthDhcpClient == 0xff)) {
-        if (strlen((char *)pSysConfig->ModelName) > ARRAY_SIZE(pSysConfig->ModelName)) {
-            memset(pSysConfig->ModelName, 0x00, ARRAY_SIZE(pSysConfig->ModelName));
-        }
-
-        if (strlen((char *)pSysConfig->SerialNumber) > ARRAY_SIZE(pSysConfig->SerialNumber)) {
-            memset(pSysConfig->SerialNumber, 0x00, ARRAY_SIZE(pSysConfig->SerialNumber));
-        }
-
-        if (strlen((char *)pSysConfig->SystemId) > ARRAY_SIZE(pSysConfig->SystemId)) {
-            memset(pSysConfig->SystemId, 0x00, ARRAY_SIZE(pSysConfig->SystemId));
-        }
-
-        if (pSysConfig->Eth0Interface.EthDhcpClient == 0xff) {
-            log_info("Ethernet dhcp config is null.");
-        }
-
-        if (strlen((char *)pSysConfig->ModelName) == 0x00) {
-            log_info("Model name over length.");
-        }
-
-        if (strlen((char *)pSysConfig->SerialNumber) == 0x00) {
-            log_info("Model serial number over length.");
-        }
-
-        if (strlen((char *)pSysConfig->SystemId) == 0x00) {
-            log_info("SystemId over length.");
-        }
-
-        system("cd /root;./FactoryConfig -m");
-        sleep(3);
-        system("/usr/bin/run_evse_restart.sh");
-    }
-    log_info("Load SysConfigData OK");
-
-
-    return PASS;
-}
-
-int Initialization(void)
-{
-    uint8_t count = 0;
-    uint8_t pinOut[2] = {116, 115};
-
-    // 初始化卡號驗證的 Flag
-    ClearAuthorizedFlag();
-
-    for (count = 0; count < pSysConfig->TotalConnectorCount; count++) {
-        pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(count);
-        // 初始化插槍驗證的 Flag
-        ClearDetectPluginFlag(count);
-
-        pDcChargingInfo->RemoteStartFlag = NO;
-
-        if (pDcChargingInfo->Type == _Type_Chademo) {
-            gpio_set_value(pinOut[count], 0x00);
-            ShmCHAdeMOData->evse[pDcChargingInfo->type_index].SelfTest_Comp = NO;
-        } else if (pDcChargingInfo->Type == _Type_GB) {
-            gpio_set_value(pinOut[count], 0x00);
-            ShmGBTData->evse[pDcChargingInfo->type_index].SelfTest_Comp = NO;
-        } else if (pDcChargingInfo->Type == _Type_CCS_2) {
-            //if (ShmCcsData->CommProtocol == _CCS_COMM_V2GMessage_DIN70121) { //DS60-120 remove
-            if (pSysConfig->TotalConnectorCount == 1) {
-                gpio_set_value(pinOut[1], 0x01);
-            } else {
-                gpio_set_value(pinOut[count], 0x01);
-            }
-            ShmCcsData->V2GMessage_DIN70121[pDcChargingInfo->type_index].SelfTest_Comp = NO;
-            //}
-        }
-
-        strcpy((char *)ShmOCPP16Data->StatusNotification[count].ErrorCode, "NoError");
-    }
-
-    for (count = 0; count < pSysConfig->AcConnectorCount; count++) {
-        pAcChargingInfo = (struct ChargingInfoData *)GetAcChargingInfoData(count);
-
-        pAcChargingInfo->RemoteStartFlag = NO;
-
-        if (pAcChargingInfo->Type == _Type_AC) {
-            pAcChargingInfo->SelfTest_Comp = NO;
-            strcpy((char *)ShmOCPP16Data->StatusNotification[count + pSysConfig->TotalConnectorCount].ErrorCode, "NoError");
-        }
-    }
-
-    return PASS;
-}
-
-bool InitialSystemDefaultConfig()
-{
-    bool result = true;
-
-    LoadSysConfigAndInfo();
-    InitGPIO();
-    InitEthernet();
-    GetMacAddress();
-
-    return result;
-}
-
-//顯示自檢錯誤原因,觸發對應的flag
-bool DisplaySelfTestFailReason()
-{
-    bool result = false;
-    uint8_t index = 0;
-
-    // RB、FB、407、EV 小板中有些板子無回應
-    if (ShmRelayModuleData->SelfTest_Comp == NO) {
-        pAlarmCode->AlarmEvents.bits.RelayboardStestFail = true;
-    }
-
-    if (ShmFanModuleData->SelfTest_Comp == NO) {
-        pAlarmCode->AlarmEvents.bits.FanboardStestFail = true;
-    }
-
-    if (ShmPrimaryMcuData->SelfTest_Comp == NO) {
-        pAlarmCode->AlarmEvents.bits.PrimaryStestFail = true;
-    }
-
-    if (ShmLedModuleData->SelfTest_Comp == NO) {
-        pAlarmCode->AlarmEvents.bits.LedboardStestFail = true;
-    }
-
-    for (index = 0; index < pSysConfig->TotalConnectorCount; index++) {
-        pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);
-
-        if (pDcChargingInfo->Type == _Type_Chademo) {
-            if (ShmCHAdeMOData->evse[pDcChargingInfo->type_index].SelfTest_Comp == NO) {
-                pAlarmCode->AlarmEvents.bits.ChademoboardStestFail = true;
-            }
-        } else if (pDcChargingInfo->Type == _Type_GB) {
-            if (ShmGBTData->evse[pDcChargingInfo->type_index].SelfTest_Comp == NO) {
-                pAlarmCode->AlarmEvents.bits.GbtboardStestFail = true;
-            }
-        } else if (pDcChargingInfo->Type == _Type_CCS_2) {
-            if (ShmCcsData->CommProtocol == _CCS_COMM_V2GMessage_DIN70121) {
-                if (ShmCcsData->V2GMessage_DIN70121[pDcChargingInfo->type_index].SelfTest_Comp == NO) {
-                    pAlarmCode->AlarmEvents.bits.CCSboardStestFail = true;
-                }
-            }
-        }
-    }
-
-    for (index = 0; index < pSysConfig->AcConnectorCount; index++) {
-        pAcChargingInfo = (struct ChargingInfoData *)GetAcChargingInfoData(index);
-
-        // 先借 GBT 顯示
-        if (pAcChargingInfo->SelfTest_Comp == NO) {
-            pAlarmCode->AlarmEvents.bits.AcConnectorStestFail = true;
-        }
-    }
-
-    if (pSysInfo->AcContactorStatus == NO) {
-#if !defined DD360 && !defined DD360Audi && !defined DD360ComBox &&!defined DD360UCar
-        // AC Contact 未搭上
-        pAlarmCode->AlarmEvents.bits.AcContactStestFail = true;
-        result = true;
-#endif // !defined DD360 && !defined DD360Audi && !defined DD360ComBox
-    }
-    //else if (pAlarmCode->AlarmEvents.bits.PsuDipSwitchStestFail == YES) { //DS60-120 add
-    //    result = true;
-    //}
-    else if (ShmPsuData->SystemAvailablePower <= 0 &&
-             ShmPsuData->SystemAvailableCurrent <= 0) {
-        // PSU 通訊問題
-        pAlarmCode->AlarmEvents.bits.PsuModuleStestFail = true;
-        result = true;
-    }
-
-    return result;
-}
-
-//===============================================
-// Common Detect Chk - Stop Charging ?
-//===============================================
-int isEvBoardStopChargeFlag(uint8_t gunIndex)
-{
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-
-    //printf("StopChargeFlag = %d", chargingInfo[gunIndex]->StopChargeFlag);
-    return pDcChargingInfo->StopChargeFlag;
-}
-
-bool isEvBoardNormalStopChargeFlag(uint8_t gunIndex)
-{
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-
-    return pDcChargingInfo->NormalStopChargeFlag;
-}
-
-//===============================================
-// 掃描插槍狀況
-//===============================================
-void ClearDetectPluginFlag(int gunIndex)
-{
-
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-
-    if (pDcChargingInfo->RemoteStartFlag == YES) {
-        pDcChargingInfo->RemoteStartFlag = NO;
-    }
-    ShmDcCommonData->pGunInfo[gunIndex].WaitForPlugit = NO;
-
-    if (pSysInfo->OrderCharging != NO_DEFINE) {
-        pSysInfo->OrderCharging = NO_DEFINE;
-    }
-}
-
-void DetectPluginStart(int gunIndex)
-{
-    //pSysInfo->WaitForPlugit = YES;
-    ShmDcCommonData->pGunInfo[gunIndex].WaitForPlugit = YES;
-}
-
-bool isDetectPlugin(int gunIndex)
-{
-    if (ShmDcCommonData->pGunInfo[gunIndex].WaitForPlugit == YES) {
-        return true;
-    }
-    /*
-    if (pSysInfo->WaitForPlugit == YES) {
-        return true;
-    }
-    */
-    return false;
-}
-
-//===============================================
-// Common Detect Chk - Chademo
-//===============================================
-bool isEvGunLocked_chademo(uint8_t gunIndex)
-{
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-
-    return (DetectBitValue(pDcChargingInfo->GunLocked , 0) == 0) ? NO : YES;
-}
-
-bool isEvContactorWelding_chademo(uint8_t gunIndex)
-{
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-
-    return DetectBitValue(ShmCHAdeMOData->ev[pDcChargingInfo->type_index].EvDetection, 3);
-}
-
-bool isEvStopReq_chademo(uint8_t gunIndex)
-{
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-
-    return DetectBitValue(ShmCHAdeMOData->ev[pDcChargingInfo->type_index].EvDetection, 4);
-}
-
-bool isEvStopCharging_chademo(uint8_t gunIndex)
-{
-    if (isEvGunLocked_chademo(gunIndex) == NO) {
-        // 無鎖槍 = 停止
-        //log_info("gun locked none (%d) ", gunIndex);
-        return YES;
-    }
-
-    return NO;
-}
-
-uint8_t isPrechargeStatus_chademo(uint8_t gunIndex)
-{
-    uint8_t result = 0x00;
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-
-    result = ShmCHAdeMOData->ev[pDcChargingInfo->type_index].PresentMsgFlowStatus;
-
-    return result;
-}
-
-//===============================================
-// Common Detect Chk - GB
-//===============================================
-bool isEvGunLocked_gb(uint8_t gunIndex)
-{
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-
-    return (DetectBitValue(pDcChargingInfo->GunLocked , 0) == 0) ? NO : YES;
-}
-
-bool isEvStopCharging_gb(uint8_t gunIndex)
-{
-    if (isEvGunLocked_gb(gunIndex) == NO) {
-        // 無鎖槍 = 停止
-        //log_info("gun locked none. ");
-        return YES;
-    }
-
-    return NO;
-}
-
-uint8_t isPrechargeStatus_gb(uint8_t gunIndex)
-{
-    uint8_t result = 0x00;
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-
-    result = ShmGBTData->ev[pDcChargingInfo->type_index].PresentMsgFlowStatus;
-
-    return result;
-}
-
-//===============================================
-// Common Detect Chk - CCS
-//===============================================
-bool isEvGunLocked_ccs(uint8_t gunIndex)
-{
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-
-    return (DetectBitValue(pDcChargingInfo->GunLocked , 0) == 0) ? NO : YES;
-}
-
-uint8_t isPrechargeStatus_ccs(uint8_t gunIndex)
-{
-    //uint8_t result = 0x00;
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-
-    return ShmCcsData->V2GMessage_DIN70121[pDcChargingInfo->type_index].PresentMsgFlowStatus;
-}
-
-bool isEvStopCharging_ccs(uint8_t gunIndex)
-{
-    if (isEvGunLocked_ccs(gunIndex) == NO) {
-        // 無鎖槍 = 停止
-        //log_info("gun locked none. ");
-        return YES;
-    }
-
-    return NO;
-}
-
-//===============================================
-// Callback
-//===============================================
-void DisplayChargingInfo()
-{
-    uint8_t i = 0;
-
-    log_info("*********** DisplayChargingInfo *********** ");
-    for (i = 0; i < pSysConfig->TotalConnectorCount; i++) {
-        pDcChargingInfo =  (struct ChargingInfoData *)GetDcChargingInfoData(i);
-
-        if (pDcChargingInfo->SystemStatus != S_IDLE &&
-                pDcChargingInfo->SystemStatus != S_RESERVATION) {
-            ChangeGunSelectByIndex(i);
-            return;
-        }
-    }
-
-    if (pSysConfig->AcConnectorCount > 0 &&
-            pSysInfo->CurGunSelectedByAc == NO_DEFINE)
-    {
-        pAcChargingInfo = (struct ChargingInfoData*)GetAcChargingInfoData(0);
-
-        if (pAcChargingInfo->SystemStatus >= S_PREPARNING &&
-            pAcChargingInfo->SystemStatus <= S_COMPLETE)
-        {
-            pSysInfo->CurGunSelectedByAc = DEFAULT_AC_INDEX;
-        }
-    }
-
-    usleep(50000);
-
-    systemPageRestoreInit();
-}
-
-void _AutoReturnTimeout(int gunIndex)
-{
-    log_info("*********** _AutoReturnTimeout(%d) *********** ", pSysInfo->PageIndex);
-    if (pSysInfo->PageIndex == _PAGE_PRECHARGE) {
-        pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-        pDcChargingInfo->SystemStatus = S_ALARM;
-        //pSysInfo->SystemPage = _LCM_ERROR;
-        pSysInfo->SystemPage = _PAGE_PLUGOUT;
-        ShmDcCommonData->PreAuth_Config = _CREDITCARD_CANCEL;
-        ShmDcCommonData->PreAuth_Result = 0;
-        //pSysInfo->SystemPage = _PAGE_PAYING;
-        //StartGunInfoTimeoutDet(pSysInfo->CurGunSelected,Timeout_FinalCost);
-        ClearDetectPluginFlag(gunIndex);
-    }
-}
-
-void _SelfTestTimeout(void)
-{
-    if (pSysInfo->BootingStatus != BOOT_COMPLETE) {
-        for (uint8_t gunIndex = 0; gunIndex < pSysConfig->TotalConnectorCount; gunIndex++) {
-            setChargerMode(gunIndex, MODE_ALARM);
-        }
-    }
-    ShmPsuData->Work_Step = _NO_WORKING;
-    pSysInfo->SelfTestSeq = _STEST_FAIL;
-    log_info("Self test timeout. ");
-}
-
-void _AuthorizedTimeout(void)
-{
-    int i;
-    //if (IsAuthorizingMode()) {
-        log_info("*********** _AuthorizedTimeout *********** ");
-        StopSystemTimeoutDet();
-        //isCardScan = false;
-        SetIsCardScan(false);
-
-        //StopSystemTimeoutDet();
-        StopGunInfoTimeoutDet(pSysInfo->CurGunSelected);
-        ShmDcCommonData->TradeCancel = TRUE;
-        ShmDcCommonData->PreAuth_Config = _CREDITCARD_CANCEL;
-        ShmDcCommonData->PreAuth_Result = 0;
-        pSysInfo->SystemPage = _PAGE_SENSING;
-        StartSystemTimeoutDet(Timeout_TradeCancel);
-        for (i = 0; i <= 30; i++) {
-            if (ShmDcCommonData->PreAuth_Config == _CREDITCARD_IDLE)
-                break;
-            sleep(1);
-        }
-        ShmDcCommonData->PreAuth_Result = 0;
-
-        StopSystemTimeoutDet();
-        ClearDetectPluginFlag(pSysInfo->CurGunSelected);
-        strcpy((char*)pSysConfig->UserId, "");
-        ClearAuthorizedFlag();
-        setChargerMode(pSysInfo->CurGunSelected, S_IDLE);
-     //   StartSystemTimeoutDet(Timeout_ReturnViewPage);
-    //}
-}
-
-void _DetectPlugInTimeout(uint8_t gunIndex)
-{
-	int i;
-    log_info("*********** Gun%d _DetectPlugInTimeout *********** ",gunIndex);
-    pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(gunIndex);
-    StopSystemTimeoutDet();
-    StopGunInfoTimeoutDet(gunIndex);
-
-    if (pDcChargingInfo->RemoteStartFlag || pDcChargingInfo->isRemoteStart) {
-        StopSystemTimeoutDet();
-        ClearDetectPluginFlag(gunIndex);
-        strcpy((char*)pSysConfig->UserId, "");
-        setChargerMode(gunIndex, S_IDLE);
-        return;
-    }
-    pSysInfo->CurGunSelected = gunIndex;
-	ShmDcCommonData->PreAuth_Config = _CREDITCARD_CANCEL;
-	ShmDcCommonData->PreAuth_Result = 0;
-    pSysInfo->SystemPage = _PAGE_SENSING;
-    ShmDcCommonData->TradeCancel = TRUE;
-    StartSystemTimeoutDet(Timeout_TradeCancel);
-	for(i=0;i<=30;i++) {
-		if(ShmDcCommonData->PreAuth_Config == _CREDITCARD_IDLE)
-			break;
-		sleep(1);
-	}
-	ShmDcCommonData->PreAuth_Result = 0;
-
-    if (pSysInfo->CurGunSelected == gunIndex) {
-        systemPageRestoreInit();
-    }
-    StopSystemTimeoutDet();
-    ClearDetectPluginFlag(gunIndex);
-    strcpy((char *)pSysConfig->UserId, "");
-	setChargerMode(gunIndex, S_IDLE);
-    //systemPageRestoreInit();
-}
-
-void _DetectEvChargingEnableTimeout(uint8_t gunIndex)
-{
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-
-    if (pDcChargingInfo->Type == _Type_Chademo) {
-        if (!isEvGunLocked_chademo(gunIndex)) {
-            log_info("*********** _DetectEvChargingEnableTimeout (chademo) ***********");
-        }
-    } else if (pDcChargingInfo->Type == _Type_GB) {
-        if (!isEvGunLocked_ccs(gunIndex)) {
-            log_info("*********** _DetectEvChargingEnableTimeout (gb) ***********");
-        }
-    } else if (pDcChargingInfo->Type == _Type_CCS_2) {
-        if (!isEvGunLocked_ccs(gunIndex)) {
-            log_info("*********** _DetectEvChargingEnableTimeout (ccs) ***********");
-        }
-    }
-    //pSysInfo->SystemPage = _LCM_ERROR;
-    pSysInfo->SystemPage = _PAGE_MAINTAIN;
-    ChargingTerminalProcess(gunIndex);
-    _AutoReturnTimeout(gunIndex);
-}
-
-void _DetectEvseChargingEnableTimeout(uint8_t gunIndex)
-{
-    log_info("*********** _DetectEvseChargingEnableTimeout (GFD timeout) ***********");
-
-    ChargingTerminalProcess(gunIndex);
-    //pSysInfo->SystemPage = _LCM_ERROR;
-    pSysInfo->SystemPage = _PAGE_MAINTAIN;
-    _AutoReturnTimeout(gunIndex);
-}
-
-void _PrepareTimeout(uint8_t gunIndex)
-{
-    log_info("*********** _PrepareTimeout ***********");
-
-    ChargingTerminalProcess(gunIndex);
-    pAlarmCode->AlarmEvents.bits.PsuNoResource = YES;
-    //pSysInfo->SystemPage = _LCM_ERROR;
-    pSysInfo->SystemPage = _PAGE_MAINTAIN;
-    _AutoReturnTimeout(gunIndex);
-}
-
-void _CcsPrechargeTimeout(uint8_t gunIndex)
-{
-    log_info("*********** _CcsPrechargeTimeout ***********");
-    ChargingTerminalProcess(gunIndex);
-    //pSysInfo->SystemPage = _LCM_ERROR;
-    pSysInfo->SystemPage = _PAGE_MAINTAIN;
-}
-void _LinkErrorTimeout(uint8_t gunIndex)
-{
-	log_info("*********** _LinkErrorTimeout ***********");
-	setChargerMode(pSysInfo->CurGunSelected, S_IDLE);
-    systemPageRestoreInit();
-}
-
-//===============================================
-// 取得卡號與卡號驗證
-//===============================================
-void AuthorizingStart(void)
-{
-    ShmOCPP16Data->SpMsg.bits.AuthorizeReq = YES;
-    pSysInfo->AuthorizeFlag = YES;
-}
-
-void ClearAuthorizedFlag(void)
-{
-    ShmOCPP16Data->SpMsg.bits.AuthorizeConf = NO;
-    pSysInfo->AuthorizeFlag = NO;
-}
-
-bool isAuthorizedComplete(void)
-{
-    if (pSysInfo->AuthorizeFlag == YES) {
-        return false;
-    }
-    return true;
-}
-
-bool IsAuthorizingMode()
-{
-    if (pSysInfo->AuthorizeFlag == NO) {
-        return false;
-    }
-
-    return true;
-}
-
-//===============================================
-// 紀錄 Alarm Code
-//===============================================
-void ResetChargerAlarmCode(uint8_t gunIndex, char *code)
-{
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-
-    if (strcmp(code, "012234") == EQUAL) {
-        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaGfdTrip = NO;
-    } else if (strcmp(code, "012235") == EQUAL) {
-        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSGfdTrip = NO;
-    } else if (strcmp(code, "012236") == EQUAL) {
-        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTGfdTrip = NO;
-    } else if (strcmp(code, "012288") == EQUAL) {
-        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSUvpFail = NO;
-    } else if (strcmp(code, "012289") == EQUAL) {
-        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaUvpFail = NO;
-    } else if (strcmp(code, "012290") == EQUAL) {
-        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTUvpFail = NO;
-    } else if (strcmp(code, "012229") == EQUAL) {
-        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaConnectOTP = NO;
-    } else if (strcmp(code, "012230") == EQUAL) {
-        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSConnectOTP = NO;
-    } else if (strcmp(code, "012231") == EQUAL) {
-        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTConnectOTP = NO;
-    } else if (strcmp(code, "011011") == EQUAL) {
-        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaRelayWeldingFault = NO;
-    } else if (strcmp(code, "011013") == EQUAL) {
-        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSRelayWeldingFault = NO;
-    } else if (strcmp(code, "011015") == EQUAL) {
-        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTRelayWeldingFault = NO;
-    } else if (strcmp(code, "011012") == EQUAL) {
-        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaRelayDrivingFault = NO;
-    } else if (strcmp(code, "011014") == EQUAL) {
-        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSRelayDrivingFault = NO;
-    } else if (strcmp(code, "011016") == EQUAL) {
-        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTRelayDrivingFault = NO;
-    } else if (strcmp(code, "011018") == EQUAL) {
-        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaConnectTempSensorFail = NO;
-    } else if (strcmp(code, "011019") == EQUAL) {
-        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSConnectTempSensorFail = NO;
-    } else if (strcmp(code, "011020") == EQUAL) {
-        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTConnectTempSensorFail = NO;
-    } else if (strcmp(code, "012323") == EQUAL) {
-        ShmDcCommonData->ChillerTempErr[gunIndex].StatusBit.ChillerOTP = NO;
-    } else if (strcmp(code, "011038") == EQUAL) {
-        ShmDcCommonData->ChillerTempErr[gunIndex].StatusBit.ChillerTempSensorFail = NO;
-    }
-
-    if (strncmp((char *)pDcChargingInfo->ConnectorAlarmCode, "012229", 6) == EQUAL ||
-            strncmp((char *)pDcChargingInfo->ConnectorAlarmCode, "012230", 6) == EQUAL ||
-            strncmp((char *)pDcChargingInfo->ConnectorAlarmCode, "012231", 6) == EQUAL ||
-            strncmp((char *)pDcChargingInfo->ConnectorAlarmCode, "011011", 6) == EQUAL ||
-            strncmp((char *)pDcChargingInfo->ConnectorAlarmCode, "011013", 6) == EQUAL ||
-            strncmp((char *)pDcChargingInfo->ConnectorAlarmCode, "011015", 6) == EQUAL ||
-            strncmp((char *)pDcChargingInfo->ConnectorAlarmCode, "011012", 6) == EQUAL ||
-            strncmp((char *)pDcChargingInfo->ConnectorAlarmCode, "011014", 6) == EQUAL ||
-            strncmp((char *)pDcChargingInfo->ConnectorAlarmCode, "011016", 6) == EQUAL ||
-            strncmp((char *)pDcChargingInfo->ConnectorAlarmCode, "011018", 6) == EQUAL ||
-            strncmp((char *)pDcChargingInfo->ConnectorAlarmCode, "011019", 6) == EQUAL ||
-            strncmp((char *)pDcChargingInfo->ConnectorAlarmCode, "011020", 6) == EQUAL ||
-            strncmp((char *)pDcChargingInfo->ConnectorAlarmCode, "012323", 6) == EQUAL ||
-            strncmp((char *)pDcChargingInfo->ConnectorAlarmCode, "011038", 6) == EQUAL) {
-        strncpy((char *)pDcChargingInfo->ConnectorAlarmCode, "", 6);
-    }
-}
-
-void RecordAlarmCode(uint8_t gunIndex, char *code)
-{
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-
-    if((pDcChargingInfo->SystemStatus > S_IDLE && pDcChargingInfo->SystemStatus < S_TERMINATING) ||
-        (pDcChargingInfo->SystemStatus >= S_CCS_PRECHARGE_ST0 && pDcChargingInfo->SystemStatus <= S_CCS_PRECHARGE_ST1))
-    {
-        if (strncmp((char *)pDcChargingInfo->ConnectorAlarmCode, "", 6) == EQUAL) {
-            memcpy(pDcChargingInfo->ConnectorAlarmCode, code, 6);
-        }
-        
-        if (pDcChargingInfo->StopChargeFlag == NO)
-        {
-            log_info("RecordAlarmCode set Stop Charge Flag");
-            pDcChargingInfo->StopChargeFlag = YES;
-        }
-        
-    }
-}
-
-void ReleaseAlarmCode(uint8_t gunIndex)
-{
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-
-    //if (strncmp((char *)pDcChargingInfo->ConnectorAlarmCode, "", 6) == EQUAL) {
-    //    return;
-    //}
-
-    switch (pDcChargingInfo->Type) {
-    case _Type_Chademo:
-        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaGfdTrip = NO;
-        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaUvpFail = NO;
-        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaConnectOVP = NO;
-        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaGfdWarning = NO;
-        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaRelayWeldingFault = NO;
-        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaRelayDrivingFault = NO;
-        break;
-
-    case _Type_CCS_2:
-        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSGfdTrip = NO;
-        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSUvpFail = NO;
-        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSConnectOVP = NO;
-        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSGfdWarning = NO;
-        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSRelayWeldingFault = NO;
-        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSRelayDrivingFault = NO;
-        break;
-
-    case _Type_GB:
-        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTGfdTrip = NO;
-        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTUvpFail = NO;
-        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTConnectOVP = NO;
-        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTGfdWarning = NO;
-        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTRelayWeldingFault = NO;
-        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTRelayDrivingFault = NO;
-        break;
-    }
-    memcpy(pDcChargingInfo->ConnectorAlarmCode, "", 6);
-}
-
-//===============================================
-// EmergencyStop and Charging Stop
-//===============================================
-void ChargingTerminalProcess(uint8_t gunIndex)
-{
-    pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(gunIndex);
-    //if (pDcChargingInfo->SystemStatus == S_CHARGING)
-    //ShmDcCommonData->StopCharge[gunIndex] = TRUE;
-    setChargerMode(gunIndex, MODE_TERMINATING);
-}
-
-void ChargingAlarmProcess(uint8_t gunIndex)
-{
-    pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(gunIndex);
-    //if (pDcChargingInfo->SystemStatus == S_CHARGING)
-    //ShmDcCommonData->StopCharge[gunIndex] = TRUE;
-    UpdateErrorCodeToOcpp(gunIndex);
-    setChargerMode(gunIndex, MODE_ALARM);
-}
-
-void AcChargingTerminalProcess(void)
-{
-    pAcChargingInfo =  (struct ChargingInfoData *)GetAcChargingInfoData(0);
-
-    pAcChargingInfo->SystemStatus = MODE_TERMINATING;
-}
-
-void StopChargingProcessByString(uint8_t level)
-{
-    if (level > pSysWarning->Level) {
-        pSysWarning->Level = level;
-    }
-}
-
-void ReleaseChargingProcessByString(uint8_t level)
-{
-    if (level >= pSysWarning->Level) {
-        pSysWarning->Level = WARN_LV_NL;
-    }
-}
-
-// 一般錯誤停止充電處理函式
-void BoardErrOccurByString(uint8_t index, char *code)
-{
-    uint8_t level = 1;
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);
-
-    if ((pDcChargingInfo->SystemStatus > S_IDLE &&
-            pDcChargingInfo->SystemStatus < S_TERMINATING) ||
-            (pDcChargingInfo->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
-             pDcChargingInfo->SystemStatus <= S_CCS_PRECHARGE_ST1)) {
-        if (strncmp(code, "023730", 6) == EQUAL &&
-                pInfoCode->InfoEvents.bits.ChademoChargerGetEmergencyStop == NO
-           ) {
-            pInfoCode->InfoEvents.bits.ChademoChargerGetEmergencyStop = YES;
-        }
-        ChargingTerminalProcess(index);
-    }
-
-    StopChargingProcessByString(level);
-}
-
-void ReleaseBoardErrOccurByString(uint8_t index, char *code)
-{
-    bool isTrigger = false;
-    uint8_t level = 1;
-
-    if (strncmp(code, "023730", 6) == 0 &&
-            pInfoCode->InfoEvents.bits.ChademoChargerGetEmergencyStop == YES) {
-        isTrigger = true;
-        pInfoCode->InfoEvents.bits.ChademoChargerGetEmergencyStop = NO;
-    }
-
-    if (isTrigger) {
-        ReleaseChargingProcessByString(level);
-    }
-}
-
-// 急停狀況的停止充電處理函式
-void EmcOccureByString(char *code)
-{
-    uint8_t level = 2;
-    // 嚴重的急停有以下幾種 : EMC 按鈕、Mainbreak、Dooropen
-    // 其錯誤等級為 2
-
-    //DS60-120 remove
-    if (strncmp(code, "012251", 6) == EQUAL ||
-            strncmp(code, "012252", 6) == EQUAL ||
-            strncmp(code, "012238", 6) == EQUAL ||
-            strncmp(code, "042251", 6) == EQUAL ||
-            strncmp(code, "042252", 6) == EQUAL ||
-            strncmp(code, "012304", 6) == EQUAL ||
-            strncmp(code, "042327", 6) == EQUAL ||
-            strncmp(code, "042328", 6) == EQUAL ||
-            strncmp(code, "042200", 6) == EQUAL ||
-            strncmp(code, "042201", 6) == EQUAL ||
-            strncmp(code, "042202", 6) == EQUAL ||
-            strncmp(code, "042267", 6) == EQUAL) {
-        for (uint8_t gun = 0; gun < pSysConfig->TotalConnectorCount; gun++) {
-            pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gun);
-
-            //strncpy((char *)ShmOCPP16Data->StatusNotification[gun].VendorErrorCode, code, 6);
-
-            if ((pDcChargingInfo->SystemStatus > S_IDLE &&
-                    pDcChargingInfo->SystemStatus < S_TERMINATING) ||
-                    (pDcChargingInfo->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
-                     pDcChargingInfo->SystemStatus <= S_CCS_PRECHARGE_ST1)) {
-                //ChargingTerminalProcess(gun);
-                if (strncmp((char *)pDcChargingInfo->ConnectorAlarmCode, "", 6) == EQUAL) {
-                    memcpy(pDcChargingInfo->ConnectorAlarmCode, code, 6);
-                }
-                ChargingAlarmProcess(gun);
-            }
-        }
-
-        StopChargingProcessByString(level);
-        InformOcppErrOccur(4);
-    }
-}
-
-void ReleaseEmsOccureByString(uint8_t index, char *code)
-{
-    bool isTrigger = false;
-    uint8_t level = 2;
-
-    if (strncmp(code, "042251", 6) == 0 ) {
-        isTrigger = true;
-    } else if (strncmp(code, "012251", 6) == 0 &&
-               pAlarmCode->AlarmEvents.bits.EmergencyStopTrip == YES) {
-        isTrigger = true;
-        pAlarmCode->AlarmEvents.bits.EmergencyStopTrip = NO;
-    } else if (strncmp(code, "012252", 6) == 0 &&
-               pAlarmCode->AlarmEvents.bits.DoorOpen == YES) {
-        isTrigger = true;
-        pAlarmCode->AlarmEvents.bits.DoorOpen = NO;
-    } else if (strncmp(code, "012237", 6) == 0 &&
-               pAlarmCode->AlarmEvents.bits.SpdTrip == YES) {
-        isTrigger = true;
-        pAlarmCode->AlarmEvents.bits.SpdTrip = NO;
-    } else if (strncmp(code, "012238", 6) == 0 &&
-               pAlarmCode->AlarmEvents.bits.MainPowerBreakerTrip == YES) {
-        isTrigger = true;
-        pAlarmCode->AlarmEvents.bits.MainPowerBreakerTrip = NO;
-    }
-
-    if (isTrigger) {
-        ReleaseChargingProcessByString(level);
-        InformOcppErrOccur(6);
-    }
-}
-
-static void checkOvpState(uint8_t gunIndex, uint8_t gunType)
-{
-    switch(gunType) {
-        case _Type_Chademo:
-            if(ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaConnectOVP == YES)
-                RecordAlarmCode(gunIndex, "012217");
-            break;
-        case _Type_CCS_2:
-            if(ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSConnectOVP == YES)
-                RecordAlarmCode(gunIndex, "012219");
-            break;
-        case _Type_GB:
-            if(ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTConnectOVP == YES)
-                RecordAlarmCode(gunIndex, "012221");
-            break;
-    }
-}
-
-//===============================================
-// 確認各小板偵測的錯誤狀況
-//===============================================
-void CheckErrorOccurStatus(uint8_t index)
-{
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);
-
-    // RB
-    if (pSysConfig->PhaseLossPolicy == YES) {
-        if (pAlarmCode->AlarmEvents.bits.SystemL1InputUVP == YES ||
-                pAlarmCode->AlarmEvents.bits.SystemL2InputUVP == YES ||
-                pAlarmCode->AlarmEvents.bits.SystemL3InputUVP == YES) {
-            if (pSysWarning->ExtraErrProcess == _EXTRA_ERR_PROCESS_NONE) {
-                pSysWarning->ExtraErrProcess = _EXTRA_ERR_PROCESS_INUVP;
-                StopChargingProcessByString(2);
-                InformOcppErrOccur(13);
-            }
-
-            //DS60-120 add -----
-            if (strncmp((char *)pDcChargingInfo->ConnectorAlarmCode, "", 6) == EQUAL) {
-                if (pAlarmCode->AlarmEvents.bits.SystemL1InputUVP == YES) {
-                    memcpy(pDcChargingInfo->ConnectorAlarmCode, "012203", 6);
-                } else if (pAlarmCode->AlarmEvents.bits.SystemL2InputUVP == YES) {
-                    memcpy(pDcChargingInfo->ConnectorAlarmCode, "012204", 6);
-                } else if (pAlarmCode->AlarmEvents.bits.SystemL3InputUVP == YES) {
-                    memcpy(pDcChargingInfo->ConnectorAlarmCode, "012205", 6);
-                }
-            }
-            log_info("1 CheckErrorOccurStatus");
-            pDcChargingInfo->StopChargeFlag = YES;
-            //------------------------------------------------------------------
-        } else {
-            if (pSysWarning->ExtraErrProcess == _EXTRA_ERR_PROCESS_INUVP) {
-                pSysWarning->ExtraErrProcess = _EXTRA_ERR_PROCESS_NONE;
-                ReleaseChargingProcessByString(2);
-                InformOcppErrOccur(6);
-            }
-        }
-    } else {
-        if (pSysWarning->ExtraErrProcess == _EXTRA_ERR_PROCESS_INUVP) {
-            pSysWarning->ExtraErrProcess = _EXTRA_ERR_PROCESS_NONE;
-            ReleaseChargingProcessByString(2);
-            InformOcppErrOccur(6);
-        }
-    }
-
-    if (pAlarmCode->AlarmEvents.bits.SystemL1InputOVP == YES ||
-            pAlarmCode->AlarmEvents.bits.SystemL2InputOVP == YES ||
-            pAlarmCode->AlarmEvents.bits.SystemL3InputOVP == YES) {
-        if (pSysWarning->ExtraErrProcess == _EXTRA_ERR_PROCESS_NONE) {
-            pSysWarning->ExtraErrProcess = _EXTRA_ERR_PROCESS_INOVP;
-            StopChargingProcessByString(2);
-            InformOcppErrOccur(14);
-        }
-
-        //DS60-120 -----
-        if (strncmp((char *)pDcChargingInfo->ConnectorAlarmCode, "", 6) == EQUAL) {
-            if (pAlarmCode->AlarmEvents.bits.SystemL1InputOVP == YES) {
-                memcpy(pDcChargingInfo->ConnectorAlarmCode, "012200", 6);
-            } else if (pAlarmCode->AlarmEvents.bits.SystemL2InputOVP == YES) {
-                memcpy(pDcChargingInfo->ConnectorAlarmCode, "012201", 6);
-            } else if (pAlarmCode->AlarmEvents.bits.SystemL3InputOVP == YES) {
-                memcpy(pDcChargingInfo->ConnectorAlarmCode, "012202", 6);
-            }
-        }
-        log_info("2 CheckErrorOccurStatus");
-        pDcChargingInfo->StopChargeFlag = YES;
-        //----------------------------------------------------------------------
-    } else {
-        if (pSysWarning->ExtraErrProcess == _EXTRA_ERR_PROCESS_INOVP) {
-            pSysWarning->ExtraErrProcess = _EXTRA_ERR_PROCESS_NONE;
-            ReleaseChargingProcessByString(2);
-            InformOcppErrOccur(6);
-        }
-    }
-
-    checkOvpState(index, pDcChargingInfo->Type);
-
-    //--------------------------------------------------------------------------
-    if (strlen((char *)pDcChargingInfo->ConnectorAlarmCode) == 0) {
-        //Primary
-        if (pAlarmCode->AlarmEvents.bits.EmergencyStopTrip == YES) {
-            memcpy(pDcChargingInfo->ConnectorAlarmCode, "012251", 6);
-        } else if (pAlarmCode->AlarmEvents.bits.DoorOpen == YES) {
-            memcpy(pDcChargingInfo->ConnectorAlarmCode, "012252", 6);
-        } else if (pAlarmCode->AlarmEvents.bits.MainPowerBreakerTrip == YES) {
-            memcpy(pDcChargingInfo->ConnectorAlarmCode, "012238", 6);
-        } else if (pAlarmCode->AlarmEvents.bits.DisconnectedFromDo == YES) {
-            memcpy(pDcChargingInfo->ConnectorAlarmCode, "012304", 6);
-        } else if (pInfoCode->InfoEvents.bits.BackendDisconnectedViaEthernet == YES) {
-            memcpy(pDcChargingInfo->ConnectorAlarmCode, "033900", 6);
-        }
-        //Chiller temperature
-        //else if (pAlarmCode->AlarmEvents.bits.SystemChillerOTP == YES) {
-        //    memcpy(pDcChargingInfo->ConnectorAlarmCode, "012323", 6);
-        //} else if (pFaultCode->FaultEvents.bits.ChillerTempSensorBroken == YES) {
-        //    memcpy(pDcChargingInfo->ConnectorAlarmCode, "011038", 6);
-        //}
-    }
-    /*
-    if (pAlarmCode->AlarmEvents.bits.EmergencyStopTrip == YES ||
-            pAlarmCode->AlarmEvents.bits.MainPowerBreakerTrip == YES ||
-            pAlarmCode->AlarmEvents.bits.DoorOpen == YES ||
-            pSysWarning->ExtraErrProcess != _EXTRA_ERR_PROCESS_NONE ||
-            pAlarmCode->AlarmEvents.bits.PsuFailureAlarm == YES ||
-            pAlarmCode->AlarmEvents.bits.DisconnectedFromDo == YES ||
-            //Power cabinet alarm status
-            ShmDcCommonData->PowerAlarmState.StatusBit.EmergencyStop == YES ||
-            ShmDcCommonData->PowerAlarmState.StatusBit.DoorOpen == YES ||
-            ShmDcCommonData->PowerAlarmState.StatusBit.DcInputOVP == YES ||
-            ShmDcCommonData->PowerAlarmState.StatusBit.DcInputUVP == YES ||
-            ShmDcCommonData->PowerAlarmState.StatusBit.SystemL1InputOVP == YES ||
-            ShmDcCommonData->PowerAlarmState.StatusBit.SystemL2InputOVP == YES ||
-            ShmDcCommonData->PowerAlarmState.StatusBit.SystemL3InputOVP == YES ||
-            ShmDcCommonData->PowerAlarmState.StatusBit.PsuFailure == YES
-       ) {
-        if ((pDcChargingInfo->SystemStatus > S_IDLE &&
-                pDcChargingInfo->SystemStatus < S_COMPLETE) ||
-                (pDcChargingInfo->SystemStatus >= S_CCS_PRECHARGE_ST0  &&
-                        pDcChargingInfo->SystemStatus <= S_CCS_PRECHARGE_ST1 ))
-            ChargingAlarmProcess(index);
-            pSysWarning->Level = WARN_LV_ER;
-    }*/
-}
-
-//===============================================
-// 確認 GPIO 狀態
-//===============================================
-void gpio_set_value(unsigned int gpio, unsigned int value)
-{
-    int fd;
-    char buf[MAX_BUF];
-
-    snprintf(buf, sizeof(buf), SYSFS_GPIO_DIR "/gpio%d/value", gpio);
-    fd = open(buf, O_WRONLY);
-    if (fd < 0) {
-        perror("gpio/set-value");
-        return;
-    }
-
-    if (value) {
-        write(fd, "1", 2);
-    } else {
-        write(fd, "0", 2);
-    }
-
-    close(fd);
-}
-
-int gpio_get_value(unsigned int gpio, unsigned int *value)
-{
-    int fd;
-    char buf[MAX_BUF];
-    char ch;
-
-    snprintf(buf, sizeof(buf), SYSFS_GPIO_DIR "/gpio%d/value", gpio);
-
-    fd = open(buf, O_RDONLY);
-    if (fd < 0) {
-        perror("gpio/get-value");
-        return fd;
-    }
-
-    read(fd, &ch, 1);
-
-    if (ch != '0') {
-        *value = 1;
-    } else {
-        *value = 0;
-    }
-
-    close(fd);
-    return 0;
-}
-
-void CheckGunTypeFromHw()
-{
-    uint8_t i = 0;
-    int pinIn[4] = {22, 23, 44, 45};
-    unsigned int gpioValue = 0;
-    uint8_t tmp[2] = {0};
-
-    log_info("ModelName = %s", pSysConfig->ModelName);
-    for (i = 0; i < ARRAY_SIZE(pinIn); i++) {
-        gpio_get_value(pinIn[i], &gpioValue);
-        switch (pinIn[i]) {
-        //right slot
-        case 22:
-            bd1_1_status = gpioValue;
-            break;
-        case 23:
-            bd1_2_status = gpioValue;
-            break;
-
-        //left slot
-        case 44:
-            bd0_1_status = gpioValue;
-            break;
-        case 45:
-            bd0_2_status = gpioValue;
-            break;
-        }
-    }
-
-    //BD1(Left-CCS-CND1-SMR2-左槍), BD2(Right-CHADEMO-CND2-SMR1-右槍), CCS: 10 , CHAdeMO: 01 , GBT: 11
-    //CcsChargingData [0至1] 分別為 Right至Left
-    //model name 槍順序左至右分別為Right至Left
-    tmp[1] = (bd0_1_status << 4 | bd0_2_status);
-    tmp[0] = (bd1_1_status << 4 | bd1_2_status);
-    for (i = 0; i < 2; i++) {
-        switch (tmp[i]) {
-        case 0x01:
-            log_info("BD%d(%s) = %s ", i + 1, i == 0 ? "Left" : "Right", "CHAdeMO");
-            break;
-
-        case 0x10:
-            log_info("BD%d(%s) = %s ", i + 1, i == 0 ? "Left" : "Right", "CCS");
-            break;
-
-        case 0x11:
-            log_info("BD%d(%s) = %s ", i + 1, i == 0 ? "Left" : "Right", "GBT");
-            break;
-
-        case 0x00:
-            log_info("BD%d(%s) = %s ", i + 1, i == 0 ? "Left" : "Right", "None");
-            break;
-        }
-    }
-}
-
-void CheckGpioInStatus()
-{
-    int i = 0;
-    int pinIn[2] = { 27, 47 };//{IO BD1_2, IO BD2_2}
-    unsigned int gpioValue = 0;
-
-    for (i = 0; i < ARRAY_SIZE(pinIn); i++) {
-        gpio_get_value(pinIn[i], &gpioValue);
-        if (gpioValue == 0x01) {
-            switch (pinIn[i]) {
-            // 小板緊急停止
-            case 47:
-                for (i = 0; i < pSysConfig->TotalConnectorCount; i++) {
-                    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(i);
-
-                    if (pDcChargingInfo->slotsIndex == 1) {
-                        if (pDcChargingInfo->Type == _Type_Chademo) {
-                            BoardErrOccurByString(i, "023730");
-                        } else if (pDcChargingInfo->Type == _Type_CCS_2) {
-                            BoardErrOccurByString(i, "013627");
-                        }
-                        break;
-                    }
-                }
-                break;
-
-            case 27:
-                for (i = 0; i < pSysConfig->TotalConnectorCount; i++) {
-                    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(i);
-
-                    if (pDcChargingInfo->slotsIndex == 3) {
-                        if (pDcChargingInfo->Type == _Type_Chademo) {
-                            BoardErrOccurByString(i, "023730");
-                        } else if (pDcChargingInfo->Type == _Type_CCS_2) {
-                            BoardErrOccurByString(i, "013627");
-                        }
-                        break;
-                    }
-                }
-                break;
-            }
-        } else {
-            switch (pinIn[i]) {
-            // 小板解除緊急停止
-            case 47:
-                for (i = 0; i < pSysConfig->TotalConnectorCount; i++) {
-                    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(i);
-
-                    if (pDcChargingInfo->slotsIndex == 1) {
-                        if (pDcChargingInfo->Type == _Type_Chademo) {
-                            ReleaseBoardErrOccurByString(i, "023730");
-                        } else if (pDcChargingInfo->Type == _Type_CCS_2) {
-                            ReleaseBoardErrOccurByString(i, "013627");
-                        }
-                        break;
-                    }
-                }
-                break;
-
-            case 27:
-                for (i = 0; i < pSysConfig->TotalConnectorCount; i++) {
-                    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(i);
-
-                    if (pDcChargingInfo->slotsIndex == 3) {
-                        if (pDcChargingInfo->Type == _Type_Chademo) {
-                            ReleaseBoardErrOccurByString(i, "023730");
-                        } else if (pDcChargingInfo->Type == _Type_CCS_2) {
-                            ReleaseBoardErrOccurByString(i, "013627");
-                        }
-                        break;
-                    }
-                }
-                break;
-            }
-        }
-    }
-}
-
-//===============================================
-// Main process
-//===============================================
-// 檢查 uint8_t 中某個 Bit 的值
-// _byte : 欲改變的 byte
-// _bit : 該 byte 的第幾個 bit
-uint8_t DetectBitValue(uint8_t _byte, uint8_t _bit)
-{
-    uint8_t mask_table[] = {0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80};
-
-    return ( _byte & mask_table[_bit] ) != 0x00;
-}
-
-// 設定 Byte 中某個 Bit的值
-// _byte : 欲改變的 byte
-// _bit : 該 byte 的第幾個 bit
-// value : 修改的值為 0 or 1
-void SetBitValue(uint8_t *_byte, uint8_t _bit, uint8_t value)
-{
-    if (value == 1) {
-        *_byte |= (1 << _bit);
-    } else if (value == 0) {
-        *_byte ^= (1 << _bit);
-    }
-}
-
-uint8_t isModeChange(uint8_t gunIndex)
-{
-    uint8_t result = NO;
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-
-    if (pDcChargingInfo->SystemStatus == pDcChargingInfo->PreviousSystemStatus) {
-        return result;
-    }
-
-    pDcChargingInfo->PreviousSystemStatus = pDcChargingInfo->SystemStatus;
-    ShmDcCommonData->SystemModeChange[gunIndex] = YES; //for Module_EvRxComm print temperature message
-
-    return YES;
-}
-
-static int checkSlotGpioMappingGunType(uint8_t gunIndex, uint8_t gunType)
-{
-    uint8_t slot1 = 0, slot2 = 0;
-
-    if (gunIndex == 0) {
-        slot1 = bd0_1_status;
-        slot2 = bd0_2_status;
-    } else if (gunIndex == 1) {
-        slot1 = bd1_1_status;
-        slot2 = bd1_2_status;
-    }
-
-    log_info("slot %d gpio1 = %d, gpio2 = %d, type = %d",
-             gunIndex,
-             slot1,
-             slot2,
-             gunType);
-
-    switch (gunType) {
-    case _Type_Chademo:
-        if (slot1 != NO && slot2 != YES) {
-            return FAIL;
-        }
-        break;
-
-    case _Type_CCS_2:
-        if (slot1 != YES && slot2 != NO) {
-            return FAIL;
-        }
-        break;
-
-    case _Type_GB:
-        if (slot1 != YES && slot2 != YES) {
-            return FAIL;
-        }
-        break;
-    }
-
-    return PASS;
-}
-
-bool CheckConnectorTypeStatus(void)
-{
-    bool result = true;
-
-    uint8_t gunIndex = 0;
-    struct SysConfigData *pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
-    struct ChargingInfoData *pDcChargingInfo = NULL;
-
-    if (!MappingGunChargingInfo("CSU Task")) {
-        log_error("CheckConnectorTypeStatus MappingGunChargingInfo failed");
-        return false;
-    }
-
-    // 偵測槍屬於哪個 slot : 可知道插在板上的Slot 0 或 1 是 Chademo 還是 CCS
-    for (gunIndex = 0; gunIndex < pSysConfig->TotalConnectorCount; gunIndex++) {
-        pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-
-        if (checkSlotGpioMappingGunType(gunIndex, pDcChargingInfo->Type) == FAIL) {
-            return false;
-        }
-
-		pDcChargingInfo->SystemStatus = S_BOOTING;
-        switch (gunIndex) {
-        case 0:
-            if (pSysConfig->TotalConnectorCount == 1) {
-                if ((bd0_1_status == YES || bd0_2_status == YES) &&
-                        (bd1_1_status == NO && bd1_2_status == NO)) {
-                    pDcChargingInfo->Evboard_id = 0x01;
-                }
-
-                if ((bd0_1_status == NO && bd0_2_status == NO) &&
-                        (bd1_1_status == YES || bd1_2_status == YES)
-                   ) {
-                    pDcChargingInfo->Evboard_id = 0x02;
-                }
-                break;
-            }
-
-            pDcChargingInfo->Evboard_id = 0x01;
-            break;
-
-        case 1:
-            pDcChargingInfo->Evboard_id = 0x02;
-            break;
-        }
-
-        CheckHwSlotStatusLog(gunIndex);
-
-        if (pDcChargingInfo->Evboard_id == 0x00) {
-            return false;
-        }
-    }
-
-    AdjustChargerCurrent();
-
-    return result;
-}
-
-int SpawnTask(void)
-{
-    if(SIMULATION)
-        system("/root/simulation &");
-    sleep(2);
-    system("/root/Module_EventLogging &");
-    system("/root/Module_PrimaryComm &");
-    system("/root/Module_EvComm &");
-    system("/root/Module_LcmControl &");
-    system("/root/Module_InternalComm &");
-    system("/root/Module_ProduceUtils &");
-    system("/root/Module_UpdateFW &");
-    system("/root/Module_DoComm &");
-
-    return PASS;
-}
-
-void KillTask(void)
-{
-    //ChangeLcmByIndex(_LCM_ERROR);
-    ChangeLcmByIndex(_PAGE_MAINTAIN);
-    system("killall Module_EventLogging");
-    system("killall Module_PrimaryComm");
-    system("killall Module_EvComm");
-    system("killall Module_LcmControl");
-    system("killall Module_InternalComm");
-    system("killall Module_UpdateFW");
-    system("killall Module_ChkSysTask");
-    //system("killall Module_DoComm");
-    return ;
-}
-
-void KillTaskExceptPrimary(void)
-{
-    //ChangeLcmByIndex(_LCM_ERROR);
-    ChangeLcmByIndex(_PAGE_MAINTAIN);
-    system("killall Module_EvComm");
-    system("killall Module_InternalComm");
-    return;
-}
-
-void KillAllTask(void)
-{
-    //ChangeLcmByIndex(_LCM_ERROR);
-    ChangeLcmByIndex(_PAGE_MAINTAIN);
-    system("killall Module_EventLogging");
-    system("killall Module_PrimaryComm");
-    system("killall Module_EvComm");
-    system("killall Module_LcmControl");
-    system("killall Module_InternalComm");
-    system("killall Module_UpdateFW");
-    system("killall Module_ChkSysTask");
-    system("killall Module_DoComm");
-    return ;
-
-}
-
-void StartSystemTimeoutDet(uint8_t flag)
-{
-    if (pSysInfo->SystemTimeoutFlag != flag) {
-        //log_info("Set System Timeout Flag %d", flag);
-        GetClockTime(&pSysInfo->SystemTimeoutTimer, NULL);
-    }
-    pSysInfo->SystemTimeoutFlag = flag;
-}
-
-void StopSystemTimeoutDet(void)
-{
-    GetClockTime(&pSysInfo->SystemTimeoutTimer, NULL);
-    pSysInfo->SystemTimeoutFlag = Timeout_None;
-}
-
-void StartGunInfoTimeoutDet(uint8_t gunIndex, uint8_t flag)
-{
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-
-    if (gunIndex < pSysConfig->TotalConnectorCount) {
-        if (pDcChargingInfo->TimeoutFlag != flag) {
-            GetClockTime(&pDcChargingInfo->ConnectorTimeout, NULL);
-            //log_info("Set Gun%d Timeout Flag %d", gunIndex, flag);
-        }
-        pDcChargingInfo->TimeoutFlag = flag;
-    }
-}
-
-void StopGunInfoTimeoutDet(uint8_t gunIndex)
-{
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-
-    if (gunIndex < pSysConfig->TotalConnectorCount) {
-        pDcChargingInfo->TimeoutFlag = Timeout_None;
-    }
-}
-
-void CheckConnectionTimeout(void)
-{
-    if (ShmSelectGunInfo->RemoteSetup.ConnectionTimeout != 0) { //Jerry add
-        _connectionTimeout = ShmSelectGunInfo->RemoteSetup.ConnectionTimeout;
-    } else {
-        _connectionTimeout = CONN_PLUG_TIMEOUT;
-    }
-    return;
-}
-void _evccidlinktimeout(uint8_t gunIndex)
-{
-    log_info("Getting EVCCID Timeout");
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-    pDcChargingInfo->isEVCCIDVerify = true;
-    StopGunInfoTimeoutDet(gunIndex);
-    destroySelGun(pSysInfo->CurGunSelected);
-    systemPageRestoreInit();
-}
-void CreateTimeoutFork(void)
-{
-    pid_t timeoutPid;
-
-    timeoutPid = fork();
-    if (timeoutPid == 0) {
-        GetClockTime(&_cmdSubPriority_time, NULL);
-        CheckConnectionTimeout();
-
-        //log_info("Timeout Fork Child's PID is %d", getpid());
-
-        while (1) {
-            if ((GetClockTimeoutValue(_cmdSubPriority_time) / 1000) > 5000) {
-                CheckConnectionTimeout();
-                GetClockTime(&_cmdSubPriority_time, NULL);
-            }
-            /*
-            if (pSysInfo->SystemTimeoutFlag != 0)
-            log_info("Timeout ***********SystemTimeoutFlag = %d(%d) ********",pSysInfo->SystemTimeoutFlag,
-                    GetClockTimeoutValue(pSysInfo->SystemTimeoutTimer) / uSEC_VAL);
-            */      
-            // 系統
-            switch (pSysInfo->SystemTimeoutFlag) {
-            case Timeout_SelftestChk:
-                if (GetClockTimeoutValue(pSysInfo->SystemTimeoutTimer) / uSEC_VAL >= SELFTEST_TIMEOUT) {
-                    _SelfTestTimeout();
-                    StopSystemTimeoutDet();
-                    destroySelGun(DESTROY_ALL_SEL); //jerry add
-                }
-                break;
-            case Timeout_ReturnViewPage:
-                if (GetClockTimeoutValue(pSysInfo->SystemTimeoutTimer) / uSEC_VAL >= RETURN_VIEWPAGE_TIMEOUT) {
-                    StopSystemTimeoutDet();
-                    systemPageRestoreInit();
-                }
-            	break;
-            case Timeout_Authorizing:
-                if (GetClockTimeoutValue(pSysInfo->SystemTimeoutTimer) / uSEC_VAL >= AUTHORIZE_TIMEOUT) {
-                    log_error("Authorizing Timeout");
-                    _AuthorizedTimeout();
-                    if (ShmSelectGunInfo->AuthorStateFromCabinet[pSysInfo->CurGunSelected] == YES) { //DoComm no ask cabinet balance
-                        ShmSelectGunInfo->AuthorStateFromCabinet[pSysInfo->CurGunSelected] = NO;
-                        pAlarmCode->AlarmEvents.bits.DisconnectedFromDo = ABNORMAL;
-                        log_error("Author timeout restart DoComm");
-                        system("killall Module_DoComm");
-                    }
-                }
-                break;
-            case Timeout_WaitBalance:
-                if (GetClockTimeoutValue(pSysInfo->SystemTimeoutTimer) / uSEC_VAL >= BALANCE_TIMEOUT) {
-                    log_error("Wait Balance timeout");
-                    _AuthorizedTimeout();
-                    if (ShmSelectGunInfo->AuthorStateFromCabinet[pSysInfo->CurGunSelected] == YES) { //DoComm no ask cabinet balance
-                        ShmSelectGunInfo->AuthorStateFromCabinet[pSysInfo->CurGunSelected] = NO;
-                        pAlarmCode->AlarmEvents.bits.DisconnectedFromDo = ABNORMAL;
-                        log_error("Author timeout restart DoComm");
-                        system("killall Module_DoComm");
-                    }
-                }
-                break;
-            case Timeout_VerifyFail:
-                if (GetClockTimeoutValue(pSysInfo->SystemTimeoutTimer) / uSEC_VAL >= AUTHORIZE_FAIL_TIMEOUT) {
-                    log_info("Timeout_VerifyFail");
-                    StopSystemTimeoutDet();
-                    systemPageRestoreInit();
-                    if (!ShmDcCommonData->pGunInfo[pSysInfo->CurGunSelected].ParkingStatus)
-                        setChargerMode(pSysInfo->CurGunSelected, S_IDLE);
-                    ShmDcCommonData->OperateIDLE[pSysInfo->CurGunSelected] = 1;
-                    ShmDcCommonData->pGunInfo[pSysInfo->CurGunSelected].GetParkingBill = FALSE;
-                }
-                break;
-                /*
-            case Timeout_WaitPlug:
-                if (GetClockTimeoutValue(pSysInfo->SystemTimeoutTimer) / uSEC_VAL >= _connectionTimeout) {
-                    _DetectPlugInTimeout();
-
-                    destroySelGun(pSysInfo->CurGunSelected);
-                }
-                break;
-                */
-/*
-            case Timeout_ReturnToChargingGunDet:
-                if (GetClockTimeoutValue(pSysInfo->SystemTimeoutTimer) / uSEC_VAL >= RETURN_TO_CHARGING_PAGE) {
-                    if (getCurLcmPage() != _LCM_VIEW &&
-                            getCurLcmPage() != _LCM_DETAIL_VIEW ) {
-                        destroySelGun(pSysInfo->CurGunSelected); //jerry add
-
-                    }
-                    DisplayChargingInfo();
-                    StopSystemTimeoutDet();
-                }
-                break;
-*/
-
-
-            case Timeout_ScanCard:
-				if (GetClockTimeoutValue(pSysInfo->SystemTimeoutTimer) / uSEC_VAL >= TCC_SCANCARD_TIMEOUT) {
-                    log_info("Timeout_ScanCard");
-					strcpy((char *)pSysConfig->UserId, "");
-					ClearAuthorizedFlag();
-					StopSystemTimeoutDet();
-                    pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(pSysInfo->CurGunSelected);
-                    pDcChargingInfo->SystemStatus = S_IDLE;
-					pSysInfo->SystemPage = _PAGE_AUTHORIZE_FAIL;
-                    ShmDcCommonData->OperateIDLE[pSysInfo->CurGunSelected] = 1;
-				}
-				break;
-            case Timeout_Terminating:
-                if (GetClockTimeoutValue(pSysInfo->SystemTimeoutTimer) / uSEC_VAL >= TERMINATING_TIMEOUT) {
-                    StopSystemTimeoutDet();
-                    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(pSysInfo->CurGunSelected);
-                    log_info("Terminating timeout");
-                    setChargerMode(pSysInfo->CurGunSelected, S_COMPLETE);
-                }
-                break;
-            case Timeout_AddLine:
-            	if (GetClockTimeoutValue(pSysInfo->SystemTimeoutTimer) / uSEC_VAL >= TCC_ADDLINE_TIMEOUT) {
-                    log_info("Timeout_AddLine");
-            		StopSystemTimeoutDet();
-                    systemPageRestoreInit();
-                    ShmDcCommonData->OperateIDLE[pSysInfo->CurGunSelected] = 1;
-            	}
-            	break;
-
-            case Timeout_DonateComfirm:
-            	if (GetClockTimeoutValue(pSysInfo->SystemTimeoutTimer) / uSEC_VAL >= TCC_DONATECOMFIRM_TIMEOUT) {
-                    log_info("Timeout_DonateComfirm");
-            		StopSystemTimeoutDet();
-                    systemPageRestoreInit();
-            	}
-            	break;
-            case Timeout_SelectPayMode:
-            	if (GetClockTimeoutValue(pSysInfo->SystemTimeoutTimer) / uSEC_VAL >= TCC_SELECTPAY_TIMEOUT) {
-                    log_info("Timeout_SelectPayMode");
-            		StopSystemTimeoutDet();
-                    systemPageRestoreInit();
-                    ShmDcCommonData->OperateIDLE[pSysInfo->CurGunSelected] = 1;
-            	}
-            	break;
-            case Timeout_TradeCancel:
-                if (GetClockTimeoutValue(pSysInfo->SystemTimeoutTimer) / uSEC_VAL >= TCC_TRADECANCEL_TIMEOUT) {
-                    log_info("Timeout_TradeCancel");
-                    StopSystemTimeoutDet();
-                    pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(pSysInfo->CurGunSelected);
-                    setChargerMode(pSysInfo->CurGunSelected, MODE_IDLE);
-                    systemPageRestoreInit();
-                    ShmDcCommonData->OperateIDLE[pSysInfo->CurGunSelected] = 1;
-                    ShmDcCommonData->pGunInfo[pSysInfo->CurGunSelected].GetParkingBill = FALSE;
-                }
-                break;
-            case Timeout_LINEPAYING:
-                if (GetClockTimeoutValue(pSysInfo->SystemTimeoutTimer) / uSEC_VAL >= TCC_LINEPAYING_TIMEOUT) {
-                    log_info("Timeout_LINEPAYING");
-                    StopSystemTimeoutDet();
-                    systemPageRestoreInit();
-                    ShmDcCommonData->OperateIDLE[pSysInfo->CurGunSelected] = 1;
-                }
-                break;
-            }
-
-            // 各槍
-            for (uint8_t gunIndex = 0; gunIndex < pSysConfig->TotalConnectorCount; gunIndex++) {
-                pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-                /*
-                if (pDcChargingInfo->TimeoutFlag != 0)
-                log_info("Timeout ***********GunTimeoutFlag = %d(%d) ********",pDcChargingInfo->TimeoutFlag,
-                        GetClockTimeoutValue(pDcChargingInfo->ConnectorTimeout) / uSEC_VAL);
-                */       
-                switch (pDcChargingInfo->TimeoutFlag) {
-
-                case Timeout_AuthorizingForStop:
-                    if (GetClockTimeoutValue(pDcChargingInfo->ConnectorTimeout) / uSEC_VAL >= AUTHORIZE_STOP_TIMEOUT) {
-                        log_info("Gun %d Timeout_AuthorizingForStop", gunIndex);
-                        strcpy((char*)pSysConfig->UserId, "");
-                        pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(gunIndex);
-                        pDcChargingInfo->SystemStatus = S_IDLE;
-                        ClearAuthorizedFlag();
-                        StopGunInfoTimeoutDet(gunIndex);
-                        if (pSysInfo->CurGunSelected == gunIndex)
-                            systemPageRestoreInit();
-                    }
-                    break;
-                case Timeout_WaitPlug:
-                    if (GetClockTimeoutValue(pDcChargingInfo->ConnectorTimeout) / uSEC_VAL >= _connectionTimeout) {
-                        _DetectPlugInTimeout(gunIndex);
-                        destroySelGun(gunIndex);
-                    }
-                    break;
-                case Timeout_EVCCID_Link:
-                if (GetClockTimeoutValue(pDcChargingInfo->ConnectorTimeout) / uSEC_VAL >= EVCCID_LINK_TIMEOUT) {
-                    _evccidlinktimeout(gunIndex);
-                	}
-                break;
-                case Timeout_LinkError:
-                    if (GetClockTimeoutValue(pDcChargingInfo->ConnectorTimeout) / uSEC_VAL >= LINKERROR_TIMEOUT) {
-                    	_LinkErrorTimeout(gunIndex);
-                    	StopGunInfoTimeoutDet(gunIndex);
-                        destroySelGun(gunIndex);
-                    }
-                	break;
-                case Timeout_Preparing:
-                    if (GetClockTimeoutValue(pDcChargingInfo->ConnectorTimeout) / uSEC_VAL >= GUN_PREPARE_TIMEOUT) {
-                        _PrepareTimeout(gunIndex);
-                        StopGunInfoTimeoutDet(gunIndex);
-                        destroySelGun(gunIndex); //jerry add
-                    }
-                    break;
-
-                case Timeout_EvChargingDet:
-                    if (GetClockTimeoutValue(pDcChargingInfo->ConnectorTimeout) / uSEC_VAL >= GUN_EV_WAIT_TIMEOUT) {
-                        _DetectEvChargingEnableTimeout(gunIndex);
-                        StopGunInfoTimeoutDet(gunIndex);
-                        destroySelGun(gunIndex); //jerry add
-                    }
-                    break;
-
-                case Timeout_EvseChargingDet:
-                    if (GetClockTimeoutValue(pDcChargingInfo->ConnectorTimeout) / uSEC_VAL >= GUN_EVSE_WAIT_TIMEOUT) {
-                        _DetectEvseChargingEnableTimeout(gunIndex);
-                        StopGunInfoTimeoutDet(gunIndex);
-                        destroySelGun(gunIndex); //jerry add
-                    }
-                    break;
-
-                case Timeout_EvseCompleteDet:
-                    if (GetClockTimeoutValue(pDcChargingInfo->ConnectorTimeout) / uSEC_VAL >= GUN_COMP_WAIT_TIMEOUT) {
-                        StopGunInfoTimeoutDet(gunIndex);
-                        destroySelGun(gunIndex); //jerry add
-                    }
-                    break;
-
-                case Timeout_ForCcsPrechargeDet:
-                    if (GetClockTimeoutValue(pDcChargingInfo->ConnectorTimeout) / uSEC_VAL >= GUN_PRECHARGING_TIMEOUT) {
-                        _CcsPrechargeTimeout(gunIndex);
-                        StopGunInfoTimeoutDet(gunIndex);
-                        destroySelGun(gunIndex); //jerry add
-                    }
-                    break;
-                case Timeout_PlugOutGun:
-                    if (GetClockTimeoutValue(pDcChargingInfo->ConnectorTimeout) / uSEC_VAL >= PLUGOUTGUN_TIMEOUT) {
-                        log_info("Gun[%d] Timeout_PlugOutGun",gunIndex);
-                        setChargerMode(gunIndex, MODE_IDLE);
-                        destroySelGun(gunIndex); //Jerry add
-                        StopGunInfoTimeoutDet(gunIndex);
-                        
-                        if (pSysInfo->CurGunSelected == gunIndex)
-                            systemPageRestoreInit();
-                    }
-                    break;
-                case Timeout_FinalCost:
-                	if (GetClockTimeoutValue(pDcChargingInfo->ConnectorTimeout) / uSEC_VAL >= TCC_FINALCOST_TIMEOUT) {
-                        log_info("Gun[%d] Timeout_FinalCost",gunIndex);
-                        StopGunInfoTimeoutDet(gunIndex);
-                		if (ShmDcCommonData->finalcost_flag[gunIndex] == FALSE) {
-                            log_info("Not Get Final Cost");
-                            ShmDcCommonData->PayPass_flag[gunIndex] = FALSE;
-                            if (pSysInfo->CurGunSelected == gunIndex)
-                                pSysInfo->SystemPage = _PAGE_PAYFAIL;
-                		}
-                	}
-                	break;
-                case Timeout_LineReigster:
-                	if (GetClockTimeoutValue(pDcChargingInfo->ConnectorTimeout) / uSEC_VAL >= TCC_LINEREGISTER_TIMEOUT) {
-                        log_info("Gun[%d] Timeout_LineReigster",gunIndex);
-                		StopGunInfoTimeoutDet(gunIndex);
-                        systemPageRestoreInit();
-                		ShmDcCommonData->TransactionInfo[gunIndex].IsDonateInvoice = FALSE;
-                        ShmDcCommonData->OperateIDLE[gunIndex] = 1;
-                	}
-                	break;
-                case Timeout_ParkingBill:
-                	if (GetClockTimeoutValue(pDcChargingInfo->ConnectorTimeout) / uSEC_VAL >= TCC_PARKINGBILL_TIMEOUT) {
-                        log_info("Gun[%d] Timeout_LineReigster",gunIndex);
-                		StopGunInfoTimeoutDet(gunIndex);
-                        systemPageRestoreInit();
-                		ShmDcCommonData->TransactionInfo[gunIndex].IsDonateInvoice = FALSE;
-                        ShmDcCommonData->OperateIDLE[gunIndex] = 1;
-                        ShmDcCommonData->pGunInfo[gunIndex].GetParkingBill = FALSE;
-                	}
-                	break;
-                case Timeout_ExitPage:
-                    if (GetClockTimeoutValue(pDcChargingInfo->ConnectorTimeout) / uSEC_VAL >= TCC_EXITPAGE_TIMEOUT) {
-                        log_info("Gun[%d] Timeout_ExitPage", gunIndex);
-                        StopGunInfoTimeoutDet(gunIndex);
-                        ShmDcCommonData->is_exit[gunIndex] = TRUE;
-                        if (pSysInfo->CurGunSelected == gunIndex)
-                            pSysInfo->SystemPage = _PAGE_EXIT;
-                        StartGunInfoTimeoutDet(gunIndex, Timeout_PlugOutGun);
-                    }
-                    break;
-                case Timeout_CompletPlugout:
-                    if (GetClockTimeoutValue(pDcChargingInfo->ConnectorTimeout) / uSEC_VAL >= TCC_COMPLETE_PLUGOUT_TIMEOUT) {
-                        log_info("Gun[%d] Timeout_CompletePlugout", gunIndex);
-                        setChargerMode(gunIndex, MODE_IDLE);
-                        destroySelGun(gunIndex); //Jerry add
-                        StopGunInfoTimeoutDet(gunIndex);
-                    }
-                    break;
-                case Timeout_WaitParkingInfo:
-                    if (GetClockTimeoutValue(pDcChargingInfo->ConnectorTimeout) / uSEC_VAL >= WAIT_PARKING_INFO_TIMEOUT) {
-                        log_info("Gun[%d] Timeout_WaitParkingInfo", gunIndex);
-                        StopGunInfoTimeoutDet(gunIndex);
-                        systemPageRestoreInit();
-                        ShmDcCommonData->OperateIDLE[gunIndex] = 1;
-                        ShmDcCommonData->pGunInfo[gunIndex].GetParkingBill = FALSE;
-
-                    }
-                    break;
-                case Timeout_ParkingSelect:
-                    if (GetClockTimeoutValue(pDcChargingInfo->ConnectorTimeout) / uSEC_VAL >= TCC_PARK_SELECTPAY_TIMEOUT) {
-                        log_info("Gun[%d] Timeout_ParkingSelect", gunIndex);
-                        StopGunInfoTimeoutDet(gunIndex);
-                        systemPageRestoreInit();
-                        ShmDcCommonData->OperateIDLE[gunIndex] = 1;
-                        ShmDcCommonData->pGunInfo[gunIndex].GetParkingBill = FALSE;
-
-                    }
-                    break;
-                case Timeout_ParkingLeave:
-                    if (GetClockTimeoutValue(pDcChargingInfo->ConnectorTimeout) / uSEC_VAL >= TCC_EXITPAGE_TIMEOUT) {
-                        log_info("Gun[%d] Timeout_ParkingLeave", gunIndex);
-                        StopGunInfoTimeoutDet(gunIndex);
-                        systemPageRestoreInit();
-                        ShmDcCommonData->OperateIDLE[gunIndex] = 1;
-                        ShmDcCommonData->pGunInfo[gunIndex].isParking = FALSE;
-                        ShmDcCommonData->pGunInfo[gunIndex].GetParkingBill = FALSE;
-                    }
-                    break;                    
-                }
-            }
-            sleep(1);
-        }
-    }
-}
-
-void CheckFactoryConfigFunction(void)
-{
-    char Buf[256] = {0};
-
-    if (pSysInfo->FactoryConfiguration) {
-        sprintf(Buf, "cd /root;./FactoryConfig -m %s %s",
-                pSysConfig->ModelName,
-                pSysConfig->SerialNumber);
-        system(Buf);
-
-        system("rm -f /Storage/OCPP/OCPPConfiguration");
-        system("sync");
-        sleep(5);
-        system("reboot -f");
-        sleep(5);
-        system("reboot -f");
-    }
-}
-
-//===============================================
-// Check reservation date is expired
-//===============================================
-int isReservationExpired(uint8_t gunIndex)
-{
-    int result = NO;
-    struct tm expiredDate;
-    struct timeb expiredTime;
-
-    if (sscanf((char *) ShmOCPP16Data->ReserveNow[gunIndex].ExpiryDate,
-               "%4d-%2d-%2dT%2d:%2d:%2d", &expiredDate.tm_year,
-               &expiredDate.tm_mon, &expiredDate.tm_mday, &expiredDate.tm_hour,
-               &expiredDate.tm_min, &expiredDate.tm_sec) == 6) {
-        expiredDate.tm_year -= 1900;
-        expiredDate.tm_mon -= 1;
-
-        expiredTime.time = mktime(&expiredDate);
-        if (!CheckTimeOut(expiredTime)) {
-            result = YES;
-        }
-    }
-
-    return result;
-}
-
-//===============================================
-// OCPP
-//===============================================
-void CheckOcppStatus(void)
-{
-    bool canReset = true;
-    //bool canHardReset = true; //DS60-120 add
-
-    if (ShmOCPP16Data->SpMsg.bits.BootNotificationConf == YES) {
-        ShmOCPP16Data->SpMsg.bits.BootNotificationConf = NO;
-    }
-
-    if (ShmOCPP16Data->MsMsg.bits.ResetReq == YES) {
-        if (pSysWarning->Level != WARN_LV_ER) {
-            for (uint8_t _index = 0; _index < pSysConfig->TotalConnectorCount; _index++) {
-                pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(_index);
-
-                if (pDcChargingInfo->SystemStatus != S_IDLE &&
-                        pDcChargingInfo->SystemStatus != S_RESERVATION &&
-                        pDcChargingInfo->SystemStatus != S_MAINTAIN) {
-                    canReset = false;
-                    if (pDcChargingInfo->SystemStatus >= S_REASSIGN &&
-                            pDcChargingInfo->SystemStatus < S_TERMINATING) {
-                        //canHardReset = false;
-                        ChargingTerminalProcess(_index);
-                        //restartFlag = 1;
-                    }
-                }
-            }
-        }
-
-        if (canReset) {
-            ShmOCPP16Data->MsMsg.bits.ResetReq = NO;
-            sprintf((char *)ShmOCPP16Data->Reset.ResponseStatus, "Accepted");
-            if (strcmp((char *)ShmOCPP16Data->Reset.Type, "Hard") == EQUAL) {
-                log_error("****** Hard Reboot ****** ");
-                ShmOCPP16Data->MsMsg.bits.ResetConf = YES;
-                sleep(3);
-                system("reboot -f");
-            } else if (strcmp((char *)ShmOCPP16Data->Reset.Type, "Soft") == EQUAL) {
-                log_error("****** Soft Reboot ****** ");
-                ShmOCPP16Data->MsMsg.bits.ResetConf = YES;
-                sleep(3);
-                system("killall OcppBackend &");
-                KillAllTask();
-                TryCloseWatchdog();
-                system("/usr/bin/run_evse_restart.sh");
-            }
-        }
-    }
-}
-
-void OcppStopTransation(uint8_t gunIndex)
-{
-    uint8_t _OcppGunIndex = gunIndex;
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-
-    // 如果有 AC 槍,而現在是 DC 第二把槍進入充電
-    if (pSysConfig->AcConnectorCount == 1 && gunIndex == 1) {
-        _OcppGunIndex = 2;
-    }
-
-    if (strcmp((char *)pDcChargingInfo->StartUserId, "") == EQUAL) {
-        strcpy((char *)ShmOCPP16Data->StopTransaction[_OcppGunIndex].IdTag, (char *)ShmOCPP16Data->StopTransaction[_OcppGunIndex].IdTag);
-    } else {
-        strcpy((char *)ShmOCPP16Data->StopTransaction[_OcppGunIndex].IdTag, (char *)pDcChargingInfo->StartUserId);
-    }
-
-    log_info("IdTag = %s ", ShmOCPP16Data->StopTransaction[_OcppGunIndex].IdTag);
-    ShmOCPP16Data->CpMsg.bits[_OcppGunIndex].StopTransactionReq = YES;
-}
-
-bool OcppRemoteStop(uint8_t gunIndex)
-{
-    uint8_t acDirIndex = pSysConfig->AcConnectorCount;
-
-    // 有 AC 槍的話
-    if (acDirIndex > 0 && gunIndex > 0) {
-        gunIndex += acDirIndex;
-    }
-
-    bool result = ShmOCPP16Data->CsMsg.bits[gunIndex].RemoteStopTransactionReq;
-
-    if (ShmOCPP16Data->CsMsg.bits[gunIndex].RemoteStopTransactionReq == YES) {
-        strcpy((char *)ShmOCPP16Data->StopTransaction[gunIndex].StopReason, "Remote");
-        ShmOCPP16Data->CsMsg.bits[gunIndex].RemoteStopTransactionReq = NO;
-    }
-
-    return result;
-}
-
-bool WifiScheduleStop(uint8_t gunIndex)
-{
-    bool result = false;
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-
-    result = pDcChargingInfo->schedule.isTriggerStop;
-    pDcChargingInfo->schedule.isTriggerStop = NO;
-
-    return result;
-}
-
-void OcppRemoteStartChk()
-{
-    if (pSysConfig->OfflinePolicy == _OFFLINE_POLICY_NO_CHARGING) {
-
-    } else {
-        // 如果有 AC 槍,則固定是第 2 把槍,所以索引固定為 1
-        uint8_t acDirIndex = pSysConfig->AcConnectorCount;
-        if (!isDetectPlugin(acDirIndex)) {
-            for (uint8_t ac_index = 0; ac_index < pSysConfig->AcConnectorCount; ac_index++) {
-                pAcChargingInfo = (struct ChargingInfoData*)GetAcChargingInfoData(ac_index);
-
-                if (ShmOCPP16Data->CsMsg.bits[acDirIndex].RemoteStartTransactionReq == YES) {
-                    if (pAcChargingInfo->SystemStatus == S_IDLE ||
-                        pAcChargingInfo->SystemStatus == S_RESERVATION) {
-                        ShmOCPP16Data->CsMsg.bits[acDirIndex].RemoteStartTransactionReq = NO;
-                        pAcChargingInfo->RemoteStartFlag = YES;
-                        pSysInfo->OrderCharging = YES;
-                        //pSysInfo->OrderCharging = DEFAULT_AC_INDEX;
-                        ShmOCPP16Data->CsMsg.bits[pSysConfig->TotalConnectorCount + ac_index].RemoteStartTransactionReq = NO;
-                        DetectPluginStart(acDirIndex);
-                        return;
-                    }
-                    ShmOCPP16Data->CsMsg.bits[acDirIndex].RemoteStartTransactionReq = NO;
-                }
-            }
-        }
-        //uint8_t threeGunIndex = 0;
-        //uint8_t dcIndex = 0;
-        //bool isGunUsingStatus = false;
-
-        for (uint8_t _index = 0; _index < pSysConfig->TotalConnectorCount; _index++) {
-            pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(_index);
-            /*
-            // 如果有 AC 槍,且 DC 槍也有兩把
-            if (acDirIndex == 1 && _index == 1) {
-                threeGunIndex = 1;
-            }
-
-            if (ShmOCPP16Data->CsMsg.bits[_index + threeGunIndex].RemoteStartTransactionReq == YES) {
-                dcIndex = _index;
-            }
-
-            if (pDcChargingInfo->SystemStatus != S_IDLE) {
-                isGunUsingStatus = true;
-            }
-            if (pDcChargingInfo->RemoteStartFlag == YES) {
-                //_remotestarting = true;
-            }
-        }
-
-        // 如果是雙槍單模,只認閒置狀態的槍,如果有預約~ 則預約也算被使用
-        if (isGunUsingStatus && pSysInfo->IsAlternatvieConf) {
-            if (dcIndex == 0) {
-                threeGunIndex = 0;
-            }
-
-            ShmOCPP16Data->CsMsg.bits[dcIndex + threeGunIndex].RemoteStartTransactionReq = NO;
-            return;
-        }
-
-        if (dcIndex == 0) {
-            threeGunIndex = 0;
-        }
-        */
-            pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(_index);
-
-            if (ShmOCPP16Data->CsMsg.bits[_index].RemoteStartTransactionReq == YES &&
-                !isDetectPlugin(_index)) {
-                if (pDcChargingInfo->SystemStatus == S_IDLE ||
-                    pDcChargingInfo->SystemStatus == S_RESERVATION) {
-
-                    pDcChargingInfo->RemoteStartFlag = YES;
-                    ShmDcCommonData->is_RemoteStart[_index] = TRUE;
-                    //pSysInfo->OrderCharging = YES;
-                    //pDcChargingInfo->SystemStatus = S_AUTHORIZING;
-                    //pSysInfo->OrderCharging = gunIndex;
-                    ShmOCPP16Data->CsMsg.bits[_index].RemoteStartTransactionReq = NO;
-                    DetectPluginStart(_index);
-                    setSelGunWaitToAuthor(_index);
-                    log_info("Ocpp Remote Start Gun%d Pass", _index);
-                }
-                ShmOCPP16Data->CsMsg.bits[_index].RemoteStartTransactionReq = NO;
-            }
-        }
-    }
-}
-
-void ChkOcppStatus(uint8_t gunIndex)
-{
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-
-    if (pDcChargingInfo->SystemStatus == S_IDLE &&
-            ShmOCPP16Data->CsMsg.bits[gunIndex].ReserveNowReq == YES) {
-        ShmOCPP16Data->CsMsg.bits[gunIndex].ReserveNowReq = NO;
-        if (isReservationExpired(gunIndex)) {
-            log_error("***************ChkOcppStatus : OcppReservedStatus******************** ");
-            pDcChargingInfo->ReservationId = ShmOCPP16Data->ReserveNow[gunIndex].ReservationId;
-            pDcChargingInfo->SystemStatus = S_RESERVATION;
-        }
-        ShmOCPP16Data->CsMsg.bits[gunIndex].ReserveNowConf = YES;
-    }
-
-    if (pDcChargingInfo->SystemStatus == S_RESERVATION &&
-            ShmOCPP16Data->CsMsg.bits[gunIndex].CancelReservationReq == YES) {
-        ShmOCPP16Data->CsMsg.bits[gunIndex].CancelReservationReq = NO;
-        if (isReservationExpired(gunIndex)) {
-            log_error("***************ChkOcppStatus : Cancel OcppReservedStatus******************** ");
-            pDcChargingInfo->ReservationId = 0;
-            pDcChargingInfo->SystemStatus = S_IDLE;
-        }
-        ShmOCPP16Data->CsMsg.bits[gunIndex].CancelReservationConf = YES;
-    }
-
-    if (ShmOCPP16Data->CsMsg.bits[gunIndex].ChangeAvailabilityReq == YES) {
-        log_error("***************ChkOcppStatus : OcppChangeAvailability******************** ");
-        ShmOCPP16Data->CsMsg.bits[gunIndex].ChangeAvailabilityReq = NO;
-        if (strcmp((char *)ShmOCPP16Data->ChangeAvailability[gunIndex].Type, "Operative") == EQUAL) {
-            if (isDb_ready) {
-                DB_Update_Operactive(gunIndex, true);
-            }
-
-            pDcChargingInfo->IsAvailable = YES;
-            if (pDcChargingInfo->SystemStatus == S_IDLE ||
-                    pDcChargingInfo->SystemStatus == S_RESERVATION ||
-                    pDcChargingInfo->SystemStatus == S_MAINTAIN) {
-                setChargerMode(gunIndex, MODE_IDLE);
-            }
-        } else if (strcmp((char *)ShmOCPP16Data->ChangeAvailability[gunIndex].Type, "Inoperative") == EQUAL) {
-            if (isDb_ready) {
-                DB_Update_Operactive(gunIndex, false);
-            }
-
-            pDcChargingInfo->IsAvailable = NO;
-            if (pDcChargingInfo->SystemStatus == S_IDLE ||
-                    pDcChargingInfo->SystemStatus == S_RESERVATION ||
-                    pDcChargingInfo->SystemStatus == S_MAINTAIN) {
-                setChargerMode(gunIndex, MODE_MAINTAIN);
-            }
-        }
-    }
-
-    if (ShmOCPP16Data->CsMsg.bits[gunIndex].UnlockConnectorReq == YES) {
-        ShmOCPP16Data->CsMsg.bits[gunIndex].UnlockConnectorReq = NO;
-        if (pDcChargingInfo->SystemStatus >= S_REASSIGN_CHECK && // DS60-120 add ||
-                pDcChargingInfo->SystemStatus <= S_CHARGING) {
-            // 充電中,需停止充電
-            strcpy((char *)ShmOCPP16Data->StopTransaction[gunIndex].StopReason, "UnlockCommand");
-            ChargingTerminalProcess(gunIndex);
-        }
-        strcpy((char *)ShmOCPP16Data->UnlockConnector[gunIndex].ResponseStatus, "Unlocked");
-        ShmOCPP16Data->CsMsg.bits[gunIndex].UnlockConnectorConf = YES;
-    }
-}
-
-bool CheckBackendChargingTimeout(uint8_t gunIndex)
-{
-    bool result = false;
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-
-    if (pSysConfig->AuthorisationMode == AUTH_MODE_ENABLE) {
-        if (pSysConfig->MaxChargingDuration > 0) {
-            if (pDcChargingInfo->PresentChargedDuration > (pSysConfig->MaxChargingDuration * 60)) {
-                result = true;
-            }
-        }
-    }
-
-    return result;
-}
-
-bool CheckBackendChargingEnergy(uint8_t gunIndex)
-{
-    bool result = false;
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-
-    if (pSysConfig->AuthorisationMode == AUTH_MODE_ENABLE) {
-        if (pSysConfig->MaxChargingEnergy > 0) {
-            if (pDcChargingInfo->PresentChargedEnergy > pSysConfig->MaxChargingEnergy) {
-                result = true;
-            }
-        }
-    }
-
-    return result;
-}
-
-void InformOcppErrOccur(uint8_t codeType)
-{
-    char _error[25];
-
-    switch (codeType) {
-    case 4:
-        strcpy(_error, "InternalError");
-        break;
-
-    case 6:
-        strcpy(_error, "NoError");
-        break;
-
-    case 7:
-        strcpy(_error, "OtherError");
-        break;
-
-    case 13:
-        strcpy(_error, "UnderVoltage");
-        break;
-
-    case 14:
-        strcpy(_error, "OverVoltage");
-        break;
-    }
-
-    for (uint8_t gunIndex = 0; gunIndex < pSysConfig->TotalConnectorCount; gunIndex++) {
-        strcpy((char *)ShmOCPP16Data->StatusNotification[gunIndex].ErrorCode, _error);
-    }
-}
-
-//===============================================
-// Config process
-//===============================================
-/*
-void AddPlugInTimes(uint8_t gunIndex)
-{
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-
-    if (pDcChargingInfo->Type == _Type_Chademo) {
-        pSysConfig->ChademoPlugInTimes += 1;
-    } else if (pDcChargingInfo->Type == _Type_CCS_2) {
-        pSysConfig->Ccs2PlugInTimes += 1;
-    } else if (pDcChargingInfo->Type == _Type_GB) {
-        pSysConfig->GbPlugInTimes += 1;
-    }
-}*/
-
-void ChangeStartOrStopDateTime(uint8_t isStart, uint8_t gunIndex)
-{
-    char cmdBuf[32];
-    struct timeb csuTime;
-    struct tm *tmCSU;
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-
-    ftime(&csuTime);
-    tmCSU = localtime(&csuTime.time);
-
-    sprintf(cmdBuf, "%04d-%02d-%02d %02d:%02d:%02d", tmCSU->tm_year + 1900,
-            tmCSU->tm_mon + 1, tmCSU->tm_mday, tmCSU->tm_hour, tmCSU->tm_min,
-            tmCSU->tm_sec);
-    if (isStart) {
-        strcpy((char *)pDcChargingInfo->StartDateTime, cmdBuf);
-    } else {
-        strcpy((char *)pDcChargingInfo->StopDateTime, cmdBuf);
-    }
-}
-
-void ChangeGunSelectByIndex(uint8_t sel)
-{
-    pSysInfo->CurGunSelected = sel;
-    pSysInfo->CurGunSelectedByAc = NO_DEFINE;
-}
-
-void CheckIsAlternatvieByModelName()
-{
-    if (pSysConfig->ModelName[1] == 'W') { //DS60-120
-        // 壁掛
-        pSysInfo->IsAlternatvieConf = YES;
-    } else {
-        pSysInfo->IsAlternatvieConf = NO;
-    }
-}
-
-void StopProcessingLoop()
-{
-    log_info("Stop Processing....");
-    for (;;) {
-        CheckFactoryConfigFunction();
-        //CheckFwUpdateFunction();
-        if (pSysWarning->Level == WARN_LV_ER) {
-            ChkPrimaryStatus();
-            if (pSysWarning->Level == WARN_LV_NL) {
-                log_info("Soft reboot for retry self-tets (Primary). ");
-                KillAllTask();
-                sleep(3);
-                TryCloseWatchdog();
-                system("/usr/bin/run_evse_restart.sh");
-                return;
-            }
-        }
-        sleep(1);
-        TryFeedWatchdog();
-    }
-}
-
-bool IsConnectorWholeIdle()
-{
-    bool result = true;
-
-    for (uint8_t count = 0; count < pSysConfig->TotalConnectorCount; count++) {
-        pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(count);
-
-        if (pDcChargingInfo->SystemStatus != S_IDLE &&
-                pDcChargingInfo->SystemStatus != S_RESERVATION) {
-            result = false;
-            break;
-        }
-    }
-
-    for (uint8_t count = 0; count < pSysConfig->AcConnectorCount; count++) {
-        pAcChargingInfo = (struct ChargingInfoData *)GetAcChargingInfoData(count);
-
-        if (pAcChargingInfo->SystemStatus != S_IDLE &&
-                pAcChargingInfo->IsErrorOccur == NO) {
-            result = false;
-            break;
-        }
-    }
-
-    return result;
-}
-
-void ClearAlarmCodeWhenAcOff()
-{
-    if (!pSysInfo->AcContactorStatus) {
-        pAlarmCode->AlarmEvents.bits.PsuNoResource = NO;
-    }
-}
-
-//==========================================
-// Check Smart Charging Profile
-//==========================================
-int GetStartScheduleTime(uint8_t *time)
-{
-    int result = -1;
-    struct tm tmScheduleStart;
-    struct timeb tbScheduleStart;
-
-    if ((sscanf((char *)time, "%4d-%2d-%2dT%2d:%2d:%2d", &tmScheduleStart.tm_year, &tmScheduleStart.tm_mon, &tmScheduleStart.tm_mday, &tmScheduleStart.tm_hour, &tmScheduleStart.tm_min, &tmScheduleStart.tm_sec) == 6)) {
-        tmScheduleStart.tm_year -= 1900;
-        tmScheduleStart.tm_mon -= 1;
-        tbScheduleStart.time = mktime(&tmScheduleStart);
-        tbScheduleStart.millitm = 0;
-
-        result = DiffTimebWithNow(tbScheduleStart) / 1000;
-    }
-
-    return result;
-}
-
-void CheckSmartChargeProfile(uint8_t _index)
-{
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(_index);
-
-    if (ShmOCPP16Data->CSUMsg.bits[_index].ChargingProfileConf == YES) {
-        // Get Charging Profile
-        ShmOCPP16Data->CSUMsg.bits[_index].ChargingProfileConf = NO;
-        if (strcmp((char *)ShmOCPP16Data->SmartChargingProfile[_index].ChargingProfileKind, "Absolute") == EQUAL &&
-                ShmOCPP16Data->SmartChargingProfile[_index].ChargingProfileId == YES //DS60-120 add
-           ) {
-            int _time = GetStartScheduleTime(ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.StartSchedule);
-            uint8_t _startCount = NO_DEFINE;
-            uint8_t _maxCount = ARRAY_SIZE(ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.ChargingSchedulePeriod);
-
-            for (uint8_t _count = 0; _count < _maxCount; _count++) {
-                // 預設最小輸出電流 (MIN_OUTPUT_CUR) A
-                if (_time >= ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.ChargingSchedulePeriod[_count].StartPeriod) {
-                    if ((_count == 0 && ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.ChargingSchedulePeriod[_count].Limit >= MIN_OUTPUT_CUR) ||
-                            ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.ChargingSchedulePeriod[_count].Limit > MIN_OUTPUT_CUR) {
-                        _startCount = _count;
-                    }
-                }
-            }
-
-            log_info("_startCount = %d ", _startCount);
-            if (_startCount < _maxCount) {
-                //DS60-120 add
-                log_info("Profile Limit = %f ", ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.ChargingSchedulePeriod[_startCount].Limit);
-                pDcChargingInfo->ChargingProfilePower = ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.ChargingSchedulePeriod[_startCount].Limit * AC_OUTPUT_VOL;
-                if (pDcChargingInfo->EvBatterytargetVoltage > 0 && pDcChargingInfo->PresentChargingVoltage > 0) {
-                    pDcChargingInfo->ChargingProfileCurrent = (pDcChargingInfo->ChargingProfilePower / pDcChargingInfo->PresentChargingVoltage) * 10;
-                } else {
-                    pDcChargingInfo->ChargingProfileCurrent = 0;
-                }
-            } else {
-                pDcChargingInfo->ChargingProfilePower = -1;
-                pDcChargingInfo->ChargingProfileCurrent = -1;
-            }
-        } else {
-            pDcChargingInfo->ChargingProfilePower = -1;
-            pDcChargingInfo->ChargingProfileCurrent = -1;
-        }
-
-        log_info("ChargingProfilePower = %f ", pDcChargingInfo->ChargingProfilePower);
-        log_info("ChargingProfileCurrent = %f ", pDcChargingInfo->ChargingProfileCurrent);
-    }
-}
-
-void ChargingProfileFlat(uint8_t _index)
-{
-    if (ShmOCPP16Data->CSUMsg.bits[_index].ChargingProfileConf == NO) {
-        if (ShmOCPP16Data->CSUMsg.bits[_index].ChargingProfileReq == NO) {
-            ShmOCPP16Data->CSUMsg.bits[_index].ChargingProfileReq = YES;
-        }
-    }
-}
-/*
-void CheckReturnToChargingConn()
-{
-    if ((pSysConfig->TotalConnectorCount + pSysConfig->AcConnectorCount) > 1 &&
-            pSysInfo->PageIndex != _LCM_START_AUTHORIZING &&
-            pSysInfo->PageIndex != _LCM_START_AUTHORIZE_FAIL &&
-            pSysInfo->PageIndex != _LCM_WAIT_PLUGIN) {
-        bool isReturnTimeout = false;
-
-        for (uint8_t count = 0; count < pSysConfig->TotalConnectorCount; count++) {
-            pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(count);
-
-            // 如果選的 DC 槍在充電~ 則 DC 槍不改變
-            if (count == pSysInfo->CurGunSelected) {
-                if ((pDcChargingInfo->SystemStatus >= S_REASSIGN_CHECK &&
-                        pDcChargingInfo->SystemStatus <= S_COMPLETE) ||
-                        (pDcChargingInfo->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
-                         pDcChargingInfo->SystemStatus <= S_CCS_PRECHARGE_ST1)
-                   ) {
-                    isReturnTimeout = false;
-                    break;
-                }
-            } else if (count != pSysInfo->CurGunSelected) {
-                if ((pDcChargingInfo->SystemStatus >= S_REASSIGN_CHECK &&
-                        pDcChargingInfo->SystemStatus <= S_COMPLETE) ||
-                        (pDcChargingInfo->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
-                         pDcChargingInfo->SystemStatus <= S_CCS_PRECHARGE_ST1)
-                   ) {
-                    isReturnTimeout = true;
-                    StartSystemTimeoutDet(Timeout_ReturnToChargingGunDet);
-                }
-            }
-        }
-
-        // AC 槍
-        if (!isReturnTimeout && pSysConfig->AcConnectorCount > 0) {
-            pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(pSysInfo->CurGunSelected);
-            pAcChargingInfo = (struct ChargingInfoData *)GetAcChargingInfoData(0);
-
-            // 沒有選中 AC,且 AC 在充電中
-            if (pSysInfo->CurGunSelectedByAc == NO_DEFINE &&
-                    (pAcChargingInfo->SystemStatus >= S_PREPARNING &&
-                     pAcChargingInfo->SystemStatus <= S_COMPLETE)) {
-                // 當前 DC 充電槍在 idle 狀態
-                if (pDcChargingInfo->SystemStatus == S_IDLE ||
-                        pDcChargingInfo->SystemStatus == S_RESERVATION) {
-                    isReturnTimeout = true;
-                    StartSystemTimeoutDet(Timeout_ReturnToChargingGunDet);
-                }
-            } else if (pSysInfo->CurGunSelectedByAc == DEFAULT_AC_INDEX &&
-                       ((pDcChargingInfo->SystemStatus >= S_REASSIGN_CHECK &&
-                         pDcChargingInfo->SystemStatus <= S_COMPLETE) ||
-                        (pDcChargingInfo->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
-                         pDcChargingInfo->SystemStatus <= S_CCS_PRECHARGE_ST1))) {
-                // 當前 DC 充電槍在 idle 狀態
-                if (pAcChargingInfo->SystemStatus == S_IDLE ||
-                        pAcChargingInfo->SystemStatus == S_RESERVATION) {
-                    isReturnTimeout = true;
-                    StartSystemTimeoutDet(Timeout_ReturnToChargingGunDet);
-                }
-            }
-        }
-
-        if (!isReturnTimeout) {
-            StopSystemTimeoutDet();
-        }
-    }
-}
-
-bool GetStartChargingByAlterMode(uint8_t _gun)
-{
-    bool result = true;
-
-    if (pSysConfig->TotalConnectorCount == 2 &&
-            pSysInfo->IsAlternatvieConf == YES) {
-        for (uint8_t _select = 0; _select < pSysConfig->TotalConnectorCount; _select++) {
-            pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(_select);
-
-            if (_select != _gun) {
-                if (pDcChargingInfo->SystemStatus != S_IDLE &&
-                        pDcChargingInfo->SystemStatus != S_RESERVATION) {
-                    result = false;
-                    break;
-                }
-            }
-        }
-    }
-
-    return result;
-}
-*/
-void TheEndCharging(uint8_t gunIndex)
-{
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-
-    ftime(&endChargingTime[gunIndex]);
-
-    if (pDcChargingInfo->PresentChargedDuration != 0) {
-        pDcChargingInfo->PresentChargedDuration = DiffTimeb(startChargingTime[gunIndex], endChargingTime[gunIndex]);
-    }
-
-    pDcChargingInfo->isRemoteStart = NO;
-    if (pDcChargingInfo->TimeoutFlag != Timeout_FinalCost)
-        StopGunInfoTimeoutDet(gunIndex);
-    //StartGunInfoTimeoutDet(gunIndex, Timeout_EvseCompleteDet);
-    ChangeStartOrStopDateTime(NO, gunIndex);
-    DB_Insert_Record(gunIndex);
-}
-
-void UpdateErrorCodeToOcpp(uint8_t index)
-{
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);
-
-    //log_info("%d = ConnectorAlarmCode = %s", index, pDcChargingInfo->ConnectorAlarmCode);
-    //log_info("%d = EvConnAlarmCode = %s", index, pDcChargingInfo->EvConnAlarmCode);
-    if (strcmp((char *)pDcChargingInfo->ConnectorAlarmCode, "") != EQUAL) {
-        //if (strlen((char *)pDcChargingInfo->ConnectorAlarmCode) == EQUAL) {
-        strcpy((char *)ShmOCPP16Data->StatusNotification[index].ErrorCode, "InternalError");
-        strcpy((char *)ShmOCPP16Data->StatusNotification[index].VendorErrorCode, (char *)pDcChargingInfo->ConnectorAlarmCode);
-    } else if (strcmp((char *)pDcChargingInfo->EvConnAlarmCode, "") != EQUAL) {
-        //} else if (strlen((char *)pDcChargingInfo->EvConnAlarmCode) == EQUAL) {
-        strcpy((char *)ShmOCPP16Data->StatusNotification[index].ErrorCode, "OtherError");
-        strcpy((char *)ShmOCPP16Data->StatusNotification[index].VendorErrorCode, (char *)pDcChargingInfo->EvConnAlarmCode);
-    }
-
-    //log_info("Gun %d = VendorErrorCode = %s", index, (char *)ShmOCPP16Data->StatusNotification[index].VendorErrorCode);
-}
-
-void AdjustChargerCurrent()
-{
-    pSysConfig->RatingCurrent = ShmPsuData->SystemAvailableCurrent / 10;
-
-    // 設定的電流~ 如超過可輸出的電流,則 bypass
-    if (pSysConfig->RatingCurrent < pSysConfig->MaxChargingCurrent ||
-            pSysConfig->RatingCurrent == 0) {
-        pSysConfig->MaxChargingCurrent = 0;
-    }
-
-    log_info("PSU : MaxChargingPower = %d, MaxChargingCurrent = %d",
-             ShmPsuData->SystemAvailablePower / 10,
-             ShmPsuData->SystemAvailableCurrent / 10
-            );
-
-    log_info("Config : ChargingPower = %d, ChargingCurrent = %d",
-             pSysConfig->MaxChargingPower,
-             pSysConfig->MaxChargingCurrent
-            );
-}
-
-void ResetDetAlarmStatus(uint8_t gun)
-{
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gun);
-
-    if (pDcChargingInfo->Type == _Type_Chademo) {
-        if (pAlarmCode->AlarmEvents.bits.SystemChademoOutputOVP == YES) {
-            pAlarmCode->AlarmEvents.bits.SystemChademoOutputOVP = NO;
-        }
-    } else if (pDcChargingInfo->Type == _Type_GB) {
-        if (pAlarmCode->AlarmEvents.bits.SystemGbOutputOVP == YES) {
-            pAlarmCode->AlarmEvents.bits.SystemGbOutputOVP = NO;
-        }
-    } else if (pDcChargingInfo->Type == _Type_CCS_2) {
-        if (pAlarmCode->AlarmEvents.bits.SystemCcsOutputOVP == YES) {
-            pAlarmCode->AlarmEvents.bits.SystemCcsOutputOVP = NO;
-        }
-    }
-}
-
-static void autoStartCharging(uint8_t gunIndex)
-{
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-
-    if ( (pSysInfo->SystemPage >= _PAGE_AUTHORIZE && pSysInfo->SystemPage <= _PAGE_SENSING) ||
-        (pDcChargingInfo->isEVCCIDVerify && strcmp( (char *)pSysConfig->UserId , "" ) != EQUAL)) {
-            return;
-    }
-
-    if ((pDcChargingInfo->ConnectorPlugIn == YES) &&
-            (pDcChargingInfo->SystemStatus == S_IDLE ) 
-       ) {
-        if(!pSysConfig->AuthorisationMode) {
-            /*
-            if (pSysConfig->isAuthrizeByEVCCID && !pDcChargingInfo->isEVCCIDVerify &&
-                    pDcChargingInfo->Type == _Type_CCS_2)  {
-                // LCM show linking pic. & timeout 2 min
-                if( pSysInfo->CurGunSelected == gunIndex ) {
-                    systemPageRestoreInit();
-                    pSysInfo->SystemPage = _LCM_PRECHARGE;
-                }
-                StartGunInfoTimeoutDet(gunIndex,Timeout_EVCCID_Link);
-                // Getting EVCCID
-                if( strcmp( (char *)pDcChargingInfo->EVCCID, "" ) != EQUAL ) {
-                    log_info("Authorizing EVCCID");
-                    StopSystemTimeoutDet();
-                    strcpy((char *)pSysConfig->UserId, (char *)pDcChargingInfo->EVCCID);
-                    ChangeGunSelectByIndex(gunIndex);
-                    confirmSelGun(gunIndex);
-                    pDcChargingInfo->isEVCCIDVerify = true;
-                    pSysInfo->SystemPage = _LCM_START_AUTHORIZING;
-                    log_info("Get User(%d) ID:%s",gunIndex,pSysConfig->UserId);
-                    setChargerMode(gunIndex, MODE_AUTHORIZING);
-                }
-            } else
-                return;
-                */
-        } else {
-            strcpy((char *)&pSysConfig->UserId, "AutoStartCharging");
-            ChangeGunSelectByIndex(gunIndex);
-            confirmSelGun(gunIndex);
-            ShmDcCommonData->TradeCancel = FALSE;
-            ShmDcCommonData->is_AutoStart[gunIndex] = TRUE;
-            pSysInfo->SystemPage = _PAGE_SENSING;
-            ShmDcCommonData->AuthPass_flag[gunIndex] = TRUE;
-            //setChargerMode(gunIndex, MODE_AUTHORIZING);
-            log_info("Get User(%d) ID:%s",gunIndex,pSysConfig->UserId);
-            sleep(1);   //讓其他task有時間執行
-        }
-    }
-}
-
-static bool PrecheckIsPass(uint8_t gunIndex)
-{
-    bool result = true;
-
-    // relay welding or driving 是反向
-    result = !ShmDcCommonData->GunRelayWeldingOccur[gunIndex];
-
-    return result;
-}
-
-static void ReviewCriticalAlarm(void)
-{
-    if (
-            pAlarmCode->AlarmEvents.bits.EmergencyStopTrip == YES ||
-            pAlarmCode->AlarmEvents.bits.MainPowerBreakerTrip == YES ||
-            pAlarmCode->AlarmEvents.bits.DoorOpen == YES ||
-            pSysWarning->ExtraErrProcess != _EXTRA_ERR_PROCESS_NONE ||
-            pAlarmCode->AlarmEvents.bits.PsuFailureAlarm == YES ||
-            pAlarmCode->AlarmEvents.bits.DisconnectedFromDo == YES ||
-            //Power cabinet alarm status
-            ShmDcCommonData->PowerAlarmState.StatusBit.EmergencyStop == YES ||
-            ShmDcCommonData->PowerAlarmState.StatusBit.DoorOpen == YES ||
-            ShmDcCommonData->PowerAlarmState.StatusBit.DcInputOVP == YES ||
-			ShmDcCommonData->PowerAlarmState.StatusBit.DcInputUVP == YES ||
-            ShmDcCommonData->PowerAlarmState.StatusBit.SystemL1InputOVP == YES ||
-            ShmDcCommonData->PowerAlarmState.StatusBit.SystemL2InputOVP == YES ||
-            ShmDcCommonData->PowerAlarmState.StatusBit.SystemL3InputOVP == YES ||
-            ShmDcCommonData->PowerAlarmState.StatusBit.PsuFailure == YES ) {
-        pSysWarning->Level = WARN_LV_ER;
-    } else {
-        if (ShmSelectGunInfo->EthDevStatus.Backend == 0 ||
-            ShmSelectGunInfo->EthDevStatus.Backend == 2 ) {
-            pInfoCode->InfoEvents.bits.BackendDisconnectedViaEthernet = TRUE;
-            if (ShmDcCommonData->DebugFlag || pSysConfig->AuthorisationMode) {
-                pSysWarning->Level = WARN_LV_NL;
-            } else {
-                pSysWarning->Level = WARN_LV_ER;
-
-                return;
-            }
-        } else if (ShmSelectGunInfo->EthDevStatus.Backend == 1) {
-            pInfoCode->InfoEvents.bits.BackendDisconnectedViaEthernet = FALSE;
-        }
-        
-        pSysWarning->Level = WARN_LV_NL;
-    }
-
-}
-
-static void CheckRelayWeldingOrDrivingFault(uint8_t gunIndex)
-{
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-
-    // relay welding fault then stop the charging process.
-    uint8_t faultCode = RELAY_STATUS_ERROR_NONE;
-    //static uint8_t drivingCount = 0;
-
-    if (gunIndex == 0) {
-        if (ShmDcCommonData->CheckRelayStatus[RELAY_SMR1_P_STATUS] == RELAY_STATUS_ERROR_WELDING ||
-                ShmDcCommonData->CheckRelayStatus[RELAY_SMR1_N_STATUS] == RELAY_STATUS_ERROR_WELDING) {
-            faultCode = RELAY_STATUS_ERROR_WELDING;
-        } else if (ShmDcCommonData->CheckRelayStatus[RELAY_SMR1_P_STATUS] == RELAY_STATUS_ERROR_DRIVING ||
-                   ShmDcCommonData->CheckRelayStatus[RELAY_SMR1_N_STATUS] == RELAY_STATUS_ERROR_DRIVING) {
-            faultCode = RELAY_STATUS_ERROR_DRIVING;
-        }
-    } else if (gunIndex == 1) {
-        if (ShmDcCommonData->CheckRelayStatus[RELAY_SMR2_P_STATUS] == RELAY_STATUS_ERROR_WELDING ||
-                ShmDcCommonData->CheckRelayStatus[RELAY_SMR2_N_STATUS] == RELAY_STATUS_ERROR_WELDING) {
-            faultCode = RELAY_STATUS_ERROR_WELDING;
-        } else if (ShmDcCommonData->CheckRelayStatus[RELAY_SMR2_P_STATUS] == RELAY_STATUS_ERROR_DRIVING ||
-                   ShmDcCommonData->CheckRelayStatus[RELAY_SMR2_N_STATUS] == RELAY_STATUS_ERROR_DRIVING) {
-            faultCode = RELAY_STATUS_ERROR_DRIVING;
-        }
-    }
-
-    if (pSysConfig->TotalConnectorCount >= 2 &&
-            !pSysInfo->IsAlternatvieConf) {
-        // 橋接
-        if (ShmDcCommonData->CheckRelayStatus[RELAY_PARA_P_STATUS] == RELAY_STATUS_ERROR_WELDING ||
-                ShmDcCommonData->CheckRelayStatus[RELAY_PARA_N_STATUS] == RELAY_STATUS_ERROR_WELDING) {
-            faultCode = RELAY_STATUS_ERROR_WELDING;
-        } else if (ShmDcCommonData->CheckRelayStatus[RELAY_PARA_P_STATUS] == RELAY_STATUS_ERROR_DRIVING ||
-                   ShmDcCommonData->CheckRelayStatus[RELAY_PARA_N_STATUS] == RELAY_STATUS_ERROR_DRIVING) {
-            faultCode = RELAY_STATUS_ERROR_DRIVING;
-        }
-    }
-
-    if (faultCode == RELAY_STATUS_ERROR_WELDING) {
-        // welding
-        if (pDcChargingInfo->Type == _Type_Chademo) {
-            RecordAlarmCode(gunIndex, "011011");
-            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaRelayWeldingFault = YES;
-        } else if (pDcChargingInfo->Type == _Type_GB) {
-            RecordAlarmCode(gunIndex, "011015");
-            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTRelayWeldingFault = YES;
-        } else if (pDcChargingInfo->Type == _Type_CCS_2) {
-            RecordAlarmCode(gunIndex, "011013");
-            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSRelayWeldingFault = YES;
-        }
-
-        ShmDcCommonData->GunRelayWeldingOccur[gunIndex] = YES;
-        //EmcOccureByString("");
-    } else if (faultCode == RELAY_STATUS_ERROR_DRIVING) {
-        //if (drivingCount++ != 2) {
-        //    return;
-        //}
-
-        // driving
-        if (pDcChargingInfo->Type == _Type_Chademo) {
-            RecordAlarmCode(gunIndex, "011012");
-            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaRelayDrivingFault = YES;
-        } else if (pDcChargingInfo->Type == _Type_GB) {
-            RecordAlarmCode(gunIndex, "011016");
-            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTRelayDrivingFault = YES;
-        } else if (pDcChargingInfo->Type == _Type_CCS_2) {
-            RecordAlarmCode(gunIndex, "011014");
-            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSRelayDrivingFault = YES;
-        }
-
-        ShmDcCommonData->GunRelayDrivingOccur[gunIndex] = YES;
-        //EmcOccureByString("");
-    } else {
-        ShmDcCommonData->GunRelayWeldingOccur[gunIndex] = NO;
-        ShmDcCommonData->GunRelayDrivingOccur[gunIndex] = NO;
-        //drivingCount = 0;
-    }
-}
-
-static void isChargingAverageState(void)
-{
-    if (pSysInfo->MainChargingMode != _MAIN_CHARGING_MODE_AVER) {
-        pSysInfo->ReAssignedFlag = _REASSIGNED_NONE;
-        return;
-    }
-
-    // 均充 -> 最大充
-    if (pSysInfo->BridgeRelayStatus == NO) {
-        if (pSysInfo->ReAssignedFlag == _REASSIGNED_NONE) {
-            log_info("=============Smart Charging============= Step 11 ");
-            pSysInfo->ReAssignedFlag = _REASSIGNED_PREPARE_A_TO_M;
-        }
-    } else if (pSysInfo->ReAssignedFlag != _REASSIGNED_COMP &&
-               pSysInfo->ReAssignedFlag != _REASSIGNED_WAITING) {
-        log_info("=============Smart Charging============= Step 14 ");
-        pSysInfo->ReAssignedFlag = _REASSIGNED_WAITING;
-    } else if (pSysInfo->ReAssignedFlag == _REASSIGNED_COMP) {
-        pSysInfo->MainChargingMode = _MAIN_CHARGING_MODE_MAX;
-        pSysInfo->ReAssignedFlag = _REASSIGNED_NONE;
-    }
-}
-
-bool Taskconutstring(char *src, char *taskname)
-{
-    bool result = false;
-
-    if (src == NULL || strlen(src) == 0)
-        return result;
-
-    if (strstr(src, taskname) != NULL &&
-        strstr(src, "grep") == NULL &&
-        strstr(src, "[") == NULL)
-    {
-        result = true;
-    }
-
-    return result;
-}
-
-int GetProcessCount(char *procName)
-{
-	int result = 0;
-	FILE *fp;
-	char cmd[256];
-	char buf[256];
-
-	sprintf(cmd, "ps -ef |grep %s", procName);
-	fp = popen(cmd, "r");
-	if(fp != NULL)
-	{
-		while(fgets(buf, sizeof(buf), fp) != NULL)
-		{
-			if (Taskconutstring(buf, procName))
-				result++;
-		}
-	}
-
-	pclose(fp);
-
-	return result;
-}
-void CheckTaskAlive()
-{
-    pid_t Pid = fork();
-    if ( Pid == 0 ) {
-        //log_info("CheckTaskAlive fork Child's PID is %d", getpid());
-        while(1) {
-            sleep(3);
-            unsigned char count = GetProcessCount("Module_ChkSysTask");
-            if( count != 1 ) {
-                system("pkill Module_ChkSysTask");
-                sleep(10);
-                //log_info("Create Check System Task");
-                system("/root/Module_ChkSysTask &");
-            }
-        }
-        return;
-    }
-    log_info("Create Check Systam fork:%d",Pid);
-    return;
-}
-/**
- * [checkPileEndGfdResult 確認充電樁GFD狀態]
- * @Author   Jerry
- * @DateTime 2021-07-01
- * @param    gunIndex   [當前的槍]
- * @param    gunType    [槍的類型]
- * @param    sysStatus  [槍的系統狀態]
- */
-static void checkPileEndGfdResult(uint8_t gunIndex, uint8_t gunType, uint8_t sysStatus)
-{
-    switch (gunType) {
-    case _Type_Chademo:
-        // 檢查樁端的 GFD 結果
-        if (sysStatus == S_PREPARING_FOR_EVSE &&
-                isPrechargeStatus_chademo(gunIndex) >= 6 ) {
-            // 當前操作的槍號,進入 Charging
-            setChargerMode(gunIndex, MODE_CHARGING);
-        }
-
-        if (pDcChargingInfo->GroundFaultStatus == GFD_FAIL) {
-            // GFD 錯誤停止
-            RecordAlarmCode(gunIndex, "012234");
-            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaGfdTrip = YES;
-            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaGfdWarning = NO;
-        } else if (pDcChargingInfo->GroundFaultStatus == GFD_WARNING) {
-            // GFD 警告
-            //RecordAlarmCode(gunIndex, "012296");
-            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaGfdTrip = NO;
-            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaGfdWarning = YES;
-        }
-        else {
-            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaGfdTrip = NO;
-            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaGfdWarning = NO;
-        }
-
-        break;
-
-    case _Type_GB:
-        // 檢查樁端的 GFD 結果
-        //if (isPrechargeStatus_gb(gunIndex) > 5 && isPrechargeStatus_gb(gunIndex) < 9) {
-        if (sysStatus == S_PREPARING_FOR_EVSE &&
-                isPrechargeStatus_gb(gunIndex) >= 6) {
-            setChargerMode(gunIndex, MODE_CHARGING);
-        }
-
-        if (pDcChargingInfo->GroundFaultStatus == GFD_FAIL) {
-            // GFD 錯誤停止
-            RecordAlarmCode(gunIndex, "012236");
-            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTGfdTrip = YES;
-            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTGfdWarning = NO;
-        } else if (pDcChargingInfo->GroundFaultStatus == GFD_WARNING) {
-            // GFD 警告
-            //RecordAlarmCode(gunIndex, "012298");
-            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTGfdTrip = NO;
-            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTGfdWarning = YES;
-        }
-        else {
-            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTGfdTrip = NO;
-            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTGfdWarning = NO;
-        }
-        break;
-
-    case _Type_CCS_2:
-        // 檢查樁端的 GFD 結果
-        if (sysStatus == S_PREPARING_FOR_EVSE &&
-                (pDcChargingInfo->GroundFaultStatus == GFD_PASS ||
-                 pDcChargingInfo->GroundFaultStatus == GFD_WARNING)
-           ) {
-            setChargerMode(gunIndex, MODE_CCS_PRECHARGE_STEP0);
-        }
-
-        if (pDcChargingInfo->GroundFaultStatus == GFD_FAIL) {
-            // GFD 錯誤停止
-            RecordAlarmCode(gunIndex, "012235");
-            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSGfdTrip = YES;
-            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSGfdWarning = NO;
-        } else if (pDcChargingInfo->GroundFaultStatus == GFD_WARNING) {
-            // GFD 警告
-            //RecordAlarmCode(gunIndex, "012297");
-            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSGfdTrip = NO;
-            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSGfdWarning = YES;
-        }
-        else {
-            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSGfdTrip = NO;
-            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSGfdWarning = NO;
-        }
-
-        break;
-    }
-}
-
-static void checkEvBoardReqStop(uint8_t sysStatus, uint8_t gunIndex)
-{
-    uint8_t evBoardStopState = 0;
-
-    if ((evBoardStopState = isEvBoardStopChargeFlag(gunIndex)) > 0) {
-
-        // 板端要求停止 (錯誤)
-        if (sysStatus != S_CCS_PRECHARGE_ST0 &&
-                sysStatus != S_CCS_PRECHARGE_ST1) {
-            if (strcmp((char *)ShmOCPP16Data->StopTransaction[gunIndex].StopReason, "") == EQUAL) {
-                strcpy((char *)ShmOCPP16Data->StopTransaction[gunIndex].StopReason, "EVDisconnected");
-            }
-        }
-
-        if (evBoardStopState == EV_BOARD_STOP_CHARGING) {
-            log_info("EV Board Stop Charging with some error");
-            ChargingAlarmProcess(gunIndex);
-        } else if (evBoardStopState == POWER_CABINET_STOP_CHARGING) {
-            log_info("Power Cabient Stop Charging");
-            ChargingTerminalProcess(gunIndex);
-        }
-    } else if (isEvBoardNormalStopChargeFlag(gunIndex) == YES) {
-        // 板端要求停止 (正常)
-        if (sysStatus != S_CCS_PRECHARGE_ST0 &&
-                sysStatus != S_CCS_PRECHARGE_ST1) {
-            if (strcmp((char *)ShmOCPP16Data->StopTransaction[gunIndex].StopReason, "") == EQUAL) {
-                strcpy((char *)ShmOCPP16Data->StopTransaction[gunIndex].StopReason, "EVDisconnected");
-            }
-        }
-        log_info("EV Board Normal Stop Charging");
-        ChargingTerminalProcess(gunIndex);
-    } else if (OcppRemoteStop(gunIndex) == YES ||
-               WifiScheduleStop(gunIndex)) {
-        // 後臺要求停止
-        log_info("OCPP Stop Charging");
-        ChargingTerminalProcess(gunIndex);
-    }
-}
-
-static void checkOCPPReqStop(uint8_t gunIndex)
-{
-    if (OcppRemoteStop(gunIndex) == YES ||
-        WifiScheduleStop(gunIndex) ||
-        CheckBackendChargingTimeout(gunIndex) ||
-        CheckBackendChargingEnergy(gunIndex) ||
-        strcmp((char *)ShmOCPP16Data->StartTransaction[gunIndex].ResponseIdTagInfo.Status, "Invalid") == EQUAL) {
-        // 後臺要求停止
-        ChargingTerminalProcess(gunIndex);
-    }
-}
-void ResetIdleData(uint8_t gunIndex)
-{
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-    ShmOCPP16Data = (struct OCPP16Data *)GetShmOCPP16Data();
-    ShmSelectGunInfo = (SelectGunInfo *)GetShmSelectGunInfo();
-    float powerconsumption = ShmDcCommonData->pGunInfo[gunIndex].PowerConsumption;
-    pDcChargingInfo->PresentChargedDuration = 0;
-    pDcChargingInfo->RemainChargingDuration = 0;
-    pDcChargingInfo->PresentChargingVoltage = 0;//DS60-120 add
-    pDcChargingInfo->PresentChargingCurrent = 0;//DS60-120 add
-    pDcChargingInfo->RemoteStartFlag = NO;
-    pDcChargingInfo->Replug_flag = FALSE;
-    strcpy((char *)pDcChargingInfo->StartDateTime, "");
-    strcpy((char *)pDcChargingInfo->StopDateTime, "");
-    strcpy((char *)pDcChargingInfo->StartUserId, "");
-    strcpy((char *)pSysConfig->UserId, "");
-    strcpy((char *)ShmOCPP16Data->StopTransaction[gunIndex].StopReason, "");
-    ClearDetectPluginFlag(gunIndex);
-    //Jerry add
-    memset(&ShmSelectGunInfo->PricesInfo[gunIndex], 0, sizeof(PricesInfo));
-    memset(&ShmDcCommonData->TransactionInfo[gunIndex], 0, sizeof(RecordTransactionInfo));
-    memset(&ShmDcCommonData->pGunInfo[gunIndex], 0, sizeof(GunInfo));
-    ShmDcCommonData->pGunInfo[gunIndex].PowerConsumption = powerconsumption;
-    ShmDcCommonData->finalcost_flag[gunIndex] = FALSE;
-    ShmDcCommonData->AuthPass_flag[gunIndex] = FALSE;
-    ShmDcCommonData->PayPass_flag[gunIndex] = FALSE;
-    ShmDcCommonData->OperateIDLE[gunIndex] = 1;
-    ShmDcCommonData->is_RemoteStart[gunIndex] = FALSE;
-    ShmDcCommonData->is_AutoStart[gunIndex] = FALSE;
-    ShmDcCommonData->is_exit[gunIndex] = FALSE;
-    ShmDcCommonData->StopCharge[gunIndex] = FALSE;
-    ShmDcCommonData->is_plugout[gunIndex] = FALSE;
-
-    ShmSelectGunInfo->PricesInfo[gunIndex].Balance = FAIL_BALANCE_PRICES;
-    destroySelGun(gunIndex);
-    ResetDetAlarmStatus(gunIndex); //recovery OVP status code
-    if (ShmSelectGunInfo->AuthorStateFromCabinet[gunIndex] == YES) {
-        ShmSelectGunInfo->AuthorStateFromCabinet[gunIndex] = NO;
-    }
-    //strcpy((char *)ShmOCPP16Data->StatusNotification[gunIndex].VendorErrorCode, "");
-    ReleaseAlarmCode(gunIndex);
-    if (pSysInfo->SystemPage != _PAGE_SELECT_GUN &&
-        pSysInfo->SystemPage != _PAGE_SELECT_PAY &&
-        pSysInfo->CurGunSelected == gunIndex) {
-        systemPageRestoreInit();
-    }
-
-}
-void CheckErrorCode(uint8_t gunIndex)
-{
-    /*
-    struct ChargingInfoData *pSelectedDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-    
-    if (gunIndex == pSysInfo->CurGunSelected) {
-        pSysInfo->SystemPage = _PAGE_MAINTAIN;
-    } else if (pSelectedDcChargingInfo->SystemStatus != S_IDLE &&
-            pSelectedDcChargingInfo->SystemStatus != S_RESERVATION &&
-            pSelectedDcChargingInfo->SystemStatus != S_MAINTAIN &&
-            pSelectedDcChargingInfo->SystemStatus != S_FAULT) {
-        if (pSelectedDcChargingInfo->SystemStatus == S_CHARGING) {
-        	if(ShmDcCommonData->PayPass_flag[gunIndex] == FALSE)
-        		pSysInfo->SystemPage = _PAGE_PAYING;
-        	else
-        		pSysInfo->SystemPage = _PAGE_COMPLETE;
-        } else {
-            systemPageRestoreInit();
-        }
-    }
-    */
-    ClearDetectPluginFlag(gunIndex);
-    if (pDcChargingInfo->SystemStatus != S_FAULT)
-    {
-        UpdateErrorCodeToOcpp(gunIndex);
-        setChargerMode(gunIndex, MODE_FAULT);
-    }
-}
-void AuthorizeStopCharging(uint8_t gunIndex)
-{
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-
-    checkOCPPReqStop(gunIndex);
-
-    //RfidStopCharging();
-
-}
-void showversion()
-{
-    char str[10240];
-    int len = 0;
-    uint8_t index = 0;
-    len += sprintf(&str[len],"\n=========== Dispenser info =========== \n");
-    len += sprintf(&str[len],"SW Version = %s\n", fwVersion);
-    len += sprintf(&str[len],"Debug Version = %s\n",DebugVersion);
-    len += sprintf(&str[len],"ModelName = %s\n", pSysConfig->ModelName);
-    len += sprintf(&str[len],"Relay Board FW Rev = %s\n", pSysInfo->RelayModuleFwRev);
-    len += sprintf(&str[len],"Fan Board FW Rev = %s\n", pSysInfo->FanModuleFwRev);
-    len += sprintf(&str[len],"Primary FW Rev = %s\n", pSysInfo->CsuPrimFwRev);
-    len += sprintf(&str[len],"LED FW Rev = %s\n", pSysInfo->LedModuleFwRev);
-
-    for (index = 0; index < pSysConfig->TotalConnectorCount; index++) {
-        pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);
-        if (pDcChargingInfo->Type == _Type_Chademo) {
-            len += sprintf(&str[len],"CHAdeMO[%d] FW Rev = %s\n",
-                                     index,
-                                     ShmCHAdeMOData->evse[pDcChargingInfo->type_index].version);
-        } else if (pDcChargingInfo->Type == _Type_GB) {
-            len += sprintf(&str[len],"GBT[%d] FW Rev = %s\n",
-                                     index,
-                                     ShmGBTData->evse[pDcChargingInfo->type_index].version);
-        } else if (pDcChargingInfo->Type == _Type_CCS_2) {
-            len += sprintf(&str[len],"CCS[%d] FW Rev = %s\n",
-                                         index,
-                                         ShmCcsData->V2GMessage_DIN70121[pDcChargingInfo->type_index].version);
-        }
-    }
-    len += sprintf(&str[len],"==================================== ");
-    log_info("%s",str);
-}
-
-void ParkingProcess(int gunIndex)
-{
-    if (pSysInfo->CurGunSelected != gunIndex)
-        return;
-
-    // 取得佔位費資訊過場畫面
-    if (ShmDcCommonData->pGunInfo[gunIndex].ParkingStatus == _TCC_PARKING_NONE) {
-        return;
-    } else if (!ShmDcCommonData->pGunInfo[gunIndex].GetParkingBill &&
-        pSysInfo->SystemPage != _PAGE_IDLE &&
-        pSysInfo->SystemPage != _PAGE_SELECT_GUN &&
-        pSysInfo->SystemPage != _PAGE_COMPLETE &&
-        pSysInfo->SystemPage != _PAGE_PAYFAIL &&
-        pSysInfo->SystemPage != _PAGE_PLUGOUT &&
-        pSysInfo->SystemPage != _PAGE_SENSING &&
-        pSysInfo->SystemPage != _PAGE_PLUGIN) {
-        pSysInfo->SystemPage = _PAGE_PAYING;
-        StartGunInfoTimeoutDet(gunIndex, Timeout_WaitParkingInfo);
-        return;
-    }
-    if (ShmDcCommonData->pGunInfo[gunIndex].GetParkingBill && pSysInfo->SystemPage == _PAGE_PAYING) {
-            pSysInfo->SystemPage = _PAGE_BILL;
-    }
-    switch (pSysInfo->SystemPage) {
-        case _PAGE_BILL:
-        case _PAGE_DONATE_LEFT:
-        case _PAGE_DONATE_RIGHT:
-        case _PAGE_SELECT_PAY:
-            StartGunInfoTimeoutDet(gunIndex, Timeout_ParkingSelect);
-            break;
-        case _PAGE_ADD_FRIEND:
-            StartGunInfoTimeoutDet(gunIndex, Timeout_ParkingBill);
-            if (ShmDcCommonData->ParkingInfo[gunIndex].LineStatus == _LINE_PARKING_INVOICE) {
-                ShmDcCommonData->ParkingInfo[gunIndex].IsDonateInvoice = FALSE;
-                pSysInfo->SystemPage = _PAGE_SELECT_PAY;
-                StopGunInfoTimeoutDet(gunIndex);
-                log_info("Change to Select Pay Page");
-            } else if (ShmDcCommonData->ParkingInfo[gunIndex].LineStatus == _LINE_PARKING_DONATE) {
-                ShmDcCommonData->ParkingInfo[gunIndex].IsDonateInvoice = TRUE;
-                pSysInfo->SystemPage = _PAGE_SELECT_PAY;
-                StopGunInfoTimeoutDet(gunIndex);
-                log_info("Change to Select Pay Page");
-            }
-            break;
-        case _PAGE_AUTHORIZE:
-            StopGunInfoTimeoutDet(gunIndex);
-            break;
-        case _PAGE_PLUGIN:
-            StartGunInfoTimeoutDet(gunIndex,Timeout_ParkingLeave);
-            /*
-            if (pDcChargingInfo->ConnectorPlugIn == NO ) {
-                if (pSysInfo->CurGunSelected == gunIndex) {
-                    StartGunInfoTimeoutDet(gunIndex, Timeout_ExitPage);
-                }
-                if (pDcChargingInfo->TimeoutFlag != Timeout_ExitPage) {
-                    StartGunInfoTimeoutDet(gunIndex, Timeout_CompletPlugout);
-                }
-            }
-            */
-            break;
-        case _PAGE_AUTHORIZE_FAIL:
-            StartSystemTimeoutDet(Timeout_VerifyFail);
-            break;
-        case _PAGE_PLUGOUT:
-            StopGunInfoTimeoutDet(gunIndex);
-            break;
-    }
-
-}
-
-int main(void)
-{
-    bool isModelNameMatch = true;
-    uint8_t _ocppProfileChkFlag;
-    uint8_t gunIndex = 0;
-
-    if (CreateAllCsuShareMemory() == FAIL) {
-        log_error("create share memory error");
-        return FAIL;
-    }
-    ClearAllShmMemParameter();
-
-    pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
-    pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
-    pSysWarning = (struct WARNING_CODE_INFO *)GetShmSysWarningInfo();
-
-    pAlarmCode = (struct AlarmCodeData *)GetShmAlarmCodeData();
-    pFaultCode = (struct FaultCodeData *)GetShmFaultCodeData();
-    pInfoCode = (struct InfoCodeData *)GetShmInfoCodeData();
-
-    ShmPsuData = (struct PsuData *)GetShmPsuData();
-
-    ShmCHAdeMOData = (struct CHAdeMOData *)GetShmCHAdeMOData();
-    ShmGBTData = (struct GBTData *)GetShmGBTData();
-    ShmCcsData = (struct CcsData *)GetShmCcsData();
-
-    ShmPrimaryMcuData = (struct PrimaryMcuData *)GetShmPrimaryMcuData();
-    ShmFanModuleData = (struct FanModuleData *)GetShmFanModuleData();
-    ShmRelayModuleData = (struct RelayModuleData *)GetShmRelayModuleData();
-    ShmLedModuleData = (struct LedModuleData *)GetShmLedModuleData();
-    ShmOCPP16Data = (struct OCPP16Data *)GetShmOCPP16Data();
-    ShmOCPP20Data = (struct OCPP20Data*)GetShmOCPP20Data();
-    ShmDcCommonData = (DcCommonInfo *)GetShmDcCommonData();
-    ShmSelectGunInfo = (SelectGunInfo *)GetShmSelectGunInfo();
-	
-    ShmSysConfigAndInfo = (struct SysConfigAndInfo *)GetShmSysConfigAndInfo();
-    ShmStatusCodeData = (struct StatusCodeData *)GetShmStatusCodeData();	
-    log_info(" ********************************************************");
-    log_info(" ******************  FileSystem Boot up *****************");
-    log_info(" ********************************************************");
-    log_info(" ******************  Project:DD360Tcc   *****************");
-    log_info(" ********************************************************");
-
-    if (!InitialSystemDefaultConfig()) {
-        log_error("InitialSystemDefaultConfig NG ");
-        //StopProcessingLoop();
-        sleep(5);
-        system("reboot -f");
-    }
-    CheckGunTypeFromHw();
-    CheckIsAlternatvieByModelName();
-    InitialShareMemoryInfo();
-    GetFirmwareVersion();
-
-    if (!CheckConnectorTypeStatus()) {
-        isModelNameMatch = false;
-    }
-
-    Initialization();
-    SpawnTask();
-    log_info("Spawned all Task");
-    if (!isModelNameMatch) {
-        pAlarmCode->AlarmEvents.bits.ModelNameNoneMatchStestFail = YES;
-        //ChangeLcmByIndex(_LCM_ERROR);
-        ChangeLcmByIndex(_PAGE_MAINTAIN);
-        // Module Name 與硬體對應不正確
-        log_error("Module Name & HW info none match. ");
-        sleep(3);
-        KillAllTask();
-        StopProcessingLoop();
-    }
-    CreateTimeoutFork();    
-    log_info("Start self test... ");
-
-    SelfTestRun();
-    StopSystemTimeoutDet();
-    log_info("Self test finished : SelfTestSeq = %d, Work_Step = %d ",
-             pSysInfo->SelfTestSeq,
-             ShmPsuData->Work_Step);
-
-    if (pSysInfo->SelfTestSeq == _STEST_FAIL || ShmPsuData->Work_Step == _NO_WORKING ||
-        pInfoCode->InfoEvents.bits.CcsSeccTimeoutQCA7000Comm == YES ) {
-        ChangeLcmByIndex(_PAGE_MAINTAIN);
-        for (gunIndex = 0; gunIndex < pSysConfig->TotalConnectorCount; gunIndex++) {
-            setChargerMode(gunIndex, MODE_MAINTAIN);
-        }
-    } else {
-        for (gunIndex = 0; gunIndex < pSysConfig->TotalConnectorCount; gunIndex++) {
-            setChargerMode(gunIndex, MODE_IDLE);
-        }
-    }
-
-    // Local DB
-    if (DB_Open() != PASS) {
-        log_info("DB_Open fail. ");
-        isDb_ready = false;
-    } else {
-        isDb_ready = true;
-        for (int _index = 0; _index < pSysConfig->TotalConnectorCount; _index++) {
-            pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(_index);
-            pDcChargingInfo->IsAvailable = DB_Get_Operactive(_index);
-
-        }
-        DB_Reboot_Record();
-    }
-
-    if (PowerDB_Open() != PASS) {
-        log_info("Power DB_Open fail. ");
-        isDb_ready = false;
-    } else {
-        int _retry = 0;
-        isDb_ready = true;
-        for (int _index = 0; _index < pSysConfig->TotalConnectorCount; _index++) {
-            pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(_index);
-            while (_retry < 3) {
-                if (DB_Get_PowerConsumption(_index)) {
-                    break;
-                } else {
-                    sleep(1);
-                    _retry++;
-                    if (_retry == 3) {
-                        DB_Insert_PowerConsumption(_index, 0);
-                    }
-                }
-            } // while
-        } // for
-    }
-    log_info("===== Create DB End ===== ");
-
-    ChangeLcmByIndex(_PAGE_IDLE);
-
-    sleep(1);
-    //***** 須新增的偵測 *****//
-    // 1. Thernal - 控制風扇轉速
-    // 2. ouput fuse - 控制風扇轉速
-    CreateRfidFork();
-    // Main loop
-
-    CheckFwSlotStatusLog();
-    //AdjustChargerCurrent();
-    GetClockTime(&_cmdMainPriority_time, NULL);
-
-   // GunIndexInfo *pGunIndexInfo = (GunIndexInfo *)GetGunIndexInfo();
-
-    CheckTaskAlive();
-
-    CreateWatchdog();
-    
-    //SetGunTypeOTPValue();
-
-    showversion();
-
-    ShmDcCommonData->ParkingLeaveTime = 15; //結束充電15分鐘後開始計算佔位費
-    ShmDcCommonData->SaleLeaveTime = 10;    //結算佔位費後開始計算10分鐘
-
-    for (;;) {
-
-        CheckOcppStatus();
-
-        ChkPrimaryStatus();
-
-        if ((IsConnectorWholeIdle() ||
-                //(pSysInfo->PageIndex == _LCM_ERROR)) &&
-                (pSysInfo->PageIndex == _PAGE_MAINTAIN))
-           ) {
-            CheckFactoryConfigFunction();
-
-            //CheckFwUpdateFunction();
-        }
-
-        // OCPP 邏輯
-        OcppRemoteStartChk();
-
-        // 當 AC 沒有搭上時,清除一些錯誤碼
-        ClearAlarmCodeWhenAcOff();
-
-        if ((GetClockTimeoutValue(_cmdMainPriority_time) / 1000) > 5000) {
-
-            for (gunIndex = 0; gunIndex < pSysConfig->TotalConnectorCount; gunIndex++) {
-                pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-
-                if ((pDcChargingInfo->SystemStatus >= S_PREPARING_FOR_EVSE &&
-                        pDcChargingInfo->SystemStatus <= S_CHARGING) ||
-                        (pDcChargingInfo->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
-                         pDcChargingInfo->SystemStatus <= S_CCS_PRECHARGE_ST1)) {
-                    if (pDcChargingInfo->SystemStatus == S_CHARGING &&
-                            _ocppProfileChkFlag == 12) {
-                        ChargingProfileFlat(gunIndex);
-                        _ocppProfileChkFlag = 0;
-                    } else if (pDcChargingInfo->SystemStatus != S_CHARGING) {
-                        ChargingProfileFlat(gunIndex);
-                        _ocppProfileChkFlag = 0;
-                    } else {
-                        _ocppProfileChkFlag++;
-                    }
-                }
-                checkGunOTPState(gunIndex); //check gun OTP
-            }
-            GetClockTime(&_cmdMainPriority_time, NULL);
-        }
-
-        gEvBoardErr.GunErrMessage = 0; //清除系統執行中的錯誤訊息
-        gChillerTempErr.TempErrMsg = 0;//清除系統執行中的錯誤訊息
-        for (gunIndex = 0; gunIndex < pSysConfig->TotalConnectorCount; gunIndex++) {
-            pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-            // 重新收集各槍的錯誤狀態
-            collectError(gunIndex);
-            checkEvBoardAlarmState(pDcChargingInfo->Type);
-        }
-        checkChillerAlarmState();
-
-        // 確認當前錯誤 Level = 2 ?
-        ReviewCriticalAlarm();
-
-        for (gunIndex = 0; gunIndex < pSysConfig->TotalConnectorCount; gunIndex++) {
-            pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-
-            CheckGpioInStatus();
-
-            CheckErrorOccurStatus(gunIndex);
-
-            // 確認 Relay Welding or Driving Fault
-            CheckRelayWeldingOrDrivingFault(gunIndex);
-
-            ChkOcppStatus(gunIndex);
-
-            if ((pDcChargingInfo->SystemStatus >= S_PREPARING_FOR_EVSE &&
-                    pDcChargingInfo->SystemStatus <= S_CHARGING) ||
-                    (pDcChargingInfo->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
-                     pDcChargingInfo->SystemStatus <= S_CCS_PRECHARGE_ST1)) {
-                CheckSmartChargeProfile(gunIndex);
-            }
-
-            switch (pDcChargingInfo->SystemStatus) {
-            case S_IDLE:
-                if (isModeChange(gunIndex)) {
-                    log_info("============================= S_IDLE(%x) ============================= ", gunIndex);
-                    ResetIdleData(gunIndex);
-                }
-                isChargingAverageState();
-                // For RemoteStart Using
-
-                if (pDcChargingInfo->RemoteStartFlag == YES && pDcChargingInfo->IsAvailable) {
-					log_info("-------- IDLE Remote Start(%d) --------", gunIndex);
-					//ChangeGunSelectByIndex(gunIndex);
-					setChargerMode(gunIndex, MODE_AUTHORIZING);
-					break;
-                }
-                autoStartCharging(gunIndex);
-                // 讀卡邏輯
-                if (!ShmDcCommonData->TradeCancel && pSysInfo->CurGunSelected == gunIndex)
-                    ScannerCardProcess(gunIndex);
-                if (pSysInfo->SystemPage == _PAGE_SELECT_GUN || pSysInfo->SystemPage == _PAGE_IDLE) {
-                	//ShmDcCommonData->LineStatus[gunIndex] = 0;
-                	StopGunInfoTimeoutDet(gunIndex);
-				}
-
-                if (pSysInfo->CurGunSelected == gunIndex) {
-                    if (ShmDcCommonData->pGunInfo[gunIndex].isParking) {
-                        // 佔位費流程
-                        ParkingProcess(gunIndex);
-                    } else {
-                        // 一般充電流程
-                        if (pSysInfo->SystemPage == _PAGE_BILL) {
-                            StartSystemTimeoutDet(Timeout_AddLine);
-                            /*
-                            if (ShmDcCommonData->TransactionInfo[gunIndex].LineStatus == _LINE_ADD_FRIEND) {
-                                pSysInfo->SystemPage = _PAGE_ADD_FRIEND;
-                                log_info("Change to Add Line Friend Page");
-                            }
-                            */
-                        } else if (pSysInfo->SystemPage == _PAGE_ADD_FRIEND) {
-                            StopSystemTimeoutDet();
-                            StartGunInfoTimeoutDet(gunIndex, Timeout_LineReigster);
-                            if (ShmDcCommonData->TransactionInfo[gunIndex].LineStatus == _LINE_CREDITCARD_INVOICE) {
-                                StopGunInfoTimeoutDet(gunIndex);
-                                pSysInfo->SystemPage = _PAGE_SELECT_PAY;
-                                ShmDcCommonData->TransactionInfo[gunIndex].IsDonateInvoice = FALSE;
-                                log_info("Change to Select Pay Page");
-                            }
-                            if (ShmDcCommonData->TransactionInfo[gunIndex].LineStatus == _LINE_CREDITCARD_DONATE) {
-                                StopGunInfoTimeoutDet(gunIndex);
-                                pSysInfo->SystemPage = _PAGE_SELECT_PAY;
-                                ShmDcCommonData->TransactionInfo[gunIndex].IsDonateInvoice = TRUE;
-                                log_info("Change to Select Pay Page");
-                            }
-                        }
-                    }
-                }
-                // 檢查預約
-                if (ShmDcCommonData->pGunInfo[gunIndex].ReservationStatus) {
-                    setChargerMode(gunIndex, MODE_RESERVATION);
-                }
-                goto CheckStatus;
-                break;
-            case S_RESERVATION:
-                if (isModeChange(gunIndex)) {
-                    log_info("============================= S_RESERVATION(%x) ============================= ", gunIndex);
-                    ShmOCPP16Data->CsMsg.bits[gunIndex].ReserveNowConf = YES;
-                }
-                if (pDcChargingInfo->RemoteStartFlag == YES && pDcChargingInfo->IsAvailable) {
-                    log_info("-------- S_RESERVATION Remote Start(%d) --------", gunIndex);
-                    //ChangeGunSelectByIndex(gunIndex);
-                    setChargerMode(gunIndex, MODE_AUTHORIZING);
-                    break;
-                }
-                // 讀卡邏輯
-                if (!ShmDcCommonData->TradeCancel && pSysInfo->CurGunSelected == gunIndex)
-                    ScannerCardProcess(gunIndex);
-                // 檢查預約
-                if (!ShmDcCommonData->pGunInfo[gunIndex].ReservationStatus) {
-                    setChargerMode(gunIndex, MODE_IDLE);
-                }
-                goto CheckStatus;
-                break;
-            case S_FAULT:
-                if (isModeChange(gunIndex)) {
-                    if (pDcChargingInfo->SystemStatus == S_FAULT) {
-                        log_info("============================= S_FAULT(%x) ============================= ", gunIndex);
-                        //pSysInfo->SystemPage = _LCM_ERROR;
-                        //pSysInfo->SystemPage = _PAGE_MAINTAIN;
-                    }
-                }
-CheckStatus:
-                if (pDcChargingInfo->IsAvailable == NO) {
-                    setChargerMode(gunIndex, MODE_MAINTAIN);
-                    break;
-                }
-                // Refresh Error Status
-                if (pSysWarning->Level == WARN_LV_ER) {
-                    CheckErrorCode(gunIndex);
-                    if (pSysInfo->CurGunSelected == gunIndex)
-                        pSysInfo->SystemPage = _PAGE_MAINTAIN;
-                    continue;
-                }
-                if (PrecheckIsPass(gunIndex) == false) {
-                    log_error("Relay welding");
-                    setChargerMode(gunIndex, MODE_FAULT);
-                    if (gunIndex == pSysInfo->CurGunSelected) {
-                        //pSysInfo->SystemPage = _LCM_ERROR;
-                        pSysInfo->SystemPage = _PAGE_MAINTAIN;
-                    }
-                    break;
-                }
-                if (pDcChargingInfo->SystemStatus == S_FAULT) {
-                    setChargerMode(gunIndex, MODE_IDLE);
-                    systemPageRestoreInit();
-                }
-
-                break;
-
-            case S_AUTHORIZING:
-                if (isModeChange(gunIndex)) {
-                    log_info("============================= S_AUTHORIZING(%x) ============================= ", gunIndex);
-                    StartGunInfoTimeoutDet(gunIndex, Timeout_AuthorizingForStop);
-                }
-
-                if (pSysInfo->CurGunSelected == gunIndex)
-                    ScannerCardProcess(gunIndex);
-
-                if (pSysInfo->SystemPage == _PAGE_PLUGIN && ShmDcCommonData->TradeCancel == FALSE) {
-                    pDcChargingInfo->Replug_flag = TRUE;
-                    StopSystemTimeoutDet();
-                }
-                if (isDetectPlugin(gunIndex)) {
-                    StartGunInfoTimeoutDet(gunIndex, Timeout_WaitPlug);
-
-                    // 卡號驗證成功後,等待充電槍插入充電車
-                    if (pDcChargingInfo->RemoteStartFlag == YES) {
-                        if (pDcChargingInfo->ConnectorPlugIn == YES &&
-                                pDcChargingInfo->IsAvailable ) {
-                            log_info("-------- S_AUTHORIZING Remote Start(%d) --------", gunIndex);
-                            pDcChargingInfo->RemoteStartFlag = NO;
-                            pDcChargingInfo->isRemoteStart = YES; //DS60-120
-                            
-                            //ChangeGunSelectByIndex(gunIndex);
-                            //AddPlugInTimes(gunIndex);
-                            setChargerMode(gunIndex, MODE_REASSIGN_CHECK);
-                            strcpy((char *)pDcChargingInfo->StartUserId, "");
-                            ClearDetectPluginFlag(gunIndex);
-                            continue;
-                        }
-                    } else if (pSysInfo->OrderCharging == NO_DEFINE) {
-                        if (pDcChargingInfo->ConnectorPlugIn == YES &&
-                                pDcChargingInfo->IsAvailable &&
-                                pDcChargingInfo->SystemStatus == S_AUTHORIZING &&
-								ShmDcCommonData->AuthPass_flag[gunIndex] == TRUE &&
-                                (waitRightGunPlugIt(gunIndex) == PASS ||
-                                 waitLeftGunPlugIt(gunIndex) == PASS)
-                           ) {
-                            log_info("-------- RFID/Auto Start(%d) --------", gunIndex);
-                            //ChangeGunSelectByIndex(gunIndex);
-                            //AddPlugInTimes(gunIndex);
-                            pDcChargingInfo->isRemoteStart = NO;
-                            strcpy((char *)pDcChargingInfo->StartUserId, (char *)pSysConfig->UserId);
-                            log_info("index = %d, CardNumber = %s ",
-                                     gunIndex,
-                                     pDcChargingInfo->StartUserId);
-                            strcpy((char *)pSysConfig->UserId, "");
-                            // 當前操作的槍號,進入 Preparing
-                            setChargerMode(gunIndex, MODE_REASSIGN_CHECK);
-                            ClearDetectPluginFlag(gunIndex);
-                            continue;
-                        }
-                    }
-
-                    if (!GetIsCardScan() && pSysInfo->CurGunSelected == gunIndex &&
-                    		pSysInfo->SystemPage != _PAGE_AUTHORIZE_FAIL &&
-                    		pSysInfo->SystemPage != _PAGE_SENSING) {
-                        pSysInfo->SystemPage = _PAGE_PLUGIN;
-                    } else if (!GetIsCardScan() && pSysInfo->SystemPage == _PAGE_IDLE &&
-                        pDcChargingInfo->RemoteStartFlag == YES) {
-                        pSysInfo->CurGunSelected = gunIndex;
-                    }
-                } else if (ShmDcCommonData->AuthPass_flag[gunIndex] && pSysInfo->CurGunSelected == gunIndex &&
-                    pSysInfo->SystemPage != _PAGE_AUTHORIZE_FAIL) {
-                    pSysInfo->SystemPage = _PAGE_SENSING;
-                }
-                break;
-
-            case S_REASSIGN_CHECK: {
-                if (isModeChange(gunIndex)) {
-                    log_info("============================= S_REASSIGN_CHECK(%x) ============================= ", gunIndex);
-                    if (pSysInfo->OrderCharging != NO_DEFINE) {
-                        pSysInfo->OrderCharging = NO_DEFINE;
-                        pDcChargingInfo->_SaftyDetect = FALSE;
-                    }
-                    pDcChargingInfo->Replug_flag = TRUE;
-                    StopSystemTimeoutDet();
-                    StopGunInfoTimeoutDet(gunIndex);
-                }
-
-                setChargerMode(gunIndex, S_PREPARNING);
-                if (pSysInfo->CurGunSelected == gunIndex) {
-                    pSysInfo->SystemPage = _PAGE_PRECHARGE;
-                }
-            }
-            break;
-
-            case S_PREPARNING:
-                if (isModeChange(gunIndex)) {
-                    log_info("============================= S_PREPARNING(%x) ============================= ", gunIndex);
-                    StopGunInfoTimeoutDet(gunIndex);
-                    StartGunInfoTimeoutDet(gunIndex, Timeout_Preparing);
-                }
-
-                if (ShmPsuData->SystemPresentPsuQuantity > 0 &&
-                        ShmPsuData->SystemAvailablePower > 10 &&
-                        GetClockTimeoutValue(pDcChargingInfo->ConnectorTimeout) >= 1000000) {
-                    setChargerMode(gunIndex, MODE_PREPARE_FOR_EV);
-                }
-
-                checkEvBoardReqStop(pDcChargingInfo->SystemStatus, gunIndex);
-                if (pSysInfo->CurGunSelected == gunIndex) {
-                    pSysInfo->SystemPage = _PAGE_PRECHARGE;
-                }
-                break;
-
-            case S_PREPARING_FOR_EV: // 等待車端的通訊 (EV 小板),待車端回報後,開始樁端的測試
-                if (isModeChange(gunIndex)) {
-                    log_info("============================= S_PREPARING_FOR_EV(%x) ============================= ", gunIndex);
-                    log_info("Waitting for Gun locked.");
-                    StopGunInfoTimeoutDet(gunIndex);
-                    StartGunInfoTimeoutDet(gunIndex, Timeout_EvChargingDet);
-                }
-
-                if (pDcChargingInfo->Type == _Type_Chademo) {
-                    if (isEvGunLocked_chademo(gunIndex) == YES) {
-                        log_info("Gun Locked");
-                        setChargerMode(gunIndex, MODE_PREPARE_FOR_EVSE);
-                    }
-                } else if (pDcChargingInfo->Type == _Type_GB) {
-                    if (isEvGunLocked_gb(gunIndex) == YES) {
-                        log_info("Gun Locked");
-                        setChargerMode(gunIndex, MODE_PREPARE_FOR_EVSE);
-                    }
-                } else if (pDcChargingInfo->Type == _Type_CCS_2) {
-                    if (isEvGunLocked_ccs(gunIndex) == YES) {
-                        log_info("Gun Locked");
-                        setChargerMode(gunIndex, MODE_PREPARE_FOR_EVSE);
-                    }
-                }
-
-                checkEvBoardReqStop(pDcChargingInfo->SystemStatus, gunIndex);
-                if (pSysInfo->CurGunSelected == gunIndex) {
-                    pSysInfo->SystemPage = _PAGE_PRECHARGE;
-                }
-                break;
-
-            case S_PREPARING_FOR_EVSE:  // Ground fault test, 等待 Relay Board 通訊及測試,並將狀態回報, CSU 確認 Pass 後,開始進入充電
-                if (isModeChange(gunIndex)) {
-                    log_info("============================= S_PREPARING_FOR_EVSE(%x) ============================= ", gunIndex);
-                    StopGunInfoTimeoutDet(gunIndex);
-                    StartGunInfoTimeoutDet(gunIndex, Timeout_EvseChargingDet);
-                }
-
-                checkPileEndGfdResult(gunIndex, pDcChargingInfo->Type, pDcChargingInfo->SystemStatus);
-
-                checkEvBoardReqStop(pDcChargingInfo->SystemStatus, gunIndex);
-
-                if (pSysInfo->CurGunSelected == gunIndex) {
-                    pSysInfo->SystemPage = _PAGE_PRECHARGE;
-                }
-                break;
-
-            case S_CCS_PRECHARGE_ST0:
-                if (isModeChange(gunIndex)) {
-                    log_info("============================= CCS Precharge Processing 1(%x) ============================= ", gunIndex);
-                    StopGunInfoTimeoutDet(gunIndex);
-                    StartGunInfoTimeoutDet(gunIndex, Timeout_ForCcsPrechargeDet);
-                }
-
-                if (pDcChargingInfo->GroundFaultStatus == GFD_FAIL) {
-                    // GFD 錯誤停止
-                    RecordAlarmCode(gunIndex, "012235");
-                    ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSGfdTrip = YES;
-                }
-
-                checkEvBoardReqStop(pDcChargingInfo->SystemStatus, gunIndex);
-
-                // 等待 EV 小板 (CCS) 通知可以開始 Precharge
-                // 切換 D+ Relay to Precharge Relay
-                if (isPrechargeStatus_ccs(gunIndex) == 39 ||
-                        isPrechargeStatus_ccs(gunIndex) == 40) {
-                    if ((pDcChargingInfo->RelayKPK2Status == YES || pDcChargingInfo->PantographFlag == YES) &&
-                            pDcChargingInfo->PrechargeStatus != PRECHARGE_READY)
-                        //if (pDcChargingInfo->PrechargeStatus != PRECHARGE_PRERELAY_PASS)
-                    {
-
-                        pDcChargingInfo->PrechargeStatus = PRECHARGE_READY;
-                    }
-                } else if (isPrechargeStatus_ccs(gunIndex) == 45 ||
-                           isPrechargeStatus_ccs(gunIndex) == 46
-                          ) {
-                    setChargerMode(gunIndex, MODE_CCS_PRECHARGE_STEP1);
-                }
-                if (pSysInfo->CurGunSelected == gunIndex) {
-                    pSysInfo->SystemPage = _PAGE_PRECHARGE;
-                }
-                break;
-
-            case S_CCS_PRECHARGE_ST1:
-                if (isModeChange(gunIndex)) {
-                    log_info("============================= CCS Precharge Processing 2(%x) ============================= ", gunIndex);
-                }
-
-                if (pDcChargingInfo->GroundFaultStatus == GFD_FAIL) {
-                    // GFD 錯誤停止
-                    RecordAlarmCode(gunIndex, "012235");
-                    ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSGfdTrip = YES;
-                }
-
-                checkEvBoardReqStop(pDcChargingInfo->SystemStatus, gunIndex);
-
-                // 等待小板通知進入充電
-                // 切換 D+ Relay to Precharge Relay
-                if (pDcChargingInfo->RelayK1K2Status == YES || pDcChargingInfo->PantographFlag == YES) {
-                    pDcChargingInfo->PrechargeStatus = PRECHARGE_READY;
-                   // pSysInfo->CurGunSelected = gunIndex;
-                    setChargerMode(gunIndex, MODE_CHARGING);
-                }
-                if (pSysInfo->CurGunSelected == gunIndex) {
-                    pSysInfo->SystemPage = _PAGE_PRECHARGE;
-                }
-                break;
-
-            case S_CHARGING:  // 剛進入充電狀態,等待 EV 小板要求的輸出電流後開始輸出
-                if (isModeChange(gunIndex)) {
-                    log_info("============================= S_CHARGING(%x) ============================= ", gunIndex);
-                    StopGunInfoTimeoutDet(gunIndex);
-                    ftime(&startChargingTime[gunIndex]);
-                    strcpy((char *)ShmOCPP16Data->StartTransaction[gunIndex].ResponseIdTagInfo.Status, ""); //DS60-120 add
-                    ChangeStartOrStopDateTime(YES, gunIndex);
-                    pDcChargingInfo->Replug_flag = FALSE;
-                    ShmDcCommonData->finalcost_flag[gunIndex] = FALSE;
-                    ShmDcCommonData->TransactionInfo[gunIndex].isIntoCharge = TRUE;
-                    ShmDcCommonData->RecordEnergyTime[gunIndex] = time((time_t*)NULL);
-                    UpdateDeductInfoStatus(gunIndex, &ShmDcCommonData->TransactionInfo[gunIndex]);
-                }
-
-                if (ShmOCPP16Data->CpMsg.bits[gunIndex].StartTransactionConf) {
-                    ShmOCPP16Data->CpMsg.bits[gunIndex].StartTransactionConf = NO;
-                }
-                ftime(&endChargingTime[gunIndex]);
-                pDcChargingInfo->PresentChargedDuration = DiffTimeb(startChargingTime[gunIndex], endChargingTime[gunIndex]);
-                ShmDcCommonData->TransactionInfo[gunIndex].Energy = pDcChargingInfo->PresentChargedEnergy;
-
-                // 每秒紀錄使用電量到資料庫內
-                if ((time((time_t*)NULL) - ShmDcCommonData->RecordEnergyTime[gunIndex]) >= 1) {
-                    ShmDcCommonData->RecordEnergyTime[gunIndex] = time((time_t*)NULL);
-                    UpdateDeductInfoStatus(gunIndex, &ShmDcCommonData->TransactionInfo[gunIndex]);
-                }
-
-                if ((time((time_t*)NULL) - ShmDcCommonData->pGunInfo[gunIndex].RecordEnergyTime) >= 5) {
-                    ShmDcCommonData->pGunInfo[gunIndex].RecordEnergyTime = time((time_t*)NULL);
-                    if (ShmDcCommonData->pGunInfo[gunIndex].PowerConsumption != 0)
-                        DB_Update_PowerConsumption(gunIndex, ShmDcCommonData->pGunInfo[gunIndex].PowerConsumption);
-                }
-
-                checkPileEndGfdResult(gunIndex, pDcChargingInfo->Type, pDcChargingInfo->SystemStatus);
-
-                checkEvBoardReqStop(pDcChargingInfo->SystemStatus, gunIndex);
-
-                // Check Stop Charging
-                AuthorizeStopCharging(gunIndex);
-                if (pSysInfo->SystemPage == _PAGE_STOP_CONFIRM_LEFT ||
-                		pSysInfo->SystemPage == _PAGE_STOP_CONFIRM_RIGHT)
-                	break;
-                // LCM => Charging
-                if (pSysInfo->CurGunSelected == gunIndex && pSysInfo->SystemPage != _PAGE_IDLE &&
-                		pSysInfo->SystemPage != _PAGE_SELECT_GUN) {
-                    pSysInfo->SystemPage = _PAGE_CHARGING;
-                }
-                break;
-
-            case S_TERMINATING:
-                if (isModeChange(gunIndex)) {
-                    log_info("============================= S_TERMINATING(%x) ============================= ", gunIndex);
-                    if (strcmp((char *)ShmOCPP16Data->StopTransaction[gunIndex].StopReason, "") == EQUAL) {
-                        strcpy((char *)ShmOCPP16Data->StopTransaction[gunIndex].StopReason, "Local");
-                    }
-                    ShmDcCommonData->StopCharge[gunIndex] = TRUE;
-                    if (ShmDcCommonData->is_AutoStart[gunIndex]) {
-                        ShmDcCommonData->finalcost_flag[gunIndex] = TRUE;
-                        ShmDcCommonData->PayPass_flag[gunIndex] = TRUE;
-                    }
-
-                    if (ShmDcCommonData->finalcost_flag[gunIndex] == FALSE && pSysInfo->CurGunSelected == gunIndex) {
-                        pSysInfo->SystemPage = _PAGE_PAYING;
-                    }
-                    StartSystemTimeoutDet(Timeout_Terminating);
-                    StartGunInfoTimeoutDet(gunIndex, Timeout_FinalCost);
-
-                    ShmDcCommonData->pGunInfo[gunIndex].RecordEnergyTime = time((time_t*)NULL);
-                    if (ShmDcCommonData->pGunInfo[gunIndex].PowerConsumption != 0)
-                        DB_Update_PowerConsumption(gunIndex, ShmDcCommonData->pGunInfo[gunIndex].PowerConsumption);
-                }
-                // For Precharging timeout
-                if (pDcChargingInfo->Type == _Type_Chademo) {
-                    if (isEvStopCharging_chademo(gunIndex) == YES ||
-                            isPrechargeStatus_chademo(gunIndex) <= 0) {
-                        setChargerMode(gunIndex, MODE_COMPLETE);
-                    }
-                } else if (pDcChargingInfo->Type == _Type_GB) {
-                    if (isEvStopCharging_gb(gunIndex) == YES ||
-                            isPrechargeStatus_gb(gunIndex) <= 0) {
-                        setChargerMode(gunIndex, MODE_COMPLETE);
-                    }
-                } else if (pDcChargingInfo->Type == _Type_CCS_2) {
-                    if (isEvStopCharging_ccs(gunIndex) == YES &&
-                            (isPrechargeStatus_ccs(gunIndex) >= 53 ||
-                             isPrechargeStatus_ccs(gunIndex) == 0  ||
-                             isPrechargeStatus_ccs(gunIndex) == 13 ||
-                             isPrechargeStatus_ccs(gunIndex) == 14)
-                       ) {
-                        setChargerMode(gunIndex, MODE_COMPLETE);
-                    }
-                }
-                if (pDcChargingInfo->Replug_flag == TRUE && pSysInfo->CurGunSelected == gunIndex) {
-                    pSysInfo->SystemPage = _PAGE_PLUGOUT;
-                    break;
-                }
-
-                if (pSysInfo->CurGunSelected == gunIndex &&
-                    pSysInfo->SystemPage != _PAGE_PAYING && pSysInfo->SystemPage != _PAGE_SENSING) {
-                    if (ShmDcCommonData->PayPass_flag[gunIndex] == TRUE)
-                        pSysInfo->SystemPage = _PAGE_COMPLETE;
-                    else
-                        pSysInfo->SystemPage = _PAGE_PAYFAIL;
-                }
-                break;
-
-            case S_COMPLETE:
-                if (isModeChange(gunIndex)) {
-                    log_info ("============================= S_COMPLETE(%x) ============================= ", gunIndex);
-                    if (strcmp((char *)pDcChargingInfo->StartDateTime, "") != EQUAL) {
-                        OcppStopTransation(gunIndex);
-                    }
-                    TheEndCharging(gunIndex);
-                    
-                    if (pDcChargingInfo->Replug_flag != TRUE && pSysInfo->SystemPage != _PAGE_PLUGOUT)
-                        StopSystemTimeoutDet();
-                    if (ShmDcCommonData->is_AutoStart[gunIndex] == TRUE && pSysInfo->CurGunSelected == gunIndex)
-                        pSysInfo->SystemPage = _PAGE_COMPLETE;
-                }
-
-                //if (pSysInfo->SystemPage == _LCM_ERROR) {
-                if (pSysInfo->SystemPage == _PAGE_MAINTAIN) {
-                    break;
-                }
-                if (pSysInfo->CurGunSelected == gunIndex && ShmDcCommonData->is_exit[gunIndex]) {
-                	pSysInfo->SystemPage = _PAGE_EXIT;
-                	break;
-                }
-
-                if (pDcChargingInfo->ConnectorPlugIn == NO && 
-                    pSysInfo->SystemPage != _PAGE_PAYING && pSysInfo->SystemPage != _PAGE_SENSING) {
-                    if (pSysInfo->CurGunSelected == gunIndex) {
-                        StartGunInfoTimeoutDet(gunIndex, Timeout_ExitPage);
-                    }
-                    if (pDcChargingInfo->TimeoutFlag != Timeout_ExitPage &&
-                        pDcChargingInfo->TimeoutFlag != Timeout_FinalCost) {
-
-                        StartGunInfoTimeoutDet(gunIndex, Timeout_CompletPlugout);
-                    }
-
-                }
-
-                if (ShmDcCommonData->pGunInfo[gunIndex].isParking) {
-                    ParkingProcess(gunIndex);
-                    break;
-                }
-
-                if (pDcChargingInfo->Replug_flag == TRUE && pSysInfo->CurGunSelected == gunIndex) {
-                    pSysInfo->SystemPage = _PAGE_PLUGOUT;
-                    break;
-                }
-
-                if (pSysInfo->CurGunSelected == gunIndex && 
-                    pSysInfo->SystemPage != _PAGE_PAYING && pSysInfo->SystemPage != _PAGE_SENSING) {
-                    if (ShmDcCommonData->PayPass_flag[gunIndex] == TRUE)
-                        pSysInfo->SystemPage = _PAGE_COMPLETE;
-                    else
-                        pSysInfo->SystemPage = _PAGE_PAYFAIL;
-                }
-
-                break;
-
-            case S_ALARM:
-                if (isModeChange(gunIndex)) {
-                    log_info("============================= S_ALARM(%x)  ============================= ", gunIndex);
-                    if (strcmp((char *)ShmOCPP16Data->StopTransaction[gunIndex].StopReason, "") == EQUAL) {
-                          strcpy((char *)ShmOCPP16Data->StopTransaction[gunIndex].StopReason, "Local");
-                    }
-                    UpdateErrorCodeToOcpp(gunIndex);
-                    if (strcmp((char *)pDcChargingInfo->StartDateTime, "") != EQUAL) {
-                      OcppStopTransation(gunIndex);
-                    }
-                    TheEndCharging(gunIndex);
-                    StopGunInfoTimeoutDet(gunIndex);
-                    ShmDcCommonData->StopCharge[gunIndex] = TRUE;
-
-                    if (ShmDcCommonData->is_AutoStart[gunIndex]) {
-                        ShmDcCommonData->finalcost_flag[gunIndex] = TRUE;
-                        ShmDcCommonData->PayPass_flag[gunIndex] = TRUE;
-                    }
-
-                    if (pDcChargingInfo->Replug_flag == TRUE) {
-
-                    } else {
-                        StartGunInfoTimeoutDet(gunIndex, Timeout_FinalCost);
-						if(ShmDcCommonData->finalcost_flag[gunIndex] == FALSE && pSysInfo->CurGunSelected == gunIndex) {
-							pSysInfo->SystemPage = _PAGE_PAYING;
-						}
-                    }
-                    ShmDcCommonData->pGunInfo[gunIndex].RecordEnergyTime = time((time_t*)NULL);
-                    if (ShmDcCommonData->pGunInfo[gunIndex].PowerConsumption != 0)
-                        DB_Update_PowerConsumption(gunIndex, ShmDcCommonData->pGunInfo[gunIndex].PowerConsumption);
-                }
-
-                if (pSysWarning->Level == WARN_LV_ER) {
-					pSysInfo->SystemPage = _PAGE_MAINTAIN;
-					continue;
-				}
-
-                if (pSysInfo->CurGunSelected == gunIndex && ShmDcCommonData->is_exit[gunIndex]) {
-                    pSysInfo->SystemPage = _PAGE_EXIT;
-                    break;
-                }
-
-                if (pDcChargingInfo->ConnectorPlugIn == NO &&
-                    pSysInfo->SystemPage != _PAGE_PAYING && pSysInfo->SystemPage != _PAGE_SENSING) {
-                    if (pSysInfo->CurGunSelected == gunIndex) {
-                        StartGunInfoTimeoutDet(gunIndex, Timeout_ExitPage);
-                    }
-                    if (pDcChargingInfo->TimeoutFlag != Timeout_ExitPage &&
-                        pDcChargingInfo->TimeoutFlag != Timeout_FinalCost) {
-                        StartGunInfoTimeoutDet(gunIndex, Timeout_CompletPlugout);
-                    }
-                }
-
-                if (ShmDcCommonData->pGunInfo[gunIndex].isParking) {
-                    ParkingProcess(gunIndex);
-                    break;
-                }
-
-                if (pDcChargingInfo->Replug_flag == TRUE && pSysInfo->CurGunSelected == gunIndex) {
-                    pSysInfo->SystemPage = _PAGE_PLUGOUT;
-                    break;
-                }
-
-                if (pSysInfo->CurGunSelected == gunIndex && pSysInfo->SystemPage != _PAGE_PAYING ) {
-                	if (ShmDcCommonData->PayPass_flag[gunIndex] == TRUE)
-						pSysInfo->SystemPage = _PAGE_COMPLETE;
-					else
-						pSysInfo->SystemPage = _PAGE_PAYFAIL;
-				}
-
-                break;
-            case S_MAINTAIN:
-                if (isModeChange(gunIndex)) {
-                    log_info("============================= S_MAINTAIN(%x) ============================= ", gunIndex);
-                    pSysInfo->SystemPage = _PAGE_MAINTAIN;
-                    if (pSysInfo->FirmwareUpdate == YES) {
-                        pSysInfo->SystemPage = _PAGE_MAINTAIN;
-                        continue;
-                    }
-                    if (pDcChargingInfo->IsAvailable == NO) {
-                        log_info("Gun%d is not availbale");
-                        break;
-                    }
-
-                    if (pSysWarning->Level != WARN_LV_ER) {
-                        if (!DisplaySelfTestFailReason()) { //DS60-120 add
-                            log_info("Soft reboot for retry self-tets. ");
-                            sleep(3);
-                            system("killall OcppBackend &");
-                            KillAllTask();
-                            system("/usr/bin/run_evse_restart.sh");
-                        }
-                    }
-                    sleep(3);
-                    if (pSysWarning->Level == WARN_LV_ER) { //DS60-120 add
-                        KillTaskExceptPrimary();
-                    } else {
-                        KillTask();
-                    }
-                    /*
-                    if (pSysInfo->SelfTestSeq == _STEST_FAIL)
-                        StopProcessingLoop();
-                        */
-                }
-
-                if (pSysInfo->SelfTestSeq == _STEST_FAIL && pSysInfo->SystemTimeoutFlag != Timeout_SelftestChk) {
-                    SelfTestRun();
-                    StopSystemTimeoutDet();
-                    sleep(3);
-                    break;
-                }
-                if (pDcChargingInfo->IsAvailable && pSysInfo->SelfTestSeq == _STEST_COMPLETE) {
-                    setChargerMode(gunIndex, MODE_IDLE);
-                }
-                if (pSysInfo->CurGunSelected == gunIndex) {
-                    pSysInfo->SystemPage = _PAGE_MAINTAIN;
-                }
-                break;
-            case S_UPDATE:
-                if (isModeChange(gunIndex)) {
-                    log_info("============================= S_UPDATE ============================= ");
-                }
-                if (pSysInfo->FirmwareUpdate == YES) {
-                    pSysInfo->SystemPage = _PAGE_MAINTAIN;
-                    continue;
-                } else {
-                }
-                break;
-            }//switch
-        }//for
-
-        //if (pSysInfo->SystemPage != _LCM_VIEW)
-        //ChangeLcmByIndex(pSysInfo->SystemPage);
-
-        TryFeedWatchdog();
-        usleep(WHILE_LOOP_TIME);
-    }
-
-    return FAIL;
-}
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <sys/time.h>
+#include <sys/timeb.h>
+#include <sys/types.h>
+#include <sys/ioctl.h>
+#include <sys/socket.h>
+#include <sys/ipc.h>
+#include <sys/shm.h>
+#include <sys/mman.h>
+#include <linux/wireless.h>
+#include <arpa/inet.h>
+#include <netinet/in.h>
+
+#include <unistd.h>
+#include <stdarg.h>
+#include <stdio.h>      /*標準輸入輸出定義*/
+#include <stdlib.h>     /*標準函數庫定義*/
+#include <unistd.h>     /*Unix 標準函數定義*/
+#include <fcntl.h>      /*檔控制定義*/
+#include <termios.h>    /*PPSIX 終端控制定義*/
+#include <errno.h>      /*錯誤號定義*/
+#include <errno.h>
+#include <string.h>
+#include <stdint.h>
+#include <time.h>
+#include <ctype.h>
+#include <ifaddrs.h>
+#include <math.h>
+#include <stdbool.h>
+#include <dirent.h>
+#include <signal.h>
+
+#include "../Config.h"
+#include "main.h"
+#include "../common.h"
+#include "../timeout.h"
+
+#include "../Log/log.h"
+#include "../DataBase/DataBase.h"
+#include "../Define/define.h"
+#include "../ShareMemory/shmMem.h"
+#include "../SelectGun/SelectGun.h"
+
+//------------------------------------------------------------------------------
+static struct SysInfoData *pSysInfo = NULL;
+static struct SysConfigData *pSysConfig = NULL;
+static struct WARNING_CODE_INFO *pSysWarning = NULL;
+
+static struct AlarmCodeData *pAlarmCode = NULL;
+static struct FaultCodeData *pFaultCode = NULL;
+static struct InfoCodeData  *pInfoCode = NULL;
+
+static struct PsuData *ShmPsuData = NULL;
+static struct CHAdeMOData *ShmCHAdeMOData = NULL;
+static struct GBTData *ShmGBTData = NULL;
+static struct CcsData *ShmCcsData = NULL;
+static struct PrimaryMcuData *ShmPrimaryMcuData = NULL;
+static struct FanModuleData *ShmFanModuleData = NULL;
+static struct RelayModuleData *ShmRelayModuleData = NULL;
+static struct LedModuleData *ShmLedModuleData = NULL;
+static struct OCPP16Data *ShmOCPP16Data = NULL;
+static struct OCPP20Data* ShmOCPP20Data = NULL;
+static DcCommonInfo *ShmDcCommonData = NULL;
+
+static struct ChargingInfoData *pDcChargingInfo = NULL;
+static struct ChargingInfoData *pAcChargingInfo = NULL;
+
+static struct timeb startChargingTime[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
+static struct timeb endChargingTime[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
+
+static SelectGunInfo *ShmSelectGunInfo = NULL; //Jerry add
+static EvBoardErrMsg gEvBoardErr = {0};
+static ChillerTempErr gChillerTempErr = {0};
+
+struct SysConfigAndInfo         *ShmSysConfigAndInfo;
+struct StatusCodeData           *ShmStatusCodeData;
+#define DERATING_TARGET_LEVEL 5
+// for initial index to check EV board type is correct
+uint8_t bd0_1_status = 0;
+uint8_t bd0_2_status = 0;
+uint8_t bd1_1_status = 0;
+uint8_t bd1_2_status = 0;
+
+char *fwVersion = "V2.23.00.0000.00"; // Phihong version
+char* DebugVersion = "V2.23.00";      // Software debug version
+//sqlite3 *localDb;
+bool isDb_ready;
+
+//------------------------------------------------------------------------------
+void ClearDetectPluginFlag(int gunIndex);
+
+long long DiffTimebWithNow(struct timeb ST);
+uint8_t DetectBitValue(uint8_t _byte, uint8_t _bit);
+void SetBitValue(uint8_t *_byte, uint8_t _bit, uint8_t value);
+unsigned long GetTimeoutValue(struct timeval _sour_time);
+unsigned long GetClockTimeoutValue(struct timespec _start_time);
+void GetClockTime(struct timespec *_now_time, void *null);
+void gpio_set_value(unsigned int gpio, unsigned int value);
+void InformOcppErrOccur(uint8_t codeType);
+
+void RecordAlarmCode(uint8_t gunIndex, char *code);
+void ReleaseAlarmCode(uint8_t gunIndex);
+void ResetChargerAlarmCode(uint8_t gunIndex, char *code);
+void AdjustChargerCurrent(void);
+void UpdateErrorCodeToOcpp(uint8_t index);
+
+//------------------------------------------------------------------------------
+//Primary.c
+extern void ChkPrimaryStatus(void);
+
+//RFID.c
+extern void CreateRfidFork(void);
+extern void ScannerCardProcess(int gunIndex);
+extern bool RfidStopCharging(void);
+extern bool GetIsCardScan(void);
+extern void SetIsCardScan(bool value);
+
+//SelfTest.c
+extern void SelfTestRun(void);
+
+//UpgradeFW.c
+/*extern void CheckFwUpdateFunction(void);*/
+
+//Ethernet.c
+extern void InitEthernet(void);
+extern void GetMacAddress(void);
+
+//WatchDog.c
+extern void CreateWatchdog(void);
+extern void TryCloseWatchdog(void);
+extern void TryFeedWatchdog(void);
+
+//ZipFile.c
+extern void zipLogFiles(void);
+
+//------------------------------------------------------------------------------
+//--- share memory value ---
+//------------------------------------------------------------------------------
+static void changeLcmPage(uint8_t index)
+{
+    pSysInfo->SystemPage = index;
+}
+
+static uint8_t getCurLcmPage(void)
+{
+    return pSysInfo->SystemPage;
+}
+
+static void systemPageRestoreInit(void)
+{
+    int is_idle = TRUE;
+    int gunIndex;
+    for (gunIndex = 0; gunIndex < pSysConfig->TotalConnectorCount; gunIndex++) {
+        pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(gunIndex);
+        // 檢查電樁狀態是否為idle狀態
+        if ((pDcChargingInfo->SystemStatus >= S_AUTHORIZING &&
+            pDcChargingInfo->SystemStatus <= S_RESERVATION) ||
+            (pDcChargingInfo->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
+            pDcChargingInfo->SystemStatus <= S_CCS_PRECHARGE_ST0)) {
+            is_idle = FALSE;
+        }
+    }
+    if (is_idle)
+        pSysInfo->SystemPage = _PAGE_IDLE;
+    else
+        pSysInfo->SystemPage = _PAGE_SELECT_GUN;
+}
+
+//------------------------------------------------------------------------------
+void destroySelGun(uint8_t curGun)
+{
+    uint8_t i = 0;
+    uint8_t totalGun = pSysConfig->TotalConnectorCount;
+
+    //for status timeout
+    if (curGun == DESTROY_ALL_SEL) {
+        ShmSelectGunInfo->SelGunInfo.RightGun = SEL_GUN_RELEASE;
+        ShmSelectGunInfo->SelGunInfo.LeftGun = SEL_GUN_RELEASE;
+        log_info("destroy all gun = %d, %d",
+                 ShmSelectGunInfo->SelGunInfo.LeftGun,
+                 ShmSelectGunInfo->SelGunInfo.RightGun);
+        for (i = 0; i < totalGun; i++) {
+            StopGunInfoTimeoutDet(i);
+            memset(&ShmSelectGunInfo->PricesInfo[i], 0, sizeof(PricesInfo));
+        }
+        pSysInfo->CurGunSelected = 0;
+        strcpy((char *)pSysConfig->UserId, "");
+        //changeLcmPage(_LCM_VIEW);
+        return;
+    }
+
+    //for charging timeout or complete
+    if ((curGun == LEFT_GUN_NUM) && (ShmSelectGunInfo->SelGunInfo.LeftGun != SEL_GUN_RELEASE)) {
+        if (ShmSelectGunInfo->SelGunInfo.LeftGun == SEL_GUN_CONFIRM ||
+                ShmSelectGunInfo->SelGunInfo.LeftGun == SEL_GUN_ATHOR) {
+            //changeLcmPage(_PAGE_SELECT_GUN);
+        }
+        ShmSelectGunInfo->SelGunInfo.LeftGun = SEL_GUN_RELEASE;
+        StopGunInfoTimeoutDet(LEFT_GUN_NUM);
+        if (ShmOCPP16Data->SpMsg.bits.AuthorizeConf != NO) {
+            ClearAuthorizedFlag();
+        }
+
+        log_info("destroy left gun, cur page = %d", getCurLcmPage());
+        if (getCurLcmPage() == pSysInfo->SystemPage) {
+            log_info("clear left balance");
+            memset(&ShmSelectGunInfo->PricesInfo[curGun], 0, sizeof(PricesInfo));
+            ShmSelectGunInfo->PricesInfo[curGun].Balance = FAIL_BALANCE_PRICES;
+        }
+    }
+
+    if ((curGun == RIGHT_GUN_NUM) && (ShmSelectGunInfo->SelGunInfo.RightGun != SEL_GUN_RELEASE)) {
+        if (ShmSelectGunInfo->SelGunInfo.RightGun == SEL_GUN_CONFIRM ||
+                ShmSelectGunInfo->SelGunInfo.RightGun == SEL_GUN_ATHOR) {
+            //changeLcmPage(_PAGE_SELECT_GUN);
+        }
+        ShmSelectGunInfo->SelGunInfo.RightGun = SEL_GUN_RELEASE;
+        StopGunInfoTimeoutDet(RIGHT_GUN_NUM);
+        if (ShmOCPP16Data->SpMsg.bits.AuthorizeConf != NO) {
+            ClearAuthorizedFlag();
+        }
+
+        log_info("destroy right gun, cur page = %d", getCurLcmPage());
+        if (getCurLcmPage() == pSysInfo->SystemPage) {
+            log_info("clear right balance");
+            memset(&ShmSelectGunInfo->PricesInfo[curGun], 0, sizeof(PricesInfo));
+            ShmSelectGunInfo->PricesInfo[curGun].Balance = FAIL_BALANCE_PRICES;
+        }
+    }
+}
+
+static int waitRightGunPlugIt(uint8_t curGun)
+{
+
+    if ((curGun == RIGHT_GUN_NUM) && (ShmSelectGunInfo->SelGunInfo.RightGun == SEL_GUN_ATHOR)) {
+        return PASS;
+    }
+
+    return FAIL;
+}
+
+static int waitLeftGunPlugIt(uint8_t curGun)
+{
+
+    if ((curGun == LEFT_GUN_NUM) && (ShmSelectGunInfo->SelGunInfo.LeftGun == SEL_GUN_ATHOR)) {
+        return PASS;
+    }
+
+    return FAIL;
+}
+
+void setSelGunWaitToAuthor(uint8_t curSel)
+{
+    if (curSel == LEFT_GUN_NUM && ShmSelectGunInfo->SelGunInfo.LeftGun == SEL_GUN_CONFIRM) {
+        ShmSelectGunInfo->SelGunInfo.LeftGun = SEL_GUN_ATHOR;
+        //log_info("setSelGunWaitToAuthor left");
+        StopGunInfoTimeoutDet(curSel);
+    } else if (curSel == RIGHT_GUN_NUM && ShmSelectGunInfo->SelGunInfo.RightGun == SEL_GUN_CONFIRM) {
+        ShmSelectGunInfo->SelGunInfo.RightGun = SEL_GUN_ATHOR;
+        //log_info("setSelGunWaitToAuthor right");
+        StopGunInfoTimeoutDet(curSel);
+    }
+}
+
+int getConfirmSelectedGun(uint8_t curSel)
+{
+    if (((curSel == LEFT_GUN_NUM) && (ShmSelectGunInfo->SelGunInfo.LeftGun >= SEL_GUN_CONFIRM)) ||
+            ((curSel == RIGHT_GUN_NUM) && (ShmSelectGunInfo->SelGunInfo.RightGun >= SEL_GUN_CONFIRM))) {
+        return PASS;
+    }
+
+    return FAIL;
+}
+
+void confirmSelGun(uint8_t selGun)
+{
+    if (selGun == LEFT_GUN_NUM) {
+        ShmSelectGunInfo->SelGunInfo.LeftGun = SEL_GUN_CONFIRM;
+        //printf("confirmSelGun left");
+    } else if (selGun == RIGHT_GUN_NUM) {
+        ShmSelectGunInfo->SelGunInfo.RightGun = SEL_GUN_CONFIRM;
+        //printf("confirmSelGun right");
+    }
+    //changeLcmPage(_PAGE_PLUGIN);
+
+    //StartGunInfoTimeoutDet(selGun, Timeout_SelectGun);
+    //StartSystemTimeoutDet(Timeout_ReturnViewPage);
+}
+
+static void GetFirmwareVersion(void)
+{
+    // Get CSU root file system version
+    sprintf((char *)pSysInfo->CsuRootFsFwRev, fwVersion);
+    sprintf((char*)ShmDcCommonData->DebugVersion, DebugVersion);
+    uint8_t count = 0, chademo = 0, ccs = 0, gb = 0;
+    for (uint8_t idx = 0; idx < 3; idx++) {
+        if (pSysConfig->ModelName[7 + idx] == 'J') {
+            chademo++;
+            count++;
+        } else if (pSysConfig->ModelName[7 + idx] == 'G') {
+            gb++;
+            count++;
+        } else if (pSysConfig->ModelName[7 + idx] == 'U' ||
+                   pSysConfig->ModelName[7 + idx] == 'V' ||
+                   pSysConfig->ModelName[7 + idx] == 'E') {
+            ccs++;
+            count++;
+        }
+    }
+
+    if (count == 1) {
+        if (chademo > 0) {
+            pSysInfo->CsuRootFsFwRev[7] = '1';
+        } else if (ccs > 0) {
+            pSysInfo->CsuRootFsFwRev[7] = '2';
+        } else if (gb > 0) {
+            pSysInfo->CsuRootFsFwRev[7] = '3';
+        }
+    } else {
+        if (chademo > 0 && ccs > 0) {
+            pSysInfo->CsuRootFsFwRev[7] = '4';
+        } else if (chademo > 0 && gb > 0) {
+            pSysInfo->CsuRootFsFwRev[7] = '5';
+        } else if (ccs > 0 && gb > 0) {
+            pSysInfo->CsuRootFsFwRev[7] = '6';
+        }
+    }
+
+    // Get network option from model name
+    switch (pSysConfig->ModelName[10]) {
+    case 'B':
+    case 'U':
+        //Blue tooth
+        pSysInfo->CsuRootFsFwRev[9] = '3';
+        break;
+    case 'W':
+        // WIFI
+        pSysInfo->CsuRootFsFwRev[9] = '1';
+        break;
+    case 'T':
+        // 3G/4G
+        pSysInfo->CsuRootFsFwRev[9] = '2';
+        break;
+    case 'D': //DS60-120 add
+        pSysInfo->CsuRootFsFwRev[9] = '5';
+        break;
+    default:
+        // LAN
+        pSysInfo->CsuRootFsFwRev[9] = '0';
+        break;
+    }
+    // Get rating power from model name
+    memcpy(&pSysInfo->CsuRootFsFwRev[10], &pSysConfig->ModelName[4], 0x03);
+
+    // Get IEC or UL
+    char _buf[3] = {0};
+    memcpy(_buf, &pSysConfig->ModelName[2], 2);
+
+    if (strcmp(_buf, "YE") == EQUAL || strcmp(_buf, "YC") == EQUAL) {
+        pSysInfo->ChargerType = _CHARGER_TYPE_IEC;
+        log_info("IEC model");
+    } else if (strcmp(_buf, "WU") == EQUAL) {
+        pSysInfo->ChargerType = _CHARGER_TYPE_UL;
+        log_info("UL model");
+    }
+}
+
+static void checkGunOTPState(uint8_t gunIndex)
+{
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+
+    //水冷機溫度檢測
+    if (((ShmDcCommonData->ChillerValve.MultiChillerGun & 0x80) >> 7) == YES) {
+        if (pDcChargingInfo->ChillerTemp != UNDEFINED_TEMP) {
+            if (pDcChargingInfo->ChillerTemp >= GUN_OTP_VALUE) {
+                if (((gunIndex == 0) &&
+                        ((strncmp((char *)&pSysConfig->ModelName[7], "V", 1) == 0) ||
+                         (strncmp((char *)&pSysConfig->ModelName[7], "F", 1) == 0)))
+                         ||
+                    ((gunIndex == 1) &&
+                        ((strncmp((char *)&pSysConfig->ModelName[9], "V", 1) == 0) ||
+                         (strncmp((char *)&pSysConfig->ModelName[9], "F", 1) == 0)))
+                   ) {
+                    RecordAlarmCode(gunIndex, "012323");
+                    ShmDcCommonData->ChillerTempErr[gunIndex].StatusBit.ChillerOTP = YES;
+                }
+                else
+                {
+                    ShmDcCommonData->ChillerTempErr[gunIndex].StatusBit.ChillerOTP = NO;
+                }
+            } else if (pDcChargingInfo->ChillerTemp != 0 &&
+                       pDcChargingInfo->ChillerTemp < GUN_OTP_RECOVERY) {
+                //ResetChargerAlarmCode(gunIndex, "012323");
+                ShmDcCommonData->ChillerTempErr[gunIndex].StatusBit.ChillerOTP = NO;
+            }
+            ShmDcCommonData->ChillerTempErr[gunIndex].StatusBit.ChillerTempSensorFail = NO;
+        } else {
+            // 沒接上 Sensor or 異常
+            //RecordAlarmCode(gunIndex, "011038");
+            //ResetChargerAlarmCode(gunIndex, "012323");
+            ShmDcCommonData->ChillerTempErr[gunIndex].StatusBit.ChillerOTP = NO;
+            if (((gunIndex == 0) &&
+                    ((strncmp((char *)&pSysConfig->ModelName[7], "V", 1) == 0) ||
+                     (strncmp((char *)&pSysConfig->ModelName[7], "F", 1) == 0)))
+                     ||
+                ((gunIndex == 1) &&
+                    ((strncmp((char *)&pSysConfig->ModelName[9], "V", 1) == 0) ||
+                     (strncmp((char *)&pSysConfig->ModelName[9], "F", 1) == 0)))
+               ) {
+                ShmDcCommonData->ChillerTempErr[gunIndex].StatusBit.ChillerTempSensorFail = YES;
+            }
+            else
+            {
+                ShmDcCommonData->ChillerTempErr[gunIndex].StatusBit.ChillerTempSensorFail = NO;
+            }
+        }
+
+        if(pFaultCode->FaultEvents.bits.CcsLiquidChillerWaterLevelFault == YES)
+        {
+            RecordAlarmCode(gunIndex, "011037");
+        }
+    }
+
+    switch (pDcChargingInfo->Type) {
+    case _Type_Chademo:
+        if (pDcChargingInfo->ConnectorTemp != UNDEFINED_TEMP) {
+            if (pDcChargingInfo->ConnectorTemp >= GUN_OTP_VALUE) {
+                RecordAlarmCode(gunIndex, "012229");
+                ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaConnectOTP = YES;
+            } else if (pDcChargingInfo->ConnectorTemp != 0 &&
+                       pDcChargingInfo->ConnectorTemp < GUN_OTP_RECOVERY) {
+                //ResetChargerAlarmCode(gunIndex, "012229");
+                ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaConnectOTP = NO;
+            }
+            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaConnectTempSensorFail = NO;
+        } else {
+            // 沒接上 Sensor or 異常
+            //RecordAlarmCode(gunIndex, "011018");
+            //ResetChargerAlarmCode(gunIndex, "012229");
+            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaConnectOTP = NO;
+            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaConnectTempSensorFail = YES;
+            if  ((gunIndex == 0) &&
+                    (strncmp((char *)&pSysConfig->ModelName[7], "J", 1) == 0)) {
+            	ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaConnectOTP = NO;
+            	ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaConnectTempSensorFail = NO;
+            } else if ((gunIndex == 1) &&
+                    ((strncmp((char *)&pSysConfig->ModelName[9], "J", 1) == 0) )) {
+            	ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaConnectOTP = NO;
+            	ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaConnectTempSensorFail = NO;
+            }
+        }
+        break;
+
+    case _Type_CCS_2:
+        // CCS 不管甚麼輸出都會有槍溫偵測!!~
+        if (pDcChargingInfo->ConnectorTemp != UNDEFINED_TEMP) {
+            //ResetChargerAlarmCode(gunIndex, "011019");
+
+            if (pDcChargingInfo->ConnectorTemp >= GUN_OTP_VALUE) {
+                RecordAlarmCode(gunIndex, "012230");
+                ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSConnectOTP = YES;
+            } else if (pDcChargingInfo->ConnectorTemp != 0 &&
+                       pDcChargingInfo->ConnectorTemp < GUN_OTP_RECOVERY) {
+                //ResetChargerAlarmCode(gunIndex, "012230");
+                ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSConnectOTP = NO;
+            }
+            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSConnectTempSensorFail = NO;
+            //ResetChargerAlarmCode(gunIndex, "011019");
+        } else {
+            // 沒接上 Sensor or 異常
+            //RecordAlarmCode(gunIndex, "011019");
+            //ResetChargerAlarmCode(gunIndex, "012230");
+            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSConnectOTP = NO;
+            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSConnectTempSensorFail = YES;
+        }
+        break;
+
+    case _Type_GB:
+        if (pDcChargingInfo->ConnectorTemp != UNDEFINED_TEMP) {
+            if (pDcChargingInfo->ConnectorTemp >= GUN_OTP_VALUE) {
+                RecordAlarmCode(gunIndex, "012231");
+                ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTConnectOTP = YES;
+            } else if (pDcChargingInfo->ConnectorTemp != 0 &&
+                       pDcChargingInfo->ConnectorTemp < GUN_OTP_RECOVERY) {
+                //ResetChargerAlarmCode(gunIndex, "012231");
+                ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTConnectOTP = NO;
+            }
+            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTConnectTempSensorFail = NO;
+        } else {
+            // 沒接上 Sensor or 異常
+            //RecordAlarmCode(gunIndex, "011020");
+            //ResetChargerAlarmCode(gunIndex, "012231");
+            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTConnectOTP = NO;
+            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTConnectTempSensorFail = YES;
+        }
+        break;
+    }
+}
+
+bool checkGunTempFail(uint8_t gunIndex)
+{
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+    switch (pDcChargingInfo->Type) {
+        case _Type_Chademo:
+            if (ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaConnectTempSensorFail) {
+                RecordAlarmCode(gunIndex,"011018");
+                if (IntoChargeProcess(pDcChargingInfo->SystemStatus)) {
+                    setChargerMode(gunIndex,S_ALARM);
+                }
+
+                if (pDcChargingInfo->SystemStatus == S_IDLE ||
+                   pDcChargingInfo->SystemStatus == S_RESERVATION ) {
+                    memcpy(pDcChargingInfo->ConnectorAlarmCode, "011018", 6);
+                    setChargerMode(gunIndex,S_FAULT);
+                }
+                return TRUE;
+            }
+            break;
+        case _Type_CCS_2:
+            if (ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSConnectTempSensorFail) {
+                RecordAlarmCode(gunIndex,"011019");
+                if (IntoChargeProcess(pDcChargingInfo->SystemStatus)) {
+                    setChargerMode(gunIndex,S_ALARM);
+                }
+
+                if (pDcChargingInfo->SystemStatus == S_IDLE ||
+                   pDcChargingInfo->SystemStatus == S_RESERVATION ) {
+                    memcpy(pDcChargingInfo->ConnectorAlarmCode, "011019", 6);
+                    setChargerMode(gunIndex,S_FAULT);
+                }
+                
+                return TRUE;
+            }
+            break;
+        case _Type_GB:
+            if (ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTConnectTempSensorFail) {
+                RecordAlarmCode(gunIndex,"011020");
+                if (IntoChargeProcess(pDcChargingInfo->SystemStatus)) {
+                    setChargerMode(gunIndex,S_ALARM);
+                }
+
+                if (pDcChargingInfo->SystemStatus == S_IDLE ||
+                   pDcChargingInfo->SystemStatus == S_RESERVATION ) {
+                    memcpy(pDcChargingInfo->ConnectorAlarmCode, "011020", 6);
+                    setChargerMode(gunIndex,S_FAULT);
+                }
+                return TRUE;
+            }
+            break;
+    }
+    return FALSE;
+}
+
+static void collectError(uint8_t gunIndex)
+{
+    gEvBoardErr.GunErrMessage |= ShmDcCommonData->ConnectErrList[gunIndex].GunErrMessage;
+    gChillerTempErr.TempErrMsg |= ShmDcCommonData->ChillerTempErr[gunIndex].TempErrMsg;
+}
+
+static void checkGBTAlarmState(uint8_t gunType)
+{
+    // GFD Trip
+    if (DetectBitValue(gEvBoardErr.GunErrMessage >> (8 * gunType), 0)) {
+        pAlarmCode->AlarmEvents.bits.GbGfdTrip = YES;
+    } else {
+        pAlarmCode->AlarmEvents.bits.GbGfdTrip = NO;
+    }
+
+    // UVP
+    if (DetectBitValue(gEvBoardErr.GunErrMessage >> (8 * gunType), 1)) {
+        pAlarmCode->AlarmEvents.bits.GbtOutputUVPFail = YES;
+    } else {
+        pAlarmCode->AlarmEvents.bits.GbtOutputUVPFail = NO;
+    }
+
+    // OTP
+    if (DetectBitValue(gEvBoardErr.GunErrMessage >> (8 * gunType), 2)) {
+        pAlarmCode->AlarmEvents.bits.GbConnectorOTP = YES;
+    } else {
+        pAlarmCode->AlarmEvents.bits.GbConnectorOTP = NO;
+    }
+
+    // OVP
+    if (DetectBitValue(gEvBoardErr.GunErrMessage >> (8 * gunType), 3)) {
+        pAlarmCode->AlarmEvents.bits.SystemGbOutputOVP = YES;
+    } else {
+        pAlarmCode->AlarmEvents.bits.SystemGbOutputOVP = NO;
+    }
+
+    // GFD Warning
+    if (DetectBitValue(gEvBoardErr.GunErrMessage >> (8 * gunType), 4)) {
+        pAlarmCode->AlarmEvents.bits.GbGroundfaultWarning = YES;
+    } else {
+        pAlarmCode->AlarmEvents.bits.GbGroundfaultWarning = NO;
+    }
+
+    // Relay Welding
+    if (DetectBitValue(gEvBoardErr.GunErrMessage >> (8 * gunType), 5)) {
+        pFaultCode->FaultEvents.bits.GbOutputRelayWelding = YES;
+    } else {
+        pFaultCode->FaultEvents.bits.GbOutputRelayWelding = NO;
+    }
+
+    // Relay Driving
+    if (DetectBitValue(gEvBoardErr.GunErrMessage >> (8 * gunType), 6)) {
+        pFaultCode->FaultEvents.bits.GbOutputRelayDrivingFault = YES;
+    } else {
+        pFaultCode->FaultEvents.bits.GbOutputRelayDrivingFault = NO;
+    }
+
+    // Connect temp Sensor broken
+    if (DetectBitValue(gEvBoardErr.GunErrMessage >> (8 * gunType), 7)) {
+        pFaultCode->FaultEvents.bits.GbConnectorTempSensorBroken = YES;
+    } else {
+        pFaultCode->FaultEvents.bits.GbConnectorTempSensorBroken = NO;
+    }
+}
+
+static void checkCCSAlarmState(uint8_t gunType)
+{
+    // GFD Trip
+    if (DetectBitValue(gEvBoardErr.GunErrMessage >> (8 * gunType), 0)) {
+        pAlarmCode->AlarmEvents.bits.CcsGfdTrip = YES;
+    } else {
+        pAlarmCode->AlarmEvents.bits.CcsGfdTrip = NO;
+    }
+
+    // UVP
+    if (DetectBitValue(gEvBoardErr.GunErrMessage >> (8 * gunType), 1)) {
+        pAlarmCode->AlarmEvents.bits.CcsOutputUVPFail = YES;
+    } else {
+        pAlarmCode->AlarmEvents.bits.CcsOutputUVPFail = NO;
+    }
+
+    // OTP
+    if (DetectBitValue(gEvBoardErr.GunErrMessage >> (8 * gunType), 2)) {
+        pAlarmCode->AlarmEvents.bits.CcsConnectorOTP = YES;
+    } else {
+        pAlarmCode->AlarmEvents.bits.CcsConnectorOTP = NO;
+    }
+
+    // OVP
+    if (DetectBitValue(gEvBoardErr.GunErrMessage >> (8 * gunType), 3)) {
+        pAlarmCode->AlarmEvents.bits.SystemCcsOutputOVP = YES;
+    } else {
+        pAlarmCode->AlarmEvents.bits.SystemCcsOutputOVP = NO;
+    }
+
+    // GFD Warning
+    if (DetectBitValue(gEvBoardErr.GunErrMessage >> (8 * gunType), 4)) {
+        pAlarmCode->AlarmEvents.bits.CcsGroundfaultWarning = YES;
+    } else {
+        pAlarmCode->AlarmEvents.bits.CcsGroundfaultWarning = NO;
+    }
+
+    // Relay Welding
+    if (DetectBitValue(gEvBoardErr.GunErrMessage >> (8 * gunType), 5)) {
+        pFaultCode->FaultEvents.bits.CcsOutputRelayWelding = YES;
+    } else {
+        pFaultCode->FaultEvents.bits.CcsOutputRelayWelding = NO;
+    }
+
+    // Relay Driving
+    if (DetectBitValue(gEvBoardErr.GunErrMessage >> (8 * gunType), 6)) {
+        pFaultCode->FaultEvents.bits.CcsOutputRelayDrivingFault = YES;
+    } else {
+        pFaultCode->FaultEvents.bits.CcsOutputRelayDrivingFault = NO;
+    }
+
+    // Connect temp Sensor broken
+    if (DetectBitValue(gEvBoardErr.GunErrMessage >> (8 * gunType), 7)) {
+        pFaultCode->FaultEvents.bits.CcsConnectorTempSensorBroken = YES;
+    } else {
+        pFaultCode->FaultEvents.bits.CcsConnectorTempSensorBroken = NO;
+    }
+}
+
+static void checkChaDeMoAlarmState(uint8_t gunType)
+{
+    // GFD Trip
+    if (DetectBitValue(gEvBoardErr.GunErrMessage >> (8 * gunType), 0)) {
+        pAlarmCode->AlarmEvents.bits.ChademoGfdTrip = YES;
+    } else {
+        pAlarmCode->AlarmEvents.bits.ChademoGfdTrip = NO;
+    }
+
+    // UVP
+    if (DetectBitValue(gEvBoardErr.GunErrMessage >> (8 * gunType), 1)) {
+        pAlarmCode->AlarmEvents.bits.ChademoOutputUVPFail = YES;
+    } else {
+        pAlarmCode->AlarmEvents.bits.ChademoOutputUVPFail = NO;
+    }
+
+    // OTP
+    if (DetectBitValue(gEvBoardErr.GunErrMessage >> (8 * gunType), 2)) {
+        pAlarmCode->AlarmEvents.bits.ChademoConnectorOTP = YES;
+    } else {
+        pAlarmCode->AlarmEvents.bits.ChademoConnectorOTP = NO;
+    }
+
+    // OVP
+    if (DetectBitValue(gEvBoardErr.GunErrMessage >> (8 * gunType), 3)) {
+        pAlarmCode->AlarmEvents.bits.SystemChademoOutputOVP = YES;
+    } else {
+        pAlarmCode->AlarmEvents.bits.SystemChademoOutputOVP = NO;
+    }
+
+    // GFD Warning
+    if (DetectBitValue(gEvBoardErr.GunErrMessage >> (8 * gunType), 4)) {
+        pAlarmCode->AlarmEvents.bits.ChademoGroundWarning = YES;
+    } else {
+        pAlarmCode->AlarmEvents.bits.ChademoGroundWarning = NO;
+    }
+
+    // Relay Welding
+    if (DetectBitValue(gEvBoardErr.GunErrMessage >> (8 * gunType), 5)) {
+        pFaultCode->FaultEvents.bits.ChademoOutputRelayWelding = YES;
+    } else {
+        pFaultCode->FaultEvents.bits.ChademoOutputRelayWelding = NO;
+    }
+
+    // Relay Driving
+    if (DetectBitValue(gEvBoardErr.GunErrMessage >> (8 * gunType), 6)) {
+        pFaultCode->FaultEvents.bits.ChademoOutputRelayDrivingFault = YES;
+    } else {
+        pFaultCode->FaultEvents.bits.ChademoOutputRelayDrivingFault = NO;
+    }
+
+    // Connect temp Sensor broken
+    if (DetectBitValue(gEvBoardErr.GunErrMessage >> (8 * gunType), 7)) {
+        pFaultCode->FaultEvents.bits.ChademoConnectorTempSensorBroken = YES;
+    } else {
+        pFaultCode->FaultEvents.bits.ChademoConnectorTempSensorBroken = NO;
+    }
+}
+
+static void checkChillerAlarmState(void)
+{
+    if (DetectBitValue(gChillerTempErr.TempErrMsg, 0)) {
+        pAlarmCode->AlarmEvents.bits.SystemChillerOTP = YES;
+    } else {
+        pAlarmCode->AlarmEvents.bits.SystemChillerOTP = NO;
+    }
+
+    if (DetectBitValue(gChillerTempErr.TempErrMsg, 1)) {
+        pFaultCode->FaultEvents.bits.ChillerTempSensorBroken = YES;
+    } else {
+        pFaultCode->FaultEvents.bits.ChillerTempSensorBroken = NO;
+    }
+}
+
+static void checkEvBoardAlarmState(uint8_t gunType)
+{
+    switch (gunType) {
+    case _Type_Chademo:
+        checkChaDeMoAlarmState(gunType);
+        break;
+
+    case _Type_CCS_2:
+        checkCCSAlarmState(gunType);
+        break;
+
+    case _Type_GB:
+        checkGBTAlarmState(gunType);
+        break;
+    }
+}
+
+unsigned long GetTimeoutValue(struct timeval _sour_time)
+{
+    struct timeval _end_time;
+    gettimeofday(&_end_time, NULL);
+
+    return 1000000 * (_end_time.tv_sec - _sour_time.tv_sec) + _end_time.tv_usec - _sour_time.tv_usec;
+}
+
+void GetClockTime(struct timespec *_now_time, void *null)
+{
+    clock_gettime(CLOCK_MONOTONIC, _now_time);
+}
+
+// return value unit: 1us
+unsigned long GetClockTimeoutValue(struct timespec _start_time)
+{
+    struct timespec ts_end;
+    unsigned long ret = 0;
+
+    clock_gettime(CLOCK_MONOTONIC, &ts_end);
+
+    ret = ((unsigned long)(ts_end.tv_sec - _start_time.tv_sec) * 1000000) + ((unsigned long)((ts_end.tv_nsec / 1000) - (_start_time.tv_nsec/ 1000)));
+
+    return ret;
+}
+
+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;
+    return (StopTime - StartTime);
+}
+
+bool CheckTimeOut(struct timeb ST)
+{
+    struct timeb ET;
+    unsigned int StartTime, StopTime;
+
+    ftime(&ET);
+    StartTime = (unsigned int) ST.time;
+    StopTime = (unsigned int) ET.time;
+    return (StopTime > StartTime) ? YES : NO;
+}
+
+void setChargerMode(uint8_t gunIndex, uint8_t mode)
+{
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+
+    pDcChargingInfo->SystemStatus = mode;
+
+}
+
+long long DiffTimebWithNow(struct timeb ST)
+{
+    //return milli-second
+    struct timeb ET;
+    long long StartTime, StopTime;
+
+    ftime(&ET);
+    StartTime = (long long)ST.time;
+    StopTime = (long long)ET.time;
+
+    return ((StopTime - StartTime) * 1000) + (ET.millitm - ST.millitm);
+}
+
+//==========================================
+// Log
+//==========================================
+void CheckFwSlotStatusLog(void)
+{
+    if (bd0_1_status == 0 && bd0_2_status == 1) {
+        log_info("Connector 1 : Chademo");
+    } else if (bd0_1_status == 1 && bd0_2_status == 0) {
+        log_info("Connector 1 : CCS");
+    } else if (bd0_1_status == 1 && bd0_2_status == 1) {
+        log_info("Connector 1 : GB");
+    }
+
+    if (bd1_1_status == 0 && bd1_2_status == 1) {
+        log_info("Connector 2 : Chademo");
+    } else if (bd1_1_status == 1 && bd1_2_status == 0) {
+        log_info("Connector 2 : CCS");
+    } else if (bd1_1_status == 1 && bd1_2_status == 1) {
+        log_info("Connector 2 : GB");
+    }
+}
+
+void CheckHwSlotStatusLog(uint8_t index)
+{
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);
+
+    if (pDcChargingInfo->Type == _Type_Chademo) {
+        log_info("Hw check : Connector %d, Type : Chademo, Evboard_id = %d ",
+                 index, pDcChargingInfo->Evboard_id);
+    } else if (pDcChargingInfo->Type == _Type_CCS_2) {
+        log_info("Hw check : Connector %d, Type : CCS, Evboard_id = %d ",
+                 index, pDcChargingInfo->Evboard_id);
+    } else if (pDcChargingInfo->Type == _Type_GB) {
+        log_info("Hw check : Connector %d, Type : GB, Evboard_id = %d ",
+                 index, pDcChargingInfo->Evboard_id);
+    }
+}
+
+//=================================
+// LCM Page
+//=================================
+void ChangeLcmByIndex(uint8_t page_index)
+{
+    if (pSysWarning->Level != WARN_LV_ER
+       ) {
+        pSysInfo->PageIndex = page_index;
+        //log_info("LCM index:%d",pSysInfo->PageIndex);
+    }
+}
+
+//======================================================
+// Peripheral initial
+//======================================================
+void InitGPIO()
+{
+    /*****************0~3, 4 bank, bank x 32+ num*********************/
+    /***************************************************************/
+    /*************** GPIO 0 ***************************************/
+    /***************************************************************/
+    /* GPMC_AD8         =>  GPIO0_22 *//*ID BD1_1*/
+    system("echo 22 > /sys/class/gpio/export");
+    system("echo \"in\" > /sys/class/gpio/gpio22/direction");
+    /* GPMC_AD9         =>  GPIO0_23 *//*ID BD1_2*/
+    system("echo 23 > /sys/class/gpio/export");
+    system("echo \"in\" > /sys/class/gpio/gpio23/direction");
+    /* GPMC_AD10        =>  GPIO0_26 *//*IO BD1_1*/
+    system("echo 26 > /sys/class/gpio/export");
+    system("echo \"out\" > /sys/class/gpio/gpio26/direction");
+    system("echo 1 > /sys/class/gpio/gpio26/value");
+    /* GPMC_AD11        =>  GPIO0_27 *//*IO BD1_2*/
+    system("echo 27 > /sys/class/gpio/export");
+    system("echo \"in\" > /sys/class/gpio/gpio27/direction");
+    /* RMII1_REF_CLK        =>  GPIO0_29 *//*USB 0 OCP detection*/
+    system("echo 29 > /sys/class/gpio/export");
+    system("echo \"in\" > /sys/class/gpio/gpio29/direction");
+    /*XDMA_EVENT_INTR0  =>  GPIO0_19 *//*AM_RFID_RST*/
+    system("echo 19 > /sys/class/gpio/export");
+    system("echo \"out\" > /sys/class/gpio/gpio19/direction");
+    system("echo 1 > /sys/class/gpio/gpio19/value");
+    /*XDMA_EVENT_INTR1  =>  GPIO0_20 *//*AM_RFID_ICC*/
+    system("echo 20 > /sys/class/gpio/export");
+    system("echo \"in\" > /sys/class/gpio/gpio20/direction");
+    /***************************************************************/
+    /*************** GPIO 1 ***************************************/
+    /***************************************************************/
+    /* GPMC_AD12    =>  GPIO1_12 *//*ID BD2_1*/
+    system("echo 44 > /sys/class/gpio/export");
+    system("echo \"in\" > /sys/class/gpio/gpio44/direction");
+    /* GPMC_AD13    =>  GPIO1_13 *//*ID BD2_2*/
+    system("echo 45 > /sys/class/gpio/export");
+    system("echo \"in\" > /sys/class/gpio/gpio45/direction");
+    /* GPMC_AD14    =>  GPIO1_14 *//*IO BD2_1*/
+    system("echo 46 > /sys/class/gpio/export");
+    system("echo \"out\" > /sys/class/gpio/gpio46/direction");
+    system("echo 0 > /sys/class/gpio/gpio46/value");
+    /* GPMC_AD15    =>  GPIO1_15 *//*IO BD2_2*/
+    system("echo 47 > /sys/class/gpio/export");
+    system("echo \"in\" > /sys/class/gpio/gpio47/direction");
+    /***************************************************************/
+    /*************** GPIO 2 ***************************************/
+    /***************************************************************/
+    /*LCD_AC_BIAS_EN    =>  GPIO2_25*//*RS-485 for module DE control*/
+    system("echo 89 > /sys/class/gpio/export");
+    system("echo \"out\" > /sys/class/gpio/gpio89/direction");
+    system("echo 1 > /sys/class/gpio/gpio89/value");
+    /*LCD_HSYNC     =>  GPIO2_23*//*RS-485 for module RE control*/
+    system("echo 87 > /sys/class/gpio/export");
+    system("echo \"out\" > /sys/class/gpio/gpio87/direction");
+    system("echo 0 > /sys/class/gpio/gpio87/value");
+    /*LCD_PCLK      =>  GPIO2_24*//*CCS communication board 1 proximity*/
+    system("echo 88 > /sys/class/gpio/export");
+    system("echo \"in\" > /sys/class/gpio/gpio88/direction");
+    /*LCD_VSYNC     =>  GPIO2_22*//*CCS communication board 2 proximity*/
+    system("echo 86 > /sys/class/gpio/export");
+    system("echo \"in\" > /sys/class/gpio/gpio86/direction");
+    /***************************************************************/
+    /*************** GPIO 3 ***************************************/
+    /***************************************************************/
+    /*MCASP0_FSX        =>  GPIO3_15*//*Emergency Stop button detect*/
+    system("echo 111 > /sys/class/gpio/export");
+    system("echo \"in\" > /sys/class/gpio/gpio111/direction");
+    /*MCASP0_ACLKR  =>  GPIO3_18*//*USB1 OCP detect*/
+    system("echo 114 > /sys/class/gpio/export");
+    system("echo \"in\" > /sys/class/gpio/gpio114/direction");
+    /*MCASP0_AHCLKR =>  GPIO3_17*//*Emergency IO for AM3352 and STM32F407*/
+    system("echo 113 > /sys/class/gpio/export");
+    system("echo \"in\" > /sys/class/gpio/gpio113/direction");
+    /*MCASP0_ACLKX  =>  GPIO3_14*//*Ethernet PHY reset*/
+    system("echo 110 > /sys/class/gpio/export");
+    system("echo \"out\" > /sys/class/gpio/gpio110/direction");
+    system("echo 0 > /sys/class/gpio/gpio110/value");
+    /* MCASP0_FSR       =>  GPIO3_19 *//*SMR Enable control_1 for Pskill_1*/
+    system("echo 115 > /sys/class/gpio/export");
+    system("echo \"out\" > /sys/class/gpio/gpio115/direction");
+    system("echo 0 > /sys/class/gpio/gpio115/value");
+    /* MCASP0_AXR0  =>  GPIO3_16 *//*CSU board function OK indicator.*/
+    system("echo 112 > /sys/class/gpio/export");
+    system("echo \"out\" > /sys/class/gpio/gpio112/direction");
+    system("echo 1 > /sys/class/gpio/gpio112/value");
+    /* MCASP0_AXR1  =>  GPIO3_20 *//*SMR Enable control_2 for Pskill_2*/
+    system("echo 116 > /sys/class/gpio/export");
+    system("echo \"out\" > /sys/class/gpio/gpio116/direction");
+    system("echo 0 > /sys/class/gpio/gpio116/value");
+
+    log_info("Initial GPIO OK");
+
+    return ;
+
+}
+
+int LoadSysConfigAndInfo()
+{
+    int fd, wrd;
+    unsigned char *buf;
+    unsigned int ChkSum, ChkSumOrg;
+
+    if ((buf = malloc(MtdBlockSize)) == NULL) {
+
+        log_error("malloc buffer NG,rebooting..");
+
+        if (pAlarmCode != NULL) {
+            pAlarmCode->AlarmEvents.bits.CsuInitFailed = 1;
+        }
+        sleep(5);
+        system("reboot -f");
+        sleep(5);
+        system("reboot -f");
+    }
+    memset(buf, 0, MtdBlockSize);
+
+    //================================================
+    // Load configuration from mtdblock10
+    //================================================
+    system("nanddump /dev/mtd10 -f /mnt/EvseConfig.bin");
+    fd = open("/mnt/EvseConfig.bin", O_RDWR);
+    if (fd < 0) {
+        free(buf);
+
+        log_error("open mtdblock10 NG,rebooting..");
+
+        if (pAlarmCode != NULL) {
+            pAlarmCode->AlarmEvents.bits.CsuInitFailed = 1;
+        }
+        sleep(5);
+        system("reboot -f");
+        sleep(5);
+        system("reboot -f");
+    }
+    wrd = read(fd, buf, MtdBlockSize);
+    close(fd);
+    if (wrd < MtdBlockSize) {
+        free(buf);
+
+        log_error("read SysConfigData data NG,rebooting..");
+
+        if (pAlarmCode != NULL) {
+            pAlarmCode->AlarmEvents.bits.CsuInitFailed = 1;
+        }
+        sleep(5);
+        system("reboot -f");
+        sleep(5);
+        system("reboot -f");
+    }
+
+    ChkSum = 0;
+    for (wrd = ARRAY_SIZE(pSysConfig->CsuBootLoadFwRev); wrd < MtdBlockSize - 4; wrd++) {
+        ChkSum += buf[wrd];
+    }
+    memcpy(&ChkSumOrg, buf + (MtdBlockSize - 4), sizeof(ChkSumOrg));
+    memcpy(&pSysConfig->ModelName, buf + (ARRAY_SIZE(pSysConfig->CsuBootLoadFwRev)), ARRAY_SIZE(pSysConfig->ModelName));
+    memcpy(&pSysConfig->SerialNumber, buf + (ARRAY_SIZE(pSysConfig->CsuBootLoadFwRev) + ARRAY_SIZE(pSysConfig->ModelName) + ARRAY_SIZE(pSysConfig->AcModelName)), ARRAY_SIZE(pSysConfig->SerialNumber));
+
+    //================================================
+    // Load configuration from mtdblock11
+    //================================================
+    if (ChkSum != ChkSumOrg) {
+        log_error("Primary SysConfigData checksum NG, read backup");
+        system("nanddump /dev/mtd11 -f /mnt/EvseConfig.bin");
+        fd = open("/mnt/EvseConfig.bin", O_RDWR);
+        if (fd < 0) {
+            free(buf);
+
+            log_error("open mtdblock11 (backup) NG,rebooting..");
+
+            if (pAlarmCode != NULL) {
+                pAlarmCode->AlarmEvents.bits.CsuInitFailed = 1;
+            }
+            sleep(5);
+            system("reboot -f");
+            sleep(5);
+            system("reboot -f");
+        }
+        memset(buf, 0, MtdBlockSize);
+        wrd = read(fd, buf, MtdBlockSize);
+        close(fd);
+        if (wrd < MtdBlockSize) {
+            free(buf);
+
+            log_error("read backup SysConfigData data NG,rebooting..");
+
+            if (pAlarmCode != NULL) {
+                pAlarmCode->AlarmEvents.bits.CsuInitFailed = 1;
+            }
+            sleep(5);
+            system("reboot -f");
+            sleep(5);
+            system("reboot -f");
+        }
+
+        ChkSum = 0;
+        for (wrd = ARRAY_SIZE(pSysConfig->CsuBootLoadFwRev); wrd < MtdBlockSize - 4; wrd++) {
+            ChkSum += buf[wrd];
+        }
+        memcpy(&ChkSumOrg, buf + (MtdBlockSize - 4), sizeof(ChkSumOrg));
+
+        //================================================
+        // Load configuration from mtdblock12 (Factory default)
+        //================================================
+        if (ChkSum != ChkSumOrg) {
+            log_warn("backup SysConfigData checksum NG, read Factory default");
+            system("nanddump /dev/mtd12 -f /mnt/EvseConfig.bin");
+            fd = open("/mnt/EvseConfig.bin", O_RDWR);
+            if (fd < 0) {
+                log_error("open mtdblock12 (Factory default) NG,rebooting..");
+
+                free(buf);
+                if (pAlarmCode != NULL) {
+                    pAlarmCode->AlarmEvents.bits.CsuInitFailed = 1;
+                }
+                sleep(5);
+                system("reboot -f");
+                sleep(5);
+                system("reboot -f");
+            }
+            memset(buf, 0, MtdBlockSize);
+            wrd = read(fd, buf, MtdBlockSize);
+            close(fd);
+            if (wrd < MtdBlockSize) {
+                log_error("read factory default  SysConfigData data NG,rebooting..");
+
+                free(buf);
+                if (pAlarmCode != NULL) {
+                    pAlarmCode->AlarmEvents.bits.CsuInitFailed = 1;
+                }
+                sleep(5);
+                system("reboot -f");
+                sleep(5);
+                system("reboot -f");
+            }
+
+            ChkSum = 0;
+            for (wrd = ARRAY_SIZE(pSysConfig->CsuBootLoadFwRev); wrd < MtdBlockSize - 4; wrd++) {
+                ChkSum += buf[wrd];
+            }
+            memcpy(&ChkSumOrg, buf + (MtdBlockSize - 4), sizeof(ChkSumOrg));
+            memcpy(buf + (ARRAY_SIZE(pSysConfig->CsuBootLoadFwRev)), &pSysConfig->ModelName, ARRAY_SIZE(pSysConfig->ModelName));
+            memcpy(buf + (ARRAY_SIZE(pSysConfig->CsuBootLoadFwRev) + ARRAY_SIZE(pSysConfig->ModelName) + ARRAY_SIZE(pSysConfig->AcModelName)), &pSysConfig->SerialNumber, ARRAY_SIZE(pSysConfig->SerialNumber));
+
+            if (ChkSum != ChkSumOrg) {
+                log_warn("factory default  SysConfigData checksum NG, restore factory default");
+                free(buf);
+                system("cd /root;./FactoryConfig -m");
+                system("rm -f /Storage/OCPP/OCPPConfiguration");
+                system("sync");
+                sleep(5);
+                system("reboot -f");
+                sleep(5);
+                system("reboot -f");
+
+                return FAIL;
+            }
+        }
+    }
+
+    //load OK
+    memcpy(pSysConfig, buf, sizeof(struct SysConfigData));
+    free(buf);
+
+    system("rm -f /mnt/EvseConfig.bin");
+
+    // SysConfig in flash is empty (0xffffffff)
+    if ((strlen((char *)pSysConfig->ModelName) > ARRAY_SIZE(pSysConfig->ModelName)) ||
+            (strlen((char *)pSysConfig->SerialNumber) > ARRAY_SIZE(pSysConfig->SerialNumber)) ||
+            (strlen((char *)pSysConfig->SystemId) > ARRAY_SIZE(pSysConfig->SystemId)) ||
+            (pSysConfig->Eth0Interface.EthDhcpClient == 0xff)) {
+        if (strlen((char *)pSysConfig->ModelName) > ARRAY_SIZE(pSysConfig->ModelName)) {
+            memset(pSysConfig->ModelName, 0x00, ARRAY_SIZE(pSysConfig->ModelName));
+        }
+
+        if (strlen((char *)pSysConfig->SerialNumber) > ARRAY_SIZE(pSysConfig->SerialNumber)) {
+            memset(pSysConfig->SerialNumber, 0x00, ARRAY_SIZE(pSysConfig->SerialNumber));
+        }
+
+        if (strlen((char *)pSysConfig->SystemId) > ARRAY_SIZE(pSysConfig->SystemId)) {
+            memset(pSysConfig->SystemId, 0x00, ARRAY_SIZE(pSysConfig->SystemId));
+        }
+
+        if (pSysConfig->Eth0Interface.EthDhcpClient == 0xff) {
+            log_info("Ethernet dhcp config is null.");
+        }
+
+        if (strlen((char *)pSysConfig->ModelName) == 0x00) {
+            log_info("Model name over length.");
+        }
+
+        if (strlen((char *)pSysConfig->SerialNumber) == 0x00) {
+            log_info("Model serial number over length.");
+        }
+
+        if (strlen((char *)pSysConfig->SystemId) == 0x00) {
+            log_info("SystemId over length.");
+        }
+
+        system("cd /root;./FactoryConfig -m");
+        sleep(3);
+        system("/usr/bin/run_evse_restart.sh");
+    }
+    log_info("Load SysConfigData OK");
+
+
+    return PASS;
+}
+
+int Initialization(void)
+{
+    uint8_t count = 0;
+    uint8_t pinOut[2] = {116, 115};
+
+    // 初始化卡號驗證的 Flag
+    ClearAuthorizedFlag();
+
+    for (count = 0; count < pSysConfig->TotalConnectorCount; count++) {
+        pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(count);
+        // 初始化插槍驗證的 Flag
+        ClearDetectPluginFlag(count);
+
+        pDcChargingInfo->RemoteStartFlag = NO;
+
+        if (pDcChargingInfo->Type == _Type_Chademo) {
+            gpio_set_value(pinOut[count], 0x00);
+            ShmCHAdeMOData->evse[pDcChargingInfo->type_index].SelfTest_Comp = NO;
+        } else if (pDcChargingInfo->Type == _Type_GB) {
+            gpio_set_value(pinOut[count], 0x00);
+            ShmGBTData->evse[pDcChargingInfo->type_index].SelfTest_Comp = NO;
+        } else if (pDcChargingInfo->Type == _Type_CCS_2) {
+            //if (ShmCcsData->CommProtocol == _CCS_COMM_V2GMessage_DIN70121) { //DS60-120 remove
+            if (pSysConfig->TotalConnectorCount == 1) {
+                gpio_set_value(pinOut[1], 0x01);
+            } else {
+                gpio_set_value(pinOut[count], 0x01);
+            }
+            ShmCcsData->V2GMessage_DIN70121[pDcChargingInfo->type_index].SelfTest_Comp = NO;
+            //}
+        }
+
+        strcpy((char *)ShmOCPP16Data->StatusNotification[count].ErrorCode, "NoError");
+    }
+
+    for (count = 0; count < pSysConfig->AcConnectorCount; count++) {
+        pAcChargingInfo = (struct ChargingInfoData *)GetAcChargingInfoData(count);
+
+        pAcChargingInfo->RemoteStartFlag = NO;
+
+        if (pAcChargingInfo->Type == _Type_AC) {
+            pAcChargingInfo->SelfTest_Comp = NO;
+            strcpy((char *)ShmOCPP16Data->StatusNotification[count + pSysConfig->TotalConnectorCount].ErrorCode, "NoError");
+        }
+    }
+
+    return PASS;
+}
+
+bool InitialSystemDefaultConfig()
+{
+    bool result = true;
+
+    LoadSysConfigAndInfo();
+    InitGPIO();
+    InitEthernet();
+    GetMacAddress();
+
+    return result;
+}
+
+//顯示自檢錯誤原因,觸發對應的flag
+bool DisplaySelfTestFailReason()
+{
+    bool result = false;
+    uint8_t index = 0;
+
+    // RB、FB、407、EV 小板中有些板子無回應
+    if (ShmRelayModuleData->SelfTest_Comp == NO) {
+        pAlarmCode->AlarmEvents.bits.RelayboardStestFail = true;
+    }
+
+    if (ShmFanModuleData->SelfTest_Comp == NO) {
+        pAlarmCode->AlarmEvents.bits.FanboardStestFail = true;
+    }
+
+    if (ShmPrimaryMcuData->SelfTest_Comp == NO) {
+        pAlarmCode->AlarmEvents.bits.PrimaryStestFail = true;
+    }
+
+    if (ShmLedModuleData->SelfTest_Comp == NO) {
+        pAlarmCode->AlarmEvents.bits.LedboardStestFail = true;
+    }
+
+    for (index = 0; index < pSysConfig->TotalConnectorCount; index++) {
+        pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);
+
+        if (pDcChargingInfo->Type == _Type_Chademo) {
+            if (ShmCHAdeMOData->evse[pDcChargingInfo->type_index].SelfTest_Comp == NO) {
+                pAlarmCode->AlarmEvents.bits.ChademoboardStestFail = true;
+            }
+        } else if (pDcChargingInfo->Type == _Type_GB) {
+            if (ShmGBTData->evse[pDcChargingInfo->type_index].SelfTest_Comp == NO) {
+                pAlarmCode->AlarmEvents.bits.GbtboardStestFail = true;
+            }
+        } else if (pDcChargingInfo->Type == _Type_CCS_2) {
+            if (ShmCcsData->CommProtocol == _CCS_COMM_V2GMessage_DIN70121) {
+                if (ShmCcsData->V2GMessage_DIN70121[pDcChargingInfo->type_index].SelfTest_Comp == NO) {
+                    pAlarmCode->AlarmEvents.bits.CCSboardStestFail = true;
+                }
+            }
+        }
+    }
+
+    for (index = 0; index < pSysConfig->AcConnectorCount; index++) {
+        pAcChargingInfo = (struct ChargingInfoData *)GetAcChargingInfoData(index);
+
+        // 先借 GBT 顯示
+        if (pAcChargingInfo->SelfTest_Comp == NO) {
+            pAlarmCode->AlarmEvents.bits.AcConnectorStestFail = true;
+        }
+    }
+
+    if (pSysInfo->AcContactorStatus == NO) {
+#if !defined DD360 && !defined DD360Audi && !defined DD360ComBox &&!defined DD360UCar
+        // AC Contact 未搭上
+        pAlarmCode->AlarmEvents.bits.AcContactStestFail = true;
+        result = true;
+#endif // !defined DD360 && !defined DD360Audi && !defined DD360ComBox
+    }
+    //else if (pAlarmCode->AlarmEvents.bits.PsuDipSwitchStestFail == YES) { //DS60-120 add
+    //    result = true;
+    //}
+    else if (ShmPsuData->SystemAvailablePower <= 0 &&
+             ShmPsuData->SystemAvailableCurrent <= 0) {
+        // PSU 通訊問題
+        pAlarmCode->AlarmEvents.bits.PsuModuleStestFail = true;
+        result = true;
+    }
+
+    return result;
+}
+
+//===============================================
+// Common Detect Chk - Stop Charging ?
+//===============================================
+int isEvBoardStopChargeFlag(uint8_t gunIndex)
+{
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+
+    //printf("StopChargeFlag = %d", chargingInfo[gunIndex]->StopChargeFlag);
+    return pDcChargingInfo->StopChargeFlag;
+}
+
+bool isEvBoardNormalStopChargeFlag(uint8_t gunIndex)
+{
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+
+    return pDcChargingInfo->NormalStopChargeFlag;
+}
+
+//===============================================
+// 掃描插槍狀況
+//===============================================
+void ClearDetectPluginFlag(int gunIndex)
+{
+
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+
+    if (pDcChargingInfo->RemoteStartFlag == YES) {
+        pDcChargingInfo->RemoteStartFlag = NO;
+    }
+    ShmDcCommonData->pGunInfo[gunIndex].WaitForPlugit = NO;
+
+    if (pSysInfo->OrderCharging != NO_DEFINE) {
+        pSysInfo->OrderCharging = NO_DEFINE;
+    }
+}
+
+void DetectPluginStart(int gunIndex)
+{
+    //pSysInfo->WaitForPlugit = YES;
+    ShmDcCommonData->pGunInfo[gunIndex].WaitForPlugit = YES;
+}
+
+bool isDetectPlugin(int gunIndex)
+{
+    if (ShmDcCommonData->pGunInfo[gunIndex].WaitForPlugit == YES) {
+        return true;
+    }
+    /*
+    if (pSysInfo->WaitForPlugit == YES) {
+        return true;
+    }
+    */
+    return false;
+}
+
+//===============================================
+// Common Detect Chk - Chademo
+//===============================================
+bool isEvGunLocked_chademo(uint8_t gunIndex)
+{
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+
+    return (DetectBitValue(pDcChargingInfo->GunLocked , 0) == 0) ? NO : YES;
+}
+
+bool isEvContactorWelding_chademo(uint8_t gunIndex)
+{
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+
+    return DetectBitValue(ShmCHAdeMOData->ev[pDcChargingInfo->type_index].EvDetection, 3);
+}
+
+bool isEvStopReq_chademo(uint8_t gunIndex)
+{
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+
+    return DetectBitValue(ShmCHAdeMOData->ev[pDcChargingInfo->type_index].EvDetection, 4);
+}
+
+bool isEvStopCharging_chademo(uint8_t gunIndex)
+{
+    if (isEvGunLocked_chademo(gunIndex) == NO) {
+        // 無鎖槍 = 停止
+        //log_info("gun locked none (%d) ", gunIndex);
+        return YES;
+    }
+
+    return NO;
+}
+
+uint8_t isPrechargeStatus_chademo(uint8_t gunIndex)
+{
+    uint8_t result = 0x00;
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+
+    result = ShmCHAdeMOData->ev[pDcChargingInfo->type_index].PresentMsgFlowStatus;
+
+    return result;
+}
+
+//===============================================
+// Common Detect Chk - GB
+//===============================================
+bool isEvGunLocked_gb(uint8_t gunIndex)
+{
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+
+    return (DetectBitValue(pDcChargingInfo->GunLocked , 0) == 0) ? NO : YES;
+}
+
+bool isEvStopCharging_gb(uint8_t gunIndex)
+{
+    if (isEvGunLocked_gb(gunIndex) == NO) {
+        // 無鎖槍 = 停止
+        //log_info("gun locked none. ");
+        return YES;
+    }
+
+    return NO;
+}
+
+uint8_t isPrechargeStatus_gb(uint8_t gunIndex)
+{
+    uint8_t result = 0x00;
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+
+    result = ShmGBTData->ev[pDcChargingInfo->type_index].PresentMsgFlowStatus;
+
+    return result;
+}
+
+//===============================================
+// Common Detect Chk - CCS
+//===============================================
+bool isEvGunLocked_ccs(uint8_t gunIndex)
+{
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+
+    return (DetectBitValue(pDcChargingInfo->GunLocked , 0) == 0) ? NO : YES;
+}
+
+uint8_t isPrechargeStatus_ccs(uint8_t gunIndex)
+{
+    //uint8_t result = 0x00;
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+
+    return ShmCcsData->V2GMessage_DIN70121[pDcChargingInfo->type_index].PresentMsgFlowStatus;
+}
+
+bool isEvStopCharging_ccs(uint8_t gunIndex)
+{
+    if (isEvGunLocked_ccs(gunIndex) == NO) {
+        // 無鎖槍 = 停止
+        //log_info("gun locked none. ");
+        return YES;
+    }
+
+    return NO;
+}
+
+//===============================================
+// Callback
+//===============================================
+void DisplayChargingInfo()
+{
+    uint8_t i = 0;
+
+    log_info("*********** DisplayChargingInfo *********** ");
+    for (i = 0; i < pSysConfig->TotalConnectorCount; i++) {
+        pDcChargingInfo =  (struct ChargingInfoData *)GetDcChargingInfoData(i);
+
+        if (pDcChargingInfo->SystemStatus != S_IDLE &&
+                pDcChargingInfo->SystemStatus != S_RESERVATION) {
+            ChangeGunSelectByIndex(i);
+            return;
+        }
+    }
+
+    if (pSysConfig->AcConnectorCount > 0 &&
+            pSysInfo->CurGunSelectedByAc == NO_DEFINE)
+    {
+        pAcChargingInfo = (struct ChargingInfoData*)GetAcChargingInfoData(0);
+
+        if (pAcChargingInfo->SystemStatus >= S_PREPARNING &&
+            pAcChargingInfo->SystemStatus <= S_COMPLETE)
+        {
+            pSysInfo->CurGunSelectedByAc = DEFAULT_AC_INDEX;
+        }
+    }
+
+    usleep(50000);
+
+    systemPageRestoreInit();
+}
+
+void _AutoReturnTimeout(int gunIndex)
+{
+    log_info("*********** _AutoReturnTimeout(%d) *********** ", pSysInfo->PageIndex);
+    if (pSysInfo->PageIndex == _PAGE_PRECHARGE) {
+        pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+        pDcChargingInfo->SystemStatus = S_ALARM;
+        //pSysInfo->SystemPage = _LCM_ERROR;
+        pSysInfo->SystemPage = _PAGE_PLUGOUT;
+        ShmDcCommonData->PreAuth_Config = _CREDITCARD_CANCEL;
+        ShmDcCommonData->PreAuth_Result = 0;
+        //pSysInfo->SystemPage = _PAGE_PAYING;
+        //StartGunInfoTimeoutDet(pSysInfo->CurGunSelected,Timeout_FinalCost);
+        ClearDetectPluginFlag(gunIndex);
+    }
+}
+
+void _SelfTestTimeout(void)
+{
+    if (pSysInfo->BootingStatus != BOOT_COMPLETE) {
+        for (uint8_t gunIndex = 0; gunIndex < pSysConfig->TotalConnectorCount; gunIndex++) {
+            setChargerMode(gunIndex, MODE_ALARM);
+        }
+    }
+    ShmPsuData->Work_Step = _NO_WORKING;
+    pSysInfo->SelfTestSeq = _STEST_FAIL;
+    log_info("Self test timeout. ");
+}
+
+void _AuthorizedTimeout(void)
+{
+    int i;
+    //if (IsAuthorizingMode()) {
+        log_info("*********** _AuthorizedTimeout *********** ");
+        StopSystemTimeoutDet();
+        //isCardScan = false;
+        SetIsCardScan(false);
+
+        //StopSystemTimeoutDet();
+        StopGunInfoTimeoutDet(pSysInfo->CurGunSelected);
+        ShmDcCommonData->TradeCancel = TRUE;
+        ShmDcCommonData->PreAuth_Config = _CREDITCARD_CANCEL;
+        ShmDcCommonData->PreAuth_Result = 0;
+        pSysInfo->SystemPage = _PAGE_SENSING;
+        StartSystemTimeoutDet(Timeout_TradeCancel);
+        for (i = 0; i <= 30; i++) {
+            if (ShmDcCommonData->PreAuth_Config == _CREDITCARD_IDLE)
+                break;
+            sleep(1);
+        }
+        ShmDcCommonData->PreAuth_Result = 0;
+
+        StopSystemTimeoutDet();
+        ClearDetectPluginFlag(pSysInfo->CurGunSelected);
+        strcpy((char*)pSysConfig->UserId, "");
+        ClearAuthorizedFlag();
+        setChargerMode(pSysInfo->CurGunSelected, S_IDLE);
+     //   StartSystemTimeoutDet(Timeout_ReturnViewPage);
+    //}
+}
+
+void _DetectPlugInTimeout(uint8_t gunIndex)
+{
+	int i;
+    log_info("*********** Gun%d _DetectPlugInTimeout *********** ",gunIndex);
+    pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(gunIndex);
+    StopSystemTimeoutDet();
+    StopGunInfoTimeoutDet(gunIndex);
+
+    if (pDcChargingInfo->RemoteStartFlag || pDcChargingInfo->isRemoteStart) {
+        StopSystemTimeoutDet();
+        ClearDetectPluginFlag(gunIndex);
+        strcpy((char*)pSysConfig->UserId, "");
+        setChargerMode(gunIndex, S_IDLE);
+        return;
+    }
+    pSysInfo->CurGunSelected = gunIndex;
+	ShmDcCommonData->PreAuth_Config = _CREDITCARD_CANCEL;
+	ShmDcCommonData->PreAuth_Result = 0;
+    pSysInfo->SystemPage = _PAGE_SENSING;
+    ShmDcCommonData->TradeCancel = TRUE;
+    StartSystemTimeoutDet(Timeout_TradeCancel);
+	for(i=0;i<=30;i++) {
+		if(ShmDcCommonData->PreAuth_Config == _CREDITCARD_IDLE)
+			break;
+		sleep(1);
+	}
+	ShmDcCommonData->PreAuth_Result = 0;
+
+    if (pSysInfo->CurGunSelected == gunIndex) {
+        systemPageRestoreInit();
+    }
+    StopSystemTimeoutDet();
+    ClearDetectPluginFlag(gunIndex);
+    strcpy((char *)pSysConfig->UserId, "");
+	setChargerMode(gunIndex, S_IDLE);
+    //systemPageRestoreInit();
+}
+
+void _DetectEvChargingEnableTimeout(uint8_t gunIndex)
+{
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+
+    if (pDcChargingInfo->Type == _Type_Chademo) {
+        if (!isEvGunLocked_chademo(gunIndex)) {
+            log_info("*********** _DetectEvChargingEnableTimeout (chademo) ***********");
+        }
+    } else if (pDcChargingInfo->Type == _Type_GB) {
+        if (!isEvGunLocked_ccs(gunIndex)) {
+            log_info("*********** _DetectEvChargingEnableTimeout (gb) ***********");
+        }
+    } else if (pDcChargingInfo->Type == _Type_CCS_2) {
+        if (!isEvGunLocked_ccs(gunIndex)) {
+            log_info("*********** _DetectEvChargingEnableTimeout (ccs) ***********");
+        }
+    }
+    //pSysInfo->SystemPage = _LCM_ERROR;
+    pSysInfo->SystemPage = _PAGE_MAINTAIN;
+    ChargingTerminalProcess(gunIndex);
+    _AutoReturnTimeout(gunIndex);
+}
+
+void _DetectEvseChargingEnableTimeout(uint8_t gunIndex)
+{
+    log_info("*********** _DetectEvseChargingEnableTimeout (GFD timeout) ***********");
+
+    ChargingTerminalProcess(gunIndex);
+    //pSysInfo->SystemPage = _LCM_ERROR;
+    pSysInfo->SystemPage = _PAGE_MAINTAIN;
+    _AutoReturnTimeout(gunIndex);
+}
+
+void _PrepareTimeout(uint8_t gunIndex)
+{
+    log_info("*********** _PrepareTimeout ***********");
+
+    ChargingTerminalProcess(gunIndex);
+    pAlarmCode->AlarmEvents.bits.PsuNoResource = YES;
+    //pSysInfo->SystemPage = _LCM_ERROR;
+    pSysInfo->SystemPage = _PAGE_MAINTAIN;
+    _AutoReturnTimeout(gunIndex);
+}
+
+void _CcsPrechargeTimeout(uint8_t gunIndex)
+{
+    log_info("*********** _CcsPrechargeTimeout ***********");
+    ChargingTerminalProcess(gunIndex);
+    //pSysInfo->SystemPage = _LCM_ERROR;
+    pSysInfo->SystemPage = _PAGE_MAINTAIN;
+}
+void _LinkErrorTimeout(uint8_t gunIndex)
+{
+	log_info("*********** _LinkErrorTimeout ***********");
+	setChargerMode(pSysInfo->CurGunSelected, S_IDLE);
+    systemPageRestoreInit();
+}
+
+//===============================================
+// 取得卡號與卡號驗證
+//===============================================
+void AuthorizingStart(void)
+{
+    ShmOCPP16Data->SpMsg.bits.AuthorizeReq = YES;
+    pSysInfo->AuthorizeFlag = YES;
+}
+
+void ClearAuthorizedFlag(void)
+{
+    ShmOCPP16Data->SpMsg.bits.AuthorizeConf = NO;
+    pSysInfo->AuthorizeFlag = NO;
+}
+
+bool isAuthorizedComplete(void)
+{
+    if (pSysInfo->AuthorizeFlag == YES) {
+        return false;
+    }
+    return true;
+}
+
+bool IsAuthorizingMode()
+{
+    if (pSysInfo->AuthorizeFlag == NO) {
+        return false;
+    }
+
+    return true;
+}
+
+//===============================================
+// 紀錄 Alarm Code
+//===============================================
+void ResetChargerAlarmCode(uint8_t gunIndex, char *code)
+{
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+
+    if (strcmp(code, "012234") == EQUAL) {
+        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaGfdTrip = NO;
+    } else if (strcmp(code, "012235") == EQUAL) {
+        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSGfdTrip = NO;
+    } else if (strcmp(code, "012236") == EQUAL) {
+        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTGfdTrip = NO;
+    } else if (strcmp(code, "012288") == EQUAL) {
+        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSUvpFail = NO;
+    } else if (strcmp(code, "012289") == EQUAL) {
+        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaUvpFail = NO;
+    } else if (strcmp(code, "012290") == EQUAL) {
+        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTUvpFail = NO;
+    } else if (strcmp(code, "012229") == EQUAL) {
+        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaConnectOTP = NO;
+    } else if (strcmp(code, "012230") == EQUAL) {
+        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSConnectOTP = NO;
+    } else if (strcmp(code, "012231") == EQUAL) {
+        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTConnectOTP = NO;
+    } else if (strcmp(code, "011011") == EQUAL) {
+        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaRelayWeldingFault = NO;
+    } else if (strcmp(code, "011013") == EQUAL) {
+        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSRelayWeldingFault = NO;
+    } else if (strcmp(code, "011015") == EQUAL) {
+        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTRelayWeldingFault = NO;
+    } else if (strcmp(code, "011012") == EQUAL) {
+        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaRelayDrivingFault = NO;
+    } else if (strcmp(code, "011014") == EQUAL) {
+        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSRelayDrivingFault = NO;
+    } else if (strcmp(code, "011016") == EQUAL) {
+        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTRelayDrivingFault = NO;
+    } else if (strcmp(code, "011018") == EQUAL) {
+        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaConnectTempSensorFail = NO;
+    } else if (strcmp(code, "011019") == EQUAL) {
+        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSConnectTempSensorFail = NO;
+    } else if (strcmp(code, "011020") == EQUAL) {
+        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTConnectTempSensorFail = NO;
+    } else if (strcmp(code, "012323") == EQUAL) {
+        ShmDcCommonData->ChillerTempErr[gunIndex].StatusBit.ChillerOTP = NO;
+    } else if (strcmp(code, "011038") == EQUAL) {
+        ShmDcCommonData->ChillerTempErr[gunIndex].StatusBit.ChillerTempSensorFail = NO;
+    }
+
+    if (strncmp((char *)pDcChargingInfo->ConnectorAlarmCode, "012229", 6) == EQUAL ||
+            strncmp((char *)pDcChargingInfo->ConnectorAlarmCode, "012230", 6) == EQUAL ||
+            strncmp((char *)pDcChargingInfo->ConnectorAlarmCode, "012231", 6) == EQUAL ||
+            strncmp((char *)pDcChargingInfo->ConnectorAlarmCode, "011011", 6) == EQUAL ||
+            strncmp((char *)pDcChargingInfo->ConnectorAlarmCode, "011013", 6) == EQUAL ||
+            strncmp((char *)pDcChargingInfo->ConnectorAlarmCode, "011015", 6) == EQUAL ||
+            strncmp((char *)pDcChargingInfo->ConnectorAlarmCode, "011012", 6) == EQUAL ||
+            strncmp((char *)pDcChargingInfo->ConnectorAlarmCode, "011014", 6) == EQUAL ||
+            strncmp((char *)pDcChargingInfo->ConnectorAlarmCode, "011016", 6) == EQUAL ||
+            strncmp((char *)pDcChargingInfo->ConnectorAlarmCode, "011018", 6) == EQUAL ||
+            strncmp((char *)pDcChargingInfo->ConnectorAlarmCode, "011019", 6) == EQUAL ||
+            strncmp((char *)pDcChargingInfo->ConnectorAlarmCode, "011020", 6) == EQUAL ||
+            strncmp((char *)pDcChargingInfo->ConnectorAlarmCode, "012323", 6) == EQUAL ||
+            strncmp((char *)pDcChargingInfo->ConnectorAlarmCode, "011038", 6) == EQUAL) {
+        strncpy((char *)pDcChargingInfo->ConnectorAlarmCode, "", 6);
+    }
+}
+
+void RecordAlarmCode(uint8_t gunIndex, char *code)
+{
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+
+    if((pDcChargingInfo->SystemStatus > S_IDLE && pDcChargingInfo->SystemStatus < S_TERMINATING) ||
+        (pDcChargingInfo->SystemStatus >= S_CCS_PRECHARGE_ST0 && pDcChargingInfo->SystemStatus <= S_CCS_PRECHARGE_ST1))
+    {
+        if (strncmp((char *)pDcChargingInfo->ConnectorAlarmCode, "", 6) == EQUAL) {
+            memcpy(pDcChargingInfo->ConnectorAlarmCode, code, 6);
+        }
+        
+        if (pDcChargingInfo->StopChargeFlag == NO)
+        {
+            log_info("RecordAlarmCode set Stop Charge Flag");
+            pDcChargingInfo->StopChargeFlag = YES;
+        }
+        
+    }
+}
+
+void ReleaseAlarmCode(uint8_t gunIndex)
+{
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+
+    //if (strncmp((char *)pDcChargingInfo->ConnectorAlarmCode, "", 6) == EQUAL) {
+    //    return;
+    //}
+
+    switch (pDcChargingInfo->Type) {
+    case _Type_Chademo:
+        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaGfdTrip = NO;
+        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaUvpFail = NO;
+        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaConnectOVP = NO;
+        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaGfdWarning = NO;
+        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaRelayWeldingFault = NO;
+        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaRelayDrivingFault = NO;
+        break;
+
+    case _Type_CCS_2:
+        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSGfdTrip = NO;
+        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSUvpFail = NO;
+        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSConnectOVP = NO;
+        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSGfdWarning = NO;
+        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSRelayWeldingFault = NO;
+        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSRelayDrivingFault = NO;
+        break;
+
+    case _Type_GB:
+        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTGfdTrip = NO;
+        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTUvpFail = NO;
+        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTConnectOVP = NO;
+        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTGfdWarning = NO;
+        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTRelayWeldingFault = NO;
+        ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTRelayDrivingFault = NO;
+        break;
+    }
+    memcpy(pDcChargingInfo->ConnectorAlarmCode, "", 6);
+}
+
+//===============================================
+// EmergencyStop and Charging Stop
+//===============================================
+void ChargingTerminalProcess(uint8_t gunIndex)
+{
+    pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(gunIndex);
+    //if (pDcChargingInfo->SystemStatus == S_CHARGING)
+    //ShmDcCommonData->StopCharge[gunIndex] = TRUE;
+    setChargerMode(gunIndex, MODE_TERMINATING);
+}
+
+void ChargingAlarmProcess(uint8_t gunIndex)
+{
+    pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(gunIndex);
+    //if (pDcChargingInfo->SystemStatus == S_CHARGING)
+    //ShmDcCommonData->StopCharge[gunIndex] = TRUE;
+    UpdateErrorCodeToOcpp(gunIndex);
+    setChargerMode(gunIndex, MODE_ALARM);
+}
+
+void AcChargingTerminalProcess(void)
+{
+    pAcChargingInfo =  (struct ChargingInfoData *)GetAcChargingInfoData(0);
+
+    pAcChargingInfo->SystemStatus = MODE_TERMINATING;
+}
+
+void StopChargingProcessByString(uint8_t level)
+{
+    if (level > pSysWarning->Level) {
+        pSysWarning->Level = level;
+    }
+}
+
+void ReleaseChargingProcessByString(uint8_t level)
+{
+    if (level >= pSysWarning->Level) {
+        pSysWarning->Level = WARN_LV_NL;
+    }
+}
+
+// 一般錯誤停止充電處理函式
+void BoardErrOccurByString(uint8_t index, char *code)
+{
+    uint8_t level = 1;
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);
+
+    if ((pDcChargingInfo->SystemStatus > S_IDLE &&
+            pDcChargingInfo->SystemStatus < S_TERMINATING) ||
+            (pDcChargingInfo->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
+             pDcChargingInfo->SystemStatus <= S_CCS_PRECHARGE_ST1)) {
+        if (strncmp(code, "023730", 6) == EQUAL &&
+                pInfoCode->InfoEvents.bits.ChademoChargerGetEmergencyStop == NO
+           ) {
+            pInfoCode->InfoEvents.bits.ChademoChargerGetEmergencyStop = YES;
+        }
+        ChargingTerminalProcess(index);
+    }
+
+    StopChargingProcessByString(level);
+}
+
+void ReleaseBoardErrOccurByString(uint8_t index, char *code)
+{
+    bool isTrigger = false;
+    uint8_t level = 1;
+
+    if (strncmp(code, "023730", 6) == 0 &&
+            pInfoCode->InfoEvents.bits.ChademoChargerGetEmergencyStop == YES) {
+        isTrigger = true;
+        pInfoCode->InfoEvents.bits.ChademoChargerGetEmergencyStop = NO;
+    }
+
+    if (isTrigger) {
+        ReleaseChargingProcessByString(level);
+    }
+}
+
+// 急停狀況的停止充電處理函式
+void EmcOccureByString(char *code)
+{
+    uint8_t level = 2;
+    // 嚴重的急停有以下幾種 : EMC 按鈕、Mainbreak、Dooropen
+    // 其錯誤等級為 2
+
+    //DS60-120 remove
+    if (strncmp(code, "012251", 6) == EQUAL ||
+            strncmp(code, "012252", 6) == EQUAL ||
+            strncmp(code, "012238", 6) == EQUAL ||
+            strncmp(code, "042251", 6) == EQUAL ||
+            strncmp(code, "042252", 6) == EQUAL ||
+            strncmp(code, "012304", 6) == EQUAL ||
+            strncmp(code, "042327", 6) == EQUAL ||
+            strncmp(code, "042328", 6) == EQUAL ||
+            strncmp(code, "042200", 6) == EQUAL ||
+            strncmp(code, "042201", 6) == EQUAL ||
+            strncmp(code, "042202", 6) == EQUAL ||
+            strncmp(code, "042267", 6) == EQUAL) {
+        for (uint8_t gun = 0; gun < pSysConfig->TotalConnectorCount; gun++) {
+            pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gun);
+
+            //strncpy((char *)ShmOCPP16Data->StatusNotification[gun].VendorErrorCode, code, 6);
+
+            if ((pDcChargingInfo->SystemStatus > S_IDLE &&
+                    pDcChargingInfo->SystemStatus < S_TERMINATING) ||
+                    (pDcChargingInfo->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
+                     pDcChargingInfo->SystemStatus <= S_CCS_PRECHARGE_ST1)) {
+                //ChargingTerminalProcess(gun);
+                if (strncmp((char *)pDcChargingInfo->ConnectorAlarmCode, "", 6) == EQUAL) {
+                    memcpy(pDcChargingInfo->ConnectorAlarmCode, code, 6);
+                }
+                ChargingAlarmProcess(gun);
+            }
+        }
+
+        StopChargingProcessByString(level);
+        InformOcppErrOccur(4);
+    }
+}
+
+void ReleaseEmsOccureByString(uint8_t index, char *code)
+{
+    bool isTrigger = false;
+    uint8_t level = 2;
+
+    if (strncmp(code, "042251", 6) == 0 ) {
+        isTrigger = true;
+    } else if (strncmp(code, "012251", 6) == 0 &&
+               pAlarmCode->AlarmEvents.bits.EmergencyStopTrip == YES) {
+        isTrigger = true;
+        pAlarmCode->AlarmEvents.bits.EmergencyStopTrip = NO;
+    } else if (strncmp(code, "012252", 6) == 0 &&
+               pAlarmCode->AlarmEvents.bits.DoorOpen == YES) {
+        isTrigger = true;
+        pAlarmCode->AlarmEvents.bits.DoorOpen = NO;
+    } else if (strncmp(code, "012237", 6) == 0 &&
+               pAlarmCode->AlarmEvents.bits.SpdTrip == YES) {
+        isTrigger = true;
+        pAlarmCode->AlarmEvents.bits.SpdTrip = NO;
+    } else if (strncmp(code, "012238", 6) == 0 &&
+               pAlarmCode->AlarmEvents.bits.MainPowerBreakerTrip == YES) {
+        isTrigger = true;
+        pAlarmCode->AlarmEvents.bits.MainPowerBreakerTrip = NO;
+    }
+
+    if (isTrigger) {
+        ReleaseChargingProcessByString(level);
+        InformOcppErrOccur(6);
+    }
+}
+
+static void checkOvpState(uint8_t gunIndex, uint8_t gunType)
+{
+    switch(gunType) {
+        case _Type_Chademo:
+            if(ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaConnectOVP == YES)
+                RecordAlarmCode(gunIndex, "012217");
+            break;
+        case _Type_CCS_2:
+            if(ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSConnectOVP == YES)
+                RecordAlarmCode(gunIndex, "012219");
+            break;
+        case _Type_GB:
+            if(ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTConnectOVP == YES)
+                RecordAlarmCode(gunIndex, "012221");
+            break;
+    }
+}
+
+//===============================================
+// 確認各小板偵測的錯誤狀況
+//===============================================
+void CheckErrorOccurStatus(uint8_t index)
+{
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);
+
+    // RB
+    if (pSysConfig->PhaseLossPolicy == YES) {
+        if (pAlarmCode->AlarmEvents.bits.SystemL1InputUVP == YES ||
+                pAlarmCode->AlarmEvents.bits.SystemL2InputUVP == YES ||
+                pAlarmCode->AlarmEvents.bits.SystemL3InputUVP == YES) {
+            if (pSysWarning->ExtraErrProcess == _EXTRA_ERR_PROCESS_NONE) {
+                pSysWarning->ExtraErrProcess = _EXTRA_ERR_PROCESS_INUVP;
+                StopChargingProcessByString(2);
+                InformOcppErrOccur(13);
+            }
+
+            //DS60-120 add -----
+            if (strncmp((char *)pDcChargingInfo->ConnectorAlarmCode, "", 6) == EQUAL) {
+                if (pAlarmCode->AlarmEvents.bits.SystemL1InputUVP == YES) {
+                    memcpy(pDcChargingInfo->ConnectorAlarmCode, "012203", 6);
+                } else if (pAlarmCode->AlarmEvents.bits.SystemL2InputUVP == YES) {
+                    memcpy(pDcChargingInfo->ConnectorAlarmCode, "012204", 6);
+                } else if (pAlarmCode->AlarmEvents.bits.SystemL3InputUVP == YES) {
+                    memcpy(pDcChargingInfo->ConnectorAlarmCode, "012205", 6);
+                }
+            }
+            log_info("1 CheckErrorOccurStatus");
+            pDcChargingInfo->StopChargeFlag = YES;
+            //------------------------------------------------------------------
+        } else {
+            if (pSysWarning->ExtraErrProcess == _EXTRA_ERR_PROCESS_INUVP) {
+                pSysWarning->ExtraErrProcess = _EXTRA_ERR_PROCESS_NONE;
+                ReleaseChargingProcessByString(2);
+                InformOcppErrOccur(6);
+            }
+        }
+    } else {
+        if (pSysWarning->ExtraErrProcess == _EXTRA_ERR_PROCESS_INUVP) {
+            pSysWarning->ExtraErrProcess = _EXTRA_ERR_PROCESS_NONE;
+            ReleaseChargingProcessByString(2);
+            InformOcppErrOccur(6);
+        }
+    }
+
+    if (pAlarmCode->AlarmEvents.bits.SystemL1InputOVP == YES ||
+            pAlarmCode->AlarmEvents.bits.SystemL2InputOVP == YES ||
+            pAlarmCode->AlarmEvents.bits.SystemL3InputOVP == YES) {
+        if (pSysWarning->ExtraErrProcess == _EXTRA_ERR_PROCESS_NONE) {
+            pSysWarning->ExtraErrProcess = _EXTRA_ERR_PROCESS_INOVP;
+            StopChargingProcessByString(2);
+            InformOcppErrOccur(14);
+        }
+
+        //DS60-120 -----
+        if (strncmp((char *)pDcChargingInfo->ConnectorAlarmCode, "", 6) == EQUAL) {
+            if (pAlarmCode->AlarmEvents.bits.SystemL1InputOVP == YES) {
+                memcpy(pDcChargingInfo->ConnectorAlarmCode, "012200", 6);
+            } else if (pAlarmCode->AlarmEvents.bits.SystemL2InputOVP == YES) {
+                memcpy(pDcChargingInfo->ConnectorAlarmCode, "012201", 6);
+            } else if (pAlarmCode->AlarmEvents.bits.SystemL3InputOVP == YES) {
+                memcpy(pDcChargingInfo->ConnectorAlarmCode, "012202", 6);
+            }
+        }
+        log_info("2 CheckErrorOccurStatus");
+        pDcChargingInfo->StopChargeFlag = YES;
+        //----------------------------------------------------------------------
+    } else {
+        if (pSysWarning->ExtraErrProcess == _EXTRA_ERR_PROCESS_INOVP) {
+            pSysWarning->ExtraErrProcess = _EXTRA_ERR_PROCESS_NONE;
+            ReleaseChargingProcessByString(2);
+            InformOcppErrOccur(6);
+        }
+    }
+
+    checkOvpState(index, pDcChargingInfo->Type);
+
+    //--------------------------------------------------------------------------
+    if (strlen((char *)pDcChargingInfo->ConnectorAlarmCode) == 0) {
+        //Primary
+        if (pAlarmCode->AlarmEvents.bits.EmergencyStopTrip == YES) {
+            memcpy(pDcChargingInfo->ConnectorAlarmCode, "012251", 6);
+        } else if (pAlarmCode->AlarmEvents.bits.DoorOpen == YES) {
+            memcpy(pDcChargingInfo->ConnectorAlarmCode, "012252", 6);
+        } else if (pAlarmCode->AlarmEvents.bits.MainPowerBreakerTrip == YES) {
+            memcpy(pDcChargingInfo->ConnectorAlarmCode, "012238", 6);
+        } else if (pAlarmCode->AlarmEvents.bits.DisconnectedFromDo == YES) {
+            memcpy(pDcChargingInfo->ConnectorAlarmCode, "012304", 6);
+        } else if (pInfoCode->InfoEvents.bits.BackendDisconnectedViaEthernet == YES) {
+            memcpy(pDcChargingInfo->ConnectorAlarmCode, "033900", 6);
+        }
+        //Chiller temperature
+        //else if (pAlarmCode->AlarmEvents.bits.SystemChillerOTP == YES) {
+        //    memcpy(pDcChargingInfo->ConnectorAlarmCode, "012323", 6);
+        //} else if (pFaultCode->FaultEvents.bits.ChillerTempSensorBroken == YES) {
+        //    memcpy(pDcChargingInfo->ConnectorAlarmCode, "011038", 6);
+        //}
+    }
+    /*
+    if (pAlarmCode->AlarmEvents.bits.EmergencyStopTrip == YES ||
+            pAlarmCode->AlarmEvents.bits.MainPowerBreakerTrip == YES ||
+            pAlarmCode->AlarmEvents.bits.DoorOpen == YES ||
+            pSysWarning->ExtraErrProcess != _EXTRA_ERR_PROCESS_NONE ||
+            pAlarmCode->AlarmEvents.bits.PsuFailureAlarm == YES ||
+            pAlarmCode->AlarmEvents.bits.DisconnectedFromDo == YES ||
+            //Power cabinet alarm status
+            ShmDcCommonData->PowerAlarmState.StatusBit.EmergencyStop == YES ||
+            ShmDcCommonData->PowerAlarmState.StatusBit.DoorOpen == YES ||
+            ShmDcCommonData->PowerAlarmState.StatusBit.DcInputOVP == YES ||
+            ShmDcCommonData->PowerAlarmState.StatusBit.DcInputUVP == YES ||
+            ShmDcCommonData->PowerAlarmState.StatusBit.SystemL1InputOVP == YES ||
+            ShmDcCommonData->PowerAlarmState.StatusBit.SystemL2InputOVP == YES ||
+            ShmDcCommonData->PowerAlarmState.StatusBit.SystemL3InputOVP == YES ||
+            ShmDcCommonData->PowerAlarmState.StatusBit.PsuFailure == YES
+       ) {
+        if ((pDcChargingInfo->SystemStatus > S_IDLE &&
+                pDcChargingInfo->SystemStatus < S_COMPLETE) ||
+                (pDcChargingInfo->SystemStatus >= S_CCS_PRECHARGE_ST0  &&
+                        pDcChargingInfo->SystemStatus <= S_CCS_PRECHARGE_ST1 ))
+            ChargingAlarmProcess(index);
+            pSysWarning->Level = WARN_LV_ER;
+    }*/
+}
+
+//===============================================
+// 確認 GPIO 狀態
+//===============================================
+void gpio_set_value(unsigned int gpio, unsigned int value)
+{
+    int fd;
+    char buf[MAX_BUF];
+
+    snprintf(buf, sizeof(buf), SYSFS_GPIO_DIR "/gpio%d/value", gpio);
+    fd = open(buf, O_WRONLY);
+    if (fd < 0) {
+        perror("gpio/set-value");
+        return;
+    }
+
+    if (value) {
+        write(fd, "1", 2);
+    } else {
+        write(fd, "0", 2);
+    }
+
+    close(fd);
+}
+
+int gpio_get_value(unsigned int gpio, unsigned int *value)
+{
+    int fd;
+    char buf[MAX_BUF];
+    char ch;
+
+    snprintf(buf, sizeof(buf), SYSFS_GPIO_DIR "/gpio%d/value", gpio);
+
+    fd = open(buf, O_RDONLY);
+    if (fd < 0) {
+        perror("gpio/get-value");
+        return fd;
+    }
+
+    read(fd, &ch, 1);
+
+    if (ch != '0') {
+        *value = 1;
+    } else {
+        *value = 0;
+    }
+
+    close(fd);
+    return 0;
+}
+
+void CheckGunTypeFromHw()
+{
+    uint8_t i = 0;
+    int pinIn[4] = {22, 23, 44, 45};
+    unsigned int gpioValue = 0;
+    uint8_t tmp[2] = {0};
+
+    log_info("ModelName = %s", pSysConfig->ModelName);
+    for (i = 0; i < ARRAY_SIZE(pinIn); i++) {
+        gpio_get_value(pinIn[i], &gpioValue);
+        switch (pinIn[i]) {
+        //right slot
+        case 22:
+            bd1_1_status = gpioValue;
+            break;
+        case 23:
+            bd1_2_status = gpioValue;
+            break;
+
+        //left slot
+        case 44:
+            bd0_1_status = gpioValue;
+            break;
+        case 45:
+            bd0_2_status = gpioValue;
+            break;
+        }
+    }
+
+    //BD1(Left-CCS-CND1-SMR2-左槍), BD2(Right-CHADEMO-CND2-SMR1-右槍), CCS: 10 , CHAdeMO: 01 , GBT: 11
+    //CcsChargingData [0至1] 分別為 Right至Left
+    //model name 槍順序左至右分別為Right至Left
+    tmp[1] = (bd0_1_status << 4 | bd0_2_status);
+    tmp[0] = (bd1_1_status << 4 | bd1_2_status);
+    for (i = 0; i < 2; i++) {
+        switch (tmp[i]) {
+        case 0x01:
+            log_info("BD%d(%s) = %s ", i + 1, i == 0 ? "Left" : "Right", "CHAdeMO");
+            break;
+
+        case 0x10:
+            log_info("BD%d(%s) = %s ", i + 1, i == 0 ? "Left" : "Right", "CCS");
+            break;
+
+        case 0x11:
+            log_info("BD%d(%s) = %s ", i + 1, i == 0 ? "Left" : "Right", "GBT");
+            break;
+
+        case 0x00:
+            log_info("BD%d(%s) = %s ", i + 1, i == 0 ? "Left" : "Right", "None");
+            break;
+        }
+    }
+}
+
+void CheckGpioInStatus()
+{
+    int i = 0;
+    int pinIn[2] = { 27, 47 };//{IO BD1_2, IO BD2_2}
+    unsigned int gpioValue = 0;
+
+    for (i = 0; i < ARRAY_SIZE(pinIn); i++) {
+        gpio_get_value(pinIn[i], &gpioValue);
+        if (gpioValue == 0x01) {
+            switch (pinIn[i]) {
+            // 小板緊急停止
+            case 47:
+                for (i = 0; i < pSysConfig->TotalConnectorCount; i++) {
+                    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(i);
+
+                    if (pDcChargingInfo->slotsIndex == 1) {
+                        if (pDcChargingInfo->Type == _Type_Chademo) {
+                            BoardErrOccurByString(i, "023730");
+                        } else if (pDcChargingInfo->Type == _Type_CCS_2) {
+                            BoardErrOccurByString(i, "013627");
+                        }
+                        break;
+                    }
+                }
+                break;
+
+            case 27:
+                for (i = 0; i < pSysConfig->TotalConnectorCount; i++) {
+                    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(i);
+
+                    if (pDcChargingInfo->slotsIndex == 3) {
+                        if (pDcChargingInfo->Type == _Type_Chademo) {
+                            BoardErrOccurByString(i, "023730");
+                        } else if (pDcChargingInfo->Type == _Type_CCS_2) {
+                            BoardErrOccurByString(i, "013627");
+                        }
+                        break;
+                    }
+                }
+                break;
+            }
+        } else {
+            switch (pinIn[i]) {
+            // 小板解除緊急停止
+            case 47:
+                for (i = 0; i < pSysConfig->TotalConnectorCount; i++) {
+                    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(i);
+
+                    if (pDcChargingInfo->slotsIndex == 1) {
+                        if (pDcChargingInfo->Type == _Type_Chademo) {
+                            ReleaseBoardErrOccurByString(i, "023730");
+                        } else if (pDcChargingInfo->Type == _Type_CCS_2) {
+                            ReleaseBoardErrOccurByString(i, "013627");
+                        }
+                        break;
+                    }
+                }
+                break;
+
+            case 27:
+                for (i = 0; i < pSysConfig->TotalConnectorCount; i++) {
+                    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(i);
+
+                    if (pDcChargingInfo->slotsIndex == 3) {
+                        if (pDcChargingInfo->Type == _Type_Chademo) {
+                            ReleaseBoardErrOccurByString(i, "023730");
+                        } else if (pDcChargingInfo->Type == _Type_CCS_2) {
+                            ReleaseBoardErrOccurByString(i, "013627");
+                        }
+                        break;
+                    }
+                }
+                break;
+            }
+        }
+    }
+}
+
+//===============================================
+// Main process
+//===============================================
+// 檢查 uint8_t 中某個 Bit 的值
+// _byte : 欲改變的 byte
+// _bit : 該 byte 的第幾個 bit
+uint8_t DetectBitValue(uint8_t _byte, uint8_t _bit)
+{
+    uint8_t mask_table[] = {0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80};
+
+    return ( _byte & mask_table[_bit] ) != 0x00;
+}
+
+// 設定 Byte 中某個 Bit的值
+// _byte : 欲改變的 byte
+// _bit : 該 byte 的第幾個 bit
+// value : 修改的值為 0 or 1
+void SetBitValue(uint8_t *_byte, uint8_t _bit, uint8_t value)
+{
+    if (value == 1) {
+        *_byte |= (1 << _bit);
+    } else if (value == 0) {
+        *_byte ^= (1 << _bit);
+    }
+}
+
+uint8_t isModeChange(uint8_t gunIndex)
+{
+    uint8_t result = NO;
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+
+    if (pDcChargingInfo->SystemStatus == pDcChargingInfo->PreviousSystemStatus) {
+        return result;
+    }
+
+    pDcChargingInfo->PreviousSystemStatus = pDcChargingInfo->SystemStatus;
+    ShmDcCommonData->SystemModeChange[gunIndex] = YES; //for Module_EvRxComm print temperature message
+
+    return YES;
+}
+
+static int checkSlotGpioMappingGunType(uint8_t gunIndex, uint8_t gunType)
+{
+    uint8_t slot1 = 0, slot2 = 0;
+
+    if (gunIndex == 0) {
+        slot1 = bd0_1_status;
+        slot2 = bd0_2_status;
+    } else if (gunIndex == 1) {
+        slot1 = bd1_1_status;
+        slot2 = bd1_2_status;
+    }
+
+    log_info("slot %d gpio1 = %d, gpio2 = %d, type = %d",
+             gunIndex,
+             slot1,
+             slot2,
+             gunType);
+
+    switch (gunType) {
+    case _Type_Chademo:
+        if (slot1 != NO && slot2 != YES) {
+            return FAIL;
+        }
+        break;
+
+    case _Type_CCS_2:
+        if (slot1 != YES && slot2 != NO) {
+            return FAIL;
+        }
+        break;
+
+    case _Type_GB:
+        if (slot1 != YES && slot2 != YES) {
+            return FAIL;
+        }
+        break;
+    }
+
+    return PASS;
+}
+
+bool CheckConnectorTypeStatus(void)
+{
+    bool result = true;
+
+    uint8_t gunIndex = 0;
+    struct SysConfigData *pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
+    struct ChargingInfoData *pDcChargingInfo = NULL;
+
+    if (!MappingGunChargingInfo("CSU Task")) {
+        log_error("CheckConnectorTypeStatus MappingGunChargingInfo failed");
+        return false;
+    }
+
+    // 偵測槍屬於哪個 slot : 可知道插在板上的Slot 0 或 1 是 Chademo 還是 CCS
+    for (gunIndex = 0; gunIndex < pSysConfig->TotalConnectorCount; gunIndex++) {
+        pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+
+        if (checkSlotGpioMappingGunType(gunIndex, pDcChargingInfo->Type) == FAIL) {
+            return false;
+        }
+
+		pDcChargingInfo->SystemStatus = S_BOOTING;
+        switch (gunIndex) {
+        case 0:
+            if (pSysConfig->TotalConnectorCount == 1) {
+                if ((bd0_1_status == YES || bd0_2_status == YES) &&
+                        (bd1_1_status == NO && bd1_2_status == NO)) {
+                    pDcChargingInfo->Evboard_id = 0x01;
+                }
+
+                if ((bd0_1_status == NO && bd0_2_status == NO) &&
+                        (bd1_1_status == YES || bd1_2_status == YES)
+                   ) {
+                    pDcChargingInfo->Evboard_id = 0x02;
+                }
+                break;
+            }
+
+            pDcChargingInfo->Evboard_id = 0x01;
+            break;
+
+        case 1:
+            pDcChargingInfo->Evboard_id = 0x02;
+            break;
+        }
+
+        CheckHwSlotStatusLog(gunIndex);
+
+        if (pDcChargingInfo->Evboard_id == 0x00) {
+            return false;
+        }
+    }
+
+    AdjustChargerCurrent();
+
+    return result;
+}
+
+int SpawnTask(void)
+{
+    if(SIMULATION)
+        system("/root/simulation &");
+    sleep(2);
+    system("/root/Module_EventLogging &");
+    system("/root/Module_PrimaryComm &");
+    system("/root/Module_EvComm &");
+    system("/root/Module_LcmControl &");
+    system("/root/Module_InternalComm &");
+    system("/root/Module_ProduceUtils &");
+    system("/root/Module_UpdateFW &");
+    system("/root/Module_DoComm &");
+
+    return PASS;
+}
+
+void KillTask(void)
+{
+    //ChangeLcmByIndex(_LCM_ERROR);
+    ChangeLcmByIndex(_PAGE_MAINTAIN);
+    system("killall Module_EventLogging");
+    system("killall Module_PrimaryComm");
+    system("killall Module_EvComm");
+    system("killall Module_LcmControl");
+    system("killall Module_InternalComm");
+    system("killall Module_UpdateFW");
+    system("killall Module_ChkSysTask");
+    //system("killall Module_DoComm");
+    return ;
+}
+
+void KillTaskExceptPrimary(void)
+{
+    //ChangeLcmByIndex(_LCM_ERROR);
+    ChangeLcmByIndex(_PAGE_MAINTAIN);
+    system("killall Module_EvComm");
+    system("killall Module_InternalComm");
+    return;
+}
+
+void KillAllTask(void)
+{
+    //ChangeLcmByIndex(_LCM_ERROR);
+    ChangeLcmByIndex(_PAGE_MAINTAIN);
+    system("killall Module_EventLogging");
+    system("killall Module_PrimaryComm");
+    system("killall Module_EvComm");
+    system("killall Module_LcmControl");
+    system("killall Module_InternalComm");
+    system("killall Module_UpdateFW");
+    system("killall Module_ChkSysTask");
+    system("killall Module_DoComm");
+    return ;
+
+}
+
+void StartSystemTimeoutDet(uint8_t flag)
+{
+    if (pSysInfo->SystemTimeoutFlag != flag) {
+        //log_info("Set System Timeout Flag %d", flag);
+        GetClockTime(&pSysInfo->SystemTimeoutTimer, NULL);
+    }
+    pSysInfo->SystemTimeoutFlag = flag;
+}
+
+void StopSystemTimeoutDet(void)
+{
+    GetClockTime(&pSysInfo->SystemTimeoutTimer, NULL);
+    pSysInfo->SystemTimeoutFlag = Timeout_None;
+}
+
+void StartGunInfoTimeoutDet(uint8_t gunIndex, uint8_t flag)
+{
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+
+    if (gunIndex < pSysConfig->TotalConnectorCount) {
+        if (pDcChargingInfo->TimeoutFlag != flag) {
+            GetClockTime(&pDcChargingInfo->ConnectorTimeout, NULL);
+            //log_info("Set Gun%d Timeout Flag %d", gunIndex, flag);
+        }
+        pDcChargingInfo->TimeoutFlag = flag;
+    }
+}
+
+void StopGunInfoTimeoutDet(uint8_t gunIndex)
+{
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+
+    if (gunIndex < pSysConfig->TotalConnectorCount) {
+        pDcChargingInfo->TimeoutFlag = Timeout_None;
+    }
+}
+
+void CheckConnectionTimeout(void)
+{
+    if (ShmSelectGunInfo->RemoteSetup.ConnectionTimeout != 0) { //Jerry add
+        _connectionTimeout = ShmSelectGunInfo->RemoteSetup.ConnectionTimeout;
+    } else {
+        _connectionTimeout = CONN_PLUG_TIMEOUT;
+    }
+    return;
+}
+void _evccidlinktimeout(uint8_t gunIndex)
+{
+    log_info("Getting EVCCID Timeout");
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+    pDcChargingInfo->isEVCCIDVerify = true;
+    StopGunInfoTimeoutDet(gunIndex);
+    destroySelGun(pSysInfo->CurGunSelected);
+    systemPageRestoreInit();
+}
+void CreateTimeoutFork(void)
+{
+    pid_t timeoutPid;
+
+    timeoutPid = fork();
+    if (timeoutPid == 0) {
+        GetClockTime(&_cmdSubPriority_time, NULL);
+        CheckConnectionTimeout();
+
+        //log_info("Timeout Fork Child's PID is %d", getpid());
+
+        while (1) {
+            if ((GetClockTimeoutValue(_cmdSubPriority_time) / 1000) > 5000) {
+                CheckConnectionTimeout();
+                GetClockTime(&_cmdSubPriority_time, NULL);
+            }
+            /*
+            if (pSysInfo->SystemTimeoutFlag != 0)
+            log_info("Timeout ***********SystemTimeoutFlag = %d(%d) ********",pSysInfo->SystemTimeoutFlag,
+                    GetClockTimeoutValue(pSysInfo->SystemTimeoutTimer) / uSEC_VAL);
+            */      
+            // 系統
+            switch (pSysInfo->SystemTimeoutFlag) {
+            case Timeout_SelftestChk:
+                if (GetClockTimeoutValue(pSysInfo->SystemTimeoutTimer) / uSEC_VAL >= SELFTEST_TIMEOUT) {
+                    _SelfTestTimeout();
+                    StopSystemTimeoutDet();
+                    destroySelGun(DESTROY_ALL_SEL); //jerry add
+                }
+                break;
+            case Timeout_ReturnViewPage:
+                if (GetClockTimeoutValue(pSysInfo->SystemTimeoutTimer) / uSEC_VAL >= RETURN_VIEWPAGE_TIMEOUT) {
+                    StopSystemTimeoutDet();
+                    systemPageRestoreInit();
+                }
+            	break;
+            case Timeout_Authorizing:
+                if (GetClockTimeoutValue(pSysInfo->SystemTimeoutTimer) / uSEC_VAL >= AUTHORIZE_TIMEOUT) {
+                    log_error("Authorizing Timeout");
+                    _AuthorizedTimeout();
+                    if (ShmSelectGunInfo->AuthorStateFromCabinet[pSysInfo->CurGunSelected] == YES) { //DoComm no ask cabinet balance
+                        ShmSelectGunInfo->AuthorStateFromCabinet[pSysInfo->CurGunSelected] = NO;
+                        pAlarmCode->AlarmEvents.bits.DisconnectedFromDo = ABNORMAL;
+                        log_error("Author timeout restart DoComm");
+                        system("killall Module_DoComm");
+                    }
+                }
+                break;
+            case Timeout_WaitBalance:
+                if (GetClockTimeoutValue(pSysInfo->SystemTimeoutTimer) / uSEC_VAL >= BALANCE_TIMEOUT) {
+                    log_error("Wait Balance timeout");
+                    _AuthorizedTimeout();
+                    if (ShmSelectGunInfo->AuthorStateFromCabinet[pSysInfo->CurGunSelected] == YES) { //DoComm no ask cabinet balance
+                        ShmSelectGunInfo->AuthorStateFromCabinet[pSysInfo->CurGunSelected] = NO;
+                        pAlarmCode->AlarmEvents.bits.DisconnectedFromDo = ABNORMAL;
+                        log_error("Author timeout restart DoComm");
+                        system("killall Module_DoComm");
+                    }
+                }
+                break;
+            case Timeout_VerifyFail:
+                if (GetClockTimeoutValue(pSysInfo->SystemTimeoutTimer) / uSEC_VAL >= AUTHORIZE_FAIL_TIMEOUT) {
+                    log_info("Timeout_VerifyFail");
+                    StopSystemTimeoutDet();
+                    systemPageRestoreInit();
+                    if (!ShmDcCommonData->pGunInfo[pSysInfo->CurGunSelected].ParkingStatus)
+                        setChargerMode(pSysInfo->CurGunSelected, S_IDLE);
+                    ShmDcCommonData->OperateIDLE[pSysInfo->CurGunSelected] = 1;
+                    ShmDcCommonData->pGunInfo[pSysInfo->CurGunSelected].GetParkingBill = FALSE;
+                }
+                break;
+                /*
+            case Timeout_WaitPlug:
+                if (GetClockTimeoutValue(pSysInfo->SystemTimeoutTimer) / uSEC_VAL >= _connectionTimeout) {
+                    _DetectPlugInTimeout();
+
+                    destroySelGun(pSysInfo->CurGunSelected);
+                }
+                break;
+                */
+/*
+            case Timeout_ReturnToChargingGunDet:
+                if (GetClockTimeoutValue(pSysInfo->SystemTimeoutTimer) / uSEC_VAL >= RETURN_TO_CHARGING_PAGE) {
+                    if (getCurLcmPage() != _LCM_VIEW &&
+                            getCurLcmPage() != _LCM_DETAIL_VIEW ) {
+                        destroySelGun(pSysInfo->CurGunSelected); //jerry add
+
+                    }
+                    DisplayChargingInfo();
+                    StopSystemTimeoutDet();
+                }
+                break;
+*/
+
+
+            case Timeout_ScanCard:
+				if (GetClockTimeoutValue(pSysInfo->SystemTimeoutTimer) / uSEC_VAL >= TCC_SCANCARD_TIMEOUT) {
+                    log_info("Timeout_ScanCard");
+					strcpy((char *)pSysConfig->UserId, "");
+					ClearAuthorizedFlag();
+					StopSystemTimeoutDet();
+                    pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(pSysInfo->CurGunSelected);
+                    pDcChargingInfo->SystemStatus = S_IDLE;
+					pSysInfo->SystemPage = _PAGE_AUTHORIZE_FAIL;
+                    ShmDcCommonData->OperateIDLE[pSysInfo->CurGunSelected] = 1;
+				}
+				break;
+            case Timeout_Terminating:
+                if (GetClockTimeoutValue(pSysInfo->SystemTimeoutTimer) / uSEC_VAL >= TERMINATING_TIMEOUT) {
+                    StopSystemTimeoutDet();
+                    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(pSysInfo->CurGunSelected);
+                    log_info("Terminating timeout");
+                    setChargerMode(pSysInfo->CurGunSelected, S_COMPLETE);
+                }
+                break;
+            case Timeout_AddLine:
+            	if (GetClockTimeoutValue(pSysInfo->SystemTimeoutTimer) / uSEC_VAL >= TCC_ADDLINE_TIMEOUT) {
+                    log_info("Timeout_AddLine");
+            		StopSystemTimeoutDet();
+                    systemPageRestoreInit();
+                    ShmDcCommonData->OperateIDLE[pSysInfo->CurGunSelected] = 1;
+            	}
+            	break;
+
+            case Timeout_DonateComfirm:
+            	if (GetClockTimeoutValue(pSysInfo->SystemTimeoutTimer) / uSEC_VAL >= TCC_DONATECOMFIRM_TIMEOUT) {
+                    log_info("Timeout_DonateComfirm");
+            		StopSystemTimeoutDet();
+                    systemPageRestoreInit();
+            	}
+            	break;
+            case Timeout_SelectPayMode:
+            	if (GetClockTimeoutValue(pSysInfo->SystemTimeoutTimer) / uSEC_VAL >= TCC_SELECTPAY_TIMEOUT) {
+                    log_info("Timeout_SelectPayMode");
+            		StopSystemTimeoutDet();
+                    systemPageRestoreInit();
+                    ShmDcCommonData->OperateIDLE[pSysInfo->CurGunSelected] = 1;
+            	}
+            	break;
+            case Timeout_TradeCancel:
+                if (GetClockTimeoutValue(pSysInfo->SystemTimeoutTimer) / uSEC_VAL >= TCC_TRADECANCEL_TIMEOUT) {
+                    log_info("Timeout_TradeCancel");
+                    StopSystemTimeoutDet();
+                    pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(pSysInfo->CurGunSelected);
+                    setChargerMode(pSysInfo->CurGunSelected, MODE_IDLE);
+                    systemPageRestoreInit();
+                    ShmDcCommonData->OperateIDLE[pSysInfo->CurGunSelected] = 1;
+                    ShmDcCommonData->pGunInfo[pSysInfo->CurGunSelected].GetParkingBill = FALSE;
+                }
+                break;
+            case Timeout_LINEPAYING:
+                if (GetClockTimeoutValue(pSysInfo->SystemTimeoutTimer) / uSEC_VAL >= TCC_LINEPAYING_TIMEOUT) {
+                    log_info("Timeout_LINEPAYING");
+                    StopSystemTimeoutDet();
+                    systemPageRestoreInit();
+                    ShmDcCommonData->OperateIDLE[pSysInfo->CurGunSelected] = 1;
+                }
+                break;
+            }
+
+            // 各槍
+            for (uint8_t gunIndex = 0; gunIndex < pSysConfig->TotalConnectorCount; gunIndex++) {
+                pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+                /*
+                if (pDcChargingInfo->TimeoutFlag != 0)
+                log_info("Timeout ***********GunTimeoutFlag = %d(%d) ********",pDcChargingInfo->TimeoutFlag,
+                        GetClockTimeoutValue(pDcChargingInfo->ConnectorTimeout) / uSEC_VAL);
+                */       
+                switch (pDcChargingInfo->TimeoutFlag) {
+
+                case Timeout_AuthorizingForStop:
+                    if (GetClockTimeoutValue(pDcChargingInfo->ConnectorTimeout) / uSEC_VAL >= AUTHORIZE_STOP_TIMEOUT) {
+                        log_info("Gun %d Timeout_AuthorizingForStop", gunIndex);
+                        strcpy((char*)pSysConfig->UserId, "");
+                        pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(gunIndex);
+                        pDcChargingInfo->SystemStatus = S_IDLE;
+                        ClearAuthorizedFlag();
+                        StopGunInfoTimeoutDet(gunIndex);
+                        if (pSysInfo->CurGunSelected == gunIndex)
+                            systemPageRestoreInit();
+                    }
+                    break;
+                case Timeout_WaitPlug:
+                    if (GetClockTimeoutValue(pDcChargingInfo->ConnectorTimeout) / uSEC_VAL >= _connectionTimeout) {
+                        _DetectPlugInTimeout(gunIndex);
+                        destroySelGun(gunIndex);
+                    }
+                    break;
+                case Timeout_EVCCID_Link:
+                if (GetClockTimeoutValue(pDcChargingInfo->ConnectorTimeout) / uSEC_VAL >= EVCCID_LINK_TIMEOUT) {
+                    _evccidlinktimeout(gunIndex);
+                	}
+                break;
+                case Timeout_LinkError:
+                    if (GetClockTimeoutValue(pDcChargingInfo->ConnectorTimeout) / uSEC_VAL >= LINKERROR_TIMEOUT) {
+                    	_LinkErrorTimeout(gunIndex);
+                    	StopGunInfoTimeoutDet(gunIndex);
+                        destroySelGun(gunIndex);
+                    }
+                	break;
+                case Timeout_Preparing:
+                    if (GetClockTimeoutValue(pDcChargingInfo->ConnectorTimeout) / uSEC_VAL >= GUN_PREPARE_TIMEOUT) {
+                        _PrepareTimeout(gunIndex);
+                        StopGunInfoTimeoutDet(gunIndex);
+                        destroySelGun(gunIndex); //jerry add
+                    }
+                    break;
+
+                case Timeout_EvChargingDet:
+                    if (GetClockTimeoutValue(pDcChargingInfo->ConnectorTimeout) / uSEC_VAL >= GUN_EV_WAIT_TIMEOUT) {
+                        _DetectEvChargingEnableTimeout(gunIndex);
+                        StopGunInfoTimeoutDet(gunIndex);
+                        destroySelGun(gunIndex); //jerry add
+                    }
+                    break;
+
+                case Timeout_EvseChargingDet:
+                    if (GetClockTimeoutValue(pDcChargingInfo->ConnectorTimeout) / uSEC_VAL >= GUN_EVSE_WAIT_TIMEOUT) {
+                        _DetectEvseChargingEnableTimeout(gunIndex);
+                        StopGunInfoTimeoutDet(gunIndex);
+                        destroySelGun(gunIndex); //jerry add
+                    }
+                    break;
+
+                case Timeout_EvseCompleteDet:
+                    if (GetClockTimeoutValue(pDcChargingInfo->ConnectorTimeout) / uSEC_VAL >= GUN_COMP_WAIT_TIMEOUT) {
+                        StopGunInfoTimeoutDet(gunIndex);
+                        destroySelGun(gunIndex); //jerry add
+                    }
+                    break;
+
+                case Timeout_ForCcsPrechargeDet:
+                    if (GetClockTimeoutValue(pDcChargingInfo->ConnectorTimeout) / uSEC_VAL >= GUN_PRECHARGING_TIMEOUT) {
+                        _CcsPrechargeTimeout(gunIndex);
+                        StopGunInfoTimeoutDet(gunIndex);
+                        destroySelGun(gunIndex); //jerry add
+                    }
+                    break;
+                case Timeout_PlugOutGun:
+                    if (GetClockTimeoutValue(pDcChargingInfo->ConnectorTimeout) / uSEC_VAL >= PLUGOUTGUN_TIMEOUT) {
+                        log_info("Gun[%d] Timeout_PlugOutGun",gunIndex);
+                        setChargerMode(gunIndex, MODE_IDLE);
+                        destroySelGun(gunIndex); //Jerry add
+                        StopGunInfoTimeoutDet(gunIndex);
+                        
+                        if (pSysInfo->CurGunSelected == gunIndex)
+                            systemPageRestoreInit();
+                    }
+                    break;
+                case Timeout_FinalCost:
+                	if (GetClockTimeoutValue(pDcChargingInfo->ConnectorTimeout) / uSEC_VAL >= TCC_FINALCOST_TIMEOUT) {
+                        log_info("Gun[%d] Timeout_FinalCost",gunIndex);
+                        StopGunInfoTimeoutDet(gunIndex);
+                		if (ShmDcCommonData->finalcost_flag[gunIndex] == FALSE) {
+                            log_info("Not Get Final Cost");
+                            ShmDcCommonData->PayPass_flag[gunIndex] = FALSE;
+                            if (pSysInfo->CurGunSelected == gunIndex)
+                                pSysInfo->SystemPage = _PAGE_PAYFAIL;
+                		}
+                	}
+                	break;
+                case Timeout_LineReigster:
+                	if (GetClockTimeoutValue(pDcChargingInfo->ConnectorTimeout) / uSEC_VAL >= TCC_LINEREGISTER_TIMEOUT) {
+                        log_info("Gun[%d] Timeout_LineReigster",gunIndex);
+                		StopGunInfoTimeoutDet(gunIndex);
+                        systemPageRestoreInit();
+                		ShmDcCommonData->TransactionInfo[gunIndex].IsDonateInvoice = FALSE;
+                        ShmDcCommonData->OperateIDLE[gunIndex] = 1;
+                	}
+                	break;
+                case Timeout_ParkingBill:
+                	if (GetClockTimeoutValue(pDcChargingInfo->ConnectorTimeout) / uSEC_VAL >= TCC_PARKINGBILL_TIMEOUT) {
+                        log_info("Gun[%d] Timeout_LineReigster",gunIndex);
+                		StopGunInfoTimeoutDet(gunIndex);
+                        systemPageRestoreInit();
+                		ShmDcCommonData->TransactionInfo[gunIndex].IsDonateInvoice = FALSE;
+                        ShmDcCommonData->OperateIDLE[gunIndex] = 1;
+                        ShmDcCommonData->pGunInfo[gunIndex].GetParkingBill = FALSE;
+                	}
+                	break;
+                case Timeout_ExitPage:
+                    if (GetClockTimeoutValue(pDcChargingInfo->ConnectorTimeout) / uSEC_VAL >= TCC_EXITPAGE_TIMEOUT) {
+                        log_info("Gun[%d] Timeout_ExitPage", gunIndex);
+                        StopGunInfoTimeoutDet(gunIndex);
+                        ShmDcCommonData->is_exit[gunIndex] = TRUE;
+                        if (pSysInfo->CurGunSelected == gunIndex)
+                            pSysInfo->SystemPage = _PAGE_EXIT;
+                        StartGunInfoTimeoutDet(gunIndex, Timeout_PlugOutGun);
+                    }
+                    break;
+                case Timeout_CompletPlugout:
+                    if (GetClockTimeoutValue(pDcChargingInfo->ConnectorTimeout) / uSEC_VAL >= TCC_COMPLETE_PLUGOUT_TIMEOUT) {
+                        log_info("Gun[%d] Timeout_CompletePlugout", gunIndex);
+                        setChargerMode(gunIndex, MODE_IDLE);
+                        destroySelGun(gunIndex); //Jerry add
+                        StopGunInfoTimeoutDet(gunIndex);
+                    }
+                    break;
+                case Timeout_WaitParkingInfo:
+                    if (GetClockTimeoutValue(pDcChargingInfo->ConnectorTimeout) / uSEC_VAL >= WAIT_PARKING_INFO_TIMEOUT) {
+                        log_info("Gun[%d] Timeout_WaitParkingInfo", gunIndex);
+                        StopGunInfoTimeoutDet(gunIndex);
+                        systemPageRestoreInit();
+                        ShmDcCommonData->OperateIDLE[gunIndex] = 1;
+                        ShmDcCommonData->pGunInfo[gunIndex].GetParkingBill = FALSE;
+
+                    }
+                    break;
+                case Timeout_ParkingSelect:
+                    if (GetClockTimeoutValue(pDcChargingInfo->ConnectorTimeout) / uSEC_VAL >= TCC_PARK_SELECTPAY_TIMEOUT) {
+                        log_info("Gun[%d] Timeout_ParkingSelect", gunIndex);
+                        StopGunInfoTimeoutDet(gunIndex);
+                        systemPageRestoreInit();
+                        ShmDcCommonData->OperateIDLE[gunIndex] = 1;
+                        ShmDcCommonData->pGunInfo[gunIndex].GetParkingBill = FALSE;
+
+                    }
+                    break;
+                case Timeout_ParkingLeave:
+                    if (GetClockTimeoutValue(pDcChargingInfo->ConnectorTimeout) / uSEC_VAL >= TCC_EXITPAGE_TIMEOUT) {
+                        log_info("Gun[%d] Timeout_ParkingLeave", gunIndex);
+                        StopGunInfoTimeoutDet(gunIndex);
+                        systemPageRestoreInit();
+                        ShmDcCommonData->OperateIDLE[gunIndex] = 1;
+                        ShmDcCommonData->pGunInfo[gunIndex].isParking = FALSE;
+                        ShmDcCommonData->pGunInfo[gunIndex].GetParkingBill = FALSE;
+                    }
+                    break;                    
+                }
+            }
+            sleep(1);
+        }
+    }
+}
+
+void CheckFactoryConfigFunction(void)
+{
+    char Buf[256] = {0};
+
+    if (pSysInfo->FactoryConfiguration) {
+        sprintf(Buf, "cd /root;./FactoryConfig -m %s %s",
+                pSysConfig->ModelName,
+                pSysConfig->SerialNumber);
+        system(Buf);
+
+        system("rm -f /Storage/OCPP/OCPPConfiguration");
+        system("sync");
+        sleep(5);
+        system("reboot -f");
+        sleep(5);
+        system("reboot -f");
+    }
+}
+
+//===============================================
+// Check reservation date is expired
+//===============================================
+int isReservationExpired(uint8_t gunIndex)
+{
+    int result = NO;
+    struct tm expiredDate;
+    struct timeb expiredTime;
+
+    if (sscanf((char *) ShmOCPP16Data->ReserveNow[gunIndex].ExpiryDate,
+               "%4d-%2d-%2dT%2d:%2d:%2d", &expiredDate.tm_year,
+               &expiredDate.tm_mon, &expiredDate.tm_mday, &expiredDate.tm_hour,
+               &expiredDate.tm_min, &expiredDate.tm_sec) == 6) {
+        expiredDate.tm_year -= 1900;
+        expiredDate.tm_mon -= 1;
+
+        expiredTime.time = mktime(&expiredDate);
+        if (!CheckTimeOut(expiredTime)) {
+            result = YES;
+        }
+    }
+
+    return result;
+}
+
+//===============================================
+// OCPP
+//===============================================
+void CheckOcppStatus(void)
+{
+    bool canReset = true;
+    //bool canHardReset = true; //DS60-120 add
+
+    if (ShmOCPP16Data->SpMsg.bits.BootNotificationConf == YES) {
+        ShmOCPP16Data->SpMsg.bits.BootNotificationConf = NO;
+    }
+
+    if (ShmOCPP16Data->MsMsg.bits.ResetReq == YES) {
+        if (pSysWarning->Level != WARN_LV_ER) {
+            for (uint8_t _index = 0; _index < pSysConfig->TotalConnectorCount; _index++) {
+                pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(_index);
+
+                if (pDcChargingInfo->SystemStatus != S_IDLE &&
+                        pDcChargingInfo->SystemStatus != S_RESERVATION &&
+                        pDcChargingInfo->SystemStatus != S_MAINTAIN) {
+                    canReset = false;
+                    if (pDcChargingInfo->SystemStatus >= S_REASSIGN &&
+                            pDcChargingInfo->SystemStatus < S_TERMINATING) {
+                        //canHardReset = false;
+                        ChargingTerminalProcess(_index);
+                        //restartFlag = 1;
+                    }
+                }
+            }
+        }
+
+        if (canReset) {
+            ShmOCPP16Data->MsMsg.bits.ResetReq = NO;
+            sprintf((char *)ShmOCPP16Data->Reset.ResponseStatus, "Accepted");
+            if (strcmp((char *)ShmOCPP16Data->Reset.Type, "Hard") == EQUAL) {
+                log_error("****** Hard Reboot ****** ");
+                ShmOCPP16Data->MsMsg.bits.ResetConf = YES;
+                sleep(3);
+                system("reboot -f");
+            } else if (strcmp((char *)ShmOCPP16Data->Reset.Type, "Soft") == EQUAL) {
+                log_error("****** Soft Reboot ****** ");
+                ShmOCPP16Data->MsMsg.bits.ResetConf = YES;
+                sleep(3);
+                system("killall OcppBackend &");
+                KillAllTask();
+                TryCloseWatchdog();
+                system("/usr/bin/run_evse_restart.sh");
+            }
+        }
+    }
+}
+
+void OcppStopTransation(uint8_t gunIndex)
+{
+    uint8_t _OcppGunIndex = gunIndex;
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+
+    // 如果有 AC 槍,而現在是 DC 第二把槍進入充電
+    if (pSysConfig->AcConnectorCount == 1 && gunIndex == 1) {
+        _OcppGunIndex = 2;
+    }
+
+    if (strcmp((char *)pDcChargingInfo->StartUserId, "") == EQUAL) {
+        strcpy((char *)ShmOCPP16Data->StopTransaction[_OcppGunIndex].IdTag, (char *)ShmOCPP16Data->StopTransaction[_OcppGunIndex].IdTag);
+    } else {
+        strcpy((char *)ShmOCPP16Data->StopTransaction[_OcppGunIndex].IdTag, (char *)pDcChargingInfo->StartUserId);
+    }
+
+    log_info("IdTag = %s ", ShmOCPP16Data->StopTransaction[_OcppGunIndex].IdTag);
+    ShmOCPP16Data->CpMsg.bits[_OcppGunIndex].StopTransactionReq = YES;
+}
+
+bool OcppRemoteStop(uint8_t gunIndex)
+{
+    uint8_t acDirIndex = pSysConfig->AcConnectorCount;
+
+    // 有 AC 槍的話
+    if (acDirIndex > 0 && gunIndex > 0) {
+        gunIndex += acDirIndex;
+    }
+
+    bool result = ShmOCPP16Data->CsMsg.bits[gunIndex].RemoteStopTransactionReq;
+
+    if (ShmOCPP16Data->CsMsg.bits[gunIndex].RemoteStopTransactionReq == YES) {
+        strcpy((char *)ShmOCPP16Data->StopTransaction[gunIndex].StopReason, "Remote");
+        ShmOCPP16Data->CsMsg.bits[gunIndex].RemoteStopTransactionReq = NO;
+    }
+
+    return result;
+}
+
+bool WifiScheduleStop(uint8_t gunIndex)
+{
+    bool result = false;
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+
+    result = pDcChargingInfo->schedule.isTriggerStop;
+    pDcChargingInfo->schedule.isTriggerStop = NO;
+
+    return result;
+}
+
+void OcppRemoteStartChk()
+{
+    if (pSysConfig->OfflinePolicy == _OFFLINE_POLICY_NO_CHARGING) {
+
+    } else {
+        // 如果有 AC 槍,則固定是第 2 把槍,所以索引固定為 1
+        uint8_t acDirIndex = pSysConfig->AcConnectorCount;
+        if (!isDetectPlugin(acDirIndex)) {
+            for (uint8_t ac_index = 0; ac_index < pSysConfig->AcConnectorCount; ac_index++) {
+                pAcChargingInfo = (struct ChargingInfoData*)GetAcChargingInfoData(ac_index);
+
+                if (ShmOCPP16Data->CsMsg.bits[acDirIndex].RemoteStartTransactionReq == YES) {
+                    if (pAcChargingInfo->SystemStatus == S_IDLE ||
+                        pAcChargingInfo->SystemStatus == S_RESERVATION) {
+                        ShmOCPP16Data->CsMsg.bits[acDirIndex].RemoteStartTransactionReq = NO;
+                        pAcChargingInfo->RemoteStartFlag = YES;
+                        pSysInfo->OrderCharging = YES;
+                        //pSysInfo->OrderCharging = DEFAULT_AC_INDEX;
+                        ShmOCPP16Data->CsMsg.bits[pSysConfig->TotalConnectorCount + ac_index].RemoteStartTransactionReq = NO;
+                        DetectPluginStart(acDirIndex);
+                        return;
+                    }
+                    ShmOCPP16Data->CsMsg.bits[acDirIndex].RemoteStartTransactionReq = NO;
+                }
+            }
+        }
+        //uint8_t threeGunIndex = 0;
+        //uint8_t dcIndex = 0;
+        //bool isGunUsingStatus = false;
+
+        for (uint8_t _index = 0; _index < pSysConfig->TotalConnectorCount; _index++) {
+            pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(_index);
+            /*
+            // 如果有 AC 槍,且 DC 槍也有兩把
+            if (acDirIndex == 1 && _index == 1) {
+                threeGunIndex = 1;
+            }
+
+            if (ShmOCPP16Data->CsMsg.bits[_index + threeGunIndex].RemoteStartTransactionReq == YES) {
+                dcIndex = _index;
+            }
+
+            if (pDcChargingInfo->SystemStatus != S_IDLE) {
+                isGunUsingStatus = true;
+            }
+            if (pDcChargingInfo->RemoteStartFlag == YES) {
+                //_remotestarting = true;
+            }
+        }
+
+        // 如果是雙槍單模,只認閒置狀態的槍,如果有預約~ 則預約也算被使用
+        if (isGunUsingStatus && pSysInfo->IsAlternatvieConf) {
+            if (dcIndex == 0) {
+                threeGunIndex = 0;
+            }
+
+            ShmOCPP16Data->CsMsg.bits[dcIndex + threeGunIndex].RemoteStartTransactionReq = NO;
+            return;
+        }
+
+        if (dcIndex == 0) {
+            threeGunIndex = 0;
+        }
+        */
+            pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(_index);
+
+            if (ShmOCPP16Data->CsMsg.bits[_index].RemoteStartTransactionReq == YES &&
+                !isDetectPlugin(_index)) {
+                if (pDcChargingInfo->SystemStatus == S_IDLE ||
+                    pDcChargingInfo->SystemStatus == S_RESERVATION) {
+
+                    pDcChargingInfo->RemoteStartFlag = YES;
+                    ShmDcCommonData->is_RemoteStart[_index] = TRUE;
+                    //pSysInfo->OrderCharging = YES;
+                    //pDcChargingInfo->SystemStatus = S_AUTHORIZING;
+                    //pSysInfo->OrderCharging = gunIndex;
+                    ShmOCPP16Data->CsMsg.bits[_index].RemoteStartTransactionReq = NO;
+                    DetectPluginStart(_index);
+                    setSelGunWaitToAuthor(_index);
+                    log_info("Ocpp Remote Start Gun%d Pass", _index);
+                }
+                ShmOCPP16Data->CsMsg.bits[_index].RemoteStartTransactionReq = NO;
+            }
+        }
+    }
+}
+
+void ChkOcppStatus(uint8_t gunIndex)
+{
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+
+    if (pDcChargingInfo->SystemStatus == S_IDLE &&
+            ShmOCPP16Data->CsMsg.bits[gunIndex].ReserveNowReq == YES) {
+        ShmOCPP16Data->CsMsg.bits[gunIndex].ReserveNowReq = NO;
+        if (isReservationExpired(gunIndex)) {
+            log_error("***************ChkOcppStatus : OcppReservedStatus******************** ");
+            pDcChargingInfo->ReservationId = ShmOCPP16Data->ReserveNow[gunIndex].ReservationId;
+            pDcChargingInfo->SystemStatus = S_RESERVATION;
+        }
+        ShmOCPP16Data->CsMsg.bits[gunIndex].ReserveNowConf = YES;
+    }
+
+    if (pDcChargingInfo->SystemStatus == S_RESERVATION &&
+            ShmOCPP16Data->CsMsg.bits[gunIndex].CancelReservationReq == YES) {
+        ShmOCPP16Data->CsMsg.bits[gunIndex].CancelReservationReq = NO;
+        if (isReservationExpired(gunIndex)) {
+            log_error("***************ChkOcppStatus : Cancel OcppReservedStatus******************** ");
+            pDcChargingInfo->ReservationId = 0;
+            pDcChargingInfo->SystemStatus = S_IDLE;
+        }
+        ShmOCPP16Data->CsMsg.bits[gunIndex].CancelReservationConf = YES;
+    }
+
+    if (ShmOCPP16Data->CsMsg.bits[gunIndex].ChangeAvailabilityReq == YES) {
+        log_error("***************ChkOcppStatus : OcppChangeAvailability******************** ");
+        ShmOCPP16Data->CsMsg.bits[gunIndex].ChangeAvailabilityReq = NO;
+        if (strcmp((char *)ShmOCPP16Data->ChangeAvailability[gunIndex].Type, "Operative") == EQUAL) {
+            if (isDb_ready) {
+                DB_Update_Operactive(gunIndex, true);
+            }
+
+            pDcChargingInfo->IsAvailable = YES;
+            if (pDcChargingInfo->SystemStatus == S_IDLE ||
+                    pDcChargingInfo->SystemStatus == S_RESERVATION ||
+                    pDcChargingInfo->SystemStatus == S_MAINTAIN) {
+                setChargerMode(gunIndex, MODE_IDLE);
+            }
+        } else if (strcmp((char *)ShmOCPP16Data->ChangeAvailability[gunIndex].Type, "Inoperative") == EQUAL) {
+            if (isDb_ready) {
+                DB_Update_Operactive(gunIndex, false);
+            }
+
+            pDcChargingInfo->IsAvailable = NO;
+            if (pDcChargingInfo->SystemStatus == S_IDLE ||
+                    pDcChargingInfo->SystemStatus == S_RESERVATION ||
+                    pDcChargingInfo->SystemStatus == S_MAINTAIN) {
+                setChargerMode(gunIndex, MODE_MAINTAIN);
+            }
+        }
+    }
+
+    if (ShmOCPP16Data->CsMsg.bits[gunIndex].UnlockConnectorReq == YES) {
+        ShmOCPP16Data->CsMsg.bits[gunIndex].UnlockConnectorReq = NO;
+        if (pDcChargingInfo->SystemStatus >= S_REASSIGN_CHECK && // DS60-120 add ||
+                pDcChargingInfo->SystemStatus <= S_CHARGING) {
+            // 充電中,需停止充電
+            strcpy((char *)ShmOCPP16Data->StopTransaction[gunIndex].StopReason, "UnlockCommand");
+            ChargingTerminalProcess(gunIndex);
+        }
+        strcpy((char *)ShmOCPP16Data->UnlockConnector[gunIndex].ResponseStatus, "Unlocked");
+        ShmOCPP16Data->CsMsg.bits[gunIndex].UnlockConnectorConf = YES;
+    }
+}
+
+bool CheckBackendChargingTimeout(uint8_t gunIndex)
+{
+    bool result = false;
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+
+    if (pSysConfig->AuthorisationMode == AUTH_MODE_ENABLE) {
+        if (pSysConfig->MaxChargingDuration > 0) {
+            if (pDcChargingInfo->PresentChargedDuration > (pSysConfig->MaxChargingDuration * 60)) {
+                result = true;
+            }
+        }
+    }
+
+    return result;
+}
+
+bool CheckBackendChargingEnergy(uint8_t gunIndex)
+{
+    bool result = false;
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+
+    if (pSysConfig->AuthorisationMode == AUTH_MODE_ENABLE) {
+        if (pSysConfig->MaxChargingEnergy > 0) {
+            if (pDcChargingInfo->PresentChargedEnergy > pSysConfig->MaxChargingEnergy) {
+                result = true;
+            }
+        }
+    }
+
+    return result;
+}
+
+void InformOcppErrOccur(uint8_t codeType)
+{
+    char _error[25];
+
+    switch (codeType) {
+    case 4:
+        strcpy(_error, "InternalError");
+        break;
+
+    case 6:
+        strcpy(_error, "NoError");
+        break;
+
+    case 7:
+        strcpy(_error, "OtherError");
+        break;
+
+    case 13:
+        strcpy(_error, "UnderVoltage");
+        break;
+
+    case 14:
+        strcpy(_error, "OverVoltage");
+        break;
+    }
+
+    for (uint8_t gunIndex = 0; gunIndex < pSysConfig->TotalConnectorCount; gunIndex++) {
+        strcpy((char *)ShmOCPP16Data->StatusNotification[gunIndex].ErrorCode, _error);
+    }
+}
+
+//===============================================
+// Config process
+//===============================================
+/*
+void AddPlugInTimes(uint8_t gunIndex)
+{
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+
+    if (pDcChargingInfo->Type == _Type_Chademo) {
+        pSysConfig->ChademoPlugInTimes += 1;
+    } else if (pDcChargingInfo->Type == _Type_CCS_2) {
+        pSysConfig->Ccs2PlugInTimes += 1;
+    } else if (pDcChargingInfo->Type == _Type_GB) {
+        pSysConfig->GbPlugInTimes += 1;
+    }
+}*/
+
+void ChangeStartOrStopDateTime(uint8_t isStart, uint8_t gunIndex)
+{
+    char cmdBuf[32];
+    struct timeb csuTime;
+    struct tm *tmCSU;
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+
+    ftime(&csuTime);
+    tmCSU = localtime(&csuTime.time);
+
+    sprintf(cmdBuf, "%04d-%02d-%02d %02d:%02d:%02d", tmCSU->tm_year + 1900,
+            tmCSU->tm_mon + 1, tmCSU->tm_mday, tmCSU->tm_hour, tmCSU->tm_min,
+            tmCSU->tm_sec);
+    if (isStart) {
+        strcpy((char *)pDcChargingInfo->StartDateTime, cmdBuf);
+    } else {
+        strcpy((char *)pDcChargingInfo->StopDateTime, cmdBuf);
+    }
+}
+
+void ChangeGunSelectByIndex(uint8_t sel)
+{
+    pSysInfo->CurGunSelected = sel;
+    pSysInfo->CurGunSelectedByAc = NO_DEFINE;
+}
+
+void CheckIsAlternatvieByModelName()
+{
+    if (pSysConfig->ModelName[1] == 'W') { //DS60-120
+        // 壁掛
+        pSysInfo->IsAlternatvieConf = YES;
+    } else {
+        pSysInfo->IsAlternatvieConf = NO;
+    }
+}
+
+void StopProcessingLoop()
+{
+    log_info("Stop Processing....");
+    for (;;) {
+        CheckFactoryConfigFunction();
+        //CheckFwUpdateFunction();
+        if (pSysWarning->Level == WARN_LV_ER) {
+            ChkPrimaryStatus();
+            if (pSysWarning->Level == WARN_LV_NL) {
+                log_info("Soft reboot for retry self-tets (Primary). ");
+                KillAllTask();
+                sleep(3);
+                TryCloseWatchdog();
+                system("/usr/bin/run_evse_restart.sh");
+                return;
+            }
+        }
+        sleep(1);
+        TryFeedWatchdog();
+    }
+}
+
+bool IsConnectorWholeIdle()
+{
+    bool result = true;
+
+    for (uint8_t count = 0; count < pSysConfig->TotalConnectorCount; count++) {
+        pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(count);
+
+        if (pDcChargingInfo->SystemStatus != S_IDLE &&
+                pDcChargingInfo->SystemStatus != S_RESERVATION) {
+            result = false;
+            break;
+        }
+    }
+
+    for (uint8_t count = 0; count < pSysConfig->AcConnectorCount; count++) {
+        pAcChargingInfo = (struct ChargingInfoData *)GetAcChargingInfoData(count);
+
+        if (pAcChargingInfo->SystemStatus != S_IDLE &&
+                pAcChargingInfo->IsErrorOccur == NO) {
+            result = false;
+            break;
+        }
+    }
+
+    return result;
+}
+
+void ClearAlarmCodeWhenAcOff()
+{
+    if (!pSysInfo->AcContactorStatus) {
+        pAlarmCode->AlarmEvents.bits.PsuNoResource = NO;
+    }
+}
+
+//==========================================
+// Check Smart Charging Profile
+//==========================================
+int GetStartScheduleTime(uint8_t *time)
+{
+    int result = -1;
+    struct tm tmScheduleStart;
+    struct timeb tbScheduleStart;
+
+    if ((sscanf((char *)time, "%4d-%2d-%2dT%2d:%2d:%2d", &tmScheduleStart.tm_year, &tmScheduleStart.tm_mon, &tmScheduleStart.tm_mday, &tmScheduleStart.tm_hour, &tmScheduleStart.tm_min, &tmScheduleStart.tm_sec) == 6)) {
+        tmScheduleStart.tm_year -= 1900;
+        tmScheduleStart.tm_mon -= 1;
+        tbScheduleStart.time = mktime(&tmScheduleStart);
+        tbScheduleStart.millitm = 0;
+
+        result = DiffTimebWithNow(tbScheduleStart) / 1000;
+    }
+
+    return result;
+}
+
+void CheckSmartChargeProfile(uint8_t _index)
+{
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(_index);
+
+    if (ShmOCPP16Data->CSUMsg.bits[_index].ChargingProfileConf == YES) {
+        // Get Charging Profile
+        ShmOCPP16Data->CSUMsg.bits[_index].ChargingProfileConf = NO;
+        if (strcmp((char *)ShmOCPP16Data->SmartChargingProfile[_index].ChargingProfileKind, "Absolute") == EQUAL &&
+                ShmOCPP16Data->SmartChargingProfile[_index].ChargingProfileId == YES //DS60-120 add
+           ) {
+            int _time = GetStartScheduleTime(ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.StartSchedule);
+            uint8_t _startCount = NO_DEFINE;
+            uint8_t _maxCount = ARRAY_SIZE(ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.ChargingSchedulePeriod);
+
+            for (uint8_t _count = 0; _count < _maxCount; _count++) {
+                // 預設最小輸出電流 (MIN_OUTPUT_CUR) A
+                if (_time >= ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.ChargingSchedulePeriod[_count].StartPeriod) {
+                    if ((_count == 0 && ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.ChargingSchedulePeriod[_count].Limit >= MIN_OUTPUT_CUR) ||
+                            ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.ChargingSchedulePeriod[_count].Limit > MIN_OUTPUT_CUR) {
+                        _startCount = _count;
+                    }
+                }
+            }
+
+            log_info("_startCount = %d ", _startCount);
+            if (_startCount < _maxCount) {
+                //DS60-120 add
+                log_info("Profile Limit = %f ", ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.ChargingSchedulePeriod[_startCount].Limit);
+                pDcChargingInfo->ChargingProfilePower = ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.ChargingSchedulePeriod[_startCount].Limit * AC_OUTPUT_VOL;
+                if (pDcChargingInfo->EvBatterytargetVoltage > 0 && pDcChargingInfo->PresentChargingVoltage > 0) {
+                    pDcChargingInfo->ChargingProfileCurrent = (pDcChargingInfo->ChargingProfilePower / pDcChargingInfo->PresentChargingVoltage) * 10;
+                } else {
+                    pDcChargingInfo->ChargingProfileCurrent = 0;
+                }
+            } else {
+                pDcChargingInfo->ChargingProfilePower = -1;
+                pDcChargingInfo->ChargingProfileCurrent = -1;
+            }
+        } else {
+            pDcChargingInfo->ChargingProfilePower = -1;
+            pDcChargingInfo->ChargingProfileCurrent = -1;
+        }
+
+        log_info("ChargingProfilePower = %f ", pDcChargingInfo->ChargingProfilePower);
+        log_info("ChargingProfileCurrent = %f ", pDcChargingInfo->ChargingProfileCurrent);
+    }
+}
+
+void ChargingProfileFlat(uint8_t _index)
+{
+    if (ShmOCPP16Data->CSUMsg.bits[_index].ChargingProfileConf == NO) {
+        if (ShmOCPP16Data->CSUMsg.bits[_index].ChargingProfileReq == NO) {
+            ShmOCPP16Data->CSUMsg.bits[_index].ChargingProfileReq = YES;
+        }
+    }
+}
+/*
+void CheckReturnToChargingConn()
+{
+    if ((pSysConfig->TotalConnectorCount + pSysConfig->AcConnectorCount) > 1 &&
+            pSysInfo->PageIndex != _LCM_START_AUTHORIZING &&
+            pSysInfo->PageIndex != _LCM_START_AUTHORIZE_FAIL &&
+            pSysInfo->PageIndex != _LCM_WAIT_PLUGIN) {
+        bool isReturnTimeout = false;
+
+        for (uint8_t count = 0; count < pSysConfig->TotalConnectorCount; count++) {
+            pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(count);
+
+            // 如果選的 DC 槍在充電~ 則 DC 槍不改變
+            if (count == pSysInfo->CurGunSelected) {
+                if ((pDcChargingInfo->SystemStatus >= S_REASSIGN_CHECK &&
+                        pDcChargingInfo->SystemStatus <= S_COMPLETE) ||
+                        (pDcChargingInfo->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
+                         pDcChargingInfo->SystemStatus <= S_CCS_PRECHARGE_ST1)
+                   ) {
+                    isReturnTimeout = false;
+                    break;
+                }
+            } else if (count != pSysInfo->CurGunSelected) {
+                if ((pDcChargingInfo->SystemStatus >= S_REASSIGN_CHECK &&
+                        pDcChargingInfo->SystemStatus <= S_COMPLETE) ||
+                        (pDcChargingInfo->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
+                         pDcChargingInfo->SystemStatus <= S_CCS_PRECHARGE_ST1)
+                   ) {
+                    isReturnTimeout = true;
+                    StartSystemTimeoutDet(Timeout_ReturnToChargingGunDet);
+                }
+            }
+        }
+
+        // AC 槍
+        if (!isReturnTimeout && pSysConfig->AcConnectorCount > 0) {
+            pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(pSysInfo->CurGunSelected);
+            pAcChargingInfo = (struct ChargingInfoData *)GetAcChargingInfoData(0);
+
+            // 沒有選中 AC,且 AC 在充電中
+            if (pSysInfo->CurGunSelectedByAc == NO_DEFINE &&
+                    (pAcChargingInfo->SystemStatus >= S_PREPARNING &&
+                     pAcChargingInfo->SystemStatus <= S_COMPLETE)) {
+                // 當前 DC 充電槍在 idle 狀態
+                if (pDcChargingInfo->SystemStatus == S_IDLE ||
+                        pDcChargingInfo->SystemStatus == S_RESERVATION) {
+                    isReturnTimeout = true;
+                    StartSystemTimeoutDet(Timeout_ReturnToChargingGunDet);
+                }
+            } else if (pSysInfo->CurGunSelectedByAc == DEFAULT_AC_INDEX &&
+                       ((pDcChargingInfo->SystemStatus >= S_REASSIGN_CHECK &&
+                         pDcChargingInfo->SystemStatus <= S_COMPLETE) ||
+                        (pDcChargingInfo->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
+                         pDcChargingInfo->SystemStatus <= S_CCS_PRECHARGE_ST1))) {
+                // 當前 DC 充電槍在 idle 狀態
+                if (pAcChargingInfo->SystemStatus == S_IDLE ||
+                        pAcChargingInfo->SystemStatus == S_RESERVATION) {
+                    isReturnTimeout = true;
+                    StartSystemTimeoutDet(Timeout_ReturnToChargingGunDet);
+                }
+            }
+        }
+
+        if (!isReturnTimeout) {
+            StopSystemTimeoutDet();
+        }
+    }
+}
+
+bool GetStartChargingByAlterMode(uint8_t _gun)
+{
+    bool result = true;
+
+    if (pSysConfig->TotalConnectorCount == 2 &&
+            pSysInfo->IsAlternatvieConf == YES) {
+        for (uint8_t _select = 0; _select < pSysConfig->TotalConnectorCount; _select++) {
+            pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(_select);
+
+            if (_select != _gun) {
+                if (pDcChargingInfo->SystemStatus != S_IDLE &&
+                        pDcChargingInfo->SystemStatus != S_RESERVATION) {
+                    result = false;
+                    break;
+                }
+            }
+        }
+    }
+
+    return result;
+}
+*/
+void TheEndCharging(uint8_t gunIndex)
+{
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+
+    ftime(&endChargingTime[gunIndex]);
+
+    if (pDcChargingInfo->PresentChargedDuration != 0) {
+        pDcChargingInfo->PresentChargedDuration = DiffTimeb(startChargingTime[gunIndex], endChargingTime[gunIndex]);
+    }
+
+    pDcChargingInfo->isRemoteStart = NO;
+    if (pDcChargingInfo->TimeoutFlag != Timeout_FinalCost)
+        StopGunInfoTimeoutDet(gunIndex);
+    //StartGunInfoTimeoutDet(gunIndex, Timeout_EvseCompleteDet);
+    ChangeStartOrStopDateTime(NO, gunIndex);
+    DB_Insert_Record(gunIndex);
+}
+
+void UpdateErrorCodeToOcpp(uint8_t index)
+{
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);
+
+    //log_info("%d = ConnectorAlarmCode = %s", index, pDcChargingInfo->ConnectorAlarmCode);
+    //log_info("%d = EvConnAlarmCode = %s", index, pDcChargingInfo->EvConnAlarmCode);
+    if (strcmp((char *)pDcChargingInfo->ConnectorAlarmCode, "") != EQUAL) {
+        //if (strlen((char *)pDcChargingInfo->ConnectorAlarmCode) == EQUAL) {
+        strcpy((char *)ShmOCPP16Data->StatusNotification[index].ErrorCode, "InternalError");
+        strcpy((char *)ShmOCPP16Data->StatusNotification[index].VendorErrorCode, (char *)pDcChargingInfo->ConnectorAlarmCode);
+    } else if (strcmp((char *)pDcChargingInfo->EvConnAlarmCode, "") != EQUAL) {
+        //} else if (strlen((char *)pDcChargingInfo->EvConnAlarmCode) == EQUAL) {
+        strcpy((char *)ShmOCPP16Data->StatusNotification[index].ErrorCode, "OtherError");
+        strcpy((char *)ShmOCPP16Data->StatusNotification[index].VendorErrorCode, (char *)pDcChargingInfo->EvConnAlarmCode);
+    }
+
+    //log_info("Gun %d = VendorErrorCode = %s", index, (char *)ShmOCPP16Data->StatusNotification[index].VendorErrorCode);
+}
+
+void AdjustChargerCurrent()
+{
+    pSysConfig->RatingCurrent = ShmPsuData->SystemAvailableCurrent / 10;
+
+    // 設定的電流~ 如超過可輸出的電流,則 bypass
+    if (pSysConfig->RatingCurrent < pSysConfig->MaxChargingCurrent ||
+            pSysConfig->RatingCurrent == 0) {
+        pSysConfig->MaxChargingCurrent = 0;
+    }
+
+    log_info("PSU : MaxChargingPower = %d, MaxChargingCurrent = %d",
+             ShmPsuData->SystemAvailablePower / 10,
+             ShmPsuData->SystemAvailableCurrent / 10
+            );
+
+    log_info("Config : ChargingPower = %d, ChargingCurrent = %d",
+             pSysConfig->MaxChargingPower,
+             pSysConfig->MaxChargingCurrent
+            );
+}
+
+void ResetDetAlarmStatus(uint8_t gun)
+{
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gun);
+
+    if (pDcChargingInfo->Type == _Type_Chademo) {
+        if (pAlarmCode->AlarmEvents.bits.SystemChademoOutputOVP == YES) {
+            pAlarmCode->AlarmEvents.bits.SystemChademoOutputOVP = NO;
+        }
+    } else if (pDcChargingInfo->Type == _Type_GB) {
+        if (pAlarmCode->AlarmEvents.bits.SystemGbOutputOVP == YES) {
+            pAlarmCode->AlarmEvents.bits.SystemGbOutputOVP = NO;
+        }
+    } else if (pDcChargingInfo->Type == _Type_CCS_2) {
+        if (pAlarmCode->AlarmEvents.bits.SystemCcsOutputOVP == YES) {
+            pAlarmCode->AlarmEvents.bits.SystemCcsOutputOVP = NO;
+        }
+    }
+}
+
+static void autoStartCharging(uint8_t gunIndex)
+{
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+
+    if ( (pSysInfo->SystemPage >= _PAGE_AUTHORIZE && pSysInfo->SystemPage <= _PAGE_SENSING) ||
+        (pDcChargingInfo->isEVCCIDVerify && strcmp( (char *)pSysConfig->UserId , "" ) != EQUAL)) {
+            return;
+    }
+
+    if ((pDcChargingInfo->ConnectorPlugIn == YES) &&
+            (pDcChargingInfo->SystemStatus == S_IDLE ) 
+       ) {
+        if(!pSysConfig->AuthorisationMode) {
+            /*
+            if (pSysConfig->isAuthrizeByEVCCID && !pDcChargingInfo->isEVCCIDVerify &&
+                    pDcChargingInfo->Type == _Type_CCS_2)  {
+                // LCM show linking pic. & timeout 2 min
+                if( pSysInfo->CurGunSelected == gunIndex ) {
+                    systemPageRestoreInit();
+                    pSysInfo->SystemPage = _LCM_PRECHARGE;
+                }
+                StartGunInfoTimeoutDet(gunIndex,Timeout_EVCCID_Link);
+                // Getting EVCCID
+                if( strcmp( (char *)pDcChargingInfo->EVCCID, "" ) != EQUAL ) {
+                    log_info("Authorizing EVCCID");
+                    StopSystemTimeoutDet();
+                    strcpy((char *)pSysConfig->UserId, (char *)pDcChargingInfo->EVCCID);
+                    ChangeGunSelectByIndex(gunIndex);
+                    confirmSelGun(gunIndex);
+                    pDcChargingInfo->isEVCCIDVerify = true;
+                    pSysInfo->SystemPage = _LCM_START_AUTHORIZING;
+                    log_info("Get User(%d) ID:%s",gunIndex,pSysConfig->UserId);
+                    setChargerMode(gunIndex, MODE_AUTHORIZING);
+                }
+            } else
+                return;
+                */
+        } else {
+            strcpy((char *)&pSysConfig->UserId, "AutoStartCharging");
+            ChangeGunSelectByIndex(gunIndex);
+            confirmSelGun(gunIndex);
+            ShmDcCommonData->TradeCancel = FALSE;
+            ShmDcCommonData->is_AutoStart[gunIndex] = TRUE;
+            pSysInfo->SystemPage = _PAGE_SENSING;
+            ShmDcCommonData->AuthPass_flag[gunIndex] = TRUE;
+            //setChargerMode(gunIndex, MODE_AUTHORIZING);
+            log_info("Get User(%d) ID:%s",gunIndex,pSysConfig->UserId);
+            sleep(1);   //讓其他task有時間執行
+        }
+    }
+}
+
+static bool PrecheckIsPass(uint8_t gunIndex)
+{
+    bool result = true;
+
+    // relay welding or driving 是反向
+    result = !ShmDcCommonData->GunRelayWeldingOccur[gunIndex];
+
+    return result;
+}
+
+static void ReviewCriticalAlarm(void)
+{
+    if (
+            pAlarmCode->AlarmEvents.bits.EmergencyStopTrip == YES ||
+            pAlarmCode->AlarmEvents.bits.MainPowerBreakerTrip == YES ||
+            pAlarmCode->AlarmEvents.bits.DoorOpen == YES ||
+            pSysWarning->ExtraErrProcess != _EXTRA_ERR_PROCESS_NONE ||
+            pAlarmCode->AlarmEvents.bits.PsuFailureAlarm == YES ||
+            pAlarmCode->AlarmEvents.bits.DisconnectedFromDo == YES ||
+            //Power cabinet alarm status
+            ShmDcCommonData->PowerAlarmState.StatusBit.EmergencyStop == YES ||
+            ShmDcCommonData->PowerAlarmState.StatusBit.DoorOpen == YES ||
+            ShmDcCommonData->PowerAlarmState.StatusBit.DcInputOVP == YES ||
+			ShmDcCommonData->PowerAlarmState.StatusBit.DcInputUVP == YES ||
+            ShmDcCommonData->PowerAlarmState.StatusBit.SystemL1InputOVP == YES ||
+            ShmDcCommonData->PowerAlarmState.StatusBit.SystemL2InputOVP == YES ||
+            ShmDcCommonData->PowerAlarmState.StatusBit.SystemL3InputOVP == YES ||
+            ShmDcCommonData->PowerAlarmState.StatusBit.PsuFailure == YES ) {
+        pSysWarning->Level = WARN_LV_ER;
+    } else {
+        if (ShmSelectGunInfo->EthDevStatus.Backend == 0 ||
+            ShmSelectGunInfo->EthDevStatus.Backend == 2 ) {
+            pInfoCode->InfoEvents.bits.BackendDisconnectedViaEthernet = TRUE;
+            if (ShmDcCommonData->DebugFlag || pSysConfig->AuthorisationMode) {
+                pSysWarning->Level = WARN_LV_NL;
+            } else {
+                pSysWarning->Level = WARN_LV_ER;
+
+                return;
+            }
+        } else if (ShmSelectGunInfo->EthDevStatus.Backend == 1) {
+            pInfoCode->InfoEvents.bits.BackendDisconnectedViaEthernet = FALSE;
+        }
+        
+        pSysWarning->Level = WARN_LV_NL;
+    }
+
+}
+
+static void CheckRelayWeldingOrDrivingFault(uint8_t gunIndex)
+{
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+
+    // relay welding fault then stop the charging process.
+    uint8_t faultCode = RELAY_STATUS_ERROR_NONE;
+    //static uint8_t drivingCount = 0;
+
+    if (gunIndex == 0) {
+        if (ShmDcCommonData->CheckRelayStatus[RELAY_SMR1_P_STATUS] == RELAY_STATUS_ERROR_WELDING ||
+                ShmDcCommonData->CheckRelayStatus[RELAY_SMR1_N_STATUS] == RELAY_STATUS_ERROR_WELDING) {
+            faultCode = RELAY_STATUS_ERROR_WELDING;
+        } else if (ShmDcCommonData->CheckRelayStatus[RELAY_SMR1_P_STATUS] == RELAY_STATUS_ERROR_DRIVING ||
+                   ShmDcCommonData->CheckRelayStatus[RELAY_SMR1_N_STATUS] == RELAY_STATUS_ERROR_DRIVING) {
+            faultCode = RELAY_STATUS_ERROR_DRIVING;
+        }
+    } else if (gunIndex == 1) {
+        if (ShmDcCommonData->CheckRelayStatus[RELAY_SMR2_P_STATUS] == RELAY_STATUS_ERROR_WELDING ||
+                ShmDcCommonData->CheckRelayStatus[RELAY_SMR2_N_STATUS] == RELAY_STATUS_ERROR_WELDING) {
+            faultCode = RELAY_STATUS_ERROR_WELDING;
+        } else if (ShmDcCommonData->CheckRelayStatus[RELAY_SMR2_P_STATUS] == RELAY_STATUS_ERROR_DRIVING ||
+                   ShmDcCommonData->CheckRelayStatus[RELAY_SMR2_N_STATUS] == RELAY_STATUS_ERROR_DRIVING) {
+            faultCode = RELAY_STATUS_ERROR_DRIVING;
+        }
+    }
+
+    if (pSysConfig->TotalConnectorCount >= 2 &&
+            !pSysInfo->IsAlternatvieConf) {
+        // 橋接
+        if (ShmDcCommonData->CheckRelayStatus[RELAY_PARA_P_STATUS] == RELAY_STATUS_ERROR_WELDING ||
+                ShmDcCommonData->CheckRelayStatus[RELAY_PARA_N_STATUS] == RELAY_STATUS_ERROR_WELDING) {
+            faultCode = RELAY_STATUS_ERROR_WELDING;
+        } else if (ShmDcCommonData->CheckRelayStatus[RELAY_PARA_P_STATUS] == RELAY_STATUS_ERROR_DRIVING ||
+                   ShmDcCommonData->CheckRelayStatus[RELAY_PARA_N_STATUS] == RELAY_STATUS_ERROR_DRIVING) {
+            faultCode = RELAY_STATUS_ERROR_DRIVING;
+        }
+    }
+
+    if (faultCode == RELAY_STATUS_ERROR_WELDING) {
+        // welding
+        if (pDcChargingInfo->Type == _Type_Chademo) {
+            RecordAlarmCode(gunIndex, "011011");
+            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaRelayWeldingFault = YES;
+        } else if (pDcChargingInfo->Type == _Type_GB) {
+            RecordAlarmCode(gunIndex, "011015");
+            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTRelayWeldingFault = YES;
+        } else if (pDcChargingInfo->Type == _Type_CCS_2) {
+            RecordAlarmCode(gunIndex, "011013");
+            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSRelayWeldingFault = YES;
+        }
+
+        ShmDcCommonData->GunRelayWeldingOccur[gunIndex] = YES;
+        //EmcOccureByString("");
+    } else if (faultCode == RELAY_STATUS_ERROR_DRIVING) {
+        //if (drivingCount++ != 2) {
+        //    return;
+        //}
+
+        // driving
+        if (pDcChargingInfo->Type == _Type_Chademo) {
+            RecordAlarmCode(gunIndex, "011012");
+            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaRelayDrivingFault = YES;
+        } else if (pDcChargingInfo->Type == _Type_GB) {
+            RecordAlarmCode(gunIndex, "011016");
+            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTRelayDrivingFault = YES;
+        } else if (pDcChargingInfo->Type == _Type_CCS_2) {
+            RecordAlarmCode(gunIndex, "011014");
+            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSRelayDrivingFault = YES;
+        }
+
+        ShmDcCommonData->GunRelayDrivingOccur[gunIndex] = YES;
+        //EmcOccureByString("");
+    } else {
+        ShmDcCommonData->GunRelayWeldingOccur[gunIndex] = NO;
+        ShmDcCommonData->GunRelayDrivingOccur[gunIndex] = NO;
+        //drivingCount = 0;
+    }
+}
+
+static void isChargingAverageState(void)
+{
+    if (pSysInfo->MainChargingMode != _MAIN_CHARGING_MODE_AVER) {
+        pSysInfo->ReAssignedFlag = _REASSIGNED_NONE;
+        return;
+    }
+
+    // 均充 -> 最大充
+    if (pSysInfo->BridgeRelayStatus == NO) {
+        if (pSysInfo->ReAssignedFlag == _REASSIGNED_NONE) {
+            log_info("=============Smart Charging============= Step 11 ");
+            pSysInfo->ReAssignedFlag = _REASSIGNED_PREPARE_A_TO_M;
+        }
+    } else if (pSysInfo->ReAssignedFlag != _REASSIGNED_COMP &&
+               pSysInfo->ReAssignedFlag != _REASSIGNED_WAITING) {
+        log_info("=============Smart Charging============= Step 14 ");
+        pSysInfo->ReAssignedFlag = _REASSIGNED_WAITING;
+    } else if (pSysInfo->ReAssignedFlag == _REASSIGNED_COMP) {
+        pSysInfo->MainChargingMode = _MAIN_CHARGING_MODE_MAX;
+        pSysInfo->ReAssignedFlag = _REASSIGNED_NONE;
+    }
+}
+
+bool Taskconutstring(char *src, char *taskname)
+{
+    bool result = false;
+
+    if (src == NULL || strlen(src) == 0)
+        return result;
+
+    if (strstr(src, taskname) != NULL &&
+        strstr(src, "grep") == NULL &&
+        strstr(src, "[") == NULL)
+    {
+        result = true;
+    }
+
+    return result;
+}
+
+int GetProcessCount(char *procName)
+{
+	int result = 0;
+	FILE *fp;
+	char cmd[256];
+	char buf[256];
+
+	sprintf(cmd, "ps -ef |grep %s", procName);
+	fp = popen(cmd, "r");
+	if(fp != NULL)
+	{
+		while(fgets(buf, sizeof(buf), fp) != NULL)
+		{
+			if (Taskconutstring(buf, procName))
+				result++;
+		}
+	}
+
+	pclose(fp);
+
+	return result;
+}
+void CheckTaskAlive()
+{
+    pid_t Pid = fork();
+    if ( Pid == 0 ) {
+        //log_info("CheckTaskAlive fork Child's PID is %d", getpid());
+        while(1) {
+            sleep(3);
+            unsigned char count = GetProcessCount("Module_ChkSysTask");
+            if( count != 1 ) {
+                system("pkill Module_ChkSysTask");
+                sleep(10);
+                //log_info("Create Check System Task");
+                system("/root/Module_ChkSysTask &");
+            }
+        }
+        return;
+    }
+    log_info("Create Check Systam fork:%d",Pid);
+    return;
+}
+/**
+ * [checkPileEndGfdResult 確認充電樁GFD狀態]
+ * @Author   Jerry
+ * @DateTime 2021-07-01
+ * @param    gunIndex   [當前的槍]
+ * @param    gunType    [槍的類型]
+ * @param    sysStatus  [槍的系統狀態]
+ */
+static void checkPileEndGfdResult(uint8_t gunIndex, uint8_t gunType, uint8_t sysStatus)
+{
+    switch (gunType) {
+    case _Type_Chademo:
+        // 檢查樁端的 GFD 結果
+        if (sysStatus == S_PREPARING_FOR_EVSE &&
+                isPrechargeStatus_chademo(gunIndex) >= 6 ) {
+            // 當前操作的槍號,進入 Charging
+            setChargerMode(gunIndex, MODE_CHARGING);
+        }
+
+        if (pDcChargingInfo->GroundFaultStatus == GFD_FAIL) {
+            // GFD 錯誤停止
+            RecordAlarmCode(gunIndex, "012234");
+            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaGfdTrip = YES;
+            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaGfdWarning = NO;
+        } else if (pDcChargingInfo->GroundFaultStatus == GFD_WARNING) {
+            // GFD 警告
+            //RecordAlarmCode(gunIndex, "012296");
+            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaGfdTrip = NO;
+            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaGfdWarning = YES;
+        }
+        else {
+            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaGfdTrip = NO;
+            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaGfdWarning = NO;
+        }
+
+        break;
+
+    case _Type_GB:
+        // 檢查樁端的 GFD 結果
+        //if (isPrechargeStatus_gb(gunIndex) > 5 && isPrechargeStatus_gb(gunIndex) < 9) {
+        if (sysStatus == S_PREPARING_FOR_EVSE &&
+                isPrechargeStatus_gb(gunIndex) >= 6) {
+            setChargerMode(gunIndex, MODE_CHARGING);
+        }
+
+        if (pDcChargingInfo->GroundFaultStatus == GFD_FAIL) {
+            // GFD 錯誤停止
+            RecordAlarmCode(gunIndex, "012236");
+            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTGfdTrip = YES;
+            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTGfdWarning = NO;
+        } else if (pDcChargingInfo->GroundFaultStatus == GFD_WARNING) {
+            // GFD 警告
+            //RecordAlarmCode(gunIndex, "012298");
+            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTGfdTrip = NO;
+            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTGfdWarning = YES;
+        }
+        else {
+            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTGfdTrip = NO;
+            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTGfdWarning = NO;
+        }
+        break;
+
+    case _Type_CCS_2:
+        // 檢查樁端的 GFD 結果
+        if (sysStatus == S_PREPARING_FOR_EVSE &&
+                (pDcChargingInfo->GroundFaultStatus == GFD_PASS ||
+                 pDcChargingInfo->GroundFaultStatus == GFD_WARNING)
+           ) {
+            setChargerMode(gunIndex, MODE_CCS_PRECHARGE_STEP0);
+        }
+
+        if (pDcChargingInfo->GroundFaultStatus == GFD_FAIL) {
+            // GFD 錯誤停止
+            RecordAlarmCode(gunIndex, "012235");
+            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSGfdTrip = YES;
+            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSGfdWarning = NO;
+        } else if (pDcChargingInfo->GroundFaultStatus == GFD_WARNING) {
+            // GFD 警告
+            //RecordAlarmCode(gunIndex, "012297");
+            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSGfdTrip = NO;
+            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSGfdWarning = YES;
+        }
+        else {
+            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSGfdTrip = NO;
+            ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSGfdWarning = NO;
+        }
+
+        break;
+    }
+}
+
+static void checkEvBoardReqStop(uint8_t sysStatus, uint8_t gunIndex)
+{
+    uint8_t evBoardStopState = 0;
+
+    if ((evBoardStopState = isEvBoardStopChargeFlag(gunIndex)) > 0) {
+
+        // 板端要求停止 (錯誤)
+        if (sysStatus != S_CCS_PRECHARGE_ST0 &&
+                sysStatus != S_CCS_PRECHARGE_ST1) {
+            if (strcmp((char *)ShmOCPP16Data->StopTransaction[gunIndex].StopReason, "") == EQUAL) {
+                strcpy((char *)ShmOCPP16Data->StopTransaction[gunIndex].StopReason, "EVDisconnected");
+            }
+        }
+
+        if (evBoardStopState == EV_BOARD_STOP_CHARGING) {
+            log_info("EV Board Stop Charging with some error");
+            ChargingAlarmProcess(gunIndex);
+        } else if (evBoardStopState == POWER_CABINET_STOP_CHARGING) {
+            log_info("Power Cabient Stop Charging");
+            ChargingTerminalProcess(gunIndex);
+        }
+    } else if (isEvBoardNormalStopChargeFlag(gunIndex) == YES) {
+        // 板端要求停止 (正常)
+        if (sysStatus != S_CCS_PRECHARGE_ST0 &&
+                sysStatus != S_CCS_PRECHARGE_ST1) {
+            if (strcmp((char *)ShmOCPP16Data->StopTransaction[gunIndex].StopReason, "") == EQUAL) {
+                strcpy((char *)ShmOCPP16Data->StopTransaction[gunIndex].StopReason, "EVDisconnected");
+            }
+        }
+        log_info("EV Board Normal Stop Charging");
+        ChargingTerminalProcess(gunIndex);
+    } else if (OcppRemoteStop(gunIndex) == YES ||
+               WifiScheduleStop(gunIndex)) {
+        // 後臺要求停止
+        log_info("OCPP Stop Charging");
+        ChargingTerminalProcess(gunIndex);
+    }
+}
+
+static void checkOCPPReqStop(uint8_t gunIndex)
+{
+    if (OcppRemoteStop(gunIndex) == YES ||
+        WifiScheduleStop(gunIndex) ||
+        CheckBackendChargingTimeout(gunIndex) ||
+        CheckBackendChargingEnergy(gunIndex) ||
+        strcmp((char *)ShmOCPP16Data->StartTransaction[gunIndex].ResponseIdTagInfo.Status, "Invalid") == EQUAL) {
+        // 後臺要求停止
+        ChargingTerminalProcess(gunIndex);
+    }
+}
+void ResetIdleData(uint8_t gunIndex)
+{
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+    ShmOCPP16Data = (struct OCPP16Data *)GetShmOCPP16Data();
+    ShmSelectGunInfo = (SelectGunInfo *)GetShmSelectGunInfo();
+    float powerconsumption = ShmDcCommonData->pGunInfo[gunIndex].PowerConsumption;
+    pDcChargingInfo->PresentChargedDuration = 0;
+    pDcChargingInfo->RemainChargingDuration = 0;
+    pDcChargingInfo->PresentChargingVoltage = 0;//DS60-120 add
+    pDcChargingInfo->PresentChargingCurrent = 0;//DS60-120 add
+    pDcChargingInfo->RemoteStartFlag = NO;
+    pDcChargingInfo->Replug_flag = FALSE;
+    strcpy((char *)pDcChargingInfo->StartDateTime, "");
+    strcpy((char *)pDcChargingInfo->StopDateTime, "");
+    strcpy((char *)pDcChargingInfo->StartUserId, "");
+    strcpy((char *)pSysConfig->UserId, "");
+    strcpy((char *)ShmOCPP16Data->StopTransaction[gunIndex].StopReason, "");
+    ClearDetectPluginFlag(gunIndex);
+    //Jerry add
+    memset(&ShmSelectGunInfo->PricesInfo[gunIndex], 0, sizeof(PricesInfo));
+    memset(&ShmDcCommonData->TransactionInfo[gunIndex], 0, sizeof(RecordTransactionInfo));
+    memset(&ShmDcCommonData->pGunInfo[gunIndex], 0, sizeof(GunInfo));
+    ShmDcCommonData->pGunInfo[gunIndex].PowerConsumption = powerconsumption;
+    ShmDcCommonData->finalcost_flag[gunIndex] = FALSE;
+    ShmDcCommonData->AuthPass_flag[gunIndex] = FALSE;
+    ShmDcCommonData->PayPass_flag[gunIndex] = FALSE;
+    ShmDcCommonData->OperateIDLE[gunIndex] = 1;
+    ShmDcCommonData->is_RemoteStart[gunIndex] = FALSE;
+    ShmDcCommonData->is_AutoStart[gunIndex] = FALSE;
+    ShmDcCommonData->is_exit[gunIndex] = FALSE;
+    ShmDcCommonData->StopCharge[gunIndex] = FALSE;
+    ShmDcCommonData->is_plugout[gunIndex] = FALSE;
+    if (pDcChargingInfo->deratingByConnOtp.deratingIndex != 0) {
+        pDcChargingInfo->deratingByConnOtp.deratingIndex = 0;
+    }
+    ShmSelectGunInfo->PricesInfo[gunIndex].Balance = FAIL_BALANCE_PRICES;
+    destroySelGun(gunIndex);
+    ResetDetAlarmStatus(gunIndex); //recovery OVP status code
+    if (ShmSelectGunInfo->AuthorStateFromCabinet[gunIndex] == YES) {
+        ShmSelectGunInfo->AuthorStateFromCabinet[gunIndex] = NO;
+    }
+    //strcpy((char *)ShmOCPP16Data->StatusNotification[gunIndex].VendorErrorCode, "");
+    ReleaseAlarmCode(gunIndex);
+    if (pSysInfo->SystemPage != _PAGE_SELECT_GUN &&
+        pSysInfo->SystemPage != _PAGE_SELECT_PAY &&
+        pSysInfo->CurGunSelected == gunIndex) {
+        systemPageRestoreInit();
+    }
+
+}
+void CheckErrorCode(uint8_t gunIndex)
+{
+    /*
+    struct ChargingInfoData *pSelectedDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+    
+    if (gunIndex == pSysInfo->CurGunSelected) {
+        pSysInfo->SystemPage = _PAGE_MAINTAIN;
+    } else if (pSelectedDcChargingInfo->SystemStatus != S_IDLE &&
+            pSelectedDcChargingInfo->SystemStatus != S_RESERVATION &&
+            pSelectedDcChargingInfo->SystemStatus != S_MAINTAIN &&
+            pSelectedDcChargingInfo->SystemStatus != S_FAULT) {
+        if (pSelectedDcChargingInfo->SystemStatus == S_CHARGING) {
+        	if(ShmDcCommonData->PayPass_flag[gunIndex] == FALSE)
+        		pSysInfo->SystemPage = _PAGE_PAYING;
+        	else
+        		pSysInfo->SystemPage = _PAGE_COMPLETE;
+        } else {
+            systemPageRestoreInit();
+        }
+    }
+    */
+    ClearDetectPluginFlag(gunIndex);
+    if (pDcChargingInfo->SystemStatus != S_FAULT)
+    {
+        UpdateErrorCodeToOcpp(gunIndex);
+        setChargerMode(gunIndex, MODE_FAULT);
+    }
+}
+void AuthorizeStopCharging(uint8_t gunIndex)
+{
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+
+    checkOCPPReqStop(gunIndex);
+
+    //RfidStopCharging();
+
+}
+
+
+void SetNatural300AGunOTPValue(struct DERATING_BY_OTP* deratingByConnOtp)
+{
+    deratingByConnOtp->isNeedDerating = YES;
+    deratingByConnOtp->deratingTargetCurrent[0] = 5000;
+    deratingByConnOtp->deratingTargetCurrent[1] = 3000;
+    deratingByConnOtp->deratingTargetCurrent[2] = 1000;
+    deratingByConnOtp->deratingTargetCurrent[3] = 0;
+    deratingByConnOtp->deratingTargetCurrent[4] = 0;
+}
+void SetLiquidCoolGunOTPValue(struct DERATING_BY_OTP* deratingByConnOtp)
+{
+    deratingByConnOtp->isNeedDerating = YES;
+    deratingByConnOtp->deratingTargetCurrent[0] = 5000;
+    deratingByConnOtp->deratingTargetCurrent[1] = 4000;
+    deratingByConnOtp->deratingTargetCurrent[2] = 3000;
+    deratingByConnOtp->deratingTargetCurrent[3] = 0;
+    deratingByConnOtp->deratingTargetCurrent[4] = 0;
+}
+
+void SetCHAdeMoTypeKOTPValue(struct DERATING_BY_OTP* deratingByConnOtp)
+{
+    deratingByConnOtp->isNeedDerating = YES;
+    deratingByConnOtp->deratingTargetRate[0] = 1;
+    deratingByConnOtp->deratingTargetRate[1] = 0.8;
+    deratingByConnOtp->deratingTargetRate[2] = 0.8;
+    deratingByConnOtp->deratingTargetRate[3] = 0;
+    deratingByConnOtp->deratingTargetRate[4] = 0;
+
+    memset(&deratingByConnOtp->deratingTargetCurrent[0], 0, sizeof(deratingByConnOtp->deratingTargetCurrent));
+}
+
+void SetCHAdeMoTypeSJOTPValue(struct DERATING_BY_OTP* deratingByConnOtp)
+{
+    deratingByConnOtp->isNeedDerating = YES;
+    deratingByConnOtp->deratingTargetCurrent[0] = 2000;
+    deratingByConnOtp->deratingTargetCurrent[1] = 1250;
+    deratingByConnOtp->deratingTargetCurrent[2] = 1250;
+    deratingByConnOtp->deratingTargetCurrent[3] = 0;
+    deratingByConnOtp->deratingTargetCurrent[4] = 0;
+}
+
+void SetCHAdeMoTypeOOTPValue(struct DERATING_BY_OTP* deratingByConnOtp)
+{
+    deratingByConnOtp->isNeedDerating = YES;
+    deratingByConnOtp->deratingTargetCurrent[0] = 3500;
+    deratingByConnOtp->deratingTargetCurrent[1] = 2000;
+    deratingByConnOtp->deratingTargetCurrent[2] = 2000;
+    deratingByConnOtp->deratingTargetCurrent[3] = 0;
+    deratingByConnOtp->deratingTargetCurrent[4] = 0;
+}
+
+static void SetGunTypeOTPValue(void)
+{
+    //struct ChargingInfoData* chargingData_2 = NULL;
+    uint8_t Gun1Type = 0;
+    uint8_t Gun2Type = 0;
+    int i,cnt;
+    if (pSysConfig->TotalConnectorCount == 1) {
+        pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(0);
+        Gun1Type = pSysConfig->ModelName[7];
+        Gun2Type = pSysConfig->ModelName[7];
+
+        switch (Gun1Type) {
+        case 'K':
+            SetCHAdeMoTypeKOTPValue(&pDcChargingInfo->deratingByConnOtp);
+            break;
+        case 'S':
+            SetCHAdeMoTypeSJOTPValue(&pDcChargingInfo->deratingByConnOtp);
+            break;
+        case 'I':
+        case 'Q':
+            SetNatural300AGunOTPValue(&pDcChargingInfo->deratingByConnOtp);
+            break;
+        case 'O':
+            SetCHAdeMoTypeOOTPValue(&pDcChargingInfo->deratingByConnOtp);
+            break;
+            // 水冷
+        case 'V':
+        case 'F':
+            SetLiquidCoolGunOTPValue(&pDcChargingInfo->deratingByConnOtp);
+            break;
+        default:
+            pDcChargingInfo->deratingByConnOtp.isNeedDerating = NO;
+        }
+        if (pDcChargingInfo->deratingByConnOtp.isNeedDerating) {
+            log_info("------------ Gun0 - Type:%c Derating info (OTP)-----------", Gun1Type);
+            if (pDcChargingInfo->deratingByConnOtp.deratingTargetRate[0] != 0) {
+                for (cnt = 0; cnt < DERATING_TARGET_LEVEL; cnt++) {
+                    if (pDcChargingInfo->deratingByConnOtp.deratingTargetRate[cnt] != 0) {
+                        log_info(" (Pwr) count = %d, valut = %.1f ", cnt, pDcChargingInfo->deratingByConnOtp.deratingTargetRate[cnt]);
+                    }
+                }
+            } else if (pDcChargingInfo->deratingByConnOtp.deratingTargetCurrent[0] != 0) {
+                for (cnt = 0; cnt < DERATING_TARGET_LEVEL; cnt++) {
+                    if (pDcChargingInfo->deratingByConnOtp.deratingTargetCurrent[cnt] != 0) {
+                        log_info(" (Cur) count = %d, valut = %.1f ", cnt, pDcChargingInfo->deratingByConnOtp.deratingTargetCurrent[cnt]);
+                    }
+                }
+            }
+        }
+
+    } else if (pSysConfig->TotalConnectorCount == 2) {
+        Gun1Type = pSysConfig->ModelName[7];
+        Gun2Type = pSysConfig->ModelName[9];
+        for (i = 0; i < pSysConfig->TotalConnectorCount; i++) {
+            pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(i);
+
+            switch (i == 0 ? Gun1Type : Gun2Type) {
+            case 'K':
+                SetCHAdeMoTypeKOTPValue(&pDcChargingInfo->deratingByConnOtp);
+                break;
+            case 'S':
+                SetCHAdeMoTypeSJOTPValue(&pDcChargingInfo->deratingByConnOtp);
+                break;
+                // 風冷300A
+            case 'I':
+            case 'Q':
+                SetNatural300AGunOTPValue(&pDcChargingInfo->deratingByConnOtp);
+                break;
+            case 'O':
+                SetCHAdeMoTypeOOTPValue(&pDcChargingInfo->deratingByConnOtp);
+                break;
+                // 水冷
+            case 'V':
+            case 'F':
+                SetLiquidCoolGunOTPValue(&pDcChargingInfo->deratingByConnOtp);
+                break;
+            default:
+                pDcChargingInfo->deratingByConnOtp.isNeedDerating = NO;
+            }
+            if (pDcChargingInfo->deratingByConnOtp.isNeedDerating) {
+                log_info("------------ Gun%d - Type:%c Derating info (OTP)-----------",i, i == 0 ? Gun1Type : Gun2Type);
+                if (pDcChargingInfo->deratingByConnOtp.deratingTargetRate[0] != 0) {
+                    for (cnt = 0; cnt < DERATING_TARGET_LEVEL; cnt++) {
+                        if (pDcChargingInfo->deratingByConnOtp.deratingTargetRate[cnt] != 0) {
+                            log_info(" (Pwr) count = %d, valut = %.1f ", cnt, pDcChargingInfo->deratingByConnOtp.deratingTargetRate[cnt]);
+                        }
+                    }
+                } else if (pDcChargingInfo->deratingByConnOtp.deratingTargetCurrent[0] != 0) {
+                    for (cnt = 0; cnt < DERATING_TARGET_LEVEL; cnt++) {
+                        if (pDcChargingInfo->deratingByConnOtp.deratingTargetCurrent[cnt] != 0) {
+                            log_info(" (Cur) count = %d, valut = %.1f ", cnt, pDcChargingInfo->deratingByConnOtp.deratingTargetCurrent[cnt]);
+                        }
+                    }
+                }
+            }
+        }
+    }
+}
+
+void showversion()
+{
+    char str[10240];
+    int len = 0;
+    uint8_t index = 0;
+    len += sprintf(&str[len],"\n=========== Dispenser info =========== \n");
+    len += sprintf(&str[len],"SW Version = %s\n", fwVersion);
+    len += sprintf(&str[len],"Debug Version = %s\n",DebugVersion);
+    len += sprintf(&str[len],"ModelName = %s\n", pSysConfig->ModelName);
+    len += sprintf(&str[len],"Relay Board FW Rev = %s\n", pSysInfo->RelayModuleFwRev);
+    len += sprintf(&str[len],"Fan Board FW Rev = %s\n", pSysInfo->FanModuleFwRev);
+    len += sprintf(&str[len],"Primary FW Rev = %s\n", pSysInfo->CsuPrimFwRev);
+    len += sprintf(&str[len],"LED FW Rev = %s\n", pSysInfo->LedModuleFwRev);
+
+    for (index = 0; index < pSysConfig->TotalConnectorCount; index++) {
+        pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);
+        if (pDcChargingInfo->Type == _Type_Chademo) {
+            len += sprintf(&str[len],"CHAdeMO[%d] FW Rev = %s\n",
+                                     index,
+                                     ShmCHAdeMOData->evse[pDcChargingInfo->type_index].version);
+        } else if (pDcChargingInfo->Type == _Type_GB) {
+            len += sprintf(&str[len],"GBT[%d] FW Rev = %s\n",
+                                     index,
+                                     ShmGBTData->evse[pDcChargingInfo->type_index].version);
+        } else if (pDcChargingInfo->Type == _Type_CCS_2) {
+            len += sprintf(&str[len],"CCS[%d] FW Rev = %s\n",
+                                         index,
+                                         ShmCcsData->V2GMessage_DIN70121[pDcChargingInfo->type_index].version);
+        }
+    }
+    len += sprintf(&str[len],"==================================== ");
+    log_info("%s",str);
+}
+
+void ParkingProcess(int gunIndex)
+{
+    if (pSysInfo->CurGunSelected != gunIndex)
+        return;
+
+    // 取得佔位費資訊過場畫面
+    if (ShmDcCommonData->pGunInfo[gunIndex].ParkingStatus == _TCC_PARKING_NONE) {
+        return;
+    } else if (!ShmDcCommonData->pGunInfo[gunIndex].GetParkingBill &&
+        pSysInfo->SystemPage != _PAGE_IDLE &&
+        pSysInfo->SystemPage != _PAGE_SELECT_GUN &&
+        pSysInfo->SystemPage != _PAGE_COMPLETE &&
+        pSysInfo->SystemPage != _PAGE_PAYFAIL &&
+        pSysInfo->SystemPage != _PAGE_PLUGOUT &&
+        pSysInfo->SystemPage != _PAGE_SENSING &&
+        pSysInfo->SystemPage != _PAGE_PLUGIN) {
+        pSysInfo->SystemPage = _PAGE_PAYING;
+        StartGunInfoTimeoutDet(gunIndex, Timeout_WaitParkingInfo);
+        return;
+    }
+    if (ShmDcCommonData->pGunInfo[gunIndex].GetParkingBill && pSysInfo->SystemPage == _PAGE_PAYING) {
+            pSysInfo->SystemPage = _PAGE_BILL;
+    }
+    switch (pSysInfo->SystemPage) {
+        case _PAGE_BILL:
+        case _PAGE_DONATE_LEFT:
+        case _PAGE_DONATE_RIGHT:
+        case _PAGE_SELECT_PAY:
+            StartGunInfoTimeoutDet(gunIndex, Timeout_ParkingSelect);
+            break;
+        case _PAGE_ADD_FRIEND:
+            StartGunInfoTimeoutDet(gunIndex, Timeout_ParkingBill);
+            if (ShmDcCommonData->ParkingInfo[gunIndex].LineStatus == _LINE_PARKING_INVOICE) {
+                ShmDcCommonData->ParkingInfo[gunIndex].IsDonateInvoice = FALSE;
+                pSysInfo->SystemPage = _PAGE_SELECT_PAY;
+                StopGunInfoTimeoutDet(gunIndex);
+                log_info("Change to Select Pay Page");
+            } else if (ShmDcCommonData->ParkingInfo[gunIndex].LineStatus == _LINE_PARKING_DONATE) {
+                ShmDcCommonData->ParkingInfo[gunIndex].IsDonateInvoice = TRUE;
+                pSysInfo->SystemPage = _PAGE_SELECT_PAY;
+                StopGunInfoTimeoutDet(gunIndex);
+                log_info("Change to Select Pay Page");
+            }
+            break;
+        case _PAGE_AUTHORIZE:
+            StopGunInfoTimeoutDet(gunIndex);
+            break;
+        case _PAGE_PLUGIN:
+            StartGunInfoTimeoutDet(gunIndex,Timeout_ParkingLeave);
+            /*
+            if (pDcChargingInfo->ConnectorPlugIn == NO ) {
+                if (pSysInfo->CurGunSelected == gunIndex) {
+                    StartGunInfoTimeoutDet(gunIndex, Timeout_ExitPage);
+                }
+                if (pDcChargingInfo->TimeoutFlag != Timeout_ExitPage) {
+                    StartGunInfoTimeoutDet(gunIndex, Timeout_CompletPlugout);
+                }
+            }
+            */
+            break;
+        case _PAGE_AUTHORIZE_FAIL:
+            StartSystemTimeoutDet(Timeout_VerifyFail);
+            break;
+        case _PAGE_PLUGOUT:
+            StopGunInfoTimeoutDet(gunIndex);
+            break;
+    }
+
+}
+
+int main(void)
+{
+    bool isModelNameMatch = true;
+    uint8_t _ocppProfileChkFlag;
+    uint8_t gunIndex = 0;
+
+    if (CreateAllCsuShareMemory() == FAIL) {
+        log_error("create share memory error");
+        return FAIL;
+    }
+    ClearAllShmMemParameter();
+
+    pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
+    pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
+    pSysWarning = (struct WARNING_CODE_INFO *)GetShmSysWarningInfo();
+
+    pAlarmCode = (struct AlarmCodeData *)GetShmAlarmCodeData();
+    pFaultCode = (struct FaultCodeData *)GetShmFaultCodeData();
+    pInfoCode = (struct InfoCodeData *)GetShmInfoCodeData();
+
+    ShmPsuData = (struct PsuData *)GetShmPsuData();
+
+    ShmCHAdeMOData = (struct CHAdeMOData *)GetShmCHAdeMOData();
+    ShmGBTData = (struct GBTData *)GetShmGBTData();
+    ShmCcsData = (struct CcsData *)GetShmCcsData();
+
+    ShmPrimaryMcuData = (struct PrimaryMcuData *)GetShmPrimaryMcuData();
+    ShmFanModuleData = (struct FanModuleData *)GetShmFanModuleData();
+    ShmRelayModuleData = (struct RelayModuleData *)GetShmRelayModuleData();
+    ShmLedModuleData = (struct LedModuleData *)GetShmLedModuleData();
+    ShmOCPP16Data = (struct OCPP16Data *)GetShmOCPP16Data();
+    ShmOCPP20Data = (struct OCPP20Data*)GetShmOCPP20Data();
+    ShmDcCommonData = (DcCommonInfo *)GetShmDcCommonData();
+    ShmSelectGunInfo = (SelectGunInfo *)GetShmSelectGunInfo();
+	
+    ShmSysConfigAndInfo = (struct SysConfigAndInfo *)GetShmSysConfigAndInfo();
+    ShmStatusCodeData = (struct StatusCodeData *)GetShmStatusCodeData();	
+    log_info(" ********************************************************");
+    log_info(" ******************  FileSystem Boot up *****************");
+    log_info(" ********************************************************");
+    log_info(" ******************  Project:DD360Tcc   *****************");
+    log_info(" ********************************************************");
+
+    if (!InitialSystemDefaultConfig()) {
+        log_error("InitialSystemDefaultConfig NG ");
+        //StopProcessingLoop();
+        sleep(5);
+        system("reboot -f");
+    }
+    CheckGunTypeFromHw();
+    CheckIsAlternatvieByModelName();
+    InitialShareMemoryInfo();
+    GetFirmwareVersion();
+
+    if (!CheckConnectorTypeStatus()) {
+        isModelNameMatch = false;
+    }
+
+    Initialization();
+    SpawnTask();
+    log_info("Spawned all Task");
+    if (!isModelNameMatch) {
+        pAlarmCode->AlarmEvents.bits.ModelNameNoneMatchStestFail = YES;
+        //ChangeLcmByIndex(_LCM_ERROR);
+        ChangeLcmByIndex(_PAGE_MAINTAIN);
+        // Module Name 與硬體對應不正確
+        log_error("Module Name & HW info none match. ");
+        sleep(3);
+        KillAllTask();
+        StopProcessingLoop();
+    }
+    CreateTimeoutFork();    
+    log_info("Start self test... ");
+
+    SelfTestRun();
+    StopSystemTimeoutDet();
+    log_info("Self test finished : SelfTestSeq = %d, Work_Step = %d ",
+             pSysInfo->SelfTestSeq,
+             ShmPsuData->Work_Step);
+
+    if (pSysInfo->SelfTestSeq == _STEST_FAIL || ShmPsuData->Work_Step == _NO_WORKING ||
+        pInfoCode->InfoEvents.bits.CcsSeccTimeoutQCA7000Comm == YES ) {
+        ChangeLcmByIndex(_PAGE_MAINTAIN);
+        for (gunIndex = 0; gunIndex < pSysConfig->TotalConnectorCount; gunIndex++) {
+            setChargerMode(gunIndex, MODE_MAINTAIN);
+        }
+    } else {
+        for (gunIndex = 0; gunIndex < pSysConfig->TotalConnectorCount; gunIndex++) {
+            setChargerMode(gunIndex, MODE_IDLE);
+        }
+    }
+
+    // Local DB
+    if (DB_Open() != PASS) {
+        log_info("DB_Open fail. ");
+        isDb_ready = false;
+    } else {
+        isDb_ready = true;
+        for (int _index = 0; _index < pSysConfig->TotalConnectorCount; _index++) {
+            pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(_index);
+            pDcChargingInfo->IsAvailable = DB_Get_Operactive(_index);
+
+        }
+        DB_Reboot_Record();
+    }
+
+    if (PowerDB_Open() != PASS) {
+        log_info("Power DB_Open fail. ");
+        isDb_ready = false;
+    } else {
+        int _retry = 0;
+        isDb_ready = true;
+        for (int _index = 0; _index < pSysConfig->TotalConnectorCount; _index++) {
+            pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(_index);
+            while (_retry < 3) {
+                if (DB_Get_PowerConsumption(_index)) {
+                    break;
+                } else {
+                    sleep(1);
+                    _retry++;
+                    if (_retry == 3) {
+                        DB_Insert_PowerConsumption(_index, 0);
+                    }
+                }
+            } // while
+        } // for
+    }
+    log_info("===== Create DB End ===== ");
+
+    ChangeLcmByIndex(_PAGE_IDLE);
+
+    sleep(1);
+    //***** 須新增的偵測 *****//
+    // 1. Thernal - 控制風扇轉速
+    // 2. ouput fuse - 控制風扇轉速
+    CreateRfidFork();
+    // Main loop
+
+    CheckFwSlotStatusLog();
+    //AdjustChargerCurrent();
+    GetClockTime(&_cmdMainPriority_time, NULL);
+
+   // GunIndexInfo *pGunIndexInfo = (GunIndexInfo *)GetGunIndexInfo();
+
+    CheckTaskAlive();
+
+    CreateWatchdog();
+    
+    SetGunTypeOTPValue();
+
+    showversion();
+
+    ShmDcCommonData->ParkingLeaveTime = 15; //結束充電15分鐘後開始計算佔位費
+    ShmDcCommonData->SaleLeaveTime = 10;    //結算佔位費後開始計算10分鐘
+    struct ChargingInfoData *pDcInfo = NULL;
+    for (;;) {
+
+        CheckOcppStatus();
+
+        ChkPrimaryStatus();
+
+        if ((IsConnectorWholeIdle() ||
+                //(pSysInfo->PageIndex == _LCM_ERROR)) &&
+                (pSysInfo->PageIndex == _PAGE_MAINTAIN))
+           ) {
+            CheckFactoryConfigFunction();
+
+            //CheckFwUpdateFunction();
+        }
+
+        // OCPP 邏輯
+        OcppRemoteStartChk();
+
+        // 當 AC 沒有搭上時,清除一些錯誤碼
+        ClearAlarmCodeWhenAcOff();
+
+        if ((GetClockTimeoutValue(_cmdMainPriority_time) / 1000) > 5000) {
+
+            for (gunIndex = 0; gunIndex < pSysConfig->TotalConnectorCount; gunIndex++) {
+                pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+
+                if ((pDcChargingInfo->SystemStatus >= S_PREPARING_FOR_EVSE &&
+                        pDcChargingInfo->SystemStatus <= S_CHARGING) ||
+                        (pDcChargingInfo->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
+                         pDcChargingInfo->SystemStatus <= S_CCS_PRECHARGE_ST1)) {
+                    if (pDcChargingInfo->SystemStatus == S_CHARGING &&
+                            _ocppProfileChkFlag == 12) {
+                        ChargingProfileFlat(gunIndex);
+                        _ocppProfileChkFlag = 0;
+                    } else if (pDcChargingInfo->SystemStatus != S_CHARGING) {
+                        ChargingProfileFlat(gunIndex);
+                        _ocppProfileChkFlag = 0;
+                    } else {
+                        _ocppProfileChkFlag++;
+                    }
+                }
+                checkGunOTPState(gunIndex); //check gun OTP
+            }
+            GetClockTime(&_cmdMainPriority_time, NULL);
+        }
+
+        gEvBoardErr.GunErrMessage = 0; //清除系統執行中的錯誤訊息
+        gChillerTempErr.TempErrMsg = 0;//清除系統執行中的錯誤訊息
+        for (gunIndex = 0; gunIndex < pSysConfig->TotalConnectorCount; gunIndex++) {
+            pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+            // 重新收集各槍的錯誤狀態
+            collectError(gunIndex);
+            checkEvBoardAlarmState(pDcChargingInfo->Type);
+        }
+        checkChillerAlarmState();
+
+        // 確認當前錯誤 Level = 2 ?
+        ReviewCriticalAlarm();
+
+        for (gunIndex = 0; gunIndex < pSysConfig->TotalConnectorCount; gunIndex++) {
+            pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+
+            CheckGpioInStatus();
+
+            CheckErrorOccurStatus(gunIndex);
+
+            // 確認 Relay Welding or Driving Fault
+            CheckRelayWeldingOrDrivingFault(gunIndex);
+
+            ChkOcppStatus(gunIndex);
+
+            if ((pDcChargingInfo->SystemStatus >= S_PREPARING_FOR_EVSE &&
+                    pDcChargingInfo->SystemStatus <= S_CHARGING) ||
+                    (pDcChargingInfo->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
+                     pDcChargingInfo->SystemStatus <= S_CCS_PRECHARGE_ST1)) {
+                CheckSmartChargeProfile(gunIndex);
+            }
+
+            switch (pDcChargingInfo->SystemStatus) {
+            case S_IDLE:
+                if (isModeChange(gunIndex)) {
+                    log_info("============================= S_IDLE(%x) ============================= ", gunIndex);
+                    ResetIdleData(gunIndex);
+                }
+                isChargingAverageState();
+                // For RemoteStart Using
+
+                if (pDcChargingInfo->RemoteStartFlag == YES && pDcChargingInfo->IsAvailable) {
+					log_info("-------- IDLE Remote Start(%d) --------", gunIndex);
+					//ChangeGunSelectByIndex(gunIndex);
+					setChargerMode(gunIndex, MODE_AUTHORIZING);
+					break;
+                }
+                autoStartCharging(gunIndex);
+                // 讀卡邏輯
+                if (!ShmDcCommonData->TradeCancel && pSysInfo->CurGunSelected == gunIndex)
+                    ScannerCardProcess(gunIndex);
+                if (pSysInfo->SystemPage == _PAGE_SELECT_GUN || pSysInfo->SystemPage == _PAGE_IDLE) {
+                	//ShmDcCommonData->LineStatus[gunIndex] = 0;
+                	StopGunInfoTimeoutDet(gunIndex);
+				}
+
+                if (pSysInfo->CurGunSelected == gunIndex) {
+                    if (ShmDcCommonData->pGunInfo[gunIndex].isParking) {
+                        // 佔位費流程
+                        ParkingProcess(gunIndex);
+                    } else {
+                        // 一般充電流程
+                        if (pSysInfo->SystemPage == _PAGE_BILL) {
+                            StartSystemTimeoutDet(Timeout_AddLine);
+                            /*
+                            if (ShmDcCommonData->TransactionInfo[gunIndex].LineStatus == _LINE_ADD_FRIEND) {
+                                pSysInfo->SystemPage = _PAGE_ADD_FRIEND;
+                                log_info("Change to Add Line Friend Page");
+                            }
+                            */
+                        } else if (pSysInfo->SystemPage == _PAGE_ADD_FRIEND) {
+                            StopSystemTimeoutDet();
+                            StartGunInfoTimeoutDet(gunIndex, Timeout_LineReigster);
+                            if (ShmDcCommonData->TransactionInfo[gunIndex].LineStatus == _LINE_CREDITCARD_INVOICE) {
+                                StopGunInfoTimeoutDet(gunIndex);
+                                pSysInfo->SystemPage = _PAGE_SELECT_PAY;
+                                ShmDcCommonData->TransactionInfo[gunIndex].IsDonateInvoice = FALSE;
+                                log_info("Change to Select Pay Page");
+                            }
+                            if (ShmDcCommonData->TransactionInfo[gunIndex].LineStatus == _LINE_CREDITCARD_DONATE) {
+                                StopGunInfoTimeoutDet(gunIndex);
+                                pSysInfo->SystemPage = _PAGE_SELECT_PAY;
+                                ShmDcCommonData->TransactionInfo[gunIndex].IsDonateInvoice = TRUE;
+                                log_info("Change to Select Pay Page");
+                            }
+                        }
+                    }
+                }
+                // 檢查預約
+                if (ShmDcCommonData->pGunInfo[gunIndex].ReservationStatus) {
+                    setChargerMode(gunIndex, MODE_RESERVATION);
+                }
+                goto CheckStatus;
+                break;
+            case S_RESERVATION:
+                if (isModeChange(gunIndex)) {
+                    log_info("============================= S_RESERVATION(%x) ============================= ", gunIndex);
+                    ShmOCPP16Data->CsMsg.bits[gunIndex].ReserveNowConf = YES;
+                }
+                if (pDcChargingInfo->RemoteStartFlag == YES && pDcChargingInfo->IsAvailable) {
+                    log_info("-------- S_RESERVATION Remote Start(%d) --------", gunIndex);
+                    //ChangeGunSelectByIndex(gunIndex);
+                    setChargerMode(gunIndex, MODE_AUTHORIZING);
+                    break;
+                }
+                // 讀卡邏輯
+                if (!ShmDcCommonData->TradeCancel && pSysInfo->CurGunSelected == gunIndex)
+                    ScannerCardProcess(gunIndex);
+                // 檢查預約
+                if (!ShmDcCommonData->pGunInfo[gunIndex].ReservationStatus) {
+                    setChargerMode(gunIndex, MODE_IDLE);
+                }
+                goto CheckStatus;
+                break;
+            case S_FAULT:
+                if (isModeChange(gunIndex)) {
+                    if (pDcChargingInfo->SystemStatus == S_FAULT) {
+                        log_info("============================= S_FAULT(%x) ============================= ", gunIndex);
+                        //pSysInfo->SystemPage = _LCM_ERROR;
+                        //pSysInfo->SystemPage = _PAGE_MAINTAIN;
+                    }
+                }
+CheckStatus:
+                if (pDcChargingInfo->IsAvailable == NO) {
+                    setChargerMode(gunIndex, MODE_MAINTAIN);
+                    break;
+                }
+                // Refresh Error Status
+                if (pSysWarning->Level == WARN_LV_ER) {
+                    CheckErrorCode(gunIndex);
+                    if (pSysInfo->CurGunSelected == gunIndex)
+                        pSysInfo->SystemPage = _PAGE_MAINTAIN;
+                    continue;
+                }
+                if (checkGunTempFail(gunIndex)) {
+                    break;
+                }
+
+                if (PrecheckIsPass(gunIndex) == false) {
+                    log_error("Relay welding");
+                    setChargerMode(gunIndex, MODE_FAULT);
+                    if (gunIndex == pSysInfo->CurGunSelected) {
+                        //pSysInfo->SystemPage = _LCM_ERROR;
+                        pSysInfo->SystemPage = _PAGE_MAINTAIN;
+                    }
+                    break;
+                }
+                if (pDcChargingInfo->SystemStatus == S_FAULT) {
+                    setChargerMode(gunIndex, MODE_IDLE);
+                    systemPageRestoreInit();
+                }
+
+                break;
+
+            case S_AUTHORIZING:
+                if (isModeChange(gunIndex)) {
+                    log_info("============================= S_AUTHORIZING(%x) ============================= ", gunIndex);
+                    StartGunInfoTimeoutDet(gunIndex, Timeout_AuthorizingForStop);
+                }
+
+                if (pSysInfo->CurGunSelected == gunIndex)
+                    ScannerCardProcess(gunIndex);
+
+                if (pSysInfo->SystemPage == _PAGE_PLUGIN && ShmDcCommonData->TradeCancel == FALSE) {
+                    pDcChargingInfo->Replug_flag = TRUE;
+                    StopSystemTimeoutDet();
+                }
+                if (isDetectPlugin(gunIndex)) {
+                    StartGunInfoTimeoutDet(gunIndex, Timeout_WaitPlug);
+
+                    // 卡號驗證成功後,等待充電槍插入充電車
+                    if (pDcChargingInfo->RemoteStartFlag == YES) {
+                        if (pDcChargingInfo->ConnectorPlugIn == YES &&
+                                pDcChargingInfo->IsAvailable ) {
+                            log_info("-------- S_AUTHORIZING Remote Start(%d) --------", gunIndex);
+                            pDcChargingInfo->RemoteStartFlag = NO;
+                            pDcChargingInfo->isRemoteStart = YES; //DS60-120
+                            
+                            //ChangeGunSelectByIndex(gunIndex);
+                            //AddPlugInTimes(gunIndex);
+                            setChargerMode(gunIndex, MODE_REASSIGN_CHECK);
+                            strcpy((char *)pDcChargingInfo->StartUserId, "");
+                            ClearDetectPluginFlag(gunIndex);
+                            continue;
+                        }
+                    } else if (pSysInfo->OrderCharging == NO_DEFINE) {
+                        if (pDcChargingInfo->ConnectorPlugIn == YES &&
+                                pDcChargingInfo->IsAvailable &&
+                                pDcChargingInfo->SystemStatus == S_AUTHORIZING &&
+								ShmDcCommonData->AuthPass_flag[gunIndex] == TRUE &&
+                                (waitRightGunPlugIt(gunIndex) == PASS ||
+                                 waitLeftGunPlugIt(gunIndex) == PASS)
+                           ) {
+                            log_info("-------- RFID/Auto Start(%d) --------", gunIndex);
+                            //ChangeGunSelectByIndex(gunIndex);
+                            //AddPlugInTimes(gunIndex);
+                            pDcChargingInfo->isRemoteStart = NO;
+                            strcpy((char *)pDcChargingInfo->StartUserId, (char *)pSysConfig->UserId);
+                            log_info("index = %d, CardNumber = %s ",
+                                     gunIndex,
+                                     pDcChargingInfo->StartUserId);
+                            strcpy((char *)pSysConfig->UserId, "");
+                            // 當前操作的槍號,進入 Preparing
+                            setChargerMode(gunIndex, MODE_REASSIGN_CHECK);
+                            ClearDetectPluginFlag(gunIndex);
+                            continue;
+                        }
+                    }
+
+                    if (!GetIsCardScan() && pSysInfo->CurGunSelected == gunIndex &&
+                    		pSysInfo->SystemPage != _PAGE_AUTHORIZE_FAIL &&
+                    		pSysInfo->SystemPage != _PAGE_SENSING) {
+                        pSysInfo->SystemPage = _PAGE_PLUGIN;
+                    } else if (!GetIsCardScan() && pSysInfo->SystemPage == _PAGE_IDLE &&
+                        pDcChargingInfo->RemoteStartFlag == YES) {
+                        pSysInfo->CurGunSelected = gunIndex;
+                    }
+                } else if (ShmDcCommonData->AuthPass_flag[gunIndex] && pSysInfo->CurGunSelected == gunIndex &&
+                    pSysInfo->SystemPage != _PAGE_AUTHORIZE_FAIL) {
+                    pSysInfo->SystemPage = _PAGE_SENSING;
+                }
+                break;
+
+            case S_REASSIGN_CHECK: {
+                if (isModeChange(gunIndex)) {
+                    log_info("============================= S_REASSIGN_CHECK(%x) ============================= ", gunIndex);
+                    if (pSysInfo->OrderCharging != NO_DEFINE) {
+                        pSysInfo->OrderCharging = NO_DEFINE;
+                        pDcChargingInfo->_SaftyDetect = FALSE;
+                    }
+                    pDcChargingInfo->Replug_flag = TRUE;
+                    StopSystemTimeoutDet();
+                    StopGunInfoTimeoutDet(gunIndex);
+                }
+
+                setChargerMode(gunIndex, S_PREPARNING);
+                if (pSysInfo->CurGunSelected == gunIndex) {
+                    pSysInfo->SystemPage = _PAGE_PRECHARGE;
+                }
+            }
+            break;
+
+            case S_PREPARNING:
+                if (isModeChange(gunIndex)) {
+                    log_info("============================= S_PREPARNING(%x) ============================= ", gunIndex);
+                    StopGunInfoTimeoutDet(gunIndex);
+                    StartGunInfoTimeoutDet(gunIndex, Timeout_Preparing);
+                }
+
+                if (ShmPsuData->SystemPresentPsuQuantity > 0 &&
+                        ShmPsuData->SystemAvailablePower > 10 &&
+                        GetClockTimeoutValue(pDcChargingInfo->ConnectorTimeout) >= 1000000) {
+                    setChargerMode(gunIndex, MODE_PREPARE_FOR_EV);
+                }
+
+                checkEvBoardReqStop(pDcChargingInfo->SystemStatus, gunIndex);
+                if (pSysInfo->CurGunSelected == gunIndex) {
+                    pSysInfo->SystemPage = _PAGE_PRECHARGE;
+                }
+                break;
+
+            case S_PREPARING_FOR_EV: // 等待車端的通訊 (EV 小板),待車端回報後,開始樁端的測試
+                if (isModeChange(gunIndex)) {
+                    log_info("============================= S_PREPARING_FOR_EV(%x) ============================= ", gunIndex);
+                    log_info("Waitting for Gun locked.");
+                    StopGunInfoTimeoutDet(gunIndex);
+                    StartGunInfoTimeoutDet(gunIndex, Timeout_EvChargingDet);
+                }
+
+                if (pDcChargingInfo->Type == _Type_Chademo) {
+                    if (isEvGunLocked_chademo(gunIndex) == YES) {
+                        log_info("Gun Locked");
+                        setChargerMode(gunIndex, MODE_PREPARE_FOR_EVSE);
+                    }
+                } else if (pDcChargingInfo->Type == _Type_GB) {
+                    if (isEvGunLocked_gb(gunIndex) == YES) {
+                        log_info("Gun Locked");
+                        setChargerMode(gunIndex, MODE_PREPARE_FOR_EVSE);
+                    }
+                } else if (pDcChargingInfo->Type == _Type_CCS_2) {
+                    if (isEvGunLocked_ccs(gunIndex) == YES) {
+                        log_info("Gun Locked");
+                        setChargerMode(gunIndex, MODE_PREPARE_FOR_EVSE);
+                    }
+                }
+
+                checkEvBoardReqStop(pDcChargingInfo->SystemStatus, gunIndex);
+                if (pSysInfo->CurGunSelected == gunIndex) {
+                    pSysInfo->SystemPage = _PAGE_PRECHARGE;
+                }
+                break;
+
+            case S_PREPARING_FOR_EVSE:  // Ground fault test, 等待 Relay Board 通訊及測試,並將狀態回報, CSU 確認 Pass 後,開始進入充電
+                if (isModeChange(gunIndex)) {
+                    log_info("============================= S_PREPARING_FOR_EVSE(%x) ============================= ", gunIndex);
+                    StopGunInfoTimeoutDet(gunIndex);
+                    StartGunInfoTimeoutDet(gunIndex, Timeout_EvseChargingDet);
+                }
+
+                checkPileEndGfdResult(gunIndex, pDcChargingInfo->Type, pDcChargingInfo->SystemStatus);
+
+                checkEvBoardReqStop(pDcChargingInfo->SystemStatus, gunIndex);
+
+                if (pSysInfo->CurGunSelected == gunIndex) {
+                    pSysInfo->SystemPage = _PAGE_PRECHARGE;
+                }
+                break;
+
+            case S_CCS_PRECHARGE_ST0:
+                if (isModeChange(gunIndex)) {
+                    log_info("============================= CCS Precharge Processing 1(%x) ============================= ", gunIndex);
+                    StopGunInfoTimeoutDet(gunIndex);
+                    StartGunInfoTimeoutDet(gunIndex, Timeout_ForCcsPrechargeDet);
+                }
+
+                if (pDcChargingInfo->GroundFaultStatus == GFD_FAIL) {
+                    // GFD 錯誤停止
+                    RecordAlarmCode(gunIndex, "012235");
+                    ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSGfdTrip = YES;
+                }
+
+                checkEvBoardReqStop(pDcChargingInfo->SystemStatus, gunIndex);
+
+                // 等待 EV 小板 (CCS) 通知可以開始 Precharge
+                // 切換 D+ Relay to Precharge Relay
+                if (isPrechargeStatus_ccs(gunIndex) == 39 ||
+                        isPrechargeStatus_ccs(gunIndex) == 40) {
+                    if ((pDcChargingInfo->RelayKPK2Status == YES || pDcChargingInfo->PantographFlag == YES) &&
+                            pDcChargingInfo->PrechargeStatus != PRECHARGE_READY)
+                        //if (pDcChargingInfo->PrechargeStatus != PRECHARGE_PRERELAY_PASS)
+                    {
+
+                        pDcChargingInfo->PrechargeStatus = PRECHARGE_READY;
+                    }
+                } else if (isPrechargeStatus_ccs(gunIndex) == 45 ||
+                           isPrechargeStatus_ccs(gunIndex) == 46
+                          ) {
+                    setChargerMode(gunIndex, MODE_CCS_PRECHARGE_STEP1);
+                }
+                if (pSysInfo->CurGunSelected == gunIndex) {
+                    pSysInfo->SystemPage = _PAGE_PRECHARGE;
+                }
+                break;
+
+            case S_CCS_PRECHARGE_ST1:
+                if (isModeChange(gunIndex)) {
+                    log_info("============================= CCS Precharge Processing 2(%x) ============================= ", gunIndex);
+                }
+
+                if (pDcChargingInfo->GroundFaultStatus == GFD_FAIL) {
+                    // GFD 錯誤停止
+                    RecordAlarmCode(gunIndex, "012235");
+                    ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSGfdTrip = YES;
+                }
+
+                checkEvBoardReqStop(pDcChargingInfo->SystemStatus, gunIndex);
+
+                // 等待小板通知進入充電
+                // 切換 D+ Relay to Precharge Relay
+                if (pDcChargingInfo->RelayK1K2Status == YES || pDcChargingInfo->PantographFlag == YES) {
+                    pDcChargingInfo->PrechargeStatus = PRECHARGE_READY;
+                   // pSysInfo->CurGunSelected = gunIndex;
+                    setChargerMode(gunIndex, MODE_CHARGING);
+                }
+                if (pSysInfo->CurGunSelected == gunIndex) {
+                    pSysInfo->SystemPage = _PAGE_PRECHARGE;
+                }
+                break;
+
+            case S_CHARGING:  // 剛進入充電狀態,等待 EV 小板要求的輸出電流後開始輸出
+                if (isModeChange(gunIndex)) {
+                    log_info("============================= S_CHARGING(%x) ============================= ", gunIndex);
+                    StopGunInfoTimeoutDet(gunIndex);
+                    ftime(&startChargingTime[gunIndex]);
+                    strcpy((char *)ShmOCPP16Data->StartTransaction[gunIndex].ResponseIdTagInfo.Status, ""); //DS60-120 add
+                    ChangeStartOrStopDateTime(YES, gunIndex);
+                    pDcChargingInfo->Replug_flag = FALSE;
+                    ShmDcCommonData->finalcost_flag[gunIndex] = FALSE;
+                    ShmDcCommonData->TransactionInfo[gunIndex].isIntoCharge = TRUE;
+                    ShmDcCommonData->RecordEnergyTime[gunIndex] = time((time_t*)NULL);
+                    UpdateDeductInfoStatus(gunIndex, &ShmDcCommonData->TransactionInfo[gunIndex]);
+                }
+
+                if (ShmOCPP16Data->CpMsg.bits[gunIndex].StartTransactionConf) {
+                    ShmOCPP16Data->CpMsg.bits[gunIndex].StartTransactionConf = NO;
+                }
+                ftime(&endChargingTime[gunIndex]);
+                pDcChargingInfo->PresentChargedDuration = DiffTimeb(startChargingTime[gunIndex], endChargingTime[gunIndex]);
+                ShmDcCommonData->TransactionInfo[gunIndex].Energy = pDcChargingInfo->PresentChargedEnergy;
+
+                // 每秒紀錄使用電量到資料庫內
+                if ((time((time_t*)NULL) - ShmDcCommonData->RecordEnergyTime[gunIndex]) >= 1) {
+                    ShmDcCommonData->RecordEnergyTime[gunIndex] = time((time_t*)NULL);
+                    UpdateDeductInfoStatus(gunIndex, &ShmDcCommonData->TransactionInfo[gunIndex]);
+                }
+
+                if ((time((time_t*)NULL) - ShmDcCommonData->pGunInfo[gunIndex].RecordEnergyTime) >= 5) {
+                    ShmDcCommonData->pGunInfo[gunIndex].RecordEnergyTime = time((time_t*)NULL);
+                    if (ShmDcCommonData->pGunInfo[gunIndex].PowerConsumption != 0)
+                        DB_Update_PowerConsumption(gunIndex, ShmDcCommonData->pGunInfo[gunIndex].PowerConsumption);
+                }
+
+                checkPileEndGfdResult(gunIndex, pDcChargingInfo->Type, pDcChargingInfo->SystemStatus);
+
+                checkEvBoardReqStop(pDcChargingInfo->SystemStatus, gunIndex);
+
+                // Check Stop Charging
+                AuthorizeStopCharging(gunIndex);
+                if (pSysInfo->SystemPage == _PAGE_STOP_CONFIRM_LEFT ||
+                		pSysInfo->SystemPage == _PAGE_STOP_CONFIRM_RIGHT)
+                	break;
+                // LCM => Charging
+                if (pSysInfo->CurGunSelected == gunIndex && pSysInfo->SystemPage != _PAGE_IDLE &&
+                		pSysInfo->SystemPage != _PAGE_SELECT_GUN) {
+                    pSysInfo->SystemPage = _PAGE_CHARGING;
+                }
+                break;
+
+            case S_TERMINATING:
+                if (isModeChange(gunIndex)) {
+                    log_info("============================= S_TERMINATING(%x) ============================= ", gunIndex);
+                    if (strcmp((char *)ShmOCPP16Data->StopTransaction[gunIndex].StopReason, "") == EQUAL) {
+                        strcpy((char *)ShmOCPP16Data->StopTransaction[gunIndex].StopReason, "Local");
+                    }
+                    ShmDcCommonData->StopCharge[gunIndex] = TRUE;
+                    if (ShmDcCommonData->is_AutoStart[gunIndex]) {
+                        ShmDcCommonData->finalcost_flag[gunIndex] = TRUE;
+                        ShmDcCommonData->PayPass_flag[gunIndex] = TRUE;
+                    }
+
+                    if (ShmDcCommonData->finalcost_flag[gunIndex] == FALSE && pSysInfo->CurGunSelected == gunIndex) {
+                        pSysInfo->SystemPage = _PAGE_PAYING;
+                    }
+                    StartSystemTimeoutDet(Timeout_Terminating);
+                    StartGunInfoTimeoutDet(gunIndex, Timeout_FinalCost);
+
+                    ShmDcCommonData->pGunInfo[gunIndex].RecordEnergyTime = time((time_t*)NULL);
+                    if (ShmDcCommonData->pGunInfo[gunIndex].PowerConsumption != 0)
+                        DB_Update_PowerConsumption(gunIndex, ShmDcCommonData->pGunInfo[gunIndex].PowerConsumption);
+                }
+                // For Precharging timeout
+                if (pDcChargingInfo->Type == _Type_Chademo) {
+                    if (isEvStopCharging_chademo(gunIndex) == YES ||
+                            isPrechargeStatus_chademo(gunIndex) <= 0) {
+                        setChargerMode(gunIndex, MODE_COMPLETE);
+                    }
+                } else if (pDcChargingInfo->Type == _Type_GB) {
+                    if (isEvStopCharging_gb(gunIndex) == YES ||
+                            isPrechargeStatus_gb(gunIndex) <= 0) {
+                        setChargerMode(gunIndex, MODE_COMPLETE);
+                    }
+                } else if (pDcChargingInfo->Type == _Type_CCS_2) {
+                    if (isEvStopCharging_ccs(gunIndex) == YES &&
+                            (isPrechargeStatus_ccs(gunIndex) >= 53 ||
+                             isPrechargeStatus_ccs(gunIndex) == 0  ||
+                             isPrechargeStatus_ccs(gunIndex) == 13 ||
+                             isPrechargeStatus_ccs(gunIndex) == 14)
+                       ) {
+                        setChargerMode(gunIndex, MODE_COMPLETE);
+                    }
+                }
+                if (pDcChargingInfo->Replug_flag == TRUE && pSysInfo->CurGunSelected == gunIndex) {
+                    pSysInfo->SystemPage = _PAGE_PLUGOUT;
+                    break;
+                }
+
+                if (pSysInfo->CurGunSelected == gunIndex &&
+                    pSysInfo->SystemPage != _PAGE_PAYING && pSysInfo->SystemPage != _PAGE_SENSING) {
+                    if (ShmDcCommonData->PayPass_flag[gunIndex] == TRUE)
+                        pSysInfo->SystemPage = _PAGE_COMPLETE;
+                    else
+                        pSysInfo->SystemPage = _PAGE_PAYFAIL;
+                }
+                break;
+
+            case S_COMPLETE:
+                if (isModeChange(gunIndex)) {
+                    log_info ("============================= S_COMPLETE(%x) ============================= ", gunIndex);
+                    if (strcmp((char *)pDcChargingInfo->StartDateTime, "") != EQUAL) {
+                        OcppStopTransation(gunIndex);
+                    }
+                    TheEndCharging(gunIndex);
+                    
+                    if (pDcChargingInfo->Replug_flag != TRUE && pSysInfo->SystemPage != _PAGE_PLUGOUT)
+                        StopSystemTimeoutDet();
+                    if (ShmDcCommonData->is_AutoStart[gunIndex] == TRUE && pSysInfo->CurGunSelected == gunIndex)
+                        pSysInfo->SystemPage = _PAGE_COMPLETE;
+                }
+
+                //if (pSysInfo->SystemPage == _LCM_ERROR) {
+                if (pSysInfo->SystemPage == _PAGE_MAINTAIN) {
+                    break;
+                }
+                if (pSysInfo->CurGunSelected == gunIndex && ShmDcCommonData->is_exit[gunIndex]) {
+                	pSysInfo->SystemPage = _PAGE_EXIT;
+                	break;
+                }
+
+                if (pDcChargingInfo->ConnectorPlugIn == NO && 
+                    pSysInfo->SystemPage != _PAGE_PAYING && pSysInfo->SystemPage != _PAGE_SENSING) {
+                    if (pSysInfo->CurGunSelected == gunIndex) {
+                        StartGunInfoTimeoutDet(gunIndex, Timeout_ExitPage);
+                    }
+                    if (pDcChargingInfo->TimeoutFlag != Timeout_ExitPage &&
+                        pDcChargingInfo->TimeoutFlag != Timeout_FinalCost) {
+
+                        StartGunInfoTimeoutDet(gunIndex, Timeout_CompletPlugout);
+                    }
+
+                }
+
+                if (ShmDcCommonData->pGunInfo[gunIndex].isParking) {
+                    ParkingProcess(gunIndex);
+                    break;
+                }
+
+                if (pDcChargingInfo->Replug_flag == TRUE && pSysInfo->CurGunSelected == gunIndex) {
+                    pSysInfo->SystemPage = _PAGE_PLUGOUT;
+                    break;
+                }
+
+                if (pSysInfo->CurGunSelected == gunIndex && 
+                    pSysInfo->SystemPage != _PAGE_PAYING && pSysInfo->SystemPage != _PAGE_SENSING) {
+                    if (ShmDcCommonData->PayPass_flag[gunIndex] == TRUE)
+                        pSysInfo->SystemPage = _PAGE_COMPLETE;
+                    else
+                        pSysInfo->SystemPage = _PAGE_PAYFAIL;
+                }
+
+                break;
+
+            case S_ALARM:
+                if (isModeChange(gunIndex)) {
+                    log_info("============================= S_ALARM(%x)  ============================= ", gunIndex);
+                    if (strcmp((char *)ShmOCPP16Data->StopTransaction[gunIndex].StopReason, "") == EQUAL) {
+                          strcpy((char *)ShmOCPP16Data->StopTransaction[gunIndex].StopReason, "Local");
+                    }
+                    UpdateErrorCodeToOcpp(gunIndex);
+                    if (strcmp((char *)pDcChargingInfo->StartDateTime, "") != EQUAL) {
+                      OcppStopTransation(gunIndex);
+                    }
+                    TheEndCharging(gunIndex);
+                    StopGunInfoTimeoutDet(gunIndex);
+                    ShmDcCommonData->StopCharge[gunIndex] = TRUE;
+
+                    if (ShmDcCommonData->is_AutoStart[gunIndex]) {
+                        ShmDcCommonData->finalcost_flag[gunIndex] = TRUE;
+                        ShmDcCommonData->PayPass_flag[gunIndex] = TRUE;
+                    }
+
+                    if (pDcChargingInfo->Replug_flag == TRUE) {
+
+                    } else {
+                        StartGunInfoTimeoutDet(gunIndex, Timeout_FinalCost);
+						if(ShmDcCommonData->finalcost_flag[gunIndex] == FALSE && pSysInfo->CurGunSelected == gunIndex) {
+							pSysInfo->SystemPage = _PAGE_PAYING;
+						}
+                    }
+                    ShmDcCommonData->pGunInfo[gunIndex].RecordEnergyTime = time((time_t*)NULL);
+                    if (ShmDcCommonData->pGunInfo[gunIndex].PowerConsumption != 0)
+                        DB_Update_PowerConsumption(gunIndex, ShmDcCommonData->pGunInfo[gunIndex].PowerConsumption);
+                }
+
+                if (pSysWarning->Level == WARN_LV_ER) {
+					pSysInfo->SystemPage = _PAGE_MAINTAIN;
+					continue;
+				}
+
+                if (pSysInfo->CurGunSelected == gunIndex && ShmDcCommonData->is_exit[gunIndex]) {
+                    pSysInfo->SystemPage = _PAGE_EXIT;
+                    break;
+                }
+
+                if (pDcChargingInfo->ConnectorPlugIn == NO &&
+                    pSysInfo->SystemPage != _PAGE_PAYING && pSysInfo->SystemPage != _PAGE_SENSING) {
+                    if (pSysInfo->CurGunSelected == gunIndex) {
+                        StartGunInfoTimeoutDet(gunIndex, Timeout_ExitPage);
+                    }
+                    if (pDcChargingInfo->TimeoutFlag != Timeout_ExitPage &&
+                        pDcChargingInfo->TimeoutFlag != Timeout_FinalCost) {
+                        StartGunInfoTimeoutDet(gunIndex, Timeout_CompletPlugout);
+                    }
+                }
+
+                if (ShmDcCommonData->pGunInfo[gunIndex].isParking) {
+                    ParkingProcess(gunIndex);
+                    break;
+                }
+
+                if (pDcChargingInfo->Replug_flag == TRUE && pSysInfo->CurGunSelected == gunIndex) {
+                    pSysInfo->SystemPage = _PAGE_PLUGOUT;
+                    break;
+                }
+
+                if (pSysInfo->CurGunSelected == gunIndex && pSysInfo->SystemPage != _PAGE_PAYING ) {
+                	if (ShmDcCommonData->PayPass_flag[gunIndex] == TRUE)
+						pSysInfo->SystemPage = _PAGE_COMPLETE;
+					else
+						pSysInfo->SystemPage = _PAGE_PAYFAIL;
+				}
+
+                break;
+            case S_MAINTAIN:
+                if (isModeChange(gunIndex)) {
+                    log_info("============================= S_MAINTAIN(%x) ============================= ", gunIndex);
+                    pSysInfo->SystemPage = _PAGE_MAINTAIN;
+                    if (pSysInfo->FirmwareUpdate == YES) {
+                        pSysInfo->SystemPage = _PAGE_MAINTAIN;
+                        continue;
+                    }
+                    if (pDcChargingInfo->IsAvailable == NO) {
+                        log_info("Gun%d is not availbale");
+                        break;
+                    }
+
+                    if (pSysWarning->Level != WARN_LV_ER) {
+                        if (!DisplaySelfTestFailReason()) { //DS60-120 add
+                            log_info("Soft reboot for retry self-tets. ");
+                            sleep(3);
+                            system("killall OcppBackend &");
+                            KillAllTask();
+                            system("/usr/bin/run_evse_restart.sh");
+                        }
+                    }
+                    sleep(3);
+                    if (pSysWarning->Level == WARN_LV_ER) { //DS60-120 add
+                        KillTaskExceptPrimary();
+                    } else {
+                        KillTask();
+                    }
+                    /*
+                    if (pSysInfo->SelfTestSeq == _STEST_FAIL)
+                        StopProcessingLoop();
+                        */
+                }
+
+                if (pSysInfo->SelfTestSeq == _STEST_FAIL && pSysInfo->SystemTimeoutFlag != Timeout_SelftestChk) {
+                    SelfTestRun();
+                    StopSystemTimeoutDet();
+                    sleep(3);
+                    break;
+                }
+                if (pDcChargingInfo->IsAvailable && pSysInfo->SelfTestSeq == _STEST_COMPLETE) {
+                    setChargerMode(gunIndex, MODE_IDLE);
+                }
+                if (pSysInfo->CurGunSelected == gunIndex) {
+                    pSysInfo->SystemPage = _PAGE_MAINTAIN;
+                }
+                break;
+            case S_UPDATE:
+                if (isModeChange(gunIndex)) {
+                    log_info("============================= S_UPDATE ============================= ");
+                }
+                if (pSysInfo->FirmwareUpdate == YES) {
+                    pSysInfo->SystemPage = _PAGE_MAINTAIN;
+                    continue;
+                } else {
+                }
+                break;
+            default:
+                if (isModeChange(gunIndex)) {
+                    log_info("============================= UNKONWN (%x) ============================= ", gunIndex);
+                }
+                if (pSysConfig->TotalConnectorCount >= 2) {
+                    pDcInfo = (struct ChargingInfoData *)GetDcChargingInfoData((gunIndex ? LEFT_GUN_NUM : RIGHT_GUN_NUM));
+                } else {
+                    pDcInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+                }
+                if (pSysInfo->SelfTestSeq != _STEST_FAIL && !IntoOperateProcess(pDcInfo->SystemStatus)) {
+                    log_info("Gun%d into UNKOWN status, Dispenser will soft reset",gunIndex);
+                    TryCloseWatchdog();
+                    system("/usr/bin/run_evse_restart.sh");
+                }
+            }//switch
+        }//for
+
+        //if (pSysInfo->SystemPage != _LCM_VIEW)
+        //ChangeLcmByIndex(pSysInfo->SystemPage);
+
+        TryFeedWatchdog();
+        usleep(WHILE_LOOP_TIME);
+    }
+
+    return FAIL;
+}

+ 116 - 116
EVSE/Projects/DD360Tcci/Apps/CSU/main.h

@@ -1,116 +1,116 @@
-#ifndef _MAIN_H_
-#define _MAIN_H_
-
-//------------------------------------------------------------------------------
-#include <stdint.h>
-
-//------------------------------------------------------------------------------
-#define MODELNAME_FAIL                          (0)
-#define BUFFER_SIZE                             (128)
-#define BTN_RELEASE                             (0)
-#define BTN_PRESS                               (1)
-#define MAX_BUF                                 (64)
-#define SYSFS_GPIO_DIR                          "/sys/class/gpio"
-#define UPGRADE_FAN                             (0x02)
-#define UPGRADE_RB                              (0x09) //0x09 for DD360Tcci dispenser
-#define UPGRADE_PRI                             (0x04)
-#define UPGRADE_AC                              (0x05)
-#define UPGRADE_LED                             (0x06)
-#define SYSTEM_MIN_VOL                          (80) //150
-#define MIN_OUTPUT_CUR                          (0)
-#define AC_OUTPUT_VOL                           (220)
-
-#define DEFAULT_AC_INDEX                        (2)
-#define PSU_MIN_CUR                             (100)
-
-//#define DB_FILE                                 "/Storage/ChargeLog/localCgargingRecord.db"
-
-#define uSEC_VAL                                (1000000)
-#define SELFTEST_TIMEOUT                        (60)//45
-#define RETURN_VIEWPAGE_TIMEOUT                 (60)
-#define AUTHORIZE_TIMEOUT                       (60)//30
-#define BALANCE_TIMEOUT                         (15)//15
-#define AUTHORIZE_FAIL_TIMEOUT                  (5)
-#define AUTHORIZE_STOP_TIMEOUT                  (30)
-#define LINKERROR_TIMEOUT						(120)
-#define WAIT_PARKING_INFO_TIMEOUT               (10)
-#define GUN_PREPARE_TIMEOUT                     (30)
-#define GUN_EV_WAIT_TIMEOUT                     (120)
-#define GUN_EVSE_WAIT_TIMEOUT                   (60)
-#define GUN_COMP_WAIT_TIMEOUT                   (10)
-#define GUN_PRECHARGING_TIMEOUT                 (60)
-#define EVCCID_LINK_TIMEOUT                     (120)
-#define CONN_PLUG_TIMEOUT                       (40)
-#define TCC_PARK_SELECTPAY_TIMEOUT              (30)
-#define TERMINATING_TIMEOUT                     (120)
-#define WHILE_LOOP_TIME                         (10000)
-#define PRECHARGING_TTIMEOUT                    (60)
-#define PLUGOUTGUN_TIMEOUT                      (10)
-#define TCC_ADDLINE_TIMEOUT						(60)
-#define TCC_LINEREGISTER_TIMEOUT				(90)
-#define TCC_DONATECOMFIRM_TIMEOUT				(180)
-#define TCC_SELECTPAY_TIMEOUT					(180)
-#define TCC_FINALCOST_TIMEOUT					(30)
-#define TCC_SCANCARD_TIMEOUT					(30)
-#define TCC_TRADECANCEL_TIMEOUT                 (60)
-#define TCC_EXITPAGE_TIMEOUT                    (10)
-#define TCC_ISPLUGOUT_TIMEOUT                   (3)
-#define TCC_LINEPAYING_TIMEOUT                  (5)
-#define TCC_COMPLETE_PLUGOUT_TIMEOUT            (120)
-#define TCC_PARKINGBILL_TIMEOUT			    	(120)
-
-//#define log_info(format, args...) StoreLogMsg_1("[%s:%d][%s][Info] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
-//#define log_warn(format, args...) StoreLogMsg_1("[%s:%d][%s][Warn] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
-//#define log_error(format, args...) StoreLogMsg_1("[%s:%d][%s][Error] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
-
-//------------------------------------------------------------------------------
-//typedef struct StLedConfig {
-//    //OutputDrvValue[0]
-//    uint8_t LeftButtonLed: 1;                   //bit 0,    H: ON,      L:OFF
-//    uint8_t RightButtonLed: 1;                  //bit 1,    H: ON,      L:OFF
-//    uint8_t GreenLED: 1;                        //bit 2,    H: ON,      L:OFF
-//    uint8_t YellowLED: 1;                       //bit 3,    H: ON,      L:OFF
-//    uint8_t RedLED: 1;                          //bit 4,    H: ON,      L:OFF
-//    uint8_t SystemLed4: 1;                      //bit 5,    H: ON,      L:OFF
-//    uint8_t AcContactor: 1;                     //bit 6,    H: ON,      L:OFF
-//    uint8_t Reserved: 1;                        //bit 7 reserved
-//} LedConfig;
-
-//------------------------------------------------------------------------------
-bool isDetectPlugin(int gunIndex);
-void _DetectPlugInTimeout(uint8_t gunIndex);
-void _evccidlinktimeout(uint8_t gunIndex);
-void StartSystemTimeoutDet(uint8_t flag);
-void StopSystemTimeoutDet(void);
-
-void StartGunInfoTimeoutDet(uint8_t gunIndex, uint8_t flag);
-void StopGunInfoTimeoutDet(uint8_t gunIndex);
-
-void AuthorizingStart(void);
-bool IsAuthorizingMode(void);
-bool isAuthorizedComplete(void);
-void ClearAuthorizedFlag(void);
-void ClearDetectPluginFlag(int gunIndex);
-
-void ChargingAlarmProcess(uint8_t gunIndex);
-void StopChargingProcessByString(uint8_t level);
-
-void EmcOccureByString(char *code);
-void ReleaseEmsOccureByString(uint8_t index, char *code);
-
-void confirmSelGun(uint8_t selGun);
-void destroySelGun(uint8_t curGun);
-int getConfirmSelectedGun(uint8_t curSel);
-void setSelGunWaitToAuthor(uint8_t curSel);
-
-void ChargingTerminalProcess(uint8_t gunIndex);
-void AcChargingTerminalProcess(void);
-
-void ChangeGunSelectByIndex(uint8_t sel);
-
-void setChargerMode(uint8_t gun_index, uint8_t mode);
-
-void KillAllTask(void);
-void KillTask(void);
-
-#endif /* _MAIN_H_ */
+#ifndef _MAIN_H_
+#define _MAIN_H_
+
+//------------------------------------------------------------------------------
+#include <stdint.h>
+
+//------------------------------------------------------------------------------
+#define MODELNAME_FAIL                          (0)
+#define BUFFER_SIZE                             (128)
+#define BTN_RELEASE                             (0)
+#define BTN_PRESS                               (1)
+#define MAX_BUF                                 (64)
+#define SYSFS_GPIO_DIR                          "/sys/class/gpio"
+#define UPGRADE_FAN                             (0x02)
+#define UPGRADE_RB                              (0x09) //0x09 for DD360Tcci dispenser
+#define UPGRADE_PRI                             (0x04)
+#define UPGRADE_AC                              (0x05)
+#define UPGRADE_LED                             (0x06)
+#define SYSTEM_MIN_VOL                          (80) //150
+#define MIN_OUTPUT_CUR                          (0)
+#define AC_OUTPUT_VOL                           (220)
+
+#define DEFAULT_AC_INDEX                        (2)
+#define PSU_MIN_CUR                             (100)
+
+//#define DB_FILE                                 "/Storage/ChargeLog/localCgargingRecord.db"
+
+#define uSEC_VAL                                (1000000)
+#define SELFTEST_TIMEOUT                        (60)//45
+#define RETURN_VIEWPAGE_TIMEOUT                 (60)
+#define AUTHORIZE_TIMEOUT                       (60)//30
+#define BALANCE_TIMEOUT                         (15)//15
+#define AUTHORIZE_FAIL_TIMEOUT                  (5)
+#define AUTHORIZE_STOP_TIMEOUT                  (30)
+#define LINKERROR_TIMEOUT						(120)
+#define WAIT_PARKING_INFO_TIMEOUT               (10)
+#define GUN_PREPARE_TIMEOUT                     (30)
+#define GUN_EV_WAIT_TIMEOUT                     (120)
+#define GUN_EVSE_WAIT_TIMEOUT                   (60)
+#define GUN_COMP_WAIT_TIMEOUT                   (10)
+#define GUN_PRECHARGING_TIMEOUT                 (60)
+#define EVCCID_LINK_TIMEOUT                     (120)
+#define CONN_PLUG_TIMEOUT                       (40)
+#define TCC_PARK_SELECTPAY_TIMEOUT              (30)
+#define TERMINATING_TIMEOUT                     (120)
+#define WHILE_LOOP_TIME                         (10000)
+#define PRECHARGING_TTIMEOUT                    (60)
+#define PLUGOUTGUN_TIMEOUT                      (10)
+#define TCC_ADDLINE_TIMEOUT						(60)
+#define TCC_LINEREGISTER_TIMEOUT				(90)
+#define TCC_DONATECOMFIRM_TIMEOUT				(180)
+#define TCC_SELECTPAY_TIMEOUT					(180)
+#define TCC_FINALCOST_TIMEOUT					(30)
+#define TCC_SCANCARD_TIMEOUT					(30)
+#define TCC_TRADECANCEL_TIMEOUT                 (60)
+#define TCC_EXITPAGE_TIMEOUT                    (10)
+#define TCC_ISPLUGOUT_TIMEOUT                   (3)
+#define TCC_LINEPAYING_TIMEOUT                  (5)
+#define TCC_COMPLETE_PLUGOUT_TIMEOUT            (120)
+#define TCC_PARKINGBILL_TIMEOUT			    	(120)
+
+//#define log_info(format, args...) StoreLogMsg_1("[%s:%d][%s][Info] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
+//#define log_warn(format, args...) StoreLogMsg_1("[%s:%d][%s][Warn] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
+//#define log_error(format, args...) StoreLogMsg_1("[%s:%d][%s][Error] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
+
+//------------------------------------------------------------------------------
+//typedef struct StLedConfig {
+//    //OutputDrvValue[0]
+//    uint8_t LeftButtonLed: 1;                   //bit 0,    H: ON,      L:OFF
+//    uint8_t RightButtonLed: 1;                  //bit 1,    H: ON,      L:OFF
+//    uint8_t GreenLED: 1;                        //bit 2,    H: ON,      L:OFF
+//    uint8_t YellowLED: 1;                       //bit 3,    H: ON,      L:OFF
+//    uint8_t RedLED: 1;                          //bit 4,    H: ON,      L:OFF
+//    uint8_t SystemLed4: 1;                      //bit 5,    H: ON,      L:OFF
+//    uint8_t AcContactor: 1;                     //bit 6,    H: ON,      L:OFF
+//    uint8_t Reserved: 1;                        //bit 7 reserved
+//} LedConfig;
+
+//------------------------------------------------------------------------------
+bool isDetectPlugin(int gunIndex);
+void _DetectPlugInTimeout(uint8_t gunIndex);
+void _evccidlinktimeout(uint8_t gunIndex);
+void StartSystemTimeoutDet(uint8_t flag);
+void StopSystemTimeoutDet(void);
+
+void StartGunInfoTimeoutDet(uint8_t gunIndex, uint8_t flag);
+void StopGunInfoTimeoutDet(uint8_t gunIndex);
+
+void AuthorizingStart(void);
+bool IsAuthorizingMode(void);
+bool isAuthorizedComplete(void);
+void ClearAuthorizedFlag(void);
+void ClearDetectPluginFlag(int gunIndex);
+
+void ChargingAlarmProcess(uint8_t gunIndex);
+void StopChargingProcessByString(uint8_t level);
+
+void EmcOccureByString(char *code);
+void ReleaseEmsOccureByString(uint8_t index, char *code);
+
+void confirmSelGun(uint8_t selGun);
+void destroySelGun(uint8_t curGun);
+int getConfirmSelectedGun(uint8_t curSel);
+void setSelGunWaitToAuthor(uint8_t curSel);
+
+void ChargingTerminalProcess(uint8_t gunIndex);
+void AcChargingTerminalProcess(void);
+
+void ChangeGunSelectByIndex(uint8_t sel);
+
+void setChargerMode(uint8_t gun_index, uint8_t mode);
+
+void KillAllTask(void);
+void KillTask(void);
+
+#endif /* _MAIN_H_ */

+ 618 - 618
EVSE/Projects/DD360Tcci/Apps/Config.h

@@ -1,618 +1,618 @@
-/*
- * Config.h
- *
- *  Created on: 2019年4月23日
- *      Author: foluswen
- */
-#ifndef CONFIG_H_
-#define CONFIG_H_
-
-//------------------------------------------------------------------------------
-#include <stdint.h>
-#include <time.h>
-//------------------------------------------------------------------------------
-//Dispenser simulation ev signal
-//------------------------------------------------------------------------------
-#define SIMULATION 0
-//------------------------------------------------------------------------------
-//independent common share memory key
-//------------------------------------------------------------------------------
-#define ShmCsuMeterKey                          2001
-#define ShmCommonKey                            2002
-
-//------------------------------------------------------------------------------
-#define TOTAL_QUANTITY_GUN                      4               //Max Count
-
-//------------------------------------------------------------------------------
-//system  runtime state
-//------------------------------------------------------------------------------
-#define MODE_BOOT                               (0)
-#define MODE_IDLE                               (1)
-#define MODE_AUTHORIZING                        (2)
-#define MODE_REASSIGN_CHECK                     (3)
-#define MODE_REASSIGN                           (4)
-#define MODE_PRECHARGE                          (5)
-#define MODE_PREPARE_FOR_EV                     (6)
-#define MODE_PREPARE_FOR_EVSE                   (7)
-#define MODE_CHARGING                           (8)
-#define MODE_TERMINATING                        (9)
-#define MODE_COMPLETE                           (10)
-#define MODE_ALARM                              (11)
-#define MODE_FAULT                              (12)
-#define MODE_RESERVATION                        (13)
-#define MODE_BOOKING                            (14)
-#define MODE_MAINTAIN                           (15)
-#define MODE_DEBUG                              (16)
-#define MODE_CCS_PRECHARGE_STEP0                (17)  // ready for ccs precharge processing, For D+ relay to precharge relay
-#define MODE_CCS_PRECHARGE_STEP1                (18)  // waitting for ev board inform to enter to charging, For precharge relay to D+ relay
-#define MODE_UPDATE                             (19)
-
-#define GFD_WAIT                                (0)
-#define GFD_PASS                                (1)
-#define GFD_FAIL                                (2)
-#define GFD_WARNING                             (3)
-
-#define PRECHARGE_WAIT                          (0)
-#define PRECHARGE_READY                         (1)
-#define PRECHARGE_PRERELAY_PASS                 (2)
-#define PRECHARGE_CHARELAY_PASS                 (3)
-
-#define BOOTTING                                (0)
-#define BOOT_COMPLETE                           (1)
-
-//------------------------------------------------------------------------------
-//common define
-//------------------------------------------------------------------------------
-#define ARRAY_SIZE(A)                           (sizeof(A) / sizeof(A[0]))
-
-#define PASS                                    (1)
-#define FAIL                                    (-1)
-
-#define START                                   (1)
-#define STOP                                    (0)
-
-#define YES                                     (1)
-#define NO                                      (0)
-
-#define NORMAL                                  (0)
-#define ABNORMAL                                (1)
-
-#define EQUAL                                   (0)
-
-#define NO_DEFINE                               (255)
-
-#define MtdBlockSize                            (0x300000) //(0x600000)
-
-//------------------------------------------------------------------------------
-//gun temperatures
-//------------------------------------------------------------------------------
-#define GUN_OTP_VALUE                           (150)
-#define GUN_OTP_RECOVERY                        (140)
-#define UNDEFINED_TEMP                          (255)
-#define TEMP_BOUNDARY                           (200)
-
-#define WARN_LV_NL                              (0) //normal state
-#define WARN_LV_WARN                            (1)
-#define WARN_LV_ER                              (2) //emergency state
-
-#define GUNOTPDERATING                          (1)
-//------------------------------------------------------------------------------
-enum _SYSTEM_STATUS {
-    S_BOOTING = 0,
-    S_IDLE,
-    S_AUTHORIZING,
-    S_REASSIGN_CHECK,
-    S_REASSIGN,
-    S_PREPARNING,
-    S_PREPARING_FOR_EV,
-    S_PREPARING_FOR_EVSE,
-    S_CHARGING,
-    S_TERMINATING,
-    S_COMPLETE,
-    S_ALARM,
-    S_FAULT,
-    S_RESERVATION,
-    S_BOOKING,
-    S_MAINTAIN,
-    S_DEBUG,
-    S_CCS_PRECHARGE_ST0,
-    S_CCS_PRECHARGE_ST1,
-    S_UPDATE,
-    S_NONE,
-};
-
-enum _AC_SYSTEM_STATUS {
-    AC_SYS_NONE = 0,
-    AC_SYS_A,
-    AC_SYS_B,
-    AC_SYS_C,
-    AC_SYS_D,
-    AC_SYS_E
-};
-
-enum _GUN_TYPE {
-    _Type_Chademo = 0,
-    _Type_CCS_2,
-    _Type_GB,
-    _Type_AC,
-};
-enum _CCS_GUN_TYPE {
-    _TYPE_CCS_NONE  = 0,
-    _TYPE_CCS1_Natural,
-    _TYPE_CCS1_Liquid,
-    _TYPE_CCS2_Natural,
-    _TYPE_CCS2_Liquid,
-};
-
-enum _PAGE_TCC_INDEX {
-	// Face 1
-    _PAGE_NONE                   = 0x00,
-    _PAGE_IDLE,
-	_PAGE_SELECT_GUN,
-	_PAGE_BILL,
-	_PAGE_ADD_FRIEND,
-	_PAGE_DONATE_LEFT,
-	_PAGE_SELECT_PAY,
-    _PAGE_AUTHORIZE,
-	_PAGE_SENSING,
-    _PAGE_PLUGIN,
-    _PAGE_PRECHARGE,
-    _PAGE_CHARGING,
-	_PAGE_STOP_CONFIRM_LEFT,
-	_PAGE_PAYING,
-    _PAGE_COMPLETE,
-	_PAGE_EXIT,
-	_PAGE_PLUGOUT,
-	_PAGE_AUTHORIZE_FAIL,
-	_PAGE_DONATE_RIGHT,
-	_PAGE_STOP_CONFIRM_RIGHT,
-	_PAGE_PAYFAIL,
-    _PAGE_LINEPAYING,
-    _PAGE_MAINTAIN = 30,
-};
-enum _SELF_TEST_SEQ {
-    _STEST_VERSION      = 0x00,
-    _STEST_AC_CONTACTOR = 0x01,
-    _STEST_PSU_DETECT   = 0x02,
-    _STEST_PSU_CAP      = 0x03,
-    _STEST_FAIL         = 0x04,
-    _STEST_COMPLETE     = 0xEE,
-};
-
-enum _MODULE_PSU_WORK_STEP {
-    INITIAL_START    = 0,
-    GET_PSU_COUNT    = 1,
-    GET_SYS_CAP      = 2,
-    BOOTING_COMPLETE = 3,
-
-    _WORK_CHARGING   = 10,
-
-    _TEST_MODE       = 20,
-
-    _NO_WORKING      = 254,
-    _INIT_PSU_STATUS = 255,
-};
-
-enum _OFFLINE_POLICY {
-    _OFFLINE_POLICY_LOCAL_LIST       = 0x00,
-    _OFFLINE_POLICY_PHIHONG_RFID_TAG = 0x01,
-    _OFFLINE_POLICY_FREE_CHARGING    = 0x02,
-    _OFFLINE_POLICY_NO_CHARGING      = 0x03,
-};
-
-enum _REASSIGNED_RESOURCE_STEP {
-    _REASSIGNED_NONE           = 0,  //
-    _REASSIGNED_PREPARE_M_TO_A = 1,  // 系統收到需要降載需求 (輸出總電流降低),PSU Task 收到將狀態切換至下個狀態
-    _REASSIGNED_GET_NEW_CAP    = 2,  // 充電中的重新取得屬於自己火線上的總能量並透過小板通知車端 - 超過10秒直接跳下一步
-    _REASSIGNED_ADJUST_M_TO_A  = 3,  // 模塊重新分配完成
-    _REASSIGNED_RELAY_M_TO_A   = 4,  // 切斷橋接的 Relay
-
-    _REASSIGNED_PREPARE_A_TO_M = 11,
-    _REASSIGNED_ADJUST_A_TO_M  = 12, // 模塊升壓
-    _REASSIGNED_RELAY_A_TO_M   = 13, // 搭接橋接的 Relay
-    _REASSIGNED_WAITING        = 14,
-    _REASSIGNED_COMP           = 15,
-};
-
-enum _MAIN_CHARGING_MODE {
-    _MAIN_CHARGING_MODE_MAX  = 0,
-    _MAIN_CHARGING_MODE_AVER = 1,
-};
-
-enum _EXTRA_ERR_PROCESS {
-    _EXTRA_ERR_PROCESS_NONE  = 0,
-    _EXTRA_ERR_PROCESS_INUVP = 1,
-    _EXTRA_ERR_PROCESS_INOVP = 2,
-};
-
-enum _CHARGER_TYPE {
-    _CHARGER_TYPE_IEC = 0,
-    _CHARGER_TYPE_UL  = 1,
-};
-
-enum _SYS_WIFI_MODE {
-    _SYS_WIFI_MODE_DISABLE = 0,
-    _SYS_WIFI_MODE_STATION = 1,
-    _SYS_WIFI_MODE_AP      = 2,
-};
-
-enum _LED_INTENSITY_LV {
-    _LED_INTENSITY_DARKEST   = 0,
-    _LED_INTENSITY_MEDIUM    = 1,
-    _LED_INTENSITY_BRIGHTEST = 2,
-};
-
-enum _CCS_COMM_PROTOCOL {
-    _CCS_COMM_V2GMessage_DIN70121      = 0x01,
-    _CCS_COMM_V2GMessage_ISO15118_2014 = 0x02,
-    _CCS_COMM_V2GMessage_ISO15118_2018 = 0x03
-};
-
-enum _ETHERNET_USAGE {
-    _ETHERNET_USAGE_NONE = 0,
-    _ETHERNET_USAGE_LAN,
-    _ETHERNET_USAGE_WIFI,
-    _ETHERNET_USAGE_3G_4g,
-};
-
-enum _PRIMARY_CHECK_TAG {
-    _PRIMARY_CHECK_TAG_AC_CONTACT   = 0,
-    _PRIMARY_CHECK_TAG_MAIN_BREAKER = 1,
-};
-
-enum _CCS_VERSION_CHECK_TAG {
-    _CCS_VERSION_CHECK_TAG_V015S0 = 0,
-    _CCS_VERSION_CHECK_TAG_V013S0 = 1,
-};
-
-enum RELAY_STATUS_ERROR_INDEX {
-    RELAY_SMR1_P_STATUS = 0,
-    RELAY_SMR1_N_STATUS = 1,
-    RELAY_SMR2_P_STATUS = 2,
-    RELAY_SMR2_N_STATUS = 3,
-    RELAY_PARA_P_STATUS = 4,
-    RELAY_PARA_N_STATUS = 5,
-};
-
-enum RELAY_STATUS_ERROR_TYPE {
-    RELAY_STATUS_ERROR_NONE    = 0,
-    RELAY_STATUS_ERROR_WELDING = 10,
-    RELAY_STATUS_ERROR_DRIVING = 11,
-};
-
-enum _CCS_TYPE {
-    _CCS_TYPE_CCS1 = 0,
-    _CCS_TYPE_CCS2 = 1,
-};
-enum _WEATHER_TYPE {
-	_WEATHER_TYPE_SUN = 1,
-	_WEATHER_TYPE_CLOUDY,
-	_WEATHER_TYPE_RAIN,
-	_WEATHER_TYPE_THUNDER,
-	_WEATHER_TYPE_SNOW,
-	_WEATHER_TYPE_FOG,
-};
-enum _CREDITCARD_STATUS {
-	_CREDITCARD_IDLE,
-	_CREDITCARD_PREAUTH,
-	_CREDITCARD_PREAUTHCOMPLETE,
-	_CREDITCARD_CANCEL,
-	_CREDITCARD_SETTLEMENT,
-	_CREDITCARD_SALE,
-};
-enum _CREDIT_DEDUCT_STATUS {
-    _DEDUCT_COMPLETE_FAIL = 0,
-    _DEDUCT_COMPLETE_PASS = 1,
-    _DEDUCT_CANCEL,
-    _DEDUCT_PREAUTH,
-    _DEDUCT_SALE_FAIL,
-    _DEDUCT_SALE_PASS,
-    _DEDUCT_REMOTESTART,
-};
-enum _LINE_STATUS {
-    _LINE_INIT = 0,
-    _LINE_SCAN_QR,
-    _LINE_ADD_FRIEND,
-    _LINE_CREDITCARD_INVOICE,
-    _LINE_CREDITCARD_DONATE,
-    _LINE_PAY_INVOICE = 7,
-    _LINE_PAY_DONATE,
-    _LINE_PAY_OPERATE,
-    _LINE_PARKING_INVOICE,
-    _LINE_PARKING_DONATE,
-    _LINE_PARKING_ONLINE_PASS = 12,
-    _LINE_PARKING_ONLINE_FAIL,
-};
-enum _DERATING_TEMP {
-    STAGE1_GUN_DERATING_TEMP = 140,
-    STAGE2_GUN_DERATING_TEMP = 145,
-};
-//------------------------------------------------------------------------------
-//struct StructMeter {
-//    float curMeterValue;
-//    float newMeterValue;
-//    uint8_t isCalculation;
-//    float _chargingValue;
-//    float _curTotalCharging;
-//};
-
-//struct MeterInformation {
-//    struct StructMeter _meter[2];
-//    uint8_t isWorking;
-//};
-
-//struct DcCommonInformation {
-//    // check if the guns are of the same type
-//    uint8_t SysGunAreSameType;
-//    // to check the ccs version
-//    uint8_t CcsVersion;
-//    // for relay welding/driving check
-//    char RelayCheckStatus[6];
-//    char GunRelayWeldingOccur[2];
-//    char GunRelayDrivingOccur[2];
-//};
-
-typedef union {
-    uint32_t GunErrMessage;
-    struct {
-        // Chademo
-        uint8_t ChaGfdTrip: 1;
-        uint8_t ChaUvpFail: 1;
-        uint8_t ChaConnectOTP: 1;
-        uint8_t ChaConnectOVP: 1;
-        uint8_t ChaGfdWarning: 1;
-        uint8_t ChaRelayWeldingFault: 1;
-        uint8_t ChaRelayDrivingFault: 1;
-        uint8_t ChaConnectTempSensorFail: 1;
-
-        // CCS
-        uint8_t CCSGfdTrip : 1;
-        uint8_t CCSUvpFail : 1;
-        uint8_t CCSConnectOTP : 1;
-        uint8_t CCSConnectOVP : 1;
-        uint8_t CCSGfdWarning : 1;
-        uint8_t CCSRelayWeldingFault : 1;
-        uint8_t CCSRelayDrivingFault : 1;
-        uint8_t CCSConnectTempSensorFail : 1;
-
-        // GBT
-        uint8_t GBTGfdTrip : 1;
-        uint8_t GBTUvpFail : 1;
-        uint8_t GBTConnectOTP : 1;
-        uint8_t GBTConnectOVP : 1;
-        uint8_t GBTGfdWarning : 1;
-        uint8_t GBTRelayWeldingFault : 1;
-        uint8_t GBTRelayDrivingFault : 1;
-        uint8_t GBTConnectTempSensorFail : 1;
-    } GunBits;
-} EvBoardErrMsg;
-
-typedef union {
-    uint8_t AlarmState;
-    struct {
-        uint8_t EmergencyStop: 1;    //Power cabinet emergency stop
-        uint8_t DoorOpen: 1;         //Power cabinet emergency door open
-        uint8_t DcInputOVP: 1;
-        uint8_t DcInputUVP: 1;
-        uint8_t SystemL1InputOVP: 1; //Power cabinet system L1 input OVP
-        uint8_t SystemL2InputOVP: 1; //Power cabinet System L2 input OVP
-        uint8_t SystemL3InputOVP: 1; //Power cabinet System L3 input OVP
-        uint8_t PsuFailure: 1;       //Power cabinet PSU Failure Alarm
-    } StatusBit;
-} PowerAlarmState;
-
-typedef union {
-    uint8_t TempErrMsg;
-    struct {
-        uint8_t ChillerOTP: 1;            //chiller Temperature OVP
-        uint8_t ChillerTempSensorFail: 1; //Chiller temperature sensor failure
-        uint8_t ChillerTubeOTP : 1;
-        uint8_t Reserved: 5;
-    } StatusBit;
-} ChillerTempErr;
-
-typedef struct StChillerValve {
-    uint8_t MultiChillerGun; //0x80, 0: 沒有水冷槍, 1: 有水冷槍, 0x7F: 紀錄水冷槍數
-    uint8_t LeftTemp;  //左槍最高溫度
-    uint8_t RightTemp; //右槍最高溫度
-    uint8_t Reserved;
-} ChillerValve;
-
-typedef struct StPcPsuOutput { //from power cabinet PSU output
-    uint16_t Voltage;
-    uint16_t Current;
-} PcPsuOutput;
-
-typedef struct StPowerConsumptionInfo {
-    float Gun1_Consumption;
-    float Gun2_Consumption;
-    float Gun3_Consumption;
-    float Gun4_Consumption;
-} PowerConsumptionValue;
-
-typedef struct StPowConsumValue {
-    uint32_t Gun1_Consumption;
-    uint32_t Gun2_Consumption;
-    uint32_t Gun3_Consumption;
-    uint32_t Gun4_Consumption;
-} PowConsumValue;
-
-typedef struct StGunInfo {
-    int ConnectorID;
-    char ReceiptInfo[255];
-    int finalcost_flag;
-    time_t EVLoseTimer;
-    uint8_t EVLoseFlag;
-    char ReservationID[32];
-    uint8_t ReservationStatus;
-    char UserPriceString[255];
-    float PowerConsumption;
-    time_t RecordEnergyTime;
-    char ChargeStartTime[32];
-    char ChargeStopTime[32];
-    char ChargeDuration[32];
-
-
-    uint8_t withChiller;      //是否有水冷機
-    uint8_t WaitForPlugit;    // 等待插槍FLAG
-    uint8_t isParking;        // 進入佔位狀態
-    uint8_t ParkingStatus;    // 佔位狀態
-    uint8_t GetParkingBill;   // 得到Parking Bill
-    uint8_t ReqParkingBill;   // 要求主櫃對後臺要Parking Bill
-} GunInfo;
-
-typedef struct Psu_VersionInfo{
-	uint8_t n_PSU;
-	uint8_t DCVersion[32];
-	uint8_t FPCVersion[32];
-}PsuVerInfo;
-
-enum _LCM_UPGRADE_RESULT {
-    _LCM_UPGRADE_RESULT_WAIT = 0,
-    _LCM_UPGRADE_RESULT_PASS,
-    _LCM_UPGRADE_RESULT_FAIL,
-};
-
-enum _TCC_PARKING_STATUS {
-    _TCC_PARKING_NONE = 0,
-    _TCC_PARKING_OCCUPENCY,
-    _TCC_PARKING_OCCUPENCY_Ready,
-    _TCC_PARKING_REQ_PARKING_FEE,
-    _TCC_WAIT_PAY,
-    _TCC_ONLINEPAY_PASS,
-    _TCC_ONLINEPAY_FAIL,
-};
-
-typedef struct stTransInfo
-{
-	unsigned char TransDate[6];	//交易日期
-	unsigned char TransTime[6];	//交易時間
-	unsigned char ROC[12];		//EDC簽單調閱編號 (左靠右補空白)
-	unsigned char ApprovalNo[9];		//授權碼[信用卡退貨交易] (左靠右補空白)
-	unsigned char StoreId[18];		//櫃號,機號,發票號碼(左靠右補空白)
-	unsigned char RRN[12];		//信用卡交易序號
-	unsigned char CardNo[20];		//卡號(左靠右補空白),卡號部份隱藏
-	unsigned char TransAmount[12];		//交易金額
-	unsigned char VemData[64];		//無人自助設備交易資訊 交易別31/32 (預授權完成/預授權取消) 必要欄位 資訊來源為交易別13 (預授權)的回傳
-}TransInfo;
-
-typedef struct stRecordTransactionInfo
-{
-    int ConnectorID;
-	int TransactionId;
-    float Amount;
-    char DeductResult;                     // 0: Fail, 1: Pass , -1: Cancel , 99:Rededuct fail
-    unsigned char IsDonateInvoice;         // 0: Do not donate, 1: Donate
-    unsigned char LineSn[20];
-    unsigned char isIntoCharge;
-    unsigned char IsUpload;                // 0: not upload, 1: uploaded
-    TransInfo pCreditCard;
-    float Energy;
-    float prices;
-    int RedeductTime;
-    int LineStatus;                        // Line State
-    unsigned char OccupancySN[36];
-    int ParkingDuration;
-    char ParkingStartTime[32];
-    time_t ParkingStopTime;
-    int ParkingCntDownFlag;
-}RecordTransactionInfo;
-
-typedef struct stPriceBillInfo {
-    float TotalCost;
-    float Balance;
-    float Discount;
-    int TransactionId;
-    float EnergyCost;
-    float ParkingFee;
-    float RemainAmount;
-    uint8_t gunIndex;
-}PriceBillInfo;
-typedef struct StDcCommonInfo {
-    uint8_t RebootCount;
-    uint8_t CcsVersion;
-    EvBoardErrMsg ConnectErrList[2]; //connector error list, 0: left gun, 1: right gun
-    uint8_t CheckRelayStatus[6]; //check Relay welding or driving fault
-    uint8_t GunRelayWeldingOccur[2];
-    uint8_t GunRelayDrivingOccur[2];
-    uint8_t ConnectorTemp[2][2];
-    uint8_t SystemTemp[4];
-    uint8_t SystemModeChange[2]; //for Module_EvRxComm
-    PowerAlarmState PowerAlarmState;
-    ChillerTempErr ChillerTempErr[2];
-    ChillerValve ChillerValve;
-    uint8_t TestTemperature; //ReadCmdline test, manual input value
-    uint8_t CcsTypeSaved[2];
-    PcPsuOutput PcPsuOutput[2];
-    uint8_t _upgrade_lcm_flag;
-    uint8_t _upgrade_lcm_result;
-    uint8_t Reserved[1];
-    // Power Cabinet Version
-    uint8_t CabinetModelName[32];
-    uint8_t CabinetBoolLoaderVersion[32];
-    uint8_t CabinetKernelVersion[32];
-    uint8_t CabinetRFSystemVersion[32];
-    uint8_t CabinetPrimaryVersion[32];
-    uint8_t CabinetIPAddr[32];
-    uint8_t CabinetRelay0Version[32];
-    uint8_t CabinetRelay1Version[32];
-    uint8_t CabinetFanVersion[32];
-    // PSU Version
-    uint8_t PSU_Number;
-    PsuVerInfo PsuVer[12];
-
-    int WeatherID; // 0:sun, 1:cloudy, 2:rain, 3:snow, 4:storm, 5:fog
-    float Temperature;
-    int Location;
-    char PresentTime[128];
-    //TransInfo pCreditCard[2];
-    int runningcost[2];
-    unsigned int finalcost_flag[2];
-    float ChargingRate;
-    int PreAuth_Config;
-    int PreAuth_Result;
-    unsigned int AuthPass_flag[2];
-    unsigned int PayPass_flag[2];
-    unsigned int StopCharge[2];
-    unsigned int TradeCancel;
-    int ConnectorID[2];
-
-    RecordTransactionInfo TransactionInfo[2];
-    RecordTransactionInfo RedeductBill;
-    RecordTransactionInfo ParkingInfo[2];
-    PriceBillInfo PriceBill;
-
-    int UnionSettlement;
-    int Exe_ReDeduct;
-    unsigned int OperateIDLE[2];
-    int RoutineReduct;
-    int RoutineSettlement;
-    int RoutineReupload;
-    int TZOffset;
-    int DebugFlag;
-    int is_RemoteStart[2];
-    int is_AutoStart[2];
-    time_t RecordEnergyTime[2];
-    int is_exit[2];
-    time_t EVDisconnectTime[2];
-    int EVDisconnectFlag[2];
-    int is_plugout[2];
-    GunInfo pGunInfo[2];
-    time_t FanOnTime;
-    uint8_t AuthroizeType; // 0: Central   1: eMAID    2: ISO14443 3: ISO15693 4: KeyCode  5: Local    6: MacAddress   7: NoAuthorization
-    char QRCodeString[255];
-    char DefaultPriceString[255];
-    PowerConsumptionValue pConsumption;
-    uint8_t CreditCardUpload;
-    uint8_t tccdev;
-    uint8_t TaiwanEast;
-    uint8_t lcmtest;
-    char DebugVersion[32];
-    uint8_t BackLight;
-    float ParkingRate;
-    int ParkingLeaveTime;
-    int SaleLeaveTime;
-    int netdump; //印出網路封包
-} DcCommonInfo;
-
-#endif /* CONFIG_H_ */
+/*
+ * Config.h
+ *
+ *  Created on: 2019年4月23日
+ *      Author: foluswen
+ */
+#ifndef CONFIG_H_
+#define CONFIG_H_
+
+//------------------------------------------------------------------------------
+#include <stdint.h>
+#include <time.h>
+//------------------------------------------------------------------------------
+//Dispenser simulation ev signal
+//------------------------------------------------------------------------------
+#define SIMULATION 0
+//------------------------------------------------------------------------------
+//independent common share memory key
+//------------------------------------------------------------------------------
+#define ShmCsuMeterKey                          2001
+#define ShmCommonKey                            2002
+
+//------------------------------------------------------------------------------
+#define TOTAL_QUANTITY_GUN                      4               //Max Count
+
+//------------------------------------------------------------------------------
+//system  runtime state
+//------------------------------------------------------------------------------
+#define MODE_BOOT                               (0)
+#define MODE_IDLE                               (1)
+#define MODE_AUTHORIZING                        (2)
+#define MODE_REASSIGN_CHECK                     (3)
+#define MODE_REASSIGN                           (4)
+#define MODE_PRECHARGE                          (5)
+#define MODE_PREPARE_FOR_EV                     (6)
+#define MODE_PREPARE_FOR_EVSE                   (7)
+#define MODE_CHARGING                           (8)
+#define MODE_TERMINATING                        (9)
+#define MODE_COMPLETE                           (10)
+#define MODE_ALARM                              (11)
+#define MODE_FAULT                              (12)
+#define MODE_RESERVATION                        (13)
+#define MODE_BOOKING                            (14)
+#define MODE_MAINTAIN                           (15)
+#define MODE_DEBUG                              (16)
+#define MODE_CCS_PRECHARGE_STEP0                (17)  // ready for ccs precharge processing, For D+ relay to precharge relay
+#define MODE_CCS_PRECHARGE_STEP1                (18)  // waitting for ev board inform to enter to charging, For precharge relay to D+ relay
+#define MODE_UPDATE                             (19)
+
+#define GFD_WAIT                                (0)
+#define GFD_PASS                                (1)
+#define GFD_FAIL                                (2)
+#define GFD_WARNING                             (3)
+
+#define PRECHARGE_WAIT                          (0)
+#define PRECHARGE_READY                         (1)
+#define PRECHARGE_PRERELAY_PASS                 (2)
+#define PRECHARGE_CHARELAY_PASS                 (3)
+
+#define BOOTTING                                (0)
+#define BOOT_COMPLETE                           (1)
+
+//------------------------------------------------------------------------------
+//common define
+//------------------------------------------------------------------------------
+#define ARRAY_SIZE(A)                           (sizeof(A) / sizeof(A[0]))
+
+#define PASS                                    (1)
+#define FAIL                                    (-1)
+
+#define START                                   (1)
+#define STOP                                    (0)
+
+#define YES                                     (1)
+#define NO                                      (0)
+
+#define NORMAL                                  (0)
+#define ABNORMAL                                (1)
+
+#define EQUAL                                   (0)
+
+#define NO_DEFINE                               (255)
+
+#define MtdBlockSize                            (0x300000) //(0x600000)
+
+//------------------------------------------------------------------------------
+//gun temperatures
+//------------------------------------------------------------------------------
+#define GUN_OTP_VALUE                           (150)
+#define GUN_OTP_RECOVERY                        (140)
+#define UNDEFINED_TEMP                          (255)
+#define TEMP_BOUNDARY                           (200)
+
+#define WARN_LV_NL                              (0) //normal state
+#define WARN_LV_WARN                            (1)
+#define WARN_LV_ER                              (2) //emergency state
+
+#define GUNOTPDERATING                          (1)
+//------------------------------------------------------------------------------
+enum _SYSTEM_STATUS {
+    S_BOOTING = 0,
+    S_IDLE,
+    S_AUTHORIZING,
+    S_REASSIGN_CHECK,
+    S_REASSIGN,
+    S_PREPARNING,
+    S_PREPARING_FOR_EV,
+    S_PREPARING_FOR_EVSE,
+    S_CHARGING,
+    S_TERMINATING,
+    S_COMPLETE,
+    S_ALARM,
+    S_FAULT,
+    S_RESERVATION,
+    S_BOOKING,
+    S_MAINTAIN,
+    S_DEBUG,
+    S_CCS_PRECHARGE_ST0,
+    S_CCS_PRECHARGE_ST1,
+    S_UPDATE,
+    S_NONE,
+};
+
+enum _AC_SYSTEM_STATUS {
+    AC_SYS_NONE = 0,
+    AC_SYS_A,
+    AC_SYS_B,
+    AC_SYS_C,
+    AC_SYS_D,
+    AC_SYS_E
+};
+
+enum _GUN_TYPE {
+    _Type_Chademo = 0,
+    _Type_CCS_2,
+    _Type_GB,
+    _Type_AC,
+};
+enum _CCS_GUN_TYPE {
+    _TYPE_CCS_NONE  = 0,
+    _TYPE_CCS1_Natural,
+    _TYPE_CCS1_Liquid,
+    _TYPE_CCS2_Natural,
+    _TYPE_CCS2_Liquid,
+};
+
+enum _PAGE_TCC_INDEX {
+	// Face 1
+    _PAGE_NONE                   = 0x00,
+    _PAGE_IDLE,
+	_PAGE_SELECT_GUN,
+	_PAGE_BILL,
+	_PAGE_ADD_FRIEND,
+	_PAGE_DONATE_LEFT,
+	_PAGE_SELECT_PAY,
+    _PAGE_AUTHORIZE,
+	_PAGE_SENSING,
+    _PAGE_PLUGIN,
+    _PAGE_PRECHARGE,
+    _PAGE_CHARGING,
+	_PAGE_STOP_CONFIRM_LEFT,
+	_PAGE_PAYING,
+    _PAGE_COMPLETE,
+	_PAGE_EXIT,
+	_PAGE_PLUGOUT,
+	_PAGE_AUTHORIZE_FAIL,
+	_PAGE_DONATE_RIGHT,
+	_PAGE_STOP_CONFIRM_RIGHT,
+	_PAGE_PAYFAIL,
+    _PAGE_LINEPAYING,
+    _PAGE_MAINTAIN = 30,
+};
+enum _SELF_TEST_SEQ {
+    _STEST_VERSION      = 0x00,
+    _STEST_AC_CONTACTOR = 0x01,
+    _STEST_PSU_DETECT   = 0x02,
+    _STEST_PSU_CAP      = 0x03,
+    _STEST_FAIL         = 0x04,
+    _STEST_COMPLETE     = 0xEE,
+};
+
+enum _MODULE_PSU_WORK_STEP {
+    INITIAL_START    = 0,
+    GET_PSU_COUNT    = 1,
+    GET_SYS_CAP      = 2,
+    BOOTING_COMPLETE = 3,
+
+    _WORK_CHARGING   = 10,
+
+    _TEST_MODE       = 20,
+
+    _NO_WORKING      = 254,
+    _INIT_PSU_STATUS = 255,
+};
+
+enum _OFFLINE_POLICY {
+    _OFFLINE_POLICY_LOCAL_LIST       = 0x00,
+    _OFFLINE_POLICY_PHIHONG_RFID_TAG = 0x01,
+    _OFFLINE_POLICY_FREE_CHARGING    = 0x02,
+    _OFFLINE_POLICY_NO_CHARGING      = 0x03,
+};
+
+enum _REASSIGNED_RESOURCE_STEP {
+    _REASSIGNED_NONE           = 0,  //
+    _REASSIGNED_PREPARE_M_TO_A = 1,  // 系統收到需要降載需求 (輸出總電流降低),PSU Task 收到將狀態切換至下個狀態
+    _REASSIGNED_GET_NEW_CAP    = 2,  // 充電中的重新取得屬於自己火線上的總能量並透過小板通知車端 - 超過10秒直接跳下一步
+    _REASSIGNED_ADJUST_M_TO_A  = 3,  // 模塊重新分配完成
+    _REASSIGNED_RELAY_M_TO_A   = 4,  // 切斷橋接的 Relay
+
+    _REASSIGNED_PREPARE_A_TO_M = 11,
+    _REASSIGNED_ADJUST_A_TO_M  = 12, // 模塊升壓
+    _REASSIGNED_RELAY_A_TO_M   = 13, // 搭接橋接的 Relay
+    _REASSIGNED_WAITING        = 14,
+    _REASSIGNED_COMP           = 15,
+};
+
+enum _MAIN_CHARGING_MODE {
+    _MAIN_CHARGING_MODE_MAX  = 0,
+    _MAIN_CHARGING_MODE_AVER = 1,
+};
+
+enum _EXTRA_ERR_PROCESS {
+    _EXTRA_ERR_PROCESS_NONE  = 0,
+    _EXTRA_ERR_PROCESS_INUVP = 1,
+    _EXTRA_ERR_PROCESS_INOVP = 2,
+};
+
+enum _CHARGER_TYPE {
+    _CHARGER_TYPE_IEC = 0,
+    _CHARGER_TYPE_UL  = 1,
+};
+
+enum _SYS_WIFI_MODE {
+    _SYS_WIFI_MODE_DISABLE = 0,
+    _SYS_WIFI_MODE_STATION = 1,
+    _SYS_WIFI_MODE_AP      = 2,
+};
+
+enum _LED_INTENSITY_LV {
+    _LED_INTENSITY_DARKEST   = 0,
+    _LED_INTENSITY_MEDIUM    = 1,
+    _LED_INTENSITY_BRIGHTEST = 2,
+};
+
+enum _CCS_COMM_PROTOCOL {
+    _CCS_COMM_V2GMessage_DIN70121      = 0x01,
+    _CCS_COMM_V2GMessage_ISO15118_2014 = 0x02,
+    _CCS_COMM_V2GMessage_ISO15118_2018 = 0x03
+};
+
+enum _ETHERNET_USAGE {
+    _ETHERNET_USAGE_NONE = 0,
+    _ETHERNET_USAGE_LAN,
+    _ETHERNET_USAGE_WIFI,
+    _ETHERNET_USAGE_3G_4g,
+};
+
+enum _PRIMARY_CHECK_TAG {
+    _PRIMARY_CHECK_TAG_AC_CONTACT   = 0,
+    _PRIMARY_CHECK_TAG_MAIN_BREAKER = 1,
+};
+
+enum _CCS_VERSION_CHECK_TAG {
+    _CCS_VERSION_CHECK_TAG_V015S0 = 0,
+    _CCS_VERSION_CHECK_TAG_V013S0 = 1,
+};
+
+enum RELAY_STATUS_ERROR_INDEX {
+    RELAY_SMR1_P_STATUS = 0,
+    RELAY_SMR1_N_STATUS = 1,
+    RELAY_SMR2_P_STATUS = 2,
+    RELAY_SMR2_N_STATUS = 3,
+    RELAY_PARA_P_STATUS = 4,
+    RELAY_PARA_N_STATUS = 5,
+};
+
+enum RELAY_STATUS_ERROR_TYPE {
+    RELAY_STATUS_ERROR_NONE    = 0,
+    RELAY_STATUS_ERROR_WELDING = 10,
+    RELAY_STATUS_ERROR_DRIVING = 11,
+};
+
+enum _CCS_TYPE {
+    _CCS_TYPE_CCS1 = 0,
+    _CCS_TYPE_CCS2 = 1,
+};
+enum _WEATHER_TYPE {
+	_WEATHER_TYPE_SUN = 1,
+	_WEATHER_TYPE_CLOUDY,
+	_WEATHER_TYPE_RAIN,
+	_WEATHER_TYPE_THUNDER,
+	_WEATHER_TYPE_SNOW,
+	_WEATHER_TYPE_FOG,
+};
+enum _CREDITCARD_STATUS {
+	_CREDITCARD_IDLE,
+	_CREDITCARD_PREAUTH,
+	_CREDITCARD_PREAUTHCOMPLETE,
+	_CREDITCARD_CANCEL,
+	_CREDITCARD_SETTLEMENT,
+	_CREDITCARD_SALE,
+};
+enum _CREDIT_DEDUCT_STATUS {
+    _DEDUCT_COMPLETE_FAIL = 0,
+    _DEDUCT_COMPLETE_PASS = 1,
+    _DEDUCT_CANCEL,
+    _DEDUCT_PREAUTH,
+    _DEDUCT_SALE_FAIL,
+    _DEDUCT_SALE_PASS,
+    _DEDUCT_REMOTESTART,
+};
+enum _LINE_STATUS {
+    _LINE_INIT = 0,
+    _LINE_SCAN_QR,
+    _LINE_ADD_FRIEND,
+    _LINE_CREDITCARD_INVOICE,
+    _LINE_CREDITCARD_DONATE,
+    _LINE_PAY_INVOICE = 7,
+    _LINE_PAY_DONATE,
+    _LINE_PAY_OPERATE,
+    _LINE_PARKING_INVOICE,
+    _LINE_PARKING_DONATE,
+    _LINE_PARKING_ONLINE_PASS = 12,
+    _LINE_PARKING_ONLINE_FAIL,
+};
+enum _DERATING_TEMP {
+    STAGE1_GUN_DERATING_TEMP = 140,
+    STAGE2_GUN_DERATING_TEMP = 145,
+};
+//------------------------------------------------------------------------------
+//struct StructMeter {
+//    float curMeterValue;
+//    float newMeterValue;
+//    uint8_t isCalculation;
+//    float _chargingValue;
+//    float _curTotalCharging;
+//};
+
+//struct MeterInformation {
+//    struct StructMeter _meter[2];
+//    uint8_t isWorking;
+//};
+
+//struct DcCommonInformation {
+//    // check if the guns are of the same type
+//    uint8_t SysGunAreSameType;
+//    // to check the ccs version
+//    uint8_t CcsVersion;
+//    // for relay welding/driving check
+//    char RelayCheckStatus[6];
+//    char GunRelayWeldingOccur[2];
+//    char GunRelayDrivingOccur[2];
+//};
+
+typedef union {
+    uint32_t GunErrMessage;
+    struct {
+        // Chademo
+        uint8_t ChaGfdTrip: 1;
+        uint8_t ChaUvpFail: 1;
+        uint8_t ChaConnectOTP: 1;
+        uint8_t ChaConnectOVP: 1;
+        uint8_t ChaGfdWarning: 1;
+        uint8_t ChaRelayWeldingFault: 1;
+        uint8_t ChaRelayDrivingFault: 1;
+        uint8_t ChaConnectTempSensorFail: 1;
+
+        // CCS
+        uint8_t CCSGfdTrip : 1;
+        uint8_t CCSUvpFail : 1;
+        uint8_t CCSConnectOTP : 1;
+        uint8_t CCSConnectOVP : 1;
+        uint8_t CCSGfdWarning : 1;
+        uint8_t CCSRelayWeldingFault : 1;
+        uint8_t CCSRelayDrivingFault : 1;
+        uint8_t CCSConnectTempSensorFail : 1;
+
+        // GBT
+        uint8_t GBTGfdTrip : 1;
+        uint8_t GBTUvpFail : 1;
+        uint8_t GBTConnectOTP : 1;
+        uint8_t GBTConnectOVP : 1;
+        uint8_t GBTGfdWarning : 1;
+        uint8_t GBTRelayWeldingFault : 1;
+        uint8_t GBTRelayDrivingFault : 1;
+        uint8_t GBTConnectTempSensorFail : 1;
+    } GunBits;
+} EvBoardErrMsg;
+
+typedef union {
+    uint8_t AlarmState;
+    struct {
+        uint8_t EmergencyStop: 1;    //Power cabinet emergency stop
+        uint8_t DoorOpen: 1;         //Power cabinet emergency door open
+        uint8_t DcInputOVP: 1;
+        uint8_t DcInputUVP: 1;
+        uint8_t SystemL1InputOVP: 1; //Power cabinet system L1 input OVP
+        uint8_t SystemL2InputOVP: 1; //Power cabinet System L2 input OVP
+        uint8_t SystemL3InputOVP: 1; //Power cabinet System L3 input OVP
+        uint8_t PsuFailure: 1;       //Power cabinet PSU Failure Alarm
+    } StatusBit;
+} PowerAlarmState;
+
+typedef union {
+    uint8_t TempErrMsg;
+    struct {
+        uint8_t ChillerOTP: 1;            //chiller Temperature OVP
+        uint8_t ChillerTempSensorFail: 1; //Chiller temperature sensor failure
+        uint8_t ChillerTubeOTP : 1;
+        uint8_t Reserved: 5;
+    } StatusBit;
+} ChillerTempErr;
+
+typedef struct StChillerValve {
+    uint8_t MultiChillerGun; //0x80, 0: 沒有水冷槍, 1: 有水冷槍, 0x7F: 紀錄水冷槍數
+    uint8_t LeftTemp;  //左槍最高溫度
+    uint8_t RightTemp; //右槍最高溫度
+    uint8_t Reserved;
+} ChillerValve;
+
+typedef struct StPcPsuOutput { //from power cabinet PSU output
+    uint16_t Voltage;
+    uint16_t Current;
+} PcPsuOutput;
+
+typedef struct StPowerConsumptionInfo {
+    float Gun1_Consumption;
+    float Gun2_Consumption;
+    float Gun3_Consumption;
+    float Gun4_Consumption;
+} PowerConsumptionValue;
+
+typedef struct StPowConsumValue {
+    uint32_t Gun1_Consumption;
+    uint32_t Gun2_Consumption;
+    uint32_t Gun3_Consumption;
+    uint32_t Gun4_Consumption;
+} PowConsumValue;
+
+typedef struct StGunInfo {
+    int ConnectorID;
+    char ReceiptInfo[255];
+    int finalcost_flag;
+    time_t EVLoseTimer;
+    uint8_t EVLoseFlag;
+    char ReservationID[32];
+    uint8_t ReservationStatus;
+    char UserPriceString[255];
+    float PowerConsumption;
+    time_t RecordEnergyTime;
+    char ChargeStartTime[32];
+    char ChargeStopTime[32];
+    char ChargeDuration[32];
+
+
+    uint8_t withChiller;      //是否有水冷機
+    uint8_t WaitForPlugit;    // 等待插槍FLAG
+    uint8_t isParking;        // 進入佔位狀態
+    uint8_t ParkingStatus;    // 佔位狀態
+    uint8_t GetParkingBill;   // 得到Parking Bill
+    uint8_t ReqParkingBill;   // 要求主櫃對後臺要Parking Bill
+} GunInfo;
+
+typedef struct Psu_VersionInfo{
+	uint8_t n_PSU;
+	uint8_t DCVersion[32];
+	uint8_t FPCVersion[32];
+}PsuVerInfo;
+
+enum _LCM_UPGRADE_RESULT {
+    _LCM_UPGRADE_RESULT_WAIT = 0,
+    _LCM_UPGRADE_RESULT_PASS,
+    _LCM_UPGRADE_RESULT_FAIL,
+};
+
+enum _TCC_PARKING_STATUS {
+    _TCC_PARKING_NONE = 0,
+    _TCC_PARKING_OCCUPENCY,
+    _TCC_PARKING_OCCUPENCY_Ready,
+    _TCC_PARKING_REQ_PARKING_FEE,
+    _TCC_WAIT_PAY,
+    _TCC_ONLINEPAY_PASS,
+    _TCC_ONLINEPAY_FAIL,
+};
+
+typedef struct stTransInfo
+{
+	unsigned char TransDate[6];	//交易日期
+	unsigned char TransTime[6];	//交易時間
+	unsigned char ROC[12];		//EDC簽單調閱編號 (左靠右補空白)
+	unsigned char ApprovalNo[9];		//授權碼[信用卡退貨交易] (左靠右補空白)
+	unsigned char StoreId[18];		//櫃號,機號,發票號碼(左靠右補空白)
+	unsigned char RRN[12];		//信用卡交易序號
+	unsigned char CardNo[20];		//卡號(左靠右補空白),卡號部份隱藏
+	unsigned char TransAmount[12];		//交易金額
+	unsigned char VemData[64];		//無人自助設備交易資訊 交易別31/32 (預授權完成/預授權取消) 必要欄位 資訊來源為交易別13 (預授權)的回傳
+}TransInfo;
+
+typedef struct stRecordTransactionInfo
+{
+    int ConnectorID;
+	int TransactionId;
+    float Amount;
+    char DeductResult;                     // 0: Fail, 1: Pass , -1: Cancel , 99:Rededuct fail
+    unsigned char IsDonateInvoice;         // 0: Do not donate, 1: Donate
+    unsigned char LineSn[20];
+    unsigned char isIntoCharge;
+    unsigned char IsUpload;                // 0: not upload, 1: uploaded
+    TransInfo pCreditCard;
+    float Energy;
+    float prices;
+    int RedeductTime;
+    int LineStatus;                        // Line State
+    unsigned char OccupancySN[36];
+    int ParkingDuration;
+    char ParkingStartTime[32];
+    time_t ParkingStopTime;
+    int ParkingCntDownFlag;
+}RecordTransactionInfo;
+
+typedef struct stPriceBillInfo {
+    float TotalCost;
+    float Balance;
+    float Discount;
+    int TransactionId;
+    float EnergyCost;
+    float ParkingFee;
+    float RemainAmount;
+    uint8_t gunIndex;
+}PriceBillInfo;
+typedef struct StDcCommonInfo {
+    uint8_t RebootCount;
+    uint8_t CcsVersion;
+    EvBoardErrMsg ConnectErrList[2]; //connector error list, 0: left gun, 1: right gun
+    uint8_t CheckRelayStatus[6]; //check Relay welding or driving fault
+    uint8_t GunRelayWeldingOccur[2];
+    uint8_t GunRelayDrivingOccur[2];
+    uint8_t ConnectorTemp[2][2];
+    uint8_t SystemTemp[4];
+    uint8_t SystemModeChange[2]; //for Module_EvRxComm
+    PowerAlarmState PowerAlarmState;
+    ChillerTempErr ChillerTempErr[2];
+    ChillerValve ChillerValve;
+    uint8_t TestTemperature; //ReadCmdline test, manual input value
+    uint8_t CcsTypeSaved[2];
+    PcPsuOutput PcPsuOutput[2];
+    uint8_t _upgrade_lcm_flag;
+    uint8_t _upgrade_lcm_result;
+    uint8_t Reserved[1];
+    // Power Cabinet Version
+    uint8_t CabinetModelName[32];
+    uint8_t CabinetBoolLoaderVersion[32];
+    uint8_t CabinetKernelVersion[32];
+    uint8_t CabinetRFSystemVersion[32];
+    uint8_t CabinetPrimaryVersion[32];
+    uint8_t CabinetIPAddr[32];
+    uint8_t CabinetRelay0Version[32];
+    uint8_t CabinetRelay1Version[32];
+    uint8_t CabinetFanVersion[32];
+    // PSU Version
+    uint8_t PSU_Number;
+    PsuVerInfo PsuVer[12];
+
+    int WeatherID; // 0:sun, 1:cloudy, 2:rain, 3:snow, 4:storm, 5:fog
+    float Temperature;
+    int Location;
+    char PresentTime[128];
+    //TransInfo pCreditCard[2];
+    int runningcost[2];
+    unsigned int finalcost_flag[2];
+    float ChargingRate;
+    int PreAuth_Config;
+    int PreAuth_Result;
+    unsigned int AuthPass_flag[2];
+    unsigned int PayPass_flag[2];
+    unsigned int StopCharge[2];
+    unsigned int TradeCancel;
+    int ConnectorID[2];
+
+    RecordTransactionInfo TransactionInfo[2];
+    RecordTransactionInfo RedeductBill;
+    RecordTransactionInfo ParkingInfo[2];
+    PriceBillInfo PriceBill;
+
+    int UnionSettlement;
+    int Exe_ReDeduct;
+    unsigned int OperateIDLE[2];
+    int RoutineReduct;
+    int RoutineSettlement;
+    int RoutineReupload;
+    int TZOffset;
+    int DebugFlag;
+    int is_RemoteStart[2];
+    int is_AutoStart[2];
+    time_t RecordEnergyTime[2];
+    int is_exit[2];
+    time_t EVDisconnectTime[2];
+    int EVDisconnectFlag[2];
+    int is_plugout[2];
+    GunInfo pGunInfo[2];
+    time_t FanOnTime;
+    uint8_t AuthroizeType; // 0: Central   1: eMAID    2: ISO14443 3: ISO15693 4: KeyCode  5: Local    6: MacAddress   7: NoAuthorization
+    char QRCodeString[255];
+    char DefaultPriceString[255];
+    PowerConsumptionValue pConsumption;
+    uint8_t CreditCardUpload;
+    uint8_t tccdev;
+    uint8_t TaiwanEast;
+    uint8_t lcmtest;
+    char DebugVersion[32];
+    uint8_t BackLight;
+    float ParkingRate;
+    int ParkingLeaveTime;
+    int SaleLeaveTime;
+    int netdump; //印出網路封包
+} DcCommonInfo;
+
+#endif /* CONFIG_H_ */

+ 1266 - 1266
EVSE/Projects/DD360Tcci/Apps/DataBase/DataBase.c

@@ -1,1267 +1,1267 @@
-#include <stdio.h>      /*標準輸入輸出定義*/
-#include <stdlib.h>     /*標準函數庫定義*/
-#include <string.h>
-#include <stdint.h>
-#include <time.h>
-
-#include "../Config.h"
-#include "../Log/log.h"
-#include "../Define/define.h"
-#include "../ShareMemory/shmMem.h"
-
-//------------------------------------------------------------------------------
-#define DB_FILE                                 "/Storage/ChargeLog/localCgargingRecord.db"
-#define DEDUCT_FILE                 			"/Storage/ChargeLog/CreditCardRecord.db"
-#define PARKINGDEDUCT_FILE                 		"/Storage/ChargeLog/ParkingCreditCardRecord.db"
-#define POWER_FILE                 			    "/Storage/ChargeLog/PowerConsumption.db"
-//------------------------------------------------------------------------------
-static sqlite3 *localDb;
-static sqlite3 *deductDb;
-static sqlite3 *parkingDb;
-static sqlite3* powerDb;
-static DcCommonInfo* ShmDcCommonData = NULL;
-//------------------------------------------------------------------------------
-//===============================================
-// SQLite3 related routine
-//===============================================
-int DB_Open(void)
-{
-    int result = PASS;
-    char *errMsg = NULL;
-    char *createRecordSql = "CREATE TABLE IF NOT EXISTS charging_record("
-                            "idx integer primary key AUTOINCREMENT, "
-                            "reservationId text, "
-                            "transactionId text, "
-                            "startMethod text, "
-                            "userId text, "
-                            "dateTimeStart text, "
-                            "dateTimeStop text,"
-                            "socStart text, "
-                            "socStop text, "
-                            "chargeEnergy text, "
-                            "stopReason text"
-                            ");";
-
-    /*char *createCfgSql = "CREATE TABLE IF NOT EXISTS `config` ( "
-                         "`idx` INTEGER PRIMARY KEY AUTOINCREMENT, "
-                         "`IsAvailable` TEXT NOT NULL, "
-                         "`connector` INTEGER NOT NULL, "
-                         "`val` TEXT NOT NULL, unique(IsAvailable,connector) on conflict replace);";
-    */
-    //DS60-120 add
-    char *createCfgSql = "CREATE TABLE IF NOT EXISTS `config` ( "
-                         "`idx` INTEGER PRIMARY KEY AUTOINCREMENT, "
-                         "`item` TEXT NOT NULL, "
-                         "`connector` INTEGER NOT NULL, "
-                         "`val` TEXT NOT NULL, unique(item,connector) on conflict replace);";
-
-    char *createrecordSql = "CREATE TABLE IF NOT EXISTS `event_record` ( "
-                            "`idx` INTEGER PRIMARY KEY AUTOINCREMENT, "
-                            "`occurDatetime` TEXT NOT NULL, "
-                            "`statusCode` TEXT NOT NULL, unique(occurDatetime,statusCode) on conflict replace);";
-
-    char *createrebootSql = "CREATE TABLE IF NOT EXISTS `reboot_record` ( "
-                            "`idx` INTEGER PRIMARY KEY AUTOINCREMENT, "
-                            "`rebootDatetime` TEXT NOT NULL, unique(rebootDatetime) on conflict replace);";
-
-    if (sqlite3_open(DB_FILE, &localDb)) {
-        result = FAIL;
-        log_info( "Can't open database: %s", sqlite3_errmsg(localDb));
-        sqlite3_close(localDb);
-    } else {
-        //log_info( "Local charging record database open successfully.");
-
-        if (sqlite3_exec(localDb, createRecordSql, 0, 0, &errMsg) != SQLITE_OK) {
-            result = FAIL;
-            log_info( "Create local charging record table error message: %s", errMsg);
-        } else {
-            log_info( "Opened local charging record table successfully");
-        }
-
-        if (sqlite3_exec(localDb, createCfgSql, 0, 0, &errMsg) != SQLITE_OK) {
-            result = FAIL;
-            log_info( "Create local config table error message: %s", errMsg);
-        } else {
-            log_info( "Opened local config table successfully");
-        }
-
-        //DS60-120
-        if (sqlite3_exec(localDb, createrecordSql, 0, 0, &errMsg) != SQLITE_OK) {
-            result = FAIL;
-            log_info( "Create local record table error message: %s", errMsg);
-        } else {
-            log_info( "Opened local record table successfully");
-        }
-
-        if (sqlite3_exec(localDb, createrebootSql, 0, 0, &errMsg) != SQLITE_OK) {
-            result = FAIL;
-            log_info( "Create reboot record table error message: %s", errMsg);
-        } else {
-            log_info( "Opened reboot record table successfully");
-        }
-        //-----
-
-        sqlite3_close(localDb);
-    }
-
-    ShmDcCommonData = (DcCommonInfo*)GetShmDcCommonData();
-    return result;
-}
-
-int DB_Insert_Record(int gunIndex)
-{
-    int result = PASS;
-    char *errMsg = NULL;
-    char insertSql[1024];
-    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-    struct OCPP16Data *ShmOCPP16Data = (struct OCPP16Data *)GetShmOCPP16Data();
-
-    sprintf(insertSql, "insert into charging_record(reservationId, transactionId, startMethod, userId, dateTimeStart, dateTimeStop, socStart, socStop, chargeEnergy, stopReason) "
-            "values('%d', '%d', '%d', '%s', '%s', '%s', '%d', '%d', '%f', '%s');",
-            pDcChargingInfo->ReservationId, //DS60-120 add
-            ShmOCPP16Data->StartTransaction[gunIndex].ResponseTransactionId,
-            pDcChargingInfo->StartMethod,
-            pDcChargingInfo->StartUserId,
-            pDcChargingInfo->StartDateTime,
-            pDcChargingInfo->StopDateTime,
-            pDcChargingInfo->EvBatteryStartSoc,
-            pDcChargingInfo->EvBatterySoc,
-            pDcChargingInfo->PresentChargedEnergy,
-            ShmOCPP16Data->StopTransaction[gunIndex].StopReason);
-
-    //if (sqlite3_open("/Storage/ChargeLog/localCgargingRecord.db", &db)) {
-    if (sqlite3_open(DB_FILE, &localDb)) { //DS60-120 add
-        result = FAIL;
-        log_info( "Can't open database: %s", sqlite3_errmsg(localDb));
-        sqlite3_close(localDb);
-    } else {
-        //log_info( "Local charging record database open successfully.");
-        if (sqlite3_exec(localDb, insertSql, 0, 0, &errMsg) != SQLITE_OK) {
-            result = FAIL;
-            log_info( "Insert local charging record error message: %s", errMsg);
-        } else {
-            //log_info( "Insert local charging record successfully");
-        }
-
-        //DS60-120 add
-        sprintf(insertSql, "delete from charging_record where idx < (select idx from charging_record order by idx desc limit 1)-2000;");
-        if (sqlite3_exec(localDb, insertSql, 0, 0, &errMsg) != SQLITE_OK) {
-            result = FAIL;
-            log_info( "delete local charging error message: %s", errMsg);
-        } else {
-            //log_info( "delete local charging record successfully");
-        }
-
-        sqlite3_close(localDb);
-    }
-
-    return result;
-}
-
-int DB_Update_Operactive(uint8_t gunIndex, uint8_t IsAvailable)
-{
-    uint8_t result = false;
-    char *errMsg = NULL;
-    char sqlStr[1024];
-    srand(time(NULL));
-
-    if (sqlite3_open(DB_FILE, &localDb)) {
-        result = FAIL;
-        log_info( "Can't open database: %s", sqlite3_errmsg(localDb));
-        sqlite3_close(localDb);
-    } else {
-        //log_info( "Local charging record database open successfully (%d).", IsAvailable);
-
-        //sprintf(sqlStr, "insert or replace into config (IsAvailable, connector, val) values('IsAvailable', %d, %d);", gunIndex, IsAvailable);
-        sprintf(sqlStr,
-                "insert or replace into config (item, connector, val) values('IsAvailable', %d, %d);",
-                gunIndex,
-                IsAvailable); //DS60-120 add
-        //log_info("sqlStr= %s", sqlStr);
-        if (sqlite3_exec(localDb, sqlStr, 0, 0, &errMsg) != SQLITE_OK) {
-            result = FAIL;
-            log_info( "update config error message: %s", errMsg);
-        } else {
-            log_info("update connector-%d config item isOperactive to %d", gunIndex, IsAvailable);
-        }
-
-        sqlite3_close(localDb);
-    }
-
-    return result;
-}
-
-int DB_Get_Operactive(uint8_t gunIndex)
-{
-    uint8_t result = true;
-    char *errMsg = NULL;
-    char sqlStr[1024];
-    char **rs;
-    int  rows, cols;
-
-    //sprintf(sqlStr, "select * from config where IsAvailable='IsAvailable' and connector=%d;", gunIndex);
-    sprintf(sqlStr, "select * from config where item='IsAvailable' and connector=%d;", gunIndex); //DS60-120 add
-    //DEBUG_INFO("sqlStr= %s", sqlStr);
-
-    if (sqlite3_open(DB_FILE, &localDb)) {
-        result = FAIL;
-        log_info( "Can't open database: %s", sqlite3_errmsg(localDb));
-        sqlite3_close(localDb);
-    } else {
-        log_info( "Local config query database open successfully.");
-        sqlite3_get_table(localDb, sqlStr, &rs, &rows, &cols, &errMsg);
-        if (rows > 0) {
-            for (int idxRow = 1; idxRow <= rows; idxRow++) {
-                if (strcmp(rs[(idxRow * cols) + 3], "0") == 0) {
-                    result = false;
-                }
-                log_info("Query connector-%d isOperactive: %s", gunIndex, rs[(idxRow * cols) + 3]);
-            }
-        } else {
-            log_info("Query connector-%d fail, set default value to operactive.", gunIndex);
-        }
-
-        sqlite3_free_table(rs);
-        sqlite3_close(localDb);
-    }
-
-    return result;
-}
-
-int DB_Reboot_Record(void)
-{
-    int result = PASS;
-    char *errMsg = NULL;
-    char insertSql[256];
-
-    sprintf(insertSql, "insert into reboot_record(rebootDatetime) values(CURRENT_TIMESTAMP);");
-
-    if (sqlite3_open(DB_FILE, &localDb)) {
-        result = FAIL;
-        log_info( "Can't open database: %s", sqlite3_errmsg(localDb));
-        sqlite3_close(localDb);
-    } else {
-        //log_info( "Local charging record database open successfully.");
-        if (sqlite3_exec(localDb, insertSql, 0, 0, &errMsg) != SQLITE_OK) {
-            result = FAIL;
-            log_info( "Insert reboot record error message: %s", errMsg);
-        } else {
-            log_info( "Insert reboot record successfully");
-        }
-
-        sprintf(insertSql, "delete from reboot_record where idx < (select idx from charging_record order by idx desc limit 1)-2000;");
-        if (sqlite3_exec(localDb, insertSql, 0, 0, &errMsg) != SQLITE_OK) {
-            result = FAIL;
-            log_info( "delete reboot record error message: %s", errMsg);
-        } else {
-            log_info( "delete reboot record successfully");
-        }
-
-        sqlite3_close(localDb);
-    }
-
-    return result;
-}
-
-//------------------------------------------------------------------------------
-//for Module_EventLog
-//------------------------------------------------------------------------------
-int CreateEventRecord(void)
-{
-    int result = PASS;
-    char *errMsg = NULL;
-    char *createRecordSql = "CREATE TABLE IF NOT EXISTS event_record("
-                            "idx integer primary key AUTOINCREMENT, "
-                            "occurDatetime text NOT NULL, "
-                            "statusCode text NOT NULL"
-                            ");";
-
-    if (sqlite3_open(DB_FILE, &localDb)) {
-        result = FAIL;
-        log_error( "Can't open database: %s", sqlite3_errmsg(localDb));
-        sqlite3_close(localDb);
-    } else {
-        log_info( "Local event record database open successfully.");
-
-        if (sqlite3_exec(localDb, createRecordSql, 0, 0, &errMsg) != SQLITE_OK) {
-            result = FAIL;
-            log_error( "Create local event record table error message: %s", errMsg);
-        } else {
-            log_info( "Opened local event record table successfully");
-        }
-
-        sqlite3_close(localDb);
-    }
-
-    return result;
-}
-
-int InsertEventRecord(uint8_t *statusCode)
-{
-    int result = PASS;
-    char *errMsg = NULL;
-    char sqlStr[1024] = {0};
-
-    sprintf(sqlStr, "insert into event_record(occurDatetime, statusCode) values(CURRENT_TIMESTAMP, '%s');", statusCode);
-
-    if (sqlite3_open(DB_FILE, &localDb)) {
-        result = FAIL;
-        log_info( "Can't open database: %s", sqlite3_errmsg(localDb));
-        sqlite3_close(localDb);
-    } else {
-        //log_info( "Local event record database open successfully.");
-        if (sqlite3_exec(localDb, sqlStr, 0, 0, &errMsg) != SQLITE_OK) {
-            result = FAIL;
-            log_info( "Insert local event record error message: %s", errMsg);
-        } else {
-            //log_info( "Insert local event record successfully");
-        }
-
-        sprintf(sqlStr, "delete from event_record where idx < (select idx from event_record order by idx desc limit 1)-2000;");
-        if (sqlite3_exec(localDb, sqlStr, 0, 0, &errMsg) != SQLITE_OK) {
-            result = FAIL;
-            log_info( "delete local event_record error message: %s", errMsg);
-        } else {
-            //log_info( "delete local event record successfully");
-        }
-
-        sqlite3_close(localDb);
-    }
-
-    return result;
-}
-void CreditCardTimeSet(char *_time, RecordTransactionInfo* deductInfo)
-{
-    _time[0] = '2';
-    _time[1] = '0';
-    _time[2] = (char)deductInfo->pCreditCard.TransDate[0];
-    _time[3] = (char)deductInfo->pCreditCard.TransDate[1];
-    _time[4] = '-';
-    _time[5] = (char)deductInfo->pCreditCard.TransDate[2];
-    _time[6] = (char)deductInfo->pCreditCard.TransDate[3];
-    _time[7] = '-';
-    _time[8] = (char)deductInfo->pCreditCard.TransDate[4];
-    _time[9] = (char)deductInfo->pCreditCard.TransDate[5];
-    _time[10] = ' ';
-    _time[11] = (char)deductInfo->pCreditCard.TransTime[0];
-    _time[12] = (char)deductInfo->pCreditCard.TransTime[1];
-    _time[13] = ':';
-    _time[14] = (char)deductInfo->pCreditCard.TransTime[2];
-    _time[15] = (char)deductInfo->pCreditCard.TransTime[3];
-    _time[16] = ':';
-    _time[17] = (char)deductInfo->pCreditCard.TransTime[4];
-    _time[18] = (char)deductInfo->pCreditCard.TransTime[5];
-    _time[19] = '\0';
-}
-
-int DeductDB_Open(void)
-{
-	int result = PASS;
-	char* errMsg = NULL;
-	char* createDeductInfoSql="CREATE TABLE IF NOT EXISTS report_credit_deduct("
-					      	  "idx integer primary key AUTOINCREMENT, "
-							  "gun_index text, "
-                              "reportDate text, "
-                              "vemData text, "
-                              "txId text, "
-                              "creditNo text, "
-                              "amount text, "
-                              "storeId text, "
-                              "approvalNo text, "
-                              "RRN text, "
-                              "ROC text, "
-                              "isDonateInvoice text, "
-                              "isDeductResult text, "
-                              "isIntoCharge text, "
-                              "isUpload text, "
-                              "lineSn text, "
-                              "Energy text, "
-                              "RedeductTime "
-						  	  ");";
-
-	if(sqlite3_open(DEDUCT_FILE, &deductDb))
-	{
-		result = FAIL;
-		log_info("Can't open deduct database: %s", sqlite3_errmsg(deductDb));
-		sqlite3_close(deductDb);
-	}
-	else
-	{
-		//log_info("Deduct database open successfully.");
-		if (sqlite3_exec(deductDb, createDeductInfoSql, 0, 0, &errMsg) != SQLITE_OK)
-		{
-			result = FAIL;
-			log_info("Create deduct info table error message: %s", errMsg);
-		}
-		else
-		{
-			log_info("Opened deduct info table successfully");
-		}
-       
-		sqlite3_close(deductDb);
-	}
-
-	return result;
-}
-
-int InsertDeductInfo(int gunIndex, RecordTransactionInfo *deductInfo)
-{
-    int result = PASS;
-    char *errMsg = NULL;
-    char sqlStr[1024] = {0};
-    char approNo[13];
-    char carNo[21];
-    char vemData[65];
-    char storeId[18];
-    char RRN[12];
-    char ROC[12];
-    char lineSn[20];
-    char _time[20];
-
-    memset(approNo, '\0', sizeof(approNo));
-    memset(carNo, '\0', sizeof(carNo));
-    memset(vemData, '\0', sizeof(vemData));
-    memset(storeId, '\0', sizeof(storeId));
-    memset(RRN, '\0', sizeof(RRN));
-    memset(ROC, '\0', sizeof(ROC));
-    memset(lineSn, '\0', sizeof(lineSn));
-
-    strncpy(approNo, (char *)&deductInfo->pCreditCard.ApprovalNo,9);
-    strncpy(carNo, (char *)&deductInfo->pCreditCard.CardNo,20);
-    strncpy(vemData, (char *)&deductInfo->pCreditCard.VemData,64);
-    strncpy(storeId, (char *)&deductInfo->pCreditCard.StoreId,18 );
-    strncpy(RRN,(char *)&deductInfo->pCreditCard.RRN,12);
-    strncpy(ROC,(char *)&deductInfo->pCreditCard.ROC,12);
-    CreditCardTimeSet(&_time[0], deductInfo);
-    //sprintf(reportDate, "%s%s", deductInfo->pCreditCard.TransDate, deductInfo->pCreditCard.TransTime);
-
-	sprintf(sqlStr, "insert into report_credit_deduct(gun_index, reportDate, vemData, txId, creditNo, amount, storeId, approvalNo, RRN, ROC, isDonateInvoice, isDeductResult, isIntoCharge, isUpload, lineSn, Energy, RedeductTime) "
-				    "values('%d', '%s', '%s', '%d', '%s', '%.1f', '%s', '%s', '%s', '%s', '%d', '%d', '%d' , '%d', '%d', '%.4f', '%d');",
-                    gunIndex,
-                    _time,
-				    vemData,
-                    deductInfo->TransactionId,
-                    carNo,
-                    deductInfo->Amount,
-					storeId,
-                    approNo,
-				    RRN,
-				    ROC,
-                    (int)deductInfo->IsDonateInvoice,
-                    (int)deductInfo->DeductResult,
-                    (int)deductInfo->isIntoCharge,
-                    (int)deductInfo->IsUpload,
-                    deductInfo->LineStatus,
-                    deductInfo->Energy,
-                    deductInfo->RedeductTime);
-
-    //log_info("%s",sqlStr);
-
-    if (sqlite3_open(DEDUCT_FILE, &deductDb))
-    {
-        result = FAIL;
-        log_info( "Can't open deduct database: %s", sqlite3_errmsg(deductDb));
-        sqlite3_close(deductDb);
-    }
-    else
-    {
-        //log_info( "Local event record database open successfully.");
-        if (sqlite3_exec(deductDb, sqlStr, 0, 0, &errMsg) != SQLITE_OK)
-        {
-            result = FAIL;
-            log_info( "Insert deduct record error message: %s", errMsg);
-        }
-        else
-        {
-            //log_info( "Insert local event record successfully");
-        }
-
-
-        sprintf(sqlStr, "delete from report_credit_deduct where idx < (select idx from report_credit_deduct order by idx desc limit 1)-10000;");
-        if (sqlite3_exec(deductDb, sqlStr, 0, 0, &errMsg) != SQLITE_OK)
-        {
-            result = FAIL;
-            log_info("delete deduct record error message: %s", errMsg);
-        }
-        else
-        {
-            //log_info("delete local charging record successfully");
-        }
-
-        sqlite3_close(deductDb);
-    }
-
-    return result;
-}
-
-int UpdateDeductInfoStatus(int gunIndex, RecordTransactionInfo *deductInfo)
-{
-
-    int result = PASS;
-    char *errMsg = NULL;
-    char sqlStr[1024] = {0};
-    char ApprovalNo[10] = {0};
-    memset(ApprovalNo, '\0', 10);
-    strncpy(ApprovalNo, (char*)&deductInfo->pCreditCard.ApprovalNo,9);
-
-    sprintf(sqlStr, "update report_credit_deduct set isUpload = %d , isIntoCharge = %d, amount = %.1f, txId = %d, isDeductResult = %d, Energy = %.4f, lineSn = %d, RedeductTime = %d where approvalNo = '%s'; ",
-                    (int)deductInfo->IsUpload,
-                    (int)deductInfo->isIntoCharge,
-                    deductInfo->Amount,
-                    deductInfo->TransactionId,
-                    (int)deductInfo->DeductResult,
-                    deductInfo->Energy,
-                    deductInfo->LineStatus,
-                    deductInfo->RedeductTime,
-                    ApprovalNo);
-
-    //log_info("%s",sqlStr);
-
-    if (sqlite3_open(DEDUCT_FILE, &deductDb))
-    {
-        result = FAIL;
-        log_info( "Can't open deduct database: %s", sqlite3_errmsg(deductDb));
-        sqlite3_close(deductDb);
-    }
-    else
-    {
-        //log_info( "Local event record database open successfully.");
-        if (sqlite3_exec(deductDb, sqlStr, 0, 0, &errMsg) != SQLITE_OK)
-        {
-            result = FAIL;
-            log_info( "update deduct record error message: %s!", errMsg);
-        }
-        else
-        {
-            //log_info( "update deduct record successfully");
-        }
-
-        sqlite3_close(deductDb);
-    }
-
-    return result;
-}
-
-int UpdateRedeuctBill(int Txid,float amount)
-{
-    int result = PASS;
-    char* errMsg = NULL;
-    char sqlStr[1024] = { 0 };
-
-    sprintf(sqlStr, "update report_credit_deduct set amount = %.1f where txId = '%d'; ",
-            amount,
-            Txid);
-
-    //log_info("%s",sqlStr);
-
-    if (sqlite3_open(DEDUCT_FILE, &deductDb))
-    {
-        result = FAIL;
-        log_info("Can't open deduct database: %s", sqlite3_errmsg(deductDb));
-        sqlite3_close(deductDb);
-    } else
-    {
-        //log_info( "Local event record database open successfully.");
-        if (sqlite3_exec(deductDb, sqlStr, 0, 0, &errMsg) != SQLITE_OK)
-        {
-            result = FAIL;
-            log_info("update deduct record error message: %s!", errMsg);
-        } else
-        {
-            //log_info( "update deduct record successfully");
-        }
-
-        sqlite3_close(deductDb);
-    }
-
-    return result;
-}
-
-int DB_GetDeductInfo(int deductResult, int uploadState, int *gunIndex, RecordTransactionInfo *deductInfo)
-{
-    int result = PASS;
-    char *errMsg = NULL;
-    char sqlStr[1024];
-    char **rs;
-    int rows, cols;
-
-    if(deductResult >= 0 && uploadState >= 0)
-    {
-        sprintf(sqlStr, "select * from report_credit_deduct where isDeductResult = %d and isUpload = %d;", deductResult > 0 ? 1 : 0, uploadState > 0 ? 1 : 0);
-    }
-    else if(deductResult >= 0 && uploadState < 0)
-    {
-        sprintf(sqlStr, "select * from report_credit_deduct where isDeductResult = 0 OR isDeductResult = 3;");
-    }
-    else if(deductResult < 0 && uploadState >= 0)
-    {
-        sprintf(sqlStr, "select * from report_credit_deduct where isUpload = %d;", uploadState > 0 ? 1 : 0);
-    }
-    else
-    {
-        sprintf(sqlStr, "select * from report_credit_deduct;");
-    }
-
-    if (sqlite3_open(DEDUCT_FILE, &deductDb))
-    {
-        result = FAIL;
-        log_info("Can't open deduct database: %s", sqlite3_errmsg(deductDb));
-        sqlite3_close(deductDb);
-    }
-    else
-    {
-        sqlite3_get_table(deductDb, sqlStr, &rs, &rows, &cols, &errMsg);
-
-        if (rows > 0)
-        {
-            for (int idxRow = 1; idxRow <= rows; idxRow++)
-            {
-                *gunIndex = atoi(rs[(idxRow * cols) + 1]);
-                deductInfo->TransactionId = atoi(rs[(idxRow * cols) + 2]);
-                deductInfo->DeductResult = atoi(rs[(idxRow * cols) + 3]);
-                deductInfo->IsDonateInvoice = atoi(rs[(idxRow * cols) + 4]);
-                strcpy((char *)&deductInfo->pCreditCard.ApprovalNo, rs[(idxRow * cols) + 5]);
-                strcpy((char *)&deductInfo->pCreditCard.CardNo, rs[(idxRow * cols) + 6]);
-                strcpy((char *)&deductInfo->pCreditCard.VemData, rs[(idxRow * cols) + 7]);
-                deductInfo->Amount = atoi(rs[(idxRow * cols) + 8]);
-                deductInfo->IsUpload = atoi(rs[(idxRow * cols) + 9]);
-                break;
-            }
-        }
-        else
-        {
-            result = FAIL;
-        }
-        sqlite3_free_table(rs);
-        sqlite3_close(deductDb);
-    }
-
-    return result;
-}
-
-int DB_GetReDeductInfo(int *gunIndex, RecordTransactionInfo *deductInfo)
-{
-    int result = PASS;
-
-    if(DB_GetDeductInfo(0, -1, gunIndex, deductInfo) == PASS)
-    {
-        //log_info("GetReDeductInfo OK");
-    }
-    else
-    {
-        result = FAIL;
-        //log_info("GetReDeductInfo NG");
-    }
-
-    return result;
-}
-
-int DB_GetReUploadDeduct(int *gunIndex, RecordTransactionInfo *deductInfo)
-{
-    int result = PASS;
-
-    if(DB_GetDeductInfo(-1, 0, gunIndex, deductInfo) == PASS)
-    {
-        //log_info("GetReUploadDeduct OK");
-    }
-    else
-    {
-        result = FAIL;
-        //log_info("GetReUploadDeduct NG");
-    }
-
-    return result;
-}
-void GetDeductTime(char* _time,RecordTransactionInfo* deductInfo)
-{
-    deductInfo->pCreditCard.TransDate[0] = (unsigned char)_time[2];
-    deductInfo->pCreditCard.TransDate[1] = (unsigned char)_time[3];
-    deductInfo->pCreditCard.TransDate[2] = (unsigned char)_time[5];
-    deductInfo->pCreditCard.TransDate[3] = (unsigned char)_time[6];
-    deductInfo->pCreditCard.TransDate[4] = (unsigned char)_time[8];
-    deductInfo->pCreditCard.TransDate[5] = (unsigned char)_time[9];
-
-    deductInfo->pCreditCard.TransTime[0] = (unsigned char)_time[11];
-    deductInfo->pCreditCard.TransTime[1] = (unsigned char)_time[12];
-    deductInfo->pCreditCard.TransTime[2] = (unsigned char)_time[14];
-    deductInfo->pCreditCard.TransTime[3] = (unsigned char)_time[15];
-    deductInfo->pCreditCard.TransTime[4] = (unsigned char)_time[17];
-    deductInfo->pCreditCard.TransTime[5] = (unsigned char)_time[18];
-
-}
-// return quantity of DeductInfo
-int DB_GetMultiDeductInfo(int deductResult, int uploadState, int *gunIndex, RecordTransactionInfo *deductInfo)
-{
-    char *errMsg = NULL;
-    char sqlStr[1024];
-    char **rs;
-    int rows = 0, cols = 0;
-
-    if(deductResult >= 0 && uploadState >= 0)
-    {
-        sprintf(sqlStr, "select * from report_credit_deduct where isDeductResult = %d and isUpload = %d;", deductResult > 0 ? 1 : 0, uploadState > 0 ? 1 : 0);
-    }
-    else if(deductResult >= 0 && uploadState < 0)
-    {
-        sprintf(sqlStr, "select * from report_credit_deduct where isDeductResult IN (0,3) AND RedeductTime < 10;");
-    }
-    else if(deductResult < 0 && uploadState >= 0)
-    {
-        sprintf(sqlStr, "select * from report_credit_deduct where isUpload = %d;", uploadState > 0 ? 1 : 0);
-    }
-    else
-    {
-        sprintf(sqlStr, "select * from report_credit_deduct;");
-    }
-
-    if (sqlite3_open(DEDUCT_FILE, &deductDb))
-    {
-        log_info("Can't open deduct database: %s", sqlite3_errmsg(deductDb));
-        sqlite3_close(deductDb);
-    }
-    else
-    {
-        sqlite3_get_table(deductDb, sqlStr, &rs, &rows, &cols, &errMsg);
-
-        if (rows > 0)
-        {
-            for (int idxRow = 1; idxRow <= rows; idxRow++)
-            {
-                //gunIndex[idxRow - 1] = atoi(rs[(idxRow * cols) + 1]);
-                deductInfo[idxRow - 1].ConnectorID = atoi(rs[(idxRow * cols) + 1]);
-               // GetDeductTime(rs[(idxRow * cols) + 1], deductInfo);
-                memcpy((char*)&deductInfo[idxRow - 1].pCreditCard.VemData, rs[(idxRow * cols) + 3],64);
-                deductInfo[idxRow - 1].TransactionId = atoi(rs[(idxRow * cols) + 4]);
-                memcpy((char*)&deductInfo[idxRow - 1].pCreditCard.CardNo, rs[(idxRow * cols) + 5],20);
-                deductInfo[idxRow - 1].Amount = atoi(rs[(idxRow * cols) + 6]);
-                memcpy((char*)&deductInfo[idxRow - 1].pCreditCard.StoreId, rs[(idxRow * cols) + 7],18);
-                memcpy((char*)&deductInfo[idxRow - 1].pCreditCard.ApprovalNo, rs[(idxRow * cols) + 8],9);
-                memcpy((char*)&deductInfo[idxRow - 1].pCreditCard.RRN, rs[(idxRow * cols) + 9],12);
-                memcpy((char*)&deductInfo[idxRow - 1].pCreditCard.ROC, rs[(idxRow * cols) + 10],12);
-                deductInfo[idxRow - 1].IsDonateInvoice = atoi(rs[(idxRow * cols) + 11]);
-                deductInfo[idxRow - 1].DeductResult = atoi(rs[(idxRow * cols) + 12]);
-                deductInfo[idxRow - 1].isIntoCharge = atoi(rs[(idxRow * cols) + 13]);
-                deductInfo[idxRow - 1].IsUpload = atoi(rs[(idxRow * cols) + 14]);
-                deductInfo[idxRow - 1].LineStatus = atoi(rs[(idxRow * cols) + 15]);
-                deductInfo[idxRow - 1].Energy = atof(rs[(idxRow * cols) + 16]);
-                deductInfo[idxRow - 1].RedeductTime = atoi(rs[(idxRow * cols) + 17]);
-                if(idxRow >= 128)
-                {
-                	rows = 128;
-                	break;
-                }
-            }
-        }
-
-        sqlite3_free_table(rs);
-        sqlite3_close(deductDb);
-    }
-
-    return rows;
-}
-
-int DB_GetMultiReDeductInfo(int *gunIndex, RecordTransactionInfo *deductInfo)
-{
-    int quantity = 0;
-
-    quantity = DB_GetMultiDeductInfo(0, -1, gunIndex, deductInfo);
-
-    return quantity;
-}
-
-int DB_GetMultiReUploadDeduct(int *gunIndex, RecordTransactionInfo *deductInfo)
-{
-	int quantity = 0;
-
-	quantity = DB_GetMultiDeductInfo(-1, 0, gunIndex, deductInfo);
-
-    return quantity;
-}
-
-void ReDeductTest()
-{
-	int quantity = 0;
-	int gunList[128];
-	RecordTransactionInfo deductInfo[128];
-
-	quantity = DB_GetMultiReDeductInfo(gunList, deductInfo);
-
-	if(quantity > 0)
-	{
-		for(int i = 0; i < quantity; i++)
-		{
-			printf("Gun %d Rededuct CardNo: %s", gunList[i], deductInfo[i].pCreditCard.VemData);
-		}
-	}
-}
-
-int PowerDB_Open(void)
-{
-    int result = PASS;
-    char* errMsg = NULL;
-    char* createPowerConsumption = "CREATE TABLE IF NOT EXISTS power_consumption( "
-        "idx INTEGER PRIMARY KEY AUTOINCREMENT, "
-        "connector TEXT, "
-        "val TEXT);";
-
-    if (sqlite3_open(POWER_FILE, &powerDb))
-    {
-        result = FAIL;
-        log_info("Can't open deduct database: %s", sqlite3_errmsg(powerDb));
-        sqlite3_close(powerDb);
-    } else
-    {
-        if (sqlite3_exec(powerDb, createPowerConsumption, 0, 0, &errMsg) != SQLITE_OK) {
-            result = FAIL;
-            log_info("Create power consumption record table error message: %s", errMsg);
-        } else {
-            log_info("Opened power consumption record table successfully");
-        }
-
-        sqlite3_close(powerDb);
-    }
-
-    return result;
-}
-
-int DB_Insert_PowerConsumption(uint8_t gunIndex, float energy)
-{
-    uint8_t result = false;
-    char* errMsg = NULL;
-    char sqlStr[1024];
-    srand(time(NULL));
-
-    if (sqlite3_open(POWER_FILE, &powerDb)) {
-        result = FAIL;
-        log_info("Can't open database: %s", sqlite3_errmsg(powerDb));
-        sqlite3_close(powerDb);
-    } else {
-        //log_info("Local charging record database open successfully (%f).", energy);
-        sprintf(sqlStr, "insert into power_consumption (connector, val) values (%d, %f);",
-            gunIndex,
-            energy); //DS60-120 add
-        //log_info("sqlStr= %s", sqlStr);
-        if (sqlite3_exec(powerDb, sqlStr, 0, 0, &errMsg) != SQLITE_OK) {
-            result = FAIL;
-            log_info("Insert power consumption error message: %s", errMsg);
-        } else {
-            log_info("Insert connector-%d config item PowerComsumption to %f", gunIndex, energy);
-        }
-
-        sqlite3_close(powerDb);
-    }
-
-    return result;
-}
-
-int DB_Update_PowerConsumption(uint8_t gunIndex, float energy)
-{
-    uint8_t result = false;
-    char* errMsg = NULL;
-    char sqlStr[1024];
-    srand(time(NULL));
-
-    if (sqlite3_open(POWER_FILE, &powerDb)) {
-        result = FAIL;
-        log_info("Can't open database: %s", sqlite3_errmsg(powerDb));
-        sqlite3_close(powerDb);
-    } else {
-        //log_info("Local charging record database open successfully.");
-        sprintf(sqlStr, "update power_consumption set val = %f where connector = %d; ",
-            energy,
-            gunIndex); //DS60-120 add
-//log_info("sqlStr= %s", sqlStr);
-        if (sqlite3_exec(powerDb, sqlStr, 0, 0, &errMsg) != SQLITE_OK) {
-            result = FAIL;
-            log_info("update config error message: %s", errMsg);
-        } else {
-            //log_info("update connector-%d config item PowerComsumption to %f", gunIndex, energy);
-        }
-
-        sqlite3_close(powerDb);
-    }
-
-    return result;
-}
-
-int DB_Get_PowerConsumption(uint8_t gunIndex)
-{
-    uint8_t result = true;
-    char* errMsg = NULL;
-    char sqlStr[1024];
-    char** rs;
-    int  rows, cols;
-
-    //sprintf(sqlStr, "select * from config where IsAvailable='IsAvailable' and connector=%d;", gunIndex);
-    sprintf(sqlStr, "select * from power_consumption where connector=%d;", gunIndex); //DS60-120 add
-    //DEBUG_INFO("sqlStr= %s", sqlStr);
-
-    if (sqlite3_open(POWER_FILE, &powerDb)) {
-        result = FAIL;
-        log_info("Can't open database: %s", sqlite3_errmsg(powerDb));
-        sqlite3_close(powerDb);
-    } else {
-        //log_info("Local config query database open successfully.");
-        sqlite3_get_table(powerDb, sqlStr, &rs, &rows, &cols, &errMsg);
-        if (rows > 0) {
-            for (int idxRow = 1; idxRow <= rows; idxRow++) {
-                ShmDcCommonData->pGunInfo[gunIndex].PowerConsumption = atof(rs[(idxRow * cols) + 2]);
-                log_info("Query connector-%d PowerConsumption: %s", gunIndex, rs[(idxRow * cols) + 2]);
-
-            }
-        } else {
-            log_info("Query connector-%d fail, set default value to operactive.", gunIndex);
-            result = false;
-        }
-
-        sqlite3_free_table(rs);
-        sqlite3_close(powerDb);
-    }
-
-    return result;
-}
-
-int ParkingDB_Open(void)
-{
-	int result = PASS;
-	char* errMsg = NULL;
-	char* createDeductInfoSql="CREATE TABLE IF NOT EXISTS report_Parking_deduct("
-					      	  "idx integer primary key AUTOINCREMENT, "
-							  "gun_index text, "
-                              "vemData text, "
-                              "OccupancySN text, "
-                              "duration text, "
-                              "creditNo text, "
-                              "amount text, "
-                              "storeId text, "
-                              "approvalNo text, "
-                              "RRN text, "
-                              "ROC text, "
-                              "isDonateInvoice text, "
-                              "isDeductResult text, "
-                              "isUpload text, "
-                              "lineSn text, "
-                              "StartTime text, "
-                              "RedeductTime "
-						  	  ");";
-	if(sqlite3_open(PARKINGDEDUCT_FILE, &parkingDb))
-	{
-		result = FAIL;
-		log_info("Can't open Parking deduct database: %s", sqlite3_errmsg(parkingDb));
-		sqlite3_close(parkingDb);
-	}
-	else
-	{
-		//log_info("Deduct database open successfully.");
-		if (sqlite3_exec(parkingDb, createDeductInfoSql, 0, 0, &errMsg) != SQLITE_OK)
-		{
-			result = FAIL;
-			log_info("Create Parking deduct info table error message: %s", errMsg);
-		}
-		else
-		{
-			log_info("Opened Parking deduct info table successfully");
-		}
-       
-		sqlite3_close(parkingDb);
-	}
-
-	return result;
-}
-
-int InsertParkingDeductInfo(int gunIndex, RecordTransactionInfo *deductInfo)
-{
-    int result = PASS;
-    char *errMsg = NULL;
-    char sqlStr[1024] = {0};
-    char approNo[13];
-    char carNo[21];
-    char OccupancySN[37];
-    char storeId[18];
-    char RRN[12];
-    char ROC[12];
-    char lineSn[20];
-    char _time[33];
-    char vemData[65];
-
-    memset(approNo, '\0', sizeof(approNo));
-    memset(carNo, '\0', sizeof(carNo));
-    memset(OccupancySN, '\0', sizeof(OccupancySN));
-    memset(storeId, '\0', sizeof(storeId));
-    memset(RRN, '\0', sizeof(RRN));
-    memset(ROC, '\0', sizeof(ROC));
-    memset(lineSn, '\0', sizeof(lineSn));
-    memset(_time,'\0',sizeof(_time));
-    memset(vemData,'\0',sizeof(vemData));
-
-    strncpy(approNo, (char *)&deductInfo->pCreditCard.ApprovalNo,9);
-    strncpy(carNo, (char *)&deductInfo->pCreditCard.CardNo,20);
-    strncpy(OccupancySN, (char *)&deductInfo->OccupancySN,36);
-    strncpy(storeId, (char *)&deductInfo->pCreditCard.StoreId,18 );
-    strncpy(RRN,(char *)&deductInfo->pCreditCard.RRN,12);
-    strncpy(ROC,(char *)&deductInfo->pCreditCard.ROC,12);
-    strncpy(_time,(char *)&deductInfo->ParkingStartTime,33);
-    strncpy(vemData,(char *)&deductInfo->pCreditCard.VemData,64);
-
-    //sprintf(reportDate, "%s%s", deductInfo->pCreditCard.TransDate, deductInfo->pCreditCard.TransTime);
-
-	sprintf(sqlStr, "insert into report_Parking_deduct(gun_index, vemData, OccupancySN, duration, creditNo, amount, storeId, approvalNo, RRN, ROC, isDonateInvoice, isDeductResult, isUpload, lineSn, StartTime, RedeductTime) "
-				    "values('%d', '%s', '%s', '%d', '%s', '%.1f', '%s', '%s', '%s', '%s', '%d', '%d', '%d', '%d', '%s', '%d');",
-                    gunIndex,
-                    vemData,
-				    OccupancySN,
-                    deductInfo->ParkingDuration,
-                    carNo,
-                    deductInfo->Amount,
-					storeId,
-                    approNo,
-				    RRN,
-				    ROC,
-                    (int)deductInfo->IsDonateInvoice,
-                    (int)deductInfo->DeductResult,
-                    (int)deductInfo->IsUpload,
-                    deductInfo->LineStatus,
-                    _time,
-                    deductInfo->RedeductTime);
-
-    //log_info("%s",sqlStr);
-
-    if (sqlite3_open(PARKINGDEDUCT_FILE, &parkingDb))
-    {
-        result = FAIL;
-        log_info( "Can't open deduct database: %s", sqlite3_errmsg(parkingDb));
-        sqlite3_close(parkingDb);
-    }
-    else
-    {
-        //log_info( "Local event record database open successfully.");
-        if (sqlite3_exec(parkingDb, sqlStr, 0, 0, &errMsg) != SQLITE_OK)
-        {
-            result = FAIL;
-            log_info( "Insert deduct record error message: %s", errMsg);
-        }
-        else
-        {
-            //log_info( "Insert local event record successfully");
-        }
-
-
-        sprintf(sqlStr, "delete from report_Parking_deduct where idx < (select idx from report_Parking_deduct order by idx desc limit 1)-10000;");
-        if (sqlite3_exec(parkingDb, sqlStr, 0, 0, &errMsg) != SQLITE_OK)
-        {
-            result = FAIL;
-            log_info("delete deduct record error message: %s", errMsg);
-        }
-        else
-        {
-            //log_info("delete local charging record successfully");
-        }
-
-        sqlite3_close(parkingDb);
-    }
-
-    return result;
-}
-
-// return quantity of DeductInfo
-int DB_GetParkingDeductUpload(int *gunIndex, RecordTransactionInfo *deductInfo)
-{
-    char *errMsg = NULL;
-    char sqlStr[1024];
-    char **rs;
-    int rows = 0, cols = 0;
-
-    sprintf(sqlStr, "select * from report_Parking_deduct where isUpload = 0;");
-
-    if (sqlite3_open(PARKINGDEDUCT_FILE, &parkingDb))
-    {
-        log_info("Can't open parking database: %s", sqlite3_errmsg(parkingDb));
-        sqlite3_close(parkingDb);
-    }
-    else
-    {
-        sqlite3_get_table(parkingDb, sqlStr, &rs, &rows, &cols, &errMsg);
-
-        if (rows > 0)
-        {
-            for (int idxRow = 1; idxRow <= rows; idxRow++)
-            {
-                //gunIndex[idxRow - 1] = atoi(rs[(idxRow * cols) + 1]);
-                deductInfo[idxRow - 1].ConnectorID = atoi(rs[(idxRow * cols) + 1]);
-                // GetDeductTime(rs[(idxRow * cols) + 1], deductInfo);
-                memcpy((char*)&deductInfo[idxRow - 1].pCreditCard.VemData, rs[(idxRow * cols) + 2],64);
-                memcpy((char*)&deductInfo[idxRow - 1].OccupancySN, rs[(idxRow * cols) + 3],36);
-                deductInfo[idxRow - 1].ParkingDuration = atoi(rs[(idxRow * cols) + 4]);
-                memcpy((char*)&deductInfo[idxRow - 1].pCreditCard.CardNo, rs[(idxRow * cols) + 5],20);
-                deductInfo[idxRow - 1].Amount = atoi(rs[(idxRow * cols) + 6]);
-                memcpy((char*)&deductInfo[idxRow - 1].pCreditCard.StoreId, rs[(idxRow * cols) + 7],18);
-                memcpy((char*)&deductInfo[idxRow - 1].pCreditCard.ApprovalNo, rs[(idxRow * cols) + 8],9);
-                memcpy((char*)&deductInfo[idxRow - 1].pCreditCard.RRN, rs[(idxRow * cols) + 9],12);
-                memcpy((char*)&deductInfo[idxRow - 1].pCreditCard.ROC, rs[(idxRow * cols) + 10],12);
-                deductInfo[idxRow - 1].IsDonateInvoice = atoi(rs[(idxRow * cols) + 11]);
-                deductInfo[idxRow - 1].DeductResult = atoi(rs[(idxRow * cols) + 12]);
-                deductInfo[idxRow - 1].IsUpload = atoi(rs[(idxRow * cols) + 13]);
-                deductInfo[idxRow - 1].LineStatus = atoi(rs[(idxRow * cols) + 14]);
-                memcpy((char*)&deductInfo[idxRow - 1].ParkingStartTime, rs[(idxRow * cols) + 15],32);
-                deductInfo[idxRow - 1].RedeductTime = atoi(rs[(idxRow * cols) + 16]);
-                if(idxRow >= 128)
-                {
-                	rows = 128;
-                	break;
-                }
-            }
-        }
-
-        sqlite3_free_table(rs);
-        sqlite3_close(parkingDb);
-    }
-
-    return rows;
-}
-
-int DB_GetParkingDeductResult(int *gunIndex, RecordTransactionInfo *deductInfo)
-{
-    char *errMsg = NULL;
-    char sqlStr[1024];
-    char **rs;
-    int rows = 0, cols = 0;
-
-    sprintf(sqlStr, "select * from report_Parking_deduct where isDeductResult = 0 OR isDeductResult = 3;");
-
-    if (sqlite3_open(PARKINGDEDUCT_FILE, &parkingDb))
-    {
-        log_info("Can't open parking database: %s", sqlite3_errmsg(parkingDb));
-        sqlite3_close(parkingDb);
-    }
-    else
-    {
-        sqlite3_get_table(parkingDb, sqlStr, &rs, &rows, &cols, &errMsg);
-
-        if (rows > 0)
-        {
-            for (int idxRow = 1; idxRow <= rows; idxRow++)
-            {
-                //gunIndex[idxRow - 1] = atoi(rs[(idxRow * cols) + 1]);
-                deductInfo[idxRow - 1].ConnectorID = atoi(rs[(idxRow * cols) + 1]);
-                // GetDeductTime(rs[(idxRow * cols) + 1], deductInfo);
-                memcpy((char*)&deductInfo[idxRow - 1].pCreditCard.VemData, rs[(idxRow * cols) + 2],64);
-                memcpy((char*)&deductInfo[idxRow - 1].OccupancySN, rs[(idxRow * cols) + 3],36);
-                deductInfo[idxRow - 1].ParkingDuration = atoi(rs[(idxRow * cols) + 4]);
-                memcpy((char*)&deductInfo[idxRow - 1].pCreditCard.CardNo, rs[(idxRow * cols) + 5],20);
-                deductInfo[idxRow - 1].Amount = atoi(rs[(idxRow * cols) + 6]);
-                memcpy((char*)&deductInfo[idxRow - 1].pCreditCard.StoreId, rs[(idxRow * cols) + 7],18);
-                memcpy((char*)&deductInfo[idxRow - 1].pCreditCard.ApprovalNo, rs[(idxRow * cols) + 8],9);
-                memcpy((char*)&deductInfo[idxRow - 1].pCreditCard.RRN, rs[(idxRow * cols) + 9],12);
-                memcpy((char*)&deductInfo[idxRow - 1].pCreditCard.ROC, rs[(idxRow * cols) + 10],12);
-                deductInfo[idxRow - 1].IsDonateInvoice = atoi(rs[(idxRow * cols) + 11]);
-                deductInfo[idxRow - 1].DeductResult = atoi(rs[(idxRow * cols) + 12]);
-                deductInfo[idxRow - 1].IsUpload = atoi(rs[(idxRow * cols) + 13]);
-                deductInfo[idxRow - 1].LineStatus = atoi(rs[(idxRow * cols) + 14]);
-                memcpy((char*)&deductInfo[idxRow - 1].ParkingStartTime, rs[(idxRow * cols) + 15],10);
-                deductInfo[idxRow - 1].RedeductTime = atoi(rs[(idxRow * cols) + 16]);
-                if(idxRow >= 128)
-                {
-                	rows = 128;
-                	break;
-                }
-            }
-        }
-
-        sqlite3_free_table(rs);
-        sqlite3_close(parkingDb);
-    }
-
-    return rows;
-}
-
-
-int UpdateParkingUpload(char* OccupancySN,int is_upload)
-{
-    int result = PASS;
-    char* errMsg = NULL;
-    char sqlStr[1024] = { 0 };
-
-    if (strcmp((char*)OccupancySN,"") == EQUAL) {
-        log_info("OccupancySN is NULL");
-        return;
-    }
-    char SN[37];
-    memset(SN,'\0',sizeof(SN));
-    memcpy((char*)SN,OccupancySN,36);
-    
-    sprintf(sqlStr, "update report_Parking_deduct set IsUpload = %d where OccupancySN = '%s'; ",
-            is_upload,
-            SN);
-
-    //log_info("%s",sqlStr);
-
-    if (sqlite3_open(PARKINGDEDUCT_FILE, &parkingDb))
-    {
-        result = FAIL;
-        log_info("Can't open parking database: %s", sqlite3_errmsg(parkingDb));
-        sqlite3_close(parkingDb);
-    } else
-    {
-        //log_info( "Local event record database open successfully.");
-        if (sqlite3_exec(parkingDb, sqlStr, 0, 0, &errMsg) != SQLITE_OK)
-        {
-            result = FAIL;
-            log_info("update parkingDB record error message: %s!", errMsg);
-        } else
-        {
-            //log_info( "update deduct record successfully");
-        }
-
-        sqlite3_close(parkingDb);
-    }
-
-    return result;
-}
-
-int UpdateParkingDeductInfo(int gunIndex, RecordTransactionInfo *deductInfo)
-{
-
-    int result = PASS;
-    char *errMsg = NULL;
-    char sqlStr[1024] = {0};
-    char OccupancySN[37] = {0};
-    memset(OccupancySN, '\0', 37);
-    strncpy(OccupancySN, (char*)&deductInfo->OccupancySN,36);
-    if (strcmp((char*)deductInfo->OccupancySN,"") == EQUAL) {
-        log_info("OccupancySN is NULL");
-        return;
-    }
-
-    sprintf(sqlStr, "update report_Parking_deduct set isUpload = %d ,amount = %.1f, isDeductResult = %d, RedeductTime = %d where OccupancySN = '%s'; ",
-                    (int)deductInfo->IsUpload,
-                    deductInfo->Amount,
-                    (int)deductInfo->DeductResult,
-                    deductInfo->RedeductTime,
-                    deductInfo->OccupancySN);
-
-    //  log_info("%s",sqlStr);
-
-    if (sqlite3_open(PARKINGDEDUCT_FILE, &parkingDb))
-    {
-        result = FAIL;
-        log_info( "Can't open deduct database: %s", sqlite3_errmsg(parkingDb));
-        sqlite3_close(parkingDb);
-    }
-    else
-    {
-        //log_info( "Local event record database open successfully.");
-        if (sqlite3_exec(parkingDb, sqlStr, 0, 0, &errMsg) != SQLITE_OK)
-        {
-            result = FAIL;
-            log_info( "update deduct record error message: %s!", errMsg);
-        }
-        else
-        {
-            //log_info( "update deduct record successfully");
-        }
-
-        sqlite3_close(parkingDb);
-    }
-
-    return result;
+#include <stdio.h>      /*標準輸入輸出定義*/
+#include <stdlib.h>     /*標準函數庫定義*/
+#include <string.h>
+#include <stdint.h>
+#include <time.h>
+
+#include "../Config.h"
+#include "../Log/log.h"
+#include "../Define/define.h"
+#include "../ShareMemory/shmMem.h"
+
+//------------------------------------------------------------------------------
+#define DB_FILE                                 "/Storage/ChargeLog/localCgargingRecord.db"
+#define DEDUCT_FILE                 			"/Storage/ChargeLog/CreditCardRecord.db"
+#define PARKINGDEDUCT_FILE                 		"/Storage/ChargeLog/ParkingCreditCardRecord.db"
+#define POWER_FILE                 			    "/Storage/ChargeLog/PowerConsumption.db"
+//------------------------------------------------------------------------------
+static sqlite3 *localDb;
+static sqlite3 *deductDb;
+static sqlite3 *parkingDb;
+static sqlite3* powerDb;
+static DcCommonInfo* ShmDcCommonData = NULL;
+//------------------------------------------------------------------------------
+//===============================================
+// SQLite3 related routine
+//===============================================
+int DB_Open(void)
+{
+    int result = PASS;
+    char *errMsg = NULL;
+    char *createRecordSql = "CREATE TABLE IF NOT EXISTS charging_record("
+                            "idx integer primary key AUTOINCREMENT, "
+                            "reservationId text, "
+                            "transactionId text, "
+                            "startMethod text, "
+                            "userId text, "
+                            "dateTimeStart text, "
+                            "dateTimeStop text,"
+                            "socStart text, "
+                            "socStop text, "
+                            "chargeEnergy text, "
+                            "stopReason text"
+                            ");";
+
+    /*char *createCfgSql = "CREATE TABLE IF NOT EXISTS `config` ( "
+                         "`idx` INTEGER PRIMARY KEY AUTOINCREMENT, "
+                         "`IsAvailable` TEXT NOT NULL, "
+                         "`connector` INTEGER NOT NULL, "
+                         "`val` TEXT NOT NULL, unique(IsAvailable,connector) on conflict replace);";
+    */
+    //DS60-120 add
+    char *createCfgSql = "CREATE TABLE IF NOT EXISTS `config` ( "
+                         "`idx` INTEGER PRIMARY KEY AUTOINCREMENT, "
+                         "`item` TEXT NOT NULL, "
+                         "`connector` INTEGER NOT NULL, "
+                         "`val` TEXT NOT NULL, unique(item,connector) on conflict replace);";
+
+    char *createrecordSql = "CREATE TABLE IF NOT EXISTS `event_record` ( "
+                            "`idx` INTEGER PRIMARY KEY AUTOINCREMENT, "
+                            "`occurDatetime` TEXT NOT NULL, "
+                            "`statusCode` TEXT NOT NULL, unique(occurDatetime,statusCode) on conflict replace);";
+
+    char *createrebootSql = "CREATE TABLE IF NOT EXISTS `reboot_record` ( "
+                            "`idx` INTEGER PRIMARY KEY AUTOINCREMENT, "
+                            "`rebootDatetime` TEXT NOT NULL, unique(rebootDatetime) on conflict replace);";
+
+    if (sqlite3_open(DB_FILE, &localDb)) {
+        result = FAIL;
+        log_info( "Can't open database: %s", sqlite3_errmsg(localDb));
+        sqlite3_close(localDb);
+    } else {
+        //log_info( "Local charging record database open successfully.");
+
+        if (sqlite3_exec(localDb, createRecordSql, 0, 0, &errMsg) != SQLITE_OK) {
+            result = FAIL;
+            log_info( "Create local charging record table error message: %s", errMsg);
+        } else {
+            log_info( "Opened local charging record table successfully");
+        }
+
+        if (sqlite3_exec(localDb, createCfgSql, 0, 0, &errMsg) != SQLITE_OK) {
+            result = FAIL;
+            log_info( "Create local config table error message: %s", errMsg);
+        } else {
+            log_info( "Opened local config table successfully");
+        }
+
+        //DS60-120
+        if (sqlite3_exec(localDb, createrecordSql, 0, 0, &errMsg) != SQLITE_OK) {
+            result = FAIL;
+            log_info( "Create local record table error message: %s", errMsg);
+        } else {
+            log_info( "Opened local record table successfully");
+        }
+
+        if (sqlite3_exec(localDb, createrebootSql, 0, 0, &errMsg) != SQLITE_OK) {
+            result = FAIL;
+            log_info( "Create reboot record table error message: %s", errMsg);
+        } else {
+            log_info( "Opened reboot record table successfully");
+        }
+        //-----
+
+        sqlite3_close(localDb);
+    }
+
+    ShmDcCommonData = (DcCommonInfo*)GetShmDcCommonData();
+    return result;
+}
+
+int DB_Insert_Record(int gunIndex)
+{
+    int result = PASS;
+    char *errMsg = NULL;
+    char insertSql[1024];
+    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+    struct OCPP16Data *ShmOCPP16Data = (struct OCPP16Data *)GetShmOCPP16Data();
+
+    sprintf(insertSql, "insert into charging_record(reservationId, transactionId, startMethod, userId, dateTimeStart, dateTimeStop, socStart, socStop, chargeEnergy, stopReason) "
+            "values('%d', '%d', '%d', '%s', '%s', '%s', '%d', '%d', '%f', '%s');",
+            pDcChargingInfo->ReservationId, //DS60-120 add
+            ShmOCPP16Data->StartTransaction[gunIndex].ResponseTransactionId,
+            pDcChargingInfo->StartMethod,
+            pDcChargingInfo->StartUserId,
+            pDcChargingInfo->StartDateTime,
+            pDcChargingInfo->StopDateTime,
+            pDcChargingInfo->EvBatteryStartSoc,
+            pDcChargingInfo->EvBatterySoc,
+            pDcChargingInfo->PresentChargedEnergy,
+            ShmOCPP16Data->StopTransaction[gunIndex].StopReason);
+
+    //if (sqlite3_open("/Storage/ChargeLog/localCgargingRecord.db", &db)) {
+    if (sqlite3_open(DB_FILE, &localDb)) { //DS60-120 add
+        result = FAIL;
+        log_info( "Can't open database: %s", sqlite3_errmsg(localDb));
+        sqlite3_close(localDb);
+    } else {
+        //log_info( "Local charging record database open successfully.");
+        if (sqlite3_exec(localDb, insertSql, 0, 0, &errMsg) != SQLITE_OK) {
+            result = FAIL;
+            log_info( "Insert local charging record error message: %s", errMsg);
+        } else {
+            //log_info( "Insert local charging record successfully");
+        }
+
+        //DS60-120 add
+        sprintf(insertSql, "delete from charging_record where idx < (select idx from charging_record order by idx desc limit 1)-2000;");
+        if (sqlite3_exec(localDb, insertSql, 0, 0, &errMsg) != SQLITE_OK) {
+            result = FAIL;
+            log_info( "delete local charging error message: %s", errMsg);
+        } else {
+            //log_info( "delete local charging record successfully");
+        }
+
+        sqlite3_close(localDb);
+    }
+
+    return result;
+}
+
+int DB_Update_Operactive(uint8_t gunIndex, uint8_t IsAvailable)
+{
+    uint8_t result = false;
+    char *errMsg = NULL;
+    char sqlStr[1024];
+    srand(time(NULL));
+
+    if (sqlite3_open(DB_FILE, &localDb)) {
+        result = FAIL;
+        log_info( "Can't open database: %s", sqlite3_errmsg(localDb));
+        sqlite3_close(localDb);
+    } else {
+        //log_info( "Local charging record database open successfully (%d).", IsAvailable);
+
+        //sprintf(sqlStr, "insert or replace into config (IsAvailable, connector, val) values('IsAvailable', %d, %d);", gunIndex, IsAvailable);
+        sprintf(sqlStr,
+                "insert or replace into config (item, connector, val) values('IsAvailable', %d, %d);",
+                gunIndex,
+                IsAvailable); //DS60-120 add
+        //log_info("sqlStr= %s", sqlStr);
+        if (sqlite3_exec(localDb, sqlStr, 0, 0, &errMsg) != SQLITE_OK) {
+            result = FAIL;
+            log_info( "update config error message: %s", errMsg);
+        } else {
+            log_info("update connector-%d config item isOperactive to %d", gunIndex, IsAvailable);
+        }
+
+        sqlite3_close(localDb);
+    }
+
+    return result;
+}
+
+int DB_Get_Operactive(uint8_t gunIndex)
+{
+    uint8_t result = true;
+    char *errMsg = NULL;
+    char sqlStr[1024];
+    char **rs;
+    int  rows, cols;
+
+    //sprintf(sqlStr, "select * from config where IsAvailable='IsAvailable' and connector=%d;", gunIndex);
+    sprintf(sqlStr, "select * from config where item='IsAvailable' and connector=%d;", gunIndex); //DS60-120 add
+    //DEBUG_INFO("sqlStr= %s", sqlStr);
+
+    if (sqlite3_open(DB_FILE, &localDb)) {
+        result = FAIL;
+        log_info( "Can't open database: %s", sqlite3_errmsg(localDb));
+        sqlite3_close(localDb);
+    } else {
+        log_info( "Local config query database open successfully.");
+        sqlite3_get_table(localDb, sqlStr, &rs, &rows, &cols, &errMsg);
+        if (rows > 0) {
+            for (int idxRow = 1; idxRow <= rows; idxRow++) {
+                if (strcmp(rs[(idxRow * cols) + 3], "0") == 0) {
+                    result = false;
+                }
+                log_info("Query connector-%d isOperactive: %s", gunIndex, rs[(idxRow * cols) + 3]);
+            }
+        } else {
+            log_info("Query connector-%d fail, set default value to operactive.", gunIndex);
+        }
+
+        sqlite3_free_table(rs);
+        sqlite3_close(localDb);
+    }
+
+    return result;
+}
+
+int DB_Reboot_Record(void)
+{
+    int result = PASS;
+    char *errMsg = NULL;
+    char insertSql[256];
+
+    sprintf(insertSql, "insert into reboot_record(rebootDatetime) values(CURRENT_TIMESTAMP);");
+
+    if (sqlite3_open(DB_FILE, &localDb)) {
+        result = FAIL;
+        log_info( "Can't open database: %s", sqlite3_errmsg(localDb));
+        sqlite3_close(localDb);
+    } else {
+        //log_info( "Local charging record database open successfully.");
+        if (sqlite3_exec(localDb, insertSql, 0, 0, &errMsg) != SQLITE_OK) {
+            result = FAIL;
+            log_info( "Insert reboot record error message: %s", errMsg);
+        } else {
+            log_info( "Insert reboot record successfully");
+        }
+
+        sprintf(insertSql, "delete from reboot_record where idx < (select idx from charging_record order by idx desc limit 1)-2000;");
+        if (sqlite3_exec(localDb, insertSql, 0, 0, &errMsg) != SQLITE_OK) {
+            result = FAIL;
+            log_info( "delete reboot record error message: %s", errMsg);
+        } else {
+            log_info( "delete reboot record successfully");
+        }
+
+        sqlite3_close(localDb);
+    }
+
+    return result;
+}
+
+//------------------------------------------------------------------------------
+//for Module_EventLog
+//------------------------------------------------------------------------------
+int CreateEventRecord(void)
+{
+    int result = PASS;
+    char *errMsg = NULL;
+    char *createRecordSql = "CREATE TABLE IF NOT EXISTS event_record("
+                            "idx integer primary key AUTOINCREMENT, "
+                            "occurDatetime text NOT NULL, "
+                            "statusCode text NOT NULL"
+                            ");";
+
+    if (sqlite3_open(DB_FILE, &localDb)) {
+        result = FAIL;
+        log_error( "Can't open database: %s", sqlite3_errmsg(localDb));
+        sqlite3_close(localDb);
+    } else {
+        log_info( "Local event record database open successfully.");
+
+        if (sqlite3_exec(localDb, createRecordSql, 0, 0, &errMsg) != SQLITE_OK) {
+            result = FAIL;
+            log_error( "Create local event record table error message: %s", errMsg);
+        } else {
+            log_info( "Opened local event record table successfully");
+        }
+
+        sqlite3_close(localDb);
+    }
+
+    return result;
+}
+
+int InsertEventRecord(uint8_t *statusCode)
+{
+    int result = PASS;
+    char *errMsg = NULL;
+    char sqlStr[1024] = {0};
+
+    sprintf(sqlStr, "insert into event_record(occurDatetime, statusCode) values(CURRENT_TIMESTAMP, '%s');", statusCode);
+
+    if (sqlite3_open(DB_FILE, &localDb)) {
+        result = FAIL;
+        log_info( "Can't open database: %s", sqlite3_errmsg(localDb));
+        sqlite3_close(localDb);
+    } else {
+        //log_info( "Local event record database open successfully.");
+        if (sqlite3_exec(localDb, sqlStr, 0, 0, &errMsg) != SQLITE_OK) {
+            result = FAIL;
+            log_info( "Insert local event record error message: %s", errMsg);
+        } else {
+            //log_info( "Insert local event record successfully");
+        }
+
+        sprintf(sqlStr, "delete from event_record where idx < (select idx from event_record order by idx desc limit 1)-2000;");
+        if (sqlite3_exec(localDb, sqlStr, 0, 0, &errMsg) != SQLITE_OK) {
+            result = FAIL;
+            log_info( "delete local event_record error message: %s", errMsg);
+        } else {
+            //log_info( "delete local event record successfully");
+        }
+
+        sqlite3_close(localDb);
+    }
+
+    return result;
+}
+void CreditCardTimeSet(char *_time, RecordTransactionInfo* deductInfo)
+{
+    _time[0] = '2';
+    _time[1] = '0';
+    _time[2] = (char)deductInfo->pCreditCard.TransDate[0];
+    _time[3] = (char)deductInfo->pCreditCard.TransDate[1];
+    _time[4] = '-';
+    _time[5] = (char)deductInfo->pCreditCard.TransDate[2];
+    _time[6] = (char)deductInfo->pCreditCard.TransDate[3];
+    _time[7] = '-';
+    _time[8] = (char)deductInfo->pCreditCard.TransDate[4];
+    _time[9] = (char)deductInfo->pCreditCard.TransDate[5];
+    _time[10] = ' ';
+    _time[11] = (char)deductInfo->pCreditCard.TransTime[0];
+    _time[12] = (char)deductInfo->pCreditCard.TransTime[1];
+    _time[13] = ':';
+    _time[14] = (char)deductInfo->pCreditCard.TransTime[2];
+    _time[15] = (char)deductInfo->pCreditCard.TransTime[3];
+    _time[16] = ':';
+    _time[17] = (char)deductInfo->pCreditCard.TransTime[4];
+    _time[18] = (char)deductInfo->pCreditCard.TransTime[5];
+    _time[19] = '\0';
+}
+
+int DeductDB_Open(void)
+{
+	int result = PASS;
+	char* errMsg = NULL;
+	char* createDeductInfoSql="CREATE TABLE IF NOT EXISTS report_credit_deduct("
+					      	  "idx integer primary key AUTOINCREMENT, "
+							  "gun_index text, "
+                              "reportDate text, "
+                              "vemData text, "
+                              "txId text, "
+                              "creditNo text, "
+                              "amount text, "
+                              "storeId text, "
+                              "approvalNo text, "
+                              "RRN text, "
+                              "ROC text, "
+                              "isDonateInvoice text, "
+                              "isDeductResult text, "
+                              "isIntoCharge text, "
+                              "isUpload text, "
+                              "lineSn text, "
+                              "Energy text, "
+                              "RedeductTime "
+						  	  ");";
+
+	if(sqlite3_open(DEDUCT_FILE, &deductDb))
+	{
+		result = FAIL;
+		log_info("Can't open deduct database: %s", sqlite3_errmsg(deductDb));
+		sqlite3_close(deductDb);
+	}
+	else
+	{
+		//log_info("Deduct database open successfully.");
+		if (sqlite3_exec(deductDb, createDeductInfoSql, 0, 0, &errMsg) != SQLITE_OK)
+		{
+			result = FAIL;
+			log_info("Create deduct info table error message: %s", errMsg);
+		}
+		else
+		{
+			log_info("Opened deduct info table successfully");
+		}
+       
+		sqlite3_close(deductDb);
+	}
+
+	return result;
+}
+
+int InsertDeductInfo(int gunIndex, RecordTransactionInfo *deductInfo)
+{
+    int result = PASS;
+    char *errMsg = NULL;
+    char sqlStr[1024] = {0};
+    char approNo[13];
+    char carNo[21];
+    char vemData[65];
+    char storeId[18];
+    char RRN[12];
+    char ROC[12];
+    char lineSn[20];
+    char _time[20];
+
+    memset(approNo, '\0', sizeof(approNo));
+    memset(carNo, '\0', sizeof(carNo));
+    memset(vemData, '\0', sizeof(vemData));
+    memset(storeId, '\0', sizeof(storeId));
+    memset(RRN, '\0', sizeof(RRN));
+    memset(ROC, '\0', sizeof(ROC));
+    memset(lineSn, '\0', sizeof(lineSn));
+
+    strncpy(approNo, (char *)&deductInfo->pCreditCard.ApprovalNo,9);
+    strncpy(carNo, (char *)&deductInfo->pCreditCard.CardNo,20);
+    strncpy(vemData, (char *)&deductInfo->pCreditCard.VemData,64);
+    strncpy(storeId, (char *)&deductInfo->pCreditCard.StoreId,18 );
+    strncpy(RRN,(char *)&deductInfo->pCreditCard.RRN,12);
+    strncpy(ROC,(char *)&deductInfo->pCreditCard.ROC,12);
+    CreditCardTimeSet(&_time[0], deductInfo);
+    //sprintf(reportDate, "%s%s", deductInfo->pCreditCard.TransDate, deductInfo->pCreditCard.TransTime);
+
+	sprintf(sqlStr, "insert into report_credit_deduct(gun_index, reportDate, vemData, txId, creditNo, amount, storeId, approvalNo, RRN, ROC, isDonateInvoice, isDeductResult, isIntoCharge, isUpload, lineSn, Energy, RedeductTime) "
+				    "values('%d', '%s', '%s', '%d', '%s', '%.1f', '%s', '%s', '%s', '%s', '%d', '%d', '%d' , '%d', '%d', '%.4f', '%d');",
+                    gunIndex,
+                    _time,
+				    vemData,
+                    deductInfo->TransactionId,
+                    carNo,
+                    deductInfo->Amount,
+					storeId,
+                    approNo,
+				    RRN,
+				    ROC,
+                    (int)deductInfo->IsDonateInvoice,
+                    (int)deductInfo->DeductResult,
+                    (int)deductInfo->isIntoCharge,
+                    (int)deductInfo->IsUpload,
+                    deductInfo->LineStatus,
+                    deductInfo->Energy,
+                    deductInfo->RedeductTime);
+
+    //log_info("%s",sqlStr);
+
+    if (sqlite3_open(DEDUCT_FILE, &deductDb))
+    {
+        result = FAIL;
+        log_info( "Can't open deduct database: %s", sqlite3_errmsg(deductDb));
+        sqlite3_close(deductDb);
+    }
+    else
+    {
+        //log_info( "Local event record database open successfully.");
+        if (sqlite3_exec(deductDb, sqlStr, 0, 0, &errMsg) != SQLITE_OK)
+        {
+            result = FAIL;
+            log_info( "Insert deduct record error message: %s", errMsg);
+        }
+        else
+        {
+            //log_info( "Insert local event record successfully");
+        }
+
+
+        sprintf(sqlStr, "delete from report_credit_deduct where idx < (select idx from report_credit_deduct order by idx desc limit 1)-10000;");
+        if (sqlite3_exec(deductDb, sqlStr, 0, 0, &errMsg) != SQLITE_OK)
+        {
+            result = FAIL;
+            log_info("delete deduct record error message: %s", errMsg);
+        }
+        else
+        {
+            //log_info("delete local charging record successfully");
+        }
+
+        sqlite3_close(deductDb);
+    }
+
+    return result;
+}
+
+int UpdateDeductInfoStatus(int gunIndex, RecordTransactionInfo *deductInfo)
+{
+
+    int result = PASS;
+    char *errMsg = NULL;
+    char sqlStr[1024] = {0};
+    char ApprovalNo[10] = {0};
+    memset(ApprovalNo, '\0', 10);
+    strncpy(ApprovalNo, (char*)&deductInfo->pCreditCard.ApprovalNo,9);
+
+    sprintf(sqlStr, "update report_credit_deduct set isUpload = %d , isIntoCharge = %d, amount = %.1f, txId = %d, isDeductResult = %d, Energy = %.4f, lineSn = %d, RedeductTime = %d where approvalNo = '%s'; ",
+                    (int)deductInfo->IsUpload,
+                    (int)deductInfo->isIntoCharge,
+                    deductInfo->Amount,
+                    deductInfo->TransactionId,
+                    (int)deductInfo->DeductResult,
+                    deductInfo->Energy,
+                    deductInfo->LineStatus,
+                    deductInfo->RedeductTime,
+                    ApprovalNo);
+
+    //log_info("%s",sqlStr);
+
+    if (sqlite3_open(DEDUCT_FILE, &deductDb))
+    {
+        result = FAIL;
+        log_info( "Can't open deduct database: %s", sqlite3_errmsg(deductDb));
+        sqlite3_close(deductDb);
+    }
+    else
+    {
+        //log_info( "Local event record database open successfully.");
+        if (sqlite3_exec(deductDb, sqlStr, 0, 0, &errMsg) != SQLITE_OK)
+        {
+            result = FAIL;
+            log_info( "update deduct record error message: %s!", errMsg);
+        }
+        else
+        {
+            //log_info( "update deduct record successfully");
+        }
+
+        sqlite3_close(deductDb);
+    }
+
+    return result;
+}
+
+int UpdateRedeuctBill(int Txid,float amount)
+{
+    int result = PASS;
+    char* errMsg = NULL;
+    char sqlStr[1024] = { 0 };
+
+    sprintf(sqlStr, "update report_credit_deduct set amount = %.1f where txId = '%d'; ",
+            amount,
+            Txid);
+
+    //log_info("%s",sqlStr);
+
+    if (sqlite3_open(DEDUCT_FILE, &deductDb))
+    {
+        result = FAIL;
+        log_info("Can't open deduct database: %s", sqlite3_errmsg(deductDb));
+        sqlite3_close(deductDb);
+    } else
+    {
+        //log_info( "Local event record database open successfully.");
+        if (sqlite3_exec(deductDb, sqlStr, 0, 0, &errMsg) != SQLITE_OK)
+        {
+            result = FAIL;
+            log_info("update deduct record error message: %s!", errMsg);
+        } else
+        {
+            //log_info( "update deduct record successfully");
+        }
+
+        sqlite3_close(deductDb);
+    }
+
+    return result;
+}
+
+int DB_GetDeductInfo(int deductResult, int uploadState, int *gunIndex, RecordTransactionInfo *deductInfo)
+{
+    int result = PASS;
+    char *errMsg = NULL;
+    char sqlStr[1024];
+    char **rs;
+    int rows, cols;
+
+    if(deductResult >= 0 && uploadState >= 0)
+    {
+        sprintf(sqlStr, "select * from report_credit_deduct where isDeductResult = %d and isUpload = %d;", deductResult > 0 ? 1 : 0, uploadState > 0 ? 1 : 0);
+    }
+    else if(deductResult >= 0 && uploadState < 0)
+    {
+        sprintf(sqlStr, "select * from report_credit_deduct where isDeductResult = 0 OR isDeductResult = 3;");
+    }
+    else if(deductResult < 0 && uploadState >= 0)
+    {
+        sprintf(sqlStr, "select * from report_credit_deduct where isUpload = %d;", uploadState > 0 ? 1 : 0);
+    }
+    else
+    {
+        sprintf(sqlStr, "select * from report_credit_deduct;");
+    }
+
+    if (sqlite3_open(DEDUCT_FILE, &deductDb))
+    {
+        result = FAIL;
+        log_info("Can't open deduct database: %s", sqlite3_errmsg(deductDb));
+        sqlite3_close(deductDb);
+    }
+    else
+    {
+        sqlite3_get_table(deductDb, sqlStr, &rs, &rows, &cols, &errMsg);
+
+        if (rows > 0)
+        {
+            for (int idxRow = 1; idxRow <= rows; idxRow++)
+            {
+                *gunIndex = atoi(rs[(idxRow * cols) + 1]);
+                deductInfo->TransactionId = atoi(rs[(idxRow * cols) + 2]);
+                deductInfo->DeductResult = atoi(rs[(idxRow * cols) + 3]);
+                deductInfo->IsDonateInvoice = atoi(rs[(idxRow * cols) + 4]);
+                strcpy((char *)&deductInfo->pCreditCard.ApprovalNo, rs[(idxRow * cols) + 5]);
+                strcpy((char *)&deductInfo->pCreditCard.CardNo, rs[(idxRow * cols) + 6]);
+                strcpy((char *)&deductInfo->pCreditCard.VemData, rs[(idxRow * cols) + 7]);
+                deductInfo->Amount = atoi(rs[(idxRow * cols) + 8]);
+                deductInfo->IsUpload = atoi(rs[(idxRow * cols) + 9]);
+                break;
+            }
+        }
+        else
+        {
+            result = FAIL;
+        }
+        sqlite3_free_table(rs);
+        sqlite3_close(deductDb);
+    }
+
+    return result;
+}
+
+int DB_GetReDeductInfo(int *gunIndex, RecordTransactionInfo *deductInfo)
+{
+    int result = PASS;
+
+    if(DB_GetDeductInfo(0, -1, gunIndex, deductInfo) == PASS)
+    {
+        //log_info("GetReDeductInfo OK");
+    }
+    else
+    {
+        result = FAIL;
+        //log_info("GetReDeductInfo NG");
+    }
+
+    return result;
+}
+
+int DB_GetReUploadDeduct(int *gunIndex, RecordTransactionInfo *deductInfo)
+{
+    int result = PASS;
+
+    if(DB_GetDeductInfo(-1, 0, gunIndex, deductInfo) == PASS)
+    {
+        //log_info("GetReUploadDeduct OK");
+    }
+    else
+    {
+        result = FAIL;
+        //log_info("GetReUploadDeduct NG");
+    }
+
+    return result;
+}
+void GetDeductTime(char* _time,RecordTransactionInfo* deductInfo)
+{
+    deductInfo->pCreditCard.TransDate[0] = (unsigned char)_time[2];
+    deductInfo->pCreditCard.TransDate[1] = (unsigned char)_time[3];
+    deductInfo->pCreditCard.TransDate[2] = (unsigned char)_time[5];
+    deductInfo->pCreditCard.TransDate[3] = (unsigned char)_time[6];
+    deductInfo->pCreditCard.TransDate[4] = (unsigned char)_time[8];
+    deductInfo->pCreditCard.TransDate[5] = (unsigned char)_time[9];
+
+    deductInfo->pCreditCard.TransTime[0] = (unsigned char)_time[11];
+    deductInfo->pCreditCard.TransTime[1] = (unsigned char)_time[12];
+    deductInfo->pCreditCard.TransTime[2] = (unsigned char)_time[14];
+    deductInfo->pCreditCard.TransTime[3] = (unsigned char)_time[15];
+    deductInfo->pCreditCard.TransTime[4] = (unsigned char)_time[17];
+    deductInfo->pCreditCard.TransTime[5] = (unsigned char)_time[18];
+
+}
+// return quantity of DeductInfo
+int DB_GetMultiDeductInfo(int deductResult, int uploadState, int *gunIndex, RecordTransactionInfo *deductInfo)
+{
+    char *errMsg = NULL;
+    char sqlStr[1024];
+    char **rs;
+    int rows = 0, cols = 0;
+
+    if(deductResult >= 0 && uploadState >= 0)
+    {
+        sprintf(sqlStr, "select * from report_credit_deduct where isDeductResult = %d and isUpload = %d;", deductResult > 0 ? 1 : 0, uploadState > 0 ? 1 : 0);
+    }
+    else if(deductResult >= 0 && uploadState < 0)
+    {
+        sprintf(sqlStr, "select * from report_credit_deduct where isDeductResult IN (0,3) AND RedeductTime < 10;");
+    }
+    else if(deductResult < 0 && uploadState >= 0)
+    {
+        sprintf(sqlStr, "select * from report_credit_deduct where isUpload = %d;", uploadState > 0 ? 1 : 0);
+    }
+    else
+    {
+        sprintf(sqlStr, "select * from report_credit_deduct;");
+    }
+
+    if (sqlite3_open(DEDUCT_FILE, &deductDb))
+    {
+        log_info("Can't open deduct database: %s", sqlite3_errmsg(deductDb));
+        sqlite3_close(deductDb);
+    }
+    else
+    {
+        sqlite3_get_table(deductDb, sqlStr, &rs, &rows, &cols, &errMsg);
+
+        if (rows > 0)
+        {
+            for (int idxRow = 1; idxRow <= rows; idxRow++)
+            {
+                //gunIndex[idxRow - 1] = atoi(rs[(idxRow * cols) + 1]);
+                deductInfo[idxRow - 1].ConnectorID = atoi(rs[(idxRow * cols) + 1]);
+               // GetDeductTime(rs[(idxRow * cols) + 1], deductInfo);
+                memcpy((char*)&deductInfo[idxRow - 1].pCreditCard.VemData, rs[(idxRow * cols) + 3],64);
+                deductInfo[idxRow - 1].TransactionId = atoi(rs[(idxRow * cols) + 4]);
+                memcpy((char*)&deductInfo[idxRow - 1].pCreditCard.CardNo, rs[(idxRow * cols) + 5],20);
+                deductInfo[idxRow - 1].Amount = atoi(rs[(idxRow * cols) + 6]);
+                memcpy((char*)&deductInfo[idxRow - 1].pCreditCard.StoreId, rs[(idxRow * cols) + 7],18);
+                memcpy((char*)&deductInfo[idxRow - 1].pCreditCard.ApprovalNo, rs[(idxRow * cols) + 8],9);
+                memcpy((char*)&deductInfo[idxRow - 1].pCreditCard.RRN, rs[(idxRow * cols) + 9],12);
+                memcpy((char*)&deductInfo[idxRow - 1].pCreditCard.ROC, rs[(idxRow * cols) + 10],12);
+                deductInfo[idxRow - 1].IsDonateInvoice = atoi(rs[(idxRow * cols) + 11]);
+                deductInfo[idxRow - 1].DeductResult = atoi(rs[(idxRow * cols) + 12]);
+                deductInfo[idxRow - 1].isIntoCharge = atoi(rs[(idxRow * cols) + 13]);
+                deductInfo[idxRow - 1].IsUpload = atoi(rs[(idxRow * cols) + 14]);
+                deductInfo[idxRow - 1].LineStatus = atoi(rs[(idxRow * cols) + 15]);
+                deductInfo[idxRow - 1].Energy = atof(rs[(idxRow * cols) + 16]);
+                deductInfo[idxRow - 1].RedeductTime = atoi(rs[(idxRow * cols) + 17]);
+                if(idxRow >= 128)
+                {
+                	rows = 128;
+                	break;
+                }
+            }
+        }
+
+        sqlite3_free_table(rs);
+        sqlite3_close(deductDb);
+    }
+
+    return rows;
+}
+
+int DB_GetMultiReDeductInfo(int *gunIndex, RecordTransactionInfo *deductInfo)
+{
+    int quantity = 0;
+
+    quantity = DB_GetMultiDeductInfo(0, -1, gunIndex, deductInfo);
+
+    return quantity;
+}
+
+int DB_GetMultiReUploadDeduct(int *gunIndex, RecordTransactionInfo *deductInfo)
+{
+	int quantity = 0;
+
+	quantity = DB_GetMultiDeductInfo(-1, 0, gunIndex, deductInfo);
+
+    return quantity;
+}
+
+void ReDeductTest()
+{
+	int quantity = 0;
+	int gunList[128];
+	RecordTransactionInfo deductInfo[128];
+
+	quantity = DB_GetMultiReDeductInfo(gunList, deductInfo);
+
+	if(quantity > 0)
+	{
+		for(int i = 0; i < quantity; i++)
+		{
+			printf("Gun %d Rededuct CardNo: %s", gunList[i], deductInfo[i].pCreditCard.VemData);
+		}
+	}
+}
+
+int PowerDB_Open(void)
+{
+    int result = PASS;
+    char* errMsg = NULL;
+    char* createPowerConsumption = "CREATE TABLE IF NOT EXISTS power_consumption( "
+        "idx INTEGER PRIMARY KEY AUTOINCREMENT, "
+        "connector TEXT, "
+        "val TEXT);";
+
+    if (sqlite3_open(POWER_FILE, &powerDb))
+    {
+        result = FAIL;
+        log_info("Can't open deduct database: %s", sqlite3_errmsg(powerDb));
+        sqlite3_close(powerDb);
+    } else
+    {
+        if (sqlite3_exec(powerDb, createPowerConsumption, 0, 0, &errMsg) != SQLITE_OK) {
+            result = FAIL;
+            log_info("Create power consumption record table error message: %s", errMsg);
+        } else {
+            log_info("Opened power consumption record table successfully");
+        }
+
+        sqlite3_close(powerDb);
+    }
+
+    return result;
+}
+
+int DB_Insert_PowerConsumption(uint8_t gunIndex, float energy)
+{
+    uint8_t result = false;
+    char* errMsg = NULL;
+    char sqlStr[1024];
+    srand(time(NULL));
+
+    if (sqlite3_open(POWER_FILE, &powerDb)) {
+        result = FAIL;
+        log_info("Can't open database: %s", sqlite3_errmsg(powerDb));
+        sqlite3_close(powerDb);
+    } else {
+        //log_info("Local charging record database open successfully (%f).", energy);
+        sprintf(sqlStr, "insert into power_consumption (connector, val) values (%d, %f);",
+            gunIndex,
+            energy); //DS60-120 add
+        //log_info("sqlStr= %s", sqlStr);
+        if (sqlite3_exec(powerDb, sqlStr, 0, 0, &errMsg) != SQLITE_OK) {
+            result = FAIL;
+            log_info("Insert power consumption error message: %s", errMsg);
+        } else {
+            log_info("Insert connector-%d config item PowerComsumption to %f", gunIndex, energy);
+        }
+
+        sqlite3_close(powerDb);
+    }
+
+    return result;
+}
+
+int DB_Update_PowerConsumption(uint8_t gunIndex, float energy)
+{
+    uint8_t result = false;
+    char* errMsg = NULL;
+    char sqlStr[1024];
+    srand(time(NULL));
+
+    if (sqlite3_open(POWER_FILE, &powerDb)) {
+        result = FAIL;
+        log_info("Can't open database: %s", sqlite3_errmsg(powerDb));
+        sqlite3_close(powerDb);
+    } else {
+        //log_info("Local charging record database open successfully.");
+        sprintf(sqlStr, "update power_consumption set val = %f where connector = %d; ",
+            energy,
+            gunIndex); //DS60-120 add
+//log_info("sqlStr= %s", sqlStr);
+        if (sqlite3_exec(powerDb, sqlStr, 0, 0, &errMsg) != SQLITE_OK) {
+            result = FAIL;
+            log_info("update config error message: %s", errMsg);
+        } else {
+            //log_info("update connector-%d config item PowerComsumption to %f", gunIndex, energy);
+        }
+
+        sqlite3_close(powerDb);
+    }
+
+    return result;
+}
+
+int DB_Get_PowerConsumption(uint8_t gunIndex)
+{
+    uint8_t result = true;
+    char* errMsg = NULL;
+    char sqlStr[1024];
+    char** rs;
+    int  rows, cols;
+
+    //sprintf(sqlStr, "select * from config where IsAvailable='IsAvailable' and connector=%d;", gunIndex);
+    sprintf(sqlStr, "select * from power_consumption where connector=%d;", gunIndex); //DS60-120 add
+    //DEBUG_INFO("sqlStr= %s", sqlStr);
+
+    if (sqlite3_open(POWER_FILE, &powerDb)) {
+        result = FAIL;
+        log_info("Can't open database: %s", sqlite3_errmsg(powerDb));
+        sqlite3_close(powerDb);
+    } else {
+        //log_info("Local config query database open successfully.");
+        sqlite3_get_table(powerDb, sqlStr, &rs, &rows, &cols, &errMsg);
+        if (rows > 0) {
+            for (int idxRow = 1; idxRow <= rows; idxRow++) {
+                ShmDcCommonData->pGunInfo[gunIndex].PowerConsumption = atof(rs[(idxRow * cols) + 2]);
+                log_info("Query connector-%d PowerConsumption: %s", gunIndex, rs[(idxRow * cols) + 2]);
+
+            }
+        } else {
+            log_info("Query connector-%d fail, set default value to operactive.", gunIndex);
+            result = false;
+        }
+
+        sqlite3_free_table(rs);
+        sqlite3_close(powerDb);
+    }
+
+    return result;
+}
+
+int ParkingDB_Open(void)
+{
+	int result = PASS;
+	char* errMsg = NULL;
+	char* createDeductInfoSql="CREATE TABLE IF NOT EXISTS report_Parking_deduct("
+					      	  "idx integer primary key AUTOINCREMENT, "
+							  "gun_index text, "
+                              "vemData text, "
+                              "OccupancySN text, "
+                              "duration text, "
+                              "creditNo text, "
+                              "amount text, "
+                              "storeId text, "
+                              "approvalNo text, "
+                              "RRN text, "
+                              "ROC text, "
+                              "isDonateInvoice text, "
+                              "isDeductResult text, "
+                              "isUpload text, "
+                              "lineSn text, "
+                              "StartTime text, "
+                              "RedeductTime "
+						  	  ");";
+	if(sqlite3_open(PARKINGDEDUCT_FILE, &parkingDb))
+	{
+		result = FAIL;
+		log_info("Can't open Parking deduct database: %s", sqlite3_errmsg(parkingDb));
+		sqlite3_close(parkingDb);
+	}
+	else
+	{
+		//log_info("Deduct database open successfully.");
+		if (sqlite3_exec(parkingDb, createDeductInfoSql, 0, 0, &errMsg) != SQLITE_OK)
+		{
+			result = FAIL;
+			log_info("Create Parking deduct info table error message: %s", errMsg);
+		}
+		else
+		{
+			log_info("Opened Parking deduct info table successfully");
+		}
+       
+		sqlite3_close(parkingDb);
+	}
+
+	return result;
+}
+
+int InsertParkingDeductInfo(int gunIndex, RecordTransactionInfo *deductInfo)
+{
+    int result = PASS;
+    char *errMsg = NULL;
+    char sqlStr[1024] = {0};
+    char approNo[13];
+    char carNo[21];
+    char OccupancySN[37];
+    char storeId[18];
+    char RRN[12];
+    char ROC[12];
+    char lineSn[20];
+    char _time[33];
+    char vemData[65];
+
+    memset(approNo, '\0', sizeof(approNo));
+    memset(carNo, '\0', sizeof(carNo));
+    memset(OccupancySN, '\0', sizeof(OccupancySN));
+    memset(storeId, '\0', sizeof(storeId));
+    memset(RRN, '\0', sizeof(RRN));
+    memset(ROC, '\0', sizeof(ROC));
+    memset(lineSn, '\0', sizeof(lineSn));
+    memset(_time,'\0',sizeof(_time));
+    memset(vemData,'\0',sizeof(vemData));
+
+    strncpy(approNo, (char *)&deductInfo->pCreditCard.ApprovalNo,9);
+    strncpy(carNo, (char *)&deductInfo->pCreditCard.CardNo,20);
+    strncpy(OccupancySN, (char *)&deductInfo->OccupancySN,36);
+    strncpy(storeId, (char *)&deductInfo->pCreditCard.StoreId,18 );
+    strncpy(RRN,(char *)&deductInfo->pCreditCard.RRN,12);
+    strncpy(ROC,(char *)&deductInfo->pCreditCard.ROC,12);
+    strncpy(_time,(char *)&deductInfo->ParkingStartTime,33);
+    strncpy(vemData,(char *)&deductInfo->pCreditCard.VemData,64);
+
+    //sprintf(reportDate, "%s%s", deductInfo->pCreditCard.TransDate, deductInfo->pCreditCard.TransTime);
+
+	sprintf(sqlStr, "insert into report_Parking_deduct(gun_index, vemData, OccupancySN, duration, creditNo, amount, storeId, approvalNo, RRN, ROC, isDonateInvoice, isDeductResult, isUpload, lineSn, StartTime, RedeductTime) "
+				    "values('%d', '%s', '%s', '%d', '%s', '%.1f', '%s', '%s', '%s', '%s', '%d', '%d', '%d', '%d', '%s', '%d');",
+                    gunIndex,
+                    vemData,
+				    OccupancySN,
+                    deductInfo->ParkingDuration,
+                    carNo,
+                    deductInfo->Amount,
+					storeId,
+                    approNo,
+				    RRN,
+				    ROC,
+                    (int)deductInfo->IsDonateInvoice,
+                    (int)deductInfo->DeductResult,
+                    (int)deductInfo->IsUpload,
+                    deductInfo->LineStatus,
+                    _time,
+                    deductInfo->RedeductTime);
+
+    //log_info("%s",sqlStr);
+
+    if (sqlite3_open(PARKINGDEDUCT_FILE, &parkingDb))
+    {
+        result = FAIL;
+        log_info( "Can't open deduct database: %s", sqlite3_errmsg(parkingDb));
+        sqlite3_close(parkingDb);
+    }
+    else
+    {
+        //log_info( "Local event record database open successfully.");
+        if (sqlite3_exec(parkingDb, sqlStr, 0, 0, &errMsg) != SQLITE_OK)
+        {
+            result = FAIL;
+            log_info( "Insert deduct record error message: %s", errMsg);
+        }
+        else
+        {
+            //log_info( "Insert local event record successfully");
+        }
+
+
+        sprintf(sqlStr, "delete from report_Parking_deduct where idx < (select idx from report_Parking_deduct order by idx desc limit 1)-10000;");
+        if (sqlite3_exec(parkingDb, sqlStr, 0, 0, &errMsg) != SQLITE_OK)
+        {
+            result = FAIL;
+            log_info("delete deduct record error message: %s", errMsg);
+        }
+        else
+        {
+            //log_info("delete local charging record successfully");
+        }
+
+        sqlite3_close(parkingDb);
+    }
+
+    return result;
+}
+
+// return quantity of DeductInfo
+int DB_GetParkingDeductUpload(int *gunIndex, RecordTransactionInfo *deductInfo)
+{
+    char *errMsg = NULL;
+    char sqlStr[1024];
+    char **rs;
+    int rows = 0, cols = 0;
+
+    sprintf(sqlStr, "select * from report_Parking_deduct where isUpload = 0;");
+
+    if (sqlite3_open(PARKINGDEDUCT_FILE, &parkingDb))
+    {
+        log_info("Can't open parking database: %s", sqlite3_errmsg(parkingDb));
+        sqlite3_close(parkingDb);
+    }
+    else
+    {
+        sqlite3_get_table(parkingDb, sqlStr, &rs, &rows, &cols, &errMsg);
+
+        if (rows > 0)
+        {
+            for (int idxRow = 1; idxRow <= rows; idxRow++)
+            {
+                //gunIndex[idxRow - 1] = atoi(rs[(idxRow * cols) + 1]);
+                deductInfo[idxRow - 1].ConnectorID = atoi(rs[(idxRow * cols) + 1]);
+                // GetDeductTime(rs[(idxRow * cols) + 1], deductInfo);
+                memcpy((char*)&deductInfo[idxRow - 1].pCreditCard.VemData, rs[(idxRow * cols) + 2],64);
+                memcpy((char*)&deductInfo[idxRow - 1].OccupancySN, rs[(idxRow * cols) + 3],36);
+                deductInfo[idxRow - 1].ParkingDuration = atoi(rs[(idxRow * cols) + 4]);
+                memcpy((char*)&deductInfo[idxRow - 1].pCreditCard.CardNo, rs[(idxRow * cols) + 5],20);
+                deductInfo[idxRow - 1].Amount = atoi(rs[(idxRow * cols) + 6]);
+                memcpy((char*)&deductInfo[idxRow - 1].pCreditCard.StoreId, rs[(idxRow * cols) + 7],18);
+                memcpy((char*)&deductInfo[idxRow - 1].pCreditCard.ApprovalNo, rs[(idxRow * cols) + 8],9);
+                memcpy((char*)&deductInfo[idxRow - 1].pCreditCard.RRN, rs[(idxRow * cols) + 9],12);
+                memcpy((char*)&deductInfo[idxRow - 1].pCreditCard.ROC, rs[(idxRow * cols) + 10],12);
+                deductInfo[idxRow - 1].IsDonateInvoice = atoi(rs[(idxRow * cols) + 11]);
+                deductInfo[idxRow - 1].DeductResult = atoi(rs[(idxRow * cols) + 12]);
+                deductInfo[idxRow - 1].IsUpload = atoi(rs[(idxRow * cols) + 13]);
+                deductInfo[idxRow - 1].LineStatus = atoi(rs[(idxRow * cols) + 14]);
+                memcpy((char*)&deductInfo[idxRow - 1].ParkingStartTime, rs[(idxRow * cols) + 15],32);
+                deductInfo[idxRow - 1].RedeductTime = atoi(rs[(idxRow * cols) + 16]);
+                if(idxRow >= 128)
+                {
+                	rows = 128;
+                	break;
+                }
+            }
+        }
+
+        sqlite3_free_table(rs);
+        sqlite3_close(parkingDb);
+    }
+
+    return rows;
+}
+
+int DB_GetParkingDeductResult(int *gunIndex, RecordTransactionInfo *deductInfo)
+{
+    char *errMsg = NULL;
+    char sqlStr[1024];
+    char **rs;
+    int rows = 0, cols = 0;
+
+    sprintf(sqlStr, "select * from report_Parking_deduct where isDeductResult = 0 OR isDeductResult = 3;");
+
+    if (sqlite3_open(PARKINGDEDUCT_FILE, &parkingDb))
+    {
+        log_info("Can't open parking database: %s", sqlite3_errmsg(parkingDb));
+        sqlite3_close(parkingDb);
+    }
+    else
+    {
+        sqlite3_get_table(parkingDb, sqlStr, &rs, &rows, &cols, &errMsg);
+
+        if (rows > 0)
+        {
+            for (int idxRow = 1; idxRow <= rows; idxRow++)
+            {
+                //gunIndex[idxRow - 1] = atoi(rs[(idxRow * cols) + 1]);
+                deductInfo[idxRow - 1].ConnectorID = atoi(rs[(idxRow * cols) + 1]);
+                // GetDeductTime(rs[(idxRow * cols) + 1], deductInfo);
+                memcpy((char*)&deductInfo[idxRow - 1].pCreditCard.VemData, rs[(idxRow * cols) + 2],64);
+                memcpy((char*)&deductInfo[idxRow - 1].OccupancySN, rs[(idxRow * cols) + 3],36);
+                deductInfo[idxRow - 1].ParkingDuration = atoi(rs[(idxRow * cols) + 4]);
+                memcpy((char*)&deductInfo[idxRow - 1].pCreditCard.CardNo, rs[(idxRow * cols) + 5],20);
+                deductInfo[idxRow - 1].Amount = atoi(rs[(idxRow * cols) + 6]);
+                memcpy((char*)&deductInfo[idxRow - 1].pCreditCard.StoreId, rs[(idxRow * cols) + 7],18);
+                memcpy((char*)&deductInfo[idxRow - 1].pCreditCard.ApprovalNo, rs[(idxRow * cols) + 8],9);
+                memcpy((char*)&deductInfo[idxRow - 1].pCreditCard.RRN, rs[(idxRow * cols) + 9],12);
+                memcpy((char*)&deductInfo[idxRow - 1].pCreditCard.ROC, rs[(idxRow * cols) + 10],12);
+                deductInfo[idxRow - 1].IsDonateInvoice = atoi(rs[(idxRow * cols) + 11]);
+                deductInfo[idxRow - 1].DeductResult = atoi(rs[(idxRow * cols) + 12]);
+                deductInfo[idxRow - 1].IsUpload = atoi(rs[(idxRow * cols) + 13]);
+                deductInfo[idxRow - 1].LineStatus = atoi(rs[(idxRow * cols) + 14]);
+                memcpy((char*)&deductInfo[idxRow - 1].ParkingStartTime, rs[(idxRow * cols) + 15],10);
+                deductInfo[idxRow - 1].RedeductTime = atoi(rs[(idxRow * cols) + 16]);
+                if(idxRow >= 128)
+                {
+                	rows = 128;
+                	break;
+                }
+            }
+        }
+
+        sqlite3_free_table(rs);
+        sqlite3_close(parkingDb);
+    }
+
+    return rows;
+}
+
+
+int UpdateParkingUpload(char* OccupancySN,int is_upload)
+{
+    int result = PASS;
+    char* errMsg = NULL;
+    char sqlStr[1024] = { 0 };
+
+    if (strcmp((char*)OccupancySN,"") == EQUAL) {
+        log_info("OccupancySN is NULL");
+        return;
+    }
+    char SN[37];
+    memset(SN,'\0',sizeof(SN));
+    memcpy((char*)SN,OccupancySN,36);
+    
+    sprintf(sqlStr, "update report_Parking_deduct set IsUpload = %d where OccupancySN = '%s'; ",
+            is_upload,
+            SN);
+
+    //log_info("%s",sqlStr);
+
+    if (sqlite3_open(PARKINGDEDUCT_FILE, &parkingDb))
+    {
+        result = FAIL;
+        log_info("Can't open parking database: %s", sqlite3_errmsg(parkingDb));
+        sqlite3_close(parkingDb);
+    } else
+    {
+        //log_info( "Local event record database open successfully.");
+        if (sqlite3_exec(parkingDb, sqlStr, 0, 0, &errMsg) != SQLITE_OK)
+        {
+            result = FAIL;
+            log_info("update parkingDB record error message: %s!", errMsg);
+        } else
+        {
+            //log_info( "update deduct record successfully");
+        }
+
+        sqlite3_close(parkingDb);
+    }
+
+    return result;
+}
+
+int UpdateParkingDeductInfo(int gunIndex, RecordTransactionInfo *deductInfo)
+{
+
+    int result = PASS;
+    char *errMsg = NULL;
+    char sqlStr[1024] = {0};
+    char OccupancySN[37] = {0};
+    memset(OccupancySN, '\0', 37);
+    strncpy(OccupancySN, (char*)&deductInfo->OccupancySN,36);
+    if (strcmp((char*)deductInfo->OccupancySN,"") == EQUAL) {
+        log_info("OccupancySN is NULL");
+        return;
+    }
+
+    sprintf(sqlStr, "update report_Parking_deduct set isUpload = %d ,amount = %.1f, isDeductResult = %d, RedeductTime = %d where OccupancySN = '%s'; ",
+                    (int)deductInfo->IsUpload,
+                    deductInfo->Amount,
+                    (int)deductInfo->DeductResult,
+                    deductInfo->RedeductTime,
+                    deductInfo->OccupancySN);
+
+    //  log_info("%s",sqlStr);
+
+    if (sqlite3_open(PARKINGDEDUCT_FILE, &parkingDb))
+    {
+        result = FAIL;
+        log_info( "Can't open deduct database: %s", sqlite3_errmsg(parkingDb));
+        sqlite3_close(parkingDb);
+    }
+    else
+    {
+        //log_info( "Local event record database open successfully.");
+        if (sqlite3_exec(parkingDb, sqlStr, 0, 0, &errMsg) != SQLITE_OK)
+        {
+            result = FAIL;
+            log_info( "update deduct record error message: %s!", errMsg);
+        }
+        else
+        {
+            //log_info( "update deduct record successfully");
+        }
+
+        sqlite3_close(parkingDb);
+    }
+
+    return result;
 }

+ 37 - 37
EVSE/Projects/DD360Tcci/Apps/DataBase/DataBase.h

@@ -1,37 +1,37 @@
-#ifndef _DATA_BASE_H_
-#define _DATA_BASE_H_
-
-#include "../Config.h"
-
-int DB_Open(void);
-int DB_Insert_Record(int gunIndex);
-int DB_Update_Operactive(uint8_t gunIndex, uint8_t IsAvailable);
-int DB_Get_Operactive(uint8_t gunIndex);
-int DB_Reboot_Record(void);
-
-//for Module_EventLog
-int CreateEventRecord(void);
-int InsertEventRecord(uint8_t *statusCode);
-
-int PowerDB_Open(void);
-int DB_Get_PowerConsumption(uint8_t gunIndex);
-int DB_Insert_PowerConsumption(uint8_t gunIndex, float energy);
-int DB_Update_PowerConsumption(uint8_t gunIndex, float energy);
-
-int DeductDB_Open(void);
-int InsertDeductInfo(int gunIndex, RecordTransactionInfo *deductInfo);
-int UpdateDeductInfoStatus(int gunIndex, RecordTransactionInfo *deductInfo);
-int DB_GetDeductInfo(int deductResult, int uploadState, int *gunIndex, RecordTransactionInfo *deductInfo);
-int DB_GetReDeductInfo(int *gunIndex, RecordTransactionInfo *deductInfo);
-int DB_GetReUploadDeduct(int *gunIndex, RecordTransactionInfo *deductInfo);
-int UpdateRedeuctBill(int Txid, float amount);
-int DB_GetMultiDeductInfo(int deductResult, int uploadState, int *gunIndex, RecordTransactionInfo *deductInfo);
-int DB_GetMultiReDeductInfo(int *gunIndex, RecordTransactionInfo *deductInfo);
-int DB_GetMultiReUploadDeduct(int *gunIndex, RecordTransactionInfo *deductInfo);
-int ParkingDB_Open(void);
-int InsertParkingDeductInfo(int gunIndex, RecordTransactionInfo *deductInfo);
-int DB_GetParkingDeductUpload(int *gunIndex, RecordTransactionInfo *deductInfo);
-int DB_GetParkingDeductResult(int *gunIndex, RecordTransactionInfo *deductInfo);
-int UpdateParkingUpload(char* OccupancySN,int is_upload);
-int UpdateParkingDeductInfo(int gunIndex, RecordTransactionInfo *deductInfo);
-#endif /* _DATA_BASE_H_ */
+#ifndef _DATA_BASE_H_
+#define _DATA_BASE_H_
+
+#include "../Config.h"
+
+int DB_Open(void);
+int DB_Insert_Record(int gunIndex);
+int DB_Update_Operactive(uint8_t gunIndex, uint8_t IsAvailable);
+int DB_Get_Operactive(uint8_t gunIndex);
+int DB_Reboot_Record(void);
+
+//for Module_EventLog
+int CreateEventRecord(void);
+int InsertEventRecord(uint8_t *statusCode);
+
+int PowerDB_Open(void);
+int DB_Get_PowerConsumption(uint8_t gunIndex);
+int DB_Insert_PowerConsumption(uint8_t gunIndex, float energy);
+int DB_Update_PowerConsumption(uint8_t gunIndex, float energy);
+
+int DeductDB_Open(void);
+int InsertDeductInfo(int gunIndex, RecordTransactionInfo *deductInfo);
+int UpdateDeductInfoStatus(int gunIndex, RecordTransactionInfo *deductInfo);
+int DB_GetDeductInfo(int deductResult, int uploadState, int *gunIndex, RecordTransactionInfo *deductInfo);
+int DB_GetReDeductInfo(int *gunIndex, RecordTransactionInfo *deductInfo);
+int DB_GetReUploadDeduct(int *gunIndex, RecordTransactionInfo *deductInfo);
+int UpdateRedeuctBill(int Txid, float amount);
+int DB_GetMultiDeductInfo(int deductResult, int uploadState, int *gunIndex, RecordTransactionInfo *deductInfo);
+int DB_GetMultiReDeductInfo(int *gunIndex, RecordTransactionInfo *deductInfo);
+int DB_GetMultiReUploadDeduct(int *gunIndex, RecordTransactionInfo *deductInfo);
+int ParkingDB_Open(void);
+int InsertParkingDeductInfo(int gunIndex, RecordTransactionInfo *deductInfo);
+int DB_GetParkingDeductUpload(int *gunIndex, RecordTransactionInfo *deductInfo);
+int DB_GetParkingDeductResult(int *gunIndex, RecordTransactionInfo *deductInfo);
+int UpdateParkingUpload(char* OccupancySN,int is_upload);
+int UpdateParkingDeductInfo(int gunIndex, RecordTransactionInfo *deductInfo);
+#endif /* _DATA_BASE_H_ */

+ 628 - 628
EVSE/Projects/DD360Tcci/Apps/Define/define.c

@@ -1,628 +1,628 @@
-#include <stdio.h>
-#include <stdlib.h>
-#include <stdint.h>
-
-#include "define.h"
-
-//------------------------------------------------------------------------------
-char Currency[54][4]=
-{
-"AED", // - Emirati Dirham
-"ARS", // - Argentine Peso
-"AUD", // - Australian Dollar
-"BGN", // - Bulgarian Lev
-"BHD", // - Bahraini Dinar
-"BND", // - Bruneian Dollar
-"BRL", // - Brazilian Real
-"BWP", // - Botswana Pula
-"CAD", // - Canadian Dollar
-"CHF", // - Swiss Franc
-"CLP", // - Chilean Peso
-"CNY", // - Chinese Yuan Renminbi
-"COP", // - Colombian Peso
-"CZK", // - Czech Koruna
-"DKK", // - Danish Krone
-"EUR", // - Euro
-"GBP", // - British Pound
-"HKD", // - Hong Kong Dollar
-"HRK", // - Croatian Kuna
-"HUF", // - Hungarian Forint
-"IDR", // - Indonesian Rupiah
-"ILS", // - Israeli Shekel
-"INR", // - Indian Rupee
-"IRR", // - Iranian Rial
-"ISK", // - Icelandic Krona
-"JPY", // - Japanese Yen
-"KRW", // - South Korean Won
-"KWD", // - Kuwaiti Dinar
-"KZT", // - Kazakhstani Tenge
-"LKR", // - Sri Lankan Rupee
-"LYD", // - Libyan Dinar
-"MUR", // - Mauritian Rupee
-"MXN", // - Mexican Peso
-"MYR", // - Malaysian Ringgit
-"NOK", // - Norwegian Krone
-"NPR", // - Nepalese Rupee
-"NZD", // - New Zealand Dollar
-"OMR", // - Omani Rial
-"PHP", // - Philippine Peso
-"PKR", // - Pakistani Rupee
-"PLN", // - Polish Zloty
-"QAR", // - Qatari Riyal
-"RON", // - Romanian New Leu
-"RUB", // - Russian Ruble
-"SAR", // - Saudi Arabian Riyal
-"SEK", // - Swedish Krona
-"SGD", // - Singapore Dollar
-"THB", // - Thai Baht
-"TRY", // - Turkish Lira
-"TTD", // - Trinidadian Dollar
-"TWD", // - Taiwan New Dollar
-"USD", // - US Dollar
-"VEF", // - Venezuelan Bolivar
-"ZAR" // - South African Rand
-};
-
-char FaultStatusCode[40][6]=
-{
-"011001", //CHAdeMO output fuse blew
-"011002", //CCS output fuse blew
-"011003", //GB output fuse blew
-"011004", //RCD/CCID self-test fail
-"011005", //AC input contactor 1 welding
-"011006", //AC input contactor 1 driving fault
-"011007", //AC input contactor 2 welding
-"011008", //AC input contactor 2 driving fault
-"011009", //AC output relay welding
-"011010", //AC output relay driving fault
-"011011", //CHAdeMO output relay welding
-"011012", //CHAdeMO output relay driving fault
-"011013", //CCS output relay welding
-"011014", //CCS output relay driving fault
-"011015", //GB output relay welding
-"011016", //GB output relay driving fault
-"011017", //AC connector temperature sensor broken
-"011018", //CHAdeMO connector temperature sensor broken
-"011019", //CCS connector temperature sensor broken
-"011020", //GB connector temperature sensor broken
-"011021", //WiFi module broken
-"011022", //3G/4G module broken
-"011023", //Aux. power module broken
-"011024", //Relay control module /smart box broken
-"011025", //CHAdeMO connector lock fail
-"011026", //GB connector lock fail
-"011027", //AC connector lock fail
-"011028", //CHAdeMO module broken
-"011029", //CCS module broken
-"011030", //GBT module broken
-"011031", //PSU module broken
-"011032", //RCD/CCID module broken
-"011033", //Maximum Output Current setup error
-"011034", //Shutter fault
-"011035", //Ble module broken
-"011036", //Rotary switch fault
-"011037", //CCS liquid chiller water level fault
-"011038", //Chiller temperature sensor broken
-"011039", //Parallel relay welding
-"011040"  //Parallel output relay driving fault
-};
-
-char AlarmStatusCode[160][6]=
-{
-"012200", //System L1 input OVP
-"012201", //System L2 input OVP
-"012202", //System L3 input OVP
-"012203", //System L1 input UVP
-"012204", //System L2 input UVP
-"012205", //System L3 input UVP
-"012206", //PSU L1 input OVP
-"012207", //PSU L2 input OVP
-"012208", //PSU L3 input OVP
-"012209", //PSU L1 input UVP
-"012210", //PSU L2 input UVP
-"012211", //PSU L3 input UVP
-"012212", //System L1 input drop
-"012213", //System L2 input drop
-"012214", //System L3 input drop
-"012215", //System AC output OVP
-"012216", //System AC output OCP L1
-"012217", //System CHAdeMO output OVP
-"012218", //System CHAdeMO output OCP
-"012219", //System CCS output OVP
-"012220", //System CCS output OCP
-"012221", //System GB output OVP
-"012222", //System GB output OCP
-"012223", //System ambient/inlet OTP
-"012224", //System critical point OTP
-"012225", //PSU ambient/inlet OTP
-"012226", //PSU critical point OTP
-"012227", //Aux. power module OTP
-"012228", //Relay board/smart box OTP
-"012229", //CHAdeMO connector OTP
-"012230", //CCS connector OTP
-"012231", //GB connector OTP
-"012232", //AC connector OTP
-"012233", //RCD/CCID trip
-"012234", //CHAdeMO GFD trip
-"012235", //CCS GFD trip
-"012236", //GB GFD trip
-"012237", //SPD trip
-"012238", //Main power breaker trip
-"012239", //Aux. power breaker trip
-"012240", //PSU communication fail
-"012241", //WiFi module communication fail
-"012242", //3G/4G module communication fail
-"012243", //RFID module communication fail
-"012244", //Bluetooth module communication fail
-"012245", //LCM module communication fail
-"012246", //Aux. power module communication fail
-"012247", //Relay control boaed/smart box communication fail
-"012248", //CCS module communication fail
-"012249", //CHAdeMO module communication fail
-"012250", //GBT module communication fail
-"012251", //Emergency stop
-"012252", //Door open
-"012253", //System fan decay
-"012254", //Fail to create share memory
-"012255", //CSU initialization failed
-"012256", //AC Ground Fault
-"012257", //MCU self-test Fault
-"012258", //Relay self-test Fault
-"012259", //CHAdeMO groundfault detection timeout (GFD)
-"012260", //CCS groundfault detection timeout (GFD)
-"012261", //GB groundfault detection timeout (GFD)
-"012262", //Circuit Short L1
-"012263", // PSU Duplicate ID
-"012264", // PSU Output Short Circuit
-"012265", // PSU Discharge Abnormal
-"012266", // PSU Dc Side ShutDown
-"012267", // PSU Failure Alarm
-"012268", // PSU Protection Alarm
-"012269", // PSU FanFailure Alarm
-"012270", // PSU Input UVP
-"012271", // PSU Input OVP
-"012272", // PSU WalkIn State
-"012273", // PSU Power Limited State
-"012274", // PSU Id Repeat
-"012275", // PSU Severe Uneven Current
-"012276", // PSU Three Phase Input Inadequate
-"012277", // PSU Three Phase Onput Imbalance
-"012278", // PSU Ffc Side ShutDown
-"012279", // NO PSU Resource
-"012280", // Self test Failed due to communication of Relayboard failure
-"012281", // Self test Failed due to communication of Fanboard failure
-"012282", // Self test Failed due to communication of Primary failure
-"012283", // Self test Failed due to communication of Chademoboard failure
-"012284", // Self test Failed due to communication of CCSboard failure
-"012285", // Self test Failed due to AC Contact failure
-"012286", // Self test Failed due to communication of PSU failure
-"012287", // Self test Failed due to Model name is none match
-"012288", // CCS output UVP
-"012289", // Chademo output UVP
-"012290", // GBT output UVP
-"012291", // Self test Failed due to communication of GBTboard failure
-"012292", // Self test Failed due to communication of AC failure
-"012293", // Self test Failed due to communication of Ledboard failure
-"012294", // Ac input OVP
-"012295", // Ac input UVP
-"012296", // CHAdeMO groundfault detection - warning
-"012297", // CCS groundfault detection - warning
-"012298", // GB groundfault detection - warning
-"012299", // System AC output OCP L2
-"012300", // System AC output OCP L3
-"012301", // Circuit Short L2
-"012302", // Circuit Short L3
-"012303", // CCS liquid chiller water level warning
-"012304", // connection disconnected from power cabinet
-"012305", // Meter communication timeout
-"012306", // The dip switch of the PSU may be incorrect
-"012307", // Psu Fuse Burn-Out
-"012308", // Psu Pfc And Dcdc Communication Fault
-"012309", // Psu Bus Voltage Unbalance
-"012310", // Psu Bus Over Voltage
-"012311", // Psu Bus Voltage Abnormal
-"012312", // Psu Bus Under Voltage
-"012313", // Psu Input Phase Loss
-"012314", // Psu Fan Full Speed
-"012315", // Psu Temperature Power Limit
-"012316", // Psu Ac Power Limit
-"012317", // Psu Dcdc Eeprom Fault
-"012318", // Psu Pfc Eeprom Fault
-"012319", // Psu Dcdc Over Voltage
-"012320", // System CHAdeMO output UCP
-"012321", // System CCS output UCP
-"012322", // System GBT output UCP
-"012323", // System Chiller output OTP
-"012324", // Connector 1 detects abnormal voltage on the output line
-"012325", // Connector 2 detects abnormal voltage on the output line
-"012326", // System task is lost
-"012327",   // DC input ovp
-"012328",   // DC input uvp
-"012329",   // Psu Can Communication Fault
-"012330",   // Psu Dc to Dc OTP
-"012331",   // Psu Dc to Dc OVP
-"012332",   // Chiller Tube OTP
-"012333",   // reserved
-"012334",   // reserved
-"012335",   // reserved
-"012336",   // reserved
-"012337",   // reserved
-"012338",   // reserved
-"012339",   // reserved
-"012340",   // reserved
-"012341",   // reserved
-"012342",   // reserved
-"012343",   // reserved
-"012344",   // AC: Meter IC communication timeout
-"012345",   // AC: Pilot negative error
-"012346",   // Psu Communication error with CSU
-"012347",   // AC: Local power sharing communication error (Slave disconnect from Master)
-"012348",   // reserved
-"012349",   // reserved
-"012350",   // reserved
-"012351",   // reserved
-"012352",   // reserved
-"012353",   // reserved
-"012354",   // reserved
-"012355",   // reserved
-"012356",   // reserved
-"012357",   // reserved
-"012358",   // reserved
-"012359",   // reserved
-};
-
-char InfoStatusCode[384][6]=
-{
-//Information comes from EVSE
-"013600", //Normal stop charging by user
-"013601", //Charging Time's up
-"013602", //Replace system air filter
-"013603", //Reach to CHAdeMO max. plugging times.
-"013604", //Reach to CCS max. plugging times.
-"013605", //Reach to GB max. plugging times.
-"013606", //Reach to AC max. plugging times.
-"013607", //CSU fimrware update fail
-"013608", //CHAdeMO Module fimrware update fail
-"013609", //CCS Module fimrware update fail
-"013610", //GB Module fimrware update fail
-"013611", //Aux. power module fimrware update fail
-"013612", //Relay control module fimrware update fail
-"013613", //LCM module fimrware update fail
-"013614", //Bluetooth module fimrware update fail
-"013615", //WiFi module fimrware update fail
-"013616", //3G/4G module fimrware update fail
-"013617", //SMR fimrware update fail
-"013618", //RFID module fimrware update fail
-"013619", //configured by USB flash drive
-"013620", //configured by backend
-"013621", //configured by webpage
-"013622", //disconnected from Internet through Ethernet
-"013623", //disconnected from Internet through WiFi
-"013624", //disconnected from Internet through 3G/4G
-"013625", //disconnected from AP through WiFi
-"013626", //disconnected from APN through 3G/4G
-"013627", //WiFi disabled (separated charger only)
-"013628", //4G disabled (separated charger only)
-"013629", //Reserved
-"013630", //Reserved
-"013631", //Reserved
-//Information comes from EV
-"023700", //CHAdeMO EV communication Fail
-"023701", //CCS EV communication Fail
-"023702", //GB EV communication Fail
-"023703", //AC: pilot fault
-"023704", //CHAdeMO: battery malfunction
-"023705", //CHAdeMO: no charging permission
-"023706", //CHAdeMO: battery incompatibility
-"023707", //CHAdeMO: battery OVP
-"023708", //CHAdeMO: battery UVP
-"023709", //CHAdeMO: battery OTP
-"023710", //CHAdeMO: battery current difference
-"023711", //CHAdeMO: battery voltage difference
-"023712", //CHAdeMO: shift position
-"023713", //CHAdeMO: battery other fault
-"023714", //CHAdeMO: charging system error
-"023715", //CHAdeMO: EV normal stop
-"023716", //CHAdeMO: connector temperature sensor broken
-"023717", //CHAdeMO: connector lock fail
-"023718", //CHAdeMO: D1 ON No Receive
-"023719", //CHAdeMO: BMS K to J Timeout
-"023720", //CHAdeMO: BMS Charge Allow Timeout
-"023721", //CHAdeMO: Wait GroundFault Timeout
-"023722", //CHAdeMO: BMS EV Relay Timeout
-"023723", //CHAdeMO: BMS Request Current Timeout
-"023724", //CHAdeMO: BMS K to J OFF Timeout
-"023725", //CHAdeMO: BMS EV Relay OFF Timeout
-"023726", //CHAdeMO: ADC More Than 10V
-"023727", //CHAdeMO: ADC More Than 20V
-"023728", //CHAdeMO: BMS Charge Before Stop
-"023729", //CHAdeMO: Charger Get Normal Stop
-"023730", //CHAdeMO: Charger Get Emergency Stop
-"023731", //CHAdeMO: Isolation Result Fail
-"023732", //CHAdeMO: Miss Link With MotherBoard
-"023733", //CHAdeMO: Output Voltage More Than Limit
-"023734", //CHAdeMO: Request Current More Than Limit
-"023735", //CHAdeMO: Re Cap BMS Eqr Current Exceed
-"023736", //CHAdeMO: Charge Remain Count Down
-"023737", //CCS:CCS_EVCC_EVErrorCode_FAILED_RESSTemperatureInhibit
-"023738", //CCS:CCS_EVCC_EVErrorCode_FAILED_EVShiftPosition
-"023739", //CCS:CCS_EVCC_EVErrorCode_FAILED_ChargerConnectorLockFault
-"023740", //CCS:CCS_EVCC_EVErrorCode_FAILED_EVRESSMalfunction
-"023741", //CCS:CCS_EVCC_EVErrorCode_FAILED_ChargingCurrentdifferential
-"023742", //CCS:CCS_EVCC_EVErrorCode_FAILED_ChargingVoltageOutOfRange
-"023743", //CCS:CCS_EVCC_EVErrorCode_FAILED_ChargingSystemIncompatibility
-"023744", //CCS:CCS_EVCC_EVErrorCode_FAILED_EmergencyEvent
-"023745", //CCS:CCS_EVCC_EVErrorCode_FAILED_Breaker
-"023746", //CCS:CCS_EVCC_EVErrorCode_FAILED_NoData
-"023747", //CCS:CCS_EVCC_EVErrorCode_FAILED_reserved_by_DIN_A
-"023748", //CCS:CCS_EVCC_EVErrorCode_FAILED_reserved_by_DIN_B
-"023749", //CCS:CCS_EVCC_EVErrorCode_FAILED_reserved_by_DIN_C
-"023750", //CCS:CCS_EVCC_EVErrorCode_FAILED_reserved_by_ISO_1
-"023751", //CCS:CCS_EVCC_EVErrorCode_FAILED_reserved_by_ISO_2
-"023752", //CCS:CCS_EVCC_EVErrorCode_FAILED_reserved_by_ISO_3
-"023753", //CCS:CCS_EVCC_EVErrorCode_FAILED_reserved_by_OEM_1
-"023754", //CCS:CCS_EVCC_EVErrorCode_FAILED_reserved_by_OEM_2
-"023755", //CCS:CCS_EVCC_EVErrorCode_FAILED_reserved_by_OEM_3
-"023756", //CCS:CCS_EVCC_EVErrorCode_FAILED_reserved_by_OEM_4
-"023757", //CCS:CCS_EVCC_EVErrorCode_FAILED_reserved_by_OEM_5
-"023758", //CCS:CCS_SECC_ResponseCode_FAILED_SequenceError
-"023759", //CCS:CCS_SECC_ResponseCode_FAILED_SignatureError
-"023760", //CCS:CCS_SECC_ResponseCode_FAILED_UnknownSession
-"023761", //CCS:CCS_SECC_ResponseCode_FAILED_ServiceIDInvalid
-"023762", //CCS:CCS_SECC_ResponseCode_FAILED_Payment SelectionInvalid
-"023763", //CCS:CCS_SECC_ResponseCode_FAILED_IdentificationSelectionInvalid
-"023764", //CCS:CCS_SECC_ResponseCode_FAILED_ServiceSelectionInvalid
-"023765", //CCS:CCS_SECC_ResponseCode_FAILED_CertificateExpired
-"023766", //CCS:CCS_SECC_ResponseCode_FAILED_CertificateNotYetValid
-"023767", //CCS:CCS_SECC_ResponseCode_FAILED_CertificateRevoked
-"023768", //CCS:CCS_SECC_ResponseCode_FAILED_NoCertificateAvailable
-"023769", //CCS:CCS_SECC_ResponseCode_FAILED_CertChainError
-"023770", //CCS:CCS_SECC_ResponseCode_FAILED_CertValidationError
-"023771", //CCS:CCS_SECC_ResponseCode_FAILED_CertVerificationError
-"023772", //CCS:CCS_SECC_ResponseCode_FAILED_ContractCanceled
-"023773", //CCS:CCS_SECC_ResponseCode_FAILED_ChallengeInvalid
-"023774", //CCS:CCS_SECC_ResponseCode_FAILED_WrongEnergyTransferMode
-"023775", //CCS:CCS_SECC_ResponseCode_FAILED_WrongChargeParameter
-"023776", //CCS:CCS_SECC_ResponseCode_FAILED_ChargingProfileInvalid
-"023777", //CCS:CCS_SECC_ResponseCode_FAILED_TariffSelectionInvalid
-"023778", //CCS:CCS_SECC_ResponseCode_FAILED_EVSEPresentVoltageToLow
-"023779", //CCS:CCS_SECC_ResponseCode_FAILED_PowerDeliveryNotApplied
-"023780", //CCS:CCS_SECC_ResponseCode_FAILED_MeteringSignatureNotValid
-"023781", //CCS:CCS_SECC_ResponseCode_FAILED_NoChargeServiceSelected
-"023782", //CCS:CCS_SECC_ResponseCode_FAILED_ContactorError
-"023783", //CCS:CCS_SECC_ResponseCode_FAILED_CertificateNotAllowedAtThisEVSE
-"023784", //CCS:CCS_SECC_ResponseCode_FAILED_GAChargeStop
-"023785", //CCS:CCS_SECC_ResponseCode_FAILED_AlignmentError
-"023786", //CCS:CCS_SECC_ResponseCode_FAILED_ACDError
-"023787", //CCS:CCS_SECC_ResponseCode_FAILED_AssociationError
-"023788", //CCS:CCS_SECC_ResponseCode_FAILED_EVSEChargeAbort
-"023789", //CCS:CCS_SECC_ResponseCode_FAILED_NoSupportedApp-Protocol-Protocol
-"023790", //CCS:CCS_SECC_ResponseCode_FAILED_ContractNotAccepted
-"023791", //CCS:CCS_SECC_ResponseCode_FAILED_MOUnknown
-"023792", //CCS:CCS_SECC_ResponseCode_FAILED_OEM_Prov_CertificateRevoke
-"023793", //CCS:CCS_SECC_ResponseCode_FAILED_OEM_SubCA1_CertificateRevoked
-"023794", //CCS:CCS_SECC_ResponseCode_FAILED_OEM_SubCA2_CertificateRevoked
-"023795", //CCS:CCS_SECC_ResponseCode_FAILED_OEM_RootCA_CertificateRevoked
-"023796", //CCS:CCS_SECC_ResponseCode_FAILED_MO_Prov_CertificateRevoked
-"023797", //CCS:CCS_SECC_ResponseCode_FAILED_MO_SubCA1_CertificateRevoked
-"023798", //CCS:CCS_SECC_ResponseCode_FAILED_MO_SubCA2_CertificateRevoked
-"023799", //CCS:CCS_SECC_ResponseCode_FAILED_MO_RootCA_CertificateRevoked
-"023800", //CCS:CCS_SECC_ResponseCode_FAILED_CPS_Prov_CertificateRevoked
-"023801", //CCS:CCS_SECC_ResponseCode_FAILED_CPS_SubCA1_CertificateRevoked
-"023802", //CCS:CCS_SECC_ResponseCode_FAILED_CPS_SubCA2_CertificateRevoked
-"023803", //CCS:CCS_SECC_ResponseCode_FAILED_CPS_RootCA_CertificateRevoked
-"023804", //CCS:CCS_SECC_ResponseCode_FAILED_reserved_1
-"023805", //CCS:CCS_SECC_ResponseCode_FAILED_reserved_2
-"023806", //CCS:CCS_SECC_ResponseCode_FAILED_reserved_3
-"023807", //CCS:CCS_SECC_ResponseCode_FAILED_reserved_4
-"023808", //CCS:CCS_SECC_ResponseCode_FAILED_reserved_5
-"023809", //CCS:CCS_SECC_TIMEOUT_SLAC_TT_EVSE_SLAC_init
-"023810", //CCS:CCS_SECC_TIMEOUT_SLAC_TP_match_response
-"023811", //CCS:CCS_SECC_TIMEOUT_CM_START_ATTEN_CHAR_IND
-"023812", //CCS:CCS_SECC_TIMEOUT_SLAC_TT_EVSE_match_MNBC
-"023813", //CCS:CCS_SECC_TIMEOUT_SLAC_TP_EVSE_avg_atten_calc
-"023814", //CCS:CCS_SECC_TIMEOUT_SLAC_CM_ATTEN_CHAR_RSP
-"023815", //CCS:CCS_SECC_TIMEOUT_SLAC_CM_VALIDATE_REQ_1ST__CM_SLAC_MATCH_REQ
-"023816", //CCS:CCS_SECC_TIMEOUT_SLAC_TT_EVSE_assoc_session
-"023817", //CCS:CCS_SECC_TIMEOUT_SLAC_TT_EVSE_vald_toggle
-"023818", //CCS:CCS_SECC_TIMEOUT_SLAC_CM_MNBC_SOUND_IND
-"023819", //CCS:CCS_SECC_TIMEOUT_SLAC_CM_VALIDATE_REQ_2ND__CM_SLAC_MATCH_REQ
-"023820", //CCS:CCS_SECC_TIMEOUT_SLAC_reserved_3
-"023821", //CCS:CCS_SECC_TIMEOUT_SLAC_reserved_4
-"023822", //CCS:CCS_SECC_TIMEOUT_SLAC_reserved_5
-"023823", //CCS:CCS_SECC_TIMEOUT_SLACC_SDP_UDP_TT_match_join
-"023824", //CCS:CCS_SECC_TIMEOUT_SLACC_SDP_TCP_TT_match_join
-"023825", //CCS:CCS_SECC_TIMEOUT_SLACC_SDP_TP_amp_map_exchange
-"023826", //CCS:CCS_SECC_TIMEOUT_SLACC_SDP_TP_link_ready_notification
-"023827", //CCS:CCS_SECC_TIMEOUT_SLACC_SDP_reserved_1
-"023828", //CCS:CCS_SECC_TIMEOUT_SLACC_SDP_reserved_2
-"023829", //CCS:CCS_SECC_TIMEOUT_SLACC_SDP_reserved_3
-"023830", //CCS:CCS_SECC_TIMEOUT_SLACC_SDP_reserved_4
-"023831", //CCS:CCS_SECC_TIMEOUT_SLACC_SDP_reserved_5
-"023832", //CCS:CCS_SECC_TIMEOUT_V2G_Msg_Performance_Time_SupportedAppProtocolRes
-"023833", //CCS:CCS_SECC_TIMEOUT_V2G_Msg_Performance_Time_SessionSetupRes
-"023834", //CCS:CCS_SECC_TIMEOUT_V2G_Msg_Performance_Time_ServiceDiscoveryRes
-"023835", //CCS:CCS_SECC_TIMEOUT_V2G_Msg_Performance_Time_ServicePaymentSelectionRes
-"023836", //CCS:CCS_SECC_TIMEOUT_V2G_Msg_Performance_Time_ContractAuthenticationRes
-"023837", //CCS:CCS_SECC_TIMEOUT_V2G_Msg_Performance_Time_ChargeParameterDiscoveryRes
-"023838", //CCS:CCS_SECC_TIMEOUT_V2G_Msg_Performance_Time_PowerDeliveryRes
-"023839", //CCS:CCS_SECC_TIMEOUT_V2G_Msg_Performance_Time_CableCheckRes
-"023840", //CCS:CCS_SECC_TIMEOUT_V2G_Msg_Performance_Time_PreChargeRes
-"023841", //CCS:CCS_SECC_TIMEOUT_V2G_Msg_Performance_Time_CurrentDemandRes
-"023842", //CCS:CCS_SECC_TIMEOUT_V2G_Msg_Performance_Time_WeldingDetectionRes
-"023843", //CCS:CCS_SECC_TIMEOUT_V2G_Msg_Performance_Time_SessionStopRes
-"023844", //CCS:CCS_SECC_TIMEOUT_V2G_Sequence_Time
-"023845", //CCS:CCS_SECC_TIMEOUT_V2G_ReadyToCharge_Performance_Time
-"023846", //CCS:CCS_SECC_TIMEOUT_V2G_CommunicationSetup_Performance_Time
-"023847", //CCS:CCS_SECC_TIMEOUT_V2G_CableCheck_Performance_Time
-"023848", //CCS:CCS_SECC_TIMEOUT_V2G_CPState_Detection_Time
-"023849", //CCS:CCS_SECC_TIMEOUT_V2G_CPOscillator_Retain_Time
-"023850", //CCS:CCS_SECC_TIMEOUT_V2G_PreCharge_Performace_Time
-"023851", //CCS:CCS_SECC_TIMEOUT_V2G_reserved_2
-"023852", //CCS:CCS_SECC_TIMEOUT_V2G_reserved_3
-"023853", //CCS:CCS_SECC_TIMEOUT_V2G_reserved_4
-"023854", //CCS:CCS_SECC_TIMEOUT_V2G_reserved_5
-"023855", //CCS:CCS_CAN_TIMEOUT_TP_GET_EV_TARGET_INFO
-"023856", //CCS:CCS_CAN_TIMEOUT_TT_GET_EV_TARGET_INFO
-"023857", //CCS:CCS_CAN_TIMEOUT_TP_GET_EV_BATTERY_INFO
-"023858", //CCS:CCS_CAN_TIMEOUT_TT_GET_EV_BATTERY_INFO
-"023859", //CCS:CCS_CAN_TIMEOUT_TP_EV_STOP_EVENT
-"023860", //CCS:CCS_CAN_TIMEOUT_TT_EV_STOP_EVENT
-"023861", //CCS:CCS_CAN_TIMEOUT_TP_EVSE_STOP_EVENT
-"023862", //CCS:CCS_CAN_TIMEOUT_TT_EVSE_STOP_EVENT
-"023863", //CCS:CCS_CAN_TIMEOUT_TP_GET_MISC_INFO
-"023864", //CCS:CCS_CAN_TIMEOUT_TT_GET_MISC_INFO
-"023865", //CCS:CCS_CAN_TIMEOUT_TP_DOWNLOAD_REQUEST
-"023866", //CCS:CCS_CAN_TIMEOUT_TT_DOWNLOAD_REQUEST
-"023867", //CCS:CCS_CAN_TIMEOUT_TP_START_BLOCK_TRANSFER
-"023868", //CCS:CCS_CAN_TIMEOUT_TT_START_BLOCK_TRANSFER
-"023869", //CCS:CCS_CAN_TIMEOUT_TP_DATA_TRANSFER
-"023870", //CCS:CCS_CAN_TIMEOUT_TT_DATA_TRANSFER
-"023871", //CCS:CCS_CAN_TIMEOUT_TP_DOWNLOAD_FINISH
-"023872", //CCS:CCS_CAN_TIMEOUT_TT_DOWNLOAD_FINISH
-"023873", //CCS:CCS_CAN_TIMEOUT_TP_ISOLATION_STATUS
-"023874", //CCS:CCS_CAN_TIMEOUT_TT_ISOLATION_STATUS
-"023875", //CCS:CCS_CAN_TIMEOUT_TP_CONNECTOR_INFO
-"023876", //CCS:CCS_CAN_TIMEOUT_TT_CONNECTOR_INFO
-"023877", //CCS:CCS_CAN_TIMEOUT_TT_RTC_INFO
-"023878", //CCS:CCS_CAN_TIMEOUT_TP_RTC_INFO
-"023879", //CCS:CCS_CAN_TIMEOUT_TP_EVSE_PRECHARGE_INFO
-"023880", //CCS:CCS_CAN_TIMEOUT_TT_EVSE_PRECHARGE_INFO
-"023881", //CCS:CCS_CAN_TIMEOUT_MSG_Sequence
-"023882", //CCS:CCS_CAN_MSG_Unrecognized_CMD_ID
-"023883", //CCS:CCS_SECC_DIN_Msg_Decode_Error
-"023884", //CCS:CCS_SECC_DIN_Msg_Encode_Error
-"023885", //CCS:CCS_SECC_ISO1_Msg_Decode_Error
-"023886", //CCS:CCS_SECC_ISO1_Msg_Encode_Error
-"023887", //CCS:CCS_SECC_ISO2_Msg_Decode_Error
-"023888", //CCS:CCS_SECC_ISO2_Msg_Encode_Error
-"023889", //CCS:CCS_SECC_CP_STATUS_Error
-"023890", //CCS:CCS_SECC_Unexpected_60V_Before_Charing_Error
-"023891", //CCS:CCS_SECC_Not_Ready_For_Charging
-"023892", //CCS:CCS_SECCC_TIMEOUT_QCA7000_COMM (The firmware code of QCA7000 may not be installed, yet)
-"023893", //CCS:CCS_SECC_FAIL_QCA7000_SETKEY
-"023894", //Reserved
-"023895", //Reserved
-"023896", //Reserved
-"023897", //Reserved
-"023898", //Reserved
-"023899", //Reserved
-"023900", //GBT: ERROR_CODE_GBT_LOS_CC1
-"023901", //GBT: ERROR_CODE_GBT_CONNECTOR_LOCK_FAIL
-"023902", //GBT: ERROR_CODE_GBT_BATTERY_INCOMPATIBLE
-"023903", //GBT: ERROR_CODE_GBT_BMS_BROAA_TIMEOUT
-"023904", //GBT: ERROR_CODE_GBT_CSU_PRECHARGE_TIMEOUT
-"023905", //GBT: ERROR_CODE_GBT_BMS_PRESENT_VOLTAGE_FAULT
-"023906", //GBT: ERROR_CODE_GBT_BMS_VOLTAGE_OVER_RANGE
-"023907", //GBT: ERROR_CODE_GBT_BSM_CHARGE_ALLOW_00_10MIN_COUUNTDONE
-"023908", //GBT: ERROR_CODE_GBT_WAIT_GROUNDFAULT_TIMEOUT
-"023909", //GBT: ERROR_CODE_GBT_ADC_MORE_THAN_10V
-"023910", //GBT: ERROR_CODE_GBT_ADC_MORE_THAN_60V
-"023911", //GBT: ERROR_CODE_GBT_CHARGER_GET_NORMAL_STOP_CMD
-"023912", //GBT: ERROR_CODE_GBT_CHARGER_GET_EMERGENCY_STOP_CMD
-"023913", //GBT: ERROR_CODE_GBT_ISOLATION_RESULT_FAIL
-"023914", //GBT: ERROR_CODE_GBT_MOTHER_BOARD_MISS_LINK
-"023915", //GBT: ERROR_CODE_GBT_OUTPUT_VOLTAGE_MORE_THAN_LIMIT
-"023916", //GBT: ERROR_CODE_GBT_REQ_CURRENT_MORE_THAN_LIMIT
-"023917", //GBT: ERROR_CODE_GBT_OUTPUT_VOLTAGE_MORE_THAN_10_PERCENT
-"023918", //GBT: ERROR_CODE_GBT_OUTPUT_VOLTAGE_DIFF_BCS_5_PERCENT
-"023919", //GBT: ERROR_CODE_GBT_STOP_ADC_MORE_THAN_10V
-"023920", // Reserved
-"023921", // Reserved
-"023922", // Reserved
-"023923", // Reserved
-"023924", // Reserved
-"023925", // Reserved
-"023926", // Reserved
-"023927", // Reserved
-"023928", // Reserved
-"023929", // Reserved
-"023930", //GBT: ERROR_CODE_CEM_BHM_TIMEOUT
-"023931", //GBT: ERROR_CODE_CEM_BRM_TIMEOUT
-"023932", //GBT: ERROR_CODE_CEM_BCP_TIMEOUT
-"023933", //GBT: ERROR_CODE_CEM_BRO_TIMEOUT
-"023934", //GBT: ERROR_CODE_CEM_BCL_TIMEOUT
-"023935", //GBT: ERROR_CODE_CEM_BCS_TIMEOUT
-"023936", //GBT: ERROR_CODE_CEM_BSM_TIMEOUT
-"023937", //GBT: ERROR_CODE_CEM_BST_TIMEOUT
-"023938", //GBT: ERROR_CODE_CEM_BSD_TIMEOUT
-"023939", //GBT: ERROR_CODE_CEM_BEM_OTHER_TIMEOUT
-"023940", //GBT: ERROR_CODE_BEM_CRM_TIMEOUT
-"023941", //GBT: ERROR_CODE_BEM_CRMAA_TIMEOUT
-"023942", //GBT: ERROR_CODE_BEM_CTS_CML_TIMEOUT
-"023943", //GBT: ERROR_CODE_BEM_CRO_TIMEOUT
-"023944", //GBT: ERROR_CODE_BEM_CCS_TIMEOUT
-"023945", //GBT: ERROR_CODE_BEM_CST_TIMEOUT
-"023946", //GBT: ERROR_CODE_BEM_CSD_TIMEOUT
-"023947", //GBT: ERROR_CODE_BEM_BEM_OTHER_TIMEOUT
-"023948", // Reserved
-"023949", // Reserved
-"023950", //GBT: ERROR_CODE_BST_SOC_GOAL
-"023951", //GBT: ERROR_CODE_BST_TOTAL_VOLTAGE_GOAL
-"023952", //GBT: ERROR_CODE_BST_CELL_VOLTAGE_GOAL
-"023953", //GBT: ERROR_CODE_BST_GET_CST
-"023954", //GBT: ERROR_CODE_BST_ISOLATION
-"023955", //GBT: ERROR_CODE_BST_OUTPUT_CONNECTOR_OTP
-"023956", //GBT: ERROR_CODE_BST_COMPONENT
-"023957", //GBT: ERROR_CODE_BST_CHARGE_CONNECTOR
-"023958", //GBT: ERROR_CODE_BST_OTP
-"023959", //GBT: ERROR_CODE_BST_OTHER
-"023960", //GBT: ERROR_CODE_BST_HIGH_V
-"023961", //GBT: ERROR_CODE_BST_CC2
-"023962", //GBT: ERROR_CODE_BST_CURRENT
-"023963", //GBT: ERROR_CODE_BST_VOLTAGE
-"023964", //GBT: ERROR_CODE_GET_BST_NO_REASON
-"023965", // Reserved
-"023966", // Reserved
-"023967", // Reserved
-"023968", // Reserved
-"023969", // Reserved
-"023970", //GBT: ERROR_CODE_BSM_CELL_OVER_VOLTAGE
-"023971", //GBT: ERROR_CODE_BSM_CELL_UNDER_VOLTAGE
-"023972", //GBT: ERROR_CODE_BSM_OVER_SOC
-"023973", //GBT: ERROR_CODE_BSM_UNDER_SOC
-"023974", //GBT: ERROR_CODE_BSM_CURRENT
-"023975", //GBT: ERROR_CODE_BSM_TEMPERATURE
-"023976", //GBT: ERROR_CODE_BSM_ISOLATE
-"023977", //GBT: ERROR_CODE_BSM_OUTPUT_CONNECTOR
-"023978", // Reserved
-"023979", // EV full charging
-"023980", // ERROR_CODE_CHADEMO_BMS_CHARGE_ALLOW_ERROR
-"023981", // ERROR_CODE_CHADEMO_OUTPUT_VOLTAGE_MORE_THEN_10_PERCENT
-"023982", // ERROR_CODE_CHADEMO_ADC_LESS_THAN_10V
-"023983", // STOP by EV with unknow reason
-"023984", // Reserved
-"023985", // Reserved
-"023986", // Reserved
-"023987", // Reserved
-"033900", //disconnected from backend through Ethernet
-"033901", //disconnected from backend through WiFi
-"033902", //disconnected from backend through 3G/4G
-"033903", //Remote start charging by backend
-"033904", //Remote stop charging by backend
-"033905", //Remote reset by backend
-"033906", //Authorization failed
-"033907", //Reserved
-};
-
-
-//------------------------------------------------------------------------------
-char *GetCurrency(uint8_t index)
-{
-    return &Currency[index][0];
-}
-
-char *GetFaultStatusCode(uint8_t index)
-{
-    return &FaultStatusCode[index][0];
-}
-
-char *GetAlarmStatusCode(uint8_t index)
-{
-    return &AlarmStatusCode[index][0];
-}
-
-char *GetInfoStatusCode(uint16_t index)
-{
-    return &InfoStatusCode[index][0];
-}
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdint.h>
+
+#include "define.h"
+
+//------------------------------------------------------------------------------
+char Currency[54][4]=
+{
+"AED", // - Emirati Dirham
+"ARS", // - Argentine Peso
+"AUD", // - Australian Dollar
+"BGN", // - Bulgarian Lev
+"BHD", // - Bahraini Dinar
+"BND", // - Bruneian Dollar
+"BRL", // - Brazilian Real
+"BWP", // - Botswana Pula
+"CAD", // - Canadian Dollar
+"CHF", // - Swiss Franc
+"CLP", // - Chilean Peso
+"CNY", // - Chinese Yuan Renminbi
+"COP", // - Colombian Peso
+"CZK", // - Czech Koruna
+"DKK", // - Danish Krone
+"EUR", // - Euro
+"GBP", // - British Pound
+"HKD", // - Hong Kong Dollar
+"HRK", // - Croatian Kuna
+"HUF", // - Hungarian Forint
+"IDR", // - Indonesian Rupiah
+"ILS", // - Israeli Shekel
+"INR", // - Indian Rupee
+"IRR", // - Iranian Rial
+"ISK", // - Icelandic Krona
+"JPY", // - Japanese Yen
+"KRW", // - South Korean Won
+"KWD", // - Kuwaiti Dinar
+"KZT", // - Kazakhstani Tenge
+"LKR", // - Sri Lankan Rupee
+"LYD", // - Libyan Dinar
+"MUR", // - Mauritian Rupee
+"MXN", // - Mexican Peso
+"MYR", // - Malaysian Ringgit
+"NOK", // - Norwegian Krone
+"NPR", // - Nepalese Rupee
+"NZD", // - New Zealand Dollar
+"OMR", // - Omani Rial
+"PHP", // - Philippine Peso
+"PKR", // - Pakistani Rupee
+"PLN", // - Polish Zloty
+"QAR", // - Qatari Riyal
+"RON", // - Romanian New Leu
+"RUB", // - Russian Ruble
+"SAR", // - Saudi Arabian Riyal
+"SEK", // - Swedish Krona
+"SGD", // - Singapore Dollar
+"THB", // - Thai Baht
+"TRY", // - Turkish Lira
+"TTD", // - Trinidadian Dollar
+"TWD", // - Taiwan New Dollar
+"USD", // - US Dollar
+"VEF", // - Venezuelan Bolivar
+"ZAR" // - South African Rand
+};
+
+char FaultStatusCode[40][6]=
+{
+"011001", //CHAdeMO output fuse blew
+"011002", //CCS output fuse blew
+"011003", //GB output fuse blew
+"011004", //RCD/CCID self-test fail
+"011005", //AC input contactor 1 welding
+"011006", //AC input contactor 1 driving fault
+"011007", //AC input contactor 2 welding
+"011008", //AC input contactor 2 driving fault
+"011009", //AC output relay welding
+"011010", //AC output relay driving fault
+"011011", //CHAdeMO output relay welding
+"011012", //CHAdeMO output relay driving fault
+"011013", //CCS output relay welding
+"011014", //CCS output relay driving fault
+"011015", //GB output relay welding
+"011016", //GB output relay driving fault
+"011017", //AC connector temperature sensor broken
+"011018", //CHAdeMO connector temperature sensor broken
+"011019", //CCS connector temperature sensor broken
+"011020", //GB connector temperature sensor broken
+"011021", //WiFi module broken
+"011022", //3G/4G module broken
+"011023", //Aux. power module broken
+"011024", //Relay control module /smart box broken
+"011025", //CHAdeMO connector lock fail
+"011026", //GB connector lock fail
+"011027", //AC connector lock fail
+"011028", //CHAdeMO module broken
+"011029", //CCS module broken
+"011030", //GBT module broken
+"011031", //PSU module broken
+"011032", //RCD/CCID module broken
+"011033", //Maximum Output Current setup error
+"011034", //Shutter fault
+"011035", //Ble module broken
+"011036", //Rotary switch fault
+"011037", //CCS liquid chiller water level fault
+"011038", //Chiller temperature sensor broken
+"011039", //Parallel relay welding
+"011040"  //Parallel output relay driving fault
+};
+
+char AlarmStatusCode[160][6]=
+{
+"012200", //System L1 input OVP
+"012201", //System L2 input OVP
+"012202", //System L3 input OVP
+"012203", //System L1 input UVP
+"012204", //System L2 input UVP
+"012205", //System L3 input UVP
+"012206", //PSU L1 input OVP
+"012207", //PSU L2 input OVP
+"012208", //PSU L3 input OVP
+"012209", //PSU L1 input UVP
+"012210", //PSU L2 input UVP
+"012211", //PSU L3 input UVP
+"012212", //System L1 input drop
+"012213", //System L2 input drop
+"012214", //System L3 input drop
+"012215", //System AC output OVP
+"012216", //System AC output OCP L1
+"012217", //System CHAdeMO output OVP
+"012218", //System CHAdeMO output OCP
+"012219", //System CCS output OVP
+"012220", //System CCS output OCP
+"012221", //System GB output OVP
+"012222", //System GB output OCP
+"012223", //System ambient/inlet OTP
+"012224", //System critical point OTP
+"012225", //PSU ambient/inlet OTP
+"012226", //PSU critical point OTP
+"012227", //Aux. power module OTP
+"012228", //Relay board/smart box OTP
+"012229", //CHAdeMO connector OTP
+"012230", //CCS connector OTP
+"012231", //GB connector OTP
+"012232", //AC connector OTP
+"012233", //RCD/CCID trip
+"012234", //CHAdeMO GFD trip
+"012235", //CCS GFD trip
+"012236", //GB GFD trip
+"012237", //SPD trip
+"012238", //Main power breaker trip
+"012239", //Aux. power breaker trip
+"012240", //PSU communication fail
+"012241", //WiFi module communication fail
+"012242", //3G/4G module communication fail
+"012243", //RFID module communication fail
+"012244", //Bluetooth module communication fail
+"012245", //LCM module communication fail
+"012246", //Aux. power module communication fail
+"012247", //Relay control boaed/smart box communication fail
+"012248", //CCS module communication fail
+"012249", //CHAdeMO module communication fail
+"012250", //GBT module communication fail
+"012251", //Emergency stop
+"012252", //Door open
+"012253", //System fan decay
+"012254", //Fail to create share memory
+"012255", //CSU initialization failed
+"012256", //AC Ground Fault
+"012257", //MCU self-test Fault
+"012258", //Relay self-test Fault
+"012259", //CHAdeMO groundfault detection timeout (GFD)
+"012260", //CCS groundfault detection timeout (GFD)
+"012261", //GB groundfault detection timeout (GFD)
+"012262", //Circuit Short L1
+"012263", // PSU Duplicate ID
+"012264", // PSU Output Short Circuit
+"012265", // PSU Discharge Abnormal
+"012266", // PSU Dc Side ShutDown
+"012267", // PSU Failure Alarm
+"012268", // PSU Protection Alarm
+"012269", // PSU FanFailure Alarm
+"012270", // PSU Input UVP
+"012271", // PSU Input OVP
+"012272", // PSU WalkIn State
+"012273", // PSU Power Limited State
+"012274", // PSU Id Repeat
+"012275", // PSU Severe Uneven Current
+"012276", // PSU Three Phase Input Inadequate
+"012277", // PSU Three Phase Onput Imbalance
+"012278", // PSU Ffc Side ShutDown
+"012279", // NO PSU Resource
+"012280", // Self test Failed due to communication of Relayboard failure
+"012281", // Self test Failed due to communication of Fanboard failure
+"012282", // Self test Failed due to communication of Primary failure
+"012283", // Self test Failed due to communication of Chademoboard failure
+"012284", // Self test Failed due to communication of CCSboard failure
+"012285", // Self test Failed due to AC Contact failure
+"012286", // Self test Failed due to communication of PSU failure
+"012287", // Self test Failed due to Model name is none match
+"012288", // CCS output UVP
+"012289", // Chademo output UVP
+"012290", // GBT output UVP
+"012291", // Self test Failed due to communication of GBTboard failure
+"012292", // Self test Failed due to communication of AC failure
+"012293", // Self test Failed due to communication of Ledboard failure
+"012294", // Ac input OVP
+"012295", // Ac input UVP
+"012296", // CHAdeMO groundfault detection - warning
+"012297", // CCS groundfault detection - warning
+"012298", // GB groundfault detection - warning
+"012299", // System AC output OCP L2
+"012300", // System AC output OCP L3
+"012301", // Circuit Short L2
+"012302", // Circuit Short L3
+"012303", // CCS liquid chiller water level warning
+"012304", // connection disconnected from power cabinet
+"012305", // Meter communication timeout
+"012306", // The dip switch of the PSU may be incorrect
+"012307", // Psu Fuse Burn-Out
+"012308", // Psu Pfc And Dcdc Communication Fault
+"012309", // Psu Bus Voltage Unbalance
+"012310", // Psu Bus Over Voltage
+"012311", // Psu Bus Voltage Abnormal
+"012312", // Psu Bus Under Voltage
+"012313", // Psu Input Phase Loss
+"012314", // Psu Fan Full Speed
+"012315", // Psu Temperature Power Limit
+"012316", // Psu Ac Power Limit
+"012317", // Psu Dcdc Eeprom Fault
+"012318", // Psu Pfc Eeprom Fault
+"012319", // Psu Dcdc Over Voltage
+"012320", // System CHAdeMO output UCP
+"012321", // System CCS output UCP
+"012322", // System GBT output UCP
+"012323", // System Chiller output OTP
+"012324", // Connector 1 detects abnormal voltage on the output line
+"012325", // Connector 2 detects abnormal voltage on the output line
+"012326", // System task is lost
+"012327",   // DC input ovp
+"012328",   // DC input uvp
+"012329",   // Psu Can Communication Fault
+"012330",   // Psu Dc to Dc OTP
+"012331",   // Psu Dc to Dc OVP
+"012332",   // Chiller Tube OTP
+"012333",   // reserved
+"012334",   // reserved
+"012335",   // reserved
+"012336",   // reserved
+"012337",   // reserved
+"012338",   // reserved
+"012339",   // reserved
+"012340",   // reserved
+"012341",   // reserved
+"012342",   // reserved
+"012343",   // reserved
+"012344",   // AC: Meter IC communication timeout
+"012345",   // AC: Pilot negative error
+"012346",   // Psu Communication error with CSU
+"012347",   // AC: Local power sharing communication error (Slave disconnect from Master)
+"012348",   // reserved
+"012349",   // reserved
+"012350",   // reserved
+"012351",   // reserved
+"012352",   // reserved
+"012353",   // reserved
+"012354",   // reserved
+"012355",   // reserved
+"012356",   // reserved
+"012357",   // reserved
+"012358",   // reserved
+"012359",   // reserved
+};
+
+char InfoStatusCode[384][6]=
+{
+//Information comes from EVSE
+"013600", //Normal stop charging by user
+"013601", //Charging Time's up
+"013602", //Replace system air filter
+"013603", //Reach to CHAdeMO max. plugging times.
+"013604", //Reach to CCS max. plugging times.
+"013605", //Reach to GB max. plugging times.
+"013606", //Reach to AC max. plugging times.
+"013607", //CSU fimrware update fail
+"013608", //CHAdeMO Module fimrware update fail
+"013609", //CCS Module fimrware update fail
+"013610", //GB Module fimrware update fail
+"013611", //Aux. power module fimrware update fail
+"013612", //Relay control module fimrware update fail
+"013613", //LCM module fimrware update fail
+"013614", //Bluetooth module fimrware update fail
+"013615", //WiFi module fimrware update fail
+"013616", //3G/4G module fimrware update fail
+"013617", //SMR fimrware update fail
+"013618", //RFID module fimrware update fail
+"013619", //configured by USB flash drive
+"013620", //configured by backend
+"013621", //configured by webpage
+"013622", //disconnected from Internet through Ethernet
+"013623", //disconnected from Internet through WiFi
+"013624", //disconnected from Internet through 3G/4G
+"013625", //disconnected from AP through WiFi
+"013626", //disconnected from APN through 3G/4G
+"013627", //WiFi disabled (separated charger only)
+"013628", //4G disabled (separated charger only)
+"013629", //Reserved
+"013630", //Reserved
+"013631", //Reserved
+//Information comes from EV
+"023700", //CHAdeMO EV communication Fail
+"023701", //CCS EV communication Fail
+"023702", //GB EV communication Fail
+"023703", //AC: pilot fault
+"023704", //CHAdeMO: battery malfunction
+"023705", //CHAdeMO: no charging permission
+"023706", //CHAdeMO: battery incompatibility
+"023707", //CHAdeMO: battery OVP
+"023708", //CHAdeMO: battery UVP
+"023709", //CHAdeMO: battery OTP
+"023710", //CHAdeMO: battery current difference
+"023711", //CHAdeMO: battery voltage difference
+"023712", //CHAdeMO: shift position
+"023713", //CHAdeMO: battery other fault
+"023714", //CHAdeMO: charging system error
+"023715", //CHAdeMO: EV normal stop
+"023716", //CHAdeMO: connector temperature sensor broken
+"023717", //CHAdeMO: connector lock fail
+"023718", //CHAdeMO: D1 ON No Receive
+"023719", //CHAdeMO: BMS K to J Timeout
+"023720", //CHAdeMO: BMS Charge Allow Timeout
+"023721", //CHAdeMO: Wait GroundFault Timeout
+"023722", //CHAdeMO: BMS EV Relay Timeout
+"023723", //CHAdeMO: BMS Request Current Timeout
+"023724", //CHAdeMO: BMS K to J OFF Timeout
+"023725", //CHAdeMO: BMS EV Relay OFF Timeout
+"023726", //CHAdeMO: ADC More Than 10V
+"023727", //CHAdeMO: ADC More Than 20V
+"023728", //CHAdeMO: BMS Charge Before Stop
+"023729", //CHAdeMO: Charger Get Normal Stop
+"023730", //CHAdeMO: Charger Get Emergency Stop
+"023731", //CHAdeMO: Isolation Result Fail
+"023732", //CHAdeMO: Miss Link With MotherBoard
+"023733", //CHAdeMO: Output Voltage More Than Limit
+"023734", //CHAdeMO: Request Current More Than Limit
+"023735", //CHAdeMO: Re Cap BMS Eqr Current Exceed
+"023736", //CHAdeMO: Charge Remain Count Down
+"023737", //CCS:CCS_EVCC_EVErrorCode_FAILED_RESSTemperatureInhibit
+"023738", //CCS:CCS_EVCC_EVErrorCode_FAILED_EVShiftPosition
+"023739", //CCS:CCS_EVCC_EVErrorCode_FAILED_ChargerConnectorLockFault
+"023740", //CCS:CCS_EVCC_EVErrorCode_FAILED_EVRESSMalfunction
+"023741", //CCS:CCS_EVCC_EVErrorCode_FAILED_ChargingCurrentdifferential
+"023742", //CCS:CCS_EVCC_EVErrorCode_FAILED_ChargingVoltageOutOfRange
+"023743", //CCS:CCS_EVCC_EVErrorCode_FAILED_ChargingSystemIncompatibility
+"023744", //CCS:CCS_EVCC_EVErrorCode_FAILED_EmergencyEvent
+"023745", //CCS:CCS_EVCC_EVErrorCode_FAILED_Breaker
+"023746", //CCS:CCS_EVCC_EVErrorCode_FAILED_NoData
+"023747", //CCS:CCS_EVCC_EVErrorCode_FAILED_reserved_by_DIN_A
+"023748", //CCS:CCS_EVCC_EVErrorCode_FAILED_reserved_by_DIN_B
+"023749", //CCS:CCS_EVCC_EVErrorCode_FAILED_reserved_by_DIN_C
+"023750", //CCS:CCS_EVCC_EVErrorCode_FAILED_reserved_by_ISO_1
+"023751", //CCS:CCS_EVCC_EVErrorCode_FAILED_reserved_by_ISO_2
+"023752", //CCS:CCS_EVCC_EVErrorCode_FAILED_reserved_by_ISO_3
+"023753", //CCS:CCS_EVCC_EVErrorCode_FAILED_reserved_by_OEM_1
+"023754", //CCS:CCS_EVCC_EVErrorCode_FAILED_reserved_by_OEM_2
+"023755", //CCS:CCS_EVCC_EVErrorCode_FAILED_reserved_by_OEM_3
+"023756", //CCS:CCS_EVCC_EVErrorCode_FAILED_reserved_by_OEM_4
+"023757", //CCS:CCS_EVCC_EVErrorCode_FAILED_reserved_by_OEM_5
+"023758", //CCS:CCS_SECC_ResponseCode_FAILED_SequenceError
+"023759", //CCS:CCS_SECC_ResponseCode_FAILED_SignatureError
+"023760", //CCS:CCS_SECC_ResponseCode_FAILED_UnknownSession
+"023761", //CCS:CCS_SECC_ResponseCode_FAILED_ServiceIDInvalid
+"023762", //CCS:CCS_SECC_ResponseCode_FAILED_Payment SelectionInvalid
+"023763", //CCS:CCS_SECC_ResponseCode_FAILED_IdentificationSelectionInvalid
+"023764", //CCS:CCS_SECC_ResponseCode_FAILED_ServiceSelectionInvalid
+"023765", //CCS:CCS_SECC_ResponseCode_FAILED_CertificateExpired
+"023766", //CCS:CCS_SECC_ResponseCode_FAILED_CertificateNotYetValid
+"023767", //CCS:CCS_SECC_ResponseCode_FAILED_CertificateRevoked
+"023768", //CCS:CCS_SECC_ResponseCode_FAILED_NoCertificateAvailable
+"023769", //CCS:CCS_SECC_ResponseCode_FAILED_CertChainError
+"023770", //CCS:CCS_SECC_ResponseCode_FAILED_CertValidationError
+"023771", //CCS:CCS_SECC_ResponseCode_FAILED_CertVerificationError
+"023772", //CCS:CCS_SECC_ResponseCode_FAILED_ContractCanceled
+"023773", //CCS:CCS_SECC_ResponseCode_FAILED_ChallengeInvalid
+"023774", //CCS:CCS_SECC_ResponseCode_FAILED_WrongEnergyTransferMode
+"023775", //CCS:CCS_SECC_ResponseCode_FAILED_WrongChargeParameter
+"023776", //CCS:CCS_SECC_ResponseCode_FAILED_ChargingProfileInvalid
+"023777", //CCS:CCS_SECC_ResponseCode_FAILED_TariffSelectionInvalid
+"023778", //CCS:CCS_SECC_ResponseCode_FAILED_EVSEPresentVoltageToLow
+"023779", //CCS:CCS_SECC_ResponseCode_FAILED_PowerDeliveryNotApplied
+"023780", //CCS:CCS_SECC_ResponseCode_FAILED_MeteringSignatureNotValid
+"023781", //CCS:CCS_SECC_ResponseCode_FAILED_NoChargeServiceSelected
+"023782", //CCS:CCS_SECC_ResponseCode_FAILED_ContactorError
+"023783", //CCS:CCS_SECC_ResponseCode_FAILED_CertificateNotAllowedAtThisEVSE
+"023784", //CCS:CCS_SECC_ResponseCode_FAILED_GAChargeStop
+"023785", //CCS:CCS_SECC_ResponseCode_FAILED_AlignmentError
+"023786", //CCS:CCS_SECC_ResponseCode_FAILED_ACDError
+"023787", //CCS:CCS_SECC_ResponseCode_FAILED_AssociationError
+"023788", //CCS:CCS_SECC_ResponseCode_FAILED_EVSEChargeAbort
+"023789", //CCS:CCS_SECC_ResponseCode_FAILED_NoSupportedApp-Protocol-Protocol
+"023790", //CCS:CCS_SECC_ResponseCode_FAILED_ContractNotAccepted
+"023791", //CCS:CCS_SECC_ResponseCode_FAILED_MOUnknown
+"023792", //CCS:CCS_SECC_ResponseCode_FAILED_OEM_Prov_CertificateRevoke
+"023793", //CCS:CCS_SECC_ResponseCode_FAILED_OEM_SubCA1_CertificateRevoked
+"023794", //CCS:CCS_SECC_ResponseCode_FAILED_OEM_SubCA2_CertificateRevoked
+"023795", //CCS:CCS_SECC_ResponseCode_FAILED_OEM_RootCA_CertificateRevoked
+"023796", //CCS:CCS_SECC_ResponseCode_FAILED_MO_Prov_CertificateRevoked
+"023797", //CCS:CCS_SECC_ResponseCode_FAILED_MO_SubCA1_CertificateRevoked
+"023798", //CCS:CCS_SECC_ResponseCode_FAILED_MO_SubCA2_CertificateRevoked
+"023799", //CCS:CCS_SECC_ResponseCode_FAILED_MO_RootCA_CertificateRevoked
+"023800", //CCS:CCS_SECC_ResponseCode_FAILED_CPS_Prov_CertificateRevoked
+"023801", //CCS:CCS_SECC_ResponseCode_FAILED_CPS_SubCA1_CertificateRevoked
+"023802", //CCS:CCS_SECC_ResponseCode_FAILED_CPS_SubCA2_CertificateRevoked
+"023803", //CCS:CCS_SECC_ResponseCode_FAILED_CPS_RootCA_CertificateRevoked
+"023804", //CCS:CCS_SECC_ResponseCode_FAILED_reserved_1
+"023805", //CCS:CCS_SECC_ResponseCode_FAILED_reserved_2
+"023806", //CCS:CCS_SECC_ResponseCode_FAILED_reserved_3
+"023807", //CCS:CCS_SECC_ResponseCode_FAILED_reserved_4
+"023808", //CCS:CCS_SECC_ResponseCode_FAILED_reserved_5
+"023809", //CCS:CCS_SECC_TIMEOUT_SLAC_TT_EVSE_SLAC_init
+"023810", //CCS:CCS_SECC_TIMEOUT_SLAC_TP_match_response
+"023811", //CCS:CCS_SECC_TIMEOUT_CM_START_ATTEN_CHAR_IND
+"023812", //CCS:CCS_SECC_TIMEOUT_SLAC_TT_EVSE_match_MNBC
+"023813", //CCS:CCS_SECC_TIMEOUT_SLAC_TP_EVSE_avg_atten_calc
+"023814", //CCS:CCS_SECC_TIMEOUT_SLAC_CM_ATTEN_CHAR_RSP
+"023815", //CCS:CCS_SECC_TIMEOUT_SLAC_CM_VALIDATE_REQ_1ST__CM_SLAC_MATCH_REQ
+"023816", //CCS:CCS_SECC_TIMEOUT_SLAC_TT_EVSE_assoc_session
+"023817", //CCS:CCS_SECC_TIMEOUT_SLAC_TT_EVSE_vald_toggle
+"023818", //CCS:CCS_SECC_TIMEOUT_SLAC_CM_MNBC_SOUND_IND
+"023819", //CCS:CCS_SECC_TIMEOUT_SLAC_CM_VALIDATE_REQ_2ND__CM_SLAC_MATCH_REQ
+"023820", //CCS:CCS_SECC_TIMEOUT_SLAC_reserved_3
+"023821", //CCS:CCS_SECC_TIMEOUT_SLAC_reserved_4
+"023822", //CCS:CCS_SECC_TIMEOUT_SLAC_reserved_5
+"023823", //CCS:CCS_SECC_TIMEOUT_SLACC_SDP_UDP_TT_match_join
+"023824", //CCS:CCS_SECC_TIMEOUT_SLACC_SDP_TCP_TT_match_join
+"023825", //CCS:CCS_SECC_TIMEOUT_SLACC_SDP_TP_amp_map_exchange
+"023826", //CCS:CCS_SECC_TIMEOUT_SLACC_SDP_TP_link_ready_notification
+"023827", //CCS:CCS_SECC_TIMEOUT_SLACC_SDP_reserved_1
+"023828", //CCS:CCS_SECC_TIMEOUT_SLACC_SDP_reserved_2
+"023829", //CCS:CCS_SECC_TIMEOUT_SLACC_SDP_reserved_3
+"023830", //CCS:CCS_SECC_TIMEOUT_SLACC_SDP_reserved_4
+"023831", //CCS:CCS_SECC_TIMEOUT_SLACC_SDP_reserved_5
+"023832", //CCS:CCS_SECC_TIMEOUT_V2G_Msg_Performance_Time_SupportedAppProtocolRes
+"023833", //CCS:CCS_SECC_TIMEOUT_V2G_Msg_Performance_Time_SessionSetupRes
+"023834", //CCS:CCS_SECC_TIMEOUT_V2G_Msg_Performance_Time_ServiceDiscoveryRes
+"023835", //CCS:CCS_SECC_TIMEOUT_V2G_Msg_Performance_Time_ServicePaymentSelectionRes
+"023836", //CCS:CCS_SECC_TIMEOUT_V2G_Msg_Performance_Time_ContractAuthenticationRes
+"023837", //CCS:CCS_SECC_TIMEOUT_V2G_Msg_Performance_Time_ChargeParameterDiscoveryRes
+"023838", //CCS:CCS_SECC_TIMEOUT_V2G_Msg_Performance_Time_PowerDeliveryRes
+"023839", //CCS:CCS_SECC_TIMEOUT_V2G_Msg_Performance_Time_CableCheckRes
+"023840", //CCS:CCS_SECC_TIMEOUT_V2G_Msg_Performance_Time_PreChargeRes
+"023841", //CCS:CCS_SECC_TIMEOUT_V2G_Msg_Performance_Time_CurrentDemandRes
+"023842", //CCS:CCS_SECC_TIMEOUT_V2G_Msg_Performance_Time_WeldingDetectionRes
+"023843", //CCS:CCS_SECC_TIMEOUT_V2G_Msg_Performance_Time_SessionStopRes
+"023844", //CCS:CCS_SECC_TIMEOUT_V2G_Sequence_Time
+"023845", //CCS:CCS_SECC_TIMEOUT_V2G_ReadyToCharge_Performance_Time
+"023846", //CCS:CCS_SECC_TIMEOUT_V2G_CommunicationSetup_Performance_Time
+"023847", //CCS:CCS_SECC_TIMEOUT_V2G_CableCheck_Performance_Time
+"023848", //CCS:CCS_SECC_TIMEOUT_V2G_CPState_Detection_Time
+"023849", //CCS:CCS_SECC_TIMEOUT_V2G_CPOscillator_Retain_Time
+"023850", //CCS:CCS_SECC_TIMEOUT_V2G_PreCharge_Performace_Time
+"023851", //CCS:CCS_SECC_TIMEOUT_V2G_reserved_2
+"023852", //CCS:CCS_SECC_TIMEOUT_V2G_reserved_3
+"023853", //CCS:CCS_SECC_TIMEOUT_V2G_reserved_4
+"023854", //CCS:CCS_SECC_TIMEOUT_V2G_reserved_5
+"023855", //CCS:CCS_CAN_TIMEOUT_TP_GET_EV_TARGET_INFO
+"023856", //CCS:CCS_CAN_TIMEOUT_TT_GET_EV_TARGET_INFO
+"023857", //CCS:CCS_CAN_TIMEOUT_TP_GET_EV_BATTERY_INFO
+"023858", //CCS:CCS_CAN_TIMEOUT_TT_GET_EV_BATTERY_INFO
+"023859", //CCS:CCS_CAN_TIMEOUT_TP_EV_STOP_EVENT
+"023860", //CCS:CCS_CAN_TIMEOUT_TT_EV_STOP_EVENT
+"023861", //CCS:CCS_CAN_TIMEOUT_TP_EVSE_STOP_EVENT
+"023862", //CCS:CCS_CAN_TIMEOUT_TT_EVSE_STOP_EVENT
+"023863", //CCS:CCS_CAN_TIMEOUT_TP_GET_MISC_INFO
+"023864", //CCS:CCS_CAN_TIMEOUT_TT_GET_MISC_INFO
+"023865", //CCS:CCS_CAN_TIMEOUT_TP_DOWNLOAD_REQUEST
+"023866", //CCS:CCS_CAN_TIMEOUT_TT_DOWNLOAD_REQUEST
+"023867", //CCS:CCS_CAN_TIMEOUT_TP_START_BLOCK_TRANSFER
+"023868", //CCS:CCS_CAN_TIMEOUT_TT_START_BLOCK_TRANSFER
+"023869", //CCS:CCS_CAN_TIMEOUT_TP_DATA_TRANSFER
+"023870", //CCS:CCS_CAN_TIMEOUT_TT_DATA_TRANSFER
+"023871", //CCS:CCS_CAN_TIMEOUT_TP_DOWNLOAD_FINISH
+"023872", //CCS:CCS_CAN_TIMEOUT_TT_DOWNLOAD_FINISH
+"023873", //CCS:CCS_CAN_TIMEOUT_TP_ISOLATION_STATUS
+"023874", //CCS:CCS_CAN_TIMEOUT_TT_ISOLATION_STATUS
+"023875", //CCS:CCS_CAN_TIMEOUT_TP_CONNECTOR_INFO
+"023876", //CCS:CCS_CAN_TIMEOUT_TT_CONNECTOR_INFO
+"023877", //CCS:CCS_CAN_TIMEOUT_TT_RTC_INFO
+"023878", //CCS:CCS_CAN_TIMEOUT_TP_RTC_INFO
+"023879", //CCS:CCS_CAN_TIMEOUT_TP_EVSE_PRECHARGE_INFO
+"023880", //CCS:CCS_CAN_TIMEOUT_TT_EVSE_PRECHARGE_INFO
+"023881", //CCS:CCS_CAN_TIMEOUT_MSG_Sequence
+"023882", //CCS:CCS_CAN_MSG_Unrecognized_CMD_ID
+"023883", //CCS:CCS_SECC_DIN_Msg_Decode_Error
+"023884", //CCS:CCS_SECC_DIN_Msg_Encode_Error
+"023885", //CCS:CCS_SECC_ISO1_Msg_Decode_Error
+"023886", //CCS:CCS_SECC_ISO1_Msg_Encode_Error
+"023887", //CCS:CCS_SECC_ISO2_Msg_Decode_Error
+"023888", //CCS:CCS_SECC_ISO2_Msg_Encode_Error
+"023889", //CCS:CCS_SECC_CP_STATUS_Error
+"023890", //CCS:CCS_SECC_Unexpected_60V_Before_Charing_Error
+"023891", //CCS:CCS_SECC_Not_Ready_For_Charging
+"023892", //CCS:CCS_SECCC_TIMEOUT_QCA7000_COMM (The firmware code of QCA7000 may not be installed, yet)
+"023893", //CCS:CCS_SECC_FAIL_QCA7000_SETKEY
+"023894", //Reserved
+"023895", //Reserved
+"023896", //Reserved
+"023897", //Reserved
+"023898", //Reserved
+"023899", //Reserved
+"023900", //GBT: ERROR_CODE_GBT_LOS_CC1
+"023901", //GBT: ERROR_CODE_GBT_CONNECTOR_LOCK_FAIL
+"023902", //GBT: ERROR_CODE_GBT_BATTERY_INCOMPATIBLE
+"023903", //GBT: ERROR_CODE_GBT_BMS_BROAA_TIMEOUT
+"023904", //GBT: ERROR_CODE_GBT_CSU_PRECHARGE_TIMEOUT
+"023905", //GBT: ERROR_CODE_GBT_BMS_PRESENT_VOLTAGE_FAULT
+"023906", //GBT: ERROR_CODE_GBT_BMS_VOLTAGE_OVER_RANGE
+"023907", //GBT: ERROR_CODE_GBT_BSM_CHARGE_ALLOW_00_10MIN_COUUNTDONE
+"023908", //GBT: ERROR_CODE_GBT_WAIT_GROUNDFAULT_TIMEOUT
+"023909", //GBT: ERROR_CODE_GBT_ADC_MORE_THAN_10V
+"023910", //GBT: ERROR_CODE_GBT_ADC_MORE_THAN_60V
+"023911", //GBT: ERROR_CODE_GBT_CHARGER_GET_NORMAL_STOP_CMD
+"023912", //GBT: ERROR_CODE_GBT_CHARGER_GET_EMERGENCY_STOP_CMD
+"023913", //GBT: ERROR_CODE_GBT_ISOLATION_RESULT_FAIL
+"023914", //GBT: ERROR_CODE_GBT_MOTHER_BOARD_MISS_LINK
+"023915", //GBT: ERROR_CODE_GBT_OUTPUT_VOLTAGE_MORE_THAN_LIMIT
+"023916", //GBT: ERROR_CODE_GBT_REQ_CURRENT_MORE_THAN_LIMIT
+"023917", //GBT: ERROR_CODE_GBT_OUTPUT_VOLTAGE_MORE_THAN_10_PERCENT
+"023918", //GBT: ERROR_CODE_GBT_OUTPUT_VOLTAGE_DIFF_BCS_5_PERCENT
+"023919", //GBT: ERROR_CODE_GBT_STOP_ADC_MORE_THAN_10V
+"023920", // Reserved
+"023921", // Reserved
+"023922", // Reserved
+"023923", // Reserved
+"023924", // Reserved
+"023925", // Reserved
+"023926", // Reserved
+"023927", // Reserved
+"023928", // Reserved
+"023929", // Reserved
+"023930", //GBT: ERROR_CODE_CEM_BHM_TIMEOUT
+"023931", //GBT: ERROR_CODE_CEM_BRM_TIMEOUT
+"023932", //GBT: ERROR_CODE_CEM_BCP_TIMEOUT
+"023933", //GBT: ERROR_CODE_CEM_BRO_TIMEOUT
+"023934", //GBT: ERROR_CODE_CEM_BCL_TIMEOUT
+"023935", //GBT: ERROR_CODE_CEM_BCS_TIMEOUT
+"023936", //GBT: ERROR_CODE_CEM_BSM_TIMEOUT
+"023937", //GBT: ERROR_CODE_CEM_BST_TIMEOUT
+"023938", //GBT: ERROR_CODE_CEM_BSD_TIMEOUT
+"023939", //GBT: ERROR_CODE_CEM_BEM_OTHER_TIMEOUT
+"023940", //GBT: ERROR_CODE_BEM_CRM_TIMEOUT
+"023941", //GBT: ERROR_CODE_BEM_CRMAA_TIMEOUT
+"023942", //GBT: ERROR_CODE_BEM_CTS_CML_TIMEOUT
+"023943", //GBT: ERROR_CODE_BEM_CRO_TIMEOUT
+"023944", //GBT: ERROR_CODE_BEM_CCS_TIMEOUT
+"023945", //GBT: ERROR_CODE_BEM_CST_TIMEOUT
+"023946", //GBT: ERROR_CODE_BEM_CSD_TIMEOUT
+"023947", //GBT: ERROR_CODE_BEM_BEM_OTHER_TIMEOUT
+"023948", // Reserved
+"023949", // Reserved
+"023950", //GBT: ERROR_CODE_BST_SOC_GOAL
+"023951", //GBT: ERROR_CODE_BST_TOTAL_VOLTAGE_GOAL
+"023952", //GBT: ERROR_CODE_BST_CELL_VOLTAGE_GOAL
+"023953", //GBT: ERROR_CODE_BST_GET_CST
+"023954", //GBT: ERROR_CODE_BST_ISOLATION
+"023955", //GBT: ERROR_CODE_BST_OUTPUT_CONNECTOR_OTP
+"023956", //GBT: ERROR_CODE_BST_COMPONENT
+"023957", //GBT: ERROR_CODE_BST_CHARGE_CONNECTOR
+"023958", //GBT: ERROR_CODE_BST_OTP
+"023959", //GBT: ERROR_CODE_BST_OTHER
+"023960", //GBT: ERROR_CODE_BST_HIGH_V
+"023961", //GBT: ERROR_CODE_BST_CC2
+"023962", //GBT: ERROR_CODE_BST_CURRENT
+"023963", //GBT: ERROR_CODE_BST_VOLTAGE
+"023964", //GBT: ERROR_CODE_GET_BST_NO_REASON
+"023965", // Reserved
+"023966", // Reserved
+"023967", // Reserved
+"023968", // Reserved
+"023969", // Reserved
+"023970", //GBT: ERROR_CODE_BSM_CELL_OVER_VOLTAGE
+"023971", //GBT: ERROR_CODE_BSM_CELL_UNDER_VOLTAGE
+"023972", //GBT: ERROR_CODE_BSM_OVER_SOC
+"023973", //GBT: ERROR_CODE_BSM_UNDER_SOC
+"023974", //GBT: ERROR_CODE_BSM_CURRENT
+"023975", //GBT: ERROR_CODE_BSM_TEMPERATURE
+"023976", //GBT: ERROR_CODE_BSM_ISOLATE
+"023977", //GBT: ERROR_CODE_BSM_OUTPUT_CONNECTOR
+"023978", // Reserved
+"023979", // EV full charging
+"023980", // ERROR_CODE_CHADEMO_BMS_CHARGE_ALLOW_ERROR
+"023981", // ERROR_CODE_CHADEMO_OUTPUT_VOLTAGE_MORE_THEN_10_PERCENT
+"023982", // ERROR_CODE_CHADEMO_ADC_LESS_THAN_10V
+"023983", // STOP by EV with unknow reason
+"023984", // Reserved
+"023985", // Reserved
+"023986", // Reserved
+"023987", // Reserved
+"033900", //disconnected from backend through Ethernet
+"033901", //disconnected from backend through WiFi
+"033902", //disconnected from backend through 3G/4G
+"033903", //Remote start charging by backend
+"033904", //Remote stop charging by backend
+"033905", //Remote reset by backend
+"033906", //Authorization failed
+"033907", //Reserved
+};
+
+
+//------------------------------------------------------------------------------
+char *GetCurrency(uint8_t index)
+{
+    return &Currency[index][0];
+}
+
+char *GetFaultStatusCode(uint8_t index)
+{
+    return &FaultStatusCode[index][0];
+}
+
+char *GetAlarmStatusCode(uint8_t index)
+{
+    return &AlarmStatusCode[index][0];
+}
+
+char *GetInfoStatusCode(uint16_t index)
+{
+    return &InfoStatusCode[index][0];
+}

+ 6549 - 6549
EVSE/Projects/DD360Tcci/Apps/Define/define.h

@@ -1,6549 +1,6549 @@
-#ifndef	DEFINE_H_
-#define	DEFINE_H_
-
-/**************************************************************************************/
-/*********************************NAND Flash mapping *****************************/
-/**************************************************************************************/
-/*
-  sector size	512 KiB
-  Page size       4096 b
-  OOB size        224 b
-  Erase size    	524288 b
--------------------------------------------------------------------------------------------------------------------------------
-Segment 					Physical address 			Size
--------------------------------------------------------------------------------------------------------------------------------
-MLO								0x00000000-0x0007FFFF		512 KB
-Primary u-boot 					0x00080000-0x0017FFFF		1 MB
-Environment 					0x00180000-0x001FFFFF		512 KB
-Secondary u-boot	 			0x00200000-0x002FFFFF		1 MB
-Primary dtb						0x00300000-0x0037FFFF		512 KB
-Secondary dtb					0x00380000-0x003FFFFF		512 KB
-Primary kernel					0x00400000-0x00DFFFFF		10 MB
-Secondary Kernel 				0x00E00000-0x017FFFFF		10 MB
-Primary root file system		0x03000000-0x05FFFFFF		48 MB
-Secondary root file system		0x06000000-0x08FFFFFF		48 MB
-Primary user configuration 		0x09000000-0x095FFFFF		6 MB
-Secondary user configuration	0x09600000-0x09BFFFFF		6 MB
-Factory default configuration	0x09C00000-0x0A1FFFFF		6 MB
-Storage							0x0A200000-0x7FFFFFFF		1886 MB
-*/
-
-/**************************************************************************************/
-/*********************************System Limitation**********************************/
-/**************************************************************************************/
-/*Rating outout power and current*/
-#define RATED_POWER			25		//kW
-#define RATED_CURRENT			350		//Amp, it depend on the capacity of charging connector
-
-/*relevant to Quantity */
-#ifdef AWRegular
-    #define MAX_PSU_QUANTITY        62
-    #define CHAdeMO_QUANTITY        1
-    #define CCS_QUANTITY            1
-    #define GB_QUANTITY             0
-    #define AC_QUANTITY             1
-    #define GENERAL_GUN_QUANTITY    0
-    #define PSU_QUANTITY            0
-    #define ONE_CONNECTOR_USE       0
-#elif defined AWChargeLab
-    #define MAX_PSU_QUANTITY        62
-    #define CHAdeMO_QUANTITY        1
-    #define CCS_QUANTITY            1
-    #define GB_QUANTITY             0
-    #define AC_QUANTITY             1
-    #define GENERAL_GUN_QUANTITY    0
-    #define PSU_QUANTITY            0
-    #define ONE_CONNECTOR_USE       0
-#elif defined AWCCS
-    #define MAX_PSU_QUANTITY        62
-    #define CHAdeMO_QUANTITY        1
-    #define CCS_QUANTITY            1
-    #define GB_QUANTITY             0
-    #define AC_QUANTITY             1
-    #define GENERAL_GUN_QUANTITY    0
-    #define PSU_QUANTITY            0
-    #define ONE_CONNECTOR_USE       0
-#elif defined NoodoeAX
-    #define MAX_PSU_QUANTITY        62
-    #define CHAdeMO_QUANTITY        1
-    #define CCS_QUANTITY            1
-    #define GB_QUANTITY             0
-    #define AC_QUANTITY             1
-    #define GENERAL_GUN_QUANTITY    0
-    #define PSU_QUANTITY            0
-    #define ONE_CONNECTOR_USE       0
-#elif defined AX80
-    #define MAX_PSU_QUANTITY        62
-    #define CHAdeMO_QUANTITY        1
-    #define CCS_QUANTITY            1
-    #define GB_QUANTITY             0
-    #define AC_QUANTITY             3
-    #define GENERAL_GUN_QUANTITY    3
-    #define PSU_QUANTITY            0
-    #define ONE_CONNECTOR_USE       0
-#elif defined DW30
-	#define MAX_PSU_QUANTITY        62
-	#define CHAdeMO_QUANTITY        0
-	#define CCS_QUANTITY            1
-	#define GB_QUANTITY             0
-	#define AC_QUANTITY             0
-    #define GENERAL_GUN_QUANTITY	0
-	#define PSU_QUANTITY            2
-	#define ONE_CONNECTOR_USE       0
-#elif defined DM30
-	#define MAX_PSU_QUANTITY        62
-	#define CHAdeMO_QUANTITY        0
-	#define CCS_QUANTITY            1
-	#define GB_QUANTITY             0
-	#define AC_QUANTITY             0
-    #define GENERAL_GUN_QUANTITY	0
-	#define PSU_QUANTITY            2
-	#define ONE_CONNECTOR_USE       0
-#elif defined DS60120
-	#define MAX_PSU_QUANTITY        62
-	#define CHAdeMO_QUANTITY        2
-	#define CCS_QUANTITY            2
-	#define GB_QUANTITY             2
-	#define AC_QUANTITY             1
-    #define GENERAL_GUN_QUANTITY	0
-	#define PSU_QUANTITY            2
-	#define ONE_CONNECTOR_USE       0
-#elif defined DS60210
-	#define MAX_PSU_QUANTITY        62
-	#define CHAdeMO_QUANTITY        1
-	#define CCS_QUANTITY            1
-	#define GB_QUANTITY             0
-	#define AC_QUANTITY             0
-    #define GENERAL_GUN_QUANTITY	0
-	#define PSU_QUANTITY            2
-	#define ONE_CONNECTOR_USE       0
-#elif defined PlugIt360
-    #define MAX_PSU_QUANTITY        62
-    #define CHAdeMO_QUANTITY        0
-    #define CCS_QUANTITY            1
-    #define GB_QUANTITY             0
-    #define AC_QUANTITY             0
-    #define GENERAL_GUN_QUANTITY	0
-    #define PSU_QUANTITY            2
-    #define ONE_CONNECTOR_USE       0
-#elif defined DD360 || defined DD360Audi || defined DD360ComBox || defined DD360UCar || defined DD360Tcci
-    #define MAX_PSU_QUANTITY        62
-    #define CHAdeMO_QUANTITY        2
-    #define CCS_QUANTITY            2
-    #define GB_QUANTITY             2
-    #define AC_QUANTITY             0
-    #define GENERAL_GUN_QUANTITY	0
-    #define PSU_QUANTITY            2
-    #define ONE_CONNECTOR_USE       0
-#elif defined DO360
-    #define MAX_PSU_QUANTITY        62
-    #define CHAdeMO_QUANTITY        0
-    #define CCS_QUANTITY            0
-    #define GB_QUANTITY             0
-    #define AC_QUANTITY             0
-    #define GENERAL_GUN_QUANTITY    4
-    #define PSU_QUANTITY            6
-    #define ONE_CONNECTOR_USE       0
-#elif defined ATE
-    #define MAX_PSU_QUANTITY        62
-    #define CHAdeMO_QUANTITY        0
-    #define CCS_QUANTITY            1
-    #define GB_QUANTITY             0
-    #define AC_QUANTITY             0
-    #define GENERAL_GUN_QUANTITY	0
-    #define PSU_QUANTITY            2
-    #define ONE_CONNECTOR_USE       0
-#elif defined Emulator
-    #define MAX_PSU_QUANTITY        62
-    #define CHAdeMO_QUANTITY        2
-    #define CCS_QUANTITY            2
-    #define GB_QUANTITY             2
-    #define AC_QUANTITY             2
-    #define GENERAL_GUN_QUANTITY    0
-    #define PSU_QUANTITY            2
-    #define ONE_CONNECTOR_USE       0
-#else
-    #define MAX_PSU_QUANTITY        62
-    #define CHAdeMO_QUANTITY        2
-    #define CCS_QUANTITY            2
-    #define GB_QUANTITY             2
-    #define AC_QUANTITY             1
-    #define GENERAL_GUN_QUANTITY    0
-    #define PSU_QUANTITY            2
-    #define ONE_CONNECTOR_USE       0
-#endif
-
-#define CONNECTOR_QUANTITY			(CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY + AC_QUANTITY + GENERAL_GUN_QUANTITY)
-
-/*SystemLog message*/
-#define SystemLogMessage			//for debug info save to log file
-//#define ConsloePrintLog				//for debug info print to console
-
-/**************************************************************************************/
-/*****************************share memory key information*****************************/
-/**************************************************************************************/
-#define ShmSysConfigAndInfoKey	1001
-#define ShmPsuKey				1002
-#define ShmCHAdeMOCommKey		1003
-#define ShmCcsCommKey			1004
-#define ShmStatusCodeKey		1005
-#define ShmPrimaryMcuKey		1006
-#define ShmFanBdKey				1007
-#define ShmRelayBdKey			1008
-#define ShmOcppModuleKey		1009
-#define ShmGBTCommKey			1010
-#define ShmLedBdKey				1011
-#define ShmOcpp20ModuleKey		1012
-#define ShmRelay2BdKey			1013
-#define ShmYesCustomKey         1014
-#define ShmOcppPHModuleKey      1015
-#define ShmSmartBoxKey          1016
-
-#define FaultCodeLength         5
-#define AlarmCodeLength         20
-#define InfoCodeLength          41
-
-/**************************************************************************************/
-/****************** Share memory configuration value constant define ******************/
-/**************************************************************************************/
-struct NoneUse
-{
-    unsigned char       unknown;                    // None use struct
-};
-
-enum SYSTEM_STATUS
-{
-	SYS_MODE_BOOTING		= 0,
-	SYS_MODE_IDLE    	  	= 1,
-	SYS_MODE_AUTHORIZING		= 2,
-	SYS_MODE_MODE_REASSIGN_CHECK	= 3,
-	SYS_MODE_REASSIGN		= 4,
-	SYS_MODE_PREPARING		= 5,
-	SYS_MODE_PREPARE_FOR_EV		= 6,
-	SYS_MODE_PREPARE_FOR_EVSE	= 7,
-	SYS_MODE_CHARGING		= 8,
-	SYS_MODE_TERMINATING		= 9,
-	SYS_MODE_COMPLETE		= 10,
-	SYS_MODE_ALARM			= 11,
-	SYS_MODE_FAULT			= 12,
-	SYS_MODE_RESERVATION		= 13,
-	SYS_MODE_BOOKING		= 14,
-	SYS_MODE_MAINTAIN		= 15,
-	SYS_MODE_DEBUG			= 16,
-	SYS_MODE_CCS_PRECHARGE_STEP0	= 17,
-	SYS_MODE_CCS_PRECHARGE_STEP1	= 18,
-	SYS_MODE_UPDATE			= 19
-};
-
-enum AUTHORIZATION_MODE
-{
-	AUTH_MODE_ENABLE		= 0,
-	AUTH_MODE_DISABLE		= 1
-};
-
-enum LCD_LANGUAGE
-{
-	LCD_LANG_ENGLISH		= 0,
-	LCD_LANG_CHT			= 1,
-	LCD_LANG_CHS			= 2,
-	LCD_LANG_JAPANESE		= 3,
-	LCD_LANG_FRENCH			= 4,
-	LCD_LANG_ITALIAN		= 5,
-	LCD_LANG_SPANISH		= 6,
-	LCD_LANG_GERMAN			= 7,
-	LCD_LANG_DUTCH			= 8,
-	LCD_LANG_NORWEGIAN		= 9,
-	LCD_LANG_FINNISH		= 10,
-	LCD_LANG_SWEDISH		= 11,
-	LCD_LANG_SLOVENIAN		= 12,
-	LCD_LANG_THAI			= 13,
-};
-
-
-enum RFID_ENDIAN
-{
-	RFID_ENDIAN_LITTLE		= 0,
-	RFID_ENDIAN_BIG			= 1
-};
-
-enum PHASE_LOSS_POLICY
-{
-	LOSS_POLICY_CHARGING		= 0,
-	LOSS_POLICY_STOP		= 1
-};
-
-enum CCS_AUTHPRIZATION_MODE
-{
-	CCS_AUTH_MODE_EIM		= 0,
-	CCS_AUTH_MODE_MIXED		= 1
-};
-
-enum OFF_LINE_POLICY
-{
-	OFF_POLICY_LOCALLIST		= 0,
-	OFF_POLICY_PH_RFID		= 1,
-	OFF_POLICY_FREE			= 2,
-	OFF_POLICY_NOCHARGE		= 3
-};
-
-/*Configuration enum*/
-enum CoreProfile {
-	 AllowOfflineTxForUnknownId=0,
-	 AuthorizationCacheEnabled,
-	 AuthorizeRemoteTxRequests,
-	 BlinkRepeat,
-	 ClockAlignedDataInterval,
-	 ConnectionTimeOut,
-	 GetConfigurationMaxKeys,
-	 HeartbeatInterval,
-	 LightIntensity,
-	 LocalAuthorizeOffline,
-	 LocalPreAuthorize,
-	 MaxEnergyOnInvalidId,
-	 MeterValuesAlignedData,
-	 MeterValuesAlignedDataMaxLength,
-	 MeterValuesSampledData,
-	 MeterValuesSampledDataMaxLength,
-	 MeterValueSampleInterval,
-	 MinimumStatusDuration,
-	 NumberOfConnectors,
-	 ResetRetries,
-	 ConnectorPhaseRotation,
-	 ConnectorPhaseRotationMaxLength,
-	 StopTransactionOnEVSideDisconnect,
-	 StopTransactionOnInvalidId,
-	 StopTxnAlignedData,
-	 StopTxnAlignedDataMaxLength,
-	 StopTxnSampledData,
-	 StopTxnSampledDataMaxLength,
-	 SupportedFeatureProfiles,
-	 SupportedFeatureProfilesMaxLength,
-	 TransactionMessageAttempts,
-	 TransactionMessageRetryInterval,
-	 UnlockConnectorOnEVSideDisconnect,
-	 WebSocketPingInterval,
-	 QueueOffLineMeterValues,
-	 AuthorizationKey,
-	 SecurityProfile,
-     DefaultPrice,
-     CustomDisplayCostAndPrice,
-     CustomIdleFeeAfterStop,
-     TimeOffset,
-     NextTimeOffsetTransitionDateTime,
-     TimeOffsetNextTransition,
-     SystemUptimeSec,
-     FreeVend,
-     FreeVendIdtag,
-     OcppServer,
-     MaintainServer,
-     StatusNotificationPeriodically,
-     StatusNotificationInterval,
-     PreAuthAmount,
-     isEnableLocalPowerSharing,
-     PowerSharingServerIP,
-     EVCCID_PREFIX,
-     OffLineMaxChargingPower,
-     ConfigurationVersion,
-	 CharingProfileRefreshInterval,
-	 CpoName,
-	 OcppSoftwareVersion,
-	 _CoreProfile_CNT
-};
-
-enum OCPP_RUNNING_VERSION {
-    OCPP_RUNNING_VERSION_16=0,
-    OCPP_RUNNING_VERSION_20
-};
-
-enum OCPP_START_ID_TYPE {
-    IdTokenType_Central=0,
-    IdTokenType_eMAID,
-    IdTokenType_ISO14443,
-    IdTokenType_ISO15693,
-    IdTokenType_KeyCode,
-    IdTokenType_Local,
-    IdTokenType_MacAddress,
-    IdTokenType_NoAuthorization
-};
-/**************************************************************************************/
-/****structure SysConfigData => shall store the data to NAND flash****************/
-/****structure SysInfoData => shall NOT store the data to NAND flash***************/
-/****according to System Configuration and Information Table.xlsx Rev.0.2 *******/
-/**************************************************************************************/
-
-struct EthConfigData
-{
-	unsigned char		EthDhcpClient;				//0: enable,1: disable
-	unsigned char		EthMacAddress[18];			//default: Null
-	unsigned char		EthIpAddress[16];			//Eth0 default:192.168.0.10	,Eth1 default:192.168.1.10
-	unsigned char		EthSubmaskAddress[16];		//Eth0 default:255.255.255.0	,Eth1 default:255.255.255.0
-	unsigned char		EthGatewayAddress[16];		//Eth0 default:192.168.0.254	,Eth1 default:192.168.1.254
-};
-
-struct WifiConfigData
-{
-	unsigned char		WifiMode;					//0: disable, 1: Infrastructure client, 2: Infrastructure server, 3: Ad-Hoc
-	unsigned char		WifiSsid[256];				//default: Null
-    unsigned char       WifiPassword[224];          //default: Null
-    unsigned char       WifiBroadcastSsid;          //the SSID broadcast configuration, 0: hidden   1: broadcast
-    unsigned char       WifiTargetBssidMac[31];     //Target connect SSID MAC address, default: Null
-	int					WifiRssi;					//dbm
-	unsigned char		WifiDhcpServer;				//0: enable, 1: disable
-	unsigned char		WifiDhcpClient;				//0: enable, 1: disable
-	unsigned char		WifiMacAddress[18];			//default: Null
-	unsigned char		WifiIpAddress[16];			//default:192.168.2.10
-	unsigned char		WifiSubmaskAddress[16];		//default:255.255.255.0
-	unsigned char		WifiGatewayAddress[16];		//default:192.168.2.254
-	unsigned char		WifiNetworkConn;			//0: disconnected, 1: connected
-};
-
-struct TeleConfigData
-{
-	unsigned char		TelcomModelName[64];		//default: Null
-	unsigned char		TelcomSoftwareVer[64];		//default: Null
-    unsigned char       TelcomApn[255];             //default: Null
-    unsigned char       TelcomNetworkType;          //0: Auto   1: CDMA  2: WCDMA  3: LTE  4: TD-SCDMA  5: UMTS  6: CDMA  7: HDR  8: CDMA/HDR
-	int					TelcomRssi;					//dbm
-	unsigned char		TelcomChapPapId[256];		//default: Null
-	unsigned char		TelcomChapPapPwd[256];		//default: Null
-	unsigned char		TelcomModemImei[16];		//default: Null
-	unsigned char		TelcomSimImsi[16];			//default: Null
-	unsigned char		TelcomSimIccid[22];			//default: Null
-	unsigned char		TelcomSimStatus;			//0: no SIM card is found, 1: valid SIM card, 2: invalid SIM card
-	unsigned char       TelcomModemMode;            //0: No services, 1: CDMA, 2: GSM/GPRS, 3: WCDMA, 4: GSM/WCDMA, 5: TD_SCDMA, 6: HSPA, 7: LTE 9: Unknown
-	unsigned char		TelcomIpAddress[16];		//default: Null
-	unsigned char		TelcomNetworkConn;			//0: disconnected, 1: connected
-	unsigned char		TelcomEnabled;				//0: disable, 1: enable
-};
-
-struct BtConfigData
-{
-	unsigned char		LoginCentralID[64];			//default: Null
-	unsigned char		isLogin;					//0: Central device non-login	1: Central device login
-	unsigned char		isRequestStart;				//0: no action	1: request start charging
-	unsigned char		isRequestStop;				//0: no action	1: request stop charging
-};
-
-struct BillingConfigData
-{
-	unsigned char		isBilling;					//0:not for business	1:for business
-	unsigned char		Currency;					//
-	float				Fee[24];					//fee for 24 hours
-	float 				Cur_fee;					// display current fee
-};
-
-struct LED
-{
-	unsigned char 			Intensity;					// LED bar intensity	0: Darkest	1: Medium	2: Brightest
-
-	unsigned char			Red[3];						// Red color	0~100, element 0: IDLE		1: CHARGING		2: FAULT
-	unsigned char			Green[3];					// Green color	0~100, element 0: IDLE		1: CHARGING		2: FAULT
-	unsigned char			Blue[3];					// Blue color	0~100, element 0: IDLE		1: CHARGING		2: FAULT
-};
-
-struct LCD_NOUSE
-{
-    unsigned char           page_index;                 // LCD override page index
-    unsigned char           duration;                   // LCD override duration
-    unsigned char           isOverideReq:1;             // LCD override request
-};
-
-struct LCD_OVERRIDE
-{
-    unsigned char           connectorId;                // LCD override connector id
-    unsigned char           page_index;                 // LCD override page index
-    unsigned char           duration;                   // LCD override duration
-    unsigned char           isOverideReq:1;             // LCD override request
-};
-
-struct Schedule
-{
-	unsigned char   isEnable;     						// 0: disable schedule function  1: enable schedule function
-	unsigned char   scheduleType;    					// 0: Once   1: Daily
-	unsigned char   scheduleMethod;    					// 0: Continuous 1: Specificate end time
-	unsigned char   startTimeHour;    					// Schedule start trigger time hour
-	unsigned char   startTimeMinute;   					// Schedule start trigger time minute
-	unsigned char   stopTimeHour;    					// Schedule stop trigger time hour
-	unsigned char   stopTimeMinute;    					// Schedule stop trigger time minute
-	unsigned char   isTriggerStart;    					// 0: disable; 1: enable
-	unsigned char   isTriggerStop;    					// 0: disable; 1: enable
-};
-
-struct TTIA
-{
-    unsigned char   server_addr[512];                   // Target server address
-    unsigned int    server_port;                        // Target server port
-    unsigned int    busVenderId;                        // Bus vender id, 0~65535
-    unsigned char   EquipmentProvider[16];              // EVSE vender max 15 bytes
-    unsigned char   TransportationCompanyNo;            // Data provider company number
-    unsigned char   ChargeBoxId;                        // 1 byte
-    unsigned char   evseStation[16];                    // UTF-8 15 bytes, Chinese 5 words
-    unsigned char   isEnableTTIA:1;                     // TTIA function enable
-};
-
-struct LocalSharingInfo
-{
-    unsigned short      AvailableShargingCurrent[4];    // 0 ~ rating value amp,  Synchronize from local sharing server
-    unsigned char       isConnectedSharingServer:1;     // 0: Disconnected, 1: Connected
-};
-
-typedef union
-{
-    unsigned int ChargingStopValue;
-    struct
-    {
-        unsigned int NormalStop:1;                  // 0: no effect,    1: normal stop
-        unsigned int AlarmStop:1;                   // 0: no effect,    1: alarm stop
-        unsigned int BackendStop:1;                 // 0: no effect,    1: backend stop
-        unsigned int ManualStop:1;                  // 0: no effect,    1: manual stop
-        unsigned int HardResetStop:1;               // 0: no effect,    1: hard reset stop
-        unsigned int SoftResetStop:1;               // 0: no effect,    1: soft reset stop
-        unsigned int InvalidIdStop:1;               // 0: no effect,    1: invalid stop when StopTransactionOnInvalidId is true
-        unsigned int RemoteStop:1;                  // 0: no effect,    1: remote stop
-        unsigned int UnlockStop:1;                  // 0: no effect,    1: unlock stop
-        unsigned int SessionTargetStop:1;           // 0: no effect,    1: session target stop
-        unsigned int res:22;
-    }bits;
-}ChargingStop;
-
-typedef struct
-{
-    unsigned char DispenserSequence;                    // dispenser sequence
-    unsigned char MaxConnectorQuantity;                 // max connector quantity
-    unsigned char WiringSetting[8];                     // record connector quantity of dispenser
-    unsigned char PowerCabinetReserved[32];
-}WiringInfoData;
-
-typedef struct
-{
-    unsigned int isCalibratedVaGain:1;                  // Voltage phase a gain is calibrated, 0: default   1: Calibrated
-    unsigned int isCalibratedVbGain:1;                  // Voltage phase b gain is calibrated, 0: default   1: Calibrated
-    unsigned int isCalibratedVcGain:1;                  // Voltage phase c gain is calibrated, 0: default   1: Calibrated
-    unsigned int isCalibratedVaOffset:1;                // Voltage phase a offset is calibrated, 0: default 1: Calibrated
-    unsigned int isCalibratedVbOffset:1;                // Voltage phase b offset is calibrated, 0: default 1: Calibrated
-    unsigned int isCalibratedVcOffset:1;                // Voltage phase c offset is calibrated, 0: default 1: Calibrated
-    unsigned int isCalibratedCaGain:1;                  // Current phase a gain is calibrated, 0: default   1: Calibrated
-    unsigned int isCalibratedCbGain:1;                  // Current phase b gain is calibrated, 0: default   1: Calibrated
-    unsigned int isCalibratedCcGain:1;                  // Current phase c gain is calibrated, 0: default   1: Calibrated
-    unsigned int isCalibratedCaOffset:1;                // Current phase a offset is calibrated, 0: default 1: Calibrated
-    unsigned int isCalibratedCbOffset:1;                // Current phase b offset is calibrated, 0: default 1: Calibrated
-    unsigned int isCalibratedCcOffset:1;                // Current phase c offset is calibrated, 0: default 1: Calibrated
-    unsigned int isCalibratedPa:1;                      // Phase angle a is calibrated, 0: default          1: Calibrated
-    unsigned int isCalibratedPb:1;                      // Phase angle b gain is calibrated, 0: default     1: Calibrated
-    unsigned int isCalibratedPc:1;                      // Phase angle c gain is calibrated, 0: default     1: Calibrated
-    unsigned int :1;
-}MeterIcCalibration;
-
-struct SysConfigData
-{
-	/**************System***************/
-	unsigned char 			CsuBootLoadFwRev[32];			//CSU board bootloader firmware version
-	unsigned char			ModelName[64];				//charger model name
-	unsigned char			AcModelName[64];			//for third gun (DC + AC)
-	unsigned char			SerialNumber[64];			//charger system serial number
-	unsigned char			SystemId[128];				//charger system ID
-	unsigned char			SystemDateTime[32];			//charger system date and time
-	unsigned char			AcPhaseCount;				//AC EVSE power phase quantity,  1: One phase	3: Three phase
-	unsigned char			AuthorisationMode;			//0: enable, 1: disable
-	unsigned char			DefaultLanguage;			//
-	unsigned char			RfidCardNumEndian;			//0: little endian,  1: big endian
-	unsigned short			AcPlugInTimes;				//0~65535
-	unsigned short			GbPlugInTimes;				//0~65535
-	unsigned short			Ccs1PlugInTime;				//0~65535
-	unsigned short			Ccs2PlugInTimes;			//0~65535
-	unsigned short			ChademoPlugInTimes;			//0~65535
-	unsigned char			PsuAcInputType;				//0: 220, 1: 277
-	unsigned short			RatingCurrent;				//0: Depend on Model name,	1 ~ rating value amp
-	unsigned short			AcRatingCurrent;			//for third gun; 0: Depend on Model name,	1 ~ rating value amp
-	unsigned char			isAPP;						//for AuthorisationMode=0; 0:false, 1:true
-	unsigned char			isQRCode;					//for AuthorisationMode=0; 0:false, 1:true
-	unsigned char			isRFID;						//for AuthorisationMode=0; 0:false, 1:true
-	unsigned char			QRCodeMadeMode;				//for isQRCode=1 ; 0: default	1:customized
-	unsigned char			QRCodeContent[128];			//for QRCodeMadeMode=1
-	unsigned char			TotalConnectorCount;		//Connector count
-	unsigned char 			AcConnectorCount;			// For DC type
-	unsigned char			SwitchDebugFlag;			// Console Debug
-	unsigned char			AlwaysGfdFlag;
-	/**************Charging***************/
-	unsigned short			MaxChargingEnergy;			//0: no limit,	1 ~ 65535	kWh
-	unsigned short			MaxChargingPower;			//0: rating value, 1 ~ RATING_POWER	kW
-	unsigned short			MaxChargingCurrent;			//0: rating value, 1 ~ RATING_CURRENT	amp
-	unsigned short			AcMaxChargingCurrent;		//for third gun; 0: rating value, 1 ~ RATING_CURRENT	amp
-	unsigned short			MaxChargingDuration;		//0: no limit,	1 ~ 65535	minutes
-	unsigned char			PhaseLossPolicy;			//0: charging,  1: stop charging
-	unsigned char			LocalWhiteCard[10][32];		//Max. card quantity is 10
-	unsigned char			UserId[32];					//the user use this ID to trigger charging event, it can be RFID card number, OCPP IdTag, etc.
-	struct BillingConfigData BillingData;
-	/**************Network***************/
-	unsigned char 			FtpServer[256];				//the ftp server for Phihong server to do data transimission
-	struct EthConfigData	Eth0Interface;
-	struct EthConfigData	Eth1Interface;
-	struct WifiConfigData 	AthInterface;
-	struct TeleConfigData	TelecomInterface;
-	struct BtConfigData		Bluetooth;
-	/**************Backend***************/
-	unsigned int 			BackendConnTimeout;			//default : 300s
-	unsigned char   		OfflinePolicy;				//0: local list, 1: Phihong RFID tag, 2: free charging, 3: no charging
-	unsigned short	   		OfflineMaxChargeEnergy;		//0: same as MaxChargingEnergy, 1 ~ 65535 kWh
-	unsigned short	   		OfflineMaxChargeDuration;	//0: same as MaxChargeDuration, 1 ~ 65535 minutes
-	unsigned char 			OcppServerURL[512];			//ws: non-secure OCPP 1.6-J, wss: secure OCPP 1.6-J"
-	unsigned char 			ChargeBoxId[128];
-	unsigned char			chargePointVendor[20];		//the Vendor of the ChargePoint
-    unsigned char           OcppSecurityProfile;        //OCPP security profile 0~3
-    unsigned char           OcppSecurityPassword[41];   //OCPP AuthorizationKey for security profile
-	unsigned int 			Checksum;					//4 bytes checksum
-	struct LED				LedInfo;					// LED configuration info
-	unsigned char			ShowInformation;
-	unsigned char           isReqFirstUpgrade;          //EVSE is request first upgrade from PH server
-	unsigned char           isEnableLocalPowerSharing;  //0: Disable power sharing  1: Master   2: Slave
-	unsigned char           StopChargingByButton;       //0: Disable  1: Enable
-    struct LCD_NOUSE        Legacy_LcdOveride;          // LCD override info (no use anymore)
-    struct TTIA             TTIA_Info;                  // TTIA configuration struct
-
-    /************PowerCabinet************/
-    WiringInfoData          WiringInfo;
-
-    unsigned char           OcppReceiptrURL[512];               // Charging receipt display URL
-    unsigned char           isAuthrizeByEVCCID;                 // is Authorize by EVCCID (CCS)
-    unsigned char           MaintainServerURL[512];             // ws: non-secure OCPP 1.6-J, wss: secure OCPP 1.6-J"
-    unsigned char           MaintainServerSecurityProfile;      // Maintain server security profile 0~3
-    unsigned char           MaintainServerSecurityPassword[41]; // Maintain server AuthorizationKey for security profile
-    unsigned char           PowerSharingServerIP[512];          // Local power sharing server ip address
-    unsigned int            PowerSharingCapacityPower;          // Local power sharing capacity power
-    unsigned char           MaxChargingSoc;                     //0: unlimit, 1 ~ 100 percent
-};
-
-struct DERATING_BY_OTP
-{
-    unsigned char isNeedDerating;
-    unsigned char deratingIndex;        // Current used power or current
-    double deratingTargetRate[5];       // Reduce the output energy rate
-    double deratingTargetCurrent[5];    // derating target current
-};
-
-struct ChargingInfoData
-{
-	unsigned char 		Index;
-	unsigned char 		slotsIndex;
-	unsigned char 		Type;					// 0 : Chademo, 1 : CCS, 2: GB
-	unsigned char 		type_index;
-	unsigned char 		Evboard_id;				// for EV board
-	unsigned char 		StopChargeFlag;			// for EV board
-	unsigned char		SystemStatus;				//0: Booting, 1: idle, 2: authorizing, 3: preparing, 4: charging, 5: terminating, 6: alarm, 7: fault
-	unsigned char		PreviousSystemStatus;		// 0: Booting, 1: idle, 2: authorizing, 3: preparing, 4: charging, 5: terminating, 6: alarm, 7: fault	
-	int 			ReservationId;
-	unsigned char 		IsAvailable;
-	float MaximumChargingVoltage;	// unit 0.1V
-	float AvailableChargingCurrent;	// unit 0.1A
-	float AvailableChargingPower;	// unit 0.1kW
-	float DividChargingCurrent;		//0~6553.5 amp
-	float DeratingChargingCurrent;  // unit 0.1A
-	float DeratingChargingPower;	// unit 0.1kW
-	float FuseChargingVoltage;		//0~6553.5 volt
-	float FireChargingVoltage;		//0~6553.5 volt
-	float PresentChargingVoltage;   // unit: 1V
-	float PresentChargingCurrent;   // unit: 1A
-	float PresentChargingPower;		//0~6553.5 kW
-	float PresentChargedEnergy;		//0~6553.5 kWh
-	float presentChargedEnergyPeriod[24];       // Session present charged energy at each period
-	int PresentChargedDuration;	// second
-	int RemainChargingDuration;	// second
-	float EvBatteryMaxVoltage;		// 0~6553.5 volt
-	float EvBatterytargetVoltage;		// 0~6553.5 volt
-	float EvBatterytargetCurrent; 	//102.3				0~200(A) (unit:1A)
-	int EvBatterySoc;				// 0~100%
-	unsigned char ConnectorPlugIn;			//0: unplug, 1: Plug-in
-	unsigned char GunLocked;				//0: unlocked 1: locked
-	unsigned char InProgress;               //0: real idle, 1: session(transaction) in progress
-	float PilotVoltage;
-	unsigned char PilotState;//1:state A, 2:State B1, 3:State B2, 4:State C, 5:State D, 6:State E, 7:State F, 8: Pilot error
-	unsigned char PilotDuty;					// 0~100%
-	unsigned char			StartUserId[32];			// This ID is trigger start charging event user by RFID, back-end, BLE.
-	unsigned char           StartIdType;                // 0: Central   1: eMAID    2: ISO14443 3: ISO15693 4: KeyCode  5: Local    6: MacAddress   7: NoAuthorization
-	unsigned char			StartDateTime[32];			// Charging cycle start date time
-	unsigned char			StopDateTime[32];			// Charging cycle stop date time
-	unsigned char			StartMethod;
-	float					ChargingFee;
-	// Connector Temp
-	unsigned char 		ConnectorTemp;			//0x00: -60¢XC  ~  0xFE: 194
-    //Chiller Temp
-    unsigned char       ChillerTemp;            //0x00: -60¢XC  ~  0xFE: 194
-	// Charging Status
-	unsigned char 		GroundFaultStatus;		// for GFD result => 0x00 : None, 0x01 : Can Start Charging, 0x02 : Stop Charging
-	unsigned short		RealRatingPower;        // unit: 0.1kW
-	unsigned char 		RelayWeldingCheck;		// 0 : No Comp., 1 : Comp.
-	unsigned char 		PrechargeStatus;		// for ccs precharge => 0x00 : None defined, 0x01 : Accepted
-	float 				PowerConsumption;		// This contains the meter value (Power Consumption) kWh
-	unsigned char		RelayK1K2Status;		// 0x00 : open, 0x01 : close
-	unsigned char		RelayKPK2Status;		// 0x00 : open, 0x01 : close
-	unsigned char 	 	TimeoutFlag;			// 0 : none,
-	struct timeval		TimeoutTimer;
-	unsigned char 		MaxChargeEnable;
-	unsigned char		IsReadyToCharging;
-	unsigned char		CcsAuthentication;				// 0:EIM, 1:EIM & PnC mixed
-	unsigned char		AcCcsChargingMode;				// 0:BC (PWM) only, 1:BC & PLC mixed
-	unsigned short		SampleChargingCur[10];
-
-	/************** Alston ***************/
-	unsigned char 		SelfTest_Comp;
-	unsigned char		version[16];
-	unsigned char 		IsModeChagned;
-	unsigned char 		IsCharging;
-	unsigned char 		IsErrorOccur;
-	float 				RealMaxVoltage;
-	float				RealMaxCurrent;
-	float 				RealMaxPower;
-	unsigned char 		ConnectorWarningCode[7];
-	unsigned char 		ConnectorAlarmCode[7];
-	unsigned char 		EvConnAlarmCode[7];
-	float 				ChargingProfileCurrent;			// unit: 0.1A
-	float 				ChargingProfilePower;			// unit: 1W
-	float               LocalPowerLimitCurrent;         // unit: 1A
-	float 				PresentChargingVoltageL2;		//0~6553.5 volt
-	float 				PresentChargingVoltageL3;		//0~6553.5 volt
-	float 				PresentChargingCurrentL2;		//0~6553.5 amp	
-	float 				PresentChargingCurrentL3;		//0~6553.5 amp
-	char 				RemoteStartFlag;
-	unsigned char 		MaxChargingToAverPassFlag;
-	unsigned char		EVCCID[18];						//the MAC address of the EVCC in Hex
-	unsigned char 		isRemoteStart;
-	struct Schedule		schedule;						// Schedule
-	int 				EvBatteryStartSoc;				// 0~100%
-	unsigned char 		NormalStopChargeFlag;			// for EV board
-	ChargingStop        ChargingStopFlag;
-    char                ReservedStartFlag;
-    float               ConnectorMaxVoltage;            // 0~6553.5 volt
-    float               ConnectorMaxCurrent;            // 0~6553.5 volt
-    unsigned char       ModelType;
-    MeterIcCalibration  meterIcCalInfo;
-    float               PowerOffered;                   //0~6553.5 kW
-    float               CurrentOffered;                 //0~6553.5 amp
-    struct timespec     ConnectorTimeout;
-    unsigned char       PantographFlag;                 // 0: normal gun type,  1: pantograph gun type
-    unsigned char       Replug_flag;
-    unsigned char       isEVCCIDVerify;
-    unsigned char       CCSGunType;
-    struct timeval      PreChargeTimer;
-    unsigned char       _SaftyDetect;
-    unsigned char       _TotalPsuCount;                 // Psu count for connector
-    unsigned char       _TakePsuGpCount;                // Get the used psu group count
-    struct DERATING_BY_OTP deratingByConnOtp;
-};
-
-typedef struct
-{
-    unsigned char       AuthId[32];
-                                                        // 0: Authorize idle, 1: Authorize wait,   2: Authorizing
-    unsigned char       AuthStatus;                     // 3: Authorize done, 4: Authorize end
-    unsigned char       AuthTarget;                     // Authorize Target Connector ID: 1 ~ 4, AutoSelection: 0xFF
-    unsigned char       AuthType;                       // 0: _AuthType_None,   1: _AuthType_RFID, 2: _AuthType_RemoteStart
-    unsigned char       AuthResult;                     // 0: _AuthResult_None, 1: _AuthResult_Valid,   2: _AuthResult_Invalid
-    unsigned char       AuthRequest;                    // 0: no request, 1: authorize request
-    unsigned char       AuthIdType;
-}AuthorizingInfoData;
-
-typedef union
-{
-    unsigned int SettingValue;
-    struct
-    {
-        unsigned int DuplicateIp:1;
-        unsigned int DuplicateIpConfirm:1;
-        unsigned int DispenserConfigSync:1;             // 0: not synced,   1: synced
-        unsigned int MiscNeedAnnouncement:1;            // 0: no need,      1: need send misc command
-        unsigned int NeedDispenserVerInfo:1;            // 0: no need,      1: need dispenser to report it's version info
-        unsigned int AuthorizeRequest:1;                // 0: idle,         1: requesting                           ( dispenser -> cabinet)
-        unsigned int HardwareRebootConfirm:1;           // 0: no effect,    1: dispenser confirmed
-        unsigned int SoftwareResetConfirm:1;            // 0: no effect,    1: dispenser confirmed
-        unsigned int FirmwareUpdateRequest:1;           // firmware update request
-        unsigned int FirmwareUpdateConfirm:1;           // firmware update start
-        unsigned int FirmwareUpdateCompleted:1;         // firmware update completed
-        unsigned int res:21;
-    }bits;
-}DispenserSettingFlag;
-
-struct DispenserModule
-{
-    unsigned char   LocalStatus;                // 0: None, 1: Identification, 2: Idle, 3: Alarm, 4: Charging, 5: _DS_Timeout
-    unsigned char   ConnectorQuantity;          //Connector count
-    unsigned char   ConnectorID[2];             //Available Connector ID: 1 ~ 4
-    unsigned char   UserId[32];                 //the user use this ID to trigger charging event, it can be RFID card number, OCPP IdTag, etc.
-    unsigned char   ModelName[64];              //charger model name
-    unsigned char   SerialNumber[64];           //charger system serial number
-    unsigned char   SystemId[128];              //charger system ID
-    unsigned char   AuthorisationMode;          //0: enable, 1: disable
-    unsigned char   RfidCardNumEndian;          //0: little endian,  1: big endian
-    unsigned char   isAPP;                      //for AuthorisationMode=0; 0:false, 1:true
-    unsigned char   isQRCode;                   //for AuthorisationMode=0; 0:false, 1:true
-    unsigned char   isRFID;                     //for AuthorisationMode=0; 0:false, 1:true; for Noodoe Credit Card +2^1:true
-    unsigned char   QRCodeMadeMode;             //for isQRCode=1 ; 0: default	1:customized
-    unsigned char   QRCodeContent[128];         //for QRCodeMadeMode=1
-
-    unsigned char   FactoryConfiguration;       //0: normal, 1: trigger, charger will return the configuration to factory default if trigger
-    unsigned char   CsuBootLoadFwRev[32];       //CSU board bootloader firmware version
-    unsigned char   CsuKernelFwRev[32];         //CSU board OS kernel firmware version
-    unsigned char   CsuRootFsFwRev[32];         //CSU board root file system firmware version
-    unsigned char   CsuPrimFwRev[32];           //CSU board root file system firmware version
-    unsigned char   LcmFwRev[32];               //LCM module firmware version
-    unsigned char   PsuPrimFwRev[32];           //PSU primary firmware version
-    unsigned char   PsuSecFwRev[32];            //PSU secondary firmware version
-    unsigned char   FanModuleFwRev[32];         //Fan  module firmware version
-    unsigned char   RelayModuleFwRev[32];       //Relay control  module firmware version
-    unsigned char   TelcomModemFwRev[32];       //the 3G/4G modem firmware version
-    unsigned char   LedModuleFwRev[32];         //LED control module firmware version
-    unsigned char   Connector1FwRev[32];        //Connector1 module firmware version
-    unsigned char   Connector2FwRev[32];        //Connector2 module firmware version
-    struct   LED    LedInfo;                    // LED configuration info
-
-    AuthorizingInfoData     AuthInfo;
-    DispenserSettingFlag    Setting;
-    char                    FwFileName[128];
-    unsigned char           ConnectionChannel;
-};
-
-struct ConnectionInfoData
-{
-    unsigned char Status;                       // 0: free, 1: WaitModelName, 2: DispenserMatched
-    unsigned char DispenserIndex;
-    unsigned int  IpAddress;
-};
-
-struct DispenserInfoData
-{
-    unsigned char               DispenserQuantity;                  // record max dispenser quantity
-    unsigned char               TotalConnectorQuantity;             // record max connector quantity
-    struct DispenserModule      Dispenser[GENERAL_GUN_QUANTITY];
-
-    unsigned char               PresentDispenserQuantity;
-    unsigned char               PresentConnectorQuantity;
-
-    union
-    {
-        unsigned char Status;
-        struct
-        {
-            unsigned char Dispenser1:1;             // 1: ever checkin, 0: never checkin
-            unsigned char Dispenser2:1;             // 1: ever checkin, 0: never checkin
-            unsigned char Dispenser3:1;             // 1: ever checkin, 0: never checkin
-            unsigned char Dispenser4:1;             // 1: ever checkin, 0: never checkin
-            unsigned char Dispenser5:1;             // 1: ever checkin, 0: never checkin
-            unsigned char Dispenser6:1;             // 1: ever checkin, 0: never checkin
-            unsigned char Dispenser7:1;             // 1: ever checkin, 0: never checkin
-            unsigned char Dispenser8:1;             // 1: ever checkin, 0: never checkin
-        }Flag;
-    }CheckInLog;                                                        // record dispenser checkin status
-    unsigned char               ConnectorLog[GENERAL_GUN_QUANTITY];     // record connector quantity of dispenser
-    struct ConnectionInfoData   ConnectionInfo[GENERAL_GUN_QUANTITY];
-};
-
-struct WARNING_CODE_INFO
-{
-    unsigned char WarningCount;
-    unsigned char PageIndex;
-    unsigned char WarningCode[10][7];
-    unsigned char Level;
-    unsigned char ExtraErrProcess;                      // 0 : none, 1 : input uvp..
-};
-
-typedef union
-{
-    unsigned int Value;
-    struct
-    {
-        unsigned int  PermissionRequest:1;              // 0: no request,    1: dispenser request to charging                   ( dispenser -> cabinet)
-        unsigned int  RemoteStartConfirm:1;
-        unsigned int  RemoteStopConfirm:1;
-        unsigned int  UnlockStopConfirm:1;
-        unsigned int  TimeoutStopRequest:1;             // 0: no request,    1: ethernet timeout stop                           ( dispenser -> cabinet)
-        unsigned int  PsuReleasable:1;
-        unsigned int  AnnounceBalance:1;                //
-        unsigned int  StartWaitPlug:1;                  //
-        unsigned int  NeedCleanAuthorizeInfo:1;         //
-        unsigned int  SwipeRfidConfirm:1;
-        unsigned int  OutputLimitEnable:1;              // 0: disable,      1: enable
-        unsigned int  ChargingPermission:2;             // 0: not allowed,  1: allowed,         2: wait
-        unsigned int  NormalStopRequest:1;              // 0: no effect,    1: connector normal stop request                    ( dispenser -> cabinet)
-        unsigned int  AlarmStopRequest:1;               // 0: no effect,    1: connector alarm stop request                     ( dispenser -> cabinet)
-        unsigned int  FaultStatusRequest:1;
-        unsigned int  Disconnection:1;
-        unsigned int  GfdDetection:1;                   // 0: stop,         1: start
-        unsigned int  GetStartChargingSoc:1;            // 0: no effect,    1: get start soc
-        unsigned int  res:13;
-    }bits;
-}ConnectorParameter;
-
-struct ConnectorInfoData
-{
-    unsigned char RemoteStatus;                         // 0: Idle, 1: Preparing, 2: Charging, 3: Terminating, 4: Alarm
-    unsigned char Enable;                               // 0: Disable, 1: Enable
-    unsigned char ReadyToCharge;                        // 0: Not Ready, 1: Ready to Charge (no use)
-    unsigned char ParentDispensetIndex;                 // Parent Dispenser Index: 0 ~ 3
-    ConnectorParameter       Parameter;
-
-    AuthorizingInfoData      AuthInfo;
-    struct ChargingInfoData  GeneralChargingData;
-    struct WARNING_CODE_INFO WarningInfo;
-
-    unsigned char           RemotenAlarmCode[7];
-    unsigned short          RemoteChargingVoltage;          // charging voltage from connector, unit: 0.1V
-    unsigned short          RemoteChargingCurrent;          // charging current from connector, unit: 0.1A
-    unsigned int            RemoteRemainChargingDuration;   // remain charging duration from connector, unit: 1s
-    unsigned char           RemoteSoc;                      // ev battery soc from connector, unit: 1%
-
-    unsigned short          RemoteMaxPhysicalVoltage;       // max physical voltage from connector, unit: 0.1V
-    unsigned short          RemoteMaxPhysicalCurrent;       // max physical current from connector, unit: 0.1A
-    unsigned short          RemoteTargetVoltage;            // target voltage from connector, unit: 0.1V
-    unsigned short          RemoteTargetCurrent;            // target current from connector, unit: 0.1A
-    unsigned short          RemoteLimitVoltage;             // limit voltage to psu voltage command, unit: 0.1V
-    unsigned short          RemoteLimitCurrent;             // limit current to psu current command, unit: 0.1A
-
-    unsigned short          MaxTotalChargingCurrent;        // max total output current, unit: 0.1A
-    unsigned short          MaxTotalChargingPower;          // max total output power, unit: 0.1kw
-    unsigned short          MaxOutputEnergy;                // 0: no limit,  1 ~ 65535   kWh
-    unsigned short          MaxOutputDuration;              // 0: no limit,  1 ~ 65535   minutes
-    float                   CapabilityVoltage;              // unit 0.1V
-    float                   CapabilityCurrent;              // unit 0.1A
-    float                   CapabilityPower;                // unit 0.1kW
-
-    float                   UserPrice;                      // connector user's user price, unit: 1 (dollar / kWh)
-    float                   TotalCost;                      // connector user's total cost, unit: 1 dollar
-    float                   AccountBalance;                 // connector user's account balance, unit: 1 dollar
-    float                   CostDiscount;                   // connector user's Discount or couponPoint, unit: 1 point
-    float                   EnergyCost;                     // connector user's energy cost, unit: 1 dollar
-    float                   ParkingFee;                     // connector user's parking fee, unit: 1 dollar
-    float                   RemainAmount;                   // connector user's remain amount, unit: 1 dollar
-};
-
-typedef union
-{
-    unsigned int SettingValue;
-    struct
-    {
-        unsigned int res:32;
-    }bits;
-}CabinetSettingFlag;
-
-struct DC_METER_INFO
-{
-    double presetVoltage;						// resolution: 1.000v
-	double presentCurrent;					// resolution: 1.000a
-	double presentPower;						// resolution: 1.000kw
-	double totlizeImportEnergy;			// resolution: 1.000kwh
-	double totlizeExportEnergy;			// resolution: 1.000kwh
-	unsigned char timestamp[32];
-	unsigned char LinkStatus;								// 0 = unknow ,1 = link , 2 miss link
-};
-
-typedef union
-{
-		unsigned char Status;
-        struct
-        {
-	    			unsigned char suLinkStatusIsOk:1;
-            unsigned char muFatalErrorOccured:1;
-            unsigned char transactionIsOnGoing:1;
-            unsigned char tamperingIsDetected:1;
-            unsigned char timeSyncStatusIsOk:1;
-            unsigned char overTemperatureIsDetected:1;
-            unsigned char reversedVoltage:1;
-            unsigned char suMeasureFailureOccurred:1;
-        }bits;
-        
-}DcmbStatusFlag;
-
-typedef union
-{
-        unsigned char Errors;
-        struct
-        {
-            unsigned char muInitIsFailed:1;
-            unsigned char suStateIsInvalid:1;
-            unsigned char versionCheckIsFailed:1;
-            unsigned char muRngInitIsFailed:1;
-            unsigned char muDataIntegrityIsFailed:1;
-            unsigned char muFwIntegrityIsFailed:1;
-            unsigned char suIntegrityIsFailed:1;
-            unsigned char logbookIntegrityIsFailed:1;
-            unsigned char logbookIsFull:1;
-            unsigned char memoryAccessIsFailed:1;
-            unsigned char muStateIsFailed:1;
-            unsigned char res:5;
-        }bits;
-        
-}DcmbErrorFlag;
-   
-struct DC_METER_STATUS_INFO
-{
-	unsigned short StatusValue;
-	DcmbStatusFlag MeterStatusFlag;
-    
-	unsigned char applicationFirmwareVersion[16];
-    unsigned char applicationFirmwareAuthTag[32];
-    unsigned char legalFirmwareVersion[16];
-    unsigned char legalFirmwareAuthTag[32];
-    unsigned char sensorFirmwareVersion[16];
-    unsigned char sensorFirmwareCrc[4];
-
-    unsigned char Systime[32];
-    unsigned char ipAddress[32];
-    unsigned char meterId[32];
-
-	unsigned short ErrorValue;
- 	DcmbErrorFlag MeterErrorFlag;
-   
-    unsigned char publicKey[140];
-    unsigned char publicKeyOcmf[200];
-    unsigned short indexOfLastTransaction;
-    unsigned short numberOfStoredTransactions;
-};
-
-struct DC_METER_TRANSACTION_HEAD
-{
-    unsigned char evseId[32];
-    unsigned char transactionId[32];
-    unsigned char clientId[32];
-    unsigned short tariffId;
-    unsigned short cableId;
-    unsigned short userData[32];
-    
-};
-
-struct DC_METER_TRANSACTION_ACTION
-{
-	struct DC_METER_TRANSACTION_HEAD head;
-	unsigned char transactionOCMF[512];
-	unsigned char OcmfInfoReady;                // 0 = nothing, 1 = ocmp info ready
-	unsigned char ActionCmd;                   // 1 = transaction Start, 2 transaction Stop, sync time
-};
-
-typedef union
-{
-				unsigned char Status;
-        struct
-        {
-	    			unsigned char intermediateRead:1;
-            unsigned char res:7;
-        }bits;
-        
-}DcmbTransactionReadlevel;
-
-struct DC_METER_TRANSACTION_RESULT
-{
-	unsigned short paginationCounter;
-	struct DC_METER_TRANSACTION_HEAD head;
-    unsigned char timestampStart[32];
-    unsigned char timestampStop[32];
-    unsigned int transactionDuration;
-    DcmbTransactionReadlevel intermediateRead;
-    unsigned int  transactionStatus;
-    unsigned char energyUnit[8];
-    double energyImport;
-    double energyImportTotalStart;
-    double energyImportTotalStop;
-    double energyExport;
-    double energyExportTotalStart;
-    double energyExportTotalStop;
-    unsigned char signature[140];
-    //unsigned char transactionOCMF[512];
-};
-
-typedef struct Bazel8Command
-{
-    unsigned char isReq:1;
-    unsigned char isRes:1;
-    unsigned char isWaitRes:1;
-    unsigned char isResultPass:1;
-} bazel8Command;
-
-typedef struct EventInfo
-{
-    int messageId;
-    char messageString[64];
-    unsigned char isGetOn:1;
-}eventInfo;
-
-typedef struct StartTxResp
-{
-    char statusCode[8];
-    char statusText[128];
-    char txnId[32];
-    unsigned char isGetOn:1;
-}startTxResp;
-
-struct BAZEL8
-{
-    eventInfo       event;
-    startTxResp     txResp;
-
-    bazel8Command   cmdPreAuth;
-};
-
-struct Enegate
-{
-    union
-    {
-        unsigned char OperationValue[CONNECTOR_QUANTITY];
-        struct
-        {
-            unsigned char isAuthorizing:1;
-            unsigned char isAuthorized:1;
-            unsigned char isAuthorizedPass:1;
-            unsigned char isSessionStopReq:1;
-            unsigned char isStopService:1;
-            unsigned char isAutoStartEnable:1;
-            unsigned char isConnectTimeout:1;
-            unsigned char :1;
-        } bits[CONNECTOR_QUANTITY];
-    }Operation;
-
-    unsigned char   serviceStartTimestamp[36];
-    unsigned char   serviceStopTimestamp[36];
-    unsigned char   isEnable:1;
-};
-
-struct SysInfoData
-{
-	/**************System***************/
-    unsigned char OcppRunningVer;           // 0: 1.6J      1:2.0
-	unsigned char BootingStatus;			// 0 : booting, 1 : Initializing Complete.
-	unsigned char AuthorizeFlag;			// 0 : None, 1 : Authorizing
-	unsigned char FactoryConfiguration;	//0: normal, 1: trigger, charger will return the configuration to factory default if trigger
-	float InputVoltageR;                    //0~655.35 volt
-	float InputVoltageS;                    //0~655.35 volt
-	float InputVoltageT;                    //0~655.35 volt
-	float InputVoltageDc;                   //0~655.35 volt
-	unsigned int SystemFanRotaSpeed;		//0 ~ 65535 RPM
-	unsigned int PsuFanRotaSpeed;			//0 ~ 65535 RPM
-	unsigned char AuxPower5V;				//0 ~ 255 volt
-	unsigned char AuxPower12V;				//0 ~ 255 volt
-	unsigned char AuxPower24V;				//0 ~ 255 volt
-	unsigned char AuxPower48V;				//0 ~ 255 volt
-	unsigned char CsuHwRev[32];			//CSU board hardware version
-	unsigned char CsuBootLoadFwRev[32];	//CSU board bootloader firmware version
-	unsigned char CsuKernelFwRev[32];//CSU board OS kernel firmware version
-	unsigned char CsuRootFsFwRev[32];//CSU board root file system firmware version
-	unsigned char CsuPrimFwRev[32];	//CSU board root file system firmware version
-	unsigned char LcmHwRev[32];	//LCM module hardware version
-	unsigned char LcmFwRev[32];	//LCM module firmware version
-	unsigned char PsuHwRev[32];		//PSU hardware version
-	unsigned char PsuPrimFwRev[32];		//PSU primary firmware version
-	unsigned char PsuSecFwRev[32];			//PSU secondary firmware version
-	unsigned char AuxPwrHwRev[32];		//Aux. power module hardware version
-	unsigned char AuxPwrFwRev[32];		//Aux. power module firmware version
-	unsigned char FanModuleHwRev[32];		//Fan  module hardware version
-	unsigned char FanModuleFwRev[32];		//Fan  module firmware version
-	unsigned char RelayModuleHwRev[32];	//Relay control  module hardware version
-	unsigned char RelayModuleFwRev[32];	//Relay control  module firmware version
-	unsigned char TelcomModemFwRev[32];	//the 3G/4G modem firmware version
-	unsigned char LedModuleFwRev[32];	//LED control module firmware version
-	unsigned char Connector1FwRev[32];	//Connector1 module firmware version
-	unsigned char Connector2FwRev[32];	//Connector2 module firmware version
-	int SystemAmbientTemp;		// -40 ~ 215 degree C
-	int SystemCriticalTemp;		// -40 ~ 215 degree C
-	int CcsConnectorTemp;		// -40 ~ 215 degree C
-	int PsuAmbientTemp;			// -40 ~ 215 degree C
-	/**************Charging***************/
-	struct ChargingInfoData 	ChademoChargingData[CHAdeMO_QUANTITY];
-	struct ChargingInfoData 	CcsChargingData[CCS_QUANTITY];
-	struct ChargingInfoData 	GbChargingData[GB_QUANTITY];
-	struct ChargingInfoData 	AcChargingData[AC_QUANTITY];
-	unsigned char CurGunSelected;
-	unsigned char CurGunSelectedByAc;
-	/**************Network***************/
-	unsigned char 		InternetConn;					//0: disconnected, 1: connected
-	/**************Backend***************/
-	unsigned char 		OcppConnStatus;					//0: disconnected, 1: connected
-    unsigned char       MaintainServerConnStatus;       //0: disconnected, 1: connected
-	char 				OrderCharging;
-    float               MaxChargingProfilePower;        // unit: 1W
-	/**************Alston***************/
-	unsigned char 		WaitForPlugit;					//0: none scan, 1: scanning
-	unsigned char 		PageIndex;						//0 : Initialize
-														//1 : idle
-														//4 : Authorizing
-														//5 : Authorizing complete
-														//6 : Authorizing fail
-														//7 : Wait for Plug
-														//8 : Pre-charge
-														//9 : Charging
-	unsigned char 		SelfTestSeq;					//
-	unsigned char 		ReAssignedFlag;					//
-	unsigned char		CanAverageCharging;
-	unsigned char 		MainChargingMode;				// 0 : Max, 1 : Average 
-	unsigned char 		BridgeRelayStatus;
-	unsigned char 		FirmwareUpdate;					// 0 : none, 1 : update.
-	unsigned char 		AcContactorStatus;				// 0: disconnected, 1: connected
-	unsigned char 	 	SystemTimeoutFlag;				// 0 : none, 1 : self test
-	struct timespec		SystemTimeoutTimer;
-	unsigned char 		SystemPage;
-	unsigned char 		ConnectorPage;
-	unsigned char		IsAlternatvieConf;				// 0 : normal, 1 : alternative
-	unsigned char		StartToChargingFlag;			// 0 : Stop, 1 : Start for modbus
-	unsigned char 		ChargerType;					// 0 : IEC, 1 : UL
-    unsigned char       ethInternetConn;                // 0 : disconnected, 1: connected
-
-    // DO360
-    unsigned char Relay2ModuleHwRev[32];	//Relay control  module hardware version
-    unsigned char Relay2ModuleFwRev[32];	//Relay control  module firmware version
-    struct DispenserInfoData DispenserInfo;
-    struct ConnectorInfoData ConnectorInfo[GENERAL_GUN_QUANTITY];
-
-    unsigned char           AuthorizedDispenser;        // record authorized dispenser index
-    unsigned char           AuthorizedTarget;           // record authorized target: 1 ~ 4, 0xFF
-    unsigned char           AuthorizedType;             // record authorized type
-    unsigned char           AuthorizedStatus;           // cabinet authorized status
-    CabinetSettingFlag      CabinetSetting;
-    struct LocalSharingInfo localSharingInfo;           // Local power sharing info structure
-    struct DC_METER_INFO    DcMeterInfo[4];
-    struct DC_METER_STATUS_INFO DcMeterStatusInfo[4];
-    struct DC_METER_TRANSACTION_ACTION DcMeterReadTransactionRecord[4];
-    struct DC_METER_TRANSACTION_ACTION DcMeterTransactionAction[4];
-    struct DC_METER_TRANSACTION_RESULT DcMeterTransactionResult[4];
-    unsigned char           OTPTemp;                    // OTP Temperature
-    unsigned char           OTPTempR;                   // OTP Recovery Temperature
-    struct LCD_OVERRIDE     LcdOveride;                 // LCD override info (no use anymore)
-    struct BAZEL8           bazel8;                     // Bazel8 payment used
-    struct Enegate          enegate;                    // Enegate payment used
-    unsigned char           PsuLostQuantity;
-};
-
-struct SysConfigAndInfo
-{
-	struct SysConfigData				SysConfig;
-	struct SysInfoData					SysInfo;
-	struct WARNING_CODE_INFO			SysWarningInfo;
-};
-
-/*
-char Currency[54][3]=
-{
-	"AED",	// - Emirati Dirham
-	"ARS",	// - Argentine Peso
-	"AUD",	// - Australian Dollar
-	"BGN",	// - Bulgarian Lev
-	"BHD",	// - Bahraini Dinar
-	"BND",	// - Bruneian Dollar
-	"BRL",	// - Brazilian Real
-	"BWP",	// - Botswana Pula
-	"CAD",	// - Canadian Dollar
-	"CHF",	// - Swiss Franc
-	"CLP",	// - Chilean Peso
-	"CNY",	// - Chinese Yuan Renminbi
-	"COP",	// - Colombian Peso
-	"CZK",	// - Czech Koruna
-	"DKK",	// - Danish Krone
-	"EUR",	// - Euro
-	"GBP",	// - British Pound
-	"HKD",	// - Hong Kong Dollar
-	"HRK",	// - Croatian Kuna
-	"HUF",	// - Hungarian Forint
-	"IDR",	// - Indonesian Rupiah
-	"ILS",	// - Israeli Shekel
-	"INR",	// - Indian Rupee
-	"IRR",	// - Iranian Rial
-	"ISK",	// - Icelandic Krona
-	"JPY",	// - Japanese Yen
-	"KRW",	// - South Korean Won
-	"KWD",	// - Kuwaiti Dinar
-	"KZT",	// - Kazakhstani Tenge
-	"LKR",	// - Sri Lankan Rupee
-	"LYD",	// - Libyan Dinar
-	"MUR",	// - Mauritian Rupee
-	"MXN",	// - Mexican Peso
-	"MYR",	// - Malaysian Ringgit
-	"NOK",	// - Norwegian Krone
-	"NPR",	// - Nepalese Rupee
-	"NZD",	// - New Zealand Dollar
-	"OMR",	// - Omani Rial
-	"PHP",	// - Philippine Peso
-	"PKR",	// - Pakistani Rupee
-	"PLN",	// - Polish Zloty
-	"QAR",	// - Qatari Riyal
-	"RON",	// - Romanian New Leu
-	"RUB",	// - Russian Ruble
-	"SAR",	// - Saudi Arabian Riyal
-	"SEK",	// - Swedish Krona
-	"SGD",	// - Singapore Dollar
-	"THB",	// - Thai Baht
-	"TRY",	// - Turkish Lira
-	"TTD",	// - Trinidadian Dollar
-	"TWD",	// - Taiwan New Dollar
-	"USD",	// - US Dollar
-	"VEF",	// - Venezuelan Bolivar
-	"ZAR"	// - South African Rand	
-};
-*/
-
-/**************************************************************************************/
-/**************************Alarm Share memory**************************************/
-/***************************************************************************************
-	Status Code	A				B					C											D	E	F
-				0: Issue		1: From EVSE 		1: Fault (unrecoverable)					001 ~ 999 serial number
-			    										e.g., hardware broken, system latch
-				1: Recovered	2: From EV			2: Alarm (recoverable)
-			   											e.g., OTP, OVP
-								3: From Backend		3: Information
-			  											e.g., swipe card to stop charging
-
-according to XXX.Revxx
-***************************************************************************************/
-/**************************************************************************************/
-/*
-char FaultStatusCode[40][6]=
-{
-	"011001",	//CHAdeMO output fuse blew
-	"011002",	//CCS output fuse blew
-	"011003",	//GB output fuse blew
-	"011004",	//RCD/CCID self-test fail
-	"011005",	//AC input contactor 1 welding
-	"011006",	//AC input contactor 1 driving fault
-	"011007",	//AC input contactor 2 welding
-	"011008",	//AC input contactor 2 driving fault
-	"011009",	//AC output relay welding
-	"011010",	//AC output relay  driving fault
-	"011011",	//CHAdeMO output relay welding
-	"011012",	//CHAdeMO output relay driving fault
-	"011013",	//CCS output relay welding
-	"011014",	//CCS output relay driving fault
-	"011015",	//GB output relay welding
-	"011016",	//GB output relay driving fault
-	"011017",	//AC connector temperature sensor broken
-	"011018",	//CHAdeMO connector temperature sensor broken
-	"011019",	//CCS connector temperature sensor broken
-	"011020",	//GB connector temperature sensor broken
-	"011021",	//WiFi module broken
-	"011022",	//3G/4G module broken
-	"011023",	//Aux. power module broken
-	"011024",	//Relay control module /smart box broken
-	"011025",	//CHAdeMO connector lock fail
-	"011026",	//GB connector lock fail
-	"011027",	//AC connector lock fail
-	"011028",	//CHAdeMO module broken
-	"011029",	//CCS module broken
-	"011030",	//GBT module broken
-	"011031",	//PSU module broken
-	"011032",	//RCD/CCID module broken
-	"011033",	//Maximum Output Current setup error
-	"011034",	//Shutter fault 
-	"011035",	//Ble module broken
-	"011036",	//Rotary switch fault
-	"011037",	//CCS liquid chiller water level fault
-	"011038",	//Chiller temperature sensor broken
-	"011039",	//Parallel relay welding
-	"011040"	//Parallel output relay driving fault
-};
-*/
-
-struct FaultCodeData
-{
-	unsigned char PreviousFaultVal[FaultCodeLength];
-	union
-	{
-		unsigned char FaultVal[FaultCodeLength];
-		struct
-		{
-			//FaultVal[0]
-		    unsigned char ChademoOutputFuseBlew:1;				//bit 0
-			unsigned char CcsOutputFuseBlew:1;					//bit 1
-			unsigned char GbOutputFuseBlew:1;   				//bit 2
-			unsigned char RcdSelfTestFail:1;					//bit 3
-			unsigned char AcInputContactor1Welding:1;			//bit 4
-			unsigned char AcInputContactor1DrivingFault:1;		//bit 5
-			unsigned char AcInputContactor2Welding:1;			//bit 6
-			unsigned char AcInputContactor2DrivingFault:1;		//bit 7
-			//FaultVal[1]
-			unsigned char AcOutputRelayWelding:1;				//bit 0
-			unsigned char AcOutputRelayDrivingFault:1;			//bit 1
-			unsigned char ChademoOutputRelayWelding:1;			//bit 2
-			unsigned char ChademoOutputRelayDrivingFault:1;		//bit 3
-			unsigned char CcsOutputRelayWelding:1;				//bit 4
-			unsigned char CcsOutputRelayDrivingFault:1;			//bit 5
-			unsigned char GbOutputRelayWelding:1;				//bit 6
-			unsigned char GbOutputRelayDrivingFault:1;			//bit 7
-			//FaultVal[2]
-			unsigned char AcConnectorTempSensorBroken:1;		//bit 0
-			unsigned char ChademoConnectorTempSensorBroken:1;	//bit 1
-			unsigned char CcsConnectorTempSensorBroken:1;		//bit 2
-			unsigned char GbConnectorTempSensorBroken:1;		//bit 3
-			unsigned char WiFiModuleBroken:1;					//bit 4
-			unsigned char Telecom4GModuleBroken:1;				//bit 5
-			unsigned char AuxPowerModuleBroken:1;				//bit 6
-			unsigned char RelayControlModuleBroken :1;			//bit 7
-			//FaultVal[3]
-			unsigned char ChademoConnectorLockFail:1;			//bit 0
-			unsigned char GbConnectorLockFail:1;				//bit 1
-			unsigned char AcConnectorLockFail:1;				//bit 2
-			unsigned char ChademoModuleBroken:1;				//bit 3
-			unsigned char CcsModuleBroken:1;					//bit 4
-			unsigned char GbModuleBroken:1;						//bit 5
-			unsigned char PsuModuleBroken:1;					//bit 6
-			unsigned char RcdCcidModuleBroken:1;				//bit 7		
-			//FaultVal[4]
-			unsigned char MaximumOutputCurrentSetupError:1;		//bit 0
-			unsigned char ShutterFault:1;						//bit 1
-			unsigned char BleModuleBroken:1;					//bit 2
-			unsigned char RotarySwitchFault:1;					//bit 3 
-			unsigned char CcsLiquidChillerWaterLevelFault:1;    //bit 4
-            unsigned char ChillerTempSensorBroken:1;            //bit 5
-            unsigned char ParallelRelayWelding:1;               //bit 6
-            unsigned char ParallelRelayDriving:1;               //bit 7
-		}bits;
-	}FaultEvents;
-};
-
-/*
-char AlarmStatusCode[160][6]=
-{
-	"012200",	//System L1 input OVP
-	"012201",	//System L2 input OVP
-	"012202",	//System L3 input OVP
-	"012203",	//System L1 input UVP
-	"012204",	//System L2 input UVP
-	"012205",	//System L3 input UVP
-	"012206",	//PSU L1 input OVP
-	"012207",	//PSU L2 input OVP
-	"012208",	//PSU L3 input OVP
-	"012209",	//PSU L1 input UVP
-	"012210",	//PSU L2 input UVP
-	"012211",	//PSU L3 input UVP
-	"012212",	//System L1 input drop
-	"012213",	//System L2 input drop
-	"012214",	//System L3 input drop
-	"012215",	//System AC output OVP
-	"012216",	//System AC output OCP L1
-	"012217",	//System CHAdeMO output OVP
-	"012218",	//System CHAdeMO output OCP
-	"012219",	//System CCS output OVP
-	"012220",	//System CCS output OCP
-	"012221",	//System GB output OVP
-	"012222",	//System GB output OCP
-	"012223",	//System ambient/inlet OTP
-	"012224",	//System critical point OTP
-	"012225",	//PSU ambient/inlet OTP
-	"012226",	//PSU critical point OTP
-	"012227",	//Aux. power module OTP
-	"012228",	//Relay board/smart box OTP
-	"012229",	//CHAdeMO connector OTP
-	"012230",	//CCS connector OTP
-	"012231",	//GB connector OTP
-	"012232",	//AC connector OTP
-	"012233",	//RCD/CCID trip
-	"012234",	//CHAdeMO GFD trip
-	"012235",	//CCS GFD trip
-	"012236",	//GB GFD trip
-	"012237",	//SPD trip
-	"012238",	//Main power breaker trip
-	"012239",	//Aux. power breaker trip
-	"012240",	//PSU communication fail
-	"012241",	//WiFi module communication fail
-	"012242",	//3G/4G module communication fail
-	"012243",	//RFID module communication fail
-	"012244",	//Bluetooth module communication fail
-	"012245",	//LCM module communication fail
-	"012246",	//Aux. power module communication fail
-	"012247",	//Relay control boaed/smart box communication fail
-	"012248",	//CCS module communication fail
-	"012249",	//CHAdeMO module communication fail
-	"012250",	//GBT module communication fail
-	"012251",	//Emergency stop
-	"012252",	//Door open
-	"012253",	//System fan decay
-	"012254",	//Fail to create share memory
-	"012255",	//CSU initialization failed
-	"012256",	//AC Ground Fault
-	"012257",	//MCU self-test Fault
-	"012258",	//Relay self-test Fault
-	"012259",	//CHAdeMO groundfault detection timeout (GFD)
-	"012260",	//CCS groundfault detection timeout (GFD)
-	"012261",	//GB groundfault detection timeout (GFD)
-	"012262",	//Circuit Short L1
-	"012263",	// PSU Duplicate ID
-	"012264", 	// Psu Fault : Infy => Output Short Circuit,UU => Abnormal discharge circuit
-	"012265", 	// PSU Discharge Abnormal
-	"012266", 	// PSU Dc Side ShutDown
-	"012267", 	// PSU Failure Alarm
-	"012268", 	// PSU Protection Alarm
-	"012269", 	// Psu Fault : Infy => Fan Fault,UU => Fan Fault
-	"012270", 	// PSU Input UVP
-	"012271",	// PSU Input OVP
-	"012272", 	// PSU WalkIn State
-	"012273", 	// Psu Fault : Infy => Power Limited State,UU => Dc OVP and shutdown
-	"012274", 	// Psu Fault : Infy => Id Repeat,UU => Id Repeat
-	"012275", 	// Psu Fault : Infy => Severe Uneven Current,UU => Pfc internal unbalance
-	"012276", 	// PSU Three Phase Input Inadequate
-	"012277", 	// PSU Three Phase Onput Imbalance
-	"012278", 	// PSU Ffc Side ShutDown
-	"012279", 	// NO PSU Resource
-	"012280", 	// Self test Failed due to communication of Relayboard failure
-	"012281", 	// Self test Failed due to communication of Fanboard failure
-	"012282", 	// Self test Failed due to communication of Primary failure
-	"012283", 	// Self test Failed due to communication of Chademoboard failure
-	"012284", 	// Self test Failed due to communication of CCSboard failure
-	"012285", 	// Self test Failed due to AC Contact failure
-	"012286", 	// Self test Failed due to communication of PSU failure
-	"012287", 	// Self test Failed due to Model name is none match
-	"012288",	// CCS output UVP
-	"012289",	// Chademo output UVP
-	"012290",	// GBT output UVP
-	"012291",	// Self test Failed due to communication of GBTboard failure
-	"012292",	// Self test Failed due to communication of AC failure
-	"012293",	// Self test Failed due to communication of Ledboard failure
-	"012294",	// Ac input OVP
-	"012295",	// Ac input UVP
-	"012296",	// CHAdeMO groundfault detection - warning
-	"012297",	// CCS groundfault detection - warning
-	"012298",	// GB groundfault detection - warning
-	"012299",	// System AC output OCP L2
-	"012300",	// System AC output OCP L3
-	"012301",	// Circuit Short L2
-	"012302",	// Circuit Short L3
-	"012303",   // CCS liquid chiller water level warning
-	"012304",   // connection disconnected from power cabinet
-	"012305",   // Meter communication timeout
-	"012306",   // The dip switch of the PSU may be incorrect
-    "012307",   // Psu Fault : Infy => Fuse Burn-Out,UU => Pfc internal OVP
-    "012308",   // Psu Fault : Infy => Pfc And Dcdc Communication Fault,UU => Pfc And Dcdc Communication Fault
-    "012309",   // Psu Fault : Infy => Bus Voltage Unbalance,UU => Dc output voltage unbalance
-    "012310",   // Psu Fault : Infy => Bus Over Voltage,UU => Ac site OVP
-    "012311",   // Psu Fault : Infy => Bus Voltage Abnormal,UU => Ac site UVP
-    "012312",   // Psu Fault : Infy => Bus Under Voltage,UU => Pfc internal UVP
-    "012313",   // Psu Fault : Infy => Input Phase Loss,UU => Dc to Dc don’t work
-    "012314",   // Psu Fault : Infy => Fan Full Speed,UU => Fan don’t work
-    "012315",   // Psu Fault : Infy => Temperature Power Limit,UU => env OTP、Pfc OTP、output relay broken、Dc OTP
-    "012316",   // Psu Fault : Infy => Ac Power Limit,UU => Ac OVP and shutdown
-    "012317",   // Psu Fault : Infy => Dcdc Eeprom Fault,UU => Dc to Dc broken
-    "012318",   // Psu Fault : Infy => Pfc Eeprom Fault,UU => Pfc broken
-    "012319",   // Psu Dcdc Over Voltage
-    "012320",   // System CHAdeMO output UCP
-    "012321",   // System CCS output UCP
-    "012322",   // System GBT output UCP
-    "012323",   // System Chiller output OTP
-    "012324",   // Connector 1 detects abnormal voltage on the output line
-    "012325",   // Connector 2 detects abnormal voltage on the output line
-    "012326",   // System task is lost
-    "012327",   // System DC input ovp
-    "012328",   // System DC input uvp
-    "012329",   // Psu Fault : Infy => Psu Can Communication Fault,UU =>
-    "012330",   // Psu Fault : Infy => Psu Dc to Dc OTP,UU => env UTP
-    "012331",   // Psu Fault : Infy => Psu Dc to Dc OVP,UU => Dc output OVP
-    "012332",   // Chiller Tube OTP
-    "012333",   // Psu Fault : Infy => DC input ovp (Phase OVP),UU => Dc output UVP
-    "012334",   // reserved
-    "012335",   // reserved
-    "012336",   // reserved
-    "012337",   // reserved
-    "012338",   // reserved
-    "012339",   // reserved
-    "012340",   // reserved
-    "012341",   // reserved
-    "012342",   // reserved
-    "012343",   // Tilt sensor self-test failed
-    "012344",   // AC: Meter IC communication timeout
-    "012345",   // AC: Pilot negative error
-    "012346",   // Psu Communication error with CSU
-    "012347",   // AC: Local power sharing communication error (Slave disconnect from Master)
-    "012348",   // Chiller Alarm failure
-    "012349",   // reserved
-    "012350",   // reserved
-    "012351",   // reserved
-    "012352",   // Payment system communication timeout
-    "012353",   // reserved
-    "012354",   // reserved
-    "012355",   // reserved
-    "012356",   // reserved
-    "012357",   // reserved
-    "012358",   // reserved
-    "012359",   // reserved
-};
-*/
-struct AlarmCodeData
-{
-	unsigned char PreviousAlarmVal[AlarmCodeLength];
-	union
-	{
-		unsigned char AlarmVal[AlarmCodeLength];
-		struct
-		{
-			//AlarmVal[0]
-		    unsigned char SystemL1InputOVP:1;					//bit 0
-			unsigned char SystemL2InputOVP:1;					//bit 1
-			unsigned char SystemL3InputOVP:1;   				//bit 2
-			unsigned char SystemL1InputUVP:1;					//bit 3
-			unsigned char SystemL2InputUVP:1;					//bit 4
-			unsigned char SystemL3InputUVP:1;					//bit 5
-			unsigned char PsuL1InputOVP:1;						//bit 6
-			unsigned char PsuL2InputOVP:1;						//bit 7
-			//AlarmVal[1]
-			unsigned char PsuL3InputOVP:1;						//bit 0
-			unsigned char PsuL1InputUVP:1;						//bit 1
-			unsigned char PsuL2InputUVP:1;						//bit 2
-			unsigned char PsuL3InputUVP	:1;						//bit 3
-			unsigned char SystemL1InputDrop:1;					//bit 4
-			unsigned char SystemL2InputDrop:1;					//bit 5
-			unsigned char SystemL3InputDrop:1;					//bit 6
-			unsigned char SystemAcOutputOVP:1;					//bit 7
-			//AlarmVal[2]
-			unsigned char SystemAcOutputOCP:1;					//bit 0
-			unsigned char SystemChademoOutputOVP:1;				//bit 1
-			unsigned char SystemChademoOutputOCP:1;				//bit 2
-			unsigned char SystemCcsOutputOVP:1;					//bit 3
-			unsigned char SystemCcsOutputOCP:1;					//bit 4
-			unsigned char SystemGbOutputOVP:1;					//bit 5
-			unsigned char SystemGbOutputOCP:1;					//bit 6
-			unsigned char SystemAmbientOTP :1;					//bit 7
-			//AlarmVal[3]
-			unsigned char SystemCriticalPointOTP:1;				//bit 0
-			unsigned char PsuAmbientOTP:1;						//bit 1
-			unsigned char PsuCriticalPointOTP:1;				//bit 2
-			unsigned char AuxPowerModuleOTP:1;					//bit 3
-			unsigned char RelayBoardOTP:1;						//bit 4
-			unsigned char ChademoConnectorOTP:1;				//bit 5
-			unsigned char CcsConnectorOTP:1;					//bit 6
-			unsigned char GbConnectorOTP:1;						//bit 7
-			 //AlarmVal[4]
-			unsigned char AcConnectorOTP:1;						//bit 0
-			unsigned char RcdTrip:1;							//bit 1
-			unsigned char ChademoGfdTrip:1;						//bit 2
-			unsigned char CcsGfdTrip:1;							//bit 3
-			unsigned char GbGfdTrip:1;							//bit 4
-			unsigned char SpdTrip:1;							//bit 5
-			unsigned char MainPowerBreakerTrip:1;				//bit 6
-			unsigned char AuxPowerBreakerTrip:1;				//bit 7
-			//AlarmVal[5]
-			unsigned char PsuCommunicationFail:1;				//bit 0
-			unsigned char WiFiModuleCommFail:1;					//bit 1
-			unsigned char Telecom4GModuleCommFail:1;			//bit 2
-			unsigned char RfidModuleCommFail:1;					//bit 3
-			unsigned char BluetoothModuleCommFail:1;			//bit 4
-			unsigned char LcmModuleCommFail:1;					//bit 5
-			unsigned char AuxPowerModuleCommFail:1;				//bit 6
-			unsigned char RelayBoardCommFail:1;					//bit 7
-			//AlarmVal[6]
-			unsigned char CcsModuleCommFail:1;					//bit 0
-			unsigned char ChademoModuleCommFail:1;				//bit 1
-			unsigned char GbModuleCommFail:1;					//bit 2
-			unsigned char EmergencyStopTrip:1;					//bit 3
-			unsigned char DoorOpen:1;							//bit 4
-			unsigned char SystemFanDecay:1;						//bit 5
-			unsigned char FailToCreateShareMemory:1;			//bit 6
-			unsigned char CsuInitFailed:1;						//bit 7
-			//AlarmVal[7]
-			unsigned char AcGroundfaultFail:1;					//bit 0
-			unsigned char McuSelftestFail:1;					//bit 1
-			unsigned char RelaySelftestFail:1;					//bit 2
-			unsigned char ChademoGroundfaultTimeout:1;			//bit 3
-			unsigned char CcsGroundfaultTimeout:1;				//bit 4
-			unsigned char GbGroundfaultTimeout:1;				//bit 5
-			unsigned char CircuitShort:1;						//bit 6
-			unsigned char PsuDuplicateID:1;						//bit 7
-			//AlarmVal[8]
-			unsigned char PsuOutputShortCircuit :1;				//bit 0
-			unsigned char PsuDischargeAbnormal :1;				//bit 1
-			unsigned char PsuDcSideShutDown :1;					//bit 2
-			unsigned char PsuFailureAlarm :1;					//bit 3
-			unsigned char PsuProtectionAlarm :1;				//bit 4
-			unsigned char PsuFanFailureAlarm :1;				//bit 5
-			unsigned char PsuInputUVP:1;						//bit 6
-			unsigned char PsuInputOVP:1;						//bit 7
-			//AlarmVal[9]
-			unsigned char PsuWalkInState :1;					//bit 0
-			unsigned char PsuPowerLimitedState :1;				//bit 1
-			unsigned char PsuIdRepeat :1;						//bit 2
-			unsigned char PsuSevereUnevenCurrent :1;			//bit 3
-			unsigned char PsuThreePhaseInputInadequate :1;		//bit 4
-			unsigned char PsuThreePhaseOnputImbalance :1;		//bit 5
-			unsigned char PsuFfcSideShutDown :1;				//bit 6
-			unsigned char PsuNoResource:1;						//bit 7
-			//AlarmVal[10]
-			unsigned char RelayboardStestFail :1;				//bit 0
-			unsigned char FanboardStestFail :1;					//bit 1
-			unsigned char PrimaryStestFail :1;					//bit 2
-			unsigned char ChademoboardStestFail :1;				//bit 3
-			unsigned char CCSboardStestFail :1;					//bit 4
-			unsigned char AcContactStestFail :1;				//bit 5
-			unsigned char PsuModuleStestFail :1;				//bit 6
-			unsigned char ModelNameNoneMatchStestFail:1;		//bit 7	
-			//AlarmVal[11]
-			unsigned char CcsOutputUVPFail :1;					//bit 0
-			unsigned char ChademoOutputUVPFail :1;				//bit 1
-			unsigned char GbtOutputUVPFail :1;					//bit 2
-			unsigned char GbtboardStestFail :1;					//bit 3
-			unsigned char AcConnectorStestFail:1;				//bit 4
-			unsigned char LedboardStestFail:1;					//bit 5
-			unsigned char AcSystemInputOVP:1;					//bit 6
-			unsigned char AcSystemInputUVP:1;					//bit 7
-			//AlarmVal[12]
-			unsigned char ChademoGroundWarning :1;					//bit 0
-			unsigned char CcsGroundfaultWarning :1;					//bit 1
-			unsigned char GbGroundfaultWarning :1;					//bit 2
-			unsigned char SystemAcOutputOCPL2:1;					//bit 3
-			unsigned char SystemAcOutputOCPL3:1;					//bit 4
-			unsigned char CircuitShortL2:1;							//bit 5
-			unsigned char CircuitShortL3:1;							//bit 6
-			unsigned char CcsLiquidChillerWaterLevelWarning:1;      //bit 7
-			//AlarmVal[13]
-            unsigned char DisconnectedFromDo:1;                     //bit 0
-            unsigned char MeterCommTimeout:1;                       //bit 1
-            unsigned char PsuDipSwitchStestFail:1;                  //bit 2
-            unsigned char PsuFuseBurnOut:1;                         //bit 3
-            unsigned char PsuPfcAndDcdcCommFault:1;                 //bit 4
-            unsigned char PsuBusVoltageUnbalance:1;                 //bit 5
-            unsigned char PsuBusOverVoltage:1;                      //bit 6
-            unsigned char PsuBusVoltageAbnormal:1;                  //bit 7
-            //AlarmVal[14]
-            unsigned char PsuBusUnderVoltage:1;                     //bit 0
-            unsigned char PsuInputPhaseLoss:1;                      //bit 1
-            unsigned char PsuFanFullSpeed:1;                        //bit 2
-            unsigned char PsuTemperaturePowerLimit:1;               //bit 3
-            unsigned char PsuAcPowerLimit:1;                        //bit 4
-            unsigned char PsuDcdcEepromFault:1;                     //bit 5
-            unsigned char PsuPfcEepromFault:1;                      //bit 6
-            unsigned char PsuDcdcOverVoltage:1;                     //bit 7
-            //AlarmVal[15]
-            unsigned char SystemChademoOutputUCP:1;                 //bit 0
-            unsigned char SystemCCSOutputUCP:1;                     //bit 1
-            unsigned char SystemGBTOutputUCP:1;                     //bit 2
-            unsigned char SystemChillerOTP:1;                       //bit 3
-            unsigned char AbnormalVoltageOnOutputLine_1:1;          //bit 4
-            unsigned char AbnormalVoltageOnOutputLine_2:1;          //bit 5
-            unsigned char SystemTaskLost:1;                         //bit 6
-            unsigned char DcInputOVP:1;                             //bit 7
-            //AlarmVal[16]
-            unsigned char DcInputUVP:1;                             //bit 0
-            unsigned char PsuCanCommFault:1;                        //bit 1
-            unsigned char PsuDcDcOtp:1;                             //bit 2
-            unsigned char PsuDcDcOvp:1;                             //bit 3
-            unsigned char ChillerTubeOTP : 1;                       //bit 4
-            unsigned char PsuPhaseOvp:1;                            //bit 5
-            unsigned char :2;                                       //reserved bit 6 ~ bit 7
-            //AlarmVal[17]
-            unsigned char :7;                                       //reserved bit 0 ~ bit 6
-            unsigned char TiltSensorStestFail:1;                    //reserved bit 7
-            //AlarmVal[18]
-            unsigned char MeterIcCommTimeout:1;                     //bit 0
-            unsigned char PilotNegativeError:1;                     //bit 1
-            unsigned char PsuComminicationErrWithCSU:1;             //bit 2
-            unsigned char LocalPowerSharingCommunicationError:1;    //bit 3
-            unsigned char ChillerAlarmFail:1;                       //bit 4
-			unsigned char :3;                                       //reserved bit 4 ~ bit 7
-            //AlarmVal[19]
-            unsigned char PaymentCommTimeout:1;                     //Payment system communication timeout
-           	unsigned char MeterSlaveLosLink:1;                     	//DCMB meter slave module los link
-            unsigned char MeterSyncTimeError:1;            					//DCMB meter Sync Time Error
-            unsigned char MetertStartTransactionError:1;            //DCMB meter Start Transaction Error
-            unsigned char MetertStopTransactionError:1;             //DCMB meter Stop Transaction Error
-            unsigned char MetertGetTransactionOcmfError:1;          //DCMB meter Get OCMF Error        	
-            unsigned char :2;                                       //reserved bit 1 ~ bit 7
-		}bits;
-	}AlarmEvents;
-};
-
-/*
-char InfoStatusCode[384][6]=
-{
-	//Information comes from EVSE
-	"013600",	//Normal stop charging by user
-	"013601",	//Charging Time's up
-	"013602",	//Replace system air filter
-	"013603",	//Reach to CHAdeMO max. plugging times.
-	"013604",	//Reach to CCS max. plugging times.
-	"013605",	//Reach to GB max. plugging times.
-	"013606",	//Reach to AC max. plugging times.
-	"013607",	//CSU fimrware update fail
-	"013608",	//CHAdeMO Module fimrware update fail
-	"013609",	//CCS Module fimrware update fail
-	"013610",	//GB Module fimrware update fail
-	"013611",	//Aux. power module fimrware update fail
-	"013612",	//Relay control module fimrware update fail
-	"013613",	//LCM module fimrware update fail
-	"013614",	//Bluetooth module fimrware update fail
-	"013615",	//WiFi module fimrware update fail
-	"013616",	//3G/4G module fimrware update fail
-	"013617",	//SMR fimrware update fail
-	"013618",	//RFID module fimrware update fail
-	"013619",	//configured by USB flash drive
-	"013620",	//configured by backend
-	"013621",	//configured by webpage
-	"013622",	//disconnected from Internet through Ethernet
-	"013623",	//disconnected from Internet through WiFi
-	"013624",	//disconnected from Internet through 3G/4G
-	"013625",	//disconnected from AP through WiFi
-	"013626",	//disconnected from APN through 3G/4G
-	"013627",	//WiFi disabled (separated charger only)
-	"013628",	//4G disabled (separated charger only)
-	"013629",	//Psu Quantity Not Match
-	"013630",	//Reserved
-	"013631",	//Reserved
-	//Information comes from EV
-	"023700",	//CHAdeMO EV communication Fail
-	"023701",	//CCS EV communication Fail
-	"023702",	//GB EV communication Fail
-	"023703",	//AC: pilot fault
-	"023704",	//CHAdeMO:  battery malfunction
-	"023705",	//CHAdeMO:  no charging permission
-	"023706",	//CHAdeMO:  battery incompatibility
-	"023707",	//CHAdeMO:  battery OVP
-	"023708",	//CHAdeMO:  battery UVP
-	"023709",	//CHAdeMO:  battery OTP
-	"023710",	//CHAdeMO:  battery current difference
-	"023711",	//CHAdeMO:  battery voltage difference
-	"023712",	//CHAdeMO:  shift position
-	"023713",	//CHAdeMO:  battery other fault
-	"023714",	//CHAdeMO:  charging system error
-	"023715",	//CHAdeMO:  EV normal stop
-	"023716",	//CHAdeMO:  connector temperature sensor broken
-	"023717",	//CHAdeMO:  connector lock fail
-	"023718",	//CHAdeMO:	D1 ON No Receive
-	"023719",	//CHAdeMO:	Permission ON but charge sequence timeout
-	"023720",	//CHAdeMO:	BMS Charge Allow Timeout
-	"023721",	//CHAdeMO:	Wait GroundFault Timeout
-	"023722",	//CHAdeMO:	BMS EV Relay Timeout
-	"023723",	//CHAdeMO:	BMS Request Current Timeout
-	"023724",	//CHAdeMO:	BMS K to J OFF Timeout
-	"023725",	//CHAdeMO:	BMS EV Relay OFF Timeout
-	"023726",	//CHAdeMO:	ADC More Than 10V
-	"023727",	//CHAdeMO:	ADC More Than 20V
-	"023728",	//CHAdeMO:	BMS Charge Before Stop
-	"023729",	//CHAdeMO:	Charger Get Normal Stop
-	"023730",	//CHAdeMO:	Charger Get Emergency Stop
-	"023731",	//CHAdeMO:  Isolation Result Fail
-	"023732",	//CHAdeMO: 	Miss Link With MotherBoard
-	"023733",	//CHAdeMO:	Output Voltage More Than Limit
-	"023734",	//CHAdeMO:	Request Current More Than Limit
-	"023735",	//CHAdeMO: 	Re Cap BMS Eqr Current Exceed
-	"023736",	//CHAdeMO:	Charge Remain Count Down
-	"023737",	//CCS:CCS_EVCC_EVErrorCode_FAILED_RESSTemperatureInhibit
-	"023738",	//CCS:CCS_EVCC_EVErrorCode_FAILED_EVShiftPosition
-	"023739",	//CCS:CCS_EVCC_EVErrorCode_FAILED_ChargerConnectorLockFault
-	"023740",	//CCS:CCS_EVCC_EVErrorCode_FAILED_EVRESSMalfunction
-	"023741",	//CCS:CCS_EVCC_EVErrorCode_FAILED_ChargingCurrentdifferential
-	"023742",	//CCS:CCS_EVCC_EVErrorCode_FAILED_ChargingVoltageOutOfRange
-	"023743",	//CCS:CCS_EVCC_EVErrorCode_FAILED_ChargingSystemIncompatibility
-	"023744",	//CCS:CCS_EVCC_EVErrorCode_FAILED_EmergencyEvent
-	"023745",	//CCS:CCS_EVCC_EVErrorCode_FAILED_Breaker
-	"023746",	//CCS:CCS_EVCC_EVErrorCode_FAILED_NoData
-	"023747",	//CCS:CCS_EVCC_EVErrorCode_FAILED_reserved_by_DIN_A
-	"023748",	//CCS:CCS_EVCC_EVErrorCode_FAILED_reserved_by_DIN_B
-	"023749",	//CCS:CCS_EVCC_EVErrorCode_FAILED_reserved_by_DIN_C
-	"023750",	//CCS:CCS_EVCC_EVErrorCode_FAILED_reserved_by_ISO_1
-	"023751",	//CCS:CCS_EVCC_EVErrorCode_FAILED_reserved_by_ISO_2
-	"023752",	//CCS:CCS_EVCC_EVErrorCode_FAILED_reserved_by_ISO_3
-	"023753",	//CCS:CCS_EVCC_EVErrorCode_FAILED_reserved_by_OEM_1
-	"023754",	//CCS:CCS_EVCC_EVErrorCode_FAILED_reserved_by_OEM_2
-	"023755",	//CCS:CCS_EVCC_EVErrorCode_FAILED_reserved_by_OEM_3
-	"023756",	//CCS:CCS_EVCC_EVErrorCode_FAILED_reserved_by_OEM_4
-	"023757",	//CCS:CCS_EVCC_EVErrorCode_FAILED_reserved_by_OEM_5
-	"023758",	//CCS:CCS_SECC_ResponseCode_FAILED_SequenceError
-	"023759",	//CCS:CCS_SECC_ResponseCode_FAILED_SignatureError
-	"023760",	//CCS:CCS_SECC_ResponseCode_FAILED_UnknownSession
-	"023761",	//CCS:CCS_SECC_ResponseCode_FAILED_ServiceIDInvalid
-	"023762",	//CCS:CCS_SECC_ResponseCode_FAILED_Payment SelectionInvalid
-	"023763",	//CCS:CCS_SECC_ResponseCode_FAILED_IdentificationSelectionInvalid
-	"023764",	//CCS:CCS_SECC_ResponseCode_FAILED_ServiceSelectionInvalid
-	"023765",	//CCS:CCS_SECC_ResponseCode_FAILED_CertificateExpired
-	"023766",	//CCS:CCS_SECC_ResponseCode_FAILED_CertificateNotYetValid
-	"023767",	//CCS:CCS_SECC_ResponseCode_FAILED_CertificateRevoked
-	"023768",	//CCS:CCS_SECC_ResponseCode_FAILED_NoCertificateAvailable
-	"023769",	//CCS:CCS_SECC_ResponseCode_FAILED_CertChainError
-	"023770",	//CCS:CCS_SECC_ResponseCode_FAILED_CertValidationError
-	"023771",	//CCS:CCS_SECC_ResponseCode_FAILED_CertVerificationError
-	"023772",	//CCS:CCS_SECC_ResponseCode_FAILED_ContractCanceled
-	"023773",	//CCS:CCS_SECC_ResponseCode_FAILED_ChallengeInvalid
-	"023774",	//CCS:CCS_SECC_ResponseCode_FAILED_WrongEnergyTransferMode
-	"023775",	//CCS:CCS_SECC_ResponseCode_FAILED_WrongChargeParameter
-	"023776",	//CCS:CCS_SECC_ResponseCode_FAILED_ChargingProfileInvalid
-	"023777",	//CCS:CCS_SECC_ResponseCode_FAILED_TariffSelectionInvalid
-	"023778",	//CCS:CCS_SECC_ResponseCode_FAILED_EVSEPresentVoltageToLow
-	"023779",	//CCS:CCS_SECC_ResponseCode_FAILED_PowerDeliveryNotApplied
-	"023780",	//CCS:CCS_SECC_ResponseCode_FAILED_MeteringSignatureNotValid
-	"023781",	//CCS:CCS_SECC_ResponseCode_FAILED_NoChargeServiceSelected
-	"023782",	//CCS:CCS_SECC_ResponseCode_FAILED_ContactorError
-	"023783",	//CCS:CCS_SECC_ResponseCode_FAILED_CertificateNotAllowedAtThisEVSE
-	"023784",	//CCS:CCS_SECC_ResponseCode_FAILED_GAChargeStop
-	"023785",	//CCS:CCS_SECC_ResponseCode_FAILED_AlignmentError
-	"023786",	//CCS:CCS_SECC_ResponseCode_FAILED_ACDError
-	"023787",	//CCS:CCS_SECC_ResponseCode_FAILED_AssociationError
-	"023788",	//CCS:CCS_SECC_ResponseCode_FAILED_EVSEChargeAbort
-	"023789",	//CCS:CCS_SECC_ResponseCode_FAILED_NoSupportedApp-Protocol-Protocol
-	"023790",	//CCS:CCS_SECC_ResponseCode_FAILED_ContractNotAccepted
-	"023791",	//CCS:CCS_SECC_ResponseCode_FAILED_MOUnknown
-	"023792",	//CCS:CCS_SECC_ResponseCode_FAILED_OEM_Prov_CertificateRevoke
-	"023793",	//CCS:CCS_SECC_ResponseCode_FAILED_OEM_SubCA1_CertificateRevoked
-	"023794",	//CCS:CCS_SECC_ResponseCode_FAILED_OEM_SubCA2_CertificateRevoked
-	"023795",	//CCS:CCS_SECC_ResponseCode_FAILED_OEM_RootCA_CertificateRevoked
-	"023796",	//CCS:CCS_SECC_ResponseCode_FAILED_MO_Prov_CertificateRevoked
-	"023797",	//CCS:CCS_SECC_ResponseCode_FAILED_MO_SubCA1_CertificateRevoked
-	"023798",	//CCS:CCS_SECC_ResponseCode_FAILED_MO_SubCA2_CertificateRevoked
-	"023799",	//CCS:CCS_SECC_ResponseCode_FAILED_MO_RootCA_CertificateRevoked
-	"023800",	//CCS:CCS_SECC_ResponseCode_FAILED_CPS_Prov_CertificateRevoked
-	"023801",	//CCS:CCS_SECC_ResponseCode_FAILED_CPS_SubCA1_CertificateRevoked
-	"023802",	//CCS:CCS_SECC_ResponseCode_FAILED_CPS_SubCA2_CertificateRevoked
-	"023803",	//CCS:CCS_SECC_ResponseCode_FAILED_CPS_RootCA_CertificateRevoked
-	"023804",	//CCS:CCS_SECC_ResponseCode_FAILED_reserved_1
-	"023805",	//CCS:CCS_SECC_ResponseCode_FAILED_reserved_2
-	"023806",	//CCS:CCS_SECC_ResponseCode_FAILED_reserved_3
-	"023807",	//CCS:CCS_SECC_ResponseCode_FAILED_reserved_4
-	"023808",	//CCS:CCS_SECC_ResponseCode_FAILED_reserved_5
-	"023809",	//CCS:CCS_SECC_TIMEOUT_SLAC_TT_EVSE_SLAC_init
-	"023810",	//CCS:CCS_SECC_TIMEOUT_SLAC_TP_match_response
-	"023811",	//CCS:CCS_SECC_TIMEOUT_CM_START_ATTEN_CHAR_IND
-	"023812",	//CCS:CCS_SECC_TIMEOUT_SLAC_TT_EVSE_match_MNBC
-	"023813",	//CCS:CCS_SECC_TIMEOUT_SLAC_TP_EVSE_avg_atten_calc
-	"023814",	//CCS:CCS_SECC_TIMEOUT_SLAC_CM_ATTEN_CHAR_RSP
-	"023815",	//CCS:CCS_SECC_TIMEOUT_SLAC_CM_VALIDATE_REQ_1ST__CM_SLAC_MATCH_REQ
-	"023816",	//CCS:CCS_SECC_TIMEOUT_SLAC_TT_EVSE_assoc_session
-	"023817",	//CCS:CCS_SECC_TIMEOUT_SLAC_TT_EVSE_vald_toggle
-	"023818",	//CCS:CCS_SECC_TIMEOUT_SLAC_CM_MNBC_SOUND_IND
-	"023819",	//CCS:CCS_SECC_TIMEOUT_SLAC_CM_VALIDATE_REQ_2ND__CM_SLAC_MATCH_REQ
-	"023820",	//CCS:CCS_SECC_TIMEOUT_SLAC_reserved_3
-	"023821",	//CCS:CCS_SECC_TIMEOUT_SLAC_reserved_4
-	"023822",	//CCS:CCS_SECC_TIMEOUT_SLAC_reserved_5
-	"023823",	//CCS:CCS_SECC_TIMEOUT_SLACC_SDP_UDP_TT_match_join
-	"023824",	//CCS:CCS_SECC_TIMEOUT_SLACC_SDP_TCP_TT_match_join
-	"023825",	//CCS:CCS_SECC_TIMEOUT_SLACC_SDP_TP_amp_map_exchange
-	"023826",	//CCS:CCS_SECC_TIMEOUT_SLACC_SDP_TP_link_ready_notification
-	"023827",	//CCS:CCS_SECC_TIMEOUT_SLACC_SDP_reserved_1
-	"023828",	//CCS:CCS_SECC_TIMEOUT_SLACC_SDP_reserved_2
-	"023829",	//CCS:CCS_SECC_TIMEOUT_SLACC_SDP_reserved_3
-	"023830",	//CCS:CCS_SECC_TIMEOUT_SLACC_SDP_reserved_4
-	"023831",	//CCS:CCS_SECC_TIMEOUT_SLACC_SDP_reserved_5
-	"023832",	//CCS:CCS_SECC_TIMEOUT_V2G_Msg_Performance_Time_SupportedAppProtocolRes
-	"023833",	//CCS:CCS_SECC_TIMEOUT_V2G_Msg_Performance_Time_SessionSetupRes
-	"023834",	//CCS:CCS_SECC_TIMEOUT_V2G_Msg_Performance_Time_ServiceDiscoveryRes
-	"023835",	//CCS:CCS_SECC_TIMEOUT_V2G_Msg_Performance_Time_ServicePaymentSelectionRes
-	"023836",	//CCS:CCS_SECC_TIMEOUT_V2G_Msg_Performance_Time_ContractAuthenticationRes
-	"023837",	//CCS:CCS_SECC_TIMEOUT_V2G_Msg_Performance_Time_ChargeParameterDiscoveryRes
-	"023838",	//CCS:CCS_SECC_TIMEOUT_V2G_Msg_Performance_Time_PowerDeliveryRes
-	"023839",	//CCS:CCS_SECC_TIMEOUT_V2G_Msg_Performance_Time_CableCheckRes
-	"023840",	//CCS:CCS_SECC_TIMEOUT_V2G_Msg_Performance_Time_PreChargeRes
-	"023841",	//CCS:CCS_SECC_TIMEOUT_V2G_Msg_Performance_Time_CurrentDemandRes
-	"023842",	//CCS:CCS_SECC_TIMEOUT_V2G_Msg_Performance_Time_WeldingDetectionRes
-	"023843",	//CCS:CCS_SECC_TIMEOUT_V2G_Msg_Performance_Time_SessionStopRes
-	"023844",	//CCS:CCS_SECC_TIMEOUT_V2G_Sequence_Time
-	"023845",	//CCS:CCS_SECC_TIMEOUT_V2G_ReadyToCharge_Performance_Time
-	"023846",	//CCS:CCS_SECC_TIMEOUT_V2G_CommunicationSetup_Performance_Time
-	"023847",	//CCS:CCS_SECC_TIMEOUT_V2G_CableCheck_Performance_Time
-	"023848",	//CCS:CCS_SECC_TIMEOUT_V2G_CPState_Detection_Time
-	"023849",	//CCS:CCS_SECC_TIMEOUT_V2G_CPOscillator_Retain_Time
-	"023850",	//CCS:CCS_SECC_TIMEOUT_V2G_PreCharge_Performace_Time
-	"023851",	//CCS:CCS_SECC_TIMEOUT_V2G_reserved_2
-	"023852",	//CCS:CCS_SECC_TIMEOUT_V2G_reserved_3
-	"023853",	//CCS:CCS_SECC_TIMEOUT_V2G_reserved_4
-	"023854",	//CCS:CCS_SECC_TIMEOUT_V2G_reserved_5
-	"023855",	//CCS:CCS_CAN_TIMEOUT_TP_GET_EV_TARGET_INFO
-	"023856",	//CCS:CCS_CAN_TIMEOUT_TT_GET_EV_TARGET_INFO
-	"023857",	//CCS:CCS_CAN_TIMEOUT_TP_GET_EV_BATTERY_INFO
-	"023858",	//CCS:CCS_CAN_TIMEOUT_TT_GET_EV_BATTERY_INFO
-	"023859",	//CCS:CCS_CAN_TIMEOUT_TP_EV_STOP_EVENT
-	"023860",	//CCS:CCS_CAN_TIMEOUT_TT_EV_STOP_EVENT
-	"023861",	//CCS:CCS_CAN_TIMEOUT_TP_EVSE_STOP_EVENT
-	"023862",	//CCS:CCS_CAN_TIMEOUT_TT_EVSE_STOP_EVENT
-	"023863",	//CCS:CCS_CAN_TIMEOUT_TP_GET_MISC_INFO
-	"023864",	//CCS:CCS_CAN_TIMEOUT_TT_GET_MISC_INFO
-	"023865",	//CCS:CCS_CAN_TIMEOUT_TP_DOWNLOAD_REQUEST
-	"023866",	//CCS:CCS_CAN_TIMEOUT_TT_DOWNLOAD_REQUEST
-	"023867",	//CCS:CCS_CAN_TIMEOUT_TP_START_BLOCK_TRANSFER
-	"023868",	//CCS:CCS_CAN_TIMEOUT_TT_START_BLOCK_TRANSFER
-	"023869",	//CCS:CCS_CAN_TIMEOUT_TP_DATA_TRANSFER
-	"023870",	//CCS:CCS_CAN_TIMEOUT_TT_DATA_TRANSFER
-	"023871",	//CCS:CCS_CAN_TIMEOUT_TP_DOWNLOAD_FINISH
-	"023872",	//CCS:CCS_CAN_TIMEOUT_TT_DOWNLOAD_FINISH
-	"023873",	//CCS:CCS_CAN_TIMEOUT_TP_ISOLATION_STATUS
-	"023874",	//CCS:CCS_CAN_TIMEOUT_TT_ISOLATION_STATUS
-	"023875",	//CCS:CCS_CAN_TIMEOUT_TP_CONNECTOR_INFO
-	"023876",	//CCS:CCS_CAN_TIMEOUT_TT_CONNECTOR_INFO
-	"023877",	//CCS:CCS_CAN_TIMEOUT_TT_RTC_INFO
-	"023878",	//CCS:CCS_CAN_TIMEOUT_TP_RTC_INFO
-	"023879",	//CCS:CCS_CAN_TIMEOUT_TP_EVSE_PRECHARGE_INFO
-	"023880",	//CCS:CCS_CAN_TIMEOUT_TT_EVSE_PRECHARGE_INFO
-	"023881",	//CCS:CCS_CAN_TIMEOUT_MSG_Sequence
-	"023882",	//CCS:CCS_CAN_MSG_Unrecognized_CMD_ID
-	"023883",	//CCS:CCS_SECC_DIN_Msg_Decode_Error
-	"023884",	//CCS:CCS_SECC_DIN_Msg_Encode_Error
-	"023885",	//CCS:CCS_SECC_ISO1_Msg_Decode_Error
-	"023886",	//CCS:CCS_SECC_ISO1_Msg_Encode_Error
-	"023887",	//CCS:CCS_SECC_ISO2_Msg_Decode_Error
-	"023888",	//CCS:CCS_SECC_ISO2_Msg_Encode_Error
-	"023889",	//CCS:CCS_SECC_CP_STATUS_Error
-	"023890",	//CCS:CCS_SECC_Unexpected_60V_Before_Charing_Error
-	"023891",	//CCS:CCS_SECC_Not_Ready_For_Charging
-	"023892",	//CCS:CCS_SECCC_TIMEOUT_QCA7000_COMM (The firmware code of QCA7000 may not be installed, yet)
-	"023893",	//CCS:CCS_SECC_FAIL_QCA7000_SETKEY
-	"023894",	//Reserved
-	"023895",	//Reserved
-	"023896",	//Reserved
-	"023897",	//Reserved
-	"023898",	//Reserved
-	"023899",	//Reserved
-	"023900",	//GBT: ERROR_CODE_GBT_LOS_CC1
-	"023901",	//GBT: ERROR_CODE_GBT_CONNECTOR_LOCK_FAIL
-	"023902",	//GBT: ERROR_CODE_GBT_BATTERY_INCOMPATIBLE
-	"023903",	//GBT: ERROR_CODE_GBT_BMS_BROAA_TIMEOUT
-	"023904",	//GBT: ERROR_CODE_GBT_CSU_PRECHARGE_TIMEOUT
-	"023905",	//GBT: ERROR_CODE_GBT_BMS_PRESENT_VOLTAGE_FAULT
-	"023906",	//GBT: ERROR_CODE_GBT_BMS_VOLTAGE_OVER_RANGE
-	"023907",	//GBT: ERROR_CODE_GBT_BSM_CHARGE_ALLOW_00_10MIN_COUUNTDONE
-	"023908",	//GBT: ERROR_CODE_GBT_WAIT_GROUNDFAULT_TIMEOUT
-	"023909",	//GBT: ERROR_CODE_GBT_ADC_MORE_THAN_10V
-	"023910",	//GBT: ERROR_CODE_GBT_ADC_MORE_THAN_60V
-	"023911",	//GBT: ERROR_CODE_GBT_CHARGER_GET_NORMAL_STOP_CMD
-	"023912",	//GBT: ERROR_CODE_GBT_CHARGER_GET_EMERGENCY_STOP_CMD
-	"023913",	//GBT: ERROR_CODE_GBT_ISOLATION_RESULT_FAIL
-	"023914",	//GBT: ERROR_CODE_GBT_MOTHER_BOARD_MISS_LINK
-	"023915",	//GBT: ERROR_CODE_GBT_OUTPUT_VOLTAGE_MORE_THAN_LIMIT
-	"023916",	//GBT: ERROR_CODE_GBT_REQ_CURRENT_MORE_THAN_LIMIT
-	"023917",	//GBT: ERROR_CODE_GBT_OUTPUT_VOLTAGE_MORE_THAN_10_PERCENT
-	"023918",	//GBT: ERROR_CODE_GBT_OUTPUT_VOLTAGE_DIFF_BCS_5_PERCENT
-	"023919",	//GBT: ERROR_CODE_GBT_STOP_ADC_MORE_THAN_10V
-	"023920",	// Reserved
-	"023921",	// Reserved
-	"023922",	// Reserved
-	"023923",	// Reserved
-	"023924",	// Reserved
-	"023925",	// Reserved
-	"023926",	// Reserved
-	"023927",	// Reserved
-	"023928",	// Reserved
-	"023929",	// Reserved
-	"023930",	//GBT: ERROR_CODE_CEM_BHM_TIMEOUT
-	"023931",	//GBT: ERROR_CODE_CEM_BRM_TIMEOUT
-	"023932",	//GBT: ERROR_CODE_CEM_BCP_TIMEOUT
-	"023933",	//GBT: ERROR_CODE_CEM_BRO_TIMEOUT
-	"023934",	//GBT: ERROR_CODE_CEM_BCL_TIMEOUT
-	"023935",	//GBT: ERROR_CODE_CEM_BCS_TIMEOUT
-	"023936",	//GBT: ERROR_CODE_CEM_BSM_TIMEOUT
-	"023937",	//GBT: ERROR_CODE_CEM_BST_TIMEOUT
-	"023938",	//GBT: ERROR_CODE_CEM_BSD_TIMEOUT
-	"023939",	//GBT: ERROR_CODE_CEM_BEM_OTHER_TIMEOUT
-	"023940",	//GBT: ERROR_CODE_BEM_CRM_TIMEOUT
-	"023941",	//GBT: ERROR_CODE_BEM_CRMAA_TIMEOUT
-	"023942",	//GBT: ERROR_CODE_BEM_CTS_CML_TIMEOUT
-	"023943",	//GBT: ERROR_CODE_BEM_CRO_TIMEOUT
-	"023944",	//GBT: ERROR_CODE_BEM_CCS_TIMEOUT
-	"023945",	//GBT: ERROR_CODE_BEM_CST_TIMEOUT
-	"023946",	//GBT: ERROR_CODE_BEM_CSD_TIMEOUT
-	"023947",	//GBT: ERROR_CODE_BEM_BEM_OTHER_TIMEOUT
-	"023948",	// Reserved
-	"023949",	// Reserved
-	"023950",	//GBT: ERROR_CODE_BST_SOC_GOAL
-	"023951",	//GBT: ERROR_CODE_BST_TOTAL_VOLTAGE_GOAL
-	"023952",	//GBT: ERROR_CODE_BST_CELL_VOLTAGE_GOAL
-	"023953",	//GBT: ERROR_CODE_BST_GET_CST
-	"023954",	//GBT: ERROR_CODE_BST_ISOLATION
-	"023955",	//GBT: ERROR_CODE_BST_OUTPUT_CONNECTOR_OTP
-	"023956",	//GBT: ERROR_CODE_BST_COMPONENT
-	"023957",	//GBT: ERROR_CODE_BST_CHARGE_CONNECTOR
-	"023958",	//GBT: ERROR_CODE_BST_OTP
-	"023959",	//GBT: ERROR_CODE_BST_OTHER
-	"023960",	//GBT: ERROR_CODE_BST_HIGH_V
-	"023961",	//GBT: ERROR_CODE_BST_CC2
-	"023962",	//GBT: ERROR_CODE_BST_CURRENT
-	"023963",	//GBT: ERROR_CODE_BST_VOLTAGE
-	"023964",	//GBT: ERROR_CODE_GET_BST_NO_REASON
-	"023965",	// Reserved
-	"023966",	// Reserved
-	"023967",	// Reserved
-	"023968",	// Reserved
-	"023969",	// Reserved
-	"023970",	//GBT: ERROR_CODE_BSM_CELL_OVER_VOLTAGE
-	"023971",	//GBT: ERROR_CODE_BSM_CELL_UNDER_VOLTAGE
-	"023972",	//GBT: ERROR_CODE_BSM_OVER_SOC
-	"023973",	//GBT: ERROR_CODE_BSM_UNDER_SOC
-	"023974",	//GBT: ERROR_CODE_BSM_CURRENT
-	"023975",	//GBT: ERROR_CODE_BSM_TEMPERATURE
-	"023976",	//GBT: ERROR_CODE_BSM_ISOLATE
-	"023977",	//GBT: ERROR_CODE_BSM_OUTPUT_CONNECTOR
-	"023978",	// Reserved
-	"023979",	// EV full charging
-    "023980",   // ERROR_CODE_CHADEMO_BMS_CHARGE_ALLOW_ERROR
-    "023981",   // ERROR_CODE_CHADEMO_OUTPUT_VOLTAGE_MORE_THEN_10_PERCENT
-    "023982",   // ERROR_CODE_CHADEMO_ADC_LESS_THAN_10V
-    "023983",   // STOP by EV with unknow reason
-    "023984",   // STOP by EVSE condition (Config or OCPP)
-    "023985",   // Reserved
-    "023986",   // Reserved
-    "023987",   // Reserved
-	"033900",	//disconnected from backend through Ethernet
-	"033901",	//disconnected from backend through WiFi
-	"033902",	//disconnected from backend through 3G/4G
-	"033903",	//Remote start charging by backend
-	"033904",	//Remote stop charging by backend
-	"033905",	//Remote reset by backend
-	"033906",	//Authorization failed
-	"033907",	//Reserved
-};
-*/
-struct InfoCodeData
-{
-	unsigned char PreviousInfoVal[InfoCodeLength];
-	union
-	{
-		unsigned char InfoVal[InfoCodeLength];
-		struct
-		{
-			//InfoVal[0]
-		    unsigned char NormalStopChargingByUser:1;				//bit 0
-			unsigned char ChargingTimesUp:1;						//bit 1
-			unsigned char ReplaceSystemAirFilter:1; 				//bit 2
-			unsigned char ReachChademoMaxPluggingTimes:1;			//bit 3
-			unsigned char ReachCcsMaxPluggingTimes:1;				//bit 4
-			unsigned char ReachGbMaxPluggingTimes:1;				//bit 5
-			unsigned char ReachAcMaxPluggingTimes:1;				//bit 6
-			unsigned char CsuFimrwareUpdateFail:1;					//bit 7
-			//InfoVal[1]
-			unsigned char ChademoModuleFimrwareUpdateFail:1;		//bit 0
-			unsigned char CcsModuleFimrwareUpdateFail:1;			//bit 1
-			unsigned char GbModuleFimrwareUpdateFail:1;				//bit 2
-			unsigned char AuxPowerModuleFimrwareUpdateFail:1;		//bit 3
-			unsigned char RelayBoardFimrwareUpdateFail:1;			//bit 4
-			unsigned char LcmModuleFimrwareUpdateFail:1;			//bit 5
-			unsigned char BluetoothModuleFimrwareUpdateFail:1;		//bit 6
-			unsigned char WiFiModuleFimrwareUpdateFail:1;			//bit 7
-			//InfoVal[2]
-			unsigned char Telocom4GModuleFimrwareUpdateFail:1;		//bit 0
-			unsigned char PsuFimrwareUpdateFail:1;					//bit 1
-			unsigned char RfidModuleFimrwareUpdateFail:1;			//bit 2
-			unsigned char ConfiguredByUsbFlashDrive:1;				//bit 3
-			unsigned char ConfiguredByBackend:1;					//bit 4
-			unsigned char ConfiguredByWebpage:1;					//bit 5
-			unsigned char InternetDisconnectViaEthernet:1;			//bit 6
-			unsigned char InternetDisconnectViaWiFi :1;				//bit 7
-	        //InfoVal[3]
-			unsigned char InternetDisconnectVia4Gi:1;				//bit 0
-			unsigned char ApDisconnectViaWiFi:1;					//bit 1
-			unsigned char ApnDisconnectVia4Gi:1;					//bit 2
-			unsigned char WiFiDisable:1;                            //bit 3
-			unsigned char Telocom4GModuleDisable:1;                 //bit 4
-			unsigned char PsuQuantityNotMatch:1;                    //bit 5
-			unsigned char :2;										//bit 6~7 reserved
-			 //InfoVal[4]
-			unsigned char ChademoEvCommFail:1;						//bit 0
-			unsigned char CcsEvCommFail:1;							//bit 1
-			unsigned char GbEvCommFail:1;							//bit 2
-			unsigned char PilotFault:1;								//bit 3
-			unsigned char ChademoBatteryMalfun:1;					//bit 4
-			unsigned char ChademoNoPermission:1;					//bit 5
-			unsigned char ChademoBatteryIncompatibility:1;			//bit 6
-			unsigned char ChademoBatteryOVP:1;						//bit 7
-			//InfoVal[5]
-			unsigned char ChademoBatteryUVP:1;						//bit 0
-			unsigned char ChademoBatteryOTP:1;						//bit 1
-			unsigned char ChademoBatteryCurrentDiff:1;				//bit 2
-			unsigned char ChademoBatteryVoltageDiff:1;				//bit 3
-			unsigned char ChademoShiftPosition:1;					//bit 4
-			unsigned char ChademoBatteryOtherFault:1;				//bit 5
-			unsigned char ChademoChargingSystemError:1;				//bit 6
-			unsigned char ChademoEvNormalStop:1;					//bit 7
-			//InfoVal[6]
-			unsigned char ChademoTempSensorBroken:1;				//bit 0
-			unsigned char ChademoConnectorLockFail:1;				//bit 1
-			unsigned char ChademoD1OnNoReceive:1;					//bit 2
-			unsigned char ChademoBmsKtoJTimeout:1;					//bit 3
-			unsigned char ChademoBmsChargeAllowTimeout:1;			//bit 4
-			unsigned char ChademoWaitGfdTimeout:1;					//bit 5
-			unsigned char ChademoBmsEvRelayTimeout:1;				//bit 6
-			unsigned char ChademoBmsReqCurrentTimeout:1;			//bit 7
-			//InfoVal[7]
-			unsigned char ChademoBmsKtoJOffTimeout :1;				//bit 0
-			unsigned char ChademoBmsEvRelayOffTimeout :1;			//bit 1
-			unsigned char ChademoAdcMoreThan10V :1;					//bit 2
-			unsigned char ChademoAdcMoreThan20V :1;					//bit 3
-			unsigned char ChademoBmsChargeBeforeStop :1;			//bit 4
-			unsigned char ChademoChargerGetNormalStop :1;			//bit 5
-			unsigned char ChademoChargerGetEmergencyStop :1;		//bit 6
-			unsigned char ChademoIsolationResultFail :1;			//bit 7
-			//InfoVal[8]
-			unsigned char ChademoMissLinkWithMotherBoard :1;		//bit 0
-			unsigned char ChademoOutputVolMoreThanLimit :1;			//bit 1
-			unsigned char ChademoReqCurrentMoreThanLimit :1;				//bit 2
-			unsigned char ChademoReCapBmsEqrCurrentExceed :1;				//bit 3
-			unsigned char ChademoChargeRemainCountDown :1;		//bit 4
-			unsigned char CcsRESTemperatureInhibit:1;				//bit 5
-			unsigned char CcsEVShiftPosition:1;				//bit 6
-			unsigned char CcsChargerConnectorLockFault:1;				//bit 7
-			//InfoVal[9]
-			unsigned char CcsEVRESSMalfunction:1;					//bit 0
-			unsigned char CcsChargingCurrentdifferential:1;		//bit 1
-			unsigned char CcsChargingVoltageOutOfRange:1;		//bit 2
-			unsigned char CcsChargingSystemIncompatibility:1;		//bit 3
-			unsigned char CcsEmergencyEvent:1;				//bit 4
-			unsigned char CcsBreaker:1;					//bit 5
-			unsigned char CcsNoData:1;							//bit 6
-			unsigned char Ccsreserved_by_DIN_A:1;				//bit 7
-			//InfoVal[10]
-			unsigned char Ccsreserved_by_DIN_B:1;				//bit 0
-			unsigned char Ccsreserved_by_DIN_C:1;					//bit 1
-			unsigned char Ccsreserved_by_ISO_1:1;				//bit 2
-			unsigned char Ccsreserved_by_ISO_2:1;					//bit 3
-			unsigned char Ccsreserved_by_ISO_3:1;					//bit 4
-			unsigned char Ccsreserved_by_OEM_1:1;				//bit 5
-			unsigned char Ccsreserved_by_OEM_2:1;			//bit 6
-			unsigned char Ccsreserved_by_OEM_3:1;				//bit 7
-			//InfoVal[11]
-			unsigned char Ccsreserved_by_OEM_4:1;			//bit 0
-			unsigned char Ccsreserved_by_OEM_5:1;			//bit 1
-			unsigned char CcsSequenceError:1;			//bit 2
-			unsigned char CcsSignatureError:1;		//bit 3
-			unsigned char CcsUnknownSession:1;					//bit 4
-			unsigned char CcsServiceIDInvalid:1;					//bit 5
-			unsigned char CcsPaymentSelectionInvalid:1;					//bit 6
-			unsigned char CcsIdentificationSelectionInvalid:1;			//bit 7
-			//InfoVal[12]
-			unsigned char CcsServiceSelectionInvalid:1;			//bit 0
-			unsigned char CcsCertificateExpired:1;			//bit 1
-			unsigned char CcsCertificateNotYetValid:1;			//bit 2
-			unsigned char CcsCertificateRevoked:1;			//bit 3
-			unsigned char CcsNoCertificateAvailable:1;			//bit 4
-			unsigned char CcsCertChainError:1;			//bit 5
-			unsigned char CcsCertValidationError:1;			//bit 6
-			unsigned char CcsCertVerificationError:1;			//bit 7
-			//InfoVal[13]
-			unsigned char CcsContractCanceled:1;				//bit 0
-			unsigned char CcsChallengeInvalid:1;				//bit 1
-			unsigned char CcsWrongEnergyTransferMode:1;				//bit 2
-			unsigned char CcsWrongChargeParameter:1;				//bit 3
-			unsigned char CcsChargingProfileInvalid:1;				//bit 4
-			unsigned char CcsTariffSelectionInvalid:1;				//bit 5
-			unsigned char CcsEVSEPresentVoltageToLow:1;				//bit 6
-			unsigned char CcsPowerDeliveryNotApplied:1;			//bit 7
-			//InfoVal[14]
-			unsigned char CcsMeteringSignatureNotValid:1;			//bit 0
-			unsigned char CcsNoChargeServiceSelected:1;			//bit 1
-			unsigned char CcsContactorError:1;					//bit 2
-			unsigned char CcsCertificateNotAllowedAtThisEVSE:1;			//bit 3
-			unsigned char CcsGAChargeStop:1;				//bit 4
-			unsigned char CcsAlignmentError:1;					//bit 5
-			unsigned char CcsACDError:1;					//bit 6
-			unsigned char CcsAssociationError:1;			//bit 7
-			//InfoVal[15]
-			unsigned char CcsEVSEChargeAbort:1;				//bit 0
-			unsigned char CcsNoSupportedAppProtocol:1;					//bit 1
-			unsigned char CcsContractNotAccepted:1;				//bit 2
-			unsigned char CcsMOUnknown:1;					//bit 3
-			unsigned char CcsOEM_Prov_CertificateRevoke:1;				//bit 4
-			unsigned char CcsOEM_SubCA1_CertificateRevoked:1;		//bit 5
-			unsigned char CcsOEM_SubCA2_CertificateRevoked:1;		//bit 6
-			unsigned char CcsOEM_RootCA_CertificateRevoked:1;		//bit 7
-			//InfoVal[16]
-			unsigned char CcsMO_Prov_CertificateRevoked:1;			//bit 0
-			unsigned char CcsMO_SubCA1_CertificateRevoked:1;		//bit 1
-			unsigned char CcsMO_SubCA2_CertificateRevoked:1;		//bit 2
-			unsigned char CcsMO_RootCA_CertificateRevoked:1;		//bit 3
-			unsigned char CcsCPS_Prov_CertificateRevoked:1;		//bit 4
-			unsigned char CcsCPS_SubCA1_CertificateRevoked:1;		//bit 5
-			unsigned char CcsCPS_SubCA2_CertificateRevoked:1;		//bit 6
-			unsigned char CcsCPS_RootCA_CertificateRevoked:1;		//bit 7
-			//InfoVal[17]
-			unsigned char :5;					//bit 0~4 reserved
-			unsigned char CcsTT_EVSE_SLAC_init:1;				//bit 5
-			unsigned char CcsTP_match_response:1;			//bit 6
-			unsigned char CcsTT_match_sequence:1;			//bit 7
-			//InfoVal[18]
-			unsigned char CcsTT_EVSE_match_MNBC:1;				//bit 0
-			unsigned char CcsTP_EVSE_avg_atten_calc:1;				//bit 1
-			unsigned char CcsTT_match_response:1;			//bit 2
-			unsigned char CcsTP_EVSE_match_session:1;			//bit 3
-			unsigned char CcsTT_EVSE_assoc_session:1;			//bit 4
-			unsigned char CcsTT_EVSE_vald_toggle:1;			//bit 5
-			unsigned char CcsSeccSlacTimeoutCmMnbcSound:1;			//bit 6 reserved
-			unsigned char CcsSeccSlacTimeoutCmValidateReq:1;			//bit 7 reserved
-			//InfoVal[19]
-			unsigned char :3;					//bit 0~2 reserved
-			unsigned char CcsUDP_TT_match_join:1;			//bit 3
-			unsigned char CcsTCP_TT_match_join:1;				//bit 4
-			unsigned char CcsTP_amp_map_exchange:1;			//bit 5
-			unsigned char CcsTP_link_ready_notification:1;			//bit 6
-			unsigned char :1;				//bit 7 resetved
-			//InfoVal[20]
-			unsigned char :4;						//bit 0~3 reserved
-			unsigned char CcsSupportedAppProtocolRes:1;			//bit 4
-			unsigned char CcsSessionSetupRes:1;				//bit 5
-			unsigned char CcsServiceDiscoveryRes:1;				//bit 6
-			unsigned char CcsServicePaymentSelectionRes:1;		//bit 7
-			//InfoVal[21]
-			unsigned char CcsContractAuthenticationRes:1;			//bit 0
-			unsigned char CcsChargeParameterDiscoveryRes:1;			//bit 1
-			unsigned char CcsPowerDeliveryRes:1;			//bit 2
-			unsigned char CcsCableCheckRes:1;			//bit 3
-			unsigned char CcsPreChargeRes:1;					//bit 4
-			unsigned char CcsCurrentDemandRes:1;					//bit 5
-			unsigned char CcsWeldingDetectionRes:1;				//bit 6
-			unsigned char CcsSessionStopRes:1;					//bit 7
-			//InfoVal[22]
-			unsigned char CcsSequence_Time:1;						//bit 0
-			unsigned char CcsReadyToCharge_Performance_Time:1;				//bit 1
-			unsigned char CcsCommunicationSetup_Performance_Time:1;					//bit 2
-			unsigned char CcsCableCheck_Performance_Time:1;				//bit 3
-			unsigned char CcsCPState_Detection_Time:1;			//bit 4
-			unsigned char CcsCPOscillator_Retain_Time:1;					//bit 5
-			unsigned char CcsSeccTimeoutV2GPreChargePerformaceTime:1;			//bit 6
-			unsigned char :1;			//bit 7 reserved
-			//InfoVal[23]
-			unsigned char :3;					//bit 0~2 reserved
-			unsigned char CcsTP_GET_EV_TARGET_INFO:1;			//bit 3
-			unsigned char CcsTT_GET_EV_TARGET_INFO:1;		//bit 4
-			unsigned char CcsTP_GET_EV_BATTERY_INFO:1;		//bit 5
-			unsigned char CcsTT_GET_EV_BATTERY_INFO:1;		//bit 6
-			unsigned char CcsTP_EV_STOP_EVENT:1;				//bit 7
-			//InfoVal[24]
-			unsigned char CcsTT_EV_STOP_EVENT:1;			//bit 0
-			unsigned char CcsTP_EVSE_STOP_EVENT:1;			//bit 1
-			unsigned char CcsTT_EVSE_STOP_EVENT:1;			//bit 2
-			unsigned char CcsTP_GET_MISC_INFO:1;			//bit 3
-			unsigned char CcsTT_GET_MISC_INFO:1;			//bit 4
-			unsigned char CcsTP_DOWNLOAD_REQUEST:1;			//bit 5
-			unsigned char CcsTT_DOWNLOAD_REQUEST:1;			//bit 6
-			unsigned char CcsTP_START_BLOCK_TRANSFER:1;			//bit 7
-			//InfoVal[25]
-			unsigned char CcsTT_START_BLOCK_TRANSFER:1;		//bit 0
-			unsigned char CcsTP_DATA_TRANSFER:1;			//bit 1
-			unsigned char CcsTT_DATA_TRANSFER:1;			//bit 2
-			unsigned char CcsTP_DOWNLOAD_FINISH:1;			//bit 3
-			unsigned char CcsTT_DOWNLOAD_FINISH:1;			//bit 4
-			unsigned char CcsTP_ISOLATION_STATUS:1;			//bit 5
-			unsigned char CcsTT_ISOLATION_STATUS:1;			//bit 6
-			unsigned char CcsTP_CONNECTOR_INFO:1;			//bit 7
-			//InfoVal[26]
-			unsigned char CcsTT_CONNECTOR_INFO:1;			//bit 0
-			unsigned char CcsTT_RTC_INFO:1;				//bit 1
-			unsigned char CcsTP_RTC_INFO:1;			//bit 2
-			unsigned char CcsTP_EVSE_PRECHARGE_INFO:1;		//bit 3
-			unsigned char CcsTT_EVSE_PRECHARGE_INFO:1;			//bit 4
-			unsigned char CcsMSG_Sequence:1;			//bit 5
-			unsigned char CcsCAN_MSG_Unrecognized_CMD_ID:1;			//bit 6
-			unsigned char CcsDIN_Msg_Decode_Error:1;			//bit 7
-			//InfoVal[27]
-			unsigned char CcsDIN_Msg_Encode_Error:1;			//bit 0
-			unsigned char CcsISO1_Msg_Decode_Error:1;			//bit 1
-			unsigned char CcsISO1_Msg_Encode_Error:1;			//bit 2
-			unsigned char CcsISO2_Msg_Decode_Error:1;			//bit 3
-			unsigned char CcsISO2_Msg_Encode_Error:1;			//bit 4
-			unsigned char CcsCpStatus_Error:1;					//bit 5
-			unsigned char CcsUnexpectVolBeforeCharing_Error:1;	//bit 6
-			unsigned char CcsSeccNotReadyForCharging:1;			//bit 7 reserved
-			//InfoVal[28]
-			unsigned char CcsSeccTimeoutQCA7000Comm:1;			//bit 0
-			unsigned char CcsSeccFailForQCA7000SetKey:1;		//bit 1
-			unsigned char :6;									//bit 2~7 reserved
-			//InfoVal[29]
-			unsigned char ERROR_CODE_GBT_LOS_CC1 :1;									//bit 0
-			unsigned char ERROR_CODE_GBT_CONNECTOR_LOCK_FAIL :1;						//bit 1
-			unsigned char ERROR_CODE_GBT_BATTERY_INCOMPATIBLE :1;						//bit 2
-			unsigned char ERROR_CODE_GBT_BMS_BROAA_TIMEOUT :1;							//bit 3
-			unsigned char ERROR_CODE_GBT_CSU_PRECHARGE_TIMEOUT :1;						//bit 4
-			unsigned char ERROR_CODE_GBT_BMS_PRESENT_VOLTAGE_FAULT :1;					//bit 5
-			unsigned char ERROR_CODE_GBT_BMS_VOLTAGE_OVER_RANGE :1;						//bit 6
-			unsigned char ERROR_CODE_GBT_BSM_CHARGE_ALLOW_00_10MIN_COUUNTDONE :1;		//bit 7
-			//InfoVal[30]
-			unsigned char ERROR_CODE_GBT_WAIT_GROUNDFAULT_TIMEOUT :1;					//bit 0
-			unsigned char ERROR_CODE_GBT_ADC_MORE_THAN_10V :1;							//bit 1
-			unsigned char ERROR_CODE_GBT_ADC_MORE_THAN_60V :1;							//bit 2
-			unsigned char ERROR_CODE_GBT_CHARGER_GET_NORMAL_STOP_CMD :1;				//bit 3
-			unsigned char ERROR_CODE_GBT_CHARGER_GET_EMERGENCY_STOP_CMD :1;				//bit 4
-			unsigned char ERROR_CODE_GBT_ISOLATION_RESULT_FAIL :1;						//bit 5
-			unsigned char ERROR_CODE_GBT_MOTHER_BOARD_MISS_LINK :1;						//bit 6
-			unsigned char ERROR_CODE_GBT_OUTPUT_VOLTAGE_MORE_THAN_LIMIT :1;				//bit 7
-			//InfoVal[31]
-			unsigned char ERROR_CODE_GBT_REQ_CURRENT_MORE_THAN_LIMIT :1;				//bit 0
-			unsigned char ERROR_CODE_GBT_OUTPUT_VOLTAGE_MORE_THAN_10_PERCENT :1;		//bit 1
-			unsigned char ERROR_CODE_GBT_OUTPUT_VOLTAGE_DIFF_BCS_5_PERCENT :1;			//bit 2
-			unsigned char ERROR_CODE_GBT_STOP_ADC_MORE_THAN_10V :1;						//bit 3
-			unsigned char :4;															//bit 4 ~ 7 reserved
-			//InfoVal[32]
-			unsigned char :6;															//bit 0 ~ 5 reserved
-			unsigned char ERROR_CODE_CEM_BHM_TIMEOUT :1;								//bit 6
-			unsigned char ERROR_CODE_CEM_BRM_TIMEOUT :1;								//bit 7
-			//InfoVal[33]
-			unsigned char ERROR_CODE_CEM_BCP_TIMEOUT :1;								//bit 0
-			unsigned char ERROR_CODE_CEM_BRO_TIMEOUT :1;								//bit 1
-			unsigned char ERROR_CODE_CEM_BCL_TIMEOUT :1;								//bit 2
-			unsigned char ERROR_CODE_CEM_BCS_TIMEOUT :1;								//bit 3
-			unsigned char ERROR_CODE_CEM_BSM_TIMEOUT :1;								//bit 4
-			unsigned char ERROR_CODE_CEM_BST_TIMEOUT :1;								//bit 5
-			unsigned char ERROR_CODE_CEM_BSD_TIMEOUT :1;								//bit 6
-			unsigned char ERROR_CODE_CEM_BEM_OTHER_TIMEOUT :1;							//bit 7
-			//InfoVal[34]
-			unsigned char ERROR_CODE_BEM_CRM_TIMEOUT :1;			//bit 0
-			unsigned char ERROR_CODE_BEM_CRMAA_TIMEOUT :1;			//bit 1
-			unsigned char ERROR_CODE_BEM_CTS_CML_TIMEOUT :1;		//bit 2
-			unsigned char ERROR_CODE_BEM_CRO_TIMEOUT :1;			//bit 3
-			unsigned char ERROR_CODE_BEM_CCS_TIMEOUT :1;			//bit 4
-			unsigned char ERROR_CODE_BEM_CST_TIMEOUT :1;			//bit 5
-			unsigned char ERROR_CODE_BEM_CSD_TIMEOUT :1;			//bit 6
-			unsigned char ERROR_CODE_BEM_BEM_OTHER_TIMEOUT :1;		//bit 7
-			//InfoVal[35]
-			unsigned char :2;										//bit 0 ~ 1
-			unsigned char ERROR_CODE_BST_SOC_GOAL :1;				//bit 2
-			unsigned char ERROR_CODE_BST_TOTAL_VOLTAGE_GOAL :1;		//bit 3
-			unsigned char ERROR_CODE_BST_CELL_VOLTAGE_GOAL :1;		//bit 4
-			unsigned char ERROR_CODE_BST_GET_CST :1;				//bit 5
-			unsigned char ERROR_CODE_BST_ISOLATION :1;				//bit 6
-			unsigned char ERROR_CODE_BST_OUTPUT_CONNECTOR_OTP :1;	//bit 7
-			//InfoVal[36]
-			unsigned char ERROR_CODE_BST_COMPONENT :1;				//bit 0
-			unsigned char ERROR_CODE_BST_CHARGE_CONNECTOR :1;		//bit 1
-			unsigned char ERROR_CODE_BST_OTP :1;					//bit 2
-			unsigned char ERROR_CODE_BST_OTHER :1;					//bit 3
-			unsigned char ERROR_CODE_BST_HIGH_V :1;					//bit 4
-			unsigned char ERROR_CODE_BST_CC2 :1;					//bit 5
-			unsigned char ERROR_CODE_BST_CURRENT :1;				//bit 6
-			unsigned char ERROR_CODE_BST_VOLTAGE :1;				//bit 7
-			//InfoVal[37]
-			unsigned char ERROR_CODE_GET_BST_NO_REASON :1;			//bit 0
-			unsigned char :5;										//bit 1 ~ 5 reserved
-			unsigned char ERROR_CODE_BSM_CELL_OVER_VOLTAGE :1;		//bit 6
-			unsigned char ERROR_CODE_BSM_CELL_UNDER_VOLTAGE :1;		//bit 7
-			//InfoVal[38]
-			unsigned char ERROR_CODE_BSM_OVER_SOC :1;				//bit 0
-			unsigned char ERROR_CODE_BSM_UNDER_SOC :1;				//bit 1
-			unsigned char ERROR_CODE_BSM_CURRENT :1;				//bit 2
-			unsigned char ERROR_CODE_BSM_TEMPERATURE :1;			//bit 3
-			unsigned char ERROR_CODE_BSM_ISOLATE :1;				//bit 4
-			unsigned char ERROR_CODE_BSM_OUTPUT_CONNECTOR :1;		//bit 5
-			unsigned char :1;										//bit 6
-			unsigned char EV_Full_Charging:1;                       //bit 7
-            //InfoVal[39]
-            unsigned char CHADEMO_BMS_CHARGE_ALLOW_ERROR:1;         //bit 0
-            unsigned char CHADEMO_OUTPUT_VOLTAGE_MORE_THEN_10_PERCENT:1; //bit 1
-            unsigned char CHADEMO_ADC_LESS_THAN_10V:1;              //bit 2
-            unsigned char Stop_by_EV_with_unknow_reason:1;          //bit 3
-            unsigned char Stop_by_EVSE_condition:1;                 //bit 4
-            unsigned char :3;                                       //bit 5 ~ 7 reserved
-			//InfoVal[40]
-			unsigned char BackendDisconnectedViaEthernet:1;			//bit 0
-			unsigned char BackendDisconnectViaWiFi:1;				//bit 1
-			unsigned char BackendDisconnectVia4G:1;					//bit 2
-			unsigned char BackendRemoteStart:1;						//bit 3
-			unsigned char BackendRemoteStop:1;						//bit 4
-			unsigned char BackendRemoteReset:1;						//bit 5
-			unsigned char AuthorizationFailed:1;					//bit 6
-			unsigned char :1;										//bit 7	reserved
-		}bits;
-	}InfoEvents;
-};
-
-struct StatusCodeData
-{
-	struct FaultCodeData	FaultCode;
-	struct AlarmCodeData	AlarmCode;
-	struct InfoCodeData		InfoCode;
-};
-/**************************************************************************************/
-/**************************PSU Share memory***************************************/
-/**************************************************************************************/
-typedef union
-{
-    unsigned int PsuGroupErrorValue;
-    struct
-    {
-        unsigned int PsuFailure:1;              // 0: no effect,    1: Psu Failure
-        unsigned int res:31;
-    }bits;
-}PsuGroupError;
-
-struct PsuModuleVer
-{
-	unsigned char 		FwPrimaryVersion[16];
-	unsigned char 		FwSecondVersion[16];
-};
-
-/*Following are the information for each PSU module*/
-struct PsuModuleData
-{
-	unsigned char 		AssignID;
-	unsigned char 		PhysicalID;
-	unsigned char 		GroupID;
-	unsigned char 		Address;
-	unsigned char 		FireWireIndex;
-	unsigned char 		FwVersion[16];
-	unsigned char 		SerialNumber[32];
-	unsigned char 		StateMachine;			//0: Identification,  1:Operation,  2: Alarm,  3: Failure,  s4:Upgrade
-	unsigned char 		OutputPowerSwitch;	//0: D.D normal OFF,  1: D.D emergency OFF,  2: D.D ON
-	unsigned short 	FanSpeed_1;			//RPM
-	unsigned short 	FanSpeed_2;			//RPM
-	unsigned short 	FanSpeed_3;			//RPM
-	unsigned short 	FanSpeed_4;			//RPM
-	unsigned short 	InputVoltage_Type;	//0x00 = Line to Line Vol, 0x01 = Line to Neutral Vol
-	unsigned short 	InputVoltageL1;		//abcd=abc.d volt
-	unsigned short 	InputVoltageL2;		//abcd=abc.d volt
-	unsigned short 	InputVoltageL3;		//abcd=abc.d volt
-	unsigned short 	InputCurrentL1;		//abcd=abc.d amp
-	unsigned short 	InputCurrentL2;		//abcd=abc.d amp
-	unsigned short 	InputCurrentL3;		//abcd=abc.d amp
-	unsigned short 	PresentOutputVoltage;	//abcd=abc.d volt
-	unsigned short 	PresentOutputCurrent;	//abcd=abc.d amp
-	unsigned short 	AvailableCurrent;		// unit: 0.1A
-	unsigned int 		AvailablePower;		// unit: 0.1kW
-	char 				CriticalTemp1;			//0x00: -60¢XC  ~  0xFE: 194¢XC, resolution: 1¢XC, offset: -60¢XC, 0xFF: invalid
-	char 				CriticalTemp2;			//0x00: -60¢XC  ~  0xFE: 194¢XC, resolution: 1¢XC, offset: -60¢XC, 0xFF: invalid
-	char 				CriticalTemp3;			//0x00: -60¢XC  ~  0xFE: 194¢XC, resolution: 1¢XC, offset: -60¢XC, 0xFF: invalid
-	char 				ExletTemp;			//0x00: -60¢XC  ~  0xFE: 194¢XC, resolution: 1¢XC, offset: -60¢XC, 0xFF: invalid
-	char 				InletTemp_1;			//0x00: -60¢XC  ~  0xFE: 194¢XC, resolution: 1¢XC, offset: -60¢XC, 0xFF: invalid
-	char 				InletTemp_2;			//0x00: -60¢XC  ~  0xFE: 194¢XC, resolution: 1¢XC, offset: -60¢XC, 0xFF: invalid
-	char 				InletTemp;			//0x00: -60¢XC  ~  0xFE: 194¢XC, resolution: 1¢XC, offset: -60¢XC, 0xFF: invalid
-	char 				OutletTemp;			//0x00: -60¢XC  ~  0xFE: 194¢XC, resolution: 1¢XC, offset: -60¢XC, 0xFF: invalid
-	unsigned int 		AlarmCode;
-	unsigned int 		FaultCode;			//
-	unsigned int 		IAvailableCurrent;		            // unit: 0.1A
-    unsigned short  PresentMaxOutputVoltage;//abcd=abc.d volt
-    unsigned short  KwAvailablePower;       // unit: 0.1 kw
-};
-
-/*Following are the information for each PSU Group*/
-struct PsuGroupData
-{
-	unsigned char           GroupPresentPsuQuantity;
-	unsigned char           GroupOutputPowerSwitch;         //0: D.D normal OFF,  1: D.D emergency OFF,  2: D.D ON
-	unsigned short          GroupTargetOutputVoltage;       //abcd=abc.d volt
-	unsigned short          GroupTargetOutputCurrent;       //abcd=abc.d amp
-	unsigned short          GroupAvailableCurrent;          // unit: 0.1A
-	unsigned int            GroupAvailablePower;            // unit: 0.1kW
-	unsigned int            GroupRealOutputPower;           // unit: 1kW
-	unsigned short          GroupPresentOutputVoltage; 	    // unit: 0.1V
-	unsigned short          GroupPresentOutputCurrent;      // unit: 0.1A
-	unsigned int            GroupPresentOutputPower;        // unit: 0.1kW
-	struct PsuModuleData 	PsuModule[MAX_PSU_QUANTITY];
-	PsuGroupError           GroupErrorFlag;
-    unsigned short          TotalIAvailableCurrent;         // unit: 0.1A
-    unsigned short          TempIAvailableCurrent;          // unit: 0.1A
-    unsigned short          StableIAvailableCurrent;        // unit: 0.1A
-    unsigned short          StableCurrentCounter;           // stable current counter
-    unsigned short          GroupMaxVoltage;                // unit: 0.1V
-    unsigned char           IsUsing;                        // 0 : none use
-    unsigned char           UsingTarget;                    // 0xFF : Check
-    unsigned char           PwSwitchStatus;
-    unsigned short          TotalRatingPower;               // unit: 1kW
-};
-
-/*Following is the information for system all PSU*/
-struct PsuData
-{
-    unsigned char           SystemInitialPsuQuantity;       // psu quantity after ac/dc contactor on
-	unsigned char           SystemPresentPsuQuantity;
-	unsigned short          SystemAvailableCurrent;			//abcd=abc.d amp
-	unsigned int            SystemAvailablePower;			//Watt
-	struct PsuGroupData     PsuGroup[4];
-	unsigned char           GroupCount;
-	unsigned char           Work_Step;
-	struct PsuModuleVer     PsuVersion[MAX_PSU_QUANTITY];
-	unsigned char           PsuStopChargeFlag;
-};
-
-struct SmartTimeChk
-{
-    struct timespec     FetchLoopTime;
-    unsigned char       IsFetchStart;
-
-    struct timespec     ReleaseLoopTime;
-    unsigned char       IsReleaseStart;
-};
-
-struct DynamicFetchCtrl
-{
-    unsigned char       ShareGroup;         // 255 : None
-    unsigned char       FetchLoopStep;      // 0 : None, 1 : Output Vol, 2 : RCB ON, 3 : Current sharing, 4 : Finish
-    unsigned short      ShareTargetCurrent; // 0.1A
-    unsigned char       TargetRelay;        // 255 : None
-};
-
-struct DynamicReleaseCtrl
-{
-    unsigned char       ReleaseGroup;       // 255 : None
-    unsigned char       ReleaseLoopStep;    // 0 : None, 1 : Limit Pwr, 2 : Pwr OFF, 3. RCB OFF, 4. Finish
-    float               CheckOutPwrIsStable;// 0.1kw
-    unsigned char       TargetRelay;        // 255 : None
-    unsigned char       AutoRelease;
-
-    float               LimitCurCap;        // Inform 0.1A
-    float               LimitPwrCap;        // Inform 0.1kw
-    float               LimitCur;           // Target 0.1A
-    float               LimitPwr;           // Target 0.1kw
-};
-
-struct ConnInfo
-{
-    unsigned char ConnectorStaus;
-    unsigned char NeedToFetch;
-};
-
-struct SmartBoxData
-{
-    struct ConnInfo     ConnectorStatus[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];     // Connector 1 / 2 Status : None, Wait, Using
-    struct ConnInfo     AnotherConnectorStatus[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
-    unsigned char       ConnectorUsingGroupCount[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY]; // Psu group for connector
-    struct SmartTimeChk SmartChk[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
-    struct DynamicFetchCtrl Dynamic4Fetch[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
-    struct DynamicReleaseCtrl Dynamic4Release[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
-    unsigned char       ParallelRelayStatus[3];
-    unsigned char       RcbParallelStatus[3];
-};
-
-/************************************************************************************/
-/**************************CHAdeMO protocol Share memory*********************/
-/**************************************************************************************/
-struct CHAdeMOEvData
-{
-	unsigned char  SupportDynamicControl;	//110.0
-										//					bit0=1:supported
-	unsigned char  SupportHighCurrent;		//110.0
-										//					bit1=1:supported
-	unsigned char  MiniChargeCurrent;		//100.0				0~200(A) (unit:1A)
-										//					0x00: request for current equivalent to 1.5kW
-										//					0x01: no request
-										//					0x02: request of 1A and following are the same rule
-	unsigned short MaxiBatteryVoltage;		//100.5,100.4 			0~600(V) (unit:1V)
-	unsigned short MaxiChargingTime;			//101.2,101.1			10(sec.)~255(min.)	(Unit:sec)
-										//					Set 0xFF to 101.1 (Unit: 10sec) in case 101.2 (Unit: 1min) is used
-	unsigned char  EstimatChargingTime;		//101.3				0~254(min.)	(Unit:sec)
-										//					Display Only
-	unsigned short TotalBatteryCapacity;		//101.6,101.5 			0.1~6553.5(kWh)	(unit:0.1 kWh)
-	unsigned char  ProtocolVersion;			//102.0				0~255
-										//					0x02: CHAdeMO specification ver.1.2
-	unsigned short TargetBatteryVoltage;		//102.2,102.1 			0~600(V) (unit:1V)
-	unsigned short ChargingCurrentRequest;	//102.3				0~200(A) (unit:1A)
-										//110.2,110.1 			0~1023(A) (unit:1A)
-	unsigned char  BatteryAlarm;				//102.4				>0:alarm
-										//					bit0=1:Battery overvoltage
-										//					bit1=1:Battery undervoltage
-										//					bit2=1:Battery current deviation error
-										//					bit3=1:High battery temperature
-										//					bit4=1:Battery voltage deviation error
-	unsigned char  EvDetection;				//102.5
-										//					bit0=0:Vehicle charging disabled,	(stop charging)
-										//					bit0=1:Vehicle charging enabled,
-										//					bit1=0:¡§Parking¡¨ position
-										//					bit1=1:other position				(stop charging)
-										//					bit2=0:Charging system normal
-										//					bit2=1:Charging system error		(stop charging)
-										//					bit3=0:EV contactor close or during welding detection
-										//					bit3=1:EV contactor open or termination of welding detection (stop charging)
-										//					bit4=0:No stop request before charging
-										//					bit4=1:Normal stop request before charging	(stop charging)
-	unsigned char  SOC;					//102.6				0~100(%) (unit:%)
-										//					Display Only
-	unsigned char  Communicating;			//					it is true if receive EV CAN message within every 1500ms
-	unsigned char  PresentMsgFlowStatus;	//
-};
-
-struct CHAdeMOEvseData
-{
-	unsigned char 	SelfTest_Comp;
-	unsigned char	version[16];									//Chademo firmware version
-	unsigned char  SupportDynamicControl;	//118.0
-										//					bit0=1:supported
-	unsigned char  SupportHighCurrent;		//118.0
-										//					bit1=1:supported
-	unsigned short  AvailableOutputVoltage;	//108.2,108.1 			0~600(V) (unit:1V)
-	unsigned short  AvailableOutputCurrent;	//108.3				0~255(A) (unit:1A)
-										//118.2,118.1 			0~1023(A) (unit:1A)
-	unsigned short  ThresholdVoltage;			//108.5,108.4 			0~600(V) (unit:1V)
-	unsigned char   ConnectorTemperatureP;	//108.6				-40~215(degC) (unit:degC) //value 0=-40	[NISSAN customized]
-	unsigned char   ConnectorTemperatureN;	//108.7				-40~215(degC) (unit:degC) //value 0=-40	[NISSAN customized]
-	unsigned char   ProtocolVersion;			//109.0				0~255
-										//					0x00: CHAdeMO specification 0.9 and earlier
-										//					0x01: CHAdeMO specification 0.9 and 0.9.1
-										//					0x02: CHAdeMO specification 1.0.0, 1.0.1, 1.1 and 1.2
-	unsigned short  PresentOutputVoltage;		//109.2,109.1	 		0~600(V) (unit:1V)
-	unsigned short   PresentOutputCurrent;		//109.3				0~255(A) (unit:1A)
-										//118.4,118.3			0~1023(A) (unit:1A)
-	unsigned char   EvseDetection;			//109.5
-										//					bit0=0:not charging state now
-										//					bit0=1:charging state now
-										//					bit1=0:EVSE normal
-										//					bit1=1:EVSE error
-										//					bit2=0:Not Energizing state
-										//					bit2=1:Energizing state
-										//					bit3=0:No Battery incompatibility
-										//					bit3=1:Battery incompatibility
-										//					bit4=0:No Charging system error
-										//					bit4=1:Charging system error
-										//					bit5=0:No Charging stop control
-										//					bit5=1:Charging stop control
-	unsigned short RemainChargingTime;		//109.7,109.6			10(sec.)~255(min.)	(Unit:sec)
-										//					Set 0xFF to 109.6 (Unit: 10sec) in case 109.7 (Unit: 1min) is used
-	unsigned char  HighPowerCondition;		//118.5
-										//					bit0=0:Present charging current H¡¦118.3,H¡¦118.4¡¨ is less than or equal to rated current of a charging cable
-										//					bit0=1:Present charging current H¡¦118.3,H¡¦118.4¡¨ is exceeds to rated current of a charging cable
-										//					bit1=1:charging cable Cooling function Operating Installed
-										//					bit2=1:charging cable Current limiting function
-										//					bit3=1:charging connector Cooling function Operating
-										//					bit4=1:charging connector Current limiting function Installed
-										//					bit5=1:charging connector Over-temperature protection Installed
-										//					bit6=1:Functional safety Applied
-	unsigned int 	MaxiGroupPower;			//					XXXXXXXX (Unit:Watt)depend on which group to be used
-	unsigned int 	MaxiGroupCurrent;			//					XXXXXXXX (unit:1A)depend on which group to be used
-	unsigned short  ApplyOutputVoltage;		// 					0~600(V) (unit:1V)
-	unsigned short  ElapseChargingTime;		//					(Unit:sec)
-	unsigned short  ElapseEnergy;				//					(Unit:10xkWh)
-	unsigned char	EvboardStatus;			// 	0 : init
-};
-
-struct CHAdeMOData
-{
-	struct CHAdeMOEvData 		ev[CHAdeMO_QUANTITY];
-	struct CHAdeMOEvseData 	evse[CHAdeMO_QUANTITY];
-};
-
-/************************************************************************************/
-/**************************GBT protocol Share memory*********************/
-/**************************************************************************************/
-struct GBTEvData
-{
-	unsigned short MaxiBatteryVoltage;		// 0~600(V) (unit:1V)
-	unsigned short MaxiChargingTime;		// 10(sec.)~255(min.)	(Unit:sec)
-
-	unsigned char  EstimatChargingTime;		// 0~254(min.)	(Unit:sec)
-
-	unsigned short TotalBatteryCapacity;	// 0.1~6553.5(kWh)	(unit:0.1 kWh)
-	unsigned char  ProtocolVersion;			// 0~255
-
-	unsigned short TargetBatteryVoltage;	// 0~600(V) (unit:1V)
-	unsigned short ChargingCurrentRequest;	// 0~200(A) (unit:1A)
-											// 0~1023(A) (unit:1A)
-
-	unsigned char  EvDetection;				//102.5
-										//					bit0=0:Vehicle charging disabled,	(stop charging)
-										//					bit0=1:Vehicle charging enabled,
-										//					bit1=0:¡§Parking¡¨ position
-										//					bit1=1:other position				(stop charging)
-										//					bit2=0:Charging system normal
-										//					bit2=1:Charging system error		(stop charging)
-										//					bit3=0:EV contactor close or during welding detection
-										//					bit3=1:EV contactor open or termination of welding detection (stop charging)
-										//					bit4=0:No stop request before charging
-										//					bit4=1:Normal stop request before charging	(stop charging)
-	unsigned char  SOC;					//102.6				0~100(%) (unit:%)
-										//					Display Only
-	unsigned char  PresentMsgFlowStatus;	//
-};
-
-struct GBTEvseData
-{
-	unsigned char 	SelfTest_Comp;
-	unsigned char	version[16];				// GBT firmware version
-
-	unsigned short  AvailableOutputVoltage;		// 0~600(V) (unit:1V)
-	unsigned short  AvailableOutputCurrent;		// 0~255(A) (unit:1A)
-
-	unsigned char   ConnectorTemperatureP;	// -40~215(degC) (unit:degC) //value 0=-40	[NISSAN customized]
-	unsigned char   ConnectorTemperatureN;	// -40~215(degC) (unit:degC) //value 0=-40	[NISSAN customized]
-
-	unsigned short  PresentOutputVoltage;		// 0~600(V) (unit:1V)
-	unsigned short  PresentOutputCurrent;		// 0~255(A) (unit:1A)
-
-	unsigned short RemainChargingTime;		//109.7,109.6			10(sec.)~255(min.)	(Unit:sec)
-	unsigned char	EvboardStatus;			// 	0 : init
-};
-
-struct GBTData
-{
-	struct GBTEvData 		ev[GB_QUANTITY];
-	struct GBTEvseData 		evse[GB_QUANTITY];
-};
-
-/************************************************************************************/
-/**************************CCS protocol Share memory***************************/
-/**************************DIN70121: 201412***************************************/
-/**************************ISO15118_2014: 2014************************************/
-/**************************ISO15118_2018: 2018************************************/
-/************************************************************************************/
-typedef enum boolean { FALSE, TRUE } BOOL;
-enum ResponseCodeType_DIN70121		{ OK_DIN70121 = 0, OK_NewSessionEstablished_DIN70121 = 1, OK_OldSessionJoined_DIN70121 = 2, OK_CertificateExpiresSoon_DIN70121 = 3,
-									   FAILED_DIN70121 = 4, FAILED_SequenceError_DIN70121 = 5, FAILED_ServiceIDInvalid_DIN70121 = 6, FAILED_UnknownSession_DIN70121 = 7,
-									   FAILED_ServiceSelectionInvalid_DIN70121 = 8, FAILED_PaymentSelectionInvalid_DIN70121 = 9, FAILED_CertificateExpired_DIN70121 = 10,
-									   FAILED_SignatureError_DIN70121 = 11, FAILED_NoCertificateAvailable_DIN70121 = 12, FAILED_CertChainError_DIN70121 = 13, FAILED_ChallengeInvalid_DIN70121 = 14,
-									   FAILED_ContractCanceled_DIN70121 = 15, FAILED_WrongChargeParameter_DIN70121 = 16, FAILED_PowerDeliveryNotApplied_DIN70121 = 17,
-									   FAILED_TariffSelectionInvalid_DIN70121 = 18, FAILED_ChargingProfileInvalid_DIN70121 = 19, FAILED_EVSEPresentVoltageToLow_DIN70121 = 20,
-									   FAILED_MeteringSignatureNotValid_DIN70121 = 21, FAILED_WrongEnergyTransferType_DIN70121 = 22};
-enum ResponseCodeType_ISO15118_2014	{ OK_ISO15118_2014 = 0, OK_NewSessionEstablished_ISO15118_2014 = 1, OK_OldSessionJoined_ISO15118_2014 = 2, OK_CertificateExpiresSoon_ISO15118_2014 = 3,
-									   FAILED_ISO15118_2014 = 4, FAILED_SequenceError_ISO15118_2014 = 5, FAILED_ServiceIDInvalid_ISO15118_2014 = 6, FAILED_UnknownSession_ISO15118_2014 = 7,
-									   FAILED_ServiceSelectionInvalid_ISO15118_2014 = 8, FAILED_PaymentSelectionInvalid_ISO15118_2014 = 9, FAILED_CertificateExpired_ISO15118_2014 = 10,
-									   FAILED_SignatureError_ISO15118_2014 = 11, FAILED_NoCertificateAvailable_ISO15118_2014 = 12, FAILED_CertChainError_ISO15118_2014 = 13, FAILED_ChallengeInvalid_ISO15118_2014 = 14,
-									   FAILED_ContractCanceled_ISO15118_2014 = 15, FAILED_WrongChargeParameter_ISO15118_2014 = 16, FAILED_PowerDeliveryNotApplied_ISO15118_2014 = 17,
-									   FAILED_TariffSelectionInvalid_ISO15118_2014 = 18, FAILED_ChargingProfileInvalid_ISO15118_2014 = 19, FAILED_MeteringSignatureNotValid_ISO15118_2014 = 20,
-									   FAILED_NoChargeServiceSelected_ISO15118_2014 = 21, FAILED_WrongEnergyTransferMode_ISO15118_2014 = 22, FAILED_ContactorError_ISO15118_2014 = 23,
-									   FAILED_CertificateNotAllowedAtThisEVSE_ISO15118_2014 = 24, FAILED_CertificateRevoked_ISO15118_2014 = 25  };
-enum ResponseCodeType_ISO15118_2018	{ OK_ISO15118_2018 = 0, OK_NewSessionEstablished_ISO15118_2018 = 1, OK_OldSessionJoined_ISO15118_2018 = 2, OK_CertificateExpiresSoon_ISO15118_2018 = 3,
-									   OK_IsolationValid_ISO15118_2018 = 4, OK_IsolationWarning_ISO15118_2018 = 5, WARNING_CertificateExpired_ISO15118_2018 = 6, WARNING_NoCertificateAvailable_ISO15118_2018 = 7,
-									   WARNING_CertValidationError_ISO15118_2018 = 8, WARNING_CertVerificationError_ISO15118_2018 = 9, WARNING_ContractCanceled_ISO15118_2018 = 10,
-									   FAILED_ISO15118_2018 = 11, FAILED_SequenceError_ISO15118_2018 = 12, FAILED_ServiceIDInvalid_ISO15118_2018 = 13, FAILED_UnknownSession_ISO15118_2018 = 14,
-									   FAILED_ServiceSelectionInvalid_ISO15118_2018 = 15, FAILED_SignatureError_ISO15118_2018 = 16, FAILED_IdentificationSelectionInvalid_ISO15118_2018 = 17,
-									   FAILED_ChallengeInvalid_ISO15118_2018 = 18, FAILED_WrongChargeParameter_ISO15118_2018 = 19, FAILED_IsolationFault_ISO15118_2018 = 20,
-									   FAILED_PowerDeliveryNotApplied_ISO15118_2018 = 21, FAILED_TariffSelectionInvalid_ISO15118_2018 = 22, FAILED_ChargingProfileInvalid_ISO15118_2018 = 23,
-									   FAILED_MeteringSignatureNotValid_ISO15118_2018 = 24, FAILED_NoChargeServiceSelected_ISO15118_2018 = 25, FAILED_WrongEnergyTransferMode_ISO15118_2018 = 26,
-									   FAILED_ContactorError_ISO15118_2018 = 27, FAILED_CertificateRevoked_ISO15118_2018 = 28, FAILED_CertificateNotYetValid_ISO15118_2018 = 29 };
-enum EVSENotificationType		 		{ None = 0, StopCharging = 1, ReNegotiation = 2};
-enum ServiceCategoryType 				{ EVCharging = 0, Internet = 1, ContractCertificate = 2, OtherCustom = 3};
-enum PaymentOptionType 		      		{ Contract = 0, ExternalPayment = 1};
-/*enum EVSESupportedEnergyTransferType 	{ AC_single_phase_core = 0, AC_three_phase_core = 1, DC_core = 2, DC_extended = 3,
-									  DC_combo_core = 4, DC_dual = 5, AC_core1p_DC_extended = 6, AC_single_DC_core = 7,
-									  AC_single_phase_three_phase_core_DC_extended = 8, AC_core3p_DC_extended = 9};*/
-enum EnergyTransferModeType			{ AC_single_phase_core = 0, AC_three_phase_core = 1, DC_core = 2, DC_extended = 3,
-									  DC_combo_core = 4, DC_unique = 5};
-//enum identificationOptionType 			{ Contract = 0, ExternalIdentification = 1};
-enum unitSymbolType_DIN70121			{ h_DIN70121 = 0, m_DIN70121 = 1, s_DIN70121 = 2, A_DIN70121 = 3, Ah_DIN70121 = 4, V_DIN70121 = 5, VA_DIN70121 = 6, W_DIN70121 = 7, Ws_DIN70121 = 8, Wh_DIN70121 = 9};
-enum unitSymbolType_ISO15118_2014		{ h_ISO15118_2014 = 0, m_ISO15118_2014 = 1, s_ISO15118_2014 = 2, A_ISO15118_2014 = 3, V_ISO15118_2014 = 4, W_ISO15118_2014 = 5, Wh_ISO15118_2014 = 6};
-enum ProcessingType					{ Finished = 0, Ongoing = 1, Ongoing_WaitingForCustomerInteraction = 2};
-enum EVSEProcessingType_DIN70121		{ Finished_DIN70121 = 0, Ongoing_DIN70121 = 1};
-enum EVSEProcessingType_ISO15118_2014	{ Finished_ISO15118_2014 = 0, Ongoing_ISO15118_2014 = 1, Ongoing_WaitingForCustomerInteraction_ISO15118_2014=2 };
-enum DC_EVErrorCodeType 		  		{ NO_ERROR = 0, FAILED_RESSTemperatureInhibit = 1, FAILED_EVShiftPosition = 2, FAILED_ChargerConnectorLockFault = 3,
-									  FAILED_EVRESSMalfunction = 4, FAILED_ChargingCurrentdifferential = 5, FAILED_ChargingVoltageOutOfRange = 6,
-									  Reserved_A = 7, Reserved_B = 8, Reserved_C = 9, FAILED_ChargingSystemIncompatibility = 10, NoData = 11};
-enum IsolationLevelType_DIN70121 		{ Invalid_DIN70121 = 0, Valid_DIN70121 = 1, Warning_DIN70121 = 2, Fault_DIN70121 = 3};
-enum IsolationLevelType_ISO15118_2014		{ Invalid_ISO15118_2014 = 0, Valid_ISO15118_2014 = 1, Warning_ISO15118_2014 = 2, Fault_ISO15118_2014 = 3, No_IMD_ISO15118_2014	 = 4};
-enum DC_EVSEStatusCodeType			{ EVSE_NotReady = 0, EVSE_Ready = 1, EVSE_Shutdown = 2, EVSE_UtilityInterruptEvent = 3,
-						 			  EVSE_IsolationMonitoringActive = 4, EVSE_EmergencyShutdown = 5, EVSE_Malfunction = 6,
-						 			  Reserved_8 = 7, Reserved_9 = 8};
-enum ScheduleOriginType				{ EV = 0, SA = 1};
-enum ChargeProgressType_ISO15118_2014	{start_ISO15118_2014 = 0, Stop_ISO15118_2014 = 1, Renegotiate_ISO15118_2014 = 2};
-enum ChargeProgressType_ISO15118_2018	{start_ISO15118_2018 = 0, Renegotiate_ISO15118_2018 = 1, Standby_ISO15118_2018 = 2, Stop_ISO15118_2018 = 3};
-enum evOperationType					{Charge = 0, Discharge = 1, Standby = 2};
-enum mechanicalChargingDeviceStatusType {Home = 0, Moving = 1, EndPosition = 2};
-enum EV_CP_StatusType					{A = 0, B = 1, C = 2, D = 3, E = 4, F = 5};
-enum EV_Error_Status_CodeType			{ No_EV_Error = 0, EV_FAILED_EmergencyEvent = 1, EV_FAILED_Breaker = 2, EV_FAILED_RESSTemperatureInhibit = 3,
-						 			  EV_FAILED_RESS = 4, EV_FAILED_ChargingCurrentDifferential = 5, EV_FAILED_ChargingVoltageOutOfRange = 6,
-						 			  Reserved_by_ISO_1 = 7,  Reserved_by_ISO_2 = 8, Reserved_by_ISO_3 = 9, OEM1 = 10,
-						 			  OEM2 = 11,  OEM3 = 12, OEM4 = 13};
-enum IsolationStatusType				{ Invalid = 0, Safe = 1, Warning = 2, Fault = 3};
-enum ChargingSessionType				{ Terminate = 0, Pause = 1};
-enum CostKindType						{ relativePricePercentage = 0, RenewableGenerationPercentage = 1, CarbonDioxideEmission = 2};
-
-
-
-struct PhysicalValueType_DIN70121 				//The final physical value is determined by: Value * 10 ^ Multiplier [Unit]
-{
-	int									Multiplier;			//range: -3..+3
-	enum unitSymbolType_DIN70121			Unit;
-	short 								Value;
-};
-struct PhysicalValueType_ISO15118_2014			//The final physical value is determined by: Value * 10 ^ Multiplier [Unit]
-{
-	int									Multiplier;			//range: -3..+3
-	enum unitSymbolType_ISO15118_2014		Unit;
-	short 								Value;
-};
-struct PhysicalValueType_ISO15118_2018			//The final physical value is determined by: Value * 10 ^ Exponent [Unit]
-{
-	int									Exponent;		//range: -3..+3
-	short 								Value;
-};
-struct AppProtocolType
-{
-	unsigned char	ProtocolNamespace[100];
-	unsigned int	VersionNumberMajor;
-	unsigned int	VersionNumberMinor;
-	unsigned char	SchemaID;
-	unsigned char	Priority;					//range 1..20
-};
-struct ACD_SSEnergyTransferModeType
-{
-	unsigned char	EVID[20];
-};
-struct EVSEStatusType
-{
-	unsigned short				NotificationMaxDelay;	//in seconds
-	enum EVSENotificationType	EVSENotification;
-};
-struct ServiceIDListType
-{
-	unsigned short	ServiceID[10];	//refer to chapter 8.6.2.1 Table 192
-};
-struct PaymentOptionListType
-{
-	enum PaymentOptionType	PaymentOption[2];
-};
-struct ServiceTagType
-{
-	unsigned short				ServiceID;
-	unsigned char				ServiceName[32];//Optional Element
-	enum ServiceCategoryType	ServiceCategory;
-	unsigned char				ServiceScope[32];//Optional Element
-};
-struct ServiceType_DIN70121
-{
-	struct ServiceTagType		ServiceTag;
-	BOOL					FreeService;
-};
-struct ServiceType_ISO15118_2014
-{
-	unsigned short				ServiceID;
-	unsigned char				ServiceName[32];	//Optional
-	enum ServiceCategoryType	ServiceCategory;
-	unsigned char				ServiceScope[64];	//Optional
-	BOOL					FreeService;
-};
-/*struct ServiceType_ISO15118_2018
-{
-	unsigned short				ServiceID;
-	BOOL					FreeService;
-}; */
-struct SupportedEnergyTransferModeType
-{
-	enum EnergyTransferModeType	EnergyTransferMode[6];
-};
-struct ServiceChargeType
-{
-	struct ServiceType_DIN70121				Services;
-	//enum EVSESupportedEnergyTransferType		EnergyTransferType;
-	enum EnergyTransferModeType			EnergyTransferType;
-};
-
-struct ChargeServiceType
-{
-	struct ServiceType_ISO15118_2014			Services;
-	struct SupportedEnergyTransferModeType	SupportedEnergyTransferMode;
-};
-struct ServiceListType
-{
-	struct ServiceType_ISO15118_2014			Service[8];
-};
-struct IdentificationOptionListType
-{
-	enum PaymentOptionType				IdentificationOption[2];
-};
-struct ParameterType
-{
-	unsigned char							Name[32];
-	struct PhysicalValueType_ISO15118_2014		PhysicalValue_ISO15118_2014;
-	struct PhysicalValueType_ISO15118_2018		PhysicalValue_ISO15118_2018;
-};
-struct ParameterSetType
-{
-	short 				ParameterSetID;
-	struct ParameterType	Parameter[16];
-};
-struct ServiceParameterListType
-{
-	struct ParameterSetType		ParameterSet[255];
-};
-struct WPT_SDlEnergyTransferModeType
-{
-	struct ServiceParameterListType	ServiceParameterList;
-};
-struct SelectedServiceType
-{
-	unsigned short			ServiceID;
-	short					ParameterSetID;
-};
-struct SelectedServiceListType
-{
-	struct SelectedServiceType	SelectedService[16];
-};
-
-struct CertificateChainType
-{
-	unsigned char 				Id[32];				//Optional
-	unsigned char 				Certificate[800];		//check size again
-	unsigned char				SubCertificates[4][800];	//Optional, 	check size again
-};
-struct PNC_AReqIdentificationModeType
-{
-	unsigned char 			GenChallenge[16];					//DIN70121=> None,	ISO15118_2014=>None,	ISO15118_2018=>Optional
-	unsigned char 			Id[32];							//DIN70121=> None,	ISO15118_2014=>None,	ISO15118_2018=>Optional
-};
-struct AC_EVChargeParameterType
-{
-	unsigned int 								DepartureTime;		//Optional
-	struct PhysicalValueType_ISO15118_2014			EAmount;
-	struct PhysicalValueType_ISO15118_2014			EVMaxVoltage;
-	struct PhysicalValueType_ISO15118_2014			EVMaxCurrent;
-	struct PhysicalValueType_ISO15118_2014			EVMinCurrent;
-};
-struct DC_EVStatusType_DIN70121
-{
-	BOOL						EVReady;
-	BOOL						EVCabinConditioning;
-	BOOL						EVRESSConiditioning;
-	enum DC_EVErrorCodeType		EVErrorCode;
-	unsigned char 					EVRESSSOC;		/*0-100 percentage*/
-};
-struct DC_EVChargeParameterType_DIN70121
-{
-	struct DC_EVStatusType_DIN70121			DC_EVStatus;
-	struct PhysicalValueType_DIN70121		EVMaximumCurrentLimit;
-	struct PhysicalValueType_DIN70121		EVMaximumPowerLimit;			//Optional
-	struct PhysicalValueType_DIN70121		EVMaximumVoltageLimit;
-	struct PhysicalValueType_DIN70121		EVEnergyCapacity;				//Optional
-	struct PhysicalValueType_DIN70121		EVEnergyRequest;				//Optional
-	unsigned char							FullSOC;/*0-100 percentage*/	//Optional
-	unsigned char							BulkSOC;/*0-100 percentage*/	//Optional
-};
-struct DC_EVStatusType_ISO15118_2014
-{
-	BOOL						EVReady;
-	enum DC_EVErrorCodeType		EVErrorCode;
-	unsigned char 					EVRESSSOC;		/*0-100 percentage*/
-};
-struct DC_EVChargeParameterType_ISO15118_2014
-{
-	unsigned int 								DepartureTime;				//Optional
-	struct DC_EVStatusType_ISO15118_2014			DC_EVStatus;
-	struct PhysicalValueType_ISO15118_2014 			EVMaximumCurrentLimit;
-	struct PhysicalValueType_ISO15118_2014			EVMaximumPowerLimit;			//Optional
-	struct PhysicalValueType_ISO15118_2014			EVMaximumVoltageLimit;
-	struct PhysicalValueType_ISO15118_2014			EVEnergyCapacity;				//Optional
-	struct PhysicalValueType_ISO15118_2014			EVEnergyRequest;				//Optional
-	unsigned char								FullSOC;/*0-100 percentage*/		//Optional
-	unsigned char								BulkSOC;/*0-100 percentage*/	//Optional
-};
-struct Dynamic_CPDReqControlModeType
-{
-	unsigned int 								DepartureTime;
-};
-struct RelativeTimeIntervalType
-{
-	unsigned int 	duration;			//Optional
-	unsigned int	start;
-};
-struct PMaxScheduleEntryType
-{
-	struct RelativeTimeIntervalType	RelativeTimeInterval;
-	unsigned short					PMax;
-};
-struct PMaxScheduleType
-{
-	unsigned short					PMaxScheduleID;			//no this itme in ISO15118_2014
-	struct PMaxScheduleEntryType		PMaxScheduleEntry[1024];
-};
-struct CostType
-{
-	unsigned int 					amount;
-	enum CostKindType				costKind;
-	int 							amountMultiplier;		//Optional , range: -3..+3
-};
-struct ConsumptionCostType
-{
-	struct CostType						Cost[3];
-	struct PhysicalValueType_ISO15118_2014		startValue;
-};
-struct SalesTariffEntryType
-{
-	struct RelativeTimeIntervalType	RelativeTimeInterval;
-	unsigned char 					EPriceLevel;			//Optional
-	struct ConsumptionCostType		ConsumptionCost[3];	//Optional
-};
-struct SalesTariffType
-{
-	unsigned char 					Id[32];					//Optional
-	short 						SalesTariffID;
-	unsigned char 					SalesTariffDescription[32];	//Optional
-	unsigned char 					NumEPriceLevels;			//Optional
-	struct SalesTariffEntryType			SalesTariffEntry[1024];
-};
-struct SAScheduleTupleType
-{
-	short 						SAScheduleTupleID;
-	struct PMaxScheduleType			PMaxSchedule;
-	struct SalesTariffType				SalesTariff;				//Optional
-};
-struct ScheduleListType
-{
-	enum ScheduleOriginType					ScheduleOrigin;
-	struct SAScheduleTupleType					ScheduleTuple[3];
-};
-struct Scheduled_CPDReqControlModeType
-{
-	enum ProcessingType						EVProcessing;
-	unsigned int 								DepartureTime;		//Optional
-	unsigned short 							MaxSupportingPoints;
-	struct ScheduleListType						ScheduleList;			//Optional
-};
-struct AC_CPDReqEnergyTransferModeType
-{
-	struct PhysicalValueType_ISO15118_2018			EVTargetEnergyRequest;			//Optional
-	struct PhysicalValueType_ISO15118_2018			EVMaximumEnergyRequest;		//Optional
-	struct PhysicalValueType_ISO15118_2018			EVMinimumEnergyRequest;		//Optional
-	struct PhysicalValueType_ISO15118_2018			EVMaximumChargePower;
-	struct PhysicalValueType_ISO15118_2018			EVMaximumChargeCurrent;
-	struct PhysicalValueType_ISO15118_2018			EVMinimumChargeCurrent;
-	struct PhysicalValueType_ISO15118_2018			EVMaximumVoltage;
-};
-struct DC_CPDReqEnergyTransferModeType
-{
-	struct PhysicalValueType_ISO15118_2018			EVMaximumChargePower;			//Optional
-	struct PhysicalValueType_ISO15118_2018			EVMinimumChargePower;			//Optional
-	struct PhysicalValueType_ISO15118_2018			EVMaximumChargeCurrent;
-	struct PhysicalValueType_ISO15118_2018			EVMinimumChargeCurrent;
-	struct PhysicalValueType_ISO15118_2018			EVMaximumVoltage;
-	struct PhysicalValueType_ISO15118_2018			EVTargetEnergyRequest;				//Optional
-	struct PhysicalValueType_ISO15118_2018			EVMaximumEnergyRequest;			//Optional
-	struct PhysicalValueType_ISO15118_2018			EVMinimumEnergyRequest;			//Optional
-	unsigned char								TargetSOC;						//Optional
-	unsigned char								BulkSOC;							//Optional
-};
-struct BPT_AC_CPDReqEnergyTransferModeType
-{
-	struct PhysicalValueType_ISO15118_2018			EVMaximumChargePower;
-	struct PhysicalValueType_ISO15118_2018			EVMaximumDischargePower;
-	struct PhysicalValueType_ISO15118_2018			EVMinimumDischargePower;
-	struct PhysicalValueType_ISO15118_2018			EVMaximumChargeCurrent;
-	struct PhysicalValueType_ISO15118_2018			EVMaximumDischargeCurrent;
-	struct PhysicalValueType_ISO15118_2018			EVMinimumChargeCurrent;
-	struct PhysicalValueType_ISO15118_2018			EVMinimumDischargeCurrent;
-	struct PhysicalValueType_ISO15118_2018			EVTargetEnergyRequest;				//Optional
-	struct PhysicalValueType_ISO15118_2018			EVMinimumEnergyRequest;			//Optional
-	struct PhysicalValueType_ISO15118_2018			EVMaximumEnergyRequest;			//Optional
-	struct PhysicalValueType_ISO15118_2018			EVMaximumVoltage;
-};
-struct BPT_DC_CPDReqEnergyTransferModeType
-{
-	struct PhysicalValueType_ISO15118_2018			EVMaximumChargePower;
-	struct PhysicalValueType_ISO15118_2018			EVMinimumChargePower;
-	struct PhysicalValueType_ISO15118_2018			EVMaximumDischargePower;
-	struct PhysicalValueType_ISO15118_2018			EVMinimumDischargePower;
-	struct PhysicalValueType_ISO15118_2018			EVMaximumChargeCurrent;
-	struct PhysicalValueType_ISO15118_2018			EVMinimumChargeCurrent;
-	struct PhysicalValueType_ISO15118_2018			EVMaximumDischargeCurrent;
-	struct PhysicalValueType_ISO15118_2018			EVMinimumDischargeCurrent;
-	struct PhysicalValueType_ISO15118_2018			EVMaximumVoltage;
-	struct PhysicalValueType_ISO15118_2018			EVMinimumVoltage;
-	struct PhysicalValueType_ISO15118_2018			EVTargetEnergyRequest;
-	struct PhysicalValueType_ISO15118_2018			EVMaximumEnergyRequest;
-	struct PhysicalValueType_ISO15118_2018			EVMinimumEnergyRequest;
-	unsigned char								TargetSOC;					//Optional
-	unsigned char								BulkSOC;						//Optional
-};
-struct WPT_CPDReqEnergyTransferModeType
-{
-	struct PhysicalValueType_ISO15118_2018			EVMaximumPower;				//Optional
-	struct PhysicalValueType_ISO15118_2018			EVMinimumPower;				//Optional
-	struct PhysicalValueType_ISO15118_2018			EVTargetEnergyRequest;			//Optional
-	struct PhysicalValueType_ISO15118_2018			EVMaximumEnergyRequest;		//Optional
-	struct PhysicalValueType_ISO15118_2018			EVMinimumEnergyRequest;		//Optional
-};
-struct ACD_CPDReqEnergyTransferModeType
-{
-	//cannot be found in standard
-};
-struct SAScheduleListType
-{
-	struct SAScheduleTupleType		SAScheduleTuple[3];
-};
-struct DC_EVSEStatusType_DIN70121
-{
-	enum IsolationLevelType_DIN70121			EVSEIsolationStatus;			//Optional
-	enum DC_EVSEStatusCodeType			EVSEStatusCode;
-	unsigned int							NotificationMaxDelay;
-	enum EVSENotificationType				EVSENotification;
-};
-struct DC_EVSEChargeParameterType_DIN70121
-{
-	struct DC_EVSEStatusType_DIN70121		DC_EVSEStatus;
-	struct PhysicalValueType_DIN70121			EVSEMaximumCurrentLimit;
-	struct PhysicalValueType_DIN70121			EVSEMaximumPowerLimit;			//Optional
-	struct PhysicalValueType_DIN70121			EVSEMaximumVoltageLimit;
-	struct PhysicalValueType_DIN70121			EVSEMinimumCurrentLimit;
-	struct PhysicalValueType_DIN70121			EVSEMinimumVoltageLimit;
-	struct PhysicalValueType_DIN70121			EVSECurrentRegulationTolerance;		//Optional
-	struct PhysicalValueType_DIN70121			EVSEPeakCurrentRipple;
-	struct PhysicalValueType_DIN70121			EVSEEnergyToBeDelivered;			//Optional
-};
-struct AC_EVSEStatusType
-{
-	BOOL							  		RCD;
-	unsigned short 							NotificationMaxDelay;
-	enum EVSENotificationType					EVSENotification;		//need to be confirmed
-};
-struct AC_EVSEChargeParameterType
-{
-	struct AC_EVSEStatusType					AC_EVSEStatus;
-	struct PhysicalValueType_ISO15118_2014			EVSENominalVoltage;
-	struct PhysicalValueType_ISO15118_2014			EVSEMaxCurrent;
-};
-struct DC_EVSEStatusType_ISO15118_2014
-{
-	unsigned short								NotificationMaxDelay;
-	enum EVSENotificationType					EVSENotification;
-	enum IsolationLevelType_ISO15118_2014			EVSEIsolationStatus;					//Optional
-	enum DC_EVSEStatusCodeType				DC_EVSEStatusCode;
-};
-struct DC_EVSEChargeParameterType_ISO15118_2014
-{
-	struct DC_EVSEStatusType_ISO15118_2014		DC_EVSEStatus;
-	struct PhysicalValueType_ISO15118_2014			EVSEMaximumCurrentLimit;
-	struct PhysicalValueType_ISO15118_2014			EVSEMaximumPowerLimit;
-	struct PhysicalValueType_ISO15118_2014			EVSEMaximumVoltageLimit;
-	struct PhysicalValueType_ISO15118_2014			EVSEMinimumCurrentLimit;
-	struct PhysicalValueType_ISO15118_2014			EVSEMinimumVoltageLimit;
-	struct PhysicalValueType_ISO15118_2014			EVSECurrentRegulationTolerance;		//Optional
-	struct PhysicalValueType_ISO15118_2014			EVSEPeakCurrentRipple;
-	struct PhysicalValueType_ISO15118_2014			EVSEEnergyToBeDelivered;			//Optional
-};
-struct Scheduled_CPDResControlModeType
-{
-	struct ScheduleListType						ScheduleList;
-};
-struct AC_CPDResEnergyTransferModeType
-{
-	struct PhysicalValueType_ISO15118_2018			EVSEMaximumChargeCurrent[3];
-	struct PhysicalValueType_ISO15118_2018			EVSENominalVoltage;
-	struct PhysicalValueType_ISO15118_2018			EVSENominalFrequency;
-};
-struct DC_CPDResEnergyTransferModeType
-{
-	struct PhysicalValueType_ISO15118_2018			EVSEMaximumChargePower;
-	struct PhysicalValueType_ISO15118_2018			EVSEMaximumChargeCurrent;
-	struct PhysicalValueType_ISO15118_2018			EVSEMinimumChargeCurrent;
-	struct PhysicalValueType_ISO15118_2018			EVSEMaximumVoltage;
-	struct PhysicalValueType_ISO15118_2018			EVSEMinimumVoltage;
-};
-struct BPT_AC_CPDResEnergyTransferModeType
-{
-	struct PhysicalValueType_ISO15118_2018			EVSEMaximumChargeCurrent[3];
-	struct PhysicalValueType_ISO15118_2018			EVSEMaximumDischargeCurrent[3];
-	struct PhysicalValueType_ISO15118_2018			EVSENominalVoltage;
-	struct PhysicalValueType_ISO15118_2018			EVSENominalFrequency;
-};
-struct BPT_DC_CPDResEnergyTransferModeType
-{
-	struct PhysicalValueType_ISO15118_2018			EVSEMaximumChargePower;
-	struct PhysicalValueType_ISO15118_2018			EVSEMaximumDischargePower;
-	struct PhysicalValueType_ISO15118_2018			EVSEMaximumChargeCurrent;
-	struct PhysicalValueType_ISO15118_2018			EVSEMaximumDischargeCurrent;
-	struct PhysicalValueType_ISO15118_2018			EVSEMinimumChargeCurrent;
-	struct PhysicalValueType_ISO15118_2018			EVSEMinimumDischargeCurrent;
-	struct PhysicalValueType_ISO15118_2018			EVSEMaximumVoltage;
-	struct PhysicalValueType_ISO15118_2018			EVSEMinimumVoltage;
-};
-struct WPT_CPDResEnergyTransferModeType
-{
-	struct PhysicalValueType_ISO15118_2018			EVSEMaximumPower;
-	struct PhysicalValueType_ISO15118_2018			EVSEMinimumPower;
-};
-struct ACD_CPDResEnergyTransferModeType
-{
-	//not found in ISO15118_2018
-};
-struct ProfileEntryType_DIN70121
-{
-	unsigned int 				ChargingProfileEntryStart;
-	short						ChargingProfileEntryMaxPower;
-};
-struct ChargingProfileType_DIN70121
-{
-	short 							SAScheduleTupleID;
-	struct ProfileEntryType_DIN70121		ProfileEntry[24];
-};
-struct DC_EVPowerDeliveryParameterType_DIN70121
-{
-	struct DC_EVStatusType_DIN70121			DC_EVStatus;
-	BOOL								BulkChargingComplete;		//Optional
-	BOOL								ChargingComplete;
-};
-struct ProfileEntryType_ISO15118_2014
-{
-	unsigned int 								ChargingProfileEntryStart;
-	struct PhysicalValueType_ISO15118_2018			ChargingProfileEntryMaxPower;
-	unsigned char 								ChargingProfileEntryMaxNumberOfPhasesInUse;	//Optional
-};
-struct ChargingProfileType_ISO15118_2014
-{
-	struct ProfileEntryType_ISO15118_2014			ProfileEntry[24];
-};
-struct DC_EVPowerDeliveryParameterType_ISO15118_2014
-{
-	struct DC_EVStatusType_ISO15118_2014 			DC_EVStatus;
-	BOOL									BulkChargingComplete;		//Optional
-	BOOL									ChargingComplete;
-};
-struct TimeInterval
-{
-	unsigned int 								start;
-	unsigned int 								duration;				//Optional
-};
-struct PowerScheduleEntryType
-{
-	struct TimeInterval							TimeInterval;
-	struct PhysicalValueType_ISO15118_2018			Power[3];
-};
-struct EVPowerProfileType
-{
-	struct PowerScheduleEntryType				EVPowerProfileEntry[2048];
-};
-struct Scheduled_PDReqControlModeType
-{
-	unsigned char 								ScheduleTupleID;
-	struct EVPowerProfileType					EVPowerProfile;
-};
-struct BPT_Scheduled_PDReqControlModeType
-{
-	unsigned char 								ScheduleTupleID;
-	struct EVPowerProfileType					EVPowerProfile;			//Optional
-	enum evOperationType						EVOperation;
-};
-struct ListOfRootCertificateIDsType
-{
-	unsigned char 								RootCertificateID[20][40];
-};
-struct ContractSignatureEncryptedPrivateKeyType
-{
-	unsigned char 								Id[32];
-};
-struct DiffieHellmanPublickeyType
-{
-	unsigned char 								Id[32];
-};
-struct ContractCertificateEncryptedPrivateKeyType
-{
-	unsigned char 								Id[32];
-};
-struct EVTechnicalStatusType
-{
-	BOOL									EV_Status_ReadyToCharge;
-	BOOL									EV_Status_ImmobilizationRequest;		//Optional
-	BOOL									EV_Status_Immobilized;
-	struct PhysicalValueType_ISO15118_2018			EV_Status_WLAN_Strength;
-	enum EV_CP_StatusType						EV_CP_Status;
-	unsigned char								EV_Status_RESSSOC;					//0~100%
-	enum EV_Error_Status_CodeType				EV_Error_Status_Code;
-	BOOL									EVSE_Timeout;
-};
-struct MeterInfoType_ISO15118_2014
-{
-	unsigned char								MeterID[32];
-	unsigned long 								MeterReading;						//Optional
-	unsigned char								SigMeterReading[64];				//Optional
-	short 									MeterStatus;						//Optional
-	short 									TMeter;							//Optional
-};
-struct Scheduled_MRReqControlModeType
-{
-	unsigned char 								ScheduleTupleID;
-};
-struct MeterInfoType_ISO15118_2018
-{
-	unsigned char								MeterID[32];
-	unsigned long 								MeterReadingWhCharged;			//Optional
-	unsigned long 								MeterReadingWhDischarged;			//Optional
-	unsigned long 								MeterReadingVARhLeading;			//Optional
-	unsigned long 								MeterReadingVARhLagging;			//Optional
-	unsigned char								SignatureMeterReading[64];			//Optional
-	short 									MeterStatus;						//Optional
-	short 									TimeStampMeter;					//Optional
-	BOOL									ReceiptRequired;					//Optional
-};
-struct PnC_CLReqIdentificationModeType
-{
-	BOOL									MeteringReceiptRequested;
-};
-struct Dynamic_CSReqControlModeType
-{
-	struct PhysicalValueType_ISO15118_2018			EVTargetEnergyRequest;
-	struct PhysicalValueType_ISO15118_2018			EVMaximumEnergyRequest;
-	struct PhysicalValueType_ISO15118_2018			EVMinimumEnergyRequest;
-	struct PhysicalValueType_ISO15118_2018			EVMaximumChargePower;
-	struct PhysicalValueType_ISO15118_2018			EVMaximumChargeCurrent;
-	struct PhysicalValueType_ISO15118_2018			EVMinimumChargeCurrent;
-};
-struct Scheduled_CSReqControlModeType
-{
-	struct PhysicalValueType_ISO15118_2018			EVTargetEnergyRequest;				//Optional
-	struct PhysicalValueType_ISO15118_2018			EVMaximumEnergyRequest;			//Optional
-	struct PhysicalValueType_ISO15118_2018			EVMinimumEnergyRequest;			//Optional
-	BOOL									Standby;
-	struct PhysicalValueType_ISO15118_2018			EVMaximumChargePower;			//Optional
-	struct PhysicalValueType_ISO15118_2018			EVMaximumChargeCurrent;			//Optional
-	struct PhysicalValueType_ISO15118_2018			EVMinimumChargeCurrent;			//Optional
-};
-struct DisplayParametersType
-{
-	unsigned short 							CurrentRange;
-	unsigned char	 							CurrentSOC;						//0~100%
-	unsigned char	 							MinimumSOC;						//0~100%
-	struct PhysicalValueType_ISO15118_2018			RemainingTimeToMaximumSOC;
-	struct PhysicalValueType_ISO15118_2018			RemainingTimeToTargetSOC;
-	struct PhysicalValueType_ISO15118_2018			RemainingTimeToBulkSOC;
-	struct PhysicalValueType_ISO15118_2018			RemainingTimeToMinimumSOC;
-	BOOL									ChargingComplete;
-	BOOL									BulkChargingComplete;
-	BOOL									InletHot;
-};
-struct PnC_CLResIdentificationModeType
-{
-	struct MeterInfoType_ISO15118_2018			MeterInfo;
-};
-struct Dynamic_CSResControlModeType
-{
-	struct PhysicalValueType_ISO15118_2018			EVSETargetActivePower;
-};
-struct Scheduled_CDResControlModeType
-{
-	struct PhysicalValueType_ISO15118_2018			EVSEMaximumChargePower;		//Optional
-	struct PhysicalValueType_ISO15118_2018			EVSEMaximumChargeCurrent;	//Optional
-	struct PhysicalValueType_ISO15118_2018			EVSEMaximumVoltage;			//Optional
-};
-struct LFA_EVFinePositioningSetupParametersType
-{
-	unsigned char 								NumberOfSensors;
-	//NOT complete yet,  to be continue.....
-};
-
-/****SupportedAppProtocolRequest****/
-struct SupportedAppProtocolRequest_DIN70121
-{
-	struct AppProtocolType	AppProtocol[20];
-};
-struct SupportedAppProtocolRequest_ISO15118_2014
-{
-	struct AppProtocolType	AppProtocol[20];
-};
-struct SupportedAppProtocolRequest_ISO15118_2018
-{
-	struct AppProtocolType	AppProtocol[20];
-};
-/****SupportedAppProtocolResponse****/
-struct SupportedAppProtocolResponse_DIN70121
-{
-	enum ResponseCodeType_DIN70121		ResponseCode;
-	unsigned char							SchemaID;				//Optional
-};
-struct SupportedAppProtocolResponse_ISO15118_2014
-{
-	enum ResponseCodeType_ISO15118_2014	ResponseCode;
-	unsigned char							SchemaID;				//Optional
-};
-struct SupportedAppProtocolResponse_ISO15118_2018
-{
-	enum ResponseCodeType_ISO15118_2018	ResponseCode;
-	unsigned char							SchemaID;					//Optional
-};
-/****SessionSetupRequest****/
-struct SessionSetupRequest_DIN70121
-{
-	unsigned char						EVCCID[8];						//the MAC address of the EVCC in Hex
-};
-struct SessionSetupRequest_ISO15118_2014
-{
-	unsigned char						EVCCID[8];						//the MAC address of the EVCC in Hex
-};
-struct SessionSetupRequest_ISO15118_2018
-{
-	unsigned char						EVCCID[8];						//the MAC address of the EVCC in Hex
-	struct ACD_SSEnergyTransferModeType	ACD_SSEnergyTransferMode;			//For ACD mandatory, optional for rest
-};
-/****SessionSetupResponse****/
-struct SessionSetupResponse_DIN70121
-{
-	enum ResponseCodeType_DIN70121		ResponseCode;
-	unsigned char							EVSEID[40];					//DIN70121=>Max length:32,	ISO15118=>min length:7, max length:37
-	unsigned int							EVSETimeStamp;				//EPOCH format, Optional
-};
-struct SessionSetupResponse_ISO15118_2014
-{
-	enum ResponseCodeType_ISO15118_2014	ResponseCode;
-	unsigned char							EVSEID[40];					//DIN70121=>Max length:32,	ISO15118=>min length:7, max length:37
-	unsigned int							EVSETimeStamp;				//EPOCH format, Optional
-};
-struct SessionSetupResponse_ISO15118_2018
-{
-	enum ResponseCodeType_ISO15118_2018	ResponseCode;
-	unsigned char							EVSEID[40];					//DIN70121=>Max length:32,	ISO15118=>min length:7, max length:37
-	struct EVSEStatusType					EVSEStatus;					//Optional
-};
-/****ServiceDiscoveryRequest****/
-struct ServiceDiscoveryRequest_DIN70121
-{
-	unsigned char				ServiceScope[32];		//Optional
-	enum ServiceCategoryType	ServiceCategory;		//Optional
-};
-struct ServiceDiscoveryRequest_ISO15118_2014
-{
-	unsigned char				ServiceScope[32];		//Optional
-	enum ServiceCategoryType	ServiceCategory;		//Optional
-};
-struct ServiceDiscoveryRequest_ISO15118_2018
-{
-	struct ServiceIDListType		SupportedServiceIDs;	//Optional
-};
-/****ServiceDiscoveryResponse****/
-struct ServiceDiscoveryResponse_DIN70121
-{
-	enum ResponseCodeType_DIN70121		ResponseCode;
-	struct PaymentOptionListType				PaymentOptions;
-	struct ServiceChargeType				ChargeService_DIN70121;
-};
-struct ServiceDiscoveryResponse_ISO15118_2014
-{
-	enum ResponseCodeType_ISO15118_2014	ResponseCode;
-	struct PaymentOptionListType				PaymentOptions;
-	struct ChargeServiceType				ChargeService;
-	struct ServiceListType					ServiceList;					//Optional
-};
-struct ServiceDiscoveryResponse_ISO15118_2018
-{
-	enum ResponseCodeType_ISO15118_2018	ResponseCode;
-	struct EVSEStatusType					EVSEStatus;					//Optional
-	struct IdentificationOptionListType			IdentificationOptionList;
-	struct ServiceListType					EnergyTransferServiceList;
-	struct ServiceListType					VASList;						//Optional
-};
-/****ServiceDetailRequest****/
-//Only in ISO15118_2014 and ISO15118_2018
-struct ServiceDetailRequest_ISO15118_2014
-{
-	unsigned short						ServiceID;
-};
-struct ServiceDetailRequest_ISO15118_2018
-{
-	unsigned short						ServiceID;
-	struct WPT_SDlEnergyTransferModeType	WPT_SDlEnergyTransferMode;
-};
-/****ServiceDetailResponse****/
-struct ServiceDetailResponse_ISO15118_2014
-{
-	enum ResponseCodeType_ISO15118_2014	ResponseCode;
-	unsigned short							ServiceID;
-	struct ServiceParameterListType 			ServiceParameterList;
-};
-struct ServiceDetailResponse_ISO15118_2018
-{
-	enum ResponseCodeType_ISO15118_2018	ResponseCode;
-	unsigned short							ServiceID;
-	struct ServiceParameterListType 			ServiceParameterList;
-	struct EVSEStatusType					EVSEStatus;					//Optional
-};
-/****ServiceAndPaymentSelectionRequest / ServiceSelectionRequest****/
-struct ServiceAndPaymentSelectionRequest_DIN70121
-{
-	enum PaymentOptionType		SelectedPaymentOption;
-	struct SelectedServiceListType		SelectedServiceList;
-};
-struct ServiceAndPaymentSelectionRequest_ISO15118_2014
-{
-	enum PaymentOptionType		SelectedPaymentOption;
-	struct SelectedServiceListType		SelectedServiceList;
-};
-struct ServiceSelectionRequest_ISO15118_2018
-{
-	enum PaymentOptionType			SelectedPaymentOption;
-	struct SelectedServiceType			SelectedEnergyTransferService;
-	struct SelectedServiceListType			SelectedVASList;
-	enum ProcessingType				EVProcessing;
-};
-/****ServiceAndPaymentSelectionResponse / ServiceSelectionResponse****/
-struct ServiceAndPaymentSelectionResponse_DIN70121
-{
-	enum ResponseCodeType_DIN70121		ResponseCode;
-};
-struct ServiceAndPaymentSelectionResponse_ISO15118_2014
-{
-	enum ResponseCodeType_ISO15118_2014	ResponseCode;
-};
-struct ServiceSelectionResponse_ISO15118_2018
-{
-	enum ResponseCodeType_ISO15118_2018	ResponseCode;
-	struct EVSEStatusType					EVSEStatus;					//Optional
-};
-/****PaymentDetailsRequest / IdentificationDetailsRequest****/
-struct PaymentDetailsRequest_ISO15118_2014
-{
-	unsigned char 					eMAID[16];
-	struct CertificateChainType		ContractSignatureCertChain;
-};
-struct IdentificationDetailsRequest_ISO15118_2018
-{
-	struct CertificateChainType		ContractSignatureCertChain;
-};
-/****PaymentDetailsResponse  / IdentificationDetailsResponse ****/
-struct PaymentDetailsResponse_ISO15118_2014
-{
-	enum ResponseCodeType_ISO15118_2014	ResponseCode;
-	unsigned char 							GenChallenge[16];
-	long 								EVSETimeStamp;
-};
-struct IdentificationDetailsResponse_ISO15118_2018
-{
-	enum ResponseCodeType_ISO15118_2018	ResponseCode;
-	struct EVSEStatusType					EVSEStatus;						//Optional
-	unsigned char 							GenChallenge[16];
-	enum ProcessingType					EVSEProcessing;
-};
-/****ContractAuthenticationRequest / AuthorizationRequest****/
-struct ContractAuthenticationRequest_DIN70121
-{
-	//None
-};
-struct AuthorizationRequest_ISO15118_2014
-{
-	unsigned char 			GenChallenge[16];					//Optional
-	unsigned char 			Id[32];							//Optional
-};
-struct AuthorizationRequest_ISO15118_2018
-{
-	struct PNC_AReqIdentificationModeType		PNC_AReqIdentificationMode;	//Optional
-};
-/****ContractAuthenticationResponse  / AuthorizationResponse****/
-struct ContractAuthenticationResponse_DIN70121
-{
-	enum ResponseCodeType_DIN70121		ResponseCode;
-	enum EVSEProcessingType_DIN70121		EVSEProcessing;
-};
-struct AuthorizationResponse_ISO15118_2014
-{
-	enum ResponseCodeType_ISO15118_2014	ResponseCode;
-	enum EVSEProcessingType_ISO15118_2014	EVSEProcessing;
-};
-struct AuthorizationResponse_ISO15118_2018
-{
-	enum ResponseCodeType_ISO15118_2018	ResponseCode;
-	enum ProcessingType					EVSEProcessing;
-	struct EVSEStatusType					EVSEStatus;						//Optional
-};
-/****ChargeParameterDiscoveryRequest****/
-struct ChargeParameterDiscoveryRequest_DIN70121
-{
-	enum EnergyTransferModeType					EVRequestedEnergyTransferType;
-	struct DC_EVChargeParameterType_DIN70121		DC_EVChargeParameter;
-};
-struct ChargeParameterDiscoveryRequest_ISO15118_2014
-{
-	unsigned short										MaxEntriesSAScheduleTuple;			//Optional
-	enum EnergyTransferModeType						RequestedEnergyTransferMode;
-	struct AC_EVChargeParameterType					AC_EVChargeParameter;
-	struct DC_EVChargeParameterType_ISO15118_2014		DC_EVChargeParameter;
-};
-struct ChargeParameterDiscoveryRequest_ISO15118_2018
-{
-	struct Dynamic_CPDReqControlModeType			Dynamic_CPDReqControlMode;
-	struct Scheduled_CPDReqControlModeType			Scheduled_CPDReqControlMode;
-	struct AC_CPDReqEnergyTransferModeType			AC_CPDReqEnergyTransferMode;
-	struct DC_CPDReqEnergyTransferModeType			DC_CPDReqEnergyTransferMode;
-	struct BPT_AC_CPDReqEnergyTransferModeType		BPT_AC_CPDReqEnergyTransferMode;
-	struct BPT_DC_CPDReqEnergyTransferModeType		BPT_DC_CPDReqEnergyTransferMode;
-	struct WPT_CPDReqEnergyTransferModeType			WPT_CPDReqEnergyTransferMode;
-	struct ACD_CPDReqEnergyTransferModeType			ACD_CPDReqEnergyTransferMode;
-};
-/****ChargeParameterDiscoveryResponse****/
-struct ChargeParameterDiscoveryResponse_DIN70121
-{
-	enum ResponseCodeType_DIN70121					ResponseCode;
-	enum EVSEProcessingType_DIN70121					EVSEProcessing;
-	struct SAScheduleListType 							SAScheduleList;
-	struct DC_EVSEChargeParameterType_DIN70121			DC_EVSEChargeParameter;
-};
-struct ChargeParameterDiscoveryResponse_ISO15118_2014
-{
-	enum EVSEProcessingType_ISO15118_2014				EVSEProcessing;
-	enum ResponseCodeType_ISO15118_2014				ResponseCode;
-	struct SAScheduleListType 							SAScheduleList;
-	struct AC_EVSEChargeParameterType					AC_EVSEChargeParameter;
-	struct DC_EVSEChargeParameterType_ISO15118_2014		DC_EVSEChargeParameter;
-};
-struct ChargeParameterDiscoveryResponse_ISO15118_2018
-{
-	enum ResponseCodeType_ISO15118_2018				ResponseCode;
-	struct EVSEStatusType								EVSEStatus;					//Optional
-	enum ProcessingType								EVSEProcessing;
-	struct Scheduled_CPDResControlModeType				Scheduled_CPDResControlMode;	//Optional
-	struct AC_CPDResEnergyTransferModeType				AC_CPDResEnergyTransferMode;
-	struct DC_CPDResEnergyTransferModeType				DC_CPDResEnergyTransferMode;
-	struct BPT_AC_CPDResEnergyTransferModeType			BPT_AC_CPDResEnergyTransferMode;
-	struct BPT_DC_CPDResEnergyTransferModeType			BPT_DC_CPDResEnergyTransferMode;
-	struct WPT_CPDResEnergyTransferModeType				WPT_CPDResEnergyTransferMode;
-	struct ACD_CPDResEnergyTransferModeType				ACD_CPDResEnergyTransferMode;
-};
-/****PowerDeliveryRequest****/
-struct PowerDeliveryRequest_DIN70121
-{
-	BOOL											ReadyToChargeState;
-	struct ChargingProfileType_DIN70121					ChargingProfile;
-	struct DC_EVPowerDeliveryParameterType_DIN70121		DC_EVPowerDeliveryParameter;
-};
-struct PowerDeliveryRequest_ISO15118_2014
-{
-	enum ChargeProgressType_ISO15118_2014				ChargeProgress;
-	short 											SAScheduleTupleID;
-	struct ChargingProfileType_ISO15118_2014 				ChargingProfile;
-	struct DC_EVPowerDeliveryParameterType_ISO15118_2014	DC_EVPowerDeliveryParameter;
-};
-struct PowerDeliveryRequest_ISO15118_2018
-{
-	enum ChargeProgressType_ISO15118_2018				ChargeProgress;
-	struct Scheduled_PDReqControlModeType				Scheduled_PDReqControlMode;
-	struct BPT_Scheduled_PDReqControlModeType			BPT_Scheduled_PDReqControlMode;
-};
-/****PowerDeliveryResponse****/
-struct PowerDeliveryResponse_DIN70121
-{
-	enum ResponseCodeType_DIN70121				ResponseCode;
-	struct DC_EVSEStatusType_DIN70121				DC_EVSEStatus;
-};
-struct PowerDeliveryResponse_ISO15118_2014
-{
-	enum ResponseCodeType_ISO15118_2014				ResponseCode;
-	struct AC_EVSEStatusType							AC_EVSEStatus;
-	struct DC_EVSEStatusType_ISO15118_2014				DC_EVSEStatus;
-};
-struct PowerDeliveryResponse_ISO15118_2018
-{
-	enum ResponseCodeType_ISO15118_2018				ResponseCode;
-	struct EVSEStatusType								EVSEStatus;			//Optional
-};
-/****CertificateUpdateRequest****/
-struct CertificateUpdateRequest_ISO15118_2014
-{
-	unsigned char 										Id[32];
-	struct CertificateChainType							ContractSignatureCertChain;
-	unsigned char 										eMAID[16];
-	struct ListOfRootCertificateIDsType						ListOfRootCertificateIDs;
-};
-/****CertificateUpdateResponse****/
-struct CertificateUpdateResponse_ISO15118_2014
-{
-	enum ResponseCodeType_ISO15118_2014				ResponseCode;
-	struct CertificateChainType							SAProvisioningCertificateChain;
-	struct CertificateChainType							ContractSignatureCertChain;
-	struct ContractSignatureEncryptedPrivateKeyType			ContractSignatureEncryptedPrivateKey;
-	struct DiffieHellmanPublickeyType						DHpublickey;
-	unsigned char 										eMAID[16];
-	short 											RetryCounter;							//Optional
-};
-/****CertificateInstallationRequest****/
-struct CertificateInstallationRequest_ISO15118_2014
-{
-	unsigned char 										Id[32];
-	unsigned char 										OEMProvisioningCert[800];
-	struct ListOfRootCertificateIDsType						ListOfRootCertificateIDs;
-};
-struct CertificateInstallationRequest_ISO15118_2018
-{
-	unsigned char 										Id[32];
-	struct CertificateChainType							OEMProvisioningCertChain;
-	struct ListOfRootCertificateIDsType						ListOfRootCertificateIDs;
-	unsigned short										MaxSupportedCerts;
-};
-/****CertificateInstallationResponse****/
-struct CertificateInstallationResponse_ISO15118_2014
-{
-	enum ResponseCodeType_ISO15118_2014				ResponseCode;
-	struct CertificateChainType							SAProvisioningCertificateChain;
-	struct CertificateChainType							ContractSignatureCertChain;
-	struct ContractSignatureEncryptedPrivateKeyType			ContractSignatureEncryptedPrivateKey;
-	struct DiffieHellmanPublickeyType						DHpublickey;
-	unsigned char 										eMAID[16];
-};
-struct CertificateInstallationResponse_ISO15118_2018
-{
-	enum ResponseCodeType_ISO15118_2018				ResponseCode;
-	struct EVSEStatusType								EVSEStatus;					//Optional
-	struct CertificateChainType							SAProvisioningCertificateChain;
-	struct CertificateChainType							ContractCertificateChain;
-	struct ContractCertificateEncryptedPrivateKeyType		ContractEncryptedPrivateKey;
-	struct DiffieHellmanPublickeyType						DHpublickey;
-	enum ProcessingType								EVSEProcessing;
-	unsigned short 									RemainingContractCertificateChains;
-};
-/****SystemStatusRequest****/
-struct SystemStatusRequest_ISO15118_2018
-{
-	enum mechanicalChargingDeviceStatusType			EVMechanicalChargingDeviceStatus;
-	struct EVTechnicalStatusType							EVTechnicalStatus;
-	unsigned char 										EV_OEMStatus[800];					//Optional
-};
-/****SystemStatusResponse****/
-struct SystemStatusResponse_ISO15118_2018
-{
-	enum ResponseCodeType_ISO15118_2018				ResponseCode;
-	enum mechanicalChargingDeviceStatusType			EVSEMechanicalChargingDeviceStatus;
-	BOOL											EVSE_ReadyToCharge;
-	enum IsolationStatusType							EVSE_IsolationStatus;
-	BOOL											EVSE_Disabled;
-	BOOL											EVSE_UtilityInterruptEvent;
-	BOOL											EVSE_EmergencyShutdown;
-	BOOL											EVSE_Malfunction;
-	BOOL											EV_InChargePosition;
-	BOOL											EV_AssociationStatus;
-};
-/****SessionStopRequest****/
-struct SessionStopRequest_DIN70121
-{
-	//No member in standard
-};
-struct SessionStopRequest_ISO15118_2014
-{
-	enum ChargingSessionType							ChargingSession;
-};
-struct SessionStopRequest_ISO15118_2018
-{
-	enum ChargingSessionType							ChargingSession;
-};
-/****SessionStopResponse****/
-struct SessionStopResponse_DIN70121
-{
-	enum ResponseCodeType_DIN70121					ResponseCode;
-};
-struct SessionStopResponse_ISO15118_2014
-{
-	enum ResponseCodeType_ISO15118_2014				ResponseCode;
-};
-struct SessionStopResponse_ISO15118_2018
-{
-	enum ResponseCodeType_ISO15118_2018				ResponseCode;
-	struct EVSEStatusType								EVSEStatus;					//Optional
-};
-/****MeteringReceiptRequest****/
-struct MeteringReceiptRequest_ISO15118_2014
-{
-	unsigned char 										Id[32];						//Optional
-	unsigned char 										SessionID[8];
-	short 											SAScheduleTupleID;				//Optional
-	struct MeterInfoType_ISO15118_2014					MeterInfo;
-};
-struct MeteringReceiptRequest_ISO15118_2018
-{
-	unsigned char 										Id[32];						//Optional
-	unsigned char 										SessionID[8];
-	struct Scheduled_MRReqControlModeType				Schedule_MRReqControlMode;
-	struct MeterInfoType_ISO15118_2018					MeterInfo;
-};
-/****MeteringReceiptResponse****/
-struct MeteringReceiptResponse_ISO15118_2014
-{
-	enum ResponseCodeType_ISO15118_2014				ResponseCode;
-	struct AC_EVSEStatusType							AC_EVSEStatus;
-	struct DC_EVSEStatusType_ISO15118_2014				DC_EVSEStatus;
-};
-struct MeteringReceiptResponse_ISO15118_2018
-{
-	enum ResponseCodeType_ISO15118_2018				ResponseCode;
-	struct EVSEStatusType								EVSEStatus;					//Optional
-};
-/****ChargingStatusRequest (AC Only)****/
-struct ChargingStatusRequest_ISO15118_2014
-{
-	//No member in standard
-};
-struct ChargingStatusRequest_ISO15118_2018
-{
-	struct PnC_CLReqIdentificationModeType				PnC_CLReqIdentificationMode;
-	struct Dynamic_CSReqControlModeType				Dynamic_CSReqControlMode;
-	struct Scheduled_CSReqControlModeType				Scheduled_CSReqControlMode;
-	struct DisplayParametersType							DisplayParameters;
-};
-/****ChargingStatusResponse (AC Only)****/
-struct ChargingStatusResponse_ISO15118_2014
-{
-	enum ResponseCodeType_ISO15118_2014				ResponseCode;
-	unsigned char										EVSEID[40];			//DIN70121=>Max length:32,	ISO15118=>min length:7, max length:37
-	short 											SAScheduleTupleID;
-	struct PhysicalValueType_ISO15118_2014					EVSEMaxCurrent;		//Optional
-	struct MeterInfoType_ISO15118_2014					MeterInfo;			//Optional
-	BOOL											ReceiptRequired;		//Optional
-	struct AC_EVSEStatusType							AC_EVSEStatus;
-};
-struct ChargingStatusResponse_ISO15118_2018
-{
-	enum ResponseCodeType_ISO15118_2018				ResponseCode;
-	struct EVSEStatusType								EVSEStatus;					//Optional
-	unsigned char										EVSEID[40];					//DIN70121=>Max length:32,	ISO15118=>min length:7, max length:37
-	struct PhysicalValueType_ISO15118_2018					EVSETargetFrequency;			//Optional
-	struct PnC_CLResIdentificationModeType				PnC_CLResIdentificationMode;
-	struct Dynamic_CSResControlModeType					Dynamic_CSResControlMode;
-	struct Scheduled_CSReqControlModeType				Scheduled_CSReqControlMode;
-};
-/****CableCheckRequest (DC Only)****/
-struct CableCheckRequest_DIN70121
-{
-	struct DC_EVStatusType_DIN70121						DC_EVStatus;
-};
-struct CableCheckRequest_ISO15118_2014
-{
-	struct DC_EVStatusType_ISO15118_2014 					DC_EVStatus;
-};
-struct CableCheckRequest_ISO15118_2018
-{
-	//No member in standard
-};
-/****CableCheckResponse (DC Only)****/
-struct CableCheckResponse_DIN70121
-{
-	enum ResponseCodeType_DIN70121					ResponseCode;
-	struct DC_EVSEStatusType_DIN70121					DC_EVSEStatus;
-	enum EVSEProcessingType_DIN70121					EVSEProcessing;
-};
-struct CableCheckResponse_ISO15118_2014
-{
-	enum ResponseCodeType_ISO15118_2014				ResponseCode;
-	struct DC_EVSEStatusType_ISO15118_2014				DC_EVSEStatus;
-	enum EVSEProcessingType_ISO15118_2014				EVSEProcessing;
-};
-struct CableCheckResponse_ISO15118_2018
-{
-	enum ResponseCodeType_ISO15118_2018				ResponseCode;
-	struct EVSEStatusType								EVSEStatus;					//Optional
-	enum ProcessingType								EVSEProcessing;
-};
-/****PreChargeRequest (DC Only)****/
-struct PreChargeRequest_DIN70121
-{
-	struct DC_EVStatusType_DIN70121						DC_EVStatus;
-	struct PhysicalValueType_DIN70121						EVTargetVoltage;
-	struct PhysicalValueType_DIN70121						EVTargetCurrent;
-};
-struct PreChargeRequest_ISO15118_2014
-{
-	struct DC_EVStatusType_ISO15118_2014 					DC_EVStatus;
-	struct PhysicalValueType_ISO15118_2014					EVTargetVoltage;
-	struct PhysicalValueType_ISO15118_2014					EVTargetCurrent;
-};
-struct PreChargeRequest_ISO15118_2018
-{
-	struct PhysicalValueType_ISO15118_2018					EVTargetVoltage;
-	struct PhysicalValueType_ISO15118_2018					EVTargetCurrent;
-};
-/****PreChargeResponse (DC Only)****/
-struct PreChargeResponse_DIN70121
-{
-	enum ResponseCodeType_DIN70121					ResponseCode;
-	struct DC_EVSEStatusType_DIN70121					DC_EVSEStatus;
-	struct PhysicalValueType_DIN70121						EVSEPresentVoltage;
-};
-struct PreChargeResponse_ISO15118_2014
-{
-	enum ResponseCodeType_ISO15118_2014				ResponseCode;
-	struct DC_EVSEStatusType_ISO15118_2014				DC_EVSEStatus;
-	struct PhysicalValueType_ISO15118_2014					EVSEPresentVoltage;
-};
-struct PreChargeResponse_ISO15118_2018
-{
-	enum ResponseCodeType_ISO15118_2018				ResponseCode;
-	struct EVSEStatusType								EVSEStatus;					//Optional
-	struct PhysicalValueType_ISO15118_2018					EVSEPresentVoltage;
-};
-/****CurrentDemandRequest (DC Only)****/
-struct CurrentDemandRequest_DIN70121
-{
-	struct DC_EVStatusType_DIN70121						DC_EVStatus;
-	struct PhysicalValueType_DIN70121						EVTargetCurrent;
-	struct PhysicalValueType_DIN70121						EVMaximumVoltageLimit;		//Optional
-	struct PhysicalValueType_DIN70121						EVMaximumCurrentLimit;		//Optional
-	struct PhysicalValueType_DIN70121						EVMaximumPowerLimit;			//Optional
-	BOOL											BulkChargingComplete;			//Optional
-	BOOL											ChargingComplete;
-	struct PhysicalValueType_DIN70121						RemainingTimeToFullSoC;		//Optional
-	struct PhysicalValueType_DIN70121						RemainingTimeToBulkSoC;		//Optional
-	struct PhysicalValueType_DIN70121						EVTargetVoltage;
-};
-struct CurrentDemandRequest_ISO15118_2014
-{
-	struct DC_EVStatusType_ISO15118_2014 					DC_EVStatus;
-	struct PhysicalValueType_ISO15118_2014					EVTargetCurrent;
-	struct PhysicalValueType_ISO15118_2014					EVMaximumVoltageLimit;		//Optional
-	struct PhysicalValueType_ISO15118_2014					EVMaximumCurrentLimit;		//Optional
-	struct PhysicalValueType_ISO15118_2014					EVMaximumPowerLimit;			//Optional
-	BOOL											BulkChargingComplete;			//Optional
-	BOOL											ChargingComplete;
-	struct PhysicalValueType_ISO15118_2014					RemainingTimeToFullSoC;		//Optional
-	struct PhysicalValueType_ISO15118_2014					RemainingTimeToBulkSoC;		//Optional
-	struct PhysicalValueType_ISO15118_2014					EVTargetVoltage;
-};
-struct CurrentDemandRequest_ISO15118_2018
-{
-	struct DisplayParametersType							DisplayParameters;				//Optional
-	struct PnC_CLReqIdentificationModeType				PnC_CLReqIdentificationMode;
-	struct Dynamic_CSReqControlModeType				Dynamic_CDReqControlMode;
-	struct Scheduled_CSReqControlModeType				Scheduled_CDReqControlMode;
-};
-/****CurrentDemandResponse (DC Only)****/
-struct CurrentDemandResponse_DIN70121
-{
-	enum ResponseCodeType_DIN70121					ResponseCode;
-	struct DC_EVSEStatusType_DIN70121					DC_EVSEStatus;
-	struct PhysicalValueType_DIN70121						EVSEPresentVoltage;
-	struct PhysicalValueType_DIN70121						EVSEPresentCurrent;
-	BOOL											EVSECurrentLimitAchieved;
-	BOOL											EVSEVoltageLimitAchieved;
-	BOOL											EVSEPowerLimitAchieved;
-	struct PhysicalValueType_DIN70121						EVSEMaximumVoltageLimit;		//Optional
-	struct PhysicalValueType_DIN70121						EVSEMaximumCurrentLimit;		//Optional
-	struct PhysicalValueType_DIN70121						EVSEMaximumPowerLimit;		//Optional
-};
-struct CurrentDemandResponse_ISO15118_2014
-{
-	enum ResponseCodeType_ISO15118_2014				ResponseCode;
-	struct DC_EVSEStatusType_ISO15118_2014				DC_EVSEStatus;
-	struct PhysicalValueType_ISO15118_2014					EVSEPresentVoltage;
-	struct PhysicalValueType_ISO15118_2014					EVSEPresentCurrent;
-	BOOL											EVSECurrentLimitAchieved;
-	BOOL											EVSEVoltageLimitAchieved;
-	BOOL											EVSEPowerLimitAchieved;
-	struct PhysicalValueType_ISO15118_2014					EVSEMaximumVoltageLimit;		//Optional
-	struct PhysicalValueType_ISO15118_2014					EVSEMaximumCurrentLimit;		//Optional
-	struct PhysicalValueType_ISO15118_2014					EVSEMaximumPowerLimit;		//Optional
-	unsigned char										EVSEID[40];			//DIN70121=>Max length:32,	ISO15118=>min length:7, max length:37
-	short 											SAScheduleTupleID;
-	struct MeterInfoType_ISO15118_2014					MeterInfo;			//Optional
-	BOOL											ReceiptRequired;		//Optional
-};
-struct CurrentDemandResponse_ISO15118_2018
-{
-	enum ResponseCodeType_ISO15118_2018				ResponseCode;
-	struct EVSEStatusType								EVSEStatus;						//Optional
-	struct PhysicalValueType_ISO15118_2018					EVSEPresentVoltage;
-	struct PhysicalValueType_ISO15118_2018					EVSEPresentCurrent;
-	BOOL											EVSECurrentLimitAchieved;
-	BOOL											EVSEVoltageLimitAchieved;
-	BOOL											EVSEPowerLimitAchieved;
-	struct PhysicalValueType_ISO15118_2018					EVSEMaximumChargeVoltage;		//Optional
-	struct PhysicalValueType_ISO15118_2018					EVSEMaximumChargeCurrent;		//Optional
-	struct PhysicalValueType_ISO15118_2018					EVSEMaximumChargePower;			//Optional
-	unsigned char										EVSEID[40];						//DIN70121=>Max length:32,	ISO15118=>min length:7, max length:37
-	struct PnC_CLResIdentificationModeType				PnC_CLResIdentificationMode;
-	struct Scheduled_CDResControlModeType				Scheduled_CDResControlMode;
-};
-/****WeldingDetectionRequest (DC Only)*****/
-struct WeldingDetectionRequest_DIN70121
-{
-	struct DC_EVStatusType_DIN70121						DC_EVStatus;
-};
-struct WeldingDetectionRequest_ISO15118_2014
-{
-	struct DC_EVStatusType_ISO15118_2014 					DC_EVStatus;
-};
-struct WeldingDetectionRequest_ISO15118_2018
-{
-	//No member in Standard
-};
-/****WeldingDetectionResponse (DC Only)****/
-struct WeldingDetectionResponse_DIN70121
-{
-	enum ResponseCodeType_DIN70121					ResponseCode;
-	struct DC_EVSEStatusType_DIN70121					DC_EVSEStatus;
-	struct PhysicalValueType_DIN70121						EVSEPresentVoltage;
-};
-struct WeldingDetectionResponse_ISO15118_2014
-{
-	enum ResponseCodeType_ISO15118_2014				ResponseCode;
-	struct DC_EVSEStatusType_ISO15118_2014				DC_EVSEStatus;
-	struct PhysicalValueType_ISO15118_2014					EVSEPresentVoltage;
-};
-struct WeldingDetectionResponse_ISO15118_2018
-{
-	enum ResponseCodeType_ISO15118_2018				ResponseCode;
-	struct EVSEStatusType								EVSEStatus;						//Optional
-	struct PhysicalValueType_ISO15118_2018					EVSEPresentVoltage;
-};
-/****FinePositioningSetupRequest (WPT Only)****/
-struct FinePositioningSetupRequest_ISO15118_2018
-{
-	struct LFA_EVFinePositioningSetupParametersType			LFA_EVFinePositioningSetupParameters;	//Optional
-};
-/****FinePositioningSetupResponse (WPT Only)****/
-struct FinePositioningSetupResponse_ISO15118_2018
-{
-	//NOT complete yet,  to be continue.....
-};
-
-
-struct V2GMessageType_DIN70121
-{
-	unsigned char 	SelfTest_Comp;
-	unsigned char	version[16];
-	unsigned char											PresentMsgFlowStatus;
-														/* 0: Idle(wait B2 state), 1: CM_SLAC_PARM.REQ, 2: CM_SLAC_PARM.CNF, 3: CM_START_ATTEN_CHAR.IND
-														    4: CM_MNBC_SOUND.IND, 5: CM_ATTEN_CHAR.IND, 6: CM_ATTEN_CHAR.RSP, 7: CM_VALIDATE.REQ
-														    8: CM_VALIDATE.CNF, 9: CM_SLAC_MATCH.REQ, 10: CM_SLAC_MATCH.CNF, 11: CM_AMP_MAP.REQ
-														    12: CM_AMP_MAP.CNF, 13: SLACC/SDP/TCP connection,
-														    16: SupportedAppProtocolRequest, 17: SupportedAppProtocolResponse, 18: SessionSetupRequest
-														    19: SessionSetupResponse, 20: ServiceDiscoveryRequest, 21: ServiceDiscoveryResponse
-														    22: ServiceDetailRequest, 23: ServiceDetailResponse
-														    24: ServiceAndPaymentSelectionRequest/ServiceSelectionRequest, 25: ServiceAndPaymentSelectionResponse/ServiceSelectionResponse
-														    26: PaymentDetailsRequest/IdentificationDetailsRequest;, 27: PaymentDetailsResponse/IdentificationDetailsResponse,
-														     28: AuthorizationRequest, 29: AuthorizationResponse,
-														    30: CertificateUpdateRequest, 31: CertificateUpdateResponse, 32:CertificateInstallationRequest, 33: CertificateInstallationResponse
-														    34: ChargeParameterDiscoveryRequest, 35: ChargeParameterDiscoveryResponse
-														    36: CableCheckRequest, 37: CableCheckResponse, 38: PreChargeRequest, 39: PreChargeResponse
-														    40: PowerDeliveryRequest start, 41: PowerDeliveryResponse start, 42: ChargingStatusRequest, 43: ChargingStatusResponse
-														    44: CurrentDemandRequest, 45: CurrentDemandResponse, 46: MeteringReceiptRequest, 47: MeteringReceiptResponse
-														    48: PowerDeliveryRequest end, 49: PowerDeliveryRequest end, 50: WeldingDetectionRequest, 51: WeldingDetectionResponse,
-														    52: SessionStopRequest, 53: SessionStopResponse
-														   253: Performance Timeout, 254: Sequence Timeout, 255: Fault
-														*/
-	struct SupportedAppProtocolRequest_DIN70121 			SupportedAppProtocolRequest;
-	struct SupportedAppProtocolResponse_DIN70121 			SupportedAppProtocolResponse;
-	struct SessionSetupRequest_DIN70121  					SessionSetupRequest;
-	struct SessionSetupResponse_DIN70121   				SessionSetupResponse;
-	struct ServiceDiscoveryRequest_DIN70121    				ServiceDiscoveryRequest;
-	struct ServiceDiscoveryResponse_DIN70121    				ServiceDiscoveryResponse;
-	struct ServiceAndPaymentSelectionRequest_DIN70121		ServiceAndPaymentSelectionRequest;
-	struct ServiceAndPaymentSelectionResponse_DIN70121		ServiceAndPaymentSelectionResponse;
-	struct ContractAuthenticationRequest_DIN70121			ContractAuthenticationRequest;
-	struct ContractAuthenticationResponse_DIN70121	 		ContractAuthenticationResponse;
-	struct ChargeParameterDiscoveryRequest_DIN70121		ChargeParameterDiscoveryRequest;
-	struct ChargeParameterDiscoveryResponse_DIN70121		ChargeParameterDiscoveryResponse;
-	struct CableCheckRequest_DIN70121					CableCheckRequest;
-	struct CableCheckResponse_DIN70121					CableCheckResponse;
-	struct PreChargeRequest_DIN70121					PreChargeRequest;
-	struct PreChargeResponse_DIN70121 					PreChargeResponse;
-	struct PowerDeliveryRequest_DIN70121					PowerDeliveryRequest;
-	struct PowerDeliveryResponse_DIN70121	   				PowerDeliveryResponse;
-	struct CurrentDemandRequest_DIN70121 				CurrentDemandRequest;
-	struct CurrentDemandResponse_DIN70121				CurrentDemandResponse;
-	struct WeldingDetectionRequest_DIN70121 				WeldingDetectionRequest;
-	struct WeldingDetectionResponse_DIN70121  			WeldingDetectionResponse;
-	struct SessionStopRequest_DIN70121					SessionStopRequest;
-	struct SessionStopResponse_DIN70121	    				SessionStopResponse;
-};
-
-struct V2GMessageType_ISO15118_2014
-{
-	unsigned char											PresentMsgFlowStatus;
-														/* 0: Idle(wait B2 state), 1: CM_SLAC_PARM.REQ, 2: CM_SLAC_PARM.CNF, 3: CM_START_ATTEN_CHAR.IND
-														    4: CM_MNBC_SOUND.IND, 5: CM_ATTEN_CHAR.IND, 6: CM_ATTEN_CHAR.RSP, 7: CM_VALIDATE.REQ
-														    8: CM_VALIDATE.CNF, 9: CM_SLAC_MATCH.REQ, 10: CM_SLAC_MATCH.CNF, 11: CM_AMP_MAP.REQ
-														    12: CM_AMP_MAP.CNF, 13: SLACC/SDP/TCP connection,
-														    16: SupportedAppProtocolRequest, 17: SupportedAppProtocolResponse, 18: SessionSetupRequest
-														    19: SessionSetupResponse, 20: ServiceDiscoveryRequest, 21: ServiceDiscoveryResponse
-														    22: ServiceDetailRequest, 23: ServiceDetailResponse
-														    24: ServiceAndPaymentSelectionRequest/ServiceSelectionRequest, 25: ServiceAndPaymentSelectionResponse/ServiceSelectionResponse
-														    26: PaymentDetailsRequest/IdentificationDetailsRequest;, 27: PaymentDetailsResponse/IdentificationDetailsResponse,
-														     28: AuthorizationRequest, 29: AuthorizationResponse,
-														    30: CertificateUpdateRequest, 31: CertificateUpdateResponse, 32:CertificateInstallationRequest, 33: CertificateInstallationResponse
-														    34: ChargeParameterDiscoveryRequest, 35: ChargeParameterDiscoveryResponse
-														    36: CableCheckRequest, 37: CableCheckResponse, 38: PreChargeRequest, 39: PreChargeResponse
-														    40: PowerDeliveryRequest start, 41: PowerDeliveryResponse start, 42: ChargingStatusRequest, 43: ChargingStatusResponse
-														    44: CurrentDemandRequest, 45: CurrentDemandResponse, 46: MeteringReceiptRequest, 47: MeteringReceiptResponse
-														    48: PowerDeliveryRequest end, 49: PowerDeliveryRequest end, 50: WeldingDetectionRequest, 51: WeldingDetectionResponse,
-														    52: SessionStopRequest, 53: SessionStopResponse
-														   253: Performance Timeout, 254: Sequence Timeout, 255: Fault
-														*/
-	struct SupportedAppProtocolRequest_ISO15118_2014 			SupportedAppProtocolRequest;
-	struct SupportedAppProtocolResponse_ISO15118_2014 			SupportedAppProtocolResponse;
-	struct SessionSetupRequest_ISO15118_2014  					SessionSetupRequest;
-	struct SessionSetupResponse_ISO15118_2014   				SessionSetupResponse;
-	struct ServiceDiscoveryRequest_ISO15118_2014    				ServiceDiscoveryRequest;
-	struct ServiceDiscoveryResponse_ISO15118_2014    				ServiceDiscoveryResponse;
-	struct ServiceDetailRequest_ISO15118_2014 					ServiceDetailRequest;
-	struct ServiceDetailResponse_ISO15118_2014					ServiceDetailResponse;
-	struct ServiceAndPaymentSelectionRequest_ISO15118_2014 		ServiceAndPaymentSelectionRequest;
-	struct ServiceAndPaymentSelectionResponse_ISO15118_2014  	ServiceAndPaymentSelectionResponse;
-	struct PaymentDetailsRequest_ISO15118_2014 				PaymentDetailsRequest;
-	struct PaymentDetailsResponse_ISO15118_2014 				PaymentDetailsResponse;
-	struct AuthorizationRequest_ISO15118_2014					AuthorizationRequest;
-	struct AuthorizationResponse_ISO15118_2014					AuthorizationResponse;
-	struct CertificateUpdateRequest_ISO15118_2014				CertificateUpdateRequest;
-	struct CertificateUpdateResponse_ISO15118_2014				CertificateUpdateResponse;
-	struct CertificateInstallationRequest_ISO15118_2014			CertificateInstallationRequest;
-	struct CertificateInstallationResponse_ISO15118_2014			CertificateInstallationResponse;
-	struct ChargeParameterDiscoveryRequest_ISO15118_2014 		ChargeParameterDiscoveryRequest;
-	struct ChargeParameterDiscoveryResponse_ISO15118_2014  		ChargeParameterDiscoveryResponse;
-	struct CableCheckRequest_ISO15118_2014 					CableCheckRequest;
-	struct CableCheckResponse_ISO15118_2014  					CableCheckResponse;
-	struct PreChargeRequest_ISO15118_2014 					PreChargeRequest;
-	struct PreChargeResponse_ISO15118_2014					PreChargeResponse;
-	struct PowerDeliveryRequest_ISO15118_2014					PowerDeliveryRequest;
-	struct PowerDeliveryResponse_ISO15118_2014					PowerDeliveryResponse;
-	struct ChargingStatusRequest_ISO15118_2014	  				ChargingStatusRequest;
-	struct ChargingStatusResponse_ISO15118_2014				ChargingStatusResponse;
-	struct CurrentDemandRequest_ISO15118_2014	 			CurrentDemandRequest;
-	struct CurrentDemandResponse_ISO15118_2014				CurrentDemandResponse;
-	struct MeteringReceiptRequest_ISO15118_2014				MeteringReceiptRequest;
-	struct MeteringReceiptResponse_ISO15118_2014				MeteringReceiptResponse;
-	struct WeldingDetectionRequest_ISO15118_2014 				WeldingDetectionRequest;
-	struct WeldingDetectionResponse_ISO15118_2014  			WeldingDetectionResponse;
-	struct SessionStopRequest_ISO15118_2014 					SessionStopRequest;
-	struct SessionStopResponse_ISO15118_2014					SessionStopResponse;
-};
-struct V2GMessageType_ISO15118_2018
-{
-	unsigned char										PresentMsgFlowStatus;
-													/* 0: Idle(wait B2 state), 1: CM_SLAC_PARM.REQ, 2: CM_SLAC_PARM.CNF, 3: CM_START_ATTEN_CHAR.IND
-													    4: CM_MNBC_SOUND.IND, 5: CM_ATTEN_CHAR.IND, 6: CM_ATTEN_CHAR.RSP, 7: CM_VALIDATE.REQ
-													    8: CM_VALIDATE.CNF, 9: CM_SLAC_MATCH.REQ, 10: CM_SLAC_MATCH.CNF, 11: CM_AMP_MAP.REQ
-													    12: CM_AMP_MAP.CNF, 13: SLACC/SDP/TCP connection,
-													    16: SupportedAppProtocolRequest, 17: SupportedAppProtocolResponse, 18: SessionSetupRequest
-													    19: SessionSetupResponse, 20: ServiceDiscoveryRequest, 21: ServiceDiscoveryResponse
-													    22: ServiceDetailRequest, 23: ServiceDetailResponse
-													    24: ServiceAndPaymentSelectionRequest/ServiceSelectionRequest, 25: ServiceAndPaymentSelectionResponse/ServiceSelectionResponse
-													    26: PaymentDetailsRequest/IdentificationDetailsRequest;, 27: PaymentDetailsResponse/IdentificationDetailsResponse,
-													     28: AuthorizationRequest, 29: AuthorizationResponse,
-													    30: CertificateUpdateRequest, 31: CertificateUpdateResponse, 32:CertificateInstallationRequest, 33: CertificateInstallationResponse
-													    34: ChargeParameterDiscoveryRequest, 35: ChargeParameterDiscoveryResponse
-													    36: CableCheckRequest, 37: CableCheckResponse, 38: PreChargeRequest, 39: PreChargeResponse
-													    40: PowerDeliveryRequest start, 41: PowerDeliveryResponse start, 42: ChargingStatusRequest, 43: ChargingStatusResponse
-													    44: CurrentDemandRequest, 45: CurrentDemandResponse, 46: MeteringReceiptRequest, 47: MeteringReceiptResponse
-													    48: PowerDeliveryRequest end, 49: PowerDeliveryRequest end, 50: WeldingDetectionRequest, 51: WeldingDetectionResponse,
-													    52: SessionStopRequest, 53: SessionStopResponse
-													   253: Performance Timeout, 254: Sequence Timeout, 255: Fault
-													*/
-	struct SupportedAppProtocolRequest_ISO15118_2018			SupportedAppProtocolRequest;
-	struct SupportedAppProtocolResponse_ISO15118_2018 			SupportedAppProtocolResponse;
-	struct SessionSetupRequest_ISO15118_2018					SessionSetupRequest;
-	struct SessionSetupResponse_ISO15118_2018  					SessionSetupResponse;
-	struct ServiceDiscoveryRequest_ISO15118_2018    				ServiceDiscoveryRequest;
-	struct ServiceDiscoveryResponse_ISO15118_2018    				ServiceDiscoveryResponse;
-	struct ServiceDetailRequest_ISO15118_2018 					ServiceDetailRequest;
-	struct ServiceDetailResponse_ISO15118_2018					ServiceDetailResponse;
-	struct ServiceSelectionRequest_ISO15118_2018				ServiceSelectionRequest;
-	struct ServiceSelectionResponse_ISO15118_2018				ServiceSelectionResponse;
-	struct IdentificationDetailsRequest_ISO15118_2018  			IdentificationDetailsRequest;
-	struct IdentificationDetailsResponse_ISO15118_2018  			IdentificationDetailsResponse;
-	struct AuthorizationRequest_ISO15118_2018  					AuthorizationRequest;
-	struct AuthorizationResponse_ISO15118_2018					AuthorizationResponse;
-	struct CertificateInstallationRequest_ISO15118_2018			CertificateInstallationRequest;
-	struct CertificateInstallationResponse_ISO15118_2018			CertificateInstallationResponse;
-	struct ChargeParameterDiscoveryRequest_ISO15118_2018 		ChargeParameterDiscoveryRequest;
-	struct ChargeParameterDiscoveryResponse_ISO15118_2018  		ChargeParameterDiscoveryResponse;
-	struct CableCheckRequest_ISO15118_2018 					CableCheckRequest;
-	struct CableCheckResponse_ISO15118_2018 					CableCheckResponse;
-	struct PreChargeRequest_ISO15118_2018 					PreChargeRequest;
-	struct PreChargeResponse_ISO15118_2018					PreChargeResponse;
-	struct PowerDeliveryRequest_ISO15118_2018					PowerDeliveryRequest;
-	struct PowerDeliveryResponse_ISO15118_2018					PowerDeliveryResponse;
-	struct ChargingStatusRequest_ISO15118_2018	  				ChargingStatusRequest;
-	struct ChargingStatusResponse_ISO15118_2018				ChargingStatusResponse;
-	struct CurrentDemandRequest_ISO15118_2018	 			CurrentDemandRequest;
-	struct CurrentDemandResponse_ISO15118_2018				CurrentDemandResponse;
-	struct MeteringReceiptRequest_ISO15118_2018				MeteringReceiptRequest;
-	struct MeteringReceiptResponse_ISO15118_2018				MeteringReceiptResponse;
-	struct WeldingDetectionRequest_ISO15118_2018 				WeldingDetectionRequest;
-	struct WeldingDetectionResponse_ISO15118_2018  			WeldingDetectionResponse;
-	struct SessionStopRequest_ISO15118_2018 					SessionStopRequest;
-	struct SessionStopResponse_ISO15118_2018					SessionStopResponse;
-};
-
-struct CcsData
-{
-	unsigned char 							CommProtocol;	// 1: V2GMessage_DIN70121, 2:V2GMessage_ISO15118_2014, 3:V2GMessage_ISO15118_2018
-	struct V2GMessageType_DIN70121			V2GMessage_DIN70121[CCS_QUANTITY];
-	struct V2GMessageType_ISO15118_2014  		V2GMessage_ISO15118_2014[CCS_QUANTITY];
-	struct V2GMessageType_ISO15118_2018  		V2GMessage_ISO15118_2018[CCS_QUANTITY];
-};
-/**************************************************************************************/
-/***************STM32F407 Communication Share memory**************************/
-/**************************************************************************************/
-struct PrimaryMcuData
-{
-    unsigned char   SelfTest_Comp;
-    unsigned char   version[16];                                //STM32F407 firmware version
-    unsigned int    InputVoltage;                               //value comes from external meter
-    unsigned int    InputCurrent;                               //value comes from external meter
-    union
-    {
-        unsigned char OutputDrvValue[1];
-        struct
-        {
-            //OutputDrvValue[0]
-            unsigned char OnButtonLedDrv:1;                     //bit 0,    H: ON,      L:OFF
-            unsigned char OffButtonLedDrv:1;                    //bit 1,    H: ON,      L:OFF
-            unsigned char SystemLed1Drv:1;                      //bit 2,    H: ON,      L:OFF
-            unsigned char SystemLed2Drv:1;                      //bit 3,    H: ON,      L:OFF
-            unsigned char SystemLed3Drv:1;                      //bit 4,    H: ON,      L:OFF
-            unsigned char SystemLed4Drv:1;                      //bit 5,    H: ON,      L:OFF
-            unsigned char AcContactorDrv:1;                     //bit 6,    H: ON,      L:OFF
-            unsigned char:1;                                    //bit 7 reserved
-        }bits;
-    }OutputDrv;
-    union
-    {
-        unsigned char InputDetValue[2];
-        struct
-        {
-            //InputDetValue[0]
-            unsigned char AcContactorDetec:1;                   //bit 0,    H: ON,      L:OFF
-            unsigned char AcMainBreakerDetec:1;                 //bit 1,    H: ON,      L:OFF
-            unsigned char SpdDetec:1;                           //bit 2,    H: ON,      L:OFF
-            unsigned char DoorOpen:1;                           //bit 3,    H: Open,    L:Close
-            unsigned char Gfd1:1;                               //bit 4,    H: Trigger, L:Normal
-            unsigned char Gfd2:1;                               //bit 5,    H: Trigger, L:Normal
-            unsigned char Button1:1;                            //bit 6 ,   H: Push,    L:Release
-            unsigned char Button2:1;                            //bit 7,    H: Push,    L:Release
-            //InputDetValue[1]
-            unsigned char EmergencyButton:1;                    //bit 0,    H: Push,    L:Release
-            unsigned char Key0:1;                               //bit 1,    H: ON,      L:OFF
-            unsigned char Key1:1;                               //bit 2,    H: ON,      L:OFF
-            unsigned char Key2:1;                               //bit 3,    H: ON,      L:OFF
-            unsigned char Key3:1;                               //bit 4,    H: ON,      L:OFF
-            unsigned char Ac_Drop;                              //bit 4,    H: Trigger, L:Normal
-			unsigned char :2;                                   //bit 5~7,  Reserved
-        }bits;
-    }InputDet;
-};
-/**************************************************************************************/
-/*************Fan power module Communication Share memory******************/
-/**************************************************************************************/
-struct FanModuleData
-{
-	unsigned char  SelfTest_Comp;
-	unsigned char	version[16];			//fan power module firmware version
-	unsigned short	PresentFan1Speed;		//RPM
-	unsigned short	PresentFan2Speed;		//RPM
-	unsigned short	PresentFan3Speed;		//RPM
-	unsigned short	PresentFan4Speed;		//RPM
-	unsigned short	SetFan1Speed;			//RPM
-	unsigned short	SetFan2Speed;			//RPM
-	unsigned short	SetFan3Speed;			//RPM
-	unsigned short	SetFan4Speed;			//RPM
-	unsigned short	TestFanSpeed;			//RPM
-	unsigned char	DiffOfAirPressure;		//pa
-	unsigned char	UpdateFW;			//1:do update
-};
-
-/**************************************************************************************/
-/***********Relay control module Communication Share memory******************/
-/**************************************************************************************/
-struct RelayModuleData
-{
-	unsigned char 	SelfTest_Comp;
-	unsigned char	version[16];				//relay module firmware version
-	unsigned short	InputL1Volt;				//XXXXX.x volt
-	unsigned short	InputL2Volt;				//XXXXX.x volt
-	unsigned short	InputL3Volt;				//XXXXX.x volt
-	unsigned short	Gun1FuseOutputVolt;		//XXXXX.x volt
-	unsigned short	Gun2FuseOutputVolt;		//XXXXX.x volt
-	unsigned short	Gun1RelayOutputVolt;		//XXXXX.x volt
-	unsigned short	Gun2RelayOutputVolt;		//XXXXX.x volt
-	unsigned short	Gun1OutputCurrent;		//XXXXX.x amp
-	unsigned short	Gun2OutputCurrent;		//XXXXX.x amp
-	unsigned char	UpdateFW;				//1:do update
-};
-
-/**************************************************************************************/
-/***********Led control module Communication Share memory******************/
-/**************************************************************************************/
-struct LedModuleData
-{
-	unsigned char 	SelfTest_Comp;
-	unsigned char	version[16];				//led module firmware version
-	unsigned short	Connect_1_Status;			// Idle : 0, Charging : 1, Alarm : 2
-	unsigned short	Connect_2_Status;			// Idle : 0, Charging : 1, Alarm : 2
-	unsigned short	EnableFunc;					// reserved
-};
-
-/**************************************************************************************/
-/************************OCPP Share memory***************************************/
-/**************************************************************************************/
-struct StructIdTagInfo
-{
-	unsigned char 	ExpiryDate[36];
-	unsigned char 	ParentIdTag[21];
-	unsigned char 	Status[16];		//Accepted, Blocked, Expired, Invalid, ConcurrentTx
-};
-struct StructLocalAuthorizationList
-{
-	unsigned char 			IdTag[21];
-	struct StructIdTagInfo	IdTagInfo;
-};
-struct StructSampledValue
-{
-	unsigned char 			Value[128];
-	unsigned char 			Context[30];//Interruption.Begin, Interruption.End, Sample.Clock, Sample.Periodic, Transaction.Begin, Transaction.End, Trigger, Other
-	unsigned char 			Format[16];//Raw,SignedData
-	unsigned char 			Measurand[40];/*	"Energy.Active.Export.Register",
-										"Energy.Active.Import.Register",
-										"Energy.Reactive.Export.Register",
-										"Energy.Reactive.Import.Register",
-										"Energy.Active.Export.Interval",
-										"Energy.Active.Import.Interval",
-										"Energy.Reactive.Export.Interval",
-										"Energy.Reactive.Import.Interval",
-										"Power.Active.Export",
-										"Power.Active.Import",
-										"Power.Offered",
-										"Power.Reactive.Export",
-										"Power.Reactive.Import",
-										"Power.Factor",
-										"Current.Import",
-										"Current.Export",
-										"Current.Offered",
-										"Voltage",
-										"Frequency",
-										"Temperature",
-										"SoC",
-										"RPM"
-										*/
-
-	unsigned char 			Phase[10];	/*		"L1",
-										"L2",
-										"L3",
-										"N",
-										"L1-N",
-										"L2-N",
-										"L3-N",
-										"L1-L2",
-										"L2-L3",
-										"L3-L1"
-								*/
-
-	unsigned char 			Location[10];		//Cable,EV,Inlet,Outlet,Body
-	unsigned char 			Unit[20];	/*		"Wh",
-										"kWh",
-										"varh",
-										"kvarh",
-										"W",
-										"kW",
-										"VA",
-										"kVA",
-										"var",
-										"kvar",
-										"A",
-										"V",
-										"K",
-										"Celcius",
-										"Fahrenheit",
-										"Percent"
-								*/
-};
-struct StructMeterValue
-{
-	unsigned char 				TimeStamp[36];
-	struct StructSampledValue	SampledValue[20];
-};
-struct StructConfigurationKeyItems
-{
-	unsigned char 	Item[50];
-};
-struct StructConfigurationKey
-{
-	unsigned char 	Key[50];
-	unsigned char 	ReadOnly[8];	//boolean
-	unsigned char 	Value[500];
-};
-struct StructChargingSchedulePeriod
-{
-	int		StartPeriod;
-	float 	Limit;//0.1;
-	int		NumberPhases;
-};
-struct StructChargingSchedule
-{
-	int											Duration;
-	unsigned char 								StartSchedule[36];
-	unsigned char 								ChargingRateUnit[4];		//A, W
-	struct StructChargingSchedulePeriod			ChargingSchedulePeriod[10];
-	float 										MinChargingRate;			//0.1;
-};
-struct StructChargingProfile
-{
-	int								ChargingProfileId;
-	int								TransactionId;
-	int								StackLevel;
-	unsigned char 					ChargingProfilePurpose[24];	//ChargePointMaxProfile, TxDefaultProfile, TxProfile
-	unsigned char 					ChargingProfileKind[12];		//Absolute, Recurring, Relative
-	unsigned char 					RecurrencyKind[8];			//Daily, Weekly
-	unsigned char 					ValidFrom[36];
-	unsigned char 					ValidTo[36];
-	struct StructChargingSchedule	ChargingSchedule;
-};
-
-struct StructBootNotification
-{
-	unsigned char CpVendor[20];				//chargePointVendor				//mandatory
-	unsigned char CpModel[20];				//chargePointModel				//mandatory
-	unsigned char CpSN[25];					//chargePointSerialNumber
-	unsigned char CbSN[25];					//chargeBoxSerialNumber
-	unsigned char CpFwVersion[50];			//firmwareVersion
-	unsigned char CpIccid[22];				//iccid
-	unsigned char CpImsi[20];				//imsi
-	unsigned char CpMeterType[25];			//meterType
-	unsigned char CpMeterSerialNumber[25];	//meterSerialNumber
-	unsigned char ResponseStatus[16];			//Accepted, Pending, Rejected
-	unsigned char ResponseCurrentTime[36];	//currentTime					//mandatory
-	int 			ResponseHeartbeatInterval;	//interval						//mandatory
-
-};
-struct StructHeartbeat
-{
-	unsigned char 				ResponseCurrentTime[36];
-};
-struct StructAuthorize
-{
-	unsigned char 				IdTag[21];
-	struct StructIdTagInfo		ResponseIdTagInfo;
-};
-struct StructStartTransaction
-{
-	int 						ConnectorId;
-	unsigned char 				IdTag[21];
-	int 						MeterStart;
-	int 						ReservationId;
-	unsigned char 				Timestamp[36];
-	struct StructIdTagInfo		ResponseIdTagInfo;
-	int 						ResponseTransactionId;
-};
-struct StructStopTransaction
-{
-	unsigned char 				IdTag[21];
-	int 						MeterStop;
-	unsigned char 				Timestamp[36];
-	int 						TransactionId;
-	unsigned char 				StopReason[20];				/*	"EmergencyStop",
-															"EVDisconnected",
-															"HardReset",
-															"Local",
-															"Other",
-															"PowerLoss",
-															"Reboot",
-															"Remote",
-															"SoftReset",
-															"UnlockCommand",
-															"DeAuthorized"
-														*/
-	struct StructMeterValue		TransactionData[1];
-	struct StructIdTagInfo		ResponseIdTagInfo;
-};
-
-struct StructStatusNotification
-{
-	int 			ConnectorId;
-	unsigned char 	ErrorCode[25];				/*	"ConnectorLockFailure",
-								                "EVCommunicationError",
-								                "GroundFailure",
-								                "HighTemperature",
-								                "InternalError",
-								                "LocalListConflict",
-								                "NoError",
-								                "OtherError",
-								                "OverCurrentFailure",
-								                "PowerMeterFailure",
-								                "PowerSwitchFailure",
-								                "ReaderFailure",
-								                "ResetFailure",
-								                "UnderVoltage",
-								                "OverVoltage",
-								                "WeakSignal"
-								            */
-
-	unsigned char 	Info[50];
-	unsigned char 	Status[20];					/*	"Available",
-								                "Preparing",
-								                "Charging",
-								                "SuspendedEVSE",
-								                "SuspendedEV",
-								                "Finishing",
-								                "Reserved",
-								                "Unavailable",
-								                "Faulted"
-								            */
-
-	unsigned char 	Timestamp[36];
-	unsigned char 	VendorId[256];
-	unsigned char 	VendorErrorCode[50];
-};
-
-
-struct StructCancelReservation
-{
-	int 				ReservationId;
-	unsigned char 		ResponseStatus[16];		//Accepted, Rejected
-	unsigned char 		guid[37];
-};
-struct StructChangeAvailability
-{
-	int 				ConnectorId;
-	unsigned char 		Type[16];					//Inoperative, Operative
-	unsigned char 		ResponseStatus[16];		//Accepted, Rejected, Scheduled
-	unsigned char 		guid[37];
-};
-struct StructChangeConfiguration
-{
-	unsigned char Key[50];
-	unsigned char Value[500];
-	unsigned char ResponseStatus[16];		//Accepted, Rejected, RebootRequired, NotSupported
-};
-struct StructClearCache
-{
-	unsigned char ResponseStatus[16];		//Accepted, Rejected
-};
-struct StructClearChargingProfile
-{
-	int			 			Id;
-	int						ConnectorId;
-	unsigned char 			ChargingProfilePurpose[24];	//ChargePointMaxProfile, TxDefaultProfile, TxProfile
-	int			 			StackLevel;
-	unsigned char 			ResponseStatus[16];			//Accepted, Unknown
-};
-struct StructDataTransfer
-{
-	unsigned char VendorId[256];
-	unsigned char MessageId[52];
-	unsigned char Data[10240];
-	unsigned char ResponseStatus[18];	//Accepted, Rejected,UnknownMessageId,UnknownVendorId
-	unsigned char ResponseData[10240];
-};
-struct StructDiagnosticsStatusNotification
-{
-	unsigned char Status[16];		//Idle,Uploaded,UploadFailed,Uploading
-};
-struct StructFirmwareStatusNotification
-{
-	unsigned char Status[20];			//Downloaded,DownloadFailed,Downloading,Idle,InstallationFailed,Installing,Installed
-};
-struct StructGetCompositeSchedule
-{
-	int 							ConnectorId;
-	int 							Duration;
-	unsigned char					ChargingRateUnit[4];		//A,W
-	unsigned char 					ResponseStatus[12];			//Accepted,Rejected
-	int 							ResponseConnectorId;
-	unsigned char					ResponseScheduleStart[36];
-	struct StructChargingSchedule	ResponseChargingSchedule;
-};
-struct StructGetConfiguration
-{
-	struct StructConfigurationKeyItems 			*Key;
-	struct StructConfigurationKey			 	*ResponseConfigurationKey;
-	struct StructConfigurationKeyItems 			*ResponseUnknownKey;
-
-};
-struct StructGetDiagnostics
-{
-	unsigned char 			Location[256];
-	int 					Retries;
-	int						RetryInterval;
-	unsigned char 			StartTime[36];
-	unsigned char 			StopTime[36];
-	unsigned char 			ResponseFileName[256];
-};
-struct StructGetLocalListVersion
-{
-	int ResponseListVersion;
-};
-struct StructMeterValues
-{
-	int					 			ConnectorId;
-	int 							TransactionId;
-	struct StructMeterValue			MeterValue[1];
-};
-struct StructRemoteStartTransaction
-{
-	int								ConnectorId;
-	unsigned char 					IdTag[21];
-	struct StructChargingProfile	ChargingProfile;
-	unsigned char 					ResponseStatus[10];	//Accepted,	Rejected
-	unsigned char 					guid[37];
-};
-struct StructRemoteStopTransaction
-{
-	int 				TransactionId;
-	unsigned char 		ResponseStatus[10];	//Accepted,	Rejected
-};
-struct StructReserveNow
-{
-	int			 		ConnectorId;
-	unsigned char 		ExpiryDate[36];
-	unsigned char 		IdTag[21];
-	unsigned char 		ParentIdTag[21];
-	int					ReservationId;
-	unsigned char 		ResponseStatus[12];		//Accepted, Faulted, Occupied, Rejected, Unavailable
-	unsigned char 		guid[37];   			//OCPP Server request message uuid
-};
-struct StructReset
-{
-	unsigned char		Type[8];			//Hard,	Soft
-	unsigned char 		ResponseStatus[10];	//Accepted,	Rejected
-	unsigned char 		guid[37];   		//OCPP Server request message uuid
-};
-struct StructSendLocalList
-{
-	int										ListVersion;
-	unsigned char 							UpdateType[16];	//Differential,	Full
-	struct StructLocalAuthorizationList		*LocalAuthorizationList;
-	unsigned char 							ResponseStatus[16];	//Accepted,	Failed, NotSupported, VersionMismatch
-};
-struct StructSetChargingProfile
-{
-	int 								ConnectorId;
-	struct StructChargingProfile		ChargingProfile;
-	unsigned char				 		ResponseStatus[16];	//Accepted,	Rejected, NotSupported
-};
-struct StructTriggerMessage
-{
-	unsigned char 		RequestedMessage[32];	/*
-											"BootNotification",
-											"DiagnosticsStatusNotification",
-											"FirmwareStatusNotification",
-											"Heartbeat",
-											"MeterValues",
-											"StatusNotification"
-										*/
-	int					ConnectorId;
-	unsigned char 		ResponseStatus[16];	//Accepted,	Rejected, NotImplemented
-};
-struct StructUnlockConnector
-{
-	int					ConnectorId;
-	unsigned char 		ResponseStatus[16];	//Unlocked,	UnlockFailed, NotSupported
-	unsigned char 		guid[37];   		//OCPP Server request message uuid
-};
-struct StructUpdateFirmware
-{
-	unsigned char 		Location[256];
-	int					Retries;
-	unsigned char 		RetrieveDate[36];
-	int 				RetryInterval;
-};
-
-struct OCPP16ConfigurationItem
-{
-	unsigned char 		ItemName[64];
-	unsigned char 		ItemAccessibility;//0:RO, 1:RW
-	unsigned char 		ItemData[501];//value should be limited in 500 bytes
-};
-
-struct OCPP16ConfigurationTable
-{
-	//please refer to OCPP 1.6 chapter 9
-	struct OCPP16ConfigurationItem 			CoreProfile[_CoreProfile_CNT];
-	struct OCPP16ConfigurationItem 			LocalAuthListManagementProfile[3];
-	struct OCPP16ConfigurationItem 			ReservationProfile[1];
-	struct OCPP16ConfigurationItem 			SmartChargingProfile[5];
-};
-
-
-struct StrcutSetUserPrice
-{
-    unsigned char   idToken[21];
-    unsigned char   price[1024];
-};
-
-struct ChargingPrice
-{
-    float kWhPrice;                                 // Price per kWh
-    float hourPrice;                                // Price per hour of charging
-    float flatFee;                                  // Flat fee for (part of) charging session
-};
-
-struct IdlePrice
-{
-    unsigned int graceMinutes;                      // Grace period in minutes before idle time is charged
-    float hourPrice;                                // Price per hour while idle
-};
-
-struct NextPeriod
-{
-    unsigned char atTime[36];                       // Time when these prices become active
-    struct ChargingPrice chargingPrice;             // Price components while charging
-    struct IdlePrice idlePrice;                     // Price components while idle. Optional if no idle fee charged.
-};
-
-struct Triggers
-{
-    unsigned char atTime[36];                       // Time when these prices become active
-    float atEnergykWh;                              // Consumed energy amount in kWh upon which a meter value must be sent
-    float atPowerkW;                                // Power threshold in kW when meter value must be sent when crossing in downward or upward direction. Can either
-                                                    // be used to trigger a meter value when vehicle stops charging or when vehicle charges at a high power that requires a
-                                                    // different tariff.
-                                                    // It is recommended to implement a hysteresis around this value to avoid repetitive triggers when the power fluctuates around this level.
-    unsigned char atCPStatus[100];
-};
-
-struct StrcutRunningCost
-{
-    int                     txId;                   // Transaction to which this applies
-    unsigned char           timestamp[36];          // Timestamp of the meter value upon which this cost is based
-    unsigned int            meterValue;             // Meter value (Wh) upon which this cost is based
-    float                   cost;                   // Calculated total running cost
-    unsigned char           state[16];              // "Charging" or "Idle"
-    struct ChargingPrice    chargingPrice;          // Price components while charging
-    struct IdlePrice        idlePrice;              // (optional) Price components while not charging. Optional if no idle fee is charged.
-    struct NextPeriod       nextPeriod;             // (optional) Pricing for next period
-    struct Triggers         triggerMeterValue;      // (optional) Triggers to request a new meter value. Optional if no idle fee charged.
-    unsigned char           description[1024];      // Compatible California pricing V1.0
-};
-
-struct StrcutFinalCost
-{
-    int             txId;
-    unsigned char   description[1024];
-
-    float           cost;
-    unsigned char   priceText[1024];
-    unsigned char   qrCodeText[1024];
-};
-
-struct StructCost
-{
-    struct StrcutSetUserPrice       SetUserPrice;
-    struct StrcutRunningCost        RunningCost[CONNECTOR_QUANTITY];
-    struct StrcutFinalCost          FinalCost[CONNECTOR_QUANTITY];
-};
-
-struct CertificateHashDataType
-{
-    unsigned char hashAlgorithm[8];                             // Required. Used algorithms for the hashes provided.
-    unsigned char issuerNameHash[129];                          // Required. hashed value of the IssuerName.
-    unsigned char issuerKeyHash[129];                           // Required. Hashed value of the issuers public key
-    unsigned char serialNumber[41];                             // Required. The serial number of the certificate.
-};
-
-struct LogParametersType
-{
-    unsigned char remoteLocation[513];                              // Required. The URL of the location at the remote system where the log should be stored.
-    unsigned char oldestTimestamp[36];                              // Optional. This contains the date and time of the oldest logging information to include in the diagnostics.
-    unsigned char latestTimestamp[36];                              // Optional. This contains the date and time of the latest logging information to include in the diagnostics.
-};
-
-struct FirmwareType
-{
-    unsigned char location[513];                                    // Required. URI defining the origin of the firmware.
-    unsigned char retrieveDateTime[36];                             // Required. Date and time at which the firmware shall be retrieved.
-    unsigned char installDateTime[36];                              // Optional. Date and time at which the firmware shall be installed.
-    unsigned char signingCertificate[5501];                         // Optional. Certificate with which the firmware was signed. X.509 certificate, first DER encoded into binary, and then Base64 encoded.
-    unsigned char signature[801];                                   // Optional. Base64 encoded firmware signature.
-};
-
-struct StructCertificateSigned
-{
-    unsigned char certificateChain[10001];
-    unsigned char Response_status[16];
-};
-
-struct StructDeleteCertificate
-{
-    struct CertificateHashDataType certificateHashData;
-    unsigned char Response_status[16];
-};
-
-struct StructExtendedTrigger
-{
-    unsigned char requestedMessage[32];
-    int connectorId;
-    unsigned char Response_status[16];
-};
-
-struct StructGetInstalledCertificateIds
-{
-    unsigned char certificateType[32];
-    unsigned char Response_status[16];
-    struct CertificateHashDataType Response_certificateHashData[3];
-};
-
-struct StructGetLog
-{
-    unsigned char logType[16];
-    int requestId;
-    int retries;
-    int retryInterval;
-    struct LogParametersType log;
-    unsigned char Response_status[16];
-    unsigned char Response_filename[256];
-};
-
-struct StructInstallCertificate
-{
-    unsigned char certificateType[32];
-    unsigned char certificate[5501];
-    unsigned char Response_status[16];
-};
-
-struct StructSignedUpdateFirmware
-{
-    int retries;
-    int retryInterval;
-    int requestId;
-    struct FirmwareType firmware;
-    unsigned char Response_status[16];
-};
-
-struct StructLogStatusNotification
-{
-    unsigned char status[32];
-    int requestId;
-};
-
-struct StructSecurityEventNotification
-{
-    unsigned char type[51];
-    unsigned char timestamp[28];
-    unsigned char techInfo[256];
-};
-
-struct StructSignCertificate
-{
-    unsigned char csr[5501];
-    unsigned char Response_status[16];
-};
-
-struct StructSignedFirmwareStatusNotification
-{
-    unsigned char status[32];
-    int requestId;
-};
-
-struct StructSessionTarget
-{
-    unsigned char       targetSoc;          // Unit: %,         0 is unlimit
-    unsigned short      targetEnergy;       // Unit: KWH        0 is unlimit
-    unsigned short      targetDuration;     // Unit: Minutes    0 is unlimit
-};
-
-/**************************************************************************************/
-/************************* OCPP 2.0 Share memory **************************************/
-/**************************************************************************************/
-/*
- * =============== Enum variable content ===============
- */
-enum OCPP20CtrlrVariable
-{
-	AlignedDataCtrlr_Enabled=0,
-	AlignedDataCtrlr_Available,
-	AlignedDataCtrlr_Measurands,
-	AlignedDataCtrlr_Interval,
-	AlignedDataCtrlr_SendDuringIdle,
-	AlignedDataCtrlr_SignReadings,
-	AlignedDataCtrlr_TxEndedMeasurands,
-	AlignedDataCtrlr_TxEndedInterval,
-	AuthCtrlr_Enabled,
-	AuthCtrlr_AdditionalInfoItemsPerMessage,
-	AuthCtrlr_OfflineTxForUnknownIdEnabled,
-	AuthCtrlr_AuthorizeRemoteStart,
-	AuthCtrlr_LocalAuthorizeOffline,
-	AuthCtrlr_LocalPreAuthorize,
-	AuthCtrlr_MasterPassGroupId,
-	AuthCacheCtrlr_Enabled,
-	AuthCacheCtrlr_Available,
-	AuthCacheCtrlr_LifeTime,
-	AuthCacheCtrlr_Storage,
-	AuthCacheCtrlr_Policy,
-	ClockCtrlr_DateTime,
-	ClockCtrlr_NtpSource,
-	ClockCtrlr_NtpServerUri,
-	ClockCtrlr_TimeOffset,
-	ClockCtrlr_NextTimeOffsetTransitionDateTime,
-	ClockCtrlr_NextTransition_TimeOffset,
-	ClockCtrlr_TimeSource,
-	ClockCtrlr_TimeZone,
-	ChargingStation_Available,
-	ChargingStation_AvailabilityState,
-	ChargingStation_SupplyPhases,
-	ChargingStation_SystemUptimeSec,
-	ChargingStation_FreeVend,
-	ChargingStation_FreeVendIdtag,
-	ChargingStation_OffLineMaxChargingPower,
-	Connector_Available,
-	Connector_ConnectorType,
-	Connector_SupplyPhases,
-	CustomizationCtrlr_CustomImplementationEnabled,
-	DeviceDataCtrlr_GetReport_ItemsPerMessage,
-	DeviceDataCtrlr_GetVariables_ItemsPerMessage,
-	DeviceDataCtrlr_GetReport_BytesPerMessage,
-	DeviceDataCtrlr_GetVariables_BytesPerMessage,
-	DeviceDataCtrlr_ConfigurationValueSize,
-	DeviceDataCtrlr_ReportingValueSize,
-	DeviceDataCtrlr_SetVariables_ItemsPerMessage,
-	DeviceDataCtrlr_SetVariables_BytesPerMessage,
-	DisplayMessageCtrlr_Enabled,
-	DisplayMessageCtrlr_Available,
-	DisplayMessageCtrlr_DisplayMessages,
-	DisplayMessageCtrlr_SupportedFormats,
-	DisplayMessageCtrlr_SupportedPriorities,
-	EVSE_Available,
-	EVSE_AvailabilityState,
-	EVSE_SupplyPhases,
-	EVSE_Power,
-	LocalAuthListCtrlr_Enabled,
-	LocalAuthListCtrlr_Entries,
-	LocalAuthListCtrlr_Available,
-	LocalAuthListCtrlr_ItemsPerMessage,
-	LocalAuthListCtrlr_BytesPerMessage,
-	LocalAuthListCtrlr_Storage,
-	MonitoringCtrlr_Enabled,
-	MonitoringCtrlr_Available,
-	MonitoringCtrlr_ClearVariableMonitoring_ItemsPerMessage,
-	MonitoringCtrlr_SetVariableMonitoring_ItemsPerMessage,
-	MonitoringCtrlr_ClearVariableMonitoring_BytesPerMessage,
-	MonitoringCtrlr_SetVariableMonitoring_BytesPerMessage,
-	MonitoringCtrlr_OfflineQueuingSeverity,
-	OCPPCommCtrlr_ActiveNetworkProfile,
-	OCPPCommCtrlr_MessageTimeout,
-	OCPPCommCtrlr_FileTransferProtocols,
-	OCPPCommCtrlr_HeartbeatInterval,
-	OCPPCommCtrlr_NetworkConfigurationPriority,
-	OCPPCommCtrlr_NetworkProfileConnectionAttempts,
-	OCPPCommCtrlr_OfflineThreshold,
-	OCPPCommCtrlr_QueueAllMessages,
-	OCPPCommCtrlr_MessageAttempts,
-	OCPPCommCtrlr_MessageAttemptInterval,
-	OCPPCommCtrlr_UnlockOnEVSideDisconnect,
-	OCPPCommCtrlr_WebSocketPingInterval,
-	OCPPCommCtrlr_ResetRetries,
-	OCPPCommCtrlr_PublicKeyWithSignedMeterValue,
-    OCPPCommCtrlr_StatusNotificationPeriodically,
-    OCPPCommCtrlr_StatusNotificationInterval,
-	OCPPCommCtrlr_CharingProfileRefreshInterval,
-    OCPPCommCtrlr_VariableVersion,
-	ReservationCtrlr_Enabled,
-	ReservationCtrlr_Available,
-	ReservationCtrlr_NonEvseSpecific,
-	SampledDataCtrlr_Enabled,
-	SampledDataCtrlr_Available,
-	SampledDataCtrlr_SignReadings,
-	SampledDataCtrlr_TxEndedMeasurands,
-	SampledDataCtrlr_TxEndedInterval,
-	SampledDataCtrlr_TxStartedMeasurands,
-	SampledDataCtrlr_TxUpdatedMeasurands,
-	SampledDataCtrlr_TxUpdatedInterval,
-	SecurityCtrlr_BasicAuthPassword,
-	SecurityCtrlr_Identity,
-	SecurityCtrlr_OrganizationName,
-	SecurityCtrlr_CertificateEntries,
-	SecurityCtrlr_SecurityProfile,
-	SecurityCtrlr_AdditionalRootCertificateCheck,
-	SecurityCtrlr_MaxCertificateChainSize,
-	SmartChargingCtrlr_Enabled,
-	SmartChargingCtrlr_Available,
-	SmartChargingCtrlr_ACPhaseSwitchingSupported,
-	SmartChargingCtrlr_ProfileStackLevel,
-	SmartChargingCtrlr_RateUnit,
-	SmartChargingCtrlr_PeriodsPerSchedule,
-	SmartChargingCtrlr_ExternalControlSignalsEnabled,
-	SmartChargingCtrlr_NotifyChargingLimitWithSchedules,
-	SmartChargingCtrlr_Phases3to1,
-	SmartChargingCtrlr_Entries,
-	SmartChargingCtrlr_LimitChangeSignificance,
-	Tariff_Enabled,
-	Tariff_Available,
-	Tariff_TariffFallbackMessage,
-	Cost_Enabled,
-	Cost_Available,
-	Cost_TotalCostFallbackMessage,
-	Cost_Currency,
-	TxCtrlr_ChargingBeforeAcceptedEnabled,
-	TxCtrlr_EVConnectionTimeOut,
-	TxCtrlr_StopTxOnEVSideDisconnect,
-	TxCtrlr_TxBeforeAcceptedEnabled,
-	TxCtrlr_TxStartPoint,
-	TxCtrlr_TxStopPoint,
-	TxCtrlr_MaxEnergyOnInvalidId,
-	TxCtrlr_StopTxOnInvalidId,
-	CtrlrVariable_CNT
-};
-
-/*
- * =============== Common class ===============
- */
-struct ACChargingParametersType
-{
-	int energyAmount;											// Required, Amount of energy requested (in Wh). This includes energy required for preconditioning.
-	int evMinCurrent;											// Required. Minimum current (amps) supported by the electric vehicle (per phase).
-	int evMaxCurrent;											// Required. Maximum current (amps) supported by the electric vehicle (per phase). Includes cable capacity.
-	int evMaxVoltage;											// Required. Maximum voltage supported by the electric vehicle
-};
-
-struct DCChargingParametersType
-{
-	int evMaxCurrent;											// Required. Maximum current (amps) supported by the electric vehicle. Includes cable capacity.
-	int evMaxVoltage;											// Required. Maximum voltage supported by the electric vehicle
-	int energyAmount;											// Optional. Amount of energy requested (in Wh). This inludes energy required for preconditioning.
-	int evMaxPower;												// Optional. Maximum power (in W) supported by the electric vehicle. Required for DC charging.
-	unsigned char stateOfCharge;								// Optional. Energy available in the battery (in percent of the battery capacity)
-	int evEnergyCapacity;										// Optional. Capacity of the electric vehicle battery (in Wh)
-	unsigned char fullSoC;										// Optional. Percentage of SoC at which the EV considers the battery fully charged. (possible values: 0 - 100)
-	unsigned char bulkSoC;										// Optional. Percentage of SoC at which the EV considers a fast charging process to end. (possible values: 0 - 100)
-};
-
-struct AdditionalInfoType
-{
-	unsigned char	additionalIdToken[37];						// Required. This field specifies the additional IdToken.
-	unsigned char	type[51];									// Required. This defines the type of the additionalIdToken. This is a custom type, so the implementation needs to be agreed upon by all involved parties.
-};
-
-struct APNType
-{
-	unsigned char apn[512];										// Required. The Access Point Name as an URL.
-	unsigned char apnUserName[20];								// Optional. APN user name.
-	unsigned char apnPassword[20];								// Optional. APN Password.
-	short int	simPin;											// Optional. SIM card pin code.
-	unsigned char	preferredNetwork[6];						// Optional. Preferred network, written as MCC and MNC concatenated. See note.
-	unsigned char useOnlyPreferredNetwork;						// Optional. Default: false. Use only the preferred Network, do not dial in when not available. See Note.
-	short int apnAuthentication[8];								// Required. Authentication method.
-};
-
-struct VPNType
-{
-	unsigned char server[512];									// Required. VPN Server Address
-	unsigned char user[20];										// Required. VPN User
-	unsigned char group[20];									// Optional. VPN group.
-	unsigned char password[20];									// Required. VPN Password.
-	unsigned char key[255];										// Required. VPN shared secret.
-	unsigned char type[8];										// Required. Type of VPN
-};
-
-struct GroupIdTokenType
-{
-	unsigned char idToken[37];									// Required. IdToken is case insensitive. Might hold the hidden id of an RFID tag, but can for example also contain a UUID.
-	unsigned char type[16];										// Required. Enumeration of possible idToken types.
-	//struct AdditionalInfoType additionalInfo[10];               // Optional. AdditionalInfo can be used to send extra information which can be validated by the CSMS in addition to the regular authorization with IdToken.
-};
-
-struct MessageContentType
-{
-	unsigned char format[8];									// Required. Format of the message.
-	unsigned char	language[9];								// Optional. Message language identifier. Contains a language code as defined in [RFC5646].
-	unsigned char content[513];									// Required. Message contents.
-};
-
-struct IdTokenInfoType
-{
-	unsigned char status[32];									// Required. Current status of the ID Token.
-	unsigned char cacheExpiryDateTime[28];						// Optional. Date and Time after which the token must be considered invalid.
-	short int	chargingPriority;								// Optional. Priority from a business point of view. Default priority is 0, The range is from -9 to 9. Higher values indicate a higher priority.
-	unsigned char language1[9];									// Optional. Preferred user interface language of identifier user. Contains a language code as defined in [RFC5646].
-	unsigned int evseId[100];									// Optional. Only used when the IdToken is only valid for one or more specific EVSEs, not for the entire Charging Station.
-	unsigned char language2[9];									// Optional. Second preferred user interface language of identifier user. Don’t use when language1 is omitted, has to be different from language1.
-	struct GroupIdTokenType groupIdToken;						// Optional. This contains the group identifier.
-	struct MessageContentType personalMessage;					// Optional. Personal message that can be shown to the EV Driver and can be used for tariff information, user greetings etc.
-};
-
-struct IdTokenType
-{
-	unsigned char idToken[37];									// Required. IdToken is case insensitive. Might hold the hidden id of an RFID tag, but can for example also contain a UUID.
-	unsigned char	type[16];									// Required. Enumeration of possible idToken types.
-	struct AdditionalInfoType additionalInfo[10];				// Optional. AdditionalInfo can be used to send extra information which can be validated by the CSMS in addition to the regular authorization with IdToken.
-};
-
-struct AuthorizationData
-{
-	struct IdTokenInfoType idTokenInfo;							// Optional. Required when UpdateType is Full. This contains information about authorization status, expiry and group id.
-	struct IdTokenType idToken;									// Required. This contains the identifier which needs to be stored for authorization.
-};
-
-struct CertificateHashDataChainType
-{
-	unsigned char certificateType[32];							// Required. Indicates the type of the requested certificate(s).
-	struct CertificateHashDataType certificateHashData;			// Required. Information to identify a certificate.
-	struct CertificateHashDataType childCertificateHashData[4]; // Optional. Information to identify the child certificate(s).
-};
-
-
-struct ChargingLimitType
-{
-	unsigned char chargingLimitSource[8];						// Required. Represents the source of the charging limit.
-	unsigned char isGridCritical;								// Optional. Indicates whether the charging limit is critical for the grid.
-};
-
-struct ChargingNeedsType
-{
-	unsigned char requestedEnergyTransfer[32];					// Required. Mode of energy transfer requested by the EV.
-	unsigned char departureTime[28];							// Optional. Estimated departure time of the EV.
-	struct ACChargingParametersType acChargingParameters;		// Optional. EV AC charging parameters.
-	struct DCChargingParametersType dcChargingParameters;		// Optional. EV DC charging parameters
-};
-
-struct ChargingProfileCriterionType
-{
-	unsigned char chargingProfilePurpose[36];					// Optional. Defines the purpose of the schedule transferred by this profile
-	unsigned short int stackLevel;								// Optional. Value determining level in hierarchy stack of profiles. Higher values have precedence over lower values. Lowest level is 0.
-	unsigned short int chargingProfileId[10];					// Optional. List of all the chargingProfileIds requested. Any ChargingProfile that matches one of these profiles will be reported.
-	unsigned char chargingLimitSource[4][8];					// Optional. For which charging limit sources, charging profiles SHALL be reported. If omitted, the Charging Station SHALL not filter on chargingLimitSource.
-};
-
-struct RelativeTimeIntervalTypeOCPP
-{
-	unsigned int start;											// Required. Start of the interval, in seconds from NOW.
-	unsigned int duration;										// Optional. Duration of the interval, in seconds.
-};
-
-struct CostTypeOCPP
-{
-	unsigned char costKind[36];									// Required. The kind of cost referred to in the message element amount
-	int amount;													// Required. The estimated or actual cost per kWh
-	int amountMultiplier;                                       // Optional. Values: -3..3, The amountMultiplier defines the exponent to base 10 (dec). The final value is determined by: amount * 10 ^ amountMultiplier
-};
-
-struct ConsumptionCostTypeOCPP
-{
-	float startValue;											// Required. The lowest level of consumption that defines the starting point of this consumption block. The block interval extends to the start of the next interval.
-	struct CostTypeOCPP cost[3];								// Required. This field contains the cost details.
-};
-
-struct SalesTariffEntryTypeOCPP
-{
-	unsigned short int ePriceLevel;								// Optional. Defines the price level of this SalesTariffEntry (referring to NumEPriceLevels). Small values for the EPriceLevel represent a cheaper TariffEntry. Large values for the EPriceLevel represent a more expensive TariffEntry.
-	struct RelativeTimeIntervalTypeOCPP relativeTimeInterval;	// Required. Defines the time interval the SalesTariffEntry is valid for, based upon relative times.
-	struct ConsumptionCostTypeOCPP consumptionCost[3];			// Optional. Defines additional means for further relative price information and/or alternative costs.
-};
-
-struct SalesTariffTypeOCPP
-{
-	unsigned short int id;										// Required. SalesTariff identifier used to identify one sales tariff. An SAID remains a unique identifier for one schedule throughout a charging session.
-	unsigned char salesTariffDescription[32];					// Optional. A human readable title/short description of the sales tariff e.g. for HMI display purposes.
-	unsigned short int numEPriceLevels;							// Optional. Defines the overall number of distinct price levels used across all provided SalesTariff elements.
-	struct SalesTariffEntryTypeOCPP salesTariffEntry[1024];		// Required. Encapsulating element describing all relevant details for one time interval of the SalesTariff. The number of SalesTariffEntry elements is limited by the parameter maxScheduleTuples.
-};
-
-struct ChargingSchedulePeriodType
-{
-	int startPeriod;											// Required. Start of the period, in seconds from the start of schedule. The value of StartPeriod also defines the stop time of the previous period.
-	float limit;												// Required. Charging rate limit during the schedule period, in the applicable chargingRateUnit, for example in Amperes (A) or Watts (W). Accepts at most one digit fraction (e.g. 8.1).
-	unsigned char	numberPhases;								// Optional. The number of phases that can be used for charging. If a number of phases is needed, numberPhases=3 will be assumed unless another number is given.
-	unsigned char phaseToUse;									// Optional. Values: 1..3, Used if numberPhases=1 and if the EVSE is capable of switching the phase connected to theEV, i.e. ACPhaseSwitchingSupported is defined and true.
-};
-
-struct ChargingScheduleType
-{
-	unsigned char startSchedule[28];							// Optional. Starting point of an absolute schedule. If absent the schedule will be relative to start of charging.
-	unsigned int duration;										// Optional. Duration of the charging schedule in seconds.
-	unsigned char chargingRateUnit[8];							// Required. The unit of measure Limit is expressed in.
-	float minChargingRate;										// Optional. Minimum charging rate supported by the EV.
-	unsigned short int id;										// Required. Identifies the ChargingSchedule.
-	struct ChargingSchedulePeriodType chargingSchedulePeriod[1024];	// Required. List of ChargingSchedulePeriod elements defining maximum power or current usage over time.
-	struct SalesTariffTypeOCPP salesTariff;						// Optional. Sales tariff associated with this charging schedule.
-};
-
-struct ChargingProfileType
-{
-	int id;											                // Required. Id of ChargingProfile.
-	unsigned short int stackLevel;									// Required. Value determining level in hierarchy stack of profiles. Higher values have precedence over lower values. Lowest level is 0.
-	unsigned char chargingProfilePurpose[36];						// Required. Defines the purpose of the schedule transferred by this profile
-	unsigned char chargingProfileKind[16];							// Required. Indicates the kind of schedule.
-	unsigned char recurrencyKind[8];								// Optional. Indicates the start point of a recurrence.
-	unsigned char validFrom[28];									// Optional. Point in time at which the profile starts to be valid. If absent, the profile is valid as soon as it is received by the Charging Station.
-	unsigned char validTo[28];										// Optional. Point in time at which the profile stops to be valid. If absent, the profile is valid until it is replaced by another profile.
-	unsigned char transactionId[37];								// Optional. SHALL only be included if ChargingProfilePurpose is set to TxProfile. The transactionId is used to match the profile to a specific transaction.
-	struct ChargingScheduleType chargingSchedule[3];				// Required. Schedule that contains limits for the available power or current over time. In order to support ISO 15118 schedule negotiation, it supports at most three schedules with associated tariff to choose from.
-};
-
-struct ModemType
-{
-	unsigned char iccid[20];										// Optional. This contains the ICCID of the modem’s SIM card.
-	unsigned char imsi[20];											// Optional. This contains the IMSI of the modem’s SIM card.
-};
-
-struct ChargingStationType
-{
-	unsigned char serialNumber[25];									// Optional. Vendor-specific device identifier.
-	unsigned char model[20];										// Required. Defines the model of the device.
-	unsigned char vendorName[50];									// Required. Identifies the vendor (not necessarily in a unique manner).
-	unsigned char firmwareVersion[50];								// Optional. This contains the firmware version of the Charging Station.
-	struct ModemType modem;											// Optional. Defines the functional parameters of a communication link.
-};
-
-struct ClearChargingProfileType
-{
-	unsigned int evseId;											// Optional. Specifies the id of the EVSE for which to clear charging profiles.
-	unsigned char chargingProfilePurpose[36];						// Optional. Specifies to purpose of the charging profiles that will be cleared, if they meet the other criteria in the request.
-	unsigned short int stackLevel;									// Optional. Specifies the stackLevel for which charging profiles will be cleared, if they meet the other criteria in the request.
-};
-
-struct ClearMonitoringResultType
-{
-	unsigned short int id;											// Required. Id of the monitor of which a clear was requested.
-	unsigned char status[16];										// Required. Result of the clear request for this monitor, identified by its Id.
-};
-
-struct EVSEType
-{
-	unsigned int id;												// Required. EVSE Identifier. This contains a number (> 0) designating an EVSE of the Charging Station.
-	unsigned char connectorId;										// Optional. An id to designate a specific connector (on an EVSE) by connector index number.
-};
-
-struct VariableType
-{
-	unsigned char name[50];											// Required. Name of the variable.
-	unsigned char instance[50];										// Optional. Name of instance in case the variable exists as multiple instances.
-};
-
-struct VariableAttributeType
-{
-	unsigned char type[8];											// Optional. Attribute: Actual, MinSet, MaxSet, etc. Defaults to Actual if absent.
-	unsigned char value[2500];										// Optional. Value of the attribute. May only be omitted when mutability is set to 'WriteOnly'.
-	unsigned char mutability[16];									// Optional. Defines the mutability of this attribute. Default is ReadWrite when omitted.
-	unsigned char persistent;										// Optional. If true, value will be persistent across system reboots or power down. Default when omitted is false.
-	unsigned char constant;											// Optional. If true, value that will never be changed by the Charging Station at runtime. Default when omitted is false.
-};
-
-struct VariableCharacteristicsType
-{
-	unsigned char unit[16];											// Optional. Unit of the variable. When the transmitted value has a unit, this field SHALL be included.
-	unsigned char dataType[16];										// Required. Data type of this variable.
-	float 	minLimit;												// Optional. Minimum possible value of this variable.
-	float 	maxLimit;												// Optional. Maximum possible value of this variable.
-	unsigned char valuesList[1000];									// Optional. Allowed values when variable is Option/Member/SequenceList.
-	unsigned char supportsMonitoring;								// Required. Flag indicating if this variable supports monitoring.
-};
-
-struct ComponentType
-{
-	unsigned char name[50];											// Required. Name of the component.
-	unsigned char instance[50];										// Optional. Name of instance in case the component exist as multiple instances.
-	struct EVSEType evse;											// Optional. Specifies the EVSE when component is located at EVSE level, also specifies the connector when component is located at Connector level.
-};
-
-struct ComponentVariableType
-{
-	struct ComponentType component;									// Required. Component for which a report of Variable is requested.
-	struct VariableType variable;									// Optional. Variable(s) for which the report is requested.
-};
-
-struct CompositeScheduleType
-{
-	unsigned char startDateTime[28];								// Required. Date and time at which the schedule becomes active.
-	struct ChargingScheduleType chargingSchedule;					// Required. Charging schedule structure defines a list of charging periods.
-};
-
-struct EventDataType
-{
-	unsigned int eventId;											// Required. Identifies the event. This field can be referred to as a cause by other events.
-	unsigned char timestamp[28];									// Required. Timestamp of the moment the report was generated.
-	unsigned char trigger[16];										// Required. Type of monitor that triggered this event, e.g. exceeding a threshold value.
-	unsigned int cause;												// Optional. Refers to the Id of an event that is considered to be the cause for this event.
-	unsigned char actualValue[2500];								// Required. Actual value (attributeType Actual) of the variable.
-	unsigned char techcode[50];										// Optional. Technical (error) code as reported by component.
-	unsigned char techInfo[500];									// Optional. Technical detail information as reported by component.
-	unsigned char cleared;											// Optional. Cleared is set to true to report the clearing of a monitored situation, i.e. a 'return to normal'.
-	unsigned char transactionId[37];								// Optional. If an event notification is linked to a specific transaction, this field can be used to specify its transactionId.
-	unsigned int variableMonitoringId;								// Optional. Identifies the VariableMonitoring which triggered the event.
-	unsigned char eventNotificationType[32];						// Required. Specifies the event notification type of the message.
-	struct ComponentType component;									// Required. Component for which event is notified.
-	struct VariableType variable;									// Required. Variable for which event is notified.
-};
-
-struct GetVariableDataType
-{
-	unsigned char attributeType[8];									// Optional. Attribute type for which value is requested. When absent, default Actual is assumed.
-	struct ComponentType component;									// Required. Component for which the Variable is requested.
-	struct VariableType variable;									// Required. Variable for which the attribute value is requested.
-};
-
-struct GetVariableResultType
-{
-	unsigned char attributeStatus[32];								// Required. Result status of getting the variable.
-	unsigned char attributeType[8];									// Optional. Attribute type for which value is requested. When absent, default Actual is assumed.
-	unsigned char attributeValue[2500];								// Optional. Value of requested attribute type of component- variable.
-	struct ComponentType component;									// Required. Component for which the Variable is requested.
-	struct VariableType variable;									// Required. Variable for which the attribute value is requested.
-};
-
-struct MessageInfoType
-{
-	unsigned int id;												// Required. Master resource identifier, unique within an exchange context. It is defined within the OCPP context as a positive Integer value (greater or equal to zero).
-	unsigned char priority[16];										// Required. With what priority should this message be shown
-	unsigned char state[16];										// Optional. During what state should this message be shown. When omitted this message should be shown in any state of the Charging Station.
-	unsigned char startDateTime[28];								// Optional. From what date-time should this message be shown. If omitted: directly.
-	unsigned char endDateTime[28];									// Optional. Until what date-time should this message be shown, after this date/time this message SHALL be removed.
-	unsigned char transactionId[37];								// Optional. During which transaction shall this message be shown. Message SHALL be removed by the Charging Station after transaction has ended.
-	struct MessageContentType message;								// Required. Contains message details for the message to be displayed on a Charging Station.
-	struct ComponentType display;									// Optional. When a Charging Station has multiple Displays, this field can be used to define to which Display this message belongs.
-};
-
-struct SignedMeterValueType
-{
-	unsigned char signedMeterData[2500];							// Required. Base64 encoded, contains the signed data which might contain more then just the meter value. It can contain information like timestamps, reference to a customer etc.
-	unsigned char signingMethod[50];								// Required. Method used to create the digital signature.
-	unsigned char encodingMethod[50];								// Required. Method used to encode the meter values before applying the digital signature algorithm.
-	unsigned char publicKey[2500];									// Required. Base64 encoded, sending depends on configuration variable PublicKeyWithSignedMeterValue.
-};
-
-struct UnitOfMeasureType
-{
-	unsigned char uint[20];											// Optional. Unit of the value. Default = "Wh" if the (default) measurand is an "Energy" type.
-	unsigned short int multiplier;									// Optional. Multiplier, this value represents the exponent to base 10. I.e. multiplier 3 means 10 raised to the 3rd power. Default is 0.
-};
-
-struct SampledValueType
-{
-    double value;													// Required. Indicates the measured value.
-	unsigned char context[32];										// Optional. Type of detail value: start, end or sample. Default = "Sample.Periodic"
-	unsigned char measurand[32];									// Optional. Type of measurement. Default = "Energy.Active.Import.Register"
-	unsigned char phase[8];											// Optional. Indicates how the measured value is to be interpreted.
-	unsigned char location[8];										// Optional. Indicates where the measured value has been sampled. Default = "Outlet"
-	struct SignedMeterValueType signedMeterValue;					// Optional. Contains the MeterValueSignature with sign/encoding method information.
-	struct UnitOfMeasureType unitOfMeasure;							// Optional. Represents a UnitOfMeasure including a multiplier
-};
-
-struct MeterValueType
-{
-	unsigned char timestamp[28];									// Required. Timestamp for measured value(s).
-	struct SampledValueType sampledValue[20];						// Required. One or more measured values
-};
-
-struct VariableMonitoringType
-{
-	unsigned int id;												// Required. Identifies the monitor.
-	float value;													// Required. Value for threshold or delta monitoring. For Periodic or PeriodicClockAligned this is the interval in seconds.
-	unsigned char type[32];											// Required. The type of this monitor, e.g. a threshold, delta or periodic monitor.
-	unsigned char severity;											// Required. The severity that will be assigned to an event that is triggered by this monitor.
-	unsigned char transaction;										// Required. Monitor only active when a transaction is ongoing on a component relevant to this transaction.
-};
-
-struct MonitoringDataType
-{
-	struct ComponentType component;									// Required. Component for which monitoring report was requested.
-	struct VariableType variable;									// Required. Variable for which monitoring report was requested.
-	struct VariableMonitoringType variableMonitoring[10];			// Required. List of monitors for this Component-Variable pair.
-};
-
-struct NetworkConnectionProfileType
-{
-	unsigned char ocppVersion[8];									// Required. Defines the OCPP version used for this communication function.
-	unsigned char ocppTransport[8];									// Required. Defines the transport protocol (e.g. SOAP or JSON). Note: SOAP is not supported in OCPP 2.0, but is supported by other versions of OCPP.
-	unsigned char ocppCsmsUrl[512];									// Required. URL of the CSMS(s) that this Charging Station communicates with.
-	unsigned int messageTimeout;									// Required. Duration in seconds before a message send by the Charging Station via this network connection times- out. The best setting depends on the underlying network and response times of the CSMS. If you are looking for a some guideline: use 30 seconds as a starting point.
-	unsigned char ocppInterface[16];								// Required. Applicable Network Interface.
-	struct VPNType vpn;												// Optional. Settings to be used to set up the VPN connection
-	struct APNType apn;												// Optional. Collection of configuration data needed to make a data-connection over a cellular network.
-};
-
-struct OCSPRequestDataType
-{
-	unsigned char hashAlgorithm[8];									// Required. Used algorithms for the hashes provided.
-	unsigned char issuerNameHash[129];								// Required. hashed value of the IssuerName.
-	unsigned char issuerKeyHash[129];								// Required. Hashed value of the issuers public key
-	unsigned char serialNumber[41];									// Required. The serial number of the certificate.
-	unsigned char responderURL[513];								// Required. This contains the responder URL (Case insensitive).
-};
-
-struct ReportDataType
-{
-	struct ComponentType component;									// Required. Component for which a report of Variable is requested.
-	struct VariableType variable;									// Required. Variable for which report is requested.
-	struct VariableAttributeType variableAttribute[4];				// Required. Attribute data of a variable.
-	struct VariableCharacteristicsType variableCharacteristics;		// Optional. Fixed read-only parameters of a variable.
-};
-
-struct SetMonitoringDataType
-{
-	unsigned int id;												// Optional. An id SHALL only be given to replace an existing monitor. The Charging Station handles the generation of id’s for new monitors.
-	float value;													// Required. Value for threshold or delta monitoring. For Periodic or PeriodicClockAligned this is the interval in seconds.
-	unsigned char type[32];											// Required. The type of this monitor, e.g. a threshold, delta or periodic monitor.
-	unsigned char severity;											// Required. The severity that will be assigned to an event that is triggered by this monitor.
-	unsigned char transaction;										// Optional. Monitor only active when a transaction is ongoing on a component relevant to this transaction. Default = false.
-	struct ComponentType component;									// Required. Component for which monitor is set.
-	struct VariableType variable;									// Required. Variable for which monitor is set.
-};
-
-struct SetMonitoringResultType
-{
-	unsigned int id;												// Optional. Id given to the VariableMonitor by the Charging Station.
-	unsigned char type[32];											// Required. The type of this monitor, e.g. a threshold, delta or periodic monitor.
-	unsigned char severity;											// Required. The severity that will be assigned to an event that is triggered by this monitor.
-	unsigned char status[32];										// Required. Status is OK if a value could be returned.
-	struct ComponentType component;									// Required. Component for which status is returned.
-	struct VariableType variable;									// Required. Variable for which status is returned.
-};
-
-struct SetVariableDataType
-{
-	unsigned char attributeType[8];									// Optional. Type of attribute: Actual, Target, MinSet, MaxSet. Default is Actual when omitted.
-	unsigned char attributeValue[1000];								// Required. Value to be assigned to attribute of variable.
-	struct ComponentType component;									// Required. The component for which the variable data is set.
-	struct VariableType variable;									// Required. Specifies the that needs to be set.
-};
-
-struct SetVariableResultType
-{
-	unsigned char attributeType[8];									// Optional. Type of attribute: Actual, Target, MinSet, MaxSet. Default is Actual when omitted.
-	unsigned char attributeStatus[32];								// Required. Result status of setting the variable.
-	struct ComponentType component;									// Required. The component for which result is returned.
-	struct VariableType variable;									// Required. The variable for which the result is returned.
-};
-
-struct TransactionType
-{
-	unsigned char transactionId[37];								// Required. This contains the Id of the transaction.
-	unsigned char chargingState[16];								// Optional. Current charging state, is required when state has changed. Omitted when there is no communication between EVSE and EV, because no cable is plugged in.
-	unsigned int timeSpentCharging;									// Optional. Contains the total time that energy flowed from EVSE to EV during the transaction (in seconds). Note that timeSpentCharging is smaller or equal to the duration of the transaction.
-	unsigned char stoppedReason[20];								// Optional. This contains the reason why the transaction was stopped. MAY only be omitted when Reason is "Local".
-	unsigned int remoteStartId;										// Optional. The ID given to remote start request (RequestStartTransactionRequest.
-};
-
-struct StatusInfoType
-{
-    unsigned char reasonCode[21];                                   // Required. A predefined code for the reason why thestatus is returned in this response. The string is case-insensitive.
-    unsigned char additionalInfo[513];                              // Optional. Additional text to provide detailed information.
-};
-/*
- * =============== Message ===============
- */
-struct Authorize_20
-{
-    unsigned char certificate[5601];                                // Optional. The X.509 certificated presented by EV for authorization.
-	struct IdTokenType idToken;										// Required. This contains the identifier that needs to be authorized.
-	struct OCSPRequestDataType iso15118CertificateHashData[4];		// Optional. Contains the information needed to verify the EV Contract Certificate via OCSP.
-	unsigned char Response_certificateStatus[32];					// Optional. Certificate status information. - if all certificates are valid: return 'Accepted'. - if one of the certificates was revoked, return 'CertificateRevoked'.
-	struct IdTokenInfoType Response_idTokenInfo;					// Required. This contains information about authorization status, expiry and group id.
-};
-
-struct BootNotification_20
-{
-	unsigned char reason[20];										// Required. This contains the reason for sending this message to the CSMS.
-	struct ChargingStationType chargingStation;						// Required. Identifies the Charging Station
-	unsigned char Response_currentTime[28];							// Required. This contains the CSMS’s current time.
-	unsigned int Response_interval;									// Required. When Status is Accepted, this contains the heartbeat interval in seconds. If the CSMS returns something other than Accepted, the value of the interval field indicates the minimum wait time before sending a next BootNotification request.
-	unsigned char Response_status[16];								// Required. This contains whether the Charging Station has been registered within the CSMS.
-};
-
-struct CancelReservation_20
-{
-	int reservationId;												// Required. Id of the reservation to cancel.
-	unsigned char Response_status[16];								// Required. This indicates the success or failure of the canceling of a reservation by CSMS.
-	unsigned char guid[37];											// Save guid from server request
-};
-
-struct CertificateSigned_20
-{
-    unsigned char certificateChain[10001];                          // Required. Required. The signed PEM encoded X.509 certificate.This can also contain the necessary sub CA certificates.In that case, the order of the bundle should follow thecertificate chain, starting from the leaf certificate.The Configuration Variable MaxCertificateChainSize canbe used to limit the maximum size of this field.
-    unsigned char certificateType[32];                              // Optional. Indicates the type of the signed certificate that is returned.
-    unsigned char Response_status[16];                              // Required. Returns whether certificate signing has been accepted, otherwise rejected.
-    struct StatusInfoType Response_statusInfo;                      // Optional. Detailed status information.
-    unsigned char guid[37];                                         // Save guid from server request
-};
-
-struct ChangeAvailability_20
-{
-	unsigned char operationalStatus[16];							// Required. This contains the type of availability change that the Charging Station should perform.
-	struct EVSEType evse;											// Optional. Contains Id’s to designate a specific EVSE/connector by index numbers. When omitted, the message refers to the Charging Station as a whole.
-	unsigned char Response_status[16];								// Required. This indicates whether the Charging Station is able to perform the availability change.
-	unsigned char guid[37];											// Save guid from server request
-};
-
-struct ClearCache_20
-{
-	unsigned char Response_status[16];								// Required. Accepted if the Charging Station has executed the request, otherwise rejected.
-	unsigned char guid[37];											// Save guid from server request
-};
-
-struct ClearChargingProfile_20
-{
-	unsigned int chargingProfileId;									// Optional. The Id of the charging profile to clear.
-	struct  ClearChargingProfileType chargingProfileCriteria;		// Optional. Specifies the charging profile.
-	unsigned char Response_status[16];								// Required. Indicates if the Charging Station was able to execute the request.
-	unsigned char guid[37];											// Save guid from server request
-};
-
-struct ClearDisplayMessage_20
-{
-	unsigned int id;												// Required. Id of the message that SHALL be removed from the Charging Station.
-	unsigned char Response_status[16];								// Required. Returns whether the Charging Station has been able to remove the message.
-	unsigned char guid[37];											// Save guid from server request
-};
-
-struct ClearedChargingLimit_20
-{
-	unsigned char chargingLimitSource[8];							// Required. Source of the charging limit.
-	unsigned int evseId;											// Optional. EVSE Identifier.
-};
-
-struct ClearVariableMonitoring_20
-{
-	unsigned int id[10];										 	// Required. List of the monitors to be cleared, identified by there Id.
-	struct ClearMonitoringResultType Response_clearMonitoringResult[10];// Required. List of result statuses per monitor.
-	unsigned char guid[37];											// Save guid from server request
-};
-
-struct CostUpdated_20
-{
-	float totalCost;												// Required. Current total cost, based on the information known by the CSMS, of the transaction including taxes. In the currency configured with the configuration Variable: [Currency]
-	unsigned char transactionId[37];								// Required. Transaction Id of the transaction the current cost are asked for.
-	unsigned char guid[37];											// Save guid from server request
-};
-
-struct CustomerInformation_20
-{
-	unsigned int requestId;											// Required. The Id of the request.
-	unsigned char report;											// Required. Flag indicating whether the Charging Station should return NotifyCustomerInformationRequest messages containing information about the customer referred to.
-	unsigned char clear;											// Required. Flag indicating whether the Charging Station should clear all information about the customer referred to.
-	unsigned char customerIdentifier[64];							// Optional. A (e.g. vendor specific) identifier of the customer this request refers to. This field contains a custom identifier other than IdToken and Certificate. One of the possible identifiers (customerIdentifier, customerIdToken or customerCertificate) should be in the request message.
-	struct IdTokenType idToken;										// Optional. The IdToken of the customer this request refers to. One of the possible identifiers (customerIdentifier, customerIdToken or customerCertificate) should be in the request message.
-	struct CertificateHashDataType customerCertificate;				// Optional. The Certificate of the customer this request refers to. One of the possible identifiers (customerIdentifier, customerIdToken or customerCertificate) should be in the request message.
-	unsigned char Response_status[16];								// Required. Indicates whether the request was accepted.
-	unsigned char guid[37];											// Save guid from server request
-};
-
-struct DataTransfer_20
-{
-	unsigned char messageId[50];									// Optional. May be used to indicate a specific message or implementation.
-	unsigned char data[512];										// Optional. Data without specified length or format. This needs to be decided by both parties (Open to implementation).
-	unsigned char vendorId[255];									// Required. This identifies the Vendor specific implementation
-	unsigned char Response_status[20];								// Required. This indicates the success or failure of the data transfer.
-	unsigned char Response_data[512];								// Optional. Data without specified length or format, in response to request.
-	unsigned char guid[37];											// Save guid from server request
-};
-
-struct DeleteCertificate_20
-{
-	struct CertificateHashDataType certificateHashData;				// Required. Indicates the certificate of which deletion is requested.
-	unsigned char Response_status[16];								// Required. Charging Station indicates if it can process the request.
-	unsigned char guid[37];											// Save guid from server request
-};
-
-struct FirmwareStatusNotification_20
-{
-	unsigned char status[32];										// Required. This contains the progress status of the firmware installation.
-	unsigned int requestId;											// Optional. The request id that was provided in the UpdateFirmwareRequest that started this firmware update. This field is mandatory, unless the message was triggered by a TriggerMessageRequest AND there is no firmware update ongoing.
-};
-
-struct Get15118EVCertificate_20
-{
-	unsigned char iso15118SchemaVersion[51];						// Required. Schema version currently used for the 15118 session between EV and Charging Station. Needed for parsing of the EXI stream by the CSMS.
-	unsigned char action[16];										// Required. Defines whether certificate needs to be installed or updated.
-	unsigned char exiRequest[5601];									// Required. Raw CertificateInstallationReq request from EV, Base64 encoded.
-	unsigned char Response_status[16];								// Required. Indicates whether the message was processed properly.
-	unsigned char Response_exiResponse[5601];						// Required. Raw CertificateInstallationRes response for the EV, Base64 encoded.
-};
-
-struct GetBaseReport_20
-{
-	unsigned int requestId;											// Required. The Id of the request.
-	unsigned char reportBase[32];									// Required. This field specifies the report base.
-	unsigned char Response_status[16];								// Required. This indicates whether the Charging Station is able to accept this request.
-	unsigned char guid[37];											// Save guid from server request
-};
-
-struct GetCertificateStatus_20
-{
-	struct OCSPRequestDataType ocspRequestData;						// Required. Indicates the certificate of which the status is requested.
-	unsigned char Response_status[16];								// Required. This indicates whether the charging station was able to retrieve the OCSP certificate status.
-	unsigned char Response_ocspResult[5501];						// Optional. OCSPResponse class as defined in IETF RFC 6960. DER encoded (as defined in IETF RFC 6960), and then base64 encoded. MAY only be omitted when status is not Accepted.
-	struct StatusInfoType Response_statusInfo;                      // Optional. Detailed status information.
-};
-
-struct GetChargingProfiles_20
-{
-	unsigned int requestId;											// Required. Reference identification that is to be used by the Charging Station in the ReportChargingProfilesRequest when provided.
-	unsigned int evseId;											// Optional. For which EVSE installed charging profiles SHALL be reported. If 0, only charging profiles installed on the Charging Station itself (the grid connection) SHALL be reported. If omitted, all installed charging profiles SHALL be reported.
-	struct ChargingProfileCriterionType chargingProfile;			// Required. Specifies the charging profile.
-	unsigned char Response_status[16];								// Required. This indicates whether the Charging Station is able to process this request and will send ReportChargingProfilesRequest messages.
-	unsigned char guid[37];											// Save guid from server request
-};
-
-struct GetCompositeSchedule_20
-{
-	unsigned int duration;											// Required. Length of the requested schedule in seconds.
-	unsigned char chargingRateUnit[8];								// Optional. Can be used to force a power or current profile.
-	unsigned int evseId;											// Required. The ID of the EVSE for which the schedule is requested. When evseid=0, the Charging Station will calculate the expected consumption for the grid connection.
-	unsigned char Response_status[16];								// Required. The Charging Station will indicate if it was able to process the request
-	struct CompositeScheduleType Response_schedule;					// Optional. This field contains the calculated composite schedule. It may only be omitted when this message contains status Rejected.
-	unsigned char guid[37];											// Save guid from server request
-};
-
-struct GetDisplayMessages_20
-{
-	unsigned int id[10];											// Optional. If provided the Charging Station shall return Display Messages of the given ids. This field SHALL NOT contain more ids than set in NumberOfDisplayMessages.maxLimit
-	unsigned int requestId;											// Required. The Id of this request.
-	unsigned char	priority[16];									// Optional. If provided the Charging Station shall return Display Messages with the given priority only.
-	unsigned char state[16];										// Optional. If provided the Charging Station shall return Display Messages with the given state only.
-	unsigned char Response_status[16];								// Required. Indicates if the Charging Station has Display Messages that match the request criteria in the GetDisplayMessagesRequest
-	unsigned char guid[37];											// Save guid from server request
-};
-
-struct GetInstalledCertificateIds_20
-{
-	unsigned char certificateType[10][32];										// Optional. Indicates the type of certificates requested. When omitted, all certificate types are requested.
-	unsigned char Response_status[16];											// Required. Charging Station indicates if it can process the request.
-	struct CertificateHashDataChainType Response_certificateHashDataChain[10];	// Optional. The Charging Station includes the Certificate information for each available certificate.
-	unsigned char guid[37];														// Save guid from server request
-};
-
-struct GetLocalListVersion_20
-{
-	int Response_versionNumber;										// Required. This contains the current version number of the local authorization list in the Charging Station.
-	unsigned char guid[37];											// Save guid from server request
-};
-
-struct GetLog_20
-{
-	unsigned char logType[16];										// Required. This contains the type of log file that the Charging Station should send.
-	unsigned int requestId;											// Required. The Id of this request
-	unsigned char retries;											// Optional. This specifies how many times the Charging Station must try to upload the log before giving up. If this field is not present, it is left to Charging Station to decide how many times it wants to retry.
-	unsigned int retryInterval;										// Optional. The interval in seconds after which a retry may be attempted. If this field is not present, it is left to Charging Station to decide how long to wait between attempts.
-	struct LogParametersType log;									// Required. This field specifies the requested log and the location to which the log should be sent.
-	unsigned char Response_status[20];								// Required. This field indicates whether the Charging Station was able to accept the request.
-	unsigned char Response_filename[255];							// Optional. This contains the name of the log file that will be uploaded. This field is not present when no logging information is available.
-	unsigned char guid[37];											// Save guid from server request
-};
-
-struct GetMonitoringReport_20
-{
-	unsigned int requestId;											// Required. The Id of the request.
-	unsigned char monitoringCriteria[3][32];						// Optional. This field contains criteria for components for which a monitoring report is requested
-	struct ComponentVariableType componentVariable[10];				// Optional. This field specifies the components and variables for which a monitoring report is requested.
-	unsigned char Response_status[20];								// Required. This field indicates whether the Charging Station was able to accept the request.
-	unsigned char guid[37];											// Save guid from server request
-};
-
-struct GetReport_20
-{
-	unsigned int requestId;											// Required. The Id of the request.
-	unsigned char componentCriteria[4][16];							// Optional. This field contains criteria for components for which a report is requested
-	struct ComponentVariableType componentVariable[10];				// Optional. This field specifies the components and variables for which a report is requested.
-	unsigned char Response_status[20];								// Required. This field indicates whether the Charging Station was able to accept the request.
-	unsigned char guid[37];											// Save guid from server request
-};
-
-struct GetTransactionStatus_20
-{
-	unsigned char transactionId[37];								// Optional. The Id of the transaction for which the status is requested.
-	unsigned char Response_ongoingIndicator;						// Optional. Whether the transaction is still ongoing.
-	unsigned char Response_messagesInQueue;							// Required. Whether there are still message to be delivered.
-	unsigned char guid[37];											// Save guid from server request
-};
-
-struct GetVariables_20
-{
-	struct GetVariableDataType getVariableData[CtrlrVariable_CNT];				// Required. List of requested variables.
-	struct GetVariableResultType Response_getVariableResult[CtrlrVariable_CNT];	// Required. List of requested variables and their values.
-	unsigned char guid[37];                                                     // Save guid from server request
-};
-
-struct Heartbeat_20
-{
-	unsigned char Response_currentTime[28];							// Required. Contains the current time of the CSMS.
-};
-
-struct InstallCertificate_20
-{
-	unsigned char certificateType[32];								// Required. Indicates the certificate type that is sent.
-	unsigned char certificate[5501];								// Required. A X.509 certificate, first DER encoded into binary, and then Base64 encoded.
-	unsigned char Response_status[16];								// Required. Charging Station indicates if installation was successful.
-	unsigned char guid[37];											// Save guid from server request
-};
-
-struct LogStatusNotification_20
-{
-	unsigned char status[32];										// Required. This contains the status of the log upload.
-	unsigned int requestId;											// Optional. The request id that was provided in GetLogRequest that started this log upload. This field is mandatory, unless the message was triggered by a TriggerMessageRequest AND there is no log upload ongoing.
-};
-
-struct MeterValues_20
-{
-	unsigned int evseId;											// Required. This contains a number (>0) designating an EVSE of the Charging Station. ‘0’ (zero) is used to designate the main power meter.
-	struct MeterValueType meterValue[1];							// Required. The sampled meter values with timestamps.
-};
-
-struct NotifyChargingLimit_20
-{
-	unsigned int evseId;											// Optional. The charging schedule contained in this notification applies to an EVSE. evseId must be > 0.
-	struct ChargingLimitType chargingLimit;							// Required. This contains the source of the charging limit and whether it is grid critical.
-	struct ChargingScheduleType chargingSchedule[1];				// Optional. Contains limits for the available power or current over time, as set by the external source.
-};
-
-struct NotifyCustomerInformation_20
-{
-	unsigned char data[512];										// Required. (Part of) the requested data. No format specified in which the data is returned. Should be human readable.
-	unsigned char tbc;												// Optional. “to be continued” indicator. Indicates whether another part of the monitoringData follows in an upcoming notifyMonitoringReportRequest message. Default value when omitted is false.
-	unsigned int seqNo;												// Required. Sequence number of this message. First message starts at 0.
-	unsigned char generatedAt[28];									// Required. Timestamp of the moment this message was generated at the Charging Station.
-	unsigned int requestId;											// Required. The Id of the request.
-};
-
-struct NotifyDisplayMessages_20
-{
-	unsigned int requestId;                                         // Required. The id of the GetDisplayMessagesRequest that requested this message.
-	unsigned char tbc;												// Optional. "to be continued" indicator. Indicates whether another part of the report follows in an upcoming NotifyDisplayMessagesRequest message. Default value when omitted is false.
-	struct MessageInfoType messageInfo[10];							// Optional. The requested display message as configured in the Charging Station.
-};
-
-struct NotifyEVChargingNeeds_20
-{
-	unsigned int maxScheduleTuples;									// Optional. Contains the maximum schedule tuples the car supports per SASchedule (both Pmax and Tariff).
-	unsigned int evseId;											// Required. Defines the EVSE and connector to which the EV is connected. EvseId may not be 0.
-	struct ChargingNeedsType chargingNeeds;							// Required. The characteristics of the energy delivery required.
-	unsigned char Response_status[16];								// Required. Returns whether the CSMS has been able to process the message successfully. It does not imply that the evChargingNeeds can be met with the current charging profile.
-	struct StatusInfoType Response_statusInfo;                      // Optional. Detailed status information.
-};
-
-struct NotifyEVChargingSchedule_20
-{
-	unsigned char timeBase[28];										// Required. Periods contained in the charging profile are relative to this point in time.
-	unsigned int evseId;											// Required. The charging schedule contained in this notification applies to an EVSE. EvseId must be > 0.
-	struct ChargingScheduleType chargingSchedule;					// Required. Planned energy consumption of the EV over time. Always relative to timeBase.
-	unsigned char Response_status[16];								// Required. Returns whether the CSMS has been able to process the message successfully. It does not imply any approval of the charging schedule.
-	struct StatusInfoType Response_statusInfo;                      // Optional. Detailed status information.
-};
-
-struct NotifyEvent_20
-{
-	unsigned char generatedAt[28];									// Required. Timestamp of the moment this message was generated at the Charging Station.
-	unsigned char tbc;												// Optional. “to be continued” indicator. Indicates whether another part of the report follows in an upcoming notifyEventRequest message. Default value when omitted is false.
-	unsigned int seqNo;												// Required. Sequence number of this message. First message starts at 0.
-	struct EventDataType eventData[10];								// Required. List of EventData.
-};
-
-struct NotifyMonitoringReport_20
-{
-	unsigned int requestId;											// Required. The id of the GetMonitoringRequest that requested this report.
-	unsigned char tbc;												// Optional. “to be continued” indicator.
-	unsigned int seqNo;												// Required. Sequence number of this message. First message starts at 0.
-	unsigned char generatedAt[28];									// Required. Timestamp of the moment this message was generated at the Charging Station.
-	struct MonitoringDataType monitor[10];							// Optional. List of MonitoringData containing monitoring settings.
-};
-
-struct NotifyReport_20
-{
-	unsigned int requestId;											// Required. The id of the GetReportRequest or GetBaseReportRequest that requested this report
-	unsigned char generatedAt[28];									// Required. Timestamp of the moment this message was generated at the Charging Station.
-	unsigned char tbc;												// Optional. “to be continued” indicator.
-	unsigned int seqNo;												// Required. Sequence number of this message. First message starts at 0.
-	struct ReportDataType reportData[10];							// Optional. List of ReportData.
-};
-
-struct PublishFirmware_20
-{
-	unsigned char location[512];									// Required. This contains a string containing a URI pointing to a location from which to retrieve the firmware.
-	unsigned char retries;											// Optional. This specifies how many times Charging Station must try to download the firmware before giving up. If this field is not present, it is left to Charging Station to decide how many times it wants to retry.
-	unsigned char checksum[32];										// Required. The MD5 checksum over the entire firmware file as a hexadecimal string of length 32.
-	unsigned int requestId;											// Required. The Id of the request.
-	unsigned int retryInterval;										// Optional. The interval in seconds after which a retry may be attempted. If this field is not present, it is left to Charging Station to decide how long to wait between attempts.
-	unsigned char Response_status[16];								// Required. Indicates whether the request was accepted.
-	unsigned char guid[37];											// Save guid from server request
-};
-
-struct PublishFirmwareStatusNotification_20
-{
-	unsigned char status[32];										// Required. This contains the progress status of the publishfirmware installation.
-	unsigned char location[10][512];                                // Optional. Required if status is Published. Can be multiple URI’s, if the Local Controller supports e.g. HTTP, HTTPS, and FTP.
-	unsigned int requestId;											// Optional. The request id that was provided in the PublishFirmwareRequest which triggered this action.
-};
-
-struct ReportChargingProfiles_20
-{
-	unsigned int requestId;											// Required. Id used to match the GetChargingProfilesRequest message with the resulting ReportChargingProfilesRequest messages
-	unsigned char chargingLimitSource[8];							// Required. Source that has installed this charging profile.
-	unsigned char tbc;												// Optional. To Be Continued. Default value when omitted: false. false indicates that there are no further messages as part of this report.
-	unsigned int evseId;											// Required. The evse to which the charging profile applies. If evseId = 0, the message contains an overall limit for the Charging Station.
-	struct ChargingProfileType chargingProfile[3];					// Required. The charging profile as configured in the Charging Station.
-};
-
-struct RequestStartTransaction_20
-{
-	unsigned int evseId;											// Optional. Number of the EVSE on which to start the transaction. EvseId SHALL be > 0
-	unsigned int remoteStartId;										// Required. Id given by the server to this start request.
-	struct IdTokenType idToken;										// Required. The identifier that the Charging Station must use to start a transaction.
-	struct ChargingProfileType chargingProfile;						// Optional. Charging Profile to be used by the Charging Station for the requested transaction.
-	struct IdTokenType groupIdToken;								// Optional. The group identifier that the Charging Station must use to start a transaction.
-	unsigned char Response_status[16];								// Required. Status indicating whether the Charging Station accepts the request to start a transaction.
-	unsigned char Response_transactionId[37];						// Optional. When the transaction was already started by the Charging Station before the RequestStartTransactionRequest was received, for example: cable plugged in first. This contains the transactionId of the already started transaction.
-	unsigned char guid[37];											// Save guid from server request
-};
-
-struct RequestStopTransaction_20
-{
-	unsigned char transactionId[37];								// Required. The identifier of the transaction which the Charging Station is requested to stop.
-	unsigned char Response_status[16];								// Required. Status indicating whether Charging Station accepts the request to stop a transaction.
-	unsigned char guid[37];											// Save guid from server request
-};
-
-struct ReservationStatusUpdate_20
-{
-	int reservationId;												// Required. The ID of the reservation.
-	unsigned char reservationUpdateStatus[8];						// Required. The updated reservation status.
-};
-
-struct ReserveNow_20
-{
-	unsigned int id;												// Required. Id of reservation.
-	unsigned char expiryDateTime[28];								// Required. Date and time at which the reservation expires.
-	unsigned char connectorType[16];								// Optional. This field specifies the connector type.
-	unsigned int evseId;											// Optional. This contains ID of the evse to be reserved.
-	struct IdTokenType idToken;										// Required. The identifier for which the reservation is made.
-	struct IdTokenType groupIdToken;								// Optional. The group identifier for which the reservation is made.
-	unsigned char Response_status[16];								// Required. This indicates the success or failure of the reservation.
-	unsigned char guid[37];											// Save guid from server request
-};
-
-struct Reset_20
-{
-	unsigned char type[16];											// Required. This contains the type of reset that the Charging Station or EVSE should perform.
-	unsigned int evseId;											// Optional. This contains the ID of a specific EVSE that needs to be reset, instead of the entire Charging Station.
-	unsigned char Response_status[16];								// Required. This indicates whether the Charging Station is able to perform the reset.
-	unsigned char guid[37];											// Save guid from server request
-};
-
-struct SecurityEventNotification_20
-{
-	unsigned char type[50];											// Required. Type of the security event. This value should be taken from the Security events list.
-	unsigned char timestamp[28];									// Required. Date and time at which the event occurred.
-	unsigned char techInfo[255];									// Optional. Additional information about the occurred security event.
-};
-
-struct SendLocalList_20
-{
-	unsigned int versionNumber;										// Required. In case of a full update this is the versio number of the full list. In case of a differential update it i the version number of the list after the update has bee applied.
-	unsigned char updateType[32];									// Required. This contains the type of update (full or differential) of this request.
-	struct AuthorizationData localAuthorizationList[500];			// Optional. This contains the Local Authorization List entries.
-	unsigned char Response_status[16];								// Required. This indicates whether the Charging Station has successfully received and applied the update of the Local Authorization List.
-	unsigned char guid[37];											// Save guid from server request
-};
-
-struct SetChargingProfile_20
-{
-	unsigned int evseId;											// Required. The EVSE to which the charging profile applies. If evseId = 0, the message contains an overall limit for the Charging Station.
-	struct ChargingProfileType chargingProfile;						// Required. The charging profile to be set at the Charging Station.
-	unsigned char Response_status[16];								// Required. Returns whether the Charging Station has been able to process the message successfully. This does not guarantee the schedule will be followed to the letter. There might be other constraints the Charging Station may need to take into account.
-	unsigned char guid[37];											// Save guid from server request
-	struct StatusInfoType Response_statusInfo;                      // Optional. Detailed status information.
-};
-
-struct SetDisplayMessage_20
-{
-	struct MessageInfoType message;									// Required. Message to be configured in the Charging Station, to be displayed.
-	unsigned char Response_status[32];								// Required. This indicates whether the Charging Station is able to display the message.
-	unsigned char guid[37];											// Save guid from server request
-};
-
-struct SetMonitoringBase_20
-{
-	unsigned char monitoringBase[16];								// Required. Specify which monitoring base will be set
-	unsigned char Response_status[16];								// Required. Indicates whether the Charging Station was able to accept the request.
-	unsigned char guid[37];											// Save guid from server request
-};
-
-struct SetMonitoringLevel_20
-{
-	unsigned int severity;											// Required. The Charging Station SHALL only report events with a severity number lower than or equal to this severity.
-	unsigned char Response_status[16];         						// Required. Indicates whether the Charging Station was able to accept the request.
-	unsigned char guid[37];											// Save guid from server request
-};
-
-struct SetNetworkProfile_20
-{
-	unsigned int configurationSlot;									// Required. Slot in which the configuration should be stored.
-	struct NetworkConnectionProfileType connectionData;				// Required. Connection details.
-	unsigned char Response_status[16];									// Required. Result of operation.
-	unsigned char guid[37];											// Save guid from server request
-};
-
-struct SetVariableMonitoring_20
-{
-	struct SetMonitoringDataType setMonitoringData[10];				// Required. List of MonitoringData containing monitoring settings.
-	struct SetMonitoringResultType Response_setMonitoringResult[10];// Required. List of result statuses per monitor.
-	unsigned char guid[37];											// Save guid from server request
-};
-
-struct SetVariables_20
-{
-	struct SetVariableDataType setVariableData[CtrlrVariable_CNT];              // Required. List of Component-Variable pairs and attribute values to set.
-	struct SetVariableResultType Response_setVariableResult[CtrlrVariable_CNT]; // Required. List of result statuses per Component-Variable.
-	unsigned char guid[37];                                                     // Save guid from server request
-};
-
-struct SignCertificate_20
-{
-    unsigned char csr[5501];                                        // Required. The Charging Station SHALL send the public key in form of a Certificate Signing Request (CSR) as described in RFC 2986 [22] using the SignCertificateRequest message.
-    unsigned char certificateType[32];                              // Optional. Indicates the type of certificate that is to be signed. When omitted the certificate is to be used for both the 15118 connection (if implemented) and the Charging Station to CSMS connection.
-    unsigned char Response_status[16];                              // Required. Specifies whether the CSMS can process the request.
-    struct StatusInfoType Response_statusInfo;                      // Optional. Detailed status information.
-};
-
-struct StatusNotification_20
-{
-	unsigned char timestamp[28];									// Required. The time for which the status is reported. If absent time of receipt of the message will be assumed.
-	unsigned char connectorStatus[16];								// Required. This contains the current status of the Connector.
-	unsigned int evseId;											// Required. The id of the EVSE to which the connector belongs for which the the status is reported.
-	unsigned char connectorId;										// Required. The id of the connector within the EVSE for which the status is reported.
-};
-
-struct TransactionEvent_20
-{
-	unsigned char eventType[16];									// Required. This contains the type of this event. The first TransactionEvent of a transaction SHALL contain: "Started" The last TransactionEvent of a transaction SHALL contain: "Ended" All others SHALL contain: "Updated"
-	unsigned char timestamp[28];									// Required. The date and time at which this transaction event occurred.
-	unsigned char triggerReason[32];								// Required. Reason the Charging Station sends this message to the CSMS
-	unsigned int seqNo;												// Required. Incremental sequence number, helps with determining if all messages of a transaction have been received.
-	unsigned char offline;											// Optional. Indication that this transaction event happened when the Charging Station was offline. Default = false, meaning: the event occurred when the Charging Station was online.
-	unsigned char numberOfPhasesUsed;								// Optional. If the Charging Station is able to report the number of phases used, then it SHALL provide it. When omitted the CSMS may be able to determine the number of phases used via device management.
-	float cableMaxCurrent;											// Optional. The maximum current of the connected cable in Ampere (A).
-	int reservationId;												// Optional. This contains the Id of the reservation that terminates as a result of this transaction.
-	struct TransactionType transactionInfo;							// Required. Contains transaction specific information.
-	struct IdTokenType idToken;										// Optional. This contains the identifier for which a transaction has to be/was started.
-	struct EVSEType evse;											// Optional. This identifies which evse (and connector) of the Charging Station is used.
-	struct MeterValueType meterValue[1];							// Optional. This contains the relevant meter values.
-	float Response_totalCost;										// Optional. SHALL only be sent when charging has ended. Final total cost of this transaction, including taxes.
-	int Response_chargingPriority;									// Optional. Priority from a business point of view. Default priority is 0,
-	struct IdTokenInfoType Response_idTokenInfo;					// Optional. This contains information about authorization status, expiry and group id. Is required when the transactionEventRequest contained an idToken.
-	struct MessageContentType Response_updatedPersonalMessage;		// Optional. This can contain updated personal message that can be shown to the EV Driver. This can be used to provide updated tariff information
-};
-
-struct TriggerMessage_20
-{
-	unsigned char requestedMessage[32];								// Required. Type of message to be triggered.
-	struct EVSEType evse;											// Optional. Can be used to specifiy the EVSE and Connector if required for the message which needs to be sent.
-	unsigned char Response_status[16];								// Required. Indicates whether the Charging Station will send the requested notification or not.
-	unsigned char guid[37];											// Save guid from server request
-};
-
-struct UnlockConnector_20
-{
-	unsigned int evseId;											// Required. This contains the identifier of the EVSE for which a connector needs to be unlocked.
-	unsigned char connectorId;										// Required. This contains the identifier of the connector that needs to be unlocked.
-	unsigned char Response_status[32];								// Required. This indicates whether the Charging Station has unlocked the connector.
-	unsigned char guid[37];											// Save guid from server request
-};
-
-struct UnpublishFirmware_20
-{
-	unsigned char checksum[32];										// Required. The MD5 checksum over the entire firmware file as a hexadecimal string of length 32.
-	unsigned char Response_status[16];								// Required. Indicates whether the Local Controller succeeded in unpublishing the firmware.
-	unsigned char guid[37];											// Save guid from server request
-};
-
-struct UpdateFirmware_20
-{
-	unsigned char retries;											// Optional. This specifies how many times Charging Station must try to download the firmware before giving up. If this field is not present, it is left to Charging Station to decide how many times it wants to retry.
-	unsigned int retryInterval;										// Optional. The interval in seconds after which a retry may be attempted. If this field is not present, it is left to Charging Station to decide how long to wait between attempts.
-	unsigned int requestId;											// Required. The Id of this request
-	struct FirmwareType firmware;									// Required. Specifies the firmware to be updated on the Charging Station.
-	unsigned char Response_status[32];								// Required. This field indicates whether the Charging Station was able to accept the request.
-	unsigned char guid[37];											// Save guid from server request
-};
-
-struct NetworkConnectionProfile_20
-{
-    unsigned int slot;
-    unsigned char retryCount;
-    struct NetworkConnectionProfileType connectionData;
-};
-
-//===================================
-// YES custom protocol
-//===================================
-struct StructChargerInfo
-{
-    unsigned char station_name[64];
-};
-
-struct StructWeatherInfo
-{
-    int   weatherId;
-    float temperature;
-};
-
-struct StructCreditDeductResult
-{
-    int txId;
-    unsigned char creditNo[64];
-    unsigned char vemData[80];
-    unsigned char ROC[20];
-    unsigned char RRN[20];
-    unsigned char storeId[20];
-    unsigned char approvalNo[20];
-    double        amount;
-    unsigned char deductResult:1;
-    unsigned char isDonateInvoice:1;
-};
-
-struct StructReaderStatus
-{
-    int readerStatus;
-    unsigned char creditNo[64];
-    unsigned char ReportReaderStatusReq:1;
-};
-
-struct StructTcciCustomData
-{
-    struct StructChargerInfo ChargerInfo;
-    struct StructWeatherInfo WeatherInfo;
-    struct StructCreditDeductResult DeductInfo;
-    struct StructReaderStatus ReaderStatus[CONNECTOR_QUANTITY];
-    unsigned char TriggerReaderReq[3];
-    unsigned char SerialNo[CONNECTOR_QUANTITY][37];
-    unsigned char VEMData[CONNECTOR_QUANTITY][65];
-
-    unsigned char ReportCreditDeductReq:1;
-    unsigned char ChargerInfoReq:1;
-    unsigned char ChargerInfoConf:1;
-    unsigned char WeatherInfoReq:1;
-    unsigned char WeatherInfoConf:1;
-    unsigned char :3;                  // bit 5-7 , reserved
-};
-
-struct OCMFData
-{
-    unsigned char SendOcmfDataReq:1;   // bit 0 , Flag to ask OCPP sending OCMF message to backend.
-    unsigned char :7;                  // bit 1-7 , reserved
-    unsigned char DataString[2048];    // Data got from meter.
-    unsigned char PublicKey[256];      // PublicKey with header got from meter.
-};
-
-struct OCPP16_V2g_Extend
-{
-	struct Authorize_20						Authorize;
-	struct CertificateSigned_20				CertificateSigned;
-	struct DeleteCertificate_20				DeleteCertificate;
-	struct Get15118EVCertificate_20			Get15118EVCertificate;
-	struct GetCertificateStatus_20			GetCertificateStatus;
-	struct GetInstalledCertificateIds_20	GetInstalledCertificateIds;
-	struct InstallCertificate_20			InstallCertificate;
-	struct SignCertificate_20				SignCertificate;
-
-
-	unsigned char							AuthorizeReq:1;
-	unsigned char							AuthorizeConf:1;
-	unsigned char							Get15118EVCertificateReq:1;
-	unsigned char 							Get15118EVCertificateConf:1;
-	unsigned char							GetCertificateStatusReq:1;
-	unsigned char 							GetCertificateStatusConf:1;
-	unsigned char							SignCertificateReq:1;
-	unsigned char							SignCertificateConf:1;
-};
-
-struct OCPP16Data
-{
-    unsigned char                           OcppServerURL[512];     //http: non-secure OCPP 1.5-S, https: secure OCPP 1.5-S, ws: non-secure OCPP 1.6-J, wss: secure OCPP 1.6-J"
-    unsigned char                           ChargeBoxId[128];
-    unsigned char                           OcppConnStatus;         //0: disconnected, 1: connected
-    unsigned int                            Timeout_Secs;
-    unsigned short                          Ping_Pong_Interval;
-    long int                                procDogTime;            // Process watch dog refresh timer
-    union
-    {
-        //Operations Initiated by Charge Point
-        unsigned char CpMsgValue[CONNECTOR_QUANTITY];
-        struct
-        {
-            //CpMsgValue[0]
-            unsigned char DataTransferReq:1;        //bit 0,
-            unsigned char DataTransferConf:1;       //bit 1,
-            unsigned char StartTransactionReq:1;    //bit 2,
-            unsigned char StartTransactionConf:1;   //bit 3,
-            unsigned char StopTransactionReq:1;     //bit 4,
-            unsigned char StopTransactionConf:1;    //bit 5,
-            unsigned char :2;                       //bit 6,7 , reserved
-        } bits[CONNECTOR_QUANTITY];
-    }CpMsg;
-
-    union
-    {
-        //Operations Initiated by Sequence Point
-        unsigned char SpMsgValue[2];
-        struct
-        {
-            //SpMsgValue[0]
-            unsigned char BootNotificationReq :1;                   //bit 0,
-            unsigned char BootNotificationConf :1;                  //bit 1,
-            unsigned char AuthorizeReq :1;                          //bit 2,
-            unsigned char AuthorizeConf :1;                         //bit 3,
-            unsigned char DiagnosticsStatusNotificationReq :1;      //bit 4,
-            unsigned char DiagnosticsStatusNotificationConf :1;     //bit 5,
-            unsigned char FirmwareStatusNotificationReq :1;         //bit 6,
-            unsigned char FirmwareStatusNotificationConf :1;        //bit 7,
-            //SpMsgValue[1]
-            unsigned char LogStatusNotificationReq :1;              //bit 0,
-            unsigned char LogStatusNotificationConf :1;             //bit 1,
-            unsigned char SecurityEventNotificationReq :1;          //bit 2,
-            unsigned char SecurityEventNotificationConf :1;         //bit 3,
-            unsigned char SignCertificateReq :1;                    //bit 4,
-            unsigned char SignCertificateConf :1;                   //bit 5,
-            unsigned char SignedFirmwareStatusNotificationReq :1;   //bit 6,
-            unsigned char SignedFirmwareStatusNotificationConf :1;  //bit 7,
-        } bits;
-    } SpMsg;
-
-    union
-    {
-        //Operations Initiated by Central System
-        unsigned char CsMsgValue[3 * (CONNECTOR_QUANTITY)];
-        struct
-        {
-            //CsMsgValue[0]
-            unsigned char CancelReservationReq :1;      //bit 0,
-            unsigned char CancelReservationConf :1;     //bit 1,
-            unsigned char ChangeAvailabilityReq :1;     //bit 2,
-            unsigned char ChangeAvailabilityConf :1;    //bit 3,
-            unsigned char ReserveNowReq :1;             //bit 4,
-            unsigned char ReserveNowConf :1;            //bit 5,
-            unsigned char SetChargingProfileReq :1;     //bit 6,
-            unsigned char SetChargingProfileConf :1;    //bit 7,
-            //CsMsgValue[1]
-            unsigned char TriggerMessageReq :1;         //bit 0,
-            unsigned char TriggerMessageConf :1;        //bit 1,
-            unsigned char UnlockConnectorReq :1;        //bit 2,
-            unsigned char UnlockConnectorConf :1;       //bit 3,
-            unsigned char RemoteStartTransactionReq :1; //bit 4,
-            unsigned char RemoteStartTransactionConf :1;//bit 5,
-            unsigned char RemoteStopTransactionReq :1;  //bit 6,
-            unsigned char RemoteStopTransactionConf :1; //bit 7,
-            //CsMsgValue[2]
-            unsigned char ClearChargingProfileReq :1;   //bit 0,
-            unsigned char ClearChargingProfileConf :1;  //bit 1,
-            unsigned char DataTransferReq :1;           //bit 2,
-            unsigned char DataTransferConf :1;          //bit 3,
-            unsigned char GetCompositeScheduleReq :1;   //bit 4,
-            unsigned char GetCompositeScheduleConf :1;  //bit 5,
-            unsigned char :2;                           //bit 6,7
-        } bits[CONNECTOR_QUANTITY];
-    }CsMsg;
-
-    union
-    {
-        //Operations Initiated by Main System
-        unsigned char MsMsgValue[4];
-        struct
-        {
-            //CsMsgValue[0]
-            unsigned char ChangeConfigurationReq :1;                //bit 0,
-            unsigned char ChangeConfigurationConf :1;               //bit 1,
-            unsigned char ClearCacheReq :1;                         //bit 2,
-            unsigned char ClearCacheConf :1;                        //bit 3,
-            unsigned char GetConfigurationReq :1;                   //bit 4,
-            unsigned char GetConfigurationConf :1;                  //bit 5,
-            unsigned char UpdateFirmwareReq :1;                     //bit 6,
-            unsigned char UpdateFirmwareConf :1;                    //bit 7,
-            //CsMsgValue[1]
-            unsigned char GetDiagnosticsReq :1;                     //bit 0,
-            unsigned char GetDiagnosticsConf :1;                    //bit 1,
-            unsigned char GetLocalListVersionReq :1;                //bit 2,
-            unsigned char GetLocalListVersionConf :1;               //bit 3,
-            unsigned char ResetReq :1;                              //bit 4,
-            unsigned char ResetConf :1;                             //bit 5,
-            unsigned char SendLocalListReq :1;                      //bit 6,
-            unsigned char SendLocalListConf :1;                     //bit 7,
-            //CsMsgValue[2]
-            unsigned char CertificateSignedReq :1;                  //bit 0
-            unsigned char CertificateSignedConf :1;                 //bit 1
-            unsigned char DeleteCertificateReq :1;                  //bit 2
-            unsigned char DeleteCertificateConf :1;                 //bit 3
-            unsigned char ExtendedTriggerMessageReq :1;             //bit 4
-            unsigned char ExtendedTriggerMessageConf :1;            //bit 5
-            unsigned char GetInstalledCertificateIdsReq :1;         //bit 6
-            unsigned char GetInstalledCertificateIdsConf :1;        //bit 7
-            //CsMsgValue[3]
-            unsigned char GetLogReq :1;                             //bit 0
-            unsigned char GetLogConf :1;                            //bit 1
-            unsigned char InstallCertificateReq :1;                 //bit 2
-            unsigned char InstallCertificateConf :1;                //bit 3
-            unsigned char SignedUpdateFirmwareReq :1;               //bit 4
-            unsigned char SignedUpdateFirmwareConf :1;              //bit 5
-            unsigned char isRemoteStartWaitReq :1;                  //bit 6
-            unsigned char :1;                                       //bit 7
-        } bits;
-    } MsMsg;
-
-    union
-    {
-        //Operations triggered by CSU
-        unsigned char CSUMsgValue[CONNECTOR_QUANTITY];
-        struct
-        {
-            //CSUMsgValue[0]
-            unsigned char ChargingProfileReq:1;     //bit 0,
-            unsigned char ChargingProfileConf:1;    //bit 0,
-            unsigned char :6;                       //bit 1,2,3,4,5,6,7 , reserved
-        } bits[CONNECTOR_QUANTITY];
-    }CSUMsg;
-
-    struct StructBootNotification                   BootNotification;
-    struct StructHeartbeat                          Heartbeat;
-    struct StructAuthorize                          Authorize;
-    struct StructStartTransaction                   StartTransaction[CONNECTOR_QUANTITY];
-    struct StructStopTransaction                    StopTransaction[CONNECTOR_QUANTITY];
-    struct StructStatusNotification                 StatusNotification[CONNECTOR_QUANTITY];
-    struct StructCancelReservation                  CancelReservation[CONNECTOR_QUANTITY];
-    struct StructChangeAvailability                 ChangeAvailability[CONNECTOR_QUANTITY];
-    struct StructChangeConfiguration                ChangeConfiguration;
-    struct StructClearCache                         ClearCache;
-    struct StructClearChargingProfile               ClearChargingProfile[CONNECTOR_QUANTITY];
-    struct StructDataTransfer                       DataTransfer[CONNECTOR_QUANTITY];
-    struct StructDiagnosticsStatusNotification      DiagnosticsStatusNotification;
-    struct StructFirmwareStatusNotification         FirmwareStatusNotification;
-    struct StructGetCompositeSchedule               GetCompositeSchedule[CONNECTOR_QUANTITY];
-    struct StructGetConfiguration                   GetConfiguration;
-    struct StructGetDiagnostics                     GetDiagnostics;
-    struct StructGetLocalListVersion                GetLocalListVersion;
-    struct StructMeterValues                        MeterValues[CONNECTOR_QUANTITY];
-    struct StructRemoteStartTransaction             RemoteStartTransaction[CONNECTOR_QUANTITY];
-    struct StructRemoteStopTransaction              RemoteStopTransaction[CONNECTOR_QUANTITY];
-    struct StructReserveNow                         ReserveNow[CONNECTOR_QUANTITY];
-    struct StructReset                              Reset;
-    struct StructSendLocalList                      SendLocalList;
-    struct StructSetChargingProfile                 SetChargingProfile[CONNECTOR_QUANTITY];
-    struct StructTriggerMessage                     TriggerMessage[CONNECTOR_QUANTITY];
-    struct StructUnlockConnector                    UnlockConnector[CONNECTOR_QUANTITY];
-    struct StructUpdateFirmware                     UpdateFirmware;
-    struct OCPP16ConfigurationTable                 ConfigurationTable;
-    struct StructChargingProfile                    SmartChargingProfile[CONNECTOR_QUANTITY];
-    struct StructChargingProfile                    MaxChargingProfile;
-    struct StructCost                               Cost;
-    struct StructCertificateSigned                  CertificateSigned;
-    struct StructDeleteCertificate                  DeleteCertificate;
-    struct StructExtendedTrigger                    ExtendedTriggerMessage;
-    struct StructGetInstalledCertificateIds         GetInstalledCertificateIds;
-    struct StructGetLog                             GetLog;
-    struct StructInstallCertificate                 InstallCertificate;
-    struct StructSignedUpdateFirmware               SignedUpdateFirmware;
-    struct StructLogStatusNotification              LogStatusNotification;
-    struct StructSecurityEventNotification          SecurityEventNotification;
-    struct StructSignCertificate                    SignCertificate;
-    struct StructSignedFirmwareStatusNotification   SignedFirmwareStatusNotification;
-    struct StructSessionTarget                      SessionTarget[CONNECTOR_QUANTITY];
-    struct StructTcciCustomData                     TcciCustomData;
-    struct OCMFData                                 OcmfData[CONNECTOR_QUANTITY];
-    struct OCPP16_V2g_Extend						v2g_extend;
-};
-
-struct OCPP20Data
-{
-	unsigned char 							OcppServerURL[512];		//http: non-secure OCPP 1.5-S, https: secure OCPP 1.5-S, ws: non-secure OCPP 1.6-J, wss: secure OCPP 1.6-J"
-	unsigned char 							ChargeBoxId[128];
-	unsigned char 							OcppConnStatus;			//0: disconnected, 1: connected
-	unsigned int 							Timeout_Secs;
-	unsigned short 							Ping_Pong_Interval;
-	long int                                procDogTime;            // Process watch dog refresh timer
-	struct ReportDataType                   ControllerComponentVariable[CtrlrVariable_CNT];
-	struct NetworkConnectionProfile_20      NetworkConnectionProfile[10];
-
-	union
-	{
-		//Operations Initiated by Charge Point
-		unsigned char CpMsgValue[CONNECTOR_QUANTITY];
-		struct
-		{
-			unsigned char DataTransferReq:1;
-			unsigned char DataTransferConf:1;
-			unsigned char ReservationStatusUpdateReq :1;
-			unsigned char ReservationStatusUpdateConf :1;
-			unsigned char TransactionEventReq :1;
-			unsigned char TransactionEventConf :1;
-			unsigned char :2;	//bit 6,7 , reserved
-		} bits[CONNECTOR_QUANTITY];
-	}CpMsg;
-
-	union
-	{
-		//Operations Initiated by Sequence Point
-		unsigned char SpMsgValue[4];
-		struct
-		{
-			unsigned char BootNotificationReq :1;	//bit 0,
-			unsigned char BootNotificationConf :1;	//bit 1,
-			unsigned char AuthorizeReq :1; //bit 2,
-			unsigned char AuthorizeConf :1;	//bit 3,
-			unsigned char FirmwareStatusNotificationReq :1; //bit 6,
-			unsigned char FirmwareStatusNotificationConf :1; //bit 7,
-			unsigned char Get15118EVCertificateReq :1;
-			unsigned char Get15118EVCertificateConf :1;
-
-			unsigned char GetCertificateStatusReq :1;
-			unsigned char GetCertificateStatusConf :1;
-			unsigned char LogStatusNotificationReq :1;
-			unsigned char LogStatusNotificationConf :1;
-			unsigned char NotifyChargingLimitReq :1;
-			unsigned char NotifyChargingLimitConf :1;
-			unsigned char NotifyDisplayMessagesReq :1;
-			unsigned char NotifyDisplayMessagesConf :1;
-
-			unsigned char NotifyCustomerInformationReq :1;
-			unsigned char NotifyCustomerInformationConf :1;
-			unsigned char NotifyEventReq :1;
-			unsigned char NotifyEventConf :1;
-			unsigned char NotifyMonitoringReportReq :1;
-			unsigned char NotifyMonitoringReportConf :1;
-			unsigned char NotifyReportReq :1;
-			unsigned char NotifyReportConf :1;
-
-			unsigned char ReportChargingProfilesReq :1;
-			unsigned char ReportChargingProfilesConf :1;
-			unsigned char SecurityEventNotificationReq :1;
-			unsigned char SecurityEventNotificationConf :1;
-			unsigned char SignCertificateReq :1;
-			unsigned char SignCertificateConf :1;
-            unsigned char :1; //bit 6
-            unsigned char :1; //bit 7
-
-		} bits;
-	} SpMsg;
-
-	union
-	{
-		//Operations Initiated by Central System
-		unsigned char CsMsgValue[3 * (CONNECTOR_QUANTITY)];
-		struct
-		{
-			unsigned char CancelReservationReq :1;	//bit 0,
-			unsigned char CancelReservationConf :1;	//bit 1,
-			unsigned char ChangeAvailabilityReq :1; //bit 2,
-			unsigned char ChangeAvailabilityConf :1;	//bit 3,
-			unsigned char ClearChargingProfileReq :1;	//bit 0,
-			unsigned char ClearChargingProfileConf :1;	//bit 1,
-			unsigned char DataTransferReq :1; //bit 2,
-			unsigned char DataTransferConf :1;	//bit 3,
-
-			unsigned char PublishFirmwareStatusNotificationReq :1;
-			unsigned char PublishFirmwareStatusNotificationConf :1;
-			unsigned char RequestStartTransactionReq :1;
-			unsigned char RequestStartTransactionConf :1;
-			unsigned char RequestStopTransactionReq :1;
-			unsigned char RequestStopTransactionConf :1;
-			unsigned char ReserveNowReq :1;	//bit 4,
-			unsigned char ReserveNowConf :1;	//bit 5,
-
-			unsigned char TriggerMessageReq :1;		//bit 0,
-			unsigned char TriggerMessageConf :1;	//bit 1,
-			unsigned char UnlockConnectorReq :1; 	//bit 2,
-			unsigned char UnlockConnectorConf :1;	//bit 3,
-			unsigned char :4;						//bit 6,7 , reserved
-
-		} bits[CONNECTOR_QUANTITY];
-	}CsMsg;
-
-	union
-	{
-		//Operations Initiated by Main System
-		unsigned char MsMsgValue[8];
-		struct
-		{
-			//CsMsgValue[0]
-			unsigned char CertificateSignedReq :1;
-			unsigned char CertificateSignedConf :1;
-			unsigned char ClearCacheReq :1;	//bit 2,
-			unsigned char ClearCacheConf :1;	//bit 3,
-			unsigned char ClearDisplayMessageReq :1;
-			unsigned char ClearDisplayMessageConf :1;
-			unsigned char ClearVariableMonitoringReq :1;
-			unsigned char ClearVariableMonitoringConf :1;
-
-			unsigned char CostUpdatedReq :1;
-			unsigned char CostUpdatedConf :1;
-			unsigned char CustomerInformationReq :1;
-			unsigned char CustomerInformationConf :1;
-			unsigned char DeleteCertificateReq :1;
-			unsigned char DeleteCertificateConf :1;
-			unsigned char GetBaseReportReq :1;
-			unsigned char GetBaseReportConf :1;
-
-			unsigned char GetChargingProfilesReq :1;
-			unsigned char GetChargingProfilesConf :1;
-			unsigned char GetCompositeScheduleReq :1;	//bit 4,
-			unsigned char GetCompositeScheduleConf :1;	//bit 5,
-			unsigned char GetDisplayMessagesReq :1;
-			unsigned char GetDisplayMessagesConf :1;
-			unsigned char GetInstalledCertificateIdsReq :1;
-			unsigned char GetInstalledCertificateIdsConf :1;
-
-			unsigned char GetLocalListVersionReq :1; //bit 2,
-			unsigned char GetLocalListVersionConf :1;	//bit 3,
-			unsigned char GetLogReq :1;
-			unsigned char GetLogConf :1;
-			unsigned char GetMonitoringReportReq :1;
-			unsigned char GetMonitoringReportConf :1;
-			unsigned char GetReportReq :1;
-			unsigned char GetReportConf :1;
-
-			unsigned char GetTransactionStatusReq :1;
-			unsigned char GetTransactionStatusConf :1;
-			unsigned char GetVariablesReq :1;
-			unsigned char GetVariablesConf :1;
-			unsigned char InstallCertificateReq :1;
-			unsigned char InstallCertificateConf :1;
-			unsigned char PublishFirmwareReq :1;
-			unsigned char PublishFirmwareConf :1;
-
-			unsigned char ResetReq :1; //bit 4,
-			unsigned char ResetConf :1;	//bit 5,
-			unsigned char SendLocalListReq :1;	//bit 6,
-			unsigned char SendLocalListConf :1;	//bit 7,
-			unsigned char SetChargingProfileReq :1;	//bit 6,
-			unsigned char SetChargingProfileConf :1;	//bit 7,
-			unsigned char SetDisplayMessageReq :1;
-			unsigned char SetDisplayMessageConf :1;
-
-			unsigned char SetMonitoringBaseReq :1;
-			unsigned char SetMonitoringBaseConf :1;
-			unsigned char SetMonitoringLevelReq :1;
-			unsigned char SetMonitoringLevelConf :1;
-			unsigned char SetNetworkProfileReq :1;
-			unsigned char SetNetworkProfileConf :1;
-			unsigned char SetVariableMonitoringReq :1;
-			unsigned char SetVariableMonitoringConf :1;
-
-			unsigned char SetVariablesReq :1;
-			unsigned char SetVariablesConf :1;
-			unsigned char UnpublishFirmwareReq :1;
-			unsigned char UnpublishFirmwareConf :1;
-			unsigned char UpdateFirmwareReq :1;
-			unsigned char UpdateFirmwareConf :1;
-            unsigned char isRemoteStartWaitReq :1;
-            unsigned char :1;
-		} bits;
-	} MsMsg;
-
-	union
-	{
-		//Operations triggered by CSU
-		unsigned char CSUMsgValue[CONNECTOR_QUANTITY];
-		struct
-		{
-			//CSUMsgValue[0]
-            unsigned char ChargingProfileReq:1;	            //bit 0
-            unsigned char ChargingProfileConf:1;	        //bit 1
-            unsigned char ClearedChargingLimitReq :1;       //bit 2
-            unsigned char ClearedChargingLimitConf :1;      //bit 3
-            unsigned char NotifyEVChargingNeedsReq :1;      //bit 4
-            unsigned char NotifyEVChargingNeedsConf :1;     //bit 5
-            unsigned char NotifyEVChargingScheduleReq:1;    //bit 6
-            unsigned char NotifyEVChargingScheduleConf:1;   //bit 7
-		} bits[CONNECTOR_QUANTITY];
-	}CSUMsg;
-
-	struct Authorize_20 						Authorize;
-	struct BootNotification_20 					BootNotification;
-	struct CancelReservation_20					CancelReservation[CONNECTOR_QUANTITY];
-	struct CertificateSigned_20					CertificateSigned;
-	struct ChangeAvailability_20				ChangeAvailability[CONNECTOR_QUANTITY];
-	struct ClearCache_20						ClearCache;
-	struct ClearChargingProfile_20				ClearChargingProfile[CONNECTOR_QUANTITY];
-	struct ClearDisplayMessage_20				ClearDisplayMessage;
-	struct ClearedChargingLimit_20				ClearedChargingLimit[CONNECTOR_QUANTITY];
-	struct ClearVariableMonitoring_20			ClearVariableMonitoring;
-	struct CostUpdated_20						CostUpdated;
-	struct CustomerInformation_20				CustomerInformation;
-	struct DataTransfer_20						DataTransfer[CONNECTOR_QUANTITY];
-	struct DeleteCertificate_20					DeleteCertificate;
-	struct FirmwareStatusNotification_20		FirmwareStatusNotification;
-	struct Get15118EVCertificate_20				Get15118EVCertificate;
-	struct GetBaseReport_20						GetBaseReport;
-	struct GetCertificateStatus_20				GetCertificateStatus;
-	struct GetChargingProfiles_20				GetChargingProfiles[CONNECTOR_QUANTITY];
-	struct GetCompositeSchedule_20				GetCompositeSchedule[CONNECTOR_QUANTITY];
-	struct GetDisplayMessages_20				GetDisplayMessages;
-	struct GetInstalledCertificateIds_20		GetInstalledCertificateIds;
-	struct GetLocalListVersion_20				GetLocalListVersion;
-	struct GetLog_20							GetLog;
-	struct GetMonitoringReport_20				GetMonitoringReport;
-	struct GetReport_20							GetReport;
-	struct GetTransactionStatus_20				GetTransactionStatus[CONNECTOR_QUANTITY];
-	struct GetVariables_20						GetVariables;
-	struct Heartbeat_20							Heartbeat;
-	struct InstallCertificate_20				InstallCertificate;
-	struct LogStatusNotification_20				LogStatusNotification;
-	struct MeterValues_20						MeterValues[CONNECTOR_QUANTITY];
-	struct NotifyChargingLimit_20				NotifyChargingLimit[CONNECTOR_QUANTITY];
-	struct NotifyCustomerInformation_20			NotifyCustomerInformation;
-	struct NotifyDisplayMessages_20				NotifyDisplayMessages;
-	struct NotifyEVChargingNeeds_20				NotifyEVChargingNeeds[CONNECTOR_QUANTITY];
-	struct NotifyEVChargingSchedule_20			NotifyEVChargingSchedule[CONNECTOR_QUANTITY];
-	struct NotifyEvent_20						NotifyEvent;
-	struct NotifyMonitoringReport_20			NotifyMonitoringReport;
-	struct NotifyReport_20						NotifyReport;
-	struct PublishFirmware_20					PublishFirmware;
-	struct PublishFirmwareStatusNotification_20	PublishFirmwareStatusNotificatio;
-	struct ReportChargingProfiles_20			ReportChargingProfiles[CONNECTOR_QUANTITY];
-	struct RequestStartTransaction_20			RequestStartTransaction[CONNECTOR_QUANTITY];
-	struct RequestStopTransaction_20			RequestStopTransaction[CONNECTOR_QUANTITY];
-	struct ReservationStatusUpdate_20			ReservationStatusUpdate[CONNECTOR_QUANTITY];
-	struct ReserveNow_20						ReserveNow[CONNECTOR_QUANTITY];
-	struct Reset_20								Reset;
-	struct SecurityEventNotification_20			SecurityEventNotification;
-	struct SendLocalList_20						SendLocalList;
-	struct SetChargingProfile_20				SetChargingProfile[CONNECTOR_QUANTITY];
-	struct SetDisplayMessage_20					SetDisplayMessage;
-	struct SetMonitoringBase_20					SetMonitoringBase;
-	struct SetMonitoringLevel_20				SetMonitoringLevel;
-	struct SetNetworkProfile_20					SetNetworkProfile;
-	struct SetVariableMonitoring_20				SetVariableMonitoring;
-	struct SetVariables_20						SetVariables;
-	struct SignCertificate_20					SignCertificate;
-	struct StatusNotification_20				StatusNotification[CONNECTOR_QUANTITY];
-	struct TransactionEvent_20					TransactionEvent[CONNECTOR_QUANTITY];
-	struct TriggerMessage_20					TriggerMessage;
-	struct UnlockConnector_20					UnlockConnector[CONNECTOR_QUANTITY];
-	struct UnpublishFirmware_20					UnpublishFirmware;
-	struct UpdateFirmware_20					UpdateFirmware;
-	struct ChargingProfileType                  SmartChargingProfile[CONNECTOR_QUANTITY];
-	struct ChargingProfileType                  MaxChargingProfile;
-	struct StructSessionTarget                  SessionTarget[CONNECTOR_QUANTITY];
-};
-
-
-
-
-
-
-//------------------------------------------------------------------------------
-char *GetCurrency(uint8_t index);
-char *GetFaultStatusCode(uint8_t index);
-char *GetAlarmStatusCode(uint8_t index);
-char *GetInfoStatusCode(uint16_t index);
-#endif // DEFINE_H_
+#ifndef	DEFINE_H_
+#define	DEFINE_H_
+
+/**************************************************************************************/
+/*********************************NAND Flash mapping *****************************/
+/**************************************************************************************/
+/*
+  sector size	512 KiB
+  Page size       4096 b
+  OOB size        224 b
+  Erase size    	524288 b
+-------------------------------------------------------------------------------------------------------------------------------
+Segment 					Physical address 			Size
+-------------------------------------------------------------------------------------------------------------------------------
+MLO								0x00000000-0x0007FFFF		512 KB
+Primary u-boot 					0x00080000-0x0017FFFF		1 MB
+Environment 					0x00180000-0x001FFFFF		512 KB
+Secondary u-boot	 			0x00200000-0x002FFFFF		1 MB
+Primary dtb						0x00300000-0x0037FFFF		512 KB
+Secondary dtb					0x00380000-0x003FFFFF		512 KB
+Primary kernel					0x00400000-0x00DFFFFF		10 MB
+Secondary Kernel 				0x00E00000-0x017FFFFF		10 MB
+Primary root file system		0x03000000-0x05FFFFFF		48 MB
+Secondary root file system		0x06000000-0x08FFFFFF		48 MB
+Primary user configuration 		0x09000000-0x095FFFFF		6 MB
+Secondary user configuration	0x09600000-0x09BFFFFF		6 MB
+Factory default configuration	0x09C00000-0x0A1FFFFF		6 MB
+Storage							0x0A200000-0x7FFFFFFF		1886 MB
+*/
+
+/**************************************************************************************/
+/*********************************System Limitation**********************************/
+/**************************************************************************************/
+/*Rating outout power and current*/
+#define RATED_POWER			25		//kW
+#define RATED_CURRENT			350		//Amp, it depend on the capacity of charging connector
+
+/*relevant to Quantity */
+#ifdef AWRegular
+    #define MAX_PSU_QUANTITY        62
+    #define CHAdeMO_QUANTITY        1
+    #define CCS_QUANTITY            1
+    #define GB_QUANTITY             0
+    #define AC_QUANTITY             1
+    #define GENERAL_GUN_QUANTITY    0
+    #define PSU_QUANTITY            0
+    #define ONE_CONNECTOR_USE       0
+#elif defined AWChargeLab
+    #define MAX_PSU_QUANTITY        62
+    #define CHAdeMO_QUANTITY        1
+    #define CCS_QUANTITY            1
+    #define GB_QUANTITY             0
+    #define AC_QUANTITY             1
+    #define GENERAL_GUN_QUANTITY    0
+    #define PSU_QUANTITY            0
+    #define ONE_CONNECTOR_USE       0
+#elif defined AWCCS
+    #define MAX_PSU_QUANTITY        62
+    #define CHAdeMO_QUANTITY        1
+    #define CCS_QUANTITY            1
+    #define GB_QUANTITY             0
+    #define AC_QUANTITY             1
+    #define GENERAL_GUN_QUANTITY    0
+    #define PSU_QUANTITY            0
+    #define ONE_CONNECTOR_USE       0
+#elif defined NoodoeAX
+    #define MAX_PSU_QUANTITY        62
+    #define CHAdeMO_QUANTITY        1
+    #define CCS_QUANTITY            1
+    #define GB_QUANTITY             0
+    #define AC_QUANTITY             1
+    #define GENERAL_GUN_QUANTITY    0
+    #define PSU_QUANTITY            0
+    #define ONE_CONNECTOR_USE       0
+#elif defined AX80
+    #define MAX_PSU_QUANTITY        62
+    #define CHAdeMO_QUANTITY        1
+    #define CCS_QUANTITY            1
+    #define GB_QUANTITY             0
+    #define AC_QUANTITY             3
+    #define GENERAL_GUN_QUANTITY    3
+    #define PSU_QUANTITY            0
+    #define ONE_CONNECTOR_USE       0
+#elif defined DW30
+	#define MAX_PSU_QUANTITY        62
+	#define CHAdeMO_QUANTITY        0
+	#define CCS_QUANTITY            1
+	#define GB_QUANTITY             0
+	#define AC_QUANTITY             0
+    #define GENERAL_GUN_QUANTITY	0
+	#define PSU_QUANTITY            2
+	#define ONE_CONNECTOR_USE       0
+#elif defined DM30
+	#define MAX_PSU_QUANTITY        62
+	#define CHAdeMO_QUANTITY        0
+	#define CCS_QUANTITY            1
+	#define GB_QUANTITY             0
+	#define AC_QUANTITY             0
+    #define GENERAL_GUN_QUANTITY	0
+	#define PSU_QUANTITY            2
+	#define ONE_CONNECTOR_USE       0
+#elif defined DS60120
+	#define MAX_PSU_QUANTITY        62
+	#define CHAdeMO_QUANTITY        2
+	#define CCS_QUANTITY            2
+	#define GB_QUANTITY             2
+	#define AC_QUANTITY             1
+    #define GENERAL_GUN_QUANTITY	0
+	#define PSU_QUANTITY            2
+	#define ONE_CONNECTOR_USE       0
+#elif defined DS60210
+	#define MAX_PSU_QUANTITY        62
+	#define CHAdeMO_QUANTITY        1
+	#define CCS_QUANTITY            1
+	#define GB_QUANTITY             0
+	#define AC_QUANTITY             0
+    #define GENERAL_GUN_QUANTITY	0
+	#define PSU_QUANTITY            2
+	#define ONE_CONNECTOR_USE       0
+#elif defined PlugIt360
+    #define MAX_PSU_QUANTITY        62
+    #define CHAdeMO_QUANTITY        0
+    #define CCS_QUANTITY            1
+    #define GB_QUANTITY             0
+    #define AC_QUANTITY             0
+    #define GENERAL_GUN_QUANTITY	0
+    #define PSU_QUANTITY            2
+    #define ONE_CONNECTOR_USE       0
+#elif defined DD360 || defined DD360Audi || defined DD360ComBox || defined DD360UCar || defined DD360Tcci
+    #define MAX_PSU_QUANTITY        62
+    #define CHAdeMO_QUANTITY        2
+    #define CCS_QUANTITY            2
+    #define GB_QUANTITY             2
+    #define AC_QUANTITY             0
+    #define GENERAL_GUN_QUANTITY	0
+    #define PSU_QUANTITY            2
+    #define ONE_CONNECTOR_USE       0
+#elif defined DO360
+    #define MAX_PSU_QUANTITY        62
+    #define CHAdeMO_QUANTITY        0
+    #define CCS_QUANTITY            0
+    #define GB_QUANTITY             0
+    #define AC_QUANTITY             0
+    #define GENERAL_GUN_QUANTITY    4
+    #define PSU_QUANTITY            6
+    #define ONE_CONNECTOR_USE       0
+#elif defined ATE
+    #define MAX_PSU_QUANTITY        62
+    #define CHAdeMO_QUANTITY        0
+    #define CCS_QUANTITY            1
+    #define GB_QUANTITY             0
+    #define AC_QUANTITY             0
+    #define GENERAL_GUN_QUANTITY	0
+    #define PSU_QUANTITY            2
+    #define ONE_CONNECTOR_USE       0
+#elif defined Emulator
+    #define MAX_PSU_QUANTITY        62
+    #define CHAdeMO_QUANTITY        2
+    #define CCS_QUANTITY            2
+    #define GB_QUANTITY             2
+    #define AC_QUANTITY             2
+    #define GENERAL_GUN_QUANTITY    0
+    #define PSU_QUANTITY            2
+    #define ONE_CONNECTOR_USE       0
+#else
+    #define MAX_PSU_QUANTITY        62
+    #define CHAdeMO_QUANTITY        2
+    #define CCS_QUANTITY            2
+    #define GB_QUANTITY             2
+    #define AC_QUANTITY             1
+    #define GENERAL_GUN_QUANTITY    0
+    #define PSU_QUANTITY            2
+    #define ONE_CONNECTOR_USE       0
+#endif
+
+#define CONNECTOR_QUANTITY			(CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY + AC_QUANTITY + GENERAL_GUN_QUANTITY)
+
+/*SystemLog message*/
+#define SystemLogMessage			//for debug info save to log file
+//#define ConsloePrintLog				//for debug info print to console
+
+/**************************************************************************************/
+/*****************************share memory key information*****************************/
+/**************************************************************************************/
+#define ShmSysConfigAndInfoKey	1001
+#define ShmPsuKey				1002
+#define ShmCHAdeMOCommKey		1003
+#define ShmCcsCommKey			1004
+#define ShmStatusCodeKey		1005
+#define ShmPrimaryMcuKey		1006
+#define ShmFanBdKey				1007
+#define ShmRelayBdKey			1008
+#define ShmOcppModuleKey		1009
+#define ShmGBTCommKey			1010
+#define ShmLedBdKey				1011
+#define ShmOcpp20ModuleKey		1012
+#define ShmRelay2BdKey			1013
+#define ShmYesCustomKey         1014
+#define ShmOcppPHModuleKey      1015
+#define ShmSmartBoxKey          1016
+
+#define FaultCodeLength         5
+#define AlarmCodeLength         20
+#define InfoCodeLength          41
+
+/**************************************************************************************/
+/****************** Share memory configuration value constant define ******************/
+/**************************************************************************************/
+struct NoneUse
+{
+    unsigned char       unknown;                    // None use struct
+};
+
+enum SYSTEM_STATUS
+{
+	SYS_MODE_BOOTING		= 0,
+	SYS_MODE_IDLE    	  	= 1,
+	SYS_MODE_AUTHORIZING		= 2,
+	SYS_MODE_MODE_REASSIGN_CHECK	= 3,
+	SYS_MODE_REASSIGN		= 4,
+	SYS_MODE_PREPARING		= 5,
+	SYS_MODE_PREPARE_FOR_EV		= 6,
+	SYS_MODE_PREPARE_FOR_EVSE	= 7,
+	SYS_MODE_CHARGING		= 8,
+	SYS_MODE_TERMINATING		= 9,
+	SYS_MODE_COMPLETE		= 10,
+	SYS_MODE_ALARM			= 11,
+	SYS_MODE_FAULT			= 12,
+	SYS_MODE_RESERVATION		= 13,
+	SYS_MODE_BOOKING		= 14,
+	SYS_MODE_MAINTAIN		= 15,
+	SYS_MODE_DEBUG			= 16,
+	SYS_MODE_CCS_PRECHARGE_STEP0	= 17,
+	SYS_MODE_CCS_PRECHARGE_STEP1	= 18,
+	SYS_MODE_UPDATE			= 19
+};
+
+enum AUTHORIZATION_MODE
+{
+	AUTH_MODE_ENABLE		= 0,
+	AUTH_MODE_DISABLE		= 1
+};
+
+enum LCD_LANGUAGE
+{
+	LCD_LANG_ENGLISH		= 0,
+	LCD_LANG_CHT			= 1,
+	LCD_LANG_CHS			= 2,
+	LCD_LANG_JAPANESE		= 3,
+	LCD_LANG_FRENCH			= 4,
+	LCD_LANG_ITALIAN		= 5,
+	LCD_LANG_SPANISH		= 6,
+	LCD_LANG_GERMAN			= 7,
+	LCD_LANG_DUTCH			= 8,
+	LCD_LANG_NORWEGIAN		= 9,
+	LCD_LANG_FINNISH		= 10,
+	LCD_LANG_SWEDISH		= 11,
+	LCD_LANG_SLOVENIAN		= 12,
+	LCD_LANG_THAI			= 13,
+};
+
+
+enum RFID_ENDIAN
+{
+	RFID_ENDIAN_LITTLE		= 0,
+	RFID_ENDIAN_BIG			= 1
+};
+
+enum PHASE_LOSS_POLICY
+{
+	LOSS_POLICY_CHARGING		= 0,
+	LOSS_POLICY_STOP		= 1
+};
+
+enum CCS_AUTHPRIZATION_MODE
+{
+	CCS_AUTH_MODE_EIM		= 0,
+	CCS_AUTH_MODE_MIXED		= 1
+};
+
+enum OFF_LINE_POLICY
+{
+	OFF_POLICY_LOCALLIST		= 0,
+	OFF_POLICY_PH_RFID		= 1,
+	OFF_POLICY_FREE			= 2,
+	OFF_POLICY_NOCHARGE		= 3
+};
+
+/*Configuration enum*/
+enum CoreProfile {
+	 AllowOfflineTxForUnknownId=0,
+	 AuthorizationCacheEnabled,
+	 AuthorizeRemoteTxRequests,
+	 BlinkRepeat,
+	 ClockAlignedDataInterval,
+	 ConnectionTimeOut,
+	 GetConfigurationMaxKeys,
+	 HeartbeatInterval,
+	 LightIntensity,
+	 LocalAuthorizeOffline,
+	 LocalPreAuthorize,
+	 MaxEnergyOnInvalidId,
+	 MeterValuesAlignedData,
+	 MeterValuesAlignedDataMaxLength,
+	 MeterValuesSampledData,
+	 MeterValuesSampledDataMaxLength,
+	 MeterValueSampleInterval,
+	 MinimumStatusDuration,
+	 NumberOfConnectors,
+	 ResetRetries,
+	 ConnectorPhaseRotation,
+	 ConnectorPhaseRotationMaxLength,
+	 StopTransactionOnEVSideDisconnect,
+	 StopTransactionOnInvalidId,
+	 StopTxnAlignedData,
+	 StopTxnAlignedDataMaxLength,
+	 StopTxnSampledData,
+	 StopTxnSampledDataMaxLength,
+	 SupportedFeatureProfiles,
+	 SupportedFeatureProfilesMaxLength,
+	 TransactionMessageAttempts,
+	 TransactionMessageRetryInterval,
+	 UnlockConnectorOnEVSideDisconnect,
+	 WebSocketPingInterval,
+	 QueueOffLineMeterValues,
+	 AuthorizationKey,
+	 SecurityProfile,
+     DefaultPrice,
+     CustomDisplayCostAndPrice,
+     CustomIdleFeeAfterStop,
+     TimeOffset,
+     NextTimeOffsetTransitionDateTime,
+     TimeOffsetNextTransition,
+     SystemUptimeSec,
+     FreeVend,
+     FreeVendIdtag,
+     OcppServer,
+     MaintainServer,
+     StatusNotificationPeriodically,
+     StatusNotificationInterval,
+     PreAuthAmount,
+     isEnableLocalPowerSharing,
+     PowerSharingServerIP,
+     EVCCID_PREFIX,
+     OffLineMaxChargingPower,
+     ConfigurationVersion,
+	 CharingProfileRefreshInterval,
+	 CpoName,
+	 OcppSoftwareVersion,
+	 _CoreProfile_CNT
+};
+
+enum OCPP_RUNNING_VERSION {
+    OCPP_RUNNING_VERSION_16=0,
+    OCPP_RUNNING_VERSION_20
+};
+
+enum OCPP_START_ID_TYPE {
+    IdTokenType_Central=0,
+    IdTokenType_eMAID,
+    IdTokenType_ISO14443,
+    IdTokenType_ISO15693,
+    IdTokenType_KeyCode,
+    IdTokenType_Local,
+    IdTokenType_MacAddress,
+    IdTokenType_NoAuthorization
+};
+/**************************************************************************************/
+/****structure SysConfigData => shall store the data to NAND flash****************/
+/****structure SysInfoData => shall NOT store the data to NAND flash***************/
+/****according to System Configuration and Information Table.xlsx Rev.0.2 *******/
+/**************************************************************************************/
+
+struct EthConfigData
+{
+	unsigned char		EthDhcpClient;				//0: enable,1: disable
+	unsigned char		EthMacAddress[18];			//default: Null
+	unsigned char		EthIpAddress[16];			//Eth0 default:192.168.0.10	,Eth1 default:192.168.1.10
+	unsigned char		EthSubmaskAddress[16];		//Eth0 default:255.255.255.0	,Eth1 default:255.255.255.0
+	unsigned char		EthGatewayAddress[16];		//Eth0 default:192.168.0.254	,Eth1 default:192.168.1.254
+};
+
+struct WifiConfigData
+{
+	unsigned char		WifiMode;					//0: disable, 1: Infrastructure client, 2: Infrastructure server, 3: Ad-Hoc
+	unsigned char		WifiSsid[256];				//default: Null
+    unsigned char       WifiPassword[224];          //default: Null
+    unsigned char       WifiBroadcastSsid;          //the SSID broadcast configuration, 0: hidden   1: broadcast
+    unsigned char       WifiTargetBssidMac[31];     //Target connect SSID MAC address, default: Null
+	int					WifiRssi;					//dbm
+	unsigned char		WifiDhcpServer;				//0: enable, 1: disable
+	unsigned char		WifiDhcpClient;				//0: enable, 1: disable
+	unsigned char		WifiMacAddress[18];			//default: Null
+	unsigned char		WifiIpAddress[16];			//default:192.168.2.10
+	unsigned char		WifiSubmaskAddress[16];		//default:255.255.255.0
+	unsigned char		WifiGatewayAddress[16];		//default:192.168.2.254
+	unsigned char		WifiNetworkConn;			//0: disconnected, 1: connected
+};
+
+struct TeleConfigData
+{
+	unsigned char		TelcomModelName[64];		//default: Null
+	unsigned char		TelcomSoftwareVer[64];		//default: Null
+    unsigned char       TelcomApn[255];             //default: Null
+    unsigned char       TelcomNetworkType;          //0: Auto   1: CDMA  2: WCDMA  3: LTE  4: TD-SCDMA  5: UMTS  6: CDMA  7: HDR  8: CDMA/HDR
+	int					TelcomRssi;					//dbm
+	unsigned char		TelcomChapPapId[256];		//default: Null
+	unsigned char		TelcomChapPapPwd[256];		//default: Null
+	unsigned char		TelcomModemImei[16];		//default: Null
+	unsigned char		TelcomSimImsi[16];			//default: Null
+	unsigned char		TelcomSimIccid[22];			//default: Null
+	unsigned char		TelcomSimStatus;			//0: no SIM card is found, 1: valid SIM card, 2: invalid SIM card
+	unsigned char       TelcomModemMode;            //0: No services, 1: CDMA, 2: GSM/GPRS, 3: WCDMA, 4: GSM/WCDMA, 5: TD_SCDMA, 6: HSPA, 7: LTE 9: Unknown
+	unsigned char		TelcomIpAddress[16];		//default: Null
+	unsigned char		TelcomNetworkConn;			//0: disconnected, 1: connected
+	unsigned char		TelcomEnabled;				//0: disable, 1: enable
+};
+
+struct BtConfigData
+{
+	unsigned char		LoginCentralID[64];			//default: Null
+	unsigned char		isLogin;					//0: Central device non-login	1: Central device login
+	unsigned char		isRequestStart;				//0: no action	1: request start charging
+	unsigned char		isRequestStop;				//0: no action	1: request stop charging
+};
+
+struct BillingConfigData
+{
+	unsigned char		isBilling;					//0:not for business	1:for business
+	unsigned char		Currency;					//
+	float				Fee[24];					//fee for 24 hours
+	float 				Cur_fee;					// display current fee
+};
+
+struct LED
+{
+	unsigned char 			Intensity;					// LED bar intensity	0: Darkest	1: Medium	2: Brightest
+
+	unsigned char			Red[3];						// Red color	0~100, element 0: IDLE		1: CHARGING		2: FAULT
+	unsigned char			Green[3];					// Green color	0~100, element 0: IDLE		1: CHARGING		2: FAULT
+	unsigned char			Blue[3];					// Blue color	0~100, element 0: IDLE		1: CHARGING		2: FAULT
+};
+
+struct LCD_NOUSE
+{
+    unsigned char           page_index;                 // LCD override page index
+    unsigned char           duration;                   // LCD override duration
+    unsigned char           isOverideReq:1;             // LCD override request
+};
+
+struct LCD_OVERRIDE
+{
+    unsigned char           connectorId;                // LCD override connector id
+    unsigned char           page_index;                 // LCD override page index
+    unsigned char           duration;                   // LCD override duration
+    unsigned char           isOverideReq:1;             // LCD override request
+};
+
+struct Schedule
+{
+	unsigned char   isEnable;     						// 0: disable schedule function  1: enable schedule function
+	unsigned char   scheduleType;    					// 0: Once   1: Daily
+	unsigned char   scheduleMethod;    					// 0: Continuous 1: Specificate end time
+	unsigned char   startTimeHour;    					// Schedule start trigger time hour
+	unsigned char   startTimeMinute;   					// Schedule start trigger time minute
+	unsigned char   stopTimeHour;    					// Schedule stop trigger time hour
+	unsigned char   stopTimeMinute;    					// Schedule stop trigger time minute
+	unsigned char   isTriggerStart;    					// 0: disable; 1: enable
+	unsigned char   isTriggerStop;    					// 0: disable; 1: enable
+};
+
+struct TTIA
+{
+    unsigned char   server_addr[512];                   // Target server address
+    unsigned int    server_port;                        // Target server port
+    unsigned int    busVenderId;                        // Bus vender id, 0~65535
+    unsigned char   EquipmentProvider[16];              // EVSE vender max 15 bytes
+    unsigned char   TransportationCompanyNo;            // Data provider company number
+    unsigned char   ChargeBoxId;                        // 1 byte
+    unsigned char   evseStation[16];                    // UTF-8 15 bytes, Chinese 5 words
+    unsigned char   isEnableTTIA:1;                     // TTIA function enable
+};
+
+struct LocalSharingInfo
+{
+    unsigned short      AvailableShargingCurrent[4];    // 0 ~ rating value amp,  Synchronize from local sharing server
+    unsigned char       isConnectedSharingServer:1;     // 0: Disconnected, 1: Connected
+};
+
+typedef union
+{
+    unsigned int ChargingStopValue;
+    struct
+    {
+        unsigned int NormalStop:1;                  // 0: no effect,    1: normal stop
+        unsigned int AlarmStop:1;                   // 0: no effect,    1: alarm stop
+        unsigned int BackendStop:1;                 // 0: no effect,    1: backend stop
+        unsigned int ManualStop:1;                  // 0: no effect,    1: manual stop
+        unsigned int HardResetStop:1;               // 0: no effect,    1: hard reset stop
+        unsigned int SoftResetStop:1;               // 0: no effect,    1: soft reset stop
+        unsigned int InvalidIdStop:1;               // 0: no effect,    1: invalid stop when StopTransactionOnInvalidId is true
+        unsigned int RemoteStop:1;                  // 0: no effect,    1: remote stop
+        unsigned int UnlockStop:1;                  // 0: no effect,    1: unlock stop
+        unsigned int SessionTargetStop:1;           // 0: no effect,    1: session target stop
+        unsigned int res:22;
+    }bits;
+}ChargingStop;
+
+typedef struct
+{
+    unsigned char DispenserSequence;                    // dispenser sequence
+    unsigned char MaxConnectorQuantity;                 // max connector quantity
+    unsigned char WiringSetting[8];                     // record connector quantity of dispenser
+    unsigned char PowerCabinetReserved[32];
+}WiringInfoData;
+
+typedef struct
+{
+    unsigned int isCalibratedVaGain:1;                  // Voltage phase a gain is calibrated, 0: default   1: Calibrated
+    unsigned int isCalibratedVbGain:1;                  // Voltage phase b gain is calibrated, 0: default   1: Calibrated
+    unsigned int isCalibratedVcGain:1;                  // Voltage phase c gain is calibrated, 0: default   1: Calibrated
+    unsigned int isCalibratedVaOffset:1;                // Voltage phase a offset is calibrated, 0: default 1: Calibrated
+    unsigned int isCalibratedVbOffset:1;                // Voltage phase b offset is calibrated, 0: default 1: Calibrated
+    unsigned int isCalibratedVcOffset:1;                // Voltage phase c offset is calibrated, 0: default 1: Calibrated
+    unsigned int isCalibratedCaGain:1;                  // Current phase a gain is calibrated, 0: default   1: Calibrated
+    unsigned int isCalibratedCbGain:1;                  // Current phase b gain is calibrated, 0: default   1: Calibrated
+    unsigned int isCalibratedCcGain:1;                  // Current phase c gain is calibrated, 0: default   1: Calibrated
+    unsigned int isCalibratedCaOffset:1;                // Current phase a offset is calibrated, 0: default 1: Calibrated
+    unsigned int isCalibratedCbOffset:1;                // Current phase b offset is calibrated, 0: default 1: Calibrated
+    unsigned int isCalibratedCcOffset:1;                // Current phase c offset is calibrated, 0: default 1: Calibrated
+    unsigned int isCalibratedPa:1;                      // Phase angle a is calibrated, 0: default          1: Calibrated
+    unsigned int isCalibratedPb:1;                      // Phase angle b gain is calibrated, 0: default     1: Calibrated
+    unsigned int isCalibratedPc:1;                      // Phase angle c gain is calibrated, 0: default     1: Calibrated
+    unsigned int :1;
+}MeterIcCalibration;
+
+struct SysConfigData
+{
+	/**************System***************/
+	unsigned char 			CsuBootLoadFwRev[32];			//CSU board bootloader firmware version
+	unsigned char			ModelName[64];				//charger model name
+	unsigned char			AcModelName[64];			//for third gun (DC + AC)
+	unsigned char			SerialNumber[64];			//charger system serial number
+	unsigned char			SystemId[128];				//charger system ID
+	unsigned char			SystemDateTime[32];			//charger system date and time
+	unsigned char			AcPhaseCount;				//AC EVSE power phase quantity,  1: One phase	3: Three phase
+	unsigned char			AuthorisationMode;			//0: enable, 1: disable
+	unsigned char			DefaultLanguage;			//
+	unsigned char			RfidCardNumEndian;			//0: little endian,  1: big endian
+	unsigned short			AcPlugInTimes;				//0~65535
+	unsigned short			GbPlugInTimes;				//0~65535
+	unsigned short			Ccs1PlugInTime;				//0~65535
+	unsigned short			Ccs2PlugInTimes;			//0~65535
+	unsigned short			ChademoPlugInTimes;			//0~65535
+	unsigned char			PsuAcInputType;				//0: 220, 1: 277
+	unsigned short			RatingCurrent;				//0: Depend on Model name,	1 ~ rating value amp
+	unsigned short			AcRatingCurrent;			//for third gun; 0: Depend on Model name,	1 ~ rating value amp
+	unsigned char			isAPP;						//for AuthorisationMode=0; 0:false, 1:true
+	unsigned char			isQRCode;					//for AuthorisationMode=0; 0:false, 1:true
+	unsigned char			isRFID;						//for AuthorisationMode=0; 0:false, 1:true
+	unsigned char			QRCodeMadeMode;				//for isQRCode=1 ; 0: default	1:customized
+	unsigned char			QRCodeContent[128];			//for QRCodeMadeMode=1
+	unsigned char			TotalConnectorCount;		//Connector count
+	unsigned char 			AcConnectorCount;			// For DC type
+	unsigned char			SwitchDebugFlag;			// Console Debug
+	unsigned char			AlwaysGfdFlag;
+	/**************Charging***************/
+	unsigned short			MaxChargingEnergy;			//0: no limit,	1 ~ 65535	kWh
+	unsigned short			MaxChargingPower;			//0: rating value, 1 ~ RATING_POWER	kW
+	unsigned short			MaxChargingCurrent;			//0: rating value, 1 ~ RATING_CURRENT	amp
+	unsigned short			AcMaxChargingCurrent;		//for third gun; 0: rating value, 1 ~ RATING_CURRENT	amp
+	unsigned short			MaxChargingDuration;		//0: no limit,	1 ~ 65535	minutes
+	unsigned char			PhaseLossPolicy;			//0: charging,  1: stop charging
+	unsigned char			LocalWhiteCard[10][32];		//Max. card quantity is 10
+	unsigned char			UserId[32];					//the user use this ID to trigger charging event, it can be RFID card number, OCPP IdTag, etc.
+	struct BillingConfigData BillingData;
+	/**************Network***************/
+	unsigned char 			FtpServer[256];				//the ftp server for Phihong server to do data transimission
+	struct EthConfigData	Eth0Interface;
+	struct EthConfigData	Eth1Interface;
+	struct WifiConfigData 	AthInterface;
+	struct TeleConfigData	TelecomInterface;
+	struct BtConfigData		Bluetooth;
+	/**************Backend***************/
+	unsigned int 			BackendConnTimeout;			//default : 300s
+	unsigned char   		OfflinePolicy;				//0: local list, 1: Phihong RFID tag, 2: free charging, 3: no charging
+	unsigned short	   		OfflineMaxChargeEnergy;		//0: same as MaxChargingEnergy, 1 ~ 65535 kWh
+	unsigned short	   		OfflineMaxChargeDuration;	//0: same as MaxChargeDuration, 1 ~ 65535 minutes
+	unsigned char 			OcppServerURL[512];			//ws: non-secure OCPP 1.6-J, wss: secure OCPP 1.6-J"
+	unsigned char 			ChargeBoxId[128];
+	unsigned char			chargePointVendor[20];		//the Vendor of the ChargePoint
+    unsigned char           OcppSecurityProfile;        //OCPP security profile 0~3
+    unsigned char           OcppSecurityPassword[41];   //OCPP AuthorizationKey for security profile
+	unsigned int 			Checksum;					//4 bytes checksum
+	struct LED				LedInfo;					// LED configuration info
+	unsigned char			ShowInformation;
+	unsigned char           isReqFirstUpgrade;          //EVSE is request first upgrade from PH server
+	unsigned char           isEnableLocalPowerSharing;  //0: Disable power sharing  1: Master   2: Slave
+	unsigned char           StopChargingByButton;       //0: Disable  1: Enable
+    struct LCD_NOUSE        Legacy_LcdOveride;          // LCD override info (no use anymore)
+    struct TTIA             TTIA_Info;                  // TTIA configuration struct
+
+    /************PowerCabinet************/
+    WiringInfoData          WiringInfo;
+
+    unsigned char           OcppReceiptrURL[512];               // Charging receipt display URL
+    unsigned char           isAuthrizeByEVCCID;                 // is Authorize by EVCCID (CCS)
+    unsigned char           MaintainServerURL[512];             // ws: non-secure OCPP 1.6-J, wss: secure OCPP 1.6-J"
+    unsigned char           MaintainServerSecurityProfile;      // Maintain server security profile 0~3
+    unsigned char           MaintainServerSecurityPassword[41]; // Maintain server AuthorizationKey for security profile
+    unsigned char           PowerSharingServerIP[512];          // Local power sharing server ip address
+    unsigned int            PowerSharingCapacityPower;          // Local power sharing capacity power
+    unsigned char           MaxChargingSoc;                     //0: unlimit, 1 ~ 100 percent
+};
+
+struct DERATING_BY_OTP
+{
+    unsigned char isNeedDerating;
+    unsigned char deratingIndex;        // Current used power or current
+    double deratingTargetRate[5];       // Reduce the output energy rate
+    double deratingTargetCurrent[5];    // derating target current
+};
+
+struct ChargingInfoData
+{
+	unsigned char 		Index;
+	unsigned char 		slotsIndex;
+	unsigned char 		Type;					// 0 : Chademo, 1 : CCS, 2: GB
+	unsigned char 		type_index;
+	unsigned char 		Evboard_id;				// for EV board
+	unsigned char 		StopChargeFlag;			// for EV board
+	unsigned char		SystemStatus;				//0: Booting, 1: idle, 2: authorizing, 3: preparing, 4: charging, 5: terminating, 6: alarm, 7: fault
+	unsigned char		PreviousSystemStatus;		// 0: Booting, 1: idle, 2: authorizing, 3: preparing, 4: charging, 5: terminating, 6: alarm, 7: fault	
+	int 			ReservationId;
+	unsigned char 		IsAvailable;
+	float MaximumChargingVoltage;	// unit 0.1V
+	float AvailableChargingCurrent;	// unit 0.1A
+	float AvailableChargingPower;	// unit 0.1kW
+	float DividChargingCurrent;		//0~6553.5 amp
+	float DeratingChargingCurrent;  // unit 0.1A
+	float DeratingChargingPower;	// unit 0.1kW
+	float FuseChargingVoltage;		//0~6553.5 volt
+	float FireChargingVoltage;		//0~6553.5 volt
+	float PresentChargingVoltage;   // unit: 1V
+	float PresentChargingCurrent;   // unit: 1A
+	float PresentChargingPower;		//0~6553.5 kW
+	float PresentChargedEnergy;		//0~6553.5 kWh
+	float presentChargedEnergyPeriod[24];       // Session present charged energy at each period
+	int PresentChargedDuration;	// second
+	int RemainChargingDuration;	// second
+	float EvBatteryMaxVoltage;		// 0~6553.5 volt
+	float EvBatterytargetVoltage;		// 0~6553.5 volt
+	float EvBatterytargetCurrent; 	//102.3				0~200(A) (unit:1A)
+	int EvBatterySoc;				// 0~100%
+	unsigned char ConnectorPlugIn;			//0: unplug, 1: Plug-in
+	unsigned char GunLocked;				//0: unlocked 1: locked
+	unsigned char InProgress;               //0: real idle, 1: session(transaction) in progress
+	float PilotVoltage;
+	unsigned char PilotState;//1:state A, 2:State B1, 3:State B2, 4:State C, 5:State D, 6:State E, 7:State F, 8: Pilot error
+	unsigned char PilotDuty;					// 0~100%
+	unsigned char			StartUserId[32];			// This ID is trigger start charging event user by RFID, back-end, BLE.
+	unsigned char           StartIdType;                // 0: Central   1: eMAID    2: ISO14443 3: ISO15693 4: KeyCode  5: Local    6: MacAddress   7: NoAuthorization
+	unsigned char			StartDateTime[32];			// Charging cycle start date time
+	unsigned char			StopDateTime[32];			// Charging cycle stop date time
+	unsigned char			StartMethod;
+	float					ChargingFee;
+	// Connector Temp
+	unsigned char 		ConnectorTemp;			//0x00: -60¢XC  ~  0xFE: 194
+    //Chiller Temp
+    unsigned char       ChillerTemp;            //0x00: -60¢XC  ~  0xFE: 194
+	// Charging Status
+	unsigned char 		GroundFaultStatus;		// for GFD result => 0x00 : None, 0x01 : Can Start Charging, 0x02 : Stop Charging
+	unsigned short		RealRatingPower;        // unit: 0.1kW
+	unsigned char 		RelayWeldingCheck;		// 0 : No Comp., 1 : Comp.
+	unsigned char 		PrechargeStatus;		// for ccs precharge => 0x00 : None defined, 0x01 : Accepted
+	float 				PowerConsumption;		// This contains the meter value (Power Consumption) kWh
+	unsigned char		RelayK1K2Status;		// 0x00 : open, 0x01 : close
+	unsigned char		RelayKPK2Status;		// 0x00 : open, 0x01 : close
+	unsigned char 	 	TimeoutFlag;			// 0 : none,
+	struct timeval		TimeoutTimer;
+	unsigned char 		MaxChargeEnable;
+	unsigned char		IsReadyToCharging;
+	unsigned char		CcsAuthentication;				// 0:EIM, 1:EIM & PnC mixed
+	unsigned char		AcCcsChargingMode;				// 0:BC (PWM) only, 1:BC & PLC mixed
+	unsigned short		SampleChargingCur[10];
+
+	/************** Alston ***************/
+	unsigned char 		SelfTest_Comp;
+	unsigned char		version[16];
+	unsigned char 		IsModeChagned;
+	unsigned char 		IsCharging;
+	unsigned char 		IsErrorOccur;
+	float 				RealMaxVoltage;
+	float				RealMaxCurrent;
+	float 				RealMaxPower;
+	unsigned char 		ConnectorWarningCode[7];
+	unsigned char 		ConnectorAlarmCode[7];
+	unsigned char 		EvConnAlarmCode[7];
+	float 				ChargingProfileCurrent;			// unit: 0.1A
+	float 				ChargingProfilePower;			// unit: 1W
+	float               LocalPowerLimitCurrent;         // unit: 1A
+	float 				PresentChargingVoltageL2;		//0~6553.5 volt
+	float 				PresentChargingVoltageL3;		//0~6553.5 volt
+	float 				PresentChargingCurrentL2;		//0~6553.5 amp	
+	float 				PresentChargingCurrentL3;		//0~6553.5 amp
+	char 				RemoteStartFlag;
+	unsigned char 		MaxChargingToAverPassFlag;
+	unsigned char		EVCCID[18];						//the MAC address of the EVCC in Hex
+	unsigned char 		isRemoteStart;
+	struct Schedule		schedule;						// Schedule
+	int 				EvBatteryStartSoc;				// 0~100%
+	unsigned char 		NormalStopChargeFlag;			// for EV board
+	ChargingStop        ChargingStopFlag;
+    char                ReservedStartFlag;
+    float               ConnectorMaxVoltage;            // 0~6553.5 volt
+    float               ConnectorMaxCurrent;            // 0~6553.5 volt
+    unsigned char       ModelType;
+    MeterIcCalibration  meterIcCalInfo;
+    float               PowerOffered;                   //0~6553.5 kW
+    float               CurrentOffered;                 //0~6553.5 amp
+    struct timespec     ConnectorTimeout;
+    unsigned char       PantographFlag;                 // 0: normal gun type,  1: pantograph gun type
+    unsigned char       Replug_flag;
+    unsigned char       isEVCCIDVerify;
+    unsigned char       CCSGunType;
+    struct timeval      PreChargeTimer;
+    unsigned char       _SaftyDetect;
+    unsigned char       _TotalPsuCount;                 // Psu count for connector
+    unsigned char       _TakePsuGpCount;                // Get the used psu group count
+    struct DERATING_BY_OTP deratingByConnOtp;
+};
+
+typedef struct
+{
+    unsigned char       AuthId[32];
+                                                        // 0: Authorize idle, 1: Authorize wait,   2: Authorizing
+    unsigned char       AuthStatus;                     // 3: Authorize done, 4: Authorize end
+    unsigned char       AuthTarget;                     // Authorize Target Connector ID: 1 ~ 4, AutoSelection: 0xFF
+    unsigned char       AuthType;                       // 0: _AuthType_None,   1: _AuthType_RFID, 2: _AuthType_RemoteStart
+    unsigned char       AuthResult;                     // 0: _AuthResult_None, 1: _AuthResult_Valid,   2: _AuthResult_Invalid
+    unsigned char       AuthRequest;                    // 0: no request, 1: authorize request
+    unsigned char       AuthIdType;
+}AuthorizingInfoData;
+
+typedef union
+{
+    unsigned int SettingValue;
+    struct
+    {
+        unsigned int DuplicateIp:1;
+        unsigned int DuplicateIpConfirm:1;
+        unsigned int DispenserConfigSync:1;             // 0: not synced,   1: synced
+        unsigned int MiscNeedAnnouncement:1;            // 0: no need,      1: need send misc command
+        unsigned int NeedDispenserVerInfo:1;            // 0: no need,      1: need dispenser to report it's version info
+        unsigned int AuthorizeRequest:1;                // 0: idle,         1: requesting                           ( dispenser -> cabinet)
+        unsigned int HardwareRebootConfirm:1;           // 0: no effect,    1: dispenser confirmed
+        unsigned int SoftwareResetConfirm:1;            // 0: no effect,    1: dispenser confirmed
+        unsigned int FirmwareUpdateRequest:1;           // firmware update request
+        unsigned int FirmwareUpdateConfirm:1;           // firmware update start
+        unsigned int FirmwareUpdateCompleted:1;         // firmware update completed
+        unsigned int res:21;
+    }bits;
+}DispenserSettingFlag;
+
+struct DispenserModule
+{
+    unsigned char   LocalStatus;                // 0: None, 1: Identification, 2: Idle, 3: Alarm, 4: Charging, 5: _DS_Timeout
+    unsigned char   ConnectorQuantity;          //Connector count
+    unsigned char   ConnectorID[2];             //Available Connector ID: 1 ~ 4
+    unsigned char   UserId[32];                 //the user use this ID to trigger charging event, it can be RFID card number, OCPP IdTag, etc.
+    unsigned char   ModelName[64];              //charger model name
+    unsigned char   SerialNumber[64];           //charger system serial number
+    unsigned char   SystemId[128];              //charger system ID
+    unsigned char   AuthorisationMode;          //0: enable, 1: disable
+    unsigned char   RfidCardNumEndian;          //0: little endian,  1: big endian
+    unsigned char   isAPP;                      //for AuthorisationMode=0; 0:false, 1:true
+    unsigned char   isQRCode;                   //for AuthorisationMode=0; 0:false, 1:true
+    unsigned char   isRFID;                     //for AuthorisationMode=0; 0:false, 1:true; for Noodoe Credit Card +2^1:true
+    unsigned char   QRCodeMadeMode;             //for isQRCode=1 ; 0: default	1:customized
+    unsigned char   QRCodeContent[128];         //for QRCodeMadeMode=1
+
+    unsigned char   FactoryConfiguration;       //0: normal, 1: trigger, charger will return the configuration to factory default if trigger
+    unsigned char   CsuBootLoadFwRev[32];       //CSU board bootloader firmware version
+    unsigned char   CsuKernelFwRev[32];         //CSU board OS kernel firmware version
+    unsigned char   CsuRootFsFwRev[32];         //CSU board root file system firmware version
+    unsigned char   CsuPrimFwRev[32];           //CSU board root file system firmware version
+    unsigned char   LcmFwRev[32];               //LCM module firmware version
+    unsigned char   PsuPrimFwRev[32];           //PSU primary firmware version
+    unsigned char   PsuSecFwRev[32];            //PSU secondary firmware version
+    unsigned char   FanModuleFwRev[32];         //Fan  module firmware version
+    unsigned char   RelayModuleFwRev[32];       //Relay control  module firmware version
+    unsigned char   TelcomModemFwRev[32];       //the 3G/4G modem firmware version
+    unsigned char   LedModuleFwRev[32];         //LED control module firmware version
+    unsigned char   Connector1FwRev[32];        //Connector1 module firmware version
+    unsigned char   Connector2FwRev[32];        //Connector2 module firmware version
+    struct   LED    LedInfo;                    // LED configuration info
+
+    AuthorizingInfoData     AuthInfo;
+    DispenserSettingFlag    Setting;
+    char                    FwFileName[128];
+    unsigned char           ConnectionChannel;
+};
+
+struct ConnectionInfoData
+{
+    unsigned char Status;                       // 0: free, 1: WaitModelName, 2: DispenserMatched
+    unsigned char DispenserIndex;
+    unsigned int  IpAddress;
+};
+
+struct DispenserInfoData
+{
+    unsigned char               DispenserQuantity;                  // record max dispenser quantity
+    unsigned char               TotalConnectorQuantity;             // record max connector quantity
+    struct DispenserModule      Dispenser[GENERAL_GUN_QUANTITY];
+
+    unsigned char               PresentDispenserQuantity;
+    unsigned char               PresentConnectorQuantity;
+
+    union
+    {
+        unsigned char Status;
+        struct
+        {
+            unsigned char Dispenser1:1;             // 1: ever checkin, 0: never checkin
+            unsigned char Dispenser2:1;             // 1: ever checkin, 0: never checkin
+            unsigned char Dispenser3:1;             // 1: ever checkin, 0: never checkin
+            unsigned char Dispenser4:1;             // 1: ever checkin, 0: never checkin
+            unsigned char Dispenser5:1;             // 1: ever checkin, 0: never checkin
+            unsigned char Dispenser6:1;             // 1: ever checkin, 0: never checkin
+            unsigned char Dispenser7:1;             // 1: ever checkin, 0: never checkin
+            unsigned char Dispenser8:1;             // 1: ever checkin, 0: never checkin
+        }Flag;
+    }CheckInLog;                                                        // record dispenser checkin status
+    unsigned char               ConnectorLog[GENERAL_GUN_QUANTITY];     // record connector quantity of dispenser
+    struct ConnectionInfoData   ConnectionInfo[GENERAL_GUN_QUANTITY];
+};
+
+struct WARNING_CODE_INFO
+{
+    unsigned char WarningCount;
+    unsigned char PageIndex;
+    unsigned char WarningCode[10][7];
+    unsigned char Level;
+    unsigned char ExtraErrProcess;                      // 0 : none, 1 : input uvp..
+};
+
+typedef union
+{
+    unsigned int Value;
+    struct
+    {
+        unsigned int  PermissionRequest:1;              // 0: no request,    1: dispenser request to charging                   ( dispenser -> cabinet)
+        unsigned int  RemoteStartConfirm:1;
+        unsigned int  RemoteStopConfirm:1;
+        unsigned int  UnlockStopConfirm:1;
+        unsigned int  TimeoutStopRequest:1;             // 0: no request,    1: ethernet timeout stop                           ( dispenser -> cabinet)
+        unsigned int  PsuReleasable:1;
+        unsigned int  AnnounceBalance:1;                //
+        unsigned int  StartWaitPlug:1;                  //
+        unsigned int  NeedCleanAuthorizeInfo:1;         //
+        unsigned int  SwipeRfidConfirm:1;
+        unsigned int  OutputLimitEnable:1;              // 0: disable,      1: enable
+        unsigned int  ChargingPermission:2;             // 0: not allowed,  1: allowed,         2: wait
+        unsigned int  NormalStopRequest:1;              // 0: no effect,    1: connector normal stop request                    ( dispenser -> cabinet)
+        unsigned int  AlarmStopRequest:1;               // 0: no effect,    1: connector alarm stop request                     ( dispenser -> cabinet)
+        unsigned int  FaultStatusRequest:1;
+        unsigned int  Disconnection:1;
+        unsigned int  GfdDetection:1;                   // 0: stop,         1: start
+        unsigned int  GetStartChargingSoc:1;            // 0: no effect,    1: get start soc
+        unsigned int  res:13;
+    }bits;
+}ConnectorParameter;
+
+struct ConnectorInfoData
+{
+    unsigned char RemoteStatus;                         // 0: Idle, 1: Preparing, 2: Charging, 3: Terminating, 4: Alarm
+    unsigned char Enable;                               // 0: Disable, 1: Enable
+    unsigned char ReadyToCharge;                        // 0: Not Ready, 1: Ready to Charge (no use)
+    unsigned char ParentDispensetIndex;                 // Parent Dispenser Index: 0 ~ 3
+    ConnectorParameter       Parameter;
+
+    AuthorizingInfoData      AuthInfo;
+    struct ChargingInfoData  GeneralChargingData;
+    struct WARNING_CODE_INFO WarningInfo;
+
+    unsigned char           RemotenAlarmCode[7];
+    unsigned short          RemoteChargingVoltage;          // charging voltage from connector, unit: 0.1V
+    unsigned short          RemoteChargingCurrent;          // charging current from connector, unit: 0.1A
+    unsigned int            RemoteRemainChargingDuration;   // remain charging duration from connector, unit: 1s
+    unsigned char           RemoteSoc;                      // ev battery soc from connector, unit: 1%
+
+    unsigned short          RemoteMaxPhysicalVoltage;       // max physical voltage from connector, unit: 0.1V
+    unsigned short          RemoteMaxPhysicalCurrent;       // max physical current from connector, unit: 0.1A
+    unsigned short          RemoteTargetVoltage;            // target voltage from connector, unit: 0.1V
+    unsigned short          RemoteTargetCurrent;            // target current from connector, unit: 0.1A
+    unsigned short          RemoteLimitVoltage;             // limit voltage to psu voltage command, unit: 0.1V
+    unsigned short          RemoteLimitCurrent;             // limit current to psu current command, unit: 0.1A
+
+    unsigned short          MaxTotalChargingCurrent;        // max total output current, unit: 0.1A
+    unsigned short          MaxTotalChargingPower;          // max total output power, unit: 0.1kw
+    unsigned short          MaxOutputEnergy;                // 0: no limit,  1 ~ 65535   kWh
+    unsigned short          MaxOutputDuration;              // 0: no limit,  1 ~ 65535   minutes
+    float                   CapabilityVoltage;              // unit 0.1V
+    float                   CapabilityCurrent;              // unit 0.1A
+    float                   CapabilityPower;                // unit 0.1kW
+
+    float                   UserPrice;                      // connector user's user price, unit: 1 (dollar / kWh)
+    float                   TotalCost;                      // connector user's total cost, unit: 1 dollar
+    float                   AccountBalance;                 // connector user's account balance, unit: 1 dollar
+    float                   CostDiscount;                   // connector user's Discount or couponPoint, unit: 1 point
+    float                   EnergyCost;                     // connector user's energy cost, unit: 1 dollar
+    float                   ParkingFee;                     // connector user's parking fee, unit: 1 dollar
+    float                   RemainAmount;                   // connector user's remain amount, unit: 1 dollar
+};
+
+typedef union
+{
+    unsigned int SettingValue;
+    struct
+    {
+        unsigned int res:32;
+    }bits;
+}CabinetSettingFlag;
+
+struct DC_METER_INFO
+{
+    double presetVoltage;						// resolution: 1.000v
+	double presentCurrent;					// resolution: 1.000a
+	double presentPower;						// resolution: 1.000kw
+	double totlizeImportEnergy;			// resolution: 1.000kwh
+	double totlizeExportEnergy;			// resolution: 1.000kwh
+	unsigned char timestamp[32];
+	unsigned char LinkStatus;								// 0 = unknow ,1 = link , 2 miss link
+};
+
+typedef union
+{
+		unsigned char Status;
+        struct
+        {
+	    			unsigned char suLinkStatusIsOk:1;
+            unsigned char muFatalErrorOccured:1;
+            unsigned char transactionIsOnGoing:1;
+            unsigned char tamperingIsDetected:1;
+            unsigned char timeSyncStatusIsOk:1;
+            unsigned char overTemperatureIsDetected:1;
+            unsigned char reversedVoltage:1;
+            unsigned char suMeasureFailureOccurred:1;
+        }bits;
+        
+}DcmbStatusFlag;
+
+typedef union
+{
+        unsigned char Errors;
+        struct
+        {
+            unsigned char muInitIsFailed:1;
+            unsigned char suStateIsInvalid:1;
+            unsigned char versionCheckIsFailed:1;
+            unsigned char muRngInitIsFailed:1;
+            unsigned char muDataIntegrityIsFailed:1;
+            unsigned char muFwIntegrityIsFailed:1;
+            unsigned char suIntegrityIsFailed:1;
+            unsigned char logbookIntegrityIsFailed:1;
+            unsigned char logbookIsFull:1;
+            unsigned char memoryAccessIsFailed:1;
+            unsigned char muStateIsFailed:1;
+            unsigned char res:5;
+        }bits;
+        
+}DcmbErrorFlag;
+   
+struct DC_METER_STATUS_INFO
+{
+	unsigned short StatusValue;
+	DcmbStatusFlag MeterStatusFlag;
+    
+	unsigned char applicationFirmwareVersion[16];
+    unsigned char applicationFirmwareAuthTag[32];
+    unsigned char legalFirmwareVersion[16];
+    unsigned char legalFirmwareAuthTag[32];
+    unsigned char sensorFirmwareVersion[16];
+    unsigned char sensorFirmwareCrc[4];
+
+    unsigned char Systime[32];
+    unsigned char ipAddress[32];
+    unsigned char meterId[32];
+
+	unsigned short ErrorValue;
+ 	DcmbErrorFlag MeterErrorFlag;
+   
+    unsigned char publicKey[140];
+    unsigned char publicKeyOcmf[200];
+    unsigned short indexOfLastTransaction;
+    unsigned short numberOfStoredTransactions;
+};
+
+struct DC_METER_TRANSACTION_HEAD
+{
+    unsigned char evseId[32];
+    unsigned char transactionId[32];
+    unsigned char clientId[32];
+    unsigned short tariffId;
+    unsigned short cableId;
+    unsigned short userData[32];
+    
+};
+
+struct DC_METER_TRANSACTION_ACTION
+{
+	struct DC_METER_TRANSACTION_HEAD head;
+	unsigned char transactionOCMF[512];
+	unsigned char OcmfInfoReady;                // 0 = nothing, 1 = ocmp info ready
+	unsigned char ActionCmd;                   // 1 = transaction Start, 2 transaction Stop, sync time
+};
+
+typedef union
+{
+				unsigned char Status;
+        struct
+        {
+	    			unsigned char intermediateRead:1;
+            unsigned char res:7;
+        }bits;
+        
+}DcmbTransactionReadlevel;
+
+struct DC_METER_TRANSACTION_RESULT
+{
+	unsigned short paginationCounter;
+	struct DC_METER_TRANSACTION_HEAD head;
+    unsigned char timestampStart[32];
+    unsigned char timestampStop[32];
+    unsigned int transactionDuration;
+    DcmbTransactionReadlevel intermediateRead;
+    unsigned int  transactionStatus;
+    unsigned char energyUnit[8];
+    double energyImport;
+    double energyImportTotalStart;
+    double energyImportTotalStop;
+    double energyExport;
+    double energyExportTotalStart;
+    double energyExportTotalStop;
+    unsigned char signature[140];
+    //unsigned char transactionOCMF[512];
+};
+
+typedef struct Bazel8Command
+{
+    unsigned char isReq:1;
+    unsigned char isRes:1;
+    unsigned char isWaitRes:1;
+    unsigned char isResultPass:1;
+} bazel8Command;
+
+typedef struct EventInfo
+{
+    int messageId;
+    char messageString[64];
+    unsigned char isGetOn:1;
+}eventInfo;
+
+typedef struct StartTxResp
+{
+    char statusCode[8];
+    char statusText[128];
+    char txnId[32];
+    unsigned char isGetOn:1;
+}startTxResp;
+
+struct BAZEL8
+{
+    eventInfo       event;
+    startTxResp     txResp;
+
+    bazel8Command   cmdPreAuth;
+};
+
+struct Enegate
+{
+    union
+    {
+        unsigned char OperationValue[CONNECTOR_QUANTITY];
+        struct
+        {
+            unsigned char isAuthorizing:1;
+            unsigned char isAuthorized:1;
+            unsigned char isAuthorizedPass:1;
+            unsigned char isSessionStopReq:1;
+            unsigned char isStopService:1;
+            unsigned char isAutoStartEnable:1;
+            unsigned char isConnectTimeout:1;
+            unsigned char :1;
+        } bits[CONNECTOR_QUANTITY];
+    }Operation;
+
+    unsigned char   serviceStartTimestamp[36];
+    unsigned char   serviceStopTimestamp[36];
+    unsigned char   isEnable:1;
+};
+
+struct SysInfoData
+{
+	/**************System***************/
+    unsigned char OcppRunningVer;           // 0: 1.6J      1:2.0
+	unsigned char BootingStatus;			// 0 : booting, 1 : Initializing Complete.
+	unsigned char AuthorizeFlag;			// 0 : None, 1 : Authorizing
+	unsigned char FactoryConfiguration;	//0: normal, 1: trigger, charger will return the configuration to factory default if trigger
+	float InputVoltageR;                    //0~655.35 volt
+	float InputVoltageS;                    //0~655.35 volt
+	float InputVoltageT;                    //0~655.35 volt
+	float InputVoltageDc;                   //0~655.35 volt
+	unsigned int SystemFanRotaSpeed;		//0 ~ 65535 RPM
+	unsigned int PsuFanRotaSpeed;			//0 ~ 65535 RPM
+	unsigned char AuxPower5V;				//0 ~ 255 volt
+	unsigned char AuxPower12V;				//0 ~ 255 volt
+	unsigned char AuxPower24V;				//0 ~ 255 volt
+	unsigned char AuxPower48V;				//0 ~ 255 volt
+	unsigned char CsuHwRev[32];			//CSU board hardware version
+	unsigned char CsuBootLoadFwRev[32];	//CSU board bootloader firmware version
+	unsigned char CsuKernelFwRev[32];//CSU board OS kernel firmware version
+	unsigned char CsuRootFsFwRev[32];//CSU board root file system firmware version
+	unsigned char CsuPrimFwRev[32];	//CSU board root file system firmware version
+	unsigned char LcmHwRev[32];	//LCM module hardware version
+	unsigned char LcmFwRev[32];	//LCM module firmware version
+	unsigned char PsuHwRev[32];		//PSU hardware version
+	unsigned char PsuPrimFwRev[32];		//PSU primary firmware version
+	unsigned char PsuSecFwRev[32];			//PSU secondary firmware version
+	unsigned char AuxPwrHwRev[32];		//Aux. power module hardware version
+	unsigned char AuxPwrFwRev[32];		//Aux. power module firmware version
+	unsigned char FanModuleHwRev[32];		//Fan  module hardware version
+	unsigned char FanModuleFwRev[32];		//Fan  module firmware version
+	unsigned char RelayModuleHwRev[32];	//Relay control  module hardware version
+	unsigned char RelayModuleFwRev[32];	//Relay control  module firmware version
+	unsigned char TelcomModemFwRev[32];	//the 3G/4G modem firmware version
+	unsigned char LedModuleFwRev[32];	//LED control module firmware version
+	unsigned char Connector1FwRev[32];	//Connector1 module firmware version
+	unsigned char Connector2FwRev[32];	//Connector2 module firmware version
+	int SystemAmbientTemp;		// -40 ~ 215 degree C
+	int SystemCriticalTemp;		// -40 ~ 215 degree C
+	int CcsConnectorTemp;		// -40 ~ 215 degree C
+	int PsuAmbientTemp;			// -40 ~ 215 degree C
+	/**************Charging***************/
+	struct ChargingInfoData 	ChademoChargingData[CHAdeMO_QUANTITY];
+	struct ChargingInfoData 	CcsChargingData[CCS_QUANTITY];
+	struct ChargingInfoData 	GbChargingData[GB_QUANTITY];
+	struct ChargingInfoData 	AcChargingData[AC_QUANTITY];
+	unsigned char CurGunSelected;
+	unsigned char CurGunSelectedByAc;
+	/**************Network***************/
+	unsigned char 		InternetConn;					//0: disconnected, 1: connected
+	/**************Backend***************/
+	unsigned char 		OcppConnStatus;					//0: disconnected, 1: connected
+    unsigned char       MaintainServerConnStatus;       //0: disconnected, 1: connected
+	char 				OrderCharging;
+    float               MaxChargingProfilePower;        // unit: 1W
+	/**************Alston***************/
+	unsigned char 		WaitForPlugit;					//0: none scan, 1: scanning
+	unsigned char 		PageIndex;						//0 : Initialize
+														//1 : idle
+														//4 : Authorizing
+														//5 : Authorizing complete
+														//6 : Authorizing fail
+														//7 : Wait for Plug
+														//8 : Pre-charge
+														//9 : Charging
+	unsigned char 		SelfTestSeq;					//
+	unsigned char 		ReAssignedFlag;					//
+	unsigned char		CanAverageCharging;
+	unsigned char 		MainChargingMode;				// 0 : Max, 1 : Average 
+	unsigned char 		BridgeRelayStatus;
+	unsigned char 		FirmwareUpdate;					// 0 : none, 1 : update.
+	unsigned char 		AcContactorStatus;				// 0: disconnected, 1: connected
+	unsigned char 	 	SystemTimeoutFlag;				// 0 : none, 1 : self test
+	struct timespec		SystemTimeoutTimer;
+	unsigned char 		SystemPage;
+	unsigned char 		ConnectorPage;
+	unsigned char		IsAlternatvieConf;				// 0 : normal, 1 : alternative
+	unsigned char		StartToChargingFlag;			// 0 : Stop, 1 : Start for modbus
+	unsigned char 		ChargerType;					// 0 : IEC, 1 : UL
+    unsigned char       ethInternetConn;                // 0 : disconnected, 1: connected
+
+    // DO360
+    unsigned char Relay2ModuleHwRev[32];	//Relay control  module hardware version
+    unsigned char Relay2ModuleFwRev[32];	//Relay control  module firmware version
+    struct DispenserInfoData DispenserInfo;
+    struct ConnectorInfoData ConnectorInfo[GENERAL_GUN_QUANTITY];
+
+    unsigned char           AuthorizedDispenser;        // record authorized dispenser index
+    unsigned char           AuthorizedTarget;           // record authorized target: 1 ~ 4, 0xFF
+    unsigned char           AuthorizedType;             // record authorized type
+    unsigned char           AuthorizedStatus;           // cabinet authorized status
+    CabinetSettingFlag      CabinetSetting;
+    struct LocalSharingInfo localSharingInfo;           // Local power sharing info structure
+    struct DC_METER_INFO    DcMeterInfo[4];
+    struct DC_METER_STATUS_INFO DcMeterStatusInfo[4];
+    struct DC_METER_TRANSACTION_ACTION DcMeterReadTransactionRecord[4];
+    struct DC_METER_TRANSACTION_ACTION DcMeterTransactionAction[4];
+    struct DC_METER_TRANSACTION_RESULT DcMeterTransactionResult[4];
+    unsigned char           OTPTemp;                    // OTP Temperature
+    unsigned char           OTPTempR;                   // OTP Recovery Temperature
+    struct LCD_OVERRIDE     LcdOveride;                 // LCD override info (no use anymore)
+    struct BAZEL8           bazel8;                     // Bazel8 payment used
+    struct Enegate          enegate;                    // Enegate payment used
+    unsigned char           PsuLostQuantity;
+};
+
+struct SysConfigAndInfo
+{
+	struct SysConfigData				SysConfig;
+	struct SysInfoData					SysInfo;
+	struct WARNING_CODE_INFO			SysWarningInfo;
+};
+
+/*
+char Currency[54][3]=
+{
+	"AED",	// - Emirati Dirham
+	"ARS",	// - Argentine Peso
+	"AUD",	// - Australian Dollar
+	"BGN",	// - Bulgarian Lev
+	"BHD",	// - Bahraini Dinar
+	"BND",	// - Bruneian Dollar
+	"BRL",	// - Brazilian Real
+	"BWP",	// - Botswana Pula
+	"CAD",	// - Canadian Dollar
+	"CHF",	// - Swiss Franc
+	"CLP",	// - Chilean Peso
+	"CNY",	// - Chinese Yuan Renminbi
+	"COP",	// - Colombian Peso
+	"CZK",	// - Czech Koruna
+	"DKK",	// - Danish Krone
+	"EUR",	// - Euro
+	"GBP",	// - British Pound
+	"HKD",	// - Hong Kong Dollar
+	"HRK",	// - Croatian Kuna
+	"HUF",	// - Hungarian Forint
+	"IDR",	// - Indonesian Rupiah
+	"ILS",	// - Israeli Shekel
+	"INR",	// - Indian Rupee
+	"IRR",	// - Iranian Rial
+	"ISK",	// - Icelandic Krona
+	"JPY",	// - Japanese Yen
+	"KRW",	// - South Korean Won
+	"KWD",	// - Kuwaiti Dinar
+	"KZT",	// - Kazakhstani Tenge
+	"LKR",	// - Sri Lankan Rupee
+	"LYD",	// - Libyan Dinar
+	"MUR",	// - Mauritian Rupee
+	"MXN",	// - Mexican Peso
+	"MYR",	// - Malaysian Ringgit
+	"NOK",	// - Norwegian Krone
+	"NPR",	// - Nepalese Rupee
+	"NZD",	// - New Zealand Dollar
+	"OMR",	// - Omani Rial
+	"PHP",	// - Philippine Peso
+	"PKR",	// - Pakistani Rupee
+	"PLN",	// - Polish Zloty
+	"QAR",	// - Qatari Riyal
+	"RON",	// - Romanian New Leu
+	"RUB",	// - Russian Ruble
+	"SAR",	// - Saudi Arabian Riyal
+	"SEK",	// - Swedish Krona
+	"SGD",	// - Singapore Dollar
+	"THB",	// - Thai Baht
+	"TRY",	// - Turkish Lira
+	"TTD",	// - Trinidadian Dollar
+	"TWD",	// - Taiwan New Dollar
+	"USD",	// - US Dollar
+	"VEF",	// - Venezuelan Bolivar
+	"ZAR"	// - South African Rand	
+};
+*/
+
+/**************************************************************************************/
+/**************************Alarm Share memory**************************************/
+/***************************************************************************************
+	Status Code	A				B					C											D	E	F
+				0: Issue		1: From EVSE 		1: Fault (unrecoverable)					001 ~ 999 serial number
+			    										e.g., hardware broken, system latch
+				1: Recovered	2: From EV			2: Alarm (recoverable)
+			   											e.g., OTP, OVP
+								3: From Backend		3: Information
+			  											e.g., swipe card to stop charging
+
+according to XXX.Revxx
+***************************************************************************************/
+/**************************************************************************************/
+/*
+char FaultStatusCode[40][6]=
+{
+	"011001",	//CHAdeMO output fuse blew
+	"011002",	//CCS output fuse blew
+	"011003",	//GB output fuse blew
+	"011004",	//RCD/CCID self-test fail
+	"011005",	//AC input contactor 1 welding
+	"011006",	//AC input contactor 1 driving fault
+	"011007",	//AC input contactor 2 welding
+	"011008",	//AC input contactor 2 driving fault
+	"011009",	//AC output relay welding
+	"011010",	//AC output relay  driving fault
+	"011011",	//CHAdeMO output relay welding
+	"011012",	//CHAdeMO output relay driving fault
+	"011013",	//CCS output relay welding
+	"011014",	//CCS output relay driving fault
+	"011015",	//GB output relay welding
+	"011016",	//GB output relay driving fault
+	"011017",	//AC connector temperature sensor broken
+	"011018",	//CHAdeMO connector temperature sensor broken
+	"011019",	//CCS connector temperature sensor broken
+	"011020",	//GB connector temperature sensor broken
+	"011021",	//WiFi module broken
+	"011022",	//3G/4G module broken
+	"011023",	//Aux. power module broken
+	"011024",	//Relay control module /smart box broken
+	"011025",	//CHAdeMO connector lock fail
+	"011026",	//GB connector lock fail
+	"011027",	//AC connector lock fail
+	"011028",	//CHAdeMO module broken
+	"011029",	//CCS module broken
+	"011030",	//GBT module broken
+	"011031",	//PSU module broken
+	"011032",	//RCD/CCID module broken
+	"011033",	//Maximum Output Current setup error
+	"011034",	//Shutter fault 
+	"011035",	//Ble module broken
+	"011036",	//Rotary switch fault
+	"011037",	//CCS liquid chiller water level fault
+	"011038",	//Chiller temperature sensor broken
+	"011039",	//Parallel relay welding
+	"011040"	//Parallel output relay driving fault
+};
+*/
+
+struct FaultCodeData
+{
+	unsigned char PreviousFaultVal[FaultCodeLength];
+	union
+	{
+		unsigned char FaultVal[FaultCodeLength];
+		struct
+		{
+			//FaultVal[0]
+		    unsigned char ChademoOutputFuseBlew:1;				//bit 0
+			unsigned char CcsOutputFuseBlew:1;					//bit 1
+			unsigned char GbOutputFuseBlew:1;   				//bit 2
+			unsigned char RcdSelfTestFail:1;					//bit 3
+			unsigned char AcInputContactor1Welding:1;			//bit 4
+			unsigned char AcInputContactor1DrivingFault:1;		//bit 5
+			unsigned char AcInputContactor2Welding:1;			//bit 6
+			unsigned char AcInputContactor2DrivingFault:1;		//bit 7
+			//FaultVal[1]
+			unsigned char AcOutputRelayWelding:1;				//bit 0
+			unsigned char AcOutputRelayDrivingFault:1;			//bit 1
+			unsigned char ChademoOutputRelayWelding:1;			//bit 2
+			unsigned char ChademoOutputRelayDrivingFault:1;		//bit 3
+			unsigned char CcsOutputRelayWelding:1;				//bit 4
+			unsigned char CcsOutputRelayDrivingFault:1;			//bit 5
+			unsigned char GbOutputRelayWelding:1;				//bit 6
+			unsigned char GbOutputRelayDrivingFault:1;			//bit 7
+			//FaultVal[2]
+			unsigned char AcConnectorTempSensorBroken:1;		//bit 0
+			unsigned char ChademoConnectorTempSensorBroken:1;	//bit 1
+			unsigned char CcsConnectorTempSensorBroken:1;		//bit 2
+			unsigned char GbConnectorTempSensorBroken:1;		//bit 3
+			unsigned char WiFiModuleBroken:1;					//bit 4
+			unsigned char Telecom4GModuleBroken:1;				//bit 5
+			unsigned char AuxPowerModuleBroken:1;				//bit 6
+			unsigned char RelayControlModuleBroken :1;			//bit 7
+			//FaultVal[3]
+			unsigned char ChademoConnectorLockFail:1;			//bit 0
+			unsigned char GbConnectorLockFail:1;				//bit 1
+			unsigned char AcConnectorLockFail:1;				//bit 2
+			unsigned char ChademoModuleBroken:1;				//bit 3
+			unsigned char CcsModuleBroken:1;					//bit 4
+			unsigned char GbModuleBroken:1;						//bit 5
+			unsigned char PsuModuleBroken:1;					//bit 6
+			unsigned char RcdCcidModuleBroken:1;				//bit 7		
+			//FaultVal[4]
+			unsigned char MaximumOutputCurrentSetupError:1;		//bit 0
+			unsigned char ShutterFault:1;						//bit 1
+			unsigned char BleModuleBroken:1;					//bit 2
+			unsigned char RotarySwitchFault:1;					//bit 3 
+			unsigned char CcsLiquidChillerWaterLevelFault:1;    //bit 4
+            unsigned char ChillerTempSensorBroken:1;            //bit 5
+            unsigned char ParallelRelayWelding:1;               //bit 6
+            unsigned char ParallelRelayDriving:1;               //bit 7
+		}bits;
+	}FaultEvents;
+};
+
+/*
+char AlarmStatusCode[160][6]=
+{
+	"012200",	//System L1 input OVP
+	"012201",	//System L2 input OVP
+	"012202",	//System L3 input OVP
+	"012203",	//System L1 input UVP
+	"012204",	//System L2 input UVP
+	"012205",	//System L3 input UVP
+	"012206",	//PSU L1 input OVP
+	"012207",	//PSU L2 input OVP
+	"012208",	//PSU L3 input OVP
+	"012209",	//PSU L1 input UVP
+	"012210",	//PSU L2 input UVP
+	"012211",	//PSU L3 input UVP
+	"012212",	//System L1 input drop
+	"012213",	//System L2 input drop
+	"012214",	//System L3 input drop
+	"012215",	//System AC output OVP
+	"012216",	//System AC output OCP L1
+	"012217",	//System CHAdeMO output OVP
+	"012218",	//System CHAdeMO output OCP
+	"012219",	//System CCS output OVP
+	"012220",	//System CCS output OCP
+	"012221",	//System GB output OVP
+	"012222",	//System GB output OCP
+	"012223",	//System ambient/inlet OTP
+	"012224",	//System critical point OTP
+	"012225",	//PSU ambient/inlet OTP
+	"012226",	//PSU critical point OTP
+	"012227",	//Aux. power module OTP
+	"012228",	//Relay board/smart box OTP
+	"012229",	//CHAdeMO connector OTP
+	"012230",	//CCS connector OTP
+	"012231",	//GB connector OTP
+	"012232",	//AC connector OTP
+	"012233",	//RCD/CCID trip
+	"012234",	//CHAdeMO GFD trip
+	"012235",	//CCS GFD trip
+	"012236",	//GB GFD trip
+	"012237",	//SPD trip
+	"012238",	//Main power breaker trip
+	"012239",	//Aux. power breaker trip
+	"012240",	//PSU communication fail
+	"012241",	//WiFi module communication fail
+	"012242",	//3G/4G module communication fail
+	"012243",	//RFID module communication fail
+	"012244",	//Bluetooth module communication fail
+	"012245",	//LCM module communication fail
+	"012246",	//Aux. power module communication fail
+	"012247",	//Relay control boaed/smart box communication fail
+	"012248",	//CCS module communication fail
+	"012249",	//CHAdeMO module communication fail
+	"012250",	//GBT module communication fail
+	"012251",	//Emergency stop
+	"012252",	//Door open
+	"012253",	//System fan decay
+	"012254",	//Fail to create share memory
+	"012255",	//CSU initialization failed
+	"012256",	//AC Ground Fault
+	"012257",	//MCU self-test Fault
+	"012258",	//Relay self-test Fault
+	"012259",	//CHAdeMO groundfault detection timeout (GFD)
+	"012260",	//CCS groundfault detection timeout (GFD)
+	"012261",	//GB groundfault detection timeout (GFD)
+	"012262",	//Circuit Short L1
+	"012263",	// PSU Duplicate ID
+	"012264", 	// Psu Fault : Infy => Output Short Circuit,UU => Abnormal discharge circuit
+	"012265", 	// PSU Discharge Abnormal
+	"012266", 	// PSU Dc Side ShutDown
+	"012267", 	// PSU Failure Alarm
+	"012268", 	// PSU Protection Alarm
+	"012269", 	// Psu Fault : Infy => Fan Fault,UU => Fan Fault
+	"012270", 	// PSU Input UVP
+	"012271",	// PSU Input OVP
+	"012272", 	// PSU WalkIn State
+	"012273", 	// Psu Fault : Infy => Power Limited State,UU => Dc OVP and shutdown
+	"012274", 	// Psu Fault : Infy => Id Repeat,UU => Id Repeat
+	"012275", 	// Psu Fault : Infy => Severe Uneven Current,UU => Pfc internal unbalance
+	"012276", 	// PSU Three Phase Input Inadequate
+	"012277", 	// PSU Three Phase Onput Imbalance
+	"012278", 	// PSU Ffc Side ShutDown
+	"012279", 	// NO PSU Resource
+	"012280", 	// Self test Failed due to communication of Relayboard failure
+	"012281", 	// Self test Failed due to communication of Fanboard failure
+	"012282", 	// Self test Failed due to communication of Primary failure
+	"012283", 	// Self test Failed due to communication of Chademoboard failure
+	"012284", 	// Self test Failed due to communication of CCSboard failure
+	"012285", 	// Self test Failed due to AC Contact failure
+	"012286", 	// Self test Failed due to communication of PSU failure
+	"012287", 	// Self test Failed due to Model name is none match
+	"012288",	// CCS output UVP
+	"012289",	// Chademo output UVP
+	"012290",	// GBT output UVP
+	"012291",	// Self test Failed due to communication of GBTboard failure
+	"012292",	// Self test Failed due to communication of AC failure
+	"012293",	// Self test Failed due to communication of Ledboard failure
+	"012294",	// Ac input OVP
+	"012295",	// Ac input UVP
+	"012296",	// CHAdeMO groundfault detection - warning
+	"012297",	// CCS groundfault detection - warning
+	"012298",	// GB groundfault detection - warning
+	"012299",	// System AC output OCP L2
+	"012300",	// System AC output OCP L3
+	"012301",	// Circuit Short L2
+	"012302",	// Circuit Short L3
+	"012303",   // CCS liquid chiller water level warning
+	"012304",   // connection disconnected from power cabinet
+	"012305",   // Meter communication timeout
+	"012306",   // The dip switch of the PSU may be incorrect
+    "012307",   // Psu Fault : Infy => Fuse Burn-Out,UU => Pfc internal OVP
+    "012308",   // Psu Fault : Infy => Pfc And Dcdc Communication Fault,UU => Pfc And Dcdc Communication Fault
+    "012309",   // Psu Fault : Infy => Bus Voltage Unbalance,UU => Dc output voltage unbalance
+    "012310",   // Psu Fault : Infy => Bus Over Voltage,UU => Ac site OVP
+    "012311",   // Psu Fault : Infy => Bus Voltage Abnormal,UU => Ac site UVP
+    "012312",   // Psu Fault : Infy => Bus Under Voltage,UU => Pfc internal UVP
+    "012313",   // Psu Fault : Infy => Input Phase Loss,UU => Dc to Dc don’t work
+    "012314",   // Psu Fault : Infy => Fan Full Speed,UU => Fan don’t work
+    "012315",   // Psu Fault : Infy => Temperature Power Limit,UU => env OTP、Pfc OTP、output relay broken、Dc OTP
+    "012316",   // Psu Fault : Infy => Ac Power Limit,UU => Ac OVP and shutdown
+    "012317",   // Psu Fault : Infy => Dcdc Eeprom Fault,UU => Dc to Dc broken
+    "012318",   // Psu Fault : Infy => Pfc Eeprom Fault,UU => Pfc broken
+    "012319",   // Psu Dcdc Over Voltage
+    "012320",   // System CHAdeMO output UCP
+    "012321",   // System CCS output UCP
+    "012322",   // System GBT output UCP
+    "012323",   // System Chiller output OTP
+    "012324",   // Connector 1 detects abnormal voltage on the output line
+    "012325",   // Connector 2 detects abnormal voltage on the output line
+    "012326",   // System task is lost
+    "012327",   // System DC input ovp
+    "012328",   // System DC input uvp
+    "012329",   // Psu Fault : Infy => Psu Can Communication Fault,UU =>
+    "012330",   // Psu Fault : Infy => Psu Dc to Dc OTP,UU => env UTP
+    "012331",   // Psu Fault : Infy => Psu Dc to Dc OVP,UU => Dc output OVP
+    "012332",   // Chiller Tube OTP
+    "012333",   // Psu Fault : Infy => DC input ovp (Phase OVP),UU => Dc output UVP
+    "012334",   // reserved
+    "012335",   // reserved
+    "012336",   // reserved
+    "012337",   // reserved
+    "012338",   // reserved
+    "012339",   // reserved
+    "012340",   // reserved
+    "012341",   // reserved
+    "012342",   // reserved
+    "012343",   // Tilt sensor self-test failed
+    "012344",   // AC: Meter IC communication timeout
+    "012345",   // AC: Pilot negative error
+    "012346",   // Psu Communication error with CSU
+    "012347",   // AC: Local power sharing communication error (Slave disconnect from Master)
+    "012348",   // Chiller Alarm failure
+    "012349",   // reserved
+    "012350",   // reserved
+    "012351",   // reserved
+    "012352",   // Payment system communication timeout
+    "012353",   // reserved
+    "012354",   // reserved
+    "012355",   // reserved
+    "012356",   // reserved
+    "012357",   // reserved
+    "012358",   // reserved
+    "012359",   // reserved
+};
+*/
+struct AlarmCodeData
+{
+	unsigned char PreviousAlarmVal[AlarmCodeLength];
+	union
+	{
+		unsigned char AlarmVal[AlarmCodeLength];
+		struct
+		{
+			//AlarmVal[0]
+		    unsigned char SystemL1InputOVP:1;					//bit 0
+			unsigned char SystemL2InputOVP:1;					//bit 1
+			unsigned char SystemL3InputOVP:1;   				//bit 2
+			unsigned char SystemL1InputUVP:1;					//bit 3
+			unsigned char SystemL2InputUVP:1;					//bit 4
+			unsigned char SystemL3InputUVP:1;					//bit 5
+			unsigned char PsuL1InputOVP:1;						//bit 6
+			unsigned char PsuL2InputOVP:1;						//bit 7
+			//AlarmVal[1]
+			unsigned char PsuL3InputOVP:1;						//bit 0
+			unsigned char PsuL1InputUVP:1;						//bit 1
+			unsigned char PsuL2InputUVP:1;						//bit 2
+			unsigned char PsuL3InputUVP	:1;						//bit 3
+			unsigned char SystemL1InputDrop:1;					//bit 4
+			unsigned char SystemL2InputDrop:1;					//bit 5
+			unsigned char SystemL3InputDrop:1;					//bit 6
+			unsigned char SystemAcOutputOVP:1;					//bit 7
+			//AlarmVal[2]
+			unsigned char SystemAcOutputOCP:1;					//bit 0
+			unsigned char SystemChademoOutputOVP:1;				//bit 1
+			unsigned char SystemChademoOutputOCP:1;				//bit 2
+			unsigned char SystemCcsOutputOVP:1;					//bit 3
+			unsigned char SystemCcsOutputOCP:1;					//bit 4
+			unsigned char SystemGbOutputOVP:1;					//bit 5
+			unsigned char SystemGbOutputOCP:1;					//bit 6
+			unsigned char SystemAmbientOTP :1;					//bit 7
+			//AlarmVal[3]
+			unsigned char SystemCriticalPointOTP:1;				//bit 0
+			unsigned char PsuAmbientOTP:1;						//bit 1
+			unsigned char PsuCriticalPointOTP:1;				//bit 2
+			unsigned char AuxPowerModuleOTP:1;					//bit 3
+			unsigned char RelayBoardOTP:1;						//bit 4
+			unsigned char ChademoConnectorOTP:1;				//bit 5
+			unsigned char CcsConnectorOTP:1;					//bit 6
+			unsigned char GbConnectorOTP:1;						//bit 7
+			 //AlarmVal[4]
+			unsigned char AcConnectorOTP:1;						//bit 0
+			unsigned char RcdTrip:1;							//bit 1
+			unsigned char ChademoGfdTrip:1;						//bit 2
+			unsigned char CcsGfdTrip:1;							//bit 3
+			unsigned char GbGfdTrip:1;							//bit 4
+			unsigned char SpdTrip:1;							//bit 5
+			unsigned char MainPowerBreakerTrip:1;				//bit 6
+			unsigned char AuxPowerBreakerTrip:1;				//bit 7
+			//AlarmVal[5]
+			unsigned char PsuCommunicationFail:1;				//bit 0
+			unsigned char WiFiModuleCommFail:1;					//bit 1
+			unsigned char Telecom4GModuleCommFail:1;			//bit 2
+			unsigned char RfidModuleCommFail:1;					//bit 3
+			unsigned char BluetoothModuleCommFail:1;			//bit 4
+			unsigned char LcmModuleCommFail:1;					//bit 5
+			unsigned char AuxPowerModuleCommFail:1;				//bit 6
+			unsigned char RelayBoardCommFail:1;					//bit 7
+			//AlarmVal[6]
+			unsigned char CcsModuleCommFail:1;					//bit 0
+			unsigned char ChademoModuleCommFail:1;				//bit 1
+			unsigned char GbModuleCommFail:1;					//bit 2
+			unsigned char EmergencyStopTrip:1;					//bit 3
+			unsigned char DoorOpen:1;							//bit 4
+			unsigned char SystemFanDecay:1;						//bit 5
+			unsigned char FailToCreateShareMemory:1;			//bit 6
+			unsigned char CsuInitFailed:1;						//bit 7
+			//AlarmVal[7]
+			unsigned char AcGroundfaultFail:1;					//bit 0
+			unsigned char McuSelftestFail:1;					//bit 1
+			unsigned char RelaySelftestFail:1;					//bit 2
+			unsigned char ChademoGroundfaultTimeout:1;			//bit 3
+			unsigned char CcsGroundfaultTimeout:1;				//bit 4
+			unsigned char GbGroundfaultTimeout:1;				//bit 5
+			unsigned char CircuitShort:1;						//bit 6
+			unsigned char PsuDuplicateID:1;						//bit 7
+			//AlarmVal[8]
+			unsigned char PsuOutputShortCircuit :1;				//bit 0
+			unsigned char PsuDischargeAbnormal :1;				//bit 1
+			unsigned char PsuDcSideShutDown :1;					//bit 2
+			unsigned char PsuFailureAlarm :1;					//bit 3
+			unsigned char PsuProtectionAlarm :1;				//bit 4
+			unsigned char PsuFanFailureAlarm :1;				//bit 5
+			unsigned char PsuInputUVP:1;						//bit 6
+			unsigned char PsuInputOVP:1;						//bit 7
+			//AlarmVal[9]
+			unsigned char PsuWalkInState :1;					//bit 0
+			unsigned char PsuPowerLimitedState :1;				//bit 1
+			unsigned char PsuIdRepeat :1;						//bit 2
+			unsigned char PsuSevereUnevenCurrent :1;			//bit 3
+			unsigned char PsuThreePhaseInputInadequate :1;		//bit 4
+			unsigned char PsuThreePhaseOnputImbalance :1;		//bit 5
+			unsigned char PsuFfcSideShutDown :1;				//bit 6
+			unsigned char PsuNoResource:1;						//bit 7
+			//AlarmVal[10]
+			unsigned char RelayboardStestFail :1;				//bit 0
+			unsigned char FanboardStestFail :1;					//bit 1
+			unsigned char PrimaryStestFail :1;					//bit 2
+			unsigned char ChademoboardStestFail :1;				//bit 3
+			unsigned char CCSboardStestFail :1;					//bit 4
+			unsigned char AcContactStestFail :1;				//bit 5
+			unsigned char PsuModuleStestFail :1;				//bit 6
+			unsigned char ModelNameNoneMatchStestFail:1;		//bit 7	
+			//AlarmVal[11]
+			unsigned char CcsOutputUVPFail :1;					//bit 0
+			unsigned char ChademoOutputUVPFail :1;				//bit 1
+			unsigned char GbtOutputUVPFail :1;					//bit 2
+			unsigned char GbtboardStestFail :1;					//bit 3
+			unsigned char AcConnectorStestFail:1;				//bit 4
+			unsigned char LedboardStestFail:1;					//bit 5
+			unsigned char AcSystemInputOVP:1;					//bit 6
+			unsigned char AcSystemInputUVP:1;					//bit 7
+			//AlarmVal[12]
+			unsigned char ChademoGroundWarning :1;					//bit 0
+			unsigned char CcsGroundfaultWarning :1;					//bit 1
+			unsigned char GbGroundfaultWarning :1;					//bit 2
+			unsigned char SystemAcOutputOCPL2:1;					//bit 3
+			unsigned char SystemAcOutputOCPL3:1;					//bit 4
+			unsigned char CircuitShortL2:1;							//bit 5
+			unsigned char CircuitShortL3:1;							//bit 6
+			unsigned char CcsLiquidChillerWaterLevelWarning:1;      //bit 7
+			//AlarmVal[13]
+            unsigned char DisconnectedFromDo:1;                     //bit 0
+            unsigned char MeterCommTimeout:1;                       //bit 1
+            unsigned char PsuDipSwitchStestFail:1;                  //bit 2
+            unsigned char PsuFuseBurnOut:1;                         //bit 3
+            unsigned char PsuPfcAndDcdcCommFault:1;                 //bit 4
+            unsigned char PsuBusVoltageUnbalance:1;                 //bit 5
+            unsigned char PsuBusOverVoltage:1;                      //bit 6
+            unsigned char PsuBusVoltageAbnormal:1;                  //bit 7
+            //AlarmVal[14]
+            unsigned char PsuBusUnderVoltage:1;                     //bit 0
+            unsigned char PsuInputPhaseLoss:1;                      //bit 1
+            unsigned char PsuFanFullSpeed:1;                        //bit 2
+            unsigned char PsuTemperaturePowerLimit:1;               //bit 3
+            unsigned char PsuAcPowerLimit:1;                        //bit 4
+            unsigned char PsuDcdcEepromFault:1;                     //bit 5
+            unsigned char PsuPfcEepromFault:1;                      //bit 6
+            unsigned char PsuDcdcOverVoltage:1;                     //bit 7
+            //AlarmVal[15]
+            unsigned char SystemChademoOutputUCP:1;                 //bit 0
+            unsigned char SystemCCSOutputUCP:1;                     //bit 1
+            unsigned char SystemGBTOutputUCP:1;                     //bit 2
+            unsigned char SystemChillerOTP:1;                       //bit 3
+            unsigned char AbnormalVoltageOnOutputLine_1:1;          //bit 4
+            unsigned char AbnormalVoltageOnOutputLine_2:1;          //bit 5
+            unsigned char SystemTaskLost:1;                         //bit 6
+            unsigned char DcInputOVP:1;                             //bit 7
+            //AlarmVal[16]
+            unsigned char DcInputUVP:1;                             //bit 0
+            unsigned char PsuCanCommFault:1;                        //bit 1
+            unsigned char PsuDcDcOtp:1;                             //bit 2
+            unsigned char PsuDcDcOvp:1;                             //bit 3
+            unsigned char ChillerTubeOTP : 1;                       //bit 4
+            unsigned char PsuPhaseOvp:1;                            //bit 5
+            unsigned char :2;                                       //reserved bit 6 ~ bit 7
+            //AlarmVal[17]
+            unsigned char :7;                                       //reserved bit 0 ~ bit 6
+            unsigned char TiltSensorStestFail:1;                    //reserved bit 7
+            //AlarmVal[18]
+            unsigned char MeterIcCommTimeout:1;                     //bit 0
+            unsigned char PilotNegativeError:1;                     //bit 1
+            unsigned char PsuComminicationErrWithCSU:1;             //bit 2
+            unsigned char LocalPowerSharingCommunicationError:1;    //bit 3
+            unsigned char ChillerAlarmFail:1;                       //bit 4
+			unsigned char :3;                                       //reserved bit 4 ~ bit 7
+            //AlarmVal[19]
+            unsigned char PaymentCommTimeout:1;                     //Payment system communication timeout
+           	unsigned char MeterSlaveLosLink:1;                     	//DCMB meter slave module los link
+            unsigned char MeterSyncTimeError:1;            					//DCMB meter Sync Time Error
+            unsigned char MetertStartTransactionError:1;            //DCMB meter Start Transaction Error
+            unsigned char MetertStopTransactionError:1;             //DCMB meter Stop Transaction Error
+            unsigned char MetertGetTransactionOcmfError:1;          //DCMB meter Get OCMF Error        	
+            unsigned char :2;                                       //reserved bit 1 ~ bit 7
+		}bits;
+	}AlarmEvents;
+};
+
+/*
+char InfoStatusCode[384][6]=
+{
+	//Information comes from EVSE
+	"013600",	//Normal stop charging by user
+	"013601",	//Charging Time's up
+	"013602",	//Replace system air filter
+	"013603",	//Reach to CHAdeMO max. plugging times.
+	"013604",	//Reach to CCS max. plugging times.
+	"013605",	//Reach to GB max. plugging times.
+	"013606",	//Reach to AC max. plugging times.
+	"013607",	//CSU fimrware update fail
+	"013608",	//CHAdeMO Module fimrware update fail
+	"013609",	//CCS Module fimrware update fail
+	"013610",	//GB Module fimrware update fail
+	"013611",	//Aux. power module fimrware update fail
+	"013612",	//Relay control module fimrware update fail
+	"013613",	//LCM module fimrware update fail
+	"013614",	//Bluetooth module fimrware update fail
+	"013615",	//WiFi module fimrware update fail
+	"013616",	//3G/4G module fimrware update fail
+	"013617",	//SMR fimrware update fail
+	"013618",	//RFID module fimrware update fail
+	"013619",	//configured by USB flash drive
+	"013620",	//configured by backend
+	"013621",	//configured by webpage
+	"013622",	//disconnected from Internet through Ethernet
+	"013623",	//disconnected from Internet through WiFi
+	"013624",	//disconnected from Internet through 3G/4G
+	"013625",	//disconnected from AP through WiFi
+	"013626",	//disconnected from APN through 3G/4G
+	"013627",	//WiFi disabled (separated charger only)
+	"013628",	//4G disabled (separated charger only)
+	"013629",	//Psu Quantity Not Match
+	"013630",	//Reserved
+	"013631",	//Reserved
+	//Information comes from EV
+	"023700",	//CHAdeMO EV communication Fail
+	"023701",	//CCS EV communication Fail
+	"023702",	//GB EV communication Fail
+	"023703",	//AC: pilot fault
+	"023704",	//CHAdeMO:  battery malfunction
+	"023705",	//CHAdeMO:  no charging permission
+	"023706",	//CHAdeMO:  battery incompatibility
+	"023707",	//CHAdeMO:  battery OVP
+	"023708",	//CHAdeMO:  battery UVP
+	"023709",	//CHAdeMO:  battery OTP
+	"023710",	//CHAdeMO:  battery current difference
+	"023711",	//CHAdeMO:  battery voltage difference
+	"023712",	//CHAdeMO:  shift position
+	"023713",	//CHAdeMO:  battery other fault
+	"023714",	//CHAdeMO:  charging system error
+	"023715",	//CHAdeMO:  EV normal stop
+	"023716",	//CHAdeMO:  connector temperature sensor broken
+	"023717",	//CHAdeMO:  connector lock fail
+	"023718",	//CHAdeMO:	D1 ON No Receive
+	"023719",	//CHAdeMO:	Permission ON but charge sequence timeout
+	"023720",	//CHAdeMO:	BMS Charge Allow Timeout
+	"023721",	//CHAdeMO:	Wait GroundFault Timeout
+	"023722",	//CHAdeMO:	BMS EV Relay Timeout
+	"023723",	//CHAdeMO:	BMS Request Current Timeout
+	"023724",	//CHAdeMO:	BMS K to J OFF Timeout
+	"023725",	//CHAdeMO:	BMS EV Relay OFF Timeout
+	"023726",	//CHAdeMO:	ADC More Than 10V
+	"023727",	//CHAdeMO:	ADC More Than 20V
+	"023728",	//CHAdeMO:	BMS Charge Before Stop
+	"023729",	//CHAdeMO:	Charger Get Normal Stop
+	"023730",	//CHAdeMO:	Charger Get Emergency Stop
+	"023731",	//CHAdeMO:  Isolation Result Fail
+	"023732",	//CHAdeMO: 	Miss Link With MotherBoard
+	"023733",	//CHAdeMO:	Output Voltage More Than Limit
+	"023734",	//CHAdeMO:	Request Current More Than Limit
+	"023735",	//CHAdeMO: 	Re Cap BMS Eqr Current Exceed
+	"023736",	//CHAdeMO:	Charge Remain Count Down
+	"023737",	//CCS:CCS_EVCC_EVErrorCode_FAILED_RESSTemperatureInhibit
+	"023738",	//CCS:CCS_EVCC_EVErrorCode_FAILED_EVShiftPosition
+	"023739",	//CCS:CCS_EVCC_EVErrorCode_FAILED_ChargerConnectorLockFault
+	"023740",	//CCS:CCS_EVCC_EVErrorCode_FAILED_EVRESSMalfunction
+	"023741",	//CCS:CCS_EVCC_EVErrorCode_FAILED_ChargingCurrentdifferential
+	"023742",	//CCS:CCS_EVCC_EVErrorCode_FAILED_ChargingVoltageOutOfRange
+	"023743",	//CCS:CCS_EVCC_EVErrorCode_FAILED_ChargingSystemIncompatibility
+	"023744",	//CCS:CCS_EVCC_EVErrorCode_FAILED_EmergencyEvent
+	"023745",	//CCS:CCS_EVCC_EVErrorCode_FAILED_Breaker
+	"023746",	//CCS:CCS_EVCC_EVErrorCode_FAILED_NoData
+	"023747",	//CCS:CCS_EVCC_EVErrorCode_FAILED_reserved_by_DIN_A
+	"023748",	//CCS:CCS_EVCC_EVErrorCode_FAILED_reserved_by_DIN_B
+	"023749",	//CCS:CCS_EVCC_EVErrorCode_FAILED_reserved_by_DIN_C
+	"023750",	//CCS:CCS_EVCC_EVErrorCode_FAILED_reserved_by_ISO_1
+	"023751",	//CCS:CCS_EVCC_EVErrorCode_FAILED_reserved_by_ISO_2
+	"023752",	//CCS:CCS_EVCC_EVErrorCode_FAILED_reserved_by_ISO_3
+	"023753",	//CCS:CCS_EVCC_EVErrorCode_FAILED_reserved_by_OEM_1
+	"023754",	//CCS:CCS_EVCC_EVErrorCode_FAILED_reserved_by_OEM_2
+	"023755",	//CCS:CCS_EVCC_EVErrorCode_FAILED_reserved_by_OEM_3
+	"023756",	//CCS:CCS_EVCC_EVErrorCode_FAILED_reserved_by_OEM_4
+	"023757",	//CCS:CCS_EVCC_EVErrorCode_FAILED_reserved_by_OEM_5
+	"023758",	//CCS:CCS_SECC_ResponseCode_FAILED_SequenceError
+	"023759",	//CCS:CCS_SECC_ResponseCode_FAILED_SignatureError
+	"023760",	//CCS:CCS_SECC_ResponseCode_FAILED_UnknownSession
+	"023761",	//CCS:CCS_SECC_ResponseCode_FAILED_ServiceIDInvalid
+	"023762",	//CCS:CCS_SECC_ResponseCode_FAILED_Payment SelectionInvalid
+	"023763",	//CCS:CCS_SECC_ResponseCode_FAILED_IdentificationSelectionInvalid
+	"023764",	//CCS:CCS_SECC_ResponseCode_FAILED_ServiceSelectionInvalid
+	"023765",	//CCS:CCS_SECC_ResponseCode_FAILED_CertificateExpired
+	"023766",	//CCS:CCS_SECC_ResponseCode_FAILED_CertificateNotYetValid
+	"023767",	//CCS:CCS_SECC_ResponseCode_FAILED_CertificateRevoked
+	"023768",	//CCS:CCS_SECC_ResponseCode_FAILED_NoCertificateAvailable
+	"023769",	//CCS:CCS_SECC_ResponseCode_FAILED_CertChainError
+	"023770",	//CCS:CCS_SECC_ResponseCode_FAILED_CertValidationError
+	"023771",	//CCS:CCS_SECC_ResponseCode_FAILED_CertVerificationError
+	"023772",	//CCS:CCS_SECC_ResponseCode_FAILED_ContractCanceled
+	"023773",	//CCS:CCS_SECC_ResponseCode_FAILED_ChallengeInvalid
+	"023774",	//CCS:CCS_SECC_ResponseCode_FAILED_WrongEnergyTransferMode
+	"023775",	//CCS:CCS_SECC_ResponseCode_FAILED_WrongChargeParameter
+	"023776",	//CCS:CCS_SECC_ResponseCode_FAILED_ChargingProfileInvalid
+	"023777",	//CCS:CCS_SECC_ResponseCode_FAILED_TariffSelectionInvalid
+	"023778",	//CCS:CCS_SECC_ResponseCode_FAILED_EVSEPresentVoltageToLow
+	"023779",	//CCS:CCS_SECC_ResponseCode_FAILED_PowerDeliveryNotApplied
+	"023780",	//CCS:CCS_SECC_ResponseCode_FAILED_MeteringSignatureNotValid
+	"023781",	//CCS:CCS_SECC_ResponseCode_FAILED_NoChargeServiceSelected
+	"023782",	//CCS:CCS_SECC_ResponseCode_FAILED_ContactorError
+	"023783",	//CCS:CCS_SECC_ResponseCode_FAILED_CertificateNotAllowedAtThisEVSE
+	"023784",	//CCS:CCS_SECC_ResponseCode_FAILED_GAChargeStop
+	"023785",	//CCS:CCS_SECC_ResponseCode_FAILED_AlignmentError
+	"023786",	//CCS:CCS_SECC_ResponseCode_FAILED_ACDError
+	"023787",	//CCS:CCS_SECC_ResponseCode_FAILED_AssociationError
+	"023788",	//CCS:CCS_SECC_ResponseCode_FAILED_EVSEChargeAbort
+	"023789",	//CCS:CCS_SECC_ResponseCode_FAILED_NoSupportedApp-Protocol-Protocol
+	"023790",	//CCS:CCS_SECC_ResponseCode_FAILED_ContractNotAccepted
+	"023791",	//CCS:CCS_SECC_ResponseCode_FAILED_MOUnknown
+	"023792",	//CCS:CCS_SECC_ResponseCode_FAILED_OEM_Prov_CertificateRevoke
+	"023793",	//CCS:CCS_SECC_ResponseCode_FAILED_OEM_SubCA1_CertificateRevoked
+	"023794",	//CCS:CCS_SECC_ResponseCode_FAILED_OEM_SubCA2_CertificateRevoked
+	"023795",	//CCS:CCS_SECC_ResponseCode_FAILED_OEM_RootCA_CertificateRevoked
+	"023796",	//CCS:CCS_SECC_ResponseCode_FAILED_MO_Prov_CertificateRevoked
+	"023797",	//CCS:CCS_SECC_ResponseCode_FAILED_MO_SubCA1_CertificateRevoked
+	"023798",	//CCS:CCS_SECC_ResponseCode_FAILED_MO_SubCA2_CertificateRevoked
+	"023799",	//CCS:CCS_SECC_ResponseCode_FAILED_MO_RootCA_CertificateRevoked
+	"023800",	//CCS:CCS_SECC_ResponseCode_FAILED_CPS_Prov_CertificateRevoked
+	"023801",	//CCS:CCS_SECC_ResponseCode_FAILED_CPS_SubCA1_CertificateRevoked
+	"023802",	//CCS:CCS_SECC_ResponseCode_FAILED_CPS_SubCA2_CertificateRevoked
+	"023803",	//CCS:CCS_SECC_ResponseCode_FAILED_CPS_RootCA_CertificateRevoked
+	"023804",	//CCS:CCS_SECC_ResponseCode_FAILED_reserved_1
+	"023805",	//CCS:CCS_SECC_ResponseCode_FAILED_reserved_2
+	"023806",	//CCS:CCS_SECC_ResponseCode_FAILED_reserved_3
+	"023807",	//CCS:CCS_SECC_ResponseCode_FAILED_reserved_4
+	"023808",	//CCS:CCS_SECC_ResponseCode_FAILED_reserved_5
+	"023809",	//CCS:CCS_SECC_TIMEOUT_SLAC_TT_EVSE_SLAC_init
+	"023810",	//CCS:CCS_SECC_TIMEOUT_SLAC_TP_match_response
+	"023811",	//CCS:CCS_SECC_TIMEOUT_CM_START_ATTEN_CHAR_IND
+	"023812",	//CCS:CCS_SECC_TIMEOUT_SLAC_TT_EVSE_match_MNBC
+	"023813",	//CCS:CCS_SECC_TIMEOUT_SLAC_TP_EVSE_avg_atten_calc
+	"023814",	//CCS:CCS_SECC_TIMEOUT_SLAC_CM_ATTEN_CHAR_RSP
+	"023815",	//CCS:CCS_SECC_TIMEOUT_SLAC_CM_VALIDATE_REQ_1ST__CM_SLAC_MATCH_REQ
+	"023816",	//CCS:CCS_SECC_TIMEOUT_SLAC_TT_EVSE_assoc_session
+	"023817",	//CCS:CCS_SECC_TIMEOUT_SLAC_TT_EVSE_vald_toggle
+	"023818",	//CCS:CCS_SECC_TIMEOUT_SLAC_CM_MNBC_SOUND_IND
+	"023819",	//CCS:CCS_SECC_TIMEOUT_SLAC_CM_VALIDATE_REQ_2ND__CM_SLAC_MATCH_REQ
+	"023820",	//CCS:CCS_SECC_TIMEOUT_SLAC_reserved_3
+	"023821",	//CCS:CCS_SECC_TIMEOUT_SLAC_reserved_4
+	"023822",	//CCS:CCS_SECC_TIMEOUT_SLAC_reserved_5
+	"023823",	//CCS:CCS_SECC_TIMEOUT_SLACC_SDP_UDP_TT_match_join
+	"023824",	//CCS:CCS_SECC_TIMEOUT_SLACC_SDP_TCP_TT_match_join
+	"023825",	//CCS:CCS_SECC_TIMEOUT_SLACC_SDP_TP_amp_map_exchange
+	"023826",	//CCS:CCS_SECC_TIMEOUT_SLACC_SDP_TP_link_ready_notification
+	"023827",	//CCS:CCS_SECC_TIMEOUT_SLACC_SDP_reserved_1
+	"023828",	//CCS:CCS_SECC_TIMEOUT_SLACC_SDP_reserved_2
+	"023829",	//CCS:CCS_SECC_TIMEOUT_SLACC_SDP_reserved_3
+	"023830",	//CCS:CCS_SECC_TIMEOUT_SLACC_SDP_reserved_4
+	"023831",	//CCS:CCS_SECC_TIMEOUT_SLACC_SDP_reserved_5
+	"023832",	//CCS:CCS_SECC_TIMEOUT_V2G_Msg_Performance_Time_SupportedAppProtocolRes
+	"023833",	//CCS:CCS_SECC_TIMEOUT_V2G_Msg_Performance_Time_SessionSetupRes
+	"023834",	//CCS:CCS_SECC_TIMEOUT_V2G_Msg_Performance_Time_ServiceDiscoveryRes
+	"023835",	//CCS:CCS_SECC_TIMEOUT_V2G_Msg_Performance_Time_ServicePaymentSelectionRes
+	"023836",	//CCS:CCS_SECC_TIMEOUT_V2G_Msg_Performance_Time_ContractAuthenticationRes
+	"023837",	//CCS:CCS_SECC_TIMEOUT_V2G_Msg_Performance_Time_ChargeParameterDiscoveryRes
+	"023838",	//CCS:CCS_SECC_TIMEOUT_V2G_Msg_Performance_Time_PowerDeliveryRes
+	"023839",	//CCS:CCS_SECC_TIMEOUT_V2G_Msg_Performance_Time_CableCheckRes
+	"023840",	//CCS:CCS_SECC_TIMEOUT_V2G_Msg_Performance_Time_PreChargeRes
+	"023841",	//CCS:CCS_SECC_TIMEOUT_V2G_Msg_Performance_Time_CurrentDemandRes
+	"023842",	//CCS:CCS_SECC_TIMEOUT_V2G_Msg_Performance_Time_WeldingDetectionRes
+	"023843",	//CCS:CCS_SECC_TIMEOUT_V2G_Msg_Performance_Time_SessionStopRes
+	"023844",	//CCS:CCS_SECC_TIMEOUT_V2G_Sequence_Time
+	"023845",	//CCS:CCS_SECC_TIMEOUT_V2G_ReadyToCharge_Performance_Time
+	"023846",	//CCS:CCS_SECC_TIMEOUT_V2G_CommunicationSetup_Performance_Time
+	"023847",	//CCS:CCS_SECC_TIMEOUT_V2G_CableCheck_Performance_Time
+	"023848",	//CCS:CCS_SECC_TIMEOUT_V2G_CPState_Detection_Time
+	"023849",	//CCS:CCS_SECC_TIMEOUT_V2G_CPOscillator_Retain_Time
+	"023850",	//CCS:CCS_SECC_TIMEOUT_V2G_PreCharge_Performace_Time
+	"023851",	//CCS:CCS_SECC_TIMEOUT_V2G_reserved_2
+	"023852",	//CCS:CCS_SECC_TIMEOUT_V2G_reserved_3
+	"023853",	//CCS:CCS_SECC_TIMEOUT_V2G_reserved_4
+	"023854",	//CCS:CCS_SECC_TIMEOUT_V2G_reserved_5
+	"023855",	//CCS:CCS_CAN_TIMEOUT_TP_GET_EV_TARGET_INFO
+	"023856",	//CCS:CCS_CAN_TIMEOUT_TT_GET_EV_TARGET_INFO
+	"023857",	//CCS:CCS_CAN_TIMEOUT_TP_GET_EV_BATTERY_INFO
+	"023858",	//CCS:CCS_CAN_TIMEOUT_TT_GET_EV_BATTERY_INFO
+	"023859",	//CCS:CCS_CAN_TIMEOUT_TP_EV_STOP_EVENT
+	"023860",	//CCS:CCS_CAN_TIMEOUT_TT_EV_STOP_EVENT
+	"023861",	//CCS:CCS_CAN_TIMEOUT_TP_EVSE_STOP_EVENT
+	"023862",	//CCS:CCS_CAN_TIMEOUT_TT_EVSE_STOP_EVENT
+	"023863",	//CCS:CCS_CAN_TIMEOUT_TP_GET_MISC_INFO
+	"023864",	//CCS:CCS_CAN_TIMEOUT_TT_GET_MISC_INFO
+	"023865",	//CCS:CCS_CAN_TIMEOUT_TP_DOWNLOAD_REQUEST
+	"023866",	//CCS:CCS_CAN_TIMEOUT_TT_DOWNLOAD_REQUEST
+	"023867",	//CCS:CCS_CAN_TIMEOUT_TP_START_BLOCK_TRANSFER
+	"023868",	//CCS:CCS_CAN_TIMEOUT_TT_START_BLOCK_TRANSFER
+	"023869",	//CCS:CCS_CAN_TIMEOUT_TP_DATA_TRANSFER
+	"023870",	//CCS:CCS_CAN_TIMEOUT_TT_DATA_TRANSFER
+	"023871",	//CCS:CCS_CAN_TIMEOUT_TP_DOWNLOAD_FINISH
+	"023872",	//CCS:CCS_CAN_TIMEOUT_TT_DOWNLOAD_FINISH
+	"023873",	//CCS:CCS_CAN_TIMEOUT_TP_ISOLATION_STATUS
+	"023874",	//CCS:CCS_CAN_TIMEOUT_TT_ISOLATION_STATUS
+	"023875",	//CCS:CCS_CAN_TIMEOUT_TP_CONNECTOR_INFO
+	"023876",	//CCS:CCS_CAN_TIMEOUT_TT_CONNECTOR_INFO
+	"023877",	//CCS:CCS_CAN_TIMEOUT_TT_RTC_INFO
+	"023878",	//CCS:CCS_CAN_TIMEOUT_TP_RTC_INFO
+	"023879",	//CCS:CCS_CAN_TIMEOUT_TP_EVSE_PRECHARGE_INFO
+	"023880",	//CCS:CCS_CAN_TIMEOUT_TT_EVSE_PRECHARGE_INFO
+	"023881",	//CCS:CCS_CAN_TIMEOUT_MSG_Sequence
+	"023882",	//CCS:CCS_CAN_MSG_Unrecognized_CMD_ID
+	"023883",	//CCS:CCS_SECC_DIN_Msg_Decode_Error
+	"023884",	//CCS:CCS_SECC_DIN_Msg_Encode_Error
+	"023885",	//CCS:CCS_SECC_ISO1_Msg_Decode_Error
+	"023886",	//CCS:CCS_SECC_ISO1_Msg_Encode_Error
+	"023887",	//CCS:CCS_SECC_ISO2_Msg_Decode_Error
+	"023888",	//CCS:CCS_SECC_ISO2_Msg_Encode_Error
+	"023889",	//CCS:CCS_SECC_CP_STATUS_Error
+	"023890",	//CCS:CCS_SECC_Unexpected_60V_Before_Charing_Error
+	"023891",	//CCS:CCS_SECC_Not_Ready_For_Charging
+	"023892",	//CCS:CCS_SECCC_TIMEOUT_QCA7000_COMM (The firmware code of QCA7000 may not be installed, yet)
+	"023893",	//CCS:CCS_SECC_FAIL_QCA7000_SETKEY
+	"023894",	//Reserved
+	"023895",	//Reserved
+	"023896",	//Reserved
+	"023897",	//Reserved
+	"023898",	//Reserved
+	"023899",	//Reserved
+	"023900",	//GBT: ERROR_CODE_GBT_LOS_CC1
+	"023901",	//GBT: ERROR_CODE_GBT_CONNECTOR_LOCK_FAIL
+	"023902",	//GBT: ERROR_CODE_GBT_BATTERY_INCOMPATIBLE
+	"023903",	//GBT: ERROR_CODE_GBT_BMS_BROAA_TIMEOUT
+	"023904",	//GBT: ERROR_CODE_GBT_CSU_PRECHARGE_TIMEOUT
+	"023905",	//GBT: ERROR_CODE_GBT_BMS_PRESENT_VOLTAGE_FAULT
+	"023906",	//GBT: ERROR_CODE_GBT_BMS_VOLTAGE_OVER_RANGE
+	"023907",	//GBT: ERROR_CODE_GBT_BSM_CHARGE_ALLOW_00_10MIN_COUUNTDONE
+	"023908",	//GBT: ERROR_CODE_GBT_WAIT_GROUNDFAULT_TIMEOUT
+	"023909",	//GBT: ERROR_CODE_GBT_ADC_MORE_THAN_10V
+	"023910",	//GBT: ERROR_CODE_GBT_ADC_MORE_THAN_60V
+	"023911",	//GBT: ERROR_CODE_GBT_CHARGER_GET_NORMAL_STOP_CMD
+	"023912",	//GBT: ERROR_CODE_GBT_CHARGER_GET_EMERGENCY_STOP_CMD
+	"023913",	//GBT: ERROR_CODE_GBT_ISOLATION_RESULT_FAIL
+	"023914",	//GBT: ERROR_CODE_GBT_MOTHER_BOARD_MISS_LINK
+	"023915",	//GBT: ERROR_CODE_GBT_OUTPUT_VOLTAGE_MORE_THAN_LIMIT
+	"023916",	//GBT: ERROR_CODE_GBT_REQ_CURRENT_MORE_THAN_LIMIT
+	"023917",	//GBT: ERROR_CODE_GBT_OUTPUT_VOLTAGE_MORE_THAN_10_PERCENT
+	"023918",	//GBT: ERROR_CODE_GBT_OUTPUT_VOLTAGE_DIFF_BCS_5_PERCENT
+	"023919",	//GBT: ERROR_CODE_GBT_STOP_ADC_MORE_THAN_10V
+	"023920",	// Reserved
+	"023921",	// Reserved
+	"023922",	// Reserved
+	"023923",	// Reserved
+	"023924",	// Reserved
+	"023925",	// Reserved
+	"023926",	// Reserved
+	"023927",	// Reserved
+	"023928",	// Reserved
+	"023929",	// Reserved
+	"023930",	//GBT: ERROR_CODE_CEM_BHM_TIMEOUT
+	"023931",	//GBT: ERROR_CODE_CEM_BRM_TIMEOUT
+	"023932",	//GBT: ERROR_CODE_CEM_BCP_TIMEOUT
+	"023933",	//GBT: ERROR_CODE_CEM_BRO_TIMEOUT
+	"023934",	//GBT: ERROR_CODE_CEM_BCL_TIMEOUT
+	"023935",	//GBT: ERROR_CODE_CEM_BCS_TIMEOUT
+	"023936",	//GBT: ERROR_CODE_CEM_BSM_TIMEOUT
+	"023937",	//GBT: ERROR_CODE_CEM_BST_TIMEOUT
+	"023938",	//GBT: ERROR_CODE_CEM_BSD_TIMEOUT
+	"023939",	//GBT: ERROR_CODE_CEM_BEM_OTHER_TIMEOUT
+	"023940",	//GBT: ERROR_CODE_BEM_CRM_TIMEOUT
+	"023941",	//GBT: ERROR_CODE_BEM_CRMAA_TIMEOUT
+	"023942",	//GBT: ERROR_CODE_BEM_CTS_CML_TIMEOUT
+	"023943",	//GBT: ERROR_CODE_BEM_CRO_TIMEOUT
+	"023944",	//GBT: ERROR_CODE_BEM_CCS_TIMEOUT
+	"023945",	//GBT: ERROR_CODE_BEM_CST_TIMEOUT
+	"023946",	//GBT: ERROR_CODE_BEM_CSD_TIMEOUT
+	"023947",	//GBT: ERROR_CODE_BEM_BEM_OTHER_TIMEOUT
+	"023948",	// Reserved
+	"023949",	// Reserved
+	"023950",	//GBT: ERROR_CODE_BST_SOC_GOAL
+	"023951",	//GBT: ERROR_CODE_BST_TOTAL_VOLTAGE_GOAL
+	"023952",	//GBT: ERROR_CODE_BST_CELL_VOLTAGE_GOAL
+	"023953",	//GBT: ERROR_CODE_BST_GET_CST
+	"023954",	//GBT: ERROR_CODE_BST_ISOLATION
+	"023955",	//GBT: ERROR_CODE_BST_OUTPUT_CONNECTOR_OTP
+	"023956",	//GBT: ERROR_CODE_BST_COMPONENT
+	"023957",	//GBT: ERROR_CODE_BST_CHARGE_CONNECTOR
+	"023958",	//GBT: ERROR_CODE_BST_OTP
+	"023959",	//GBT: ERROR_CODE_BST_OTHER
+	"023960",	//GBT: ERROR_CODE_BST_HIGH_V
+	"023961",	//GBT: ERROR_CODE_BST_CC2
+	"023962",	//GBT: ERROR_CODE_BST_CURRENT
+	"023963",	//GBT: ERROR_CODE_BST_VOLTAGE
+	"023964",	//GBT: ERROR_CODE_GET_BST_NO_REASON
+	"023965",	// Reserved
+	"023966",	// Reserved
+	"023967",	// Reserved
+	"023968",	// Reserved
+	"023969",	// Reserved
+	"023970",	//GBT: ERROR_CODE_BSM_CELL_OVER_VOLTAGE
+	"023971",	//GBT: ERROR_CODE_BSM_CELL_UNDER_VOLTAGE
+	"023972",	//GBT: ERROR_CODE_BSM_OVER_SOC
+	"023973",	//GBT: ERROR_CODE_BSM_UNDER_SOC
+	"023974",	//GBT: ERROR_CODE_BSM_CURRENT
+	"023975",	//GBT: ERROR_CODE_BSM_TEMPERATURE
+	"023976",	//GBT: ERROR_CODE_BSM_ISOLATE
+	"023977",	//GBT: ERROR_CODE_BSM_OUTPUT_CONNECTOR
+	"023978",	// Reserved
+	"023979",	// EV full charging
+    "023980",   // ERROR_CODE_CHADEMO_BMS_CHARGE_ALLOW_ERROR
+    "023981",   // ERROR_CODE_CHADEMO_OUTPUT_VOLTAGE_MORE_THEN_10_PERCENT
+    "023982",   // ERROR_CODE_CHADEMO_ADC_LESS_THAN_10V
+    "023983",   // STOP by EV with unknow reason
+    "023984",   // STOP by EVSE condition (Config or OCPP)
+    "023985",   // Reserved
+    "023986",   // Reserved
+    "023987",   // Reserved
+	"033900",	//disconnected from backend through Ethernet
+	"033901",	//disconnected from backend through WiFi
+	"033902",	//disconnected from backend through 3G/4G
+	"033903",	//Remote start charging by backend
+	"033904",	//Remote stop charging by backend
+	"033905",	//Remote reset by backend
+	"033906",	//Authorization failed
+	"033907",	//Reserved
+};
+*/
+struct InfoCodeData
+{
+	unsigned char PreviousInfoVal[InfoCodeLength];
+	union
+	{
+		unsigned char InfoVal[InfoCodeLength];
+		struct
+		{
+			//InfoVal[0]
+		    unsigned char NormalStopChargingByUser:1;				//bit 0
+			unsigned char ChargingTimesUp:1;						//bit 1
+			unsigned char ReplaceSystemAirFilter:1; 				//bit 2
+			unsigned char ReachChademoMaxPluggingTimes:1;			//bit 3
+			unsigned char ReachCcsMaxPluggingTimes:1;				//bit 4
+			unsigned char ReachGbMaxPluggingTimes:1;				//bit 5
+			unsigned char ReachAcMaxPluggingTimes:1;				//bit 6
+			unsigned char CsuFimrwareUpdateFail:1;					//bit 7
+			//InfoVal[1]
+			unsigned char ChademoModuleFimrwareUpdateFail:1;		//bit 0
+			unsigned char CcsModuleFimrwareUpdateFail:1;			//bit 1
+			unsigned char GbModuleFimrwareUpdateFail:1;				//bit 2
+			unsigned char AuxPowerModuleFimrwareUpdateFail:1;		//bit 3
+			unsigned char RelayBoardFimrwareUpdateFail:1;			//bit 4
+			unsigned char LcmModuleFimrwareUpdateFail:1;			//bit 5
+			unsigned char BluetoothModuleFimrwareUpdateFail:1;		//bit 6
+			unsigned char WiFiModuleFimrwareUpdateFail:1;			//bit 7
+			//InfoVal[2]
+			unsigned char Telocom4GModuleFimrwareUpdateFail:1;		//bit 0
+			unsigned char PsuFimrwareUpdateFail:1;					//bit 1
+			unsigned char RfidModuleFimrwareUpdateFail:1;			//bit 2
+			unsigned char ConfiguredByUsbFlashDrive:1;				//bit 3
+			unsigned char ConfiguredByBackend:1;					//bit 4
+			unsigned char ConfiguredByWebpage:1;					//bit 5
+			unsigned char InternetDisconnectViaEthernet:1;			//bit 6
+			unsigned char InternetDisconnectViaWiFi :1;				//bit 7
+	        //InfoVal[3]
+			unsigned char InternetDisconnectVia4Gi:1;				//bit 0
+			unsigned char ApDisconnectViaWiFi:1;					//bit 1
+			unsigned char ApnDisconnectVia4Gi:1;					//bit 2
+			unsigned char WiFiDisable:1;                            //bit 3
+			unsigned char Telocom4GModuleDisable:1;                 //bit 4
+			unsigned char PsuQuantityNotMatch:1;                    //bit 5
+			unsigned char :2;										//bit 6~7 reserved
+			 //InfoVal[4]
+			unsigned char ChademoEvCommFail:1;						//bit 0
+			unsigned char CcsEvCommFail:1;							//bit 1
+			unsigned char GbEvCommFail:1;							//bit 2
+			unsigned char PilotFault:1;								//bit 3
+			unsigned char ChademoBatteryMalfun:1;					//bit 4
+			unsigned char ChademoNoPermission:1;					//bit 5
+			unsigned char ChademoBatteryIncompatibility:1;			//bit 6
+			unsigned char ChademoBatteryOVP:1;						//bit 7
+			//InfoVal[5]
+			unsigned char ChademoBatteryUVP:1;						//bit 0
+			unsigned char ChademoBatteryOTP:1;						//bit 1
+			unsigned char ChademoBatteryCurrentDiff:1;				//bit 2
+			unsigned char ChademoBatteryVoltageDiff:1;				//bit 3
+			unsigned char ChademoShiftPosition:1;					//bit 4
+			unsigned char ChademoBatteryOtherFault:1;				//bit 5
+			unsigned char ChademoChargingSystemError:1;				//bit 6
+			unsigned char ChademoEvNormalStop:1;					//bit 7
+			//InfoVal[6]
+			unsigned char ChademoTempSensorBroken:1;				//bit 0
+			unsigned char ChademoConnectorLockFail:1;				//bit 1
+			unsigned char ChademoD1OnNoReceive:1;					//bit 2
+			unsigned char ChademoBmsKtoJTimeout:1;					//bit 3
+			unsigned char ChademoBmsChargeAllowTimeout:1;			//bit 4
+			unsigned char ChademoWaitGfdTimeout:1;					//bit 5
+			unsigned char ChademoBmsEvRelayTimeout:1;				//bit 6
+			unsigned char ChademoBmsReqCurrentTimeout:1;			//bit 7
+			//InfoVal[7]
+			unsigned char ChademoBmsKtoJOffTimeout :1;				//bit 0
+			unsigned char ChademoBmsEvRelayOffTimeout :1;			//bit 1
+			unsigned char ChademoAdcMoreThan10V :1;					//bit 2
+			unsigned char ChademoAdcMoreThan20V :1;					//bit 3
+			unsigned char ChademoBmsChargeBeforeStop :1;			//bit 4
+			unsigned char ChademoChargerGetNormalStop :1;			//bit 5
+			unsigned char ChademoChargerGetEmergencyStop :1;		//bit 6
+			unsigned char ChademoIsolationResultFail :1;			//bit 7
+			//InfoVal[8]
+			unsigned char ChademoMissLinkWithMotherBoard :1;		//bit 0
+			unsigned char ChademoOutputVolMoreThanLimit :1;			//bit 1
+			unsigned char ChademoReqCurrentMoreThanLimit :1;				//bit 2
+			unsigned char ChademoReCapBmsEqrCurrentExceed :1;				//bit 3
+			unsigned char ChademoChargeRemainCountDown :1;		//bit 4
+			unsigned char CcsRESTemperatureInhibit:1;				//bit 5
+			unsigned char CcsEVShiftPosition:1;				//bit 6
+			unsigned char CcsChargerConnectorLockFault:1;				//bit 7
+			//InfoVal[9]
+			unsigned char CcsEVRESSMalfunction:1;					//bit 0
+			unsigned char CcsChargingCurrentdifferential:1;		//bit 1
+			unsigned char CcsChargingVoltageOutOfRange:1;		//bit 2
+			unsigned char CcsChargingSystemIncompatibility:1;		//bit 3
+			unsigned char CcsEmergencyEvent:1;				//bit 4
+			unsigned char CcsBreaker:1;					//bit 5
+			unsigned char CcsNoData:1;							//bit 6
+			unsigned char Ccsreserved_by_DIN_A:1;				//bit 7
+			//InfoVal[10]
+			unsigned char Ccsreserved_by_DIN_B:1;				//bit 0
+			unsigned char Ccsreserved_by_DIN_C:1;					//bit 1
+			unsigned char Ccsreserved_by_ISO_1:1;				//bit 2
+			unsigned char Ccsreserved_by_ISO_2:1;					//bit 3
+			unsigned char Ccsreserved_by_ISO_3:1;					//bit 4
+			unsigned char Ccsreserved_by_OEM_1:1;				//bit 5
+			unsigned char Ccsreserved_by_OEM_2:1;			//bit 6
+			unsigned char Ccsreserved_by_OEM_3:1;				//bit 7
+			//InfoVal[11]
+			unsigned char Ccsreserved_by_OEM_4:1;			//bit 0
+			unsigned char Ccsreserved_by_OEM_5:1;			//bit 1
+			unsigned char CcsSequenceError:1;			//bit 2
+			unsigned char CcsSignatureError:1;		//bit 3
+			unsigned char CcsUnknownSession:1;					//bit 4
+			unsigned char CcsServiceIDInvalid:1;					//bit 5
+			unsigned char CcsPaymentSelectionInvalid:1;					//bit 6
+			unsigned char CcsIdentificationSelectionInvalid:1;			//bit 7
+			//InfoVal[12]
+			unsigned char CcsServiceSelectionInvalid:1;			//bit 0
+			unsigned char CcsCertificateExpired:1;			//bit 1
+			unsigned char CcsCertificateNotYetValid:1;			//bit 2
+			unsigned char CcsCertificateRevoked:1;			//bit 3
+			unsigned char CcsNoCertificateAvailable:1;			//bit 4
+			unsigned char CcsCertChainError:1;			//bit 5
+			unsigned char CcsCertValidationError:1;			//bit 6
+			unsigned char CcsCertVerificationError:1;			//bit 7
+			//InfoVal[13]
+			unsigned char CcsContractCanceled:1;				//bit 0
+			unsigned char CcsChallengeInvalid:1;				//bit 1
+			unsigned char CcsWrongEnergyTransferMode:1;				//bit 2
+			unsigned char CcsWrongChargeParameter:1;				//bit 3
+			unsigned char CcsChargingProfileInvalid:1;				//bit 4
+			unsigned char CcsTariffSelectionInvalid:1;				//bit 5
+			unsigned char CcsEVSEPresentVoltageToLow:1;				//bit 6
+			unsigned char CcsPowerDeliveryNotApplied:1;			//bit 7
+			//InfoVal[14]
+			unsigned char CcsMeteringSignatureNotValid:1;			//bit 0
+			unsigned char CcsNoChargeServiceSelected:1;			//bit 1
+			unsigned char CcsContactorError:1;					//bit 2
+			unsigned char CcsCertificateNotAllowedAtThisEVSE:1;			//bit 3
+			unsigned char CcsGAChargeStop:1;				//bit 4
+			unsigned char CcsAlignmentError:1;					//bit 5
+			unsigned char CcsACDError:1;					//bit 6
+			unsigned char CcsAssociationError:1;			//bit 7
+			//InfoVal[15]
+			unsigned char CcsEVSEChargeAbort:1;				//bit 0
+			unsigned char CcsNoSupportedAppProtocol:1;					//bit 1
+			unsigned char CcsContractNotAccepted:1;				//bit 2
+			unsigned char CcsMOUnknown:1;					//bit 3
+			unsigned char CcsOEM_Prov_CertificateRevoke:1;				//bit 4
+			unsigned char CcsOEM_SubCA1_CertificateRevoked:1;		//bit 5
+			unsigned char CcsOEM_SubCA2_CertificateRevoked:1;		//bit 6
+			unsigned char CcsOEM_RootCA_CertificateRevoked:1;		//bit 7
+			//InfoVal[16]
+			unsigned char CcsMO_Prov_CertificateRevoked:1;			//bit 0
+			unsigned char CcsMO_SubCA1_CertificateRevoked:1;		//bit 1
+			unsigned char CcsMO_SubCA2_CertificateRevoked:1;		//bit 2
+			unsigned char CcsMO_RootCA_CertificateRevoked:1;		//bit 3
+			unsigned char CcsCPS_Prov_CertificateRevoked:1;		//bit 4
+			unsigned char CcsCPS_SubCA1_CertificateRevoked:1;		//bit 5
+			unsigned char CcsCPS_SubCA2_CertificateRevoked:1;		//bit 6
+			unsigned char CcsCPS_RootCA_CertificateRevoked:1;		//bit 7
+			//InfoVal[17]
+			unsigned char :5;					//bit 0~4 reserved
+			unsigned char CcsTT_EVSE_SLAC_init:1;				//bit 5
+			unsigned char CcsTP_match_response:1;			//bit 6
+			unsigned char CcsTT_match_sequence:1;			//bit 7
+			//InfoVal[18]
+			unsigned char CcsTT_EVSE_match_MNBC:1;				//bit 0
+			unsigned char CcsTP_EVSE_avg_atten_calc:1;				//bit 1
+			unsigned char CcsTT_match_response:1;			//bit 2
+			unsigned char CcsTP_EVSE_match_session:1;			//bit 3
+			unsigned char CcsTT_EVSE_assoc_session:1;			//bit 4
+			unsigned char CcsTT_EVSE_vald_toggle:1;			//bit 5
+			unsigned char CcsSeccSlacTimeoutCmMnbcSound:1;			//bit 6 reserved
+			unsigned char CcsSeccSlacTimeoutCmValidateReq:1;			//bit 7 reserved
+			//InfoVal[19]
+			unsigned char :3;					//bit 0~2 reserved
+			unsigned char CcsUDP_TT_match_join:1;			//bit 3
+			unsigned char CcsTCP_TT_match_join:1;				//bit 4
+			unsigned char CcsTP_amp_map_exchange:1;			//bit 5
+			unsigned char CcsTP_link_ready_notification:1;			//bit 6
+			unsigned char :1;				//bit 7 resetved
+			//InfoVal[20]
+			unsigned char :4;						//bit 0~3 reserved
+			unsigned char CcsSupportedAppProtocolRes:1;			//bit 4
+			unsigned char CcsSessionSetupRes:1;				//bit 5
+			unsigned char CcsServiceDiscoveryRes:1;				//bit 6
+			unsigned char CcsServicePaymentSelectionRes:1;		//bit 7
+			//InfoVal[21]
+			unsigned char CcsContractAuthenticationRes:1;			//bit 0
+			unsigned char CcsChargeParameterDiscoveryRes:1;			//bit 1
+			unsigned char CcsPowerDeliveryRes:1;			//bit 2
+			unsigned char CcsCableCheckRes:1;			//bit 3
+			unsigned char CcsPreChargeRes:1;					//bit 4
+			unsigned char CcsCurrentDemandRes:1;					//bit 5
+			unsigned char CcsWeldingDetectionRes:1;				//bit 6
+			unsigned char CcsSessionStopRes:1;					//bit 7
+			//InfoVal[22]
+			unsigned char CcsSequence_Time:1;						//bit 0
+			unsigned char CcsReadyToCharge_Performance_Time:1;				//bit 1
+			unsigned char CcsCommunicationSetup_Performance_Time:1;					//bit 2
+			unsigned char CcsCableCheck_Performance_Time:1;				//bit 3
+			unsigned char CcsCPState_Detection_Time:1;			//bit 4
+			unsigned char CcsCPOscillator_Retain_Time:1;					//bit 5
+			unsigned char CcsSeccTimeoutV2GPreChargePerformaceTime:1;			//bit 6
+			unsigned char :1;			//bit 7 reserved
+			//InfoVal[23]
+			unsigned char :3;					//bit 0~2 reserved
+			unsigned char CcsTP_GET_EV_TARGET_INFO:1;			//bit 3
+			unsigned char CcsTT_GET_EV_TARGET_INFO:1;		//bit 4
+			unsigned char CcsTP_GET_EV_BATTERY_INFO:1;		//bit 5
+			unsigned char CcsTT_GET_EV_BATTERY_INFO:1;		//bit 6
+			unsigned char CcsTP_EV_STOP_EVENT:1;				//bit 7
+			//InfoVal[24]
+			unsigned char CcsTT_EV_STOP_EVENT:1;			//bit 0
+			unsigned char CcsTP_EVSE_STOP_EVENT:1;			//bit 1
+			unsigned char CcsTT_EVSE_STOP_EVENT:1;			//bit 2
+			unsigned char CcsTP_GET_MISC_INFO:1;			//bit 3
+			unsigned char CcsTT_GET_MISC_INFO:1;			//bit 4
+			unsigned char CcsTP_DOWNLOAD_REQUEST:1;			//bit 5
+			unsigned char CcsTT_DOWNLOAD_REQUEST:1;			//bit 6
+			unsigned char CcsTP_START_BLOCK_TRANSFER:1;			//bit 7
+			//InfoVal[25]
+			unsigned char CcsTT_START_BLOCK_TRANSFER:1;		//bit 0
+			unsigned char CcsTP_DATA_TRANSFER:1;			//bit 1
+			unsigned char CcsTT_DATA_TRANSFER:1;			//bit 2
+			unsigned char CcsTP_DOWNLOAD_FINISH:1;			//bit 3
+			unsigned char CcsTT_DOWNLOAD_FINISH:1;			//bit 4
+			unsigned char CcsTP_ISOLATION_STATUS:1;			//bit 5
+			unsigned char CcsTT_ISOLATION_STATUS:1;			//bit 6
+			unsigned char CcsTP_CONNECTOR_INFO:1;			//bit 7
+			//InfoVal[26]
+			unsigned char CcsTT_CONNECTOR_INFO:1;			//bit 0
+			unsigned char CcsTT_RTC_INFO:1;				//bit 1
+			unsigned char CcsTP_RTC_INFO:1;			//bit 2
+			unsigned char CcsTP_EVSE_PRECHARGE_INFO:1;		//bit 3
+			unsigned char CcsTT_EVSE_PRECHARGE_INFO:1;			//bit 4
+			unsigned char CcsMSG_Sequence:1;			//bit 5
+			unsigned char CcsCAN_MSG_Unrecognized_CMD_ID:1;			//bit 6
+			unsigned char CcsDIN_Msg_Decode_Error:1;			//bit 7
+			//InfoVal[27]
+			unsigned char CcsDIN_Msg_Encode_Error:1;			//bit 0
+			unsigned char CcsISO1_Msg_Decode_Error:1;			//bit 1
+			unsigned char CcsISO1_Msg_Encode_Error:1;			//bit 2
+			unsigned char CcsISO2_Msg_Decode_Error:1;			//bit 3
+			unsigned char CcsISO2_Msg_Encode_Error:1;			//bit 4
+			unsigned char CcsCpStatus_Error:1;					//bit 5
+			unsigned char CcsUnexpectVolBeforeCharing_Error:1;	//bit 6
+			unsigned char CcsSeccNotReadyForCharging:1;			//bit 7 reserved
+			//InfoVal[28]
+			unsigned char CcsSeccTimeoutQCA7000Comm:1;			//bit 0
+			unsigned char CcsSeccFailForQCA7000SetKey:1;		//bit 1
+			unsigned char :6;									//bit 2~7 reserved
+			//InfoVal[29]
+			unsigned char ERROR_CODE_GBT_LOS_CC1 :1;									//bit 0
+			unsigned char ERROR_CODE_GBT_CONNECTOR_LOCK_FAIL :1;						//bit 1
+			unsigned char ERROR_CODE_GBT_BATTERY_INCOMPATIBLE :1;						//bit 2
+			unsigned char ERROR_CODE_GBT_BMS_BROAA_TIMEOUT :1;							//bit 3
+			unsigned char ERROR_CODE_GBT_CSU_PRECHARGE_TIMEOUT :1;						//bit 4
+			unsigned char ERROR_CODE_GBT_BMS_PRESENT_VOLTAGE_FAULT :1;					//bit 5
+			unsigned char ERROR_CODE_GBT_BMS_VOLTAGE_OVER_RANGE :1;						//bit 6
+			unsigned char ERROR_CODE_GBT_BSM_CHARGE_ALLOW_00_10MIN_COUUNTDONE :1;		//bit 7
+			//InfoVal[30]
+			unsigned char ERROR_CODE_GBT_WAIT_GROUNDFAULT_TIMEOUT :1;					//bit 0
+			unsigned char ERROR_CODE_GBT_ADC_MORE_THAN_10V :1;							//bit 1
+			unsigned char ERROR_CODE_GBT_ADC_MORE_THAN_60V :1;							//bit 2
+			unsigned char ERROR_CODE_GBT_CHARGER_GET_NORMAL_STOP_CMD :1;				//bit 3
+			unsigned char ERROR_CODE_GBT_CHARGER_GET_EMERGENCY_STOP_CMD :1;				//bit 4
+			unsigned char ERROR_CODE_GBT_ISOLATION_RESULT_FAIL :1;						//bit 5
+			unsigned char ERROR_CODE_GBT_MOTHER_BOARD_MISS_LINK :1;						//bit 6
+			unsigned char ERROR_CODE_GBT_OUTPUT_VOLTAGE_MORE_THAN_LIMIT :1;				//bit 7
+			//InfoVal[31]
+			unsigned char ERROR_CODE_GBT_REQ_CURRENT_MORE_THAN_LIMIT :1;				//bit 0
+			unsigned char ERROR_CODE_GBT_OUTPUT_VOLTAGE_MORE_THAN_10_PERCENT :1;		//bit 1
+			unsigned char ERROR_CODE_GBT_OUTPUT_VOLTAGE_DIFF_BCS_5_PERCENT :1;			//bit 2
+			unsigned char ERROR_CODE_GBT_STOP_ADC_MORE_THAN_10V :1;						//bit 3
+			unsigned char :4;															//bit 4 ~ 7 reserved
+			//InfoVal[32]
+			unsigned char :6;															//bit 0 ~ 5 reserved
+			unsigned char ERROR_CODE_CEM_BHM_TIMEOUT :1;								//bit 6
+			unsigned char ERROR_CODE_CEM_BRM_TIMEOUT :1;								//bit 7
+			//InfoVal[33]
+			unsigned char ERROR_CODE_CEM_BCP_TIMEOUT :1;								//bit 0
+			unsigned char ERROR_CODE_CEM_BRO_TIMEOUT :1;								//bit 1
+			unsigned char ERROR_CODE_CEM_BCL_TIMEOUT :1;								//bit 2
+			unsigned char ERROR_CODE_CEM_BCS_TIMEOUT :1;								//bit 3
+			unsigned char ERROR_CODE_CEM_BSM_TIMEOUT :1;								//bit 4
+			unsigned char ERROR_CODE_CEM_BST_TIMEOUT :1;								//bit 5
+			unsigned char ERROR_CODE_CEM_BSD_TIMEOUT :1;								//bit 6
+			unsigned char ERROR_CODE_CEM_BEM_OTHER_TIMEOUT :1;							//bit 7
+			//InfoVal[34]
+			unsigned char ERROR_CODE_BEM_CRM_TIMEOUT :1;			//bit 0
+			unsigned char ERROR_CODE_BEM_CRMAA_TIMEOUT :1;			//bit 1
+			unsigned char ERROR_CODE_BEM_CTS_CML_TIMEOUT :1;		//bit 2
+			unsigned char ERROR_CODE_BEM_CRO_TIMEOUT :1;			//bit 3
+			unsigned char ERROR_CODE_BEM_CCS_TIMEOUT :1;			//bit 4
+			unsigned char ERROR_CODE_BEM_CST_TIMEOUT :1;			//bit 5
+			unsigned char ERROR_CODE_BEM_CSD_TIMEOUT :1;			//bit 6
+			unsigned char ERROR_CODE_BEM_BEM_OTHER_TIMEOUT :1;		//bit 7
+			//InfoVal[35]
+			unsigned char :2;										//bit 0 ~ 1
+			unsigned char ERROR_CODE_BST_SOC_GOAL :1;				//bit 2
+			unsigned char ERROR_CODE_BST_TOTAL_VOLTAGE_GOAL :1;		//bit 3
+			unsigned char ERROR_CODE_BST_CELL_VOLTAGE_GOAL :1;		//bit 4
+			unsigned char ERROR_CODE_BST_GET_CST :1;				//bit 5
+			unsigned char ERROR_CODE_BST_ISOLATION :1;				//bit 6
+			unsigned char ERROR_CODE_BST_OUTPUT_CONNECTOR_OTP :1;	//bit 7
+			//InfoVal[36]
+			unsigned char ERROR_CODE_BST_COMPONENT :1;				//bit 0
+			unsigned char ERROR_CODE_BST_CHARGE_CONNECTOR :1;		//bit 1
+			unsigned char ERROR_CODE_BST_OTP :1;					//bit 2
+			unsigned char ERROR_CODE_BST_OTHER :1;					//bit 3
+			unsigned char ERROR_CODE_BST_HIGH_V :1;					//bit 4
+			unsigned char ERROR_CODE_BST_CC2 :1;					//bit 5
+			unsigned char ERROR_CODE_BST_CURRENT :1;				//bit 6
+			unsigned char ERROR_CODE_BST_VOLTAGE :1;				//bit 7
+			//InfoVal[37]
+			unsigned char ERROR_CODE_GET_BST_NO_REASON :1;			//bit 0
+			unsigned char :5;										//bit 1 ~ 5 reserved
+			unsigned char ERROR_CODE_BSM_CELL_OVER_VOLTAGE :1;		//bit 6
+			unsigned char ERROR_CODE_BSM_CELL_UNDER_VOLTAGE :1;		//bit 7
+			//InfoVal[38]
+			unsigned char ERROR_CODE_BSM_OVER_SOC :1;				//bit 0
+			unsigned char ERROR_CODE_BSM_UNDER_SOC :1;				//bit 1
+			unsigned char ERROR_CODE_BSM_CURRENT :1;				//bit 2
+			unsigned char ERROR_CODE_BSM_TEMPERATURE :1;			//bit 3
+			unsigned char ERROR_CODE_BSM_ISOLATE :1;				//bit 4
+			unsigned char ERROR_CODE_BSM_OUTPUT_CONNECTOR :1;		//bit 5
+			unsigned char :1;										//bit 6
+			unsigned char EV_Full_Charging:1;                       //bit 7
+            //InfoVal[39]
+            unsigned char CHADEMO_BMS_CHARGE_ALLOW_ERROR:1;         //bit 0
+            unsigned char CHADEMO_OUTPUT_VOLTAGE_MORE_THEN_10_PERCENT:1; //bit 1
+            unsigned char CHADEMO_ADC_LESS_THAN_10V:1;              //bit 2
+            unsigned char Stop_by_EV_with_unknow_reason:1;          //bit 3
+            unsigned char Stop_by_EVSE_condition:1;                 //bit 4
+            unsigned char :3;                                       //bit 5 ~ 7 reserved
+			//InfoVal[40]
+			unsigned char BackendDisconnectedViaEthernet:1;			//bit 0
+			unsigned char BackendDisconnectViaWiFi:1;				//bit 1
+			unsigned char BackendDisconnectVia4G:1;					//bit 2
+			unsigned char BackendRemoteStart:1;						//bit 3
+			unsigned char BackendRemoteStop:1;						//bit 4
+			unsigned char BackendRemoteReset:1;						//bit 5
+			unsigned char AuthorizationFailed:1;					//bit 6
+			unsigned char :1;										//bit 7	reserved
+		}bits;
+	}InfoEvents;
+};
+
+struct StatusCodeData
+{
+	struct FaultCodeData	FaultCode;
+	struct AlarmCodeData	AlarmCode;
+	struct InfoCodeData		InfoCode;
+};
+/**************************************************************************************/
+/**************************PSU Share memory***************************************/
+/**************************************************************************************/
+typedef union
+{
+    unsigned int PsuGroupErrorValue;
+    struct
+    {
+        unsigned int PsuFailure:1;              // 0: no effect,    1: Psu Failure
+        unsigned int res:31;
+    }bits;
+}PsuGroupError;
+
+struct PsuModuleVer
+{
+	unsigned char 		FwPrimaryVersion[16];
+	unsigned char 		FwSecondVersion[16];
+};
+
+/*Following are the information for each PSU module*/
+struct PsuModuleData
+{
+	unsigned char 		AssignID;
+	unsigned char 		PhysicalID;
+	unsigned char 		GroupID;
+	unsigned char 		Address;
+	unsigned char 		FireWireIndex;
+	unsigned char 		FwVersion[16];
+	unsigned char 		SerialNumber[32];
+	unsigned char 		StateMachine;			//0: Identification,  1:Operation,  2: Alarm,  3: Failure,  s4:Upgrade
+	unsigned char 		OutputPowerSwitch;	//0: D.D normal OFF,  1: D.D emergency OFF,  2: D.D ON
+	unsigned short 	FanSpeed_1;			//RPM
+	unsigned short 	FanSpeed_2;			//RPM
+	unsigned short 	FanSpeed_3;			//RPM
+	unsigned short 	FanSpeed_4;			//RPM
+	unsigned short 	InputVoltage_Type;	//0x00 = Line to Line Vol, 0x01 = Line to Neutral Vol
+	unsigned short 	InputVoltageL1;		//abcd=abc.d volt
+	unsigned short 	InputVoltageL2;		//abcd=abc.d volt
+	unsigned short 	InputVoltageL3;		//abcd=abc.d volt
+	unsigned short 	InputCurrentL1;		//abcd=abc.d amp
+	unsigned short 	InputCurrentL2;		//abcd=abc.d amp
+	unsigned short 	InputCurrentL3;		//abcd=abc.d amp
+	unsigned short 	PresentOutputVoltage;	//abcd=abc.d volt
+	unsigned short 	PresentOutputCurrent;	//abcd=abc.d amp
+	unsigned short 	AvailableCurrent;		// unit: 0.1A
+	unsigned int 		AvailablePower;		// unit: 0.1kW
+	char 				CriticalTemp1;			//0x00: -60¢XC  ~  0xFE: 194¢XC, resolution: 1¢XC, offset: -60¢XC, 0xFF: invalid
+	char 				CriticalTemp2;			//0x00: -60¢XC  ~  0xFE: 194¢XC, resolution: 1¢XC, offset: -60¢XC, 0xFF: invalid
+	char 				CriticalTemp3;			//0x00: -60¢XC  ~  0xFE: 194¢XC, resolution: 1¢XC, offset: -60¢XC, 0xFF: invalid
+	char 				ExletTemp;			//0x00: -60¢XC  ~  0xFE: 194¢XC, resolution: 1¢XC, offset: -60¢XC, 0xFF: invalid
+	char 				InletTemp_1;			//0x00: -60¢XC  ~  0xFE: 194¢XC, resolution: 1¢XC, offset: -60¢XC, 0xFF: invalid
+	char 				InletTemp_2;			//0x00: -60¢XC  ~  0xFE: 194¢XC, resolution: 1¢XC, offset: -60¢XC, 0xFF: invalid
+	char 				InletTemp;			//0x00: -60¢XC  ~  0xFE: 194¢XC, resolution: 1¢XC, offset: -60¢XC, 0xFF: invalid
+	char 				OutletTemp;			//0x00: -60¢XC  ~  0xFE: 194¢XC, resolution: 1¢XC, offset: -60¢XC, 0xFF: invalid
+	unsigned int 		AlarmCode;
+	unsigned int 		FaultCode;			//
+	unsigned int 		IAvailableCurrent;		            // unit: 0.1A
+    unsigned short  PresentMaxOutputVoltage;//abcd=abc.d volt
+    unsigned short  KwAvailablePower;       // unit: 0.1 kw
+};
+
+/*Following are the information for each PSU Group*/
+struct PsuGroupData
+{
+	unsigned char           GroupPresentPsuQuantity;
+	unsigned char           GroupOutputPowerSwitch;         //0: D.D normal OFF,  1: D.D emergency OFF,  2: D.D ON
+	unsigned short          GroupTargetOutputVoltage;       //abcd=abc.d volt
+	unsigned short          GroupTargetOutputCurrent;       //abcd=abc.d amp
+	unsigned short          GroupAvailableCurrent;          // unit: 0.1A
+	unsigned int            GroupAvailablePower;            // unit: 0.1kW
+	unsigned int            GroupRealOutputPower;           // unit: 1kW
+	unsigned short          GroupPresentOutputVoltage; 	    // unit: 0.1V
+	unsigned short          GroupPresentOutputCurrent;      // unit: 0.1A
+	unsigned int            GroupPresentOutputPower;        // unit: 0.1kW
+	struct PsuModuleData 	PsuModule[MAX_PSU_QUANTITY];
+	PsuGroupError           GroupErrorFlag;
+    unsigned short          TotalIAvailableCurrent;         // unit: 0.1A
+    unsigned short          TempIAvailableCurrent;          // unit: 0.1A
+    unsigned short          StableIAvailableCurrent;        // unit: 0.1A
+    unsigned short          StableCurrentCounter;           // stable current counter
+    unsigned short          GroupMaxVoltage;                // unit: 0.1V
+    unsigned char           IsUsing;                        // 0 : none use
+    unsigned char           UsingTarget;                    // 0xFF : Check
+    unsigned char           PwSwitchStatus;
+    unsigned short          TotalRatingPower;               // unit: 1kW
+};
+
+/*Following is the information for system all PSU*/
+struct PsuData
+{
+    unsigned char           SystemInitialPsuQuantity;       // psu quantity after ac/dc contactor on
+	unsigned char           SystemPresentPsuQuantity;
+	unsigned short          SystemAvailableCurrent;			//abcd=abc.d amp
+	unsigned int            SystemAvailablePower;			//Watt
+	struct PsuGroupData     PsuGroup[4];
+	unsigned char           GroupCount;
+	unsigned char           Work_Step;
+	struct PsuModuleVer     PsuVersion[MAX_PSU_QUANTITY];
+	unsigned char           PsuStopChargeFlag;
+};
+
+struct SmartTimeChk
+{
+    struct timespec     FetchLoopTime;
+    unsigned char       IsFetchStart;
+
+    struct timespec     ReleaseLoopTime;
+    unsigned char       IsReleaseStart;
+};
+
+struct DynamicFetchCtrl
+{
+    unsigned char       ShareGroup;         // 255 : None
+    unsigned char       FetchLoopStep;      // 0 : None, 1 : Output Vol, 2 : RCB ON, 3 : Current sharing, 4 : Finish
+    unsigned short      ShareTargetCurrent; // 0.1A
+    unsigned char       TargetRelay;        // 255 : None
+};
+
+struct DynamicReleaseCtrl
+{
+    unsigned char       ReleaseGroup;       // 255 : None
+    unsigned char       ReleaseLoopStep;    // 0 : None, 1 : Limit Pwr, 2 : Pwr OFF, 3. RCB OFF, 4. Finish
+    float               CheckOutPwrIsStable;// 0.1kw
+    unsigned char       TargetRelay;        // 255 : None
+    unsigned char       AutoRelease;
+
+    float               LimitCurCap;        // Inform 0.1A
+    float               LimitPwrCap;        // Inform 0.1kw
+    float               LimitCur;           // Target 0.1A
+    float               LimitPwr;           // Target 0.1kw
+};
+
+struct ConnInfo
+{
+    unsigned char ConnectorStaus;
+    unsigned char NeedToFetch;
+};
+
+struct SmartBoxData
+{
+    struct ConnInfo     ConnectorStatus[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];     // Connector 1 / 2 Status : None, Wait, Using
+    struct ConnInfo     AnotherConnectorStatus[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
+    unsigned char       ConnectorUsingGroupCount[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY]; // Psu group for connector
+    struct SmartTimeChk SmartChk[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
+    struct DynamicFetchCtrl Dynamic4Fetch[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
+    struct DynamicReleaseCtrl Dynamic4Release[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
+    unsigned char       ParallelRelayStatus[3];
+    unsigned char       RcbParallelStatus[3];
+};
+
+/************************************************************************************/
+/**************************CHAdeMO protocol Share memory*********************/
+/**************************************************************************************/
+struct CHAdeMOEvData
+{
+	unsigned char  SupportDynamicControl;	//110.0
+										//					bit0=1:supported
+	unsigned char  SupportHighCurrent;		//110.0
+										//					bit1=1:supported
+	unsigned char  MiniChargeCurrent;		//100.0				0~200(A) (unit:1A)
+										//					0x00: request for current equivalent to 1.5kW
+										//					0x01: no request
+										//					0x02: request of 1A and following are the same rule
+	unsigned short MaxiBatteryVoltage;		//100.5,100.4 			0~600(V) (unit:1V)
+	unsigned short MaxiChargingTime;			//101.2,101.1			10(sec.)~255(min.)	(Unit:sec)
+										//					Set 0xFF to 101.1 (Unit: 10sec) in case 101.2 (Unit: 1min) is used
+	unsigned char  EstimatChargingTime;		//101.3				0~254(min.)	(Unit:sec)
+										//					Display Only
+	unsigned short TotalBatteryCapacity;		//101.6,101.5 			0.1~6553.5(kWh)	(unit:0.1 kWh)
+	unsigned char  ProtocolVersion;			//102.0				0~255
+										//					0x02: CHAdeMO specification ver.1.2
+	unsigned short TargetBatteryVoltage;		//102.2,102.1 			0~600(V) (unit:1V)
+	unsigned short ChargingCurrentRequest;	//102.3				0~200(A) (unit:1A)
+										//110.2,110.1 			0~1023(A) (unit:1A)
+	unsigned char  BatteryAlarm;				//102.4				>0:alarm
+										//					bit0=1:Battery overvoltage
+										//					bit1=1:Battery undervoltage
+										//					bit2=1:Battery current deviation error
+										//					bit3=1:High battery temperature
+										//					bit4=1:Battery voltage deviation error
+	unsigned char  EvDetection;				//102.5
+										//					bit0=0:Vehicle charging disabled,	(stop charging)
+										//					bit0=1:Vehicle charging enabled,
+										//					bit1=0:¡§Parking¡¨ position
+										//					bit1=1:other position				(stop charging)
+										//					bit2=0:Charging system normal
+										//					bit2=1:Charging system error		(stop charging)
+										//					bit3=0:EV contactor close or during welding detection
+										//					bit3=1:EV contactor open or termination of welding detection (stop charging)
+										//					bit4=0:No stop request before charging
+										//					bit4=1:Normal stop request before charging	(stop charging)
+	unsigned char  SOC;					//102.6				0~100(%) (unit:%)
+										//					Display Only
+	unsigned char  Communicating;			//					it is true if receive EV CAN message within every 1500ms
+	unsigned char  PresentMsgFlowStatus;	//
+};
+
+struct CHAdeMOEvseData
+{
+	unsigned char 	SelfTest_Comp;
+	unsigned char	version[16];									//Chademo firmware version
+	unsigned char  SupportDynamicControl;	//118.0
+										//					bit0=1:supported
+	unsigned char  SupportHighCurrent;		//118.0
+										//					bit1=1:supported
+	unsigned short  AvailableOutputVoltage;	//108.2,108.1 			0~600(V) (unit:1V)
+	unsigned short  AvailableOutputCurrent;	//108.3				0~255(A) (unit:1A)
+										//118.2,118.1 			0~1023(A) (unit:1A)
+	unsigned short  ThresholdVoltage;			//108.5,108.4 			0~600(V) (unit:1V)
+	unsigned char   ConnectorTemperatureP;	//108.6				-40~215(degC) (unit:degC) //value 0=-40	[NISSAN customized]
+	unsigned char   ConnectorTemperatureN;	//108.7				-40~215(degC) (unit:degC) //value 0=-40	[NISSAN customized]
+	unsigned char   ProtocolVersion;			//109.0				0~255
+										//					0x00: CHAdeMO specification 0.9 and earlier
+										//					0x01: CHAdeMO specification 0.9 and 0.9.1
+										//					0x02: CHAdeMO specification 1.0.0, 1.0.1, 1.1 and 1.2
+	unsigned short  PresentOutputVoltage;		//109.2,109.1	 		0~600(V) (unit:1V)
+	unsigned short   PresentOutputCurrent;		//109.3				0~255(A) (unit:1A)
+										//118.4,118.3			0~1023(A) (unit:1A)
+	unsigned char   EvseDetection;			//109.5
+										//					bit0=0:not charging state now
+										//					bit0=1:charging state now
+										//					bit1=0:EVSE normal
+										//					bit1=1:EVSE error
+										//					bit2=0:Not Energizing state
+										//					bit2=1:Energizing state
+										//					bit3=0:No Battery incompatibility
+										//					bit3=1:Battery incompatibility
+										//					bit4=0:No Charging system error
+										//					bit4=1:Charging system error
+										//					bit5=0:No Charging stop control
+										//					bit5=1:Charging stop control
+	unsigned short RemainChargingTime;		//109.7,109.6			10(sec.)~255(min.)	(Unit:sec)
+										//					Set 0xFF to 109.6 (Unit: 10sec) in case 109.7 (Unit: 1min) is used
+	unsigned char  HighPowerCondition;		//118.5
+										//					bit0=0:Present charging current H¡¦118.3,H¡¦118.4¡¨ is less than or equal to rated current of a charging cable
+										//					bit0=1:Present charging current H¡¦118.3,H¡¦118.4¡¨ is exceeds to rated current of a charging cable
+										//					bit1=1:charging cable Cooling function Operating Installed
+										//					bit2=1:charging cable Current limiting function
+										//					bit3=1:charging connector Cooling function Operating
+										//					bit4=1:charging connector Current limiting function Installed
+										//					bit5=1:charging connector Over-temperature protection Installed
+										//					bit6=1:Functional safety Applied
+	unsigned int 	MaxiGroupPower;			//					XXXXXXXX (Unit:Watt)depend on which group to be used
+	unsigned int 	MaxiGroupCurrent;			//					XXXXXXXX (unit:1A)depend on which group to be used
+	unsigned short  ApplyOutputVoltage;		// 					0~600(V) (unit:1V)
+	unsigned short  ElapseChargingTime;		//					(Unit:sec)
+	unsigned short  ElapseEnergy;				//					(Unit:10xkWh)
+	unsigned char	EvboardStatus;			// 	0 : init
+};
+
+struct CHAdeMOData
+{
+	struct CHAdeMOEvData 		ev[CHAdeMO_QUANTITY];
+	struct CHAdeMOEvseData 	evse[CHAdeMO_QUANTITY];
+};
+
+/************************************************************************************/
+/**************************GBT protocol Share memory*********************/
+/**************************************************************************************/
+struct GBTEvData
+{
+	unsigned short MaxiBatteryVoltage;		// 0~600(V) (unit:1V)
+	unsigned short MaxiChargingTime;		// 10(sec.)~255(min.)	(Unit:sec)
+
+	unsigned char  EstimatChargingTime;		// 0~254(min.)	(Unit:sec)
+
+	unsigned short TotalBatteryCapacity;	// 0.1~6553.5(kWh)	(unit:0.1 kWh)
+	unsigned char  ProtocolVersion;			// 0~255
+
+	unsigned short TargetBatteryVoltage;	// 0~600(V) (unit:1V)
+	unsigned short ChargingCurrentRequest;	// 0~200(A) (unit:1A)
+											// 0~1023(A) (unit:1A)
+
+	unsigned char  EvDetection;				//102.5
+										//					bit0=0:Vehicle charging disabled,	(stop charging)
+										//					bit0=1:Vehicle charging enabled,
+										//					bit1=0:¡§Parking¡¨ position
+										//					bit1=1:other position				(stop charging)
+										//					bit2=0:Charging system normal
+										//					bit2=1:Charging system error		(stop charging)
+										//					bit3=0:EV contactor close or during welding detection
+										//					bit3=1:EV contactor open or termination of welding detection (stop charging)
+										//					bit4=0:No stop request before charging
+										//					bit4=1:Normal stop request before charging	(stop charging)
+	unsigned char  SOC;					//102.6				0~100(%) (unit:%)
+										//					Display Only
+	unsigned char  PresentMsgFlowStatus;	//
+};
+
+struct GBTEvseData
+{
+	unsigned char 	SelfTest_Comp;
+	unsigned char	version[16];				// GBT firmware version
+
+	unsigned short  AvailableOutputVoltage;		// 0~600(V) (unit:1V)
+	unsigned short  AvailableOutputCurrent;		// 0~255(A) (unit:1A)
+
+	unsigned char   ConnectorTemperatureP;	// -40~215(degC) (unit:degC) //value 0=-40	[NISSAN customized]
+	unsigned char   ConnectorTemperatureN;	// -40~215(degC) (unit:degC) //value 0=-40	[NISSAN customized]
+
+	unsigned short  PresentOutputVoltage;		// 0~600(V) (unit:1V)
+	unsigned short  PresentOutputCurrent;		// 0~255(A) (unit:1A)
+
+	unsigned short RemainChargingTime;		//109.7,109.6			10(sec.)~255(min.)	(Unit:sec)
+	unsigned char	EvboardStatus;			// 	0 : init
+};
+
+struct GBTData
+{
+	struct GBTEvData 		ev[GB_QUANTITY];
+	struct GBTEvseData 		evse[GB_QUANTITY];
+};
+
+/************************************************************************************/
+/**************************CCS protocol Share memory***************************/
+/**************************DIN70121: 201412***************************************/
+/**************************ISO15118_2014: 2014************************************/
+/**************************ISO15118_2018: 2018************************************/
+/************************************************************************************/
+typedef enum boolean { FALSE, TRUE } BOOL;
+enum ResponseCodeType_DIN70121		{ OK_DIN70121 = 0, OK_NewSessionEstablished_DIN70121 = 1, OK_OldSessionJoined_DIN70121 = 2, OK_CertificateExpiresSoon_DIN70121 = 3,
+									   FAILED_DIN70121 = 4, FAILED_SequenceError_DIN70121 = 5, FAILED_ServiceIDInvalid_DIN70121 = 6, FAILED_UnknownSession_DIN70121 = 7,
+									   FAILED_ServiceSelectionInvalid_DIN70121 = 8, FAILED_PaymentSelectionInvalid_DIN70121 = 9, FAILED_CertificateExpired_DIN70121 = 10,
+									   FAILED_SignatureError_DIN70121 = 11, FAILED_NoCertificateAvailable_DIN70121 = 12, FAILED_CertChainError_DIN70121 = 13, FAILED_ChallengeInvalid_DIN70121 = 14,
+									   FAILED_ContractCanceled_DIN70121 = 15, FAILED_WrongChargeParameter_DIN70121 = 16, FAILED_PowerDeliveryNotApplied_DIN70121 = 17,
+									   FAILED_TariffSelectionInvalid_DIN70121 = 18, FAILED_ChargingProfileInvalid_DIN70121 = 19, FAILED_EVSEPresentVoltageToLow_DIN70121 = 20,
+									   FAILED_MeteringSignatureNotValid_DIN70121 = 21, FAILED_WrongEnergyTransferType_DIN70121 = 22};
+enum ResponseCodeType_ISO15118_2014	{ OK_ISO15118_2014 = 0, OK_NewSessionEstablished_ISO15118_2014 = 1, OK_OldSessionJoined_ISO15118_2014 = 2, OK_CertificateExpiresSoon_ISO15118_2014 = 3,
+									   FAILED_ISO15118_2014 = 4, FAILED_SequenceError_ISO15118_2014 = 5, FAILED_ServiceIDInvalid_ISO15118_2014 = 6, FAILED_UnknownSession_ISO15118_2014 = 7,
+									   FAILED_ServiceSelectionInvalid_ISO15118_2014 = 8, FAILED_PaymentSelectionInvalid_ISO15118_2014 = 9, FAILED_CertificateExpired_ISO15118_2014 = 10,
+									   FAILED_SignatureError_ISO15118_2014 = 11, FAILED_NoCertificateAvailable_ISO15118_2014 = 12, FAILED_CertChainError_ISO15118_2014 = 13, FAILED_ChallengeInvalid_ISO15118_2014 = 14,
+									   FAILED_ContractCanceled_ISO15118_2014 = 15, FAILED_WrongChargeParameter_ISO15118_2014 = 16, FAILED_PowerDeliveryNotApplied_ISO15118_2014 = 17,
+									   FAILED_TariffSelectionInvalid_ISO15118_2014 = 18, FAILED_ChargingProfileInvalid_ISO15118_2014 = 19, FAILED_MeteringSignatureNotValid_ISO15118_2014 = 20,
+									   FAILED_NoChargeServiceSelected_ISO15118_2014 = 21, FAILED_WrongEnergyTransferMode_ISO15118_2014 = 22, FAILED_ContactorError_ISO15118_2014 = 23,
+									   FAILED_CertificateNotAllowedAtThisEVSE_ISO15118_2014 = 24, FAILED_CertificateRevoked_ISO15118_2014 = 25  };
+enum ResponseCodeType_ISO15118_2018	{ OK_ISO15118_2018 = 0, OK_NewSessionEstablished_ISO15118_2018 = 1, OK_OldSessionJoined_ISO15118_2018 = 2, OK_CertificateExpiresSoon_ISO15118_2018 = 3,
+									   OK_IsolationValid_ISO15118_2018 = 4, OK_IsolationWarning_ISO15118_2018 = 5, WARNING_CertificateExpired_ISO15118_2018 = 6, WARNING_NoCertificateAvailable_ISO15118_2018 = 7,
+									   WARNING_CertValidationError_ISO15118_2018 = 8, WARNING_CertVerificationError_ISO15118_2018 = 9, WARNING_ContractCanceled_ISO15118_2018 = 10,
+									   FAILED_ISO15118_2018 = 11, FAILED_SequenceError_ISO15118_2018 = 12, FAILED_ServiceIDInvalid_ISO15118_2018 = 13, FAILED_UnknownSession_ISO15118_2018 = 14,
+									   FAILED_ServiceSelectionInvalid_ISO15118_2018 = 15, FAILED_SignatureError_ISO15118_2018 = 16, FAILED_IdentificationSelectionInvalid_ISO15118_2018 = 17,
+									   FAILED_ChallengeInvalid_ISO15118_2018 = 18, FAILED_WrongChargeParameter_ISO15118_2018 = 19, FAILED_IsolationFault_ISO15118_2018 = 20,
+									   FAILED_PowerDeliveryNotApplied_ISO15118_2018 = 21, FAILED_TariffSelectionInvalid_ISO15118_2018 = 22, FAILED_ChargingProfileInvalid_ISO15118_2018 = 23,
+									   FAILED_MeteringSignatureNotValid_ISO15118_2018 = 24, FAILED_NoChargeServiceSelected_ISO15118_2018 = 25, FAILED_WrongEnergyTransferMode_ISO15118_2018 = 26,
+									   FAILED_ContactorError_ISO15118_2018 = 27, FAILED_CertificateRevoked_ISO15118_2018 = 28, FAILED_CertificateNotYetValid_ISO15118_2018 = 29 };
+enum EVSENotificationType		 		{ None = 0, StopCharging = 1, ReNegotiation = 2};
+enum ServiceCategoryType 				{ EVCharging = 0, Internet = 1, ContractCertificate = 2, OtherCustom = 3};
+enum PaymentOptionType 		      		{ Contract = 0, ExternalPayment = 1};
+/*enum EVSESupportedEnergyTransferType 	{ AC_single_phase_core = 0, AC_three_phase_core = 1, DC_core = 2, DC_extended = 3,
+									  DC_combo_core = 4, DC_dual = 5, AC_core1p_DC_extended = 6, AC_single_DC_core = 7,
+									  AC_single_phase_three_phase_core_DC_extended = 8, AC_core3p_DC_extended = 9};*/
+enum EnergyTransferModeType			{ AC_single_phase_core = 0, AC_three_phase_core = 1, DC_core = 2, DC_extended = 3,
+									  DC_combo_core = 4, DC_unique = 5};
+//enum identificationOptionType 			{ Contract = 0, ExternalIdentification = 1};
+enum unitSymbolType_DIN70121			{ h_DIN70121 = 0, m_DIN70121 = 1, s_DIN70121 = 2, A_DIN70121 = 3, Ah_DIN70121 = 4, V_DIN70121 = 5, VA_DIN70121 = 6, W_DIN70121 = 7, Ws_DIN70121 = 8, Wh_DIN70121 = 9};
+enum unitSymbolType_ISO15118_2014		{ h_ISO15118_2014 = 0, m_ISO15118_2014 = 1, s_ISO15118_2014 = 2, A_ISO15118_2014 = 3, V_ISO15118_2014 = 4, W_ISO15118_2014 = 5, Wh_ISO15118_2014 = 6};
+enum ProcessingType					{ Finished = 0, Ongoing = 1, Ongoing_WaitingForCustomerInteraction = 2};
+enum EVSEProcessingType_DIN70121		{ Finished_DIN70121 = 0, Ongoing_DIN70121 = 1};
+enum EVSEProcessingType_ISO15118_2014	{ Finished_ISO15118_2014 = 0, Ongoing_ISO15118_2014 = 1, Ongoing_WaitingForCustomerInteraction_ISO15118_2014=2 };
+enum DC_EVErrorCodeType 		  		{ NO_ERROR = 0, FAILED_RESSTemperatureInhibit = 1, FAILED_EVShiftPosition = 2, FAILED_ChargerConnectorLockFault = 3,
+									  FAILED_EVRESSMalfunction = 4, FAILED_ChargingCurrentdifferential = 5, FAILED_ChargingVoltageOutOfRange = 6,
+									  Reserved_A = 7, Reserved_B = 8, Reserved_C = 9, FAILED_ChargingSystemIncompatibility = 10, NoData = 11};
+enum IsolationLevelType_DIN70121 		{ Invalid_DIN70121 = 0, Valid_DIN70121 = 1, Warning_DIN70121 = 2, Fault_DIN70121 = 3};
+enum IsolationLevelType_ISO15118_2014		{ Invalid_ISO15118_2014 = 0, Valid_ISO15118_2014 = 1, Warning_ISO15118_2014 = 2, Fault_ISO15118_2014 = 3, No_IMD_ISO15118_2014	 = 4};
+enum DC_EVSEStatusCodeType			{ EVSE_NotReady = 0, EVSE_Ready = 1, EVSE_Shutdown = 2, EVSE_UtilityInterruptEvent = 3,
+						 			  EVSE_IsolationMonitoringActive = 4, EVSE_EmergencyShutdown = 5, EVSE_Malfunction = 6,
+						 			  Reserved_8 = 7, Reserved_9 = 8};
+enum ScheduleOriginType				{ EV = 0, SA = 1};
+enum ChargeProgressType_ISO15118_2014	{start_ISO15118_2014 = 0, Stop_ISO15118_2014 = 1, Renegotiate_ISO15118_2014 = 2};
+enum ChargeProgressType_ISO15118_2018	{start_ISO15118_2018 = 0, Renegotiate_ISO15118_2018 = 1, Standby_ISO15118_2018 = 2, Stop_ISO15118_2018 = 3};
+enum evOperationType					{Charge = 0, Discharge = 1, Standby = 2};
+enum mechanicalChargingDeviceStatusType {Home = 0, Moving = 1, EndPosition = 2};
+enum EV_CP_StatusType					{A = 0, B = 1, C = 2, D = 3, E = 4, F = 5};
+enum EV_Error_Status_CodeType			{ No_EV_Error = 0, EV_FAILED_EmergencyEvent = 1, EV_FAILED_Breaker = 2, EV_FAILED_RESSTemperatureInhibit = 3,
+						 			  EV_FAILED_RESS = 4, EV_FAILED_ChargingCurrentDifferential = 5, EV_FAILED_ChargingVoltageOutOfRange = 6,
+						 			  Reserved_by_ISO_1 = 7,  Reserved_by_ISO_2 = 8, Reserved_by_ISO_3 = 9, OEM1 = 10,
+						 			  OEM2 = 11,  OEM3 = 12, OEM4 = 13};
+enum IsolationStatusType				{ Invalid = 0, Safe = 1, Warning = 2, Fault = 3};
+enum ChargingSessionType				{ Terminate = 0, Pause = 1};
+enum CostKindType						{ relativePricePercentage = 0, RenewableGenerationPercentage = 1, CarbonDioxideEmission = 2};
+
+
+
+struct PhysicalValueType_DIN70121 				//The final physical value is determined by: Value * 10 ^ Multiplier [Unit]
+{
+	int									Multiplier;			//range: -3..+3
+	enum unitSymbolType_DIN70121			Unit;
+	short 								Value;
+};
+struct PhysicalValueType_ISO15118_2014			//The final physical value is determined by: Value * 10 ^ Multiplier [Unit]
+{
+	int									Multiplier;			//range: -3..+3
+	enum unitSymbolType_ISO15118_2014		Unit;
+	short 								Value;
+};
+struct PhysicalValueType_ISO15118_2018			//The final physical value is determined by: Value * 10 ^ Exponent [Unit]
+{
+	int									Exponent;		//range: -3..+3
+	short 								Value;
+};
+struct AppProtocolType
+{
+	unsigned char	ProtocolNamespace[100];
+	unsigned int	VersionNumberMajor;
+	unsigned int	VersionNumberMinor;
+	unsigned char	SchemaID;
+	unsigned char	Priority;					//range 1..20
+};
+struct ACD_SSEnergyTransferModeType
+{
+	unsigned char	EVID[20];
+};
+struct EVSEStatusType
+{
+	unsigned short				NotificationMaxDelay;	//in seconds
+	enum EVSENotificationType	EVSENotification;
+};
+struct ServiceIDListType
+{
+	unsigned short	ServiceID[10];	//refer to chapter 8.6.2.1 Table 192
+};
+struct PaymentOptionListType
+{
+	enum PaymentOptionType	PaymentOption[2];
+};
+struct ServiceTagType
+{
+	unsigned short				ServiceID;
+	unsigned char				ServiceName[32];//Optional Element
+	enum ServiceCategoryType	ServiceCategory;
+	unsigned char				ServiceScope[32];//Optional Element
+};
+struct ServiceType_DIN70121
+{
+	struct ServiceTagType		ServiceTag;
+	BOOL					FreeService;
+};
+struct ServiceType_ISO15118_2014
+{
+	unsigned short				ServiceID;
+	unsigned char				ServiceName[32];	//Optional
+	enum ServiceCategoryType	ServiceCategory;
+	unsigned char				ServiceScope[64];	//Optional
+	BOOL					FreeService;
+};
+/*struct ServiceType_ISO15118_2018
+{
+	unsigned short				ServiceID;
+	BOOL					FreeService;
+}; */
+struct SupportedEnergyTransferModeType
+{
+	enum EnergyTransferModeType	EnergyTransferMode[6];
+};
+struct ServiceChargeType
+{
+	struct ServiceType_DIN70121				Services;
+	//enum EVSESupportedEnergyTransferType		EnergyTransferType;
+	enum EnergyTransferModeType			EnergyTransferType;
+};
+
+struct ChargeServiceType
+{
+	struct ServiceType_ISO15118_2014			Services;
+	struct SupportedEnergyTransferModeType	SupportedEnergyTransferMode;
+};
+struct ServiceListType
+{
+	struct ServiceType_ISO15118_2014			Service[8];
+};
+struct IdentificationOptionListType
+{
+	enum PaymentOptionType				IdentificationOption[2];
+};
+struct ParameterType
+{
+	unsigned char							Name[32];
+	struct PhysicalValueType_ISO15118_2014		PhysicalValue_ISO15118_2014;
+	struct PhysicalValueType_ISO15118_2018		PhysicalValue_ISO15118_2018;
+};
+struct ParameterSetType
+{
+	short 				ParameterSetID;
+	struct ParameterType	Parameter[16];
+};
+struct ServiceParameterListType
+{
+	struct ParameterSetType		ParameterSet[255];
+};
+struct WPT_SDlEnergyTransferModeType
+{
+	struct ServiceParameterListType	ServiceParameterList;
+};
+struct SelectedServiceType
+{
+	unsigned short			ServiceID;
+	short					ParameterSetID;
+};
+struct SelectedServiceListType
+{
+	struct SelectedServiceType	SelectedService[16];
+};
+
+struct CertificateChainType
+{
+	unsigned char 				Id[32];				//Optional
+	unsigned char 				Certificate[800];		//check size again
+	unsigned char				SubCertificates[4][800];	//Optional, 	check size again
+};
+struct PNC_AReqIdentificationModeType
+{
+	unsigned char 			GenChallenge[16];					//DIN70121=> None,	ISO15118_2014=>None,	ISO15118_2018=>Optional
+	unsigned char 			Id[32];							//DIN70121=> None,	ISO15118_2014=>None,	ISO15118_2018=>Optional
+};
+struct AC_EVChargeParameterType
+{
+	unsigned int 								DepartureTime;		//Optional
+	struct PhysicalValueType_ISO15118_2014			EAmount;
+	struct PhysicalValueType_ISO15118_2014			EVMaxVoltage;
+	struct PhysicalValueType_ISO15118_2014			EVMaxCurrent;
+	struct PhysicalValueType_ISO15118_2014			EVMinCurrent;
+};
+struct DC_EVStatusType_DIN70121
+{
+	BOOL						EVReady;
+	BOOL						EVCabinConditioning;
+	BOOL						EVRESSConiditioning;
+	enum DC_EVErrorCodeType		EVErrorCode;
+	unsigned char 					EVRESSSOC;		/*0-100 percentage*/
+};
+struct DC_EVChargeParameterType_DIN70121
+{
+	struct DC_EVStatusType_DIN70121			DC_EVStatus;
+	struct PhysicalValueType_DIN70121		EVMaximumCurrentLimit;
+	struct PhysicalValueType_DIN70121		EVMaximumPowerLimit;			//Optional
+	struct PhysicalValueType_DIN70121		EVMaximumVoltageLimit;
+	struct PhysicalValueType_DIN70121		EVEnergyCapacity;				//Optional
+	struct PhysicalValueType_DIN70121		EVEnergyRequest;				//Optional
+	unsigned char							FullSOC;/*0-100 percentage*/	//Optional
+	unsigned char							BulkSOC;/*0-100 percentage*/	//Optional
+};
+struct DC_EVStatusType_ISO15118_2014
+{
+	BOOL						EVReady;
+	enum DC_EVErrorCodeType		EVErrorCode;
+	unsigned char 					EVRESSSOC;		/*0-100 percentage*/
+};
+struct DC_EVChargeParameterType_ISO15118_2014
+{
+	unsigned int 								DepartureTime;				//Optional
+	struct DC_EVStatusType_ISO15118_2014			DC_EVStatus;
+	struct PhysicalValueType_ISO15118_2014 			EVMaximumCurrentLimit;
+	struct PhysicalValueType_ISO15118_2014			EVMaximumPowerLimit;			//Optional
+	struct PhysicalValueType_ISO15118_2014			EVMaximumVoltageLimit;
+	struct PhysicalValueType_ISO15118_2014			EVEnergyCapacity;				//Optional
+	struct PhysicalValueType_ISO15118_2014			EVEnergyRequest;				//Optional
+	unsigned char								FullSOC;/*0-100 percentage*/		//Optional
+	unsigned char								BulkSOC;/*0-100 percentage*/	//Optional
+};
+struct Dynamic_CPDReqControlModeType
+{
+	unsigned int 								DepartureTime;
+};
+struct RelativeTimeIntervalType
+{
+	unsigned int 	duration;			//Optional
+	unsigned int	start;
+};
+struct PMaxScheduleEntryType
+{
+	struct RelativeTimeIntervalType	RelativeTimeInterval;
+	unsigned short					PMax;
+};
+struct PMaxScheduleType
+{
+	unsigned short					PMaxScheduleID;			//no this itme in ISO15118_2014
+	struct PMaxScheduleEntryType		PMaxScheduleEntry[1024];
+};
+struct CostType
+{
+	unsigned int 					amount;
+	enum CostKindType				costKind;
+	int 							amountMultiplier;		//Optional , range: -3..+3
+};
+struct ConsumptionCostType
+{
+	struct CostType						Cost[3];
+	struct PhysicalValueType_ISO15118_2014		startValue;
+};
+struct SalesTariffEntryType
+{
+	struct RelativeTimeIntervalType	RelativeTimeInterval;
+	unsigned char 					EPriceLevel;			//Optional
+	struct ConsumptionCostType		ConsumptionCost[3];	//Optional
+};
+struct SalesTariffType
+{
+	unsigned char 					Id[32];					//Optional
+	short 						SalesTariffID;
+	unsigned char 					SalesTariffDescription[32];	//Optional
+	unsigned char 					NumEPriceLevels;			//Optional
+	struct SalesTariffEntryType			SalesTariffEntry[1024];
+};
+struct SAScheduleTupleType
+{
+	short 						SAScheduleTupleID;
+	struct PMaxScheduleType			PMaxSchedule;
+	struct SalesTariffType				SalesTariff;				//Optional
+};
+struct ScheduleListType
+{
+	enum ScheduleOriginType					ScheduleOrigin;
+	struct SAScheduleTupleType					ScheduleTuple[3];
+};
+struct Scheduled_CPDReqControlModeType
+{
+	enum ProcessingType						EVProcessing;
+	unsigned int 								DepartureTime;		//Optional
+	unsigned short 							MaxSupportingPoints;
+	struct ScheduleListType						ScheduleList;			//Optional
+};
+struct AC_CPDReqEnergyTransferModeType
+{
+	struct PhysicalValueType_ISO15118_2018			EVTargetEnergyRequest;			//Optional
+	struct PhysicalValueType_ISO15118_2018			EVMaximumEnergyRequest;		//Optional
+	struct PhysicalValueType_ISO15118_2018			EVMinimumEnergyRequest;		//Optional
+	struct PhysicalValueType_ISO15118_2018			EVMaximumChargePower;
+	struct PhysicalValueType_ISO15118_2018			EVMaximumChargeCurrent;
+	struct PhysicalValueType_ISO15118_2018			EVMinimumChargeCurrent;
+	struct PhysicalValueType_ISO15118_2018			EVMaximumVoltage;
+};
+struct DC_CPDReqEnergyTransferModeType
+{
+	struct PhysicalValueType_ISO15118_2018			EVMaximumChargePower;			//Optional
+	struct PhysicalValueType_ISO15118_2018			EVMinimumChargePower;			//Optional
+	struct PhysicalValueType_ISO15118_2018			EVMaximumChargeCurrent;
+	struct PhysicalValueType_ISO15118_2018			EVMinimumChargeCurrent;
+	struct PhysicalValueType_ISO15118_2018			EVMaximumVoltage;
+	struct PhysicalValueType_ISO15118_2018			EVTargetEnergyRequest;				//Optional
+	struct PhysicalValueType_ISO15118_2018			EVMaximumEnergyRequest;			//Optional
+	struct PhysicalValueType_ISO15118_2018			EVMinimumEnergyRequest;			//Optional
+	unsigned char								TargetSOC;						//Optional
+	unsigned char								BulkSOC;							//Optional
+};
+struct BPT_AC_CPDReqEnergyTransferModeType
+{
+	struct PhysicalValueType_ISO15118_2018			EVMaximumChargePower;
+	struct PhysicalValueType_ISO15118_2018			EVMaximumDischargePower;
+	struct PhysicalValueType_ISO15118_2018			EVMinimumDischargePower;
+	struct PhysicalValueType_ISO15118_2018			EVMaximumChargeCurrent;
+	struct PhysicalValueType_ISO15118_2018			EVMaximumDischargeCurrent;
+	struct PhysicalValueType_ISO15118_2018			EVMinimumChargeCurrent;
+	struct PhysicalValueType_ISO15118_2018			EVMinimumDischargeCurrent;
+	struct PhysicalValueType_ISO15118_2018			EVTargetEnergyRequest;				//Optional
+	struct PhysicalValueType_ISO15118_2018			EVMinimumEnergyRequest;			//Optional
+	struct PhysicalValueType_ISO15118_2018			EVMaximumEnergyRequest;			//Optional
+	struct PhysicalValueType_ISO15118_2018			EVMaximumVoltage;
+};
+struct BPT_DC_CPDReqEnergyTransferModeType
+{
+	struct PhysicalValueType_ISO15118_2018			EVMaximumChargePower;
+	struct PhysicalValueType_ISO15118_2018			EVMinimumChargePower;
+	struct PhysicalValueType_ISO15118_2018			EVMaximumDischargePower;
+	struct PhysicalValueType_ISO15118_2018			EVMinimumDischargePower;
+	struct PhysicalValueType_ISO15118_2018			EVMaximumChargeCurrent;
+	struct PhysicalValueType_ISO15118_2018			EVMinimumChargeCurrent;
+	struct PhysicalValueType_ISO15118_2018			EVMaximumDischargeCurrent;
+	struct PhysicalValueType_ISO15118_2018			EVMinimumDischargeCurrent;
+	struct PhysicalValueType_ISO15118_2018			EVMaximumVoltage;
+	struct PhysicalValueType_ISO15118_2018			EVMinimumVoltage;
+	struct PhysicalValueType_ISO15118_2018			EVTargetEnergyRequest;
+	struct PhysicalValueType_ISO15118_2018			EVMaximumEnergyRequest;
+	struct PhysicalValueType_ISO15118_2018			EVMinimumEnergyRequest;
+	unsigned char								TargetSOC;					//Optional
+	unsigned char								BulkSOC;						//Optional
+};
+struct WPT_CPDReqEnergyTransferModeType
+{
+	struct PhysicalValueType_ISO15118_2018			EVMaximumPower;				//Optional
+	struct PhysicalValueType_ISO15118_2018			EVMinimumPower;				//Optional
+	struct PhysicalValueType_ISO15118_2018			EVTargetEnergyRequest;			//Optional
+	struct PhysicalValueType_ISO15118_2018			EVMaximumEnergyRequest;		//Optional
+	struct PhysicalValueType_ISO15118_2018			EVMinimumEnergyRequest;		//Optional
+};
+struct ACD_CPDReqEnergyTransferModeType
+{
+	//cannot be found in standard
+};
+struct SAScheduleListType
+{
+	struct SAScheduleTupleType		SAScheduleTuple[3];
+};
+struct DC_EVSEStatusType_DIN70121
+{
+	enum IsolationLevelType_DIN70121			EVSEIsolationStatus;			//Optional
+	enum DC_EVSEStatusCodeType			EVSEStatusCode;
+	unsigned int							NotificationMaxDelay;
+	enum EVSENotificationType				EVSENotification;
+};
+struct DC_EVSEChargeParameterType_DIN70121
+{
+	struct DC_EVSEStatusType_DIN70121		DC_EVSEStatus;
+	struct PhysicalValueType_DIN70121			EVSEMaximumCurrentLimit;
+	struct PhysicalValueType_DIN70121			EVSEMaximumPowerLimit;			//Optional
+	struct PhysicalValueType_DIN70121			EVSEMaximumVoltageLimit;
+	struct PhysicalValueType_DIN70121			EVSEMinimumCurrentLimit;
+	struct PhysicalValueType_DIN70121			EVSEMinimumVoltageLimit;
+	struct PhysicalValueType_DIN70121			EVSECurrentRegulationTolerance;		//Optional
+	struct PhysicalValueType_DIN70121			EVSEPeakCurrentRipple;
+	struct PhysicalValueType_DIN70121			EVSEEnergyToBeDelivered;			//Optional
+};
+struct AC_EVSEStatusType
+{
+	BOOL							  		RCD;
+	unsigned short 							NotificationMaxDelay;
+	enum EVSENotificationType					EVSENotification;		//need to be confirmed
+};
+struct AC_EVSEChargeParameterType
+{
+	struct AC_EVSEStatusType					AC_EVSEStatus;
+	struct PhysicalValueType_ISO15118_2014			EVSENominalVoltage;
+	struct PhysicalValueType_ISO15118_2014			EVSEMaxCurrent;
+};
+struct DC_EVSEStatusType_ISO15118_2014
+{
+	unsigned short								NotificationMaxDelay;
+	enum EVSENotificationType					EVSENotification;
+	enum IsolationLevelType_ISO15118_2014			EVSEIsolationStatus;					//Optional
+	enum DC_EVSEStatusCodeType				DC_EVSEStatusCode;
+};
+struct DC_EVSEChargeParameterType_ISO15118_2014
+{
+	struct DC_EVSEStatusType_ISO15118_2014		DC_EVSEStatus;
+	struct PhysicalValueType_ISO15118_2014			EVSEMaximumCurrentLimit;
+	struct PhysicalValueType_ISO15118_2014			EVSEMaximumPowerLimit;
+	struct PhysicalValueType_ISO15118_2014			EVSEMaximumVoltageLimit;
+	struct PhysicalValueType_ISO15118_2014			EVSEMinimumCurrentLimit;
+	struct PhysicalValueType_ISO15118_2014			EVSEMinimumVoltageLimit;
+	struct PhysicalValueType_ISO15118_2014			EVSECurrentRegulationTolerance;		//Optional
+	struct PhysicalValueType_ISO15118_2014			EVSEPeakCurrentRipple;
+	struct PhysicalValueType_ISO15118_2014			EVSEEnergyToBeDelivered;			//Optional
+};
+struct Scheduled_CPDResControlModeType
+{
+	struct ScheduleListType						ScheduleList;
+};
+struct AC_CPDResEnergyTransferModeType
+{
+	struct PhysicalValueType_ISO15118_2018			EVSEMaximumChargeCurrent[3];
+	struct PhysicalValueType_ISO15118_2018			EVSENominalVoltage;
+	struct PhysicalValueType_ISO15118_2018			EVSENominalFrequency;
+};
+struct DC_CPDResEnergyTransferModeType
+{
+	struct PhysicalValueType_ISO15118_2018			EVSEMaximumChargePower;
+	struct PhysicalValueType_ISO15118_2018			EVSEMaximumChargeCurrent;
+	struct PhysicalValueType_ISO15118_2018			EVSEMinimumChargeCurrent;
+	struct PhysicalValueType_ISO15118_2018			EVSEMaximumVoltage;
+	struct PhysicalValueType_ISO15118_2018			EVSEMinimumVoltage;
+};
+struct BPT_AC_CPDResEnergyTransferModeType
+{
+	struct PhysicalValueType_ISO15118_2018			EVSEMaximumChargeCurrent[3];
+	struct PhysicalValueType_ISO15118_2018			EVSEMaximumDischargeCurrent[3];
+	struct PhysicalValueType_ISO15118_2018			EVSENominalVoltage;
+	struct PhysicalValueType_ISO15118_2018			EVSENominalFrequency;
+};
+struct BPT_DC_CPDResEnergyTransferModeType
+{
+	struct PhysicalValueType_ISO15118_2018			EVSEMaximumChargePower;
+	struct PhysicalValueType_ISO15118_2018			EVSEMaximumDischargePower;
+	struct PhysicalValueType_ISO15118_2018			EVSEMaximumChargeCurrent;
+	struct PhysicalValueType_ISO15118_2018			EVSEMaximumDischargeCurrent;
+	struct PhysicalValueType_ISO15118_2018			EVSEMinimumChargeCurrent;
+	struct PhysicalValueType_ISO15118_2018			EVSEMinimumDischargeCurrent;
+	struct PhysicalValueType_ISO15118_2018			EVSEMaximumVoltage;
+	struct PhysicalValueType_ISO15118_2018			EVSEMinimumVoltage;
+};
+struct WPT_CPDResEnergyTransferModeType
+{
+	struct PhysicalValueType_ISO15118_2018			EVSEMaximumPower;
+	struct PhysicalValueType_ISO15118_2018			EVSEMinimumPower;
+};
+struct ACD_CPDResEnergyTransferModeType
+{
+	//not found in ISO15118_2018
+};
+struct ProfileEntryType_DIN70121
+{
+	unsigned int 				ChargingProfileEntryStart;
+	short						ChargingProfileEntryMaxPower;
+};
+struct ChargingProfileType_DIN70121
+{
+	short 							SAScheduleTupleID;
+	struct ProfileEntryType_DIN70121		ProfileEntry[24];
+};
+struct DC_EVPowerDeliveryParameterType_DIN70121
+{
+	struct DC_EVStatusType_DIN70121			DC_EVStatus;
+	BOOL								BulkChargingComplete;		//Optional
+	BOOL								ChargingComplete;
+};
+struct ProfileEntryType_ISO15118_2014
+{
+	unsigned int 								ChargingProfileEntryStart;
+	struct PhysicalValueType_ISO15118_2018			ChargingProfileEntryMaxPower;
+	unsigned char 								ChargingProfileEntryMaxNumberOfPhasesInUse;	//Optional
+};
+struct ChargingProfileType_ISO15118_2014
+{
+	struct ProfileEntryType_ISO15118_2014			ProfileEntry[24];
+};
+struct DC_EVPowerDeliveryParameterType_ISO15118_2014
+{
+	struct DC_EVStatusType_ISO15118_2014 			DC_EVStatus;
+	BOOL									BulkChargingComplete;		//Optional
+	BOOL									ChargingComplete;
+};
+struct TimeInterval
+{
+	unsigned int 								start;
+	unsigned int 								duration;				//Optional
+};
+struct PowerScheduleEntryType
+{
+	struct TimeInterval							TimeInterval;
+	struct PhysicalValueType_ISO15118_2018			Power[3];
+};
+struct EVPowerProfileType
+{
+	struct PowerScheduleEntryType				EVPowerProfileEntry[2048];
+};
+struct Scheduled_PDReqControlModeType
+{
+	unsigned char 								ScheduleTupleID;
+	struct EVPowerProfileType					EVPowerProfile;
+};
+struct BPT_Scheduled_PDReqControlModeType
+{
+	unsigned char 								ScheduleTupleID;
+	struct EVPowerProfileType					EVPowerProfile;			//Optional
+	enum evOperationType						EVOperation;
+};
+struct ListOfRootCertificateIDsType
+{
+	unsigned char 								RootCertificateID[20][40];
+};
+struct ContractSignatureEncryptedPrivateKeyType
+{
+	unsigned char 								Id[32];
+};
+struct DiffieHellmanPublickeyType
+{
+	unsigned char 								Id[32];
+};
+struct ContractCertificateEncryptedPrivateKeyType
+{
+	unsigned char 								Id[32];
+};
+struct EVTechnicalStatusType
+{
+	BOOL									EV_Status_ReadyToCharge;
+	BOOL									EV_Status_ImmobilizationRequest;		//Optional
+	BOOL									EV_Status_Immobilized;
+	struct PhysicalValueType_ISO15118_2018			EV_Status_WLAN_Strength;
+	enum EV_CP_StatusType						EV_CP_Status;
+	unsigned char								EV_Status_RESSSOC;					//0~100%
+	enum EV_Error_Status_CodeType				EV_Error_Status_Code;
+	BOOL									EVSE_Timeout;
+};
+struct MeterInfoType_ISO15118_2014
+{
+	unsigned char								MeterID[32];
+	unsigned long 								MeterReading;						//Optional
+	unsigned char								SigMeterReading[64];				//Optional
+	short 									MeterStatus;						//Optional
+	short 									TMeter;							//Optional
+};
+struct Scheduled_MRReqControlModeType
+{
+	unsigned char 								ScheduleTupleID;
+};
+struct MeterInfoType_ISO15118_2018
+{
+	unsigned char								MeterID[32];
+	unsigned long 								MeterReadingWhCharged;			//Optional
+	unsigned long 								MeterReadingWhDischarged;			//Optional
+	unsigned long 								MeterReadingVARhLeading;			//Optional
+	unsigned long 								MeterReadingVARhLagging;			//Optional
+	unsigned char								SignatureMeterReading[64];			//Optional
+	short 									MeterStatus;						//Optional
+	short 									TimeStampMeter;					//Optional
+	BOOL									ReceiptRequired;					//Optional
+};
+struct PnC_CLReqIdentificationModeType
+{
+	BOOL									MeteringReceiptRequested;
+};
+struct Dynamic_CSReqControlModeType
+{
+	struct PhysicalValueType_ISO15118_2018			EVTargetEnergyRequest;
+	struct PhysicalValueType_ISO15118_2018			EVMaximumEnergyRequest;
+	struct PhysicalValueType_ISO15118_2018			EVMinimumEnergyRequest;
+	struct PhysicalValueType_ISO15118_2018			EVMaximumChargePower;
+	struct PhysicalValueType_ISO15118_2018			EVMaximumChargeCurrent;
+	struct PhysicalValueType_ISO15118_2018			EVMinimumChargeCurrent;
+};
+struct Scheduled_CSReqControlModeType
+{
+	struct PhysicalValueType_ISO15118_2018			EVTargetEnergyRequest;				//Optional
+	struct PhysicalValueType_ISO15118_2018			EVMaximumEnergyRequest;			//Optional
+	struct PhysicalValueType_ISO15118_2018			EVMinimumEnergyRequest;			//Optional
+	BOOL									Standby;
+	struct PhysicalValueType_ISO15118_2018			EVMaximumChargePower;			//Optional
+	struct PhysicalValueType_ISO15118_2018			EVMaximumChargeCurrent;			//Optional
+	struct PhysicalValueType_ISO15118_2018			EVMinimumChargeCurrent;			//Optional
+};
+struct DisplayParametersType
+{
+	unsigned short 							CurrentRange;
+	unsigned char	 							CurrentSOC;						//0~100%
+	unsigned char	 							MinimumSOC;						//0~100%
+	struct PhysicalValueType_ISO15118_2018			RemainingTimeToMaximumSOC;
+	struct PhysicalValueType_ISO15118_2018			RemainingTimeToTargetSOC;
+	struct PhysicalValueType_ISO15118_2018			RemainingTimeToBulkSOC;
+	struct PhysicalValueType_ISO15118_2018			RemainingTimeToMinimumSOC;
+	BOOL									ChargingComplete;
+	BOOL									BulkChargingComplete;
+	BOOL									InletHot;
+};
+struct PnC_CLResIdentificationModeType
+{
+	struct MeterInfoType_ISO15118_2018			MeterInfo;
+};
+struct Dynamic_CSResControlModeType
+{
+	struct PhysicalValueType_ISO15118_2018			EVSETargetActivePower;
+};
+struct Scheduled_CDResControlModeType
+{
+	struct PhysicalValueType_ISO15118_2018			EVSEMaximumChargePower;		//Optional
+	struct PhysicalValueType_ISO15118_2018			EVSEMaximumChargeCurrent;	//Optional
+	struct PhysicalValueType_ISO15118_2018			EVSEMaximumVoltage;			//Optional
+};
+struct LFA_EVFinePositioningSetupParametersType
+{
+	unsigned char 								NumberOfSensors;
+	//NOT complete yet,  to be continue.....
+};
+
+/****SupportedAppProtocolRequest****/
+struct SupportedAppProtocolRequest_DIN70121
+{
+	struct AppProtocolType	AppProtocol[20];
+};
+struct SupportedAppProtocolRequest_ISO15118_2014
+{
+	struct AppProtocolType	AppProtocol[20];
+};
+struct SupportedAppProtocolRequest_ISO15118_2018
+{
+	struct AppProtocolType	AppProtocol[20];
+};
+/****SupportedAppProtocolResponse****/
+struct SupportedAppProtocolResponse_DIN70121
+{
+	enum ResponseCodeType_DIN70121		ResponseCode;
+	unsigned char							SchemaID;				//Optional
+};
+struct SupportedAppProtocolResponse_ISO15118_2014
+{
+	enum ResponseCodeType_ISO15118_2014	ResponseCode;
+	unsigned char							SchemaID;				//Optional
+};
+struct SupportedAppProtocolResponse_ISO15118_2018
+{
+	enum ResponseCodeType_ISO15118_2018	ResponseCode;
+	unsigned char							SchemaID;					//Optional
+};
+/****SessionSetupRequest****/
+struct SessionSetupRequest_DIN70121
+{
+	unsigned char						EVCCID[8];						//the MAC address of the EVCC in Hex
+};
+struct SessionSetupRequest_ISO15118_2014
+{
+	unsigned char						EVCCID[8];						//the MAC address of the EVCC in Hex
+};
+struct SessionSetupRequest_ISO15118_2018
+{
+	unsigned char						EVCCID[8];						//the MAC address of the EVCC in Hex
+	struct ACD_SSEnergyTransferModeType	ACD_SSEnergyTransferMode;			//For ACD mandatory, optional for rest
+};
+/****SessionSetupResponse****/
+struct SessionSetupResponse_DIN70121
+{
+	enum ResponseCodeType_DIN70121		ResponseCode;
+	unsigned char							EVSEID[40];					//DIN70121=>Max length:32,	ISO15118=>min length:7, max length:37
+	unsigned int							EVSETimeStamp;				//EPOCH format, Optional
+};
+struct SessionSetupResponse_ISO15118_2014
+{
+	enum ResponseCodeType_ISO15118_2014	ResponseCode;
+	unsigned char							EVSEID[40];					//DIN70121=>Max length:32,	ISO15118=>min length:7, max length:37
+	unsigned int							EVSETimeStamp;				//EPOCH format, Optional
+};
+struct SessionSetupResponse_ISO15118_2018
+{
+	enum ResponseCodeType_ISO15118_2018	ResponseCode;
+	unsigned char							EVSEID[40];					//DIN70121=>Max length:32,	ISO15118=>min length:7, max length:37
+	struct EVSEStatusType					EVSEStatus;					//Optional
+};
+/****ServiceDiscoveryRequest****/
+struct ServiceDiscoveryRequest_DIN70121
+{
+	unsigned char				ServiceScope[32];		//Optional
+	enum ServiceCategoryType	ServiceCategory;		//Optional
+};
+struct ServiceDiscoveryRequest_ISO15118_2014
+{
+	unsigned char				ServiceScope[32];		//Optional
+	enum ServiceCategoryType	ServiceCategory;		//Optional
+};
+struct ServiceDiscoveryRequest_ISO15118_2018
+{
+	struct ServiceIDListType		SupportedServiceIDs;	//Optional
+};
+/****ServiceDiscoveryResponse****/
+struct ServiceDiscoveryResponse_DIN70121
+{
+	enum ResponseCodeType_DIN70121		ResponseCode;
+	struct PaymentOptionListType				PaymentOptions;
+	struct ServiceChargeType				ChargeService_DIN70121;
+};
+struct ServiceDiscoveryResponse_ISO15118_2014
+{
+	enum ResponseCodeType_ISO15118_2014	ResponseCode;
+	struct PaymentOptionListType				PaymentOptions;
+	struct ChargeServiceType				ChargeService;
+	struct ServiceListType					ServiceList;					//Optional
+};
+struct ServiceDiscoveryResponse_ISO15118_2018
+{
+	enum ResponseCodeType_ISO15118_2018	ResponseCode;
+	struct EVSEStatusType					EVSEStatus;					//Optional
+	struct IdentificationOptionListType			IdentificationOptionList;
+	struct ServiceListType					EnergyTransferServiceList;
+	struct ServiceListType					VASList;						//Optional
+};
+/****ServiceDetailRequest****/
+//Only in ISO15118_2014 and ISO15118_2018
+struct ServiceDetailRequest_ISO15118_2014
+{
+	unsigned short						ServiceID;
+};
+struct ServiceDetailRequest_ISO15118_2018
+{
+	unsigned short						ServiceID;
+	struct WPT_SDlEnergyTransferModeType	WPT_SDlEnergyTransferMode;
+};
+/****ServiceDetailResponse****/
+struct ServiceDetailResponse_ISO15118_2014
+{
+	enum ResponseCodeType_ISO15118_2014	ResponseCode;
+	unsigned short							ServiceID;
+	struct ServiceParameterListType 			ServiceParameterList;
+};
+struct ServiceDetailResponse_ISO15118_2018
+{
+	enum ResponseCodeType_ISO15118_2018	ResponseCode;
+	unsigned short							ServiceID;
+	struct ServiceParameterListType 			ServiceParameterList;
+	struct EVSEStatusType					EVSEStatus;					//Optional
+};
+/****ServiceAndPaymentSelectionRequest / ServiceSelectionRequest****/
+struct ServiceAndPaymentSelectionRequest_DIN70121
+{
+	enum PaymentOptionType		SelectedPaymentOption;
+	struct SelectedServiceListType		SelectedServiceList;
+};
+struct ServiceAndPaymentSelectionRequest_ISO15118_2014
+{
+	enum PaymentOptionType		SelectedPaymentOption;
+	struct SelectedServiceListType		SelectedServiceList;
+};
+struct ServiceSelectionRequest_ISO15118_2018
+{
+	enum PaymentOptionType			SelectedPaymentOption;
+	struct SelectedServiceType			SelectedEnergyTransferService;
+	struct SelectedServiceListType			SelectedVASList;
+	enum ProcessingType				EVProcessing;
+};
+/****ServiceAndPaymentSelectionResponse / ServiceSelectionResponse****/
+struct ServiceAndPaymentSelectionResponse_DIN70121
+{
+	enum ResponseCodeType_DIN70121		ResponseCode;
+};
+struct ServiceAndPaymentSelectionResponse_ISO15118_2014
+{
+	enum ResponseCodeType_ISO15118_2014	ResponseCode;
+};
+struct ServiceSelectionResponse_ISO15118_2018
+{
+	enum ResponseCodeType_ISO15118_2018	ResponseCode;
+	struct EVSEStatusType					EVSEStatus;					//Optional
+};
+/****PaymentDetailsRequest / IdentificationDetailsRequest****/
+struct PaymentDetailsRequest_ISO15118_2014
+{
+	unsigned char 					eMAID[16];
+	struct CertificateChainType		ContractSignatureCertChain;
+};
+struct IdentificationDetailsRequest_ISO15118_2018
+{
+	struct CertificateChainType		ContractSignatureCertChain;
+};
+/****PaymentDetailsResponse  / IdentificationDetailsResponse ****/
+struct PaymentDetailsResponse_ISO15118_2014
+{
+	enum ResponseCodeType_ISO15118_2014	ResponseCode;
+	unsigned char 							GenChallenge[16];
+	long 								EVSETimeStamp;
+};
+struct IdentificationDetailsResponse_ISO15118_2018
+{
+	enum ResponseCodeType_ISO15118_2018	ResponseCode;
+	struct EVSEStatusType					EVSEStatus;						//Optional
+	unsigned char 							GenChallenge[16];
+	enum ProcessingType					EVSEProcessing;
+};
+/****ContractAuthenticationRequest / AuthorizationRequest****/
+struct ContractAuthenticationRequest_DIN70121
+{
+	//None
+};
+struct AuthorizationRequest_ISO15118_2014
+{
+	unsigned char 			GenChallenge[16];					//Optional
+	unsigned char 			Id[32];							//Optional
+};
+struct AuthorizationRequest_ISO15118_2018
+{
+	struct PNC_AReqIdentificationModeType		PNC_AReqIdentificationMode;	//Optional
+};
+/****ContractAuthenticationResponse  / AuthorizationResponse****/
+struct ContractAuthenticationResponse_DIN70121
+{
+	enum ResponseCodeType_DIN70121		ResponseCode;
+	enum EVSEProcessingType_DIN70121		EVSEProcessing;
+};
+struct AuthorizationResponse_ISO15118_2014
+{
+	enum ResponseCodeType_ISO15118_2014	ResponseCode;
+	enum EVSEProcessingType_ISO15118_2014	EVSEProcessing;
+};
+struct AuthorizationResponse_ISO15118_2018
+{
+	enum ResponseCodeType_ISO15118_2018	ResponseCode;
+	enum ProcessingType					EVSEProcessing;
+	struct EVSEStatusType					EVSEStatus;						//Optional
+};
+/****ChargeParameterDiscoveryRequest****/
+struct ChargeParameterDiscoveryRequest_DIN70121
+{
+	enum EnergyTransferModeType					EVRequestedEnergyTransferType;
+	struct DC_EVChargeParameterType_DIN70121		DC_EVChargeParameter;
+};
+struct ChargeParameterDiscoveryRequest_ISO15118_2014
+{
+	unsigned short										MaxEntriesSAScheduleTuple;			//Optional
+	enum EnergyTransferModeType						RequestedEnergyTransferMode;
+	struct AC_EVChargeParameterType					AC_EVChargeParameter;
+	struct DC_EVChargeParameterType_ISO15118_2014		DC_EVChargeParameter;
+};
+struct ChargeParameterDiscoveryRequest_ISO15118_2018
+{
+	struct Dynamic_CPDReqControlModeType			Dynamic_CPDReqControlMode;
+	struct Scheduled_CPDReqControlModeType			Scheduled_CPDReqControlMode;
+	struct AC_CPDReqEnergyTransferModeType			AC_CPDReqEnergyTransferMode;
+	struct DC_CPDReqEnergyTransferModeType			DC_CPDReqEnergyTransferMode;
+	struct BPT_AC_CPDReqEnergyTransferModeType		BPT_AC_CPDReqEnergyTransferMode;
+	struct BPT_DC_CPDReqEnergyTransferModeType		BPT_DC_CPDReqEnergyTransferMode;
+	struct WPT_CPDReqEnergyTransferModeType			WPT_CPDReqEnergyTransferMode;
+	struct ACD_CPDReqEnergyTransferModeType			ACD_CPDReqEnergyTransferMode;
+};
+/****ChargeParameterDiscoveryResponse****/
+struct ChargeParameterDiscoveryResponse_DIN70121
+{
+	enum ResponseCodeType_DIN70121					ResponseCode;
+	enum EVSEProcessingType_DIN70121					EVSEProcessing;
+	struct SAScheduleListType 							SAScheduleList;
+	struct DC_EVSEChargeParameterType_DIN70121			DC_EVSEChargeParameter;
+};
+struct ChargeParameterDiscoveryResponse_ISO15118_2014
+{
+	enum EVSEProcessingType_ISO15118_2014				EVSEProcessing;
+	enum ResponseCodeType_ISO15118_2014				ResponseCode;
+	struct SAScheduleListType 							SAScheduleList;
+	struct AC_EVSEChargeParameterType					AC_EVSEChargeParameter;
+	struct DC_EVSEChargeParameterType_ISO15118_2014		DC_EVSEChargeParameter;
+};
+struct ChargeParameterDiscoveryResponse_ISO15118_2018
+{
+	enum ResponseCodeType_ISO15118_2018				ResponseCode;
+	struct EVSEStatusType								EVSEStatus;					//Optional
+	enum ProcessingType								EVSEProcessing;
+	struct Scheduled_CPDResControlModeType				Scheduled_CPDResControlMode;	//Optional
+	struct AC_CPDResEnergyTransferModeType				AC_CPDResEnergyTransferMode;
+	struct DC_CPDResEnergyTransferModeType				DC_CPDResEnergyTransferMode;
+	struct BPT_AC_CPDResEnergyTransferModeType			BPT_AC_CPDResEnergyTransferMode;
+	struct BPT_DC_CPDResEnergyTransferModeType			BPT_DC_CPDResEnergyTransferMode;
+	struct WPT_CPDResEnergyTransferModeType				WPT_CPDResEnergyTransferMode;
+	struct ACD_CPDResEnergyTransferModeType				ACD_CPDResEnergyTransferMode;
+};
+/****PowerDeliveryRequest****/
+struct PowerDeliveryRequest_DIN70121
+{
+	BOOL											ReadyToChargeState;
+	struct ChargingProfileType_DIN70121					ChargingProfile;
+	struct DC_EVPowerDeliveryParameterType_DIN70121		DC_EVPowerDeliveryParameter;
+};
+struct PowerDeliveryRequest_ISO15118_2014
+{
+	enum ChargeProgressType_ISO15118_2014				ChargeProgress;
+	short 											SAScheduleTupleID;
+	struct ChargingProfileType_ISO15118_2014 				ChargingProfile;
+	struct DC_EVPowerDeliveryParameterType_ISO15118_2014	DC_EVPowerDeliveryParameter;
+};
+struct PowerDeliveryRequest_ISO15118_2018
+{
+	enum ChargeProgressType_ISO15118_2018				ChargeProgress;
+	struct Scheduled_PDReqControlModeType				Scheduled_PDReqControlMode;
+	struct BPT_Scheduled_PDReqControlModeType			BPT_Scheduled_PDReqControlMode;
+};
+/****PowerDeliveryResponse****/
+struct PowerDeliveryResponse_DIN70121
+{
+	enum ResponseCodeType_DIN70121				ResponseCode;
+	struct DC_EVSEStatusType_DIN70121				DC_EVSEStatus;
+};
+struct PowerDeliveryResponse_ISO15118_2014
+{
+	enum ResponseCodeType_ISO15118_2014				ResponseCode;
+	struct AC_EVSEStatusType							AC_EVSEStatus;
+	struct DC_EVSEStatusType_ISO15118_2014				DC_EVSEStatus;
+};
+struct PowerDeliveryResponse_ISO15118_2018
+{
+	enum ResponseCodeType_ISO15118_2018				ResponseCode;
+	struct EVSEStatusType								EVSEStatus;			//Optional
+};
+/****CertificateUpdateRequest****/
+struct CertificateUpdateRequest_ISO15118_2014
+{
+	unsigned char 										Id[32];
+	struct CertificateChainType							ContractSignatureCertChain;
+	unsigned char 										eMAID[16];
+	struct ListOfRootCertificateIDsType						ListOfRootCertificateIDs;
+};
+/****CertificateUpdateResponse****/
+struct CertificateUpdateResponse_ISO15118_2014
+{
+	enum ResponseCodeType_ISO15118_2014				ResponseCode;
+	struct CertificateChainType							SAProvisioningCertificateChain;
+	struct CertificateChainType							ContractSignatureCertChain;
+	struct ContractSignatureEncryptedPrivateKeyType			ContractSignatureEncryptedPrivateKey;
+	struct DiffieHellmanPublickeyType						DHpublickey;
+	unsigned char 										eMAID[16];
+	short 											RetryCounter;							//Optional
+};
+/****CertificateInstallationRequest****/
+struct CertificateInstallationRequest_ISO15118_2014
+{
+	unsigned char 										Id[32];
+	unsigned char 										OEMProvisioningCert[800];
+	struct ListOfRootCertificateIDsType						ListOfRootCertificateIDs;
+};
+struct CertificateInstallationRequest_ISO15118_2018
+{
+	unsigned char 										Id[32];
+	struct CertificateChainType							OEMProvisioningCertChain;
+	struct ListOfRootCertificateIDsType						ListOfRootCertificateIDs;
+	unsigned short										MaxSupportedCerts;
+};
+/****CertificateInstallationResponse****/
+struct CertificateInstallationResponse_ISO15118_2014
+{
+	enum ResponseCodeType_ISO15118_2014				ResponseCode;
+	struct CertificateChainType							SAProvisioningCertificateChain;
+	struct CertificateChainType							ContractSignatureCertChain;
+	struct ContractSignatureEncryptedPrivateKeyType			ContractSignatureEncryptedPrivateKey;
+	struct DiffieHellmanPublickeyType						DHpublickey;
+	unsigned char 										eMAID[16];
+};
+struct CertificateInstallationResponse_ISO15118_2018
+{
+	enum ResponseCodeType_ISO15118_2018				ResponseCode;
+	struct EVSEStatusType								EVSEStatus;					//Optional
+	struct CertificateChainType							SAProvisioningCertificateChain;
+	struct CertificateChainType							ContractCertificateChain;
+	struct ContractCertificateEncryptedPrivateKeyType		ContractEncryptedPrivateKey;
+	struct DiffieHellmanPublickeyType						DHpublickey;
+	enum ProcessingType								EVSEProcessing;
+	unsigned short 									RemainingContractCertificateChains;
+};
+/****SystemStatusRequest****/
+struct SystemStatusRequest_ISO15118_2018
+{
+	enum mechanicalChargingDeviceStatusType			EVMechanicalChargingDeviceStatus;
+	struct EVTechnicalStatusType							EVTechnicalStatus;
+	unsigned char 										EV_OEMStatus[800];					//Optional
+};
+/****SystemStatusResponse****/
+struct SystemStatusResponse_ISO15118_2018
+{
+	enum ResponseCodeType_ISO15118_2018				ResponseCode;
+	enum mechanicalChargingDeviceStatusType			EVSEMechanicalChargingDeviceStatus;
+	BOOL											EVSE_ReadyToCharge;
+	enum IsolationStatusType							EVSE_IsolationStatus;
+	BOOL											EVSE_Disabled;
+	BOOL											EVSE_UtilityInterruptEvent;
+	BOOL											EVSE_EmergencyShutdown;
+	BOOL											EVSE_Malfunction;
+	BOOL											EV_InChargePosition;
+	BOOL											EV_AssociationStatus;
+};
+/****SessionStopRequest****/
+struct SessionStopRequest_DIN70121
+{
+	//No member in standard
+};
+struct SessionStopRequest_ISO15118_2014
+{
+	enum ChargingSessionType							ChargingSession;
+};
+struct SessionStopRequest_ISO15118_2018
+{
+	enum ChargingSessionType							ChargingSession;
+};
+/****SessionStopResponse****/
+struct SessionStopResponse_DIN70121
+{
+	enum ResponseCodeType_DIN70121					ResponseCode;
+};
+struct SessionStopResponse_ISO15118_2014
+{
+	enum ResponseCodeType_ISO15118_2014				ResponseCode;
+};
+struct SessionStopResponse_ISO15118_2018
+{
+	enum ResponseCodeType_ISO15118_2018				ResponseCode;
+	struct EVSEStatusType								EVSEStatus;					//Optional
+};
+/****MeteringReceiptRequest****/
+struct MeteringReceiptRequest_ISO15118_2014
+{
+	unsigned char 										Id[32];						//Optional
+	unsigned char 										SessionID[8];
+	short 											SAScheduleTupleID;				//Optional
+	struct MeterInfoType_ISO15118_2014					MeterInfo;
+};
+struct MeteringReceiptRequest_ISO15118_2018
+{
+	unsigned char 										Id[32];						//Optional
+	unsigned char 										SessionID[8];
+	struct Scheduled_MRReqControlModeType				Schedule_MRReqControlMode;
+	struct MeterInfoType_ISO15118_2018					MeterInfo;
+};
+/****MeteringReceiptResponse****/
+struct MeteringReceiptResponse_ISO15118_2014
+{
+	enum ResponseCodeType_ISO15118_2014				ResponseCode;
+	struct AC_EVSEStatusType							AC_EVSEStatus;
+	struct DC_EVSEStatusType_ISO15118_2014				DC_EVSEStatus;
+};
+struct MeteringReceiptResponse_ISO15118_2018
+{
+	enum ResponseCodeType_ISO15118_2018				ResponseCode;
+	struct EVSEStatusType								EVSEStatus;					//Optional
+};
+/****ChargingStatusRequest (AC Only)****/
+struct ChargingStatusRequest_ISO15118_2014
+{
+	//No member in standard
+};
+struct ChargingStatusRequest_ISO15118_2018
+{
+	struct PnC_CLReqIdentificationModeType				PnC_CLReqIdentificationMode;
+	struct Dynamic_CSReqControlModeType				Dynamic_CSReqControlMode;
+	struct Scheduled_CSReqControlModeType				Scheduled_CSReqControlMode;
+	struct DisplayParametersType							DisplayParameters;
+};
+/****ChargingStatusResponse (AC Only)****/
+struct ChargingStatusResponse_ISO15118_2014
+{
+	enum ResponseCodeType_ISO15118_2014				ResponseCode;
+	unsigned char										EVSEID[40];			//DIN70121=>Max length:32,	ISO15118=>min length:7, max length:37
+	short 											SAScheduleTupleID;
+	struct PhysicalValueType_ISO15118_2014					EVSEMaxCurrent;		//Optional
+	struct MeterInfoType_ISO15118_2014					MeterInfo;			//Optional
+	BOOL											ReceiptRequired;		//Optional
+	struct AC_EVSEStatusType							AC_EVSEStatus;
+};
+struct ChargingStatusResponse_ISO15118_2018
+{
+	enum ResponseCodeType_ISO15118_2018				ResponseCode;
+	struct EVSEStatusType								EVSEStatus;					//Optional
+	unsigned char										EVSEID[40];					//DIN70121=>Max length:32,	ISO15118=>min length:7, max length:37
+	struct PhysicalValueType_ISO15118_2018					EVSETargetFrequency;			//Optional
+	struct PnC_CLResIdentificationModeType				PnC_CLResIdentificationMode;
+	struct Dynamic_CSResControlModeType					Dynamic_CSResControlMode;
+	struct Scheduled_CSReqControlModeType				Scheduled_CSReqControlMode;
+};
+/****CableCheckRequest (DC Only)****/
+struct CableCheckRequest_DIN70121
+{
+	struct DC_EVStatusType_DIN70121						DC_EVStatus;
+};
+struct CableCheckRequest_ISO15118_2014
+{
+	struct DC_EVStatusType_ISO15118_2014 					DC_EVStatus;
+};
+struct CableCheckRequest_ISO15118_2018
+{
+	//No member in standard
+};
+/****CableCheckResponse (DC Only)****/
+struct CableCheckResponse_DIN70121
+{
+	enum ResponseCodeType_DIN70121					ResponseCode;
+	struct DC_EVSEStatusType_DIN70121					DC_EVSEStatus;
+	enum EVSEProcessingType_DIN70121					EVSEProcessing;
+};
+struct CableCheckResponse_ISO15118_2014
+{
+	enum ResponseCodeType_ISO15118_2014				ResponseCode;
+	struct DC_EVSEStatusType_ISO15118_2014				DC_EVSEStatus;
+	enum EVSEProcessingType_ISO15118_2014				EVSEProcessing;
+};
+struct CableCheckResponse_ISO15118_2018
+{
+	enum ResponseCodeType_ISO15118_2018				ResponseCode;
+	struct EVSEStatusType								EVSEStatus;					//Optional
+	enum ProcessingType								EVSEProcessing;
+};
+/****PreChargeRequest (DC Only)****/
+struct PreChargeRequest_DIN70121
+{
+	struct DC_EVStatusType_DIN70121						DC_EVStatus;
+	struct PhysicalValueType_DIN70121						EVTargetVoltage;
+	struct PhysicalValueType_DIN70121						EVTargetCurrent;
+};
+struct PreChargeRequest_ISO15118_2014
+{
+	struct DC_EVStatusType_ISO15118_2014 					DC_EVStatus;
+	struct PhysicalValueType_ISO15118_2014					EVTargetVoltage;
+	struct PhysicalValueType_ISO15118_2014					EVTargetCurrent;
+};
+struct PreChargeRequest_ISO15118_2018
+{
+	struct PhysicalValueType_ISO15118_2018					EVTargetVoltage;
+	struct PhysicalValueType_ISO15118_2018					EVTargetCurrent;
+};
+/****PreChargeResponse (DC Only)****/
+struct PreChargeResponse_DIN70121
+{
+	enum ResponseCodeType_DIN70121					ResponseCode;
+	struct DC_EVSEStatusType_DIN70121					DC_EVSEStatus;
+	struct PhysicalValueType_DIN70121						EVSEPresentVoltage;
+};
+struct PreChargeResponse_ISO15118_2014
+{
+	enum ResponseCodeType_ISO15118_2014				ResponseCode;
+	struct DC_EVSEStatusType_ISO15118_2014				DC_EVSEStatus;
+	struct PhysicalValueType_ISO15118_2014					EVSEPresentVoltage;
+};
+struct PreChargeResponse_ISO15118_2018
+{
+	enum ResponseCodeType_ISO15118_2018				ResponseCode;
+	struct EVSEStatusType								EVSEStatus;					//Optional
+	struct PhysicalValueType_ISO15118_2018					EVSEPresentVoltage;
+};
+/****CurrentDemandRequest (DC Only)****/
+struct CurrentDemandRequest_DIN70121
+{
+	struct DC_EVStatusType_DIN70121						DC_EVStatus;
+	struct PhysicalValueType_DIN70121						EVTargetCurrent;
+	struct PhysicalValueType_DIN70121						EVMaximumVoltageLimit;		//Optional
+	struct PhysicalValueType_DIN70121						EVMaximumCurrentLimit;		//Optional
+	struct PhysicalValueType_DIN70121						EVMaximumPowerLimit;			//Optional
+	BOOL											BulkChargingComplete;			//Optional
+	BOOL											ChargingComplete;
+	struct PhysicalValueType_DIN70121						RemainingTimeToFullSoC;		//Optional
+	struct PhysicalValueType_DIN70121						RemainingTimeToBulkSoC;		//Optional
+	struct PhysicalValueType_DIN70121						EVTargetVoltage;
+};
+struct CurrentDemandRequest_ISO15118_2014
+{
+	struct DC_EVStatusType_ISO15118_2014 					DC_EVStatus;
+	struct PhysicalValueType_ISO15118_2014					EVTargetCurrent;
+	struct PhysicalValueType_ISO15118_2014					EVMaximumVoltageLimit;		//Optional
+	struct PhysicalValueType_ISO15118_2014					EVMaximumCurrentLimit;		//Optional
+	struct PhysicalValueType_ISO15118_2014					EVMaximumPowerLimit;			//Optional
+	BOOL											BulkChargingComplete;			//Optional
+	BOOL											ChargingComplete;
+	struct PhysicalValueType_ISO15118_2014					RemainingTimeToFullSoC;		//Optional
+	struct PhysicalValueType_ISO15118_2014					RemainingTimeToBulkSoC;		//Optional
+	struct PhysicalValueType_ISO15118_2014					EVTargetVoltage;
+};
+struct CurrentDemandRequest_ISO15118_2018
+{
+	struct DisplayParametersType							DisplayParameters;				//Optional
+	struct PnC_CLReqIdentificationModeType				PnC_CLReqIdentificationMode;
+	struct Dynamic_CSReqControlModeType				Dynamic_CDReqControlMode;
+	struct Scheduled_CSReqControlModeType				Scheduled_CDReqControlMode;
+};
+/****CurrentDemandResponse (DC Only)****/
+struct CurrentDemandResponse_DIN70121
+{
+	enum ResponseCodeType_DIN70121					ResponseCode;
+	struct DC_EVSEStatusType_DIN70121					DC_EVSEStatus;
+	struct PhysicalValueType_DIN70121						EVSEPresentVoltage;
+	struct PhysicalValueType_DIN70121						EVSEPresentCurrent;
+	BOOL											EVSECurrentLimitAchieved;
+	BOOL											EVSEVoltageLimitAchieved;
+	BOOL											EVSEPowerLimitAchieved;
+	struct PhysicalValueType_DIN70121						EVSEMaximumVoltageLimit;		//Optional
+	struct PhysicalValueType_DIN70121						EVSEMaximumCurrentLimit;		//Optional
+	struct PhysicalValueType_DIN70121						EVSEMaximumPowerLimit;		//Optional
+};
+struct CurrentDemandResponse_ISO15118_2014
+{
+	enum ResponseCodeType_ISO15118_2014				ResponseCode;
+	struct DC_EVSEStatusType_ISO15118_2014				DC_EVSEStatus;
+	struct PhysicalValueType_ISO15118_2014					EVSEPresentVoltage;
+	struct PhysicalValueType_ISO15118_2014					EVSEPresentCurrent;
+	BOOL											EVSECurrentLimitAchieved;
+	BOOL											EVSEVoltageLimitAchieved;
+	BOOL											EVSEPowerLimitAchieved;
+	struct PhysicalValueType_ISO15118_2014					EVSEMaximumVoltageLimit;		//Optional
+	struct PhysicalValueType_ISO15118_2014					EVSEMaximumCurrentLimit;		//Optional
+	struct PhysicalValueType_ISO15118_2014					EVSEMaximumPowerLimit;		//Optional
+	unsigned char										EVSEID[40];			//DIN70121=>Max length:32,	ISO15118=>min length:7, max length:37
+	short 											SAScheduleTupleID;
+	struct MeterInfoType_ISO15118_2014					MeterInfo;			//Optional
+	BOOL											ReceiptRequired;		//Optional
+};
+struct CurrentDemandResponse_ISO15118_2018
+{
+	enum ResponseCodeType_ISO15118_2018				ResponseCode;
+	struct EVSEStatusType								EVSEStatus;						//Optional
+	struct PhysicalValueType_ISO15118_2018					EVSEPresentVoltage;
+	struct PhysicalValueType_ISO15118_2018					EVSEPresentCurrent;
+	BOOL											EVSECurrentLimitAchieved;
+	BOOL											EVSEVoltageLimitAchieved;
+	BOOL											EVSEPowerLimitAchieved;
+	struct PhysicalValueType_ISO15118_2018					EVSEMaximumChargeVoltage;		//Optional
+	struct PhysicalValueType_ISO15118_2018					EVSEMaximumChargeCurrent;		//Optional
+	struct PhysicalValueType_ISO15118_2018					EVSEMaximumChargePower;			//Optional
+	unsigned char										EVSEID[40];						//DIN70121=>Max length:32,	ISO15118=>min length:7, max length:37
+	struct PnC_CLResIdentificationModeType				PnC_CLResIdentificationMode;
+	struct Scheduled_CDResControlModeType				Scheduled_CDResControlMode;
+};
+/****WeldingDetectionRequest (DC Only)*****/
+struct WeldingDetectionRequest_DIN70121
+{
+	struct DC_EVStatusType_DIN70121						DC_EVStatus;
+};
+struct WeldingDetectionRequest_ISO15118_2014
+{
+	struct DC_EVStatusType_ISO15118_2014 					DC_EVStatus;
+};
+struct WeldingDetectionRequest_ISO15118_2018
+{
+	//No member in Standard
+};
+/****WeldingDetectionResponse (DC Only)****/
+struct WeldingDetectionResponse_DIN70121
+{
+	enum ResponseCodeType_DIN70121					ResponseCode;
+	struct DC_EVSEStatusType_DIN70121					DC_EVSEStatus;
+	struct PhysicalValueType_DIN70121						EVSEPresentVoltage;
+};
+struct WeldingDetectionResponse_ISO15118_2014
+{
+	enum ResponseCodeType_ISO15118_2014				ResponseCode;
+	struct DC_EVSEStatusType_ISO15118_2014				DC_EVSEStatus;
+	struct PhysicalValueType_ISO15118_2014					EVSEPresentVoltage;
+};
+struct WeldingDetectionResponse_ISO15118_2018
+{
+	enum ResponseCodeType_ISO15118_2018				ResponseCode;
+	struct EVSEStatusType								EVSEStatus;						//Optional
+	struct PhysicalValueType_ISO15118_2018					EVSEPresentVoltage;
+};
+/****FinePositioningSetupRequest (WPT Only)****/
+struct FinePositioningSetupRequest_ISO15118_2018
+{
+	struct LFA_EVFinePositioningSetupParametersType			LFA_EVFinePositioningSetupParameters;	//Optional
+};
+/****FinePositioningSetupResponse (WPT Only)****/
+struct FinePositioningSetupResponse_ISO15118_2018
+{
+	//NOT complete yet,  to be continue.....
+};
+
+
+struct V2GMessageType_DIN70121
+{
+	unsigned char 	SelfTest_Comp;
+	unsigned char	version[16];
+	unsigned char											PresentMsgFlowStatus;
+														/* 0: Idle(wait B2 state), 1: CM_SLAC_PARM.REQ, 2: CM_SLAC_PARM.CNF, 3: CM_START_ATTEN_CHAR.IND
+														    4: CM_MNBC_SOUND.IND, 5: CM_ATTEN_CHAR.IND, 6: CM_ATTEN_CHAR.RSP, 7: CM_VALIDATE.REQ
+														    8: CM_VALIDATE.CNF, 9: CM_SLAC_MATCH.REQ, 10: CM_SLAC_MATCH.CNF, 11: CM_AMP_MAP.REQ
+														    12: CM_AMP_MAP.CNF, 13: SLACC/SDP/TCP connection,
+														    16: SupportedAppProtocolRequest, 17: SupportedAppProtocolResponse, 18: SessionSetupRequest
+														    19: SessionSetupResponse, 20: ServiceDiscoveryRequest, 21: ServiceDiscoveryResponse
+														    22: ServiceDetailRequest, 23: ServiceDetailResponse
+														    24: ServiceAndPaymentSelectionRequest/ServiceSelectionRequest, 25: ServiceAndPaymentSelectionResponse/ServiceSelectionResponse
+														    26: PaymentDetailsRequest/IdentificationDetailsRequest;, 27: PaymentDetailsResponse/IdentificationDetailsResponse,
+														     28: AuthorizationRequest, 29: AuthorizationResponse,
+														    30: CertificateUpdateRequest, 31: CertificateUpdateResponse, 32:CertificateInstallationRequest, 33: CertificateInstallationResponse
+														    34: ChargeParameterDiscoveryRequest, 35: ChargeParameterDiscoveryResponse
+														    36: CableCheckRequest, 37: CableCheckResponse, 38: PreChargeRequest, 39: PreChargeResponse
+														    40: PowerDeliveryRequest start, 41: PowerDeliveryResponse start, 42: ChargingStatusRequest, 43: ChargingStatusResponse
+														    44: CurrentDemandRequest, 45: CurrentDemandResponse, 46: MeteringReceiptRequest, 47: MeteringReceiptResponse
+														    48: PowerDeliveryRequest end, 49: PowerDeliveryRequest end, 50: WeldingDetectionRequest, 51: WeldingDetectionResponse,
+														    52: SessionStopRequest, 53: SessionStopResponse
+														   253: Performance Timeout, 254: Sequence Timeout, 255: Fault
+														*/
+	struct SupportedAppProtocolRequest_DIN70121 			SupportedAppProtocolRequest;
+	struct SupportedAppProtocolResponse_DIN70121 			SupportedAppProtocolResponse;
+	struct SessionSetupRequest_DIN70121  					SessionSetupRequest;
+	struct SessionSetupResponse_DIN70121   				SessionSetupResponse;
+	struct ServiceDiscoveryRequest_DIN70121    				ServiceDiscoveryRequest;
+	struct ServiceDiscoveryResponse_DIN70121    				ServiceDiscoveryResponse;
+	struct ServiceAndPaymentSelectionRequest_DIN70121		ServiceAndPaymentSelectionRequest;
+	struct ServiceAndPaymentSelectionResponse_DIN70121		ServiceAndPaymentSelectionResponse;
+	struct ContractAuthenticationRequest_DIN70121			ContractAuthenticationRequest;
+	struct ContractAuthenticationResponse_DIN70121	 		ContractAuthenticationResponse;
+	struct ChargeParameterDiscoveryRequest_DIN70121		ChargeParameterDiscoveryRequest;
+	struct ChargeParameterDiscoveryResponse_DIN70121		ChargeParameterDiscoveryResponse;
+	struct CableCheckRequest_DIN70121					CableCheckRequest;
+	struct CableCheckResponse_DIN70121					CableCheckResponse;
+	struct PreChargeRequest_DIN70121					PreChargeRequest;
+	struct PreChargeResponse_DIN70121 					PreChargeResponse;
+	struct PowerDeliveryRequest_DIN70121					PowerDeliveryRequest;
+	struct PowerDeliveryResponse_DIN70121	   				PowerDeliveryResponse;
+	struct CurrentDemandRequest_DIN70121 				CurrentDemandRequest;
+	struct CurrentDemandResponse_DIN70121				CurrentDemandResponse;
+	struct WeldingDetectionRequest_DIN70121 				WeldingDetectionRequest;
+	struct WeldingDetectionResponse_DIN70121  			WeldingDetectionResponse;
+	struct SessionStopRequest_DIN70121					SessionStopRequest;
+	struct SessionStopResponse_DIN70121	    				SessionStopResponse;
+};
+
+struct V2GMessageType_ISO15118_2014
+{
+	unsigned char											PresentMsgFlowStatus;
+														/* 0: Idle(wait B2 state), 1: CM_SLAC_PARM.REQ, 2: CM_SLAC_PARM.CNF, 3: CM_START_ATTEN_CHAR.IND
+														    4: CM_MNBC_SOUND.IND, 5: CM_ATTEN_CHAR.IND, 6: CM_ATTEN_CHAR.RSP, 7: CM_VALIDATE.REQ
+														    8: CM_VALIDATE.CNF, 9: CM_SLAC_MATCH.REQ, 10: CM_SLAC_MATCH.CNF, 11: CM_AMP_MAP.REQ
+														    12: CM_AMP_MAP.CNF, 13: SLACC/SDP/TCP connection,
+														    16: SupportedAppProtocolRequest, 17: SupportedAppProtocolResponse, 18: SessionSetupRequest
+														    19: SessionSetupResponse, 20: ServiceDiscoveryRequest, 21: ServiceDiscoveryResponse
+														    22: ServiceDetailRequest, 23: ServiceDetailResponse
+														    24: ServiceAndPaymentSelectionRequest/ServiceSelectionRequest, 25: ServiceAndPaymentSelectionResponse/ServiceSelectionResponse
+														    26: PaymentDetailsRequest/IdentificationDetailsRequest;, 27: PaymentDetailsResponse/IdentificationDetailsResponse,
+														     28: AuthorizationRequest, 29: AuthorizationResponse,
+														    30: CertificateUpdateRequest, 31: CertificateUpdateResponse, 32:CertificateInstallationRequest, 33: CertificateInstallationResponse
+														    34: ChargeParameterDiscoveryRequest, 35: ChargeParameterDiscoveryResponse
+														    36: CableCheckRequest, 37: CableCheckResponse, 38: PreChargeRequest, 39: PreChargeResponse
+														    40: PowerDeliveryRequest start, 41: PowerDeliveryResponse start, 42: ChargingStatusRequest, 43: ChargingStatusResponse
+														    44: CurrentDemandRequest, 45: CurrentDemandResponse, 46: MeteringReceiptRequest, 47: MeteringReceiptResponse
+														    48: PowerDeliveryRequest end, 49: PowerDeliveryRequest end, 50: WeldingDetectionRequest, 51: WeldingDetectionResponse,
+														    52: SessionStopRequest, 53: SessionStopResponse
+														   253: Performance Timeout, 254: Sequence Timeout, 255: Fault
+														*/
+	struct SupportedAppProtocolRequest_ISO15118_2014 			SupportedAppProtocolRequest;
+	struct SupportedAppProtocolResponse_ISO15118_2014 			SupportedAppProtocolResponse;
+	struct SessionSetupRequest_ISO15118_2014  					SessionSetupRequest;
+	struct SessionSetupResponse_ISO15118_2014   				SessionSetupResponse;
+	struct ServiceDiscoveryRequest_ISO15118_2014    				ServiceDiscoveryRequest;
+	struct ServiceDiscoveryResponse_ISO15118_2014    				ServiceDiscoveryResponse;
+	struct ServiceDetailRequest_ISO15118_2014 					ServiceDetailRequest;
+	struct ServiceDetailResponse_ISO15118_2014					ServiceDetailResponse;
+	struct ServiceAndPaymentSelectionRequest_ISO15118_2014 		ServiceAndPaymentSelectionRequest;
+	struct ServiceAndPaymentSelectionResponse_ISO15118_2014  	ServiceAndPaymentSelectionResponse;
+	struct PaymentDetailsRequest_ISO15118_2014 				PaymentDetailsRequest;
+	struct PaymentDetailsResponse_ISO15118_2014 				PaymentDetailsResponse;
+	struct AuthorizationRequest_ISO15118_2014					AuthorizationRequest;
+	struct AuthorizationResponse_ISO15118_2014					AuthorizationResponse;
+	struct CertificateUpdateRequest_ISO15118_2014				CertificateUpdateRequest;
+	struct CertificateUpdateResponse_ISO15118_2014				CertificateUpdateResponse;
+	struct CertificateInstallationRequest_ISO15118_2014			CertificateInstallationRequest;
+	struct CertificateInstallationResponse_ISO15118_2014			CertificateInstallationResponse;
+	struct ChargeParameterDiscoveryRequest_ISO15118_2014 		ChargeParameterDiscoveryRequest;
+	struct ChargeParameterDiscoveryResponse_ISO15118_2014  		ChargeParameterDiscoveryResponse;
+	struct CableCheckRequest_ISO15118_2014 					CableCheckRequest;
+	struct CableCheckResponse_ISO15118_2014  					CableCheckResponse;
+	struct PreChargeRequest_ISO15118_2014 					PreChargeRequest;
+	struct PreChargeResponse_ISO15118_2014					PreChargeResponse;
+	struct PowerDeliveryRequest_ISO15118_2014					PowerDeliveryRequest;
+	struct PowerDeliveryResponse_ISO15118_2014					PowerDeliveryResponse;
+	struct ChargingStatusRequest_ISO15118_2014	  				ChargingStatusRequest;
+	struct ChargingStatusResponse_ISO15118_2014				ChargingStatusResponse;
+	struct CurrentDemandRequest_ISO15118_2014	 			CurrentDemandRequest;
+	struct CurrentDemandResponse_ISO15118_2014				CurrentDemandResponse;
+	struct MeteringReceiptRequest_ISO15118_2014				MeteringReceiptRequest;
+	struct MeteringReceiptResponse_ISO15118_2014				MeteringReceiptResponse;
+	struct WeldingDetectionRequest_ISO15118_2014 				WeldingDetectionRequest;
+	struct WeldingDetectionResponse_ISO15118_2014  			WeldingDetectionResponse;
+	struct SessionStopRequest_ISO15118_2014 					SessionStopRequest;
+	struct SessionStopResponse_ISO15118_2014					SessionStopResponse;
+};
+struct V2GMessageType_ISO15118_2018
+{
+	unsigned char										PresentMsgFlowStatus;
+													/* 0: Idle(wait B2 state), 1: CM_SLAC_PARM.REQ, 2: CM_SLAC_PARM.CNF, 3: CM_START_ATTEN_CHAR.IND
+													    4: CM_MNBC_SOUND.IND, 5: CM_ATTEN_CHAR.IND, 6: CM_ATTEN_CHAR.RSP, 7: CM_VALIDATE.REQ
+													    8: CM_VALIDATE.CNF, 9: CM_SLAC_MATCH.REQ, 10: CM_SLAC_MATCH.CNF, 11: CM_AMP_MAP.REQ
+													    12: CM_AMP_MAP.CNF, 13: SLACC/SDP/TCP connection,
+													    16: SupportedAppProtocolRequest, 17: SupportedAppProtocolResponse, 18: SessionSetupRequest
+													    19: SessionSetupResponse, 20: ServiceDiscoveryRequest, 21: ServiceDiscoveryResponse
+													    22: ServiceDetailRequest, 23: ServiceDetailResponse
+													    24: ServiceAndPaymentSelectionRequest/ServiceSelectionRequest, 25: ServiceAndPaymentSelectionResponse/ServiceSelectionResponse
+													    26: PaymentDetailsRequest/IdentificationDetailsRequest;, 27: PaymentDetailsResponse/IdentificationDetailsResponse,
+													     28: AuthorizationRequest, 29: AuthorizationResponse,
+													    30: CertificateUpdateRequest, 31: CertificateUpdateResponse, 32:CertificateInstallationRequest, 33: CertificateInstallationResponse
+													    34: ChargeParameterDiscoveryRequest, 35: ChargeParameterDiscoveryResponse
+													    36: CableCheckRequest, 37: CableCheckResponse, 38: PreChargeRequest, 39: PreChargeResponse
+													    40: PowerDeliveryRequest start, 41: PowerDeliveryResponse start, 42: ChargingStatusRequest, 43: ChargingStatusResponse
+													    44: CurrentDemandRequest, 45: CurrentDemandResponse, 46: MeteringReceiptRequest, 47: MeteringReceiptResponse
+													    48: PowerDeliveryRequest end, 49: PowerDeliveryRequest end, 50: WeldingDetectionRequest, 51: WeldingDetectionResponse,
+													    52: SessionStopRequest, 53: SessionStopResponse
+													   253: Performance Timeout, 254: Sequence Timeout, 255: Fault
+													*/
+	struct SupportedAppProtocolRequest_ISO15118_2018			SupportedAppProtocolRequest;
+	struct SupportedAppProtocolResponse_ISO15118_2018 			SupportedAppProtocolResponse;
+	struct SessionSetupRequest_ISO15118_2018					SessionSetupRequest;
+	struct SessionSetupResponse_ISO15118_2018  					SessionSetupResponse;
+	struct ServiceDiscoveryRequest_ISO15118_2018    				ServiceDiscoveryRequest;
+	struct ServiceDiscoveryResponse_ISO15118_2018    				ServiceDiscoveryResponse;
+	struct ServiceDetailRequest_ISO15118_2018 					ServiceDetailRequest;
+	struct ServiceDetailResponse_ISO15118_2018					ServiceDetailResponse;
+	struct ServiceSelectionRequest_ISO15118_2018				ServiceSelectionRequest;
+	struct ServiceSelectionResponse_ISO15118_2018				ServiceSelectionResponse;
+	struct IdentificationDetailsRequest_ISO15118_2018  			IdentificationDetailsRequest;
+	struct IdentificationDetailsResponse_ISO15118_2018  			IdentificationDetailsResponse;
+	struct AuthorizationRequest_ISO15118_2018  					AuthorizationRequest;
+	struct AuthorizationResponse_ISO15118_2018					AuthorizationResponse;
+	struct CertificateInstallationRequest_ISO15118_2018			CertificateInstallationRequest;
+	struct CertificateInstallationResponse_ISO15118_2018			CertificateInstallationResponse;
+	struct ChargeParameterDiscoveryRequest_ISO15118_2018 		ChargeParameterDiscoveryRequest;
+	struct ChargeParameterDiscoveryResponse_ISO15118_2018  		ChargeParameterDiscoveryResponse;
+	struct CableCheckRequest_ISO15118_2018 					CableCheckRequest;
+	struct CableCheckResponse_ISO15118_2018 					CableCheckResponse;
+	struct PreChargeRequest_ISO15118_2018 					PreChargeRequest;
+	struct PreChargeResponse_ISO15118_2018					PreChargeResponse;
+	struct PowerDeliveryRequest_ISO15118_2018					PowerDeliveryRequest;
+	struct PowerDeliveryResponse_ISO15118_2018					PowerDeliveryResponse;
+	struct ChargingStatusRequest_ISO15118_2018	  				ChargingStatusRequest;
+	struct ChargingStatusResponse_ISO15118_2018				ChargingStatusResponse;
+	struct CurrentDemandRequest_ISO15118_2018	 			CurrentDemandRequest;
+	struct CurrentDemandResponse_ISO15118_2018				CurrentDemandResponse;
+	struct MeteringReceiptRequest_ISO15118_2018				MeteringReceiptRequest;
+	struct MeteringReceiptResponse_ISO15118_2018				MeteringReceiptResponse;
+	struct WeldingDetectionRequest_ISO15118_2018 				WeldingDetectionRequest;
+	struct WeldingDetectionResponse_ISO15118_2018  			WeldingDetectionResponse;
+	struct SessionStopRequest_ISO15118_2018 					SessionStopRequest;
+	struct SessionStopResponse_ISO15118_2018					SessionStopResponse;
+};
+
+struct CcsData
+{
+	unsigned char 							CommProtocol;	// 1: V2GMessage_DIN70121, 2:V2GMessage_ISO15118_2014, 3:V2GMessage_ISO15118_2018
+	struct V2GMessageType_DIN70121			V2GMessage_DIN70121[CCS_QUANTITY];
+	struct V2GMessageType_ISO15118_2014  		V2GMessage_ISO15118_2014[CCS_QUANTITY];
+	struct V2GMessageType_ISO15118_2018  		V2GMessage_ISO15118_2018[CCS_QUANTITY];
+};
+/**************************************************************************************/
+/***************STM32F407 Communication Share memory**************************/
+/**************************************************************************************/
+struct PrimaryMcuData
+{
+    unsigned char   SelfTest_Comp;
+    unsigned char   version[16];                                //STM32F407 firmware version
+    unsigned int    InputVoltage;                               //value comes from external meter
+    unsigned int    InputCurrent;                               //value comes from external meter
+    union
+    {
+        unsigned char OutputDrvValue[1];
+        struct
+        {
+            //OutputDrvValue[0]
+            unsigned char OnButtonLedDrv:1;                     //bit 0,    H: ON,      L:OFF
+            unsigned char OffButtonLedDrv:1;                    //bit 1,    H: ON,      L:OFF
+            unsigned char SystemLed1Drv:1;                      //bit 2,    H: ON,      L:OFF
+            unsigned char SystemLed2Drv:1;                      //bit 3,    H: ON,      L:OFF
+            unsigned char SystemLed3Drv:1;                      //bit 4,    H: ON,      L:OFF
+            unsigned char SystemLed4Drv:1;                      //bit 5,    H: ON,      L:OFF
+            unsigned char AcContactorDrv:1;                     //bit 6,    H: ON,      L:OFF
+            unsigned char:1;                                    //bit 7 reserved
+        }bits;
+    }OutputDrv;
+    union
+    {
+        unsigned char InputDetValue[2];
+        struct
+        {
+            //InputDetValue[0]
+            unsigned char AcContactorDetec:1;                   //bit 0,    H: ON,      L:OFF
+            unsigned char AcMainBreakerDetec:1;                 //bit 1,    H: ON,      L:OFF
+            unsigned char SpdDetec:1;                           //bit 2,    H: ON,      L:OFF
+            unsigned char DoorOpen:1;                           //bit 3,    H: Open,    L:Close
+            unsigned char Gfd1:1;                               //bit 4,    H: Trigger, L:Normal
+            unsigned char Gfd2:1;                               //bit 5,    H: Trigger, L:Normal
+            unsigned char Button1:1;                            //bit 6 ,   H: Push,    L:Release
+            unsigned char Button2:1;                            //bit 7,    H: Push,    L:Release
+            //InputDetValue[1]
+            unsigned char EmergencyButton:1;                    //bit 0,    H: Push,    L:Release
+            unsigned char Key0:1;                               //bit 1,    H: ON,      L:OFF
+            unsigned char Key1:1;                               //bit 2,    H: ON,      L:OFF
+            unsigned char Key2:1;                               //bit 3,    H: ON,      L:OFF
+            unsigned char Key3:1;                               //bit 4,    H: ON,      L:OFF
+            unsigned char Ac_Drop;                              //bit 4,    H: Trigger, L:Normal
+			unsigned char :2;                                   //bit 5~7,  Reserved
+        }bits;
+    }InputDet;
+};
+/**************************************************************************************/
+/*************Fan power module Communication Share memory******************/
+/**************************************************************************************/
+struct FanModuleData
+{
+	unsigned char  SelfTest_Comp;
+	unsigned char	version[16];			//fan power module firmware version
+	unsigned short	PresentFan1Speed;		//RPM
+	unsigned short	PresentFan2Speed;		//RPM
+	unsigned short	PresentFan3Speed;		//RPM
+	unsigned short	PresentFan4Speed;		//RPM
+	unsigned short	SetFan1Speed;			//RPM
+	unsigned short	SetFan2Speed;			//RPM
+	unsigned short	SetFan3Speed;			//RPM
+	unsigned short	SetFan4Speed;			//RPM
+	unsigned short	TestFanSpeed;			//RPM
+	unsigned char	DiffOfAirPressure;		//pa
+	unsigned char	UpdateFW;			//1:do update
+};
+
+/**************************************************************************************/
+/***********Relay control module Communication Share memory******************/
+/**************************************************************************************/
+struct RelayModuleData
+{
+	unsigned char 	SelfTest_Comp;
+	unsigned char	version[16];				//relay module firmware version
+	unsigned short	InputL1Volt;				//XXXXX.x volt
+	unsigned short	InputL2Volt;				//XXXXX.x volt
+	unsigned short	InputL3Volt;				//XXXXX.x volt
+	unsigned short	Gun1FuseOutputVolt;		//XXXXX.x volt
+	unsigned short	Gun2FuseOutputVolt;		//XXXXX.x volt
+	unsigned short	Gun1RelayOutputVolt;		//XXXXX.x volt
+	unsigned short	Gun2RelayOutputVolt;		//XXXXX.x volt
+	unsigned short	Gun1OutputCurrent;		//XXXXX.x amp
+	unsigned short	Gun2OutputCurrent;		//XXXXX.x amp
+	unsigned char	UpdateFW;				//1:do update
+};
+
+/**************************************************************************************/
+/***********Led control module Communication Share memory******************/
+/**************************************************************************************/
+struct LedModuleData
+{
+	unsigned char 	SelfTest_Comp;
+	unsigned char	version[16];				//led module firmware version
+	unsigned short	Connect_1_Status;			// Idle : 0, Charging : 1, Alarm : 2
+	unsigned short	Connect_2_Status;			// Idle : 0, Charging : 1, Alarm : 2
+	unsigned short	EnableFunc;					// reserved
+};
+
+/**************************************************************************************/
+/************************OCPP Share memory***************************************/
+/**************************************************************************************/
+struct StructIdTagInfo
+{
+	unsigned char 	ExpiryDate[36];
+	unsigned char 	ParentIdTag[21];
+	unsigned char 	Status[16];		//Accepted, Blocked, Expired, Invalid, ConcurrentTx
+};
+struct StructLocalAuthorizationList
+{
+	unsigned char 			IdTag[21];
+	struct StructIdTagInfo	IdTagInfo;
+};
+struct StructSampledValue
+{
+	unsigned char 			Value[128];
+	unsigned char 			Context[30];//Interruption.Begin, Interruption.End, Sample.Clock, Sample.Periodic, Transaction.Begin, Transaction.End, Trigger, Other
+	unsigned char 			Format[16];//Raw,SignedData
+	unsigned char 			Measurand[40];/*	"Energy.Active.Export.Register",
+										"Energy.Active.Import.Register",
+										"Energy.Reactive.Export.Register",
+										"Energy.Reactive.Import.Register",
+										"Energy.Active.Export.Interval",
+										"Energy.Active.Import.Interval",
+										"Energy.Reactive.Export.Interval",
+										"Energy.Reactive.Import.Interval",
+										"Power.Active.Export",
+										"Power.Active.Import",
+										"Power.Offered",
+										"Power.Reactive.Export",
+										"Power.Reactive.Import",
+										"Power.Factor",
+										"Current.Import",
+										"Current.Export",
+										"Current.Offered",
+										"Voltage",
+										"Frequency",
+										"Temperature",
+										"SoC",
+										"RPM"
+										*/
+
+	unsigned char 			Phase[10];	/*		"L1",
+										"L2",
+										"L3",
+										"N",
+										"L1-N",
+										"L2-N",
+										"L3-N",
+										"L1-L2",
+										"L2-L3",
+										"L3-L1"
+								*/
+
+	unsigned char 			Location[10];		//Cable,EV,Inlet,Outlet,Body
+	unsigned char 			Unit[20];	/*		"Wh",
+										"kWh",
+										"varh",
+										"kvarh",
+										"W",
+										"kW",
+										"VA",
+										"kVA",
+										"var",
+										"kvar",
+										"A",
+										"V",
+										"K",
+										"Celcius",
+										"Fahrenheit",
+										"Percent"
+								*/
+};
+struct StructMeterValue
+{
+	unsigned char 				TimeStamp[36];
+	struct StructSampledValue	SampledValue[20];
+};
+struct StructConfigurationKeyItems
+{
+	unsigned char 	Item[50];
+};
+struct StructConfigurationKey
+{
+	unsigned char 	Key[50];
+	unsigned char 	ReadOnly[8];	//boolean
+	unsigned char 	Value[500];
+};
+struct StructChargingSchedulePeriod
+{
+	int		StartPeriod;
+	float 	Limit;//0.1;
+	int		NumberPhases;
+};
+struct StructChargingSchedule
+{
+	int											Duration;
+	unsigned char 								StartSchedule[36];
+	unsigned char 								ChargingRateUnit[4];		//A, W
+	struct StructChargingSchedulePeriod			ChargingSchedulePeriod[10];
+	float 										MinChargingRate;			//0.1;
+};
+struct StructChargingProfile
+{
+	int								ChargingProfileId;
+	int								TransactionId;
+	int								StackLevel;
+	unsigned char 					ChargingProfilePurpose[24];	//ChargePointMaxProfile, TxDefaultProfile, TxProfile
+	unsigned char 					ChargingProfileKind[12];		//Absolute, Recurring, Relative
+	unsigned char 					RecurrencyKind[8];			//Daily, Weekly
+	unsigned char 					ValidFrom[36];
+	unsigned char 					ValidTo[36];
+	struct StructChargingSchedule	ChargingSchedule;
+};
+
+struct StructBootNotification
+{
+	unsigned char CpVendor[20];				//chargePointVendor				//mandatory
+	unsigned char CpModel[20];				//chargePointModel				//mandatory
+	unsigned char CpSN[25];					//chargePointSerialNumber
+	unsigned char CbSN[25];					//chargeBoxSerialNumber
+	unsigned char CpFwVersion[50];			//firmwareVersion
+	unsigned char CpIccid[22];				//iccid
+	unsigned char CpImsi[20];				//imsi
+	unsigned char CpMeterType[25];			//meterType
+	unsigned char CpMeterSerialNumber[25];	//meterSerialNumber
+	unsigned char ResponseStatus[16];			//Accepted, Pending, Rejected
+	unsigned char ResponseCurrentTime[36];	//currentTime					//mandatory
+	int 			ResponseHeartbeatInterval;	//interval						//mandatory
+
+};
+struct StructHeartbeat
+{
+	unsigned char 				ResponseCurrentTime[36];
+};
+struct StructAuthorize
+{
+	unsigned char 				IdTag[21];
+	struct StructIdTagInfo		ResponseIdTagInfo;
+};
+struct StructStartTransaction
+{
+	int 						ConnectorId;
+	unsigned char 				IdTag[21];
+	int 						MeterStart;
+	int 						ReservationId;
+	unsigned char 				Timestamp[36];
+	struct StructIdTagInfo		ResponseIdTagInfo;
+	int 						ResponseTransactionId;
+};
+struct StructStopTransaction
+{
+	unsigned char 				IdTag[21];
+	int 						MeterStop;
+	unsigned char 				Timestamp[36];
+	int 						TransactionId;
+	unsigned char 				StopReason[20];				/*	"EmergencyStop",
+															"EVDisconnected",
+															"HardReset",
+															"Local",
+															"Other",
+															"PowerLoss",
+															"Reboot",
+															"Remote",
+															"SoftReset",
+															"UnlockCommand",
+															"DeAuthorized"
+														*/
+	struct StructMeterValue		TransactionData[1];
+	struct StructIdTagInfo		ResponseIdTagInfo;
+};
+
+struct StructStatusNotification
+{
+	int 			ConnectorId;
+	unsigned char 	ErrorCode[25];				/*	"ConnectorLockFailure",
+								                "EVCommunicationError",
+								                "GroundFailure",
+								                "HighTemperature",
+								                "InternalError",
+								                "LocalListConflict",
+								                "NoError",
+								                "OtherError",
+								                "OverCurrentFailure",
+								                "PowerMeterFailure",
+								                "PowerSwitchFailure",
+								                "ReaderFailure",
+								                "ResetFailure",
+								                "UnderVoltage",
+								                "OverVoltage",
+								                "WeakSignal"
+								            */
+
+	unsigned char 	Info[50];
+	unsigned char 	Status[20];					/*	"Available",
+								                "Preparing",
+								                "Charging",
+								                "SuspendedEVSE",
+								                "SuspendedEV",
+								                "Finishing",
+								                "Reserved",
+								                "Unavailable",
+								                "Faulted"
+								            */
+
+	unsigned char 	Timestamp[36];
+	unsigned char 	VendorId[256];
+	unsigned char 	VendorErrorCode[50];
+};
+
+
+struct StructCancelReservation
+{
+	int 				ReservationId;
+	unsigned char 		ResponseStatus[16];		//Accepted, Rejected
+	unsigned char 		guid[37];
+};
+struct StructChangeAvailability
+{
+	int 				ConnectorId;
+	unsigned char 		Type[16];					//Inoperative, Operative
+	unsigned char 		ResponseStatus[16];		//Accepted, Rejected, Scheduled
+	unsigned char 		guid[37];
+};
+struct StructChangeConfiguration
+{
+	unsigned char Key[50];
+	unsigned char Value[500];
+	unsigned char ResponseStatus[16];		//Accepted, Rejected, RebootRequired, NotSupported
+};
+struct StructClearCache
+{
+	unsigned char ResponseStatus[16];		//Accepted, Rejected
+};
+struct StructClearChargingProfile
+{
+	int			 			Id;
+	int						ConnectorId;
+	unsigned char 			ChargingProfilePurpose[24];	//ChargePointMaxProfile, TxDefaultProfile, TxProfile
+	int			 			StackLevel;
+	unsigned char 			ResponseStatus[16];			//Accepted, Unknown
+};
+struct StructDataTransfer
+{
+	unsigned char VendorId[256];
+	unsigned char MessageId[52];
+	unsigned char Data[10240];
+	unsigned char ResponseStatus[18];	//Accepted, Rejected,UnknownMessageId,UnknownVendorId
+	unsigned char ResponseData[10240];
+};
+struct StructDiagnosticsStatusNotification
+{
+	unsigned char Status[16];		//Idle,Uploaded,UploadFailed,Uploading
+};
+struct StructFirmwareStatusNotification
+{
+	unsigned char Status[20];			//Downloaded,DownloadFailed,Downloading,Idle,InstallationFailed,Installing,Installed
+};
+struct StructGetCompositeSchedule
+{
+	int 							ConnectorId;
+	int 							Duration;
+	unsigned char					ChargingRateUnit[4];		//A,W
+	unsigned char 					ResponseStatus[12];			//Accepted,Rejected
+	int 							ResponseConnectorId;
+	unsigned char					ResponseScheduleStart[36];
+	struct StructChargingSchedule	ResponseChargingSchedule;
+};
+struct StructGetConfiguration
+{
+	struct StructConfigurationKeyItems 			*Key;
+	struct StructConfigurationKey			 	*ResponseConfigurationKey;
+	struct StructConfigurationKeyItems 			*ResponseUnknownKey;
+
+};
+struct StructGetDiagnostics
+{
+	unsigned char 			Location[256];
+	int 					Retries;
+	int						RetryInterval;
+	unsigned char 			StartTime[36];
+	unsigned char 			StopTime[36];
+	unsigned char 			ResponseFileName[256];
+};
+struct StructGetLocalListVersion
+{
+	int ResponseListVersion;
+};
+struct StructMeterValues
+{
+	int					 			ConnectorId;
+	int 							TransactionId;
+	struct StructMeterValue			MeterValue[1];
+};
+struct StructRemoteStartTransaction
+{
+	int								ConnectorId;
+	unsigned char 					IdTag[21];
+	struct StructChargingProfile	ChargingProfile;
+	unsigned char 					ResponseStatus[10];	//Accepted,	Rejected
+	unsigned char 					guid[37];
+};
+struct StructRemoteStopTransaction
+{
+	int 				TransactionId;
+	unsigned char 		ResponseStatus[10];	//Accepted,	Rejected
+};
+struct StructReserveNow
+{
+	int			 		ConnectorId;
+	unsigned char 		ExpiryDate[36];
+	unsigned char 		IdTag[21];
+	unsigned char 		ParentIdTag[21];
+	int					ReservationId;
+	unsigned char 		ResponseStatus[12];		//Accepted, Faulted, Occupied, Rejected, Unavailable
+	unsigned char 		guid[37];   			//OCPP Server request message uuid
+};
+struct StructReset
+{
+	unsigned char		Type[8];			//Hard,	Soft
+	unsigned char 		ResponseStatus[10];	//Accepted,	Rejected
+	unsigned char 		guid[37];   		//OCPP Server request message uuid
+};
+struct StructSendLocalList
+{
+	int										ListVersion;
+	unsigned char 							UpdateType[16];	//Differential,	Full
+	struct StructLocalAuthorizationList		*LocalAuthorizationList;
+	unsigned char 							ResponseStatus[16];	//Accepted,	Failed, NotSupported, VersionMismatch
+};
+struct StructSetChargingProfile
+{
+	int 								ConnectorId;
+	struct StructChargingProfile		ChargingProfile;
+	unsigned char				 		ResponseStatus[16];	//Accepted,	Rejected, NotSupported
+};
+struct StructTriggerMessage
+{
+	unsigned char 		RequestedMessage[32];	/*
+											"BootNotification",
+											"DiagnosticsStatusNotification",
+											"FirmwareStatusNotification",
+											"Heartbeat",
+											"MeterValues",
+											"StatusNotification"
+										*/
+	int					ConnectorId;
+	unsigned char 		ResponseStatus[16];	//Accepted,	Rejected, NotImplemented
+};
+struct StructUnlockConnector
+{
+	int					ConnectorId;
+	unsigned char 		ResponseStatus[16];	//Unlocked,	UnlockFailed, NotSupported
+	unsigned char 		guid[37];   		//OCPP Server request message uuid
+};
+struct StructUpdateFirmware
+{
+	unsigned char 		Location[256];
+	int					Retries;
+	unsigned char 		RetrieveDate[36];
+	int 				RetryInterval;
+};
+
+struct OCPP16ConfigurationItem
+{
+	unsigned char 		ItemName[64];
+	unsigned char 		ItemAccessibility;//0:RO, 1:RW
+	unsigned char 		ItemData[501];//value should be limited in 500 bytes
+};
+
+struct OCPP16ConfigurationTable
+{
+	//please refer to OCPP 1.6 chapter 9
+	struct OCPP16ConfigurationItem 			CoreProfile[_CoreProfile_CNT];
+	struct OCPP16ConfigurationItem 			LocalAuthListManagementProfile[3];
+	struct OCPP16ConfigurationItem 			ReservationProfile[1];
+	struct OCPP16ConfigurationItem 			SmartChargingProfile[5];
+};
+
+
+struct StrcutSetUserPrice
+{
+    unsigned char   idToken[21];
+    unsigned char   price[1024];
+};
+
+struct ChargingPrice
+{
+    float kWhPrice;                                 // Price per kWh
+    float hourPrice;                                // Price per hour of charging
+    float flatFee;                                  // Flat fee for (part of) charging session
+};
+
+struct IdlePrice
+{
+    unsigned int graceMinutes;                      // Grace period in minutes before idle time is charged
+    float hourPrice;                                // Price per hour while idle
+};
+
+struct NextPeriod
+{
+    unsigned char atTime[36];                       // Time when these prices become active
+    struct ChargingPrice chargingPrice;             // Price components while charging
+    struct IdlePrice idlePrice;                     // Price components while idle. Optional if no idle fee charged.
+};
+
+struct Triggers
+{
+    unsigned char atTime[36];                       // Time when these prices become active
+    float atEnergykWh;                              // Consumed energy amount in kWh upon which a meter value must be sent
+    float atPowerkW;                                // Power threshold in kW when meter value must be sent when crossing in downward or upward direction. Can either
+                                                    // be used to trigger a meter value when vehicle stops charging or when vehicle charges at a high power that requires a
+                                                    // different tariff.
+                                                    // It is recommended to implement a hysteresis around this value to avoid repetitive triggers when the power fluctuates around this level.
+    unsigned char atCPStatus[100];
+};
+
+struct StrcutRunningCost
+{
+    int                     txId;                   // Transaction to which this applies
+    unsigned char           timestamp[36];          // Timestamp of the meter value upon which this cost is based
+    unsigned int            meterValue;             // Meter value (Wh) upon which this cost is based
+    float                   cost;                   // Calculated total running cost
+    unsigned char           state[16];              // "Charging" or "Idle"
+    struct ChargingPrice    chargingPrice;          // Price components while charging
+    struct IdlePrice        idlePrice;              // (optional) Price components while not charging. Optional if no idle fee is charged.
+    struct NextPeriod       nextPeriod;             // (optional) Pricing for next period
+    struct Triggers         triggerMeterValue;      // (optional) Triggers to request a new meter value. Optional if no idle fee charged.
+    unsigned char           description[1024];      // Compatible California pricing V1.0
+};
+
+struct StrcutFinalCost
+{
+    int             txId;
+    unsigned char   description[1024];
+
+    float           cost;
+    unsigned char   priceText[1024];
+    unsigned char   qrCodeText[1024];
+};
+
+struct StructCost
+{
+    struct StrcutSetUserPrice       SetUserPrice;
+    struct StrcutRunningCost        RunningCost[CONNECTOR_QUANTITY];
+    struct StrcutFinalCost          FinalCost[CONNECTOR_QUANTITY];
+};
+
+struct CertificateHashDataType
+{
+    unsigned char hashAlgorithm[8];                             // Required. Used algorithms for the hashes provided.
+    unsigned char issuerNameHash[129];                          // Required. hashed value of the IssuerName.
+    unsigned char issuerKeyHash[129];                           // Required. Hashed value of the issuers public key
+    unsigned char serialNumber[41];                             // Required. The serial number of the certificate.
+};
+
+struct LogParametersType
+{
+    unsigned char remoteLocation[513];                              // Required. The URL of the location at the remote system where the log should be stored.
+    unsigned char oldestTimestamp[36];                              // Optional. This contains the date and time of the oldest logging information to include in the diagnostics.
+    unsigned char latestTimestamp[36];                              // Optional. This contains the date and time of the latest logging information to include in the diagnostics.
+};
+
+struct FirmwareType
+{
+    unsigned char location[513];                                    // Required. URI defining the origin of the firmware.
+    unsigned char retrieveDateTime[36];                             // Required. Date and time at which the firmware shall be retrieved.
+    unsigned char installDateTime[36];                              // Optional. Date and time at which the firmware shall be installed.
+    unsigned char signingCertificate[5501];                         // Optional. Certificate with which the firmware was signed. X.509 certificate, first DER encoded into binary, and then Base64 encoded.
+    unsigned char signature[801];                                   // Optional. Base64 encoded firmware signature.
+};
+
+struct StructCertificateSigned
+{
+    unsigned char certificateChain[10001];
+    unsigned char Response_status[16];
+};
+
+struct StructDeleteCertificate
+{
+    struct CertificateHashDataType certificateHashData;
+    unsigned char Response_status[16];
+};
+
+struct StructExtendedTrigger
+{
+    unsigned char requestedMessage[32];
+    int connectorId;
+    unsigned char Response_status[16];
+};
+
+struct StructGetInstalledCertificateIds
+{
+    unsigned char certificateType[32];
+    unsigned char Response_status[16];
+    struct CertificateHashDataType Response_certificateHashData[3];
+};
+
+struct StructGetLog
+{
+    unsigned char logType[16];
+    int requestId;
+    int retries;
+    int retryInterval;
+    struct LogParametersType log;
+    unsigned char Response_status[16];
+    unsigned char Response_filename[256];
+};
+
+struct StructInstallCertificate
+{
+    unsigned char certificateType[32];
+    unsigned char certificate[5501];
+    unsigned char Response_status[16];
+};
+
+struct StructSignedUpdateFirmware
+{
+    int retries;
+    int retryInterval;
+    int requestId;
+    struct FirmwareType firmware;
+    unsigned char Response_status[16];
+};
+
+struct StructLogStatusNotification
+{
+    unsigned char status[32];
+    int requestId;
+};
+
+struct StructSecurityEventNotification
+{
+    unsigned char type[51];
+    unsigned char timestamp[28];
+    unsigned char techInfo[256];
+};
+
+struct StructSignCertificate
+{
+    unsigned char csr[5501];
+    unsigned char Response_status[16];
+};
+
+struct StructSignedFirmwareStatusNotification
+{
+    unsigned char status[32];
+    int requestId;
+};
+
+struct StructSessionTarget
+{
+    unsigned char       targetSoc;          // Unit: %,         0 is unlimit
+    unsigned short      targetEnergy;       // Unit: KWH        0 is unlimit
+    unsigned short      targetDuration;     // Unit: Minutes    0 is unlimit
+};
+
+/**************************************************************************************/
+/************************* OCPP 2.0 Share memory **************************************/
+/**************************************************************************************/
+/*
+ * =============== Enum variable content ===============
+ */
+enum OCPP20CtrlrVariable
+{
+	AlignedDataCtrlr_Enabled=0,
+	AlignedDataCtrlr_Available,
+	AlignedDataCtrlr_Measurands,
+	AlignedDataCtrlr_Interval,
+	AlignedDataCtrlr_SendDuringIdle,
+	AlignedDataCtrlr_SignReadings,
+	AlignedDataCtrlr_TxEndedMeasurands,
+	AlignedDataCtrlr_TxEndedInterval,
+	AuthCtrlr_Enabled,
+	AuthCtrlr_AdditionalInfoItemsPerMessage,
+	AuthCtrlr_OfflineTxForUnknownIdEnabled,
+	AuthCtrlr_AuthorizeRemoteStart,
+	AuthCtrlr_LocalAuthorizeOffline,
+	AuthCtrlr_LocalPreAuthorize,
+	AuthCtrlr_MasterPassGroupId,
+	AuthCacheCtrlr_Enabled,
+	AuthCacheCtrlr_Available,
+	AuthCacheCtrlr_LifeTime,
+	AuthCacheCtrlr_Storage,
+	AuthCacheCtrlr_Policy,
+	ClockCtrlr_DateTime,
+	ClockCtrlr_NtpSource,
+	ClockCtrlr_NtpServerUri,
+	ClockCtrlr_TimeOffset,
+	ClockCtrlr_NextTimeOffsetTransitionDateTime,
+	ClockCtrlr_NextTransition_TimeOffset,
+	ClockCtrlr_TimeSource,
+	ClockCtrlr_TimeZone,
+	ChargingStation_Available,
+	ChargingStation_AvailabilityState,
+	ChargingStation_SupplyPhases,
+	ChargingStation_SystemUptimeSec,
+	ChargingStation_FreeVend,
+	ChargingStation_FreeVendIdtag,
+	ChargingStation_OffLineMaxChargingPower,
+	Connector_Available,
+	Connector_ConnectorType,
+	Connector_SupplyPhases,
+	CustomizationCtrlr_CustomImplementationEnabled,
+	DeviceDataCtrlr_GetReport_ItemsPerMessage,
+	DeviceDataCtrlr_GetVariables_ItemsPerMessage,
+	DeviceDataCtrlr_GetReport_BytesPerMessage,
+	DeviceDataCtrlr_GetVariables_BytesPerMessage,
+	DeviceDataCtrlr_ConfigurationValueSize,
+	DeviceDataCtrlr_ReportingValueSize,
+	DeviceDataCtrlr_SetVariables_ItemsPerMessage,
+	DeviceDataCtrlr_SetVariables_BytesPerMessage,
+	DisplayMessageCtrlr_Enabled,
+	DisplayMessageCtrlr_Available,
+	DisplayMessageCtrlr_DisplayMessages,
+	DisplayMessageCtrlr_SupportedFormats,
+	DisplayMessageCtrlr_SupportedPriorities,
+	EVSE_Available,
+	EVSE_AvailabilityState,
+	EVSE_SupplyPhases,
+	EVSE_Power,
+	LocalAuthListCtrlr_Enabled,
+	LocalAuthListCtrlr_Entries,
+	LocalAuthListCtrlr_Available,
+	LocalAuthListCtrlr_ItemsPerMessage,
+	LocalAuthListCtrlr_BytesPerMessage,
+	LocalAuthListCtrlr_Storage,
+	MonitoringCtrlr_Enabled,
+	MonitoringCtrlr_Available,
+	MonitoringCtrlr_ClearVariableMonitoring_ItemsPerMessage,
+	MonitoringCtrlr_SetVariableMonitoring_ItemsPerMessage,
+	MonitoringCtrlr_ClearVariableMonitoring_BytesPerMessage,
+	MonitoringCtrlr_SetVariableMonitoring_BytesPerMessage,
+	MonitoringCtrlr_OfflineQueuingSeverity,
+	OCPPCommCtrlr_ActiveNetworkProfile,
+	OCPPCommCtrlr_MessageTimeout,
+	OCPPCommCtrlr_FileTransferProtocols,
+	OCPPCommCtrlr_HeartbeatInterval,
+	OCPPCommCtrlr_NetworkConfigurationPriority,
+	OCPPCommCtrlr_NetworkProfileConnectionAttempts,
+	OCPPCommCtrlr_OfflineThreshold,
+	OCPPCommCtrlr_QueueAllMessages,
+	OCPPCommCtrlr_MessageAttempts,
+	OCPPCommCtrlr_MessageAttemptInterval,
+	OCPPCommCtrlr_UnlockOnEVSideDisconnect,
+	OCPPCommCtrlr_WebSocketPingInterval,
+	OCPPCommCtrlr_ResetRetries,
+	OCPPCommCtrlr_PublicKeyWithSignedMeterValue,
+    OCPPCommCtrlr_StatusNotificationPeriodically,
+    OCPPCommCtrlr_StatusNotificationInterval,
+	OCPPCommCtrlr_CharingProfileRefreshInterval,
+    OCPPCommCtrlr_VariableVersion,
+	ReservationCtrlr_Enabled,
+	ReservationCtrlr_Available,
+	ReservationCtrlr_NonEvseSpecific,
+	SampledDataCtrlr_Enabled,
+	SampledDataCtrlr_Available,
+	SampledDataCtrlr_SignReadings,
+	SampledDataCtrlr_TxEndedMeasurands,
+	SampledDataCtrlr_TxEndedInterval,
+	SampledDataCtrlr_TxStartedMeasurands,
+	SampledDataCtrlr_TxUpdatedMeasurands,
+	SampledDataCtrlr_TxUpdatedInterval,
+	SecurityCtrlr_BasicAuthPassword,
+	SecurityCtrlr_Identity,
+	SecurityCtrlr_OrganizationName,
+	SecurityCtrlr_CertificateEntries,
+	SecurityCtrlr_SecurityProfile,
+	SecurityCtrlr_AdditionalRootCertificateCheck,
+	SecurityCtrlr_MaxCertificateChainSize,
+	SmartChargingCtrlr_Enabled,
+	SmartChargingCtrlr_Available,
+	SmartChargingCtrlr_ACPhaseSwitchingSupported,
+	SmartChargingCtrlr_ProfileStackLevel,
+	SmartChargingCtrlr_RateUnit,
+	SmartChargingCtrlr_PeriodsPerSchedule,
+	SmartChargingCtrlr_ExternalControlSignalsEnabled,
+	SmartChargingCtrlr_NotifyChargingLimitWithSchedules,
+	SmartChargingCtrlr_Phases3to1,
+	SmartChargingCtrlr_Entries,
+	SmartChargingCtrlr_LimitChangeSignificance,
+	Tariff_Enabled,
+	Tariff_Available,
+	Tariff_TariffFallbackMessage,
+	Cost_Enabled,
+	Cost_Available,
+	Cost_TotalCostFallbackMessage,
+	Cost_Currency,
+	TxCtrlr_ChargingBeforeAcceptedEnabled,
+	TxCtrlr_EVConnectionTimeOut,
+	TxCtrlr_StopTxOnEVSideDisconnect,
+	TxCtrlr_TxBeforeAcceptedEnabled,
+	TxCtrlr_TxStartPoint,
+	TxCtrlr_TxStopPoint,
+	TxCtrlr_MaxEnergyOnInvalidId,
+	TxCtrlr_StopTxOnInvalidId,
+	CtrlrVariable_CNT
+};
+
+/*
+ * =============== Common class ===============
+ */
+struct ACChargingParametersType
+{
+	int energyAmount;											// Required, Amount of energy requested (in Wh). This includes energy required for preconditioning.
+	int evMinCurrent;											// Required. Minimum current (amps) supported by the electric vehicle (per phase).
+	int evMaxCurrent;											// Required. Maximum current (amps) supported by the electric vehicle (per phase). Includes cable capacity.
+	int evMaxVoltage;											// Required. Maximum voltage supported by the electric vehicle
+};
+
+struct DCChargingParametersType
+{
+	int evMaxCurrent;											// Required. Maximum current (amps) supported by the electric vehicle. Includes cable capacity.
+	int evMaxVoltage;											// Required. Maximum voltage supported by the electric vehicle
+	int energyAmount;											// Optional. Amount of energy requested (in Wh). This inludes energy required for preconditioning.
+	int evMaxPower;												// Optional. Maximum power (in W) supported by the electric vehicle. Required for DC charging.
+	unsigned char stateOfCharge;								// Optional. Energy available in the battery (in percent of the battery capacity)
+	int evEnergyCapacity;										// Optional. Capacity of the electric vehicle battery (in Wh)
+	unsigned char fullSoC;										// Optional. Percentage of SoC at which the EV considers the battery fully charged. (possible values: 0 - 100)
+	unsigned char bulkSoC;										// Optional. Percentage of SoC at which the EV considers a fast charging process to end. (possible values: 0 - 100)
+};
+
+struct AdditionalInfoType
+{
+	unsigned char	additionalIdToken[37];						// Required. This field specifies the additional IdToken.
+	unsigned char	type[51];									// Required. This defines the type of the additionalIdToken. This is a custom type, so the implementation needs to be agreed upon by all involved parties.
+};
+
+struct APNType
+{
+	unsigned char apn[512];										// Required. The Access Point Name as an URL.
+	unsigned char apnUserName[20];								// Optional. APN user name.
+	unsigned char apnPassword[20];								// Optional. APN Password.
+	short int	simPin;											// Optional. SIM card pin code.
+	unsigned char	preferredNetwork[6];						// Optional. Preferred network, written as MCC and MNC concatenated. See note.
+	unsigned char useOnlyPreferredNetwork;						// Optional. Default: false. Use only the preferred Network, do not dial in when not available. See Note.
+	short int apnAuthentication[8];								// Required. Authentication method.
+};
+
+struct VPNType
+{
+	unsigned char server[512];									// Required. VPN Server Address
+	unsigned char user[20];										// Required. VPN User
+	unsigned char group[20];									// Optional. VPN group.
+	unsigned char password[20];									// Required. VPN Password.
+	unsigned char key[255];										// Required. VPN shared secret.
+	unsigned char type[8];										// Required. Type of VPN
+};
+
+struct GroupIdTokenType
+{
+	unsigned char idToken[37];									// Required. IdToken is case insensitive. Might hold the hidden id of an RFID tag, but can for example also contain a UUID.
+	unsigned char type[16];										// Required. Enumeration of possible idToken types.
+	//struct AdditionalInfoType additionalInfo[10];               // Optional. AdditionalInfo can be used to send extra information which can be validated by the CSMS in addition to the regular authorization with IdToken.
+};
+
+struct MessageContentType
+{
+	unsigned char format[8];									// Required. Format of the message.
+	unsigned char	language[9];								// Optional. Message language identifier. Contains a language code as defined in [RFC5646].
+	unsigned char content[513];									// Required. Message contents.
+};
+
+struct IdTokenInfoType
+{
+	unsigned char status[32];									// Required. Current status of the ID Token.
+	unsigned char cacheExpiryDateTime[28];						// Optional. Date and Time after which the token must be considered invalid.
+	short int	chargingPriority;								// Optional. Priority from a business point of view. Default priority is 0, The range is from -9 to 9. Higher values indicate a higher priority.
+	unsigned char language1[9];									// Optional. Preferred user interface language of identifier user. Contains a language code as defined in [RFC5646].
+	unsigned int evseId[100];									// Optional. Only used when the IdToken is only valid for one or more specific EVSEs, not for the entire Charging Station.
+	unsigned char language2[9];									// Optional. Second preferred user interface language of identifier user. Don’t use when language1 is omitted, has to be different from language1.
+	struct GroupIdTokenType groupIdToken;						// Optional. This contains the group identifier.
+	struct MessageContentType personalMessage;					// Optional. Personal message that can be shown to the EV Driver and can be used for tariff information, user greetings etc.
+};
+
+struct IdTokenType
+{
+	unsigned char idToken[37];									// Required. IdToken is case insensitive. Might hold the hidden id of an RFID tag, but can for example also contain a UUID.
+	unsigned char	type[16];									// Required. Enumeration of possible idToken types.
+	struct AdditionalInfoType additionalInfo[10];				// Optional. AdditionalInfo can be used to send extra information which can be validated by the CSMS in addition to the regular authorization with IdToken.
+};
+
+struct AuthorizationData
+{
+	struct IdTokenInfoType idTokenInfo;							// Optional. Required when UpdateType is Full. This contains information about authorization status, expiry and group id.
+	struct IdTokenType idToken;									// Required. This contains the identifier which needs to be stored for authorization.
+};
+
+struct CertificateHashDataChainType
+{
+	unsigned char certificateType[32];							// Required. Indicates the type of the requested certificate(s).
+	struct CertificateHashDataType certificateHashData;			// Required. Information to identify a certificate.
+	struct CertificateHashDataType childCertificateHashData[4]; // Optional. Information to identify the child certificate(s).
+};
+
+
+struct ChargingLimitType
+{
+	unsigned char chargingLimitSource[8];						// Required. Represents the source of the charging limit.
+	unsigned char isGridCritical;								// Optional. Indicates whether the charging limit is critical for the grid.
+};
+
+struct ChargingNeedsType
+{
+	unsigned char requestedEnergyTransfer[32];					// Required. Mode of energy transfer requested by the EV.
+	unsigned char departureTime[28];							// Optional. Estimated departure time of the EV.
+	struct ACChargingParametersType acChargingParameters;		// Optional. EV AC charging parameters.
+	struct DCChargingParametersType dcChargingParameters;		// Optional. EV DC charging parameters
+};
+
+struct ChargingProfileCriterionType
+{
+	unsigned char chargingProfilePurpose[36];					// Optional. Defines the purpose of the schedule transferred by this profile
+	unsigned short int stackLevel;								// Optional. Value determining level in hierarchy stack of profiles. Higher values have precedence over lower values. Lowest level is 0.
+	unsigned short int chargingProfileId[10];					// Optional. List of all the chargingProfileIds requested. Any ChargingProfile that matches one of these profiles will be reported.
+	unsigned char chargingLimitSource[4][8];					// Optional. For which charging limit sources, charging profiles SHALL be reported. If omitted, the Charging Station SHALL not filter on chargingLimitSource.
+};
+
+struct RelativeTimeIntervalTypeOCPP
+{
+	unsigned int start;											// Required. Start of the interval, in seconds from NOW.
+	unsigned int duration;										// Optional. Duration of the interval, in seconds.
+};
+
+struct CostTypeOCPP
+{
+	unsigned char costKind[36];									// Required. The kind of cost referred to in the message element amount
+	int amount;													// Required. The estimated or actual cost per kWh
+	int amountMultiplier;                                       // Optional. Values: -3..3, The amountMultiplier defines the exponent to base 10 (dec). The final value is determined by: amount * 10 ^ amountMultiplier
+};
+
+struct ConsumptionCostTypeOCPP
+{
+	float startValue;											// Required. The lowest level of consumption that defines the starting point of this consumption block. The block interval extends to the start of the next interval.
+	struct CostTypeOCPP cost[3];								// Required. This field contains the cost details.
+};
+
+struct SalesTariffEntryTypeOCPP
+{
+	unsigned short int ePriceLevel;								// Optional. Defines the price level of this SalesTariffEntry (referring to NumEPriceLevels). Small values for the EPriceLevel represent a cheaper TariffEntry. Large values for the EPriceLevel represent a more expensive TariffEntry.
+	struct RelativeTimeIntervalTypeOCPP relativeTimeInterval;	// Required. Defines the time interval the SalesTariffEntry is valid for, based upon relative times.
+	struct ConsumptionCostTypeOCPP consumptionCost[3];			// Optional. Defines additional means for further relative price information and/or alternative costs.
+};
+
+struct SalesTariffTypeOCPP
+{
+	unsigned short int id;										// Required. SalesTariff identifier used to identify one sales tariff. An SAID remains a unique identifier for one schedule throughout a charging session.
+	unsigned char salesTariffDescription[32];					// Optional. A human readable title/short description of the sales tariff e.g. for HMI display purposes.
+	unsigned short int numEPriceLevels;							// Optional. Defines the overall number of distinct price levels used across all provided SalesTariff elements.
+	struct SalesTariffEntryTypeOCPP salesTariffEntry[1024];		// Required. Encapsulating element describing all relevant details for one time interval of the SalesTariff. The number of SalesTariffEntry elements is limited by the parameter maxScheduleTuples.
+};
+
+struct ChargingSchedulePeriodType
+{
+	int startPeriod;											// Required. Start of the period, in seconds from the start of schedule. The value of StartPeriod also defines the stop time of the previous period.
+	float limit;												// Required. Charging rate limit during the schedule period, in the applicable chargingRateUnit, for example in Amperes (A) or Watts (W). Accepts at most one digit fraction (e.g. 8.1).
+	unsigned char	numberPhases;								// Optional. The number of phases that can be used for charging. If a number of phases is needed, numberPhases=3 will be assumed unless another number is given.
+	unsigned char phaseToUse;									// Optional. Values: 1..3, Used if numberPhases=1 and if the EVSE is capable of switching the phase connected to theEV, i.e. ACPhaseSwitchingSupported is defined and true.
+};
+
+struct ChargingScheduleType
+{
+	unsigned char startSchedule[28];							// Optional. Starting point of an absolute schedule. If absent the schedule will be relative to start of charging.
+	unsigned int duration;										// Optional. Duration of the charging schedule in seconds.
+	unsigned char chargingRateUnit[8];							// Required. The unit of measure Limit is expressed in.
+	float minChargingRate;										// Optional. Minimum charging rate supported by the EV.
+	unsigned short int id;										// Required. Identifies the ChargingSchedule.
+	struct ChargingSchedulePeriodType chargingSchedulePeriod[1024];	// Required. List of ChargingSchedulePeriod elements defining maximum power or current usage over time.
+	struct SalesTariffTypeOCPP salesTariff;						// Optional. Sales tariff associated with this charging schedule.
+};
+
+struct ChargingProfileType
+{
+	int id;											                // Required. Id of ChargingProfile.
+	unsigned short int stackLevel;									// Required. Value determining level in hierarchy stack of profiles. Higher values have precedence over lower values. Lowest level is 0.
+	unsigned char chargingProfilePurpose[36];						// Required. Defines the purpose of the schedule transferred by this profile
+	unsigned char chargingProfileKind[16];							// Required. Indicates the kind of schedule.
+	unsigned char recurrencyKind[8];								// Optional. Indicates the start point of a recurrence.
+	unsigned char validFrom[28];									// Optional. Point in time at which the profile starts to be valid. If absent, the profile is valid as soon as it is received by the Charging Station.
+	unsigned char validTo[28];										// Optional. Point in time at which the profile stops to be valid. If absent, the profile is valid until it is replaced by another profile.
+	unsigned char transactionId[37];								// Optional. SHALL only be included if ChargingProfilePurpose is set to TxProfile. The transactionId is used to match the profile to a specific transaction.
+	struct ChargingScheduleType chargingSchedule[3];				// Required. Schedule that contains limits for the available power or current over time. In order to support ISO 15118 schedule negotiation, it supports at most three schedules with associated tariff to choose from.
+};
+
+struct ModemType
+{
+	unsigned char iccid[20];										// Optional. This contains the ICCID of the modem’s SIM card.
+	unsigned char imsi[20];											// Optional. This contains the IMSI of the modem’s SIM card.
+};
+
+struct ChargingStationType
+{
+	unsigned char serialNumber[25];									// Optional. Vendor-specific device identifier.
+	unsigned char model[20];										// Required. Defines the model of the device.
+	unsigned char vendorName[50];									// Required. Identifies the vendor (not necessarily in a unique manner).
+	unsigned char firmwareVersion[50];								// Optional. This contains the firmware version of the Charging Station.
+	struct ModemType modem;											// Optional. Defines the functional parameters of a communication link.
+};
+
+struct ClearChargingProfileType
+{
+	unsigned int evseId;											// Optional. Specifies the id of the EVSE for which to clear charging profiles.
+	unsigned char chargingProfilePurpose[36];						// Optional. Specifies to purpose of the charging profiles that will be cleared, if they meet the other criteria in the request.
+	unsigned short int stackLevel;									// Optional. Specifies the stackLevel for which charging profiles will be cleared, if they meet the other criteria in the request.
+};
+
+struct ClearMonitoringResultType
+{
+	unsigned short int id;											// Required. Id of the monitor of which a clear was requested.
+	unsigned char status[16];										// Required. Result of the clear request for this monitor, identified by its Id.
+};
+
+struct EVSEType
+{
+	unsigned int id;												// Required. EVSE Identifier. This contains a number (> 0) designating an EVSE of the Charging Station.
+	unsigned char connectorId;										// Optional. An id to designate a specific connector (on an EVSE) by connector index number.
+};
+
+struct VariableType
+{
+	unsigned char name[50];											// Required. Name of the variable.
+	unsigned char instance[50];										// Optional. Name of instance in case the variable exists as multiple instances.
+};
+
+struct VariableAttributeType
+{
+	unsigned char type[8];											// Optional. Attribute: Actual, MinSet, MaxSet, etc. Defaults to Actual if absent.
+	unsigned char value[2500];										// Optional. Value of the attribute. May only be omitted when mutability is set to 'WriteOnly'.
+	unsigned char mutability[16];									// Optional. Defines the mutability of this attribute. Default is ReadWrite when omitted.
+	unsigned char persistent;										// Optional. If true, value will be persistent across system reboots or power down. Default when omitted is false.
+	unsigned char constant;											// Optional. If true, value that will never be changed by the Charging Station at runtime. Default when omitted is false.
+};
+
+struct VariableCharacteristicsType
+{
+	unsigned char unit[16];											// Optional. Unit of the variable. When the transmitted value has a unit, this field SHALL be included.
+	unsigned char dataType[16];										// Required. Data type of this variable.
+	float 	minLimit;												// Optional. Minimum possible value of this variable.
+	float 	maxLimit;												// Optional. Maximum possible value of this variable.
+	unsigned char valuesList[1000];									// Optional. Allowed values when variable is Option/Member/SequenceList.
+	unsigned char supportsMonitoring;								// Required. Flag indicating if this variable supports monitoring.
+};
+
+struct ComponentType
+{
+	unsigned char name[50];											// Required. Name of the component.
+	unsigned char instance[50];										// Optional. Name of instance in case the component exist as multiple instances.
+	struct EVSEType evse;											// Optional. Specifies the EVSE when component is located at EVSE level, also specifies the connector when component is located at Connector level.
+};
+
+struct ComponentVariableType
+{
+	struct ComponentType component;									// Required. Component for which a report of Variable is requested.
+	struct VariableType variable;									// Optional. Variable(s) for which the report is requested.
+};
+
+struct CompositeScheduleType
+{
+	unsigned char startDateTime[28];								// Required. Date and time at which the schedule becomes active.
+	struct ChargingScheduleType chargingSchedule;					// Required. Charging schedule structure defines a list of charging periods.
+};
+
+struct EventDataType
+{
+	unsigned int eventId;											// Required. Identifies the event. This field can be referred to as a cause by other events.
+	unsigned char timestamp[28];									// Required. Timestamp of the moment the report was generated.
+	unsigned char trigger[16];										// Required. Type of monitor that triggered this event, e.g. exceeding a threshold value.
+	unsigned int cause;												// Optional. Refers to the Id of an event that is considered to be the cause for this event.
+	unsigned char actualValue[2500];								// Required. Actual value (attributeType Actual) of the variable.
+	unsigned char techcode[50];										// Optional. Technical (error) code as reported by component.
+	unsigned char techInfo[500];									// Optional. Technical detail information as reported by component.
+	unsigned char cleared;											// Optional. Cleared is set to true to report the clearing of a monitored situation, i.e. a 'return to normal'.
+	unsigned char transactionId[37];								// Optional. If an event notification is linked to a specific transaction, this field can be used to specify its transactionId.
+	unsigned int variableMonitoringId;								// Optional. Identifies the VariableMonitoring which triggered the event.
+	unsigned char eventNotificationType[32];						// Required. Specifies the event notification type of the message.
+	struct ComponentType component;									// Required. Component for which event is notified.
+	struct VariableType variable;									// Required. Variable for which event is notified.
+};
+
+struct GetVariableDataType
+{
+	unsigned char attributeType[8];									// Optional. Attribute type for which value is requested. When absent, default Actual is assumed.
+	struct ComponentType component;									// Required. Component for which the Variable is requested.
+	struct VariableType variable;									// Required. Variable for which the attribute value is requested.
+};
+
+struct GetVariableResultType
+{
+	unsigned char attributeStatus[32];								// Required. Result status of getting the variable.
+	unsigned char attributeType[8];									// Optional. Attribute type for which value is requested. When absent, default Actual is assumed.
+	unsigned char attributeValue[2500];								// Optional. Value of requested attribute type of component- variable.
+	struct ComponentType component;									// Required. Component for which the Variable is requested.
+	struct VariableType variable;									// Required. Variable for which the attribute value is requested.
+};
+
+struct MessageInfoType
+{
+	unsigned int id;												// Required. Master resource identifier, unique within an exchange context. It is defined within the OCPP context as a positive Integer value (greater or equal to zero).
+	unsigned char priority[16];										// Required. With what priority should this message be shown
+	unsigned char state[16];										// Optional. During what state should this message be shown. When omitted this message should be shown in any state of the Charging Station.
+	unsigned char startDateTime[28];								// Optional. From what date-time should this message be shown. If omitted: directly.
+	unsigned char endDateTime[28];									// Optional. Until what date-time should this message be shown, after this date/time this message SHALL be removed.
+	unsigned char transactionId[37];								// Optional. During which transaction shall this message be shown. Message SHALL be removed by the Charging Station after transaction has ended.
+	struct MessageContentType message;								// Required. Contains message details for the message to be displayed on a Charging Station.
+	struct ComponentType display;									// Optional. When a Charging Station has multiple Displays, this field can be used to define to which Display this message belongs.
+};
+
+struct SignedMeterValueType
+{
+	unsigned char signedMeterData[2500];							// Required. Base64 encoded, contains the signed data which might contain more then just the meter value. It can contain information like timestamps, reference to a customer etc.
+	unsigned char signingMethod[50];								// Required. Method used to create the digital signature.
+	unsigned char encodingMethod[50];								// Required. Method used to encode the meter values before applying the digital signature algorithm.
+	unsigned char publicKey[2500];									// Required. Base64 encoded, sending depends on configuration variable PublicKeyWithSignedMeterValue.
+};
+
+struct UnitOfMeasureType
+{
+	unsigned char uint[20];											// Optional. Unit of the value. Default = "Wh" if the (default) measurand is an "Energy" type.
+	unsigned short int multiplier;									// Optional. Multiplier, this value represents the exponent to base 10. I.e. multiplier 3 means 10 raised to the 3rd power. Default is 0.
+};
+
+struct SampledValueType
+{
+    double value;													// Required. Indicates the measured value.
+	unsigned char context[32];										// Optional. Type of detail value: start, end or sample. Default = "Sample.Periodic"
+	unsigned char measurand[32];									// Optional. Type of measurement. Default = "Energy.Active.Import.Register"
+	unsigned char phase[8];											// Optional. Indicates how the measured value is to be interpreted.
+	unsigned char location[8];										// Optional. Indicates where the measured value has been sampled. Default = "Outlet"
+	struct SignedMeterValueType signedMeterValue;					// Optional. Contains the MeterValueSignature with sign/encoding method information.
+	struct UnitOfMeasureType unitOfMeasure;							// Optional. Represents a UnitOfMeasure including a multiplier
+};
+
+struct MeterValueType
+{
+	unsigned char timestamp[28];									// Required. Timestamp for measured value(s).
+	struct SampledValueType sampledValue[20];						// Required. One or more measured values
+};
+
+struct VariableMonitoringType
+{
+	unsigned int id;												// Required. Identifies the monitor.
+	float value;													// Required. Value for threshold or delta monitoring. For Periodic or PeriodicClockAligned this is the interval in seconds.
+	unsigned char type[32];											// Required. The type of this monitor, e.g. a threshold, delta or periodic monitor.
+	unsigned char severity;											// Required. The severity that will be assigned to an event that is triggered by this monitor.
+	unsigned char transaction;										// Required. Monitor only active when a transaction is ongoing on a component relevant to this transaction.
+};
+
+struct MonitoringDataType
+{
+	struct ComponentType component;									// Required. Component for which monitoring report was requested.
+	struct VariableType variable;									// Required. Variable for which monitoring report was requested.
+	struct VariableMonitoringType variableMonitoring[10];			// Required. List of monitors for this Component-Variable pair.
+};
+
+struct NetworkConnectionProfileType
+{
+	unsigned char ocppVersion[8];									// Required. Defines the OCPP version used for this communication function.
+	unsigned char ocppTransport[8];									// Required. Defines the transport protocol (e.g. SOAP or JSON). Note: SOAP is not supported in OCPP 2.0, but is supported by other versions of OCPP.
+	unsigned char ocppCsmsUrl[512];									// Required. URL of the CSMS(s) that this Charging Station communicates with.
+	unsigned int messageTimeout;									// Required. Duration in seconds before a message send by the Charging Station via this network connection times- out. The best setting depends on the underlying network and response times of the CSMS. If you are looking for a some guideline: use 30 seconds as a starting point.
+	unsigned char ocppInterface[16];								// Required. Applicable Network Interface.
+	struct VPNType vpn;												// Optional. Settings to be used to set up the VPN connection
+	struct APNType apn;												// Optional. Collection of configuration data needed to make a data-connection over a cellular network.
+};
+
+struct OCSPRequestDataType
+{
+	unsigned char hashAlgorithm[8];									// Required. Used algorithms for the hashes provided.
+	unsigned char issuerNameHash[129];								// Required. hashed value of the IssuerName.
+	unsigned char issuerKeyHash[129];								// Required. Hashed value of the issuers public key
+	unsigned char serialNumber[41];									// Required. The serial number of the certificate.
+	unsigned char responderURL[513];								// Required. This contains the responder URL (Case insensitive).
+};
+
+struct ReportDataType
+{
+	struct ComponentType component;									// Required. Component for which a report of Variable is requested.
+	struct VariableType variable;									// Required. Variable for which report is requested.
+	struct VariableAttributeType variableAttribute[4];				// Required. Attribute data of a variable.
+	struct VariableCharacteristicsType variableCharacteristics;		// Optional. Fixed read-only parameters of a variable.
+};
+
+struct SetMonitoringDataType
+{
+	unsigned int id;												// Optional. An id SHALL only be given to replace an existing monitor. The Charging Station handles the generation of id’s for new monitors.
+	float value;													// Required. Value for threshold or delta monitoring. For Periodic or PeriodicClockAligned this is the interval in seconds.
+	unsigned char type[32];											// Required. The type of this monitor, e.g. a threshold, delta or periodic monitor.
+	unsigned char severity;											// Required. The severity that will be assigned to an event that is triggered by this monitor.
+	unsigned char transaction;										// Optional. Monitor only active when a transaction is ongoing on a component relevant to this transaction. Default = false.
+	struct ComponentType component;									// Required. Component for which monitor is set.
+	struct VariableType variable;									// Required. Variable for which monitor is set.
+};
+
+struct SetMonitoringResultType
+{
+	unsigned int id;												// Optional. Id given to the VariableMonitor by the Charging Station.
+	unsigned char type[32];											// Required. The type of this monitor, e.g. a threshold, delta or periodic monitor.
+	unsigned char severity;											// Required. The severity that will be assigned to an event that is triggered by this monitor.
+	unsigned char status[32];										// Required. Status is OK if a value could be returned.
+	struct ComponentType component;									// Required. Component for which status is returned.
+	struct VariableType variable;									// Required. Variable for which status is returned.
+};
+
+struct SetVariableDataType
+{
+	unsigned char attributeType[8];									// Optional. Type of attribute: Actual, Target, MinSet, MaxSet. Default is Actual when omitted.
+	unsigned char attributeValue[1000];								// Required. Value to be assigned to attribute of variable.
+	struct ComponentType component;									// Required. The component for which the variable data is set.
+	struct VariableType variable;									// Required. Specifies the that needs to be set.
+};
+
+struct SetVariableResultType
+{
+	unsigned char attributeType[8];									// Optional. Type of attribute: Actual, Target, MinSet, MaxSet. Default is Actual when omitted.
+	unsigned char attributeStatus[32];								// Required. Result status of setting the variable.
+	struct ComponentType component;									// Required. The component for which result is returned.
+	struct VariableType variable;									// Required. The variable for which the result is returned.
+};
+
+struct TransactionType
+{
+	unsigned char transactionId[37];								// Required. This contains the Id of the transaction.
+	unsigned char chargingState[16];								// Optional. Current charging state, is required when state has changed. Omitted when there is no communication between EVSE and EV, because no cable is plugged in.
+	unsigned int timeSpentCharging;									// Optional. Contains the total time that energy flowed from EVSE to EV during the transaction (in seconds). Note that timeSpentCharging is smaller or equal to the duration of the transaction.
+	unsigned char stoppedReason[20];								// Optional. This contains the reason why the transaction was stopped. MAY only be omitted when Reason is "Local".
+	unsigned int remoteStartId;										// Optional. The ID given to remote start request (RequestStartTransactionRequest.
+};
+
+struct StatusInfoType
+{
+    unsigned char reasonCode[21];                                   // Required. A predefined code for the reason why thestatus is returned in this response. The string is case-insensitive.
+    unsigned char additionalInfo[513];                              // Optional. Additional text to provide detailed information.
+};
+/*
+ * =============== Message ===============
+ */
+struct Authorize_20
+{
+    unsigned char certificate[5601];                                // Optional. The X.509 certificated presented by EV for authorization.
+	struct IdTokenType idToken;										// Required. This contains the identifier that needs to be authorized.
+	struct OCSPRequestDataType iso15118CertificateHashData[4];		// Optional. Contains the information needed to verify the EV Contract Certificate via OCSP.
+	unsigned char Response_certificateStatus[32];					// Optional. Certificate status information. - if all certificates are valid: return 'Accepted'. - if one of the certificates was revoked, return 'CertificateRevoked'.
+	struct IdTokenInfoType Response_idTokenInfo;					// Required. This contains information about authorization status, expiry and group id.
+};
+
+struct BootNotification_20
+{
+	unsigned char reason[20];										// Required. This contains the reason for sending this message to the CSMS.
+	struct ChargingStationType chargingStation;						// Required. Identifies the Charging Station
+	unsigned char Response_currentTime[28];							// Required. This contains the CSMS’s current time.
+	unsigned int Response_interval;									// Required. When Status is Accepted, this contains the heartbeat interval in seconds. If the CSMS returns something other than Accepted, the value of the interval field indicates the minimum wait time before sending a next BootNotification request.
+	unsigned char Response_status[16];								// Required. This contains whether the Charging Station has been registered within the CSMS.
+};
+
+struct CancelReservation_20
+{
+	int reservationId;												// Required. Id of the reservation to cancel.
+	unsigned char Response_status[16];								// Required. This indicates the success or failure of the canceling of a reservation by CSMS.
+	unsigned char guid[37];											// Save guid from server request
+};
+
+struct CertificateSigned_20
+{
+    unsigned char certificateChain[10001];                          // Required. Required. The signed PEM encoded X.509 certificate.This can also contain the necessary sub CA certificates.In that case, the order of the bundle should follow thecertificate chain, starting from the leaf certificate.The Configuration Variable MaxCertificateChainSize canbe used to limit the maximum size of this field.
+    unsigned char certificateType[32];                              // Optional. Indicates the type of the signed certificate that is returned.
+    unsigned char Response_status[16];                              // Required. Returns whether certificate signing has been accepted, otherwise rejected.
+    struct StatusInfoType Response_statusInfo;                      // Optional. Detailed status information.
+    unsigned char guid[37];                                         // Save guid from server request
+};
+
+struct ChangeAvailability_20
+{
+	unsigned char operationalStatus[16];							// Required. This contains the type of availability change that the Charging Station should perform.
+	struct EVSEType evse;											// Optional. Contains Id’s to designate a specific EVSE/connector by index numbers. When omitted, the message refers to the Charging Station as a whole.
+	unsigned char Response_status[16];								// Required. This indicates whether the Charging Station is able to perform the availability change.
+	unsigned char guid[37];											// Save guid from server request
+};
+
+struct ClearCache_20
+{
+	unsigned char Response_status[16];								// Required. Accepted if the Charging Station has executed the request, otherwise rejected.
+	unsigned char guid[37];											// Save guid from server request
+};
+
+struct ClearChargingProfile_20
+{
+	unsigned int chargingProfileId;									// Optional. The Id of the charging profile to clear.
+	struct  ClearChargingProfileType chargingProfileCriteria;		// Optional. Specifies the charging profile.
+	unsigned char Response_status[16];								// Required. Indicates if the Charging Station was able to execute the request.
+	unsigned char guid[37];											// Save guid from server request
+};
+
+struct ClearDisplayMessage_20
+{
+	unsigned int id;												// Required. Id of the message that SHALL be removed from the Charging Station.
+	unsigned char Response_status[16];								// Required. Returns whether the Charging Station has been able to remove the message.
+	unsigned char guid[37];											// Save guid from server request
+};
+
+struct ClearedChargingLimit_20
+{
+	unsigned char chargingLimitSource[8];							// Required. Source of the charging limit.
+	unsigned int evseId;											// Optional. EVSE Identifier.
+};
+
+struct ClearVariableMonitoring_20
+{
+	unsigned int id[10];										 	// Required. List of the monitors to be cleared, identified by there Id.
+	struct ClearMonitoringResultType Response_clearMonitoringResult[10];// Required. List of result statuses per monitor.
+	unsigned char guid[37];											// Save guid from server request
+};
+
+struct CostUpdated_20
+{
+	float totalCost;												// Required. Current total cost, based on the information known by the CSMS, of the transaction including taxes. In the currency configured with the configuration Variable: [Currency]
+	unsigned char transactionId[37];								// Required. Transaction Id of the transaction the current cost are asked for.
+	unsigned char guid[37];											// Save guid from server request
+};
+
+struct CustomerInformation_20
+{
+	unsigned int requestId;											// Required. The Id of the request.
+	unsigned char report;											// Required. Flag indicating whether the Charging Station should return NotifyCustomerInformationRequest messages containing information about the customer referred to.
+	unsigned char clear;											// Required. Flag indicating whether the Charging Station should clear all information about the customer referred to.
+	unsigned char customerIdentifier[64];							// Optional. A (e.g. vendor specific) identifier of the customer this request refers to. This field contains a custom identifier other than IdToken and Certificate. One of the possible identifiers (customerIdentifier, customerIdToken or customerCertificate) should be in the request message.
+	struct IdTokenType idToken;										// Optional. The IdToken of the customer this request refers to. One of the possible identifiers (customerIdentifier, customerIdToken or customerCertificate) should be in the request message.
+	struct CertificateHashDataType customerCertificate;				// Optional. The Certificate of the customer this request refers to. One of the possible identifiers (customerIdentifier, customerIdToken or customerCertificate) should be in the request message.
+	unsigned char Response_status[16];								// Required. Indicates whether the request was accepted.
+	unsigned char guid[37];											// Save guid from server request
+};
+
+struct DataTransfer_20
+{
+	unsigned char messageId[50];									// Optional. May be used to indicate a specific message or implementation.
+	unsigned char data[512];										// Optional. Data without specified length or format. This needs to be decided by both parties (Open to implementation).
+	unsigned char vendorId[255];									// Required. This identifies the Vendor specific implementation
+	unsigned char Response_status[20];								// Required. This indicates the success or failure of the data transfer.
+	unsigned char Response_data[512];								// Optional. Data without specified length or format, in response to request.
+	unsigned char guid[37];											// Save guid from server request
+};
+
+struct DeleteCertificate_20
+{
+	struct CertificateHashDataType certificateHashData;				// Required. Indicates the certificate of which deletion is requested.
+	unsigned char Response_status[16];								// Required. Charging Station indicates if it can process the request.
+	unsigned char guid[37];											// Save guid from server request
+};
+
+struct FirmwareStatusNotification_20
+{
+	unsigned char status[32];										// Required. This contains the progress status of the firmware installation.
+	unsigned int requestId;											// Optional. The request id that was provided in the UpdateFirmwareRequest that started this firmware update. This field is mandatory, unless the message was triggered by a TriggerMessageRequest AND there is no firmware update ongoing.
+};
+
+struct Get15118EVCertificate_20
+{
+	unsigned char iso15118SchemaVersion[51];						// Required. Schema version currently used for the 15118 session between EV and Charging Station. Needed for parsing of the EXI stream by the CSMS.
+	unsigned char action[16];										// Required. Defines whether certificate needs to be installed or updated.
+	unsigned char exiRequest[5601];									// Required. Raw CertificateInstallationReq request from EV, Base64 encoded.
+	unsigned char Response_status[16];								// Required. Indicates whether the message was processed properly.
+	unsigned char Response_exiResponse[5601];						// Required. Raw CertificateInstallationRes response for the EV, Base64 encoded.
+};
+
+struct GetBaseReport_20
+{
+	unsigned int requestId;											// Required. The Id of the request.
+	unsigned char reportBase[32];									// Required. This field specifies the report base.
+	unsigned char Response_status[16];								// Required. This indicates whether the Charging Station is able to accept this request.
+	unsigned char guid[37];											// Save guid from server request
+};
+
+struct GetCertificateStatus_20
+{
+	struct OCSPRequestDataType ocspRequestData;						// Required. Indicates the certificate of which the status is requested.
+	unsigned char Response_status[16];								// Required. This indicates whether the charging station was able to retrieve the OCSP certificate status.
+	unsigned char Response_ocspResult[5501];						// Optional. OCSPResponse class as defined in IETF RFC 6960. DER encoded (as defined in IETF RFC 6960), and then base64 encoded. MAY only be omitted when status is not Accepted.
+	struct StatusInfoType Response_statusInfo;                      // Optional. Detailed status information.
+};
+
+struct GetChargingProfiles_20
+{
+	unsigned int requestId;											// Required. Reference identification that is to be used by the Charging Station in the ReportChargingProfilesRequest when provided.
+	unsigned int evseId;											// Optional. For which EVSE installed charging profiles SHALL be reported. If 0, only charging profiles installed on the Charging Station itself (the grid connection) SHALL be reported. If omitted, all installed charging profiles SHALL be reported.
+	struct ChargingProfileCriterionType chargingProfile;			// Required. Specifies the charging profile.
+	unsigned char Response_status[16];								// Required. This indicates whether the Charging Station is able to process this request and will send ReportChargingProfilesRequest messages.
+	unsigned char guid[37];											// Save guid from server request
+};
+
+struct GetCompositeSchedule_20
+{
+	unsigned int duration;											// Required. Length of the requested schedule in seconds.
+	unsigned char chargingRateUnit[8];								// Optional. Can be used to force a power or current profile.
+	unsigned int evseId;											// Required. The ID of the EVSE for which the schedule is requested. When evseid=0, the Charging Station will calculate the expected consumption for the grid connection.
+	unsigned char Response_status[16];								// Required. The Charging Station will indicate if it was able to process the request
+	struct CompositeScheduleType Response_schedule;					// Optional. This field contains the calculated composite schedule. It may only be omitted when this message contains status Rejected.
+	unsigned char guid[37];											// Save guid from server request
+};
+
+struct GetDisplayMessages_20
+{
+	unsigned int id[10];											// Optional. If provided the Charging Station shall return Display Messages of the given ids. This field SHALL NOT contain more ids than set in NumberOfDisplayMessages.maxLimit
+	unsigned int requestId;											// Required. The Id of this request.
+	unsigned char	priority[16];									// Optional. If provided the Charging Station shall return Display Messages with the given priority only.
+	unsigned char state[16];										// Optional. If provided the Charging Station shall return Display Messages with the given state only.
+	unsigned char Response_status[16];								// Required. Indicates if the Charging Station has Display Messages that match the request criteria in the GetDisplayMessagesRequest
+	unsigned char guid[37];											// Save guid from server request
+};
+
+struct GetInstalledCertificateIds_20
+{
+	unsigned char certificateType[10][32];										// Optional. Indicates the type of certificates requested. When omitted, all certificate types are requested.
+	unsigned char Response_status[16];											// Required. Charging Station indicates if it can process the request.
+	struct CertificateHashDataChainType Response_certificateHashDataChain[10];	// Optional. The Charging Station includes the Certificate information for each available certificate.
+	unsigned char guid[37];														// Save guid from server request
+};
+
+struct GetLocalListVersion_20
+{
+	int Response_versionNumber;										// Required. This contains the current version number of the local authorization list in the Charging Station.
+	unsigned char guid[37];											// Save guid from server request
+};
+
+struct GetLog_20
+{
+	unsigned char logType[16];										// Required. This contains the type of log file that the Charging Station should send.
+	unsigned int requestId;											// Required. The Id of this request
+	unsigned char retries;											// Optional. This specifies how many times the Charging Station must try to upload the log before giving up. If this field is not present, it is left to Charging Station to decide how many times it wants to retry.
+	unsigned int retryInterval;										// Optional. The interval in seconds after which a retry may be attempted. If this field is not present, it is left to Charging Station to decide how long to wait between attempts.
+	struct LogParametersType log;									// Required. This field specifies the requested log and the location to which the log should be sent.
+	unsigned char Response_status[20];								// Required. This field indicates whether the Charging Station was able to accept the request.
+	unsigned char Response_filename[255];							// Optional. This contains the name of the log file that will be uploaded. This field is not present when no logging information is available.
+	unsigned char guid[37];											// Save guid from server request
+};
+
+struct GetMonitoringReport_20
+{
+	unsigned int requestId;											// Required. The Id of the request.
+	unsigned char monitoringCriteria[3][32];						// Optional. This field contains criteria for components for which a monitoring report is requested
+	struct ComponentVariableType componentVariable[10];				// Optional. This field specifies the components and variables for which a monitoring report is requested.
+	unsigned char Response_status[20];								// Required. This field indicates whether the Charging Station was able to accept the request.
+	unsigned char guid[37];											// Save guid from server request
+};
+
+struct GetReport_20
+{
+	unsigned int requestId;											// Required. The Id of the request.
+	unsigned char componentCriteria[4][16];							// Optional. This field contains criteria for components for which a report is requested
+	struct ComponentVariableType componentVariable[10];				// Optional. This field specifies the components and variables for which a report is requested.
+	unsigned char Response_status[20];								// Required. This field indicates whether the Charging Station was able to accept the request.
+	unsigned char guid[37];											// Save guid from server request
+};
+
+struct GetTransactionStatus_20
+{
+	unsigned char transactionId[37];								// Optional. The Id of the transaction for which the status is requested.
+	unsigned char Response_ongoingIndicator;						// Optional. Whether the transaction is still ongoing.
+	unsigned char Response_messagesInQueue;							// Required. Whether there are still message to be delivered.
+	unsigned char guid[37];											// Save guid from server request
+};
+
+struct GetVariables_20
+{
+	struct GetVariableDataType getVariableData[CtrlrVariable_CNT];				// Required. List of requested variables.
+	struct GetVariableResultType Response_getVariableResult[CtrlrVariable_CNT];	// Required. List of requested variables and their values.
+	unsigned char guid[37];                                                     // Save guid from server request
+};
+
+struct Heartbeat_20
+{
+	unsigned char Response_currentTime[28];							// Required. Contains the current time of the CSMS.
+};
+
+struct InstallCertificate_20
+{
+	unsigned char certificateType[32];								// Required. Indicates the certificate type that is sent.
+	unsigned char certificate[5501];								// Required. A X.509 certificate, first DER encoded into binary, and then Base64 encoded.
+	unsigned char Response_status[16];								// Required. Charging Station indicates if installation was successful.
+	unsigned char guid[37];											// Save guid from server request
+};
+
+struct LogStatusNotification_20
+{
+	unsigned char status[32];										// Required. This contains the status of the log upload.
+	unsigned int requestId;											// Optional. The request id that was provided in GetLogRequest that started this log upload. This field is mandatory, unless the message was triggered by a TriggerMessageRequest AND there is no log upload ongoing.
+};
+
+struct MeterValues_20
+{
+	unsigned int evseId;											// Required. This contains a number (>0) designating an EVSE of the Charging Station. ‘0’ (zero) is used to designate the main power meter.
+	struct MeterValueType meterValue[1];							// Required. The sampled meter values with timestamps.
+};
+
+struct NotifyChargingLimit_20
+{
+	unsigned int evseId;											// Optional. The charging schedule contained in this notification applies to an EVSE. evseId must be > 0.
+	struct ChargingLimitType chargingLimit;							// Required. This contains the source of the charging limit and whether it is grid critical.
+	struct ChargingScheduleType chargingSchedule[1];				// Optional. Contains limits for the available power or current over time, as set by the external source.
+};
+
+struct NotifyCustomerInformation_20
+{
+	unsigned char data[512];										// Required. (Part of) the requested data. No format specified in which the data is returned. Should be human readable.
+	unsigned char tbc;												// Optional. “to be continued” indicator. Indicates whether another part of the monitoringData follows in an upcoming notifyMonitoringReportRequest message. Default value when omitted is false.
+	unsigned int seqNo;												// Required. Sequence number of this message. First message starts at 0.
+	unsigned char generatedAt[28];									// Required. Timestamp of the moment this message was generated at the Charging Station.
+	unsigned int requestId;											// Required. The Id of the request.
+};
+
+struct NotifyDisplayMessages_20
+{
+	unsigned int requestId;                                         // Required. The id of the GetDisplayMessagesRequest that requested this message.
+	unsigned char tbc;												// Optional. "to be continued" indicator. Indicates whether another part of the report follows in an upcoming NotifyDisplayMessagesRequest message. Default value when omitted is false.
+	struct MessageInfoType messageInfo[10];							// Optional. The requested display message as configured in the Charging Station.
+};
+
+struct NotifyEVChargingNeeds_20
+{
+	unsigned int maxScheduleTuples;									// Optional. Contains the maximum schedule tuples the car supports per SASchedule (both Pmax and Tariff).
+	unsigned int evseId;											// Required. Defines the EVSE and connector to which the EV is connected. EvseId may not be 0.
+	struct ChargingNeedsType chargingNeeds;							// Required. The characteristics of the energy delivery required.
+	unsigned char Response_status[16];								// Required. Returns whether the CSMS has been able to process the message successfully. It does not imply that the evChargingNeeds can be met with the current charging profile.
+	struct StatusInfoType Response_statusInfo;                      // Optional. Detailed status information.
+};
+
+struct NotifyEVChargingSchedule_20
+{
+	unsigned char timeBase[28];										// Required. Periods contained in the charging profile are relative to this point in time.
+	unsigned int evseId;											// Required. The charging schedule contained in this notification applies to an EVSE. EvseId must be > 0.
+	struct ChargingScheduleType chargingSchedule;					// Required. Planned energy consumption of the EV over time. Always relative to timeBase.
+	unsigned char Response_status[16];								// Required. Returns whether the CSMS has been able to process the message successfully. It does not imply any approval of the charging schedule.
+	struct StatusInfoType Response_statusInfo;                      // Optional. Detailed status information.
+};
+
+struct NotifyEvent_20
+{
+	unsigned char generatedAt[28];									// Required. Timestamp of the moment this message was generated at the Charging Station.
+	unsigned char tbc;												// Optional. “to be continued” indicator. Indicates whether another part of the report follows in an upcoming notifyEventRequest message. Default value when omitted is false.
+	unsigned int seqNo;												// Required. Sequence number of this message. First message starts at 0.
+	struct EventDataType eventData[10];								// Required. List of EventData.
+};
+
+struct NotifyMonitoringReport_20
+{
+	unsigned int requestId;											// Required. The id of the GetMonitoringRequest that requested this report.
+	unsigned char tbc;												// Optional. “to be continued” indicator.
+	unsigned int seqNo;												// Required. Sequence number of this message. First message starts at 0.
+	unsigned char generatedAt[28];									// Required. Timestamp of the moment this message was generated at the Charging Station.
+	struct MonitoringDataType monitor[10];							// Optional. List of MonitoringData containing monitoring settings.
+};
+
+struct NotifyReport_20
+{
+	unsigned int requestId;											// Required. The id of the GetReportRequest or GetBaseReportRequest that requested this report
+	unsigned char generatedAt[28];									// Required. Timestamp of the moment this message was generated at the Charging Station.
+	unsigned char tbc;												// Optional. “to be continued” indicator.
+	unsigned int seqNo;												// Required. Sequence number of this message. First message starts at 0.
+	struct ReportDataType reportData[10];							// Optional. List of ReportData.
+};
+
+struct PublishFirmware_20
+{
+	unsigned char location[512];									// Required. This contains a string containing a URI pointing to a location from which to retrieve the firmware.
+	unsigned char retries;											// Optional. This specifies how many times Charging Station must try to download the firmware before giving up. If this field is not present, it is left to Charging Station to decide how many times it wants to retry.
+	unsigned char checksum[32];										// Required. The MD5 checksum over the entire firmware file as a hexadecimal string of length 32.
+	unsigned int requestId;											// Required. The Id of the request.
+	unsigned int retryInterval;										// Optional. The interval in seconds after which a retry may be attempted. If this field is not present, it is left to Charging Station to decide how long to wait between attempts.
+	unsigned char Response_status[16];								// Required. Indicates whether the request was accepted.
+	unsigned char guid[37];											// Save guid from server request
+};
+
+struct PublishFirmwareStatusNotification_20
+{
+	unsigned char status[32];										// Required. This contains the progress status of the publishfirmware installation.
+	unsigned char location[10][512];                                // Optional. Required if status is Published. Can be multiple URI’s, if the Local Controller supports e.g. HTTP, HTTPS, and FTP.
+	unsigned int requestId;											// Optional. The request id that was provided in the PublishFirmwareRequest which triggered this action.
+};
+
+struct ReportChargingProfiles_20
+{
+	unsigned int requestId;											// Required. Id used to match the GetChargingProfilesRequest message with the resulting ReportChargingProfilesRequest messages
+	unsigned char chargingLimitSource[8];							// Required. Source that has installed this charging profile.
+	unsigned char tbc;												// Optional. To Be Continued. Default value when omitted: false. false indicates that there are no further messages as part of this report.
+	unsigned int evseId;											// Required. The evse to which the charging profile applies. If evseId = 0, the message contains an overall limit for the Charging Station.
+	struct ChargingProfileType chargingProfile[3];					// Required. The charging profile as configured in the Charging Station.
+};
+
+struct RequestStartTransaction_20
+{
+	unsigned int evseId;											// Optional. Number of the EVSE on which to start the transaction. EvseId SHALL be > 0
+	unsigned int remoteStartId;										// Required. Id given by the server to this start request.
+	struct IdTokenType idToken;										// Required. The identifier that the Charging Station must use to start a transaction.
+	struct ChargingProfileType chargingProfile;						// Optional. Charging Profile to be used by the Charging Station for the requested transaction.
+	struct IdTokenType groupIdToken;								// Optional. The group identifier that the Charging Station must use to start a transaction.
+	unsigned char Response_status[16];								// Required. Status indicating whether the Charging Station accepts the request to start a transaction.
+	unsigned char Response_transactionId[37];						// Optional. When the transaction was already started by the Charging Station before the RequestStartTransactionRequest was received, for example: cable plugged in first. This contains the transactionId of the already started transaction.
+	unsigned char guid[37];											// Save guid from server request
+};
+
+struct RequestStopTransaction_20
+{
+	unsigned char transactionId[37];								// Required. The identifier of the transaction which the Charging Station is requested to stop.
+	unsigned char Response_status[16];								// Required. Status indicating whether Charging Station accepts the request to stop a transaction.
+	unsigned char guid[37];											// Save guid from server request
+};
+
+struct ReservationStatusUpdate_20
+{
+	int reservationId;												// Required. The ID of the reservation.
+	unsigned char reservationUpdateStatus[8];						// Required. The updated reservation status.
+};
+
+struct ReserveNow_20
+{
+	unsigned int id;												// Required. Id of reservation.
+	unsigned char expiryDateTime[28];								// Required. Date and time at which the reservation expires.
+	unsigned char connectorType[16];								// Optional. This field specifies the connector type.
+	unsigned int evseId;											// Optional. This contains ID of the evse to be reserved.
+	struct IdTokenType idToken;										// Required. The identifier for which the reservation is made.
+	struct IdTokenType groupIdToken;								// Optional. The group identifier for which the reservation is made.
+	unsigned char Response_status[16];								// Required. This indicates the success or failure of the reservation.
+	unsigned char guid[37];											// Save guid from server request
+};
+
+struct Reset_20
+{
+	unsigned char type[16];											// Required. This contains the type of reset that the Charging Station or EVSE should perform.
+	unsigned int evseId;											// Optional. This contains the ID of a specific EVSE that needs to be reset, instead of the entire Charging Station.
+	unsigned char Response_status[16];								// Required. This indicates whether the Charging Station is able to perform the reset.
+	unsigned char guid[37];											// Save guid from server request
+};
+
+struct SecurityEventNotification_20
+{
+	unsigned char type[50];											// Required. Type of the security event. This value should be taken from the Security events list.
+	unsigned char timestamp[28];									// Required. Date and time at which the event occurred.
+	unsigned char techInfo[255];									// Optional. Additional information about the occurred security event.
+};
+
+struct SendLocalList_20
+{
+	unsigned int versionNumber;										// Required. In case of a full update this is the versio number of the full list. In case of a differential update it i the version number of the list after the update has bee applied.
+	unsigned char updateType[32];									// Required. This contains the type of update (full or differential) of this request.
+	struct AuthorizationData localAuthorizationList[500];			// Optional. This contains the Local Authorization List entries.
+	unsigned char Response_status[16];								// Required. This indicates whether the Charging Station has successfully received and applied the update of the Local Authorization List.
+	unsigned char guid[37];											// Save guid from server request
+};
+
+struct SetChargingProfile_20
+{
+	unsigned int evseId;											// Required. The EVSE to which the charging profile applies. If evseId = 0, the message contains an overall limit for the Charging Station.
+	struct ChargingProfileType chargingProfile;						// Required. The charging profile to be set at the Charging Station.
+	unsigned char Response_status[16];								// Required. Returns whether the Charging Station has been able to process the message successfully. This does not guarantee the schedule will be followed to the letter. There might be other constraints the Charging Station may need to take into account.
+	unsigned char guid[37];											// Save guid from server request
+	struct StatusInfoType Response_statusInfo;                      // Optional. Detailed status information.
+};
+
+struct SetDisplayMessage_20
+{
+	struct MessageInfoType message;									// Required. Message to be configured in the Charging Station, to be displayed.
+	unsigned char Response_status[32];								// Required. This indicates whether the Charging Station is able to display the message.
+	unsigned char guid[37];											// Save guid from server request
+};
+
+struct SetMonitoringBase_20
+{
+	unsigned char monitoringBase[16];								// Required. Specify which monitoring base will be set
+	unsigned char Response_status[16];								// Required. Indicates whether the Charging Station was able to accept the request.
+	unsigned char guid[37];											// Save guid from server request
+};
+
+struct SetMonitoringLevel_20
+{
+	unsigned int severity;											// Required. The Charging Station SHALL only report events with a severity number lower than or equal to this severity.
+	unsigned char Response_status[16];         						// Required. Indicates whether the Charging Station was able to accept the request.
+	unsigned char guid[37];											// Save guid from server request
+};
+
+struct SetNetworkProfile_20
+{
+	unsigned int configurationSlot;									// Required. Slot in which the configuration should be stored.
+	struct NetworkConnectionProfileType connectionData;				// Required. Connection details.
+	unsigned char Response_status[16];									// Required. Result of operation.
+	unsigned char guid[37];											// Save guid from server request
+};
+
+struct SetVariableMonitoring_20
+{
+	struct SetMonitoringDataType setMonitoringData[10];				// Required. List of MonitoringData containing monitoring settings.
+	struct SetMonitoringResultType Response_setMonitoringResult[10];// Required. List of result statuses per monitor.
+	unsigned char guid[37];											// Save guid from server request
+};
+
+struct SetVariables_20
+{
+	struct SetVariableDataType setVariableData[CtrlrVariable_CNT];              // Required. List of Component-Variable pairs and attribute values to set.
+	struct SetVariableResultType Response_setVariableResult[CtrlrVariable_CNT]; // Required. List of result statuses per Component-Variable.
+	unsigned char guid[37];                                                     // Save guid from server request
+};
+
+struct SignCertificate_20
+{
+    unsigned char csr[5501];                                        // Required. The Charging Station SHALL send the public key in form of a Certificate Signing Request (CSR) as described in RFC 2986 [22] using the SignCertificateRequest message.
+    unsigned char certificateType[32];                              // Optional. Indicates the type of certificate that is to be signed. When omitted the certificate is to be used for both the 15118 connection (if implemented) and the Charging Station to CSMS connection.
+    unsigned char Response_status[16];                              // Required. Specifies whether the CSMS can process the request.
+    struct StatusInfoType Response_statusInfo;                      // Optional. Detailed status information.
+};
+
+struct StatusNotification_20
+{
+	unsigned char timestamp[28];									// Required. The time for which the status is reported. If absent time of receipt of the message will be assumed.
+	unsigned char connectorStatus[16];								// Required. This contains the current status of the Connector.
+	unsigned int evseId;											// Required. The id of the EVSE to which the connector belongs for which the the status is reported.
+	unsigned char connectorId;										// Required. The id of the connector within the EVSE for which the status is reported.
+};
+
+struct TransactionEvent_20
+{
+	unsigned char eventType[16];									// Required. This contains the type of this event. The first TransactionEvent of a transaction SHALL contain: "Started" The last TransactionEvent of a transaction SHALL contain: "Ended" All others SHALL contain: "Updated"
+	unsigned char timestamp[28];									// Required. The date and time at which this transaction event occurred.
+	unsigned char triggerReason[32];								// Required. Reason the Charging Station sends this message to the CSMS
+	unsigned int seqNo;												// Required. Incremental sequence number, helps with determining if all messages of a transaction have been received.
+	unsigned char offline;											// Optional. Indication that this transaction event happened when the Charging Station was offline. Default = false, meaning: the event occurred when the Charging Station was online.
+	unsigned char numberOfPhasesUsed;								// Optional. If the Charging Station is able to report the number of phases used, then it SHALL provide it. When omitted the CSMS may be able to determine the number of phases used via device management.
+	float cableMaxCurrent;											// Optional. The maximum current of the connected cable in Ampere (A).
+	int reservationId;												// Optional. This contains the Id of the reservation that terminates as a result of this transaction.
+	struct TransactionType transactionInfo;							// Required. Contains transaction specific information.
+	struct IdTokenType idToken;										// Optional. This contains the identifier for which a transaction has to be/was started.
+	struct EVSEType evse;											// Optional. This identifies which evse (and connector) of the Charging Station is used.
+	struct MeterValueType meterValue[1];							// Optional. This contains the relevant meter values.
+	float Response_totalCost;										// Optional. SHALL only be sent when charging has ended. Final total cost of this transaction, including taxes.
+	int Response_chargingPriority;									// Optional. Priority from a business point of view. Default priority is 0,
+	struct IdTokenInfoType Response_idTokenInfo;					// Optional. This contains information about authorization status, expiry and group id. Is required when the transactionEventRequest contained an idToken.
+	struct MessageContentType Response_updatedPersonalMessage;		// Optional. This can contain updated personal message that can be shown to the EV Driver. This can be used to provide updated tariff information
+};
+
+struct TriggerMessage_20
+{
+	unsigned char requestedMessage[32];								// Required. Type of message to be triggered.
+	struct EVSEType evse;											// Optional. Can be used to specifiy the EVSE and Connector if required for the message which needs to be sent.
+	unsigned char Response_status[16];								// Required. Indicates whether the Charging Station will send the requested notification or not.
+	unsigned char guid[37];											// Save guid from server request
+};
+
+struct UnlockConnector_20
+{
+	unsigned int evseId;											// Required. This contains the identifier of the EVSE for which a connector needs to be unlocked.
+	unsigned char connectorId;										// Required. This contains the identifier of the connector that needs to be unlocked.
+	unsigned char Response_status[32];								// Required. This indicates whether the Charging Station has unlocked the connector.
+	unsigned char guid[37];											// Save guid from server request
+};
+
+struct UnpublishFirmware_20
+{
+	unsigned char checksum[32];										// Required. The MD5 checksum over the entire firmware file as a hexadecimal string of length 32.
+	unsigned char Response_status[16];								// Required. Indicates whether the Local Controller succeeded in unpublishing the firmware.
+	unsigned char guid[37];											// Save guid from server request
+};
+
+struct UpdateFirmware_20
+{
+	unsigned char retries;											// Optional. This specifies how many times Charging Station must try to download the firmware before giving up. If this field is not present, it is left to Charging Station to decide how many times it wants to retry.
+	unsigned int retryInterval;										// Optional. The interval in seconds after which a retry may be attempted. If this field is not present, it is left to Charging Station to decide how long to wait between attempts.
+	unsigned int requestId;											// Required. The Id of this request
+	struct FirmwareType firmware;									// Required. Specifies the firmware to be updated on the Charging Station.
+	unsigned char Response_status[32];								// Required. This field indicates whether the Charging Station was able to accept the request.
+	unsigned char guid[37];											// Save guid from server request
+};
+
+struct NetworkConnectionProfile_20
+{
+    unsigned int slot;
+    unsigned char retryCount;
+    struct NetworkConnectionProfileType connectionData;
+};
+
+//===================================
+// YES custom protocol
+//===================================
+struct StructChargerInfo
+{
+    unsigned char station_name[64];
+};
+
+struct StructWeatherInfo
+{
+    int   weatherId;
+    float temperature;
+};
+
+struct StructCreditDeductResult
+{
+    int txId;
+    unsigned char creditNo[64];
+    unsigned char vemData[80];
+    unsigned char ROC[20];
+    unsigned char RRN[20];
+    unsigned char storeId[20];
+    unsigned char approvalNo[20];
+    double        amount;
+    unsigned char deductResult:1;
+    unsigned char isDonateInvoice:1;
+};
+
+struct StructReaderStatus
+{
+    int readerStatus;
+    unsigned char creditNo[64];
+    unsigned char ReportReaderStatusReq:1;
+};
+
+struct StructTcciCustomData
+{
+    struct StructChargerInfo ChargerInfo;
+    struct StructWeatherInfo WeatherInfo;
+    struct StructCreditDeductResult DeductInfo;
+    struct StructReaderStatus ReaderStatus[CONNECTOR_QUANTITY];
+    unsigned char TriggerReaderReq[3];
+    unsigned char SerialNo[CONNECTOR_QUANTITY][37];
+    unsigned char VEMData[CONNECTOR_QUANTITY][65];
+
+    unsigned char ReportCreditDeductReq:1;
+    unsigned char ChargerInfoReq:1;
+    unsigned char ChargerInfoConf:1;
+    unsigned char WeatherInfoReq:1;
+    unsigned char WeatherInfoConf:1;
+    unsigned char :3;                  // bit 5-7 , reserved
+};
+
+struct OCMFData
+{
+    unsigned char SendOcmfDataReq:1;   // bit 0 , Flag to ask OCPP sending OCMF message to backend.
+    unsigned char :7;                  // bit 1-7 , reserved
+    unsigned char DataString[2048];    // Data got from meter.
+    unsigned char PublicKey[256];      // PublicKey with header got from meter.
+};
+
+struct OCPP16_V2g_Extend
+{
+	struct Authorize_20						Authorize;
+	struct CertificateSigned_20				CertificateSigned;
+	struct DeleteCertificate_20				DeleteCertificate;
+	struct Get15118EVCertificate_20			Get15118EVCertificate;
+	struct GetCertificateStatus_20			GetCertificateStatus;
+	struct GetInstalledCertificateIds_20	GetInstalledCertificateIds;
+	struct InstallCertificate_20			InstallCertificate;
+	struct SignCertificate_20				SignCertificate;
+
+
+	unsigned char							AuthorizeReq:1;
+	unsigned char							AuthorizeConf:1;
+	unsigned char							Get15118EVCertificateReq:1;
+	unsigned char 							Get15118EVCertificateConf:1;
+	unsigned char							GetCertificateStatusReq:1;
+	unsigned char 							GetCertificateStatusConf:1;
+	unsigned char							SignCertificateReq:1;
+	unsigned char							SignCertificateConf:1;
+};
+
+struct OCPP16Data
+{
+    unsigned char                           OcppServerURL[512];     //http: non-secure OCPP 1.5-S, https: secure OCPP 1.5-S, ws: non-secure OCPP 1.6-J, wss: secure OCPP 1.6-J"
+    unsigned char                           ChargeBoxId[128];
+    unsigned char                           OcppConnStatus;         //0: disconnected, 1: connected
+    unsigned int                            Timeout_Secs;
+    unsigned short                          Ping_Pong_Interval;
+    long int                                procDogTime;            // Process watch dog refresh timer
+    union
+    {
+        //Operations Initiated by Charge Point
+        unsigned char CpMsgValue[CONNECTOR_QUANTITY];
+        struct
+        {
+            //CpMsgValue[0]
+            unsigned char DataTransferReq:1;        //bit 0,
+            unsigned char DataTransferConf:1;       //bit 1,
+            unsigned char StartTransactionReq:1;    //bit 2,
+            unsigned char StartTransactionConf:1;   //bit 3,
+            unsigned char StopTransactionReq:1;     //bit 4,
+            unsigned char StopTransactionConf:1;    //bit 5,
+            unsigned char :2;                       //bit 6,7 , reserved
+        } bits[CONNECTOR_QUANTITY];
+    }CpMsg;
+
+    union
+    {
+        //Operations Initiated by Sequence Point
+        unsigned char SpMsgValue[2];
+        struct
+        {
+            //SpMsgValue[0]
+            unsigned char BootNotificationReq :1;                   //bit 0,
+            unsigned char BootNotificationConf :1;                  //bit 1,
+            unsigned char AuthorizeReq :1;                          //bit 2,
+            unsigned char AuthorizeConf :1;                         //bit 3,
+            unsigned char DiagnosticsStatusNotificationReq :1;      //bit 4,
+            unsigned char DiagnosticsStatusNotificationConf :1;     //bit 5,
+            unsigned char FirmwareStatusNotificationReq :1;         //bit 6,
+            unsigned char FirmwareStatusNotificationConf :1;        //bit 7,
+            //SpMsgValue[1]
+            unsigned char LogStatusNotificationReq :1;              //bit 0,
+            unsigned char LogStatusNotificationConf :1;             //bit 1,
+            unsigned char SecurityEventNotificationReq :1;          //bit 2,
+            unsigned char SecurityEventNotificationConf :1;         //bit 3,
+            unsigned char SignCertificateReq :1;                    //bit 4,
+            unsigned char SignCertificateConf :1;                   //bit 5,
+            unsigned char SignedFirmwareStatusNotificationReq :1;   //bit 6,
+            unsigned char SignedFirmwareStatusNotificationConf :1;  //bit 7,
+        } bits;
+    } SpMsg;
+
+    union
+    {
+        //Operations Initiated by Central System
+        unsigned char CsMsgValue[3 * (CONNECTOR_QUANTITY)];
+        struct
+        {
+            //CsMsgValue[0]
+            unsigned char CancelReservationReq :1;      //bit 0,
+            unsigned char CancelReservationConf :1;     //bit 1,
+            unsigned char ChangeAvailabilityReq :1;     //bit 2,
+            unsigned char ChangeAvailabilityConf :1;    //bit 3,
+            unsigned char ReserveNowReq :1;             //bit 4,
+            unsigned char ReserveNowConf :1;            //bit 5,
+            unsigned char SetChargingProfileReq :1;     //bit 6,
+            unsigned char SetChargingProfileConf :1;    //bit 7,
+            //CsMsgValue[1]
+            unsigned char TriggerMessageReq :1;         //bit 0,
+            unsigned char TriggerMessageConf :1;        //bit 1,
+            unsigned char UnlockConnectorReq :1;        //bit 2,
+            unsigned char UnlockConnectorConf :1;       //bit 3,
+            unsigned char RemoteStartTransactionReq :1; //bit 4,
+            unsigned char RemoteStartTransactionConf :1;//bit 5,
+            unsigned char RemoteStopTransactionReq :1;  //bit 6,
+            unsigned char RemoteStopTransactionConf :1; //bit 7,
+            //CsMsgValue[2]
+            unsigned char ClearChargingProfileReq :1;   //bit 0,
+            unsigned char ClearChargingProfileConf :1;  //bit 1,
+            unsigned char DataTransferReq :1;           //bit 2,
+            unsigned char DataTransferConf :1;          //bit 3,
+            unsigned char GetCompositeScheduleReq :1;   //bit 4,
+            unsigned char GetCompositeScheduleConf :1;  //bit 5,
+            unsigned char :2;                           //bit 6,7
+        } bits[CONNECTOR_QUANTITY];
+    }CsMsg;
+
+    union
+    {
+        //Operations Initiated by Main System
+        unsigned char MsMsgValue[4];
+        struct
+        {
+            //CsMsgValue[0]
+            unsigned char ChangeConfigurationReq :1;                //bit 0,
+            unsigned char ChangeConfigurationConf :1;               //bit 1,
+            unsigned char ClearCacheReq :1;                         //bit 2,
+            unsigned char ClearCacheConf :1;                        //bit 3,
+            unsigned char GetConfigurationReq :1;                   //bit 4,
+            unsigned char GetConfigurationConf :1;                  //bit 5,
+            unsigned char UpdateFirmwareReq :1;                     //bit 6,
+            unsigned char UpdateFirmwareConf :1;                    //bit 7,
+            //CsMsgValue[1]
+            unsigned char GetDiagnosticsReq :1;                     //bit 0,
+            unsigned char GetDiagnosticsConf :1;                    //bit 1,
+            unsigned char GetLocalListVersionReq :1;                //bit 2,
+            unsigned char GetLocalListVersionConf :1;               //bit 3,
+            unsigned char ResetReq :1;                              //bit 4,
+            unsigned char ResetConf :1;                             //bit 5,
+            unsigned char SendLocalListReq :1;                      //bit 6,
+            unsigned char SendLocalListConf :1;                     //bit 7,
+            //CsMsgValue[2]
+            unsigned char CertificateSignedReq :1;                  //bit 0
+            unsigned char CertificateSignedConf :1;                 //bit 1
+            unsigned char DeleteCertificateReq :1;                  //bit 2
+            unsigned char DeleteCertificateConf :1;                 //bit 3
+            unsigned char ExtendedTriggerMessageReq :1;             //bit 4
+            unsigned char ExtendedTriggerMessageConf :1;            //bit 5
+            unsigned char GetInstalledCertificateIdsReq :1;         //bit 6
+            unsigned char GetInstalledCertificateIdsConf :1;        //bit 7
+            //CsMsgValue[3]
+            unsigned char GetLogReq :1;                             //bit 0
+            unsigned char GetLogConf :1;                            //bit 1
+            unsigned char InstallCertificateReq :1;                 //bit 2
+            unsigned char InstallCertificateConf :1;                //bit 3
+            unsigned char SignedUpdateFirmwareReq :1;               //bit 4
+            unsigned char SignedUpdateFirmwareConf :1;              //bit 5
+            unsigned char isRemoteStartWaitReq :1;                  //bit 6
+            unsigned char :1;                                       //bit 7
+        } bits;
+    } MsMsg;
+
+    union
+    {
+        //Operations triggered by CSU
+        unsigned char CSUMsgValue[CONNECTOR_QUANTITY];
+        struct
+        {
+            //CSUMsgValue[0]
+            unsigned char ChargingProfileReq:1;     //bit 0,
+            unsigned char ChargingProfileConf:1;    //bit 0,
+            unsigned char :6;                       //bit 1,2,3,4,5,6,7 , reserved
+        } bits[CONNECTOR_QUANTITY];
+    }CSUMsg;
+
+    struct StructBootNotification                   BootNotification;
+    struct StructHeartbeat                          Heartbeat;
+    struct StructAuthorize                          Authorize;
+    struct StructStartTransaction                   StartTransaction[CONNECTOR_QUANTITY];
+    struct StructStopTransaction                    StopTransaction[CONNECTOR_QUANTITY];
+    struct StructStatusNotification                 StatusNotification[CONNECTOR_QUANTITY];
+    struct StructCancelReservation                  CancelReservation[CONNECTOR_QUANTITY];
+    struct StructChangeAvailability                 ChangeAvailability[CONNECTOR_QUANTITY];
+    struct StructChangeConfiguration                ChangeConfiguration;
+    struct StructClearCache                         ClearCache;
+    struct StructClearChargingProfile               ClearChargingProfile[CONNECTOR_QUANTITY];
+    struct StructDataTransfer                       DataTransfer[CONNECTOR_QUANTITY];
+    struct StructDiagnosticsStatusNotification      DiagnosticsStatusNotification;
+    struct StructFirmwareStatusNotification         FirmwareStatusNotification;
+    struct StructGetCompositeSchedule               GetCompositeSchedule[CONNECTOR_QUANTITY];
+    struct StructGetConfiguration                   GetConfiguration;
+    struct StructGetDiagnostics                     GetDiagnostics;
+    struct StructGetLocalListVersion                GetLocalListVersion;
+    struct StructMeterValues                        MeterValues[CONNECTOR_QUANTITY];
+    struct StructRemoteStartTransaction             RemoteStartTransaction[CONNECTOR_QUANTITY];
+    struct StructRemoteStopTransaction              RemoteStopTransaction[CONNECTOR_QUANTITY];
+    struct StructReserveNow                         ReserveNow[CONNECTOR_QUANTITY];
+    struct StructReset                              Reset;
+    struct StructSendLocalList                      SendLocalList;
+    struct StructSetChargingProfile                 SetChargingProfile[CONNECTOR_QUANTITY];
+    struct StructTriggerMessage                     TriggerMessage[CONNECTOR_QUANTITY];
+    struct StructUnlockConnector                    UnlockConnector[CONNECTOR_QUANTITY];
+    struct StructUpdateFirmware                     UpdateFirmware;
+    struct OCPP16ConfigurationTable                 ConfigurationTable;
+    struct StructChargingProfile                    SmartChargingProfile[CONNECTOR_QUANTITY];
+    struct StructChargingProfile                    MaxChargingProfile;
+    struct StructCost                               Cost;
+    struct StructCertificateSigned                  CertificateSigned;
+    struct StructDeleteCertificate                  DeleteCertificate;
+    struct StructExtendedTrigger                    ExtendedTriggerMessage;
+    struct StructGetInstalledCertificateIds         GetInstalledCertificateIds;
+    struct StructGetLog                             GetLog;
+    struct StructInstallCertificate                 InstallCertificate;
+    struct StructSignedUpdateFirmware               SignedUpdateFirmware;
+    struct StructLogStatusNotification              LogStatusNotification;
+    struct StructSecurityEventNotification          SecurityEventNotification;
+    struct StructSignCertificate                    SignCertificate;
+    struct StructSignedFirmwareStatusNotification   SignedFirmwareStatusNotification;
+    struct StructSessionTarget                      SessionTarget[CONNECTOR_QUANTITY];
+    struct StructTcciCustomData                     TcciCustomData;
+    struct OCMFData                                 OcmfData[CONNECTOR_QUANTITY];
+    struct OCPP16_V2g_Extend						v2g_extend;
+};
+
+struct OCPP20Data
+{
+	unsigned char 							OcppServerURL[512];		//http: non-secure OCPP 1.5-S, https: secure OCPP 1.5-S, ws: non-secure OCPP 1.6-J, wss: secure OCPP 1.6-J"
+	unsigned char 							ChargeBoxId[128];
+	unsigned char 							OcppConnStatus;			//0: disconnected, 1: connected
+	unsigned int 							Timeout_Secs;
+	unsigned short 							Ping_Pong_Interval;
+	long int                                procDogTime;            // Process watch dog refresh timer
+	struct ReportDataType                   ControllerComponentVariable[CtrlrVariable_CNT];
+	struct NetworkConnectionProfile_20      NetworkConnectionProfile[10];
+
+	union
+	{
+		//Operations Initiated by Charge Point
+		unsigned char CpMsgValue[CONNECTOR_QUANTITY];
+		struct
+		{
+			unsigned char DataTransferReq:1;
+			unsigned char DataTransferConf:1;
+			unsigned char ReservationStatusUpdateReq :1;
+			unsigned char ReservationStatusUpdateConf :1;
+			unsigned char TransactionEventReq :1;
+			unsigned char TransactionEventConf :1;
+			unsigned char :2;	//bit 6,7 , reserved
+		} bits[CONNECTOR_QUANTITY];
+	}CpMsg;
+
+	union
+	{
+		//Operations Initiated by Sequence Point
+		unsigned char SpMsgValue[4];
+		struct
+		{
+			unsigned char BootNotificationReq :1;	//bit 0,
+			unsigned char BootNotificationConf :1;	//bit 1,
+			unsigned char AuthorizeReq :1; //bit 2,
+			unsigned char AuthorizeConf :1;	//bit 3,
+			unsigned char FirmwareStatusNotificationReq :1; //bit 6,
+			unsigned char FirmwareStatusNotificationConf :1; //bit 7,
+			unsigned char Get15118EVCertificateReq :1;
+			unsigned char Get15118EVCertificateConf :1;
+
+			unsigned char GetCertificateStatusReq :1;
+			unsigned char GetCertificateStatusConf :1;
+			unsigned char LogStatusNotificationReq :1;
+			unsigned char LogStatusNotificationConf :1;
+			unsigned char NotifyChargingLimitReq :1;
+			unsigned char NotifyChargingLimitConf :1;
+			unsigned char NotifyDisplayMessagesReq :1;
+			unsigned char NotifyDisplayMessagesConf :1;
+
+			unsigned char NotifyCustomerInformationReq :1;
+			unsigned char NotifyCustomerInformationConf :1;
+			unsigned char NotifyEventReq :1;
+			unsigned char NotifyEventConf :1;
+			unsigned char NotifyMonitoringReportReq :1;
+			unsigned char NotifyMonitoringReportConf :1;
+			unsigned char NotifyReportReq :1;
+			unsigned char NotifyReportConf :1;
+
+			unsigned char ReportChargingProfilesReq :1;
+			unsigned char ReportChargingProfilesConf :1;
+			unsigned char SecurityEventNotificationReq :1;
+			unsigned char SecurityEventNotificationConf :1;
+			unsigned char SignCertificateReq :1;
+			unsigned char SignCertificateConf :1;
+            unsigned char :1; //bit 6
+            unsigned char :1; //bit 7
+
+		} bits;
+	} SpMsg;
+
+	union
+	{
+		//Operations Initiated by Central System
+		unsigned char CsMsgValue[3 * (CONNECTOR_QUANTITY)];
+		struct
+		{
+			unsigned char CancelReservationReq :1;	//bit 0,
+			unsigned char CancelReservationConf :1;	//bit 1,
+			unsigned char ChangeAvailabilityReq :1; //bit 2,
+			unsigned char ChangeAvailabilityConf :1;	//bit 3,
+			unsigned char ClearChargingProfileReq :1;	//bit 0,
+			unsigned char ClearChargingProfileConf :1;	//bit 1,
+			unsigned char DataTransferReq :1; //bit 2,
+			unsigned char DataTransferConf :1;	//bit 3,
+
+			unsigned char PublishFirmwareStatusNotificationReq :1;
+			unsigned char PublishFirmwareStatusNotificationConf :1;
+			unsigned char RequestStartTransactionReq :1;
+			unsigned char RequestStartTransactionConf :1;
+			unsigned char RequestStopTransactionReq :1;
+			unsigned char RequestStopTransactionConf :1;
+			unsigned char ReserveNowReq :1;	//bit 4,
+			unsigned char ReserveNowConf :1;	//bit 5,
+
+			unsigned char TriggerMessageReq :1;		//bit 0,
+			unsigned char TriggerMessageConf :1;	//bit 1,
+			unsigned char UnlockConnectorReq :1; 	//bit 2,
+			unsigned char UnlockConnectorConf :1;	//bit 3,
+			unsigned char :4;						//bit 6,7 , reserved
+
+		} bits[CONNECTOR_QUANTITY];
+	}CsMsg;
+
+	union
+	{
+		//Operations Initiated by Main System
+		unsigned char MsMsgValue[8];
+		struct
+		{
+			//CsMsgValue[0]
+			unsigned char CertificateSignedReq :1;
+			unsigned char CertificateSignedConf :1;
+			unsigned char ClearCacheReq :1;	//bit 2,
+			unsigned char ClearCacheConf :1;	//bit 3,
+			unsigned char ClearDisplayMessageReq :1;
+			unsigned char ClearDisplayMessageConf :1;
+			unsigned char ClearVariableMonitoringReq :1;
+			unsigned char ClearVariableMonitoringConf :1;
+
+			unsigned char CostUpdatedReq :1;
+			unsigned char CostUpdatedConf :1;
+			unsigned char CustomerInformationReq :1;
+			unsigned char CustomerInformationConf :1;
+			unsigned char DeleteCertificateReq :1;
+			unsigned char DeleteCertificateConf :1;
+			unsigned char GetBaseReportReq :1;
+			unsigned char GetBaseReportConf :1;
+
+			unsigned char GetChargingProfilesReq :1;
+			unsigned char GetChargingProfilesConf :1;
+			unsigned char GetCompositeScheduleReq :1;	//bit 4,
+			unsigned char GetCompositeScheduleConf :1;	//bit 5,
+			unsigned char GetDisplayMessagesReq :1;
+			unsigned char GetDisplayMessagesConf :1;
+			unsigned char GetInstalledCertificateIdsReq :1;
+			unsigned char GetInstalledCertificateIdsConf :1;
+
+			unsigned char GetLocalListVersionReq :1; //bit 2,
+			unsigned char GetLocalListVersionConf :1;	//bit 3,
+			unsigned char GetLogReq :1;
+			unsigned char GetLogConf :1;
+			unsigned char GetMonitoringReportReq :1;
+			unsigned char GetMonitoringReportConf :1;
+			unsigned char GetReportReq :1;
+			unsigned char GetReportConf :1;
+
+			unsigned char GetTransactionStatusReq :1;
+			unsigned char GetTransactionStatusConf :1;
+			unsigned char GetVariablesReq :1;
+			unsigned char GetVariablesConf :1;
+			unsigned char InstallCertificateReq :1;
+			unsigned char InstallCertificateConf :1;
+			unsigned char PublishFirmwareReq :1;
+			unsigned char PublishFirmwareConf :1;
+
+			unsigned char ResetReq :1; //bit 4,
+			unsigned char ResetConf :1;	//bit 5,
+			unsigned char SendLocalListReq :1;	//bit 6,
+			unsigned char SendLocalListConf :1;	//bit 7,
+			unsigned char SetChargingProfileReq :1;	//bit 6,
+			unsigned char SetChargingProfileConf :1;	//bit 7,
+			unsigned char SetDisplayMessageReq :1;
+			unsigned char SetDisplayMessageConf :1;
+
+			unsigned char SetMonitoringBaseReq :1;
+			unsigned char SetMonitoringBaseConf :1;
+			unsigned char SetMonitoringLevelReq :1;
+			unsigned char SetMonitoringLevelConf :1;
+			unsigned char SetNetworkProfileReq :1;
+			unsigned char SetNetworkProfileConf :1;
+			unsigned char SetVariableMonitoringReq :1;
+			unsigned char SetVariableMonitoringConf :1;
+
+			unsigned char SetVariablesReq :1;
+			unsigned char SetVariablesConf :1;
+			unsigned char UnpublishFirmwareReq :1;
+			unsigned char UnpublishFirmwareConf :1;
+			unsigned char UpdateFirmwareReq :1;
+			unsigned char UpdateFirmwareConf :1;
+            unsigned char isRemoteStartWaitReq :1;
+            unsigned char :1;
+		} bits;
+	} MsMsg;
+
+	union
+	{
+		//Operations triggered by CSU
+		unsigned char CSUMsgValue[CONNECTOR_QUANTITY];
+		struct
+		{
+			//CSUMsgValue[0]
+            unsigned char ChargingProfileReq:1;	            //bit 0
+            unsigned char ChargingProfileConf:1;	        //bit 1
+            unsigned char ClearedChargingLimitReq :1;       //bit 2
+            unsigned char ClearedChargingLimitConf :1;      //bit 3
+            unsigned char NotifyEVChargingNeedsReq :1;      //bit 4
+            unsigned char NotifyEVChargingNeedsConf :1;     //bit 5
+            unsigned char NotifyEVChargingScheduleReq:1;    //bit 6
+            unsigned char NotifyEVChargingScheduleConf:1;   //bit 7
+		} bits[CONNECTOR_QUANTITY];
+	}CSUMsg;
+
+	struct Authorize_20 						Authorize;
+	struct BootNotification_20 					BootNotification;
+	struct CancelReservation_20					CancelReservation[CONNECTOR_QUANTITY];
+	struct CertificateSigned_20					CertificateSigned;
+	struct ChangeAvailability_20				ChangeAvailability[CONNECTOR_QUANTITY];
+	struct ClearCache_20						ClearCache;
+	struct ClearChargingProfile_20				ClearChargingProfile[CONNECTOR_QUANTITY];
+	struct ClearDisplayMessage_20				ClearDisplayMessage;
+	struct ClearedChargingLimit_20				ClearedChargingLimit[CONNECTOR_QUANTITY];
+	struct ClearVariableMonitoring_20			ClearVariableMonitoring;
+	struct CostUpdated_20						CostUpdated;
+	struct CustomerInformation_20				CustomerInformation;
+	struct DataTransfer_20						DataTransfer[CONNECTOR_QUANTITY];
+	struct DeleteCertificate_20					DeleteCertificate;
+	struct FirmwareStatusNotification_20		FirmwareStatusNotification;
+	struct Get15118EVCertificate_20				Get15118EVCertificate;
+	struct GetBaseReport_20						GetBaseReport;
+	struct GetCertificateStatus_20				GetCertificateStatus;
+	struct GetChargingProfiles_20				GetChargingProfiles[CONNECTOR_QUANTITY];
+	struct GetCompositeSchedule_20				GetCompositeSchedule[CONNECTOR_QUANTITY];
+	struct GetDisplayMessages_20				GetDisplayMessages;
+	struct GetInstalledCertificateIds_20		GetInstalledCertificateIds;
+	struct GetLocalListVersion_20				GetLocalListVersion;
+	struct GetLog_20							GetLog;
+	struct GetMonitoringReport_20				GetMonitoringReport;
+	struct GetReport_20							GetReport;
+	struct GetTransactionStatus_20				GetTransactionStatus[CONNECTOR_QUANTITY];
+	struct GetVariables_20						GetVariables;
+	struct Heartbeat_20							Heartbeat;
+	struct InstallCertificate_20				InstallCertificate;
+	struct LogStatusNotification_20				LogStatusNotification;
+	struct MeterValues_20						MeterValues[CONNECTOR_QUANTITY];
+	struct NotifyChargingLimit_20				NotifyChargingLimit[CONNECTOR_QUANTITY];
+	struct NotifyCustomerInformation_20			NotifyCustomerInformation;
+	struct NotifyDisplayMessages_20				NotifyDisplayMessages;
+	struct NotifyEVChargingNeeds_20				NotifyEVChargingNeeds[CONNECTOR_QUANTITY];
+	struct NotifyEVChargingSchedule_20			NotifyEVChargingSchedule[CONNECTOR_QUANTITY];
+	struct NotifyEvent_20						NotifyEvent;
+	struct NotifyMonitoringReport_20			NotifyMonitoringReport;
+	struct NotifyReport_20						NotifyReport;
+	struct PublishFirmware_20					PublishFirmware;
+	struct PublishFirmwareStatusNotification_20	PublishFirmwareStatusNotificatio;
+	struct ReportChargingProfiles_20			ReportChargingProfiles[CONNECTOR_QUANTITY];
+	struct RequestStartTransaction_20			RequestStartTransaction[CONNECTOR_QUANTITY];
+	struct RequestStopTransaction_20			RequestStopTransaction[CONNECTOR_QUANTITY];
+	struct ReservationStatusUpdate_20			ReservationStatusUpdate[CONNECTOR_QUANTITY];
+	struct ReserveNow_20						ReserveNow[CONNECTOR_QUANTITY];
+	struct Reset_20								Reset;
+	struct SecurityEventNotification_20			SecurityEventNotification;
+	struct SendLocalList_20						SendLocalList;
+	struct SetChargingProfile_20				SetChargingProfile[CONNECTOR_QUANTITY];
+	struct SetDisplayMessage_20					SetDisplayMessage;
+	struct SetMonitoringBase_20					SetMonitoringBase;
+	struct SetMonitoringLevel_20				SetMonitoringLevel;
+	struct SetNetworkProfile_20					SetNetworkProfile;
+	struct SetVariableMonitoring_20				SetVariableMonitoring;
+	struct SetVariables_20						SetVariables;
+	struct SignCertificate_20					SignCertificate;
+	struct StatusNotification_20				StatusNotification[CONNECTOR_QUANTITY];
+	struct TransactionEvent_20					TransactionEvent[CONNECTOR_QUANTITY];
+	struct TriggerMessage_20					TriggerMessage;
+	struct UnlockConnector_20					UnlockConnector[CONNECTOR_QUANTITY];
+	struct UnpublishFirmware_20					UnpublishFirmware;
+	struct UpdateFirmware_20					UpdateFirmware;
+	struct ChargingProfileType                  SmartChargingProfile[CONNECTOR_QUANTITY];
+	struct ChargingProfileType                  MaxChargingProfile;
+	struct StructSessionTarget                  SessionTarget[CONNECTOR_QUANTITY];
+};
+
+
+
+
+
+
+//------------------------------------------------------------------------------
+char *GetCurrency(uint8_t index);
+char *GetFaultStatusCode(uint8_t index);
+char *GetAlarmStatusCode(uint8_t index);
+char *GetInfoStatusCode(uint16_t index);
+#endif // DEFINE_H_

+ 124 - 124
EVSE/Projects/DD360Tcci/Apps/Log/log.c

@@ -1,124 +1,124 @@
-#include <stdio.h>
-#include <stdlib.h>
-#include <stdint.h>
-#include <string.h>
-
-#include <unistd.h>
-#include <time.h>
-#include <stdarg.h>
-
-#include <sys/timeb.h>
-#include <sys/time.h>
-
-#include "../ShareMemory/shmMem.h"
-#include "../Define/define.h"
-#include "log.h"
-
-//------------------------------------------------------------------------------
-#define YES                                     1
-#define NO                                      0
-
-//------------------------------------------------------------------------------
-int StoreLogMsg(const char *fmt, ...)
-{
-    char Buf[4096 + 256] = {0};
-    char buffer[4096] = {0};
-    int rc = -1;
-    va_list args;
-    struct timeb  SeqEndTime;
-    struct tm *tm;
-    struct SysConfigData *pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
-
-    va_start(args, fmt);
-    rc = vsnprintf(buffer, sizeof(buffer), fmt, args);
-    va_end(args);
-
-    ftime(&SeqEndTime);
-    SeqEndTime.time = time(NULL);
-    tm = localtime(&SeqEndTime.time);
-
-    if (pSysConfig->SwitchDebugFlag == YES) {
-        sprintf(Buf, "%02d:%02d:%02d:%03d - %s",
-                tm->tm_hour,
-                tm->tm_min,
-                tm->tm_sec,
-                SeqEndTime.millitm,
-                buffer);
-        printf("%s", Buf);
-    } else {
-        sprintf(Buf, "echo \"%04d-%02d-%02d %02d:%02d:%02d:%03d - %s\" >> /Storage/SystemLog/[%04d.%02d]SystemLog",
-                tm->tm_year + 1900,
-                tm->tm_mon + 1,
-                tm->tm_mday,
-                tm->tm_hour,
-                tm->tm_min,
-                tm->tm_sec,
-                SeqEndTime.millitm,
-                buffer,
-                tm->tm_year + 1900,
-                tm->tm_mon + 1);
-        system(Buf);
-    }
-
-    return rc;
-}
-
-int StoreEventLogMsg(const char *fmt, ...)
-{
-    char Buf[4096 + 256];
-    char buffer[4096];
-    time_t CurrentTime;
-    struct tm *tm;
-    struct timeval tv;
-    va_list args;
-    struct SysConfigData *pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
-
-    va_start(args, fmt);
-    int rc = vsnprintf(buffer, sizeof(buffer), fmt, args);
-    va_end(args);
-
-    memset(Buf, 0, sizeof(Buf));
-    CurrentTime = time(NULL);
-    tm = localtime(&CurrentTime);
-    gettimeofday(&tv, NULL); // get microseconds, 10^-6
-
-    if ((pSysConfig->ModelName != NULL) &&
-            (pSysConfig->SerialNumber != NULL) &&
-            (strlen((char *)pSysConfig->ModelName) >= 14)) {
-        sprintf(Buf, "echo -n \"[%04d.%02d.%02d %02d:%02d:%02d.%06ld]%s\" >> /Storage/EventLog/[%04d.%02d]%s_%s_EventLog",
-                tm->tm_year + 1900,
-                tm->tm_mon + 1,
-                tm->tm_mday,
-                tm->tm_hour,
-                tm->tm_min,
-                tm->tm_sec,
-                tv.tv_usec,
-                buffer,
-                tm->tm_year + 1900,
-                tm->tm_mon + 1,
-                pSysConfig->ModelName,
-                pSysConfig->SerialNumber);
-    } else {
-        sprintf(Buf, "echo -n \"[%04d.%02d.%02d %02d:%02d:%02d.%06ld]%s\" >> /Storage/EventLog/[%04d.%02d]EventLog",
-                tm->tm_year + 1900,
-                tm->tm_mon + 1,
-                tm->tm_mday,
-                tm->tm_hour,
-                tm->tm_min,
-                tm->tm_sec,
-                tv.tv_usec,
-                buffer,
-                tm->tm_year + 1900,
-                tm->tm_mon + 1);
-    }
-
-#ifdef SystemLogMessage
-    system(Buf);
-#endif //SystemLogMessage
-
-#ifdef ConsloePrintLog
-    printf("[%04d.%02d.%02d %02d:%02d:%02d.%06ld]%s", tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec, tv.tv_usec, buffer);
-#endif //ConsloePrintLog
-
-    return rc;
-}
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdint.h>
+#include <string.h>
+
+#include <unistd.h>
+#include <time.h>
+#include <stdarg.h>
+
+#include <sys/timeb.h>
+#include <sys/time.h>
+
+#include "../ShareMemory/shmMem.h"
+#include "../Define/define.h"
+#include "log.h"
+
+//------------------------------------------------------------------------------
+#define YES                                     1
+#define NO                                      0
+
+//------------------------------------------------------------------------------
+int StoreLogMsg(const char *fmt, ...)
+{
+    char Buf[4096 + 256] = {0};
+    char buffer[4096] = {0};
+    int rc = -1;
+    va_list args;
+    struct timeb  SeqEndTime;
+    struct tm *tm;
+    struct SysConfigData *pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
+
+    va_start(args, fmt);
+    rc = vsnprintf(buffer, sizeof(buffer), fmt, args);
+    va_end(args);
+
+    ftime(&SeqEndTime);
+    SeqEndTime.time = time(NULL);
+    tm = localtime(&SeqEndTime.time);
+
+    if (pSysConfig->SwitchDebugFlag == YES) {
+        sprintf(Buf, "%02d:%02d:%02d:%03d - %s",
+                tm->tm_hour,
+                tm->tm_min,
+                tm->tm_sec,
+                SeqEndTime.millitm,
+                buffer);
+        printf("%s", Buf);
+    } else {
+        sprintf(Buf, "echo \"%04d-%02d-%02d %02d:%02d:%02d:%03d - %s\" >> /Storage/SystemLog/[%04d.%02d]SystemLog",
+                tm->tm_year + 1900,
+                tm->tm_mon + 1,
+                tm->tm_mday,
+                tm->tm_hour,
+                tm->tm_min,
+                tm->tm_sec,
+                SeqEndTime.millitm,
+                buffer,
+                tm->tm_year + 1900,
+                tm->tm_mon + 1);
+        system(Buf);
+    }
+
+    return rc;
+}
+
+int StoreEventLogMsg(const char *fmt, ...)
+{
+    char Buf[4096 + 256];
+    char buffer[4096];
+    time_t CurrentTime;
+    struct tm *tm;
+    struct timeval tv;
+    va_list args;
+    struct SysConfigData *pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
+
+    va_start(args, fmt);
+    int rc = vsnprintf(buffer, sizeof(buffer), fmt, args);
+    va_end(args);
+
+    memset(Buf, 0, sizeof(Buf));
+    CurrentTime = time(NULL);
+    tm = localtime(&CurrentTime);
+    gettimeofday(&tv, NULL); // get microseconds, 10^-6
+
+    if ((pSysConfig->ModelName != NULL) &&
+            (pSysConfig->SerialNumber != NULL) &&
+            (strlen((char *)pSysConfig->ModelName) >= 14)) {
+        sprintf(Buf, "echo -n \"[%04d.%02d.%02d %02d:%02d:%02d.%06ld]%s\" >> /Storage/EventLog/[%04d.%02d]%s_%s_EventLog",
+                tm->tm_year + 1900,
+                tm->tm_mon + 1,
+                tm->tm_mday,
+                tm->tm_hour,
+                tm->tm_min,
+                tm->tm_sec,
+                tv.tv_usec,
+                buffer,
+                tm->tm_year + 1900,
+                tm->tm_mon + 1,
+                pSysConfig->ModelName,
+                pSysConfig->SerialNumber);
+    } else {
+        sprintf(Buf, "echo -n \"[%04d.%02d.%02d %02d:%02d:%02d.%06ld]%s\" >> /Storage/EventLog/[%04d.%02d]EventLog",
+                tm->tm_year + 1900,
+                tm->tm_mon + 1,
+                tm->tm_mday,
+                tm->tm_hour,
+                tm->tm_min,
+                tm->tm_sec,
+                tv.tv_usec,
+                buffer,
+                tm->tm_year + 1900,
+                tm->tm_mon + 1);
+    }
+
+#ifdef SystemLogMessage
+    system(Buf);
+#endif //SystemLogMessage
+
+#ifdef ConsloePrintLog
+    printf("[%04d.%02d.%02d %02d:%02d:%02d.%06ld]%s", tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec, tv.tv_usec, buffer);
+#endif //ConsloePrintLog
+
+    return rc;
+}

+ 14 - 14
EVSE/Projects/DD360Tcci/Apps/Log/log.h

@@ -1,14 +1,14 @@
-#ifndef _LOG_H_
-#define _LOG_H_
-
-//------------------------------------------------------------------------------
-#define log_info(format, args...) StoreLogMsg("[%s:%d][%s][Info] "format, (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : (strrchr(__FILE__, '\\') ? strrchr(__FILE__, '\\') + 1 : __FILE__)), __LINE__, __FUNCTION__, ##args)
-#define log_warn(format, args...) StoreLogMsg("[%s:%d][%s][Warn] "format, (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : (strrchr(__FILE__, '\\') ? strrchr(__FILE__, '\\') + 1 : __FILE__)), __LINE__, __FUNCTION__, ##args)
-#define log_error(format, args...) StoreLogMsg("[%s:%d][%s][Error] "format, (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : (strrchr(__FILE__, '\\') ? strrchr(__FILE__, '\\') + 1 : __FILE__)), __LINE__, __FUNCTION__, ##args)
-
-#define event_info(format, args...) StoreEventLogMsg("[%s:%d][%s][Info] "format, (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : (strrchr(__FILE__, '\\') ? strrchr(__FILE__, '\\') + 1 : __FILE__)), __LINE__, __FUNCTION__, ##args) //DS60-120 add
-//------------------------------------------------------------------------------
-int StoreLogMsg(const char *fmt, ...);
-int StoreEventLogMsg(const char *fmt, ...);
-
-#endif /* _LOG_H_ */
+#ifndef _LOG_H_
+#define _LOG_H_
+
+//------------------------------------------------------------------------------
+#define log_info(format, args...) StoreLogMsg("[%s:%d][%s][Info] "format, (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : (strrchr(__FILE__, '\\') ? strrchr(__FILE__, '\\') + 1 : __FILE__)), __LINE__, __FUNCTION__, ##args)
+#define log_warn(format, args...) StoreLogMsg("[%s:%d][%s][Warn] "format, (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : (strrchr(__FILE__, '\\') ? strrchr(__FILE__, '\\') + 1 : __FILE__)), __LINE__, __FUNCTION__, ##args)
+#define log_error(format, args...) StoreLogMsg("[%s:%d][%s][Error] "format, (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : (strrchr(__FILE__, '\\') ? strrchr(__FILE__, '\\') + 1 : __FILE__)), __LINE__, __FUNCTION__, ##args)
+
+#define event_info(format, args...) StoreEventLogMsg("[%s:%d][%s][Info] "format, (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : (strrchr(__FILE__, '\\') ? strrchr(__FILE__, '\\') + 1 : __FILE__)), __LINE__, __FUNCTION__, ##args) //DS60-120 add
+//------------------------------------------------------------------------------
+int StoreLogMsg(const char *fmt, ...);
+int StoreEventLogMsg(const char *fmt, ...);
+
+#endif /* _LOG_H_ */

+ 251 - 251
EVSE/Projects/DD360Tcci/Apps/ModuleChkSysTask/Module_ChkSysTask.c

@@ -1,251 +1,251 @@
-/*
- * CheckTask.c
- *
- *  Created on: 2021年9月22日
- *      Author: 8513
- */
-#include <stdio.h>      /*標準輸入輸出定義*/
-#include <stdlib.h>     /*標準函數庫定義*/
-#include <string.h>
-#include <stdint.h>
-#include <sys/types.h>
-#include <dirent.h>
-#include "../Config.h"
-#include "../Log/log.h"
-#include "../Define/define.h"
-
-#include "../ShareMemory/shmMem.h"
-#include "Module_ChkSysTask.h"
-
-struct SysConfigData *pSysConfig = NULL;
-struct SysInfoData *pSysInfo = NULL;
-struct OCPP16Data *ShmOCPP16Data = NULL;
-struct ChargingInfoData *pAcChargingInfo = NULL;
-static struct ChargingInfoData *pDcChargingInfo = NULL;
-struct SysConfigAndInfo         *ShmSysConfigAndInfo;
-struct StatusCodeData           *ShmStatusCodeData;
-static DcCommonInfo* ShmDcCommonData = NULL;
-
-bool Taskconutstring(char *src, char *taskname)
-{
-    bool result = false;
-
-    if (src == NULL || strlen(src) == 0)
-        return result;
-
-    if (strstr(src, taskname) != NULL &&
-        strstr(src, "grep") == NULL &&
-        strstr(src, "[") == NULL)
-    {
-        result = true;
-    }
-
-    return result;
-}
-
-int GetProcessCount(char *procName)
-{
-	int result = 0;
-	FILE *fp;
-	char cmd[256];
-	char buf[256];
-
-	sprintf(cmd, "ps -ef |grep %s", procName);
-	fp = popen(cmd, "r");
-	if(fp != NULL)
-	{
-		while(fgets(buf, sizeof(buf), fp) != NULL)
-		{
-			if (Taskconutstring(buf, procName))
-				result++;
-		}
-	}
-
-	pclose(fp);
-
-	return result;
-}
-
-unsigned char CheckSystemTask(unsigned char systemPage)
-{
-	unsigned char result = 0;
-	unsigned char count_main 		= GetProcessCount("main");
-	unsigned char count_evComm 		= GetProcessCount("Module_EvComm");
-	unsigned char count_interComm	= GetProcessCount("Module_InternalComm");
-	unsigned char count_eventComm	= GetProcessCount("Module_EventLogging");
-	unsigned char count_primaryComm	= GetProcessCount("Module_PrimaryComm");
-	unsigned char count_lcmComm	    = GetProcessCount("Module_LcmControl");
-	unsigned char count_doComm	    = GetProcessCount("Module_DoComm");
-	unsigned char count_produceComm	= GetProcessCount("Module_ProduceUtils");
-	unsigned char count_updateFW	= GetProcessCount("Module_UpdateFW");
-
-	//if (systemPage != _LCM_FIX )
-	{
-		if (count_main < _SYSTEM_TASK_COUNT_MAIN )
-		{
-            ///*
-            system("/usr/bin/fuser -k /dev/watchdog");
-            sleep(1);
-            system("echo V > /dev/watchdog");
-            system("killall main");
-			system("killall Module_EventLogging");
-			system("killall Module_PrimaryComm");
-			system("killall Module_EvComm");
-			system("killall Module_LcmControl");
-			system("killall Module_InternalComm");
-			system("killall Module_DoComm");
-			system("killall Module_ProduceUtils");
-			system("killall Module_UpdateFW");
-            sleep(3);
-            system("/root/main &");
-            sleep(20);
-            //*/
-            /*
-            log_info("System task lost (CSU). ");
-            sleep(3);
-            system("reboot -f");
-            */
-		}
-		else
-		{
-			if (count_evComm < _SYSTEM_TASK_COUNT_EVCOMM )
-			{
-				system("killall Module_EvComm");
-				sleep(3);
-				system("/root/Module_EvComm &");
-			}
-        	if (count_interComm < _SYSTEM_TASK_COUNT_INTERNALCOMM )
-			{
-				system("killall Module_InternalComm");
-				sleep(3);
-				system("/root/Module_InternalComm &");
-			}
-			if (count_eventComm < _SYSTEM_TASK_COUNT_EVENTLOGGING )
-			{
-				system("killall Module_EventLogging");
-				sleep(3);
-				system("/root/Module_EventLogging &");
-			}
-			if (count_primaryComm < _SYSTEM_TASK_COUNT_PRIMARYCOMM )
-			{
-				system("killall Module_PrimaryComm");
-				sleep(3);
-				system("/root/Module_PrimaryComm &");
-			}
-			if (count_lcmComm < _SYSTEM_TASK_COUNT_LCM )
-			{
-				system("killall Module_LcmControl");
-				sleep(3);
-				system("/root/Module_LcmControl &");
-			}
-			if (count_doComm < _SYSTEM_TASK_COUNT_DOCOMM )
-			{
-				system("killall Module_DoComm");
-				sleep(3);
-				system("/root/Module_DoComm &");
-			}
-			if (count_produceComm < _SYSTEM_TASK_COUNT_PRODUCEUTILS )
-			{
-				system("killall Module_ProduceUtils");
-				sleep(3);
-				system("/root/Module_ProduceUtils &");
-			}
-			if (count_updateFW < _SYSTEM_TASK_COUNT_UPDATEFW )
-			{
-				system("killall Module_UpdateFW");
-				sleep(3);
-				system("/root/Module_UpdateFW &");
-			}
-		}
-
-	}
-
-	if (count_main < _SYSTEM_TASK_COUNT_MAIN)
-		result = _SYSTEM_TASK_LOST_ITEM_MAIN;
-	else if (count_evComm < _SYSTEM_TASK_COUNT_EVCOMM)
-		result = _SYSTEM_TASK_LOST_ITEM_EVCOMM;
-/*	else if (count_psuComm < 2)
-		result = 3; */
-    else if (count_eventComm < _SYSTEM_TASK_COUNT_EVENTLOGGING )
-        result = _SYSTEM_TASK_LOST_ITEM_EVENTLOG;
-    else if (count_primaryComm < _SYSTEM_TASK_COUNT_PRIMARYCOMM)
-        result = _SYSTEM_TASK_LOST_ITEM_PRIMARYCOMM;
-    else if (count_lcmComm < _SYSTEM_TASK_COUNT_LCM)
-        result = _SYSTEM_TASK_LOST_ITEM_LCMCONTROL;
-    else if (count_interComm < _SYSTEM_TASK_COUNT_INTERNALCOMM )
-        result = _SYSTEM_TASK_LOST_ITEM_INTERCOMM;
-    else if (count_doComm < _SYSTEM_TASK_COUNT_DOCOMM)
-        result = _SYSTEM_TASK_LOST_ITEM_DOCOMM;
-    else if (count_produceComm < _SYSTEM_TASK_COUNT_PRODUCEUTILS)
-        result = _SYSTEM_TASK_LOST_ITEM_PRODUCTUTILS;
-    else if (count_updateFW < _SYSTEM_TASK_COUNT_UPDATEFW)
-        result = _SYSTEM_TASK_LOST_ITEM_UPDATEFW;
-
-
-	return result;
-}
-
-//===============================================
-// Check System Task alive
-// ==============================================
-void CheckSystemTaskAlive()
-{
-    unsigned char lostId = CheckSystemTask(ShmSysConfigAndInfo->SysInfo.SystemPage);
-    if (lostId != 0) {
-        if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemTaskLost == NO) {
-           if (lostId == _SYSTEM_TASK_LOST_ITEM_MAIN)
-               log_error("System task lost (CSU). ");
-           else if (lostId == _SYSTEM_TASK_LOST_ITEM_EVCOMM)
-               log_error("System task lost (EVComm). ");
-//           else if (lostId == _SYSTEM_TASK_LOST_ITEM_PSUCOMM)
-//               PRINTF_FUNC("System task lost (PSU Task). ");
-           else if (lostId == _SYSTEM_TASK_LOST_ITEM_EVENTLOG)
-               log_error("System task lost (Event log). ");
-           else if (lostId == _SYSTEM_TASK_LOST_ITEM_PRIMARYCOMM)
-               log_error("System task lost (Primary). ");
-           else if (lostId == _SYSTEM_TASK_LOST_ITEM_LCMCONTROL)
-               log_error("System task lost (LCM Comm). ");
-           else if (lostId == _SYSTEM_TASK_LOST_ITEM_INTERCOMM)
-               log_error("System task lost (Internal Comm). ");
-           else if (lostId == _SYSTEM_TASK_LOST_ITEM_DOCOMM)
-               log_error("System task lost (Do Comm). ");
-           else if (lostId == _SYSTEM_TASK_LOST_ITEM_PRODUCTUTILS)
-               log_error("System task lost (ProcductUtils Comm). ");
-           else if (lostId == _SYSTEM_TASK_LOST_ITEM_UPDATEFW)
-               log_error("System task lost (Update FW) ");
-           ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemTaskLost = YES;
-        }
-    } else
-        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemTaskLost = NO;
-}
-
-
-int main(void)
-{
-    if (CreateAllCsuShareMemory() == FAIL) {
-        log_error("create share memory error");
-        return FAIL;
-    }
-
-    pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
-    pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
-    ShmOCPP16Data = (struct OCPP16Data *)GetShmOCPP16Data();
-    ShmSysConfigAndInfo = (struct SysConfigAndInfo *)GetShmSysConfigAndInfo();
-	ShmStatusCodeData = (struct StatusCodeData*)GetShmStatusCodeData();
-	ShmDcCommonData = (DcCommonInfo*)GetShmDcCommonData();
-    MappingGunChargingInfo("CheckSystem Task");
-    while(true)
-    {
-		sleep(3);
-      	for (uint8_t gun = 0; gun < pSysConfig->TotalConnectorCount; gun++) {
-    		pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gun);
-			if (pDcChargingInfo->SystemStatus == SYS_MODE_UPDATE )
-				continue;
-		}
-		if (ShmDcCommonData->DebugFlag == TRUE) {
-			continue;
-		}
-		CheckSystemTaskAlive();
-    }
-	return FAIL;
-}
+/*
+ * CheckTask.c
+ *
+ *  Created on: 2021年9月22日
+ *      Author: 8513
+ */
+#include <stdio.h>      /*標準輸入輸出定義*/
+#include <stdlib.h>     /*標準函數庫定義*/
+#include <string.h>
+#include <stdint.h>
+#include <sys/types.h>
+#include <dirent.h>
+#include "../Config.h"
+#include "../Log/log.h"
+#include "../Define/define.h"
+
+#include "../ShareMemory/shmMem.h"
+#include "Module_ChkSysTask.h"
+
+struct SysConfigData *pSysConfig = NULL;
+struct SysInfoData *pSysInfo = NULL;
+struct OCPP16Data *ShmOCPP16Data = NULL;
+struct ChargingInfoData *pAcChargingInfo = NULL;
+static struct ChargingInfoData *pDcChargingInfo = NULL;
+struct SysConfigAndInfo         *ShmSysConfigAndInfo;
+struct StatusCodeData           *ShmStatusCodeData;
+static DcCommonInfo* ShmDcCommonData = NULL;
+
+bool Taskconutstring(char *src, char *taskname)
+{
+    bool result = false;
+
+    if (src == NULL || strlen(src) == 0)
+        return result;
+
+    if (strstr(src, taskname) != NULL &&
+        strstr(src, "grep") == NULL &&
+        strstr(src, "[") == NULL)
+    {
+        result = true;
+    }
+
+    return result;
+}
+
+int GetProcessCount(char *procName)
+{
+	int result = 0;
+	FILE *fp;
+	char cmd[256];
+	char buf[256];
+
+	sprintf(cmd, "ps -ef |grep %s", procName);
+	fp = popen(cmd, "r");
+	if(fp != NULL)
+	{
+		while(fgets(buf, sizeof(buf), fp) != NULL)
+		{
+			if (Taskconutstring(buf, procName))
+				result++;
+		}
+	}
+
+	pclose(fp);
+
+	return result;
+}
+
+unsigned char CheckSystemTask(unsigned char systemPage)
+{
+	unsigned char result = 0;
+	unsigned char count_main 		= GetProcessCount("main");
+	unsigned char count_evComm 		= GetProcessCount("Module_EvComm");
+	unsigned char count_interComm	= GetProcessCount("Module_InternalComm");
+	unsigned char count_eventComm	= GetProcessCount("Module_EventLogging");
+	unsigned char count_primaryComm	= GetProcessCount("Module_PrimaryComm");
+	unsigned char count_lcmComm	    = GetProcessCount("Module_LcmControl");
+	unsigned char count_doComm	    = GetProcessCount("Module_DoComm");
+	unsigned char count_produceComm	= GetProcessCount("Module_ProduceUtils");
+	unsigned char count_updateFW	= GetProcessCount("Module_UpdateFW");
+
+	//if (systemPage != _LCM_FIX )
+	{
+		if (count_main < _SYSTEM_TASK_COUNT_MAIN )
+		{
+            ///*
+            system("/usr/bin/fuser -k /dev/watchdog");
+            sleep(1);
+            system("echo V > /dev/watchdog");
+            system("killall main");
+			system("killall Module_EventLogging");
+			system("killall Module_PrimaryComm");
+			system("killall Module_EvComm");
+			system("killall Module_LcmControl");
+			system("killall Module_InternalComm");
+			system("killall Module_DoComm");
+			system("killall Module_ProduceUtils");
+			system("killall Module_UpdateFW");
+            sleep(3);
+            system("/root/main &");
+            sleep(20);
+            //*/
+            /*
+            log_info("System task lost (CSU). ");
+            sleep(3);
+            system("reboot -f");
+            */
+		}
+		else
+		{
+			if (count_evComm < _SYSTEM_TASK_COUNT_EVCOMM )
+			{
+				system("killall Module_EvComm");
+				sleep(3);
+				system("/root/Module_EvComm &");
+			}
+        	if (count_interComm < _SYSTEM_TASK_COUNT_INTERNALCOMM )
+			{
+				system("killall Module_InternalComm");
+				sleep(3);
+				system("/root/Module_InternalComm &");
+			}
+			if (count_eventComm < _SYSTEM_TASK_COUNT_EVENTLOGGING )
+			{
+				system("killall Module_EventLogging");
+				sleep(3);
+				system("/root/Module_EventLogging &");
+			}
+			if (count_primaryComm < _SYSTEM_TASK_COUNT_PRIMARYCOMM )
+			{
+				system("killall Module_PrimaryComm");
+				sleep(3);
+				system("/root/Module_PrimaryComm &");
+			}
+			if (count_lcmComm < _SYSTEM_TASK_COUNT_LCM )
+			{
+				system("killall Module_LcmControl");
+				sleep(3);
+				system("/root/Module_LcmControl &");
+			}
+			if (count_doComm < _SYSTEM_TASK_COUNT_DOCOMM )
+			{
+				system("killall Module_DoComm");
+				sleep(3);
+				system("/root/Module_DoComm &");
+			}
+			if (count_produceComm < _SYSTEM_TASK_COUNT_PRODUCEUTILS )
+			{
+				system("killall Module_ProduceUtils");
+				sleep(3);
+				system("/root/Module_ProduceUtils &");
+			}
+			if (count_updateFW < _SYSTEM_TASK_COUNT_UPDATEFW )
+			{
+				system("killall Module_UpdateFW");
+				sleep(3);
+				system("/root/Module_UpdateFW &");
+			}
+		}
+
+	}
+
+	if (count_main < _SYSTEM_TASK_COUNT_MAIN)
+		result = _SYSTEM_TASK_LOST_ITEM_MAIN;
+	else if (count_evComm < _SYSTEM_TASK_COUNT_EVCOMM)
+		result = _SYSTEM_TASK_LOST_ITEM_EVCOMM;
+/*	else if (count_psuComm < 2)
+		result = 3; */
+    else if (count_eventComm < _SYSTEM_TASK_COUNT_EVENTLOGGING )
+        result = _SYSTEM_TASK_LOST_ITEM_EVENTLOG;
+    else if (count_primaryComm < _SYSTEM_TASK_COUNT_PRIMARYCOMM)
+        result = _SYSTEM_TASK_LOST_ITEM_PRIMARYCOMM;
+    else if (count_lcmComm < _SYSTEM_TASK_COUNT_LCM)
+        result = _SYSTEM_TASK_LOST_ITEM_LCMCONTROL;
+    else if (count_interComm < _SYSTEM_TASK_COUNT_INTERNALCOMM )
+        result = _SYSTEM_TASK_LOST_ITEM_INTERCOMM;
+    else if (count_doComm < _SYSTEM_TASK_COUNT_DOCOMM)
+        result = _SYSTEM_TASK_LOST_ITEM_DOCOMM;
+    else if (count_produceComm < _SYSTEM_TASK_COUNT_PRODUCEUTILS)
+        result = _SYSTEM_TASK_LOST_ITEM_PRODUCTUTILS;
+    else if (count_updateFW < _SYSTEM_TASK_COUNT_UPDATEFW)
+        result = _SYSTEM_TASK_LOST_ITEM_UPDATEFW;
+
+
+	return result;
+}
+
+//===============================================
+// Check System Task alive
+// ==============================================
+void CheckSystemTaskAlive()
+{
+    unsigned char lostId = CheckSystemTask(ShmSysConfigAndInfo->SysInfo.SystemPage);
+    if (lostId != 0) {
+        if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemTaskLost == NO) {
+           if (lostId == _SYSTEM_TASK_LOST_ITEM_MAIN)
+               log_error("System task lost (CSU). ");
+           else if (lostId == _SYSTEM_TASK_LOST_ITEM_EVCOMM)
+               log_error("System task lost (EVComm). ");
+//           else if (lostId == _SYSTEM_TASK_LOST_ITEM_PSUCOMM)
+//               PRINTF_FUNC("System task lost (PSU Task). ");
+           else if (lostId == _SYSTEM_TASK_LOST_ITEM_EVENTLOG)
+               log_error("System task lost (Event log). ");
+           else if (lostId == _SYSTEM_TASK_LOST_ITEM_PRIMARYCOMM)
+               log_error("System task lost (Primary). ");
+           else if (lostId == _SYSTEM_TASK_LOST_ITEM_LCMCONTROL)
+               log_error("System task lost (LCM Comm). ");
+           else if (lostId == _SYSTEM_TASK_LOST_ITEM_INTERCOMM)
+               log_error("System task lost (Internal Comm). ");
+           else if (lostId == _SYSTEM_TASK_LOST_ITEM_DOCOMM)
+               log_error("System task lost (Do Comm). ");
+           else if (lostId == _SYSTEM_TASK_LOST_ITEM_PRODUCTUTILS)
+               log_error("System task lost (ProcductUtils Comm). ");
+           else if (lostId == _SYSTEM_TASK_LOST_ITEM_UPDATEFW)
+               log_error("System task lost (Update FW) ");
+           ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemTaskLost = YES;
+        }
+    } else
+        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemTaskLost = NO;
+}
+
+
+int main(void)
+{
+    if (CreateAllCsuShareMemory() == FAIL) {
+        log_error("create share memory error");
+        return FAIL;
+    }
+
+    pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
+    pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
+    ShmOCPP16Data = (struct OCPP16Data *)GetShmOCPP16Data();
+    ShmSysConfigAndInfo = (struct SysConfigAndInfo *)GetShmSysConfigAndInfo();
+	ShmStatusCodeData = (struct StatusCodeData*)GetShmStatusCodeData();
+	ShmDcCommonData = (DcCommonInfo*)GetShmDcCommonData();
+    MappingGunChargingInfo("CheckSystem Task");
+    while(true)
+    {
+		sleep(3);
+      	for (uint8_t gun = 0; gun < pSysConfig->TotalConnectorCount; gun++) {
+    		pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gun);
+			if (pDcChargingInfo->SystemStatus == SYS_MODE_UPDATE )
+				continue;
+		}
+		if (ShmDcCommonData->DebugFlag == TRUE) {
+			continue;
+		}
+		CheckSystemTaskAlive();
+    }
+	return FAIL;
+}

+ 63 - 63
EVSE/Projects/DD360Tcci/Apps/ModuleChkSysTask/Module_ChkSysTask.h

@@ -1,63 +1,63 @@
-/*
- * CheckTask.h
- *
- *  Created on: 2021年9月2日
- *      Author: 7564
- */
-
-#ifndef CHECKTASK_H_
-#define CHECKTASK_H_
-
-#include 	<sys/timeb.h>
-#include 	<sys/types.h>
-#include 	<sys/ioctl.h>
-#include 	<sys/socket.h>
-#include 	<sys/ipc.h>
-#include 	<sys/shm.h>
-#include 	<sys/mman.h>
-#include 	<linux/wireless.h>
-#include 	<arpa/inet.h>
-#include 	<netinet/in.h>
-
-#include 	<unistd.h>
-#include 	<stdarg.h>
-#include    <stdio.h>      /*標準輸入輸出定義*/
-#include    <stdlib.h>     /*標準函數庫定義*/
-#include    <unistd.h>     /*Unix 標準函數定義*/
-#include    <fcntl.h>      /*檔控制定義*/
-#include    <termios.h>    /*PPSIX 終端控制定義*/
-#include    <errno.h>      /*錯誤號定義*/
-#include 	<string.h>
-#include 	<stdint.h>
-#include	<time.h>
-#include	<ctype.h>
-#include 	<ifaddrs.h>
-#include 	<math.h>
-#include 	<stdbool.h>
-#include 	<dirent.h>
-
-#define _SYSTEM_TASK_LOST_ITEM_MAIN         1
-#define _SYSTEM_TASK_LOST_ITEM_EVCOMM       2
-#define _SYSTEM_TASK_LOST_ITEM_EVENTLOG     3
-#define _SYSTEM_TASK_LOST_ITEM_PRIMARYCOMM  4
-#define _SYSTEM_TASK_LOST_ITEM_LCMCONTROL   5
-#define _SYSTEM_TASK_LOST_ITEM_INTERCOMM    6
-#define _SYSTEM_TASK_LOST_ITEM_DOCOMM       7
-#define _SYSTEM_TASK_LOST_ITEM_PRODUCTUTILS 8
-#define _SYSTEM_TASK_LOST_ITEM_UPDATEFW     9
-
-///*
-#define _SYSTEM_TASK_COUNT_MAIN             5
-#define _SYSTEM_TASK_COUNT_EVCOMM           2
-#define _SYSTEM_TASK_COUNT_INTERNALCOMM     2
-#define _SYSTEM_TASK_COUNT_EVENTLOGGING     1
-#define _SYSTEM_TASK_COUNT_PRIMARYCOMM      1
-#define _SYSTEM_TASK_COUNT_LCM              2
-#define _SYSTEM_TASK_COUNT_DOCOMM           1
-#define _SYSTEM_TASK_COUNT_PRODUCEUTILS     1
-#define _SYSTEM_TASK_COUNT_UPDATEFW         1
-//*/
-
-unsigned char CheckSystemTask(unsigned char systemPage);
-
-#endif /* CHECKSYSTEMTASK_H_ */
+/*
+ * CheckTask.h
+ *
+ *  Created on: 2021年9月2日
+ *      Author: 7564
+ */
+
+#ifndef CHECKTASK_H_
+#define CHECKTASK_H_
+
+#include 	<sys/timeb.h>
+#include 	<sys/types.h>
+#include 	<sys/ioctl.h>
+#include 	<sys/socket.h>
+#include 	<sys/ipc.h>
+#include 	<sys/shm.h>
+#include 	<sys/mman.h>
+#include 	<linux/wireless.h>
+#include 	<arpa/inet.h>
+#include 	<netinet/in.h>
+
+#include 	<unistd.h>
+#include 	<stdarg.h>
+#include    <stdio.h>      /*標準輸入輸出定義*/
+#include    <stdlib.h>     /*標準函數庫定義*/
+#include    <unistd.h>     /*Unix 標準函數定義*/
+#include    <fcntl.h>      /*檔控制定義*/
+#include    <termios.h>    /*PPSIX 終端控制定義*/
+#include    <errno.h>      /*錯誤號定義*/
+#include 	<string.h>
+#include 	<stdint.h>
+#include	<time.h>
+#include	<ctype.h>
+#include 	<ifaddrs.h>
+#include 	<math.h>
+#include 	<stdbool.h>
+#include 	<dirent.h>
+
+#define _SYSTEM_TASK_LOST_ITEM_MAIN         1
+#define _SYSTEM_TASK_LOST_ITEM_EVCOMM       2
+#define _SYSTEM_TASK_LOST_ITEM_EVENTLOG     3
+#define _SYSTEM_TASK_LOST_ITEM_PRIMARYCOMM  4
+#define _SYSTEM_TASK_LOST_ITEM_LCMCONTROL   5
+#define _SYSTEM_TASK_LOST_ITEM_INTERCOMM    6
+#define _SYSTEM_TASK_LOST_ITEM_DOCOMM       7
+#define _SYSTEM_TASK_LOST_ITEM_PRODUCTUTILS 8
+#define _SYSTEM_TASK_LOST_ITEM_UPDATEFW     9
+
+///*
+#define _SYSTEM_TASK_COUNT_MAIN             5
+#define _SYSTEM_TASK_COUNT_EVCOMM           2
+#define _SYSTEM_TASK_COUNT_INTERNALCOMM     2
+#define _SYSTEM_TASK_COUNT_EVENTLOGGING     1
+#define _SYSTEM_TASK_COUNT_PRIMARYCOMM      1
+#define _SYSTEM_TASK_COUNT_LCM              2
+#define _SYSTEM_TASK_COUNT_DOCOMM           1
+#define _SYSTEM_TASK_COUNT_PRODUCEUTILS     1
+#define _SYSTEM_TASK_COUNT_UPDATEFW         1
+//*/
+
+unsigned char CheckSystemTask(unsigned char systemPage);
+
+#endif /* CHECKSYSTEMTASK_H_ */

+ 3292 - 3271
EVSE/Projects/DD360Tcci/Apps/ModuleDoComm/DoComm.c

@@ -1,3271 +1,3292 @@
-#include <stdio.h>
-#include <stdlib.h>
-#include <stdint.h>
-#include <stdarg.h>
-#include <string.h>
-#include <stdbool.h>
-
-#include <sys/time.h>
-#include <sys/timeb.h>
-#include <sys/socket.h>
-#include <sys/types.h>
-#include <sys/ipc.h>
-#include <sys/shm.h>
-
-#include <arpa/inet.h>
-#include <netinet/in.h>
-
-#include <assert.h>
-#include <time.h>
-#include <errno.h>
-#include <unistd.h>
-#include <signal.h>
-
-#include "../Log/log.h"
-#include "../ShareMemory/shmMem.h"
-#include "../Define/define.h"
-#include "../Config.h"
-#include "../SelectGun/SelectGun.h"
-#include "../timeout.h"
-#include "../DataBase/DataBase.h"
-#include "DoComm.h"
-
-//------------------------------------------------------------------------------
-static DoCommGblData gDoCommGblData             = {0};
-static MoreInfoReq gMoreInfoReq[2]              = {0};
-//static ChangePageReq gPageReq[2]                = {0};
-static ConnectorActReqVar gConnectorActReq[2]   = {0};
-static struct SysConfigData *pSysConfig         = NULL;
-static struct SysInfoData *pSysInfo             = NULL;
-static struct WARNING_CODE_INFO *pSysWarning    = NULL;
-static struct AlarmCodeData *pAlarmCode         = NULL;
-static struct PsuData *ShmPsuData               = NULL;
-static struct OCPP16Data *ShmOCPP16Data         = NULL;
-static struct PrimaryMcuData *ShmPrimaryMcuData = NULL;
-static SelectGunInfo *ShmSelectGunInfo          = NULL;
-static DcCommonInfo *ShmDcCommonData            = NULL;
-
-//static struct ChargingInfoData  *ChargingData[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY]
-static struct ChargingInfoData *pDcChargingInfo = NULL;
-static struct timeb             gRegTimeUp[2][MAX_REGISTER_NUM] = {0};
-static struct WARNING_CODE_INFO gPreSysWarningInfo = {0};
-
-// Hexdump
-char old_Hexdump[10240];
-static uint8_t RemoteStartNoIDState = NO;
-static uint8_t ReservationState[2] = {0};
-static char ReservationIdTag[2][32];
-//static uint8_t DeductResultReq[2] = {0};
-static int LineStatusCode[2] = {0};
-static unsigned int LedIntensity = 0;
-static int TimeZoneOffset = 0;
-uint8_t _isplugin[2] = { 0 };
-//------------------------------------------------------------------------------
-static void removeFaultCodeToBuf(uint8_t *Code);
-static void addFaultCodeToBuf(uint8_t *Code);
-static int readMiscCommand(int fd, uint8_t id);
-static int writeCsuModuleVersion(int fd);
-static int writeGroundFaultDetection(int fd, uint8_t status, uint8_t id);
-
-//------------------------------------------------------------------------------
-//--- Common function ---
-//------------------------------------------------------------------------------
-void GetClockTime(struct timespec *_now_time, void *null)
-{
-    clock_gettime(CLOCK_MONOTONIC, _now_time);
-}
-
-static 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;
-}
-static void systemPageRestoreInit(void)
-{
-    int is_idle = TRUE;
-    int gunIndex;
-    for (gunIndex = 0; gunIndex < pSysConfig->TotalConnectorCount; gunIndex++) {
-        pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(gunIndex);
-        // 檢查電樁狀態是否為idle狀態
-        if ((pDcChargingInfo->SystemStatus >= S_AUTHORIZING &&
-            pDcChargingInfo->SystemStatus <= S_RESERVATION) ||
-            (pDcChargingInfo->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
-                pDcChargingInfo->SystemStatus <= S_CCS_PRECHARGE_ST0)) {
-            is_idle = FALSE;
-        }
-    }
-    if (is_idle)
-        pSysInfo->SystemPage = _PAGE_IDLE;
-    else
-        pSysInfo->SystemPage = _PAGE_SELECT_GUN;
-}
-/**
- * [hexdump : check data]
- * @Author   Jerry
- * @DateTime 2018-12-21
- * @param    p          [description]
- * @param    size       [description]
- */
-static void Hexdump(const void *p, size_t size)
-{
-    const uint8_t *c = p;
-    char message[10240] = {0};
-    uint32_t i = 0;
-    uint32_t message_len = 0;
-
-    assert(p);
-
-    //printf("Dumping %u bytes from %p:\n", size, p);
-    message_len += sprintf(&message[message_len], "\nDumping %u bytes from %p:\n",  (unsigned int)size, p);
-
-    while (size > 0) {
-        for (i = 0; i < 16; i++) {
-            if (i < size) {
-                //printf("%02x ", c[i]);
-                message_len += sprintf(&message[message_len], "%02x ", c[i]);
-            } else {
-                //printf("   ");
-                message_len += sprintf(&message[message_len], "   ");
-            }
-        }
-
-        for (i = 0; i < 16; i++) {
-            if (i < size) {
-                //printf("%c", c[i] >= 32 && c[i] < 127 ? c[i] : '.');
-                message_len += sprintf(&message[message_len], "%c", c[i] >= 32 && c[i] < 127 ? c[i] : '.');
-            } else {
-                //printf(" ");
-                message_len += sprintf(&message[message_len], " ");
-            }
-        }
-
-        //printf("\n");
-        message_len += sprintf(&message[message_len], "\n");
-        c += 16;
-
-        if (size <= 16) {
-            break;
-        }
-
-        size -= 16;
-    }
-
-    //message_len += sprintf(&message[message_len], "\n");
-    if( strcmp(old_Hexdump,message) != EQUAL ) {
-        log_info("%s", message);
-        strcpy(old_Hexdump,message);
-    }
-}
-
-static int string2ByteArray(char *input, uint8_t *output)
-{
-    int loop = 0;
-    int i = 0;
-
-    while (input[loop] != '\0') {
-        output[i++] = input[loop++];
-    }
-    output[loop] = '\0';
-
-    return loop + 1;
-}
-
-int string2Date(char* input, uint8_t* output)
-{
-    int loop = 0;
-    int i = 0;
-
-    while (input[loop] != '\0') {
-        loop++;
-    }
-    loop++;
-
-    while (input[loop] != '\0') {
-        output[i++] = input[loop++];
-    }
-    output[loop] = '\0';
-
-    return loop + 1;
-}
-static void unixSocketSigPipeHandle(int sig)
-{
-    //log_error("socket packet error %x", sig);
-}
-
-static void InitSocketSigPipe(void)
-{
-    struct sigaction action;
-
-    action.sa_handler = unixSocketSigPipeHandle;
-    sigemptyset(&action.sa_mask);
-    action.sa_flags = 0;
-    sigaction(SIGPIPE, &action, NULL);
-}
-
-//------------------------------------------------------------------------------
-static void setTcpStatus(uint8_t setValue)
-{
-    pAlarmCode->AlarmEvents.bits.DisconnectedFromDo = setValue;
-}
-
-//------------------------------------------------------------------------------
-//--- TCP socket function ---
-//------------------------------------------------------------------------------
-static int sendTcpSocket(int fd, uint8_t *data, uint16_t dataLen)
-{
-    int size = -1;
-    if (ShmDcCommonData->netdump) {
-        printf("\nTx Data:\t");
-        for(int i = 0 ; i < dataLen ; i++)
-            printf("[0x%2x] ",data[i]);
-    }
-    size = send(fd, data, dataLen , 0);
-    if ((size < 0) || (errno == EAGAIN)) {
-        if (size < 0) {
-            log_error("Send Socket Size = %d, EAGAIN error %d:%s", size, errno, strerror(errno));
-        }
-    }
-
-    return size;
-}
-
-static int recvTcpSocket(int fd, uint8_t *data, uint16_t dataLen)
-{
-    int size = -1;
-    uint8_t *pdata = (uint8_t *)data;
-    if (ShmDcCommonData->netdump) {
-        printf("\nRx Data:\t");
-        for(int i = 0 ; i < dataLen ; i++)
-            printf("[0x%2x] ",data[i]);
-    }
-    size = recv(fd, pdata, dataLen, MSG_WAITALL);
-    if ((errno == EAGAIN) || (size < 0)) {
-        log_error("Receive Socket Size = %d, EAGAIN error %d:%s", size, errno, strerror(errno));
-    }
-
-    return size;
-}
-
-static int getSO_ERROR(int fd)
-{
-    int err = 1;
-    socklen_t len = sizeof err;
-
-    if (-1 == getsockopt(fd, SOL_SOCKET, SO_ERROR, (char *)&err, &len)) {
-        log_error("getSO_ERROR");
-    }
-
-    if (err) {
-        errno = err;        // set errno to the socket SO_ERROR
-    }
-
-    return err;
-}
-
-static void closeSocket(int fd)        // *not* the Windows closesocket()
-{
-    if (fd < 0) {
-        return;
-    }
-
-    getSO_ERROR(fd); // first clear any errors, which can cause close to fail
-    if (shutdown(fd, SHUT_RDWR) < 0) { // secondly, terminate the 'reliable' delivery
-        if (errno != ENOTCONN && errno != EINVAL) { // SGI causes EINVAL
-            log_info("shutdown");
-        }
-    }
-
-    if (close(fd) < 0) { // finally call close()
-        log_info("client socket close");
-    }
-}
-
-static int doCommConnToServer(void)
-{
-    struct sockaddr_in dest;
-    struct timeval tv;
-    int flag;
-    int TcpSock = 0;
-
-    //if (TcpSock > 0) {
-    //    close(TcpSock);
-    //}
-
-    if ((TcpSock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
-        log_error("Open TCP socket NG");
-        return -1;
-    }
-
-    //flag = fcntl (TcpSock, F_GETFL, 0);
-    //if (flag >= 0) {
-    //    flag |= O_NONBLOCK;
-    //    fcntl(TcpSock, F_SETFL, flag );
-    //}
-
-    tv.tv_sec = 3;
-    tv.tv_usec = 0;
-    setsockopt(TcpSock, SOL_SOCKET,  SO_RCVTIMEO, &tv, sizeof(struct timeval)); //設定等待3s
-    setsockopt(TcpSock, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(struct timeval));  //設定傳送3s
-    flag = 1;
-    setsockopt(TcpSock, SOL_SOCKET, MSG_NOSIGNAL, &flag, sizeof(flag));
-
-    memset(&dest, 0, sizeof(dest));
-    dest.sin_family = AF_INET;
-    dest.sin_port = htons(DoTcpPort);
-    inet_aton(DoIPAddress, (struct in_addr *) &dest.sin_addr.s_addr);
-
-    if (connect(TcpSock, (struct sockaddr *) &dest, sizeof(dest)) != 0) {
-        close(TcpSock);
-        return -1;
-    }
-
-    return TcpSock;
-}
-
-//------------------------------------------------------------------------------
-//--- Audi select gun ---
-//------------------------------------------------------------------------------
-static void clearPricesInfo(uint8_t id)
-{
-    memset(&ShmSelectGunInfo->PricesInfo[id], 0, sizeof(PricesInfo));
-    ShmSelectGunInfo->PricesInfo[id].Balance = FAIL_BALANCE_PRICES;
-}
-
-static void ClearAuthorizedFlag(void)
-{
-    ShmOCPP16Data->SpMsg.bits.AuthorizeConf = NO;
-    pSysInfo->AuthorizeFlag = NO;
-}
-
-static void ClearDetectPluginFlag(int gunIndex)
-{
-    //pSysInfo->WaitForPlugit = NO;
-    ShmDcCommonData->pGunInfo[gunIndex].WaitForPlugit = NO;
-}
-
-static bool isDetectPlugin(int gunIndex)
-{
-    if (ShmDcCommonData->pGunInfo[gunIndex].WaitForPlugit == YES) {
-        return true;
-    }
-    /*
-    if (pSysInfo->WaitForPlugit == YES) {
-        return YES;
-    }
-    */
-    return NO;
-}
-
-static void destroySelectGun(uint8_t curGun)
-{
-    uint8_t i = 0;
-    uint8_t totalGun = pSysConfig->TotalConnectorCount;
-
-    if (curGun == DESTROY_ALL_SEL) {
-        ShmSelectGunInfo->SelGunInfo.RightGun = SEL_GUN_RELEASE;
-        ShmSelectGunInfo->SelGunInfo.LeftGun = SEL_GUN_RELEASE;
-
-        for (i = 0; i < totalGun; i++) {
-            pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(i);
-
-            pDcChargingInfo->TimeoutFlag = Timeout_None;
-            clearPricesInfo(i);
-        }
-        pSysInfo->CurGunSelected = 0;
-        strcpy((char *)pSysConfig->UserId, "");
-    }
-
-    //for charging timeout or complete
-    if ((curGun == LEFT_GUN_NUM) && (ShmSelectGunInfo->SelGunInfo.LeftGun != SEL_GUN_RELEASE)) {
-        ShmSelectGunInfo->SelGunInfo.LeftGun = SEL_GUN_RELEASE;
-        if (ShmOCPP16Data->SpMsg.bits.AuthorizeConf != NO) {
-            ClearAuthorizedFlag();
-        }
-        clearPricesInfo(curGun);
-    }
-
-    if ((curGun == RIGHT_GUN_NUM) && (ShmSelectGunInfo->SelGunInfo.RightGun != SEL_GUN_RELEASE)) {
-        if (ShmOCPP16Data->SpMsg.bits.AuthorizeConf != NO) {
-            ClearAuthorizedFlag();
-        }
-
-        clearPricesInfo(curGun);
-    }
-}
-
-static void setConfirmSelGun(uint8_t selGun)
-{
-    if (selGun == LEFT_GUN_NUM && ShmSelectGunInfo->SelGunInfo.LeftGun == SEL_GUN_RELEASE) {
-        ShmSelectGunInfo->SelGunInfo.LeftGun = SEL_GUN_CONFIRM;
-        //printf("confirmSelGun left");
-    } else if (selGun == RIGHT_GUN_NUM && ShmSelectGunInfo->SelGunInfo.RightGun == SEL_GUN_RELEASE) {
-        ShmSelectGunInfo->SelGunInfo.RightGun = SEL_GUN_CONFIRM;
-        //printf("confirmSelGun right");
-    }
-}
-
-//------------------------------------------------------------------------------
-//--- DoComm function ---
-//------------------------------------------------------------------------------
-static int compareOpcode(uint8_t opCode)
-{
-    if (opCode != OP_WAIT_RESPONSE) {
-        //log_error("response operative code fail");
-        return FAIL;
-    }
-
-    return PASS;
-}
-
-static int compareResult(uint8_t result)
-{
-    if (result != COMMAND_RESULT_OK) {
-        //log_error("response result fail");
-        return FAIL;
-    }
-
-    return PASS;
-}
-
-static int compareRegister(uint8_t srcReg, uint8_t destReg)
-{
-    if (srcReg != destReg) {
-        //log_error("response register fail");
-        return FAIL;
-    }
-
-    return PASS;
-}
-
-static float transPricesUnit(int prices)
-{
-    //printf("prices = %.2f", prices * PRICES_UNIT);
-    return (prices * PRICES_UNIT);
-}
-
-static void clearMiscCommand(void)
-{
-    gDoCommGblData.MiscCmd = 0;
-}
-int timecmp(uint8_t* time1, uint8_t* time2)
-{
-    for (int i = 0; i < strlen(time1); i++) {
-        if (time1[i] != time2[i]) {
-            return FALSE;
-        }
-    }
-    return TRUE;
-}
-static int qrCodeUrlInfoHandle(uint8_t *data)
-{
-    //int len = 0;
-    //char cmdBuf[128] = {0};
-    char localTime[128] = {0};
-    uint16_t timeLen = 0;
-    struct timeb SeqEndTime;
-    struct tm *tm;
-    char _setTime[50];
-    uint8_t cmdBuf[128];
-    int is_idle = TRUE;
-    if ((char *)&data[0] == '\0') {
-        log_error("QR code date error");
-        return FAIL;
-    }
-
-    //get local system time
-    ftime(&SeqEndTime);
-    SeqEndTime.time = time(NULL);
-    tm = localtime(&SeqEndTime.time);
-    timeLen = sprintf(localTime, "%04d-%02d-%02d %02d:%02d",
-                      tm->tm_year + 1900,
-                      tm->tm_mon + 1,
-                      tm->tm_mday,
-                      tm->tm_hour,
-                      tm->tm_min);
-    memset(pSysConfig->SystemId, '\0', sizeof(pSysConfig->SystemId));
-    string2ByteArray((char *)data, (uint8_t *)pSysConfig->SystemId);
-    //log_info("Data = %s SystemId = %s",data, pSysConfig->SystemId);
-    //copy QR code string
-    if (strncmp((char *)localTime, (char *)&data[0], timeLen - 2) != 0) {
-        // 充電槍IDLE時才更新系統時間
-        for (int i = 0; i < pSysConfig->TotalConnectorCount; i++) {
-            pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(i);
-            if (pDcChargingInfo->SystemStatus != S_IDLE)
-                is_idle = FALSE;
-        }
-
-        string2Date((char*)data, (uint8_t*)_setTime);
-        //printf("SystemId = %s", pSysConfig->SystemId);
-        if (!timecmp(localTime, _setTime) && is_idle) {
-            //log_info("Set Timer:%s", _setTime);
-            sprintf((char*)cmdBuf, "date -u -s \"%s\" >> /dev/null &", _setTime);
-            system((char*)cmdBuf);
-            system("hwclock -w -u");
-            system("hwclock -s");
-        }
-        
-    }
-    sprintf(ShmDcCommonData->PresentTime, "%04d/%02d/%02d",
-                      tm->tm_year + 1900,
-                      tm->tm_mon + 1,
-                      tm->tm_mday);
-
-    //if ((char *)&data[len] == '\0') {
-    //    log_error("power cabinet system date error");
-    //    return FAIL;
-    //}
-
-    //set system date
-    //if (strncmp((char *)localTime, (char *)&data[len], timeLen) != 0) {
-    //    sprintf(cmdBuf, "date -s \"%s\" >> /dev/null", (char *)&data[len]);
-    //    system(cmdBuf);
-    //    log_info("local time = %s, data time = %s", localTime, (char *)&data[len]);
-    //    ShmOCPP16Data->MsMsg.bits.ResetReq = YES;
-    //    strcpy((char *)ShmOCPP16Data->Reset.Type, "Soft");
-    //    sleep(3);
-    //    //gDoCommGblData.DisConnCount = CHECK_NETWORK_FAIL_COUNT;
-    //}
-
-    return PASS;
-}
-
-static int updateFirmwareHandle(uint8_t *imgName)
-{
-    int ret = PASS;
-    char cmdBuf[1024] = {0};
-
-    sprintf(cmdBuf, "/mnt/%s", imgName);
-    log_info("Program ready to check file %s", cmdBuf);
-    if ( access(cmdBuf, F_OK) != -1) {
-        log_info("File '%s' exist.", cmdBuf);
-        pSysInfo->FirmwareUpdate = YES;
-    } else {
-        log_info("File '%s' doesn't exist.", cmdBuf);
-        ret = FAIL;
-    }
-
-#if 0
-    char cmdBuf[1024] = {0};
-    int status = 0;
-
-    system("touch ./tftpUpdate.sh"); //創建shell
-    sprintf(cmdBuf, "echo tftp -gr %s -l %s/%s %s; > ./tftpUpdate.sh",
-            imgName,
-            IMAGE_FILE_PATH,
-            imgName,
-            DoIPAddress);
-    system("chmod +x ./tftpUpdate.sh"); //修改權限
-
-    status = system("sh tftpUpdate.sh"); //執行shell
-    if (-1 == status) {
-        printf("system error!");
-    } else {
-        printf("exit status value = [0x%x]", status);
-
-        if (WIFEXITED(status)) {
-            if (0 == WEXITSTATUS(status)) {
-                printf("run shell script successfully.");
-                pSysInfo->FirmwareUpdate = YES;
-            } else {
-                printf("run shell script fail, script exit code: %d", WEXITSTATUS(status));
-            }
-        } else {
-            printf("exit status = [%d]", WEXITSTATUS(status));
-        }
-    }
-
-    system("rm -rf ./tftpUpdate.sh"); //刪除shell
-#endif //0
-
-    return ret;
-}
-
-static int miscCommandHandle(uint8_t dataLen, uint8_t plugNum, uint8_t *data)
-{
-    int ret = PASS;
-    uint8_t i = 0, j = 0;
-    uint8_t cmdCount = (dataLen / 6);
-    uint16_t cmd = 0;
-    uint32_t value = 0;
-    float prices = 0;
-    MiscCommand *pMiscCmd = NULL;
-
-    if (cmdCount < 1) {
-        gDoCommGblData.MiscCmd = 0;
-        //printf("cmdCount fail = %d, data len = %d", cmdCount, dataLen);
-        return FAIL;
-    }
-
-    for (i = 0; i < cmdCount; i++) {
-        pMiscCmd = (MiscCommand *)data + i;
-        cmd = ntohs(pMiscCmd->CMD);
-        value = ntohl(*((uint32_t *)&pMiscCmd->Value[0]));
-        //log_info("misc command = %x, value = %d", cmd, value);
-
-        switch (cmd) {
-        //--- Execute parameter ---
-        case MISC_CMD_CONNECOTOR_TIMEOUT:
-            ShmSelectGunInfo->RemoteSetup.ConnectionTimeout = value;
-            log_info("connection timeout = %d", ShmSelectGunInfo->RemoteSetup.ConnectionTimeout);
-            clearMiscCommand();
-            break;
-
-        case MISC_CMD_OPERATIVE_STATE:
-            if ((value > YES) || (value < NO)) {
-                if (plugNum == 1) {
-                    clearMiscCommand();
-                }
-                break;
-            }
-
-            log_info("change availability plugNum = %d, value = %d", plugNum, value);
-            ShmOCPP16Data->CsMsg.bits[plugNum].ChangeAvailabilityReq = YES;
-            if (value == YES) {
-                strcpy((char *)ShmOCPP16Data->ChangeAvailability[plugNum].Type, "Operative");
-            } else if (value == NO) {
-                strcpy((char *)ShmOCPP16Data->ChangeAvailability[plugNum].Type, "Inoperative");
-            }
-
-            if (plugNum == 1) {
-                clearMiscCommand();
-            }
-            break;
-
-        case MISC_CMD_DEFAULT_PRICES:
-            prices = transPricesUnit((int)value);
-            log_info("default prices = %.2f", prices);
-            if (prices > 0)
-                ShmDcCommonData->ChargingRate = prices;
-            //pSysConfig->BillingData.isBilling = YES;
-            for (j = 0; j < 24; j++) {
-                pSysConfig->BillingData.Fee[j] = prices;
-            }
-
-            clearMiscCommand();
-            break;
-
-        case MISC_CMD_DEFAULT_CURRENCY:
-            if (value < 0) {
-                clearMiscCommand();
-                return FAIL;
-            }
-
-            //log_info("default currency = %s%c", (uint8_t *)Currency[value]);
-            log_info("default currency = %s", (uint8_t *)GetCurrency(value));
-            pSysConfig->BillingData.Currency = value;
-            clearMiscCommand();
-            break;
-
-        case MISC_CMD_ACCOUNT_BALANCE:
-            if (pSysInfo->CurGunSelected != (plugNum)) {
-                clearMiscCommand();
-                break;
-            }
-
-            ShmSelectGunInfo->PricesInfo[plugNum].Balance = transPricesUnit((int)value);
-            log_info("%d misc balance = %.2f", plugNum, ShmSelectGunInfo->PricesInfo[plugNum].Balance);
-            clearMiscCommand();
-            break;
-
-        case MISC_CMD_BACKEND_STATUS :
-            if (ShmSelectGunInfo->EthDevStatus.Backend != value) {
-                if (value == 0 || value == 2) {
-                    log_info("!!!!!!!!!!!!!! Backend Disconnect !!!!!!!!!!!!!!");
-                } else {
-                    log_info("!!!!!!!!!!!!!! Backend Connect !!!!!!!!!!!!!");
-                }
-            }
-            ShmSelectGunInfo->EthDevStatus.Backend = value;
-
-            break;
-
-        case MISC_CMD_ETHERNET_STATUS :
-            ShmSelectGunInfo->EthDevStatus.Ethernet = value;
-            break;
-
-        case MISC_CMD_WIFI_STATUS :
-            ShmSelectGunInfo->EthDevStatus.Wifi = value;
-            break;
-
-        case MISC_CMD_4G_STATUS :
-            ShmSelectGunInfo->EthDevStatus.FourG = value;
-            break;
-
-        case MISC_CMD_BILLING_INFO:
-            pSysConfig->BillingData.isBilling = value;
-            break;
-
-        case MISC_CMD_WEB_STOP_CHARGING:
-            pSysConfig->StopChargingByButton = value;
-            break;
-
-        //--- Control Dispenser ---
-        case MISC_CMD_HARDWARE_REBOOT:
-            if (value != YES) {
-                clearMiscCommand();
-                break;
-            }
-
-            log_info("Hardware reboot");
-            ShmOCPP16Data->MsMsg.bits.ResetReq = YES;
-            strcpy((char *)ShmOCPP16Data->Reset.Type, "Hard");
-            clearMiscCommand();
-            break;
-
-        case MISC_CMD_SOFTWARE_RESTART:
-            if (value != YES) {
-                clearMiscCommand();
-                break;
-            }
-
-            clearMiscCommand();
-            log_info("Software reboot");
-            ShmOCPP16Data->MsMsg.bits.ResetReq = YES;
-            strcpy((char *)ShmOCPP16Data->Reset.Type, "Soft");
-            break;
-
-        case MISC_CMD_REMOTE_START_CHARGING:
-            if (value != YES) {
-                if (plugNum == 1) {
-                    clearMiscCommand();
-                }
-                break;
-            }
-            log_info("Remote start charging plugNum = %d", plugNum);
-
-            //pSysInfo->CurGunSelected = (plugNum);
-            //pSysInfo->CurGunSelectedByAc = NO_DEFINE;
-            if (ShmDcCommonData->pGunInfo[plugNum].ParkingStatus) {
-                log_info("Gun%d is in the Parking status can't access Remote Start",plugNum);
-                break;
-            }
-            setConfirmSelGun(plugNum);
-
-            ShmOCPP16Data->CsMsg.bits[plugNum].RemoteStartTransactionReq = YES;
-            ShmSelectGunInfo->PricesInfo[plugNum].Balance = 0.00;
-
-            clearMiscCommand();
-            break;
-
-        case MISC_CMD_REMOTE_STOP_CHARGING:
-            if (value != YES) {
-                if (plugNum == 1) {
-                    clearMiscCommand();
-                }
-                break;
-            }
-
-            strcpy((char *)pSysConfig->UserId, "");
-            ClearDetectPluginFlag(plugNum);
-            //pSysInfo->SystemPage = _LCM_SELECT_GUN;
-            GetClockTime(&pSysInfo->SystemTimeoutTimer, NULL);
-            pSysInfo->SystemTimeoutFlag = Timeout_None;
-            destroySelectGun(plugNum);
-
-            clearMiscCommand();
-            break;
-
-        case MISC_CMD_REMOTE_UNLOCK:
-            if (value != YES) {
-                if (plugNum == 1) {
-                    clearMiscCommand();
-                }
-                break;
-            }
-
-            if (isDetectPlugin(plugNum) == YES) {
-                ClearDetectPluginFlag(plugNum);
-                strcpy((char *)pSysConfig->UserId, "");
-                //pSysInfo->SystemPage = _LCM_SELECT_GUN;
-                GetClockTime(&pSysInfo->SystemTimeoutTimer, NULL);
-                pSysInfo->SystemTimeoutFlag = Timeout_None;
-                destroySelectGun(plugNum);
-            } else {
-                pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(plugNum);
-
-                pDcChargingInfo->StopChargeFlag = POWER_CABINET_STOP_CHARGING;
-            }
-            break;
-        case MISC_CMD_AUTH_DISABLE:
-            pSysConfig->AuthorisationMode = value;
-            log_info("Auto Authorize Disable:%d", pSysConfig->AuthorisationMode);
-            //clearMiscCommand();
-        	break;
-        case MISC_CMD_EVCCID_ENABLE:
-            pSysConfig->isAuthrizeByEVCCID = value;
-            log_info("Authorize By EVCCID:%d",pSysConfig->isAuthrizeByEVCCID);
-            //clearMiscCommand();
-        	break;
-        case MISC_CMD_RESERVATION:
-            if(value != YES)
-            {
-                break;
-            }
-            gMoreInfoReq[plugNum].bits.ReservationReq = YES;
-            break;
-        case MISC_CMD_CHANGE_LCM_PAGE:
-            if(value == LCM_PAGE_REMOTE_START_NO_ID)
-            {
-                gMoreInfoReq[plugNum].bits.RemoteStartNoID = YES;
-            }
-            /*
-            if(value == LCM_PAGE_JOIN_LINE)
-            {
-                if(!gPageReq[plugNum].bits.JoinLine)
-                {
-                    log_info("Gun %d JoinLine page is trigger", plugNum);
-                }
-                gPageReq[plugNum].bits.JoinLine = YES;
-            }
-            if(value == LCM_PAGE_PAYMENT_SWITCH)
-            {
-                if(!gPageReq[plugNum].bits.PaymentSwitch)
-                {
-                    log_info("Gun %d PaymentSwitch page is trigger", plugNum);
-                }
-                gPageReq[plugNum].bits.PaymentSwitch = YES;
-            }*/
-            break;
-        case MISC_CMD_QR_CODE_REQ:
-            break;
-        case MISC_CMD_STATION_INFO_REQ:
-            if(value != YES)
-            {
-                break;
-            }
-            gMoreInfoReq[plugNum].bits.StationInfoReq = YES;
-            break;
-        case MISC_CMD_FINAL_COST_REQ:
-            if(value != YES)
-            {
-                break;
-            }
-            gMoreInfoReq[plugNum].bits.FinalCostReq = YES;
-            break;
-        case MISC_CMD_LINE_STATUS_REQ:
-            LineStatusCode[plugNum] = value;
-            if (ShmDcCommonData->pGunInfo[plugNum].ParkingStatus) {
-                ShmDcCommonData->ParkingInfo[plugNum].LineStatus = value;
-                log_info("Gun %d Line Status Code: %d", plugNum, LineStatusCode[plugNum]);
-                if (ShmDcCommonData->ParkingInfo[plugNum].LineStatus != value &&
-                    strcmp((char*)ShmDcCommonData->ParkingInfo[plugNum].pCreditCard.ApprovalNo, "") != 0) {
-                    UpdateDeductInfoStatus(plugNum,&ShmDcCommonData->ParkingInfo[plugNum]);
-                }
-            } else {
-                ShmDcCommonData->TransactionInfo[plugNum].LineStatus = value;
-                log_info("Gun %d Line Status Code: %d", plugNum, LineStatusCode[plugNum]);
-                if (ShmDcCommonData->TransactionInfo[plugNum].LineStatus != value &&
-                    strcmp((char*)ShmDcCommonData->TransactionInfo[plugNum].pCreditCard.ApprovalNo, "") != 0) {
-                    UpdateDeductInfoStatus(plugNum,&ShmDcCommonData->TransactionInfo[plugNum]);
-                }
-            }
-            break;
-        case MISC_CMD_LED_INTENSITY:
-            LedIntensity = value;
-            log_info("Led Intensity: %d", LedIntensity);
-            break;
-        case MISC_CMD_TIME_OFFSET:
-            TimeZoneOffset = value;
-            log_info("Time Zone Offset: %d", TimeZoneOffset);
-            ShmDcCommonData->TZOffset = TimeZoneOffset;
-            /*
-            if (TimeZoneOffset == 480) {
-                system("export TZ=CST-8");
-                log_info("Set Time Zone CST 8");
-            }
-            */
-            break;
-        case MISC_CMD_CHARGING_BILL:
-            if (value != YES)
-            {
-                break;
-            }
-            gMoreInfoReq[plugNum].bits.ChargingBill = YES;
-            ShmDcCommonData->PriceBill.gunIndex = plugNum;
-            break;
-        case MISC_CMD_PAKING_PRICES:
-            prices = transPricesUnit((int)value);
-            log_info("parking prices = %.2f", prices);
-            if (prices > 0)
-                ShmDcCommonData->ParkingRate = prices;
-            break;
-        case MISC_CMD_PARKING_STATUS:
-            if (gMoreInfoReq[plugNum].bits.ParkingReq != value) {
-                if (value == 0x0001 && pSysInfo->CurGunSelected == plugNum &&
-                    (pSysInfo->SystemPage >= _PAGE_BILL && pSysInfo->SystemPage <= _PAGE_CHARGING ||
-                    pSysInfo->SystemPage ==  _PAGE_DONATE_RIGHT)) {
-                    //log_info("Gun%d already enter charging operate. Don't Enter Parking mode!",plugNum);
-                    return FAIL;
-                }
-                if (value) {
-                    ShmDcCommonData->pGunInfo[plugNum].isParking = TRUE;
-                } else {
-                    log_info("Clear Parking Bill information");
-                    memset(&ShmDcCommonData->ParkingInfo[plugNum], 0, sizeof(RecordTransactionInfo));
-                    ShmDcCommonData->pGunInfo[plugNum].GetParkingBill = FALSE;
-                }
-                log_info("Parking Request %s",value ? "ON" : "OFF");
-            }
-            gMoreInfoReq[plugNum].bits.ParkingReq = value;
-            break;
-        default:
-            clearMiscCommand();
-            break;
-        }
-        usleep(128);
-    }
-
-    return ret;
-}
-void AddDispenserReq(uint8_t* buff, MiscCommand* req)
-{
-    buff[0] = (req->CMD >> 8) & 0xFF;
-    buff[1] = req->CMD & 0xFF;
-
-    buff[2] = req->Value[0];
-    buff[3] = req->Value[1];
-    buff[4] = req->Value[2];
-    buff[5] = req->Value[3];
-}
-
-
-static int chargingbillHandle(uint8_t* data, uint8_t gunIndex)
-{
-
-    ChargingBillInfo* pBillInfo = (ChargingBillInfo*)&data[0];
-    pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(gunIndex);
-
-    ShmDcCommonData->PriceBill.TotalCost = transPricesUnit(ntohl(pBillInfo->TotalCost));
-    ShmDcCommonData->PriceBill.Balance = transPricesUnit(ntohl(pBillInfo->Balance));
-    ShmDcCommonData->PriceBill.Discount = transPricesUnit(ntohl(pBillInfo->Discount));
-    ShmDcCommonData->PriceBill.TransactionId = ntohl(pBillInfo->Transaction);
-    ShmDcCommonData->PriceBill.EnergyCost = transPricesUnit(ntohl(pBillInfo->EnergyCost));
-    ShmDcCommonData->PriceBill.ParkingFee = transPricesUnit(ntohl(pBillInfo->ParkingFee));
-    pBillInfo->RemainAmount = ntohl(pBillInfo->RemainAmount);
-    memcpy((char*)&ShmDcCommonData->PriceBill.RemainAmount, (char*)&pBillInfo->RemainAmount, sizeof(uint32_t));
-    log_info("\t ******* TxId %d Charging Bill *******", ShmDcCommonData->PriceBill.TransactionId);
-    log_info("\t Total Cost = %.2f", ShmDcCommonData->PriceBill.TotalCost);
-    log_info("\t Discount = %.2f", ShmDcCommonData->PriceBill.Discount);
-    log_info("\t EnergyCost = %.2f", ShmDcCommonData->PriceBill.EnergyCost);
-    log_info("\t ParkingFee = %.2f", ShmDcCommonData->PriceBill.ParkingFee);
-    log_info("\t RemainAmount = %.2f", ShmDcCommonData->PriceBill.RemainAmount);
-    if (ShmDcCommonData->PriceBill.TransactionId != ShmDcCommonData->TransactionInfo[gunIndex].TransactionId)
-        UpdateRedeuctBill(ShmDcCommonData->PriceBill.TransactionId, ShmDcCommonData->PriceBill.TotalCost);
-}
-
-static int parkingbillHandle(uint8_t* data, uint8_t gunIndex)
-{
-
-    ParkingBillInfo* pBillInfo = (ParkingBillInfo*)&data[0];
-
-    ShmDcCommonData->ParkingInfo[gunIndex].Amount = transPricesUnit(ntohl(pBillInfo->ParkingFee));
-    ShmDcCommonData->ParkingInfo[gunIndex].ParkingDuration = ntohl(pBillInfo->Duration);
-    strcpy((char*)ShmDcCommonData->ParkingInfo[gunIndex].ParkingStartTime, (char*)&data[8]);
-    log_info("Gun%d Parking Bill: Amount:[%.2f], Duration:[%d], Start Time[%s]", gunIndex,
-                                                ShmDcCommonData->ParkingInfo[gunIndex].Amount,
-                                                ShmDcCommonData->ParkingInfo[gunIndex].ParkingDuration,
-                                                ShmDcCommonData->ParkingInfo[gunIndex].ParkingStartTime);
-}
-
-static int chargingcapabilityHandle(uint8_t *data, uint8_t plugNum)
-{
-    uint8_t addr = 0;
-    float MaxVolt, MaxCurrent, MaxPower;
-    static PricesInfo pricesInfo[2] = {0};
-    CapabilityInfo *pCapabilityInfo = NULL;
-    AccountInfo *pAccountInfo = NULL;
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(plugNum);
-
-    //--- charging capability information --------------------------------------
-    pCapabilityInfo = (CapabilityInfo *)&data[0];
-
-    MaxVolt = (float)(ntohs(pCapabilityInfo->OutputVoltage));
-    if (MaxVolt >= 0) {
-        if (MaxVolt > MAX_VOLTAGE) {
-            MaxVolt = MAX_VOLTAGE;
-        }
-        pDcChargingInfo->MaximumChargingVoltage = MaxVolt;
-    }
-
-    MaxCurrent = (float)(ntohs(pCapabilityInfo->OutputCurrent));
-    if (MaxCurrent >= 0) {
-        if (MaxCurrent > MAX_CURRENCY) {
-            MaxCurrent = MAX_CURRENCY;
-        }
-        pDcChargingInfo->AvailableChargingCurrent = MaxCurrent;
-    }
-
-    MaxPower = (float)(ntohs(pCapabilityInfo->OutputPower));
-    if (MaxPower >= 0) {
-        if (MaxPower > MAX_POWER) {
-            MaxPower = MAX_POWER;
-        }
-        pDcChargingInfo->AvailableChargingPower = MaxPower;
-    }
-    //MaxVolt = (float)(data[0] << 8 |data[1]);
-    //MaxCurrent = (float)(data[2] << 8 | data[3]);
-    //MaxPower = (float)(data[4] << 8 | data[5]);
-    //printf("MaxVolt=%f, MaxCurrent=%f, MaxPower=%f,", MaxVolt, MaxCurrent, MaxPower);
-
-    //--- user prices information ----------------------------------------------
-    addr = (sizeof(CapabilityInfo) - 2); //2 byte reserved
-    pAccountInfo = (AccountInfo *)&data[addr];
-
-    pSysConfig->BillingData.Currency = pAccountInfo->Currency;
-    ShmSelectGunInfo->PricesInfo[plugNum].UserPrices = transPricesUnit(ntohl(pAccountInfo->UserPrices));
-    pDcChargingInfo->ChargingFee                     = transPricesUnit(ntohl(pAccountInfo->TotalCost));
-    ShmSelectGunInfo->PricesInfo[plugNum].Balance    = transPricesUnit(ntohl(pAccountInfo->Balance));
-    ShmSelectGunInfo->PricesInfo[plugNum].Discount   = transPricesUnit(ntohl(pAccountInfo->Discount));
-    ShmSelectGunInfo->PricesInfo[plugNum].TransactionId = ntohl(pAccountInfo->Transaction);
-    ShmSelectGunInfo->PricesInfo[plugNum].EnergyCost = transPricesUnit(ntohl(pAccountInfo->EnergyCost));
-    ShmSelectGunInfo->PricesInfo[plugNum].ParkingFee = transPricesUnit(ntohl(pAccountInfo->ParkingFee));
-    pAccountInfo->RemainAmount = ntohl(pAccountInfo->RemainAmount);
-    memcpy((char*)&ShmSelectGunInfo->PricesInfo[plugNum].RemainAmount, (char*)&pAccountInfo->RemainAmount, sizeof(uint32_t));
-
-    if ((pricesInfo[plugNum].UserPrices != ShmSelectGunInfo->PricesInfo[plugNum].UserPrices) ||
-            (pricesInfo[plugNum].Balance != ShmSelectGunInfo->PricesInfo[plugNum].Balance) ||
-			(pricesInfo[plugNum].Discount != ShmSelectGunInfo->PricesInfo[plugNum].Discount) ||
-			(pricesInfo[plugNum].TransactionId != ShmSelectGunInfo->PricesInfo[plugNum].TransactionId)) {
-        pricesInfo[plugNum].UserPrices = ShmSelectGunInfo->PricesInfo[plugNum].UserPrices;
-        pricesInfo[plugNum].Balance = ShmSelectGunInfo->PricesInfo[plugNum].Balance;
-        pricesInfo[plugNum].Discount = ShmSelectGunInfo->PricesInfo[plugNum].Discount;
-        pricesInfo[plugNum].TransactionId = ShmSelectGunInfo->PricesInfo[plugNum].TransactionId;
-        pricesInfo[plugNum].ParkingFee = ShmSelectGunInfo->PricesInfo[plugNum].ParkingFee;
-        pricesInfo[plugNum].EnergyCost = ShmSelectGunInfo->PricesInfo[plugNum].EnergyCost;
-        pricesInfo[plugNum].RemainAmount = ShmSelectGunInfo->PricesInfo[plugNum].RemainAmount;
-        if (ShmSelectGunInfo->PricesInfo[plugNum].TransactionId != 0) {
-
-            ShmDcCommonData->TransactionInfo[plugNum].TransactionId = ShmSelectGunInfo->PricesInfo[plugNum].TransactionId;
-
-            UpdateDeductInfoStatus(plugNum, &ShmDcCommonData->TransactionInfo[plugNum]);
-
-            log_info("id = %d, transaction id = %d, user prices = %.2f, Discount = %.2f, Total cost = %.2f, Account balances = %.2f, currency = %s",
-                plugNum,
-                ShmSelectGunInfo->PricesInfo[plugNum].TransactionId,
-                ShmSelectGunInfo->PricesInfo[plugNum].UserPrices,
-                ShmSelectGunInfo->PricesInfo[plugNum].Discount,
-                pDcChargingInfo->ChargingFee,
-                ShmSelectGunInfo->PricesInfo[plugNum].Balance,
-                (uint8_t*)GetCurrency(pSysConfig->BillingData.Currency)
-            );
-            log_info("Total Cost:%.2f", pDcChargingInfo->ChargingFee);
-            log_info("Parking Fee:%.2f", ShmSelectGunInfo->PricesInfo[plugNum].ParkingFee);
-            log_info("Energy Cost:%.2f", ShmSelectGunInfo->PricesInfo[plugNum].EnergyCost);
-            log_info("Remain Amount:%.2f", ShmSelectGunInfo->PricesInfo[plugNum].RemainAmount);
-        }
-    }
-
-    return PASS;
-}
-
-static void addFaultCodeToBuf(uint8_t *Code)
-{
-    uint8_t warningCount = pSysWarning->WarningCount;
-
-    if (warningCount < 10) {
-        memcpy(&pSysWarning->WarningCode[warningCount][0],
-               Code,
-               strlen((char *)Code));
-        pSysWarning->WarningCount++;
-        log_info("Warning Code:%s",Code);
-    }
-}
-
-static void removeFaultCodeToBuf(uint8_t *Code)
-{
-    uint8_t find = 0x01;
-    uint8_t i = 0;
-    char _code[7] = {0};
-
-    sprintf(_code, "%s", Code);
-
-    // 把相關的錯誤碼一次移除,避免重複顯示
-    while (find) {
-        usleep(128);
-        find = 0x00;
-        for (i = 0; i < pSysWarning->WarningCount; i++) {
-            usleep(128);
-            if (find == 0x00) {
-                if (memcmp(&pSysWarning->WarningCode[i][0], _code, 7) == 0) {
-                    find = 0x01;
-                }
-            } else {
-                memcpy(&pSysWarning->WarningCode[i - 1][0],
-                       &pSysWarning->WarningCode[i][0], 7);
-            }
-        }
-
-        if (find) {
-            pSysWarning->WarningCount--;
-        }
-    }
-}
-
-bool CompareArrayIsZero(uint8_t *array, unsigned int array_size)
-{
-    uint8_t i;
-
-    if (array != NULL) {
-        for (i = 0; i < array_size; i++) {
-            if (array[i] != 0) {
-                return false;
-            }
-        }
-    }
-
-    return true;
-}
-static int powerCabinetStatusProcess(uint8_t dataLen, uint8_t *data)
-{
-    uint8_t ret = 0;
-    uint8_t i = 0;
-    uint8_t count = 0;
-    uint8_t EventCodeTmp[7] = {0};
-    uint8_t StatusArray[MAX_REGISTER_NUM][WARNING_CODE_SIZE] = {0};
-    uint8_t remaindLen = 0;
-    //uint8_t statusCodeError = 0;
-
-    if (dataLen > 0) {
-        //Hexdump((uint8_t *)data, dataLen);
-
-        remaindLen = dataLen % WARNING_CODE_SIZE;
-
-        if (remaindLen != 0) {
-            log_info("fail status code length =  %d", dataLen);
-            dataLen -= remaindLen;
-        }
-
-        if (dataLen < WARNING_CODE_SIZE) {
-            log_error("fail status code length = %d", dataLen);
-            //Hexdump(data, dataLen);
-            if (pSysWarning->WarningCount > 0) {
-                for (i = 0; i < pSysWarning->WarningCount; i++) {
-                    usleep(128);
-                    if (pSysWarning->WarningCode[i][1] >= '3' ||  //from backend or power cabinet
-                            (pSysWarning->WarningCode[i][0] >= 'B' &&
-                             pSysWarning->WarningCode[i][1] >= '4')) {
-                        memset(EventCodeTmp, 0, sizeof(EventCodeTmp));
-                        memcpy(EventCodeTmp,
-                               pSysWarning->WarningCode[i],
-                               sizeof(EventCodeTmp));
-                        removeFaultCodeToBuf(EventCodeTmp);
-                    }
-                }
-            }
-            return FAIL;
-        }
-
-        for (count = 0; count < dataLen; count += WARNING_CODE_SIZE) {
-            usleep(128);
-
-            if (strncmp((char *)&data[count + 1], "1", 1) != 0 &&
-                    strncmp((char *)&data[count + 1], "2", 1) != 0 &&
-                    strncmp((char *)&data[count + 1], "3", 1) != 0 &&
-                    (strncmp((char *)&data[count], "B", 1) != 0 &&
-                     strncmp((char *)&data[count + 1], "4", 1) != 0)
-               ) {
-                log_error("error status code = %s", (char *)&data[count]);
-                continue;
-            }
-
-            // misc command status code handle
-            if (strncmp((char *)&data[count], MISC_ST_MISC_CMD, WARNING_CODE_SIZE) == 0) {
-                gDoCommGblData.MiscCmd = REG_MISC_CONTROL;
-                memset((char *)&data[count], 0, WARNING_CODE_SIZE);
-                continue;
-            } else if (strncmp((char *)&data[count], MISC_ST_VERSION, WARNING_CODE_SIZE) == 0) {
-                gDoCommGblData.MiscCmd = REG_REPORT_CSU_VERSION;
-                memset((char *)&data[count], 0, WARNING_CODE_SIZE);
-                continue;
-            }
-
-            if (CompareArrayIsZero((uint8_t *)&data[count], WARNING_CODE_SIZE) == true) {
-                memset(EventCodeTmp, 0, sizeof(EventCodeTmp));
-                memcpy(EventCodeTmp, (char *)&data[count], sizeof(EventCodeTmp));
-                log_error("error status = %s", EventCodeTmp);
-                continue;
-            }
-
-            strncpy((char *)&StatusArray[count / WARNING_CODE_SIZE], (char *)&data[count], WARNING_CODE_SIZE);
-
-            ret = 0;
-            for (i = 0; i < pSysWarning->WarningCount; i++) {
-                usleep(128);
-                if (memcmp(&pSysWarning->WarningCode[i][0],
-                           StatusArray[count / WARNING_CODE_SIZE],
-                           WARNING_CODE_SIZE) == 0) {
-                    ret = 1;
-                    break;
-                }
-            }
-
-            if (ret == 0) {
-                addFaultCodeToBuf(StatusArray[count / WARNING_CODE_SIZE]);
-            }
-            //Rtn=StatusCodeProcessing(StatusArray[count/6]);
-        }
-    } else {
-        if (CompareArrayIsZero(data, WARNING_CODE_SIZE) == false) {
-            log_error("power cabinet status code data length is zero, but have data");
-            //Hexdump((uint8_t *)data, WARNING_CODE_SIZE);
-        }
-    }
-
-    for (i = 0; i < pSysWarning->WarningCount; i++) {
-        usleep(128);
-
-        if (pSysWarning->WarningCode[i][1] >= '3' || //from backend or power cabinet 0x33
-                (pSysWarning->WarningCode[i][0] >= 'B' &&
-                 pSysWarning->WarningCode[i][1] >= '4')) {
-            ret = 0;
-
-            for (count = 0; count < (dataLen / WARNING_CODE_SIZE); count++) {
-                usleep(128);
-                if (memcmp(&pSysWarning->WarningCode[i][0],
-                           StatusArray[count],
-                           WARNING_CODE_SIZE) == 0) {
-                    ret = 1;
-                    break;
-                }
-            }
-
-            if (ret == 0) {
-                memset(EventCodeTmp, 0, sizeof(EventCodeTmp));
-                memcpy(EventCodeTmp,
-                       pSysWarning->WarningCode[i],
-                       sizeof(EventCodeTmp));
-                removeFaultCodeToBuf(EventCodeTmp);
-            }
-        }
-    }
-
-    return PASS;
-}
-void CheckTaiwanEastWest(int id)
-{
-    ShmDcCommonData->TaiwanEast = TRUE;
-    //西半部
-    if (id >= 100 && id <= 116) {//台北
-        ShmDcCommonData->TaiwanEast = FALSE;
-    } else if (id >= 200 && id <= 206) { //基隆
-        ShmDcCommonData->TaiwanEast = FALSE;
-    } else if (id >= 207 && id <= 253) { //新北
-        ShmDcCommonData->TaiwanEast = FALSE;
-    } else if (id >= 300 && id <= 315) { //新竹
-        ShmDcCommonData->TaiwanEast = FALSE;
-    } else if (id >= 320 && id <= 338) { //桃園
-        ShmDcCommonData->TaiwanEast = FALSE;
-    } else if (id >= 350 && id <= 369) { //苗栗
-        ShmDcCommonData->TaiwanEast = FALSE;
-    } else if (id >= 400 && id <= 439) { //台中
-        ShmDcCommonData->TaiwanEast = FALSE;
-    } else if (id >= 500 && id <= 530) { //彰化
-        ShmDcCommonData->TaiwanEast = FALSE;
-    } else if (id >= 600 && id <= 625) { //嘉義
-        ShmDcCommonData->TaiwanEast = FALSE;
-    } else if (id >= 630 && id <= 655) { //雲林
-        ShmDcCommonData->TaiwanEast = FALSE;
-    } else if (id >= 700 && id <= 745) { //台南
-        ShmDcCommonData->TaiwanEast = FALSE;
-    } else if (id >= 800 && id <= 852) { //高雄
-        ShmDcCommonData->TaiwanEast = FALSE;
-    } else if (id >= 900 && id <= 947) { //屏東
-        ShmDcCommonData->TaiwanEast = FALSE;
-    } else if (id >= 880 && id <= 885) { //澎湖
-        ShmDcCommonData->TaiwanEast = FALSE;
-    // 東半部
-    } else if (id >= 540 && id <= 558) { //南投
-        ShmDcCommonData->TaiwanEast = TRUE;
-    } else if (id >= 260 && id <= 272) { //宜蘭
-        ShmDcCommonData->TaiwanEast = TRUE;
-    } else if (id >= 950 && id <= 966) { //台東
-        ShmDcCommonData->TaiwanEast = TRUE;
-    } else if (id >= 970 && id <= 983) { //花蓮
-        ShmDcCommonData->TaiwanEast = TRUE;
-    }
-}
-static int responsePackeHandle(int fd, uint8_t *pResult, uint8_t plugNum, uint8_t reg)
-{
-    int ret = PASS;
-    uint8_t rawDataLen = 0;
-    CsuResultPkt *pCsuResult = (CsuResultPkt *)pResult;
-    SoftwareUpdInfo *pSoftwareUpd = NULL;
-    PcPsuOutput *pPcPsuOutput = NULL;
-
-    //Hexdump((uint8_t *)pCsuResult, sizeof(CmdHead) + pCsuResult->Head.DataLen);
-    if (compareOpcode(pCsuResult->Head.OP) == FAIL ||
-            compareResult(pCsuResult->Data.Result) == FAIL ||
-            compareRegister(pCsuResult->Data.Register, reg) == FAIL) {
-        if (reg != REG_CHARGING_PERMISSION) {
-            return FAIL;
-        }
-    }
-
-    rawDataLen = (pCsuResult->Head.DataLen - 2); //2 byte = register and result byte
-
-    switch (pCsuResult->Data.Register) {
-    case REG_MODEL_NAME:
-        break;
-
-    case REG_CONNECTOR_ID:
-        gDoCommGblData.ConnectorID[0] = pCsuResult->Data.Data[0];
-        gDoCommGblData.ConnectorID[1] = pCsuResult->Data.Data[1];
-        log_info("OK (Left connector ID = %d, Right connector ID = %d)",
-                 pCsuResult->Data.Data[0],
-                 pCsuResult->Data.Data[1]);
-        ShmDcCommonData->ConnectorID[0] = pCsuResult->Data.Data[0];
-        ShmDcCommonData->ConnectorID[1] = pCsuResult->Data.Data[1];
-        break;
-
-    case REG_POWER_CABINET_STATUS:
-        ret = powerCabinetStatusProcess(rawDataLen, pCsuResult->Data.Data);
-        break;
-
-    case REG_DISPENSER_STATUS:
-        memset(&gPreSysWarningInfo, 0, sizeof(struct WARNING_CODE_INFO));
-        memcpy((uint8_t *)&gPreSysWarningInfo,
-               pSysWarning,
-               sizeof(struct WARNING_CODE_INFO));
-        break;
-
-    case REG_CHARGING_CAP:
-        chargingcapabilityHandle(pCsuResult->Data.Data, plugNum);
-        break;
-
-    case REG_CHARGING_TARGET:
-        break;
-
-    case REG_SOFTWARE_UPDATE:
-        pSoftwareUpd = (SoftwareUpdInfo *)&pCsuResult->Data.Data[0];
-
-        if ((strcmp((char *)pSoftwareUpd->ImgName, "") == 0) ||
-                (rawDataLen == 0) ||
-                pSoftwareUpd->UpdateState != 1) {
-            ret = FAIL;
-            break;
-        }
-
-        ret = FAIL;
-        ret = updateFirmwareHandle(pSoftwareUpd->ImgName);
-        break;
-
-    case REG_PLUG_IN_STATE:
-        break;
-
-    case REG_CONNECTOR_STATE:
-        break;
-
-    case REG_USER_ID:
-        //log_info("USER ID:%s", pCsuResult->Data.Data[0] == 1 ? "Accept" : "Reject" );
-        //if (pCsuResult->Data.Data[0] <= 0) {
-        //    return FAIL;
-        //}
-        if (pCsuResult->Data.Result == COMMAND_RESULT_NG) {
-            return COMMAND_RESULT_NG;
-        }
-
-        ShmSelectGunInfo->AuthorStateFromCabinet[plugNum] = pCsuResult->Data.Data[0];
-
-        return pCsuResult->Data.Data[0];
-        break;
-
-    case REG_CHARGING_PERMISSION:
-        //log_info("id = %d, result = %s, action = %s",
-        //           pCsuResult->Head.ID,
-        //           pCsuResult->Data.Result == 1 ? "OK" : "NG",
-        //           pCsuResult->Data.Data[0] == 1 ? "Permitted" : "NOT permitted");
-        if (pCsuResult->Data.Result == COMMAND_RESULT_NG) {
-            return COMMAND_RESULT_NG;
-        }
-
-        ShmSelectGunInfo->WaitDoCommPermission[plugNum] = pCsuResult->Data.Data[0];
-
-        return pCsuResult->Data.Data[0];
-        break;
-
-    case REG_MISC_CONTROL:
-        miscCommandHandle(rawDataLen, plugNum, pCsuResult->Data.Data);
-        break;
-
-    case REG_REPORT_CSU_VERSION:
-    case REG_REPORT_OTHER_VERSION:
-        break;
-
-    case REG_PRESENT_CHARGING_INFO:
-        pPcPsuOutput = (PcPsuOutput *)&pCsuResult->Data.Data[0];
-
-        ShmDcCommonData->PcPsuOutput[plugNum].Voltage = ntohs((uint16_t)pPcPsuOutput->Voltage);
-        ShmDcCommonData->PcPsuOutput[plugNum].Current = ntohs((uint16_t)pPcPsuOutput->Current);
-        //log_info("%d power cabinet PSU output vol = %f, cur = %f",
-        //         plugNum,
-        //         (float)ShmDcCommonData->PcPsuOutput[plugNum].Voltage,
-        //         (float)ShmDcCommonData->PcPsuOutput[plugNum].Current);
-        break;
-
-    case REG_QRCODE_URL_INFO:
-        ret = qrCodeUrlInfoHandle(pCsuResult->Data.Data);
-        break;
-
-    case REG_WAIT_PLUG_IT_STATE:
-        break;
-
-    case REG_Ground_Fault_Detection:
-        if (pCsuResult->Data.Result == COMMAND_RESULT_NG) {
-            return COMMAND_RESULT_NG;
-        }
-
-        //集電弓relay 不打開才能進入動作
-        pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(plugNum);
-        if(pDcChargingInfo->PantographFlag == YES)
-        {
-            GroundFaultDetection *gfd = (GroundFaultDetection *)&pCsuResult->Data.Data[0];
-            if(pDcChargingInfo->GroundFaultStatus != gfd->Status)
-            {
-                log_info("id = %d, GFD Result = %d",
-                           pCsuResult->Head.ID,
-                           gfd->Status);
-            }
-            pDcChargingInfo->GroundFaultStatus = gfd->Status;
-        }
-        break;
-
-    case REG_RESERVATION_IDTAG:
-        if (pCsuResult->Data.Result == COMMAND_RESULT_NG) {
-            return COMMAND_RESULT_NG;
-        }
-        uint8_t reservationState = pCsuResult->Data.Data[0] == YES ? YES : NO;
-        memset(&ReservationIdTag[plugNum][0], 0x00, 32);
-        ShmDcCommonData->pGunInfo[plugNum].ReservationStatus = reservationState;
-        if(reservationState)
-        {
-            strcpy(&ReservationIdTag[plugNum][0], (char *)&pCsuResult->Data.Data[1]);
-        }
-        if(reservationState != ReservationState[plugNum])
-        {
-            log_info("id = %d reservation is %s", pCsuResult->Head.ID, reservationState ? "trigger" : "expired");
-            if(reservationState)
-            {
-                log_info("id = %d reservation idTag: %s", pCsuResult->Head.ID, (char *)&ReservationIdTag[plugNum][0]);
-                strcpy(&ShmDcCommonData->pGunInfo[plugNum].ReservationID[0], (char*)&pCsuResult->Data.Data[1]);
-                if (pSysInfo->SystemPage == _PAGE_IDLE) {
-                    pSysInfo->SystemPage = _PAGE_SELECT_GUN;
-                }
-            } else {
-                strcpy(&ShmDcCommonData->pGunInfo[plugNum].ReservationID[0], "");
-            }
-        }
-        ReservationState[plugNum] = reservationState;
-        break;
-
-    case REG_REMOTE_START_NO_ID:
-        if (pCsuResult->Data.Result == COMMAND_RESULT_NG) {
-            return COMMAND_RESULT_NG;
-        }
-        uint8_t remoteStartNoIdState = pCsuResult->Data.Data[0] == YES ? YES : NO;
-        if(remoteStartNoIdState != RemoteStartNoIDState)
-        {
-            log_info("RemoteStartNoID is %s", remoteStartNoIdState ? "trigger" : "expired");
-        }
-        RemoteStartNoIDState = remoteStartNoIdState;
-        break;
-
-    case REG_STATION_INFO:
-        if (pCsuResult->Data.Result == COMMAND_RESULT_NG) {
-            return COMMAND_RESULT_NG;
-        }
-        StationVar _stationInfo;
-        memset((char *)&_stationInfo, 0x00, sizeof(StationVar));
-
-        _stationInfo.StationID = (pCsuResult->Data.Data[0] << 24) +
-                                 (pCsuResult->Data.Data[1] << 16) +
-                                 (pCsuResult->Data.Data[2] << 8) +
-                                 pCsuResult->Data.Data[3];
-        memcpy(_stationInfo.StationName, (char *)&pCsuResult->Data.Data[4], 64);
-        _stationInfo.WeatherID |= (pCsuResult->Data.Data[68] << 24);
-        _stationInfo.WeatherID |= (pCsuResult->Data.Data[69] << 16);
-        _stationInfo.WeatherID |= (pCsuResult->Data.Data[70] << 8);
-        _stationInfo.WeatherID |= pCsuResult->Data.Data[71];
-        uint8_t *pFloat = (uint8_t *)&_stationInfo.Temperature;
-        *(pFloat + 3) = pCsuResult->Data.Data[72];
-        *(pFloat + 2) = pCsuResult->Data.Data[73];
-        *(pFloat + 1) = pCsuResult->Data.Data[74];
-        *(pFloat) = pCsuResult->Data.Data[75];
-
-        ShmDcCommonData->WeatherID = _stationInfo.WeatherID;
-        ShmDcCommonData->Temperature = _stationInfo.Temperature;
-        ShmDcCommonData->Location = atoi(_stationInfo.StationName);
-
-        CheckTaiwanEastWest(ShmDcCommonData->Location);
-        
-        log_info("Station Name: %s, ID: %d, Weather: %d, Temperature: %.1f",
-                _stationInfo.StationName,
-                _stationInfo.StationID,
-                _stationInfo.WeatherID,
-                _stationInfo.Temperature);
-        
-        break;
-
-    case REG_DEDUCT_INFO:
-        if (pCsuResult->Data.Result == COMMAND_RESULT_NG) {
-            return COMMAND_RESULT_NG;
-        }
-        break;
-
-    case REG_POWER_CONSUMPTION_INFO:
-        if (pCsuResult->Data.Result == COMMAND_RESULT_NG) {
-            return COMMAND_RESULT_NG;
-        }
-
-        PowConsumValue* pValue = NULL;
-        pValue = (PowConsumValue*)&pCsuResult->Data.Data[0];
-
-        pValue->Gun1_Consumption = ntohl(pValue->Gun1_Consumption);
-        pValue->Gun2_Consumption = ntohl(pValue->Gun2_Consumption);
-        pValue->Gun3_Consumption = ntohl(pValue->Gun3_Consumption);
-        pValue->Gun4_Consumption = ntohl(pValue->Gun4_Consumption);
-        memcpy((char*)&ShmDcCommonData->pConsumption.Gun1_Consumption, (char*)&pValue->Gun1_Consumption, sizeof(uint32_t));
-        memcpy((char*)&ShmDcCommonData->pConsumption.Gun2_Consumption, (char*)&pValue->Gun2_Consumption, sizeof(uint32_t));
-        memcpy((char*)&ShmDcCommonData->pConsumption.Gun3_Consumption, (char*)&pValue->Gun3_Consumption, sizeof(uint32_t));
-        memcpy((char*)&ShmDcCommonData->pConsumption.Gun4_Consumption, (char*)&pValue->Gun4_Consumption, sizeof(uint32_t));
-
-        log_info("Gun1_Consumption:%f", ShmDcCommonData->pConsumption.Gun1_Consumption);
-        log_info("Gun2_Consumption:%f", ShmDcCommonData->pConsumption.Gun2_Consumption);
-        log_info("Gun3_Consumption:%f", ShmDcCommonData->pConsumption.Gun3_Consumption);
-        log_info("Gun4_Consumption:%f", ShmDcCommonData->pConsumption.Gun4_Consumption);
-
-
-        break;
-    case REG_READ_CHARGING_TIMESTAMP:
-        break;
-    case REG_CHARGING_BILL:
-        if (pCsuResult->Data.Result == COMMAND_RESULT_NG) {
-            return COMMAND_RESULT_NG;
-        }
-        chargingbillHandle(pCsuResult->Data.Data, plugNum);
-        break;
-    case REG_PARKING_STATUS:
-        if (pCsuResult->Data.Result == COMMAND_RESULT_NG) {
-            return COMMAND_RESULT_NG;
-        }
-        char cmd[37];
-        memset(cmd,'\0',sizeof(cmd));
-        memcpy(cmd,&pCsuResult->Data.Data[1],36);
-        if (memcmp(ShmDcCommonData->ParkingInfo[plugNum].OccupancySN,&pCsuResult->Data.Data[1],36) != EQUAL) {
-            memcpy(ShmDcCommonData->ParkingInfo[plugNum].OccupancySN,&pCsuResult->Data.Data[1],36);
-        }
-        if (ShmDcCommonData->pGunInfo[plugNum].ParkingStatus != pCsuResult->Data.Data[0]) {
-            ShmDcCommonData->pGunInfo[plugNum].ParkingStatus = pCsuResult->Data.Data[0];
-            if (ShmDcCommonData->pGunInfo[plugNum].ParkingStatus == _TCC_PARKING_NONE )
-                ShmDcCommonData->pGunInfo[plugNum].isParking = FALSE;
-            else {
-                ShmDcCommonData->pGunInfo[plugNum].isParking = TRUE;
-            }
-            log_info("Gun%d Parking STATUS is [%d] SN:[%s] isParking:[%s]",plugNum,pCsuResult->Data.Data[0],cmd,(ShmDcCommonData->pGunInfo[plugNum].isParking ? "ON":"OFF"));
-            if (!ShmDcCommonData->pGunInfo[plugNum].ParkingStatus) {
-                //if (pSysInfo->CurGunSelected == plugNum)
-                //    systemPageRestoreInit();
-                gMoreInfoReq[plugNum].bits.ParkingReq = FALSE;
-                ShmDcCommonData->pGunInfo[plugNum].GetParkingBill = FALSE;
-                memset(&ShmDcCommonData->ParkingInfo[plugNum],0,sizeof(RecordTransactionInfo));
-                ShmDcCommonData->ParkingInfo[plugNum].IsUpload = TRUE;
-            } else {
-                if (pSysInfo->SystemPage >= _PAGE_BILL && pSysInfo->SystemPage <= _PAGE_PLUGIN) {
-                    if (pSysInfo->CurGunSelected == plugNum) {
-                        if (ShmDcCommonData->pGunInfo[plugNum].ParkingStatus == _TCC_PARKING_OCCUPENCY) {
-                            systemPageRestoreInit();
-                        } else if (ShmDcCommonData->pGunInfo[plugNum].ParkingStatus == _TCC_ONLINEPAY_PASS) {
-                            pSysInfo->SystemPage = _PAGE_PLUGIN;
-                        } else if (ShmDcCommonData->pGunInfo[plugNum].ParkingStatus == _TCC_ONLINEPAY_FAIL) {
-                            pSysInfo->SystemPage = _PAGE_AUTHORIZE_FAIL;
-                        }
-                    }
-                }
-            }
-        }
-
-        break;
-    case REG_PARKING_BILL:
-        if (pCsuResult->Data.Result == COMMAND_RESULT_NG) {
-            return COMMAND_RESULT_NG;
-        }
-        parkingbillHandle(pCsuResult->Data.Data, plugNum);
-        break;
-    default:
-        break;
-    }
-
-    return ret;
-}
-
-static int composeSocketData(int fd,
-                             uint8_t id,
-                             uint8_t opCode,
-                             uint8_t reg,
-                             uint8_t dataLen,
-                             uint8_t *data)
-{
-    int ret = PASS;
-    int size = 0;
-    int sendPktLen = 0;
-    uint8_t i = 0;
-    uint8_t plugNum = 0;
-    CsuCmdPkt csuCmdPkt = {0};
-    CsuResultPkt csuResult = {0};
-
-    csuCmdPkt.Head.SeqNum = gDoCommGblData.SeqNum++;
-    csuCmdPkt.Head.ID = id;
-    csuCmdPkt.Head.OP = opCode;
-    csuCmdPkt.Head.DataLen = dataLen + 1; //+1 for register byte
-
-    csuCmdPkt.Data.Register = reg;
-    if ((data != NULL) && (dataLen > 0)) {
-        memcpy(csuCmdPkt.Data.Data, data, dataLen);
-    }
-
-    sendPktLen = csuCmdPkt.Head.DataLen + sizeof(csuCmdPkt.Head);
-
-    //Hexdump((uint8_t *)&csuCmdPkt, sendPktLen);
-
-    //send command packet
-    if ((size = sendTcpSocket(fd, (uint8_t *)&csuCmdPkt, sendPktLen)) < 0) {
-        log_error("TCP socket reg=0x%x send packet fail = %d",reg, size);
-        gDoCommGblData.DisConnCount++;
-        return FAIL;
-    }
-
-    //receive result head
-    if ((size = recvTcpSocket(fd, (uint8_t *)&csuResult.Head, sizeof(csuResult.Head))) < 0) {
-        log_error("TCP socket reg=0x%x RX head fail = %d",reg, size);
-        gDoCommGblData.DisConnCount++;
-        return FAIL;
-    }
-
-    //receive result raw data
-    if ((size = recvTcpSocket(fd, (uint8_t *)&csuResult.Data, csuResult.Head.DataLen)) < 0) {
-        log_error("TCP socket reg=0x%x RX data fail = %d",reg, size);
-        gDoCommGblData.DisConnCount++;
-        return FAIL;
-    }
-
-    for (i = 0; i < sizeof(gDoCommGblData.ConnectorID); i++) {
-        if (id == gDoCommGblData.ConnectorID[i]) {
-            plugNum = i;
-            break;
-        }
-    }
-
-    ret = responsePackeHandle(fd, (uint8_t *)&csuResult, plugNum, csuCmdPkt.Data.Register);
-
-    gDoCommGblData.DisConnCount = 0; //送收資料沒有問題, 清除中斷網路計數
-
-    return ret;
-}
-static int writeDispenserRequest(int fd, uint8_t id, uint8_t gunIndex)
-{
-    int ret = PASS;
-    int count = 0;
-    MiscCommand dispenserReq;
-    uint8_t data[12] = { 0 };
-    if (gConnectorActReq[gunIndex].bits.ChargingCancel)
-    {
-        dispenserReq.CMD = DISPENSER_REQ_CHARGING_CANCEL;
-        dispenserReq.Value[0] = 0;
-        dispenserReq.Value[1] = 0;
-        dispenserReq.Value[2] = 0;
-        dispenserReq.Value[3] = 1;
-        AddDispenserReq(&data[count*6], &dispenserReq);
-        count++;
-        //log_info("Write Gun %d CHARGING_CANCEL", gunIndex);
-    }
-    if (gConnectorActReq[gunIndex].bits.ParkingBillReq) {
-        dispenserReq.CMD = DISPENSER_REQ_PARKING_BILL;
-        dispenserReq.Value[0] = 0;
-        dispenserReq.Value[1] = 0;
-        dispenserReq.Value[2] = 0;
-        dispenserReq.Value[3] = 1;
-        AddDispenserReq(&data[count*6], &dispenserReq);
-        count++;
-    }
-
-    if ((ret = composeSocketData(fd,
-                                id,
-                                OP_WRITE_DATA,
-                                REG_DISPENSER_REQUEST,
-                                (count * 6),
-                                &data[0])) == FAIL) {
-                                return ret;
-    }
-    return ret;
-}
-static int readReservationState(int fd, uint8_t id)
-{
-    int ret = PASS;
-
-    if ((ret = composeSocketData(fd,
-                                 id,
-                                 OP_READ_DATA,
-                                 REG_RESERVATION_IDTAG,
-                                 0,
-                                 NULL)) == FAIL) {
-        return ret;
-    }
-
-    return ret;
-}
-
-static int readRemoteStartNoIDState(int fd)
-{
-    int ret = PASS;
-
-    if ((ret = composeSocketData(fd,
-                                 ID_REGISTER,
-                                 OP_READ_DATA,
-                                 REG_REMOTE_START_NO_ID,
-                                 0,
-                                 NULL)) == FAIL) {
-        return ret;
-    }
-
-    return ret;
-}
-
-static int readChargingBill(int fd,int gunID)
-{
-    int ret = PASS;
-
-    if ((ret = composeSocketData(fd,
-                                gunID,
-                                OP_READ_DATA,
-                                REG_CHARGING_BILL,
-                                0,
-                                NULL)) == FAIL) {
-        return ret;
-    }
-
-    return ret;
-}
-
-static int readParkingStatus(int fd, int gunID)
-{
-    int ret = PASS;
-
-    if ((ret = composeSocketData(fd,
-                                gunID,
-                                OP_READ_DATA,
-                                REG_PARKING_STATUS,
-                                0,
-                                NULL)) == FAIL) {
-        return ret;
-    }
-
-    return ret;
-}
-
-static int readParkingBill(int fd, int gunID)
-{
-    int ret = PASS;
-
-    if ((ret = composeSocketData(fd,
-                                gunID,
-                                OP_READ_DATA,
-                                REG_PARKING_BILL,
-                                0,
-                                NULL)) == FAIL) {
-        return ret;
-    }
-
-    return ret;
-}
-
-static int readChargerStationInfo(int fd)
-{
-    int ret = PASS;
-
-    if ((ret = composeSocketData(fd,
-                                 ID_REGISTER,
-                                 OP_READ_DATA,
-                                 REG_STATION_INFO,
-                                 0,
-                                 NULL)) == FAIL) {
-        return ret;
-    }
-
-    return ret;
-}
-void showDeductInfo(RecordTransactionInfo* transactionInfo)
-{
-    char ApprovalNo[10];
-    char vemdata[65];
-    char cardno[21];
-    char OccupancySN[37];
-    memset(ApprovalNo,'\0',sizeof(ApprovalNo));
-    memset(vemdata,'\0',sizeof(vemdata));
-    memset(cardno,'\0',sizeof(cardno));
-    memset(OccupancySN,'\0',sizeof(OccupancySN));
-    memcpy(ApprovalNo,&transactionInfo->pCreditCard.ApprovalNo[0],9);
-    memcpy(vemdata,&transactionInfo->pCreditCard.VemData[0],64);
-    memcpy(cardno,&transactionInfo->pCreditCard.CardNo[0],20);
-    memcpy(OccupancySN,&transactionInfo->OccupancySN[0],36);
-    log_info("Gun[%d] TransactionId:%d DeductResult:%d IsDonateInvoice:%d Amount:%f Approva Num:[%s] VemData:[%s] CardNo:[%s] OccupancySN:[%s]",
-    		transactionInfo->ConnectorID,
-            transactionInfo->TransactionId,
-            transactionInfo->DeductResult,
-            transactionInfo->IsDonateInvoice,
-            transactionInfo->Amount,
-            ApprovalNo,
-            vemdata,
-            cardno,
-            OccupancySN);
-}
-
-
-static int writeDeductInfo(int fd, uint8_t id,uint8_t gunIndex, RecordTransactionInfo *transactionInfo)
-{
-    int ret = PASS;
-    if (ShmDcCommonData->DebugFlag &&
-        strcmp((char*)transactionInfo->pCreditCard.ApprovalNo ,"") == EQUAL) {
-        return ret;
-    }
-
-    uint8_t dataBuf[139] = {0};
-    //int i;
-
-    memset((char *)dataBuf, 0x00, sizeof(dataBuf));
-    dataBuf[0] = transactionInfo->DeductResult;
-    dataBuf[1] = transactionInfo->IsDonateInvoice;
-    dataBuf[2] = (transactionInfo->TransactionId >> 24) & 0xFF;
-    dataBuf[3] = (transactionInfo->TransactionId >> 16) & 0xFF;
-    dataBuf[4] = (transactionInfo->TransactionId >> 8) & 0xFF;
-    dataBuf[5] = (transactionInfo->TransactionId & 0xFF);
-
-    int amount = (int)(transactionInfo->Amount * 100);
-
-    dataBuf[6] = (amount >> 24) & 0xFF;
-    dataBuf[7] = (amount >> 16) & 0xFF;
-    dataBuf[8] = (amount >> 8) & 0xFF;
-    dataBuf[9] = (amount & 0xFF);
-    memcpy((char *)&dataBuf[10], &transactionInfo->pCreditCard.ApprovalNo[0],9);
-    memcpy((char *)&dataBuf[19], &transactionInfo->pCreditCard.VemData[0], 64);
-    memcpy((char*)&dataBuf[83], &transactionInfo->pCreditCard.CardNo[0], 20);
-    memcpy((char*)&dataBuf[103], &transactionInfo->OccupancySN[0], 36);
-
-    showDeductInfo(transactionInfo);
-    /*
-    log_info("Gun[%d] TransactionId:%d DeductResult:%d IsDonateInvoice:%d Amount:%f Approva Num:'%s' VemData:'%s' CardNo:'%s'",
-    		transactionInfo->ConnectorID,
-            transactionInfo->TransactionId,
-            transactionInfo->DeductResult,
-            transactionInfo->IsDonateInvoice,
-            transactionInfo->Amount,
-            transactionInfo->pCreditCard.ApprovalNo,
-            transactionInfo->pCreditCard.VemData,
-            transactionInfo->pCreditCard.CardNo);
-            */
-    // copy deduct result to dataBuf here
-
-    if ((ret = composeSocketData(fd,
-                                 id,
-                                 OP_WRITE_DATA,
-                                 REG_DEDUCT_INFO,
-                                 139,
-                                 &dataBuf[0])) == FAIL) {
-        return ret;
-    }
-
-    return ret;
-}
-
-static int writeWaitPlugItState(int fd, uint8_t id,uint8_t gunIndex)
-{
-    int ret = PASS;
-    uint8_t data[2] = { ShmDcCommonData->pGunInfo[gunIndex].WaitForPlugit, 0};
-    if (_isplugin[gunIndex] != ShmDcCommonData->pGunInfo[gunIndex].WaitForPlugit) {
-        //log_info("Wait Gun%d for plug:%s", gunIndex, ShmDcCommonData->pGunInfo[gunIndex].WaitForPlugit == 0 ? "disable" : "enable");
-        _isplugin[gunIndex] = ShmDcCommonData->pGunInfo[gunIndex].WaitForPlugit;
-    }
-    //printf("WaitForPlugit = %d", pSysInfo->WaitForPlugit);
-
-    if ((ret = composeSocketData(fd,
-                                 id,
-                                 OP_WRITE_DATA,
-                                 REG_WAIT_PLUG_IT_STATE,
-                                 1,
-                                 &data[0])) == FAIL) {
-        return ret;
-    }
-
-    return ret;
-}
-
-static int readQRcodeURLAndSystemDate(int fd)
-{
-    int ret = PASS;
-
-    ret = composeSocketData(fd,
-                            ID_REGISTER,
-                            OP_READ_DATA,
-                            REG_QRCODE_URL_INFO,
-                            0,
-                            NULL);
-    return ret;
-}
-
-static int writePresentChargingInfo(int fd, uint8_t plugNum, uint8_t id)
-{
-    int ret = PASS;
-    uint8_t dataBuf[16] = {0};
-    PreChargingInfo *pPreChargingInfo = (PreChargingInfo *)dataBuf;
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(plugNum);
-
-    if(pDcChargingInfo->PantographFlag == NO)
-    {
-        pPreChargingInfo->PresentChargingVoltage = htons((uint16_t)(pDcChargingInfo->PresentChargingVoltage * 10));
-        pPreChargingInfo->PresentChargingCurrent = htons((uint16_t)(pDcChargingInfo->PresentChargingCurrent * 10));
-    }
-    else
-    {
-        pPreChargingInfo->PresentChargingVoltage = htons((uint16_t)(ShmDcCommonData->PcPsuOutput[plugNum].Voltage));
-        pPreChargingInfo->PresentChargingCurrent = htons((uint16_t)(ShmDcCommonData->PcPsuOutput[plugNum].Current));
-    }
-    pPreChargingInfo->RemainChargingDuration = htonl(pDcChargingInfo->RemainChargingDuration);
-    pPreChargingInfo->EvBatterySoc = pDcChargingInfo->EvBatterySoc;
-
-    ret = composeSocketData(fd,
-                            id,
-                            OP_WRITE_DATA,
-                            REG_PRESENT_CHARGING_INFO,
-                            sizeof(PreChargingInfo),
-                            (uint8_t *)pPreChargingInfo);
-    return ret;
-}
-
-static int writeOtherModuleVersion(int fd)
-{
-    int ret = PASS;
-    uint8_t data[255] = {0};
-    uint8_t dataLen = 0;
-
-    //report other module version message
-    memcpy(&data[dataLen], pSysInfo->FanModuleFwRev, VERSION_BUF_SIZE);
-    dataLen += VERSION_BUF_SIZE;
-    memcpy(&data[dataLen], pSysInfo->RelayModuleFwRev, VERSION_BUF_SIZE);
-    dataLen += VERSION_BUF_SIZE;
-    memcpy(&data[dataLen], pSysInfo->Connector1FwRev, VERSION_BUF_SIZE);
-    dataLen += VERSION_BUF_SIZE;
-    memcpy(&data[dataLen], pSysInfo->Connector2FwRev, VERSION_BUF_SIZE);
-    dataLen += VERSION_BUF_SIZE;
-    memcpy(&data[dataLen], pSysInfo->LedModuleFwRev, VERSION_BUF_SIZE);
-    dataLen += VERSION_BUF_SIZE;
-
-    ret = composeSocketData(fd,
-                            ID_REGISTER,
-                            OP_WRITE_DATA,
-                            REG_REPORT_OTHER_VERSION,
-                            dataLen,
-                            &data[0]);
-
-    return ret;
-}
-
-static int writeCsuModuleVersion(int fd)
-{
-    int ret = PASS;
-    uint8_t data[255] = {0};
-    uint8_t dataLen = 0;
-
-    //report CSU platform version message
-    memcpy(&data[dataLen], pSysInfo->CsuBootLoadFwRev, VERSION_BUF_SIZE);
-    dataLen += VERSION_BUF_SIZE;
-    memcpy(&data[dataLen], pSysInfo->CsuKernelFwRev, VERSION_BUF_SIZE);
-    dataLen += VERSION_BUF_SIZE;
-    memcpy(&data[dataLen], pSysInfo->CsuRootFsFwRev, VERSION_BUF_SIZE);
-    dataLen += VERSION_BUF_SIZE;
-    memcpy(&data[dataLen], pSysInfo->CsuPrimFwRev, VERSION_BUF_SIZE);
-    dataLen += VERSION_BUF_SIZE;
-
-    ret = composeSocketData(fd,
-                            ID_REGISTER,
-                            OP_WRITE_DATA,
-                            REG_REPORT_CSU_VERSION,
-                            dataLen,
-                            &data[0]);
-
-    return ret;
-}
-
-static int readMiscCommand(int fd, uint8_t id)
-{
-    int ret = PASS;
-
-    ret = composeSocketData(fd,
-                            id,
-                            OP_READ_DATA,
-                            REG_MISC_CONTROL,
-                            0,
-                            NULL);
-
-    return ret;
-}
-
-static int readChargePermission(int fd, uint8_t id)
-{
-    return composeSocketData(fd,
-                             id,
-                             OP_READ_DATA,
-                             REG_CHARGING_PERMISSION,
-                             0,
-                             NULL);
-}
-
-static int writeGroundFaultDetection(int fd, uint8_t status, uint8_t id)
-{
-    int ret = PASS;
-    uint8_t dataBuf[1] = {status};
-    ret = composeSocketData(fd,
-                            id,
-                            OP_WRITE_DATA,
-                            REG_Ground_Fault_Detection,
-                            1,
-                            &dataBuf[0]);
-    return ret;
-}
-
-static int writeUserID(int fd, uint8_t id, uint8_t *pUserID)
-{
-    if ((strlen((char *)pUserID) <= 0) || (pUserID == NULL)) {
-        return FAIL;
-    }
-
-    return composeSocketData(fd,
-                             id,
-                             OP_WRITE_DATA,
-                             REG_USER_ID,
-                             strlen((char *)pUserID),
-                             pUserID);
-}
-
-static int writeConnectorState(int fd, uint8_t plugNum, uint8_t id)
-{
-    uint8_t dataBuf[16] = {'\0'};
-    uint32_t _consumption;
-    ConnectorState *pConnState = (ConnectorState *)dataBuf;
-    static char vendorErrorCodeTmp[2][WARNING_CODE_SIZE] = {0};
-    int ret = PASS;
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(plugNum);
-
-    pConnState->ConnectorTemp = pDcChargingInfo->ConnectorTemp;
-    pConnState->ChillerTemp = pDcChargingInfo->ChillerTemp;
-    pConnState->PlugIn = pDcChargingInfo->ConnectorPlugIn;
-    pConnState->ConnectMode = pDcChargingInfo->SystemStatus;
-
-    if (pDcChargingInfo->SystemStatus <= S_AUTHORIZING) {
-        pConnState->State = CONN_ST_IDLE;    //idle
-        strncpy((char *)ShmOCPP16Data->StatusNotification[plugNum].VendorErrorCode,
-                "",
-                sizeof(ShmOCPP16Data->StatusNotification[plugNum].VendorErrorCode));
-
-        strncpy(&vendorErrorCodeTmp[plugNum][0], "", WARNING_CODE_SIZE);
-    } else if ((pDcChargingInfo->SystemStatus <= S_PREPARING_FOR_EVSE) ||
-               (pDcChargingInfo->SystemStatus == S_CCS_PRECHARGE_ST0) ||
-               (pDcChargingInfo->SystemStatus == S_CCS_PRECHARGE_ST1)) {
-        pConnState->State = CONN_ST_PREPARING;    //preparing
-    } else if (pDcChargingInfo->SystemStatus == S_CHARGING) {
-        pConnState->State = CONN_ST_CHARGING;    //charging
-    } else if (pDcChargingInfo->SystemStatus == S_TERMINATING ||
-            pDcChargingInfo->SystemStatus == S_COMPLETE) {
-        pConnState->State = CONN_ST_TERMINATING;    //terminating
-    } else if ((pDcChargingInfo->SystemStatus == S_ALARM) ||
-               (pDcChargingInfo->SystemStatus == S_FAULT)) {
-        pConnState->State = CONN_ST_ALARM;
-        strncpy((char *)pConnState->WarningCode,
-                (char *)ShmOCPP16Data->StatusNotification[plugNum].VendorErrorCode,
-                WARNING_CODE_SIZE);
-
-        if (strncmp(&vendorErrorCodeTmp[plugNum][0], "", WARNING_CODE_SIZE) == 0) {
-            strncpy(&vendorErrorCodeTmp[plugNum][0],
-                    (char *)ShmOCPP16Data->StatusNotification[plugNum].VendorErrorCode,
-                    WARNING_CODE_SIZE);
-            vendorErrorCodeTmp[plugNum][6] = '\0';
-            /*
-            log_info("1 ID = %d, VendorErrorCode = %s",
-                     plugNum,
-                     (char *)ShmOCPP16Data->StatusNotification[plugNum].VendorErrorCode);
-                     */
-        } else {
-            if (strncmp(&vendorErrorCodeTmp[plugNum][0],
-                        (char *)ShmOCPP16Data->StatusNotification[plugNum].VendorErrorCode,
-                        WARNING_CODE_SIZE) != 0
-               ) {
-                strncpy(&vendorErrorCodeTmp[plugNum][0],
-                        (char *)ShmOCPP16Data->StatusNotification[plugNum].VendorErrorCode,
-                        WARNING_CODE_SIZE);
-                vendorErrorCodeTmp[plugNum][6] = '\0';
-                /*
-                log_info("2 ID = %d, VendorErrorCode = %s",
-                         plugNum,
-                         (char *)ShmOCPP16Data->StatusNotification[plugNum].VendorErrorCode);
-                         */
-            }
-        }
-    }
-
-    memcpy((char*)&_consumption, (char*)&ShmDcCommonData->pGunInfo[plugNum].PowerConsumption, sizeof(float));
-    pConnState->consumption = ntohl(_consumption);
-
-    ret = composeSocketData(fd,
-                            id,
-                            OP_WRITE_DATA,
-                            REG_CONNECTOR_STATE,
-                            sizeof(dataBuf) - 1,
-                            &dataBuf[0]);
-    return ret;
-}
-
-static int writePlugInStatus(int fd, uint8_t plugNum, uint8_t id)
-{
-    int ret = PASS;
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(plugNum);
-    uint8_t dataBuf[2] = {pDcChargingInfo->ConnectorPlugIn, 0};
-
-    ret = composeSocketData(fd,
-                            id,
-                            OP_WRITE_DATA,
-                            REG_PLUG_IN_STATE,
-                            1,
-                            &dataBuf[0]);
-    return ret;
-}
-
-static int readSoftwareUpdate(int fd, uint8_t gunID)
-{
-    int ret = PASS;
-    uint8_t dataBuf[2] = {pSysInfo->FirmwareUpdate, 0};
-
-    ret = composeSocketData(fd,
-                            gunID,
-                            OP_READ_DATA,
-                            REG_SOFTWARE_UPDATE,
-                            1,
-                            &dataBuf[0]);
-
-    return ret;
-}
-
-static int writeChargingTarget(int fd, uint8_t plugNum, uint8_t id)
-{
-    int ret = PASS;
-    float ChargingVolt, ChargingAmp;
-    uint8_t dataBuf[4] = {0};
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(plugNum);
-
-    ChargingVolt = pDcChargingInfo->EvBatterytargetVoltage;
-    ChargingAmp = pDcChargingInfo->EvBatterytargetCurrent;
-    ChargingVolt *= 10;
-    ChargingAmp *= 10;
-
-    dataBuf[0] = ((uint16_t)ChargingVolt >> 8) & 0xFF;
-    dataBuf[1] = ((uint16_t)ChargingVolt) & 0xFF;
-    dataBuf[2] = ((uint16_t)ChargingAmp >> 8) & 0xFF;
-    dataBuf[3] = ((uint16_t)ChargingAmp) & 0xFF;
-
-    ret = composeSocketData(fd,
-                            id,
-                            OP_WRITE_DATA,
-                            REG_CHARGING_TARGET,
-                            sizeof(dataBuf),
-                            &dataBuf[0]);
-
-    return ret;
-}
-
-static int readChargingCapability(int fd, uint8_t id)
-{
-    int ret = PASS;
-
-    ret = composeSocketData(fd,
-                            id,
-                            OP_READ_DATA,
-                            REG_CHARGING_CAP,
-                            0,
-                            NULL);
-
-    return ret;
-}
-
-static int writeDispenserStatus(int fd, uint8_t gunID)
-{
-    uint8_t warningCount = 0;
-    uint8_t count = 0;
-    uint8_t CurWarnCodeTmp[10][6] = {0};
-    uint8_t PreWarnCodeTmp[10][6] = {0};
-    int ret = PASS;
-
-    if ((pSysWarning->WarningCount <= 0) &&
-            (gPreSysWarningInfo.WarningCount <= 0)) {
-        return FAIL;
-    }
-
-    warningCount = pSysWarning->WarningCount;
-    for (count = 0; count < warningCount; count++) {
-        memcpy(CurWarnCodeTmp[count], pSysWarning->WarningCode[count], WARNING_CODE_SIZE);
-    }
-
-    warningCount = gPreSysWarningInfo.WarningCount;
-    for (count = 0; count < warningCount; count++) {
-        memcpy(PreWarnCodeTmp[count], gPreSysWarningInfo.WarningCode[count], WARNING_CODE_SIZE);
-    }
-
-    if (strcmp((char *)&CurWarnCodeTmp[0], (char *)&PreWarnCodeTmp[0]) == 0) {
-        return FAIL;
-    }
-
-    ret = composeSocketData(fd,
-                            gunID,
-                            OP_WRITE_DATA,
-                            REG_DISPENSER_STATUS,
-                            strlen((char *)CurWarnCodeTmp),
-                            &CurWarnCodeTmp[0][0]);
-
-    return ret;
-}
-
-static int readPowerCabinetStatus(int fd, uint8_t gunID)
-{
-    int ret = PASS;
-
-    ret = composeSocketData(fd,
-                            gunID,
-                            OP_READ_DATA,
-                            REG_POWER_CABINET_STATUS,
-                            0,
-                            NULL);
-
-    return ret;
-}
-
-static int readConnectorID(int fd)
-{
-    int ret = PASS;
-
-    ret = composeSocketData(fd,
-                            ID_REGISTER,
-                            OP_READ_DATA,
-                            REG_CONNECTOR_ID,
-                            0,
-                            NULL);
-
-    return ret;
-}
-
-static int WriteModelName(int fd)
-{
-    int ret = PASS;
-    uint8_t Tmp = 0;
-    uint8_t TmpBuf[255] = {0};
-
-    memcpy(TmpBuf,
-           pSysConfig->ModelName,
-           strlen((char *)pSysConfig->ModelName));
-
-    Tmp = (uint8_t)(ShmPrimaryMcuData->InputDet.bits.Key2 << 2 |
-                    ShmPrimaryMcuData->InputDet.bits.Key1 << 1 |
-                    ShmPrimaryMcuData->InputDet.bits.Key0);
-
-    TmpBuf[strlen((char *)pSysConfig->ModelName)] = Tmp; //Dispenser switch value
-
-    ret = composeSocketData(fd,
-                            ID_REGISTER,
-                            OP_WRITE_DATA,
-                            REG_MODEL_NAME,
-                            strlen((char *)pSysConfig->ModelName) + 1,
-                            &TmpBuf[0]);
-
-    return ret;
-}
-
-static void calDisconnectCount(uint8_t *pValue, uint8_t maxCount)
-{
-    sleep(3); //wait 1 second
-
-    if ((*pValue) >= maxCount) {
-        setTcpStatus(ABNORMAL);
-    } else {
-        (*pValue)++;
-    }
-}
-
-static int CheckNetworkStatus(void)
-{
-    char *ipAddr = (char *)&pSysConfig->Eth0Interface.EthIpAddress;
-
-    //printf("Check network IP Header = %s\n", ipAddr);
-    if (strstr(ipAddr, CMP_ETH_IP_HEAD) != NULL) {
-        return 1;
-    }
-
-    return 0;
-}
-
-static void updateFirmwareProcess(int fd, uint8_t gunID, uint8_t totalConnCount)
-{
-    bool canUpdateFirmware = true;
-    uint8_t plugNum = 0;
-    uint8_t ackCount = 5;
-    struct timeb updateTime;
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(plugNum);
-
-    if (pSysWarning->Level != 2) {
-        for (plugNum = 0; plugNum < totalConnCount; plugNum++) {
-            if (pDcChargingInfo->SystemStatus != S_IDLE &&
-                    pDcChargingInfo->SystemStatus != S_RESERVATION &&
-                    pDcChargingInfo->SystemStatus != S_MAINTAIN) {
-                canUpdateFirmware = false;
-            }
-        }
-    }
-
-    if (canUpdateFirmware) {
-        ftime(&updateTime);
-        if (DiffTimeb(gRegTimeUp[0][REG_SOFTWARE_UPDATE], updateTime) > LOOP_RETRY_TIME * 5) {
-            readSoftwareUpdate(fd, gunID);
-            ftime(&gRegTimeUp[0][REG_SOFTWARE_UPDATE]);
-        }
-
-        if (pSysInfo->FirmwareUpdate == YES) {
-            while (ackCount != 0) {
-                ftime(&updateTime);
-                if (DiffTimeb(gRegTimeUp[0][REG_SOFTWARE_UPDATE], updateTime) > LOOP_RETRY_TIME / 2) {
-                    readSoftwareUpdate(fd, gunID);
-                    ftime(&gRegTimeUp[0][REG_SOFTWARE_UPDATE]);
-                    if (pSysInfo->FirmwareUpdate == NO) {
-                        ackCount--;
-                    }
-                }
-                usleep(128);
-            }
-        }
-    }
-}
-
-static void checkAuthorProcess(int fd, uint8_t plugNum)
-{
-    int ret = 0;
-    uint8_t gunID = 0;
-    struct timeb AuthNowTime;
-
-#if defined DD360Audi
-    gunID = gDoCommGblData.ConnectorID[pSysInfo->CurGunSelected];
-    //gunID = gDoCommGblData.ConnectorID[plugNum];
-    if (pSysConfig->AuthorisationMode) {
-        gunID = ID_REGISTER;
-        ShmSelectGunInfo->PricesInfo[pSysInfo->CurGunSelected].Balance = 0.0;
-    }
-#else
-    gunID = gDoCommGblData.ConnectorID[pSysInfo->CurGunSelected];
-
-    ShmSelectGunInfo->PricesInfo[pSysInfo->CurGunSelected].Balance = 0.0; //非Audi 不需要等待主櫃回報餘額
-#endif // DD360Audi
-
-    if ((ShmOCPP16Data->SpMsg.bits.AuthorizeReq == YES) ||
-            (pSysInfo->AuthorizeFlag == YES)) {
-        ftime(&AuthNowTime);
-
-        if (DiffTimeb(gRegTimeUp[plugNum][REG_USER_ID], AuthNowTime) > LOOP_RETRY_TIME) {
-            ret = writeUserID(fd,
-                              gunID,
-                              pSysConfig->UserId);
-            if (ret >= 0) {
-                memset(ShmOCPP16Data->Authorize.ResponseIdTagInfo.Status,
-                       0,
-                       sizeof(ShmOCPP16Data->Authorize.ResponseIdTagInfo.Status));
-
-                if (ret == 0) {
-                    strcpy((char *)ShmOCPP16Data->Authorize.ResponseIdTagInfo.Status, "Invalid");
-                } else {
-                    strcpy((char *)ShmOCPP16Data->Authorize.ResponseIdTagInfo.Status, "Accepted");
-                }
-
-                //printf("%d Balance = %.2f, %.2f\n",
-                //       plugNum,
-                //       ShmSelectGunInfo->PricesInfo[plugNum].Balance,
-                //       FAIL_BALANCE_PRICES);
-
-                if (ShmSelectGunInfo->PricesInfo[plugNum].Balance != FAIL_BALANCE_PRICES) {
-                    ShmOCPP16Data->SpMsg.bits.AuthorizeConf = YES; //isAuthorizedComplete
-                    ShmOCPP16Data->SpMsg.bits.AuthorizeReq  = NO;
-                    pSysInfo->AuthorizeFlag                 = NO;
-                    ShmPsuData->SystemAvailablePower        = NO;
-                    ShmPsuData->SystemPresentPsuQuantity    = NO;
-                }
-            }
-            ftime(&gRegTimeUp[plugNum][REG_USER_ID]);
-        }
-    }
-}
-void SetDispenserReq(uint8_t plugNum)
-{
-    if (gConnectorActReq[plugNum].bits.ChargingCancel != ShmDcCommonData->OperateIDLE[plugNum]) {
-        gConnectorActReq[plugNum].bits.ChargingCancel = ShmDcCommonData->OperateIDLE[plugNum];
-        memset(&ShmDcCommonData->ParkingInfo[plugNum],0,sizeof(RecordTransactionInfo));
-    }
-    if (gConnectorActReq[plugNum].bits.ParkingBillReq != ShmDcCommonData->pGunInfo[plugNum].ReqParkingBill) {
-        gConnectorActReq[plugNum].bits.ParkingBillReq = ShmDcCommonData->pGunInfo[plugNum].ReqParkingBill;
-    }
-}
-void clearDispenserReq(uint8_t plugNum)
-{
-    gConnectorActReq[plugNum].Value = 0;
-    if (gConnectorActReq[plugNum].bits.ChargingCancel != ShmDcCommonData->OperateIDLE[plugNum]) {
-        ShmDcCommonData->OperateIDLE[plugNum] = 0;
-        ShmDcCommonData->TransactionInfo[plugNum].LineStatus = _LINE_INIT;
-        log_info("Gun%d Return Cancel OK", plugNum);
-    }
-    if (gConnectorActReq[plugNum].bits.ParkingBillReq != ShmDcCommonData->pGunInfo[plugNum].ReqParkingBill) {
-        ShmDcCommonData->pGunInfo[plugNum].ReqParkingBill = 0;
-        log_info("Gun%d Parking Bill Requset OK", plugNum);
-    }
-}
-
-static int messageTrigger(int fd, uint8_t plugNum, uint8_t gunID, uint8_t curReg)
-{
-    int ret = DISPENSER_INIT_SUCC;
-    int isContinue = 1;
-    struct timeb NowTime;
-
-    while (isContinue) {
-        usleep(128);
-        ftime(&NowTime);
-
-        switch (curReg) {
-        case REG_MODEL_NAME:
-            if (WriteModelName(fd) == PASS) {
-                gDoCommGblData.DisConnCount = 0;
-                curReg = REG_CONNECTOR_ID;
-            } else {
-                sleep(1);
-            }
-            break;
-
-        case REG_CONNECTOR_ID:
-            if (readConnectorID(fd) == PASS) {
-                gDoCommGblData.DisConnCount = 0;
-                curReg = REG_REPORT_CSU_VERSION;
-            } else {
-                sleep(1);
-            }
-            break;
-
-        case REG_POWER_CABINET_STATUS:
-            if (DiffTimeb(gRegTimeUp[plugNum][curReg], NowTime) > LOOP_RETRY_TIME ||
-                    DiffTimeb(gRegTimeUp[plugNum][curReg], NowTime) < 0) {
-                readPowerCabinetStatus(fd, gunID);
-                ftime(&gRegTimeUp[plugNum][curReg]);
-            }
-            curReg = REG_DISPENSER_STATUS;
-            break;
-
-        case REG_DISPENSER_STATUS:
-            if (DiffTimeb(gRegTimeUp[plugNum][curReg], NowTime) > LOOP_RETRY_TIME ||
-                    DiffTimeb(gRegTimeUp[plugNum][curReg], NowTime) < 0) {
-                writeDispenserStatus(fd, gunID);
-                ftime(&gRegTimeUp[plugNum][curReg]);
-            }
-            curReg = REG_CHARGING_CAP;
-            break;
-
-        case REG_CHARGING_CAP:
-            if(gMoreInfoReq[plugNum].bits.FinalCostReq)
-            {
-                if (readChargingCapability(fd, gunID) == PASS) {
-					gMoreInfoReq[plugNum].bits.FinalCostReq = false;
-					pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(plugNum);
-					ShmDcCommonData->TransactionInfo[plugNum].Amount = pDcChargingInfo->ChargingFee;
-					ShmDcCommonData->finalcost_flag[plugNum] = TRUE;
-					log_info("Gun %d get final cost %f", plugNum, ShmDcCommonData->TransactionInfo[plugNum].Amount);
-                    if (ShmDcCommonData->is_AutoStart[plugNum] || ShmDcCommonData->is_RemoteStart[plugNum]) {
-                        ShmDcCommonData->PayPass_flag[plugNum] = TRUE;
-                        if (pSysInfo->CurGunSelected == plugNum )
-                            pSysInfo->SystemPage = _PAGE_COMPLETE;
-                    } else {
-                        UpdateDeductInfoStatus(plugNum, &ShmDcCommonData->TransactionInfo[plugNum]);
-                    }
-                }
-            }
-            curReg = REG_PLUG_IN_STATE;
-            break;
-
-        case REG_PLUG_IN_STATE:
-            if (DiffTimeb(gRegTimeUp[plugNum][curReg], NowTime) > LOOP_RETRY_TIME ||
-                    DiffTimeb(gRegTimeUp[plugNum][curReg], NowTime) < 0) {
-                writePlugInStatus(fd, plugNum, gunID);
-                ftime(&gRegTimeUp[plugNum][curReg]);
-            }
-            curReg = REG_CONNECTOR_STATE;
-            break;
-
-        case REG_CONNECTOR_STATE:
-            if (DiffTimeb(gRegTimeUp[plugNum][curReg], NowTime) > LOOP_RETRY_TIME ||
-                    DiffTimeb(gRegTimeUp[plugNum][curReg], NowTime) < 0) {
-                writeConnectorState(fd, plugNum, gunID);
-                ftime(&gRegTimeUp[plugNum][curReg]);
-            }
-            curReg = REG_DISPENSER_REQUEST;
-            break;
-        case REG_DISPENSER_REQUEST:
-            SetDispenserReq(plugNum);
-            if (gConnectorActReq[plugNum].Value != 0)
-            {
-                if (DiffTimeb(gRegTimeUp[plugNum][curReg], NowTime) > LOOP_RETRY_TIME ||
-                    DiffTimeb(gRegTimeUp[plugNum][curReg], NowTime) < 0) {
-                    if (writeDispenserRequest(fd, gunID, plugNum) == PASS)
-                    {
-                        clearDispenserReq(plugNum);
-                    }
-                    ftime(&gRegTimeUp[plugNum][curReg]);
-                }
-            }
-            curReg = REG_PARKING_STATUS;
-            break;
-        case REG_PARKING_STATUS:
-            if (gMoreInfoReq[plugNum].bits.ParkingReq) {
-                if (DiffTimeb(gRegTimeUp[plugNum][curReg], NowTime) > LOOP_RETRY_TIME ||
-                    DiffTimeb(gRegTimeUp[plugNum][curReg], NowTime) < 0) {
-                    readParkingStatus(fd, gunID);
-
-                    ftime(&gRegTimeUp[plugNum][curReg]);
-                }
-            }
-            curReg = REG_PARKING_BILL;
-            break;
-        case REG_PARKING_BILL:
-            if (ShmDcCommonData->pGunInfo[plugNum].ParkingStatus == _TCC_WAIT_PAY && ShmDcCommonData->pGunInfo[plugNum].GetParkingBill == FALSE &&
-                pSysInfo->SystemPage == _PAGE_PAYING) {
-                if (DiffTimeb(gRegTimeUp[plugNum][curReg], NowTime) > LOOP_RETRY_TIME ||
-                    DiffTimeb(gRegTimeUp[plugNum][curReg], NowTime) < 0) {
-                    //log_info("Ask Parking Bill ");
-                    if (readParkingBill(fd, gunID) == PASS)
-                    {
-                        ShmDcCommonData->pGunInfo[plugNum].GetParkingBill = TRUE;
-                        if (pSysInfo->CurGunSelected == plugNum &&
-                             ShmDcCommonData->pGunInfo[plugNum].ReqParkingBill)
-                            pSysInfo->SystemPage = _PAGE_BILL;
-                    }
-                    ftime(&gRegTimeUp[plugNum][curReg]);
-                }
-            }
-            curReg = REG_QRCODE_URL_INFO;
-            break;
-        case REG_QRCODE_URL_INFO:
-            //if (gunID == 1) {
-                if (DiffTimeb(gRegTimeUp[plugNum][curReg], NowTime) > (LOOP_RETRY_TIME * 10) ||
-                    DiffTimeb(gRegTimeUp[plugNum][curReg], NowTime) < 0
-                    ) {
-                    readQRcodeURLAndSystemDate(fd);
-                    ftime(&gRegTimeUp[plugNum][curReg]);
-                }
-            //}
-
-            //check misc command from power cabinet
-            if (gDoCommGblData.MiscCmd != 0) {
-                if (gDoCommGblData.MiscCmd != REG_MISC_CONTROL) {
-                    log_error("misc command failed = %x", gDoCommGblData.MiscCmd);
-                }
-                curReg = gDoCommGblData.MiscCmd;
-            } else if (gMoreInfoReq[plugNum].Value != 0) {
-                curReg = REG_RESERVATION_IDTAG;
-            } else {
-                isContinue = 0;
-            }
-            //curReg = REG_SOFTWARE_UPDATE;
-            break;
-        //case REG_USER_ID:
-        //    writeUserID(fd, gunID, uint8_t *pUserID);
-        //    break;
-
-        //case REG_CHARGING_PERMISSION:
-        //    readChargePermission(fd, gunID);
-        //    break;
-
-        case REG_MISC_CONTROL:
-            readMiscCommand(fd, gunID);
-
-            if(gMoreInfoReq[plugNum].Value == 0)
-            {
-                isContinue = 0;
-            }
-            else
-            {
-                curReg = REG_RESERVATION_IDTAG;
-            }
-            break;
-
-        case REG_REPORT_CSU_VERSION:
-        case REG_REPORT_OTHER_VERSION:
-            if (gDoCommGblData.MiscCmd != 0) {
-                writeCsuModuleVersion(fd);
-                writeOtherModuleVersion(fd);
-                clearMiscCommand();
-                isContinue = 0;
-            } else {
-                //power up write dispenser version and get power cabinet system ID
-                if ((writeCsuModuleVersion(fd) == PASS) &&
-                        (writeOtherModuleVersion(fd) == PASS) &&
-                        (readQRcodeURLAndSystemDate(fd) == PASS)
-                   ) {
-                    //gDoCommGblData.DisConnCount = 0;
-                    isContinue = 0;
-                }
-            }
-            break;
-
-        //case REG_PRESENT_CHARGING_INFO:
-        //    break;
-
-
-
-        //case REG_WAIT_PLUG_IT_STATE:
-        //    if (DiffTimeb(gRegTimeUp[plugNum][curReg], NowTime) > (LOOP_RETRY_TIME / 10)) {
-        //        writeWaitPlugItState(fd, gunID);
-        //        ftime(&gRegTimeUp[plugNum][curReg]);
-        //    }
-        //    isContinue = 0;
-        //    break;
-
-        //case REG_CABINET_DCM_VERSION:
-        //    break;
-
-        //case REG_CABINET_OTHER_VERSION:
-        //    break;
-
-        //case REG_TOTAL_PSU_QUANTITY:
-        //    break;
-
-        //case REG_PSU_VERSION:
-        //    break;
-
-        case REG_RESERVATION_IDTAG:
-            if(gMoreInfoReq[plugNum].bits.ReservationReq)
-            {
-                if (DiffTimeb(gRegTimeUp[plugNum][curReg], NowTime) > LOOP_RETRY_TIME ||
-                        DiffTimeb(gRegTimeUp[plugNum][curReg], NowTime) < 0) {
-                    if(readReservationState(fd, gunID) == PASS)
-                    {
-                        gMoreInfoReq[plugNum].bits.ReservationReq = ReservationState[plugNum] == NO ? NO : YES;
-                    }
-                    ftime(&gRegTimeUp[plugNum][curReg]);
-                }
-            }
-            curReg = REG_REMOTE_START_NO_ID;
-            break;
-
-        //case REG_DISPENSER_REQUEST:
-        //    break;
-
-        case REG_REMOTE_START_NO_ID:
-            if(gMoreInfoReq[plugNum].bits.RemoteStartNoID)
-            {
-                if (DiffTimeb(gRegTimeUp[plugNum][curReg], NowTime) > LOOP_RETRY_TIME ||
-                        DiffTimeb(gRegTimeUp[plugNum][curReg], NowTime) < 0) {
-                    if(readRemoteStartNoIDState(fd) == PASS)
-                    {
-                        gMoreInfoReq[plugNum].bits.RemoteStartNoID = RemoteStartNoIDState == NO ? NO : YES;
-                    }
-                    ftime(&gRegTimeUp[plugNum][curReg]);
-                }
-            }
-            curReg = REG_CHARGING_BILL;
-            break;
-        case REG_CHARGING_BILL:
-            if (gMoreInfoReq[plugNum].bits.ChargingBill) {
-                if (DiffTimeb(gRegTimeUp[plugNum][curReg], NowTime) > LOOP_RETRY_TIME ||
-                    DiffTimeb(gRegTimeUp[plugNum][curReg], NowTime) < 0) {
-                    if (readChargingBill(fd, gunID) == PASS)
-                    {
-                        log_info("Need to rededuct Bill");
-                        gMoreInfoReq[plugNum].bits.ChargingBill = false;
-                    }
-                    ftime(&gRegTimeUp[plugNum][curReg]);
-                }
-            }
-            curReg = REG_REFUND_AMOUNT;
-            break;
-        case REG_REFUND_AMOUNT:
-            curReg = REG_PREPAYMENT_INFO;
-            break;
-
-        case REG_PREPAYMENT_INFO:
-            curReg = REG_PAYMENT_FAIL_REASON;
-            break;
-
-        case REG_PAYMENT_FAIL_REASON:
-            curReg = REG_CONNECTOR_QR_CODE;
-            break;
-
-        case REG_CONNECTOR_QR_CODE:
-            curReg = REG_STATION_INFO;
-            break;
-
-        case REG_STATION_INFO:
-            if(gMoreInfoReq[plugNum].bits.StationInfoReq)
-            {
-                if (DiffTimeb(gRegTimeUp[plugNum][curReg], NowTime) > LOOP_RETRY_TIME ||
-                        DiffTimeb(gRegTimeUp[plugNum][curReg], NowTime) < 0) {
-
-                    if(readChargerStationInfo(fd) == PASS)
-                    {
-                        gMoreInfoReq[plugNum].bits.StationInfoReq = NO;
-                    }
-                    ftime(&gRegTimeUp[plugNum][curReg]);
-                }
-            }
-            isContinue = 0;
-            break;
-
-        default:
-            log_error("error curReg = %x", curReg);
-            gDoCommGblData.MiscCmd = 0;
-            gDoCommGblData.DisConnCount = CHECK_NETWORK_FAIL_COUNT;
-            isContinue = 0;
-            break;
-        }
-
-        if (gDoCommGblData.DisConnCount >= CHECK_NETWORK_FAIL_COUNT) {
-            return DISPENSER_SOCKET_RECONN;
-        }
-    }//for
-
-    return ret;
-}
-
-//static bool isDetectPlugin()
-//{
-//    if (pSysInfo->WaitForPlugit == YES) {
-//        return YES;
-//    }
-//
-//    return NO;
-//}
-static void systemStatusProcess(int fd, uint8_t totalGun, uint8_t plugNum, uint8_t gunID)
-{
-    uint8_t i = 0;
-    int j;
-    struct timeb AuthNowTime = {0};
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(plugNum);
-    int reupload_gunIndex[128] = {0};
-    RecordTransactionInfo reuploadInfo[128];
-    int reupload_num = 0;
-    struct timeb SeqEndTime;
-    struct tm* tm;
-
-    switch (pDcChargingInfo->SystemStatus) {
-    case S_IDLE:
-    case S_RESERVATION:
-    case S_MAINTAIN:
-    case S_ALARM:
-    case S_AUTHORIZING:
-        /*
-        if(pDcChargingInfo->SystemStatus != S_ALARM)
-        {
-            DeductResultReq[plugNum] = NO;
-        }
-        */
-
-        if (pDcChargingInfo->SystemStatus == S_ALARM) {
-            ftime(&AuthNowTime);
-            if (DiffTimeb(gRegTimeUp[plugNum][REG_PRESENT_CHARGING_INFO], AuthNowTime) > LOOP_RETRY_TIME ||
-                DiffTimeb(gRegTimeUp[plugNum][REG_PRESENT_CHARGING_INFO], AuthNowTime) < 0
-                ) {
-                writePresentChargingInfo(fd, plugNum, gunID);
-                ftime(&gRegTimeUp[plugNum][REG_PRESENT_CHARGING_INFO]);
-            }
-        }
-
-        checkAuthorProcess(fd, plugNum);
-
-        //authorization complete, write wait plug it state
-        if (ShmSelectGunInfo->PricesInfo[plugNum].Balance == FAIL_BALANCE_PRICES) {
-            break;
-        }
-
-        ftime(&SeqEndTime);
-        SeqEndTime.time = time(NULL);
-        tm = localtime(&SeqEndTime.time);
-        
-        if ((pSysInfo->SystemPage == _PAGE_IDLE || pSysInfo->SystemPage == _PAGE_SELECT_GUN) &&
-            !ShmDcCommonData->pGunInfo[plugNum].isParking) {
-            ftime(&AuthNowTime);
-            if (DiffTimeb(gRegTimeUp[plugNum][REG_DEDUCT_INFO], AuthNowTime) > LOOP_RETRY_TIME ||
-                DiffTimeb(gRegTimeUp[plugNum][REG_DEDUCT_INFO], AuthNowTime) < 0
-                ) {
-                // 充電費補上傳
-                reupload_num = DB_GetMultiReUploadDeduct(&reupload_gunIndex[0], &reuploadInfo[0]);
-                if (reupload_num >= 1 && reuploadInfo[0].ConnectorID != 0) {
-
-                    if (writeDeductInfo(fd, reuploadInfo[0].ConnectorID, reupload_gunIndex[0], &reuploadInfo[0]) == PASS) {
-                        reuploadInfo[0].IsUpload = TRUE;
-                        UpdateDeductInfoStatus(&reupload_gunIndex[0], &reuploadInfo[0]);
-                    } else
-                        log_info("Charging Information Reupload fail");
-
-                }
-                usleep(100);
-                // 佔位費補上傳
-                memset(reuploadInfo,0,sizeof(RecordTransactionInfo)*128);
-                reupload_num = DB_GetParkingDeductUpload(&reupload_gunIndex[0], &reuploadInfo[0]);
-                if (reupload_num >= 1 && reuploadInfo[0].ConnectorID != 0) {
-                    showDeductInfo(&reuploadInfo[0]);
-                    if (writeDeductInfo(fd, reuploadInfo[0].ConnectorID, reupload_gunIndex[0], &reuploadInfo[0]) == PASS) {
-                        reuploadInfo[0].IsUpload = YES;
-                        log_info("OccupancySN:[%s] upload set:%d",reuploadInfo[0].OccupancySN,reuploadInfo[0].IsUpload);
-                        UpdateParkingUpload(&reuploadInfo[0].OccupancySN[0],YES);
-                    } else
-                        log_info("Parking Information Reupload fail");
-
-                }
-                ftime(&gRegTimeUp[plugNum][REG_DEDUCT_INFO]);
-            }
-        }
-        
-        /*
-        if (pSysInfo->SystemPage == _PAGE_IDLE || pSysInfo->SystemPage == _PAGE_SELECT_GUN) {
-            reupload_num = DB_GetMultiReUploadDeduct(&reupload_gunIndex[0], &reuploadInfo[0]);
-            log_info("ReUpload number:%d", reupload_num);
-
-            for (j = 0; j < reupload_num; j++) {
-                log_info("Connector ID:%d Card No:%s", reuploadInfo[j].ConnectorID, reuploadInfo[j].pCreditCard.CardNo);
-
-                if (writeDeductInfo(fd, reuploadInfo[j].ConnectorID, reupload_gunIndex[j], &reuploadInfo[j]) == PASS) {
-                    log_info("Reupload Success");
-                    reuploadInfo[j].IsUpload = YES;
-                    UpdateDeductInfoStatus(reupload_gunIndex[j], &reuploadInfo[j]);
-                } else
-                    log_info("Reupload fail");
-            }
-        }*/
-
-        ftime(&AuthNowTime);
-        if (DiffTimeb(gRegTimeUp[plugNum][REG_WAIT_PLUG_IT_STATE], AuthNowTime) > (LOOP_RETRY_TIME / 10) ||
-                DiffTimeb(gRegTimeUp[plugNum][REG_WAIT_PLUG_IT_STATE], AuthNowTime) < 0
-           ) {
-            writeWaitPlugItState(fd, gunID, plugNum);
-            ftime(&gRegTimeUp[plugNum][REG_WAIT_PLUG_IT_STATE]);
-        }
-        /*
-        ftime(&AuthNowTime);
-        if (DiffTimeb(gRegTimeUp[plugNum][REG_MISC_CONTROL], AuthNowTime) > (LOOP_RETRY_TIME / 10) ||
-                DiffTimeb(gRegTimeUp[plugNum][REG_MISC_CONTROL], AuthNowTime) < 0
-           ) {
-            readMiscCommand(fd, gunID);
-            ftime(&gRegTimeUp[plugNum][REG_MISC_CONTROL]);
-        }
-        */
-        ftime(&AuthNowTime);
-        if (DiffTimeb(gRegTimeUp[plugNum][REG_CHARGING_CAP], AuthNowTime) > LOOP_RETRY_TIME ||
-                DiffTimeb(gRegTimeUp[plugNum][REG_CHARGING_CAP], AuthNowTime) < 0
-           ) {
-            readChargingCapability(fd, gunID);
-			if (pDcChargingInfo->PantographFlag)
-				writeGroundFaultDetection(fd, 0, gunID);
-            ftime(&gRegTimeUp[plugNum][REG_CHARGING_CAP]);
-        }
-
-        break;
-
-    case S_PREPARNING: //get permission
-        ftime(&AuthNowTime);
-        if (DiffTimeb(gRegTimeUp[plugNum][REG_CONNECTOR_STATE], AuthNowTime) > LOOP_RETRY_TIME ||
-                DiffTimeb(gRegTimeUp[plugNum][REG_CONNECTOR_STATE], AuthNowTime) < 0
-           ) {
-            writeConnectorState(fd, plugNum, gunID);
-            ftime(&gRegTimeUp[plugNum][REG_CONNECTOR_STATE]);
-        }
-
-        ftime(&AuthNowTime);
-        if (DiffTimeb(gRegTimeUp[plugNum][REG_CHARGING_PERMISSION], AuthNowTime) > LOOP_RETRY_TIME ||
-                DiffTimeb(gRegTimeUp[plugNum][REG_CHARGING_PERMISSION], AuthNowTime) < 0
-           ) {
-            if (readChargePermission(fd, gunID) && readChargingCapability(fd, gunID)) {
-                for (i = 0; i < totalGun; i++) {
-                    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(i);
-
-                    ShmPsuData->SystemAvailablePower += pDcChargingInfo->AvailableChargingPower;
-                }
-                ShmPsuData->SystemPresentPsuQuantity = (ShmPsuData->SystemAvailablePower / 30);
-            }
-            ftime(&gRegTimeUp[plugNum][REG_CHARGING_PERMISSION]);
-        }
-
-        ftime(&AuthNowTime);
-        if (DiffTimeb(gRegTimeUp[plugNum][REG_PRESENT_CHARGING_INFO], AuthNowTime) > LOOP_RETRY_TIME ||
-                DiffTimeb(gRegTimeUp[plugNum][REG_PRESENT_CHARGING_INFO], AuthNowTime) < 0
-           ) {
-            writePresentChargingInfo(fd, plugNum, gunID);
-			if (pDcChargingInfo->PantographFlag)
-				writeGroundFaultDetection(fd, 0, gunID);
-            ftime(&gRegTimeUp[plugNum][REG_PRESENT_CHARGING_INFO]);
-        }
-        break;
-
-    case S_PREPARING_FOR_EV://wait connector lock
-        ftime(&AuthNowTime);
-        if (DiffTimeb(gRegTimeUp[plugNum][REG_CHARGING_CAP], AuthNowTime) > LOOP_RETRY_TIME ||
-                DiffTimeb(gRegTimeUp[plugNum][REG_CHARGING_CAP], AuthNowTime) < 0
-           ) {
-            readChargingCapability(fd, gunID);
-            ftime(&gRegTimeUp[plugNum][REG_CHARGING_CAP]);
-        }
-
-        ftime(&AuthNowTime);
-        if (DiffTimeb(gRegTimeUp[plugNum][REG_CHARGING_PERMISSION], AuthNowTime) > LOOP_RETRY_TIME ||
-                DiffTimeb(gRegTimeUp[plugNum][REG_CHARGING_PERMISSION], AuthNowTime) < 0
-           ) {
-            if (readChargePermission(fd, gunID) == 0) {
-                log_info("S_PREPARING_FOR_EV Stop charging by power cabinet's permission = %d, %d",
-                         plugNum,
-                         REG_CHARGING_PERMISSION);
-                pDcChargingInfo->StopChargeFlag = POWER_CABINET_STOP_CHARGING;
-            }
-            ftime(&gRegTimeUp[plugNum][REG_CHARGING_PERMISSION]);
-        }
-
-        ftime(&AuthNowTime);
-        if (DiffTimeb(gRegTimeUp[plugNum][REG_PRESENT_CHARGING_INFO], AuthNowTime) > LOOP_RETRY_TIME ||
-                DiffTimeb(gRegTimeUp[plugNum][REG_PRESENT_CHARGING_INFO], AuthNowTime) < 0
-           ) {
-            writePresentChargingInfo(fd, plugNum, gunID);
-			if (pDcChargingInfo->PantographFlag)
-				writeGroundFaultDetection(fd, 0, gunID);
-            ftime(&gRegTimeUp[plugNum][REG_PRESENT_CHARGING_INFO]);
-        }
-        break;
-
-    case S_PREPARING_FOR_EVSE: //insaulation test
-    case S_CCS_PRECHARGE_ST0:
-    case S_CCS_PRECHARGE_ST1:
-
-        writeChargingTarget(fd, plugNum, gunID);
-
-		if (pDcChargingInfo->PantographFlag)
-			writeGroundFaultDetection(fd, 1, gunID);
-
-        ftime(&AuthNowTime);
-        if (DiffTimeb(gRegTimeUp[plugNum][REG_CHARGING_CAP], AuthNowTime) > LOOP_RETRY_TIME ||
-                DiffTimeb(gRegTimeUp[plugNum][REG_CHARGING_CAP], AuthNowTime) < 0
-           ) {
-            readChargingCapability(fd, gunID);
-            ftime(&gRegTimeUp[plugNum][REG_CHARGING_CAP]);
-        }
-
-        ftime(&AuthNowTime);
-        if (DiffTimeb(gRegTimeUp[plugNum][REG_CHARGING_PERMISSION], AuthNowTime) > LOOP_RETRY_TIME ||
-                DiffTimeb(gRegTimeUp[plugNum][REG_CHARGING_PERMISSION], AuthNowTime) < 0
-           ) {
-            if (readChargePermission(fd, gunID) == 0) {
-                log_info("S_PREPARING_FOR_EVSE Stop charging by power cabinet's permission = %d, %d",
-                         plugNum,
-                         REG_CHARGING_PERMISSION);
-                pDcChargingInfo->StopChargeFlag = POWER_CABINET_STOP_CHARGING;
-            }
-            ftime(&gRegTimeUp[plugNum][REG_CHARGING_PERMISSION]);
-        }
-
-        ftime(&AuthNowTime);
-        if (DiffTimeb(gRegTimeUp[plugNum][REG_PRESENT_CHARGING_INFO], AuthNowTime) > LOOP_RETRY_TIME ||
-                DiffTimeb(gRegTimeUp[plugNum][REG_PRESENT_CHARGING_INFO], AuthNowTime) < 0
-           ) {
-            writePresentChargingInfo(fd, plugNum, gunID);
-            ftime(&gRegTimeUp[plugNum][REG_PRESENT_CHARGING_INFO]);
-        }
-        break;
-
-    case S_CHARGING: //charging
-    case S_TERMINATING:
-        if(pDcChargingInfo->Type == _Type_GB || pDcChargingInfo->Type == _Type_Chademo)
-        {
-			if (pDcChargingInfo->PantographFlag)
-				writeGroundFaultDetection(fd, 0, gunID);
-        }
-        else
-        {
-			if (pDcChargingInfo->PantographFlag)
-				writeGroundFaultDetection(fd, 1, gunID);
-        }
-
-        ftime(&AuthNowTime);
-        if (DiffTimeb(gRegTimeUp[plugNum][REG_CHARGING_CAP], AuthNowTime) > LOOP_RETRY_TIME ||
-                DiffTimeb(gRegTimeUp[plugNum][REG_CHARGING_CAP], AuthNowTime) < 0
-           ) {
-            readChargingCapability(fd, gunID);
-            ftime(&gRegTimeUp[plugNum][REG_CHARGING_CAP]);
-        }
-
-        ftime(&AuthNowTime);
-        if (DiffTimeb(gRegTimeUp[plugNum][REG_CHARGING_PERMISSION], AuthNowTime) > LOOP_RETRY_TIME ||
-                DiffTimeb(gRegTimeUp[plugNum][REG_CHARGING_PERMISSION], AuthNowTime) < 0
-           ) {
-            if (readChargePermission(fd, gunID) == 0) {
-                log_info("Stop charging by power cabinet's permission = %d, %d",
-                         plugNum,
-                         REG_CHARGING_PERMISSION);
-                pDcChargingInfo->StopChargeFlag = POWER_CABINET_STOP_CHARGING;
-                //printf("%d StopChargeFlag = %d\n", plugNum, pDcChargingInfo->StopChargeFlag);
-            }
-            ftime(&gRegTimeUp[plugNum][REG_CHARGING_PERMISSION]);
-        }
-        writeChargingTarget(fd, plugNum, gunID);
-
-        ftime(&AuthNowTime);
-        if (DiffTimeb(gRegTimeUp[plugNum][REG_PRESENT_CHARGING_INFO], AuthNowTime) > LOOP_RETRY_TIME ||
-                DiffTimeb(gRegTimeUp[plugNum][REG_PRESENT_CHARGING_INFO], AuthNowTime) < 0
-           ) {
-            writePresentChargingInfo(fd, plugNum, gunID);
-            ftime(&gRegTimeUp[plugNum][REG_PRESENT_CHARGING_INFO]);
-        }
-
-        break;
-
-    case S_COMPLETE:
-        ftime(&AuthNowTime);
-        if (DiffTimeb(gRegTimeUp[plugNum][REG_CHARGING_CAP], AuthNowTime) > LOOP_RETRY_TIME ||
-                DiffTimeb(gRegTimeUp[plugNum][REG_CHARGING_CAP], AuthNowTime) < 0
-           ) {
-            readChargingCapability(fd, gunID);
-			if (pDcChargingInfo->PantographFlag)
-				writeGroundFaultDetection(fd, 0, gunID);
-            ftime(&gRegTimeUp[plugNum][REG_CHARGING_CAP]);
-        }
-
-        ftime(&AuthNowTime);
-        if (DiffTimeb(gRegTimeUp[plugNum][REG_PRESENT_CHARGING_INFO], AuthNowTime) > LOOP_RETRY_TIME ||
-            DiffTimeb(gRegTimeUp[plugNum][REG_PRESENT_CHARGING_INFO], AuthNowTime) < 0
-            ) {
-            writePresentChargingInfo(fd, plugNum, gunID);
-            ftime(&gRegTimeUp[plugNum][REG_PRESENT_CHARGING_INFO]);
-        }
-        break;
-
-    default:
-        break;
-    }
-}
-
-static int networkCreatePorcess(void)
-{
-    int fd = 0;
-    uint8_t discount = 0;
-    while (pSysInfo->SelfTestSeq != _STEST_COMPLETE) {
-        usleep(128);
-    }
-
-    setTcpStatus(ABNORMAL);
-
-    /**************** Check Network **********/
-    //log_info("Check Dispenser Network Information");
-    while (pSysInfo->SelfTestSeq != _STEST_COMPLETE) {
-        usleep(125);
-    }
-
-    while (!CheckNetworkStatus()) {
-        calDisconnectCount(&gDoCommGblData.DisConnCount, CHECK_NETWORK_FAIL_COUNT);
-        if( gDoCommGblData.DisConnCount != discount ) {
-            discount =  gDoCommGblData.DisConnCount;
-            log_error("disconnect count = % d", gDoCommGblData.DisConnCount);
-        }
-    }
-    log_info("Dispenser Network Information checked: IP = % s Netmask = % s, Gateway = % s",
-             pSysConfig->Eth0Interface.EthIpAddress,
-             pSysConfig->Eth0Interface.EthSubmaskAddress,
-             pSysConfig->Eth0Interface.EthGatewayAddress);
-
-    gDoCommGblData.DisConnCount = 0;
-    discount = 0;
-
-    /**************** Power cabinet connection **********/
-    log_info("Connect to Power Cabinet");
-    while ((fd = doCommConnToServer()) <= 0) {
-        calDisconnectCount(&gDoCommGblData.DisConnCount, CONNECT_SERVER_FAIL_COUNT);
-        if( gDoCommGblData.DisConnCount != discount && fd == -1) {
-            discount = gDoCommGblData.DisConnCount;
-            log_error("disconnect count = %d, fd = %d", gDoCommGblData.DisConnCount, fd);
-        }
-    }
-    log_info("Power cabinet connected(fd = % d): IP = % s Netmask = % s, Gateway = % s",
-             fd,
-             pSysConfig->Eth0Interface.EthIpAddress,
-             pSysConfig->Eth0Interface.EthSubmaskAddress,
-             pSysConfig->Eth0Interface.EthGatewayAddress);
-
-    gDoCommGblData.DisConnCount = 0;
-    destroySelectGun(DESTROY_ALL_SEL);
-
-    sleep(3);
-
-    setTcpStatus(NORMAL);
-
-    return fd;
-}
-
-void CreditCardProcess(int fd,int plugNum,int gunID,bool isPark, RecordTransactionInfo *pInfo)
-{
-    struct timeb AuthNowTime = {0};
-    //佔位費處理
-    if (isPark) {
-        if (pInfo->IsUpload == TRUE || (strcmp((char*)pInfo->pCreditCard.ApprovalNo,"") == 0) ||
-            pInfo->DeductResult != _TCC_ONLINEPAY_PASS)
-            return;
-        ftime(&AuthNowTime);
-        if (DiffTimeb(gRegTimeUp[plugNum][REG_DEDUCT_INFO], AuthNowTime) > LOOP_RETRY_TIME * 5 ||
-            DiffTimeb(gRegTimeUp[plugNum][REG_DEDUCT_INFO], AuthNowTime) < 0
-            ) {
-                if (writeDeductInfo(fd, gunID, plugNum, pInfo) == PASS) {
-                    pInfo->IsUpload = TRUE;
-                    UpdateParkingUpload(pInfo->OccupancySN,YES);
-                } else {
-                    log_info("Gun%d Write Deduct fail",plugNum);
-                }
-                ftime(&gRegTimeUp[plugNum][REG_DEDUCT_INFO]);
-            }
-
-        return;
-    }
-
-    // 充電費處理
-    if (pInfo->IsUpload == TRUE || (strcmp((char*)pInfo->pCreditCard.VemData,"") == 0) ||
-        pSysInfo->SystemPage == _PAGE_SENSING || ShmDcCommonData->is_RemoteStart[plugNum])
-        return;
-
-    if (pInfo->ConnectorID != 0) {
-        ftime(&AuthNowTime);
-        if (DiffTimeb(gRegTimeUp[plugNum][REG_DEDUCT_INFO], AuthNowTime) > LOOP_RETRY_TIME * 5 ||
-            DiffTimeb(gRegTimeUp[plugNum][REG_DEDUCT_INFO], AuthNowTime) < 0
-            ) {
-                if (writeDeductInfo(fd, gunID, plugNum, pInfo) == PASS) {
-                    pInfo->IsUpload = TRUE;
-
-                    UpdateDeductInfoStatus(plugNum, pInfo);
-
-                    if (pInfo->DeductResult == _DEDUCT_CANCEL) {
-                        memset(&pInfo->pCreditCard, 0x00, sizeof(TransInfo));
-                    }
-
-                    log_info("Gun%d writeDeductInfo finish",plugNum);
-                } else {
-                    log_info("Gun%d Write Deduct fail",plugNum);
-                }
-                ftime(&gRegTimeUp[plugNum][REG_DEDUCT_INFO]);
-            }
-    }
-}
-int main(int argc, char *argv[])
-{
-    uint8_t plugNum = 0, gunID = 0;
-    uint8_t index = 0;
-    uint8_t totalConnCount = 0;
-    uint8_t initDone = DISPENER_INIT_FAIL;
-    char tmpbuf[256] = {0};
-    int fd = 0;
-    int isContinue = 1;
-
-    InitSocketSigPipe();
-
-    /**************** Initialization **********/
-    if (CreateAllCsuShareMemory() == FAIL) {
-        log_error("create share memory error");
-        return FAIL;
-    }
-
-    MappingGunChargingInfo("DoComm Task");
-
-    pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
-    pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
-    pSysWarning = (struct WARNING_CODE_INFO *)GetShmSysWarningInfo();
-
-    pAlarmCode = (struct AlarmCodeData *)GetShmAlarmCodeData();
-    ShmPsuData = (struct PsuData *)GetShmPsuData();
-    ShmPrimaryMcuData = (struct PrimaryMcuData *)GetShmPrimaryMcuData();
-    ShmOCPP16Data = (struct OCPP16Data *)GetShmOCPP16Data();
-    ShmSelectGunInfo = (SelectGunInfo *)GetShmSelectGunInfo();
-    ShmDcCommonData = (DcCommonInfo *)GetShmDcCommonData();
-
-    totalConnCount = pSysConfig->TotalConnectorCount;
-
-    for (index = 0; index < totalConnCount; index++) {
-        clearPricesInfo(index);
-    }
-
-    //initial trigger message timer
-    for (index = 0; index < MAX_REGISTER_NUM; index++) {
-        ftime(&gRegTimeUp[0][index]);
-        usleep(128);
-        ftime(&gRegTimeUp[1][index]);
-        usleep(50000);
-    }
-
-    setTcpStatus(NORMAL);
-
-    while (isContinue) {
-        if (initDone == DISPENER_INIT_FAIL) {
-            fd = networkCreatePorcess();
-
-            initDone = messageTrigger(fd, 0, 0, REG_MODEL_NAME); //first trigger model name and connector id
-        } else {
-            plugNum = 0;
-            gunID = 0;
-            for (plugNum = 0; plugNum < totalConnCount; plugNum++) {
-                //checkAuthorProcess(fd, plugNum);
-
-                //plugNum : setup chargingData value for bottom layer
-                //gunID : connector Id from power cabinet, 1 = left gun, 2 = right gun,
-                gunID = gDoCommGblData.ConnectorID[plugNum];
-                systemStatusProcess(fd, totalConnCount, plugNum, gunID);
-                if (ShmDcCommonData->pGunInfo[plugNum].ParkingStatus)
-                    CreditCardProcess(fd, plugNum,gunID,TRUE, &ShmDcCommonData->ParkingInfo[plugNum]);
-                else
-                    CreditCardProcess(fd, plugNum,gunID,FALSE, &ShmDcCommonData->TransactionInfo[plugNum]);
-
-                initDone = messageTrigger(fd,
-                                          plugNum,
-                                          gunID,
-                                          REG_POWER_CABINET_STATUS);
-
-                if (initDone == DISPENSER_SOCKET_RECONN) {
-                    break;
-                }
-            }
-        }
-
-        if (initDone != DISPENSER_SOCKET_RECONN) {
-            //update dispenser firmware
-            updateFirmwareProcess(fd, gDoCommGblData.ConnectorID[0], totalConnCount);
-
-            usleep(100000);
-            continue;
-        }
-
-        //Ethernet error recovery handle
-        log_info("Disconnected from power cabinet...re-connecting");
-        setTcpStatus(ABNORMAL);
-
-
-        if (pSysConfig->Eth0Interface.EthDhcpClient == 0) {
-            system("pgrep -f \"udhcpc -i eth0\" | xargs kill");
-            sprintf(tmpbuf,
-                    "/sbin/udhcpc -i eth0 -x hostname:CSU3_%s -s /root/dhcp_script/eth0.script > /dev/null &",
-                    pSysConfig->SystemId);
-            system(tmpbuf);
-        }
-
-        gDoCommGblData.DisConnCount = 0;
-        gDoCommGblData.SeqNum = 0;
-
-        closeSocket(fd);
-        fd = 0;
-
-        initDone = DISPENER_INIT_FAIL;
-    }
-}
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdint.h>
+#include <stdarg.h>
+#include <string.h>
+#include <stdbool.h>
+
+#include <sys/time.h>
+#include <sys/timeb.h>
+#include <sys/socket.h>
+#include <sys/types.h>
+#include <sys/ipc.h>
+#include <sys/shm.h>
+
+#include <arpa/inet.h>
+#include <netinet/in.h>
+
+#include <assert.h>
+#include <time.h>
+#include <errno.h>
+#include <unistd.h>
+#include <signal.h>
+
+#include "../Log/log.h"
+#include "../ShareMemory/shmMem.h"
+#include "../Define/define.h"
+#include "../Config.h"
+#include "../SelectGun/SelectGun.h"
+#include "../timeout.h"
+#include "../DataBase/DataBase.h"
+#include "DoComm.h"
+
+//------------------------------------------------------------------------------
+static DoCommGblData gDoCommGblData             = {0};
+static MoreInfoReq gMoreInfoReq[2]              = {0};
+//static ChangePageReq gPageReq[2]                = {0};
+static ConnectorActReqVar gConnectorActReq[2]   = {0};
+static struct SysConfigData *pSysConfig         = NULL;
+static struct SysInfoData *pSysInfo             = NULL;
+static struct WARNING_CODE_INFO *pSysWarning    = NULL;
+static struct AlarmCodeData *pAlarmCode         = NULL;
+static struct PsuData *ShmPsuData               = NULL;
+static struct OCPP16Data *ShmOCPP16Data         = NULL;
+static struct PrimaryMcuData *ShmPrimaryMcuData = NULL;
+static SelectGunInfo *ShmSelectGunInfo          = NULL;
+static DcCommonInfo *ShmDcCommonData            = NULL;
+
+//static struct ChargingInfoData  *ChargingData[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY]
+static struct ChargingInfoData *pDcChargingInfo = NULL;
+static struct timeb             gRegTimeUp[2][MAX_REGISTER_NUM] = {0};
+static struct WARNING_CODE_INFO gPreSysWarningInfo = {0};
+
+// Hexdump
+char old_Hexdump[10240];
+static uint8_t RemoteStartNoIDState = NO;
+static uint8_t ReservationState[2] = {0};
+static char ReservationIdTag[2][32];
+//static uint8_t DeductResultReq[2] = {0};
+static int LineStatusCode[2] = {0};
+static unsigned int LedIntensity = 0;
+static int TimeZoneOffset = 0;
+uint8_t _isplugin[2] = { 0 };
+int gunstatus[2];
+//------------------------------------------------------------------------------
+static void removeFaultCodeToBuf(uint8_t *Code);
+static void addFaultCodeToBuf(uint8_t *Code);
+static int readMiscCommand(int fd, uint8_t id);
+static int writeCsuModuleVersion(int fd);
+static int writeGroundFaultDetection(int fd, uint8_t status, uint8_t id);
+
+//------------------------------------------------------------------------------
+//--- Common function ---
+//------------------------------------------------------------------------------
+void GetClockTime(struct timespec *_now_time, void *null)
+{
+    clock_gettime(CLOCK_MONOTONIC, _now_time);
+}
+
+static 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;
+}
+static void systemPageRestoreInit(void)
+{
+    int is_idle = TRUE;
+    int gunIndex;
+    for (gunIndex = 0; gunIndex < pSysConfig->TotalConnectorCount; gunIndex++) {
+        pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(gunIndex);
+        // 檢查電樁狀態是否為idle狀態
+        if ((pDcChargingInfo->SystemStatus >= S_AUTHORIZING &&
+            pDcChargingInfo->SystemStatus <= S_RESERVATION) ||
+            (pDcChargingInfo->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
+                pDcChargingInfo->SystemStatus <= S_CCS_PRECHARGE_ST0)) {
+            is_idle = FALSE;
+        }
+    }
+    if (is_idle)
+        pSysInfo->SystemPage = _PAGE_IDLE;
+    else
+        pSysInfo->SystemPage = _PAGE_SELECT_GUN;
+}
+/**
+ * [hexdump : check data]
+ * @Author   Jerry
+ * @DateTime 2018-12-21
+ * @param    p          [description]
+ * @param    size       [description]
+ */
+static void Hexdump(const void *p, size_t size)
+{
+    const uint8_t *c = p;
+    char message[10240] = {0};
+    uint32_t i = 0;
+    uint32_t message_len = 0;
+
+    assert(p);
+
+    //printf("Dumping %u bytes from %p:\n", size, p);
+    message_len += sprintf(&message[message_len], "\nDumping %u bytes from %p:\n",  (unsigned int)size, p);
+
+    while (size > 0) {
+        for (i = 0; i < 16; i++) {
+            if (i < size) {
+                //printf("%02x ", c[i]);
+                message_len += sprintf(&message[message_len], "%02x ", c[i]);
+            } else {
+                //printf("   ");
+                message_len += sprintf(&message[message_len], "   ");
+            }
+        }
+
+        for (i = 0; i < 16; i++) {
+            if (i < size) {
+                //printf("%c", c[i] >= 32 && c[i] < 127 ? c[i] : '.');
+                message_len += sprintf(&message[message_len], "%c", c[i] >= 32 && c[i] < 127 ? c[i] : '.');
+            } else {
+                //printf(" ");
+                message_len += sprintf(&message[message_len], " ");
+            }
+        }
+
+        //printf("\n");
+        message_len += sprintf(&message[message_len], "\n");
+        c += 16;
+
+        if (size <= 16) {
+            break;
+        }
+
+        size -= 16;
+    }
+
+    //message_len += sprintf(&message[message_len], "\n");
+    if( strcmp(old_Hexdump,message) != EQUAL ) {
+        log_info("%s", message);
+        strcpy(old_Hexdump,message);
+    }
+}
+
+static int string2ByteArray(char *input, uint8_t *output)
+{
+    int loop = 0;
+    int i = 0;
+
+    while (input[loop] != '\0') {
+        output[i++] = input[loop++];
+    }
+    output[loop] = '\0';
+
+    return loop + 1;
+}
+
+int string2Date(char* input, uint8_t* output)
+{
+    int loop = 0;
+    int i = 0;
+
+    while (input[loop] != '\0') {
+        loop++;
+    }
+    loop++;
+
+    while (input[loop] != '\0') {
+        output[i++] = input[loop++];
+    }
+    output[loop] = '\0';
+
+    return loop + 1;
+}
+static void unixSocketSigPipeHandle(int sig)
+{
+    //log_error("socket packet error %x", sig);
+}
+
+static void InitSocketSigPipe(void)
+{
+    struct sigaction action;
+
+    action.sa_handler = unixSocketSigPipeHandle;
+    sigemptyset(&action.sa_mask);
+    action.sa_flags = 0;
+    sigaction(SIGPIPE, &action, NULL);
+}
+
+//------------------------------------------------------------------------------
+static void setTcpStatus(uint8_t setValue)
+{
+    pAlarmCode->AlarmEvents.bits.DisconnectedFromDo = setValue;
+}
+
+//------------------------------------------------------------------------------
+//--- TCP socket function ---
+//------------------------------------------------------------------------------
+static int sendTcpSocket(int fd, uint8_t *data, uint16_t dataLen)
+{
+    int size = -1;
+    if (ShmDcCommonData->netdump) {
+        printf("\nTx Data:\t");
+        for(int i = 0 ; i < dataLen ; i++)
+            printf("[0x%2x] ",data[i]);
+    }
+    size = send(fd, data, dataLen , 0);
+    if ((size < 0) || (errno == EAGAIN)) {
+        if (size < 0) {
+            log_error("Send Socket Size = %d, EAGAIN error %d:%s", size, errno, strerror(errno));
+        }
+    }
+
+    return size;
+}
+
+static int recvTcpSocket(int fd, uint8_t *data, uint16_t dataLen)
+{
+    int size = -1;
+    uint8_t *pdata = (uint8_t *)data;
+    if (ShmDcCommonData->netdump) {
+        printf("\nRx Data:\t");
+        for(int i = 0 ; i < dataLen ; i++)
+            printf("[0x%2x] ",data[i]);
+    }
+    size = recv(fd, pdata, dataLen, MSG_WAITALL);
+    if ((errno == EAGAIN) || (size < 0)) {
+        log_error("Receive Socket Size = %d, EAGAIN error %d:%s", size, errno, strerror(errno));
+    }
+
+    return size;
+}
+
+static int getSO_ERROR(int fd)
+{
+    int err = 1;
+    socklen_t len = sizeof err;
+
+    if (-1 == getsockopt(fd, SOL_SOCKET, SO_ERROR, (char *)&err, &len)) {
+        log_error("getSO_ERROR");
+    }
+
+    if (err) {
+        errno = err;        // set errno to the socket SO_ERROR
+    }
+
+    return err;
+}
+
+static void closeSocket(int fd)        // *not* the Windows closesocket()
+{
+    if (fd < 0) {
+        return;
+    }
+
+    getSO_ERROR(fd); // first clear any errors, which can cause close to fail
+    if (shutdown(fd, SHUT_RDWR) < 0) { // secondly, terminate the 'reliable' delivery
+        if (errno != ENOTCONN && errno != EINVAL) { // SGI causes EINVAL
+            log_info("shutdown");
+        }
+    }
+
+    if (close(fd) < 0) { // finally call close()
+        log_info("client socket close");
+    }
+}
+
+static int doCommConnToServer(void)
+{
+    struct sockaddr_in dest;
+    struct timeval tv;
+    int flag;
+    int TcpSock = 0;
+
+    //if (TcpSock > 0) {
+    //    close(TcpSock);
+    //}
+
+    if ((TcpSock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
+        log_error("Open TCP socket NG");
+        return -1;
+    }
+
+    //flag = fcntl (TcpSock, F_GETFL, 0);
+    //if (flag >= 0) {
+    //    flag |= O_NONBLOCK;
+    //    fcntl(TcpSock, F_SETFL, flag );
+    //}
+
+    tv.tv_sec = 3;
+    tv.tv_usec = 0;
+    setsockopt(TcpSock, SOL_SOCKET,  SO_RCVTIMEO, &tv, sizeof(struct timeval)); //設定等待3s
+    setsockopt(TcpSock, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(struct timeval));  //設定傳送3s
+    flag = 1;
+    setsockopt(TcpSock, SOL_SOCKET, MSG_NOSIGNAL, &flag, sizeof(flag));
+
+    memset(&dest, 0, sizeof(dest));
+    dest.sin_family = AF_INET;
+    dest.sin_port = htons(DoTcpPort);
+    inet_aton(DoIPAddress, (struct in_addr *) &dest.sin_addr.s_addr);
+
+    if (connect(TcpSock, (struct sockaddr *) &dest, sizeof(dest)) != 0) {
+        close(TcpSock);
+        return -1;
+    }
+
+    return TcpSock;
+}
+
+//------------------------------------------------------------------------------
+//--- Audi select gun ---
+//------------------------------------------------------------------------------
+static void clearPricesInfo(uint8_t id)
+{
+    memset(&ShmSelectGunInfo->PricesInfo[id], 0, sizeof(PricesInfo));
+    ShmSelectGunInfo->PricesInfo[id].Balance = FAIL_BALANCE_PRICES;
+}
+
+static void ClearAuthorizedFlag(void)
+{
+    ShmOCPP16Data->SpMsg.bits.AuthorizeConf = NO;
+    pSysInfo->AuthorizeFlag = NO;
+}
+
+static void ClearDetectPluginFlag(int gunIndex)
+{
+    //pSysInfo->WaitForPlugit = NO;
+    ShmDcCommonData->pGunInfo[gunIndex].WaitForPlugit = NO;
+}
+
+static bool isDetectPlugin(int gunIndex)
+{
+    if (ShmDcCommonData->pGunInfo[gunIndex].WaitForPlugit == YES) {
+        return true;
+    }
+    /*
+    if (pSysInfo->WaitForPlugit == YES) {
+        return YES;
+    }
+    */
+    return NO;
+}
+
+static void destroySelectGun(uint8_t curGun)
+{
+    uint8_t i = 0;
+    uint8_t totalGun = pSysConfig->TotalConnectorCount;
+
+    if (curGun == DESTROY_ALL_SEL) {
+        ShmSelectGunInfo->SelGunInfo.RightGun = SEL_GUN_RELEASE;
+        ShmSelectGunInfo->SelGunInfo.LeftGun = SEL_GUN_RELEASE;
+
+        for (i = 0; i < totalGun; i++) {
+            pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(i);
+
+            pDcChargingInfo->TimeoutFlag = Timeout_None;
+            clearPricesInfo(i);
+        }
+        pSysInfo->CurGunSelected = 0;
+        strcpy((char *)pSysConfig->UserId, "");
+    }
+
+    //for charging timeout or complete
+    if ((curGun == LEFT_GUN_NUM) && (ShmSelectGunInfo->SelGunInfo.LeftGun != SEL_GUN_RELEASE)) {
+        ShmSelectGunInfo->SelGunInfo.LeftGun = SEL_GUN_RELEASE;
+        if (ShmOCPP16Data->SpMsg.bits.AuthorizeConf != NO) {
+            ClearAuthorizedFlag();
+        }
+        clearPricesInfo(curGun);
+    }
+
+    if ((curGun == RIGHT_GUN_NUM) && (ShmSelectGunInfo->SelGunInfo.RightGun != SEL_GUN_RELEASE)) {
+        if (ShmOCPP16Data->SpMsg.bits.AuthorizeConf != NO) {
+            ClearAuthorizedFlag();
+        }
+
+        clearPricesInfo(curGun);
+    }
+}
+
+static void setConfirmSelGun(uint8_t selGun)
+{
+    if (selGun == LEFT_GUN_NUM && ShmSelectGunInfo->SelGunInfo.LeftGun == SEL_GUN_RELEASE) {
+        ShmSelectGunInfo->SelGunInfo.LeftGun = SEL_GUN_CONFIRM;
+        //printf("confirmSelGun left");
+    } else if (selGun == RIGHT_GUN_NUM && ShmSelectGunInfo->SelGunInfo.RightGun == SEL_GUN_RELEASE) {
+        ShmSelectGunInfo->SelGunInfo.RightGun = SEL_GUN_CONFIRM;
+        //printf("confirmSelGun right");
+    }
+}
+
+//------------------------------------------------------------------------------
+//--- DoComm function ---
+//------------------------------------------------------------------------------
+static int compareOpcode(uint8_t opCode)
+{
+    if (opCode != OP_WAIT_RESPONSE) {
+        //log_error("response operative code fail");
+        return FAIL;
+    }
+
+    return PASS;
+}
+
+static int compareResult(uint8_t result)
+{
+    if (result != COMMAND_RESULT_OK) {
+        //log_error("response result fail");
+        return FAIL;
+    }
+
+    return PASS;
+}
+
+static int compareRegister(uint8_t srcReg, uint8_t destReg)
+{
+    if (srcReg != destReg) {
+        //log_error("response register fail");
+        return FAIL;
+    }
+
+    return PASS;
+}
+
+static float transPricesUnit(int prices)
+{
+    //printf("prices = %.2f", prices * PRICES_UNIT);
+    return (prices * PRICES_UNIT);
+}
+
+static void clearMiscCommand(void)
+{
+    gDoCommGblData.MiscCmd = 0;
+}
+int timecmp(uint8_t* time1, uint8_t* time2)
+{
+    for (int i = 0; i < strlen(time1); i++) {
+        if (time1[i] != time2[i]) {
+            return FALSE;
+        }
+    }
+    return TRUE;
+}
+static int qrCodeUrlInfoHandle(uint8_t *data)
+{
+    //int len = 0;
+    //char cmdBuf[128] = {0};
+    char localTime[128] = {0};
+    uint16_t timeLen = 0;
+    struct timeb SeqEndTime;
+    struct tm *tm;
+    char _setTime[50];
+    uint8_t cmdBuf[128];
+    int is_idle = TRUE;
+    if ((char *)&data[0] == '\0') {
+        log_error("QR code date error");
+        return FAIL;
+    }
+
+    //get local system time
+    ftime(&SeqEndTime);
+    SeqEndTime.time = time(NULL);
+    tm = localtime(&SeqEndTime.time);
+    timeLen = sprintf(localTime, "%04d-%02d-%02d %02d:%02d",
+                      tm->tm_year + 1900,
+                      tm->tm_mon + 1,
+                      tm->tm_mday,
+                      tm->tm_hour,
+                      tm->tm_min);
+    memset(pSysConfig->SystemId, '\0', sizeof(pSysConfig->SystemId));
+    string2ByteArray((char *)data, (uint8_t *)pSysConfig->SystemId);
+    //log_info("Data = %s SystemId = %s",data, pSysConfig->SystemId);
+    //copy QR code string
+    if (strncmp((char *)localTime, (char *)&data[0], timeLen - 2) != 0) {
+        // 充電槍IDLE時才更新系統時間
+        for (int i = 0; i < pSysConfig->TotalConnectorCount; i++) {
+            pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(i);
+            if (pDcChargingInfo->SystemStatus != S_IDLE)
+                is_idle = FALSE;
+        }
+
+        string2Date((char*)data, (uint8_t*)_setTime);
+        //printf("SystemId = %s", pSysConfig->SystemId);
+        if (!timecmp(localTime, _setTime) && is_idle) {
+            //log_info("Set Timer:%s", _setTime);
+            sprintf((char*)cmdBuf, "date -u -s \"%s\" >> /dev/null &", _setTime);
+            system((char*)cmdBuf);
+            system("hwclock -w -u");
+            system("hwclock -s");
+        }
+        
+    }
+    sprintf(ShmDcCommonData->PresentTime, "%04d/%02d/%02d",
+                      tm->tm_year + 1900,
+                      tm->tm_mon + 1,
+                      tm->tm_mday);
+
+    //if ((char *)&data[len] == '\0') {
+    //    log_error("power cabinet system date error");
+    //    return FAIL;
+    //}
+
+    //set system date
+    //if (strncmp((char *)localTime, (char *)&data[len], timeLen) != 0) {
+    //    sprintf(cmdBuf, "date -s \"%s\" >> /dev/null", (char *)&data[len]);
+    //    system(cmdBuf);
+    //    log_info("local time = %s, data time = %s", localTime, (char *)&data[len]);
+    //    ShmOCPP16Data->MsMsg.bits.ResetReq = YES;
+    //    strcpy((char *)ShmOCPP16Data->Reset.Type, "Soft");
+    //    sleep(3);
+    //    //gDoCommGblData.DisConnCount = CHECK_NETWORK_FAIL_COUNT;
+    //}
+
+    return PASS;
+}
+
+static int updateFirmwareHandle(uint8_t *imgName)
+{
+    int ret = PASS;
+    char cmdBuf[1024] = {0};
+
+    sprintf(cmdBuf, "/mnt/%s", imgName);
+    log_info("Program ready to check file %s", cmdBuf);
+    if ( access(cmdBuf, F_OK) != -1) {
+        log_info("File '%s' exist.", cmdBuf);
+        pSysInfo->FirmwareUpdate = YES;
+    } else {
+        log_info("File '%s' doesn't exist.", cmdBuf);
+        ret = FAIL;
+    }
+
+#if 0
+    char cmdBuf[1024] = {0};
+    int status = 0;
+
+    system("touch ./tftpUpdate.sh"); //創建shell
+    sprintf(cmdBuf, "echo tftp -gr %s -l %s/%s %s; > ./tftpUpdate.sh",
+            imgName,
+            IMAGE_FILE_PATH,
+            imgName,
+            DoIPAddress);
+    system("chmod +x ./tftpUpdate.sh"); //修改權限
+
+    status = system("sh tftpUpdate.sh"); //執行shell
+    if (-1 == status) {
+        printf("system error!");
+    } else {
+        printf("exit status value = [0x%x]", status);
+
+        if (WIFEXITED(status)) {
+            if (0 == WEXITSTATUS(status)) {
+                printf("run shell script successfully.");
+                pSysInfo->FirmwareUpdate = YES;
+            } else {
+                printf("run shell script fail, script exit code: %d", WEXITSTATUS(status));
+            }
+        } else {
+            printf("exit status = [%d]", WEXITSTATUS(status));
+        }
+    }
+
+    system("rm -rf ./tftpUpdate.sh"); //刪除shell
+#endif //0
+
+    return ret;
+}
+
+static int miscCommandHandle(uint8_t dataLen, uint8_t plugNum, uint8_t *data)
+{
+    int ret = PASS;
+    uint8_t i = 0, j = 0;
+    uint8_t cmdCount = (dataLen / 6);
+    uint16_t cmd = 0;
+    uint32_t value = 0;
+    float prices = 0;
+    MiscCommand *pMiscCmd = NULL;
+
+    if (cmdCount < 1) {
+        gDoCommGblData.MiscCmd = 0;
+        //printf("cmdCount fail = %d, data len = %d", cmdCount, dataLen);
+        return FAIL;
+    }
+
+    for (i = 0; i < cmdCount; i++) {
+        pMiscCmd = (MiscCommand *)data + i;
+        cmd = ntohs(pMiscCmd->CMD);
+        value = ntohl(*((uint32_t *)&pMiscCmd->Value[0]));
+        //log_info("misc command = %x, value = %d", cmd, value);
+
+        switch (cmd) {
+        //--- Execute parameter ---
+        case MISC_CMD_CONNECOTOR_TIMEOUT:
+            ShmSelectGunInfo->RemoteSetup.ConnectionTimeout = value;
+            log_info("connection timeout = %d", ShmSelectGunInfo->RemoteSetup.ConnectionTimeout);
+            clearMiscCommand();
+            break;
+
+        case MISC_CMD_OPERATIVE_STATE:
+            if ((value > YES) || (value < NO)) {
+                if (plugNum == 1) {
+                    clearMiscCommand();
+                }
+                break;
+            }
+
+            log_info("change availability plugNum = %d, value = %d", plugNum, value);
+            ShmOCPP16Data->CsMsg.bits[plugNum].ChangeAvailabilityReq = YES;
+            if (value == YES) {
+                strcpy((char *)ShmOCPP16Data->ChangeAvailability[plugNum].Type, "Operative");
+            } else if (value == NO) {
+                strcpy((char *)ShmOCPP16Data->ChangeAvailability[plugNum].Type, "Inoperative");
+            }
+
+            if (plugNum == 1) {
+                clearMiscCommand();
+            }
+            break;
+
+        case MISC_CMD_DEFAULT_PRICES:
+            prices = transPricesUnit((int)value);
+            log_info("default prices = %.2f", prices);
+            if (prices > 0)
+                ShmDcCommonData->ChargingRate = prices;
+            //pSysConfig->BillingData.isBilling = YES;
+            for (j = 0; j < 24; j++) {
+                pSysConfig->BillingData.Fee[j] = prices;
+            }
+
+            clearMiscCommand();
+            break;
+
+        case MISC_CMD_DEFAULT_CURRENCY:
+            if (value < 0) {
+                clearMiscCommand();
+                return FAIL;
+            }
+
+            //log_info("default currency = %s%c", (uint8_t *)Currency[value]);
+            log_info("default currency = %s", (uint8_t *)GetCurrency(value));
+            pSysConfig->BillingData.Currency = value;
+            clearMiscCommand();
+            break;
+
+        case MISC_CMD_ACCOUNT_BALANCE:
+            if (pSysInfo->CurGunSelected != (plugNum)) {
+                clearMiscCommand();
+                break;
+            }
+
+            ShmSelectGunInfo->PricesInfo[plugNum].Balance = transPricesUnit((int)value);
+            log_info("%d misc balance = %.2f", plugNum, ShmSelectGunInfo->PricesInfo[plugNum].Balance);
+            clearMiscCommand();
+            break;
+
+        case MISC_CMD_BACKEND_STATUS :
+            if (ShmSelectGunInfo->EthDevStatus.Backend != value) {
+                if (value == 0 || value == 2) {
+                    log_info("!!!!!!!!!!!!!! Backend Disconnect !!!!!!!!!!!!!!");
+                } else {
+                    log_info("!!!!!!!!!!!!!! Backend Connect !!!!!!!!!!!!!");
+                }
+            }
+            ShmSelectGunInfo->EthDevStatus.Backend = value;
+
+            break;
+
+        case MISC_CMD_ETHERNET_STATUS :
+            ShmSelectGunInfo->EthDevStatus.Ethernet = value;
+            break;
+
+        case MISC_CMD_WIFI_STATUS :
+            ShmSelectGunInfo->EthDevStatus.Wifi = value;
+            break;
+
+        case MISC_CMD_4G_STATUS :
+            ShmSelectGunInfo->EthDevStatus.FourG = value;
+            break;
+
+        case MISC_CMD_BILLING_INFO:
+            pSysConfig->BillingData.isBilling = value;
+            break;
+
+        case MISC_CMD_WEB_STOP_CHARGING:
+            pSysConfig->StopChargingByButton = value;
+            break;
+
+        //--- Control Dispenser ---
+        case MISC_CMD_HARDWARE_REBOOT:
+            if (value != YES) {
+                clearMiscCommand();
+                break;
+            }
+
+            log_info("Hardware reboot");
+            ShmOCPP16Data->MsMsg.bits.ResetReq = YES;
+            strcpy((char *)ShmOCPP16Data->Reset.Type, "Hard");
+            clearMiscCommand();
+            break;
+
+        case MISC_CMD_SOFTWARE_RESTART:
+            if (value != YES) {
+                clearMiscCommand();
+                break;
+            }
+
+            clearMiscCommand();
+            log_info("Software reboot");
+            ShmOCPP16Data->MsMsg.bits.ResetReq = YES;
+            strcpy((char *)ShmOCPP16Data->Reset.Type, "Soft");
+            break;
+
+        case MISC_CMD_REMOTE_START_CHARGING:
+            if (value != YES) {
+                if (plugNum == 1) {
+                    clearMiscCommand();
+                }
+                break;
+            }
+            log_info("Remote start charging plugNum = %d", plugNum);
+
+            //pSysInfo->CurGunSelected = (plugNum);
+            //pSysInfo->CurGunSelectedByAc = NO_DEFINE;
+            if (ShmDcCommonData->pGunInfo[plugNum].ParkingStatus) {
+                log_info("Gun%d is in the Parking status can't access Remote Start",plugNum);
+                break;
+            }
+            setConfirmSelGun(plugNum);
+
+            ShmOCPP16Data->CsMsg.bits[plugNum].RemoteStartTransactionReq = YES;
+            ShmSelectGunInfo->PricesInfo[plugNum].Balance = 0.00;
+
+            clearMiscCommand();
+            break;
+
+        case MISC_CMD_REMOTE_STOP_CHARGING:
+            if (value != YES) {
+                if (plugNum == 1) {
+                    clearMiscCommand();
+                }
+                break;
+            }
+
+            strcpy((char *)pSysConfig->UserId, "");
+            ClearDetectPluginFlag(plugNum);
+            //pSysInfo->SystemPage = _LCM_SELECT_GUN;
+            GetClockTime(&pSysInfo->SystemTimeoutTimer, NULL);
+            pSysInfo->SystemTimeoutFlag = Timeout_None;
+            destroySelectGun(plugNum);
+
+            clearMiscCommand();
+            break;
+
+        case MISC_CMD_REMOTE_UNLOCK:
+            if (value != YES) {
+                if (plugNum == 1) {
+                    clearMiscCommand();
+                }
+                break;
+            }
+
+            if (isDetectPlugin(plugNum) == YES) {
+                ClearDetectPluginFlag(plugNum);
+                strcpy((char *)pSysConfig->UserId, "");
+                //pSysInfo->SystemPage = _LCM_SELECT_GUN;
+                GetClockTime(&pSysInfo->SystemTimeoutTimer, NULL);
+                pSysInfo->SystemTimeoutFlag = Timeout_None;
+                destroySelectGun(plugNum);
+            } else {
+                pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(plugNum);
+
+                pDcChargingInfo->StopChargeFlag = POWER_CABINET_STOP_CHARGING;
+            }
+            break;
+        case MISC_CMD_AUTH_DISABLE:
+            pSysConfig->AuthorisationMode = value;
+            log_info("Auto Authorize Disable:%d", pSysConfig->AuthorisationMode);
+            //clearMiscCommand();
+        	break;
+        case MISC_CMD_EVCCID_ENABLE:
+            pSysConfig->isAuthrizeByEVCCID = value;
+            log_info("Authorize By EVCCID:%d",pSysConfig->isAuthrizeByEVCCID);
+            //clearMiscCommand();
+        	break;
+        case MISC_CMD_RESERVATION:
+            if(value != YES)
+            {
+                break;
+            }
+            gMoreInfoReq[plugNum].bits.ReservationReq = YES;
+            break;
+        case MISC_CMD_CHANGE_LCM_PAGE:
+            if(value == LCM_PAGE_REMOTE_START_NO_ID)
+            {
+                gMoreInfoReq[plugNum].bits.RemoteStartNoID = YES;
+            }
+            /*
+            if(value == LCM_PAGE_JOIN_LINE)
+            {
+                if(!gPageReq[plugNum].bits.JoinLine)
+                {
+                    log_info("Gun %d JoinLine page is trigger", plugNum);
+                }
+                gPageReq[plugNum].bits.JoinLine = YES;
+            }
+            if(value == LCM_PAGE_PAYMENT_SWITCH)
+            {
+                if(!gPageReq[plugNum].bits.PaymentSwitch)
+                {
+                    log_info("Gun %d PaymentSwitch page is trigger", plugNum);
+                }
+                gPageReq[plugNum].bits.PaymentSwitch = YES;
+            }*/
+            break;
+        case MISC_CMD_QR_CODE_REQ:
+            break;
+        case MISC_CMD_STATION_INFO_REQ:
+            if(value != YES)
+            {
+                break;
+            }
+            gMoreInfoReq[plugNum].bits.StationInfoReq = YES;
+            break;
+        case MISC_CMD_FINAL_COST_REQ:
+            if(value != YES)
+            {
+                break;
+            }
+            gMoreInfoReq[plugNum].bits.FinalCostReq = YES;
+            break;
+        case MISC_CMD_LINE_STATUS_REQ:
+            LineStatusCode[plugNum] = value;
+            if (ShmDcCommonData->pGunInfo[plugNum].ParkingStatus) {
+                ShmDcCommonData->ParkingInfo[plugNum].LineStatus = value;
+                log_info("Gun %d Line Status Code: %d", plugNum, LineStatusCode[plugNum]);
+                if (ShmDcCommonData->ParkingInfo[plugNum].LineStatus != value &&
+                    strcmp((char*)ShmDcCommonData->ParkingInfo[plugNum].pCreditCard.ApprovalNo, "") != 0) {
+                    UpdateDeductInfoStatus(plugNum,&ShmDcCommonData->ParkingInfo[plugNum]);
+                }
+            } else {
+                ShmDcCommonData->TransactionInfo[plugNum].LineStatus = value;
+                log_info("Gun %d Line Status Code: %d", plugNum, LineStatusCode[plugNum]);
+                if (ShmDcCommonData->TransactionInfo[plugNum].LineStatus != value &&
+                    strcmp((char*)ShmDcCommonData->TransactionInfo[plugNum].pCreditCard.ApprovalNo, "") != 0) {
+                    UpdateDeductInfoStatus(plugNum,&ShmDcCommonData->TransactionInfo[plugNum]);
+                }
+            }
+            break;
+        case MISC_CMD_LED_INTENSITY:
+            LedIntensity = value;
+            log_info("Led Intensity: %d", LedIntensity);
+            break;
+        case MISC_CMD_TIME_OFFSET:
+            TimeZoneOffset = value;
+            log_info("Time Zone Offset: %d", TimeZoneOffset);
+            ShmDcCommonData->TZOffset = TimeZoneOffset;
+            /*
+            if (TimeZoneOffset == 480) {
+                system("export TZ=CST-8");
+                log_info("Set Time Zone CST 8");
+            }
+            */
+            break;
+        case MISC_CMD_CHARGING_BILL:
+            if (value != YES)
+            {
+                break;
+            }
+            gMoreInfoReq[plugNum].bits.ChargingBill = YES;
+            ShmDcCommonData->PriceBill.gunIndex = plugNum;
+            break;
+        case MISC_CMD_PAKING_PRICES:
+            prices = transPricesUnit((int)value);
+            log_info("parking prices = %.2f", prices);
+            if (prices > 0)
+                ShmDcCommonData->ParkingRate = prices;
+            break;
+        case MISC_CMD_PARKING_STATUS:
+            if (gMoreInfoReq[plugNum].bits.ParkingReq != value) {
+                if (value == 0x0001 && pSysInfo->CurGunSelected == plugNum &&
+                    (pSysInfo->SystemPage >= _PAGE_BILL && pSysInfo->SystemPage <= _PAGE_CHARGING ||
+                    pSysInfo->SystemPage ==  _PAGE_DONATE_RIGHT)) {
+                    //log_info("Gun%d already enter charging operate. Don't Enter Parking mode!",plugNum);
+                    return FAIL;
+                }
+                if (value) {
+                    ShmDcCommonData->pGunInfo[plugNum].isParking = TRUE;
+                } else {
+                    log_info("Clear Parking Bill information");
+                    memset(&ShmDcCommonData->ParkingInfo[plugNum], 0, sizeof(RecordTransactionInfo));
+                    ShmDcCommonData->pGunInfo[plugNum].GetParkingBill = FALSE;
+                }
+                log_info("Parking Request %s",value ? "ON" : "OFF");
+            }
+            gMoreInfoReq[plugNum].bits.ParkingReq = value;
+            break;
+        default:
+            clearMiscCommand();
+            break;
+        }
+        usleep(128);
+    }
+
+    return ret;
+}
+void AddDispenserReq(uint8_t* buff, MiscCommand* req)
+{
+    buff[0] = (req->CMD >> 8) & 0xFF;
+    buff[1] = req->CMD & 0xFF;
+
+    buff[2] = req->Value[0];
+    buff[3] = req->Value[1];
+    buff[4] = req->Value[2];
+    buff[5] = req->Value[3];
+}
+
+
+static int chargingbillHandle(uint8_t* data, uint8_t gunIndex)
+{
+
+    ChargingBillInfo* pBillInfo = (ChargingBillInfo*)&data[0];
+    pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(gunIndex);
+
+    ShmDcCommonData->PriceBill.TotalCost = transPricesUnit(ntohl(pBillInfo->TotalCost));
+    ShmDcCommonData->PriceBill.Balance = transPricesUnit(ntohl(pBillInfo->Balance));
+    ShmDcCommonData->PriceBill.Discount = transPricesUnit(ntohl(pBillInfo->Discount));
+    ShmDcCommonData->PriceBill.TransactionId = ntohl(pBillInfo->Transaction);
+    ShmDcCommonData->PriceBill.EnergyCost = transPricesUnit(ntohl(pBillInfo->EnergyCost));
+    ShmDcCommonData->PriceBill.ParkingFee = transPricesUnit(ntohl(pBillInfo->ParkingFee));
+    pBillInfo->RemainAmount = ntohl(pBillInfo->RemainAmount);
+    memcpy((char*)&ShmDcCommonData->PriceBill.RemainAmount, (char*)&pBillInfo->RemainAmount, sizeof(uint32_t));
+    log_info("\t ******* TxId %d Charging Bill *******", ShmDcCommonData->PriceBill.TransactionId);
+    log_info("\t Total Cost = %.2f", ShmDcCommonData->PriceBill.TotalCost);
+    log_info("\t Discount = %.2f", ShmDcCommonData->PriceBill.Discount);
+    log_info("\t EnergyCost = %.2f", ShmDcCommonData->PriceBill.EnergyCost);
+    log_info("\t ParkingFee = %.2f", ShmDcCommonData->PriceBill.ParkingFee);
+    log_info("\t RemainAmount = %.2f", ShmDcCommonData->PriceBill.RemainAmount);
+    if (ShmDcCommonData->PriceBill.TransactionId != ShmDcCommonData->TransactionInfo[gunIndex].TransactionId)
+        UpdateRedeuctBill(ShmDcCommonData->PriceBill.TransactionId, ShmDcCommonData->PriceBill.TotalCost);
+}
+
+static int parkingbillHandle(uint8_t* data, uint8_t gunIndex)
+{
+
+    ParkingBillInfo* pBillInfo = (ParkingBillInfo*)&data[0];
+
+    ShmDcCommonData->ParkingInfo[gunIndex].Amount = transPricesUnit(ntohl(pBillInfo->ParkingFee));
+    ShmDcCommonData->ParkingInfo[gunIndex].ParkingDuration = ntohl(pBillInfo->Duration);
+    strcpy((char*)ShmDcCommonData->ParkingInfo[gunIndex].ParkingStartTime, (char*)&data[8]);
+    log_info("Gun%d Parking Bill: Amount:[%.2f], Duration:[%d], Start Time[%s]", gunIndex,
+                                                ShmDcCommonData->ParkingInfo[gunIndex].Amount,
+                                                ShmDcCommonData->ParkingInfo[gunIndex].ParkingDuration,
+                                                ShmDcCommonData->ParkingInfo[gunIndex].ParkingStartTime);
+}
+
+static int chargingcapabilityHandle(uint8_t *data, uint8_t plugNum)
+{
+    uint8_t addr = 0;
+    float MaxVolt, MaxCurrent, MaxPower;
+    static PricesInfo pricesInfo[2] = {0};
+    CapabilityInfo *pCapabilityInfo = NULL;
+    AccountInfo *pAccountInfo = NULL;
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(plugNum);
+
+    //--- charging capability information --------------------------------------
+    pCapabilityInfo = (CapabilityInfo *)&data[0];
+
+    MaxVolt = (float)(ntohs(pCapabilityInfo->OutputVoltage));
+    if (MaxVolt >= 0) {
+        if (MaxVolt > MAX_VOLTAGE) {
+            MaxVolt = MAX_VOLTAGE;
+        }
+        pDcChargingInfo->MaximumChargingVoltage = MaxVolt;
+    }
+
+    MaxCurrent = (float)(ntohs(pCapabilityInfo->OutputCurrent));
+    if (MaxCurrent >= 0) {
+        if (MaxCurrent > MAX_CURRENCY) {
+            MaxCurrent = MAX_CURRENCY;
+        }
+        pDcChargingInfo->AvailableChargingCurrent = MaxCurrent;
+    }
+
+    MaxPower = (float)(ntohs(pCapabilityInfo->OutputPower));
+    if (MaxPower >= 0) {
+        if (MaxPower > MAX_POWER) {
+            MaxPower = MAX_POWER;
+        }
+        pDcChargingInfo->AvailableChargingPower = MaxPower;
+    }
+    //MaxVolt = (float)(data[0] << 8 |data[1]);
+    //MaxCurrent = (float)(data[2] << 8 | data[3]);
+    //MaxPower = (float)(data[4] << 8 | data[5]);
+    //printf("MaxVolt=%f, MaxCurrent=%f, MaxPower=%f,", MaxVolt, MaxCurrent, MaxPower);
+
+    //--- user prices information ----------------------------------------------
+    addr = (sizeof(CapabilityInfo) - 2); //2 byte reserved
+    pAccountInfo = (AccountInfo *)&data[addr];
+
+    pSysConfig->BillingData.Currency = pAccountInfo->Currency;
+    ShmSelectGunInfo->PricesInfo[plugNum].UserPrices = transPricesUnit(ntohl(pAccountInfo->UserPrices));
+    pDcChargingInfo->ChargingFee                     = transPricesUnit(ntohl(pAccountInfo->TotalCost));
+    ShmSelectGunInfo->PricesInfo[plugNum].Balance    = transPricesUnit(ntohl(pAccountInfo->Balance));
+    ShmSelectGunInfo->PricesInfo[plugNum].Discount   = transPricesUnit(ntohl(pAccountInfo->Discount));
+    ShmSelectGunInfo->PricesInfo[plugNum].TransactionId = ntohl(pAccountInfo->Transaction);
+    ShmSelectGunInfo->PricesInfo[plugNum].EnergyCost = transPricesUnit(ntohl(pAccountInfo->EnergyCost));
+    ShmSelectGunInfo->PricesInfo[plugNum].ParkingFee = transPricesUnit(ntohl(pAccountInfo->ParkingFee));
+    pAccountInfo->RemainAmount = ntohl(pAccountInfo->RemainAmount);
+    memcpy((char*)&ShmSelectGunInfo->PricesInfo[plugNum].RemainAmount, (char*)&pAccountInfo->RemainAmount, sizeof(uint32_t));
+
+    if ((pricesInfo[plugNum].UserPrices != ShmSelectGunInfo->PricesInfo[plugNum].UserPrices) ||
+            (pricesInfo[plugNum].Balance != ShmSelectGunInfo->PricesInfo[plugNum].Balance) ||
+			(pricesInfo[plugNum].Discount != ShmSelectGunInfo->PricesInfo[plugNum].Discount) ||
+			(pricesInfo[plugNum].TransactionId != ShmSelectGunInfo->PricesInfo[plugNum].TransactionId)) {
+        pricesInfo[plugNum].UserPrices = ShmSelectGunInfo->PricesInfo[plugNum].UserPrices;
+        pricesInfo[plugNum].Balance = ShmSelectGunInfo->PricesInfo[plugNum].Balance;
+        pricesInfo[plugNum].Discount = ShmSelectGunInfo->PricesInfo[plugNum].Discount;
+        pricesInfo[plugNum].TransactionId = ShmSelectGunInfo->PricesInfo[plugNum].TransactionId;
+        pricesInfo[plugNum].ParkingFee = ShmSelectGunInfo->PricesInfo[plugNum].ParkingFee;
+        pricesInfo[plugNum].EnergyCost = ShmSelectGunInfo->PricesInfo[plugNum].EnergyCost;
+        pricesInfo[plugNum].RemainAmount = ShmSelectGunInfo->PricesInfo[plugNum].RemainAmount;
+        if (ShmSelectGunInfo->PricesInfo[plugNum].TransactionId != 0) {
+
+            ShmDcCommonData->TransactionInfo[plugNum].TransactionId = ShmSelectGunInfo->PricesInfo[plugNum].TransactionId;
+
+            UpdateDeductInfoStatus(plugNum, &ShmDcCommonData->TransactionInfo[plugNum]);
+
+            log_info("id = %d, transaction id = %d, user prices = %.2f, Discount = %.2f, Total cost = %.2f, Account balances = %.2f, currency = %s",
+                plugNum,
+                ShmSelectGunInfo->PricesInfo[plugNum].TransactionId,
+                ShmSelectGunInfo->PricesInfo[plugNum].UserPrices,
+                ShmSelectGunInfo->PricesInfo[plugNum].Discount,
+                pDcChargingInfo->ChargingFee,
+                ShmSelectGunInfo->PricesInfo[plugNum].Balance,
+                (uint8_t*)GetCurrency(pSysConfig->BillingData.Currency)
+            );
+            log_info("Total Cost:%.2f", pDcChargingInfo->ChargingFee);
+            log_info("Parking Fee:%.2f", ShmSelectGunInfo->PricesInfo[plugNum].ParkingFee);
+            log_info("Energy Cost:%.2f", ShmSelectGunInfo->PricesInfo[plugNum].EnergyCost);
+            log_info("Remain Amount:%.2f", ShmSelectGunInfo->PricesInfo[plugNum].RemainAmount);
+        }
+    }
+
+    return PASS;
+}
+
+static void addFaultCodeToBuf(uint8_t *Code)
+{
+    uint8_t warningCount = pSysWarning->WarningCount;
+
+    if (warningCount < 10) {
+        memcpy(&pSysWarning->WarningCode[warningCount][0],
+               Code,
+               strlen((char *)Code));
+        pSysWarning->WarningCount++;
+        log_info("Warning Code:%s",Code);
+    }
+}
+
+static void removeFaultCodeToBuf(uint8_t *Code)
+{
+    uint8_t find = 0x01;
+    uint8_t i = 0;
+    char _code[7] = {0};
+
+    sprintf(_code, "%s", Code);
+
+    // 把相關的錯誤碼一次移除,避免重複顯示
+    while (find) {
+        usleep(128);
+        find = 0x00;
+        for (i = 0; i < pSysWarning->WarningCount; i++) {
+            usleep(128);
+            if (find == 0x00) {
+                if (memcmp(&pSysWarning->WarningCode[i][0], _code, 7) == 0) {
+                    find = 0x01;
+                }
+            } else {
+                memcpy(&pSysWarning->WarningCode[i - 1][0],
+                       &pSysWarning->WarningCode[i][0], 7);
+            }
+        }
+
+        if (find) {
+            pSysWarning->WarningCount--;
+        }
+    }
+}
+
+bool CompareArrayIsZero(uint8_t *array, unsigned int array_size)
+{
+    uint8_t i;
+
+    if (array != NULL) {
+        for (i = 0; i < array_size; i++) {
+            if (array[i] != 0) {
+                return false;
+            }
+        }
+    }
+
+    return true;
+}
+static int powerCabinetStatusProcess(uint8_t dataLen, uint8_t *data)
+{
+    uint8_t ret = 0;
+    uint8_t i = 0;
+    uint8_t count = 0;
+    uint8_t EventCodeTmp[7] = {0};
+    uint8_t StatusArray[MAX_REGISTER_NUM][WARNING_CODE_SIZE] = {0};
+    uint8_t remaindLen = 0;
+    //uint8_t statusCodeError = 0;
+
+    if (dataLen > 0) {
+        //Hexdump((uint8_t *)data, dataLen);
+
+        remaindLen = dataLen % WARNING_CODE_SIZE;
+
+        if (remaindLen != 0) {
+            log_info("fail status code length =  %d", dataLen);
+            dataLen -= remaindLen;
+        }
+
+        if (dataLen < WARNING_CODE_SIZE) {
+            log_error("fail status code length = %d", dataLen);
+            //Hexdump(data, dataLen);
+            if (pSysWarning->WarningCount > 0) {
+                for (i = 0; i < pSysWarning->WarningCount; i++) {
+                    usleep(128);
+                    if (pSysWarning->WarningCode[i][1] >= '3' ||  //from backend or power cabinet
+                            (pSysWarning->WarningCode[i][0] >= 'B' &&
+                             pSysWarning->WarningCode[i][1] >= '4')) {
+                        memset(EventCodeTmp, 0, sizeof(EventCodeTmp));
+                        memcpy(EventCodeTmp,
+                               pSysWarning->WarningCode[i],
+                               sizeof(EventCodeTmp));
+                        removeFaultCodeToBuf(EventCodeTmp);
+                    }
+                }
+            }
+            return FAIL;
+        }
+
+        for (count = 0; count < dataLen; count += WARNING_CODE_SIZE) {
+            usleep(128);
+
+            if (strncmp((char *)&data[count + 1], "1", 1) != 0 &&
+                    strncmp((char *)&data[count + 1], "2", 1) != 0 &&
+                    strncmp((char *)&data[count + 1], "3", 1) != 0 &&
+                    (strncmp((char *)&data[count], "B", 1) != 0 &&
+                     strncmp((char *)&data[count + 1], "4", 1) != 0)
+               ) {
+                log_error("error status code = %s", (char *)&data[count]);
+                continue;
+            }
+
+            // misc command status code handle
+            if (strncmp((char *)&data[count], MISC_ST_MISC_CMD, WARNING_CODE_SIZE) == 0) {
+                gDoCommGblData.MiscCmd = REG_MISC_CONTROL;
+                memset((char *)&data[count], 0, WARNING_CODE_SIZE);
+                continue;
+            } else if (strncmp((char *)&data[count], MISC_ST_VERSION, WARNING_CODE_SIZE) == 0) {
+                gDoCommGblData.MiscCmd = REG_REPORT_CSU_VERSION;
+                memset((char *)&data[count], 0, WARNING_CODE_SIZE);
+                continue;
+            }
+
+            if (CompareArrayIsZero((uint8_t *)&data[count], WARNING_CODE_SIZE) == true) {
+                memset(EventCodeTmp, 0, sizeof(EventCodeTmp));
+                memcpy(EventCodeTmp, (char *)&data[count], sizeof(EventCodeTmp));
+                log_error("error status = %s", EventCodeTmp);
+                continue;
+            }
+
+            strncpy((char *)&StatusArray[count / WARNING_CODE_SIZE], (char *)&data[count], WARNING_CODE_SIZE);
+
+            ret = 0;
+            for (i = 0; i < pSysWarning->WarningCount; i++) {
+                usleep(128);
+                if (memcmp(&pSysWarning->WarningCode[i][0],
+                           StatusArray[count / WARNING_CODE_SIZE],
+                           WARNING_CODE_SIZE) == 0) {
+                    ret = 1;
+                    break;
+                }
+            }
+
+            if (ret == 0) {
+                addFaultCodeToBuf(StatusArray[count / WARNING_CODE_SIZE]);
+            }
+            //Rtn=StatusCodeProcessing(StatusArray[count/6]);
+        }
+    } else {
+        if (CompareArrayIsZero(data, WARNING_CODE_SIZE) == false) {
+            log_error("power cabinet status code data length is zero, but have data");
+            //Hexdump((uint8_t *)data, WARNING_CODE_SIZE);
+        }
+    }
+
+    for (i = 0; i < pSysWarning->WarningCount; i++) {
+        usleep(128);
+
+        if (pSysWarning->WarningCode[i][1] >= '3' || //from backend or power cabinet 0x33
+                (pSysWarning->WarningCode[i][0] >= 'B' &&
+                 pSysWarning->WarningCode[i][1] >= '4')) {
+            ret = 0;
+
+            for (count = 0; count < (dataLen / WARNING_CODE_SIZE); count++) {
+                usleep(128);
+                if (memcmp(&pSysWarning->WarningCode[i][0],
+                           StatusArray[count],
+                           WARNING_CODE_SIZE) == 0) {
+                    ret = 1;
+                    break;
+                }
+            }
+
+            if (ret == 0) {
+                memset(EventCodeTmp, 0, sizeof(EventCodeTmp));
+                memcpy(EventCodeTmp,
+                       pSysWarning->WarningCode[i],
+                       sizeof(EventCodeTmp));
+                removeFaultCodeToBuf(EventCodeTmp);
+            }
+        }
+    }
+
+    return PASS;
+}
+void CheckTaiwanEastWest(int id)
+{
+    ShmDcCommonData->TaiwanEast = TRUE;
+    //西半部
+    if (id >= 100 && id <= 116) {//台北
+        ShmDcCommonData->TaiwanEast = FALSE;
+    } else if (id >= 200 && id <= 206) { //基隆
+        ShmDcCommonData->TaiwanEast = FALSE;
+    } else if (id >= 207 && id <= 253) { //新北
+        ShmDcCommonData->TaiwanEast = FALSE;
+    } else if (id >= 300 && id <= 315) { //新竹
+        ShmDcCommonData->TaiwanEast = FALSE;
+    } else if (id >= 320 && id <= 338) { //桃園
+        ShmDcCommonData->TaiwanEast = FALSE;
+    } else if (id >= 350 && id <= 369) { //苗栗
+        ShmDcCommonData->TaiwanEast = FALSE;
+    } else if (id >= 400 && id <= 439) { //台中
+        ShmDcCommonData->TaiwanEast = FALSE;
+    } else if (id >= 500 && id <= 530) { //彰化
+        ShmDcCommonData->TaiwanEast = FALSE;
+    } else if (id >= 600 && id <= 625) { //嘉義
+        ShmDcCommonData->TaiwanEast = FALSE;
+    } else if (id >= 630 && id <= 655) { //雲林
+        ShmDcCommonData->TaiwanEast = FALSE;
+    } else if (id >= 700 && id <= 745) { //台南
+        ShmDcCommonData->TaiwanEast = FALSE;
+    } else if (id >= 800 && id <= 852) { //高雄
+        ShmDcCommonData->TaiwanEast = FALSE;
+    } else if (id >= 900 && id <= 947) { //屏東
+        ShmDcCommonData->TaiwanEast = FALSE;
+    } else if (id >= 880 && id <= 885) { //澎湖
+        ShmDcCommonData->TaiwanEast = FALSE;
+    // 東半部
+    } else if (id >= 540 && id <= 558) { //南投
+        ShmDcCommonData->TaiwanEast = TRUE;
+    } else if (id >= 260 && id <= 272) { //宜蘭
+        ShmDcCommonData->TaiwanEast = TRUE;
+    } else if (id >= 950 && id <= 966) { //台東
+        ShmDcCommonData->TaiwanEast = TRUE;
+    } else if (id >= 970 && id <= 983) { //花蓮
+        ShmDcCommonData->TaiwanEast = TRUE;
+    }
+}
+static int responsePackeHandle(int fd, uint8_t *pResult, uint8_t plugNum, uint8_t reg)
+{
+    int ret = PASS;
+    uint8_t rawDataLen = 0;
+    CsuResultPkt *pCsuResult = (CsuResultPkt *)pResult;
+    SoftwareUpdInfo *pSoftwareUpd = NULL;
+    PcPsuOutput *pPcPsuOutput = NULL;
+
+    //Hexdump((uint8_t *)pCsuResult, sizeof(CmdHead) + pCsuResult->Head.DataLen);
+    if (compareOpcode(pCsuResult->Head.OP) == FAIL ||
+            compareResult(pCsuResult->Data.Result) == FAIL ||
+            compareRegister(pCsuResult->Data.Register, reg) == FAIL) {
+        if (reg != REG_CHARGING_PERMISSION) {
+            return FAIL;
+        }
+    }
+
+    rawDataLen = (pCsuResult->Head.DataLen - 2); //2 byte = register and result byte
+
+    switch (pCsuResult->Data.Register) {
+    case REG_MODEL_NAME:
+        break;
+
+    case REG_CONNECTOR_ID:
+        gDoCommGblData.ConnectorID[0] = pCsuResult->Data.Data[0];
+        gDoCommGblData.ConnectorID[1] = pCsuResult->Data.Data[1];
+        log_info("OK (Left connector ID = %d, Right connector ID = %d)",
+                 pCsuResult->Data.Data[0],
+                 pCsuResult->Data.Data[1]);
+        ShmDcCommonData->ConnectorID[0] = pCsuResult->Data.Data[0];
+        ShmDcCommonData->ConnectorID[1] = pCsuResult->Data.Data[1];
+        break;
+
+    case REG_POWER_CABINET_STATUS:
+        ret = powerCabinetStatusProcess(rawDataLen, pCsuResult->Data.Data);
+        break;
+
+    case REG_DISPENSER_STATUS:
+        memset(&gPreSysWarningInfo, 0, sizeof(struct WARNING_CODE_INFO));
+        memcpy((uint8_t *)&gPreSysWarningInfo,
+               pSysWarning,
+               sizeof(struct WARNING_CODE_INFO));
+        break;
+
+    case REG_CHARGING_CAP:
+        chargingcapabilityHandle(pCsuResult->Data.Data, plugNum);
+        break;
+
+    case REG_CHARGING_TARGET:
+        break;
+
+    case REG_SOFTWARE_UPDATE:
+        pSoftwareUpd = (SoftwareUpdInfo *)&pCsuResult->Data.Data[0];
+
+        if ((strcmp((char *)pSoftwareUpd->ImgName, "") == 0) ||
+                (rawDataLen == 0) ||
+                pSoftwareUpd->UpdateState != 1) {
+            ret = FAIL;
+            break;
+        }
+
+        ret = FAIL;
+        ret = updateFirmwareHandle(pSoftwareUpd->ImgName);
+        break;
+
+    case REG_PLUG_IN_STATE:
+        break;
+
+    case REG_CONNECTOR_STATE:
+        break;
+
+    case REG_USER_ID:
+        //log_info("USER ID:%s", pCsuResult->Data.Data[0] == 1 ? "Accept" : "Reject" );
+        //if (pCsuResult->Data.Data[0] <= 0) {
+        //    return FAIL;
+        //}
+        if (pCsuResult->Data.Result == COMMAND_RESULT_NG) {
+            return COMMAND_RESULT_NG;
+        }
+
+        ShmSelectGunInfo->AuthorStateFromCabinet[plugNum] = pCsuResult->Data.Data[0];
+
+        return pCsuResult->Data.Data[0];
+        break;
+
+    case REG_CHARGING_PERMISSION:
+        //log_info("id = %d, result = %s, action = %s",
+        //           pCsuResult->Head.ID,
+        //           pCsuResult->Data.Result == 1 ? "OK" : "NG",
+        //           pCsuResult->Data.Data[0] == 1 ? "Permitted" : "NOT permitted");
+        if (pCsuResult->Data.Result == COMMAND_RESULT_NG) {
+            return COMMAND_RESULT_NG;
+        }
+
+        ShmSelectGunInfo->WaitDoCommPermission[plugNum] = pCsuResult->Data.Data[0];
+
+        return pCsuResult->Data.Data[0];
+        break;
+
+    case REG_MISC_CONTROL:
+        miscCommandHandle(rawDataLen, plugNum, pCsuResult->Data.Data);
+        break;
+
+    case REG_REPORT_CSU_VERSION:
+    case REG_REPORT_OTHER_VERSION:
+        break;
+
+    case REG_PRESENT_CHARGING_INFO:
+        pPcPsuOutput = (PcPsuOutput *)&pCsuResult->Data.Data[0];
+
+        ShmDcCommonData->PcPsuOutput[plugNum].Voltage = ntohs((uint16_t)pPcPsuOutput->Voltage);
+        ShmDcCommonData->PcPsuOutput[plugNum].Current = ntohs((uint16_t)pPcPsuOutput->Current);
+        //log_info("%d power cabinet PSU output vol = %f, cur = %f",
+        //         plugNum,
+        //         (float)ShmDcCommonData->PcPsuOutput[plugNum].Voltage,
+        //         (float)ShmDcCommonData->PcPsuOutput[plugNum].Current);
+        break;
+
+    case REG_QRCODE_URL_INFO:
+        ret = qrCodeUrlInfoHandle(pCsuResult->Data.Data);
+        break;
+
+    case REG_WAIT_PLUG_IT_STATE:
+        break;
+
+    case REG_Ground_Fault_Detection:
+        if (pCsuResult->Data.Result == COMMAND_RESULT_NG) {
+            return COMMAND_RESULT_NG;
+        }
+
+        //集電弓relay 不打開才能進入動作
+        pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(plugNum);
+        if(pDcChargingInfo->PantographFlag == YES)
+        {
+            GroundFaultDetection *gfd = (GroundFaultDetection *)&pCsuResult->Data.Data[0];
+            if(pDcChargingInfo->GroundFaultStatus != gfd->Status)
+            {
+                log_info("id = %d, GFD Result = %d",
+                           pCsuResult->Head.ID,
+                           gfd->Status);
+            }
+            pDcChargingInfo->GroundFaultStatus = gfd->Status;
+        }
+        break;
+
+    case REG_RESERVATION_IDTAG:
+        if (pCsuResult->Data.Result == COMMAND_RESULT_NG) {
+            return COMMAND_RESULT_NG;
+        }
+        uint8_t reservationState = pCsuResult->Data.Data[0] == YES ? YES : NO;
+        memset(&ReservationIdTag[plugNum][0], 0x00, 32);
+        ShmDcCommonData->pGunInfo[plugNum].ReservationStatus = reservationState;
+        if(reservationState)
+        {
+            strcpy(&ReservationIdTag[plugNum][0], (char *)&pCsuResult->Data.Data[1]);
+        }
+        if(reservationState != ReservationState[plugNum])
+        {
+            log_info("id = %d reservation is %s", pCsuResult->Head.ID, reservationState ? "trigger" : "expired");
+            if(reservationState)
+            {
+                log_info("id = %d reservation idTag: %s", pCsuResult->Head.ID, (char *)&ReservationIdTag[plugNum][0]);
+                strcpy(&ShmDcCommonData->pGunInfo[plugNum].ReservationID[0], (char*)&pCsuResult->Data.Data[1]);
+                if (pSysInfo->SystemPage == _PAGE_IDLE) {
+                    pSysInfo->SystemPage = _PAGE_SELECT_GUN;
+                }
+            } else {
+                strcpy(&ShmDcCommonData->pGunInfo[plugNum].ReservationID[0], "");
+            }
+        }
+        ReservationState[plugNum] = reservationState;
+        break;
+
+    case REG_REMOTE_START_NO_ID:
+        if (pCsuResult->Data.Result == COMMAND_RESULT_NG) {
+            return COMMAND_RESULT_NG;
+        }
+        uint8_t remoteStartNoIdState = pCsuResult->Data.Data[0] == YES ? YES : NO;
+        if(remoteStartNoIdState != RemoteStartNoIDState)
+        {
+            log_info("RemoteStartNoID is %s", remoteStartNoIdState ? "trigger" : "expired");
+        }
+        RemoteStartNoIDState = remoteStartNoIdState;
+        break;
+
+    case REG_STATION_INFO:
+        if (pCsuResult->Data.Result == COMMAND_RESULT_NG) {
+            return COMMAND_RESULT_NG;
+        }
+        StationVar _stationInfo;
+        memset((char *)&_stationInfo, 0x00, sizeof(StationVar));
+
+        _stationInfo.StationID = (pCsuResult->Data.Data[0] << 24) +
+                                 (pCsuResult->Data.Data[1] << 16) +
+                                 (pCsuResult->Data.Data[2] << 8) +
+                                 pCsuResult->Data.Data[3];
+        memcpy(_stationInfo.StationName, (char *)&pCsuResult->Data.Data[4], 64);
+        _stationInfo.WeatherID |= (pCsuResult->Data.Data[68] << 24);
+        _stationInfo.WeatherID |= (pCsuResult->Data.Data[69] << 16);
+        _stationInfo.WeatherID |= (pCsuResult->Data.Data[70] << 8);
+        _stationInfo.WeatherID |= pCsuResult->Data.Data[71];
+        uint8_t *pFloat = (uint8_t *)&_stationInfo.Temperature;
+        *(pFloat + 3) = pCsuResult->Data.Data[72];
+        *(pFloat + 2) = pCsuResult->Data.Data[73];
+        *(pFloat + 1) = pCsuResult->Data.Data[74];
+        *(pFloat) = pCsuResult->Data.Data[75];
+
+        ShmDcCommonData->WeatherID = _stationInfo.WeatherID;
+        ShmDcCommonData->Temperature = _stationInfo.Temperature;
+        ShmDcCommonData->Location = atoi(_stationInfo.StationName);
+
+        CheckTaiwanEastWest(ShmDcCommonData->Location);
+        
+        log_info("Station Name: %s, ID: %d, Weather: %d, Temperature: %.1f",
+                _stationInfo.StationName,
+                _stationInfo.StationID,
+                _stationInfo.WeatherID,
+                _stationInfo.Temperature);
+        
+        break;
+
+    case REG_DEDUCT_INFO:
+        if (pCsuResult->Data.Result == COMMAND_RESULT_NG) {
+            return COMMAND_RESULT_NG;
+        }
+        break;
+
+    case REG_POWER_CONSUMPTION_INFO:
+        if (pCsuResult->Data.Result == COMMAND_RESULT_NG) {
+            return COMMAND_RESULT_NG;
+        }
+
+        PowConsumValue* pValue = NULL;
+        pValue = (PowConsumValue*)&pCsuResult->Data.Data[0];
+
+        pValue->Gun1_Consumption = ntohl(pValue->Gun1_Consumption);
+        pValue->Gun2_Consumption = ntohl(pValue->Gun2_Consumption);
+        pValue->Gun3_Consumption = ntohl(pValue->Gun3_Consumption);
+        pValue->Gun4_Consumption = ntohl(pValue->Gun4_Consumption);
+        memcpy((char*)&ShmDcCommonData->pConsumption.Gun1_Consumption, (char*)&pValue->Gun1_Consumption, sizeof(uint32_t));
+        memcpy((char*)&ShmDcCommonData->pConsumption.Gun2_Consumption, (char*)&pValue->Gun2_Consumption, sizeof(uint32_t));
+        memcpy((char*)&ShmDcCommonData->pConsumption.Gun3_Consumption, (char*)&pValue->Gun3_Consumption, sizeof(uint32_t));
+        memcpy((char*)&ShmDcCommonData->pConsumption.Gun4_Consumption, (char*)&pValue->Gun4_Consumption, sizeof(uint32_t));
+
+        log_info("Gun1_Consumption:%f", ShmDcCommonData->pConsumption.Gun1_Consumption);
+        log_info("Gun2_Consumption:%f", ShmDcCommonData->pConsumption.Gun2_Consumption);
+        log_info("Gun3_Consumption:%f", ShmDcCommonData->pConsumption.Gun3_Consumption);
+        log_info("Gun4_Consumption:%f", ShmDcCommonData->pConsumption.Gun4_Consumption);
+
+
+        break;
+    case REG_READ_CHARGING_TIMESTAMP:
+        break;
+    case REG_CHARGING_BILL:
+        if (pCsuResult->Data.Result == COMMAND_RESULT_NG) {
+            return COMMAND_RESULT_NG;
+        }
+        chargingbillHandle(pCsuResult->Data.Data, plugNum);
+        break;
+    case REG_PARKING_STATUS:
+        pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(plugNum);
+        if (pCsuResult->Data.Result == COMMAND_RESULT_NG || pDcChargingInfo->TimeoutFlag == Timeout_ParkingLeave) {
+            return COMMAND_RESULT_NG;
+        }
+        char cmd[37];
+        memset(cmd,'\0',sizeof(cmd));
+        memcpy(cmd,&pCsuResult->Data.Data[1],36);
+        if (memcmp(ShmDcCommonData->ParkingInfo[plugNum].OccupancySN,&pCsuResult->Data.Data[1],36) != EQUAL) {
+            memcpy(ShmDcCommonData->ParkingInfo[plugNum].OccupancySN,&pCsuResult->Data.Data[1],36);
+        }
+        if (ShmDcCommonData->pGunInfo[plugNum].ParkingStatus != pCsuResult->Data.Data[0]) {
+            ShmDcCommonData->pGunInfo[plugNum].ParkingStatus = pCsuResult->Data.Data[0];
+            if (ShmDcCommonData->pGunInfo[plugNum].ParkingStatus == _TCC_PARKING_NONE )
+                ShmDcCommonData->pGunInfo[plugNum].isParking = FALSE;
+            else {
+                ShmDcCommonData->pGunInfo[plugNum].isParking = TRUE;
+            }
+            log_info("Gun%d Parking STATUS is [%d] SN:[%s] isParking:[%s]",plugNum,pCsuResult->Data.Data[0],cmd,(ShmDcCommonData->pGunInfo[plugNum].isParking ? "ON":"OFF"));
+            if (!ShmDcCommonData->pGunInfo[plugNum].ParkingStatus) {
+                //if (pSysInfo->CurGunSelected == plugNum)
+                //    systemPageRestoreInit();
+                gMoreInfoReq[plugNum].bits.ParkingReq = FALSE;
+                ShmDcCommonData->pGunInfo[plugNum].GetParkingBill = FALSE;
+                memset(&ShmDcCommonData->ParkingInfo[plugNum],0,sizeof(RecordTransactionInfo));
+                ShmDcCommonData->ParkingInfo[plugNum].IsUpload = TRUE;
+            } else {
+                if (pSysInfo->SystemPage >= _PAGE_BILL && pSysInfo->SystemPage <= _PAGE_PLUGIN) {
+                    if (pSysInfo->CurGunSelected == plugNum) {
+                        if (ShmDcCommonData->pGunInfo[plugNum].ParkingStatus == _TCC_PARKING_OCCUPENCY) {
+                            systemPageRestoreInit();
+                        } else if (ShmDcCommonData->pGunInfo[plugNum].ParkingStatus == _TCC_ONLINEPAY_PASS) {
+                            pSysInfo->SystemPage = _PAGE_PLUGIN;
+                        } else if (ShmDcCommonData->pGunInfo[plugNum].ParkingStatus == _TCC_ONLINEPAY_FAIL) {
+                            pSysInfo->SystemPage = _PAGE_AUTHORIZE_FAIL;
+                        }
+                    }
+                }
+            }
+        }
+
+        break;
+    case REG_PARKING_BILL:
+        if (pCsuResult->Data.Result == COMMAND_RESULT_NG) {
+            return COMMAND_RESULT_NG;
+        }
+        parkingbillHandle(pCsuResult->Data.Data, plugNum);
+        break;
+    default:
+        break;
+    }
+
+    return ret;
+}
+
+static int composeSocketData(int fd,
+                             uint8_t id,
+                             uint8_t opCode,
+                             uint8_t reg,
+                             uint8_t dataLen,
+                             uint8_t *data)
+{
+    int ret = PASS;
+    int size = 0;
+    int sendPktLen = 0;
+    uint8_t i = 0;
+    uint8_t plugNum = 0;
+    CsuCmdPkt csuCmdPkt = {0};
+    CsuResultPkt csuResult = {0};
+
+    csuCmdPkt.Head.SeqNum = gDoCommGblData.SeqNum++;
+    csuCmdPkt.Head.ID = id;
+    csuCmdPkt.Head.OP = opCode;
+    csuCmdPkt.Head.DataLen = dataLen + 1; //+1 for register byte
+
+    csuCmdPkt.Data.Register = reg;
+    if ((data != NULL) && (dataLen > 0)) {
+        memcpy(csuCmdPkt.Data.Data, data, dataLen);
+    }
+
+    sendPktLen = csuCmdPkt.Head.DataLen + sizeof(csuCmdPkt.Head);
+
+    //Hexdump((uint8_t *)&csuCmdPkt, sendPktLen);
+
+    //send command packet
+    if ((size = sendTcpSocket(fd, (uint8_t *)&csuCmdPkt, sendPktLen)) < 0) {
+        log_error("TCP socket reg=0x%x send packet fail = %d",reg, size);
+        gDoCommGblData.DisConnCount++;
+        return FAIL;
+    }
+
+    //receive result head
+    if ((size = recvTcpSocket(fd, (uint8_t *)&csuResult.Head, sizeof(csuResult.Head))) < 0) {
+        log_error("TCP socket reg=0x%x RX head fail = %d",reg, size);
+        gDoCommGblData.DisConnCount++;
+        return FAIL;
+    }
+
+    //receive result raw data
+    if ((size = recvTcpSocket(fd, (uint8_t *)&csuResult.Data, csuResult.Head.DataLen)) < 0) {
+        log_error("TCP socket reg=0x%x RX data fail = %d",reg, size);
+        gDoCommGblData.DisConnCount++;
+        return FAIL;
+    }
+
+    for (i = 0; i < sizeof(gDoCommGblData.ConnectorID); i++) {
+        if (id == gDoCommGblData.ConnectorID[i]) {
+            plugNum = i;
+            break;
+        }
+    }
+
+    ret = responsePackeHandle(fd, (uint8_t *)&csuResult, plugNum, csuCmdPkt.Data.Register);
+
+    gDoCommGblData.DisConnCount = 0; //送收資料沒有問題, 清除中斷網路計數
+
+    return ret;
+}
+static int writeDispenserRequest(int fd, uint8_t id, uint8_t gunIndex)
+{
+    int ret = PASS;
+    int count = 0;
+    MiscCommand dispenserReq;
+    uint8_t data[12] = { 0 };
+    if (gConnectorActReq[gunIndex].bits.ChargingCancel)
+    {
+        dispenserReq.CMD = DISPENSER_REQ_CHARGING_CANCEL;
+        dispenserReq.Value[0] = 0;
+        dispenserReq.Value[1] = 0;
+        dispenserReq.Value[2] = 0;
+        dispenserReq.Value[3] = 1;
+        AddDispenserReq(&data[count*6], &dispenserReq);
+        count++;
+        //log_info("Write Gun %d CHARGING_CANCEL", gunIndex);
+    }
+    if (gConnectorActReq[gunIndex].bits.ParkingBillReq) {
+        dispenserReq.CMD = DISPENSER_REQ_PARKING_BILL;
+        dispenserReq.Value[0] = 0;
+        dispenserReq.Value[1] = 0;
+        dispenserReq.Value[2] = 0;
+        dispenserReq.Value[3] = 1;
+        AddDispenserReq(&data[count*6], &dispenserReq);
+        count++;
+    }
+
+    if ((ret = composeSocketData(fd,
+                                id,
+                                OP_WRITE_DATA,
+                                REG_DISPENSER_REQUEST,
+                                (count * 6),
+                                &data[0])) == FAIL) {
+                                return ret;
+    }
+    return ret;
+}
+static int readReservationState(int fd, uint8_t id)
+{
+    int ret = PASS;
+
+    if ((ret = composeSocketData(fd,
+                                 id,
+                                 OP_READ_DATA,
+                                 REG_RESERVATION_IDTAG,
+                                 0,
+                                 NULL)) == FAIL) {
+        return ret;
+    }
+
+    return ret;
+}
+
+static int readRemoteStartNoIDState(int fd)
+{
+    int ret = PASS;
+
+    if ((ret = composeSocketData(fd,
+                                 ID_REGISTER,
+                                 OP_READ_DATA,
+                                 REG_REMOTE_START_NO_ID,
+                                 0,
+                                 NULL)) == FAIL) {
+        return ret;
+    }
+
+    return ret;
+}
+
+static int readChargingBill(int fd,int gunID)
+{
+    int ret = PASS;
+
+    if ((ret = composeSocketData(fd,
+                                gunID,
+                                OP_READ_DATA,
+                                REG_CHARGING_BILL,
+                                0,
+                                NULL)) == FAIL) {
+        return ret;
+    }
+
+    return ret;
+}
+
+static int readParkingStatus(int fd, int gunID)
+{
+    int ret = PASS;
+
+    if ((ret = composeSocketData(fd,
+                                gunID,
+                                OP_READ_DATA,
+                                REG_PARKING_STATUS,
+                                0,
+                                NULL)) == FAIL) {
+        return ret;
+    }
+
+    return ret;
+}
+
+static int readParkingBill(int fd, int gunID)
+{
+    int ret = PASS;
+
+    if ((ret = composeSocketData(fd,
+                                gunID,
+                                OP_READ_DATA,
+                                REG_PARKING_BILL,
+                                0,
+                                NULL)) == FAIL) {
+        return ret;
+    }
+
+    return ret;
+}
+
+static int readChargerStationInfo(int fd)
+{
+    int ret = PASS;
+
+    if ((ret = composeSocketData(fd,
+                                 ID_REGISTER,
+                                 OP_READ_DATA,
+                                 REG_STATION_INFO,
+                                 0,
+                                 NULL)) == FAIL) {
+        return ret;
+    }
+
+    return ret;
+}
+void showDeductInfo(RecordTransactionInfo* transactionInfo)
+{
+    char ApprovalNo[10];
+    char vemdata[65];
+    char cardno[21];
+    char OccupancySN[37];
+    memset(ApprovalNo,'\0',sizeof(ApprovalNo));
+    memset(vemdata,'\0',sizeof(vemdata));
+    memset(cardno,'\0',sizeof(cardno));
+    memset(OccupancySN,'\0',sizeof(OccupancySN));
+    memcpy(ApprovalNo,&transactionInfo->pCreditCard.ApprovalNo[0],9);
+    memcpy(vemdata,&transactionInfo->pCreditCard.VemData[0],64);
+    memcpy(cardno,&transactionInfo->pCreditCard.CardNo[0],20);
+    memcpy(OccupancySN,&transactionInfo->OccupancySN[0],36);
+    log_info("Gun[%d] TransactionId:%d DeductResult:%d IsDonateInvoice:%d Amount:%f Approva Num:[%s] VemData:[%s] CardNo:[%s] OccupancySN:[%s]",
+    		transactionInfo->ConnectorID,
+            transactionInfo->TransactionId,
+            transactionInfo->DeductResult,
+            transactionInfo->IsDonateInvoice,
+            transactionInfo->Amount,
+            ApprovalNo,
+            vemdata,
+            cardno,
+            OccupancySN);
+}
+
+
+static int writeDeductInfo(int fd, uint8_t id,uint8_t gunIndex, RecordTransactionInfo *transactionInfo)
+{
+    int ret = PASS;
+    if (ShmDcCommonData->DebugFlag &&
+        strcmp((char*)transactionInfo->pCreditCard.ApprovalNo ,"") == EQUAL) {
+        return ret;
+    }
+
+    uint8_t dataBuf[139] = {0};
+    //int i;
+
+    memset((char *)dataBuf, 0x00, sizeof(dataBuf));
+    dataBuf[0] = transactionInfo->DeductResult;
+    dataBuf[1] = transactionInfo->IsDonateInvoice;
+    dataBuf[2] = (transactionInfo->TransactionId >> 24) & 0xFF;
+    dataBuf[3] = (transactionInfo->TransactionId >> 16) & 0xFF;
+    dataBuf[4] = (transactionInfo->TransactionId >> 8) & 0xFF;
+    dataBuf[5] = (transactionInfo->TransactionId & 0xFF);
+
+    int amount = (int)(transactionInfo->Amount * 100);
+
+    dataBuf[6] = (amount >> 24) & 0xFF;
+    dataBuf[7] = (amount >> 16) & 0xFF;
+    dataBuf[8] = (amount >> 8) & 0xFF;
+    dataBuf[9] = (amount & 0xFF);
+    memcpy((char *)&dataBuf[10], &transactionInfo->pCreditCard.ApprovalNo[0],9);
+    memcpy((char *)&dataBuf[19], &transactionInfo->pCreditCard.VemData[0], 64);
+    memcpy((char*)&dataBuf[83], &transactionInfo->pCreditCard.CardNo[0], 20);
+    memcpy((char*)&dataBuf[103], &transactionInfo->OccupancySN[0], 36);
+
+    showDeductInfo(transactionInfo);
+    /*
+    log_info("Gun[%d] TransactionId:%d DeductResult:%d IsDonateInvoice:%d Amount:%f Approva Num:'%s' VemData:'%s' CardNo:'%s'",
+    		transactionInfo->ConnectorID,
+            transactionInfo->TransactionId,
+            transactionInfo->DeductResult,
+            transactionInfo->IsDonateInvoice,
+            transactionInfo->Amount,
+            transactionInfo->pCreditCard.ApprovalNo,
+            transactionInfo->pCreditCard.VemData,
+            transactionInfo->pCreditCard.CardNo);
+            */
+    // copy deduct result to dataBuf here
+
+    if ((ret = composeSocketData(fd,
+                                 id,
+                                 OP_WRITE_DATA,
+                                 REG_DEDUCT_INFO,
+                                 139,
+                                 &dataBuf[0])) == FAIL) {
+        return ret;
+    }
+
+    return ret;
+}
+
+static int writeWaitPlugItState(int fd, uint8_t id,uint8_t gunIndex)
+{
+    int ret = PASS;
+    uint8_t data[2] = { ShmDcCommonData->pGunInfo[gunIndex].WaitForPlugit, 0};
+    if (_isplugin[gunIndex] != ShmDcCommonData->pGunInfo[gunIndex].WaitForPlugit) {
+        //log_info("Wait Gun%d for plug:%s", gunIndex, ShmDcCommonData->pGunInfo[gunIndex].WaitForPlugit == 0 ? "disable" : "enable");
+        _isplugin[gunIndex] = ShmDcCommonData->pGunInfo[gunIndex].WaitForPlugit;
+    }
+    //printf("WaitForPlugit = %d", pSysInfo->WaitForPlugit);
+
+    if ((ret = composeSocketData(fd,
+                                 id,
+                                 OP_WRITE_DATA,
+                                 REG_WAIT_PLUG_IT_STATE,
+                                 1,
+                                 &data[0])) == FAIL) {
+        return ret;
+    }
+
+    return ret;
+}
+
+static int readQRcodeURLAndSystemDate(int fd)
+{
+    int ret = PASS;
+
+    ret = composeSocketData(fd,
+                            ID_REGISTER,
+                            OP_READ_DATA,
+                            REG_QRCODE_URL_INFO,
+                            0,
+                            NULL);
+    return ret;
+}
+
+static int writePresentChargingInfo(int fd, uint8_t plugNum, uint8_t id)
+{
+    int ret = PASS;
+    uint8_t dataBuf[16] = {0};
+    PreChargingInfo *pPreChargingInfo = (PreChargingInfo *)dataBuf;
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(plugNum);
+
+    if(pDcChargingInfo->PantographFlag == NO)
+    {
+        pPreChargingInfo->PresentChargingVoltage = htons((uint16_t)(pDcChargingInfo->PresentChargingVoltage * 10));
+        pPreChargingInfo->PresentChargingCurrent = htons((uint16_t)(pDcChargingInfo->PresentChargingCurrent * 10));
+    }
+    else
+    {
+        pPreChargingInfo->PresentChargingVoltage = htons((uint16_t)(ShmDcCommonData->PcPsuOutput[plugNum].Voltage));
+        pPreChargingInfo->PresentChargingCurrent = htons((uint16_t)(ShmDcCommonData->PcPsuOutput[plugNum].Current));
+    }
+    pPreChargingInfo->RemainChargingDuration = htonl(pDcChargingInfo->RemainChargingDuration);
+    pPreChargingInfo->EvBatterySoc = pDcChargingInfo->EvBatterySoc;
+
+    ret = composeSocketData(fd,
+                            id,
+                            OP_WRITE_DATA,
+                            REG_PRESENT_CHARGING_INFO,
+                            sizeof(PreChargingInfo),
+                            (uint8_t *)pPreChargingInfo);
+    return ret;
+}
+
+static int writeOtherModuleVersion(int fd)
+{
+    int ret = PASS;
+    uint8_t data[255] = {0};
+    uint8_t dataLen = 0;
+
+    //report other module version message
+    memcpy(&data[dataLen], pSysInfo->FanModuleFwRev, VERSION_BUF_SIZE);
+    dataLen += VERSION_BUF_SIZE;
+    memcpy(&data[dataLen], pSysInfo->RelayModuleFwRev, VERSION_BUF_SIZE);
+    dataLen += VERSION_BUF_SIZE;
+    memcpy(&data[dataLen], pSysInfo->Connector1FwRev, VERSION_BUF_SIZE);
+    dataLen += VERSION_BUF_SIZE;
+    memcpy(&data[dataLen], pSysInfo->Connector2FwRev, VERSION_BUF_SIZE);
+    dataLen += VERSION_BUF_SIZE;
+    memcpy(&data[dataLen], pSysInfo->LedModuleFwRev, VERSION_BUF_SIZE);
+    dataLen += VERSION_BUF_SIZE;
+
+    ret = composeSocketData(fd,
+                            ID_REGISTER,
+                            OP_WRITE_DATA,
+                            REG_REPORT_OTHER_VERSION,
+                            dataLen,
+                            &data[0]);
+
+    return ret;
+}
+
+static int writeCsuModuleVersion(int fd)
+{
+    int ret = PASS;
+    uint8_t data[255] = {0};
+    uint8_t dataLen = 0;
+
+    //report CSU platform version message
+    memcpy(&data[dataLen], pSysInfo->CsuBootLoadFwRev, VERSION_BUF_SIZE);
+    dataLen += VERSION_BUF_SIZE;
+    memcpy(&data[dataLen], pSysInfo->CsuKernelFwRev, VERSION_BUF_SIZE);
+    dataLen += VERSION_BUF_SIZE;
+    memcpy(&data[dataLen], pSysInfo->CsuRootFsFwRev, VERSION_BUF_SIZE);
+    dataLen += VERSION_BUF_SIZE;
+    memcpy(&data[dataLen], pSysInfo->CsuPrimFwRev, VERSION_BUF_SIZE);
+    dataLen += VERSION_BUF_SIZE;
+
+    ret = composeSocketData(fd,
+                            ID_REGISTER,
+                            OP_WRITE_DATA,
+                            REG_REPORT_CSU_VERSION,
+                            dataLen,
+                            &data[0]);
+
+    return ret;
+}
+
+static int readMiscCommand(int fd, uint8_t id)
+{
+    int ret = PASS;
+
+    ret = composeSocketData(fd,
+                            id,
+                            OP_READ_DATA,
+                            REG_MISC_CONTROL,
+                            0,
+                            NULL);
+
+    return ret;
+}
+
+static int readChargePermission(int fd, uint8_t id)
+{
+    return composeSocketData(fd,
+                             id,
+                             OP_READ_DATA,
+                             REG_CHARGING_PERMISSION,
+                             0,
+                             NULL);
+}
+
+static int writeGroundFaultDetection(int fd, uint8_t status, uint8_t id)
+{
+    int ret = PASS;
+    uint8_t dataBuf[1] = {status};
+    ret = composeSocketData(fd,
+                            id,
+                            OP_WRITE_DATA,
+                            REG_Ground_Fault_Detection,
+                            1,
+                            &dataBuf[0]);
+    return ret;
+}
+
+static int writeUserID(int fd, uint8_t id, uint8_t *pUserID)
+{
+    if ((strlen((char *)pUserID) <= 0) || (pUserID == NULL)) {
+        return FAIL;
+    }
+
+    return composeSocketData(fd,
+                             id,
+                             OP_WRITE_DATA,
+                             REG_USER_ID,
+                             strlen((char *)pUserID),
+                             pUserID);
+}
+
+static int writeConnectorState(int fd, uint8_t plugNum, uint8_t id)
+{
+    uint8_t dataBuf[16] = {'\0'};
+    uint32_t _consumption;
+    ConnectorState *pConnState = (ConnectorState *)dataBuf;
+    static char vendorErrorCodeTmp[2][WARNING_CODE_SIZE] = {0};
+    int ret = PASS;
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(plugNum);
+
+    pConnState->ConnectorTemp = pDcChargingInfo->ConnectorTemp;
+    pConnState->ChillerTemp = pDcChargingInfo->ChillerTemp;
+    pConnState->PlugIn = pDcChargingInfo->ConnectorPlugIn;
+    pConnState->ConnectMode = pDcChargingInfo->SystemStatus;
+
+    if (pDcChargingInfo->SystemStatus <= S_AUTHORIZING) {
+        pConnState->State = CONN_ST_IDLE;    //idle
+        strncpy((char *)ShmOCPP16Data->StatusNotification[plugNum].VendorErrorCode,
+                "",
+                sizeof(ShmOCPP16Data->StatusNotification[plugNum].VendorErrorCode));
+
+        strncpy(&vendorErrorCodeTmp[plugNum][0], "", WARNING_CODE_SIZE);
+    } else if ((pDcChargingInfo->SystemStatus <= S_PREPARING_FOR_EVSE) ||
+               (pDcChargingInfo->SystemStatus == S_CCS_PRECHARGE_ST0) ||
+               (pDcChargingInfo->SystemStatus == S_CCS_PRECHARGE_ST1)) {
+        pConnState->State = CONN_ST_PREPARING;    //preparing
+    } else if (pDcChargingInfo->SystemStatus == S_CHARGING) {
+        pConnState->State = CONN_ST_CHARGING;    //charging
+    } else if (pDcChargingInfo->SystemStatus == S_TERMINATING ||
+            pDcChargingInfo->SystemStatus == S_COMPLETE) {
+
+            if (pDcChargingInfo->RelayK1K2Status == YES) {
+                return FAIL;
+            }
+        pConnState->State = CONN_ST_TERMINATING;    //terminating
+    } else if ((pDcChargingInfo->SystemStatus == S_ALARM) ||
+               (pDcChargingInfo->SystemStatus == S_FAULT)) {
+
+        if (pDcChargingInfo->RelayK1K2Status == YES && pDcChargingInfo->SystemStatus == S_ALARM) {
+            return FAIL;
+        }
+
+        pConnState->State = CONN_ST_ALARM;
+        strncpy((char *)pConnState->WarningCode,
+                (char *)ShmOCPP16Data->StatusNotification[plugNum].VendorErrorCode,
+                WARNING_CODE_SIZE);
+
+        if (strncmp(&vendorErrorCodeTmp[plugNum][0], "", WARNING_CODE_SIZE) == 0) {
+            strncpy(&vendorErrorCodeTmp[plugNum][0],
+                    (char *)ShmOCPP16Data->StatusNotification[plugNum].VendorErrorCode,
+                    WARNING_CODE_SIZE);
+            vendorErrorCodeTmp[plugNum][6] = '\0';
+            /*
+            log_info("1 ID = %d, VendorErrorCode = %s",
+                     plugNum,
+                     (char *)ShmOCPP16Data->StatusNotification[plugNum].VendorErrorCode);
+                     */
+        } else {
+            if (strncmp(&vendorErrorCodeTmp[plugNum][0],
+                        (char *)ShmOCPP16Data->StatusNotification[plugNum].VendorErrorCode,
+                        WARNING_CODE_SIZE) != 0
+               ) {
+                strncpy(&vendorErrorCodeTmp[plugNum][0],
+                        (char *)ShmOCPP16Data->StatusNotification[plugNum].VendorErrorCode,
+                        WARNING_CODE_SIZE);
+                vendorErrorCodeTmp[plugNum][6] = '\0';
+                /*
+                log_info("2 ID = %d, VendorErrorCode = %s",
+                         plugNum,
+                         (char *)ShmOCPP16Data->StatusNotification[plugNum].VendorErrorCode);
+                         */
+            }
+        }
+    }
+
+    memcpy((char*)&_consumption, (char*)&ShmDcCommonData->pGunInfo[plugNum].PowerConsumption, sizeof(float));
+    pConnState->consumption = ntohl(_consumption);
+
+    if (gunstatus[plugNum] != pConnState->State) {
+        log_info("Gun%d Status[%d] to OCPP Backend VendorErrorCode[%s]",plugNum,pConnState->State,(char *)ShmOCPP16Data->StatusNotification[plugNum].VendorErrorCode);
+        gunstatus[plugNum] = pConnState->State;
+    }
+
+    ret = composeSocketData(fd,
+                            id,
+                            OP_WRITE_DATA,
+                            REG_CONNECTOR_STATE,
+                            sizeof(dataBuf) - 1,
+                            &dataBuf[0]);
+    return ret;
+}
+
+static int writePlugInStatus(int fd, uint8_t plugNum, uint8_t id)
+{
+    int ret = PASS;
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(plugNum);
+    uint8_t dataBuf[2] = {pDcChargingInfo->ConnectorPlugIn, 0};
+
+    ret = composeSocketData(fd,
+                            id,
+                            OP_WRITE_DATA,
+                            REG_PLUG_IN_STATE,
+                            1,
+                            &dataBuf[0]);
+    return ret;
+}
+
+static int readSoftwareUpdate(int fd, uint8_t gunID)
+{
+    int ret = PASS;
+    uint8_t dataBuf[2] = {pSysInfo->FirmwareUpdate, 0};
+
+    ret = composeSocketData(fd,
+                            gunID,
+                            OP_READ_DATA,
+                            REG_SOFTWARE_UPDATE,
+                            1,
+                            &dataBuf[0]);
+
+    return ret;
+}
+
+static int writeChargingTarget(int fd, uint8_t plugNum, uint8_t id)
+{
+    int ret = PASS;
+    float ChargingVolt, ChargingAmp;
+    uint8_t dataBuf[4] = {0};
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(plugNum);
+    if ((pDcChargingInfo->SystemStatus <= S_PREPARING_FOR_EV || pDcChargingInfo->SystemStatus >= S_TERMINATING) &&
+        pDcChargingInfo->SystemStatus != S_CCS_PRECHARGE_ST0 && pDcChargingInfo->SystemStatus != S_CCS_PRECHARGE_ST1) {
+        pDcChargingInfo->EvBatterytargetVoltage = 0;
+        pDcChargingInfo->EvBatterytargetCurrent = 0;
+    }
+    ChargingVolt = pDcChargingInfo->EvBatterytargetVoltage;
+    ChargingAmp = pDcChargingInfo->EvBatterytargetCurrent;
+    ChargingVolt *= 10;
+    ChargingAmp *= 10;
+
+    dataBuf[0] = ((uint16_t)ChargingVolt >> 8) & 0xFF;
+    dataBuf[1] = ((uint16_t)ChargingVolt) & 0xFF;
+    dataBuf[2] = ((uint16_t)ChargingAmp >> 8) & 0xFF;
+    dataBuf[3] = ((uint16_t)ChargingAmp) & 0xFF;
+
+    ret = composeSocketData(fd,
+                            id,
+                            OP_WRITE_DATA,
+                            REG_CHARGING_TARGET,
+                            sizeof(dataBuf),
+                            &dataBuf[0]);
+
+    return ret;
+}
+
+static int readChargingCapability(int fd, uint8_t id)
+{
+    int ret = PASS;
+
+    ret = composeSocketData(fd,
+                            id,
+                            OP_READ_DATA,
+                            REG_CHARGING_CAP,
+                            0,
+                            NULL);
+
+    return ret;
+}
+
+static int writeDispenserStatus(int fd, uint8_t gunID)
+{
+    uint8_t warningCount = 0;
+    uint8_t count = 0;
+    uint8_t CurWarnCodeTmp[10][6] = {0};
+    uint8_t PreWarnCodeTmp[10][6] = {0};
+    int ret = PASS;
+
+    if ((pSysWarning->WarningCount <= 0) &&
+            (gPreSysWarningInfo.WarningCount <= 0)) {
+        return FAIL;
+    }
+
+    warningCount = pSysWarning->WarningCount;
+    for (count = 0; count < warningCount; count++) {
+        memcpy(CurWarnCodeTmp[count], pSysWarning->WarningCode[count], WARNING_CODE_SIZE);
+    }
+
+    warningCount = gPreSysWarningInfo.WarningCount;
+    for (count = 0; count < warningCount; count++) {
+        memcpy(PreWarnCodeTmp[count], gPreSysWarningInfo.WarningCode[count], WARNING_CODE_SIZE);
+    }
+
+    if (strcmp((char *)&CurWarnCodeTmp[0], (char *)&PreWarnCodeTmp[0]) == 0) {
+        return FAIL;
+    }
+
+    ret = composeSocketData(fd,
+                            gunID,
+                            OP_WRITE_DATA,
+                            REG_DISPENSER_STATUS,
+                            strlen((char *)CurWarnCodeTmp),
+                            &CurWarnCodeTmp[0][0]);
+
+    return ret;
+}
+
+static int readPowerCabinetStatus(int fd, uint8_t gunID)
+{
+    int ret = PASS;
+
+    ret = composeSocketData(fd,
+                            gunID,
+                            OP_READ_DATA,
+                            REG_POWER_CABINET_STATUS,
+                            0,
+                            NULL);
+
+    return ret;
+}
+
+static int readConnectorID(int fd)
+{
+    int ret = PASS;
+
+    ret = composeSocketData(fd,
+                            ID_REGISTER,
+                            OP_READ_DATA,
+                            REG_CONNECTOR_ID,
+                            0,
+                            NULL);
+
+    return ret;
+}
+
+static int WriteModelName(int fd)
+{
+    int ret = PASS;
+    uint8_t Tmp = 0;
+    uint8_t TmpBuf[255] = {0};
+
+    memcpy(TmpBuf,
+           pSysConfig->ModelName,
+           strlen((char *)pSysConfig->ModelName));
+
+    Tmp = (uint8_t)(ShmPrimaryMcuData->InputDet.bits.Key2 << 2 |
+                    ShmPrimaryMcuData->InputDet.bits.Key1 << 1 |
+                    ShmPrimaryMcuData->InputDet.bits.Key0);
+
+    TmpBuf[strlen((char *)pSysConfig->ModelName)] = Tmp; //Dispenser switch value
+
+    ret = composeSocketData(fd,
+                            ID_REGISTER,
+                            OP_WRITE_DATA,
+                            REG_MODEL_NAME,
+                            strlen((char *)pSysConfig->ModelName) + 1,
+                            &TmpBuf[0]);
+
+    return ret;
+}
+
+static void calDisconnectCount(uint8_t *pValue, uint8_t maxCount)
+{
+    sleep(3); //wait 1 second
+
+    if ((*pValue) >= maxCount) {
+        setTcpStatus(ABNORMAL);
+    } else {
+        (*pValue)++;
+    }
+}
+
+static int CheckNetworkStatus(void)
+{
+    char *ipAddr = (char *)&pSysConfig->Eth0Interface.EthIpAddress;
+
+    //printf("Check network IP Header = %s\n", ipAddr);
+    if (strstr(ipAddr, CMP_ETH_IP_HEAD) != NULL) {
+        return 1;
+    }
+
+    return 0;
+}
+
+static void updateFirmwareProcess(int fd, uint8_t gunID, uint8_t totalConnCount)
+{
+    bool canUpdateFirmware = true;
+    uint8_t plugNum = 0;
+    uint8_t ackCount = 5;
+    struct timeb updateTime;
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(plugNum);
+
+    if (pSysWarning->Level != 2) {
+        for (plugNum = 0; plugNum < totalConnCount; plugNum++) {
+            if (pDcChargingInfo->SystemStatus != S_IDLE &&
+                    pDcChargingInfo->SystemStatus != S_RESERVATION &&
+                    pDcChargingInfo->SystemStatus != S_MAINTAIN) {
+                canUpdateFirmware = false;
+            }
+        }
+    }
+
+    if (canUpdateFirmware) {
+        ftime(&updateTime);
+        if (DiffTimeb(gRegTimeUp[0][REG_SOFTWARE_UPDATE], updateTime) > LOOP_RETRY_TIME * 5) {
+            readSoftwareUpdate(fd, gunID);
+            ftime(&gRegTimeUp[0][REG_SOFTWARE_UPDATE]);
+        }
+
+        if (pSysInfo->FirmwareUpdate == YES) {
+            while (ackCount != 0) {
+                ftime(&updateTime);
+                if (DiffTimeb(gRegTimeUp[0][REG_SOFTWARE_UPDATE], updateTime) > LOOP_RETRY_TIME / 2) {
+                    readSoftwareUpdate(fd, gunID);
+                    ftime(&gRegTimeUp[0][REG_SOFTWARE_UPDATE]);
+                    if (pSysInfo->FirmwareUpdate == NO) {
+                        ackCount--;
+                    }
+                }
+                usleep(128);
+            }
+        }
+    }
+}
+
+static void checkAuthorProcess(int fd, uint8_t plugNum)
+{
+    int ret = 0;
+    uint8_t gunID = 0;
+    struct timeb AuthNowTime;
+
+#if defined DD360Audi
+    gunID = gDoCommGblData.ConnectorID[pSysInfo->CurGunSelected];
+    //gunID = gDoCommGblData.ConnectorID[plugNum];
+    if (pSysConfig->AuthorisationMode) {
+        gunID = ID_REGISTER;
+        ShmSelectGunInfo->PricesInfo[pSysInfo->CurGunSelected].Balance = 0.0;
+    }
+#else
+    gunID = gDoCommGblData.ConnectorID[pSysInfo->CurGunSelected];
+
+    ShmSelectGunInfo->PricesInfo[pSysInfo->CurGunSelected].Balance = 0.0; //非Audi 不需要等待主櫃回報餘額
+#endif // DD360Audi
+
+    if ((ShmOCPP16Data->SpMsg.bits.AuthorizeReq == YES) ||
+            (pSysInfo->AuthorizeFlag == YES)) {
+        ftime(&AuthNowTime);
+
+        if (DiffTimeb(gRegTimeUp[plugNum][REG_USER_ID], AuthNowTime) > LOOP_RETRY_TIME) {
+            ret = writeUserID(fd,
+                              gunID,
+                              pSysConfig->UserId);
+            if (ret >= 0) {
+                memset(ShmOCPP16Data->Authorize.ResponseIdTagInfo.Status,
+                       0,
+                       sizeof(ShmOCPP16Data->Authorize.ResponseIdTagInfo.Status));
+
+                if (ret == 0) {
+                    strcpy((char *)ShmOCPP16Data->Authorize.ResponseIdTagInfo.Status, "Invalid");
+                } else {
+                    strcpy((char *)ShmOCPP16Data->Authorize.ResponseIdTagInfo.Status, "Accepted");
+                }
+
+                //printf("%d Balance = %.2f, %.2f\n",
+                //       plugNum,
+                //       ShmSelectGunInfo->PricesInfo[plugNum].Balance,
+                //       FAIL_BALANCE_PRICES);
+
+                if (ShmSelectGunInfo->PricesInfo[plugNum].Balance != FAIL_BALANCE_PRICES) {
+                    ShmOCPP16Data->SpMsg.bits.AuthorizeConf = YES; //isAuthorizedComplete
+                    ShmOCPP16Data->SpMsg.bits.AuthorizeReq  = NO;
+                    pSysInfo->AuthorizeFlag                 = NO;
+                    ShmPsuData->SystemAvailablePower        = NO;
+                    ShmPsuData->SystemPresentPsuQuantity    = NO;
+                }
+            }
+            ftime(&gRegTimeUp[plugNum][REG_USER_ID]);
+        }
+    }
+}
+void SetDispenserReq(uint8_t plugNum)
+{
+    if (gConnectorActReq[plugNum].bits.ChargingCancel != ShmDcCommonData->OperateIDLE[plugNum]) {
+        gConnectorActReq[plugNum].bits.ChargingCancel = ShmDcCommonData->OperateIDLE[plugNum];
+        memset(&ShmDcCommonData->ParkingInfo[plugNum],0,sizeof(RecordTransactionInfo));
+    }
+    if (gConnectorActReq[plugNum].bits.ParkingBillReq != ShmDcCommonData->pGunInfo[plugNum].ReqParkingBill) {
+        gConnectorActReq[plugNum].bits.ParkingBillReq = ShmDcCommonData->pGunInfo[plugNum].ReqParkingBill;
+    }
+}
+void clearDispenserReq(uint8_t plugNum)
+{
+    gConnectorActReq[plugNum].Value = 0;
+    if (gConnectorActReq[plugNum].bits.ChargingCancel != ShmDcCommonData->OperateIDLE[plugNum]) {
+        ShmDcCommonData->OperateIDLE[plugNum] = 0;
+        ShmDcCommonData->TransactionInfo[plugNum].LineStatus = _LINE_INIT;
+        log_info("Gun%d Return Cancel OK", plugNum);
+    }
+    if (gConnectorActReq[plugNum].bits.ParkingBillReq != ShmDcCommonData->pGunInfo[plugNum].ReqParkingBill) {
+        ShmDcCommonData->pGunInfo[plugNum].ReqParkingBill = 0;
+        log_info("Gun%d Parking Bill Requset OK", plugNum);
+    }
+}
+
+static int messageTrigger(int fd, uint8_t plugNum, uint8_t gunID, uint8_t curReg)
+{
+    int ret = DISPENSER_INIT_SUCC;
+    int isContinue = 1;
+    struct timeb NowTime;
+
+    while (isContinue) {
+        usleep(128);
+        ftime(&NowTime);
+
+        switch (curReg) {
+        case REG_MODEL_NAME:
+            if (WriteModelName(fd) == PASS) {
+                gDoCommGblData.DisConnCount = 0;
+                curReg = REG_CONNECTOR_ID;
+            } else {
+                sleep(1);
+            }
+            break;
+
+        case REG_CONNECTOR_ID:
+            if (readConnectorID(fd) == PASS) {
+                gDoCommGblData.DisConnCount = 0;
+                curReg = REG_REPORT_CSU_VERSION;
+            } else {
+                sleep(1);
+            }
+            break;
+
+        case REG_POWER_CABINET_STATUS:
+            if (DiffTimeb(gRegTimeUp[plugNum][curReg], NowTime) > LOOP_RETRY_TIME ||
+                    DiffTimeb(gRegTimeUp[plugNum][curReg], NowTime) < 0) {
+                readPowerCabinetStatus(fd, gunID);
+                ftime(&gRegTimeUp[plugNum][curReg]);
+            }
+            curReg = REG_DISPENSER_STATUS;
+            break;
+
+        case REG_DISPENSER_STATUS:
+            if (DiffTimeb(gRegTimeUp[plugNum][curReg], NowTime) > LOOP_RETRY_TIME ||
+                    DiffTimeb(gRegTimeUp[plugNum][curReg], NowTime) < 0) {
+                writeDispenserStatus(fd, gunID);
+                ftime(&gRegTimeUp[plugNum][curReg]);
+            }
+            curReg = REG_CHARGING_CAP;
+            break;
+
+        case REG_CHARGING_CAP:
+            if(gMoreInfoReq[plugNum].bits.FinalCostReq)
+            {
+                if (readChargingCapability(fd, gunID) == PASS) {
+					gMoreInfoReq[plugNum].bits.FinalCostReq = false;
+					pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(plugNum);
+					ShmDcCommonData->TransactionInfo[plugNum].Amount = pDcChargingInfo->ChargingFee;
+					ShmDcCommonData->finalcost_flag[plugNum] = TRUE;
+					log_info("Gun %d get final cost %f", plugNum, ShmDcCommonData->TransactionInfo[plugNum].Amount);
+                    if (ShmDcCommonData->is_AutoStart[plugNum] || ShmDcCommonData->is_RemoteStart[plugNum]) {
+                        ShmDcCommonData->PayPass_flag[plugNum] = TRUE;
+                        if (pSysInfo->CurGunSelected == plugNum )
+                            pSysInfo->SystemPage = _PAGE_COMPLETE;
+                    } else {
+                        UpdateDeductInfoStatus(plugNum, &ShmDcCommonData->TransactionInfo[plugNum]);
+                    }
+                }
+            }
+            curReg = REG_PLUG_IN_STATE;
+            break;
+
+        case REG_PLUG_IN_STATE:
+            if (DiffTimeb(gRegTimeUp[plugNum][curReg], NowTime) > LOOP_RETRY_TIME ||
+                    DiffTimeb(gRegTimeUp[plugNum][curReg], NowTime) < 0) {
+                writePlugInStatus(fd, plugNum, gunID);
+                ftime(&gRegTimeUp[plugNum][curReg]);
+            }
+            curReg = REG_CONNECTOR_STATE;
+            break;
+
+        case REG_CONNECTOR_STATE:
+            if (DiffTimeb(gRegTimeUp[plugNum][curReg], NowTime) > LOOP_RETRY_TIME ||
+                    DiffTimeb(gRegTimeUp[plugNum][curReg], NowTime) < 0) {
+                writeConnectorState(fd, plugNum, gunID);
+                ftime(&gRegTimeUp[plugNum][curReg]);
+            }
+            curReg = REG_DISPENSER_REQUEST;
+            break;
+        case REG_DISPENSER_REQUEST:
+            SetDispenserReq(plugNum);
+            if (gConnectorActReq[plugNum].Value != 0)
+            {
+                if (DiffTimeb(gRegTimeUp[plugNum][curReg], NowTime) > LOOP_RETRY_TIME ||
+                    DiffTimeb(gRegTimeUp[plugNum][curReg], NowTime) < 0) {
+                    if (writeDispenserRequest(fd, gunID, plugNum) == PASS)
+                    {
+                        clearDispenserReq(plugNum);
+                    }
+                    ftime(&gRegTimeUp[plugNum][curReg]);
+                }
+            }
+            curReg = REG_PARKING_STATUS;
+            break;
+        case REG_PARKING_STATUS:
+            if (gMoreInfoReq[plugNum].bits.ParkingReq) {
+                if (DiffTimeb(gRegTimeUp[plugNum][curReg], NowTime) > LOOP_RETRY_TIME ||
+                    DiffTimeb(gRegTimeUp[plugNum][curReg], NowTime) < 0) {
+                    readParkingStatus(fd, gunID);
+
+                    ftime(&gRegTimeUp[plugNum][curReg]);
+                }
+            }
+            curReg = REG_PARKING_BILL;
+            break;
+        case REG_PARKING_BILL:
+            if (ShmDcCommonData->pGunInfo[plugNum].ParkingStatus == _TCC_WAIT_PAY && ShmDcCommonData->pGunInfo[plugNum].GetParkingBill == FALSE &&
+                pSysInfo->SystemPage == _PAGE_PAYING) {
+                if (DiffTimeb(gRegTimeUp[plugNum][curReg], NowTime) > LOOP_RETRY_TIME ||
+                    DiffTimeb(gRegTimeUp[plugNum][curReg], NowTime) < 0) {
+                    //log_info("Ask Parking Bill ");
+                    if (readParkingBill(fd, gunID) == PASS)
+                    {
+                        ShmDcCommonData->pGunInfo[plugNum].GetParkingBill = TRUE;
+                        if (pSysInfo->CurGunSelected == plugNum &&
+                             ShmDcCommonData->pGunInfo[plugNum].ReqParkingBill)
+                            pSysInfo->SystemPage = _PAGE_BILL;
+                    }
+                    ftime(&gRegTimeUp[plugNum][curReg]);
+                }
+            }
+            curReg = REG_QRCODE_URL_INFO;
+            break;
+        case REG_QRCODE_URL_INFO:
+            //if (gunID == 1) {
+                if (DiffTimeb(gRegTimeUp[plugNum][curReg], NowTime) > (LOOP_RETRY_TIME * 10) ||
+                    DiffTimeb(gRegTimeUp[plugNum][curReg], NowTime) < 0
+                    ) {
+                    readQRcodeURLAndSystemDate(fd);
+                    ftime(&gRegTimeUp[plugNum][curReg]);
+                }
+            //}
+
+            //check misc command from power cabinet
+            if (gDoCommGblData.MiscCmd != 0) {
+                if (gDoCommGblData.MiscCmd != REG_MISC_CONTROL) {
+                    log_error("misc command failed = %x", gDoCommGblData.MiscCmd);
+                }
+                curReg = gDoCommGblData.MiscCmd;
+            } else if (gMoreInfoReq[plugNum].Value != 0) {
+                curReg = REG_RESERVATION_IDTAG;
+            } else {
+                isContinue = 0;
+            }
+            //curReg = REG_SOFTWARE_UPDATE;
+            break;
+        //case REG_USER_ID:
+        //    writeUserID(fd, gunID, uint8_t *pUserID);
+        //    break;
+
+        //case REG_CHARGING_PERMISSION:
+        //    readChargePermission(fd, gunID);
+        //    break;
+
+        case REG_MISC_CONTROL:
+            readMiscCommand(fd, gunID);
+
+            if(gMoreInfoReq[plugNum].Value == 0)
+            {
+                isContinue = 0;
+            }
+            else
+            {
+                curReg = REG_RESERVATION_IDTAG;
+            }
+            break;
+
+        case REG_REPORT_CSU_VERSION:
+        case REG_REPORT_OTHER_VERSION:
+            if (gDoCommGblData.MiscCmd != 0) {
+                writeCsuModuleVersion(fd);
+                writeOtherModuleVersion(fd);
+                clearMiscCommand();
+                isContinue = 0;
+            } else {
+                //power up write dispenser version and get power cabinet system ID
+                if ((writeCsuModuleVersion(fd) == PASS) &&
+                        (writeOtherModuleVersion(fd) == PASS) &&
+                        (readQRcodeURLAndSystemDate(fd) == PASS)
+                   ) {
+                    //gDoCommGblData.DisConnCount = 0;
+                    isContinue = 0;
+                }
+            }
+            break;
+
+        //case REG_PRESENT_CHARGING_INFO:
+        //    break;
+
+
+
+        //case REG_WAIT_PLUG_IT_STATE:
+        //    if (DiffTimeb(gRegTimeUp[plugNum][curReg], NowTime) > (LOOP_RETRY_TIME / 10)) {
+        //        writeWaitPlugItState(fd, gunID);
+        //        ftime(&gRegTimeUp[plugNum][curReg]);
+        //    }
+        //    isContinue = 0;
+        //    break;
+
+        //case REG_CABINET_DCM_VERSION:
+        //    break;
+
+        //case REG_CABINET_OTHER_VERSION:
+        //    break;
+
+        //case REG_TOTAL_PSU_QUANTITY:
+        //    break;
+
+        //case REG_PSU_VERSION:
+        //    break;
+
+        case REG_RESERVATION_IDTAG:
+            if(gMoreInfoReq[plugNum].bits.ReservationReq)
+            {
+                if (DiffTimeb(gRegTimeUp[plugNum][curReg], NowTime) > LOOP_RETRY_TIME ||
+                        DiffTimeb(gRegTimeUp[plugNum][curReg], NowTime) < 0) {
+                    if(readReservationState(fd, gunID) == PASS)
+                    {
+                        gMoreInfoReq[plugNum].bits.ReservationReq = ReservationState[plugNum] == NO ? NO : YES;
+                    }
+                    ftime(&gRegTimeUp[plugNum][curReg]);
+                }
+            }
+            curReg = REG_REMOTE_START_NO_ID;
+            break;
+
+        //case REG_DISPENSER_REQUEST:
+        //    break;
+
+        case REG_REMOTE_START_NO_ID:
+            if(gMoreInfoReq[plugNum].bits.RemoteStartNoID)
+            {
+                if (DiffTimeb(gRegTimeUp[plugNum][curReg], NowTime) > LOOP_RETRY_TIME ||
+                        DiffTimeb(gRegTimeUp[plugNum][curReg], NowTime) < 0) {
+                    if(readRemoteStartNoIDState(fd) == PASS)
+                    {
+                        gMoreInfoReq[plugNum].bits.RemoteStartNoID = RemoteStartNoIDState == NO ? NO : YES;
+                    }
+                    ftime(&gRegTimeUp[plugNum][curReg]);
+                }
+            }
+            curReg = REG_CHARGING_BILL;
+            break;
+        case REG_CHARGING_BILL:
+            if (gMoreInfoReq[plugNum].bits.ChargingBill) {
+                if (DiffTimeb(gRegTimeUp[plugNum][curReg], NowTime) > LOOP_RETRY_TIME ||
+                    DiffTimeb(gRegTimeUp[plugNum][curReg], NowTime) < 0) {
+                    if (readChargingBill(fd, gunID) == PASS)
+                    {
+                        log_info("Need to rededuct Bill");
+                        gMoreInfoReq[plugNum].bits.ChargingBill = false;
+                    }
+                    ftime(&gRegTimeUp[plugNum][curReg]);
+                }
+            }
+            curReg = REG_REFUND_AMOUNT;
+            break;
+        case REG_REFUND_AMOUNT:
+            curReg = REG_PREPAYMENT_INFO;
+            break;
+
+        case REG_PREPAYMENT_INFO:
+            curReg = REG_PAYMENT_FAIL_REASON;
+            break;
+
+        case REG_PAYMENT_FAIL_REASON:
+            curReg = REG_CONNECTOR_QR_CODE;
+            break;
+
+        case REG_CONNECTOR_QR_CODE:
+            curReg = REG_STATION_INFO;
+            break;
+
+        case REG_STATION_INFO:
+            if(gMoreInfoReq[plugNum].bits.StationInfoReq)
+            {
+                if (DiffTimeb(gRegTimeUp[plugNum][curReg], NowTime) > LOOP_RETRY_TIME ||
+                        DiffTimeb(gRegTimeUp[plugNum][curReg], NowTime) < 0) {
+
+                    if(readChargerStationInfo(fd) == PASS)
+                    {
+                        gMoreInfoReq[plugNum].bits.StationInfoReq = NO;
+                    }
+                    ftime(&gRegTimeUp[plugNum][curReg]);
+                }
+            }
+            isContinue = 0;
+            break;
+
+        default:
+            log_error("error curReg = %x", curReg);
+            gDoCommGblData.MiscCmd = 0;
+            gDoCommGblData.DisConnCount = CHECK_NETWORK_FAIL_COUNT;
+            isContinue = 0;
+            break;
+        }
+
+        if (gDoCommGblData.DisConnCount >= CHECK_NETWORK_FAIL_COUNT) {
+            return DISPENSER_SOCKET_RECONN;
+        }
+    }//for
+
+    return ret;
+}
+
+//static bool isDetectPlugin()
+//{
+//    if (pSysInfo->WaitForPlugit == YES) {
+//        return YES;
+//    }
+//
+//    return NO;
+//}
+static void systemStatusProcess(int fd, uint8_t totalGun, uint8_t plugNum, uint8_t gunID)
+{
+    uint8_t i = 0;
+    int j;
+    struct timeb AuthNowTime = {0};
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(plugNum);
+    int reupload_gunIndex[128] = {0};
+    RecordTransactionInfo reuploadInfo[128];
+    int reupload_num = 0;
+    struct timeb SeqEndTime;
+    struct tm* tm;
+
+    switch (pDcChargingInfo->SystemStatus) {
+    case S_IDLE:
+    case S_RESERVATION:
+    case S_MAINTAIN:
+    case S_ALARM:
+    case S_AUTHORIZING:
+        /*
+        if(pDcChargingInfo->SystemStatus != S_ALARM)
+        {
+            DeductResultReq[plugNum] = NO;
+        }
+        */
+
+        if (pDcChargingInfo->SystemStatus == S_ALARM) {
+            writeChargingTarget(fd, plugNum, gunID);
+            ftime(&AuthNowTime);
+            if (DiffTimeb(gRegTimeUp[plugNum][REG_PRESENT_CHARGING_INFO], AuthNowTime) > LOOP_RETRY_TIME ||
+                DiffTimeb(gRegTimeUp[plugNum][REG_PRESENT_CHARGING_INFO], AuthNowTime) < 0
+                ) {
+                writePresentChargingInfo(fd, plugNum, gunID);
+                ftime(&gRegTimeUp[plugNum][REG_PRESENT_CHARGING_INFO]);
+            }
+        }
+
+        checkAuthorProcess(fd, plugNum);
+
+        //authorization complete, write wait plug it state
+        if (ShmSelectGunInfo->PricesInfo[plugNum].Balance == FAIL_BALANCE_PRICES) {
+            break;
+        }
+
+        ftime(&SeqEndTime);
+        SeqEndTime.time = time(NULL);
+        tm = localtime(&SeqEndTime.time);
+        
+        if ((pSysInfo->SystemPage == _PAGE_IDLE || pSysInfo->SystemPage == _PAGE_SELECT_GUN) &&
+            !ShmDcCommonData->pGunInfo[plugNum].isParking) {
+            ftime(&AuthNowTime);
+            if (DiffTimeb(gRegTimeUp[plugNum][REG_DEDUCT_INFO], AuthNowTime) > LOOP_RETRY_TIME ||
+                DiffTimeb(gRegTimeUp[plugNum][REG_DEDUCT_INFO], AuthNowTime) < 0
+                ) {
+                // 充電費補上傳
+                reupload_num = DB_GetMultiReUploadDeduct(&reupload_gunIndex[0], &reuploadInfo[0]);
+                if (reupload_num >= 1 && reuploadInfo[0].ConnectorID != 0) {
+
+                    if (writeDeductInfo(fd, reuploadInfo[0].ConnectorID, reupload_gunIndex[0], &reuploadInfo[0]) == PASS) {
+                        reuploadInfo[0].IsUpload = TRUE;
+                        UpdateDeductInfoStatus(&reupload_gunIndex[0], &reuploadInfo[0]);
+                    } else
+                        log_info("Charging Information Reupload fail");
+
+                }
+                usleep(100);
+                // 佔位費補上傳
+                memset(reuploadInfo,0,sizeof(RecordTransactionInfo)*128);
+                reupload_num = DB_GetParkingDeductUpload(&reupload_gunIndex[0], &reuploadInfo[0]);
+                if (reupload_num >= 1 && reuploadInfo[0].ConnectorID != 0) {
+                    showDeductInfo(&reuploadInfo[0]);
+                    if (writeDeductInfo(fd, reuploadInfo[0].ConnectorID, reupload_gunIndex[0], &reuploadInfo[0]) == PASS) {
+                        reuploadInfo[0].IsUpload = YES;
+                        log_info("OccupancySN:[%s] upload set:%d",reuploadInfo[0].OccupancySN,reuploadInfo[0].IsUpload);
+                        UpdateParkingUpload(&reuploadInfo[0].OccupancySN[0],YES);
+                    } else
+                        log_info("Parking Information Reupload fail");
+
+                }
+                ftime(&gRegTimeUp[plugNum][REG_DEDUCT_INFO]);
+            }
+        }
+        
+        /*
+        if (pSysInfo->SystemPage == _PAGE_IDLE || pSysInfo->SystemPage == _PAGE_SELECT_GUN) {
+            reupload_num = DB_GetMultiReUploadDeduct(&reupload_gunIndex[0], &reuploadInfo[0]);
+            log_info("ReUpload number:%d", reupload_num);
+
+            for (j = 0; j < reupload_num; j++) {
+                log_info("Connector ID:%d Card No:%s", reuploadInfo[j].ConnectorID, reuploadInfo[j].pCreditCard.CardNo);
+
+                if (writeDeductInfo(fd, reuploadInfo[j].ConnectorID, reupload_gunIndex[j], &reuploadInfo[j]) == PASS) {
+                    log_info("Reupload Success");
+                    reuploadInfo[j].IsUpload = YES;
+                    UpdateDeductInfoStatus(reupload_gunIndex[j], &reuploadInfo[j]);
+                } else
+                    log_info("Reupload fail");
+            }
+        }*/
+
+        ftime(&AuthNowTime);
+        if (DiffTimeb(gRegTimeUp[plugNum][REG_WAIT_PLUG_IT_STATE], AuthNowTime) > (LOOP_RETRY_TIME / 10) ||
+                DiffTimeb(gRegTimeUp[plugNum][REG_WAIT_PLUG_IT_STATE], AuthNowTime) < 0
+           ) {
+            writeWaitPlugItState(fd, gunID, plugNum);
+            ftime(&gRegTimeUp[plugNum][REG_WAIT_PLUG_IT_STATE]);
+        }
+        /*
+        ftime(&AuthNowTime);
+        if (DiffTimeb(gRegTimeUp[plugNum][REG_MISC_CONTROL], AuthNowTime) > (LOOP_RETRY_TIME / 10) ||
+                DiffTimeb(gRegTimeUp[plugNum][REG_MISC_CONTROL], AuthNowTime) < 0
+           ) {
+            readMiscCommand(fd, gunID);
+            ftime(&gRegTimeUp[plugNum][REG_MISC_CONTROL]);
+        }
+        */
+        ftime(&AuthNowTime);
+        if (DiffTimeb(gRegTimeUp[plugNum][REG_CHARGING_CAP], AuthNowTime) > LOOP_RETRY_TIME ||
+                DiffTimeb(gRegTimeUp[plugNum][REG_CHARGING_CAP], AuthNowTime) < 0
+           ) {
+            readChargingCapability(fd, gunID);
+			if (pDcChargingInfo->PantographFlag)
+				writeGroundFaultDetection(fd, 0, gunID);
+            ftime(&gRegTimeUp[plugNum][REG_CHARGING_CAP]);
+        }
+
+        break;
+
+    case S_PREPARNING: //get permission
+        ftime(&AuthNowTime);
+        if (DiffTimeb(gRegTimeUp[plugNum][REG_CONNECTOR_STATE], AuthNowTime) > LOOP_RETRY_TIME ||
+                DiffTimeb(gRegTimeUp[plugNum][REG_CONNECTOR_STATE], AuthNowTime) < 0
+           ) {
+            writeConnectorState(fd, plugNum, gunID);
+            ftime(&gRegTimeUp[plugNum][REG_CONNECTOR_STATE]);
+        }
+
+        ftime(&AuthNowTime);
+        if (DiffTimeb(gRegTimeUp[plugNum][REG_CHARGING_PERMISSION], AuthNowTime) > LOOP_RETRY_TIME ||
+                DiffTimeb(gRegTimeUp[plugNum][REG_CHARGING_PERMISSION], AuthNowTime) < 0
+           ) {
+            if (readChargePermission(fd, gunID) && readChargingCapability(fd, gunID)) {
+                for (i = 0; i < totalGun; i++) {
+                    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(i);
+
+                    ShmPsuData->SystemAvailablePower += pDcChargingInfo->AvailableChargingPower;
+                }
+                ShmPsuData->SystemPresentPsuQuantity = (ShmPsuData->SystemAvailablePower / 30);
+            }
+            ftime(&gRegTimeUp[plugNum][REG_CHARGING_PERMISSION]);
+        }
+
+        ftime(&AuthNowTime);
+        if (DiffTimeb(gRegTimeUp[plugNum][REG_PRESENT_CHARGING_INFO], AuthNowTime) > LOOP_RETRY_TIME ||
+                DiffTimeb(gRegTimeUp[plugNum][REG_PRESENT_CHARGING_INFO], AuthNowTime) < 0
+           ) {
+            writePresentChargingInfo(fd, plugNum, gunID);
+			if (pDcChargingInfo->PantographFlag)
+				writeGroundFaultDetection(fd, 0, gunID);
+            ftime(&gRegTimeUp[plugNum][REG_PRESENT_CHARGING_INFO]);
+        }
+        break;
+
+    case S_PREPARING_FOR_EV://wait connector lock
+        ftime(&AuthNowTime);
+        if (DiffTimeb(gRegTimeUp[plugNum][REG_CHARGING_CAP], AuthNowTime) > LOOP_RETRY_TIME ||
+                DiffTimeb(gRegTimeUp[plugNum][REG_CHARGING_CAP], AuthNowTime) < 0
+           ) {
+            readChargingCapability(fd, gunID);
+            ftime(&gRegTimeUp[plugNum][REG_CHARGING_CAP]);
+        }
+
+        ftime(&AuthNowTime);
+        if (DiffTimeb(gRegTimeUp[plugNum][REG_CHARGING_PERMISSION], AuthNowTime) > LOOP_RETRY_TIME ||
+                DiffTimeb(gRegTimeUp[plugNum][REG_CHARGING_PERMISSION], AuthNowTime) < 0
+           ) {
+            if (readChargePermission(fd, gunID) == 0) {
+                log_info("S_PREPARING_FOR_EV Stop charging by power cabinet's permission = %d, %d",
+                         plugNum,
+                         REG_CHARGING_PERMISSION);
+                pDcChargingInfo->StopChargeFlag = POWER_CABINET_STOP_CHARGING;
+            }
+            ftime(&gRegTimeUp[plugNum][REG_CHARGING_PERMISSION]);
+        }
+
+        ftime(&AuthNowTime);
+        if (DiffTimeb(gRegTimeUp[plugNum][REG_PRESENT_CHARGING_INFO], AuthNowTime) > LOOP_RETRY_TIME ||
+                DiffTimeb(gRegTimeUp[plugNum][REG_PRESENT_CHARGING_INFO], AuthNowTime) < 0
+           ) {
+            writePresentChargingInfo(fd, plugNum, gunID);
+			if (pDcChargingInfo->PantographFlag)
+				writeGroundFaultDetection(fd, 0, gunID);
+            ftime(&gRegTimeUp[plugNum][REG_PRESENT_CHARGING_INFO]);
+        }
+        break;
+
+    case S_PREPARING_FOR_EVSE: //insaulation test
+    case S_CCS_PRECHARGE_ST0:
+    case S_CCS_PRECHARGE_ST1:
+
+        writeChargingTarget(fd, plugNum, gunID);
+
+		if (pDcChargingInfo->PantographFlag)
+			writeGroundFaultDetection(fd, 1, gunID);
+
+        ftime(&AuthNowTime);
+        if (DiffTimeb(gRegTimeUp[plugNum][REG_CHARGING_CAP], AuthNowTime) > LOOP_RETRY_TIME ||
+                DiffTimeb(gRegTimeUp[plugNum][REG_CHARGING_CAP], AuthNowTime) < 0
+           ) {
+            readChargingCapability(fd, gunID);
+            ftime(&gRegTimeUp[plugNum][REG_CHARGING_CAP]);
+        }
+
+        ftime(&AuthNowTime);
+        if (DiffTimeb(gRegTimeUp[plugNum][REG_CHARGING_PERMISSION], AuthNowTime) > LOOP_RETRY_TIME ||
+                DiffTimeb(gRegTimeUp[plugNum][REG_CHARGING_PERMISSION], AuthNowTime) < 0
+           ) {
+            if (readChargePermission(fd, gunID) == 0) {
+                log_info("S_PREPARING_FOR_EVSE Stop charging by power cabinet's permission = %d, %d",
+                         plugNum,
+                         REG_CHARGING_PERMISSION);
+                pDcChargingInfo->StopChargeFlag = POWER_CABINET_STOP_CHARGING;
+            }
+            ftime(&gRegTimeUp[plugNum][REG_CHARGING_PERMISSION]);
+        }
+
+        ftime(&AuthNowTime);
+        if (DiffTimeb(gRegTimeUp[plugNum][REG_PRESENT_CHARGING_INFO], AuthNowTime) > LOOP_RETRY_TIME ||
+                DiffTimeb(gRegTimeUp[plugNum][REG_PRESENT_CHARGING_INFO], AuthNowTime) < 0
+           ) {
+            writePresentChargingInfo(fd, plugNum, gunID);
+            ftime(&gRegTimeUp[plugNum][REG_PRESENT_CHARGING_INFO]);
+        }
+        break;
+
+    case S_CHARGING: //charging
+    case S_TERMINATING:
+        if(pDcChargingInfo->Type == _Type_GB || pDcChargingInfo->Type == _Type_Chademo)
+        {
+			if (pDcChargingInfo->PantographFlag)
+				writeGroundFaultDetection(fd, 0, gunID);
+        }
+        else
+        {
+			if (pDcChargingInfo->PantographFlag)
+				writeGroundFaultDetection(fd, 1, gunID);
+        }
+
+        ftime(&AuthNowTime);
+        if (DiffTimeb(gRegTimeUp[plugNum][REG_CHARGING_CAP], AuthNowTime) > LOOP_RETRY_TIME ||
+                DiffTimeb(gRegTimeUp[plugNum][REG_CHARGING_CAP], AuthNowTime) < 0
+           ) {
+            readChargingCapability(fd, gunID);
+            ftime(&gRegTimeUp[plugNum][REG_CHARGING_CAP]);
+        }
+
+        ftime(&AuthNowTime);
+        if (DiffTimeb(gRegTimeUp[plugNum][REG_CHARGING_PERMISSION], AuthNowTime) > LOOP_RETRY_TIME ||
+                DiffTimeb(gRegTimeUp[plugNum][REG_CHARGING_PERMISSION], AuthNowTime) < 0
+           ) {
+            if (readChargePermission(fd, gunID) == 0) {
+                log_info("Stop charging by power cabinet's permission = %d, %d",
+                         plugNum,
+                         REG_CHARGING_PERMISSION);
+                pDcChargingInfo->StopChargeFlag = POWER_CABINET_STOP_CHARGING;
+                //printf("%d StopChargeFlag = %d\n", plugNum, pDcChargingInfo->StopChargeFlag);
+            }
+            ftime(&gRegTimeUp[plugNum][REG_CHARGING_PERMISSION]);
+        }
+        writeChargingTarget(fd, plugNum, gunID);
+
+        ftime(&AuthNowTime);
+        if (DiffTimeb(gRegTimeUp[plugNum][REG_PRESENT_CHARGING_INFO], AuthNowTime) > LOOP_RETRY_TIME ||
+                DiffTimeb(gRegTimeUp[plugNum][REG_PRESENT_CHARGING_INFO], AuthNowTime) < 0
+           ) {
+            writePresentChargingInfo(fd, plugNum, gunID);
+            ftime(&gRegTimeUp[plugNum][REG_PRESENT_CHARGING_INFO]);
+        }
+
+        break;
+
+    case S_COMPLETE:
+        ftime(&AuthNowTime);
+        if (DiffTimeb(gRegTimeUp[plugNum][REG_CHARGING_CAP], AuthNowTime) > LOOP_RETRY_TIME ||
+                DiffTimeb(gRegTimeUp[plugNum][REG_CHARGING_CAP], AuthNowTime) < 0
+           ) {
+            readChargingCapability(fd, gunID);
+			if (pDcChargingInfo->PantographFlag)
+				writeGroundFaultDetection(fd, 0, gunID);
+            ftime(&gRegTimeUp[plugNum][REG_CHARGING_CAP]);
+        }
+
+        ftime(&AuthNowTime);
+        if (DiffTimeb(gRegTimeUp[plugNum][REG_PRESENT_CHARGING_INFO], AuthNowTime) > LOOP_RETRY_TIME ||
+            DiffTimeb(gRegTimeUp[plugNum][REG_PRESENT_CHARGING_INFO], AuthNowTime) < 0
+            ) {
+            writePresentChargingInfo(fd, plugNum, gunID);
+            ftime(&gRegTimeUp[plugNum][REG_PRESENT_CHARGING_INFO]);
+        }
+        break;
+
+    default:
+        break;
+    }
+}
+
+static int networkCreatePorcess(void)
+{
+    int fd = 0;
+    uint8_t discount = 0;
+    while (pSysInfo->SelfTestSeq != _STEST_COMPLETE) {
+        usleep(128);
+    }
+
+    setTcpStatus(ABNORMAL);
+
+    /**************** Check Network **********/
+    //log_info("Check Dispenser Network Information");
+    while (pSysInfo->SelfTestSeq != _STEST_COMPLETE) {
+        usleep(125);
+    }
+
+    while (!CheckNetworkStatus()) {
+        calDisconnectCount(&gDoCommGblData.DisConnCount, CHECK_NETWORK_FAIL_COUNT);
+        if( gDoCommGblData.DisConnCount != discount ) {
+            discount =  gDoCommGblData.DisConnCount;
+            log_error("disconnect count = % d", gDoCommGblData.DisConnCount);
+        }
+    }
+    log_info("Dispenser Network Information checked: IP = % s Netmask = % s, Gateway = % s",
+             pSysConfig->Eth0Interface.EthIpAddress,
+             pSysConfig->Eth0Interface.EthSubmaskAddress,
+             pSysConfig->Eth0Interface.EthGatewayAddress);
+
+    gDoCommGblData.DisConnCount = 0;
+    discount = 0;
+
+    /**************** Power cabinet connection **********/
+    log_info("Connect to Power Cabinet");
+    while ((fd = doCommConnToServer()) <= 0) {
+        calDisconnectCount(&gDoCommGblData.DisConnCount, CONNECT_SERVER_FAIL_COUNT);
+        if( gDoCommGblData.DisConnCount != discount && fd == -1) {
+            discount = gDoCommGblData.DisConnCount;
+            log_error("disconnect count = %d, fd = %d", gDoCommGblData.DisConnCount, fd);
+        }
+    }
+    log_info("Power cabinet connected(fd = % d): IP = % s Netmask = % s, Gateway = % s",
+             fd,
+             pSysConfig->Eth0Interface.EthIpAddress,
+             pSysConfig->Eth0Interface.EthSubmaskAddress,
+             pSysConfig->Eth0Interface.EthGatewayAddress);
+
+    gDoCommGblData.DisConnCount = 0;
+    destroySelectGun(DESTROY_ALL_SEL);
+
+    sleep(3);
+
+    setTcpStatus(NORMAL);
+
+    return fd;
+}
+
+void CreditCardProcess(int fd,int plugNum,int gunID,bool isPark, RecordTransactionInfo *pInfo)
+{
+    struct timeb AuthNowTime = {0};
+    //佔位費處理
+    if (isPark) {
+        if (pInfo->IsUpload == TRUE || (strcmp((char*)pInfo->pCreditCard.ApprovalNo,"") == 0) ||
+            pInfo->DeductResult != _TCC_ONLINEPAY_PASS)
+            return;
+        ftime(&AuthNowTime);
+        if (DiffTimeb(gRegTimeUp[plugNum][REG_DEDUCT_INFO], AuthNowTime) > LOOP_RETRY_TIME * 5 ||
+            DiffTimeb(gRegTimeUp[plugNum][REG_DEDUCT_INFO], AuthNowTime) < 0
+            ) {
+                if (writeDeductInfo(fd, gunID, plugNum, pInfo) == PASS) {
+                    pInfo->IsUpload = TRUE;
+                    UpdateParkingUpload(pInfo->OccupancySN,YES);
+                } else {
+                    log_info("Gun%d Write Deduct fail",plugNum);
+                }
+                ftime(&gRegTimeUp[plugNum][REG_DEDUCT_INFO]);
+            }
+
+        return;
+    }
+
+    // 充電費處理
+    if (pInfo->IsUpload == TRUE || (strcmp((char*)pInfo->pCreditCard.VemData,"") == 0) ||
+        pSysInfo->SystemPage == _PAGE_SENSING || ShmDcCommonData->is_RemoteStart[plugNum])
+        return;
+
+    if (pInfo->ConnectorID != 0) {
+        ftime(&AuthNowTime);
+        if (DiffTimeb(gRegTimeUp[plugNum][REG_DEDUCT_INFO], AuthNowTime) > LOOP_RETRY_TIME * 5 ||
+            DiffTimeb(gRegTimeUp[plugNum][REG_DEDUCT_INFO], AuthNowTime) < 0
+            ) {
+                if (writeDeductInfo(fd, gunID, plugNum, pInfo) == PASS) {
+                    pInfo->IsUpload = TRUE;
+
+                    UpdateDeductInfoStatus(plugNum, pInfo);
+
+                    if (pInfo->DeductResult == _DEDUCT_CANCEL) {
+                        memset(&pInfo->pCreditCard, 0x00, sizeof(TransInfo));
+                    }
+
+                    log_info("Gun%d writeDeductInfo finish",plugNum);
+                } else {
+                    log_info("Gun%d Write Deduct fail",plugNum);
+                }
+                ftime(&gRegTimeUp[plugNum][REG_DEDUCT_INFO]);
+            }
+    }
+}
+int main(int argc, char *argv[])
+{
+    uint8_t plugNum = 0, gunID = 0;
+    uint8_t index = 0;
+    uint8_t totalConnCount = 0;
+    uint8_t initDone = DISPENER_INIT_FAIL;
+    char tmpbuf[256] = {0};
+    int fd = 0;
+    int isContinue = 1;
+
+    InitSocketSigPipe();
+
+    /**************** Initialization **********/
+    if (CreateAllCsuShareMemory() == FAIL) {
+        log_error("create share memory error");
+        return FAIL;
+    }
+
+    MappingGunChargingInfo("DoComm Task");
+
+    pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
+    pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
+    pSysWarning = (struct WARNING_CODE_INFO *)GetShmSysWarningInfo();
+
+    pAlarmCode = (struct AlarmCodeData *)GetShmAlarmCodeData();
+    ShmPsuData = (struct PsuData *)GetShmPsuData();
+    ShmPrimaryMcuData = (struct PrimaryMcuData *)GetShmPrimaryMcuData();
+    ShmOCPP16Data = (struct OCPP16Data *)GetShmOCPP16Data();
+    ShmSelectGunInfo = (SelectGunInfo *)GetShmSelectGunInfo();
+    ShmDcCommonData = (DcCommonInfo *)GetShmDcCommonData();
+
+    totalConnCount = pSysConfig->TotalConnectorCount;
+
+    for (index = 0; index < totalConnCount; index++) {
+        clearPricesInfo(index);
+    }
+
+    //initial trigger message timer
+    for (index = 0; index < MAX_REGISTER_NUM; index++) {
+        ftime(&gRegTimeUp[0][index]);
+        usleep(128);
+        ftime(&gRegTimeUp[1][index]);
+        usleep(50000);
+    }
+
+    setTcpStatus(NORMAL);
+
+    while (isContinue) {
+        if (initDone == DISPENER_INIT_FAIL) {
+            fd = networkCreatePorcess();
+
+            initDone = messageTrigger(fd, 0, 0, REG_MODEL_NAME); //first trigger model name and connector id
+        } else {
+            plugNum = 0;
+            gunID = 0;
+            for (plugNum = 0; plugNum < totalConnCount; plugNum++) {
+                //checkAuthorProcess(fd, plugNum);
+
+                //plugNum : setup chargingData value for bottom layer
+                //gunID : connector Id from power cabinet, 1 = left gun, 2 = right gun,
+                gunID = gDoCommGblData.ConnectorID[plugNum];
+                systemStatusProcess(fd, totalConnCount, plugNum, gunID);
+                if (ShmDcCommonData->pGunInfo[plugNum].ParkingStatus)
+                    CreditCardProcess(fd, plugNum,gunID,TRUE, &ShmDcCommonData->ParkingInfo[plugNum]);
+                else
+                    CreditCardProcess(fd, plugNum,gunID,FALSE, &ShmDcCommonData->TransactionInfo[plugNum]);
+
+                initDone = messageTrigger(fd,
+                                          plugNum,
+                                          gunID,
+                                          REG_POWER_CABINET_STATUS);
+
+                if (initDone == DISPENSER_SOCKET_RECONN) {
+                    break;
+                }
+            }
+        }
+
+        if (initDone != DISPENSER_SOCKET_RECONN) {
+            //update dispenser firmware
+            updateFirmwareProcess(fd, gDoCommGblData.ConnectorID[0], totalConnCount);
+
+            usleep(100000);
+            continue;
+        }
+
+        //Ethernet error recovery handle
+        log_info("Disconnected from power cabinet...re-connecting");
+        setTcpStatus(ABNORMAL);
+
+
+        if (pSysConfig->Eth0Interface.EthDhcpClient == 0) {
+            system("pgrep -f \"udhcpc -i eth0\" | xargs kill");
+            sprintf(tmpbuf,
+                    "/sbin/udhcpc -i eth0 -x hostname:CSU3_%s -s /root/dhcp_script/eth0.script > /dev/null &",
+                    pSysConfig->SystemId);
+            system(tmpbuf);
+        }
+
+        gDoCommGblData.DisConnCount = 0;
+        gDoCommGblData.SeqNum = 0;
+
+        closeSocket(fd);
+        fd = 0;
+
+        initDone = DISPENER_INIT_FAIL;
+    }
+}

+ 358 - 358
EVSE/Projects/DD360Tcci/Apps/ModuleDoComm/DoComm.h

@@ -1,358 +1,358 @@
-#ifndef _DO_COMM_H_
-#define _DO_COMM_H_
-
-//------------------------------------------------------------------------------
-#include <stdint.h>
-
-//------------------------------------------------------------------------------
-//--- common define ---
-//------------------------------------------------------------------------------
-#define CMP_ETH_IP_HEAD                         "192.168.100"
-
-#define DoIPAddress                             "192.168.100.1"
-#define DoTcpPort                               36000
-
-#define IMAGE_FILE_PATH                         "../mnt"
-#define TFTP_PULL_CMD                           "tftp"
-#define SIGTERM_MSG                             "SegmentFault.~~~~\n"
-
-#define MAX_REGISTER_NUM                        45
-
-#define CHECK_NETWORK_FAIL_COUNT                10//10
-#define CONNECT_SERVER_FAIL_COUNT               3//5
-#define WARNING_CODE_SIZE                       6
-
-#define MAX_VOLTAGE                             10000
-#define MAX_CURRENCY                            5000
-#define MAX_POWER                               3600
-
-#define DISPENSER_INIT_SUCC                     0x01
-#define DISPENER_INIT_FAIL                      0x02
-#define DISPENSER_SOCKET_RECONN                 0x03
-
-#define VERSION_BUF_SIZE                        32
-
-#define PRICES_UNIT                             0.01
-
-#define LOOP_RETRY_TIME                         1000 //1 second
-
-//------------------------------------------------------------------------------
-//--- dispenser ID ---
-//------------------------------------------------------------------------------
-#define ID_RESERVER                             0x00
-#define ID_OF_DISPENSER                         0x01
-#define ID_REGISTER                             0xFF
-
-//------------------------------------------------------------------------------
-//--- dispenser operation ---
-//------------------------------------------------------------------------------
-#define OP_READ_DATA                            0x01
-#define OP_WRITE_DATA                           0x02
-#define OP_WAIT_RESPONSE                        0x03
-
-//------------------------------------------------------------------------------
-//--- connector status ---
-//------------------------------------------------------------------------------
-#define CONN_ST_IDLE                            0x00
-#define CONN_ST_PREPARING                       0x01
-#define CONN_ST_CHARGING                        0x02
-#define CONN_ST_TERMINATING                     0x03
-#define CONN_ST_ALARM                           0x04
-
-//------------------------------------------------------------------------------
-//--- dispenser register ---
-//------------------------------------------------------------------------------
-#define REG_MODEL_NAME                          0x01
-#define REG_CONNECTOR_ID                        0x02
-#define REG_POWER_CABINET_STATUS                0x03
-#define REG_DISPENSER_STATUS                    0x04
-#define REG_CHARGING_CAP                        0x05
-#define REG_CHARGING_TARGET                     0x06
-#define REG_SOFTWARE_UPDATE                     0x07
-#define REG_PLUG_IN_STATE                       0x08
-#define REG_CONNECTOR_STATE                     0x09
-#define REG_USER_ID                             0x0A
-#define REG_CHARGING_PERMISSION                 0x0B
-#define REG_MISC_CONTROL                        0X0C
-#define REG_REPORT_CSU_VERSION                  0X0D
-#define REG_REPORT_OTHER_VERSION                0X0E
-#define REG_PRESENT_CHARGING_INFO               0X0F
-#define REG_QRCODE_URL_INFO                     0X10
-#define REG_WAIT_PLUG_IT_STATE                  0x11
-#define REG_Ground_Fault_Detection              0x12
-#define REG_CABINET_DCM_VERSION                 0x13
-#define REG_CABINET_OTHER_VERSION               0x14
-#define REG_TOTAL_PSU_QUANTITY                  0x15
-#define REG_PSU_VERSION                         0x16
-#define REG_RESERVATION_IDTAG                   0x17
-#define REG_DISPENSER_REQUEST                   0x18
-#define REG_REMOTE_START_NO_ID                  0x19
-#define REG_REFUND_AMOUNT                       0x1A
-#define REG_PREPAYMENT_INFO                     0x1B
-#define REG_PAYMENT_FAIL_REASON                 0x1C
-#define REG_CONNECTOR_QR_CODE                   0x1D
-#define REG_STATION_INFO                        0x1E
-#define REG_DEDUCT_INFO                         0x1F
-#define REG_READ_CABINET_SYSTEMID               0x20
-#define REG_READ_DEFAULT_PRICE                  0x21
-#define REG_READ_USER_PRICE                     0x22
-#define REG_RECEIPT_INFO                        0x23
-#define REG_POWER_CONSUMPTION_INFO              0x24
-#define REG_READ_CHARGING_TIMESTAMP             0x25
-#define REG_CHARGING_BILL                       0x26
-#define REG_PARKING_STATUS                      0x27
-#define REG_PARKING_BILL                        0x28
-
-//------------------------------------------------------------------------------
-//--- dispenser result ---
-//------------------------------------------------------------------------------
-#define COMMAND_RESULT_OK                       0x01
-#define COMMAND_RESULT_NG                       0x02 //wait state
-
-//------------------------------------------------------------------------------
-//--- power cabinet misc status code ---
-//------------------------------------------------------------------------------
-#define MISC_ST_MISC_CMD                        "B40001"
-
-#define MISC_ST_VERSION                         "B40999"
-
-//------------------------------------------------------------------------------
-//--- power cabinet misc command ---
-//------------------------------------------------------------------------------
-#define MISC_CMD_CONNECOTOR_TIMEOUT             (0X0001)
-#define MISC_CMD_OPERATIVE_STATE                (0X0002)
-#define MISC_CMD_DEFAULT_PRICES                 (0x0003)
-#define MISC_CMD_DEFAULT_CURRENCY               (0x0004)
-#define MISC_CMD_ACCOUNT_BALANCE                (0x0005)
-
-#define MISC_CMD_BACKEND_STATUS                 (0x0006)
-#define MISC_CMD_ETHERNET_STATUS                (0x0007)
-#define MISC_CMD_WIFI_STATUS                    (0x0008)
-#define MISC_CMD_4G_STATUS                      (0x0009)
-#define MISC_CMD_BILLING_INFO                   (0x000A)
-#define MISC_CMD_WEB_STOP_CHARGING              (0x000B)
-#define MISC_CMD_AUTH_DISABLE					(0x000C)
-#define MISC_CMD_EVCCID_ENABLE					(0x000D)
-#define MISC_CMD_LED_INTENSITY                  (0x000E)
-#define MISC_CMD_AC_CONTACTOR                   (0x000F)
-#define MISC_CMD_TIME_OFFSET                    (0x0010)
-#define MISC_CMD_PAKING_PRICES                  (0x0011)
-#define MISC_CMD_RFID_ENDIAN                    (0x0012)
-
-#define MISC_CMD_HARDWARE_REBOOT                (0x0101)
-#define MISC_CMD_SOFTWARE_RESTART               (0x0102)
-#define MISC_CMD_REMOTE_START_CHARGING          (0x0103)
-#define MISC_CMD_REMOTE_STOP_CHARGING           (0x0104)
-#define MISC_CMD_REMOTE_UNLOCK                  (0x0105)
-#define MISC_CMD_RESERVATION                    (0x0106)
-#define MISC_CMD_CHANGE_LCM_PAGE                (0x0107)
-#define MISC_CMD_QR_CODE_REQ                    (0x0108)
-#define MISC_CMD_STATION_INFO_REQ               (0x0109)
-#define MISC_CMD_FINAL_COST_REQ                 (0x010A)
-#define MISC_CMD_LINE_STATUS_REQ                (0x010B)
-#define MISC_CMD_DEFAULT_PRICE_REQ              (0x010C)
-#define MISC_CMD_USER_PRICE_REQ                 (0x010D)
-#define MISC_CMD_RECEIPT_REQ                    (0x010E)
-#define MISC_CMD_CHARGING_BILL                  (0x010F)
-#define MISC_CMD_PARKING_STATUS                 (0x0110)
-
-#define ST_UPDATE_FIRMWARE                      (0x01)
-#define ST_NO_UPDATE_FIRMWARE                   (0x02)
-
-#define LCM_PAGE_REMOTE_START_NO_ID             (0x0001)
-#define DISPENSER_REQ_CHARGING_CANCEL           (0x0001)
-#define DISPENSER_REQ_PARKING_BILL              (0x0002)
-#define UPLOAD_DEDUCT_DB						(0x5656)
-
-
-//------------------------------------------------------------------------------
-#pragma pack(push)
-#pragma pack(1)
-typedef union
-{
-    unsigned int Value;
-    struct
-    {
-        unsigned int ChargingCancel : 1; // 0: no effect, 1: charging cancel request
-        unsigned int ParkingBillReq : 1; // 0: no effect, 1: Parking Bill Request
-        unsigned int res : 30;
-    }bits;
-} ConnectorActReqVar;
-
-typedef struct StDeductInfoVar {
-    unsigned char DeductResult;                     // 0: Fail, 1: Pass
-    unsigned char IsDonateInvoice;                  // 0: Do not donate, 1: Donate
-    int TransactionId;								// transaction id
-    int Amount;                                     // unit = 0.01 dollar
-    char ApprovalNumber[12];						// approval number
-} DeductInfoVar;
-
-/*
-typedef union
-{
-    unsigned int Value;
-    struct
-    {
-        unsigned int JoinLine:1;                    // 0: no effect,                1: JoinLine page is trigger
-        unsigned int PaymentSwitch:1;               // 0: no effect,                1: PaymentSwitch page is trigger
-        unsigned int res:30;
-    }bits;
-} ChangePageReq;
-*/
-
-typedef union
-{
-    unsigned int Value;
-    struct
-    {
-        unsigned int ReservationReq:1;              // 0: no effect,                1: need to request Reservation
-        unsigned int RemoteStartNoID:1;             // 0: no effect,                1: need to request RemoteStartNoID
-        unsigned int StationInfoReq:1;              // 0: no effect,                1: need to request StationInfo
-        unsigned int FinalCostReq:1;                // 0: no effect,                1: need to request FinalCost
-        unsigned int ChargingBill:1;                // 0: no effect,                1: need to request ChargineBill
-        unsigned int ParkingReq : 1;                // 0: no effect,                1: need to request Parking
-        unsigned int res:26;
-    } bits;
-} MoreInfoReq;
-
-typedef struct StStationVar {
-    int StationID;
-    char StationName[64];
-    int WeatherID;
-    float Temperature;
-} StationVar;
-
-typedef struct StConnectorState {
-    uint8_t State;
-    uint8_t WarningCode[6];
-    uint8_t ConnectorTemp;
-    uint8_t ChillerTemp;
-    uint8_t PlugIn;
-    uint32_t consumption;
-    uint8_t ConnectMode;
-} ConnectorState;
-
-typedef struct StConnectorIDTable {
-    uint8_t DcConnID1;
-    uint8_t DcConnID2;
-    uint8_t AcConnID;
-    uint8_t Reserved;
-} ConnectorIDTable;
-
-typedef struct StDoCommGlobalVar {
-    uint8_t SeqNum;
-    uint8_t DisConnCount;
-    uint8_t ConnectorID[3]; //keep from power cabinet
-    uint8_t MiscCmd;
-    uint8_t Reserved[2];
-} DoCommGblData;
-
-typedef struct StCommnadHead {
-    uint8_t SeqNum;     //sequence number 0 ~ 255
-    uint8_t ID;         //0: Reserved, 0x01 ~ 0xFE: connector ID, 0xFF: exists in register 1 and register 2
-    uint8_t OP;         //0x01: read, 0x02: write, 0x03: response from power cabinet
-    uint8_t DataLen;    //raw data Length
-} CmdHead;
-
-typedef struct StCommandData {
-    uint8_t Register;   /*  0x01: dispenser model name (maximum 32 bytes) and the value of dispenser switch
-                            0x02: The ID to connector equipped at dispenser
-                            0x03: Power cabinet status
-                            0x04: Dispenser status
-                            0x05: The charging capacity of each connector
-                            0x06: The required voltage and current during charging
-                            0x07: The indicator of software update to dispenser
-                            0x08: Indicate whether the connector is plug-in or not
-                            0x09: Indicate the connector state
-                            0x0A: The user ID can be RFID card number, EVCCID, etc.
-                            0x0B: Charging permission from power cabinet to dispenser
-                        */
-    uint8_t Data[250];
-} CmdData;
-
-typedef struct StResultData {
-    uint8_t Register;   /*  0x01: dispenser model name (maximum 32 bytes) and the value of dispenser switch
-                            0x02: The ID to connector equipped at dispenser
-                            0x03: Power cabinet status
-                            0x04: Dispenser status
-                            0x05: The charging capacity of each connector
-                            0x06: The required voltage and current during charging
-                            0x07: The indicator of software update to dispenser
-                            0x08: Indicate whether the connector is plug-in or not
-                            0x09: Indicate the connector state
-                            0x0A: The user ID can be RFID card number, EVCCID, etc.
-                            0x0B: Charging permission from power cabinet to dispenser
-                        */
-    uint8_t Result;
-    uint8_t Data[249];
-} ResultData;
-
-typedef struct StCsuCmdPkt {
-    CmdHead Head;
-    CmdData Data;
-} CsuCmdPkt;
-
-typedef struct StCsuResultPkt {
-    CmdHead Head;
-    ResultData Data;
-} CsuResultPkt;
-
-typedef struct StMiscCommand {
-    uint16_t CMD;
-    uint8_t Value[4];
-} MiscCommand;
-
-typedef struct StPresentChargingInfo {
-    uint16_t PresentChargingVoltage;   //0~6553.5 volt
-    uint16_t PresentChargingCurrent;   //0~6553.5 amp
-    int RemainChargingDuration;     // second
-    uint8_t EvBatterySoc;               // 0~100%
-} PreChargingInfo;
-
-typedef struct StGroundFaultDetection { //Ground Fault Detection
-    uint8_t Status;
-} GroundFaultDetection;
-
-typedef struct StSoftwareUpdInfo {
-    uint8_t UpdateState;         //1:update , 2: not update
-    uint8_t ImgName[248];
-} SoftwareUpdInfo;
-
-typedef struct StCapabilityInfo {
-    uint16_t OutputVoltage;
-    uint16_t OutputCurrent;
-    uint16_t OutputPower;
-    uint8_t Reserved[2];
-} CapabilityInfo;
-
-typedef struct StAccountInfo {
-    uint8_t Currency;
-    int UserPrices;
-    int TotalCost;
-    int Balance;
-    int Discount;
-    int Transaction;
-    int EnergyCost;
-    int ParkingFee;
-    uint32_t RemainAmount;
-    uint8_t Reserved[1];
-} AccountInfo;
-
-typedef struct StChargingBillInfo {
-    int TotalCost;
-    int Balance;
-    int Discount;
-    int Transaction;
-    int EnergyCost;
-    int ParkingFee;
-    uint32_t RemainAmount;
-} ChargingBillInfo;
-
-typedef struct StParkingBillInfo {
-    int ParkingFee;
-    int Duration;
-} ParkingBillInfo;
-
-#pragma pack(pop)
-
-#endif /* _DO_COMM_H_ */
+#ifndef _DO_COMM_H_
+#define _DO_COMM_H_
+
+//------------------------------------------------------------------------------
+#include <stdint.h>
+
+//------------------------------------------------------------------------------
+//--- common define ---
+//------------------------------------------------------------------------------
+#define CMP_ETH_IP_HEAD                         "192.168.100"
+
+#define DoIPAddress                             "192.168.100.1"
+#define DoTcpPort                               36000
+
+#define IMAGE_FILE_PATH                         "../mnt"
+#define TFTP_PULL_CMD                           "tftp"
+#define SIGTERM_MSG                             "SegmentFault.~~~~\n"
+
+#define MAX_REGISTER_NUM                        45
+
+#define CHECK_NETWORK_FAIL_COUNT                10//10
+#define CONNECT_SERVER_FAIL_COUNT               3//5
+#define WARNING_CODE_SIZE                       6
+
+#define MAX_VOLTAGE                             10000
+#define MAX_CURRENCY                            5000
+#define MAX_POWER                               3600
+
+#define DISPENSER_INIT_SUCC                     0x01
+#define DISPENER_INIT_FAIL                      0x02
+#define DISPENSER_SOCKET_RECONN                 0x03
+
+#define VERSION_BUF_SIZE                        32
+
+#define PRICES_UNIT                             0.01
+
+#define LOOP_RETRY_TIME                         1000 //1 second
+
+//------------------------------------------------------------------------------
+//--- dispenser ID ---
+//------------------------------------------------------------------------------
+#define ID_RESERVER                             0x00
+#define ID_OF_DISPENSER                         0x01
+#define ID_REGISTER                             0xFF
+
+//------------------------------------------------------------------------------
+//--- dispenser operation ---
+//------------------------------------------------------------------------------
+#define OP_READ_DATA                            0x01
+#define OP_WRITE_DATA                           0x02
+#define OP_WAIT_RESPONSE                        0x03
+
+//------------------------------------------------------------------------------
+//--- connector status ---
+//------------------------------------------------------------------------------
+#define CONN_ST_IDLE                            0x00
+#define CONN_ST_PREPARING                       0x01
+#define CONN_ST_CHARGING                        0x02
+#define CONN_ST_TERMINATING                     0x03
+#define CONN_ST_ALARM                           0x04
+
+//------------------------------------------------------------------------------
+//--- dispenser register ---
+//------------------------------------------------------------------------------
+#define REG_MODEL_NAME                          0x01
+#define REG_CONNECTOR_ID                        0x02
+#define REG_POWER_CABINET_STATUS                0x03
+#define REG_DISPENSER_STATUS                    0x04
+#define REG_CHARGING_CAP                        0x05
+#define REG_CHARGING_TARGET                     0x06
+#define REG_SOFTWARE_UPDATE                     0x07
+#define REG_PLUG_IN_STATE                       0x08
+#define REG_CONNECTOR_STATE                     0x09
+#define REG_USER_ID                             0x0A
+#define REG_CHARGING_PERMISSION                 0x0B
+#define REG_MISC_CONTROL                        0X0C
+#define REG_REPORT_CSU_VERSION                  0X0D
+#define REG_REPORT_OTHER_VERSION                0X0E
+#define REG_PRESENT_CHARGING_INFO               0X0F
+#define REG_QRCODE_URL_INFO                     0X10
+#define REG_WAIT_PLUG_IT_STATE                  0x11
+#define REG_Ground_Fault_Detection              0x12
+#define REG_CABINET_DCM_VERSION                 0x13
+#define REG_CABINET_OTHER_VERSION               0x14
+#define REG_TOTAL_PSU_QUANTITY                  0x15
+#define REG_PSU_VERSION                         0x16
+#define REG_RESERVATION_IDTAG                   0x17
+#define REG_DISPENSER_REQUEST                   0x18
+#define REG_REMOTE_START_NO_ID                  0x19
+#define REG_REFUND_AMOUNT                       0x1A
+#define REG_PREPAYMENT_INFO                     0x1B
+#define REG_PAYMENT_FAIL_REASON                 0x1C
+#define REG_CONNECTOR_QR_CODE                   0x1D
+#define REG_STATION_INFO                        0x1E
+#define REG_DEDUCT_INFO                         0x1F
+#define REG_READ_CABINET_SYSTEMID               0x20
+#define REG_READ_DEFAULT_PRICE                  0x21
+#define REG_READ_USER_PRICE                     0x22
+#define REG_RECEIPT_INFO                        0x23
+#define REG_POWER_CONSUMPTION_INFO              0x24
+#define REG_READ_CHARGING_TIMESTAMP             0x25
+#define REG_CHARGING_BILL                       0x26
+#define REG_PARKING_STATUS                      0x27
+#define REG_PARKING_BILL                        0x28
+
+//------------------------------------------------------------------------------
+//--- dispenser result ---
+//------------------------------------------------------------------------------
+#define COMMAND_RESULT_OK                       0x01
+#define COMMAND_RESULT_NG                       0x02 //wait state
+
+//------------------------------------------------------------------------------
+//--- power cabinet misc status code ---
+//------------------------------------------------------------------------------
+#define MISC_ST_MISC_CMD                        "B40001"
+
+#define MISC_ST_VERSION                         "B40999"
+
+//------------------------------------------------------------------------------
+//--- power cabinet misc command ---
+//------------------------------------------------------------------------------
+#define MISC_CMD_CONNECOTOR_TIMEOUT             (0X0001)
+#define MISC_CMD_OPERATIVE_STATE                (0X0002)
+#define MISC_CMD_DEFAULT_PRICES                 (0x0003)
+#define MISC_CMD_DEFAULT_CURRENCY               (0x0004)
+#define MISC_CMD_ACCOUNT_BALANCE                (0x0005)
+
+#define MISC_CMD_BACKEND_STATUS                 (0x0006)
+#define MISC_CMD_ETHERNET_STATUS                (0x0007)
+#define MISC_CMD_WIFI_STATUS                    (0x0008)
+#define MISC_CMD_4G_STATUS                      (0x0009)
+#define MISC_CMD_BILLING_INFO                   (0x000A)
+#define MISC_CMD_WEB_STOP_CHARGING              (0x000B)
+#define MISC_CMD_AUTH_DISABLE					(0x000C)
+#define MISC_CMD_EVCCID_ENABLE					(0x000D)
+#define MISC_CMD_LED_INTENSITY                  (0x000E)
+#define MISC_CMD_AC_CONTACTOR                   (0x000F)
+#define MISC_CMD_TIME_OFFSET                    (0x0010)
+#define MISC_CMD_PAKING_PRICES                  (0x0011)
+#define MISC_CMD_RFID_ENDIAN                    (0x0012)
+
+#define MISC_CMD_HARDWARE_REBOOT                (0x0101)
+#define MISC_CMD_SOFTWARE_RESTART               (0x0102)
+#define MISC_CMD_REMOTE_START_CHARGING          (0x0103)
+#define MISC_CMD_REMOTE_STOP_CHARGING           (0x0104)
+#define MISC_CMD_REMOTE_UNLOCK                  (0x0105)
+#define MISC_CMD_RESERVATION                    (0x0106)
+#define MISC_CMD_CHANGE_LCM_PAGE                (0x0107)
+#define MISC_CMD_QR_CODE_REQ                    (0x0108)
+#define MISC_CMD_STATION_INFO_REQ               (0x0109)
+#define MISC_CMD_FINAL_COST_REQ                 (0x010A)
+#define MISC_CMD_LINE_STATUS_REQ                (0x010B)
+#define MISC_CMD_DEFAULT_PRICE_REQ              (0x010C)
+#define MISC_CMD_USER_PRICE_REQ                 (0x010D)
+#define MISC_CMD_RECEIPT_REQ                    (0x010E)
+#define MISC_CMD_CHARGING_BILL                  (0x010F)
+#define MISC_CMD_PARKING_STATUS                 (0x0110)
+
+#define ST_UPDATE_FIRMWARE                      (0x01)
+#define ST_NO_UPDATE_FIRMWARE                   (0x02)
+
+#define LCM_PAGE_REMOTE_START_NO_ID             (0x0001)
+#define DISPENSER_REQ_CHARGING_CANCEL           (0x0001)
+#define DISPENSER_REQ_PARKING_BILL              (0x0002)
+#define UPLOAD_DEDUCT_DB						(0x5656)
+
+
+//------------------------------------------------------------------------------
+#pragma pack(push)
+#pragma pack(1)
+typedef union
+{
+    unsigned int Value;
+    struct
+    {
+        unsigned int ChargingCancel : 1; // 0: no effect, 1: charging cancel request
+        unsigned int ParkingBillReq : 1; // 0: no effect, 1: Parking Bill Request
+        unsigned int res : 30;
+    }bits;
+} ConnectorActReqVar;
+
+typedef struct StDeductInfoVar {
+    unsigned char DeductResult;                     // 0: Fail, 1: Pass
+    unsigned char IsDonateInvoice;                  // 0: Do not donate, 1: Donate
+    int TransactionId;								// transaction id
+    int Amount;                                     // unit = 0.01 dollar
+    char ApprovalNumber[12];						// approval number
+} DeductInfoVar;
+
+/*
+typedef union
+{
+    unsigned int Value;
+    struct
+    {
+        unsigned int JoinLine:1;                    // 0: no effect,                1: JoinLine page is trigger
+        unsigned int PaymentSwitch:1;               // 0: no effect,                1: PaymentSwitch page is trigger
+        unsigned int res:30;
+    }bits;
+} ChangePageReq;
+*/
+
+typedef union
+{
+    unsigned int Value;
+    struct
+    {
+        unsigned int ReservationReq:1;              // 0: no effect,                1: need to request Reservation
+        unsigned int RemoteStartNoID:1;             // 0: no effect,                1: need to request RemoteStartNoID
+        unsigned int StationInfoReq:1;              // 0: no effect,                1: need to request StationInfo
+        unsigned int FinalCostReq:1;                // 0: no effect,                1: need to request FinalCost
+        unsigned int ChargingBill:1;                // 0: no effect,                1: need to request ChargineBill
+        unsigned int ParkingReq : 1;                // 0: no effect,                1: need to request Parking
+        unsigned int res:26;
+    } bits;
+} MoreInfoReq;
+
+typedef struct StStationVar {
+    int StationID;
+    char StationName[64];
+    int WeatherID;
+    float Temperature;
+} StationVar;
+
+typedef struct StConnectorState {
+    uint8_t State;
+    uint8_t WarningCode[6];
+    uint8_t ConnectorTemp;
+    uint8_t ChillerTemp;
+    uint8_t PlugIn;
+    uint32_t consumption;
+    uint8_t ConnectMode;
+} ConnectorState;
+
+typedef struct StConnectorIDTable {
+    uint8_t DcConnID1;
+    uint8_t DcConnID2;
+    uint8_t AcConnID;
+    uint8_t Reserved;
+} ConnectorIDTable;
+
+typedef struct StDoCommGlobalVar {
+    uint8_t SeqNum;
+    uint8_t DisConnCount;
+    uint8_t ConnectorID[3]; //keep from power cabinet
+    uint8_t MiscCmd;
+    uint8_t Reserved[2];
+} DoCommGblData;
+
+typedef struct StCommnadHead {
+    uint8_t SeqNum;     //sequence number 0 ~ 255
+    uint8_t ID;         //0: Reserved, 0x01 ~ 0xFE: connector ID, 0xFF: exists in register 1 and register 2
+    uint8_t OP;         //0x01: read, 0x02: write, 0x03: response from power cabinet
+    uint8_t DataLen;    //raw data Length
+} CmdHead;
+
+typedef struct StCommandData {
+    uint8_t Register;   /*  0x01: dispenser model name (maximum 32 bytes) and the value of dispenser switch
+                            0x02: The ID to connector equipped at dispenser
+                            0x03: Power cabinet status
+                            0x04: Dispenser status
+                            0x05: The charging capacity of each connector
+                            0x06: The required voltage and current during charging
+                            0x07: The indicator of software update to dispenser
+                            0x08: Indicate whether the connector is plug-in or not
+                            0x09: Indicate the connector state
+                            0x0A: The user ID can be RFID card number, EVCCID, etc.
+                            0x0B: Charging permission from power cabinet to dispenser
+                        */
+    uint8_t Data[250];
+} CmdData;
+
+typedef struct StResultData {
+    uint8_t Register;   /*  0x01: dispenser model name (maximum 32 bytes) and the value of dispenser switch
+                            0x02: The ID to connector equipped at dispenser
+                            0x03: Power cabinet status
+                            0x04: Dispenser status
+                            0x05: The charging capacity of each connector
+                            0x06: The required voltage and current during charging
+                            0x07: The indicator of software update to dispenser
+                            0x08: Indicate whether the connector is plug-in or not
+                            0x09: Indicate the connector state
+                            0x0A: The user ID can be RFID card number, EVCCID, etc.
+                            0x0B: Charging permission from power cabinet to dispenser
+                        */
+    uint8_t Result;
+    uint8_t Data[249];
+} ResultData;
+
+typedef struct StCsuCmdPkt {
+    CmdHead Head;
+    CmdData Data;
+} CsuCmdPkt;
+
+typedef struct StCsuResultPkt {
+    CmdHead Head;
+    ResultData Data;
+} CsuResultPkt;
+
+typedef struct StMiscCommand {
+    uint16_t CMD;
+    uint8_t Value[4];
+} MiscCommand;
+
+typedef struct StPresentChargingInfo {
+    uint16_t PresentChargingVoltage;   //0~6553.5 volt
+    uint16_t PresentChargingCurrent;   //0~6553.5 amp
+    int RemainChargingDuration;     // second
+    uint8_t EvBatterySoc;               // 0~100%
+} PreChargingInfo;
+
+typedef struct StGroundFaultDetection { //Ground Fault Detection
+    uint8_t Status;
+} GroundFaultDetection;
+
+typedef struct StSoftwareUpdInfo {
+    uint8_t UpdateState;         //1:update , 2: not update
+    uint8_t ImgName[248];
+} SoftwareUpdInfo;
+
+typedef struct StCapabilityInfo {
+    uint16_t OutputVoltage;
+    uint16_t OutputCurrent;
+    uint16_t OutputPower;
+    uint8_t Reserved[2];
+} CapabilityInfo;
+
+typedef struct StAccountInfo {
+    uint8_t Currency;
+    int UserPrices;
+    int TotalCost;
+    int Balance;
+    int Discount;
+    int Transaction;
+    int EnergyCost;
+    int ParkingFee;
+    uint32_t RemainAmount;
+    uint8_t Reserved[1];
+} AccountInfo;
+
+typedef struct StChargingBillInfo {
+    int TotalCost;
+    int Balance;
+    int Discount;
+    int Transaction;
+    int EnergyCost;
+    int ParkingFee;
+    uint32_t RemainAmount;
+} ChargingBillInfo;
+
+typedef struct StParkingBillInfo {
+    int ParkingFee;
+    int Duration;
+} ParkingBillInfo;
+
+#pragma pack(pop)
+
+#endif /* _DO_COMM_H_ */

+ 918 - 918
EVSE/Projects/DD360Tcci/Apps/ModuleEvComm/AbnormalCCS.c

@@ -1,918 +1,918 @@
-#include <stdio.h>
-#include <stdint.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include "../Config.h"
-#include "../Log/log.h"
-#include "../ShareMemory/shmMem.h"
-#include "../Define/define.h"
-
-//------------------------------------------------------------------------------
-void ClearAbnormalStatus_CCS(uint8_t gun_index)
-{
-    bool isCleanCheck = false;
-    char code[7];
-    struct SysConfigData *pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
-    struct InfoCodeData *pInfoCode = (struct InfoCodeData *)GetShmInfoCodeData();
-    struct AlarmCodeData *pAlarmCode = (struct AlarmCodeData *)GetShmAlarmCodeData();
-    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gun_index);
-    memset(code, '\n', sizeof(code));
-    
-    if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "", 6) == EQUAL) {
-        return;
-    }
-
-    if (true) {
-        if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "012219", 6) == EQUAL &&
-                pAlarmCode->AlarmEvents.bits.SystemCcsOutputOVP == YES) {
-            memcpy(code, "012219", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023701", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsEvCommFail == YES) {
-            memcpy(code, "023701", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023737", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsRESTemperatureInhibit == YES) {
-            memcpy(code, "023737", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023738", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsEVShiftPosition == YES) {
-            memcpy(code, "023738", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023739", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsChargerConnectorLockFault == YES) {
-            memcpy(code, "023739", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023740", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsEVRESSMalfunction == YES) {
-            memcpy(code, "023740", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023741", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsChargingCurrentdifferential == YES) {
-            memcpy(code, "023741", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023742", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsChargingVoltageOutOfRange == YES) {
-            memcpy(code, "023742", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023743", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsChargingSystemIncompatibility == YES) {
-            memcpy(code, "023743", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023744", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsEmergencyEvent == YES) {
-            memcpy(code, "023744", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023745", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsBreaker == YES) {
-            memcpy(code, "023745", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023746", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsNoData == YES) {
-            memcpy(code, "023746", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023747", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.Ccsreserved_by_DIN_A == YES) {
-            memcpy(code, "023747", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023748", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.Ccsreserved_by_DIN_B == YES) {
-            memcpy(code, "023748", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023749", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.Ccsreserved_by_DIN_C == YES) {
-            memcpy(code, "023749", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023750", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.Ccsreserved_by_ISO_1 == YES) {
-            memcpy(code, "023750", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023751", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.Ccsreserved_by_ISO_2 == YES) {
-            memcpy(code, "023751", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023752", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.Ccsreserved_by_ISO_3 == YES) {
-            memcpy(code, "023752", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023753", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.Ccsreserved_by_OEM_1 == YES) {
-            memcpy(code, "023753", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023754", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.Ccsreserved_by_OEM_2 == YES) {
-            memcpy(code, "023754", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023755", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.Ccsreserved_by_OEM_3 == YES) {
-            memcpy(code, "023755", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023756", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.Ccsreserved_by_OEM_4 == YES) {
-            memcpy(code, "023756", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023757", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.Ccsreserved_by_OEM_5 == YES) {
-            memcpy(code, "023757", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023758", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsSequenceError == YES) {
-            memcpy(code, "023758", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023759", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsSignatureError == YES) {
-            memcpy(code, "023759", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023760", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsUnknownSession == YES) {
-            memcpy(code, "023760", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023761", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsServiceIDInvalid == YES) {
-            memcpy(code, "023761", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023762", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsPaymentSelectionInvalid == YES) {
-            memcpy(code, "023762", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023763", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsIdentificationSelectionInvalid == YES) {
-            memcpy(code, "023763", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023764", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsServiceSelectionInvalid == YES) {
-            memcpy(code, "023764", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023765", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsCertificateExpired == YES) {
-            memcpy(code, "023765", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023766", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsCertificateNotYetValid == YES) {
-            memcpy(code, "023766", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023767", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsCertificateRevoked == YES) {
-            memcpy(code, "023767", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023768", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsNoCertificateAvailable == YES) {
-            memcpy(code, "023768", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023769", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsCertChainError == YES) {
-            memcpy(code, "023769", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023770", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsCertValidationError == YES) {
-            memcpy(code, "023770", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023771", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsCertVerificationError == YES) {
-            memcpy(code, "023771", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023772", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsContractCanceled == YES) {
-            memcpy(code, "023772", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023773", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsChallengeInvalid == YES) {
-            memcpy(code, "023773", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023774", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsWrongEnergyTransferMode == YES) {
-            memcpy(code, "023774", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023775", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsWrongChargeParameter == YES) {
-            memcpy(code, "023775", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023776", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsChargingProfileInvalid == YES) {
-            memcpy(code, "023776", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023777", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsTariffSelectionInvalid == YES) {
-            memcpy(code, "023777", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023778", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsEVSEPresentVoltageToLow == YES) {
-            memcpy(code, "023778", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023779", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsPowerDeliveryNotApplied == YES) {
-            memcpy(code, "023779", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023780", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsMeteringSignatureNotValid == YES) {
-            memcpy(code, "023780", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023781", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsNoChargeServiceSelected == YES) {
-            memcpy(code, "023781", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023782", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsContactorError == YES) {
-            memcpy(code, "023782", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023783", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsCertificateNotAllowedAtThisEVSE == YES) {
-            memcpy(code, "023783", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023784", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsGAChargeStop == YES) {
-            memcpy(code, "023784", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023785", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsAlignmentError == YES) {
-            memcpy(code, "023785", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023786", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsACDError == YES) {
-            memcpy(code, "023786", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023787", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsAssociationError == YES) {
-            memcpy(code, "023787", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023788", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsEVSEChargeAbort == YES) {
-            memcpy(code, "023788", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023789", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsNoSupportedAppProtocol == YES) {
-            memcpy(code, "023789", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023790", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsContractNotAccepted == YES) {
-            memcpy(code, "023790", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023791", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsMOUnknown == YES) {
-            memcpy(code, "023791", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023792", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsOEM_Prov_CertificateRevoke == YES) {
-            memcpy(code, "023792", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023793", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsOEM_SubCA1_CertificateRevoked == YES) {
-            memcpy(code, "023793", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023794", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsOEM_SubCA2_CertificateRevoked == YES) {
-            memcpy(code, "023794", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023795", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsOEM_RootCA_CertificateRevoked == YES) {
-            memcpy(code, "023795", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023796", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsMO_Prov_CertificateRevoked == YES) {
-            memcpy(code, "023796", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023797", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsMO_SubCA1_CertificateRevoked == YES) {
-            memcpy(code, "023797", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023798", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsMO_SubCA2_CertificateRevoked == YES) {
-            memcpy(code, "023798", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023799", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsMO_RootCA_CertificateRevoked == YES) {
-            memcpy(code, "023799", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023800", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsCPS_Prov_CertificateRevoked == YES) {
-            memcpy(code, "023800", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023801", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsCPS_SubCA1_CertificateRevoked == YES) {
-            memcpy(code, "023801", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023802", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsCPS_SubCA2_CertificateRevoked == YES) {
-            memcpy(code, "023802", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023803", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsCPS_RootCA_CertificateRevoked == YES) {
-            memcpy(code, "023803", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023809", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsTT_EVSE_SLAC_init == YES) {
-            memcpy(code, "023809", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023810", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsTP_match_response == YES) {
-            memcpy(code, "023810", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023811", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsTT_match_sequence == YES) {
-            memcpy(code, "023811", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023812", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsTT_EVSE_match_MNBC == YES) {
-            memcpy(code, "023812", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023813", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsTP_EVSE_avg_atten_calc == YES) {
-            memcpy(code, "023813", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023814", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsTT_match_response == YES) {
-            memcpy(code, "023814", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023815", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsTP_EVSE_match_session == YES) {
-            memcpy(code, "023815", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023816", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsTT_EVSE_assoc_session == YES) {
-            memcpy(code, "023816", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023817", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsTT_EVSE_vald_toggle == YES) {
-            memcpy(code, "023817", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023818", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsSeccSlacTimeoutCmMnbcSound == YES) {
-            memcpy(code, "023818", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023819", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsSeccSlacTimeoutCmValidateReq == YES) {
-            memcpy(code, "023819", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023823", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsUDP_TT_match_join == YES) {
-            memcpy(code, "023823", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023824", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsTCP_TT_match_join == YES) {
-            memcpy(code, "023824", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023825", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsTP_amp_map_exchange == YES) {
-            memcpy(code, "023825", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023826", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsTP_link_ready_notification == YES) {
-            memcpy(code, "023826", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023832", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsSupportedAppProtocolRes == YES) {
-            memcpy(code, "023832", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023833", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsSessionSetupRes == YES) {
-            memcpy(code, "023833", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023834", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsServiceDiscoveryRes == YES) {
-            memcpy(code, "023834", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023835", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsServicePaymentSelectionRes == YES) {
-            memcpy(code, "023835", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023836", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsContractAuthenticationRes == YES) {
-            memcpy(code, "023836", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023837", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsChargeParameterDiscoveryRes == YES) {
-            memcpy(code, "023837", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023838", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsPowerDeliveryRes == YES) {
-            memcpy(code, "023838", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023839", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsCableCheckRes == YES) {
-            memcpy(code, "023839", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023840", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsPreChargeRes == YES) {
-            memcpy(code, "023840", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023841", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsCurrentDemandRes == YES) {
-            memcpy(code, "023841", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023842", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsWeldingDetectionRes == YES) {
-            memcpy(code, "023842", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023843", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsSessionStopRes == YES) {
-            memcpy(code, "023843", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023844", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsSequence_Time == YES) {
-            memcpy(code, "023844", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023845", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsReadyToCharge_Performance_Time == YES) {
-            memcpy(code, "023845", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023846", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsCommunicationSetup_Performance_Time == YES) {
-            memcpy(code, "023846", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023847", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsCableCheck_Performance_Time == YES) {
-            memcpy(code, "023847", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023848", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsCPState_Detection_Time == YES) {
-            memcpy(code, "023848", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023849", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsCPOscillator_Retain_Time == YES) {
-            memcpy(code, "023849", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023850", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsSeccTimeoutV2GPreChargePerformaceTime == YES) {
-            memcpy(code, "023850", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023855", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsTP_GET_EV_TARGET_INFO == YES) {
-            memcpy(code, "023855", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023856", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsTT_GET_EV_TARGET_INFO == YES) {
-            memcpy(code, "023856", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023857", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsTP_GET_EV_BATTERY_INFO == YES) {
-            memcpy(code, "023857", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023858", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsTT_GET_EV_BATTERY_INFO == YES) {
-            memcpy(code, "023858", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023859", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsTP_EV_STOP_EVENT == YES) {
-            memcpy(code, "023859", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023860", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsTT_EV_STOP_EVENT == YES) {
-            memcpy(code, "023860", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023861", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsTP_EVSE_STOP_EVENT == YES) {
-            memcpy(code, "023861", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023862", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsTT_EVSE_STOP_EVENT == YES) {
-            memcpy(code, "023862", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023863", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsTP_GET_MISC_INFO == YES) {
-            memcpy(code, "023863", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023864", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsTT_GET_MISC_INFO == YES) {
-            memcpy(code, "023864", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023865", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsTP_DOWNLOAD_REQUEST == YES) {
-            memcpy(code, "023865", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023866", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsTT_DOWNLOAD_REQUEST == YES) {
-            memcpy(code, "023866", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023867", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsTP_START_BLOCK_TRANSFER == YES) {
-            memcpy(code, "023867", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023868", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsTT_START_BLOCK_TRANSFER == YES) {
-            memcpy(code, "023868", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023869", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsTP_DATA_TRANSFER == YES) {
-            memcpy(code, "023869", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023870", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsTT_DATA_TRANSFER == YES) {
-            memcpy(code, "023870", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023871", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsTP_DOWNLOAD_FINISH == YES) {
-            memcpy(code, "023871", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023872", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsTT_DOWNLOAD_FINISH == YES) {
-            memcpy(code, "023872", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023873", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsTP_ISOLATION_STATUS == YES) {
-            memcpy(code, "023873", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023874", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsTT_ISOLATION_STATUS == YES) {
-            memcpy(code, "023874", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023875", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsTP_CONNECTOR_INFO == YES) {
-            memcpy(code, "023875", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023876", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsTT_CONNECTOR_INFO == YES) {
-            memcpy(code, "023876", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023877", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsTT_RTC_INFO == YES) {
-            memcpy(code, "023877", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023878", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsTP_RTC_INFO == YES) {
-            memcpy(code, "023878", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023879", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsTP_EVSE_PRECHARGE_INFO == YES) {
-            memcpy(code, "023879", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023880", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsTT_EVSE_PRECHARGE_INFO == YES) {
-            memcpy(code, "023880", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023881", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsMSG_Sequence == YES) {
-            memcpy(code, "023881", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023882", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsCAN_MSG_Unrecognized_CMD_ID == YES) {
-            memcpy(code, "023882", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023883", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsDIN_Msg_Decode_Error == YES) {
-            memcpy(code, "023883", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023884", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsDIN_Msg_Encode_Error == YES) {
-            memcpy(code, "023884", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023885", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsISO1_Msg_Decode_Error == YES) {
-            memcpy(code, "023885", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023886", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsISO1_Msg_Encode_Error == YES) {
-            memcpy(code, "023886", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023887", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsISO2_Msg_Decode_Error == YES) {
-            memcpy(code, "023887", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023888", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsISO2_Msg_Encode_Error == YES) {
-            memcpy(code, "023888", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023889", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsCpStatus_Error == YES) {
-            memcpy(code, "023889", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023890", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsUnexpectVolBeforeCharing_Error == YES) {
-            memcpy(code, "023890", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023891", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.CcsSeccNotReadyForCharging == YES) {
-            memcpy(code, "023891", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        }
-//  else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023892", 6) == EQUAL &&
-//          pInfoCode->InfoEvents.bits.CcsSeccTimeoutQCA7000Comm == YES)
-//  {
-//      memcpy(code, "023892", 6);
-//      memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-//      isCleanCheck = true;
-//  }
-        else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023893", 6) == EQUAL &&
-                 pInfoCode->InfoEvents.bits.CcsSeccFailForQCA7000SetKey == YES) {
-            memcpy(code, "023893", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023979", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.EV_Full_Charging == YES) {
-            memcpy(code, "023979", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023983", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.Stop_by_EV_with_unknow_reason == YES) {
-            memcpy(code, "023983", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        }
-    }
-
-    if (isCleanCheck) {
-        for (uint8_t index = 0; index < pSysConfig->TotalConnectorCount; index++) {
-            pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);
-
-            if (index != gun_index || pSysConfig->TotalConnectorCount == 1) {
-                log_info("CCS clean error : index = %d, EvConnAlarmCode = %s, code = %s \n",
-                         index,
-                         pDcChargingInfo->EvConnAlarmCode,
-                         code);
-
-                if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, code, 6) != EQUAL) {
-                    if (strncmp(code, "012219", 6) == EQUAL) { pAlarmCode->AlarmEvents.bits.SystemCcsOutputOVP = NO; }
-
-                    if (strncmp(code, "023701", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsEvCommFail = NO; }
-                    if (strncmp(code, "023737", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsRESTemperatureInhibit = NO; }
-                    if (strncmp(code, "023738", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsEVShiftPosition = NO; }
-                    if (strncmp(code, "023739", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsChargerConnectorLockFault = NO; }
-                    if (strncmp(code, "023740", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsEVRESSMalfunction = NO; }
-                    if (strncmp(code, "023741", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsChargingCurrentdifferential = NO; }
-                    if (strncmp(code, "023742", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsChargingVoltageOutOfRange = NO; }
-                    if (strncmp(code, "023743", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsChargingSystemIncompatibility = NO; }
-                    if (strncmp(code, "023744", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsEmergencyEvent = NO; }
-                    if (strncmp(code, "023745", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsBreaker = NO; }
-                    if (strncmp(code, "023746", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsNoData = NO; }
-                    if (strncmp(code, "023747", 6) == EQUAL) { pInfoCode->InfoEvents.bits.Ccsreserved_by_DIN_A = NO; }
-                    if (strncmp(code, "023748", 6) == EQUAL) { pInfoCode->InfoEvents.bits.Ccsreserved_by_DIN_B = NO; }
-                    if (strncmp(code, "023749", 6) == EQUAL) { pInfoCode->InfoEvents.bits.Ccsreserved_by_DIN_C = NO; }
-                    if (strncmp(code, "023750", 6) == EQUAL) { pInfoCode->InfoEvents.bits.Ccsreserved_by_ISO_1 = NO; }
-                    if (strncmp(code, "023751", 6) == EQUAL) { pInfoCode->InfoEvents.bits.Ccsreserved_by_ISO_2 = NO; }
-                    if (strncmp(code, "023752", 6) == EQUAL) { pInfoCode->InfoEvents.bits.Ccsreserved_by_ISO_3 = NO; }
-                    if (strncmp(code, "023753", 6) == EQUAL) { pInfoCode->InfoEvents.bits.Ccsreserved_by_OEM_1 = NO; }
-                    if (strncmp(code, "023754", 6) == EQUAL) { pInfoCode->InfoEvents.bits.Ccsreserved_by_OEM_2 = NO; }
-                    if (strncmp(code, "023755", 6) == EQUAL) { pInfoCode->InfoEvents.bits.Ccsreserved_by_OEM_3 = NO; }
-                    if (strncmp(code, "023756", 6) == EQUAL) { pInfoCode->InfoEvents.bits.Ccsreserved_by_OEM_4 = NO; }
-                    if (strncmp(code, "023757", 6) == EQUAL) { pInfoCode->InfoEvents.bits.Ccsreserved_by_OEM_5 = NO; }
-                    if (strncmp(code, "023758", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsSequenceError = NO; }
-                    if (strncmp(code, "023759", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsSignatureError = NO; }
-                    if (strncmp(code, "023760", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsUnknownSession = NO; }
-                    if (strncmp(code, "023761", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsServiceIDInvalid = NO; }
-                    if (strncmp(code, "023762", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsPaymentSelectionInvalid = NO; }
-                    if (strncmp(code, "023763", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsIdentificationSelectionInvalid = NO; }
-                    if (strncmp(code, "023764", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsServiceSelectionInvalid = NO; }
-                    if (strncmp(code, "023765", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsCertificateExpired = NO; }
-                    if (strncmp(code, "023766", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsCertificateNotYetValid = NO; }
-                    if (strncmp(code, "023767", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsCertificateRevoked = NO; }
-                    if (strncmp(code, "023768", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsNoCertificateAvailable = NO; }
-                    if (strncmp(code, "023769", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsCertChainError = NO; }
-                    if (strncmp(code, "023770", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsCertValidationError = NO; }
-                    if (strncmp(code, "023771", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsCertVerificationError = NO; }
-                    if (strncmp(code, "023772", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsContractCanceled = NO; }
-                    if (strncmp(code, "023773", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsChallengeInvalid = NO; }
-                    if (strncmp(code, "023774", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsWrongEnergyTransferMode = NO; }
-                    if (strncmp(code, "023775", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsWrongChargeParameter = NO; }
-                    if (strncmp(code, "023776", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsChargingProfileInvalid = NO; }
-                    if (strncmp(code, "023777", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTariffSelectionInvalid = NO; }
-                    if (strncmp(code, "023778", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsEVSEPresentVoltageToLow = NO; }
-                    if (strncmp(code, "023779", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsPowerDeliveryNotApplied = NO; }
-                    if (strncmp(code, "023780", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsMeteringSignatureNotValid = NO; }
-                    if (strncmp(code, "023781", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsNoChargeServiceSelected = NO; }
-                    if (strncmp(code, "023782", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsContactorError = NO; }
-                    if (strncmp(code, "023783", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsCertificateNotAllowedAtThisEVSE = NO; }
-                    if (strncmp(code, "023784", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsGAChargeStop = NO; }
-                    if (strncmp(code, "023785", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsAlignmentError = NO; }
-                    if (strncmp(code, "023786", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsACDError = NO; }
-                    if (strncmp(code, "023787", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsAssociationError = NO; }
-                    if (strncmp(code, "023788", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsEVSEChargeAbort = NO; }
-                    if (strncmp(code, "023789", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsNoSupportedAppProtocol = NO; }
-                    if (strncmp(code, "023790", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsContractNotAccepted = NO; }
-                    if (strncmp(code, "023791", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsMOUnknown = NO; }
-                    if (strncmp(code, "023792", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsOEM_Prov_CertificateRevoke = NO; }
-                    if (strncmp(code, "023793", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsOEM_SubCA1_CertificateRevoked = NO; }
-                    if (strncmp(code, "023794", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsOEM_SubCA2_CertificateRevoked = NO; }
-                    if (strncmp(code, "023795", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsOEM_RootCA_CertificateRevoked = NO; }
-                    if (strncmp(code, "023796", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsMO_Prov_CertificateRevoked = NO; }
-                    if (strncmp(code, "023797", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsMO_SubCA1_CertificateRevoked = NO; }
-                    if (strncmp(code, "023798", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsMO_SubCA2_CertificateRevoked = NO; }
-                    if (strncmp(code, "023799", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsMO_RootCA_CertificateRevoked = NO; }
-                    if (strncmp(code, "023800", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsCPS_Prov_CertificateRevoked = NO; }
-                    if (strncmp(code, "023801", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsCPS_SubCA1_CertificateRevoked = NO; }
-                    if (strncmp(code, "023802", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsCPS_SubCA2_CertificateRevoked = NO; }
-                    if (strncmp(code, "023803", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsCPS_RootCA_CertificateRevoked = NO; }
-                    if (strncmp(code, "023809", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_EVSE_SLAC_init = NO; }
-                    if (strncmp(code, "023810", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_match_response = NO; }
-                    if (strncmp(code, "023811", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_match_sequence = NO; }
-                    if (strncmp(code, "023812", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_EVSE_match_MNBC = NO; }
-                    if (strncmp(code, "023813", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_EVSE_avg_atten_calc = NO; }
-                    if (strncmp(code, "023814", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_match_response = NO; }
-                    if (strncmp(code, "023815", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_EVSE_match_session = NO; }
-                    if (strncmp(code, "023816", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_EVSE_assoc_session = NO; }
-                    if (strncmp(code, "023817", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_EVSE_vald_toggle = NO; }
-                    if (strncmp(code, "023818", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsSeccSlacTimeoutCmMnbcSound = NO; }
-                    if (strncmp(code, "023819", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsSeccSlacTimeoutCmValidateReq = NO; }
-                    if (strncmp(code, "023823", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsUDP_TT_match_join = NO; }
-                    if (strncmp(code, "023824", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTCP_TT_match_join = NO; }
-                    if (strncmp(code, "023825", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_amp_map_exchange = NO; }
-                    if (strncmp(code, "023826", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_link_ready_notification = NO; }
-                    if (strncmp(code, "023832", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsSupportedAppProtocolRes = NO; }
-                    if (strncmp(code, "023833", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsSessionSetupRes = NO; }
-                    if (strncmp(code, "023834", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsServiceDiscoveryRes = NO; }
-                    if (strncmp(code, "023835", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsServicePaymentSelectionRes = NO; }
-                    if (strncmp(code, "023836", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsContractAuthenticationRes = NO; }
-                    if (strncmp(code, "023837", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsChargeParameterDiscoveryRes = NO; }
-                    if (strncmp(code, "023838", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsPowerDeliveryRes = NO; }
-                    if (strncmp(code, "023839", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsCableCheckRes = NO; }
-                    if (strncmp(code, "023840", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsPreChargeRes = NO; }
-                    if (strncmp(code, "023841", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsCurrentDemandRes = NO; }
-                    if (strncmp(code, "023842", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsWeldingDetectionRes = NO; }
-                    if (strncmp(code, "023843", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsSessionStopRes = NO; }
-                    if (strncmp(code, "023844", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsSequence_Time = NO; }
-                    if (strncmp(code, "023845", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsReadyToCharge_Performance_Time = NO; }
-                    if (strncmp(code, "023846", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsCommunicationSetup_Performance_Time = NO; }
-                    if (strncmp(code, "023847", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsCableCheck_Performance_Time = NO; }
-                    if (strncmp(code, "023848", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsCPState_Detection_Time = NO; }
-                    if (strncmp(code, "023849", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsCPOscillator_Retain_Time = NO; }
-                    if (strncmp(code, "023850", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsSeccTimeoutV2GPreChargePerformaceTime = NO; }
-                    if (strncmp(code, "023855", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_GET_EV_TARGET_INFO = NO; }
-                    if (strncmp(code, "023856", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_GET_EV_TARGET_INFO = NO; }
-                    if (strncmp(code, "023857", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_GET_EV_BATTERY_INFO = NO; }
-                    if (strncmp(code, "023858", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_GET_EV_BATTERY_INFO = NO; }
-                    if (strncmp(code, "023859", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_EV_STOP_EVENT = NO; }
-                    if (strncmp(code, "023860", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_EV_STOP_EVENT = NO; }
-                    if (strncmp(code, "023861", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_EVSE_STOP_EVENT = NO; }
-                    if (strncmp(code, "023862", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_EVSE_STOP_EVENT = NO; }
-                    if (strncmp(code, "023863", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_GET_MISC_INFO = NO; }
-                    if (strncmp(code, "023864", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_GET_MISC_INFO = NO; }
-                    if (strncmp(code, "023865", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_DOWNLOAD_REQUEST = NO; }
-                    if (strncmp(code, "023866", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_DOWNLOAD_REQUEST = NO; }
-                    if (strncmp(code, "023867", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_START_BLOCK_TRANSFER = NO; }
-                    if (strncmp(code, "023868", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_START_BLOCK_TRANSFER = NO; }
-                    if (strncmp(code, "023869", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_DATA_TRANSFER = NO; }
-                    if (strncmp(code, "023870", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_DATA_TRANSFER = NO; }
-                    if (strncmp(code, "023871", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_DOWNLOAD_FINISH = NO; }
-                    if (strncmp(code, "023872", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_DOWNLOAD_FINISH = NO; }
-                    if (strncmp(code, "023873", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_ISOLATION_STATUS = NO; }
-                    if (strncmp(code, "023874", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_ISOLATION_STATUS = NO; }
-                    if (strncmp(code, "023875", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_CONNECTOR_INFO = NO; }
-                    if (strncmp(code, "023876", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_CONNECTOR_INFO = NO; }
-                    if (strncmp(code, "023877", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_RTC_INFO = NO; }
-                    if (strncmp(code, "023878", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_RTC_INFO = NO; }
-                    if (strncmp(code, "023879", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_EVSE_PRECHARGE_INFO = NO; }
-                    if (strncmp(code, "023880", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_EVSE_PRECHARGE_INFO = NO; }
-                    if (strncmp(code, "023881", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsMSG_Sequence = NO; }
-                    if (strncmp(code, "023882", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsCAN_MSG_Unrecognized_CMD_ID = NO; }
-                    if (strncmp(code, "023883", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsDIN_Msg_Decode_Error = NO; }
-                    if (strncmp(code, "023884", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsDIN_Msg_Encode_Error = NO; }
-                    if (strncmp(code, "023885", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsISO1_Msg_Decode_Error = NO; }
-                    if (strncmp(code, "023886", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsISO1_Msg_Encode_Error = NO; }
-                    if (strncmp(code, "023887", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsISO2_Msg_Decode_Error = NO; }
-                    if (strncmp(code, "023888", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsISO2_Msg_Encode_Error = NO; }
-                    if (strncmp(code, "023889", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsCpStatus_Error = NO; }
-                    if (strncmp(code, "023890", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsUnexpectVolBeforeCharing_Error = NO; }
-                    if (strncmp(code, "023891", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsSeccNotReadyForCharging = NO; }
-                    //if (strncmp(code, "023892", 6) == EQUAL) pInfoCode->InfoEvents.bits.CcsSeccTimeoutQCA7000Comm = NO;
-                    if (strncmp(code, "023893", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsSeccFailForQCA7000SetKey = NO; }
-
-                    if (strncmp(code, "023979", 6) == EQUAL) { pInfoCode->InfoEvents.bits.EV_Full_Charging = NO; }
-                    if (strncmp(code, "023983", 6) == EQUAL) { pInfoCode->InfoEvents.bits.Stop_by_EV_with_unknow_reason = NO; }
-                }
-            }
-        }
-    }
-    pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(gun_index);
-    if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "", 6) != EQUAL) {
-        memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-    }
-}
+#include <stdio.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "../Config.h"
+#include "../Log/log.h"
+#include "../ShareMemory/shmMem.h"
+#include "../Define/define.h"
+
+//------------------------------------------------------------------------------
+void ClearAbnormalStatus_CCS(uint8_t gun_index)
+{
+    bool isCleanCheck = false;
+    char code[7];
+    struct SysConfigData *pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
+    struct InfoCodeData *pInfoCode = (struct InfoCodeData *)GetShmInfoCodeData();
+    struct AlarmCodeData *pAlarmCode = (struct AlarmCodeData *)GetShmAlarmCodeData();
+    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gun_index);
+    memset(code, '\n', sizeof(code));
+    
+    if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "", 6) == EQUAL) {
+        return;
+    }
+
+    if (true) {
+        if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "012219", 6) == EQUAL &&
+                pAlarmCode->AlarmEvents.bits.SystemCcsOutputOVP == YES) {
+            memcpy(code, "012219", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023701", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsEvCommFail == YES) {
+            memcpy(code, "023701", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023737", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsRESTemperatureInhibit == YES) {
+            memcpy(code, "023737", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023738", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsEVShiftPosition == YES) {
+            memcpy(code, "023738", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023739", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsChargerConnectorLockFault == YES) {
+            memcpy(code, "023739", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023740", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsEVRESSMalfunction == YES) {
+            memcpy(code, "023740", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023741", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsChargingCurrentdifferential == YES) {
+            memcpy(code, "023741", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023742", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsChargingVoltageOutOfRange == YES) {
+            memcpy(code, "023742", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023743", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsChargingSystemIncompatibility == YES) {
+            memcpy(code, "023743", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023744", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsEmergencyEvent == YES) {
+            memcpy(code, "023744", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023745", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsBreaker == YES) {
+            memcpy(code, "023745", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023746", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsNoData == YES) {
+            memcpy(code, "023746", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023747", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.Ccsreserved_by_DIN_A == YES) {
+            memcpy(code, "023747", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023748", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.Ccsreserved_by_DIN_B == YES) {
+            memcpy(code, "023748", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023749", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.Ccsreserved_by_DIN_C == YES) {
+            memcpy(code, "023749", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023750", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.Ccsreserved_by_ISO_1 == YES) {
+            memcpy(code, "023750", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023751", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.Ccsreserved_by_ISO_2 == YES) {
+            memcpy(code, "023751", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023752", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.Ccsreserved_by_ISO_3 == YES) {
+            memcpy(code, "023752", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023753", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.Ccsreserved_by_OEM_1 == YES) {
+            memcpy(code, "023753", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023754", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.Ccsreserved_by_OEM_2 == YES) {
+            memcpy(code, "023754", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023755", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.Ccsreserved_by_OEM_3 == YES) {
+            memcpy(code, "023755", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023756", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.Ccsreserved_by_OEM_4 == YES) {
+            memcpy(code, "023756", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023757", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.Ccsreserved_by_OEM_5 == YES) {
+            memcpy(code, "023757", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023758", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsSequenceError == YES) {
+            memcpy(code, "023758", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023759", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsSignatureError == YES) {
+            memcpy(code, "023759", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023760", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsUnknownSession == YES) {
+            memcpy(code, "023760", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023761", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsServiceIDInvalid == YES) {
+            memcpy(code, "023761", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023762", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsPaymentSelectionInvalid == YES) {
+            memcpy(code, "023762", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023763", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsIdentificationSelectionInvalid == YES) {
+            memcpy(code, "023763", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023764", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsServiceSelectionInvalid == YES) {
+            memcpy(code, "023764", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023765", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsCertificateExpired == YES) {
+            memcpy(code, "023765", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023766", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsCertificateNotYetValid == YES) {
+            memcpy(code, "023766", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023767", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsCertificateRevoked == YES) {
+            memcpy(code, "023767", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023768", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsNoCertificateAvailable == YES) {
+            memcpy(code, "023768", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023769", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsCertChainError == YES) {
+            memcpy(code, "023769", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023770", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsCertValidationError == YES) {
+            memcpy(code, "023770", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023771", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsCertVerificationError == YES) {
+            memcpy(code, "023771", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023772", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsContractCanceled == YES) {
+            memcpy(code, "023772", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023773", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsChallengeInvalid == YES) {
+            memcpy(code, "023773", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023774", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsWrongEnergyTransferMode == YES) {
+            memcpy(code, "023774", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023775", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsWrongChargeParameter == YES) {
+            memcpy(code, "023775", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023776", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsChargingProfileInvalid == YES) {
+            memcpy(code, "023776", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023777", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsTariffSelectionInvalid == YES) {
+            memcpy(code, "023777", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023778", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsEVSEPresentVoltageToLow == YES) {
+            memcpy(code, "023778", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023779", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsPowerDeliveryNotApplied == YES) {
+            memcpy(code, "023779", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023780", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsMeteringSignatureNotValid == YES) {
+            memcpy(code, "023780", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023781", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsNoChargeServiceSelected == YES) {
+            memcpy(code, "023781", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023782", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsContactorError == YES) {
+            memcpy(code, "023782", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023783", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsCertificateNotAllowedAtThisEVSE == YES) {
+            memcpy(code, "023783", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023784", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsGAChargeStop == YES) {
+            memcpy(code, "023784", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023785", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsAlignmentError == YES) {
+            memcpy(code, "023785", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023786", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsACDError == YES) {
+            memcpy(code, "023786", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023787", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsAssociationError == YES) {
+            memcpy(code, "023787", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023788", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsEVSEChargeAbort == YES) {
+            memcpy(code, "023788", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023789", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsNoSupportedAppProtocol == YES) {
+            memcpy(code, "023789", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023790", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsContractNotAccepted == YES) {
+            memcpy(code, "023790", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023791", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsMOUnknown == YES) {
+            memcpy(code, "023791", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023792", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsOEM_Prov_CertificateRevoke == YES) {
+            memcpy(code, "023792", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023793", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsOEM_SubCA1_CertificateRevoked == YES) {
+            memcpy(code, "023793", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023794", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsOEM_SubCA2_CertificateRevoked == YES) {
+            memcpy(code, "023794", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023795", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsOEM_RootCA_CertificateRevoked == YES) {
+            memcpy(code, "023795", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023796", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsMO_Prov_CertificateRevoked == YES) {
+            memcpy(code, "023796", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023797", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsMO_SubCA1_CertificateRevoked == YES) {
+            memcpy(code, "023797", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023798", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsMO_SubCA2_CertificateRevoked == YES) {
+            memcpy(code, "023798", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023799", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsMO_RootCA_CertificateRevoked == YES) {
+            memcpy(code, "023799", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023800", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsCPS_Prov_CertificateRevoked == YES) {
+            memcpy(code, "023800", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023801", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsCPS_SubCA1_CertificateRevoked == YES) {
+            memcpy(code, "023801", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023802", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsCPS_SubCA2_CertificateRevoked == YES) {
+            memcpy(code, "023802", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023803", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsCPS_RootCA_CertificateRevoked == YES) {
+            memcpy(code, "023803", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023809", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsTT_EVSE_SLAC_init == YES) {
+            memcpy(code, "023809", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023810", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsTP_match_response == YES) {
+            memcpy(code, "023810", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023811", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsTT_match_sequence == YES) {
+            memcpy(code, "023811", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023812", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsTT_EVSE_match_MNBC == YES) {
+            memcpy(code, "023812", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023813", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsTP_EVSE_avg_atten_calc == YES) {
+            memcpy(code, "023813", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023814", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsTT_match_response == YES) {
+            memcpy(code, "023814", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023815", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsTP_EVSE_match_session == YES) {
+            memcpy(code, "023815", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023816", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsTT_EVSE_assoc_session == YES) {
+            memcpy(code, "023816", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023817", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsTT_EVSE_vald_toggle == YES) {
+            memcpy(code, "023817", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023818", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsSeccSlacTimeoutCmMnbcSound == YES) {
+            memcpy(code, "023818", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023819", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsSeccSlacTimeoutCmValidateReq == YES) {
+            memcpy(code, "023819", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023823", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsUDP_TT_match_join == YES) {
+            memcpy(code, "023823", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023824", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsTCP_TT_match_join == YES) {
+            memcpy(code, "023824", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023825", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsTP_amp_map_exchange == YES) {
+            memcpy(code, "023825", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023826", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsTP_link_ready_notification == YES) {
+            memcpy(code, "023826", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023832", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsSupportedAppProtocolRes == YES) {
+            memcpy(code, "023832", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023833", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsSessionSetupRes == YES) {
+            memcpy(code, "023833", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023834", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsServiceDiscoveryRes == YES) {
+            memcpy(code, "023834", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023835", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsServicePaymentSelectionRes == YES) {
+            memcpy(code, "023835", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023836", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsContractAuthenticationRes == YES) {
+            memcpy(code, "023836", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023837", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsChargeParameterDiscoveryRes == YES) {
+            memcpy(code, "023837", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023838", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsPowerDeliveryRes == YES) {
+            memcpy(code, "023838", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023839", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsCableCheckRes == YES) {
+            memcpy(code, "023839", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023840", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsPreChargeRes == YES) {
+            memcpy(code, "023840", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023841", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsCurrentDemandRes == YES) {
+            memcpy(code, "023841", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023842", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsWeldingDetectionRes == YES) {
+            memcpy(code, "023842", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023843", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsSessionStopRes == YES) {
+            memcpy(code, "023843", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023844", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsSequence_Time == YES) {
+            memcpy(code, "023844", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023845", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsReadyToCharge_Performance_Time == YES) {
+            memcpy(code, "023845", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023846", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsCommunicationSetup_Performance_Time == YES) {
+            memcpy(code, "023846", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023847", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsCableCheck_Performance_Time == YES) {
+            memcpy(code, "023847", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023848", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsCPState_Detection_Time == YES) {
+            memcpy(code, "023848", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023849", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsCPOscillator_Retain_Time == YES) {
+            memcpy(code, "023849", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023850", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsSeccTimeoutV2GPreChargePerformaceTime == YES) {
+            memcpy(code, "023850", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023855", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsTP_GET_EV_TARGET_INFO == YES) {
+            memcpy(code, "023855", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023856", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsTT_GET_EV_TARGET_INFO == YES) {
+            memcpy(code, "023856", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023857", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsTP_GET_EV_BATTERY_INFO == YES) {
+            memcpy(code, "023857", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023858", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsTT_GET_EV_BATTERY_INFO == YES) {
+            memcpy(code, "023858", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023859", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsTP_EV_STOP_EVENT == YES) {
+            memcpy(code, "023859", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023860", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsTT_EV_STOP_EVENT == YES) {
+            memcpy(code, "023860", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023861", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsTP_EVSE_STOP_EVENT == YES) {
+            memcpy(code, "023861", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023862", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsTT_EVSE_STOP_EVENT == YES) {
+            memcpy(code, "023862", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023863", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsTP_GET_MISC_INFO == YES) {
+            memcpy(code, "023863", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023864", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsTT_GET_MISC_INFO == YES) {
+            memcpy(code, "023864", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023865", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsTP_DOWNLOAD_REQUEST == YES) {
+            memcpy(code, "023865", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023866", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsTT_DOWNLOAD_REQUEST == YES) {
+            memcpy(code, "023866", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023867", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsTP_START_BLOCK_TRANSFER == YES) {
+            memcpy(code, "023867", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023868", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsTT_START_BLOCK_TRANSFER == YES) {
+            memcpy(code, "023868", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023869", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsTP_DATA_TRANSFER == YES) {
+            memcpy(code, "023869", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023870", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsTT_DATA_TRANSFER == YES) {
+            memcpy(code, "023870", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023871", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsTP_DOWNLOAD_FINISH == YES) {
+            memcpy(code, "023871", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023872", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsTT_DOWNLOAD_FINISH == YES) {
+            memcpy(code, "023872", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023873", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsTP_ISOLATION_STATUS == YES) {
+            memcpy(code, "023873", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023874", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsTT_ISOLATION_STATUS == YES) {
+            memcpy(code, "023874", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023875", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsTP_CONNECTOR_INFO == YES) {
+            memcpy(code, "023875", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023876", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsTT_CONNECTOR_INFO == YES) {
+            memcpy(code, "023876", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023877", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsTT_RTC_INFO == YES) {
+            memcpy(code, "023877", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023878", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsTP_RTC_INFO == YES) {
+            memcpy(code, "023878", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023879", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsTP_EVSE_PRECHARGE_INFO == YES) {
+            memcpy(code, "023879", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023880", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsTT_EVSE_PRECHARGE_INFO == YES) {
+            memcpy(code, "023880", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023881", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsMSG_Sequence == YES) {
+            memcpy(code, "023881", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023882", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsCAN_MSG_Unrecognized_CMD_ID == YES) {
+            memcpy(code, "023882", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023883", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsDIN_Msg_Decode_Error == YES) {
+            memcpy(code, "023883", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023884", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsDIN_Msg_Encode_Error == YES) {
+            memcpy(code, "023884", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023885", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsISO1_Msg_Decode_Error == YES) {
+            memcpy(code, "023885", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023886", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsISO1_Msg_Encode_Error == YES) {
+            memcpy(code, "023886", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023887", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsISO2_Msg_Decode_Error == YES) {
+            memcpy(code, "023887", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023888", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsISO2_Msg_Encode_Error == YES) {
+            memcpy(code, "023888", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023889", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsCpStatus_Error == YES) {
+            memcpy(code, "023889", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023890", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsUnexpectVolBeforeCharing_Error == YES) {
+            memcpy(code, "023890", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023891", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.CcsSeccNotReadyForCharging == YES) {
+            memcpy(code, "023891", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        }
+//  else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023892", 6) == EQUAL &&
+//          pInfoCode->InfoEvents.bits.CcsSeccTimeoutQCA7000Comm == YES)
+//  {
+//      memcpy(code, "023892", 6);
+//      memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+//      isCleanCheck = true;
+//  }
+        else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023893", 6) == EQUAL &&
+                 pInfoCode->InfoEvents.bits.CcsSeccFailForQCA7000SetKey == YES) {
+            memcpy(code, "023893", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023979", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.EV_Full_Charging == YES) {
+            memcpy(code, "023979", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023983", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.Stop_by_EV_with_unknow_reason == YES) {
+            memcpy(code, "023983", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        }
+    }
+
+    if (isCleanCheck) {
+        for (uint8_t index = 0; index < pSysConfig->TotalConnectorCount; index++) {
+            pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);
+
+            if (index != gun_index || pSysConfig->TotalConnectorCount == 1) {
+                log_info("CCS clean error : index = %d, EvConnAlarmCode = %s, code = %s \n",
+                         index,
+                         pDcChargingInfo->EvConnAlarmCode,
+                         code);
+
+                if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, code, 6) != EQUAL) {
+                    if (strncmp(code, "012219", 6) == EQUAL) { pAlarmCode->AlarmEvents.bits.SystemCcsOutputOVP = NO; }
+
+                    if (strncmp(code, "023701", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsEvCommFail = NO; }
+                    if (strncmp(code, "023737", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsRESTemperatureInhibit = NO; }
+                    if (strncmp(code, "023738", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsEVShiftPosition = NO; }
+                    if (strncmp(code, "023739", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsChargerConnectorLockFault = NO; }
+                    if (strncmp(code, "023740", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsEVRESSMalfunction = NO; }
+                    if (strncmp(code, "023741", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsChargingCurrentdifferential = NO; }
+                    if (strncmp(code, "023742", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsChargingVoltageOutOfRange = NO; }
+                    if (strncmp(code, "023743", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsChargingSystemIncompatibility = NO; }
+                    if (strncmp(code, "023744", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsEmergencyEvent = NO; }
+                    if (strncmp(code, "023745", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsBreaker = NO; }
+                    if (strncmp(code, "023746", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsNoData = NO; }
+                    if (strncmp(code, "023747", 6) == EQUAL) { pInfoCode->InfoEvents.bits.Ccsreserved_by_DIN_A = NO; }
+                    if (strncmp(code, "023748", 6) == EQUAL) { pInfoCode->InfoEvents.bits.Ccsreserved_by_DIN_B = NO; }
+                    if (strncmp(code, "023749", 6) == EQUAL) { pInfoCode->InfoEvents.bits.Ccsreserved_by_DIN_C = NO; }
+                    if (strncmp(code, "023750", 6) == EQUAL) { pInfoCode->InfoEvents.bits.Ccsreserved_by_ISO_1 = NO; }
+                    if (strncmp(code, "023751", 6) == EQUAL) { pInfoCode->InfoEvents.bits.Ccsreserved_by_ISO_2 = NO; }
+                    if (strncmp(code, "023752", 6) == EQUAL) { pInfoCode->InfoEvents.bits.Ccsreserved_by_ISO_3 = NO; }
+                    if (strncmp(code, "023753", 6) == EQUAL) { pInfoCode->InfoEvents.bits.Ccsreserved_by_OEM_1 = NO; }
+                    if (strncmp(code, "023754", 6) == EQUAL) { pInfoCode->InfoEvents.bits.Ccsreserved_by_OEM_2 = NO; }
+                    if (strncmp(code, "023755", 6) == EQUAL) { pInfoCode->InfoEvents.bits.Ccsreserved_by_OEM_3 = NO; }
+                    if (strncmp(code, "023756", 6) == EQUAL) { pInfoCode->InfoEvents.bits.Ccsreserved_by_OEM_4 = NO; }
+                    if (strncmp(code, "023757", 6) == EQUAL) { pInfoCode->InfoEvents.bits.Ccsreserved_by_OEM_5 = NO; }
+                    if (strncmp(code, "023758", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsSequenceError = NO; }
+                    if (strncmp(code, "023759", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsSignatureError = NO; }
+                    if (strncmp(code, "023760", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsUnknownSession = NO; }
+                    if (strncmp(code, "023761", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsServiceIDInvalid = NO; }
+                    if (strncmp(code, "023762", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsPaymentSelectionInvalid = NO; }
+                    if (strncmp(code, "023763", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsIdentificationSelectionInvalid = NO; }
+                    if (strncmp(code, "023764", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsServiceSelectionInvalid = NO; }
+                    if (strncmp(code, "023765", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsCertificateExpired = NO; }
+                    if (strncmp(code, "023766", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsCertificateNotYetValid = NO; }
+                    if (strncmp(code, "023767", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsCertificateRevoked = NO; }
+                    if (strncmp(code, "023768", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsNoCertificateAvailable = NO; }
+                    if (strncmp(code, "023769", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsCertChainError = NO; }
+                    if (strncmp(code, "023770", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsCertValidationError = NO; }
+                    if (strncmp(code, "023771", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsCertVerificationError = NO; }
+                    if (strncmp(code, "023772", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsContractCanceled = NO; }
+                    if (strncmp(code, "023773", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsChallengeInvalid = NO; }
+                    if (strncmp(code, "023774", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsWrongEnergyTransferMode = NO; }
+                    if (strncmp(code, "023775", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsWrongChargeParameter = NO; }
+                    if (strncmp(code, "023776", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsChargingProfileInvalid = NO; }
+                    if (strncmp(code, "023777", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTariffSelectionInvalid = NO; }
+                    if (strncmp(code, "023778", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsEVSEPresentVoltageToLow = NO; }
+                    if (strncmp(code, "023779", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsPowerDeliveryNotApplied = NO; }
+                    if (strncmp(code, "023780", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsMeteringSignatureNotValid = NO; }
+                    if (strncmp(code, "023781", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsNoChargeServiceSelected = NO; }
+                    if (strncmp(code, "023782", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsContactorError = NO; }
+                    if (strncmp(code, "023783", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsCertificateNotAllowedAtThisEVSE = NO; }
+                    if (strncmp(code, "023784", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsGAChargeStop = NO; }
+                    if (strncmp(code, "023785", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsAlignmentError = NO; }
+                    if (strncmp(code, "023786", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsACDError = NO; }
+                    if (strncmp(code, "023787", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsAssociationError = NO; }
+                    if (strncmp(code, "023788", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsEVSEChargeAbort = NO; }
+                    if (strncmp(code, "023789", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsNoSupportedAppProtocol = NO; }
+                    if (strncmp(code, "023790", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsContractNotAccepted = NO; }
+                    if (strncmp(code, "023791", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsMOUnknown = NO; }
+                    if (strncmp(code, "023792", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsOEM_Prov_CertificateRevoke = NO; }
+                    if (strncmp(code, "023793", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsOEM_SubCA1_CertificateRevoked = NO; }
+                    if (strncmp(code, "023794", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsOEM_SubCA2_CertificateRevoked = NO; }
+                    if (strncmp(code, "023795", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsOEM_RootCA_CertificateRevoked = NO; }
+                    if (strncmp(code, "023796", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsMO_Prov_CertificateRevoked = NO; }
+                    if (strncmp(code, "023797", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsMO_SubCA1_CertificateRevoked = NO; }
+                    if (strncmp(code, "023798", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsMO_SubCA2_CertificateRevoked = NO; }
+                    if (strncmp(code, "023799", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsMO_RootCA_CertificateRevoked = NO; }
+                    if (strncmp(code, "023800", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsCPS_Prov_CertificateRevoked = NO; }
+                    if (strncmp(code, "023801", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsCPS_SubCA1_CertificateRevoked = NO; }
+                    if (strncmp(code, "023802", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsCPS_SubCA2_CertificateRevoked = NO; }
+                    if (strncmp(code, "023803", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsCPS_RootCA_CertificateRevoked = NO; }
+                    if (strncmp(code, "023809", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_EVSE_SLAC_init = NO; }
+                    if (strncmp(code, "023810", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_match_response = NO; }
+                    if (strncmp(code, "023811", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_match_sequence = NO; }
+                    if (strncmp(code, "023812", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_EVSE_match_MNBC = NO; }
+                    if (strncmp(code, "023813", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_EVSE_avg_atten_calc = NO; }
+                    if (strncmp(code, "023814", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_match_response = NO; }
+                    if (strncmp(code, "023815", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_EVSE_match_session = NO; }
+                    if (strncmp(code, "023816", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_EVSE_assoc_session = NO; }
+                    if (strncmp(code, "023817", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_EVSE_vald_toggle = NO; }
+                    if (strncmp(code, "023818", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsSeccSlacTimeoutCmMnbcSound = NO; }
+                    if (strncmp(code, "023819", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsSeccSlacTimeoutCmValidateReq = NO; }
+                    if (strncmp(code, "023823", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsUDP_TT_match_join = NO; }
+                    if (strncmp(code, "023824", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTCP_TT_match_join = NO; }
+                    if (strncmp(code, "023825", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_amp_map_exchange = NO; }
+                    if (strncmp(code, "023826", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_link_ready_notification = NO; }
+                    if (strncmp(code, "023832", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsSupportedAppProtocolRes = NO; }
+                    if (strncmp(code, "023833", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsSessionSetupRes = NO; }
+                    if (strncmp(code, "023834", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsServiceDiscoveryRes = NO; }
+                    if (strncmp(code, "023835", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsServicePaymentSelectionRes = NO; }
+                    if (strncmp(code, "023836", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsContractAuthenticationRes = NO; }
+                    if (strncmp(code, "023837", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsChargeParameterDiscoveryRes = NO; }
+                    if (strncmp(code, "023838", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsPowerDeliveryRes = NO; }
+                    if (strncmp(code, "023839", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsCableCheckRes = NO; }
+                    if (strncmp(code, "023840", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsPreChargeRes = NO; }
+                    if (strncmp(code, "023841", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsCurrentDemandRes = NO; }
+                    if (strncmp(code, "023842", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsWeldingDetectionRes = NO; }
+                    if (strncmp(code, "023843", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsSessionStopRes = NO; }
+                    if (strncmp(code, "023844", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsSequence_Time = NO; }
+                    if (strncmp(code, "023845", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsReadyToCharge_Performance_Time = NO; }
+                    if (strncmp(code, "023846", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsCommunicationSetup_Performance_Time = NO; }
+                    if (strncmp(code, "023847", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsCableCheck_Performance_Time = NO; }
+                    if (strncmp(code, "023848", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsCPState_Detection_Time = NO; }
+                    if (strncmp(code, "023849", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsCPOscillator_Retain_Time = NO; }
+                    if (strncmp(code, "023850", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsSeccTimeoutV2GPreChargePerformaceTime = NO; }
+                    if (strncmp(code, "023855", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_GET_EV_TARGET_INFO = NO; }
+                    if (strncmp(code, "023856", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_GET_EV_TARGET_INFO = NO; }
+                    if (strncmp(code, "023857", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_GET_EV_BATTERY_INFO = NO; }
+                    if (strncmp(code, "023858", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_GET_EV_BATTERY_INFO = NO; }
+                    if (strncmp(code, "023859", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_EV_STOP_EVENT = NO; }
+                    if (strncmp(code, "023860", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_EV_STOP_EVENT = NO; }
+                    if (strncmp(code, "023861", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_EVSE_STOP_EVENT = NO; }
+                    if (strncmp(code, "023862", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_EVSE_STOP_EVENT = NO; }
+                    if (strncmp(code, "023863", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_GET_MISC_INFO = NO; }
+                    if (strncmp(code, "023864", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_GET_MISC_INFO = NO; }
+                    if (strncmp(code, "023865", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_DOWNLOAD_REQUEST = NO; }
+                    if (strncmp(code, "023866", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_DOWNLOAD_REQUEST = NO; }
+                    if (strncmp(code, "023867", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_START_BLOCK_TRANSFER = NO; }
+                    if (strncmp(code, "023868", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_START_BLOCK_TRANSFER = NO; }
+                    if (strncmp(code, "023869", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_DATA_TRANSFER = NO; }
+                    if (strncmp(code, "023870", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_DATA_TRANSFER = NO; }
+                    if (strncmp(code, "023871", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_DOWNLOAD_FINISH = NO; }
+                    if (strncmp(code, "023872", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_DOWNLOAD_FINISH = NO; }
+                    if (strncmp(code, "023873", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_ISOLATION_STATUS = NO; }
+                    if (strncmp(code, "023874", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_ISOLATION_STATUS = NO; }
+                    if (strncmp(code, "023875", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_CONNECTOR_INFO = NO; }
+                    if (strncmp(code, "023876", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_CONNECTOR_INFO = NO; }
+                    if (strncmp(code, "023877", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_RTC_INFO = NO; }
+                    if (strncmp(code, "023878", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_RTC_INFO = NO; }
+                    if (strncmp(code, "023879", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_EVSE_PRECHARGE_INFO = NO; }
+                    if (strncmp(code, "023880", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_EVSE_PRECHARGE_INFO = NO; }
+                    if (strncmp(code, "023881", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsMSG_Sequence = NO; }
+                    if (strncmp(code, "023882", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsCAN_MSG_Unrecognized_CMD_ID = NO; }
+                    if (strncmp(code, "023883", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsDIN_Msg_Decode_Error = NO; }
+                    if (strncmp(code, "023884", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsDIN_Msg_Encode_Error = NO; }
+                    if (strncmp(code, "023885", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsISO1_Msg_Decode_Error = NO; }
+                    if (strncmp(code, "023886", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsISO1_Msg_Encode_Error = NO; }
+                    if (strncmp(code, "023887", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsISO2_Msg_Decode_Error = NO; }
+                    if (strncmp(code, "023888", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsISO2_Msg_Encode_Error = NO; }
+                    if (strncmp(code, "023889", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsCpStatus_Error = NO; }
+                    if (strncmp(code, "023890", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsUnexpectVolBeforeCharing_Error = NO; }
+                    if (strncmp(code, "023891", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsSeccNotReadyForCharging = NO; }
+                    //if (strncmp(code, "023892", 6) == EQUAL) pInfoCode->InfoEvents.bits.CcsSeccTimeoutQCA7000Comm = NO;
+                    if (strncmp(code, "023893", 6) == EQUAL) { pInfoCode->InfoEvents.bits.CcsSeccFailForQCA7000SetKey = NO; }
+
+                    if (strncmp(code, "023979", 6) == EQUAL) { pInfoCode->InfoEvents.bits.EV_Full_Charging = NO; }
+                    if (strncmp(code, "023983", 6) == EQUAL) { pInfoCode->InfoEvents.bits.Stop_by_EV_with_unknow_reason = NO; }
+                }
+            }
+        }
+    }
+    pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(gun_index);
+    if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "", 6) != EQUAL) {
+        memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+    }
+}

+ 251 - 251
EVSE/Projects/DD360Tcci/Apps/ModuleEvComm/AbnormalCHA.c

@@ -1,251 +1,251 @@
-#include <stdio.h>
-#include <stdint.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include "../Config.h"
-#include "../Log/log.h"
-#include "../ShareMemory/shmMem.h"
-#include "../Define/define.h"
-
-//------------------------------------------------------------------------------
-void ClearAbnormalStatus_Chademo(uint8_t gun_index)
-{
-    bool isCleanCheck = false;
-    char code[7];
-    struct SysConfigData *pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
-    struct InfoCodeData *pInfoCode = (struct InfoCodeData *)GetShmInfoCodeData();
-    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gun_index);
-
-    if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "", 6) == EQUAL) {
-        return;
-    }
-
-    if (true) {
-        if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023700", 6) == EQUAL &&
-                pInfoCode->InfoEvents.bits.ChademoEvCommFail == YES) {
-            memcpy(code, "023700", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023704", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ChademoBatteryMalfun == YES) {
-            memcpy(code, "023704", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023705", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ChademoNoPermission == YES) {
-            memcpy(code, "023705", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023706", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ChademoBatteryIncompatibility == YES) {
-            memcpy(code, "023706", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023707", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ChademoBatteryOVP == YES) {
-            memcpy(code, "023707", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023708", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ChademoBatteryUVP == YES) {
-            memcpy(code, "023708", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023709", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ChademoBatteryOTP == YES) {
-            memcpy(code, "023709", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023710", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ChademoBatteryCurrentDiff == YES) {
-            memcpy(code, "023710", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023711", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ChademoBatteryVoltageDiff == YES) {
-            memcpy(code, "023711", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023712", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ChademoShiftPosition == YES) {
-            memcpy(code, "023712", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023713", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ChademoBatteryOtherFault == YES) {
-            memcpy(code, "023713", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023714", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ChademoChargingSystemError == YES) {
-            memcpy(code, "023714", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023715", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ChademoEvNormalStop == YES) {
-            memcpy(code, "023715", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023716", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ChademoTempSensorBroken == YES) {
-            memcpy(code, "023716", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023717", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ChademoConnectorLockFail == YES) {
-            memcpy(code, "023717", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023718", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ChademoD1OnNoReceive == YES) {
-            memcpy(code, "023718", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023719", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ChademoBmsKtoJTimeout == YES) {
-            memcpy(code, "023719", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023720", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ChademoBmsChargeAllowTimeout == YES) {
-            memcpy(code, "023720", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023721", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ChademoWaitGfdTimeout == YES) {
-            memcpy(code, "023721", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023722", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ChademoBmsEvRelayTimeout == YES) {
-            memcpy(code, "023722", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023723", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ChademoBmsReqCurrentTimeout == YES) {
-            memcpy(code, "023723", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023724", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ChademoBmsKtoJOffTimeout == YES) {
-            memcpy(code, "023724", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023725", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ChademoBmsEvRelayOffTimeout == YES) {
-            memcpy(code, "023725", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023726", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ChademoAdcMoreThan10V == YES) {
-            memcpy(code, "023726", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023727", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ChademoAdcMoreThan20V == YES) {
-            memcpy(code, "023727", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023728", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ChademoBmsChargeBeforeStop == YES) {
-            memcpy(code, "023728", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023729", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ChademoChargerGetNormalStop == YES) {
-            memcpy(code, "023729", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023730", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ChademoChargerGetEmergencyStop == YES) {
-            memcpy(code, "023730", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023731", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ChademoIsolationResultFail == YES) {
-            memcpy(code, "023731", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023732", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ChademoMissLinkWithMotherBoard == YES) {
-            memcpy(code, "023732", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023733", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ChademoOutputVolMoreThanLimit == YES) {
-            memcpy(code, "023733", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023734", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ChademoReqCurrentMoreThanLimit == YES) {
-            memcpy(code, "023734", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023735", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ChademoReCapBmsEqrCurrentExceed == YES) {
-            memcpy(code, "023735", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023736", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ChademoChargeRemainCountDown == YES) {
-            memcpy(code, "023736", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        }
-    }
-
-    if (isCleanCheck) {
-        for (uint8_t index = 0; index < pSysConfig->TotalConnectorCount; index++) {
-            pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);
-
-            if (index != gun_index || pSysConfig->TotalConnectorCount == 1) {
-                log_info("CHA clean error : index = %d, EvConnAlarmCode = %s, code = %s \n",
-                         index,
-                         pDcChargingInfo->EvConnAlarmCode,
-                         code);
-
-                if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, code, 6) != EQUAL) {
-                    if (strncmp(code, "023700", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoEvCommFail = NO; }
-                    if (strncmp(code, "023704", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBatteryMalfun = NO; }
-                    if (strncmp(code, "023705", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoNoPermission = NO; }
-                    if (strncmp(code, "023706", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBatteryIncompatibility = NO; }
-                    if (strncmp(code, "023707", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBatteryOVP = NO; }
-                    if (strncmp(code, "023708", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBatteryUVP = NO; }
-                    if (strncmp(code, "023709", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBatteryOTP = NO; }
-                    if (strncmp(code, "023710", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBatteryCurrentDiff = NO; }
-                    if (strncmp(code, "023711", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBatteryVoltageDiff = NO; }
-                    if (strncmp(code, "023712", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoShiftPosition = NO; }
-                    if (strncmp(code, "023713", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBatteryOtherFault = NO; }
-                    if (strncmp(code, "023714", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoChargingSystemError = NO; }
-                    if (strncmp(code, "023715", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoEvNormalStop = NO; }
-                    if (strncmp(code, "023716", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoTempSensorBroken = NO; }
-                    if (strncmp(code, "023717", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoConnectorLockFail = NO; }
-                    if (strncmp(code, "023718", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoD1OnNoReceive = NO; }
-                    if (strncmp(code, "023719", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBmsKtoJTimeout = NO; }
-                    if (strncmp(code, "023720", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBmsChargeAllowTimeout = NO; }
-                    if (strncmp(code, "023721", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoWaitGfdTimeout = NO; }
-                    if (strncmp(code, "023722", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBmsEvRelayTimeout = NO; }
-                    if (strncmp(code, "023723", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBmsReqCurrentTimeout = NO; }
-                    if (strncmp(code, "023724", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBmsKtoJOffTimeout = NO; }
-                    if (strncmp(code, "023725", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBmsEvRelayOffTimeout = NO; }
-                    if (strncmp(code, "023726", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoAdcMoreThan10V = NO; }
-                    if (strncmp(code, "023727", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoAdcMoreThan20V = NO; }
-                    if (strncmp(code, "023728", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBmsChargeBeforeStop = NO; }
-                    if (strncmp(code, "023729", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoChargerGetNormalStop = NO; }
-                    if (strncmp(code, "023730", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoChargerGetEmergencyStop = NO; }
-                    if (strncmp(code, "023731", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoIsolationResultFail = NO; }
-                    if (strncmp(code, "023732", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoMissLinkWithMotherBoard = NO; }
-                    if (strncmp(code, "023733", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoOutputVolMoreThanLimit = NO; }
-                    if (strncmp(code, "023734", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoReqCurrentMoreThanLimit = NO; }
-                    if (strncmp(code, "023735", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoReCapBmsEqrCurrentExceed = NO; }
-                    if (strncmp(code, "023736", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoChargeRemainCountDown = NO; }
-                }
-            }
-        }
-    }
-    pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(gun_index);
-    if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "", 6) != EQUAL) {
-        memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-    }
-}
+#include <stdio.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "../Config.h"
+#include "../Log/log.h"
+#include "../ShareMemory/shmMem.h"
+#include "../Define/define.h"
+
+//------------------------------------------------------------------------------
+void ClearAbnormalStatus_Chademo(uint8_t gun_index)
+{
+    bool isCleanCheck = false;
+    char code[7];
+    struct SysConfigData *pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
+    struct InfoCodeData *pInfoCode = (struct InfoCodeData *)GetShmInfoCodeData();
+    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gun_index);
+
+    if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "", 6) == EQUAL) {
+        return;
+    }
+
+    if (true) {
+        if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023700", 6) == EQUAL &&
+                pInfoCode->InfoEvents.bits.ChademoEvCommFail == YES) {
+            memcpy(code, "023700", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023704", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ChademoBatteryMalfun == YES) {
+            memcpy(code, "023704", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023705", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ChademoNoPermission == YES) {
+            memcpy(code, "023705", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023706", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ChademoBatteryIncompatibility == YES) {
+            memcpy(code, "023706", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023707", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ChademoBatteryOVP == YES) {
+            memcpy(code, "023707", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023708", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ChademoBatteryUVP == YES) {
+            memcpy(code, "023708", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023709", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ChademoBatteryOTP == YES) {
+            memcpy(code, "023709", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023710", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ChademoBatteryCurrentDiff == YES) {
+            memcpy(code, "023710", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023711", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ChademoBatteryVoltageDiff == YES) {
+            memcpy(code, "023711", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023712", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ChademoShiftPosition == YES) {
+            memcpy(code, "023712", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023713", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ChademoBatteryOtherFault == YES) {
+            memcpy(code, "023713", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023714", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ChademoChargingSystemError == YES) {
+            memcpy(code, "023714", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023715", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ChademoEvNormalStop == YES) {
+            memcpy(code, "023715", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023716", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ChademoTempSensorBroken == YES) {
+            memcpy(code, "023716", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023717", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ChademoConnectorLockFail == YES) {
+            memcpy(code, "023717", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023718", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ChademoD1OnNoReceive == YES) {
+            memcpy(code, "023718", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023719", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ChademoBmsKtoJTimeout == YES) {
+            memcpy(code, "023719", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023720", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ChademoBmsChargeAllowTimeout == YES) {
+            memcpy(code, "023720", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023721", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ChademoWaitGfdTimeout == YES) {
+            memcpy(code, "023721", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023722", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ChademoBmsEvRelayTimeout == YES) {
+            memcpy(code, "023722", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023723", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ChademoBmsReqCurrentTimeout == YES) {
+            memcpy(code, "023723", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023724", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ChademoBmsKtoJOffTimeout == YES) {
+            memcpy(code, "023724", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023725", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ChademoBmsEvRelayOffTimeout == YES) {
+            memcpy(code, "023725", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023726", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ChademoAdcMoreThan10V == YES) {
+            memcpy(code, "023726", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023727", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ChademoAdcMoreThan20V == YES) {
+            memcpy(code, "023727", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023728", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ChademoBmsChargeBeforeStop == YES) {
+            memcpy(code, "023728", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023729", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ChademoChargerGetNormalStop == YES) {
+            memcpy(code, "023729", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023730", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ChademoChargerGetEmergencyStop == YES) {
+            memcpy(code, "023730", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023731", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ChademoIsolationResultFail == YES) {
+            memcpy(code, "023731", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023732", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ChademoMissLinkWithMotherBoard == YES) {
+            memcpy(code, "023732", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023733", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ChademoOutputVolMoreThanLimit == YES) {
+            memcpy(code, "023733", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023734", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ChademoReqCurrentMoreThanLimit == YES) {
+            memcpy(code, "023734", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023735", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ChademoReCapBmsEqrCurrentExceed == YES) {
+            memcpy(code, "023735", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023736", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ChademoChargeRemainCountDown == YES) {
+            memcpy(code, "023736", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        }
+    }
+
+    if (isCleanCheck) {
+        for (uint8_t index = 0; index < pSysConfig->TotalConnectorCount; index++) {
+            pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);
+
+            if (index != gun_index || pSysConfig->TotalConnectorCount == 1) {
+                log_info("CHA clean error : index = %d, EvConnAlarmCode = %s, code = %s \n",
+                         index,
+                         pDcChargingInfo->EvConnAlarmCode,
+                         code);
+
+                if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, code, 6) != EQUAL) {
+                    if (strncmp(code, "023700", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoEvCommFail = NO; }
+                    if (strncmp(code, "023704", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBatteryMalfun = NO; }
+                    if (strncmp(code, "023705", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoNoPermission = NO; }
+                    if (strncmp(code, "023706", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBatteryIncompatibility = NO; }
+                    if (strncmp(code, "023707", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBatteryOVP = NO; }
+                    if (strncmp(code, "023708", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBatteryUVP = NO; }
+                    if (strncmp(code, "023709", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBatteryOTP = NO; }
+                    if (strncmp(code, "023710", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBatteryCurrentDiff = NO; }
+                    if (strncmp(code, "023711", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBatteryVoltageDiff = NO; }
+                    if (strncmp(code, "023712", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoShiftPosition = NO; }
+                    if (strncmp(code, "023713", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBatteryOtherFault = NO; }
+                    if (strncmp(code, "023714", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoChargingSystemError = NO; }
+                    if (strncmp(code, "023715", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoEvNormalStop = NO; }
+                    if (strncmp(code, "023716", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoTempSensorBroken = NO; }
+                    if (strncmp(code, "023717", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoConnectorLockFail = NO; }
+                    if (strncmp(code, "023718", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoD1OnNoReceive = NO; }
+                    if (strncmp(code, "023719", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBmsKtoJTimeout = NO; }
+                    if (strncmp(code, "023720", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBmsChargeAllowTimeout = NO; }
+                    if (strncmp(code, "023721", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoWaitGfdTimeout = NO; }
+                    if (strncmp(code, "023722", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBmsEvRelayTimeout = NO; }
+                    if (strncmp(code, "023723", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBmsReqCurrentTimeout = NO; }
+                    if (strncmp(code, "023724", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBmsKtoJOffTimeout = NO; }
+                    if (strncmp(code, "023725", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBmsEvRelayOffTimeout = NO; }
+                    if (strncmp(code, "023726", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoAdcMoreThan10V = NO; }
+                    if (strncmp(code, "023727", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoAdcMoreThan20V = NO; }
+                    if (strncmp(code, "023728", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBmsChargeBeforeStop = NO; }
+                    if (strncmp(code, "023729", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoChargerGetNormalStop = NO; }
+                    if (strncmp(code, "023730", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoChargerGetEmergencyStop = NO; }
+                    if (strncmp(code, "023731", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoIsolationResultFail = NO; }
+                    if (strncmp(code, "023732", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoMissLinkWithMotherBoard = NO; }
+                    if (strncmp(code, "023733", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoOutputVolMoreThanLimit = NO; }
+                    if (strncmp(code, "023734", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoReqCurrentMoreThanLimit = NO; }
+                    if (strncmp(code, "023735", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoReCapBmsEqrCurrentExceed = NO; }
+                    if (strncmp(code, "023736", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ChademoChargeRemainCountDown = NO; }
+                }
+            }
+        }
+    }
+    pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(gun_index);
+    if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "", 6) != EQUAL) {
+        memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+    }
+}

+ 420 - 420
EVSE/Projects/DD360Tcci/Apps/ModuleEvComm/AbnormalGBT.c

@@ -1,420 +1,420 @@
-#include <stdio.h>
-#include <stdint.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include "../Config.h"
-#include "../Log/log.h"
-#include "../ShareMemory/shmMem.h"
-#include "../Define/define.h"
-
-//------------------------------------------------------------------------------
-void ClearAbnormalStatus_GB(uint8_t gun_index)
-{
-    bool isCleanCheck = false;
-    char code[7];
-    struct SysConfigData *pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
-    struct InfoCodeData *pInfoCode = (struct InfoCodeData *)GetShmInfoCodeData();
-    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gun_index);
-
-    if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "", 6) == EQUAL) {
-        return;
-    }
-
-    if (true) {
-        if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023702", 6) == EQUAL &&
-                pInfoCode->InfoEvents.bits.GbEvCommFail == YES) {
-            memcpy(code, "023702", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023900", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_LOS_CC1 == YES) {
-            memcpy(code, "023900", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023901", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_CONNECTOR_LOCK_FAIL == YES) {
-            memcpy(code, "023901", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023902", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_BATTERY_INCOMPATIBLE == YES) {
-            memcpy(code, "023902", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023903", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_BMS_BROAA_TIMEOUT == YES) {
-            memcpy(code, "023903", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023904", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_CSU_PRECHARGE_TIMEOUT == YES) {
-            memcpy(code, "023904", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023905", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_BMS_PRESENT_VOLTAGE_FAULT == YES) {
-            memcpy(code, "023905", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023906", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_BMS_VOLTAGE_OVER_RANGE == YES) {
-            memcpy(code, "023906", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023907", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_BSM_CHARGE_ALLOW_00_10MIN_COUUNTDONE == YES) {
-            memcpy(code, "023907", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023908", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_WAIT_GROUNDFAULT_TIMEOUT == YES) {
-            memcpy(code, "023908", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023909", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_ADC_MORE_THAN_10V == YES) {
-            memcpy(code, "023909", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023910", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_ADC_MORE_THAN_60V == YES) {
-            memcpy(code, "023910", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023911", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_CHARGER_GET_NORMAL_STOP_CMD == YES) {
-            memcpy(code, "023911", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023912", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_CHARGER_GET_EMERGENCY_STOP_CMD == YES) {
-            memcpy(code, "023912", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023913", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_ISOLATION_RESULT_FAIL == YES) {
-            memcpy(code, "023913", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023914", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_MOTHER_BOARD_MISS_LINK == YES) {
-            memcpy(code, "023914", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023915", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_OUTPUT_VOLTAGE_MORE_THAN_LIMIT == YES) {
-            memcpy(code, "023915", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023916", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_REQ_CURRENT_MORE_THAN_LIMIT == YES) {
-            memcpy(code, "023916", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023917", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_OUTPUT_VOLTAGE_MORE_THAN_10_PERCENT == YES) {
-            memcpy(code, "023917", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023918", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_OUTPUT_VOLTAGE_DIFF_BCS_5_PERCENT == YES) {
-            memcpy(code, "023918", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023919", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_STOP_ADC_MORE_THAN_10V == YES) {
-            memcpy(code, "023919", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023930", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BHM_TIMEOUT == YES) {
-            memcpy(code, "023930", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023931", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BRM_TIMEOUT == YES) {
-            memcpy(code, "023931", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023932", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BCP_TIMEOUT == YES) {
-            memcpy(code, "023932", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023933", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BRO_TIMEOUT == YES) {
-            memcpy(code, "023933", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023934", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BCL_TIMEOUT == YES) {
-            memcpy(code, "023934", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023935", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BCS_TIMEOUT == YES) {
-            memcpy(code, "023935", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023936", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BSM_TIMEOUT == YES) {
-            memcpy(code, "023936", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023937", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BST_TIMEOUT == YES) {
-            memcpy(code, "023937", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023938", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BSD_TIMEOUT == YES) {
-            memcpy(code, "023938", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023939", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BEM_OTHER_TIMEOUT == YES) {
-            memcpy(code, "023939", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023940", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_BEM_CRM_TIMEOUT == YES) {
-            memcpy(code, "023940", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023941", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_BEM_CRMAA_TIMEOUT == YES) {
-            memcpy(code, "023941", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023942", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_BEM_CTS_CML_TIMEOUT == YES) {
-            memcpy(code, "023942", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023943", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_BEM_CRO_TIMEOUT == YES) {
-            memcpy(code, "023943", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023944", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_BEM_CCS_TIMEOUT == YES) {
-            memcpy(code, "023944", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023945", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_BEM_CST_TIMEOUT == YES) {
-            memcpy(code, "023945", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023946", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_BEM_CSD_TIMEOUT == YES) {
-            memcpy(code, "023946", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023947", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_BEM_BEM_OTHER_TIMEOUT == YES) {
-            memcpy(code, "023947", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023950", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_BST_SOC_GOAL == YES) {
-            memcpy(code, "023950", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023951", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_BST_TOTAL_VOLTAGE_GOAL == YES) {
-            memcpy(code, "023951", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023952", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_BST_CELL_VOLTAGE_GOAL == YES) {
-            memcpy(code, "023952", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023953", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_BST_GET_CST == YES) {
-            memcpy(code, "023953", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023954", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_BST_ISOLATION == YES) {
-            memcpy(code, "023954", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023955", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_BST_OUTPUT_CONNECTOR_OTP == YES) {
-            memcpy(code, "023955", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023956", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_BST_COMPONENT == YES) {
-            memcpy(code, "023956", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023957", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_BST_CHARGE_CONNECTOR == YES) {
-            memcpy(code, "023957", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023958", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_BST_OTP == YES) {
-            memcpy(code, "023958", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023959", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_BST_OTHER == YES) {
-            memcpy(code, "023959", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023960", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_BST_HIGH_V == YES) {
-            memcpy(code, "023960", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023961", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_BST_CC2 == YES) {
-            memcpy(code, "023961", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023962", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_BST_CURRENT == YES) {
-            memcpy(code, "023962", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023963", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_BST_VOLTAGE == YES) {
-            memcpy(code, "023963", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023964", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_GET_BST_NO_REASON == YES) {
-            memcpy(code, "023964", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023970", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_BSM_CELL_OVER_VOLTAGE == YES) {
-            memcpy(code, "023970", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023971", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_BSM_CELL_UNDER_VOLTAGE == YES) {
-            memcpy(code, "023971", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023972", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_BSM_OVER_SOC == YES) {
-            memcpy(code, "023972", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023973", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_BSM_UNDER_SOC == YES) {
-            memcpy(code, "023973", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023974", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_BSM_CURRENT == YES) {
-            memcpy(code, "023974", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023975", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_BSM_TEMPERATURE == YES) {
-            memcpy(code, "023975", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023976", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_BSM_ISOLATE == YES) {
-            memcpy(code, "023976", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023977", 6) == EQUAL &&
-                   pInfoCode->InfoEvents.bits.ERROR_CODE_BSM_OUTPUT_CONNECTOR == YES) {
-            memcpy(code, "023977", 6);
-            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-            isCleanCheck = true;
-        }
-    }
-
-    if (isCleanCheck) {
-        for (uint8_t index = 0; index < pSysConfig->TotalConnectorCount; index++) {
-            pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);
-
-            if (index != gun_index || pSysConfig->TotalConnectorCount == 1) {
-                log_info("GBT clean error : index = %d, EvConnAlarmCode = %s, code = %s \n",
-                         index,
-                         pDcChargingInfo->EvConnAlarmCode,
-                         code);
-
-                if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, code, 6) != EQUAL) {
-                    if (strncmp(code, "023702", 6) == EQUAL) { pInfoCode->InfoEvents.bits.GbEvCommFail = NO; }
-                    if (strncmp(code, "023900", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_LOS_CC1 = NO; }
-                    if (strncmp(code, "023901", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_CONNECTOR_LOCK_FAIL = NO; }
-                    if (strncmp(code, "023902", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_BATTERY_INCOMPATIBLE = NO; }
-                    if (strncmp(code, "023903", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_BMS_BROAA_TIMEOUT = NO; }
-                    if (strncmp(code, "023904", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_CSU_PRECHARGE_TIMEOUT = NO; }
-                    if (strncmp(code, "023905", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_BMS_PRESENT_VOLTAGE_FAULT = NO; }
-                    if (strncmp(code, "023906", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_BMS_VOLTAGE_OVER_RANGE = NO; }
-                    if (strncmp(code, "023907", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_BSM_CHARGE_ALLOW_00_10MIN_COUUNTDONE = NO; }
-                    if (strncmp(code, "023908", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_WAIT_GROUNDFAULT_TIMEOUT = NO; }
-                    if (strncmp(code, "023909", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_ADC_MORE_THAN_10V = NO; }
-                    if (strncmp(code, "023910", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_ADC_MORE_THAN_60V = NO; }
-                    if (strncmp(code, "023911", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_CHARGER_GET_NORMAL_STOP_CMD = NO; }
-                    if (strncmp(code, "023912", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_CHARGER_GET_EMERGENCY_STOP_CMD = NO; }
-                    if (strncmp(code, "023913", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_ISOLATION_RESULT_FAIL = NO; }
-                    if (strncmp(code, "023914", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_MOTHER_BOARD_MISS_LINK = NO; }
-                    if (strncmp(code, "023915", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_OUTPUT_VOLTAGE_MORE_THAN_LIMIT = NO; }
-                    if (strncmp(code, "023916", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_REQ_CURRENT_MORE_THAN_LIMIT = NO; }
-                    if (strncmp(code, "023917", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_OUTPUT_VOLTAGE_MORE_THAN_10_PERCENT = NO; }
-                    if (strncmp(code, "023918", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_OUTPUT_VOLTAGE_DIFF_BCS_5_PERCENT = NO; }
-                    if (strncmp(code, "023919", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_STOP_ADC_MORE_THAN_10V = NO; }
-                    if (strncmp(code, "023930", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BHM_TIMEOUT = NO; }
-                    if (strncmp(code, "023931", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BRM_TIMEOUT = NO; }
-                    if (strncmp(code, "023932", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BCP_TIMEOUT = NO; }
-                    if (strncmp(code, "023933", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BRO_TIMEOUT = NO; }
-                    if (strncmp(code, "023934", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BCL_TIMEOUT = NO; }
-                    if (strncmp(code, "023935", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BCS_TIMEOUT = NO; }
-                    if (strncmp(code, "023936", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BSM_TIMEOUT = NO; }
-                    if (strncmp(code, "023937", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BST_TIMEOUT = NO; }
-                    if (strncmp(code, "023938", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BSD_TIMEOUT = NO; }
-                    if (strncmp(code, "023939", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BEM_OTHER_TIMEOUT = NO; }
-                    if (strncmp(code, "023940", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BEM_CRM_TIMEOUT = NO; }
-                    if (strncmp(code, "023941", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BEM_CRMAA_TIMEOUT = NO; }
-                    if (strncmp(code, "023942", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BEM_CTS_CML_TIMEOUT = NO; }
-                    if (strncmp(code, "023943", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BEM_CRO_TIMEOUT = NO; }
-                    if (strncmp(code, "023944", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BEM_CCS_TIMEOUT = NO; }
-                    if (strncmp(code, "023945", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BEM_CST_TIMEOUT = NO; }
-                    if (strncmp(code, "023946", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BEM_CSD_TIMEOUT = NO; }
-                    if (strncmp(code, "023947", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BEM_BEM_OTHER_TIMEOUT = NO; }
-                    if (strncmp(code, "023950", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_SOC_GOAL = NO; }
-                    if (strncmp(code, "023951", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_TOTAL_VOLTAGE_GOAL = NO; }
-                    if (strncmp(code, "023952", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_CELL_VOLTAGE_GOAL = NO; }
-                    if (strncmp(code, "023953", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_GET_CST = NO; }
-                    if (strncmp(code, "023954", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_ISOLATION = NO; }
-                    if (strncmp(code, "023955", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_OUTPUT_CONNECTOR_OTP = NO; }
-                    if (strncmp(code, "023956", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_COMPONENT = NO; }
-                    if (strncmp(code, "023957", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_CHARGE_CONNECTOR = NO; }
-                    if (strncmp(code, "023958", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_OTP = NO; }
-                    if (strncmp(code, "023959", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_OTHER = NO; }
-                    if (strncmp(code, "023960", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_HIGH_V = NO; }
-                    if (strncmp(code, "023961", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_CC2 = NO; }
-                    if (strncmp(code, "023962", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_CURRENT = NO; }
-                    if (strncmp(code, "023963", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_VOLTAGE = NO; }
-                    if (strncmp(code, "023964", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GET_BST_NO_REASON = NO; }
-                    if (strncmp(code, "023970", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BSM_CELL_OVER_VOLTAGE = NO; }
-                    if (strncmp(code, "023971", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BSM_CELL_UNDER_VOLTAGE = NO; }
-                    if (strncmp(code, "023972", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BSM_OVER_SOC = NO; }
-                    if (strncmp(code, "023973", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BSM_UNDER_SOC = NO; }
-                    if (strncmp(code, "023974", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BSM_CURRENT = NO; }
-                    if (strncmp(code, "023975", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BSM_TEMPERATURE = NO; }
-                    if (strncmp(code, "023976", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BSM_ISOLATE = NO; }
-                    if (strncmp(code, "023977", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BSM_OUTPUT_CONNECTOR = NO; }
-                }
-            }
-        }
-    }
-
-    pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(gun_index);
-    if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "", 6) != EQUAL) {
-        memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
-    }
-}
+#include <stdio.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "../Config.h"
+#include "../Log/log.h"
+#include "../ShareMemory/shmMem.h"
+#include "../Define/define.h"
+
+//------------------------------------------------------------------------------
+void ClearAbnormalStatus_GB(uint8_t gun_index)
+{
+    bool isCleanCheck = false;
+    char code[7];
+    struct SysConfigData *pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
+    struct InfoCodeData *pInfoCode = (struct InfoCodeData *)GetShmInfoCodeData();
+    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gun_index);
+
+    if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "", 6) == EQUAL) {
+        return;
+    }
+
+    if (true) {
+        if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023702", 6) == EQUAL &&
+                pInfoCode->InfoEvents.bits.GbEvCommFail == YES) {
+            memcpy(code, "023702", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023900", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_LOS_CC1 == YES) {
+            memcpy(code, "023900", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023901", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_CONNECTOR_LOCK_FAIL == YES) {
+            memcpy(code, "023901", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023902", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_BATTERY_INCOMPATIBLE == YES) {
+            memcpy(code, "023902", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023903", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_BMS_BROAA_TIMEOUT == YES) {
+            memcpy(code, "023903", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023904", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_CSU_PRECHARGE_TIMEOUT == YES) {
+            memcpy(code, "023904", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023905", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_BMS_PRESENT_VOLTAGE_FAULT == YES) {
+            memcpy(code, "023905", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023906", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_BMS_VOLTAGE_OVER_RANGE == YES) {
+            memcpy(code, "023906", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023907", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_BSM_CHARGE_ALLOW_00_10MIN_COUUNTDONE == YES) {
+            memcpy(code, "023907", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023908", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_WAIT_GROUNDFAULT_TIMEOUT == YES) {
+            memcpy(code, "023908", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023909", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_ADC_MORE_THAN_10V == YES) {
+            memcpy(code, "023909", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023910", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_ADC_MORE_THAN_60V == YES) {
+            memcpy(code, "023910", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023911", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_CHARGER_GET_NORMAL_STOP_CMD == YES) {
+            memcpy(code, "023911", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023912", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_CHARGER_GET_EMERGENCY_STOP_CMD == YES) {
+            memcpy(code, "023912", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023913", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_ISOLATION_RESULT_FAIL == YES) {
+            memcpy(code, "023913", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023914", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_MOTHER_BOARD_MISS_LINK == YES) {
+            memcpy(code, "023914", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023915", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_OUTPUT_VOLTAGE_MORE_THAN_LIMIT == YES) {
+            memcpy(code, "023915", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023916", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_REQ_CURRENT_MORE_THAN_LIMIT == YES) {
+            memcpy(code, "023916", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023917", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_OUTPUT_VOLTAGE_MORE_THAN_10_PERCENT == YES) {
+            memcpy(code, "023917", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023918", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_OUTPUT_VOLTAGE_DIFF_BCS_5_PERCENT == YES) {
+            memcpy(code, "023918", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023919", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_STOP_ADC_MORE_THAN_10V == YES) {
+            memcpy(code, "023919", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023930", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BHM_TIMEOUT == YES) {
+            memcpy(code, "023930", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023931", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BRM_TIMEOUT == YES) {
+            memcpy(code, "023931", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023932", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BCP_TIMEOUT == YES) {
+            memcpy(code, "023932", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023933", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BRO_TIMEOUT == YES) {
+            memcpy(code, "023933", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023934", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BCL_TIMEOUT == YES) {
+            memcpy(code, "023934", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023935", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BCS_TIMEOUT == YES) {
+            memcpy(code, "023935", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023936", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BSM_TIMEOUT == YES) {
+            memcpy(code, "023936", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023937", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BST_TIMEOUT == YES) {
+            memcpy(code, "023937", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023938", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BSD_TIMEOUT == YES) {
+            memcpy(code, "023938", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023939", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BEM_OTHER_TIMEOUT == YES) {
+            memcpy(code, "023939", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023940", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_BEM_CRM_TIMEOUT == YES) {
+            memcpy(code, "023940", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023941", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_BEM_CRMAA_TIMEOUT == YES) {
+            memcpy(code, "023941", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023942", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_BEM_CTS_CML_TIMEOUT == YES) {
+            memcpy(code, "023942", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023943", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_BEM_CRO_TIMEOUT == YES) {
+            memcpy(code, "023943", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023944", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_BEM_CCS_TIMEOUT == YES) {
+            memcpy(code, "023944", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023945", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_BEM_CST_TIMEOUT == YES) {
+            memcpy(code, "023945", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023946", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_BEM_CSD_TIMEOUT == YES) {
+            memcpy(code, "023946", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023947", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_BEM_BEM_OTHER_TIMEOUT == YES) {
+            memcpy(code, "023947", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023950", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_BST_SOC_GOAL == YES) {
+            memcpy(code, "023950", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023951", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_BST_TOTAL_VOLTAGE_GOAL == YES) {
+            memcpy(code, "023951", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023952", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_BST_CELL_VOLTAGE_GOAL == YES) {
+            memcpy(code, "023952", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023953", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_BST_GET_CST == YES) {
+            memcpy(code, "023953", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023954", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_BST_ISOLATION == YES) {
+            memcpy(code, "023954", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023955", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_BST_OUTPUT_CONNECTOR_OTP == YES) {
+            memcpy(code, "023955", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023956", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_BST_COMPONENT == YES) {
+            memcpy(code, "023956", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023957", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_BST_CHARGE_CONNECTOR == YES) {
+            memcpy(code, "023957", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023958", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_BST_OTP == YES) {
+            memcpy(code, "023958", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023959", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_BST_OTHER == YES) {
+            memcpy(code, "023959", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023960", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_BST_HIGH_V == YES) {
+            memcpy(code, "023960", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023961", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_BST_CC2 == YES) {
+            memcpy(code, "023961", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023962", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_BST_CURRENT == YES) {
+            memcpy(code, "023962", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023963", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_BST_VOLTAGE == YES) {
+            memcpy(code, "023963", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023964", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_GET_BST_NO_REASON == YES) {
+            memcpy(code, "023964", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023970", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_BSM_CELL_OVER_VOLTAGE == YES) {
+            memcpy(code, "023970", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023971", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_BSM_CELL_UNDER_VOLTAGE == YES) {
+            memcpy(code, "023971", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023972", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_BSM_OVER_SOC == YES) {
+            memcpy(code, "023972", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023973", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_BSM_UNDER_SOC == YES) {
+            memcpy(code, "023973", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023974", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_BSM_CURRENT == YES) {
+            memcpy(code, "023974", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023975", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_BSM_TEMPERATURE == YES) {
+            memcpy(code, "023975", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023976", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_BSM_ISOLATE == YES) {
+            memcpy(code, "023976", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        } else if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "023977", 6) == EQUAL &&
+                   pInfoCode->InfoEvents.bits.ERROR_CODE_BSM_OUTPUT_CONNECTOR == YES) {
+            memcpy(code, "023977", 6);
+            memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+            isCleanCheck = true;
+        }
+    }
+
+    if (isCleanCheck) {
+        for (uint8_t index = 0; index < pSysConfig->TotalConnectorCount; index++) {
+            pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);
+
+            if (index != gun_index || pSysConfig->TotalConnectorCount == 1) {
+                log_info("GBT clean error : index = %d, EvConnAlarmCode = %s, code = %s \n",
+                         index,
+                         pDcChargingInfo->EvConnAlarmCode,
+                         code);
+
+                if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, code, 6) != EQUAL) {
+                    if (strncmp(code, "023702", 6) == EQUAL) { pInfoCode->InfoEvents.bits.GbEvCommFail = NO; }
+                    if (strncmp(code, "023900", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_LOS_CC1 = NO; }
+                    if (strncmp(code, "023901", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_CONNECTOR_LOCK_FAIL = NO; }
+                    if (strncmp(code, "023902", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_BATTERY_INCOMPATIBLE = NO; }
+                    if (strncmp(code, "023903", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_BMS_BROAA_TIMEOUT = NO; }
+                    if (strncmp(code, "023904", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_CSU_PRECHARGE_TIMEOUT = NO; }
+                    if (strncmp(code, "023905", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_BMS_PRESENT_VOLTAGE_FAULT = NO; }
+                    if (strncmp(code, "023906", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_BMS_VOLTAGE_OVER_RANGE = NO; }
+                    if (strncmp(code, "023907", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_BSM_CHARGE_ALLOW_00_10MIN_COUUNTDONE = NO; }
+                    if (strncmp(code, "023908", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_WAIT_GROUNDFAULT_TIMEOUT = NO; }
+                    if (strncmp(code, "023909", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_ADC_MORE_THAN_10V = NO; }
+                    if (strncmp(code, "023910", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_ADC_MORE_THAN_60V = NO; }
+                    if (strncmp(code, "023911", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_CHARGER_GET_NORMAL_STOP_CMD = NO; }
+                    if (strncmp(code, "023912", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_CHARGER_GET_EMERGENCY_STOP_CMD = NO; }
+                    if (strncmp(code, "023913", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_ISOLATION_RESULT_FAIL = NO; }
+                    if (strncmp(code, "023914", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_MOTHER_BOARD_MISS_LINK = NO; }
+                    if (strncmp(code, "023915", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_OUTPUT_VOLTAGE_MORE_THAN_LIMIT = NO; }
+                    if (strncmp(code, "023916", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_REQ_CURRENT_MORE_THAN_LIMIT = NO; }
+                    if (strncmp(code, "023917", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_OUTPUT_VOLTAGE_MORE_THAN_10_PERCENT = NO; }
+                    if (strncmp(code, "023918", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_OUTPUT_VOLTAGE_DIFF_BCS_5_PERCENT = NO; }
+                    if (strncmp(code, "023919", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_STOP_ADC_MORE_THAN_10V = NO; }
+                    if (strncmp(code, "023930", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BHM_TIMEOUT = NO; }
+                    if (strncmp(code, "023931", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BRM_TIMEOUT = NO; }
+                    if (strncmp(code, "023932", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BCP_TIMEOUT = NO; }
+                    if (strncmp(code, "023933", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BRO_TIMEOUT = NO; }
+                    if (strncmp(code, "023934", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BCL_TIMEOUT = NO; }
+                    if (strncmp(code, "023935", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BCS_TIMEOUT = NO; }
+                    if (strncmp(code, "023936", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BSM_TIMEOUT = NO; }
+                    if (strncmp(code, "023937", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BST_TIMEOUT = NO; }
+                    if (strncmp(code, "023938", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BSD_TIMEOUT = NO; }
+                    if (strncmp(code, "023939", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BEM_OTHER_TIMEOUT = NO; }
+                    if (strncmp(code, "023940", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BEM_CRM_TIMEOUT = NO; }
+                    if (strncmp(code, "023941", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BEM_CRMAA_TIMEOUT = NO; }
+                    if (strncmp(code, "023942", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BEM_CTS_CML_TIMEOUT = NO; }
+                    if (strncmp(code, "023943", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BEM_CRO_TIMEOUT = NO; }
+                    if (strncmp(code, "023944", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BEM_CCS_TIMEOUT = NO; }
+                    if (strncmp(code, "023945", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BEM_CST_TIMEOUT = NO; }
+                    if (strncmp(code, "023946", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BEM_CSD_TIMEOUT = NO; }
+                    if (strncmp(code, "023947", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BEM_BEM_OTHER_TIMEOUT = NO; }
+                    if (strncmp(code, "023950", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_SOC_GOAL = NO; }
+                    if (strncmp(code, "023951", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_TOTAL_VOLTAGE_GOAL = NO; }
+                    if (strncmp(code, "023952", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_CELL_VOLTAGE_GOAL = NO; }
+                    if (strncmp(code, "023953", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_GET_CST = NO; }
+                    if (strncmp(code, "023954", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_ISOLATION = NO; }
+                    if (strncmp(code, "023955", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_OUTPUT_CONNECTOR_OTP = NO; }
+                    if (strncmp(code, "023956", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_COMPONENT = NO; }
+                    if (strncmp(code, "023957", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_CHARGE_CONNECTOR = NO; }
+                    if (strncmp(code, "023958", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_OTP = NO; }
+                    if (strncmp(code, "023959", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_OTHER = NO; }
+                    if (strncmp(code, "023960", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_HIGH_V = NO; }
+                    if (strncmp(code, "023961", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_CC2 = NO; }
+                    if (strncmp(code, "023962", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_CURRENT = NO; }
+                    if (strncmp(code, "023963", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_VOLTAGE = NO; }
+                    if (strncmp(code, "023964", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GET_BST_NO_REASON = NO; }
+                    if (strncmp(code, "023970", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BSM_CELL_OVER_VOLTAGE = NO; }
+                    if (strncmp(code, "023971", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BSM_CELL_UNDER_VOLTAGE = NO; }
+                    if (strncmp(code, "023972", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BSM_OVER_SOC = NO; }
+                    if (strncmp(code, "023973", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BSM_UNDER_SOC = NO; }
+                    if (strncmp(code, "023974", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BSM_CURRENT = NO; }
+                    if (strncmp(code, "023975", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BSM_TEMPERATURE = NO; }
+                    if (strncmp(code, "023976", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BSM_ISOLATE = NO; }
+                    if (strncmp(code, "023977", 6) == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BSM_OUTPUT_CONNECTOR = NO; }
+                }
+            }
+        }
+    }
+
+    pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(gun_index);
+    if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "", 6) != EQUAL) {
+        memcpy(pDcChargingInfo->EvConnAlarmCode, "", 6);
+    }
+}

+ 292 - 292
EVSE/Projects/DD360Tcci/Apps/ModuleEvComm/AbnormalState.c

@@ -1,292 +1,292 @@
-#include <stdio.h>
-#include <stdint.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include "../Config.h"
-#include "../Log/log.h"
-#include "../ShareMemory/shmMem.h"
-#include "../Define/define.h"
-
-//------------------------------------------------------------------------------
-bool AbnormalStopAnalysis(uint8_t gun_index, uint8_t *errCode)
-{
-    char string[7];
-
-    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gun_index);
-    struct AlarmCodeData *pAlarmCode = (struct AlarmCodeData *)GetShmAlarmCodeData();
-    struct InfoCodeData *pInfoCode = (struct InfoCodeData *)GetShmInfoCodeData();
-
-    sprintf(string, "%d%d%d%d%d%d",
-            *(errCode + 0),
-            *(errCode + 1),
-            *(errCode + 2),
-            *(errCode + 3),
-            *(errCode + 4),
-            *(errCode + 5));
-    //iflog_info("NOTIFICATION_EV_STOP : Err Code = %s \n", string);
-
-    if (strncmp(string, "000000", 6) == EQUAL ||
-            strncmp(string, "012219", 6) == EQUAL ||
-            strncmp(string, "023979", 6) == EQUAL || 
-            strncmp(string, "023983", 6) == EQUAL)
-    {
-		log_info("NOTIFICATION_EV_STOP : EvCode = %s\n", string);
-        return false;
-    }
-
-    if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "", 6) != EQUAL) {
-        return true;
-    }
-
-    memcpy(pDcChargingInfo->EvConnAlarmCode, string, 6);
-    log_info("NOTIFICATION_EV_STOP : EvConnAlarmCode = %s\n", pDcChargingInfo->EvConnAlarmCode);
-
-    if (strcmp(string, "023700") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoEvCommFail = YES; }
-    if (strcmp(string, "023704") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBatteryMalfun = YES; }
-    if (strcmp(string, "023705") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoNoPermission = YES; }
-    if (strcmp(string, "023706") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBatteryIncompatibility = YES; }
-    if (strcmp(string, "023707") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBatteryOVP = YES; }
-    if (strcmp(string, "023708") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBatteryUVP = YES; }
-    if (strcmp(string, "023709") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBatteryOTP = YES; }
-    if (strcmp(string, "023710") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBatteryCurrentDiff = YES; }
-    if (strcmp(string, "023711") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBatteryVoltageDiff = YES; }
-    if (strcmp(string, "023712") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoShiftPosition = YES; }
-    if (strcmp(string, "023713") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBatteryOtherFault = YES; }
-    if (strcmp(string, "023714") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoChargingSystemError = YES; }
-    if (strcmp(string, "023715") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoEvNormalStop = YES; }
-    if (strcmp(string, "023716") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoTempSensorBroken = YES; }
-    if (strcmp(string, "023717") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoConnectorLockFail = YES; }
-    if (strcmp(string, "023718") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoD1OnNoReceive = YES; }
-    if (strcmp(string, "023719") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBmsKtoJTimeout = YES; }
-    if (strcmp(string, "023720") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBmsChargeAllowTimeout = YES; }
-    if (strcmp(string, "023721") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoWaitGfdTimeout = YES; }
-    if (strcmp(string, "023722") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBmsEvRelayTimeout = YES; }
-    if (strcmp(string, "023723") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBmsReqCurrentTimeout = YES; }
-    if (strcmp(string, "023724") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBmsKtoJOffTimeout = YES; }
-    if (strcmp(string, "023725") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBmsEvRelayOffTimeout = YES; }
-    if (strcmp(string, "023726") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoAdcMoreThan10V = YES; }
-    if (strcmp(string, "023727") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoAdcMoreThan20V = YES; }
-    if (strcmp(string, "023728") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBmsChargeBeforeStop = YES; }
-    if (strcmp(string, "023729") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoChargerGetNormalStop = YES; }
-    if (strcmp(string, "023730") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoChargerGetEmergencyStop = YES; }
-    if (strcmp(string, "023731") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoIsolationResultFail = YES; }
-    if (strcmp(string, "023732") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoMissLinkWithMotherBoard = YES; }
-    if (strcmp(string, "023733") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoOutputVolMoreThanLimit = YES; }
-    if (strcmp(string, "023734") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoReqCurrentMoreThanLimit = YES; }
-    if (strcmp(string, "023735") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoReCapBmsEqrCurrentExceed = YES; }
-    if (strcmp(string, "023736") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoChargeRemainCountDown = YES; }
-    if (strcmp(string, "023980") == EQUAL) { pInfoCode->InfoEvents.bits.CHADEMO_BMS_CHARGE_ALLOW_ERROR = YES; }
-    if (strcmp(string, "023981") == EQUAL) { pInfoCode->InfoEvents.bits.CHADEMO_OUTPUT_VOLTAGE_MORE_THEN_10_PERCENT = YES; }
-    if (strcmp(string, "023982") == EQUAL) { pInfoCode->InfoEvents.bits.CHADEMO_ADC_LESS_THAN_10V = YES; }
-
-    if (strcmp(string, "012288") == EQUAL) { pAlarmCode->AlarmEvents.bits.CcsOutputUVPFail = YES; }
-    if (strcmp(string, "023701") == EQUAL) { pInfoCode->InfoEvents.bits.CcsEvCommFail = YES; }
-    if (strcmp(string, "023737") == EQUAL) { pInfoCode->InfoEvents.bits.CcsRESTemperatureInhibit = YES; }
-    if (strcmp(string, "023738") == EQUAL) { pInfoCode->InfoEvents.bits.CcsEVShiftPosition = YES; }
-    if (strcmp(string, "023739") == EQUAL) { pInfoCode->InfoEvents.bits.CcsChargerConnectorLockFault = YES; }
-    if (strcmp(string, "023740") == EQUAL) { pInfoCode->InfoEvents.bits.CcsEVRESSMalfunction = YES; }
-    if (strcmp(string, "023741") == EQUAL) { pInfoCode->InfoEvents.bits.CcsChargingCurrentdifferential = YES; }
-    if (strcmp(string, "023742") == EQUAL) { pInfoCode->InfoEvents.bits.CcsChargingVoltageOutOfRange = YES; }
-    if (strcmp(string, "023743") == EQUAL) { pInfoCode->InfoEvents.bits.CcsChargingSystemIncompatibility = YES; }
-    if (strcmp(string, "023744") == EQUAL) { pInfoCode->InfoEvents.bits.CcsEmergencyEvent = YES; }
-    if (strcmp(string, "023745") == EQUAL) { pInfoCode->InfoEvents.bits.CcsBreaker = YES; }
-    if (strcmp(string, "023746") == EQUAL) { pInfoCode->InfoEvents.bits.CcsNoData = YES; }
-    if (strcmp(string, "023747") == EQUAL) { pInfoCode->InfoEvents.bits.Ccsreserved_by_DIN_A = YES; }
-    if (strcmp(string, "023748") == EQUAL) { pInfoCode->InfoEvents.bits.Ccsreserved_by_DIN_B = YES; }
-    if (strcmp(string, "023749") == EQUAL) { pInfoCode->InfoEvents.bits.Ccsreserved_by_DIN_C = YES; }
-    if (strcmp(string, "023750") == EQUAL) { pInfoCode->InfoEvents.bits.Ccsreserved_by_ISO_1 = YES; }
-    if (strcmp(string, "023751") == EQUAL) { pInfoCode->InfoEvents.bits.Ccsreserved_by_ISO_2 = YES; }
-    if (strcmp(string, "023752") == EQUAL) { pInfoCode->InfoEvents.bits.Ccsreserved_by_ISO_3 = YES; }
-    if (strcmp(string, "023753") == EQUAL) { pInfoCode->InfoEvents.bits.Ccsreserved_by_OEM_1 = YES; }
-    if (strcmp(string, "023754") == EQUAL) { pInfoCode->InfoEvents.bits.Ccsreserved_by_OEM_2 = YES; }
-    if (strcmp(string, "023755") == EQUAL) { pInfoCode->InfoEvents.bits.Ccsreserved_by_OEM_3 = YES; }
-    if (strcmp(string, "023756") == EQUAL) { pInfoCode->InfoEvents.bits.Ccsreserved_by_OEM_4 = YES; }
-    if (strcmp(string, "023757") == EQUAL) { pInfoCode->InfoEvents.bits.Ccsreserved_by_OEM_5 = YES; }
-    if (strcmp(string, "023758") == EQUAL) { pInfoCode->InfoEvents.bits.CcsSequenceError = YES; }
-    if (strcmp(string, "023759") == EQUAL) { pInfoCode->InfoEvents.bits.CcsSignatureError = YES; }
-    if (strcmp(string, "023760") == EQUAL) { pInfoCode->InfoEvents.bits.CcsUnknownSession = YES; }
-    if (strcmp(string, "023761") == EQUAL) { pInfoCode->InfoEvents.bits.CcsServiceIDInvalid = YES; }
-    if (strcmp(string, "023762") == EQUAL) { pInfoCode->InfoEvents.bits.CcsPaymentSelectionInvalid = YES; }
-    if (strcmp(string, "023763") == EQUAL) { pInfoCode->InfoEvents.bits.CcsIdentificationSelectionInvalid = YES; }
-    if (strcmp(string, "023764") == EQUAL) { pInfoCode->InfoEvents.bits.CcsServiceSelectionInvalid = YES; }
-    if (strcmp(string, "023765") == EQUAL) { pInfoCode->InfoEvents.bits.CcsCertificateExpired = YES; }
-    if (strcmp(string, "023766") == EQUAL) { pInfoCode->InfoEvents.bits.CcsCertificateNotYetValid = YES; }
-    if (strcmp(string, "023767") == EQUAL) { pInfoCode->InfoEvents.bits.CcsCertificateRevoked = YES; }
-    if (strcmp(string, "023768") == EQUAL) { pInfoCode->InfoEvents.bits.CcsNoCertificateAvailable = YES; }
-    if (strcmp(string, "023769") == EQUAL) { pInfoCode->InfoEvents.bits.CcsCertChainError = YES; }
-    if (strcmp(string, "023770") == EQUAL) { pInfoCode->InfoEvents.bits.CcsCertValidationError = YES; }
-    if (strcmp(string, "023771") == EQUAL) { pInfoCode->InfoEvents.bits.CcsCertVerificationError = YES; }
-    if (strcmp(string, "023772") == EQUAL) { pInfoCode->InfoEvents.bits.CcsContractCanceled = YES; }
-    if (strcmp(string, "023773") == EQUAL) { pInfoCode->InfoEvents.bits.CcsChallengeInvalid = YES; }
-    if (strcmp(string, "023774") == EQUAL) { pInfoCode->InfoEvents.bits.CcsWrongEnergyTransferMode = YES; }
-    if (strcmp(string, "023775") == EQUAL) { pInfoCode->InfoEvents.bits.CcsWrongChargeParameter = YES; }
-    if (strcmp(string, "023776") == EQUAL) { pInfoCode->InfoEvents.bits.CcsChargingProfileInvalid = YES; }
-    if (strcmp(string, "023777") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTariffSelectionInvalid = YES; }
-    if (strcmp(string, "023778") == EQUAL) { pInfoCode->InfoEvents.bits.CcsEVSEPresentVoltageToLow = YES; }
-    if (strcmp(string, "023779") == EQUAL) { pInfoCode->InfoEvents.bits.CcsPowerDeliveryNotApplied = YES; }
-    if (strcmp(string, "023780") == EQUAL) { pInfoCode->InfoEvents.bits.CcsMeteringSignatureNotValid = YES; }
-    if (strcmp(string, "023781") == EQUAL) { pInfoCode->InfoEvents.bits.CcsNoChargeServiceSelected = YES; }
-    if (strcmp(string, "023782") == EQUAL) { pInfoCode->InfoEvents.bits.CcsContactorError = YES; }
-    if (strcmp(string, "023783") == EQUAL) { pInfoCode->InfoEvents.bits.CcsCertificateNotAllowedAtThisEVSE = YES; }
-    if (strcmp(string, "023784") == EQUAL) { pInfoCode->InfoEvents.bits.CcsGAChargeStop = YES; }
-    if (strcmp(string, "023785") == EQUAL) { pInfoCode->InfoEvents.bits.CcsAlignmentError = YES; }
-    if (strcmp(string, "023786") == EQUAL) { pInfoCode->InfoEvents.bits.CcsACDError = YES; }
-    if (strcmp(string, "023787") == EQUAL) { pInfoCode->InfoEvents.bits.CcsAssociationError = YES; }
-    if (strcmp(string, "023788") == EQUAL) { pInfoCode->InfoEvents.bits.CcsEVSEChargeAbort = YES; }
-    if (strcmp(string, "023789") == EQUAL) { pInfoCode->InfoEvents.bits.CcsNoSupportedAppProtocol = YES; }
-    if (strcmp(string, "023790") == EQUAL) { pInfoCode->InfoEvents.bits.CcsContractNotAccepted = YES; }
-    if (strcmp(string, "023791") == EQUAL) { pInfoCode->InfoEvents.bits.CcsMOUnknown = YES; }
-    if (strcmp(string, "023792") == EQUAL) { pInfoCode->InfoEvents.bits.CcsOEM_Prov_CertificateRevoke = YES; }
-    if (strcmp(string, "023793") == EQUAL) { pInfoCode->InfoEvents.bits.CcsOEM_SubCA1_CertificateRevoked = YES; }
-    if (strcmp(string, "023794") == EQUAL) { pInfoCode->InfoEvents.bits.CcsOEM_SubCA2_CertificateRevoked = YES; }
-    if (strcmp(string, "023795") == EQUAL) { pInfoCode->InfoEvents.bits.CcsOEM_RootCA_CertificateRevoked = YES; }
-    if (strcmp(string, "023796") == EQUAL) { pInfoCode->InfoEvents.bits.CcsMO_Prov_CertificateRevoked = YES; }
-    if (strcmp(string, "023797") == EQUAL) { pInfoCode->InfoEvents.bits.CcsMO_SubCA1_CertificateRevoked = YES; }
-    if (strcmp(string, "023798") == EQUAL) { pInfoCode->InfoEvents.bits.CcsMO_SubCA2_CertificateRevoked = YES; }
-    if (strcmp(string, "023799") == EQUAL) { pInfoCode->InfoEvents.bits.CcsMO_RootCA_CertificateRevoked = YES; }
-    if (strcmp(string, "023800") == EQUAL) { pInfoCode->InfoEvents.bits.CcsCPS_Prov_CertificateRevoked = YES; }
-    if (strcmp(string, "023801") == EQUAL) { pInfoCode->InfoEvents.bits.CcsCPS_SubCA1_CertificateRevoked = YES; }
-    if (strcmp(string, "023802") == EQUAL) { pInfoCode->InfoEvents.bits.CcsCPS_SubCA2_CertificateRevoked = YES; }
-    if (strcmp(string, "023803") == EQUAL) { pInfoCode->InfoEvents.bits.CcsCPS_RootCA_CertificateRevoked = YES; }
-    if (strcmp(string, "023809") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_EVSE_SLAC_init = YES; }
-    if (strcmp(string, "023810") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_match_response = YES; }
-    if (strcmp(string, "023811") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_match_sequence = YES; }
-    if (strcmp(string, "023812") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_EVSE_match_MNBC = YES; }
-    if (strcmp(string, "023813") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_EVSE_avg_atten_calc = YES; }
-    if (strcmp(string, "023814") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_match_response = YES; }
-    if (strcmp(string, "023815") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_EVSE_match_session = YES; }
-    if (strcmp(string, "023816") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_EVSE_assoc_session = YES; }
-    if (strcmp(string, "023817") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_EVSE_vald_toggle = YES; }
-    if (strcmp(string, "023818") == EQUAL) { pInfoCode->InfoEvents.bits.CcsSeccSlacTimeoutCmMnbcSound = YES; }
-    if (strcmp(string, "023819") == EQUAL) { pInfoCode->InfoEvents.bits.CcsSeccSlacTimeoutCmValidateReq = YES; }
-    if (strcmp(string, "023823") == EQUAL) { pInfoCode->InfoEvents.bits.CcsUDP_TT_match_join = YES; }
-    if (strcmp(string, "023824") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTCP_TT_match_join = YES; }
-    if (strcmp(string, "023825") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_amp_map_exchange = YES; }
-    if (strcmp(string, "023826") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_link_ready_notification = YES; }
-    if (strcmp(string, "023832") == EQUAL) { pInfoCode->InfoEvents.bits.CcsSupportedAppProtocolRes = YES; }
-    if (strcmp(string, "023833") == EQUAL) { pInfoCode->InfoEvents.bits.CcsSessionSetupRes = YES; }
-    if (strcmp(string, "023834") == EQUAL) { pInfoCode->InfoEvents.bits.CcsServiceDiscoveryRes = YES; }
-    if (strcmp(string, "023835") == EQUAL) { pInfoCode->InfoEvents.bits.CcsServicePaymentSelectionRes = YES; }
-    if (strcmp(string, "023836") == EQUAL) { pInfoCode->InfoEvents.bits.CcsContractAuthenticationRes = YES; }
-    if (strcmp(string, "023837") == EQUAL) { pInfoCode->InfoEvents.bits.CcsChargeParameterDiscoveryRes = YES; }
-    if (strcmp(string, "023838") == EQUAL) { pInfoCode->InfoEvents.bits.CcsPowerDeliveryRes = YES; }
-    if (strcmp(string, "023839") == EQUAL) { pInfoCode->InfoEvents.bits.CcsCableCheckRes = YES; }
-    if (strcmp(string, "023840") == EQUAL) { pInfoCode->InfoEvents.bits.CcsPreChargeRes = YES; }
-    if (strcmp(string, "023841") == EQUAL) { pInfoCode->InfoEvents.bits.CcsCurrentDemandRes = YES; }
-    if (strcmp(string, "023842") == EQUAL) { pInfoCode->InfoEvents.bits.CcsWeldingDetectionRes = YES; }
-    if (strcmp(string, "023843") == EQUAL) { pInfoCode->InfoEvents.bits.CcsSessionStopRes = YES; }
-    if (strcmp(string, "023844") == EQUAL) { pInfoCode->InfoEvents.bits.CcsSequence_Time = YES; }
-    if (strcmp(string, "023845") == EQUAL) { pInfoCode->InfoEvents.bits.CcsReadyToCharge_Performance_Time = YES; }
-    if (strcmp(string, "023846") == EQUAL) { pInfoCode->InfoEvents.bits.CcsCommunicationSetup_Performance_Time = YES; }
-    if (strcmp(string, "023847") == EQUAL) { pInfoCode->InfoEvents.bits.CcsCableCheck_Performance_Time = YES; }
-    if (strcmp(string, "023848") == EQUAL) { pInfoCode->InfoEvents.bits.CcsCPState_Detection_Time = YES; }
-    if (strcmp(string, "023849") == EQUAL) { pInfoCode->InfoEvents.bits.CcsCPOscillator_Retain_Time = YES; }
-    if (strcmp(string, "023850") == EQUAL) { pInfoCode->InfoEvents.bits.CcsSeccTimeoutV2GPreChargePerformaceTime = YES; }
-    if (strcmp(string, "023855") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_GET_EV_TARGET_INFO = YES; }
-    if (strcmp(string, "023856") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_GET_EV_TARGET_INFO = YES; }
-    if (strcmp(string, "023857") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_GET_EV_BATTERY_INFO = YES; }
-    if (strcmp(string, "023858") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_GET_EV_BATTERY_INFO = YES; }
-    if (strcmp(string, "023859") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_EV_STOP_EVENT = YES; }
-    if (strcmp(string, "023860") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_EV_STOP_EVENT = YES; }
-    if (strcmp(string, "023861") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_EVSE_STOP_EVENT = YES; }
-    if (strcmp(string, "023862") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_EVSE_STOP_EVENT = YES; }
-    if (strcmp(string, "023863") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_GET_MISC_INFO = YES; }
-    if (strcmp(string, "023864") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_GET_MISC_INFO = YES; }
-    if (strcmp(string, "023865") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_DOWNLOAD_REQUEST = YES; }
-    if (strcmp(string, "023866") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_DOWNLOAD_REQUEST = YES; }
-    if (strcmp(string, "023867") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_START_BLOCK_TRANSFER = YES; }
-    if (strcmp(string, "023868") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_START_BLOCK_TRANSFER = YES; }
-    if (strcmp(string, "023869") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_DATA_TRANSFER = YES; }
-    if (strcmp(string, "023870") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_DATA_TRANSFER = YES; }
-    if (strcmp(string, "023871") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_DOWNLOAD_FINISH = YES; }
-    if (strcmp(string, "023872") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_DOWNLOAD_FINISH = YES; }
-    if (strcmp(string, "023873") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_ISOLATION_STATUS = YES; }
-    if (strcmp(string, "023874") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_ISOLATION_STATUS = YES; }
-    if (strcmp(string, "023875") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_CONNECTOR_INFO = YES; }
-    if (strcmp(string, "023876") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_CONNECTOR_INFO = YES; }
-    if (strcmp(string, "023877") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_RTC_INFO = YES; }
-    if (strcmp(string, "023878") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_RTC_INFO = YES; }
-    if (strcmp(string, "023879") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_EVSE_PRECHARGE_INFO = YES; }
-    if (strcmp(string, "023880") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_EVSE_PRECHARGE_INFO = YES; }
-    if (strcmp(string, "023881") == EQUAL) { pInfoCode->InfoEvents.bits.CcsMSG_Sequence = YES; }
-    if (strcmp(string, "023882") == EQUAL) { pInfoCode->InfoEvents.bits.CcsCAN_MSG_Unrecognized_CMD_ID = YES; }
-    if (strcmp(string, "023883") == EQUAL) { pInfoCode->InfoEvents.bits.CcsDIN_Msg_Decode_Error = YES; }
-    if (strcmp(string, "023884") == EQUAL) { pInfoCode->InfoEvents.bits.CcsDIN_Msg_Encode_Error = YES; }
-    if (strcmp(string, "023885") == EQUAL) { pInfoCode->InfoEvents.bits.CcsISO1_Msg_Decode_Error = YES; }
-    if (strcmp(string, "023886") == EQUAL) { pInfoCode->InfoEvents.bits.CcsISO1_Msg_Encode_Error = YES; }
-    if (strcmp(string, "023887") == EQUAL) { pInfoCode->InfoEvents.bits.CcsISO2_Msg_Decode_Error = YES; }
-    if (strcmp(string, "023888") == EQUAL) { pInfoCode->InfoEvents.bits.CcsISO2_Msg_Encode_Error = YES; }
-    if (strcmp(string, "023889") == EQUAL) { pInfoCode->InfoEvents.bits.CcsCpStatus_Error = YES; }
-    if (strcmp(string, "023890") == EQUAL) { pInfoCode->InfoEvents.bits.CcsUnexpectVolBeforeCharing_Error = YES; }
-    if (strcmp(string, "023891") == EQUAL) { pInfoCode->InfoEvents.bits.CcsSeccNotReadyForCharging = YES; }
-    if (strcmp(string, "023892") == EQUAL) { pInfoCode->InfoEvents.bits.CcsSeccTimeoutQCA7000Comm = YES; }
-    if (strcmp(string, "023893") == EQUAL) { pInfoCode->InfoEvents.bits.CcsSeccFailForQCA7000SetKey = YES; }
-    if (strcmp(string, "023979") == EQUAL) { pInfoCode->InfoEvents.bits.EV_Full_Charging = YES; }
-    if (strcmp(string, "023983") == EQUAL) { pInfoCode->InfoEvents.bits.Stop_by_EV_with_unknow_reason = YES; }
-
-    if (strcmp(string, "023702") == EQUAL) { pInfoCode->InfoEvents.bits.GbEvCommFail = YES; }
-    if (strcmp(string, "023900") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_LOS_CC1 = YES; }
-    if (strcmp(string, "023901") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_CONNECTOR_LOCK_FAIL = YES; }
-    if (strcmp(string, "023902") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_BATTERY_INCOMPATIBLE = YES; }
-    if (strcmp(string, "023903") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_BMS_BROAA_TIMEOUT = YES; }
-    if (strcmp(string, "023904") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_CSU_PRECHARGE_TIMEOUT = YES; }
-    if (strcmp(string, "023905") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_BMS_PRESENT_VOLTAGE_FAULT = YES; }
-    if (strcmp(string, "023906") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_BMS_VOLTAGE_OVER_RANGE = YES; }
-    if (strcmp(string, "023907") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_BSM_CHARGE_ALLOW_00_10MIN_COUUNTDONE = YES; }
-    if (strcmp(string, "023908") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_WAIT_GROUNDFAULT_TIMEOUT = YES; }
-    if (strcmp(string, "023909") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_ADC_MORE_THAN_10V = YES; }
-    if (strcmp(string, "023910") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_ADC_MORE_THAN_60V = YES; }
-    if (strcmp(string, "023911") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_CHARGER_GET_NORMAL_STOP_CMD = YES; }
-    if (strcmp(string, "023912") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_CHARGER_GET_EMERGENCY_STOP_CMD = YES; }
-    if (strcmp(string, "023913") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_ISOLATION_RESULT_FAIL = YES; }
-    if (strcmp(string, "023914") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_MOTHER_BOARD_MISS_LINK = YES; }
-    if (strcmp(string, "023915") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_OUTPUT_VOLTAGE_MORE_THAN_LIMIT = YES; }
-    if (strcmp(string, "023916") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_REQ_CURRENT_MORE_THAN_LIMIT = YES; }
-    if (strcmp(string, "023917") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_OUTPUT_VOLTAGE_MORE_THAN_10_PERCENT = YES; }
-    if (strcmp(string, "023918") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_OUTPUT_VOLTAGE_DIFF_BCS_5_PERCENT = YES; }
-    if (strcmp(string, "023919") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_STOP_ADC_MORE_THAN_10V = YES; }
-    if (strcmp(string, "023930") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BHM_TIMEOUT = YES; }
-    if (strcmp(string, "023931") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BRM_TIMEOUT = YES; }
-    if (strcmp(string, "023932") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BCP_TIMEOUT = YES; }
-    if (strcmp(string, "023933") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BRO_TIMEOUT = YES; }
-    if (strcmp(string, "023934") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BCL_TIMEOUT = YES; }
-    if (strcmp(string, "023935") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BCS_TIMEOUT = YES; }
-    if (strcmp(string, "023936") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BSM_TIMEOUT = YES; }
-    if (strcmp(string, "023937") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BST_TIMEOUT = YES; }
-    if (strcmp(string, "023938") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BSD_TIMEOUT = YES; }
-    if (strcmp(string, "023939") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BEM_OTHER_TIMEOUT = YES; }
-    if (strcmp(string, "023940") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BEM_CRM_TIMEOUT = YES; }
-    if (strcmp(string, "023941") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BEM_CRMAA_TIMEOUT = YES; }
-    if (strcmp(string, "023942") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BEM_CTS_CML_TIMEOUT = YES; }
-    if (strcmp(string, "023943") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BEM_CRO_TIMEOUT = YES; }
-    if (strcmp(string, "023944") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BEM_CCS_TIMEOUT = YES; }
-    if (strcmp(string, "023945") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BEM_CST_TIMEOUT = YES; }
-    if (strcmp(string, "023946") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BEM_CSD_TIMEOUT = YES; }
-    if (strcmp(string, "023947") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BEM_BEM_OTHER_TIMEOUT = YES; }
-    if (strcmp(string, "023950") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_SOC_GOAL = YES; }
-    if (strcmp(string, "023951") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_TOTAL_VOLTAGE_GOAL = YES; }
-    if (strcmp(string, "023952") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_CELL_VOLTAGE_GOAL = YES; }
-    if (strcmp(string, "023953") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_GET_CST = YES; }
-    if (strcmp(string, "023954") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_ISOLATION = YES; }
-    if (strcmp(string, "023955") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_OUTPUT_CONNECTOR_OTP = YES; }
-    if (strcmp(string, "023956") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_COMPONENT = YES; }
-    if (strcmp(string, "023957") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_CHARGE_CONNECTOR = YES; }
-    if (strcmp(string, "023958") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_OTP = YES; }
-    if (strcmp(string, "023959") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_OTHER = YES; }
-    if (strcmp(string, "023960") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_HIGH_V = YES; }
-    if (strcmp(string, "023961") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_CC2 = YES; }
-    if (strcmp(string, "023962") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_CURRENT = YES; }
-    if (strcmp(string, "023963") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_VOLTAGE = YES; }
-    if (strcmp(string, "023964") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GET_BST_NO_REASON = YES; }
-    if (strcmp(string, "023970") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BSM_CELL_OVER_VOLTAGE = YES; }
-    if (strcmp(string, "023971") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BSM_CELL_UNDER_VOLTAGE = YES; }
-    if (strcmp(string, "023972") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BSM_OVER_SOC = YES; }
-    if (strcmp(string, "023973") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BSM_UNDER_SOC = YES; }
-    if (strcmp(string, "023974") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BSM_CURRENT = YES; }
-    if (strcmp(string, "023975") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BSM_TEMPERATURE = YES; }
-    if (strcmp(string, "023976") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BSM_ISOLATE = YES; }
-    if (strcmp(string, "023977") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BSM_OUTPUT_CONNECTOR = YES; }
-
-    return true;
-}
+#include <stdio.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "../Config.h"
+#include "../Log/log.h"
+#include "../ShareMemory/shmMem.h"
+#include "../Define/define.h"
+
+//------------------------------------------------------------------------------
+bool AbnormalStopAnalysis(uint8_t gun_index, uint8_t *errCode)
+{
+    char string[7];
+
+    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gun_index);
+    struct AlarmCodeData *pAlarmCode = (struct AlarmCodeData *)GetShmAlarmCodeData();
+    struct InfoCodeData *pInfoCode = (struct InfoCodeData *)GetShmInfoCodeData();
+
+    sprintf(string, "%d%d%d%d%d%d",
+            *(errCode + 0),
+            *(errCode + 1),
+            *(errCode + 2),
+            *(errCode + 3),
+            *(errCode + 4),
+            *(errCode + 5));
+    //iflog_info("NOTIFICATION_EV_STOP : Err Code = %s \n", string);
+
+    if (strncmp(string, "000000", 6) == EQUAL ||
+            strncmp(string, "012219", 6) == EQUAL ||
+            strncmp(string, "023979", 6) == EQUAL || 
+            strncmp(string, "023983", 6) == EQUAL)
+    {
+		log_info("NOTIFICATION_EV_STOP : EvCode = %s\n", string);
+        return false;
+    }
+
+    if (strncmp((char *)pDcChargingInfo->EvConnAlarmCode, "", 6) != EQUAL) {
+        return true;
+    }
+
+    memcpy(pDcChargingInfo->EvConnAlarmCode, string, 6);
+    log_info("NOTIFICATION_EV_STOP : EvConnAlarmCode = %s\n", pDcChargingInfo->EvConnAlarmCode);
+
+    if (strcmp(string, "023700") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoEvCommFail = YES; }
+    if (strcmp(string, "023704") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBatteryMalfun = YES; }
+    if (strcmp(string, "023705") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoNoPermission = YES; }
+    if (strcmp(string, "023706") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBatteryIncompatibility = YES; }
+    if (strcmp(string, "023707") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBatteryOVP = YES; }
+    if (strcmp(string, "023708") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBatteryUVP = YES; }
+    if (strcmp(string, "023709") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBatteryOTP = YES; }
+    if (strcmp(string, "023710") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBatteryCurrentDiff = YES; }
+    if (strcmp(string, "023711") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBatteryVoltageDiff = YES; }
+    if (strcmp(string, "023712") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoShiftPosition = YES; }
+    if (strcmp(string, "023713") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBatteryOtherFault = YES; }
+    if (strcmp(string, "023714") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoChargingSystemError = YES; }
+    if (strcmp(string, "023715") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoEvNormalStop = YES; }
+    if (strcmp(string, "023716") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoTempSensorBroken = YES; }
+    if (strcmp(string, "023717") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoConnectorLockFail = YES; }
+    if (strcmp(string, "023718") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoD1OnNoReceive = YES; }
+    if (strcmp(string, "023719") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBmsKtoJTimeout = YES; }
+    if (strcmp(string, "023720") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBmsChargeAllowTimeout = YES; }
+    if (strcmp(string, "023721") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoWaitGfdTimeout = YES; }
+    if (strcmp(string, "023722") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBmsEvRelayTimeout = YES; }
+    if (strcmp(string, "023723") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBmsReqCurrentTimeout = YES; }
+    if (strcmp(string, "023724") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBmsKtoJOffTimeout = YES; }
+    if (strcmp(string, "023725") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBmsEvRelayOffTimeout = YES; }
+    if (strcmp(string, "023726") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoAdcMoreThan10V = YES; }
+    if (strcmp(string, "023727") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoAdcMoreThan20V = YES; }
+    if (strcmp(string, "023728") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoBmsChargeBeforeStop = YES; }
+    if (strcmp(string, "023729") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoChargerGetNormalStop = YES; }
+    if (strcmp(string, "023730") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoChargerGetEmergencyStop = YES; }
+    if (strcmp(string, "023731") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoIsolationResultFail = YES; }
+    if (strcmp(string, "023732") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoMissLinkWithMotherBoard = YES; }
+    if (strcmp(string, "023733") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoOutputVolMoreThanLimit = YES; }
+    if (strcmp(string, "023734") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoReqCurrentMoreThanLimit = YES; }
+    if (strcmp(string, "023735") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoReCapBmsEqrCurrentExceed = YES; }
+    if (strcmp(string, "023736") == EQUAL) { pInfoCode->InfoEvents.bits.ChademoChargeRemainCountDown = YES; }
+    if (strcmp(string, "023980") == EQUAL) { pInfoCode->InfoEvents.bits.CHADEMO_BMS_CHARGE_ALLOW_ERROR = YES; }
+    if (strcmp(string, "023981") == EQUAL) { pInfoCode->InfoEvents.bits.CHADEMO_OUTPUT_VOLTAGE_MORE_THEN_10_PERCENT = YES; }
+    if (strcmp(string, "023982") == EQUAL) { pInfoCode->InfoEvents.bits.CHADEMO_ADC_LESS_THAN_10V = YES; }
+
+    if (strcmp(string, "012288") == EQUAL) { pAlarmCode->AlarmEvents.bits.CcsOutputUVPFail = YES; }
+    if (strcmp(string, "023701") == EQUAL) { pInfoCode->InfoEvents.bits.CcsEvCommFail = YES; }
+    if (strcmp(string, "023737") == EQUAL) { pInfoCode->InfoEvents.bits.CcsRESTemperatureInhibit = YES; }
+    if (strcmp(string, "023738") == EQUAL) { pInfoCode->InfoEvents.bits.CcsEVShiftPosition = YES; }
+    if (strcmp(string, "023739") == EQUAL) { pInfoCode->InfoEvents.bits.CcsChargerConnectorLockFault = YES; }
+    if (strcmp(string, "023740") == EQUAL) { pInfoCode->InfoEvents.bits.CcsEVRESSMalfunction = YES; }
+    if (strcmp(string, "023741") == EQUAL) { pInfoCode->InfoEvents.bits.CcsChargingCurrentdifferential = YES; }
+    if (strcmp(string, "023742") == EQUAL) { pInfoCode->InfoEvents.bits.CcsChargingVoltageOutOfRange = YES; }
+    if (strcmp(string, "023743") == EQUAL) { pInfoCode->InfoEvents.bits.CcsChargingSystemIncompatibility = YES; }
+    if (strcmp(string, "023744") == EQUAL) { pInfoCode->InfoEvents.bits.CcsEmergencyEvent = YES; }
+    if (strcmp(string, "023745") == EQUAL) { pInfoCode->InfoEvents.bits.CcsBreaker = YES; }
+    if (strcmp(string, "023746") == EQUAL) { pInfoCode->InfoEvents.bits.CcsNoData = YES; }
+    if (strcmp(string, "023747") == EQUAL) { pInfoCode->InfoEvents.bits.Ccsreserved_by_DIN_A = YES; }
+    if (strcmp(string, "023748") == EQUAL) { pInfoCode->InfoEvents.bits.Ccsreserved_by_DIN_B = YES; }
+    if (strcmp(string, "023749") == EQUAL) { pInfoCode->InfoEvents.bits.Ccsreserved_by_DIN_C = YES; }
+    if (strcmp(string, "023750") == EQUAL) { pInfoCode->InfoEvents.bits.Ccsreserved_by_ISO_1 = YES; }
+    if (strcmp(string, "023751") == EQUAL) { pInfoCode->InfoEvents.bits.Ccsreserved_by_ISO_2 = YES; }
+    if (strcmp(string, "023752") == EQUAL) { pInfoCode->InfoEvents.bits.Ccsreserved_by_ISO_3 = YES; }
+    if (strcmp(string, "023753") == EQUAL) { pInfoCode->InfoEvents.bits.Ccsreserved_by_OEM_1 = YES; }
+    if (strcmp(string, "023754") == EQUAL) { pInfoCode->InfoEvents.bits.Ccsreserved_by_OEM_2 = YES; }
+    if (strcmp(string, "023755") == EQUAL) { pInfoCode->InfoEvents.bits.Ccsreserved_by_OEM_3 = YES; }
+    if (strcmp(string, "023756") == EQUAL) { pInfoCode->InfoEvents.bits.Ccsreserved_by_OEM_4 = YES; }
+    if (strcmp(string, "023757") == EQUAL) { pInfoCode->InfoEvents.bits.Ccsreserved_by_OEM_5 = YES; }
+    if (strcmp(string, "023758") == EQUAL) { pInfoCode->InfoEvents.bits.CcsSequenceError = YES; }
+    if (strcmp(string, "023759") == EQUAL) { pInfoCode->InfoEvents.bits.CcsSignatureError = YES; }
+    if (strcmp(string, "023760") == EQUAL) { pInfoCode->InfoEvents.bits.CcsUnknownSession = YES; }
+    if (strcmp(string, "023761") == EQUAL) { pInfoCode->InfoEvents.bits.CcsServiceIDInvalid = YES; }
+    if (strcmp(string, "023762") == EQUAL) { pInfoCode->InfoEvents.bits.CcsPaymentSelectionInvalid = YES; }
+    if (strcmp(string, "023763") == EQUAL) { pInfoCode->InfoEvents.bits.CcsIdentificationSelectionInvalid = YES; }
+    if (strcmp(string, "023764") == EQUAL) { pInfoCode->InfoEvents.bits.CcsServiceSelectionInvalid = YES; }
+    if (strcmp(string, "023765") == EQUAL) { pInfoCode->InfoEvents.bits.CcsCertificateExpired = YES; }
+    if (strcmp(string, "023766") == EQUAL) { pInfoCode->InfoEvents.bits.CcsCertificateNotYetValid = YES; }
+    if (strcmp(string, "023767") == EQUAL) { pInfoCode->InfoEvents.bits.CcsCertificateRevoked = YES; }
+    if (strcmp(string, "023768") == EQUAL) { pInfoCode->InfoEvents.bits.CcsNoCertificateAvailable = YES; }
+    if (strcmp(string, "023769") == EQUAL) { pInfoCode->InfoEvents.bits.CcsCertChainError = YES; }
+    if (strcmp(string, "023770") == EQUAL) { pInfoCode->InfoEvents.bits.CcsCertValidationError = YES; }
+    if (strcmp(string, "023771") == EQUAL) { pInfoCode->InfoEvents.bits.CcsCertVerificationError = YES; }
+    if (strcmp(string, "023772") == EQUAL) { pInfoCode->InfoEvents.bits.CcsContractCanceled = YES; }
+    if (strcmp(string, "023773") == EQUAL) { pInfoCode->InfoEvents.bits.CcsChallengeInvalid = YES; }
+    if (strcmp(string, "023774") == EQUAL) { pInfoCode->InfoEvents.bits.CcsWrongEnergyTransferMode = YES; }
+    if (strcmp(string, "023775") == EQUAL) { pInfoCode->InfoEvents.bits.CcsWrongChargeParameter = YES; }
+    if (strcmp(string, "023776") == EQUAL) { pInfoCode->InfoEvents.bits.CcsChargingProfileInvalid = YES; }
+    if (strcmp(string, "023777") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTariffSelectionInvalid = YES; }
+    if (strcmp(string, "023778") == EQUAL) { pInfoCode->InfoEvents.bits.CcsEVSEPresentVoltageToLow = YES; }
+    if (strcmp(string, "023779") == EQUAL) { pInfoCode->InfoEvents.bits.CcsPowerDeliveryNotApplied = YES; }
+    if (strcmp(string, "023780") == EQUAL) { pInfoCode->InfoEvents.bits.CcsMeteringSignatureNotValid = YES; }
+    if (strcmp(string, "023781") == EQUAL) { pInfoCode->InfoEvents.bits.CcsNoChargeServiceSelected = YES; }
+    if (strcmp(string, "023782") == EQUAL) { pInfoCode->InfoEvents.bits.CcsContactorError = YES; }
+    if (strcmp(string, "023783") == EQUAL) { pInfoCode->InfoEvents.bits.CcsCertificateNotAllowedAtThisEVSE = YES; }
+    if (strcmp(string, "023784") == EQUAL) { pInfoCode->InfoEvents.bits.CcsGAChargeStop = YES; }
+    if (strcmp(string, "023785") == EQUAL) { pInfoCode->InfoEvents.bits.CcsAlignmentError = YES; }
+    if (strcmp(string, "023786") == EQUAL) { pInfoCode->InfoEvents.bits.CcsACDError = YES; }
+    if (strcmp(string, "023787") == EQUAL) { pInfoCode->InfoEvents.bits.CcsAssociationError = YES; }
+    if (strcmp(string, "023788") == EQUAL) { pInfoCode->InfoEvents.bits.CcsEVSEChargeAbort = YES; }
+    if (strcmp(string, "023789") == EQUAL) { pInfoCode->InfoEvents.bits.CcsNoSupportedAppProtocol = YES; }
+    if (strcmp(string, "023790") == EQUAL) { pInfoCode->InfoEvents.bits.CcsContractNotAccepted = YES; }
+    if (strcmp(string, "023791") == EQUAL) { pInfoCode->InfoEvents.bits.CcsMOUnknown = YES; }
+    if (strcmp(string, "023792") == EQUAL) { pInfoCode->InfoEvents.bits.CcsOEM_Prov_CertificateRevoke = YES; }
+    if (strcmp(string, "023793") == EQUAL) { pInfoCode->InfoEvents.bits.CcsOEM_SubCA1_CertificateRevoked = YES; }
+    if (strcmp(string, "023794") == EQUAL) { pInfoCode->InfoEvents.bits.CcsOEM_SubCA2_CertificateRevoked = YES; }
+    if (strcmp(string, "023795") == EQUAL) { pInfoCode->InfoEvents.bits.CcsOEM_RootCA_CertificateRevoked = YES; }
+    if (strcmp(string, "023796") == EQUAL) { pInfoCode->InfoEvents.bits.CcsMO_Prov_CertificateRevoked = YES; }
+    if (strcmp(string, "023797") == EQUAL) { pInfoCode->InfoEvents.bits.CcsMO_SubCA1_CertificateRevoked = YES; }
+    if (strcmp(string, "023798") == EQUAL) { pInfoCode->InfoEvents.bits.CcsMO_SubCA2_CertificateRevoked = YES; }
+    if (strcmp(string, "023799") == EQUAL) { pInfoCode->InfoEvents.bits.CcsMO_RootCA_CertificateRevoked = YES; }
+    if (strcmp(string, "023800") == EQUAL) { pInfoCode->InfoEvents.bits.CcsCPS_Prov_CertificateRevoked = YES; }
+    if (strcmp(string, "023801") == EQUAL) { pInfoCode->InfoEvents.bits.CcsCPS_SubCA1_CertificateRevoked = YES; }
+    if (strcmp(string, "023802") == EQUAL) { pInfoCode->InfoEvents.bits.CcsCPS_SubCA2_CertificateRevoked = YES; }
+    if (strcmp(string, "023803") == EQUAL) { pInfoCode->InfoEvents.bits.CcsCPS_RootCA_CertificateRevoked = YES; }
+    if (strcmp(string, "023809") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_EVSE_SLAC_init = YES; }
+    if (strcmp(string, "023810") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_match_response = YES; }
+    if (strcmp(string, "023811") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_match_sequence = YES; }
+    if (strcmp(string, "023812") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_EVSE_match_MNBC = YES; }
+    if (strcmp(string, "023813") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_EVSE_avg_atten_calc = YES; }
+    if (strcmp(string, "023814") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_match_response = YES; }
+    if (strcmp(string, "023815") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_EVSE_match_session = YES; }
+    if (strcmp(string, "023816") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_EVSE_assoc_session = YES; }
+    if (strcmp(string, "023817") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_EVSE_vald_toggle = YES; }
+    if (strcmp(string, "023818") == EQUAL) { pInfoCode->InfoEvents.bits.CcsSeccSlacTimeoutCmMnbcSound = YES; }
+    if (strcmp(string, "023819") == EQUAL) { pInfoCode->InfoEvents.bits.CcsSeccSlacTimeoutCmValidateReq = YES; }
+    if (strcmp(string, "023823") == EQUAL) { pInfoCode->InfoEvents.bits.CcsUDP_TT_match_join = YES; }
+    if (strcmp(string, "023824") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTCP_TT_match_join = YES; }
+    if (strcmp(string, "023825") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_amp_map_exchange = YES; }
+    if (strcmp(string, "023826") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_link_ready_notification = YES; }
+    if (strcmp(string, "023832") == EQUAL) { pInfoCode->InfoEvents.bits.CcsSupportedAppProtocolRes = YES; }
+    if (strcmp(string, "023833") == EQUAL) { pInfoCode->InfoEvents.bits.CcsSessionSetupRes = YES; }
+    if (strcmp(string, "023834") == EQUAL) { pInfoCode->InfoEvents.bits.CcsServiceDiscoveryRes = YES; }
+    if (strcmp(string, "023835") == EQUAL) { pInfoCode->InfoEvents.bits.CcsServicePaymentSelectionRes = YES; }
+    if (strcmp(string, "023836") == EQUAL) { pInfoCode->InfoEvents.bits.CcsContractAuthenticationRes = YES; }
+    if (strcmp(string, "023837") == EQUAL) { pInfoCode->InfoEvents.bits.CcsChargeParameterDiscoveryRes = YES; }
+    if (strcmp(string, "023838") == EQUAL) { pInfoCode->InfoEvents.bits.CcsPowerDeliveryRes = YES; }
+    if (strcmp(string, "023839") == EQUAL) { pInfoCode->InfoEvents.bits.CcsCableCheckRes = YES; }
+    if (strcmp(string, "023840") == EQUAL) { pInfoCode->InfoEvents.bits.CcsPreChargeRes = YES; }
+    if (strcmp(string, "023841") == EQUAL) { pInfoCode->InfoEvents.bits.CcsCurrentDemandRes = YES; }
+    if (strcmp(string, "023842") == EQUAL) { pInfoCode->InfoEvents.bits.CcsWeldingDetectionRes = YES; }
+    if (strcmp(string, "023843") == EQUAL) { pInfoCode->InfoEvents.bits.CcsSessionStopRes = YES; }
+    if (strcmp(string, "023844") == EQUAL) { pInfoCode->InfoEvents.bits.CcsSequence_Time = YES; }
+    if (strcmp(string, "023845") == EQUAL) { pInfoCode->InfoEvents.bits.CcsReadyToCharge_Performance_Time = YES; }
+    if (strcmp(string, "023846") == EQUAL) { pInfoCode->InfoEvents.bits.CcsCommunicationSetup_Performance_Time = YES; }
+    if (strcmp(string, "023847") == EQUAL) { pInfoCode->InfoEvents.bits.CcsCableCheck_Performance_Time = YES; }
+    if (strcmp(string, "023848") == EQUAL) { pInfoCode->InfoEvents.bits.CcsCPState_Detection_Time = YES; }
+    if (strcmp(string, "023849") == EQUAL) { pInfoCode->InfoEvents.bits.CcsCPOscillator_Retain_Time = YES; }
+    if (strcmp(string, "023850") == EQUAL) { pInfoCode->InfoEvents.bits.CcsSeccTimeoutV2GPreChargePerformaceTime = YES; }
+    if (strcmp(string, "023855") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_GET_EV_TARGET_INFO = YES; }
+    if (strcmp(string, "023856") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_GET_EV_TARGET_INFO = YES; }
+    if (strcmp(string, "023857") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_GET_EV_BATTERY_INFO = YES; }
+    if (strcmp(string, "023858") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_GET_EV_BATTERY_INFO = YES; }
+    if (strcmp(string, "023859") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_EV_STOP_EVENT = YES; }
+    if (strcmp(string, "023860") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_EV_STOP_EVENT = YES; }
+    if (strcmp(string, "023861") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_EVSE_STOP_EVENT = YES; }
+    if (strcmp(string, "023862") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_EVSE_STOP_EVENT = YES; }
+    if (strcmp(string, "023863") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_GET_MISC_INFO = YES; }
+    if (strcmp(string, "023864") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_GET_MISC_INFO = YES; }
+    if (strcmp(string, "023865") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_DOWNLOAD_REQUEST = YES; }
+    if (strcmp(string, "023866") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_DOWNLOAD_REQUEST = YES; }
+    if (strcmp(string, "023867") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_START_BLOCK_TRANSFER = YES; }
+    if (strcmp(string, "023868") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_START_BLOCK_TRANSFER = YES; }
+    if (strcmp(string, "023869") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_DATA_TRANSFER = YES; }
+    if (strcmp(string, "023870") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_DATA_TRANSFER = YES; }
+    if (strcmp(string, "023871") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_DOWNLOAD_FINISH = YES; }
+    if (strcmp(string, "023872") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_DOWNLOAD_FINISH = YES; }
+    if (strcmp(string, "023873") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_ISOLATION_STATUS = YES; }
+    if (strcmp(string, "023874") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_ISOLATION_STATUS = YES; }
+    if (strcmp(string, "023875") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_CONNECTOR_INFO = YES; }
+    if (strcmp(string, "023876") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_CONNECTOR_INFO = YES; }
+    if (strcmp(string, "023877") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_RTC_INFO = YES; }
+    if (strcmp(string, "023878") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_RTC_INFO = YES; }
+    if (strcmp(string, "023879") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTP_EVSE_PRECHARGE_INFO = YES; }
+    if (strcmp(string, "023880") == EQUAL) { pInfoCode->InfoEvents.bits.CcsTT_EVSE_PRECHARGE_INFO = YES; }
+    if (strcmp(string, "023881") == EQUAL) { pInfoCode->InfoEvents.bits.CcsMSG_Sequence = YES; }
+    if (strcmp(string, "023882") == EQUAL) { pInfoCode->InfoEvents.bits.CcsCAN_MSG_Unrecognized_CMD_ID = YES; }
+    if (strcmp(string, "023883") == EQUAL) { pInfoCode->InfoEvents.bits.CcsDIN_Msg_Decode_Error = YES; }
+    if (strcmp(string, "023884") == EQUAL) { pInfoCode->InfoEvents.bits.CcsDIN_Msg_Encode_Error = YES; }
+    if (strcmp(string, "023885") == EQUAL) { pInfoCode->InfoEvents.bits.CcsISO1_Msg_Decode_Error = YES; }
+    if (strcmp(string, "023886") == EQUAL) { pInfoCode->InfoEvents.bits.CcsISO1_Msg_Encode_Error = YES; }
+    if (strcmp(string, "023887") == EQUAL) { pInfoCode->InfoEvents.bits.CcsISO2_Msg_Decode_Error = YES; }
+    if (strcmp(string, "023888") == EQUAL) { pInfoCode->InfoEvents.bits.CcsISO2_Msg_Encode_Error = YES; }
+    if (strcmp(string, "023889") == EQUAL) { pInfoCode->InfoEvents.bits.CcsCpStatus_Error = YES; }
+    if (strcmp(string, "023890") == EQUAL) { pInfoCode->InfoEvents.bits.CcsUnexpectVolBeforeCharing_Error = YES; }
+    if (strcmp(string, "023891") == EQUAL) { pInfoCode->InfoEvents.bits.CcsSeccNotReadyForCharging = YES; }
+    if (strcmp(string, "023892") == EQUAL) { pInfoCode->InfoEvents.bits.CcsSeccTimeoutQCA7000Comm = YES; }
+    if (strcmp(string, "023893") == EQUAL) { pInfoCode->InfoEvents.bits.CcsSeccFailForQCA7000SetKey = YES; }
+    if (strcmp(string, "023979") == EQUAL) { pInfoCode->InfoEvents.bits.EV_Full_Charging = YES; }
+    if (strcmp(string, "023983") == EQUAL) { pInfoCode->InfoEvents.bits.Stop_by_EV_with_unknow_reason = YES; }
+
+    if (strcmp(string, "023702") == EQUAL) { pInfoCode->InfoEvents.bits.GbEvCommFail = YES; }
+    if (strcmp(string, "023900") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_LOS_CC1 = YES; }
+    if (strcmp(string, "023901") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_CONNECTOR_LOCK_FAIL = YES; }
+    if (strcmp(string, "023902") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_BATTERY_INCOMPATIBLE = YES; }
+    if (strcmp(string, "023903") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_BMS_BROAA_TIMEOUT = YES; }
+    if (strcmp(string, "023904") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_CSU_PRECHARGE_TIMEOUT = YES; }
+    if (strcmp(string, "023905") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_BMS_PRESENT_VOLTAGE_FAULT = YES; }
+    if (strcmp(string, "023906") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_BMS_VOLTAGE_OVER_RANGE = YES; }
+    if (strcmp(string, "023907") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_BSM_CHARGE_ALLOW_00_10MIN_COUUNTDONE = YES; }
+    if (strcmp(string, "023908") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_WAIT_GROUNDFAULT_TIMEOUT = YES; }
+    if (strcmp(string, "023909") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_ADC_MORE_THAN_10V = YES; }
+    if (strcmp(string, "023910") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_ADC_MORE_THAN_60V = YES; }
+    if (strcmp(string, "023911") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_CHARGER_GET_NORMAL_STOP_CMD = YES; }
+    if (strcmp(string, "023912") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_CHARGER_GET_EMERGENCY_STOP_CMD = YES; }
+    if (strcmp(string, "023913") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_ISOLATION_RESULT_FAIL = YES; }
+    if (strcmp(string, "023914") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_MOTHER_BOARD_MISS_LINK = YES; }
+    if (strcmp(string, "023915") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_OUTPUT_VOLTAGE_MORE_THAN_LIMIT = YES; }
+    if (strcmp(string, "023916") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_REQ_CURRENT_MORE_THAN_LIMIT = YES; }
+    if (strcmp(string, "023917") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_OUTPUT_VOLTAGE_MORE_THAN_10_PERCENT = YES; }
+    if (strcmp(string, "023918") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_OUTPUT_VOLTAGE_DIFF_BCS_5_PERCENT = YES; }
+    if (strcmp(string, "023919") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GBT_STOP_ADC_MORE_THAN_10V = YES; }
+    if (strcmp(string, "023930") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BHM_TIMEOUT = YES; }
+    if (strcmp(string, "023931") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BRM_TIMEOUT = YES; }
+    if (strcmp(string, "023932") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BCP_TIMEOUT = YES; }
+    if (strcmp(string, "023933") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BRO_TIMEOUT = YES; }
+    if (strcmp(string, "023934") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BCL_TIMEOUT = YES; }
+    if (strcmp(string, "023935") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BCS_TIMEOUT = YES; }
+    if (strcmp(string, "023936") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BSM_TIMEOUT = YES; }
+    if (strcmp(string, "023937") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BST_TIMEOUT = YES; }
+    if (strcmp(string, "023938") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BSD_TIMEOUT = YES; }
+    if (strcmp(string, "023939") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_CEM_BEM_OTHER_TIMEOUT = YES; }
+    if (strcmp(string, "023940") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BEM_CRM_TIMEOUT = YES; }
+    if (strcmp(string, "023941") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BEM_CRMAA_TIMEOUT = YES; }
+    if (strcmp(string, "023942") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BEM_CTS_CML_TIMEOUT = YES; }
+    if (strcmp(string, "023943") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BEM_CRO_TIMEOUT = YES; }
+    if (strcmp(string, "023944") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BEM_CCS_TIMEOUT = YES; }
+    if (strcmp(string, "023945") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BEM_CST_TIMEOUT = YES; }
+    if (strcmp(string, "023946") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BEM_CSD_TIMEOUT = YES; }
+    if (strcmp(string, "023947") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BEM_BEM_OTHER_TIMEOUT = YES; }
+    if (strcmp(string, "023950") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_SOC_GOAL = YES; }
+    if (strcmp(string, "023951") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_TOTAL_VOLTAGE_GOAL = YES; }
+    if (strcmp(string, "023952") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_CELL_VOLTAGE_GOAL = YES; }
+    if (strcmp(string, "023953") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_GET_CST = YES; }
+    if (strcmp(string, "023954") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_ISOLATION = YES; }
+    if (strcmp(string, "023955") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_OUTPUT_CONNECTOR_OTP = YES; }
+    if (strcmp(string, "023956") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_COMPONENT = YES; }
+    if (strcmp(string, "023957") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_CHARGE_CONNECTOR = YES; }
+    if (strcmp(string, "023958") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_OTP = YES; }
+    if (strcmp(string, "023959") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_OTHER = YES; }
+    if (strcmp(string, "023960") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_HIGH_V = YES; }
+    if (strcmp(string, "023961") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_CC2 = YES; }
+    if (strcmp(string, "023962") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_CURRENT = YES; }
+    if (strcmp(string, "023963") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BST_VOLTAGE = YES; }
+    if (strcmp(string, "023964") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_GET_BST_NO_REASON = YES; }
+    if (strcmp(string, "023970") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BSM_CELL_OVER_VOLTAGE = YES; }
+    if (strcmp(string, "023971") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BSM_CELL_UNDER_VOLTAGE = YES; }
+    if (strcmp(string, "023972") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BSM_OVER_SOC = YES; }
+    if (strcmp(string, "023973") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BSM_UNDER_SOC = YES; }
+    if (strcmp(string, "023974") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BSM_CURRENT = YES; }
+    if (strcmp(string, "023975") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BSM_TEMPERATURE = YES; }
+    if (strcmp(string, "023976") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BSM_ISOLATE = YES; }
+    if (strcmp(string, "023977") == EQUAL) { pInfoCode->InfoEvents.bits.ERROR_CODE_BSM_OUTPUT_CONNECTOR = YES; }
+
+    return true;
+}

+ 205 - 205
EVSE/Projects/DD360Tcci/Apps/ModuleEvComm/Ev_Comm.c

@@ -1,205 +1,205 @@
-#include <stdio.h>      /*標準輸入輸出定義*/
-#include <stdlib.h>     /*標準函數庫定義*/
-#include <stdint.h>
-#include <string.h>
-
-#include <linux/can.h>
-#include <linux/can/raw.h>
-
-#include <unistd.h>     /*Unix 標準函數定義*/
-#include <fcntl.h>      /*檔控制定義*/
-#include <termios.h>    /*PPSIX 終端控制定義*/
-#include <errno.h>      /*錯誤號定義*/
-
-#include "Ev_Comm.h"
-#include "Module_EvComm.h"
-
-//------------------------------------------------------------------------------
-int PackageIdCmd(int cmd)
-{
-    return cmd | 0x80000000;
-}
-
-void SendCmdToEvboard(int cmd, uint8_t *data, uint8_t dataLen)
-{
-    int fd = GetCanFd();
-    struct can_frame frame;
-
-    frame.can_id = cmd;
-    frame.can_dlc = dataLen;
-    memcpy(frame.data, data, sizeof(frame.data));
-
-    write(fd, &frame, sizeof(struct can_frame));
-}
-
-//------------------------------------------------------------------------------
-void SetTargetAddr(uint8_t *target_number, uint8_t index)
-{
-    int id = PackageIdCmd(CMD_ADDR_ASSIGNMENT + index);
-    //printf("intCmd = %x \n", cmd & CAN_EFF_MASK);
-    //cmd = cmd & CAN_EFF_MASK;
-
-    uint8_t data[8];
-
-    data[0] = *target_number;
-    data[1] = *(target_number + 1);
-    data[2] = *(target_number + 2);
-    data[3] = *(target_number + 3);
-    data[4] = index;
-
-    SendCmdToEvboard(id, data, 5);
-}
-
-void GetFirmwareVersion(uint8_t gunIndex, uint8_t toId)
-{
-    int id = PackageIdCmd(CMD_GET_FW_VER + toId);
-    uint8_t data[8];
-
-    SendCmdToEvboard(id, data, 0);
-}
-
-void GetHardwareVersion(uint8_t gunIndex, uint8_t toId)
-{
-    int id = PackageIdCmd(CMD_GET_HW_VER + toId);
-    uint8_t data[8];
-
-    SendCmdToEvboard(id, data, 0);
-}
-
-void SyncRtcInfo(uint8_t gunIndex, uint8_t toId, int epoch)
-{
-    int id = PackageIdCmd(CMD_SYNC_RTC + toId);
-    uint8_t data[8];
-
-    data[0] = epoch & 0xff;
-    data[1] = (epoch >> 8) & 0xff;
-    data[2] = (epoch >> 16) & 0xff;
-    data[3] = (epoch >> 24) & 0xff;
-
-    SendCmdToEvboard(id, data, 4);
-}
-
-void SetChargingPermission(uint8_t gunIndex, uint8_t permissionStatus, uint16_t aOutputPw, uint16_t aOutputCur, uint16_t aOutputVol, uint8_t toId)
-{
-    int id = PackageIdCmd(CMD_CHARGING_PERMISSION + toId);
-    uint8_t data[8];
-
-    data[0] = permissionStatus;
-    data[1] = aOutputPw & 0xff;
-    data[2] = (aOutputPw >> 8) & 0xff;
-    data[3] = aOutputCur & 0xff;
-    data[4] = (aOutputCur >> 8) & 0xff;
-    data[5] = aOutputVol & 0xff;
-    data[6] = (aOutputVol >> 8) & 0xff;
-    data[7] = 0xf0;
-
-    SendCmdToEvboard(id, data, sizeof(data));
-}
-
-void SetPresentOutputPower(uint16_t outputVol_b1, uint16_t outputCur_b1, uint16_t outputVol_b2, uint16_t outputCur_b2)
-{
-    int id = PackageIdCmd(CMD_PRESENT_OUTPUT_POWER);
-    uint8_t data[8];
-
-    data[0] = outputVol_b1 & 0xff;
-    data[1] = (outputVol_b1 >> 8) & 0xff;
-    data[2] = outputCur_b1 & 0xff;
-    data[3] = (outputCur_b1 >> 8) & 0xff;
-    data[4] = outputVol_b2 & 0xff;
-    data[5] = (outputVol_b2 >> 8) & 0xff;
-    data[6] = outputCur_b2 & 0xff;
-    data[7] = (outputCur_b2 >> 8) & 0xff;
-
-    SendCmdToEvboard(id, data, 8);
-}
-
-void SetPresentOutputCapacity(uint16_t aOutputPw_b1, uint16_t aOutputCur_b1, uint16_t aOutputPw_b2, uint16_t aOutputCur_b2)
-{
-    int id = PackageIdCmd(CMD_PRESENT_OUTPUT_CAPABILITIES);
-    uint8_t data[8];
-
-    data[0] = aOutputPw_b1 & 0xff;
-    data[1] = (aOutputPw_b1 >> 8) & 0xff;
-    data[2] = aOutputCur_b1 & 0xff;
-    data[3] = (aOutputCur_b1 >> 8) & 0xff;
-    data[4] = aOutputPw_b2 & 0xff;
-    data[5] = (aOutputPw_b2 >> 8) & 0xff;
-    data[6] = aOutputCur_b2 & 0xff;
-    data[7] = (aOutputCur_b2 >> 8) & 0xff;
-
-    SendCmdToEvboard(id, data, 8);
-}
-
-void GetOutputReq(uint8_t gunIndex, uint8_t toId)
-{
-    int id = PackageIdCmd(CMD_GET_OUTPUT_REQ + toId);
-    uint8_t data[8];
-
-    SendCmdToEvboard(id, data, 0);
-}
-
-void GetEvBatteryInfo(uint8_t gunIndex, uint8_t toId)
-{
-    int id = PackageIdCmd(CMD_GET_BATTERY_INFO + toId);
-    uint8_t data[8];
-
-    SendCmdToEvboard(id, data, 0);
-}
-
-void EvseStopChargingEvent(uint8_t stopResult, uint8_t *stopReason, uint8_t toId)
-{
-    int id = PackageIdCmd(CMD_EVSE_STOP_CHARGING + toId);
-    uint8_t data[8];
-
-    data[0] = stopResult;
-    data[1] = *stopReason;
-    data[2] = *(stopReason + 1);
-    data[3] = *(stopReason + 2);
-    data[4] = *(stopReason + 3);
-    data[5] = *(stopReason + 4);
-    data[6] = *(stopReason + 5);
-
-    SendCmdToEvboard(id, data, 7);
-}
-
-void GetMiscellaneousInfo(uint8_t gunIndex, uint8_t relayStatus, float power, float voltage, uint8_t toId)
-{
-    int id = PackageIdCmd(CMD_GET_MISC_INFO + toId);
-    uint8_t data[8];
-
-    int _power = power * 10;
-
-    data[0] = relayStatus;
-    data[1] = (int)_power & 0xff;
-    data[2] = ((int)_power >> 8) & 0xff;
-    data[3] = (int)voltage & 0xff;
-    data[4] = ((int)voltage >> 8) & 0xff;
-
-    SendCmdToEvboard(id, data, 5);
-}
-
-void SetIsolationStatus(uint8_t gunIndex, uint8_t result, uint8_t toId)
-{
-    int id = PackageIdCmd(CMD_ISOLATION_STATUS + toId);
-    uint8_t data[8];
-
-    data[0] = result;
-    SendCmdToEvboard(id, data, 1);
-}
-
-void SetEvsePrechargeInfo(uint8_t gunIndex, uint8_t result, uint8_t toId)
-{
-    int id = PackageIdCmd(CMD_EVSE_PRECHARGE + toId);
-    uint8_t data[8];
-
-    data[0] = result;
-    SendCmdToEvboard(id, data, 1);
-}
-
-void GetEVCCIDReq(uint8_t gunIndex, uint8_t toId)
-{
-    int id = PackageIdCmd(CMD_EVCCID_REQ + toId);
-    uint8_t data[8];
-
-    SendCmdToEvboard(id, data, 0);
-}
+#include <stdio.h>      /*標準輸入輸出定義*/
+#include <stdlib.h>     /*標準函數庫定義*/
+#include <stdint.h>
+#include <string.h>
+
+#include <linux/can.h>
+#include <linux/can/raw.h>
+
+#include <unistd.h>     /*Unix 標準函數定義*/
+#include <fcntl.h>      /*檔控制定義*/
+#include <termios.h>    /*PPSIX 終端控制定義*/
+#include <errno.h>      /*錯誤號定義*/
+
+#include "Ev_Comm.h"
+#include "Module_EvComm.h"
+
+//------------------------------------------------------------------------------
+int PackageIdCmd(int cmd)
+{
+    return cmd | 0x80000000;
+}
+
+void SendCmdToEvboard(int cmd, uint8_t *data, uint8_t dataLen)
+{
+    int fd = GetCanFd();
+    struct can_frame frame;
+
+    frame.can_id = cmd;
+    frame.can_dlc = dataLen;
+    memcpy(frame.data, data, sizeof(frame.data));
+
+    write(fd, &frame, sizeof(struct can_frame));
+}
+
+//------------------------------------------------------------------------------
+void SetTargetAddr(uint8_t *target_number, uint8_t index)
+{
+    int id = PackageIdCmd(CMD_ADDR_ASSIGNMENT + index);
+    //printf("intCmd = %x \n", cmd & CAN_EFF_MASK);
+    //cmd = cmd & CAN_EFF_MASK;
+
+    uint8_t data[8];
+
+    data[0] = *target_number;
+    data[1] = *(target_number + 1);
+    data[2] = *(target_number + 2);
+    data[3] = *(target_number + 3);
+    data[4] = index;
+
+    SendCmdToEvboard(id, data, 5);
+}
+
+void GetFirmwareVersion(uint8_t gunIndex, uint8_t toId)
+{
+    int id = PackageIdCmd(CMD_GET_FW_VER + toId);
+    uint8_t data[8];
+
+    SendCmdToEvboard(id, data, 0);
+}
+
+void GetHardwareVersion(uint8_t gunIndex, uint8_t toId)
+{
+    int id = PackageIdCmd(CMD_GET_HW_VER + toId);
+    uint8_t data[8];
+
+    SendCmdToEvboard(id, data, 0);
+}
+
+void SyncRtcInfo(uint8_t gunIndex, uint8_t toId, int epoch)
+{
+    int id = PackageIdCmd(CMD_SYNC_RTC + toId);
+    uint8_t data[8];
+
+    data[0] = epoch & 0xff;
+    data[1] = (epoch >> 8) & 0xff;
+    data[2] = (epoch >> 16) & 0xff;
+    data[3] = (epoch >> 24) & 0xff;
+
+    SendCmdToEvboard(id, data, 4);
+}
+
+void SetChargingPermission(uint8_t gunIndex, uint8_t permissionStatus, uint16_t aOutputPw, uint16_t aOutputCur, uint16_t aOutputVol, uint8_t toId)
+{
+    int id = PackageIdCmd(CMD_CHARGING_PERMISSION + toId);
+    uint8_t data[8];
+
+    data[0] = permissionStatus;
+    data[1] = aOutputPw & 0xff;
+    data[2] = (aOutputPw >> 8) & 0xff;
+    data[3] = aOutputCur & 0xff;
+    data[4] = (aOutputCur >> 8) & 0xff;
+    data[5] = aOutputVol & 0xff;
+    data[6] = (aOutputVol >> 8) & 0xff;
+    data[7] = 0xf0;
+
+    SendCmdToEvboard(id, data, sizeof(data));
+}
+
+void SetPresentOutputPower(uint16_t outputVol_b1, uint16_t outputCur_b1, uint16_t outputVol_b2, uint16_t outputCur_b2)
+{
+    int id = PackageIdCmd(CMD_PRESENT_OUTPUT_POWER);
+    uint8_t data[8];
+
+    data[0] = outputVol_b1 & 0xff;
+    data[1] = (outputVol_b1 >> 8) & 0xff;
+    data[2] = outputCur_b1 & 0xff;
+    data[3] = (outputCur_b1 >> 8) & 0xff;
+    data[4] = outputVol_b2 & 0xff;
+    data[5] = (outputVol_b2 >> 8) & 0xff;
+    data[6] = outputCur_b2 & 0xff;
+    data[7] = (outputCur_b2 >> 8) & 0xff;
+
+    SendCmdToEvboard(id, data, 8);
+}
+
+void SetPresentOutputCapacity(uint16_t aOutputPw_b1, uint16_t aOutputCur_b1, uint16_t aOutputPw_b2, uint16_t aOutputCur_b2)
+{
+    int id = PackageIdCmd(CMD_PRESENT_OUTPUT_CAPABILITIES);
+    uint8_t data[8];
+
+    data[0] = aOutputPw_b1 & 0xff;
+    data[1] = (aOutputPw_b1 >> 8) & 0xff;
+    data[2] = aOutputCur_b1 & 0xff;
+    data[3] = (aOutputCur_b1 >> 8) & 0xff;
+    data[4] = aOutputPw_b2 & 0xff;
+    data[5] = (aOutputPw_b2 >> 8) & 0xff;
+    data[6] = aOutputCur_b2 & 0xff;
+    data[7] = (aOutputCur_b2 >> 8) & 0xff;
+
+    SendCmdToEvboard(id, data, 8);
+}
+
+void GetOutputReq(uint8_t gunIndex, uint8_t toId)
+{
+    int id = PackageIdCmd(CMD_GET_OUTPUT_REQ + toId);
+    uint8_t data[8];
+
+    SendCmdToEvboard(id, data, 0);
+}
+
+void GetEvBatteryInfo(uint8_t gunIndex, uint8_t toId)
+{
+    int id = PackageIdCmd(CMD_GET_BATTERY_INFO + toId);
+    uint8_t data[8];
+
+    SendCmdToEvboard(id, data, 0);
+}
+
+void EvseStopChargingEvent(uint8_t stopResult, uint8_t *stopReason, uint8_t toId)
+{
+    int id = PackageIdCmd(CMD_EVSE_STOP_CHARGING + toId);
+    uint8_t data[8];
+
+    data[0] = stopResult;
+    data[1] = *stopReason;
+    data[2] = *(stopReason + 1);
+    data[3] = *(stopReason + 2);
+    data[4] = *(stopReason + 3);
+    data[5] = *(stopReason + 4);
+    data[6] = *(stopReason + 5);
+
+    SendCmdToEvboard(id, data, 7);
+}
+
+void GetMiscellaneousInfo(uint8_t gunIndex, uint8_t relayStatus, float power, float voltage, uint8_t toId)
+{
+    int id = PackageIdCmd(CMD_GET_MISC_INFO + toId);
+    uint8_t data[8];
+
+    int _power = power * 10;
+
+    data[0] = relayStatus;
+    data[1] = (int)_power & 0xff;
+    data[2] = ((int)_power >> 8) & 0xff;
+    data[3] = (int)voltage & 0xff;
+    data[4] = ((int)voltage >> 8) & 0xff;
+
+    SendCmdToEvboard(id, data, 5);
+}
+
+void SetIsolationStatus(uint8_t gunIndex, uint8_t result, uint8_t toId)
+{
+    int id = PackageIdCmd(CMD_ISOLATION_STATUS + toId);
+    uint8_t data[8];
+
+    data[0] = result;
+    SendCmdToEvboard(id, data, 1);
+}
+
+void SetEvsePrechargeInfo(uint8_t gunIndex, uint8_t result, uint8_t toId)
+{
+    int id = PackageIdCmd(CMD_EVSE_PRECHARGE + toId);
+    uint8_t data[8];
+
+    data[0] = result;
+    SendCmdToEvboard(id, data, 1);
+}
+
+void GetEVCCIDReq(uint8_t gunIndex, uint8_t toId)
+{
+    int id = PackageIdCmd(CMD_EVCCID_REQ + toId);
+    uint8_t data[8];
+
+    SendCmdToEvboard(id, data, 0);
+}

+ 66 - 66
EVSE/Projects/DD360Tcci/Apps/ModuleEvComm/Ev_Comm.h

@@ -1,66 +1,66 @@
-#ifndef _EV_COMM_H_
-#define _EV_COMM_H_
-
-#include <stdbool.h>
-#include <stdint.h>
-
-//------------------------------------------------------------------------------
-//EV command address
-//------------------------------------------------------------------------------
-#define CMD_NONE                                (0)
-#define CMD_ADDR_ASSIGNMENT                     (0x00000200)
-#define CMD_GET_FW_VER                          (0x00000400)
-#define CMD_GET_HW_VER                          (0x00000500)
-#define CMD_CHARGING_PERMISSION                 (0x00000600)
-#define CMD_PRESENT_OUTPUT_POWER                (0x00000700)
-#define CMD_PRESENT_OUTPUT_CAPABILITIES         (0x00000800)
-#define CMD_GET_OUTPUT_REQ                      (0x00000900)
-#define CMD_GET_BATTERY_INFO                    (0x00000A00)
-#define CMD_EVSE_STOP_CHARGING                  (0x00000C00)
-#define CMD_GET_MISC_INFO                       (0x00000D00)
-
-#define CMD_DOWNLOAD_REQ                        (0x00000E00)
-#define CMD_START_BLOCK_TRANS                   (0x00000F00)
-#define CMD_DATA_TRANS                          (0x00001000)
-#define CMD_DOWNLOAD_FINISH                     (0x00001100)
-
-#define CMD_ISOLATION_STATUS                    (0x00001200)
-#define CMD_SYNC_RTC                            (0x00001400)
-#define CMD_EVSE_PRECHARGE                      (0x00001500)
-#define CMD_EVCCID_REQ                          (0x00001600)
-
-// 車端主動
-#define ADDRESS_REQ                             (0x080001FF)
-#define NOTIFICATION_EV_STATUS                  (0x08000300)
-#define NOTIFICATION_EV_STOP                    (0x08000B00)
-
-// 車端回應
-#define ACK_EV_FW_VERSION                       (0x08000400)
-#define ACK_EV_HW_VERSION                       (0x08000500)
-#define ACK_GET_OUTPUT_REQ                      (0x08000900)
-#define ACK_GET_EV_BATTERY_INFO                 (0x08000A00)
-#define ACK_GET_MISCELLANEOUS_INFO              (0x08000D00)
-#define ACK_EVSE_ISOLATION_STATUS               (0x08001200)
-#define ACK_EVSE_PRECHAGE_INFO                  (0x08001500)
-#define ACK_EVCCID_REQ                          (0x08001600)
-
-//------------------------------------------------------------------------------
-// Send msg to can-bus
-void SetTargetAddr(uint8_t *target_number, uint8_t index);
-
-void GetFirmwareVersion(uint8_t gunIndex, uint8_t toId);
-void GetHardwareVersion(uint8_t gunIndex, uint8_t toId);
-void SyncRtcInfo(uint8_t gunIndex, uint8_t toId, int epoch);
-void SetChargingPermission(uint8_t gunIndex, uint8_t permissionStatus, uint16_t aOutputPw, uint16_t aOutputVol, uint16_t aOutputCur, uint8_t toId);
-void SetPresentOutputPower(uint16_t outputVol_b1, uint16_t outputCur_b1, uint16_t outputVol_b2, uint16_t outputCur_b2);
-void SetPresentOutputCapacity(uint16_t aOutputPw_b1, uint16_t aOutputCur_b1, uint16_t aOutputPw_b2, uint16_t aOutputCur_b2);
-void GetOutputReq(uint8_t gunIndex, uint8_t toId);
-void GetEvBatteryInfo(uint8_t gunIndex, uint8_t toId);
-void GetMiscellaneousInfo(uint8_t gunIndex, uint8_t relayStatus, float power, float voltage, uint8_t toId);
-void SetIsolationStatus(uint8_t gunIndex, uint8_t result, uint8_t toId);
-void SetEvsePrechargeInfo(uint8_t gunIndex, uint8_t result, uint8_t toId);
-// 發送電樁主動停止充電結果及原因
-void EvseStopChargingEvent(uint8_t stopResult, uint8_t *stopReason, uint8_t toId);
-void GetEVCCIDReq(uint8_t gunIndex, uint8_t toId);
-
-#endif /* _EV_COMM_H_ */
+#ifndef _EV_COMM_H_
+#define _EV_COMM_H_
+
+#include <stdbool.h>
+#include <stdint.h>
+
+//------------------------------------------------------------------------------
+//EV command address
+//------------------------------------------------------------------------------
+#define CMD_NONE                                (0)
+#define CMD_ADDR_ASSIGNMENT                     (0x00000200)
+#define CMD_GET_FW_VER                          (0x00000400)
+#define CMD_GET_HW_VER                          (0x00000500)
+#define CMD_CHARGING_PERMISSION                 (0x00000600)
+#define CMD_PRESENT_OUTPUT_POWER                (0x00000700)
+#define CMD_PRESENT_OUTPUT_CAPABILITIES         (0x00000800)
+#define CMD_GET_OUTPUT_REQ                      (0x00000900)
+#define CMD_GET_BATTERY_INFO                    (0x00000A00)
+#define CMD_EVSE_STOP_CHARGING                  (0x00000C00)
+#define CMD_GET_MISC_INFO                       (0x00000D00)
+
+#define CMD_DOWNLOAD_REQ                        (0x00000E00)
+#define CMD_START_BLOCK_TRANS                   (0x00000F00)
+#define CMD_DATA_TRANS                          (0x00001000)
+#define CMD_DOWNLOAD_FINISH                     (0x00001100)
+
+#define CMD_ISOLATION_STATUS                    (0x00001200)
+#define CMD_SYNC_RTC                            (0x00001400)
+#define CMD_EVSE_PRECHARGE                      (0x00001500)
+#define CMD_EVCCID_REQ                          (0x00001600)
+
+// 車端主動
+#define ADDRESS_REQ                             (0x080001FF)
+#define NOTIFICATION_EV_STATUS                  (0x08000300)
+#define NOTIFICATION_EV_STOP                    (0x08000B00)
+
+// 車端回應
+#define ACK_EV_FW_VERSION                       (0x08000400)
+#define ACK_EV_HW_VERSION                       (0x08000500)
+#define ACK_GET_OUTPUT_REQ                      (0x08000900)
+#define ACK_GET_EV_BATTERY_INFO                 (0x08000A00)
+#define ACK_GET_MISCELLANEOUS_INFO              (0x08000D00)
+#define ACK_EVSE_ISOLATION_STATUS               (0x08001200)
+#define ACK_EVSE_PRECHAGE_INFO                  (0x08001500)
+#define ACK_EVCCID_REQ                          (0x08001600)
+
+//------------------------------------------------------------------------------
+// Send msg to can-bus
+void SetTargetAddr(uint8_t *target_number, uint8_t index);
+
+void GetFirmwareVersion(uint8_t gunIndex, uint8_t toId);
+void GetHardwareVersion(uint8_t gunIndex, uint8_t toId);
+void SyncRtcInfo(uint8_t gunIndex, uint8_t toId, int epoch);
+void SetChargingPermission(uint8_t gunIndex, uint8_t permissionStatus, uint16_t aOutputPw, uint16_t aOutputVol, uint16_t aOutputCur, uint8_t toId);
+void SetPresentOutputPower(uint16_t outputVol_b1, uint16_t outputCur_b1, uint16_t outputVol_b2, uint16_t outputCur_b2);
+void SetPresentOutputCapacity(uint16_t aOutputPw_b1, uint16_t aOutputCur_b1, uint16_t aOutputPw_b2, uint16_t aOutputCur_b2);
+void GetOutputReq(uint8_t gunIndex, uint8_t toId);
+void GetEvBatteryInfo(uint8_t gunIndex, uint8_t toId);
+void GetMiscellaneousInfo(uint8_t gunIndex, uint8_t relayStatus, float power, float voltage, uint8_t toId);
+void SetIsolationStatus(uint8_t gunIndex, uint8_t result, uint8_t toId);
+void SetEvsePrechargeInfo(uint8_t gunIndex, uint8_t result, uint8_t toId);
+// 發送電樁主動停止充電結果及原因
+void EvseStopChargingEvent(uint8_t stopResult, uint8_t *stopReason, uint8_t toId);
+void GetEVCCIDReq(uint8_t gunIndex, uint8_t toId);
+
+#endif /* _EV_COMM_H_ */

+ 776 - 776
EVSE/Projects/DD360Tcci/Apps/ModuleEvComm/Module_EvRxComm.c

@@ -1,776 +1,776 @@
-#include <stdio.h>
-#include <stdlib.h>
-#include <stdint.h>
-#include <string.h>
-#include <fcntl.h>
-#include <unistd.h>
-
-#include <sys/stat.h>
-
-#include <linux/can.h>
-#include <linux/can/raw.h>
-
-#include "../Config.h"
-#include "../Log/log.h"
-#include "../Define/define.h"
-#include "../ShareMemory/shmMem.h"
-#include "Ev_Comm.h"
-#include "Module_EvComm.h"
-
-//------------------------------------------------------------------------------
-static struct SysConfigData *pSysConfig = NULL;
-static struct SysInfoData *pSysInfo = NULL;
-static struct WARNING_CODE_INFO *pSysWarning = NULL;
-static struct AlarmCodeData *pAlarmCode = NULL;
-static struct CHAdeMOData *ShmCHAdeMOData = NULL;
-static struct GBTData *ShmGBTData = NULL;
-static struct CcsData *ShmCcsData = NULL;
-static struct FanModuleData *ShmFanModuleData = NULL;
-static DcCommonInfo *ShmDcCommonData = NULL;
-struct StatusCodeData* ShmStatusCodeData;
-#define TempArraySize 10
-uint8_t TempArray_1[TempArraySize]={0};
-uint8_t TempArray_2[TempArraySize]={0};
-uint8_t ptemp_1 = 0;
-uint8_t ptemp_2 = 0;
-bool firstcircule = true;
-float EvTargetVolt[2] = { 0 };
-float EvTargetCur[2] = { 0 };
-unsigned char GunStatus[2] = {0};
-//------------------------------------------------------------------------------
-extern bool AbnormalStopAnalysis(uint8_t gun_index, uint8_t *errCode);
-
-//------------------------------------------------------------------------------
-/*static uint8_t getMaxConnectTempAndChiller(uint8_t headTemp1, uint8_t headTemp2,
-        uint8_t chillerTemp1, uint8_t chillerTemp2)
-{
-    uint8_t i = 0;
-    uint8_t tempSource[4] = {headTemp1, headTemp2, chillerTemp1, chillerTemp2};
-    uint8_t maxTemp = 0;
-
-    if (headTemp1 == UNDEFINED_TEMP &&
-            headTemp2 == UNDEFINED_TEMP &&
-            chillerTemp1 == UNDEFINED_TEMP &&
-            chillerTemp2 == UNDEFINED_TEMP) {
-        return UNDEFINED_TEMP;
-    }
-
-    //先取得第一個非UNDEFINED_TEMP的值
-    for (i = 0; i < (sizeof(tempSource) / sizeof(uint8_t)); i++) {
-        if (tempSource[i] != UNDEFINED_TEMP) {
-            maxTemp = tempSource[i];
-            break;
-        }
-    }
-
-    //找最大的溫度值
-    for (i = 0; i < (sizeof(tempSource) / sizeof(uint8_t)); i++) {
-        if (tempSource[i] != UNDEFINED_TEMP) {
-            if (maxTemp < tempSource[i]) {
-                maxTemp = tempSource[i];
-            }
-        }
-    }
-
-    return maxTemp;
-}
-*/
-static uint8_t getAvageTemp(uint8_t value,uint8_t gun)
-{
-    uint16_t avagetemp = 0;
-    int i;
-    uint8_t ptr = 0;
-    uint8_t *pArray; 
-    if(gun == 0) { 
-        pArray = &TempArray_1[0];
-        ptr = ptemp_1;
-    } else {
-        pArray = &TempArray_2[0];
-        ptr = ptemp_2;
-    }
-
-    pArray[ptr] = value;
-    for(i=0;i<TempArraySize;i++) 
-        avagetemp+=pArray[i];
-
-    if (firstcircule) {
-        avagetemp/=(ptr+1);
-    } else {
-        avagetemp/=TempArraySize;
-    }
-    ptr++;
-    if(ptr >= TempArraySize){
-        ptr = 0;
-        firstcircule = false;
-    }
-    if(gun == 0 )
-        ptemp_1 = ptr;
-    else 
-        ptemp_2 = ptr;
-
-    if(avagetemp > TEMP_BOUNDARY)
-        return UNDEFINED_TEMP;
-    return avagetemp;
-}
-
-static uint8_t getMaxConnectTemp(uint8_t headTemp1, uint8_t headTemp2)
-{
-    uint8_t maxTemp = 0;
-
-    if (headTemp1 > TEMP_BOUNDARY &&
-            headTemp2 > TEMP_BOUNDARY) {
-        return UNDEFINED_TEMP;
-    }
-
-    if (headTemp1 <= TEMP_BOUNDARY) {
-        maxTemp = headTemp1;
-    }
-
-    if (headTemp2 <= TEMP_BOUNDARY) {
-        if (headTemp2 > maxTemp) {
-            maxTemp = headTemp2;
-        }
-    }
-    return maxTemp;
-}
-
-static float ReadAdcVolt(uint8_t AdcChannel)
-{
-    //AIN0=CCS GUN Temp 1
-    //AIN1=CCS GUN Temp 2
-    //AIN2=CCS_Proximity/2
-    //AIN3=pilot voltage
-    int fd = -1;
-    uint8_t str[64] = {0};
-    uint8_t AdcValue[8] = {'\0'};
-
-    if (AdcChannel > 7) {
-        return -1;
-    }
-
-    sprintf((char *)str, "/sys/bus/iio/devices/iio\:device0/in_voltage%d_raw", AdcChannel);
-    fd = open((char *)str, O_RDONLY);
-    read(fd, AdcValue, 4);
-
-    close(fd);
-
-    return (1.8 * atoi((char *)&AdcValue[0])) / 4095;
-    //return (1.8 * atoi((char *)&AdcValue)) / 4095;
-}
-
-static void getChillerTemperature(ChillerTemp *chillerTemp)
-{
-    uint8_t i = 0;
-    float adcVoltage = 0.0;
-    ChillerTemp *pChillerTemp = (ChillerTemp *)chillerTemp;
-
-    for (i = 0; i < 4; i++) {
-        adcVoltage = 0.0;
-        adcVoltage =  ReadAdcVolt(i);
-        if ((adcVoltage <= 0.9) && (adcVoltage >= 0.8)) { //0 ~ -40
-            pChillerTemp->Temp[i] = ((adcVoltage - 0.908) * 500) + 60;
-            //log_info("1 adcVoltage = %f", (adcVoltage - 0.9) * 500);
-        } else if ((adcVoltage <= 1.07) && (adcVoltage > 0.9)) {
-            pChillerTemp->Temp[i] = ((adcVoltage - 0.91) * 705.88) + 60;
-            //log_info("2 adcVoltage = %f", (adcVoltage - 0.9) * 500);
-        } else {
-            pChillerTemp->Temp[i] = UNDEFINED_TEMP;
-        }
-
-        /*CcsConnectorTemp1 = ReadAdcVolt(i);
-        if ((CcsConnectorTemp1 <= 0.9) && (CcsConnectorTemp1 >= 0.8)) { //0 ~ -40
-            CcsConnectorTemp1 = (CcsConnectorTemp1 - 0.9) * 500;
-        } else if ((CcsConnectorTemp1 <= 1.07) && (CcsConnectorTemp1 > 0.9)) {
-            CcsConnectorTemp1 = (CcsConnectorTemp1 - 0.9) * 705.88;
-        } else {
-            CcsConnectorTemp1 = 195;    //not available
-        }
-        CcsConnectorTemp |= ((unsigned int)(CcsConnectorTemp1 + 60) & 0xFF) << (i * 8); //0x00(-60)~0xFE(194)
-        */
-    }
-}
-
-
-static void AddrAssignment(uint8_t *data)
-{
-    uint8_t target_number[8];
-    uint8_t index = 0x00;
-    struct ChargingInfoData *pDcChargingInfo = NULL;
-
-    memcpy(target_number, data, sizeof(target_number));
-    index = *(data + 4);
-
-    if (pSysConfig->TotalConnectorCount == 1) {
-        index = 0x01;
-    }
-
-    //if (CheckUniqNumber(index)) {
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index - 1);
-    //DS60-120 add
-    if (pDcChargingInfo->Type == _Type_Chademo) {
-        log_info("Set EV board info : (Chademo) TargetAddr = %d ", index);
-    } else if (pDcChargingInfo->Type == _Type_CCS_2) {
-        log_info("Set EV board info : (CCS) TargetAddr = %d ", index);
-    } else if (pDcChargingInfo->Type == _Type_GB) {
-        log_info("Set EV board info : (GB) TargetAddr = %d ", index);
-    }
-    //log_info("EV board id = %x ", index); //DS60-120 remove
-
-    //log_info("target_number[0] = %x ", target_number[0]);
-    //log_info("target_number[1] = %x ", target_number[1]);
-    //log_info("target_number[2] = %x ", target_number[2]);
-    //log_info("target_number[3] = %x ", target_number[3]);
-    //log_info("target_number[4] = %x ", target_number[4]);
-
-    log_info("SetTargetAddr = %d, type = %d ", index, pDcChargingInfo->Type);
-
-    SetTargetAddr(target_number, index);
-    //}
-}
-
-void CheckEvConnect(int gunIndex)
-{
-    int isDisconnect = FALSE;
-    int gunType = _Type_CCS_2;
-    int isSameType = FALSE;
-    struct ChargingInfoData* pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(gunIndex);
-    struct InfoCodeData* pInfoCode = (struct InfoCodeData*)GetShmInfoCodeData();
-    struct ChargingInfoData* pDcChargingInfo_0 = (struct ChargingInfoData*)GetDcChargingInfoData(0);
-    struct ChargingInfoData* pDcChargingInfo_1 = (struct ChargingInfoData*)GetDcChargingInfoData(1);
-
-    if (pDcChargingInfo_0->Type == pDcChargingInfo_1->Type) {
-        isSameType = TRUE;
-        isDisconnect = ShmDcCommonData->EVDisconnectFlag[0] | ShmDcCommonData->EVDisconnectFlag[1];
-        gunType = pDcChargingInfo_0->Type;
-    } else {
-        isDisconnect = ShmDcCommonData->EVDisconnectFlag[gunIndex];
-        gunType = pDcChargingInfo->Type;
-    }
-
-    //log_info("ShmDcCommonData->EVDisconnectFlag[%d]:%d", gunIndex, ShmDcCommonData->EVDisconnectFlag[gunIndex]);
-    if (isDisconnect) {
-        switch (gunType) {
-        case _Type_Chademo:
-            pInfoCode->InfoEvents.bits.ChademoEvCommFail = YES;
-            break;
-        case _Type_CCS_2:
-            pInfoCode->InfoEvents.bits.CcsEvCommFail = YES;
-            break;
-        case _Type_GB:
-            pInfoCode->InfoEvents.bits.GbEvCommFail = YES;
-            break;
-        }
-
-    } else {
-        switch (gunType) {
-        case _Type_Chademo:
-            pInfoCode->InfoEvents.bits.ChademoEvCommFail = NO;
-            break;
-        case _Type_CCS_2:
-            pInfoCode->InfoEvents.bits.CcsEvCommFail = NO;
-            break;
-        case _Type_GB:
-            pInfoCode->InfoEvents.bits.GbEvCommFail = NO;
-            break;
-        }
-    }
-}
-
-void CANReceiver(int fd)
-{
-    pid_t canRecPid;
-
-    canRecPid = fork();
-
-    if (canRecPid < 0) {
-        log_error("Create CAN Bus receive task failed");
-        return;
-    }
-
-    if (canRecPid == 0) {
-        int isContinue = 1;
-        int nbytes;
-        int intCmd;
-        uint8_t _index = 0;
-        uint8_t recvID = 0;
-        uint8_t targetGun = 0x00;
-        uint8_t gunTypeIndex = 0;
-        uint8_t ver[16] = {0};
-        uint8_t printChillerTemp = NO;
-        uint8_t printConnTemp = NO;
-        uint8_t chillerTemp[2] = {0, 0};
-        uint8_t maxChillerTemp = 0;
-        uint8_t lastChillerTemp = 0;
-        uint8_t maxConnTemp = 0;
-        uint8_t lastConnTemp[2] = {0, 0};
-        struct can_frame frame;
-        ChillerTemp chiilerTemp = {0};
-        struct ChargingInfoData *pDcChargingInfo = NULL;
-        time_t CCS_PlugoutTimer[2];
-        pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
-        pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
-        pSysWarning = (struct WARNING_CODE_INFO *)GetShmSysWarningInfo();
-
-        pAlarmCode = (struct AlarmCodeData *)GetShmAlarmCodeData();
-
-        ShmCHAdeMOData = (struct CHAdeMOData *)GetShmCHAdeMOData();
-        ShmGBTData = (struct GBTData *)GetShmGBTData();
-        ShmCcsData = (struct CcsData *)GetShmCcsData();
-        ShmDcCommonData = (DcCommonInfo *)GetShmDcCommonData();
-        ShmFanModuleData = (struct FanModuleData *)GetShmFanModuleData();
-        ShmStatusCodeData = (struct StatusCodeData*)GetShmStatusCodeData();
-
-        //log_info("Module_EvRXComm Child's PID is %d", getpid());
-        CCS_PlugoutTimer[0] = time((time_t*)NULL);
-        CCS_PlugoutTimer[1] = time((time_t*)NULL);
-
-        while (isContinue) {
-            memset(&frame, 0, sizeof(struct can_frame));
-
-            for (_index = 0; _index < pSysConfig->TotalConnectorCount; _index++) {
-                // 檢查是否有收到EV小板訊號
-                if (pSysInfo->SelfTestSeq == _STEST_COMPLETE && !ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemTaskLost) {
-                    if ((time((time_t*)NULL) - ShmDcCommonData->pGunInfo[_index].EVLoseTimer > 5) &&
-                        !ShmDcCommonData->pGunInfo[_index].EVLoseFlag &&
-                        pDcChargingInfo->SystemStatus != S_UPDATE && !ShmDcCommonData->DebugFlag) {
-
-                        ShmDcCommonData->pGunInfo[_index].EVLoseTimer = time((time_t*)NULL);
-                        ShmDcCommonData->pGunInfo[_index].EVLoseFlag = TRUE;
-
-                        system("/sbin/ip link set can0 down");
-                        sleep(1);
-                        system("/sbin/ip link set can0 type can bitrate 500000 restart-ms 100");
-                        system("/sbin/ip link set can0 up");
-                    }
-                    CheckEvConnect(_index);
-                } else {
-                    ShmDcCommonData->pGunInfo[targetGun].EVLoseTimer = time((time_t*)NULL);
-                    ShmDcCommonData->pGunInfo[targetGun].EVLoseFlag = FALSE;
-                }
-            }
-
-            nbytes = read(fd, &frame, sizeof(struct can_frame));
-            if (nbytes <= 0) {
-                usleep(10000);
-                continue;
-            }
-
-            recvID = 0;
-            targetGun = 0x00;
-            intCmd = (int) (frame.can_id & CAN_EFF_MASK);
-
-            if (intCmd == ADDRESS_REQ) {
-                //ShmDcCommonData->CcsVersion = _CCS_VERSION_CHECK_TAG_V013S0;
-                AddrAssignment(frame.data);
-                continue;
-            }
-
-            intCmd = (int) (frame.can_id & CAN_EFF_MASK & 0xFFFFFF00);
-
-            recvID = ((uint8_t) (frame.can_id & 0x000000FF)); // 0x01 or 0x02
-
-            for (_index = 0; _index < pSysConfig->TotalConnectorCount; _index++) {                    // 假設有找到回應的 Index
-                pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(_index);
-
-                //if (gun_count == 1 &&
-                //        _chargingData[_index]->Type == _Type_CCS_2 &&
-                //        ShmDcCommonData->CcsVersion == _CCS_VERSION_CHECK_TAG_V015S0) {
-                //    target -= 1;
-                //}
-
-                if (pDcChargingInfo->Evboard_id == recvID) {
-                    targetGun = _index;
-                    break;
-                }
-            }
-
-            if ((targetGun < 0) || (targetGun >= CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY)) {
-                log_info("EvComm (CANReceiver) : Target index = %x is < 0 or > QUANTITY ", targetGun);
-                usleep(10000);
-                continue;
-            }
-            //else if (gun_count == 1 && targetGun == 0 && findIndex == 1 &&
-            //           ShmDcCommonData->CcsVersion == _CCS_VERSION_CHECK_TAG_V015S0) {
-            //    // 這樣的條件下~ 也是單槍 CCS 舊版本的狀況 : 因為舊版 CCS 不會 timeout, then send request id
-            //    ShmDcCommonData->CcsVersion = _CCS_VERSION_CHECK_TAG_V013S0;
-            //}
-
-            if (intCmd == 256) {
-                log_info("EvComm command = 256");
-                usleep(10000);
-                continue;
-            }
-            // Reset Connect Timer
-            ShmDcCommonData->EVDisconnectTime[targetGun] = time((time_t*)NULL);
-            ShmDcCommonData->EVDisconnectFlag[targetGun] = FALSE;
-
-            pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(targetGun);
-            gunTypeIndex = pDcChargingInfo->type_index;
-
-            switch (intCmd) {
-            case NOTIFICATION_EV_STATUS:
-                if (pDcChargingInfo->ConnectorPlugIn != frame.data[0]) {
-                    if (frame.data[0] == PLUG) {
-                        log_info("Conn %d, Plugin. ", targetGun);
-                        pDcChargingInfo->isEVCCIDVerify = false;
-#ifdef DD360Audi                       
-                        if (pSysConfig->EVCCID_Authorize)
-                            pSysInfo->CurGunSelected = targetGun;
-#endif                        
-                    } else if (frame.data[0] == UNPLUG) {
-                        if (pDcChargingInfo->Type != _Type_CCS_2)
-                            log_info("Conn %d, Unplug. ", targetGun);
-                        strcpy( (char *) pDcChargingInfo->EVCCID, "");
-                    } else {
-                        log_info("Conn %d, None Check. (%d) ", targetGun, frame.data[0]);
-                    }
-                    /*
-                    if(pDcChargingInfo->RemoteStartFlag == YES) {
-                        pSysInfo->CurGunSelected = targetGun;
-                    }
-                    */
-                }
-
-                pDcChargingInfo->PilotVoltage = frame.data[1];
-                // CCS 小板確認Pilot Voltage != 0
-                if (pDcChargingInfo->Type == _Type_CCS_2 && pDcChargingInfo->PilotVoltage != 0) {
-                    if (frame.data[0] == UNPLUG && pDcChargingInfo->ConnectorPlugIn != frame.data[0])
-                        log_info("Conn %d, Unplug. ", targetGun);
-                    pDcChargingInfo->ConnectorPlugIn = frame.data[0];
-                } else {
-                    pDcChargingInfo->ConnectorPlugIn = frame.data[0];
-                }
-
-                //log_info("index = %d, ConnectorPlugIn = %x, data[0] = %x ",
-                //         targetGun,
-                //         pDcChargingInfo->ConnectorPlugIn,
-                //         frame.data[0]);
-
-                //log_info("ConnectorPlugIn = %x ", (-120 + frame.data[1]) / 10);
-                break;
-
-            case ACK_EV_FW_VERSION:
-                memset(ver, 0, sizeof(ver));
-                if (pDcChargingInfo->Type == _Type_Chademo) {
-                    memcpy(ver, frame.data, frame.can_dlc);
-                    memcpy(ShmCHAdeMOData->evse[gunTypeIndex].version, ver, ARRAY_SIZE(ver));
-                    ShmCHAdeMOData->evse[gunTypeIndex].SelfTest_Comp = PASS;
-                    log_info("chademo ver. : %s", ShmCHAdeMOData->evse[gunTypeIndex].version);
-                } else if (pDcChargingInfo->Type == _Type_GB) {
-                    memcpy(ver, frame.data, frame.can_dlc);
-                    memcpy(ShmGBTData->evse[gunTypeIndex].version, ver, ARRAY_SIZE(ver));
-                    ShmGBTData->evse[gunTypeIndex].SelfTest_Comp = PASS;
-                    log_info("gbt ver. : %s", ShmGBTData->evse[gunTypeIndex].version);
-                } else if (pDcChargingInfo->Type == _Type_CCS_2) {
-                    if (ShmCcsData->CommProtocol == _CCS_COMM_V2GMessage_DIN70121) {
-                        memcpy(ver, frame.data, frame.can_dlc); //DS60-120 add
-
-                        memcpy(&ShmCcsData->V2GMessage_DIN70121[gunTypeIndex].version, ver, ARRAY_SIZE(ver));
-                        ShmCcsData->V2GMessage_DIN70121[gunTypeIndex].SelfTest_Comp = PASS;
-                        log_info("CCS FW = %s ", ShmCcsData->V2GMessage_DIN70121[gunTypeIndex].version);
-                    }
-                }
-
-                if (targetGun == 0) {
-                    memset(pSysInfo->Connector1FwRev,
-                           0,
-                           sizeof(pSysInfo->Connector1FwRev));
-
-                    memcpy(pSysInfo->Connector1FwRev, ver, ARRAY_SIZE(ver));
-                } else if (targetGun == 1) {
-                    memset(pSysInfo->Connector2FwRev,
-                           0,
-                           sizeof(pSysInfo->Connector2FwRev));
-
-                    memcpy(pSysInfo->Connector2FwRev, ver, ARRAY_SIZE(ver));
-                }
-                break;
-
-            case ACK_EV_HW_VERSION:
-                //log_info("Get EV HW = %s ", frame.data);
-                break;
-
-            case ACK_GET_OUTPUT_REQ:
-                if ((pDcChargingInfo->SystemStatus >= S_PREPARING_FOR_EV &&
-                        pDcChargingInfo->SystemStatus <= S_TERMINATING) ||
-                        pDcChargingInfo->SystemStatus == S_ALARM ||
-                        (pDcChargingInfo->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
-                         pDcChargingInfo->SystemStatus <= S_CCS_PRECHARGE_ST1)
-                   ) {
-                    if (pDcChargingInfo->EvBatteryStartSoc <= 0 &&
-                            pDcChargingInfo->SystemStatus >= S_PREPARING_FOR_EVSE) {
-                        pDcChargingInfo->EvBatteryStartSoc = frame.data[1];
-                    }
-
-                    // 進入充電時重新更新電池電量
-                    if (GunStatus[targetGun] != pDcChargingInfo->SystemStatus && pDcChargingInfo->SystemStatus == S_CHARGING) {
-
-                        log_info("Reset Gun%d SoC:%d", targetGun, frame.data[1]);
-                        pDcChargingInfo->EvBatterySoc = frame.data[1];
-                        GunStatus[targetGun] = pDcChargingInfo->SystemStatus;
-                    }
-
-                    if (frame.data[1] > pDcChargingInfo->EvBatterySoc || pDcChargingInfo->SystemStatus == S_CHARGING) {
-                        pDcChargingInfo->EvBatterySoc = frame.data[1];
-                        if (frame.data[1] > pDcChargingInfo->EvBatterySoc)
-                            log_info("Gun%d SOC:%d", targetGun,pDcChargingInfo->EvBatterySoc);
-                    }
-                }
-                //pDcChargingInfo->EvBatterySoc = frame.data[1]; //DS60-120 remove
-
-                //Jerry add set voltage limit
-                pDcChargingInfo->EvBatterytargetVoltage = (float)((frame.data[3] << 8) + frame.data[2]) / 10;
-                if (pDcChargingInfo->EvBatterytargetVoltage > (GetMaxChargingVol(targetGun) * 0.1)) {
-                    pDcChargingInfo->EvBatterytargetVoltage = (GetMaxChargingVol(targetGun) * 0.1);
-                }
-                //printf("id = %d, EvBatterytargetVoltage = %.2f", targetGun, pDcChargingInfo->EvBatterytargetVoltage);
-
-                //Jerry add set currency limit
-                pDcChargingInfo->EvBatterytargetCurrent = (float)((frame.data[5] << 8) + frame.data[4]) / 10;
-                if (pDcChargingInfo->EvBatterytargetCurrent > (GetMaxCharginigCur(targetGun) * 0.1)) {
-                    pDcChargingInfo->EvBatterytargetCurrent = (GetMaxCharginigCur(targetGun) * 0.1);
-                }
-                //printf("id = %d, EvBatterytargetCurrent = %.2f", targetGun, pDcChargingInfo->EvBatterytargetCurrent);
-
-                pDcChargingInfo->RemainChargingDuration = ((short) frame.data[7] << 8) + (short) frame.data[6];
-                //log_info("RemainChargingDuration = %d",  pDcChargingInfo->RemainChargingDuration);
-
-                if (pDcChargingInfo->Type == _Type_Chademo) {
-                    if (ShmCHAdeMOData->ev[gunTypeIndex].PresentMsgFlowStatus != frame.data[0])
-                    {
-                        log_info("Gun%d CHAdeMO board status = %d ", targetGun, ShmCHAdeMOData->ev[gunTypeIndex].PresentMsgFlowStatus);
-                        ShmCHAdeMOData->ev[gunTypeIndex].PresentMsgFlowStatus = frame.data[0];
-                    }
-
-                    ShmCHAdeMOData->ev[gunTypeIndex].EvDetection = frame.data[0];
-                    ShmCHAdeMOData->ev[gunTypeIndex].SOC = pDcChargingInfo->EvBatterySoc;
-                    ShmCHAdeMOData->ev[gunTypeIndex].TargetBatteryVoltage = (pDcChargingInfo->EvBatterytargetVoltage * 10);
-                    ShmCHAdeMOData->ev[gunTypeIndex].ChargingCurrentRequest = (pDcChargingInfo->EvBatterytargetCurrent * 10);
-                } else if (pDcChargingInfo->Type == _Type_GB) {
-                    if (ShmGBTData->ev[gunTypeIndex].PresentMsgFlowStatus != frame.data[0]) {
-                        log_info("Gun%d GB Board status = %d ", targetGun, ShmGBTData->ev[pDcChargingInfo->type_index].PresentMsgFlowStatus);
-                        ShmGBTData->ev[gunTypeIndex].PresentMsgFlowStatus = frame.data[0];
-                    }
-
-                    ShmGBTData->ev[gunTypeIndex].EvDetection = frame.data[0];
-                    ShmGBTData->ev[gunTypeIndex].SOC = pDcChargingInfo->EvBatterySoc;
-                    ShmGBTData->ev[gunTypeIndex].TargetBatteryVoltage = (pDcChargingInfo->EvBatterytargetVoltage * 10);
-                    ShmGBTData->ev[gunTypeIndex].ChargingCurrentRequest = (pDcChargingInfo->EvBatterytargetCurrent * 10);
-                } else if (pDcChargingInfo->Type == _Type_CCS_2) {
-                    if (ShmCcsData->CommProtocol == _CCS_COMM_V2GMessage_DIN70121) {
-                        if (ShmCcsData->V2GMessage_DIN70121[gunTypeIndex].PresentMsgFlowStatus != frame.data[0] && frame.data[0] != 0xFF) {
-                            log_info("Gun%d CCS board status = %d ", targetGun, ShmCcsData->V2GMessage_DIN70121[pDcChargingInfo->type_index].PresentMsgFlowStatus);
-                            ShmCcsData->V2GMessage_DIN70121[gunTypeIndex].PresentMsgFlowStatus = frame.data[0];
-                        }
-                    }
-                }
-                if (pDcChargingInfo->EvBatterytargetVoltage > (EvTargetVolt[targetGun] + 3) ||
-                    pDcChargingInfo->EvBatterytargetVoltage < (EvTargetVolt[targetGun] - 3) ||
-                    pDcChargingInfo->EvBatterytargetCurrent > (EvTargetCur[targetGun] + 1) ||
-                    pDcChargingInfo->EvBatterytargetCurrent < (EvTargetCur[targetGun] - 1)) {
-                    log_info("Gun%d Battery TargetVoltage = %.1f , TargetCurrent = %.1f",
-                        targetGun,pDcChargingInfo->EvBatterytargetVoltage, pDcChargingInfo->EvBatterytargetCurrent);
-                    EvTargetVolt[targetGun] = pDcChargingInfo->EvBatterytargetVoltage;
-                    EvTargetCur[targetGun] = pDcChargingInfo->EvBatterytargetCurrent;
-                }
-                //log_info("EvBatterytargetVoltage = %f ", pDcChargingInfo->EvBatterytargetVoltage);
-                //log_info("EvBatterytargetCurrent = %f ", pDcChargingInfo->EvBatterytargetCurrent);
-                //log_info("BatteryVoltage = %d ",
-                //         ShmCHAdeMOData->ev[_chargingData[target]->type_index].TargetBatteryVoltage);
-                //log_info("CurrentRequest = %d ",
-                //         ShmCHAdeMOData->ev[_chargingData[target]->type_index].ChargingCurrentRequest);
-                break;
-
-            case ACK_GET_EV_BATTERY_INFO:
-                //_chargingData[target].EvACorDCcharging = frame.data[0];
-                //_chargingData[target]->TotalBatteryCap = ((float) frame.data[4] << 8) + (short) frame.data[3];
-                pDcChargingInfo->EvBatteryMaxVoltage = ((float)(((uint16_t)frame.data[4] << 8) + (uint16_t)frame.data[3])) / 10;
-                //_chargingData[target]->EvBatteryMaxCurrent = ((float) frame.data[4] << 8) + (short) frame.data[3];
-                //_chargingData[target].MaxiBatteryCurrent = ((short) frame.data[6] << 8) + (short) frame.data[5];
-                if (pDcChargingInfo->Type == _Type_Chademo) {
-                    ShmCHAdeMOData->ev[gunTypeIndex].TotalBatteryCapacity = ((uint16_t)frame.data[2] << 8) + (uint16_t)frame.data[1];
-                    ShmCHAdeMOData->ev[gunTypeIndex].MaxiBatteryVoltage = pDcChargingInfo->EvBatteryMaxVoltage;
-
-                    //log_info("EvBatteryMaxVoltage = %f ", _chargingData[target]->EvBatteryMaxVoltage);
-                    //log_info("TotalBatteryCapacity = %d ", ShmCHAdeMOData->ev[_chargingData[target]->type_index].TotalBatteryCapacity);
-                    //log_info("MaxiBatteryVoltage = %d ", ShmCHAdeMOData->ev[_chargingData[target]->type_index].MaxiBatteryVoltage);
-                } else if (pDcChargingInfo->Type == _Type_GB) {
-                    ShmGBTData->ev[gunTypeIndex].TotalBatteryCapacity = ((uint16_t)frame.data[2] << 8) + (uint16_t)frame.data[1];
-                    ShmGBTData->ev[gunTypeIndex].MaxiBatteryVoltage = pDcChargingInfo->EvBatteryMaxVoltage;
-                }
-                //else if (pDcChargingInfo->Type == _Type_CCS_2) {
-                //}
-                break;
-            case ACK_GET_MISCELLANEOUS_INFO:
-                pDcChargingInfo->GunLocked = frame.data[0];
-                pDcChargingInfo->PilotVoltage = ((float)(-120 + frame.data[3])) / 10;
-
-                if (pDcChargingInfo->Type == _Type_Chademo) {
-                    ShmCHAdeMOData->evse[gunTypeIndex].ConnectorTemperatureP = frame.data[1];
-                    ShmCHAdeMOData->evse[gunTypeIndex].ConnectorTemperatureN = frame.data[2];
-                    ShmCHAdeMOData->evse[gunTypeIndex].EvboardStatus = frame.data[7];
-                } else if (pDcChargingInfo->Type == _Type_GB) {
-                    ShmGBTData->evse[gunTypeIndex].ConnectorTemperatureP = frame.data[1];
-                    ShmGBTData->evse[gunTypeIndex].ConnectorTemperatureN = frame.data[2];
-                    ShmGBTData->evse[gunTypeIndex].EvboardStatus = frame.data[7];
-                }
-                /*else if (pDcChargingInfo->Type == _Type_CCS_2) {
-                if (ShmCcsData->CommProtocol == _CCS_COMM_V2GMessage_DIN70121) {
-                    //ShmCcsData->V2GMessage_DIN70121[gunTypeIndex]. .ConnectorTemperatureP = frame.data[1];
-                    //ShmCcsData->V2GMessage_DIN70121[gunTypeIndex]. .ConnectorTemperatureN = frame.data[2];
-                }
-                }*/
-
-                ShmDcCommonData->ConnectorTemp[gunTypeIndex][0] = frame.data[1];
-                ShmDcCommonData->ConnectorTemp[gunTypeIndex][1] = frame.data[2];
-
-                if (ShmDcCommonData->TestTemperature == YES) { //ReadCmdline test
-                    break;
-                }
-
-                printChillerTemp = NO;
-                printConnTemp = NO;
-
-                if (((ShmDcCommonData->ChillerValve.MultiChillerGun & 0x80) >> 7) == YES) {
-                    getChillerTemperature(&chiilerTemp);
-                    memcpy((char *)ShmDcCommonData->SystemTemp, (char *)chiilerTemp.Temp, sizeof(ChillerTemp));
-                    chillerTemp[0] = getMaxConnectTemp(chiilerTemp.Temp[0], chiilerTemp.Temp[1]);
-                    chillerTemp[1] = getMaxConnectTemp(chiilerTemp.Temp[2], chiilerTemp.Temp[3]);
-
-                    maxChillerTemp = getMaxConnectTemp(chillerTemp[0], chillerTemp[1]);
-
-                    //if ((maxChillerTemp - 3) >= pDcChargingInfo->ChillerTemp) {
-                    //    printChillerTemp = YES;
-                    //}
-                    if(maxChillerTemp > (lastChillerTemp + 2) || maxChillerTemp < (lastChillerTemp - 2))
-                    {
-                        lastChillerTemp = maxChillerTemp;
-                        printChillerTemp = YES;
-                    }
-
-                    pDcChargingInfo->ChillerTemp = maxChillerTemp;
-                }
-                if (frame.data[1] != 0 || frame.data[2] != 0) {
-                    maxConnTemp = getMaxConnectTemp(frame.data[1], frame.data[2]);
-
-                    maxConnTemp = getAvageTemp(maxConnTemp, targetGun);
-                }
-                if(maxConnTemp > (lastConnTemp[targetGun] + 2) || maxConnTemp < (lastConnTemp[targetGun] - 2))
-                {
-                    lastConnTemp[targetGun] = maxConnTemp;
-                    printConnTemp = YES;
-                }
-
-                pDcChargingInfo->ConnectorTemp = maxConnTemp;
-
-                //紀錄槍頭和水冷機溫度, 在系統狀態變化或溫度大於150
-                if ((ShmDcCommonData->SystemModeChange[targetGun] == YES) ||
-                        (printConnTemp == YES) ||
-                        (printChillerTemp == YES) //&&
-                        //(((pDcChargingInfo->ConnectorTemp >= GUN_OTP_VALUE) &&
-                        //  (pDcChargingInfo->ConnectorTemp != UNDEFINED_TEMP)) ||
-                        // ((pDcChargingInfo->ChillerTemp >= GUN_OTP_VALUE) &&
-                        //  (pDcChargingInfo->ChillerTemp != UNDEFINED_TEMP)))
-                   ) {
-                    ShmDcCommonData->SystemModeChange[targetGun] = NO;
-                    log_info("Conn %d max head temp = %d, max chiller = %d, max chiller2 = %d",
-                             targetGun,
-                             maxConnTemp,
-                             chillerTemp[0],
-                             chillerTemp[1]);
-                }
-
-                if (((ShmDcCommonData->ChillerValve.MultiChillerGun & 0x80) >> 7) == YES) {
-                    //沒有水冷槍
-                    break;
-                }
-
-                if ((ShmDcCommonData->ChillerValve.MultiChillerGun & 0x7F) == 1) {
-                    //單一水冷槍,不需要切換水冷機油閥
-                    //ShmFanModuleData-> ? = YES; //尚未定義
-                    break;
-                }
-
-                //紀錄槍頭溫度
-                if (pDcChargingInfo->ConnectorTemp != UNDEFINED_TEMP) {
-                    if (targetGun == 0) {
-                        ShmDcCommonData->ChillerValve.LeftTemp = pDcChargingInfo->ConnectorTemp;
-                    } else if (targetGun == 1) {
-                        ShmDcCommonData->ChillerValve.RightTemp = pDcChargingInfo->ConnectorTemp;
-                    }
-                }
-
-                //有兩把水冷槍,判斷兩把槍頭溫度,將水冷機節流閥導向溫度高的那一把槍
-                if (ShmDcCommonData->ChillerValve.LeftTemp > ShmDcCommonData->ChillerValve.RightTemp) {
-                    //ShmFanModuleData->? = YES; //尚未定義
-                } else {
-                    //ShmFanModuleData->? = NO; //尚未定義
-                }
-
-                //log_info("EvboardStatus = %x ",
-                //         ShmCHAdeMOData->evse[gunTypeIndex].EvboardStatus);
-                //log_info("ConnectorPlug locked = %x ",
-                //         frame.data[0]);
-                //log_info("PilotVoltage = %x ", (-120 + frame.data[3]) / 10);
-                break;
-
-            case ACK_EVSE_ISOLATION_STATUS:
-                break;
-
-            case ACK_EVSE_PRECHAGE_INFO:
-                pDcChargingInfo->PrechargeStatus = frame.data[0];
-                break;
-
-            case NOTIFICATION_EV_STOP:
-                // 車端要求停止
-                if ((pDcChargingInfo->SystemStatus >= S_REASSIGN_CHECK && //DS60-120 add
-                        pDcChargingInfo->SystemStatus <= S_TERMINATING) ||
-                        (pDcChargingInfo->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
-                         pDcChargingInfo->SystemStatus <= S_CCS_PRECHARGE_ST1)) {
-                    // frame.data[0] : 0x01 => normal stop, 0x02 => ev emergency stop
-                    log_info("----------------------------- (%d) NOTIFICATION_EV_STOP err level = %d -----------------------------",
-                             targetGun,
-                             frame.data[0]);
-                    if (frame.data[0] == 0x02) {
-                        if (AbnormalStopAnalysis(targetGun, frame.data + 1) == true) {
-                            pDcChargingInfo->StopChargeFlag = YES;
-                        } else {
-                            pDcChargingInfo->NormalStopChargeFlag = YES;
-                        }
-                    } else {
-                        AbnormalStopAnalysis(targetGun, frame.data + 1);
-                        pDcChargingInfo->NormalStopChargeFlag = YES;
-                    }
-                }
-                break;
-            case ACK_EVCCID_REQ:
-
-                if (frame.can_dlc > 0 && strcmp ( (char *)pDcChargingInfo->EVCCID, "" ) == EQUAL &&
-                    pDcChargingInfo->Type == _Type_CCS_2)
-                {
-                    {
-                        memset (
-                                ShmCcsData->V2GMessage_DIN70121 [pDcChargingInfo->type_index].SessionSetupRequest.EVCCID,
-                                0,
-                                sizeof(ShmCcsData->V2GMessage_DIN70121 [pDcChargingInfo->type_index].SessionSetupRequest.EVCCID) );
-                        memcpy (
-                                ShmCcsData->V2GMessage_DIN70121 [pDcChargingInfo->type_index].SessionSetupRequest.EVCCID,
-                                frame.data, frame.can_dlc );
-                    }
-
-                    sprintf ( (char *) pDcChargingInfo->EVCCID, "%.2x%.2x%.2x%.2x%.2x%.2x", frame.data [0],
-                            frame.data [1], frame.data [2], frame.data [3], frame.data [4], frame.data [5] );
-
-                    pDcChargingInfo->EVCCID [17] = '\0';
-                    log_info( "Gun %d->EVCCID = %s ", targetGun, pDcChargingInfo->EVCCID );
-                }
-                break;
-            default:
-                log_info("EV board = %d, Ack none defined. intCmd = %d  ", targetGun, intCmd);
-                break;
-            }//switch
-
-            usleep(10000);
-        }//while
-    }
-}
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdint.h>
+#include <string.h>
+#include <fcntl.h>
+#include <unistd.h>
+
+#include <sys/stat.h>
+
+#include <linux/can.h>
+#include <linux/can/raw.h>
+
+#include "../Config.h"
+#include "../Log/log.h"
+#include "../Define/define.h"
+#include "../ShareMemory/shmMem.h"
+#include "Ev_Comm.h"
+#include "Module_EvComm.h"
+
+//------------------------------------------------------------------------------
+static struct SysConfigData *pSysConfig = NULL;
+static struct SysInfoData *pSysInfo = NULL;
+static struct WARNING_CODE_INFO *pSysWarning = NULL;
+static struct AlarmCodeData *pAlarmCode = NULL;
+static struct CHAdeMOData *ShmCHAdeMOData = NULL;
+static struct GBTData *ShmGBTData = NULL;
+static struct CcsData *ShmCcsData = NULL;
+static struct FanModuleData *ShmFanModuleData = NULL;
+static DcCommonInfo *ShmDcCommonData = NULL;
+struct StatusCodeData* ShmStatusCodeData;
+#define TempArraySize 10
+uint8_t TempArray_1[TempArraySize]={0};
+uint8_t TempArray_2[TempArraySize]={0};
+uint8_t ptemp_1 = 0;
+uint8_t ptemp_2 = 0;
+bool firstcircule = true;
+float EvTargetVolt[2] = { 0 };
+float EvTargetCur[2] = { 0 };
+unsigned char GunStatus[2] = {0};
+//------------------------------------------------------------------------------
+extern bool AbnormalStopAnalysis(uint8_t gun_index, uint8_t *errCode);
+
+//------------------------------------------------------------------------------
+/*static uint8_t getMaxConnectTempAndChiller(uint8_t headTemp1, uint8_t headTemp2,
+        uint8_t chillerTemp1, uint8_t chillerTemp2)
+{
+    uint8_t i = 0;
+    uint8_t tempSource[4] = {headTemp1, headTemp2, chillerTemp1, chillerTemp2};
+    uint8_t maxTemp = 0;
+
+    if (headTemp1 == UNDEFINED_TEMP &&
+            headTemp2 == UNDEFINED_TEMP &&
+            chillerTemp1 == UNDEFINED_TEMP &&
+            chillerTemp2 == UNDEFINED_TEMP) {
+        return UNDEFINED_TEMP;
+    }
+
+    //先取得第一個非UNDEFINED_TEMP的值
+    for (i = 0; i < (sizeof(tempSource) / sizeof(uint8_t)); i++) {
+        if (tempSource[i] != UNDEFINED_TEMP) {
+            maxTemp = tempSource[i];
+            break;
+        }
+    }
+
+    //找最大的溫度值
+    for (i = 0; i < (sizeof(tempSource) / sizeof(uint8_t)); i++) {
+        if (tempSource[i] != UNDEFINED_TEMP) {
+            if (maxTemp < tempSource[i]) {
+                maxTemp = tempSource[i];
+            }
+        }
+    }
+
+    return maxTemp;
+}
+*/
+static uint8_t getAvageTemp(uint8_t value,uint8_t gun)
+{
+    uint16_t avagetemp = 0;
+    int i;
+    uint8_t ptr = 0;
+    uint8_t *pArray; 
+    if(gun == 0) { 
+        pArray = &TempArray_1[0];
+        ptr = ptemp_1;
+    } else {
+        pArray = &TempArray_2[0];
+        ptr = ptemp_2;
+    }
+
+    pArray[ptr] = value;
+    for(i=0;i<TempArraySize;i++) 
+        avagetemp+=pArray[i];
+
+    if (firstcircule) {
+        avagetemp/=(ptr+1);
+    } else {
+        avagetemp/=TempArraySize;
+    }
+    ptr++;
+    if(ptr >= TempArraySize){
+        ptr = 0;
+        firstcircule = false;
+    }
+    if(gun == 0 )
+        ptemp_1 = ptr;
+    else 
+        ptemp_2 = ptr;
+
+    if(avagetemp > TEMP_BOUNDARY)
+        return UNDEFINED_TEMP;
+    return avagetemp;
+}
+
+static uint8_t getMaxConnectTemp(uint8_t headTemp1, uint8_t headTemp2)
+{
+    uint8_t maxTemp = 0;
+
+    if (headTemp1 > TEMP_BOUNDARY &&
+            headTemp2 > TEMP_BOUNDARY) {
+        return UNDEFINED_TEMP;
+    }
+
+    if (headTemp1 <= TEMP_BOUNDARY) {
+        maxTemp = headTemp1;
+    }
+
+    if (headTemp2 <= TEMP_BOUNDARY) {
+        if (headTemp2 > maxTemp) {
+            maxTemp = headTemp2;
+        }
+    }
+    return maxTemp;
+}
+
+static float ReadAdcVolt(uint8_t AdcChannel)
+{
+    //AIN0=CCS GUN Temp 1
+    //AIN1=CCS GUN Temp 2
+    //AIN2=CCS_Proximity/2
+    //AIN3=pilot voltage
+    int fd = -1;
+    uint8_t str[64] = {0};
+    uint8_t AdcValue[8] = {'\0'};
+
+    if (AdcChannel > 7) {
+        return -1;
+    }
+
+    sprintf((char *)str, "/sys/bus/iio/devices/iio\:device0/in_voltage%d_raw", AdcChannel);
+    fd = open((char *)str, O_RDONLY);
+    read(fd, AdcValue, 4);
+
+    close(fd);
+
+    return (1.8 * atoi((char *)&AdcValue[0])) / 4095;
+    //return (1.8 * atoi((char *)&AdcValue)) / 4095;
+}
+
+static void getChillerTemperature(ChillerTemp *chillerTemp)
+{
+    uint8_t i = 0;
+    float adcVoltage = 0.0;
+    ChillerTemp *pChillerTemp = (ChillerTemp *)chillerTemp;
+
+    for (i = 0; i < 4; i++) {
+        adcVoltage = 0.0;
+        adcVoltage =  ReadAdcVolt(i);
+        if ((adcVoltage <= 0.9) && (adcVoltage >= 0.8)) { //0 ~ -40
+            pChillerTemp->Temp[i] = ((adcVoltage - 0.908) * 500) + 60;
+            //log_info("1 adcVoltage = %f", (adcVoltage - 0.9) * 500);
+        } else if ((adcVoltage <= 1.07) && (adcVoltage > 0.9)) {
+            pChillerTemp->Temp[i] = ((adcVoltage - 0.91) * 705.88) + 60;
+            //log_info("2 adcVoltage = %f", (adcVoltage - 0.9) * 500);
+        } else {
+            pChillerTemp->Temp[i] = UNDEFINED_TEMP;
+        }
+
+        /*CcsConnectorTemp1 = ReadAdcVolt(i);
+        if ((CcsConnectorTemp1 <= 0.9) && (CcsConnectorTemp1 >= 0.8)) { //0 ~ -40
+            CcsConnectorTemp1 = (CcsConnectorTemp1 - 0.9) * 500;
+        } else if ((CcsConnectorTemp1 <= 1.07) && (CcsConnectorTemp1 > 0.9)) {
+            CcsConnectorTemp1 = (CcsConnectorTemp1 - 0.9) * 705.88;
+        } else {
+            CcsConnectorTemp1 = 195;    //not available
+        }
+        CcsConnectorTemp |= ((unsigned int)(CcsConnectorTemp1 + 60) & 0xFF) << (i * 8); //0x00(-60)~0xFE(194)
+        */
+    }
+}
+
+
+static void AddrAssignment(uint8_t *data)
+{
+    uint8_t target_number[8];
+    uint8_t index = 0x00;
+    struct ChargingInfoData *pDcChargingInfo = NULL;
+
+    memcpy(target_number, data, sizeof(target_number));
+    index = *(data + 4);
+
+    if (pSysConfig->TotalConnectorCount == 1) {
+        index = 0x01;
+    }
+
+    //if (CheckUniqNumber(index)) {
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index - 1);
+    //DS60-120 add
+    if (pDcChargingInfo->Type == _Type_Chademo) {
+        log_info("Set EV board info : (Chademo) TargetAddr = %d ", index);
+    } else if (pDcChargingInfo->Type == _Type_CCS_2) {
+        log_info("Set EV board info : (CCS) TargetAddr = %d ", index);
+    } else if (pDcChargingInfo->Type == _Type_GB) {
+        log_info("Set EV board info : (GB) TargetAddr = %d ", index);
+    }
+    //log_info("EV board id = %x ", index); //DS60-120 remove
+
+    //log_info("target_number[0] = %x ", target_number[0]);
+    //log_info("target_number[1] = %x ", target_number[1]);
+    //log_info("target_number[2] = %x ", target_number[2]);
+    //log_info("target_number[3] = %x ", target_number[3]);
+    //log_info("target_number[4] = %x ", target_number[4]);
+
+    log_info("SetTargetAddr = %d, type = %d ", index, pDcChargingInfo->Type);
+
+    SetTargetAddr(target_number, index);
+    //}
+}
+
+void CheckEvConnect(int gunIndex)
+{
+    int isDisconnect = FALSE;
+    int gunType = _Type_CCS_2;
+    int isSameType = FALSE;
+    struct ChargingInfoData* pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(gunIndex);
+    struct InfoCodeData* pInfoCode = (struct InfoCodeData*)GetShmInfoCodeData();
+    struct ChargingInfoData* pDcChargingInfo_0 = (struct ChargingInfoData*)GetDcChargingInfoData(0);
+    struct ChargingInfoData* pDcChargingInfo_1 = (struct ChargingInfoData*)GetDcChargingInfoData(1);
+
+    if (pDcChargingInfo_0->Type == pDcChargingInfo_1->Type) {
+        isSameType = TRUE;
+        isDisconnect = ShmDcCommonData->EVDisconnectFlag[0] | ShmDcCommonData->EVDisconnectFlag[1];
+        gunType = pDcChargingInfo_0->Type;
+    } else {
+        isDisconnect = ShmDcCommonData->EVDisconnectFlag[gunIndex];
+        gunType = pDcChargingInfo->Type;
+    }
+
+    //log_info("ShmDcCommonData->EVDisconnectFlag[%d]:%d", gunIndex, ShmDcCommonData->EVDisconnectFlag[gunIndex]);
+    if (isDisconnect) {
+        switch (gunType) {
+        case _Type_Chademo:
+            pInfoCode->InfoEvents.bits.ChademoEvCommFail = YES;
+            break;
+        case _Type_CCS_2:
+            pInfoCode->InfoEvents.bits.CcsEvCommFail = YES;
+            break;
+        case _Type_GB:
+            pInfoCode->InfoEvents.bits.GbEvCommFail = YES;
+            break;
+        }
+
+    } else {
+        switch (gunType) {
+        case _Type_Chademo:
+            pInfoCode->InfoEvents.bits.ChademoEvCommFail = NO;
+            break;
+        case _Type_CCS_2:
+            pInfoCode->InfoEvents.bits.CcsEvCommFail = NO;
+            break;
+        case _Type_GB:
+            pInfoCode->InfoEvents.bits.GbEvCommFail = NO;
+            break;
+        }
+    }
+}
+
+void CANReceiver(int fd)
+{
+    pid_t canRecPid;
+
+    canRecPid = fork();
+
+    if (canRecPid < 0) {
+        log_error("Create CAN Bus receive task failed");
+        return;
+    }
+
+    if (canRecPid == 0) {
+        int isContinue = 1;
+        int nbytes;
+        int intCmd;
+        uint8_t _index = 0;
+        uint8_t recvID = 0;
+        uint8_t targetGun = 0x00;
+        uint8_t gunTypeIndex = 0;
+        uint8_t ver[16] = {0};
+        uint8_t printChillerTemp = NO;
+        uint8_t printConnTemp = NO;
+        uint8_t chillerTemp[2] = {0, 0};
+        uint8_t maxChillerTemp = 0;
+        uint8_t lastChillerTemp = 0;
+        uint8_t maxConnTemp = 0;
+        uint8_t lastConnTemp[2] = {0, 0};
+        struct can_frame frame;
+        ChillerTemp chiilerTemp = {0};
+        struct ChargingInfoData *pDcChargingInfo = NULL;
+        time_t CCS_PlugoutTimer[2];
+        pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
+        pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
+        pSysWarning = (struct WARNING_CODE_INFO *)GetShmSysWarningInfo();
+
+        pAlarmCode = (struct AlarmCodeData *)GetShmAlarmCodeData();
+
+        ShmCHAdeMOData = (struct CHAdeMOData *)GetShmCHAdeMOData();
+        ShmGBTData = (struct GBTData *)GetShmGBTData();
+        ShmCcsData = (struct CcsData *)GetShmCcsData();
+        ShmDcCommonData = (DcCommonInfo *)GetShmDcCommonData();
+        ShmFanModuleData = (struct FanModuleData *)GetShmFanModuleData();
+        ShmStatusCodeData = (struct StatusCodeData*)GetShmStatusCodeData();
+
+        //log_info("Module_EvRXComm Child's PID is %d", getpid());
+        CCS_PlugoutTimer[0] = time((time_t*)NULL);
+        CCS_PlugoutTimer[1] = time((time_t*)NULL);
+
+        while (isContinue) {
+            memset(&frame, 0, sizeof(struct can_frame));
+
+            for (_index = 0; _index < pSysConfig->TotalConnectorCount; _index++) {
+                // 檢查是否有收到EV小板訊號
+                if (pSysInfo->SelfTestSeq == _STEST_COMPLETE && !ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemTaskLost) {
+                    if ((time((time_t*)NULL) - ShmDcCommonData->pGunInfo[_index].EVLoseTimer > 5) &&
+                        !ShmDcCommonData->pGunInfo[_index].EVLoseFlag &&
+                        pDcChargingInfo->SystemStatus != S_UPDATE && !ShmDcCommonData->DebugFlag) {
+
+                        ShmDcCommonData->pGunInfo[_index].EVLoseTimer = time((time_t*)NULL);
+                        ShmDcCommonData->pGunInfo[_index].EVLoseFlag = TRUE;
+
+                        system("/sbin/ip link set can0 down");
+                        sleep(1);
+                        system("/sbin/ip link set can0 type can bitrate 500000 restart-ms 100");
+                        system("/sbin/ip link set can0 up");
+                    }
+                    CheckEvConnect(_index);
+                } else {
+                    ShmDcCommonData->pGunInfo[targetGun].EVLoseTimer = time((time_t*)NULL);
+                    ShmDcCommonData->pGunInfo[targetGun].EVLoseFlag = FALSE;
+                }
+            }
+
+            nbytes = read(fd, &frame, sizeof(struct can_frame));
+            if (nbytes <= 0) {
+                usleep(10000);
+                continue;
+            }
+
+            recvID = 0;
+            targetGun = 0x00;
+            intCmd = (int) (frame.can_id & CAN_EFF_MASK);
+
+            if (intCmd == ADDRESS_REQ) {
+                //ShmDcCommonData->CcsVersion = _CCS_VERSION_CHECK_TAG_V013S0;
+                AddrAssignment(frame.data);
+                continue;
+            }
+
+            intCmd = (int) (frame.can_id & CAN_EFF_MASK & 0xFFFFFF00);
+
+            recvID = ((uint8_t) (frame.can_id & 0x000000FF)); // 0x01 or 0x02
+
+            for (_index = 0; _index < pSysConfig->TotalConnectorCount; _index++) {                    // 假設有找到回應的 Index
+                pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(_index);
+
+                //if (gun_count == 1 &&
+                //        _chargingData[_index]->Type == _Type_CCS_2 &&
+                //        ShmDcCommonData->CcsVersion == _CCS_VERSION_CHECK_TAG_V015S0) {
+                //    target -= 1;
+                //}
+
+                if (pDcChargingInfo->Evboard_id == recvID) {
+                    targetGun = _index;
+                    break;
+                }
+            }
+
+            if ((targetGun < 0) || (targetGun >= CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY)) {
+                log_info("EvComm (CANReceiver) : Target index = %x is < 0 or > QUANTITY ", targetGun);
+                usleep(10000);
+                continue;
+            }
+            //else if (gun_count == 1 && targetGun == 0 && findIndex == 1 &&
+            //           ShmDcCommonData->CcsVersion == _CCS_VERSION_CHECK_TAG_V015S0) {
+            //    // 這樣的條件下~ 也是單槍 CCS 舊版本的狀況 : 因為舊版 CCS 不會 timeout, then send request id
+            //    ShmDcCommonData->CcsVersion = _CCS_VERSION_CHECK_TAG_V013S0;
+            //}
+
+            if (intCmd == 256) {
+                log_info("EvComm command = 256");
+                usleep(10000);
+                continue;
+            }
+            // Reset Connect Timer
+            ShmDcCommonData->EVDisconnectTime[targetGun] = time((time_t*)NULL);
+            ShmDcCommonData->EVDisconnectFlag[targetGun] = FALSE;
+
+            pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(targetGun);
+            gunTypeIndex = pDcChargingInfo->type_index;
+
+            switch (intCmd) {
+            case NOTIFICATION_EV_STATUS:
+                if (pDcChargingInfo->ConnectorPlugIn != frame.data[0]) {
+                    if (frame.data[0] == PLUG) {
+                        log_info("Conn %d, Plugin. ", targetGun);
+                        pDcChargingInfo->isEVCCIDVerify = false;
+#ifdef DD360Audi                       
+                        if (pSysConfig->EVCCID_Authorize)
+                            pSysInfo->CurGunSelected = targetGun;
+#endif                        
+                    } else if (frame.data[0] == UNPLUG) {
+                        if (pDcChargingInfo->Type != _Type_CCS_2)
+                            log_info("Conn %d, Unplug. ", targetGun);
+                        strcpy( (char *) pDcChargingInfo->EVCCID, "");
+                    } else {
+                        log_info("Conn %d, None Check. (%d) ", targetGun, frame.data[0]);
+                    }
+                    /*
+                    if(pDcChargingInfo->RemoteStartFlag == YES) {
+                        pSysInfo->CurGunSelected = targetGun;
+                    }
+                    */
+                }
+
+                pDcChargingInfo->PilotVoltage = frame.data[1];
+                // CCS 小板確認Pilot Voltage != 0
+                if (pDcChargingInfo->Type == _Type_CCS_2 && pDcChargingInfo->PilotVoltage != 0) {
+                    if (frame.data[0] == UNPLUG && pDcChargingInfo->ConnectorPlugIn != frame.data[0])
+                        log_info("Conn %d, Unplug. ", targetGun);
+                    pDcChargingInfo->ConnectorPlugIn = frame.data[0];
+                } else {
+                    pDcChargingInfo->ConnectorPlugIn = frame.data[0];
+                }
+
+                //log_info("index = %d, ConnectorPlugIn = %x, data[0] = %x ",
+                //         targetGun,
+                //         pDcChargingInfo->ConnectorPlugIn,
+                //         frame.data[0]);
+
+                //log_info("ConnectorPlugIn = %x ", (-120 + frame.data[1]) / 10);
+                break;
+
+            case ACK_EV_FW_VERSION:
+                memset(ver, 0, sizeof(ver));
+                if (pDcChargingInfo->Type == _Type_Chademo) {
+                    memcpy(ver, frame.data, frame.can_dlc);
+                    memcpy(ShmCHAdeMOData->evse[gunTypeIndex].version, ver, ARRAY_SIZE(ver));
+                    ShmCHAdeMOData->evse[gunTypeIndex].SelfTest_Comp = PASS;
+                    log_info("chademo ver. : %s", ShmCHAdeMOData->evse[gunTypeIndex].version);
+                } else if (pDcChargingInfo->Type == _Type_GB) {
+                    memcpy(ver, frame.data, frame.can_dlc);
+                    memcpy(ShmGBTData->evse[gunTypeIndex].version, ver, ARRAY_SIZE(ver));
+                    ShmGBTData->evse[gunTypeIndex].SelfTest_Comp = PASS;
+                    log_info("gbt ver. : %s", ShmGBTData->evse[gunTypeIndex].version);
+                } else if (pDcChargingInfo->Type == _Type_CCS_2) {
+                    if (ShmCcsData->CommProtocol == _CCS_COMM_V2GMessage_DIN70121) {
+                        memcpy(ver, frame.data, frame.can_dlc); //DS60-120 add
+
+                        memcpy(&ShmCcsData->V2GMessage_DIN70121[gunTypeIndex].version, ver, ARRAY_SIZE(ver));
+                        ShmCcsData->V2GMessage_DIN70121[gunTypeIndex].SelfTest_Comp = PASS;
+                        log_info("CCS FW = %s ", ShmCcsData->V2GMessage_DIN70121[gunTypeIndex].version);
+                    }
+                }
+
+                if (targetGun == 0) {
+                    memset(pSysInfo->Connector1FwRev,
+                           0,
+                           sizeof(pSysInfo->Connector1FwRev));
+
+                    memcpy(pSysInfo->Connector1FwRev, ver, ARRAY_SIZE(ver));
+                } else if (targetGun == 1) {
+                    memset(pSysInfo->Connector2FwRev,
+                           0,
+                           sizeof(pSysInfo->Connector2FwRev));
+
+                    memcpy(pSysInfo->Connector2FwRev, ver, ARRAY_SIZE(ver));
+                }
+                break;
+
+            case ACK_EV_HW_VERSION:
+                //log_info("Get EV HW = %s ", frame.data);
+                break;
+
+            case ACK_GET_OUTPUT_REQ:
+                if ((pDcChargingInfo->SystemStatus >= S_PREPARING_FOR_EV &&
+                        pDcChargingInfo->SystemStatus <= S_TERMINATING) ||
+                        pDcChargingInfo->SystemStatus == S_ALARM ||
+                        (pDcChargingInfo->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
+                         pDcChargingInfo->SystemStatus <= S_CCS_PRECHARGE_ST1)
+                   ) {
+                    if (pDcChargingInfo->EvBatteryStartSoc <= 0 &&
+                            pDcChargingInfo->SystemStatus >= S_PREPARING_FOR_EVSE) {
+                        pDcChargingInfo->EvBatteryStartSoc = frame.data[1];
+                    }
+
+                    // 進入充電時重新更新電池電量
+                    if (GunStatus[targetGun] != pDcChargingInfo->SystemStatus && pDcChargingInfo->SystemStatus == S_CHARGING) {
+
+                        log_info("Reset Gun%d SoC:%d", targetGun, frame.data[1]);
+                        pDcChargingInfo->EvBatterySoc = frame.data[1];
+                        GunStatus[targetGun] = pDcChargingInfo->SystemStatus;
+                    }
+
+                    if (frame.data[1] > pDcChargingInfo->EvBatterySoc || pDcChargingInfo->SystemStatus == S_CHARGING) {
+                        pDcChargingInfo->EvBatterySoc = frame.data[1];
+                        if (frame.data[1] > pDcChargingInfo->EvBatterySoc)
+                            log_info("Gun%d SOC:%d", targetGun,pDcChargingInfo->EvBatterySoc);
+                    }
+                }
+                //pDcChargingInfo->EvBatterySoc = frame.data[1]; //DS60-120 remove
+
+                //Jerry add set voltage limit
+                pDcChargingInfo->EvBatterytargetVoltage = (float)((frame.data[3] << 8) + frame.data[2]) / 10;
+                if (pDcChargingInfo->EvBatterytargetVoltage > (GetMaxChargingVol(targetGun) * 0.1)) {
+                    pDcChargingInfo->EvBatterytargetVoltage = (GetMaxChargingVol(targetGun) * 0.1);
+                }
+                //printf("id = %d, EvBatterytargetVoltage = %.2f", targetGun, pDcChargingInfo->EvBatterytargetVoltage);
+
+                //Jerry add set currency limit
+                pDcChargingInfo->EvBatterytargetCurrent = (float)((frame.data[5] << 8) + frame.data[4]) / 10;
+                if (pDcChargingInfo->EvBatterytargetCurrent > (GetMaxCharginigCur(targetGun) * 0.1)) {
+                    pDcChargingInfo->EvBatterytargetCurrent = (GetMaxCharginigCur(targetGun) * 0.1);
+                }
+                //printf("id = %d, EvBatterytargetCurrent = %.2f", targetGun, pDcChargingInfo->EvBatterytargetCurrent);
+
+                pDcChargingInfo->RemainChargingDuration = ((short) frame.data[7] << 8) + (short) frame.data[6];
+                //log_info("RemainChargingDuration = %d",  pDcChargingInfo->RemainChargingDuration);
+
+                if (pDcChargingInfo->Type == _Type_Chademo) {
+                    if (ShmCHAdeMOData->ev[gunTypeIndex].PresentMsgFlowStatus != frame.data[0])
+                    {
+                        log_info("Gun%d CHAdeMO board status = %d ", targetGun, ShmCHAdeMOData->ev[gunTypeIndex].PresentMsgFlowStatus);
+                        ShmCHAdeMOData->ev[gunTypeIndex].PresentMsgFlowStatus = frame.data[0];
+                    }
+
+                    ShmCHAdeMOData->ev[gunTypeIndex].EvDetection = frame.data[0];
+                    ShmCHAdeMOData->ev[gunTypeIndex].SOC = pDcChargingInfo->EvBatterySoc;
+                    ShmCHAdeMOData->ev[gunTypeIndex].TargetBatteryVoltage = (pDcChargingInfo->EvBatterytargetVoltage * 10);
+                    ShmCHAdeMOData->ev[gunTypeIndex].ChargingCurrentRequest = (pDcChargingInfo->EvBatterytargetCurrent * 10);
+                } else if (pDcChargingInfo->Type == _Type_GB) {
+                    if (ShmGBTData->ev[gunTypeIndex].PresentMsgFlowStatus != frame.data[0]) {
+                        log_info("Gun%d GB Board status = %d ", targetGun, ShmGBTData->ev[pDcChargingInfo->type_index].PresentMsgFlowStatus);
+                        ShmGBTData->ev[gunTypeIndex].PresentMsgFlowStatus = frame.data[0];
+                    }
+
+                    ShmGBTData->ev[gunTypeIndex].EvDetection = frame.data[0];
+                    ShmGBTData->ev[gunTypeIndex].SOC = pDcChargingInfo->EvBatterySoc;
+                    ShmGBTData->ev[gunTypeIndex].TargetBatteryVoltage = (pDcChargingInfo->EvBatterytargetVoltage * 10);
+                    ShmGBTData->ev[gunTypeIndex].ChargingCurrentRequest = (pDcChargingInfo->EvBatterytargetCurrent * 10);
+                } else if (pDcChargingInfo->Type == _Type_CCS_2) {
+                    if (ShmCcsData->CommProtocol == _CCS_COMM_V2GMessage_DIN70121) {
+                        if (ShmCcsData->V2GMessage_DIN70121[gunTypeIndex].PresentMsgFlowStatus != frame.data[0] && frame.data[0] != 0xFF) {
+                            log_info("Gun%d CCS board status = %d ", targetGun, ShmCcsData->V2GMessage_DIN70121[pDcChargingInfo->type_index].PresentMsgFlowStatus);
+                            ShmCcsData->V2GMessage_DIN70121[gunTypeIndex].PresentMsgFlowStatus = frame.data[0];
+                        }
+                    }
+                }
+                if (pDcChargingInfo->EvBatterytargetVoltage > (EvTargetVolt[targetGun] + 3) ||
+                    pDcChargingInfo->EvBatterytargetVoltage < (EvTargetVolt[targetGun] - 3) ||
+                    pDcChargingInfo->EvBatterytargetCurrent > (EvTargetCur[targetGun] + 1) ||
+                    pDcChargingInfo->EvBatterytargetCurrent < (EvTargetCur[targetGun] - 1)) {
+                    log_info("Gun%d Battery TargetVoltage = %.1f , TargetCurrent = %.1f",
+                        targetGun,pDcChargingInfo->EvBatterytargetVoltage, pDcChargingInfo->EvBatterytargetCurrent);
+                    EvTargetVolt[targetGun] = pDcChargingInfo->EvBatterytargetVoltage;
+                    EvTargetCur[targetGun] = pDcChargingInfo->EvBatterytargetCurrent;
+                }
+                //log_info("EvBatterytargetVoltage = %f ", pDcChargingInfo->EvBatterytargetVoltage);
+                //log_info("EvBatterytargetCurrent = %f ", pDcChargingInfo->EvBatterytargetCurrent);
+                //log_info("BatteryVoltage = %d ",
+                //         ShmCHAdeMOData->ev[_chargingData[target]->type_index].TargetBatteryVoltage);
+                //log_info("CurrentRequest = %d ",
+                //         ShmCHAdeMOData->ev[_chargingData[target]->type_index].ChargingCurrentRequest);
+                break;
+
+            case ACK_GET_EV_BATTERY_INFO:
+                //_chargingData[target].EvACorDCcharging = frame.data[0];
+                //_chargingData[target]->TotalBatteryCap = ((float) frame.data[4] << 8) + (short) frame.data[3];
+                pDcChargingInfo->EvBatteryMaxVoltage = ((float)(((uint16_t)frame.data[4] << 8) + (uint16_t)frame.data[3])) / 10;
+                //_chargingData[target]->EvBatteryMaxCurrent = ((float) frame.data[4] << 8) + (short) frame.data[3];
+                //_chargingData[target].MaxiBatteryCurrent = ((short) frame.data[6] << 8) + (short) frame.data[5];
+                if (pDcChargingInfo->Type == _Type_Chademo) {
+                    ShmCHAdeMOData->ev[gunTypeIndex].TotalBatteryCapacity = ((uint16_t)frame.data[2] << 8) + (uint16_t)frame.data[1];
+                    ShmCHAdeMOData->ev[gunTypeIndex].MaxiBatteryVoltage = pDcChargingInfo->EvBatteryMaxVoltage;
+
+                    //log_info("EvBatteryMaxVoltage = %f ", _chargingData[target]->EvBatteryMaxVoltage);
+                    //log_info("TotalBatteryCapacity = %d ", ShmCHAdeMOData->ev[_chargingData[target]->type_index].TotalBatteryCapacity);
+                    //log_info("MaxiBatteryVoltage = %d ", ShmCHAdeMOData->ev[_chargingData[target]->type_index].MaxiBatteryVoltage);
+                } else if (pDcChargingInfo->Type == _Type_GB) {
+                    ShmGBTData->ev[gunTypeIndex].TotalBatteryCapacity = ((uint16_t)frame.data[2] << 8) + (uint16_t)frame.data[1];
+                    ShmGBTData->ev[gunTypeIndex].MaxiBatteryVoltage = pDcChargingInfo->EvBatteryMaxVoltage;
+                }
+                //else if (pDcChargingInfo->Type == _Type_CCS_2) {
+                //}
+                break;
+            case ACK_GET_MISCELLANEOUS_INFO:
+                pDcChargingInfo->GunLocked = frame.data[0];
+                pDcChargingInfo->PilotVoltage = ((float)(-120 + frame.data[3])) / 10;
+
+                if (pDcChargingInfo->Type == _Type_Chademo) {
+                    ShmCHAdeMOData->evse[gunTypeIndex].ConnectorTemperatureP = frame.data[1];
+                    ShmCHAdeMOData->evse[gunTypeIndex].ConnectorTemperatureN = frame.data[2];
+                    ShmCHAdeMOData->evse[gunTypeIndex].EvboardStatus = frame.data[7];
+                } else if (pDcChargingInfo->Type == _Type_GB) {
+                    ShmGBTData->evse[gunTypeIndex].ConnectorTemperatureP = frame.data[1];
+                    ShmGBTData->evse[gunTypeIndex].ConnectorTemperatureN = frame.data[2];
+                    ShmGBTData->evse[gunTypeIndex].EvboardStatus = frame.data[7];
+                }
+                /*else if (pDcChargingInfo->Type == _Type_CCS_2) {
+                if (ShmCcsData->CommProtocol == _CCS_COMM_V2GMessage_DIN70121) {
+                    //ShmCcsData->V2GMessage_DIN70121[gunTypeIndex]. .ConnectorTemperatureP = frame.data[1];
+                    //ShmCcsData->V2GMessage_DIN70121[gunTypeIndex]. .ConnectorTemperatureN = frame.data[2];
+                }
+                }*/
+
+                ShmDcCommonData->ConnectorTemp[gunTypeIndex][0] = frame.data[1];
+                ShmDcCommonData->ConnectorTemp[gunTypeIndex][1] = frame.data[2];
+
+                if (ShmDcCommonData->TestTemperature == YES) { //ReadCmdline test
+                    break;
+                }
+
+                printChillerTemp = NO;
+                printConnTemp = NO;
+
+                if (((ShmDcCommonData->ChillerValve.MultiChillerGun & 0x80) >> 7) == YES) {
+                    getChillerTemperature(&chiilerTemp);
+                    memcpy((char *)ShmDcCommonData->SystemTemp, (char *)chiilerTemp.Temp, sizeof(ChillerTemp));
+                    chillerTemp[0] = getMaxConnectTemp(chiilerTemp.Temp[0], chiilerTemp.Temp[1]);
+                    chillerTemp[1] = getMaxConnectTemp(chiilerTemp.Temp[2], chiilerTemp.Temp[3]);
+
+                    maxChillerTemp = getMaxConnectTemp(chillerTemp[0], chillerTemp[1]);
+
+                    //if ((maxChillerTemp - 3) >= pDcChargingInfo->ChillerTemp) {
+                    //    printChillerTemp = YES;
+                    //}
+                    if(maxChillerTemp > (lastChillerTemp + 2) || maxChillerTemp < (lastChillerTemp - 2))
+                    {
+                        lastChillerTemp = maxChillerTemp;
+                        printChillerTemp = YES;
+                    }
+
+                    pDcChargingInfo->ChillerTemp = maxChillerTemp;
+                }
+                if (frame.data[1] != 0 || frame.data[2] != 0) {
+                    maxConnTemp = getMaxConnectTemp(frame.data[1], frame.data[2]);
+
+                    maxConnTemp = getAvageTemp(maxConnTemp, targetGun);
+                }
+                if(maxConnTemp > (lastConnTemp[targetGun] + 2) || maxConnTemp < (lastConnTemp[targetGun] - 2))
+                {
+                    lastConnTemp[targetGun] = maxConnTemp;
+                    printConnTemp = YES;
+                }
+
+                pDcChargingInfo->ConnectorTemp = maxConnTemp;
+
+                //紀錄槍頭和水冷機溫度, 在系統狀態變化或溫度大於150
+                if ((ShmDcCommonData->SystemModeChange[targetGun] == YES) ||
+                        (printConnTemp == YES) ||
+                        (printChillerTemp == YES) //&&
+                        //(((pDcChargingInfo->ConnectorTemp >= GUN_OTP_VALUE) &&
+                        //  (pDcChargingInfo->ConnectorTemp != UNDEFINED_TEMP)) ||
+                        // ((pDcChargingInfo->ChillerTemp >= GUN_OTP_VALUE) &&
+                        //  (pDcChargingInfo->ChillerTemp != UNDEFINED_TEMP)))
+                   ) {
+                    ShmDcCommonData->SystemModeChange[targetGun] = NO;
+                    log_info("Conn %d max head temp = %d, max chiller = %d, max chiller2 = %d",
+                             targetGun,
+                             maxConnTemp,
+                             chillerTemp[0],
+                             chillerTemp[1]);
+                }
+
+                if (((ShmDcCommonData->ChillerValve.MultiChillerGun & 0x80) >> 7) == YES) {
+                    //沒有水冷槍
+                    break;
+                }
+
+                if ((ShmDcCommonData->ChillerValve.MultiChillerGun & 0x7F) == 1) {
+                    //單一水冷槍,不需要切換水冷機油閥
+                    //ShmFanModuleData-> ? = YES; //尚未定義
+                    break;
+                }
+
+                //紀錄槍頭溫度
+                if (pDcChargingInfo->ConnectorTemp != UNDEFINED_TEMP) {
+                    if (targetGun == 0) {
+                        ShmDcCommonData->ChillerValve.LeftTemp = pDcChargingInfo->ConnectorTemp;
+                    } else if (targetGun == 1) {
+                        ShmDcCommonData->ChillerValve.RightTemp = pDcChargingInfo->ConnectorTemp;
+                    }
+                }
+
+                //有兩把水冷槍,判斷兩把槍頭溫度,將水冷機節流閥導向溫度高的那一把槍
+                if (ShmDcCommonData->ChillerValve.LeftTemp > ShmDcCommonData->ChillerValve.RightTemp) {
+                    //ShmFanModuleData->? = YES; //尚未定義
+                } else {
+                    //ShmFanModuleData->? = NO; //尚未定義
+                }
+
+                //log_info("EvboardStatus = %x ",
+                //         ShmCHAdeMOData->evse[gunTypeIndex].EvboardStatus);
+                //log_info("ConnectorPlug locked = %x ",
+                //         frame.data[0]);
+                //log_info("PilotVoltage = %x ", (-120 + frame.data[3]) / 10);
+                break;
+
+            case ACK_EVSE_ISOLATION_STATUS:
+                break;
+
+            case ACK_EVSE_PRECHAGE_INFO:
+                pDcChargingInfo->PrechargeStatus = frame.data[0];
+                break;
+
+            case NOTIFICATION_EV_STOP:
+                // 車端要求停止
+                if ((pDcChargingInfo->SystemStatus >= S_REASSIGN_CHECK && //DS60-120 add
+                        pDcChargingInfo->SystemStatus <= S_TERMINATING) ||
+                        (pDcChargingInfo->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
+                         pDcChargingInfo->SystemStatus <= S_CCS_PRECHARGE_ST1)) {
+                    // frame.data[0] : 0x01 => normal stop, 0x02 => ev emergency stop
+                    log_info("----------------------------- (%d) NOTIFICATION_EV_STOP err level = %d -----------------------------",
+                             targetGun,
+                             frame.data[0]);
+                    if (frame.data[0] == 0x02) {
+                        if (AbnormalStopAnalysis(targetGun, frame.data + 1) == true) {
+                            pDcChargingInfo->StopChargeFlag = YES;
+                        } else {
+                            pDcChargingInfo->NormalStopChargeFlag = YES;
+                        }
+                    } else {
+                        AbnormalStopAnalysis(targetGun, frame.data + 1);
+                        pDcChargingInfo->NormalStopChargeFlag = YES;
+                    }
+                }
+                break;
+            case ACK_EVCCID_REQ:
+
+                if (frame.can_dlc > 0 && strcmp ( (char *)pDcChargingInfo->EVCCID, "" ) == EQUAL &&
+                    pDcChargingInfo->Type == _Type_CCS_2)
+                {
+                    {
+                        memset (
+                                ShmCcsData->V2GMessage_DIN70121 [pDcChargingInfo->type_index].SessionSetupRequest.EVCCID,
+                                0,
+                                sizeof(ShmCcsData->V2GMessage_DIN70121 [pDcChargingInfo->type_index].SessionSetupRequest.EVCCID) );
+                        memcpy (
+                                ShmCcsData->V2GMessage_DIN70121 [pDcChargingInfo->type_index].SessionSetupRequest.EVCCID,
+                                frame.data, frame.can_dlc );
+                    }
+
+                    sprintf ( (char *) pDcChargingInfo->EVCCID, "%.2x%.2x%.2x%.2x%.2x%.2x", frame.data [0],
+                            frame.data [1], frame.data [2], frame.data [3], frame.data [4], frame.data [5] );
+
+                    pDcChargingInfo->EVCCID [17] = '\0';
+                    log_info( "Gun %d->EVCCID = %s ", targetGun, pDcChargingInfo->EVCCID );
+                }
+                break;
+            default:
+                log_info("EV board = %d, Ack none defined. intCmd = %d  ", targetGun, intCmd);
+                break;
+            }//switch
+
+            usleep(10000);
+        }//while
+    }
+}

+ 1380 - 1380
EVSE/Projects/DD360Tcci/Apps/ModuleEvComm/Module_EvTxComm.c

@@ -1,1380 +1,1380 @@
-#include <stdio.h>
-#include <stdlib.h>
-#include <stdint.h>
-#include <string.h>
-#include <fcntl.h>
-#include <unistd.h>
-#include <time.h>
-
-#include <sys/ioctl.h>
-#include <sys/stat.h>
-#include <sys/timeb.h>
-#include <sys/time.h>
-
-#include <net/if.h>
-
-#include <linux/can.h>
-#include <linux/can/raw.h>
-#include <signal.h>
-
-#include "../Config.h"
-#include "../Log/log.h"
-#include "../Define/define.h"
-#include "../ShareMemory/shmMem.h"
-#include "../SelectGun/SelectGun.h"
-#include "Ev_Comm.h"
-#include "Module_EvComm.h"
-#include "../CSU/main.h"
-
-//------------------------------------------------------------------------------
-static struct SysConfigData *pSysConfig = NULL;
-static struct SysInfoData *pSysInfo = NULL;
-
-static struct FaultCodeData *pFaultCode = NULL;
-static struct AlarmCodeData *pAlarmCode = NULL;
-static struct CHAdeMOData *ShmCHAdeMOData = NULL;
-static struct GBTData *ShmGBTData = NULL;
-static struct CcsData *ShmCcsData = NULL;
-static DcCommonInfo *ShmDcCommonData = NULL;
-static SelectGunInfo *ShmSelectGunInfo = NULL;
-uint8_t deratingIndex[2];
-// 限制最大充電電壓,因應不同 type 槍線來限制
-// Chademo : 500V, 125A,
-// GB : 750, 120A
-// CCS : 950V, 120A
-//DS60-120 add
-//static double chademoVol = 5000;
-//static double ccsVol = 9500;
-//static double gbVol = 7500;
-static float maxChargingVol[2] = {0, 0};       // 限制最大充電電壓,如依照模塊則填上 0
-// 限制最大充電電流與能量透過 Web
-static float maxChargingCur[2] = {0, 0};         // 限制最大充電電流,如依照模塊則填上 0
-static float maxChargingPow = 0;                   // 限制最大充電能量,如依照模塊則填上 0
-
-static float LogInfo[2][10]; //DS60-120 add
-static int CanFd = -1;
-
-bool psuOutputReady[2] = {0, 0};
-
-//------------------------------------------------------------------------------
-extern void CANReceiver(int fd);
-extern void ClearAbnormalStatus_Chademo(uint8_t gun_index);
-extern void ClearAbnormalStatus_GB(uint8_t gun_index);
-extern void ClearAbnormalStatus_CCS(uint8_t gun_index);
-
-//------------------------------------------------------------------------------
-int GetCanFd(void)
-{
-    return CanFd;
-}
-void GetClockTime(struct timespec* _now_time, void* null)
-{
-    clock_gettime(CLOCK_MONOTONIC, _now_time);
-}
-uint32_t GetTimeoutValue(struct timeval _sour_time)
-{
-    struct timeval _end_time;
-    gettimeofday(&_end_time, NULL);
-
-    return 1000000 * (_end_time.tv_sec - _sour_time.tv_sec) + _end_time.tv_usec - _sour_time.tv_usec;
-}
-unsigned long GetClockTimeoutValue(struct timespec _start_time)
-{
-    struct timespec ts_end;
-    unsigned long ret = 0;
-
-    clock_gettime(CLOCK_MONOTONIC, &ts_end);
-
-    ret = ((unsigned long)(ts_end.tv_sec - _start_time.tv_sec) * 1000000) + ((unsigned long)((ts_end.tv_nsec / 1000) - (_start_time.tv_nsec / 1000)));
-
-    return ret;
-}
-int InitCanBus(void)
-{
-    int s0, nbytes;
-    struct timeval tv;
-    struct ifreq ifr0;
-    struct sockaddr_can addr0;
-    struct can_filter rxfilter[3];
-
-    system("/sbin/ip link set can0 down");
-    system("/sbin/ip link set can0 type can bitrate 500000 restart-ms 100");
-    system("/sbin/ip link set can0 up");
-
-    s0 = socket(PF_CAN, SOCK_RAW, CAN_RAW);
-
-    tv.tv_sec = 0;
-    tv.tv_usec = 10000;
-
-    if (setsockopt(s0, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(struct  timeval)) < 0) {
-        log_error("Set SO_RCVTIMEO NG");
-    }
-
-    nbytes = 40960;
-    if (setsockopt(s0, SOL_SOCKET,  SO_RCVBUF, &nbytes, sizeof(int)) < 0) {
-        log_error("Set SO_RCVBUF NG");
-    }
-
-    nbytes = 40960;
-    if (setsockopt(s0, SOL_SOCKET, SO_SNDBUF, &nbytes, sizeof(int)) < 0) {
-        log_error("Set SO_SNDBUF NG");
-    }
-
-    rxfilter[0].can_id = 0x01;
-    rxfilter[0].can_mask = 0x000000FF;
-    rxfilter[1].can_id = 0x02;
-    rxfilter[1].can_mask = 0x000000FF;
-    rxfilter[2].can_id = 0x01FF;
-    rxfilter[2].can_mask = 0x00000FFF;
-    if (setsockopt(s0, SOL_CAN_RAW, CAN_RAW_FILTER,
-                   &rxfilter, sizeof(struct can_filter) * 3) < 0) {
-        log_error("RX setsockopt CAN_RAW_FILTER failed");
-    }
-
-    strcpy(ifr0.ifr_name, "can0");
-    ioctl(s0, SIOCGIFINDEX, &ifr0); /* ifr.ifr_ifindex gets filled with that device's index */
-    addr0.can_family = AF_CAN;
-    addr0.can_ifindex = ifr0.ifr_ifindex;
-    bind(s0, (struct sockaddr *)&addr0, sizeof(addr0));
-
-    return s0;
-}
-
-void SetNatural200AGunOTPValue(struct DERATING_BY_OTP* deratingByConnOtp)
-{
-    memset(&deratingByConnOtp->deratingTargetRate[0], 200, sizeof(deratingByConnOtp->deratingTargetRate));
-}
-void SetNatural300AGunOTPValue(struct DERATING_BY_OTP* deratingByConnOtp)
-{
-    deratingByConnOtp->deratingTargetCurrent[0] = 500;
-    deratingByConnOtp->deratingTargetCurrent[1] = 300;
-    deratingByConnOtp->deratingTargetCurrent[2] = 100;
-    deratingByConnOtp->deratingTargetCurrent[3] = 100;
-    deratingByConnOtp->deratingTargetCurrent[4] = 100;
-}
-void SetLiquidCoolGunOTPValue(struct DERATING_BY_OTP* deratingByConnOtp)
-{
-    deratingByConnOtp->deratingTargetCurrent[0] = 500;
-    deratingByConnOtp->deratingTargetCurrent[1] = 400;
-    deratingByConnOtp->deratingTargetCurrent[2] = 300;
-    deratingByConnOtp->deratingTargetCurrent[3] = 300;
-    deratingByConnOtp->deratingTargetCurrent[4] = 300;
-}
-void SetCHAdeMoTypeJOTPValue(uint8_t regulation, struct DERATING_BY_OTP* deratingByConnOtp)
-{
-    if (regulation == 'J') {
-        memset(&deratingByConnOtp->deratingTargetRate[0], 125, sizeof(deratingByConnOtp->deratingTargetRate));
-    }
-    else {
-        memset(&deratingByConnOtp->deratingTargetRate[0], 120, sizeof(deratingByConnOtp->deratingTargetRate));
-    }
-}
-void SetCHAdeMoTypeKOTPValue(struct DERATING_BY_OTP* deratingByConnOtp)
-{
-    memset(&deratingByConnOtp->deratingTargetRate[0], 200, sizeof(deratingByConnOtp->deratingTargetRate));
-}
-
-void SetCHAdeMoTypeSJOTPValue(struct DERATING_BY_OTP* deratingByConnOtp)
-{
-    deratingByConnOtp->deratingTargetRate[0] = 1;
-    deratingByConnOtp->deratingTargetRate[1] = 0.8;
-}
-
-static void SetGunTypeOTPValue(void)
-{
-    struct ChargingInfoData* pDcChargingInfo = NULL;
-    uint8_t Gun1Type = 0;
-    uint8_t Gun2Type = 0;
-    int i;
-    if (pSysConfig->TotalConnectorCount == 1) {
-        pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(0);
-        Gun1Type = pSysConfig->ModelName[7];
-        Gun2Type = pSysConfig->ModelName[7];
-
-        switch (Gun1Type) {
-            //CHAdeMo
-        case 'J':
-            SetCHAdeMoTypeJOTPValue(pSysConfig->ModelName[3], &pDcChargingInfo->deratingByConnOtp);
-            break;
-        case 'K':
-            SetCHAdeMoTypeKOTPValue(&pDcChargingInfo->deratingByConnOtp);
-            break;
-        case 'S':
-            SetCHAdeMoTypeSJOTPValue(&pDcChargingInfo->deratingByConnOtp);
-            break;
-            // 風冷200A以下
-        case 'U':
-        case 'E':
-        case 'M':
-        case 'N':
-            SetNatural200AGunOTPValue(&pDcChargingInfo->deratingByConnOtp);
-            break;
-            // 風冷300A
-        case 'T':
-        case 'D':
-            SetNatural300AGunOTPValue(&pDcChargingInfo->deratingByConnOtp);
-            break;
-            // 水冷
-        case 'V':
-        case 'F':
-        case 'P':
-        case 'R':
-            SetLiquidCoolGunOTPValue(&pDcChargingInfo->deratingByConnOtp);
-            break;
-        }
-
-    }
-    else if (pSysConfig->TotalConnectorCount == 2) {
-        Gun1Type = pSysConfig->ModelName[7];
-        Gun2Type = pSysConfig->ModelName[9];
-        for (i = 0; i < pSysConfig->TotalConnectorCount; i++) {
-            pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(i);
-            pDcChargingInfo->deratingByConnOtp.isNeedDerating = GUNOTPDERATING;
-            switch (i == 0 ? Gun1Type : Gun2Type) {
-                //CHAdeMo
-            case 'J':
-                SetCHAdeMoTypeJOTPValue(pSysConfig->ModelName[3], &pDcChargingInfo->deratingByConnOtp);
-                break;
-            case 'K':
-                SetCHAdeMoTypeKOTPValue(&pDcChargingInfo->deratingByConnOtp);
-                break;
-            case 'S':
-                SetCHAdeMoTypeSJOTPValue(&pDcChargingInfo->deratingByConnOtp);
-                break;
-                // 風冷200A以下
-            case 'U':
-            case 'E':
-            case 'M':
-            case 'N':
-                SetNatural200AGunOTPValue(&pDcChargingInfo->deratingByConnOtp);
-                break;
-                // 風冷300A
-            case 'T':
-            case 'D':
-                SetNatural300AGunOTPValue(&pDcChargingInfo->deratingByConnOtp);
-                break;
-                // 水冷
-            case 'V':
-            case 'F':
-            case 'P':
-            case 'R':
-                SetLiquidCoolGunOTPValue(&pDcChargingInfo->deratingByConnOtp);
-                break;
-            }
-        }
-    }
-}
-
-float GetMaxChargingVol(uint8_t index)
-{
-    return maxChargingVol[index];
-}
-
-float GetMaxCharginigCur(uint8_t index)
-{
-    return maxChargingCur[index];
-}
-
-static void SendCommunicationOnly(uint8_t index)
-{
-    struct ChargingInfoData *pDcCharginigInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);
-    uint8_t targetID = pDcCharginigInfo->Evboard_id;
-/*
-    if (pSysConfig->TotalConnectorCount == 1 &&
-            pDcCharginigInfo->Type == _Type_CCS_2 &&
-            ShmDcCommonData->CcsVersion == _CCS_VERSION_CHECK_TAG_V015S0) {
-        targetID += 1;
-    }
-*/
-    SetChargingPermission(index,
-                          COMMUNICATION,
-                          pDcCharginigInfo->AvailableChargingPower,
-                          0,
-                          0,
-                          targetID);
-}
-
-static void SendStopOnly(uint8_t index)
-{
-    struct ChargingInfoData *pDcCharginigInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);
-
-    uint8_t targetID = pDcCharginigInfo->Evboard_id;
-/*
-    if (pSysConfig->TotalConnectorCount == 1 &&
-            pDcCharginigInfo->Type == _Type_CCS_2 &&
-            ShmDcCommonData->CcsVersion == _CCS_VERSION_CHECK_TAG_V015S0) {
-        targetID += 1;
-    }
-*/
-    SetChargingPermission(index,
-                          STOP,
-                          pDcCharginigInfo->AvailableChargingPower,
-                          0,
-                          0,
-                          targetID);
-}
-
-static uint8_t GetStopChargingReasonByEvse(uint8_t gunIndex, uint8_t *reason)
-{
-    uint8_t result = NO;
-    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-
-    if (pAlarmCode->AlarmEvents.bits.EmergencyStopTrip == 0x01) {
-        // 012251
-        *(reason + 5)  = 0;
-        *(reason + 4)  = 1;
-        *(reason + 3)  = 2;
-        *(reason + 2)  = 2;
-        *(reason + 1)  = 5;
-        *(reason + 0)  = 1;
-        result = YES;
-    }
-
-    if (pDcChargingInfo->Type == _Type_Chademo) {
-        if (pFaultCode->FaultEvents.bits.ChademoOutputRelayDrivingFault == YES) {
-            // 011012
-            *(reason + 5) = 0;
-            *(reason + 4) = 1;
-            *(reason + 3) = 1;
-            *(reason + 2) = 0;
-            *(reason + 1) = 1;
-            *(reason + 0) = 2;
-            result = YES;
-        } else if (pAlarmCode->AlarmEvents.bits.ChademoOutputUVPFail == YES) {
-            // 012289
-            *(reason + 5) = 0;
-            *(reason + 4) = 1;
-            *(reason + 3) = 2;
-            *(reason + 2) = 2;
-            *(reason + 1) = 8;
-            *(reason + 0) = 9;
-            result = YES;
-        } else if (pAlarmCode->AlarmEvents.bits.ChademoGfdTrip == YES) {
-            // 012234
-            *(reason + 5) = 0;
-            *(reason + 4) = 1;
-            *(reason + 3) = 2;
-            *(reason + 2) = 2;
-            *(reason + 1) = 3;
-            *(reason + 0) = 4;
-            result = YES;
-        }
-    } else if (pDcChargingInfo->Type == _Type_GB) {
-        if (pFaultCode->FaultEvents.bits.ChademoOutputRelayDrivingFault == YES) {
-            // 012290
-            *(reason + 5) = 0;
-            *(reason + 4) = 1;
-            *(reason + 3) = 2;
-            *(reason + 2) = 2;
-            *(reason + 1) = 9;
-            *(reason + 0) = 0;
-            result = YES;
-        } else if (pAlarmCode->AlarmEvents.bits.GbGfdTrip == YES) {
-            // 012236
-            *(reason + 5) = 0;
-            *(reason + 4) = 1;
-            *(reason + 3) = 2;
-            *(reason + 2) = 2;
-            *(reason + 1) = 3;
-            *(reason + 0) = 6;
-            result = YES;
-        }
-    } else if (pDcChargingInfo->Type == _Type_CCS_2) {
-        if (pFaultCode->FaultEvents.bits.CcsOutputRelayDrivingFault == YES) {
-            // 011014
-            *(reason + 5) = 0;
-            *(reason + 4) = 1;
-            *(reason + 3) = 1;
-            *(reason + 2) = 0;
-            *(reason + 1) = 1;
-            *(reason + 0) = 4;
-            result = YES;
-        } else if (pAlarmCode->AlarmEvents.bits.CcsOutputUVPFail == YES) {
-            // 012288
-            *(reason + 5) = 0;
-            *(reason + 4) = 1;
-            *(reason + 3) = 2;
-            *(reason + 2) = 2;
-            *(reason + 1) = 8;
-            *(reason + 0) = 8;
-            result = YES;
-        } else if (pAlarmCode->AlarmEvents.bits.CcsGfdTrip == YES) {
-            // 012235
-            *(reason + 5) = 0;
-            *(reason + 4) = 1;
-            *(reason + 3) = 2;
-            *(reason + 2) = 2;
-            *(reason + 1) = 3;
-            *(reason + 0) = 5;
-            result = YES;
-        }
-    }
-
-    return result;
-}
-
-static void setCurrentOutput(void)
-{
-    struct ChargingInfoData *chargingData_1 = NULL;
-    struct ChargingInfoData *chargingData_2 = NULL;
-
-    if (pSysConfig->TotalConnectorCount == 1) {
-        chargingData_1 = (struct ChargingInfoData *)GetDcChargingInfoData(0);
-        //chargingData_2 = (struct ChargingInfoData *)GetDcChargingInfoData(0);
-
-        if (chargingData_1->FireChargingVoltage <= 500) { //DS60-120 add
-            chargingData_1->PresentChargingCurrent = 0;
-        }
-
-    } else if (pSysConfig->TotalConnectorCount == 2) {
-        chargingData_1 = (struct ChargingInfoData *)GetDcChargingInfoData(0);
-        chargingData_2 = (struct ChargingInfoData *)GetDcChargingInfoData(1);
-
-        if (chargingData_1->FireChargingVoltage <= 500) { //DS60-120 add
-            chargingData_1->PresentChargingCurrent = 0;
-        }
-
-        if (chargingData_2->FireChargingVoltage <= 500) {
-            chargingData_2->PresentChargingCurrent = 0;
-        }
-    }
-}
-
-static void GetMaxVolAndCurMethod(uint8_t index, float *vol, float *cur)
-{
-    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);
-
-    if (maxChargingVol[index] != 0 && maxChargingVol[index] <= *vol) {
-        *vol = maxChargingVol[index];
-    }
-
-    if (maxChargingCur[index] != 0 && maxChargingCur[index] <= *cur) {
-        *cur = maxChargingCur[index];
-    }
-
-    if (((pDcChargingInfo->SystemStatus >= S_PREPARING_FOR_EVSE &&
-            pDcChargingInfo->SystemStatus <= S_CHARGING) ||
-            (pDcChargingInfo->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
-             pDcChargingInfo->SystemStatus <= S_CCS_PRECHARGE_ST1)) &&
-            pDcChargingInfo->ChargingProfileCurrent >= 0 &&
-            pDcChargingInfo->ChargingProfileCurrent <= *cur
-       ) {
-        *cur = pDcChargingInfo->ChargingProfileCurrent;
-    }
-}
-
-void GetOtpPwrOrCurMethod(struct ChargingInfoData* chargingData, float* pow, float* cur)
-{
-    if (((chargingData->ConnectorTemp >= STAGE1_GUN_DERATING_TEMP &&
-        chargingData->ConnectorTemp < STAGE2_GUN_DERATING_TEMP) ||
-        (chargingData->ChillerTemp >= STAGE1_GUN_DERATING_TEMP &&
-            chargingData->ChillerTemp < STAGE2_GUN_DERATING_TEMP)) &&
-        chargingData->deratingByConnOtp.deratingIndex < 1)
-    {
-        chargingData->deratingByConnOtp.deratingIndex = 1;
-    }
-    else if ((chargingData->ConnectorTemp >= STAGE2_GUN_DERATING_TEMP ||
-        chargingData->ChillerTemp >= STAGE2_GUN_DERATING_TEMP) &&
-        chargingData->ConnectorTemp != UNDEFINED_TEMP &&
-        chargingData->ChillerTemp != UNDEFINED_TEMP &&
-        chargingData->deratingByConnOtp.deratingIndex < 2)
-    {
-        chargingData->deratingByConnOtp.deratingIndex = 2;
-    }
-
-    if (chargingData->deratingByConnOtp.deratingTargetRate[chargingData->deratingByConnOtp.deratingIndex] != 0)
-    {
-        *pow *= chargingData->deratingByConnOtp.deratingTargetRate[chargingData->deratingByConnOtp.deratingIndex];
-    }
-    else if (chargingData->deratingByConnOtp.deratingTargetCurrent[chargingData->deratingByConnOtp.deratingIndex] != 0)
-    {
-        if (*cur > chargingData->deratingByConnOtp.deratingTargetCurrent[chargingData->deratingByConnOtp.deratingIndex])
-            *cur = chargingData->deratingByConnOtp.deratingTargetCurrent[chargingData->deratingByConnOtp.deratingIndex];
-    }
-}   
-
-static void SetPresentChargingOutputCap(void)
-{
-    float pow1 = 0, cur1 = 0;
-    float pow2 = 0, cur2 = 0;
-    struct ChargingInfoData *chargingData_1 = NULL;
-    struct ChargingInfoData *chargingData_2 = NULL;
-    struct PrimaryMcuData* ShmPrimaryMcuData = (struct PrimaryMcuData*)GetShmPrimaryMcuData();
-
-    if (pSysConfig->TotalConnectorCount == 1) {
-        chargingData_1 = (struct ChargingInfoData *)GetDcChargingInfoData(0);
-        chargingData_2 = (struct ChargingInfoData *)GetDcChargingInfoData(0);
-    } else if (pSysConfig->TotalConnectorCount == 2) {
-        chargingData_1 = (struct ChargingInfoData *)GetDcChargingInfoData(0);
-        chargingData_2 = (struct ChargingInfoData *)GetDcChargingInfoData(1);
-    }
-/*
-#if !defined DD360Tcci && !defined DD360Audi && !defined DD360ComBox && !defined DD360UCar
-    float vol = 0;
-#endif //!defined DD360Tcci && !defined DD360Audi
-*/
-    pow1 = chargingData_1->AvailableChargingPower;
-    cur1 = chargingData_1->AvailableChargingCurrent;
-/*
-#if !defined DD360Tcci && !defined DD360Audi && !defined DD360ComBox && !defined DD360UCar
-    vol = chargingData_1->MaximumChargingVoltage;
-    GetMaxVolAndCurMethod(chargingData_1->Index, &vol, &cur1);
-    //GetMaxPowerMethod(chargingData_1->Index, &pow1);
-#endif //!defined DD360Tcci && !defined DD360Audi
-*/
-    if (pow1 <= 0) {
-        cur1 = 0;
-    } else {
-        if (chargingData_1->SystemStatus == S_CHARGING &&
-                chargingData_1->FireChargingVoltage > 1500) {
-            float maxCur = 0;
-            maxCur = (pow1 * 1000) / chargingData_1->FireChargingVoltage;
-
-            if (maxCur * 10 <= cur1) {
-                //log_info("Gun1 -> MaxCharging Current = %f, Cap Current = %f ", (maxCur * 10), cur1);
-                cur1 = maxCur * 10;
-            }
-        }
-    }
-
-    if (chargingData_1->deratingByConnOtp.isNeedDerating) {
-        GetOtpPwrOrCurMethod(chargingData_1, &pow1, &cur1);
-        if (deratingIndex[0] != chargingData_1->deratingByConnOtp.deratingIndex) {
-            log_info("Gun0 Derating Index Set %d", chargingData_1->deratingByConnOtp.deratingIndex);
-            deratingIndex[0] = chargingData_1->deratingByConnOtp.deratingIndex;
-        }
-    }
-
-    pow2 = chargingData_2->AvailableChargingPower;
-    cur2 = chargingData_2->AvailableChargingCurrent;
-    /*
-#if !defined DD360Tcci && !defined DD360Audi && !defined DD360ComBox && !defined DD360UCar
-    vol = chargingData_2->MaximumChargingVoltage;
-    GetMaxVolAndCurMethod(chargingData_2->Index, &vol, &cur2);
-    //GetMaxPowerMethod(chargingData_2->Index, &pow2);
-#endif //!defined DD360Tcci && !defined DD360Audi
-*/
-    if (pow2 <= 0) {
-        cur2 = 0;
-    } else {
-        if (chargingData_2->SystemStatus == S_CHARGING &&
-                chargingData_2->FireChargingVoltage > 1500) {
-            float maxCur = 0;
-            maxCur = (pow2 * 1000) / chargingData_2->FireChargingVoltage;
-
-            if (maxCur * 10 <= cur2) {
-                //log_info("Gun2 -> MaxCharging Current = %f, Cap Current = %f ", (maxCur * 10), cur2);
-                cur2 = maxCur * 10;
-            }
-        }
-    }
-    if (chargingData_2->deratingByConnOtp.isNeedDerating) {
-        GetOtpPwrOrCurMethod(chargingData_2, &pow2, &cur2);
-        if (deratingIndex[1] != chargingData_2->deratingByConnOtp.deratingIndex) {
-            log_info("Gun1 Derating Index Set %d", chargingData_2->deratingByConnOtp.deratingIndex);
-            deratingIndex[1] = chargingData_2->deratingByConnOtp.deratingIndex;
-        }
-    }
-    if (ShmPrimaryMcuData->InputDet.bits.Ac_Drop == ABNORMAL) {
-        if (cur1 > 1500) {
-            log_info("Gun0 chiller alarm set current less than 150A");
-            cur1 = 1500;
-        }
-        if (cur2 > 1500) {
-            log_info("Gun1 chiller alarm set current less than 150A");
-            cur2 = 1500;
-        }
-    }
-    //DS60-120 add
-    if ((LogInfo[0][EV_LOG_OUTPUT_CAP_POW] <= pow1 - 5 ||
-            LogInfo[0][EV_LOG_OUTPUT_CAP_POW] >= pow1 + 5) ||
-            (LogInfo[0][EV_LOG_OUTPUT_CAP_CUR] <= cur1 - 5 ||
-             LogInfo[0][EV_LOG_OUTPUT_CAP_CUR] >= cur1 + 5) ||
-            (LogInfo[1][EV_LOG_OUTPUT_CAP_POW] <= pow2 - 5 ||
-             LogInfo[1][EV_LOG_OUTPUT_CAP_POW] >= pow2 + 5) ||
-            (LogInfo[1][EV_LOG_OUTPUT_CAP_CUR] <= cur2 - 5 ||
-             LogInfo[1][EV_LOG_OUTPUT_CAP_CUR] >= cur2 + 5)
-       ) {
-        //log_info("----------------------------------------------------- ");
-        log_info("To EV (Real) Power_1 = %.1f, Cur_1 = %.1f, Power_2 = %.1f, Cur_2 = %.1f",
-                 pow1 / 10, cur1 / 10, pow2 / 10, cur2 / 10);
-        //log_info("----------------------------------------------------- ");
-
-        LogInfo[0][EV_LOG_OUTPUT_CAP_POW] = pow1;
-        LogInfo[0][EV_LOG_OUTPUT_CAP_CUR] = cur1;
-        LogInfo[1][EV_LOG_OUTPUT_CAP_POW] = pow2;
-        LogInfo[1][EV_LOG_OUTPUT_CAP_CUR] = cur2;
-        chargingData_1->RealMaxCurrent = cur1;
-        chargingData_1->RealMaxPower = pow1;
-
-        if (pSysConfig->TotalConnectorCount == 2) {
-            chargingData_2->RealMaxCurrent = cur2;
-            chargingData_2->RealMaxPower = pow2;
-        }
-    }
-    if (pSysConfig->TotalConnectorCount == 2) {
-        chargingData_2->RealMaxCurrent = cur2;
-        chargingData_2->RealMaxPower = pow2;
-    }
-    SetPresentOutputCapacity(pow1, cur1, pow2, cur2);
-}
-/*
-static uint8_t waitPsuVolwithRealyVol(uint8_t gunIndex)
-{
-    PcPsuOutput *pPcPsuOutput = (PcPsuOutput *)&ShmDcCommonData->PcPsuOutput[gunIndex];
-    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-    int vol = 0;
-
-    vol = abs(pPcPsuOutput->Voltage - pDcChargingInfo->FireChargingVoltage);
-    if (vol <= 10) {
-        return YES;
-    }
-
-    return NO;
-}
-*/
-/**
- * [SetPresentChargingOutputFromPcPsu 充電狀態讀取電源櫃PSU輸出電壓電流,縮小誤差值]
- * @Author   Jerry
- * @DateTime 2021-07-05
- */
-/*
-static void SetPresentChargingOutputFromPcPsu(uint8_t gunCount)
-{
-    float vol1 = 0, cur1 = 0;
-    float vol2 = 0, cur2 = 0;
-    PcPsuOutput *pPcPsuOutput0 = NULL;
-    PcPsuOutput *pPcPsuOutput1 = NULL;
-    struct ChargingInfoData *chargingData0 = NULL;
-    struct ChargingInfoData *chargingData1 = NULL;
-
-    switch (gunCount) {
-    case 1:
-        pPcPsuOutput0 = (PcPsuOutput *)&ShmDcCommonData->PcPsuOutput[0];
-        pPcPsuOutput1 = (PcPsuOutput *)&ShmDcCommonData->PcPsuOutput[0];
-        chargingData0 = (struct ChargingInfoData *)GetDcChargingInfoData(0);
-        chargingData1 = (struct ChargingInfoData *)GetDcChargingInfoData(0);
-        break;
-
-    case 2:
-        pPcPsuOutput0 = (PcPsuOutput *)&ShmDcCommonData->PcPsuOutput[0];
-        pPcPsuOutput1 = (PcPsuOutput *)&ShmDcCommonData->PcPsuOutput[1];
-        chargingData0 = (struct ChargingInfoData *)GetDcChargingInfoData(0);
-        chargingData1 = (struct ChargingInfoData *)GetDcChargingInfoData(1);
-        break;
-    }
-
-    vol1 = pPcPsuOutput0->Voltage == 0 ? chargingData0->FireChargingVoltage : (((float)pPcPsuOutput0->Voltage));
-    cur1 = (chargingData0->PresentChargingCurrent * 10);//(((float)pPcPsuOutput0->Current) * 0.1);
-    vol2 = pPcPsuOutput1->Voltage == 0 ? chargingData1->FireChargingVoltage : (((float)pPcPsuOutput1->Voltage));
-    cur2 = (chargingData1->PresentChargingCurrent * 10);//(((float)pPcPsuOutput1->Current) * 0.1);
-
-    if (
-        (LogInfo[0][EV_LOG_NOW_OUTPUT_VOL] >= vol1 + CHK_VOL_RANGE) ||
-        (LogInfo[0][EV_LOG_NOW_OUTPUT_VOL] <= vol1 - CHK_VOL_RANGE) ||
-        (LogInfo[0][EV_LOG_NOW_OUTPUT_CUR] >= cur1 + CHK_CUR_RANGE) ||
-        (LogInfo[0][EV_LOG_NOW_OUTPUT_CUR] <= cur1 - CHK_CUR_RANGE) ||
-        (LogInfo[1][EV_LOG_NOW_OUTPUT_VOL] >= vol2 + CHK_VOL_RANGE) ||
-        (LogInfo[1][EV_LOG_NOW_OUTPUT_VOL] <= vol2 - CHK_VOL_RANGE) ||
-        (LogInfo[1][EV_LOG_NOW_OUTPUT_CUR] >= cur2 + CHK_CUR_RANGE) ||
-        (LogInfo[1][EV_LOG_NOW_OUTPUT_CUR] <= cur2 - CHK_CUR_RANGE)
-    ) {
-        log_info("G1->Out Vol=%.1f,Out Cur=%.1f - G2->Out Vol=%.1f,Out Cur=%.1f",
-                 vol1,
-                 cur1 / 10,
-                 vol2,
-                 cur2 / 10);
-
-        LogInfo[0][EV_LOG_NOW_OUTPUT_VOL] = vol1;
-        LogInfo[0][EV_LOG_NOW_OUTPUT_CUR] = cur1;
-        LogInfo[1][EV_LOG_NOW_OUTPUT_VOL] = vol2;
-        LogInfo[1][EV_LOG_NOW_OUTPUT_CUR] = cur2;
-    }
-
-    SetPresentOutputPower(vol1, cur1, vol2, cur2);
-}
-*/
-static void SetPresentChargingOutputPower(void)
-{
-    float vol1 = 0, cur1 = 0;
-    float vol2 = 0, cur2 = 0;
-    PcPsuOutput *pPcPsuOutput1 = NULL;
-    PcPsuOutput *pPcPsuOutput2 = NULL;
-    struct ChargingInfoData *chargingData_1 = NULL;
-    struct ChargingInfoData *chargingData_2 = NULL;
-    bool isPsuVol1 = false, isPsuVol2 = false, isPsuCur1 = false, isPsuCur2 = false;
-
-    if (pSysConfig->TotalConnectorCount == 1) {
-        pPcPsuOutput1 = (PcPsuOutput *)&ShmDcCommonData->PcPsuOutput[0];
-        pPcPsuOutput2 = (PcPsuOutput *)&ShmDcCommonData->PcPsuOutput[0];
-        chargingData_1 = (struct ChargingInfoData *)GetDcChargingInfoData(0);
-        chargingData_2 = (struct ChargingInfoData *)GetDcChargingInfoData(0);
-    } else if (pSysConfig->TotalConnectorCount == 2) {
-        pPcPsuOutput1 = (PcPsuOutput *)&ShmDcCommonData->PcPsuOutput[0];
-        pPcPsuOutput2 = (PcPsuOutput *)&ShmDcCommonData->PcPsuOutput[1];
-        chargingData_1 = (struct ChargingInfoData *)GetDcChargingInfoData(0);
-        chargingData_2 = (struct ChargingInfoData *)GetDcChargingInfoData(1);
-    }
-
-    psuOutputReady[0] = chargingData_1->SystemStatus != S_CHARGING ? false : psuOutputReady[0];
-    psuOutputReady[1] = chargingData_2->SystemStatus != S_CHARGING ? false : psuOutputReady[1];
-
-    isPsuVol1 = chargingData_1->PantographFlag ? true : (pPcPsuOutput1->Voltage != 0 && psuOutputReady[0] == true);
-    isPsuVol2 = chargingData_2->PantographFlag ? true : (pPcPsuOutput2->Voltage != 0 && psuOutputReady[1] == true);
-    isPsuCur1 = chargingData_1->PantographFlag ? true : false;
-    isPsuCur2 = chargingData_2->PantographFlag ? true : false;
-
-    //vol1 = chargingData_1->FireChargingVoltage;
-    vol1 = isPsuVol1 == false ? chargingData_1->FireChargingVoltage : (((float)pPcPsuOutput1->Voltage));
-    cur1 = isPsuCur1 == false ? (chargingData_1->PresentChargingCurrent * 10) : pPcPsuOutput1->Current;
-    //vol2 = chargingData_2->FireChargingVoltage;
-    vol2 = isPsuVol2 == false ? chargingData_2->FireChargingVoltage : (((float)pPcPsuOutput2->Voltage));
-    cur2 = isPsuCur2 == false ? (chargingData_2->PresentChargingCurrent * 10) : pPcPsuOutput2->Current;
-
-    //DS60-120 add
-    if ((LogInfo[0][EV_LOG_NOW_OUTPUT_VOL] >= vol1 + CHK_VOL_RANGE) ||
-            (LogInfo[0][EV_LOG_NOW_OUTPUT_VOL] <= vol1 - CHK_VOL_RANGE) ||
-            (LogInfo[0][EV_LOG_NOW_OUTPUT_CUR] >= cur1 + CHK_CUR_RANGE) ||
-            (LogInfo[0][EV_LOG_NOW_OUTPUT_CUR] <= cur1 - CHK_CUR_RANGE) ||
-            (LogInfo[1][EV_LOG_NOW_OUTPUT_VOL] >= vol2 + CHK_VOL_RANGE) ||
-            (LogInfo[1][EV_LOG_NOW_OUTPUT_VOL] <= vol2 - CHK_VOL_RANGE) ||
-            (LogInfo[1][EV_LOG_NOW_OUTPUT_CUR] >= cur2 + CHK_CUR_RANGE) ||
-            (LogInfo[1][EV_LOG_NOW_OUTPUT_CUR] <= cur2 - CHK_CUR_RANGE)
-       ) {
-        log_info("G1-> Vol=%.1f, Cur=%.1f - G2-> Vol = %.1f, Cur = %.1f",
-                 vol1 / 10,
-                 cur1 / 10,
-                 vol2 / 10,
-                 cur2 / 10);
-
-        LogInfo[0][EV_LOG_NOW_OUTPUT_VOL] = vol1;
-        LogInfo[0][EV_LOG_NOW_OUTPUT_CUR] = cur1;
-        LogInfo[1][EV_LOG_NOW_OUTPUT_VOL] = vol2;
-        LogInfo[1][EV_LOG_NOW_OUTPUT_CUR] = cur2;
-    }
-    //if (_outVol_1 != vol1 ||
-    //        _outCur_1 != cur1 ||
-    //        _outVol_2 != vol2 ||
-    //        _outCur_2 != cur2) {
-    /*log_info("G1 -> Output Vol = %f, Output Cur = %f -- G2 -> Output Vol = %f, Output Cur = %f ",
-        vol1, cur1, vol2, cur2);
-    */
-    //    _outVol_1 = vol1; _outCur_1 = cur1; _outVol_2 = vol2; _outCur_2 = cur2;
-    //}
-
-    SetPresentOutputPower(vol1, cur1, vol2, cur2);
-}
-/*
-static void checkConnectorOVPState(uint8_t gunIndex)
-{
-    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-    // 避免槍溫偵測誤判
-    static uint8_t gunTempAllowCount[2] = {0};
-
-    bool isOTP = false;
-
-    switch (pDcChargingInfo->Type) {
-    case _Type_Chademo:
-        if (ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaConnectOTP) {
-            isOTP = true;
-        }
-        break;
-
-    case _Type_CCS_2:
-        if (ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSConnectOTP) {
-            isOTP = true;
-        }
-        break;
-
-    case _Type_GB:
-        if (ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTConnectOTP) {
-            isOTP = true;
-        }
-        break;
-    }
-
-    if (ShmDcCommonData->ChillerTempErr[gunIndex].StatusBit.ChillerOTP == YES) {
-        isOTP = true;
-    }
-
-    if (isOTP) {
-        if (gunTempAllowCount[gunIndex] >= 2) {
-            pDcChargingInfo->StopChargeFlag = YES;
-        } else {
-            gunTempAllowCount[gunIndex] += 1;
-        }
-    } else {
-        gunTempAllowCount[gunIndex] = 0;
-    }
-}
-*/
-static time_t GetRtcInfoForEpoch(void)
-{
-    struct timeb csuTime;
-    struct tm *tmCSU;
-    struct tm t;
-    time_t result;
-
-    ftime(&csuTime);
-    tmCSU = localtime(&csuTime.time);
-
-    t.tm_year = tmCSU->tm_year;
-    t.tm_mon = tmCSU->tm_mon;
-    t.tm_mday = tmCSU->tm_mday;
-    t.tm_hour = tmCSU->tm_hour;
-    t.tm_min = tmCSU->tm_min;
-    t.tm_sec = tmCSU->tm_sec;
-    t.tm_isdst = -1;
-    result = mktime(&t);
-
-    return result;
-}
-
-static void FormatVoltageAndCurrent(void)
-{
-    uint8_t gunIndex = 0;
-    ParsingRatedCur parsingRatedCur = {0};
-    RateCurInfo *pRatedCurInfo = NULL;
-
-    if (RatedCurrentParsing((char *)pSysConfig->ModelName, &parsingRatedCur) != PASS) {
-        log_error("Parsing rated current failed");
-        return;
-    }
-
-    maxChargingPow = parsingRatedCur.Power;
-
-    for (gunIndex = 0; gunIndex < pSysConfig->TotalConnectorCount; gunIndex++) {
-        pRatedCurInfo = (RateCurInfo *)&parsingRatedCur.ParsingInfo[gunIndex];
-
-        maxChargingVol[gunIndex] = pRatedCurInfo->Voltage;
-        maxChargingCur[gunIndex] = pRatedCurInfo->Current;
-
-        log_info("Conn %d GunType = %d, MaxVol = %f, MaxCur = %f ",
-                 gunIndex,
-                 pRatedCurInfo->GunType,
-                 maxChargingVol[gunIndex],
-                 maxChargingCur[gunIndex]);
-    }
-}
-
-static 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;
-}
-
-int main(int argc, char *argv[])
-{
-    bool chkChademoPermission[2] = {false};
-    int isContinue = 1;
-    uint8_t gunIndex = 0;
-    uint8_t typeIndex = 0;
-    uint8_t priorityLow = 1;
-    uint8_t SendErrorCount[2] = {0, 0};
-    uint8_t gfgResult = 0;
-    uint32_t _timeBuf = 0;
-    uint32_t chargingTime[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY] = {0};
-    float maxVol, maxCur;
-    struct timespec _chk_ratingPower_timeout[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
-    struct timespec _chk_chademo_permission_timeout[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
-    time_t rtc = {0};
-    struct ChargingInfoData *pDcChargingInfo = NULL;
-    struct timeb waitChargingTime;
-    struct timeb nowTime;
-    uint8_t Comcont = 0;
-    uint8_t evstatus;
-
-    if (CreateAllCsuShareMemory() == FAIL) {
-        log_error("create share memory error");
-        return FAIL;
-    }
-
-    MappingGunChargingInfo("EvComm Task");
-
-    pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
-    pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
-    pAlarmCode = (struct AlarmCodeData *)GetShmAlarmCodeData();
-    pFaultCode = (struct FaultCodeData *)GetShmFaultCodeData();
-    ShmDcCommonData = (DcCommonInfo *)GetShmDcCommonData();
-    ShmCHAdeMOData = (struct CHAdeMOData *)GetShmCHAdeMOData();
-    ShmGBTData = (struct GBTData *)GetShmGBTData();
-    ShmCcsData = (struct CcsData *)GetShmCcsData();
-    ShmSelectGunInfo = (SelectGunInfo *)GetShmSelectGunInfo();
-
-    CanFd = InitCanBus();
-
-    FormatVoltageAndCurrent();
-
-    signal(SIGCHLD,SIG_IGN);
-    
-    CANReceiver(CanFd);
-
-    //SetGunTypeOTPValue();
-
-    rtc = GetRtcInfoForEpoch();
-
-    while (isContinue) {
-        for (gunIndex = 0; gunIndex < pSysConfig->TotalConnectorCount; gunIndex++) {
-            pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-            typeIndex = pDcChargingInfo->type_index;
-
-            if (priorityLow == 1) {
-                // 優先權較低 - 只要有回應即不會再詢問
-                if (pDcChargingInfo->Type == _Type_Chademo &&
-                        ShmCHAdeMOData->evse[typeIndex].SelfTest_Comp != PASS) {
-                    SyncRtcInfo(gunIndex, pDcChargingInfo->Evboard_id, (int)rtc);
-                    GetFirmwareVersion(gunIndex, pDcChargingInfo->Evboard_id);
-                } else if (pDcChargingInfo->Type == _Type_GB &&
-                           ShmGBTData->evse[typeIndex].SelfTest_Comp != PASS) {
-                    SyncRtcInfo(gunIndex, pDcChargingInfo->Evboard_id, (int)rtc);
-                    GetFirmwareVersion(gunIndex, pDcChargingInfo->Evboard_id);
-                } else if (pDcChargingInfo->Type == _Type_CCS_2) {
-                    if (ShmCcsData->CommProtocol == _CCS_COMM_V2GMessage_DIN70121 &&
-                            ShmCcsData->V2GMessage_DIN70121[typeIndex].SelfTest_Comp != PASS) {
-                        SyncRtcInfo(gunIndex, pDcChargingInfo->Evboard_id, (int)rtc);
-                        GetFirmwareVersion(gunIndex, pDcChargingInfo->Evboard_id);
-                    }
-                }
-                /*
-                if (pDcChargingInfo->Type == _Type_Chademo) {
-                    pAlarmCode->AlarmEvents.bits.ChademoboardStestFail = 
-                        (ShmCHAdeMOData->evse[typeIndex].SelfTest_Comp != PASS) ? true : false;
-                    pAlarmCode->AlarmEvents.bits.ChademoModuleCommFail =
-                        ( CanFd < 0 ) ? true : false;
-                } else if (pDcChargingInfo->Type == _Type_GB) {
-                    pAlarmCode->AlarmEvents.bits.GbtboardStestFail = 
-                        (ShmGBTData->evse[typeIndex].SelfTest_Comp != PASS) ? true : false;
-                    pAlarmCode->AlarmEvents.bits.mFail =
-                        ( CanFd < 0 ) ? true : false;
-                } else if (pDcChargingInfo->Type == _Type_CCS_2) {
-                    pAlarmCode->AlarmEvents.bits.CCSboardStestFail = 
-                        (ShmCcsData->V2GMessage_DIN70121[typeIndex].SelfTest_Comp != PASS) ? true : false;
-                    pAlarmCode->AlarmEvents.bits.ChademoModuleCommFail =
-                        ( CanFd < 0 ) ? true : false;
-                        
-                }*/
-                //固定要取得的資訊 : 1.槍鎖狀態, 2."Connector 1" 溫度, 3."Connector 2" 溫度, 4.Pilot Voltage
-                //log_info("GetMiscellaneousInfo. index = %d, Eid = %d ",
-                //         gunIndex,
-                //         pDcChargingInfo->Evboard_id);
-                GetMiscellaneousInfo(gunIndex,
-                                     pDcChargingInfo->RelayK1K2Status,
-                                     pDcChargingInfo->PresentChargedEnergy,
-                                     (pDcChargingInfo->PresentChargingVoltage * 10),
-                                     pDcChargingInfo->Evboard_id);
-
-                //checkConnectorOVPState(gunIndex);
-            }
-
-            switch (pDcChargingInfo->SystemStatus) {
-            case S_IDLE:
-            case S_AUTHORIZING:
-            case S_RESERVATION:
-                if (pDcChargingInfo->Type == _Type_Chademo) {
-
-                    ClearAbnormalStatus_Chademo(gunIndex);
-                    if (pSysInfo->PageIndex == _PAGE_PLUGIN) {
-                        if (!chkChademoPermission[gunIndex]) {
-                            chkChademoPermission[gunIndex] = true;
-                            GetClockTime(&_chk_chademo_permission_timeout[gunIndex], NULL);
-                            SendCommunicationOnly(gunIndex);
-                        } else {
-                            _timeBuf = GetClockTimeoutValue(_chk_chademo_permission_timeout[gunIndex]);
-
-                            if (_timeBuf < 0) {
-                                GetClockTime(&_chk_chademo_permission_timeout[gunIndex], NULL);
-                            } else {
-                                if (_timeBuf / 1000 > 10000) {
-                                    SendCommunicationOnly(gunIndex);
-                                    GetClockTime(&_chk_chademo_permission_timeout[gunIndex], NULL);
-                                }
-                            }
-                        }
-                    } else if (chkChademoPermission[gunIndex]) {
-                        chkChademoPermission[gunIndex] = false;
-                        SendStopOnly(gunIndex);
-                    }
-
-                    if (ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaConnectOTP == NO) {
-                        pDcChargingInfo->StopChargeFlag = NO;
-                    }
-                } else if (pDcChargingInfo->Type == _Type_GB) {
-                    ClearAbnormalStatus_GB(gunIndex);
-
-                    if (ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTConnectOTP == NO) {
-                        pDcChargingInfo->StopChargeFlag = NO;
-                    }
-                } else if (pDcChargingInfo->Type == _Type_CCS_2) {
-                    ClearAbnormalStatus_CCS(gunIndex);
-
-                    if (ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSConnectOTP == NO) {
-                        pDcChargingInfo->StopChargeFlag = NO;
-                    }
-                }
-                // Set Ev board in communication mode
-                // Get EVCCID for authorize when gun plug-in only for CCS
-                if ( pDcChargingInfo->ConnectorPlugIn && pSysConfig->isAuthrizeByEVCCID &&
-                        ShmCcsData->CommProtocol == _CCS_COMM_V2GMessage_DIN70121) {
-                    if (Comcont == 1 && evstatus < 15) {
-                        GetEVCCIDReq(gunIndex,pDcChargingInfo->Evboard_id);
-                        SendCommunicationOnly(gunIndex);
-                    } 
-                }
-                if (ShmCcsData->CommProtocol == _CCS_COMM_V2GMessage_DIN70121 && priorityLow == 1) {
-                    GetOutputReq(gunIndex,pDcChargingInfo->Evboard_id);
-                    if (evstatus != ShmCcsData->V2GMessage_DIN70121[pDcChargingInfo->type_index].PresentMsgFlowStatus) {
-                        evstatus = ShmCcsData->V2GMessage_DIN70121[pDcChargingInfo->type_index].PresentMsgFlowStatus;
-                    }
-                    if ( evstatus > 19 && evstatus < 255 )
-                        GetEVCCIDReq(gunIndex,pDcChargingInfo->Evboard_id);
-                }
-                if (priorityLow == 1) {
-                    pDcChargingInfo->PresentChargedEnergy   = 0;
-                    pDcChargingInfo->PresentChargingPower   = 0;
-                    pDcChargingInfo->GroundFaultStatus      = GFD_WAIT;
-                    pDcChargingInfo->RealRatingPower        = 0;
-                    pDcChargingInfo->StopChargeFlag         = NO;
-                    pDcChargingInfo->NormalStopChargeFlag   = NO;//DS60-120 add
-                    pDcChargingInfo->ChargingFee            = 0.0;
-                    pDcChargingInfo->EvBatterySoc           = 0;
-                    pDcChargingInfo->EvBatteryStartSoc      = 0; //DS60-120 add
-                    pDcChargingInfo->EvBatteryMaxVoltage    = 0; //DS60-120 add
-                    pDcChargingInfo->ChargingProfilePower   = -1; //DS60-120 add
-                    pDcChargingInfo->ChargingProfileCurrent = -1; //DS60-120 add
-
-                    if (pSysInfo->MainChargingMode == _MAIN_CHARGING_MODE_MAX) { //DS60-120 add
-                        pDcChargingInfo->PresentChargingVoltage = 0;
-                        pDcChargingInfo->PresentChargingCurrent = 0;
-                        pDcChargingInfo->EvBatteryMaxVoltage = 0;
-                    }
-
-                    chargingTime[gunIndex] = 0;
-                    //maxChargingCur[gunIndex] = pSysConfig->MaxChargingCurrent * 10;
-                    //maxChargingPow = (pSysConfig->MaxChargingPower * 10);
-                    //DS60-120 add
-                    SendErrorCount[gunIndex] = 0;
-
-                    //maxChargingPow = pSysConfig->MaxChargingPower * 10;
-                    // ShmPsuData->SystemAvailablePower 已是 * 10
-                    //maxChargingPow = ShmPsuData->SystemAvailablePower;
-                    if (pSysConfig->MaxChargingPower * 10 != 0 &&
-                            pSysConfig->MaxChargingPower * 10 < maxChargingPow) {
-                        maxChargingPow = pSysConfig->MaxChargingPower * 10;
-                    }
-
-                    LogInfo[gunIndex][EV_LOG_EVSE_MAX_VOL] = 0;
-                    LogInfo[gunIndex][EV_LOG_EVSE_MAX_CUR] = 0;
-                    LogInfo[gunIndex][EV_LOG_MAX_BATT_VOL] = 0;
-                    LogInfo[gunIndex][EV_LOG_SOC] = 0;
-
-                    SetPresentChargingOutputPower();
-                }
-                break;
-
-            case S_PREPARNING:
-                chkChademoPermission[gunIndex] = false; //DS60-120 add
-                // 設定當前輸出
-                SetPresentChargingOutputPower();
-
-                pDcChargingInfo->PowerConsumption = 0;
-                break;
-
-            case S_PREPARING_FOR_EV:
-                // 開始確認車端是否同意開始充電 : 1.SOC, 2.Target Vol, 3.Target Cur, 4.Charging remaining time
-                GetOutputReq(gunIndex, pDcChargingInfo->Evboard_id);
-
-                //log_info("PresentChargingVoltage = %f ", pDcChargingInfo->PresentChargingVoltage);
-                //log_info("PresentChargingCurrent = %f ", pDcChargingInfo->PresentChargingCurrent);
-                //log_info("AvailableChargingPower = %f ", pDcChargingInfo->AvailableChargingPower);
-                //log_info("AvailableChargingCurrent = %f ", pDcChargingInfo->AvailableChargingCurrent);
-                //log_info("MaximumChargingVoltage = %f ", pDcChargingInfo->MaximumChargingVoltage);
-
-                // 設定當前輸出
-                SetPresentChargingOutputPower();
-
-                if (ShmSelectGunInfo->WaitDoCommPermission[gunIndex] == YES) {
-                    ShmSelectGunInfo->WaitDoCommPermission[gunIndex] = NO;
-                    //if (priorityLow == 1) {
-                    // 樁端輸出能力
-                    maxVol = pDcChargingInfo->MaximumChargingVoltage;
-                    maxCur = pDcChargingInfo->AvailableChargingCurrent;
-
-                    GetMaxVolAndCurMethod(gunIndex, &maxVol, &maxCur);
-
-                    //DS60-120 add
-                    if (LogInfo[gunIndex][EV_LOG_EVSE_MAX_VOL] != maxVol ||
-                            LogInfo[gunIndex][EV_LOG_EVSE_MAX_CUR] != maxCur) {
-                        LogInfo[gunIndex][EV_LOG_EVSE_MAX_VOL] = maxVol;
-                        LogInfo[gunIndex][EV_LOG_EVSE_MAX_CUR] = maxCur;
-
-                        log_info("To EV_%d Max_Vol = %.1f, Cap_Cur = %.1f, Cap_Pow = %.1f",
-                                 gunIndex,
-                                 maxVol / 10,
-                                 maxCur / 10,
-                                 pDcChargingInfo->AvailableChargingPower / 10);
-                    }
-
-                    pDcChargingInfo->RealMaxVoltage = maxVol;
-
-                    SetChargingPermission(gunIndex,
-                                          START,
-                                          pDcChargingInfo->AvailableChargingPower,
-                                          maxCur,
-                                          maxVol,
-                                          pDcChargingInfo->Evboard_id);
-
-                    // 取得車端電池資訊 : 1.AC or DC ? 2.Total battery cap, 3.Max battery vol, 4.Max battery cur
-                    GetEvBatteryInfo(gunIndex, pDcChargingInfo->Evboard_id);
-                }
-
-                GetClockTime(&_chk_ratingPower_timeout[gunIndex], NULL);
-                break;
-
-            case S_PREPARING_FOR_EVSE:
-            case S_CCS_PRECHARGE_ST0:
-            case S_CCS_PRECHARGE_ST1:
-                // 開始確認車端是否同意開始充電
-                GetOutputReq(gunIndex, pDcChargingInfo->Evboard_id);
-
-                // 設定當前輸出
-                SetPresentChargingOutputPower();
-
-                if (priorityLow % 5 == 1) {
-                    // 取得車端電池資訊 : 1.AC or DC ? 2.Total battery cap, 3.Max battery vol, 4.Max battery cur
-                    GetEvBatteryInfo(gunIndex, pDcChargingInfo->Evboard_id); //DS60-120 add
-
-                    // 樁端輸出能力改變
-                    SetPresentChargingOutputCap();
-                }
-
-                //DS60-120 add
-                if (LogInfo[gunIndex][EV_LOG_MAX_BATT_VOL] != pDcChargingInfo->EvBatteryMaxVoltage) {
-                    LogInfo[gunIndex][EV_LOG_MAX_BATT_VOL] = pDcChargingInfo->EvBatteryMaxVoltage;
-                    log_info("index = %d, Ev Maximum Battery Voltage = %f ",
-                             gunIndex,
-                             pDcChargingInfo->EvBatteryMaxVoltage);
-                }
-
-                if (LogInfo[gunIndex][EV_LOG_SOC] != pDcChargingInfo->EvBatterySoc) {
-                    LogInfo[gunIndex][EV_LOG_SOC] = pDcChargingInfo->EvBatterySoc;
-                    log_info("index = %d, SOC = %d ",
-                             gunIndex,
-                             pDcChargingInfo->EvBatterySoc);
-                }
-
-                // 持續通知 Isolation 測試狀態
-                if (priorityLow == 1) {
-                    // 拉 500 V 如果在一秒鐘內 GFD 都符合則 PASS
-//                      if (_chargingData[_index]->FireChargingVoltage >= 3500)
-//                         pDcChargingInfo->GroundFaultStatus = GFD_PASS;
-
-                    //log_info("To EV_%d GFD = %d ",   _index,pDcChargingInfo->GroundFaultStatus);
-                    //if(_chargingData[_index]->GroundFaultStatus != GFD_WAIT)
-                    {
-                        //if ((GetClockTimeoutValue(_derating_time) / 1000) > 1000)
-                        gfgResult = pDcChargingInfo->GroundFaultStatus;
-
-                        // GB & Chademo ~ Warning 也先算 Pass,因為 CCS 認證會驗 Warning 故不可更動
-                        if (pDcChargingInfo->Type == _Type_Chademo ||
-                                pDcChargingInfo->Type == _Type_GB) {
-                            if (gfgResult == GFD_WARNING) {
-                                gfgResult = GFD_PASS;
-                            }
-                        }
-
-                        if (gfgResult == GFD_WARNING || gfgResult == GFD_PASS) {
-                            if (((GetClockTimeoutValue(_chk_ratingPower_timeout[gunIndex]) / 1000) > 12000 &&
-                                    pDcChargingInfo->RealRatingPower > 0) ||
-                                    (GetClockTimeoutValue(_chk_ratingPower_timeout[gunIndex]) / 1000) > 14000) {
-                                //log_info("**********EvComm : gunIndex= %d, RealRatingPower = %d ",
-                                //            gunIndex,pDcChargingInfo->RealRatingPower);
-                                //gfgResult = GFD_PASS;
-
-                                //DS60-120 add
-                                if (LogInfo[gunIndex][EV_LOG_REAL_CAP_POW] != pDcChargingInfo->RealRatingPower) {
-                                    LogInfo[gunIndex][EV_LOG_REAL_CAP_POW] = pDcChargingInfo->RealRatingPower;
-                                    log_info("Conn %d, RealRatingPower = %d ",
-                                             gunIndex,
-                                             pDcChargingInfo->RealRatingPower);
-
-                                }
-                            } else {
-                                gfgResult = GFD_WAIT;
-                            }
-                        }
-
-                        SetIsolationStatus(gunIndex, gfgResult, pDcChargingInfo->Evboard_id);
-                    }
-
-                    if (pDcChargingInfo->SystemStatus == S_CCS_PRECHARGE_ST0 &&
-                            pDcChargingInfo->PrechargeStatus == PRECHARGE_READY
-                       ) {
-                        SetEvsePrechargeInfo(gunIndex, PRECHARGE_PRERELAY_PASS, pDcChargingInfo->Evboard_id);
-                    }
-                }
-                ftime(&waitChargingTime);
-                break;
-
-            case S_CHARGING:
-                //if (waitPsuVolwithRealyVol(gunIndex) == NO) {
-                //    continue;
-                //}
-                GetEvBatteryInfo(gunIndex, pDcChargingInfo->Evboard_id); //DS60-120 add
-                // 計算 Power
-                pDcChargingInfo->PresentChargingPower =
-                    ((float)((pDcChargingInfo->PresentChargingVoltage) *
-                             (pDcChargingInfo->PresentChargingCurrent)) / 1000);
-
-                //DS60-120 remove
-                if (chargingTime[gunIndex] == 0 ||
-                        chargingTime[gunIndex] > pDcChargingInfo->PresentChargedDuration) {
-                    chargingTime[gunIndex] = pDcChargingInfo->PresentChargedDuration;
-                } else {
-                    int passTime = pDcChargingInfo->PresentChargedDuration - chargingTime[gunIndex];
-
-                    if (passTime > 0) {
-                        float changingPow = (pDcChargingInfo->PresentChargingPower) * passTime / 3600;
-                        if (pSysConfig->BillingData.isBilling) {
-                            pDcChargingInfo->ChargingFee += changingPow * pSysConfig->BillingData.Cur_fee;
-                        }
-
-                        pDcChargingInfo->PresentChargedEnergy += changingPow;
-                        pDcChargingInfo->PowerConsumption += changingPow;
-                        ShmDcCommonData->pGunInfo[gunIndex].PowerConsumption += changingPow;
-                        chargingTime[gunIndex] = pDcChargingInfo->PresentChargedDuration;
-                    }
-                }
-
-                // 開始確認車端是否同意開始充電
-                GetOutputReq(gunIndex, pDcChargingInfo->Evboard_id);
-
-                // 設定當前輸出
-                ftime(&nowTime);
-                if (!(DiffTimeb(waitChargingTime, nowTime) < 5000 ||
-                        DiffTimeb(waitChargingTime, nowTime) < 0)) {
-                    psuOutputReady[gunIndex] = true;
-                }
-                SetPresentChargingOutputPower();
-
-                // for test end
-                if (priorityLow % 5 == 0) {
-                    // 樁端輸出能力改變
-                    SetPresentChargingOutputCap();
-                }
-
-                if ((pDcChargingInfo->GroundFaultStatus == GFD_FAIL) ||
-                        (pDcChargingInfo->Type == _Type_CCS_2)) {
-                    SetIsolationStatus(gunIndex,
-                                       pDcChargingInfo->GroundFaultStatus,
-                                       pDcChargingInfo->Evboard_id);
-                }
-                /*
-                else if (pDcChargingInfo->Type == _Type_CCS_2) {
-                SetIsolationStatus(gunIndex, pDcChargingInfo->GroundFaultStatus, pDcChargingInfo->Evboard_id);
-                }*/
-
-                // GFD 失敗再通知
-                if (priorityLow == 1) {
-                    if (pDcChargingInfo->Type == _Type_CCS_2 &&
-                            pDcChargingInfo->PrechargeStatus == PRECHARGE_READY) {
-                        SetEvsePrechargeInfo(gunIndex,
-                                             PRECHARGE_CHARELAY_PASS,
-                                             pDcChargingInfo->Evboard_id);
-                    }
-                }
-                break;
-
-            case S_ALARM:
-            case S_TERMINATING:
-                // 設定當前輸出
-                setCurrentOutput();
-                SetPresentChargingOutputPower();
-
-                // 槍鎖還在,則代表是樁端要求的停止
-                if (pDcChargingInfo->GunLocked == START ||
-                        pDcChargingInfo->Type == _Type_CCS_2) {
-                    uint8_t normalStop = 0x01;
-                    uint8_t stopReason[6] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
-
-                    if (GetStopChargingReasonByEvse(gunIndex, stopReason)) {
-                        normalStop = 0x02;
-                    }
-
-                    EvseStopChargingEvent(normalStop,
-                                          stopReason,
-                                          pDcChargingInfo->Evboard_id);
-
-                    SendErrorCount[gunIndex] += 1; //DS60-120 add
-                }
-
-                if (pDcChargingInfo->Type == _Type_CCS_2) {
-                    SetIsolationStatus(gunIndex,
-                                       pDcChargingInfo->GroundFaultStatus,
-                                       pDcChargingInfo->Evboard_id);
-                }
-
-                GetOutputReq(gunIndex, pDcChargingInfo->Evboard_id);
-
-                //DS60-120 add
-                if (pDcChargingInfo->SystemStatus == S_ALARM) {
-                    if (priorityLow == 1) {
-                        // 樁端輸出能力
-                        maxVol = pDcChargingInfo->MaximumChargingVoltage;
-                        maxCur = pDcChargingInfo->AvailableChargingCurrent;
-
-                        GetMaxVolAndCurMethod(gunIndex, &maxVol, &maxCur);
-
-                        SetChargingPermission(gunIndex,
-                                              STOP,
-                                              pDcChargingInfo->AvailableChargingPower,
-                                              maxCur,
-                                              maxVol,
-                                              pDcChargingInfo->Evboard_id);
-                    }
-                }
-                break;
-
-            case S_COMPLETE:
-                // 設定當前輸出
-                SetPresentChargingOutputPower();
-
-                if (priorityLow == 1) {
-                    // 樁端輸出能力
-                    maxVol = pDcChargingInfo->MaximumChargingVoltage;
-                    maxCur = pDcChargingInfo->AvailableChargingCurrent;
-
-                    GetMaxVolAndCurMethod(gunIndex, &maxVol, &maxCur);
-                    SetChargingPermission(gunIndex,
-                                          STOP,
-                                          pDcChargingInfo->AvailableChargingPower,
-                                          maxCur,
-                                          maxVol,
-                                          pDcChargingInfo->Evboard_id);
-
-                    //DS60-120 add
-                    //if (pDcChargingInfo->EvBatterySoc >= 100) {
-                    //    //滿電,則直接清掉錯誤
-                    //    if (pDcChargingInfo->Type == _Type_Chademo) {
-                    //        ClearAbnormalStatus_Chademo(gunIndex);
-                    //    } else if (pDcChargingInfo->Type == _Type_GB) {
-                    //        ClearAbnormalStatus_GB(gunIndex);
-                    //    } else if (pDcChargingInfo->Type == _Type_CCS_2) {
-                    //        ClearAbnormalStatus_CCS(gunIndex);
-                    //    }
-                    //}
-                }
-                break;
-            }//switch
-        }//for
-        Comcont >= 200 ? Comcont = 1: Comcont++;
-        priorityLow >= 20 ? priorityLow = 1 : priorityLow++;
-        usleep(50000);
-    }//while
-
-    return 0;
-}
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdint.h>
+#include <string.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <time.h>
+
+#include <sys/ioctl.h>
+#include <sys/stat.h>
+#include <sys/timeb.h>
+#include <sys/time.h>
+
+#include <net/if.h>
+
+#include <linux/can.h>
+#include <linux/can/raw.h>
+#include <signal.h>
+
+#include "../Config.h"
+#include "../Log/log.h"
+#include "../Define/define.h"
+#include "../ShareMemory/shmMem.h"
+#include "../SelectGun/SelectGun.h"
+#include "Ev_Comm.h"
+#include "Module_EvComm.h"
+#include "../CSU/main.h"
+
+//------------------------------------------------------------------------------
+static struct SysConfigData *pSysConfig = NULL;
+static struct SysInfoData *pSysInfo = NULL;
+
+static struct FaultCodeData *pFaultCode = NULL;
+static struct AlarmCodeData *pAlarmCode = NULL;
+static struct CHAdeMOData *ShmCHAdeMOData = NULL;
+static struct GBTData *ShmGBTData = NULL;
+static struct CcsData *ShmCcsData = NULL;
+static DcCommonInfo *ShmDcCommonData = NULL;
+static SelectGunInfo *ShmSelectGunInfo = NULL;
+uint8_t deratingIndex[2];
+// 限制最大充電電壓,因應不同 type 槍線來限制
+// Chademo : 500V, 125A,
+// GB : 750, 120A
+// CCS : 950V, 120A
+//DS60-120 add
+//static double chademoVol = 5000;
+//static double ccsVol = 9500;
+//static double gbVol = 7500;
+static float maxChargingVol[2] = {0, 0};       // 限制最大充電電壓,如依照模塊則填上 0
+// 限制最大充電電流與能量透過 Web
+static float maxChargingCur[2] = {0, 0};         // 限制最大充電電流,如依照模塊則填上 0
+static float maxChargingPow = 0;                   // 限制最大充電能量,如依照模塊則填上 0
+
+static float LogInfo[2][10]; //DS60-120 add
+static int CanFd = -1;
+
+bool psuOutputReady[2] = {0, 0};
+
+//------------------------------------------------------------------------------
+extern void CANReceiver(int fd);
+extern void ClearAbnormalStatus_Chademo(uint8_t gun_index);
+extern void ClearAbnormalStatus_GB(uint8_t gun_index);
+extern void ClearAbnormalStatus_CCS(uint8_t gun_index);
+
+//------------------------------------------------------------------------------
+int GetCanFd(void)
+{
+    return CanFd;
+}
+void GetClockTime(struct timespec* _now_time, void* null)
+{
+    clock_gettime(CLOCK_MONOTONIC, _now_time);
+}
+uint32_t GetTimeoutValue(struct timeval _sour_time)
+{
+    struct timeval _end_time;
+    gettimeofday(&_end_time, NULL);
+
+    return 1000000 * (_end_time.tv_sec - _sour_time.tv_sec) + _end_time.tv_usec - _sour_time.tv_usec;
+}
+unsigned long GetClockTimeoutValue(struct timespec _start_time)
+{
+    struct timespec ts_end;
+    unsigned long ret = 0;
+
+    clock_gettime(CLOCK_MONOTONIC, &ts_end);
+
+    ret = ((unsigned long)(ts_end.tv_sec - _start_time.tv_sec) * 1000000) + ((unsigned long)((ts_end.tv_nsec / 1000) - (_start_time.tv_nsec / 1000)));
+
+    return ret;
+}
+int InitCanBus(void)
+{
+    int s0, nbytes;
+    struct timeval tv;
+    struct ifreq ifr0;
+    struct sockaddr_can addr0;
+    struct can_filter rxfilter[3];
+
+    system("/sbin/ip link set can0 down");
+    system("/sbin/ip link set can0 type can bitrate 500000 restart-ms 100");
+    system("/sbin/ip link set can0 up");
+
+    s0 = socket(PF_CAN, SOCK_RAW, CAN_RAW);
+
+    tv.tv_sec = 0;
+    tv.tv_usec = 10000;
+
+    if (setsockopt(s0, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(struct  timeval)) < 0) {
+        log_error("Set SO_RCVTIMEO NG");
+    }
+
+    nbytes = 40960;
+    if (setsockopt(s0, SOL_SOCKET,  SO_RCVBUF, &nbytes, sizeof(int)) < 0) {
+        log_error("Set SO_RCVBUF NG");
+    }
+
+    nbytes = 40960;
+    if (setsockopt(s0, SOL_SOCKET, SO_SNDBUF, &nbytes, sizeof(int)) < 0) {
+        log_error("Set SO_SNDBUF NG");
+    }
+
+    rxfilter[0].can_id = 0x01;
+    rxfilter[0].can_mask = 0x000000FF;
+    rxfilter[1].can_id = 0x02;
+    rxfilter[1].can_mask = 0x000000FF;
+    rxfilter[2].can_id = 0x01FF;
+    rxfilter[2].can_mask = 0x00000FFF;
+    if (setsockopt(s0, SOL_CAN_RAW, CAN_RAW_FILTER,
+                   &rxfilter, sizeof(struct can_filter) * 3) < 0) {
+        log_error("RX setsockopt CAN_RAW_FILTER failed");
+    }
+
+    strcpy(ifr0.ifr_name, "can0");
+    ioctl(s0, SIOCGIFINDEX, &ifr0); /* ifr.ifr_ifindex gets filled with that device's index */
+    addr0.can_family = AF_CAN;
+    addr0.can_ifindex = ifr0.ifr_ifindex;
+    bind(s0, (struct sockaddr *)&addr0, sizeof(addr0));
+
+    return s0;
+}
+
+void SetNatural200AGunOTPValue(struct DERATING_BY_OTP* deratingByConnOtp)
+{
+    memset(&deratingByConnOtp->deratingTargetRate[0], 200, sizeof(deratingByConnOtp->deratingTargetRate));
+}
+void SetNatural300AGunOTPValue(struct DERATING_BY_OTP* deratingByConnOtp)
+{
+    deratingByConnOtp->deratingTargetCurrent[0] = 500;
+    deratingByConnOtp->deratingTargetCurrent[1] = 300;
+    deratingByConnOtp->deratingTargetCurrent[2] = 100;
+    deratingByConnOtp->deratingTargetCurrent[3] = 100;
+    deratingByConnOtp->deratingTargetCurrent[4] = 100;
+}
+void SetLiquidCoolGunOTPValue(struct DERATING_BY_OTP* deratingByConnOtp)
+{
+    deratingByConnOtp->deratingTargetCurrent[0] = 500;
+    deratingByConnOtp->deratingTargetCurrent[1] = 400;
+    deratingByConnOtp->deratingTargetCurrent[2] = 300;
+    deratingByConnOtp->deratingTargetCurrent[3] = 300;
+    deratingByConnOtp->deratingTargetCurrent[4] = 300;
+}
+void SetCHAdeMoTypeJOTPValue(uint8_t regulation, struct DERATING_BY_OTP* deratingByConnOtp)
+{
+    if (regulation == 'J') {
+        memset(&deratingByConnOtp->deratingTargetRate[0], 125, sizeof(deratingByConnOtp->deratingTargetRate));
+    }
+    else {
+        memset(&deratingByConnOtp->deratingTargetRate[0], 120, sizeof(deratingByConnOtp->deratingTargetRate));
+    }
+}
+void SetCHAdeMoTypeKOTPValue(struct DERATING_BY_OTP* deratingByConnOtp)
+{
+    memset(&deratingByConnOtp->deratingTargetRate[0], 200, sizeof(deratingByConnOtp->deratingTargetRate));
+}
+
+void SetCHAdeMoTypeSJOTPValue(struct DERATING_BY_OTP* deratingByConnOtp)
+{
+    deratingByConnOtp->deratingTargetRate[0] = 1;
+    deratingByConnOtp->deratingTargetRate[1] = 0.8;
+}
+
+static void SetGunTypeOTPValue(void)
+{
+    struct ChargingInfoData* pDcChargingInfo = NULL;
+    uint8_t Gun1Type = 0;
+    uint8_t Gun2Type = 0;
+    int i;
+    if (pSysConfig->TotalConnectorCount == 1) {
+        pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(0);
+        Gun1Type = pSysConfig->ModelName[7];
+        Gun2Type = pSysConfig->ModelName[7];
+
+        switch (Gun1Type) {
+            //CHAdeMo
+        case 'J':
+            SetCHAdeMoTypeJOTPValue(pSysConfig->ModelName[3], &pDcChargingInfo->deratingByConnOtp);
+            break;
+        case 'K':
+            SetCHAdeMoTypeKOTPValue(&pDcChargingInfo->deratingByConnOtp);
+            break;
+        case 'S':
+            SetCHAdeMoTypeSJOTPValue(&pDcChargingInfo->deratingByConnOtp);
+            break;
+            // 風冷200A以下
+        case 'U':
+        case 'E':
+        case 'M':
+        case 'N':
+            SetNatural200AGunOTPValue(&pDcChargingInfo->deratingByConnOtp);
+            break;
+            // 風冷300A
+        case 'T':
+        case 'D':
+            SetNatural300AGunOTPValue(&pDcChargingInfo->deratingByConnOtp);
+            break;
+            // 水冷
+        case 'V':
+        case 'F':
+        case 'P':
+        case 'R':
+            SetLiquidCoolGunOTPValue(&pDcChargingInfo->deratingByConnOtp);
+            break;
+        }
+
+    }
+    else if (pSysConfig->TotalConnectorCount == 2) {
+        Gun1Type = pSysConfig->ModelName[7];
+        Gun2Type = pSysConfig->ModelName[9];
+        for (i = 0; i < pSysConfig->TotalConnectorCount; i++) {
+            pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(i);
+            pDcChargingInfo->deratingByConnOtp.isNeedDerating = GUNOTPDERATING;
+            switch (i == 0 ? Gun1Type : Gun2Type) {
+                //CHAdeMo
+            case 'J':
+                SetCHAdeMoTypeJOTPValue(pSysConfig->ModelName[3], &pDcChargingInfo->deratingByConnOtp);
+                break;
+            case 'K':
+                SetCHAdeMoTypeKOTPValue(&pDcChargingInfo->deratingByConnOtp);
+                break;
+            case 'S':
+                SetCHAdeMoTypeSJOTPValue(&pDcChargingInfo->deratingByConnOtp);
+                break;
+                // 風冷200A以下
+            case 'U':
+            case 'E':
+            case 'M':
+            case 'N':
+                SetNatural200AGunOTPValue(&pDcChargingInfo->deratingByConnOtp);
+                break;
+                // 風冷300A
+            case 'T':
+            case 'D':
+                SetNatural300AGunOTPValue(&pDcChargingInfo->deratingByConnOtp);
+                break;
+                // 水冷
+            case 'V':
+            case 'F':
+            case 'P':
+            case 'R':
+                SetLiquidCoolGunOTPValue(&pDcChargingInfo->deratingByConnOtp);
+                break;
+            }
+        }
+    }
+}
+
+float GetMaxChargingVol(uint8_t index)
+{
+    return maxChargingVol[index];
+}
+
+float GetMaxCharginigCur(uint8_t index)
+{
+    return maxChargingCur[index];
+}
+
+static void SendCommunicationOnly(uint8_t index)
+{
+    struct ChargingInfoData *pDcCharginigInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);
+    uint8_t targetID = pDcCharginigInfo->Evboard_id;
+/*
+    if (pSysConfig->TotalConnectorCount == 1 &&
+            pDcCharginigInfo->Type == _Type_CCS_2 &&
+            ShmDcCommonData->CcsVersion == _CCS_VERSION_CHECK_TAG_V015S0) {
+        targetID += 1;
+    }
+*/
+    SetChargingPermission(index,
+                          COMMUNICATION,
+                          pDcCharginigInfo->AvailableChargingPower,
+                          0,
+                          0,
+                          targetID);
+}
+
+static void SendStopOnly(uint8_t index)
+{
+    struct ChargingInfoData *pDcCharginigInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);
+
+    uint8_t targetID = pDcCharginigInfo->Evboard_id;
+/*
+    if (pSysConfig->TotalConnectorCount == 1 &&
+            pDcCharginigInfo->Type == _Type_CCS_2 &&
+            ShmDcCommonData->CcsVersion == _CCS_VERSION_CHECK_TAG_V015S0) {
+        targetID += 1;
+    }
+*/
+    SetChargingPermission(index,
+                          STOP,
+                          pDcCharginigInfo->AvailableChargingPower,
+                          0,
+                          0,
+                          targetID);
+}
+
+static uint8_t GetStopChargingReasonByEvse(uint8_t gunIndex, uint8_t *reason)
+{
+    uint8_t result = NO;
+    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+
+    if (pAlarmCode->AlarmEvents.bits.EmergencyStopTrip == 0x01) {
+        // 012251
+        *(reason + 5)  = 0;
+        *(reason + 4)  = 1;
+        *(reason + 3)  = 2;
+        *(reason + 2)  = 2;
+        *(reason + 1)  = 5;
+        *(reason + 0)  = 1;
+        result = YES;
+    }
+
+    if (pDcChargingInfo->Type == _Type_Chademo) {
+        if (pFaultCode->FaultEvents.bits.ChademoOutputRelayDrivingFault == YES) {
+            // 011012
+            *(reason + 5) = 0;
+            *(reason + 4) = 1;
+            *(reason + 3) = 1;
+            *(reason + 2) = 0;
+            *(reason + 1) = 1;
+            *(reason + 0) = 2;
+            result = YES;
+        } else if (pAlarmCode->AlarmEvents.bits.ChademoOutputUVPFail == YES) {
+            // 012289
+            *(reason + 5) = 0;
+            *(reason + 4) = 1;
+            *(reason + 3) = 2;
+            *(reason + 2) = 2;
+            *(reason + 1) = 8;
+            *(reason + 0) = 9;
+            result = YES;
+        } else if (pAlarmCode->AlarmEvents.bits.ChademoGfdTrip == YES) {
+            // 012234
+            *(reason + 5) = 0;
+            *(reason + 4) = 1;
+            *(reason + 3) = 2;
+            *(reason + 2) = 2;
+            *(reason + 1) = 3;
+            *(reason + 0) = 4;
+            result = YES;
+        }
+    } else if (pDcChargingInfo->Type == _Type_GB) {
+        if (pFaultCode->FaultEvents.bits.ChademoOutputRelayDrivingFault == YES) {
+            // 012290
+            *(reason + 5) = 0;
+            *(reason + 4) = 1;
+            *(reason + 3) = 2;
+            *(reason + 2) = 2;
+            *(reason + 1) = 9;
+            *(reason + 0) = 0;
+            result = YES;
+        } else if (pAlarmCode->AlarmEvents.bits.GbGfdTrip == YES) {
+            // 012236
+            *(reason + 5) = 0;
+            *(reason + 4) = 1;
+            *(reason + 3) = 2;
+            *(reason + 2) = 2;
+            *(reason + 1) = 3;
+            *(reason + 0) = 6;
+            result = YES;
+        }
+    } else if (pDcChargingInfo->Type == _Type_CCS_2) {
+        if (pFaultCode->FaultEvents.bits.CcsOutputRelayDrivingFault == YES) {
+            // 011014
+            *(reason + 5) = 0;
+            *(reason + 4) = 1;
+            *(reason + 3) = 1;
+            *(reason + 2) = 0;
+            *(reason + 1) = 1;
+            *(reason + 0) = 4;
+            result = YES;
+        } else if (pAlarmCode->AlarmEvents.bits.CcsOutputUVPFail == YES) {
+            // 012288
+            *(reason + 5) = 0;
+            *(reason + 4) = 1;
+            *(reason + 3) = 2;
+            *(reason + 2) = 2;
+            *(reason + 1) = 8;
+            *(reason + 0) = 8;
+            result = YES;
+        } else if (pAlarmCode->AlarmEvents.bits.CcsGfdTrip == YES) {
+            // 012235
+            *(reason + 5) = 0;
+            *(reason + 4) = 1;
+            *(reason + 3) = 2;
+            *(reason + 2) = 2;
+            *(reason + 1) = 3;
+            *(reason + 0) = 5;
+            result = YES;
+        }
+    }
+
+    return result;
+}
+
+static void setCurrentOutput(void)
+{
+    struct ChargingInfoData *chargingData_1 = NULL;
+    struct ChargingInfoData *chargingData_2 = NULL;
+
+    if (pSysConfig->TotalConnectorCount == 1) {
+        chargingData_1 = (struct ChargingInfoData *)GetDcChargingInfoData(0);
+        //chargingData_2 = (struct ChargingInfoData *)GetDcChargingInfoData(0);
+
+        if (chargingData_1->FireChargingVoltage <= 500) { //DS60-120 add
+            chargingData_1->PresentChargingCurrent = 0;
+        }
+
+    } else if (pSysConfig->TotalConnectorCount == 2) {
+        chargingData_1 = (struct ChargingInfoData *)GetDcChargingInfoData(0);
+        chargingData_2 = (struct ChargingInfoData *)GetDcChargingInfoData(1);
+
+        if (chargingData_1->FireChargingVoltage <= 500) { //DS60-120 add
+            chargingData_1->PresentChargingCurrent = 0;
+        }
+
+        if (chargingData_2->FireChargingVoltage <= 500) {
+            chargingData_2->PresentChargingCurrent = 0;
+        }
+    }
+}
+
+static void GetMaxVolAndCurMethod(uint8_t index, float *vol, float *cur)
+{
+    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);
+
+    if (maxChargingVol[index] != 0 && maxChargingVol[index] <= *vol) {
+        *vol = maxChargingVol[index];
+    }
+
+    if (maxChargingCur[index] != 0 && maxChargingCur[index] <= *cur) {
+        *cur = maxChargingCur[index];
+    }
+
+    if (((pDcChargingInfo->SystemStatus >= S_PREPARING_FOR_EVSE &&
+            pDcChargingInfo->SystemStatus <= S_CHARGING) ||
+            (pDcChargingInfo->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
+             pDcChargingInfo->SystemStatus <= S_CCS_PRECHARGE_ST1)) &&
+            pDcChargingInfo->ChargingProfileCurrent >= 0 &&
+            pDcChargingInfo->ChargingProfileCurrent <= *cur
+       ) {
+        *cur = pDcChargingInfo->ChargingProfileCurrent;
+    }
+}
+
+void GetOtpPwrOrCurMethod(struct ChargingInfoData* chargingData, float* pow, float* cur)
+{
+    if (((chargingData->ConnectorTemp >= STAGE1_GUN_DERATING_TEMP &&
+        chargingData->ConnectorTemp < STAGE2_GUN_DERATING_TEMP) ||
+        (chargingData->ChillerTemp >= STAGE1_GUN_DERATING_TEMP &&
+            chargingData->ChillerTemp < STAGE2_GUN_DERATING_TEMP)) &&
+        chargingData->deratingByConnOtp.deratingIndex < 1)
+    {
+        chargingData->deratingByConnOtp.deratingIndex = 1;
+    }
+    else if ((chargingData->ConnectorTemp >= STAGE2_GUN_DERATING_TEMP ||
+        chargingData->ChillerTemp >= STAGE2_GUN_DERATING_TEMP) &&
+        chargingData->ConnectorTemp != UNDEFINED_TEMP &&
+        chargingData->ChillerTemp != UNDEFINED_TEMP &&
+        chargingData->deratingByConnOtp.deratingIndex < 2)
+    {
+        chargingData->deratingByConnOtp.deratingIndex = 2;
+    }
+
+    if (chargingData->deratingByConnOtp.deratingTargetRate[chargingData->deratingByConnOtp.deratingIndex] != 0)
+    {
+        *pow *= chargingData->deratingByConnOtp.deratingTargetRate[chargingData->deratingByConnOtp.deratingIndex];
+    }
+    else if (chargingData->deratingByConnOtp.deratingTargetCurrent[chargingData->deratingByConnOtp.deratingIndex] != 0)
+    {
+        if (*cur > chargingData->deratingByConnOtp.deratingTargetCurrent[chargingData->deratingByConnOtp.deratingIndex])
+            *cur = chargingData->deratingByConnOtp.deratingTargetCurrent[chargingData->deratingByConnOtp.deratingIndex];
+    }
+}   
+
+static void SetPresentChargingOutputCap(void)
+{
+    float pow1 = 0, cur1 = 0;
+    float pow2 = 0, cur2 = 0;
+    struct ChargingInfoData *chargingData_1 = NULL;
+    struct ChargingInfoData *chargingData_2 = NULL;
+    struct PrimaryMcuData* ShmPrimaryMcuData = (struct PrimaryMcuData*)GetShmPrimaryMcuData();
+
+    if (pSysConfig->TotalConnectorCount == 1) {
+        chargingData_1 = (struct ChargingInfoData *)GetDcChargingInfoData(0);
+        chargingData_2 = (struct ChargingInfoData *)GetDcChargingInfoData(0);
+    } else if (pSysConfig->TotalConnectorCount == 2) {
+        chargingData_1 = (struct ChargingInfoData *)GetDcChargingInfoData(0);
+        chargingData_2 = (struct ChargingInfoData *)GetDcChargingInfoData(1);
+    }
+/*
+#if !defined DD360Tcci && !defined DD360Audi && !defined DD360ComBox && !defined DD360UCar
+    float vol = 0;
+#endif //!defined DD360Tcci && !defined DD360Audi
+*/
+    pow1 = chargingData_1->AvailableChargingPower;
+    cur1 = chargingData_1->AvailableChargingCurrent;
+/*
+#if !defined DD360Tcci && !defined DD360Audi && !defined DD360ComBox && !defined DD360UCar
+    vol = chargingData_1->MaximumChargingVoltage;
+    GetMaxVolAndCurMethod(chargingData_1->Index, &vol, &cur1);
+    //GetMaxPowerMethod(chargingData_1->Index, &pow1);
+#endif //!defined DD360Tcci && !defined DD360Audi
+*/
+    if (pow1 <= 0) {
+        cur1 = 0;
+    } else {
+        if (chargingData_1->SystemStatus == S_CHARGING &&
+                chargingData_1->FireChargingVoltage > 1500) {
+            float maxCur = 0;
+            maxCur = (pow1 * 1000) / chargingData_1->FireChargingVoltage;
+
+            if (maxCur * 10 <= cur1) {
+                //log_info("Gun1 -> MaxCharging Current = %f, Cap Current = %f ", (maxCur * 10), cur1);
+                cur1 = maxCur * 10;
+            }
+        }
+    }
+
+    if (chargingData_1->deratingByConnOtp.isNeedDerating) {
+        GetOtpPwrOrCurMethod(chargingData_1, &pow1, &cur1);
+        if (deratingIndex[0] != chargingData_1->deratingByConnOtp.deratingIndex) {
+            log_info("Gun0 Derating Index Set %d", chargingData_1->deratingByConnOtp.deratingIndex);
+            deratingIndex[0] = chargingData_1->deratingByConnOtp.deratingIndex;
+        }
+    }
+
+    pow2 = chargingData_2->AvailableChargingPower;
+    cur2 = chargingData_2->AvailableChargingCurrent;
+    /*
+#if !defined DD360Tcci && !defined DD360Audi && !defined DD360ComBox && !defined DD360UCar
+    vol = chargingData_2->MaximumChargingVoltage;
+    GetMaxVolAndCurMethod(chargingData_2->Index, &vol, &cur2);
+    //GetMaxPowerMethod(chargingData_2->Index, &pow2);
+#endif //!defined DD360Tcci && !defined DD360Audi
+*/
+    if (pow2 <= 0) {
+        cur2 = 0;
+    } else {
+        if (chargingData_2->SystemStatus == S_CHARGING &&
+                chargingData_2->FireChargingVoltage > 1500) {
+            float maxCur = 0;
+            maxCur = (pow2 * 1000) / chargingData_2->FireChargingVoltage;
+
+            if (maxCur * 10 <= cur2) {
+                //log_info("Gun2 -> MaxCharging Current = %f, Cap Current = %f ", (maxCur * 10), cur2);
+                cur2 = maxCur * 10;
+            }
+        }
+    }
+    if (chargingData_2->deratingByConnOtp.isNeedDerating) {
+        GetOtpPwrOrCurMethod(chargingData_2, &pow2, &cur2);
+        if (deratingIndex[1] != chargingData_2->deratingByConnOtp.deratingIndex) {
+            log_info("Gun1 Derating Index Set %d", chargingData_2->deratingByConnOtp.deratingIndex);
+            deratingIndex[1] = chargingData_2->deratingByConnOtp.deratingIndex;
+        }
+    }
+    if (ShmPrimaryMcuData->InputDet.bits.Ac_Drop == ABNORMAL) {
+        if (cur1 > 1500) {
+            log_info("Gun0 chiller alarm set current less than 150A");
+            cur1 = 1500;
+        }
+        if (cur2 > 1500) {
+            log_info("Gun1 chiller alarm set current less than 150A");
+            cur2 = 1500;
+        }
+    }
+    //DS60-120 add
+    if ((LogInfo[0][EV_LOG_OUTPUT_CAP_POW] <= pow1 - 5 ||
+            LogInfo[0][EV_LOG_OUTPUT_CAP_POW] >= pow1 + 5) ||
+            (LogInfo[0][EV_LOG_OUTPUT_CAP_CUR] <= cur1 - 5 ||
+             LogInfo[0][EV_LOG_OUTPUT_CAP_CUR] >= cur1 + 5) ||
+            (LogInfo[1][EV_LOG_OUTPUT_CAP_POW] <= pow2 - 5 ||
+             LogInfo[1][EV_LOG_OUTPUT_CAP_POW] >= pow2 + 5) ||
+            (LogInfo[1][EV_LOG_OUTPUT_CAP_CUR] <= cur2 - 5 ||
+             LogInfo[1][EV_LOG_OUTPUT_CAP_CUR] >= cur2 + 5)
+       ) {
+        //log_info("----------------------------------------------------- ");
+        log_info("To EV (Real) Power_1 = %.1f, Cur_1 = %.1f, Power_2 = %.1f, Cur_2 = %.1f",
+                 pow1 / 10, cur1 / 10, pow2 / 10, cur2 / 10);
+        //log_info("----------------------------------------------------- ");
+
+        LogInfo[0][EV_LOG_OUTPUT_CAP_POW] = pow1;
+        LogInfo[0][EV_LOG_OUTPUT_CAP_CUR] = cur1;
+        LogInfo[1][EV_LOG_OUTPUT_CAP_POW] = pow2;
+        LogInfo[1][EV_LOG_OUTPUT_CAP_CUR] = cur2;
+        chargingData_1->RealMaxCurrent = cur1;
+        chargingData_1->RealMaxPower = pow1;
+
+        if (pSysConfig->TotalConnectorCount == 2) {
+            chargingData_2->RealMaxCurrent = cur2;
+            chargingData_2->RealMaxPower = pow2;
+        }
+    }
+    if (pSysConfig->TotalConnectorCount == 2) {
+        chargingData_2->RealMaxCurrent = cur2;
+        chargingData_2->RealMaxPower = pow2;
+    }
+    SetPresentOutputCapacity(pow1, cur1, pow2, cur2);
+}
+/*
+static uint8_t waitPsuVolwithRealyVol(uint8_t gunIndex)
+{
+    PcPsuOutput *pPcPsuOutput = (PcPsuOutput *)&ShmDcCommonData->PcPsuOutput[gunIndex];
+    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+    int vol = 0;
+
+    vol = abs(pPcPsuOutput->Voltage - pDcChargingInfo->FireChargingVoltage);
+    if (vol <= 10) {
+        return YES;
+    }
+
+    return NO;
+}
+*/
+/**
+ * [SetPresentChargingOutputFromPcPsu 充電狀態讀取電源櫃PSU輸出電壓電流,縮小誤差值]
+ * @Author   Jerry
+ * @DateTime 2021-07-05
+ */
+/*
+static void SetPresentChargingOutputFromPcPsu(uint8_t gunCount)
+{
+    float vol1 = 0, cur1 = 0;
+    float vol2 = 0, cur2 = 0;
+    PcPsuOutput *pPcPsuOutput0 = NULL;
+    PcPsuOutput *pPcPsuOutput1 = NULL;
+    struct ChargingInfoData *chargingData0 = NULL;
+    struct ChargingInfoData *chargingData1 = NULL;
+
+    switch (gunCount) {
+    case 1:
+        pPcPsuOutput0 = (PcPsuOutput *)&ShmDcCommonData->PcPsuOutput[0];
+        pPcPsuOutput1 = (PcPsuOutput *)&ShmDcCommonData->PcPsuOutput[0];
+        chargingData0 = (struct ChargingInfoData *)GetDcChargingInfoData(0);
+        chargingData1 = (struct ChargingInfoData *)GetDcChargingInfoData(0);
+        break;
+
+    case 2:
+        pPcPsuOutput0 = (PcPsuOutput *)&ShmDcCommonData->PcPsuOutput[0];
+        pPcPsuOutput1 = (PcPsuOutput *)&ShmDcCommonData->PcPsuOutput[1];
+        chargingData0 = (struct ChargingInfoData *)GetDcChargingInfoData(0);
+        chargingData1 = (struct ChargingInfoData *)GetDcChargingInfoData(1);
+        break;
+    }
+
+    vol1 = pPcPsuOutput0->Voltage == 0 ? chargingData0->FireChargingVoltage : (((float)pPcPsuOutput0->Voltage));
+    cur1 = (chargingData0->PresentChargingCurrent * 10);//(((float)pPcPsuOutput0->Current) * 0.1);
+    vol2 = pPcPsuOutput1->Voltage == 0 ? chargingData1->FireChargingVoltage : (((float)pPcPsuOutput1->Voltage));
+    cur2 = (chargingData1->PresentChargingCurrent * 10);//(((float)pPcPsuOutput1->Current) * 0.1);
+
+    if (
+        (LogInfo[0][EV_LOG_NOW_OUTPUT_VOL] >= vol1 + CHK_VOL_RANGE) ||
+        (LogInfo[0][EV_LOG_NOW_OUTPUT_VOL] <= vol1 - CHK_VOL_RANGE) ||
+        (LogInfo[0][EV_LOG_NOW_OUTPUT_CUR] >= cur1 + CHK_CUR_RANGE) ||
+        (LogInfo[0][EV_LOG_NOW_OUTPUT_CUR] <= cur1 - CHK_CUR_RANGE) ||
+        (LogInfo[1][EV_LOG_NOW_OUTPUT_VOL] >= vol2 + CHK_VOL_RANGE) ||
+        (LogInfo[1][EV_LOG_NOW_OUTPUT_VOL] <= vol2 - CHK_VOL_RANGE) ||
+        (LogInfo[1][EV_LOG_NOW_OUTPUT_CUR] >= cur2 + CHK_CUR_RANGE) ||
+        (LogInfo[1][EV_LOG_NOW_OUTPUT_CUR] <= cur2 - CHK_CUR_RANGE)
+    ) {
+        log_info("G1->Out Vol=%.1f,Out Cur=%.1f - G2->Out Vol=%.1f,Out Cur=%.1f",
+                 vol1,
+                 cur1 / 10,
+                 vol2,
+                 cur2 / 10);
+
+        LogInfo[0][EV_LOG_NOW_OUTPUT_VOL] = vol1;
+        LogInfo[0][EV_LOG_NOW_OUTPUT_CUR] = cur1;
+        LogInfo[1][EV_LOG_NOW_OUTPUT_VOL] = vol2;
+        LogInfo[1][EV_LOG_NOW_OUTPUT_CUR] = cur2;
+    }
+
+    SetPresentOutputPower(vol1, cur1, vol2, cur2);
+}
+*/
+static void SetPresentChargingOutputPower(void)
+{
+    float vol1 = 0, cur1 = 0;
+    float vol2 = 0, cur2 = 0;
+    PcPsuOutput *pPcPsuOutput1 = NULL;
+    PcPsuOutput *pPcPsuOutput2 = NULL;
+    struct ChargingInfoData *chargingData_1 = NULL;
+    struct ChargingInfoData *chargingData_2 = NULL;
+    bool isPsuVol1 = false, isPsuVol2 = false, isPsuCur1 = false, isPsuCur2 = false;
+
+    if (pSysConfig->TotalConnectorCount == 1) {
+        pPcPsuOutput1 = (PcPsuOutput *)&ShmDcCommonData->PcPsuOutput[0];
+        pPcPsuOutput2 = (PcPsuOutput *)&ShmDcCommonData->PcPsuOutput[0];
+        chargingData_1 = (struct ChargingInfoData *)GetDcChargingInfoData(0);
+        chargingData_2 = (struct ChargingInfoData *)GetDcChargingInfoData(0);
+    } else if (pSysConfig->TotalConnectorCount == 2) {
+        pPcPsuOutput1 = (PcPsuOutput *)&ShmDcCommonData->PcPsuOutput[0];
+        pPcPsuOutput2 = (PcPsuOutput *)&ShmDcCommonData->PcPsuOutput[1];
+        chargingData_1 = (struct ChargingInfoData *)GetDcChargingInfoData(0);
+        chargingData_2 = (struct ChargingInfoData *)GetDcChargingInfoData(1);
+    }
+
+    psuOutputReady[0] = chargingData_1->SystemStatus != S_CHARGING ? false : psuOutputReady[0];
+    psuOutputReady[1] = chargingData_2->SystemStatus != S_CHARGING ? false : psuOutputReady[1];
+
+    isPsuVol1 = chargingData_1->PantographFlag ? true : (pPcPsuOutput1->Voltage != 0 && psuOutputReady[0] == true);
+    isPsuVol2 = chargingData_2->PantographFlag ? true : (pPcPsuOutput2->Voltage != 0 && psuOutputReady[1] == true);
+    isPsuCur1 = chargingData_1->PantographFlag ? true : false;
+    isPsuCur2 = chargingData_2->PantographFlag ? true : false;
+
+    //vol1 = chargingData_1->FireChargingVoltage;
+    vol1 = isPsuVol1 == false ? chargingData_1->FireChargingVoltage : (((float)pPcPsuOutput1->Voltage));
+    cur1 = isPsuCur1 == false ? (chargingData_1->PresentChargingCurrent * 10) : pPcPsuOutput1->Current;
+    //vol2 = chargingData_2->FireChargingVoltage;
+    vol2 = isPsuVol2 == false ? chargingData_2->FireChargingVoltage : (((float)pPcPsuOutput2->Voltage));
+    cur2 = isPsuCur2 == false ? (chargingData_2->PresentChargingCurrent * 10) : pPcPsuOutput2->Current;
+
+    //DS60-120 add
+    if ((LogInfo[0][EV_LOG_NOW_OUTPUT_VOL] >= vol1 + CHK_VOL_RANGE) ||
+            (LogInfo[0][EV_LOG_NOW_OUTPUT_VOL] <= vol1 - CHK_VOL_RANGE) ||
+            (LogInfo[0][EV_LOG_NOW_OUTPUT_CUR] >= cur1 + CHK_CUR_RANGE) ||
+            (LogInfo[0][EV_LOG_NOW_OUTPUT_CUR] <= cur1 - CHK_CUR_RANGE) ||
+            (LogInfo[1][EV_LOG_NOW_OUTPUT_VOL] >= vol2 + CHK_VOL_RANGE) ||
+            (LogInfo[1][EV_LOG_NOW_OUTPUT_VOL] <= vol2 - CHK_VOL_RANGE) ||
+            (LogInfo[1][EV_LOG_NOW_OUTPUT_CUR] >= cur2 + CHK_CUR_RANGE) ||
+            (LogInfo[1][EV_LOG_NOW_OUTPUT_CUR] <= cur2 - CHK_CUR_RANGE)
+       ) {
+        log_info("G1-> Vol=%.1f, Cur=%.1f - G2-> Vol = %.1f, Cur = %.1f",
+                 vol1 / 10,
+                 cur1 / 10,
+                 vol2 / 10,
+                 cur2 / 10);
+
+        LogInfo[0][EV_LOG_NOW_OUTPUT_VOL] = vol1;
+        LogInfo[0][EV_LOG_NOW_OUTPUT_CUR] = cur1;
+        LogInfo[1][EV_LOG_NOW_OUTPUT_VOL] = vol2;
+        LogInfo[1][EV_LOG_NOW_OUTPUT_CUR] = cur2;
+    }
+    //if (_outVol_1 != vol1 ||
+    //        _outCur_1 != cur1 ||
+    //        _outVol_2 != vol2 ||
+    //        _outCur_2 != cur2) {
+    /*log_info("G1 -> Output Vol = %f, Output Cur = %f -- G2 -> Output Vol = %f, Output Cur = %f ",
+        vol1, cur1, vol2, cur2);
+    */
+    //    _outVol_1 = vol1; _outCur_1 = cur1; _outVol_2 = vol2; _outCur_2 = cur2;
+    //}
+
+    SetPresentOutputPower(vol1, cur1, vol2, cur2);
+}
+/*
+static void checkConnectorOVPState(uint8_t gunIndex)
+{
+    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+    // 避免槍溫偵測誤判
+    static uint8_t gunTempAllowCount[2] = {0};
+
+    bool isOTP = false;
+
+    switch (pDcChargingInfo->Type) {
+    case _Type_Chademo:
+        if (ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaConnectOTP) {
+            isOTP = true;
+        }
+        break;
+
+    case _Type_CCS_2:
+        if (ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSConnectOTP) {
+            isOTP = true;
+        }
+        break;
+
+    case _Type_GB:
+        if (ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTConnectOTP) {
+            isOTP = true;
+        }
+        break;
+    }
+
+    if (ShmDcCommonData->ChillerTempErr[gunIndex].StatusBit.ChillerOTP == YES) {
+        isOTP = true;
+    }
+
+    if (isOTP) {
+        if (gunTempAllowCount[gunIndex] >= 2) {
+            pDcChargingInfo->StopChargeFlag = YES;
+        } else {
+            gunTempAllowCount[gunIndex] += 1;
+        }
+    } else {
+        gunTempAllowCount[gunIndex] = 0;
+    }
+}
+*/
+static time_t GetRtcInfoForEpoch(void)
+{
+    struct timeb csuTime;
+    struct tm *tmCSU;
+    struct tm t;
+    time_t result;
+
+    ftime(&csuTime);
+    tmCSU = localtime(&csuTime.time);
+
+    t.tm_year = tmCSU->tm_year;
+    t.tm_mon = tmCSU->tm_mon;
+    t.tm_mday = tmCSU->tm_mday;
+    t.tm_hour = tmCSU->tm_hour;
+    t.tm_min = tmCSU->tm_min;
+    t.tm_sec = tmCSU->tm_sec;
+    t.tm_isdst = -1;
+    result = mktime(&t);
+
+    return result;
+}
+
+static void FormatVoltageAndCurrent(void)
+{
+    uint8_t gunIndex = 0;
+    ParsingRatedCur parsingRatedCur = {0};
+    RateCurInfo *pRatedCurInfo = NULL;
+
+    if (RatedCurrentParsing((char *)pSysConfig->ModelName, &parsingRatedCur) != PASS) {
+        log_error("Parsing rated current failed");
+        return;
+    }
+
+    maxChargingPow = parsingRatedCur.Power;
+
+    for (gunIndex = 0; gunIndex < pSysConfig->TotalConnectorCount; gunIndex++) {
+        pRatedCurInfo = (RateCurInfo *)&parsingRatedCur.ParsingInfo[gunIndex];
+
+        maxChargingVol[gunIndex] = pRatedCurInfo->Voltage;
+        maxChargingCur[gunIndex] = pRatedCurInfo->Current;
+
+        log_info("Conn %d GunType = %d, MaxVol = %f, MaxCur = %f ",
+                 gunIndex,
+                 pRatedCurInfo->GunType,
+                 maxChargingVol[gunIndex],
+                 maxChargingCur[gunIndex]);
+    }
+}
+
+static 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;
+}
+
+int main(int argc, char *argv[])
+{
+    bool chkChademoPermission[2] = {false};
+    int isContinue = 1;
+    uint8_t gunIndex = 0;
+    uint8_t typeIndex = 0;
+    uint8_t priorityLow = 1;
+    uint8_t SendErrorCount[2] = {0, 0};
+    uint8_t gfgResult = 0;
+    uint32_t _timeBuf = 0;
+    uint32_t chargingTime[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY] = {0};
+    float maxVol, maxCur;
+    struct timespec _chk_ratingPower_timeout[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
+    struct timespec _chk_chademo_permission_timeout[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
+    time_t rtc = {0};
+    struct ChargingInfoData *pDcChargingInfo = NULL;
+    struct timeb waitChargingTime;
+    struct timeb nowTime;
+    uint8_t Comcont = 0;
+    uint8_t evstatus;
+
+    if (CreateAllCsuShareMemory() == FAIL) {
+        log_error("create share memory error");
+        return FAIL;
+    }
+
+    MappingGunChargingInfo("EvComm Task");
+
+    pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
+    pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
+    pAlarmCode = (struct AlarmCodeData *)GetShmAlarmCodeData();
+    pFaultCode = (struct FaultCodeData *)GetShmFaultCodeData();
+    ShmDcCommonData = (DcCommonInfo *)GetShmDcCommonData();
+    ShmCHAdeMOData = (struct CHAdeMOData *)GetShmCHAdeMOData();
+    ShmGBTData = (struct GBTData *)GetShmGBTData();
+    ShmCcsData = (struct CcsData *)GetShmCcsData();
+    ShmSelectGunInfo = (SelectGunInfo *)GetShmSelectGunInfo();
+
+    CanFd = InitCanBus();
+
+    FormatVoltageAndCurrent();
+
+    signal(SIGCHLD,SIG_IGN);
+    
+    CANReceiver(CanFd);
+
+    //SetGunTypeOTPValue();
+
+    rtc = GetRtcInfoForEpoch();
+
+    while (isContinue) {
+        for (gunIndex = 0; gunIndex < pSysConfig->TotalConnectorCount; gunIndex++) {
+            pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+            typeIndex = pDcChargingInfo->type_index;
+
+            if (priorityLow == 1) {
+                // 優先權較低 - 只要有回應即不會再詢問
+                if (pDcChargingInfo->Type == _Type_Chademo &&
+                        ShmCHAdeMOData->evse[typeIndex].SelfTest_Comp != PASS) {
+                    SyncRtcInfo(gunIndex, pDcChargingInfo->Evboard_id, (int)rtc);
+                    GetFirmwareVersion(gunIndex, pDcChargingInfo->Evboard_id);
+                } else if (pDcChargingInfo->Type == _Type_GB &&
+                           ShmGBTData->evse[typeIndex].SelfTest_Comp != PASS) {
+                    SyncRtcInfo(gunIndex, pDcChargingInfo->Evboard_id, (int)rtc);
+                    GetFirmwareVersion(gunIndex, pDcChargingInfo->Evboard_id);
+                } else if (pDcChargingInfo->Type == _Type_CCS_2) {
+                    if (ShmCcsData->CommProtocol == _CCS_COMM_V2GMessage_DIN70121 &&
+                            ShmCcsData->V2GMessage_DIN70121[typeIndex].SelfTest_Comp != PASS) {
+                        SyncRtcInfo(gunIndex, pDcChargingInfo->Evboard_id, (int)rtc);
+                        GetFirmwareVersion(gunIndex, pDcChargingInfo->Evboard_id);
+                    }
+                }
+                /*
+                if (pDcChargingInfo->Type == _Type_Chademo) {
+                    pAlarmCode->AlarmEvents.bits.ChademoboardStestFail = 
+                        (ShmCHAdeMOData->evse[typeIndex].SelfTest_Comp != PASS) ? true : false;
+                    pAlarmCode->AlarmEvents.bits.ChademoModuleCommFail =
+                        ( CanFd < 0 ) ? true : false;
+                } else if (pDcChargingInfo->Type == _Type_GB) {
+                    pAlarmCode->AlarmEvents.bits.GbtboardStestFail = 
+                        (ShmGBTData->evse[typeIndex].SelfTest_Comp != PASS) ? true : false;
+                    pAlarmCode->AlarmEvents.bits.mFail =
+                        ( CanFd < 0 ) ? true : false;
+                } else if (pDcChargingInfo->Type == _Type_CCS_2) {
+                    pAlarmCode->AlarmEvents.bits.CCSboardStestFail = 
+                        (ShmCcsData->V2GMessage_DIN70121[typeIndex].SelfTest_Comp != PASS) ? true : false;
+                    pAlarmCode->AlarmEvents.bits.ChademoModuleCommFail =
+                        ( CanFd < 0 ) ? true : false;
+                        
+                }*/
+                //固定要取得的資訊 : 1.槍鎖狀態, 2."Connector 1" 溫度, 3."Connector 2" 溫度, 4.Pilot Voltage
+                //log_info("GetMiscellaneousInfo. index = %d, Eid = %d ",
+                //         gunIndex,
+                //         pDcChargingInfo->Evboard_id);
+                GetMiscellaneousInfo(gunIndex,
+                                     pDcChargingInfo->RelayK1K2Status,
+                                     pDcChargingInfo->PresentChargedEnergy,
+                                     (pDcChargingInfo->PresentChargingVoltage * 10),
+                                     pDcChargingInfo->Evboard_id);
+
+                //checkConnectorOVPState(gunIndex);
+            }
+
+            switch (pDcChargingInfo->SystemStatus) {
+            case S_IDLE:
+            case S_AUTHORIZING:
+            case S_RESERVATION:
+                if (pDcChargingInfo->Type == _Type_Chademo) {
+
+                    ClearAbnormalStatus_Chademo(gunIndex);
+                    if (pSysInfo->PageIndex == _PAGE_PLUGIN) {
+                        if (!chkChademoPermission[gunIndex]) {
+                            chkChademoPermission[gunIndex] = true;
+                            GetClockTime(&_chk_chademo_permission_timeout[gunIndex], NULL);
+                            SendCommunicationOnly(gunIndex);
+                        } else {
+                            _timeBuf = GetClockTimeoutValue(_chk_chademo_permission_timeout[gunIndex]);
+
+                            if (_timeBuf < 0) {
+                                GetClockTime(&_chk_chademo_permission_timeout[gunIndex], NULL);
+                            } else {
+                                if (_timeBuf / 1000 > 10000) {
+                                    SendCommunicationOnly(gunIndex);
+                                    GetClockTime(&_chk_chademo_permission_timeout[gunIndex], NULL);
+                                }
+                            }
+                        }
+                    } else if (chkChademoPermission[gunIndex]) {
+                        chkChademoPermission[gunIndex] = false;
+                        SendStopOnly(gunIndex);
+                    }
+
+                    if (ShmDcCommonData->ConnectErrList[gunIndex].GunBits.ChaConnectOTP == NO) {
+                        pDcChargingInfo->StopChargeFlag = NO;
+                    }
+                } else if (pDcChargingInfo->Type == _Type_GB) {
+                    ClearAbnormalStatus_GB(gunIndex);
+
+                    if (ShmDcCommonData->ConnectErrList[gunIndex].GunBits.GBTConnectOTP == NO) {
+                        pDcChargingInfo->StopChargeFlag = NO;
+                    }
+                } else if (pDcChargingInfo->Type == _Type_CCS_2) {
+                    ClearAbnormalStatus_CCS(gunIndex);
+
+                    if (ShmDcCommonData->ConnectErrList[gunIndex].GunBits.CCSConnectOTP == NO) {
+                        pDcChargingInfo->StopChargeFlag = NO;
+                    }
+                }
+                // Set Ev board in communication mode
+                // Get EVCCID for authorize when gun plug-in only for CCS
+                if ( pDcChargingInfo->ConnectorPlugIn && pSysConfig->isAuthrizeByEVCCID &&
+                        ShmCcsData->CommProtocol == _CCS_COMM_V2GMessage_DIN70121) {
+                    if (Comcont == 1 && evstatus < 15) {
+                        GetEVCCIDReq(gunIndex,pDcChargingInfo->Evboard_id);
+                        SendCommunicationOnly(gunIndex);
+                    } 
+                }
+                if (ShmCcsData->CommProtocol == _CCS_COMM_V2GMessage_DIN70121 && priorityLow == 1) {
+                    GetOutputReq(gunIndex,pDcChargingInfo->Evboard_id);
+                    if (evstatus != ShmCcsData->V2GMessage_DIN70121[pDcChargingInfo->type_index].PresentMsgFlowStatus) {
+                        evstatus = ShmCcsData->V2GMessage_DIN70121[pDcChargingInfo->type_index].PresentMsgFlowStatus;
+                    }
+                    if ( evstatus > 19 && evstatus < 255 )
+                        GetEVCCIDReq(gunIndex,pDcChargingInfo->Evboard_id);
+                }
+                if (priorityLow == 1) {
+                    pDcChargingInfo->PresentChargedEnergy   = 0;
+                    pDcChargingInfo->PresentChargingPower   = 0;
+                    pDcChargingInfo->GroundFaultStatus      = GFD_WAIT;
+                    pDcChargingInfo->RealRatingPower        = 0;
+                    pDcChargingInfo->StopChargeFlag         = NO;
+                    pDcChargingInfo->NormalStopChargeFlag   = NO;//DS60-120 add
+                    pDcChargingInfo->ChargingFee            = 0.0;
+                    pDcChargingInfo->EvBatterySoc           = 0;
+                    pDcChargingInfo->EvBatteryStartSoc      = 0; //DS60-120 add
+                    pDcChargingInfo->EvBatteryMaxVoltage    = 0; //DS60-120 add
+                    pDcChargingInfo->ChargingProfilePower   = -1; //DS60-120 add
+                    pDcChargingInfo->ChargingProfileCurrent = -1; //DS60-120 add
+
+                    if (pSysInfo->MainChargingMode == _MAIN_CHARGING_MODE_MAX) { //DS60-120 add
+                        pDcChargingInfo->PresentChargingVoltage = 0;
+                        pDcChargingInfo->PresentChargingCurrent = 0;
+                        pDcChargingInfo->EvBatteryMaxVoltage = 0;
+                    }
+
+                    chargingTime[gunIndex] = 0;
+                    //maxChargingCur[gunIndex] = pSysConfig->MaxChargingCurrent * 10;
+                    //maxChargingPow = (pSysConfig->MaxChargingPower * 10);
+                    //DS60-120 add
+                    SendErrorCount[gunIndex] = 0;
+
+                    //maxChargingPow = pSysConfig->MaxChargingPower * 10;
+                    // ShmPsuData->SystemAvailablePower 已是 * 10
+                    //maxChargingPow = ShmPsuData->SystemAvailablePower;
+                    if (pSysConfig->MaxChargingPower * 10 != 0 &&
+                            pSysConfig->MaxChargingPower * 10 < maxChargingPow) {
+                        maxChargingPow = pSysConfig->MaxChargingPower * 10;
+                    }
+
+                    LogInfo[gunIndex][EV_LOG_EVSE_MAX_VOL] = 0;
+                    LogInfo[gunIndex][EV_LOG_EVSE_MAX_CUR] = 0;
+                    LogInfo[gunIndex][EV_LOG_MAX_BATT_VOL] = 0;
+                    LogInfo[gunIndex][EV_LOG_SOC] = 0;
+
+                    SetPresentChargingOutputPower();
+                }
+                break;
+
+            case S_PREPARNING:
+                chkChademoPermission[gunIndex] = false; //DS60-120 add
+                // 設定當前輸出
+                SetPresentChargingOutputPower();
+
+                pDcChargingInfo->PowerConsumption = 0;
+                break;
+
+            case S_PREPARING_FOR_EV:
+                // 開始確認車端是否同意開始充電 : 1.SOC, 2.Target Vol, 3.Target Cur, 4.Charging remaining time
+                GetOutputReq(gunIndex, pDcChargingInfo->Evboard_id);
+
+                //log_info("PresentChargingVoltage = %f ", pDcChargingInfo->PresentChargingVoltage);
+                //log_info("PresentChargingCurrent = %f ", pDcChargingInfo->PresentChargingCurrent);
+                //log_info("AvailableChargingPower = %f ", pDcChargingInfo->AvailableChargingPower);
+                //log_info("AvailableChargingCurrent = %f ", pDcChargingInfo->AvailableChargingCurrent);
+                //log_info("MaximumChargingVoltage = %f ", pDcChargingInfo->MaximumChargingVoltage);
+
+                // 設定當前輸出
+                SetPresentChargingOutputPower();
+
+                if (ShmSelectGunInfo->WaitDoCommPermission[gunIndex] == YES) {
+                    ShmSelectGunInfo->WaitDoCommPermission[gunIndex] = NO;
+                    //if (priorityLow == 1) {
+                    // 樁端輸出能力
+                    maxVol = pDcChargingInfo->MaximumChargingVoltage;
+                    maxCur = pDcChargingInfo->AvailableChargingCurrent;
+
+                    GetMaxVolAndCurMethod(gunIndex, &maxVol, &maxCur);
+
+                    //DS60-120 add
+                    if (LogInfo[gunIndex][EV_LOG_EVSE_MAX_VOL] != maxVol ||
+                            LogInfo[gunIndex][EV_LOG_EVSE_MAX_CUR] != maxCur) {
+                        LogInfo[gunIndex][EV_LOG_EVSE_MAX_VOL] = maxVol;
+                        LogInfo[gunIndex][EV_LOG_EVSE_MAX_CUR] = maxCur;
+
+                        log_info("To EV_%d Max_Vol = %.1f, Cap_Cur = %.1f, Cap_Pow = %.1f",
+                                 gunIndex,
+                                 maxVol / 10,
+                                 maxCur / 10,
+                                 pDcChargingInfo->AvailableChargingPower / 10);
+                    }
+
+                    pDcChargingInfo->RealMaxVoltage = maxVol;
+
+                    SetChargingPermission(gunIndex,
+                                          START,
+                                          pDcChargingInfo->AvailableChargingPower,
+                                          maxCur,
+                                          maxVol,
+                                          pDcChargingInfo->Evboard_id);
+
+                    // 取得車端電池資訊 : 1.AC or DC ? 2.Total battery cap, 3.Max battery vol, 4.Max battery cur
+                    GetEvBatteryInfo(gunIndex, pDcChargingInfo->Evboard_id);
+                }
+
+                GetClockTime(&_chk_ratingPower_timeout[gunIndex], NULL);
+                break;
+
+            case S_PREPARING_FOR_EVSE:
+            case S_CCS_PRECHARGE_ST0:
+            case S_CCS_PRECHARGE_ST1:
+                // 開始確認車端是否同意開始充電
+                GetOutputReq(gunIndex, pDcChargingInfo->Evboard_id);
+
+                // 設定當前輸出
+                SetPresentChargingOutputPower();
+
+                if (priorityLow % 5 == 1) {
+                    // 取得車端電池資訊 : 1.AC or DC ? 2.Total battery cap, 3.Max battery vol, 4.Max battery cur
+                    GetEvBatteryInfo(gunIndex, pDcChargingInfo->Evboard_id); //DS60-120 add
+
+                    // 樁端輸出能力改變
+                    SetPresentChargingOutputCap();
+                }
+
+                //DS60-120 add
+                if (LogInfo[gunIndex][EV_LOG_MAX_BATT_VOL] != pDcChargingInfo->EvBatteryMaxVoltage) {
+                    LogInfo[gunIndex][EV_LOG_MAX_BATT_VOL] = pDcChargingInfo->EvBatteryMaxVoltage;
+                    log_info("index = %d, Ev Maximum Battery Voltage = %f ",
+                             gunIndex,
+                             pDcChargingInfo->EvBatteryMaxVoltage);
+                }
+
+                if (LogInfo[gunIndex][EV_LOG_SOC] != pDcChargingInfo->EvBatterySoc) {
+                    LogInfo[gunIndex][EV_LOG_SOC] = pDcChargingInfo->EvBatterySoc;
+                    log_info("index = %d, SOC = %d ",
+                             gunIndex,
+                             pDcChargingInfo->EvBatterySoc);
+                }
+
+                // 持續通知 Isolation 測試狀態
+                if (priorityLow == 1) {
+                    // 拉 500 V 如果在一秒鐘內 GFD 都符合則 PASS
+//                      if (_chargingData[_index]->FireChargingVoltage >= 3500)
+//                         pDcChargingInfo->GroundFaultStatus = GFD_PASS;
+
+                    //log_info("To EV_%d GFD = %d ",   _index,pDcChargingInfo->GroundFaultStatus);
+                    //if(_chargingData[_index]->GroundFaultStatus != GFD_WAIT)
+                    {
+                        //if ((GetClockTimeoutValue(_derating_time) / 1000) > 1000)
+                        gfgResult = pDcChargingInfo->GroundFaultStatus;
+
+                        // GB & Chademo ~ Warning 也先算 Pass,因為 CCS 認證會驗 Warning 故不可更動
+                        if (pDcChargingInfo->Type == _Type_Chademo ||
+                                pDcChargingInfo->Type == _Type_GB) {
+                            if (gfgResult == GFD_WARNING) {
+                                gfgResult = GFD_PASS;
+                            }
+                        }
+
+                        if (gfgResult == GFD_WARNING || gfgResult == GFD_PASS) {
+                            if (((GetClockTimeoutValue(_chk_ratingPower_timeout[gunIndex]) / 1000) > 12000 &&
+                                    pDcChargingInfo->RealRatingPower > 0) ||
+                                    (GetClockTimeoutValue(_chk_ratingPower_timeout[gunIndex]) / 1000) > 14000) {
+                                //log_info("**********EvComm : gunIndex= %d, RealRatingPower = %d ",
+                                //            gunIndex,pDcChargingInfo->RealRatingPower);
+                                //gfgResult = GFD_PASS;
+
+                                //DS60-120 add
+                                if (LogInfo[gunIndex][EV_LOG_REAL_CAP_POW] != pDcChargingInfo->RealRatingPower) {
+                                    LogInfo[gunIndex][EV_LOG_REAL_CAP_POW] = pDcChargingInfo->RealRatingPower;
+                                    log_info("Conn %d, RealRatingPower = %d ",
+                                             gunIndex,
+                                             pDcChargingInfo->RealRatingPower);
+
+                                }
+                            } else {
+                                gfgResult = GFD_WAIT;
+                            }
+                        }
+
+                        SetIsolationStatus(gunIndex, gfgResult, pDcChargingInfo->Evboard_id);
+                    }
+
+                    if (pDcChargingInfo->SystemStatus == S_CCS_PRECHARGE_ST0 &&
+                            pDcChargingInfo->PrechargeStatus == PRECHARGE_READY
+                       ) {
+                        SetEvsePrechargeInfo(gunIndex, PRECHARGE_PRERELAY_PASS, pDcChargingInfo->Evboard_id);
+                    }
+                }
+                ftime(&waitChargingTime);
+                break;
+
+            case S_CHARGING:
+                //if (waitPsuVolwithRealyVol(gunIndex) == NO) {
+                //    continue;
+                //}
+                GetEvBatteryInfo(gunIndex, pDcChargingInfo->Evboard_id); //DS60-120 add
+                // 計算 Power
+                pDcChargingInfo->PresentChargingPower =
+                    ((float)((pDcChargingInfo->PresentChargingVoltage) *
+                             (pDcChargingInfo->PresentChargingCurrent)) / 1000);
+
+                //DS60-120 remove
+                if (chargingTime[gunIndex] == 0 ||
+                        chargingTime[gunIndex] > pDcChargingInfo->PresentChargedDuration) {
+                    chargingTime[gunIndex] = pDcChargingInfo->PresentChargedDuration;
+                } else {
+                    int passTime = pDcChargingInfo->PresentChargedDuration - chargingTime[gunIndex];
+
+                    if (passTime > 0) {
+                        float changingPow = (pDcChargingInfo->PresentChargingPower) * passTime / 3600;
+                        if (pSysConfig->BillingData.isBilling) {
+                            pDcChargingInfo->ChargingFee += changingPow * pSysConfig->BillingData.Cur_fee;
+                        }
+
+                        pDcChargingInfo->PresentChargedEnergy += changingPow;
+                        pDcChargingInfo->PowerConsumption += changingPow;
+                        ShmDcCommonData->pGunInfo[gunIndex].PowerConsumption += changingPow;
+                        chargingTime[gunIndex] = pDcChargingInfo->PresentChargedDuration;
+                    }
+                }
+
+                // 開始確認車端是否同意開始充電
+                GetOutputReq(gunIndex, pDcChargingInfo->Evboard_id);
+
+                // 設定當前輸出
+                ftime(&nowTime);
+                if (!(DiffTimeb(waitChargingTime, nowTime) < 5000 ||
+                        DiffTimeb(waitChargingTime, nowTime) < 0)) {
+                    psuOutputReady[gunIndex] = true;
+                }
+                SetPresentChargingOutputPower();
+
+                // for test end
+                if (priorityLow % 5 == 0) {
+                    // 樁端輸出能力改變
+                    SetPresentChargingOutputCap();
+                }
+
+                if ((pDcChargingInfo->GroundFaultStatus == GFD_FAIL) ||
+                        (pDcChargingInfo->Type == _Type_CCS_2)) {
+                    SetIsolationStatus(gunIndex,
+                                       pDcChargingInfo->GroundFaultStatus,
+                                       pDcChargingInfo->Evboard_id);
+                }
+                /*
+                else if (pDcChargingInfo->Type == _Type_CCS_2) {
+                SetIsolationStatus(gunIndex, pDcChargingInfo->GroundFaultStatus, pDcChargingInfo->Evboard_id);
+                }*/
+
+                // GFD 失敗再通知
+                if (priorityLow == 1) {
+                    if (pDcChargingInfo->Type == _Type_CCS_2 &&
+                            pDcChargingInfo->PrechargeStatus == PRECHARGE_READY) {
+                        SetEvsePrechargeInfo(gunIndex,
+                                             PRECHARGE_CHARELAY_PASS,
+                                             pDcChargingInfo->Evboard_id);
+                    }
+                }
+                break;
+
+            case S_ALARM:
+            case S_TERMINATING:
+                // 設定當前輸出
+                setCurrentOutput();
+                SetPresentChargingOutputPower();
+
+                // 槍鎖還在,則代表是樁端要求的停止
+                if (pDcChargingInfo->GunLocked == START ||
+                        pDcChargingInfo->Type == _Type_CCS_2) {
+                    uint8_t normalStop = 0x01;
+                    uint8_t stopReason[6] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
+
+                    if (GetStopChargingReasonByEvse(gunIndex, stopReason)) {
+                        normalStop = 0x02;
+                    }
+
+                    EvseStopChargingEvent(normalStop,
+                                          stopReason,
+                                          pDcChargingInfo->Evboard_id);
+
+                    SendErrorCount[gunIndex] += 1; //DS60-120 add
+                }
+
+                if (pDcChargingInfo->Type == _Type_CCS_2) {
+                    SetIsolationStatus(gunIndex,
+                                       pDcChargingInfo->GroundFaultStatus,
+                                       pDcChargingInfo->Evboard_id);
+                }
+
+                GetOutputReq(gunIndex, pDcChargingInfo->Evboard_id);
+
+                //DS60-120 add
+                if (pDcChargingInfo->SystemStatus == S_ALARM) {
+                    if (priorityLow == 1) {
+                        // 樁端輸出能力
+                        maxVol = pDcChargingInfo->MaximumChargingVoltage;
+                        maxCur = pDcChargingInfo->AvailableChargingCurrent;
+
+                        GetMaxVolAndCurMethod(gunIndex, &maxVol, &maxCur);
+
+                        SetChargingPermission(gunIndex,
+                                              STOP,
+                                              pDcChargingInfo->AvailableChargingPower,
+                                              maxCur,
+                                              maxVol,
+                                              pDcChargingInfo->Evboard_id);
+                    }
+                }
+                break;
+
+            case S_COMPLETE:
+                // 設定當前輸出
+                SetPresentChargingOutputPower();
+
+                if (priorityLow == 1) {
+                    // 樁端輸出能力
+                    maxVol = pDcChargingInfo->MaximumChargingVoltage;
+                    maxCur = pDcChargingInfo->AvailableChargingCurrent;
+
+                    GetMaxVolAndCurMethod(gunIndex, &maxVol, &maxCur);
+                    SetChargingPermission(gunIndex,
+                                          STOP,
+                                          pDcChargingInfo->AvailableChargingPower,
+                                          maxCur,
+                                          maxVol,
+                                          pDcChargingInfo->Evboard_id);
+
+                    //DS60-120 add
+                    //if (pDcChargingInfo->EvBatterySoc >= 100) {
+                    //    //滿電,則直接清掉錯誤
+                    //    if (pDcChargingInfo->Type == _Type_Chademo) {
+                    //        ClearAbnormalStatus_Chademo(gunIndex);
+                    //    } else if (pDcChargingInfo->Type == _Type_GB) {
+                    //        ClearAbnormalStatus_GB(gunIndex);
+                    //    } else if (pDcChargingInfo->Type == _Type_CCS_2) {
+                    //        ClearAbnormalStatus_CCS(gunIndex);
+                    //    }
+                    //}
+                }
+                break;
+            }//switch
+        }//for
+        Comcont >= 200 ? Comcont = 1: Comcont++;
+        priorityLow >= 20 ? priorityLow = 1 : priorityLow++;
+        usleep(50000);
+    }//while
+
+    return 0;
+}

+ 422 - 422
EVSE/Projects/DD360Tcci/Apps/ModuleEventLog/Module_EventLogging.c

@@ -1,422 +1,422 @@
-#include <sys/time.h>
-#include <sys/timeb.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <sys/types.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 <arpa/inet.h>
-#include <netinet/in.h>
-
-#include <unistd.h>
-#include <stdarg.h>
-#include <stdio.h>      /*標準輸入輸出定義*/
-#include <stdlib.h>     /*標準函數庫定義*/
-#include <unistd.h>     /*Unix 標準函數定義*/
-#include <fcntl.h>      /*檔控制定義*/
-#include <termios.h>    /*PPSIX 終端控制定義*/
-#include <errno.h>      /*錯誤號定義*/
-#include <errno.h>
-#include <string.h>
-#include <time.h>
-#include <ctype.h>
-#include <ifaddrs.h>
-
-#include "../Log/log.h"
-#include "../ShareMemory/shmMem.h"
-#include "../DataBase/DataBase.h"
-#include "../Define/define.h"
-#include "../Config.h"
-
-//------------------------------------------------------------------------------
-//struct SysConfigAndInfo         *ShmSysConfigAndInfo;
-//struct StatusCodeData           *ShmStatusCodeData;
-static struct SysConfigData *pSysConfig      = NULL;
-static struct SysInfoData *pSysInfo          = NULL;
-static struct WARNING_CODE_INFO *pSysWarning = NULL;
-static struct AlarmCodeData *pAlarmCode      = NULL;
-static struct InfoCodeData *pInfoCode        = NULL;
-static struct FaultCodeData *pFaultCode      = NULL;
-
-//sqlite3 *localDb; //DS60-120 add
-
-//------------------------------------------------------------------------------
-#define WRITE_FLASH_TIME                        (128)
-#define DB_FILE             "/Storage/ChargeLog/localCgargingRecord.db" //DS60-120 add
-
-//#define log_info(format, args...) StoreLogMsg("[%s:%d][%s][Info] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
-//#define log_warn(format, args...) StoreLogMsg("[%s:%d][%s][Warn] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
-//#define log_error(format, args...) StoreLogMsg("[%s:%d][%s][Error] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
-#define event_info(format, args...) StoreEventLogMsg("[%s:%d][%s][Info] "format, __FILE__, __LINE__, __FUNCTION__, ##args) //DS60-120 add
-
-/*
-int StoreLogMsg(const char *fmt, ...)
-{
-    char Buf[4096 + 256];
-    char buffer[4096];
-    va_list args;
-    struct timeb  SeqEndTime;
-    struct tm *tm;
-
-    va_start(args, fmt);
-    int rc = vsnprintf(buffer, sizeof(buffer), fmt, args);
-    va_end(args);
-
-    memset(Buf, 0, sizeof(Buf));
-    ftime(&SeqEndTime);
-    SeqEndTime.time = time(NULL);
-    tm = localtime(&SeqEndTime.time);
-
-    if (ShmSysConfigAndInfo->SysConfig.SwitchDebugFlag == YES) {
-        sprintf(Buf, "%02d:%02d:%02d:%03d - %s",
-                tm->tm_hour, tm->tm_min, tm->tm_sec, SeqEndTime.millitm, buffer);
-        printf("%s ", Buf);
-    } else {
-        sprintf(Buf, "echo \"%04d-%02d-%02d %02d:%02d:%02d:%03d - %s\" >> /Storage/SystemLog/[%04d.%02d]SystemLog",
-                tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec, SeqEndTime.millitm,
-                buffer,
-                tm->tm_year + 1900, tm->tm_mon + 1);
-        system(Buf);
-    }
-
-    return rc;
-}
-
-int StoreEventLogMsg(const char *fmt, ...)
-{
-    char Buf[4096 + 256];
-    char buffer[4096];
-    time_t CurrentTime;
-    struct tm *tm;
-    struct timeval tv;
-    va_list args;
-
-    va_start(args, fmt);
-    int rc = vsnprintf(buffer, sizeof(buffer), fmt, args);
-    va_end(args);
-
-    memset(Buf, 0, sizeof(Buf));
-    CurrentTime = time(NULL);
-    tm = localtime(&CurrentTime);
-    gettimeofday(&tv, NULL); // get microseconds, 10^-6
-
-    if ((ShmSysConfigAndInfo->SysConfig.ModelName != NULL) && (ShmSysConfigAndInfo->SysConfig.SerialNumber != NULL) && (strlen((char *)ShmSysConfigAndInfo->SysConfig.ModelName) >= 14)) {
-        sprintf(Buf, "echo -n \"[%04d.%02d.%02d %02d:%02d:%02d.%06ld]%s\" >> /Storage/EventLog/[%04d.%02d]%s_%s_EventLog",
-                tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec, tv.tv_usec,
-                buffer,
-                tm->tm_year + 1900, tm->tm_mon + 1,
-                ShmSysConfigAndInfo->SysConfig.ModelName,
-                ShmSysConfigAndInfo->SysConfig.SerialNumber);
-    } else {
-        sprintf(Buf, "echo -n \"[%04d.%02d.%02d %02d:%02d:%02d.%06ld]%s\" >> /Storage/EventLog/[%04d.%02d]EventLog",
-                tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec, tv.tv_usec,
-                buffer,
-                tm->tm_year + 1900, tm->tm_mon + 1);
-    }
-
-#ifdef SystemLogMessage
-    system(Buf);
-
-#endif
-
-#ifdef ConsloePrintLog
-    printf("[%04d.%02d.%02d %02d:%02d:%02d.%06ld]%s", tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec, tv.tv_usec, buffer);
-#endif
-
-    return rc;
-}
-
-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
-//=================================
-char *getTimeString(void)
-{
-    char *result = malloc(21);
-    time_t timep;
-    struct tm *p;
-    time(&timep);
-    p = gmtime(&timep);
-
-    sprintf(result, "[%04d-%02d-%02d %02d:%02d:%02d]", (1900 + p->tm_year), (1 + p->tm_mon), p->tm_mday, p->tm_hour, p->tm_hour, p->tm_sec);
-
-    return result;
-}
-
-//==========================================
-// Init all share memory
-//==========================================
-int InitShareMemory()
-{
-    int result = PASS;
-    int MeterSMId;
-
-    //creat ShmSysConfigAndInfo
-    if ((MeterSMId = shmget(ShmSysConfigAndInfoKey, sizeof(struct SysConfigAndInfo),  0777)) < 0) {
-        result = FAIL;
-    } else if ((ShmSysConfigAndInfo = shmat(MeterSMId, NULL, 0)) == (void *) - 1) {
-        result = FAIL;
-    }
-
-    //creat ShmStatusCodeData
-    if ((MeterSMId = shmget(ShmStatusCodeKey, sizeof(struct StatusCodeData),  0777)) < 0) {
-        result = FAIL;
-    } else if ((ShmStatusCodeData = shmat(MeterSMId, NULL, 0)) == (void *) - 1) {
-        result = FAIL;
-    }
-
-    return result;
-}
-*/
-
-//================================================
-// Main process
-//================================================
-void AddFaultCodeToBuf(uint8_t *Code)
-{
-    if (pSysWarning->WarningCount < 10) {
-        memcpy(&pSysWarning->WarningCode[pSysWarning->WarningCount][0], Code, 7);
-        pSysWarning->WarningCount++;
-    }
-}
-
-void RemoveFaultCodeToBuf(uint8_t *Code)
-{
-    uint8_t find = 0x01;
-    char _code[7];
-    sprintf(_code, "%s", Code);
-
-    // 把相關的錯誤碼一次移除,避免重複顯示
-    while (find) {
-        find = 0x00;
-        for (uint8_t i = 0; i < pSysWarning->WarningCount; i++) {
-            if (find == 0x00) {
-                if (memcmp(&pSysWarning->WarningCode[i][0], _code, 7) == 0) {
-                    find = 0x01;
-                }
-            } else {
-                memcpy(&pSysWarning->WarningCode[i - 1][0],
-                       &pSysWarning->WarningCode[i][0], 7);
-            }
-        }
-
-        if (find) {
-            pSysWarning->WarningCount--;
-        }
-    }
-}
-
-#if 0
-//==========================================
-// SQLite routne
-//==========================================
-int DB_Open(sqlite3 *db) //DS60-120 add
-{
-    int result = PASS;
-    char *errMsg = NULL;
-    char *createRecordSql = "CREATE TABLE IF NOT EXISTS event_record("
-                            "idx integer primary key AUTOINCREMENT, "
-                            "occurDatetime text NOT NULL, "
-                            "statusCode text NOT NULL"
-                            ");";
-
-    if (sqlite3_open(DB_FILE, &db)) {
-        result = FAIL;
-        log_error( "Can't open database: %s", sqlite3_errmsg(db));
-        sqlite3_close(db);
-    } else {
-        log_info( "Local event record database open successfully.");
-
-        if (sqlite3_exec(db, createRecordSql, 0, 0, &errMsg) != SQLITE_OK) {
-            result = FAIL;
-            log_error( "Create local event record table error message: %s", errMsg);
-        } else {
-            log_info( "Opened local event record table successfully");
-        }
-
-        sqlite3_close(db);
-    }
-
-    return result;
-}
-
-int DB_Insert_Record(sqlite3 *db, uint8_t *statusCode) //DS60-120 add
-{
-    int result = PASS;
-    char *errMsg = NULL;
-    char sqlStr[1024];
-
-    sprintf(sqlStr, "insert into event_record(occurDatetime, statusCode) values(CURRENT_TIMESTAMP, '%s');", statusCode);
-
-    if (sqlite3_open(DB_FILE, &db)) {
-        result = FAIL;
-        log_info( "Can't open database: %s", sqlite3_errmsg(db));
-        sqlite3_close(db);
-    } else {
-        log_info( "Local event record database open successfully.");
-        if (sqlite3_exec(db, sqlStr, 0, 0, &errMsg) != SQLITE_OK) {
-            result = FAIL;
-            log_info( "Insert local event record error message: %s", errMsg);
-        } else {
-            log_info( "Insert local event record successfully");
-        }
-
-        sprintf(sqlStr, "delete from event_record where idx < (select idx from event_record order by idx desc limit 1)-2000;");
-        if (sqlite3_exec(db, sqlStr, 0, 0, &errMsg) != SQLITE_OK) {
-            result = FAIL;
-            log_info( "delete local event_record error message: %s", errMsg);
-        } else {
-            log_info( "delete local event record successfully");
-        }
-
-        sqlite3_close(db);
-    }
-
-    return result;
-}
-#endif //0
-
-int main(void)
-{
-    int ByteCounter, BitCounter;
-    uint8_t tmp, EventCodeTmp[7] = {0};
-
-    //if (InitShareMemory() == FAIL) {
-    //    log_error("InitShareMemory NG");
-    //    if (ShmStatusCodeData != NULL) {
-    //        pAlarmCode->AlarmEvents.bits.FailToCreateShareMemory = 1;
-    //    }
-    //    sleep(5);
-    //    return 0;
-    //}
-    if (CreateAllCsuShareMemory() == FAIL) {
-        log_error("create share memory error");
-        return FAIL;
-    }
-
-    MappingGunChargingInfo("EventLog Task");
-
-    pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
-    pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
-    pSysWarning = (struct WARNING_CODE_INFO *)GetShmSysWarningInfo();
-
-    pAlarmCode = (struct AlarmCodeData *)GetShmAlarmCodeData();
-    pInfoCode = (struct InfoCodeData *)GetShmInfoCodeData();
-    pFaultCode = (struct FaultCodeData *)GetShmFaultCodeData();
-
-
-    for (;;) {
-        //check Fault Status
-        for (ByteCounter = 0; ByteCounter < sizeof(pFaultCode->PreviousFaultVal); ByteCounter++) {
-            usleep(WRITE_FLASH_TIME);
-            if (pFaultCode->FaultEvents.FaultVal[ByteCounter] == pFaultCode->PreviousFaultVal[ByteCounter]) {
-                continue;
-            }
-
-            tmp = pFaultCode->FaultEvents.FaultVal[ByteCounter]; //prevent be modified during following process
-            for (BitCounter = 0; BitCounter < 8; BitCounter++) {
-                usleep(WRITE_FLASH_TIME);
-                if (((tmp >> BitCounter) & 0x01) == ((pFaultCode->PreviousFaultVal[ByteCounter] >> BitCounter) & 0x01)) {
-                    continue;
-                }
-
-                memset(EventCodeTmp, 0, sizeof(EventCodeTmp));
-                memcpy(EventCodeTmp, GetFaultStatusCode(ByteCounter * 8 + BitCounter), sizeof(EventCodeTmp) - 1);
-                if (((tmp >> BitCounter) & 0x01) == 0) { //Recovered
-                    //EventCodeTmp[0]=1;
-                    log_info("Recovery Fault Code = %s", EventCodeTmp);
-                    pFaultCode->PreviousFaultVal[ByteCounter] &= ~(1 << BitCounter);
-                    RemoveFaultCodeToBuf(EventCodeTmp);
-                    EventCodeTmp[0] = '1';//DS60-120 add
-                } else {
-                    log_info("Fault Code = %s", EventCodeTmp);
-                    pFaultCode->PreviousFaultVal[ByteCounter] |= (1 << BitCounter);
-                    AddFaultCodeToBuf(EventCodeTmp);
-                }
-                event_info("%s", EventCodeTmp); //DS60-120 add
-                InsertEventRecord(EventCodeTmp); //DS60-120 add
-            }
-        }
-
-        //check Alarm Status
-        for (ByteCounter = 0; ByteCounter < sizeof(pAlarmCode->PreviousAlarmVal); ByteCounter++) {
-            usleep(WRITE_FLASH_TIME);
-            if (pAlarmCode->AlarmEvents.AlarmVal[ByteCounter] == pAlarmCode->PreviousAlarmVal[ByteCounter]) {
-                continue;
-            }
-
-            tmp = pAlarmCode->AlarmEvents.AlarmVal[ByteCounter]; //prevent be modified during following process
-            for (BitCounter = 0; BitCounter < 8; BitCounter++) {
-                usleep(WRITE_FLASH_TIME);
-                if (((tmp >> BitCounter) & 0x01) == ((pAlarmCode->PreviousAlarmVal[ByteCounter] >> BitCounter) & 0x01)) {
-                    continue;
-                }
-
-                memset(EventCodeTmp, 0, sizeof(EventCodeTmp));
-                memcpy(EventCodeTmp, GetAlarmStatusCode(ByteCounter * 8 + BitCounter), sizeof(EventCodeTmp) - 1);
-                if (((tmp >> BitCounter) & 0x01) == 0) { //Recovered
-                    //EventCodeTmp[0]=1;
-                    log_info("Recovery Alarm Code = %s", EventCodeTmp);
-                    pAlarmCode->PreviousAlarmVal[ByteCounter] &= ~(1 << BitCounter);
-                    RemoveFaultCodeToBuf(EventCodeTmp);
-                    EventCodeTmp[0] = '1';//DS60-120 add
-                } else {
-                    log_info("Alarm Code = %s", EventCodeTmp);
-                    pAlarmCode->PreviousAlarmVal[ByteCounter] |= (1 << BitCounter);
-                    AddFaultCodeToBuf(EventCodeTmp);
-                }
-                event_info("%s", EventCodeTmp); //DS60-120 add
-                InsertEventRecord(EventCodeTmp); //DS60-120 add
-            }
-        }
-
-        //check Info Status
-        for (ByteCounter = 0; ByteCounter < sizeof(pInfoCode->PreviousInfoVal); ByteCounter++) {
-            usleep(WRITE_FLASH_TIME);
-            if (pInfoCode->InfoEvents.InfoVal[ByteCounter] == pInfoCode->PreviousInfoVal[ByteCounter]) {
-                continue;
-            }
-
-            tmp = pInfoCode->InfoEvents.InfoVal[ByteCounter]; //prevent be modified during following process
-            for (BitCounter = 0; BitCounter < 8; BitCounter++) {
-                usleep(WRITE_FLASH_TIME);
-                if (((tmp >> BitCounter) & 0x01) == ((pInfoCode->PreviousInfoVal[ByteCounter] >> BitCounter) & 0x01)) {
-                    continue;
-                }
-
-                memset(EventCodeTmp, 0, sizeof(EventCodeTmp));
-                memcpy(EventCodeTmp, GetInfoStatusCode(ByteCounter * 8 + BitCounter), sizeof(EventCodeTmp) - 1);
-                if (((tmp >> BitCounter) & 0x01) == 0) { //Recovered
-                    //EventCodeTmp[0]=1;
-                    log_info("Recovery Info Code = %s", EventCodeTmp);
-                    pInfoCode->PreviousInfoVal[ByteCounter] &= ~(1 << BitCounter);
-                    RemoveFaultCodeToBuf(EventCodeTmp);
-                    EventCodeTmp[0] = '1';//DS60-120 add
-                } else {
-                    log_info("Info Code = %s", EventCodeTmp);
-                    pInfoCode->PreviousInfoVal[ByteCounter] |= (1 << BitCounter);
-                    AddFaultCodeToBuf(EventCodeTmp);
-                }
-                event_info("%s", EventCodeTmp); //DS60-120 add
-                InsertEventRecord(EventCodeTmp); //DS60-120 add
-            }
-        }
-        usleep(500000);
-    }
-
-    return FAIL;
-}
+#include <sys/time.h>
+#include <sys/timeb.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <sys/types.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 <arpa/inet.h>
+#include <netinet/in.h>
+
+#include <unistd.h>
+#include <stdarg.h>
+#include <stdio.h>      /*標準輸入輸出定義*/
+#include <stdlib.h>     /*標準函數庫定義*/
+#include <unistd.h>     /*Unix 標準函數定義*/
+#include <fcntl.h>      /*檔控制定義*/
+#include <termios.h>    /*PPSIX 終端控制定義*/
+#include <errno.h>      /*錯誤號定義*/
+#include <errno.h>
+#include <string.h>
+#include <time.h>
+#include <ctype.h>
+#include <ifaddrs.h>
+
+#include "../Log/log.h"
+#include "../ShareMemory/shmMem.h"
+#include "../DataBase/DataBase.h"
+#include "../Define/define.h"
+#include "../Config.h"
+
+//------------------------------------------------------------------------------
+//struct SysConfigAndInfo         *ShmSysConfigAndInfo;
+//struct StatusCodeData           *ShmStatusCodeData;
+static struct SysConfigData *pSysConfig      = NULL;
+static struct SysInfoData *pSysInfo          = NULL;
+static struct WARNING_CODE_INFO *pSysWarning = NULL;
+static struct AlarmCodeData *pAlarmCode      = NULL;
+static struct InfoCodeData *pInfoCode        = NULL;
+static struct FaultCodeData *pFaultCode      = NULL;
+
+//sqlite3 *localDb; //DS60-120 add
+
+//------------------------------------------------------------------------------
+#define WRITE_FLASH_TIME                        (128)
+#define DB_FILE             "/Storage/ChargeLog/localCgargingRecord.db" //DS60-120 add
+
+//#define log_info(format, args...) StoreLogMsg("[%s:%d][%s][Info] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
+//#define log_warn(format, args...) StoreLogMsg("[%s:%d][%s][Warn] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
+//#define log_error(format, args...) StoreLogMsg("[%s:%d][%s][Error] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
+#define event_info(format, args...) StoreEventLogMsg("[%s:%d][%s][Info] "format, __FILE__, __LINE__, __FUNCTION__, ##args) //DS60-120 add
+
+/*
+int StoreLogMsg(const char *fmt, ...)
+{
+    char Buf[4096 + 256];
+    char buffer[4096];
+    va_list args;
+    struct timeb  SeqEndTime;
+    struct tm *tm;
+
+    va_start(args, fmt);
+    int rc = vsnprintf(buffer, sizeof(buffer), fmt, args);
+    va_end(args);
+
+    memset(Buf, 0, sizeof(Buf));
+    ftime(&SeqEndTime);
+    SeqEndTime.time = time(NULL);
+    tm = localtime(&SeqEndTime.time);
+
+    if (ShmSysConfigAndInfo->SysConfig.SwitchDebugFlag == YES) {
+        sprintf(Buf, "%02d:%02d:%02d:%03d - %s",
+                tm->tm_hour, tm->tm_min, tm->tm_sec, SeqEndTime.millitm, buffer);
+        printf("%s ", Buf);
+    } else {
+        sprintf(Buf, "echo \"%04d-%02d-%02d %02d:%02d:%02d:%03d - %s\" >> /Storage/SystemLog/[%04d.%02d]SystemLog",
+                tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec, SeqEndTime.millitm,
+                buffer,
+                tm->tm_year + 1900, tm->tm_mon + 1);
+        system(Buf);
+    }
+
+    return rc;
+}
+
+int StoreEventLogMsg(const char *fmt, ...)
+{
+    char Buf[4096 + 256];
+    char buffer[4096];
+    time_t CurrentTime;
+    struct tm *tm;
+    struct timeval tv;
+    va_list args;
+
+    va_start(args, fmt);
+    int rc = vsnprintf(buffer, sizeof(buffer), fmt, args);
+    va_end(args);
+
+    memset(Buf, 0, sizeof(Buf));
+    CurrentTime = time(NULL);
+    tm = localtime(&CurrentTime);
+    gettimeofday(&tv, NULL); // get microseconds, 10^-6
+
+    if ((ShmSysConfigAndInfo->SysConfig.ModelName != NULL) && (ShmSysConfigAndInfo->SysConfig.SerialNumber != NULL) && (strlen((char *)ShmSysConfigAndInfo->SysConfig.ModelName) >= 14)) {
+        sprintf(Buf, "echo -n \"[%04d.%02d.%02d %02d:%02d:%02d.%06ld]%s\" >> /Storage/EventLog/[%04d.%02d]%s_%s_EventLog",
+                tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec, tv.tv_usec,
+                buffer,
+                tm->tm_year + 1900, tm->tm_mon + 1,
+                ShmSysConfigAndInfo->SysConfig.ModelName,
+                ShmSysConfigAndInfo->SysConfig.SerialNumber);
+    } else {
+        sprintf(Buf, "echo -n \"[%04d.%02d.%02d %02d:%02d:%02d.%06ld]%s\" >> /Storage/EventLog/[%04d.%02d]EventLog",
+                tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec, tv.tv_usec,
+                buffer,
+                tm->tm_year + 1900, tm->tm_mon + 1);
+    }
+
+#ifdef SystemLogMessage
+    system(Buf);
+
+#endif
+
+#ifdef ConsloePrintLog
+    printf("[%04d.%02d.%02d %02d:%02d:%02d.%06ld]%s", tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec, tv.tv_usec, buffer);
+#endif
+
+    return rc;
+}
+
+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
+//=================================
+char *getTimeString(void)
+{
+    char *result = malloc(21);
+    time_t timep;
+    struct tm *p;
+    time(&timep);
+    p = gmtime(&timep);
+
+    sprintf(result, "[%04d-%02d-%02d %02d:%02d:%02d]", (1900 + p->tm_year), (1 + p->tm_mon), p->tm_mday, p->tm_hour, p->tm_hour, p->tm_sec);
+
+    return result;
+}
+
+//==========================================
+// Init all share memory
+//==========================================
+int InitShareMemory()
+{
+    int result = PASS;
+    int MeterSMId;
+
+    //creat ShmSysConfigAndInfo
+    if ((MeterSMId = shmget(ShmSysConfigAndInfoKey, sizeof(struct SysConfigAndInfo),  0777)) < 0) {
+        result = FAIL;
+    } else if ((ShmSysConfigAndInfo = shmat(MeterSMId, NULL, 0)) == (void *) - 1) {
+        result = FAIL;
+    }
+
+    //creat ShmStatusCodeData
+    if ((MeterSMId = shmget(ShmStatusCodeKey, sizeof(struct StatusCodeData),  0777)) < 0) {
+        result = FAIL;
+    } else if ((ShmStatusCodeData = shmat(MeterSMId, NULL, 0)) == (void *) - 1) {
+        result = FAIL;
+    }
+
+    return result;
+}
+*/
+
+//================================================
+// Main process
+//================================================
+void AddFaultCodeToBuf(uint8_t *Code)
+{
+    if (pSysWarning->WarningCount < 10) {
+        memcpy(&pSysWarning->WarningCode[pSysWarning->WarningCount][0], Code, 7);
+        pSysWarning->WarningCount++;
+    }
+}
+
+void RemoveFaultCodeToBuf(uint8_t *Code)
+{
+    uint8_t find = 0x01;
+    char _code[7];
+    sprintf(_code, "%s", Code);
+
+    // 把相關的錯誤碼一次移除,避免重複顯示
+    while (find) {
+        find = 0x00;
+        for (uint8_t i = 0; i < pSysWarning->WarningCount; i++) {
+            if (find == 0x00) {
+                if (memcmp(&pSysWarning->WarningCode[i][0], _code, 7) == 0) {
+                    find = 0x01;
+                }
+            } else {
+                memcpy(&pSysWarning->WarningCode[i - 1][0],
+                       &pSysWarning->WarningCode[i][0], 7);
+            }
+        }
+
+        if (find) {
+            pSysWarning->WarningCount--;
+        }
+    }
+}
+
+#if 0
+//==========================================
+// SQLite routne
+//==========================================
+int DB_Open(sqlite3 *db) //DS60-120 add
+{
+    int result = PASS;
+    char *errMsg = NULL;
+    char *createRecordSql = "CREATE TABLE IF NOT EXISTS event_record("
+                            "idx integer primary key AUTOINCREMENT, "
+                            "occurDatetime text NOT NULL, "
+                            "statusCode text NOT NULL"
+                            ");";
+
+    if (sqlite3_open(DB_FILE, &db)) {
+        result = FAIL;
+        log_error( "Can't open database: %s", sqlite3_errmsg(db));
+        sqlite3_close(db);
+    } else {
+        log_info( "Local event record database open successfully.");
+
+        if (sqlite3_exec(db, createRecordSql, 0, 0, &errMsg) != SQLITE_OK) {
+            result = FAIL;
+            log_error( "Create local event record table error message: %s", errMsg);
+        } else {
+            log_info( "Opened local event record table successfully");
+        }
+
+        sqlite3_close(db);
+    }
+
+    return result;
+}
+
+int DB_Insert_Record(sqlite3 *db, uint8_t *statusCode) //DS60-120 add
+{
+    int result = PASS;
+    char *errMsg = NULL;
+    char sqlStr[1024];
+
+    sprintf(sqlStr, "insert into event_record(occurDatetime, statusCode) values(CURRENT_TIMESTAMP, '%s');", statusCode);
+
+    if (sqlite3_open(DB_FILE, &db)) {
+        result = FAIL;
+        log_info( "Can't open database: %s", sqlite3_errmsg(db));
+        sqlite3_close(db);
+    } else {
+        log_info( "Local event record database open successfully.");
+        if (sqlite3_exec(db, sqlStr, 0, 0, &errMsg) != SQLITE_OK) {
+            result = FAIL;
+            log_info( "Insert local event record error message: %s", errMsg);
+        } else {
+            log_info( "Insert local event record successfully");
+        }
+
+        sprintf(sqlStr, "delete from event_record where idx < (select idx from event_record order by idx desc limit 1)-2000;");
+        if (sqlite3_exec(db, sqlStr, 0, 0, &errMsg) != SQLITE_OK) {
+            result = FAIL;
+            log_info( "delete local event_record error message: %s", errMsg);
+        } else {
+            log_info( "delete local event record successfully");
+        }
+
+        sqlite3_close(db);
+    }
+
+    return result;
+}
+#endif //0
+
+int main(void)
+{
+    int ByteCounter, BitCounter;
+    uint8_t tmp, EventCodeTmp[7] = {0};
+
+    //if (InitShareMemory() == FAIL) {
+    //    log_error("InitShareMemory NG");
+    //    if (ShmStatusCodeData != NULL) {
+    //        pAlarmCode->AlarmEvents.bits.FailToCreateShareMemory = 1;
+    //    }
+    //    sleep(5);
+    //    return 0;
+    //}
+    if (CreateAllCsuShareMemory() == FAIL) {
+        log_error("create share memory error");
+        return FAIL;
+    }
+
+    MappingGunChargingInfo("EventLog Task");
+
+    pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
+    pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
+    pSysWarning = (struct WARNING_CODE_INFO *)GetShmSysWarningInfo();
+
+    pAlarmCode = (struct AlarmCodeData *)GetShmAlarmCodeData();
+    pInfoCode = (struct InfoCodeData *)GetShmInfoCodeData();
+    pFaultCode = (struct FaultCodeData *)GetShmFaultCodeData();
+
+
+    for (;;) {
+        //check Fault Status
+        for (ByteCounter = 0; ByteCounter < sizeof(pFaultCode->PreviousFaultVal); ByteCounter++) {
+            usleep(WRITE_FLASH_TIME);
+            if (pFaultCode->FaultEvents.FaultVal[ByteCounter] == pFaultCode->PreviousFaultVal[ByteCounter]) {
+                continue;
+            }
+
+            tmp = pFaultCode->FaultEvents.FaultVal[ByteCounter]; //prevent be modified during following process
+            for (BitCounter = 0; BitCounter < 8; BitCounter++) {
+                usleep(WRITE_FLASH_TIME);
+                if (((tmp >> BitCounter) & 0x01) == ((pFaultCode->PreviousFaultVal[ByteCounter] >> BitCounter) & 0x01)) {
+                    continue;
+                }
+
+                memset(EventCodeTmp, 0, sizeof(EventCodeTmp));
+                memcpy(EventCodeTmp, GetFaultStatusCode(ByteCounter * 8 + BitCounter), sizeof(EventCodeTmp) - 1);
+                if (((tmp >> BitCounter) & 0x01) == 0) { //Recovered
+                    //EventCodeTmp[0]=1;
+                    log_info("Recovery Fault Code = %s", EventCodeTmp);
+                    pFaultCode->PreviousFaultVal[ByteCounter] &= ~(1 << BitCounter);
+                    RemoveFaultCodeToBuf(EventCodeTmp);
+                    EventCodeTmp[0] = '1';//DS60-120 add
+                } else {
+                    log_info("Fault Code = %s", EventCodeTmp);
+                    pFaultCode->PreviousFaultVal[ByteCounter] |= (1 << BitCounter);
+                    AddFaultCodeToBuf(EventCodeTmp);
+                }
+                event_info("%s", EventCodeTmp); //DS60-120 add
+                InsertEventRecord(EventCodeTmp); //DS60-120 add
+            }
+        }
+
+        //check Alarm Status
+        for (ByteCounter = 0; ByteCounter < sizeof(pAlarmCode->PreviousAlarmVal); ByteCounter++) {
+            usleep(WRITE_FLASH_TIME);
+            if (pAlarmCode->AlarmEvents.AlarmVal[ByteCounter] == pAlarmCode->PreviousAlarmVal[ByteCounter]) {
+                continue;
+            }
+
+            tmp = pAlarmCode->AlarmEvents.AlarmVal[ByteCounter]; //prevent be modified during following process
+            for (BitCounter = 0; BitCounter < 8; BitCounter++) {
+                usleep(WRITE_FLASH_TIME);
+                if (((tmp >> BitCounter) & 0x01) == ((pAlarmCode->PreviousAlarmVal[ByteCounter] >> BitCounter) & 0x01)) {
+                    continue;
+                }
+
+                memset(EventCodeTmp, 0, sizeof(EventCodeTmp));
+                memcpy(EventCodeTmp, GetAlarmStatusCode(ByteCounter * 8 + BitCounter), sizeof(EventCodeTmp) - 1);
+                if (((tmp >> BitCounter) & 0x01) == 0) { //Recovered
+                    //EventCodeTmp[0]=1;
+                    log_info("Recovery Alarm Code = %s", EventCodeTmp);
+                    pAlarmCode->PreviousAlarmVal[ByteCounter] &= ~(1 << BitCounter);
+                    RemoveFaultCodeToBuf(EventCodeTmp);
+                    EventCodeTmp[0] = '1';//DS60-120 add
+                } else {
+                    log_info("Alarm Code = %s", EventCodeTmp);
+                    pAlarmCode->PreviousAlarmVal[ByteCounter] |= (1 << BitCounter);
+                    AddFaultCodeToBuf(EventCodeTmp);
+                }
+                event_info("%s", EventCodeTmp); //DS60-120 add
+                InsertEventRecord(EventCodeTmp); //DS60-120 add
+            }
+        }
+
+        //check Info Status
+        for (ByteCounter = 0; ByteCounter < sizeof(pInfoCode->PreviousInfoVal); ByteCounter++) {
+            usleep(WRITE_FLASH_TIME);
+            if (pInfoCode->InfoEvents.InfoVal[ByteCounter] == pInfoCode->PreviousInfoVal[ByteCounter]) {
+                continue;
+            }
+
+            tmp = pInfoCode->InfoEvents.InfoVal[ByteCounter]; //prevent be modified during following process
+            for (BitCounter = 0; BitCounter < 8; BitCounter++) {
+                usleep(WRITE_FLASH_TIME);
+                if (((tmp >> BitCounter) & 0x01) == ((pInfoCode->PreviousInfoVal[ByteCounter] >> BitCounter) & 0x01)) {
+                    continue;
+                }
+
+                memset(EventCodeTmp, 0, sizeof(EventCodeTmp));
+                memcpy(EventCodeTmp, GetInfoStatusCode(ByteCounter * 8 + BitCounter), sizeof(EventCodeTmp) - 1);
+                if (((tmp >> BitCounter) & 0x01) == 0) { //Recovered
+                    //EventCodeTmp[0]=1;
+                    log_info("Recovery Info Code = %s", EventCodeTmp);
+                    pInfoCode->PreviousInfoVal[ByteCounter] &= ~(1 << BitCounter);
+                    RemoveFaultCodeToBuf(EventCodeTmp);
+                    EventCodeTmp[0] = '1';//DS60-120 add
+                } else {
+                    log_info("Info Code = %s", EventCodeTmp);
+                    pInfoCode->PreviousInfoVal[ByteCounter] |= (1 << BitCounter);
+                    AddFaultCodeToBuf(EventCodeTmp);
+                }
+                event_info("%s", EventCodeTmp); //DS60-120 add
+                InsertEventRecord(EventCodeTmp); //DS60-120 add
+            }
+        }
+        usleep(500000);
+    }
+
+    return FAIL;
+}

+ 492 - 492
EVSE/Projects/DD360Tcci/Apps/ModuleInternalComm/AcPlug.c

@@ -1,492 +1,492 @@
-#include <stdio.h>      /*標準輸入輸出定義*/
-#include <stdlib.h>     /*標準函數庫定義*/
-#include <string.h>
-#include <stdint.h>
-#include <time.h>
-
-#include <unistd.h>
-#include <sys/time.h>
-#include <sys/timeb.h>
-
-#include "../Define/define.h"
-#include "../ShareMemory/shmMem.h"
-#include "../Config.h"
-#include "../Log/log.h"
-#include "Module_InternalComm.h"
-#include "internalComm.h"
-
-//------------------------------------------------------------------------------
-static struct SysConfigData *pSysConfig = NULL;
-static struct SysInfoData *pSysInfo = NULL;
-static struct AlarmCodeData *pAlarmCode = NULL;
-static struct InfoCodeData *pInfoCode = NULL;
-static struct FaultCodeData *pFaultCode = NULL;
-static struct OCPP16Data *ShmOCPP16Data = NULL;
-
-static int Uart5Fd = 0;
-
-static struct timespec  _ac_charging_comp;
-static struct timespec  _ac_preparing;
-static struct timeb    _ac_startChargingTime;
-static struct timeb    _ac_endChargingTime;
-
-static Ac_Status acStatus;
-static Ac_Led_Status ledStatus;
-static Ac_Alarm_code acAlarmCode;
-static Ac_Charging_energy acChargingEnergy;
-static Ac_Charging_current acChargingCurrent;
-
-static int _alarm_code[] = {
-    AC_OVP,
-    AC_UVP,
-    AC_OCP,
-    AC_OTP,
-    AC_GMI_FAULT,
-    AC_CP_ERROR,
-    AC_AC_LEAKAGE,
-    AC_DC_LEAKAGE,
-    AC_SYSTEM_SELFTEST_FAULT,
-    AC_HANDSHAKE_TIMEOUT,
-    AC_EMC_STOP,
-    AC_RELAY_WELDING,
-    AC_GF_MODULE_FAULT,
-    AC_SHUTTER_FAULT,
-    AC_LOCKER_FAULT,
-    AC_POWER_DROP,
-    AC_CIRCUIT_SHORT,
-    AC_ROTARY_SWITCH_FAULT,
-    AC_RELAY_DRIVE_FAULT
-};
-
-//------------------------------------------------------------------------------
-static void OcppStopTransation(uint8_t gunIndex)
-{
-    struct ChargingInfoData *pAcChargingInfo = (struct ChargingInfoData *)GetAcChargingInfoData(0);
-
-    if (strcmp((char *)pAcChargingInfo->StartUserId, "") == EQUAL) {
-        strcpy((char *)ShmOCPP16Data->StopTransaction[gunIndex].IdTag,
-               (char *)ShmOCPP16Data->StopTransaction[gunIndex].IdTag);
-    } else {
-        strcpy((char *)ShmOCPP16Data->StopTransaction[gunIndex].IdTag,
-               (char *)pAcChargingInfo->StartUserId);
-    }
-
-    log_info("AC IdTag = %s \n", ShmOCPP16Data->StopTransaction[gunIndex].IdTag);
-    ShmOCPP16Data->CpMsg.bits[gunIndex].StopTransactionReq = YES;
-}
-
-static void SetCpDuty(uint8_t _value)
-{
-    Config_Ac_Duty(Uart5Fd, ADDR_AC_PLUG, _value);
-}
-
-static uint8_t GetChargingCurrent(void)
-{
-    return Query_Charging_Current(Uart5Fd, ADDR_AC_PLUG, &acChargingCurrent);
-}
-
-static uint8_t GetChargingEnergy(void)
-{
-    return Query_Charging_Energy(Uart5Fd, ADDR_AC_PLUG, &acChargingEnergy);
-}
-
-static void ChangeStartOrStopDateTime(uint8_t isStart)
-{
-    char cmdBuf[32];
-    struct timeb csuTime;
-    struct tm *tmCSU;
-    struct ChargingInfoData *pAcChargingInfo = (struct ChargingInfoData *)GetAcChargingInfoData(0);
-
-    ftime(&csuTime);
-    tmCSU = localtime(&csuTime.time);
-
-    sprintf(cmdBuf, "%04d-%02d-%02d %02d:%02d:%02d",
-            tmCSU->tm_year + 1900,
-            tmCSU->tm_mon + 1,
-            tmCSU->tm_mday,
-            tmCSU->tm_hour,
-            tmCSU->tm_min,
-            tmCSU->tm_sec);
-
-    if (isStart) {
-        strcpy((char *)pAcChargingInfo->StartDateTime, cmdBuf);
-    } else {
-        strcpy((char *)pAcChargingInfo->StopDateTime, cmdBuf);
-    }
-}
-
-static void OcppStartTransation(uint8_t gunIndex)
-{
-    struct ChargingInfoData *pAcChargingInfo = (struct ChargingInfoData *)GetAcChargingInfoData(0);
-
-    if (strcmp((char *)pAcChargingInfo->StartUserId, "") == EQUAL) {
-        strcpy((char *)ShmOCPP16Data->StartTransaction[gunIndex].IdTag,
-               (char *)ShmOCPP16Data->StartTransaction[gunIndex].IdTag);
-    } else {
-        strcpy((char *)ShmOCPP16Data->StartTransaction[gunIndex].IdTag,
-               (char *)pAcChargingInfo->StartUserId);
-    }
-
-    log_info("AC IdTag = %s \n", ShmOCPP16Data->StartTransaction[gunIndex].IdTag);
-    ShmOCPP16Data->CpMsg.bits[gunIndex].StartTransactionReq = YES;
-}
-
-static void SetLegacyReq(uint8_t _switch)
-{
-    Config_Legacy_Req(Uart5Fd, ADDR_AC_PLUG, _switch);
-}
-
-static void ChangeLedStatus(void)
-{
-    struct ChargingInfoData *pAcChargingInfo = (struct ChargingInfoData *)GetAcChargingInfoData(0);
-
-    if (pAcChargingInfo->SystemStatus == S_IDLE) {
-        ledStatus.ActionMode = 1;
-    } else if (pAcChargingInfo->SystemStatus == S_PREPARNING) {
-        ledStatus.ActionMode = 3;
-    } else if (pAcChargingInfo->SystemStatus == S_CHARGING) {
-        ledStatus.ActionMode = 4;
-    }
-
-    Config_LED_Status(Uart5Fd, ADDR_AC_PLUG, &ledStatus);
-}
-
-static uint8_t isModeChange(void)
-{
-    uint8_t result = NO;
-    struct ChargingInfoData *pAcChargingInfo = (struct ChargingInfoData *)GetAcChargingInfoData(0);
-
-    if (pAcChargingInfo->SystemStatus != pAcChargingInfo->PreviousSystemStatus) {
-        result = YES;
-        pAcChargingInfo->PreviousSystemStatus = pAcChargingInfo->SystemStatus;
-    }
-
-    return result;
-}
-
-static bool OcppRemoteStop(uint8_t gunIndex)
-{
-    bool result = ShmOCPP16Data->CsMsg.bits[gunIndex].RemoteStopTransactionReq;
-
-    if (ShmOCPP16Data->CsMsg.bits[gunIndex].RemoteStopTransactionReq == YES) {
-        strcpy((char *)ShmOCPP16Data->StopTransaction[gunIndex].StopReason, "Remote");
-        ShmOCPP16Data->CsMsg.bits[gunIndex].RemoteStopTransactionReq = NO;
-    }
-
-    return result;
-}
-
-static void CheckAlarmOccur(void)
-{
-    bool isErr = false;
-    uint8_t count = 0;
-    struct ChargingInfoData *pAcChargingInfo = (struct ChargingInfoData *)GetAcChargingInfoData(0);
-
-    for (count = 0; count < sizeof(_alarm_code) / sizeof(_alarm_code[0]); count++) {
-        if (acAlarmCode.AcAlarmCode & _alarm_code[count]) {
-            isErr = true;
-            switch (_alarm_code[count]) {
-            case AC_OVP: pAlarmCode->AlarmEvents.bits.AcSystemInputOVP = YES; break;
-            case AC_UVP: pAlarmCode->AlarmEvents.bits.AcSystemInputUVP = YES; break;
-            case AC_OCP: pAlarmCode->AlarmEvents.bits.SystemAcOutputOCP = YES; break;
-            case AC_OTP: pAlarmCode->AlarmEvents.bits.SystemAmbientOTP = YES; break;
-            case AC_GMI_FAULT: pAlarmCode->AlarmEvents.bits.AcGroundfaultFail = YES; break;
-            case AC_CP_ERROR: pInfoCode->InfoEvents.bits.PilotFault = YES; break;
-            case AC_AC_LEAKAGE: pAlarmCode->AlarmEvents.bits.RcdTrip = YES; break;
-            case AC_DC_LEAKAGE: pAlarmCode->AlarmEvents.bits.RcdTrip = YES; break;
-            case AC_SYSTEM_SELFTEST_FAULT: pAlarmCode->AlarmEvents.bits.McuSelftestFail = YES; break;
-            case AC_HANDSHAKE_TIMEOUT: break;
-            //case AC_EMC_STOP: pAlarmCode->AlarmEvents.bits.EmergencyStopTrip = YES; break;
-            case AC_RELAY_WELDING: pFaultCode->FaultEvents.bits.AcOutputRelayWelding = YES; break;
-            case AC_GF_MODULE_FAULT: pFaultCode->FaultEvents.bits.RcdSelfTestFail = YES; break;
-            case AC_SHUTTER_FAULT: break;
-            case AC_LOCKER_FAULT: pFaultCode->FaultEvents.bits.AcConnectorLockFail = YES; break;
-            case AC_POWER_DROP: pAlarmCode->AlarmEvents.bits.SystemL1InputDrop = YES; break;
-            case AC_CIRCUIT_SHORT: pAlarmCode->AlarmEvents.bits.CircuitShort = YES; break;
-            case AC_ROTARY_SWITCH_FAULT: break;
-            case AC_RELAY_DRIVE_FAULT: pFaultCode->FaultEvents.bits.AcOutputRelayDrivingFault = YES; break;
-            }
-        } else {
-            switch (_alarm_code[count]) {
-            case AC_OVP: pAlarmCode->AlarmEvents.bits.AcSystemInputOVP = NO; break;
-            case AC_UVP: pAlarmCode->AlarmEvents.bits.AcSystemInputUVP = NO; break;
-            case AC_OCP: pAlarmCode->AlarmEvents.bits.SystemAcOutputOCP = NO; break;
-            case AC_OTP: pAlarmCode->AlarmEvents.bits.SystemAmbientOTP = NO; break;
-            case AC_GMI_FAULT: pAlarmCode->AlarmEvents.bits.AcGroundfaultFail = NO; break;
-            case AC_CP_ERROR: pInfoCode->InfoEvents.bits.PilotFault = NO; break;
-            case AC_AC_LEAKAGE: pAlarmCode->AlarmEvents.bits.RcdTrip = NO; break;
-            case AC_DC_LEAKAGE: pAlarmCode->AlarmEvents.bits.RcdTrip = NO; break;
-            case AC_SYSTEM_SELFTEST_FAULT: pAlarmCode->AlarmEvents.bits.McuSelftestFail = NO; break;
-            case AC_HANDSHAKE_TIMEOUT: break;
-            //case AC_EMC_STOP: pAlarmCode->AlarmEvents.bits.EmergencyStopTrip = NO; break;
-            case AC_RELAY_WELDING: pFaultCode->FaultEvents.bits.AcOutputRelayWelding = NO; break;
-            case AC_GF_MODULE_FAULT: pFaultCode->FaultEvents.bits.RcdSelfTestFail = NO; break;
-            case AC_SHUTTER_FAULT: break;
-            case AC_LOCKER_FAULT: pFaultCode->FaultEvents.bits.AcConnectorLockFail = NO; break;
-            case AC_POWER_DROP: pAlarmCode->AlarmEvents.bits.SystemL1InputDrop = NO; break;
-            case AC_CIRCUIT_SHORT: pAlarmCode->AlarmEvents.bits.CircuitShort = NO; break;
-            case AC_ROTARY_SWITCH_FAULT:  break;
-            case AC_RELAY_DRIVE_FAULT: pFaultCode->FaultEvents.bits.AcOutputRelayDrivingFault = NO; break;
-            }
-        }
-    }
-
-    pAcChargingInfo->IsErrorOccur = isErr;
-}
-
-static void GetAcAlarmCode(void)
-{
-    if (Query_AC_Alarm_Code(Uart5Fd, ADDR_AC_PLUG, &acAlarmCode) == PASS) {
-        CheckAlarmOccur();
-    }
-}
-
-static void GetAcStatus(void)
-{
-    struct ChargingInfoData *pAcChargingInfo = (struct ChargingInfoData *)GetAcChargingInfoData(0);
-
-    if (Query_AC_Status(Uart5Fd, ADDR_AC_PLUG, &acStatus) == PASS) {
-        pSysConfig->AcRatingCurrent = acStatus.MaxCurrent;
-
-        if (pSysConfig->AcMaxChargingCurrent == 0) {
-            pSysConfig->AcMaxChargingCurrent = pSysConfig->AcRatingCurrent;
-        }
-
-        pAcChargingInfo->ConnectorPlugIn = acStatus.CpStatus;
-        //  log_info("CpStatus = %d \n", acStatus.CpStatus);
-        //              printf("CurLimit = %d \n", acStatus.CurLimit);
-        //              printf("PilotVol_P = %d \n", acStatus.PilotVol_P);
-        //              printf("PilotVol_N = %d \n", acStatus.PilotVol_N);
-        //              printf("LockStatus = %d \n", acStatus.LockStatus);
-        //              printf("RelayStatus = %d \n", acStatus.RelayStatus);
-        //              printf("ShutterStatus = %d \n", acStatus.ShutterStatus);
-        //              printf("MeterStatus = %d \n", acStatus.MeterStatus);
-        //              printf("PpStatus = %d \n", acStatus.PpStatus);
-        //              printf("MaxCurrent = %d \n", acStatus.MaxCurrent);
-        //              printf("RotateSwitchStatus = %d \n", acStatus.RelayStatus);
-        //              printf("============================== \n");
-        //
-        //              pAcChargingInfo->SystemStatus = acStatus.CpStatus;
-    }
-//  else
-//      log_info("GetAcStatus return fail. \n");
-}
-
-
-static void ChangeToCsuMode(void)
-{
-    struct ChargingInfoData *pAcChargingInfo = (struct ChargingInfoData *)GetAcChargingInfoData(0);
-
-    pAcChargingInfo->IsModeChagned = Config_CSU_Mode(Uart5Fd, ADDR_AC_PLUG);
-
-//  if (pAcChargingInfo->IsModeChagned == PASS)
-//  {
-//      Config_Reset_MCU(Uart5Fd, ADDR_AC_PLUG);
-//  }
-}
-
-static void GetAcModelName(void)
-{
-    memset(pSysConfig->AcModelName, 0, sizeof(pSysConfig->AcModelName));
-    if (Query_Model_Name(Uart5Fd, ADDR_AC_PLUG, pSysConfig->AcModelName) == PASS) {
-        log_info("ac model name = %s \n", pSysConfig->AcModelName);
-    }
-}
-
-static void GetFwVersion_AC(void)
-{
-    Ver ver = {0};
-    struct ChargingInfoData *pAcChargingInfo = (struct ChargingInfoData *)GetAcChargingInfoData(0);
-
-    if (Query_FW_Ver(Uart5Fd, ADDR_AC_PLUG, &ver) == PASS) {
-        pAcChargingInfo->SelfTest_Comp = YES;
-        strcpy((char *)pAcChargingInfo->version, ver.Version_FW);
-    }
-}
-
-void AcPlugTask(int uartFD)
-{
-    static float _beforeChargingTotalEnergy = 0.0;
-
-    if (pSysConfig->AcConnectorCount <= 0) {
-        return;
-    }
-
-    //share memory mapping
-    pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
-    pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
-    pAlarmCode = (struct AlarmCodeData *)GetShmAlarmCodeData();
-    pInfoCode = (struct InfoCodeData *)GetShmInfoCodeData();
-    pFaultCode = (struct FaultCodeData *)GetShmFaultCodeData();
-    ShmOCPP16Data = (struct OCPP16Data *)GetShmOCPP16Data();
-
-    struct ChargingInfoData *pAcChargingInfo = (struct ChargingInfoData *)GetAcChargingInfoData(0);
-
-    Uart5Fd = uartFD;
-
-    //pAcChargingInfo->SelfTest_Comp = YES;
-    //pAcChargingInfo->IsModeChagned = PASS;
-    //---------------------------------------------
-    if (pAcChargingInfo->SelfTest_Comp == NO) {
-        pAcChargingInfo->IsModeChagned = NO;
-        GetFwVersion_AC();
-        GetAcModelName();
-    } else if (pAcChargingInfo->SelfTest_Comp == YES) {
-        if (pAcChargingInfo->IsModeChagned != PASS) {
-            ChangeToCsuMode();
-            return;
-        }
-        GetAcStatus();
-        GetAcAlarmCode();
-
-        uint8_t _status = S_NONE;
-
-        if (pAcChargingInfo->SystemStatus == S_IDLE && pAcChargingInfo->IsErrorOccur) {
-            _status = S_ALARM;
-        } else if (acStatus.CpStatus == AC_SYS_A || pAcChargingInfo->IsErrorOccur) {
-            if (pAcChargingInfo->SystemStatus == S_CHARGING) {
-                _status = S_TERMINATING;
-            } else if (pAcChargingInfo->SystemStatus >= S_TERMINATING) {
-                if (GetClockTimeoutValue(_ac_charging_comp) >= 10000000 && acStatus.CpStatus == AC_SYS_A) {
-                    _status = S_IDLE;
-                }
-            } else {
-                _status = S_IDLE;
-            }
-        } else if (pAcChargingInfo->SystemStatus >= S_PREPARNING &&
-                   pAcChargingInfo->SystemStatus < S_CHARGING) {
-            if (acStatus.CpStatus == AC_SYS_C && acStatus.RelayStatus == YES) {
-                _status = S_CHARGING;
-            } else if (GetClockTimeoutValue(_ac_preparing) >= 30000000) {
-                _status = S_IDLE;
-            }
-        } else if ((acStatus.CpStatus == AC_SYS_B || pAcChargingInfo->ConnectorPlugIn == AC_SYS_B) &&
-                   pAcChargingInfo->IsAvailable &&
-                   !pAcChargingInfo->IsErrorOccur &&
-                   (pSysInfo->WaitForPlugit == YES ||
-                    pSysConfig->AuthorisationMode == AUTH_MODE_DISABLE)) {
-            if (pAcChargingInfo->RemoteStartFlag == YES) {
-                log_info("** AC Remote \n");
-                pAcChargingInfo->RemoteStartFlag = NO;
-                strcpy((char *)pAcChargingInfo->StartUserId, "");
-                pSysInfo->WaitForPlugit = NO;
-                _status = S_PREPARNING;
-            } else if (pSysInfo->OrderCharging == NO_DEFINE) {
-                log_info("** UserId = %s \n", pSysConfig->UserId);
-                strcpy((char *)pAcChargingInfo->StartUserId, (char *)pSysConfig->UserId);
-                log_info("** CardNumber = %s \n", pAcChargingInfo->StartUserId);
-                strcpy((char *)pSysConfig->UserId, "");
-                pSysInfo->WaitForPlugit = NO;
-                _status = S_PREPARNING;
-            }
-        } else if (pAcChargingInfo->SystemStatus == S_CHARGING) {
-            if (OcppRemoteStop(1)) {
-                _status = S_TERMINATING;
-            }
-        }
-
-        //printf("_status = %d \n", _status);
-
-        if (_status != S_NONE && pAcChargingInfo->SystemStatus != _status) {
-            pAcChargingInfo->SystemStatus = _status;
-        }
-
-        // 設定限制最大充電電流 >= 6 ~ <= 32
-        switch (pAcChargingInfo->SystemStatus) {
-        case S_IDLE:
-        case S_ALARM: {
-            if (isModeChange()) {
-                pAcChargingInfo->PresentChargedEnergy = 0.0;
-                pAcChargingInfo->PresentChargingVoltage = 0;
-                pAcChargingInfo->ChargingFee = 0.0;
-                strcpy((char *)pAcChargingInfo->StartDateTime, "");
-                strcpy((char *)pAcChargingInfo->StopDateTime, "");
-                _beforeChargingTotalEnergy = 0.0;
-            }
-
-            ChangeLedStatus();
-        }
-        break;
-        case S_PREPARNING: {
-            if (isModeChange()) {
-                pSysInfo->SystemPage = _PAGE_PRECHARGE;
-                pSysInfo->CurGunSelectedByAc = DEFAULT_AC_INDEX;
-                if (pSysInfo->OrderCharging != NO_DEFINE) {
-                    pSysInfo->OrderCharging = NO_DEFINE;
-                }
-                GetClockTime(&_ac_preparing, NULL);
-            }
-
-            if (GetChargingEnergy() == PASS) {
-                //pAcChargingInfo->PresentChargedEnergy = acChargingEnergy.Energy / 100;
-                _beforeChargingTotalEnergy = acChargingEnergy.Energy;
-            }
-
-            SetLegacyReq(YES);
-            ChangeLedStatus();
-        }
-        break;
-        case S_CHARGING: {
-            if (isModeChange()) {
-                ftime(&_ac_startChargingTime);
-                OcppStartTransation(1);
-                ChangeStartOrStopDateTime(YES);
-                pSysInfo->CurGunSelectedByAc = DEFAULT_AC_INDEX;
-            }
-
-            if (GetChargingEnergy() == PASS) {
-                if ((acChargingEnergy.Energy - _beforeChargingTotalEnergy) > 0) {
-                    pAcChargingInfo->PresentChargedEnergy += (acChargingEnergy.Energy - _beforeChargingTotalEnergy) / 100;
-                    if (pSysConfig->BillingData.isBilling) {
-                        pAcChargingInfo->ChargingFee += pAcChargingInfo->PresentChargedEnergy * pSysConfig->BillingData.Cur_fee;
-                    }
-                }
-
-                _beforeChargingTotalEnergy = acChargingEnergy.Energy;
-            }
-
-            if (GetChargingCurrent() == PASS) {
-                pAcChargingInfo->PresentChargingPower = (((float)(AC_DEFAULT_VOL * acChargingCurrent.OuputCurrentL1) / 10) / 1000);
-            }
-
-            ftime(&_ac_endChargingTime);
-            pAcChargingInfo->PresentChargedDuration = DiffTimeb(_ac_startChargingTime, _ac_endChargingTime);
-            pAcChargingInfo->PresentChargingVoltage = AC_DEFAULT_VOL;
-            pAcChargingInfo->PresentChargingCurrent = ((float)acChargingCurrent.OuputCurrentL1 / 10);
-
-            // 用以判斷是否有在輸出
-            pAcChargingInfo->IsCharging = acStatus.RelayStatus;
-
-            SetCpDuty(pSysConfig->AcMaxChargingCurrent);
-            ChangeLedStatus();
-        }
-        break;
-        case S_TERMINATING: {
-            if (isModeChange()) {
-                ChangeStartOrStopDateTime(NO);
-                GetClockTime(&_ac_charging_comp, NULL);
-            }
-
-            SetLegacyReq(NO);
-            if (acStatus.RelayStatus == NO) {
-                pAcChargingInfo->SystemStatus = S_COMPLETE;
-            }
-        }
-        break;
-        case S_COMPLETE: {
-            if (isModeChange()) {
-                GetClockTime(&_ac_charging_comp, NULL);
-                ftime(&_ac_endChargingTime);
-                if (strcmp((char *)pAcChargingInfo->StartDateTime, "") != EQUAL) {
-                    // AC 固定為第2把槍
-                    OcppStopTransation(1);
-                }
-
-                ChangeStartOrStopDateTime(NO);
-                pAcChargingInfo->PresentChargedDuration = DiffTimeb(_ac_startChargingTime, _ac_endChargingTime);
-            }
-        }
-        break;
-        }
-    }
-}
+#include <stdio.h>      /*標準輸入輸出定義*/
+#include <stdlib.h>     /*標準函數庫定義*/
+#include <string.h>
+#include <stdint.h>
+#include <time.h>
+
+#include <unistd.h>
+#include <sys/time.h>
+#include <sys/timeb.h>
+
+#include "../Define/define.h"
+#include "../ShareMemory/shmMem.h"
+#include "../Config.h"
+#include "../Log/log.h"
+#include "Module_InternalComm.h"
+#include "internalComm.h"
+
+//------------------------------------------------------------------------------
+static struct SysConfigData *pSysConfig = NULL;
+static struct SysInfoData *pSysInfo = NULL;
+static struct AlarmCodeData *pAlarmCode = NULL;
+static struct InfoCodeData *pInfoCode = NULL;
+static struct FaultCodeData *pFaultCode = NULL;
+static struct OCPP16Data *ShmOCPP16Data = NULL;
+
+static int Uart5Fd = 0;
+
+static struct timespec  _ac_charging_comp;
+static struct timespec  _ac_preparing;
+static struct timeb    _ac_startChargingTime;
+static struct timeb    _ac_endChargingTime;
+
+static Ac_Status acStatus;
+static Ac_Led_Status ledStatus;
+static Ac_Alarm_code acAlarmCode;
+static Ac_Charging_energy acChargingEnergy;
+static Ac_Charging_current acChargingCurrent;
+
+static int _alarm_code[] = {
+    AC_OVP,
+    AC_UVP,
+    AC_OCP,
+    AC_OTP,
+    AC_GMI_FAULT,
+    AC_CP_ERROR,
+    AC_AC_LEAKAGE,
+    AC_DC_LEAKAGE,
+    AC_SYSTEM_SELFTEST_FAULT,
+    AC_HANDSHAKE_TIMEOUT,
+    AC_EMC_STOP,
+    AC_RELAY_WELDING,
+    AC_GF_MODULE_FAULT,
+    AC_SHUTTER_FAULT,
+    AC_LOCKER_FAULT,
+    AC_POWER_DROP,
+    AC_CIRCUIT_SHORT,
+    AC_ROTARY_SWITCH_FAULT,
+    AC_RELAY_DRIVE_FAULT
+};
+
+//------------------------------------------------------------------------------
+static void OcppStopTransation(uint8_t gunIndex)
+{
+    struct ChargingInfoData *pAcChargingInfo = (struct ChargingInfoData *)GetAcChargingInfoData(0);
+
+    if (strcmp((char *)pAcChargingInfo->StartUserId, "") == EQUAL) {
+        strcpy((char *)ShmOCPP16Data->StopTransaction[gunIndex].IdTag,
+               (char *)ShmOCPP16Data->StopTransaction[gunIndex].IdTag);
+    } else {
+        strcpy((char *)ShmOCPP16Data->StopTransaction[gunIndex].IdTag,
+               (char *)pAcChargingInfo->StartUserId);
+    }
+
+    log_info("AC IdTag = %s \n", ShmOCPP16Data->StopTransaction[gunIndex].IdTag);
+    ShmOCPP16Data->CpMsg.bits[gunIndex].StopTransactionReq = YES;
+}
+
+static void SetCpDuty(uint8_t _value)
+{
+    Config_Ac_Duty(Uart5Fd, ADDR_AC_PLUG, _value);
+}
+
+static uint8_t GetChargingCurrent(void)
+{
+    return Query_Charging_Current(Uart5Fd, ADDR_AC_PLUG, &acChargingCurrent);
+}
+
+static uint8_t GetChargingEnergy(void)
+{
+    return Query_Charging_Energy(Uart5Fd, ADDR_AC_PLUG, &acChargingEnergy);
+}
+
+static void ChangeStartOrStopDateTime(uint8_t isStart)
+{
+    char cmdBuf[32];
+    struct timeb csuTime;
+    struct tm *tmCSU;
+    struct ChargingInfoData *pAcChargingInfo = (struct ChargingInfoData *)GetAcChargingInfoData(0);
+
+    ftime(&csuTime);
+    tmCSU = localtime(&csuTime.time);
+
+    sprintf(cmdBuf, "%04d-%02d-%02d %02d:%02d:%02d",
+            tmCSU->tm_year + 1900,
+            tmCSU->tm_mon + 1,
+            tmCSU->tm_mday,
+            tmCSU->tm_hour,
+            tmCSU->tm_min,
+            tmCSU->tm_sec);
+
+    if (isStart) {
+        strcpy((char *)pAcChargingInfo->StartDateTime, cmdBuf);
+    } else {
+        strcpy((char *)pAcChargingInfo->StopDateTime, cmdBuf);
+    }
+}
+
+static void OcppStartTransation(uint8_t gunIndex)
+{
+    struct ChargingInfoData *pAcChargingInfo = (struct ChargingInfoData *)GetAcChargingInfoData(0);
+
+    if (strcmp((char *)pAcChargingInfo->StartUserId, "") == EQUAL) {
+        strcpy((char *)ShmOCPP16Data->StartTransaction[gunIndex].IdTag,
+               (char *)ShmOCPP16Data->StartTransaction[gunIndex].IdTag);
+    } else {
+        strcpy((char *)ShmOCPP16Data->StartTransaction[gunIndex].IdTag,
+               (char *)pAcChargingInfo->StartUserId);
+    }
+
+    log_info("AC IdTag = %s \n", ShmOCPP16Data->StartTransaction[gunIndex].IdTag);
+    ShmOCPP16Data->CpMsg.bits[gunIndex].StartTransactionReq = YES;
+}
+
+static void SetLegacyReq(uint8_t _switch)
+{
+    Config_Legacy_Req(Uart5Fd, ADDR_AC_PLUG, _switch);
+}
+
+static void ChangeLedStatus(void)
+{
+    struct ChargingInfoData *pAcChargingInfo = (struct ChargingInfoData *)GetAcChargingInfoData(0);
+
+    if (pAcChargingInfo->SystemStatus == S_IDLE) {
+        ledStatus.ActionMode = 1;
+    } else if (pAcChargingInfo->SystemStatus == S_PREPARNING) {
+        ledStatus.ActionMode = 3;
+    } else if (pAcChargingInfo->SystemStatus == S_CHARGING) {
+        ledStatus.ActionMode = 4;
+    }
+
+    Config_LED_Status(Uart5Fd, ADDR_AC_PLUG, &ledStatus);
+}
+
+static uint8_t isModeChange(void)
+{
+    uint8_t result = NO;
+    struct ChargingInfoData *pAcChargingInfo = (struct ChargingInfoData *)GetAcChargingInfoData(0);
+
+    if (pAcChargingInfo->SystemStatus != pAcChargingInfo->PreviousSystemStatus) {
+        result = YES;
+        pAcChargingInfo->PreviousSystemStatus = pAcChargingInfo->SystemStatus;
+    }
+
+    return result;
+}
+
+static bool OcppRemoteStop(uint8_t gunIndex)
+{
+    bool result = ShmOCPP16Data->CsMsg.bits[gunIndex].RemoteStopTransactionReq;
+
+    if (ShmOCPP16Data->CsMsg.bits[gunIndex].RemoteStopTransactionReq == YES) {
+        strcpy((char *)ShmOCPP16Data->StopTransaction[gunIndex].StopReason, "Remote");
+        ShmOCPP16Data->CsMsg.bits[gunIndex].RemoteStopTransactionReq = NO;
+    }
+
+    return result;
+}
+
+static void CheckAlarmOccur(void)
+{
+    bool isErr = false;
+    uint8_t count = 0;
+    struct ChargingInfoData *pAcChargingInfo = (struct ChargingInfoData *)GetAcChargingInfoData(0);
+
+    for (count = 0; count < sizeof(_alarm_code) / sizeof(_alarm_code[0]); count++) {
+        if (acAlarmCode.AcAlarmCode & _alarm_code[count]) {
+            isErr = true;
+            switch (_alarm_code[count]) {
+            case AC_OVP: pAlarmCode->AlarmEvents.bits.AcSystemInputOVP = YES; break;
+            case AC_UVP: pAlarmCode->AlarmEvents.bits.AcSystemInputUVP = YES; break;
+            case AC_OCP: pAlarmCode->AlarmEvents.bits.SystemAcOutputOCP = YES; break;
+            case AC_OTP: pAlarmCode->AlarmEvents.bits.SystemAmbientOTP = YES; break;
+            case AC_GMI_FAULT: pAlarmCode->AlarmEvents.bits.AcGroundfaultFail = YES; break;
+            case AC_CP_ERROR: pInfoCode->InfoEvents.bits.PilotFault = YES; break;
+            case AC_AC_LEAKAGE: pAlarmCode->AlarmEvents.bits.RcdTrip = YES; break;
+            case AC_DC_LEAKAGE: pAlarmCode->AlarmEvents.bits.RcdTrip = YES; break;
+            case AC_SYSTEM_SELFTEST_FAULT: pAlarmCode->AlarmEvents.bits.McuSelftestFail = YES; break;
+            case AC_HANDSHAKE_TIMEOUT: break;
+            //case AC_EMC_STOP: pAlarmCode->AlarmEvents.bits.EmergencyStopTrip = YES; break;
+            case AC_RELAY_WELDING: pFaultCode->FaultEvents.bits.AcOutputRelayWelding = YES; break;
+            case AC_GF_MODULE_FAULT: pFaultCode->FaultEvents.bits.RcdSelfTestFail = YES; break;
+            case AC_SHUTTER_FAULT: break;
+            case AC_LOCKER_FAULT: pFaultCode->FaultEvents.bits.AcConnectorLockFail = YES; break;
+            case AC_POWER_DROP: pAlarmCode->AlarmEvents.bits.SystemL1InputDrop = YES; break;
+            case AC_CIRCUIT_SHORT: pAlarmCode->AlarmEvents.bits.CircuitShort = YES; break;
+            case AC_ROTARY_SWITCH_FAULT: break;
+            case AC_RELAY_DRIVE_FAULT: pFaultCode->FaultEvents.bits.AcOutputRelayDrivingFault = YES; break;
+            }
+        } else {
+            switch (_alarm_code[count]) {
+            case AC_OVP: pAlarmCode->AlarmEvents.bits.AcSystemInputOVP = NO; break;
+            case AC_UVP: pAlarmCode->AlarmEvents.bits.AcSystemInputUVP = NO; break;
+            case AC_OCP: pAlarmCode->AlarmEvents.bits.SystemAcOutputOCP = NO; break;
+            case AC_OTP: pAlarmCode->AlarmEvents.bits.SystemAmbientOTP = NO; break;
+            case AC_GMI_FAULT: pAlarmCode->AlarmEvents.bits.AcGroundfaultFail = NO; break;
+            case AC_CP_ERROR: pInfoCode->InfoEvents.bits.PilotFault = NO; break;
+            case AC_AC_LEAKAGE: pAlarmCode->AlarmEvents.bits.RcdTrip = NO; break;
+            case AC_DC_LEAKAGE: pAlarmCode->AlarmEvents.bits.RcdTrip = NO; break;
+            case AC_SYSTEM_SELFTEST_FAULT: pAlarmCode->AlarmEvents.bits.McuSelftestFail = NO; break;
+            case AC_HANDSHAKE_TIMEOUT: break;
+            //case AC_EMC_STOP: pAlarmCode->AlarmEvents.bits.EmergencyStopTrip = NO; break;
+            case AC_RELAY_WELDING: pFaultCode->FaultEvents.bits.AcOutputRelayWelding = NO; break;
+            case AC_GF_MODULE_FAULT: pFaultCode->FaultEvents.bits.RcdSelfTestFail = NO; break;
+            case AC_SHUTTER_FAULT: break;
+            case AC_LOCKER_FAULT: pFaultCode->FaultEvents.bits.AcConnectorLockFail = NO; break;
+            case AC_POWER_DROP: pAlarmCode->AlarmEvents.bits.SystemL1InputDrop = NO; break;
+            case AC_CIRCUIT_SHORT: pAlarmCode->AlarmEvents.bits.CircuitShort = NO; break;
+            case AC_ROTARY_SWITCH_FAULT:  break;
+            case AC_RELAY_DRIVE_FAULT: pFaultCode->FaultEvents.bits.AcOutputRelayDrivingFault = NO; break;
+            }
+        }
+    }
+
+    pAcChargingInfo->IsErrorOccur = isErr;
+}
+
+static void GetAcAlarmCode(void)
+{
+    if (Query_AC_Alarm_Code(Uart5Fd, ADDR_AC_PLUG, &acAlarmCode) == PASS) {
+        CheckAlarmOccur();
+    }
+}
+
+static void GetAcStatus(void)
+{
+    struct ChargingInfoData *pAcChargingInfo = (struct ChargingInfoData *)GetAcChargingInfoData(0);
+
+    if (Query_AC_Status(Uart5Fd, ADDR_AC_PLUG, &acStatus) == PASS) {
+        pSysConfig->AcRatingCurrent = acStatus.MaxCurrent;
+
+        if (pSysConfig->AcMaxChargingCurrent == 0) {
+            pSysConfig->AcMaxChargingCurrent = pSysConfig->AcRatingCurrent;
+        }
+
+        pAcChargingInfo->ConnectorPlugIn = acStatus.CpStatus;
+        //  log_info("CpStatus = %d \n", acStatus.CpStatus);
+        //              printf("CurLimit = %d \n", acStatus.CurLimit);
+        //              printf("PilotVol_P = %d \n", acStatus.PilotVol_P);
+        //              printf("PilotVol_N = %d \n", acStatus.PilotVol_N);
+        //              printf("LockStatus = %d \n", acStatus.LockStatus);
+        //              printf("RelayStatus = %d \n", acStatus.RelayStatus);
+        //              printf("ShutterStatus = %d \n", acStatus.ShutterStatus);
+        //              printf("MeterStatus = %d \n", acStatus.MeterStatus);
+        //              printf("PpStatus = %d \n", acStatus.PpStatus);
+        //              printf("MaxCurrent = %d \n", acStatus.MaxCurrent);
+        //              printf("RotateSwitchStatus = %d \n", acStatus.RelayStatus);
+        //              printf("============================== \n");
+        //
+        //              pAcChargingInfo->SystemStatus = acStatus.CpStatus;
+    }
+//  else
+//      log_info("GetAcStatus return fail. \n");
+}
+
+
+static void ChangeToCsuMode(void)
+{
+    struct ChargingInfoData *pAcChargingInfo = (struct ChargingInfoData *)GetAcChargingInfoData(0);
+
+    pAcChargingInfo->IsModeChagned = Config_CSU_Mode(Uart5Fd, ADDR_AC_PLUG);
+
+//  if (pAcChargingInfo->IsModeChagned == PASS)
+//  {
+//      Config_Reset_MCU(Uart5Fd, ADDR_AC_PLUG);
+//  }
+}
+
+static void GetAcModelName(void)
+{
+    memset(pSysConfig->AcModelName, 0, sizeof(pSysConfig->AcModelName));
+    if (Query_Model_Name(Uart5Fd, ADDR_AC_PLUG, pSysConfig->AcModelName) == PASS) {
+        log_info("ac model name = %s \n", pSysConfig->AcModelName);
+    }
+}
+
+static void GetFwVersion_AC(void)
+{
+    Ver ver = {0};
+    struct ChargingInfoData *pAcChargingInfo = (struct ChargingInfoData *)GetAcChargingInfoData(0);
+
+    if (Query_FW_Ver(Uart5Fd, ADDR_AC_PLUG, &ver) == PASS) {
+        pAcChargingInfo->SelfTest_Comp = YES;
+        strcpy((char *)pAcChargingInfo->version, ver.Version_FW);
+    }
+}
+
+void AcPlugTask(int uartFD)
+{
+    static float _beforeChargingTotalEnergy = 0.0;
+
+    if (pSysConfig->AcConnectorCount <= 0) {
+        return;
+    }
+
+    //share memory mapping
+    pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
+    pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
+    pAlarmCode = (struct AlarmCodeData *)GetShmAlarmCodeData();
+    pInfoCode = (struct InfoCodeData *)GetShmInfoCodeData();
+    pFaultCode = (struct FaultCodeData *)GetShmFaultCodeData();
+    ShmOCPP16Data = (struct OCPP16Data *)GetShmOCPP16Data();
+
+    struct ChargingInfoData *pAcChargingInfo = (struct ChargingInfoData *)GetAcChargingInfoData(0);
+
+    Uart5Fd = uartFD;
+
+    //pAcChargingInfo->SelfTest_Comp = YES;
+    //pAcChargingInfo->IsModeChagned = PASS;
+    //---------------------------------------------
+    if (pAcChargingInfo->SelfTest_Comp == NO) {
+        pAcChargingInfo->IsModeChagned = NO;
+        GetFwVersion_AC();
+        GetAcModelName();
+    } else if (pAcChargingInfo->SelfTest_Comp == YES) {
+        if (pAcChargingInfo->IsModeChagned != PASS) {
+            ChangeToCsuMode();
+            return;
+        }
+        GetAcStatus();
+        GetAcAlarmCode();
+
+        uint8_t _status = S_NONE;
+
+        if (pAcChargingInfo->SystemStatus == S_IDLE && pAcChargingInfo->IsErrorOccur) {
+            _status = S_ALARM;
+        } else if (acStatus.CpStatus == AC_SYS_A || pAcChargingInfo->IsErrorOccur) {
+            if (pAcChargingInfo->SystemStatus == S_CHARGING) {
+                _status = S_TERMINATING;
+            } else if (pAcChargingInfo->SystemStatus >= S_TERMINATING) {
+                if (GetClockTimeoutValue(_ac_charging_comp) >= 10000000 && acStatus.CpStatus == AC_SYS_A) {
+                    _status = S_IDLE;
+                }
+            } else {
+                _status = S_IDLE;
+            }
+        } else if (pAcChargingInfo->SystemStatus >= S_PREPARNING &&
+                   pAcChargingInfo->SystemStatus < S_CHARGING) {
+            if (acStatus.CpStatus == AC_SYS_C && acStatus.RelayStatus == YES) {
+                _status = S_CHARGING;
+            } else if (GetClockTimeoutValue(_ac_preparing) >= 30000000) {
+                _status = S_IDLE;
+            }
+        } else if ((acStatus.CpStatus == AC_SYS_B || pAcChargingInfo->ConnectorPlugIn == AC_SYS_B) &&
+                   pAcChargingInfo->IsAvailable &&
+                   !pAcChargingInfo->IsErrorOccur &&
+                   (pSysInfo->WaitForPlugit == YES ||
+                    pSysConfig->AuthorisationMode == AUTH_MODE_DISABLE)) {
+            if (pAcChargingInfo->RemoteStartFlag == YES) {
+                log_info("** AC Remote \n");
+                pAcChargingInfo->RemoteStartFlag = NO;
+                strcpy((char *)pAcChargingInfo->StartUserId, "");
+                pSysInfo->WaitForPlugit = NO;
+                _status = S_PREPARNING;
+            } else if (pSysInfo->OrderCharging == NO_DEFINE) {
+                log_info("** UserId = %s \n", pSysConfig->UserId);
+                strcpy((char *)pAcChargingInfo->StartUserId, (char *)pSysConfig->UserId);
+                log_info("** CardNumber = %s \n", pAcChargingInfo->StartUserId);
+                strcpy((char *)pSysConfig->UserId, "");
+                pSysInfo->WaitForPlugit = NO;
+                _status = S_PREPARNING;
+            }
+        } else if (pAcChargingInfo->SystemStatus == S_CHARGING) {
+            if (OcppRemoteStop(1)) {
+                _status = S_TERMINATING;
+            }
+        }
+
+        //printf("_status = %d \n", _status);
+
+        if (_status != S_NONE && pAcChargingInfo->SystemStatus != _status) {
+            pAcChargingInfo->SystemStatus = _status;
+        }
+
+        // 設定限制最大充電電流 >= 6 ~ <= 32
+        switch (pAcChargingInfo->SystemStatus) {
+        case S_IDLE:
+        case S_ALARM: {
+            if (isModeChange()) {
+                pAcChargingInfo->PresentChargedEnergy = 0.0;
+                pAcChargingInfo->PresentChargingVoltage = 0;
+                pAcChargingInfo->ChargingFee = 0.0;
+                strcpy((char *)pAcChargingInfo->StartDateTime, "");
+                strcpy((char *)pAcChargingInfo->StopDateTime, "");
+                _beforeChargingTotalEnergy = 0.0;
+            }
+
+            ChangeLedStatus();
+        }
+        break;
+        case S_PREPARNING: {
+            if (isModeChange()) {
+                pSysInfo->SystemPage = _PAGE_PRECHARGE;
+                pSysInfo->CurGunSelectedByAc = DEFAULT_AC_INDEX;
+                if (pSysInfo->OrderCharging != NO_DEFINE) {
+                    pSysInfo->OrderCharging = NO_DEFINE;
+                }
+                GetClockTime(&_ac_preparing, NULL);
+            }
+
+            if (GetChargingEnergy() == PASS) {
+                //pAcChargingInfo->PresentChargedEnergy = acChargingEnergy.Energy / 100;
+                _beforeChargingTotalEnergy = acChargingEnergy.Energy;
+            }
+
+            SetLegacyReq(YES);
+            ChangeLedStatus();
+        }
+        break;
+        case S_CHARGING: {
+            if (isModeChange()) {
+                ftime(&_ac_startChargingTime);
+                OcppStartTransation(1);
+                ChangeStartOrStopDateTime(YES);
+                pSysInfo->CurGunSelectedByAc = DEFAULT_AC_INDEX;
+            }
+
+            if (GetChargingEnergy() == PASS) {
+                if ((acChargingEnergy.Energy - _beforeChargingTotalEnergy) > 0) {
+                    pAcChargingInfo->PresentChargedEnergy += (acChargingEnergy.Energy - _beforeChargingTotalEnergy) / 100;
+                    if (pSysConfig->BillingData.isBilling) {
+                        pAcChargingInfo->ChargingFee += pAcChargingInfo->PresentChargedEnergy * pSysConfig->BillingData.Cur_fee;
+                    }
+                }
+
+                _beforeChargingTotalEnergy = acChargingEnergy.Energy;
+            }
+
+            if (GetChargingCurrent() == PASS) {
+                pAcChargingInfo->PresentChargingPower = (((float)(AC_DEFAULT_VOL * acChargingCurrent.OuputCurrentL1) / 10) / 1000);
+            }
+
+            ftime(&_ac_endChargingTime);
+            pAcChargingInfo->PresentChargedDuration = DiffTimeb(_ac_startChargingTime, _ac_endChargingTime);
+            pAcChargingInfo->PresentChargingVoltage = AC_DEFAULT_VOL;
+            pAcChargingInfo->PresentChargingCurrent = ((float)acChargingCurrent.OuputCurrentL1 / 10);
+
+            // 用以判斷是否有在輸出
+            pAcChargingInfo->IsCharging = acStatus.RelayStatus;
+
+            SetCpDuty(pSysConfig->AcMaxChargingCurrent);
+            ChangeLedStatus();
+        }
+        break;
+        case S_TERMINATING: {
+            if (isModeChange()) {
+                ChangeStartOrStopDateTime(NO);
+                GetClockTime(&_ac_charging_comp, NULL);
+            }
+
+            SetLegacyReq(NO);
+            if (acStatus.RelayStatus == NO) {
+                pAcChargingInfo->SystemStatus = S_COMPLETE;
+            }
+        }
+        break;
+        case S_COMPLETE: {
+            if (isModeChange()) {
+                GetClockTime(&_ac_charging_comp, NULL);
+                ftime(&_ac_endChargingTime);
+                if (strcmp((char *)pAcChargingInfo->StartDateTime, "") != EQUAL) {
+                    // AC 固定為第2把槍
+                    OcppStopTransation(1);
+                }
+
+                ChangeStartOrStopDateTime(NO);
+                pAcChargingInfo->PresentChargedDuration = DiffTimeb(_ac_startChargingTime, _ac_endChargingTime);
+            }
+        }
+        break;
+        }
+    }
+}

+ 284 - 284
EVSE/Projects/DD360Tcci/Apps/ModuleInternalComm/FanBoard.c

@@ -1,284 +1,284 @@
-#include <stdio.h>      /*標準輸入輸出定義*/
-#include <stdlib.h>     /*標準函數庫定義*/
-#include <string.h>
-#include <stdint.h>
-#include <time.h>
-#include <unistd.h>
-
-#include <sys/time.h>
-#include <sys/timeb.h>
-
-#include "../ShareMemory/shmMem.h"
-#include "../Config.h"
-#include "../Log/log.h"
-#include "Module_InternalComm.h"
-#include "internalComm.h"
-
-//------------------------------------------------------------------------------
-static struct SysConfigData *pSysConfig = NULL;
-static struct SysInfoData *pSysInfo = NULL;
-static struct AlarmCodeData *pAlarmCode = NULL;
-static struct FanModuleData *ShmFanModuleData = NULL;
-static struct PsuData *ShmPsuData = NULL;
-
-static int Uart5Fd = 0;
-static struct timespec gFanBoardRunTimer;
-
-static uint16_t _setFanSpeed = 0;
-static uint16_t fanSpeedSmoothValue = 1000;
-
-//------------------------------------------------------------------------------
-static void SetFanModuleSpeed(void)
-{
-    {
-        FanSpeed _fanSpeed = {0};
-
-        _setFanSpeed += fanSpeedSmoothValue;
-
-        if (_setFanSpeed >= ShmFanModuleData->SetFan1Speed) {
-            _setFanSpeed = ShmFanModuleData->SetFan1Speed;
-        }
-
-        //printf("_setFanSpeed = %d ", _setFanSpeed);
-        _fanSpeed.speed[0] = _setFanSpeed;
-
-        _fanSpeed.speed[1] = _setFanSpeed;
-
-        _fanSpeed.speed[2] = _setFanSpeed;
-
-        _fanSpeed.speed[3] = _setFanSpeed;
-
-        if (Config_Fan_Speed(Uart5Fd, ADDR_FAN, &_fanSpeed) == PASS) {
-            //log_info("successfully Fan");
-        }
-    }
-}
-
-// 風扇速度
-static void GetFanSpeed(void)
-{
-    FanSpeed fanSpeed = {0};
-
-    //log_info("Get fan board speed ");
-    if (Query_Fan_Speed(Uart5Fd, ADDR_FAN, &fanSpeed) == PASS) {
-        ShmFanModuleData->PresentFan1Speed = fanSpeed.speed[0];
-        ShmFanModuleData->PresentFan2Speed = fanSpeed.speed[1];
-        ShmFanModuleData->PresentFan3Speed = fanSpeed.speed[2];
-        ShmFanModuleData->PresentFan4Speed = fanSpeed.speed[3];
-//      log_info("SystemFanRotaSpeed_1 = %d ", fanSpeed.speed[0]);
-//      log_info("SystemFanRotaSpeed_2 = %d ", fanSpeed.speed[1]);
-//      log_info("SystemFanRotaSpeed_3 = %d ", fanSpeed.speed[2]);
-//      log_info("SystemFanRotaSpeed_4 = %d ", fanSpeed.speed[3]);
-        // Config_Fan_Speed(Uart5Fd, ADDR_FAN, &fanSpeed[0]);
-        //SysInfoData (SystemFanRotaSpeed)
-    }
-}
-
-static void GetFanSpeedByFunction(void)
-{
-    if (pSysConfig->SwitchDebugFlag == YES) {
-        return;
-    }
-
-    // 風控修改 :
-    // ******************************************************* //
-    //
-    //       當前PSU輸出總 KW       PSU Temp
-    // 30 x -------------------- x ---------- + 14 x (PSU Temp - 45)
-    //       當前樁最大功率 KW         45
-    //
-    // ******************************************************* //
-
-    // 當前樁最大功率 KW : ShmPsuData->SystemAvailablePower
-    uint32_t _maxPower = ShmPsuData->SystemAvailablePower;
-    // 當前PSU輸出總 KW & PSU Temp :
-    uint8_t temp = 0;
-    uint8_t index = 0;
-    uint8_t count = 0;
-    uint8_t gunIndex = 0;
-    uint8_t _temp_diff = 0;
-    float power = 0;
-    double _pw_rate = 0;
-    double _temp_rate = 0;
-    struct ChargingInfoData *pDcChargingInfo = NULL;
-
-    for (index = 0; index < ShmPsuData->GroupCount; index++) {
-        for (count = 0; count < ShmPsuData->PsuGroup[index].GroupPresentPsuQuantity; count++) {
-            if (temp < ShmPsuData->PsuGroup[index].PsuModule[count].ExletTemp) {
-                temp = ShmPsuData->PsuGroup[index].PsuModule[count].ExletTemp;
-            }
-        }
-    }
-
-    for (gunIndex = 0; gunIndex < pSysConfig->TotalConnectorCount; gunIndex++) {
-        pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-
-        power += (pDcChargingInfo->PresentChargingPower * 10);
-    }
-
-    if (_maxPower > 0) {
-        _pw_rate = power / (double)_maxPower;
-    }
-
-    if (temp > 0) {
-        _temp_rate = (double)temp / 50;
-    }
-
-    if (temp > 45) {
-        _temp_diff = temp - 70;
-    }
-
-    ShmFanModuleData->TestFanSpeed = (((50 * _pw_rate * _temp_rate) + (0.5 * _temp_diff)) / 100) * MAX_FAN_SPEED;
-
-    if (ShmFanModuleData->TestFanSpeed > MAX_FAN_SPEED) {
-        ShmFanModuleData->TestFanSpeed = MAX_FAN_SPEED;
-    }
-
-    if (ShmFanModuleData->TestFanSpeed < 0) {
-        ShmFanModuleData->TestFanSpeed = 0;
-    }
-//
-//  printf("power = %f ", power);
-//  printf("_maxPower = %d ", _maxPower);
-//  printf("temp = %d ", temp);
-//
-//  printf("_pw_rate = %f ", _pw_rate);
-//  printf("_temp_rate = %f ", _temp_rate);
-//  printf("_temp_diff = %d ", _temp_diff);
-//  printf("fan rate = %f ", (30 * _pw_rate * _temp_rate + 14 * _temp_diff));
-//  printf("ShmFanModuleData->TestFanSpeed = %d ", ShmFanModuleData->TestFanSpeed);
-}
-
-static void SetRtcData_Fan(void)
-{
-    struct timeb csuTime;
-    struct tm *tmCSU;
-    Rtc rtc = {0};
-
-    ftime(&csuTime);
-    tmCSU = localtime(&csuTime.time);
-    //  log_info("Time : %04d-%02d-%02d %02d:%02d:%02d ", tmCSU->tm_year + 1900,
-    //          tmCSU->tm_mon + 1, tmCSU->tm_mday, tmCSU->tm_hour, tmCSU->tm_min,
-    //          tmCSU->tm_sec);
-
-    rtc.RtcData[0] = '0' + (tmCSU->tm_year + 1900) / 1000 % 10;
-    rtc.RtcData[1] = '0' + (tmCSU->tm_year + 1900) / 100 % 10;
-    rtc.RtcData[2] = '0' + (tmCSU->tm_year + 1900) / 10 % 10;
-    rtc.RtcData[3] = '0' + (tmCSU->tm_year + 1900) / 1 % 10;
-
-    rtc.RtcData[4] = '0' + (tmCSU->tm_mon + 1) / 10 % 10;
-    rtc.RtcData[5] = '0' + (tmCSU->tm_mon + 1) / 1 % 10;
-
-    rtc.RtcData[6] = '0' + (tmCSU->tm_mday) / 10 % 10;
-    rtc.RtcData[7] = '0' + (tmCSU->tm_mday) / 1 % 10;
-
-    rtc.RtcData[8] = '0' + (tmCSU->tm_hour) / 10 % 10;
-    rtc.RtcData[9] = '0' + (tmCSU->tm_hour) / 1 % 10;
-
-    rtc.RtcData[10] = '0' + (tmCSU->tm_min) / 10 % 10;
-    rtc.RtcData[11] = '0' + (tmCSU->tm_min) / 1 % 10;
-
-    rtc.RtcData[12] = '0' + (tmCSU->tm_sec) / 10 % 10;
-    rtc.RtcData[13] = '0' + (tmCSU->tm_sec) / 1 % 10;
-
-    if (Config_Rtc_Data(Uart5Fd, ADDR_FAN, &rtc) == PASS) {
-        //log_info("SetRtc (FB) sucessfully. ");
-    }
-}
-
-static void SetModelName_Fan(void)
-{
-    if (Config_Model_Name(Uart5Fd, ADDR_FAN, pSysConfig->ModelName) == PASS) {
-        return;
-    } else
-        log_info("******** Set Model name FAIL = %s ************", pSysConfig->ModelName);
-}
-
-static void GetFwAndHwVersion_Fan(void)
-{
-    Ver ver = {0};
-
-    if (Query_FW_Ver(Uart5Fd, ADDR_FAN, &ver) == PASS) {
-        // FanModuleData
-        strcpy((char *)ShmFanModuleData->version, ver.Version_FW);
-        // SystemInfo
-        strcpy((char *)pSysInfo->FanModuleFwRev, ver.Version_FW);
-        //log_info("GetFwAndHwVersion_Fan s1 = %s ", ver.Version_FW);
-    }
-
-    if (Query_HW_Ver(Uart5Fd, ADDR_FAN, &ver) == PASS) {
-        // SystemInfo
-        strcpy((char *)pSysInfo->FanModuleHwRev, ver.Version_FW);
-        //log_info("GetFwAndHwVersion_Fan s2 = %s ", ver.Version_HW);
-    }
-}
-
-static void fanBoardPorcess(void)
-{
-    if (ShmFanModuleData->SelfTest_Comp == NO) {
-        return;
-    }
-
-    if (ShmFanModuleData->SelfTest_Comp == YES ||
-            strlen((char *)pSysInfo->FanModuleFwRev) != 0 ||
-            pSysInfo->FanModuleFwRev[0] != '\0') {
-        ShmFanModuleData->SelfTest_Comp = YES;
-
-        if (GetClockTimeoutValue(gFanBoardRunTimer) / 1000 >= 1000) {
-            //GetPsuTempForFanSpeed();
-            GetFanSpeedByFunction();
-            GetFanSpeed();
-            pSysInfo->SystemFanRotaSpeed = _setFanSpeed;
-            GetClockTime(&gFanBoardRunTimer, NULL);
-
-            ShmFanModuleData->SetFan1Speed = ShmFanModuleData->TestFanSpeed;
-            ShmFanModuleData->SetFan2Speed = ShmFanModuleData->TestFanSpeed;
-            ShmFanModuleData->SetFan3Speed = ShmFanModuleData->TestFanSpeed;
-            ShmFanModuleData->SetFan4Speed = ShmFanModuleData->TestFanSpeed;
-
-            //log_info("set fan = %d ", ShmFanModuleData->SetFan1Speed);
-            SetFanModuleSpeed();
-        }
-    }
-}
-
-static void fanBoardSelfTest(void)
-{
-    if (ShmFanModuleData->SelfTest_Comp == YES) {
-        return;
-    }
-
-    GetFwAndHwVersion_Fan();
-    SetModelName_Fan();
-    SetRtcData_Fan();
-    sleep(1);
-    GetClockTime(&gFanBoardRunTimer, NULL);
-}
-
-void FanBoardTask(int uartFD)
-{
-#if defined NO_FAN_BOARD || defined DD360ComBox
-#endif //defined NO_FAN_BOARD || defined DD360ComBox
-
-    pid_t pid = fork();
-
-    if (pid == 0) {
-        int isContinue = 1;
-
-        //share memory mapping
-        pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
-        pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
-        pAlarmCode = (struct AlarmCodeData *)GetShmAlarmCodeData();
-        ShmFanModuleData = (struct FanModuleData *)GetShmFanModuleData();
-        ShmPsuData = (struct PsuData *)GetShmPsuData();
-
-        Uart5Fd = uartFD;
-
-        while (isContinue) {
-            fanBoardSelfTest();
-
-            fanBoardPorcess();
-            usleep(100000);
-        }
-    }
-}
+#include <stdio.h>      /*標準輸入輸出定義*/
+#include <stdlib.h>     /*標準函數庫定義*/
+#include <string.h>
+#include <stdint.h>
+#include <time.h>
+#include <unistd.h>
+
+#include <sys/time.h>
+#include <sys/timeb.h>
+
+#include "../ShareMemory/shmMem.h"
+#include "../Config.h"
+#include "../Log/log.h"
+#include "Module_InternalComm.h"
+#include "internalComm.h"
+
+//------------------------------------------------------------------------------
+static struct SysConfigData *pSysConfig = NULL;
+static struct SysInfoData *pSysInfo = NULL;
+static struct AlarmCodeData *pAlarmCode = NULL;
+static struct FanModuleData *ShmFanModuleData = NULL;
+static struct PsuData *ShmPsuData = NULL;
+
+static int Uart5Fd = 0;
+static struct timespec gFanBoardRunTimer;
+
+static uint16_t _setFanSpeed = 0;
+static uint16_t fanSpeedSmoothValue = 1000;
+
+//------------------------------------------------------------------------------
+static void SetFanModuleSpeed(void)
+{
+    {
+        FanSpeed _fanSpeed = {0};
+
+        _setFanSpeed += fanSpeedSmoothValue;
+
+        if (_setFanSpeed >= ShmFanModuleData->SetFan1Speed) {
+            _setFanSpeed = ShmFanModuleData->SetFan1Speed;
+        }
+
+        //printf("_setFanSpeed = %d ", _setFanSpeed);
+        _fanSpeed.speed[0] = _setFanSpeed;
+
+        _fanSpeed.speed[1] = _setFanSpeed;
+
+        _fanSpeed.speed[2] = _setFanSpeed;
+
+        _fanSpeed.speed[3] = _setFanSpeed;
+
+        if (Config_Fan_Speed(Uart5Fd, ADDR_FAN, &_fanSpeed) == PASS) {
+            //log_info("successfully Fan");
+        }
+    }
+}
+
+// 風扇速度
+static void GetFanSpeed(void)
+{
+    FanSpeed fanSpeed = {0};
+
+    //log_info("Get fan board speed ");
+    if (Query_Fan_Speed(Uart5Fd, ADDR_FAN, &fanSpeed) == PASS) {
+        ShmFanModuleData->PresentFan1Speed = fanSpeed.speed[0];
+        ShmFanModuleData->PresentFan2Speed = fanSpeed.speed[1];
+        ShmFanModuleData->PresentFan3Speed = fanSpeed.speed[2];
+        ShmFanModuleData->PresentFan4Speed = fanSpeed.speed[3];
+//      log_info("SystemFanRotaSpeed_1 = %d ", fanSpeed.speed[0]);
+//      log_info("SystemFanRotaSpeed_2 = %d ", fanSpeed.speed[1]);
+//      log_info("SystemFanRotaSpeed_3 = %d ", fanSpeed.speed[2]);
+//      log_info("SystemFanRotaSpeed_4 = %d ", fanSpeed.speed[3]);
+        // Config_Fan_Speed(Uart5Fd, ADDR_FAN, &fanSpeed[0]);
+        //SysInfoData (SystemFanRotaSpeed)
+    }
+}
+
+static void GetFanSpeedByFunction(void)
+{
+    if (pSysConfig->SwitchDebugFlag == YES) {
+        return;
+    }
+
+    // 風控修改 :
+    // ******************************************************* //
+    //
+    //       當前PSU輸出總 KW       PSU Temp
+    // 30 x -------------------- x ---------- + 14 x (PSU Temp - 45)
+    //       當前樁最大功率 KW         45
+    //
+    // ******************************************************* //
+
+    // 當前樁最大功率 KW : ShmPsuData->SystemAvailablePower
+    uint32_t _maxPower = ShmPsuData->SystemAvailablePower;
+    // 當前PSU輸出總 KW & PSU Temp :
+    uint8_t temp = 0;
+    uint8_t index = 0;
+    uint8_t count = 0;
+    uint8_t gunIndex = 0;
+    uint8_t _temp_diff = 0;
+    float power = 0;
+    double _pw_rate = 0;
+    double _temp_rate = 0;
+    struct ChargingInfoData *pDcChargingInfo = NULL;
+
+    for (index = 0; index < ShmPsuData->GroupCount; index++) {
+        for (count = 0; count < ShmPsuData->PsuGroup[index].GroupPresentPsuQuantity; count++) {
+            if (temp < ShmPsuData->PsuGroup[index].PsuModule[count].ExletTemp) {
+                temp = ShmPsuData->PsuGroup[index].PsuModule[count].ExletTemp;
+            }
+        }
+    }
+
+    for (gunIndex = 0; gunIndex < pSysConfig->TotalConnectorCount; gunIndex++) {
+        pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+
+        power += (pDcChargingInfo->PresentChargingPower * 10);
+    }
+
+    if (_maxPower > 0) {
+        _pw_rate = power / (double)_maxPower;
+    }
+
+    if (temp > 0) {
+        _temp_rate = (double)temp / 50;
+    }
+
+    if (temp > 45) {
+        _temp_diff = temp - 70;
+    }
+
+    ShmFanModuleData->TestFanSpeed = (((50 * _pw_rate * _temp_rate) + (0.5 * _temp_diff)) / 100) * MAX_FAN_SPEED;
+
+    if (ShmFanModuleData->TestFanSpeed > MAX_FAN_SPEED) {
+        ShmFanModuleData->TestFanSpeed = MAX_FAN_SPEED;
+    }
+
+    if (ShmFanModuleData->TestFanSpeed < 0) {
+        ShmFanModuleData->TestFanSpeed = 0;
+    }
+//
+//  printf("power = %f ", power);
+//  printf("_maxPower = %d ", _maxPower);
+//  printf("temp = %d ", temp);
+//
+//  printf("_pw_rate = %f ", _pw_rate);
+//  printf("_temp_rate = %f ", _temp_rate);
+//  printf("_temp_diff = %d ", _temp_diff);
+//  printf("fan rate = %f ", (30 * _pw_rate * _temp_rate + 14 * _temp_diff));
+//  printf("ShmFanModuleData->TestFanSpeed = %d ", ShmFanModuleData->TestFanSpeed);
+}
+
+static void SetRtcData_Fan(void)
+{
+    struct timeb csuTime;
+    struct tm *tmCSU;
+    Rtc rtc = {0};
+
+    ftime(&csuTime);
+    tmCSU = localtime(&csuTime.time);
+    //  log_info("Time : %04d-%02d-%02d %02d:%02d:%02d ", tmCSU->tm_year + 1900,
+    //          tmCSU->tm_mon + 1, tmCSU->tm_mday, tmCSU->tm_hour, tmCSU->tm_min,
+    //          tmCSU->tm_sec);
+
+    rtc.RtcData[0] = '0' + (tmCSU->tm_year + 1900) / 1000 % 10;
+    rtc.RtcData[1] = '0' + (tmCSU->tm_year + 1900) / 100 % 10;
+    rtc.RtcData[2] = '0' + (tmCSU->tm_year + 1900) / 10 % 10;
+    rtc.RtcData[3] = '0' + (tmCSU->tm_year + 1900) / 1 % 10;
+
+    rtc.RtcData[4] = '0' + (tmCSU->tm_mon + 1) / 10 % 10;
+    rtc.RtcData[5] = '0' + (tmCSU->tm_mon + 1) / 1 % 10;
+
+    rtc.RtcData[6] = '0' + (tmCSU->tm_mday) / 10 % 10;
+    rtc.RtcData[7] = '0' + (tmCSU->tm_mday) / 1 % 10;
+
+    rtc.RtcData[8] = '0' + (tmCSU->tm_hour) / 10 % 10;
+    rtc.RtcData[9] = '0' + (tmCSU->tm_hour) / 1 % 10;
+
+    rtc.RtcData[10] = '0' + (tmCSU->tm_min) / 10 % 10;
+    rtc.RtcData[11] = '0' + (tmCSU->tm_min) / 1 % 10;
+
+    rtc.RtcData[12] = '0' + (tmCSU->tm_sec) / 10 % 10;
+    rtc.RtcData[13] = '0' + (tmCSU->tm_sec) / 1 % 10;
+
+    if (Config_Rtc_Data(Uart5Fd, ADDR_FAN, &rtc) == PASS) {
+        //log_info("SetRtc (FB) sucessfully. ");
+    }
+}
+
+static void SetModelName_Fan(void)
+{
+    if (Config_Model_Name(Uart5Fd, ADDR_FAN, pSysConfig->ModelName) == PASS) {
+        return;
+    } else
+        log_info("******** Set Model name FAIL = %s ************", pSysConfig->ModelName);
+}
+
+static void GetFwAndHwVersion_Fan(void)
+{
+    Ver ver = {0};
+
+    if (Query_FW_Ver(Uart5Fd, ADDR_FAN, &ver) == PASS) {
+        // FanModuleData
+        strcpy((char *)ShmFanModuleData->version, ver.Version_FW);
+        // SystemInfo
+        strcpy((char *)pSysInfo->FanModuleFwRev, ver.Version_FW);
+        //log_info("GetFwAndHwVersion_Fan s1 = %s ", ver.Version_FW);
+    }
+
+    if (Query_HW_Ver(Uart5Fd, ADDR_FAN, &ver) == PASS) {
+        // SystemInfo
+        strcpy((char *)pSysInfo->FanModuleHwRev, ver.Version_FW);
+        //log_info("GetFwAndHwVersion_Fan s2 = %s ", ver.Version_HW);
+    }
+}
+
+static void fanBoardPorcess(void)
+{
+    if (ShmFanModuleData->SelfTest_Comp == NO) {
+        return;
+    }
+
+    if (ShmFanModuleData->SelfTest_Comp == YES ||
+            strlen((char *)pSysInfo->FanModuleFwRev) != 0 ||
+            pSysInfo->FanModuleFwRev[0] != '\0') {
+        ShmFanModuleData->SelfTest_Comp = YES;
+
+        if (GetClockTimeoutValue(gFanBoardRunTimer) / 1000 >= 1000) {
+            //GetPsuTempForFanSpeed();
+            GetFanSpeedByFunction();
+            GetFanSpeed();
+            pSysInfo->SystemFanRotaSpeed = _setFanSpeed;
+            GetClockTime(&gFanBoardRunTimer, NULL);
+
+            ShmFanModuleData->SetFan1Speed = ShmFanModuleData->TestFanSpeed;
+            ShmFanModuleData->SetFan2Speed = ShmFanModuleData->TestFanSpeed;
+            ShmFanModuleData->SetFan3Speed = ShmFanModuleData->TestFanSpeed;
+            ShmFanModuleData->SetFan4Speed = ShmFanModuleData->TestFanSpeed;
+
+            //log_info("set fan = %d ", ShmFanModuleData->SetFan1Speed);
+            SetFanModuleSpeed();
+        }
+    }
+}
+
+static void fanBoardSelfTest(void)
+{
+    if (ShmFanModuleData->SelfTest_Comp == YES) {
+        return;
+    }
+
+    GetFwAndHwVersion_Fan();
+    SetModelName_Fan();
+    SetRtcData_Fan();
+    sleep(1);
+    GetClockTime(&gFanBoardRunTimer, NULL);
+}
+
+void FanBoardTask(int uartFD)
+{
+#if defined NO_FAN_BOARD || defined DD360ComBox
+#endif //defined NO_FAN_BOARD || defined DD360ComBox
+
+    pid_t pid = fork();
+
+    if (pid == 0) {
+        int isContinue = 1;
+
+        //share memory mapping
+        pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
+        pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
+        pAlarmCode = (struct AlarmCodeData *)GetShmAlarmCodeData();
+        ShmFanModuleData = (struct FanModuleData *)GetShmFanModuleData();
+        ShmPsuData = (struct PsuData *)GetShmPsuData();
+
+        Uart5Fd = uartFD;
+
+        while (isContinue) {
+            fanBoardSelfTest();
+
+            fanBoardPorcess();
+            usleep(100000);
+        }
+    }
+}

+ 315 - 315
EVSE/Projects/DD360Tcci/Apps/ModuleInternalComm/LEDlight.c

@@ -1,315 +1,315 @@
-#include <stdio.h>      /*標準輸入輸出定義*/
-#include <stdlib.h>     /*標準函數庫定義*/
-#include <string.h>
-#include <stdint.h>
-#include <time.h>
-
-#include <unistd.h>
-#include <sys/time.h>
-#include <sys/timeb.h>
-
-#include "../Define/define.h"
-#include "../ShareMemory/shmMem.h"
-#include "../Config.h"
-#include "../Log/log.h"
-#include "Module_InternalComm.h"
-#include "internalComm.h"
-
-//------------------------------------------------------------------------------
-static struct SysConfigData *pSysConfig = NULL;
-static struct SysInfoData *pSysInfo = NULL;
-static struct WARNING_CODE_INFO *pSysWarning = NULL;
-static struct AlarmCodeData *pAlarmCode = NULL;
-static struct LedModuleData *ShmLedModuleData = NULL;
-
-static int Uart5Fd = 0;
-
-static Led_Color cur_led_color = {COLOR_MIN_LV};
-static Led_Color led_color;
-
-static struct timespec _led_priority_time;
-
-//------------------------------------------------------------------------------
-static bool IsNoneMatchLedColor(void)
-{
-    bool result = false;
-
-    if (cur_led_color.Connect_1_Red != led_color.Connect_1_Red ||
-            cur_led_color.Connect_1_Green != led_color.Connect_1_Green ||
-            cur_led_color.Connect_1_Blue != led_color.Connect_1_Blue ||
-            cur_led_color.Connect_2_Red != led_color.Connect_2_Red ||
-            cur_led_color.Connect_2_Green != led_color.Connect_2_Green ||
-            cur_led_color.Connect_2_Blue != led_color.Connect_2_Blue) {
-        result = true;
-    }
-
-    return result;
-}
-
-//static void SetLedColor(struct ChargingInfoData *chargingData_1, struct ChargingInfoData *chargingData_2)
-static void SetLedColor(void)
-{
-    static uint8_t _checkLedChanged = 3;
-    struct ChargingInfoData *chargingData_1 = NULL;
-    struct ChargingInfoData *chargingData_2 = NULL;
-    uint8_t _colorBuf = COLOR_MAX_LV * LED_INTENSITY_BRIGHTEST;
-
-    if (pSysConfig->TotalConnectorCount == 1) {
-        chargingData_1 = (struct ChargingInfoData *)GetDcChargingInfoData(0);
-        chargingData_2 = (struct ChargingInfoData *)GetDcChargingInfoData(0);
-    } else if (pSysConfig->TotalConnectorCount == 2) {
-        chargingData_1 = (struct ChargingInfoData *)GetDcChargingInfoData(0);
-        chargingData_2 = (struct ChargingInfoData *)GetDcChargingInfoData(1);
-    }
-
-    if (pSysConfig->LedInfo.Intensity == _LED_INTENSITY_DARKEST) {
-        _colorBuf = COLOR_MAX_LV * LED_INTENSITY_DARKEST;
-    } else if (pSysConfig->LedInfo.Intensity == _LED_INTENSITY_MEDIUM) {
-        _colorBuf = COLOR_MAX_LV * LED_INTENSITY_MEDIUM;
-    }
-
-    //printf("chargingData_1->SystemStatus=%d\n",chargingData_1->SystemStatus);
-    //printf("chargingData_2->SystemStatus=%d\n",chargingData_2->SystemStatus);
-    //printf("pSysWarning->Level=%d\n",pSysWarning->Level);
-    if (pSysWarning->Level == 2) {
-        led_color.Connect_1_Green = COLOR_MIN_LV;
-        led_color.Connect_1_Blue = COLOR_MIN_LV;
-        led_color.Connect_1_Red = _colorBuf;
-        led_color.Connect_2_Green = COLOR_MIN_LV;
-        led_color.Connect_2_Blue = COLOR_MIN_LV;
-        led_color.Connect_2_Red = _colorBuf;
-    } else {
-        if (pSysInfo->IsAlternatvieConf) {
-            if ((chargingData_1->SystemStatus == S_BOOTING ||
-                    chargingData_1->SystemStatus == S_IDLE ||
-                    chargingData_1->SystemStatus == S_RESERVATION) &&
-                    (chargingData_2->SystemStatus == S_BOOTING ||
-                     chargingData_2->SystemStatus == S_IDLE ||
-                     chargingData_2->SystemStatus == S_RESERVATION)) {
-#if defined DD360Audi
-                led_color.Connect_1_Green = _colorBuf;
-                led_color.Connect_1_Blue = _colorBuf;
-                led_color.Connect_1_Red = _colorBuf;
-
-                led_color.Connect_2_Green = _colorBuf;
-                led_color.Connect_2_Blue = _colorBuf;
-                led_color.Connect_2_Red = _colorBuf;
-#else
-                led_color.Connect_1_Green = _colorBuf;
-                led_color.Connect_1_Blue = COLOR_MIN_LV;
-                led_color.Connect_1_Red = COLOR_MIN_LV;
-
-                led_color.Connect_2_Green = _colorBuf;
-                led_color.Connect_2_Blue = COLOR_MIN_LV;
-                led_color.Connect_2_Red = COLOR_MIN_LV;
-#endif
-            } else if ((chargingData_1->SystemStatus >= S_AUTHORIZING &&
-                        chargingData_1->SystemStatus <= S_COMPLETE) ||
-                       (chargingData_1->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
-                        chargingData_1->SystemStatus <= S_CCS_PRECHARGE_ST1) ||
-                       (chargingData_2->SystemStatus >= S_AUTHORIZING &&
-                        chargingData_2->SystemStatus <= S_COMPLETE) ||
-                       (chargingData_2->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
-                        chargingData_2->SystemStatus <= S_CCS_PRECHARGE_ST1)) {
-                led_color.Connect_1_Green = COLOR_MIN_LV;
-                led_color.Connect_1_Blue = _colorBuf;
-                led_color.Connect_1_Red = COLOR_MIN_LV;
-                led_color.Connect_2_Green = COLOR_MIN_LV;
-                led_color.Connect_2_Blue = _colorBuf;
-                led_color.Connect_2_Red = COLOR_MIN_LV;
-            } else if ( chargingData_1->SystemStatus == S_UPDATE ||
-                    chargingData_2->SystemStatus == S_UPDATE ) {
-                led_color.Connect_1_Green = COLOR_MIN_LV;
-                led_color.Connect_1_Blue = COLOR_MIN_LV;
-                led_color.Connect_1_Red = _colorBuf;
-                led_color.Connect_2_Green = COLOR_MIN_LV;
-                led_color.Connect_2_Blue = COLOR_MIN_LV;
-                led_color.Connect_2_Red = _colorBuf;
-            }
-        } else {
-            if (chargingData_1->SystemStatus == S_BOOTING ||
-                    chargingData_1->SystemStatus == S_IDLE ||
-                    chargingData_1->SystemStatus == S_RESERVATION ||
-                    chargingData_1->SystemStatus == S_MAINTAIN) {
-
-                if (chargingData_1->IsAvailable == NO) { //For Audi
-                    led_color.Connect_1_Green = COLOR_MIN_LV;
-                    led_color.Connect_1_Blue = COLOR_MIN_LV;
-                    led_color.Connect_1_Red = _colorBuf;
-                } else {
-#if defined DD360Audi
-                    led_color.Connect_1_Green = _colorBuf;
-                    led_color.Connect_1_Blue = _colorBuf;
-                    led_color.Connect_1_Red = _colorBuf;
-#else
-                    led_color.Connect_1_Green = _colorBuf;
-                    led_color.Connect_1_Blue = COLOR_MIN_LV;
-                    led_color.Connect_1_Red = COLOR_MIN_LV;
-#endif
-                }
-            } else if ((chargingData_1->SystemStatus >= S_AUTHORIZING &&
-                        chargingData_1->SystemStatus <= S_COMPLETE) ||
-                       (chargingData_1->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
-                        chargingData_1->SystemStatus <= S_CCS_PRECHARGE_ST1)) {
-                led_color.Connect_1_Green = COLOR_MIN_LV;
-                led_color.Connect_1_Blue = _colorBuf;
-                led_color.Connect_1_Red = COLOR_MIN_LV;
-            } else if ( chargingData_1->SystemStatus == S_UPDATE ) {
-                led_color.Connect_1_Green = COLOR_MIN_LV;
-                led_color.Connect_1_Blue = COLOR_MIN_LV;
-                led_color.Connect_1_Red = _colorBuf;
-            }
-
-            // --------------------------------------------------------------------------
-            if (chargingData_2->SystemStatus == S_BOOTING ||
-                    chargingData_2->SystemStatus == S_IDLE ||
-                    chargingData_2->SystemStatus == S_RESERVATION ||
-                    chargingData_2->SystemStatus == S_MAINTAIN) {
-                if (chargingData_2->IsAvailable == NO) {
-                    led_color.Connect_2_Green = COLOR_MIN_LV;
-                    led_color.Connect_2_Blue = COLOR_MIN_LV;
-                    led_color.Connect_2_Red = _colorBuf;
-                } else {
-#if defined DD360Audi
-                    led_color.Connect_2_Green = _colorBuf;
-                    led_color.Connect_2_Blue = _colorBuf;
-                    led_color.Connect_2_Red = _colorBuf;
-#else
-                    led_color.Connect_2_Green = _colorBuf;
-                    led_color.Connect_2_Blue = COLOR_MIN_LV;
-                    led_color.Connect_2_Red = COLOR_MIN_LV;
-#endif
-                }
-            } else if ((chargingData_2->SystemStatus >= S_AUTHORIZING &&
-                        chargingData_2->SystemStatus <= S_COMPLETE) ||
-                       (chargingData_2->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
-                        chargingData_2->SystemStatus <= S_CCS_PRECHARGE_ST1)) {
-                led_color.Connect_2_Green = COLOR_MIN_LV;
-                led_color.Connect_2_Blue = _colorBuf;
-                led_color.Connect_2_Red = COLOR_MIN_LV;
-            } else if ( chargingData_2->SystemStatus == S_UPDATE ) {
-                led_color.Connect_2_Green = COLOR_MIN_LV;
-                led_color.Connect_2_Blue = COLOR_MIN_LV;
-                led_color.Connect_2_Red = _colorBuf;
-            }
-
-        }
-    }
-
-    if (_checkLedChanged > 0) {
-        if (Config_Led_Color(Uart5Fd, ADDR_LED, &led_color) == PASS) {
-            _checkLedChanged--;
-
-            cur_led_color.Connect_1_Red     = led_color.Connect_1_Red;
-            cur_led_color.Connect_1_Green   = led_color.Connect_1_Green;
-            cur_led_color.Connect_1_Blue    = led_color.Connect_1_Blue;
-            cur_led_color.Connect_2_Red     = led_color.Connect_2_Red;
-            cur_led_color.Connect_2_Green   = led_color.Connect_2_Green;
-            cur_led_color.Connect_2_Blue    = led_color.Connect_2_Blue;
-        }
-    } else if (IsNoneMatchLedColor()) {
-        _checkLedChanged = 3;
-    }
-}
-
-static void GetFwAndHwVersion_Led(void)
-{
-    Ver ver = {0};
-
-    if (Query_FW_Ver(Uart5Fd, ADDR_LED, &ver) == PASS) {
-        // LedModuleData
-        strcpy((char *) ShmLedModuleData->version, ver.Version_FW);
-        // SystemInfo
-        strcpy((char *) pSysInfo->LedModuleFwRev, ver.Version_FW);
-        log_info("GetFwAndHwVersion_Led s1 = %s \n", ver.Version_FW);
-        ShmLedModuleData->SelfTest_Comp = YES;
-    } else {
-        //log_info("GetFwAndHwVersion_Led fail \n");
-    }
-
-//  if (Query_HW_Ver(Uart5Fd, ADDR_LED, &ver) == PASS)
-//  {
-//      // SystemInfo
-//      strcpy((char *) pSysInfo->RelayModuleHwRev, ver.Version_FW);
-//      //log_info("GetFwAndHwVersion_Relay s2 = %s \n", ver.Version_HW);
-//  }
-}
-
-static void LEDBoardProcess(void)
-{
-    //struct ChargingInfoData *pDcChargingInfo0 = NULL;
-    //struct ChargingInfoData *pDcChargingInfo1 = NULL;
-
-    if (ShmLedModuleData->SelfTest_Comp == NO) {
-        return;
-    }
-
-    if (GetClockTimeoutValue(_led_priority_time) / 1000 >= 1000) {
-
-        //if (pSysConfig->TotalConnectorCount == 1) {
-        //    pDcChargingInfo0 = (struct ChargeingInfoData *)GetDcChargingInfoData(0);
-        //    SetLedColor(pDcChargingInfo0, pDcChargingInfo0);
-        //} else if (pSysConfig->TotalConnectorCount == 2) {
-        //    pDcChargingInfo0 = (struct ChargeingInfoData *)GetDcChargingInfoData(0);
-        //    pDcChargingInfo1 = (struct ChargeingInfoData *)GetDcChargingInfoData(1);
-        //    SetLedColor(pDcChargingInfo0, pDcChargingInfo1);
-        //}
-        SetLedColor();
-        GetClockTime(&_led_priority_time, NULL);
-    }
-}
-
-static void LEDBoardSelfTest(void)
-{
-    // 自檢階段處理,自檢階段如果讀不到版號則代表該系統沒有掛燈板
-    if (ShmLedModuleData->SelfTest_Comp == YES) {
-        return;
-    }
-
-#if defined DD360Tcci ||defined DD360Audi
-    GetFwAndHwVersion_Led();
-    sleep(1);
-    GetClockTime(&_led_priority_time, NULL);
-
-    return;
-#endif //defined DD360Tcci || defined DD360Audi
-
-    // 自檢階段
-    if (pSysInfo->SelfTestSeq <= _STEST_PSU_CAP) {
-        GetFwAndHwVersion_Led();
-        sleep(1);
-        GetClockTime(&_led_priority_time, NULL);
-    } else {
-        // 自檢階段沒有問到版號
-        if (pAlarmCode->AlarmEvents.bits.LedboardStestFail == NO) {
-            pAlarmCode->AlarmEvents.bits.LedboardStestFail = YES;
-        }
-    }
-}
-
-void LEDBoardTask(int uartFD)
-{
-#if defined DD360ComBox
-    return;
-#endif //defined DD360ComBox
-
-    pid_t pid = fork();
-
-    if (pid == 0) {
-        int isContinue = 1;
-
-        pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
-        pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
-        pSysWarning = (struct WARNING_CODE_INFO *)GetShmSysWarningInfo();
-
-        pAlarmCode = (struct AlarmCodeData *)GetShmAlarmCodeData();
-        ShmLedModuleData = (struct LedModuleData *)GetShmLedModuleData();
-        Uart5Fd = uartFD;
-
-        while (isContinue) {
-            LEDBoardSelfTest();
-            LEDBoardProcess();
-            usleep(100000);
-        }
-    }
-}
+#include <stdio.h>      /*標準輸入輸出定義*/
+#include <stdlib.h>     /*標準函數庫定義*/
+#include <string.h>
+#include <stdint.h>
+#include <time.h>
+
+#include <unistd.h>
+#include <sys/time.h>
+#include <sys/timeb.h>
+
+#include "../Define/define.h"
+#include "../ShareMemory/shmMem.h"
+#include "../Config.h"
+#include "../Log/log.h"
+#include "Module_InternalComm.h"
+#include "internalComm.h"
+
+//------------------------------------------------------------------------------
+static struct SysConfigData *pSysConfig = NULL;
+static struct SysInfoData *pSysInfo = NULL;
+static struct WARNING_CODE_INFO *pSysWarning = NULL;
+static struct AlarmCodeData *pAlarmCode = NULL;
+static struct LedModuleData *ShmLedModuleData = NULL;
+
+static int Uart5Fd = 0;
+
+static Led_Color cur_led_color = {COLOR_MIN_LV};
+static Led_Color led_color;
+
+static struct timespec _led_priority_time;
+
+//------------------------------------------------------------------------------
+static bool IsNoneMatchLedColor(void)
+{
+    bool result = false;
+
+    if (cur_led_color.Connect_1_Red != led_color.Connect_1_Red ||
+            cur_led_color.Connect_1_Green != led_color.Connect_1_Green ||
+            cur_led_color.Connect_1_Blue != led_color.Connect_1_Blue ||
+            cur_led_color.Connect_2_Red != led_color.Connect_2_Red ||
+            cur_led_color.Connect_2_Green != led_color.Connect_2_Green ||
+            cur_led_color.Connect_2_Blue != led_color.Connect_2_Blue) {
+        result = true;
+    }
+
+    return result;
+}
+
+//static void SetLedColor(struct ChargingInfoData *chargingData_1, struct ChargingInfoData *chargingData_2)
+static void SetLedColor(void)
+{
+    static uint8_t _checkLedChanged = 3;
+    struct ChargingInfoData *chargingData_1 = NULL;
+    struct ChargingInfoData *chargingData_2 = NULL;
+    uint8_t _colorBuf = COLOR_MAX_LV * LED_INTENSITY_BRIGHTEST;
+
+    if (pSysConfig->TotalConnectorCount == 1) {
+        chargingData_1 = (struct ChargingInfoData *)GetDcChargingInfoData(0);
+        chargingData_2 = (struct ChargingInfoData *)GetDcChargingInfoData(0);
+    } else if (pSysConfig->TotalConnectorCount == 2) {
+        chargingData_1 = (struct ChargingInfoData *)GetDcChargingInfoData(0);
+        chargingData_2 = (struct ChargingInfoData *)GetDcChargingInfoData(1);
+    }
+
+    if (pSysConfig->LedInfo.Intensity == _LED_INTENSITY_DARKEST) {
+        _colorBuf = COLOR_MAX_LV * LED_INTENSITY_DARKEST;
+    } else if (pSysConfig->LedInfo.Intensity == _LED_INTENSITY_MEDIUM) {
+        _colorBuf = COLOR_MAX_LV * LED_INTENSITY_MEDIUM;
+    }
+
+    //printf("chargingData_1->SystemStatus=%d\n",chargingData_1->SystemStatus);
+    //printf("chargingData_2->SystemStatus=%d\n",chargingData_2->SystemStatus);
+    //printf("pSysWarning->Level=%d\n",pSysWarning->Level);
+    if (pSysWarning->Level == 2) {
+        led_color.Connect_1_Green = COLOR_MIN_LV;
+        led_color.Connect_1_Blue = COLOR_MIN_LV;
+        led_color.Connect_1_Red = _colorBuf;
+        led_color.Connect_2_Green = COLOR_MIN_LV;
+        led_color.Connect_2_Blue = COLOR_MIN_LV;
+        led_color.Connect_2_Red = _colorBuf;
+    } else {
+        if (pSysInfo->IsAlternatvieConf) {
+            if ((chargingData_1->SystemStatus == S_BOOTING ||
+                    chargingData_1->SystemStatus == S_IDLE ||
+                    chargingData_1->SystemStatus == S_RESERVATION) &&
+                    (chargingData_2->SystemStatus == S_BOOTING ||
+                     chargingData_2->SystemStatus == S_IDLE ||
+                     chargingData_2->SystemStatus == S_RESERVATION)) {
+#if defined DD360Audi
+                led_color.Connect_1_Green = _colorBuf;
+                led_color.Connect_1_Blue = _colorBuf;
+                led_color.Connect_1_Red = _colorBuf;
+
+                led_color.Connect_2_Green = _colorBuf;
+                led_color.Connect_2_Blue = _colorBuf;
+                led_color.Connect_2_Red = _colorBuf;
+#else
+                led_color.Connect_1_Green = _colorBuf;
+                led_color.Connect_1_Blue = COLOR_MIN_LV;
+                led_color.Connect_1_Red = COLOR_MIN_LV;
+
+                led_color.Connect_2_Green = _colorBuf;
+                led_color.Connect_2_Blue = COLOR_MIN_LV;
+                led_color.Connect_2_Red = COLOR_MIN_LV;
+#endif
+            } else if ((chargingData_1->SystemStatus >= S_AUTHORIZING &&
+                        chargingData_1->SystemStatus <= S_COMPLETE) ||
+                       (chargingData_1->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
+                        chargingData_1->SystemStatus <= S_CCS_PRECHARGE_ST1) ||
+                       (chargingData_2->SystemStatus >= S_AUTHORIZING &&
+                        chargingData_2->SystemStatus <= S_COMPLETE) ||
+                       (chargingData_2->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
+                        chargingData_2->SystemStatus <= S_CCS_PRECHARGE_ST1)) {
+                led_color.Connect_1_Green = COLOR_MIN_LV;
+                led_color.Connect_1_Blue = _colorBuf;
+                led_color.Connect_1_Red = COLOR_MIN_LV;
+                led_color.Connect_2_Green = COLOR_MIN_LV;
+                led_color.Connect_2_Blue = _colorBuf;
+                led_color.Connect_2_Red = COLOR_MIN_LV;
+            } else if ( chargingData_1->SystemStatus == S_UPDATE ||
+                    chargingData_2->SystemStatus == S_UPDATE ) {
+                led_color.Connect_1_Green = COLOR_MIN_LV;
+                led_color.Connect_1_Blue = COLOR_MIN_LV;
+                led_color.Connect_1_Red = _colorBuf;
+                led_color.Connect_2_Green = COLOR_MIN_LV;
+                led_color.Connect_2_Blue = COLOR_MIN_LV;
+                led_color.Connect_2_Red = _colorBuf;
+            }
+        } else {
+            if (chargingData_1->SystemStatus == S_BOOTING ||
+                    chargingData_1->SystemStatus == S_IDLE ||
+                    chargingData_1->SystemStatus == S_RESERVATION ||
+                    chargingData_1->SystemStatus == S_MAINTAIN) {
+
+                if (chargingData_1->IsAvailable == NO) { //For Audi
+                    led_color.Connect_1_Green = COLOR_MIN_LV;
+                    led_color.Connect_1_Blue = COLOR_MIN_LV;
+                    led_color.Connect_1_Red = _colorBuf;
+                } else {
+#if defined DD360Audi
+                    led_color.Connect_1_Green = _colorBuf;
+                    led_color.Connect_1_Blue = _colorBuf;
+                    led_color.Connect_1_Red = _colorBuf;
+#else
+                    led_color.Connect_1_Green = _colorBuf;
+                    led_color.Connect_1_Blue = COLOR_MIN_LV;
+                    led_color.Connect_1_Red = COLOR_MIN_LV;
+#endif
+                }
+            } else if ((chargingData_1->SystemStatus >= S_AUTHORIZING &&
+                        chargingData_1->SystemStatus <= S_COMPLETE) ||
+                       (chargingData_1->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
+                        chargingData_1->SystemStatus <= S_CCS_PRECHARGE_ST1)) {
+                led_color.Connect_1_Green = COLOR_MIN_LV;
+                led_color.Connect_1_Blue = _colorBuf;
+                led_color.Connect_1_Red = COLOR_MIN_LV;
+            } else if ( chargingData_1->SystemStatus == S_UPDATE ) {
+                led_color.Connect_1_Green = COLOR_MIN_LV;
+                led_color.Connect_1_Blue = COLOR_MIN_LV;
+                led_color.Connect_1_Red = _colorBuf;
+            }
+
+            // --------------------------------------------------------------------------
+            if (chargingData_2->SystemStatus == S_BOOTING ||
+                    chargingData_2->SystemStatus == S_IDLE ||
+                    chargingData_2->SystemStatus == S_RESERVATION ||
+                    chargingData_2->SystemStatus == S_MAINTAIN) {
+                if (chargingData_2->IsAvailable == NO) {
+                    led_color.Connect_2_Green = COLOR_MIN_LV;
+                    led_color.Connect_2_Blue = COLOR_MIN_LV;
+                    led_color.Connect_2_Red = _colorBuf;
+                } else {
+#if defined DD360Audi
+                    led_color.Connect_2_Green = _colorBuf;
+                    led_color.Connect_2_Blue = _colorBuf;
+                    led_color.Connect_2_Red = _colorBuf;
+#else
+                    led_color.Connect_2_Green = _colorBuf;
+                    led_color.Connect_2_Blue = COLOR_MIN_LV;
+                    led_color.Connect_2_Red = COLOR_MIN_LV;
+#endif
+                }
+            } else if ((chargingData_2->SystemStatus >= S_AUTHORIZING &&
+                        chargingData_2->SystemStatus <= S_COMPLETE) ||
+                       (chargingData_2->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
+                        chargingData_2->SystemStatus <= S_CCS_PRECHARGE_ST1)) {
+                led_color.Connect_2_Green = COLOR_MIN_LV;
+                led_color.Connect_2_Blue = _colorBuf;
+                led_color.Connect_2_Red = COLOR_MIN_LV;
+            } else if ( chargingData_2->SystemStatus == S_UPDATE ) {
+                led_color.Connect_2_Green = COLOR_MIN_LV;
+                led_color.Connect_2_Blue = COLOR_MIN_LV;
+                led_color.Connect_2_Red = _colorBuf;
+            }
+
+        }
+    }
+
+    if (_checkLedChanged > 0) {
+        if (Config_Led_Color(Uart5Fd, ADDR_LED, &led_color) == PASS) {
+            _checkLedChanged--;
+
+            cur_led_color.Connect_1_Red     = led_color.Connect_1_Red;
+            cur_led_color.Connect_1_Green   = led_color.Connect_1_Green;
+            cur_led_color.Connect_1_Blue    = led_color.Connect_1_Blue;
+            cur_led_color.Connect_2_Red     = led_color.Connect_2_Red;
+            cur_led_color.Connect_2_Green   = led_color.Connect_2_Green;
+            cur_led_color.Connect_2_Blue    = led_color.Connect_2_Blue;
+        }
+    } else if (IsNoneMatchLedColor()) {
+        _checkLedChanged = 3;
+    }
+}
+
+static void GetFwAndHwVersion_Led(void)
+{
+    Ver ver = {0};
+
+    if (Query_FW_Ver(Uart5Fd, ADDR_LED, &ver) == PASS) {
+        // LedModuleData
+        strcpy((char *) ShmLedModuleData->version, ver.Version_FW);
+        // SystemInfo
+        strcpy((char *) pSysInfo->LedModuleFwRev, ver.Version_FW);
+        log_info("GetFwAndHwVersion_Led s1 = %s \n", ver.Version_FW);
+        ShmLedModuleData->SelfTest_Comp = YES;
+    } else {
+        //log_info("GetFwAndHwVersion_Led fail \n");
+    }
+
+//  if (Query_HW_Ver(Uart5Fd, ADDR_LED, &ver) == PASS)
+//  {
+//      // SystemInfo
+//      strcpy((char *) pSysInfo->RelayModuleHwRev, ver.Version_FW);
+//      //log_info("GetFwAndHwVersion_Relay s2 = %s \n", ver.Version_HW);
+//  }
+}
+
+static void LEDBoardProcess(void)
+{
+    //struct ChargingInfoData *pDcChargingInfo0 = NULL;
+    //struct ChargingInfoData *pDcChargingInfo1 = NULL;
+
+    if (ShmLedModuleData->SelfTest_Comp == NO) {
+        return;
+    }
+
+    if (GetClockTimeoutValue(_led_priority_time) / 1000 >= 1000) {
+
+        //if (pSysConfig->TotalConnectorCount == 1) {
+        //    pDcChargingInfo0 = (struct ChargeingInfoData *)GetDcChargingInfoData(0);
+        //    SetLedColor(pDcChargingInfo0, pDcChargingInfo0);
+        //} else if (pSysConfig->TotalConnectorCount == 2) {
+        //    pDcChargingInfo0 = (struct ChargeingInfoData *)GetDcChargingInfoData(0);
+        //    pDcChargingInfo1 = (struct ChargeingInfoData *)GetDcChargingInfoData(1);
+        //    SetLedColor(pDcChargingInfo0, pDcChargingInfo1);
+        //}
+        SetLedColor();
+        GetClockTime(&_led_priority_time, NULL);
+    }
+}
+
+static void LEDBoardSelfTest(void)
+{
+    // 自檢階段處理,自檢階段如果讀不到版號則代表該系統沒有掛燈板
+    if (ShmLedModuleData->SelfTest_Comp == YES) {
+        return;
+    }
+
+#if defined DD360Tcci ||defined DD360Audi
+    GetFwAndHwVersion_Led();
+    sleep(1);
+    GetClockTime(&_led_priority_time, NULL);
+
+    return;
+#endif //defined DD360Tcci || defined DD360Audi
+
+    // 自檢階段
+    if (pSysInfo->SelfTestSeq <= _STEST_PSU_CAP) {
+        GetFwAndHwVersion_Led();
+        sleep(1);
+        GetClockTime(&_led_priority_time, NULL);
+    } else {
+        // 自檢階段沒有問到版號
+        if (pAlarmCode->AlarmEvents.bits.LedboardStestFail == NO) {
+            pAlarmCode->AlarmEvents.bits.LedboardStestFail = YES;
+        }
+    }
+}
+
+void LEDBoardTask(int uartFD)
+{
+#if defined DD360ComBox
+    return;
+#endif //defined DD360ComBox
+
+    pid_t pid = fork();
+
+    if (pid == 0) {
+        int isContinue = 1;
+
+        pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
+        pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
+        pSysWarning = (struct WARNING_CODE_INFO *)GetShmSysWarningInfo();
+
+        pAlarmCode = (struct AlarmCodeData *)GetShmAlarmCodeData();
+        ShmLedModuleData = (struct LedModuleData *)GetShmLedModuleData();
+        Uart5Fd = uartFD;
+
+        while (isContinue) {
+            LEDBoardSelfTest();
+            LEDBoardProcess();
+            usleep(100000);
+        }
+    }
+}

+ 126 - 126
EVSE/Projects/DD360Tcci/Apps/ModuleInternalComm/Module_InternalComm.c

@@ -1,126 +1,126 @@
-#include <stdio.h>      /*標準輸入輸出定義*/
-#include <stdlib.h>     /*標準函數庫定義*/
-#include <string.h>
-#include <stdint.h>
-
-#include <termios.h>
-#include <unistd.h>
-#include <fcntl.h>
-
-
-#include <sys/timeb.h>
-#include <sys/ioctl.h>
-#include <sys/time.h>
-
-#include "../Config.h"
-#include "../Log/log.h"
-#include "../ShareMemory/shmMem.h"
-#include "Module_InternalComm.h"
-
-//------------------------------------------------------------------------------
-#define INTERNAL_COM_PORT                       ("/dev/ttyS5")
-
-//------------------------------------------------------------------------------
-extern void RelayBoardTask(int uartFD);
-//extern void LEDBoardTask(int uartFD);
-//extern void FanBoardTask(int uartFD);
-extern void AcPlugTask(int uartFD);
-
-//------------------------------------------------------------------------------
-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;
-    return (StopTime - StartTime);
-}
-
-uint32_t GetTimeoutValue(struct timeval _sour_time)
-{
-    struct timeval _end_time;
-    gettimeofday(&_end_time, NULL);
-
-    return 1000000 * (_end_time.tv_sec - _sour_time.tv_sec) + _end_time.tv_usec - _sour_time.tv_usec;
-}
-void GetClockTime(struct timespec* _now_time, void* null)
-{
-    clock_gettime(CLOCK_MONOTONIC, _now_time);
-}
-unsigned long GetClockTimeoutValue(struct timespec _start_time)
-{
-    struct timespec ts_end;
-    unsigned long ret = 0;
-
-    clock_gettime(CLOCK_MONOTONIC, &ts_end);
-
-    ret = ((unsigned long)(ts_end.tv_sec - _start_time.tv_sec) * 1000000) + ((unsigned long)((ts_end.tv_nsec / 1000) - (_start_time.tv_nsec / 1000)));
-
-    return ret;
-}
-
-static int Init485ComPort(void)
-{
-    int fd;
-    struct termios tios;
-
-    fd = open(INTERNAL_COM_PORT, O_RDWR);
-    if (fd <= 0) {
-        log_error("Module_InternalComm. InitComPort NG");
-        sleep(5);
-        return -1;
-    }
-    ioctl (fd, TCGETS, &tios);
-    tios.c_cflag = B115200 | CS8 | CLOCAL | CREAD;
-    tios.c_lflag = 0;
-    tios.c_iflag = 0;
-    tios.c_oflag = 0;
-    tios.c_cc[VMIN] = 0;
-    tios.c_cc[VTIME] = (uint8_t)0;     // timeout 0.5 second
-    tios.c_lflag = 0;
-    tcflush(fd, TCIFLUSH);
-    ioctl (fd, TCSETS, &tios);
-
-    return fd;
-}
-
-int main(int argc, char *argv[])
-{
-    int fd = 0;
-    int isContinue = 1;
-    struct AlarmCodeData *pAlarmCode = NULL;
-
-    if (CreateAllCsuShareMemory() == FAIL) {
-        log_error("create share memory error");
-        return FAIL;
-    }
-
-    MappingGunChargingInfo("InternalComm Task");
-
-    fd = Init485ComPort();
-    if (fd == FAIL) {
-        pAlarmCode = (struct AlarmCodeData *)GetShmAlarmCodeData();
-        pAlarmCode->AlarmEvents.bits.CsuInitFailed = YES;
-        log_info("ModuleInternalComTask create port error...");
-
-        return FAIL;
-    }
-
-    RelayBoardTask(fd);
-    usleep(100000);
-    //LEDBoardTask(fd);
-    //usleep(100000);
-    //FanBoardTask(fd);
-
-    while (isContinue) {
-        if(AC_QUANTITY > 0)
-        {
-            AcPlugTask(fd);
-        }
-        usleep(100000);
-    }
-
-    return 0;
-}
+#include <stdio.h>      /*標準輸入輸出定義*/
+#include <stdlib.h>     /*標準函數庫定義*/
+#include <string.h>
+#include <stdint.h>
+
+#include <termios.h>
+#include <unistd.h>
+#include <fcntl.h>
+
+
+#include <sys/timeb.h>
+#include <sys/ioctl.h>
+#include <sys/time.h>
+
+#include "../Config.h"
+#include "../Log/log.h"
+#include "../ShareMemory/shmMem.h"
+#include "Module_InternalComm.h"
+
+//------------------------------------------------------------------------------
+#define INTERNAL_COM_PORT                       ("/dev/ttyS5")
+
+//------------------------------------------------------------------------------
+extern void RelayBoardTask(int uartFD);
+//extern void LEDBoardTask(int uartFD);
+//extern void FanBoardTask(int uartFD);
+extern void AcPlugTask(int uartFD);
+
+//------------------------------------------------------------------------------
+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;
+    return (StopTime - StartTime);
+}
+
+uint32_t GetTimeoutValue(struct timeval _sour_time)
+{
+    struct timeval _end_time;
+    gettimeofday(&_end_time, NULL);
+
+    return 1000000 * (_end_time.tv_sec - _sour_time.tv_sec) + _end_time.tv_usec - _sour_time.tv_usec;
+}
+void GetClockTime(struct timespec* _now_time, void* null)
+{
+    clock_gettime(CLOCK_MONOTONIC, _now_time);
+}
+unsigned long GetClockTimeoutValue(struct timespec _start_time)
+{
+    struct timespec ts_end;
+    unsigned long ret = 0;
+
+    clock_gettime(CLOCK_MONOTONIC, &ts_end);
+
+    ret = ((unsigned long)(ts_end.tv_sec - _start_time.tv_sec) * 1000000) + ((unsigned long)((ts_end.tv_nsec / 1000) - (_start_time.tv_nsec / 1000)));
+
+    return ret;
+}
+
+static int Init485ComPort(void)
+{
+    int fd;
+    struct termios tios;
+
+    fd = open(INTERNAL_COM_PORT, O_RDWR);
+    if (fd <= 0) {
+        log_error("Module_InternalComm. InitComPort NG");
+        sleep(5);
+        return -1;
+    }
+    ioctl (fd, TCGETS, &tios);
+    tios.c_cflag = B115200 | CS8 | CLOCAL | CREAD;
+    tios.c_lflag = 0;
+    tios.c_iflag = 0;
+    tios.c_oflag = 0;
+    tios.c_cc[VMIN] = 0;
+    tios.c_cc[VTIME] = (uint8_t)0;     // timeout 0.5 second
+    tios.c_lflag = 0;
+    tcflush(fd, TCIFLUSH);
+    ioctl (fd, TCSETS, &tios);
+
+    return fd;
+}
+
+int main(int argc, char *argv[])
+{
+    int fd = 0;
+    int isContinue = 1;
+    struct AlarmCodeData *pAlarmCode = NULL;
+
+    if (CreateAllCsuShareMemory() == FAIL) {
+        log_error("create share memory error");
+        return FAIL;
+    }
+
+    MappingGunChargingInfo("InternalComm Task");
+
+    fd = Init485ComPort();
+    if (fd == FAIL) {
+        pAlarmCode = (struct AlarmCodeData *)GetShmAlarmCodeData();
+        pAlarmCode->AlarmEvents.bits.CsuInitFailed = YES;
+        log_info("ModuleInternalComTask create port error...");
+
+        return FAIL;
+    }
+
+    RelayBoardTask(fd);
+    usleep(100000);
+    //LEDBoardTask(fd);
+    //usleep(100000);
+    //FanBoardTask(fd);
+
+    while (isContinue) {
+        if(AC_QUANTITY > 0)
+        {
+            AcPlugTask(fd);
+        }
+        usleep(100000);
+    }
+
+    return 0;
+}

+ 111 - 111
EVSE/Projects/DD360Tcci/Apps/ModuleInternalComm/Module_InternalComm.h

@@ -1,111 +1,111 @@
-#ifndef _MODULE_INTERNAL_COMM_H_
-#define _MODULE_INTERNAL_COMM_H_
-
-//------------------------------------------------------------------------------
-#define RELAY_CHECK_TIME                        (5)       // s
-#define OUTPUT_VOL_CHK_TIME                     (200)     // ms
-#define TEN_MINUTES                             (600)     // s
-#define FORCE_STOP_TIME                         (30)
-//#define TEN_MINUTES                             5
-#define ENV_TEMP_MIN                            (45)
-#define ENV_TEMP_MAX                            (50)
-#define DEFAULT_AC_INDEX                        (2)
-#define COLOR_MAX_LV                            (100)
-#define COLOR_MIN_LV                            (0)
-
-#define AC_DEFAULT_VOL                          (220)
-
-#define NDEFAULT_AC_INDEX                       (2)
-
-#define OVP_UVP_CHK_COUNT                       (3)
-
-#define VIN_MAX_VOLTAGE_IEC                     (285) // 大於該值 : OVP
-#define VIN_MAX_REV_VOLTAGE_IEC                 (275) // 小於賦歸 OVP
-#define VIN_MIN_VOLTAGE_IEC                     (160) // 小於該值 : UVP
-#define VIN_MIN_REV_VOLTAGE_IEC                 (170) // 大於賦歸 UVP
-
-#define VIN_MAX_VOLTAGE_UL                      (315) // 大於該值 : OVP // 美規 (W)
-#define VIN_MAX_REV_VOLTAGE_UL                  (305) // 小於賦歸 OVP
-#define VIN_MIN_VOLTAGE_UL                      (210) // 小於該值 : UVP
-#define VIN_MIN_REV_VOLTAGE_UL                  (220) // 大於賦歸 UVP
-
-#define VIN_DROP_VOLTAGE                        (150) // 小於該值 : ac drop
-
-#define VOUT_MAX_VOLTAGE                        (995)
-#define VOUT_MIN_VOLTAGE                        (150)
-#define IOUT_MAX_CURRENT                        (50)
-
-#define MAX_FAN_SPEED                           (14000)
-#define MIN_FAN_SPEED                           (3000)
-#define NORMAL_FAN_SPEED                        (7000)
-
-// GFD Status
-#define GFD_IDLE                                (0)
-#define GFD_CABLECHK                            (1)
-#define GFD_PRECHARGE                           (2)
-#define GFD_CHARGING                            (3)
-
-// LED Intensity (rate)
-#define LED_INTENSITY_DARKEST                   (0.2)
-#define LED_INTENSITY_MEDIUM                    (0.6)
-#define LED_INTENSITY_BRIGHTEST                 (1)
-
-// EE Spec
-#define LED_BRIGHTNESS_LV_HIGH                  (1)
-#define LED_BRIGHTNESS_LV_MID                   (0.5)
-#define LED_BRIGHTNESS_LV_LOW                   (0.2)
-
-// 最小切換 Relay 電壓
-#define SELF_TO_CHANGE_RELAY_STATUS             (600)
-// 透過電壓確認 Relay 是否搭上的依據電壓
-#define CHECK_RELAY_STATUS                      (300)
-#define CHECK_RELAY_STATUS_GAP                  (100)
-// 安全在停止充電程序中斷開 Relay 的電流
-#define SEFETY_SWITCH_RELAY_CUR                 (50)//20 DS60-120 modify
-// 確認 Relay Welding 電壓
-#define RELAY_WELDING_DET                       (300)
-
-#define AC_OVP                                  (1)
-#define AC_UVP                                  (2)
-#define AC_OCP                                  (4)
-#define AC_OTP                                  (8)
-#define AC_GMI_FAULT                            (16)
-#define AC_CP_ERROR                             (32)
-#define AC_AC_LEAKAGE                           (64)
-#define AC_DC_LEAKAGE                           (128)
-#define AC_SYSTEM_SELFTEST_FAULT                (256)
-#define AC_HANDSHAKE_TIMEOUT                    (512)
-#define AC_EMC_STOP                             (1024)
-#define AC_RELAY_WELDING                        (2048)
-#define AC_GF_MODULE_FAULT                      (4096)
-#define AC_SHUTTER_FAULT                        (8192)
-#define AC_LOCKER_FAULT                         (16384)
-#define AC_POWER_DROP                           (32768)
-#define AC_CIRCUIT_SHORT                        (65536)
-#define AC_ROTARY_SWITCH_FAULT                  (131072)
-#define AC_RELAY_DRIVE_FAULT                    (262144)
-
-#define log_info(format, args...) StoreLogMsg("[%s:%d][%s][Info] "format, (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : (strrchr(__FILE__, '\\') ? strrchr(__FILE__, '\\') + 1 : __FILE__)), __LINE__, __FUNCTION__, ##args)
-#define log_warn(format, args...) StoreLogMsg("[%s:%d][%s][Warn] "format, (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : (strrchr(__FILE__, '\\') ? strrchr(__FILE__, '\\') + 1 : __FILE__)), __LINE__, __FUNCTION__, ##args)
-#define log_error(format, args...) StoreLogMsg("[%s:%d][%s][Error] "format, (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : (strrchr(__FILE__, '\\') ? strrchr(__FILE__, '\\') + 1 : __FILE__)), __LINE__, __FUNCTION__, ##args)
-
-//------------------------------------------------------------------------------
-
-typedef struct StGunPNState {
-    uint8_t GunP: 1;
-    uint8_t GunN: 1;
-    uint8_t Reserved: 6;
-} GunPNState;
-
-typedef struct StPreCharginState {
-    uint8_t AcContactor : 1;     //bit 0
-    uint8_t CcsPrecharge : 1;    //bit 1
-    uint8_t Reserved: 6;
-} PreChargingState;
-
-//------------------------------------------------------------------------------
-uint32_t GetTimeoutValue(struct timeval _sour_time);
-unsigned long GetClockTimeoutValue(struct timespec _start_time);
-int DiffTimeb(struct timeb ST, struct timeb ET);
-void GetClockTime(struct timespec* _now_time, void* null);
-#endif /* _MODULE_INTERNAL_COMM_H_ */
+#ifndef _MODULE_INTERNAL_COMM_H_
+#define _MODULE_INTERNAL_COMM_H_
+
+//------------------------------------------------------------------------------
+#define RELAY_CHECK_TIME                        (5)       // s
+#define OUTPUT_VOL_CHK_TIME                     (200)     // ms
+#define TEN_MINUTES                             (600)     // s
+#define FORCE_STOP_TIME                         (30)
+//#define TEN_MINUTES                             5
+#define ENV_TEMP_MIN                            (45)
+#define ENV_TEMP_MAX                            (50)
+#define DEFAULT_AC_INDEX                        (2)
+#define COLOR_MAX_LV                            (100)
+#define COLOR_MIN_LV                            (0)
+
+#define AC_DEFAULT_VOL                          (220)
+
+#define NDEFAULT_AC_INDEX                       (2)
+
+#define OVP_UVP_CHK_COUNT                       (3)
+
+#define VIN_MAX_VOLTAGE_IEC                     (285) // 大於該值 : OVP
+#define VIN_MAX_REV_VOLTAGE_IEC                 (275) // 小於賦歸 OVP
+#define VIN_MIN_VOLTAGE_IEC                     (160) // 小於該值 : UVP
+#define VIN_MIN_REV_VOLTAGE_IEC                 (170) // 大於賦歸 UVP
+
+#define VIN_MAX_VOLTAGE_UL                      (315) // 大於該值 : OVP // 美規 (W)
+#define VIN_MAX_REV_VOLTAGE_UL                  (305) // 小於賦歸 OVP
+#define VIN_MIN_VOLTAGE_UL                      (210) // 小於該值 : UVP
+#define VIN_MIN_REV_VOLTAGE_UL                  (220) // 大於賦歸 UVP
+
+#define VIN_DROP_VOLTAGE                        (150) // 小於該值 : ac drop
+
+#define VOUT_MAX_VOLTAGE                        (995)
+#define VOUT_MIN_VOLTAGE                        (150)
+#define IOUT_MAX_CURRENT                        (50)
+
+#define MAX_FAN_SPEED                           (14000)
+#define MIN_FAN_SPEED                           (3000)
+#define NORMAL_FAN_SPEED                        (7000)
+
+// GFD Status
+#define GFD_IDLE                                (0)
+#define GFD_CABLECHK                            (1)
+#define GFD_PRECHARGE                           (2)
+#define GFD_CHARGING                            (3)
+
+// LED Intensity (rate)
+#define LED_INTENSITY_DARKEST                   (0.2)
+#define LED_INTENSITY_MEDIUM                    (0.6)
+#define LED_INTENSITY_BRIGHTEST                 (1)
+
+// EE Spec
+#define LED_BRIGHTNESS_LV_HIGH                  (1)
+#define LED_BRIGHTNESS_LV_MID                   (0.5)
+#define LED_BRIGHTNESS_LV_LOW                   (0.2)
+
+// 最小切換 Relay 電壓
+#define SELF_TO_CHANGE_RELAY_STATUS             (600)
+// 透過電壓確認 Relay 是否搭上的依據電壓
+#define CHECK_RELAY_STATUS                      (300)
+#define CHECK_RELAY_STATUS_GAP                  (100)
+// 安全在停止充電程序中斷開 Relay 的電流
+#define SEFETY_SWITCH_RELAY_CUR                 (50)//20 DS60-120 modify
+// 確認 Relay Welding 電壓
+#define RELAY_WELDING_DET                       (300)
+
+#define AC_OVP                                  (1)
+#define AC_UVP                                  (2)
+#define AC_OCP                                  (4)
+#define AC_OTP                                  (8)
+#define AC_GMI_FAULT                            (16)
+#define AC_CP_ERROR                             (32)
+#define AC_AC_LEAKAGE                           (64)
+#define AC_DC_LEAKAGE                           (128)
+#define AC_SYSTEM_SELFTEST_FAULT                (256)
+#define AC_HANDSHAKE_TIMEOUT                    (512)
+#define AC_EMC_STOP                             (1024)
+#define AC_RELAY_WELDING                        (2048)
+#define AC_GF_MODULE_FAULT                      (4096)
+#define AC_SHUTTER_FAULT                        (8192)
+#define AC_LOCKER_FAULT                         (16384)
+#define AC_POWER_DROP                           (32768)
+#define AC_CIRCUIT_SHORT                        (65536)
+#define AC_ROTARY_SWITCH_FAULT                  (131072)
+#define AC_RELAY_DRIVE_FAULT                    (262144)
+
+#define log_info(format, args...) StoreLogMsg("[%s:%d][%s][Info] "format, (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : (strrchr(__FILE__, '\\') ? strrchr(__FILE__, '\\') + 1 : __FILE__)), __LINE__, __FUNCTION__, ##args)
+#define log_warn(format, args...) StoreLogMsg("[%s:%d][%s][Warn] "format, (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : (strrchr(__FILE__, '\\') ? strrchr(__FILE__, '\\') + 1 : __FILE__)), __LINE__, __FUNCTION__, ##args)
+#define log_error(format, args...) StoreLogMsg("[%s:%d][%s][Error] "format, (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : (strrchr(__FILE__, '\\') ? strrchr(__FILE__, '\\') + 1 : __FILE__)), __LINE__, __FUNCTION__, ##args)
+
+//------------------------------------------------------------------------------
+
+typedef struct StGunPNState {
+    uint8_t GunP: 1;
+    uint8_t GunN: 1;
+    uint8_t Reserved: 6;
+} GunPNState;
+
+typedef struct StPreCharginState {
+    uint8_t AcContactor : 1;     //bit 0
+    uint8_t CcsPrecharge : 1;    //bit 1
+    uint8_t Reserved: 6;
+} PreChargingState;
+
+//------------------------------------------------------------------------------
+uint32_t GetTimeoutValue(struct timeval _sour_time);
+unsigned long GetClockTimeoutValue(struct timespec _start_time);
+int DiffTimeb(struct timeb ST, struct timeb ET);
+void GetClockTime(struct timespec* _now_time, void* null);
+#endif /* _MODULE_INTERNAL_COMM_H_ */

+ 2488 - 2488
EVSE/Projects/DD360Tcci/Apps/ModuleInternalComm/Module_InternalCommOrg.c

@@ -1,2488 +1,2488 @@
-#include <sys/time.h>
-#include <sys/timeb.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <sys/ioctl.h>
-#include <sys/socket.h>
-#include <sys/ipc.h>
-#include <sys/shm.h>
-#include <sys/mman.h>
-#include <linux/wireless.h>
-#include <arpa/inet.h>
-#include <netinet/in.h>
-
-#include <unistd.h>
-#include <stdarg.h>
-#include <stdio.h>      /*標準輸入輸出定義*/
-#include <stdlib.h>     /*標準函數庫定義*/
-#include <unistd.h>     /*Unix 標準函數定義*/
-#include <fcntl.h>      /*檔控制定義*/
-#include <termios.h>    /*PPSIX 終端控制定義*/
-#include <errno.h>      /*錯誤號定義*/
-#include <errno.h>
-#include <string.h>
-#include <time.h>
-#include <ctype.h>
-#include <ifaddrs.h>
-#include <math.h>
-#include <stdbool.h>
-
-#include "../Define/define.h"
-#include "Module_InternalComm.h"
-#include "internalComm.h"
-#include "../Config.h"
-
-//------------------------------------------------------------------------------
-struct SysConfigAndInfo         *ShmSysConfigAndInfo;
-struct StatusCodeData           *ShmStatusCodeData;
-struct FanModuleData            *ShmFanModuleData;
-struct RelayModuleData          *ShmRelayModuleData;
-struct LedModuleData            *ShmLedModuleData;
-struct PsuData                  *ShmPsuData;
-struct OCPP16Data               *ShmOCPP16Data;
-DcCommonInfo                    *ShmDcCommonData;
-
-uint8_t gunCount;
-uint8_t acgunCount;
-// 槍資訊
-struct ChargingInfoData *_chargingData[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
-struct ChargingInfoData *ac_chargingInfo[AC_QUANTITY];
-
-bool _isOutputNoneMatch[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
-struct timeval _checkOutputNoneMatchTimer[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
-
-bool _isRelayWelding[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
-struct timeval _checkRelayWeldingTimer[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
-
-bool _isOvpChkTimeFlag[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY]; //DS60-120 add
-struct timeval _checkOutputVolProtectTimer[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY]; //DS60-120 add
-
-// SMR1 *2 + SMR2 * 2 + Parallel * 2
-struct timeval _relayStateChkTimer[6]; //DS60-120 add
-
-uint8_t _threePhaseOvp[3] = {0, 0, 0}; //DS60-120 add
-uint8_t _threePhaseUvp[3] = {0, 0, 0}; //DS60-120 add
-
-bool FindChargingInfoData(uint8_t target, struct ChargingInfoData **chargingData);
-
-int Uart5Fd;
-char *relayRs485PortName = "/dev/ttyS5";
-unsigned short fanSpeedSmoothValue = 500;
-
-bool isStopChargingCount = false;
-struct timeval _close_ac_contactor;
-
-struct timeval _priority_time;
-struct timeval _led_priority_time;
-
-struct timeval  _ac_charging_comp;
-struct timeval  _ac_preparing;
-struct timeb    _ac_startChargingTime;
-struct timeb    _ac_endChargingTime;
-
-unsigned short _setFanSpeed = 0;
-float _beforeChargingTotalEnergy = 0.0;
-uint8_t _checkLedChanged = 3;
-
-Ver ver;
-PresentInputVoltage inputVoltage;
-PresentOutputVoltage outputVoltage;
-FanSpeed fanSpeed;
-Temperature temperature;
-AuxPower auxPower;
-Gfd gfd_adc;
-Gfd_config gfd_config;
-Gpio_in gpio_in;
-Gpio_out gpio_out;
-Relay outputRelay;
-Relay regRelay;
-Rtc rtc;
-Led_Color cur_led_color;
-Led_Color led_color;
-
-Ac_Status acStatus;
-Ac_Led_Status ledStatus;
-Ac_Alarm_code acAlarmCode;
-Ac_Charging_energy acChargingEnergy;
-Ac_Charging_current acChargingCurrent;
-
-int _alarm_code[] = {
-    AC_OVP,
-    AC_UVP,
-    AC_OCP,
-    AC_OTP,
-    AC_GMI_FAULT,
-    AC_CP_ERROR,
-    AC_AC_LEAKAGE,
-    AC_DC_LEAKAGE,
-    AC_SYSTEM_SELFTEST_FAULT,
-    AC_HANDSHAKE_TIMEOUT,
-    AC_EMC_STOP,
-    AC_RELAY_WELDING,
-    AC_GF_MODULE_FAULT,
-    AC_SHUTTER_FAULT,
-    AC_LOCKER_FAULT,
-    AC_POWER_DROP,
-    AC_CIRCUIT_SHORT,
-    AC_ROTARY_SWITCH_FAULT,
-    AC_RELAY_DRIVE_FAULT
-};
-
-uint8_t getCommTargetID(uint8_t index)
-{
-    uint8_t targetID = 0;
-
-    if (gunCount == 1) {
-        if (strncmp((char *)&ShmSysConfigAndInfo->SysConfig.ModelName[7], "0", 1) != 0) {
-            targetID = 0x01;
-        } else if (strncmp((char *)&ShmSysConfigAndInfo->SysConfig.ModelName[9], "0", 1) != 0) {
-            targetID = 0x02;
-        }
-    } else {
-        targetID = _chargingData[index]->Evboard_id;
-    }
-
-    return targetID;
-}
-
-unsigned long GetTimeoutValue(struct timeval _sour_time)
-{
-    struct timeval _end_time;
-    gettimeofday(&_end_time, NULL);
-
-    return 1000000 * (_end_time.tv_sec - _sour_time.tv_sec) + _end_time.tv_usec - _sour_time.tv_usec;
-}
-
-int StoreLogMsg(const char *fmt, ...)
-{
-    char Buf[4096 + 256];
-    char buffer[4096];
-    va_list args;
-    struct timeb  SeqEndTime;
-    struct tm *tm;
-
-    va_start(args, fmt);
-    int rc = vsnprintf(buffer, sizeof(buffer), fmt, args);
-    va_end(args);
-
-    memset(Buf, 0, sizeof(Buf));
-    ftime(&SeqEndTime);
-    SeqEndTime.time = time(NULL);
-    tm = localtime(&SeqEndTime.time);
-
-    if (ShmSysConfigAndInfo->SysConfig.SwitchDebugFlag == YES) {
-        sprintf(Buf, "%02d:%02d:%02d:%03d - %s",
-                tm->tm_hour, tm->tm_min, tm->tm_sec, SeqEndTime.millitm, buffer);
-        printf("%s \n", Buf);
-    } else {
-        sprintf(Buf, "echo \"%04d-%02d-%02d %02d:%02d:%02d:%03d - %s\" >> /Storage/SystemLog/[%04d.%02d]SystemLog",
-                tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec, SeqEndTime.millitm,
-                buffer,
-                tm->tm_year + 1900, tm->tm_mon + 1);
-        system(Buf);
-    }
-
-    return rc;
-}
-
-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;
-    return (StopTime - StartTime);
-}
-
-unsigned short MaxValue(unsigned short value1, unsigned short value2)
-{
-    return value1 >= value2 ? value1 : value2;
-}
-
-//==========================================
-// Communication Function
-//==========================================
-void GetFwAndHwVersion_Fan()
-{
-    if (Query_FW_Ver(Uart5Fd, ADDR_FAN, &ver) == PASS) {
-        // FanModuleData
-        strcpy((char *) ShmFanModuleData->version, ver.Version_FW);
-        // SystemInfo
-        strcpy((char *) ShmSysConfigAndInfo->SysInfo.FanModuleFwRev, ver.Version_FW);
-        //log_info("GetFwAndHwVersion_Fan s1 = %s \n", ver.Version_FW);
-    }
-
-    if (Query_HW_Ver(Uart5Fd, ADDR_FAN, &ver) == PASS) {
-        // SystemInfo
-        strcpy((char *) ShmSysConfigAndInfo->SysInfo.FanModuleHwRev, ver.Version_FW);
-        //log_info("GetFwAndHwVersion_Fan s2 = %s \n", ver.Version_HW);
-    }
-}
-
-void GetFwAndHwVersion_Relay()
-{
-    if (Query_FW_Ver(Uart5Fd, ADDR_RELAY, &ver) == PASS) {
-        // RelayModuleData
-        strcpy((char *) ShmRelayModuleData->version, ver.Version_FW);
-        // SystemInfo
-        strcpy((char *) ShmSysConfigAndInfo->SysInfo.RelayModuleFwRev, ver.Version_FW);
-        //log_info("GetFwAndHwVersion_Relay s1 = %s \n", ver.Version_FW);
-    }
-
-    if (Query_HW_Ver(Uart5Fd, ADDR_RELAY, &ver) == PASS) {
-        // SystemInfo
-        strcpy((char *) ShmSysConfigAndInfo->SysInfo.RelayModuleHwRev, ver.Version_FW);
-        //log_info("GetFwAndHwVersion_Relay s2 = %s \n", ver.Version_HW);
-    }
-}
-
-void GetFwAndHwVersion_Led()
-{
-    if (Query_FW_Ver(Uart5Fd, ADDR_LED, &ver) == PASS) {
-        // LedModuleData
-        strcpy((char *) ShmLedModuleData->version, ver.Version_FW);
-        // SystemInfo
-        strcpy((char *) ShmSysConfigAndInfo->SysInfo.LedModuleFwRev, ver.Version_FW);
-        //log_info("GetFwAndHwVersion_Led s1 = %s \n", ver.Version_FW);
-        ShmLedModuleData->SelfTest_Comp = YES;
-    } else {
-        //log_info("GetFwAndHwVersion_Led fail \n");
-    }
-
-//  if (Query_HW_Ver(Uart5Fd, ADDR_LED, &ver) == PASS)
-//  {
-//      // SystemInfo
-//      strcpy((char *) ShmSysConfigAndInfo->SysInfo.RelayModuleHwRev, ver.Version_FW);
-//      //log_info("GetFwAndHwVersion_Relay s2 = %s \n", ver.Version_HW);
-//  }
-}
-
-void GetFwVersion_AC()
-{
-    if (Query_FW_Ver(Uart5Fd, ADDR_AC_PLUG, &ver) == PASS) {
-        ac_chargingInfo[0]->SelfTest_Comp = YES;
-        strcpy((char *) ac_chargingInfo[0]->version, ver.Version_FW);
-    }
-}
-
-void GetAcModelName()
-{
-    memset(ShmSysConfigAndInfo->SysConfig.AcModelName, 0x00, sizeof(ShmSysConfigAndInfo->SysConfig.AcModelName));
-    if (Query_Model_Name(Uart5Fd, ADDR_AC_PLUG, ShmSysConfigAndInfo->SysConfig.AcModelName) == PASS) {
-        log_info("ac model name = %s \n", ShmSysConfigAndInfo->SysConfig.AcModelName);
-    }
-}
-
-void SetRtcData_Relay()
-{
-    struct timeb csuTime;
-    struct tm *tmCSU;
-
-    ftime(&csuTime);
-    tmCSU = localtime(&csuTime.time);
-    //  log_info("Time : %04d-%02d-%02d %02d:%02d:%02d \n", tmCSU->tm_year + 1900,
-    //          tmCSU->tm_mon + 1, tmCSU->tm_mday, tmCSU->tm_hour, tmCSU->tm_min,
-    //          tmCSU->tm_sec);
-
-    rtc.RtcData[0] = '0' + (tmCSU->tm_year + 1900) / 1000 % 10;
-    rtc.RtcData[1] = '0' + (tmCSU->tm_year + 1900) / 100 % 10;
-    rtc.RtcData[2] = '0' + (tmCSU->tm_year + 1900) / 10 % 10;
-    rtc.RtcData[3] = '0' + (tmCSU->tm_year + 1900) / 1 % 10;
-
-    rtc.RtcData[4] = '0' + (tmCSU->tm_mon + 1) / 10 % 10;
-    rtc.RtcData[5] = '0' + (tmCSU->tm_mon + 1) / 1 % 10;
-
-    rtc.RtcData[6] = '0' + (tmCSU->tm_mday) / 10 % 10;
-    rtc.RtcData[7] = '0' + (tmCSU->tm_mday) / 1 % 10;
-
-    rtc.RtcData[8] = '0' + (tmCSU->tm_hour) / 10 % 10;
-    rtc.RtcData[9] = '0' + (tmCSU->tm_hour) / 1 % 10;
-
-    rtc.RtcData[10] = '0' + (tmCSU->tm_min) / 10 % 10;
-    rtc.RtcData[11] = '0' + (tmCSU->tm_min) / 1 % 10;
-
-    rtc.RtcData[12] = '0' + (tmCSU->tm_sec) / 10 % 10;
-    rtc.RtcData[13] = '0' + (tmCSU->tm_sec) / 1 % 10;
-
-    if (Config_Rtc_Data(Uart5Fd, ADDR_RELAY, &rtc) == PASS) {
-        //log_info("SetRtc (RB) sucessfully. \n");
-    }
-}
-
-void SetModelName_Relay()
-{
-    if (Config_Model_Name(Uart5Fd, ADDR_RELAY, ShmSysConfigAndInfo->SysConfig.ModelName) == PASS) {
-        //log_info("Set Model name (RB) PASS = %s \n", ShmSysConfigAndInfo->SysConfig.ModelName);
-    }
-}
-
-void SetRtcData_Fan()
-{
-    struct timeb csuTime;
-    struct tm *tmCSU;
-
-    ftime(&csuTime);
-    tmCSU = localtime(&csuTime.time);
-    //  log_info("Time : %04d-%02d-%02d %02d:%02d:%02d \n", tmCSU->tm_year + 1900,
-    //          tmCSU->tm_mon + 1, tmCSU->tm_mday, tmCSU->tm_hour, tmCSU->tm_min,
-    //          tmCSU->tm_sec);
-
-    rtc.RtcData[0] = '0' + (tmCSU->tm_year + 1900) / 1000 % 10;
-    rtc.RtcData[1] = '0' + (tmCSU->tm_year + 1900) / 100 % 10;
-    rtc.RtcData[2] = '0' + (tmCSU->tm_year + 1900) / 10 % 10;
-    rtc.RtcData[3] = '0' + (tmCSU->tm_year + 1900) / 1 % 10;
-
-    rtc.RtcData[4] = '0' + (tmCSU->tm_mon + 1) / 10 % 10;
-    rtc.RtcData[5] = '0' + (tmCSU->tm_mon + 1) / 1 % 10;
-
-    rtc.RtcData[6] = '0' + (tmCSU->tm_mday) / 10 % 10;
-    rtc.RtcData[7] = '0' + (tmCSU->tm_mday) / 1 % 10;
-
-    rtc.RtcData[8] = '0' + (tmCSU->tm_hour) / 10 % 10;
-    rtc.RtcData[9] = '0' + (tmCSU->tm_hour) / 1 % 10;
-
-    rtc.RtcData[10] = '0' + (tmCSU->tm_min) / 10 % 10;
-    rtc.RtcData[11] = '0' + (tmCSU->tm_min) / 1 % 10;
-
-    rtc.RtcData[12] = '0' + (tmCSU->tm_sec) / 10 % 10;
-    rtc.RtcData[13] = '0' + (tmCSU->tm_sec) / 1 % 10;
-
-    if (Config_Rtc_Data(Uart5Fd, ADDR_FAN, &rtc) == PASS) {
-        //log_info("SetRtc (FB) sucessfully. \n");
-    }
-}
-
-void SetModelName_Fan()
-{
-    if (Config_Model_Name(Uart5Fd, ADDR_FAN, ShmSysConfigAndInfo->SysConfig.ModelName) == PASS) {
-        log_info("Set Model name PASS = %s \n", ShmSysConfigAndInfo->SysConfig.ModelName);
-    }
-}
-
-// AC 三相輸入電壓
-void GetPresentInputVol(void)
-{
-    if (Query_Present_InputVoltage(Uart5Fd, ADDR_RELAY, &inputVoltage) == PASS) {
-        // resolution : 0.1
-        ShmSysConfigAndInfo->SysInfo.InputVoltageR = ShmRelayModuleData->InputL1Volt = inputVoltage.L1N_L12;
-        ShmSysConfigAndInfo->SysInfo.InputVoltageS = ShmRelayModuleData->InputL2Volt = inputVoltage.L2N_L23;
-        ShmSysConfigAndInfo->SysInfo.InputVoltageT = ShmRelayModuleData->InputL3Volt = inputVoltage.L3N_L31;
-
-        //********************************************************************************************************//
-        // Vin (UVP)
-        if (ShmSysConfigAndInfo->SysInfo.ChargerType == _CHARGER_TYPE_IEC) {
-            if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputUVP == NO) {
-                if (inputVoltage.L1N_L12 < VIN_MIN_VOLTAGE_IEC) {
-                    log_info("In Uvp L1N_L12 = %f \n", inputVoltage.L1N_L12);
-                    if (_threePhaseUvp[0] >= OVP_UVP_CHK_COUNT) {
-                        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputUVP = YES;
-                    } else {
-                        _threePhaseUvp[0] += 1;
-                    }
-                }
-            } else {
-                if (inputVoltage.L1N_L12 > VIN_MIN_REV_VOLTAGE_IEC) {
-                    ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputUVP = NO;
-                    _threePhaseUvp[0] = 0;
-                }
-            }
-
-            if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL2InputUVP == NO) {
-                if (inputVoltage.L2N_L23 < VIN_MIN_VOLTAGE_IEC) {
-                    log_info("In Uvp L2N_L23 = %f \n", inputVoltage.L2N_L23);
-                    if (_threePhaseUvp[1] >= OVP_UVP_CHK_COUNT) {
-                        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL2InputUVP = YES;
-                    } else {
-                        _threePhaseUvp[1] += 1;
-                    }
-                }
-            } else {
-                if (inputVoltage.L2N_L23 > VIN_MIN_REV_VOLTAGE_IEC) {
-                    ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL2InputUVP = NO;
-                    _threePhaseUvp[1] = 0;
-                }
-            }
-
-            if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL3InputUVP == NO) {
-                if (inputVoltage.L3N_L31 < VIN_MIN_VOLTAGE_IEC) {
-                    log_info("In Uvp L3N_L31 = %f \n", inputVoltage.L3N_L31);
-                    if (_threePhaseUvp[2] >= OVP_UVP_CHK_COUNT) {
-                        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL3InputUVP = YES;
-                    } else {
-                        _threePhaseUvp[2] += 1;
-                    }
-                }
-            } else {
-                if (inputVoltage.L3N_L31 > VIN_MIN_REV_VOLTAGE_IEC) {
-                    ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL3InputUVP = NO;
-                    _threePhaseUvp[2] = 0;
-                }
-            }
-        } else if (ShmSysConfigAndInfo->SysInfo.ChargerType == _CHARGER_TYPE_UL) {
-            if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputUVP == NO) {
-                if (inputVoltage.L1N_L12 < VIN_MIN_VOLTAGE_UL) {
-                    log_info("In Uvp L1N_L12 = %f \n", inputVoltage.L1N_L12);
-                    if (_threePhaseUvp[0] >= OVP_UVP_CHK_COUNT) {
-                        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputUVP = YES;
-                    } else {
-                        _threePhaseUvp[0] += 1;
-                    }
-                }
-            } else {
-                if (inputVoltage.L1N_L12 > VIN_MIN_REV_VOLTAGE_UL) {
-                    ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputUVP = NO;
-                    _threePhaseUvp[0] = 0;
-                }
-            }
-
-            if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL2InputUVP == NO) {
-                if (inputVoltage.L2N_L23 < VIN_MIN_VOLTAGE_UL) {
-                    log_info("In Uvp L2N_L23 = %f \n", inputVoltage.L2N_L23);
-                    if (_threePhaseUvp[1] >= OVP_UVP_CHK_COUNT) {
-                        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL2InputUVP = YES;
-                    } else {
-                        _threePhaseUvp[1] += 1;
-                    }
-                }
-            } else {
-                if (inputVoltage.L2N_L23 > VIN_MIN_REV_VOLTAGE_UL) {
-                    ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL2InputUVP = NO;
-                    _threePhaseUvp[1] = 0;
-                }
-            }
-
-            if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL3InputUVP == NO) {
-                if (inputVoltage.L3N_L31 < VIN_MIN_VOLTAGE_UL) {
-                    log_info("In Uvp L3N_L31 = %f \n", inputVoltage.L3N_L31);
-                    if (_threePhaseUvp[2] >= OVP_UVP_CHK_COUNT) {
-                        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL3InputUVP = YES;
-                    } else {
-                        _threePhaseUvp[2] += 1;
-                    }
-                }
-            } else {
-                if (inputVoltage.L3N_L31 > VIN_MIN_REV_VOLTAGE_UL) {
-                    ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL3InputUVP = NO;
-                    _threePhaseUvp[2] = 0;
-                }
-            }
-        }
-
-        //********************************************************************************************************//
-        // Vin (OVP)
-        if (ShmSysConfigAndInfo->SysInfo.ChargerType == _CHARGER_TYPE_IEC) {
-            if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputOVP == NO) {
-                if (inputVoltage.L1N_L12 > VIN_MAX_VOLTAGE_IEC) {
-                    log_info("In Ovp L1N_L12 = %f \n", inputVoltage.L1N_L12);
-                    if (_threePhaseOvp[0] >= OVP_UVP_CHK_COUNT) {
-                        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputOVP = YES;
-                    } else {
-                        _threePhaseOvp[0] += 1;
-                    }
-                }
-            } else {
-                if (inputVoltage.L1N_L12 < VIN_MAX_REV_VOLTAGE_IEC) {
-                    ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputOVP = NO;
-                    _threePhaseOvp[0] = 0;
-                }
-            }
-
-            if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL2InputOVP == NO) {
-                if (inputVoltage.L2N_L23 > VIN_MAX_VOLTAGE_IEC) {
-                    log_info("In Ovp L2N_L23 = %f \n", inputVoltage.L2N_L23);
-                    if (_threePhaseOvp[1] >= OVP_UVP_CHK_COUNT) {
-                        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL2InputOVP = YES;
-                    } else {
-                        _threePhaseOvp[1] += 1;
-                    }
-                }
-            } else {
-                if (inputVoltage.L2N_L23 < VIN_MAX_REV_VOLTAGE_IEC) {
-                    ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL2InputOVP = NO;
-                    _threePhaseOvp[1] = 0;
-                }
-            }
-
-            if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL3InputOVP == NO) {
-                if (inputVoltage.L3N_L31 > VIN_MAX_VOLTAGE_IEC) {
-                    log_info("In Ovp L3N_L31 = %f \n", inputVoltage.L3N_L31);
-                    if (_threePhaseOvp[2] >= OVP_UVP_CHK_COUNT) {
-                        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL3InputOVP = YES;
-                    } else {
-                        _threePhaseOvp[2] += 1;
-                    }
-                }
-            } else {
-                if (inputVoltage.L3N_L31 < VIN_MAX_REV_VOLTAGE_IEC) {
-                    ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL3InputOVP = NO;
-                    _threePhaseOvp[2] = 0;
-                }
-            }
-        } else if (ShmSysConfigAndInfo->SysInfo.ChargerType == _CHARGER_TYPE_UL) {
-            if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputOVP == NO) {
-                if (inputVoltage.L1N_L12 > VIN_MAX_VOLTAGE_UL) {
-                    log_info("In Ovp L1N_L12 = %f \n", inputVoltage.L1N_L12);
-                    if (_threePhaseOvp[0] >= OVP_UVP_CHK_COUNT) {
-                        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputOVP = YES;
-                    } else {
-                        _threePhaseOvp[0] += 0;
-                    }
-                }
-            } else {
-                if (inputVoltage.L1N_L12 < VIN_MAX_REV_VOLTAGE_UL) {
-                    ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputOVP = NO;
-                    _threePhaseOvp[0] = 0;
-                }
-            }
-
-            if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL2InputOVP == NO) {
-                if (inputVoltage.L2N_L23 > VIN_MAX_VOLTAGE_UL) {
-                    log_info("In Ovp L2N_L23 = %f \n", inputVoltage.L2N_L23);
-                    if (_threePhaseOvp[1] >= OVP_UVP_CHK_COUNT) {
-                        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL2InputOVP = YES;
-                    } else {
-                        _threePhaseOvp[1] += 0;
-                    }
-                }
-            } else {
-                if (inputVoltage.L2N_L23 < VIN_MAX_REV_VOLTAGE_UL) {
-                    ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL2InputOVP = NO;
-                    _threePhaseOvp[1] = 0;
-                }
-            }
-
-            if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL2InputOVP == NO) {
-                if (inputVoltage.L3N_L31 > VIN_MAX_VOLTAGE_UL) {
-                    log_info("In Ovp L3N_L31 = %f \n", inputVoltage.L3N_L31);
-                    if (_threePhaseOvp[2] >= OVP_UVP_CHK_COUNT) {
-                        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL3InputOVP = YES;
-                    } else {
-                        _threePhaseOvp[2] += 1;
-                    }
-                }
-            } else {
-                if (inputVoltage.L3N_L31 < VIN_MAX_REV_VOLTAGE_UL) {
-                    ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL3InputOVP = NO;
-                    _threePhaseOvp[2] = 0;
-                }
-            }
-        }
-    }
-}
-
-// 左右槍的 Relay 前後的輸出電壓
-void GetPersentOutputVol(void)
-{
-    uint8_t index = 0;
-    uint8_t targetID = 0;
-
-    if (Query_Present_OutputVoltage(Uart5Fd, ADDR_RELAY, &outputVoltage) != PASS) {
-        return;
-    }
-
-    //log_info("Conn1 fuse 1 = %f \n", outputVoltage.behindFuse_Voltage_C1);
-    //log_info("Conn1 relay 1 = %f \n", outputVoltage.behindRelay_Voltage_C1);
-    //log_info("Conn2 fuse 2 = %f \n", outputVoltage.behindFuse_Voltage_C2);
-    //log_info("Conn2 relay 2 = %f \n", outputVoltage.behindRelay_Voltage_C2);
-
-    //log_info("outputVoltage.behindFuse_Voltage_C1 = %f \n", outputVoltage.behindFuse_Voltage_C1);
-    //log_info("outputVoltage.behindFuse_Voltage_C2 = %f \n", outputVoltage.behindFuse_Voltage_C2);
-
-    ShmRelayModuleData->Gun1FuseOutputVolt = outputVoltage.behindFuse_Voltage_C1;
-    ShmRelayModuleData->Gun1RelayOutputVolt = outputVoltage.behindRelay_Voltage_C1;
-    ShmRelayModuleData->Gun2FuseOutputVolt = outputVoltage.behindFuse_Voltage_C2;
-    ShmRelayModuleData->Gun2RelayOutputVolt = outputVoltage.behindRelay_Voltage_C2;
-
-    for (index = 0; index < gunCount; index++) {
-        targetID = getCommTargetID(index);
-
-        switch (targetID) {
-        case 0x01:
-#if defined DD360Tcci || defined DD360Audi || defined DD360ComBox
-            _chargingData[index]->FireChargingVoltage = ShmRelayModuleData->Gun1RelayOutputVolt;
-            _chargingData[index]->PresentChargingCurrent = ShmRelayModuleData->Gun1FuseOutputVolt / 10;
-            _chargingData[index]->PresentChargingVoltage = _chargingData[index]->FireChargingVoltage / 10;
-            _chargingData[index]->FuseChargingVoltage = _chargingData[index]->FireChargingVoltage;
-            break;
-#endif //defined DD360Tcci || defined DD360Audi || defined DD360ComBox
-
-            _chargingData[index]->FireChargingVoltage = ShmRelayModuleData->Gun1RelayOutputVolt;
-            _chargingData[index]->FuseChargingVoltage = ShmRelayModuleData->Gun1FuseOutputVolt;
-            break;
-
-        case 0x02:
-#if defined DD360Tcci || defined DD360Audi || defined DD360ComBox
-            _chargingData[index]->FireChargingVoltage = ShmRelayModuleData->Gun2RelayOutputVolt;
-            _chargingData[index]->PresentChargingCurrent = ShmRelayModuleData->Gun2FuseOutputVolt / 10;
-            _chargingData[index]->PresentChargingVoltage = _chargingData[index]->FireChargingVoltage / 10;
-            _chargingData[index]->FuseChargingVoltage = _chargingData[index]->FireChargingVoltage;
-            break;
-#endif //defined DD360Tcci || defined DD360Audi || defined DD360ComBox
-
-            _chargingData[index]->FireChargingVoltage = ShmRelayModuleData->Gun2RelayOutputVolt;
-            _chargingData[index]->FuseChargingVoltage = ShmRelayModuleData->Gun2FuseOutputVolt;
-            break;
-        }
-
-        //unsigned short Ovp = 0;
-        //unsigned short Ocp = 0;
-        //Ovp = MIN [VOUT_MAX_VOLTAGE, EV_BATTERY_VOLTAGE]  // 最大輸出電壓與電池電壓最大值
-        //Ocp = MIN [IOUT_MAX_CURRENT, EV_CURRENT_REQ]      // 最大輸出電流與需求電流最小值
-        //if (_chargingData[index]->Type == _Type_Chademo) {
-        //    //Ovp = MaxValue(_chargingData[index]->MaximumChargingVoltage, _chargingData[index]->EvBatteryMaxVoltage);
-        //    //Ocp = MaxValue(_chargingData[index]->PresentChargingCurrent, ShmCHAdeMOData->ev[_chargingData[index]->type_index].ChargingCurrentRequest);
-        //} else if (_chargingData[index]->Type == _Type_CCS_2) {
-        //}
-    }
-}
-
-// 風扇速度
-void GetFanSpeed()
-{
-    //log_info("Get fan board speed \n");
-    if (Query_Fan_Speed(Uart5Fd, ADDR_FAN, &fanSpeed) == PASS) {
-        ShmFanModuleData->PresentFan1Speed = fanSpeed.speed[0];
-        ShmFanModuleData->PresentFan2Speed = fanSpeed.speed[1];
-        ShmFanModuleData->PresentFan3Speed = fanSpeed.speed[2];
-        ShmFanModuleData->PresentFan4Speed = fanSpeed.speed[3];
-//      log_info("SystemFanRotaSpeed_1 = %d \n", fanSpeed.speed[0]);
-//      log_info("SystemFanRotaSpeed_2 = %d \n", fanSpeed.speed[1]);
-//      log_info("SystemFanRotaSpeed_3 = %d \n", fanSpeed.speed[2]);
-//      log_info("SystemFanRotaSpeed_4 = %d \n", fanSpeed.speed[3]);
-        // Config_Fan_Speed(Uart5Fd, ADDR_FAN, &fanSpeed[0]);
-        //SysInfoData (SystemFanRotaSpeed)
-    }
-}
-
-// 讀取 Relay 狀態
-void GetRelayOutputStatus(void)
-{
-    if (Query_Relay_Output(Uart5Fd, ADDR_RELAY, &regRelay) == PASS) {
-#if !defined DD360Tcci && !defined DD360Audi && !defined DD360ComBox
-        regRelay.relay_event.bits.AC_Contactor = ShmSysConfigAndInfo->SysInfo.AcContactorStatus;
-#endif //!defined DD360Tcci && !defined DD360Audi
-    }
-}
-
-// 確認 K1 K2 relay 的狀態
-void CheckK1K2RelayOutput(uint8_t index)
-{
-    uint8_t targetID = 0;
-
-    targetID = getCommTargetID(index);
-
-    switch (targetID) {
-    case 0x01:
-        if (regRelay.relay_event.bits.Gun1_N == YES && regRelay.relay_event.bits.Gun1_P == YES) {
-            _chargingData[index]->RelayK1K2Status = YES;
-        } else {
-            _chargingData[index]->RelayK1K2Status = NO;
-        }
-
-        if (_chargingData[index]->Type == _Type_CCS_2) {
-#if !defined DD360Tcci && !defined DD360Audi && !defined DD360ComBox
-            if (regRelay.relay_event.bits.Gun1_N == YES && regRelay.relay_event.bits.CCS_Precharge == YES) {
-                _chargingData[index]->RelayKPK2Status = YES;
-            } else {
-                _chargingData[index]->RelayKPK2Status = NO;
-            }
-#else
-            if (_chargingData[index]->SystemStatus == S_CCS_PRECHARGE_ST0) {
-                _chargingData[index]->RelayKPK2Status = YES;
-            } else {
-                _chargingData[index]->RelayKPK2Status = NO;
-            }
-#endif //!defined DD360Tcci && !defined DD360Audi
-        }
-        break;
-
-    case 0x02:
-        if (regRelay.relay_event.bits.Gun2_N == YES &&
-                regRelay.relay_event.bits.Gun2_P == YES) {
-            _chargingData[index]->RelayK1K2Status = YES;
-        } else {
-            _chargingData[index]->RelayK1K2Status = NO;
-        }
-
-        if (_chargingData[index]->Type == _Type_CCS_2) {
-#if !defined DD360Tcci && !defined DD360Audi && !defined DD360ComBox
-            if (regRelay.relay_event.bits.Gun2_N == YES &&
-                    regRelay.relay_event.bits.CCS_Precharge == YES) {
-                _chargingData[index]->RelayKPK2Status = YES;
-            } else {
-                _chargingData[index]->RelayKPK2Status = NO;
-            }
-#else
-            if (_chargingData[index]->SystemStatus == S_CCS_PRECHARGE_ST0) {
-                _chargingData[index]->RelayKPK2Status = YES;
-            } else {
-                _chargingData[index]->RelayKPK2Status = NO;
-            }
-#endif //!defined DD360Tcci && !defined DD360Audi
-        }
-        break;
-    }
-
-#if !defined DD360Tcci && !defined DD360Audi && !defined DD360ComBox
-    //DS60-120 add
-    if (ShmSysConfigAndInfo->SysInfo.BridgeRelayStatus == YES) {
-        if (regRelay.relay_event.bits.Gun1_Parallel_N == NO &&
-                regRelay.relay_event.bits.Gun1_Parallel_P == NO) {
-            ShmSysConfigAndInfo->SysInfo.BridgeRelayStatus = NO;
-        }
-    } else if (ShmSysConfigAndInfo->SysInfo.BridgeRelayStatus == NO) {
-        if (regRelay.relay_event.bits.Gun1_Parallel_N == YES &&
-                regRelay.relay_event.bits.Gun1_Parallel_P == YES) {
-            ShmSysConfigAndInfo->SysInfo.BridgeRelayStatus = YES;
-        }
-    }
-#else
-    ShmSysConfigAndInfo->SysInfo.BridgeRelayStatus = YES;
-#endif //!defined DD360Tcci && !defined DD360Audi
-}
-
-void GetGfdAdc()
-{
-    int gunIndex = 0;
-    uint8_t targetID = 0;
-
-    // define : 每 0.2 ~ 1 秒一次
-    // occur : <= 75k 歐姆 @ 150 - 750 Vdc
-    // warning : >= 100 歐姆 && <= 500 歐姆 @ 150-750 Vdc
-    if (Query_Gfd_Adc(Uart5Fd, ADDR_RELAY, &gfd_adc) == PASS) {
-        for (gunIndex = 0; gunIndex < gunCount; gunIndex++) {
-            if (_chargingData[gunIndex]->Type == 0x09 &&
-                    !ShmSysConfigAndInfo->SysConfig.AlwaysGfdFlag
-               ) {
-                if ((_chargingData[gunIndex]->PresentChargingVoltage * 10) >= VOUT_MIN_VOLTAGE) {
-                    _chargingData[gunIndex]->GroundFaultStatus = GFD_PASS;
-                }
-                continue;
-            }
-
-            targetID = getCommTargetID(gunIndex);
-
-            if (targetID == 0x01) {
-                if (gfd_adc.result_conn1 == GFD_WARNING) {
-                    gfd_adc.result_conn1 = GFD_PASS;
-                }
-
-                _chargingData[gunIndex]->GroundFaultStatus = gfd_adc.result_conn1;
-                //log_info("GFD ******** Result = %d, Step = %d, R = %d, Vol = %d \n",
-                //            _chargingData[gunIndex]->GroundFaultStatus,
-                //            gfd_adc.rb_step_1,
-                //            gfd_adc.Resister_conn1,
-                //            gfd_adc.voltage_conn1);
-                if (_chargingData[gunIndex]->GroundFaultStatus == GFD_FAIL) {
-                    log_info("GFD Fail. index = %d, Step = %d, R = %d, Vol = %d \n",
-                             gunIndex,
-                             gfd_adc.rb_step_1,
-                             gfd_adc.Resister_conn1,
-                             gfd_adc.voltage_conn1);
-
-                } else if (_chargingData[gunIndex]->GroundFaultStatus == GFD_PASS ||
-                           _chargingData[gunIndex]->GroundFaultStatus == GFD_WARNING
-                          ) {
-                    if (_chargingData[gunIndex]->GroundFaultStatus == GFD_WARNING) {
-                        log_info("GFD Warning. index = %d, Result = %d, R = %d, Vol = %d \n",
-                                 gunIndex,
-                                 _chargingData[gunIndex]->GroundFaultStatus,
-                                 gfd_adc.Resister_conn1,
-                                 gfd_adc.voltage_conn1);
-                    }
-                }
-            } else if (targetID == 0x02) {
-                if (gfd_adc.result_conn2 == GFD_WARNING) {
-                    gfd_adc.result_conn2 = GFD_PASS;
-                }
-                _chargingData[gunIndex]->GroundFaultStatus = gfd_adc.result_conn2;
-                if (_chargingData[gunIndex]->GroundFaultStatus == GFD_FAIL) {
-                    log_info("GFD Fail. index = %d, Step = %d, R = %d, Vol = %d \n",
-                             gunIndex,
-                             gfd_adc.rb_step_2,
-                             gfd_adc.Resister_conn2,
-                             gfd_adc.voltage_conn2);
-                } else if (_chargingData[gunIndex]->GroundFaultStatus == GFD_PASS ||
-                           _chargingData[gunIndex]->GroundFaultStatus == GFD_WARNING
-                          ) {
-                    if (_chargingData[gunIndex]->GroundFaultStatus == GFD_WARNING) {
-                        log_info("GFD Warning. index = %d, Result = %d, R = %d, Vol = %d \n",
-                                 gunIndex,
-                                 _chargingData[gunIndex]->GroundFaultStatus,
-                                 gfd_adc.Resister_conn1,
-                                 gfd_adc.voltage_conn1);
-                    }
-                }
-            }
-        }
-    }
-}
-
-void GetGpioInput()
-{
-    if (Query_Gpio_Input(Uart5Fd, ADDR_AUX, &gpio_in) == PASS) {
-        // AC Contactor Status
-        if (gpio_in.AC_MainBreaker == 1) {
-            // AC Main Breaker ON
-            log_info("RB AC Main Breaker. \n");
-        }
-
-        if (gpio_in.SPD == 1) {
-            // SPD (雷擊保護) ON
-            log_info("RB SPD. \n");
-        }
-
-        if (gpio_in.Door_Open == 1) {
-            // Door Open
-            log_info("RB Door Open. \n");
-        }
-
-        if (gpio_in.GFD[0] == 1) {
-            // GFD_1 Trigger
-        }
-
-        if (gpio_in.GFD[1] == 1) {
-            // GFD_2 Trigger
-        }
-
-        if (gpio_in.AC_Drop == 1) {
-            // AC Drop
-            log_info("RB AC Drop. \n");
-        }
-
-        if (gpio_in.Emergency_IO == 1) {
-            // Emergency IO ON
-            log_info("RB Emergency IO ON. \n");
-        }
-
-        if (gpio_in.Button_Emergency_Press == 1) {
-            // Emergency button Press
-        }
-
-        if (gpio_in.Button_On_Press == 1) {
-            // On button Press
-        }
-
-        if (gpio_in.Button_Off_Press == 1) {
-            // Off button Press
-        }
-
-        if (gpio_in.Key_1_Press == 1) {
-            // key 1 press
-        }
-
-        if (gpio_in.Key_2_Press == 1) {
-            // key 2 press
-        }
-
-        if (gpio_in.Key_3_Press == 1) {
-            // key 3 press
-        }
-
-        if (gpio_in.Key_4_Press == 1) {
-            // key 4 press
-        }
-    }
-}
-
-// 5V 12V 24V 48V
-void GetAuxPower()
-{
-    if (Query_Aux_PowerVoltage(Uart5Fd, ADDR_FAN, &auxPower) == PASS) {
-        ShmSysConfigAndInfo->SysInfo.AuxPower48V = auxPower.voltage[0];
-        ShmSysConfigAndInfo->SysInfo.AuxPower24V = auxPower.voltage[1];
-        //ShmSysConfigAndInfo->SysInfo.AuxPower12V = auxPower.voltage[4];
-        //ShmSysConfigAndInfo->SysInfo.AuxPower5V = auxPower.voltage[6];
-        // aux power voltage
-        //log_info("aux1 = %x, \n", auxPower.voltage[0]);
-        //log_info("aux2 = %x, \n", auxPower.voltage[1]);
-    }
-}
-
-void SetFanModuleSpeed()
-{
-    {
-        FanSpeed _fanSpeed;
-
-        _setFanSpeed += fanSpeedSmoothValue;
-
-        if (_setFanSpeed >= ShmFanModuleData->SetFan1Speed) {
-            _setFanSpeed = ShmFanModuleData->SetFan1Speed;
-        }
-
-        //printf("_setFanSpeed = %d \n", _setFanSpeed);
-        _fanSpeed.speed[0] = _setFanSpeed;
-
-        _fanSpeed.speed[1] = _setFanSpeed;
-
-        _fanSpeed.speed[2] = _setFanSpeed;
-
-        _fanSpeed.speed[3] = _setFanSpeed;
-
-        if (Config_Fan_Speed(Uart5Fd, ADDR_FAN, &_fanSpeed) == PASS) {
-            //log_info("successfully Fan\n");
-        }
-    }
-}
-
-//==========================================
-// Common Function
-//==========================================
-void SetK1K2RelayStatus(uint8_t index)
-{
-    uint8_t targetID = 0;
-    PreChargingState *pRegPreChargingState = NULL;
-    PreChargingState *pOutputPreChargingState = NULL;
-    GunPNState *pRegGunPNState = NULL;
-    GunPNState *pOutputGunPNState = NULL;
-    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)_chargingData[index];
-
-    if (ShmPsuData->Work_Step >= _TEST_MODE && ShmPsuData->Work_Step <= _TEST_MODE) {
-        if (regRelay.relay_event.bits.Gun1_N == NO) {
-            outputRelay.relay_event.bits.Gun1_N = YES;
-        } else if (regRelay.relay_event.bits.Gun1_P == NO) {
-            outputRelay.relay_event.bits.Gun1_P = YES;
-        }
-        return;
-    }
-
-    targetID = getCommTargetID(index);
-
-    pRegPreChargingState = (PreChargingState *)&regRelay.relay_event.relay_status[0];
-    pOutputPreChargingState = (PreChargingState *)&outputRelay.relay_event.relay_status[0];
-    if (targetID == 0x01) {
-        pRegGunPNState = (GunPNState *)&regRelay.relay_event.relay_status[1];
-        pOutputGunPNState = (GunPNState *)&outputRelay.relay_event.relay_status[1];
-    } else if (targetID == 0x02) {
-        pRegGunPNState = (GunPNState *)&regRelay.relay_event.relay_status[2];
-        pOutputGunPNState = (GunPNState *)&outputRelay.relay_event.relay_status[2];
-    }
-
-    switch (pDcChargingInfo->SystemStatus) {
-    case S_BOOTING:
-    case S_IDLE:
-    case S_AUTHORIZING:
-    case S_REASSIGN_CHECK:
-    case S_REASSIGN:
-    case S_PREPARNING:
-    case S_PREPARING_FOR_EV:
-        if (pRegGunPNState->GunP == YES) {
-            pOutputGunPNState->GunP = NO;
-        } else if (pRegGunPNState->GunN == YES) {
-            pOutputGunPNState->GunN = NO;
-        }
-
-        if (targetID == 0x02 && pDcChargingInfo->Type == _Type_CCS_2) {
-            if (pRegPreChargingState->CcsPrecharge == YES) {
-                pOutputPreChargingState->CcsPrecharge = NO;
-            }
-        }
-        break;
-
-    case S_PREPARING_FOR_EVSE:
-    case S_CHARGING:
-        //if (pDcChargingInfo->RelayWeldingCheck != YES) {
-        //    break;
-        //}
-
-        if (pRegGunPNState->GunN == NO) {
-            pOutputGunPNState->GunN = YES;
-        } else if (pRegGunPNState->GunP == NO) {
-            pOutputGunPNState->GunP = YES;
-        }
-        break;
-
-    case S_TERMINATING:
-    case S_COMPLETE:
-    case S_ALARM:
-        if ((pDcChargingInfo->PresentChargingCurrent * 10) <= SEFETY_SWITCH_RELAY_CUR) {
-            if (pRegGunPNState->GunP == YES) {
-                pOutputGunPNState->GunP = NO;
-            } else if (pRegGunPNState->GunN == YES) {
-                pOutputGunPNState->GunN = NO;
-            }
-        }
-        break;
-
-    case S_CCS_PRECHARGE_ST0:
-#if defined DD360Tcci || defined DD360Audi || defined DD360ComBox
-        break;
-#endif //defined DD360Tcci || defined DD360Audi || defined DD360ComBox
-
-        if (pDcChargingInfo->Type == _Type_CCS_2 && targetID == 0x02) {
-            if (pRegPreChargingState->CcsPrecharge == NO) {
-                pOutputPreChargingState->CcsPrecharge = YES;
-            } else if (pRegPreChargingState->CcsPrecharge == YES) {
-                pRegGunPNState->GunP = NO;
-            }
-        }
-        break;
-
-    case S_CCS_PRECHARGE_ST1:
-#if defined DD360Tcci || defined DD360Audi || defined DD360ComBox
-        break;
-#endif //defined DD360Tcci || defined DD360Audi || defined DD360ComBox
-
-        if (pDcChargingInfo->Type == _Type_CCS_2 && targetID == 0x02) {
-            if (pRegGunPNState->GunP == NO) {
-                pOutputGunPNState->GunP = YES;
-            } else if (pRegGunPNState->GunP == YES) {
-                pOutputPreChargingState->CcsPrecharge = NO;
-            }
-        }
-        break;
-    }
-}
-
-void CheckAcInputOvpStatus(uint8_t index)
-{
-    if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputOVP == YES ||
-            ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL2InputOVP == YES ||
-            ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL3InputOVP == YES) {
-//      if ((_chargingData[index]->SystemStatus >= S_PREPARNING && _chargingData[index]->SystemStatus <= S_CHARGING) ||
-//              (_chargingData[index]->SystemStatus >= S_CCS_PRECHARGE_ST0 && _chargingData[index]->SystemStatus <= S_CCS_PRECHARGE_ST1))
-//      {
-//          if (ShmSysConfigAndInfo->SysInfo.ChargerType == _CHARGER_TYPE_IEC)
-//          {
-//              if (_psuInputVolR > VIN_MAX_VOLTAGE_IEC ||
-//                      _psuInputVolS > VIN_MAX_VOLTAGE_IEC ||
-//                      _psuInputVolT > VIN_MAX_VOLTAGE_IEC)
-//              {
-//                  log_info("IEC _psuInputVolR = %f, _psuInputVolS = %f, _psuInputVolT = %f \n",
-//                          _psuInputVolR, _psuInputVolS, _psuInputVolT);
-//                  _chargingData[index]->StopChargeFlag = YES;
-//              }
-//
-//          }
-//          else if (ShmSysConfigAndInfo->SysInfo.ChargerType == _CHARGER_TYPE_UL)
-//          {
-//              if (_psuInputVolR > VIN_MAX_VOLTAGE_UL ||
-//                      _psuInputVolS > VIN_MAX_VOLTAGE_UL ||
-//                      _psuInputVolT > VIN_MAX_VOLTAGE_UL)
-//              {
-//                  log_info("UL _psuInputVolR = %f, _psuInputVolS = %f, _psuInputVolT = %f \n",
-//                          _psuInputVolR, _psuInputVolS, _psuInputVolT);
-//                  _chargingData[index]->StopChargeFlag = YES;
-//              }
-//          }
-//      }
-//      else
-        //log_info("CheckAcInputOvpStatus\r\n");
-        _chargingData[index]->StopChargeFlag = YES;
-    }
-}
-
-void CheckPhaseLossStatus(uint8_t index)
-{
-    if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputUVP == YES ||
-            ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL2InputUVP == YES ||
-            ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL3InputUVP == YES) {
-        //log_info("CheckPhaseLossStatus\r\n");
-        _chargingData[index]->StopChargeFlag = YES;
-    }
-}
-
-void SetParalleRelayStatus(void)
-{
-#if defined  DD360Tcci || defined DD360Audi || defined DD360ComBox
-    return;
-#endif //!defined  DD360Tcci || !defined DD360Audi || !defined DD360ComBox
-
-    // 之後雙槍單模機種,橋接都會上
-    if (gunCount >= 2) {
-        if (_chargingData[0]->SystemStatus == S_BOOTING || _chargingData[1]->SystemStatus == S_BOOTING ||
-                (_chargingData[0]->SystemStatus == S_IDLE && _chargingData[1]->SystemStatus == S_IDLE)) {
-            // 初始化~ 不搭橋接
-            if (regRelay.relay_event.bits.Gun1_Parallel_P == YES) {
-                outputRelay.relay_event.bits.Gun1_Parallel_P = NO;
-            } else if (regRelay.relay_event.bits.Gun1_Parallel_N == YES) {
-                outputRelay.relay_event.bits.Gun1_Parallel_N = NO;
-            }
-        } else {
-            if (_chargingData[0]->IsReadyToCharging == YES ||
-                    _chargingData[1]->IsReadyToCharging == YES) {
-                // ************需考慮在切換中 - 切開 relay 與搭回 relay 的時機點************
-                if (ShmSysConfigAndInfo->SysInfo.MainChargingMode == _MAIN_CHARGING_MODE_MAX) {
-                    if (ShmSysConfigAndInfo->SysInfo.ReAssignedFlag < _REASSIGNED_RELAY_M_TO_A) {
-                        // 最大充 - 搭上橋接
-                        if (regRelay.relay_event.bits.Gun1_Parallel_N == NO) {
-                            outputRelay.relay_event.bits.Gun1_Parallel_N = YES;
-                        } else if (regRelay.relay_event.bits.Gun1_Parallel_P == NO) {
-                            outputRelay.relay_event.bits.Gun1_Parallel_P = YES;
-                        }
-                    } else {
-                        // 平均充 - 不搭
-                        if (regRelay.relay_event.bits.Gun1_Parallel_P == YES) {
-                            outputRelay.relay_event.bits.Gun1_Parallel_P = NO;
-                        } else if (regRelay.relay_event.bits.Gun1_Parallel_N == YES) {
-                            outputRelay.relay_event.bits.Gun1_Parallel_N = NO;
-                        }
-                    }
-                } else if (ShmSysConfigAndInfo->SysInfo.MainChargingMode == _MAIN_CHARGING_MODE_AVER) {
-                    if (ShmSysConfigAndInfo->SysInfo.ReAssignedFlag < _REASSIGNED_RELAY_A_TO_M) {
-                        // 平均充 - 不搭
-                        if (regRelay.relay_event.bits.Gun1_Parallel_P == YES) {
-                            outputRelay.relay_event.bits.Gun1_Parallel_P = NO;
-                        } else if (regRelay.relay_event.bits.Gun1_Parallel_N == YES) {
-                            outputRelay.relay_event.bits.Gun1_Parallel_N = NO;
-                        }
-                    } else {
-                        // 最大充 - 搭上橋接
-                        if (regRelay.relay_event.bits.Gun1_Parallel_N == NO) {
-                            outputRelay.relay_event.bits.Gun1_Parallel_N = YES;
-                        } else if (regRelay.relay_event.bits.Gun1_Parallel_P == NO) {
-                            outputRelay.relay_event.bits.Gun1_Parallel_P = YES;
-                        }
-                    }
-                }
-            }
-        }
-    }
-}
-
-void CheckAlarmOccur()
-{
-    bool isErr = false;
-    for (uint8_t count = 0; count < sizeof(_alarm_code) / sizeof(_alarm_code[0]); count++) {
-        if (acAlarmCode.AcAlarmCode & _alarm_code[count]) {
-            isErr = true;
-            switch (_alarm_code[count]) {
-            case AC_OVP: ShmStatusCodeData->AlarmCode.AlarmEvents.bits.AcSystemInputOVP = YES; break;
-            case AC_UVP: ShmStatusCodeData->AlarmCode.AlarmEvents.bits.AcSystemInputUVP = YES; break;
-            case AC_OCP: ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemAcOutputOCP = YES; break;
-            case AC_OTP: ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemAmbientOTP = YES; break;
-            case AC_GMI_FAULT: ShmStatusCodeData->AlarmCode.AlarmEvents.bits.AcGroundfaultFail = YES; break;
-            case AC_CP_ERROR: ShmStatusCodeData->InfoCode.InfoEvents.bits.PilotFault = YES; break;
-            case AC_AC_LEAKAGE: ShmStatusCodeData->AlarmCode.AlarmEvents.bits.RcdTrip = YES; break;
-            case AC_DC_LEAKAGE: ShmStatusCodeData->AlarmCode.AlarmEvents.bits.RcdTrip = YES; break;
-            case AC_SYSTEM_SELFTEST_FAULT: ShmStatusCodeData->AlarmCode.AlarmEvents.bits.McuSelftestFail = YES; break;
-            case AC_HANDSHAKE_TIMEOUT: break;
-            //case AC_EMC_STOP: ShmStatusCodeData->AlarmCode.AlarmEvents.bits.EmergencyStopTrip = YES; break;
-            case AC_RELAY_WELDING: ShmStatusCodeData->FaultCode.FaultEvents.bits.AcOutputRelayWelding = YES; break;
-            case AC_GF_MODULE_FAULT: ShmStatusCodeData->FaultCode.FaultEvents.bits.RcdSelfTestFail = YES; break;
-            case AC_SHUTTER_FAULT: break;
-            case AC_LOCKER_FAULT: ShmStatusCodeData->FaultCode.FaultEvents.bits.AcConnectorLockFail = YES; break;
-            case AC_POWER_DROP: ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputDrop = YES; break;
-            case AC_CIRCUIT_SHORT: ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CircuitShort = YES; break;
-            case AC_ROTARY_SWITCH_FAULT: break;
-            case AC_RELAY_DRIVE_FAULT: ShmStatusCodeData->FaultCode.FaultEvents.bits.AcOutputRelayDrivingFault = YES; break;
-            }
-        } else {
-            switch (_alarm_code[count]) {
-            case AC_OVP: ShmStatusCodeData->AlarmCode.AlarmEvents.bits.AcSystemInputOVP = NO; break;
-            case AC_UVP: ShmStatusCodeData->AlarmCode.AlarmEvents.bits.AcSystemInputUVP = NO; break;
-            case AC_OCP: ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemAcOutputOCP = NO; break;
-            case AC_OTP: ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemAmbientOTP = NO; break;
-            case AC_GMI_FAULT: ShmStatusCodeData->AlarmCode.AlarmEvents.bits.AcGroundfaultFail = NO; break;
-            case AC_CP_ERROR: ShmStatusCodeData->InfoCode.InfoEvents.bits.PilotFault = NO; break;
-            case AC_AC_LEAKAGE: ShmStatusCodeData->AlarmCode.AlarmEvents.bits.RcdTrip = NO; break;
-            case AC_DC_LEAKAGE: ShmStatusCodeData->AlarmCode.AlarmEvents.bits.RcdTrip = NO; break;
-            case AC_SYSTEM_SELFTEST_FAULT: ShmStatusCodeData->AlarmCode.AlarmEvents.bits.McuSelftestFail = NO; break;
-            case AC_HANDSHAKE_TIMEOUT: break;
-            //case AC_EMC_STOP: ShmStatusCodeData->AlarmCode.AlarmEvents.bits.EmergencyStopTrip = NO; break;
-            case AC_RELAY_WELDING: ShmStatusCodeData->FaultCode.FaultEvents.bits.AcOutputRelayWelding = NO; break;
-            case AC_GF_MODULE_FAULT: ShmStatusCodeData->FaultCode.FaultEvents.bits.RcdSelfTestFail = NO; break;
-            case AC_SHUTTER_FAULT: break;
-            case AC_LOCKER_FAULT: ShmStatusCodeData->FaultCode.FaultEvents.bits.AcConnectorLockFail = NO; break;
-            case AC_POWER_DROP: ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputDrop = NO; break;
-            case AC_CIRCUIT_SHORT: ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CircuitShort = NO; break;
-            case AC_ROTARY_SWITCH_FAULT:  break;
-            case AC_RELAY_DRIVE_FAULT: ShmStatusCodeData->FaultCode.FaultEvents.bits.AcOutputRelayDrivingFault = NO; break;
-            }
-        }
-    }
-
-    ac_chargingInfo[0]->IsErrorOccur = isErr;
-}
-
-bool IsNoneMatchLedColor()
-{
-    bool result = false;
-
-    if (cur_led_color.Connect_1_Red != led_color.Connect_1_Red ||
-            cur_led_color.Connect_1_Green != led_color.Connect_1_Green ||
-            cur_led_color.Connect_1_Blue != led_color.Connect_1_Blue ||
-            cur_led_color.Connect_2_Red != led_color.Connect_2_Red ||
-            cur_led_color.Connect_2_Green != led_color.Connect_2_Green ||
-            cur_led_color.Connect_2_Blue != led_color.Connect_2_Blue) {
-        result = true;
-    }
-
-    return result;
-}
-
-void SetLedColor(struct ChargingInfoData *chargingData_1, struct ChargingInfoData *chargingData_2)
-{
-    uint8_t _colorBuf = COLOR_MAX_LV * LED_INTENSITY_BRIGHTEST;
-
-    if (ShmSysConfigAndInfo->SysConfig.LedInfo.Intensity == _LED_INTENSITY_DARKEST) {
-        _colorBuf = COLOR_MAX_LV * LED_INTENSITY_DARKEST;
-    } else if (ShmSysConfigAndInfo->SysConfig.LedInfo.Intensity == _LED_INTENSITY_MEDIUM) {
-        _colorBuf = COLOR_MAX_LV * LED_INTENSITY_MEDIUM;
-    }
-
-    //printf("chargingData_1->SystemStatus=%d\n",chargingData_1->SystemStatus);
-    //printf("chargingData_2->SystemStatus=%d\n",chargingData_2->SystemStatus);
-    //printf("ShmSysConfigAndInfo->SysWarningInfo.Level=%d\n",ShmSysConfigAndInfo->SysWarningInfo.Level);
-    if (ShmSysConfigAndInfo->SysWarningInfo.Level == 2) {
-        led_color.Connect_1_Green = COLOR_MIN_LV;
-        led_color.Connect_1_Blue = COLOR_MIN_LV;
-        led_color.Connect_1_Red = _colorBuf;
-        led_color.Connect_2_Green = COLOR_MIN_LV;
-        led_color.Connect_2_Blue = COLOR_MIN_LV;
-        led_color.Connect_2_Red = _colorBuf;
-    } else {
-        if (ShmSysConfigAndInfo->SysInfo.IsAlternatvieConf) {
-            if ((chargingData_1->SystemStatus == S_BOOTING ||
-                    chargingData_1->SystemStatus == S_IDLE ||
-                    chargingData_1->SystemStatus == S_RESERVATION) &&
-                    (chargingData_2->SystemStatus == S_BOOTING ||
-                     chargingData_2->SystemStatus == S_IDLE ||
-                     chargingData_2->SystemStatus == S_RESERVATION)) {
-#if defined DD360Audi
-                led_color.Connect_1_Green = _colorBuf;
-                led_color.Connect_1_Blue = _colorBuf;
-                led_color.Connect_1_Red = _colorBuf;
-
-                led_color.Connect_2_Green = _colorBuf;
-                led_color.Connect_2_Blue = _colorBuf;
-                led_color.Connect_2_Red = _colorBuf;
-#else
-                led_color.Connect_1_Green = _colorBuf;
-                led_color.Connect_1_Blue = COLOR_MIN_LV;
-                led_color.Connect_1_Red = COLOR_MIN_LV;
-
-                led_color.Connect_2_Green = _colorBuf;
-                led_color.Connect_2_Blue = COLOR_MIN_LV;
-                led_color.Connect_2_Red = COLOR_MIN_LV;
-#endif
-            } else if ((chargingData_1->SystemStatus >= S_AUTHORIZING &&
-                        chargingData_1->SystemStatus <= S_COMPLETE) ||
-                       (chargingData_1->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
-                        chargingData_1->SystemStatus <= S_CCS_PRECHARGE_ST1) ||
-                       (chargingData_2->SystemStatus >= S_AUTHORIZING &&
-                        chargingData_2->SystemStatus <= S_COMPLETE) ||
-                       (chargingData_2->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
-                        chargingData_2->SystemStatus <= S_CCS_PRECHARGE_ST1)) {
-                led_color.Connect_1_Green = COLOR_MIN_LV;
-                led_color.Connect_1_Blue = _colorBuf;
-                led_color.Connect_1_Red = COLOR_MIN_LV;
-                led_color.Connect_2_Green = COLOR_MIN_LV;
-                led_color.Connect_2_Blue = _colorBuf;
-                led_color.Connect_2_Red = COLOR_MIN_LV;
-            }
-        } else {
-            if (chargingData_1->SystemStatus == S_BOOTING ||
-                    chargingData_1->SystemStatus == S_IDLE ||
-                    chargingData_1->SystemStatus == S_RESERVATION ||
-                    chargingData_1->SystemStatus == S_MAINTAIN) {
-
-                if (chargingData_1->IsAvailable == NO) { //For Audi
-                    led_color.Connect_1_Green = COLOR_MIN_LV;
-                    led_color.Connect_1_Blue = COLOR_MIN_LV;
-                    led_color.Connect_1_Red = _colorBuf;
-                } else {
-#if defined DD360Audi
-                    led_color.Connect_1_Green = _colorBuf;
-                    led_color.Connect_1_Blue = _colorBuf;
-                    led_color.Connect_1_Red = _colorBuf;
-#else
-                    led_color.Connect_1_Green = _colorBuf;
-                    led_color.Connect_1_Blue = COLOR_MIN_LV;
-                    led_color.Connect_1_Red = COLOR_MIN_LV;
-#endif
-                }
-            } else if ((chargingData_1->SystemStatus >= S_AUTHORIZING &&
-                        chargingData_1->SystemStatus <= S_COMPLETE) ||
-                       (chargingData_1->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
-                        chargingData_1->SystemStatus <= S_CCS_PRECHARGE_ST1)) {
-                led_color.Connect_1_Green = COLOR_MIN_LV;
-                led_color.Connect_1_Blue = _colorBuf;
-                led_color.Connect_1_Red = COLOR_MIN_LV;
-            }
-
-            // --------------------------------------------------------------------------
-            if (chargingData_2->SystemStatus == S_BOOTING ||
-                    chargingData_2->SystemStatus == S_IDLE ||
-                    chargingData_2->SystemStatus == S_RESERVATION ||
-                    chargingData_2->SystemStatus == S_MAINTAIN) {
-                if (chargingData_2->IsAvailable == NO) {
-                    led_color.Connect_2_Green = COLOR_MIN_LV;
-                    led_color.Connect_2_Blue = COLOR_MIN_LV;
-                    led_color.Connect_2_Red = _colorBuf;
-                } else {
-#if defined DD360Audi
-                    led_color.Connect_2_Green = _colorBuf;
-                    led_color.Connect_2_Blue = _colorBuf;
-                    led_color.Connect_2_Red = _colorBuf;
-#else
-                    led_color.Connect_2_Green = _colorBuf;
-                    led_color.Connect_2_Blue = COLOR_MIN_LV;
-                    led_color.Connect_2_Red = COLOR_MIN_LV;
-#endif
-                }
-            } else if ((chargingData_2->SystemStatus >= S_AUTHORIZING &&
-                        chargingData_2->SystemStatus <= S_COMPLETE) ||
-                       (chargingData_2->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
-                        chargingData_2->SystemStatus <= S_CCS_PRECHARGE_ST1)) {
-                led_color.Connect_2_Green = COLOR_MIN_LV;
-                led_color.Connect_2_Blue = _colorBuf;
-                led_color.Connect_2_Red = COLOR_MIN_LV;
-            }
-        }
-    }
-
-    if (_checkLedChanged > 0) {
-        if (Config_Led_Color(Uart5Fd, ADDR_LED, &led_color) == PASS) {
-            _checkLedChanged--;
-
-            cur_led_color.Connect_1_Red     = led_color.Connect_1_Red;
-            cur_led_color.Connect_1_Green   = led_color.Connect_1_Green;
-            cur_led_color.Connect_1_Blue    = led_color.Connect_1_Blue;
-            cur_led_color.Connect_2_Red     = led_color.Connect_2_Red;
-            cur_led_color.Connect_2_Green   = led_color.Connect_2_Green;
-            cur_led_color.Connect_2_Blue    = led_color.Connect_2_Blue;
-        }
-    } else if (IsNoneMatchLedColor()) {
-        _checkLedChanged = 3;
-    }
-}
-
-//==========================================
-// Init all share memory
-//==========================================
-int InitShareMemory()
-{
-    int result = PASS;
-    int MeterSMId;
-
-    if ((MeterSMId = shmget(ShmSysConfigAndInfoKey, sizeof(struct SysConfigAndInfo),  0777)) < 0) {
-        result = FAIL;
-    } else if ((ShmSysConfigAndInfo = shmat(MeterSMId, NULL, 0)) == (void *) - 1) {
-        result = FAIL;
-    }
-
-    if ((MeterSMId = shmget(ShmStatusCodeKey, sizeof(struct StatusCodeData),  0777)) < 0) {
-        result = FAIL;
-    } else if ((ShmStatusCodeData = shmat(MeterSMId, NULL, 0)) == (void *) - 1) {
-        result = FAIL;
-    }
-
-    if ((MeterSMId = shmget(ShmFanBdKey, sizeof(struct FanModuleData),  0777)) < 0) {
-        result = FAIL;
-    } else if ((ShmFanModuleData = shmat(MeterSMId, NULL, 0)) == (void *) - 1) {
-        result = FAIL;
-    }
-    memset(ShmFanModuleData, 0, sizeof(struct FanModuleData));
-
-    if ((MeterSMId = shmget(ShmRelayBdKey, sizeof(struct RelayModuleData),  0777)) < 0) {
-        result = FAIL;
-    } else if ((ShmRelayModuleData = shmat(MeterSMId, NULL, 0)) == (void *) - 1) {
-        result = FAIL;
-    }
-    memset(ShmRelayModuleData, 0, sizeof(struct RelayModuleData));
-
-    if ((MeterSMId = shmget(ShmLedBdKey, sizeof(struct LedModuleData),  0777)) < 0) {
-        result = FAIL;
-    } else if ((ShmLedModuleData = shmat(MeterSMId, NULL, 0)) == (void *) - 1) {
-        result = FAIL;
-    }
-    memset(ShmLedModuleData, 0, sizeof(struct LedModuleData));
-
-    if ((MeterSMId = shmget(ShmPsuKey, sizeof(struct PsuData),  0777)) < 0) {
-        result = FAIL;
-    } else if ((ShmPsuData = shmat(MeterSMId, NULL, 0)) == (void *) - 1) {
-        result = FAIL;
-    }
-
-    if ((MeterSMId = shmget(ShmOcppModuleKey, sizeof(struct OCPP16Data), 0777)) < 0) {
-        result = FAIL;
-    } else if ((ShmOCPP16Data = shmat(MeterSMId, NULL, 0)) == (void *) - 1) {
-        result = FAIL;
-    }
-
-    if ((MeterSMId = shmget(ShmCommonKey, sizeof(DcCommonInfo), IPC_CREAT | 0777)) < 0) {
-        return FAIL;
-    } else if ((ShmDcCommonData = shmat(MeterSMId, NULL, 0)) == (void *) - 1) {
-        return FAIL;
-    }
-
-    return result;
-}
-
-int InitComPort()
-{
-    int fd;
-    struct termios tios;
-
-    fd = open(relayRs485PortName, O_RDWR);
-    if (fd <= 0) {
-#ifdef SystemLogMessage
-        log_error("Module_InternalComm. InitComPort NG\n");
-#endif
-        if (ShmStatusCodeData != NULL) {
-            ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed = 1;
-        }
-        sleep(5);
-        return -1;
-    }
-    ioctl (fd, TCGETS, &tios);
-    tios.c_cflag = B115200 | CS8 | CLOCAL | CREAD;
-    tios.c_lflag = 0;
-    tios.c_iflag = 0;
-    tios.c_oflag = 0;
-    tios.c_cc[VMIN] = 0;
-    tios.c_cc[VTIME] = (uint8_t)0;     // timeout 0.5 second
-    tios.c_lflag = 0;
-    tcflush(fd, TCIFLUSH);
-    ioctl (fd, TCSETS, &tios);
-
-    return fd;
-}
-
-//================================================
-// Main process
-//================================================
-bool FindChargingInfoData(uint8_t target, struct ChargingInfoData **chargingData)
-{
-    for (uint8_t index = 0; index < CHAdeMO_QUANTITY; index++) {
-        if (ShmSysConfigAndInfo->SysInfo.ChademoChargingData[index].Index
-                == target) {
-            chargingData[target] =
-                &ShmSysConfigAndInfo->SysInfo.ChademoChargingData[index];
-            return true;
-        }
-    }
-
-    for (uint8_t index = 0; index < CCS_QUANTITY; index++) {
-        if (ShmSysConfigAndInfo->SysInfo.CcsChargingData[index].Index
-                == target) {
-            chargingData[target] =
-                &ShmSysConfigAndInfo->SysInfo.CcsChargingData[index];
-            return true;
-        }
-    }
-
-    for (uint8_t index = 0; index < GB_QUANTITY; index++) {
-        if (ShmSysConfigAndInfo->SysInfo.GbChargingData[index].Index
-                == target) {
-            chargingData[target] =
-                &ShmSysConfigAndInfo->SysInfo.GbChargingData[index];
-            return true;
-        }
-    }
-
-    return false;
-}
-
-bool FindAcChargingInfoData(uint8_t target, struct ChargingInfoData **acChargingData)
-{
-    if (target < AC_QUANTITY) {
-        acChargingData[target] = &ShmSysConfigAndInfo->SysInfo.AcChargingData[target];
-        return true;
-    }
-
-    return false;
-}
-
-void Initialization()
-{
-    bool isPass = false;
-
-    for (uint8_t index = 0; index < ARRAY_SIZE(outputRelay.relay_event.relay_status); index++) {
-        outputRelay.relay_event.relay_status[index] = 0x00;
-    }
-
-    while (!isPass) {
-        isPass = true;
-        for (uint8_t _index = 0; _index < gunCount; _index++) {
-            if (!FindChargingInfoData(_index, &_chargingData[0])) {
-                log_error("InternalComm : FindChargingInfoData false \n");
-                isPass = false;
-                break;
-            }
-        }
-
-        sleep(1);
-    }
-
-    isPass = false;
-
-    if (acgunCount > 0) {
-        while (!isPass) {
-            isPass = true;
-            for (uint8_t _index = 0; _index < acgunCount; _index++) {
-                if (!FindAcChargingInfoData(_index, &ac_chargingInfo[0])) {
-                    log_error("EvComm : FindAcChargingInfoData false \n");
-                    isPass = false;
-                    break;
-                }
-            }
-
-            sleep(1);
-        }
-    }
-}
-
-bool IsNoneMatchRelayStatus()
-{
-    bool result = false;
-
-    if (
-#if !defined DD360Tcci && !defined DD360Audi && !defined DD360ComBox
-        (regRelay.relay_event.bits.AC_Contactor != outputRelay.relay_event.bits.AC_Contactor) ||
-        (regRelay.relay_event.bits.CCS_Precharge != outputRelay.relay_event.bits.CCS_Precharge) ||
-#endif //!defined DD360Tcci && !defined DD360Audi
-        (regRelay.relay_event.bits.Gun1_P != outputRelay.relay_event.bits.Gun1_P) ||
-        (regRelay.relay_event.bits.Gun1_N != outputRelay.relay_event.bits.Gun1_N) ||
-        (regRelay.relay_event.bits.Gun2_P != outputRelay.relay_event.bits.Gun2_P) ||
-        (regRelay.relay_event.bits.Gun2_N != outputRelay.relay_event.bits.Gun2_N)
-#if !defined DD360Tcci && !defined DD360Audi && !defined DD360ComBox
-        ||
-        (regRelay.relay_event.bits.Gun1_Parallel_P != outputRelay.relay_event.bits.Gun1_Parallel_P) ||
-        (regRelay.relay_event.bits.Gun1_Parallel_N != outputRelay.relay_event.bits.Gun1_Parallel_N)
-#endif //!defined DD360Tcci && !defined DD360Audi
-    ) {
-        /*if (regRelay.relay_event.bits.AC_Contactor != outputRelay.relay_event.bits.AC_Contactor) {
-            log_info("AC Contact Relay none match. \n");
-        }
-
-        if (regRelay.relay_event.bits.CCS_Precharge != outputRelay.relay_event.bits.CCS_Precharge) {
-            log_info("CCS Precharge Relay none match. \n");
-        }
-
-        if (regRelay.relay_event.bits.Gun1_P != outputRelay.relay_event.bits.Gun1_P) {
-            log_info("SMR1:D+ Relay none match. \n");
-        }
-
-        if (regRelay.relay_event.bits.Gun1_N != outputRelay.relay_event.bits.Gun1_N) {
-            log_info("SMR1:D- Relay none match. \n");
-        }
-
-        if (regRelay.relay_event.bits.Gun2_P != outputRelay.relay_event.bits.Gun2_P) {
-            log_info("SMR2:D+ Relay none match. \n");
-        }
-
-        if (regRelay.relay_event.bits.Gun2_N != outputRelay.relay_event.bits.Gun2_N) {
-            log_info("SMR2:D- Relay none match. \n");
-        }
-
-        if (regRelay.relay_event.bits.Gun1_Parallel_P != outputRelay.relay_event.bits.Gun1_Parallel_P) {
-            log_info("Parallel:D+ Relay none match. \n");
-        }
-
-        if (regRelay.relay_event.bits.Gun1_Parallel_N != outputRelay.relay_event.bits.Gun1_Parallel_N) {
-            log_info("Parallel:D- Relay none match. \n");
-        }*/
-
-        result = true;
-    }
-
-    return result;
-}
-
-void MatchRelayStatus()
-{
-    // 因為 AC Contactor 沒有 Feedback,所以暫時先這樣處理
-    //regRelay.relay_event.bits.AC_Contactor = outputRelay.relay_event.bits.AC_Contactor;
-#if !defined DD360Tcci && !defined DD360Audi && !defined DD360ComBox
-    ShmSysConfigAndInfo->SysInfo.AcContactorStatus  = regRelay.relay_event.bits.AC_Contactor = outputRelay.relay_event.bits.AC_Contactor;
-#endif //!defined DD360Tcci && !defined DD360Audi
-
-    regRelay.relay_event.bits.CCS_Precharge = outputRelay.relay_event.bits.CCS_Precharge;
-    regRelay.relay_event.bits.Gun1_P = outputRelay.relay_event.bits.Gun1_P;
-    regRelay.relay_event.bits.Gun1_N = outputRelay.relay_event.bits.Gun1_N;
-    regRelay.relay_event.bits.Gun2_P = outputRelay.relay_event.bits.Gun2_P;
-    regRelay.relay_event.bits.Gun2_N = outputRelay.relay_event.bits.Gun2_N;
-    regRelay.relay_event.bits.Gun1_Parallel_P = outputRelay.relay_event.bits.Gun1_Parallel_P;
-    regRelay.relay_event.bits.Gun1_Parallel_N = outputRelay.relay_event.bits.Gun1_Parallel_N;
-}
-
-void CheckRelayStatusByADC()
-{
-    if (ShmRelayModuleData->Gun1FuseOutputVolt > 0 && ShmRelayModuleData->Gun1RelayOutputVolt > 0 &&
-            (ShmRelayModuleData->Gun1FuseOutputVolt == ShmRelayModuleData->Gun1RelayOutputVolt)) {
-        // Relay 前後電壓一致
-        _chargingData[0]->RelayK1K2Status = 0x01;
-    } else {
-        _chargingData[0]->RelayK1K2Status = 0x00;
-    }
-
-    if (ShmRelayModuleData->Gun2FuseOutputVolt > 0 && ShmRelayModuleData->Gun2RelayOutputVolt > 0 &&
-            (ShmRelayModuleData->Gun2FuseOutputVolt == ShmRelayModuleData->Gun2RelayOutputVolt)) {
-        // Relay 前後電壓一致
-        _chargingData[1]->RelayK1K2Status = 0x01;
-    } else {
-        _chargingData[1]->RelayK1K2Status = 0x00;
-    }
-}
-
-void SetGfdConfig(uint8_t index, uint8_t resister)
-{
-    gfd_config.index = index;
-    gfd_config.state = resister;
-
-    //log_info("************************GFD Vol = %d, GFD Res = %d \n", gfd_config.reqVol, gfd_config.resister);
-    if (Config_Gfd_Value(Uart5Fd, ADDR_RELAY, &gfd_config) == PASS) {
-//      log_info("Set reqVol = %f, resister = %d \n",
-//              gfd_config.reqVol,
-//              gfd_config.resister);
-    }
-}
-
-void CableCheckDetected(uint8_t index)
-{
-    uint8_t targetID = 0;
-    // Cable Check
-    // 當火線上的電壓 = 車端要求的電壓電流
-    // _chargingData[targetGun]->EvBatterytargetVoltage
-    // 才可以開始偵測 1s
-    // Warning : Rgfd <= 150 歐/V 假設電壓為 500V 則~ Rgfd <= 75000 歐
-    // Pre-Warning : 150 歐/V < Rgfd <= 500 歐/V 假設電壓為 500V 則 75000 歐 < Rgfd <= 250000
-    // SO Normal : Rgfd > 500 歐/V 假設電壓為 500 V 則 Rgfd > 250000 歐
-
-    if (gunCount == 1) {
-        if (strncmp((char *)&ShmSysConfigAndInfo->SysConfig.ModelName[7], "0", 1) != 0) {
-            targetID = 0;
-        } else if (strncmp((char *)&ShmSysConfigAndInfo->SysConfig.ModelName[9], "0", 1) != 0) {
-            targetID = 1;
-        }
-    } else {
-        targetID = index;
-    }
-
-    if ((_chargingData[index]->Type >= _Type_Chademo &&
-            _chargingData[index]->Type <= _Type_GB) ||
-            (_chargingData[index]->Type == 0x09 &&
-             ShmSysConfigAndInfo->SysConfig.AlwaysGfdFlag)) {
-        if ((_chargingData[index]->SystemStatus >= S_PREPARING_FOR_EVSE &&
-                _chargingData[index]->SystemStatus <= S_TERMINATING) ||
-                (_chargingData[index]->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
-                 _chargingData[index]->SystemStatus <= S_CCS_PRECHARGE_ST1)) {
-            if (_chargingData[index]->SystemStatus == S_PREPARING_FOR_EVSE &&
-                    _chargingData[index]->RelayWeldingCheck == YES) {
-                SetGfdConfig(targetID, GFD_CABLECHK);
-            } else if (_chargingData[index]->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
-                       _chargingData[index]->SystemStatus <= S_CCS_PRECHARGE_ST1) {
-                SetGfdConfig(targetID, GFD_PRECHARGE);
-            } else if (_chargingData[index]->SystemStatus >= S_CHARGING &&
-                       _chargingData[index]->SystemStatus <= S_TERMINATING) {
-                if (_chargingData[index]->Type == _Type_GB || _chargingData[index]->Type == _Type_Chademo) {
-                    SetGfdConfig(targetID, GFD_IDLE);
-                } else {
-                    SetGfdConfig(targetID, GFD_CHARGING);
-                }
-            }
-        } else if (_chargingData[index]->SystemStatus == S_COMPLETE ||
-                   _chargingData[index]->SystemStatus == S_PREPARNING
-                   || _chargingData[index]->SystemStatus == S_IDLE) {
-            SetGfdConfig(targetID, GFD_IDLE);
-        }
-    }
-}
-
-void CheckOutputPowerOverCarReq(uint8_t index)
-{
-    float fireV = _chargingData[index]->FireChargingVoltage;
-    float carV = _chargingData[index]->EvBatteryMaxVoltage * 10;
-
-    if ((_chargingData[index]->EvBatterytargetVoltage * 10) > 1500 &&
-            (_chargingData[index]->Type == _Type_Chademo ||
-             _chargingData[index]->Type == _Type_CCS_2 ||
-             _chargingData[index]->Type == _Type_GB)) {
-        if (fireV >= (carV + (carV * 0.02))) {
-            if (!_isOvpChkTimeFlag[index]) {
-                if ((_chargingData[index]->PresentChargingVoltage * 10) >= VOUT_MIN_VOLTAGE * 10) {
-                    gettimeofday(&_checkOutputVolProtectTimer[index], NULL);
-                    _isOvpChkTimeFlag[index] = YES;
-                }
-            } else {
-                log_info("[Module_InternalComm]CheckOutputPowerOverCarReq NG : fire = %f, battery = %f \n",
-                         _chargingData[index]->FireChargingVoltage, (_chargingData[index]->EvBatterytargetVoltage * 10));
-                log_error("[Module_InternalComm]CheckOutputPowerOverCarReq NG : fire = %f, battery = %f \n",
-                          _chargingData[index]->FireChargingVoltage, (_chargingData[index]->EvBatterytargetVoltage * 10));
-                if ((GetTimeoutValue(_checkOutputVolProtectTimer[index]) / 1000) >= OUTPUT_VOL_CHK_TIME) {
-                    //if (_chargingData[index]->Type == _Type_Chademo) {
-                    //    ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemChademoOutputOVP = YES;
-                    //} else if (_chargingData[index]->Type == _Type_CCS_2) {
-                    //    ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemCcsOutputOVP = YES;
-                    //} else if (_chargingData[index]->Type == _Type_GB) {
-                    //    ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemGbOutputOVP = YES;
-                    //}
-                    if (_chargingData[index]->Type == _Type_Chademo) {
-                        ShmDcCommonData->ConnectErrList[index].GunBits.ChaConnectOVP = YES;
-                        if (strncmp((char *)_chargingData[index]->ConnectorAlarmCode, "", 6) == EQUAL) {
-                            memcpy(_chargingData[index]->ConnectorAlarmCode, "012217", 6);
-                        }
-                    } else if (_chargingData[index]->Type == _Type_CCS_2) {
-                        ShmDcCommonData->ConnectErrList[index].GunBits.CCSConnectOVP = YES;
-                        if (strncmp((char *)_chargingData[index]->ConnectorAlarmCode, "", 6) == EQUAL) {
-                            memcpy(_chargingData[index]->ConnectorAlarmCode, "012219", 6);
-                        }
-                    } else if (_chargingData[index]->Type == _Type_GB) {
-                        ShmDcCommonData->ConnectErrList[index].GunBits.GBTConnectOVP = YES;
-                        if (strncmp((char *)_chargingData[index]->ConnectorAlarmCode, "", 6) == EQUAL) {
-                            memcpy(_chargingData[index]->ConnectorAlarmCode, "012221", 6);
-                        }
-                    }
-
-                    _chargingData[index]->StopChargeFlag = YES;
-                }
-            }
-        } else {
-            if (_isOvpChkTimeFlag[index] == YES) {
-                _isOvpChkTimeFlag[index] = NO;
-            }
-        }
-    }
-}
-
-void CheckOutputVolNoneMatchFire(uint8_t index)
-{
-    if ((_chargingData[index]->EvBatterytargetVoltage * 10) > 1500 &&
-            (_chargingData[index]->Type == _Type_Chademo ||
-             _chargingData[index]->Type == _Type_CCS_2 ||
-             _chargingData[index]->Type == _Type_GB)) {
-        if (((_chargingData[index]->PresentChargingVoltage * 10) < _chargingData[index]->FireChargingVoltage - 300) ||
-                ((_chargingData[index]->PresentChargingVoltage * 10) > _chargingData[index]->FireChargingVoltage + 300)) {
-            if (!_isOutputNoneMatch[index]) {
-                _isOutputNoneMatch[index] = YES;
-                gettimeofday(&_checkOutputNoneMatchTimer[index], NULL);
-            } else {
-                if ((GetTimeoutValue(_checkOutputNoneMatchTimer[index]) / 1000) >= 5000) {
-                    /*log_info("[Module_InternalComm]CheckOutputVolNoneMatchFire NG (%d) : pre = %f, fire = %f \n",
-                            index, (_chargingData[index]->PresentChargingVoltage * 10), _chargingData[index]->FireChargingVoltage);
-                    log_error("[Module_InternalComm]CheckOutputVolNoneMatchFire NG (%d): pre = %f, fire = %f \n",
-                            index, (_chargingData[index]->PresentChargingVoltage * 10), _chargingData[index]->FireChargingVoltage);
-                    _chargingData[index]->StopChargeFlag = YES;*/
-                }
-            }
-        } else {
-            _isOutputNoneMatch[index] = NO;
-        }
-    }
-}
-
-void CheckRelayWeldingStatus(uint8_t index)
-{
-    if (!_isRelayWelding[index]) {
-        if ((_chargingData[index]->PresentChargingVoltage * 10) >= VOUT_MIN_VOLTAGE * 10) {
-            gettimeofday(&_checkRelayWeldingTimer[index], NULL);
-            _isRelayWelding[index] = YES;
-        }
-    } else {
-        if ((GetTimeoutValue(_checkRelayWeldingTimer[index]) / 1000) >= 1000) {
-            _chargingData[index]->RelayWeldingCheck = YES;
-            return;
-        }
-
-        if (_chargingData[index]->FireChargingVoltage >= VOUT_MIN_VOLTAGE) {
-            if (_chargingData[index]->Type == _Type_Chademo) {
-                ShmStatusCodeData->FaultCode.FaultEvents.bits.ChademoOutputRelayWelding = YES;
-            } else if (_chargingData[index]->Type == _Type_GB) {
-                ShmStatusCodeData->FaultCode.FaultEvents.bits.GbOutputRelayWelding = YES;
-            } else if (_chargingData[index]->Type == _Type_CCS_2) {
-                ShmStatusCodeData->FaultCode.FaultEvents.bits.CcsOutputRelayWelding = YES;
-            }
-
-            log_info("CheckRelayWeldingStatus : fail \n");
-            _chargingData[index]->StopChargeFlag = YES;
-        }
-    }
-}
-
-void GetPsuTempForFanSpeed()
-{
-    char temp = 0;
-
-    for (uint8_t index = 0; index < ShmPsuData->GroupCount; index++) {
-        for (uint8_t count = 0; count < ShmPsuData->PsuGroup[index].GroupPresentPsuQuantity; count++) {
-            if (temp < ShmPsuData->PsuGroup[index].PsuModule[count].ExletTemp) {
-                temp = ShmPsuData->PsuGroup[index].PsuModule[count].ExletTemp;
-            }
-        }
-    }
-
-    ShmSysConfigAndInfo->SysInfo.SystemAmbientTemp = temp;
-
-    if (ShmSysConfigAndInfo->SysConfig.SwitchDebugFlag == NO) {
-        if (ShmFanModuleData->TestFanSpeed == NORMAL_FAN_SPEED) {
-            if (temp >= ENV_TEMP_MAX) {
-                ShmFanModuleData->TestFanSpeed = MAX_FAN_SPEED;
-            }
-        } else if (ShmFanModuleData->TestFanSpeed == MAX_FAN_SPEED) {
-            if (temp <= ENV_TEMP_MIN) {
-                ShmFanModuleData->TestFanSpeed = NORMAL_FAN_SPEED;
-            }
-        } else {
-            ShmFanModuleData->TestFanSpeed = NORMAL_FAN_SPEED;
-        }
-    }
-}
-
-void GetFanSpeedByFunction()
-{
-    if (ShmSysConfigAndInfo->SysConfig.SwitchDebugFlag == YES) {
-        return;
-    }
-
-    // 風控修改 :
-    // ******************************************************* //
-    //
-    //       當前PSU輸出總 KW       PSU Temp
-    // 30 x -------------------- x ---------- + 14 x (PSU Temp - 45)
-    //       當前樁最大功率 KW         45
-    //
-    // ******************************************************* //
-
-    // 當前樁最大功率 KW : ShmPsuData->SystemAvailablePower
-    unsigned int _maxPower = ShmPsuData->SystemAvailablePower;
-    // 當前PSU輸出總 KW & PSU Temp :
-    uint8_t temp = 0;
-    float power = 0;
-
-    for (uint8_t index = 0; index < ShmPsuData->GroupCount; index++) {
-        for (uint8_t count = 0; count < ShmPsuData->PsuGroup[index].GroupPresentPsuQuantity; count++) {
-            if (temp < ShmPsuData->PsuGroup[index].PsuModule[count].ExletTemp) {
-                temp = ShmPsuData->PsuGroup[index].PsuModule[count].ExletTemp;
-            }
-        }
-    }
-
-    for (uint8_t gunIndex = 0; gunIndex < gunCount; gunIndex++) {
-        power += (_chargingData[gunIndex]->PresentChargingPower * 10);
-    }
-
-    double _pw_rate = 0;
-    if (_maxPower > 0) {
-        _pw_rate = power / (double)_maxPower;
-    }
-    double _temp_rate = 0;
-    if (temp > 0) {
-        _temp_rate = (double)temp / 50;
-    }
-    uint8_t _temp_diff = 0;
-    if (temp > 45) {
-        _temp_diff = temp - 70;
-    }
-
-    ShmFanModuleData->TestFanSpeed = (((50 * _pw_rate * _temp_rate) + (0.5 * _temp_diff)) / 100) * MAX_FAN_SPEED;
-
-    if (ShmFanModuleData->TestFanSpeed > MAX_FAN_SPEED) {
-        ShmFanModuleData->TestFanSpeed = MAX_FAN_SPEED;
-    }
-
-    if (ShmFanModuleData->TestFanSpeed < 0) {
-        ShmFanModuleData->TestFanSpeed = 0;
-    }
-//
-//  printf("power = %f \n", power);
-//  printf("_maxPower = %d \n", _maxPower);
-//  printf("temp = %d \n", temp);
-//
-//  printf("_pw_rate = %f \n", _pw_rate);
-//  printf("_temp_rate = %f \n", _temp_rate);
-//  printf("_temp_diff = %d \n", _temp_diff);
-//  printf("fan rate = %f \n", (30 * _pw_rate * _temp_rate + 14 * _temp_diff));
-//  printf("ShmFanModuleData->TestFanSpeed = %d \n", ShmFanModuleData->TestFanSpeed);
-}
-
-void GetAcStatus()
-{
-    if (Query_AC_Status(Uart5Fd, ADDR_AC_PLUG, &acStatus) == PASS) {
-        ShmSysConfigAndInfo->SysConfig.AcRatingCurrent = acStatus.MaxCurrent;
-
-        if (ShmSysConfigAndInfo->SysConfig.AcMaxChargingCurrent == 0) {
-            ShmSysConfigAndInfo->SysConfig.AcMaxChargingCurrent = ShmSysConfigAndInfo->SysConfig.AcRatingCurrent;
-        }
-
-        ac_chargingInfo[0]->ConnectorPlugIn = acStatus.CpStatus;
-        //  log_info("CpStatus = %d \n", acStatus.CpStatus);
-        //              printf("CurLimit = %d \n", acStatus.CurLimit);
-        //              printf("PilotVol_P = %d \n", acStatus.PilotVol_P);
-        //              printf("PilotVol_N = %d \n", acStatus.PilotVol_N);
-        //              printf("LockStatus = %d \n", acStatus.LockStatus);
-        //              printf("RelayStatus = %d \n", acStatus.RelayStatus);
-        //              printf("ShutterStatus = %d \n", acStatus.ShutterStatus);
-        //              printf("MeterStatus = %d \n", acStatus.MeterStatus);
-        //              printf("PpStatus = %d \n", acStatus.PpStatus);
-        //              printf("MaxCurrent = %d \n", acStatus.MaxCurrent);
-        //              printf("RotateSwitchStatus = %d \n", acStatus.RelayStatus);
-        //              printf("============================== \n");
-        //
-        //              ac_chargingInfo[0]->SystemStatus = acStatus.CpStatus;
-    }
-//  else
-//      log_info("GetAcStatus return fail. \n");
-}
-
-void GetAcAlarmCode()
-{
-    if (Query_AC_Alarm_Code(Uart5Fd, ADDR_AC_PLUG, &acAlarmCode) == PASS) {
-        CheckAlarmOccur();
-    }
-}
-
-uint8_t GetChargingEnergy()
-{
-    return Query_Charging_Energy(Uart5Fd, ADDR_AC_PLUG, &acChargingEnergy);
-}
-
-uint8_t GetChargingCurrent()
-{
-    return Query_Charging_Current(Uart5Fd, ADDR_AC_PLUG, &acChargingCurrent);
-}
-
-void ChangeLedStatus()
-{
-    if (ac_chargingInfo[0]->SystemStatus == S_IDLE) {
-        ledStatus.ActionMode = 1;
-    } else if (ac_chargingInfo[0]->SystemStatus == S_PREPARNING) {
-        ledStatus.ActionMode = 3;
-    } else if (ac_chargingInfo[0]->SystemStatus == S_CHARGING) {
-        ledStatus.ActionMode = 4;
-    }
-
-    Config_LED_Status(Uart5Fd, ADDR_AC_PLUG, &ledStatus);
-}
-
-void SetLegacyReq(uint8_t _switch)
-{
-    Config_Legacy_Req(Uart5Fd, ADDR_AC_PLUG, _switch);
-}
-
-void SetCpDuty(uint8_t _value)
-{
-    Config_Ac_Duty(Uart5Fd, ADDR_AC_PLUG, _value);
-}
-
-void ChangeToCsuMode()
-{
-    ac_chargingInfo[0]->IsModeChagned = Config_CSU_Mode(Uart5Fd, ADDR_AC_PLUG);
-
-//  if (ac_chargingInfo[0]->IsModeChagned == PASS)
-//  {
-//      Config_Reset_MCU(Uart5Fd, ADDR_AC_PLUG);
-//  }
-}
-
-void ChangeStartOrStopDateTime(uint8_t isStart)
-{
-    char cmdBuf[32];
-    struct timeb csuTime;
-    struct tm *tmCSU;
-
-    ftime(&csuTime);
-    tmCSU = localtime(&csuTime.time);
-
-    sprintf(cmdBuf, "%04d-%02d-%02d %02d:%02d:%02d", tmCSU->tm_year + 1900,
-            tmCSU->tm_mon + 1, tmCSU->tm_mday, tmCSU->tm_hour, tmCSU->tm_min,
-            tmCSU->tm_sec);
-    if (isStart) {
-        strcpy((char *)ac_chargingInfo[0]->StartDateTime, cmdBuf);
-    } else {
-        strcpy((char *)ac_chargingInfo[0]->StopDateTime, cmdBuf);
-    }
-}
-
-void OcppStartTransation(uint8_t gunIndex)
-{
-    if (strcmp((char *)ac_chargingInfo[0]->StartUserId, "") == EQUAL) {
-        strcpy((char *)ShmOCPP16Data->StartTransaction[gunIndex].IdTag, (char *)ShmOCPP16Data->StartTransaction[gunIndex].IdTag);
-    } else {
-        strcpy((char *)ShmOCPP16Data->StartTransaction[gunIndex].IdTag, (char *)ac_chargingInfo[0]->StartUserId);
-    }
-
-    log_info("AC IdTag = %s \n", ShmOCPP16Data->StartTransaction[gunIndex].IdTag);
-    ShmOCPP16Data->CpMsg.bits[gunIndex].StartTransactionReq = YES;
-}
-
-void OcppStopTransation(uint8_t gunIndex)
-{
-    if (strcmp((char *)ac_chargingInfo[0]->StartUserId, "") == EQUAL) {
-        strcpy((char *)ShmOCPP16Data->StopTransaction[gunIndex].IdTag, (char *)ShmOCPP16Data->StopTransaction[gunIndex].IdTag);
-    } else {
-        strcpy((char *)ShmOCPP16Data->StopTransaction[gunIndex].IdTag, (char *)ac_chargingInfo[0]->StartUserId);
-    }
-
-    log_info("AC IdTag = %s \n", ShmOCPP16Data->StopTransaction[gunIndex].IdTag);
-    ShmOCPP16Data->CpMsg.bits[gunIndex].StopTransactionReq = YES;
-}
-
-bool OcppRemoteStop(uint8_t gunIndex)
-{
-    bool result = ShmOCPP16Data->CsMsg.bits[gunIndex].RemoteStopTransactionReq;
-
-    if (ShmOCPP16Data->CsMsg.bits[gunIndex].RemoteStopTransactionReq == YES) {
-        strcpy((char *)ShmOCPP16Data->StopTransaction[gunIndex].StopReason, "Remote");
-        ShmOCPP16Data->CsMsg.bits[gunIndex].RemoteStopTransactionReq = NO;
-    }
-
-    return result;
-}
-
-uint8_t isModeChange()
-{
-    uint8_t result = NO;
-
-    if (ac_chargingInfo[0]->SystemStatus != ac_chargingInfo[0]->PreviousSystemStatus) {
-        result = YES;
-        ac_chargingInfo[0]->PreviousSystemStatus = ac_chargingInfo[0]->SystemStatus;
-    }
-
-    return result;
-}
-
-void AcChargeTypeProcess()
-{
-    if (acgunCount > 0) {
-        //ac_chargingInfo[0]->SelfTest_Comp = YES;
-        //ac_chargingInfo[0]->IsModeChagned = PASS;
-        //---------------------------------------------
-        if (ac_chargingInfo[0]->SelfTest_Comp == NO) {
-            ac_chargingInfo[0]->IsModeChagned = NO;
-            GetFwVersion_AC();
-            GetAcModelName();
-        } else if (ac_chargingInfo[0]->SelfTest_Comp == YES) {
-            if (ac_chargingInfo[0]->IsModeChagned != PASS) {
-                ChangeToCsuMode();
-                return;
-            }
-            GetAcStatus();
-            GetAcAlarmCode();
-
-            uint8_t _status = S_NONE;
-
-            if (ac_chargingInfo[0]->SystemStatus == S_IDLE && ac_chargingInfo[0]->IsErrorOccur) {
-                _status = S_ALARM;
-            } else if (acStatus.CpStatus == AC_SYS_A || ac_chargingInfo[0]->IsErrorOccur) {
-                if (ac_chargingInfo[0]->SystemStatus == S_CHARGING) {
-                    _status = S_TERMINATING;
-                } else if (ac_chargingInfo[0]->SystemStatus >= S_TERMINATING) {
-                    if (GetTimeoutValue(_ac_charging_comp) >= 10000000 && acStatus.CpStatus == AC_SYS_A) {
-                        _status = S_IDLE;
-                    }
-                } else {
-                    _status = S_IDLE;
-                }
-            } else if (ac_chargingInfo[0]->SystemStatus >= S_PREPARNING &&
-                       ac_chargingInfo[0]->SystemStatus < S_CHARGING) {
-                if (acStatus.CpStatus == AC_SYS_C && acStatus.RelayStatus == YES) {
-                    _status = S_CHARGING;
-                } else if (GetTimeoutValue(_ac_preparing) >= 30000000) {
-                    _status = S_IDLE;
-                }
-            } else if ((acStatus.CpStatus == AC_SYS_B || ac_chargingInfo[0]->ConnectorPlugIn == AC_SYS_B) &&
-                       ac_chargingInfo[0]->IsAvailable &&
-                       !ac_chargingInfo[0]->IsErrorOccur &&
-                       (ShmSysConfigAndInfo->SysInfo.WaitForPlugit == YES ||
-                        ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_DISABLE)) {
-                if (ac_chargingInfo[0]->RemoteStartFlag == YES) {
-                    log_info("** AC Remote \n");
-                    ac_chargingInfo[0]->RemoteStartFlag = NO;
-                    strcpy((char *)ac_chargingInfo[0]->StartUserId, "");
-                    ShmSysConfigAndInfo->SysInfo.WaitForPlugit = NO;
-                    _status = S_PREPARNING;
-                } else if (ShmSysConfigAndInfo->SysInfo.OrderCharging == NO_DEFINE) {
-                    log_info("** UserId = %s \n", ShmSysConfigAndInfo->SysConfig.UserId);
-                    strcpy((char *)ac_chargingInfo[0]->StartUserId, (char *)ShmSysConfigAndInfo->SysConfig.UserId);
-                    log_info("** CardNumber = %s \n", ac_chargingInfo[0]->StartUserId);
-                    strcpy((char *)ShmSysConfigAndInfo->SysConfig.UserId, "");
-                    ShmSysConfigAndInfo->SysInfo.WaitForPlugit = NO;
-                    _status = S_PREPARNING;
-                }
-            } else if (ac_chargingInfo[0]->SystemStatus == S_CHARGING) {
-                if (OcppRemoteStop(1)) {
-                    _status = S_TERMINATING;
-                }
-            }
-
-            //printf("_status = %d \n", _status);
-
-            if (_status != S_NONE && ac_chargingInfo[0]->SystemStatus != _status) {
-                ac_chargingInfo[0]->SystemStatus = _status;
-            }
-
-            // 設定限制最大充電電流 >= 6 ~ <= 32
-            switch (ac_chargingInfo[0]->SystemStatus) {
-            case S_IDLE:
-            case S_ALARM: {
-                if (isModeChange()) {
-                    ac_chargingInfo[0]->PresentChargedEnergy = 0.0;
-                    ac_chargingInfo[0]->PresentChargingVoltage = 0;
-                    ac_chargingInfo[0]->ChargingFee = 0.0;
-                    strcpy((char *)ac_chargingInfo[0]->StartDateTime, "");
-                    strcpy((char *)ac_chargingInfo[0]->StopDateTime, "");
-                    _beforeChargingTotalEnergy = 0.0;
-                }
-
-                ChangeLedStatus();
-            }
-            break;
-            case S_PREPARNING: {
-                if (isModeChange()) {
-                    ShmSysConfigAndInfo->SysInfo.SystemPage = _LCM_NONE;
-                    ShmSysConfigAndInfo->SysInfo.CurGunSelectedByAc = DEFAULT_AC_INDEX;
-                    if (ShmSysConfigAndInfo->SysInfo.OrderCharging != NO_DEFINE) {
-                        ShmSysConfigAndInfo->SysInfo.OrderCharging = NO_DEFINE;
-                    }
-                    gettimeofday(&_ac_preparing, NULL);
-                }
-
-                if (GetChargingEnergy() == PASS) {
-                    //ac_chargingInfo[0]->PresentChargedEnergy = acChargingEnergy.Energy / 100;
-                    _beforeChargingTotalEnergy = acChargingEnergy.Energy;
-                }
-
-                SetLegacyReq(YES);
-                ChangeLedStatus();
-            }
-            break;
-            case S_CHARGING: {
-                if (isModeChange()) {
-                    ftime(&_ac_startChargingTime);
-                    OcppStartTransation(1);
-                    ChangeStartOrStopDateTime(YES);
-                    ShmSysConfigAndInfo->SysInfo.CurGunSelectedByAc = DEFAULT_AC_INDEX;
-                }
-
-                if (GetChargingEnergy() == PASS) {
-                    if ((acChargingEnergy.Energy - _beforeChargingTotalEnergy) > 0) {
-                        ac_chargingInfo[0]->PresentChargedEnergy += (acChargingEnergy.Energy - _beforeChargingTotalEnergy) / 100;
-                        if (ShmSysConfigAndInfo->SysConfig.BillingData.isBilling) {
-                            ac_chargingInfo[0]->ChargingFee += ac_chargingInfo[0]->PresentChargedEnergy * ShmSysConfigAndInfo->SysConfig.BillingData.Cur_fee;
-                        }
-                    }
-
-                    _beforeChargingTotalEnergy = acChargingEnergy.Energy;
-                }
-
-                if (GetChargingCurrent() == PASS) {
-                    ac_chargingInfo[0]->PresentChargingPower = (((float)(AC_DEFAULT_VOL * acChargingCurrent.OuputCurrentL1) / 10) / 1000);
-                }
-
-                ftime(&_ac_endChargingTime);
-                ac_chargingInfo[0]->PresentChargedDuration = DiffTimeb(_ac_startChargingTime, _ac_endChargingTime);
-                ac_chargingInfo[0]->PresentChargingVoltage = AC_DEFAULT_VOL;
-                ac_chargingInfo[0]->PresentChargingCurrent = ((float)acChargingCurrent.OuputCurrentL1 / 10);
-
-                // 用以判斷是否有在輸出
-                ac_chargingInfo[0]->IsCharging = acStatus.RelayStatus;
-
-                SetCpDuty(ShmSysConfigAndInfo->SysConfig.AcMaxChargingCurrent);
-                ChangeLedStatus();
-            }
-            break;
-            case S_TERMINATING: {
-                if (isModeChange()) {
-                    ChangeStartOrStopDateTime(NO);
-                    gettimeofday(&_ac_charging_comp, NULL);
-                }
-
-                SetLegacyReq(NO);
-                if (acStatus.RelayStatus == NO) {
-                    ac_chargingInfo[0]->SystemStatus = S_COMPLETE;
-                }
-            }
-            break;
-            case S_COMPLETE: {
-                if (isModeChange()) {
-                    gettimeofday(&_ac_charging_comp, NULL);
-                    ftime(&_ac_endChargingTime);
-                    if (strcmp((char *)ac_chargingInfo[0]->StartDateTime, "") != EQUAL) {
-                        // AC 固定為第2把槍
-                        OcppStopTransation(1);
-                    }
-
-                    ChangeStartOrStopDateTime(NO);
-                    ac_chargingInfo[0]->PresentChargedDuration = DiffTimeb(_ac_startChargingTime, _ac_endChargingTime);
-                }
-            }
-            break;
-            }
-        }
-    }
-}
-
-void ResetDetAlarmStatus(uint8_t gun)
-{
-    if (_chargingData[gun]->Type == _Type_Chademo) {
-        if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemChademoOutputOVP == YES) {
-            ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemChademoOutputOVP = NO;
-        }
-    } else if (_chargingData[gun]->Type == _Type_GB) {
-        if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemGbOutputOVP == YES) {
-            ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemGbOutputOVP = NO;
-        }
-    } else if (_chargingData[gun]->Type == _Type_CCS_2) {
-        if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemCcsOutputOVP == YES) {
-            ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemCcsOutputOVP = NO;
-        }
-    }
-}
-
-int main(void)
-{
-    uint8_t i = 0;
-    if (InitShareMemory() == FAIL) {
-        log_error("InitShareMemory NG\n");
-        if (ShmStatusCodeData != NULL) {
-            ShmStatusCodeData->AlarmCode.AlarmEvents.bits.FailToCreateShareMemory = 1;
-        }
-        sleep(5);
-        return 0;
-    }
-
-    gunCount = ShmSysConfigAndInfo->SysConfig.TotalConnectorCount;
-    acgunCount = ShmSysConfigAndInfo->SysConfig.AcConnectorCount;
-    // Open Uart5 for RB
-    Uart5Fd = InitComPort();
-    Initialization();
-    sleep(1);
-
-    if (Uart5Fd < 0) {
-        log_info("(Internal) open port error. \n");
-        return 0;
-    }
-
-    outputRelay.relay_event.bits.AC_Contactor = 0x00;
-    outputRelay.relay_event.bits.CCS_Precharge = 0x00;
-    outputRelay.relay_event.bits.Gun1_Parallel_P = 0x00;
-    outputRelay.relay_event.bits.Gun1_Parallel_N = 0x00;
-    outputRelay.relay_event.bits.Gun1_P = 0x00;
-    outputRelay.relay_event.bits.Gun1_N = 0x00;
-    outputRelay.relay_event.bits.Gun2_N = 0x00;
-    outputRelay.relay_event.bits.Gun2_P = 0x00;
-    if (Config_Relay_Output(Uart5Fd, ADDR_RELAY, &outputRelay) != PASS) {
-        log_info("Config_Relay_Output fail \n");
-
-    }
-
-    cur_led_color.Connect_1_Red = COLOR_MIN_LV;
-    cur_led_color.Connect_1_Green = COLOR_MIN_LV;
-    cur_led_color.Connect_1_Blue = COLOR_MIN_LV;
-    cur_led_color.Connect_2_Red = COLOR_MIN_LV;
-    cur_led_color.Connect_2_Green = COLOR_MIN_LV;
-    cur_led_color.Connect_2_Blue = COLOR_MIN_LV;
-
-    //bool printRelayStatus = true;
-    for (;;) {
-        bool isCharging = false;
-
-        // 程序開始之前~ 必須先確定 FW 版本與硬體版本,確認後!!~ 該模組才算是真正的 Initial Comp.
-        if (ShmRelayModuleData->SelfTest_Comp == NO) {
-            GetFwAndHwVersion_Relay();
-            SetModelName_Relay(); //DS60-120 add
-            SetRtcData_Relay();
-            sleep(1);
-        }
-
-#if !defined NO_FAN_BOARD && !defined DD360ComBox
-        if (ShmFanModuleData->SelfTest_Comp == NO) {
-            GetFwAndHwVersion_Fan();
-            SetModelName_Fan();
-            SetRtcData_Fan();
-            sleep(1);
-            gettimeofday(&_priority_time, NULL);
-        }
-#endif //NO_FAN_BOARD
-
-#if !defined DD360ComBox
-        // 自檢階段處理,自檢階段如果讀不到版號則代表該系統沒有掛燈板
-        if (ShmLedModuleData->SelfTest_Comp == NO) {
-#if defined DD360Tcci ||defined DD360Audi
-            GetFwAndHwVersion_Led();
-            sleep(1);
-            gettimeofday(&_led_priority_time, NULL);
-#else
-            // 自檢階段
-            if (ShmSysConfigAndInfo->SysInfo.SelfTestSeq <= _STEST_PSU_CAP) {
-                GetFwAndHwVersion_Led();
-                sleep(1);
-                gettimeofday(&_led_priority_time, NULL);
-            } else {
-                // 自檢階段沒有問到版號
-                if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.LedboardStestFail == NO) {
-                    ShmStatusCodeData->AlarmCode.AlarmEvents.bits.LedboardStestFail = YES;
-                }
-            }
-#endif //defined DD360Tcci || defined DD360Audi
-        }
-#endif //!defined DD360ComBox
-
-        AcChargeTypeProcess();
-
-        if (ShmRelayModuleData->SelfTest_Comp == YES) {
-            // ==============優先權最高 10 ms ==============
-            // 輸出電壓
-            GetPersentOutputVol();
-
-#if !defined DD360Tcci && !defined DD360Audi && !defined DD360ComBox
-            // 三相輸入電壓
-            GetPresentInputVol();
-            // 讀取當前 AC relay 狀態
-            regRelay.relay_event.bits.AC_Contactor = ShmSysConfigAndInfo->SysInfo.AcContactorStatus;
-
-            GetRelayOutputStatus();
-#endif //!defined DD360Tcci && !defined DD360Audi
-
-            for (i = 0; i < gunCount; i++) {
-                // Cable check (Set)
-                CableCheckDetected(i);
-
-                // check k1 k2 relay 狀態
-                CheckK1K2RelayOutput(i);
-
-                // 依據當前各槍的狀態選擇 搭上/放開 Relay
-                SetK1K2RelayStatus(i);
-
-#if !defined DD360Tcci && !defined DD360Audi && !defined DD360ComBox
-                if (ShmSysConfigAndInfo->SysConfig.PhaseLossPolicy == YES) {
-                    CheckPhaseLossStatus(i);
-                }
-
-                CheckAcInputOvpStatus(i);
-#endif //!defined DD360Tcci && !defined DD360Audi
-
-                if (_chargingData[i]->SystemStatus == S_IDLE) {
-                    _chargingData[i]->RelayWeldingCheck = NO;
-                    _isRelayWelding[i] = NO;
-                    _isOvpChkTimeFlag[i] = NO;
-                    ResetDetAlarmStatus(i); //DS60-120 add
-                }
-
-                if (_chargingData[i]->SystemStatus == S_BOOTING ||
-                        (_chargingData[i]->SystemStatus >= S_REASSIGN_CHECK && _chargingData[i]->SystemStatus <= S_COMPLETE) ||
-                        (_chargingData[i]->SystemStatus >= S_CCS_PRECHARGE_ST0 && _chargingData[i]->SystemStatus <= S_CCS_PRECHARGE_ST1) ||
-                        ShmSysConfigAndInfo->SysInfo.WaitForPlugit == YES ||
-                        (ShmSysConfigAndInfo->SysInfo.PageIndex >= _LCM_AUTHORIZING && ShmSysConfigAndInfo->SysInfo.PageIndex <= _LCM_WAIT_FOR_PLUG)) {
-                    _chargingData[i]->IsReadyToCharging = YES;
-                    isCharging = true;
-
-                    // 限定只有在槍類別為 GBT 的時候才做 relay welding 的判斷
-                    //if (_chargingData[i]->Type == _Type_GB) {
-                    //    if (_chargingData[i]->SystemStatus >= S_PREPARING_FOR_EVSE &&
-                    //            _chargingData[i]->RelayWeldingCheck == NO) {
-                    //        CheckRelayWeldingStatus(i);
-                    //    }
-                    //} else {
-                    _chargingData[i]->RelayWeldingCheck = YES;
-                    //}
-
-                    if (_chargingData[i]->SystemStatus == S_CHARGING) {
-                        CheckOutputPowerOverCarReq(i);
-                        //CheckOutputVolNoneMatchFire(i);
-                    } else {
-                        _isOutputNoneMatch[i] = NO;
-                    }
-                } else {
-                    _chargingData[i]->IsReadyToCharging = NO;
-                }
-            }
-
-            // Cable check (Get)
-            GetGfdAdc();
-
-            // 橋接 relay
-            SetParalleRelayStatus();
-
-            // 搭上 AC Contactor
-            //if (isCharging) {
-            //    outputRelay.relay_event.bits.AC_Contactor = YES;
-            //} else {
-            //    outputRelay.relay_event.bits.AC_Contactor = NO;
-            //}
-
-            if (isCharging ||
-                    (ShmPsuData->Work_Step >= _TEST_MODE &&
-                     ShmPsuData->Work_Step <= _TEST_MODE)) {
-                isStopChargingCount = false;
-                outputRelay.relay_event.bits.AC_Contactor = YES;
-            } else {
-                if (!isStopChargingCount) {
-                    gettimeofday(&_close_ac_contactor, NULL);
-                    isStopChargingCount = true;
-                } else {
-                    if ((outputRelay.relay_event.bits.AC_Contactor == YES &&
-                            GetTimeoutValue(_close_ac_contactor) / 1000 >= (TEN_MINUTES * 1000))) {
-                        outputRelay.relay_event.bits.AC_Contactor = NO;
-                    }
-                }
-            }
-
-            if (ShmPsuData->Work_Step >= _TEST_MODE && ShmPsuData->Work_Step <= _TEST_MODE) {
-                outputRelay.relay_event.bits.Gun1_N = outputRelay.relay_event.bits.Gun1_P = YES;
-            }
-
-            // 搭上/鬆開 Relay
-            if (IsNoneMatchRelayStatus()) {
-                if (Config_Relay_Output(Uart5Fd, ADDR_RELAY, &outputRelay)) {
-                    //regRelay.relay_event.bits.AC_Contactor = ShmSysConfigAndInfo->SysInfo.AcContactorStatus;
-                    regRelay.relay_event.bits.CCS_Precharge = outputRelay.relay_event.bits.CCS_Precharge;
-                    regRelay.relay_event.bits.Gun1_P = outputRelay.relay_event.bits.Gun1_P;
-                    regRelay.relay_event.bits.Gun1_N = outputRelay.relay_event.bits.Gun1_N;
-                    regRelay.relay_event.bits.Gun2_P = outputRelay.relay_event.bits.Gun2_P;
-                    regRelay.relay_event.bits.Gun2_N = outputRelay.relay_event.bits.Gun2_N;
-                    regRelay.relay_event.bits.Gun1_Parallel_P = outputRelay.relay_event.bits.Gun1_Parallel_P;
-                    regRelay.relay_event.bits.Gun1_Parallel_N = outputRelay.relay_event.bits.Gun1_Parallel_N;
-
-                    //log_info("Match Relay, AC = %x, g1_p = %x, g1_n = %x, g2_p = %x, g2_n = %x, pre = %x, bri_p = %x, bri_n = %x \n",
-                    //            regRelay.relay_event.bits.AC_Contactor,
-                    //            regRelay.relay_event.bits.Gun1_P,
-                    //            regRelay.relay_event.bits.Gun1_N,
-                    //            regRelay.relay_event.bits.Gun2_P,
-                    //            regRelay.relay_event.bits.Gun2_N,
-                    //            regRelay.relay_event.bits.CCS_Precharge,
-                    //            regRelay.relay_event.bits.Gun1_Parallel_P,
-                    //            regRelay.relay_event.bits.Gun1_Parallel_N);
-
-                }
-            }
-        }
-
-#if !defined NO_FAN_BOARD && !defined DD360ComBox
-        if (ShmFanModuleData->SelfTest_Comp == YES ||
-                strlen((char *)ShmSysConfigAndInfo->SysInfo.FanModuleFwRev) != 0 ||
-                ShmSysConfigAndInfo->SysInfo.FanModuleFwRev[0] != '\0') {
-            ShmFanModuleData->SelfTest_Comp = YES;
-
-            if (GetTimeoutValue(_priority_time) / 1000 >= 1000) {
-                //GetPsuTempForFanSpeed();
-                GetFanSpeedByFunction();
-                GetFanSpeed();
-                ShmSysConfigAndInfo->SysInfo.SystemFanRotaSpeed = _setFanSpeed;
-                gettimeofday(&_priority_time, NULL);
-
-                ShmFanModuleData->SetFan1Speed = ShmFanModuleData->TestFanSpeed;
-                ShmFanModuleData->SetFan2Speed = ShmFanModuleData->TestFanSpeed;
-                ShmFanModuleData->SetFan3Speed = ShmFanModuleData->TestFanSpeed;
-                ShmFanModuleData->SetFan4Speed = ShmFanModuleData->TestFanSpeed;
-
-                //log_info("set fan = %d \n", ShmFanModuleData->SetFan1Speed);
-                SetFanModuleSpeed();
-            }
-        }
-#endif //NO_FAN_BOARD
-
-#if !defined DD360ComBox
-        if (ShmLedModuleData->SelfTest_Comp == YES) {
-            if (GetTimeoutValue(_led_priority_time) / 1000 >= 1000) {
-                if (gunCount == 1) {
-                    SetLedColor(_chargingData[0], _chargingData[0]);
-                } else if (gunCount == 2) {
-                    SetLedColor(_chargingData[0], _chargingData[1]);
-                }
-
-                gettimeofday(&_led_priority_time, NULL);
-            }
-        }
-#endif //defined DD360ComBox
-
-        usleep(10000);
-    }
-
-    return FAIL;
-}
+#include <sys/time.h>
+#include <sys/timeb.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <sys/ioctl.h>
+#include <sys/socket.h>
+#include <sys/ipc.h>
+#include <sys/shm.h>
+#include <sys/mman.h>
+#include <linux/wireless.h>
+#include <arpa/inet.h>
+#include <netinet/in.h>
+
+#include <unistd.h>
+#include <stdarg.h>
+#include <stdio.h>      /*標準輸入輸出定義*/
+#include <stdlib.h>     /*標準函數庫定義*/
+#include <unistd.h>     /*Unix 標準函數定義*/
+#include <fcntl.h>      /*檔控制定義*/
+#include <termios.h>    /*PPSIX 終端控制定義*/
+#include <errno.h>      /*錯誤號定義*/
+#include <errno.h>
+#include <string.h>
+#include <time.h>
+#include <ctype.h>
+#include <ifaddrs.h>
+#include <math.h>
+#include <stdbool.h>
+
+#include "../Define/define.h"
+#include "Module_InternalComm.h"
+#include "internalComm.h"
+#include "../Config.h"
+
+//------------------------------------------------------------------------------
+struct SysConfigAndInfo         *ShmSysConfigAndInfo;
+struct StatusCodeData           *ShmStatusCodeData;
+struct FanModuleData            *ShmFanModuleData;
+struct RelayModuleData          *ShmRelayModuleData;
+struct LedModuleData            *ShmLedModuleData;
+struct PsuData                  *ShmPsuData;
+struct OCPP16Data               *ShmOCPP16Data;
+DcCommonInfo                    *ShmDcCommonData;
+
+uint8_t gunCount;
+uint8_t acgunCount;
+// 槍資訊
+struct ChargingInfoData *_chargingData[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
+struct ChargingInfoData *ac_chargingInfo[AC_QUANTITY];
+
+bool _isOutputNoneMatch[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
+struct timeval _checkOutputNoneMatchTimer[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
+
+bool _isRelayWelding[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
+struct timeval _checkRelayWeldingTimer[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
+
+bool _isOvpChkTimeFlag[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY]; //DS60-120 add
+struct timeval _checkOutputVolProtectTimer[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY]; //DS60-120 add
+
+// SMR1 *2 + SMR2 * 2 + Parallel * 2
+struct timeval _relayStateChkTimer[6]; //DS60-120 add
+
+uint8_t _threePhaseOvp[3] = {0, 0, 0}; //DS60-120 add
+uint8_t _threePhaseUvp[3] = {0, 0, 0}; //DS60-120 add
+
+bool FindChargingInfoData(uint8_t target, struct ChargingInfoData **chargingData);
+
+int Uart5Fd;
+char *relayRs485PortName = "/dev/ttyS5";
+unsigned short fanSpeedSmoothValue = 500;
+
+bool isStopChargingCount = false;
+struct timeval _close_ac_contactor;
+
+struct timeval _priority_time;
+struct timeval _led_priority_time;
+
+struct timeval  _ac_charging_comp;
+struct timeval  _ac_preparing;
+struct timeb    _ac_startChargingTime;
+struct timeb    _ac_endChargingTime;
+
+unsigned short _setFanSpeed = 0;
+float _beforeChargingTotalEnergy = 0.0;
+uint8_t _checkLedChanged = 3;
+
+Ver ver;
+PresentInputVoltage inputVoltage;
+PresentOutputVoltage outputVoltage;
+FanSpeed fanSpeed;
+Temperature temperature;
+AuxPower auxPower;
+Gfd gfd_adc;
+Gfd_config gfd_config;
+Gpio_in gpio_in;
+Gpio_out gpio_out;
+Relay outputRelay;
+Relay regRelay;
+Rtc rtc;
+Led_Color cur_led_color;
+Led_Color led_color;
+
+Ac_Status acStatus;
+Ac_Led_Status ledStatus;
+Ac_Alarm_code acAlarmCode;
+Ac_Charging_energy acChargingEnergy;
+Ac_Charging_current acChargingCurrent;
+
+int _alarm_code[] = {
+    AC_OVP,
+    AC_UVP,
+    AC_OCP,
+    AC_OTP,
+    AC_GMI_FAULT,
+    AC_CP_ERROR,
+    AC_AC_LEAKAGE,
+    AC_DC_LEAKAGE,
+    AC_SYSTEM_SELFTEST_FAULT,
+    AC_HANDSHAKE_TIMEOUT,
+    AC_EMC_STOP,
+    AC_RELAY_WELDING,
+    AC_GF_MODULE_FAULT,
+    AC_SHUTTER_FAULT,
+    AC_LOCKER_FAULT,
+    AC_POWER_DROP,
+    AC_CIRCUIT_SHORT,
+    AC_ROTARY_SWITCH_FAULT,
+    AC_RELAY_DRIVE_FAULT
+};
+
+uint8_t getCommTargetID(uint8_t index)
+{
+    uint8_t targetID = 0;
+
+    if (gunCount == 1) {
+        if (strncmp((char *)&ShmSysConfigAndInfo->SysConfig.ModelName[7], "0", 1) != 0) {
+            targetID = 0x01;
+        } else if (strncmp((char *)&ShmSysConfigAndInfo->SysConfig.ModelName[9], "0", 1) != 0) {
+            targetID = 0x02;
+        }
+    } else {
+        targetID = _chargingData[index]->Evboard_id;
+    }
+
+    return targetID;
+}
+
+unsigned long GetTimeoutValue(struct timeval _sour_time)
+{
+    struct timeval _end_time;
+    gettimeofday(&_end_time, NULL);
+
+    return 1000000 * (_end_time.tv_sec - _sour_time.tv_sec) + _end_time.tv_usec - _sour_time.tv_usec;
+}
+
+int StoreLogMsg(const char *fmt, ...)
+{
+    char Buf[4096 + 256];
+    char buffer[4096];
+    va_list args;
+    struct timeb  SeqEndTime;
+    struct tm *tm;
+
+    va_start(args, fmt);
+    int rc = vsnprintf(buffer, sizeof(buffer), fmt, args);
+    va_end(args);
+
+    memset(Buf, 0, sizeof(Buf));
+    ftime(&SeqEndTime);
+    SeqEndTime.time = time(NULL);
+    tm = localtime(&SeqEndTime.time);
+
+    if (ShmSysConfigAndInfo->SysConfig.SwitchDebugFlag == YES) {
+        sprintf(Buf, "%02d:%02d:%02d:%03d - %s",
+                tm->tm_hour, tm->tm_min, tm->tm_sec, SeqEndTime.millitm, buffer);
+        printf("%s \n", Buf);
+    } else {
+        sprintf(Buf, "echo \"%04d-%02d-%02d %02d:%02d:%02d:%03d - %s\" >> /Storage/SystemLog/[%04d.%02d]SystemLog",
+                tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec, SeqEndTime.millitm,
+                buffer,
+                tm->tm_year + 1900, tm->tm_mon + 1);
+        system(Buf);
+    }
+
+    return rc;
+}
+
+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;
+    return (StopTime - StartTime);
+}
+
+unsigned short MaxValue(unsigned short value1, unsigned short value2)
+{
+    return value1 >= value2 ? value1 : value2;
+}
+
+//==========================================
+// Communication Function
+//==========================================
+void GetFwAndHwVersion_Fan()
+{
+    if (Query_FW_Ver(Uart5Fd, ADDR_FAN, &ver) == PASS) {
+        // FanModuleData
+        strcpy((char *) ShmFanModuleData->version, ver.Version_FW);
+        // SystemInfo
+        strcpy((char *) ShmSysConfigAndInfo->SysInfo.FanModuleFwRev, ver.Version_FW);
+        //log_info("GetFwAndHwVersion_Fan s1 = %s \n", ver.Version_FW);
+    }
+
+    if (Query_HW_Ver(Uart5Fd, ADDR_FAN, &ver) == PASS) {
+        // SystemInfo
+        strcpy((char *) ShmSysConfigAndInfo->SysInfo.FanModuleHwRev, ver.Version_FW);
+        //log_info("GetFwAndHwVersion_Fan s2 = %s \n", ver.Version_HW);
+    }
+}
+
+void GetFwAndHwVersion_Relay()
+{
+    if (Query_FW_Ver(Uart5Fd, ADDR_RELAY, &ver) == PASS) {
+        // RelayModuleData
+        strcpy((char *) ShmRelayModuleData->version, ver.Version_FW);
+        // SystemInfo
+        strcpy((char *) ShmSysConfigAndInfo->SysInfo.RelayModuleFwRev, ver.Version_FW);
+        //log_info("GetFwAndHwVersion_Relay s1 = %s \n", ver.Version_FW);
+    }
+
+    if (Query_HW_Ver(Uart5Fd, ADDR_RELAY, &ver) == PASS) {
+        // SystemInfo
+        strcpy((char *) ShmSysConfigAndInfo->SysInfo.RelayModuleHwRev, ver.Version_FW);
+        //log_info("GetFwAndHwVersion_Relay s2 = %s \n", ver.Version_HW);
+    }
+}
+
+void GetFwAndHwVersion_Led()
+{
+    if (Query_FW_Ver(Uart5Fd, ADDR_LED, &ver) == PASS) {
+        // LedModuleData
+        strcpy((char *) ShmLedModuleData->version, ver.Version_FW);
+        // SystemInfo
+        strcpy((char *) ShmSysConfigAndInfo->SysInfo.LedModuleFwRev, ver.Version_FW);
+        //log_info("GetFwAndHwVersion_Led s1 = %s \n", ver.Version_FW);
+        ShmLedModuleData->SelfTest_Comp = YES;
+    } else {
+        //log_info("GetFwAndHwVersion_Led fail \n");
+    }
+
+//  if (Query_HW_Ver(Uart5Fd, ADDR_LED, &ver) == PASS)
+//  {
+//      // SystemInfo
+//      strcpy((char *) ShmSysConfigAndInfo->SysInfo.RelayModuleHwRev, ver.Version_FW);
+//      //log_info("GetFwAndHwVersion_Relay s2 = %s \n", ver.Version_HW);
+//  }
+}
+
+void GetFwVersion_AC()
+{
+    if (Query_FW_Ver(Uart5Fd, ADDR_AC_PLUG, &ver) == PASS) {
+        ac_chargingInfo[0]->SelfTest_Comp = YES;
+        strcpy((char *) ac_chargingInfo[0]->version, ver.Version_FW);
+    }
+}
+
+void GetAcModelName()
+{
+    memset(ShmSysConfigAndInfo->SysConfig.AcModelName, 0x00, sizeof(ShmSysConfigAndInfo->SysConfig.AcModelName));
+    if (Query_Model_Name(Uart5Fd, ADDR_AC_PLUG, ShmSysConfigAndInfo->SysConfig.AcModelName) == PASS) {
+        log_info("ac model name = %s \n", ShmSysConfigAndInfo->SysConfig.AcModelName);
+    }
+}
+
+void SetRtcData_Relay()
+{
+    struct timeb csuTime;
+    struct tm *tmCSU;
+
+    ftime(&csuTime);
+    tmCSU = localtime(&csuTime.time);
+    //  log_info("Time : %04d-%02d-%02d %02d:%02d:%02d \n", tmCSU->tm_year + 1900,
+    //          tmCSU->tm_mon + 1, tmCSU->tm_mday, tmCSU->tm_hour, tmCSU->tm_min,
+    //          tmCSU->tm_sec);
+
+    rtc.RtcData[0] = '0' + (tmCSU->tm_year + 1900) / 1000 % 10;
+    rtc.RtcData[1] = '0' + (tmCSU->tm_year + 1900) / 100 % 10;
+    rtc.RtcData[2] = '0' + (tmCSU->tm_year + 1900) / 10 % 10;
+    rtc.RtcData[3] = '0' + (tmCSU->tm_year + 1900) / 1 % 10;
+
+    rtc.RtcData[4] = '0' + (tmCSU->tm_mon + 1) / 10 % 10;
+    rtc.RtcData[5] = '0' + (tmCSU->tm_mon + 1) / 1 % 10;
+
+    rtc.RtcData[6] = '0' + (tmCSU->tm_mday) / 10 % 10;
+    rtc.RtcData[7] = '0' + (tmCSU->tm_mday) / 1 % 10;
+
+    rtc.RtcData[8] = '0' + (tmCSU->tm_hour) / 10 % 10;
+    rtc.RtcData[9] = '0' + (tmCSU->tm_hour) / 1 % 10;
+
+    rtc.RtcData[10] = '0' + (tmCSU->tm_min) / 10 % 10;
+    rtc.RtcData[11] = '0' + (tmCSU->tm_min) / 1 % 10;
+
+    rtc.RtcData[12] = '0' + (tmCSU->tm_sec) / 10 % 10;
+    rtc.RtcData[13] = '0' + (tmCSU->tm_sec) / 1 % 10;
+
+    if (Config_Rtc_Data(Uart5Fd, ADDR_RELAY, &rtc) == PASS) {
+        //log_info("SetRtc (RB) sucessfully. \n");
+    }
+}
+
+void SetModelName_Relay()
+{
+    if (Config_Model_Name(Uart5Fd, ADDR_RELAY, ShmSysConfigAndInfo->SysConfig.ModelName) == PASS) {
+        //log_info("Set Model name (RB) PASS = %s \n", ShmSysConfigAndInfo->SysConfig.ModelName);
+    }
+}
+
+void SetRtcData_Fan()
+{
+    struct timeb csuTime;
+    struct tm *tmCSU;
+
+    ftime(&csuTime);
+    tmCSU = localtime(&csuTime.time);
+    //  log_info("Time : %04d-%02d-%02d %02d:%02d:%02d \n", tmCSU->tm_year + 1900,
+    //          tmCSU->tm_mon + 1, tmCSU->tm_mday, tmCSU->tm_hour, tmCSU->tm_min,
+    //          tmCSU->tm_sec);
+
+    rtc.RtcData[0] = '0' + (tmCSU->tm_year + 1900) / 1000 % 10;
+    rtc.RtcData[1] = '0' + (tmCSU->tm_year + 1900) / 100 % 10;
+    rtc.RtcData[2] = '0' + (tmCSU->tm_year + 1900) / 10 % 10;
+    rtc.RtcData[3] = '0' + (tmCSU->tm_year + 1900) / 1 % 10;
+
+    rtc.RtcData[4] = '0' + (tmCSU->tm_mon + 1) / 10 % 10;
+    rtc.RtcData[5] = '0' + (tmCSU->tm_mon + 1) / 1 % 10;
+
+    rtc.RtcData[6] = '0' + (tmCSU->tm_mday) / 10 % 10;
+    rtc.RtcData[7] = '0' + (tmCSU->tm_mday) / 1 % 10;
+
+    rtc.RtcData[8] = '0' + (tmCSU->tm_hour) / 10 % 10;
+    rtc.RtcData[9] = '0' + (tmCSU->tm_hour) / 1 % 10;
+
+    rtc.RtcData[10] = '0' + (tmCSU->tm_min) / 10 % 10;
+    rtc.RtcData[11] = '0' + (tmCSU->tm_min) / 1 % 10;
+
+    rtc.RtcData[12] = '0' + (tmCSU->tm_sec) / 10 % 10;
+    rtc.RtcData[13] = '0' + (tmCSU->tm_sec) / 1 % 10;
+
+    if (Config_Rtc_Data(Uart5Fd, ADDR_FAN, &rtc) == PASS) {
+        //log_info("SetRtc (FB) sucessfully. \n");
+    }
+}
+
+void SetModelName_Fan()
+{
+    if (Config_Model_Name(Uart5Fd, ADDR_FAN, ShmSysConfigAndInfo->SysConfig.ModelName) == PASS) {
+        log_info("Set Model name PASS = %s \n", ShmSysConfigAndInfo->SysConfig.ModelName);
+    }
+}
+
+// AC 三相輸入電壓
+void GetPresentInputVol(void)
+{
+    if (Query_Present_InputVoltage(Uart5Fd, ADDR_RELAY, &inputVoltage) == PASS) {
+        // resolution : 0.1
+        ShmSysConfigAndInfo->SysInfo.InputVoltageR = ShmRelayModuleData->InputL1Volt = inputVoltage.L1N_L12;
+        ShmSysConfigAndInfo->SysInfo.InputVoltageS = ShmRelayModuleData->InputL2Volt = inputVoltage.L2N_L23;
+        ShmSysConfigAndInfo->SysInfo.InputVoltageT = ShmRelayModuleData->InputL3Volt = inputVoltage.L3N_L31;
+
+        //********************************************************************************************************//
+        // Vin (UVP)
+        if (ShmSysConfigAndInfo->SysInfo.ChargerType == _CHARGER_TYPE_IEC) {
+            if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputUVP == NO) {
+                if (inputVoltage.L1N_L12 < VIN_MIN_VOLTAGE_IEC) {
+                    log_info("In Uvp L1N_L12 = %f \n", inputVoltage.L1N_L12);
+                    if (_threePhaseUvp[0] >= OVP_UVP_CHK_COUNT) {
+                        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputUVP = YES;
+                    } else {
+                        _threePhaseUvp[0] += 1;
+                    }
+                }
+            } else {
+                if (inputVoltage.L1N_L12 > VIN_MIN_REV_VOLTAGE_IEC) {
+                    ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputUVP = NO;
+                    _threePhaseUvp[0] = 0;
+                }
+            }
+
+            if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL2InputUVP == NO) {
+                if (inputVoltage.L2N_L23 < VIN_MIN_VOLTAGE_IEC) {
+                    log_info("In Uvp L2N_L23 = %f \n", inputVoltage.L2N_L23);
+                    if (_threePhaseUvp[1] >= OVP_UVP_CHK_COUNT) {
+                        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL2InputUVP = YES;
+                    } else {
+                        _threePhaseUvp[1] += 1;
+                    }
+                }
+            } else {
+                if (inputVoltage.L2N_L23 > VIN_MIN_REV_VOLTAGE_IEC) {
+                    ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL2InputUVP = NO;
+                    _threePhaseUvp[1] = 0;
+                }
+            }
+
+            if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL3InputUVP == NO) {
+                if (inputVoltage.L3N_L31 < VIN_MIN_VOLTAGE_IEC) {
+                    log_info("In Uvp L3N_L31 = %f \n", inputVoltage.L3N_L31);
+                    if (_threePhaseUvp[2] >= OVP_UVP_CHK_COUNT) {
+                        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL3InputUVP = YES;
+                    } else {
+                        _threePhaseUvp[2] += 1;
+                    }
+                }
+            } else {
+                if (inputVoltage.L3N_L31 > VIN_MIN_REV_VOLTAGE_IEC) {
+                    ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL3InputUVP = NO;
+                    _threePhaseUvp[2] = 0;
+                }
+            }
+        } else if (ShmSysConfigAndInfo->SysInfo.ChargerType == _CHARGER_TYPE_UL) {
+            if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputUVP == NO) {
+                if (inputVoltage.L1N_L12 < VIN_MIN_VOLTAGE_UL) {
+                    log_info("In Uvp L1N_L12 = %f \n", inputVoltage.L1N_L12);
+                    if (_threePhaseUvp[0] >= OVP_UVP_CHK_COUNT) {
+                        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputUVP = YES;
+                    } else {
+                        _threePhaseUvp[0] += 1;
+                    }
+                }
+            } else {
+                if (inputVoltage.L1N_L12 > VIN_MIN_REV_VOLTAGE_UL) {
+                    ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputUVP = NO;
+                    _threePhaseUvp[0] = 0;
+                }
+            }
+
+            if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL2InputUVP == NO) {
+                if (inputVoltage.L2N_L23 < VIN_MIN_VOLTAGE_UL) {
+                    log_info("In Uvp L2N_L23 = %f \n", inputVoltage.L2N_L23);
+                    if (_threePhaseUvp[1] >= OVP_UVP_CHK_COUNT) {
+                        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL2InputUVP = YES;
+                    } else {
+                        _threePhaseUvp[1] += 1;
+                    }
+                }
+            } else {
+                if (inputVoltage.L2N_L23 > VIN_MIN_REV_VOLTAGE_UL) {
+                    ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL2InputUVP = NO;
+                    _threePhaseUvp[1] = 0;
+                }
+            }
+
+            if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL3InputUVP == NO) {
+                if (inputVoltage.L3N_L31 < VIN_MIN_VOLTAGE_UL) {
+                    log_info("In Uvp L3N_L31 = %f \n", inputVoltage.L3N_L31);
+                    if (_threePhaseUvp[2] >= OVP_UVP_CHK_COUNT) {
+                        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL3InputUVP = YES;
+                    } else {
+                        _threePhaseUvp[2] += 1;
+                    }
+                }
+            } else {
+                if (inputVoltage.L3N_L31 > VIN_MIN_REV_VOLTAGE_UL) {
+                    ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL3InputUVP = NO;
+                    _threePhaseUvp[2] = 0;
+                }
+            }
+        }
+
+        //********************************************************************************************************//
+        // Vin (OVP)
+        if (ShmSysConfigAndInfo->SysInfo.ChargerType == _CHARGER_TYPE_IEC) {
+            if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputOVP == NO) {
+                if (inputVoltage.L1N_L12 > VIN_MAX_VOLTAGE_IEC) {
+                    log_info("In Ovp L1N_L12 = %f \n", inputVoltage.L1N_L12);
+                    if (_threePhaseOvp[0] >= OVP_UVP_CHK_COUNT) {
+                        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputOVP = YES;
+                    } else {
+                        _threePhaseOvp[0] += 1;
+                    }
+                }
+            } else {
+                if (inputVoltage.L1N_L12 < VIN_MAX_REV_VOLTAGE_IEC) {
+                    ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputOVP = NO;
+                    _threePhaseOvp[0] = 0;
+                }
+            }
+
+            if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL2InputOVP == NO) {
+                if (inputVoltage.L2N_L23 > VIN_MAX_VOLTAGE_IEC) {
+                    log_info("In Ovp L2N_L23 = %f \n", inputVoltage.L2N_L23);
+                    if (_threePhaseOvp[1] >= OVP_UVP_CHK_COUNT) {
+                        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL2InputOVP = YES;
+                    } else {
+                        _threePhaseOvp[1] += 1;
+                    }
+                }
+            } else {
+                if (inputVoltage.L2N_L23 < VIN_MAX_REV_VOLTAGE_IEC) {
+                    ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL2InputOVP = NO;
+                    _threePhaseOvp[1] = 0;
+                }
+            }
+
+            if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL3InputOVP == NO) {
+                if (inputVoltage.L3N_L31 > VIN_MAX_VOLTAGE_IEC) {
+                    log_info("In Ovp L3N_L31 = %f \n", inputVoltage.L3N_L31);
+                    if (_threePhaseOvp[2] >= OVP_UVP_CHK_COUNT) {
+                        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL3InputOVP = YES;
+                    } else {
+                        _threePhaseOvp[2] += 1;
+                    }
+                }
+            } else {
+                if (inputVoltage.L3N_L31 < VIN_MAX_REV_VOLTAGE_IEC) {
+                    ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL3InputOVP = NO;
+                    _threePhaseOvp[2] = 0;
+                }
+            }
+        } else if (ShmSysConfigAndInfo->SysInfo.ChargerType == _CHARGER_TYPE_UL) {
+            if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputOVP == NO) {
+                if (inputVoltage.L1N_L12 > VIN_MAX_VOLTAGE_UL) {
+                    log_info("In Ovp L1N_L12 = %f \n", inputVoltage.L1N_L12);
+                    if (_threePhaseOvp[0] >= OVP_UVP_CHK_COUNT) {
+                        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputOVP = YES;
+                    } else {
+                        _threePhaseOvp[0] += 0;
+                    }
+                }
+            } else {
+                if (inputVoltage.L1N_L12 < VIN_MAX_REV_VOLTAGE_UL) {
+                    ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputOVP = NO;
+                    _threePhaseOvp[0] = 0;
+                }
+            }
+
+            if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL2InputOVP == NO) {
+                if (inputVoltage.L2N_L23 > VIN_MAX_VOLTAGE_UL) {
+                    log_info("In Ovp L2N_L23 = %f \n", inputVoltage.L2N_L23);
+                    if (_threePhaseOvp[1] >= OVP_UVP_CHK_COUNT) {
+                        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL2InputOVP = YES;
+                    } else {
+                        _threePhaseOvp[1] += 0;
+                    }
+                }
+            } else {
+                if (inputVoltage.L2N_L23 < VIN_MAX_REV_VOLTAGE_UL) {
+                    ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL2InputOVP = NO;
+                    _threePhaseOvp[1] = 0;
+                }
+            }
+
+            if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL2InputOVP == NO) {
+                if (inputVoltage.L3N_L31 > VIN_MAX_VOLTAGE_UL) {
+                    log_info("In Ovp L3N_L31 = %f \n", inputVoltage.L3N_L31);
+                    if (_threePhaseOvp[2] >= OVP_UVP_CHK_COUNT) {
+                        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL3InputOVP = YES;
+                    } else {
+                        _threePhaseOvp[2] += 1;
+                    }
+                }
+            } else {
+                if (inputVoltage.L3N_L31 < VIN_MAX_REV_VOLTAGE_UL) {
+                    ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL3InputOVP = NO;
+                    _threePhaseOvp[2] = 0;
+                }
+            }
+        }
+    }
+}
+
+// 左右槍的 Relay 前後的輸出電壓
+void GetPersentOutputVol(void)
+{
+    uint8_t index = 0;
+    uint8_t targetID = 0;
+
+    if (Query_Present_OutputVoltage(Uart5Fd, ADDR_RELAY, &outputVoltage) != PASS) {
+        return;
+    }
+
+    //log_info("Conn1 fuse 1 = %f \n", outputVoltage.behindFuse_Voltage_C1);
+    //log_info("Conn1 relay 1 = %f \n", outputVoltage.behindRelay_Voltage_C1);
+    //log_info("Conn2 fuse 2 = %f \n", outputVoltage.behindFuse_Voltage_C2);
+    //log_info("Conn2 relay 2 = %f \n", outputVoltage.behindRelay_Voltage_C2);
+
+    //log_info("outputVoltage.behindFuse_Voltage_C1 = %f \n", outputVoltage.behindFuse_Voltage_C1);
+    //log_info("outputVoltage.behindFuse_Voltage_C2 = %f \n", outputVoltage.behindFuse_Voltage_C2);
+
+    ShmRelayModuleData->Gun1FuseOutputVolt = outputVoltage.behindFuse_Voltage_C1;
+    ShmRelayModuleData->Gun1RelayOutputVolt = outputVoltage.behindRelay_Voltage_C1;
+    ShmRelayModuleData->Gun2FuseOutputVolt = outputVoltage.behindFuse_Voltage_C2;
+    ShmRelayModuleData->Gun2RelayOutputVolt = outputVoltage.behindRelay_Voltage_C2;
+
+    for (index = 0; index < gunCount; index++) {
+        targetID = getCommTargetID(index);
+
+        switch (targetID) {
+        case 0x01:
+#if defined DD360Tcci || defined DD360Audi || defined DD360ComBox
+            _chargingData[index]->FireChargingVoltage = ShmRelayModuleData->Gun1RelayOutputVolt;
+            _chargingData[index]->PresentChargingCurrent = ShmRelayModuleData->Gun1FuseOutputVolt / 10;
+            _chargingData[index]->PresentChargingVoltage = _chargingData[index]->FireChargingVoltage / 10;
+            _chargingData[index]->FuseChargingVoltage = _chargingData[index]->FireChargingVoltage;
+            break;
+#endif //defined DD360Tcci || defined DD360Audi || defined DD360ComBox
+
+            _chargingData[index]->FireChargingVoltage = ShmRelayModuleData->Gun1RelayOutputVolt;
+            _chargingData[index]->FuseChargingVoltage = ShmRelayModuleData->Gun1FuseOutputVolt;
+            break;
+
+        case 0x02:
+#if defined DD360Tcci || defined DD360Audi || defined DD360ComBox
+            _chargingData[index]->FireChargingVoltage = ShmRelayModuleData->Gun2RelayOutputVolt;
+            _chargingData[index]->PresentChargingCurrent = ShmRelayModuleData->Gun2FuseOutputVolt / 10;
+            _chargingData[index]->PresentChargingVoltage = _chargingData[index]->FireChargingVoltage / 10;
+            _chargingData[index]->FuseChargingVoltage = _chargingData[index]->FireChargingVoltage;
+            break;
+#endif //defined DD360Tcci || defined DD360Audi || defined DD360ComBox
+
+            _chargingData[index]->FireChargingVoltage = ShmRelayModuleData->Gun2RelayOutputVolt;
+            _chargingData[index]->FuseChargingVoltage = ShmRelayModuleData->Gun2FuseOutputVolt;
+            break;
+        }
+
+        //unsigned short Ovp = 0;
+        //unsigned short Ocp = 0;
+        //Ovp = MIN [VOUT_MAX_VOLTAGE, EV_BATTERY_VOLTAGE]  // 最大輸出電壓與電池電壓最大值
+        //Ocp = MIN [IOUT_MAX_CURRENT, EV_CURRENT_REQ]      // 最大輸出電流與需求電流最小值
+        //if (_chargingData[index]->Type == _Type_Chademo) {
+        //    //Ovp = MaxValue(_chargingData[index]->MaximumChargingVoltage, _chargingData[index]->EvBatteryMaxVoltage);
+        //    //Ocp = MaxValue(_chargingData[index]->PresentChargingCurrent, ShmCHAdeMOData->ev[_chargingData[index]->type_index].ChargingCurrentRequest);
+        //} else if (_chargingData[index]->Type == _Type_CCS_2) {
+        //}
+    }
+}
+
+// 風扇速度
+void GetFanSpeed()
+{
+    //log_info("Get fan board speed \n");
+    if (Query_Fan_Speed(Uart5Fd, ADDR_FAN, &fanSpeed) == PASS) {
+        ShmFanModuleData->PresentFan1Speed = fanSpeed.speed[0];
+        ShmFanModuleData->PresentFan2Speed = fanSpeed.speed[1];
+        ShmFanModuleData->PresentFan3Speed = fanSpeed.speed[2];
+        ShmFanModuleData->PresentFan4Speed = fanSpeed.speed[3];
+//      log_info("SystemFanRotaSpeed_1 = %d \n", fanSpeed.speed[0]);
+//      log_info("SystemFanRotaSpeed_2 = %d \n", fanSpeed.speed[1]);
+//      log_info("SystemFanRotaSpeed_3 = %d \n", fanSpeed.speed[2]);
+//      log_info("SystemFanRotaSpeed_4 = %d \n", fanSpeed.speed[3]);
+        // Config_Fan_Speed(Uart5Fd, ADDR_FAN, &fanSpeed[0]);
+        //SysInfoData (SystemFanRotaSpeed)
+    }
+}
+
+// 讀取 Relay 狀態
+void GetRelayOutputStatus(void)
+{
+    if (Query_Relay_Output(Uart5Fd, ADDR_RELAY, &regRelay) == PASS) {
+#if !defined DD360Tcci && !defined DD360Audi && !defined DD360ComBox
+        regRelay.relay_event.bits.AC_Contactor = ShmSysConfigAndInfo->SysInfo.AcContactorStatus;
+#endif //!defined DD360Tcci && !defined DD360Audi
+    }
+}
+
+// 確認 K1 K2 relay 的狀態
+void CheckK1K2RelayOutput(uint8_t index)
+{
+    uint8_t targetID = 0;
+
+    targetID = getCommTargetID(index);
+
+    switch (targetID) {
+    case 0x01:
+        if (regRelay.relay_event.bits.Gun1_N == YES && regRelay.relay_event.bits.Gun1_P == YES) {
+            _chargingData[index]->RelayK1K2Status = YES;
+        } else {
+            _chargingData[index]->RelayK1K2Status = NO;
+        }
+
+        if (_chargingData[index]->Type == _Type_CCS_2) {
+#if !defined DD360Tcci && !defined DD360Audi && !defined DD360ComBox
+            if (regRelay.relay_event.bits.Gun1_N == YES && regRelay.relay_event.bits.CCS_Precharge == YES) {
+                _chargingData[index]->RelayKPK2Status = YES;
+            } else {
+                _chargingData[index]->RelayKPK2Status = NO;
+            }
+#else
+            if (_chargingData[index]->SystemStatus == S_CCS_PRECHARGE_ST0) {
+                _chargingData[index]->RelayKPK2Status = YES;
+            } else {
+                _chargingData[index]->RelayKPK2Status = NO;
+            }
+#endif //!defined DD360Tcci && !defined DD360Audi
+        }
+        break;
+
+    case 0x02:
+        if (regRelay.relay_event.bits.Gun2_N == YES &&
+                regRelay.relay_event.bits.Gun2_P == YES) {
+            _chargingData[index]->RelayK1K2Status = YES;
+        } else {
+            _chargingData[index]->RelayK1K2Status = NO;
+        }
+
+        if (_chargingData[index]->Type == _Type_CCS_2) {
+#if !defined DD360Tcci && !defined DD360Audi && !defined DD360ComBox
+            if (regRelay.relay_event.bits.Gun2_N == YES &&
+                    regRelay.relay_event.bits.CCS_Precharge == YES) {
+                _chargingData[index]->RelayKPK2Status = YES;
+            } else {
+                _chargingData[index]->RelayKPK2Status = NO;
+            }
+#else
+            if (_chargingData[index]->SystemStatus == S_CCS_PRECHARGE_ST0) {
+                _chargingData[index]->RelayKPK2Status = YES;
+            } else {
+                _chargingData[index]->RelayKPK2Status = NO;
+            }
+#endif //!defined DD360Tcci && !defined DD360Audi
+        }
+        break;
+    }
+
+#if !defined DD360Tcci && !defined DD360Audi && !defined DD360ComBox
+    //DS60-120 add
+    if (ShmSysConfigAndInfo->SysInfo.BridgeRelayStatus == YES) {
+        if (regRelay.relay_event.bits.Gun1_Parallel_N == NO &&
+                regRelay.relay_event.bits.Gun1_Parallel_P == NO) {
+            ShmSysConfigAndInfo->SysInfo.BridgeRelayStatus = NO;
+        }
+    } else if (ShmSysConfigAndInfo->SysInfo.BridgeRelayStatus == NO) {
+        if (regRelay.relay_event.bits.Gun1_Parallel_N == YES &&
+                regRelay.relay_event.bits.Gun1_Parallel_P == YES) {
+            ShmSysConfigAndInfo->SysInfo.BridgeRelayStatus = YES;
+        }
+    }
+#else
+    ShmSysConfigAndInfo->SysInfo.BridgeRelayStatus = YES;
+#endif //!defined DD360Tcci && !defined DD360Audi
+}
+
+void GetGfdAdc()
+{
+    int gunIndex = 0;
+    uint8_t targetID = 0;
+
+    // define : 每 0.2 ~ 1 秒一次
+    // occur : <= 75k 歐姆 @ 150 - 750 Vdc
+    // warning : >= 100 歐姆 && <= 500 歐姆 @ 150-750 Vdc
+    if (Query_Gfd_Adc(Uart5Fd, ADDR_RELAY, &gfd_adc) == PASS) {
+        for (gunIndex = 0; gunIndex < gunCount; gunIndex++) {
+            if (_chargingData[gunIndex]->Type == 0x09 &&
+                    !ShmSysConfigAndInfo->SysConfig.AlwaysGfdFlag
+               ) {
+                if ((_chargingData[gunIndex]->PresentChargingVoltage * 10) >= VOUT_MIN_VOLTAGE) {
+                    _chargingData[gunIndex]->GroundFaultStatus = GFD_PASS;
+                }
+                continue;
+            }
+
+            targetID = getCommTargetID(gunIndex);
+
+            if (targetID == 0x01) {
+                if (gfd_adc.result_conn1 == GFD_WARNING) {
+                    gfd_adc.result_conn1 = GFD_PASS;
+                }
+
+                _chargingData[gunIndex]->GroundFaultStatus = gfd_adc.result_conn1;
+                //log_info("GFD ******** Result = %d, Step = %d, R = %d, Vol = %d \n",
+                //            _chargingData[gunIndex]->GroundFaultStatus,
+                //            gfd_adc.rb_step_1,
+                //            gfd_adc.Resister_conn1,
+                //            gfd_adc.voltage_conn1);
+                if (_chargingData[gunIndex]->GroundFaultStatus == GFD_FAIL) {
+                    log_info("GFD Fail. index = %d, Step = %d, R = %d, Vol = %d \n",
+                             gunIndex,
+                             gfd_adc.rb_step_1,
+                             gfd_adc.Resister_conn1,
+                             gfd_adc.voltage_conn1);
+
+                } else if (_chargingData[gunIndex]->GroundFaultStatus == GFD_PASS ||
+                           _chargingData[gunIndex]->GroundFaultStatus == GFD_WARNING
+                          ) {
+                    if (_chargingData[gunIndex]->GroundFaultStatus == GFD_WARNING) {
+                        log_info("GFD Warning. index = %d, Result = %d, R = %d, Vol = %d \n",
+                                 gunIndex,
+                                 _chargingData[gunIndex]->GroundFaultStatus,
+                                 gfd_adc.Resister_conn1,
+                                 gfd_adc.voltage_conn1);
+                    }
+                }
+            } else if (targetID == 0x02) {
+                if (gfd_adc.result_conn2 == GFD_WARNING) {
+                    gfd_adc.result_conn2 = GFD_PASS;
+                }
+                _chargingData[gunIndex]->GroundFaultStatus = gfd_adc.result_conn2;
+                if (_chargingData[gunIndex]->GroundFaultStatus == GFD_FAIL) {
+                    log_info("GFD Fail. index = %d, Step = %d, R = %d, Vol = %d \n",
+                             gunIndex,
+                             gfd_adc.rb_step_2,
+                             gfd_adc.Resister_conn2,
+                             gfd_adc.voltage_conn2);
+                } else if (_chargingData[gunIndex]->GroundFaultStatus == GFD_PASS ||
+                           _chargingData[gunIndex]->GroundFaultStatus == GFD_WARNING
+                          ) {
+                    if (_chargingData[gunIndex]->GroundFaultStatus == GFD_WARNING) {
+                        log_info("GFD Warning. index = %d, Result = %d, R = %d, Vol = %d \n",
+                                 gunIndex,
+                                 _chargingData[gunIndex]->GroundFaultStatus,
+                                 gfd_adc.Resister_conn1,
+                                 gfd_adc.voltage_conn1);
+                    }
+                }
+            }
+        }
+    }
+}
+
+void GetGpioInput()
+{
+    if (Query_Gpio_Input(Uart5Fd, ADDR_AUX, &gpio_in) == PASS) {
+        // AC Contactor Status
+        if (gpio_in.AC_MainBreaker == 1) {
+            // AC Main Breaker ON
+            log_info("RB AC Main Breaker. \n");
+        }
+
+        if (gpio_in.SPD == 1) {
+            // SPD (雷擊保護) ON
+            log_info("RB SPD. \n");
+        }
+
+        if (gpio_in.Door_Open == 1) {
+            // Door Open
+            log_info("RB Door Open. \n");
+        }
+
+        if (gpio_in.GFD[0] == 1) {
+            // GFD_1 Trigger
+        }
+
+        if (gpio_in.GFD[1] == 1) {
+            // GFD_2 Trigger
+        }
+
+        if (gpio_in.AC_Drop == 1) {
+            // AC Drop
+            log_info("RB AC Drop. \n");
+        }
+
+        if (gpio_in.Emergency_IO == 1) {
+            // Emergency IO ON
+            log_info("RB Emergency IO ON. \n");
+        }
+
+        if (gpio_in.Button_Emergency_Press == 1) {
+            // Emergency button Press
+        }
+
+        if (gpio_in.Button_On_Press == 1) {
+            // On button Press
+        }
+
+        if (gpio_in.Button_Off_Press == 1) {
+            // Off button Press
+        }
+
+        if (gpio_in.Key_1_Press == 1) {
+            // key 1 press
+        }
+
+        if (gpio_in.Key_2_Press == 1) {
+            // key 2 press
+        }
+
+        if (gpio_in.Key_3_Press == 1) {
+            // key 3 press
+        }
+
+        if (gpio_in.Key_4_Press == 1) {
+            // key 4 press
+        }
+    }
+}
+
+// 5V 12V 24V 48V
+void GetAuxPower()
+{
+    if (Query_Aux_PowerVoltage(Uart5Fd, ADDR_FAN, &auxPower) == PASS) {
+        ShmSysConfigAndInfo->SysInfo.AuxPower48V = auxPower.voltage[0];
+        ShmSysConfigAndInfo->SysInfo.AuxPower24V = auxPower.voltage[1];
+        //ShmSysConfigAndInfo->SysInfo.AuxPower12V = auxPower.voltage[4];
+        //ShmSysConfigAndInfo->SysInfo.AuxPower5V = auxPower.voltage[6];
+        // aux power voltage
+        //log_info("aux1 = %x, \n", auxPower.voltage[0]);
+        //log_info("aux2 = %x, \n", auxPower.voltage[1]);
+    }
+}
+
+void SetFanModuleSpeed()
+{
+    {
+        FanSpeed _fanSpeed;
+
+        _setFanSpeed += fanSpeedSmoothValue;
+
+        if (_setFanSpeed >= ShmFanModuleData->SetFan1Speed) {
+            _setFanSpeed = ShmFanModuleData->SetFan1Speed;
+        }
+
+        //printf("_setFanSpeed = %d \n", _setFanSpeed);
+        _fanSpeed.speed[0] = _setFanSpeed;
+
+        _fanSpeed.speed[1] = _setFanSpeed;
+
+        _fanSpeed.speed[2] = _setFanSpeed;
+
+        _fanSpeed.speed[3] = _setFanSpeed;
+
+        if (Config_Fan_Speed(Uart5Fd, ADDR_FAN, &_fanSpeed) == PASS) {
+            //log_info("successfully Fan\n");
+        }
+    }
+}
+
+//==========================================
+// Common Function
+//==========================================
+void SetK1K2RelayStatus(uint8_t index)
+{
+    uint8_t targetID = 0;
+    PreChargingState *pRegPreChargingState = NULL;
+    PreChargingState *pOutputPreChargingState = NULL;
+    GunPNState *pRegGunPNState = NULL;
+    GunPNState *pOutputGunPNState = NULL;
+    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)_chargingData[index];
+
+    if (ShmPsuData->Work_Step >= _TEST_MODE && ShmPsuData->Work_Step <= _TEST_MODE) {
+        if (regRelay.relay_event.bits.Gun1_N == NO) {
+            outputRelay.relay_event.bits.Gun1_N = YES;
+        } else if (regRelay.relay_event.bits.Gun1_P == NO) {
+            outputRelay.relay_event.bits.Gun1_P = YES;
+        }
+        return;
+    }
+
+    targetID = getCommTargetID(index);
+
+    pRegPreChargingState = (PreChargingState *)&regRelay.relay_event.relay_status[0];
+    pOutputPreChargingState = (PreChargingState *)&outputRelay.relay_event.relay_status[0];
+    if (targetID == 0x01) {
+        pRegGunPNState = (GunPNState *)&regRelay.relay_event.relay_status[1];
+        pOutputGunPNState = (GunPNState *)&outputRelay.relay_event.relay_status[1];
+    } else if (targetID == 0x02) {
+        pRegGunPNState = (GunPNState *)&regRelay.relay_event.relay_status[2];
+        pOutputGunPNState = (GunPNState *)&outputRelay.relay_event.relay_status[2];
+    }
+
+    switch (pDcChargingInfo->SystemStatus) {
+    case S_BOOTING:
+    case S_IDLE:
+    case S_AUTHORIZING:
+    case S_REASSIGN_CHECK:
+    case S_REASSIGN:
+    case S_PREPARNING:
+    case S_PREPARING_FOR_EV:
+        if (pRegGunPNState->GunP == YES) {
+            pOutputGunPNState->GunP = NO;
+        } else if (pRegGunPNState->GunN == YES) {
+            pOutputGunPNState->GunN = NO;
+        }
+
+        if (targetID == 0x02 && pDcChargingInfo->Type == _Type_CCS_2) {
+            if (pRegPreChargingState->CcsPrecharge == YES) {
+                pOutputPreChargingState->CcsPrecharge = NO;
+            }
+        }
+        break;
+
+    case S_PREPARING_FOR_EVSE:
+    case S_CHARGING:
+        //if (pDcChargingInfo->RelayWeldingCheck != YES) {
+        //    break;
+        //}
+
+        if (pRegGunPNState->GunN == NO) {
+            pOutputGunPNState->GunN = YES;
+        } else if (pRegGunPNState->GunP == NO) {
+            pOutputGunPNState->GunP = YES;
+        }
+        break;
+
+    case S_TERMINATING:
+    case S_COMPLETE:
+    case S_ALARM:
+        if ((pDcChargingInfo->PresentChargingCurrent * 10) <= SEFETY_SWITCH_RELAY_CUR) {
+            if (pRegGunPNState->GunP == YES) {
+                pOutputGunPNState->GunP = NO;
+            } else if (pRegGunPNState->GunN == YES) {
+                pOutputGunPNState->GunN = NO;
+            }
+        }
+        break;
+
+    case S_CCS_PRECHARGE_ST0:
+#if defined DD360Tcci || defined DD360Audi || defined DD360ComBox
+        break;
+#endif //defined DD360Tcci || defined DD360Audi || defined DD360ComBox
+
+        if (pDcChargingInfo->Type == _Type_CCS_2 && targetID == 0x02) {
+            if (pRegPreChargingState->CcsPrecharge == NO) {
+                pOutputPreChargingState->CcsPrecharge = YES;
+            } else if (pRegPreChargingState->CcsPrecharge == YES) {
+                pRegGunPNState->GunP = NO;
+            }
+        }
+        break;
+
+    case S_CCS_PRECHARGE_ST1:
+#if defined DD360Tcci || defined DD360Audi || defined DD360ComBox
+        break;
+#endif //defined DD360Tcci || defined DD360Audi || defined DD360ComBox
+
+        if (pDcChargingInfo->Type == _Type_CCS_2 && targetID == 0x02) {
+            if (pRegGunPNState->GunP == NO) {
+                pOutputGunPNState->GunP = YES;
+            } else if (pRegGunPNState->GunP == YES) {
+                pOutputPreChargingState->CcsPrecharge = NO;
+            }
+        }
+        break;
+    }
+}
+
+void CheckAcInputOvpStatus(uint8_t index)
+{
+    if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputOVP == YES ||
+            ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL2InputOVP == YES ||
+            ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL3InputOVP == YES) {
+//      if ((_chargingData[index]->SystemStatus >= S_PREPARNING && _chargingData[index]->SystemStatus <= S_CHARGING) ||
+//              (_chargingData[index]->SystemStatus >= S_CCS_PRECHARGE_ST0 && _chargingData[index]->SystemStatus <= S_CCS_PRECHARGE_ST1))
+//      {
+//          if (ShmSysConfigAndInfo->SysInfo.ChargerType == _CHARGER_TYPE_IEC)
+//          {
+//              if (_psuInputVolR > VIN_MAX_VOLTAGE_IEC ||
+//                      _psuInputVolS > VIN_MAX_VOLTAGE_IEC ||
+//                      _psuInputVolT > VIN_MAX_VOLTAGE_IEC)
+//              {
+//                  log_info("IEC _psuInputVolR = %f, _psuInputVolS = %f, _psuInputVolT = %f \n",
+//                          _psuInputVolR, _psuInputVolS, _psuInputVolT);
+//                  _chargingData[index]->StopChargeFlag = YES;
+//              }
+//
+//          }
+//          else if (ShmSysConfigAndInfo->SysInfo.ChargerType == _CHARGER_TYPE_UL)
+//          {
+//              if (_psuInputVolR > VIN_MAX_VOLTAGE_UL ||
+//                      _psuInputVolS > VIN_MAX_VOLTAGE_UL ||
+//                      _psuInputVolT > VIN_MAX_VOLTAGE_UL)
+//              {
+//                  log_info("UL _psuInputVolR = %f, _psuInputVolS = %f, _psuInputVolT = %f \n",
+//                          _psuInputVolR, _psuInputVolS, _psuInputVolT);
+//                  _chargingData[index]->StopChargeFlag = YES;
+//              }
+//          }
+//      }
+//      else
+        //log_info("CheckAcInputOvpStatus\r\n");
+        _chargingData[index]->StopChargeFlag = YES;
+    }
+}
+
+void CheckPhaseLossStatus(uint8_t index)
+{
+    if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputUVP == YES ||
+            ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL2InputUVP == YES ||
+            ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL3InputUVP == YES) {
+        //log_info("CheckPhaseLossStatus\r\n");
+        _chargingData[index]->StopChargeFlag = YES;
+    }
+}
+
+void SetParalleRelayStatus(void)
+{
+#if defined  DD360Tcci || defined DD360Audi || defined DD360ComBox
+    return;
+#endif //!defined  DD360Tcci || !defined DD360Audi || !defined DD360ComBox
+
+    // 之後雙槍單模機種,橋接都會上
+    if (gunCount >= 2) {
+        if (_chargingData[0]->SystemStatus == S_BOOTING || _chargingData[1]->SystemStatus == S_BOOTING ||
+                (_chargingData[0]->SystemStatus == S_IDLE && _chargingData[1]->SystemStatus == S_IDLE)) {
+            // 初始化~ 不搭橋接
+            if (regRelay.relay_event.bits.Gun1_Parallel_P == YES) {
+                outputRelay.relay_event.bits.Gun1_Parallel_P = NO;
+            } else if (regRelay.relay_event.bits.Gun1_Parallel_N == YES) {
+                outputRelay.relay_event.bits.Gun1_Parallel_N = NO;
+            }
+        } else {
+            if (_chargingData[0]->IsReadyToCharging == YES ||
+                    _chargingData[1]->IsReadyToCharging == YES) {
+                // ************需考慮在切換中 - 切開 relay 與搭回 relay 的時機點************
+                if (ShmSysConfigAndInfo->SysInfo.MainChargingMode == _MAIN_CHARGING_MODE_MAX) {
+                    if (ShmSysConfigAndInfo->SysInfo.ReAssignedFlag < _REASSIGNED_RELAY_M_TO_A) {
+                        // 最大充 - 搭上橋接
+                        if (regRelay.relay_event.bits.Gun1_Parallel_N == NO) {
+                            outputRelay.relay_event.bits.Gun1_Parallel_N = YES;
+                        } else if (regRelay.relay_event.bits.Gun1_Parallel_P == NO) {
+                            outputRelay.relay_event.bits.Gun1_Parallel_P = YES;
+                        }
+                    } else {
+                        // 平均充 - 不搭
+                        if (regRelay.relay_event.bits.Gun1_Parallel_P == YES) {
+                            outputRelay.relay_event.bits.Gun1_Parallel_P = NO;
+                        } else if (regRelay.relay_event.bits.Gun1_Parallel_N == YES) {
+                            outputRelay.relay_event.bits.Gun1_Parallel_N = NO;
+                        }
+                    }
+                } else if (ShmSysConfigAndInfo->SysInfo.MainChargingMode == _MAIN_CHARGING_MODE_AVER) {
+                    if (ShmSysConfigAndInfo->SysInfo.ReAssignedFlag < _REASSIGNED_RELAY_A_TO_M) {
+                        // 平均充 - 不搭
+                        if (regRelay.relay_event.bits.Gun1_Parallel_P == YES) {
+                            outputRelay.relay_event.bits.Gun1_Parallel_P = NO;
+                        } else if (regRelay.relay_event.bits.Gun1_Parallel_N == YES) {
+                            outputRelay.relay_event.bits.Gun1_Parallel_N = NO;
+                        }
+                    } else {
+                        // 最大充 - 搭上橋接
+                        if (regRelay.relay_event.bits.Gun1_Parallel_N == NO) {
+                            outputRelay.relay_event.bits.Gun1_Parallel_N = YES;
+                        } else if (regRelay.relay_event.bits.Gun1_Parallel_P == NO) {
+                            outputRelay.relay_event.bits.Gun1_Parallel_P = YES;
+                        }
+                    }
+                }
+            }
+        }
+    }
+}
+
+void CheckAlarmOccur()
+{
+    bool isErr = false;
+    for (uint8_t count = 0; count < sizeof(_alarm_code) / sizeof(_alarm_code[0]); count++) {
+        if (acAlarmCode.AcAlarmCode & _alarm_code[count]) {
+            isErr = true;
+            switch (_alarm_code[count]) {
+            case AC_OVP: ShmStatusCodeData->AlarmCode.AlarmEvents.bits.AcSystemInputOVP = YES; break;
+            case AC_UVP: ShmStatusCodeData->AlarmCode.AlarmEvents.bits.AcSystemInputUVP = YES; break;
+            case AC_OCP: ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemAcOutputOCP = YES; break;
+            case AC_OTP: ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemAmbientOTP = YES; break;
+            case AC_GMI_FAULT: ShmStatusCodeData->AlarmCode.AlarmEvents.bits.AcGroundfaultFail = YES; break;
+            case AC_CP_ERROR: ShmStatusCodeData->InfoCode.InfoEvents.bits.PilotFault = YES; break;
+            case AC_AC_LEAKAGE: ShmStatusCodeData->AlarmCode.AlarmEvents.bits.RcdTrip = YES; break;
+            case AC_DC_LEAKAGE: ShmStatusCodeData->AlarmCode.AlarmEvents.bits.RcdTrip = YES; break;
+            case AC_SYSTEM_SELFTEST_FAULT: ShmStatusCodeData->AlarmCode.AlarmEvents.bits.McuSelftestFail = YES; break;
+            case AC_HANDSHAKE_TIMEOUT: break;
+            //case AC_EMC_STOP: ShmStatusCodeData->AlarmCode.AlarmEvents.bits.EmergencyStopTrip = YES; break;
+            case AC_RELAY_WELDING: ShmStatusCodeData->FaultCode.FaultEvents.bits.AcOutputRelayWelding = YES; break;
+            case AC_GF_MODULE_FAULT: ShmStatusCodeData->FaultCode.FaultEvents.bits.RcdSelfTestFail = YES; break;
+            case AC_SHUTTER_FAULT: break;
+            case AC_LOCKER_FAULT: ShmStatusCodeData->FaultCode.FaultEvents.bits.AcConnectorLockFail = YES; break;
+            case AC_POWER_DROP: ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputDrop = YES; break;
+            case AC_CIRCUIT_SHORT: ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CircuitShort = YES; break;
+            case AC_ROTARY_SWITCH_FAULT: break;
+            case AC_RELAY_DRIVE_FAULT: ShmStatusCodeData->FaultCode.FaultEvents.bits.AcOutputRelayDrivingFault = YES; break;
+            }
+        } else {
+            switch (_alarm_code[count]) {
+            case AC_OVP: ShmStatusCodeData->AlarmCode.AlarmEvents.bits.AcSystemInputOVP = NO; break;
+            case AC_UVP: ShmStatusCodeData->AlarmCode.AlarmEvents.bits.AcSystemInputUVP = NO; break;
+            case AC_OCP: ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemAcOutputOCP = NO; break;
+            case AC_OTP: ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemAmbientOTP = NO; break;
+            case AC_GMI_FAULT: ShmStatusCodeData->AlarmCode.AlarmEvents.bits.AcGroundfaultFail = NO; break;
+            case AC_CP_ERROR: ShmStatusCodeData->InfoCode.InfoEvents.bits.PilotFault = NO; break;
+            case AC_AC_LEAKAGE: ShmStatusCodeData->AlarmCode.AlarmEvents.bits.RcdTrip = NO; break;
+            case AC_DC_LEAKAGE: ShmStatusCodeData->AlarmCode.AlarmEvents.bits.RcdTrip = NO; break;
+            case AC_SYSTEM_SELFTEST_FAULT: ShmStatusCodeData->AlarmCode.AlarmEvents.bits.McuSelftestFail = NO; break;
+            case AC_HANDSHAKE_TIMEOUT: break;
+            //case AC_EMC_STOP: ShmStatusCodeData->AlarmCode.AlarmEvents.bits.EmergencyStopTrip = NO; break;
+            case AC_RELAY_WELDING: ShmStatusCodeData->FaultCode.FaultEvents.bits.AcOutputRelayWelding = NO; break;
+            case AC_GF_MODULE_FAULT: ShmStatusCodeData->FaultCode.FaultEvents.bits.RcdSelfTestFail = NO; break;
+            case AC_SHUTTER_FAULT: break;
+            case AC_LOCKER_FAULT: ShmStatusCodeData->FaultCode.FaultEvents.bits.AcConnectorLockFail = NO; break;
+            case AC_POWER_DROP: ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputDrop = NO; break;
+            case AC_CIRCUIT_SHORT: ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CircuitShort = NO; break;
+            case AC_ROTARY_SWITCH_FAULT:  break;
+            case AC_RELAY_DRIVE_FAULT: ShmStatusCodeData->FaultCode.FaultEvents.bits.AcOutputRelayDrivingFault = NO; break;
+            }
+        }
+    }
+
+    ac_chargingInfo[0]->IsErrorOccur = isErr;
+}
+
+bool IsNoneMatchLedColor()
+{
+    bool result = false;
+
+    if (cur_led_color.Connect_1_Red != led_color.Connect_1_Red ||
+            cur_led_color.Connect_1_Green != led_color.Connect_1_Green ||
+            cur_led_color.Connect_1_Blue != led_color.Connect_1_Blue ||
+            cur_led_color.Connect_2_Red != led_color.Connect_2_Red ||
+            cur_led_color.Connect_2_Green != led_color.Connect_2_Green ||
+            cur_led_color.Connect_2_Blue != led_color.Connect_2_Blue) {
+        result = true;
+    }
+
+    return result;
+}
+
+void SetLedColor(struct ChargingInfoData *chargingData_1, struct ChargingInfoData *chargingData_2)
+{
+    uint8_t _colorBuf = COLOR_MAX_LV * LED_INTENSITY_BRIGHTEST;
+
+    if (ShmSysConfigAndInfo->SysConfig.LedInfo.Intensity == _LED_INTENSITY_DARKEST) {
+        _colorBuf = COLOR_MAX_LV * LED_INTENSITY_DARKEST;
+    } else if (ShmSysConfigAndInfo->SysConfig.LedInfo.Intensity == _LED_INTENSITY_MEDIUM) {
+        _colorBuf = COLOR_MAX_LV * LED_INTENSITY_MEDIUM;
+    }
+
+    //printf("chargingData_1->SystemStatus=%d\n",chargingData_1->SystemStatus);
+    //printf("chargingData_2->SystemStatus=%d\n",chargingData_2->SystemStatus);
+    //printf("ShmSysConfigAndInfo->SysWarningInfo.Level=%d\n",ShmSysConfigAndInfo->SysWarningInfo.Level);
+    if (ShmSysConfigAndInfo->SysWarningInfo.Level == 2) {
+        led_color.Connect_1_Green = COLOR_MIN_LV;
+        led_color.Connect_1_Blue = COLOR_MIN_LV;
+        led_color.Connect_1_Red = _colorBuf;
+        led_color.Connect_2_Green = COLOR_MIN_LV;
+        led_color.Connect_2_Blue = COLOR_MIN_LV;
+        led_color.Connect_2_Red = _colorBuf;
+    } else {
+        if (ShmSysConfigAndInfo->SysInfo.IsAlternatvieConf) {
+            if ((chargingData_1->SystemStatus == S_BOOTING ||
+                    chargingData_1->SystemStatus == S_IDLE ||
+                    chargingData_1->SystemStatus == S_RESERVATION) &&
+                    (chargingData_2->SystemStatus == S_BOOTING ||
+                     chargingData_2->SystemStatus == S_IDLE ||
+                     chargingData_2->SystemStatus == S_RESERVATION)) {
+#if defined DD360Audi
+                led_color.Connect_1_Green = _colorBuf;
+                led_color.Connect_1_Blue = _colorBuf;
+                led_color.Connect_1_Red = _colorBuf;
+
+                led_color.Connect_2_Green = _colorBuf;
+                led_color.Connect_2_Blue = _colorBuf;
+                led_color.Connect_2_Red = _colorBuf;
+#else
+                led_color.Connect_1_Green = _colorBuf;
+                led_color.Connect_1_Blue = COLOR_MIN_LV;
+                led_color.Connect_1_Red = COLOR_MIN_LV;
+
+                led_color.Connect_2_Green = _colorBuf;
+                led_color.Connect_2_Blue = COLOR_MIN_LV;
+                led_color.Connect_2_Red = COLOR_MIN_LV;
+#endif
+            } else if ((chargingData_1->SystemStatus >= S_AUTHORIZING &&
+                        chargingData_1->SystemStatus <= S_COMPLETE) ||
+                       (chargingData_1->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
+                        chargingData_1->SystemStatus <= S_CCS_PRECHARGE_ST1) ||
+                       (chargingData_2->SystemStatus >= S_AUTHORIZING &&
+                        chargingData_2->SystemStatus <= S_COMPLETE) ||
+                       (chargingData_2->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
+                        chargingData_2->SystemStatus <= S_CCS_PRECHARGE_ST1)) {
+                led_color.Connect_1_Green = COLOR_MIN_LV;
+                led_color.Connect_1_Blue = _colorBuf;
+                led_color.Connect_1_Red = COLOR_MIN_LV;
+                led_color.Connect_2_Green = COLOR_MIN_LV;
+                led_color.Connect_2_Blue = _colorBuf;
+                led_color.Connect_2_Red = COLOR_MIN_LV;
+            }
+        } else {
+            if (chargingData_1->SystemStatus == S_BOOTING ||
+                    chargingData_1->SystemStatus == S_IDLE ||
+                    chargingData_1->SystemStatus == S_RESERVATION ||
+                    chargingData_1->SystemStatus == S_MAINTAIN) {
+
+                if (chargingData_1->IsAvailable == NO) { //For Audi
+                    led_color.Connect_1_Green = COLOR_MIN_LV;
+                    led_color.Connect_1_Blue = COLOR_MIN_LV;
+                    led_color.Connect_1_Red = _colorBuf;
+                } else {
+#if defined DD360Audi
+                    led_color.Connect_1_Green = _colorBuf;
+                    led_color.Connect_1_Blue = _colorBuf;
+                    led_color.Connect_1_Red = _colorBuf;
+#else
+                    led_color.Connect_1_Green = _colorBuf;
+                    led_color.Connect_1_Blue = COLOR_MIN_LV;
+                    led_color.Connect_1_Red = COLOR_MIN_LV;
+#endif
+                }
+            } else if ((chargingData_1->SystemStatus >= S_AUTHORIZING &&
+                        chargingData_1->SystemStatus <= S_COMPLETE) ||
+                       (chargingData_1->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
+                        chargingData_1->SystemStatus <= S_CCS_PRECHARGE_ST1)) {
+                led_color.Connect_1_Green = COLOR_MIN_LV;
+                led_color.Connect_1_Blue = _colorBuf;
+                led_color.Connect_1_Red = COLOR_MIN_LV;
+            }
+
+            // --------------------------------------------------------------------------
+            if (chargingData_2->SystemStatus == S_BOOTING ||
+                    chargingData_2->SystemStatus == S_IDLE ||
+                    chargingData_2->SystemStatus == S_RESERVATION ||
+                    chargingData_2->SystemStatus == S_MAINTAIN) {
+                if (chargingData_2->IsAvailable == NO) {
+                    led_color.Connect_2_Green = COLOR_MIN_LV;
+                    led_color.Connect_2_Blue = COLOR_MIN_LV;
+                    led_color.Connect_2_Red = _colorBuf;
+                } else {
+#if defined DD360Audi
+                    led_color.Connect_2_Green = _colorBuf;
+                    led_color.Connect_2_Blue = _colorBuf;
+                    led_color.Connect_2_Red = _colorBuf;
+#else
+                    led_color.Connect_2_Green = _colorBuf;
+                    led_color.Connect_2_Blue = COLOR_MIN_LV;
+                    led_color.Connect_2_Red = COLOR_MIN_LV;
+#endif
+                }
+            } else if ((chargingData_2->SystemStatus >= S_AUTHORIZING &&
+                        chargingData_2->SystemStatus <= S_COMPLETE) ||
+                       (chargingData_2->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
+                        chargingData_2->SystemStatus <= S_CCS_PRECHARGE_ST1)) {
+                led_color.Connect_2_Green = COLOR_MIN_LV;
+                led_color.Connect_2_Blue = _colorBuf;
+                led_color.Connect_2_Red = COLOR_MIN_LV;
+            }
+        }
+    }
+
+    if (_checkLedChanged > 0) {
+        if (Config_Led_Color(Uart5Fd, ADDR_LED, &led_color) == PASS) {
+            _checkLedChanged--;
+
+            cur_led_color.Connect_1_Red     = led_color.Connect_1_Red;
+            cur_led_color.Connect_1_Green   = led_color.Connect_1_Green;
+            cur_led_color.Connect_1_Blue    = led_color.Connect_1_Blue;
+            cur_led_color.Connect_2_Red     = led_color.Connect_2_Red;
+            cur_led_color.Connect_2_Green   = led_color.Connect_2_Green;
+            cur_led_color.Connect_2_Blue    = led_color.Connect_2_Blue;
+        }
+    } else if (IsNoneMatchLedColor()) {
+        _checkLedChanged = 3;
+    }
+}
+
+//==========================================
+// Init all share memory
+//==========================================
+int InitShareMemory()
+{
+    int result = PASS;
+    int MeterSMId;
+
+    if ((MeterSMId = shmget(ShmSysConfigAndInfoKey, sizeof(struct SysConfigAndInfo),  0777)) < 0) {
+        result = FAIL;
+    } else if ((ShmSysConfigAndInfo = shmat(MeterSMId, NULL, 0)) == (void *) - 1) {
+        result = FAIL;
+    }
+
+    if ((MeterSMId = shmget(ShmStatusCodeKey, sizeof(struct StatusCodeData),  0777)) < 0) {
+        result = FAIL;
+    } else if ((ShmStatusCodeData = shmat(MeterSMId, NULL, 0)) == (void *) - 1) {
+        result = FAIL;
+    }
+
+    if ((MeterSMId = shmget(ShmFanBdKey, sizeof(struct FanModuleData),  0777)) < 0) {
+        result = FAIL;
+    } else if ((ShmFanModuleData = shmat(MeterSMId, NULL, 0)) == (void *) - 1) {
+        result = FAIL;
+    }
+    memset(ShmFanModuleData, 0, sizeof(struct FanModuleData));
+
+    if ((MeterSMId = shmget(ShmRelayBdKey, sizeof(struct RelayModuleData),  0777)) < 0) {
+        result = FAIL;
+    } else if ((ShmRelayModuleData = shmat(MeterSMId, NULL, 0)) == (void *) - 1) {
+        result = FAIL;
+    }
+    memset(ShmRelayModuleData, 0, sizeof(struct RelayModuleData));
+
+    if ((MeterSMId = shmget(ShmLedBdKey, sizeof(struct LedModuleData),  0777)) < 0) {
+        result = FAIL;
+    } else if ((ShmLedModuleData = shmat(MeterSMId, NULL, 0)) == (void *) - 1) {
+        result = FAIL;
+    }
+    memset(ShmLedModuleData, 0, sizeof(struct LedModuleData));
+
+    if ((MeterSMId = shmget(ShmPsuKey, sizeof(struct PsuData),  0777)) < 0) {
+        result = FAIL;
+    } else if ((ShmPsuData = shmat(MeterSMId, NULL, 0)) == (void *) - 1) {
+        result = FAIL;
+    }
+
+    if ((MeterSMId = shmget(ShmOcppModuleKey, sizeof(struct OCPP16Data), 0777)) < 0) {
+        result = FAIL;
+    } else if ((ShmOCPP16Data = shmat(MeterSMId, NULL, 0)) == (void *) - 1) {
+        result = FAIL;
+    }
+
+    if ((MeterSMId = shmget(ShmCommonKey, sizeof(DcCommonInfo), IPC_CREAT | 0777)) < 0) {
+        return FAIL;
+    } else if ((ShmDcCommonData = shmat(MeterSMId, NULL, 0)) == (void *) - 1) {
+        return FAIL;
+    }
+
+    return result;
+}
+
+int InitComPort()
+{
+    int fd;
+    struct termios tios;
+
+    fd = open(relayRs485PortName, O_RDWR);
+    if (fd <= 0) {
+#ifdef SystemLogMessage
+        log_error("Module_InternalComm. InitComPort NG\n");
+#endif
+        if (ShmStatusCodeData != NULL) {
+            ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed = 1;
+        }
+        sleep(5);
+        return -1;
+    }
+    ioctl (fd, TCGETS, &tios);
+    tios.c_cflag = B115200 | CS8 | CLOCAL | CREAD;
+    tios.c_lflag = 0;
+    tios.c_iflag = 0;
+    tios.c_oflag = 0;
+    tios.c_cc[VMIN] = 0;
+    tios.c_cc[VTIME] = (uint8_t)0;     // timeout 0.5 second
+    tios.c_lflag = 0;
+    tcflush(fd, TCIFLUSH);
+    ioctl (fd, TCSETS, &tios);
+
+    return fd;
+}
+
+//================================================
+// Main process
+//================================================
+bool FindChargingInfoData(uint8_t target, struct ChargingInfoData **chargingData)
+{
+    for (uint8_t index = 0; index < CHAdeMO_QUANTITY; index++) {
+        if (ShmSysConfigAndInfo->SysInfo.ChademoChargingData[index].Index
+                == target) {
+            chargingData[target] =
+                &ShmSysConfigAndInfo->SysInfo.ChademoChargingData[index];
+            return true;
+        }
+    }
+
+    for (uint8_t index = 0; index < CCS_QUANTITY; index++) {
+        if (ShmSysConfigAndInfo->SysInfo.CcsChargingData[index].Index
+                == target) {
+            chargingData[target] =
+                &ShmSysConfigAndInfo->SysInfo.CcsChargingData[index];
+            return true;
+        }
+    }
+
+    for (uint8_t index = 0; index < GB_QUANTITY; index++) {
+        if (ShmSysConfigAndInfo->SysInfo.GbChargingData[index].Index
+                == target) {
+            chargingData[target] =
+                &ShmSysConfigAndInfo->SysInfo.GbChargingData[index];
+            return true;
+        }
+    }
+
+    return false;
+}
+
+bool FindAcChargingInfoData(uint8_t target, struct ChargingInfoData **acChargingData)
+{
+    if (target < AC_QUANTITY) {
+        acChargingData[target] = &ShmSysConfigAndInfo->SysInfo.AcChargingData[target];
+        return true;
+    }
+
+    return false;
+}
+
+void Initialization()
+{
+    bool isPass = false;
+
+    for (uint8_t index = 0; index < ARRAY_SIZE(outputRelay.relay_event.relay_status); index++) {
+        outputRelay.relay_event.relay_status[index] = 0x00;
+    }
+
+    while (!isPass) {
+        isPass = true;
+        for (uint8_t _index = 0; _index < gunCount; _index++) {
+            if (!FindChargingInfoData(_index, &_chargingData[0])) {
+                log_error("InternalComm : FindChargingInfoData false \n");
+                isPass = false;
+                break;
+            }
+        }
+
+        sleep(1);
+    }
+
+    isPass = false;
+
+    if (acgunCount > 0) {
+        while (!isPass) {
+            isPass = true;
+            for (uint8_t _index = 0; _index < acgunCount; _index++) {
+                if (!FindAcChargingInfoData(_index, &ac_chargingInfo[0])) {
+                    log_error("EvComm : FindAcChargingInfoData false \n");
+                    isPass = false;
+                    break;
+                }
+            }
+
+            sleep(1);
+        }
+    }
+}
+
+bool IsNoneMatchRelayStatus()
+{
+    bool result = false;
+
+    if (
+#if !defined DD360Tcci && !defined DD360Audi && !defined DD360ComBox
+        (regRelay.relay_event.bits.AC_Contactor != outputRelay.relay_event.bits.AC_Contactor) ||
+        (regRelay.relay_event.bits.CCS_Precharge != outputRelay.relay_event.bits.CCS_Precharge) ||
+#endif //!defined DD360Tcci && !defined DD360Audi
+        (regRelay.relay_event.bits.Gun1_P != outputRelay.relay_event.bits.Gun1_P) ||
+        (regRelay.relay_event.bits.Gun1_N != outputRelay.relay_event.bits.Gun1_N) ||
+        (regRelay.relay_event.bits.Gun2_P != outputRelay.relay_event.bits.Gun2_P) ||
+        (regRelay.relay_event.bits.Gun2_N != outputRelay.relay_event.bits.Gun2_N)
+#if !defined DD360Tcci && !defined DD360Audi && !defined DD360ComBox
+        ||
+        (regRelay.relay_event.bits.Gun1_Parallel_P != outputRelay.relay_event.bits.Gun1_Parallel_P) ||
+        (regRelay.relay_event.bits.Gun1_Parallel_N != outputRelay.relay_event.bits.Gun1_Parallel_N)
+#endif //!defined DD360Tcci && !defined DD360Audi
+    ) {
+        /*if (regRelay.relay_event.bits.AC_Contactor != outputRelay.relay_event.bits.AC_Contactor) {
+            log_info("AC Contact Relay none match. \n");
+        }
+
+        if (regRelay.relay_event.bits.CCS_Precharge != outputRelay.relay_event.bits.CCS_Precharge) {
+            log_info("CCS Precharge Relay none match. \n");
+        }
+
+        if (regRelay.relay_event.bits.Gun1_P != outputRelay.relay_event.bits.Gun1_P) {
+            log_info("SMR1:D+ Relay none match. \n");
+        }
+
+        if (regRelay.relay_event.bits.Gun1_N != outputRelay.relay_event.bits.Gun1_N) {
+            log_info("SMR1:D- Relay none match. \n");
+        }
+
+        if (regRelay.relay_event.bits.Gun2_P != outputRelay.relay_event.bits.Gun2_P) {
+            log_info("SMR2:D+ Relay none match. \n");
+        }
+
+        if (regRelay.relay_event.bits.Gun2_N != outputRelay.relay_event.bits.Gun2_N) {
+            log_info("SMR2:D- Relay none match. \n");
+        }
+
+        if (regRelay.relay_event.bits.Gun1_Parallel_P != outputRelay.relay_event.bits.Gun1_Parallel_P) {
+            log_info("Parallel:D+ Relay none match. \n");
+        }
+
+        if (regRelay.relay_event.bits.Gun1_Parallel_N != outputRelay.relay_event.bits.Gun1_Parallel_N) {
+            log_info("Parallel:D- Relay none match. \n");
+        }*/
+
+        result = true;
+    }
+
+    return result;
+}
+
+void MatchRelayStatus()
+{
+    // 因為 AC Contactor 沒有 Feedback,所以暫時先這樣處理
+    //regRelay.relay_event.bits.AC_Contactor = outputRelay.relay_event.bits.AC_Contactor;
+#if !defined DD360Tcci && !defined DD360Audi && !defined DD360ComBox
+    ShmSysConfigAndInfo->SysInfo.AcContactorStatus  = regRelay.relay_event.bits.AC_Contactor = outputRelay.relay_event.bits.AC_Contactor;
+#endif //!defined DD360Tcci && !defined DD360Audi
+
+    regRelay.relay_event.bits.CCS_Precharge = outputRelay.relay_event.bits.CCS_Precharge;
+    regRelay.relay_event.bits.Gun1_P = outputRelay.relay_event.bits.Gun1_P;
+    regRelay.relay_event.bits.Gun1_N = outputRelay.relay_event.bits.Gun1_N;
+    regRelay.relay_event.bits.Gun2_P = outputRelay.relay_event.bits.Gun2_P;
+    regRelay.relay_event.bits.Gun2_N = outputRelay.relay_event.bits.Gun2_N;
+    regRelay.relay_event.bits.Gun1_Parallel_P = outputRelay.relay_event.bits.Gun1_Parallel_P;
+    regRelay.relay_event.bits.Gun1_Parallel_N = outputRelay.relay_event.bits.Gun1_Parallel_N;
+}
+
+void CheckRelayStatusByADC()
+{
+    if (ShmRelayModuleData->Gun1FuseOutputVolt > 0 && ShmRelayModuleData->Gun1RelayOutputVolt > 0 &&
+            (ShmRelayModuleData->Gun1FuseOutputVolt == ShmRelayModuleData->Gun1RelayOutputVolt)) {
+        // Relay 前後電壓一致
+        _chargingData[0]->RelayK1K2Status = 0x01;
+    } else {
+        _chargingData[0]->RelayK1K2Status = 0x00;
+    }
+
+    if (ShmRelayModuleData->Gun2FuseOutputVolt > 0 && ShmRelayModuleData->Gun2RelayOutputVolt > 0 &&
+            (ShmRelayModuleData->Gun2FuseOutputVolt == ShmRelayModuleData->Gun2RelayOutputVolt)) {
+        // Relay 前後電壓一致
+        _chargingData[1]->RelayK1K2Status = 0x01;
+    } else {
+        _chargingData[1]->RelayK1K2Status = 0x00;
+    }
+}
+
+void SetGfdConfig(uint8_t index, uint8_t resister)
+{
+    gfd_config.index = index;
+    gfd_config.state = resister;
+
+    //log_info("************************GFD Vol = %d, GFD Res = %d \n", gfd_config.reqVol, gfd_config.resister);
+    if (Config_Gfd_Value(Uart5Fd, ADDR_RELAY, &gfd_config) == PASS) {
+//      log_info("Set reqVol = %f, resister = %d \n",
+//              gfd_config.reqVol,
+//              gfd_config.resister);
+    }
+}
+
+void CableCheckDetected(uint8_t index)
+{
+    uint8_t targetID = 0;
+    // Cable Check
+    // 當火線上的電壓 = 車端要求的電壓電流
+    // _chargingData[targetGun]->EvBatterytargetVoltage
+    // 才可以開始偵測 1s
+    // Warning : Rgfd <= 150 歐/V 假設電壓為 500V 則~ Rgfd <= 75000 歐
+    // Pre-Warning : 150 歐/V < Rgfd <= 500 歐/V 假設電壓為 500V 則 75000 歐 < Rgfd <= 250000
+    // SO Normal : Rgfd > 500 歐/V 假設電壓為 500 V 則 Rgfd > 250000 歐
+
+    if (gunCount == 1) {
+        if (strncmp((char *)&ShmSysConfigAndInfo->SysConfig.ModelName[7], "0", 1) != 0) {
+            targetID = 0;
+        } else if (strncmp((char *)&ShmSysConfigAndInfo->SysConfig.ModelName[9], "0", 1) != 0) {
+            targetID = 1;
+        }
+    } else {
+        targetID = index;
+    }
+
+    if ((_chargingData[index]->Type >= _Type_Chademo &&
+            _chargingData[index]->Type <= _Type_GB) ||
+            (_chargingData[index]->Type == 0x09 &&
+             ShmSysConfigAndInfo->SysConfig.AlwaysGfdFlag)) {
+        if ((_chargingData[index]->SystemStatus >= S_PREPARING_FOR_EVSE &&
+                _chargingData[index]->SystemStatus <= S_TERMINATING) ||
+                (_chargingData[index]->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
+                 _chargingData[index]->SystemStatus <= S_CCS_PRECHARGE_ST1)) {
+            if (_chargingData[index]->SystemStatus == S_PREPARING_FOR_EVSE &&
+                    _chargingData[index]->RelayWeldingCheck == YES) {
+                SetGfdConfig(targetID, GFD_CABLECHK);
+            } else if (_chargingData[index]->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
+                       _chargingData[index]->SystemStatus <= S_CCS_PRECHARGE_ST1) {
+                SetGfdConfig(targetID, GFD_PRECHARGE);
+            } else if (_chargingData[index]->SystemStatus >= S_CHARGING &&
+                       _chargingData[index]->SystemStatus <= S_TERMINATING) {
+                if (_chargingData[index]->Type == _Type_GB || _chargingData[index]->Type == _Type_Chademo) {
+                    SetGfdConfig(targetID, GFD_IDLE);
+                } else {
+                    SetGfdConfig(targetID, GFD_CHARGING);
+                }
+            }
+        } else if (_chargingData[index]->SystemStatus == S_COMPLETE ||
+                   _chargingData[index]->SystemStatus == S_PREPARNING
+                   || _chargingData[index]->SystemStatus == S_IDLE) {
+            SetGfdConfig(targetID, GFD_IDLE);
+        }
+    }
+}
+
+void CheckOutputPowerOverCarReq(uint8_t index)
+{
+    float fireV = _chargingData[index]->FireChargingVoltage;
+    float carV = _chargingData[index]->EvBatteryMaxVoltage * 10;
+
+    if ((_chargingData[index]->EvBatterytargetVoltage * 10) > 1500 &&
+            (_chargingData[index]->Type == _Type_Chademo ||
+             _chargingData[index]->Type == _Type_CCS_2 ||
+             _chargingData[index]->Type == _Type_GB)) {
+        if (fireV >= (carV + (carV * 0.02))) {
+            if (!_isOvpChkTimeFlag[index]) {
+                if ((_chargingData[index]->PresentChargingVoltage * 10) >= VOUT_MIN_VOLTAGE * 10) {
+                    gettimeofday(&_checkOutputVolProtectTimer[index], NULL);
+                    _isOvpChkTimeFlag[index] = YES;
+                }
+            } else {
+                log_info("[Module_InternalComm]CheckOutputPowerOverCarReq NG : fire = %f, battery = %f \n",
+                         _chargingData[index]->FireChargingVoltage, (_chargingData[index]->EvBatterytargetVoltage * 10));
+                log_error("[Module_InternalComm]CheckOutputPowerOverCarReq NG : fire = %f, battery = %f \n",
+                          _chargingData[index]->FireChargingVoltage, (_chargingData[index]->EvBatterytargetVoltage * 10));
+                if ((GetTimeoutValue(_checkOutputVolProtectTimer[index]) / 1000) >= OUTPUT_VOL_CHK_TIME) {
+                    //if (_chargingData[index]->Type == _Type_Chademo) {
+                    //    ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemChademoOutputOVP = YES;
+                    //} else if (_chargingData[index]->Type == _Type_CCS_2) {
+                    //    ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemCcsOutputOVP = YES;
+                    //} else if (_chargingData[index]->Type == _Type_GB) {
+                    //    ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemGbOutputOVP = YES;
+                    //}
+                    if (_chargingData[index]->Type == _Type_Chademo) {
+                        ShmDcCommonData->ConnectErrList[index].GunBits.ChaConnectOVP = YES;
+                        if (strncmp((char *)_chargingData[index]->ConnectorAlarmCode, "", 6) == EQUAL) {
+                            memcpy(_chargingData[index]->ConnectorAlarmCode, "012217", 6);
+                        }
+                    } else if (_chargingData[index]->Type == _Type_CCS_2) {
+                        ShmDcCommonData->ConnectErrList[index].GunBits.CCSConnectOVP = YES;
+                        if (strncmp((char *)_chargingData[index]->ConnectorAlarmCode, "", 6) == EQUAL) {
+                            memcpy(_chargingData[index]->ConnectorAlarmCode, "012219", 6);
+                        }
+                    } else if (_chargingData[index]->Type == _Type_GB) {
+                        ShmDcCommonData->ConnectErrList[index].GunBits.GBTConnectOVP = YES;
+                        if (strncmp((char *)_chargingData[index]->ConnectorAlarmCode, "", 6) == EQUAL) {
+                            memcpy(_chargingData[index]->ConnectorAlarmCode, "012221", 6);
+                        }
+                    }
+
+                    _chargingData[index]->StopChargeFlag = YES;
+                }
+            }
+        } else {
+            if (_isOvpChkTimeFlag[index] == YES) {
+                _isOvpChkTimeFlag[index] = NO;
+            }
+        }
+    }
+}
+
+void CheckOutputVolNoneMatchFire(uint8_t index)
+{
+    if ((_chargingData[index]->EvBatterytargetVoltage * 10) > 1500 &&
+            (_chargingData[index]->Type == _Type_Chademo ||
+             _chargingData[index]->Type == _Type_CCS_2 ||
+             _chargingData[index]->Type == _Type_GB)) {
+        if (((_chargingData[index]->PresentChargingVoltage * 10) < _chargingData[index]->FireChargingVoltage - 300) ||
+                ((_chargingData[index]->PresentChargingVoltage * 10) > _chargingData[index]->FireChargingVoltage + 300)) {
+            if (!_isOutputNoneMatch[index]) {
+                _isOutputNoneMatch[index] = YES;
+                gettimeofday(&_checkOutputNoneMatchTimer[index], NULL);
+            } else {
+                if ((GetTimeoutValue(_checkOutputNoneMatchTimer[index]) / 1000) >= 5000) {
+                    /*log_info("[Module_InternalComm]CheckOutputVolNoneMatchFire NG (%d) : pre = %f, fire = %f \n",
+                            index, (_chargingData[index]->PresentChargingVoltage * 10), _chargingData[index]->FireChargingVoltage);
+                    log_error("[Module_InternalComm]CheckOutputVolNoneMatchFire NG (%d): pre = %f, fire = %f \n",
+                            index, (_chargingData[index]->PresentChargingVoltage * 10), _chargingData[index]->FireChargingVoltage);
+                    _chargingData[index]->StopChargeFlag = YES;*/
+                }
+            }
+        } else {
+            _isOutputNoneMatch[index] = NO;
+        }
+    }
+}
+
+void CheckRelayWeldingStatus(uint8_t index)
+{
+    if (!_isRelayWelding[index]) {
+        if ((_chargingData[index]->PresentChargingVoltage * 10) >= VOUT_MIN_VOLTAGE * 10) {
+            gettimeofday(&_checkRelayWeldingTimer[index], NULL);
+            _isRelayWelding[index] = YES;
+        }
+    } else {
+        if ((GetTimeoutValue(_checkRelayWeldingTimer[index]) / 1000) >= 1000) {
+            _chargingData[index]->RelayWeldingCheck = YES;
+            return;
+        }
+
+        if (_chargingData[index]->FireChargingVoltage >= VOUT_MIN_VOLTAGE) {
+            if (_chargingData[index]->Type == _Type_Chademo) {
+                ShmStatusCodeData->FaultCode.FaultEvents.bits.ChademoOutputRelayWelding = YES;
+            } else if (_chargingData[index]->Type == _Type_GB) {
+                ShmStatusCodeData->FaultCode.FaultEvents.bits.GbOutputRelayWelding = YES;
+            } else if (_chargingData[index]->Type == _Type_CCS_2) {
+                ShmStatusCodeData->FaultCode.FaultEvents.bits.CcsOutputRelayWelding = YES;
+            }
+
+            log_info("CheckRelayWeldingStatus : fail \n");
+            _chargingData[index]->StopChargeFlag = YES;
+        }
+    }
+}
+
+void GetPsuTempForFanSpeed()
+{
+    char temp = 0;
+
+    for (uint8_t index = 0; index < ShmPsuData->GroupCount; index++) {
+        for (uint8_t count = 0; count < ShmPsuData->PsuGroup[index].GroupPresentPsuQuantity; count++) {
+            if (temp < ShmPsuData->PsuGroup[index].PsuModule[count].ExletTemp) {
+                temp = ShmPsuData->PsuGroup[index].PsuModule[count].ExletTemp;
+            }
+        }
+    }
+
+    ShmSysConfigAndInfo->SysInfo.SystemAmbientTemp = temp;
+
+    if (ShmSysConfigAndInfo->SysConfig.SwitchDebugFlag == NO) {
+        if (ShmFanModuleData->TestFanSpeed == NORMAL_FAN_SPEED) {
+            if (temp >= ENV_TEMP_MAX) {
+                ShmFanModuleData->TestFanSpeed = MAX_FAN_SPEED;
+            }
+        } else if (ShmFanModuleData->TestFanSpeed == MAX_FAN_SPEED) {
+            if (temp <= ENV_TEMP_MIN) {
+                ShmFanModuleData->TestFanSpeed = NORMAL_FAN_SPEED;
+            }
+        } else {
+            ShmFanModuleData->TestFanSpeed = NORMAL_FAN_SPEED;
+        }
+    }
+}
+
+void GetFanSpeedByFunction()
+{
+    if (ShmSysConfigAndInfo->SysConfig.SwitchDebugFlag == YES) {
+        return;
+    }
+
+    // 風控修改 :
+    // ******************************************************* //
+    //
+    //       當前PSU輸出總 KW       PSU Temp
+    // 30 x -------------------- x ---------- + 14 x (PSU Temp - 45)
+    //       當前樁最大功率 KW         45
+    //
+    // ******************************************************* //
+
+    // 當前樁最大功率 KW : ShmPsuData->SystemAvailablePower
+    unsigned int _maxPower = ShmPsuData->SystemAvailablePower;
+    // 當前PSU輸出總 KW & PSU Temp :
+    uint8_t temp = 0;
+    float power = 0;
+
+    for (uint8_t index = 0; index < ShmPsuData->GroupCount; index++) {
+        for (uint8_t count = 0; count < ShmPsuData->PsuGroup[index].GroupPresentPsuQuantity; count++) {
+            if (temp < ShmPsuData->PsuGroup[index].PsuModule[count].ExletTemp) {
+                temp = ShmPsuData->PsuGroup[index].PsuModule[count].ExletTemp;
+            }
+        }
+    }
+
+    for (uint8_t gunIndex = 0; gunIndex < gunCount; gunIndex++) {
+        power += (_chargingData[gunIndex]->PresentChargingPower * 10);
+    }
+
+    double _pw_rate = 0;
+    if (_maxPower > 0) {
+        _pw_rate = power / (double)_maxPower;
+    }
+    double _temp_rate = 0;
+    if (temp > 0) {
+        _temp_rate = (double)temp / 50;
+    }
+    uint8_t _temp_diff = 0;
+    if (temp > 45) {
+        _temp_diff = temp - 70;
+    }
+
+    ShmFanModuleData->TestFanSpeed = (((50 * _pw_rate * _temp_rate) + (0.5 * _temp_diff)) / 100) * MAX_FAN_SPEED;
+
+    if (ShmFanModuleData->TestFanSpeed > MAX_FAN_SPEED) {
+        ShmFanModuleData->TestFanSpeed = MAX_FAN_SPEED;
+    }
+
+    if (ShmFanModuleData->TestFanSpeed < 0) {
+        ShmFanModuleData->TestFanSpeed = 0;
+    }
+//
+//  printf("power = %f \n", power);
+//  printf("_maxPower = %d \n", _maxPower);
+//  printf("temp = %d \n", temp);
+//
+//  printf("_pw_rate = %f \n", _pw_rate);
+//  printf("_temp_rate = %f \n", _temp_rate);
+//  printf("_temp_diff = %d \n", _temp_diff);
+//  printf("fan rate = %f \n", (30 * _pw_rate * _temp_rate + 14 * _temp_diff));
+//  printf("ShmFanModuleData->TestFanSpeed = %d \n", ShmFanModuleData->TestFanSpeed);
+}
+
+void GetAcStatus()
+{
+    if (Query_AC_Status(Uart5Fd, ADDR_AC_PLUG, &acStatus) == PASS) {
+        ShmSysConfigAndInfo->SysConfig.AcRatingCurrent = acStatus.MaxCurrent;
+
+        if (ShmSysConfigAndInfo->SysConfig.AcMaxChargingCurrent == 0) {
+            ShmSysConfigAndInfo->SysConfig.AcMaxChargingCurrent = ShmSysConfigAndInfo->SysConfig.AcRatingCurrent;
+        }
+
+        ac_chargingInfo[0]->ConnectorPlugIn = acStatus.CpStatus;
+        //  log_info("CpStatus = %d \n", acStatus.CpStatus);
+        //              printf("CurLimit = %d \n", acStatus.CurLimit);
+        //              printf("PilotVol_P = %d \n", acStatus.PilotVol_P);
+        //              printf("PilotVol_N = %d \n", acStatus.PilotVol_N);
+        //              printf("LockStatus = %d \n", acStatus.LockStatus);
+        //              printf("RelayStatus = %d \n", acStatus.RelayStatus);
+        //              printf("ShutterStatus = %d \n", acStatus.ShutterStatus);
+        //              printf("MeterStatus = %d \n", acStatus.MeterStatus);
+        //              printf("PpStatus = %d \n", acStatus.PpStatus);
+        //              printf("MaxCurrent = %d \n", acStatus.MaxCurrent);
+        //              printf("RotateSwitchStatus = %d \n", acStatus.RelayStatus);
+        //              printf("============================== \n");
+        //
+        //              ac_chargingInfo[0]->SystemStatus = acStatus.CpStatus;
+    }
+//  else
+//      log_info("GetAcStatus return fail. \n");
+}
+
+void GetAcAlarmCode()
+{
+    if (Query_AC_Alarm_Code(Uart5Fd, ADDR_AC_PLUG, &acAlarmCode) == PASS) {
+        CheckAlarmOccur();
+    }
+}
+
+uint8_t GetChargingEnergy()
+{
+    return Query_Charging_Energy(Uart5Fd, ADDR_AC_PLUG, &acChargingEnergy);
+}
+
+uint8_t GetChargingCurrent()
+{
+    return Query_Charging_Current(Uart5Fd, ADDR_AC_PLUG, &acChargingCurrent);
+}
+
+void ChangeLedStatus()
+{
+    if (ac_chargingInfo[0]->SystemStatus == S_IDLE) {
+        ledStatus.ActionMode = 1;
+    } else if (ac_chargingInfo[0]->SystemStatus == S_PREPARNING) {
+        ledStatus.ActionMode = 3;
+    } else if (ac_chargingInfo[0]->SystemStatus == S_CHARGING) {
+        ledStatus.ActionMode = 4;
+    }
+
+    Config_LED_Status(Uart5Fd, ADDR_AC_PLUG, &ledStatus);
+}
+
+void SetLegacyReq(uint8_t _switch)
+{
+    Config_Legacy_Req(Uart5Fd, ADDR_AC_PLUG, _switch);
+}
+
+void SetCpDuty(uint8_t _value)
+{
+    Config_Ac_Duty(Uart5Fd, ADDR_AC_PLUG, _value);
+}
+
+void ChangeToCsuMode()
+{
+    ac_chargingInfo[0]->IsModeChagned = Config_CSU_Mode(Uart5Fd, ADDR_AC_PLUG);
+
+//  if (ac_chargingInfo[0]->IsModeChagned == PASS)
+//  {
+//      Config_Reset_MCU(Uart5Fd, ADDR_AC_PLUG);
+//  }
+}
+
+void ChangeStartOrStopDateTime(uint8_t isStart)
+{
+    char cmdBuf[32];
+    struct timeb csuTime;
+    struct tm *tmCSU;
+
+    ftime(&csuTime);
+    tmCSU = localtime(&csuTime.time);
+
+    sprintf(cmdBuf, "%04d-%02d-%02d %02d:%02d:%02d", tmCSU->tm_year + 1900,
+            tmCSU->tm_mon + 1, tmCSU->tm_mday, tmCSU->tm_hour, tmCSU->tm_min,
+            tmCSU->tm_sec);
+    if (isStart) {
+        strcpy((char *)ac_chargingInfo[0]->StartDateTime, cmdBuf);
+    } else {
+        strcpy((char *)ac_chargingInfo[0]->StopDateTime, cmdBuf);
+    }
+}
+
+void OcppStartTransation(uint8_t gunIndex)
+{
+    if (strcmp((char *)ac_chargingInfo[0]->StartUserId, "") == EQUAL) {
+        strcpy((char *)ShmOCPP16Data->StartTransaction[gunIndex].IdTag, (char *)ShmOCPP16Data->StartTransaction[gunIndex].IdTag);
+    } else {
+        strcpy((char *)ShmOCPP16Data->StartTransaction[gunIndex].IdTag, (char *)ac_chargingInfo[0]->StartUserId);
+    }
+
+    log_info("AC IdTag = %s \n", ShmOCPP16Data->StartTransaction[gunIndex].IdTag);
+    ShmOCPP16Data->CpMsg.bits[gunIndex].StartTransactionReq = YES;
+}
+
+void OcppStopTransation(uint8_t gunIndex)
+{
+    if (strcmp((char *)ac_chargingInfo[0]->StartUserId, "") == EQUAL) {
+        strcpy((char *)ShmOCPP16Data->StopTransaction[gunIndex].IdTag, (char *)ShmOCPP16Data->StopTransaction[gunIndex].IdTag);
+    } else {
+        strcpy((char *)ShmOCPP16Data->StopTransaction[gunIndex].IdTag, (char *)ac_chargingInfo[0]->StartUserId);
+    }
+
+    log_info("AC IdTag = %s \n", ShmOCPP16Data->StopTransaction[gunIndex].IdTag);
+    ShmOCPP16Data->CpMsg.bits[gunIndex].StopTransactionReq = YES;
+}
+
+bool OcppRemoteStop(uint8_t gunIndex)
+{
+    bool result = ShmOCPP16Data->CsMsg.bits[gunIndex].RemoteStopTransactionReq;
+
+    if (ShmOCPP16Data->CsMsg.bits[gunIndex].RemoteStopTransactionReq == YES) {
+        strcpy((char *)ShmOCPP16Data->StopTransaction[gunIndex].StopReason, "Remote");
+        ShmOCPP16Data->CsMsg.bits[gunIndex].RemoteStopTransactionReq = NO;
+    }
+
+    return result;
+}
+
+uint8_t isModeChange()
+{
+    uint8_t result = NO;
+
+    if (ac_chargingInfo[0]->SystemStatus != ac_chargingInfo[0]->PreviousSystemStatus) {
+        result = YES;
+        ac_chargingInfo[0]->PreviousSystemStatus = ac_chargingInfo[0]->SystemStatus;
+    }
+
+    return result;
+}
+
+void AcChargeTypeProcess()
+{
+    if (acgunCount > 0) {
+        //ac_chargingInfo[0]->SelfTest_Comp = YES;
+        //ac_chargingInfo[0]->IsModeChagned = PASS;
+        //---------------------------------------------
+        if (ac_chargingInfo[0]->SelfTest_Comp == NO) {
+            ac_chargingInfo[0]->IsModeChagned = NO;
+            GetFwVersion_AC();
+            GetAcModelName();
+        } else if (ac_chargingInfo[0]->SelfTest_Comp == YES) {
+            if (ac_chargingInfo[0]->IsModeChagned != PASS) {
+                ChangeToCsuMode();
+                return;
+            }
+            GetAcStatus();
+            GetAcAlarmCode();
+
+            uint8_t _status = S_NONE;
+
+            if (ac_chargingInfo[0]->SystemStatus == S_IDLE && ac_chargingInfo[0]->IsErrorOccur) {
+                _status = S_ALARM;
+            } else if (acStatus.CpStatus == AC_SYS_A || ac_chargingInfo[0]->IsErrorOccur) {
+                if (ac_chargingInfo[0]->SystemStatus == S_CHARGING) {
+                    _status = S_TERMINATING;
+                } else if (ac_chargingInfo[0]->SystemStatus >= S_TERMINATING) {
+                    if (GetTimeoutValue(_ac_charging_comp) >= 10000000 && acStatus.CpStatus == AC_SYS_A) {
+                        _status = S_IDLE;
+                    }
+                } else {
+                    _status = S_IDLE;
+                }
+            } else if (ac_chargingInfo[0]->SystemStatus >= S_PREPARNING &&
+                       ac_chargingInfo[0]->SystemStatus < S_CHARGING) {
+                if (acStatus.CpStatus == AC_SYS_C && acStatus.RelayStatus == YES) {
+                    _status = S_CHARGING;
+                } else if (GetTimeoutValue(_ac_preparing) >= 30000000) {
+                    _status = S_IDLE;
+                }
+            } else if ((acStatus.CpStatus == AC_SYS_B || ac_chargingInfo[0]->ConnectorPlugIn == AC_SYS_B) &&
+                       ac_chargingInfo[0]->IsAvailable &&
+                       !ac_chargingInfo[0]->IsErrorOccur &&
+                       (ShmSysConfigAndInfo->SysInfo.WaitForPlugit == YES ||
+                        ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_DISABLE)) {
+                if (ac_chargingInfo[0]->RemoteStartFlag == YES) {
+                    log_info("** AC Remote \n");
+                    ac_chargingInfo[0]->RemoteStartFlag = NO;
+                    strcpy((char *)ac_chargingInfo[0]->StartUserId, "");
+                    ShmSysConfigAndInfo->SysInfo.WaitForPlugit = NO;
+                    _status = S_PREPARNING;
+                } else if (ShmSysConfigAndInfo->SysInfo.OrderCharging == NO_DEFINE) {
+                    log_info("** UserId = %s \n", ShmSysConfigAndInfo->SysConfig.UserId);
+                    strcpy((char *)ac_chargingInfo[0]->StartUserId, (char *)ShmSysConfigAndInfo->SysConfig.UserId);
+                    log_info("** CardNumber = %s \n", ac_chargingInfo[0]->StartUserId);
+                    strcpy((char *)ShmSysConfigAndInfo->SysConfig.UserId, "");
+                    ShmSysConfigAndInfo->SysInfo.WaitForPlugit = NO;
+                    _status = S_PREPARNING;
+                }
+            } else if (ac_chargingInfo[0]->SystemStatus == S_CHARGING) {
+                if (OcppRemoteStop(1)) {
+                    _status = S_TERMINATING;
+                }
+            }
+
+            //printf("_status = %d \n", _status);
+
+            if (_status != S_NONE && ac_chargingInfo[0]->SystemStatus != _status) {
+                ac_chargingInfo[0]->SystemStatus = _status;
+            }
+
+            // 設定限制最大充電電流 >= 6 ~ <= 32
+            switch (ac_chargingInfo[0]->SystemStatus) {
+            case S_IDLE:
+            case S_ALARM: {
+                if (isModeChange()) {
+                    ac_chargingInfo[0]->PresentChargedEnergy = 0.0;
+                    ac_chargingInfo[0]->PresentChargingVoltage = 0;
+                    ac_chargingInfo[0]->ChargingFee = 0.0;
+                    strcpy((char *)ac_chargingInfo[0]->StartDateTime, "");
+                    strcpy((char *)ac_chargingInfo[0]->StopDateTime, "");
+                    _beforeChargingTotalEnergy = 0.0;
+                }
+
+                ChangeLedStatus();
+            }
+            break;
+            case S_PREPARNING: {
+                if (isModeChange()) {
+                    ShmSysConfigAndInfo->SysInfo.SystemPage = _LCM_NONE;
+                    ShmSysConfigAndInfo->SysInfo.CurGunSelectedByAc = DEFAULT_AC_INDEX;
+                    if (ShmSysConfigAndInfo->SysInfo.OrderCharging != NO_DEFINE) {
+                        ShmSysConfigAndInfo->SysInfo.OrderCharging = NO_DEFINE;
+                    }
+                    gettimeofday(&_ac_preparing, NULL);
+                }
+
+                if (GetChargingEnergy() == PASS) {
+                    //ac_chargingInfo[0]->PresentChargedEnergy = acChargingEnergy.Energy / 100;
+                    _beforeChargingTotalEnergy = acChargingEnergy.Energy;
+                }
+
+                SetLegacyReq(YES);
+                ChangeLedStatus();
+            }
+            break;
+            case S_CHARGING: {
+                if (isModeChange()) {
+                    ftime(&_ac_startChargingTime);
+                    OcppStartTransation(1);
+                    ChangeStartOrStopDateTime(YES);
+                    ShmSysConfigAndInfo->SysInfo.CurGunSelectedByAc = DEFAULT_AC_INDEX;
+                }
+
+                if (GetChargingEnergy() == PASS) {
+                    if ((acChargingEnergy.Energy - _beforeChargingTotalEnergy) > 0) {
+                        ac_chargingInfo[0]->PresentChargedEnergy += (acChargingEnergy.Energy - _beforeChargingTotalEnergy) / 100;
+                        if (ShmSysConfigAndInfo->SysConfig.BillingData.isBilling) {
+                            ac_chargingInfo[0]->ChargingFee += ac_chargingInfo[0]->PresentChargedEnergy * ShmSysConfigAndInfo->SysConfig.BillingData.Cur_fee;
+                        }
+                    }
+
+                    _beforeChargingTotalEnergy = acChargingEnergy.Energy;
+                }
+
+                if (GetChargingCurrent() == PASS) {
+                    ac_chargingInfo[0]->PresentChargingPower = (((float)(AC_DEFAULT_VOL * acChargingCurrent.OuputCurrentL1) / 10) / 1000);
+                }
+
+                ftime(&_ac_endChargingTime);
+                ac_chargingInfo[0]->PresentChargedDuration = DiffTimeb(_ac_startChargingTime, _ac_endChargingTime);
+                ac_chargingInfo[0]->PresentChargingVoltage = AC_DEFAULT_VOL;
+                ac_chargingInfo[0]->PresentChargingCurrent = ((float)acChargingCurrent.OuputCurrentL1 / 10);
+
+                // 用以判斷是否有在輸出
+                ac_chargingInfo[0]->IsCharging = acStatus.RelayStatus;
+
+                SetCpDuty(ShmSysConfigAndInfo->SysConfig.AcMaxChargingCurrent);
+                ChangeLedStatus();
+            }
+            break;
+            case S_TERMINATING: {
+                if (isModeChange()) {
+                    ChangeStartOrStopDateTime(NO);
+                    gettimeofday(&_ac_charging_comp, NULL);
+                }
+
+                SetLegacyReq(NO);
+                if (acStatus.RelayStatus == NO) {
+                    ac_chargingInfo[0]->SystemStatus = S_COMPLETE;
+                }
+            }
+            break;
+            case S_COMPLETE: {
+                if (isModeChange()) {
+                    gettimeofday(&_ac_charging_comp, NULL);
+                    ftime(&_ac_endChargingTime);
+                    if (strcmp((char *)ac_chargingInfo[0]->StartDateTime, "") != EQUAL) {
+                        // AC 固定為第2把槍
+                        OcppStopTransation(1);
+                    }
+
+                    ChangeStartOrStopDateTime(NO);
+                    ac_chargingInfo[0]->PresentChargedDuration = DiffTimeb(_ac_startChargingTime, _ac_endChargingTime);
+                }
+            }
+            break;
+            }
+        }
+    }
+}
+
+void ResetDetAlarmStatus(uint8_t gun)
+{
+    if (_chargingData[gun]->Type == _Type_Chademo) {
+        if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemChademoOutputOVP == YES) {
+            ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemChademoOutputOVP = NO;
+        }
+    } else if (_chargingData[gun]->Type == _Type_GB) {
+        if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemGbOutputOVP == YES) {
+            ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemGbOutputOVP = NO;
+        }
+    } else if (_chargingData[gun]->Type == _Type_CCS_2) {
+        if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemCcsOutputOVP == YES) {
+            ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemCcsOutputOVP = NO;
+        }
+    }
+}
+
+int main(void)
+{
+    uint8_t i = 0;
+    if (InitShareMemory() == FAIL) {
+        log_error("InitShareMemory NG\n");
+        if (ShmStatusCodeData != NULL) {
+            ShmStatusCodeData->AlarmCode.AlarmEvents.bits.FailToCreateShareMemory = 1;
+        }
+        sleep(5);
+        return 0;
+    }
+
+    gunCount = ShmSysConfigAndInfo->SysConfig.TotalConnectorCount;
+    acgunCount = ShmSysConfigAndInfo->SysConfig.AcConnectorCount;
+    // Open Uart5 for RB
+    Uart5Fd = InitComPort();
+    Initialization();
+    sleep(1);
+
+    if (Uart5Fd < 0) {
+        log_info("(Internal) open port error. \n");
+        return 0;
+    }
+
+    outputRelay.relay_event.bits.AC_Contactor = 0x00;
+    outputRelay.relay_event.bits.CCS_Precharge = 0x00;
+    outputRelay.relay_event.bits.Gun1_Parallel_P = 0x00;
+    outputRelay.relay_event.bits.Gun1_Parallel_N = 0x00;
+    outputRelay.relay_event.bits.Gun1_P = 0x00;
+    outputRelay.relay_event.bits.Gun1_N = 0x00;
+    outputRelay.relay_event.bits.Gun2_N = 0x00;
+    outputRelay.relay_event.bits.Gun2_P = 0x00;
+    if (Config_Relay_Output(Uart5Fd, ADDR_RELAY, &outputRelay) != PASS) {
+        log_info("Config_Relay_Output fail \n");
+
+    }
+
+    cur_led_color.Connect_1_Red = COLOR_MIN_LV;
+    cur_led_color.Connect_1_Green = COLOR_MIN_LV;
+    cur_led_color.Connect_1_Blue = COLOR_MIN_LV;
+    cur_led_color.Connect_2_Red = COLOR_MIN_LV;
+    cur_led_color.Connect_2_Green = COLOR_MIN_LV;
+    cur_led_color.Connect_2_Blue = COLOR_MIN_LV;
+
+    //bool printRelayStatus = true;
+    for (;;) {
+        bool isCharging = false;
+
+        // 程序開始之前~ 必須先確定 FW 版本與硬體版本,確認後!!~ 該模組才算是真正的 Initial Comp.
+        if (ShmRelayModuleData->SelfTest_Comp == NO) {
+            GetFwAndHwVersion_Relay();
+            SetModelName_Relay(); //DS60-120 add
+            SetRtcData_Relay();
+            sleep(1);
+        }
+
+#if !defined NO_FAN_BOARD && !defined DD360ComBox
+        if (ShmFanModuleData->SelfTest_Comp == NO) {
+            GetFwAndHwVersion_Fan();
+            SetModelName_Fan();
+            SetRtcData_Fan();
+            sleep(1);
+            gettimeofday(&_priority_time, NULL);
+        }
+#endif //NO_FAN_BOARD
+
+#if !defined DD360ComBox
+        // 自檢階段處理,自檢階段如果讀不到版號則代表該系統沒有掛燈板
+        if (ShmLedModuleData->SelfTest_Comp == NO) {
+#if defined DD360Tcci ||defined DD360Audi
+            GetFwAndHwVersion_Led();
+            sleep(1);
+            gettimeofday(&_led_priority_time, NULL);
+#else
+            // 自檢階段
+            if (ShmSysConfigAndInfo->SysInfo.SelfTestSeq <= _STEST_PSU_CAP) {
+                GetFwAndHwVersion_Led();
+                sleep(1);
+                gettimeofday(&_led_priority_time, NULL);
+            } else {
+                // 自檢階段沒有問到版號
+                if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.LedboardStestFail == NO) {
+                    ShmStatusCodeData->AlarmCode.AlarmEvents.bits.LedboardStestFail = YES;
+                }
+            }
+#endif //defined DD360Tcci || defined DD360Audi
+        }
+#endif //!defined DD360ComBox
+
+        AcChargeTypeProcess();
+
+        if (ShmRelayModuleData->SelfTest_Comp == YES) {
+            // ==============優先權最高 10 ms ==============
+            // 輸出電壓
+            GetPersentOutputVol();
+
+#if !defined DD360Tcci && !defined DD360Audi && !defined DD360ComBox
+            // 三相輸入電壓
+            GetPresentInputVol();
+            // 讀取當前 AC relay 狀態
+            regRelay.relay_event.bits.AC_Contactor = ShmSysConfigAndInfo->SysInfo.AcContactorStatus;
+
+            GetRelayOutputStatus();
+#endif //!defined DD360Tcci && !defined DD360Audi
+
+            for (i = 0; i < gunCount; i++) {
+                // Cable check (Set)
+                CableCheckDetected(i);
+
+                // check k1 k2 relay 狀態
+                CheckK1K2RelayOutput(i);
+
+                // 依據當前各槍的狀態選擇 搭上/放開 Relay
+                SetK1K2RelayStatus(i);
+
+#if !defined DD360Tcci && !defined DD360Audi && !defined DD360ComBox
+                if (ShmSysConfigAndInfo->SysConfig.PhaseLossPolicy == YES) {
+                    CheckPhaseLossStatus(i);
+                }
+
+                CheckAcInputOvpStatus(i);
+#endif //!defined DD360Tcci && !defined DD360Audi
+
+                if (_chargingData[i]->SystemStatus == S_IDLE) {
+                    _chargingData[i]->RelayWeldingCheck = NO;
+                    _isRelayWelding[i] = NO;
+                    _isOvpChkTimeFlag[i] = NO;
+                    ResetDetAlarmStatus(i); //DS60-120 add
+                }
+
+                if (_chargingData[i]->SystemStatus == S_BOOTING ||
+                        (_chargingData[i]->SystemStatus >= S_REASSIGN_CHECK && _chargingData[i]->SystemStatus <= S_COMPLETE) ||
+                        (_chargingData[i]->SystemStatus >= S_CCS_PRECHARGE_ST0 && _chargingData[i]->SystemStatus <= S_CCS_PRECHARGE_ST1) ||
+                        ShmSysConfigAndInfo->SysInfo.WaitForPlugit == YES ||
+                        (ShmSysConfigAndInfo->SysInfo.PageIndex >= _LCM_AUTHORIZING && ShmSysConfigAndInfo->SysInfo.PageIndex <= _LCM_WAIT_FOR_PLUG)) {
+                    _chargingData[i]->IsReadyToCharging = YES;
+                    isCharging = true;
+
+                    // 限定只有在槍類別為 GBT 的時候才做 relay welding 的判斷
+                    //if (_chargingData[i]->Type == _Type_GB) {
+                    //    if (_chargingData[i]->SystemStatus >= S_PREPARING_FOR_EVSE &&
+                    //            _chargingData[i]->RelayWeldingCheck == NO) {
+                    //        CheckRelayWeldingStatus(i);
+                    //    }
+                    //} else {
+                    _chargingData[i]->RelayWeldingCheck = YES;
+                    //}
+
+                    if (_chargingData[i]->SystemStatus == S_CHARGING) {
+                        CheckOutputPowerOverCarReq(i);
+                        //CheckOutputVolNoneMatchFire(i);
+                    } else {
+                        _isOutputNoneMatch[i] = NO;
+                    }
+                } else {
+                    _chargingData[i]->IsReadyToCharging = NO;
+                }
+            }
+
+            // Cable check (Get)
+            GetGfdAdc();
+
+            // 橋接 relay
+            SetParalleRelayStatus();
+
+            // 搭上 AC Contactor
+            //if (isCharging) {
+            //    outputRelay.relay_event.bits.AC_Contactor = YES;
+            //} else {
+            //    outputRelay.relay_event.bits.AC_Contactor = NO;
+            //}
+
+            if (isCharging ||
+                    (ShmPsuData->Work_Step >= _TEST_MODE &&
+                     ShmPsuData->Work_Step <= _TEST_MODE)) {
+                isStopChargingCount = false;
+                outputRelay.relay_event.bits.AC_Contactor = YES;
+            } else {
+                if (!isStopChargingCount) {
+                    gettimeofday(&_close_ac_contactor, NULL);
+                    isStopChargingCount = true;
+                } else {
+                    if ((outputRelay.relay_event.bits.AC_Contactor == YES &&
+                            GetTimeoutValue(_close_ac_contactor) / 1000 >= (TEN_MINUTES * 1000))) {
+                        outputRelay.relay_event.bits.AC_Contactor = NO;
+                    }
+                }
+            }
+
+            if (ShmPsuData->Work_Step >= _TEST_MODE && ShmPsuData->Work_Step <= _TEST_MODE) {
+                outputRelay.relay_event.bits.Gun1_N = outputRelay.relay_event.bits.Gun1_P = YES;
+            }
+
+            // 搭上/鬆開 Relay
+            if (IsNoneMatchRelayStatus()) {
+                if (Config_Relay_Output(Uart5Fd, ADDR_RELAY, &outputRelay)) {
+                    //regRelay.relay_event.bits.AC_Contactor = ShmSysConfigAndInfo->SysInfo.AcContactorStatus;
+                    regRelay.relay_event.bits.CCS_Precharge = outputRelay.relay_event.bits.CCS_Precharge;
+                    regRelay.relay_event.bits.Gun1_P = outputRelay.relay_event.bits.Gun1_P;
+                    regRelay.relay_event.bits.Gun1_N = outputRelay.relay_event.bits.Gun1_N;
+                    regRelay.relay_event.bits.Gun2_P = outputRelay.relay_event.bits.Gun2_P;
+                    regRelay.relay_event.bits.Gun2_N = outputRelay.relay_event.bits.Gun2_N;
+                    regRelay.relay_event.bits.Gun1_Parallel_P = outputRelay.relay_event.bits.Gun1_Parallel_P;
+                    regRelay.relay_event.bits.Gun1_Parallel_N = outputRelay.relay_event.bits.Gun1_Parallel_N;
+
+                    //log_info("Match Relay, AC = %x, g1_p = %x, g1_n = %x, g2_p = %x, g2_n = %x, pre = %x, bri_p = %x, bri_n = %x \n",
+                    //            regRelay.relay_event.bits.AC_Contactor,
+                    //            regRelay.relay_event.bits.Gun1_P,
+                    //            regRelay.relay_event.bits.Gun1_N,
+                    //            regRelay.relay_event.bits.Gun2_P,
+                    //            regRelay.relay_event.bits.Gun2_N,
+                    //            regRelay.relay_event.bits.CCS_Precharge,
+                    //            regRelay.relay_event.bits.Gun1_Parallel_P,
+                    //            regRelay.relay_event.bits.Gun1_Parallel_N);
+
+                }
+            }
+        }
+
+#if !defined NO_FAN_BOARD && !defined DD360ComBox
+        if (ShmFanModuleData->SelfTest_Comp == YES ||
+                strlen((char *)ShmSysConfigAndInfo->SysInfo.FanModuleFwRev) != 0 ||
+                ShmSysConfigAndInfo->SysInfo.FanModuleFwRev[0] != '\0') {
+            ShmFanModuleData->SelfTest_Comp = YES;
+
+            if (GetTimeoutValue(_priority_time) / 1000 >= 1000) {
+                //GetPsuTempForFanSpeed();
+                GetFanSpeedByFunction();
+                GetFanSpeed();
+                ShmSysConfigAndInfo->SysInfo.SystemFanRotaSpeed = _setFanSpeed;
+                gettimeofday(&_priority_time, NULL);
+
+                ShmFanModuleData->SetFan1Speed = ShmFanModuleData->TestFanSpeed;
+                ShmFanModuleData->SetFan2Speed = ShmFanModuleData->TestFanSpeed;
+                ShmFanModuleData->SetFan3Speed = ShmFanModuleData->TestFanSpeed;
+                ShmFanModuleData->SetFan4Speed = ShmFanModuleData->TestFanSpeed;
+
+                //log_info("set fan = %d \n", ShmFanModuleData->SetFan1Speed);
+                SetFanModuleSpeed();
+            }
+        }
+#endif //NO_FAN_BOARD
+
+#if !defined DD360ComBox
+        if (ShmLedModuleData->SelfTest_Comp == YES) {
+            if (GetTimeoutValue(_led_priority_time) / 1000 >= 1000) {
+                if (gunCount == 1) {
+                    SetLedColor(_chargingData[0], _chargingData[0]);
+                } else if (gunCount == 2) {
+                    SetLedColor(_chargingData[0], _chargingData[1]);
+                }
+
+                gettimeofday(&_led_priority_time, NULL);
+            }
+        }
+#endif //defined DD360ComBox
+
+        usleep(10000);
+    }
+
+    return FAIL;
+}

+ 1914 - 1913
EVSE/Projects/DD360Tcci/Apps/ModuleInternalComm/RelayBoard.c

@@ -1,1913 +1,1914 @@
-#include <stdio.h>      /*標準輸入輸出定義*/
-#include <stdlib.h>     /*標準函數庫定義*/
-#include <string.h>
-#include <stdint.h>
-#include <time.h>
-#include <unistd.h>
-
-#include <sys/time.h>
-#include <sys/timeb.h>
-
-#include "../ShareMemory/shmMem.h"
-#include "../Config.h"
-#include "../Log/log.h"
-#include "Module_InternalComm.h"
-#include "internalComm.h"
-
-//------------------------------------------------------------------------------
-static struct SysConfigData *pSysConfig = NULL;
-static struct SysInfoData *pSysInfo = NULL;
-static struct AlarmCodeData *pAlarmCode = NULL;
-static struct RelayModuleData *ShmRelayModuleData = NULL;
-static struct PsuData *ShmPsuData = NULL;
-static struct PrimaryMcuData *ShmPrimaryMcuData = NULL;
-static DcCommonInfo *ShmDcCommonData = NULL;
-static struct WARNING_CODE_INFO *pSysWarning = NULL;
-static struct LedModuleData *ShmLedModuleData = NULL;
-static struct FanModuleData *ShmFanModuleData = NULL;
-
-static Relay outputRelay = {0};
-static Relay regRelay = {0};
-static int Uart5Fd = 0;
-static struct timespec gFanBoardRunTimer;
-static uint16_t _setFanSpeed = 0;
-static uint16_t fanSpeedSmoothValue = 500;
-
-static Led_Color cur_led_color = {COLOR_MIN_LV};
-static Led_Color led_color;
-static struct timespec _led_priority_time;
-int ReservationLed;
-time_t ReservationFlashTimer;
-bool _show_GFD_Warming[2] = {TRUE};
-//static bool _isRelayWelding[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
-//static struct timeval _checkRelayWeldingTimer[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
-
-//static bool _isOutputNoneMatch[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
-//static struct timeval _checkOutputNoneMatchTimer[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
-
-static bool _isOvpChkTimeFlag[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY]; //DS60-120 add
-static struct timespec _checkOutputVolProtectTimer[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY]; //DS60-120 add
-
-static void SetLedColor(void);
-static struct timespec _close_ac_contactor;
-
-//------------------------------------------------------------------------------
-static void RunForceStopProcess(void)
-{
-    static bool isCriticalStop = NO;
-    static struct timespec  _psuCriticalStop;
-    uint32_t _timebuf;
-
-    if (isCriticalStop == NO) {
-        isCriticalStop = YES;
-        GetClockTime(&_psuCriticalStop, NULL);
-    } else {
-        _timebuf = GetClockTimeoutValue(_psuCriticalStop);
-
-        if (_timebuf < 0) {
-            GetClockTime(&_psuCriticalStop, NULL);
-        } else {
-            if (_timebuf / 1000 >= (FORCE_STOP_TIME * 1000)) {
-                isCriticalStop = NO;
-                pAlarmCode->AlarmEvents.bits.PsuFailureAlarm = NORMAL;
-            }
-        }
-    }
-}
-
-static void StopCheckRelayInfo(uint8_t _chkIndex)
-{
-    if (ShmDcCommonData->CheckRelayStatus[_chkIndex] != STOP) {
-        ShmDcCommonData->CheckRelayStatus[_chkIndex] = STOP;
-    }
-}
-
-static void StartCheckRelayInfo(uint8_t _chkIndex, uint8_t toState)
-{
-    // SMR1 *2 + SMR2 * 2 + Parallel * 2
-    static struct timespec lastCheckRelayStateTimer[6] = {0};
-    //uint8_t *pCheckRelayState = (uint8_t *)ShmDcCommonData->CheckRelayStatus[_chkIndex];
-
-    if (ShmDcCommonData->CheckRelayStatus[_chkIndex] == STOP) {
-        GetClockTime(&lastCheckRelayStateTimer[_chkIndex], NULL);
-        ShmDcCommonData->CheckRelayStatus[_chkIndex] = START;
-    } else {
-        if ((GetClockTimeoutValue(lastCheckRelayStateTimer[_chkIndex]) / 1000000) >= 1) {
-            //log_info("relay welding or driving fault = %d ", _chkIndex);
-            if (toState == 1) {
-                ShmDcCommonData->CheckRelayStatus[_chkIndex] = RELAY_STATUS_ERROR_DRIVING;
-            } else {
-                ShmDcCommonData->CheckRelayStatus[_chkIndex] = RELAY_STATUS_ERROR_WELDING;
-            }
-            GetClockTime(&lastCheckRelayStateTimer[_chkIndex], NULL);
-        }
-    }
-}
-
-static uint8_t getCommTargetID(uint8_t index)
-{
-    uint8_t targetID = 0;
-    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);
-
-    if (pSysConfig->TotalConnectorCount == 1) {
-        if (strncmp((char *)&pSysConfig->ModelName[7], "0", 1) != 0) {
-            targetID = 0x01;
-        } else if (strncmp((char *)&pSysConfig->ModelName[9], "0", 1) != 0) {
-            targetID = 0x02;
-        }
-    } else {
-        targetID = pDcChargingInfo->Evboard_id;
-    }
-
-    return targetID;
-}
-
-/*static void MatchRelayStatus(void)
-{
-    // 因為 AC Contactor 沒有 Feedback,所以暫時先這樣處理
-    //regRelay.relay_event.bits.AC_Contactor = outputRelay.relay_event.bits.AC_Contactor;
-    //pSysInfo->AcContactorStatus =
-    //    regRelay.relay_event.bits.AC_Contactor =
-    //        outputRelay.relay_event.bits.AC_Contactor;
-    regRelay.relay_event.bits.CCS_Precharge = outputRelay.relay_event.bits.CCS_Precharge;
-    regRelay.relay_event.bits.Gun1_P = outputRelay.relay_event.bits.Gun1_P;
-    regRelay.relay_event.bits.Gun1_N = outputRelay.relay_event.bits.Gun1_N;
-    regRelay.relay_event.bits.Gun2_P = outputRelay.relay_event.bits.Gun2_P;
-    regRelay.relay_event.bits.Gun2_N = outputRelay.relay_event.bits.Gun2_N;
-    regRelay.relay_event.bits.Gun1_Parallel_P = outputRelay.relay_event.bits.Gun1_Parallel_P;
-    regRelay.relay_event.bits.Gun1_Parallel_N = outputRelay.relay_event.bits.Gun1_Parallel_N;
-}
-*/
-
-static bool IsNoneMatchRelayStatus(void)
-{
-    bool result = false;
-
-    if (
-#if !defined DD360Tcci && !defined DD360Audi && !defined DD360ComBox && !defined DD360UCar
-        (regRelay.relay_event.bits.AC_Contactor != outputRelay.relay_event.bits.AC_Contactor) ||
-        (regRelay.relay_event.bits.CCS_Precharge != outputRelay.relay_event.bits.CCS_Precharge) ||
-#endif //!defined DD360Tcci && !defined DD360Audi
-        (regRelay.relay_event.bits.Gun1_P != outputRelay.relay_event.bits.Gun1_P) ||
-        (regRelay.relay_event.bits.Gun1_N != outputRelay.relay_event.bits.Gun1_N) ||
-        (regRelay.relay_event.bits.Gun2_P != outputRelay.relay_event.bits.Gun2_P) ||
-        (regRelay.relay_event.bits.Gun2_N != outputRelay.relay_event.bits.Gun2_N)
-#if !defined DD360Tcci && !defined DD360Audi && !defined DD360ComBox && !defined DD360UCar
-        ||
-        (regRelay.relay_event.bits.Gun1_Parallel_P != outputRelay.relay_event.bits.Gun1_Parallel_P) ||
-        (regRelay.relay_event.bits.Gun1_Parallel_N != outputRelay.relay_event.bits.Gun1_Parallel_N)
-#endif //!defined DD360Tcci && !defined DD360Audi
-    ) {
-        result = true;
-    }
-
-#if !defined DD360Tcci && !defined DD360Audi && !defined DD360ComBox && !defined DD360UCar
-    if (regRelay.relay_event.bits.AC_Contactor != outputRelay.relay_event.bits.AC_Contactor) {
-        log_info("AC Contact Relay none match. ");
-    }
-
-    if (regRelay.relay_event.bits.CCS_Precharge != outputRelay.relay_event.bits.CCS_Precharge) {
-        log_info("CCS Precharge Relay none match. ");
-    }
-#endif //
-
-    if (regRelay.relay_event.bits.Gun1_P != outputRelay.relay_event.bits.Gun1_P) {
-        //log_info("SMR1:D+ Relay none match. ");
-        StartCheckRelayInfo(RELAY_SMR1_P_STATUS, outputRelay.relay_event.bits.Gun1_P);
-    } else {
-        StopCheckRelayInfo(RELAY_SMR1_P_STATUS);
-    }
-
-    if (regRelay.relay_event.bits.Gun1_N != outputRelay.relay_event.bits.Gun1_N) {
-        //log_info("SMR1:D- Relay none match. ");
-        StartCheckRelayInfo(RELAY_SMR1_N_STATUS, outputRelay.relay_event.bits.Gun1_N);
-    } else {
-        StopCheckRelayInfo(RELAY_SMR1_N_STATUS);
-    }
-
-    if (regRelay.relay_event.bits.Gun2_P != outputRelay.relay_event.bits.Gun2_P) {
-        //log_info("SMR2:D+ Relay none match. ");
-        StartCheckRelayInfo(RELAY_SMR2_P_STATUS, outputRelay.relay_event.bits.Gun2_P);
-    } else {
-        StopCheckRelayInfo(RELAY_SMR2_P_STATUS);
-    }
-
-    if (regRelay.relay_event.bits.Gun2_N != outputRelay.relay_event.bits.Gun2_N) {
-        //log_info("SMR2:D- Relay none match. ");
-        StartCheckRelayInfo(RELAY_SMR2_N_STATUS, outputRelay.relay_event.bits.Gun2_N);
-    } else {
-        StopCheckRelayInfo(RELAY_SMR2_N_STATUS);
-    }
-
-#if !defined DD360Tcci && !defined DD360Audi && !defined DD360ComBox && !defined DD360UCar
-    if (regRelay.relay_event.bits.Gun1_Parallel_P != outputRelay.relay_event.bits.Gun1_Parallel_P) {
-        //log_info("Parallel:D+ Relay none match. ");
-        StartCheckRelayInfo(RELAY_PARA_P_STATUS, outputRelay.relay_event.bits.Gun1_Parallel_P);
-    } else {
-        StopCheckRelayInfo(RELAY_PARA_P_STATUS);
-    }
-
-    if (regRelay.relay_event.bits.Gun1_Parallel_N != outputRelay.relay_event.bits.Gun1_Parallel_N) {
-        //log_info("Parallel:D- Relay none match. ");
-        StartCheckRelayInfo(RELAY_PARA_N_STATUS, outputRelay.relay_event.bits.Gun1_Parallel_N);
-    } else {
-        StopCheckRelayInfo(RELAY_PARA_N_STATUS);
-    }
-#endif //
-
-    return result;
-}
-
-static void SetParalleRelayStatus(void)
-{
-#if defined DD360Tcci || defined DD360Audi || defined DD360ComBox || defined DD360UCar
-    return;
-#endif //!defined  DD360Tcci || !defined DD360Audi || !defined DD360ComBox
-
-    struct ChargingInfoData *pDcChargingInfo0 = (struct ChargingInfoData *)GetDcChargingInfoData(0);
-    struct ChargingInfoData *pDcChargingInfo1 = (struct ChargingInfoData *)GetDcChargingInfoData(1);
-
-    // 之後雙槍單模機種,橋接都會上
-    if (pSysConfig->TotalConnectorCount >= 2) {
-        if (pDcChargingInfo0->SystemStatus == S_BOOTING || pDcChargingInfo1->SystemStatus == S_BOOTING ||
-                (pDcChargingInfo0->SystemStatus == S_IDLE && pDcChargingInfo1->SystemStatus == S_IDLE)) {
-            // 初始化~ 不搭橋接
-            if (regRelay.relay_event.bits.Gun1_Parallel_P == YES) {
-                outputRelay.relay_event.bits.Gun1_Parallel_P = NO;
-            } else if (regRelay.relay_event.bits.Gun1_Parallel_N == YES) {
-                outputRelay.relay_event.bits.Gun1_Parallel_N = NO;
-            }
-        } else {
-            if (pDcChargingInfo0->IsReadyToCharging == YES ||
-                    pDcChargingInfo1->IsReadyToCharging == YES) {
-                // ************需考慮在切換中 - 切開 relay 與搭回 relay 的時機點************
-                if (pSysInfo->MainChargingMode == _MAIN_CHARGING_MODE_MAX) {
-                    if (pSysInfo->ReAssignedFlag < _REASSIGNED_RELAY_M_TO_A) {
-                        // 最大充 - 搭上橋接
-                        if (regRelay.relay_event.bits.Gun1_Parallel_N == NO) {
-                            outputRelay.relay_event.bits.Gun1_Parallel_N = YES;
-                        } else if (regRelay.relay_event.bits.Gun1_Parallel_P == NO) {
-                            outputRelay.relay_event.bits.Gun1_Parallel_P = YES;
-                        }
-                    } else {
-                        // 平均充 - 不搭
-                        if (regRelay.relay_event.bits.Gun1_Parallel_P == YES) {
-                            outputRelay.relay_event.bits.Gun1_Parallel_P = NO;
-                        } else if (regRelay.relay_event.bits.Gun1_Parallel_N == YES) {
-                            outputRelay.relay_event.bits.Gun1_Parallel_N = NO;
-                        }
-                    }
-                } else if (pSysInfo->MainChargingMode == _MAIN_CHARGING_MODE_AVER) {
-                    if (pSysInfo->ReAssignedFlag < _REASSIGNED_RELAY_A_TO_M) {
-                        // 平均充 - 不搭
-                        if (regRelay.relay_event.bits.Gun1_Parallel_P == YES) {
-                            outputRelay.relay_event.bits.Gun1_Parallel_P = NO;
-                        } else if (regRelay.relay_event.bits.Gun1_Parallel_N == YES) {
-                            outputRelay.relay_event.bits.Gun1_Parallel_N = NO;
-                        }
-                    } else {
-                        // 最大充 - 搭上橋接
-                        if (regRelay.relay_event.bits.Gun1_Parallel_N == NO) {
-                            outputRelay.relay_event.bits.Gun1_Parallel_N = YES;
-                        } else if (regRelay.relay_event.bits.Gun1_Parallel_P == NO) {
-                            outputRelay.relay_event.bits.Gun1_Parallel_P = YES;
-                        }
-                    }
-                }
-            }
-        }
-    }
-}
-
-static void GetGfdAdc(void)
-{
-    int gunIndex = 0;
-    uint8_t targetID = 0;
-    struct ChargingInfoData *pDcChargingInfo = NULL;
-    Gfd gfd_adc = {0};
-
-    // define : 每 0.2 ~ 1 秒一次
-    // occur : <= 75k 歐姆 @ 150 - 750 Vdc
-    // warning : >= 100 歐姆 && <= 500 歐姆 @ 150-750 Vdc
-    if (Query_Gfd_Adc(Uart5Fd, ADDR_RELAY, &gfd_adc) == PASS) {
-        for (gunIndex = 0; gunIndex < pSysConfig->TotalConnectorCount; gunIndex++) {
-            pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-
-            if (pDcChargingInfo->Type == 0x09 &&
-                    !pSysConfig->AlwaysGfdFlag
-               ) {
-                if ((pDcChargingInfo->PresentChargingVoltage * 10) >= VOUT_MIN_VOLTAGE) {
-                    pDcChargingInfo->GroundFaultStatus = GFD_PASS;
-                }
-                continue;
-            }
-
-            targetID = getCommTargetID(gunIndex);
-
-            if (targetID == 0x01) {
-                //if (gfd_adc.result_conn1 == GFD_WARNING) {
-                //    gfd_adc.result_conn1 = GFD_PASS;
-                //}
-
-                pDcChargingInfo->GroundFaultStatus = gfd_adc.result_conn1;
-                //log_info("GFD ******** Result = %d, Step = %d, R = %d, Vol = %d ",
-                //            pDcChargingInfo->GroundFaultStatus,
-                //            gfd_adc.rb_step_1,
-                //            gfd_adc.Resister_conn1,
-                //            gfd_adc.voltage_conn1);
-                if (pDcChargingInfo->GroundFaultStatus == GFD_FAIL) {
-                    log_info("GFD Fail. index = %d, Step = %d, R = %d, Vol = %d ",
-                             gunIndex,
-                             gfd_adc.rb_step_1,
-                             gfd_adc.Resister_conn1,
-                             gfd_adc.voltage_conn1);
-
-                } else if (pDcChargingInfo->GroundFaultStatus == GFD_PASS ||
-                           pDcChargingInfo->GroundFaultStatus == GFD_WARNING
-                          ) {
-                    if (pDcChargingInfo->GroundFaultStatus == GFD_WARNING && _show_GFD_Warming[gunIndex]) {
-                        log_info("GFD Warning. index = %d, Result = %d, R = %d, Vol = %d ",
-                                 gunIndex,
-                                 pDcChargingInfo->GroundFaultStatus,
-                                 gfd_adc.Resister_conn1,
-                                 gfd_adc.voltage_conn1);
-                        _show_GFD_Warming[gunIndex] = FALSE;
-                    }
-                }
-            } else if (targetID == 0x02) {
-                //if (gfd_adc.result_conn2 == GFD_WARNING) {
-                //    gfd_adc.result_conn2 = GFD_PASS;
-                //}
-                pDcChargingInfo->GroundFaultStatus = gfd_adc.result_conn2;
-                if (pDcChargingInfo->GroundFaultStatus == GFD_FAIL) {
-                    log_info("GFD Fail. index = %d, Step = %d, R = %d, Vol = %d ",
-                             gunIndex,
-                             gfd_adc.rb_step_2,
-                             gfd_adc.Resister_conn2,
-                             gfd_adc.voltage_conn2);
-                } else if (pDcChargingInfo->GroundFaultStatus == GFD_PASS ||
-                           pDcChargingInfo->GroundFaultStatus == GFD_WARNING
-                          ) {
-                    if (pDcChargingInfo->GroundFaultStatus == GFD_WARNING && _show_GFD_Warming[gunIndex]) {
-                        log_info("GFD Warning. index = %d, Result = %d, R = %d, Vol = %d ",
-                                 gunIndex,
-                                 pDcChargingInfo->GroundFaultStatus,
-                                 gfd_adc.Resister_conn1,
-                                 gfd_adc.voltage_conn1);
-                        _show_GFD_Warming[gunIndex] = FALSE;
-                    }
-                }
-            }
-        }
-    }
-}
-
-void CheckOutputPowerOverCarReq(uint8_t index)
-{
-    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);
-
-    float fireV = pDcChargingInfo->FireChargingVoltage;
-    float carV = pDcChargingInfo->EvBatteryMaxVoltage * 10;
-
-    if ((pDcChargingInfo->EvBatterytargetVoltage * 10) > 1500 &&
-            (pDcChargingInfo->Type == _Type_Chademo ||
-             pDcChargingInfo->Type == _Type_CCS_2 ||
-             pDcChargingInfo->Type == _Type_GB)) {
-        if (fireV >= (carV + (carV * 0.02))) {
-            if (!_isOvpChkTimeFlag[index]) {
-                if ((pDcChargingInfo->PresentChargingVoltage * 10) >= VOUT_MIN_VOLTAGE * 10) {
-                    GetClockTime(&_checkOutputVolProtectTimer[index], NULL);
-                    _isOvpChkTimeFlag[index] = YES;
-                }
-            } else {
-                log_info("[Module_InternalComm]CheckOutputPowerOverCarReq NG : fire = %f, battery = %f ",
-                         pDcChargingInfo->FireChargingVoltage,
-                         (pDcChargingInfo->EvBatterytargetVoltage * 10));
-
-                log_error("[Module_InternalComm]CheckOutputPowerOverCarReq NG : fire = %f, battery = %f ",
-                          pDcChargingInfo->FireChargingVoltage,
-                          (pDcChargingInfo->EvBatterytargetVoltage * 10));
-                if ((GetClockTimeoutValue(_checkOutputVolProtectTimer[index]) / 1000) >= OUTPUT_VOL_CHK_TIME) {
-                    if (pDcChargingInfo->Type == _Type_Chademo) {
-                        //pAlarmCode->AlarmEvents.bits.SystemChademoOutputOVP = YES;
-                        ShmDcCommonData->ConnectErrList[index].GunBits.ChaConnectOVP = YES;
-                    } else if (pDcChargingInfo->Type == _Type_CCS_2) {
-                        //pAlarmCode->AlarmEvents.bits.SystemCcsOutputOVP = YES;
-                        ShmDcCommonData->ConnectErrList[index].GunBits.CCSConnectOVP = YES;
-                    } else if (pDcChargingInfo->Type == _Type_GB) {
-                        //pAlarmCode->AlarmEvents.bits.SystemGbOutputOVP = YES;
-                        ShmDcCommonData->ConnectErrList[index].GunBits.GBTConnectOVP = YES;
-                    }
-                    //pDcChargingInfo->StopChargeFlag = YES;
-                }
-            }
-        } else {
-            if (_isOvpChkTimeFlag[index] == YES) {
-                _isOvpChkTimeFlag[index] = NO;
-            }
-        }
-    }
-}
-
-void ResetDetAlarmStatus(uint8_t gun)
-{
-    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gun);
-
-    if (pDcChargingInfo->Type == _Type_Chademo) {
-        if (pAlarmCode->AlarmEvents.bits.SystemChademoOutputOVP == YES) {
-            pAlarmCode->AlarmEvents.bits.SystemChademoOutputOVP = NO;
-        }
-    } else if (pDcChargingInfo->Type == _Type_GB) {
-        if (pAlarmCode->AlarmEvents.bits.SystemGbOutputOVP == YES) {
-            pAlarmCode->AlarmEvents.bits.SystemGbOutputOVP = NO;
-        }
-    } else if (pDcChargingInfo->Type == _Type_CCS_2) {
-        if (pAlarmCode->AlarmEvents.bits.SystemCcsOutputOVP == YES) {
-            pAlarmCode->AlarmEvents.bits.SystemCcsOutputOVP = NO;
-        }
-    }
-}
-
-void CheckAcInputOvpStatus(uint8_t index)
-{
-    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);
-
-    if (pAlarmCode->AlarmEvents.bits.SystemL1InputOVP == YES ||
-            pAlarmCode->AlarmEvents.bits.SystemL2InputOVP == YES ||
-            pAlarmCode->AlarmEvents.bits.SystemL3InputOVP == YES) {
-//      if ((pDcChargingInfo->SystemStatus >= S_PREPARNING && pDcChargingInfo->SystemStatus <= S_CHARGING) ||
-//              (pDcChargingInfo->SystemStatus >= S_CCS_PRECHARGE_ST0 && pDcChargingInfo->SystemStatus <= S_CCS_PRECHARGE_ST1))
-//      {
-//          if (pSysInfo->ChargerType == _CHARGER_TYPE_IEC)
-//          {
-//              if (_psuInputVolR > VIN_MAX_VOLTAGE_IEC ||
-//                      _psuInputVolS > VIN_MAX_VOLTAGE_IEC ||
-//                      _psuInputVolT > VIN_MAX_VOLTAGE_IEC)
-//              {
-//                  log_info("IEC _psuInputVolR = %f, _psuInputVolS = %f, _psuInputVolT = %f ",
-//                          _psuInputVolR, _psuInputVolS, _psuInputVolT);
-//                  pDcChargingInfo->StopChargeFlag = YES;
-//              }
-//
-//          }
-//          else if (pSysInfo->ChargerType == _CHARGER_TYPE_UL)
-//          {
-//              if (_psuInputVolR > VIN_MAX_VOLTAGE_UL ||
-//                      _psuInputVolS > VIN_MAX_VOLTAGE_UL ||
-//                      _psuInputVolT > VIN_MAX_VOLTAGE_UL)
-//              {
-//                  log_info("UL _psuInputVolR = %f, _psuInputVolS = %f, _psuInputVolT = %f ",
-//                          _psuInputVolR, _psuInputVolS, _psuInputVolT);
-//                  pDcChargingInfo->StopChargeFlag = YES;
-//              }
-//          }
-//      }
-//      else
-        log_info("CheckAcInputOvpStatus");
-        pDcChargingInfo->StopChargeFlag = YES;
-    }
-}
-
-//void CheckOutputVolNoneMatchFire(uint8_t index)
-//{
-//    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);
-//
-//    if ((pDcChargingInfo->EvBatterytargetVoltage * 10) > 1500 &&
-//            (pDcChargingInfo->Type == _Type_Chademo ||
-//             pDcChargingInfo->Type == _Type_CCS_2 ||
-//             pDcChargingInfo->Type == _Type_GB)) {
-//        if (((pDcChargingInfo->PresentChargingVoltage * 10) < pDcChargingInfo->FireChargingVoltage - 300) ||
-//                ((pDcChargingInfo->PresentChargingVoltage * 10) > pDcChargingInfo->FireChargingVoltage + 300)) {
-//            if (!_isOutputNoneMatch[index]) {
-//                _isOutputNoneMatch[index] = YES;
-//                GetClockTime(&_checkOutputNoneMatchTimer[index], NULL);
-//            } else {
-//                if ((GetClockTimeoutValue(_checkOutputNoneMatchTimer[index]) / 1000) >= 5000) {
-//                    /*log_info("[Module_InternalComm]CheckOutputVolNoneMatchFire NG (%d) : pre = %f, fire = %f ",
-//                            index, (pDcChargingInfo->PresentChargingVoltage * 10), pDcChargingInfo->FireChargingVoltage);
-//                    log_error("[Module_InternalComm]CheckOutputVolNoneMatchFire NG (%d): pre = %f, fire = %f ",
-//                            index, (pDcChargingInfo->PresentChargingVoltage * 10), pDcChargingInfo->FireChargingVoltage);
-//                    pDcChargingInfo->StopChargeFlag = YES;*/
-//                }
-//            }
-//        } else {
-//            _isOutputNoneMatch[index] = NO;
-//        }
-//    }
-//}
-
-void CheckPhaseLossStatus(uint8_t index)
-{
-    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);
-
-    if (pAlarmCode->AlarmEvents.bits.SystemL1InputUVP == YES ||
-            pAlarmCode->AlarmEvents.bits.SystemL2InputUVP == YES ||
-            pAlarmCode->AlarmEvents.bits.SystemL3InputUVP == YES) {
-        log_info("CheckPhaseLossStatus");
-        pDcChargingInfo->StopChargeFlag = YES;
-    }
-}
-
-void SetK1K2RelayStatus(uint8_t index)
-{
-    uint8_t targetID = 0;
-    PreChargingState *pRegPreChargingState = NULL;
-    PreChargingState *pOutputPreChargingState = NULL;
-    GunPNState *pRegGunPNState = NULL;
-    GunPNState *pOutputGunPNState = NULL;
-    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);
-
-    if (ShmPsuData->Work_Step >= _TEST_MODE &&
-            ShmPsuData->Work_Step <= _TEST_MODE) {
-        if (regRelay.relay_event.bits.Gun1_N == NO) {
-            outputRelay.relay_event.bits.Gun1_N = YES;
-        } else if (regRelay.relay_event.bits.Gun1_P == NO) {
-            outputRelay.relay_event.bits.Gun1_P = YES;
-        }
-        return;
-    }
-
-    targetID = getCommTargetID(index);
-
-    pRegPreChargingState = (PreChargingState *)&regRelay.relay_event.relay_status[0];
-    pOutputPreChargingState = (PreChargingState *)&outputRelay.relay_event.relay_status[0];
-    if (targetID == 0x01) {
-        pRegGunPNState = (GunPNState *)&regRelay.relay_event.relay_status[1];
-        pOutputGunPNState = (GunPNState *)&outputRelay.relay_event.relay_status[1];
-    } else if (targetID == 0x02) {
-        pRegGunPNState = (GunPNState *)&regRelay.relay_event.relay_status[2];
-        pOutputGunPNState = (GunPNState *)&outputRelay.relay_event.relay_status[2];
-    }
-
-    switch (pDcChargingInfo->SystemStatus) {
-    case S_BOOTING:
-    case S_IDLE:
-    case S_AUTHORIZING:
-    case S_REASSIGN_CHECK:
-    case S_REASSIGN:
-    case S_PREPARNING:
-    case S_PREPARING_FOR_EV:
-        if (pRegGunPNState->GunP == YES) {
-            pOutputGunPNState->GunP = NO;
-        } else if (pRegGunPNState->GunN == YES) {
-            pOutputGunPNState->GunN = NO;
-        }
-
-        if (targetID == 0x02 && pDcChargingInfo->Type == _Type_CCS_2) {
-            if (pRegPreChargingState->CcsPrecharge == YES) {
-                pOutputPreChargingState->CcsPrecharge = NO;
-            }
-        }
-        break;
-
-    case S_PREPARING_FOR_EVSE:
-    case S_CHARGING:
-        //if (pDcChargingInfo->RelayWeldingCheck != YES) {
-        //    break;
-        //}
-        if (pRegGunPNState->GunN == NO) {
-            if (pDcChargingInfo->GroundFaultStatus != GFD_FAIL) {
-                pOutputGunPNState->GunN = YES;
-            } else {
-                pOutputGunPNState->GunN = NO;
-            }
-        } else {
-            if (pDcChargingInfo->GroundFaultStatus == GFD_FAIL) {
-                pOutputGunPNState->GunN = NO;
-            }
-        }
-        if (pRegGunPNState->GunP == NO) {
-            if (pDcChargingInfo->GroundFaultStatus != GFD_FAIL) {
-                pOutputGunPNState->GunP = YES;
-            } else {
-                pOutputGunPNState->GunP = NO;
-            }
-        } else {
-            if (pDcChargingInfo->GroundFaultStatus == GFD_FAIL) {
-                pOutputGunPNState->GunP = NO;
-            }
-        }
-        break;
-
-    case S_TERMINATING:
-    case S_COMPLETE:
-    case S_ALARM:
-        if ((pDcChargingInfo->PresentChargingCurrent * 10) <= SEFETY_SWITCH_RELAY_CUR) {
-            pOutputGunPNState->GunP = NO;
-            pOutputGunPNState->GunN = NO;
-        }
-        if (pDcChargingInfo->GroundFaultStatus == GFD_FAIL) {
-            pOutputGunPNState->GunP = NO;
-            pOutputGunPNState->GunN = NO;
-        }
-        break;
-
-    case S_CCS_PRECHARGE_ST0:
-#if defined DD360Tcci || defined DD360Audi || defined DD360ComBox || defined DD360UCar
-        break;
-#endif //defined DD360Tcci || defined DD360Audi || defined DD360ComBox
-
-        //if (pDcChargingInfo->Type == _Type_CCS_2 && targetID == 0x02) {
-        //    if (pRegPreChargingState->CcsPrecharge == NO) {
-        //        pOutputPreChargingState->CcsPrecharge = YES;
-        //    } else if (pRegPreChargingState->CcsPrecharge == YES) {
-        //        pRegGunPNState->GunP = NO;
-        //    }
-        //}
-        if (pDcChargingInfo->GroundFaultStatus == GFD_FAIL) {
-            pOutputGunPNState->GunP = NO;
-            pOutputGunPNState->GunN = NO;
-        }
-        break;
-
-    case S_CCS_PRECHARGE_ST1:
-#if defined DD360Tcci || defined DD360Audi || defined DD360ComBox || defined DD360UCar
-        break;
-#endif //defined DD360Tcci || defined DD360Audi || defined DD360ComBox
-
-        //if (pDcChargingInfo->Type == _Type_CCS_2 && targetID == 0x02) {
-        //    if (pRegGunPNState->GunP == NO) {
-        //        pOutputGunPNState->GunP = YES;
-        //    } else if (pRegGunPNState->GunP == YES) {
-        //        pOutputPreChargingState->CcsPrecharge = NO;
-        //    }
-        //}
-        if (pDcChargingInfo->GroundFaultStatus == GFD_FAIL) {
-            pOutputGunPNState->GunP = NO;
-            pOutputGunPNState->GunN = NO;
-        }
-        break;
-    }
-}
-
-// 確認 K1 K2 relay 的狀態
-void CheckK1K2RelayOutput(uint8_t index)
-{
-    uint8_t targetID = 0;
-    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);
-
-    targetID = getCommTargetID(index);
-
-    switch (targetID) {
-    case 0x01:
-        if (regRelay.relay_event.bits.Gun1_N == YES && regRelay.relay_event.bits.Gun1_P == YES) {
-            pDcChargingInfo->RelayK1K2Status = YES;
-        } else {
-            pDcChargingInfo->RelayK1K2Status = NO;
-        }
-
-        if (pDcChargingInfo->Type == _Type_CCS_2) {
-#if !defined DD360Tcci && !defined DD360Audi && !defined DD360ComBox && !defined DD360UCar
-            if (regRelay.relay_event.bits.Gun1_N == YES && regRelay.relay_event.bits.CCS_Precharge == YES) {
-                pDcChargingInfo->RelayKPK2Status = YES;
-            } else {
-                pDcChargingInfo->RelayKPK2Status = NO;
-            }
-#else
-            if (pDcChargingInfo->SystemStatus == S_CCS_PRECHARGE_ST0) {
-                pDcChargingInfo->RelayKPK2Status = YES;
-            } else {
-                pDcChargingInfo->RelayKPK2Status = NO;
-            }
-#endif //!defined DD360Tcci && !defined DD360Audi
-        }
-        break;
-
-    case 0x02:
-        if (regRelay.relay_event.bits.Gun2_N == YES &&
-                regRelay.relay_event.bits.Gun2_P == YES) {
-            pDcChargingInfo->RelayK1K2Status = YES;
-        } else {
-            pDcChargingInfo->RelayK1K2Status = NO;
-        }
-
-        if (pDcChargingInfo->Type == _Type_CCS_2) {
-#if !defined DD360Tcci && !defined DD360Audi && !defined DD360ComBox && !defined DD360UCar
-            if (regRelay.relay_event.bits.Gun2_N == YES &&
-                    regRelay.relay_event.bits.CCS_Precharge == YES) {
-                pDcChargingInfo->RelayKPK2Status = YES;
-            } else {
-                pDcChargingInfo->RelayKPK2Status = NO;
-            }
-#else
-            if (pDcChargingInfo->SystemStatus == S_CCS_PRECHARGE_ST0) {
-                pDcChargingInfo->RelayKPK2Status = YES;
-            } else {
-                pDcChargingInfo->RelayKPK2Status = NO;
-            }
-#endif //!defined DD360Tcci && !defined DD360Audi
-        }
-        break;
-    }
-
-#if !defined DD360Tcci && !defined DD360Audi && !defined DD360ComBox && !defined DD360UCar
-    //DS60-120 add
-    if (pSysInfo->BridgeRelayStatus == YES) {
-        if (regRelay.relay_event.bits.Gun1_Parallel_N == NO &&
-                regRelay.relay_event.bits.Gun1_Parallel_P == NO) {
-            pSysInfo->BridgeRelayStatus = NO;
-        }
-    } else if (pSysInfo->BridgeRelayStatus == NO) {
-        if (regRelay.relay_event.bits.Gun1_Parallel_N == YES &&
-                regRelay.relay_event.bits.Gun1_Parallel_P == YES) {
-            pSysInfo->BridgeRelayStatus = YES;
-        }
-    }
-#else
-    pSysInfo->BridgeRelayStatus = YES;
-#endif //!defined DD360Tcci && !defined DD360Audi
-}
-
-void SetGfdConfig(uint8_t index, uint8_t resister)
-{
-    Gfd_config gfd_config = {
-        .index = index,
-        .state = resister,
-    };
-
-    //log_info("************************GFD Vol = %d, GFD Res = %d ", gfd_config.reqVol, gfd_config.resister);
-    if (Config_Gfd_Value(Uart5Fd, ADDR_RELAY, &gfd_config) == PASS) {
-//      log_info("Set reqVol = %f, resister = %d ",
-//              gfd_config.reqVol,
-//              gfd_config.resister);
-    }
-}
-
-void CableCheckDetected(uint8_t index)
-{
-    uint8_t targetID = 0;
-    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);
-    // Cable Check
-    // 當火線上的電壓 = 車端要求的電壓電流
-    // _chargingData[targetGun]->EvBatterytargetVoltage
-    // 才可以開始偵測 1s
-    // Warning : Rgfd <= 150 歐/V 假設電壓為 500V 則~ Rgfd <= 75000 歐
-    // Pre-Warning : 150 歐/V < Rgfd <= 500 歐/V 假設電壓為 500V 則 75000 歐 < Rgfd <= 250000
-    // SO Normal : Rgfd > 500 歐/V 假設電壓為 500 V 則 Rgfd > 250000 歐
-
-    if (pSysConfig->TotalConnectorCount == 1) {
-        if (strncmp((char *)&pSysConfig->ModelName[7], "0", 1) != 0) {
-            targetID = 0;
-        } else if (strncmp((char *)&pSysConfig->ModelName[9], "0", 1) != 0) {
-            targetID = 1;
-        }
-    } else {
-        targetID = index;
-    }
-
-    if ((pDcChargingInfo->Type >= _Type_Chademo &&
-            pDcChargingInfo->Type <= _Type_GB) ||
-            (pDcChargingInfo->Type == 0x09 &&
-             pSysConfig->AlwaysGfdFlag)
-       ) {
-        if ((pDcChargingInfo->SystemStatus >= S_PREPARING_FOR_EVSE &&
-                pDcChargingInfo->SystemStatus < S_TERMINATING) ||
-                (pDcChargingInfo->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
-                 pDcChargingInfo->SystemStatus <= S_CCS_PRECHARGE_ST1)
-           ) {
-            //if ((pDcChargingInfo->SystemStatus == S_PREPARING_FOR_EVSE) &&
-            //        (pDcChargingInfo->RelayWeldingCheck == YES)
-            //   ) {
-            if (pDcChargingInfo->SystemStatus == S_PREPARING_FOR_EVSE) {
-                SetGfdConfig(targetID, GFD_CABLECHK);
-            } else if ((pDcChargingInfo->SystemStatus >= S_CCS_PRECHARGE_ST0) &&
-                       (pDcChargingInfo->SystemStatus <= S_CCS_PRECHARGE_ST1)
-                      ) {
-                SetGfdConfig(targetID, GFD_PRECHARGE);
-            } else if ((pDcChargingInfo->SystemStatus >= S_CHARGING) &&
-                       (pDcChargingInfo->SystemStatus < S_TERMINATING)
-                      ) {
-                if ((pDcChargingInfo->Type == _Type_GB) ||
-                        (pDcChargingInfo->Type == _Type_Chademo)
-                   ) {
-                    SetGfdConfig(targetID, GFD_IDLE);
-                } else {
-                    SetGfdConfig(targetID, GFD_CHARGING);
-                }
-            }
-        }
-        else if(pDcChargingInfo->SystemStatus == S_TERMINATING || pDcChargingInfo->SystemStatus == S_ALARM)
-        {
-            if (pDcChargingInfo->Type == _Type_CCS_2)
-            {
-                SetGfdConfig(targetID, GFD_CHARGING);
-            }
-        } else {
-            SetGfdConfig(targetID, GFD_IDLE);
-        }
-    }
-}
-
-// 讀取 Relay 狀態
-void GetRelayOutputStatus(void)
-{
-    if (Query_Relay_Output(Uart5Fd, ADDR_RELAY, &regRelay) == PASS) {
-#if !defined DD360Tcci && !defined DD360Audi && !defined DD360ComBox && !defined DD360UCar
-        regRelay.relay_event.bits.AC_Contactor = pSysInfo->AcContactorStatus;
-#endif //!defined DD360Tcci && !defined DD360Audi
-    }
-}
-
-// AC 三相輸入電壓
-void GetPresentInputVol(void)
-{
-    static uint8_t _threePhaseOvp[3] = {0, 0, 0}; //DS60-120 add
-    static uint8_t _threePhaseUvp[3] = {0, 0, 0}; //DS60-120 add
-    PresentInputVoltage inputVoltage = {0};
-
-    if (Query_Present_InputVoltage(Uart5Fd, ADDR_RELAY, &inputVoltage) == PASS) {
-        // resolution : 0.1
-        pSysInfo->InputVoltageR = ShmRelayModuleData->InputL1Volt = inputVoltage.L1N_L12;
-        pSysInfo->InputVoltageS = ShmRelayModuleData->InputL2Volt = inputVoltage.L2N_L23;
-        pSysInfo->InputVoltageT = ShmRelayModuleData->InputL3Volt = inputVoltage.L3N_L31;
-
-        //********************************************************************************************************//
-        // Vin (UVP)
-        if (pSysInfo->ChargerType == _CHARGER_TYPE_IEC) {
-            if (pAlarmCode->AlarmEvents.bits.SystemL1InputUVP == NO) {
-                if (inputVoltage.L1N_L12 < VIN_MIN_VOLTAGE_IEC) {
-                    log_info("In Uvp L1N_L12 = %f ", inputVoltage.L1N_L12);
-                    if (_threePhaseUvp[0] >= OVP_UVP_CHK_COUNT) {
-                        pAlarmCode->AlarmEvents.bits.SystemL1InputUVP = YES;
-                    } else {
-                        _threePhaseUvp[0] += 1;
-                    }
-                }
-            } else {
-                if (inputVoltage.L1N_L12 > VIN_MIN_REV_VOLTAGE_IEC) {
-                    pAlarmCode->AlarmEvents.bits.SystemL1InputUVP = NO;
-                    _threePhaseUvp[0] = 0;
-                }
-            }
-
-            if (pAlarmCode->AlarmEvents.bits.SystemL2InputUVP == NO) {
-                if (inputVoltage.L2N_L23 < VIN_MIN_VOLTAGE_IEC) {
-                    log_info("In Uvp L2N_L23 = %f ", inputVoltage.L2N_L23);
-                    if (_threePhaseUvp[1] >= OVP_UVP_CHK_COUNT) {
-                        pAlarmCode->AlarmEvents.bits.SystemL2InputUVP = YES;
-                    } else {
-                        _threePhaseUvp[1] += 1;
-                    }
-                }
-            } else {
-                if (inputVoltage.L2N_L23 > VIN_MIN_REV_VOLTAGE_IEC) {
-                    pAlarmCode->AlarmEvents.bits.SystemL2InputUVP = NO;
-                    _threePhaseUvp[1] = 0;
-                }
-            }
-
-            if (pAlarmCode->AlarmEvents.bits.SystemL3InputUVP == NO) {
-                if (inputVoltage.L3N_L31 < VIN_MIN_VOLTAGE_IEC) {
-                    log_info("In Uvp L3N_L31 = %f ", inputVoltage.L3N_L31);
-                    if (_threePhaseUvp[2] >= OVP_UVP_CHK_COUNT) {
-                        pAlarmCode->AlarmEvents.bits.SystemL3InputUVP = YES;
-                    } else {
-                        _threePhaseUvp[2] += 1;
-                    }
-                }
-            } else {
-                if (inputVoltage.L3N_L31 > VIN_MIN_REV_VOLTAGE_IEC) {
-                    pAlarmCode->AlarmEvents.bits.SystemL3InputUVP = NO;
-                    _threePhaseUvp[2] = 0;
-                }
-            }
-        } else if (pSysInfo->ChargerType == _CHARGER_TYPE_UL) {
-            if (pAlarmCode->AlarmEvents.bits.SystemL1InputUVP == NO) {
-                if (inputVoltage.L1N_L12 < VIN_MIN_VOLTAGE_UL) {
-                    log_info("In Uvp L1N_L12 = %f ", inputVoltage.L1N_L12);
-                    if (_threePhaseUvp[0] >= OVP_UVP_CHK_COUNT) {
-                        pAlarmCode->AlarmEvents.bits.SystemL1InputUVP = YES;
-                    } else {
-                        _threePhaseUvp[0] += 1;
-                    }
-                }
-            } else {
-                if (inputVoltage.L1N_L12 > VIN_MIN_REV_VOLTAGE_UL) {
-                    pAlarmCode->AlarmEvents.bits.SystemL1InputUVP = NO;
-                    _threePhaseUvp[0] = 0;
-                }
-            }
-
-            if (pAlarmCode->AlarmEvents.bits.SystemL2InputUVP == NO) {
-                if (inputVoltage.L2N_L23 < VIN_MIN_VOLTAGE_UL) {
-                    log_info("In Uvp L2N_L23 = %f ", inputVoltage.L2N_L23);
-                    if (_threePhaseUvp[1] >= OVP_UVP_CHK_COUNT) {
-                        pAlarmCode->AlarmEvents.bits.SystemL2InputUVP = YES;
-                    } else {
-                        _threePhaseUvp[1] += 1;
-                    }
-                }
-            } else {
-                if (inputVoltage.L2N_L23 > VIN_MIN_REV_VOLTAGE_UL) {
-                    pAlarmCode->AlarmEvents.bits.SystemL2InputUVP = NO;
-                    _threePhaseUvp[1] = 0;
-                }
-            }
-
-            if (pAlarmCode->AlarmEvents.bits.SystemL3InputUVP == NO) {
-                if (inputVoltage.L3N_L31 < VIN_MIN_VOLTAGE_UL) {
-                    log_info("In Uvp L3N_L31 = %f ", inputVoltage.L3N_L31);
-                    if (_threePhaseUvp[2] >= OVP_UVP_CHK_COUNT) {
-                        pAlarmCode->AlarmEvents.bits.SystemL3InputUVP = YES;
-                    } else {
-                        _threePhaseUvp[2] += 1;
-                    }
-                }
-            } else {
-                if (inputVoltage.L3N_L31 > VIN_MIN_REV_VOLTAGE_UL) {
-                    pAlarmCode->AlarmEvents.bits.SystemL3InputUVP = NO;
-                    _threePhaseUvp[2] = 0;
-                }
-            }
-        }
-
-        //********************************************************************************************************//
-        // Vin (OVP)
-        if (pSysInfo->ChargerType == _CHARGER_TYPE_IEC) {
-            if (pAlarmCode->AlarmEvents.bits.SystemL1InputOVP == NO) {
-                if (inputVoltage.L1N_L12 > VIN_MAX_VOLTAGE_IEC) {
-                    log_info("In Ovp L1N_L12 = %f ", inputVoltage.L1N_L12);
-                    if (_threePhaseOvp[0] >= OVP_UVP_CHK_COUNT) {
-                        pAlarmCode->AlarmEvents.bits.SystemL1InputOVP = YES;
-                    } else {
-                        _threePhaseOvp[0] += 1;
-                    }
-                }
-            } else {
-                if (inputVoltage.L1N_L12 < VIN_MAX_REV_VOLTAGE_IEC) {
-                    pAlarmCode->AlarmEvents.bits.SystemL1InputOVP = NO;
-                    _threePhaseOvp[0] = 0;
-                }
-            }
-
-            if (pAlarmCode->AlarmEvents.bits.SystemL2InputOVP == NO) {
-                if (inputVoltage.L2N_L23 > VIN_MAX_VOLTAGE_IEC) {
-                    log_info("In Ovp L2N_L23 = %f ", inputVoltage.L2N_L23);
-                    if (_threePhaseOvp[1] >= OVP_UVP_CHK_COUNT) {
-                        pAlarmCode->AlarmEvents.bits.SystemL2InputOVP = YES;
-                    } else {
-                        _threePhaseOvp[1] += 1;
-                    }
-                }
-            } else {
-                if (inputVoltage.L2N_L23 < VIN_MAX_REV_VOLTAGE_IEC) {
-                    pAlarmCode->AlarmEvents.bits.SystemL2InputOVP = NO;
-                    _threePhaseOvp[1] = 0;
-                }
-            }
-
-            if (pAlarmCode->AlarmEvents.bits.SystemL3InputOVP == NO) {
-                if (inputVoltage.L3N_L31 > VIN_MAX_VOLTAGE_IEC) {
-                    log_info("In Ovp L3N_L31 = %f ", inputVoltage.L3N_L31);
-                    if (_threePhaseOvp[2] >= OVP_UVP_CHK_COUNT) {
-                        pAlarmCode->AlarmEvents.bits.SystemL3InputOVP = YES;
-                    } else {
-                        _threePhaseOvp[2] += 1;
-                    }
-                }
-            } else {
-                if (inputVoltage.L3N_L31 < VIN_MAX_REV_VOLTAGE_IEC) {
-                    pAlarmCode->AlarmEvents.bits.SystemL3InputOVP = NO;
-                    _threePhaseOvp[2] = 0;
-                }
-            }
-        } else if (pSysInfo->ChargerType == _CHARGER_TYPE_UL) {
-            if (pAlarmCode->AlarmEvents.bits.SystemL1InputOVP == NO) {
-                if (inputVoltage.L1N_L12 > VIN_MAX_VOLTAGE_UL) {
-                    log_info("In Ovp L1N_L12 = %f ", inputVoltage.L1N_L12);
-                    if (_threePhaseOvp[0] >= OVP_UVP_CHK_COUNT) {
-                        pAlarmCode->AlarmEvents.bits.SystemL1InputOVP = YES;
-                    } else {
-                        _threePhaseOvp[0] += 0;
-                    }
-                }
-            } else {
-                if (inputVoltage.L1N_L12 < VIN_MAX_REV_VOLTAGE_UL) {
-                    pAlarmCode->AlarmEvents.bits.SystemL1InputOVP = NO;
-                    _threePhaseOvp[0] = 0;
-                }
-            }
-
-            if (pAlarmCode->AlarmEvents.bits.SystemL2InputOVP == NO) {
-                if (inputVoltage.L2N_L23 > VIN_MAX_VOLTAGE_UL) {
-                    log_info("In Ovp L2N_L23 = %f ", inputVoltage.L2N_L23);
-                    if (_threePhaseOvp[1] >= OVP_UVP_CHK_COUNT) {
-                        pAlarmCode->AlarmEvents.bits.SystemL2InputOVP = YES;
-                    } else {
-                        _threePhaseOvp[1] += 0;
-                    }
-                }
-            } else {
-                if (inputVoltage.L2N_L23 < VIN_MAX_REV_VOLTAGE_UL) {
-                    pAlarmCode->AlarmEvents.bits.SystemL2InputOVP = NO;
-                    _threePhaseOvp[1] = 0;
-                }
-            }
-
-            if (pAlarmCode->AlarmEvents.bits.SystemL2InputOVP == NO) {
-                if (inputVoltage.L3N_L31 > VIN_MAX_VOLTAGE_UL) {
-                    log_info("In Ovp L3N_L31 = %f ", inputVoltage.L3N_L31);
-                    if (_threePhaseOvp[2] >= OVP_UVP_CHK_COUNT) {
-                        pAlarmCode->AlarmEvents.bits.SystemL3InputOVP = YES;
-                    } else {
-                        _threePhaseOvp[2] += 1;
-                    }
-                }
-            } else {
-                if (inputVoltage.L3N_L31 < VIN_MAX_REV_VOLTAGE_UL) {
-                    pAlarmCode->AlarmEvents.bits.SystemL3InputOVP = NO;
-                    _threePhaseOvp[2] = 0;
-                }
-            }
-        }
-    }
-}
-
-// 左右槍的 Relay 前後的輸出電壓
-void GetPersentOutputVol(void)
-{
-    uint8_t index = 0;
-    uint8_t targetID = 0;
-    struct ChargingInfoData *pDcChargingInfo = NULL;
-    PresentOutputVoltage outputVoltage = {0};
-
-    if (Query_Present_OutputVoltage(Uart5Fd, ADDR_RELAY, &outputVoltage) != PASS) {
-        return;
-    }
-
-    //log_info("Conn1 fuse 1 = %f ", outputVoltage.behindFuse_Voltage_C1);
-    //log_info("Conn1 relay 1 = %f ", outputVoltage.behindRelay_Voltage_C1);
-    //log_info("Conn2 fuse 2 = %f ", outputVoltage.behindFuse_Voltage_C2);
-    //log_info("Conn2 relay 2 = %f ", outputVoltage.behindRelay_Voltage_C2);
-
-    //log_info("outputVoltage.behindFuse_Voltage_C1 = %f ", outputVoltage.behindFuse_Voltage_C1);
-    //log_info("outputVoltage.behindFuse_Voltage_C2 = %f ", outputVoltage.behindFuse_Voltage_C2);
-
-    ShmRelayModuleData->Gun1FuseOutputVolt = outputVoltage.behindFuse_Voltage_C1;
-    ShmRelayModuleData->Gun1RelayOutputVolt = outputVoltage.behindRelay_Voltage_C1;
-    ShmRelayModuleData->Gun2FuseOutputVolt = outputVoltage.behindFuse_Voltage_C2;
-    ShmRelayModuleData->Gun2RelayOutputVolt = outputVoltage.behindRelay_Voltage_C2;
-
-    for (index = 0; index < pSysConfig->TotalConnectorCount; index++) {
-        pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);
-        targetID = getCommTargetID(index);
-
-        switch (targetID) {
-        case 0x01:
-#if defined DD360Tcci || defined DD360Audi || defined DD360ComBox || defined DD360UCar
-            pDcChargingInfo->FireChargingVoltage = ShmRelayModuleData->Gun1RelayOutputVolt;
-            pDcChargingInfo->PresentChargingCurrent = ((float)ShmRelayModuleData->Gun1FuseOutputVolt) / 10;
-            pDcChargingInfo->PresentChargingVoltage = ((float)pDcChargingInfo->FireChargingVoltage) / 10;
-            pDcChargingInfo->FuseChargingVoltage = pDcChargingInfo->FireChargingVoltage;
-            break;
-#endif //defined DD360Tcci || defined DD360Audi || defined DD360ComBox
-
-            pDcChargingInfo->FireChargingVoltage = ShmRelayModuleData->Gun1RelayOutputVolt;
-            pDcChargingInfo->FuseChargingVoltage = ShmRelayModuleData->Gun1FuseOutputVolt;
-            break;
-
-        case 0x02:
-#if defined DD360Tcci || defined DD360Audi || defined DD360ComBox
-            pDcChargingInfo->FireChargingVoltage = ShmRelayModuleData->Gun2RelayOutputVolt;
-            pDcChargingInfo->PresentChargingCurrent = ((float)ShmRelayModuleData->Gun2FuseOutputVolt) / 10;
-            pDcChargingInfo->PresentChargingVoltage = ((float)pDcChargingInfo->FireChargingVoltage) / 10;
-            pDcChargingInfo->FuseChargingVoltage = pDcChargingInfo->FireChargingVoltage;
-            break;
-#endif //defined DD360Tcci || defined DD360Audi || defined DD360ComBox
-
-            pDcChargingInfo->FireChargingVoltage = ShmRelayModuleData->Gun2RelayOutputVolt;
-            pDcChargingInfo->FuseChargingVoltage = ShmRelayModuleData->Gun2FuseOutputVolt;
-            break;
-        }
-
-        //log_info("%d persent vol = %f, cur = %f",
-        //         index,
-        //         pDcChargingInfo->PresentChargingVoltage,
-        //         pDcChargingInfo->PresentChargingCurrent);
-
-        //unsigned short Ovp = 0;
-        //unsigned short Ocp = 0;
-        //Ovp = MIN [VOUT_MAX_VOLTAGE, EV_BATTERY_VOLTAGE]  // 最大輸出電壓與電池電壓最大值
-        //Ocp = MIN [IOUT_MAX_CURRENT, EV_CURRENT_REQ]      // 最大輸出電流與需求電流最小值
-        //if (pDcChargingInfo->Type == _Type_Chademo) {
-        //    //Ovp = MaxValue(pDcChargingInfo->MaximumChargingVoltage, pDcChargingInfo->EvBatteryMaxVoltage);
-        //    //Ocp = MaxValue(pDcChargingInfo->PresentChargingCurrent, ShmCHAdeMOData->ev[pDcChargingInfo->type_index].ChargingCurrentRequest);
-        //} else if (pDcChargingInfo->Type == _Type_CCS_2) {
-        //}
-    }
-}
-
-void SetRtcData_Relay(void)
-{
-    struct timeb csuTime;
-    struct tm *tmCSU;
-    Rtc rtc = {0};
-
-    ftime(&csuTime);
-    tmCSU = localtime(&csuTime.time);
-    //  log_info("Time : %04d-%02d-%02d %02d:%02d:%02d ", tmCSU->tm_year + 1900,
-    //          tmCSU->tm_mon + 1, tmCSU->tm_mday, tmCSU->tm_hour, tmCSU->tm_min,
-    //          tmCSU->tm_sec);
-
-    rtc.RtcData[0] = '0' + (tmCSU->tm_year + 1900) / 1000 % 10;
-    rtc.RtcData[1] = '0' + (tmCSU->tm_year + 1900) / 100 % 10;
-    rtc.RtcData[2] = '0' + (tmCSU->tm_year + 1900) / 10 % 10;
-    rtc.RtcData[3] = '0' + (tmCSU->tm_year + 1900) / 1 % 10;
-
-    rtc.RtcData[4] = '0' + (tmCSU->tm_mon + 1) / 10 % 10;
-    rtc.RtcData[5] = '0' + (tmCSU->tm_mon + 1) / 1 % 10;
-
-    rtc.RtcData[6] = '0' + (tmCSU->tm_mday) / 10 % 10;
-    rtc.RtcData[7] = '0' + (tmCSU->tm_mday) / 1 % 10;
-
-    rtc.RtcData[8] = '0' + (tmCSU->tm_hour) / 10 % 10;
-    rtc.RtcData[9] = '0' + (tmCSU->tm_hour) / 1 % 10;
-
-    rtc.RtcData[10] = '0' + (tmCSU->tm_min) / 10 % 10;
-    rtc.RtcData[11] = '0' + (tmCSU->tm_min) / 1 % 10;
-
-    rtc.RtcData[12] = '0' + (tmCSU->tm_sec) / 10 % 10;
-    rtc.RtcData[13] = '0' + (tmCSU->tm_sec) / 1 % 10;
-
-    if (Config_Rtc_Data(Uart5Fd, ADDR_RELAY, &rtc) == PASS) {
-        //log_info("SetRtc (RB) sucessfully. ");
-    }
-}
-
-void SetModelName_Relay(void)
-{
-    if (Config_Model_Name(Uart5Fd, ADDR_RELAY, pSysConfig->ModelName) == PASS) {
-        //log_info("Set Model name (RB) PASS = %s ", pSysConfig->ModelName);
-    }
-}
-
-void GetFwAndHwVersion_Relay(void)
-{
-    Ver ver = {0};
-
-    if (Query_FW_Ver(Uart5Fd, ADDR_RELAY, &ver) == PASS) {
-        // RelayModuleData
-        strcpy((char *)ShmRelayModuleData->version, ver.Version_FW);
-        // SystemInfo
-        strcpy((char *)pSysInfo->RelayModuleFwRev, ver.Version_FW);
-        //log_info("GetFwAndHwVersion_Relay s1 = %s ", ver.Version_FW);
-    }
-
-    if (Query_HW_Ver(Uart5Fd, ADDR_RELAY, &ver) == PASS) {
-        // SystemInfo
-        strcpy((char *)pSysInfo->RelayModuleHwRev, ver.Version_FW);
-        //log_info("GetFwAndHwVersion_Relay s2 = %s ", ver.Version_HW);
-    }
-}
-
-static void outputRelayInit(int fd)
-{
-    memset((uint8_t *)&outputRelay, 0, sizeof(Relay));
-
-    if (Config_Relay_Output(fd, ADDR_RELAY, &outputRelay) != PASS) {
-        log_info("Config_Relay_Output fail ");
-    }
-}
-
-static bool IsRelayProcessNeedPause(void)
-{
-    bool _pause = false;
-    static bool isPause = false;
-    struct ChargingInfoData *pDcChargingInfo = NULL;
-
-    for (uint8_t i = 0; i < pSysConfig->TotalConnectorCount; i++)
-    {
-        pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(i);
-        if(pDcChargingInfo->SystemStatus == S_UPDATE)
-        {
-            SetLedColor();
-            _pause = true;
-        }
-    }
-    if(isPause != _pause)
-    {
-        log_info("Relay Process Now Is %s ", _pause == true ? "Paused" : "Continued");
-    }
-    isPause = _pause;
-
-    return _pause;
-}
-
-static void SetFanModuleSpeed(void)
-{
-    {
-        FanSpeed _fanSpeed = {0};
-
-        _setFanSpeed += fanSpeedSmoothValue;
-
-        if (_setFanSpeed >= ShmFanModuleData->SetFan1Speed) {
-            _setFanSpeed = ShmFanModuleData->SetFan1Speed;
-        }
-
-        //printf("_setFanSpeed = %d \n", _setFanSpeed);
-        _fanSpeed.speed[0] = _setFanSpeed;
-
-        _fanSpeed.speed[1] = _setFanSpeed;
-
-        _fanSpeed.speed[2] = _setFanSpeed;
-
-        _fanSpeed.speed[3] = _setFanSpeed;
-
-        if (Config_Fan_Speed(Uart5Fd, ADDR_FAN, &_fanSpeed) == PASS) {
-            //log_info("successfully Fan");
-        }
-    }
-}
-
-// 風扇速度
-static void GetFanSpeed(void)
-{
-    FanSpeed fanSpeed = {0};
-
-    //log_info("Get fan board speed ");
-    if (Query_Fan_Speed(Uart5Fd, ADDR_FAN, &fanSpeed) == PASS) {
-        ShmFanModuleData->PresentFan1Speed = fanSpeed.speed[0];
-        ShmFanModuleData->PresentFan2Speed = fanSpeed.speed[1];
-        ShmFanModuleData->PresentFan3Speed = fanSpeed.speed[2];
-        ShmFanModuleData->PresentFan4Speed = fanSpeed.speed[3];
-//      log_info("SystemFanRotaSpeed_1 = %d ", fanSpeed.speed[0]);
-//      log_info("SystemFanRotaSpeed_2 = %d ", fanSpeed.speed[1]);
-//      log_info("SystemFanRotaSpeed_3 = %d ", fanSpeed.speed[2]);
-//      log_info("SystemFanRotaSpeed_4 = %d ", fanSpeed.speed[3]);
-        // Config_Fan_Speed(Uart5Fd, ADDR_FAN, &fanSpeed[0]);
-        //SysInfoData (SystemFanRotaSpeed)
-    }
-}
-
-static void GetFanSpeedByFunction(void)
-{
-    if (ShmDcCommonData->DebugFlag == YES) {
-        return;
-    }
-
-    int gunIndex;
-    struct ChargingInfoData* pDcChargingInfo = NULL;
-    for (gunIndex = 0; gunIndex < pSysConfig->TotalConnectorCount; gunIndex++) {
-        pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(gunIndex);
-        if ((pDcChargingInfo->SystemStatus > S_AUTHORIZING && pDcChargingInfo->SystemStatus < S_TERMINATING) ||
-            (pDcChargingInfo->SystemStatus >= S_CCS_PRECHARGE_ST0 && pDcChargingInfo->SystemStatus <= S_CCS_PRECHARGE_ST1)) {
-            ShmDcCommonData->FanOnTime = time((time_t*)NULL);
-            if (ShmFanModuleData->SetFan1Speed == 0) {
-                ShmFanModuleData->SetFan1Speed = 7000;
-                log_info("Set Fan speed 7000");
-            }
-        }
-    }
-
-    if ((time((time_t*)NULL) - ShmDcCommonData->FanOnTime) >= 600 &&
-        ShmFanModuleData->SetFan1Speed == 7000) {
-        ShmFanModuleData->SetFan1Speed = 0;
-        log_info("Close fan");
-    }
-
-    // 風控修改 :
-    // ******************************************************* //
-    //
-    //       當前PSU輸出總 KW       PSU Temp
-    // 30 x -------------------- x ---------- + 14 x (PSU Temp - 45)
-    //       當前樁最大功率 KW         45
-    //
-    // ******************************************************* //
-    /*
-    // 當前樁最大功率 KW : ShmPsuData->SystemAvailablePower
-    uint32_t _maxPower = ShmPsuData->SystemAvailablePower;
-    // 當前PSU輸出總 KW & PSU Temp :
-    uint8_t temp = 0;
-    uint8_t index = 0;
-    uint8_t count = 0;
-    uint8_t gunIndex = 0;
-    uint8_t _temp_diff = 0;
-    float power = 0;
-    double _pw_rate = 0;
-    double _temp_rate = 0;
-    struct ChargingInfoData *pDcChargingInfo = NULL;
-
-    for (index = 0; index < ShmPsuData->GroupCount; index++) {
-        for (count = 0; count < ShmPsuData->PsuGroup[index].GroupPresentPsuQuantity; count++) {
-            if (temp < ShmPsuData->PsuGroup[index].PsuModule[count].ExletTemp) {
-                temp = ShmPsuData->PsuGroup[index].PsuModule[count].ExletTemp;
-            }
-        }
-    }
-
-    for (gunIndex = 0; gunIndex < pSysConfig->TotalConnectorCount; gunIndex++) {
-        pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-
-        power += (pDcChargingInfo->PresentChargingPower * 10);
-    }
-
-    if (_maxPower > 0) {
-        _pw_rate = power / (double)_maxPower;
-    }
-
-    if (temp > 0) {
-        _temp_rate = (double)temp / 50;
-    }
-
-    if (temp > 45) {
-        _temp_diff = temp - 70;
-    }
-
-    ShmFanModuleData->TestFanSpeed = (((50 * _pw_rate * _temp_rate) + (0.5 * _temp_diff)) / 100) * MAX_FAN_SPEED;
-
-    if (ShmFanModuleData->TestFanSpeed > MAX_FAN_SPEED) {
-        ShmFanModuleData->TestFanSpeed = MAX_FAN_SPEED;
-    }
-
-    if (ShmFanModuleData->TestFanSpeed < 0) {
-        ShmFanModuleData->TestFanSpeed = 0;
-    }
-    */
-//
-//  printf("power = %f \n", power);
-//  printf("_maxPower = %d \n", _maxPower);
-//  printf("temp = %d \n", temp);
-//
-//  printf("_pw_rate = %f \n", _pw_rate);
-//  printf("_temp_rate = %f \n", _temp_rate);
-//  printf("_temp_diff = %d \n", _temp_diff);
-//  printf("fan rate = %f \n", (30 * _pw_rate * _temp_rate + 14 * _temp_diff));
-//  printf("ShmFanModuleData->TestFanSpeed = %d \n", ShmFanModuleData->TestFanSpeed);
-}
-
-static void SetRtcData_Fan(void)
-{
-    struct timeb csuTime;
-    struct tm *tmCSU;
-    Rtc rtc = {0};
-
-    ftime(&csuTime);
-    tmCSU = localtime(&csuTime.time);
-    //  log_info("Time : %04d-%02d-%02d %02d:%02d:%02d ", tmCSU->tm_year + 1900,
-    //          tmCSU->tm_mon + 1, tmCSU->tm_mday, tmCSU->tm_hour, tmCSU->tm_min,
-    //          tmCSU->tm_sec);
-
-    rtc.RtcData[0] = '0' + (tmCSU->tm_year + 1900) / 1000 % 10;
-    rtc.RtcData[1] = '0' + (tmCSU->tm_year + 1900) / 100 % 10;
-    rtc.RtcData[2] = '0' + (tmCSU->tm_year + 1900) / 10 % 10;
-    rtc.RtcData[3] = '0' + (tmCSU->tm_year + 1900) / 1 % 10;
-
-    rtc.RtcData[4] = '0' + (tmCSU->tm_mon + 1) / 10 % 10;
-    rtc.RtcData[5] = '0' + (tmCSU->tm_mon + 1) / 1 % 10;
-
-    rtc.RtcData[6] = '0' + (tmCSU->tm_mday) / 10 % 10;
-    rtc.RtcData[7] = '0' + (tmCSU->tm_mday) / 1 % 10;
-
-    rtc.RtcData[8] = '0' + (tmCSU->tm_hour) / 10 % 10;
-    rtc.RtcData[9] = '0' + (tmCSU->tm_hour) / 1 % 10;
-
-    rtc.RtcData[10] = '0' + (tmCSU->tm_min) / 10 % 10;
-    rtc.RtcData[11] = '0' + (tmCSU->tm_min) / 1 % 10;
-
-    rtc.RtcData[12] = '0' + (tmCSU->tm_sec) / 10 % 10;
-    rtc.RtcData[13] = '0' + (tmCSU->tm_sec) / 1 % 10;
-
-    if (Config_Rtc_Data(Uart5Fd, ADDR_FAN, &rtc) == PASS) {
-        //log_info("SetRtc (FB) sucessfully. ");
-    }
-}
-
-static void SetModelName_Fan(void)
-{
-    if (Config_Model_Name(Uart5Fd, ADDR_FAN, pSysConfig->ModelName) == PASS) {
-        log_info("Set Model name PASS = %s ", pSysConfig->ModelName);
-    }
-}
-
-static void GetFwAndHwVersion_Fan(void)
-{
-    Ver ver = {0};
-
-    if (Query_FW_Ver(Uart5Fd, ADDR_FAN, &ver) == PASS) {
-        // FanModuleData
-        strcpy((char *)ShmFanModuleData->version, ver.Version_FW);
-        // SystemInfo
-        strcpy((char *)pSysInfo->FanModuleFwRev, ver.Version_FW);
-        //log_info("GetFwAndHwVersion_Fan s1 = %s ", ver.Version_FW);
-    }
-
-    if (Query_HW_Ver(Uart5Fd, ADDR_FAN, &ver) == PASS) {
-        // SystemInfo
-        strcpy((char *)pSysInfo->FanModuleHwRev, ver.Version_FW);
-        //log_info("GetFwAndHwVersion_Fan s2 = %s ", ver.Version_HW);
-    }
-}
-
-static void fanBoardSelfTest(void)
-{
-    if (ShmFanModuleData->SelfTest_Comp == YES) {
-        return;
-    }
-
-    GetFwAndHwVersion_Fan();
-    SetModelName_Fan();
-    SetRtcData_Fan();
-    sleep(1);
-    GetClockTime(&gFanBoardRunTimer, NULL);
-}
-
-static void fanBoardPorcess(void)
-{
-    if (ShmFanModuleData->SelfTest_Comp == NO) {
-        return;
-    }
-
-    if (ShmFanModuleData->SelfTest_Comp == YES ||
-            strlen((char *)pSysInfo->FanModuleFwRev) != 0 ||
-            pSysInfo->FanModuleFwRev[0] != '\0') {
-        ShmFanModuleData->SelfTest_Comp = YES;
-
-        if (GetClockTimeoutValue(gFanBoardRunTimer) / 1000 >= 1000) {
-            //GetPsuTempForFanSpeed();
-            //GetFanSpeedByFunction();
-            GetFanSpeed();
-            pSysInfo->SystemFanRotaSpeed = _setFanSpeed;
-            GetClockTime(&gFanBoardRunTimer, NULL);
-            /*
-            ShmFanModuleData->SetFan1Speed = ShmFanModuleData->TestFanSpeed;
-            ShmFanModuleData->SetFan2Speed = ShmFanModuleData->TestFanSpeed;
-            ShmFanModuleData->SetFan3Speed = ShmFanModuleData->TestFanSpeed;
-            ShmFanModuleData->SetFan4Speed = ShmFanModuleData->TestFanSpeed;
-            */
-            //log_info("set fan = %d ", ShmFanModuleData->SetFan1Speed);
-            SetFanModuleSpeed();
-        }
-    }
-}
-
-static void GetFwAndHwVersion_Led(void)
-{
-    Ver ver = {0};
-
-    if (Query_FW_Ver(Uart5Fd, ADDR_LED, &ver) == PASS) {
-        // LedModuleData
-        strcpy((char *) ShmLedModuleData->version, ver.Version_FW);
-        // SystemInfo
-        strcpy((char *) pSysInfo->LedModuleFwRev, ver.Version_FW);
-        log_info("GetFwAndHwVersion_Led s1 = %s ", ver.Version_FW);
-        ShmLedModuleData->SelfTest_Comp = YES;
-    } else {
-        //log_info("GetFwAndHwVersion_Led fail ");
-    }
-
-//  if (Query_HW_Ver(Uart5Fd, ADDR_LED, &ver) == PASS)
-//  {
-//      // SystemInfo
-//      strcpy((char *) pSysInfo->RelayModuleHwRev, ver.Version_FW);
-//      //log_info("GetFwAndHwVersion_Relay s2 = %s ", ver.Version_HW);
-//  }
-}
-
-static bool IsNoneMatchLedColor(void)
-{
-    bool result = false;
-
-    if (cur_led_color.Connect_1_Red != led_color.Connect_1_Red ||
-            cur_led_color.Connect_1_Green != led_color.Connect_1_Green ||
-            cur_led_color.Connect_1_Blue != led_color.Connect_1_Blue ||
-            cur_led_color.Connect_2_Red != led_color.Connect_2_Red ||
-            cur_led_color.Connect_2_Green != led_color.Connect_2_Green ||
-            cur_led_color.Connect_2_Blue != led_color.Connect_2_Blue) {
-        result = true;
-    }
-
-    return result;
-}
-
-//static void SetLedColor(struct ChargingInfoData *chargingData_1, struct ChargingInfoData *chargingData_2)
-static void SetLedColor(void)
-{
-    static uint8_t _checkLedChanged = 3;
-    struct ChargingInfoData *chargingData_1 = NULL;
-    struct ChargingInfoData *chargingData_2 = NULL;
-
-    if (pSysConfig->TotalConnectorCount == 1) {
-        chargingData_1 = (struct ChargingInfoData *)GetDcChargingInfoData(0);
-        chargingData_2 = (struct ChargingInfoData *)GetDcChargingInfoData(0);
-    } else if (pSysConfig->TotalConnectorCount == 2) {
-        chargingData_1 = (struct ChargingInfoData *)GetDcChargingInfoData(0);
-        chargingData_2 = (struct ChargingInfoData *)GetDcChargingInfoData(1);
-    }
-    uint8_t _colorBuf = COLOR_MAX_LV * LED_INTENSITY_BRIGHTEST;
-
-    if (pSysConfig->LedInfo.Intensity == _LED_INTENSITY_DARKEST) {
-        _colorBuf = COLOR_MAX_LV * LED_INTENSITY_DARKEST;
-    } else if (pSysConfig->LedInfo.Intensity == _LED_INTENSITY_MEDIUM) {
-        _colorBuf = COLOR_MAX_LV * LED_INTENSITY_MEDIUM;
-    } else if (pSysConfig->LedInfo.Intensity == LED_INTENSITY_BRIGHTEST) {
-        _colorBuf = COLOR_MAX_LV * LED_INTENSITY_BRIGHTEST;
-    }
-
-    //printf("chargingData_1->SystemStatus=%d\n",chargingData_1->SystemStatus);
-    //printf("chargingData_2->SystemStatus=%d\n",chargingData_2->SystemStatus);
-    //printf("pSysWarning->Level=%d\n",pSysWarning->Level);
-    if (pSysWarning->Level == 2) {
-        led_color.Connect_1_Green = COLOR_MIN_LV;
-        led_color.Connect_1_Blue = COLOR_MIN_LV;
-        led_color.Connect_1_Red = _colorBuf;
-        led_color.Connect_2_Green = COLOR_MIN_LV;
-        led_color.Connect_2_Blue = COLOR_MIN_LV;
-        led_color.Connect_2_Red = _colorBuf;
-    } else {
-        if (pSysInfo->IsAlternatvieConf) {
-
-        } else {
-            // 左邊燈條
-            if (chargingData_1->SystemStatus == S_BOOTING ||
-                    chargingData_1->SystemStatus == S_IDLE ) {
-                if (chargingData_1->IsAvailable == NO) { //For Audi
-                    led_color.Connect_1_Green = COLOR_MIN_LV;
-                    led_color.Connect_1_Blue = COLOR_MIN_LV;
-                    led_color.Connect_1_Red = _colorBuf;
-                } else {
-#if defined DD360Audi
-                    led_color.Connect_1_Green = _colorBuf;
-                    led_color.Connect_1_Blue = _colorBuf;
-                    led_color.Connect_1_Red = _colorBuf;
-#else
-                    led_color.Connect_1_Green = _colorBuf;
-                    led_color.Connect_1_Blue = COLOR_MIN_LV;
-                    led_color.Connect_1_Red = COLOR_MIN_LV;
-#endif
-                }
-            } else if ((chargingData_1->SystemStatus >= S_AUTHORIZING &&
-                        chargingData_1->SystemStatus <= S_COMPLETE) ||
-                       (chargingData_1->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
-                        chargingData_1->SystemStatus <= S_CCS_PRECHARGE_ST1)) {
-                led_color.Connect_1_Green = COLOR_MIN_LV;
-                led_color.Connect_1_Blue = _colorBuf;
-                led_color.Connect_1_Red = COLOR_MIN_LV;
-            } else if ( chargingData_1->SystemStatus == S_UPDATE ||
-                    chargingData_1->SystemStatus == S_MAINTAIN ) {
-                led_color.Connect_1_Green = COLOR_MIN_LV;
-                led_color.Connect_1_Blue = COLOR_MIN_LV;
-                led_color.Connect_1_Red = _colorBuf;
-            } else if (chargingData_1->SystemStatus == S_RESERVATION) {
-                if (ReservationLed) {
-                    led_color.Connect_1_Green = COLOR_MIN_LV;
-                } else {
-                    led_color.Connect_1_Green = _colorBuf;
-                }
-                led_color.Connect_1_Blue = COLOR_MIN_LV;
-                led_color.Connect_1_Red = COLOR_MIN_LV;
-            }
-            // 右邊燈條
-            // --------------------------------------------------------------------------
-            if (chargingData_2->SystemStatus == S_BOOTING ||
-                    chargingData_2->SystemStatus == S_IDLE ) {
-                if (chargingData_2->IsAvailable == NO) {
-                    led_color.Connect_2_Green = COLOR_MIN_LV;
-                    led_color.Connect_2_Blue = COLOR_MIN_LV;
-                    led_color.Connect_2_Red = _colorBuf;
-                } else {
-#if defined DD360Audi
-                    led_color.Connect_2_Green = _colorBuf;
-                    led_color.Connect_2_Blue = _colorBuf;
-                    led_color.Connect_2_Red = _colorBuf;
-#else
-                    led_color.Connect_2_Green = _colorBuf;
-                    led_color.Connect_2_Blue = COLOR_MIN_LV;
-                    led_color.Connect_2_Red = COLOR_MIN_LV;
-#endif
-                }
-            } else if ((chargingData_2->SystemStatus >= S_AUTHORIZING &&
-                        chargingData_2->SystemStatus <= S_COMPLETE) ||
-                       (chargingData_2->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
-                        chargingData_2->SystemStatus <= S_CCS_PRECHARGE_ST1)) {
-                led_color.Connect_2_Green = COLOR_MIN_LV;
-                led_color.Connect_2_Blue = _colorBuf;
-                led_color.Connect_2_Red = COLOR_MIN_LV;
-            }else if ( chargingData_2->SystemStatus == S_UPDATE ||
-                    chargingData_2->SystemStatus == S_MAINTAIN) {
-                led_color.Connect_2_Green = COLOR_MIN_LV;
-                led_color.Connect_2_Blue = COLOR_MIN_LV;
-                led_color.Connect_2_Red = _colorBuf;
-            } else if (chargingData_2->SystemStatus == S_RESERVATION) {
-                if (ReservationLed) {
-                    led_color.Connect_2_Green = COLOR_MIN_LV;
-                } else {
-                    led_color.Connect_2_Green = _colorBuf;
-                }
-                led_color.Connect_2_Blue = COLOR_MIN_LV;
-                led_color.Connect_2_Red = COLOR_MIN_LV;
-            }
-
-        }
-    }
-    if (_checkLedChanged > 0) {
-        if (Config_Led_Color(Uart5Fd, ADDR_LED, &led_color) == PASS) {
-            _checkLedChanged--;
-
-            cur_led_color.Connect_1_Red     = led_color.Connect_1_Red;
-            cur_led_color.Connect_1_Green   = led_color.Connect_1_Green;
-            cur_led_color.Connect_1_Blue    = led_color.Connect_1_Blue;
-            cur_led_color.Connect_2_Red     = led_color.Connect_2_Red;
-            cur_led_color.Connect_2_Green   = led_color.Connect_2_Green;
-            cur_led_color.Connect_2_Blue    = led_color.Connect_2_Blue;
-        }
-    } else if (IsNoneMatchLedColor()) {
-        _checkLedChanged = 3;
-    }
-}
-
-static void LEDBoardSelfTest(void)
-{
-    // 自檢階段處理,自檢階段如果讀不到版號則代表該系統沒有掛燈板
-    if (ShmLedModuleData->SelfTest_Comp == YES) {
-        return;
-    }
-
-#if defined DD360Tcci ||defined DD360Audi || defined DD360UCar
-    GetFwAndHwVersion_Led();
-    sleep(1);
-    GetClockTime(&_led_priority_time, NULL);
-
-    return;
-#endif //defined DD360Tcci || defined DD360Audi
-
-    // 自檢階段
-    if (pSysInfo->SelfTestSeq <= _STEST_PSU_CAP) {
-        GetFwAndHwVersion_Led();
-        sleep(1);
-        GetClockTime(&_led_priority_time, NULL);
-    } else {
-        // 自檢階段沒有問到版號
-        if (pAlarmCode->AlarmEvents.bits.LedboardStestFail == NO) {
-            pAlarmCode->AlarmEvents.bits.LedboardStestFail = YES;
-        }
-    }
-}
-
-static void LEDBoardProcess(void)
-{
-    //struct ChargingInfoData *pDcChargingInfo0 = NULL;
-    //struct ChargingInfoData *pDcChargingInfo1 = NULL;
-
-    if (ShmLedModuleData->SelfTest_Comp == NO) {
-        return;
-    }
-    pSysConfig->LedInfo.Intensity = LED_INTENSITY_BRIGHTEST;
-    if (GetClockTimeoutValue(_led_priority_time) / 1000 >= 500) {
-        if (time((time_t*)NULL) - ReservationFlashTimer >= 3) {
-            ReservationFlashTimer = time((time_t*)NULL);
-            if (ReservationLed)
-                ReservationLed = 0;
-            else
-                ReservationLed = 1;
-        }
-        SetLedColor();
-        GetClockTime(&_led_priority_time, NULL);
-    }
-}
-
-void RelayBoardTask(int uartFD)
-{
-    bool isRelayBypass = false;
-    pid_t pid = fork();
-
-    if (pid == 0) {
-        bool isCharging = false;
-        bool isStopChargingCount = false;
-        uint8_t i = 0;
-        int isContinue = 1;
-        struct ChargingInfoData *pDcChargingInfo = NULL;
-
-        //share memory mapping
-        pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
-        pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
-        pAlarmCode = (struct AlarmCodeData *)GetShmAlarmCodeData();
-        ShmRelayModuleData = (struct RelayModuleData *)GetShmRelayModuleData();
-        ShmPsuData = (struct PsuData *)GetShmPsuData();
-        ShmDcCommonData = (DcCommonInfo *)GetShmDcCommonData();
-        ShmPrimaryMcuData = (struct PrimaryMcuData *)GetShmPrimaryMcuData();
-        pSysWarning = (struct WARNING_CODE_INFO *)GetShmSysWarningInfo();
-        ShmFanModuleData = (struct FanModuleData *)GetShmFanModuleData();
-        ShmLedModuleData = (struct LedModuleData *)GetShmLedModuleData();
-
-        Uart5Fd = uartFD;
-
-        for(int i = 0; i < pSysConfig->TotalConnectorCount; i++)
-        {
-            pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(i);
-            if(pDcChargingInfo->PantographFlag == YES)
-            {
-                isRelayBypass = true;
-            }
-        }
-
-        //relay init
-        if(isRelayBypass == false)
-        {
-            outputRelayInit(uartFD);
-        }
-
-        while (isContinue) {
-
-            if(IsRelayProcessNeedPause() == true)
-            {
-                sleep(1);
-                continue;
-            }
-
-            // 程序開始之前~ 必須先確定 FW 版本與硬體版本,確認後!!~ 該模組才算是真正的 Initial Comp.
-            if (ShmRelayModuleData->SelfTest_Comp == NO && isRelayBypass == false) {
-                GetFwAndHwVersion_Relay();
-                SetModelName_Relay(); //DS60-120 add
-                SetRtcData_Relay();
-                sleep(1);
-            }
-
-#if !defined NO_FAN_BOARD && !defined DD360ComBox
-            fanBoardSelfTest();
-#endif //NO_FAN_BOARD
-
-#if !defined DD360ComBox
-            LEDBoardSelfTest();
-#endif //defined DD360ComBox
-
-            if (ShmRelayModuleData->SelfTest_Comp == YES && isRelayBypass == false)
-            {
-                // ==============優先權最高 10 ms ==============
-                // 輸出電壓
-                GetPersentOutputVol();
-
-    #if !defined DD360Tcci && !defined DD360Audi && !defined DD360ComBox && !defined DD360UCar
-                // 三相輸入電壓
-                GetPresentInputVol();
-    #endif //!defined DD360Tcci && !defined DD360Audi
-
-                // 讀取當前 AC relay 狀態
-                regRelay.relay_event.bits.AC_Contactor = pSysInfo->AcContactorStatus;
-                GetRelayOutputStatus();
-
-                // Cable check (Get)
-                GetGfdAdc();
-
-                for (i = 0; i < pSysConfig->TotalConnectorCount; i++) {
-                    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(i);
-
-                    // Cable check (Set)
-                    CableCheckDetected(i);
-
-                    // check k1 k2 relay 狀態
-                    CheckK1K2RelayOutput(i);
-
-                    // 依據當前各槍的狀態選擇 搭上/放開 Relay
-                    SetK1K2RelayStatus(i);
-
-#if !defined DD360Tcci && !defined DD360Audi && !defined DD360ComBox && !defined DD360UCar
-                    if (pSysConfig->PhaseLossPolicy == YES) {
-                        CheckPhaseLossStatus(i);
-                    }
-
-                    CheckAcInputOvpStatus(i);
-#endif //!defined DD360Tcci && !defined DD360Audi
-
-                    if (pDcChargingInfo->SystemStatus == S_IDLE ||
-                            pDcChargingInfo->SystemStatus == S_RESERVATION ||
-                            pDcChargingInfo->SystemStatus == S_MAINTAIN) {
-                        //pDcChargingInfo->RelayWeldingCheck = NO;
-                        //_isRelayWelding[i] = NO;
-                        _isOvpChkTimeFlag[i] = NO;
-                        _show_GFD_Warming[i] = TRUE;
-                        //ResetDetAlarmStatus(i); //DS60-120 add
-                    }
-
-                    if (pDcChargingInfo->SystemStatus == S_BOOTING ||
-                            (pDcChargingInfo->SystemStatus >= S_REASSIGN_CHECK &&
-                             pDcChargingInfo->SystemStatus <= S_COMPLETE) ||
-                            (pDcChargingInfo->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
-                             pDcChargingInfo->SystemStatus <= S_CCS_PRECHARGE_ST1) ||
-                            ShmDcCommonData->pGunInfo[i].WaitForPlugit == YES ||
-                            (pSysInfo->PageIndex >=  _PAGE_AUTHORIZE &&
-                             pSysInfo->PageIndex <= _PAGE_PLUGIN)
-                       ) {
-                        pDcChargingInfo->IsReadyToCharging = YES;
-                        isCharging = true;
-
-                        // 限定只有在槍類別為 GBT 的時候才做 relay welding 的判斷
-                        //if (pDcChargingInfo->Type == _Type_GB) {
-                        //    if (pDcChargingInfo->SystemStatus >= S_PREPARING_FOR_EVSE &&
-                        //            pDcChargingInfo->RelayWeldingCheck == NO) {
-                        //        CheckRelayWeldingStatus(i);
-                        //    }
-                        //} else {
-                        //pDcChargingInfo->RelayWeldingCheck = YES;
-                        //}
-
-                        if (pDcChargingInfo->SystemStatus == S_CHARGING) {
-                            CheckOutputPowerOverCarReq(i);
-                            //CheckOutputVolNoneMatchFire(i);
-                        }
-                        /*else {
-                            _isOutputNoneMatch[i] = NO;
-                        }*/
-                    } else {
-                        pDcChargingInfo->IsReadyToCharging = NO;
-                    }
-                }
-
-                    // 橋接 relay
-                    SetParalleRelayStatus();
-
-                    // 搭上 AC Contactor
-                    //if (isCharging) {
-                    //    outputRelay.relay_event.bits.AC_Contactor = YES;
-                    //} else {
-                    //    outputRelay.relay_event.bits.AC_Contactor = NO;
-                    //}
-
-                    if (isCharging ||
-                            (ShmPsuData->Work_Step >= _TEST_MODE &&
-                             ShmPsuData->Work_Step <= _TEST_MODE)) {
-                        isStopChargingCount = false;
-                        outputRelay.relay_event.bits.AC_Contactor = YES;
-                    } else {
-                        if (!isStopChargingCount) {
-                            GetClockTime(&_close_ac_contactor, NULL);
-                            isStopChargingCount = true;
-                        } else {
-                            if ((outputRelay.relay_event.bits.AC_Contactor == YES &&
-                                    GetClockTimeoutValue(_close_ac_contactor) / 1000 >= (TEN_MINUTES * 1000))) {
-                                outputRelay.relay_event.bits.AC_Contactor = NO;
-                            }
-                        }
-                    }
-
-                    if (ShmPrimaryMcuData->InputDet.bits.EmergencyButton == ABNORMAL) {
-                        outputRelay.relay_event.bits.AC_Contactor = NO;
-                    }
-
-                    if (pAlarmCode->AlarmEvents.bits.PsuFailureAlarm == ABNORMAL) {
-                        RunForceStopProcess();
-                        outputRelay.relay_event.bits.AC_Contactor = NO;
-                    }
-
-                    if (ShmPsuData->Work_Step >= _TEST_MODE && ShmPsuData->Work_Step <= _TEST_MODE) {
-                        outputRelay.relay_event.bits.Gun1_N = outputRelay.relay_event.bits.Gun1_P = YES;
-                    }
-
-                    // 搭上/鬆開 Relay
-                    if (IsNoneMatchRelayStatus()) {
-                        if (Config_Relay_Output(Uart5Fd, ADDR_RELAY, &outputRelay)) {
-                            //regRelay.relay_event.bits.AC_Contactor = pSysInfo->AcContactorStatus;
-
-                            //regRelay.relay_event.bits.CCS_Precharge = outputRelay.relay_event.bits.CCS_Precharge;
-                            //regRelay.relay_event.bits.Gun1_P = outputRelay.relay_event.bits.Gun1_P;
-                            //regRelay.relay_event.bits.Gun1_N = outputRelay.relay_event.bits.Gun1_N;
-                            //regRelay.relay_event.bits.Gun2_P = outputRelay.relay_event.bits.Gun2_P;
-                            //regRelay.relay_event.bits.Gun2_N = outputRelay.relay_event.bits.Gun2_N;
-                            //regRelay.relay_event.bits.Gun1_Parallel_P = outputRelay.relay_event.bits.Gun1_Parallel_P;
-                            //regRelay.relay_event.bits.Gun1_Parallel_N = outputRelay.relay_event.bits.Gun1_Parallel_N;
-
-                            //MatchRelayStatus();
-
-                            //log_info("Match Relay, AC = %x, g1_p = %x, g1_n = %x, g2_p = %x, g2_n = %x, pre = %x, bri_p = %x, bri_n = %x ",
-                            //         regRelay.relay_event.bits.AC_Contactor,
-                            //         regRelay.relay_event.bits.Gun1_P,
-                        //         regRelay.relay_event.bits.Gun1_N,
-                        //         regRelay.relay_event.bits.Gun2_P,
-                        //         regRelay.relay_event.bits.Gun2_N,
-                        //         regRelay.relay_event.bits.CCS_Precharge,
-                        //         regRelay.relay_event.bits.Gun1_Parallel_P,
-                        //         regRelay.relay_event.bits.Gun1_Parallel_N);
-
-                    }
-                }
-            }
-            else if(isRelayBypass == true)
-            {
-                for(i = 0; i < pSysConfig->TotalConnectorCount; i++)
-                {
-                    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(i);
-
-                    if (pDcChargingInfo->SystemStatus == S_IDLE ||
-                            pDcChargingInfo->SystemStatus == S_RESERVATION ||
-                            pDcChargingInfo->SystemStatus == S_MAINTAIN)
-                    {
-                        _isOvpChkTimeFlag[i] = NO;
-                    }
-                    if (pDcChargingInfo->SystemStatus == S_CHARGING)
-                    {
-                        CheckOutputPowerOverCarReq(i);
-                    }
-                }
-            }
-
-#if !defined NO_FAN_BOARD && !defined DD360ComBox
-            fanBoardPorcess();
-#endif //NO_FAN_BOARD
-
-#if !defined DD360ComBox
-            LEDBoardProcess();
-#endif //defined DD360ComBox
-
-            usleep(10000);
-        }
-    }
-}
+#include <stdio.h>      /*標準輸入輸出定義*/
+#include <stdlib.h>     /*標準函數庫定義*/
+#include <string.h>
+#include <stdint.h>
+#include <time.h>
+#include <unistd.h>
+
+#include <sys/time.h>
+#include <sys/timeb.h>
+
+#include "../ShareMemory/shmMem.h"
+#include "../Config.h"
+#include "../Log/log.h"
+#include "Module_InternalComm.h"
+#include "internalComm.h"
+
+//------------------------------------------------------------------------------
+static struct SysConfigData *pSysConfig = NULL;
+static struct SysInfoData *pSysInfo = NULL;
+static struct AlarmCodeData *pAlarmCode = NULL;
+static struct RelayModuleData *ShmRelayModuleData = NULL;
+static struct PsuData *ShmPsuData = NULL;
+static struct PrimaryMcuData *ShmPrimaryMcuData = NULL;
+static DcCommonInfo *ShmDcCommonData = NULL;
+static struct WARNING_CODE_INFO *pSysWarning = NULL;
+static struct LedModuleData *ShmLedModuleData = NULL;
+static struct FanModuleData *ShmFanModuleData = NULL;
+
+static Relay outputRelay = {0};
+static Relay regRelay = {0};
+static int Uart5Fd = 0;
+static struct timespec gFanBoardRunTimer;
+static uint16_t _setFanSpeed = 0;
+static uint16_t fanSpeedSmoothValue = 500;
+
+static Led_Color cur_led_color = {COLOR_MIN_LV};
+static Led_Color led_color;
+static struct timespec _led_priority_time;
+int ReservationLed;
+time_t ReservationFlashTimer;
+bool _show_GFD_Warming[2] = {TRUE};
+//static bool _isRelayWelding[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
+//static struct timeval _checkRelayWeldingTimer[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
+
+//static bool _isOutputNoneMatch[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
+//static struct timeval _checkOutputNoneMatchTimer[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
+
+static bool _isOvpChkTimeFlag[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY]; //DS60-120 add
+static struct timespec _checkOutputVolProtectTimer[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY]; //DS60-120 add
+
+static void SetLedColor(void);
+static struct timespec _close_ac_contactor;
+
+//------------------------------------------------------------------------------
+static void RunForceStopProcess(void)
+{
+    static bool isCriticalStop = NO;
+    static struct timespec  _psuCriticalStop;
+    uint32_t _timebuf;
+
+    if (isCriticalStop == NO) {
+        isCriticalStop = YES;
+        GetClockTime(&_psuCriticalStop, NULL);
+    } else {
+        _timebuf = GetClockTimeoutValue(_psuCriticalStop);
+
+        if (_timebuf < 0) {
+            GetClockTime(&_psuCriticalStop, NULL);
+        } else {
+            if (_timebuf / 1000 >= (FORCE_STOP_TIME * 1000)) {
+                isCriticalStop = NO;
+                pAlarmCode->AlarmEvents.bits.PsuFailureAlarm = NORMAL;
+            }
+        }
+    }
+}
+
+static void StopCheckRelayInfo(uint8_t _chkIndex)
+{
+    if (ShmDcCommonData->CheckRelayStatus[_chkIndex] != STOP) {
+        ShmDcCommonData->CheckRelayStatus[_chkIndex] = STOP;
+    }
+}
+
+static void StartCheckRelayInfo(uint8_t _chkIndex, uint8_t toState)
+{
+    // SMR1 *2 + SMR2 * 2 + Parallel * 2
+    static struct timespec lastCheckRelayStateTimer[6] = {0};
+    //uint8_t *pCheckRelayState = (uint8_t *)ShmDcCommonData->CheckRelayStatus[_chkIndex];
+
+    if (ShmDcCommonData->CheckRelayStatus[_chkIndex] == STOP) {
+        GetClockTime(&lastCheckRelayStateTimer[_chkIndex], NULL);
+        ShmDcCommonData->CheckRelayStatus[_chkIndex] = START;
+    } else {
+        if ((GetClockTimeoutValue(lastCheckRelayStateTimer[_chkIndex]) / 1000000) >= 1) {
+            //log_info("relay welding or driving fault = %d ", _chkIndex);
+            if (toState == 1) {
+                ShmDcCommonData->CheckRelayStatus[_chkIndex] = RELAY_STATUS_ERROR_DRIVING;
+            } else {
+                ShmDcCommonData->CheckRelayStatus[_chkIndex] = RELAY_STATUS_ERROR_WELDING;
+            }
+            log_info("relay %d %s fault", _chkIndex,(toState == 1) ? "driving" : "welding");
+            GetClockTime(&lastCheckRelayStateTimer[_chkIndex], NULL);
+        }
+    }
+}
+
+static uint8_t getCommTargetID(uint8_t index)
+{
+    uint8_t targetID = 0;
+    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);
+
+    if (pSysConfig->TotalConnectorCount == 1) {
+        if (strncmp((char *)&pSysConfig->ModelName[7], "0", 1) != 0) {
+            targetID = 0x01;
+        } else if (strncmp((char *)&pSysConfig->ModelName[9], "0", 1) != 0) {
+            targetID = 0x02;
+        }
+    } else {
+        targetID = pDcChargingInfo->Evboard_id;
+    }
+
+    return targetID;
+}
+
+/*static void MatchRelayStatus(void)
+{
+    // 因為 AC Contactor 沒有 Feedback,所以暫時先這樣處理
+    //regRelay.relay_event.bits.AC_Contactor = outputRelay.relay_event.bits.AC_Contactor;
+    //pSysInfo->AcContactorStatus =
+    //    regRelay.relay_event.bits.AC_Contactor =
+    //        outputRelay.relay_event.bits.AC_Contactor;
+    regRelay.relay_event.bits.CCS_Precharge = outputRelay.relay_event.bits.CCS_Precharge;
+    regRelay.relay_event.bits.Gun1_P = outputRelay.relay_event.bits.Gun1_P;
+    regRelay.relay_event.bits.Gun1_N = outputRelay.relay_event.bits.Gun1_N;
+    regRelay.relay_event.bits.Gun2_P = outputRelay.relay_event.bits.Gun2_P;
+    regRelay.relay_event.bits.Gun2_N = outputRelay.relay_event.bits.Gun2_N;
+    regRelay.relay_event.bits.Gun1_Parallel_P = outputRelay.relay_event.bits.Gun1_Parallel_P;
+    regRelay.relay_event.bits.Gun1_Parallel_N = outputRelay.relay_event.bits.Gun1_Parallel_N;
+}
+*/
+
+static bool IsNoneMatchRelayStatus(void)
+{
+    bool result = false;
+
+    if (
+#if !defined DD360Tcci && !defined DD360Audi && !defined DD360ComBox && !defined DD360UCar
+        (regRelay.relay_event.bits.AC_Contactor != outputRelay.relay_event.bits.AC_Contactor) ||
+        (regRelay.relay_event.bits.CCS_Precharge != outputRelay.relay_event.bits.CCS_Precharge) ||
+#endif //!defined DD360Tcci && !defined DD360Audi
+        (regRelay.relay_event.bits.Gun1_P != outputRelay.relay_event.bits.Gun1_P) ||
+        (regRelay.relay_event.bits.Gun1_N != outputRelay.relay_event.bits.Gun1_N) ||
+        (regRelay.relay_event.bits.Gun2_P != outputRelay.relay_event.bits.Gun2_P) ||
+        (regRelay.relay_event.bits.Gun2_N != outputRelay.relay_event.bits.Gun2_N)
+#if !defined DD360Tcci && !defined DD360Audi && !defined DD360ComBox && !defined DD360UCar
+        ||
+        (regRelay.relay_event.bits.Gun1_Parallel_P != outputRelay.relay_event.bits.Gun1_Parallel_P) ||
+        (regRelay.relay_event.bits.Gun1_Parallel_N != outputRelay.relay_event.bits.Gun1_Parallel_N)
+#endif //!defined DD360Tcci && !defined DD360Audi
+    ) {
+        result = true;
+    }
+
+#if !defined DD360Tcci && !defined DD360Audi && !defined DD360ComBox && !defined DD360UCar
+    if (regRelay.relay_event.bits.AC_Contactor != outputRelay.relay_event.bits.AC_Contactor) {
+        log_info("AC Contact Relay none match. ");
+    }
+
+    if (regRelay.relay_event.bits.CCS_Precharge != outputRelay.relay_event.bits.CCS_Precharge) {
+        log_info("CCS Precharge Relay none match. ");
+    }
+#endif //
+
+    if (regRelay.relay_event.bits.Gun1_P != outputRelay.relay_event.bits.Gun1_P) {
+        //log_info("SMR1:D+ Relay none match. ");
+        StartCheckRelayInfo(RELAY_SMR1_P_STATUS, outputRelay.relay_event.bits.Gun1_P);
+    } else {
+        StopCheckRelayInfo(RELAY_SMR1_P_STATUS);
+    }
+
+    if (regRelay.relay_event.bits.Gun1_N != outputRelay.relay_event.bits.Gun1_N) {
+        //log_info("SMR1:D- Relay none match. ");
+        StartCheckRelayInfo(RELAY_SMR1_N_STATUS, outputRelay.relay_event.bits.Gun1_N);
+    } else {
+        StopCheckRelayInfo(RELAY_SMR1_N_STATUS);
+    }
+
+    if (regRelay.relay_event.bits.Gun2_P != outputRelay.relay_event.bits.Gun2_P) {
+        //log_info("SMR2:D+ Relay none match. ");
+        StartCheckRelayInfo(RELAY_SMR2_P_STATUS, outputRelay.relay_event.bits.Gun2_P);
+    } else {
+        StopCheckRelayInfo(RELAY_SMR2_P_STATUS);
+    }
+
+    if (regRelay.relay_event.bits.Gun2_N != outputRelay.relay_event.bits.Gun2_N) {
+        //log_info("SMR2:D- Relay none match. ");
+        StartCheckRelayInfo(RELAY_SMR2_N_STATUS, outputRelay.relay_event.bits.Gun2_N);
+    } else {
+        StopCheckRelayInfo(RELAY_SMR2_N_STATUS);
+    }
+
+#if !defined DD360Tcci && !defined DD360Audi && !defined DD360ComBox && !defined DD360UCar
+    if (regRelay.relay_event.bits.Gun1_Parallel_P != outputRelay.relay_event.bits.Gun1_Parallel_P) {
+        //log_info("Parallel:D+ Relay none match. ");
+        StartCheckRelayInfo(RELAY_PARA_P_STATUS, outputRelay.relay_event.bits.Gun1_Parallel_P);
+    } else {
+        StopCheckRelayInfo(RELAY_PARA_P_STATUS);
+    }
+
+    if (regRelay.relay_event.bits.Gun1_Parallel_N != outputRelay.relay_event.bits.Gun1_Parallel_N) {
+        //log_info("Parallel:D- Relay none match. ");
+        StartCheckRelayInfo(RELAY_PARA_N_STATUS, outputRelay.relay_event.bits.Gun1_Parallel_N);
+    } else {
+        StopCheckRelayInfo(RELAY_PARA_N_STATUS);
+    }
+#endif //
+
+    return result;
+}
+
+static void SetParalleRelayStatus(void)
+{
+#if defined DD360Tcci || defined DD360Audi || defined DD360ComBox || defined DD360UCar
+    return;
+#endif //!defined  DD360Tcci || !defined DD360Audi || !defined DD360ComBox
+
+    struct ChargingInfoData *pDcChargingInfo0 = (struct ChargingInfoData *)GetDcChargingInfoData(0);
+    struct ChargingInfoData *pDcChargingInfo1 = (struct ChargingInfoData *)GetDcChargingInfoData(1);
+
+    // 之後雙槍單模機種,橋接都會上
+    if (pSysConfig->TotalConnectorCount >= 2) {
+        if (pDcChargingInfo0->SystemStatus == S_BOOTING || pDcChargingInfo1->SystemStatus == S_BOOTING ||
+                (pDcChargingInfo0->SystemStatus == S_IDLE && pDcChargingInfo1->SystemStatus == S_IDLE)) {
+            // 初始化~ 不搭橋接
+            if (regRelay.relay_event.bits.Gun1_Parallel_P == YES) {
+                outputRelay.relay_event.bits.Gun1_Parallel_P = NO;
+            } else if (regRelay.relay_event.bits.Gun1_Parallel_N == YES) {
+                outputRelay.relay_event.bits.Gun1_Parallel_N = NO;
+            }
+        } else {
+            if (pDcChargingInfo0->IsReadyToCharging == YES ||
+                    pDcChargingInfo1->IsReadyToCharging == YES) {
+                // ************需考慮在切換中 - 切開 relay 與搭回 relay 的時機點************
+                if (pSysInfo->MainChargingMode == _MAIN_CHARGING_MODE_MAX) {
+                    if (pSysInfo->ReAssignedFlag < _REASSIGNED_RELAY_M_TO_A) {
+                        // 最大充 - 搭上橋接
+                        if (regRelay.relay_event.bits.Gun1_Parallel_N == NO) {
+                            outputRelay.relay_event.bits.Gun1_Parallel_N = YES;
+                        } else if (regRelay.relay_event.bits.Gun1_Parallel_P == NO) {
+                            outputRelay.relay_event.bits.Gun1_Parallel_P = YES;
+                        }
+                    } else {
+                        // 平均充 - 不搭
+                        if (regRelay.relay_event.bits.Gun1_Parallel_P == YES) {
+                            outputRelay.relay_event.bits.Gun1_Parallel_P = NO;
+                        } else if (regRelay.relay_event.bits.Gun1_Parallel_N == YES) {
+                            outputRelay.relay_event.bits.Gun1_Parallel_N = NO;
+                        }
+                    }
+                } else if (pSysInfo->MainChargingMode == _MAIN_CHARGING_MODE_AVER) {
+                    if (pSysInfo->ReAssignedFlag < _REASSIGNED_RELAY_A_TO_M) {
+                        // 平均充 - 不搭
+                        if (regRelay.relay_event.bits.Gun1_Parallel_P == YES) {
+                            outputRelay.relay_event.bits.Gun1_Parallel_P = NO;
+                        } else if (regRelay.relay_event.bits.Gun1_Parallel_N == YES) {
+                            outputRelay.relay_event.bits.Gun1_Parallel_N = NO;
+                        }
+                    } else {
+                        // 最大充 - 搭上橋接
+                        if (regRelay.relay_event.bits.Gun1_Parallel_N == NO) {
+                            outputRelay.relay_event.bits.Gun1_Parallel_N = YES;
+                        } else if (regRelay.relay_event.bits.Gun1_Parallel_P == NO) {
+                            outputRelay.relay_event.bits.Gun1_Parallel_P = YES;
+                        }
+                    }
+                }
+            }
+        }
+    }
+}
+
+static void GetGfdAdc(void)
+{
+    int gunIndex = 0;
+    uint8_t targetID = 0;
+    struct ChargingInfoData *pDcChargingInfo = NULL;
+    Gfd gfd_adc = {0};
+
+    // define : 每 0.2 ~ 1 秒一次
+    // occur : <= 75k 歐姆 @ 150 - 750 Vdc
+    // warning : >= 100 歐姆 && <= 500 歐姆 @ 150-750 Vdc
+    if (Query_Gfd_Adc(Uart5Fd, ADDR_RELAY, &gfd_adc) == PASS) {
+        for (gunIndex = 0; gunIndex < pSysConfig->TotalConnectorCount; gunIndex++) {
+            pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+
+            if (pDcChargingInfo->Type == 0x09 &&
+                    !pSysConfig->AlwaysGfdFlag
+               ) {
+                if ((pDcChargingInfo->PresentChargingVoltage * 10) >= VOUT_MIN_VOLTAGE) {
+                    pDcChargingInfo->GroundFaultStatus = GFD_PASS;
+                }
+                continue;
+            }
+
+            targetID = getCommTargetID(gunIndex);
+
+            if (targetID == 0x01) {
+                //if (gfd_adc.result_conn1 == GFD_WARNING) {
+                //    gfd_adc.result_conn1 = GFD_PASS;
+                //}
+
+                pDcChargingInfo->GroundFaultStatus = gfd_adc.result_conn1;
+                //log_info("GFD ******** Result = %d, Step = %d, R = %d, Vol = %d ",
+                //            pDcChargingInfo->GroundFaultStatus,
+                //            gfd_adc.rb_step_1,
+                //            gfd_adc.Resister_conn1,
+                //            gfd_adc.voltage_conn1);
+                if (pDcChargingInfo->GroundFaultStatus == GFD_FAIL) {
+                    log_info("GFD Fail. index = %d, Step = %d, R = %d, Vol = %d ",
+                             gunIndex,
+                             gfd_adc.rb_step_1,
+                             gfd_adc.Resister_conn1,
+                             gfd_adc.voltage_conn1);
+
+                } else if (pDcChargingInfo->GroundFaultStatus == GFD_PASS ||
+                           pDcChargingInfo->GroundFaultStatus == GFD_WARNING
+                          ) {
+                    if (pDcChargingInfo->GroundFaultStatus == GFD_WARNING && _show_GFD_Warming[gunIndex]) {
+                        log_info("GFD Warning. index = %d, Result = %d, R = %d, Vol = %d ",
+                                 gunIndex,
+                                 pDcChargingInfo->GroundFaultStatus,
+                                 gfd_adc.Resister_conn1,
+                                 gfd_adc.voltage_conn1);
+                        _show_GFD_Warming[gunIndex] = FALSE;
+                    }
+                }
+            } else if (targetID == 0x02) {
+                //if (gfd_adc.result_conn2 == GFD_WARNING) {
+                //    gfd_adc.result_conn2 = GFD_PASS;
+                //}
+                pDcChargingInfo->GroundFaultStatus = gfd_adc.result_conn2;
+                if (pDcChargingInfo->GroundFaultStatus == GFD_FAIL) {
+                    log_info("GFD Fail. index = %d, Step = %d, R = %d, Vol = %d ",
+                             gunIndex,
+                             gfd_adc.rb_step_2,
+                             gfd_adc.Resister_conn2,
+                             gfd_adc.voltage_conn2);
+                } else if (pDcChargingInfo->GroundFaultStatus == GFD_PASS ||
+                           pDcChargingInfo->GroundFaultStatus == GFD_WARNING
+                          ) {
+                    if (pDcChargingInfo->GroundFaultStatus == GFD_WARNING && _show_GFD_Warming[gunIndex]) {
+                        log_info("GFD Warning. index = %d, Result = %d, R = %d, Vol = %d ",
+                                 gunIndex,
+                                 pDcChargingInfo->GroundFaultStatus,
+                                 gfd_adc.Resister_conn1,
+                                 gfd_adc.voltage_conn1);
+                        _show_GFD_Warming[gunIndex] = FALSE;
+                    }
+                }
+            }
+        }
+    }
+}
+
+void CheckOutputPowerOverCarReq(uint8_t index)
+{
+    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);
+
+    float fireV = pDcChargingInfo->FireChargingVoltage;
+    float carV = pDcChargingInfo->EvBatteryMaxVoltage * 10;
+
+    if ((pDcChargingInfo->EvBatterytargetVoltage * 10) > 1500 &&
+            (pDcChargingInfo->Type == _Type_Chademo ||
+             pDcChargingInfo->Type == _Type_CCS_2 ||
+             pDcChargingInfo->Type == _Type_GB)) {
+        if (fireV >= (carV + (carV * 0.02))) {
+            if (!_isOvpChkTimeFlag[index]) {
+                if ((pDcChargingInfo->PresentChargingVoltage * 10) >= VOUT_MIN_VOLTAGE * 10) {
+                    GetClockTime(&_checkOutputVolProtectTimer[index], NULL);
+                    _isOvpChkTimeFlag[index] = YES;
+                }
+            } else {
+                log_info("[Module_InternalComm]CheckOutputPowerOverCarReq NG : fire = %f, battery = %f ",
+                         pDcChargingInfo->FireChargingVoltage,
+                         (pDcChargingInfo->EvBatterytargetVoltage * 10));
+
+                log_error("[Module_InternalComm]CheckOutputPowerOverCarReq NG : fire = %f, battery = %f ",
+                          pDcChargingInfo->FireChargingVoltage,
+                          (pDcChargingInfo->EvBatterytargetVoltage * 10));
+                if ((GetClockTimeoutValue(_checkOutputVolProtectTimer[index]) / 1000) >= OUTPUT_VOL_CHK_TIME) {
+                    if (pDcChargingInfo->Type == _Type_Chademo) {
+                        //pAlarmCode->AlarmEvents.bits.SystemChademoOutputOVP = YES;
+                        ShmDcCommonData->ConnectErrList[index].GunBits.ChaConnectOVP = YES;
+                    } else if (pDcChargingInfo->Type == _Type_CCS_2) {
+                        //pAlarmCode->AlarmEvents.bits.SystemCcsOutputOVP = YES;
+                        ShmDcCommonData->ConnectErrList[index].GunBits.CCSConnectOVP = YES;
+                    } else if (pDcChargingInfo->Type == _Type_GB) {
+                        //pAlarmCode->AlarmEvents.bits.SystemGbOutputOVP = YES;
+                        ShmDcCommonData->ConnectErrList[index].GunBits.GBTConnectOVP = YES;
+                    }
+                    //pDcChargingInfo->StopChargeFlag = YES;
+                }
+            }
+        } else {
+            if (_isOvpChkTimeFlag[index] == YES) {
+                _isOvpChkTimeFlag[index] = NO;
+            }
+        }
+    }
+}
+
+void ResetDetAlarmStatus(uint8_t gun)
+{
+    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gun);
+
+    if (pDcChargingInfo->Type == _Type_Chademo) {
+        if (pAlarmCode->AlarmEvents.bits.SystemChademoOutputOVP == YES) {
+            pAlarmCode->AlarmEvents.bits.SystemChademoOutputOVP = NO;
+        }
+    } else if (pDcChargingInfo->Type == _Type_GB) {
+        if (pAlarmCode->AlarmEvents.bits.SystemGbOutputOVP == YES) {
+            pAlarmCode->AlarmEvents.bits.SystemGbOutputOVP = NO;
+        }
+    } else if (pDcChargingInfo->Type == _Type_CCS_2) {
+        if (pAlarmCode->AlarmEvents.bits.SystemCcsOutputOVP == YES) {
+            pAlarmCode->AlarmEvents.bits.SystemCcsOutputOVP = NO;
+        }
+    }
+}
+
+void CheckAcInputOvpStatus(uint8_t index)
+{
+    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);
+
+    if (pAlarmCode->AlarmEvents.bits.SystemL1InputOVP == YES ||
+            pAlarmCode->AlarmEvents.bits.SystemL2InputOVP == YES ||
+            pAlarmCode->AlarmEvents.bits.SystemL3InputOVP == YES) {
+//      if ((pDcChargingInfo->SystemStatus >= S_PREPARNING && pDcChargingInfo->SystemStatus <= S_CHARGING) ||
+//              (pDcChargingInfo->SystemStatus >= S_CCS_PRECHARGE_ST0 && pDcChargingInfo->SystemStatus <= S_CCS_PRECHARGE_ST1))
+//      {
+//          if (pSysInfo->ChargerType == _CHARGER_TYPE_IEC)
+//          {
+//              if (_psuInputVolR > VIN_MAX_VOLTAGE_IEC ||
+//                      _psuInputVolS > VIN_MAX_VOLTAGE_IEC ||
+//                      _psuInputVolT > VIN_MAX_VOLTAGE_IEC)
+//              {
+//                  log_info("IEC _psuInputVolR = %f, _psuInputVolS = %f, _psuInputVolT = %f ",
+//                          _psuInputVolR, _psuInputVolS, _psuInputVolT);
+//                  pDcChargingInfo->StopChargeFlag = YES;
+//              }
+//
+//          }
+//          else if (pSysInfo->ChargerType == _CHARGER_TYPE_UL)
+//          {
+//              if (_psuInputVolR > VIN_MAX_VOLTAGE_UL ||
+//                      _psuInputVolS > VIN_MAX_VOLTAGE_UL ||
+//                      _psuInputVolT > VIN_MAX_VOLTAGE_UL)
+//              {
+//                  log_info("UL _psuInputVolR = %f, _psuInputVolS = %f, _psuInputVolT = %f ",
+//                          _psuInputVolR, _psuInputVolS, _psuInputVolT);
+//                  pDcChargingInfo->StopChargeFlag = YES;
+//              }
+//          }
+//      }
+//      else
+        log_info("CheckAcInputOvpStatus");
+        pDcChargingInfo->StopChargeFlag = YES;
+    }
+}
+
+//void CheckOutputVolNoneMatchFire(uint8_t index)
+//{
+//    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);
+//
+//    if ((pDcChargingInfo->EvBatterytargetVoltage * 10) > 1500 &&
+//            (pDcChargingInfo->Type == _Type_Chademo ||
+//             pDcChargingInfo->Type == _Type_CCS_2 ||
+//             pDcChargingInfo->Type == _Type_GB)) {
+//        if (((pDcChargingInfo->PresentChargingVoltage * 10) < pDcChargingInfo->FireChargingVoltage - 300) ||
+//                ((pDcChargingInfo->PresentChargingVoltage * 10) > pDcChargingInfo->FireChargingVoltage + 300)) {
+//            if (!_isOutputNoneMatch[index]) {
+//                _isOutputNoneMatch[index] = YES;
+//                GetClockTime(&_checkOutputNoneMatchTimer[index], NULL);
+//            } else {
+//                if ((GetClockTimeoutValue(_checkOutputNoneMatchTimer[index]) / 1000) >= 5000) {
+//                    /*log_info("[Module_InternalComm]CheckOutputVolNoneMatchFire NG (%d) : pre = %f, fire = %f ",
+//                            index, (pDcChargingInfo->PresentChargingVoltage * 10), pDcChargingInfo->FireChargingVoltage);
+//                    log_error("[Module_InternalComm]CheckOutputVolNoneMatchFire NG (%d): pre = %f, fire = %f ",
+//                            index, (pDcChargingInfo->PresentChargingVoltage * 10), pDcChargingInfo->FireChargingVoltage);
+//                    pDcChargingInfo->StopChargeFlag = YES;*/
+//                }
+//            }
+//        } else {
+//            _isOutputNoneMatch[index] = NO;
+//        }
+//    }
+//}
+
+void CheckPhaseLossStatus(uint8_t index)
+{
+    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);
+
+    if (pAlarmCode->AlarmEvents.bits.SystemL1InputUVP == YES ||
+            pAlarmCode->AlarmEvents.bits.SystemL2InputUVP == YES ||
+            pAlarmCode->AlarmEvents.bits.SystemL3InputUVP == YES) {
+        log_info("CheckPhaseLossStatus");
+        pDcChargingInfo->StopChargeFlag = YES;
+    }
+}
+
+void SetK1K2RelayStatus(uint8_t index)
+{
+    uint8_t targetID = 0;
+    PreChargingState *pRegPreChargingState = NULL;
+    PreChargingState *pOutputPreChargingState = NULL;
+    GunPNState *pRegGunPNState = NULL;
+    GunPNState *pOutputGunPNState = NULL;
+    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);
+
+    if (ShmPsuData->Work_Step >= _TEST_MODE &&
+            ShmPsuData->Work_Step <= _TEST_MODE) {
+        if (regRelay.relay_event.bits.Gun1_N == NO) {
+            outputRelay.relay_event.bits.Gun1_N = YES;
+        } else if (regRelay.relay_event.bits.Gun1_P == NO) {
+            outputRelay.relay_event.bits.Gun1_P = YES;
+        }
+        return;
+    }
+
+    targetID = getCommTargetID(index);
+
+    pRegPreChargingState = (PreChargingState *)&regRelay.relay_event.relay_status[0];
+    pOutputPreChargingState = (PreChargingState *)&outputRelay.relay_event.relay_status[0];
+    if (targetID == 0x01) {
+        pRegGunPNState = (GunPNState *)&regRelay.relay_event.relay_status[1];
+        pOutputGunPNState = (GunPNState *)&outputRelay.relay_event.relay_status[1];
+    } else if (targetID == 0x02) {
+        pRegGunPNState = (GunPNState *)&regRelay.relay_event.relay_status[2];
+        pOutputGunPNState = (GunPNState *)&outputRelay.relay_event.relay_status[2];
+    }
+
+    switch (pDcChargingInfo->SystemStatus) {
+    case S_BOOTING:
+    case S_IDLE:
+    case S_AUTHORIZING:
+    case S_REASSIGN_CHECK:
+    case S_REASSIGN:
+    case S_PREPARNING:
+    case S_PREPARING_FOR_EV:
+        if (pRegGunPNState->GunP == YES) {
+            pOutputGunPNState->GunP = NO;
+        } else if (pRegGunPNState->GunN == YES) {
+            pOutputGunPNState->GunN = NO;
+        }
+
+        if (targetID == 0x02 && pDcChargingInfo->Type == _Type_CCS_2) {
+            if (pRegPreChargingState->CcsPrecharge == YES) {
+                pOutputPreChargingState->CcsPrecharge = NO;
+            }
+        }
+        break;
+
+    case S_PREPARING_FOR_EVSE:
+    case S_CHARGING:
+        //if (pDcChargingInfo->RelayWeldingCheck != YES) {
+        //    break;
+        //}
+        if (pRegGunPNState->GunN == NO) {
+            if (pDcChargingInfo->GroundFaultStatus != GFD_FAIL) {
+                pOutputGunPNState->GunN = YES;
+            } else {
+                pOutputGunPNState->GunN = NO;
+            }
+        } else {
+            if (pDcChargingInfo->GroundFaultStatus == GFD_FAIL) {
+                pOutputGunPNState->GunN = NO;
+            }
+        }
+        if (pRegGunPNState->GunP == NO) {
+            if (pDcChargingInfo->GroundFaultStatus != GFD_FAIL) {
+                pOutputGunPNState->GunP = YES;
+            } else {
+                pOutputGunPNState->GunP = NO;
+            }
+        } else {
+            if (pDcChargingInfo->GroundFaultStatus == GFD_FAIL) {
+                pOutputGunPNState->GunP = NO;
+            }
+        }
+        break;
+
+    case S_TERMINATING:
+    case S_COMPLETE:
+    case S_ALARM:
+        if ((pDcChargingInfo->PresentChargingCurrent * 10) <= SEFETY_SWITCH_RELAY_CUR) {
+            pOutputGunPNState->GunP = NO;
+            pOutputGunPNState->GunN = NO;
+        }
+        if (pDcChargingInfo->GroundFaultStatus == GFD_FAIL) {
+            pOutputGunPNState->GunP = NO;
+            pOutputGunPNState->GunN = NO;
+        }
+        break;
+
+    case S_CCS_PRECHARGE_ST0:
+#if defined DD360Tcci || defined DD360Audi || defined DD360ComBox || defined DD360UCar
+        break;
+#endif //defined DD360Tcci || defined DD360Audi || defined DD360ComBox
+
+        //if (pDcChargingInfo->Type == _Type_CCS_2 && targetID == 0x02) {
+        //    if (pRegPreChargingState->CcsPrecharge == NO) {
+        //        pOutputPreChargingState->CcsPrecharge = YES;
+        //    } else if (pRegPreChargingState->CcsPrecharge == YES) {
+        //        pRegGunPNState->GunP = NO;
+        //    }
+        //}
+        if (pDcChargingInfo->GroundFaultStatus == GFD_FAIL) {
+            pOutputGunPNState->GunP = NO;
+            pOutputGunPNState->GunN = NO;
+        }
+        break;
+
+    case S_CCS_PRECHARGE_ST1:
+#if defined DD360Tcci || defined DD360Audi || defined DD360ComBox || defined DD360UCar
+        break;
+#endif //defined DD360Tcci || defined DD360Audi || defined DD360ComBox
+
+        //if (pDcChargingInfo->Type == _Type_CCS_2 && targetID == 0x02) {
+        //    if (pRegGunPNState->GunP == NO) {
+        //        pOutputGunPNState->GunP = YES;
+        //    } else if (pRegGunPNState->GunP == YES) {
+        //        pOutputPreChargingState->CcsPrecharge = NO;
+        //    }
+        //}
+        if (pDcChargingInfo->GroundFaultStatus == GFD_FAIL) {
+            pOutputGunPNState->GunP = NO;
+            pOutputGunPNState->GunN = NO;
+        }
+        break;
+    }
+}
+
+// 確認 K1 K2 relay 的狀態
+void CheckK1K2RelayOutput(uint8_t index)
+{
+    uint8_t targetID = 0;
+    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);
+
+    targetID = getCommTargetID(index);
+
+    switch (targetID) {
+    case 0x01:
+        if (regRelay.relay_event.bits.Gun1_N == YES && regRelay.relay_event.bits.Gun1_P == YES) {
+            pDcChargingInfo->RelayK1K2Status = YES;
+        } else {
+            pDcChargingInfo->RelayK1K2Status = NO;
+        }
+
+        if (pDcChargingInfo->Type == _Type_CCS_2) {
+#if !defined DD360Tcci && !defined DD360Audi && !defined DD360ComBox && !defined DD360UCar
+            if (regRelay.relay_event.bits.Gun1_N == YES && regRelay.relay_event.bits.CCS_Precharge == YES) {
+                pDcChargingInfo->RelayKPK2Status = YES;
+            } else {
+                pDcChargingInfo->RelayKPK2Status = NO;
+            }
+#else
+            if (pDcChargingInfo->SystemStatus == S_CCS_PRECHARGE_ST0) {
+                pDcChargingInfo->RelayKPK2Status = YES;
+            } else {
+                pDcChargingInfo->RelayKPK2Status = NO;
+            }
+#endif //!defined DD360Tcci && !defined DD360Audi
+        }
+        break;
+
+    case 0x02:
+        if (regRelay.relay_event.bits.Gun2_N == YES &&
+                regRelay.relay_event.bits.Gun2_P == YES) {
+            pDcChargingInfo->RelayK1K2Status = YES;
+        } else {
+            pDcChargingInfo->RelayK1K2Status = NO;
+        }
+
+        if (pDcChargingInfo->Type == _Type_CCS_2) {
+#if !defined DD360Tcci && !defined DD360Audi && !defined DD360ComBox && !defined DD360UCar
+            if (regRelay.relay_event.bits.Gun2_N == YES &&
+                    regRelay.relay_event.bits.CCS_Precharge == YES) {
+                pDcChargingInfo->RelayKPK2Status = YES;
+            } else {
+                pDcChargingInfo->RelayKPK2Status = NO;
+            }
+#else
+            if (pDcChargingInfo->SystemStatus == S_CCS_PRECHARGE_ST0) {
+                pDcChargingInfo->RelayKPK2Status = YES;
+            } else {
+                pDcChargingInfo->RelayKPK2Status = NO;
+            }
+#endif //!defined DD360Tcci && !defined DD360Audi
+        }
+        break;
+    }
+
+#if !defined DD360Tcci && !defined DD360Audi && !defined DD360ComBox && !defined DD360UCar
+    //DS60-120 add
+    if (pSysInfo->BridgeRelayStatus == YES) {
+        if (regRelay.relay_event.bits.Gun1_Parallel_N == NO &&
+                regRelay.relay_event.bits.Gun1_Parallel_P == NO) {
+            pSysInfo->BridgeRelayStatus = NO;
+        }
+    } else if (pSysInfo->BridgeRelayStatus == NO) {
+        if (regRelay.relay_event.bits.Gun1_Parallel_N == YES &&
+                regRelay.relay_event.bits.Gun1_Parallel_P == YES) {
+            pSysInfo->BridgeRelayStatus = YES;
+        }
+    }
+#else
+    pSysInfo->BridgeRelayStatus = YES;
+#endif //!defined DD360Tcci && !defined DD360Audi
+}
+
+void SetGfdConfig(uint8_t index, uint8_t resister)
+{
+    Gfd_config gfd_config = {
+        .index = index,
+        .state = resister,
+    };
+
+    //log_info("************************GFD Vol = %d, GFD Res = %d ", gfd_config.reqVol, gfd_config.resister);
+    if (Config_Gfd_Value(Uart5Fd, ADDR_RELAY, &gfd_config) == PASS) {
+//      log_info("Set reqVol = %f, resister = %d ",
+//              gfd_config.reqVol,
+//              gfd_config.resister);
+    }
+}
+
+void CableCheckDetected(uint8_t index)
+{
+    uint8_t targetID = 0;
+    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);
+    // Cable Check
+    // 當火線上的電壓 = 車端要求的電壓電流
+    // _chargingData[targetGun]->EvBatterytargetVoltage
+    // 才可以開始偵測 1s
+    // Warning : Rgfd <= 150 歐/V 假設電壓為 500V 則~ Rgfd <= 75000 歐
+    // Pre-Warning : 150 歐/V < Rgfd <= 500 歐/V 假設電壓為 500V 則 75000 歐 < Rgfd <= 250000
+    // SO Normal : Rgfd > 500 歐/V 假設電壓為 500 V 則 Rgfd > 250000 歐
+
+    if (pSysConfig->TotalConnectorCount == 1) {
+        if (strncmp((char *)&pSysConfig->ModelName[7], "0", 1) != 0) {
+            targetID = 0;
+        } else if (strncmp((char *)&pSysConfig->ModelName[9], "0", 1) != 0) {
+            targetID = 1;
+        }
+    } else {
+        targetID = index;
+    }
+
+    if ((pDcChargingInfo->Type >= _Type_Chademo &&
+            pDcChargingInfo->Type <= _Type_GB) ||
+            (pDcChargingInfo->Type == 0x09 &&
+             pSysConfig->AlwaysGfdFlag)
+       ) {
+        if ((pDcChargingInfo->SystemStatus >= S_PREPARING_FOR_EVSE &&
+                pDcChargingInfo->SystemStatus < S_TERMINATING) ||
+                (pDcChargingInfo->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
+                 pDcChargingInfo->SystemStatus <= S_CCS_PRECHARGE_ST1)
+           ) {
+            //if ((pDcChargingInfo->SystemStatus == S_PREPARING_FOR_EVSE) &&
+            //        (pDcChargingInfo->RelayWeldingCheck == YES)
+            //   ) {
+            if (pDcChargingInfo->SystemStatus == S_PREPARING_FOR_EVSE) {
+                SetGfdConfig(targetID, GFD_CABLECHK);
+            } else if ((pDcChargingInfo->SystemStatus >= S_CCS_PRECHARGE_ST0) &&
+                       (pDcChargingInfo->SystemStatus <= S_CCS_PRECHARGE_ST1)
+                      ) {
+                SetGfdConfig(targetID, GFD_PRECHARGE);
+            } else if ((pDcChargingInfo->SystemStatus >= S_CHARGING) &&
+                       (pDcChargingInfo->SystemStatus < S_TERMINATING)
+                      ) {
+                if ((pDcChargingInfo->Type == _Type_GB) ||
+                        (pDcChargingInfo->Type == _Type_Chademo)
+                   ) {
+                    SetGfdConfig(targetID, GFD_IDLE);
+                } else {
+                    SetGfdConfig(targetID, GFD_CHARGING);
+                }
+            }
+        }
+        else if(pDcChargingInfo->SystemStatus == S_TERMINATING || pDcChargingInfo->SystemStatus == S_ALARM)
+        {
+            if (pDcChargingInfo->Type == _Type_CCS_2)
+            {
+                SetGfdConfig(targetID, GFD_CHARGING);
+            }
+        } else {
+            SetGfdConfig(targetID, GFD_IDLE);
+        }
+    }
+}
+
+// 讀取 Relay 狀態
+void GetRelayOutputStatus(void)
+{
+    if (Query_Relay_Output(Uart5Fd, ADDR_RELAY, &regRelay) == PASS) {
+#if !defined DD360Tcci && !defined DD360Audi && !defined DD360ComBox && !defined DD360UCar
+        regRelay.relay_event.bits.AC_Contactor = pSysInfo->AcContactorStatus;
+#endif //!defined DD360Tcci && !defined DD360Audi
+    }
+}
+
+// AC 三相輸入電壓
+void GetPresentInputVol(void)
+{
+    static uint8_t _threePhaseOvp[3] = {0, 0, 0}; //DS60-120 add
+    static uint8_t _threePhaseUvp[3] = {0, 0, 0}; //DS60-120 add
+    PresentInputVoltage inputVoltage = {0};
+
+    if (Query_Present_InputVoltage(Uart5Fd, ADDR_RELAY, &inputVoltage) == PASS) {
+        // resolution : 0.1
+        pSysInfo->InputVoltageR = ShmRelayModuleData->InputL1Volt = inputVoltage.L1N_L12;
+        pSysInfo->InputVoltageS = ShmRelayModuleData->InputL2Volt = inputVoltage.L2N_L23;
+        pSysInfo->InputVoltageT = ShmRelayModuleData->InputL3Volt = inputVoltage.L3N_L31;
+
+        //********************************************************************************************************//
+        // Vin (UVP)
+        if (pSysInfo->ChargerType == _CHARGER_TYPE_IEC) {
+            if (pAlarmCode->AlarmEvents.bits.SystemL1InputUVP == NO) {
+                if (inputVoltage.L1N_L12 < VIN_MIN_VOLTAGE_IEC) {
+                    log_info("In Uvp L1N_L12 = %f ", inputVoltage.L1N_L12);
+                    if (_threePhaseUvp[0] >= OVP_UVP_CHK_COUNT) {
+                        pAlarmCode->AlarmEvents.bits.SystemL1InputUVP = YES;
+                    } else {
+                        _threePhaseUvp[0] += 1;
+                    }
+                }
+            } else {
+                if (inputVoltage.L1N_L12 > VIN_MIN_REV_VOLTAGE_IEC) {
+                    pAlarmCode->AlarmEvents.bits.SystemL1InputUVP = NO;
+                    _threePhaseUvp[0] = 0;
+                }
+            }
+
+            if (pAlarmCode->AlarmEvents.bits.SystemL2InputUVP == NO) {
+                if (inputVoltage.L2N_L23 < VIN_MIN_VOLTAGE_IEC) {
+                    log_info("In Uvp L2N_L23 = %f ", inputVoltage.L2N_L23);
+                    if (_threePhaseUvp[1] >= OVP_UVP_CHK_COUNT) {
+                        pAlarmCode->AlarmEvents.bits.SystemL2InputUVP = YES;
+                    } else {
+                        _threePhaseUvp[1] += 1;
+                    }
+                }
+            } else {
+                if (inputVoltage.L2N_L23 > VIN_MIN_REV_VOLTAGE_IEC) {
+                    pAlarmCode->AlarmEvents.bits.SystemL2InputUVP = NO;
+                    _threePhaseUvp[1] = 0;
+                }
+            }
+
+            if (pAlarmCode->AlarmEvents.bits.SystemL3InputUVP == NO) {
+                if (inputVoltage.L3N_L31 < VIN_MIN_VOLTAGE_IEC) {
+                    log_info("In Uvp L3N_L31 = %f ", inputVoltage.L3N_L31);
+                    if (_threePhaseUvp[2] >= OVP_UVP_CHK_COUNT) {
+                        pAlarmCode->AlarmEvents.bits.SystemL3InputUVP = YES;
+                    } else {
+                        _threePhaseUvp[2] += 1;
+                    }
+                }
+            } else {
+                if (inputVoltage.L3N_L31 > VIN_MIN_REV_VOLTAGE_IEC) {
+                    pAlarmCode->AlarmEvents.bits.SystemL3InputUVP = NO;
+                    _threePhaseUvp[2] = 0;
+                }
+            }
+        } else if (pSysInfo->ChargerType == _CHARGER_TYPE_UL) {
+            if (pAlarmCode->AlarmEvents.bits.SystemL1InputUVP == NO) {
+                if (inputVoltage.L1N_L12 < VIN_MIN_VOLTAGE_UL) {
+                    log_info("In Uvp L1N_L12 = %f ", inputVoltage.L1N_L12);
+                    if (_threePhaseUvp[0] >= OVP_UVP_CHK_COUNT) {
+                        pAlarmCode->AlarmEvents.bits.SystemL1InputUVP = YES;
+                    } else {
+                        _threePhaseUvp[0] += 1;
+                    }
+                }
+            } else {
+                if (inputVoltage.L1N_L12 > VIN_MIN_REV_VOLTAGE_UL) {
+                    pAlarmCode->AlarmEvents.bits.SystemL1InputUVP = NO;
+                    _threePhaseUvp[0] = 0;
+                }
+            }
+
+            if (pAlarmCode->AlarmEvents.bits.SystemL2InputUVP == NO) {
+                if (inputVoltage.L2N_L23 < VIN_MIN_VOLTAGE_UL) {
+                    log_info("In Uvp L2N_L23 = %f ", inputVoltage.L2N_L23);
+                    if (_threePhaseUvp[1] >= OVP_UVP_CHK_COUNT) {
+                        pAlarmCode->AlarmEvents.bits.SystemL2InputUVP = YES;
+                    } else {
+                        _threePhaseUvp[1] += 1;
+                    }
+                }
+            } else {
+                if (inputVoltage.L2N_L23 > VIN_MIN_REV_VOLTAGE_UL) {
+                    pAlarmCode->AlarmEvents.bits.SystemL2InputUVP = NO;
+                    _threePhaseUvp[1] = 0;
+                }
+            }
+
+            if (pAlarmCode->AlarmEvents.bits.SystemL3InputUVP == NO) {
+                if (inputVoltage.L3N_L31 < VIN_MIN_VOLTAGE_UL) {
+                    log_info("In Uvp L3N_L31 = %f ", inputVoltage.L3N_L31);
+                    if (_threePhaseUvp[2] >= OVP_UVP_CHK_COUNT) {
+                        pAlarmCode->AlarmEvents.bits.SystemL3InputUVP = YES;
+                    } else {
+                        _threePhaseUvp[2] += 1;
+                    }
+                }
+            } else {
+                if (inputVoltage.L3N_L31 > VIN_MIN_REV_VOLTAGE_UL) {
+                    pAlarmCode->AlarmEvents.bits.SystemL3InputUVP = NO;
+                    _threePhaseUvp[2] = 0;
+                }
+            }
+        }
+
+        //********************************************************************************************************//
+        // Vin (OVP)
+        if (pSysInfo->ChargerType == _CHARGER_TYPE_IEC) {
+            if (pAlarmCode->AlarmEvents.bits.SystemL1InputOVP == NO) {
+                if (inputVoltage.L1N_L12 > VIN_MAX_VOLTAGE_IEC) {
+                    log_info("In Ovp L1N_L12 = %f ", inputVoltage.L1N_L12);
+                    if (_threePhaseOvp[0] >= OVP_UVP_CHK_COUNT) {
+                        pAlarmCode->AlarmEvents.bits.SystemL1InputOVP = YES;
+                    } else {
+                        _threePhaseOvp[0] += 1;
+                    }
+                }
+            } else {
+                if (inputVoltage.L1N_L12 < VIN_MAX_REV_VOLTAGE_IEC) {
+                    pAlarmCode->AlarmEvents.bits.SystemL1InputOVP = NO;
+                    _threePhaseOvp[0] = 0;
+                }
+            }
+
+            if (pAlarmCode->AlarmEvents.bits.SystemL2InputOVP == NO) {
+                if (inputVoltage.L2N_L23 > VIN_MAX_VOLTAGE_IEC) {
+                    log_info("In Ovp L2N_L23 = %f ", inputVoltage.L2N_L23);
+                    if (_threePhaseOvp[1] >= OVP_UVP_CHK_COUNT) {
+                        pAlarmCode->AlarmEvents.bits.SystemL2InputOVP = YES;
+                    } else {
+                        _threePhaseOvp[1] += 1;
+                    }
+                }
+            } else {
+                if (inputVoltage.L2N_L23 < VIN_MAX_REV_VOLTAGE_IEC) {
+                    pAlarmCode->AlarmEvents.bits.SystemL2InputOVP = NO;
+                    _threePhaseOvp[1] = 0;
+                }
+            }
+
+            if (pAlarmCode->AlarmEvents.bits.SystemL3InputOVP == NO) {
+                if (inputVoltage.L3N_L31 > VIN_MAX_VOLTAGE_IEC) {
+                    log_info("In Ovp L3N_L31 = %f ", inputVoltage.L3N_L31);
+                    if (_threePhaseOvp[2] >= OVP_UVP_CHK_COUNT) {
+                        pAlarmCode->AlarmEvents.bits.SystemL3InputOVP = YES;
+                    } else {
+                        _threePhaseOvp[2] += 1;
+                    }
+                }
+            } else {
+                if (inputVoltage.L3N_L31 < VIN_MAX_REV_VOLTAGE_IEC) {
+                    pAlarmCode->AlarmEvents.bits.SystemL3InputOVP = NO;
+                    _threePhaseOvp[2] = 0;
+                }
+            }
+        } else if (pSysInfo->ChargerType == _CHARGER_TYPE_UL) {
+            if (pAlarmCode->AlarmEvents.bits.SystemL1InputOVP == NO) {
+                if (inputVoltage.L1N_L12 > VIN_MAX_VOLTAGE_UL) {
+                    log_info("In Ovp L1N_L12 = %f ", inputVoltage.L1N_L12);
+                    if (_threePhaseOvp[0] >= OVP_UVP_CHK_COUNT) {
+                        pAlarmCode->AlarmEvents.bits.SystemL1InputOVP = YES;
+                    } else {
+                        _threePhaseOvp[0] += 0;
+                    }
+                }
+            } else {
+                if (inputVoltage.L1N_L12 < VIN_MAX_REV_VOLTAGE_UL) {
+                    pAlarmCode->AlarmEvents.bits.SystemL1InputOVP = NO;
+                    _threePhaseOvp[0] = 0;
+                }
+            }
+
+            if (pAlarmCode->AlarmEvents.bits.SystemL2InputOVP == NO) {
+                if (inputVoltage.L2N_L23 > VIN_MAX_VOLTAGE_UL) {
+                    log_info("In Ovp L2N_L23 = %f ", inputVoltage.L2N_L23);
+                    if (_threePhaseOvp[1] >= OVP_UVP_CHK_COUNT) {
+                        pAlarmCode->AlarmEvents.bits.SystemL2InputOVP = YES;
+                    } else {
+                        _threePhaseOvp[1] += 0;
+                    }
+                }
+            } else {
+                if (inputVoltage.L2N_L23 < VIN_MAX_REV_VOLTAGE_UL) {
+                    pAlarmCode->AlarmEvents.bits.SystemL2InputOVP = NO;
+                    _threePhaseOvp[1] = 0;
+                }
+            }
+
+            if (pAlarmCode->AlarmEvents.bits.SystemL2InputOVP == NO) {
+                if (inputVoltage.L3N_L31 > VIN_MAX_VOLTAGE_UL) {
+                    log_info("In Ovp L3N_L31 = %f ", inputVoltage.L3N_L31);
+                    if (_threePhaseOvp[2] >= OVP_UVP_CHK_COUNT) {
+                        pAlarmCode->AlarmEvents.bits.SystemL3InputOVP = YES;
+                    } else {
+                        _threePhaseOvp[2] += 1;
+                    }
+                }
+            } else {
+                if (inputVoltage.L3N_L31 < VIN_MAX_REV_VOLTAGE_UL) {
+                    pAlarmCode->AlarmEvents.bits.SystemL3InputOVP = NO;
+                    _threePhaseOvp[2] = 0;
+                }
+            }
+        }
+    }
+}
+
+// 左右槍的 Relay 前後的輸出電壓
+void GetPersentOutputVol(void)
+{
+    uint8_t index = 0;
+    uint8_t targetID = 0;
+    struct ChargingInfoData *pDcChargingInfo = NULL;
+    PresentOutputVoltage outputVoltage = {0};
+
+    if (Query_Present_OutputVoltage(Uart5Fd, ADDR_RELAY, &outputVoltage) != PASS) {
+        return;
+    }
+
+    //log_info("Conn1 fuse 1 = %f ", outputVoltage.behindFuse_Voltage_C1);
+    //log_info("Conn1 relay 1 = %f ", outputVoltage.behindRelay_Voltage_C1);
+    //log_info("Conn2 fuse 2 = %f ", outputVoltage.behindFuse_Voltage_C2);
+    //log_info("Conn2 relay 2 = %f ", outputVoltage.behindRelay_Voltage_C2);
+
+    //log_info("outputVoltage.behindFuse_Voltage_C1 = %f ", outputVoltage.behindFuse_Voltage_C1);
+    //log_info("outputVoltage.behindFuse_Voltage_C2 = %f ", outputVoltage.behindFuse_Voltage_C2);
+
+    ShmRelayModuleData->Gun1FuseOutputVolt = outputVoltage.behindFuse_Voltage_C1;
+    ShmRelayModuleData->Gun1RelayOutputVolt = outputVoltage.behindRelay_Voltage_C1;
+    ShmRelayModuleData->Gun2FuseOutputVolt = outputVoltage.behindFuse_Voltage_C2;
+    ShmRelayModuleData->Gun2RelayOutputVolt = outputVoltage.behindRelay_Voltage_C2;
+
+    for (index = 0; index < pSysConfig->TotalConnectorCount; index++) {
+        pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);
+        targetID = getCommTargetID(index);
+
+        switch (targetID) {
+        case 0x01:
+#if defined DD360Tcci || defined DD360Audi || defined DD360ComBox || defined DD360UCar
+            pDcChargingInfo->FireChargingVoltage = ShmRelayModuleData->Gun1RelayOutputVolt;
+            pDcChargingInfo->PresentChargingCurrent = ((float)ShmRelayModuleData->Gun1FuseOutputVolt) / 10;
+            pDcChargingInfo->PresentChargingVoltage = ((float)pDcChargingInfo->FireChargingVoltage) / 10;
+            pDcChargingInfo->FuseChargingVoltage = pDcChargingInfo->FireChargingVoltage;
+            break;
+#endif //defined DD360Tcci || defined DD360Audi || defined DD360ComBox
+
+            pDcChargingInfo->FireChargingVoltage = ShmRelayModuleData->Gun1RelayOutputVolt;
+            pDcChargingInfo->FuseChargingVoltage = ShmRelayModuleData->Gun1FuseOutputVolt;
+            break;
+
+        case 0x02:
+#if defined DD360Tcci || defined DD360Audi || defined DD360ComBox
+            pDcChargingInfo->FireChargingVoltage = ShmRelayModuleData->Gun2RelayOutputVolt;
+            pDcChargingInfo->PresentChargingCurrent = ((float)ShmRelayModuleData->Gun2FuseOutputVolt) / 10;
+            pDcChargingInfo->PresentChargingVoltage = ((float)pDcChargingInfo->FireChargingVoltage) / 10;
+            pDcChargingInfo->FuseChargingVoltage = pDcChargingInfo->FireChargingVoltage;
+            break;
+#endif //defined DD360Tcci || defined DD360Audi || defined DD360ComBox
+
+            pDcChargingInfo->FireChargingVoltage = ShmRelayModuleData->Gun2RelayOutputVolt;
+            pDcChargingInfo->FuseChargingVoltage = ShmRelayModuleData->Gun2FuseOutputVolt;
+            break;
+        }
+
+        //log_info("%d persent vol = %f, cur = %f",
+        //         index,
+        //         pDcChargingInfo->PresentChargingVoltage,
+        //         pDcChargingInfo->PresentChargingCurrent);
+
+        //unsigned short Ovp = 0;
+        //unsigned short Ocp = 0;
+        //Ovp = MIN [VOUT_MAX_VOLTAGE, EV_BATTERY_VOLTAGE]  // 最大輸出電壓與電池電壓最大值
+        //Ocp = MIN [IOUT_MAX_CURRENT, EV_CURRENT_REQ]      // 最大輸出電流與需求電流最小值
+        //if (pDcChargingInfo->Type == _Type_Chademo) {
+        //    //Ovp = MaxValue(pDcChargingInfo->MaximumChargingVoltage, pDcChargingInfo->EvBatteryMaxVoltage);
+        //    //Ocp = MaxValue(pDcChargingInfo->PresentChargingCurrent, ShmCHAdeMOData->ev[pDcChargingInfo->type_index].ChargingCurrentRequest);
+        //} else if (pDcChargingInfo->Type == _Type_CCS_2) {
+        //}
+    }
+}
+
+void SetRtcData_Relay(void)
+{
+    struct timeb csuTime;
+    struct tm *tmCSU;
+    Rtc rtc = {0};
+
+    ftime(&csuTime);
+    tmCSU = localtime(&csuTime.time);
+    //  log_info("Time : %04d-%02d-%02d %02d:%02d:%02d ", tmCSU->tm_year + 1900,
+    //          tmCSU->tm_mon + 1, tmCSU->tm_mday, tmCSU->tm_hour, tmCSU->tm_min,
+    //          tmCSU->tm_sec);
+
+    rtc.RtcData[0] = '0' + (tmCSU->tm_year + 1900) / 1000 % 10;
+    rtc.RtcData[1] = '0' + (tmCSU->tm_year + 1900) / 100 % 10;
+    rtc.RtcData[2] = '0' + (tmCSU->tm_year + 1900) / 10 % 10;
+    rtc.RtcData[3] = '0' + (tmCSU->tm_year + 1900) / 1 % 10;
+
+    rtc.RtcData[4] = '0' + (tmCSU->tm_mon + 1) / 10 % 10;
+    rtc.RtcData[5] = '0' + (tmCSU->tm_mon + 1) / 1 % 10;
+
+    rtc.RtcData[6] = '0' + (tmCSU->tm_mday) / 10 % 10;
+    rtc.RtcData[7] = '0' + (tmCSU->tm_mday) / 1 % 10;
+
+    rtc.RtcData[8] = '0' + (tmCSU->tm_hour) / 10 % 10;
+    rtc.RtcData[9] = '0' + (tmCSU->tm_hour) / 1 % 10;
+
+    rtc.RtcData[10] = '0' + (tmCSU->tm_min) / 10 % 10;
+    rtc.RtcData[11] = '0' + (tmCSU->tm_min) / 1 % 10;
+
+    rtc.RtcData[12] = '0' + (tmCSU->tm_sec) / 10 % 10;
+    rtc.RtcData[13] = '0' + (tmCSU->tm_sec) / 1 % 10;
+
+    if (Config_Rtc_Data(Uart5Fd, ADDR_RELAY, &rtc) == PASS) {
+        //log_info("SetRtc (RB) sucessfully. ");
+    }
+}
+
+void SetModelName_Relay(void)
+{
+    if (Config_Model_Name(Uart5Fd, ADDR_RELAY, pSysConfig->ModelName) == PASS) {
+        //log_info("Set Model name (RB) PASS = %s ", pSysConfig->ModelName);
+    }
+}
+
+void GetFwAndHwVersion_Relay(void)
+{
+    Ver ver = {0};
+
+    if (Query_FW_Ver(Uart5Fd, ADDR_RELAY, &ver) == PASS) {
+        // RelayModuleData
+        strcpy((char *)ShmRelayModuleData->version, ver.Version_FW);
+        // SystemInfo
+        strcpy((char *)pSysInfo->RelayModuleFwRev, ver.Version_FW);
+        //log_info("GetFwAndHwVersion_Relay s1 = %s ", ver.Version_FW);
+    }
+
+    if (Query_HW_Ver(Uart5Fd, ADDR_RELAY, &ver) == PASS) {
+        // SystemInfo
+        strcpy((char *)pSysInfo->RelayModuleHwRev, ver.Version_FW);
+        //log_info("GetFwAndHwVersion_Relay s2 = %s ", ver.Version_HW);
+    }
+}
+
+static void outputRelayInit(int fd)
+{
+    memset((uint8_t *)&outputRelay, 0, sizeof(Relay));
+
+    if (Config_Relay_Output(fd, ADDR_RELAY, &outputRelay) != PASS) {
+        log_info("Config_Relay_Output fail ");
+    }
+}
+
+static bool IsRelayProcessNeedPause(void)
+{
+    bool _pause = false;
+    static bool isPause = false;
+    struct ChargingInfoData *pDcChargingInfo = NULL;
+
+    for (uint8_t i = 0; i < pSysConfig->TotalConnectorCount; i++)
+    {
+        pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(i);
+        if(pDcChargingInfo->SystemStatus == S_UPDATE)
+        {
+            SetLedColor();
+            _pause = true;
+        }
+    }
+    if(isPause != _pause)
+    {
+        log_info("Relay Process Now Is %s ", _pause == true ? "Paused" : "Continued");
+    }
+    isPause = _pause;
+
+    return _pause;
+}
+
+static void SetFanModuleSpeed(void)
+{
+    {
+        FanSpeed _fanSpeed = {0};
+
+        _setFanSpeed += fanSpeedSmoothValue;
+
+        if (_setFanSpeed >= ShmFanModuleData->SetFan1Speed) {
+            _setFanSpeed = ShmFanModuleData->SetFan1Speed;
+        }
+
+        //printf("_setFanSpeed = %d \n", _setFanSpeed);
+        _fanSpeed.speed[0] = _setFanSpeed;
+
+        _fanSpeed.speed[1] = _setFanSpeed;
+
+        _fanSpeed.speed[2] = _setFanSpeed;
+
+        _fanSpeed.speed[3] = _setFanSpeed;
+
+        if (Config_Fan_Speed(Uart5Fd, ADDR_FAN, &_fanSpeed) == PASS) {
+            //log_info("successfully Fan");
+        }
+    }
+}
+
+// 風扇速度
+static void GetFanSpeed(void)
+{
+    FanSpeed fanSpeed = {0};
+
+    //log_info("Get fan board speed ");
+    if (Query_Fan_Speed(Uart5Fd, ADDR_FAN, &fanSpeed) == PASS) {
+        ShmFanModuleData->PresentFan1Speed = fanSpeed.speed[0];
+        ShmFanModuleData->PresentFan2Speed = fanSpeed.speed[1];
+        ShmFanModuleData->PresentFan3Speed = fanSpeed.speed[2];
+        ShmFanModuleData->PresentFan4Speed = fanSpeed.speed[3];
+//      log_info("SystemFanRotaSpeed_1 = %d ", fanSpeed.speed[0]);
+//      log_info("SystemFanRotaSpeed_2 = %d ", fanSpeed.speed[1]);
+//      log_info("SystemFanRotaSpeed_3 = %d ", fanSpeed.speed[2]);
+//      log_info("SystemFanRotaSpeed_4 = %d ", fanSpeed.speed[3]);
+        // Config_Fan_Speed(Uart5Fd, ADDR_FAN, &fanSpeed[0]);
+        //SysInfoData (SystemFanRotaSpeed)
+    }
+}
+
+static void GetFanSpeedByFunction(void)
+{
+    if (ShmDcCommonData->DebugFlag == YES) {
+        return;
+    }
+
+    int gunIndex;
+    struct ChargingInfoData* pDcChargingInfo = NULL;
+    for (gunIndex = 0; gunIndex < pSysConfig->TotalConnectorCount; gunIndex++) {
+        pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(gunIndex);
+        if ((pDcChargingInfo->SystemStatus > S_AUTHORIZING && pDcChargingInfo->SystemStatus < S_TERMINATING) ||
+            (pDcChargingInfo->SystemStatus >= S_CCS_PRECHARGE_ST0 && pDcChargingInfo->SystemStatus <= S_CCS_PRECHARGE_ST1)) {
+            ShmDcCommonData->FanOnTime = time((time_t*)NULL);
+            if (ShmFanModuleData->SetFan1Speed == 0) {
+                ShmFanModuleData->SetFan1Speed = 7000;
+                log_info("Set Fan speed 7000");
+            }
+        }
+    }
+
+    if ((time((time_t*)NULL) - ShmDcCommonData->FanOnTime) >= 600 &&
+        ShmFanModuleData->SetFan1Speed == 7000) {
+        ShmFanModuleData->SetFan1Speed = 0;
+        log_info("Close fan");
+    }
+
+    // 風控修改 :
+    // ******************************************************* //
+    //
+    //       當前PSU輸出總 KW       PSU Temp
+    // 30 x -------------------- x ---------- + 14 x (PSU Temp - 45)
+    //       當前樁最大功率 KW         45
+    //
+    // ******************************************************* //
+    /*
+    // 當前樁最大功率 KW : ShmPsuData->SystemAvailablePower
+    uint32_t _maxPower = ShmPsuData->SystemAvailablePower;
+    // 當前PSU輸出總 KW & PSU Temp :
+    uint8_t temp = 0;
+    uint8_t index = 0;
+    uint8_t count = 0;
+    uint8_t gunIndex = 0;
+    uint8_t _temp_diff = 0;
+    float power = 0;
+    double _pw_rate = 0;
+    double _temp_rate = 0;
+    struct ChargingInfoData *pDcChargingInfo = NULL;
+
+    for (index = 0; index < ShmPsuData->GroupCount; index++) {
+        for (count = 0; count < ShmPsuData->PsuGroup[index].GroupPresentPsuQuantity; count++) {
+            if (temp < ShmPsuData->PsuGroup[index].PsuModule[count].ExletTemp) {
+                temp = ShmPsuData->PsuGroup[index].PsuModule[count].ExletTemp;
+            }
+        }
+    }
+
+    for (gunIndex = 0; gunIndex < pSysConfig->TotalConnectorCount; gunIndex++) {
+        pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+
+        power += (pDcChargingInfo->PresentChargingPower * 10);
+    }
+
+    if (_maxPower > 0) {
+        _pw_rate = power / (double)_maxPower;
+    }
+
+    if (temp > 0) {
+        _temp_rate = (double)temp / 50;
+    }
+
+    if (temp > 45) {
+        _temp_diff = temp - 70;
+    }
+
+    ShmFanModuleData->TestFanSpeed = (((50 * _pw_rate * _temp_rate) + (0.5 * _temp_diff)) / 100) * MAX_FAN_SPEED;
+
+    if (ShmFanModuleData->TestFanSpeed > MAX_FAN_SPEED) {
+        ShmFanModuleData->TestFanSpeed = MAX_FAN_SPEED;
+    }
+
+    if (ShmFanModuleData->TestFanSpeed < 0) {
+        ShmFanModuleData->TestFanSpeed = 0;
+    }
+    */
+//
+//  printf("power = %f \n", power);
+//  printf("_maxPower = %d \n", _maxPower);
+//  printf("temp = %d \n", temp);
+//
+//  printf("_pw_rate = %f \n", _pw_rate);
+//  printf("_temp_rate = %f \n", _temp_rate);
+//  printf("_temp_diff = %d \n", _temp_diff);
+//  printf("fan rate = %f \n", (30 * _pw_rate * _temp_rate + 14 * _temp_diff));
+//  printf("ShmFanModuleData->TestFanSpeed = %d \n", ShmFanModuleData->TestFanSpeed);
+}
+
+static void SetRtcData_Fan(void)
+{
+    struct timeb csuTime;
+    struct tm *tmCSU;
+    Rtc rtc = {0};
+
+    ftime(&csuTime);
+    tmCSU = localtime(&csuTime.time);
+    //  log_info("Time : %04d-%02d-%02d %02d:%02d:%02d ", tmCSU->tm_year + 1900,
+    //          tmCSU->tm_mon + 1, tmCSU->tm_mday, tmCSU->tm_hour, tmCSU->tm_min,
+    //          tmCSU->tm_sec);
+
+    rtc.RtcData[0] = '0' + (tmCSU->tm_year + 1900) / 1000 % 10;
+    rtc.RtcData[1] = '0' + (tmCSU->tm_year + 1900) / 100 % 10;
+    rtc.RtcData[2] = '0' + (tmCSU->tm_year + 1900) / 10 % 10;
+    rtc.RtcData[3] = '0' + (tmCSU->tm_year + 1900) / 1 % 10;
+
+    rtc.RtcData[4] = '0' + (tmCSU->tm_mon + 1) / 10 % 10;
+    rtc.RtcData[5] = '0' + (tmCSU->tm_mon + 1) / 1 % 10;
+
+    rtc.RtcData[6] = '0' + (tmCSU->tm_mday) / 10 % 10;
+    rtc.RtcData[7] = '0' + (tmCSU->tm_mday) / 1 % 10;
+
+    rtc.RtcData[8] = '0' + (tmCSU->tm_hour) / 10 % 10;
+    rtc.RtcData[9] = '0' + (tmCSU->tm_hour) / 1 % 10;
+
+    rtc.RtcData[10] = '0' + (tmCSU->tm_min) / 10 % 10;
+    rtc.RtcData[11] = '0' + (tmCSU->tm_min) / 1 % 10;
+
+    rtc.RtcData[12] = '0' + (tmCSU->tm_sec) / 10 % 10;
+    rtc.RtcData[13] = '0' + (tmCSU->tm_sec) / 1 % 10;
+
+    if (Config_Rtc_Data(Uart5Fd, ADDR_FAN, &rtc) == PASS) {
+        //log_info("SetRtc (FB) sucessfully. ");
+    }
+}
+
+static void SetModelName_Fan(void)
+{
+    if (Config_Model_Name(Uart5Fd, ADDR_FAN, pSysConfig->ModelName) == PASS) {
+        log_info("Set Model name PASS = %s ", pSysConfig->ModelName);
+    }
+}
+
+static void GetFwAndHwVersion_Fan(void)
+{
+    Ver ver = {0};
+
+    if (Query_FW_Ver(Uart5Fd, ADDR_FAN, &ver) == PASS) {
+        // FanModuleData
+        strcpy((char *)ShmFanModuleData->version, ver.Version_FW);
+        // SystemInfo
+        strcpy((char *)pSysInfo->FanModuleFwRev, ver.Version_FW);
+        //log_info("GetFwAndHwVersion_Fan s1 = %s ", ver.Version_FW);
+    }
+
+    if (Query_HW_Ver(Uart5Fd, ADDR_FAN, &ver) == PASS) {
+        // SystemInfo
+        strcpy((char *)pSysInfo->FanModuleHwRev, ver.Version_FW);
+        //log_info("GetFwAndHwVersion_Fan s2 = %s ", ver.Version_HW);
+    }
+}
+
+static void fanBoardSelfTest(void)
+{
+    if (ShmFanModuleData->SelfTest_Comp == YES) {
+        return;
+    }
+
+    GetFwAndHwVersion_Fan();
+    SetModelName_Fan();
+    SetRtcData_Fan();
+    sleep(1);
+    GetClockTime(&gFanBoardRunTimer, NULL);
+}
+
+static void fanBoardPorcess(void)
+{
+    if (ShmFanModuleData->SelfTest_Comp == NO) {
+        return;
+    }
+
+    if (ShmFanModuleData->SelfTest_Comp == YES ||
+            strlen((char *)pSysInfo->FanModuleFwRev) != 0 ||
+            pSysInfo->FanModuleFwRev[0] != '\0') {
+        ShmFanModuleData->SelfTest_Comp = YES;
+
+        if (GetClockTimeoutValue(gFanBoardRunTimer) / 1000 >= 1000) {
+            //GetPsuTempForFanSpeed();
+            //GetFanSpeedByFunction();
+            GetFanSpeed();
+            pSysInfo->SystemFanRotaSpeed = _setFanSpeed;
+            GetClockTime(&gFanBoardRunTimer, NULL);
+            /*
+            ShmFanModuleData->SetFan1Speed = ShmFanModuleData->TestFanSpeed;
+            ShmFanModuleData->SetFan2Speed = ShmFanModuleData->TestFanSpeed;
+            ShmFanModuleData->SetFan3Speed = ShmFanModuleData->TestFanSpeed;
+            ShmFanModuleData->SetFan4Speed = ShmFanModuleData->TestFanSpeed;
+            */
+            //log_info("set fan = %d ", ShmFanModuleData->SetFan1Speed);
+            SetFanModuleSpeed();
+        }
+    }
+}
+
+static void GetFwAndHwVersion_Led(void)
+{
+    Ver ver = {0};
+
+    if (Query_FW_Ver(Uart5Fd, ADDR_LED, &ver) == PASS) {
+        // LedModuleData
+        strcpy((char *) ShmLedModuleData->version, ver.Version_FW);
+        // SystemInfo
+        strcpy((char *) pSysInfo->LedModuleFwRev, ver.Version_FW);
+        log_info("GetFwAndHwVersion_Led s1 = %s ", ver.Version_FW);
+        ShmLedModuleData->SelfTest_Comp = YES;
+    } else {
+        //log_info("GetFwAndHwVersion_Led fail ");
+    }
+
+//  if (Query_HW_Ver(Uart5Fd, ADDR_LED, &ver) == PASS)
+//  {
+//      // SystemInfo
+//      strcpy((char *) pSysInfo->RelayModuleHwRev, ver.Version_FW);
+//      //log_info("GetFwAndHwVersion_Relay s2 = %s ", ver.Version_HW);
+//  }
+}
+
+static bool IsNoneMatchLedColor(void)
+{
+    bool result = false;
+
+    if (cur_led_color.Connect_1_Red != led_color.Connect_1_Red ||
+            cur_led_color.Connect_1_Green != led_color.Connect_1_Green ||
+            cur_led_color.Connect_1_Blue != led_color.Connect_1_Blue ||
+            cur_led_color.Connect_2_Red != led_color.Connect_2_Red ||
+            cur_led_color.Connect_2_Green != led_color.Connect_2_Green ||
+            cur_led_color.Connect_2_Blue != led_color.Connect_2_Blue) {
+        result = true;
+    }
+
+    return result;
+}
+
+//static void SetLedColor(struct ChargingInfoData *chargingData_1, struct ChargingInfoData *chargingData_2)
+static void SetLedColor(void)
+{
+    static uint8_t _checkLedChanged = 3;
+    struct ChargingInfoData *chargingData_1 = NULL;
+    struct ChargingInfoData *chargingData_2 = NULL;
+
+    if (pSysConfig->TotalConnectorCount == 1) {
+        chargingData_1 = (struct ChargingInfoData *)GetDcChargingInfoData(0);
+        chargingData_2 = (struct ChargingInfoData *)GetDcChargingInfoData(0);
+    } else if (pSysConfig->TotalConnectorCount == 2) {
+        chargingData_1 = (struct ChargingInfoData *)GetDcChargingInfoData(0);
+        chargingData_2 = (struct ChargingInfoData *)GetDcChargingInfoData(1);
+    }
+    uint8_t _colorBuf = COLOR_MAX_LV * LED_INTENSITY_BRIGHTEST;
+
+    if (pSysConfig->LedInfo.Intensity == _LED_INTENSITY_DARKEST) {
+        _colorBuf = COLOR_MAX_LV * LED_INTENSITY_DARKEST;
+    } else if (pSysConfig->LedInfo.Intensity == _LED_INTENSITY_MEDIUM) {
+        _colorBuf = COLOR_MAX_LV * LED_INTENSITY_MEDIUM;
+    } else if (pSysConfig->LedInfo.Intensity == LED_INTENSITY_BRIGHTEST) {
+        _colorBuf = COLOR_MAX_LV * LED_INTENSITY_BRIGHTEST;
+    }
+
+    //printf("chargingData_1->SystemStatus=%d\n",chargingData_1->SystemStatus);
+    //printf("chargingData_2->SystemStatus=%d\n",chargingData_2->SystemStatus);
+    //printf("pSysWarning->Level=%d\n",pSysWarning->Level);
+    if (pSysWarning->Level == 2) {
+        led_color.Connect_1_Green = COLOR_MIN_LV;
+        led_color.Connect_1_Blue = COLOR_MIN_LV;
+        led_color.Connect_1_Red = _colorBuf;
+        led_color.Connect_2_Green = COLOR_MIN_LV;
+        led_color.Connect_2_Blue = COLOR_MIN_LV;
+        led_color.Connect_2_Red = _colorBuf;
+    } else {
+        if (pSysInfo->IsAlternatvieConf) {
+
+        } else {
+            // 左邊燈條
+            if (chargingData_1->SystemStatus == S_BOOTING ||
+                    chargingData_1->SystemStatus == S_IDLE ) {
+                if (chargingData_1->IsAvailable == NO) { //For Audi
+                    led_color.Connect_1_Green = COLOR_MIN_LV;
+                    led_color.Connect_1_Blue = COLOR_MIN_LV;
+                    led_color.Connect_1_Red = _colorBuf;
+                } else {
+#if defined DD360Audi
+                    led_color.Connect_1_Green = _colorBuf;
+                    led_color.Connect_1_Blue = _colorBuf;
+                    led_color.Connect_1_Red = _colorBuf;
+#else
+                    led_color.Connect_1_Green = _colorBuf;
+                    led_color.Connect_1_Blue = COLOR_MIN_LV;
+                    led_color.Connect_1_Red = COLOR_MIN_LV;
+#endif
+                }
+            } else if ((chargingData_1->SystemStatus >= S_AUTHORIZING &&
+                        chargingData_1->SystemStatus <= S_COMPLETE) ||
+                       (chargingData_1->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
+                        chargingData_1->SystemStatus <= S_CCS_PRECHARGE_ST1)) {
+                led_color.Connect_1_Green = COLOR_MIN_LV;
+                led_color.Connect_1_Blue = _colorBuf;
+                led_color.Connect_1_Red = COLOR_MIN_LV;
+            } else if ( chargingData_1->SystemStatus == S_UPDATE ||
+                    chargingData_1->SystemStatus == S_MAINTAIN ) {
+                led_color.Connect_1_Green = COLOR_MIN_LV;
+                led_color.Connect_1_Blue = COLOR_MIN_LV;
+                led_color.Connect_1_Red = _colorBuf;
+            } else if (chargingData_1->SystemStatus == S_RESERVATION) {
+                if (ReservationLed) {
+                    led_color.Connect_1_Green = COLOR_MIN_LV;
+                } else {
+                    led_color.Connect_1_Green = _colorBuf;
+                }
+                led_color.Connect_1_Blue = COLOR_MIN_LV;
+                led_color.Connect_1_Red = COLOR_MIN_LV;
+            }
+            // 右邊燈條
+            // --------------------------------------------------------------------------
+            if (chargingData_2->SystemStatus == S_BOOTING ||
+                    chargingData_2->SystemStatus == S_IDLE ) {
+                if (chargingData_2->IsAvailable == NO) {
+                    led_color.Connect_2_Green = COLOR_MIN_LV;
+                    led_color.Connect_2_Blue = COLOR_MIN_LV;
+                    led_color.Connect_2_Red = _colorBuf;
+                } else {
+#if defined DD360Audi
+                    led_color.Connect_2_Green = _colorBuf;
+                    led_color.Connect_2_Blue = _colorBuf;
+                    led_color.Connect_2_Red = _colorBuf;
+#else
+                    led_color.Connect_2_Green = _colorBuf;
+                    led_color.Connect_2_Blue = COLOR_MIN_LV;
+                    led_color.Connect_2_Red = COLOR_MIN_LV;
+#endif
+                }
+            } else if ((chargingData_2->SystemStatus >= S_AUTHORIZING &&
+                        chargingData_2->SystemStatus <= S_COMPLETE) ||
+                       (chargingData_2->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
+                        chargingData_2->SystemStatus <= S_CCS_PRECHARGE_ST1)) {
+                led_color.Connect_2_Green = COLOR_MIN_LV;
+                led_color.Connect_2_Blue = _colorBuf;
+                led_color.Connect_2_Red = COLOR_MIN_LV;
+            }else if ( chargingData_2->SystemStatus == S_UPDATE ||
+                    chargingData_2->SystemStatus == S_MAINTAIN) {
+                led_color.Connect_2_Green = COLOR_MIN_LV;
+                led_color.Connect_2_Blue = COLOR_MIN_LV;
+                led_color.Connect_2_Red = _colorBuf;
+            } else if (chargingData_2->SystemStatus == S_RESERVATION) {
+                if (ReservationLed) {
+                    led_color.Connect_2_Green = COLOR_MIN_LV;
+                } else {
+                    led_color.Connect_2_Green = _colorBuf;
+                }
+                led_color.Connect_2_Blue = COLOR_MIN_LV;
+                led_color.Connect_2_Red = COLOR_MIN_LV;
+            }
+
+        }
+    }
+    if (_checkLedChanged > 0) {
+        if (Config_Led_Color(Uart5Fd, ADDR_LED, &led_color) == PASS) {
+            _checkLedChanged--;
+
+            cur_led_color.Connect_1_Red     = led_color.Connect_1_Red;
+            cur_led_color.Connect_1_Green   = led_color.Connect_1_Green;
+            cur_led_color.Connect_1_Blue    = led_color.Connect_1_Blue;
+            cur_led_color.Connect_2_Red     = led_color.Connect_2_Red;
+            cur_led_color.Connect_2_Green   = led_color.Connect_2_Green;
+            cur_led_color.Connect_2_Blue    = led_color.Connect_2_Blue;
+        }
+    } else if (IsNoneMatchLedColor()) {
+        _checkLedChanged = 3;
+    }
+}
+
+static void LEDBoardSelfTest(void)
+{
+    // 自檢階段處理,自檢階段如果讀不到版號則代表該系統沒有掛燈板
+    if (ShmLedModuleData->SelfTest_Comp == YES) {
+        return;
+    }
+
+#if defined DD360Tcci ||defined DD360Audi || defined DD360UCar
+    GetFwAndHwVersion_Led();
+    sleep(1);
+    GetClockTime(&_led_priority_time, NULL);
+
+    return;
+#endif //defined DD360Tcci || defined DD360Audi
+
+    // 自檢階段
+    if (pSysInfo->SelfTestSeq <= _STEST_PSU_CAP) {
+        GetFwAndHwVersion_Led();
+        sleep(1);
+        GetClockTime(&_led_priority_time, NULL);
+    } else {
+        // 自檢階段沒有問到版號
+        if (pAlarmCode->AlarmEvents.bits.LedboardStestFail == NO) {
+            pAlarmCode->AlarmEvents.bits.LedboardStestFail = YES;
+        }
+    }
+}
+
+static void LEDBoardProcess(void)
+{
+    //struct ChargingInfoData *pDcChargingInfo0 = NULL;
+    //struct ChargingInfoData *pDcChargingInfo1 = NULL;
+
+    if (ShmLedModuleData->SelfTest_Comp == NO) {
+        return;
+    }
+    pSysConfig->LedInfo.Intensity = LED_INTENSITY_BRIGHTEST;
+    if (GetClockTimeoutValue(_led_priority_time) / 1000 >= 500) {
+        if (time((time_t*)NULL) - ReservationFlashTimer >= 3) {
+            ReservationFlashTimer = time((time_t*)NULL);
+            if (ReservationLed)
+                ReservationLed = 0;
+            else
+                ReservationLed = 1;
+        }
+        SetLedColor();
+        GetClockTime(&_led_priority_time, NULL);
+    }
+}
+
+void RelayBoardTask(int uartFD)
+{
+    bool isRelayBypass = false;
+    pid_t pid = fork();
+
+    if (pid == 0) {
+        bool isCharging = false;
+        bool isStopChargingCount = false;
+        uint8_t i = 0;
+        int isContinue = 1;
+        struct ChargingInfoData *pDcChargingInfo = NULL;
+
+        //share memory mapping
+        pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
+        pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
+        pAlarmCode = (struct AlarmCodeData *)GetShmAlarmCodeData();
+        ShmRelayModuleData = (struct RelayModuleData *)GetShmRelayModuleData();
+        ShmPsuData = (struct PsuData *)GetShmPsuData();
+        ShmDcCommonData = (DcCommonInfo *)GetShmDcCommonData();
+        ShmPrimaryMcuData = (struct PrimaryMcuData *)GetShmPrimaryMcuData();
+        pSysWarning = (struct WARNING_CODE_INFO *)GetShmSysWarningInfo();
+        ShmFanModuleData = (struct FanModuleData *)GetShmFanModuleData();
+        ShmLedModuleData = (struct LedModuleData *)GetShmLedModuleData();
+
+        Uart5Fd = uartFD;
+
+        for(int i = 0; i < pSysConfig->TotalConnectorCount; i++)
+        {
+            pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(i);
+            if(pDcChargingInfo->PantographFlag == YES)
+            {
+                isRelayBypass = true;
+            }
+        }
+
+        //relay init
+        if(isRelayBypass == false)
+        {
+            outputRelayInit(uartFD);
+        }
+
+        while (isContinue) {
+
+            if(IsRelayProcessNeedPause() == true)
+            {
+                sleep(1);
+                continue;
+            }
+
+            // 程序開始之前~ 必須先確定 FW 版本與硬體版本,確認後!!~ 該模組才算是真正的 Initial Comp.
+            if (ShmRelayModuleData->SelfTest_Comp == NO && isRelayBypass == false) {
+                GetFwAndHwVersion_Relay();
+                SetModelName_Relay(); //DS60-120 add
+                SetRtcData_Relay();
+                sleep(1);
+            }
+
+#if !defined NO_FAN_BOARD && !defined DD360ComBox
+            fanBoardSelfTest();
+#endif //NO_FAN_BOARD
+
+#if !defined DD360ComBox
+            LEDBoardSelfTest();
+#endif //defined DD360ComBox
+
+            if (ShmRelayModuleData->SelfTest_Comp == YES && isRelayBypass == false)
+            {
+                // ==============優先權最高 10 ms ==============
+                // 輸出電壓
+                GetPersentOutputVol();
+
+    #if !defined DD360Tcci && !defined DD360Audi && !defined DD360ComBox && !defined DD360UCar
+                // 三相輸入電壓
+                GetPresentInputVol();
+    #endif //!defined DD360Tcci && !defined DD360Audi
+
+                // 讀取當前 AC relay 狀態
+                regRelay.relay_event.bits.AC_Contactor = pSysInfo->AcContactorStatus;
+                GetRelayOutputStatus();
+
+                // Cable check (Get)
+                GetGfdAdc();
+
+                for (i = 0; i < pSysConfig->TotalConnectorCount; i++) {
+                    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(i);
+
+                    // Cable check (Set)
+                    CableCheckDetected(i);
+
+                    // check k1 k2 relay 狀態
+                    CheckK1K2RelayOutput(i);
+
+                    // 依據當前各槍的狀態選擇 搭上/放開 Relay
+                    SetK1K2RelayStatus(i);
+
+#if !defined DD360Tcci && !defined DD360Audi && !defined DD360ComBox && !defined DD360UCar
+                    if (pSysConfig->PhaseLossPolicy == YES) {
+                        CheckPhaseLossStatus(i);
+                    }
+
+                    CheckAcInputOvpStatus(i);
+#endif //!defined DD360Tcci && !defined DD360Audi
+
+                    if (pDcChargingInfo->SystemStatus == S_IDLE ||
+                            pDcChargingInfo->SystemStatus == S_RESERVATION ||
+                            pDcChargingInfo->SystemStatus == S_MAINTAIN) {
+                        //pDcChargingInfo->RelayWeldingCheck = NO;
+                        //_isRelayWelding[i] = NO;
+                        _isOvpChkTimeFlag[i] = NO;
+                        _show_GFD_Warming[i] = TRUE;
+                        //ResetDetAlarmStatus(i); //DS60-120 add
+                    }
+
+                    if (pDcChargingInfo->SystemStatus == S_BOOTING ||
+                            (pDcChargingInfo->SystemStatus >= S_REASSIGN_CHECK &&
+                             pDcChargingInfo->SystemStatus <= S_COMPLETE) ||
+                            (pDcChargingInfo->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
+                             pDcChargingInfo->SystemStatus <= S_CCS_PRECHARGE_ST1) ||
+                            ShmDcCommonData->pGunInfo[i].WaitForPlugit == YES ||
+                            (pSysInfo->PageIndex >=  _PAGE_AUTHORIZE &&
+                             pSysInfo->PageIndex <= _PAGE_PLUGIN)
+                       ) {
+                        pDcChargingInfo->IsReadyToCharging = YES;
+                        isCharging = true;
+
+                        // 限定只有在槍類別為 GBT 的時候才做 relay welding 的判斷
+                        //if (pDcChargingInfo->Type == _Type_GB) {
+                        //    if (pDcChargingInfo->SystemStatus >= S_PREPARING_FOR_EVSE &&
+                        //            pDcChargingInfo->RelayWeldingCheck == NO) {
+                        //        CheckRelayWeldingStatus(i);
+                        //    }
+                        //} else {
+                        //pDcChargingInfo->RelayWeldingCheck = YES;
+                        //}
+
+                        if (pDcChargingInfo->SystemStatus == S_CHARGING) {
+                            CheckOutputPowerOverCarReq(i);
+                            //CheckOutputVolNoneMatchFire(i);
+                        }
+                        /*else {
+                            _isOutputNoneMatch[i] = NO;
+                        }*/
+                    } else {
+                        pDcChargingInfo->IsReadyToCharging = NO;
+                    }
+                }
+
+                    // 橋接 relay
+                    SetParalleRelayStatus();
+
+                    // 搭上 AC Contactor
+                    //if (isCharging) {
+                    //    outputRelay.relay_event.bits.AC_Contactor = YES;
+                    //} else {
+                    //    outputRelay.relay_event.bits.AC_Contactor = NO;
+                    //}
+
+                    if (isCharging ||
+                            (ShmPsuData->Work_Step >= _TEST_MODE &&
+                             ShmPsuData->Work_Step <= _TEST_MODE)) {
+                        isStopChargingCount = false;
+                        outputRelay.relay_event.bits.AC_Contactor = YES;
+                    } else {
+                        if (!isStopChargingCount) {
+                            GetClockTime(&_close_ac_contactor, NULL);
+                            isStopChargingCount = true;
+                        } else {
+                            if ((outputRelay.relay_event.bits.AC_Contactor == YES &&
+                                    GetClockTimeoutValue(_close_ac_contactor) / 1000 >= (TEN_MINUTES * 1000))) {
+                                outputRelay.relay_event.bits.AC_Contactor = NO;
+                            }
+                        }
+                    }
+
+                    if (ShmPrimaryMcuData->InputDet.bits.EmergencyButton == ABNORMAL) {
+                        outputRelay.relay_event.bits.AC_Contactor = NO;
+                    }
+
+                    if (pAlarmCode->AlarmEvents.bits.PsuFailureAlarm == ABNORMAL) {
+                        RunForceStopProcess();
+                        outputRelay.relay_event.bits.AC_Contactor = NO;
+                    }
+
+                    if (ShmPsuData->Work_Step >= _TEST_MODE && ShmPsuData->Work_Step <= _TEST_MODE) {
+                        outputRelay.relay_event.bits.Gun1_N = outputRelay.relay_event.bits.Gun1_P = YES;
+                    }
+
+                    // 搭上/鬆開 Relay
+                    if (IsNoneMatchRelayStatus()) {
+                        if (Config_Relay_Output(Uart5Fd, ADDR_RELAY, &outputRelay)) {
+                            //regRelay.relay_event.bits.AC_Contactor = pSysInfo->AcContactorStatus;
+
+                            //regRelay.relay_event.bits.CCS_Precharge = outputRelay.relay_event.bits.CCS_Precharge;
+                            //regRelay.relay_event.bits.Gun1_P = outputRelay.relay_event.bits.Gun1_P;
+                            //regRelay.relay_event.bits.Gun1_N = outputRelay.relay_event.bits.Gun1_N;
+                            //regRelay.relay_event.bits.Gun2_P = outputRelay.relay_event.bits.Gun2_P;
+                            //regRelay.relay_event.bits.Gun2_N = outputRelay.relay_event.bits.Gun2_N;
+                            //regRelay.relay_event.bits.Gun1_Parallel_P = outputRelay.relay_event.bits.Gun1_Parallel_P;
+                            //regRelay.relay_event.bits.Gun1_Parallel_N = outputRelay.relay_event.bits.Gun1_Parallel_N;
+
+                            //MatchRelayStatus();
+
+                            //log_info("Match Relay, AC = %x, g1_p = %x, g1_n = %x, g2_p = %x, g2_n = %x, pre = %x, bri_p = %x, bri_n = %x ",
+                            //         regRelay.relay_event.bits.AC_Contactor,
+                            //         regRelay.relay_event.bits.Gun1_P,
+                        //         regRelay.relay_event.bits.Gun1_N,
+                        //         regRelay.relay_event.bits.Gun2_P,
+                        //         regRelay.relay_event.bits.Gun2_N,
+                        //         regRelay.relay_event.bits.CCS_Precharge,
+                        //         regRelay.relay_event.bits.Gun1_Parallel_P,
+                        //         regRelay.relay_event.bits.Gun1_Parallel_N);
+
+                    }
+                }
+            }
+            else if(isRelayBypass == true)
+            {
+                for(i = 0; i < pSysConfig->TotalConnectorCount; i++)
+                {
+                    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(i);
+
+                    if (pDcChargingInfo->SystemStatus == S_IDLE ||
+                            pDcChargingInfo->SystemStatus == S_RESERVATION ||
+                            pDcChargingInfo->SystemStatus == S_MAINTAIN)
+                    {
+                        _isOvpChkTimeFlag[i] = NO;
+                    }
+                    if (pDcChargingInfo->SystemStatus == S_CHARGING)
+                    {
+                        CheckOutputPowerOverCarReq(i);
+                    }
+                }
+            }
+
+#if !defined NO_FAN_BOARD && !defined DD360ComBox
+            fanBoardPorcess();
+#endif //NO_FAN_BOARD
+
+#if !defined DD360ComBox
+            LEDBoardProcess();
+#endif //defined DD360ComBox
+
+            usleep(10000);
+        }
+    }
+}

+ 1188 - 1188
EVSE/Projects/DD360Tcci/Apps/ModuleInternalComm/internalComm.c

@@ -1,1188 +1,1188 @@
-/*
- * internalComm.c
- *
- *  Created on: 2019年5月7日
- *      Author: foluswen
- */
-#include <stdio.h>      /*標準輸入輸出定義*/
-#include <stdlib.h>     /*標準函數庫定義*/
-#include <stdint.h>
-#include <string.h>
-
-#include <unistd.h>
-#include <termios.h>
-
-#include "internalComm.h"
-#include "../Config.h"
-
-//------------------------------------------------------------------------------
-int tranceiveRelDelayTime(int fd, uint8_t *cmd, uint8_t cmd_len, uint8_t *rx, uint16_t _delay)
-{
-    int len;
-    //sleep(2); //required to make flush work, for some reason
-    tcflush(fd, TCIOFLUSH);
-
-    if (write(fd, cmd, cmd_len) >= cmd_len) {
-        usleep(_delay * 1000);
-        len = read(fd, rx, 512);
-    } else {
-#ifdef SystemLogMessage
-        DEBUG_ERROR("Serial command %s response fail.\n", cmd);
-#endif
-    }
-
-    return len;
-}
-
-int tranceive(int fd, uint8_t *cmd, uint8_t cmd_len, uint8_t *rx)
-{
-    int len;
-    //sleep(2); //required to make flush work, for some reason
-    tcflush(fd, TCIOFLUSH);
-
-    if (write(fd, cmd, cmd_len) >= cmd_len) {
-        usleep(15000);
-        len = read(fd, rx, 512);
-    } else {
-#ifdef SystemLogMessage
-        DEBUG_ERROR("Serial command %s response fail.\n", cmd);
-#endif
-    }
-
-    return len;
-}
-
-//------------------------------------------------------------------------------
-//===== Query =====
-//------------------------------------------------------------------------------
-int Query_FW_Ver(uint8_t fd, uint8_t targetAddr, Ver *Ret_Buf)
-{
-    int result = FAIL;
-    uint8_t tx[7] = {0xaa, 0x00, targetAddr, CMD_QUERY_FW_VER, 0x00, 0x00, 0x00};
-    uint8_t rx[512];
-    uint8_t chksum = 0x00;
-    uint8_t len = tranceive(fd, tx, sizeof(tx), rx);
-
-//      for (int i = 0; i < 7; i++)
-//          printf("tx = %x \n", tx[i]);
-//      for (int i = 0; i < len; i++)
-//          printf("rx = %x \n", rx[i]);
-
-    if (len > 6) {
-        if (len < 6 + (rx[4] | rx[5] << 8)) {
-            return result;
-        }
-
-        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
-            chksum ^= rx[6 + idx];
-        }
-
-        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
-                (rx[2] == tx[1]) &&
-                (rx[1] == tx[2]) &&
-                (rx[3] == tx[3])) {
-            memcpy(Ret_Buf->Version_FW, (char *)rx + 6, (rx[4] | rx[5] << 8));
-            *(Ret_Buf->Version_FW + 8) = 0x00;
-            result = PASS;
-        }
-    }
-
-    return result;
-}
-
-int Query_HW_Ver(uint8_t fd, uint8_t targetAddr, Ver *Ret_Buf)
-{
-    int result = FAIL;
-    uint8_t tx[7] = {0xaa, 0x00, targetAddr, CMD_QUERY_HW_VER, 0x00, 0x00, 0x00};
-    uint8_t rx[512];
-    uint8_t chksum = 0x00;
-    uint8_t len = tranceive(fd, tx, sizeof(tx), rx);
-
-    if (len > 6) {
-        if (len < 6 + (rx[4] | rx[5] << 8)) {
-            return result;
-        }
-
-        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
-            chksum ^= rx[6 + idx];
-        }
-
-        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
-                (rx[2] == tx[1]) &&
-                (rx[1] == tx[2]) &&
-                (rx[3] == tx[3])) {
-            memcpy(Ret_Buf->Version_HW, (char *)rx + 6, (rx[4] | rx[5] << 8));
-            *(Ret_Buf->Version_HW + 8) = 0x00;
-            result = PASS;
-        }
-    }
-
-    return result;
-}
-
-int Query_Present_InputVoltage(uint8_t fd, uint8_t targetAddr, PresentInputVoltage *Ret_Buf)
-{
-    int result = FAIL;
-    uint8_t tx[7] = {0xaa, 0x00, targetAddr, CMD_QUERY_PRESENT_IN_VOL, 0x00, 0x00, 0x00};
-    uint8_t rx[512];
-    uint8_t chksum = 0x00;
-    uint8_t len = tranceive(fd, tx, sizeof(tx), rx);
-
-    if (len > 13) {
-        if (len < 6 + (rx[4] | rx[5] << 8)) {
-            return result;
-        }
-
-        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
-            chksum ^= rx[6 + idx];
-        }
-        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
-                (rx[2] == tx[1]) &&
-                (rx[1] == tx[2]) &&
-                (rx[3] == tx[3]) &&
-                chksum != 0) {
-            Ret_Buf->inputType = rx[6];
-            Ret_Buf->L1N_L12 = (rx[7] | (rx[8] << 8)) / 10.0;
-            Ret_Buf->L2N_L23 = (rx[9] | (rx[10] << 8)) / 10.0;
-            Ret_Buf->L3N_L31 = (rx[11] | (rx[12] << 8)) / 10.0;
-
-            if (Ret_Buf->L1N_L12 >= 320 ||
-                    Ret_Buf->L2N_L23 >= 320 ||
-                    Ret_Buf->L3N_L31 >= 320) {
-                result = FAIL;
-            } else {
-                result = PASS;
-            }
-        }
-    }
-
-    return result;
-}
-
-int Query_Present_OutputVoltage(uint8_t fd, uint8_t targetAddr, PresentOutputVoltage *Ret_Buf)
-{
-    int result = FAIL;
-    uint8_t tx[7] = {0xaa, 0x00, targetAddr, CMD_QUERY_PRESENT_OUT_VOL, 0x00, 0x00, 0x00};
-    uint8_t rx[512];
-    uint8_t chksum = 0x00;
-    uint8_t len = tranceive(fd, tx, sizeof(tx), rx);
-
-    if (len > 6) {
-        if (len < 6 + (rx[4] | rx[5] << 8)) {
-            return result;
-        }
-
-        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
-            chksum ^= rx[6 + idx];
-        }
-
-        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
-                (rx[2] == tx[1]) &&
-                (rx[1] == tx[2]) &&
-                (rx[3] == tx[3])) {
-
-            Ret_Buf->behindFuse_Voltage_C1 = (rx[6] | (rx[7] << 8));
-            Ret_Buf->behindRelay_Voltage_C1 = (rx[8] | (rx[9] << 8));
-            if ((rx[4] | rx[5] << 8) > 4) {
-                Ret_Buf->behindFuse_Voltage_C2 = (rx[10] | (rx[11] << 8));
-                Ret_Buf->behindRelay_Voltage_C2 = (rx[12] | (rx[13] << 8));
-            }
-            result = PASS;
-        }
-    }
-
-    return result;
-}
-
-int Query_Fan_Speed(uint8_t fd, uint8_t targetAddr, FanSpeed *Ret_Buf)
-{
-    int result = FAIL;
-    uint8_t tx[7] = {0xaa, 0x00, targetAddr, CMD_QUERY_FAN_SPEED, 0x00, 0x00, 0x00};
-    uint8_t rx[512];
-    uint8_t chksum = 0x00;
-    uint8_t len = tranceive(fd, tx, sizeof(tx), rx);
-
-    if (len > 6) {
-        if (len < 6 + (rx[4] | rx[5] << 8)) {
-            return result;
-        }
-
-        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
-            chksum ^= rx[6 + idx];
-        }
-
-        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
-                (rx[2] == tx[1]) &&
-                (rx[1] == tx[2]) &&
-                (rx[3] == tx[3])) {
-            for (int idx = 0; idx < 4; idx++) {
-                Ret_Buf->speed[idx] = (rx[6 + (2 * idx)] | (rx[6 + (2 * idx) + 1] << 8));
-            }
-
-            result = PASS;
-        }
-    }
-
-    return result;
-}
-
-int Query_Temperature(uint8_t fd, uint8_t targetAddr, Temperature *Ret_Buf)
-{
-    int result = FAIL;
-    uint8_t tx[7] = {0xaa, 0x00, targetAddr, CMD_QUERY_TEMPERATURE, 0x00, 0x00, 0x00};
-    uint8_t rx[512];
-    uint8_t chksum = 0x00;
-    uint8_t len = tranceive(fd, tx, sizeof(tx), rx);
-
-    if (len > 6) {
-        if (len < 6 + (rx[4] | rx[5] << 8)) {
-            return result;
-        }
-
-        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
-            chksum ^= rx[6 + idx];
-        }
-
-        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
-                (rx[2] == tx[1]) &&
-                (rx[1] == tx[2]) &&
-                (rx[3] == tx[3])) {
-            for (int idx = 0; idx < 4; idx++) {
-                Ret_Buf->temperature[idx] = rx[6 + idx] - 60;
-            }
-
-            result = PASS;
-        }
-    }
-
-
-    return result;
-}
-
-int Query_Aux_PowerVoltage(uint8_t fd, uint8_t targetAddr, AuxPower *Ret_Buf)
-{
-    int result = FAIL;
-    uint8_t tx[7] = {0xaa, 0x00, targetAddr, CMD_QUERY_AUX_POWER_VOL, 0x00, 0x00, 0x00};
-    uint8_t rx[512];
-    uint8_t chksum = 0x00;
-    uint8_t len = tranceive(fd, tx, sizeof(tx), rx);
-
-    if (len > 6) {
-        if (len < 6 + (rx[4] | rx[5] << 8)) {
-            return result;
-        }
-
-        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
-            chksum ^= rx[6 + idx];
-        }
-
-        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
-                (rx[2] == tx[1]) &&
-                (rx[1] == tx[2]) &&
-                (rx[3] == tx[3])) {
-            for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
-                Ret_Buf->voltage[idx] = rx[6 + idx];
-            }
-
-            result = PASS;
-        }
-    }
-
-    return result;
-}
-
-int Query_Relay_Output(uint8_t fd, uint8_t targetAddr, Relay *Ret_Buf)
-{
-    int result = FAIL;
-    uint8_t tx[7] = {0xaa, 0x00, targetAddr, CMD_QUERY_RELAY_OUTPUT, 0x00, 0x00, 0x00};
-    uint8_t rx[512];
-    uint8_t chksum = 0x00;
-    uint8_t len = tranceive(fd, tx, sizeof(tx), rx);
-
-//  for (int i = 0; i < 7; i++)
-//      printf("tx = %x \n", tx[i]);
-//  for (int i = 0; i < len; i++)
-//      printf("rx = %x \n", rx[i]);
-
-    if (len > 6) {
-        if (len < 6 + (rx[4] | rx[5] << 8)) {
-            return result;
-        }
-
-        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
-            chksum ^= rx[6 + idx];
-        }
-
-        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
-                (rx[2] == tx[1]) &&
-                (rx[1] == tx[2]) &&
-                (rx[3] == tx[3])) {
-            Ret_Buf->relay_event.bits.AC_Contactor = (rx[6] >> 0) & 0x01;
-            Ret_Buf->relay_event.bits.CCS_Precharge = (rx[6] >> 1) & 0x01;
-
-            Ret_Buf->relay_event.bits.Gun1_N = (rx[7] >> 0) & 0x01;
-            Ret_Buf->relay_event.bits.Gun1_P = (rx[7] >> 1) & 0x01;
-            Ret_Buf->relay_event.bits.Gun1_Parallel_N = (rx[7] >> 2) & 0x01;
-            Ret_Buf->relay_event.bits.Gun1_Parallel_P = (rx[7] >> 3) & 0x01;
-
-            Ret_Buf->relay_event.bits.Gun2_N = (rx[8] >> 0) & 0x01;
-            Ret_Buf->relay_event.bits.Gun2_P = (rx[8] >> 1) & 0x01;
-            result = PASS;
-        }
-    }
-
-    return result;
-}
-
-int Query_Gfd_Adc(uint8_t fd, uint8_t targetAddr, Gfd *Ret_Buf)
-{
-    int result = FAIL;
-    uint8_t tx[7] = {0xaa, 0x00, targetAddr, CMD_QUERY_GFD_ADC, 0x00, 0x00, 0x00};
-    uint8_t rx[512];
-    uint8_t chksum = 0x00;
-    uint8_t len = tranceive(fd, tx, sizeof(tx), rx);
-
-//  for(int i = 0; i < 7; i++)
-//      printf ("tx = %d \n", tx[i]);
-    if (len > 6) {
-        if (len < 6 + (rx[4] | rx[5] << 8)) {
-            //printf("Query_Gfd_Adc fail \n");
-            return result;
-        }
-
-//      for(int i = 0; i < len; i++)
-//          printf ("rx = %d \n", rx[i]);
-
-        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
-            chksum ^= rx[6 + idx];
-        }
-
-        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
-                (rx[2] == tx[1]) &&
-                (rx[1] == tx[2]) &&
-                (rx[3] == tx[3])) {
-            Ret_Buf->Resister_conn1 = (rx[6] | (rx[7] << 8));
-            Ret_Buf->voltage_conn1 = (rx[8] | (rx[9] << 8));
-            Ret_Buf->result_conn1 = rx[10];
-            Ret_Buf->rb_step_1 = rx[11];
-
-            Ret_Buf->Resister_conn2 = (rx[12] | (rx[13] << 8));
-            Ret_Buf->voltage_conn2 = (rx[14] | (rx[15] << 8));
-            Ret_Buf->result_conn2 = rx[16];
-            Ret_Buf->rb_step_2 = rx[17];
-
-            result = PASS;
-        }
-    }
-
-    return result;
-}
-
-int Query_Gpio_Input(uint8_t fd, uint8_t targetAddr, Gpio_in *Ret_Buf)
-{
-    int result = FAIL;
-    uint8_t tx[7] = {0xaa, 0x00, targetAddr, CMD_QUERY_GPIO_IN, 0x00, 0x00, 0x00};
-    uint8_t rx[512];
-    uint8_t chksum = 0x00;
-    uint8_t len = tranceive(fd, tx, sizeof(tx), rx);
-
-    if (len > 6) {
-        if (len < 6 + (rx[4] | rx[5] << 8)) {
-            return result;
-        }
-
-        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
-            chksum ^= rx[6 + idx];
-        }
-
-        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
-                (rx[2] == tx[1]) &&
-                (rx[1] == tx[2]) &&
-                (rx[3] == tx[3])) {
-            Ret_Buf->AC_Connector       = (rx[6] >> 0) & 0x01;
-            Ret_Buf->AC_MainBreaker     = (rx[6] >> 1) & 0x01;
-            Ret_Buf->SPD                = (rx[6] >> 2) & 0x01;
-            Ret_Buf->Door_Open          = ((rx[6] >> 3) & 0x01);
-            Ret_Buf->GFD[0]             = (rx[6] >> 4) & 0x01;
-            Ret_Buf->GFD[1]             = (rx[6] >> 5) & 0x01;
-            Ret_Buf->AC_Drop            = (rx[6] >> 6) & 0x01;
-
-            Ret_Buf->Emergency_IO       = (rx[7] >> 0) & 0x01;
-
-            Ret_Buf->Button_Emergency_Press = (rx[8] >> 0) & 0x01;
-            Ret_Buf->Button_On_Press    = (rx[8] >> 1) & 0x01;
-            Ret_Buf->Button_Off_Press   = (rx[8] >> 2) & 0x01;
-            Ret_Buf->Key_1_Press        = (rx[8] >> 3) & 0x01;
-            Ret_Buf->Key_2_Press        = (rx[8] >> 4) & 0x01;
-            Ret_Buf->Key_3_Press        = (rx[8] >> 5) & 0x01;
-            Ret_Buf->Key_4_Press        = (rx[8] >> 6) & 0x01;
-
-            result = PASS;
-        }
-    }
-
-    return result;
-}
-
-int Query_Model_Name(uint8_t fd, uint8_t targetAddr, uint8_t *modelname)
-{
-    int result = FAIL;
-    uint8_t tx[7] = {0xaa, 0x00, targetAddr, CMD_QUERY_MODEL_NAME, 0x00, 0x00, 0x00};
-    uint8_t rx[512];
-    uint8_t chksum = 0x00;
-    uint8_t len = tranceive(fd, tx, sizeof(tx), rx);
-
-    if (len > 6) {
-        if (len < 6 + (rx[4] | rx[5] << 8)) {
-            return result;
-        }
-
-        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
-            chksum ^= rx[6 + idx];
-        }
-
-        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
-                (rx[2] == tx[1]) &&
-                (rx[1] == tx[2]) &&
-                (rx[3] == tx[3])) {
-            strncpy((char *)modelname, (char *)(rx + 6), (rx[4] | rx[5] << 8));
-            result = PASS;
-        }
-    }
-
-    return result;
-}
-
-int Query_Charging_Current(uint8_t fd, uint8_t targetAddr, Ac_Charging_current *Ret_Buf)
-{
-    int result = FAIL;
-    uint8_t tx[7] = {0xaa, 0x00, targetAddr, CMD_QUERY_AC_OUTPUT_CURRENT, 0x00, 0x00, 0x00};
-    uint8_t rx[512];
-    uint8_t chksum = 0x00;
-    uint8_t len = tranceiveRelDelayTime(fd, tx, sizeof(tx), rx, 100);
-
-    if (len > 6) {
-        if (len < 6 + (rx[4] | rx[5] << 8)) {
-            return result;
-        }
-
-        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
-            chksum ^= rx[6 + idx];
-        }
-
-        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
-                (rx[2] == tx[1]) &&
-                (rx[1] == tx[2]) &&
-                (rx[3] == tx[3])) {
-            Ret_Buf->OuputCurrentL1 = rx[6] + (rx[7] << 8);
-            Ret_Buf->OuputCurrentL2 = rx[8] + (rx[9] << 8);
-            Ret_Buf->OuputCurrentL3 = rx[10] + (rx[11] << 8);
-            result = PASS;
-        }
-    }
-
-    return result;
-}
-
-int Query_AC_Status(uint8_t fd, uint8_t targetAddr, Ac_Status *Ret_Buf)
-{
-    int result = FAIL;
-    uint8_t tx[7] = {0xaa, 0x00, targetAddr, CMD_QUERY_AC_STATUS, 0x00, 0x00, 0x00};
-    uint8_t rx[512];
-    uint8_t chksum = 0x00;
-    uint8_t len = tranceiveRelDelayTime(fd, tx, sizeof(tx), rx, 100);
-
-    if (len > 6) {
-        if (len < 6 + (rx[4] | rx[5] << 8)) {
-            return result;
-        }
-
-        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
-            chksum ^= rx[6 + idx];
-        }
-
-        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
-                (rx[2] == tx[1]) &&
-                (rx[1] == tx[2]) &&
-                (rx[3] == tx[3])) {
-            Ret_Buf->CpStatus = rx[6];
-            Ret_Buf->CurLimit = (rx[7] | (rx[8] << 8));
-            Ret_Buf->PilotVol_P = (rx[9] | (rx[10] << 8));
-            Ret_Buf->PilotVol_N = (rx[11] | (rx[12] << 8));
-            Ret_Buf->LockStatus = rx[13];
-            Ret_Buf->RelayStatus = rx[14];
-            Ret_Buf->ShutterStatus = rx[15];
-            Ret_Buf->MeterStatus = rx[16];
-            Ret_Buf->PpStatus = rx[17];
-            Ret_Buf->MaxCurrent = rx[18];
-            Ret_Buf->RotateSwitchStatus = rx[19];
-//
-//          Ret_Buf->AC_Connector       = (rx[6] >> 0) & 0x01;
-//          Ret_Buf->AC_MainBreaker     = (rx[6] >> 1) & 0x01;
-//          Ret_Buf->SPD                = (rx[6] >> 2) & 0x01;
-//          Ret_Buf->Door_Open          = (rx[6] >> 3) & 0x01;
-//          Ret_Buf->GFD[0]             = (rx[6] >> 4) & 0x01;
-//          Ret_Buf->GFD[1]             = (rx[6] >> 5) & 0x01;
-//          Ret_Buf->AC_Drop            = (rx[6] >> 6) & 0x01;
-//
-//          Ret_Buf->Emergency_IO       = (rx[7] >> 0) & 0x01;
-//
-//          Ret_Buf->Button_Emergency_Press = (rx[8] >> 0) & 0x01;
-//          Ret_Buf->Button_On_Press    = (rx[8] >> 1) & 0x01;
-//          Ret_Buf->Button_Off_Press   = (rx[8] >> 2) & 0x01;
-//          Ret_Buf->Key_1_Press        = (rx[8] >> 3) & 0x01;
-//          Ret_Buf->Key_2_Press        = (rx[8] >> 4) & 0x01;
-//          Ret_Buf->Key_3_Press        = (rx[8] >> 5) & 0x01;
-//          Ret_Buf->Key_4_Press        = (rx[8] >> 6) & 0x01;
-
-            result = PASS;
-        }
-    }
-
-    return result;
-}
-
-int Query_AC_Alarm_Code(uint8_t fd, uint8_t targetAddr, Ac_Alarm_code *Ret_Buf)
-{
-    int result = FAIL;
-    uint8_t tx[7] = {0xaa, 0x00, targetAddr, CMD_QUERY_AC_ALARM_CODE, 0x00, 0x00};
-    uint8_t rx[512];
-    uint8_t chksum = 0x00;
-    uint8_t len = tranceiveRelDelayTime(fd, tx, sizeof(tx), rx, 100);
-
-    if (len > 6) {
-        if (len < 6 + (rx[4] | rx[5] << 8)) {
-            return result;
-        }
-
-        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
-            chksum ^= rx[6 + idx];
-        }
-
-        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
-                (rx[2] == tx[1]) &&
-                (rx[1] == tx[2]) &&
-                (rx[3] == tx[3])) {
-            Ret_Buf->AcAlarmCode = rx[6] + (rx[7] << 8) + (rx[8] << 16) + (rx[9] << 24);
-            result = PASS;
-        }
-    }
-
-    return result;
-}
-
-int Query_Charging_Energy(uint8_t fd, uint8_t targetAddr, Ac_Charging_energy *Ret_Buf)
-{
-    int result = FAIL;
-    uint8_t tx[7] = {0xaa, 0x00, targetAddr, CMD_QUERY_AC_OUTPUT_ENERGY, 0x00, 0x00, 0x00};
-    uint8_t rx[512];
-    uint8_t chksum = 0x00;
-    uint8_t len = tranceiveRelDelayTime(fd, tx, sizeof(tx), rx, 100);
-
-    if (len > 6) {
-        if (len < 6 + (rx[4] | rx[5] << 8)) {
-            return result;
-        }
-
-        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
-            chksum ^= rx[6 + idx];
-        }
-
-        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
-                (rx[2] == tx[1]) &&
-                (rx[1] == tx[2]) &&
-                (rx[3] == tx[3])) {
-            Ret_Buf->Energy = rx[6] + (rx[7] << 8) + (rx[8] << 16) + (rx[9] << 24);
-            result = PASS;
-        }
-    }
-
-    return result;
-}
-
-//------------------------------------------------------------------------------
-//===== Configure =====
-//------------------------------------------------------------------------------
-int Config_Fan_Speed(uint8_t fd, uint8_t targetAddr, FanSpeed *Set_Buf)
-{
-    int result = FAIL;
-    uint8_t tx[15] = {0xaa, 0x00, targetAddr, CMD_CONFIG_FAN_SPEED, 0x08, 0x00, Set_Buf->speed[0] & 0xff, (Set_Buf->speed[0] >> 8) & 0xff, Set_Buf->speed[1] & 0xff, (Set_Buf->speed[1] >> 8) & 0xff, Set_Buf->speed[2] & 0xff, (Set_Buf->speed[2] >> 8) & 0xff, Set_Buf->speed[3] & 0xff, (Set_Buf->speed[3] >> 8) & 0xff, 0x00};
-    uint8_t rx[512];
-    uint8_t chksum = 0x00;
-
-    for (int idx = 0; idx < (tx[4] | tx[5] << 8); idx++) {
-        chksum ^= tx[6 + idx];
-    }
-    tx[14] = chksum;
-
-    uint8_t len = tranceive(fd, tx, sizeof(tx), rx);
-    if (len > 6) {
-        if (len < 6 + (rx[4] | rx[5] << 8)) {
-            return result;
-        }
-
-        chksum = 0x00;
-        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
-            chksum ^= rx[6 + idx];
-        }
-
-        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
-                (rx[2] == tx[1]) &&
-                (rx[1] == tx[2]) &&
-                (rx[3] == tx[3]) &&
-                rx[6] == PASS) {
-            result = PASS;
-        }
-    }
-
-    return result;
-}
-
-int Config_Model_Name(uint8_t fd, uint8_t targetAddr, uint8_t *modelname)
-{
-    int result = FAIL;
-    uint8_t tx[21] = {0xaa, 0x00, targetAddr, CMD_CONFIG_MODEL_NAME, 0x0E, 0x00,
-                      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
-                     };
-    uint8_t rx[512];
-    uint8_t chksum = 0x00;
-
-    memcpy(tx + 6, modelname, 14);
-
-    for (int idx = 0; idx < (tx[4] | tx[5] << 8); idx++) {
-        chksum ^= tx[6 + idx];
-    }
-    tx[20] = chksum;
-
-//  for(int i = 0; i < 21; i++)
-//              printf ("tx = %x \n", tx[i]);
-    uint8_t len = tranceive(fd, tx, sizeof(tx), rx);
-//  for(int i = 0; i < len; i++)
-//                  printf ("rx = %x \n", rx[i]);
-    if (len > 6) {
-        if (len < 6 + (rx[4] | rx[5] << 8)) {
-            return result;
-        }
-
-        chksum = 0x00;
-        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
-            chksum ^= rx[6 + idx];
-        }
-
-        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
-                (rx[2] == tx[1]) &&
-                (rx[1] == tx[2]) &&
-                (rx[3] == tx[3]) &&
-                rx[6] == PASS) {
-            result = PASS;
-        }
-    }
-
-    return result;
-}
-
-int Config_Relay_Output(uint8_t fd, uint8_t targetAddr, Relay *Set_Buf)
-{
-    int result = FAIL;
-    uint8_t tx[10] = {0xaa, 0x00, targetAddr, CMD_CONFIG_RELAY_OUTPUT, 0x03, 0x00, Set_Buf->relay_event.relay_status[0], Set_Buf->relay_event.relay_status[1], Set_Buf->relay_event.relay_status[2]};
-    uint8_t rx[512];
-    uint8_t chksum = 0x00;
-
-    for (int idx = 0; idx < (tx[4] | tx[5] << 8); idx++) {
-        chksum ^= tx[6 + idx];
-    }
-    tx[9] = chksum;
-
-//  for (int i = 0; i < 10; i++)
-//      printf("set relay cmd : tx = %x \n", tx[i]);
-
-    uint8_t len = tranceive(fd, tx, sizeof(tx), rx);
-
-    if (len > 6) {
-        if (len < 6 + (rx[4] | rx[5] << 8)) {
-            return result;
-        }
-
-//      for (int i = 0; i < len; i++)
-//          printf("set relay cmd : rx = %x \n", rx[i]);
-
-        chksum = 0x00;
-        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
-            chksum ^= rx[6 + idx];
-        }
-
-        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
-                (rx[2] == tx[1]) &&
-                (rx[1] == tx[2]) &&
-                (rx[3] == tx[3]) &&
-                rx[6] == PASS) {
-            result = PASS;
-        }
-    }
-
-    return result;
-}
-
-int Config_Gpio_Output(uint8_t fd, uint8_t targetAddr, Gpio_out *Set_Buf)
-{
-    int result = FAIL;
-    uint8_t tx[9] = {0xaa, 0x00, targetAddr, CMD_CONFIG_GPIO_OUTPUT, 0x01, 0x00, 0x00, 0x00};
-    uint8_t rx[512];
-    uint8_t chksum = 0x00;
-
-    tx[6] |= (Set_Buf->AC_Connector ? 0x01 : 0x00);
-
-    for (int idx = 0; idx < 2; idx++) {
-        tx[6] |= (Set_Buf->Button_LED[idx] ? 0x01 : 0x00) << (1 + idx);
-    }
-
-    for (int idx = 0; idx < 4; idx++) {
-        tx[6] |= (Set_Buf->System_LED[idx] ? 0x01 : 0x00) << (3 + idx);
-    }
-
-    for (int idx = 0; idx < (tx[4] | tx[5] << 8); idx++) {
-        chksum ^= tx[6 + idx];
-    }
-    tx[14] = chksum;
-
-    uint8_t len = tranceive(fd, tx, sizeof(tx), rx);
-
-    if (len > 6) {
-        if (len < 6 + (rx[4] | rx[5] << 8)) {
-            return result;
-        }
-
-        chksum = 0x00;
-        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
-            chksum ^= rx[6 + idx];
-        }
-
-        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
-                (rx[2] == tx[1]) &&
-                (rx[1] == tx[2]) &&
-                (rx[3] == tx[3])) {
-            result = PASS;
-        }
-    }
-
-    return result;
-}
-
-int Config_Rtc_Data(uint8_t fd, uint8_t targetAddr, Rtc *Set_Buf)
-{
-    int result = FAIL;
-    uint8_t tx[21] = { 0xaa, 0x00, targetAddr, CMD_CONFIG_RTC_DATA, 0x0E, 0x00, Set_Buf->RtcData[0], Set_Buf->RtcData[1],
-                       Set_Buf->RtcData[2], Set_Buf->RtcData[3], Set_Buf->RtcData[4], Set_Buf->RtcData[5], Set_Buf->RtcData[6], Set_Buf->RtcData[7],
-                       Set_Buf->RtcData[8], Set_Buf->RtcData[9], Set_Buf->RtcData[10], Set_Buf->RtcData[11], Set_Buf->RtcData[12], Set_Buf->RtcData[13]
-                     };
-    uint8_t rx[512];
-    uint8_t chksum = 0x00;
-
-    for (int idx = 0; idx < (tx[4] | tx[5] << 8); idx++) {
-        chksum ^= tx[6 + idx];
-    }
-    tx[20] = chksum;
-
-    if (tranceive(fd, tx, sizeof(tx), rx) > 0) {
-        chksum = 0x00;
-        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
-            chksum ^= rx[6 + idx];
-        }
-
-        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
-                (rx[2] == tx[1]) &&
-                (rx[1] == tx[2]) &&
-                (rx[3] == tx[3]) &&
-                rx[6] == PASS) {
-            result = PASS;
-        }
-    }
-
-    return result;
-}
-
-int Config_LED_Status(uint8_t fd, uint8_t targetAddr, Ac_Led_Status *Ret_Buf)
-{
-    int result = FAIL;
-    uint8_t tx[12] = {0xaa, 0x00, targetAddr, CMD_CONFIG_AC_LED_STATUS, 0x05, 0x00, Ret_Buf->ActionMode, (Ret_Buf->AcAlarmCode >> 0) & 0xFF,
-                      (Ret_Buf->AcAlarmCode >> 8) & 0xFF, (Ret_Buf->AcAlarmCode >> 16) & 0xFF, (Ret_Buf->AcAlarmCode >> 24) & 0xFF
-                     };
-    uint8_t rx[512];
-    uint8_t chksum = 0x00;
-
-    for (int idx = 0; idx < (tx[4] | tx[5] << 8); idx++) {
-        chksum ^= tx[6 + idx];
-    }
-    tx[11] = chksum;
-
-    if (tranceiveRelDelayTime(fd, tx, sizeof(tx), rx, 100) > 0) {
-        chksum = 0x00;
-        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
-            chksum ^= rx[6 + idx];
-        }
-
-        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
-                (rx[2] == tx[1]) &&
-                (rx[1] == tx[2]) &&
-                (rx[3] == tx[3]) &&
-                rx[6] == PASS) {
-            result = PASS;
-        }
-    }
-
-    return result;
-}
-
-int Config_Ac_Duty(uint8_t fd, uint8_t targetAddr, uint8_t _value)
-{
-    int result = FAIL;
-    uint8_t tx[8] = {0xaa, 0x00, targetAddr, CMD_CONFIG_AC_DUTY, 0x01, 0x00, _value};
-    uint8_t rx[512];
-    uint8_t chksum = 0x00;
-
-    for (int idx = 0; idx < (tx[4] | tx[5] << 8); idx++) {
-        chksum ^= tx[6 + idx];
-    }
-    tx[7] = chksum;
-
-    if (tranceiveRelDelayTime(fd, tx, sizeof(tx), rx, 100) > 0) {
-        chksum = 0x00;
-        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
-            chksum ^= rx[6 + idx];
-        }
-
-        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
-                (rx[2] == tx[1]) &&
-                (rx[1] == tx[2]) &&
-                (rx[3] == tx[3]) &&
-                rx[6] == PASS) {
-            result = PASS;
-        }
-    }
-
-    return result;
-}
-
-int Config_Legacy_Req(uint8_t fd, uint8_t targetAddr, uint8_t _switch)
-{
-    int result = FAIL;
-    uint8_t tx[9] = {0xaa, 0x00, targetAddr, CMD_CONFIG_LEGACY_REQ, 0x02, 0x00, _switch, 0x00};
-    uint8_t rx[512];
-    uint8_t chksum = 0x00;
-
-    for (int idx = 0; idx < (tx[4] | tx[5] << 8); idx++) {
-        chksum ^= tx[6 + idx];
-    }
-    tx[8] = chksum;
-
-    if (tranceiveRelDelayTime(fd, tx, sizeof(tx), rx, 100) > 0) {
-        chksum = 0x00;
-        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
-            chksum ^= rx[6 + idx];
-        }
-
-        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
-                (rx[2] == tx[1]) &&
-                (rx[1] == tx[2]) &&
-                (rx[3] == tx[3]) &&
-                rx[6] == PASS) {
-            result = PASS;
-        }
-    }
-
-    return result;
-}
-
-int Config_Reset_MCU(uint8_t fd, uint8_t targetAddr)
-{
-    int result = FAIL;
-    uint8_t tx[9] = {0xaa, 0x00, targetAddr, CMD_CONFIG_RESET_MCU, 0x02, 0x00, 0x01, 0x00};
-    uint8_t rx[512];
-    uint8_t chksum = 0x00;
-
-    for (int idx = 0; idx < (tx[4] | tx[5] << 8); idx++) {
-        chksum ^= tx[6 + idx];
-    }
-    tx[7] = chksum;
-
-    if (tranceiveRelDelayTime(fd, tx, sizeof(tx), rx, 100) > 0) {
-        chksum = 0x00;
-        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
-            chksum ^= rx[6 + idx];
-        }
-
-        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
-                (rx[2] == tx[1]) &&
-                (rx[1] == tx[2]) &&
-                (rx[3] == tx[3]) &&
-                rx[6] == PASS) {
-            result = PASS;
-        }
-    }
-
-    return result;
-}
-
-int Config_Gfd_Value(uint8_t fd, uint8_t targetAddr, Gfd_config *Set_Buf)
-{
-    int result = FAIL;
-    uint8_t tx[9] = {0xaa, 0x00, targetAddr, CMD_CONFIG_GDF_VALUE, 0x02, 0x00, 0x00, 0x00, 0x00};
-    uint8_t rx[512];
-    uint8_t chksum = 0x00;
-
-    tx[6] = Set_Buf->index;
-    tx[7] = Set_Buf->state;
-
-    for (int idx = 0; idx < (tx[4] | tx[5] << 8); idx++) {
-        chksum ^= tx[6 + idx];
-    }
-    tx[8] = chksum;
-
-    uint8_t len = tranceive(fd, tx, sizeof(tx), rx);
-
-    if (len > 6) {
-        if (len < 6 + (rx[4] | rx[5] << 8)) {
-            return result;
-        }
-
-        chksum = 0x00;
-        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
-            chksum ^= rx[6 + idx];
-        }
-
-        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
-                (rx[2] == tx[1]) &&
-                (rx[1] == tx[2]) &&
-                (rx[3] == tx[3])) {
-            result = PASS;
-        }
-    }
-
-    return result;
-}
-
-int Config_CSU_Mode(uint8_t fd, uint8_t targetAddr)
-{
-    int result = FAIL;
-    uint8_t tx[9] = {0xaa, 0x00, targetAddr, CMD_CONFIG_CSU_MODE, 0x02, 0x00, 0x01, 0x00};
-    uint8_t rx[512];
-    uint8_t chksum = 0x00;
-
-    for (int idx = 0; idx < (tx[4] | tx[5] << 8); idx++) {
-        chksum ^= tx[6 + idx];
-    }
-    tx[7] = chksum;
-
-    if (tranceiveRelDelayTime(fd, tx, sizeof(tx), rx, 100) > 0) {
-        chksum = 0x00;
-        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
-            chksum ^= rx[6 + idx];
-        }
-
-        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
-                (rx[2] == tx[1]) &&
-                (rx[1] == tx[2]) &&
-                (rx[3] == tx[3]) &&
-                rx[6] == PASS) {
-            result = PASS;
-        }
-    }
-
-    return result;
-}
-
-int Config_Led_Color(uint8_t fd, uint8_t targetAddr, Led_Color *Ret_Buf)
-{
-    int result = FAIL;
-    uint8_t tx[13] = {0xaa,
-                      0x00,
-                      targetAddr,
-                      CMD_CONFIG_LEN_COLOR,
-                      0x06,
-                      0x00,
-                      Ret_Buf->Connect_1_Red,
-                      Ret_Buf->Connect_1_Green,
-                      Ret_Buf->Connect_1_Blue,
-                      Ret_Buf->Connect_2_Red,
-                      Ret_Buf->Connect_2_Green,
-                      Ret_Buf->Connect_2_Blue
-                     };
-    uint8_t rx[512];
-    uint8_t chksum = 0x00;
-
-    for (int idx = 0; idx < (tx[4] | tx[5] << 8); idx++) {
-        chksum ^= tx[6 + idx];
-    }
-    tx[12] = chksum;
-
-//  for(int i = 0; i < 13; i++)
-//          printf ("tx = %x \n", tx[i]);
-
-    uint8_t len = tranceive(fd, tx, sizeof(tx), rx);
-
-//  for(int i = 0; i < len; i++)
-//      printf ("rx = %x \n", rx[i]);
-
-    if (len > 6) {
-        if (len < 6 + (rx[4] | rx[5] << 8)) {
-            return result;
-        }
-
-        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
-            chksum ^= rx[6 + idx];
-        }
-
-        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
-                (rx[2] == tx[1]) &&
-                (rx[1] == tx[2]) &&
-                (rx[3] == tx[3]) &&
-                (rx[6] == PASS)) {
-            result = PASS;
-        }
-    }
-
-    return result;
-}
-
-//------------------------------------------------------------------------------
-//===== Update =====
-//------------------------------------------------------------------------------
-int Update_Start(uint8_t fd, uint8_t targetAddr, uint32_t crc32)
-{
-    int result = FAIL;
-    uint8_t tx[11] = {0xaa, 0x00, targetAddr, CMD_UPDATE_START, 0x04, 0x00, (crc32 >> 0) & 0xff, (crc32 >> 8) & 0xff, (crc32 >> 16) & 0xff, (crc32 >> 24) & 0xff, 0x00};
-    uint8_t rx[512];
-    uint8_t chksum = 0x00;
-
-    for (int idx = 0; idx < (tx[4] | tx[5] << 8); idx++) {
-        chksum ^= tx[6 + idx];
-    }
-    tx[10] = chksum;
-
-    uint8_t len = tranceive(fd, tx, sizeof(tx), rx);
-    if (len > 6) {
-        if (len < 6 + (rx[4] | rx[5] << 8)) {
-            return result;
-        }
-
-        chksum = 0x00;
-        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
-            chksum ^= rx[6 + idx];
-        }
-
-        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
-                (rx[2] == tx[1]) &&
-                (rx[1] == tx[2]) &&
-                (rx[3] == tx[3]) &&
-                (rx[6] == 0x00)) {
-            result = PASS;
-        }
-    }
-
-    return result;
-}
-
-int Update_Abord(uint8_t fd, uint8_t targetAddr)
-{
-    int result = FAIL;
-    uint8_t tx[7] = {0xaa, 0x00, targetAddr, CMD_UPDATE_ABORT, 0x04, 0x00, 0x00};
-    uint8_t rx[512];
-    uint8_t chksum = 0x00;
-    uint8_t len = tranceive(fd, tx, sizeof(tx), rx);
-
-    if (len > 6) {
-        if (len < 6 + (rx[4] | rx[5] << 8)) {
-            return result;
-        }
-
-        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
-            chksum ^= rx[6 + idx];
-        }
-
-        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
-                (rx[2] == tx[1]) &&
-                (rx[1] == tx[2]) &&
-                (rx[3] == tx[3]) &&
-                (rx[6] == 0x00)) {
-            result = PASS;
-        }
-    }
-
-    return result;
-}
-
-int Update_Transfer(uint8_t fd, uint8_t targetAddr, uint32_t startAddr, uint8_t *data, uint16_t length)
-{
-    int result = FAIL;
-    uint8_t tx[11 + length];
-    uint8_t rx[512];
-    uint8_t chksum = 0x00;
-
-    tx[0] = 0xaa;
-    tx[1] = 0x00;
-    tx[2] = targetAddr;
-    tx[3] = CMD_UPDATE_TRANSFER;
-    tx[4] = (4 + length) & 0xff;
-    tx[5] = ((4 + length) >> 8) & 0xff;
-    tx[6] = (startAddr >> 0) & 0xff;
-    tx[7] = (startAddr >> 8) & 0xff;
-    tx[8] = (startAddr >> 16) & 0xff;
-    tx[9] = (startAddr >> 24) & 0xff;
-    memcpy(tx + 10, data, length);
-
-    for (int idx = 0; idx < (tx[4] | tx[5] << 8); idx++) {
-        chksum ^= tx[6 + idx];
-    }
-    tx[sizeof(tx) - 1] = chksum;
-
-    uint8_t len = tranceive(fd, tx, sizeof(tx), rx);
-
-    if (len > 6) {
-        if (len < 6 + (rx[4] | rx[5] << 8)) {
-            return result;
-        }
-
-        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
-            chksum ^= rx[6 + idx];
-        }
-
-        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
-                (rx[2] == tx[1]) &&
-                (rx[1] == tx[2]) &&
-                (rx[3] == tx[3]) &&
-                (rx[6] == 0x00)) {
-            result = PASS;
-        }
-    }
-
-    return result;
-}
-
-int Update_Finish(uint8_t fd, uint8_t targetAddr)
-{
-    int result = FAIL;
-    uint8_t tx[7] = {0xaa, 0x00, targetAddr, CMD_UPDATE_FINISH, 0x04, 0x00, 0x00};
-    uint8_t rx[512];
-    uint8_t chksum = 0x00;
-    uint8_t len = tranceive(fd, tx, sizeof(tx), rx);
-
-    if (len > 6) {
-        if (len < 6 + (rx[4] | rx[5] << 8)) {
-            return result;
-        }
-
-        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
-            chksum ^= rx[6 + idx];
-        }
-
-        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
-                (rx[2] == tx[1]) &&
-                (rx[1] == tx[2]) &&
-                (rx[3] == tx[3]) &&
-                (rx[6] == 0x00)) {
-            result = PASS;
-        }
-    }
-
-    return result;
-}
+/*
+ * internalComm.c
+ *
+ *  Created on: 2019年5月7日
+ *      Author: foluswen
+ */
+#include <stdio.h>      /*標準輸入輸出定義*/
+#include <stdlib.h>     /*標準函數庫定義*/
+#include <stdint.h>
+#include <string.h>
+
+#include <unistd.h>
+#include <termios.h>
+
+#include "internalComm.h"
+#include "../Config.h"
+
+//------------------------------------------------------------------------------
+int tranceiveRelDelayTime(int fd, uint8_t *cmd, uint8_t cmd_len, uint8_t *rx, uint16_t _delay)
+{
+    int len;
+    //sleep(2); //required to make flush work, for some reason
+    tcflush(fd, TCIOFLUSH);
+
+    if (write(fd, cmd, cmd_len) >= cmd_len) {
+        usleep(_delay * 1000);
+        len = read(fd, rx, 512);
+    } else {
+#ifdef SystemLogMessage
+        DEBUG_ERROR("Serial command %s response fail.\n", cmd);
+#endif
+    }
+
+    return len;
+}
+
+int tranceive(int fd, uint8_t *cmd, uint8_t cmd_len, uint8_t *rx)
+{
+    int len;
+    //sleep(2); //required to make flush work, for some reason
+    tcflush(fd, TCIOFLUSH);
+
+    if (write(fd, cmd, cmd_len) >= cmd_len) {
+        usleep(15000);
+        len = read(fd, rx, 512);
+    } else {
+#ifdef SystemLogMessage
+        DEBUG_ERROR("Serial command %s response fail.\n", cmd);
+#endif
+    }
+
+    return len;
+}
+
+//------------------------------------------------------------------------------
+//===== Query =====
+//------------------------------------------------------------------------------
+int Query_FW_Ver(uint8_t fd, uint8_t targetAddr, Ver *Ret_Buf)
+{
+    int result = FAIL;
+    uint8_t tx[7] = {0xaa, 0x00, targetAddr, CMD_QUERY_FW_VER, 0x00, 0x00, 0x00};
+    uint8_t rx[512];
+    uint8_t chksum = 0x00;
+    uint8_t len = tranceive(fd, tx, sizeof(tx), rx);
+
+//      for (int i = 0; i < 7; i++)
+//          printf("tx = %x \n", tx[i]);
+//      for (int i = 0; i < len; i++)
+//          printf("rx = %x \n", rx[i]);
+
+    if (len > 6) {
+        if (len < 6 + (rx[4] | rx[5] << 8)) {
+            return result;
+        }
+
+        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
+            chksum ^= rx[6 + idx];
+        }
+
+        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
+                (rx[2] == tx[1]) &&
+                (rx[1] == tx[2]) &&
+                (rx[3] == tx[3])) {
+            memcpy(Ret_Buf->Version_FW, (char *)rx + 6, (rx[4] | rx[5] << 8));
+            *(Ret_Buf->Version_FW + 8) = 0x00;
+            result = PASS;
+        }
+    }
+
+    return result;
+}
+
+int Query_HW_Ver(uint8_t fd, uint8_t targetAddr, Ver *Ret_Buf)
+{
+    int result = FAIL;
+    uint8_t tx[7] = {0xaa, 0x00, targetAddr, CMD_QUERY_HW_VER, 0x00, 0x00, 0x00};
+    uint8_t rx[512];
+    uint8_t chksum = 0x00;
+    uint8_t len = tranceive(fd, tx, sizeof(tx), rx);
+
+    if (len > 6) {
+        if (len < 6 + (rx[4] | rx[5] << 8)) {
+            return result;
+        }
+
+        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
+            chksum ^= rx[6 + idx];
+        }
+
+        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
+                (rx[2] == tx[1]) &&
+                (rx[1] == tx[2]) &&
+                (rx[3] == tx[3])) {
+            memcpy(Ret_Buf->Version_HW, (char *)rx + 6, (rx[4] | rx[5] << 8));
+            *(Ret_Buf->Version_HW + 8) = 0x00;
+            result = PASS;
+        }
+    }
+
+    return result;
+}
+
+int Query_Present_InputVoltage(uint8_t fd, uint8_t targetAddr, PresentInputVoltage *Ret_Buf)
+{
+    int result = FAIL;
+    uint8_t tx[7] = {0xaa, 0x00, targetAddr, CMD_QUERY_PRESENT_IN_VOL, 0x00, 0x00, 0x00};
+    uint8_t rx[512];
+    uint8_t chksum = 0x00;
+    uint8_t len = tranceive(fd, tx, sizeof(tx), rx);
+
+    if (len > 13) {
+        if (len < 6 + (rx[4] | rx[5] << 8)) {
+            return result;
+        }
+
+        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
+            chksum ^= rx[6 + idx];
+        }
+        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
+                (rx[2] == tx[1]) &&
+                (rx[1] == tx[2]) &&
+                (rx[3] == tx[3]) &&
+                chksum != 0) {
+            Ret_Buf->inputType = rx[6];
+            Ret_Buf->L1N_L12 = (rx[7] | (rx[8] << 8)) / 10.0;
+            Ret_Buf->L2N_L23 = (rx[9] | (rx[10] << 8)) / 10.0;
+            Ret_Buf->L3N_L31 = (rx[11] | (rx[12] << 8)) / 10.0;
+
+            if (Ret_Buf->L1N_L12 >= 320 ||
+                    Ret_Buf->L2N_L23 >= 320 ||
+                    Ret_Buf->L3N_L31 >= 320) {
+                result = FAIL;
+            } else {
+                result = PASS;
+            }
+        }
+    }
+
+    return result;
+}
+
+int Query_Present_OutputVoltage(uint8_t fd, uint8_t targetAddr, PresentOutputVoltage *Ret_Buf)
+{
+    int result = FAIL;
+    uint8_t tx[7] = {0xaa, 0x00, targetAddr, CMD_QUERY_PRESENT_OUT_VOL, 0x00, 0x00, 0x00};
+    uint8_t rx[512];
+    uint8_t chksum = 0x00;
+    uint8_t len = tranceive(fd, tx, sizeof(tx), rx);
+
+    if (len > 6) {
+        if (len < 6 + (rx[4] | rx[5] << 8)) {
+            return result;
+        }
+
+        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
+            chksum ^= rx[6 + idx];
+        }
+
+        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
+                (rx[2] == tx[1]) &&
+                (rx[1] == tx[2]) &&
+                (rx[3] == tx[3])) {
+
+            Ret_Buf->behindFuse_Voltage_C1 = (rx[6] | (rx[7] << 8));
+            Ret_Buf->behindRelay_Voltage_C1 = (rx[8] | (rx[9] << 8));
+            if ((rx[4] | rx[5] << 8) > 4) {
+                Ret_Buf->behindFuse_Voltage_C2 = (rx[10] | (rx[11] << 8));
+                Ret_Buf->behindRelay_Voltage_C2 = (rx[12] | (rx[13] << 8));
+            }
+            result = PASS;
+        }
+    }
+
+    return result;
+}
+
+int Query_Fan_Speed(uint8_t fd, uint8_t targetAddr, FanSpeed *Ret_Buf)
+{
+    int result = FAIL;
+    uint8_t tx[7] = {0xaa, 0x00, targetAddr, CMD_QUERY_FAN_SPEED, 0x00, 0x00, 0x00};
+    uint8_t rx[512];
+    uint8_t chksum = 0x00;
+    uint8_t len = tranceive(fd, tx, sizeof(tx), rx);
+
+    if (len > 6) {
+        if (len < 6 + (rx[4] | rx[5] << 8)) {
+            return result;
+        }
+
+        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
+            chksum ^= rx[6 + idx];
+        }
+
+        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
+                (rx[2] == tx[1]) &&
+                (rx[1] == tx[2]) &&
+                (rx[3] == tx[3])) {
+            for (int idx = 0; idx < 4; idx++) {
+                Ret_Buf->speed[idx] = (rx[6 + (2 * idx)] | (rx[6 + (2 * idx) + 1] << 8));
+            }
+
+            result = PASS;
+        }
+    }
+
+    return result;
+}
+
+int Query_Temperature(uint8_t fd, uint8_t targetAddr, Temperature *Ret_Buf)
+{
+    int result = FAIL;
+    uint8_t tx[7] = {0xaa, 0x00, targetAddr, CMD_QUERY_TEMPERATURE, 0x00, 0x00, 0x00};
+    uint8_t rx[512];
+    uint8_t chksum = 0x00;
+    uint8_t len = tranceive(fd, tx, sizeof(tx), rx);
+
+    if (len > 6) {
+        if (len < 6 + (rx[4] | rx[5] << 8)) {
+            return result;
+        }
+
+        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
+            chksum ^= rx[6 + idx];
+        }
+
+        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
+                (rx[2] == tx[1]) &&
+                (rx[1] == tx[2]) &&
+                (rx[3] == tx[3])) {
+            for (int idx = 0; idx < 4; idx++) {
+                Ret_Buf->temperature[idx] = rx[6 + idx] - 60;
+            }
+
+            result = PASS;
+        }
+    }
+
+
+    return result;
+}
+
+int Query_Aux_PowerVoltage(uint8_t fd, uint8_t targetAddr, AuxPower *Ret_Buf)
+{
+    int result = FAIL;
+    uint8_t tx[7] = {0xaa, 0x00, targetAddr, CMD_QUERY_AUX_POWER_VOL, 0x00, 0x00, 0x00};
+    uint8_t rx[512];
+    uint8_t chksum = 0x00;
+    uint8_t len = tranceive(fd, tx, sizeof(tx), rx);
+
+    if (len > 6) {
+        if (len < 6 + (rx[4] | rx[5] << 8)) {
+            return result;
+        }
+
+        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
+            chksum ^= rx[6 + idx];
+        }
+
+        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
+                (rx[2] == tx[1]) &&
+                (rx[1] == tx[2]) &&
+                (rx[3] == tx[3])) {
+            for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
+                Ret_Buf->voltage[idx] = rx[6 + idx];
+            }
+
+            result = PASS;
+        }
+    }
+
+    return result;
+}
+
+int Query_Relay_Output(uint8_t fd, uint8_t targetAddr, Relay *Ret_Buf)
+{
+    int result = FAIL;
+    uint8_t tx[7] = {0xaa, 0x00, targetAddr, CMD_QUERY_RELAY_OUTPUT, 0x00, 0x00, 0x00};
+    uint8_t rx[512];
+    uint8_t chksum = 0x00;
+    uint8_t len = tranceive(fd, tx, sizeof(tx), rx);
+
+//  for (int i = 0; i < 7; i++)
+//      printf("tx = %x \n", tx[i]);
+//  for (int i = 0; i < len; i++)
+//      printf("rx = %x \n", rx[i]);
+
+    if (len > 6) {
+        if (len < 6 + (rx[4] | rx[5] << 8)) {
+            return result;
+        }
+
+        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
+            chksum ^= rx[6 + idx];
+        }
+
+        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
+                (rx[2] == tx[1]) &&
+                (rx[1] == tx[2]) &&
+                (rx[3] == tx[3])) {
+            Ret_Buf->relay_event.bits.AC_Contactor = (rx[6] >> 0) & 0x01;
+            Ret_Buf->relay_event.bits.CCS_Precharge = (rx[6] >> 1) & 0x01;
+
+            Ret_Buf->relay_event.bits.Gun1_N = (rx[7] >> 0) & 0x01;
+            Ret_Buf->relay_event.bits.Gun1_P = (rx[7] >> 1) & 0x01;
+            Ret_Buf->relay_event.bits.Gun1_Parallel_N = (rx[7] >> 2) & 0x01;
+            Ret_Buf->relay_event.bits.Gun1_Parallel_P = (rx[7] >> 3) & 0x01;
+
+            Ret_Buf->relay_event.bits.Gun2_N = (rx[8] >> 0) & 0x01;
+            Ret_Buf->relay_event.bits.Gun2_P = (rx[8] >> 1) & 0x01;
+            result = PASS;
+        }
+    }
+
+    return result;
+}
+
+int Query_Gfd_Adc(uint8_t fd, uint8_t targetAddr, Gfd *Ret_Buf)
+{
+    int result = FAIL;
+    uint8_t tx[7] = {0xaa, 0x00, targetAddr, CMD_QUERY_GFD_ADC, 0x00, 0x00, 0x00};
+    uint8_t rx[512];
+    uint8_t chksum = 0x00;
+    uint8_t len = tranceive(fd, tx, sizeof(tx), rx);
+
+//  for(int i = 0; i < 7; i++)
+//      printf ("tx = %d \n", tx[i]);
+    if (len > 6) {
+        if (len < 6 + (rx[4] | rx[5] << 8)) {
+            //printf("Query_Gfd_Adc fail \n");
+            return result;
+        }
+
+//      for(int i = 0; i < len; i++)
+//          printf ("rx = %d \n", rx[i]);
+
+        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
+            chksum ^= rx[6 + idx];
+        }
+
+        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
+                (rx[2] == tx[1]) &&
+                (rx[1] == tx[2]) &&
+                (rx[3] == tx[3])) {
+            Ret_Buf->Resister_conn1 = (rx[6] | (rx[7] << 8));
+            Ret_Buf->voltage_conn1 = (rx[8] | (rx[9] << 8));
+            Ret_Buf->result_conn1 = rx[10];
+            Ret_Buf->rb_step_1 = rx[11];
+
+            Ret_Buf->Resister_conn2 = (rx[12] | (rx[13] << 8));
+            Ret_Buf->voltage_conn2 = (rx[14] | (rx[15] << 8));
+            Ret_Buf->result_conn2 = rx[16];
+            Ret_Buf->rb_step_2 = rx[17];
+
+            result = PASS;
+        }
+    }
+
+    return result;
+}
+
+int Query_Gpio_Input(uint8_t fd, uint8_t targetAddr, Gpio_in *Ret_Buf)
+{
+    int result = FAIL;
+    uint8_t tx[7] = {0xaa, 0x00, targetAddr, CMD_QUERY_GPIO_IN, 0x00, 0x00, 0x00};
+    uint8_t rx[512];
+    uint8_t chksum = 0x00;
+    uint8_t len = tranceive(fd, tx, sizeof(tx), rx);
+
+    if (len > 6) {
+        if (len < 6 + (rx[4] | rx[5] << 8)) {
+            return result;
+        }
+
+        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
+            chksum ^= rx[6 + idx];
+        }
+
+        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
+                (rx[2] == tx[1]) &&
+                (rx[1] == tx[2]) &&
+                (rx[3] == tx[3])) {
+            Ret_Buf->AC_Connector       = (rx[6] >> 0) & 0x01;
+            Ret_Buf->AC_MainBreaker     = (rx[6] >> 1) & 0x01;
+            Ret_Buf->SPD                = (rx[6] >> 2) & 0x01;
+            Ret_Buf->Door_Open          = ((rx[6] >> 3) & 0x01);
+            Ret_Buf->GFD[0]             = (rx[6] >> 4) & 0x01;
+            Ret_Buf->GFD[1]             = (rx[6] >> 5) & 0x01;
+            Ret_Buf->AC_Drop            = (rx[6] >> 6) & 0x01;
+
+            Ret_Buf->Emergency_IO       = (rx[7] >> 0) & 0x01;
+
+            Ret_Buf->Button_Emergency_Press = (rx[8] >> 0) & 0x01;
+            Ret_Buf->Button_On_Press    = (rx[8] >> 1) & 0x01;
+            Ret_Buf->Button_Off_Press   = (rx[8] >> 2) & 0x01;
+            Ret_Buf->Key_1_Press        = (rx[8] >> 3) & 0x01;
+            Ret_Buf->Key_2_Press        = (rx[8] >> 4) & 0x01;
+            Ret_Buf->Key_3_Press        = (rx[8] >> 5) & 0x01;
+            Ret_Buf->Key_4_Press        = (rx[8] >> 6) & 0x01;
+
+            result = PASS;
+        }
+    }
+
+    return result;
+}
+
+int Query_Model_Name(uint8_t fd, uint8_t targetAddr, uint8_t *modelname)
+{
+    int result = FAIL;
+    uint8_t tx[7] = {0xaa, 0x00, targetAddr, CMD_QUERY_MODEL_NAME, 0x00, 0x00, 0x00};
+    uint8_t rx[512];
+    uint8_t chksum = 0x00;
+    uint8_t len = tranceive(fd, tx, sizeof(tx), rx);
+
+    if (len > 6) {
+        if (len < 6 + (rx[4] | rx[5] << 8)) {
+            return result;
+        }
+
+        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
+            chksum ^= rx[6 + idx];
+        }
+
+        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
+                (rx[2] == tx[1]) &&
+                (rx[1] == tx[2]) &&
+                (rx[3] == tx[3])) {
+            strncpy((char *)modelname, (char *)(rx + 6), (rx[4] | rx[5] << 8));
+            result = PASS;
+        }
+    }
+
+    return result;
+}
+
+int Query_Charging_Current(uint8_t fd, uint8_t targetAddr, Ac_Charging_current *Ret_Buf)
+{
+    int result = FAIL;
+    uint8_t tx[7] = {0xaa, 0x00, targetAddr, CMD_QUERY_AC_OUTPUT_CURRENT, 0x00, 0x00, 0x00};
+    uint8_t rx[512];
+    uint8_t chksum = 0x00;
+    uint8_t len = tranceiveRelDelayTime(fd, tx, sizeof(tx), rx, 100);
+
+    if (len > 6) {
+        if (len < 6 + (rx[4] | rx[5] << 8)) {
+            return result;
+        }
+
+        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
+            chksum ^= rx[6 + idx];
+        }
+
+        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
+                (rx[2] == tx[1]) &&
+                (rx[1] == tx[2]) &&
+                (rx[3] == tx[3])) {
+            Ret_Buf->OuputCurrentL1 = rx[6] + (rx[7] << 8);
+            Ret_Buf->OuputCurrentL2 = rx[8] + (rx[9] << 8);
+            Ret_Buf->OuputCurrentL3 = rx[10] + (rx[11] << 8);
+            result = PASS;
+        }
+    }
+
+    return result;
+}
+
+int Query_AC_Status(uint8_t fd, uint8_t targetAddr, Ac_Status *Ret_Buf)
+{
+    int result = FAIL;
+    uint8_t tx[7] = {0xaa, 0x00, targetAddr, CMD_QUERY_AC_STATUS, 0x00, 0x00, 0x00};
+    uint8_t rx[512];
+    uint8_t chksum = 0x00;
+    uint8_t len = tranceiveRelDelayTime(fd, tx, sizeof(tx), rx, 100);
+
+    if (len > 6) {
+        if (len < 6 + (rx[4] | rx[5] << 8)) {
+            return result;
+        }
+
+        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
+            chksum ^= rx[6 + idx];
+        }
+
+        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
+                (rx[2] == tx[1]) &&
+                (rx[1] == tx[2]) &&
+                (rx[3] == tx[3])) {
+            Ret_Buf->CpStatus = rx[6];
+            Ret_Buf->CurLimit = (rx[7] | (rx[8] << 8));
+            Ret_Buf->PilotVol_P = (rx[9] | (rx[10] << 8));
+            Ret_Buf->PilotVol_N = (rx[11] | (rx[12] << 8));
+            Ret_Buf->LockStatus = rx[13];
+            Ret_Buf->RelayStatus = rx[14];
+            Ret_Buf->ShutterStatus = rx[15];
+            Ret_Buf->MeterStatus = rx[16];
+            Ret_Buf->PpStatus = rx[17];
+            Ret_Buf->MaxCurrent = rx[18];
+            Ret_Buf->RotateSwitchStatus = rx[19];
+//
+//          Ret_Buf->AC_Connector       = (rx[6] >> 0) & 0x01;
+//          Ret_Buf->AC_MainBreaker     = (rx[6] >> 1) & 0x01;
+//          Ret_Buf->SPD                = (rx[6] >> 2) & 0x01;
+//          Ret_Buf->Door_Open          = (rx[6] >> 3) & 0x01;
+//          Ret_Buf->GFD[0]             = (rx[6] >> 4) & 0x01;
+//          Ret_Buf->GFD[1]             = (rx[6] >> 5) & 0x01;
+//          Ret_Buf->AC_Drop            = (rx[6] >> 6) & 0x01;
+//
+//          Ret_Buf->Emergency_IO       = (rx[7] >> 0) & 0x01;
+//
+//          Ret_Buf->Button_Emergency_Press = (rx[8] >> 0) & 0x01;
+//          Ret_Buf->Button_On_Press    = (rx[8] >> 1) & 0x01;
+//          Ret_Buf->Button_Off_Press   = (rx[8] >> 2) & 0x01;
+//          Ret_Buf->Key_1_Press        = (rx[8] >> 3) & 0x01;
+//          Ret_Buf->Key_2_Press        = (rx[8] >> 4) & 0x01;
+//          Ret_Buf->Key_3_Press        = (rx[8] >> 5) & 0x01;
+//          Ret_Buf->Key_4_Press        = (rx[8] >> 6) & 0x01;
+
+            result = PASS;
+        }
+    }
+
+    return result;
+}
+
+int Query_AC_Alarm_Code(uint8_t fd, uint8_t targetAddr, Ac_Alarm_code *Ret_Buf)
+{
+    int result = FAIL;
+    uint8_t tx[7] = {0xaa, 0x00, targetAddr, CMD_QUERY_AC_ALARM_CODE, 0x00, 0x00};
+    uint8_t rx[512];
+    uint8_t chksum = 0x00;
+    uint8_t len = tranceiveRelDelayTime(fd, tx, sizeof(tx), rx, 100);
+
+    if (len > 6) {
+        if (len < 6 + (rx[4] | rx[5] << 8)) {
+            return result;
+        }
+
+        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
+            chksum ^= rx[6 + idx];
+        }
+
+        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
+                (rx[2] == tx[1]) &&
+                (rx[1] == tx[2]) &&
+                (rx[3] == tx[3])) {
+            Ret_Buf->AcAlarmCode = rx[6] + (rx[7] << 8) + (rx[8] << 16) + (rx[9] << 24);
+            result = PASS;
+        }
+    }
+
+    return result;
+}
+
+int Query_Charging_Energy(uint8_t fd, uint8_t targetAddr, Ac_Charging_energy *Ret_Buf)
+{
+    int result = FAIL;
+    uint8_t tx[7] = {0xaa, 0x00, targetAddr, CMD_QUERY_AC_OUTPUT_ENERGY, 0x00, 0x00, 0x00};
+    uint8_t rx[512];
+    uint8_t chksum = 0x00;
+    uint8_t len = tranceiveRelDelayTime(fd, tx, sizeof(tx), rx, 100);
+
+    if (len > 6) {
+        if (len < 6 + (rx[4] | rx[5] << 8)) {
+            return result;
+        }
+
+        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
+            chksum ^= rx[6 + idx];
+        }
+
+        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
+                (rx[2] == tx[1]) &&
+                (rx[1] == tx[2]) &&
+                (rx[3] == tx[3])) {
+            Ret_Buf->Energy = rx[6] + (rx[7] << 8) + (rx[8] << 16) + (rx[9] << 24);
+            result = PASS;
+        }
+    }
+
+    return result;
+}
+
+//------------------------------------------------------------------------------
+//===== Configure =====
+//------------------------------------------------------------------------------
+int Config_Fan_Speed(uint8_t fd, uint8_t targetAddr, FanSpeed *Set_Buf)
+{
+    int result = FAIL;
+    uint8_t tx[15] = {0xaa, 0x00, targetAddr, CMD_CONFIG_FAN_SPEED, 0x08, 0x00, Set_Buf->speed[0] & 0xff, (Set_Buf->speed[0] >> 8) & 0xff, Set_Buf->speed[1] & 0xff, (Set_Buf->speed[1] >> 8) & 0xff, Set_Buf->speed[2] & 0xff, (Set_Buf->speed[2] >> 8) & 0xff, Set_Buf->speed[3] & 0xff, (Set_Buf->speed[3] >> 8) & 0xff, 0x00};
+    uint8_t rx[512];
+    uint8_t chksum = 0x00;
+
+    for (int idx = 0; idx < (tx[4] | tx[5] << 8); idx++) {
+        chksum ^= tx[6 + idx];
+    }
+    tx[14] = chksum;
+
+    uint8_t len = tranceive(fd, tx, sizeof(tx), rx);
+    if (len > 6) {
+        if (len < 6 + (rx[4] | rx[5] << 8)) {
+            return result;
+        }
+
+        chksum = 0x00;
+        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
+            chksum ^= rx[6 + idx];
+        }
+
+        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
+                (rx[2] == tx[1]) &&
+                (rx[1] == tx[2]) &&
+                (rx[3] == tx[3]) &&
+                rx[6] == PASS) {
+            result = PASS;
+        }
+    }
+
+    return result;
+}
+
+int Config_Model_Name(uint8_t fd, uint8_t targetAddr, uint8_t *modelname)
+{
+    int result = FAIL;
+    uint8_t tx[21] = {0xaa, 0x00, targetAddr, CMD_CONFIG_MODEL_NAME, 0x0E, 0x00,
+                      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
+                     };
+    uint8_t rx[512];
+    uint8_t chksum = 0x00;
+
+    memcpy(tx + 6, modelname, 14);
+
+    for (int idx = 0; idx < (tx[4] | tx[5] << 8); idx++) {
+        chksum ^= tx[6 + idx];
+    }
+    tx[20] = chksum;
+
+//  for(int i = 0; i < 21; i++)
+//              printf ("tx = %x \n", tx[i]);
+    uint8_t len = tranceive(fd, tx, sizeof(tx), rx);
+//  for(int i = 0; i < len; i++)
+//                  printf ("rx = %x \n", rx[i]);
+    if (len > 6) {
+        if (len < 6 + (rx[4] | rx[5] << 8)) {
+            return result;
+        }
+
+        chksum = 0x00;
+        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
+            chksum ^= rx[6 + idx];
+        }
+
+        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
+                (rx[2] == tx[1]) &&
+                (rx[1] == tx[2]) &&
+                (rx[3] == tx[3]) &&
+                rx[6] == PASS) {
+            result = PASS;
+        }
+    }
+
+    return result;
+}
+
+int Config_Relay_Output(uint8_t fd, uint8_t targetAddr, Relay *Set_Buf)
+{
+    int result = FAIL;
+    uint8_t tx[10] = {0xaa, 0x00, targetAddr, CMD_CONFIG_RELAY_OUTPUT, 0x03, 0x00, Set_Buf->relay_event.relay_status[0], Set_Buf->relay_event.relay_status[1], Set_Buf->relay_event.relay_status[2]};
+    uint8_t rx[512];
+    uint8_t chksum = 0x00;
+
+    for (int idx = 0; idx < (tx[4] | tx[5] << 8); idx++) {
+        chksum ^= tx[6 + idx];
+    }
+    tx[9] = chksum;
+
+//  for (int i = 0; i < 10; i++)
+//      printf("set relay cmd : tx = %x \n", tx[i]);
+
+    uint8_t len = tranceive(fd, tx, sizeof(tx), rx);
+
+    if (len > 6) {
+        if (len < 6 + (rx[4] | rx[5] << 8)) {
+            return result;
+        }
+
+//      for (int i = 0; i < len; i++)
+//          printf("set relay cmd : rx = %x \n", rx[i]);
+
+        chksum = 0x00;
+        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
+            chksum ^= rx[6 + idx];
+        }
+
+        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
+                (rx[2] == tx[1]) &&
+                (rx[1] == tx[2]) &&
+                (rx[3] == tx[3]) &&
+                rx[6] == PASS) {
+            result = PASS;
+        }
+    }
+
+    return result;
+}
+
+int Config_Gpio_Output(uint8_t fd, uint8_t targetAddr, Gpio_out *Set_Buf)
+{
+    int result = FAIL;
+    uint8_t tx[9] = {0xaa, 0x00, targetAddr, CMD_CONFIG_GPIO_OUTPUT, 0x01, 0x00, 0x00, 0x00};
+    uint8_t rx[512];
+    uint8_t chksum = 0x00;
+
+    tx[6] |= (Set_Buf->AC_Connector ? 0x01 : 0x00);
+
+    for (int idx = 0; idx < 2; idx++) {
+        tx[6] |= (Set_Buf->Button_LED[idx] ? 0x01 : 0x00) << (1 + idx);
+    }
+
+    for (int idx = 0; idx < 4; idx++) {
+        tx[6] |= (Set_Buf->System_LED[idx] ? 0x01 : 0x00) << (3 + idx);
+    }
+
+    for (int idx = 0; idx < (tx[4] | tx[5] << 8); idx++) {
+        chksum ^= tx[6 + idx];
+    }
+    tx[14] = chksum;
+
+    uint8_t len = tranceive(fd, tx, sizeof(tx), rx);
+
+    if (len > 6) {
+        if (len < 6 + (rx[4] | rx[5] << 8)) {
+            return result;
+        }
+
+        chksum = 0x00;
+        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
+            chksum ^= rx[6 + idx];
+        }
+
+        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
+                (rx[2] == tx[1]) &&
+                (rx[1] == tx[2]) &&
+                (rx[3] == tx[3])) {
+            result = PASS;
+        }
+    }
+
+    return result;
+}
+
+int Config_Rtc_Data(uint8_t fd, uint8_t targetAddr, Rtc *Set_Buf)
+{
+    int result = FAIL;
+    uint8_t tx[21] = { 0xaa, 0x00, targetAddr, CMD_CONFIG_RTC_DATA, 0x0E, 0x00, Set_Buf->RtcData[0], Set_Buf->RtcData[1],
+                       Set_Buf->RtcData[2], Set_Buf->RtcData[3], Set_Buf->RtcData[4], Set_Buf->RtcData[5], Set_Buf->RtcData[6], Set_Buf->RtcData[7],
+                       Set_Buf->RtcData[8], Set_Buf->RtcData[9], Set_Buf->RtcData[10], Set_Buf->RtcData[11], Set_Buf->RtcData[12], Set_Buf->RtcData[13]
+                     };
+    uint8_t rx[512];
+    uint8_t chksum = 0x00;
+
+    for (int idx = 0; idx < (tx[4] | tx[5] << 8); idx++) {
+        chksum ^= tx[6 + idx];
+    }
+    tx[20] = chksum;
+
+    if (tranceive(fd, tx, sizeof(tx), rx) > 0) {
+        chksum = 0x00;
+        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
+            chksum ^= rx[6 + idx];
+        }
+
+        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
+                (rx[2] == tx[1]) &&
+                (rx[1] == tx[2]) &&
+                (rx[3] == tx[3]) &&
+                rx[6] == PASS) {
+            result = PASS;
+        }
+    }
+
+    return result;
+}
+
+int Config_LED_Status(uint8_t fd, uint8_t targetAddr, Ac_Led_Status *Ret_Buf)
+{
+    int result = FAIL;
+    uint8_t tx[12] = {0xaa, 0x00, targetAddr, CMD_CONFIG_AC_LED_STATUS, 0x05, 0x00, Ret_Buf->ActionMode, (Ret_Buf->AcAlarmCode >> 0) & 0xFF,
+                      (Ret_Buf->AcAlarmCode >> 8) & 0xFF, (Ret_Buf->AcAlarmCode >> 16) & 0xFF, (Ret_Buf->AcAlarmCode >> 24) & 0xFF
+                     };
+    uint8_t rx[512];
+    uint8_t chksum = 0x00;
+
+    for (int idx = 0; idx < (tx[4] | tx[5] << 8); idx++) {
+        chksum ^= tx[6 + idx];
+    }
+    tx[11] = chksum;
+
+    if (tranceiveRelDelayTime(fd, tx, sizeof(tx), rx, 100) > 0) {
+        chksum = 0x00;
+        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
+            chksum ^= rx[6 + idx];
+        }
+
+        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
+                (rx[2] == tx[1]) &&
+                (rx[1] == tx[2]) &&
+                (rx[3] == tx[3]) &&
+                rx[6] == PASS) {
+            result = PASS;
+        }
+    }
+
+    return result;
+}
+
+int Config_Ac_Duty(uint8_t fd, uint8_t targetAddr, uint8_t _value)
+{
+    int result = FAIL;
+    uint8_t tx[8] = {0xaa, 0x00, targetAddr, CMD_CONFIG_AC_DUTY, 0x01, 0x00, _value};
+    uint8_t rx[512];
+    uint8_t chksum = 0x00;
+
+    for (int idx = 0; idx < (tx[4] | tx[5] << 8); idx++) {
+        chksum ^= tx[6 + idx];
+    }
+    tx[7] = chksum;
+
+    if (tranceiveRelDelayTime(fd, tx, sizeof(tx), rx, 100) > 0) {
+        chksum = 0x00;
+        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
+            chksum ^= rx[6 + idx];
+        }
+
+        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
+                (rx[2] == tx[1]) &&
+                (rx[1] == tx[2]) &&
+                (rx[3] == tx[3]) &&
+                rx[6] == PASS) {
+            result = PASS;
+        }
+    }
+
+    return result;
+}
+
+int Config_Legacy_Req(uint8_t fd, uint8_t targetAddr, uint8_t _switch)
+{
+    int result = FAIL;
+    uint8_t tx[9] = {0xaa, 0x00, targetAddr, CMD_CONFIG_LEGACY_REQ, 0x02, 0x00, _switch, 0x00};
+    uint8_t rx[512];
+    uint8_t chksum = 0x00;
+
+    for (int idx = 0; idx < (tx[4] | tx[5] << 8); idx++) {
+        chksum ^= tx[6 + idx];
+    }
+    tx[8] = chksum;
+
+    if (tranceiveRelDelayTime(fd, tx, sizeof(tx), rx, 100) > 0) {
+        chksum = 0x00;
+        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
+            chksum ^= rx[6 + idx];
+        }
+
+        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
+                (rx[2] == tx[1]) &&
+                (rx[1] == tx[2]) &&
+                (rx[3] == tx[3]) &&
+                rx[6] == PASS) {
+            result = PASS;
+        }
+    }
+
+    return result;
+}
+
+int Config_Reset_MCU(uint8_t fd, uint8_t targetAddr)
+{
+    int result = FAIL;
+    uint8_t tx[9] = {0xaa, 0x00, targetAddr, CMD_CONFIG_RESET_MCU, 0x02, 0x00, 0x01, 0x00};
+    uint8_t rx[512];
+    uint8_t chksum = 0x00;
+
+    for (int idx = 0; idx < (tx[4] | tx[5] << 8); idx++) {
+        chksum ^= tx[6 + idx];
+    }
+    tx[7] = chksum;
+
+    if (tranceiveRelDelayTime(fd, tx, sizeof(tx), rx, 100) > 0) {
+        chksum = 0x00;
+        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
+            chksum ^= rx[6 + idx];
+        }
+
+        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
+                (rx[2] == tx[1]) &&
+                (rx[1] == tx[2]) &&
+                (rx[3] == tx[3]) &&
+                rx[6] == PASS) {
+            result = PASS;
+        }
+    }
+
+    return result;
+}
+
+int Config_Gfd_Value(uint8_t fd, uint8_t targetAddr, Gfd_config *Set_Buf)
+{
+    int result = FAIL;
+    uint8_t tx[9] = {0xaa, 0x00, targetAddr, CMD_CONFIG_GDF_VALUE, 0x02, 0x00, 0x00, 0x00, 0x00};
+    uint8_t rx[512];
+    uint8_t chksum = 0x00;
+
+    tx[6] = Set_Buf->index;
+    tx[7] = Set_Buf->state;
+
+    for (int idx = 0; idx < (tx[4] | tx[5] << 8); idx++) {
+        chksum ^= tx[6 + idx];
+    }
+    tx[8] = chksum;
+
+    uint8_t len = tranceive(fd, tx, sizeof(tx), rx);
+
+    if (len > 6) {
+        if (len < 6 + (rx[4] | rx[5] << 8)) {
+            return result;
+        }
+
+        chksum = 0x00;
+        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
+            chksum ^= rx[6 + idx];
+        }
+
+        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
+                (rx[2] == tx[1]) &&
+                (rx[1] == tx[2]) &&
+                (rx[3] == tx[3])) {
+            result = PASS;
+        }
+    }
+
+    return result;
+}
+
+int Config_CSU_Mode(uint8_t fd, uint8_t targetAddr)
+{
+    int result = FAIL;
+    uint8_t tx[9] = {0xaa, 0x00, targetAddr, CMD_CONFIG_CSU_MODE, 0x02, 0x00, 0x01, 0x00};
+    uint8_t rx[512];
+    uint8_t chksum = 0x00;
+
+    for (int idx = 0; idx < (tx[4] | tx[5] << 8); idx++) {
+        chksum ^= tx[6 + idx];
+    }
+    tx[7] = chksum;
+
+    if (tranceiveRelDelayTime(fd, tx, sizeof(tx), rx, 100) > 0) {
+        chksum = 0x00;
+        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
+            chksum ^= rx[6 + idx];
+        }
+
+        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
+                (rx[2] == tx[1]) &&
+                (rx[1] == tx[2]) &&
+                (rx[3] == tx[3]) &&
+                rx[6] == PASS) {
+            result = PASS;
+        }
+    }
+
+    return result;
+}
+
+int Config_Led_Color(uint8_t fd, uint8_t targetAddr, Led_Color *Ret_Buf)
+{
+    int result = FAIL;
+    uint8_t tx[13] = {0xaa,
+                      0x00,
+                      targetAddr,
+                      CMD_CONFIG_LEN_COLOR,
+                      0x06,
+                      0x00,
+                      Ret_Buf->Connect_1_Red,
+                      Ret_Buf->Connect_1_Green,
+                      Ret_Buf->Connect_1_Blue,
+                      Ret_Buf->Connect_2_Red,
+                      Ret_Buf->Connect_2_Green,
+                      Ret_Buf->Connect_2_Blue
+                     };
+    uint8_t rx[512];
+    uint8_t chksum = 0x00;
+
+    for (int idx = 0; idx < (tx[4] | tx[5] << 8); idx++) {
+        chksum ^= tx[6 + idx];
+    }
+    tx[12] = chksum;
+
+//  for(int i = 0; i < 13; i++)
+//          printf ("tx = %x \n", tx[i]);
+
+    uint8_t len = tranceive(fd, tx, sizeof(tx), rx);
+
+//  for(int i = 0; i < len; i++)
+//      printf ("rx = %x \n", rx[i]);
+
+    if (len > 6) {
+        if (len < 6 + (rx[4] | rx[5] << 8)) {
+            return result;
+        }
+
+        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
+            chksum ^= rx[6 + idx];
+        }
+
+        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
+                (rx[2] == tx[1]) &&
+                (rx[1] == tx[2]) &&
+                (rx[3] == tx[3]) &&
+                (rx[6] == PASS)) {
+            result = PASS;
+        }
+    }
+
+    return result;
+}
+
+//------------------------------------------------------------------------------
+//===== Update =====
+//------------------------------------------------------------------------------
+int Update_Start(uint8_t fd, uint8_t targetAddr, uint32_t crc32)
+{
+    int result = FAIL;
+    uint8_t tx[11] = {0xaa, 0x00, targetAddr, CMD_UPDATE_START, 0x04, 0x00, (crc32 >> 0) & 0xff, (crc32 >> 8) & 0xff, (crc32 >> 16) & 0xff, (crc32 >> 24) & 0xff, 0x00};
+    uint8_t rx[512];
+    uint8_t chksum = 0x00;
+
+    for (int idx = 0; idx < (tx[4] | tx[5] << 8); idx++) {
+        chksum ^= tx[6 + idx];
+    }
+    tx[10] = chksum;
+
+    uint8_t len = tranceive(fd, tx, sizeof(tx), rx);
+    if (len > 6) {
+        if (len < 6 + (rx[4] | rx[5] << 8)) {
+            return result;
+        }
+
+        chksum = 0x00;
+        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
+            chksum ^= rx[6 + idx];
+        }
+
+        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
+                (rx[2] == tx[1]) &&
+                (rx[1] == tx[2]) &&
+                (rx[3] == tx[3]) &&
+                (rx[6] == 0x00)) {
+            result = PASS;
+        }
+    }
+
+    return result;
+}
+
+int Update_Abord(uint8_t fd, uint8_t targetAddr)
+{
+    int result = FAIL;
+    uint8_t tx[7] = {0xaa, 0x00, targetAddr, CMD_UPDATE_ABORT, 0x04, 0x00, 0x00};
+    uint8_t rx[512];
+    uint8_t chksum = 0x00;
+    uint8_t len = tranceive(fd, tx, sizeof(tx), rx);
+
+    if (len > 6) {
+        if (len < 6 + (rx[4] | rx[5] << 8)) {
+            return result;
+        }
+
+        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
+            chksum ^= rx[6 + idx];
+        }
+
+        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
+                (rx[2] == tx[1]) &&
+                (rx[1] == tx[2]) &&
+                (rx[3] == tx[3]) &&
+                (rx[6] == 0x00)) {
+            result = PASS;
+        }
+    }
+
+    return result;
+}
+
+int Update_Transfer(uint8_t fd, uint8_t targetAddr, uint32_t startAddr, uint8_t *data, uint16_t length)
+{
+    int result = FAIL;
+    uint8_t tx[11 + length];
+    uint8_t rx[512];
+    uint8_t chksum = 0x00;
+
+    tx[0] = 0xaa;
+    tx[1] = 0x00;
+    tx[2] = targetAddr;
+    tx[3] = CMD_UPDATE_TRANSFER;
+    tx[4] = (4 + length) & 0xff;
+    tx[5] = ((4 + length) >> 8) & 0xff;
+    tx[6] = (startAddr >> 0) & 0xff;
+    tx[7] = (startAddr >> 8) & 0xff;
+    tx[8] = (startAddr >> 16) & 0xff;
+    tx[9] = (startAddr >> 24) & 0xff;
+    memcpy(tx + 10, data, length);
+
+    for (int idx = 0; idx < (tx[4] | tx[5] << 8); idx++) {
+        chksum ^= tx[6 + idx];
+    }
+    tx[sizeof(tx) - 1] = chksum;
+
+    uint8_t len = tranceive(fd, tx, sizeof(tx), rx);
+
+    if (len > 6) {
+        if (len < 6 + (rx[4] | rx[5] << 8)) {
+            return result;
+        }
+
+        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
+            chksum ^= rx[6 + idx];
+        }
+
+        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
+                (rx[2] == tx[1]) &&
+                (rx[1] == tx[2]) &&
+                (rx[3] == tx[3]) &&
+                (rx[6] == 0x00)) {
+            result = PASS;
+        }
+    }
+
+    return result;
+}
+
+int Update_Finish(uint8_t fd, uint8_t targetAddr)
+{
+    int result = FAIL;
+    uint8_t tx[7] = {0xaa, 0x00, targetAddr, CMD_UPDATE_FINISH, 0x04, 0x00, 0x00};
+    uint8_t rx[512];
+    uint8_t chksum = 0x00;
+    uint8_t len = tranceive(fd, tx, sizeof(tx), rx);
+
+    if (len > 6) {
+        if (len < 6 + (rx[4] | rx[5] << 8)) {
+            return result;
+        }
+
+        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++) {
+            chksum ^= rx[6 + idx];
+        }
+
+        if ((chksum == rx[6 + (rx[4] | rx[5] << 8)]) &&
+                (rx[2] == tx[1]) &&
+                (rx[1] == tx[2]) &&
+                (rx[3] == tx[3]) &&
+                (rx[6] == 0x00)) {
+            result = PASS;
+        }
+    }
+
+    return result;
+}

+ 251 - 251
EVSE/Projects/DD360Tcci/Apps/ModuleInternalComm/internalComm.h

@@ -1,251 +1,251 @@
-/*
- * internalComm.h
- *
- *  Created on: 2019年5月7日
- *      Author: foluswen
- */
-
-#ifndef _INTERNAL_COMM_H_
-#define _INTERNAL_COMM_H_
-
-//------------------------------------------------------------------------------
-#include <stdint.h>
-
-//------------------------------------------------------------------------------
-//address
-#define ADDR_AUX                                (0x01)
-#define ADDR_FAN                                (0x02)
-#if defined DD360Tcci || defined DD360Audi || defined DD360ComBox || defined DD360UCar
-#define ADDR_RELAY                              (0x09)
-#else
-#define ADDR_RELAY                              (0x03)
-#endif //defined DD360Tcci || defined DD360Audi || defined DD360ComBox
-#define ADDR_AC_PLUG                            (0x05)
-#define ADDR_LED                                (0x06)
-#define ADDR_BROADCAST                          (0xFF)
-
-//command
-#define CMD_QUERY_FW_VER                        (0x01)
-#define CMD_QUERY_HW_VER                        (0x02)
-#define CMD_QUERY_PRESENT_IN_VOL                (0x03)
-#define CMD_QUERY_PRESENT_OUT_VOL               (0x04)
-#define CMD_QUERY_FAN_SPEED                     (0x05)
-#define CMD_QUERY_TEMPERATURE                   (0x06)
-#define CMD_QUERY_AUX_POWER_VOL                 (0x07)
-#define CMD_QUERY_RELAY_OUTPUT                  (0x08)
-#define CMD_QUERY_GFD_ADC                       (0x09)
-#define CMD_QUERY_GPIO_IN                       (0x0a)
-#define CMD_QUERY_MODEL_NAME                    (0x24)
-#define CMD_QUERY_AC_OUTPUT_CURRENT             (0x27)
-#define CMD_QUERY_AC_STATUS                     (0x28)
-#define CMD_QUERY_AC_ALARM_CODE                 (0x29)
-#define CMD_QUERY_AC_OUTPUT_ENERGY              (0x2C)
-
-#define CMD_CONFIG_FAN_SPEED                    (0x81)
-#define CMD_CONFIG_MODEL_NAME                   (0x83)
-#define CMD_CONFIG_RELAY_OUTPUT                 (0x85)
-#define CMD_CONFIG_GPIO_OUTPUT                  (0x86)
-#define CMD_CONFIG_RTC_DATA                     (0x87)
-#define CMD_CONFIG_AC_LED_STATUS                (0x88)
-#define CMD_CONFIG_AC_DUTY                      (0x89)
-#define CMD_CONFIG_LEGACY_REQ                   (0x8A)
-#define CMD_CONFIG_GDF_VALUE                    (0x8B)
-#define CMD_CONFIG_RESET_MCU                    (0x8C)
-#define CMD_CONFIG_CSU_MODE                     (0x90)
-#define CMD_CONFIG_LEN_COLOR                    (0x93)
-
-#define CMD_UPDATE_START                        (0xe0)
-#define CMD_UPDATE_ABORT                        (0xe1)
-#define CMD_UPDATE_TRANSFER                     (0xe2)
-#define CMD_UPDATE_FINISH                       (0xe3)
-
-//------------------------------------------------------------------------------
-typedef struct Verion {
-    char Version_FW[9];
-    char Version_HW[9];
-} Ver;
-
-typedef struct PRESENTINPUTVOLTAGE {
-    uint8_t inputType;    // 0x00: Line to Line       0x01: Line to Neutral
-    double L1N_L12;
-    double L2N_L23;
-    double L3N_L31;
-} PresentInputVoltage;
-
-typedef struct PRESENTOUTPUTVOLTAGE {
-    double behindFuse_Voltage_C1;
-    double behindRelay_Voltage_C1;
-    double behindFuse_Voltage_C2;
-    double behindRelay_Voltage_C2;
-} PresentOutputVoltage;
-
-typedef struct FANSPEED {
-    uint16_t speed[8];
-} FanSpeed;
-
-typedef struct TEMPERATURE {
-    uint8_t temperature[8];
-} Temperature;
-
-typedef struct AUXPOWER {
-    uint8_t voltage[8];
-} AuxPower;
-
-typedef struct RELAY {
-    union {
-        uint8_t relay_status[8];
-        struct {
-            uint8_t AC_Contactor : 1;     //bit 0
-            uint8_t CCS_Precharge : 1; //bit 1
-            uint8_t : 1;              //bit 2 reserved
-            uint8_t : 1;                  //bit 3 reserved
-            uint8_t : 1;                  //bit 4 reserved
-            uint8_t : 1;                  //bit 5 reserved
-            uint8_t : 1;                  //bit 6 reserved
-            uint8_t : 1;                  //bit 7 reserved
-
-            uint8_t Gun1_N : 1;           //bit 0
-            uint8_t Gun1_P : 1;           //bit 1
-            uint8_t Gun1_Parallel_N : 1; //bit 2
-            uint8_t Gun1_Parallel_P : 1;  //bit 3
-            uint8_t : 1;                  //bit 4 reserved
-            uint8_t : 1;                  //bit 5 reserved
-            uint8_t : 1;                  //bit 6 reserved
-            uint8_t : 1;                  //bit 7 reserved
-
-            uint8_t Gun2_N : 1;           //bit 0
-            uint8_t Gun2_P : 1;           //bit 1
-            uint8_t : 1;                  //bit 2 reserved
-            uint8_t : 1;                  //bit 3 reserved
-            uint8_t : 1;                  //bit 4 reserved
-            uint8_t : 1;                  //bit 5 reserved
-            uint8_t : 1;                  //bit 6 reserved
-            uint8_t : 1;                  //bit 7 reserved
-        } bits;
-    } relay_event;
-} Relay;
-
-typedef struct GFD {
-    unsigned short Resister_conn1;
-    unsigned short voltage_conn1;
-    uint8_t result_conn1;
-    uint8_t rb_step_1;
-
-    unsigned short Resister_conn2;
-    unsigned short voltage_conn2;
-    uint8_t result_conn2;
-    uint8_t rb_step_2;
-} Gfd;
-
-typedef struct Gfd_CONFIG {
-    uint8_t index;
-    uint8_t state;
-} Gfd_config;
-
-typedef struct GPIO_IN {
-    uint8_t AC_Connector;         // bit 0
-    uint8_t AC_MainBreaker;           // bit 1
-    uint8_t SPD;                      // bit 2
-    uint8_t Door_Open;                // bit 3
-    uint8_t GFD[2];                   // bit 4,5
-    uint8_t AC_Drop;                  // bit 6
-
-    uint8_t Emergency_IO;         // bit 0
-
-    uint8_t Button_Emergency_Press;   // bit 0
-    uint8_t Button_On_Press;          // bit 1
-    uint8_t Button_Off_Press;     // bit 2
-    uint8_t Key_1_Press;              // bit 3
-    uint8_t Key_2_Press;              // bit 4
-    uint8_t Key_3_Press;              // bit 5
-    uint8_t Key_4_Press;              // bit 6
-} Gpio_in;
-
-typedef struct GPIO_OUT {
-    uint8_t AC_Connector;
-    uint8_t Button_LED[2];
-    uint8_t System_LED[4];
-} Gpio_out;
-
-typedef struct RTC {
-    uint8_t RtcData[14];
-} Rtc;
-
-typedef struct LED_Color {
-    uint8_t Connect_1_Red;
-    uint8_t Connect_1_Green;
-    uint8_t Connect_1_Blue;
-    uint8_t Connect_2_Red;
-    uint8_t Connect_2_Green;
-    uint8_t Connect_2_Blue;
-} Led_Color;
-
-typedef struct AC_Status {
-    uint8_t       CpStatus;
-    unsigned short      CurLimit;
-    short               PilotVol_P;
-    short               PilotVol_N;
-    uint8_t       LockStatus;
-    uint8_t       RelayStatus;
-    uint8_t       ShutterStatus;
-    uint8_t       MeterStatus;
-    uint8_t       PpStatus;
-    uint8_t       MaxCurrent;
-    uint8_t       RotateSwitchStatus;
-} Ac_Status;
-
-typedef struct AC_LED_Status {
-    uint8_t       ActionMode;
-    unsigned long       AcAlarmCode;
-} Ac_Led_Status;
-
-typedef struct AC_Alarm_Code {
-    uint32_t        AcAlarmCode;
-} Ac_Alarm_code;
-
-typedef struct AC_Charging_Energy {
-    uint32_t        Energy;
-} Ac_Charging_energy;
-
-typedef struct AC_Charging_Current {
-    unsigned short      OuputCurrentL1;
-    unsigned short      OuputCurrentL2;
-    unsigned short      OuputCurrentL3;
-} Ac_Charging_current;
-
-int Query_FW_Ver(uint8_t fd, uint8_t targetAddr, Ver *Ret_Buf);
-int Query_HW_Ver(uint8_t fd, uint8_t targetAddr, Ver *Ret_Buf);
-int Query_Present_InputVoltage(uint8_t fd, uint8_t targetAddr, PresentInputVoltage *Ret_Buf);
-int Query_Present_OutputVoltage(uint8_t fd, uint8_t targetAddr, PresentOutputVoltage *Ret_Buf);
-int Query_Fan_Speed(uint8_t fd, uint8_t targetAddr, FanSpeed *Ret_Buf);
-int Query_Temperature(uint8_t fd, uint8_t targetAddr, Temperature *Ret_Buf);
-int Query_Aux_PowerVoltage(uint8_t fd, uint8_t targetAddr, AuxPower *Ret_Buf);
-int Query_Relay_Output(uint8_t fd, uint8_t targetAddr, Relay *Ret_Buf);
-int Query_Gfd_Adc(uint8_t fd, uint8_t targetAddr, Gfd *Ret_Buf);
-int Query_Gpio_Input(uint8_t fd, uint8_t targetAddr, Gpio_in *Ret_Buf);
-int Query_Model_Name(uint8_t fd, uint8_t targetAddr, uint8_t *modelname);
-int Query_AC_Status(uint8_t fd, uint8_t targetAddr, Ac_Status *Ret_Buf);
-int Query_AC_Alarm_Code(uint8_t fd, uint8_t targetAddr, Ac_Alarm_code *Ret_Buf);
-int Query_Charging_Energy(uint8_t fd, uint8_t targetAddr, Ac_Charging_energy *Ret_Buf);
-int Query_Charging_Current(uint8_t fd, uint8_t targetAddr, Ac_Charging_current *Ret_Buf);
-
-int Config_Fan_Speed(uint8_t fd, uint8_t targetAddr, FanSpeed *Set_Buf);
-int Config_Relay_Output(uint8_t fd, uint8_t targetAddr, Relay *Set_Buf);
-int Config_Gpio_Output(uint8_t fd, uint8_t targetAddr, Gpio_out *Set_Buf);
-int Config_Gfd_Value(uint8_t fd, uint8_t targetAddr, Gfd_config *Set_Buf);
-int Config_Model_Name(uint8_t fd, uint8_t targetAddr, uint8_t *modelname);
-int Config_Rtc_Data(uint8_t fd, uint8_t targetAddr, Rtc *Set_Buf);
-
-int Config_LED_Status(uint8_t fd, uint8_t targetAddr, Ac_Led_Status *Ret_Buf);
-int Config_Legacy_Req(uint8_t fd, uint8_t targetAddr, uint8_t _switch);
-int Config_Ac_Duty(uint8_t fd, uint8_t targetAddr, uint8_t _value);
-int Config_CSU_Mode(uint8_t fd, uint8_t targetAddr);
-int Config_Reset_MCU(uint8_t fd, uint8_t targetAddr);
-int Config_Led_Color(uint8_t fd, uint8_t targetAddr, Led_Color *Ret_Buf);
-
-int Update_Start(uint8_t fd, uint8_t targetAddr, uint32_t crc32);
-int Update_Abord(uint8_t fd, uint8_t targetAddr);
-int Update_Transfer(uint8_t fd, uint8_t targetAddr, uint32_t startAddr, uint8_t *data, uint16_t length);
-int Update_Finish(uint8_t fd, uint8_t targetAddr);
-
-#endif /* _INTERNAL_COMM_H_ */
+/*
+ * internalComm.h
+ *
+ *  Created on: 2019年5月7日
+ *      Author: foluswen
+ */
+
+#ifndef _INTERNAL_COMM_H_
+#define _INTERNAL_COMM_H_
+
+//------------------------------------------------------------------------------
+#include <stdint.h>
+
+//------------------------------------------------------------------------------
+//address
+#define ADDR_AUX                                (0x01)
+#define ADDR_FAN                                (0x02)
+#if defined DD360Tcci || defined DD360Audi || defined DD360ComBox || defined DD360UCar
+#define ADDR_RELAY                              (0x09)
+#else
+#define ADDR_RELAY                              (0x03)
+#endif //defined DD360Tcci || defined DD360Audi || defined DD360ComBox
+#define ADDR_AC_PLUG                            (0x05)
+#define ADDR_LED                                (0x06)
+#define ADDR_BROADCAST                          (0xFF)
+
+//command
+#define CMD_QUERY_FW_VER                        (0x01)
+#define CMD_QUERY_HW_VER                        (0x02)
+#define CMD_QUERY_PRESENT_IN_VOL                (0x03)
+#define CMD_QUERY_PRESENT_OUT_VOL               (0x04)
+#define CMD_QUERY_FAN_SPEED                     (0x05)
+#define CMD_QUERY_TEMPERATURE                   (0x06)
+#define CMD_QUERY_AUX_POWER_VOL                 (0x07)
+#define CMD_QUERY_RELAY_OUTPUT                  (0x08)
+#define CMD_QUERY_GFD_ADC                       (0x09)
+#define CMD_QUERY_GPIO_IN                       (0x0a)
+#define CMD_QUERY_MODEL_NAME                    (0x24)
+#define CMD_QUERY_AC_OUTPUT_CURRENT             (0x27)
+#define CMD_QUERY_AC_STATUS                     (0x28)
+#define CMD_QUERY_AC_ALARM_CODE                 (0x29)
+#define CMD_QUERY_AC_OUTPUT_ENERGY              (0x2C)
+
+#define CMD_CONFIG_FAN_SPEED                    (0x81)
+#define CMD_CONFIG_MODEL_NAME                   (0x83)
+#define CMD_CONFIG_RELAY_OUTPUT                 (0x85)
+#define CMD_CONFIG_GPIO_OUTPUT                  (0x86)
+#define CMD_CONFIG_RTC_DATA                     (0x87)
+#define CMD_CONFIG_AC_LED_STATUS                (0x88)
+#define CMD_CONFIG_AC_DUTY                      (0x89)
+#define CMD_CONFIG_LEGACY_REQ                   (0x8A)
+#define CMD_CONFIG_GDF_VALUE                    (0x8B)
+#define CMD_CONFIG_RESET_MCU                    (0x8C)
+#define CMD_CONFIG_CSU_MODE                     (0x90)
+#define CMD_CONFIG_LEN_COLOR                    (0x93)
+
+#define CMD_UPDATE_START                        (0xe0)
+#define CMD_UPDATE_ABORT                        (0xe1)
+#define CMD_UPDATE_TRANSFER                     (0xe2)
+#define CMD_UPDATE_FINISH                       (0xe3)
+
+//------------------------------------------------------------------------------
+typedef struct Verion {
+    char Version_FW[9];
+    char Version_HW[9];
+} Ver;
+
+typedef struct PRESENTINPUTVOLTAGE {
+    uint8_t inputType;    // 0x00: Line to Line       0x01: Line to Neutral
+    double L1N_L12;
+    double L2N_L23;
+    double L3N_L31;
+} PresentInputVoltage;
+
+typedef struct PRESENTOUTPUTVOLTAGE {
+    double behindFuse_Voltage_C1;
+    double behindRelay_Voltage_C1;
+    double behindFuse_Voltage_C2;
+    double behindRelay_Voltage_C2;
+} PresentOutputVoltage;
+
+typedef struct FANSPEED {
+    uint16_t speed[8];
+} FanSpeed;
+
+typedef struct TEMPERATURE {
+    uint8_t temperature[8];
+} Temperature;
+
+typedef struct AUXPOWER {
+    uint8_t voltage[8];
+} AuxPower;
+
+typedef struct RELAY {
+    union {
+        uint8_t relay_status[8];
+        struct {
+            uint8_t AC_Contactor : 1;     //bit 0
+            uint8_t CCS_Precharge : 1; //bit 1
+            uint8_t : 1;              //bit 2 reserved
+            uint8_t : 1;                  //bit 3 reserved
+            uint8_t : 1;                  //bit 4 reserved
+            uint8_t : 1;                  //bit 5 reserved
+            uint8_t : 1;                  //bit 6 reserved
+            uint8_t : 1;                  //bit 7 reserved
+
+            uint8_t Gun1_N : 1;           //bit 0
+            uint8_t Gun1_P : 1;           //bit 1
+            uint8_t Gun1_Parallel_N : 1; //bit 2
+            uint8_t Gun1_Parallel_P : 1;  //bit 3
+            uint8_t : 1;                  //bit 4 reserved
+            uint8_t : 1;                  //bit 5 reserved
+            uint8_t : 1;                  //bit 6 reserved
+            uint8_t : 1;                  //bit 7 reserved
+
+            uint8_t Gun2_N : 1;           //bit 0
+            uint8_t Gun2_P : 1;           //bit 1
+            uint8_t : 1;                  //bit 2 reserved
+            uint8_t : 1;                  //bit 3 reserved
+            uint8_t : 1;                  //bit 4 reserved
+            uint8_t : 1;                  //bit 5 reserved
+            uint8_t : 1;                  //bit 6 reserved
+            uint8_t : 1;                  //bit 7 reserved
+        } bits;
+    } relay_event;
+} Relay;
+
+typedef struct GFD {
+    unsigned short Resister_conn1;
+    unsigned short voltage_conn1;
+    uint8_t result_conn1;
+    uint8_t rb_step_1;
+
+    unsigned short Resister_conn2;
+    unsigned short voltage_conn2;
+    uint8_t result_conn2;
+    uint8_t rb_step_2;
+} Gfd;
+
+typedef struct Gfd_CONFIG {
+    uint8_t index;
+    uint8_t state;
+} Gfd_config;
+
+typedef struct GPIO_IN {
+    uint8_t AC_Connector;         // bit 0
+    uint8_t AC_MainBreaker;           // bit 1
+    uint8_t SPD;                      // bit 2
+    uint8_t Door_Open;                // bit 3
+    uint8_t GFD[2];                   // bit 4,5
+    uint8_t AC_Drop;                  // bit 6
+
+    uint8_t Emergency_IO;         // bit 0
+
+    uint8_t Button_Emergency_Press;   // bit 0
+    uint8_t Button_On_Press;          // bit 1
+    uint8_t Button_Off_Press;     // bit 2
+    uint8_t Key_1_Press;              // bit 3
+    uint8_t Key_2_Press;              // bit 4
+    uint8_t Key_3_Press;              // bit 5
+    uint8_t Key_4_Press;              // bit 6
+} Gpio_in;
+
+typedef struct GPIO_OUT {
+    uint8_t AC_Connector;
+    uint8_t Button_LED[2];
+    uint8_t System_LED[4];
+} Gpio_out;
+
+typedef struct RTC {
+    uint8_t RtcData[14];
+} Rtc;
+
+typedef struct LED_Color {
+    uint8_t Connect_1_Red;
+    uint8_t Connect_1_Green;
+    uint8_t Connect_1_Blue;
+    uint8_t Connect_2_Red;
+    uint8_t Connect_2_Green;
+    uint8_t Connect_2_Blue;
+} Led_Color;
+
+typedef struct AC_Status {
+    uint8_t       CpStatus;
+    unsigned short      CurLimit;
+    short               PilotVol_P;
+    short               PilotVol_N;
+    uint8_t       LockStatus;
+    uint8_t       RelayStatus;
+    uint8_t       ShutterStatus;
+    uint8_t       MeterStatus;
+    uint8_t       PpStatus;
+    uint8_t       MaxCurrent;
+    uint8_t       RotateSwitchStatus;
+} Ac_Status;
+
+typedef struct AC_LED_Status {
+    uint8_t       ActionMode;
+    unsigned long       AcAlarmCode;
+} Ac_Led_Status;
+
+typedef struct AC_Alarm_Code {
+    uint32_t        AcAlarmCode;
+} Ac_Alarm_code;
+
+typedef struct AC_Charging_Energy {
+    uint32_t        Energy;
+} Ac_Charging_energy;
+
+typedef struct AC_Charging_Current {
+    unsigned short      OuputCurrentL1;
+    unsigned short      OuputCurrentL2;
+    unsigned short      OuputCurrentL3;
+} Ac_Charging_current;
+
+int Query_FW_Ver(uint8_t fd, uint8_t targetAddr, Ver *Ret_Buf);
+int Query_HW_Ver(uint8_t fd, uint8_t targetAddr, Ver *Ret_Buf);
+int Query_Present_InputVoltage(uint8_t fd, uint8_t targetAddr, PresentInputVoltage *Ret_Buf);
+int Query_Present_OutputVoltage(uint8_t fd, uint8_t targetAddr, PresentOutputVoltage *Ret_Buf);
+int Query_Fan_Speed(uint8_t fd, uint8_t targetAddr, FanSpeed *Ret_Buf);
+int Query_Temperature(uint8_t fd, uint8_t targetAddr, Temperature *Ret_Buf);
+int Query_Aux_PowerVoltage(uint8_t fd, uint8_t targetAddr, AuxPower *Ret_Buf);
+int Query_Relay_Output(uint8_t fd, uint8_t targetAddr, Relay *Ret_Buf);
+int Query_Gfd_Adc(uint8_t fd, uint8_t targetAddr, Gfd *Ret_Buf);
+int Query_Gpio_Input(uint8_t fd, uint8_t targetAddr, Gpio_in *Ret_Buf);
+int Query_Model_Name(uint8_t fd, uint8_t targetAddr, uint8_t *modelname);
+int Query_AC_Status(uint8_t fd, uint8_t targetAddr, Ac_Status *Ret_Buf);
+int Query_AC_Alarm_Code(uint8_t fd, uint8_t targetAddr, Ac_Alarm_code *Ret_Buf);
+int Query_Charging_Energy(uint8_t fd, uint8_t targetAddr, Ac_Charging_energy *Ret_Buf);
+int Query_Charging_Current(uint8_t fd, uint8_t targetAddr, Ac_Charging_current *Ret_Buf);
+
+int Config_Fan_Speed(uint8_t fd, uint8_t targetAddr, FanSpeed *Set_Buf);
+int Config_Relay_Output(uint8_t fd, uint8_t targetAddr, Relay *Set_Buf);
+int Config_Gpio_Output(uint8_t fd, uint8_t targetAddr, Gpio_out *Set_Buf);
+int Config_Gfd_Value(uint8_t fd, uint8_t targetAddr, Gfd_config *Set_Buf);
+int Config_Model_Name(uint8_t fd, uint8_t targetAddr, uint8_t *modelname);
+int Config_Rtc_Data(uint8_t fd, uint8_t targetAddr, Rtc *Set_Buf);
+
+int Config_LED_Status(uint8_t fd, uint8_t targetAddr, Ac_Led_Status *Ret_Buf);
+int Config_Legacy_Req(uint8_t fd, uint8_t targetAddr, uint8_t _switch);
+int Config_Ac_Duty(uint8_t fd, uint8_t targetAddr, uint8_t _value);
+int Config_CSU_Mode(uint8_t fd, uint8_t targetAddr);
+int Config_Reset_MCU(uint8_t fd, uint8_t targetAddr);
+int Config_Led_Color(uint8_t fd, uint8_t targetAddr, Led_Color *Ret_Buf);
+
+int Update_Start(uint8_t fd, uint8_t targetAddr, uint32_t crc32);
+int Update_Abord(uint8_t fd, uint8_t targetAddr);
+int Update_Transfer(uint8_t fd, uint8_t targetAddr, uint32_t startAddr, uint8_t *data, uint16_t length);
+int Update_Finish(uint8_t fd, uint8_t targetAddr);
+
+#endif /* _INTERNAL_COMM_H_ */

+ 2061 - 2056
EVSE/Projects/DD360Tcci/Apps/ModuleLcmCtrl/Module_LcmControl.c

@@ -1,2056 +1,2061 @@
-#include <stdio.h>      /*標準輸入輸出定義*/
-#include <stdlib.h>     /*標準函數庫定義*/
-#include <stdint.h>
-#include <string.h>
-#include <unistd.h>
-#include <termios.h>
-#include <fcntl.h>
-#include <time.h>
-
-#include <sys/ioctl.h>
-#include <sys/timeb.h>
-
-#include "Module_LcmControl.h"
-#include "../Log/log.h"
-#include "../ShareMemory/shmMem.h"
-#include "../Define/define.h"
-#include "../Config.h"
-#include "../SelectGun/SelectGun.h"
-#include "../CSU/main.h"
-#include "../timeout.h"
-
-#define uSEC_VAL                                (1000000)
-
-//------------------------------------------------------------------------------
-//struct SysConfigAndInfo         *ShmSysConfigAndInfo;
-//struct StatusCodeData           *ShmStatusCodeData;
-static struct SysConfigData *pSysConfig = NULL;
-static struct SysInfoData *pSysInfo = NULL;
-static struct WARNING_CODE_INFO *pSysWarning = NULL;
-static struct OCPP16Data *ShmOCPP16Data = NULL;
-static struct FanModuleData *ShmFanModuleData;
-static struct PrimaryMcuData *ShmPrimaryMcuData;
-static SelectGunInfo *ShmSelectGunInfo = NULL;
-static struct ChargingInfoData *pDcChargingInfo = NULL;
-static DcCommonInfo *ShmDcCommonData            = NULL;
-//int CardReadFd = -1;
-
-short _currentPage              = _PAGE_NONE;
-uint8_t _totalCount;
-uint8_t _showInformIndex = 0;
-float ChargeMaxPower_0 = 0;
-float ChargeMaxPower_1 = 0;
-bool _battery_display_ani = false;
-int _port;
-//char* pPortName         = "/dev/ttyO2";
-char *pPortName           = "/dev/ttyS3";
-char *moduleName          = "DMT80480T070_09WT";
-bool is_show = false;
-bool is_stop = false;
-uint8_t _everyPageRollChange;
-uint8_t _btn_press = 0;
-short _btn_press_id = 0;
-uint8_t _btn_press_count = 0;
-int _Text_Running_Count = 1;
-int Battery_Test = 0;
-extern void UpdateLcmFunction(DcCommonInfo *ShmDcCommonData,int _lcmport);
-//==========================================
-// Open and Close RS232 and R/W
-//==========================================
-void AuthorizingStart(void)
-{
-    ShmOCPP16Data->SpMsg.bits.AuthorizeReq = YES;
-    pSysInfo->AuthorizeFlag = YES;
-}
-void GetClockTime(struct timespec *_now_time, void *null)
-{
-    clock_gettime(CLOCK_MONOTONIC, _now_time);
-}
-void StartSystemTimeoutDet(uint8_t flag)
-{
-    if (pSysInfo->SystemTimeoutFlag != flag) {
-        GetClockTime(&pSysInfo->SystemTimeoutTimer, NULL);
-    }
-    pSysInfo->SystemTimeoutFlag = flag;
-}
-
-void StopSystemTimeoutDet(void)
-{
-    GetClockTime(&pSysInfo->SystemTimeoutTimer, NULL);
-    pSysInfo->SystemTimeoutFlag = Timeout_None;
-}
-
-void StartGunInfoTimeoutDet(uint8_t gunIndex, uint8_t flag)
-{
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-
-    if (gunIndex < pSysConfig->TotalConnectorCount) {
-        if (pDcChargingInfo->TimeoutFlag != flag) {
-            GetClockTime(&pDcChargingInfo->ConnectorTimeout, NULL);
-        }
-        pDcChargingInfo->TimeoutFlag = flag;
-    }
-}
-
-void StopGunInfoTimeoutDet(uint8_t gunIndex)
-{
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-
-    if (gunIndex < pSysConfig->TotalConnectorCount) {
-        pDcChargingInfo->TimeoutFlag = Timeout_None;
-    }
-}
-unsigned long GetClockTimeoutValue(struct timespec _start_time)
-{
-    struct timespec ts_end;
-    unsigned long ret = 0;
-
-    clock_gettime(CLOCK_MONOTONIC, &ts_end);
-
-    ret = ((unsigned long)(ts_end.tv_sec - _start_time.tv_sec) * 1000000) + ((unsigned long)((ts_end.tv_nsec / 1000) - (_start_time.tv_nsec/ 1000)));
-
-    return ret;
-}
-int CreateCommunicationLcmPort()
-{
-    int fd;
-    struct termios tios;
-
-    fd = open(pPortName, O_RDWR);
-    if (fd <= 0) {
-        log_error("open /dev/ttyS3 NG ");
-        return -1;
-    }
-    ioctl(fd, TCGETS, &tios);
-    tios.c_cflag = B115200 | CS8 | CLOCAL | CREAD;
-    tios.c_lflag = 0;
-    tios.c_iflag = 0;
-    tios.c_oflag = 0;
-    tios.c_cc[VMIN] = 0;
-    tios.c_cc[VTIME] = (uint8_t) 5;
-    tios.c_lflag = 0;
-    tcflush(fd, TCIFLUSH);
-    ioctl(fd, TCSETS, &tios);
-
-    return fd;
-}
-bool isChargingEnd(gunIndex)
-{
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-    if (pDcChargingInfo->SystemStatus == S_COMPLETE || pDcChargingInfo->SystemStatus == S_ALARM) {
-        return TRUE;
-    } else {
-        return FALSE;
-    }
-}
-void CloseCommunicationLcmPort()
-{
-    close(_port);
-}
-
-void setSelGunWaitToAuthor(uint8_t curSel)
-{
-    if (curSel == LEFT_GUN_NUM && ShmSelectGunInfo->SelGunInfo.LeftGun == SEL_GUN_CONFIRM) {
-        ShmSelectGunInfo->SelGunInfo.LeftGun = SEL_GUN_ATHOR;
-        log_info("setSelGunWaitToAuthor left");
-
-    } else if (curSel == RIGHT_GUN_NUM && ShmSelectGunInfo->SelGunInfo.RightGun == SEL_GUN_CONFIRM) {
-        ShmSelectGunInfo->SelGunInfo.RightGun = SEL_GUN_ATHOR;
-        log_info("setSelGunWaitToAuthor right");
-
-    }
-}
-void confirmSelGun(uint8_t selGun)
-{
-    if (selGun == LEFT_GUN_NUM) {
-        ShmSelectGunInfo->SelGunInfo.LeftGun = SEL_GUN_CONFIRM;
-        //printf("confirmSelGun left");
-    } else if (selGun == RIGHT_GUN_NUM) {
-        ShmSelectGunInfo->SelGunInfo.RightGun = SEL_GUN_CONFIRM;
-        //printf("confirmSelGun right");
-    }
-    //changeLcmPage(_PAGE_PLUGIN);
-
-    //StartGunInfoTimeoutDet(selGun, Timeout_SelectGun);
-    //StartSystemTimeoutDet(Timeout_ReturnViewPage);
-}
-
-void WriteCmdToLcm(uint8_t *cmd, uint8_t cmdLen)
-{
-    int len = write(_port, cmd, cmdLen);
-    if (len < sizeof(cmd)) {
-        log_error("Write cmd to LCM Failure. ");
-    }
-}
-void ReadMsgFromLcm(uint8_t* msg, uint8_t readLen)
-{
-    read(_port, msg, readLen);
-
-    //  5a : CMD_TITLE_1
-    //  a5 : CMD_TITLE_2
-    //  5
-    //  81 : CMD_WRITE
-    //  3  : CMD_REGISTER
-    //  2  : Data length
-    //  0  : High byte
-    //  1  : Low byte
-
-    //  printf("-------------------------------------------- \n");
-    //  printf("msg = %x \n", *msg);            // A5
-    //  printf("msg = %x \n", *(msg + 1));      // 5A
-    //  printf("msg = %x \n", *(msg + 2));      // Len : [3] ~ [6] + Data Len
-    //  printf("msg = %x \n", *(msg + 3));      // cmd : 0x83
-    //  printf("msg = %x \n", *(msg + 4));      // addr : H
-    //  printf("msg = %x \n", *(msg + 5));      // addr : L
-    //  printf("msg = %x \n", *(msg + 6));      // Data Len
-    //
-    //  printf("msg = %x \n", *(msg + 7));
-    //  printf("msg = %x \n", *(msg + 8));
-    //  printf("msg = %x \n", *(msg + 9));
-    //  printf("msg = %x \n", *(msg + 10));
-    //  printf("msg = %x \n", *(msg + 11));
-    //  printf("msg = %x \n", *(msg + 12));
-    //  printf("msg = %x \n", *(msg + 13));
-    //  printf("msg = %x \n", *(msg + 14));
-        /*
-        for(uint8_t i = 0 ; i<readLen+3; i++) {
-            log_info("Read data[%d]:0x%x",i,msg[i]);
-        }*/
-
-    if (*msg == CMD_TITLE_1 && *(msg + 1) == CMD_TITLE_2)
-    {
-        if (*(msg + 3) == CMD_WRITE)
-        {
-            switch (*(msg + 4))
-            {
-            case CMD_REGISTER:
-            {
-                // 頁面
-                if (strcmp((char*)pSysInfo->LcmHwRev, "") != EQUAL)
-                    strcpy((char*)pSysInfo->LcmHwRev, moduleName);
-
-                _currentPage = *(msg + 7);
-                log_info("Current Page:%d", _currentPage);
-                //                  if (_currentPage != 1 && _currentPage != 5 && _currentPage != 6 && _currentPage != 7 && _currentPage != 8)
-                //                      printf("_currentPage = %d \n", _currentPage);
-            }
-            break;
-            }
-        } else if (*(msg + 3) == CMD_MULTI_READ)
-        {
-            short key = ((short)(*(msg + 4) << 8) + *(msg + 5));
-            if (strcmp((char*)pSysInfo->LcmHwRev, "") != EQUAL)
-                strcpy((char*)pSysInfo->LcmHwRev, moduleName);
-            if (key == 0x0014)
-                _currentPage = *(msg + 8);
-            if (key == 0x0031) {
-                log_info("Get LCM Backlight change to 0x%x", *(msg + 8));
-            }
-            if (key >= _Touch_IDLE && key <= _Touch_Parking_Complete) {
-
-                _btn_press_id = key;
-                _btn_press = *(msg + 8);
-            }
-            //          switch ((unsigned short) (*(msg + 4) << 8) + (unsigned short) *(msg + 5))
-            //          {
-            //              case BUTTON_GUN_INDEX:
-            //              {
-            //                  // 當前選的槍號
-            //                  _curGunIndex = (*(msg + 8));
-            //              }
-            //              break;
-            //          }
-        }
-    }
-}
-void GetDeviceInfoStatus(short address, uint8_t len)
-{
-    uint8_t cmd[8];
-    memset(cmd, 0x00, sizeof(cmd));
-    uint8_t msg[11];
-    memset(msg, 0x00, sizeof(msg));
-
-    cmd[0] = CMD_TITLE_1;
-    cmd[1] = CMD_TITLE_2;
-    cmd[2] = 0x04;
-    cmd[3] = CMD_MULTI_READ;
-    cmd[4] = (address >> 8) & 0xff;
-    cmd[5] = (address >> 0) & 0xff;
-    cmd[6] = len;
-
-    WriteCmdToLcm(cmd, ARRAY_SIZE(cmd));
-    usleep(1000);
-    ReadMsgFromLcm(msg, ARRAY_SIZE(msg));
-}
-
-void DisplayValueToLcm(short address, uint8_t* data, uint8_t len)
-{
-
-    uint8_t cmd[256];
-    memset(cmd, 0x00, sizeof(cmd));
-    uint8_t msg[9];
-    memset(msg, 0x00, sizeof(msg));
-
-    cmd[0] = CMD_TITLE_1;
-    cmd[1] = CMD_TITLE_2;
-    cmd[2] = 0x03 + len;
-    cmd[3] = CMD_MULTI_WRITE;
-    cmd[4] = address >> 8;
-    cmd[5] = address & 0x00FF;
-
-    for (uint8_t count = 0; count < len; count++)
-    {
-        cmd[6 + count] = *(data + count);
-    }
-
-    WriteCmdToLcm(cmd, cmd[2] + 3);
-    usleep(10000);
-    ReadMsgFromLcm(msg, ARRAY_SIZE(msg));
-}
-
-void ChangeDisplay2Value(short address, short value)
-{
-    uint8_t data[2];
-    data[0] = value >> 8;
-    data[1] = value & 0x00FF;
-    //log_info("Addr:0x%x, value:%d",address,value);
-    DisplayValueToLcm(address, data, sizeof(data));
-}
-void TradeRunning(uint8_t _run)
-{
-    if (_run == TRUE) {
-        ChangeDisplay2Value(_Icon_PreAuth, 1);
-        ChangeDisplay2Value(_Icon_Ani_Dot, 1);
-        ChangeDisplay2Value(_Icon_CountDownBG, 0);
-        ChangeDisplay2Value(_Icon_CancelCntDownTen, 0);
-        ChangeDisplay2Value(_Icon_CancelCntDownDigits, 0);
-        ChangeDisplay2Value(_Icon_PreAuthWord, _TCC_PreAuthWord);
-    }
-    else {
-        ChangeDisplay2Value(_Icon_PreAuth, _TCC_TradeCancelString);
-        ChangeDisplay2Value(_Icon_Ani_Dot, 0);
-        ChangeDisplay2Value(_Icon_PreAuthWord, 0);
-        ChangeDisplay2Value(_Icon_CountDownBG, _TCC_TradeCancelFrame);
-        //log_info("SystemTimeoutFlag:%d", pSysInfo->SystemTimeoutFlag);
-        if (pSysInfo->SystemTimeoutFlag == Timeout_TradeCancel) {
-            unsigned long _time = TCC_TRADECANCEL_TIMEOUT-(GetClockTimeoutValue(pSysInfo->SystemTimeoutTimer) / uSEC_VAL);
-            ChangeDisplay2Value(_Icon_CancelCntDownTen, (short)(_TCC_CancelNum_0 + (_time / 10)));
-            ChangeDisplay2Value(_Icon_CancelCntDownDigits, (short)(_TCC_CancelNum_0 + (_time % 10)));
-        }
-
-    }
-}
-
-static void systemPageRestoreInit(void)
-{
-    int is_idle = TRUE;
-    int gunIndex;
-    for (gunIndex = 0; gunIndex < pSysConfig->TotalConnectorCount; gunIndex++) {
-        pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(gunIndex);
-        // 檢查電樁狀態是否為idle狀態
-        if ((pDcChargingInfo->SystemStatus >= S_AUTHORIZING &&
-            pDcChargingInfo->SystemStatus <= S_RESERVATION) ||
-            (pDcChargingInfo->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
-                pDcChargingInfo->SystemStatus <= S_CCS_PRECHARGE_ST0)) {
-            is_idle = FALSE;
-        }
-    }
-    if (is_idle)
-        pSysInfo->SystemPage = _PAGE_IDLE;
-    else
-        pSysInfo->SystemPage = _PAGE_SELECT_GUN;
-}
-
-void CheckIdlePress()
-{
-    systemPageRestoreInit();
-    log_info("IDLE Enter Select Gun Page");
-}
-void CheckReturnPress()
-{
-	int i;
-	pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(pSysInfo->CurGunSelected);
-	//pDcChargingInfo->SystemStatus = S_IDLE;
-    if (pSysInfo->SystemPage >= _PAGE_BILL && pSysInfo->SystemPage <= _PAGE_PLUGIN ||
-        pSysInfo->SystemPage == _PAGE_AUTHORIZE_FAIL || pSysInfo->SystemPage == _PAGE_DONATE_RIGHT) {
-        if (pSysInfo->SystemPage == _PAGE_AUTHORIZE && ShmDcCommonData->pGunInfo[pSysInfo->CurGunSelected].isParking) {
-            log_info("Parking Status cann't press return button");
-            return;
-        }
-        ShmDcCommonData->OperateIDLE[pSysInfo->CurGunSelected] = 1;
-        StopGunInfoTimeoutDet(pSysInfo->CurGunSelected);
-        ShmDcCommonData->pGunInfo[pSysInfo->CurGunSelected].GetParkingBill = FALSE;
-        ShmDcCommonData->pGunInfo[pSysInfo->CurGunSelected].isParking = FALSE;
-        log_info("Operate return to IDLE");
-    }
-    // Cancel Trade
-    if (ShmDcCommonData->pGunInfo[pSysInfo->CurGunSelected].ParkingStatus) {
-        ShmDcCommonData->pGunInfo[pSysInfo->CurGunSelected].GetParkingBill = FALSE;
-        //if (pSysInfo->SystemPage == _PAGE_AUTHORIZE) {
-            log_info("Press Return button Cancel Sale");
-            ShmDcCommonData->TradeCancel = TRUE;
-            pSysInfo->SystemPage = _PAGE_SENSING;
-            StopGunInfoTimeoutDet(pSysInfo->CurGunSelected);
-            StartSystemTimeoutDet(Timeout_TradeCancel);
-            for (i = 0; i <= 60; i++) {
-            if (ShmDcCommonData->pGunInfo[pSysInfo->CurGunSelected].ParkingStatus == _TCC_PARKING_OCCUPENCY_Ready)
-                break;
-                sleep(1);
-            }
-        //}
-        ShmDcCommonData->TradeCancel = FALSE;
-        StopSystemTimeoutDet();
-        systemPageRestoreInit();
-        return;
-    } else if ( pDcChargingInfo->SystemStatus == S_AUTHORIZING || 
-        ((pDcChargingInfo->SystemStatus == S_IDLE || pDcChargingInfo->SystemStatus == S_RESERVATION ) &&
-            pSysInfo->SystemPage == _PAGE_AUTHORIZE)) {
-        log_info("Press Return button cancel PreAuth");
-        ShmDcCommonData->TradeCancel = TRUE;
-        pSysInfo->SystemPage = _PAGE_SENSING;
-        StopGunInfoTimeoutDet(pSysInfo->CurGunSelected);
-        StartSystemTimeoutDet(Timeout_TradeCancel);
-        for (i = 0; i <= 30; i++) {
-            if (ShmDcCommonData->PreAuth_Config == _CREDITCARD_IDLE)
-                break;
-            sleep(1);
-        }
-
-        ShmDcCommonData->PreAuth_Result = 0;
-        ShmDcCommonData->AuthPass_flag[pSysInfo->CurGunSelected] = FALSE;
-        
-        if (strcmp(ShmDcCommonData->TransactionInfo[pSysInfo->CurGunSelected].pCreditCard.VemData, "") != 0) {
-            ShmDcCommonData->PreAuth_Config = _CREDITCARD_CANCEL;
-            ShmDcCommonData->PreAuth_Result = 0;
-            for (i = 0; i <= 30; i++) {
-                if (ShmDcCommonData->PreAuth_Config == _CREDITCARD_IDLE)
-                    break;
-                sleep(1);
-            }
-            ShmDcCommonData->PreAuth_Result = 0;
-        }
-        StopSystemTimeoutDet();
-
-        pDcChargingInfo->SystemStatus = S_IDLE;
-        systemPageRestoreInit();
-		strcpy((char *)pSysConfig->UserId, "");
-		return;
-	}
-
-	if ( pSysInfo->SystemPage == _PAGE_EXIT ) {
-        StopGunInfoTimeoutDet(pSysInfo->CurGunSelected);
-		pDcChargingInfo->SystemStatus = S_IDLE;
-
-		return;
-	}
-
-    if (pSysInfo->SystemPage == _PAGE_AUTHORIZE)
-        pSysInfo->SystemPage = _PAGE_SELECT_PAY;
-    else
-        systemPageRestoreInit();
-}
-void CheckStopPress()
-{
-	//ChangeDisplay2Value(_ConfirmStopIcon,is_stop);
-	if (pSysInfo->CurGunSelected == LEFT_GUN_NUM)
-		pSysInfo->SystemPage = _PAGE_STOP_CONFIRM_LEFT;
-	else
-		pSysInfo->SystemPage = _PAGE_STOP_CONFIRM_RIGHT;
-}
-void CheckStopConfirmPress()
-{
-	pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(pSysInfo->CurGunSelected);
-	pDcChargingInfo->SystemStatus = S_TERMINATING;
-	pSysInfo->SystemPage = _PAGE_PAYING;
-    is_stop = TRUE;
-    /*
-	//ShmDcCommonData->StopCharge[pSysInfo->CurGunSelected] = TRUE;
-    if (ShmDcCommonData->is_AutoStart[pSysInfo->CurGunSelected] ||
-        ShmDcCommonData->is_RemoteStart[pSysInfo->CurGunSelected]) {
-        pSysInfo->SystemPage = _PAGE_COMPLETE;
-        return;
-    }
-    */
-}
-void CheckStopCancelPress()
-{
-	//ChangeDisplay2Value(_ConfirmStopIcon,is_stop);
-	pSysInfo->SystemPage = _PAGE_CHARGING;
-    is_stop = FALSE;
-}
-void CheckConfirmGun(uint8_t gunIndex)
-{
-    pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(gunIndex);
-    if (pDcChargingInfo->SystemStatus == S_RESERVATION) {
-        log_info("Reservation can't select");
-        return;
-    }
-
-    //log_info("Confirm Gun%d",gunIndex);
-	pSysInfo->CurGunSelected = gunIndex;
-    if (ShmDcCommonData->pGunInfo[gunIndex].ParkingStatus) {
-
-        if (pDcChargingInfo->SystemStatus == S_IDLE)
-            ShmDcCommonData->pGunInfo[gunIndex].ReqParkingBill = TRUE;
-        //else if (isChargingEnd(gunIndex)) {
-        //}
-        if (pDcChargingInfo->SystemStatus == S_COMPLETE || pDcChargingInfo->SystemStatus == S_ALARM) {
-            if (ShmDcCommonData->PayPass_flag[gunIndex] == TRUE)
-                pSysInfo->SystemPage = _PAGE_COMPLETE;
-            else {
-                if (pDcChargingInfo->Replug_flag)
-                    pSysInfo->SystemPage = _PAGE_PLUGOUT;
-                else
-                    pSysInfo->SystemPage = _PAGE_PAYFAIL;
-            }
-        } else {
-            pSysInfo->SystemPage = _PAGE_PAYING;
-        }
-        
-    } else {
-	    pSysInfo->SystemPage = _PAGE_BILL;
-    }
-}
-void CheckDonateBill(uint8_t gunIndex)
-{
-	if (gunIndex == LEFT_GUN_NUM) {
-		pSysInfo->SystemPage = _PAGE_DONATE_LEFT;
-	} else
-		pSysInfo->SystemPage = _PAGE_DONATE_RIGHT;
-}
-void CheckDonateYes()
-{
-    if (ShmDcCommonData->pGunInfo[pSysInfo->CurGunSelected].ParkingStatus) {
-        StopGunInfoTimeoutDet(pSysInfo->CurGunSelected);
-        StartGunInfoTimeoutDet(pSysInfo->CurGunSelected, Timeout_ParkingSelect);
-        ShmDcCommonData->ParkingInfo[pSysInfo->CurGunSelected].IsDonateInvoice = TRUE;
-    } else {
-	    ShmDcCommonData->TransactionInfo[pSysInfo->CurGunSelected].IsDonateInvoice = TRUE;
-    }
-	pSysInfo->SystemPage = _PAGE_SELECT_PAY;
-
-}
-void CheckDonateNo()
-{
-    if (ShmDcCommonData->pGunInfo[pSysInfo->CurGunSelected].ParkingStatus) {
-        StopGunInfoTimeoutDet(pSysInfo->CurGunSelected);
-        StartGunInfoTimeoutDet(pSysInfo->CurGunSelected, Timeout_ParkingSelect);
-        ShmDcCommonData->ParkingInfo[pSysInfo->CurGunSelected].IsDonateInvoice = FALSE;
-    } else {
-        StartSystemTimeoutDet(Timeout_AddLine);
-        ShmDcCommonData->TransactionInfo[pSysInfo->CurGunSelected].IsDonateInvoice = FALSE;
-    }
-	pSysInfo->SystemPage = _PAGE_BILL;
-}
-void CheckPayCreditCard()
-{
-    //ShmDcCommonData->LineStatus[pSysInfo->CurGunSelected] = 0;
-    pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(pSysInfo->CurGunSelected);
-    // 使用者進入線上支付,禁止使用者使用刷卡機
-    if (ShmDcCommonData->TransactionInfo[pSysInfo->CurGunSelected].LineStatus == _LINE_PAY_OPERATE ||
-        pDcChargingInfo->SystemStatus == S_RESERVATION ) {
-        pSysInfo->SystemPage = _PAGE_LINEPAYING;
-        StartSystemTimeoutDet(Timeout_LINEPAYING);
-        log_info("Some one online operate");
-        return;
-    }
-    ShmDcCommonData->TradeCancel = FALSE;
-
-    if (ShmDcCommonData->pGunInfo[pSysInfo->CurGunSelected].ParkingStatus) {
-        if ((pDcChargingInfo->SystemStatus == S_IDLE || isChargingEnd(pSysInfo->CurGunSelected)) &&
-            ShmDcCommonData->PreAuth_Config == _CREDITCARD_IDLE) {
-            ShmDcCommonData->PreAuth_Config = _CREDITCARD_SALE;
-            ShmDcCommonData->PreAuth_Result = 0;
-            pSysInfo->SystemPage = _PAGE_AUTHORIZE;
-            }
-    } else {
-        if ((pDcChargingInfo->SystemStatus == S_IDLE ) &&
-            pSysInfo->SystemPage == _PAGE_SELECT_PAY &&
-            ShmDcCommonData->PreAuth_Config == _CREDITCARD_IDLE) {
-            ShmDcCommonData->PreAuth_Config = _CREDITCARD_PREAUTH;
-            ShmDcCommonData->PreAuth_Result = 0;
-            pSysInfo->SystemPage = _PAGE_AUTHORIZE;
-            //log_info("Press Credit card pay status:%d Page:%d Config:%d", pDcChargingInfo->SystemStatus,
-            //    pSysInfo->SystemPage, ShmDcCommonData->PreAuth_Config);
-        }
-    }
-}
-
-void CheckPayLinePay()
-{
-    log_info("Change to Add Line Friend Page");
-    StopSystemTimeoutDet();
-    StopGunInfoTimeoutDet(pSysInfo->CurGunSelected);
-    pSysInfo->SystemPage = _PAGE_ADD_FRIEND;
-}
-void CheckTouchPress(short id)
-{
-    GetDeviceInfoStatus(id,1);
-    if (_btn_press >= 1 && _btn_press_id == id ) {
-    	_btn_press_count++;
-    }
-    if (_btn_press >= 1 && _btn_press_id == id && _btn_press_count >= 2) {
-        ChangeDisplay2Value(id, 0);
-        //log_info("Press id : 0x%04x",id);
-        _btn_press_count = 0;
-        switch (id) {
-        case _Touch_Show_Left:
-        	if (pSysInfo->SystemPage >= _PAGE_BILL && pSysInfo->SystemPage <= _PAGE_PLUGIN) {
-        		log_info("Authorize Process can't select gun");
-        		return;
-        	}
-            // Show log
-        	if(pSysInfo->CurGunSelected != LEFT_GUN_NUM) {
-        		pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(LEFT_GUN_NUM);
-        		pSysInfo->CurGunSelected = LEFT_GUN_NUM;
-                if(pDcChargingInfo->SystemStatus == S_IDLE || pDcChargingInfo->SystemStatus == S_RESERVATION) {
-                    systemPageRestoreInit();
-                }
-				log_info("LCM left Gun down...............................%x %x %x",
-						pSysInfo->CurGunSelected,pDcChargingInfo->SystemStatus,pSysInfo->SystemPage);
-			}
-            pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(LEFT_GUN_NUM);
-            if (ShmDcCommonData->pGunInfo[LEFT_GUN_NUM].ParkingStatus) {
-                if (pDcChargingInfo->SystemStatus == S_COMPLETE || pDcChargingInfo->SystemStatus == S_ALARM) {
-                    if (ShmDcCommonData->PayPass_flag[LEFT_GUN_NUM] == TRUE)
-                        pSysInfo->SystemPage = _PAGE_COMPLETE;
-                    else {
-                        if (pDcChargingInfo->Replug_flag)
-                            pSysInfo->SystemPage = _PAGE_PLUGOUT;
-                        else
-                            pSysInfo->SystemPage = _PAGE_PAYFAIL;
-                    }
-                }
-            }
-        	if (pSysInfo->SystemPage == _PAGE_CHARGING || pSysInfo->SystemPage == _PAGE_COMPLETE ||
-        			pSysInfo->SystemPage == _PAGE_PAYFAIL) {
-				StopSystemTimeoutDet();
-        	}
-            break;
-        case _Touch_Show_Right:
-        	if (pSysInfo->SystemPage >= _PAGE_BILL && pSysInfo->SystemPage <= _PAGE_PLUGIN) {
-        		log_info("Authorize Process can't select gun");
-        		return;
-        	}
-			// Show log
-			if(pSysInfo->CurGunSelected != RIGHT_GUN_NUM) {
-				pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(RIGHT_GUN_NUM);
-				pSysInfo->CurGunSelected = RIGHT_GUN_NUM;
-                if (pDcChargingInfo->SystemStatus == S_IDLE || pDcChargingInfo->SystemStatus == S_RESERVATION) {
-                    systemPageRestoreInit();
-	            }
-				log_info("LCM Right Gun down...............................%x %x %x",
-						pSysInfo->CurGunSelected,pDcChargingInfo->SystemStatus,pSysInfo->SystemPage);
-			}
-            pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(RIGHT_GUN_NUM);
-            if (ShmDcCommonData->pGunInfo[RIGHT_GUN_NUM].ParkingStatus) {
-                if (pDcChargingInfo->SystemStatus == S_COMPLETE || pDcChargingInfo->SystemStatus == S_ALARM) {
-                    if (ShmDcCommonData->PayPass_flag[RIGHT_GUN_NUM] == TRUE)
-                        pSysInfo->SystemPage = _PAGE_COMPLETE;
-                    else
-                        if (pDcChargingInfo->Replug_flag)
-                            pSysInfo->SystemPage = _PAGE_PLUGOUT;
-                        else
-                            pSysInfo->SystemPage = _PAGE_PAYFAIL;
-                }
-            }
-        	if (pSysInfo->SystemPage == _PAGE_CHARGING || pSysInfo->SystemPage == _PAGE_COMPLETE ||
-        			pSysInfo->SystemPage == _PAGE_PAYFAIL) {
-				StopSystemTimeoutDet();
-        	}
-            break;
-        case _Touch_Return:
-        	CheckReturnPress();
-        	break;
-        case _Touch_IDLE:
-            CheckIdlePress();
-            break;
-        case _Touch_StopCharge:
-        	CheckStopPress();
-        	break;
-        case _Touch_Stop_Confirm:
-        	CheckStopConfirmPress();
-        	break;
-        case _Touch_Stop_Cancel:
-        	CheckStopCancelPress();
-        	break;
-        case _Touch_Select_Left:
-        	CheckConfirmGun(LEFT_GUN_NUM);
-        	break;
-        case _Touch_Select_Right:
-        	CheckConfirmGun(RIGHT_GUN_NUM);
-        	break;
-        case _Touch_DonateBill:
-        	StopSystemTimeoutDet();
-        	CheckDonateBill(pSysInfo->CurGunSelected);
-        	break;
-        case _Touch_DonateYes:
-        	CheckDonateYes();
-        	break;
-        case _Touch_DonateNo:
-
-        	CheckDonateNo();
-        	break;
-        case _Touch_Pay_CreditCard:
-        	CheckPayCreditCard();
-        	break;
-        case _Touch_Pay_LinePay:
-        	CheckPayLinePay();
-        	break;
-        case _Touch_Parking_Complete:
-            ShmDcCommonData->pGunInfo[pSysInfo->CurGunSelected].ReqParkingBill = TRUE;
-            pSysInfo->SystemPage = _PAGE_PAYING;
-            //log_info("Set Page to %d",pSysInfo->SystemPage);
-            break;
-        } // switch
-
-    }   //if (_btn_press >= 3)
-}
-
-void CheckLCMPressed()
-{
-    pid_t Pid = fork();
-    if ( Pid == 0 ) {
-        while (1) {
-        	if (pSysInfo->SystemPage != _PAGE_SELECT_GUN && pSysInfo->SystemPage != _PAGE_IDLE) {
-				CheckTouchPress(_Touch_Show_Left);
-				CheckTouchPress(_Touch_Show_Right);
-        	}
-            switch (pSysInfo->SystemPage) {
-            case _PAGE_IDLE:
-				//CheckTouchPress(_Touch_IDLE);
-                CheckTouchPress(_Touch_Select_Left);
-                CheckTouchPress(_Touch_Select_Right);
-                break;
-            case _PAGE_SELECT_GUN:
-				CheckTouchPress(_Touch_Select_Left);
-				CheckTouchPress(_Touch_Select_Right);
-            	break;
-            case _PAGE_BILL:
-            	CheckTouchPress(_Touch_Return);
-            	CheckTouchPress(_Touch_DonateBill);
-                CheckTouchPress(_Touch_Pay_LinePay);
-            	break;
-            case _PAGE_ADD_FRIEND:
-            	CheckTouchPress(_Touch_Return);
-            	//CheckTouchPress(_Touch_DonateBill);
-            	break;
-            case _PAGE_DONATE_LEFT:
-            case _PAGE_DONATE_RIGHT:
-            	CheckTouchPress(_Touch_Return);
-            	CheckTouchPress(_Touch_DonateYes);
-            	CheckTouchPress(_Touch_DonateNo);
-            	break;
-            case _PAGE_SELECT_PAY:
-                CheckTouchPress(_Touch_Pay_CreditCard);
-            	CheckTouchPress(_Touch_Return);
-            	break;
-            case _PAGE_PLUGIN:
-            	CheckTouchPress(_Touch_Return);
-
-            	break;
-            ///*
-            case _PAGE_CHARGING:
-				CheckTouchPress(_Touch_StopCharge);
-            	break;
-            case _PAGE_AUTHORIZE:
-            	CheckTouchPress(_Touch_Return);
-            	break;
-            case _PAGE_STOP_CONFIRM_LEFT:
-            case _PAGE_STOP_CONFIRM_RIGHT:
-            	StopSystemTimeoutDet();
-				CheckTouchPress(_Touch_Stop_Confirm);
-				CheckTouchPress(_Touch_Stop_Cancel);
-            	break;
-            case _PAGE_EXIT:
-            	CheckTouchPress(_Touch_Return);
-            	break;
-            case _PAGE_AUTHORIZE_FAIL:
-            	CheckTouchPress(_Touch_Return);
-            	break;
-            case _PAGE_COMPLETE:
-            case _PAGE_PAYFAIL:
-            case _PAGE_PLUGOUT:
-                if (ShmDcCommonData->pGunInfo[pSysInfo->CurGunSelected].ParkingStatus >= _TCC_PARKING_OCCUPENCY)
-                    CheckTouchPress(_Touch_Parking_Complete);
-                break;
-            } // switch
-            usleep(5000);
-        } //while
-    } // if pid
-    log_info("Create LCM fork:%d\n\n",Pid);
-}
-
-
-void GetHrFormTimeString(char* time,char* hr)
-{
-    //char tm[] = "2021-12-06 17:29:08:084";
-    for(int i = 0 ; i < 2 ; i++) {
-        hr[i] = time[i+11];
-    }
-    if( atoi(hr) < 0 || atoi(hr) > 24) {
-        strcmp(hr,"");
-    }
-}
-void GetMinFormTimeString(char* time,char* min)
-{
-    //char tm[] = "2021-12-06 17:29:08:084";
-    for(int i = 0 ; i < 2 ; i++) {
-        min[i] = time[i+14];
-    }
-    if( atoi(min) < 0 || atoi(min) > 60) {
-        strcmp(min,"");
-    }
-}
-//================================================
-// Function
-//================================================
-void ChangeToOtherPage(short newPage)
-{
-
-    uint8_t cmd[10];
-    memset(cmd, 0x00, sizeof(cmd));
-    uint8_t msg[9];
-    memset(msg, 0x00, sizeof(msg));
-
-    cmd[0] = CMD_TITLE_1;
-    cmd[1] = CMD_TITLE_2;
-    cmd[2] = 0x07;
-    cmd[3] = 0x82;
-    cmd[4] = 0x00;
-    cmd[5] = 0x84;
-    cmd[6] = 0x5A;
-    cmd[7] = 0x01;
-    cmd[8] = newPage >> 8;
-    cmd[9] = newPage & 0x00FF;
-
-    WriteCmdToLcm(cmd, ARRAY_SIZE(cmd));
-    usleep(5000);
-    ReadMsgFromLcm(msg, ARRAY_SIZE(msg));
-}
-
-void ChangeBackLight(uint8_t value)
-{
-    //uint8_t value = 0x01;
-    uint8_t msg[9];
-    memset(msg, 0x00, sizeof(msg));
-
-    uint8_t cmd[7];
-    memset(cmd, 0x00, sizeof(cmd));
-
-    cmd[0] = CMD_TITLE_1;
-    cmd[1] = CMD_TITLE_2;
-    cmd[2] = 0x05;
-    cmd[3] = CMD_MULTI_WRITE;
-    cmd[4] = 0x00;
-    cmd[5] = 0x82;
-    cmd[6] = value;
-
-    WriteCmdToLcm(cmd, ARRAY_SIZE(cmd));
-    usleep(10000);
-    ReadMsgFromLcm(msg, ARRAY_SIZE(msg));
-}
-
-void GetCurrentPage()
-{
-    uint8_t cmd[7];
-    memset(cmd, 0x00, sizeof(cmd));
-    uint8_t msg[9];
-    memset(msg, 0x00, sizeof(msg));
-
-    cmd[0] = CMD_TITLE_1;
-    cmd[1] = CMD_TITLE_2;
-    cmd[2] = 0x04;              // 底下總長度
-    cmd[3] = 0x83;
-    cmd[4] = 0x00;
-    cmd[5] = 0x14;
-    cmd[6] = 0x01;
-
-    WriteCmdToLcm(cmd, ARRAY_SIZE(cmd));
-    usleep(5000);
-    ReadMsgFromLcm(msg, ARRAY_SIZE(msg));
-}
-
-
-//================================================
-// Warning process
-//================================================
-void string2ByteArray(uint8_t *input, uint8_t *output)
-{
-    int loop;
-    int i;
-
-    loop = 0;
-    i = 0;
-
-    while (input[loop] != '\0') {
-        output[i++] = input[loop++];
-    }
-    output[loop] = '\0';
-}
-
-void RefreshProgressAnimation()
-{
-	_everyPageRollChange >= 30 ? _everyPageRollChange = 0 : _everyPageRollChange++;
-}
-
-//================================================
-// Change current page
-//================================================
-void ChangeCurPage()
-{
-    //log_info("cur = %d ,system = %d, lcm = %d ",_currentPage, pSysInfo->SystemPage, pSysInfo->PageIndex);
-    if (pSysInfo->PageIndex != pSysInfo->SystemPage)
-        log_info("Gun[%d] Chagne LCM Page:%d",pSysInfo->CurGunSelected, pSysInfo->SystemPage);
-    pSysInfo->PageIndex = pSysInfo->SystemPage;
-
-    if (_currentPage != pSysInfo->PageIndex) {
-        switch (pSysInfo->SystemPage) {
-        case _PAGE_AUTHORIZE:
-            break;
-        case _PAGE_PLUGIN:
-            break;
-        case _PAGE_PRECHARGE:
-            break;
-        case _PAGE_CHARGING:
-            break;
-        case _PAGE_COMPLETE:
-            is_stop = FALSE;
-            break;
-        case _PAGE_PAYFAIL:
-            is_stop = FALSE;
-            break;
-        case _PAGE_MAINTAIN:
-            break;
-        }
-        
-        _currentPage = pSysInfo->PageIndex;
-        //if (pSysInfo->PageIndex != _PAGE_IDLE)
-
-        ChangeToOtherPage(pSysInfo->PageIndex);
-    }
-}
-
-/*
- * View Page
- *
- */
-
-unsigned long GetTimeoutValue(struct timeval _sour_time)
-{
-    struct timeval _end_time;
-    gettimeofday(&_end_time, NULL);
-
-    return 1000000 * (_end_time.tv_sec - _sour_time.tv_sec) + _end_time.tv_usec - _sour_time.tv_usec;
-}
-
-void showGunWorkingType()
-{
-    if (pSysInfo->CurGunSelected == LEFT_GUN_NUM) {
-
-        pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(LEFT_GUN_NUM);
-        if (ShmDcCommonData->pGunInfo[LEFT_GUN_NUM].ParkingStatus) {
-            ChangeDisplay2Value(_Icon_ShowLeft,_TCC_LeftParkingSel);
-        } else {
-            if (pDcChargingInfo->CCSGunType == _TYPE_CCS1_Liquid ||
-                    pDcChargingInfo->CCSGunType == _TYPE_CCS1_Natural) {
-                ChangeDisplay2Value(_Icon_ShowLeft,_TCC_ShowLeft_CCS1_On);
-
-            } else if (pDcChargingInfo->CCSGunType == _TYPE_CCS2_Liquid ||
-                    pDcChargingInfo->CCSGunType == _TYPE_CCS2_Natural) {
-                ChangeDisplay2Value(_Icon_ShowLeft,_TCC_ShowLeft_CCS2_On);
-            } else if (pDcChargingInfo->Type == _Type_Chademo) {
-                ChangeDisplay2Value(_Icon_ShowLeft,_TCC_ShowLeft_CHAdeMo_On);
-            }
-        }
-
-        // Set Right Gun
-        pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(RIGHT_GUN_NUM);
-        if (ShmDcCommonData->pGunInfo[RIGHT_GUN_NUM].ParkingStatus) {
-            ChangeDisplay2Value(_Icon_ShowRight,_TCC_RightParkingSel);
-        } else {
-            if (pDcChargingInfo->CCSGunType == _TYPE_CCS1_Liquid ||
-                    pDcChargingInfo->CCSGunType == _TYPE_CCS1_Natural) {
-                ChangeDisplay2Value(_Icon_ShowRight,_TCC_ShowRight_CCS1_Off);
-
-            } else if (pDcChargingInfo->CCSGunType == _TYPE_CCS2_Liquid ||
-                    pDcChargingInfo->CCSGunType == _TYPE_CCS2_Natural) {
-                ChangeDisplay2Value(_Icon_ShowRight,_TCC_ShowRight_CCS2_Off);
-            } else if (pDcChargingInfo->Type == _Type_Chademo) {
-                ChangeDisplay2Value(_Icon_ShowRight,_TCC_ShowRight_CHAdeMo_Off);
-            }
-        }
-    } else if (pSysInfo->CurGunSelected == RIGHT_GUN_NUM){
-        // Left Gun
-        pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(LEFT_GUN_NUM);
-        if (ShmDcCommonData->pGunInfo[LEFT_GUN_NUM].ParkingStatus) {
-            ChangeDisplay2Value(_Icon_ShowLeft,_TCC_LeftParkingSel);
-        } else {
-            if (pDcChargingInfo->CCSGunType == _TYPE_CCS1_Liquid ||
-                    pDcChargingInfo->CCSGunType == _TYPE_CCS1_Natural) {
-                ChangeDisplay2Value(_Icon_ShowLeft,_TCC_ShowLeft_CCS1_Off);
-
-            } else if (pDcChargingInfo->CCSGunType == _TYPE_CCS2_Liquid ||
-                    pDcChargingInfo->CCSGunType == _TYPE_CCS2_Natural) {
-                ChangeDisplay2Value(_Icon_ShowLeft,_TCC_ShowLeft_CCS2_Off);
-            } else if (pDcChargingInfo->Type == _Type_Chademo) {
-                ChangeDisplay2Value(_Icon_ShowLeft,_TCC_ShowLeft_CHAdeMo_Off);
-            }
-        }
-        // Right Gun
-        pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(RIGHT_GUN_NUM);
-        if (ShmDcCommonData->pGunInfo[RIGHT_GUN_NUM].ParkingStatus) {
-            ChangeDisplay2Value(_Icon_ShowRight,_TCC_RightParkingSel);
-        } else {
-            if (pDcChargingInfo->CCSGunType == _TYPE_CCS1_Liquid ||
-                    pDcChargingInfo->CCSGunType == _TYPE_CCS1_Natural) {
-                ChangeDisplay2Value(_Icon_ShowRight,_TCC_ShowRight_CCS1_On);
-
-            } else if (pDcChargingInfo->CCSGunType == _TYPE_CCS2_Liquid ||
-                    pDcChargingInfo->CCSGunType == _TYPE_CCS2_Natural) {
-                ChangeDisplay2Value(_Icon_ShowRight,_TCC_ShowRight_CCS2_On);
-            } else if (pDcChargingInfo->Type == _Type_Chademo) {
-                ChangeDisplay2Value(_Icon_ShowRight,_TCC_ShowRight_CHAdeMo_On);
-            }
-        }
-    }
-}
-void ClearQrCode_Idle()
-{
-    char cmd[200];
-    memset(cmd,0,200);
-    DisplayValueToLcm(_QRCode_AddLine, cmd, 200);
-}
-void ChangeQrCode_Idle(char *input)
-{
-    char cmd[256];
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(pSysInfo->CurGunSelected);
-    int len = 0;
-    memset(cmd,0,256);
-    time_t timep;
-    struct tm* tm;
-    time(&timep);
-    char SN[37];
-    memset(SN,'\0',sizeof(SN));
-    memcpy(SN,ShmDcCommonData->ParkingInfo[pSysInfo->CurGunSelected].OccupancySN,36);
-    tm = localtime(&timep);
-
-    if (ShmDcCommonData->pGunInfo[pSysInfo->CurGunSelected].ParkingStatus && !ShmDcCommonData->ParkingInfo[pSysInfo->CurGunSelected].ParkingCntDownFlag) {
-        tm->tm_year -= 50;
-        ShmDcCommonData->ParkingInfo[pSysInfo->CurGunSelected].ParkingStopTime = mktime(tm) + 120 +(ShmDcCommonData->TZOffset * 60);
-        ShmDcCommonData->ParkingInfo[pSysInfo->CurGunSelected].ParkingCntDownFlag = TRUE;
-        tm = gmtime(&ShmDcCommonData->ParkingInfo[pSysInfo->CurGunSelected].ParkingStopTime);
-        log_info("QR Code Show Time:(%d)%s",ShmDcCommonData->ParkingInfo[pSysInfo->CurGunSelected].ParkingStopTime,asctime(tm));
-    }
-
-    if (!ShmDcCommonData->tccdev) {
-        if (ShmDcCommonData->pGunInfo[pSysInfo->CurGunSelected].ParkingStatus) {
-            len = sprintf(cmd, "https://nhoatcc.lineapid.tw/web/placeholder?sn=%s&ts=%d",SN,
-                                                                                        ShmDcCommonData->ParkingInfo[pSysInfo->CurGunSelected].ParkingStopTime);
-        } else
-            len = sprintf(cmd, "https://nhoatcc.lineapid.tw/web/tologin?sn=%s&cid=%d", input, ShmDcCommonData->ConnectorID[pSysInfo->CurGunSelected]);
-    } else {
-        if (ShmDcCommonData->pGunInfo[pSysInfo->CurGunSelected].ParkingStatus) {
-            len = sprintf(cmd, "https://nhoatcctest.lineapid.tw/web/placeholder?sn=%s&ts=%d",SN,
-                                                                                        ShmDcCommonData->ParkingInfo[pSysInfo->CurGunSelected].ParkingStopTime);
-        } else {
-            len = sprintf(cmd, "https://nhoatcctest.lineapid.tw/web/tologin?sn=%s&cid=%d", input, ShmDcCommonData->ConnectorID[pSysInfo->CurGunSelected]);
-        }
-    }
-    //log_info("QR Code:URL:%s",cmd);
-    if (pSysInfo->SystemPage == _PAGE_ADD_FRIEND)
-    	DisplayValueToLcm(_QRCode_AddLine, cmd, len+1);
-}
-void ClearQrCode_Error()
-{
-    char cmd[200];
-    memset(cmd, 0, 200);
-    DisplayValueToLcm(_QRCode_Service, cmd, 200);
-}
-void ChangeQrCode_Error()
-{
-    char cmd[200];
-    memset(cmd, 0, 200);
-    sprintf(cmd, "https://line.me/R/ti/p/@217tcevc");
-
-    //log_info("QR Code:URL:%s",cmd);
-
-    DisplayValueToLcm(_QRCode_Service, cmd, 200);
-}
-/*
-void ChangeRemainTime(int sec)
-{
-    int h, m, s;
-    uint8_t cmd[10];
-    uint8_t value[10];
-
-    memset(cmd, 0x00, sizeof(cmd));
-
-//  srand(time(NULL));
-//  int min = 0;
-//  int max = 65536;
-//  sec = rand() % (max - min + 1) + min;
-
-    h = (sec / 3600);
-    m = (sec - (3600 * h)) / 60;
-    s = (sec - (3600 * h) - (m * 60));
-    sprintf((char *)value, "%02d:%02d:%02d", h, m, s);
-    string2ByteArray(value, cmd);
-    DisplayValueToLcm(_Text_Time, cmd, sizeof(cmd));
-}
-*/
-void ShowSelectGun()
-{
-	pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(LEFT_GUN_NUM);
-    if (ShmDcCommonData->pGunInfo[LEFT_GUN_NUM].ParkingStatus){
-        ChangeDisplay2Value(_Icon_Select_Left,_TCC_LeftParkingIdle);
-    } else if ((pDcChargingInfo->SystemStatus >= S_AUTHORIZING &&
-        pDcChargingInfo->SystemStatus <= S_ALARM) ||
-        pDcChargingInfo->SystemStatus == S_CCS_PRECHARGE_ST0 ||
-        pDcChargingInfo->SystemStatus == S_CCS_PRECHARGE_ST1) {
-        // 使用中
-        if (pDcChargingInfo->CCSGunType == _TYPE_CCS1_Liquid ||
-            pDcChargingInfo->CCSGunType == _TYPE_CCS1_Natural) {
-            ChangeDisplay2Value(_Icon_Select_Left, _TCC_ShowLeftGunCharging_CCS1);
-
-        } else if (pDcChargingInfo->CCSGunType == _TYPE_CCS2_Liquid ||
-            pDcChargingInfo->CCSGunType == _TYPE_CCS2_Natural) {
-            ChangeDisplay2Value(_Icon_Select_Left, _TCC_ShowLeftGunCharging_CCS2);
-
-        } else if (pDcChargingInfo->Type == _Type_Chademo) {
-            ChangeDisplay2Value(_Icon_Select_Left, _TCC_ShowLeftGunCharging_CHAdeMo);
-        }
-    } else if (pDcChargingInfo->SystemStatus == S_RESERVATION) {
-        // 預約中
-        if (pDcChargingInfo->CCSGunType == _TYPE_CCS1_Liquid ||
-            pDcChargingInfo->CCSGunType == _TYPE_CCS1_Natural) {
-            ChangeDisplay2Value(_Icon_Select_Left, _TCC_ShowLeftGunReservation_CCS1);
-
-        } else if (pDcChargingInfo->CCSGunType == _TYPE_CCS2_Liquid ||
-            pDcChargingInfo->CCSGunType == _TYPE_CCS2_Natural) {
-            ChangeDisplay2Value(_Icon_Select_Left, _TCC_ShowLeftGunReservation_CCS2);
-
-        } else if (pDcChargingInfo->Type == _Type_Chademo) {
-            ChangeDisplay2Value(_Icon_Select_Left, _TCC_ShowLeftGunReservation_CHAdeMo);
-        }
-    } else {
-		if (pDcChargingInfo->CCSGunType == _TYPE_CCS1_Liquid ||
-				pDcChargingInfo->CCSGunType == _TYPE_CCS1_Natural) {
-			ChangeDisplay2Value(_Icon_Select_Left,_TCC_SelectLeft_CCS1);
-
-		} else if (pDcChargingInfo->CCSGunType == _TYPE_CCS2_Liquid ||
-				pDcChargingInfo->CCSGunType == _TYPE_CCS2_Natural) {
-			ChangeDisplay2Value(_Icon_Select_Left,_TCC_SelectLeft_CCS2);
-
-		} else if (pDcChargingInfo->Type == _Type_Chademo) {
-			ChangeDisplay2Value(_Icon_Select_Left,_TCC_SelectLeft_CHAdeMo);
-		}
-	}
-	pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(RIGHT_GUN_NUM);
-    if (ShmDcCommonData->pGunInfo[RIGHT_GUN_NUM].ParkingStatus) {
-        ChangeDisplay2Value(_Icon_Select_Right,_TCC_RightParkingIdle);
-    } else if ((pDcChargingInfo->SystemStatus >= S_AUTHORIZING &&
-        pDcChargingInfo->SystemStatus <= S_ALARM) ||
-        pDcChargingInfo->SystemStatus == S_CCS_PRECHARGE_ST0 ||
-        pDcChargingInfo->SystemStatus == S_CCS_PRECHARGE_ST1) {
-        if (pDcChargingInfo->CCSGunType == _TYPE_CCS1_Liquid ||
-            pDcChargingInfo->CCSGunType == _TYPE_CCS1_Natural) {
-            ChangeDisplay2Value(_Icon_Select_Right, _TCC_ShowRightGunCharging_CCS1);
-
-        } else if (pDcChargingInfo->CCSGunType == _TYPE_CCS2_Liquid ||
-            pDcChargingInfo->CCSGunType == _TYPE_CCS2_Natural) {
-            ChangeDisplay2Value(_Icon_Select_Right, _TCC_ShowRightGunCharging_CCS2);
-
-        } else if (pDcChargingInfo->Type == _Type_Chademo) {
-            ChangeDisplay2Value(_Icon_Select_Right, _TCC_ShowRightGunCharging_CHAdeMo);
-
-        }
-    } else if (pDcChargingInfo->SystemStatus == S_RESERVATION) {
-        if (pDcChargingInfo->CCSGunType == _TYPE_CCS1_Liquid ||
-            pDcChargingInfo->CCSGunType == _TYPE_CCS1_Natural) {
-            ChangeDisplay2Value(_Icon_Select_Right, _TCC_ShowRightGunReservation_CCS1);
-
-        } else if (pDcChargingInfo->CCSGunType == _TYPE_CCS2_Liquid ||
-            pDcChargingInfo->CCSGunType == _TYPE_CCS2_Natural) {
-            ChangeDisplay2Value(_Icon_Select_Right, _TCC_ShowRightGunReservation_CCS2);
-
-        } else if (pDcChargingInfo->Type == _Type_Chademo) {
-            ChangeDisplay2Value(_Icon_Select_Right, _TCC_ShowRightGunReservation_CHAdeMo);
-
-        }
-	} else {
-		if (pDcChargingInfo->CCSGunType == _TYPE_CCS1_Liquid ||
-				pDcChargingInfo->CCSGunType == _TYPE_CCS1_Natural) {
-			ChangeDisplay2Value(_Icon_Select_Right,_TCC_SelectRight_CCS1);
-
-		} else if (pDcChargingInfo->CCSGunType == _TYPE_CCS2_Liquid ||
-				pDcChargingInfo->CCSGunType == _TYPE_CCS2_Natural) {
-			ChangeDisplay2Value(_Icon_Select_Right,_TCC_SelectRight_CCS2);
-
-		} else if (pDcChargingInfo->Type == _Type_Chademo) {
-			ChangeDisplay2Value(_Icon_Select_Right,_TCC_SelectRight_CHAdeMo);
-
-		}
-	}
-
-}
-void ChangeChargingPowerValue(float pow)
-{
-    uint8_t cmd[10];
-    uint8_t value[10];
-
-    memset(cmd, 0x00, sizeof(cmd));
-
-    sprintf((char *) value, "%d",(int)pow);
-    string2ByteArray(value, cmd);
-    DisplayValueToLcm(_String_ChargePower, cmd, sizeof(cmd));
-}
-void ChangeChargingRateValue(float rate,int show)
-{
-    uint8_t cmd[10];
-    uint8_t value[10];
-
-    memset(cmd, 0x00, sizeof(cmd));
-    if (show)
-        sprintf((char *) value, "%.1f",rate);
-    else
-        sprintf((char *) value, "");
-    string2ByteArray(value, cmd);
-    DisplayValueToLcm(_String_ChargeRate, cmd, sizeof(cmd));
-}
-
-void ChangeChargingFeeValue(float fee)
-{
-    uint8_t cmd[10];
-    uint8_t value[10];
-
-    memset(cmd, 0x00, sizeof(cmd));
-
-    sprintf((char *) value, "%d", (int)fee);
-    string2ByteArray(value, cmd);
-    DisplayValueToLcm(_String_Money, cmd, sizeof(cmd));
-}
-void ChangeCarBonValue(float data)
-{
-    uint8_t cmd[10];
-    uint8_t value[10];
-    float _carbon = 0;
-    memset(cmd, 0x00, sizeof(cmd));
-    _carbon = data * 0.577;
-    //log_info("Carbon:%d",(int)_carbon);
-
-	sprintf((char *) value, "%.1f", _carbon);
-    string2ByteArray(value, cmd);
-    DisplayValueToLcm(_String_Carbon, cmd, sizeof(cmd));
-}
-void ChangeChargingEnergyValue(float energy)
-{
-    uint8_t cmd[10];
-    uint8_t value[10];
-
-    memset(cmd, 0x00, sizeof(cmd));
-    if (energy >= 0.05) {
-        energy -= 0.05;
-    }
-
-    if (energy < 0 )
-    	ChangeDisplay2Value(_Icon_ChargeBar,_TCC_Charging_Bar0);
-    else if (energy > 100)
-    	ChangeDisplay2Value(_Icon_ChargeBar,_TCC_Charging_Bar0+100);
-    else
-    	ChangeDisplay2Value(_Icon_ChargeBar,(int)energy+_TCC_Charging_Bar0);
-    if (energy < 10)
-    	sprintf((char *) value, "%.1f", energy);
-    else
-    	sprintf((char *) value, "%d", (int)energy);
-    string2ByteArray(value, cmd);
-    DisplayValueToLcm(_Strting_Energy, cmd, sizeof(cmd));
-}
-
-void ChangeParkingRateValue(float fee,int show)
-{
-    uint8_t cmd[10];
-    uint8_t value[10];
-
-    memset(cmd, 0x00, sizeof(cmd));
-    if (show)
-        sprintf((char *) value, "%d", (int)fee);
-    else
-        sprintf((char *) value, "");
-    string2ByteArray(value, cmd);
-    DisplayValueToLcm(_String_ParkRate, cmd, sizeof(cmd));
-}
-
-void ChangeParkingLeaveTime(int min,int show)
-{
-    uint8_t cmd[10];
-    uint8_t value[10];
-
-    memset(cmd, 0x00, sizeof(cmd));
-    if (show)
-        sprintf((char *) value, "%d", (int)min);
-    else
-        sprintf((char *) value, "");
-    string2ByteArray(value, cmd);
-    DisplayValueToLcm(_String_ParkingLeaveTime, cmd, sizeof(cmd));
-}
-
-void ChangeSaleLeaveTime(int min,int show)
-{
-    uint8_t cmd[10];
-    uint8_t value[10];
-
-    memset(cmd, 0x00, sizeof(cmd));
-    if (show)
-        sprintf((char *) value, "%d", (int)min);
-    else
-        sprintf((char *) value, "");
-    string2ByteArray(value, cmd);
-    DisplayValueToLcm(_String_SaleLeaveTime, cmd, sizeof(cmd));
-}
-
-uint8_t _battery_display_count = 0;
-void ChangeBattMapAndValue(int soc)
-{
-    int i = (soc*36)/100;
-    uint8_t cmd[5];
-    uint8_t value[5];
-
-	_battery_display_count++;
-	if (_battery_display_count == 3 ) {
-		if (_battery_display_ani == 0)
-			_battery_display_ani= TRUE;
-		else
-			_battery_display_ani= FALSE ;
-		_battery_display_count = 0;
-	}
-	if (pSysInfo->SystemPage == _PAGE_CHARGING) {
-		if (i>=36)
-			ChangeDisplay2Value(_Icon_ChargeCircle,_TCC_Charging_Circle0+36);
-		else {
-			if (_battery_display_ani) {
-				ChangeDisplay2Value(_Icon_ChargeCircle, _TCC_Charging_Circle0+i);
-			} else {
-				ChangeDisplay2Value(_Icon_ChargeCircle, _TCC_Charging_Circle0+i+1);
-			}
-		}
-	} else if (pSysInfo->SystemPage == _PAGE_COMPLETE)
-		ChangeDisplay2Value(_Icon_CompleteCircle, _TCC_CompleteCircle0+i);
-	else
-		ChangeDisplay2Value(_Icon_CompleteCircle, _TCC_FAILCircle0 +i);
-
-    memset(cmd, 0x00, sizeof(cmd));
-    memset(value, 0x00, sizeof(value));
-
-    sprintf((char *)value, "%d", soc);
-
-    string2ByteArray(value, cmd);
-    DisplayValueToLcm(_String_Battery, cmd, sizeof(cmd));
-}
-unsigned long GetPreChargeTimeoutValue(struct timeval _sour_time)
-{
-    struct timeval _end_time;
-    gettimeofday(&_end_time, NULL);
-
-    return 1000000 * (_end_time.tv_sec - _sour_time.tv_sec) + _end_time.tv_usec - _sour_time.tv_usec;
-}
-void ChangeTimeValue(int time)
-{
-    uint8_t cmd[6];
-    uint8_t value[6];
-
-    memset(cmd, 0x00, sizeof(cmd));
-    sprintf((char *) value, "%d", time);
-    string2ByteArray(value, cmd);
-    DisplayValueToLcm(_String_ChargeTime, cmd, sizeof(cmd));
-}
-
-void changeWeatherValue(int _weather)
-{
-	switch (_weather) {
-	case _WEATHER_TYPE_SUN:
-		ChangeDisplay2Value(_Icon_Weather,_TCC_Sun);
-		break;
-	case _WEATHER_TYPE_CLOUDY:
-		ChangeDisplay2Value(_Icon_Weather,_TCC_Cloudy);
-		break;
-	case _WEATHER_TYPE_RAIN:
-		ChangeDisplay2Value(_Icon_Weather,_TCC_Rain);
-		break;
-	case _WEATHER_TYPE_THUNDER:
-		ChangeDisplay2Value(_Icon_Weather,_TCC_Thunder);
-		break;
-	case _WEATHER_TYPE_SNOW:
-		ChangeDisplay2Value(_Icon_Weather,_TCC_Snow);
-		break;
-	case _WEATHER_TYPE_FOG:
-		ChangeDisplay2Value(_Icon_Weather,_TCC_Fog);
-		break;
-	}
-}
-void changeWeekValue(int _week)
-{
-    time_t timep;
-    struct tm* tm;
-    time(&timep);
-    timep += (ShmDcCommonData->TZOffset * 60);
-
-    tm = localtime(&timep);
-	_week = tm->tm_wday;
-	if (_week == 0 )
-		_week = 7;
-	ChangeDisplay2Value(_Icon_Week,_week);
-}
-void changeDegreeValue(int _degree)
-{
-    char value[16];
-    memset(value, 0x00, sizeof(value));
-    sprintf((char *)value,"%d",_degree);
-    DisplayValueToLcm(_String_Tempture, (uint8_t *)value, sizeof(value));
-}
-void changeDateValue(char* _date)
-{
-    time_t timep;
-    struct tm* tm;
-    time(&timep);
-    timep += (ShmDcCommonData->TZOffset * 60);
-
-    tm = localtime(&timep);
-
-    sprintf(_date, "%04d/%02d/%02d",
-        tm->tm_year + 1900,
-        tm->tm_mon + 1,
-        tm->tm_mday);
-    char value[16];
-    memset(value, 0x00, sizeof(value));
-    sprintf((char *)value,"%s",_date);
-	DisplayValueToLcm(_String_Date, (uint8_t *)value, sizeof(value));
-}
-void changeLocationValue(int _location)
-{
-	//_location+=1000;
-	//log_info("location:%d",_location);
-	ChangeDisplay2Value(_Icon_Location,(short)_location);
-}
-void ShowLineRegisterCountDown(int _show)
-{
-    if(!_show) {
-        ChangeDisplay2Value(_Icon_ScanCntDw_BG,_ICON_Empty);
-        ChangeDisplay2Value(_Icon_ScanCntDownTen, _ICON_Empty);
-        ChangeDisplay2Value(_Icon_ScanCntDownDigits, _ICON_Empty);
-        return;
-    }
-    int _ten, _digits;
-    pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(pSysInfo->CurGunSelected);
-    if (pDcChargingInfo->TimeoutFlag == Timeout_LineReigster) {
-        _ten = (TCC_LINEREGISTER_TIMEOUT - (GetClockTimeoutValue(pDcChargingInfo->ConnectorTimeout) / uSEC_VAL)) / 10;
-        _digits = (TCC_LINEREGISTER_TIMEOUT - (GetClockTimeoutValue(pDcChargingInfo->ConnectorTimeout) / uSEC_VAL)) % 10;
-        ChangeDisplay2Value(_Icon_ScanCntDw_BG,_TCC_Scan_CntDw_BG);
-        ChangeDisplay2Value(_Icon_ScanCntDownTen, (short)_TCC_CntDownNumber0+_ten);
-        ChangeDisplay2Value(_Icon_ScanCntDownDigits, (short)_TCC_CntDownNumber0+ _digits);
-    } else {
-        //log_info("Not get Line Register Count Down");
-    }
-}
-void ShowAuthorizeCountDown()
-{
-    int _ten, _digits;
-    
-    if (pSysInfo->SystemTimeoutFlag == Timeout_ScanCard) {
-        ChangeDisplay2Value(_Icon_ScanCntDw_BG,_TCC_Scan_CntDw_BG);
-        _ten = (TCC_SCANCARD_TIMEOUT - (GetClockTimeoutValue(pSysInfo->SystemTimeoutTimer) / uSEC_VAL)) / 10;
-        _digits = (TCC_SCANCARD_TIMEOUT - (GetClockTimeoutValue(pSysInfo->SystemTimeoutTimer) / uSEC_VAL)) % 10;
-        ChangeDisplay2Value(_Icon_AuthCntDownTen, (short)_TCC_CntDownNumber0 + _ten);
-        ChangeDisplay2Value(_Icon_AuthCntDownDigits, (short)_TCC_CntDownNumber0 + _digits);
-    }
-    else {
-        log_info("Not get Line Register Count Down");
-    }
-}
-
-void ShowParkingCountDown(int is_parking)
-{
-    int _ten, _digits , _hun;
-    unsigned char time_flag;
-    int TimeoutTime;
-    pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(pSysInfo->CurGunSelected);
-    if (is_parking) {
-
-        if (pSysInfo->SystemPage == _PAGE_ADD_FRIEND) {
-            time_flag = Timeout_ParkingBill;
-            TimeoutTime = TCC_PARKINGBILL_TIMEOUT;
-        } else {
-            time_flag = Timeout_ParkingSelect;
-            TimeoutTime = TCC_PARK_SELECTPAY_TIMEOUT;
-        }
-
-        if (pDcChargingInfo->TimeoutFlag == time_flag ) {
-            _hun = (TimeoutTime - (GetClockTimeoutValue(pDcChargingInfo->ConnectorTimeout) / uSEC_VAL)) / 100;
-            _ten = ((TimeoutTime - (GetClockTimeoutValue(pDcChargingInfo->ConnectorTimeout) / uSEC_VAL)) / 10)%10;
-            _digits = (TimeoutTime - (GetClockTimeoutValue(pDcChargingInfo->ConnectorTimeout) / uSEC_VAL)) % 10;
-            if (pSysInfo->SystemPage == _PAGE_ADD_FRIEND) {
-                ChangeDisplay2Value(_Icon_ParkingCntDw_BG, (short)_TCC_ParkingCntDown_BG3);
-                ChangeDisplay2Value(_Icon_ParkingCntDw_Hun, (short)_TCC_ParkingCD_0 + _hun);
-                ChangeDisplay2Value(_Icon_ParkingCntDw_Tens, (short)_TCC_ParkingCD_0 + _ten);
-                ChangeDisplay2Value(_Icon_ParkingCntDw_Digits, (short)_TCC_ParkingCD_0 + _digits);
-            } else {
-                ChangeDisplay2Value(_Icon_ParkingCntDw_BG, (short)_TCC_ParkingCntDown_BG);
-                ChangeDisplay2Value(_Icon_ParkingCntDw_Tens, (short)_TCC_ParkingCD_0 + _ten);
-                ChangeDisplay2Value(_Icon_ParkingCntDw_Digits, (short)_TCC_ParkingCD_0 + _digits);
-            }
-
-        }
-        else {
-            log_info("Not get Parking Count Down(%d)",pDcChargingInfo->TimeoutFlag);
-        }
-    } else {
-        ChangeDisplay2Value(_Icon_ParkingCntDw_BG, NULL);
-        ChangeDisplay2Value(_Icon_ParkingCntDw_Hun, NULL);
-        ChangeDisplay2Value(_Icon_ParkingCntDw_Tens, NULL);
-        ChangeDisplay2Value(_Icon_ParkingCntDw_Digits, NULL);
-    }
-}
-
-void changeGunType()
-{
-    pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(LEFT_GUN_NUM);
-    if (ShmDcCommonData->pGunInfo[LEFT_GUN_NUM].ParkingStatus) {
-        ChangeDisplay2Value(_Icon_Select_Left,_TCC_LeftParkingIdle);
-    } else if (pDcChargingInfo->CCSGunType == _TYPE_CCS1_Liquid ||
-        pDcChargingInfo->CCSGunType == _TYPE_CCS1_Natural) {
-        ChangeDisplay2Value(_Icon_Select_Left, _TCC_IDLE_LEFT_CCS1);
-
-    } else if (pDcChargingInfo->CCSGunType == _TYPE_CCS2_Liquid ||
-        pDcChargingInfo->CCSGunType == _TYPE_CCS2_Natural) {
-        ChangeDisplay2Value(_Icon_Select_Left, _TCC_IDLE_LEFT_CCS2);
-    } else if (pDcChargingInfo->Type == _Type_Chademo) {
-        ChangeDisplay2Value(_Icon_Select_Left, _TCC_IDLE_LEFT_CHAdeMo);
-    }
-
-    // Set Right Gun
-    pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(RIGHT_GUN_NUM);
-    if (ShmDcCommonData->pGunInfo[RIGHT_GUN_NUM].ParkingStatus) {
-        ChangeDisplay2Value(_Icon_Select_Right,_TCC_RightParkingIdle);
-    } else if (pDcChargingInfo->CCSGunType == _TYPE_CCS1_Liquid ||
-        pDcChargingInfo->CCSGunType == _TYPE_CCS1_Natural) {
-        ChangeDisplay2Value(_Icon_Select_Right, _TCC_IDLE_RIGHT_CCS1);
-
-    } else if (pDcChargingInfo->CCSGunType == _TYPE_CCS2_Liquid ||
-        pDcChargingInfo->CCSGunType == _TYPE_CCS2_Natural) {
-        ChangeDisplay2Value(_Icon_Select_Right, _TCC_IDLE_RIGHT_CCS2);
-    } else if (pDcChargingInfo->Type == _Type_Chademo) {
-        ChangeDisplay2Value(_Icon_Select_Right, _TCC_IDLE_RIGHT_CHAdeMo);
-    }
-}
-void ShowParkingInfo(bool is_show,uint8_t gunIndex)
-{
-    char cmd[32];
-    if (is_show) {
-        ChangeDisplay2Value(_Icon_ParkingInfo,_TCC_ParkingInfo);
-        memset(cmd, 0x00, sizeof(cmd));
-        sprintf((char *)cmd,"%s",ShmDcCommonData->ParkingInfo[gunIndex].ParkingStartTime);
-        DisplayValueToLcm(_String_ParkingStartTime, (uint8_t *)cmd, sizeof(cmd));
-        memset(cmd, 0x00, sizeof(cmd));
-        sprintf((char *)cmd,"%d",ShmDcCommonData->ParkingInfo[gunIndex].ParkingDuration);
-        DisplayValueToLcm(_String_ParkingDuration, (uint8_t *)cmd, sizeof(cmd));
-        memset(cmd, 0x00, sizeof(cmd));
-        sprintf((char *)cmd,"%d",(int)ShmDcCommonData->ParkingInfo[gunIndex].Amount);
-        DisplayValueToLcm(_String_ParkingFee, (uint8_t *)cmd, sizeof(cmd));
-    } else {
-        if (pSysInfo->SystemPage == _PAGE_BILL) {
-            ChangeDisplay2Value(_Icon_ParkingInfo,_TCC_ICON_SelectChargeMode);
-        } else if (pSysInfo->SystemPage >= _PAGE_ADD_FRIEND && pSysInfo->SystemPage <= _PAGE_AUTHORIZE) {
-            ChangeDisplay2Value(_Icon_ParkingInfo,_TCC_ICON_SelectPayMode);
-        } else {
-            ChangeDisplay2Value(_Icon_ParkingInfo,NULL);
-        }
-        memset(cmd, 0x00, sizeof(cmd));
-        DisplayValueToLcm(_String_ParkingStartTime, (uint8_t *)cmd, sizeof(cmd));
-        DisplayValueToLcm(_String_ParkingDuration, (uint8_t *)cmd, sizeof(cmd));
-        DisplayValueToLcm(_String_ParkingFee, (uint8_t *)cmd, sizeof(cmd));
-    }
-    if (pSysInfo->SystemPage >= _PAGE_BILL && pSysInfo->SystemPage <= _PAGE_SELECT_PAY)
-        ShowParkingCountDown(is_show);
-}
-int old_money = 0;
-int ClearQR_flag[2];
-void ProcessPageInfo()
-{
-    if (ShmDcCommonData->CreditCardUpload) {
-        pSysInfo->SystemPage = _PAGE_PAYING;
-    }
-    // Show Gun Working and Type
-    
-    if (pSysInfo->SystemPage == _PAGE_IDLE) {
-    	changeWeatherValue(ShmDcCommonData->WeatherID);
-    	changeWeekValue(0);
-    	changeDegreeValue((int)ShmDcCommonData->Temperature);
-    	changeDateValue(&ShmDcCommonData->PresentTime[0]);
-    	changeLocationValue(1000);
-        changeGunType();
-        ClearQR_flag[pSysInfo->CurGunSelected] = FALSE;
-    	return;
-    }
-    
-    if (pSysInfo->SystemPage == _PAGE_MAINTAIN) {
-
-        pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(LEFT_GUN_NUM);
-        if (pDcChargingInfo->CCSGunType == _TYPE_CCS1_Liquid ||
-                pDcChargingInfo->CCSGunType == _TYPE_CCS1_Natural) {
-            ChangeDisplay2Value(_Icon_ShowLeft,_TCC_ShowLeft_CCS1_Off);
-
-        } else if (pDcChargingInfo->CCSGunType == _TYPE_CCS2_Liquid ||
-                pDcChargingInfo->CCSGunType == _TYPE_CCS2_Natural) {
-            ChangeDisplay2Value(_Icon_ShowLeft,_TCC_ShowLeft_CCS2_Off);
-        } else if (pDcChargingInfo->Type == _Type_Chademo) {
-            ChangeDisplay2Value(_Icon_ShowLeft,_TCC_ShowLeft_CHAdeMo_Off);
-        }
-
-        // Set Right Gun
-        pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(RIGHT_GUN_NUM);
-        if (pDcChargingInfo->CCSGunType == _TYPE_CCS1_Liquid ||
-                pDcChargingInfo->CCSGunType == _TYPE_CCS1_Natural) {
-            ChangeDisplay2Value(_Icon_ShowRight,_TCC_ShowRight_CCS1_Off);
-
-        } else if (pDcChargingInfo->CCSGunType == _TYPE_CCS2_Liquid ||
-                pDcChargingInfo->CCSGunType == _TYPE_CCS2_Natural) {
-            ChangeDisplay2Value(_Icon_ShowRight,_TCC_ShowRight_CCS2_Off);
-        } else if (pDcChargingInfo->Type == _Type_Chademo) {
-            ChangeDisplay2Value(_Icon_ShowRight,_TCC_ShowRight_CHAdeMo_Off);
-        }
-        ChangeQrCode_Error();
-    	return;
-    }
-    showGunWorkingType();
-    for (uint8_t i = 0; i < pSysConfig->TotalConnectorCount; i++) {
-
-        if (pSysInfo->CurGunSelected == i) {
-            pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(i);
-
-            if (pDcChargingInfo->SystemStatus == S_IDLE) {
-                _everyPageRollChange = 0;
-                _Text_Running_Count = 1;
-            }
-            if (pSysInfo->SystemPage == _PAGE_AUTHORIZE) {
-                if (ShmDcCommonData->pGunInfo[i].ParkingStatus) {
-                    ChangeDisplay2Value(_Icon_Return,NULL);
-                } else {
-                    ChangeDisplay2Value(_Icon_Return,_TCC_Return);
-                }
-                ShowParkingCountDown(FALSE);
-            } else {
-                ChangeDisplay2Value(_Icon_Return,_TCC_Return);
-            }
-            switch (pSysInfo->SystemPage) {
-            case _PAGE_IDLE:
-                ShowSelectGun();
-                ClearQR_flag[i] = FALSE;
-            	break;
-            case _PAGE_SELECT_PAY:
-                if (ShmDcCommonData->pGunInfo[i].ParkingStatus) {
-                    ShowParkingInfo(true,i);
-                } else {
-                    ShowParkingInfo(false,i);
-                }
-
-            	break;
-            case _PAGE_SELECT_GUN:
-            	ShowSelectGun();
-            	ClearQR_flag[i] = FALSE;
-				break;
-            case _PAGE_BILL:
-                if (ShmDcCommonData->pGunInfo[i].ParkingStatus) {
-                    ChangeDisplay2Value(_Icon_Add_Line,_TCC_ParkingLine);
-                    ChangeDisplay2Value(_Icon_Donate,_TCC_ParkingDonate);
-                    ShowParkingInfo(true,i);
-
-                } else {
-                    ChangeDisplay2Value(_Icon_Add_Line,_TCC_GetBill);
-                    ChangeDisplay2Value(_Icon_Donate,_TCC_DonateBill);
-                    ShowParkingInfo(false,i);
-                }
-            	break;
-            case _PAGE_AUTHORIZE:
-                StartSystemTimeoutDet(Timeout_ScanCard);
-                if (ShmDcCommonData->pGunInfo[i].ParkingStatus) {
-                    ShowParkingInfo(true,i);
-                    ChangeDisplay2Value(_Icon_CreditCardFrame,_TCC_ParkingFee);
-                    ChangeChargingRateValue(ShmDcCommonData->ChargingRate,FALSE);
-                    ChangeParkingRateValue(ShmDcCommonData->ParkingRate,FALSE);
-                    ChangeParkingLeaveTime(ShmDcCommonData->ParkingLeaveTime,FALSE);
-                } else {
-                    ShowParkingInfo(false,i);
-                    ChangeDisplay2Value(_Icon_CreditCardFrame,_TCC_CardSensing_Frame);
-                    ChangeChargingRateValue(ShmDcCommonData->ChargingRate,TRUE);
-                    ChangeParkingRateValue(ShmDcCommonData->ParkingRate,TRUE);
-                    ChangeParkingLeaveTime(ShmDcCommonData->ParkingLeaveTime,TRUE);
-                }
-                ShowAuthorizeCountDown();
-
-                break;
-            case _PAGE_SENSING:
-                if (ShmDcCommonData->TradeCancel == TRUE) {
-                    TradeRunning(FALSE);
-                }
-                else
-                    TradeRunning(TRUE);
-                break;
-            case _PAGE_PLUGIN:
-            	_everyPageRollChange = 0;
-                if (ShmDcCommonData->pGunInfo[i].isParking) {
-                    ChangeDisplay2Value(_Icon_PreAuth_Complete,_TCC_ParkingLeave);
-                    ChangeParkingRateValue(ShmDcCommonData->ParkingRate,FALSE);
-                    ChangeParkingLeaveTime(ShmDcCommonData->ParkingLeaveTime,FALSE);
-                    ChangeSaleLeaveTime(ShmDcCommonData->SaleLeaveTime,TRUE);
-                } else {
-                    ChangeDisplay2Value(_Icon_PreAuth_Complete,_TCC_PaySuccess);
-                    ChangeParkingRateValue(ShmDcCommonData->ParkingRate,TRUE);
-                    ChangeParkingLeaveTime(ShmDcCommonData->ParkingLeaveTime,TRUE);
-                    ChangeSaleLeaveTime(ShmDcCommonData->SaleLeaveTime,FALSE);
-                }
-                break;
-            case _PAGE_ADD_FRIEND:
-                if(ClearQR_flag[i] == FALSE) {
-                    ClearQrCode_Idle();
-            		ClearQR_flag[i] = TRUE;
-            	}
-            	ChangeQrCode_Idle((char *)pSysConfig->SystemId);
-                if (ShmDcCommonData->pGunInfo[i].ParkingStatus) {
-                    ShowParkingInfo(true,i);
-                    ShowLineRegisterCountDown(FALSE);
-                } else {
-                    ShowLineRegisterCountDown(TRUE);
-                    ShowParkingInfo(false,i);
-                }
-
-                break;
-            case _PAGE_PRECHARGE:
-            	RefreshProgressAnimation();
-            	if (_everyPageRollChange == 0) {
-            		ChangeDisplay2Value(_Icon_Precharge,_Text_Running_Count);
-            		_Text_Running_Count >= 24 ? _Text_Running_Count = 24 : _Text_Running_Count++;
-            	}
-                break;
-            case _PAGE_CHARGING:
-                if (pDcChargingInfo->PresentChargingPower >= 0 &&
-                        pDcChargingInfo->PresentChargingPower <= POWER_MAX_KW) {
-
-                    ChangeChargingPowerValue(pDcChargingInfo->PresentChargingPower);
-                } else {
-                    ChangeChargingPowerValue(0);
-                }
-                if (pDcChargingInfo->PresentChargedEnergy >= 0.1 &&
-                        pDcChargingInfo->PresentChargedEnergy <= ENERGY_MAX_KWH) {
-
-                    ChangeChargingEnergyValue(pDcChargingInfo->PresentChargedEnergy);
-                } else {
-                    ChangeChargingEnergyValue(0);
-                }
-                if ( pDcChargingInfo->ChargingFee >= 0) {
-                    ChangeChargingFeeValue(pDcChargingInfo->ChargingFee);
-
-                }
-                if (pDcChargingInfo->RemainChargingDuration >= 0 &&
-                        pDcChargingInfo->RemainChargingDuration <= TIME_MAX_SEC) {
-                	ChangeTimeValue(pDcChargingInfo->RemainChargingDuration/60);
-                } else {
-                	ChangeTimeValue(0);
-                }
-                ChangeBattMapAndValue(pDcChargingInfo->EvBatterySoc);
-                StartSystemTimeoutDet(Timeout_ReturnViewPage);
-                break;
-            case _PAGE_COMPLETE:
-            case _PAGE_PAYFAIL:
-
-                if (pDcChargingInfo->PresentChargedEnergy >= 0.1 &&
-                        pDcChargingInfo->PresentChargedEnergy <= ENERGY_MAX_KWH) {
-                    ChangeChargingEnergyValue(pDcChargingInfo->PresentChargedEnergy);
-                } else {
-                    ChangeChargingEnergyValue(0);
-                }
-
-				ChangeChargingFeeValue(ShmDcCommonData->TransactionInfo[i].Amount);
-                ChangeCarBonValue(pDcChargingInfo->PresentChargedEnergy);
-                ChangeBattMapAndValue(pDcChargingInfo->EvBatterySoc);
-                if (ShmDcCommonData->pGunInfo[i].ParkingStatus) {
-                    ChangeParkingRateValue(ShmDcCommonData->ParkingRate,FALSE);
-                    ChangeDisplay2Value(_Icon_CompleteBtn,_TCC_ParkingComplete);
-                } else {
-                    ChangeParkingRateValue(ShmDcCommonData->ParkingRate,TRUE);
-                    ChangeDisplay2Value(_Icon_CompleteBtn,_TCC_NoParkingComplete);
-                }
-                //StartSystemTimeoutDet(Timeout_ReturnViewPage);
-				
-                break;
-
-            case _PAGE_PLUGOUT:
-                if (ShmDcCommonData->pGunInfo[i].ParkingStatus) {
-                    ChangeParkingRateValue(ShmDcCommonData->ParkingRate,FALSE);
-                    ChangeDisplay2Value(_Icon_CompleteBtn,_TCC_ParkingComplete);
-                } else {
-                    ChangeParkingRateValue(ShmDcCommonData->ParkingRate,TRUE);
-                    ChangeDisplay2Value(_Icon_CompleteBtn,NULL);
-                }
-            	break;
-            case _PAGE_PAYING:
-                ChangeDisplay2Value(_Icon_Ani_Dot, 1);
-                if (ShmDcCommonData->CreditCardUpload) {
-                    ChangeDisplay2Value(_Icon_Uploading, _TCC_Uploading);
-                    ChangeDisplay2Value(_Icon_Paying, _ICON_Empty);
-                } else {
-                    if (ShmDcCommonData->StopCharge[i]) {
-                        ChangeDisplay2Value(_Icon_Uploading, _ICON_Empty);
-                        ChangeDisplay2Value(_Icon_Paying, _TCC_Paying);
-                    } else if (ShmDcCommonData->pGunInfo[i].isParking){
-                        ChangeDisplay2Value(_Icon_Uploading, _TCC_WaitParkInfo);
-                        ChangeDisplay2Value(_Icon_Paying, _ICON_Empty);
-                    }
-                }
-            	break;
-            case _PAGE_EXIT:
-                
-                break;
-            case _PAGE_LINEPAYING:
-                StartSystemTimeoutDet(Timeout_LINEPAYING);
-                break;
-            case _PAGE_MAINTAIN:
-                ChangeQrCode_Error();
-                break;
-            }
-        }
-    }
-}
-
-/*
-void InformationShow()
-{
-    is_show = true;
-    if (_showInformIndex == 0 ) {
-        pSysInfo->PageIndex = __SHOW_CABIENT_VERSION;
-    } else {
-        pSysInfo->PageIndex = __SHOW_DISPENSER_VERASION;
-        ShowDispenserVersion();
-    }
-}
-*/
-
-void DefautLayOut()
-{
-	int i;
-	for (i = 0 ; i <= 0x5C ; i+=2 ) {
-		ChangeDisplay2Value(0x1000+i,1);
-		if (i==0x28 || i ==0x2A)
-			continue;
-	}
-	ChangeDisplay2Value(_Icon_MobilePay,0);
-	ChangeDisplay2Value(_Icon_CardPay,0);
-	ChangeDisplay2Value(0x5000,1);
-    //ChangeDisplay2Value(_QRCode_Service, 1);
-	ShowSelectGun();
-}
-/*
-static int InitialRfidPort(void)
-{
-    int fd = open(rfidPortName, O_RDWR);
-    struct termios tios;
-    struct AlarmCodeData *pAlarmCode = (struct AlarmCodeData *)GetShmAlarmCodeData();
-
-    if (fd != FAIL) {
-        ioctl (fd, TCGETS, &tios);
-        tios.c_cflag = B115200 | CS8 | CLOCAL | CREAD;
-        tios.c_lflag = 0;
-        tios.c_iflag = 0;
-        tios.c_oflag = 0;
-        tios.c_cc[VMIN] = 0;
-        tios.c_cc[VTIME] = (uint8_t) 1;
-        tios.c_lflag = 0;
-        tcflush(fd, TCIFLUSH);
-        ioctl(fd, TCSETS, &tios);
-    }
-
-    if (fd < 0) {
-        pAlarmCode->AlarmEvents.bits.RfidModuleCommFail = 1;
-    }
-
-    return fd;
-}
-*/
-void DemoFunction(int index)
-{
-    int i;
-    showGunWorkingType();
-    switch (index) {
-    case 1:   // _PAGE_IDLE
-        /*
-        for (i = 0; i <= 100; i++) {
-            changeWeatherValue(i / 20);
-            ChangeDisplay2Value(_Icon_Week, i / 15);
-            changeDegreeValue(i);
-            sprintf(text, "20%02d/%02d/%02d %02d:%02d:%02d", i, i, i, i, i, i);
-            DisplayValueToLcm(_String_Date, (uint8_t*)text, 30);
-            usleep(100000);
-        }
-        */
-        break;
-    case 3:
-        ChangeQrCode_Idle((char*)pSysConfig->SystemId);
-        sleep(3);
-        break;
-    case 4:  //_PAGE_ADD_FRIEND
-        for (i = 0; i <= 10; i++) {
-            ChangeDisplay2Value(_Icon_ScanCntDownTen, (short)_TCC_CntDownNumber0 + i);
-            ChangeDisplay2Value(_Icon_ScanCntDownDigits, (short)_TCC_CntDownNumber0 + i);
-            usleep(100000);
-        }
-        break;
-    case 7:  //_PAGE_AUTHORIZE
-        for (i = 0; i < 10; i++) {
-            ChangeChargingRateValue(i+i*10,TRUE);
-            ChangeDisplay2Value(_Icon_AuthCntDownTen, (short)_TCC_CntDownNumber0 + i);
-            ChangeDisplay2Value(_Icon_AuthCntDownDigits, (short)_TCC_CntDownNumber0 + i);
-            usleep(100000);
-        }
-        break;
-    case 8:  //_PAGE_SENSING
-        for (i = 0; i < 10; i++) {
-            ChangeDisplay2Value(_Icon_CancelCntDownTen, (short)(_TCC_CancelNum_0 + i));
-            ChangeDisplay2Value(_Icon_CancelCntDownDigits, (short)(_TCC_CancelNum_0 + i));
-            usleep(100000);
-        }
-        break;
-    case 10:  //_PAGE_PRECHARGE
-        for (i = 1; i <= 24; i++) {
-            ChangeDisplay2Value(_Icon_Precharge, i);
-            usleep(100000);
-        }
-        break;
-    case 11:  //_PAGE_CHARGING
-        for (i = 0; i <= 100; i++) {
-            ChangeChargingPowerValue(i);
-            ChangeChargingEnergyValue(i);
-            ChangeChargingFeeValue(i);
-            ChangeTimeValue(i);
-            ChangeBattMapAndValue(i);
-            usleep(100000);
-        }
-        break;
-    case 13:  //_PAGE_PAYING
-        break;
-    case 14:  //_PAGE_COMPLETE
-    case 20:  //_PAGE_PAYFAIL
-        for (i = 0; i <= 100; i++) {
-            ChangeChargingEnergyValue(i);
-            ChangeChargingFeeValue(i);
-            ChangeCarBonValue(i*2);
-            ChangeBattMapAndValue(i);
-            usleep(100000);
-        }
-        break;
-    }
-    sleep(1);
-}
-int main(void)
-{
-    bool defaulttext = false;
-    if (CreateAllCsuShareMemory() == FAIL) {
-        log_error("create share memory error");
-        return FAIL;
-    }
-
-    MappingGunChargingInfo("LCM Control Task");
-
-    pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
-    pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
-    pSysWarning = (struct WARNING_CODE_INFO *)GetShmSysWarningInfo();
-    ShmFanModuleData = (struct FanModuleData *)GetShmFanModuleData();;
-    ShmPrimaryMcuData = (struct PrimaryMcuData *)GetShmPrimaryMcuData();
-    ShmSelectGunInfo = (SelectGunInfo *)GetShmSelectGunInfo();
-    ShmDcCommonData = (DcCommonInfo *)GetShmDcCommonData();
-    ShmOCPP16Data = (struct OCPP16Data *)GetShmOCPP16Data();
-    struct StatusCodeData *ShmStatusCodeData = (struct StatusCodeData *)GetShmStatusCodeData();;
-
-    _port = CreateCommunicationLcmPort();
-    uint8_t changeWarningPriority = 0;
-    uint8_t curWarningCount = 255;
-    uint8_t light = 0x64;
-    ShmDcCommonData->BackLight = light;
-    ChangeBackLight(light);
-    _totalCount = pSysConfig->TotalConnectorCount;
-    _everyPageRollChange = 0;
-    //Initialization();
-
-    //printf("_LCM_COMPLETE ");
-    //ChangeToOtherPage(_LCM_COMPLETE);
-    DefautLayOut();
-    //return 0;
-    uint8_t index = 1;
-
-    ShmDcCommonData->PSU_Number = 12;
-    /*
-    CardReadFd = InitialRfidPort();
-    if (CardReadFd <0) {
-    	log_info("Card Read Port open fail!");
-    }*/
-
-    CheckLCMPressed();
-
-    while (_port != -1) {
-        if (strcmp((char *)pSysInfo->LcmHwRev, moduleName) != 0x00) {
-            GetCurrentPage();
-            sleep(1);
-
-            ShmStatusCodeData->AlarmCode.AlarmEvents.bits.LcmModuleCommFail = true;
-        } else {
-            UpdateLcmFunction(ShmDcCommonData,_port);
-
-            if (ShmDcCommonData->BackLight != light) {
-                ChangeBackLight(ShmDcCommonData->BackLight);
-                light = ShmDcCommonData->BackLight;
-                log_info("Set Backlight:%d",light);
-            }
-            ///*
-            ShmStatusCodeData->AlarmCode.AlarmEvents.bits.LcmModuleCommFail = false;
-            // 頁面資訊處理
-            if (!ShmDcCommonData->lcmtest)
-                ProcessPageInfo();
-            else
-                pSysInfo->SystemPage = index;
-
-            // 換頁處理
-            //GetCurrentPage(); //DS60-120 add
-            /*
-            if (pSysConfig->ShowInformation == YES && pSysInfo->SystemPage == _PAGE_AUTHORIZE) {
-                InformationShow();
-                ChangeToOtherPage(pSysInfo->PageIndex);
-                usleep(100000);
-                continue;
-            } else {
-                if (is_show)
-                    _showInformIndex >= 1 ? _showInformIndex = 0 : _showInformIndex++;
-                is_show = false;
-            }*/
-            GetCurrentPage(); //DS60-120 add
-
-            ChangeCurPage();
-            changeWarningPriority >= 30 ? changeWarningPriority = 0 : changeWarningPriority++;
-            if (ShmDcCommonData->lcmtest) {
-                DemoFunction(index);
-                index >= 20 ? index = 1 : index++;
-            }
-            usleep(10000); //*/
-
-            /*
-            GetCurrentPage();
-            ChangeCurPage();
-            usleep(10000);
-            //*/
-        }
-    } //while
-
-    ShmStatusCodeData->AlarmCode.AlarmEvents.bits.LcmModuleCommFail = true;
-
-    log_info("Close LCM Uart Port");
-    CloseCommunicationLcmPort();
-
-    return FAIL;
-}
+#include <stdio.h>      /*標準輸入輸出定義*/
+#include <stdlib.h>     /*標準函數庫定義*/
+#include <stdint.h>
+#include <string.h>
+#include <unistd.h>
+#include <termios.h>
+#include <fcntl.h>
+#include <time.h>
+
+#include <sys/ioctl.h>
+#include <sys/timeb.h>
+
+#include "Module_LcmControl.h"
+#include "../Log/log.h"
+#include "../ShareMemory/shmMem.h"
+#include "../Define/define.h"
+#include "../Config.h"
+#include "../SelectGun/SelectGun.h"
+#include "../CSU/main.h"
+#include "../timeout.h"
+
+#define uSEC_VAL                                (1000000)
+
+//------------------------------------------------------------------------------
+//struct SysConfigAndInfo         *ShmSysConfigAndInfo;
+//struct StatusCodeData           *ShmStatusCodeData;
+static struct SysConfigData *pSysConfig = NULL;
+static struct SysInfoData *pSysInfo = NULL;
+static struct WARNING_CODE_INFO *pSysWarning = NULL;
+static struct OCPP16Data *ShmOCPP16Data = NULL;
+static struct FanModuleData *ShmFanModuleData;
+static struct PrimaryMcuData *ShmPrimaryMcuData;
+static SelectGunInfo *ShmSelectGunInfo = NULL;
+static struct ChargingInfoData *pDcChargingInfo = NULL;
+static DcCommonInfo *ShmDcCommonData            = NULL;
+//int CardReadFd = -1;
+
+short _currentPage              = _PAGE_NONE;
+uint8_t _totalCount;
+uint8_t _showInformIndex = 0;
+float ChargeMaxPower_0 = 0;
+float ChargeMaxPower_1 = 0;
+bool _battery_display_ani = false;
+int _port;
+//char* pPortName         = "/dev/ttyO2";
+char *pPortName           = "/dev/ttyS3";
+char *moduleName          = "DMT80480T070_09WT";
+bool is_show = false;
+bool is_stop = false;
+uint8_t _everyPageRollChange;
+uint8_t _btn_press = 0;
+short _btn_press_id = 0;
+uint8_t _btn_press_count = 0;
+int _Text_Running_Count = 1;
+int Battery_Test = 0;
+extern void UpdateLcmFunction(DcCommonInfo *ShmDcCommonData,int _lcmport);
+//==========================================
+// Open and Close RS232 and R/W
+//==========================================
+void AuthorizingStart(void)
+{
+    ShmOCPP16Data->SpMsg.bits.AuthorizeReq = YES;
+    pSysInfo->AuthorizeFlag = YES;
+}
+void GetClockTime(struct timespec *_now_time, void *null)
+{
+    clock_gettime(CLOCK_MONOTONIC, _now_time);
+}
+void StartSystemTimeoutDet(uint8_t flag)
+{
+    if (pSysInfo->SystemTimeoutFlag != flag) {
+        GetClockTime(&pSysInfo->SystemTimeoutTimer, NULL);
+    }
+    pSysInfo->SystemTimeoutFlag = flag;
+}
+
+void StopSystemTimeoutDet(void)
+{
+    GetClockTime(&pSysInfo->SystemTimeoutTimer, NULL);
+    pSysInfo->SystemTimeoutFlag = Timeout_None;
+}
+
+void StartGunInfoTimeoutDet(uint8_t gunIndex, uint8_t flag)
+{
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+
+    if (gunIndex < pSysConfig->TotalConnectorCount) {
+        if (pDcChargingInfo->TimeoutFlag != flag) {
+            GetClockTime(&pDcChargingInfo->ConnectorTimeout, NULL);
+        }
+        pDcChargingInfo->TimeoutFlag = flag;
+    }
+}
+
+void StopGunInfoTimeoutDet(uint8_t gunIndex)
+{
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+
+    if (gunIndex < pSysConfig->TotalConnectorCount) {
+        pDcChargingInfo->TimeoutFlag = Timeout_None;
+    }
+}
+unsigned long GetClockTimeoutValue(struct timespec _start_time)
+{
+    struct timespec ts_end;
+    unsigned long ret = 0;
+
+    clock_gettime(CLOCK_MONOTONIC, &ts_end);
+
+    ret = ((unsigned long)(ts_end.tv_sec - _start_time.tv_sec) * 1000000) + ((unsigned long)((ts_end.tv_nsec / 1000) - (_start_time.tv_nsec/ 1000)));
+
+    return ret;
+}
+int CreateCommunicationLcmPort()
+{
+    int fd;
+    struct termios tios;
+
+    fd = open(pPortName, O_RDWR);
+    if (fd <= 0) {
+        log_error("open /dev/ttyS3 NG ");
+        return -1;
+    }
+    ioctl(fd, TCGETS, &tios);
+    tios.c_cflag = B115200 | CS8 | CLOCAL | CREAD;
+    tios.c_lflag = 0;
+    tios.c_iflag = 0;
+    tios.c_oflag = 0;
+    tios.c_cc[VMIN] = 0;
+    tios.c_cc[VTIME] = (uint8_t) 5;
+    tios.c_lflag = 0;
+    tcflush(fd, TCIFLUSH);
+    ioctl(fd, TCSETS, &tios);
+
+    return fd;
+}
+bool isChargingEnd(gunIndex)
+{
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+    if (pDcChargingInfo->SystemStatus == S_COMPLETE || pDcChargingInfo->SystemStatus == S_ALARM) {
+        return TRUE;
+    } else {
+        return FALSE;
+    }
+}
+void CloseCommunicationLcmPort()
+{
+    close(_port);
+}
+
+void setSelGunWaitToAuthor(uint8_t curSel)
+{
+    if (curSel == LEFT_GUN_NUM && ShmSelectGunInfo->SelGunInfo.LeftGun == SEL_GUN_CONFIRM) {
+        ShmSelectGunInfo->SelGunInfo.LeftGun = SEL_GUN_ATHOR;
+        log_info("setSelGunWaitToAuthor left");
+
+    } else if (curSel == RIGHT_GUN_NUM && ShmSelectGunInfo->SelGunInfo.RightGun == SEL_GUN_CONFIRM) {
+        ShmSelectGunInfo->SelGunInfo.RightGun = SEL_GUN_ATHOR;
+        log_info("setSelGunWaitToAuthor right");
+
+    }
+}
+void confirmSelGun(uint8_t selGun)
+{
+    if (selGun == LEFT_GUN_NUM) {
+        ShmSelectGunInfo->SelGunInfo.LeftGun = SEL_GUN_CONFIRM;
+        //printf("confirmSelGun left");
+    } else if (selGun == RIGHT_GUN_NUM) {
+        ShmSelectGunInfo->SelGunInfo.RightGun = SEL_GUN_CONFIRM;
+        //printf("confirmSelGun right");
+    }
+    //changeLcmPage(_PAGE_PLUGIN);
+
+    //StartGunInfoTimeoutDet(selGun, Timeout_SelectGun);
+    //StartSystemTimeoutDet(Timeout_ReturnViewPage);
+}
+
+void WriteCmdToLcm(uint8_t *cmd, uint8_t cmdLen)
+{
+    int len = write(_port, cmd, cmdLen);
+    if (len < sizeof(cmd)) {
+        log_error("Write cmd to LCM Failure. ");
+    }
+}
+void ReadMsgFromLcm(uint8_t* msg, uint8_t readLen)
+{
+    read(_port, msg, readLen);
+
+    //  5a : CMD_TITLE_1
+    //  a5 : CMD_TITLE_2
+    //  5
+    //  81 : CMD_WRITE
+    //  3  : CMD_REGISTER
+    //  2  : Data length
+    //  0  : High byte
+    //  1  : Low byte
+
+    //  printf("-------------------------------------------- \n");
+    //  printf("msg = %x \n", *msg);            // A5
+    //  printf("msg = %x \n", *(msg + 1));      // 5A
+    //  printf("msg = %x \n", *(msg + 2));      // Len : [3] ~ [6] + Data Len
+    //  printf("msg = %x \n", *(msg + 3));      // cmd : 0x83
+    //  printf("msg = %x \n", *(msg + 4));      // addr : H
+    //  printf("msg = %x \n", *(msg + 5));      // addr : L
+    //  printf("msg = %x \n", *(msg + 6));      // Data Len
+    //
+    //  printf("msg = %x \n", *(msg + 7));
+    //  printf("msg = %x \n", *(msg + 8));
+    //  printf("msg = %x \n", *(msg + 9));
+    //  printf("msg = %x \n", *(msg + 10));
+    //  printf("msg = %x \n", *(msg + 11));
+    //  printf("msg = %x \n", *(msg + 12));
+    //  printf("msg = %x \n", *(msg + 13));
+    //  printf("msg = %x \n", *(msg + 14));
+        /*
+        for(uint8_t i = 0 ; i<readLen+3; i++) {
+            log_info("Read data[%d]:0x%x",i,msg[i]);
+        }*/
+
+    if (*msg == CMD_TITLE_1 && *(msg + 1) == CMD_TITLE_2)
+    {
+        if (*(msg + 3) == CMD_WRITE)
+        {
+            switch (*(msg + 4))
+            {
+            case CMD_REGISTER:
+            {
+                // 頁面
+                if (strcmp((char*)pSysInfo->LcmHwRev, "") != EQUAL)
+                    strcpy((char*)pSysInfo->LcmHwRev, moduleName);
+
+                _currentPage = *(msg + 7);
+                log_info("Current Page:%d", _currentPage);
+                //                  if (_currentPage != 1 && _currentPage != 5 && _currentPage != 6 && _currentPage != 7 && _currentPage != 8)
+                //                      printf("_currentPage = %d \n", _currentPage);
+            }
+            break;
+            }
+        } else if (*(msg + 3) == CMD_MULTI_READ)
+        {
+            short key = ((short)(*(msg + 4) << 8) + *(msg + 5));
+            if (strcmp((char*)pSysInfo->LcmHwRev, "") != EQUAL)
+                strcpy((char*)pSysInfo->LcmHwRev, moduleName);
+            if (key == 0x0014)
+                _currentPage = *(msg + 8);
+            if (key == 0x0031) {
+                log_info("Get LCM Backlight change to 0x%x", *(msg + 8));
+            }
+            if (key >= _Touch_IDLE && key <= _Touch_Parking_Complete) {
+
+                _btn_press_id = key;
+                _btn_press = *(msg + 8);
+            }
+            //          switch ((unsigned short) (*(msg + 4) << 8) + (unsigned short) *(msg + 5))
+            //          {
+            //              case BUTTON_GUN_INDEX:
+            //              {
+            //                  // 當前選的槍號
+            //                  _curGunIndex = (*(msg + 8));
+            //              }
+            //              break;
+            //          }
+        }
+    }
+}
+void GetDeviceInfoStatus(short address, uint8_t len)
+{
+    uint8_t cmd[8];
+    memset(cmd, 0x00, sizeof(cmd));
+    uint8_t msg[11];
+    memset(msg, 0x00, sizeof(msg));
+
+    cmd[0] = CMD_TITLE_1;
+    cmd[1] = CMD_TITLE_2;
+    cmd[2] = 0x04;
+    cmd[3] = CMD_MULTI_READ;
+    cmd[4] = (address >> 8) & 0xff;
+    cmd[5] = (address >> 0) & 0xff;
+    cmd[6] = len;
+
+    WriteCmdToLcm(cmd, ARRAY_SIZE(cmd));
+    usleep(1000);
+    ReadMsgFromLcm(msg, ARRAY_SIZE(msg));
+}
+
+void DisplayValueToLcm(short address, uint8_t* data, uint8_t len)
+{
+
+    uint8_t cmd[256];
+    memset(cmd, 0x00, sizeof(cmd));
+    uint8_t msg[9];
+    memset(msg, 0x00, sizeof(msg));
+
+    cmd[0] = CMD_TITLE_1;
+    cmd[1] = CMD_TITLE_2;
+    cmd[2] = 0x03 + len;
+    cmd[3] = CMD_MULTI_WRITE;
+    cmd[4] = address >> 8;
+    cmd[5] = address & 0x00FF;
+
+    for (uint8_t count = 0; count < len; count++)
+    {
+        cmd[6 + count] = *(data + count);
+    }
+
+    WriteCmdToLcm(cmd, cmd[2] + 3);
+    usleep(10000);
+    ReadMsgFromLcm(msg, ARRAY_SIZE(msg));
+}
+
+void ChangeDisplay2Value(short address, short value)
+{
+    uint8_t data[2];
+    data[0] = value >> 8;
+    data[1] = value & 0x00FF;
+    //log_info("Addr:0x%x, value:%d",address,value);
+    DisplayValueToLcm(address, data, sizeof(data));
+}
+void TradeRunning(uint8_t _run)
+{
+    if (_run == TRUE) {
+        ChangeDisplay2Value(_Icon_PreAuth, 1);
+        ChangeDisplay2Value(_Icon_Ani_Dot, 1);
+        ChangeDisplay2Value(_Icon_CountDownBG, 0);
+        ChangeDisplay2Value(_Icon_CancelCntDownTen, 0);
+        ChangeDisplay2Value(_Icon_CancelCntDownDigits, 0);
+        ChangeDisplay2Value(_Icon_PreAuthWord, _TCC_PreAuthWord);
+    }
+    else {
+        ChangeDisplay2Value(_Icon_PreAuth, _TCC_TradeCancelString);
+        ChangeDisplay2Value(_Icon_Ani_Dot, 0);
+        ChangeDisplay2Value(_Icon_PreAuthWord, 0);
+        ChangeDisplay2Value(_Icon_CountDownBG, _TCC_TradeCancelFrame);
+        //log_info("SystemTimeoutFlag:%d", pSysInfo->SystemTimeoutFlag);
+        if (pSysInfo->SystemTimeoutFlag == Timeout_TradeCancel) {
+            unsigned long _time = TCC_TRADECANCEL_TIMEOUT-(GetClockTimeoutValue(pSysInfo->SystemTimeoutTimer) / uSEC_VAL);
+            ChangeDisplay2Value(_Icon_CancelCntDownTen, (short)(_TCC_CancelNum_0 + (_time / 10)));
+            ChangeDisplay2Value(_Icon_CancelCntDownDigits, (short)(_TCC_CancelNum_0 + (_time % 10)));
+        }
+
+    }
+}
+
+static void systemPageRestoreInit(void)
+{
+    int is_idle = TRUE;
+    int gunIndex;
+    for (gunIndex = 0; gunIndex < pSysConfig->TotalConnectorCount; gunIndex++) {
+        pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(gunIndex);
+        // 檢查電樁狀態是否為idle狀態
+        if ((pDcChargingInfo->SystemStatus >= S_AUTHORIZING &&
+            pDcChargingInfo->SystemStatus <= S_RESERVATION) ||
+            (pDcChargingInfo->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
+                pDcChargingInfo->SystemStatus <= S_CCS_PRECHARGE_ST0)) {
+            is_idle = FALSE;
+        }
+    }
+    if (is_idle)
+        pSysInfo->SystemPage = _PAGE_IDLE;
+    else
+        pSysInfo->SystemPage = _PAGE_SELECT_GUN;
+}
+
+void CheckIdlePress()
+{
+    systemPageRestoreInit();
+    log_info("IDLE Enter Select Gun Page");
+}
+void CheckReturnPress()
+{
+	int i;
+	pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(pSysInfo->CurGunSelected);
+	//pDcChargingInfo->SystemStatus = S_IDLE;
+    if (pSysInfo->SystemPage >= _PAGE_BILL && pSysInfo->SystemPage <= _PAGE_PLUGIN ||
+        pSysInfo->SystemPage == _PAGE_AUTHORIZE_FAIL || pSysInfo->SystemPage == _PAGE_DONATE_RIGHT) {
+        if (pSysInfo->SystemPage == _PAGE_AUTHORIZE && ShmDcCommonData->pGunInfo[pSysInfo->CurGunSelected].isParking) {
+            log_info("Parking Status cann't press return button");
+            return;
+        }
+        ShmDcCommonData->OperateIDLE[pSysInfo->CurGunSelected] = 1;
+        StopGunInfoTimeoutDet(pSysInfo->CurGunSelected);
+        ShmDcCommonData->pGunInfo[pSysInfo->CurGunSelected].GetParkingBill = FALSE;
+        ShmDcCommonData->pGunInfo[pSysInfo->CurGunSelected].isParking = FALSE;
+        log_info("Operate return to IDLE");
+    }
+    // Cancel Trade
+    if (ShmDcCommonData->pGunInfo[pSysInfo->CurGunSelected].ParkingStatus) {
+        ShmDcCommonData->pGunInfo[pSysInfo->CurGunSelected].GetParkingBill = FALSE;
+        //if (pSysInfo->SystemPage == _PAGE_AUTHORIZE) {
+            log_info("Press Return button Cancel Sale");
+            ShmDcCommonData->TradeCancel = TRUE;
+            pSysInfo->SystemPage = _PAGE_SENSING;
+            StopGunInfoTimeoutDet(pSysInfo->CurGunSelected);
+            StartSystemTimeoutDet(Timeout_TradeCancel);
+            for (i = 0; i <= 60; i++) {
+            if (ShmDcCommonData->pGunInfo[pSysInfo->CurGunSelected].ParkingStatus == _TCC_PARKING_OCCUPENCY_Ready ||
+                ShmDcCommonData->ParkingInfo[pSysInfo->CurGunSelected].DeductResult == _DEDUCT_SALE_PASS)
+                break;
+                sleep(1);
+            }
+        //}
+        ShmDcCommonData->TradeCancel = FALSE;
+        StopSystemTimeoutDet();
+        systemPageRestoreInit();
+        return;
+    } else if ( pDcChargingInfo->SystemStatus == S_AUTHORIZING || 
+        ((pDcChargingInfo->SystemStatus == S_IDLE || pDcChargingInfo->SystemStatus == S_RESERVATION ) &&
+            pSysInfo->SystemPage == _PAGE_AUTHORIZE)) {
+        log_info("Press Return button cancel PreAuth");
+        ShmDcCommonData->TradeCancel = TRUE;
+        pSysInfo->SystemPage = _PAGE_SENSING;
+        StopGunInfoTimeoutDet(pSysInfo->CurGunSelected);
+        StartSystemTimeoutDet(Timeout_TradeCancel);
+        for (i = 0; i <= 30; i++) {
+            if (ShmDcCommonData->PreAuth_Config == _CREDITCARD_IDLE)
+                break;
+            sleep(1);
+        }
+
+        ShmDcCommonData->PreAuth_Result = 0;
+        ShmDcCommonData->AuthPass_flag[pSysInfo->CurGunSelected] = FALSE;
+        
+        if (strcmp(ShmDcCommonData->TransactionInfo[pSysInfo->CurGunSelected].pCreditCard.VemData, "") != 0) {
+            ShmDcCommonData->PreAuth_Config = _CREDITCARD_CANCEL;
+            ShmDcCommonData->PreAuth_Result = 0;
+            for (i = 0; i <= 30; i++) {
+                if (ShmDcCommonData->PreAuth_Config == _CREDITCARD_IDLE)
+                    break;
+                sleep(1);
+            }
+            ShmDcCommonData->PreAuth_Result = 0;
+        }
+        StopSystemTimeoutDet();
+
+        pDcChargingInfo->SystemStatus = S_IDLE;
+        systemPageRestoreInit();
+		strcpy((char *)pSysConfig->UserId, "");
+		return;
+	}
+
+	if ( pSysInfo->SystemPage == _PAGE_EXIT ) {
+        StopGunInfoTimeoutDet(pSysInfo->CurGunSelected);
+		pDcChargingInfo->SystemStatus = S_IDLE;
+
+		return;
+	}
+
+    if (pSysInfo->SystemPage == _PAGE_AUTHORIZE)
+        pSysInfo->SystemPage = _PAGE_SELECT_PAY;
+    else
+        systemPageRestoreInit();
+}
+void CheckStopPress()
+{
+	//ChangeDisplay2Value(_ConfirmStopIcon,is_stop);
+	if (pSysInfo->CurGunSelected == LEFT_GUN_NUM)
+		pSysInfo->SystemPage = _PAGE_STOP_CONFIRM_LEFT;
+	else
+		pSysInfo->SystemPage = _PAGE_STOP_CONFIRM_RIGHT;
+}
+void CheckStopConfirmPress()
+{
+	pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(pSysInfo->CurGunSelected);
+	pDcChargingInfo->SystemStatus = S_TERMINATING;
+	pSysInfo->SystemPage = _PAGE_PAYING;
+    is_stop = TRUE;
+    /*
+	//ShmDcCommonData->StopCharge[pSysInfo->CurGunSelected] = TRUE;
+    if (ShmDcCommonData->is_AutoStart[pSysInfo->CurGunSelected] ||
+        ShmDcCommonData->is_RemoteStart[pSysInfo->CurGunSelected]) {
+        pSysInfo->SystemPage = _PAGE_COMPLETE;
+        return;
+    }
+    */
+}
+void CheckStopCancelPress()
+{
+	//ChangeDisplay2Value(_ConfirmStopIcon,is_stop);
+	pSysInfo->SystemPage = _PAGE_CHARGING;
+    is_stop = FALSE;
+}
+void CheckConfirmGun(uint8_t gunIndex)
+{
+    pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(gunIndex);
+    if (pDcChargingInfo->SystemStatus == S_RESERVATION) {
+        log_info("Reservation can't select");
+        return;
+    }
+
+    //log_info("Confirm Gun%d",gunIndex);
+	pSysInfo->CurGunSelected = gunIndex;
+    if (ShmDcCommonData->pGunInfo[gunIndex].ParkingStatus) {
+
+        if (pDcChargingInfo->SystemStatus == S_IDLE)
+            ShmDcCommonData->pGunInfo[gunIndex].ReqParkingBill = TRUE;
+        //else if (isChargingEnd(gunIndex)) {
+        //}
+        if (pDcChargingInfo->SystemStatus == S_COMPLETE || pDcChargingInfo->SystemStatus == S_ALARM) {
+            if (ShmDcCommonData->PayPass_flag[gunIndex] == TRUE)
+                pSysInfo->SystemPage = _PAGE_COMPLETE;
+            else {
+                if (pDcChargingInfo->Replug_flag)
+                    pSysInfo->SystemPage = _PAGE_PLUGOUT;
+                else
+                    pSysInfo->SystemPage = _PAGE_PAYFAIL;
+            }
+        } else {
+            pSysInfo->SystemPage = _PAGE_PAYING;
+        }
+        
+    } else {
+	    pSysInfo->SystemPage = _PAGE_BILL;
+    }
+}
+void CheckDonateBill(uint8_t gunIndex)
+{
+	if (gunIndex == LEFT_GUN_NUM) {
+		pSysInfo->SystemPage = _PAGE_DONATE_LEFT;
+	} else
+		pSysInfo->SystemPage = _PAGE_DONATE_RIGHT;
+}
+void CheckDonateYes()
+{
+    if (ShmDcCommonData->pGunInfo[pSysInfo->CurGunSelected].ParkingStatus) {
+        StopGunInfoTimeoutDet(pSysInfo->CurGunSelected);
+        StartGunInfoTimeoutDet(pSysInfo->CurGunSelected, Timeout_ParkingSelect);
+        ShmDcCommonData->ParkingInfo[pSysInfo->CurGunSelected].IsDonateInvoice = TRUE;
+    } else {
+	    ShmDcCommonData->TransactionInfo[pSysInfo->CurGunSelected].IsDonateInvoice = TRUE;
+    }
+	pSysInfo->SystemPage = _PAGE_SELECT_PAY;
+
+}
+void CheckDonateNo()
+{
+    if (ShmDcCommonData->pGunInfo[pSysInfo->CurGunSelected].ParkingStatus) {
+        StopGunInfoTimeoutDet(pSysInfo->CurGunSelected);
+        StartGunInfoTimeoutDet(pSysInfo->CurGunSelected, Timeout_ParkingSelect);
+        ShmDcCommonData->ParkingInfo[pSysInfo->CurGunSelected].IsDonateInvoice = FALSE;
+    } else {
+        StartSystemTimeoutDet(Timeout_AddLine);
+        ShmDcCommonData->TransactionInfo[pSysInfo->CurGunSelected].IsDonateInvoice = FALSE;
+    }
+	pSysInfo->SystemPage = _PAGE_BILL;
+}
+void CheckPayCreditCard()
+{
+    //ShmDcCommonData->LineStatus[pSysInfo->CurGunSelected] = 0;
+    pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(pSysInfo->CurGunSelected);
+    // 使用者進入線上支付,禁止使用者使用刷卡機
+    if (ShmDcCommonData->TransactionInfo[pSysInfo->CurGunSelected].LineStatus == _LINE_PAY_OPERATE ||
+        pDcChargingInfo->SystemStatus == S_RESERVATION ) {
+        pSysInfo->SystemPage = _PAGE_LINEPAYING;
+        StartSystemTimeoutDet(Timeout_LINEPAYING);
+        log_info("Some one online operate");
+        return;
+    }
+    ShmDcCommonData->TradeCancel = FALSE;
+
+    if (ShmDcCommonData->pGunInfo[pSysInfo->CurGunSelected].ParkingStatus) {
+        if ((pDcChargingInfo->SystemStatus == S_IDLE || isChargingEnd(pSysInfo->CurGunSelected)) &&
+            ShmDcCommonData->PreAuth_Config == _CREDITCARD_IDLE) {
+            ShmDcCommonData->PreAuth_Config = _CREDITCARD_SALE;
+            ShmDcCommonData->PreAuth_Result = 0;
+            pSysInfo->SystemPage = _PAGE_AUTHORIZE;
+            }
+    } else {
+        if ((pDcChargingInfo->SystemStatus == S_IDLE ) &&
+            pSysInfo->SystemPage == _PAGE_SELECT_PAY &&
+            ShmDcCommonData->PreAuth_Config == _CREDITCARD_IDLE) {
+            ShmDcCommonData->PreAuth_Config = _CREDITCARD_PREAUTH;
+            ShmDcCommonData->PreAuth_Result = 0;
+            pSysInfo->SystemPage = _PAGE_AUTHORIZE;
+            //log_info("Press Credit card pay status:%d Page:%d Config:%d", pDcChargingInfo->SystemStatus,
+            //    pSysInfo->SystemPage, ShmDcCommonData->PreAuth_Config);
+        }
+    }
+}
+
+void CheckPayLinePay()
+{
+    log_info("Change to Add Line Friend Page");
+    StopSystemTimeoutDet();
+    StopGunInfoTimeoutDet(pSysInfo->CurGunSelected);
+    pSysInfo->SystemPage = _PAGE_ADD_FRIEND;
+}
+void CheckTouchPress(short id)
+{
+    GetDeviceInfoStatus(id,1);
+    if (_btn_press >= 1 && _btn_press_id == id ) {
+    	_btn_press_count++;
+    }
+    if (_btn_press >= 1 && _btn_press_id == id && _btn_press_count >= 2) {
+        ChangeDisplay2Value(id, 0);
+        //log_info("Press id : 0x%04x",id);
+        _btn_press_count = 0;
+        switch (id) {
+        case _Touch_Show_Left:
+        	if (pSysInfo->SystemPage >= _PAGE_BILL && pSysInfo->SystemPage <= _PAGE_PLUGIN) {
+        		log_info("Authorize Process can't select gun");
+        		return;
+        	}
+            // Show log
+        	if(pSysInfo->CurGunSelected != LEFT_GUN_NUM) {
+        		pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(LEFT_GUN_NUM);
+        		pSysInfo->CurGunSelected = LEFT_GUN_NUM;
+                if(pDcChargingInfo->SystemStatus == S_IDLE || pDcChargingInfo->SystemStatus == S_RESERVATION) {
+                    systemPageRestoreInit();
+                }
+				log_info("LCM left Gun down...............................%x %x %x",
+						pSysInfo->CurGunSelected,pDcChargingInfo->SystemStatus,pSysInfo->SystemPage);
+			}
+            pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(LEFT_GUN_NUM);
+            if (ShmDcCommonData->pGunInfo[LEFT_GUN_NUM].ParkingStatus) {
+                if (pDcChargingInfo->SystemStatus == S_COMPLETE || pDcChargingInfo->SystemStatus == S_ALARM) {
+                    if (ShmDcCommonData->PayPass_flag[LEFT_GUN_NUM] == TRUE)
+                        pSysInfo->SystemPage = _PAGE_COMPLETE;
+                    else {
+                        if (pDcChargingInfo->Replug_flag)
+                            pSysInfo->SystemPage = _PAGE_PLUGOUT;
+                        else
+                            pSysInfo->SystemPage = _PAGE_PAYFAIL;
+                    }
+                }
+            }
+        	if (pSysInfo->SystemPage == _PAGE_CHARGING || pSysInfo->SystemPage == _PAGE_COMPLETE ||
+        			pSysInfo->SystemPage == _PAGE_PAYFAIL) {
+				StopSystemTimeoutDet();
+        	}
+            break;
+        case _Touch_Show_Right:
+        	if (pSysInfo->SystemPage >= _PAGE_BILL && pSysInfo->SystemPage <= _PAGE_PLUGIN) {
+        		log_info("Authorize Process can't select gun");
+        		return;
+        	}
+			// Show log
+			if(pSysInfo->CurGunSelected != RIGHT_GUN_NUM) {
+				pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(RIGHT_GUN_NUM);
+				pSysInfo->CurGunSelected = RIGHT_GUN_NUM;
+                if (pDcChargingInfo->SystemStatus == S_IDLE || pDcChargingInfo->SystemStatus == S_RESERVATION) {
+                    systemPageRestoreInit();
+	            }
+				log_info("LCM Right Gun down...............................%x %x %x",
+						pSysInfo->CurGunSelected,pDcChargingInfo->SystemStatus,pSysInfo->SystemPage);
+			}
+            pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(RIGHT_GUN_NUM);
+            if (ShmDcCommonData->pGunInfo[RIGHT_GUN_NUM].ParkingStatus) {
+                if (pDcChargingInfo->SystemStatus == S_COMPLETE || pDcChargingInfo->SystemStatus == S_ALARM) {
+                    if (ShmDcCommonData->PayPass_flag[RIGHT_GUN_NUM] == TRUE)
+                        pSysInfo->SystemPage = _PAGE_COMPLETE;
+                    else
+                        if (pDcChargingInfo->Replug_flag)
+                            pSysInfo->SystemPage = _PAGE_PLUGOUT;
+                        else
+                            pSysInfo->SystemPage = _PAGE_PAYFAIL;
+                }
+            }
+        	if (pSysInfo->SystemPage == _PAGE_CHARGING || pSysInfo->SystemPage == _PAGE_COMPLETE ||
+        			pSysInfo->SystemPage == _PAGE_PAYFAIL) {
+				StopSystemTimeoutDet();
+        	}
+            break;
+        case _Touch_Return:
+        	CheckReturnPress();
+        	break;
+        case _Touch_IDLE:
+            CheckIdlePress();
+            break;
+        case _Touch_StopCharge:
+        	CheckStopPress();
+        	break;
+        case _Touch_Stop_Confirm:
+        	CheckStopConfirmPress();
+        	break;
+        case _Touch_Stop_Cancel:
+        	CheckStopCancelPress();
+        	break;
+        case _Touch_Select_Left:
+        	CheckConfirmGun(LEFT_GUN_NUM);
+        	break;
+        case _Touch_Select_Right:
+        	CheckConfirmGun(RIGHT_GUN_NUM);
+        	break;
+        case _Touch_DonateBill:
+        	StopSystemTimeoutDet();
+        	CheckDonateBill(pSysInfo->CurGunSelected);
+        	break;
+        case _Touch_DonateYes:
+        	CheckDonateYes();
+        	break;
+        case _Touch_DonateNo:
+
+        	CheckDonateNo();
+        	break;
+        case _Touch_Pay_CreditCard:
+        	CheckPayCreditCard();
+        	break;
+        case _Touch_Pay_LinePay:
+        	CheckPayLinePay();
+        	break;
+        case _Touch_Parking_Complete:
+            ShmDcCommonData->pGunInfo[pSysInfo->CurGunSelected].ReqParkingBill = TRUE;
+            pSysInfo->SystemPage = _PAGE_PAYING;
+            //log_info("Set Page to %d",pSysInfo->SystemPage);
+            break;
+        } // switch
+
+    }   //if (_btn_press >= 3)
+}
+
+void CheckLCMPressed()
+{
+    pid_t Pid = fork();
+    if ( Pid == 0 ) {
+        while (1) {
+        	if (pSysInfo->SystemPage != _PAGE_SELECT_GUN && pSysInfo->SystemPage != _PAGE_IDLE) {
+				CheckTouchPress(_Touch_Show_Left);
+				CheckTouchPress(_Touch_Show_Right);
+        	}
+            switch (pSysInfo->SystemPage) {
+            case _PAGE_IDLE:
+				//CheckTouchPress(_Touch_IDLE);
+                CheckTouchPress(_Touch_Select_Left);
+                CheckTouchPress(_Touch_Select_Right);
+                break;
+            case _PAGE_SELECT_GUN:
+				CheckTouchPress(_Touch_Select_Left);
+				CheckTouchPress(_Touch_Select_Right);
+            	break;
+            case _PAGE_BILL:
+            	CheckTouchPress(_Touch_Return);
+            	CheckTouchPress(_Touch_DonateBill);
+                CheckTouchPress(_Touch_Pay_LinePay);
+            	break;
+            case _PAGE_ADD_FRIEND:
+            	CheckTouchPress(_Touch_Return);
+            	//CheckTouchPress(_Touch_DonateBill);
+            	break;
+            case _PAGE_DONATE_LEFT:
+            case _PAGE_DONATE_RIGHT:
+            	CheckTouchPress(_Touch_Return);
+            	CheckTouchPress(_Touch_DonateYes);
+            	CheckTouchPress(_Touch_DonateNo);
+            	break;
+            case _PAGE_SELECT_PAY:
+                CheckTouchPress(_Touch_Pay_CreditCard);
+            	CheckTouchPress(_Touch_Return);
+            	break;
+            case _PAGE_PLUGIN:
+            	CheckTouchPress(_Touch_Return);
+
+            	break;
+            ///*
+            case _PAGE_CHARGING:
+				CheckTouchPress(_Touch_StopCharge);
+            	break;
+            case _PAGE_AUTHORIZE:
+            	CheckTouchPress(_Touch_Return);
+            	break;
+            case _PAGE_STOP_CONFIRM_LEFT:
+            case _PAGE_STOP_CONFIRM_RIGHT:
+            	StopSystemTimeoutDet();
+				CheckTouchPress(_Touch_Stop_Confirm);
+				CheckTouchPress(_Touch_Stop_Cancel);
+            	break;
+            case _PAGE_EXIT:
+            	CheckTouchPress(_Touch_Return);
+            	break;
+            case _PAGE_AUTHORIZE_FAIL:
+            	CheckTouchPress(_Touch_Return);
+            	break;
+            case _PAGE_COMPLETE:
+            case _PAGE_PAYFAIL:
+            case _PAGE_PLUGOUT:
+                if (ShmDcCommonData->pGunInfo[pSysInfo->CurGunSelected].ParkingStatus >= _TCC_PARKING_OCCUPENCY)
+                    CheckTouchPress(_Touch_Parking_Complete);
+                break;
+            } // switch
+            usleep(5000);
+        } //while
+    } // if pid
+    log_info("Create LCM fork:%d\n\n",Pid);
+}
+
+
+void GetHrFormTimeString(char* time,char* hr)
+{
+    //char tm[] = "2021-12-06 17:29:08:084";
+    for(int i = 0 ; i < 2 ; i++) {
+        hr[i] = time[i+11];
+    }
+    if( atoi(hr) < 0 || atoi(hr) > 24) {
+        strcmp(hr,"");
+    }
+}
+void GetMinFormTimeString(char* time,char* min)
+{
+    //char tm[] = "2021-12-06 17:29:08:084";
+    for(int i = 0 ; i < 2 ; i++) {
+        min[i] = time[i+14];
+    }
+    if( atoi(min) < 0 || atoi(min) > 60) {
+        strcmp(min,"");
+    }
+}
+//================================================
+// Function
+//================================================
+void ChangeToOtherPage(short newPage)
+{
+
+    uint8_t cmd[10];
+    memset(cmd, 0x00, sizeof(cmd));
+    uint8_t msg[9];
+    memset(msg, 0x00, sizeof(msg));
+
+    cmd[0] = CMD_TITLE_1;
+    cmd[1] = CMD_TITLE_2;
+    cmd[2] = 0x07;
+    cmd[3] = 0x82;
+    cmd[4] = 0x00;
+    cmd[5] = 0x84;
+    cmd[6] = 0x5A;
+    cmd[7] = 0x01;
+    cmd[8] = newPage >> 8;
+    cmd[9] = newPage & 0x00FF;
+
+    WriteCmdToLcm(cmd, ARRAY_SIZE(cmd));
+    usleep(5000);
+    ReadMsgFromLcm(msg, ARRAY_SIZE(msg));
+}
+
+void ChangeBackLight(uint8_t value)
+{
+    //uint8_t value = 0x01;
+    uint8_t msg[9];
+    memset(msg, 0x00, sizeof(msg));
+
+    uint8_t cmd[7];
+    memset(cmd, 0x00, sizeof(cmd));
+
+    cmd[0] = CMD_TITLE_1;
+    cmd[1] = CMD_TITLE_2;
+    cmd[2] = 0x05;
+    cmd[3] = CMD_MULTI_WRITE;
+    cmd[4] = 0x00;
+    cmd[5] = 0x82;
+    cmd[6] = value;
+
+    WriteCmdToLcm(cmd, ARRAY_SIZE(cmd));
+    usleep(10000);
+    ReadMsgFromLcm(msg, ARRAY_SIZE(msg));
+}
+
+void GetCurrentPage()
+{
+    uint8_t cmd[7];
+    memset(cmd, 0x00, sizeof(cmd));
+    uint8_t msg[9];
+    memset(msg, 0x00, sizeof(msg));
+
+    cmd[0] = CMD_TITLE_1;
+    cmd[1] = CMD_TITLE_2;
+    cmd[2] = 0x04;              // 底下總長度
+    cmd[3] = 0x83;
+    cmd[4] = 0x00;
+    cmd[5] = 0x14;
+    cmd[6] = 0x01;
+
+    WriteCmdToLcm(cmd, ARRAY_SIZE(cmd));
+    usleep(5000);
+    ReadMsgFromLcm(msg, ARRAY_SIZE(msg));
+}
+
+
+//================================================
+// Warning process
+//================================================
+void string2ByteArray(uint8_t *input, uint8_t *output)
+{
+    int loop;
+    int i;
+
+    loop = 0;
+    i = 0;
+
+    while (input[loop] != '\0') {
+        output[i++] = input[loop++];
+    }
+    output[loop] = '\0';
+}
+
+void RefreshProgressAnimation()
+{
+	_everyPageRollChange >= 30 ? _everyPageRollChange = 0 : _everyPageRollChange++;
+}
+
+//================================================
+// Change current page
+//================================================
+void ChangeCurPage()
+{
+    //log_info("cur = %d ,system = %d, lcm = %d ",_currentPage, pSysInfo->SystemPage, pSysInfo->PageIndex);
+    if (pSysInfo->PageIndex != pSysInfo->SystemPage)
+        log_info("Gun[%d] Chagne LCM Page:%d",pSysInfo->CurGunSelected, pSysInfo->SystemPage);
+    pSysInfo->PageIndex = pSysInfo->SystemPage;
+
+    if (_currentPage != pSysInfo->PageIndex) {
+        switch (pSysInfo->SystemPage) {
+        case _PAGE_AUTHORIZE:
+            break;
+        case _PAGE_PLUGIN:
+            break;
+        case _PAGE_PRECHARGE:
+            break;
+        case _PAGE_CHARGING:
+            break;
+        case _PAGE_COMPLETE:
+            is_stop = FALSE;
+            break;
+        case _PAGE_PAYFAIL:
+            is_stop = FALSE;
+            break;
+        case _PAGE_MAINTAIN:
+            break;
+        }
+        
+        _currentPage = pSysInfo->PageIndex;
+        //if (pSysInfo->PageIndex != _PAGE_IDLE)
+
+        ChangeToOtherPage(pSysInfo->PageIndex);
+    }
+}
+
+/*
+ * View Page
+ *
+ */
+
+unsigned long GetTimeoutValue(struct timeval _sour_time)
+{
+    struct timeval _end_time;
+    gettimeofday(&_end_time, NULL);
+
+    return 1000000 * (_end_time.tv_sec - _sour_time.tv_sec) + _end_time.tv_usec - _sour_time.tv_usec;
+}
+
+void showGunWorkingType()
+{
+    if (pSysInfo->CurGunSelected == LEFT_GUN_NUM) {
+
+        pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(LEFT_GUN_NUM);
+        if (ShmDcCommonData->pGunInfo[LEFT_GUN_NUM].ParkingStatus) {
+            ChangeDisplay2Value(_Icon_ShowLeft,_TCC_LeftParkingSel);
+        } else {
+            if (pDcChargingInfo->CCSGunType == _TYPE_CCS1_Liquid ||
+                    pDcChargingInfo->CCSGunType == _TYPE_CCS1_Natural) {
+                ChangeDisplay2Value(_Icon_ShowLeft,_TCC_ShowLeft_CCS1_On);
+
+            } else if (pDcChargingInfo->CCSGunType == _TYPE_CCS2_Liquid ||
+                    pDcChargingInfo->CCSGunType == _TYPE_CCS2_Natural) {
+                ChangeDisplay2Value(_Icon_ShowLeft,_TCC_ShowLeft_CCS2_On);
+            } else if (pDcChargingInfo->Type == _Type_Chademo) {
+                ChangeDisplay2Value(_Icon_ShowLeft,_TCC_ShowLeft_CHAdeMo_On);
+            }
+        }
+
+        // Set Right Gun
+        pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(RIGHT_GUN_NUM);
+        if (ShmDcCommonData->pGunInfo[RIGHT_GUN_NUM].ParkingStatus) {
+            ChangeDisplay2Value(_Icon_ShowRight,_TCC_RightParkingSel);
+        } else {
+            if (pDcChargingInfo->CCSGunType == _TYPE_CCS1_Liquid ||
+                    pDcChargingInfo->CCSGunType == _TYPE_CCS1_Natural) {
+                ChangeDisplay2Value(_Icon_ShowRight,_TCC_ShowRight_CCS1_Off);
+
+            } else if (pDcChargingInfo->CCSGunType == _TYPE_CCS2_Liquid ||
+                    pDcChargingInfo->CCSGunType == _TYPE_CCS2_Natural) {
+                ChangeDisplay2Value(_Icon_ShowRight,_TCC_ShowRight_CCS2_Off);
+            } else if (pDcChargingInfo->Type == _Type_Chademo) {
+                ChangeDisplay2Value(_Icon_ShowRight,_TCC_ShowRight_CHAdeMo_Off);
+            }
+        }
+    } else if (pSysInfo->CurGunSelected == RIGHT_GUN_NUM){
+        // Left Gun
+        pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(LEFT_GUN_NUM);
+        if (ShmDcCommonData->pGunInfo[LEFT_GUN_NUM].ParkingStatus) {
+            ChangeDisplay2Value(_Icon_ShowLeft,_TCC_LeftParkingSel);
+        } else {
+            if (pDcChargingInfo->CCSGunType == _TYPE_CCS1_Liquid ||
+                    pDcChargingInfo->CCSGunType == _TYPE_CCS1_Natural) {
+                ChangeDisplay2Value(_Icon_ShowLeft,_TCC_ShowLeft_CCS1_Off);
+
+            } else if (pDcChargingInfo->CCSGunType == _TYPE_CCS2_Liquid ||
+                    pDcChargingInfo->CCSGunType == _TYPE_CCS2_Natural) {
+                ChangeDisplay2Value(_Icon_ShowLeft,_TCC_ShowLeft_CCS2_Off);
+            } else if (pDcChargingInfo->Type == _Type_Chademo) {
+                ChangeDisplay2Value(_Icon_ShowLeft,_TCC_ShowLeft_CHAdeMo_Off);
+            }
+        }
+        // Right Gun
+        pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(RIGHT_GUN_NUM);
+        if (ShmDcCommonData->pGunInfo[RIGHT_GUN_NUM].ParkingStatus) {
+            ChangeDisplay2Value(_Icon_ShowRight,_TCC_RightParkingSel);
+        } else {
+            if (pDcChargingInfo->CCSGunType == _TYPE_CCS1_Liquid ||
+                    pDcChargingInfo->CCSGunType == _TYPE_CCS1_Natural) {
+                ChangeDisplay2Value(_Icon_ShowRight,_TCC_ShowRight_CCS1_On);
+
+            } else if (pDcChargingInfo->CCSGunType == _TYPE_CCS2_Liquid ||
+                    pDcChargingInfo->CCSGunType == _TYPE_CCS2_Natural) {
+                ChangeDisplay2Value(_Icon_ShowRight,_TCC_ShowRight_CCS2_On);
+            } else if (pDcChargingInfo->Type == _Type_Chademo) {
+                ChangeDisplay2Value(_Icon_ShowRight,_TCC_ShowRight_CHAdeMo_On);
+            }
+        }
+    }
+}
+void ClearQrCode_Idle()
+{
+    char cmd[200];
+    memset(cmd,0,200);
+    DisplayValueToLcm(_QRCode_AddLine, cmd, 200);
+}
+void ChangeQrCode_Idle(char *input)
+{
+    char cmd[256];
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(pSysInfo->CurGunSelected);
+    int len = 0;
+    memset(cmd,0,256);
+    time_t timep;
+    struct tm* tm;
+    time(&timep);
+    char SN[37];
+    memset(SN,'\0',sizeof(SN));
+    memcpy(SN,ShmDcCommonData->ParkingInfo[pSysInfo->CurGunSelected].OccupancySN,36);
+    tm = localtime(&timep);
+
+    if (ShmDcCommonData->pGunInfo[pSysInfo->CurGunSelected].ParkingStatus && !ShmDcCommonData->ParkingInfo[pSysInfo->CurGunSelected].ParkingCntDownFlag) {
+        tm->tm_year -= 50;
+        ShmDcCommonData->ParkingInfo[pSysInfo->CurGunSelected].ParkingStopTime = mktime(tm) + 120 +(ShmDcCommonData->TZOffset * 60);
+        ShmDcCommonData->ParkingInfo[pSysInfo->CurGunSelected].ParkingCntDownFlag = TRUE;
+        tm = gmtime(&ShmDcCommonData->ParkingInfo[pSysInfo->CurGunSelected].ParkingStopTime);
+        log_info("QR Code Show Time:(%d)%s",ShmDcCommonData->ParkingInfo[pSysInfo->CurGunSelected].ParkingStopTime,asctime(tm));
+    }
+
+    if (!ShmDcCommonData->tccdev) {
+        if (ShmDcCommonData->pGunInfo[pSysInfo->CurGunSelected].ParkingStatus) {
+            //len = sprintf(cmd, "https://nhoatcc.lineapid.tw/web/placeholder?sn=%s&ts=%d",SN,
+            //                                                                            ShmDcCommonData->ParkingInfo[pSysInfo->CurGunSelected].ParkingStopTime);
+            len = sprintf(cmd, "https://liff.line.me/1656875983-yr0MMWqY/web_placeholder/sn/%s/ts/%d",SN,
+                                                                                        ShmDcCommonData->ParkingInfo[pSysInfo->CurGunSelected].ParkingStopTime);
+        } else
+            //len = sprintf(cmd, "https://nhoatcc.lineapid.tw/web/tologin?sn=%s&cid=%d", input, ShmDcCommonData->ConnectorID[pSysInfo->CurGunSelected]);
+            len = sprintf(cmd, "https://liff.line.me/1656875983-yr0MMWqY/tologin/sn/%s/cid/%d", input, ShmDcCommonData->ConnectorID[pSysInfo->CurGunSelected]);
+    } else {
+        if (ShmDcCommonData->pGunInfo[pSysInfo->CurGunSelected].ParkingStatus) {
+            len = sprintf(cmd, "https://liff.line.me/1656908881-rjazze69/web_placeholder/sn/%s/ts/%d",SN,
+                                                                                        ShmDcCommonData->ParkingInfo[pSysInfo->CurGunSelected].ParkingStopTime);
+        } else {
+            //len = sprintf(cmd, "https://nhoatcctest.lineapid.tw/web/tologin?sn=%s&cid=%d", input, ShmDcCommonData->ConnectorID[pSysInfo->CurGunSelected]);
+            len = sprintf(cmd, "https://liff.line.me/1656908881-rjazze69/tologin/sn/%s/cid/%d", input, ShmDcCommonData->ConnectorID[pSysInfo->CurGunSelected]);
+        }
+    }
+    //log_info("QR Code:URL:%s",cmd);
+    if (pSysInfo->SystemPage == _PAGE_ADD_FRIEND)
+    	DisplayValueToLcm(_QRCode_AddLine, cmd, len+1);
+}
+void ClearQrCode_Error()
+{
+    char cmd[200];
+    memset(cmd, 0, 200);
+    DisplayValueToLcm(_QRCode_Service, cmd, 200);
+}
+void ChangeQrCode_Error()
+{
+    char cmd[200];
+    memset(cmd, 0, 200);
+    sprintf(cmd, "https://line.me/R/ti/p/@217tcevc");
+
+    //log_info("QR Code:URL:%s",cmd);
+
+    DisplayValueToLcm(_QRCode_Service, cmd, 200);
+}
+/*
+void ChangeRemainTime(int sec)
+{
+    int h, m, s;
+    uint8_t cmd[10];
+    uint8_t value[10];
+
+    memset(cmd, 0x00, sizeof(cmd));
+
+//  srand(time(NULL));
+//  int min = 0;
+//  int max = 65536;
+//  sec = rand() % (max - min + 1) + min;
+
+    h = (sec / 3600);
+    m = (sec - (3600 * h)) / 60;
+    s = (sec - (3600 * h) - (m * 60));
+    sprintf((char *)value, "%02d:%02d:%02d", h, m, s);
+    string2ByteArray(value, cmd);
+    DisplayValueToLcm(_Text_Time, cmd, sizeof(cmd));
+}
+*/
+void ShowSelectGun()
+{
+	pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(LEFT_GUN_NUM);
+    if (ShmDcCommonData->pGunInfo[LEFT_GUN_NUM].ParkingStatus){
+        ChangeDisplay2Value(_Icon_Select_Left,_TCC_LeftParkingIdle);
+    } else if ((pDcChargingInfo->SystemStatus >= S_AUTHORIZING &&
+        pDcChargingInfo->SystemStatus <= S_ALARM) ||
+        pDcChargingInfo->SystemStatus == S_CCS_PRECHARGE_ST0 ||
+        pDcChargingInfo->SystemStatus == S_CCS_PRECHARGE_ST1) {
+        // 使用中
+        if (pDcChargingInfo->CCSGunType == _TYPE_CCS1_Liquid ||
+            pDcChargingInfo->CCSGunType == _TYPE_CCS1_Natural) {
+            ChangeDisplay2Value(_Icon_Select_Left, _TCC_ShowLeftGunCharging_CCS1);
+
+        } else if (pDcChargingInfo->CCSGunType == _TYPE_CCS2_Liquid ||
+            pDcChargingInfo->CCSGunType == _TYPE_CCS2_Natural) {
+            ChangeDisplay2Value(_Icon_Select_Left, _TCC_ShowLeftGunCharging_CCS2);
+
+        } else if (pDcChargingInfo->Type == _Type_Chademo) {
+            ChangeDisplay2Value(_Icon_Select_Left, _TCC_ShowLeftGunCharging_CHAdeMo);
+        }
+    } else if (pDcChargingInfo->SystemStatus == S_RESERVATION) {
+        // 預約中
+        if (pDcChargingInfo->CCSGunType == _TYPE_CCS1_Liquid ||
+            pDcChargingInfo->CCSGunType == _TYPE_CCS1_Natural) {
+            ChangeDisplay2Value(_Icon_Select_Left, _TCC_ShowLeftGunReservation_CCS1);
+
+        } else if (pDcChargingInfo->CCSGunType == _TYPE_CCS2_Liquid ||
+            pDcChargingInfo->CCSGunType == _TYPE_CCS2_Natural) {
+            ChangeDisplay2Value(_Icon_Select_Left, _TCC_ShowLeftGunReservation_CCS2);
+
+        } else if (pDcChargingInfo->Type == _Type_Chademo) {
+            ChangeDisplay2Value(_Icon_Select_Left, _TCC_ShowLeftGunReservation_CHAdeMo);
+        }
+    } else {
+		if (pDcChargingInfo->CCSGunType == _TYPE_CCS1_Liquid ||
+				pDcChargingInfo->CCSGunType == _TYPE_CCS1_Natural) {
+			ChangeDisplay2Value(_Icon_Select_Left,_TCC_SelectLeft_CCS1);
+
+		} else if (pDcChargingInfo->CCSGunType == _TYPE_CCS2_Liquid ||
+				pDcChargingInfo->CCSGunType == _TYPE_CCS2_Natural) {
+			ChangeDisplay2Value(_Icon_Select_Left,_TCC_SelectLeft_CCS2);
+
+		} else if (pDcChargingInfo->Type == _Type_Chademo) {
+			ChangeDisplay2Value(_Icon_Select_Left,_TCC_SelectLeft_CHAdeMo);
+		}
+	}
+	pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(RIGHT_GUN_NUM);
+    if (ShmDcCommonData->pGunInfo[RIGHT_GUN_NUM].ParkingStatus) {
+        ChangeDisplay2Value(_Icon_Select_Right,_TCC_RightParkingIdle);
+    } else if ((pDcChargingInfo->SystemStatus >= S_AUTHORIZING &&
+        pDcChargingInfo->SystemStatus <= S_ALARM) ||
+        pDcChargingInfo->SystemStatus == S_CCS_PRECHARGE_ST0 ||
+        pDcChargingInfo->SystemStatus == S_CCS_PRECHARGE_ST1) {
+        if (pDcChargingInfo->CCSGunType == _TYPE_CCS1_Liquid ||
+            pDcChargingInfo->CCSGunType == _TYPE_CCS1_Natural) {
+            ChangeDisplay2Value(_Icon_Select_Right, _TCC_ShowRightGunCharging_CCS1);
+
+        } else if (pDcChargingInfo->CCSGunType == _TYPE_CCS2_Liquid ||
+            pDcChargingInfo->CCSGunType == _TYPE_CCS2_Natural) {
+            ChangeDisplay2Value(_Icon_Select_Right, _TCC_ShowRightGunCharging_CCS2);
+
+        } else if (pDcChargingInfo->Type == _Type_Chademo) {
+            ChangeDisplay2Value(_Icon_Select_Right, _TCC_ShowRightGunCharging_CHAdeMo);
+
+        }
+    } else if (pDcChargingInfo->SystemStatus == S_RESERVATION) {
+        if (pDcChargingInfo->CCSGunType == _TYPE_CCS1_Liquid ||
+            pDcChargingInfo->CCSGunType == _TYPE_CCS1_Natural) {
+            ChangeDisplay2Value(_Icon_Select_Right, _TCC_ShowRightGunReservation_CCS1);
+
+        } else if (pDcChargingInfo->CCSGunType == _TYPE_CCS2_Liquid ||
+            pDcChargingInfo->CCSGunType == _TYPE_CCS2_Natural) {
+            ChangeDisplay2Value(_Icon_Select_Right, _TCC_ShowRightGunReservation_CCS2);
+
+        } else if (pDcChargingInfo->Type == _Type_Chademo) {
+            ChangeDisplay2Value(_Icon_Select_Right, _TCC_ShowRightGunReservation_CHAdeMo);
+
+        }
+	} else {
+		if (pDcChargingInfo->CCSGunType == _TYPE_CCS1_Liquid ||
+				pDcChargingInfo->CCSGunType == _TYPE_CCS1_Natural) {
+			ChangeDisplay2Value(_Icon_Select_Right,_TCC_SelectRight_CCS1);
+
+		} else if (pDcChargingInfo->CCSGunType == _TYPE_CCS2_Liquid ||
+				pDcChargingInfo->CCSGunType == _TYPE_CCS2_Natural) {
+			ChangeDisplay2Value(_Icon_Select_Right,_TCC_SelectRight_CCS2);
+
+		} else if (pDcChargingInfo->Type == _Type_Chademo) {
+			ChangeDisplay2Value(_Icon_Select_Right,_TCC_SelectRight_CHAdeMo);
+
+		}
+	}
+
+}
+void ChangeChargingPowerValue(float pow)
+{
+    uint8_t cmd[10];
+    uint8_t value[10];
+
+    memset(cmd, 0x00, sizeof(cmd));
+
+    sprintf((char *) value, "%d",(int)pow);
+    string2ByteArray(value, cmd);
+    DisplayValueToLcm(_String_ChargePower, cmd, sizeof(cmd));
+}
+void ChangeChargingRateValue(float rate,int show)
+{
+    uint8_t cmd[10];
+    uint8_t value[10];
+
+    memset(cmd, 0x00, sizeof(cmd));
+    if (show)
+        sprintf((char *) value, "%.1f",rate);
+    else
+        sprintf((char *) value, "");
+    string2ByteArray(value, cmd);
+    DisplayValueToLcm(_String_ChargeRate, cmd, sizeof(cmd));
+}
+
+void ChangeChargingFeeValue(float fee)
+{
+    uint8_t cmd[10];
+    uint8_t value[10];
+
+    memset(cmd, 0x00, sizeof(cmd));
+
+    sprintf((char *) value, "%d", (int)fee);
+    string2ByteArray(value, cmd);
+    DisplayValueToLcm(_String_Money, cmd, sizeof(cmd));
+}
+void ChangeCarBonValue(float data)
+{
+    uint8_t cmd[10];
+    uint8_t value[10];
+    float _carbon = 0;
+    memset(cmd, 0x00, sizeof(cmd));
+    _carbon = data * 0.577;
+    //log_info("Carbon:%d",(int)_carbon);
+
+	sprintf((char *) value, "%.1f", _carbon);
+    string2ByteArray(value, cmd);
+    DisplayValueToLcm(_String_Carbon, cmd, sizeof(cmd));
+}
+void ChangeChargingEnergyValue(float energy)
+{
+    uint8_t cmd[10];
+    uint8_t value[10];
+
+    memset(cmd, 0x00, sizeof(cmd));
+    if (energy >= 0.05) {
+        energy -= 0.05;
+    }
+
+    if (energy < 0 )
+    	ChangeDisplay2Value(_Icon_ChargeBar,_TCC_Charging_Bar0);
+    else if (energy > 100)
+    	ChangeDisplay2Value(_Icon_ChargeBar,_TCC_Charging_Bar0+100);
+    else
+    	ChangeDisplay2Value(_Icon_ChargeBar,(int)energy+_TCC_Charging_Bar0);
+    if (energy < 10)
+    	sprintf((char *) value, "%.1f", energy);
+    else
+    	sprintf((char *) value, "%d", (int)energy);
+    string2ByteArray(value, cmd);
+    DisplayValueToLcm(_Strting_Energy, cmd, sizeof(cmd));
+}
+
+void ChangeParkingRateValue(float fee,int show)
+{
+    uint8_t cmd[10];
+    uint8_t value[10];
+
+    memset(cmd, 0x00, sizeof(cmd));
+    if (show)
+        sprintf((char *) value, "%d", (int)fee);
+    else
+        sprintf((char *) value, "");
+    string2ByteArray(value, cmd);
+    DisplayValueToLcm(_String_ParkRate, cmd, sizeof(cmd));
+}
+
+void ChangeParkingLeaveTime(int min,int show)
+{
+    uint8_t cmd[10];
+    uint8_t value[10];
+
+    memset(cmd, 0x00, sizeof(cmd));
+    if (show)
+        sprintf((char *) value, "%d", (int)min);
+    else
+        sprintf((char *) value, "");
+    string2ByteArray(value, cmd);
+    DisplayValueToLcm(_String_ParkingLeaveTime, cmd, sizeof(cmd));
+}
+
+void ChangeSaleLeaveTime(int min,int show)
+{
+    uint8_t cmd[10];
+    uint8_t value[10];
+
+    memset(cmd, 0x00, sizeof(cmd));
+    if (show)
+        sprintf((char *) value, "%d", (int)min);
+    else
+        sprintf((char *) value, "");
+    string2ByteArray(value, cmd);
+    DisplayValueToLcm(_String_SaleLeaveTime, cmd, sizeof(cmd));
+}
+
+uint8_t _battery_display_count = 0;
+void ChangeBattMapAndValue(int soc)
+{
+    int i = (soc*36)/100;
+    uint8_t cmd[5];
+    uint8_t value[5];
+
+	_battery_display_count++;
+	if (_battery_display_count == 3 ) {
+		if (_battery_display_ani == 0)
+			_battery_display_ani= TRUE;
+		else
+			_battery_display_ani= FALSE ;
+		_battery_display_count = 0;
+	}
+	if (pSysInfo->SystemPage == _PAGE_CHARGING) {
+		if (i>=36)
+			ChangeDisplay2Value(_Icon_ChargeCircle,_TCC_Charging_Circle0+36);
+		else {
+			if (_battery_display_ani) {
+				ChangeDisplay2Value(_Icon_ChargeCircle, _TCC_Charging_Circle0+i);
+			} else {
+				ChangeDisplay2Value(_Icon_ChargeCircle, _TCC_Charging_Circle0+i+1);
+			}
+		}
+	} else if (pSysInfo->SystemPage == _PAGE_COMPLETE)
+		ChangeDisplay2Value(_Icon_CompleteCircle, _TCC_CompleteCircle0+i);
+	else
+		ChangeDisplay2Value(_Icon_CompleteCircle, _TCC_FAILCircle0 +i);
+
+    memset(cmd, 0x00, sizeof(cmd));
+    memset(value, 0x00, sizeof(value));
+
+    sprintf((char *)value, "%d", soc);
+
+    string2ByteArray(value, cmd);
+    DisplayValueToLcm(_String_Battery, cmd, sizeof(cmd));
+}
+unsigned long GetPreChargeTimeoutValue(struct timeval _sour_time)
+{
+    struct timeval _end_time;
+    gettimeofday(&_end_time, NULL);
+
+    return 1000000 * (_end_time.tv_sec - _sour_time.tv_sec) + _end_time.tv_usec - _sour_time.tv_usec;
+}
+void ChangeTimeValue(int time)
+{
+    uint8_t cmd[6];
+    uint8_t value[6];
+
+    memset(cmd, 0x00, sizeof(cmd));
+    sprintf((char *) value, "%d", time);
+    string2ByteArray(value, cmd);
+    DisplayValueToLcm(_String_ChargeTime, cmd, sizeof(cmd));
+}
+
+void changeWeatherValue(int _weather)
+{
+	switch (_weather) {
+	case _WEATHER_TYPE_SUN:
+		ChangeDisplay2Value(_Icon_Weather,_TCC_Sun);
+		break;
+	case _WEATHER_TYPE_CLOUDY:
+		ChangeDisplay2Value(_Icon_Weather,_TCC_Cloudy);
+		break;
+	case _WEATHER_TYPE_RAIN:
+		ChangeDisplay2Value(_Icon_Weather,_TCC_Rain);
+		break;
+	case _WEATHER_TYPE_THUNDER:
+		ChangeDisplay2Value(_Icon_Weather,_TCC_Thunder);
+		break;
+	case _WEATHER_TYPE_SNOW:
+		ChangeDisplay2Value(_Icon_Weather,_TCC_Snow);
+		break;
+	case _WEATHER_TYPE_FOG:
+		ChangeDisplay2Value(_Icon_Weather,_TCC_Fog);
+		break;
+	}
+}
+void changeWeekValue(int _week)
+{
+    time_t timep;
+    struct tm* tm;
+    time(&timep);
+    timep += (ShmDcCommonData->TZOffset * 60);
+
+    tm = localtime(&timep);
+	_week = tm->tm_wday;
+	if (_week == 0 )
+		_week = 7;
+	ChangeDisplay2Value(_Icon_Week,_week);
+}
+void changeDegreeValue(int _degree)
+{
+    char value[16];
+    memset(value, 0x00, sizeof(value));
+    sprintf((char *)value,"%d",_degree);
+    DisplayValueToLcm(_String_Tempture, (uint8_t *)value, sizeof(value));
+}
+void changeDateValue(char* _date)
+{
+    time_t timep;
+    struct tm* tm;
+    time(&timep);
+    timep += (ShmDcCommonData->TZOffset * 60);
+
+    tm = localtime(&timep);
+
+    sprintf(_date, "%04d/%02d/%02d",
+        tm->tm_year + 1900,
+        tm->tm_mon + 1,
+        tm->tm_mday);
+    char value[16];
+    memset(value, 0x00, sizeof(value));
+    sprintf((char *)value,"%s",_date);
+	DisplayValueToLcm(_String_Date, (uint8_t *)value, sizeof(value));
+}
+void changeLocationValue(int _location)
+{
+	//_location+=1000;
+	//log_info("location:%d",_location);
+	ChangeDisplay2Value(_Icon_Location,(short)_location);
+}
+void ShowLineRegisterCountDown(int _show)
+{
+    if(!_show) {
+        ChangeDisplay2Value(_Icon_ScanCntDw_BG,_ICON_Empty);
+        ChangeDisplay2Value(_Icon_ScanCntDownTen, _ICON_Empty);
+        ChangeDisplay2Value(_Icon_ScanCntDownDigits, _ICON_Empty);
+        return;
+    }
+    int _ten, _digits;
+    pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(pSysInfo->CurGunSelected);
+    if (pDcChargingInfo->TimeoutFlag == Timeout_LineReigster) {
+        _ten = (TCC_LINEREGISTER_TIMEOUT - (GetClockTimeoutValue(pDcChargingInfo->ConnectorTimeout) / uSEC_VAL)) / 10;
+        _digits = (TCC_LINEREGISTER_TIMEOUT - (GetClockTimeoutValue(pDcChargingInfo->ConnectorTimeout) / uSEC_VAL)) % 10;
+        ChangeDisplay2Value(_Icon_ScanCntDw_BG,_TCC_Scan_CntDw_BG);
+        ChangeDisplay2Value(_Icon_ScanCntDownTen, (short)_TCC_CntDownNumber0+_ten);
+        ChangeDisplay2Value(_Icon_ScanCntDownDigits, (short)_TCC_CntDownNumber0+ _digits);
+    } else {
+        //log_info("Not get Line Register Count Down");
+    }
+}
+void ShowAuthorizeCountDown()
+{
+    int _ten, _digits;
+    
+    if (pSysInfo->SystemTimeoutFlag == Timeout_ScanCard) {
+        ChangeDisplay2Value(_Icon_ScanCntDw_BG,_TCC_Scan_CntDw_BG);
+        _ten = (TCC_SCANCARD_TIMEOUT - (GetClockTimeoutValue(pSysInfo->SystemTimeoutTimer) / uSEC_VAL)) / 10;
+        _digits = (TCC_SCANCARD_TIMEOUT - (GetClockTimeoutValue(pSysInfo->SystemTimeoutTimer) / uSEC_VAL)) % 10;
+        ChangeDisplay2Value(_Icon_AuthCntDownTen, (short)_TCC_CntDownNumber0 + _ten);
+        ChangeDisplay2Value(_Icon_AuthCntDownDigits, (short)_TCC_CntDownNumber0 + _digits);
+    }
+    else {
+        log_info("Not get Line Register Count Down");
+    }
+}
+
+void ShowParkingCountDown(int is_parking)
+{
+    int _ten, _digits , _hun;
+    unsigned char time_flag;
+    int TimeoutTime;
+    pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(pSysInfo->CurGunSelected);
+    if (is_parking) {
+
+        if (pSysInfo->SystemPage == _PAGE_ADD_FRIEND) {
+            time_flag = Timeout_ParkingBill;
+            TimeoutTime = TCC_PARKINGBILL_TIMEOUT;
+        } else {
+            time_flag = Timeout_ParkingSelect;
+            TimeoutTime = TCC_PARK_SELECTPAY_TIMEOUT;
+        }
+
+        if (pDcChargingInfo->TimeoutFlag == time_flag ) {
+            _hun = (TimeoutTime - (GetClockTimeoutValue(pDcChargingInfo->ConnectorTimeout) / uSEC_VAL)) / 100;
+            _ten = ((TimeoutTime - (GetClockTimeoutValue(pDcChargingInfo->ConnectorTimeout) / uSEC_VAL)) / 10)%10;
+            _digits = (TimeoutTime - (GetClockTimeoutValue(pDcChargingInfo->ConnectorTimeout) / uSEC_VAL)) % 10;
+            if (pSysInfo->SystemPage == _PAGE_ADD_FRIEND) {
+                ChangeDisplay2Value(_Icon_ParkingCntDw_BG, (short)_TCC_ParkingCntDown_BG3);
+                ChangeDisplay2Value(_Icon_ParkingCntDw_Hun, (short)_TCC_ParkingCD_0 + _hun);
+                ChangeDisplay2Value(_Icon_ParkingCntDw_Tens, (short)_TCC_ParkingCD_0 + _ten);
+                ChangeDisplay2Value(_Icon_ParkingCntDw_Digits, (short)_TCC_ParkingCD_0 + _digits);
+            } else {
+                ChangeDisplay2Value(_Icon_ParkingCntDw_BG, (short)_TCC_ParkingCntDown_BG);
+                ChangeDisplay2Value(_Icon_ParkingCntDw_Tens, (short)_TCC_ParkingCD_0 + _ten);
+                ChangeDisplay2Value(_Icon_ParkingCntDw_Digits, (short)_TCC_ParkingCD_0 + _digits);
+            }
+
+        }
+        else {
+            log_info("Not get Parking Count Down(%d)",pDcChargingInfo->TimeoutFlag);
+        }
+    } else {
+        ChangeDisplay2Value(_Icon_ParkingCntDw_BG, NULL);
+        ChangeDisplay2Value(_Icon_ParkingCntDw_Hun, NULL);
+        ChangeDisplay2Value(_Icon_ParkingCntDw_Tens, NULL);
+        ChangeDisplay2Value(_Icon_ParkingCntDw_Digits, NULL);
+    }
+}
+
+void changeGunType()
+{
+    pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(LEFT_GUN_NUM);
+    if (ShmDcCommonData->pGunInfo[LEFT_GUN_NUM].ParkingStatus) {
+        ChangeDisplay2Value(_Icon_Select_Left,_TCC_LeftParkingIdle);
+    } else if (pDcChargingInfo->CCSGunType == _TYPE_CCS1_Liquid ||
+        pDcChargingInfo->CCSGunType == _TYPE_CCS1_Natural) {
+        ChangeDisplay2Value(_Icon_Select_Left, _TCC_IDLE_LEFT_CCS1);
+
+    } else if (pDcChargingInfo->CCSGunType == _TYPE_CCS2_Liquid ||
+        pDcChargingInfo->CCSGunType == _TYPE_CCS2_Natural) {
+        ChangeDisplay2Value(_Icon_Select_Left, _TCC_IDLE_LEFT_CCS2);
+    } else if (pDcChargingInfo->Type == _Type_Chademo) {
+        ChangeDisplay2Value(_Icon_Select_Left, _TCC_IDLE_LEFT_CHAdeMo);
+    }
+
+    // Set Right Gun
+    pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(RIGHT_GUN_NUM);
+    if (ShmDcCommonData->pGunInfo[RIGHT_GUN_NUM].ParkingStatus) {
+        ChangeDisplay2Value(_Icon_Select_Right,_TCC_RightParkingIdle);
+    } else if (pDcChargingInfo->CCSGunType == _TYPE_CCS1_Liquid ||
+        pDcChargingInfo->CCSGunType == _TYPE_CCS1_Natural) {
+        ChangeDisplay2Value(_Icon_Select_Right, _TCC_IDLE_RIGHT_CCS1);
+
+    } else if (pDcChargingInfo->CCSGunType == _TYPE_CCS2_Liquid ||
+        pDcChargingInfo->CCSGunType == _TYPE_CCS2_Natural) {
+        ChangeDisplay2Value(_Icon_Select_Right, _TCC_IDLE_RIGHT_CCS2);
+    } else if (pDcChargingInfo->Type == _Type_Chademo) {
+        ChangeDisplay2Value(_Icon_Select_Right, _TCC_IDLE_RIGHT_CHAdeMo);
+    }
+}
+void ShowParkingInfo(bool is_show,uint8_t gunIndex)
+{
+    char cmd[32];
+    if (is_show) {
+        ChangeDisplay2Value(_Icon_ParkingInfo,_TCC_ParkingInfo);
+        memset(cmd, 0x00, sizeof(cmd));
+        sprintf((char *)cmd,"%s",ShmDcCommonData->ParkingInfo[gunIndex].ParkingStartTime);
+        DisplayValueToLcm(_String_ParkingStartTime, (uint8_t *)cmd, sizeof(cmd));
+        memset(cmd, 0x00, sizeof(cmd));
+        sprintf((char *)cmd,"%d",ShmDcCommonData->ParkingInfo[gunIndex].ParkingDuration);
+        DisplayValueToLcm(_String_ParkingDuration, (uint8_t *)cmd, sizeof(cmd));
+        memset(cmd, 0x00, sizeof(cmd));
+        sprintf((char *)cmd,"%d",(int)ShmDcCommonData->ParkingInfo[gunIndex].Amount);
+        DisplayValueToLcm(_String_ParkingFee, (uint8_t *)cmd, sizeof(cmd));
+    } else {
+        if (pSysInfo->SystemPage == _PAGE_BILL) {
+            ChangeDisplay2Value(_Icon_ParkingInfo,_TCC_ICON_SelectChargeMode);
+        } else if (pSysInfo->SystemPage >= _PAGE_ADD_FRIEND && pSysInfo->SystemPage <= _PAGE_AUTHORIZE) {
+            ChangeDisplay2Value(_Icon_ParkingInfo,_TCC_ICON_SelectPayMode);
+        } else {
+            ChangeDisplay2Value(_Icon_ParkingInfo,NULL);
+        }
+        memset(cmd, 0x00, sizeof(cmd));
+        DisplayValueToLcm(_String_ParkingStartTime, (uint8_t *)cmd, sizeof(cmd));
+        DisplayValueToLcm(_String_ParkingDuration, (uint8_t *)cmd, sizeof(cmd));
+        DisplayValueToLcm(_String_ParkingFee, (uint8_t *)cmd, sizeof(cmd));
+    }
+    if (pSysInfo->SystemPage >= _PAGE_BILL && pSysInfo->SystemPage <= _PAGE_SELECT_PAY)
+        ShowParkingCountDown(is_show);
+}
+int old_money = 0;
+int ClearQR_flag[2];
+void ProcessPageInfo()
+{
+    if (ShmDcCommonData->CreditCardUpload) {
+        pSysInfo->SystemPage = _PAGE_PAYING;
+    }
+    // Show Gun Working and Type
+    
+    if (pSysInfo->SystemPage == _PAGE_IDLE) {
+    	changeWeatherValue(ShmDcCommonData->WeatherID);
+    	changeWeekValue(0);
+    	changeDegreeValue((int)ShmDcCommonData->Temperature);
+    	changeDateValue(&ShmDcCommonData->PresentTime[0]);
+    	changeLocationValue(1000);
+        changeGunType();
+        ClearQR_flag[pSysInfo->CurGunSelected] = FALSE;
+    	return;
+    }
+    
+    if (pSysInfo->SystemPage == _PAGE_MAINTAIN) {
+
+        pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(LEFT_GUN_NUM);
+        if (pDcChargingInfo->CCSGunType == _TYPE_CCS1_Liquid ||
+                pDcChargingInfo->CCSGunType == _TYPE_CCS1_Natural) {
+            ChangeDisplay2Value(_Icon_ShowLeft,_TCC_ShowLeft_CCS1_Off);
+
+        } else if (pDcChargingInfo->CCSGunType == _TYPE_CCS2_Liquid ||
+                pDcChargingInfo->CCSGunType == _TYPE_CCS2_Natural) {
+            ChangeDisplay2Value(_Icon_ShowLeft,_TCC_ShowLeft_CCS2_Off);
+        } else if (pDcChargingInfo->Type == _Type_Chademo) {
+            ChangeDisplay2Value(_Icon_ShowLeft,_TCC_ShowLeft_CHAdeMo_Off);
+        }
+
+        // Set Right Gun
+        pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(RIGHT_GUN_NUM);
+        if (pDcChargingInfo->CCSGunType == _TYPE_CCS1_Liquid ||
+                pDcChargingInfo->CCSGunType == _TYPE_CCS1_Natural) {
+            ChangeDisplay2Value(_Icon_ShowRight,_TCC_ShowRight_CCS1_Off);
+
+        } else if (pDcChargingInfo->CCSGunType == _TYPE_CCS2_Liquid ||
+                pDcChargingInfo->CCSGunType == _TYPE_CCS2_Natural) {
+            ChangeDisplay2Value(_Icon_ShowRight,_TCC_ShowRight_CCS2_Off);
+        } else if (pDcChargingInfo->Type == _Type_Chademo) {
+            ChangeDisplay2Value(_Icon_ShowRight,_TCC_ShowRight_CHAdeMo_Off);
+        }
+        ChangeQrCode_Error();
+    	return;
+    }
+    showGunWorkingType();
+    for (uint8_t i = 0; i < pSysConfig->TotalConnectorCount; i++) {
+
+        if (pSysInfo->CurGunSelected == i) {
+            pDcChargingInfo = (struct ChargingInfoData*)GetDcChargingInfoData(i);
+
+            if (pDcChargingInfo->SystemStatus == S_IDLE) {
+                _everyPageRollChange = 0;
+                _Text_Running_Count = 1;
+            }
+            if (pSysInfo->SystemPage == _PAGE_AUTHORIZE) {
+                if (ShmDcCommonData->pGunInfo[i].ParkingStatus) {
+                    ChangeDisplay2Value(_Icon_Return,NULL);
+                } else {
+                    ChangeDisplay2Value(_Icon_Return,_TCC_Return);
+                }
+                ShowParkingCountDown(FALSE);
+            } else {
+                ChangeDisplay2Value(_Icon_Return,_TCC_Return);
+            }
+            switch (pSysInfo->SystemPage) {
+            case _PAGE_IDLE:
+                ShowSelectGun();
+                ClearQR_flag[i] = FALSE;
+            	break;
+            case _PAGE_SELECT_PAY:
+                if (ShmDcCommonData->pGunInfo[i].ParkingStatus) {
+                    ShowParkingInfo(true,i);
+                } else {
+                    ShowParkingInfo(false,i);
+                }
+
+            	break;
+            case _PAGE_SELECT_GUN:
+            	ShowSelectGun();
+            	ClearQR_flag[i] = FALSE;
+				break;
+            case _PAGE_BILL:
+                if (ShmDcCommonData->pGunInfo[i].ParkingStatus) {
+                    ChangeDisplay2Value(_Icon_Add_Line,_TCC_ParkingLine);
+                    ChangeDisplay2Value(_Icon_Donate,_TCC_ParkingDonate);
+                    ShowParkingInfo(true,i);
+
+                } else {
+                    ChangeDisplay2Value(_Icon_Add_Line,_TCC_GetBill);
+                    ChangeDisplay2Value(_Icon_Donate,_TCC_DonateBill);
+                    ShowParkingInfo(false,i);
+                }
+            	break;
+            case _PAGE_AUTHORIZE:
+                StartSystemTimeoutDet(Timeout_ScanCard);
+                if (ShmDcCommonData->pGunInfo[i].ParkingStatus) {
+                    ShowParkingInfo(true,i);
+                    ChangeDisplay2Value(_Icon_CreditCardFrame,_TCC_ParkingFee);
+                    ChangeChargingRateValue(ShmDcCommonData->ChargingRate,FALSE);
+                    ChangeParkingRateValue(ShmDcCommonData->ParkingRate,FALSE);
+                    ChangeParkingLeaveTime(ShmDcCommonData->ParkingLeaveTime,FALSE);
+                } else {
+                    ShowParkingInfo(false,i);
+                    ChangeDisplay2Value(_Icon_CreditCardFrame,_TCC_CardSensing_Frame);
+                    ChangeChargingRateValue(ShmDcCommonData->ChargingRate,TRUE);
+                    ChangeParkingRateValue(ShmDcCommonData->ParkingRate,TRUE);
+                    ChangeParkingLeaveTime(ShmDcCommonData->ParkingLeaveTime,TRUE);
+                }
+                ShowAuthorizeCountDown();
+
+                break;
+            case _PAGE_SENSING:
+                if (ShmDcCommonData->TradeCancel == TRUE) {
+                    TradeRunning(FALSE);
+                }
+                else
+                    TradeRunning(TRUE);
+                break;
+            case _PAGE_PLUGIN:
+            	_everyPageRollChange = 0;
+                if (ShmDcCommonData->pGunInfo[i].isParking) {
+                    ChangeDisplay2Value(_Icon_PreAuth_Complete,_TCC_ParkingLeave);
+                    ChangeParkingRateValue(ShmDcCommonData->ParkingRate,FALSE);
+                    ChangeParkingLeaveTime(ShmDcCommonData->ParkingLeaveTime,FALSE);
+                    ChangeSaleLeaveTime(ShmDcCommonData->SaleLeaveTime,TRUE);
+                } else {
+                    ChangeDisplay2Value(_Icon_PreAuth_Complete,_TCC_PaySuccess);
+                    ChangeParkingRateValue(ShmDcCommonData->ParkingRate,TRUE);
+                    ChangeParkingLeaveTime(ShmDcCommonData->ParkingLeaveTime,TRUE);
+                    ChangeSaleLeaveTime(ShmDcCommonData->SaleLeaveTime,FALSE);
+                }
+                break;
+            case _PAGE_ADD_FRIEND:
+                if(ClearQR_flag[i] == FALSE) {
+                    ClearQrCode_Idle();
+            		ClearQR_flag[i] = TRUE;
+            	}
+            	ChangeQrCode_Idle((char *)pSysConfig->SystemId);
+                if (ShmDcCommonData->pGunInfo[i].ParkingStatus) {
+                    ShowParkingInfo(true,i);
+                    ShowLineRegisterCountDown(FALSE);
+                } else {
+                    ShowLineRegisterCountDown(TRUE);
+                    ShowParkingInfo(false,i);
+                }
+
+                break;
+            case _PAGE_PRECHARGE:
+            	RefreshProgressAnimation();
+            	if (_everyPageRollChange == 0) {
+            		ChangeDisplay2Value(_Icon_Precharge,_Text_Running_Count);
+            		_Text_Running_Count >= 24 ? _Text_Running_Count = 24 : _Text_Running_Count++;
+            	}
+                break;
+            case _PAGE_CHARGING:
+                if (pDcChargingInfo->PresentChargingPower >= 0 &&
+                        pDcChargingInfo->PresentChargingPower <= POWER_MAX_KW) {
+
+                    ChangeChargingPowerValue(pDcChargingInfo->PresentChargingPower);
+                } else {
+                    ChangeChargingPowerValue(0);
+                }
+                if (pDcChargingInfo->PresentChargedEnergy >= 0.1 &&
+                        pDcChargingInfo->PresentChargedEnergy <= ENERGY_MAX_KWH) {
+
+                    ChangeChargingEnergyValue(pDcChargingInfo->PresentChargedEnergy);
+                } else {
+                    ChangeChargingEnergyValue(0);
+                }
+                if ( pDcChargingInfo->ChargingFee >= 0) {
+                    ChangeChargingFeeValue(pDcChargingInfo->ChargingFee);
+
+                }
+                if (pDcChargingInfo->RemainChargingDuration >= 0 &&
+                        pDcChargingInfo->RemainChargingDuration <= TIME_MAX_SEC) {
+                	ChangeTimeValue(pDcChargingInfo->RemainChargingDuration/60);
+                } else {
+                	ChangeTimeValue(0);
+                }
+                ChangeBattMapAndValue(pDcChargingInfo->EvBatterySoc);
+                StartSystemTimeoutDet(Timeout_ReturnViewPage);
+                break;
+            case _PAGE_COMPLETE:
+            case _PAGE_PAYFAIL:
+
+                if (pDcChargingInfo->PresentChargedEnergy >= 0.1 &&
+                        pDcChargingInfo->PresentChargedEnergy <= ENERGY_MAX_KWH) {
+                    ChangeChargingEnergyValue(pDcChargingInfo->PresentChargedEnergy);
+                } else {
+                    ChangeChargingEnergyValue(0);
+                }
+
+				ChangeChargingFeeValue(ShmDcCommonData->TransactionInfo[i].Amount);
+                ChangeCarBonValue(pDcChargingInfo->PresentChargedEnergy);
+                ChangeBattMapAndValue(pDcChargingInfo->EvBatterySoc);
+                if (ShmDcCommonData->pGunInfo[i].ParkingStatus) {
+                    ChangeParkingRateValue(ShmDcCommonData->ParkingRate,FALSE);
+                    ChangeDisplay2Value(_Icon_CompleteBtn,_TCC_ParkingComplete);
+                } else {
+                    ChangeParkingRateValue(ShmDcCommonData->ParkingRate,TRUE);
+                    ChangeDisplay2Value(_Icon_CompleteBtn,_TCC_NoParkingComplete);
+                }
+                //StartSystemTimeoutDet(Timeout_ReturnViewPage);
+				
+                break;
+
+            case _PAGE_PLUGOUT:
+                if (ShmDcCommonData->pGunInfo[i].ParkingStatus) {
+                    ChangeParkingRateValue(ShmDcCommonData->ParkingRate,FALSE);
+                    ChangeDisplay2Value(_Icon_CompleteBtn,_TCC_ParkingComplete);
+                } else {
+                    ChangeParkingRateValue(ShmDcCommonData->ParkingRate,TRUE);
+                    ChangeDisplay2Value(_Icon_CompleteBtn,NULL);
+                }
+            	break;
+            case _PAGE_PAYING:
+                ChangeDisplay2Value(_Icon_Ani_Dot, 1);
+                if (ShmDcCommonData->CreditCardUpload) {
+                    ChangeDisplay2Value(_Icon_Uploading, _TCC_Uploading);
+                    ChangeDisplay2Value(_Icon_Paying, _ICON_Empty);
+                } else {
+                    if (ShmDcCommonData->StopCharge[i]) {
+                        ChangeDisplay2Value(_Icon_Uploading, _ICON_Empty);
+                        ChangeDisplay2Value(_Icon_Paying, _TCC_Paying);
+                    } else if (ShmDcCommonData->pGunInfo[i].isParking){
+                        ChangeDisplay2Value(_Icon_Uploading, _TCC_WaitParkInfo);
+                        ChangeDisplay2Value(_Icon_Paying, _ICON_Empty);
+                    }
+                }
+            	break;
+            case _PAGE_EXIT:
+                
+                break;
+            case _PAGE_LINEPAYING:
+                StartSystemTimeoutDet(Timeout_LINEPAYING);
+                break;
+            case _PAGE_MAINTAIN:
+                ChangeQrCode_Error();
+                break;
+            }
+        }
+    }
+}
+
+/*
+void InformationShow()
+{
+    is_show = true;
+    if (_showInformIndex == 0 ) {
+        pSysInfo->PageIndex = __SHOW_CABIENT_VERSION;
+    } else {
+        pSysInfo->PageIndex = __SHOW_DISPENSER_VERASION;
+        ShowDispenserVersion();
+    }
+}
+*/
+
+void DefautLayOut()
+{
+	int i;
+	for (i = 0 ; i <= 0x5C ; i+=2 ) {
+		ChangeDisplay2Value(0x1000+i,1);
+		if (i==0x28 || i ==0x2A)
+			continue;
+	}
+	ChangeDisplay2Value(_Icon_MobilePay,0);
+	ChangeDisplay2Value(_Icon_CardPay,0);
+	ChangeDisplay2Value(0x5000,1);
+    //ChangeDisplay2Value(_QRCode_Service, 1);
+	ShowSelectGun();
+}
+/*
+static int InitialRfidPort(void)
+{
+    int fd = open(rfidPortName, O_RDWR);
+    struct termios tios;
+    struct AlarmCodeData *pAlarmCode = (struct AlarmCodeData *)GetShmAlarmCodeData();
+
+    if (fd != FAIL) {
+        ioctl (fd, TCGETS, &tios);
+        tios.c_cflag = B115200 | CS8 | CLOCAL | CREAD;
+        tios.c_lflag = 0;
+        tios.c_iflag = 0;
+        tios.c_oflag = 0;
+        tios.c_cc[VMIN] = 0;
+        tios.c_cc[VTIME] = (uint8_t) 1;
+        tios.c_lflag = 0;
+        tcflush(fd, TCIFLUSH);
+        ioctl(fd, TCSETS, &tios);
+    }
+
+    if (fd < 0) {
+        pAlarmCode->AlarmEvents.bits.RfidModuleCommFail = 1;
+    }
+
+    return fd;
+}
+*/
+void DemoFunction(int index)
+{
+    int i;
+    showGunWorkingType();
+    switch (index) {
+    case 1:   // _PAGE_IDLE
+        /*
+        for (i = 0; i <= 100; i++) {
+            changeWeatherValue(i / 20);
+            ChangeDisplay2Value(_Icon_Week, i / 15);
+            changeDegreeValue(i);
+            sprintf(text, "20%02d/%02d/%02d %02d:%02d:%02d", i, i, i, i, i, i);
+            DisplayValueToLcm(_String_Date, (uint8_t*)text, 30);
+            usleep(100000);
+        }
+        */
+        break;
+    case 3:
+        ChangeQrCode_Idle((char*)pSysConfig->SystemId);
+        sleep(3);
+        break;
+    case 4:  //_PAGE_ADD_FRIEND
+        for (i = 0; i <= 10; i++) {
+            ChangeDisplay2Value(_Icon_ScanCntDownTen, (short)_TCC_CntDownNumber0 + i);
+            ChangeDisplay2Value(_Icon_ScanCntDownDigits, (short)_TCC_CntDownNumber0 + i);
+            usleep(100000);
+        }
+        break;
+    case 7:  //_PAGE_AUTHORIZE
+        for (i = 0; i < 10; i++) {
+            ChangeChargingRateValue(i+i*10,TRUE);
+            ChangeDisplay2Value(_Icon_AuthCntDownTen, (short)_TCC_CntDownNumber0 + i);
+            ChangeDisplay2Value(_Icon_AuthCntDownDigits, (short)_TCC_CntDownNumber0 + i);
+            usleep(100000);
+        }
+        break;
+    case 8:  //_PAGE_SENSING
+        for (i = 0; i < 10; i++) {
+            ChangeDisplay2Value(_Icon_CancelCntDownTen, (short)(_TCC_CancelNum_0 + i));
+            ChangeDisplay2Value(_Icon_CancelCntDownDigits, (short)(_TCC_CancelNum_0 + i));
+            usleep(100000);
+        }
+        break;
+    case 10:  //_PAGE_PRECHARGE
+        for (i = 1; i <= 24; i++) {
+            ChangeDisplay2Value(_Icon_Precharge, i);
+            usleep(100000);
+        }
+        break;
+    case 11:  //_PAGE_CHARGING
+        for (i = 0; i <= 100; i++) {
+            ChangeChargingPowerValue(i);
+            ChangeChargingEnergyValue(i);
+            ChangeChargingFeeValue(i);
+            ChangeTimeValue(i);
+            ChangeBattMapAndValue(i);
+            usleep(100000);
+        }
+        break;
+    case 13:  //_PAGE_PAYING
+        break;
+    case 14:  //_PAGE_COMPLETE
+    case 20:  //_PAGE_PAYFAIL
+        for (i = 0; i <= 100; i++) {
+            ChangeChargingEnergyValue(i);
+            ChangeChargingFeeValue(i);
+            ChangeCarBonValue(i*2);
+            ChangeBattMapAndValue(i);
+            usleep(100000);
+        }
+        break;
+    }
+    sleep(1);
+}
+int main(void)
+{
+    bool defaulttext = false;
+    if (CreateAllCsuShareMemory() == FAIL) {
+        log_error("create share memory error");
+        return FAIL;
+    }
+
+    MappingGunChargingInfo("LCM Control Task");
+
+    pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
+    pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
+    pSysWarning = (struct WARNING_CODE_INFO *)GetShmSysWarningInfo();
+    ShmFanModuleData = (struct FanModuleData *)GetShmFanModuleData();;
+    ShmPrimaryMcuData = (struct PrimaryMcuData *)GetShmPrimaryMcuData();
+    ShmSelectGunInfo = (SelectGunInfo *)GetShmSelectGunInfo();
+    ShmDcCommonData = (DcCommonInfo *)GetShmDcCommonData();
+    ShmOCPP16Data = (struct OCPP16Data *)GetShmOCPP16Data();
+    struct StatusCodeData *ShmStatusCodeData = (struct StatusCodeData *)GetShmStatusCodeData();;
+
+    _port = CreateCommunicationLcmPort();
+    uint8_t changeWarningPriority = 0;
+    uint8_t curWarningCount = 255;
+    uint8_t light = 0x64;
+    ShmDcCommonData->BackLight = light;
+    ChangeBackLight(light);
+    _totalCount = pSysConfig->TotalConnectorCount;
+    _everyPageRollChange = 0;
+    //Initialization();
+
+    //printf("_LCM_COMPLETE ");
+    //ChangeToOtherPage(_LCM_COMPLETE);
+    DefautLayOut();
+    //return 0;
+    uint8_t index = 1;
+
+    ShmDcCommonData->PSU_Number = 12;
+    /*
+    CardReadFd = InitialRfidPort();
+    if (CardReadFd <0) {
+    	log_info("Card Read Port open fail!");
+    }*/
+
+    CheckLCMPressed();
+
+    while (_port != -1) {
+        if (strcmp((char *)pSysInfo->LcmHwRev, moduleName) != 0x00) {
+            GetCurrentPage();
+            sleep(1);
+
+            ShmStatusCodeData->AlarmCode.AlarmEvents.bits.LcmModuleCommFail = true;
+        } else {
+            UpdateLcmFunction(ShmDcCommonData,_port);
+
+            if (ShmDcCommonData->BackLight != light) {
+                ChangeBackLight(ShmDcCommonData->BackLight);
+                light = ShmDcCommonData->BackLight;
+                log_info("Set Backlight:%d",light);
+            }
+            ///*
+            ShmStatusCodeData->AlarmCode.AlarmEvents.bits.LcmModuleCommFail = false;
+            // 頁面資訊處理
+            if (!ShmDcCommonData->lcmtest)
+                ProcessPageInfo();
+            else
+                pSysInfo->SystemPage = index;
+
+            // 換頁處理
+            //GetCurrentPage(); //DS60-120 add
+            /*
+            if (pSysConfig->ShowInformation == YES && pSysInfo->SystemPage == _PAGE_AUTHORIZE) {
+                InformationShow();
+                ChangeToOtherPage(pSysInfo->PageIndex);
+                usleep(100000);
+                continue;
+            } else {
+                if (is_show)
+                    _showInformIndex >= 1 ? _showInformIndex = 0 : _showInformIndex++;
+                is_show = false;
+            }*/
+            GetCurrentPage(); //DS60-120 add
+
+            ChangeCurPage();
+            changeWarningPriority >= 30 ? changeWarningPriority = 0 : changeWarningPriority++;
+            if (ShmDcCommonData->lcmtest) {
+                DemoFunction(index);
+                index >= 20 ? index = 1 : index++;
+            }
+            usleep(10000); //*/
+
+            /*
+            GetCurrentPage();
+            ChangeCurPage();
+            usleep(10000);
+            //*/
+        }
+    } //while
+
+    ShmStatusCodeData->AlarmCode.AlarmEvents.bits.LcmModuleCommFail = true;
+
+    log_info("Close LCM Uart Port");
+    CloseCommunicationLcmPort();
+
+    return FAIL;
+}

+ 367 - 367
EVSE/Projects/DD360Tcci/Apps/ModuleLcmCtrl/Module_LcmControl.h

@@ -1,367 +1,367 @@
-#ifndef MODULE_LCM_CTRL_H_
-#define MODULE_LCM_CTRL_H_
-#include <stdint.h>
-#include <stdbool.h>
-#include "../Define/define.h"
-
-//------------------------------------------------------------------------------
-#define PREAUTHMONEY						2000
-#define RETURNIDLE_Timeout					60
-#define DEFAULT_AC_INDEX                        (2)
-
-#define TIME_MAX_SEC                            (2592000) // 一個月,秒數
-#define POWER_MAX_KW                            (5000)
-#define ENERGY_MAX_KWH                          (5000)
-
-#define CMD_TITLE_1                             (0x5A)
-#define CMD_TITLE_2                             (0xA5)
-#define CMD_READ                                (0x80)
-#define CMD_WRITE                               (0x81)
-#define CMD_MULTI_WRITE                         (0x82)
-#define CMD_MULTI_READ                          (0x83)
-
-#define CMD_BACKLIGHT                           (0x01)
-#define CMD_REGISTER                            (0x03)
-
-#define CMD_HEADER_1                        0x5A
-#define CMD_HEADER_2                        0xA5
-#define CMD_REG_WRITE                       0x80
-#define CMD_REG_READ                        0x81
-#define CMD_REG_WRITE_DATA                  0x82
-#define CMD_REG_READ_DATA                   0x83
-
-#define REG_ADDRESS_READ_VERSION            0x0F
-#define REG_ADDRESS_READ_RTC                0x10
-#define REG_ADDRESS_READ_PAGE_ID            0x14
-#define REG_ADDRESS_READ_BRIGHTNESS         0x31
-#define REG_ADDRESS_WRITE_BRIGHTNESS        0X82
-#define REG_ADDRESS_SET_PAGE_ID             0x84
-#define REG_ADDRESS_SET_RTC                 0x9C
-#define REG_TYPE_CONTROL                    0x00
-#define REG_TYPE_RAM                        0x01
-#define REG_TYPE_SPECIAL_CONTROL            0x02
-
-#define _CHANGE_REMOTESTART     0x01
-#define _CHANGE_REFUNDING       0x02
-#define _CHANGE_REFUNDAMOUNT    0x03
-#define _CHANGE_NOREFUND        0x04
-#define _CHANGE_PREPAYMENTINFO  0x05
-#define _CHANGE_PAYMENT_OK      0x06
-#define _CHANGE_PAYMENT_FAIL    0x07
-
-
-#define _Animation				0x1000
-#define _Icon_TouchStart		0x1002
-#define _Icon_Location			0x1004
-#define _Icon_Week				0x1006
-#define _Icon_Weather			0x1008
-#define _Icon_Welcom_Ad			0x100A
-#define _Icon_Select_Left		0x100C
-#define _Icon_Select_Right		0x100E
-#define _Icon_NHOA				0x1010
-#define _Icon_Return			0x1012
-#define _Icon_Donate			0x1014
-#define _Icon_Add_Line			0x1016
-#define _Icon_ShowLeft			0x1018
-#define _Icon_ShowRight			0x101A
-#define _Icon_ScanComplete		0x101C
-#define _Icon_WordYes			0x101E
-#define _Icon_WordNo			0x1020
-#define _Icon_WordAddFriend		0x1022
-#define _Icon_PayFrame			0x1024
-#define _Icon_SenseRadio		0x1026
-#define _Icon_MobilePay			0x1028
-#define _Icon_CardPay			0x102A
-#define _Icon_CreditCardFrame	0x102C
-#define _Icon_PreAuth			0x102E
-#define _Icon_Ani_Dot			0x1030
-#define _Icon_PreAuth_Complete	0x1032
-#define _Icon_Precharge			0x1034
-#define _Icon_ChargeFrame		0x1036
-#define _Icon_WordKW			0x1038
-#define _Icon_ChargeCircle		0x103A
-#define _Icon_ChargeBar			0x103C
-#define _Icon_Paying			0x103E
-#define _Icon_CompleteFrame		0x1040
-#define _Icon_CompleteCircle	0x1042
-#define _Icon_ExitAd			0x1044
-#define _Icon_ExitBar			0x1046
-#define _Icon_ExitWord			0x1048
-#define _Icon_PlugoutFrame		0x104A
-#define _Icon_PreAuthFail		0x104C
-#define _Icon_ReWork			0x1050
-#define _Icon_FixFrame			0x1052
-#define _Icon_Warming0			0x1054
-#define _Icon_Warming1			0x1056
-#define _Icon_Warming2			0x1058
-#define _Icon_Warming3			0x105A
-#define _Icon_Warming4			0x105C
-#define _Icon_StopCharge		0x105E
-#define _Icon_CountDownBG		0x1060
-#define _Icon_CancelCntDownTen	0x1062
-#define _Icon_CancelCntDownDigits	0x1064
-#define _Icon_ScanCntDownTen    0x1066
-#define _Icon_ScanCntDownDigits 0x1068
-#define _Icon_AuthCntDownTen    0x106A
-#define _Icon_AuthCntDownDigits 0x106C
-#define _Icon_Uploading         0x1070
-#define _Icon_DAKAWelcome       0x1072
-#define _Icon_PreAuthWord       0x1074
-#define _Icon_ParkingInfo		0x1076
-#define _Icon_ParkingLeave		0x1078
-#define _Icon_CompleteBtn		0x107A
-#define _Icon_ParkingCntDw_BG	0x107C
-#define _Icon_ParkingCntDw_Tens	0x107E
-#define _Icon_ParkingCntDw_Digits	0x1080
-#define _Icon_ScanCntDw_BG		0x1082
-#define _Icon_ParkingCntDw_Hun  0x1084
-
-#define _String_Date			0x3000
-#define _String_Tempture		0x3010
-#define _QRCode_AddLine			0x3020
-#define _String_ChargeRate		0x3030
-#define _String_ChargeTime		0x3040
-#define _String_ChargePower		0x3050
-#define _String_Battery			0x3060
-#define _Strting_Energy			0x3070
-#define _String_Money			0x3080
-#define _String_ParkRate		0x3090
-#define _String_Carbon			0x30A0
-#define _QRCode_Service			0x30B0
-#define _String_ParkingStartTime 0x30C0
-#define _String_ParkingDuration	0x30D0
-#define _String_ParkingFee		0x30E0
-#define _String_ParkingLeaveTime	0x30F0
-#define _String_SaleLeaveTime	0x3100
-
-#define _Touch_IDLE				0x1500
-#define _Touch_Select_Left		0x1502
-#define _Touch_Select_Right		0x1504
-#define _Touch_Show_Left		0x1506
-#define _Touch_Show_Right		0x1508
-#define _Touch_Return			0x150A
-#define _Touch_DonateBill		0x150C
-#define _Touch_DonateYes		0x150E
-#define _Touch_DonateNo			0x1510
-#define _Touch_StopCharge		0x1512
-#define _Touch_Stop_Confirm		0x1514
-#define _Touch_Stop_Cancel		0x1516
-#define _Touch_Pay_CreditCard	0x1518
-#define _Touch_Pay_LinePay		0x151A
-#define _Touch_Parking_Complete	0x151C
-
-enum _TCC_ICON_LIST_ {
-	_ICON_Empty 			= 0,
-	_TCC_Week_Monday,
-	_TCC_Week_Tuesday,
-	_TCC_Week_Wensday,
-	_TCC_Week_Thrusday,
-	_TCC_Week_Friday,
-	_TCC_Week_Saturday,
-	_TCC_Week_Sunday,
-	_TCC_TouchStart,
-	_TCC_Sun,
-	_TCC_Cloudy,
-	_TCC_Rain,
-	_TCC_Snow,
-	_TCC_Thunder,
-	_TCC_Fog,
-	_TCC_Taipei_ZhongShan,
-	_TCC_Scan_CntDw_BG,
-	_TCC_Welcom_Coffee,
-	_TCC_SelectLeft_CCS1,
-	_TCC_SelectLeft_CCS2,
-	_TCC_SelectLeft_CHAdeMo,
-	_TCC_SelectRight_CCS1,
-	_TCC_SelectRight_CCS2,
-	_TCC_SelectRight_CHAdeMo,
-	_TCC_Return,
-	_TCC_DonateBill,
-	_TCC_GetBill,
-	_TCC_ShowLeft_CCS1_Off,
-	_TCC_ShowLeft_CCS2_Off,
-	_TCC_ShowLeft_CHAdeMo_Off,
-	_TCC_ShowLeft_CCS1_On,
-	_TCC_ShowLeft_CCS2_On,
-	_TCC_ShowLeft_CHAdeMo_On,
-	_TCC_ShowRight_CCS1_Off,
-	_TCC_ShowRight_CCS2_Off,
-	_TCC_ShowRight_CHAdeMo_Off,
-	_TCC_ShowRight_CCS1_On,
-	_TCC_ShowRight_CCS2_On,
-	_TCC_ShowRight_CHAdeMo_On,
-	_TCC_ScanQR_Pass,
-	_TCC_SelectPayMode,
-	_TCC_CreditCard_Wifi,
-	_TCC_CreditCard_Frame,
-	_TCC_PreAuthWord,
-	_TCC_LinePay,
-	_TCC_CardSensing_Frame,
-	_TCC_PreAuth,
-	_TCC_Dot_0,
-	_TCC_PaySuccess 		= 62,
-	_TCC_Plugin,
-	_TCC_ChargingFrame,
-	_TCC_StopCharging,
-	_TCC_String_KW,
-	_TCC_Charging_Circle0,
-	_TCC_Charging_Bar0     	= 104,
-	_TCC_NHOA 				= 204,
-	_TCC_WordYes			= 206,
-	_TCC_WordNo,
-	_TCC_Paying,
-	_TCC_CompleteFrame,
-	_TCC_CompleteCircle0,
-	_TCC_EnjoyLife   		= 247,
-	_TCC_BlackBar,
-	_TCC_ExitAd,
-	_TCC_PayFail,
-	_TCC_Restart,
-	_TCC_PlugOutFrame,
-	_TCC_ErrorFrame,
-	_TCC_Warming,
-	_TCC_FAILCircle0,
-	_TCC_ShowLeftGunCharging_CCS1 = 292,
-	_TCC_ShowLeftGunCharging_CCS2,
-	_TCC_ShowLeftGunCharging_CHAdeMo,
-	_TCC_ShowRightGunCharging_CCS1,
-	_TCC_ShowRightGunCharging_CCS2,
-	_TCC_ShowRightGunCharging_CHAdeMo,
-	_TCC_ReturnFrontPage,
-	_TCC_CancelNum_0,
-	_TCC_TradeCancelString = 309,
-	_TCC_TradeCancelFrame,
-	_TCC_SecondSense,
-	_TCC_CntDownNumber0,
-	_TCC_Uploading = 323,
-	_TCC_IDLE_LEFT_CCS1,
-	_TCC_IDLE_LEFT_CCS2,
-	_TCC_IDLE_LEFT_CHAdeMo,
-	_TCC_IDLE_RIGHT_CCS1,
-	_TCC_IDLE_RIGHT_CCS2,
-	_TCC_IDLE_RIGHT_CHAdeMo,
-	_TCC_ShowLeftGunReservation_CCS1,
-	_TCC_ShowLeftGunReservation_CCS2,
-	_TCC_ShowLeftGunReservation_CHAdeMo,
-	_TCC_ShowRightGunReservation_CCS1,
-	_TCC_ShowRightGunReservation_CCS2,
-	_TCC_ShowRightGunReservation_CHAdeMo,
-	_TCC_LeftParkingIdle,
-	_TCC_RightParkingIdle,
-	_TCC_LeftParkingSel,
-	_TCC_RightParkingSel,
-	_TCC_ParkingInfo,
-	_TCC_ParkingLine,
-	_TCC_ParkingDonate,
-	_TCC_ParkingFee,
-	_TCC_ParkingLeave,
-	_TCC_NoParkingComplete,
-	_TCC_ParkingComplete,
-	_TCC_LinePaying,
-	_TCC_ParkingCntDown_BG,
-	_TCC_ParkingCD_0,
-	_TCC_ParkingCD_1,
-	_TCC_ParkingCD_2,
-	_TCC_ParkingCD_3,
-	_TCC_ParkingCD_4,
-	_TCC_ParkingCD_5,
-	_TCC_ParkingCD_6,
-	_TCC_ParkingCD_7,
-	_TCC_ParkingCD_8,
-	_TCC_ParkingCD_9,
-	_TCC_WaitParkInfo,
-	_TCC_ParkingCntDown_BG3,
-	_TCC_ICON_SelectChargeMode,
-	_TCC_ICON_SelectPayMode,
-};
-
-
-/* Show Version */
-
-#define _Version_Cabient_Name_Text          0x0500
-#define _Version_Cabient_BootLoader_Text    0x0510
-#define _Version_Cabient_Kernel_Text        0x0520
-#define _Version_Cabient_CSU_Text           0x0530
-#define _Version_Cabient_Priamry_Text       0x0540
-#define _Version_Cabient_Relay0_Text        0x0550
-#define _Version_Cabient_Relay1_Text        0x0560
-#define _Version_Cabient_Fan_Text           0x0570
-#define _Version_Cabient_IPAddr_Text        0x0580
-#define _Version_Cabient_PSU1_Text          0x0590
-#define _Version_Cabient_PSU2_Text          0x05A0
-#define _Version_Cabient_PSU3_Text          0x05B0
-#define _Version_Cabient_PSU4_Text          0x05C0
-#define _Version_Cabient_PSU5_Text          0x05D0
-#define _Version_Cabient_PSU6_Text          0x05E0
-#define _Version_Cabient_PSU7_Text          0x05F0
-#define _Version_Cabient_PSU8_Text          0x0600
-#define _Version_Cabient_PSU9_Text          0x0610
-#define _Version_Cabient_PSU10_Text         0x0620
-#define _Version_Cabient_PSU11_Text         0x0630
-#define _Version_Cabient_PSU12_Text         0x0640
-
-#define _Version_Cabient_Primary_Text       0x0920
-#define _Version_Cabient_Secondary_Text     0x0930
-
-#define _Version_Cabient_Model_value        0x0650
-#define _Version_Cabient_BootLoader_value   0x0660
-#define _Version_Cabient_Kernel_value       0x0670
-#define _Version_Cabient_CSU_value          0x0680
-#define _Version_Cabient_Priamry_value      0x0690
-#define _Version_Cabient_Relay0_value       0x06A0
-#define _Version_Cabient_Relay1_value       0x06B0
-#define _Version_Cabient_Fan_value          0x06C0
-#define _Version_Cabient_IPAddr_value       0x06D0
-#define _Version_Cabient_PSU_Prim1_value    0x06E0
-#define _Version_Cabient_PSU_Prim2_value    0x06F0
-#define _Version_Cabient_PSU_Prim3_value    0x0700
-#define _Version_Cabient_PSU_Prim4_value    0x0710
-#define _Version_Cabient_PSU_Prim5_value    0x0720
-#define _Version_Cabient_PSU_Prim6_value    0x0730
-#define _Version_Cabient_PSU_Sec1_value     0x0740
-#define _Version_Cabient_PSU_Sec2_value     0x0750
-#define _Version_Cabient_PSU_Sec3_value     0x0760
-#define _Version_Cabient_PSU_Sec4_value     0x0770
-#define _Version_Cabient_PSU_Sec5_value     0x0780
-#define _Version_Cabient_PSU_Sec6_value     0x0790
-
-#define _Version_Cabient_PSU_Prim7_value    0x09E0
-#define _Version_Cabient_PSU_Prim8_value    0x09F0
-#define _Version_Cabient_PSU_Prim9_value    0x1000
-#define _Version_Cabient_PSU_Prim10_value   0x1010
-#define _Version_Cabient_PSU_Prim11_value   0x1020
-#define _Version_Cabient_PSU_Prim12_value   0x1030
-#define _Version_Cabient_PSU_Sec7_value     0x1040
-#define _Version_Cabient_PSU_Sec8_value     0x1050
-#define _Version_Cabient_PSU_Sec9_value     0x1060
-#define _Version_Cabient_PSU_Sec10_value    0x1070
-#define _Version_Cabient_PSU_Sec11_value    0x1080
-#define _Version_Cabient_PSU_Sec12_value    0x1090
-
-#define _Version_Dispenser_Name_Text        0x07A0
-#define _Version_Dispenser_BootLoader_Text  0x07B0
-#define _Version_Dispenser_Kernel_Text      0x07C0
-#define _Version_Dispenser_CSU_Text         0x07D0
-#define _Version_Dispenser_Relay_Text       0x07E0
-#define _Version_Dispenser_Fan_Text         0x07F0
-#define _Version_Dispenser_Priamry_Text     0x0800
-#define _Version_Dispenser_LCM_Text         0x0810
-#define _Version_Dispenser_LED_Text         0x0820
-#define _Version_Dispenser_Connector0_Text  0x0830
-#define _Version_Dispenser_Connector1_Text  0x0840
-#define _Version_Dispenser_IPAddr_Text      0x0850
-
-#define _Version_Dispenser_Model_value      0x0860
-#define _Version_Dispenser_BootLoader_value 0x0870
-#define _Version_Dispenser_Kernel_value     0x0880
-#define _Version_Dispenser_CSU_value        0x0890
-#define _Version_Dispenser_Relay_value      0x08A0
-#define _Version_Dispenser_Fan_value        0x08B0
-#define _Version_Dispenser_Priamry_value    0x08C0
-#define _Version_Dispenser_LCM_value        0x08D0
-#define _Version_Dispenser_LED_value        0x08E0
-#define _Version_Dispenser_Connector0_value 0x08F0
-#define _Version_Dispenser_Connector1_value 0x0900
-#define _Version_Dispenser_IPAddr_value     0x0910
-
-#endif //MODULE_LCM_CTRL_H_
+#ifndef MODULE_LCM_CTRL_H_
+#define MODULE_LCM_CTRL_H_
+#include <stdint.h>
+#include <stdbool.h>
+#include "../Define/define.h"
+
+//------------------------------------------------------------------------------
+#define PREAUTHMONEY						2000
+#define RETURNIDLE_Timeout					60
+#define DEFAULT_AC_INDEX                        (2)
+
+#define TIME_MAX_SEC                            (2592000) // 一個月,秒數
+#define POWER_MAX_KW                            (5000)
+#define ENERGY_MAX_KWH                          (5000)
+
+#define CMD_TITLE_1                             (0x5A)
+#define CMD_TITLE_2                             (0xA5)
+#define CMD_READ                                (0x80)
+#define CMD_WRITE                               (0x81)
+#define CMD_MULTI_WRITE                         (0x82)
+#define CMD_MULTI_READ                          (0x83)
+
+#define CMD_BACKLIGHT                           (0x01)
+#define CMD_REGISTER                            (0x03)
+
+#define CMD_HEADER_1                        0x5A
+#define CMD_HEADER_2                        0xA5
+#define CMD_REG_WRITE                       0x80
+#define CMD_REG_READ                        0x81
+#define CMD_REG_WRITE_DATA                  0x82
+#define CMD_REG_READ_DATA                   0x83
+
+#define REG_ADDRESS_READ_VERSION            0x0F
+#define REG_ADDRESS_READ_RTC                0x10
+#define REG_ADDRESS_READ_PAGE_ID            0x14
+#define REG_ADDRESS_READ_BRIGHTNESS         0x31
+#define REG_ADDRESS_WRITE_BRIGHTNESS        0X82
+#define REG_ADDRESS_SET_PAGE_ID             0x84
+#define REG_ADDRESS_SET_RTC                 0x9C
+#define REG_TYPE_CONTROL                    0x00
+#define REG_TYPE_RAM                        0x01
+#define REG_TYPE_SPECIAL_CONTROL            0x02
+
+#define _CHANGE_REMOTESTART     0x01
+#define _CHANGE_REFUNDING       0x02
+#define _CHANGE_REFUNDAMOUNT    0x03
+#define _CHANGE_NOREFUND        0x04
+#define _CHANGE_PREPAYMENTINFO  0x05
+#define _CHANGE_PAYMENT_OK      0x06
+#define _CHANGE_PAYMENT_FAIL    0x07
+
+
+#define _Animation				0x1000
+#define _Icon_TouchStart		0x1002
+#define _Icon_Location			0x1004
+#define _Icon_Week				0x1006
+#define _Icon_Weather			0x1008
+#define _Icon_Welcom_Ad			0x100A
+#define _Icon_Select_Left		0x100C
+#define _Icon_Select_Right		0x100E
+#define _Icon_NHOA				0x1010
+#define _Icon_Return			0x1012
+#define _Icon_Donate			0x1014
+#define _Icon_Add_Line			0x1016
+#define _Icon_ShowLeft			0x1018
+#define _Icon_ShowRight			0x101A
+#define _Icon_ScanComplete		0x101C
+#define _Icon_WordYes			0x101E
+#define _Icon_WordNo			0x1020
+#define _Icon_WordAddFriend		0x1022
+#define _Icon_PayFrame			0x1024
+#define _Icon_SenseRadio		0x1026
+#define _Icon_MobilePay			0x1028
+#define _Icon_CardPay			0x102A
+#define _Icon_CreditCardFrame	0x102C
+#define _Icon_PreAuth			0x102E
+#define _Icon_Ani_Dot			0x1030
+#define _Icon_PreAuth_Complete	0x1032
+#define _Icon_Precharge			0x1034
+#define _Icon_ChargeFrame		0x1036
+#define _Icon_WordKW			0x1038
+#define _Icon_ChargeCircle		0x103A
+#define _Icon_ChargeBar			0x103C
+#define _Icon_Paying			0x103E
+#define _Icon_CompleteFrame		0x1040
+#define _Icon_CompleteCircle	0x1042
+#define _Icon_ExitAd			0x1044
+#define _Icon_ExitBar			0x1046
+#define _Icon_ExitWord			0x1048
+#define _Icon_PlugoutFrame		0x104A
+#define _Icon_PreAuthFail		0x104C
+#define _Icon_ReWork			0x1050
+#define _Icon_FixFrame			0x1052
+#define _Icon_Warming0			0x1054
+#define _Icon_Warming1			0x1056
+#define _Icon_Warming2			0x1058
+#define _Icon_Warming3			0x105A
+#define _Icon_Warming4			0x105C
+#define _Icon_StopCharge		0x105E
+#define _Icon_CountDownBG		0x1060
+#define _Icon_CancelCntDownTen	0x1062
+#define _Icon_CancelCntDownDigits	0x1064
+#define _Icon_ScanCntDownTen    0x1066
+#define _Icon_ScanCntDownDigits 0x1068
+#define _Icon_AuthCntDownTen    0x106A
+#define _Icon_AuthCntDownDigits 0x106C
+#define _Icon_Uploading         0x1070
+#define _Icon_DAKAWelcome       0x1072
+#define _Icon_PreAuthWord       0x1074
+#define _Icon_ParkingInfo		0x1076
+#define _Icon_ParkingLeave		0x1078
+#define _Icon_CompleteBtn		0x107A
+#define _Icon_ParkingCntDw_BG	0x107C
+#define _Icon_ParkingCntDw_Tens	0x107E
+#define _Icon_ParkingCntDw_Digits	0x1080
+#define _Icon_ScanCntDw_BG		0x1082
+#define _Icon_ParkingCntDw_Hun  0x1084
+
+#define _String_Date			0x3000
+#define _String_Tempture		0x3010
+#define _QRCode_AddLine			0x3020
+#define _String_ChargeRate		0x3030
+#define _String_ChargeTime		0x3040
+#define _String_ChargePower		0x3050
+#define _String_Battery			0x3060
+#define _Strting_Energy			0x3070
+#define _String_Money			0x3080
+#define _String_ParkRate		0x3090
+#define _String_Carbon			0x30A0
+#define _QRCode_Service			0x30B0
+#define _String_ParkingStartTime 0x30C0
+#define _String_ParkingDuration	0x30D0
+#define _String_ParkingFee		0x30E0
+#define _String_ParkingLeaveTime	0x30F0
+#define _String_SaleLeaveTime	0x3100
+
+#define _Touch_IDLE				0x1500
+#define _Touch_Select_Left		0x1502
+#define _Touch_Select_Right		0x1504
+#define _Touch_Show_Left		0x1506
+#define _Touch_Show_Right		0x1508
+#define _Touch_Return			0x150A
+#define _Touch_DonateBill		0x150C
+#define _Touch_DonateYes		0x150E
+#define _Touch_DonateNo			0x1510
+#define _Touch_StopCharge		0x1512
+#define _Touch_Stop_Confirm		0x1514
+#define _Touch_Stop_Cancel		0x1516
+#define _Touch_Pay_CreditCard	0x1518
+#define _Touch_Pay_LinePay		0x151A
+#define _Touch_Parking_Complete	0x151C
+
+enum _TCC_ICON_LIST_ {
+	_ICON_Empty 			= 0,
+	_TCC_Week_Monday,
+	_TCC_Week_Tuesday,
+	_TCC_Week_Wensday,
+	_TCC_Week_Thrusday,
+	_TCC_Week_Friday,
+	_TCC_Week_Saturday,
+	_TCC_Week_Sunday,
+	_TCC_TouchStart,
+	_TCC_Sun,
+	_TCC_Cloudy,
+	_TCC_Rain,
+	_TCC_Snow,
+	_TCC_Thunder,
+	_TCC_Fog,
+	_TCC_Taipei_ZhongShan,
+	_TCC_Scan_CntDw_BG,
+	_TCC_Welcom_Coffee,
+	_TCC_SelectLeft_CCS1,
+	_TCC_SelectLeft_CCS2,
+	_TCC_SelectLeft_CHAdeMo,
+	_TCC_SelectRight_CCS1,
+	_TCC_SelectRight_CCS2,
+	_TCC_SelectRight_CHAdeMo,
+	_TCC_Return,
+	_TCC_DonateBill,
+	_TCC_GetBill,
+	_TCC_ShowLeft_CCS1_Off,
+	_TCC_ShowLeft_CCS2_Off,
+	_TCC_ShowLeft_CHAdeMo_Off,
+	_TCC_ShowLeft_CCS1_On,
+	_TCC_ShowLeft_CCS2_On,
+	_TCC_ShowLeft_CHAdeMo_On,
+	_TCC_ShowRight_CCS1_Off,
+	_TCC_ShowRight_CCS2_Off,
+	_TCC_ShowRight_CHAdeMo_Off,
+	_TCC_ShowRight_CCS1_On,
+	_TCC_ShowRight_CCS2_On,
+	_TCC_ShowRight_CHAdeMo_On,
+	_TCC_ScanQR_Pass,
+	_TCC_SelectPayMode,
+	_TCC_CreditCard_Wifi,
+	_TCC_CreditCard_Frame,
+	_TCC_PreAuthWord,
+	_TCC_LinePay,
+	_TCC_CardSensing_Frame,
+	_TCC_PreAuth,
+	_TCC_Dot_0,
+	_TCC_PaySuccess 		= 62,
+	_TCC_Plugin,
+	_TCC_ChargingFrame,
+	_TCC_StopCharging,
+	_TCC_String_KW,
+	_TCC_Charging_Circle0,
+	_TCC_Charging_Bar0     	= 104,
+	_TCC_NHOA 				= 204,
+	_TCC_WordYes			= 206,
+	_TCC_WordNo,
+	_TCC_Paying,
+	_TCC_CompleteFrame,
+	_TCC_CompleteCircle0,
+	_TCC_EnjoyLife   		= 247,
+	_TCC_BlackBar,
+	_TCC_ExitAd,
+	_TCC_PayFail,
+	_TCC_Restart,
+	_TCC_PlugOutFrame,
+	_TCC_ErrorFrame,
+	_TCC_Warming,
+	_TCC_FAILCircle0,
+	_TCC_ShowLeftGunCharging_CCS1 = 292,
+	_TCC_ShowLeftGunCharging_CCS2,
+	_TCC_ShowLeftGunCharging_CHAdeMo,
+	_TCC_ShowRightGunCharging_CCS1,
+	_TCC_ShowRightGunCharging_CCS2,
+	_TCC_ShowRightGunCharging_CHAdeMo,
+	_TCC_ReturnFrontPage,
+	_TCC_CancelNum_0,
+	_TCC_TradeCancelString = 309,
+	_TCC_TradeCancelFrame,
+	_TCC_SecondSense,
+	_TCC_CntDownNumber0,
+	_TCC_Uploading = 323,
+	_TCC_IDLE_LEFT_CCS1,
+	_TCC_IDLE_LEFT_CCS2,
+	_TCC_IDLE_LEFT_CHAdeMo,
+	_TCC_IDLE_RIGHT_CCS1,
+	_TCC_IDLE_RIGHT_CCS2,
+	_TCC_IDLE_RIGHT_CHAdeMo,
+	_TCC_ShowLeftGunReservation_CCS1,
+	_TCC_ShowLeftGunReservation_CCS2,
+	_TCC_ShowLeftGunReservation_CHAdeMo,
+	_TCC_ShowRightGunReservation_CCS1,
+	_TCC_ShowRightGunReservation_CCS2,
+	_TCC_ShowRightGunReservation_CHAdeMo,
+	_TCC_LeftParkingIdle,
+	_TCC_RightParkingIdle,
+	_TCC_LeftParkingSel,
+	_TCC_RightParkingSel,
+	_TCC_ParkingInfo,
+	_TCC_ParkingLine,
+	_TCC_ParkingDonate,
+	_TCC_ParkingFee,
+	_TCC_ParkingLeave,
+	_TCC_NoParkingComplete,
+	_TCC_ParkingComplete,
+	_TCC_LinePaying,
+	_TCC_ParkingCntDown_BG,
+	_TCC_ParkingCD_0,
+	_TCC_ParkingCD_1,
+	_TCC_ParkingCD_2,
+	_TCC_ParkingCD_3,
+	_TCC_ParkingCD_4,
+	_TCC_ParkingCD_5,
+	_TCC_ParkingCD_6,
+	_TCC_ParkingCD_7,
+	_TCC_ParkingCD_8,
+	_TCC_ParkingCD_9,
+	_TCC_WaitParkInfo,
+	_TCC_ParkingCntDown_BG3,
+	_TCC_ICON_SelectChargeMode,
+	_TCC_ICON_SelectPayMode,
+};
+
+
+/* Show Version */
+
+#define _Version_Cabient_Name_Text          0x0500
+#define _Version_Cabient_BootLoader_Text    0x0510
+#define _Version_Cabient_Kernel_Text        0x0520
+#define _Version_Cabient_CSU_Text           0x0530
+#define _Version_Cabient_Priamry_Text       0x0540
+#define _Version_Cabient_Relay0_Text        0x0550
+#define _Version_Cabient_Relay1_Text        0x0560
+#define _Version_Cabient_Fan_Text           0x0570
+#define _Version_Cabient_IPAddr_Text        0x0580
+#define _Version_Cabient_PSU1_Text          0x0590
+#define _Version_Cabient_PSU2_Text          0x05A0
+#define _Version_Cabient_PSU3_Text          0x05B0
+#define _Version_Cabient_PSU4_Text          0x05C0
+#define _Version_Cabient_PSU5_Text          0x05D0
+#define _Version_Cabient_PSU6_Text          0x05E0
+#define _Version_Cabient_PSU7_Text          0x05F0
+#define _Version_Cabient_PSU8_Text          0x0600
+#define _Version_Cabient_PSU9_Text          0x0610
+#define _Version_Cabient_PSU10_Text         0x0620
+#define _Version_Cabient_PSU11_Text         0x0630
+#define _Version_Cabient_PSU12_Text         0x0640
+
+#define _Version_Cabient_Primary_Text       0x0920
+#define _Version_Cabient_Secondary_Text     0x0930
+
+#define _Version_Cabient_Model_value        0x0650
+#define _Version_Cabient_BootLoader_value   0x0660
+#define _Version_Cabient_Kernel_value       0x0670
+#define _Version_Cabient_CSU_value          0x0680
+#define _Version_Cabient_Priamry_value      0x0690
+#define _Version_Cabient_Relay0_value       0x06A0
+#define _Version_Cabient_Relay1_value       0x06B0
+#define _Version_Cabient_Fan_value          0x06C0
+#define _Version_Cabient_IPAddr_value       0x06D0
+#define _Version_Cabient_PSU_Prim1_value    0x06E0
+#define _Version_Cabient_PSU_Prim2_value    0x06F0
+#define _Version_Cabient_PSU_Prim3_value    0x0700
+#define _Version_Cabient_PSU_Prim4_value    0x0710
+#define _Version_Cabient_PSU_Prim5_value    0x0720
+#define _Version_Cabient_PSU_Prim6_value    0x0730
+#define _Version_Cabient_PSU_Sec1_value     0x0740
+#define _Version_Cabient_PSU_Sec2_value     0x0750
+#define _Version_Cabient_PSU_Sec3_value     0x0760
+#define _Version_Cabient_PSU_Sec4_value     0x0770
+#define _Version_Cabient_PSU_Sec5_value     0x0780
+#define _Version_Cabient_PSU_Sec6_value     0x0790
+
+#define _Version_Cabient_PSU_Prim7_value    0x09E0
+#define _Version_Cabient_PSU_Prim8_value    0x09F0
+#define _Version_Cabient_PSU_Prim9_value    0x1000
+#define _Version_Cabient_PSU_Prim10_value   0x1010
+#define _Version_Cabient_PSU_Prim11_value   0x1020
+#define _Version_Cabient_PSU_Prim12_value   0x1030
+#define _Version_Cabient_PSU_Sec7_value     0x1040
+#define _Version_Cabient_PSU_Sec8_value     0x1050
+#define _Version_Cabient_PSU_Sec9_value     0x1060
+#define _Version_Cabient_PSU_Sec10_value    0x1070
+#define _Version_Cabient_PSU_Sec11_value    0x1080
+#define _Version_Cabient_PSU_Sec12_value    0x1090
+
+#define _Version_Dispenser_Name_Text        0x07A0
+#define _Version_Dispenser_BootLoader_Text  0x07B0
+#define _Version_Dispenser_Kernel_Text      0x07C0
+#define _Version_Dispenser_CSU_Text         0x07D0
+#define _Version_Dispenser_Relay_Text       0x07E0
+#define _Version_Dispenser_Fan_Text         0x07F0
+#define _Version_Dispenser_Priamry_Text     0x0800
+#define _Version_Dispenser_LCM_Text         0x0810
+#define _Version_Dispenser_LED_Text         0x0820
+#define _Version_Dispenser_Connector0_Text  0x0830
+#define _Version_Dispenser_Connector1_Text  0x0840
+#define _Version_Dispenser_IPAddr_Text      0x0850
+
+#define _Version_Dispenser_Model_value      0x0860
+#define _Version_Dispenser_BootLoader_value 0x0870
+#define _Version_Dispenser_Kernel_value     0x0880
+#define _Version_Dispenser_CSU_value        0x0890
+#define _Version_Dispenser_Relay_value      0x08A0
+#define _Version_Dispenser_Fan_value        0x08B0
+#define _Version_Dispenser_Priamry_value    0x08C0
+#define _Version_Dispenser_LCM_value        0x08D0
+#define _Version_Dispenser_LED_value        0x08E0
+#define _Version_Dispenser_Connector0_value 0x08F0
+#define _Version_Dispenser_Connector1_value 0x0900
+#define _Version_Dispenser_IPAddr_value     0x0910
+
+#endif //MODULE_LCM_CTRL_H_

+ 315 - 315
EVSE/Projects/DD360Tcci/Apps/ModuleLcmCtrl/cbmp.c

@@ -1,315 +1,315 @@
-#include <stdlib.h>
-#include <stdio.h>
-#include "cbmp.h"
-
-// Constants
-
-#define BITS_PER_BYTE 8
-
-#define BLUE 0
-#define GREEN 1
-#define RED 2
-#define ALPHA 3
-
-#define PIXEL_ARRAY_START_BYTES 4
-#define PIXEL_ARRAY_START_OFFSET 10
-
-#define WIDTH_BYTES 4
-#define WIDTH_OFFSET 18
-
-#define HEIGHT_BYTES 4
-#define HEIGHT_OFFSET 22
-
-#define DEPTH_BYTES 2
-#define DEPTH_OFFSET 28
-
-// Private function declarations
-
-void _throw_error(char* message);
-unsigned int _get_int_from_buffer(unsigned int bytes, 
-                                  unsigned int offset, 
-                                  unsigned char* buffer);
-unsigned int _get_file_byte_number(FILE* fp);
-unsigned char* _get_file_byte_contents(FILE* fp, unsigned int file_byte_number);
-int _validate_file_type(unsigned char* file_byte_contents);
-int _validate_depth(unsigned int depth);
-unsigned int _get_pixel_array_start(unsigned char* file_byte_contents);
-int _get_width(unsigned char* file_byte_contents);
-int _get_height(unsigned char* file_byte_contents);
-unsigned int _get_depth(unsigned char* file_byte_contents);
-void _update_file_byte_contents(BMP* bmp, int index, int offset, int channel);
-void _populate_pixel_array(BMP* bmp);
-void _map(BMP* bmp, void (*f)(BMP* bmp, int, int, int));
-void _get_pixel(BMP* bmp, int index, int offset, int channel);
-
-// Public function implementations
-
-BMP* bopen(char* file_path)
-{
-    FILE* fp = fopen(file_path, "rb");
-  
-    if (fp == NULL)
-    {
-        perror("Error opening file");
-        exit(EXIT_FAILURE);
-    }
-
-    BMP* bmp = (BMP*) malloc(sizeof(BMP));
-    bmp->file_byte_number = _get_file_byte_number(fp);
-    bmp->file_byte_contents = _get_file_byte_contents(fp, bmp->file_byte_number);
-    fclose(fp);
-
-    if(!_validate_file_type(bmp->file_byte_contents))
-    {
-        _throw_error("Invalid file type");
-    }
-
-    bmp->pixel_array_start = _get_pixel_array_start(bmp->file_byte_contents);
-
-    bmp->width = _get_width(bmp->file_byte_contents);
-    bmp->height = _get_height(bmp->file_byte_contents);
-    bmp->depth = _get_depth(bmp->file_byte_contents);
-
-    if(!_validate_depth(bmp->depth))
-    {
-        _throw_error("Invalid file depth");
-    }
-
-    _populate_pixel_array(bmp);
-
-    return bmp;
-}
-
-BMP* b_deep_copy(BMP* to_copy)
-{
-    BMP* copy = (BMP*) malloc(sizeof(BMP));
-    copy->file_byte_number = to_copy->file_byte_number;
-    copy->pixel_array_start = to_copy->pixel_array_start;
-    copy->width = to_copy->width;
-    copy->height = to_copy->height;
-    copy->depth = to_copy->depth;
-
-    copy->file_byte_contents = (unsigned char*) malloc(copy->file_byte_number * sizeof(unsigned char));
-
-    unsigned int i;
-    for (i = 0; i < copy->file_byte_number; i++)
-    {
-        copy->file_byte_contents[i] = to_copy->file_byte_contents[i];
-    }
-
-    copy->pixels = (pixel*) malloc(copy->width * copy->height * sizeof(pixel));
-
-    unsigned int x, y;
-    int index;
-    for (y = 0; y < copy->height; y++)
-    {
-        for (x = 0; x < copy->width; x++)
-        {
-            index = y * copy->width + x;
-            copy->pixels[index].red = to_copy->pixels[index].red;
-            copy->pixels[index].green = to_copy->pixels[index].green;
-            copy->pixels[index].blue = to_copy->pixels[index].blue;
-            copy->pixels[index].alpha = to_copy->pixels[index].alpha;
-        }
-    }
-
-    return copy;
-}
-
-int get_width(BMP* bmp)
-{
-    return bmp->width;
-}
-
-int get_height(BMP* bmp)
-{
-    return bmp->height;
-}
-
-unsigned int get_depth(BMP* bmp)
-{
-    return bmp->depth;
-}
-
-void get_pixel_rgb(BMP* bmp, int x, int y, unsigned char* r, unsigned char* g, unsigned char* b)
-{
-    int index = y * bmp->width + x;
-    *r = bmp->pixels[index].red;
-    *g = bmp->pixels[index].green;
-    *b = bmp->pixels[index].blue;
-}
-
-void set_pixel_rgb(BMP* bmp, int x, int y, unsigned char r, unsigned char g, unsigned char b)
-{
-    int index = y * bmp->width + x;
-    bmp->pixels[index].red = r;
-    bmp->pixels[index].green = g;
-    bmp->pixels[index].blue = b;
-}
-
-void bwrite(BMP* bmp, char* file_name)
-{
-    _map(bmp, _update_file_byte_contents);
-
-    FILE* fp = fopen(file_name, "wb");
-    fwrite(bmp->file_byte_contents, sizeof(char), bmp->file_byte_number, fp);
-    fclose(fp);
-}
-
-void bclose(BMP* bmp)
-{
-    free(bmp->pixels);
-    bmp->pixels = NULL;
-    free(bmp->file_byte_contents);
-    bmp->file_byte_contents = NULL;
-    free(bmp);
-    bmp = NULL;
-}
-
-
-// Private function implementations
-
-void _throw_error(char* message)
-{
-    fprintf(stderr, "%s\n", message);
-    exit(1);
-}
-
-unsigned int _get_int_from_buffer(unsigned int bytes, 
-                                  unsigned int offset, 
-                                  unsigned char* buffer)
-{
-    unsigned char* _buffer = (unsigned char*) malloc(bytes * sizeof(unsigned char));
-
-    unsigned int i;
-    for (i = 0; i < bytes; i++)
-    {
-        _buffer[i] = buffer[i + offset];
-    }
-
-    unsigned int value = *(unsigned int*) _buffer;
-    free(_buffer);
-    return value;
-}
-
-unsigned int _get_file_byte_number(FILE* fp)
-{
-    unsigned int byte_number;
-    fseek(fp, 0, SEEK_END);
-    byte_number = ftell(fp);
-    rewind(fp);
-    return byte_number;
-}
-
-unsigned char* _get_file_byte_contents(FILE* fp, unsigned int file_byte_number)
-{
-    unsigned char* buffer = (unsigned char*) malloc(file_byte_number * sizeof(char));
-    unsigned int result = fread(buffer, 1, file_byte_number, fp);
-
-    if (result != file_byte_number)
-    {
-        _throw_error("There was a problem reading the file");
-    }
-
-
-    return buffer;
-}
-
-int _validate_file_type(unsigned char* file_byte_contents)
-{
-    return file_byte_contents[0] == 'B' && file_byte_contents[1] == 'M';
-}
-
-int _validate_depth(unsigned int depth)
-{
-    return depth == 24 || depth == 32;
-}
-
-unsigned int _get_pixel_array_start(unsigned char* file_byte_contents)
-{
-    return _get_int_from_buffer(PIXEL_ARRAY_START_BYTES, PIXEL_ARRAY_START_OFFSET, file_byte_contents);
-}
-
-int _get_width(unsigned char* file_byte_contents)
-{
-    return (int) _get_int_from_buffer(WIDTH_BYTES, WIDTH_OFFSET, file_byte_contents);
-}
-
-int _get_height(unsigned char* file_byte_contents)
-{
-    return (int) _get_int_from_buffer(HEIGHT_BYTES, HEIGHT_OFFSET, file_byte_contents);
-}
-
-unsigned int _get_depth(unsigned char* file_byte_contents)
-{
-    return _get_int_from_buffer(DEPTH_BYTES, DEPTH_OFFSET, file_byte_contents);
-}
-
-void _update_file_byte_contents(BMP* bmp, int index, int offset, int channel)
-{
-    char value;
-    switch(channel)
-    {
-        case BLUE:
-            value = bmp->pixels[index].blue;
-            break;
-        case GREEN:
-            value = bmp->pixels[index].green;
-            break;
-        case RED:
-            value = bmp->pixels[index].red;
-            break;
-        case ALPHA:
-            value = bmp->pixels[index].alpha;
-            break;
-    }
-    bmp->file_byte_contents[offset + channel] = value;
-}
-
-void _populate_pixel_array(BMP* bmp)
-{
-    bmp->pixels = (pixel*) malloc(bmp->width * bmp->height * sizeof(pixel));
-    _map(bmp, _get_pixel);
-}
-
-void _map(BMP* bmp, void (*f)(BMP*, int, int, int))
-{
-    int channels = bmp->depth / (sizeof(unsigned char) * BITS_PER_BYTE);
-    int row_size = ((int) (bmp->depth * bmp->width + 31) / 32) * 4;
-    int padding = row_size - bmp->width * channels;
-
-    int c;
-    unsigned int x, y, index, offset;
-    for (y = 0; y < bmp->height; y++)
-    {
-        for (x = 0; x < bmp->width; x++)
-        {
-            index = y * bmp->width + x;
-            offset = bmp->pixel_array_start + index * channels + y * padding;
-            for (c = 0; c < channels; c++)
-            {
-                (*f)(bmp, index, offset, c);
-            }
-        }
-    }
-}
-
-void _get_pixel(BMP* bmp, int index, int offset, int channel)
-{
-    unsigned char value = _get_int_from_buffer(sizeof(unsigned char), offset + channel, bmp->file_byte_contents);
-    switch(channel)
-    {
-        case BLUE:
-            bmp->pixels[index].blue = value;
-            break;
-        case GREEN:
-            bmp->pixels[index].green = value;
-            break;
-        case RED:
-            bmp->pixels[index].red = value;
-            break;
-        case ALPHA:
-            bmp->pixels[index].alpha = value;
-            break;
-    }
-}
+#include <stdlib.h>
+#include <stdio.h>
+#include "cbmp.h"
+
+// Constants
+
+#define BITS_PER_BYTE 8
+
+#define BLUE 0
+#define GREEN 1
+#define RED 2
+#define ALPHA 3
+
+#define PIXEL_ARRAY_START_BYTES 4
+#define PIXEL_ARRAY_START_OFFSET 10
+
+#define WIDTH_BYTES 4
+#define WIDTH_OFFSET 18
+
+#define HEIGHT_BYTES 4
+#define HEIGHT_OFFSET 22
+
+#define DEPTH_BYTES 2
+#define DEPTH_OFFSET 28
+
+// Private function declarations
+
+void _throw_error(char* message);
+unsigned int _get_int_from_buffer(unsigned int bytes, 
+                                  unsigned int offset, 
+                                  unsigned char* buffer);
+unsigned int _get_file_byte_number(FILE* fp);
+unsigned char* _get_file_byte_contents(FILE* fp, unsigned int file_byte_number);
+int _validate_file_type(unsigned char* file_byte_contents);
+int _validate_depth(unsigned int depth);
+unsigned int _get_pixel_array_start(unsigned char* file_byte_contents);
+int _get_width(unsigned char* file_byte_contents);
+int _get_height(unsigned char* file_byte_contents);
+unsigned int _get_depth(unsigned char* file_byte_contents);
+void _update_file_byte_contents(BMP* bmp, int index, int offset, int channel);
+void _populate_pixel_array(BMP* bmp);
+void _map(BMP* bmp, void (*f)(BMP* bmp, int, int, int));
+void _get_pixel(BMP* bmp, int index, int offset, int channel);
+
+// Public function implementations
+
+BMP* bopen(char* file_path)
+{
+    FILE* fp = fopen(file_path, "rb");
+  
+    if (fp == NULL)
+    {
+        perror("Error opening file");
+        exit(EXIT_FAILURE);
+    }
+
+    BMP* bmp = (BMP*) malloc(sizeof(BMP));
+    bmp->file_byte_number = _get_file_byte_number(fp);
+    bmp->file_byte_contents = _get_file_byte_contents(fp, bmp->file_byte_number);
+    fclose(fp);
+
+    if(!_validate_file_type(bmp->file_byte_contents))
+    {
+        _throw_error("Invalid file type");
+    }
+
+    bmp->pixel_array_start = _get_pixel_array_start(bmp->file_byte_contents);
+
+    bmp->width = _get_width(bmp->file_byte_contents);
+    bmp->height = _get_height(bmp->file_byte_contents);
+    bmp->depth = _get_depth(bmp->file_byte_contents);
+
+    if(!_validate_depth(bmp->depth))
+    {
+        _throw_error("Invalid file depth");
+    }
+
+    _populate_pixel_array(bmp);
+
+    return bmp;
+}
+
+BMP* b_deep_copy(BMP* to_copy)
+{
+    BMP* copy = (BMP*) malloc(sizeof(BMP));
+    copy->file_byte_number = to_copy->file_byte_number;
+    copy->pixel_array_start = to_copy->pixel_array_start;
+    copy->width = to_copy->width;
+    copy->height = to_copy->height;
+    copy->depth = to_copy->depth;
+
+    copy->file_byte_contents = (unsigned char*) malloc(copy->file_byte_number * sizeof(unsigned char));
+
+    unsigned int i;
+    for (i = 0; i < copy->file_byte_number; i++)
+    {
+        copy->file_byte_contents[i] = to_copy->file_byte_contents[i];
+    }
+
+    copy->pixels = (pixel*) malloc(copy->width * copy->height * sizeof(pixel));
+
+    unsigned int x, y;
+    int index;
+    for (y = 0; y < copy->height; y++)
+    {
+        for (x = 0; x < copy->width; x++)
+        {
+            index = y * copy->width + x;
+            copy->pixels[index].red = to_copy->pixels[index].red;
+            copy->pixels[index].green = to_copy->pixels[index].green;
+            copy->pixels[index].blue = to_copy->pixels[index].blue;
+            copy->pixels[index].alpha = to_copy->pixels[index].alpha;
+        }
+    }
+
+    return copy;
+}
+
+int get_width(BMP* bmp)
+{
+    return bmp->width;
+}
+
+int get_height(BMP* bmp)
+{
+    return bmp->height;
+}
+
+unsigned int get_depth(BMP* bmp)
+{
+    return bmp->depth;
+}
+
+void get_pixel_rgb(BMP* bmp, int x, int y, unsigned char* r, unsigned char* g, unsigned char* b)
+{
+    int index = y * bmp->width + x;
+    *r = bmp->pixels[index].red;
+    *g = bmp->pixels[index].green;
+    *b = bmp->pixels[index].blue;
+}
+
+void set_pixel_rgb(BMP* bmp, int x, int y, unsigned char r, unsigned char g, unsigned char b)
+{
+    int index = y * bmp->width + x;
+    bmp->pixels[index].red = r;
+    bmp->pixels[index].green = g;
+    bmp->pixels[index].blue = b;
+}
+
+void bwrite(BMP* bmp, char* file_name)
+{
+    _map(bmp, _update_file_byte_contents);
+
+    FILE* fp = fopen(file_name, "wb");
+    fwrite(bmp->file_byte_contents, sizeof(char), bmp->file_byte_number, fp);
+    fclose(fp);
+}
+
+void bclose(BMP* bmp)
+{
+    free(bmp->pixels);
+    bmp->pixels = NULL;
+    free(bmp->file_byte_contents);
+    bmp->file_byte_contents = NULL;
+    free(bmp);
+    bmp = NULL;
+}
+
+
+// Private function implementations
+
+void _throw_error(char* message)
+{
+    fprintf(stderr, "%s\n", message);
+    exit(1);
+}
+
+unsigned int _get_int_from_buffer(unsigned int bytes, 
+                                  unsigned int offset, 
+                                  unsigned char* buffer)
+{
+    unsigned char* _buffer = (unsigned char*) malloc(bytes * sizeof(unsigned char));
+
+    unsigned int i;
+    for (i = 0; i < bytes; i++)
+    {
+        _buffer[i] = buffer[i + offset];
+    }
+
+    unsigned int value = *(unsigned int*) _buffer;
+    free(_buffer);
+    return value;
+}
+
+unsigned int _get_file_byte_number(FILE* fp)
+{
+    unsigned int byte_number;
+    fseek(fp, 0, SEEK_END);
+    byte_number = ftell(fp);
+    rewind(fp);
+    return byte_number;
+}
+
+unsigned char* _get_file_byte_contents(FILE* fp, unsigned int file_byte_number)
+{
+    unsigned char* buffer = (unsigned char*) malloc(file_byte_number * sizeof(char));
+    unsigned int result = fread(buffer, 1, file_byte_number, fp);
+
+    if (result != file_byte_number)
+    {
+        _throw_error("There was a problem reading the file");
+    }
+
+
+    return buffer;
+}
+
+int _validate_file_type(unsigned char* file_byte_contents)
+{
+    return file_byte_contents[0] == 'B' && file_byte_contents[1] == 'M';
+}
+
+int _validate_depth(unsigned int depth)
+{
+    return depth == 24 || depth == 32;
+}
+
+unsigned int _get_pixel_array_start(unsigned char* file_byte_contents)
+{
+    return _get_int_from_buffer(PIXEL_ARRAY_START_BYTES, PIXEL_ARRAY_START_OFFSET, file_byte_contents);
+}
+
+int _get_width(unsigned char* file_byte_contents)
+{
+    return (int) _get_int_from_buffer(WIDTH_BYTES, WIDTH_OFFSET, file_byte_contents);
+}
+
+int _get_height(unsigned char* file_byte_contents)
+{
+    return (int) _get_int_from_buffer(HEIGHT_BYTES, HEIGHT_OFFSET, file_byte_contents);
+}
+
+unsigned int _get_depth(unsigned char* file_byte_contents)
+{
+    return _get_int_from_buffer(DEPTH_BYTES, DEPTH_OFFSET, file_byte_contents);
+}
+
+void _update_file_byte_contents(BMP* bmp, int index, int offset, int channel)
+{
+    char value;
+    switch(channel)
+    {
+        case BLUE:
+            value = bmp->pixels[index].blue;
+            break;
+        case GREEN:
+            value = bmp->pixels[index].green;
+            break;
+        case RED:
+            value = bmp->pixels[index].red;
+            break;
+        case ALPHA:
+            value = bmp->pixels[index].alpha;
+            break;
+    }
+    bmp->file_byte_contents[offset + channel] = value;
+}
+
+void _populate_pixel_array(BMP* bmp)
+{
+    bmp->pixels = (pixel*) malloc(bmp->width * bmp->height * sizeof(pixel));
+    _map(bmp, _get_pixel);
+}
+
+void _map(BMP* bmp, void (*f)(BMP*, int, int, int))
+{
+    int channels = bmp->depth / (sizeof(unsigned char) * BITS_PER_BYTE);
+    int row_size = ((int) (bmp->depth * bmp->width + 31) / 32) * 4;
+    int padding = row_size - bmp->width * channels;
+
+    int c;
+    unsigned int x, y, index, offset;
+    for (y = 0; y < bmp->height; y++)
+    {
+        for (x = 0; x < bmp->width; x++)
+        {
+            index = y * bmp->width + x;
+            offset = bmp->pixel_array_start + index * channels + y * padding;
+            for (c = 0; c < channels; c++)
+            {
+                (*f)(bmp, index, offset, c);
+            }
+        }
+    }
+}
+
+void _get_pixel(BMP* bmp, int index, int offset, int channel)
+{
+    unsigned char value = _get_int_from_buffer(sizeof(unsigned char), offset + channel, bmp->file_byte_contents);
+    switch(channel)
+    {
+        case BLUE:
+            bmp->pixels[index].blue = value;
+            break;
+        case GREEN:
+            bmp->pixels[index].green = value;
+            break;
+        case RED:
+            bmp->pixels[index].red = value;
+            break;
+        case ALPHA:
+            bmp->pixels[index].alpha = value;
+            break;
+    }
+}

+ 54 - 54
EVSE/Projects/DD360Tcci/Apps/ModuleLcmCtrl/cbmp.h

@@ -1,54 +1,54 @@
-#ifndef CBMP_CBMP_H
-#define CBMP_CBMP_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-// Pixel structure
-// Not meant to be edited directly
-// Please use the API
-
-typedef struct pixel_data
-{
-    unsigned char red;
-    unsigned char green;
-    unsigned char blue;
-    unsigned char alpha;
-} pixel;
-
-// BMP structure
-// Not meant to be edited directly
-// Please use the API
-
-typedef struct BMP_data
-{
-    unsigned int file_byte_number;
-    unsigned char* file_byte_contents;
-
-    unsigned int pixel_array_start;
-
-    unsigned int width;
-    unsigned int height;
-    unsigned int depth;
-
-    pixel* pixels;
-} BMP;
-
-// Public function declarations
-
-BMP* bopen(char* file_path);
-BMP* b_deep_copy(BMP* to_copy);
-int get_width(BMP* bmp);
-int get_height(BMP* bmp);
-unsigned int get_depth(BMP* bmp);
-void get_pixel_rgb(BMP* bmp, int x, int y, unsigned char* r, unsigned char* g, unsigned char* b);
-void set_pixel_rgb(BMP* bmp, int x, int y, unsigned char r, unsigned char g, unsigned char b);
-void bwrite(BMP* bmp, char* file_name);
-void bclose(BMP* bmp);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // CBMP_CBMP_H
+#ifndef CBMP_CBMP_H
+#define CBMP_CBMP_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+// Pixel structure
+// Not meant to be edited directly
+// Please use the API
+
+typedef struct pixel_data
+{
+    unsigned char red;
+    unsigned char green;
+    unsigned char blue;
+    unsigned char alpha;
+} pixel;
+
+// BMP structure
+// Not meant to be edited directly
+// Please use the API
+
+typedef struct BMP_data
+{
+    unsigned int file_byte_number;
+    unsigned char* file_byte_contents;
+
+    unsigned int pixel_array_start;
+
+    unsigned int width;
+    unsigned int height;
+    unsigned int depth;
+
+    pixel* pixels;
+} BMP;
+
+// Public function declarations
+
+BMP* bopen(char* file_path);
+BMP* b_deep_copy(BMP* to_copy);
+int get_width(BMP* bmp);
+int get_height(BMP* bmp);
+unsigned int get_depth(BMP* bmp);
+void get_pixel_rgb(BMP* bmp, int x, int y, unsigned char* r, unsigned char* g, unsigned char* b);
+void set_pixel_rgb(BMP* bmp, int x, int y, unsigned char r, unsigned char g, unsigned char b);
+void bwrite(BMP* bmp, char* file_name);
+void bclose(BMP* bmp);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // CBMP_CBMP_H

+ 494 - 494
EVSE/Projects/DD360Tcci/Apps/ModulePrimary/Module_PrimaryComm.c

@@ -1,494 +1,494 @@
-#include <sys/time.h>
-#include <sys/timeb.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <sys/types.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 <arpa/inet.h>
-#include <netinet/in.h>
-#include <stdbool.h>
-
-#include <unistd.h>
-#include <stdarg.h>
-#include <stdio.h>      /*標準輸入輸出定義*/
-#include <stdlib.h>     /*標準函數庫定義*/
-#include <unistd.h>     /*Unix 標準函數定義*/
-#include <fcntl.h>      /*檔控制定義*/
-#include <termios.h>    /*PPSIX 終端控制定義*/
-#include <errno.h>      /*錯誤號定義*/
-#include <errno.h>
-#include <string.h>
-#include <time.h>
-#include <ctype.h>
-#include <ifaddrs.h>
-#include <math.h>
-
-#include "../Log/log.h"
-#include "../Define/define.h"
-#include "../Config.h"
-#include "../ShareMemory/shmMem.h"
-#include "PrimaryComm.h"
-#include "Module_PrimaryComm.h"
-
-//------------------------------------------------------------------------------
-//struct SysConfigAndInfo *ShmSysConfigAndInfo;
-//struct StatusCodeData *ShmStatusCodeData;
-static struct SysConfigData *pSysConfig = NULL;
-static struct SysInfoData *pSysInfo = NULL;
-static struct AlarmCodeData *pAlarmCode = NULL;
-static struct FaultCodeData *pFaultCode = NULL;
-static struct PrimaryMcuData *ShmPrimaryMcuData;
-static DcCommonInfo *ShmDcCommonData = NULL;
-
-const char *priPortName = "/dev/ttyS1";
-uint8_t gun_count; //DS60-120 add
-
-uint8_t EmgBtn_count = 0;
-uint8_t Door_count = 0;
-uint8_t EmgBtn_flag = 0;
-uint8_t Door_flag = 0;
-
-
-//================================================
-// Function
-//================================================
-void GetFwAndHwVersion(int fd)
-{
-    Ver ver = {0};
-
-    if (Query_FW_Ver(fd, OP_ADDR_IO_EXTEND, &ver) == PASS) {
-        //log_info("Primary FW Rev = %s ", ver.Version_FW);
-        strcpy((char *)ShmPrimaryMcuData->version, ver.Version_FW);
-        strcpy((char *) pSysInfo->CsuPrimFwRev, ver.Version_FW);
-    }
-
-    //if (Query_HW_Ver(fd, OP_ADDR_IO_EXTEND, &ver) == PASS)
-    //    ;//log_info("Primary HW Rev  = %s ", ver.Version_HW);
-}
-
-void GetInputGpioStatus(int fd)
-{
-    uint8_t dispenserSwTmp = 0;
-    Gpio_in gpio_in = {0};
-    static uint8_t dispenserSw = 0;
-
-    //log_info("GetInputGpioStatus ");
-    if (Query_Gpio_Input(fd, OP_ADDR_IO_EXTEND, &gpio_in) != PASS) {
-        return;
-    }
-
-    ShmPrimaryMcuData->InputDet.bits.SpdDetec = gpio_in.SPD;
-    ShmPrimaryMcuData->InputDet.bits.Ac_Drop = ~gpio_in.AC_Drop; // Chiller Alarm ping
-
-    if (gpio_in.Emergency_Btn && (EmgBtn_flag != gpio_in.Emergency_Btn))
-    {
-            EmgBtn_count++;
-        if (EmgBtn_count > SensorTrigCount) {
-           EmgBtn_flag = 1;
-           EmgBtn_count = 0; // Avoid Overflow
-       }
-    } else if (EmgBtn_flag != gpio_in.Emergency_Btn ) {
-        EmgBtn_count++;
-        if (EmgBtn_count > SensorTrigCount) {
-            EmgBtn_flag = 0;
-            EmgBtn_count = 0;
-        }
-    }
-
-    ShmPrimaryMcuData->InputDet.bits.EmergencyButton = EmgBtn_flag;
-
-    dispenserSwTmp |= (ShmPrimaryMcuData->InputDet.bits.Key0);
-    dispenserSwTmp |= (ShmPrimaryMcuData->InputDet.bits.Key1 << 1);
-    dispenserSwTmp |= (ShmPrimaryMcuData->InputDet.bits.Key2 << 2);
-    dispenserSwTmp |= (ShmPrimaryMcuData->InputDet.bits.Key3 << 3);
-
-    if (dispenserSwTmp != dispenserSw) {
-        dispenserSw = dispenserSwTmp;
-        log_info("Dispenser switch number =  %d, bit = %d, %d, %d, %d",
-                 dispenserSw,
-                 ShmPrimaryMcuData->InputDet.bits.Key3,
-                 ShmPrimaryMcuData->InputDet.bits.Key2,
-                 ShmPrimaryMcuData->InputDet.bits.Key1,
-                 ShmPrimaryMcuData->InputDet.bits.Key0);
-    }
-
-    ShmPrimaryMcuData->InputDet.bits.Button1 = gpio_in.Button[0];
-    ShmPrimaryMcuData->InputDet.bits.Button2 = gpio_in.Button[1];
-
-
-    if ((strncmp((char *)&pSysConfig->ModelName[7], "V", 1) == 0) ||
-            (strncmp((char *)&pSysConfig->ModelName[9], "V", 1) == 0) ||
-            (strncmp((char *)&pSysConfig->ModelName[7], "F", 1) == 0) ||
-            (strncmp((char *)&pSysConfig->ModelName[9], "F", 1) == 0)
-       ) {
-        pAlarmCode->AlarmEvents.bits.CcsLiquidChillerWaterLevelWarning = ~gpio_in.AC_Connector;
-        pFaultCode->FaultEvents.bits.CcsLiquidChillerWaterLevelFault = ~gpio_in.AC_MainBreaker;
-    } else {
-        pAlarmCode->AlarmEvents.bits.CcsLiquidChillerWaterLevelWarning = gpio_in.AC_Connector;
-        pFaultCode->FaultEvents.bits.CcsLiquidChillerWaterLevelFault = gpio_in.AC_MainBreaker;
-    }
-
-    if (Door_flag == gpio_in.Door_Open) {
-        Door_count++;
-        if (Door_count == 3 ) {
-            Door_count = 0;
-            Door_flag = gpio_in.Door_Open;
-        }
-    } else { 
-        Door_flag = gpio_in.Door_Open;
-        Door_count = 0;
-    }
-    /*
-    if (gpio_in.Door_Open == 0 && (Door_flag == gpio_in.Door_Open))
-    {
-        Door_count++;
-        if (Door_count > SensorTrigCount) {
-            Door_flag = 1;
-            Door_count = 0; // Avoid Overflow
-       }
-    } else if (gpio_in.Door_Open && Door_flag) {
-        Door_count++;
-        if (Door_count > SensorTrigCount) {
-            Door_flag = 0;
-            Door_count = 0;
-        }
-    }
-    */
-
-
-    ShmPrimaryMcuData->InputDet.bits.DoorOpen = ~Door_flag;
-
-
-/*
-    log_info("Emergency Button Count = %d , Emergency flag = %d",
-            EmgBtn_count,EmgBtn_flag);
-    log_info("Door Sensor Count = %d , Door Sensor flag = %d",
-            Door_count,Door_flag);
-*/
-
-    ShmPrimaryMcuData->InputDet.bits.Key0 = ~gpio_in.Key[0] & 0x01;
-    ShmPrimaryMcuData->InputDet.bits.Key1 = ~gpio_in.Key[1] & 0x01;
-    ShmPrimaryMcuData->InputDet.bits.Key2 = ~gpio_in.Key[2] & 0x01;
-    ShmPrimaryMcuData->InputDet.bits.Key3 = ~gpio_in.Key[3] & 0x01;
-
-    return;
-
-
-}
-
-static void checkChillerStatus(Gpio_out *gpio)
-{
-    uint8_t gunIndex = 0;
-    uint8_t chillerCount = 0;
-    struct ChargingInfoData *pDcChargingInfo = NULL;
-    static ChillerInfo fChillerInfo[2] = {0}, *pChillerInfo = NULL;
-    static ChillerInfo _chiller;
-    struct FanModuleData* ShmFanModuleData = (struct FanModuleData*)GetShmFanModuleData();
-    DcCommonInfo* ShmDcCommonData = (DcCommonInfo*)GetShmDcCommonData();
-    Gpio_out *pGpio = (Gpio_out *)gpio;
-
-    if ((strncmp((char*)&pSysConfig->ModelName[7], "V", 1) == 0) ||
-        (strncmp((char*)&pSysConfig->ModelName[7], "F", 1) == 0)) {
-        chillerCount++;
-        ShmDcCommonData->pGunInfo[0].withChiller = TRUE;
-    }
-
-    if ((strncmp((char*)&pSysConfig->ModelName[9], "V", 1) == 0) ||
-        (strncmp((char*)&pSysConfig->ModelName[9], "F", 1) == 0)) {
-        chillerCount++;
-        ShmDcCommonData->pGunInfo[1].withChiller = TRUE;
-    }
-
-    if (chillerCount == 0) {
-        pGpio->AC_Connector = 0x00;
-        return;
-    }
-    // 設定chiller 開關
-    for (gunIndex = 0; gunIndex < pSysConfig->TotalConnectorCount; gunIndex++) {
-        if (!ShmDcCommonData->pGunInfo[gunIndex].withChiller)
-            continue;
-        pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-        pChillerInfo = (ChillerInfo *)&fChillerInfo[gunIndex];
-
-        if((pDcChargingInfo->SystemStatus > S_AUTHORIZING && pDcChargingInfo->SystemStatus < S_TERMINATING) ||
-            (pDcChargingInfo->SystemStatus >= S_CCS_PRECHARGE_ST0 && pDcChargingInfo->SystemStatus <= S_CCS_PRECHARGE_ST1)) {
-            pChillerInfo->ChillerSwitch = YES;
-            pChillerInfo->ChillerOnTime = time((time_t *)NULL);
-        } else {
-            if(pChillerInfo->ChillerSwitch == YES) {
-                //10分鐘後停止
-                if ((time((time_t *)NULL) - pChillerInfo->ChillerOnTime) >= 600) {
-                    pChillerInfo->ChillerSwitch = NO;
-                }
-            } else {
-                pChillerInfo->ChillerSwitch = NO;
-                ShmFanModuleData->SetFan1Speed = 0;
-            }
-        }
-        // 檢查Chiller溫度點,若小於零下時開啟heater,大於10度時關閉heater
-        if (pDcChargingInfo->ChillerTemp < 60) {
-            pGpio->AC_Breaker = YES;
-        } else if(pDcChargingInfo->ChillerTemp > 70) {
-            pGpio->AC_Breaker = NO;
-        }
-        //log_info("Set Heater %s", pGpio->AC_Breaker ? "ON" : "OFF");
-    }
-
-    uint8_t _chillerNeedOn = NO;
-    for (gunIndex = 0; gunIndex < pSysConfig->TotalConnectorCount; gunIndex++)
-    {
-        pChillerInfo = (ChillerInfo*)&fChillerInfo[gunIndex];
-        if (pChillerInfo->ChillerSwitch == YES) {
-            _chillerNeedOn = YES;
-            ShmFanModuleData->SetFan1Speed = 7000;
-        }
-    }
-    /*
-    if (ShmDcCommonData->debugflag == YES)
-        _chillerNeedOn = ShmDcCommonData->chillerCtrl;
-    */
-    if (ShmPrimaryMcuData->InputDet.bits.Ac_Drop == ABNORMAL) {
-        _chillerNeedOn = NO;
-    }
-
-    if(_chiller.ChillerSwitch != _chillerNeedOn) {
-        log_info("Chiller Need Turn %s", _chillerNeedOn == YES ? "ON" : "OFF");
-    }
-    _chiller.ChillerSwitch = _chillerNeedOn;
-    pGpio->AC_Connector = _chiller.ChillerSwitch;//Chiller ON/OFF Control, "0: Chiller disable, 1: Chiller enable"
-
-}
-
-void SetOutputGpio(int fd, uint8_t outputValue)
-{
-    Gpio_out gpio;
-    LedConfig *pLedConfig = (LedConfig *)&outputValue;
-    static uint8_t flash = NO;
-
-    if (strcmp((char *)pSysInfo->LcmHwRev, " ") == 0x00) {
-        if (flash == NO) {
-            flash = YES;
-        } else {
-            flash = NO;
-        }
-    } else {
-        if (flash == NO) {
-            flash = YES;
-        }
-    }
-
-    pLedConfig->LeftButtonLed = flash;
-    pLedConfig->RightButtonLed = flash;
-
-    gpio.Button_LED[0] = pLedConfig->LeftButtonLed;
-    gpio.Button_LED[1] = pLedConfig->RightButtonLed;
-
-    gpio.System_LED[0] = pLedConfig->GreenLED;
-    gpio.System_LED[1] = pLedConfig->YellowLED;
-    gpio.System_LED[2] = pLedConfig->RedLED;
-    gpio.System_LED[3] = 0x00;
-
-    checkChillerStatus(&gpio);
-
-    //gpio.AC_Breaker = 0x00;
-
-    Config_Gpio_Output(fd, OP_ADDR_IO_EXTEND, &gpio);
-}
-
-void SetRtcData(int fd)
-{
-    Rtc rtc = {0};
-    struct timeb csuTime;
-    struct tm *tmCSU;
-
-    ftime(&csuTime);
-    tmCSU = localtime(&csuTime.time);
-    //log_info("Time : %04d-%02d-%02d %02d:%02d:%02d ",
-    //         tmCSU->tm_year + 1900,
-    //         tmCSU->tm_mon + 1,
-    //         tmCSU->tm_mday,
-    //         tmCSU->tm_hour,
-    //         tmCSU->tm_min,
-    //         tmCSU->tm_sec);
-
-    rtc.RtcData[0] = '0' + (tmCSU->tm_year + 1900) / 1000 % 10;
-    rtc.RtcData[1] = '0' + (tmCSU->tm_year + 1900) / 100 % 10;
-    rtc.RtcData[2] = '0' + (tmCSU->tm_year + 1900) / 10 % 10;
-    rtc.RtcData[3] = '0' + (tmCSU->tm_year + 1900) / 1 % 10;
-
-    rtc.RtcData[4] = '0' + (tmCSU->tm_mon + 1) / 10 % 10;
-    rtc.RtcData[5] = '0' + (tmCSU->tm_mon + 1) / 1 % 10;
-
-    rtc.RtcData[6] = '0' + (tmCSU->tm_mday) / 10 % 10;
-    rtc.RtcData[7] = '0' + (tmCSU->tm_mday) / 1 % 10;
-
-    rtc.RtcData[8] = '0' + (tmCSU->tm_hour) / 10 % 10;
-    rtc.RtcData[9] = '0' + (tmCSU->tm_hour) / 1 % 10;
-
-    rtc.RtcData[10] = '0' + (tmCSU->tm_min) / 10 % 10;
-    rtc.RtcData[11] = '0' + (tmCSU->tm_min) / 1 % 10;
-
-    rtc.RtcData[12] = '0' + (tmCSU->tm_sec) / 10 % 10;
-    rtc.RtcData[13] = '0' + (tmCSU->tm_sec) / 1 % 10;
-
-    if (Config_Rtc_Data(fd, OP_ADDR_IO_EXTEND, &rtc) == PASS) {
-        //log_info("SetRtc sucessfully. ");
-    } else {
-        //log_info("SetRtc fail. ");
-    }
-}
-
-void SetModelName(int fd)
-{
-    if (Config_Model_Name(fd, OP_ADDR_IO_EXTEND, pSysConfig->ModelName) == PASS) {
-    }
-}
-
-//================================================
-// Main process
-//================================================
-int InitComPort()
-{
-    int fd;
-    struct termios tios;
-
-    fd = open(priPortName, O_RDWR);
-    if (fd <= 0) {
-        log_error("open 407 Communication port NG ");
-        return -1;
-    }
-    ioctl (fd, TCGETS, &tios);
-    tios.c_cflag = B115200 | CS8 | CLOCAL | CREAD;
-    tios.c_lflag = 0;
-    tios.c_iflag = 0;
-    tios.c_oflag = 0;
-    tios.c_cc[VMIN] = 0;
-    tios.c_cc[VTIME] = (uint8_t)1;
-    tios.c_lflag = 0;
-    tcflush(fd, TCIFLUSH);
-    ioctl (fd, TCSETS, &tios);
-
-    return fd;
-}
-
-unsigned long GetTimeoutValue(struct timeval _sour_time)
-{
-    struct timeval _end_time;
-    gettimeofday(&_end_time, NULL);
-
-    return 1000000 * (_end_time.tv_sec - _sour_time.tv_sec) + _end_time.tv_usec - _sour_time.tv_usec;
-}
-unsigned long GetClockTimeoutValue(struct timespec _start_time)
-{
-    struct timespec ts_end;
-    unsigned long ret = 0;
-
-    clock_gettime(CLOCK_MONOTONIC, &ts_end);
-
-    ret = ((unsigned long)(ts_end.tv_sec - _start_time.tv_sec) * 1000000) + ((unsigned long)((ts_end.tv_nsec / 1000) - (_start_time.tv_nsec / 1000)));
-
-    return ret;
-}
-
-static bool IsPrimaryProcessNeedPause(void)
-{
-    bool _pause = false;
-    static bool isPause = false;
-    struct ChargingInfoData *pDcChargingInfo = NULL;
-
-    for (uint8_t i = 0; i < pSysConfig->TotalConnectorCount; i++)
-    {
-        pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(i);
-        if(pDcChargingInfo->SystemStatus == S_UPDATE)
-        {
-            _pause = true;
-        }
-    }
-    if(isPause != _pause)
-    {
-        log_info("Primary Process Now Is %s ", _pause == true ? "Paused" : "Continued");
-    }
-    isPause = _pause;
-
-    return _pause;
-}
-
-int main(void)
-{
-    int Uart1Fd = -1;
-
-    //if (InitShareMemory() == FAIL) {
-    //    log_error("InitShareMemory NG");
-    //    if (ShmStatusCodeData != NULL) {
-    //        pAlarmCode->AlarmEvents.bits.FailToCreateShareMemory = 1;
-    //    }
-    //    sleep(5);
-    //    return 0;
-    //}
-
-    if (CreateAllCsuShareMemory() == FAIL) {
-        log_error("create share memory error");
-        return FAIL;
-    }
-
-    MappingGunChargingInfo("Primary Task");
-
-    pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
-    pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
-    pAlarmCode = (struct AlarmCodeData *)GetShmAlarmCodeData();
-    pFaultCode = (struct FaultCodeData *)GetShmFaultCodeData();
-    ShmPrimaryMcuData = (struct PrimaryMcuData *)GetShmPrimaryMcuData();
-    ShmDcCommonData = (DcCommonInfo *)GetShmDcCommonData();
-
-    Uart1Fd = InitComPort();
-    //log_info("407 Port id = %d ", Uart1Fd);
-
-    if (Uart1Fd < 0) {
-        log_error("InitComPort (Uart1 : AM3352 - STM32) NG");
-
-        if (pAlarmCode != NULL) {
-            pAlarmCode->AlarmEvents.bits.CsuInitFailed = 1;
-        }
-        sleep(5);
-
-        return 0;
-    }
-
-    SetRtcData(Uart1Fd);
-    SetModelName(Uart1Fd);
-
-    gun_count = pSysConfig->TotalConnectorCount;
-
-    //Initialization();
-
-    for (;;) {
-        // 程序開始之前~ 必須先確定 FW 版本與硬體版本,確認後!!~ 該模組才算是真正的 Initial Comp.
-        // 模組更新 FW 後,需重新做
-        if(IsPrimaryProcessNeedPause() == true)
-        {
-            sleep(1);
-            continue;
-        }
-        if (ShmPrimaryMcuData->SelfTest_Comp != PASS) {
-            //log_info("(407) Get Fw and Hw Ver. ");
-            GetFwAndHwVersion(Uart1Fd);
-            sleep(1);
-            ShmPrimaryMcuData->SelfTest_Comp = PASS;
-        } else {
-            SetOutputGpio(Uart1Fd, ShmPrimaryMcuData->OutputDrv.OutputDrvValue[0]);
-
-            GetInputGpioStatus(Uart1Fd);
-        }
-
-
-        usleep(50000);
-    }
-
-    return FAIL;
-}
+#include <sys/time.h>
+#include <sys/timeb.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <sys/types.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 <arpa/inet.h>
+#include <netinet/in.h>
+#include <stdbool.h>
+
+#include <unistd.h>
+#include <stdarg.h>
+#include <stdio.h>      /*標準輸入輸出定義*/
+#include <stdlib.h>     /*標準函數庫定義*/
+#include <unistd.h>     /*Unix 標準函數定義*/
+#include <fcntl.h>      /*檔控制定義*/
+#include <termios.h>    /*PPSIX 終端控制定義*/
+#include <errno.h>      /*錯誤號定義*/
+#include <errno.h>
+#include <string.h>
+#include <time.h>
+#include <ctype.h>
+#include <ifaddrs.h>
+#include <math.h>
+
+#include "../Log/log.h"
+#include "../Define/define.h"
+#include "../Config.h"
+#include "../ShareMemory/shmMem.h"
+#include "PrimaryComm.h"
+#include "Module_PrimaryComm.h"
+
+//------------------------------------------------------------------------------
+//struct SysConfigAndInfo *ShmSysConfigAndInfo;
+//struct StatusCodeData *ShmStatusCodeData;
+static struct SysConfigData *pSysConfig = NULL;
+static struct SysInfoData *pSysInfo = NULL;
+static struct AlarmCodeData *pAlarmCode = NULL;
+static struct FaultCodeData *pFaultCode = NULL;
+static struct PrimaryMcuData *ShmPrimaryMcuData;
+static DcCommonInfo *ShmDcCommonData = NULL;
+
+const char *priPortName = "/dev/ttyS1";
+uint8_t gun_count; //DS60-120 add
+
+uint8_t EmgBtn_count = 0;
+uint8_t Door_count = 0;
+uint8_t EmgBtn_flag = 0;
+uint8_t Door_flag = 0;
+
+
+//================================================
+// Function
+//================================================
+void GetFwAndHwVersion(int fd)
+{
+    Ver ver = {0};
+
+    if (Query_FW_Ver(fd, OP_ADDR_IO_EXTEND, &ver) == PASS) {
+        //log_info("Primary FW Rev = %s ", ver.Version_FW);
+        strcpy((char *)ShmPrimaryMcuData->version, ver.Version_FW);
+        strcpy((char *) pSysInfo->CsuPrimFwRev, ver.Version_FW);
+    }
+
+    //if (Query_HW_Ver(fd, OP_ADDR_IO_EXTEND, &ver) == PASS)
+    //    ;//log_info("Primary HW Rev  = %s ", ver.Version_HW);
+}
+
+void GetInputGpioStatus(int fd)
+{
+    uint8_t dispenserSwTmp = 0;
+    Gpio_in gpio_in = {0};
+    static uint8_t dispenserSw = 0;
+
+    //log_info("GetInputGpioStatus ");
+    if (Query_Gpio_Input(fd, OP_ADDR_IO_EXTEND, &gpio_in) != PASS) {
+        return;
+    }
+
+    ShmPrimaryMcuData->InputDet.bits.SpdDetec = gpio_in.SPD;
+    ShmPrimaryMcuData->InputDet.bits.Ac_Drop = ~gpio_in.AC_Drop; // Chiller Alarm ping
+
+    if (gpio_in.Emergency_Btn && (EmgBtn_flag != gpio_in.Emergency_Btn))
+    {
+            EmgBtn_count++;
+        if (EmgBtn_count > SensorTrigCount) {
+           EmgBtn_flag = 1;
+           EmgBtn_count = 0; // Avoid Overflow
+       }
+    } else if (EmgBtn_flag != gpio_in.Emergency_Btn ) {
+        EmgBtn_count++;
+        if (EmgBtn_count > SensorTrigCount) {
+            EmgBtn_flag = 0;
+            EmgBtn_count = 0;
+        }
+    }
+
+    ShmPrimaryMcuData->InputDet.bits.EmergencyButton = EmgBtn_flag;
+
+    dispenserSwTmp |= (ShmPrimaryMcuData->InputDet.bits.Key0);
+    dispenserSwTmp |= (ShmPrimaryMcuData->InputDet.bits.Key1 << 1);
+    dispenserSwTmp |= (ShmPrimaryMcuData->InputDet.bits.Key2 << 2);
+    dispenserSwTmp |= (ShmPrimaryMcuData->InputDet.bits.Key3 << 3);
+
+    if (dispenserSwTmp != dispenserSw) {
+        dispenserSw = dispenserSwTmp;
+        log_info("Dispenser switch number =  %d, bit = %d, %d, %d, %d",
+                 dispenserSw,
+                 ShmPrimaryMcuData->InputDet.bits.Key3,
+                 ShmPrimaryMcuData->InputDet.bits.Key2,
+                 ShmPrimaryMcuData->InputDet.bits.Key1,
+                 ShmPrimaryMcuData->InputDet.bits.Key0);
+    }
+
+    ShmPrimaryMcuData->InputDet.bits.Button1 = gpio_in.Button[0];
+    ShmPrimaryMcuData->InputDet.bits.Button2 = gpio_in.Button[1];
+
+
+    if ((strncmp((char *)&pSysConfig->ModelName[7], "V", 1) == 0) ||
+            (strncmp((char *)&pSysConfig->ModelName[9], "V", 1) == 0) ||
+            (strncmp((char *)&pSysConfig->ModelName[7], "F", 1) == 0) ||
+            (strncmp((char *)&pSysConfig->ModelName[9], "F", 1) == 0)
+       ) {
+        pAlarmCode->AlarmEvents.bits.CcsLiquidChillerWaterLevelWarning = ~gpio_in.AC_Connector;
+        pFaultCode->FaultEvents.bits.CcsLiquidChillerWaterLevelFault = ~gpio_in.AC_MainBreaker;
+    } else {
+        pAlarmCode->AlarmEvents.bits.CcsLiquidChillerWaterLevelWarning = gpio_in.AC_Connector;
+        pFaultCode->FaultEvents.bits.CcsLiquidChillerWaterLevelFault = gpio_in.AC_MainBreaker;
+    }
+
+    if (Door_flag == gpio_in.Door_Open) {
+        Door_count++;
+        if (Door_count == 3 ) {
+            Door_count = 0;
+            Door_flag = gpio_in.Door_Open;
+        }
+    } else { 
+        Door_flag = gpio_in.Door_Open;
+        Door_count = 0;
+    }
+    /*
+    if (gpio_in.Door_Open == 0 && (Door_flag == gpio_in.Door_Open))
+    {
+        Door_count++;
+        if (Door_count > SensorTrigCount) {
+            Door_flag = 1;
+            Door_count = 0; // Avoid Overflow
+       }
+    } else if (gpio_in.Door_Open && Door_flag) {
+        Door_count++;
+        if (Door_count > SensorTrigCount) {
+            Door_flag = 0;
+            Door_count = 0;
+        }
+    }
+    */
+
+
+    ShmPrimaryMcuData->InputDet.bits.DoorOpen = ~Door_flag;
+
+
+/*
+    log_info("Emergency Button Count = %d , Emergency flag = %d",
+            EmgBtn_count,EmgBtn_flag);
+    log_info("Door Sensor Count = %d , Door Sensor flag = %d",
+            Door_count,Door_flag);
+*/
+
+    ShmPrimaryMcuData->InputDet.bits.Key0 = ~gpio_in.Key[0] & 0x01;
+    ShmPrimaryMcuData->InputDet.bits.Key1 = ~gpio_in.Key[1] & 0x01;
+    ShmPrimaryMcuData->InputDet.bits.Key2 = ~gpio_in.Key[2] & 0x01;
+    ShmPrimaryMcuData->InputDet.bits.Key3 = ~gpio_in.Key[3] & 0x01;
+
+    return;
+
+
+}
+
+static void checkChillerStatus(Gpio_out *gpio)
+{
+    uint8_t gunIndex = 0;
+    uint8_t chillerCount = 0;
+    struct ChargingInfoData *pDcChargingInfo = NULL;
+    static ChillerInfo fChillerInfo[2] = {0}, *pChillerInfo = NULL;
+    static ChillerInfo _chiller;
+    struct FanModuleData* ShmFanModuleData = (struct FanModuleData*)GetShmFanModuleData();
+    DcCommonInfo* ShmDcCommonData = (DcCommonInfo*)GetShmDcCommonData();
+    Gpio_out *pGpio = (Gpio_out *)gpio;
+
+    if ((strncmp((char*)&pSysConfig->ModelName[7], "V", 1) == 0) ||
+        (strncmp((char*)&pSysConfig->ModelName[7], "F", 1) == 0)) {
+        chillerCount++;
+        ShmDcCommonData->pGunInfo[0].withChiller = TRUE;
+    }
+
+    if ((strncmp((char*)&pSysConfig->ModelName[9], "V", 1) == 0) ||
+        (strncmp((char*)&pSysConfig->ModelName[9], "F", 1) == 0)) {
+        chillerCount++;
+        ShmDcCommonData->pGunInfo[1].withChiller = TRUE;
+    }
+
+    if (chillerCount == 0) {
+        pGpio->AC_Connector = 0x00;
+        return;
+    }
+    // 設定chiller 開關
+    for (gunIndex = 0; gunIndex < pSysConfig->TotalConnectorCount; gunIndex++) {
+        if (!ShmDcCommonData->pGunInfo[gunIndex].withChiller)
+            continue;
+        pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+        pChillerInfo = (ChillerInfo *)&fChillerInfo[gunIndex];
+
+        if((pDcChargingInfo->SystemStatus > S_AUTHORIZING && pDcChargingInfo->SystemStatus < S_TERMINATING) ||
+            (pDcChargingInfo->SystemStatus >= S_CCS_PRECHARGE_ST0 && pDcChargingInfo->SystemStatus <= S_CCS_PRECHARGE_ST1)) {
+            pChillerInfo->ChillerSwitch = YES;
+            pChillerInfo->ChillerOnTime = time((time_t *)NULL);
+        } else {
+            if(pChillerInfo->ChillerSwitch == YES) {
+                //10分鐘後停止
+                if ((time((time_t *)NULL) - pChillerInfo->ChillerOnTime) >= 600) {
+                    pChillerInfo->ChillerSwitch = NO;
+                }
+            } else {
+                pChillerInfo->ChillerSwitch = NO;
+                ShmFanModuleData->SetFan1Speed = 0;
+            }
+        }
+        // 檢查Chiller溫度點,若小於零下時開啟heater,大於10度時關閉heater
+        if (pDcChargingInfo->ChillerTemp < 60) {
+            pGpio->AC_Breaker = YES;
+        } else if(pDcChargingInfo->ChillerTemp > 70) {
+            pGpio->AC_Breaker = NO;
+        }
+        //log_info("Set Heater %s", pGpio->AC_Breaker ? "ON" : "OFF");
+    }
+
+    uint8_t _chillerNeedOn = NO;
+    for (gunIndex = 0; gunIndex < pSysConfig->TotalConnectorCount; gunIndex++)
+    {
+        pChillerInfo = (ChillerInfo*)&fChillerInfo[gunIndex];
+        if (pChillerInfo->ChillerSwitch == YES) {
+            _chillerNeedOn = YES;
+            ShmFanModuleData->SetFan1Speed = 7000;
+        }
+    }
+    /*
+    if (ShmDcCommonData->debugflag == YES)
+        _chillerNeedOn = ShmDcCommonData->chillerCtrl;
+    */
+    if (ShmPrimaryMcuData->InputDet.bits.Ac_Drop == ABNORMAL) {
+        _chillerNeedOn = NO;
+    }
+
+    if(_chiller.ChillerSwitch != _chillerNeedOn) {
+        log_info("Chiller Need Turn %s", _chillerNeedOn == YES ? "ON" : "OFF");
+    }
+    _chiller.ChillerSwitch = _chillerNeedOn;
+    pGpio->AC_Connector = _chiller.ChillerSwitch;//Chiller ON/OFF Control, "0: Chiller disable, 1: Chiller enable"
+
+}
+
+void SetOutputGpio(int fd, uint8_t outputValue)
+{
+    Gpio_out gpio;
+    LedConfig *pLedConfig = (LedConfig *)&outputValue;
+    static uint8_t flash = NO;
+
+    if (strcmp((char *)pSysInfo->LcmHwRev, " ") == 0x00) {
+        if (flash == NO) {
+            flash = YES;
+        } else {
+            flash = NO;
+        }
+    } else {
+        if (flash == NO) {
+            flash = YES;
+        }
+    }
+
+    pLedConfig->LeftButtonLed = flash;
+    pLedConfig->RightButtonLed = flash;
+
+    gpio.Button_LED[0] = pLedConfig->LeftButtonLed;
+    gpio.Button_LED[1] = pLedConfig->RightButtonLed;
+
+    gpio.System_LED[0] = pLedConfig->GreenLED;
+    gpio.System_LED[1] = pLedConfig->YellowLED;
+    gpio.System_LED[2] = pLedConfig->RedLED;
+    gpio.System_LED[3] = 0x00;
+
+    checkChillerStatus(&gpio);
+
+    //gpio.AC_Breaker = 0x00;
+
+    Config_Gpio_Output(fd, OP_ADDR_IO_EXTEND, &gpio);
+}
+
+void SetRtcData(int fd)
+{
+    Rtc rtc = {0};
+    struct timeb csuTime;
+    struct tm *tmCSU;
+
+    ftime(&csuTime);
+    tmCSU = localtime(&csuTime.time);
+    //log_info("Time : %04d-%02d-%02d %02d:%02d:%02d ",
+    //         tmCSU->tm_year + 1900,
+    //         tmCSU->tm_mon + 1,
+    //         tmCSU->tm_mday,
+    //         tmCSU->tm_hour,
+    //         tmCSU->tm_min,
+    //         tmCSU->tm_sec);
+
+    rtc.RtcData[0] = '0' + (tmCSU->tm_year + 1900) / 1000 % 10;
+    rtc.RtcData[1] = '0' + (tmCSU->tm_year + 1900) / 100 % 10;
+    rtc.RtcData[2] = '0' + (tmCSU->tm_year + 1900) / 10 % 10;
+    rtc.RtcData[3] = '0' + (tmCSU->tm_year + 1900) / 1 % 10;
+
+    rtc.RtcData[4] = '0' + (tmCSU->tm_mon + 1) / 10 % 10;
+    rtc.RtcData[5] = '0' + (tmCSU->tm_mon + 1) / 1 % 10;
+
+    rtc.RtcData[6] = '0' + (tmCSU->tm_mday) / 10 % 10;
+    rtc.RtcData[7] = '0' + (tmCSU->tm_mday) / 1 % 10;
+
+    rtc.RtcData[8] = '0' + (tmCSU->tm_hour) / 10 % 10;
+    rtc.RtcData[9] = '0' + (tmCSU->tm_hour) / 1 % 10;
+
+    rtc.RtcData[10] = '0' + (tmCSU->tm_min) / 10 % 10;
+    rtc.RtcData[11] = '0' + (tmCSU->tm_min) / 1 % 10;
+
+    rtc.RtcData[12] = '0' + (tmCSU->tm_sec) / 10 % 10;
+    rtc.RtcData[13] = '0' + (tmCSU->tm_sec) / 1 % 10;
+
+    if (Config_Rtc_Data(fd, OP_ADDR_IO_EXTEND, &rtc) == PASS) {
+        //log_info("SetRtc sucessfully. ");
+    } else {
+        //log_info("SetRtc fail. ");
+    }
+}
+
+void SetModelName(int fd)
+{
+    if (Config_Model_Name(fd, OP_ADDR_IO_EXTEND, pSysConfig->ModelName) == PASS) {
+    }
+}
+
+//================================================
+// Main process
+//================================================
+int InitComPort()
+{
+    int fd;
+    struct termios tios;
+
+    fd = open(priPortName, O_RDWR);
+    if (fd <= 0) {
+        log_error("open 407 Communication port NG ");
+        return -1;
+    }
+    ioctl (fd, TCGETS, &tios);
+    tios.c_cflag = B115200 | CS8 | CLOCAL | CREAD;
+    tios.c_lflag = 0;
+    tios.c_iflag = 0;
+    tios.c_oflag = 0;
+    tios.c_cc[VMIN] = 0;
+    tios.c_cc[VTIME] = (uint8_t)1;
+    tios.c_lflag = 0;
+    tcflush(fd, TCIFLUSH);
+    ioctl (fd, TCSETS, &tios);
+
+    return fd;
+}
+
+unsigned long GetTimeoutValue(struct timeval _sour_time)
+{
+    struct timeval _end_time;
+    gettimeofday(&_end_time, NULL);
+
+    return 1000000 * (_end_time.tv_sec - _sour_time.tv_sec) + _end_time.tv_usec - _sour_time.tv_usec;
+}
+unsigned long GetClockTimeoutValue(struct timespec _start_time)
+{
+    struct timespec ts_end;
+    unsigned long ret = 0;
+
+    clock_gettime(CLOCK_MONOTONIC, &ts_end);
+
+    ret = ((unsigned long)(ts_end.tv_sec - _start_time.tv_sec) * 1000000) + ((unsigned long)((ts_end.tv_nsec / 1000) - (_start_time.tv_nsec / 1000)));
+
+    return ret;
+}
+
+static bool IsPrimaryProcessNeedPause(void)
+{
+    bool _pause = false;
+    static bool isPause = false;
+    struct ChargingInfoData *pDcChargingInfo = NULL;
+
+    for (uint8_t i = 0; i < pSysConfig->TotalConnectorCount; i++)
+    {
+        pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(i);
+        if(pDcChargingInfo->SystemStatus == S_UPDATE)
+        {
+            _pause = true;
+        }
+    }
+    if(isPause != _pause)
+    {
+        log_info("Primary Process Now Is %s ", _pause == true ? "Paused" : "Continued");
+    }
+    isPause = _pause;
+
+    return _pause;
+}
+
+int main(void)
+{
+    int Uart1Fd = -1;
+
+    //if (InitShareMemory() == FAIL) {
+    //    log_error("InitShareMemory NG");
+    //    if (ShmStatusCodeData != NULL) {
+    //        pAlarmCode->AlarmEvents.bits.FailToCreateShareMemory = 1;
+    //    }
+    //    sleep(5);
+    //    return 0;
+    //}
+
+    if (CreateAllCsuShareMemory() == FAIL) {
+        log_error("create share memory error");
+        return FAIL;
+    }
+
+    MappingGunChargingInfo("Primary Task");
+
+    pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
+    pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
+    pAlarmCode = (struct AlarmCodeData *)GetShmAlarmCodeData();
+    pFaultCode = (struct FaultCodeData *)GetShmFaultCodeData();
+    ShmPrimaryMcuData = (struct PrimaryMcuData *)GetShmPrimaryMcuData();
+    ShmDcCommonData = (DcCommonInfo *)GetShmDcCommonData();
+
+    Uart1Fd = InitComPort();
+    //log_info("407 Port id = %d ", Uart1Fd);
+
+    if (Uart1Fd < 0) {
+        log_error("InitComPort (Uart1 : AM3352 - STM32) NG");
+
+        if (pAlarmCode != NULL) {
+            pAlarmCode->AlarmEvents.bits.CsuInitFailed = 1;
+        }
+        sleep(5);
+
+        return 0;
+    }
+
+    SetRtcData(Uart1Fd);
+    SetModelName(Uart1Fd);
+
+    gun_count = pSysConfig->TotalConnectorCount;
+
+    //Initialization();
+
+    for (;;) {
+        // 程序開始之前~ 必須先確定 FW 版本與硬體版本,確認後!!~ 該模組才算是真正的 Initial Comp.
+        // 模組更新 FW 後,需重新做
+        if(IsPrimaryProcessNeedPause() == true)
+        {
+            sleep(1);
+            continue;
+        }
+        if (ShmPrimaryMcuData->SelfTest_Comp != PASS) {
+            //log_info("(407) Get Fw and Hw Ver. ");
+            GetFwAndHwVersion(Uart1Fd);
+            sleep(1);
+            ShmPrimaryMcuData->SelfTest_Comp = PASS;
+        } else {
+            SetOutputGpio(Uart1Fd, ShmPrimaryMcuData->OutputDrv.OutputDrvValue[0]);
+
+            GetInputGpioStatus(Uart1Fd);
+        }
+
+
+        usleep(50000);
+    }
+
+    return FAIL;
+}

+ 35 - 35
EVSE/Projects/DD360Tcci/Apps/ModulePrimary/Module_PrimaryComm.h

@@ -1,35 +1,35 @@
-#ifndef _MODULE_PRIMARY_COMM_H_
-#define _MODULE_PRIMARY_COMM_H_
-
-//------------------------------------------------------------------------------
-#include <stdint.h>
-
-//------------------------------------------------------------------------------
-//#define log_info(format, args...) StoreLogMsg("[%s:%d][%s][Info] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
-//#define log_warn(format, args...) StoreLogMsg("[%s:%d][%s][Warn] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
-//#define log_error(format, args...) StoreLogMsg("[%s:%d][%s][Error] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
-
-//------------------------------------------------------------------------------
-typedef struct StChillerInfo {
-    uint8_t ChillerSwitch;
-    uint32_t ChillerOnTime;
-    uint8_t Reserved[3];
-} ChillerInfo;
-
-typedef struct StLedConfig {
-    //OutputDrvValue[0]
-    uint8_t LeftButtonLed: 1;                   //bit 0,    H: ON,      L:OFF
-    uint8_t RightButtonLed: 1;                  //bit 1,    H: ON,      L:OFF
-    uint8_t GreenLED: 1;                          //bit 2,    H: ON,      L:OFF
-    uint8_t YellowLED: 1;                       //bit 3,    H: ON,      L:OFF
-    uint8_t RedLED: 1;                        //bit 4,    H: ON,      L:OFF
-    uint8_t SystemLed4: 1;                      //bit 5,    H: ON,      L:OFF
-    uint8_t AcContactor: 1;                     //bit 6,    H: ON,      L:OFF
-    uint8_t Reserved: 1;                        //bit 7 reserved
-} LedConfig;
-
-//------------------------------------------------------------------------------
-//int StoreLogMsg(const char *fmt, ...);
-#define SensorTrigCount 3
-
-#endif /* _MODULE_PRIMARY_COMM_H_ */
+#ifndef _MODULE_PRIMARY_COMM_H_
+#define _MODULE_PRIMARY_COMM_H_
+
+//------------------------------------------------------------------------------
+#include <stdint.h>
+
+//------------------------------------------------------------------------------
+//#define log_info(format, args...) StoreLogMsg("[%s:%d][%s][Info] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
+//#define log_warn(format, args...) StoreLogMsg("[%s:%d][%s][Warn] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
+//#define log_error(format, args...) StoreLogMsg("[%s:%d][%s][Error] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
+
+//------------------------------------------------------------------------------
+typedef struct StChillerInfo {
+    uint8_t ChillerSwitch;
+    uint32_t ChillerOnTime;
+    uint8_t Reserved[3];
+} ChillerInfo;
+
+typedef struct StLedConfig {
+    //OutputDrvValue[0]
+    uint8_t LeftButtonLed: 1;                   //bit 0,    H: ON,      L:OFF
+    uint8_t RightButtonLed: 1;                  //bit 1,    H: ON,      L:OFF
+    uint8_t GreenLED: 1;                          //bit 2,    H: ON,      L:OFF
+    uint8_t YellowLED: 1;                       //bit 3,    H: ON,      L:OFF
+    uint8_t RedLED: 1;                        //bit 4,    H: ON,      L:OFF
+    uint8_t SystemLed4: 1;                      //bit 5,    H: ON,      L:OFF
+    uint8_t AcContactor: 1;                     //bit 6,    H: ON,      L:OFF
+    uint8_t Reserved: 1;                        //bit 7 reserved
+} LedConfig;
+
+//------------------------------------------------------------------------------
+//int StoreLogMsg(const char *fmt, ...);
+#define SensorTrigCount 3
+
+#endif /* _MODULE_PRIMARY_COMM_H_ */

+ 595 - 595
EVSE/Projects/DD360Tcci/Apps/ModuleUpdateFW/Module_UpdateFW.c

@@ -1,595 +1,595 @@
-#include <stdio.h>      /*標準輸入輸出定義*/
-#include <stdlib.h>     /*標準函數庫定義*/
-#include <string.h>
-#include <stdint.h>
-
-#include <sys/types.h>
-#include <dirent.h>
-
-#include "../Config.h"
-#include "../Log/log.h"
-#include "../Define/define.h"
-
-#include "../ShareMemory/shmMem.h"
-#include "../CSU/main.h"
-#include "../Config.h"
-
-struct SysConfigData *pSysConfig = NULL;
-struct SysInfoData *pSysInfo = NULL;
-struct OCPP16Data *ShmOCPP16Data = NULL;
-struct ChargingInfoData *pAcChargingInfo = NULL;
-static struct ChargingInfoData *pDcChargingInfo = NULL;
-DcCommonInfo *ShmDcCommonData = NULL; 
-#define MODELNAME_FAIL                          (0)
-#define UPGRADE_FAN                             (0x02)
-#if defined DD360Tcci || defined DD360Audi || defined DD360ComBox
-#define UPGRADE_RB                              (0x09) //0x09 for DD360Tcci dispenser
-#else
-#define UPGRADE_RB                              (0x03) //other module use
-#endif //defined DD360Tcci ||defined DD360Audi || defined DD360ComBox
-#define UPGRADE_PRI                             (0x04)
-#define UPGRADE_AC                              (0x05)
-#define UPGRADE_LED                             (0x06)
-
-//------------------------------------------------------------------------------
-static char *_priPortName = "/dev/ttyS1";
-static char *_485PortName = "/dev/ttyS5";
-
-//------------------------------------------------------------------------------
-
-void KillAllTask(void)
-{
-    pSysInfo->PageIndex = _PAGE_MAINTAIN;
-
-    system("killall Module_EventLogging");
-    system("killall Module_PrimaryComm");
-    system("killall Module_EvComm");
-    system("killall Module_LcmControl");
-    system("killall Module_InternalComm");
-
-#if defined DD360Tcci || defined DD360Audi || defined DD360ComBox
-    system("killall Module_DoComm");
-    return ;
-#endif //defined DD360Tcci || defined DD360Audi || defined DD360ComBox
-
-    system("killall Module_PsuComm");
-    system("killall OcppBackend &");
-    system("killall Module_4g &");
-    system("killall Module_Wifi &");
-}
-
-void KillTask(void)
-{
-    pSysInfo->PageIndex = _PAGE_MAINTAIN;
-
-    system("killall Module_EventLogging");
-    system("killall Module_PrimaryComm");
-    system("killall Module_EvComm");
-    system("killall Module_LcmControl");
-    system("killall Module_InternalComm");
-    //system("killall Module_DoComm");
-#if defined DD360Tcci || defined DD360Audi || defined DD360ComBox
-    return ;
-#endif //defined DD360Tcci || defined DD360Audi || defined DD360ComBox
-
-    system("killall Module_PsuComm");
-    system("killall OcppBackend &");
-    system("killall Module_4g &");
-    system("killall Module_Wifi &");
-}
-void setChargerMode(uint8_t gunIndex, uint8_t mode)
-{
-    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
-
-    pDcChargingInfo->SystemStatus = mode;
-
-    //log_info(" ====== System Status:%d ======",mode);
-}
-void TryCloseWatchdog()
-{
-    system("echo V > /dev/watchdog");
-}
-static int InitComPort(uint8_t target)
-{
-    int fd;
-    struct termios tios;
-
-    if (target == UPGRADE_PRI) {
-        fd = open(_priPortName, O_RDWR);
-    } else if (target == UPGRADE_FAN ||
-               target == UPGRADE_RB ||
-               target == UPGRADE_AC ||
-               target == UPGRADE_LED
-              ) {
-        fd = open(_485PortName, O_RDWR);
-    }
-
-    if (fd <= 0) {
-        log_error("open 407 Communication port NG ");
-        return -1;
-    }
-
-    ioctl (fd, TCGETS, &tios);
-    tios.c_cflag = B115200 | CS8 | CLOCAL | CREAD;
-    tios.c_lflag = 0;
-    tios.c_iflag = 0;
-    tios.c_oflag = 0;
-    tios.c_cc[VMIN] = 0;
-    tios.c_cc[VTIME] = (uint8_t)1;
-    tios.c_lflag = 0;
-    tcflush(fd, TCIFLUSH);
-    ioctl (fd, TCSETS, &tios);
-
-    return fd;
-}
-bool IsConnectorWholeIdle()
-{
-    bool result = true;
-
-    for (uint8_t count = 0; count < pSysConfig->TotalConnectorCount; count++) {
-        pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(count);
-
-        if (pDcChargingInfo->SystemStatus != S_IDLE &&
-                pDcChargingInfo->SystemStatus != S_RESERVATION) {
-            result = false;
-            break;
-        }
-    }
-
-    for (uint8_t count = 0; count < pSysConfig->AcConnectorCount; count++) {
-        pAcChargingInfo = (struct ChargingInfoData *)GetAcChargingInfoData(count);
-
-        if (pAcChargingInfo->SystemStatus != S_IDLE &&
-                pAcChargingInfo->IsErrorOccur == NO) {
-            result = false;
-            break;
-        }
-    }
-
-    return result;
-}
-
-
-static int InitCanBus(void)
-{
-    int fd = -1;
-    int nbytes;
-    struct timeval tv;
-    struct ifreq ifr0;
-    struct sockaddr_can addr0;
-
-    system("/sbin/ip link set can0 down");
-    system("/sbin/ip link set can0 type can bitrate 500000 restart-ms 100");
-    system("/sbin/ip link set can0 up");
-
-    fd = socket(PF_CAN, SOCK_RAW, CAN_RAW);
-
-    tv.tv_sec = 0;
-    tv.tv_usec = 10000;
-    if (setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(struct  timeval)) < 0) {
-        log_error("Set SO_RCVTIMEO NG");
-    }
-    nbytes = 40960;
-    if (setsockopt(fd, SOL_SOCKET,  SO_RCVBUF, &nbytes, sizeof(int)) < 0) {
-        log_error("Set SO_RCVBUF NG");
-    }
-    nbytes = 40960;
-    if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &nbytes, sizeof(int)) < 0) {
-        log_error("Set SO_SNDBUF NG");
-    }
-
-    strcpy(ifr0.ifr_name, "can0");
-    ioctl(fd, SIOCGIFINDEX, &ifr0); /* ifr.ifr_ifindex gets filled with that device's index */
-    addr0.can_family = AF_CAN;
-    addr0.can_ifindex = ifr0.ifr_ifindex;
-    bind(fd, (struct sockaddr *)&addr0, sizeof(addr0));
-
-    return fd;
-}
-bool CreateBufferForLcmFile(char *file)
-{
-	bool result = FAIL;
-	unsigned char *ptr = NULL;
-	long int MaxLen = 48 * 1024 * 1024, ImageLen = 0;
-	int fd, fd_lcm;
-	int wrd_lcm;
-	char Buf_lcm[256] = "/mnt/BUFFER.zip";
-
-	fd = open ( file, O_RDONLY );
-	if (fd < 0) {
-	    close ( fd );
-	    return result;
-	}
-
-	ptr = malloc(MaxLen);
-	ImageLen = read(fd, ptr, MaxLen);
-
-	fd_lcm = open ( Buf_lcm, O_RDWR | O_CREAT | O_EXCL );
-	if (fd_lcm < 0) {
-    	log_info( "Can not create %s \n", Buf_lcm );
-	} else {
-    	log_info( "Writing data to %s file.... \n", Buf_lcm );
-    	wrd_lcm = write ( fd_lcm, ptr + 48, ImageLen - 48 );
-    	close ( fd_lcm );
-    	log_info( ">> %s Written length : 0x%x \n", Buf_lcm, wrd_lcm );
-
-    	if (wrd_lcm != (ImageLen - 48)) {
-            result = FAIL;
-    	} else {
-        	result = PASS;
-    	}
-
-    	close(fd);
-    	free(ptr);
-	}
-
-	return result;
-}
-
-unsigned long long getAvailableMemory()
-{
-    system("pkill ntpd");
-    sleep(1);
-    long pages = sysconf(_SC_AVPHYS_PAGES);
-    long page_size = sysconf(_SC_PAGE_SIZE);
-    log_info("Avaiable Memory size:%d MB",pages*page_size/(1024*1024));
-    return pages * page_size;
-}
-
-static int CheckUpdateProcess(void)
-{
-    //bool isPass = true;
-    uint8_t retSucc = 0;
-    uint8_t retFail = 0;
-    uint8_t index = 0;
-    uint8_t target = 0;
-    char Buf[256];
-    char *new_str = NULL;
-    uint8_t *ptr = NULL;
-    int fd = 0;
-    int CanFd = 0;
-    int uartFd = 0;
-    unsigned int Type = 0;
-    long int MaxLen = 48 * 1024 * 1024, ImageLen = 0;
-    DIR *d;
-    struct dirent *dir;
-
-    struct ChargingInfoData *pDcChargingInfo = NULL;
-    
-    pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
-
-    if (getAvailableMemory() < (200 * 1024 * 1024))
-    {
-        log_info("Available memory (%.2f Bytes) less than 200 MBytes, free cache first.\n", getAvailableMemory() / (1024 * 1024.0));
-        system("echo 3 > /proc/sys/vm/drop_caches");
-    }
-
-    d = opendir("/mnt/");
-    if (d) {
-        log_info("Open /mnt success");
-        while ((dir = readdir(d)) != NULL) {
-            if (strcmp(dir->d_name, ".") == 0 || strcmp(dir->d_name, "..") == 0) {
-                continue;
-            }
-
-            new_str = calloc(strlen("/mnt/") + strlen(dir->d_name) + 1, sizeof(char));
-            //new_str[0] = '\0';
-            strcat(new_str, "/mnt/");
-            strcat(new_str, dir->d_name);
-            log_info("%s%s", "/mnt/", dir->d_name);
-            
-            fd = open(new_str, O_RDONLY);
-            if (fd < 0) {
-                return FAIL;
-            }
-
-            ptr = calloc(MaxLen, sizeof(char)); //-48 is take out the header
-            //memset(ptr, 0xFF, MaxLen);  //-48 is take out the header
-
-            //get the image length
-            ImageLen = read(fd, ptr, MaxLen);
-            for (uint8_t i = 0; i < 16; i++) {
-                if (pSysConfig->ModelName[i] != ptr[i]) {
-                    log_info("model name check fail. ");
-                    return FAIL;
-                }
-            }
-
-            log_info("model name check pass. ");
-            if (ImageLen > 20) {
-                Type = (((unsigned int)ptr[16]) << 24 |
-                        ((unsigned int)ptr[17]) << 16 |
-                        ((unsigned int)ptr[18]) << 8  |
-                        ((unsigned int)ptr[19]));
-                log_info("Typed...%x ", Type);
-                free(ptr);
-                switch (Type) {
-                case 0x10000001:
-                case 0x10000002:
-                case 0x10000003:
-                case 0x10000004:
-                case 0x10000005:
-                    if (Upgrade_Flash(Type, new_str, (char *)pSysConfig->ModelName) == PASS) {
-                        //return PASS;
-                        retSucc++;
-                    } else {
-                        log_info("Upgrade %x Failed", Type);
-                        //return FAIL;
-                        retFail++;
-                    }
-                    break;
-
-                case 0x10000007:
-                case 0x10000008:
-                case 0x10000009:
-                case 0x1000000A:
-                    CanFd = InitCanBus();
-                    if (CanFd > 0) {
-                        for (index = 0; index < pSysConfig->TotalConnectorCount; index++) {
-                            pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);
-                            if (pDcChargingInfo->Type == _Type_CCS_2) {
-                                uint8_t targetID = pDcChargingInfo->Evboard_id;
-                                /*
-                                if (pSysConfig->TotalConnectorCount == 1 &&
-                                        ShmDcCommonData->CcsVersion == _CCS_VERSION_CHECK_TAG_V015S0) {
-                                    //targetID += 1;
-                                }*/
-
-                                system("echo 3 > /proc/sys/vm/drop_caches");
-                                sleep(2);
-                                log_info("Upgrade CCS Processing..target id = %d ", targetID);
-                                if (Upgrade_CCS(CanFd,
-                                                Type,
-                                                targetID,
-                                                new_str,
-                                                (char *)pSysConfig->ModelName) == FAIL) {
-                                    log_info("Upgrade CCS Failed ");
-                                    retFail++;
-                                } else {
-                                    retSucc++;
-                                }
-                            }
-                        }
-                        close(CanFd);
-                    }
-                    memset(Buf, 0, sizeof(Buf));
-                    sprintf(Buf, "rm -rvf /mnt/%s", new_str);
-                    system(Buf);
-                    //isPass = true;
-#if 0
-                    CanFd = InitCanBus();
-                    if (CanFd > 0) {
-                        for (index = 0; index < pSysConfig->TotalConnectorCount; index++) {
-                            //if (!isPass) {
-                            //    break;
-                            //}
-                            if (chargingInfo[index]->Type == _Type_CCS_2) {
-                                if (Upgrade_CCS(CanFd, Type, chargingInfo[index]->Evboard_id, new_str, (char *)pSysConfig->ModelName) == FAIL) {
-                                    //isPass = false;
-                                    log_info("Upgrade %x Failed", Type);
-                                    retFail++;
-                                }
-                            }
-                        }
-                    } else {
-                        log_error("Upgrade CCS open CAN FD fail.");
-                        //isPass = false;
-                        return FAIL;
-                    }
-
-                    if (retFail != 0) {
-                        break;
-                    } else {
-                        retSucc++;
-                    }
-                    //return isPass;
-#endif //0
-                    break;
-
-                case 0x10000006:
-                case 0x1000000D:
-                case 0x1000000E:
-                case 0x20000002:
-                case 0x10000014:
-                    // CSU_PRIMARY_CONTROLLER : 0x10000006
-                    target = 0x00;
-
-                    if (Type == 0x10000006) {
-                        target = UPGRADE_PRI;
-                    } else if (Type == 0x1000000D) {
-                        target = UPGRADE_RB;
-                    } else if (Type == 0x1000000E) {
-                        target = UPGRADE_FAN;
-                    } else if (Type == 0x20000002) {
-                        target = UPGRADE_AC;
-                    } else if (Type == 0x10000014) {
-                        target = UPGRADE_LED;
-                    }
-
-                    uartFd = InitComPort(target);
-
-                    if (Upgrade_UART(uartFd, Type, target, new_str, (char *)pSysConfig->ModelName) == PASS) {
-                        //return PASS;
-                        retSucc++;
-                    } else {
-                        log_info("Upgrade %x Failed", Type);
-                        //return FAIL;
-                        return FAIL;
-                    }
-
-                    if (uartFd > 0) {
-                        close(uartFd);
-                    }
-                    break;
-
-                case 0x1000000B:
-                case 0x1000000C:
-                    // CHAdeMO_BOARD : 0x1000000B, GBT : 0x1000000C
-                    //bool isPass = true;
-                    CanFd = InitCanBus();
-                    if (CanFd > 0) {
-                        for (index = 0; index < pSysConfig->TotalConnectorCount; index++) {
-                            pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);
-
-                            //if (!isPass) {
-                            //    break;
-                            //}
-
-                            if ((Type == 0x1000000B && pDcChargingInfo->Type == _Type_Chademo) ||
-                                    (Type == 0x1000000C && pDcChargingInfo->Type == _Type_GB)) {
-                                if (Upgrade_CAN(CanFd, Type, pDcChargingInfo->Evboard_id, new_str, (char *)pSysConfig->ModelName) == PASS) {
-                                    //isPass = PASS;
-                                    retSucc++;
-                                } else {
-                                    log_info("Upgrade %x Failed", Type);
-                                    //isPass = FAIL;
-                                    retFail++;
-                                }
-                            }
-                        }
-                    } else {
-                        log_info("Upgrad FD fail. ");
-                        //isPass = false;
-                        return FAIL;
-                    }
-
-                    //return isPass;
-                    break;
-                case 0x1000000F:
-                    // Update LCM
-                    if (CreateBufferForLcmFile(new_str)) {
-                        system("mkdir -p /mnt/lcd");
-                        system("unzip /mnt/BUFFER.zip -d /mnt/lcd");
-                        log_info("Start Upgrade LCM Firmware.");
-                        ShmDcCommonData->_upgrade_lcm_flag = YES;
-                        while(ShmDcCommonData->_upgrade_lcm_result == _LCM_UPGRADE_RESULT_WAIT ) {
-                            sleep(5);
-                        }
-                        if (ShmDcCommonData->_upgrade_lcm_result == _LCM_UPGRADE_RESULT_PASS) {
-                            retSucc++;
-                        } else
-                            retFail++;
-                    } else {
-                        log_info("CreateBufferForLcmFile fail");
-                    }
-                    break;
-                }
-            } else { 
-                free(ptr);
-            }
-
-            free(new_str);
-
-        }
-    }
-    //free(dir);
-    closedir(d);
-
-    if (retFail != 0) {
-        return FAIL;
-    }
-
-    return PASS;
-}
-
-void CheckFwUpdateFunction(void)
-{
-    //log_info("pSysInfo->FirmwareUpdate = %d ", pSysInfo->FirmwareUpdate);
-    if (pSysInfo->FirmwareUpdate == YES) {
-        log_info("ftp : update start. ");
-        TryCloseWatchdog();
-        pSysInfo->SystemPage = _PAGE_MAINTAIN;
-        for (uint8_t gun_index = 0; gun_index < pSysConfig->TotalConnectorCount; gun_index++) {
-            setChargerMode(gun_index, MODE_UPDATE);
-        }
-        sleep(1);
-        uint8_t updateResult = CheckUpdateProcess();
-
-        if (updateResult == PASS) {
-            log_info("ftp : update complete. ");
-        } else if (updateResult == MODELNAME_FAIL) {
-            log_info("ftp : model name is none match. ");
-            KillAllTask();
-            pSysInfo->FirmwareUpdate = NO;
-            sleep(5);
-            system("/usr/bin/run_evse_restart.sh");
-            return;
-        } else {
-            log_info("ftp : update fail. ");
-        }
-
-        pSysInfo->FirmwareUpdate = NO;
-        sleep(5);
-        system("reboot -f");
-    } else if (ShmOCPP16Data->MsMsg.bits.UpdateFirmwareReq == YES) {
-        ShmOCPP16Data->MsMsg.bits.UpdateFirmwareReq = NO;
-
-        if (strcmp((char *)ShmOCPP16Data->FirmwareStatusNotification.Status, "Downloaded") == EQUAL) {
-            log_info("Backend : update start. ");
-            TryCloseWatchdog();
-            strcpy((char *)ShmOCPP16Data->FirmwareStatusNotification.Status, "");
-            strcpy((char *)ShmOCPP16Data->FirmwareStatusNotification.Status, "Installing");
-            ShmOCPP16Data->SpMsg.bits.FirmwareStatusNotificationReq = YES;
-            KillTask();
-
-            for (uint8_t _index = 0; _index < pSysConfig->TotalConnectorCount; _index++) {
-                setChargerMode(_index, MODE_UPDATE);
-            }
-
-            for (uint8_t _index = 0; _index < pSysConfig->AcConnectorCount; _index++) {
-                pAcChargingInfo = (struct ChargingInfoData *)GetAcChargingInfoData(_index);
-
-                pAcChargingInfo->SystemStatus = MODE_UPDATE;
-            }
-            sleep(1);
-
-            uint8_t updateResult = CheckUpdateProcess();
-
-            if (updateResult == PASS) {
-                log_info("Backend : update complete. ");
-                strcpy((char *)ShmOCPP16Data->FirmwareStatusNotification.Status, "Installed");
-            } else if (updateResult == MODELNAME_FAIL) {
-                log_info("Backend : model name is none match. ");
-                KillAllTask();
-                strcpy((char *)ShmOCPP16Data->FirmwareStatusNotification.Status, "InstallationFailed");
-                ShmOCPP16Data->SpMsg.bits.FirmwareStatusNotificationReq = YES;
-                sleep(5);
-                system("/usr/bin/run_evse_restart.sh");
-                return;
-            } else {
-                log_info("Backend : update fail. ");
-                strcpy((char *)ShmOCPP16Data->FirmwareStatusNotification.Status, "InstallationFailed");
-            }
-
-            strcpy((char *)ShmOCPP16Data->FirmwareStatusNotification.Status, "Installed");
-            ShmOCPP16Data->SpMsg.bits.FirmwareStatusNotificationReq = YES;
-            sleep(5);
-            system("reboot -f");
-        }
-    }
-}
-
-int main(int argc, char *argv[])
-{
-    if (CreateAllCsuShareMemory() == FAIL) {
-        log_error("create share memory error");
-        return FAIL;
-    }
-    
-    MappingGunChargingInfo("Upgrade Task");
-
-    pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
-    pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
-    ShmOCPP16Data = (struct OCPP16Data *)GetShmOCPP16Data();
-   
-    ShmDcCommonData = (DcCommonInfo *)GetShmDcCommonData();
-    ShmDcCommonData->_upgrade_lcm_flag = NO;
-    ShmDcCommonData->_upgrade_lcm_result = _LCM_UPGRADE_RESULT_WAIT;
-
-    while (1) {
-        //if (IsConnectorWholeIdle() || (pSysInfo->PageIndex == _PAGE_MAINTAIN) )
-            CheckFwUpdateFunction();
-        sleep(3);
-    } //while
-    return 0;
-}
+#include <stdio.h>      /*標準輸入輸出定義*/
+#include <stdlib.h>     /*標準函數庫定義*/
+#include <string.h>
+#include <stdint.h>
+
+#include <sys/types.h>
+#include <dirent.h>
+
+#include "../Config.h"
+#include "../Log/log.h"
+#include "../Define/define.h"
+
+#include "../ShareMemory/shmMem.h"
+#include "../CSU/main.h"
+#include "../Config.h"
+
+struct SysConfigData *pSysConfig = NULL;
+struct SysInfoData *pSysInfo = NULL;
+struct OCPP16Data *ShmOCPP16Data = NULL;
+struct ChargingInfoData *pAcChargingInfo = NULL;
+static struct ChargingInfoData *pDcChargingInfo = NULL;
+DcCommonInfo *ShmDcCommonData = NULL; 
+#define MODELNAME_FAIL                          (0)
+#define UPGRADE_FAN                             (0x02)
+#if defined DD360Tcci || defined DD360Audi || defined DD360ComBox
+#define UPGRADE_RB                              (0x09) //0x09 for DD360Tcci dispenser
+#else
+#define UPGRADE_RB                              (0x03) //other module use
+#endif //defined DD360Tcci ||defined DD360Audi || defined DD360ComBox
+#define UPGRADE_PRI                             (0x04)
+#define UPGRADE_AC                              (0x05)
+#define UPGRADE_LED                             (0x06)
+
+//------------------------------------------------------------------------------
+static char *_priPortName = "/dev/ttyS1";
+static char *_485PortName = "/dev/ttyS5";
+
+//------------------------------------------------------------------------------
+
+void KillAllTask(void)
+{
+    pSysInfo->PageIndex = _PAGE_MAINTAIN;
+
+    system("killall Module_EventLogging");
+    system("killall Module_PrimaryComm");
+    system("killall Module_EvComm");
+    system("killall Module_LcmControl");
+    system("killall Module_InternalComm");
+
+#if defined DD360Tcci || defined DD360Audi || defined DD360ComBox
+    system("killall Module_DoComm");
+    return ;
+#endif //defined DD360Tcci || defined DD360Audi || defined DD360ComBox
+
+    system("killall Module_PsuComm");
+    system("killall OcppBackend &");
+    system("killall Module_4g &");
+    system("killall Module_Wifi &");
+}
+
+void KillTask(void)
+{
+    pSysInfo->PageIndex = _PAGE_MAINTAIN;
+
+    system("killall Module_EventLogging");
+    system("killall Module_PrimaryComm");
+    system("killall Module_EvComm");
+    system("killall Module_LcmControl");
+    system("killall Module_InternalComm");
+    //system("killall Module_DoComm");
+#if defined DD360Tcci || defined DD360Audi || defined DD360ComBox
+    return ;
+#endif //defined DD360Tcci || defined DD360Audi || defined DD360ComBox
+
+    system("killall Module_PsuComm");
+    system("killall OcppBackend &");
+    system("killall Module_4g &");
+    system("killall Module_Wifi &");
+}
+void setChargerMode(uint8_t gunIndex, uint8_t mode)
+{
+    pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);
+
+    pDcChargingInfo->SystemStatus = mode;
+
+    //log_info(" ====== System Status:%d ======",mode);
+}
+void TryCloseWatchdog()
+{
+    system("echo V > /dev/watchdog");
+}
+static int InitComPort(uint8_t target)
+{
+    int fd;
+    struct termios tios;
+
+    if (target == UPGRADE_PRI) {
+        fd = open(_priPortName, O_RDWR);
+    } else if (target == UPGRADE_FAN ||
+               target == UPGRADE_RB ||
+               target == UPGRADE_AC ||
+               target == UPGRADE_LED
+              ) {
+        fd = open(_485PortName, O_RDWR);
+    }
+
+    if (fd <= 0) {
+        log_error("open 407 Communication port NG ");
+        return -1;
+    }
+
+    ioctl (fd, TCGETS, &tios);
+    tios.c_cflag = B115200 | CS8 | CLOCAL | CREAD;
+    tios.c_lflag = 0;
+    tios.c_iflag = 0;
+    tios.c_oflag = 0;
+    tios.c_cc[VMIN] = 0;
+    tios.c_cc[VTIME] = (uint8_t)1;
+    tios.c_lflag = 0;
+    tcflush(fd, TCIFLUSH);
+    ioctl (fd, TCSETS, &tios);
+
+    return fd;
+}
+bool IsConnectorWholeIdle()
+{
+    bool result = true;
+
+    for (uint8_t count = 0; count < pSysConfig->TotalConnectorCount; count++) {
+        pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(count);
+
+        if (pDcChargingInfo->SystemStatus != S_IDLE &&
+                pDcChargingInfo->SystemStatus != S_RESERVATION) {
+            result = false;
+            break;
+        }
+    }
+
+    for (uint8_t count = 0; count < pSysConfig->AcConnectorCount; count++) {
+        pAcChargingInfo = (struct ChargingInfoData *)GetAcChargingInfoData(count);
+
+        if (pAcChargingInfo->SystemStatus != S_IDLE &&
+                pAcChargingInfo->IsErrorOccur == NO) {
+            result = false;
+            break;
+        }
+    }
+
+    return result;
+}
+
+
+static int InitCanBus(void)
+{
+    int fd = -1;
+    int nbytes;
+    struct timeval tv;
+    struct ifreq ifr0;
+    struct sockaddr_can addr0;
+
+    system("/sbin/ip link set can0 down");
+    system("/sbin/ip link set can0 type can bitrate 500000 restart-ms 100");
+    system("/sbin/ip link set can0 up");
+
+    fd = socket(PF_CAN, SOCK_RAW, CAN_RAW);
+
+    tv.tv_sec = 0;
+    tv.tv_usec = 10000;
+    if (setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(struct  timeval)) < 0) {
+        log_error("Set SO_RCVTIMEO NG");
+    }
+    nbytes = 40960;
+    if (setsockopt(fd, SOL_SOCKET,  SO_RCVBUF, &nbytes, sizeof(int)) < 0) {
+        log_error("Set SO_RCVBUF NG");
+    }
+    nbytes = 40960;
+    if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &nbytes, sizeof(int)) < 0) {
+        log_error("Set SO_SNDBUF NG");
+    }
+
+    strcpy(ifr0.ifr_name, "can0");
+    ioctl(fd, SIOCGIFINDEX, &ifr0); /* ifr.ifr_ifindex gets filled with that device's index */
+    addr0.can_family = AF_CAN;
+    addr0.can_ifindex = ifr0.ifr_ifindex;
+    bind(fd, (struct sockaddr *)&addr0, sizeof(addr0));
+
+    return fd;
+}
+bool CreateBufferForLcmFile(char *file)
+{
+	bool result = FAIL;
+	unsigned char *ptr = NULL;
+	long int MaxLen = 48 * 1024 * 1024, ImageLen = 0;
+	int fd, fd_lcm;
+	int wrd_lcm;
+	char Buf_lcm[256] = "/mnt/BUFFER.zip";
+
+	fd = open ( file, O_RDONLY );
+	if (fd < 0) {
+	    close ( fd );
+	    return result;
+	}
+
+	ptr = malloc(MaxLen);
+	ImageLen = read(fd, ptr, MaxLen);
+
+	fd_lcm = open ( Buf_lcm, O_RDWR | O_CREAT | O_EXCL );
+	if (fd_lcm < 0) {
+    	log_info( "Can not create %s \n", Buf_lcm );
+	} else {
+    	log_info( "Writing data to %s file.... \n", Buf_lcm );
+    	wrd_lcm = write ( fd_lcm, ptr + 48, ImageLen - 48 );
+    	close ( fd_lcm );
+    	log_info( ">> %s Written length : 0x%x \n", Buf_lcm, wrd_lcm );
+
+    	if (wrd_lcm != (ImageLen - 48)) {
+            result = FAIL;
+    	} else {
+        	result = PASS;
+    	}
+
+    	close(fd);
+    	free(ptr);
+	}
+
+	return result;
+}
+
+unsigned long long getAvailableMemory()
+{
+    system("pkill ntpd");
+    sleep(1);
+    long pages = sysconf(_SC_AVPHYS_PAGES);
+    long page_size = sysconf(_SC_PAGE_SIZE);
+    log_info("Avaiable Memory size:%d MB",pages*page_size/(1024*1024));
+    return pages * page_size;
+}
+
+static int CheckUpdateProcess(void)
+{
+    //bool isPass = true;
+    uint8_t retSucc = 0;
+    uint8_t retFail = 0;
+    uint8_t index = 0;
+    uint8_t target = 0;
+    char Buf[256];
+    char *new_str = NULL;
+    uint8_t *ptr = NULL;
+    int fd = 0;
+    int CanFd = 0;
+    int uartFd = 0;
+    unsigned int Type = 0;
+    long int MaxLen = 48 * 1024 * 1024, ImageLen = 0;
+    DIR *d;
+    struct dirent *dir;
+
+    struct ChargingInfoData *pDcChargingInfo = NULL;
+    
+    pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
+
+    if (getAvailableMemory() < (200 * 1024 * 1024))
+    {
+        log_info("Available memory (%.2f Bytes) less than 200 MBytes, free cache first.\n", getAvailableMemory() / (1024 * 1024.0));
+        system("echo 3 > /proc/sys/vm/drop_caches");
+    }
+
+    d = opendir("/mnt/");
+    if (d) {
+        log_info("Open /mnt success");
+        while ((dir = readdir(d)) != NULL) {
+            if (strcmp(dir->d_name, ".") == 0 || strcmp(dir->d_name, "..") == 0) {
+                continue;
+            }
+
+            new_str = calloc(strlen("/mnt/") + strlen(dir->d_name) + 1, sizeof(char));
+            //new_str[0] = '\0';
+            strcat(new_str, "/mnt/");
+            strcat(new_str, dir->d_name);
+            log_info("%s%s", "/mnt/", dir->d_name);
+            
+            fd = open(new_str, O_RDONLY);
+            if (fd < 0) {
+                return FAIL;
+            }
+
+            ptr = calloc(MaxLen, sizeof(char)); //-48 is take out the header
+            //memset(ptr, 0xFF, MaxLen);  //-48 is take out the header
+
+            //get the image length
+            ImageLen = read(fd, ptr, MaxLen);
+            for (uint8_t i = 0; i < 16; i++) {
+                if (pSysConfig->ModelName[i] != ptr[i]) {
+                    log_info("model name check fail. ");
+                    return FAIL;
+                }
+            }
+
+            log_info("model name check pass. ");
+            if (ImageLen > 20) {
+                Type = (((unsigned int)ptr[16]) << 24 |
+                        ((unsigned int)ptr[17]) << 16 |
+                        ((unsigned int)ptr[18]) << 8  |
+                        ((unsigned int)ptr[19]));
+                log_info("Typed...%x ", Type);
+                free(ptr);
+                switch (Type) {
+                case 0x10000001:
+                case 0x10000002:
+                case 0x10000003:
+                case 0x10000004:
+                case 0x10000005:
+                    if (Upgrade_Flash(Type, new_str, (char *)pSysConfig->ModelName) == PASS) {
+                        //return PASS;
+                        retSucc++;
+                    } else {
+                        log_info("Upgrade %x Failed", Type);
+                        //return FAIL;
+                        retFail++;
+                    }
+                    break;
+
+                case 0x10000007:
+                case 0x10000008:
+                case 0x10000009:
+                case 0x1000000A:
+                    CanFd = InitCanBus();
+                    if (CanFd > 0) {
+                        for (index = 0; index < pSysConfig->TotalConnectorCount; index++) {
+                            pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);
+                            if (pDcChargingInfo->Type == _Type_CCS_2) {
+                                uint8_t targetID = pDcChargingInfo->Evboard_id;
+                                /*
+                                if (pSysConfig->TotalConnectorCount == 1 &&
+                                        ShmDcCommonData->CcsVersion == _CCS_VERSION_CHECK_TAG_V015S0) {
+                                    //targetID += 1;
+                                }*/
+
+                                system("echo 3 > /proc/sys/vm/drop_caches");
+                                sleep(2);
+                                log_info("Upgrade CCS Processing..target id = %d ", targetID);
+                                if (Upgrade_CCS(CanFd,
+                                                Type,
+                                                targetID,
+                                                new_str,
+                                                (char *)pSysConfig->ModelName) == FAIL) {
+                                    log_info("Upgrade CCS Failed ");
+                                    retFail++;
+                                } else {
+                                    retSucc++;
+                                }
+                            }
+                        }
+                        close(CanFd);
+                    }
+                    memset(Buf, 0, sizeof(Buf));
+                    sprintf(Buf, "rm -rvf /mnt/%s", new_str);
+                    system(Buf);
+                    //isPass = true;
+#if 0
+                    CanFd = InitCanBus();
+                    if (CanFd > 0) {
+                        for (index = 0; index < pSysConfig->TotalConnectorCount; index++) {
+                            //if (!isPass) {
+                            //    break;
+                            //}
+                            if (chargingInfo[index]->Type == _Type_CCS_2) {
+                                if (Upgrade_CCS(CanFd, Type, chargingInfo[index]->Evboard_id, new_str, (char *)pSysConfig->ModelName) == FAIL) {
+                                    //isPass = false;
+                                    log_info("Upgrade %x Failed", Type);
+                                    retFail++;
+                                }
+                            }
+                        }
+                    } else {
+                        log_error("Upgrade CCS open CAN FD fail.");
+                        //isPass = false;
+                        return FAIL;
+                    }
+
+                    if (retFail != 0) {
+                        break;
+                    } else {
+                        retSucc++;
+                    }
+                    //return isPass;
+#endif //0
+                    break;
+
+                case 0x10000006:
+                case 0x1000000D:
+                case 0x1000000E:
+                case 0x20000002:
+                case 0x10000014:
+                    // CSU_PRIMARY_CONTROLLER : 0x10000006
+                    target = 0x00;
+
+                    if (Type == 0x10000006) {
+                        target = UPGRADE_PRI;
+                    } else if (Type == 0x1000000D) {
+                        target = UPGRADE_RB;
+                    } else if (Type == 0x1000000E) {
+                        target = UPGRADE_FAN;
+                    } else if (Type == 0x20000002) {
+                        target = UPGRADE_AC;
+                    } else if (Type == 0x10000014) {
+                        target = UPGRADE_LED;
+                    }
+
+                    uartFd = InitComPort(target);
+
+                    if (Upgrade_UART(uartFd, Type, target, new_str, (char *)pSysConfig->ModelName) == PASS) {
+                        //return PASS;
+                        retSucc++;
+                    } else {
+                        log_info("Upgrade %x Failed", Type);
+                        //return FAIL;
+                        return FAIL;
+                    }
+
+                    if (uartFd > 0) {
+                        close(uartFd);
+                    }
+                    break;
+
+                case 0x1000000B:
+                case 0x1000000C:
+                    // CHAdeMO_BOARD : 0x1000000B, GBT : 0x1000000C
+                    //bool isPass = true;
+                    CanFd = InitCanBus();
+                    if (CanFd > 0) {
+                        for (index = 0; index < pSysConfig->TotalConnectorCount; index++) {
+                            pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);
+
+                            //if (!isPass) {
+                            //    break;
+                            //}
+
+                            if ((Type == 0x1000000B && pDcChargingInfo->Type == _Type_Chademo) ||
+                                    (Type == 0x1000000C && pDcChargingInfo->Type == _Type_GB)) {
+                                if (Upgrade_CAN(CanFd, Type, pDcChargingInfo->Evboard_id, new_str, (char *)pSysConfig->ModelName) == PASS) {
+                                    //isPass = PASS;
+                                    retSucc++;
+                                } else {
+                                    log_info("Upgrade %x Failed", Type);
+                                    //isPass = FAIL;
+                                    retFail++;
+                                }
+                            }
+                        }
+                    } else {
+                        log_info("Upgrad FD fail. ");
+                        //isPass = false;
+                        return FAIL;
+                    }
+
+                    //return isPass;
+                    break;
+                case 0x1000000F:
+                    // Update LCM
+                    if (CreateBufferForLcmFile(new_str)) {
+                        system("mkdir -p /mnt/lcd");
+                        system("unzip /mnt/BUFFER.zip -d /mnt/lcd");
+                        log_info("Start Upgrade LCM Firmware.");
+                        ShmDcCommonData->_upgrade_lcm_flag = YES;
+                        while(ShmDcCommonData->_upgrade_lcm_result == _LCM_UPGRADE_RESULT_WAIT ) {
+                            sleep(5);
+                        }
+                        if (ShmDcCommonData->_upgrade_lcm_result == _LCM_UPGRADE_RESULT_PASS) {
+                            retSucc++;
+                        } else
+                            retFail++;
+                    } else {
+                        log_info("CreateBufferForLcmFile fail");
+                    }
+                    break;
+                }
+            } else { 
+                free(ptr);
+            }
+
+            free(new_str);
+
+        }
+    }
+    //free(dir);
+    closedir(d);
+
+    if (retFail != 0) {
+        return FAIL;
+    }
+
+    return PASS;
+}
+
+void CheckFwUpdateFunction(void)
+{
+    //log_info("pSysInfo->FirmwareUpdate = %d ", pSysInfo->FirmwareUpdate);
+    if (pSysInfo->FirmwareUpdate == YES) {
+        log_info("ftp : update start. ");
+        TryCloseWatchdog();
+        pSysInfo->SystemPage = _PAGE_MAINTAIN;
+        for (uint8_t gun_index = 0; gun_index < pSysConfig->TotalConnectorCount; gun_index++) {
+            setChargerMode(gun_index, MODE_UPDATE);
+        }
+        sleep(1);
+        uint8_t updateResult = CheckUpdateProcess();
+
+        if (updateResult == PASS) {
+            log_info("ftp : update complete. ");
+        } else if (updateResult == MODELNAME_FAIL) {
+            log_info("ftp : model name is none match. ");
+            KillAllTask();
+            pSysInfo->FirmwareUpdate = NO;
+            sleep(5);
+            system("/usr/bin/run_evse_restart.sh");
+            return;
+        } else {
+            log_info("ftp : update fail. ");
+        }
+
+        pSysInfo->FirmwareUpdate = NO;
+        sleep(5);
+        system("reboot -f");
+    } else if (ShmOCPP16Data->MsMsg.bits.UpdateFirmwareReq == YES) {
+        ShmOCPP16Data->MsMsg.bits.UpdateFirmwareReq = NO;
+
+        if (strcmp((char *)ShmOCPP16Data->FirmwareStatusNotification.Status, "Downloaded") == EQUAL) {
+            log_info("Backend : update start. ");
+            TryCloseWatchdog();
+            strcpy((char *)ShmOCPP16Data->FirmwareStatusNotification.Status, "");
+            strcpy((char *)ShmOCPP16Data->FirmwareStatusNotification.Status, "Installing");
+            ShmOCPP16Data->SpMsg.bits.FirmwareStatusNotificationReq = YES;
+            KillTask();
+
+            for (uint8_t _index = 0; _index < pSysConfig->TotalConnectorCount; _index++) {
+                setChargerMode(_index, MODE_UPDATE);
+            }
+
+            for (uint8_t _index = 0; _index < pSysConfig->AcConnectorCount; _index++) {
+                pAcChargingInfo = (struct ChargingInfoData *)GetAcChargingInfoData(_index);
+
+                pAcChargingInfo->SystemStatus = MODE_UPDATE;
+            }
+            sleep(1);
+
+            uint8_t updateResult = CheckUpdateProcess();
+
+            if (updateResult == PASS) {
+                log_info("Backend : update complete. ");
+                strcpy((char *)ShmOCPP16Data->FirmwareStatusNotification.Status, "Installed");
+            } else if (updateResult == MODELNAME_FAIL) {
+                log_info("Backend : model name is none match. ");
+                KillAllTask();
+                strcpy((char *)ShmOCPP16Data->FirmwareStatusNotification.Status, "InstallationFailed");
+                ShmOCPP16Data->SpMsg.bits.FirmwareStatusNotificationReq = YES;
+                sleep(5);
+                system("/usr/bin/run_evse_restart.sh");
+                return;
+            } else {
+                log_info("Backend : update fail. ");
+                strcpy((char *)ShmOCPP16Data->FirmwareStatusNotification.Status, "InstallationFailed");
+            }
+
+            strcpy((char *)ShmOCPP16Data->FirmwareStatusNotification.Status, "Installed");
+            ShmOCPP16Data->SpMsg.bits.FirmwareStatusNotificationReq = YES;
+            sleep(5);
+            system("reboot -f");
+        }
+    }
+}
+
+int main(int argc, char *argv[])
+{
+    if (CreateAllCsuShareMemory() == FAIL) {
+        log_error("create share memory error");
+        return FAIL;
+    }
+    
+    MappingGunChargingInfo("Upgrade Task");
+
+    pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
+    pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
+    ShmOCPP16Data = (struct OCPP16Data *)GetShmOCPP16Data();
+   
+    ShmDcCommonData = (DcCommonInfo *)GetShmDcCommonData();
+    ShmDcCommonData->_upgrade_lcm_flag = NO;
+    ShmDcCommonData->_upgrade_lcm_result = _LCM_UPGRADE_RESULT_WAIT;
+
+    while (1) {
+        //if (IsConnectorWholeIdle() || (pSysInfo->PageIndex == _PAGE_MAINTAIN) )
+            CheckFwUpdateFunction();
+        sleep(3);
+    } //while
+    return 0;
+}

+ 10 - 10
EVSE/Projects/DD360Tcci/Apps/Readme.md

@@ -1,10 +1,10 @@
-## merge master
-    1. merge master,fixed conflict完成。
-    2. 執行DD360Audi/Apps/Script/createDefine.sh
-    3. compiler 確認沒有問題。
-    4. 執行DD360Audi/Apps/Script/replaceOtherDD360Project.sh
-    5. 重新commit。
-
-## 更換DD360 和 DD360ComBox project
-    DD360Tcci 和 DD360ComBox 都是用DD360Audi開發和修改,完成後,執行
-    DD360Audi/Apps/Script/replaceOtherDD360Project.sh
+## merge master
+    1. merge master,fixed conflict完成。
+    2. 執行DD360Audi/Apps/Script/createDefine.sh
+    3. compiler 確認沒有問題。
+    4. 執行DD360Audi/Apps/Script/replaceOtherDD360Project.sh
+    5. 重新commit。
+
+## 更換DD360 和 DD360ComBox project
+    DD360Tcci 和 DD360ComBox 都是用DD360Audi開發和修改,完成後,執行
+    DD360Audi/Apps/Script/replaceOtherDD360Project.sh

+ 10 - 10
EVSE/Projects/DD360Tcci/Apps/Script/SearchIP.sh

@@ -1,10 +1,10 @@
-#!/bin/bash
-# 用 arping 來 ping 區域網路中所有的 IP 位址
-echo $0;
-
-for ip in "$1".{1..254}; do
-  arping -I "$0" -w 3 -f $ip | grep reply &;
-done
-
-# 等待所有背景的 arping 結束
-wait;
+#!/bin/bash
+# 用 arping 來 ping 區域網路中所有的 IP 位址
+echo $0;
+
+for ip in "$1".{1..254}; do
+  arping -I "$0" -w 3 -f $ip | grep reply &;
+done
+
+# 等待所有背景的 arping 結束
+wait;

+ 2 - 2
EVSE/Projects/DD360Tcci/Apps/Script/copy_from_d.sh

@@ -1,2 +1,2 @@
-#!/bin/bash
-sudo cp -r /mnt/d/Phihong/Project/DD360Tcci/Apps/* /opt/ti-processor-sdk-linux-am335x-evm-04.02.00.09/EVSE/Projects/DD360Tcci/Apps/ 
+#!/bin/bash
+sudo cp -r /mnt/d/Phihong/Project/DD360Tcci/Apps/* /opt/ti-processor-sdk-linux-am335x-evm-04.02.00.09/EVSE/Projects/DD360Tcci/Apps/ 

+ 2 - 2
EVSE/Projects/DD360Tcci/Apps/Script/copy_to_d.sh

@@ -1,2 +1,2 @@
-#!/bin/bash
-sudo cp -r /opt/ti-processor-sdk-linux-am335x-evm-04.02.00.09/EVSE/Projects/DD360Tcci/Apps/* /mnt/d/Phihong/Project/DD360Tcci/Apps/
+#!/bin/bash
+sudo cp -r /opt/ti-processor-sdk-linux-am335x-evm-04.02.00.09/EVSE/Projects/DD360Tcci/Apps/* /mnt/d/Phihong/Project/DD360Tcci/Apps/

+ 187 - 187
EVSE/Projects/DD360Tcci/Apps/Script/createDefine.sh

@@ -1,187 +1,187 @@
-#/bin/bash
-ProjectPath="/opt/ti-processor-sdk-linux-am335x-evm-04.02.00.09"
-defineFilePath="$ProjectPath/EVSE/Projects/define.h"
-workPath="$ProjectPath/EVSE/Projects/DD360Audi/Apps/Define"
-filename="$workPath/define.h";
-copyFile="$workPath/define.c"
-frontKey="/*";
-afterKey="*/";
-
-Currency="char Currency\[54\]\[3\]"
-
-FaultCode="char FaultStatusCode\[40\]\[6\]";
-
-AlarmCode="char AlarmStatusCode\[128\]\[6\]";
-
-InfoCode="char InfoStatusCode\[384\]\[6\]";
-
-finalString="#endif // DEFINE_H_";
-
-count=512;
-
-rm -rf $workPath/define.h;
-rm -rf $workPath/define.c;
-cp -r $defineFilePath $workPath;
-
-# Currency String
-line=$(grep -n "$Currency" $filename | cut -d ":" -f 1);
-echo $line;
-
-line_n=$(sed -n "$(($line-1))"p $filename);
-if [ "$line_n" != "/*" ]
-then
-rm -rf define.c
-echo "#include <stdio.h>
-#include <stdlib.h>
-#include <stdint.h>
-
-#include \"define.h\"
-
-//------------------------------------------------------------------------------" >> $copyFile
-
-addKey=$line"i $frontKey"
-sed -i "$addKey" $filename
-
-line=$(grep -n "$Currency" $filename | cut -d ":" -f 1);
-while [ $line -le $(($line+$count)) ]
-do
-line_n=$(sed -n "$line"p $filename);
-#echo $line_n
-if [ "$line_n" == "};" ]
-then
-    echo $line_n >> $copyFile;
-    echo -e >> $copyFile;
-    line=$line"a $afterKey";
-    sed -i "$line" $filename;
-    break;
-else
-    line=$(($line+1));
-    echo $line_n >> $copyFile;
-fi
-done
-fi
-
-#fault Status code
-line=$(grep -n "$FaultCode" $filename | cut -d ":" -f 1);
-echo $line;
-
-line_n=$(sed -n "$(($line-1))"p $filename);
-if [ "$line_n" != "/*" ]
-then
-addKey=$line"i $frontKey"
-sed -i "$addKey" $filename
-
-line=$(grep -n "$FaultCode" $filename | cut -d ":" -f 1);
-while [ $line -le $(($line+$count)) ]
-do
-line_n=$(sed -n "$line"p $filename);
-#echo $line_n
-if [ "$line_n" == "};" ]
-then
-    echo $line_n >> $copyFile;
-    echo -e >> $copyFile;
-    line=$line"a $afterKey";
-    sed -i "$line" $filename;
-    break;
-else
-    line=$(($line+1));
-    echo $line_n >> $copyFile;
-fi
-done
-fi
-
-#Alarm Status Code
-line=$(grep -n "$AlarmCode" $filename | cut -d ":" -f 1);
-echo $line;
-
-line_n=$(sed -n "$(($line-1))"p $filename);
-if [ "$line_n" != "/*" ]
-then
-addKey=$line"i $frontKey";
-sed -i "$addKey" $filename;
-
-line=$(grep -n "$AlarmCode" $filename | cut -d ":" -f 1);
-while [ $line -le $(($line+$count)) ]
-do
-line_n=$(sed -n "$line"p $filename);
-#echo $line_n
-if [ "$line_n" == "};" ]
-then
-    echo $line_n >> $copyFile;
-    echo -e >> $copyFile;
-    line=$line"a $afterKey";
-    sed -i "$line" $filename;
-    break;
-else
-    line=$(($line+1));
-    echo $line_n >> $copyFile;
-fi
-done
-fi
-
-#Info Status Code
-line=$(grep -n "$InfoCode" $filename | cut -d ":" -f 1);
-echo $line;
-
-line_n=$(sed -n "$(($line-1))"p $filename);
-if [ "$line_n" != "/*" ]
-then
-addKey=$line"i $frontKey"
-sed -i "$addKey" $filename
-
-line=$(grep -n "$InfoCode" $filename | cut -d ":" -f 1);
-while [ $line -le $(($line+$count)) ]
-do
-line_n=$(sed -n "$line"p $filename);
-#echo $line_n
-if [ "$line_n" == "};" ]
-then
-    echo $line_n >> $copyFile;
-    echo -e >> $copyFile;
-    line=$line"a $afterKey";
-    sed -i "$line" $filename;
-    break;
-else
-    line=$(($line+1));
-    echo $line_n >> $copyFile;
-fi
-done
-echo "
-//------------------------------------------------------------------------------
-char *GetCurrency(uint8_t index)
-{
-    return &Currency[index][0];
-}
-
-char *GetFaultStatusCode(uint8_t index)
-{
-    return &FaultStatusCode[index][0];
-}
-
-char *GetAlarmStatusCode(uint8_t index)
-{
-    return &AlarmStatusCode[index][0];
-}
-
-char *GetInfoStatusCode(uint16_t index)
-{
-    return &InfoStatusCode[index][0];
-}" >> $copyFile;
-fi
-
-line=$(grep -n "$finalString" $filename | cut -d ":" -f 1);
-echo $line;
-
-line_n=$(sed -n "$(($line-1))"p $filename);
-if [ "$line_n" != "char *GetInfoCode(uint16_t index);" ]
-then
-sed -i "$line"d $filename
-
-echo "
-//------------------------------------------------------------------------------
-char *GetCurrency(uint8_t index);
-char *GetFaultStatusCode(uint8_t index);
-char *GetAlarmStatusCode(uint8_t index);
-char *GetInfoStatusCode(uint16_t index);
-#endif // DEFINE_H_" >> $filename;
-fi
+#/bin/bash
+ProjectPath="/opt/ti-processor-sdk-linux-am335x-evm-04.02.00.09"
+defineFilePath="$ProjectPath/EVSE/Projects/define.h"
+workPath="$ProjectPath/EVSE/Projects/DD360Audi/Apps/Define"
+filename="$workPath/define.h";
+copyFile="$workPath/define.c"
+frontKey="/*";
+afterKey="*/";
+
+Currency="char Currency\[54\]\[3\]"
+
+FaultCode="char FaultStatusCode\[40\]\[6\]";
+
+AlarmCode="char AlarmStatusCode\[128\]\[6\]";
+
+InfoCode="char InfoStatusCode\[384\]\[6\]";
+
+finalString="#endif // DEFINE_H_";
+
+count=512;
+
+rm -rf $workPath/define.h;
+rm -rf $workPath/define.c;
+cp -r $defineFilePath $workPath;
+
+# Currency String
+line=$(grep -n "$Currency" $filename | cut -d ":" -f 1);
+echo $line;
+
+line_n=$(sed -n "$(($line-1))"p $filename);
+if [ "$line_n" != "/*" ]
+then
+rm -rf define.c
+echo "#include <stdio.h>
+#include <stdlib.h>
+#include <stdint.h>
+
+#include \"define.h\"
+
+//------------------------------------------------------------------------------" >> $copyFile
+
+addKey=$line"i $frontKey"
+sed -i "$addKey" $filename
+
+line=$(grep -n "$Currency" $filename | cut -d ":" -f 1);
+while [ $line -le $(($line+$count)) ]
+do
+line_n=$(sed -n "$line"p $filename);
+#echo $line_n
+if [ "$line_n" == "};" ]
+then
+    echo $line_n >> $copyFile;
+    echo -e >> $copyFile;
+    line=$line"a $afterKey";
+    sed -i "$line" $filename;
+    break;
+else
+    line=$(($line+1));
+    echo $line_n >> $copyFile;
+fi
+done
+fi
+
+#fault Status code
+line=$(grep -n "$FaultCode" $filename | cut -d ":" -f 1);
+echo $line;
+
+line_n=$(sed -n "$(($line-1))"p $filename);
+if [ "$line_n" != "/*" ]
+then
+addKey=$line"i $frontKey"
+sed -i "$addKey" $filename
+
+line=$(grep -n "$FaultCode" $filename | cut -d ":" -f 1);
+while [ $line -le $(($line+$count)) ]
+do
+line_n=$(sed -n "$line"p $filename);
+#echo $line_n
+if [ "$line_n" == "};" ]
+then
+    echo $line_n >> $copyFile;
+    echo -e >> $copyFile;
+    line=$line"a $afterKey";
+    sed -i "$line" $filename;
+    break;
+else
+    line=$(($line+1));
+    echo $line_n >> $copyFile;
+fi
+done
+fi
+
+#Alarm Status Code
+line=$(grep -n "$AlarmCode" $filename | cut -d ":" -f 1);
+echo $line;
+
+line_n=$(sed -n "$(($line-1))"p $filename);
+if [ "$line_n" != "/*" ]
+then
+addKey=$line"i $frontKey";
+sed -i "$addKey" $filename;
+
+line=$(grep -n "$AlarmCode" $filename | cut -d ":" -f 1);
+while [ $line -le $(($line+$count)) ]
+do
+line_n=$(sed -n "$line"p $filename);
+#echo $line_n
+if [ "$line_n" == "};" ]
+then
+    echo $line_n >> $copyFile;
+    echo -e >> $copyFile;
+    line=$line"a $afterKey";
+    sed -i "$line" $filename;
+    break;
+else
+    line=$(($line+1));
+    echo $line_n >> $copyFile;
+fi
+done
+fi
+
+#Info Status Code
+line=$(grep -n "$InfoCode" $filename | cut -d ":" -f 1);
+echo $line;
+
+line_n=$(sed -n "$(($line-1))"p $filename);
+if [ "$line_n" != "/*" ]
+then
+addKey=$line"i $frontKey"
+sed -i "$addKey" $filename
+
+line=$(grep -n "$InfoCode" $filename | cut -d ":" -f 1);
+while [ $line -le $(($line+$count)) ]
+do
+line_n=$(sed -n "$line"p $filename);
+#echo $line_n
+if [ "$line_n" == "};" ]
+then
+    echo $line_n >> $copyFile;
+    echo -e >> $copyFile;
+    line=$line"a $afterKey";
+    sed -i "$line" $filename;
+    break;
+else
+    line=$(($line+1));
+    echo $line_n >> $copyFile;
+fi
+done
+echo "
+//------------------------------------------------------------------------------
+char *GetCurrency(uint8_t index)
+{
+    return &Currency[index][0];
+}
+
+char *GetFaultStatusCode(uint8_t index)
+{
+    return &FaultStatusCode[index][0];
+}
+
+char *GetAlarmStatusCode(uint8_t index)
+{
+    return &AlarmStatusCode[index][0];
+}
+
+char *GetInfoStatusCode(uint16_t index)
+{
+    return &InfoStatusCode[index][0];
+}" >> $copyFile;
+fi
+
+line=$(grep -n "$finalString" $filename | cut -d ":" -f 1);
+echo $line;
+
+line_n=$(sed -n "$(($line-1))"p $filename);
+if [ "$line_n" != "char *GetInfoCode(uint16_t index);" ]
+then
+sed -i "$line"d $filename
+
+echo "
+//------------------------------------------------------------------------------
+char *GetCurrency(uint8_t index);
+char *GetFaultStatusCode(uint8_t index);
+char *GetAlarmStatusCode(uint8_t index);
+char *GetInfoStatusCode(uint16_t index);
+#endif // DEFINE_H_" >> $filename;
+fi

+ 15 - 15
EVSE/Projects/DD360Tcci/Apps/Script/init.sh

@@ -1,15 +1,15 @@
-chmod 777 Module_CSU
-chmod 777 Module_PrimaryComm
-chmod 777 Module_LcmControl
-chmod 777 Module_InternalComm
-chmod 777 Module_EventLogging
-chmod 777 Module_EvComm
-chmod 777 Module_PsuComm
-chmod 777 Module_UpdateFW
-chmod 777 Module_ChkSysTask
-chmod 777 OcppBackend
-chmod 777 kill.sh
-chmod 777 ReadCmdline
-chmod 777 Module_DoComm
-chmod 777 SearchIP.sh
-chmod 777 FactoryConfig
+chmod 777 Module_CSU
+chmod 777 Module_PrimaryComm
+chmod 777 Module_LcmControl
+chmod 777 Module_InternalComm
+chmod 777 Module_EventLogging
+chmod 777 Module_EvComm
+chmod 777 Module_PsuComm
+chmod 777 Module_UpdateFW
+chmod 777 Module_ChkSysTask
+chmod 777 OcppBackend
+chmod 777 kill.sh
+chmod 777 ReadCmdline
+chmod 777 Module_DoComm
+chmod 777 SearchIP.sh
+chmod 777 FactoryConfig

+ 47 - 47
EVSE/Projects/DD360Tcci/Apps/Script/kill.sh

@@ -1,47 +1,47 @@
-pkill Module_CSU;
-pkill Module_PrimaryComm;
-pkill Module_LcmControl;
-pkill Module_InternalComm;
-pkill Module_EventLogging;
-pkill Module_EvComm;
-pkill Module_PsuComm;
-pkill Module_UpdateFW;
-pkill Module_ChkSysTask;
-pkill Module_4g;
-pkill Module_Wifi;
-pkill OcppBackend;
-pkill Module_ProduceUtils;
-pkill Module_DoComm;
-pkill main;
-
-/usr/bin/fuser -k /dev/watchdog
-sleep 1
-
-echo V > /dev/watchdog
-
-ipcrm -M 0x000003e9;
-ipcrm -M 0x000003ed;
-ipcrm -M 0x000003ea;
-ipcrm -M 0x000003ec;
-ipcrm -M 0x000003ee;
-ipcrm -M 0x000003ef;
-ipcrm -M 0x000003f0;
-ipcrm -M 0x000003f3;
-ipcrm -M 0x000003f1;
-ipcrm -M 0x000003f6;
-
-ipcrm -M 0x000003e9;
-ipcrm -M 0x000003ed;
-ipcrm -M 0x000003ea;
-ipcrm -M 0x000003ec;
-ipcrm -M 0x000003ee;
-ipcrm -M 0x000003ef;
-ipcrm -M 0x000003f0;
-ipcrm -M 0x000003f3;
-ipcrm -M 0x000003f1;
-ipcrm -M 0x000003f6;
-ipcrm -M 0x000003eb;
-ipcrm -M 0x000003f2;
-ipcrm -M 0x000007d2;
-
-ipcs;
+pkill Module_CSU;
+pkill Module_PrimaryComm;
+pkill Module_LcmControl;
+pkill Module_InternalComm;
+pkill Module_EventLogging;
+pkill Module_EvComm;
+pkill Module_PsuComm;
+pkill Module_UpdateFW;
+pkill Module_ChkSysTask;
+pkill Module_4g;
+pkill Module_Wifi;
+pkill OcppBackend;
+pkill Module_ProduceUtils;
+pkill Module_DoComm;
+pkill main;
+
+/usr/bin/fuser -k /dev/watchdog
+sleep 1
+
+echo V > /dev/watchdog
+
+ipcrm -M 0x000003e9;
+ipcrm -M 0x000003ed;
+ipcrm -M 0x000003ea;
+ipcrm -M 0x000003ec;
+ipcrm -M 0x000003ee;
+ipcrm -M 0x000003ef;
+ipcrm -M 0x000003f0;
+ipcrm -M 0x000003f3;
+ipcrm -M 0x000003f1;
+ipcrm -M 0x000003f6;
+
+ipcrm -M 0x000003e9;
+ipcrm -M 0x000003ed;
+ipcrm -M 0x000003ea;
+ipcrm -M 0x000003ec;
+ipcrm -M 0x000003ee;
+ipcrm -M 0x000003ef;
+ipcrm -M 0x000003f0;
+ipcrm -M 0x000003f3;
+ipcrm -M 0x000003f1;
+ipcrm -M 0x000003f6;
+ipcrm -M 0x000003eb;
+ipcrm -M 0x000003f2;
+ipcrm -M 0x000007d2;
+
+ipcs;

+ 23 - 23
EVSE/Projects/DD360Tcci/Apps/Script/replaceOtherDD360Project.sh

@@ -1,23 +1,23 @@
-#/bin/bash
-
-# Absolute path to this script, e.g. /home/user/bin/foo.sh
-SCRIPT=$(readlink -f "$0")
-
-# Absolute path this script is in, thus /home/user/bin
-SCRIPTPATH=$(dirname "$SCRIPT")
-echo $SCRIPTPATH
-
-ProjectPath="/opt/ti-processor-sdk-linux-am335x-evm-04.02.00.09/EVSE/Projects"
-
-rm -rf $ProjectPath/DD360Tcci/Apps/;
-cp -r $ProjectPath/DD360Audi/Apps/ $ProjectPath/DD360Tcci/Apps;
-cp -r $ProjectPath/DD360Audi/ModelNameList.txt  $ProjectPath/DD360Tcci/ModelNameList.txt;
-
-rm -rf $ProjectPath/DD360ComBox/Apps/;
-cp -r $ProjectPath/DD360Audi/Apps/ $ProjectPath/DD360ComBox/Apps;
-cp -r $ProjectPath/DD360Audi/ModelNameList.txt $ProjectPath/DD360ComBox/ModelNameList.txt;
-
-# git add $ProjectPath/DD360Tcci;
-# git add $ProjectPath/DD360Audi;
-# git add $ProjectPath/DD360ComBox;
-# git status;
+#/bin/bash
+
+# Absolute path to this script, e.g. /home/user/bin/foo.sh
+SCRIPT=$(readlink -f "$0")
+
+# Absolute path this script is in, thus /home/user/bin
+SCRIPTPATH=$(dirname "$SCRIPT")
+echo $SCRIPTPATH
+
+ProjectPath="/opt/ti-processor-sdk-linux-am335x-evm-04.02.00.09/EVSE/Projects"
+
+rm -rf $ProjectPath/DD360Tcci/Apps/;
+cp -r $ProjectPath/DD360Audi/Apps/ $ProjectPath/DD360Tcci/Apps;
+cp -r $ProjectPath/DD360Audi/ModelNameList.txt  $ProjectPath/DD360Tcci/ModelNameList.txt;
+
+rm -rf $ProjectPath/DD360ComBox/Apps/;
+cp -r $ProjectPath/DD360Audi/Apps/ $ProjectPath/DD360ComBox/Apps;
+cp -r $ProjectPath/DD360Audi/ModelNameList.txt $ProjectPath/DD360ComBox/ModelNameList.txt;
+
+# git add $ProjectPath/DD360Tcci;
+# git add $ProjectPath/DD360Audi;
+# git add $ProjectPath/DD360ComBox;
+# git status;

+ 194 - 194
EVSE/Projects/DD360Tcci/Apps/SelectGun/SelectGun.c

@@ -1,194 +1,194 @@
-#if 0
-#include <stdio.h>      /*標準輸入輸出定義*/
-#include <stdlib.h>     /*標準函數庫定義*/
-#include <string.h>
-#include <stdint.h>
-
-#include "../Config.h"
-#include "../Log/log.h"
-#include "../Define/define.h"
-#include "../ShareMemory/shmMem.h"
-#include "../timeout.h"
-#include "../CSU/main.h"
-
-#include "SelectGun.h"
-
-//------------------------------------------------------------------------------
-int WaitAuthorPageState(void)
-{
-    int ret = FAIL;
-    struct SysInfoData *pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
-
-#if !defined DD360Audi
-    return PASS;
-#endif //!defined DD360Audi
-
-    if (pSysInfo->SystemPage != _LCM_AUTHORIZING &&
-            pSysInfo->SystemPage != _LCM_AUTHORIZ_COMP &&
-            pSysInfo->SystemPage != _LCM_AUTHORIZ_FAIL) {
-        ret = PASS;
-    }
-
-    return ret;
-}
-
-void destroySelGun(uint8_t curGun)
-{
-    uint8_t i = 0;
-
-#if !defined DD360Audi
-    return;
-#endif //!defined DD360Audi
-
-    struct SysConfigData *pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
-    struct SysInfoData *pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
-    SelectGunInfo *pSelectGunInfo = (SelectGunInfo *)GetShmSelectGunInfo(); //Jerry add
-    struct OCPP16Data *ShmOCPP16Data = (struct OCPP16Data *)GetShmOCPP16Data();
-
-    //for status timeout
-    if (curGun == DESTROY_ALL_SEL) {
-        pSelectGunInfo->SelGunInfo.RightGun = SEL_GUN_RELEASE;
-        pSelectGunInfo->SelGunInfo.LeftGun = SEL_GUN_RELEASE;
-        log_info("destroy all gun = %d, %d",
-                 pSelectGunInfo->SelGunInfo.LeftGun,
-                 pSelectGunInfo->SelGunInfo.RightGun);
-        for (i = 0; i < pSysConfig->TotalConnectorCount; i++) {
-            StopGunInfoTimeoutDet(i);
-            memset(&pSelectGunInfo->PricesInfo[i], 0, sizeof(PricesInfo));
-        }
-        pSysInfo->CurGunSelected = 0;
-        strcpy((char *)pSysConfig->UserId, "");
-        //changeLcmPage(_LCM_SELECT_GUN);
-        return;
-    }
-
-    //for charging timeout or complete
-    if ((curGun == LEFT_GUN_NUM) && (pSelectGunInfo->SelGunInfo.LeftGun != SEL_GUN_RELEASE)) {
-        if (pSelectGunInfo->SelGunInfo.LeftGun == SEL_GUN_CONFIRM ||
-                pSelectGunInfo->SelGunInfo.LeftGun == SEL_GUN_ATHOR) {
-            pSysInfo->SystemPage = _LCM_SELECT_GUN;
-        }
-        pSelectGunInfo->SelGunInfo.LeftGun = SEL_GUN_RELEASE;
-        StopGunInfoTimeoutDet(LEFT_GUN_NUM);
-        if (ShmOCPP16Data->SpMsg.bits.AuthorizeConf != NO) {
-            ClearAuthorizedFlag();
-        }
-
-        log_info("destroy left gun, cur page = %d", pSysInfo->SystemPage);
-        //if (pSysInfo->SystemPage == pSysInfo->SystemPage) {
-        log_info("clear left balance");
-        memset(&pSelectGunInfo->PricesInfo[curGun], 0, sizeof(PricesInfo));
-        pSelectGunInfo->PricesInfo[curGun].Balance = FAIL_BALANCE_PRICES;
-        //}
-    }
-
-    if ((curGun == RIGHT_GUN_NUM) && (pSelectGunInfo->SelGunInfo.RightGun != SEL_GUN_RELEASE)) {
-        if (pSelectGunInfo->SelGunInfo.RightGun == SEL_GUN_CONFIRM ||
-                pSelectGunInfo->SelGunInfo.RightGun == SEL_GUN_ATHOR) {
-            pSysInfo->SystemPage = _LCM_SELECT_GUN;
-        }
-        pSelectGunInfo->SelGunInfo.RightGun = SEL_GUN_RELEASE;
-        StopGunInfoTimeoutDet(RIGHT_GUN_NUM);
-        if (ShmOCPP16Data->SpMsg.bits.AuthorizeConf != NO) {
-            ClearAuthorizedFlag();
-        }
-
-        log_info("destroy right gun, cur page = %d", pSysInfo->SystemPage);
-        //if (pSysInfo->SystemPage == pSysInfo->SystemPage) {
-        log_info("clear right balance");
-        memset(&pSelectGunInfo->PricesInfo[curGun], 0, sizeof(PricesInfo));
-        pSelectGunInfo->PricesInfo[curGun].Balance = FAIL_BALANCE_PRICES;
-        //}
-    }
-}
-
-int waitRightGunPlugIt(uint8_t curGun)
-{
-#if !defined DD360Audi
-    return;
-#endif //!defined DD360Audi
-
-    SelectGunInfo *pSelectGunInfo = (SelectGunInfo *)GetShmSelectGunInfo(); //Jerry add
-
-
-    if ((curGun == RIGHT_GUN_NUM) && (pSelectGunInfo->SelGunInfo.RightGun == SEL_GUN_ATHOR)) {
-        return PASS;
-    }
-
-    return FAIL;
-}
-
-int waitLeftGunPlugIt(uint8_t curGun)
-{
-#if !defined DD360Audi
-    return;
-#endif //!defined DD360Audi
-
-    SelectGunInfo *pSelectGunInfo = (SelectGunInfo *)GetShmSelectGunInfo(); //Jerry add
-
-    if ((curGun == LEFT_GUN_NUM) && (pSelectGunInfo->SelGunInfo.LeftGun == SEL_GUN_ATHOR)) {
-        return PASS;
-    }
-
-    return FAIL;
-}
-
-void setSelGunWaitToAuthor(uint8_t curSel)
-{
-#if !defined DD360Audi
-    return;
-#endif //!defined DD360Audi
-
-    SelectGunInfo *pSelectGunInfo = (SelectGunInfo *)GetShmSelectGunInfo(); //Jerry add
-
-    if (curSel == LEFT_GUN_NUM && pSelectGunInfo->SelGunInfo.LeftGun == SEL_GUN_CONFIRM) {
-        pSelectGunInfo->SelGunInfo.LeftGun = SEL_GUN_ATHOR;
-        //printf("setSelGunWaitToAuthor left");
-        StopGunInfoTimeoutDet(curSel);
-    } else if (curSel == RIGHT_GUN_NUM && pSelectGunInfo->SelGunInfo.RightGun == SEL_GUN_CONFIRM) {
-        pSelectGunInfo->SelGunInfo.RightGun = SEL_GUN_ATHOR;
-        //printf("setSelGunWaitToAuthor right");
-        StopGunInfoTimeoutDet(curSel);
-    }
-}
-
-int getConfirmSelectedGun(uint8_t curSel)
-{
-#if !defined DD360Audi
-    return;
-#endif //!defined DD360Audi
-
-    SelectGunInfo *pSelectGunInfo = (SelectGunInfo *)GetShmSelectGunInfo(); //Jerry add
-
-    if (((curSel == LEFT_GUN_NUM) && (pSelectGunInfo->SelGunInfo.LeftGun >= SEL_GUN_CONFIRM)) ||
-            ((curSel == RIGHT_GUN_NUM) && (pSelectGunInfo->SelGunInfo.RightGun >= SEL_GUN_CONFIRM))) {
-        return PASS;
-    }
-
-    return FAIL;
-}
-
-void confirmSelGun(uint8_t selGun)
-{
-#if !defined DD360Audi
-    return;
-#endif //!defined DD360Audi
-
-    struct SysInfoData *pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
-    SelectGunInfo *pSelectGunInfo = (SelectGunInfo *)GetShmSelectGunInfo(); //Jerry add
-
-    if (selGun == LEFT_GUN_NUM) {
-        pSelectGunInfo->SelGunInfo.LeftGun = SEL_GUN_CONFIRM;
-        StopGunInfoTimeoutDet(selGun);
-        //printf("confirmSelGun left");
-    } else if (selGun == RIGHT_GUN_NUM) {
-        pSelectGunInfo->SelGunInfo.RightGun = SEL_GUN_CONFIRM;
-        StopGunInfoTimeoutDet(selGun);
-        //printf("confirmSelGun right");
-    }
-
-    pSysInfo->SystemPage = _LCM_IDLE;
-
-    StartGunInfoTimeoutDet(selGun, Timeout_SelectGun);
-}
-#endif //0
+#if 0
+#include <stdio.h>      /*標準輸入輸出定義*/
+#include <stdlib.h>     /*標準函數庫定義*/
+#include <string.h>
+#include <stdint.h>
+
+#include "../Config.h"
+#include "../Log/log.h"
+#include "../Define/define.h"
+#include "../ShareMemory/shmMem.h"
+#include "../timeout.h"
+#include "../CSU/main.h"
+
+#include "SelectGun.h"
+
+//------------------------------------------------------------------------------
+int WaitAuthorPageState(void)
+{
+    int ret = FAIL;
+    struct SysInfoData *pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
+
+#if !defined DD360Audi
+    return PASS;
+#endif //!defined DD360Audi
+
+    if (pSysInfo->SystemPage != _LCM_AUTHORIZING &&
+            pSysInfo->SystemPage != _LCM_AUTHORIZ_COMP &&
+            pSysInfo->SystemPage != _LCM_AUTHORIZ_FAIL) {
+        ret = PASS;
+    }
+
+    return ret;
+}
+
+void destroySelGun(uint8_t curGun)
+{
+    uint8_t i = 0;
+
+#if !defined DD360Audi
+    return;
+#endif //!defined DD360Audi
+
+    struct SysConfigData *pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
+    struct SysInfoData *pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
+    SelectGunInfo *pSelectGunInfo = (SelectGunInfo *)GetShmSelectGunInfo(); //Jerry add
+    struct OCPP16Data *ShmOCPP16Data = (struct OCPP16Data *)GetShmOCPP16Data();
+
+    //for status timeout
+    if (curGun == DESTROY_ALL_SEL) {
+        pSelectGunInfo->SelGunInfo.RightGun = SEL_GUN_RELEASE;
+        pSelectGunInfo->SelGunInfo.LeftGun = SEL_GUN_RELEASE;
+        log_info("destroy all gun = %d, %d",
+                 pSelectGunInfo->SelGunInfo.LeftGun,
+                 pSelectGunInfo->SelGunInfo.RightGun);
+        for (i = 0; i < pSysConfig->TotalConnectorCount; i++) {
+            StopGunInfoTimeoutDet(i);
+            memset(&pSelectGunInfo->PricesInfo[i], 0, sizeof(PricesInfo));
+        }
+        pSysInfo->CurGunSelected = 0;
+        strcpy((char *)pSysConfig->UserId, "");
+        //changeLcmPage(_LCM_SELECT_GUN);
+        return;
+    }
+
+    //for charging timeout or complete
+    if ((curGun == LEFT_GUN_NUM) && (pSelectGunInfo->SelGunInfo.LeftGun != SEL_GUN_RELEASE)) {
+        if (pSelectGunInfo->SelGunInfo.LeftGun == SEL_GUN_CONFIRM ||
+                pSelectGunInfo->SelGunInfo.LeftGun == SEL_GUN_ATHOR) {
+            pSysInfo->SystemPage = _LCM_SELECT_GUN;
+        }
+        pSelectGunInfo->SelGunInfo.LeftGun = SEL_GUN_RELEASE;
+        StopGunInfoTimeoutDet(LEFT_GUN_NUM);
+        if (ShmOCPP16Data->SpMsg.bits.AuthorizeConf != NO) {
+            ClearAuthorizedFlag();
+        }
+
+        log_info("destroy left gun, cur page = %d", pSysInfo->SystemPage);
+        //if (pSysInfo->SystemPage == pSysInfo->SystemPage) {
+        log_info("clear left balance");
+        memset(&pSelectGunInfo->PricesInfo[curGun], 0, sizeof(PricesInfo));
+        pSelectGunInfo->PricesInfo[curGun].Balance = FAIL_BALANCE_PRICES;
+        //}
+    }
+
+    if ((curGun == RIGHT_GUN_NUM) && (pSelectGunInfo->SelGunInfo.RightGun != SEL_GUN_RELEASE)) {
+        if (pSelectGunInfo->SelGunInfo.RightGun == SEL_GUN_CONFIRM ||
+                pSelectGunInfo->SelGunInfo.RightGun == SEL_GUN_ATHOR) {
+            pSysInfo->SystemPage = _LCM_SELECT_GUN;
+        }
+        pSelectGunInfo->SelGunInfo.RightGun = SEL_GUN_RELEASE;
+        StopGunInfoTimeoutDet(RIGHT_GUN_NUM);
+        if (ShmOCPP16Data->SpMsg.bits.AuthorizeConf != NO) {
+            ClearAuthorizedFlag();
+        }
+
+        log_info("destroy right gun, cur page = %d", pSysInfo->SystemPage);
+        //if (pSysInfo->SystemPage == pSysInfo->SystemPage) {
+        log_info("clear right balance");
+        memset(&pSelectGunInfo->PricesInfo[curGun], 0, sizeof(PricesInfo));
+        pSelectGunInfo->PricesInfo[curGun].Balance = FAIL_BALANCE_PRICES;
+        //}
+    }
+}
+
+int waitRightGunPlugIt(uint8_t curGun)
+{
+#if !defined DD360Audi
+    return;
+#endif //!defined DD360Audi
+
+    SelectGunInfo *pSelectGunInfo = (SelectGunInfo *)GetShmSelectGunInfo(); //Jerry add
+
+
+    if ((curGun == RIGHT_GUN_NUM) && (pSelectGunInfo->SelGunInfo.RightGun == SEL_GUN_ATHOR)) {
+        return PASS;
+    }
+
+    return FAIL;
+}
+
+int waitLeftGunPlugIt(uint8_t curGun)
+{
+#if !defined DD360Audi
+    return;
+#endif //!defined DD360Audi
+
+    SelectGunInfo *pSelectGunInfo = (SelectGunInfo *)GetShmSelectGunInfo(); //Jerry add
+
+    if ((curGun == LEFT_GUN_NUM) && (pSelectGunInfo->SelGunInfo.LeftGun == SEL_GUN_ATHOR)) {
+        return PASS;
+    }
+
+    return FAIL;
+}
+
+void setSelGunWaitToAuthor(uint8_t curSel)
+{
+#if !defined DD360Audi
+    return;
+#endif //!defined DD360Audi
+
+    SelectGunInfo *pSelectGunInfo = (SelectGunInfo *)GetShmSelectGunInfo(); //Jerry add
+
+    if (curSel == LEFT_GUN_NUM && pSelectGunInfo->SelGunInfo.LeftGun == SEL_GUN_CONFIRM) {
+        pSelectGunInfo->SelGunInfo.LeftGun = SEL_GUN_ATHOR;
+        //printf("setSelGunWaitToAuthor left");
+        StopGunInfoTimeoutDet(curSel);
+    } else if (curSel == RIGHT_GUN_NUM && pSelectGunInfo->SelGunInfo.RightGun == SEL_GUN_CONFIRM) {
+        pSelectGunInfo->SelGunInfo.RightGun = SEL_GUN_ATHOR;
+        //printf("setSelGunWaitToAuthor right");
+        StopGunInfoTimeoutDet(curSel);
+    }
+}
+
+int getConfirmSelectedGun(uint8_t curSel)
+{
+#if !defined DD360Audi
+    return;
+#endif //!defined DD360Audi
+
+    SelectGunInfo *pSelectGunInfo = (SelectGunInfo *)GetShmSelectGunInfo(); //Jerry add
+
+    if (((curSel == LEFT_GUN_NUM) && (pSelectGunInfo->SelGunInfo.LeftGun >= SEL_GUN_CONFIRM)) ||
+            ((curSel == RIGHT_GUN_NUM) && (pSelectGunInfo->SelGunInfo.RightGun >= SEL_GUN_CONFIRM))) {
+        return PASS;
+    }
+
+    return FAIL;
+}
+
+void confirmSelGun(uint8_t selGun)
+{
+#if !defined DD360Audi
+    return;
+#endif //!defined DD360Audi
+
+    struct SysInfoData *pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
+    SelectGunInfo *pSelectGunInfo = (SelectGunInfo *)GetShmSelectGunInfo(); //Jerry add
+
+    if (selGun == LEFT_GUN_NUM) {
+        pSelectGunInfo->SelGunInfo.LeftGun = SEL_GUN_CONFIRM;
+        StopGunInfoTimeoutDet(selGun);
+        //printf("confirmSelGun left");
+    } else if (selGun == RIGHT_GUN_NUM) {
+        pSelectGunInfo->SelGunInfo.RightGun = SEL_GUN_CONFIRM;
+        StopGunInfoTimeoutDet(selGun);
+        //printf("confirmSelGun right");
+    }
+
+    pSysInfo->SystemPage = _LCM_IDLE;
+
+    StartGunInfoTimeoutDet(selGun, Timeout_SelectGun);
+}
+#endif //0

+ 112 - 112
EVSE/Projects/DD360Tcci/Apps/SelectGun/SelectGun.h

@@ -1,112 +1,112 @@
-#ifndef _SELECT_GUN_H_
-#define _SELECT_GUN_H_
-
-#include <stdint.h>
-
-//------------------------------------------------------------------------------
-//--- //For Audi for Audi customization ---
-//------------------------------------------------------------------------------
-#define ShmSelectGunInfoKey                     (1014)
-
-#define SEL_GUN_RELEASE                         (0x00)
-#define SEL_GUN_CONFIRM                         (0x01)
-#define SEL_GUN_ATHOR                           (0x02)
-#define SEL_GUN_PLUG_IT                         (0x03)
-//#define SEL_GUN_CHARGING                        (0x04)
-//#define SEL_GUN_CHARGING_COMP                   (0x05)
-
-#define LEFT_GUN_NUM                            (0)
-#define RIGHT_GUN_NUM                           (1)
-#define SEL_GUN_TIMEOUT                         (120)
-
-#define DESTROY_ALL_SEL                         (0x03)
-
-#define FAIL_BALANCE_PRICES                     (-65535.00)
-
-//------------------------------------------------------------------------------
-//--- remote control ---
-//------------------------------------------------------------------------------
-//#define RT_NON_ACTION                           0x00
-//#define RT_HARDWARE_REBOOT                      0x01
-//#define RT_SOFTWARE_RESTART                     0x02
-
-//------------------------------------------------------------------------------
-//--- power cabinet Ethernet device status ---
-//------------------------------------------------------------------------------
-#define DEV_ST_DISABLE                          0x00
-#define DEV_ST_ENABLE_USE                       0x01
-#define DEV_ST_ENABLE_NO_USE                    0x02
-
-#define EV_BOARD_STOP_CHARGING                  1
-#define POWER_CABINET_STOP_CHARGING             2
-
-//------------------------------------------------------------------------------
-typedef struct StEthDevStatus {
-    uint8_t Backend;
-    uint8_t Ethernet;
-    uint8_t Wifi;
-    uint8_t FourG;
-} EthDevStatus;
-
-typedef struct StSelGunInfo {
-    uint8_t LeftGun;
-    uint8_t RightGun;
-    uint8_t Reserved[2];
-} SelGunInfo;
-
-typedef struct StPricesInfo {
-    //uint8_t Currency;
-    float UserPrices;           //unit = 0.01 dollar, value / 100
-    //float TotalCost;            //unit = 0.01 dollar, value / 100
-    float Balance;              //unit = 0.01 dollar, value / 100
-    //float DefaultPrices;        //unit = 0.01 dollar, value / 100
-    float Discount;
-    int TransactionId;
-    float EnergyCost;
-    float ParkingFee;
-    float RemainAmount;
-} PricesInfo;
-
-//typedef struct StOperativeInfo {
-//    uint8_t ChangeReq;
-//    uint8_t ConnectorID;
-//    uint8_t AvailabilityReq;
-//    uint8_t Reserved;
-//} OperativeInfo;
-
-//typedef struct StStartCharge {
-//    uint8_t ConnectorID;
-//    uint8_t Status;
-//    uint8_t Reserved[2];
-//} StartCharge;
-
-typedef struct StRemoteSetup {
-    //uint8_t Execution;
-    //uint8_t BtnStopCharging;
-    uint16_t ConnectionTimeout;
-    //float DefaultPrices;
-    //OperativeInfo Operative;
-    //StartCharge StartCharge;
-    uint8_t Reserved[2];
-} RemoteSetup;
-
-typedef struct StAudiCustInfo {
-    SelGunInfo SelGunInfo;
-    PricesInfo PricesInfo[2];
-    RemoteSetup RemoteSetup;
-    EthDevStatus EthDevStatus;
-    uint8_t AuthorStateFromCabinet[2];
-    uint8_t WaitDoCommPermission[2]; //等待主櫃回覆再進入充電檢測
-    //uint8_t Reserved; //保留
-} SelectGunInfo;
-
-//------------------------------------------------------------------------------
-//int WaitAuthorPageState(void);
-//void destroySelGun(uint8_t curGun);
-//int waitRightGunPlugIt(uint8_t curGun);
-//int waitLeftGunPlugIt(uint8_t curGun);
-//void setSelGunWaitToAuthor(uint8_t curSel);
-//int getConfirmSelectedGun(uint8_t curSel);
-//void confirmSelGun(uint8_t selGun);
-
-#endif /* _SELECT_GUN_H_ */
+#ifndef _SELECT_GUN_H_
+#define _SELECT_GUN_H_
+
+#include <stdint.h>
+
+//------------------------------------------------------------------------------
+//--- //For Audi for Audi customization ---
+//------------------------------------------------------------------------------
+#define ShmSelectGunInfoKey                     (1014)
+
+#define SEL_GUN_RELEASE                         (0x00)
+#define SEL_GUN_CONFIRM                         (0x01)
+#define SEL_GUN_ATHOR                           (0x02)
+#define SEL_GUN_PLUG_IT                         (0x03)
+//#define SEL_GUN_CHARGING                        (0x04)
+//#define SEL_GUN_CHARGING_COMP                   (0x05)
+
+#define LEFT_GUN_NUM                            (0)
+#define RIGHT_GUN_NUM                           (1)
+#define SEL_GUN_TIMEOUT                         (120)
+
+#define DESTROY_ALL_SEL                         (0x03)
+
+#define FAIL_BALANCE_PRICES                     (-65535.00)
+
+//------------------------------------------------------------------------------
+//--- remote control ---
+//------------------------------------------------------------------------------
+//#define RT_NON_ACTION                           0x00
+//#define RT_HARDWARE_REBOOT                      0x01
+//#define RT_SOFTWARE_RESTART                     0x02
+
+//------------------------------------------------------------------------------
+//--- power cabinet Ethernet device status ---
+//------------------------------------------------------------------------------
+#define DEV_ST_DISABLE                          0x00
+#define DEV_ST_ENABLE_USE                       0x01
+#define DEV_ST_ENABLE_NO_USE                    0x02
+
+#define EV_BOARD_STOP_CHARGING                  1
+#define POWER_CABINET_STOP_CHARGING             2
+
+//------------------------------------------------------------------------------
+typedef struct StEthDevStatus {
+    uint8_t Backend;
+    uint8_t Ethernet;
+    uint8_t Wifi;
+    uint8_t FourG;
+} EthDevStatus;
+
+typedef struct StSelGunInfo {
+    uint8_t LeftGun;
+    uint8_t RightGun;
+    uint8_t Reserved[2];
+} SelGunInfo;
+
+typedef struct StPricesInfo {
+    //uint8_t Currency;
+    float UserPrices;           //unit = 0.01 dollar, value / 100
+    //float TotalCost;            //unit = 0.01 dollar, value / 100
+    float Balance;              //unit = 0.01 dollar, value / 100
+    //float DefaultPrices;        //unit = 0.01 dollar, value / 100
+    float Discount;
+    int TransactionId;
+    float EnergyCost;
+    float ParkingFee;
+    float RemainAmount;
+} PricesInfo;
+
+//typedef struct StOperativeInfo {
+//    uint8_t ChangeReq;
+//    uint8_t ConnectorID;
+//    uint8_t AvailabilityReq;
+//    uint8_t Reserved;
+//} OperativeInfo;
+
+//typedef struct StStartCharge {
+//    uint8_t ConnectorID;
+//    uint8_t Status;
+//    uint8_t Reserved[2];
+//} StartCharge;
+
+typedef struct StRemoteSetup {
+    //uint8_t Execution;
+    //uint8_t BtnStopCharging;
+    uint16_t ConnectionTimeout;
+    //float DefaultPrices;
+    //OperativeInfo Operative;
+    //StartCharge StartCharge;
+    uint8_t Reserved[2];
+} RemoteSetup;
+
+typedef struct StAudiCustInfo {
+    SelGunInfo SelGunInfo;
+    PricesInfo PricesInfo[2];
+    RemoteSetup RemoteSetup;
+    EthDevStatus EthDevStatus;
+    uint8_t AuthorStateFromCabinet[2];
+    uint8_t WaitDoCommPermission[2]; //等待主櫃回覆再進入充電檢測
+    //uint8_t Reserved; //保留
+} SelectGunInfo;
+
+//------------------------------------------------------------------------------
+//int WaitAuthorPageState(void);
+//void destroySelGun(uint8_t curGun);
+//int waitRightGunPlugIt(uint8_t curGun);
+//int waitLeftGunPlugIt(uint8_t curGun);
+//void setSelGunWaitToAuthor(uint8_t curSel);
+//int getConfirmSelectedGun(uint8_t curSel);
+//void confirmSelGun(uint8_t selGun);
+
+#endif /* _SELECT_GUN_H_ */

+ 1090 - 1175
EVSE/Projects/DD360Tcci/Apps/ShareMemory/shmMem.c

@@ -1,1175 +1,1090 @@
-#include <stdio.h>
-#include <stdlib.h>
-#include <stdint.h>
-#include <string.h>
-#include <stdbool.h>
-
-#include <unistd.h>
-#include <sys/ipc.h>
-#include <sys/shm.h>
-
-#include "../Define/define.h"
-//#include "../AudiCust.h"
-#include "../SelectGun/SelectGun.h"
-#include "../common.h"
-#include "../Log/log.h"
-#include "../Config.h"
-#include "shmMem.h"
-
-//------------------------------------------------------------------------------
-static struct SysConfigAndInfo *ShmSysConfigAndInfo = NULL;
-//static struct SysInfoData *ShmSysInfoData = NULL;
-//static struct SysConfigData *ShmSysConfigData = NULL;
-//static struct WARNING_CODE_INFO *SysWarningInfo = NULL;
-
-static struct StatusCodeData *ShmStatusCodeData = NULL;
-//static struct AlarmCodeData *ShmAlarmCodeData = NULL;
-//static struct FaultCodeData *ShmFaultCodeData = NULL;
-//static struct InfoCodeData  *ShmInfoCodeData = NULL;
-
-static struct PsuData *ShmPsuData = NULL;
-
-static struct CHAdeMOData *ShmCHAdeMOData = NULL;
-static struct GBTData *ShmGBTData = NULL;
-static struct CcsData *ShmCcsData = NULL;
-
-static struct PrimaryMcuData *ShmPrimaryMcuData = NULL;
-static struct FanModuleData *ShmFanModuleData = NULL;
-static struct RelayModuleData *ShmRelayModuleData = NULL;
-static struct LedModuleData *ShmLedModuleData = NULL;
-static struct OCPP16Data *ShmOCPP16Data = NULL;
-static struct OCPP20Data* ShmOCPP20Data = NULL;
-
-static SelectGunInfo *ShmSelectGunInfo = NULL;
-static DcCommonInfo *ShmDcCommonData = NULL;
-
-static struct ChargingInfoData *DcChargingData[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY] = {NULL};
-static struct ChargingInfoData *AcChargingData[AC_QUANTITY] = {NULL};
-
-static GunIndexInfo gGunIndexInfo = {0};
-
-//struct SysConfigData *pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
-//struct SysInfoData *pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
-//struct WARNING_CODE_INFO *pSysWarning = (struct WARNING_CODE_INFO *)GetShmSysWarningInfo();
-
-//struct AlarmCodeData *pAlarmCode = (struct AlarmCodeData *)GetShmAlarmCodeData();
-//struct InfoCodeData *pInfoCode = (struct InfoCodeData *)GetShmInfoCodeData();
-//struct FaultCodeData *pFaultCode = (struct FaultCodeData *)GetShmFaultCodeData();
-
-//struct PsuData *ShmPsuData = (struct PsuData *)GetShmPsuData();
-
-//struct CHAdeMOData *ShmCHAdeMOData = (struct CHAdeMOData *)GetShmCHAdeMOData();
-//struct GBTData *ShmGBTData = (struct GBTData *)GetShmGBTData();
-//struct CcsData *ShmCcsData = (struct CcsData *)GetShmCcsData();
-
-//struct PrimaryMcuData *ShmPrimaryMcuData = (struct PrimaryMcuData *)GetShmPrimaryMcuData();
-//struct FanModuleData *ShmFanModuleData = (struct FanModuleData *)GetShmFanModuleData();
-//struct RelayModuleData *ShmRelayModuleData = (struct RelayModuleData *)GetShmRelayModuleData();
-//struct LedModuleData *ShmLedModuleData = (struct LedModuleData *)GetShmLedModuleData();
-//struct OCPP16Data *ShmOCPP16Data = (struct OCPP16Data *)GetShmOCPP16Data();
-
-//SelectGunInfo *ShmSelectGunInfo = (SelectGunInfo *)GetShmSelectGunInfo();
-//DcCommonInfo *ShmDcCommonData = (DcCommonInfo *)GetShmDcCommonData();
-
-//struct ChargingInfoData *pDcChargingInfo = NULL;
-//struct ChargingInfoData *pAcChargingInfo = NULL;
-
-//------------------------------------------------------------------------------
-void *GetGunIndexInfo(void)
-{
-    return &gGunIndexInfo;
-}
-
-#if 0
-static int findChargingInfoData(uint8_t target, struct ChargingInfoData **chargingData)
-{
-    uint8_t i = 0;
-
-    for (i = 0; i < CHAdeMO_QUANTITY; i++) {
-        if (ShmSysConfigAndInfo->SysInfo.ChademoChargingData[i].Index == target) {
-            chargingData[target] = &ShmSysConfigAndInfo->SysInfo.ChademoChargingData[i];
-            return PASS;
-        }
-    }
-
-    for (i = 0; i < CCS_QUANTITY; i++) {
-        if (ShmSysConfigAndInfo->SysInfo.CcsChargingData[i].Index == target) {
-            log_info("Index = %d, %d", target, ShmSysConfigAndInfo->SysInfo.CcsChargingData[i].Index);
-            chargingData[target] = &ShmSysConfigAndInfo->SysInfo.CcsChargingData[i];
-            return PASS;
-        }
-    }
-
-    for (i = 0; i < GB_QUANTITY; i++) {
-        if (ShmSysConfigAndInfo->SysInfo.GbChargingData[i].Index == target) {
-            chargingData[target] = &ShmSysConfigAndInfo->SysInfo.GbChargingData[i];
-            return PASS;
-        }
-    }
-
-    return FAIL;
-}
-
-void MappingChargingInfoData(void) //DS60-120 add
-{
-    bool isPass = true;
-    uint8_t i = 0;
-
-    while (isPass) {
-        for (i = 0; i < 2; i++) {
-            if (!findChargingInfoData(i, &DcChargingData[0])) {
-                log_error("Find ChargingInfoData failed");
-                isPass = false;
-                break;
-            }
-        }
-        sleep(1);
-    }
-}
-#endif //0
-
-void SetAcChargingInfoData(uint8_t index, struct ChargingInfoData *chargingInfoIndex)
-{
-    AcChargingData[index] = chargingInfoIndex;
-}
-
-void *GetAcChargingInfoData(uint8_t index)
-{
-    return AcChargingData[index];
-}
-
-void SetDcChargingInfoData(uint8_t index, struct ChargingInfoData *chargingInfoIndex)
-{
-    DcChargingData[index] = chargingInfoIndex;
-}
-
-void *GetDcChargingInfoData(uint8_t index)
-{
-    return DcChargingData[index];
-}
-
-void *GetShmSysWarningInfo(void)
-{
-    if (ShmSysConfigAndInfo == NULL) {
-        return NULL;
-    }
-
-    return &ShmSysConfigAndInfo->SysWarningInfo;
-}
-
-void *GetShmSysConfigData(void)
-{
-    if (ShmSysConfigAndInfo == NULL) {
-        return NULL;
-    }
-
-    return &ShmSysConfigAndInfo->SysConfig;
-}
-
-void *GetShmSysInfoData(void)
-{
-    if (ShmSysConfigAndInfo == NULL) {
-        return NULL;
-    }
-
-    return &ShmSysConfigAndInfo->SysInfo;
-}
-
-void *GetShmSysConfigAndInfo(void)
-{
-    if (ShmSysConfigAndInfo == NULL) {
-        return NULL;
-    }
-
-    return ShmSysConfigAndInfo;
-}
-
-void *GetShmInfoCodeData(void)
-{
-    if (ShmStatusCodeData == NULL) {
-        return NULL;
-    }
-
-    return &ShmStatusCodeData->InfoCode;
-}
-
-void *GetShmFaultCodeData(void)
-{
-    if (ShmStatusCodeData == NULL) {
-        return NULL;
-    }
-
-    return &ShmStatusCodeData->FaultCode;
-}
-
-void *GetShmAlarmCodeData(void)
-{
-    if (ShmStatusCodeData == NULL) {
-        return NULL;
-    }
-
-    return &ShmStatusCodeData->AlarmCode;
-}
-
-void *GetShmStatusCodeData(void)
-{
-    if (ShmStatusCodeData == NULL) {
-        return NULL;
-    }
-
-    return ShmStatusCodeData;
-}
-
-void *GetShmPsuData(void)
-{
-    if (ShmPsuData == NULL) {
-        return NULL;
-    }
-
-    return ShmPsuData;
-}
-
-void *GetShmCHAdeMOData(void)
-{
-    if (ShmCHAdeMOData == NULL) {
-        return NULL;
-    }
-
-    return ShmCHAdeMOData;
-}
-
-void *GetShmGBTData(void)
-{
-    if (ShmGBTData == NULL) {
-        return NULL;
-    }
-
-    return ShmGBTData;
-}
-
-void *GetShmCcsData(void)
-{
-    if (ShmCcsData == NULL) {
-        return NULL;
-    }
-
-    return ShmCcsData;
-}
-
-void *GetShmPrimaryMcuData(void)
-{
-    if (ShmPrimaryMcuData == NULL) {
-        return NULL;
-    }
-
-    return ShmPrimaryMcuData;
-}
-
-void *GetShmFanModuleData(void)
-{
-    if (ShmFanModuleData == NULL) {
-        return NULL;
-    }
-
-    return ShmFanModuleData;
-}
-
-void *GetShmRelayModuleData(void)
-{
-    if (ShmRelayModuleData == NULL) {
-        return NULL;
-    }
-
-    return ShmRelayModuleData;
-}
-
-void *GetShmLedModuleData(void)
-{
-    if (ShmLedModuleData == NULL) {
-        return NULL;
-    }
-
-    return ShmLedModuleData;
-}
-
-void *GetShmOCPP16Data(void)
-{
-    if (ShmOCPP16Data == NULL) {
-        return NULL;
-    }
-
-    return ShmOCPP16Data;
-}
-
-void* GetShmOCPP20Data(void)
-{
-    if (ShmOCPP20Data == NULL) {
-        return NULL;
-    }
-
-    return ShmOCPP20Data;
-}
-
-void *GetShmSelectGunInfo(void)
-{
-    if (ShmSelectGunInfo == NULL) {
-        return NULL;
-    }
-
-    return ShmSelectGunInfo;
-}
-
-void *GetShmDcCommonData(void)
-{
-    if (ShmDcCommonData == NULL) {
-        return NULL;
-    }
-
-    return ShmDcCommonData;
-}
-
-//------------------------------------------------------------------------------
-static void initialGunIndexToUnUse(void)
-{
-    uint8_t index = 0;
-    struct SysInfoData *pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
-
-    for (index = 0; index < CHAdeMO_QUANTITY; index++) {
-        pSysInfo->ChademoChargingData[index].Index = NO_DEFINE;
-    }
-
-    for (index = 0; index < CCS_QUANTITY; index++) {
-        pSysInfo->CcsChargingData[index].Index = NO_DEFINE;
-    }
-
-    for (index = 0; index < GB_QUANTITY; index++) {
-        pSysInfo->GbChargingData[index].Index = NO_DEFINE;
-    }
-
-    for (index = 0; index < AC_QUANTITY; index++) {
-        pSysInfo->AcChargingData[index].Index = NO_DEFINE;
-    }
-}
-
-#if 0
-static void getFirmwareVersion(void)
-{
-    uint8_t count = 0, chademo = 0, ccs = 0, gb = 0;
-    uint8_t index = 0;
-    struct SysConfigData *pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
-    struct SysInfoData *pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
-
-    // Get CSU root file system version
-    sprintf((char *)pSysInfo->CsuRootFsFwRev, fwVersion);
-
-    for (index = 0; index < 3; index++) {
-        if (pSysConfig->ModelName[7 + index] == 'J') {
-            chademo++;
-            count++;
-        } else if (pSysConfig->ModelName[7 + index] == 'G') {
-            gb++;
-            count++;
-        } else if (pSysConfig->ModelName[7 + index] == 'U' ||
-                   pSysConfig->ModelName[7 + index] == 'V' ||
-                   pSysConfig->ModelName[7 + index] == 'E') {
-            ccs++;
-            count++;
-        }
-    }
-
-    if (count == 1) {
-        if (chademo > 0) {
-            pSysInfo->CsuRootFsFwRev[7] = '1';
-        } else if (ccs > 0) {
-            pSysInfo->CsuRootFsFwRev[7] = '2';
-        } else if (gb > 0) {
-            pSysInfo->CsuRootFsFwRev[7] = '3';
-        }
-    } else {
-        if (chademo > 0 && ccs > 0) {
-            pSysInfo->CsuRootFsFwRev[7] = '4';
-        } else if (chademo > 0 && gb > 0) {
-            pSysInfo->CsuRootFsFwRev[7] = '5';
-        } else if (ccs > 0 && gb > 0) {
-            pSysInfo->CsuRootFsFwRev[7] = '6';
-        }
-    }
-
-    // Get network option from model name
-    switch (pSysConfig->ModelName[10]) {
-    case 'B':
-    case 'U':
-        //Blue tooth
-        pSysInfo->CsuRootFsFwRev[9] = '3';
-        break;
-    case 'W':
-        // WIFI
-        pSysInfo->CsuRootFsFwRev[9] = '1';
-        break;
-    case 'T':
-        // 3G/4G
-        pSysInfo->CsuRootFsFwRev[9] = '2';
-        break;
-    case 'D': //DS60-120 add
-        pSysInfo->CsuRootFsFwRev[9] = '5';
-        break;
-    default:
-        // LAN
-        pSysInfo->CsuRootFsFwRev[9] = '0';
-        break;
-    }
-
-    // Get rating power from model name
-    memcpy(&pSysInfo->CsuRootFsFwRev[10], &pSysConfig->ModelName[4], 0x03);
-
-    // Get IEC or UL
-    char _buf[3] = {0};
-    memcpy(_buf, &pSysConfig->ModelName[2], 2);
-
-    if (strcmp(_buf, "YE") == EQUAL || strcmp(_buf, "YC") == EQUAL) {
-        pSysInfo->ChargerType = _CHARGER_TYPE_IEC;
-        log_info("IEC model");
-    } else if (strcmp(_buf, "WU") == EQUAL) {
-        pSysInfo->ChargerType = _CHARGER_TYPE_UL;
-        log_info("UL model");
-    }
-}
-#endif //0
-
-void InitialShareMemoryInfo(void)
-{
-    FILE *fp = NULL;
-    char cmd[512] = {0};
-    char buf[512] = {0};
-    struct SysConfigData *pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
-    struct SysInfoData *pSysInfo     = (struct SysInfoData *)GetShmSysInfoData();
-    struct AlarmCodeData *pAlarmCode = (struct AlarmCodeData *)GetShmAlarmCodeData();
-
-    //SysConfig init
-    sprintf((char *)pSysConfig->TelecomInterface.TelcomApn, "Internet");
-    sprintf((char *)pSysConfig->TelecomInterface.TelcomChapPapId, " ");
-    sprintf((char *)pSysConfig->TelecomInterface.TelcomChapPapPwd, " ");
-
-    pSysConfig->TotalConnectorCount = 0;
-    pSysConfig->AcConnectorCount = 0;
-
-    memcpy(pSysInfo->CsuBootLoadFwRev,
-           pSysConfig->CsuBootLoadFwRev,
-           ARRAY_SIZE(pSysConfig->CsuBootLoadFwRev));
-
-    strcpy((char *) pSysConfig->UserId, "");
-    pSysConfig->QRCodeMadeMode = NO; //DS60-120 add
-    pSysConfig->SwitchDebugFlag = NO;
-    pSysConfig->AlwaysGfdFlag = NO;
-
-    //SysInfo init
-    pSysInfo->FactoryConfiguration = 0;
-    pSysInfo->InputVoltageR = 0;
-    pSysInfo->InputVoltageS = 0;
-    pSysInfo->InputVoltageT = 0;
-    pSysInfo->SystemFanRotaSpeed = 0;
-    pSysInfo->PsuFanRotaSpeed = 0;
-    pSysInfo->AuxPower5V = 0;
-    pSysInfo->AuxPower12V = 0;
-    pSysInfo->AuxPower24V = 0;
-    pSysInfo->AuxPower48V = 0;
-
-    sprintf((char *)pSysInfo->CsuHwRev, "REV:5.0");
-
-    sprintf(cmd, "/bin/uname -r");
-    fp = popen(cmd, "r");
-    if (fp == NULL) {
-        sprintf((char *)pSysInfo->CsuKernelFwRev, "Unknown version");
-    } else {
-        while (fgets(buf, sizeof(buf), fp) != NULL) {
-            strcpy((char *)pSysInfo->CsuKernelFwRev, buf);
-        }
-    }
-
-    // 雙槍 CCS + Chademo
-    //getFirmwareVersion();
-
-    //sprintf((char *) pSysInfo->CsuRootFsFwRev, fwVersion);
-    sprintf((char *) pSysInfo->CsuPrimFwRev, " ");
-
-    sprintf((char *)pSysInfo->LcmHwRev, " ");
-    sprintf((char *)pSysInfo->LcmFwRev, " ");
-    sprintf((char *)pSysInfo->PsuHwRev, " ");
-    sprintf((char *)pSysInfo->PsuPrimFwRev, " ");
-    sprintf((char *)pSysInfo->PsuSecFwRev, " ");
-    sprintf((char *)pSysInfo->AuxPwrHwRev, " ");
-    sprintf((char *)pSysInfo->AuxPwrFwRev, " ");
-    sprintf((char *)pSysInfo->FanModuleHwRev, " ");
-    sprintf((char *)pSysInfo->FanModuleFwRev, " ");
-    sprintf((char *)pSysInfo->RelayModuleHwRev, " ");
-    sprintf((char *)pSysInfo->RelayModuleFwRev, " ");
-    sprintf((char *)pSysInfo->TelcomModemFwRev, " ");
-    pSysInfo->SystemAmbientTemp = 0;
-    pSysInfo->SystemCriticalTemp = 0;
-    pSysInfo->PsuAmbientTemp = 0;
-    pSysInfo->CcsConnectorTemp = 0;
-    pSysInfo->InternetConn = 0;
-    pSysInfo->OcppConnStatus = 0;
-    pSysInfo->OrderCharging = NO_DEFINE;
-
-    memset(pSysInfo->FanModuleFwRev, 0, ARRAY_SIZE(pSysInfo->FanModuleFwRev));
-    memset(pSysInfo->RelayModuleFwRev, 0, ARRAY_SIZE(pSysInfo->RelayModuleFwRev));
-
-    pSysInfo->SystemPage = _PAGE_IDLE;
-
-    pSysInfo->MainChargingMode = _MAIN_CHARGING_MODE_MAX;
-    pSysInfo->ReAssignedFlag = _REASSIGNED_NONE;
-    pSysInfo->CurGunSelectedByAc = NO_DEFINE;
-    pSysInfo->BootingStatus = BOOTTING; //DS60-120 add
-
-    //other board init
-    ShmPrimaryMcuData->SelfTest_Comp = NO;
-    ShmRelayModuleData->SelfTest_Comp = NO;
-    ShmFanModuleData->SelfTest_Comp = NO;
-    ShmLedModuleData->SelfTest_Comp = NO;
-    ShmFanModuleData->TestFanSpeed = 0;
-
-    //status code init
-    pAlarmCode->AlarmEvents.bits.RelayboardStestFail = NO;
-    pAlarmCode->AlarmEvents.bits.FanboardStestFail = NO;
-    pAlarmCode->AlarmEvents.bits.PrimaryStestFail = NO;
-    pAlarmCode->AlarmEvents.bits.LedboardStestFail = NO; //DS60-120 Add
-    pAlarmCode->AlarmEvents.bits.ChademoboardStestFail = NO;
-    pAlarmCode->AlarmEvents.bits.CCSboardStestFail = NO;
-    pAlarmCode->AlarmEvents.bits.AcContactStestFail = NO;
-    pAlarmCode->AlarmEvents.bits.PsuModuleStestFail = NO;
-    pAlarmCode->AlarmEvents.bits.PsuDipSwitchStestFail = NO; //DS60-120 Add
-    pAlarmCode->AlarmEvents.bits.ModelNameNoneMatchStestFail = NO;
-    pAlarmCode->AlarmEvents.bits.PsuNoResource = NO;
-    pAlarmCode->AlarmEvents.bits.FailToCreateShareMemory = NO;
-
-    initialGunIndexToUnUse();//DS60-120 add
-
-    //ShmDcCommonData->CcsVersion = _CCS_VERSION_CHECK_TAG_V015S0;
-    //ShmDcCommonData->psuKeepCommunication = NO;
-    //ShmDcCommonData->acContactSwitch = NO;
-    ShmDcCommonData->ConnectErrList[0].GunErrMessage = 0;
-    ShmDcCommonData->ConnectErrList[1].GunErrMessage = 0;
-    ShmDcCommonData->TestTemperature = NO;
-    //ShmDcCommonData->LcmFwVersion = 0;
-}
-
-int InitSelectGunShmMem(void)
-{
-    int MeterSMId = FAIL;
-
-#if !defined DD360Tcci && !defined DD360Audi && !defined DD360ComBox && !defined DD360UCar
-    return;
-#endif //!defined DD360Tcci && !defined DD360Audi && !defined DD360ComBox
-
-    if ((MeterSMId = shmget(ShmSelectGunInfoKey, sizeof(SelectGunInfo), IPC_CREAT | 0777)) < 0) {
-        return FAIL;
-    } else if ((ShmSelectGunInfo = shmat(MeterSMId, NULL, 0)) == (void *) - 1) {
-        return FAIL;
-    }
-
-    return PASS;
-}
-
-int InitCommonShmMem(void)
-{
-    int MeterSMId = FAIL;
-
-    if ((MeterSMId = shmget(ShmCommonKey, sizeof(DcCommonInfo), IPC_CREAT | 0777)) < 0) {
-        return FAIL;
-    } else if ((ShmDcCommonData = shmat(MeterSMId, NULL, 0)) == (void *) - 1) {
-        return FAIL;
-    }
-
-    return PASS;
-}
-
-//int InitCSUMeterShmMem(void)
-//{
-//    int MeterSMId = FAIL;
-//
-//    if ((MeterSMId = shmget(ShmCsuMeterKey, sizeof(struct MeterInformation), IPC_CREAT | 0777)) < 0) {
-//        return FAIL;
-//    } else if ((ShmCsuMeterInfo = shmat(MeterSMId, NULL, 0)) == (void *) - 1) {
-//        return FAIL;
-//    }
-//
-//    return PASS;
-//}
-
-int InitOCPPShmMem(void)
-{
-    int MeterSMId = FAIL;
-
-    if ((MeterSMId = shmget(ShmOcppModuleKey, sizeof(struct OCPP16Data), IPC_CREAT | 0777)) < 0) {
-        log_info("Get OCPP share memory error");
-        return FAIL;
-    } else if ((ShmOCPP16Data = shmat(MeterSMId, NULL, 0)) == (void *) - 1) {
-        log_info("Create OCPP share memory error");
-        return FAIL;
-    }
-
-    return PASS;
-}
-
-int InitOCPP20ShmMem(void)
-{
-    int MeterSMId = FAIL;
-
-    if ((MeterSMId = shmget(ShmOcpp20ModuleKey, sizeof(struct OCPP20Data), IPC_CREAT | 0777)) < 0) {
-        log_info("Get OCPP20 share memory error");
-        return FAIL;
-    } else if ((ShmOCPP20Data = shmat(MeterSMId, NULL, 0)) == (void*)-1) {
-        log_info("Create OCPP20 share memory error");
-        return FAIL;
-    }
-
-    return PASS;
-}
-
-int InitLEDShmMem(void)
-{
-    int MeterSMId = FAIL;
-
-    if ((MeterSMId = shmget(ShmLedBdKey, sizeof(struct LedModuleData), IPC_CREAT | 0777)) < 0) {
-        return FAIL;
-    } else if ((ShmLedModuleData = shmat(MeterSMId, NULL, 0)) == (void *) - 1) {
-        return FAIL;
-    }
-
-    return PASS;
-}
-
-int InitRelayShmMem(void)
-{
-    int MeterSMId = FAIL;
-
-    if ((MeterSMId = shmget(ShmRelayBdKey, sizeof(struct RelayModuleData),  IPC_CREAT | 0777)) < 0) {
-        return FAIL;
-    } else if ((ShmRelayModuleData = shmat(MeterSMId, NULL, 0)) == (void *) - 1) {
-        return FAIL;
-    }
-
-    return PASS;
-}
-
-int InitFanShmMem(void)
-{
-    int MeterSMId = FAIL;
-
-    if ((MeterSMId = shmget(ShmFanBdKey, sizeof(struct FanModuleData),  IPC_CREAT | 0777)) < 0) {
-        return FAIL;
-    } else if ((ShmFanModuleData = shmat(MeterSMId, NULL, 0)) == (void *) - 1) {
-        return FAIL;
-    }
-
-    return PASS;
-}
-
-int InitPrimaryShmMem(void)
-{
-    int MeterSMId = FAIL;
-
-    if ((MeterSMId = shmget(ShmPrimaryMcuKey, sizeof(struct PrimaryMcuData), IPC_CREAT | 0777)) < 0) {
-        return FAIL;
-    } else if ((ShmPrimaryMcuData = shmat(MeterSMId, NULL, 0)) == (void *) - 1) {
-        return FAIL;
-    }
-
-    return PASS;
-}
-
-int InitCCSShmMem(void)
-{
-    int MeterSMId = FAIL;
-
-    if ((MeterSMId = shmget(ShmCcsCommKey, sizeof(struct CcsData),  IPC_CREAT | 0777)) < 0) {
-        return FAIL;
-    } else if ((ShmCcsData = shmat(MeterSMId, NULL, 0)) == (void *) - 1) {
-        return FAIL;
-    }
-
-    return PASS;
-}
-
-int InitGBShmMem(void)
-{
-    int MeterSMId = FAIL;
-
-    if ((MeterSMId = shmget(ShmGBTCommKey, sizeof(struct GBTData),  IPC_CREAT | 0777)) < 0) {
-        return FAIL;
-    } else if ((ShmGBTData = shmat(MeterSMId, NULL, 0)) == (void *) - 1) {
-        return FAIL;
-    }
-
-    return PASS;
-}
-
-int InitCHADeMoShmMem(void)
-{
-    int MeterSMId = FAIL;
-
-    if ((MeterSMId = shmget(ShmCHAdeMOCommKey, sizeof(struct CHAdeMOData),  IPC_CREAT | 0777)) < 0) {
-        return FAIL;
-    } else if ((ShmCHAdeMOData = shmat(MeterSMId, NULL, 0)) == (void *) - 1) {
-        return FAIL;
-    }
-    return PASS;
-}
-
-int InitPSUDataShmMem(void)
-{
-    int MeterSMId = FAIL;
-
-    //creat ShmPsuData
-    if ((MeterSMId = shmget(ShmPsuKey, sizeof(struct PsuData), IPC_CREAT | 0777)) < 0) {
-        return FAIL;
-    } else if ((ShmPsuData = shmat(MeterSMId, NULL, 0)) == (void *) - 1) {
-        return FAIL;
-    }
-
-    return PASS;
-}
-
-int InitStatusCodeShmMem(void)
-{
-    int MeterSMId = FAIL;
-
-    if ((MeterSMId = shmget(ShmStatusCodeKey, sizeof(struct StatusCodeData), IPC_CREAT | 0777)) < 0) {
-        return FAIL;
-    } else if ((ShmStatusCodeData = shmat(MeterSMId, NULL, 0)) == (void *) - 1) {
-        return FAIL;
-    }
-
-    return PASS;
-}
-
-int InitSysConfigAndInfoShmMem(void)
-{
-    int MeterSMId = FAIL;
-
-    if ((MeterSMId = shmget(ShmSysConfigAndInfoKey, sizeof(struct SysConfigAndInfo), IPC_CREAT | 0777)) < 0) {
-        printf("1 InitSysConfigAndInfoShmMem");
-        return FAIL;
-    } else if ((ShmSysConfigAndInfo = shmat(MeterSMId, NULL, 0))  == (void *) - 1) {
-        printf("2 InitSysConfigAndInfoShmMem");
-        return FAIL;
-    }
-
-    return PASS;
-}
-
-void ClearAllShmMemParameter(void)
-{
-    uint8_t i = 0;
-
-    memset(ShmSysConfigAndInfo, 0, sizeof(struct SysConfigAndInfo));
-    memset(ShmStatusCodeData, 0, sizeof(struct StatusCodeData));
-    memset(ShmPsuData, 0, sizeof(struct PsuData));
-
-    if (CHAdeMO_QUANTITY > 0) {
-        memset(ShmCHAdeMOData, 0, sizeof(struct CHAdeMOData));
-    }
-
-    if (GB_QUANTITY > 0) {
-        memset(ShmGBTData, 0, sizeof(struct GBTData));
-    }
-
-    if (CCS_QUANTITY > 0) {
-        memset(ShmCcsData, 0, sizeof(struct CcsData));
-    }
-
-    memset(ShmPrimaryMcuData, 0, sizeof(struct PrimaryMcuData));
-    memset(ShmFanModuleData, 0, sizeof(struct FanModuleData));
-    memset(ShmRelayModuleData, 0, sizeof(struct RelayModuleData));
-    memset(ShmLedModuleData, 0, sizeof(struct LedModuleData));
-    //memset(ShmOCPP16Data,0,sizeof(struct OCPP16Data));
-
-    //memset(ShmCsuMeterInfo, 0, sizeof(struct MeterInformation));
-    memset(ShmDcCommonData, 0, sizeof(DcCommonInfo));
-
-#if defined DD360Tcci || defined DD360Audi || defined DD360ComBox || defined DD360UCar
-    memset(ShmSelectGunInfo, 0, sizeof(SelectGunInfo));
-
-    for (i = 0; i < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; i++) {
-        ShmSelectGunInfo->PricesInfo[i].Balance = FAIL_BALANCE_PRICES;
-    }
-#endif //defined DD360Tcci || defined DD360Audi || defined DD360ComBox
-}
-
-static void setAcGunTiggerStatus(void)
-{
-    struct ChargingInfoData *pAcChargingInfo = NULL;
-
-    if (gGunIndexInfo.AcGunIndex == 0) {
-        return;
-    }
-
-    pAcChargingInfo = (struct ChargingInfoData *)GetAcChargingInfoData(gGunIndexInfo.AcGunIndex);
-
-    pAcChargingInfo->schedule.isTriggerStart = NO; //DS60-120 add
-    pAcChargingInfo->schedule.isTriggerStop = NO;  //DS60-120 add
-}
-
-static int findAcChargingInfoData(uint8_t gunIndex)
-{
-    struct SysInfoData *pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
-    //acChargingData[gunIndex] = &pSysInfo->AcChargingData[0];
-    SetAcChargingInfoData(gunIndex, &pSysInfo->AcChargingData[0]);
-
-    return PASS;
-}
-
-static int findDcChargingInfoData(uint8_t gunIndex)
-{
-    uint8_t i = 0;
-    struct SysInfoData *pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
-
-    //printf("Chademo count = %d\n", gGunIndexInfo.ChademoIndex);
-    for (i = 0; i < gGunIndexInfo.DcGunIndex; i++) {
-        if (pSysInfo->ChademoChargingData[i].Index == gunIndex) {
-            //printf("chademo index = %d, %d\n", pSysInfo->ChademoChargingData[i].Index, gunIndex);
-            //dcChargingData[gunIndex] = &pSysInfo->ChademoChargingData[i];
-            SetDcChargingInfoData(pSysInfo->ChademoChargingData[i].Index, &pSysInfo->ChademoChargingData[i]);
-            return PASS;
-        }
-    }
-
-    //printf("ccs count = %d\n", gGunIndexInfo.CcsIndex);
-    for (i = 0; i < gGunIndexInfo.DcGunIndex; i++) {
-        if (pSysInfo->CcsChargingData[i].Index == gunIndex) {
-            //printf("ccs index = %d, %d\n", pSysInfo->CcsChargingData[i].Index, gunIndex);
-            //dcChargingData[gunIndex] = (struct ChargingInfoData *)&pSysInfo->CcsChargingData[i];
-            SetDcChargingInfoData(pSysInfo->CcsChargingData[i].Index, &pSysInfo->CcsChargingData[i]);
-            return PASS;
-        }
-    }
-
-    for (i = 0; i < gGunIndexInfo.DcGunIndex; i++) {
-        if (pSysInfo->GbChargingData[i].Index == gunIndex) {
-            //dcChargingData[gunIndex] = &pSysInfo->GbChargingData[i];
-            SetDcChargingInfoData(pSysInfo->GbChargingData[i].Index, &pSysInfo->GbChargingData[i]);
-            return PASS;
-        }
-    }
-
-    return FAIL;
-}
-
-static bool addGunInfoByConnector(uint8_t typeValue, uint8_t slots,char *whichtask)
-{
-    bool result = true;
-    struct SysInfoData *pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
-    struct ChargingInfoData *pDcChargingInfo = NULL;
-    struct ChargingInfoData *pAcChargingInfo = (struct ChargingInfoData *)GetAcChargingInfoData(gGunIndexInfo.AcGunIndex);
-    struct CcsData *pCcsData = (struct CcsData *)GetShmCcsData();
-
-    switch (typeValue) {
-    // AC Gun Type -------------------------------------------------------------
-    case '0': // none
-        break;
-
-    case '1': // IEC 62196-2 Type 1/SAE J1772 Plug
-        break;
-
-    case '2': // IEC 62196-2 Type 1/SAE J1772 Socket
-        break;
-
-    case '3': // IEC 62196-2 Type 2 Plug
-    case '4': // IEC 62196-2 Type 2 Socket
-        if (AC_QUANTITY > gGunIndexInfo.AcIndex) {
-            pAcChargingInfo = (struct ChargingInfoData *)&pSysInfo->AcChargingData[gGunIndexInfo.AcIndex];
-
-            // AC 固定 index
-            pAcChargingInfo->Index = 0;
-            pAcChargingInfo->ReservationId = -1;
-            pAcChargingInfo->SystemStatus = S_IDLE;
-            pAcChargingInfo->Type = _Type_AC;
-            pAcChargingInfo->schedule.isTriggerStart = NO; //DS60-120 add
-            pAcChargingInfo->schedule.isTriggerStop = NO;  //DS60-120 add
-            //if( strcmp(whichtask,"CSU task") == EQUAL ) 
-            {
-                gGunIndexInfo.AcIndex++;
-                gGunIndexInfo.AcGunIndex++;
-                pAcChargingInfo->IsAvailable = YES;
-            }
-        } else {
-            result = false;
-        }
-        break;
-
-    case '5': // GB/T AC Plug
-        break;
-
-    case '6': // GB/T AC Socket
-        break;
-    case '7': // CCS2 AC plug
-        break;
-    case '8': // Type E Socket
-        break;
-    //DC Gun Type --------------------------------------------------------------
-    case 'J':  // CHAdeMO
-    case 'K':  // CHAdeMO 200A
-        if (CHAdeMO_QUANTITY > gGunIndexInfo.ChademoIndex) {
-            pDcChargingInfo = (struct ChargingInfoData *)&pSysInfo->ChademoChargingData[gGunIndexInfo.ChademoIndex];
-            pDcChargingInfo->Index = gGunIndexInfo.DcGunIndex;
-            pDcChargingInfo->ReservationId = -1;
-            pDcChargingInfo->slotsIndex = slots;
-            //pDcChargingInfo->SystemStatus = S_BOOTING;
-			//pDcChargingInfo->SystemStatus = S_IDLE;
-            pDcChargingInfo->Type = _Type_Chademo;
-            pDcChargingInfo->type_index = gGunIndexInfo.ChademoIndex;
-            setAcGunTiggerStatus();
-            //if( strcmp(whichtask,"CSU task") == EQUAL ) 
-            {
-                pDcChargingInfo->IsAvailable = YES;
-                gGunIndexInfo.ChademoIndex++;
-                gGunIndexInfo.DcGunIndex++;
-            }
-        } else {
-            result = false;
-        }
-        break;
-
-    case 'V': // Liquid CCS1 combo
-    case 'F': // Liquid CCS2 combo
-    case 'T': // Rema CCS1
-    case 'D': // Rema CCS2
-    case 'U': // CCS1 combo
-    case 'E': // CCS2 combo
-    case 'M': // 80A CCS2
-    case 'N': // 80A CCS1
-    case 'P': // 急電弓
-        if (CCS_QUANTITY > gGunIndexInfo.CcsIndex) {
-            pDcChargingInfo = (struct ChargingInfoData *)&pSysInfo->CcsChargingData[gGunIndexInfo.CcsIndex];
-
-            pDcChargingInfo->Index = gGunIndexInfo.DcGunIndex;
-            pDcChargingInfo->ReservationId = -1;
-            pDcChargingInfo->slotsIndex = slots;
-            //pDcChargingInfo->SystemStatus = S_BOOTING;
-            pDcChargingInfo->Type = _Type_CCS_2;
-            pDcChargingInfo->type_index = gGunIndexInfo.CcsIndex;
-
-            setAcGunTiggerStatus();
-            // 現階段預設為走 DIN70121
-            pCcsData->CommProtocol = _CCS_COMM_V2GMessage_DIN70121;
-            //if( strcmp(whichtask,"CSU task") == EQUAL ) 
-            {
-                pDcChargingInfo->IsAvailable = YES;
-                gGunIndexInfo.CcsIndex++;
-                gGunIndexInfo.DcGunIndex++;
-            }
-            if(typeValue == 'P') {
-                pDcChargingInfo->PantographFlag = YES;
-            } else if (typeValue == 'V') {
-                pDcChargingInfo->CCSGunType = _TYPE_CCS1_Liquid;
-            } else if (typeValue == 'F') {
-                pDcChargingInfo->CCSGunType = _TYPE_CCS2_Liquid;
-            } else if (typeValue == 'T' || typeValue == 'U' || typeValue == 'N') {
-                pDcChargingInfo->CCSGunType = _TYPE_CCS1_Natural;
-            } else if (typeValue == 'D' || typeValue == 'E' || typeValue == 'M') {
-                pDcChargingInfo->CCSGunType = _TYPE_CCS2_Natural;
-            } else
-                pDcChargingInfo->CCSGunType = _TYPE_CCS_NONE;
-        } else {
-            result = false;
-        }
-        break;
-
-    case 'G':  // GBT DC
-    case 'B': // GBT YG PT100
-        if (GB_QUANTITY > gGunIndexInfo.GbIndex) {
-            pDcChargingInfo = (struct ChargingInfoData *)&pSysInfo->GbChargingData[gGunIndexInfo.GbIndex];
-
-            pDcChargingInfo->Index = gGunIndexInfo.DcGunIndex;
-            pDcChargingInfo->ReservationId = -1;
-            pDcChargingInfo->slotsIndex = slots;
-            //pDcChargingInfo->SystemStatus = S_BOOTING;
-            pDcChargingInfo->Type = _Type_GB;
-            pDcChargingInfo->type_index = gGunIndexInfo.GbIndex;
-            setAcGunTiggerStatus();
-            //if( strcmp(whichtask,"CSU task") == EQUAL ) 
-            {
-                pDcChargingInfo->IsAvailable = YES;
-                gGunIndexInfo.GbIndex++;
-                gGunIndexInfo.DcGunIndex++;
-            }
-        } else {
-            result = false;
-        }
-        break;
-
-        //case 'D': // GBT DC x 2
-        //    break;
-
-        //default:
-        //    result = false;
-        //    break;
-    }
-
-    return result;
-}
-
-bool MappingGunChargingInfo(char *whichTask)
-{
-    bool result = true;
-    uint8_t typeIndex = 0;
-    uint8_t slots = 1;
-    uint8_t gunIndex = 0;
-    struct SysConfigData *pSysConfig = NULL;
-    //struct ChargingInfoData *pDcChargingInfo = NULL;
-    struct ChargingInfoData *pAcChargingInfo = NULL;
-
-    if (ShmSysConfigAndInfo == NULL) {
-        log_error("ShmSysConfigAndInfo failed");
-        return false;
-    }
-
-    pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
-
-    if (strlen((char *)pSysConfig->ModelName) < 9) {
-        log_error("Module name length < 9 get %s", (char *)pSysConfig->ModelName);
-        return false;
-    }
-
-    ShmDcCommonData->ChillerValve.MultiChillerGun = 0;
-
-    //printf("1 CheckConnectorTypeStatus\n");
-    for (typeIndex = 7; typeIndex <= 9; typeIndex++) {
-        if (!addGunInfoByConnector(pSysConfig->ModelName[typeIndex], slots, whichTask)) {
-            log_error("%s add gun info failed", whichTask);
-            return false;
-        }
-
-        //確認有幾把水冷槍
-        if (strncmp((char *)&pSysConfig->ModelName[typeIndex], "V", 1) == 0 ||
-                strncmp((char *)&pSysConfig->ModelName[typeIndex], "F", 1) == 0
-           ) {
-            ShmDcCommonData->ChillerValve.MultiChillerGun++; //水冷槍數
-        }
-        slots++;
-    }
-
-    if (ShmDcCommonData->ChillerValve.MultiChillerGun != 0) {
-        ShmDcCommonData->ChillerValve.MultiChillerGun |= 0x80; //有水冷槍標記
-        if (strncmp(whichTask, "CSU Task", 8) == EQUAL) {
-            log_info("get chiller gun = %x, chiller gun count = %d",
-                     (ShmDcCommonData->ChillerValve.MultiChillerGun & 0x80) >> 7,
-                     ShmDcCommonData->ChillerValve.MultiChillerGun & 0x7F);
-        }
-    }
-
-    // AC index 接在 DC 後面
-    //if (AC_QUANTITY > 0) {
-    if (gGunIndexInfo.AcIndex > 0) { //DS60-120 add
-        pAcChargingInfo = (struct ChargingInfoData *)GetAcChargingInfoData(0);
-
-        pAcChargingInfo->Index += gGunIndexInfo.DcGunIndex;
-    }
-
-    pSysConfig->TotalConnectorCount = gGunIndexInfo.DcGunIndex;
-    pSysConfig->AcConnectorCount = gGunIndexInfo.AcGunIndex;
-    if (strcmp(whichTask, "CSU Task") == 0) {
-        log_info("DC connector Quality = %d, AC connector Quality = %d",
-                 pSysConfig->TotalConnectorCount,
-                 pSysConfig->AcConnectorCount);
-    }
-
-    for (gunIndex = 0; gunIndex < pSysConfig->TotalConnectorCount; gunIndex++) {
-        findDcChargingInfoData(gunIndex);
-    }
-
-    findAcChargingInfoData(gunIndex);
-
-    //log_info("Type 0~3 = CHAdeMO, CCS, GB, AC");
-    if (pSysConfig->TotalConnectorCount == 0 && pSysConfig->AcConnectorCount == 0) {
-        log_error("DC %d or AC %d connector failed",
-                  pSysConfig->TotalConnectorCount,
-                  pSysConfig->AcConnectorCount);
-        result = false;
-    }
-
-    return result;
-}
-
-int CreateAllCsuShareMemory(void)
-{
-    int ret = FAIL;
-
-
-    if ((ret = InitSysConfigAndInfoShmMem()) == FAIL) {
-        return ret;
-    }
-
-    if ((ret = InitStatusCodeShmMem()) == FAIL) {
-        return ret;
-    }
-
-    if ((ret = InitPSUDataShmMem()) == FAIL) {
-        return ret;
-    }
-
-    if (CHAdeMO_QUANTITY > 0) {
-        if ((ret = InitCHADeMoShmMem()) == FAIL) {
-            return ret;
-        }
-    }
-
-    if (GB_QUANTITY > 0) {
-        if ((ret = InitGBShmMem()) == FAIL) {
-            return ret;
-        }
-    }
-
-    //creat ShmCcsData
-    if (CCS_QUANTITY > 0) {
-        if ((ret = InitCCSShmMem()) == FAIL) {
-            return ret;
-        }
-    }
-
-    if ((ret = InitPrimaryShmMem()) == FAIL) {
-        return ret;
-    }
-
-    if ((ret = InitFanShmMem()) == FAIL) {
-        return ret;
-    }
-
-    if ((ret = InitRelayShmMem()) == FAIL) {
-        return ret;
-    }
-
-    if ((ret = InitLEDShmMem()) == FAIL) {
-        return ret;
-    }
-
-    if ((ret = InitOCPPShmMem()) == FAIL) {
-        return ret;
-    }
-
-    if ((ret = InitOCPP20ShmMem()) == FAIL) {
-        return ret;
-    }
-
-    if ((ret = InitSelectGunShmMem()) == FAIL) {
-        return ret;
-    }
-
-    if ((ret = InitSelectGunShmMem()) == FAIL) {
-        return ret;
-    }
-
-    if ((ret = InitCommonShmMem()) == FAIL) {
-        return ret;
-    }
-    //ClearAllShmMemParameter();
-
-    //MappingChargingInfoData();
-    //initialShareMemoryParameter();
-    //initialGunIndexToUnUse();
-
-    sleep(1);
-
-    return PASS;
-}
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdint.h>
+#include <string.h>
+#include <stdbool.h>
+
+#include <unistd.h>
+#include <sys/ipc.h>
+#include <sys/shm.h>
+
+#include "../Define/define.h"
+//#include "../AudiCust.h"
+#include "../SelectGun/SelectGun.h"
+#include "../common.h"
+#include "../Log/log.h"
+#include "../Config.h"
+#include "shmMem.h"
+
+//------------------------------------------------------------------------------
+static struct SysConfigAndInfo *ShmSysConfigAndInfo = NULL;
+//static struct SysInfoData *ShmSysInfoData = NULL;
+//static struct SysConfigData *ShmSysConfigData = NULL;
+//static struct WARNING_CODE_INFO *SysWarningInfo = NULL;
+
+static struct StatusCodeData *ShmStatusCodeData = NULL;
+//static struct AlarmCodeData *ShmAlarmCodeData = NULL;
+//static struct FaultCodeData *ShmFaultCodeData = NULL;
+//static struct InfoCodeData  *ShmInfoCodeData = NULL;
+
+static struct PsuData *ShmPsuData = NULL;
+
+static struct CHAdeMOData *ShmCHAdeMOData = NULL;
+static struct GBTData *ShmGBTData = NULL;
+static struct CcsData *ShmCcsData = NULL;
+
+static struct PrimaryMcuData *ShmPrimaryMcuData = NULL;
+static struct FanModuleData *ShmFanModuleData = NULL;
+static struct RelayModuleData *ShmRelayModuleData = NULL;
+static struct LedModuleData *ShmLedModuleData = NULL;
+static struct OCPP16Data *ShmOCPP16Data = NULL;
+static struct OCPP20Data* ShmOCPP20Data = NULL;
+
+static SelectGunInfo *ShmSelectGunInfo = NULL;
+static DcCommonInfo *ShmDcCommonData = NULL;
+
+static struct ChargingInfoData *DcChargingData[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY] = {NULL};
+static struct ChargingInfoData *AcChargingData[AC_QUANTITY] = {NULL};
+
+static GunIndexInfo gGunIndexInfo = {0};
+
+//struct SysConfigData *pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
+//struct SysInfoData *pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
+//struct WARNING_CODE_INFO *pSysWarning = (struct WARNING_CODE_INFO *)GetShmSysWarningInfo();
+
+//struct AlarmCodeData *pAlarmCode = (struct AlarmCodeData *)GetShmAlarmCodeData();
+//struct InfoCodeData *pInfoCode = (struct InfoCodeData *)GetShmInfoCodeData();
+//struct FaultCodeData *pFaultCode = (struct FaultCodeData *)GetShmFaultCodeData();
+
+//struct PsuData *ShmPsuData = (struct PsuData *)GetShmPsuData();
+
+//struct CHAdeMOData *ShmCHAdeMOData = (struct CHAdeMOData *)GetShmCHAdeMOData();
+//struct GBTData *ShmGBTData = (struct GBTData *)GetShmGBTData();
+//struct CcsData *ShmCcsData = (struct CcsData *)GetShmCcsData();
+
+//struct PrimaryMcuData *ShmPrimaryMcuData = (struct PrimaryMcuData *)GetShmPrimaryMcuData();
+//struct FanModuleData *ShmFanModuleData = (struct FanModuleData *)GetShmFanModuleData();
+//struct RelayModuleData *ShmRelayModuleData = (struct RelayModuleData *)GetShmRelayModuleData();
+//struct LedModuleData *ShmLedModuleData = (struct LedModuleData *)GetShmLedModuleData();
+//struct OCPP16Data *ShmOCPP16Data = (struct OCPP16Data *)GetShmOCPP16Data();
+
+//SelectGunInfo *ShmSelectGunInfo = (SelectGunInfo *)GetShmSelectGunInfo();
+//DcCommonInfo *ShmDcCommonData = (DcCommonInfo *)GetShmDcCommonData();
+
+//struct ChargingInfoData *pDcChargingInfo = NULL;
+//struct ChargingInfoData *pAcChargingInfo = NULL;
+
+//------------------------------------------------------------------------------
+void *GetGunIndexInfo(void)
+{
+    return &gGunIndexInfo;
+}
+
+#if 0
+static int findChargingInfoData(uint8_t target, struct ChargingInfoData **chargingData)
+{
+    uint8_t i = 0;
+
+    for (i = 0; i < CHAdeMO_QUANTITY; i++) {
+        if (ShmSysConfigAndInfo->SysInfo.ChademoChargingData[i].Index == target) {
+            chargingData[target] = &ShmSysConfigAndInfo->SysInfo.ChademoChargingData[i];
+            return PASS;
+        }
+    }
+
+    for (i = 0; i < CCS_QUANTITY; i++) {
+        if (ShmSysConfigAndInfo->SysInfo.CcsChargingData[i].Index == target) {
+            log_info("Index = %d, %d", target, ShmSysConfigAndInfo->SysInfo.CcsChargingData[i].Index);
+            chargingData[target] = &ShmSysConfigAndInfo->SysInfo.CcsChargingData[i];
+            return PASS;
+        }
+    }
+
+    for (i = 0; i < GB_QUANTITY; i++) {
+        if (ShmSysConfigAndInfo->SysInfo.GbChargingData[i].Index == target) {
+            chargingData[target] = &ShmSysConfigAndInfo->SysInfo.GbChargingData[i];
+            return PASS;
+        }
+    }
+
+    return FAIL;
+}
+
+void MappingChargingInfoData(void) //DS60-120 add
+{
+    bool isPass = true;
+    uint8_t i = 0;
+
+    while (isPass) {
+        for (i = 0; i < 2; i++) {
+            if (!findChargingInfoData(i, &DcChargingData[0])) {
+                log_error("Find ChargingInfoData failed");
+                isPass = false;
+                break;
+            }
+        }
+        sleep(1);
+    }
+}
+#endif //0
+
+void SetAcChargingInfoData(uint8_t index, struct ChargingInfoData *chargingInfoIndex)
+{
+    AcChargingData[index] = chargingInfoIndex;
+}
+
+void *GetAcChargingInfoData(uint8_t index)
+{
+    return AcChargingData[index];
+}
+
+void SetDcChargingInfoData(uint8_t index, struct ChargingInfoData *chargingInfoIndex)
+{
+    DcChargingData[index] = chargingInfoIndex;
+}
+
+void *GetDcChargingInfoData(uint8_t index)
+{
+    return DcChargingData[index];
+}
+
+void *GetShmSysWarningInfo(void)
+{
+    if (ShmSysConfigAndInfo == NULL) {
+        return NULL;
+    }
+
+    return &ShmSysConfigAndInfo->SysWarningInfo;
+}
+
+void *GetShmSysConfigData(void)
+{
+    if (ShmSysConfigAndInfo == NULL) {
+        return NULL;
+    }
+
+    return &ShmSysConfigAndInfo->SysConfig;
+}
+
+void *GetShmSysInfoData(void)
+{
+    if (ShmSysConfigAndInfo == NULL) {
+        return NULL;
+    }
+
+    return &ShmSysConfigAndInfo->SysInfo;
+}
+
+void *GetShmSysConfigAndInfo(void)
+{
+    if (ShmSysConfigAndInfo == NULL) {
+        return NULL;
+    }
+
+    return ShmSysConfigAndInfo;
+}
+
+void *GetShmInfoCodeData(void)
+{
+    if (ShmStatusCodeData == NULL) {
+        return NULL;
+    }
+
+    return &ShmStatusCodeData->InfoCode;
+}
+
+void *GetShmFaultCodeData(void)
+{
+    if (ShmStatusCodeData == NULL) {
+        return NULL;
+    }
+
+    return &ShmStatusCodeData->FaultCode;
+}
+
+void *GetShmAlarmCodeData(void)
+{
+    if (ShmStatusCodeData == NULL) {
+        return NULL;
+    }
+
+    return &ShmStatusCodeData->AlarmCode;
+}
+
+void *GetShmStatusCodeData(void)
+{
+    if (ShmStatusCodeData == NULL) {
+        return NULL;
+    }
+
+    return ShmStatusCodeData;
+}
+
+void *GetShmPsuData(void)
+{
+    if (ShmPsuData == NULL) {
+        return NULL;
+    }
+
+    return ShmPsuData;
+}
+
+void *GetShmCHAdeMOData(void)
+{
+    if (ShmCHAdeMOData == NULL) {
+        return NULL;
+    }
+
+    return ShmCHAdeMOData;
+}
+
+void *GetShmGBTData(void)
+{
+    if (ShmGBTData == NULL) {
+        return NULL;
+    }
+
+    return ShmGBTData;
+}
+
+void *GetShmCcsData(void)
+{
+    if (ShmCcsData == NULL) {
+        return NULL;
+    }
+
+    return ShmCcsData;
+}
+
+void *GetShmPrimaryMcuData(void)
+{
+    if (ShmPrimaryMcuData == NULL) {
+        return NULL;
+    }
+
+    return ShmPrimaryMcuData;
+}
+
+void *GetShmFanModuleData(void)
+{
+    if (ShmFanModuleData == NULL) {
+        return NULL;
+    }
+
+    return ShmFanModuleData;
+}
+
+void *GetShmRelayModuleData(void)
+{
+    if (ShmRelayModuleData == NULL) {
+        return NULL;
+    }
+
+    return ShmRelayModuleData;
+}
+
+void *GetShmLedModuleData(void)
+{
+    if (ShmLedModuleData == NULL) {
+        return NULL;
+    }
+
+    return ShmLedModuleData;
+}
+
+void *GetShmOCPP16Data(void)
+{
+    if (ShmOCPP16Data == NULL) {
+        return NULL;
+    }
+
+    return ShmOCPP16Data;
+}
+
+void* GetShmOCPP20Data(void)
+{
+    if (ShmOCPP20Data == NULL) {
+        return NULL;
+    }
+
+    return ShmOCPP20Data;
+}
+
+void *GetShmSelectGunInfo(void)
+{
+    if (ShmSelectGunInfo == NULL) {
+        return NULL;
+    }
+
+    return ShmSelectGunInfo;
+}
+
+void *GetShmDcCommonData(void)
+{
+    if (ShmDcCommonData == NULL) {
+        return NULL;
+    }
+
+    return ShmDcCommonData;
+}
+
+//------------------------------------------------------------------------------
+static void initialGunIndexToUnUse(void)
+{
+    uint8_t index = 0;
+    struct SysInfoData *pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
+
+    for (index = 0; index < CHAdeMO_QUANTITY; index++) {
+        pSysInfo->ChademoChargingData[index].Index = NO_DEFINE;
+    }
+
+    for (index = 0; index < CCS_QUANTITY; index++) {
+        pSysInfo->CcsChargingData[index].Index = NO_DEFINE;
+    }
+
+    for (index = 0; index < GB_QUANTITY; index++) {
+        pSysInfo->GbChargingData[index].Index = NO_DEFINE;
+    }
+
+    for (index = 0; index < AC_QUANTITY; index++) {
+        pSysInfo->AcChargingData[index].Index = NO_DEFINE;
+    }
+}
+
+void InitialShareMemoryInfo(void)
+{
+    FILE *fp = NULL;
+    char cmd[512] = {0};
+    char buf[512] = {0};
+    struct SysConfigData *pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
+    struct SysInfoData *pSysInfo     = (struct SysInfoData *)GetShmSysInfoData();
+    struct AlarmCodeData *pAlarmCode = (struct AlarmCodeData *)GetShmAlarmCodeData();
+
+    //SysConfig init
+    sprintf((char *)pSysConfig->TelecomInterface.TelcomApn, "Internet");
+    sprintf((char *)pSysConfig->TelecomInterface.TelcomChapPapId, " ");
+    sprintf((char *)pSysConfig->TelecomInterface.TelcomChapPapPwd, " ");
+
+    pSysConfig->TotalConnectorCount = 0;
+    pSysConfig->AcConnectorCount = 0;
+
+    memcpy(pSysInfo->CsuBootLoadFwRev,
+           pSysConfig->CsuBootLoadFwRev,
+           ARRAY_SIZE(pSysConfig->CsuBootLoadFwRev));
+
+    strcpy((char *) pSysConfig->UserId, "");
+    pSysConfig->QRCodeMadeMode = NO; //DS60-120 add
+    pSysConfig->SwitchDebugFlag = NO;
+    pSysConfig->AlwaysGfdFlag = NO;
+
+    //SysInfo init
+    pSysInfo->FactoryConfiguration = 0;
+    pSysInfo->InputVoltageR = 0;
+    pSysInfo->InputVoltageS = 0;
+    pSysInfo->InputVoltageT = 0;
+    pSysInfo->SystemFanRotaSpeed = 0;
+    pSysInfo->PsuFanRotaSpeed = 0;
+    pSysInfo->AuxPower5V = 0;
+    pSysInfo->AuxPower12V = 0;
+    pSysInfo->AuxPower24V = 0;
+    pSysInfo->AuxPower48V = 0;
+
+    sprintf((char *)pSysInfo->CsuHwRev, "REV:5.0");
+
+    sprintf(cmd, "/bin/uname -r");
+    fp = popen(cmd, "r");
+    if (fp == NULL) {
+        sprintf((char *)pSysInfo->CsuKernelFwRev, "Unknown version");
+    } else {
+        while (fgets(buf, sizeof(buf), fp) != NULL) {
+            strcpy((char *)pSysInfo->CsuKernelFwRev, buf);
+        }
+    }
+
+    // 雙槍 CCS + Chademo
+    //getFirmwareVersion();
+
+    //sprintf((char *) pSysInfo->CsuRootFsFwRev, fwVersion);
+    sprintf((char *) pSysInfo->CsuPrimFwRev, " ");
+
+    sprintf((char *)pSysInfo->LcmHwRev, " ");
+    sprintf((char *)pSysInfo->LcmFwRev, " ");
+    sprintf((char *)pSysInfo->PsuHwRev, " ");
+    sprintf((char *)pSysInfo->PsuPrimFwRev, " ");
+    sprintf((char *)pSysInfo->PsuSecFwRev, " ");
+    sprintf((char *)pSysInfo->AuxPwrHwRev, " ");
+    sprintf((char *)pSysInfo->AuxPwrFwRev, " ");
+    sprintf((char *)pSysInfo->FanModuleHwRev, " ");
+    sprintf((char *)pSysInfo->FanModuleFwRev, " ");
+    sprintf((char *)pSysInfo->RelayModuleHwRev, " ");
+    sprintf((char *)pSysInfo->RelayModuleFwRev, " ");
+    sprintf((char *)pSysInfo->TelcomModemFwRev, " ");
+    pSysInfo->SystemAmbientTemp = 0;
+    pSysInfo->SystemCriticalTemp = 0;
+    pSysInfo->PsuAmbientTemp = 0;
+    pSysInfo->CcsConnectorTemp = 0;
+    pSysInfo->InternetConn = 0;
+    pSysInfo->OcppConnStatus = 0;
+    pSysInfo->OrderCharging = NO_DEFINE;
+
+    memset(pSysInfo->FanModuleFwRev, 0, ARRAY_SIZE(pSysInfo->FanModuleFwRev));
+    memset(pSysInfo->RelayModuleFwRev, 0, ARRAY_SIZE(pSysInfo->RelayModuleFwRev));
+
+    pSysInfo->SystemPage = _PAGE_IDLE;
+
+    pSysInfo->MainChargingMode = _MAIN_CHARGING_MODE_MAX;
+    pSysInfo->ReAssignedFlag = _REASSIGNED_NONE;
+    pSysInfo->CurGunSelectedByAc = NO_DEFINE;
+    pSysInfo->BootingStatus = BOOTTING; //DS60-120 add
+
+    //other board init
+    ShmPrimaryMcuData->SelfTest_Comp = NO;
+    ShmRelayModuleData->SelfTest_Comp = NO;
+    ShmFanModuleData->SelfTest_Comp = NO;
+    ShmLedModuleData->SelfTest_Comp = NO;
+    ShmFanModuleData->TestFanSpeed = 0;
+
+    //status code init
+    pAlarmCode->AlarmEvents.bits.RelayboardStestFail = NO;
+    pAlarmCode->AlarmEvents.bits.FanboardStestFail = NO;
+    pAlarmCode->AlarmEvents.bits.PrimaryStestFail = NO;
+    pAlarmCode->AlarmEvents.bits.LedboardStestFail = NO; //DS60-120 Add
+    pAlarmCode->AlarmEvents.bits.ChademoboardStestFail = NO;
+    pAlarmCode->AlarmEvents.bits.CCSboardStestFail = NO;
+    pAlarmCode->AlarmEvents.bits.AcContactStestFail = NO;
+    pAlarmCode->AlarmEvents.bits.PsuModuleStestFail = NO;
+    pAlarmCode->AlarmEvents.bits.PsuDipSwitchStestFail = NO; //DS60-120 Add
+    pAlarmCode->AlarmEvents.bits.ModelNameNoneMatchStestFail = NO;
+    pAlarmCode->AlarmEvents.bits.PsuNoResource = NO;
+    pAlarmCode->AlarmEvents.bits.FailToCreateShareMemory = NO;
+
+    initialGunIndexToUnUse();//DS60-120 add
+
+    //ShmDcCommonData->CcsVersion = _CCS_VERSION_CHECK_TAG_V015S0;
+    //ShmDcCommonData->psuKeepCommunication = NO;
+    //ShmDcCommonData->acContactSwitch = NO;
+    ShmDcCommonData->ConnectErrList[0].GunErrMessage = 0;
+    ShmDcCommonData->ConnectErrList[1].GunErrMessage = 0;
+    ShmDcCommonData->TestTemperature = NO;
+    //ShmDcCommonData->LcmFwVersion = 0;
+}
+
+int InitSelectGunShmMem(void)
+{
+    int MeterSMId = FAIL;
+
+#if !defined DD360Tcci && !defined DD360Audi && !defined DD360ComBox && !defined DD360UCar
+    return;
+#endif //!defined DD360Tcci && !defined DD360Audi && !defined DD360ComBox
+
+    if ((MeterSMId = shmget(ShmSelectGunInfoKey, sizeof(SelectGunInfo), IPC_CREAT | 0777)) < 0) {
+        return FAIL;
+    } else if ((ShmSelectGunInfo = shmat(MeterSMId, NULL, 0)) == (void *) - 1) {
+        return FAIL;
+    }
+
+    return PASS;
+}
+
+int InitCommonShmMem(void)
+{
+    int MeterSMId = FAIL;
+
+    if ((MeterSMId = shmget(ShmCommonKey, sizeof(DcCommonInfo), IPC_CREAT | 0777)) < 0) {
+        return FAIL;
+    } else if ((ShmDcCommonData = shmat(MeterSMId, NULL, 0)) == (void *) - 1) {
+        return FAIL;
+    }
+
+    return PASS;
+}
+
+//int InitCSUMeterShmMem(void)
+//{
+//    int MeterSMId = FAIL;
+//
+//    if ((MeterSMId = shmget(ShmCsuMeterKey, sizeof(struct MeterInformation), IPC_CREAT | 0777)) < 0) {
+//        return FAIL;
+//    } else if ((ShmCsuMeterInfo = shmat(MeterSMId, NULL, 0)) == (void *) - 1) {
+//        return FAIL;
+//    }
+//
+//    return PASS;
+//}
+
+int InitOCPPShmMem(void)
+{
+    int MeterSMId = FAIL;
+
+    if ((MeterSMId = shmget(ShmOcppModuleKey, sizeof(struct OCPP16Data), IPC_CREAT | 0777)) < 0) {
+        log_info("Get OCPP share memory error");
+        return FAIL;
+    } else if ((ShmOCPP16Data = shmat(MeterSMId, NULL, 0)) == (void *) - 1) {
+        log_info("Create OCPP share memory error");
+        return FAIL;
+    }
+
+    return PASS;
+}
+
+int InitOCPP20ShmMem(void)
+{
+    int MeterSMId = FAIL;
+
+    if ((MeterSMId = shmget(ShmOcpp20ModuleKey, sizeof(struct OCPP20Data), IPC_CREAT | 0777)) < 0) {
+        log_info("Get OCPP20 share memory error");
+        return FAIL;
+    } else if ((ShmOCPP20Data = shmat(MeterSMId, NULL, 0)) == (void*)-1) {
+        log_info("Create OCPP20 share memory error");
+        return FAIL;
+    }
+
+    return PASS;
+}
+
+int InitLEDShmMem(void)
+{
+    int MeterSMId = FAIL;
+
+    if ((MeterSMId = shmget(ShmLedBdKey, sizeof(struct LedModuleData), IPC_CREAT | 0777)) < 0) {
+        return FAIL;
+    } else if ((ShmLedModuleData = shmat(MeterSMId, NULL, 0)) == (void *) - 1) {
+        return FAIL;
+    }
+
+    return PASS;
+}
+
+int InitRelayShmMem(void)
+{
+    int MeterSMId = FAIL;
+
+    if ((MeterSMId = shmget(ShmRelayBdKey, sizeof(struct RelayModuleData),  IPC_CREAT | 0777)) < 0) {
+        return FAIL;
+    } else if ((ShmRelayModuleData = shmat(MeterSMId, NULL, 0)) == (void *) - 1) {
+        return FAIL;
+    }
+
+    return PASS;
+}
+
+int InitFanShmMem(void)
+{
+    int MeterSMId = FAIL;
+
+    if ((MeterSMId = shmget(ShmFanBdKey, sizeof(struct FanModuleData),  IPC_CREAT | 0777)) < 0) {
+        return FAIL;
+    } else if ((ShmFanModuleData = shmat(MeterSMId, NULL, 0)) == (void *) - 1) {
+        return FAIL;
+    }
+
+    return PASS;
+}
+
+int InitPrimaryShmMem(void)
+{
+    int MeterSMId = FAIL;
+
+    if ((MeterSMId = shmget(ShmPrimaryMcuKey, sizeof(struct PrimaryMcuData), IPC_CREAT | 0777)) < 0) {
+        return FAIL;
+    } else if ((ShmPrimaryMcuData = shmat(MeterSMId, NULL, 0)) == (void *) - 1) {
+        return FAIL;
+    }
+
+    return PASS;
+}
+
+int InitCCSShmMem(void)
+{
+    int MeterSMId = FAIL;
+
+    if ((MeterSMId = shmget(ShmCcsCommKey, sizeof(struct CcsData),  IPC_CREAT | 0777)) < 0) {
+        return FAIL;
+    } else if ((ShmCcsData = shmat(MeterSMId, NULL, 0)) == (void *) - 1) {
+        return FAIL;
+    }
+
+    return PASS;
+}
+
+int InitGBShmMem(void)
+{
+    int MeterSMId = FAIL;
+
+    if ((MeterSMId = shmget(ShmGBTCommKey, sizeof(struct GBTData),  IPC_CREAT | 0777)) < 0) {
+        return FAIL;
+    } else if ((ShmGBTData = shmat(MeterSMId, NULL, 0)) == (void *) - 1) {
+        return FAIL;
+    }
+
+    return PASS;
+}
+
+int InitCHADeMoShmMem(void)
+{
+    int MeterSMId = FAIL;
+
+    if ((MeterSMId = shmget(ShmCHAdeMOCommKey, sizeof(struct CHAdeMOData),  IPC_CREAT | 0777)) < 0) {
+        return FAIL;
+    } else if ((ShmCHAdeMOData = shmat(MeterSMId, NULL, 0)) == (void *) - 1) {
+        return FAIL;
+    }
+    return PASS;
+}
+
+int InitPSUDataShmMem(void)
+{
+    int MeterSMId = FAIL;
+
+    //creat ShmPsuData
+    if ((MeterSMId = shmget(ShmPsuKey, sizeof(struct PsuData), IPC_CREAT | 0777)) < 0) {
+        return FAIL;
+    } else if ((ShmPsuData = shmat(MeterSMId, NULL, 0)) == (void *) - 1) {
+        return FAIL;
+    }
+
+    return PASS;
+}
+
+int InitStatusCodeShmMem(void)
+{
+    int MeterSMId = FAIL;
+
+    if ((MeterSMId = shmget(ShmStatusCodeKey, sizeof(struct StatusCodeData), IPC_CREAT | 0777)) < 0) {
+        return FAIL;
+    } else if ((ShmStatusCodeData = shmat(MeterSMId, NULL, 0)) == (void *) - 1) {
+        return FAIL;
+    }
+
+    return PASS;
+}
+
+int InitSysConfigAndInfoShmMem(void)
+{
+    int MeterSMId = FAIL;
+
+    if ((MeterSMId = shmget(ShmSysConfigAndInfoKey, sizeof(struct SysConfigAndInfo), IPC_CREAT | 0777)) < 0) {
+        printf("1 InitSysConfigAndInfoShmMem");
+        return FAIL;
+    } else if ((ShmSysConfigAndInfo = shmat(MeterSMId, NULL, 0))  == (void *) - 1) {
+        printf("2 InitSysConfigAndInfoShmMem");
+        return FAIL;
+    }
+
+    return PASS;
+}
+
+void ClearAllShmMemParameter(void)
+{
+    uint8_t i = 0;
+
+    memset(ShmSysConfigAndInfo, 0, sizeof(struct SysConfigAndInfo));
+    memset(ShmStatusCodeData, 0, sizeof(struct StatusCodeData));
+    memset(ShmPsuData, 0, sizeof(struct PsuData));
+
+    if (CHAdeMO_QUANTITY > 0) {
+        memset(ShmCHAdeMOData, 0, sizeof(struct CHAdeMOData));
+    }
+
+    if (GB_QUANTITY > 0) {
+        memset(ShmGBTData, 0, sizeof(struct GBTData));
+    }
+
+    if (CCS_QUANTITY > 0) {
+        memset(ShmCcsData, 0, sizeof(struct CcsData));
+    }
+
+    memset(ShmPrimaryMcuData, 0, sizeof(struct PrimaryMcuData));
+    memset(ShmFanModuleData, 0, sizeof(struct FanModuleData));
+    memset(ShmRelayModuleData, 0, sizeof(struct RelayModuleData));
+    memset(ShmLedModuleData, 0, sizeof(struct LedModuleData));
+    //memset(ShmOCPP16Data,0,sizeof(struct OCPP16Data));
+
+    //memset(ShmCsuMeterInfo, 0, sizeof(struct MeterInformation));
+    memset(ShmDcCommonData, 0, sizeof(DcCommonInfo));
+
+#if defined DD360Tcci || defined DD360Audi || defined DD360ComBox || defined DD360UCar
+    memset(ShmSelectGunInfo, 0, sizeof(SelectGunInfo));
+
+    for (i = 0; i < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; i++) {
+        ShmSelectGunInfo->PricesInfo[i].Balance = FAIL_BALANCE_PRICES;
+    }
+#endif //defined DD360Tcci || defined DD360Audi || defined DD360ComBox
+}
+
+static void setAcGunTiggerStatus(void)
+{
+    struct ChargingInfoData *pAcChargingInfo = NULL;
+
+    if (gGunIndexInfo.AcGunIndex == 0) {
+        return;
+    }
+
+    pAcChargingInfo = (struct ChargingInfoData *)GetAcChargingInfoData(gGunIndexInfo.AcGunIndex);
+
+    pAcChargingInfo->schedule.isTriggerStart = NO; //DS60-120 add
+    pAcChargingInfo->schedule.isTriggerStop = NO;  //DS60-120 add
+}
+
+static int findAcChargingInfoData(uint8_t gunIndex)
+{
+    struct SysInfoData *pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
+    //acChargingData[gunIndex] = &pSysInfo->AcChargingData[0];
+    SetAcChargingInfoData(gunIndex, &pSysInfo->AcChargingData[0]);
+
+    return PASS;
+}
+
+static int findDcChargingInfoData(uint8_t gunIndex)
+{
+    uint8_t i = 0;
+    struct SysInfoData *pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
+
+    //printf("Chademo count = %d\n", gGunIndexInfo.ChademoIndex);
+    for (i = 0; i < gGunIndexInfo.DcGunIndex; i++) {
+        if (pSysInfo->ChademoChargingData[i].Index == gunIndex) {
+            //printf("chademo index = %d, %d\n", pSysInfo->ChademoChargingData[i].Index, gunIndex);
+            //dcChargingData[gunIndex] = &pSysInfo->ChademoChargingData[i];
+            SetDcChargingInfoData(pSysInfo->ChademoChargingData[i].Index, &pSysInfo->ChademoChargingData[i]);
+            return PASS;
+        }
+    }
+
+    //printf("ccs count = %d\n", gGunIndexInfo.CcsIndex);
+    for (i = 0; i < gGunIndexInfo.DcGunIndex; i++) {
+        if (pSysInfo->CcsChargingData[i].Index == gunIndex) {
+            //printf("ccs index = %d, %d\n", pSysInfo->CcsChargingData[i].Index, gunIndex);
+            //dcChargingData[gunIndex] = (struct ChargingInfoData *)&pSysInfo->CcsChargingData[i];
+            SetDcChargingInfoData(pSysInfo->CcsChargingData[i].Index, &pSysInfo->CcsChargingData[i]);
+            return PASS;
+        }
+    }
+
+    for (i = 0; i < gGunIndexInfo.DcGunIndex; i++) {
+        if (pSysInfo->GbChargingData[i].Index == gunIndex) {
+            //dcChargingData[gunIndex] = &pSysInfo->GbChargingData[i];
+            SetDcChargingInfoData(pSysInfo->GbChargingData[i].Index, &pSysInfo->GbChargingData[i]);
+            return PASS;
+        }
+    }
+
+    return FAIL;
+}
+
+static bool addGunInfoByConnector(uint8_t typeValue, uint8_t slots,char *whichtask)
+{
+    bool result = true;
+    struct SysInfoData *pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
+    struct ChargingInfoData *pDcChargingInfo = NULL;
+    struct ChargingInfoData *pAcChargingInfo = (struct ChargingInfoData *)GetAcChargingInfoData(gGunIndexInfo.AcGunIndex);
+    struct CcsData *pCcsData = (struct CcsData *)GetShmCcsData();
+
+    switch (typeValue) {
+    // AC Gun Type -------------------------------------------------------------
+    case '0': // none
+        break;
+
+    case '1': // IEC 62196-2 Type 1/SAE J1772 Plug
+        break;
+
+    case '2': // IEC 62196-2 Type 1/SAE J1772 Socket
+        break;
+
+    case '3': // IEC 62196-2 Type 2 Plug
+    case '4': // IEC 62196-2 Type 2 Socket
+        if (AC_QUANTITY > gGunIndexInfo.AcIndex) {
+            pAcChargingInfo = (struct ChargingInfoData *)&pSysInfo->AcChargingData[gGunIndexInfo.AcIndex];
+
+            // AC 固定 index
+            pAcChargingInfo->Index = 0;
+            pAcChargingInfo->ReservationId = -1;
+            pAcChargingInfo->SystemStatus = S_IDLE;
+            pAcChargingInfo->Type = _Type_AC;
+            pAcChargingInfo->schedule.isTriggerStart = NO; //DS60-120 add
+            pAcChargingInfo->schedule.isTriggerStop = NO;  //DS60-120 add
+            //if( strcmp(whichtask,"CSU task") == EQUAL ) 
+            {
+                gGunIndexInfo.AcIndex++;
+                gGunIndexInfo.AcGunIndex++;
+                pAcChargingInfo->IsAvailable = YES;
+            }
+        } else {
+            result = false;
+        }
+        break;
+
+    case '5': // GB/T AC Plug
+        break;
+
+    case '6': // GB/T AC Socket
+        break;
+    case '7': // CCS2 AC plug
+        break;
+    case '8': // Type E Socket
+        break;
+    //DC Gun Type --------------------------------------------------------------
+    case 'J':  // CHAdeMO
+    case 'K':  // CHAdeMO 200A
+        if (CHAdeMO_QUANTITY > gGunIndexInfo.ChademoIndex) {
+            pDcChargingInfo = (struct ChargingInfoData *)&pSysInfo->ChademoChargingData[gGunIndexInfo.ChademoIndex];
+            pDcChargingInfo->Index = gGunIndexInfo.DcGunIndex;
+            pDcChargingInfo->ReservationId = -1;
+            pDcChargingInfo->slotsIndex = slots;
+            //pDcChargingInfo->SystemStatus = S_BOOTING;
+			//pDcChargingInfo->SystemStatus = S_IDLE;
+            pDcChargingInfo->Type = _Type_Chademo;
+            pDcChargingInfo->type_index = gGunIndexInfo.ChademoIndex;
+            setAcGunTiggerStatus();
+            //if( strcmp(whichtask,"CSU task") == EQUAL ) 
+            {
+                pDcChargingInfo->IsAvailable = YES;
+                gGunIndexInfo.ChademoIndex++;
+                gGunIndexInfo.DcGunIndex++;
+            }
+        } else {
+            result = false;
+        }
+        break;
+
+    case 'V': // Liquid CCS1 combo
+    case 'F': // Liquid CCS2 combo
+    case 'T': // Rema CCS1
+    case 'D': // Rema CCS2
+    case 'U': // CCS1 combo
+    case 'E': // CCS2 combo
+    case 'M': // 80A CCS2
+    case 'N': // 80A CCS1
+    case 'P': // 急電弓
+        if (CCS_QUANTITY > gGunIndexInfo.CcsIndex) {
+            pDcChargingInfo = (struct ChargingInfoData *)&pSysInfo->CcsChargingData[gGunIndexInfo.CcsIndex];
+
+            pDcChargingInfo->Index = gGunIndexInfo.DcGunIndex;
+            pDcChargingInfo->ReservationId = -1;
+            pDcChargingInfo->slotsIndex = slots;
+            //pDcChargingInfo->SystemStatus = S_BOOTING;
+            pDcChargingInfo->Type = _Type_CCS_2;
+            pDcChargingInfo->type_index = gGunIndexInfo.CcsIndex;
+
+            setAcGunTiggerStatus();
+            // 現階段預設為走 DIN70121
+            pCcsData->CommProtocol = _CCS_COMM_V2GMessage_DIN70121;
+            //if( strcmp(whichtask,"CSU task") == EQUAL ) 
+            {
+                pDcChargingInfo->IsAvailable = YES;
+                gGunIndexInfo.CcsIndex++;
+                gGunIndexInfo.DcGunIndex++;
+            }
+            if(typeValue == 'P') {
+                pDcChargingInfo->PantographFlag = YES;
+            } else if (typeValue == 'V') {
+                pDcChargingInfo->CCSGunType = _TYPE_CCS1_Liquid;
+            } else if (typeValue == 'F') {
+                pDcChargingInfo->CCSGunType = _TYPE_CCS2_Liquid;
+            } else if (typeValue == 'T' || typeValue == 'U' || typeValue == 'N') {
+                pDcChargingInfo->CCSGunType = _TYPE_CCS1_Natural;
+            } else if (typeValue == 'D' || typeValue == 'E' || typeValue == 'M') {
+                pDcChargingInfo->CCSGunType = _TYPE_CCS2_Natural;
+            } else
+                pDcChargingInfo->CCSGunType = _TYPE_CCS_NONE;
+        } else {
+            result = false;
+        }
+        break;
+
+    case 'G':  // GBT DC
+    case 'B': // GBT YG PT100
+        if (GB_QUANTITY > gGunIndexInfo.GbIndex) {
+            pDcChargingInfo = (struct ChargingInfoData *)&pSysInfo->GbChargingData[gGunIndexInfo.GbIndex];
+
+            pDcChargingInfo->Index = gGunIndexInfo.DcGunIndex;
+            pDcChargingInfo->ReservationId = -1;
+            pDcChargingInfo->slotsIndex = slots;
+            //pDcChargingInfo->SystemStatus = S_BOOTING;
+            pDcChargingInfo->Type = _Type_GB;
+            pDcChargingInfo->type_index = gGunIndexInfo.GbIndex;
+            setAcGunTiggerStatus();
+            //if( strcmp(whichtask,"CSU task") == EQUAL ) 
+            {
+                pDcChargingInfo->IsAvailable = YES;
+                gGunIndexInfo.GbIndex++;
+                gGunIndexInfo.DcGunIndex++;
+            }
+        } else {
+            result = false;
+        }
+        break;
+
+        //case 'D': // GBT DC x 2
+        //    break;
+
+        //default:
+        //    result = false;
+        //    break;
+    }
+
+    return result;
+}
+
+bool MappingGunChargingInfo(char *whichTask)
+{
+    bool result = true;
+    uint8_t typeIndex = 0;
+    uint8_t slots = 1;
+    uint8_t gunIndex = 0;
+    struct SysConfigData *pSysConfig = NULL;
+    //struct ChargingInfoData *pDcChargingInfo = NULL;
+    struct ChargingInfoData *pAcChargingInfo = NULL;
+
+    if (ShmSysConfigAndInfo == NULL) {
+        log_error("ShmSysConfigAndInfo failed");
+        return false;
+    }
+
+    pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
+
+    if (strlen((char *)pSysConfig->ModelName) < 9) {
+        log_error("Module name length < 9 get %s", (char *)pSysConfig->ModelName);
+        return false;
+    }
+
+    ShmDcCommonData->ChillerValve.MultiChillerGun = 0;
+
+    //printf("1 CheckConnectorTypeStatus\n");
+    for (typeIndex = 7; typeIndex <= 9; typeIndex++) {
+        if (!addGunInfoByConnector(pSysConfig->ModelName[typeIndex], slots, whichTask)) {
+            log_error("%s add gun info failed", whichTask);
+            return false;
+        }
+
+        //確認有幾把水冷槍
+        if (strncmp((char *)&pSysConfig->ModelName[typeIndex], "V", 1) == 0 ||
+                strncmp((char *)&pSysConfig->ModelName[typeIndex], "F", 1) == 0
+           ) {
+            ShmDcCommonData->ChillerValve.MultiChillerGun++; //水冷槍數
+        }
+        slots++;
+    }
+
+    if (ShmDcCommonData->ChillerValve.MultiChillerGun != 0) {
+        ShmDcCommonData->ChillerValve.MultiChillerGun |= 0x80; //有水冷槍標記
+        if (strncmp(whichTask, "CSU Task", 8) == EQUAL) {
+            log_info("get chiller gun = %x, chiller gun count = %d",
+                     (ShmDcCommonData->ChillerValve.MultiChillerGun & 0x80) >> 7,
+                     ShmDcCommonData->ChillerValve.MultiChillerGun & 0x7F);
+        }
+    }
+
+    // AC index 接在 DC 後面
+    //if (AC_QUANTITY > 0) {
+    if (gGunIndexInfo.AcIndex > 0) { //DS60-120 add
+        pAcChargingInfo = (struct ChargingInfoData *)GetAcChargingInfoData(0);
+
+        pAcChargingInfo->Index += gGunIndexInfo.DcGunIndex;
+    }
+
+    pSysConfig->TotalConnectorCount = gGunIndexInfo.DcGunIndex;
+    pSysConfig->AcConnectorCount = gGunIndexInfo.AcGunIndex;
+    if (strcmp(whichTask, "CSU Task") == 0) {
+        log_info("DC connector Quality = %d, AC connector Quality = %d",
+                 pSysConfig->TotalConnectorCount,
+                 pSysConfig->AcConnectorCount);
+    }
+
+    for (gunIndex = 0; gunIndex < pSysConfig->TotalConnectorCount; gunIndex++) {
+        findDcChargingInfoData(gunIndex);
+    }
+
+    findAcChargingInfoData(gunIndex);
+
+    //log_info("Type 0~3 = CHAdeMO, CCS, GB, AC");
+    if (pSysConfig->TotalConnectorCount == 0 && pSysConfig->AcConnectorCount == 0) {
+        log_error("DC %d or AC %d connector failed",
+                  pSysConfig->TotalConnectorCount,
+                  pSysConfig->AcConnectorCount);
+        result = false;
+    }
+
+    return result;
+}
+
+int CreateAllCsuShareMemory(void)
+{
+    int ret = FAIL;
+
+
+    if ((ret = InitSysConfigAndInfoShmMem()) == FAIL) {
+        return ret;
+    }
+
+    if ((ret = InitStatusCodeShmMem()) == FAIL) {
+        return ret;
+    }
+
+    if ((ret = InitPSUDataShmMem()) == FAIL) {
+        return ret;
+    }
+
+    if (CHAdeMO_QUANTITY > 0) {
+        if ((ret = InitCHADeMoShmMem()) == FAIL) {
+            return ret;
+        }
+    }
+
+    if (GB_QUANTITY > 0) {
+        if ((ret = InitGBShmMem()) == FAIL) {
+            return ret;
+        }
+    }
+
+    //creat ShmCcsData
+    if (CCS_QUANTITY > 0) {
+        if ((ret = InitCCSShmMem()) == FAIL) {
+            return ret;
+        }
+    }
+
+    if ((ret = InitPrimaryShmMem()) == FAIL) {
+        return ret;
+    }
+
+    if ((ret = InitFanShmMem()) == FAIL) {
+        return ret;
+    }
+
+    if ((ret = InitRelayShmMem()) == FAIL) {
+        return ret;
+    }
+
+    if ((ret = InitLEDShmMem()) == FAIL) {
+        return ret;
+    }
+
+    if ((ret = InitOCPPShmMem()) == FAIL) {
+        return ret;
+    }
+
+    if ((ret = InitOCPP20ShmMem()) == FAIL) {
+        return ret;
+    }
+
+    if ((ret = InitSelectGunShmMem()) == FAIL) {
+        return ret;
+    }
+
+    if ((ret = InitSelectGunShmMem()) == FAIL) {
+        return ret;
+    }
+
+    if ((ret = InitCommonShmMem()) == FAIL) {
+        return ret;
+    }
+    //ClearAllShmMemParameter();
+
+    //MappingChargingInfoData();
+    //initialShareMemoryParameter();
+    //initialGunIndexToUnUse();
+
+    sleep(1);
+
+    return PASS;
+}

+ 72 - 72
EVSE/Projects/DD360Tcci/Apps/ShareMemory/shmMem.h

@@ -1,72 +1,72 @@
-#ifndef _CSU_SHARE_MEMORY_H_
-#define _CSU_SHARE_MEMORY_H_
-
-#include <stdint.h>
-#include <stdbool.h>
-#include "../Define/define.h"
-
-//------------------------------------------------------------------------------
-#define ShmCsuMeterKey          2001
-#define ShmCommonKey            2002
-
-//------------------------------------------------------------------------------
-typedef struct StGunIndexInfo {
-    volatile uint8_t AcIndex;    //AC Gun Count
-    volatile uint8_t AcGunIndex; //AC type index
-
-    volatile uint8_t DcGunIndex; //DC gun Count
-
-    //DC gun type index
-    volatile uint8_t ChademoIndex;
-    volatile uint8_t CcsIndex;
-    volatile uint8_t GbIndex;
-} GunIndexInfo;
-
-//------------------------------------------------------------------------------
-void *GetGunIndexInfo(void);
-bool MappingGunChargingInfo(char *whichTask);
-
-int CreateAllCsuShareMemory(void);
-void ClearAllShmMemParameter(void);
-void InitialShareMemoryInfo(void);
-
-void SetDcChargingInfoData(uint8_t index, struct ChargingInfoData *chargingInfoIndex);
-void *GetDcChargingInfoData(uint8_t index);
-
-void SetAcChargingInfoData(uint8_t index, struct ChargingInfoData *chargingInfoIndex);
-void *GetAcChargingInfoData(uint8_t index);
-
-void *GetShmSysConfigAndInfo(void);
-void *GetShmSysConfigData(void);
-void *GetShmSysInfoData(void);
-void *GetShmSysWarningInfo(void);
-
-void *GetShmOCPP16Data(void);
-void* GetShmOCPP20Data(void);
-
-void *GetShmCHAdeMOData(void);
-void *GetShmGBTData(void);
-void *GetShmCcsData(void);
-
-void *GetShmInfoCodeData(void);
-void *GetShmFaultCodeData(void);
-void *GetShmAlarmCodeData(void);
-void *GetShmStatusCodeData(void);
-
-void *GetShmPsuData(void);
-void *GetShmPrimaryMcuData(void);
-
-void *GetShmRelayModuleData(void);
-void *GetShmFanModuleData(void);
-void *GetShmLedModuleData(void);
-
-void *GetShmCsuMeterData(void);
-void *GetShmDcCommonData(void);
-
-void MappingChargingInfoData(void);
-
-void *GetShmSelectGunInfo(void);
-
-int InitSelectGunShmMem(void);
-
-#endif /* _CSU_SHARE_MEMORY_H_ */
+#ifndef _CSU_SHARE_MEMORY_H_
+#define _CSU_SHARE_MEMORY_H_
+
+#include <stdint.h>
+#include <stdbool.h>
+#include "../Define/define.h"
+
+//------------------------------------------------------------------------------
+#define ShmCsuMeterKey          2001
+#define ShmCommonKey            2002
+
+//------------------------------------------------------------------------------
+typedef struct StGunIndexInfo {
+    volatile uint8_t AcIndex;    //AC Gun Count
+    volatile uint8_t AcGunIndex; //AC type index
+
+    volatile uint8_t DcGunIndex; //DC gun Count
+
+    //DC gun type index
+    volatile uint8_t ChademoIndex;
+    volatile uint8_t CcsIndex;
+    volatile uint8_t GbIndex;
+} GunIndexInfo;
+
+//------------------------------------------------------------------------------
+void *GetGunIndexInfo(void);
+bool MappingGunChargingInfo(char *whichTask);
+
+int CreateAllCsuShareMemory(void);
+void ClearAllShmMemParameter(void);
+void InitialShareMemoryInfo(void);
+
+void SetDcChargingInfoData(uint8_t index, struct ChargingInfoData *chargingInfoIndex);
+void *GetDcChargingInfoData(uint8_t index);
+
+void SetAcChargingInfoData(uint8_t index, struct ChargingInfoData *chargingInfoIndex);
+void *GetAcChargingInfoData(uint8_t index);
+
+void *GetShmSysConfigAndInfo(void);
+void *GetShmSysConfigData(void);
+void *GetShmSysInfoData(void);
+void *GetShmSysWarningInfo(void);
+
+void *GetShmOCPP16Data(void);
+void* GetShmOCPP20Data(void);
+
+void *GetShmCHAdeMOData(void);
+void *GetShmGBTData(void);
+void *GetShmCcsData(void);
+
+void *GetShmInfoCodeData(void);
+void *GetShmFaultCodeData(void);
+void *GetShmAlarmCodeData(void);
+void *GetShmStatusCodeData(void);
+
+void *GetShmPsuData(void);
+void *GetShmPrimaryMcuData(void);
+
+void *GetShmRelayModuleData(void);
+void *GetShmFanModuleData(void);
+void *GetShmLedModuleData(void);
+
+void *GetShmCsuMeterData(void);
+void *GetShmDcCommonData(void);
+
+void MappingChargingInfoData(void);
+
+void *GetShmSelectGunInfo(void);
+
+int InitSelectGunShmMem(void);
+
+#endif /* _CSU_SHARE_MEMORY_H_ */

+ 107 - 60
EVSE/Projects/DD360Tcci/Apps/common.c

@@ -1,60 +1,107 @@
-#include <stdio.h>
-#include <stdlib.h>
-#include <stdint.h>
-#include <string.h>
-
-#include "Config.h"
-
-//------------------------------------------------------------------------------
-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, uint32_t start, uint32_t cnt)
-{
-    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);
-    }
-}
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdint.h>
+#include <string.h>
+
+#include "Config.h"
+#include "Define/define.h"
+#include "ShareMemory/shmMem.h"
+//------------------------------------------------------------------------------
+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, uint32_t start, uint32_t cnt)
+{
+    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);
+    }
+}
+
+bool IntoChargeProcess(int status)
+{
+    if ((status >= S_AUTHORIZING && status <= S_CHARGING) ||
+        status == S_CCS_PRECHARGE_ST0 || status == S_CCS_PRECHARGE_ST1) {
+        return TRUE;
+    }
+    return FALSE;
+}
+
+bool IntoOperateProcess(int status)
+{
+    if ((status >= S_AUTHORIZING && status <= S_ALARM) ||
+        status == S_CCS_PRECHARGE_ST0 || status == S_CCS_PRECHARGE_ST1) {
+        return TRUE;
+    }
+    return FALSE;
+}
+
+char* GetStatusName(int status)
+{
+    switch (status) {
+        case S_BOOTING: return "BOOTING"; break;
+        case S_IDLE:     return "IDLE"; break;
+        case S_AUTHORIZING: return "AUTHORIZING"; break;
+        case S_REASSIGN_CHECK: return "REASSIGN_CHECK"; break;
+        case S_REASSIGN: return "REASSIGN"; break;
+        case S_PREPARNING: return "PREPARING"; break;
+        case S_PREPARING_FOR_EV: return "PREPARING_FOR_EV"; break;
+        case S_PREPARING_FOR_EVSE: return "PREPARING_FOR_EVSE"; break;
+        case S_CHARGING: return "CHARGING"; break;
+        case S_TERMINATING: return "TERMINATING"; break;
+        case S_COMPLETE: return "COMPLETE"; break;
+        case S_ALARM: return "ALARM"; break;
+        case S_FAULT: return "FAULT"; break;
+        case S_RESERVATION: return "RESERVATION"; break;
+        case S_BOOKING: return "BOOKNG"; break;
+        case S_MAINTAIN: return "MAINTAIN"; break;
+        case S_DEBUG: return "DEBUG"; break;
+        case S_CCS_PRECHARGE_ST0: return "CCS_PRECHARGE_ST0"; break;
+        case S_CCS_PRECHARGE_ST1: return "CCS_PRECHARGE_ST1"; break;
+        case S_UPDATE: return "UPDATE"; break;
+        case S_NONE: return "NONE"; break;
+    }
+    return "";
+}

+ 15 - 13
EVSE/Projects/DD360Tcci/Apps/common.h

@@ -1,13 +1,15 @@
-#ifndef _COMMON_H_
-#define _COMMON_H_
-
-//------------------------------------------------------------------------------
-#include <stdint.h>
-
-//------------------------------------------------------------------------------
-void trim(char *s);
-int mystrcmp(char *p1, char *p2);
-void substr(char *dest, const char *src, uint32_t start, uint32_t cnt);
-void split(char **arr, char *str, const char *del);
-
-#endif /* _COMMON_H_ */
+#ifndef _COMMON_H_
+#define _COMMON_H_
+
+//------------------------------------------------------------------------------
+#include <stdint.h>
+
+//------------------------------------------------------------------------------
+void trim(char *s);
+int mystrcmp(char *p1, char *p2);
+void substr(char *dest, const char *src, uint32_t start, uint32_t cnt);
+void split(char **arr, char *str, const char *del);
+bool IntoChargeProcess(int status);
+bool IntoOperateProcess(int status);
+char* GetStatusName(int status);
+#endif /* _COMMON_H_ */

二进制
EVSE/Projects/DD360Tcci/Images/ramdisk.gz


二进制
EVSE/Projects/DD360Tcci/output/Module_ChkSysTask


二进制
EVSE/Projects/DD360Tcci/output/Module_DoComm


二进制
EVSE/Projects/DD360Tcci/output/Module_EvComm


二进制
EVSE/Projects/DD360Tcci/output/Module_EventLogging


二进制
EVSE/Projects/DD360Tcci/output/Module_InternalComm


二进制
EVSE/Projects/DD360Tcci/output/Module_LcmControl


二进制
EVSE/Projects/DD360Tcci/output/Module_PrimaryComm


二进制
EVSE/Projects/DD360Tcci/output/Module_UpdateFW


二进制
EVSE/Projects/DD360Tcci/output/ReadCmdline


+ 10 - 10
EVSE/Projects/DD360Tcci/output/SearchIP.sh

@@ -1,10 +1,10 @@
-#!/bin/bash
-# 用 arping 來 ping 區域網路中所有的 IP 位址
-echo $0;
-
-for ip in "$1".{1..254}; do
-  arping -I "$0" -w 3 -f $ip | grep reply &;
-done
-
-# 等待所有背景的 arping 結束
-wait;
+#!/bin/bash
+# 用 arping 來 ping 區域網路中所有的 IP 位址
+echo $0;
+
+for ip in "$1".{1..254}; do
+  arping -I "$0" -w 3 -f $ip | grep reply &;
+done
+
+# 等待所有背景的 arping 結束
+wait;

+ 15 - 15
EVSE/Projects/DD360Tcci/output/init.sh

@@ -1,15 +1,15 @@
-chmod 777 Module_CSU
-chmod 777 Module_PrimaryComm
-chmod 777 Module_LcmControl
-chmod 777 Module_InternalComm
-chmod 777 Module_EventLogging
-chmod 777 Module_EvComm
-chmod 777 Module_PsuComm
-chmod 777 Module_UpdateFW
-chmod 777 Module_ChkSysTask
-chmod 777 OcppBackend
-chmod 777 kill.sh
-chmod 777 ReadCmdline
-chmod 777 Module_DoComm
-chmod 777 SearchIP.sh
-chmod 777 FactoryConfig
+chmod 777 Module_CSU
+chmod 777 Module_PrimaryComm
+chmod 777 Module_LcmControl
+chmod 777 Module_InternalComm
+chmod 777 Module_EventLogging
+chmod 777 Module_EvComm
+chmod 777 Module_PsuComm
+chmod 777 Module_UpdateFW
+chmod 777 Module_ChkSysTask
+chmod 777 OcppBackend
+chmod 777 kill.sh
+chmod 777 ReadCmdline
+chmod 777 Module_DoComm
+chmod 777 SearchIP.sh
+chmod 777 FactoryConfig

+ 47 - 47
EVSE/Projects/DD360Tcci/output/kill.sh

@@ -1,47 +1,47 @@
-pkill Module_CSU;
-pkill Module_PrimaryComm;
-pkill Module_LcmControl;
-pkill Module_InternalComm;
-pkill Module_EventLogging;
-pkill Module_EvComm;
-pkill Module_PsuComm;
-pkill Module_UpdateFW;
-pkill Module_ChkSysTask;
-pkill Module_4g;
-pkill Module_Wifi;
-pkill OcppBackend;
-pkill Module_ProduceUtils;
-pkill Module_DoComm;
-pkill main;
-
-/usr/bin/fuser -k /dev/watchdog
-sleep 1
-
-echo V > /dev/watchdog
-
-ipcrm -M 0x000003e9;
-ipcrm -M 0x000003ed;
-ipcrm -M 0x000003ea;
-ipcrm -M 0x000003ec;
-ipcrm -M 0x000003ee;
-ipcrm -M 0x000003ef;
-ipcrm -M 0x000003f0;
-ipcrm -M 0x000003f3;
-ipcrm -M 0x000003f1;
-ipcrm -M 0x000003f6;
-
-ipcrm -M 0x000003e9;
-ipcrm -M 0x000003ed;
-ipcrm -M 0x000003ea;
-ipcrm -M 0x000003ec;
-ipcrm -M 0x000003ee;
-ipcrm -M 0x000003ef;
-ipcrm -M 0x000003f0;
-ipcrm -M 0x000003f3;
-ipcrm -M 0x000003f1;
-ipcrm -M 0x000003f6;
-ipcrm -M 0x000003eb;
-ipcrm -M 0x000003f2;
-ipcrm -M 0x000007d2;
-
-ipcs;
+pkill Module_CSU;
+pkill Module_PrimaryComm;
+pkill Module_LcmControl;
+pkill Module_InternalComm;
+pkill Module_EventLogging;
+pkill Module_EvComm;
+pkill Module_PsuComm;
+pkill Module_UpdateFW;
+pkill Module_ChkSysTask;
+pkill Module_4g;
+pkill Module_Wifi;
+pkill OcppBackend;
+pkill Module_ProduceUtils;
+pkill Module_DoComm;
+pkill main;
+
+/usr/bin/fuser -k /dev/watchdog
+sleep 1
+
+echo V > /dev/watchdog
+
+ipcrm -M 0x000003e9;
+ipcrm -M 0x000003ed;
+ipcrm -M 0x000003ea;
+ipcrm -M 0x000003ec;
+ipcrm -M 0x000003ee;
+ipcrm -M 0x000003ef;
+ipcrm -M 0x000003f0;
+ipcrm -M 0x000003f3;
+ipcrm -M 0x000003f1;
+ipcrm -M 0x000003f6;
+
+ipcrm -M 0x000003e9;
+ipcrm -M 0x000003ed;
+ipcrm -M 0x000003ea;
+ipcrm -M 0x000003ec;
+ipcrm -M 0x000003ee;
+ipcrm -M 0x000003ef;
+ipcrm -M 0x000003f0;
+ipcrm -M 0x000003f3;
+ipcrm -M 0x000003f1;
+ipcrm -M 0x000003f6;
+ipcrm -M 0x000003eb;
+ipcrm -M 0x000003f2;
+ipcrm -M 0x000007d2;
+
+ipcs;

二进制
EVSE/Projects/DD360Tcci/output/main


二进制
EVSE/rootfs/root/Module_Firewall