zte's code,first commit

Change-Id: I9a04da59e459a9bc0d67f101f700d9d7dc8d681b
diff --git a/ap/app/zte_log_agent/Makefile b/ap/app/zte_log_agent/Makefile
new file mode 100755
index 0000000..62ccc32
--- /dev/null
+++ b/ap/app/zte_log_agent/Makefile
@@ -0,0 +1,54 @@
+#*******************************************************************************

+# include ZTE application makefile

+#*******************************************************************************

+include $(COMMON_MK)

+

+WORKPATH = $(zte_lib_path)

+SOFT_TIMER_PATH = $(zte_lib_path)/libsoft_timer

+#*******************************************************************************

+# execute

+#*******************************************************************************

+EXEC    = zte_log_agent

+

+#*******************************************************************************

+# objects

+#*******************************************************************************

+c_sources = $(wildcard *.c)

+

+OBJS=$(c_sources:%c=%o) 

+

+#*******************************************************************************

+# include path

+#*******************************************************************************

+CFLAGS += -I./../include                                                   \

+	-I$(zte_app_path)/include \

+          -I$(zte_lib_path)/libnvram                                                                  

+CFLAGS += -g

+

+#*******************************************************************************

+# library

+#*******************************************************************************

+LDLIBS += -lpthread

+LDLIBS += -lnvram -L$(zte_lib_path)/libnvram

+

+

+#*******************************************************************************

+# library path

+#*******************************************************************************

+LDLIBS  += -L$(zte_lib_path)/libnvram

+

+#*******************************************************************************

+# targets

+#*******************************************************************************

+all: $(EXEC)

+

+$(EXEC): $(OBJS)

+	$(CC) $(LDFLAGS) -o $@ $(OBJS) -Wl,--start-group $(LDLIBS) -Wl,--end-group

+

+romfs:

+	cp $(EXEC) $(EXEC).elf

+	$(ROMFSINST)  /bin/$(EXEC)

+	

+clean:

+	-rm -f $(EXEC) *.elf *.gdb *.o

+

diff --git a/ap/app/zte_log_agent/ap_log.c b/ap/app/zte_log_agent/ap_log.c
new file mode 100644
index 0000000..9e4da4d
--- /dev/null
+++ b/ap/app/zte_log_agent/ap_log.c
@@ -0,0 +1,184 @@
+/**

+ * 

+ * @file      ap_log.c

+ * @brief     

+ *            This file is part of ZCAT.

+ *            zcatÓ¦Óòãlog_agent´¦Àílogcat_printf/logcat_printkÉ豸

+ *            

+ * @details   

+ * @author    Tools Team.

+ * @email     

+ * @copyright Copyright (C) 2013 Sanechips Technology Co., Ltd.

+ * @warning   

+ * @date      2019/02/02

+ * @version   1.2

+ * @pre       

+ * @post      

+ *            

+ * @par       

+ * Change History :

+ * ---------------------------------------------------------------------------

+ * date        version  author         description

+ * ---------------------------------------------------------------------------

+ * 2017/07/17  1.0      hou.bing       Create file

+ * 2019/01/24  1.1      jiang.fenglin  1.Ìí¼Óusblog¶ÁÐ´Ëø

+ *                                     2.Ìí¼ÓÏß³ÌÃû³Æ

+ * 2019/02/02  1.2      jiang.fenglin  ÐÞ¸Ä×¢ÊÍ·½Ê½Îªdoxygen

+ * ---------------------------------------------------------------------------

+ * 

+ * 

+ */

+

+#include <string.h>

+#include <pthread.h>

+#include <sys/prctl.h>

+#include "log_agent.h"

+

+/*É豸·¾¶*/

+const char* kernellog_dev = "/dev/logcat_printk";

+const char* applog_dev = "/dev/logcat_printf";

+

+static BOOL g_KernelNewLine = TRUE;

+static BOOL g_AppNewLine    = TRUE;

+extern int hb_flag;

+pthread_t read_kernellog_thread = 0;;

+pthread_t read_applog_thread = 0;;

+int kernellog_fd = -1;

+int applog_fd = -1;

+

+extern void zCatAgt_Ap_GetModAndPri(unsigned char **buf, unsigned short *bufLen, unsigned char *pPriority, unsigned char *pMod);

+extern BOOL zCatAgt_Ap_ReadBuffer(T_AP_SRC_BUFFER_TYPE *src, T_AP_DEST_BUFFER_TYPE *dest);

+extern unsigned int zCatAgt_Ap_SendMsg(unsigned char cmd_code, unsigned char priority, unsigned char mod, unsigned char *buf, unsigned int len);

+

+/**

+ * @brief ¶ÁÈ¡applogµÄÏ̺߳¯Êý£¬\n

+ *        ´¦Àí´Óapplog_devÉ豸ÖеÄlogÊý¾Ý£¬²¢×ª·¢³öÈ¥.

+ * @param[in] args Ï̺߳¯Êý²ÎÊý

+ * @return void

+ * @note

+ * @see 

+ */

+void *read_applog(void* args)

+{

+    int read_len = -1; 

+    static unsigned char  readApplogBuffer[4096] = {0};

+    

+    prctl(PR_SET_NAME, "read_applog");

+    //printf("zcat: read_applog \n"); 

+    while(1)

+    {     

+         if(hb_flag)

+         read_len = read(applog_fd, readApplogBuffer, sizeof(readApplogBuffer));  

+         if(read_len>0) 

+         {

+                T_AP_DEST_BUFFER_TYPE dest = {0};

+                T_AP_SRC_BUFFER_TYPE src = {0};

+                src.buf = readApplogBuffer;

+                src.beginIndex=0;

+                src.bufSize = read_len;

+                //printf("zcat: read_applog read_len %d \n", read_len); 

+                

+                while (zCatAgt_Ap_ReadBuffer(&src , &dest))

+                {

+                    unsigned char *p   = dest.buf;

+                    unsigned short len = dest.len;

+                    unsigned char  priority = APP_LOG_DEFAULT_LEVEL;

+                    unsigned char  mod = 1;

+                    static unsigned char curPriority = APP_LOG_DEFAULT_LEVEL;

+

+                    if (g_AppNewLine)

+                    {

+                        g_AppNewLine = FALSE;

+                        zCatAgt_Ap_GetModAndPri(&p, &len, &priority, &mod);

+                        curPriority = priority;

+                    }

+                    else

+                    {

+                        priority = curPriority;

+                    }

+                    zCatAgt_Ap_SendMsg(ZCAT_AP_APP_LOG, priority, mod, p, len);

+                    if (dest.newLine == 1)

+                    {

+                        g_AppNewLine = TRUE;

+                    }

+                    memset(&dest, 0, sizeof(T_AP_DEST_BUFFER_TYPE));

+                }

+                memset(readApplogBuffer, 0, sizeof(readApplogBuffer));

+         }

+          else

+        {

+            sleep(1);

+        }

+

+    }

+    return NULL;

+}

+

+

+/**

+ * @brief ¶ÁÈ¡kernellogµÄÏ̺߳¯Êý£¬\n

+ *        ´¦Àí´Ókernellog_devÉ豸ÖеÄlogÊý¾Ý£¬²¢×ª·¢³öÈ¥.

+ * @param[in] args Ï̺߳¯Êý²ÎÊý

+ * @return void

+ * @note

+ * @see 

+ */

+void *read_kernellog(void* args)

+{

+    int read_len = -1; 

+    unsigned char readKernelLogBuffer[1024] = {0};

+

+    prctl(PR_SET_NAME, "read_kernellog");

+    //printf("read_kernellog kkkkkkkkkkkk fd %d\n", fd); 

+    while(1)

+    {            

+        if(hb_flag)

+        read_len = read(kernellog_fd, readKernelLogBuffer, sizeof(readKernelLogBuffer)); 

+        if(read_len > 0) 

+        {

+            T_AP_DEST_BUFFER_TYPE dest = {0};

+            T_AP_SRC_BUFFER_TYPE src = {0};

+            src.buf = readKernelLogBuffer;

+            src.beginIndex=0;

+            src.bufSize = read_len;

+            //printf("read_kernellog read_len %d \n", read_len); 

+            //CHAR atCmd[200] = {0};

+            //g_cp_log_count++;

+            //sprintf(atCmd, " /sbin/atlog.sh \"%s\" \"%s\" \"%s\",\"%d\",\"%d\"", "send",zte_time(),"wubo deal_with_kernellog_from_devkkkkkkkk", read_len, 0); 

+            //system(atCmd);

+            while (zCatAgt_Ap_ReadBuffer(&src , &dest))

+            {

+                unsigned char *p   = dest.buf;

+                unsigned short len = dest.len;

+                unsigned char  priority = KERNEL_LOG_DEFAULT_LEVEL;

+                unsigned char  mod = 1;

+                static unsigned char curPriority = KERNEL_LOG_DEFAULT_LEVEL;

+

+                if (g_KernelNewLine)

+                {

+                    g_KernelNewLine = FALSE;

+                    zCatAgt_Ap_GetModAndPri(&p, &len, &priority, &mod);

+                    curPriority = priority;

+                }

+                else

+                {

+                    priority = curPriority;

+                }

+                zCatAgt_Ap_SendMsg(ZCAT_AP_KERNEL_LOG, priority, mod, p, len);

+

+                if (dest.newLine == 1)

+                {

+                    g_AppNewLine = TRUE;

+                }

+

+                memset(&dest, 0, sizeof(T_AP_DEST_BUFFER_TYPE));

+            }

+            memset(readKernelLogBuffer, 0, sizeof(readKernelLogBuffer));

+        }

+        else

+        {

+            sleep(1);

+        }

+    }

+}

+

diff --git a/ap/app/zte_log_agent/cp_log.c b/ap/app/zte_log_agent/cp_log.c
new file mode 100644
index 0000000..2187689
--- /dev/null
+++ b/ap/app/zte_log_agent/cp_log.c
@@ -0,0 +1,89 @@
+/**

+ * 

+ * @file      cp_log.c

+ * @brief     

+ *            This file is part of ZCAT.

+ *            zcatÓ¦Óòãlog_agent´¦ÀícplogÉ豸

+ *            

+ * @details   

+ * @author    Tools Team.

+ * @email     

+ * @copyright Copyright (C) 2013 Sanechips Technology Co., Ltd.

+ * @warning   

+ * @date      2019/02/02

+ * @version   1.2

+ * @pre       

+ * @post      

+ *            

+ * @par       

+ * Change History :

+ * ---------------------------------------------------------------------------

+ * date        version  author         description

+ * ---------------------------------------------------------------------------

+ * 2017/07/17  1.0      hou.bing       Create file

+ * 2019/01/24  1.1      jiang.fenglin  1.Ìí¼Óusblog¶ÁÐ´Ëø

+ *                                     2.Ìí¼ÓÏß³ÌÃû³Æ

+ * 2019/02/02  1.2      jiang.fenglin  ÐÞ¸Ä×¢ÊÍ·½Ê½Îªdoxygen

+ * ---------------------------------------------------------------------------

+ * 

+ * 

+ */

+

+#include <string.h>

+#include <time.h>

+#include <pthread.h>

+#include <sys/prctl.h>

+#include "log_agent.h"

+

+#define MAX_PACKET_LEN       (0x10000)

+#define MAX_CP_PACKET_LEN    (MAX_PACKET_LEN * 2)

+

+const char* cplog_dev = "/dev/cplog";     // É豸·¾¶

+static unsigned char g_cp_read_buffer[MAX_CP_PACKET_LEN] = {0}; // Êý¾Ý»º´æ

+pthread_t read_cplog_thread = 0;

+int cplog_fd = -1;

+

+extern void send_log_out(unsigned char* buf, int len);

+

+/**

+ * @brief ¶ÁÈ¡cplogÏ̺߳¯Êý£¬\n

+ *        ´¦Àí´ÓcplogÉ豸ÖеÄlogÊý¾Ý£¬²¢×ª·¢³öÈ¥.

+ * @param[in] args Ï̺߳¯Êý²ÎÊý

+ * @return void

+ * @note

+ * @see 

+ */

+void *read_cplog(void* args)

+{

+    const struct timespec notimer_interval = {0, 20000000};//20ms

+    int read_Len = -1;

+    int nosleep_ret = -1;

+

+    prctl(PR_SET_NAME, "read_cplog");

+    

+    while(1)

+    {   

+        read_Len = read(cplog_fd, g_cp_read_buffer, MAX_CP_PACKET_LEN);

+        

+        if(read_Len > 0)

+        {           

+            //printf("zcat: read_cplog read_Len %d\n", read_Len);

+            send_log_out(g_cp_read_buffer, read_Len);   

+            memset(g_cp_read_buffer, 0, MAX_CP_PACKET_LEN);

+        }

+        else if(read_Len == 0)

+        {

+            nosleep_ret = nanosleep(&notimer_interval, NULL);

+            if(nosleep_ret < 0)

+            {

+                sleep(1);

+            }

+        }

+        else

+        {

+            sleep(1);

+        }

+        

+    }

+}

+

diff --git a/ap/app/zte_log_agent/cp_ramdump.c b/ap/app/zte_log_agent/cp_ramdump.c
new file mode 100644
index 0000000..0e9c52b
--- /dev/null
+++ b/ap/app/zte_log_agent/cp_ramdump.c
@@ -0,0 +1,852 @@
+/**

+ * 

+ * @file      cp_ramdump.c

+ * @brief     

+ *            This file is part of ZCAT.

+ *            zcatÓ¦Óòãlog_agent´¦Àícp_ramdumpÉ豸

+ *            

+ * @details   

+ * @author    Tools Team.

+ * @email     

+ * @copyright Copyright (C) 2013 Sanechips Technology Co., Ltd.

+ * @warning   

+ * @date      2019/02/02

+ * @version   1.1

+ * @pre       

+ * @post      

+ *            

+ * @par       

+ * Change History :

+ * ---------------------------------------------------------------------------

+ * date        version  author         description

+ * ---------------------------------------------------------------------------

+ * 2017/07/17  1.0      hou.bing       Create file

+ * 2019/02/02  1.1      jiang.fenglin  ÐÞ¸Ä×¢ÊÍ·½Ê½Îªdoxygen

+ * ---------------------------------------------------------------------------

+ * 

+ * 

+ */

+#if 0

+#include "log_agent.h"

+#include <stdlib.h>

+#include <stdio.h>

+#include <string.h>

+#include <sys/types.h>

+#include <sys/stat.h>

+#include <fcntl.h>

+#include <errno.h>

+#include <getopt.h>

+#include <stdarg.h>

+#include <termios.h>

+#include <stddef.h>

+#include <dirent.h>

+#include <time.h>

+#include <pthread.h>

+

+/**

+ * Êý¾Ý½á¹¹¶¨Òå

+ */

+typedef struct {

+    char file_name[32];

+    unsigned int file_size;

+} file_info_t;

+

+/**

+ * È«¾Ö±äÁ¿ºÍºê¶¨Òå

+ */

+#define LOG_TAG "Modem_Ramdump"

+#define ZTE_LOG_PATH   "/mnt/sdcard/ZTELog"

+#define RAMDUMP_LOG_PATH "/mnt/sdcard/ZTELog/Ramdump"

+#define DEFAULT_RAMDUMP_PATH "/sdcard/ZTELog/ramdump"

+#define USB_RAMDUMP_FLAG_FILE_NAME  "/sys/dwc_usb/usbconfig/ramdumpFlag"

+// #define MODEM_RAMDUMP_PATH "/data/local/log/Ramdump"

+

+pthread_t get_ramdump_thread = 0;

+//typedef unsigned int UINT32;

+int ramdump_fd = -1;

+

+#define RAMDUMP_DEFAULT_DELAY 10000

+#define MAX_AP_LOG_BUFF_LEN   8192

+

+/*Ramdump Ö¸ÁÒå*/

+#define DUMPFILE_LINK_REQ       (UINT32)1       //ͬ²½ÇëÇó

+#define DUMPFILE_LINK_RSP       (UINT32)2       //ͬ²½ÇëÇóÓ¦´ð£¬¸½´øramdumpÎļþÊýÄ¿

+#define DUMPFILE_FILE_REQ       (UINT32)3       //ÇëÇóÖ¸¶¨±àºÅÎļþÐÅÏ¢

+#define DUMPFILE_FILE_RSP       (UINT32)4       //Îļþ±àºÅÎļþÐÅÏ¢Ó¦´ð£¬¸½´ø´«ÊäÎļþÃû¼°´óС

+#define DUMPFILE_READ_REQ       (UINT32)5       //ÇëÇó¶Áȡָ¶¨±àºÅÎļþÄÚÈÝ

+#define DUMPFILE_READ_RSP       (UINT32)6       //ÎļþÄÚÈݶÁȡӦ´ð£¬¸½´øÎļþÄÚÈÝ

+#define DUMPFILE_END_REQ        (UINT32)7       //´«Êä½áÊø

+#define DUMPFILE_END_RSP        (UINT32)8       //´«Êä½áÊøÓ¦´ð

+#define DUMPFILE_CMD_FAIL       (UINT32)9       //Ö¸Áî´íÎó

+#define DUMPFILE_NO_FAIL        (UINT32)10      //Îļþ±àºÅ´íÎó

+#define DUMPFILE_LENGTH_FAIL    (UINT32)11      //ÎļþλÖôóС´íÎó

+#define CMD_BUFFER_LEN          (UINT32)16      //Ö¸Áî²Á·À¶¾

+#define FILENAME_LEN            (UINT32)32      //ÎļþÃû³¤¶È

+#define FILENAME_MAX_LEN        (UINT32)256     //ÎļþÃû×î´ó³¤¶È

+//#define DATA_BLOCK_SIZE         (0x40000)       // Êý¾Ý»º³å´óС

+#define DATA_BLOCK_SIZE         (0x01000)       // Êý¾Ý»º³å´óС

+

+#define MIN(a, b) ((a)< (b) ? (a): (b))

+

+static char g_ramdump_datablock_buffer[DATA_BLOCK_SIZE] = {0};

+//static T_LOG_SDCARD_PARA g_ramdump_sdcard_para = { {0} };

+static char* g_ramdump_path = NULL;

+static int g_modem_fd = -1;

+/*É豸·¾¶*/

+static char* ramdump_dev="/dev/ramdump";

+static char* usb_ramdump_dev="/dev/ttyGS0";

+

+BOOL g_cp_trap_flag = TRUE;

+BOOL g_cpcrash_flag = FALSE;

+BOOL g_trap_flag = TRUE;

+

+int usb_ramdump_dev_fd = -1;

+pthread_t  usb_ramdump_dev_thread = -1;

+

+/**

+ * Íⲿ±äÁ¿ºÍº¯ÊýÒýÓÃ

+ */

+extern int ramdump_fd;

+extern E_ZCAT_MODE g_log_dir;

+extern unsigned int zTools_SendData(unsigned char *buf, unsigned int buf_len,unsigned char tgt_mdl_no, unsigned char tgt_submdl_no, unsigned char src_submdl_no);

+extern int filelength(FILE *fp);

+extern BOOL zCatAgt_Ap_ReadBuffer(T_AP_SRC_BUFFER_TYPE *src, T_AP_DEST_BUFFER_TYPE *dest);

+extern int test_dir_exist(char* dir_path);

+

+/**

+ * º¯ÊýʵÏÖ

+ */

+

+BOOL get_cp_crash_flag()

+{

+     return g_cpcrash_flag;

+}

+

+#if 0

+static char * zte_time()

+{

+	time_t timep;

+	struct tm *p;

+	static char buf[22];

+	memset(buf,0,22);

+	time(&timep);

+	p =localtime(&timep);

+	snprintf(buf,21,"%4d/%02d/%02d %02d:%02d:%02d ",1900 + p->tm_year,1 + p->tm_mon,p->tm_mday,p->tm_hour,p->tm_min,p->tm_sec);

+	return buf;

+}

+#endif

+static int writefile(char*path, char*buf, unsigned len)

+{

+    FILE *fp;

+    int rtv;

+    if((fp=fopen(path,"w"))==NULL)

+    {

+        printf("open file %s error.\n",path);

+        return -1;

+    }

+    rtv = fwrite(buf,len,1, fp);

+    fclose(fp);

+    return rtv;

+}

+

+static int readfile(char *path, char* buf, unsigned len)

+{

+    FILE *fp;

+    int length;

+    if((fp=fopen(path,"r"))==NULL)

+    {

+        printf("open file %s error.\n",path);

+        return -1;

+    }

+    length = filelength(fp);

+    length = length > len? len: length;

+    //ch=(char *)malloc(length+1);

+    fread(buf,length,1,fp);

+    fclose(fp);

+    *(buf+length)='\0';

+    return length;

+}

+

+BOOL get_trap_flag_from_dev()

+{

+	

+	int ramdumpFlag = 0;

+    char buf[2]={0};

+    

+    readfile(USB_RAMDUMP_FLAG_FILE_NAME, buf, 1);

+

+    ramdumpFlag = atoi(buf);

+    printf("ramdumpFlag : %d \n", ramdumpFlag);

+

+    if(ramdumpFlag == 0){

+        printf("usb normal \n");

+    }else{

+        printf("usb ramdump \n");

+    }

+	if(ramdumpFlag == 1)

+	{

+		return TRUE;

+	}

+	

+    return FALSE;

+}

+

+

+int send_ramdump_to_trap(unsigned char *buf, int read_len)

+{

+    int write_len = -1;

+    while(usb_ramdump_dev_fd == -1)

+	{

+	    sleep(1);

+		printf("hb ramdump test\n");

+	}

+	

+    write_len = write(usb_ramdump_dev_fd, buf, read_len);

+     

+	if (write_len != read_len)

+	{

+		printf("modem_log, send_rule error, write_len = %d, len = %d. \n", write_len, read_len);

+		return -1;

+	}

+

+    return 0;

+}

+

+static unsigned char gReadApplogBuffer[1024*130] = {0};  

+/**********************************************************************************

+*º¯Êý˵Ã÷:´ÓramdumpÉ豸¶ÁÈ¡Êý¾Ý 

+***********************************************************************************/

+void *get_ramdump_from_dev(void *arg)

+//void *get_ramdump_from_dev(int fd)

+{

+

+    int read_len = -1;   

+     

+	printf("get_ramdump_from_dev * p_fd %d \n", ramdump_fd); 

+

+    while(1)

+    {   

+    	read_len = read(ramdump_fd, gReadApplogBuffer, sizeof(gReadApplogBuffer));     

+    	if(read_len>0) 

+    	{

+			if(g_log_dir == ZCAT_MODE_AP_USB)

+			{

+				if(g_cp_trap_flag)

+				{

+					writefile(USB_RAMDUMP_FLAG_FILE_NAME, "1", 1);

+					printf("get_ramdump_from_dev: writefile");

+				}

+				else

+				{

+					send_ramdump_to_trap(gReadApplogBuffer, read_len);

+					printf("get_ramdump_from_dev: send_ramdump_to_trap");

+				}

+			}

+			else if(g_log_dir == ZCAT_MODE_AP_NET)

+			{

+				g_cpcrash_flag = TRUE;

+				T_AP_DEST_BUFFER_TYPE dest = {0};            

+				T_AP_SRC_BUFFER_TYPE src = {0};

+				src.buf = gReadApplogBuffer;

+				src.beginIndex=0;

+				src.bufSize = sizeof(gReadApplogBuffer);

+				while (zCatAgt_Ap_ReadBuffer(&src , &dest))

+				{

+					unsigned char *p   = dest.buf;

+					unsigned short len = dest.len;

+					//if(g_log_dir == ZCAT_MODE_AP_NET)

+					{

+						//»¥³â???

+						zTools_SendData(p,  len, MDL_ZCAT, 1, SUBMDL_ZCATAGT);

+					}

+					

+					memset(&dest, 0, sizeof(T_AP_DEST_BUFFER_TYPE));

+				}

+			}

+			else

+			{

+				printf("get_ramdump_from_dev g_log_dir error \n"); 

+			}

+    	} 

+		else

+		{

+			sleep(1);

+			//printf("get_ramdump_from_dev: sleep1");

+		}

+    }

+    return NULL;

+}

+

+//³õʼ»¯ramdump logÉ豸

+int init_ramdump_log_device()

+{

+    int ret_ramdump;

+    int fd;

+    

+    fd = open(ramdump_dev, O_RDWR);

+	printf("init_ramdump_log_device fd %d \n", fd); 

+    if (fd < 0)

+    {

+        printf("open ramdump_dev error!!!\n");

+        return -1;  

+    }

+    ramdump_fd = fd;

+    ret_ramdump = pthread_create(&get_ramdump_thread, NULL, get_ramdump_from_dev, NULL);

+    if(ret_ramdump!=0)

+    {	

+    	printf("pthread_create getramdump_thread error\n"); 

+    	return -1;

+    }

+	

+    return fd;

+}

+

+static int tty_write(int fd, const char* buf, int size)

+{

+    int ret = 0;

+    ret = write(fd, buf, size);

+    if (ret != size) {

+        printf("%s failed, size=%d, ret=%d\n", __FUNCTION__, size, ret);

+        return -1;

+    }

+    return 0;

+}

+

+static int tty_read(int fd, char*buf, int size ,unsigned int delay_ms)

+{

+    int ret = -1;

+    int read_count = 0;

+    fd_set fds;

+    struct timeval tv;

+    if (buf == NULL)

+        return -1;

+    tv.tv_sec = delay_ms/1000;

+    tv.tv_usec = (delay_ms%1000) *1000;

+    FD_ZERO(&fds);

+    FD_SET(fd, &fds);

+    ret = select(fd +1, &fds, NULL, NULL, &tv);

+    if (ret > 0) {

+        read_count = read(fd, buf, size);

+        if (read_count <= 0) {

+            printf("%s read %d failed for ret=%d\n" , __FUNCTION__, read_count, ret);

+            return -1;

+        }

+        return read_count;

+    } else if (ret == 0) {

+        printf("select time out %dms\n" , delay_ms);

+    } else {

+        printf("select failed %s\n" , strerror(errno));

+    }

+    return -1;

+}

+static int mdp_send(const char*buf, int size)

+{

+    //mdp_print_array(,buf, size);

+    return  tty_write(g_modem_fd, buf,size);

+}

+

+

+static int mdp_receive(char *buf, int size)

+{

+    int count = 0;

+    int length = size;

+    char *pbuffer = buf;

+    while ( length  > 0) {

+        count  = tty_read(g_modem_fd, pbuffer,size, RAMDUMP_DEFAULT_DELAY);

+        if (count < 0) {

+            return -1;

+        }

+        pbuffer += count;

+        length -= count;

+    }

+    //mdp_print_array(, buf, size);

+    return size;

+}

+static int mdp_send_command(unsigned int cmd, unsigned int argc,...)

+{

+    char buffer[CMD_BUFFER_LEN] = {0};

+    unsigned int i = 0;

+    unsigned int arg = 0;

+    UINT32 *pbuffer = (UINT32*)buffer;

+    *pbuffer = cmd;

+    va_list ap;

+    va_start(ap, argc);

+    for (i=0; i<argc; i++) {

+        arg = va_arg(ap, unsigned int);

+        *(++pbuffer) = arg;

+    }

+    va_end(ap);

+    return mdp_send(buffer, CMD_BUFFER_LEN);

+}

+static int mdp_receive_ack(unsigned int ack)

+{

+    int ret = 0;

+    unsigned int  resp;

+    //char buffer[64] = {0};

+    ret = mdp_receive((char *)&resp, sizeof(unsigned int));

+    if (ret > 0) {

+        if (ack == resp)

+            return 0;

+    }

+    return -1;

+}

+static int init_devices(char* dev_path)

+{

+    int fd = -1;

+

+    fd = open(dev_path, O_RDWR);

+    if (fd < 0) {

+        printf("Can't open %s(%s)\n", dev_path, strerror(errno));

+        return -1;

+    }

+   

+    return fd;

+}

+static int create_fold(char *fold)

+{

+    char buffer[256]= {0};

+    snprintf(buffer, 256, "mkdir -p %s\n", fold);

+    int ret = system(buffer);

+    if (ret < 0)

+        return -1;

+    return 0;

+}

+static int create_file(char* fold, char * path)

+{

+    int fd = -1;

+    DIR* pdir = NULL;

+    char file_name[FILENAME_MAX_LEN] = {0};

+    int ret = 0;

+    if ((fold==NULL) || (*fold=='\0'))

+        fold = g_ramdump_path;

+    if ( (path==NULL) || (*path=='\0')) {

+     

+        return -1;

+    }

+    if ((pdir = opendir(fold)) == NULL) {

+        ret = create_fold(fold);

+        if (ret < 0) {

+            printf("%s create fold %d failed (%s)", fold, errno, strerror(errno));

+            return -1;

+        }

+    }

+    if (pdir != NULL)

+        closedir(pdir);

+    snprintf(file_name, FILENAME_MAX_LEN, "%s/%s", fold, path);

+    unlink(file_name);

+    printf("%s\n" , file_name);

+    fd = open(file_name, O_CREAT| O_RDWR, 0777);

+    if (fd < 0) {

+        printf("failed to create %s (%s)\n", path, strerror(errno));

+    }

+    return fd;

+

+}

+static int write_to_file(int fd, char *buffer, int size)

+{

+    int  ret = 0;

+    if ((fd < 0) || (buffer==NULL) || (size<=0))

+        return -1;

+    ret = write(fd, buffer, size);

+    if (ret < size) {

+        printf("write to file failed, ret=%d, size=%d\n", ret, size);

+        return -1;

+    }

+    return 0;

+

+}

+

+static int mdp_receive_ack_and_info(int cmd, void *receive_info, int receive_size)

+{

+	int ret = -1;

+	char* buffer = NULL;

+	int rsp = -1;

+	

+	buffer = malloc(receive_size + sizeof(rsp));

+	if(buffer == NULL)

+		goto exit;

+	ret = mdp_receive(buffer, receive_size + sizeof(rsp));

+	if (ret < sizeof(rsp) + receive_size) {

+        printf("failed to mdp_receive_ack_and_info\n");

+        goto exit;

+    }

+	

+	memcpy(&rsp, buffer, sizeof(rsp));

+    if (rsp != cmd) {

+        printf("failed to receive cmd:%d\n", cmd);

+        goto exit;

+    }

+	

+    memcpy(receive_info, buffer + sizeof(rsp), receive_size);

+exit:

+	free(buffer);

+	ret = 0;

+	return ret;

+}

+

+

+//»ñÈ¡µÚindex¸öramdumpÎļþ²¢Ð´Èët¿¨

+static int dump_file(int index, char *fold)

+{

+    int ret = 0;

+    //char path[256] = {0};

+    //char cmd_buffer[CMD_BUFFER_LEN] = {0};

+    file_info_t file_info = {{0}, 0};

+    int fd = 0;

+    int file_size , read_count, file_offset;

+	

+	ret = mdp_send_command(DUMPFILE_FILE_REQ, 1, index);	

+    if (ret < 0) {       

+        return -1;

+    }

+	

+	ret = mdp_receive_ack_and_info(DUMPFILE_FILE_RSP, (void*)(&file_info), sizeof(file_info));

+    /*

+	if (ret < 0) {      

+        return -1;

+    }*/

+	

+	fd = create_file(fold, file_info.file_name);

+    if (fd < 0) {

+        printf("failed to create file %s\n", file_info.file_name);

+        return -1;

+    }	

+    printf("filename=%s\t size=%d\n", file_info.file_name, file_info.file_size);

+    file_size = file_info.file_size;

+    file_offset = read_count = 0;

+    while (file_size > 0) {

+        read_count = MIN(file_size, DATA_BLOCK_SIZE);

+        if (mdp_send_command(DUMPFILE_READ_REQ, 3, index, file_offset, read_count) < 0) {

+            ret = -1;			

+            goto exit;

+        }

+		if (mdp_receive_ack(DUMPFILE_READ_RSP) < 0) {

+            ret = -1;

+            goto exit;

+        }

+        if (mdp_receive(g_ramdump_datablock_buffer, read_count) < 0) {

+            printf("failed to read file data\n");

+            ret = -1;

+            goto exit;

+        }

+        if (write_to_file(fd, g_ramdump_datablock_buffer, read_count)< 0) {

+            printf("failed to write file data\n");

+            ret = -1;

+            goto exit;

+        }

+        file_offset += read_count;

+        file_size -= read_count;

+    }

+    ret = 0;

+exit:

+    close(fd);

+    return ret;;

+}

+

+static int do_modem_ramdump( char* tty, char*path)

+{

+    int ret = -1;

+    int file_number = 0;

+    int i = 0;

+    int read_count = 0;

+    char read_buf[5] = {0};

+	

+    g_modem_fd = init_devices(tty);

+    if (g_modem_fd < 0) {

+        printf("failed to open %s\n", tty);

+        return -1;

+    }

+    read_count = read(g_modem_fd, read_buf, sizeof(read_buf));

+    if (0 >= read_count )

+    {

+		printf("read_count %d\n", read_count);

+                goto exit;

+    }

+	ret = mdp_send_command(DUMPFILE_LINK_REQ, 0);

+    if (ret < 0) {

+        printf("Send DUMPFILE_LINK_REQ failed\n");

+        ret = -1;

+        goto exit;

+    }	

+	

+	ret = mdp_receive_ack_and_info(DUMPFILE_LINK_RSP, &file_number, sizeof(file_number));

+	/*

+    if (ret < 0) {

+        printf("mdp_receive_ack_and_filenum failed\n");

+        ret = -1;

+        goto exit;

+    }

+    */

+	

+    printf("file_number = %d\n", file_number);

+    for (i=0; i<file_number; i++) {

+        printf("dump file index=%d ...\n", i);

+        ret = dump_file(i, path);

+        if (ret < 0) {

+            printf("dump file index=%d failed\n", i);

+            ret =  -1;

+            goto exit;

+        }

+        printf("dump file index=%d success\n", i);

+    }

+	ret = mdp_send_command(DUMPFILE_END_REQ, 0);

+    if (ret < 0) {

+        printf("failed to send DUMPFILE_END_REQ\n");

+        ret = -1;

+        goto exit;

+    }

+    mdp_receive_ack(DUMPFILE_END_RSP);

+    ret = 0;

+exit:

+    if (g_modem_fd > 0)

+        close(g_modem_fd);

+    return ret;

+}

+

+void broadcast_ramdump_result(int success)

+{

+    char command[256];

+    sprintf(command, "am broadcast -a zte.com.cn.intent_modemramdump_finished --ez extra_success %s", (success == 0 ? "true" : "false"));

+    printf("%s\n" , command);

+    system(command);

+}

+#if 0

+static void  compress_and_rm_fold(char *pfold, char *time_str)

+{

+    char buffer[512] = {0};

+    int ret = 0;

+    printf("%s %s %s\n", pfold, time_str);

+    snprintf(buffer, 512, "cd %s;tar -zcf %s.tgz %s/*\n", pfold, time_str, time_str);

+    printf("%s %s\n" , buffer);

+    ret = system(buffer);

+    if(ret !=  0){

+        printf("compress failed, delete the unfinished compressed file\n");

+        snprintf(buffer, 512, "cd %s;rm -rvf  %s.tgz \n", pfold, time_str);

+    }else {

+        printf("compress finished, delete the source fold\n");

+        snprintf(buffer, 512, "cd %s; rm -rvf %s\n", pfold, time_str);

+    }

+    printf("%s %s\n", buffer);

+    system(buffer);

+}

+#endif

+static int get_time_str(char*buf, size_t size)

+{

+    struct tm cur_tm;

+    time_t now = time(NULL);

+    if (NULL==buf || size<=0)

+        return -1;

+    localtime_r(&now, &cur_tm);

+    strftime(buf, size, "%Y_%m%d_%H%M%S", &cur_tm);

+    printf("%s\n", buf);

+    return 0;

+}

+static int get_ramdump_fold_name(char*ramdump_path, size_t size, char *time_buffer)

+{

+    if (ramdump_path==NULL || size<=0 || time_buffer==NULL)

+    {

+        return -1;

+    }

+    snprintf(ramdump_path, size, "%s/%s", g_ramdump_path, time_buffer); 

+    printf("ramdump_path: %s\n", ramdump_path);

+    return 0;

+}

+

+/***********************************************************************************

+º¯Êý˵Ã÷£ºramdump²Ù×÷Ïß³Ì

+Êä   È룺

+Êä   ³ö£º

+·µ »Ø Öµ£º

+Æä   Ëû£º

+***********************************************************************************/

+static void* ramdump_entry(void *arg)

+{

+    int ret = -1;

+    char dev_tty[256] = {0};

+    char dump_path[256] = {0};

+    char time_str[64] = {0};

+

+    // property_set("ctl.stop", "ztemodemlog");

+    /*

+    if(get_time_str(time_str, 64) < 0){

+        printf("Can't get the time str\n");

+        return NULL;

+    }

+    */

+	get_time_str(time_str, 64);

+    ret = get_ramdump_fold_name(dump_path, 256, time_str);

+	/*

+    if (ret < 0) {

+        printf("Can't get the ramdump fold path\n");

+        return NULL;

+    }	*/

+    memcpy(dev_tty, ramdump_dev, 256);

+       

+    printf("try to get the ramdump data from %s\n", ramdump_dev);

+	

+    ret = do_modem_ramdump(ramdump_dev,dump_path);

+	#if 0//for test

+    if (ret >= 0) 

+    {

+    	printf("get the ramdump data from %s success\n", dev_tty);

+    	compress_and_rm_fold(dump_path, time_str);

+       

+    }

+    else

+    {

+    	printf("get the ramdump data from %s failed\n", dev_tty);

+    }

+	#endif

+    return NULL;

+}

+

+static void init_output_flash_mode()

+{	   

+    if(test_dir_exist(DEFAULT_RAMDUMP_PATH) < 0)

+    {

+        printf("test_dir_exist failed:%s. \n", DEFAULT_RAMDUMP_PATH);

+    	return;

+    }

+    g_ramdump_path = DEFAULT_RAMDUMP_PATH;

+}

+

+static int init_output_u_mode()

+{

+    if(test_dir_exist(ZTE_LOG_PATH) < 0)//ÅжϸùĿ¼

+    {

+    	printf("test_dir_exist failed:%s. \n", ZTE_LOG_PATH);

+    	return -1;

+    }

+    if(test_dir_exist(RAMDUMP_LOG_PATH) < 0)//ÅжÏramdumpÈÕ־Ŀ¼ÊÇ·ñ´æÔÚ

+    {

+    	printf("test_dir_exist failed:%s. \n", RAMDUMP_LOG_PATH);

+    	return -1;

+    }

+    g_ramdump_path = RAMDUMP_LOG_PATH;       

+    return 0;

+}

+

+int init_ramdump_output_dir(E_FLASH_MODE mode)

+{	  

+    int ret = -1;

+    pthread_t ramdump_thread = -1;

+

+    if(mode == FLASH_MODE_NOMAL)

+    {

+        init_output_flash_mode();

+    }

+    else if(mode == FLASH_MODE_U)

+    {

+        init_output_u_mode();

+    }

+    else

+    {

+        return -1;

+    }

+    ret = pthread_create(&ramdump_thread, NULL, ramdump_entry, NULL);

+    return ret;

+}

+

+static int send_ramdump_rules_to_cp(char *buf, int read_len)

+{

+    int write_len = write(ramdump_fd, buf, read_len);

+	if (write_len != read_len)

+	{

+		printf("modem_log, send_rule error, write_len = %d, len = %d. \n", write_len, read_len);

+		return -1;

+	}

+    return 0;

+}

+

+void *get_rule_from_ramdump_dev(void* args)

+{

+	char *pbuf = NULL;

+    int read_len = 0;

+	pbuf = (char *)malloc(8*1024);

+	if(pbuf == NULL)

+	{

+		return NULL;

+	}

+

+    while(1)

+    {   		

+		read_len = read(usb_ramdump_dev_fd, pbuf, 8*1024);

+

+        if(read_len > 0)

+        {

+        	//send_rules_to_ramdump(pbuf, read_len);//Ïòramdump·¢Ë͹æÔò

+			send_ramdump_rules_to_cp(pbuf, read_len);

+            	

+        }

+		else

+		{

+			sleep(2);

+		}

+    }

+    return NULL;

+}

+

+static void* init_usb_trap_device(void* args)

+{

+    int ret_ramdump = -1;

+    int fd = -1;

+	

+	while(TRUE)

+	{

+	    //ret_ramdump = close(usb_ramdump_dev);

+		fd = open(usb_ramdump_dev, O_RDWR);

+		if (fd < 0)

+		{

+			sleep(1);

+			printf("usb_ramdump_dev open fail\n");

+		}

+		else

+		{

+		    printf("usb_ramdump_dev open success\n");

+			break;

+		}

+	}

+	usb_ramdump_dev_fd = fd;

+

+    ret_ramdump=pthread_create(&usb_ramdump_dev_thread, NULL, get_rule_from_ramdump_dev, NULL);

+    if(ret_ramdump != 0)

+    {	

+    	printf("pthread_create cp_interact_thread error\n"); 

+    }	

+

+    return NULL;

+}

+

+int init_ramdump_device()

+{

+    int ret = -1;

+	pthread_t  trap_dev_thread = -1;

+

+    ret=pthread_create(&trap_dev_thread, NULL, init_usb_trap_device, NULL);

+    if(ret != 0)

+    {	

+    	printf("pthread_create init_ramdump_device error\n"); 

+    	return -1;

+    }	

+	g_cp_trap_flag = FALSE;

+    return ret;

+}

+

+int ramdump_trap_rev_close(VOID)

+{

+    int ret = -1;	 

+	

+    ret = close(usb_ramdump_dev_fd);

+    if (ret < 0)

+    {

+        printf("open devtty GS0  error!!!\n");

+        return -1;  

+    }

+	usb_ramdump_dev_fd = -1;

+    return ret;

+}

+

+#endif

+

+

+

diff --git a/ap/app/zte_log_agent/hdlc.c b/ap/app/zte_log_agent/hdlc.c
new file mode 100644
index 0000000..a4744b3
--- /dev/null
+++ b/ap/app/zte_log_agent/hdlc.c
@@ -0,0 +1,263 @@
+/**

+* 

+* @file      hdlc.c

+* @brief     

+*            This file is part of tools.

+*            hdlc encode/decode lib

+*            

+* @details   

+* @author    Tools Team.

+* @email     

+* @copyright Copyright (C) 2013 Sanechips Technology Co., Ltd.

+* @warning   

+* @date      2019/02/02

+* @version   1.1

+* @pre       

+* @post      

+*            

+* @par       

+* Change History :

+* ---------------------------------------------------------------------------

+* date        version  author         description

+* ---------------------------------------------------------------------------

+* 2013/01/21  1.0      lu.xieji       Create file

+* 2019/02/02  1.1      jiang.fenglin  ÐÞ¸Ä×¢ÊÍ·½Ê½Îªdoxygen

+* ---------------------------------------------------------------------------

+* 

+* 

+*/

+

+

+#include "log_agent.h"

+

+#define HDLC_CONTROL_CHAR   0x7E  // ½áÊø·û

+#define HDLC_ESC_CHAR       0x7D  // תÒë×Ö·ûÖµ

+#define HDLC_ESC_MASK       0x20  // תÒëÔËËãÖµ

+#define HDLC_TAIL_SIZE      3     // β²¿Ìí¼Ó×Ö·û³¤¶È

+

+// CRC table for 16 bit CRC, with generator polynomial 0x8408, calculated 8 bits at a time, LSB first.

+#define CRC_TAB_SIZE        256   // 2^CRC_TAB_BITS

+#define CRC_16_L_SEED       0xFFFF

+#define CRC_16_L_POLYNOMIAL 0x8408

+#define CRC_16_L_OK         0x0F47

+

+#define CRC_16_L_STEP(xx_crc, xx_c) \

+	(((xx_crc) >> 8) ^ crc_16_l_table[((xx_crc) ^ (xx_c)) & 0x00ff])

+

+const unsigned short crc_16_l_table[CRC_TAB_SIZE] =

+{

+    0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf,

+    0x8c48, 0x9dc1, 0xaf5a, 0xbed3, 0xca6c, 0xdbe5, 0xe97e, 0xf8f7,

+    0x1081, 0x0108, 0x3393, 0x221a, 0x56a5, 0x472c, 0x75b7, 0x643e,

+    0x9cc9, 0x8d40, 0xbfdb, 0xae52, 0xdaed, 0xcb64, 0xf9ff, 0xe876,

+    0x2102, 0x308b, 0x0210, 0x1399, 0x6726, 0x76af, 0x4434, 0x55bd,

+    0xad4a, 0xbcc3, 0x8e58, 0x9fd1, 0xeb6e, 0xfae7, 0xc87c, 0xd9f5,

+    0x3183, 0x200a, 0x1291, 0x0318, 0x77a7, 0x662e, 0x54b5, 0x453c,

+    0xbdcb, 0xac42, 0x9ed9, 0x8f50, 0xfbef, 0xea66, 0xd8fd, 0xc974,

+    0x4204, 0x538d, 0x6116, 0x709f, 0x0420, 0x15a9, 0x2732, 0x36bb,

+    0xce4c, 0xdfc5, 0xed5e, 0xfcd7, 0x8868, 0x99e1, 0xab7a, 0xbaf3,

+    0x5285, 0x430c, 0x7197, 0x601e, 0x14a1, 0x0528, 0x37b3, 0x263a,

+    0xdecd, 0xcf44, 0xfddf, 0xec56, 0x98e9, 0x8960, 0xbbfb, 0xaa72,

+    0x6306, 0x728f, 0x4014, 0x519d, 0x2522, 0x34ab, 0x0630, 0x17b9,

+    0xef4e, 0xfec7, 0xcc5c, 0xddd5, 0xa96a, 0xb8e3, 0x8a78, 0x9bf1,

+    0x7387, 0x620e, 0x5095, 0x411c, 0x35a3, 0x242a, 0x16b1, 0x0738,

+    0xffcf, 0xee46, 0xdcdd, 0xcd54, 0xb9eb, 0xa862, 0x9af9, 0x8b70,

+    0x8408, 0x9581, 0xa71a, 0xb693, 0xc22c, 0xd3a5, 0xe13e, 0xf0b7,

+    0x0840, 0x19c9, 0x2b52, 0x3adb, 0x4e64, 0x5fed, 0x6d76, 0x7cff,

+    0x9489, 0x8500, 0xb79b, 0xa612, 0xd2ad, 0xc324, 0xf1bf, 0xe036,

+    0x18c1, 0x0948, 0x3bd3, 0x2a5a, 0x5ee5, 0x4f6c, 0x7df7, 0x6c7e,

+    0xa50a, 0xb483, 0x8618, 0x9791, 0xe32e, 0xf2a7, 0xc03c, 0xd1b5,

+    0x2942, 0x38cb, 0x0a50, 0x1bd9, 0x6f66, 0x7eef, 0x4c74, 0x5dfd,

+    0xb58b, 0xa402, 0x9699, 0x8710, 0xf3af, 0xe226, 0xd0bd, 0xc134,

+    0x39c3, 0x284a, 0x1ad1, 0x0b58, 0x7fe7, 0x6e6e, 0x5cf5, 0x4d7c,

+    0xc60c, 0xd785, 0xe51e, 0xf497, 0x8028, 0x91a1, 0xa33a, 0xb2b3,

+    0x4a44, 0x5bcd, 0x6956, 0x78df, 0x0c60, 0x1de9, 0x2f72, 0x3efb,

+    0xd68d, 0xc704, 0xf59f, 0xe416, 0x90a9, 0x8120, 0xb3bb, 0xa232,

+    0x5ac5, 0x4b4c, 0x79d7, 0x685e, 0x1ce1, 0x0d68, 0x3ff3, 0x2e7a,

+    0xe70e, 0xf687, 0xc41c, 0xd595, 0xa12a, 0xb0a3, 0x8238, 0x93b1,

+    0x6b46, 0x7acf, 0x4854, 0x59dd, 0x2d62, 0x3ceb, 0x0e70, 0x1ff9,

+    0xf78f, 0xe606, 0xd49d, 0xc514, 0xb1ab, 0xa022, 0x92b9, 0x8330,

+    0x7bc7, 0x6a4e, 0x58d5, 0x495c, 0x3de3, 0x2c6a, 0x1ef1, 0x0f78

+};

+

+

+/**

+* @brief HDLC±àÂë

+* @param[out] dest Ä¿±êT_HDLC_BUFFER_TYPEÖ¸Õë

+* @param[in] src Ô´T_HDLC_BUFFER_TYPEÖ¸Õë

+* @return ³É¹¦·µ»ØTRUE£»Ê§°Ü·µ»ØFALSE

+* @note

+* @see 

+*/

+BOOL hdlc_encode(T_HDLC_BUFFER_TYPE *dest, const T_HDLC_BUFFER_TYPE *src)

+{

+    if (dest && src && dest->buf && src->buf \

+            && dest->bufSize > dest->bufIndex && src->bufSize > src->bufIndex)

+    {

+        unsigned char *dest_buf	= dest->buf + dest->bufIndex;

+        unsigned char *src_buf	= src->buf + src->bufIndex;

+        unsigned char src_byte = 0;

+        unsigned short crc = CRC_16_L_SEED;

+        unsigned int converted_length = 0;

+        unsigned int i, src_length;

+        src_length = src->bufSize - src->bufIndex;

+

+        for (i = 0; i < src_length; i++)

+        {

+            src_byte = src_buf[i];

+

+            if ((src_byte == HDLC_CONTROL_CHAR) || (src_byte == HDLC_ESC_CHAR))

+            {

+                crc = CRC_16_L_STEP(crc, src_byte);

+                dest_buf[converted_length++] = HDLC_ESC_CHAR;

+                dest_buf[converted_length++] = src_byte ^ HDLC_ESC_MASK;

+            }

+            else

+            {

+                crc = CRC_16_L_STEP(crc, src_byte);

+                dest_buf[converted_length++] = src_byte;

+            }

+        }

+

+        crc = ~crc;

+        //  ¶ÔµÚÒ»¸öunsigned charµÄcrc½øÐÐתÒë

+        src_byte = (crc & 0xFF);

+

+        if ((src_byte == HDLC_CONTROL_CHAR) || (src_byte == HDLC_ESC_CHAR))

+        {

+            dest_buf[converted_length++] = HDLC_ESC_CHAR;

+            dest_buf[converted_length++] = src_byte ^ HDLC_ESC_MASK;

+        }

+        else

+        {

+            dest_buf[converted_length++] = src_byte;

+        }

+

+        // ¶ÔµÚ¶þ¸öunsigned charµÄcrc½øÐÐתÒë

+        src_byte = (crc >> 8);

+

+        if ((src_byte == HDLC_CONTROL_CHAR) || (src_byte == HDLC_ESC_CHAR))

+        {

+            dest_buf[converted_length++] = HDLC_ESC_CHAR;

+            dest_buf[converted_length++] = src_byte ^ HDLC_ESC_MASK;

+        }

+        else

+        {

+            dest_buf[converted_length++] = src_byte;

+        }

+

+        // Ìí¼Ó½áÊø·û

+        dest_buf[converted_length++] = HDLC_CONTROL_CHAR;

+        dest->bufIndex = converted_length;

+        return TRUE;

+    }

+    else

+    {

+        return FALSE;

+    }

+}

+

+/**

+* @brief 16λcrcУÑ鼯Ë㣬

+* @param[in] buf_ptr ´ýУÑéÊý¾ÝÖ¸Õë

+* @param[in] len ´ýУÑéÊý¾Ý³¤¶È

+* @return crcУÑéÖµ£¬Èç¹ûbuf_ptr×îºóÁ½Î»°üº¬ÁËУÑ飬½«·µ»ØCRC_16_L_OK

+* @note

+* @see 

+*/

+unsigned short crc_16_l_calc(unsigned char *buf_ptr, unsigned int len)

+{

+    unsigned short crc_16;

+

+    for (crc_16 = CRC_16_L_SEED ; len >= 8; len -= 8, buf_ptr++)

+    {

+        crc_16 = crc_16_l_table[(crc_16 ^ *buf_ptr) & 0x00ff ] ^ (crc_16 >> 8);

+    }

+

+    return(~crc_16);

+}

+

+

+/**

+* @brief HDLC½âÂë

+* @param[out] dest Ä¿±êT_HDLC_BUFFER_TYPEÖ¸Õë

+* @param[in] src Ô´T_HDLC_BUFFER_TYPEÖ¸Õë

+* @return ³É¹¦·µ»ØTRUE£»Ê§°Ü·µ»ØFALSE

+* @note

+* @see 

+*/

+BOOL hdlc_decode(T_HDLC_BUFFER_TYPE *dest, T_HDLC_BUFFER_TYPE *src)

+{

+    if (dest != NULL && src != NULL && dest->buf != NULL && src->buf != NULL &&

+            src->bufSize > src->bufIndex && dest->bufSize > dest->bufIndex)

+    {

+        unsigned char *dest_buf	= dest->buf + dest->bufIndex;

+        unsigned char *src_buf	= src->buf + src->bufIndex;

+        unsigned int dest_length = dest->bufSize - dest->bufIndex;

+        unsigned int src_length  = src->bufSize - src->bufIndex;

+

+        unsigned char src_byte = 0;

+        unsigned int converted_length = 0;

+        BOOL findEnd = FALSE;

+        unsigned int i;

+

+        for (i = 0; i < src_length; i++)

+        {

+            src_byte = src_buf[i];

+

+            if (src_byte == HDLC_ESC_CHAR)

+            {

+                if (i == (src_length - 1))

+                {

+                    break;

+                }

+                else

+                {

+                    dest_buf[converted_length++] = src_buf[++i] ^ HDLC_ESC_MASK;

+                }

+            }

+            else if (src_byte == HDLC_CONTROL_CHAR)

+            {

+                dest_buf[converted_length++] = src_byte;

+                i++;

+                findEnd = TRUE;

+                break;

+            }

+            else

+            {

+                dest_buf[converted_length++] = src_byte;

+            }

+

+            if (converted_length >= dest_length)

+            {

+                i++;

+                break;

+            }

+        }

+

+        src->bufIndex += i;

+        dest->bufIndex += converted_length;

+

+        if (findEnd)

+        {

+            unsigned short crc = crc_16_l_calc(dest->buf, (dest->bufIndex - 1) * 8);

+

+            if (crc == CRC_16_L_OK)

+            {

+                dest->bufIndex -= HDLC_TAIL_SIZE;

+            }

+            else

+            {

+                dest->bufIndex = 0;

+                findEnd = FALSE;

+            }

+        }

+

+        return findEnd;

+    }

+    else

+    {

+        return FALSE;

+    }

+}

+

diff --git a/ap/app/zte_log_agent/log_agent.h b/ap/app/zte_log_agent/log_agent.h
new file mode 100644
index 0000000..3d94767
--- /dev/null
+++ b/ap/app/zte_log_agent/log_agent.h
@@ -0,0 +1,276 @@
+/**

+ * 

+ * @file      log_agent.h

+ * @brief     

+ *            This file is part of ZCAT.

+ *            zcatÓ¦Óòãlog_agent app¹«¹²Í·Îļþ

+ *            

+ * @details   

+ * @author    Tools Team.

+ * @email     

+ * @copyright Copyright (C) 2013 Sanechips Technology Co., Ltd.

+ * @warning   

+ * @date      2019/02/02

+ * @version   1.1

+ * @pre       

+ * @post      

+ *            

+ * @par       

+ * Change History :

+ * ---------------------------------------------------------------------------

+ * date        version  author         description

+ * ---------------------------------------------------------------------------

+ * 2017/07/17  1.0      hou.bing       Create file

+ * 2019/02/02  1.1      jiang.fenglin  ÐÞ¸Ä×¢ÊÍ·½Ê½Îªdoxygen

+ * 2019/07/08  1.2      jiang.fenglin  Ôö¼ÓAPFS/CPFSģʽ

+ * ---------------------------------------------------------------------------

+ * 

+ * 

+ */

+

+

+#ifndef ZTE_LOG_AP_AGENT_H_

+#define ZTE_LOG_AP_AGENT_H_

+

+#include <unistd.h>

+#include <stdlib.h>

+#include <stdio.h>

+#include <errno.h>

+#include <sys/socket.h>

+#include <fcntl.h>

+#include <sys/types.h>

+#include <sys/stat.h>

+#include <netinet/in.h>

+#include <arpa/inet.h>

+#include <dirent.h>

+

+//#include "../include/message.h"

+//#include "../include/zte_log.h"

+

+

+/********************************************

+* receive result

+********************************************/

+

+#define RAMDUMP_RECEIVE_RESULT_SYS_CRASH 0x0010 

+

+/********************************************

+* verify result

+********************************************/

+#define KERNEL_LOG_DEFAULT_LEVEL LEVEL_INFOMATION

+#define APP_LOG_DEFAULT_LEVEL    LEVEL_INFOMATION

+

+#define AP_LOG_MAX_LENGTH   260

+#define READ_BUFFER_SIZE    (1024 * 16)

+#define MAX_DATA_LEN 2048

+

+#define TRUE  1

+#define FALSE 0

+

+/* ͨѶģ¿éºÅ */

+#define MDL_TOOLS_BASE            (100)

+#define SUBMDL_TOOLAGENT_SET      (85)

+#define MDL_ZCAT                  (MDL_TOOLS_BASE + 15)      /* ZCAT¹¤¾ß          */

+#define SUBMDL_ZCATAGT            (SUBMDL_TOOLAGENT_SET + 0)  /* ZCAT¹¤¾ß´úÀí */

+

+#define MDL_PHONE                 (1)                     /* ÊÖ»ú             */

+

+/* ÈÕÖ¾Á÷ÏòÖ¾ */

+#define DIR_LOG_TCARD_VALUE 0x01

+#define DIR_LOG_NET_VALUE   0x02

+#define DIR_LOG_USB_VALUE   0x03

+#define DIR_LOG_USB_AP_VALUE   0x04

+

+#define MAX_STRING_LENGTH    256

+typedef int BOOL;

+typedef void VOID;

+

+typedef signed char         SINT8;  /* sc */

+typedef unsigned char       UINT8;  /* c */

+

+typedef short               SINT16; /* sw */

+typedef unsigned short      UINT16; /* w */

+typedef long                SINT32; /* sdw */

+typedef unsigned int        UINT32; /* dw */

+typedef struct

+{

+    unsigned char *buf;

+    unsigned int bufIndex; // Ö¸ÕëÆ«ÒÆ

+    unsigned int bufSize;

+} T_HDLC_BUFFER_TYPE;

+

+typedef enum

+{

+    LEVEL_EMERGENCY = 0,    // ÓÃÓÚ½ô¼±Ê¼þÏûÏ¢£¬Ò»°ãÊÇϵͳ±ÀÀ£Ö®Ç°ÌáʾµÄÏûÏ¢

+    LEVEL_ALERT,            // ÓÃÓÚÐèÒªÁ¢¼´²ÉÈ¡¶¯×÷µÄÇé¿ö

+    LEVEL_CRITICAL,         // ÁÙ½ç״̬£¬Í¨³£Éæ¼°ÑÏÖØµÄÓ²¼þ»òÈí¼þ²Ù×÷ʧ°Ü

+    LEVEL_ERROR,            // ÓÃÓÚ±¨¸æ´íÎó״̬£¬ÈçÉ豸Çý¶¯³ÌÐò¾­³£ÓÃÀ´±¨¸æÀ´×ÔÓ²¼þµÄÎÊÌâ

+    LEVEL_WARNING,          // ¶Ô¿ÉÄܳöÏÖÎÊÌâµÄÇé¿ö½øÐо¯¸æ£¬Í¨³£²»»á¶ÔϵͳÔì³ÉÑÏÖØÎÊÌâ

+    LEVEL_NOTICE,           // ÓбØÒª½øÐÐÌáʾµÄÕý³£ÇéÐΣ¬ÈçÓ밲ȫÏà¹ØµÄ×´¿ö»ã±¨

+    LEVEL_INFOMATION,       // ÌáʾÐÔÐÅÏ¢£¬ÈçÇý¶¯³ÌÐòÔÚÆô¶¯Ê±´òÓ¡ËûÃÇÕÒµ½µÄÓ²¼þÐÅÏ¢

+    LEVEL_DEBUG,            // ÓÃÓÚµ÷ÊÔÐÅÏ¢

+    LEVEL_PRICNT

+} E_ZCAT_AP_PRIORITY;

+

+//AP Header ½á¹¹¶¨Òå

+typedef struct

+{

+    unsigned char priority;

+    unsigned char mod;

+    unsigned short len;

+} T_ZCAT_APLOG_HEADER;

+typedef struct

+{

+    unsigned char *buf;

+    unsigned short len;

+    unsigned short newLine;

+} T_AP_DEST_BUFFER_TYPE;

+

+typedef struct

+{

+    unsigned char *buf;

+    unsigned int beginIndex;

+    unsigned int bufSize;

+} T_AP_SRC_BUFFER_TYPE;

+

+// ZCAT Header½á¹¹¶¨Òå

+typedef struct

+{

+    unsigned char   cmd_code;

+    unsigned char   padding;

+    unsigned short  reserved;

+    unsigned int  length;

+    unsigned int  timeStamp[2];

+} T_ZCAT_HEADER;

+

+//DIAG Header ½á¹¹¶¨Òå

+typedef struct

+{

+    unsigned short diag_id;

+    unsigned short len;

+} T_ZCAT_DIAG_HEADER;

+

+typedef struct

+{

+    UINT16 type;

+    UINT8  operation;

+    UINT8  reserved;

+} T_ZCAT_DIAG_CONFIG_REQ;

+

+typedef enum

+{

+    ZCAT_SIG_REPORT    = 1,

+    ZCAT_EVT_REPORT    = 2,

+    ZCAT_PRN_REPORT    = 3,

+    ZCAT_DBG_REPORT    = 4,

+    ZCAT_IPPPP_REPORT  = 5,

+    ZCAT_DIAG_REPORT   = 6,

+    ZCAT_DIAG_NULL,   //ֻռһ룬²»Ê¹Óã¬Ê¹ÓëPC¶ÔÆë

+

+    ZCAT_AP_KERNEL_LOG = 8,

+    ZCAT_AP_APP_LOG    = 9,

+

+    ZCAT_CMDCODE_MAX

+} T_ZCAT_CMDCODE;

+

+typedef enum 

+{

+    ZCAT_SIG_TYPE               = ZCAT_SIG_REPORT,

+    ZCAT_EVENT_TYPE             = ZCAT_EVT_REPORT,

+    ZCAT_PRINT_TYPE             = ZCAT_PRN_REPORT,

+    ZCAT_DBG_TYPE               = ZCAT_DBG_REPORT,

+    ZCAT_IPPPP_TYPE             = ZCAT_IPPPP_REPORT,

+    ZCAT_DIAG_TYPE              = ZCAT_DIAG_REPORT, 

+    ZCAT_AP_KERNEL_TYPE         = ZCAT_AP_KERNEL_LOG,

+    ZCAT_AP_APP_TYPE            = ZCAT_AP_APP_LOG,

+

+    ZCAT_ALL_TYPE               = 0xFFFF

+} ZCAT_ENUM_TYPE;

+

+// Comm½á¹¹¶¨Òå

+typedef struct

+{

+    unsigned char  msg_type;                   /* ÏûÏ¢ÀàÐÍ */

+    unsigned char  pad;                        /* Ìî³äλ */

+    unsigned short reserved;                   /* ±£Áô×ֶΣ¬ÌîΪ0xAAAA */

+    unsigned char  tgt_mdl_no;                 /* Ä¿±ê(½ÓÊÕÏûÏ¢)Ä£¿éÄ£¿éºÅ */

+    unsigned char  tgt_submdl_no;              /* Ä¿±ê(½ÓÊÕÏûÏ¢)Ä£¿é×ÓÄ£¿éºÅ */

+    unsigned char  src_mdl_no;                 /* Ô´(·¢ËÍÏûÏ¢)Ä£¿éÄ£¿éºÅ */

+    unsigned char  src_submdl_no;              /* Ô´(·¢ËÍÏûÏ¢)Ä£¿é×ÓÄ£¿éºÅ */

+    unsigned int buf_len;                      /* ÏûÏ¢Êý¾Ý³¤¶È(²»º¬ÏûϢͷ) */

+} T_COMM_TYPE;

+

+typedef enum

+{

+    ZCAT_STATE_INIT = 0,

+    ZCAT_STATE_RUNNING,

+    ZCAT_STATE_STOP,

+    ZCAT_STATE_EXIT

+} E_ZCAT_STATE;

+

+typedef enum

+{

+    ZCAT_MODE_AP_USB = 0xC1,

+    ZCAT_MODE_AP_NET,

+    ZCAT_MODE_AP_TF,

+    ZCAT_MODE_AP_FS,

+    ZCAT_MODE_CP_USB,

+    ZCAT_MODE_CP_TF,

+    ZCAT_MODE_CP_NET,

+    ZCAT_MODE_CP_FS

+} E_ZCAT_MODE;

+

+typedef enum

+{

+    ZCAT_IPC_SYN = 0xA0,

+    ZCAT_IPC_ACK,

+    ZCAT_IPC_ESTABLISHED,

+    ZCAT_IPC_SET_TTY,

+    ZCAT_IPC_SET_PERIPHERAL_MODE,

+    ZCAT_IPC_STOP,

+    ZCAT_IPC_START,

+    ZCAT_IPC_EXIT

+} E_ZCAT_IPC_HANDSHAKE;

+

+

+typedef enum

+{

+    FLASH_MODE_NOMAL = 1,

+    FLASH_MODE_U = 2

+} E_FLASH_MODE;

+

+typedef enum

+{

+    DIAG_FILTER_CONFIG = 1,

+    DIAG_DROP_COUNT,

+    DIAG_LINK_MSG,

+    DIAG_SIG_CONTROL_MSG,

+    DIAG_NV_MSG,

+    DIAG_LTE_CONTROL_MSG,

+    DIAG_PS_GLB_MSG,

+    DIAG_PS_FILTERRANK_MSG,

+    DIAG_UE_MEM_LOOKUP,

+    DIAG_RAMDUMP_MSG,

+    DIAG_TSPVERSION_MSG,

+    DIAG_SYSVIEW_MSG,

+    DIAG_CP_STATUS

+}DIAG_CONDITION;

+

+

+/*ÈÕÖ¾´æT¿¨²ÎÊý*/

+typedef struct

+{

+    char log_dir[MAX_STRING_LENGTH];

+    char log_name[MAX_STRING_LENGTH];

+	char rule_path[MAX_STRING_LENGTH];

+    int max_file_size;

+    int max_file_num;

+    int log_overwrite;

+    int compress_log_files;

+    int file_counts;

+    int output_fd;

+    int file_size;

+	int free_space_limit;

+}T_LOG_SDCARD_PARA;

+

+#endif /* ZTE_LOG_AP_AGENT_H_ */

diff --git a/ap/app/zte_log_agent/log_agent_main.c b/ap/app/zte_log_agent/log_agent_main.c
new file mode 100644
index 0000000..9a21cd6
--- /dev/null
+++ b/ap/app/zte_log_agent/log_agent_main.c
@@ -0,0 +1,299 @@
+/**

+ * 

+ * @file      log_agent_main.c

+ * @brief     

+ *            This file is part of ZCAT.

+ *            log_agentÈë¿ÚÎļþ£¬´¦ÀíNVÊäÈë²ÎÊý£¬¸ù¾Ý²»Í¬ÍâÉèģʽ´¦ÀíÊý¾ÝÁ÷Ïò

+ *            NV²ÎÊý°üÀ¨:

+ *            zcat_mode

+ *                APUSB - Ó¦Óòã²Ù×÷usb¿Ú´«Êälog

+ *                APTF  - Ó¦ÓÃ²ã´æ´¢logµ½TF¿¨

+ *                APNET - Ó¦Óòã²Ù×÷socket´«Êälog

+ *                APFS  - Ó¦ÓÃ²ã´æ´¢logµ½Îļþϵͳ/var/zcatĿ¼

+ *                CPUSB - Äں˲ã²Ù×÷usb¿Ú´«Êälog

+ *                CPTF  - ÄÚºË²ã´æ´¢logµ½TF¿¨

+ *                CPNET - Äں˲ã²Ù×÷socket´«Êälog

+ *                CPFS  - ÄÚºË²ã´æ´¢logµ½Îļþϵͳ/var/zcatĿ¼

+ *            zcat_usblog

+ *                Ö¸¶¨log¿Útty·¾¶£¬ÀýÈç: ttyGS2

+ *            

+ * @details   

+ * @author    Tools Team.

+ * @email     

+ * @copyright Copyright (C) 2013 Sanechips Technology Co., Ltd.

+ * @warning   

+ * @date      2019/02/22

+ * @version   1.6

+ * @pre       

+ * @post      

+ *            

+ * @par       

+ * Change History :

+ * ---------------------------------------------------------------------------

+ * date        version  author         description

+ * ---------------------------------------------------------------------------

+ * 2017/07/17  1.0      hou.bing       Create file

+ * 2019/01/24  1.1      jiang.fenglin  1.Ìí¼Óusblog¶ÁÐ´Ëø

+ *                                     2.Ìí¼ÓÏß³ÌÃû³Æ

+ * 2019/01/25  1.2      jiang.fenglin  Ôö¼ÓAPUSBģʽÏÂtty·¾¶ÅäÖù¦ÄÜ

+ * 2019/02/02  1.3      jiang.fenglin  ÐÞ¸Ä×¢ÊÍ·½Ê½Îªdoxygen,¹æ·¶ÃüÃû

+ * 2019/02/02  1.4      jiang.fenglin  empty log_agent_usb.c

+ * 2019/02/22  1.5      jiang.fenglin  ¶¯Ì¬¿ÉÅäÖÃLOG¶Ë¿Ú,log¶Ë¿Ú¶¯Ì¬ÅäÖÃÖ»Õë¶ÔusbÅäÖÃΪÕý³£Ä£Ê½µÄÇé¿ö£¬¹¤³§Ä£Ê½±£³Ö²»±ä

+ * 2019/03/04  1.6      jiang.fenglin  Çå±àÒ뾯¸æ

+ * 2019/07/08  1.7      jiang.fenglin  Ôö¼ÓAPFS/CPFSģʽ

+ * ---------------------------------------------------------------------------

+ * 

+ * 

+ */

+

+#include <stdarg.h>

+#include <string.h>

+#include <pthread.h>

+#include <sys/msg.h>

+#include <sys/ioctl.h>

+#include "log_agent.h"

+#include "cfg_api.h"

+

+E_ZCAT_MODE g_log_dir = ZCAT_MODE_CP_USB;

+E_ZCAT_STATE g_log_state = ZCAT_STATE_INIT;

+

+extern pthread_t read_kernellog_thread;

+extern pthread_t read_applog_thread;

+extern pthread_t read_cplog_thread;

+extern pthread_t read_usb_thread;

+extern pthread_t monitor_hotplug_thread;

+extern pthread_t read_wifi_thread;

+extern pthread_t rule_heartbeat_thread;

+

+extern const char* cplog_dev;

+extern const char* applog_dev;

+extern const char* kernellog_dev;

+

+extern int cplog_fd;

+extern int applog_fd;

+extern int kernellog_fd;

+

+extern int init_log_agent_tools();

+extern int init_usblog_mode();

+extern int init_sdcard_mode();

+extern int init_net_mode();

+

+extern void *read_applog(void* args);

+extern void *read_kernellog(void* args);

+extern void *read_cplog(void* args);

+

+extern char g_zcat_usblog[8]; // ´æ´¢usblogµÄttyÉ豸Ãû

+

+

+

+/**

+ * @brief µ±cp²àÍÂlogʱµÄ³õʼ»¯

+ * @param[in] void

+ * @return 1 on success, errno otherwise

+ * @note

+ * @see 

+ */

+int init_cp_mode()

+{

+    return 1;

+}

+

+

+/** 

+ * @brief zte_log_agentÈë¿Úº¯Êý£¬´¦ÀíNVÊäÈë²ÎÊý£¬¸ù¾Ý²»Í¬Ä£Ê½´¦ÀíÊý¾ÝÁ÷Ïò

+ *

+ * @return ·µ»ØËµÃ÷

+ *        -<em>-1</em> fail

+ *        -<em>0</em> succeed

+ */

+int main()

+{

+    char zcat_mode[16] = { 0 };

+    char zcat_usblog[8] = { 0 };

+    int ret = 0;

+

+    // 1.»ñÈ¡nvÖµ

+    cfg_get_item("zcat_mode", zcat_mode, sizeof(zcat_mode) - 1);

+    if (strcmp(zcat_mode, "APTF") == 0)

+    {

+        g_log_dir = ZCAT_MODE_AP_TF;

+    }

+    else if (strcmp(zcat_mode, "CPTF") == 0)

+    {

+        g_log_dir = ZCAT_MODE_CP_TF;

+    }

+	else if (strcmp(zcat_mode, "APFS") == 0)

+    {

+        g_log_dir = ZCAT_MODE_AP_FS;

+    }

+    else if (strcmp(zcat_mode, "CPFS") == 0)

+    {

+        g_log_dir = ZCAT_MODE_CP_FS;

+    }

+    else if (strcmp(zcat_mode, "APNET") == 0)

+    {

+        g_log_dir = ZCAT_MODE_AP_NET;

+    }

+    else if (strcmp(zcat_mode, "CPNET") == 0)

+    {

+        g_log_dir = ZCAT_MODE_CP_NET;

+    }

+    else if (strcmp(zcat_mode, "APUSB") == 0)

+    {

+        g_log_dir = ZCAT_MODE_AP_USB;

+    }

+    else

+    {

+        g_log_dir = ZCAT_MODE_CP_USB;

+    }

+

+    printf("[zcat] zcat_mode = 0x%x\n", g_log_dir);

+    

+    if (ZCAT_MODE_AP_USB == g_log_dir || ZCAT_MODE_CP_USB == g_log_dir)

+    {

+        cfg_get_item("zcat_usblog", zcat_usblog, sizeof(zcat_usblog) - 1);

+        if (strlen(zcat_usblog) > 3)

+        {

+            memcpy(g_zcat_usblog, zcat_usblog, sizeof(zcat_usblog));

+        }

+        printf("[zcat] zcat_usblog = %s\n", g_zcat_usblog);

+    }

+    

+

+    // 2.³õʼ»¯È«¾Ö±äÁ¿

+    init_log_agent_tools();

+    

+    // 3.¸ù¾Ýģʽ´ò¿ªlogÊý¾ÝÔ´É豸²¢´´½¨µÄ¹¤×÷Ïß³Ì

+    //   V3E²»ÐèÒª¶ÁÈ¡applogºÍkernellogÉ豸

+    cplog_fd = open(cplog_dev, O_RDWR);

+    if (cplog_fd < 0) {

+        goto __exit;

+    }

+   

+    if((g_log_dir == ZCAT_MODE_AP_USB) || (g_log_dir == ZCAT_MODE_AP_TF) || (g_log_dir == ZCAT_MODE_AP_NET) || (g_log_dir == ZCAT_MODE_AP_FS))

+    {

+        // 3.1 ´ò¿ªÊý¾ÝÔ´É豸

+        #if 0

+        applog_fd = open(applog_dev, O_RDWR);

+        if (applog_fd < 0) {

+            goto __exit;

+        }

+        kernellog_fd = open(kernellog_dev, O_RDWR);

+        if (kernellog_fd < 0) {

+            goto __exit;

+        }

+        #endif

+

+        // 3.2 ´´½¨Êý¾ÝÔ´É豸µÄ¶ÁдÏß³Ì

+        #if 0

+        ret = pthread_create(&read_applog_thread, NULL, read_applog, NULL);

+        if(ret != 0 ) {

+            goto __exit;

+        }

+        ret = pthread_create(&read_kernellog_thread, NULL, read_kernellog, NULL);

+        if(ret != 0) {

+            goto __exit;

+        }

+        #endif

+        ret = pthread_create(&read_cplog_thread, NULL, read_cplog, NULL);

+        if(ret != 0) {

+            goto __exit;

+        }

+    }

+    

+    printf("[zcat] init logdev success.\n");

+

+    // 4.³õʼ»¯Êý¾ÝÊä³öÍâÉè

+    switch(g_log_dir)

+    {

+        case ZCAT_MODE_AP_USB:

+        {

+            if(init_usblog_mode() < 0) {

+                goto __exit;

+            }

+            break;

+        }

+        case ZCAT_MODE_AP_TF:

+		case ZCAT_MODE_AP_FS:

+        {

+			/*

+            if(init_sdcard_mode() < 0) {

+                goto __exit;

+            }*/

+			init_sdcard_mode();

+            break;

+        }

+        case ZCAT_MODE_AP_NET:

+        {

+            if(init_net_mode() < 0) {

+                goto __exit;

+            }

+            break;

+        }

+        case ZCAT_MODE_CP_USB:

+        case ZCAT_MODE_CP_TF:

+        case ZCAT_MODE_CP_NET:

+		case ZCAT_MODE_CP_FS:

+        {

+

+          /*

+			if(init_cp_mode() < 0) {

+                goto __exit;

+            }

+		  */

+			init_cp_mode();

+            break;

+        }

+

+        default: {

+            goto __exit;

+        }

+    }

+    

+    g_log_state = ZCAT_STATE_RUNNING;

+    

+    // 5.³õʼ»¯Á÷³ÌÍê³É£¬Óëcpͬ²½

+    printf("[zcat] init peripheral success.\n");

+    

+    if(ioctl(cplog_fd, ZCAT_IPC_SET_PERIPHERAL_MODE, g_log_dir)!= 0)

+    {

+        printf("[zcat]ioctl:ZCAT_IPC_SET_PERIPHERAL_MODE fail!\n");

+    }

+    if(ioctl(cplog_fd, ZCAT_IPC_SET_TTY, g_zcat_usblog)!= 0)

+    {

+        printf("[zcat]ioctl:ZCAT_IPC_SET_TTY fail!\n");

+    }

+    if(ioctl(cplog_fd, ZCAT_IPC_SYN, 0)!=0)

+    {

+        printf("[zcat]ioctl:ZCAT_IPC_SYN fail!\n");

+	}

+

+    while(1)

+    {

+        ret = ioctl(cplog_fd, ZCAT_IPC_ACK, 0);

+        if(ret == 0)

+        {

+            ioctl(cplog_fd, ZCAT_IPC_ESTABLISHED, 0);

+            break;

+        }

+        sleep(1);

+    }

+

+__exit:

+    // 6. Í˳ö

+    if(read_kernellog_thread > 0) pthread_join(read_kernellog_thread, NULL);

+    if(read_applog_thread > 0) pthread_join(read_applog_thread, NULL);

+    if(read_cplog_thread > 0) pthread_join(read_cplog_thread, NULL);

+    if(monitor_hotplug_thread > 0) pthread_join(monitor_hotplug_thread, NULL);

+    if(read_usb_thread > 0) pthread_join(read_usb_thread, NULL);

+    if(read_wifi_thread > 0) pthread_join(read_wifi_thread, NULL);

+    if(rule_heartbeat_thread > 0) pthread_join(rule_heartbeat_thread, NULL);

+    

+    if(applog_fd >= 0) close(applog_fd);

+    if(kernellog_fd >= 0) close(kernellog_fd);

+    if(cplog_fd >= 0) close(cplog_fd);

+    

+    printf("[zcat] zte_log_agent exit.\n");

+

+    return 0;

+}

diff --git a/ap/app/zte_log_agent/log_agent_network.c b/ap/app/zte_log_agent/log_agent_network.c
new file mode 100755
index 0000000..09c35e9
--- /dev/null
+++ b/ap/app/zte_log_agent/log_agent_network.c
@@ -0,0 +1,185 @@
+/**

+ * 

+ * @file      log_agent_network.c

+ * @brief     

+ *            This file is part of ZCAT.

+ *            zcatÓ¦Óòãlog_agent´¦Àíͨ¹ýsocketµÄÊý¾ÝÁ÷

+ *            ´´½¨Ò»¸öÏ߳̽ÓÊÕpc²à·¢À´µÄ¹æÔòºÍÐÄÌø

+ *            ÀûÓÃÐéÄâÉ豸´¦ÀíỊ̈߳¬½«logÊý¾Ýͨ¹ýsocket·¢¸øpc

+ *            

+ * @details   

+ * @author    Tools Team.

+ * @email     

+ * @copyright Copyright (C) 2013 Sanechips Technology Co., Ltd.

+ * @warning   

+ * @date      2019/02/02

+ * @version   1.2

+ * @pre       

+ * @post      

+ *            

+ * @par       

+ * Change History :

+ * ---------------------------------------------------------------------------

+ * date        version  author         description

+ * ---------------------------------------------------------------------------

+ * 2017/07/17  1.0      hou.bing       Create file

+ * 2019/01/24  1.1      jiang.fenglin  1.Ìí¼Óusblog¶ÁÐ´Ëø

+ *                                     2.Ìí¼ÓÏß³ÌÃû³Æ

+ * 2019/02/02  1.2      jiang.fenglin  ÐÞ¸Ä×¢ÊÍ·½Ê½Îªdoxygen

+ * ---------------------------------------------------------------------------

+ * 

+ * 

+ */

+

+#include <signal.h>

+#include <pthread.h>

+#include <string.h>

+#include <sys/prctl.h>

+#include "log_agent.h"

+

+static int g_client_sockfd = -1;

+pthread_t  read_wifi_thread = 0;

+

+extern unsigned char g_UsbLogBuf[2048 + 1];

+extern int send_log_to_cp(unsigned char *buf, int len);

+extern int deal_with_encoded_data(unsigned char *buffer, int buf_len);

+

+static void sig_test_func(int sig)

+{

+

+}

+

+

+/**

+ * @brief ·¢Êý¾Ý¸øsocket¿Í»§¶Ë.

+ * @param[in] buf ´ý·¢Ë͵ÄÊý¾ÝÖ¸Õë

+ * @param[in] len ´ý·¢Ë͵ÄÊý¾Ý³¤¶È

+ * @return ʵ¼Ê·¢Ë͵ÄÊý¾Ý³¤¶È

+ * @note

+ * @see 

+ */

+int send_message_to_client(unsigned char* buf, int len)

+{

+    int write_len = 0;

+    

+    if(buf && len && (g_client_sockfd >= 0))

+    {

+        write_len = write(g_client_sockfd, buf, len);

+        if(write_len != len)

+        {

+            printf("[zcat] write to client error!\n");

+            return write_len;

+        }

+    }

+    return write_len;

+}

+

+/**

+ * @brief socket serverÏ̺߳¯Êý£¬\n

+ *        ½ÓÊÜpc²àsocket clientµÄ½ÓÈ룬´¦Àípc·¢À´µÄÊý¾Ý.

+ * @param[in] args Ï̺߳¯Êý²ÎÊý

+ * @return void

+ * @note

+ * @see 

+ */

+static void* read_wifi(void* args)

+{

+    int serverfd = -1, clientfd = -1;

+    socklen_t cliaddr_len = 0;

+    struct sockaddr_in server_addr, client_addr;

+    unsigned char *pbuf = g_UsbLogBuf;

+    int read_len = 0;

+    int opt = 1;

+

+    struct sigaction action;

+    action.sa_handler = sig_test_func;

+    sigemptyset(&action.sa_mask);

+    action.sa_flags = 0;

+    sigaction(SIGPIPE, &action, NULL);

+

+    prctl(PR_SET_NAME, "read_wifi");

+  

+    serverfd = socket(AF_INET, SOCK_STREAM, 0);

+    if (serverfd == -1) {

+        printf("[zcat] socket create fail!\n");

+        goto __exit;

+    }

+    

+    if(setsockopt(serverfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt))!= 0)

+    {

+        printf("[zcat] setsockopt fail!\n");

+    }

+    bzero(&server_addr, sizeof(server_addr));

+

+    memset(&server_addr, 0, sizeof(server_addr));

+    server_addr.sin_family = AF_INET;

+    server_addr.sin_port = htons(10005);

+    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);

+  

+    if (bind(serverfd, (struct sockaddr *) &server_addr, sizeof(server_addr)) == -1) {

+        printf("[zcat] socket bind fail!\n");

+        goto __exit;

+    }

+  

+    if ((listen(serverfd, 20)) == -1) {

+        printf("[zcat] socket listen fail!\n");

+        goto __exit;

+    }

+  

+

+    for (;;)

+    {

+        if(clientfd >= 0)

+        {

+            close(clientfd);

+        }

+        

+        clientfd = accept(serverfd, (struct sockaddr *) &client_addr, &cliaddr_len);

+        printf("[zcat] socket accept %s.\n", inet_ntoa(client_addr.sin_addr));

+        g_client_sockfd = clientfd;

+        

+        while(1)

+        {

+            read_len = read(g_client_sockfd, pbuf, 2048);

+            if(read_len > 0)

+            {

+                send_log_to_cp(pbuf, read_len);

+                deal_with_encoded_data(pbuf, read_len);

+            }

+            else

+            {

+                close(g_client_sockfd);

+                g_client_sockfd = -1;

+                printf("[zcat] socket client closed.\n");

+                break;

+            }

+        }

+    }

+    

+__exit:

+    if(serverfd >= 0) close(serverfd);

+

+    return NULL;

+}

+

+/**

+ * @brief ³õʼ»¯Íø¿¨Ä£Ê½£¬\n

+ *        ´´½¨¶ÁÈ¡pc²àÏûÏ¢µÄÏß³Ì.

+ * @param[in] void

+ * @return 0 on success, errno otherwise

+ * @note

+ * @see 

+ */

+int init_net_mode()

+{

+    int ret = -1;

+    

+    ret = pthread_create(&read_wifi_thread, NULL, read_wifi, NULL);

+    if(ret < 0)

+    {

+        printf("[zcat] init_network_device error!\n");

+        return ret;

+    }

+    return ret;

+}

+

diff --git a/ap/app/zte_log_agent/log_agent_sdcard.c b/ap/app/zte_log_agent/log_agent_sdcard.c
new file mode 100755
index 0000000..16245e0
--- /dev/null
+++ b/ap/app/zte_log_agent/log_agent_sdcard.c
@@ -0,0 +1,653 @@
+/**

+ * 

+ * @file      log_agent_sdcard.c

+ * @brief     

+ *            This file is part of ZCAT.

+ *            zcatÓ¦Óòãlog_agent´¦Àíͨ¹ýsd¿¨µÄÊý¾ÝÁ÷

+ *            

+ * @details   

+ * @author    Tools Team.

+ * @email     

+ * @copyright Copyright (C) 2013 Sanechips Technology Co., Ltd.

+ * @warning   

+ * @date      2019/02/02

+ * @version   1.2

+ * @pre       

+ * @post      

+ *            

+ * @par       

+ * Change History :

+ * ---------------------------------------------------------------------------

+ * date        version  author         description

+ * ---------------------------------------------------------------------------

+ * 2017/07/17  1.0      hou.bing       Create file

+ * 2019/01/24  1.1      jiang.fenglin  1.Ìí¼Óusblog¶ÁÐ´Ëø

+ *                                     2.Ìí¼ÓÏß³ÌÃû³Æ

+ * 2019/02/02  1.2      jiang.fenglin  ÐÞ¸Ä×¢ÊÍ·½Ê½Îªdoxygen

+ * 2019/07/08  1.3      jiang.fenglin  Ôö¼ÓAPFS/CPFSģʽ

+ * ---------------------------------------------------------------------------

+ * 

+ * 

+ */

+

+#include <string.h>

+#include <pthread.h>

+#include <sys/prctl.h>

+#include <sys/statfs.h>

+#include "log_agent.h"

+#include "cfg_api.h"

+

+#if 0

+#define DEFAULT_LOG_ROOT "/sdcard"

+#define DEFAULT_LOG_ROOT_PARENT "/ZTELog"

+#define CONFIG_STORAGE_FILE_PATH "/data/misc/rild/log_storage.cfg"

+#endif

+

+#define USB_DEV_SDCARD_PATH      "/dev/mmcblk0p1"

+#define USB_DEV_SDCARD_PATH_BACK "/dev/mmcblk0"

+

+#define ZCAT_SDCARD_MOUNT_PATH   "/tmp/udisk"

+

+#define ZCAT_SDCARD_RULE_PATH    "/tmp/udisk/log.rule"

+#define ZCAT_SDCARD_LOG_PATH     "/tmp/udisk/zcat_log"

+

+#define ZCAT_FS_RULE_PATH        "/var/zcat/log.rule"

+#define ZCAT_FS_PATH             "/var/zcat"

+

+

+static T_LOG_SDCARD_PARA g_log_sdcard_para = { {0} };

+pthread_t rule_heartbeat_thread = 0;

+

+extern int deal_with_encoded_data(unsigned char *buffer,int buf_len);

+

+typedef struct

+{

+    char head1[16];

+    int heartbeat_pos;

+    int heartbeat_len;

+    int rule_pos;

+    int rule_len;

+    int ap_rule_pos;

+    int ap_rule_len;

+	int log_file_size;

+	int log_file_cnt;

+}rule_struct;

+

+char g_heartbeat_buff[35] = {

+    0x01,0xaa,0xaa,0xaa,0x01,0x55,0x73,0x01,

+    0x14,0x00,0x00,0x00,0x06,0x01,0xbb,0xbb,

+    0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,

+    0x00,0x00,0x00,0x00,0x03,0x00,0x00,0x00,

+    0xe6,0x7a,0x7e

+};

+

+/* É豸¾ä±ú */

+extern BOOL bSDSet;

+extern int cplog_fd;

+

+

+/**

+ * @brief ÅжÏĿ¼ÊÇ·ñ´æÔÚ£¬Èç¹û²»´æÔÚÔò´´½¨Ò»¸öеÄĿ¼

+ * @param[in] dir_path Ŀ¼·¾¶

+ * @return 0 on success, -1 error.

+ * @note

+ * @see 

+ */

+int test_dir_exist(char* dir_path)

+{

+    DIR *p_dir = NULL;

+    

+    if ((p_dir = opendir(dir_path)) == NULL)

+    {

+        printf("[zcat] opendir failed, mkdir %s\n", dir_path);

+        if (mkdir(dir_path, 0777) != 0)

+        {

+            printf("[zcat] mkdir %s error, error info: %s\n", dir_path, strerror(errno));

+            return -1;

+        }

+    }

+    else

+    {

+        closedir(p_dir);

+        p_dir = NULL;

+    }

+    return 0;

+}

+

+/**

+ * @brief ³õʼ»¯sd¿¨´ælogµÄÅäÖòÎÊý

+ * @return void

+ * @note

+ * @see 

+ */

+static void init_sdcard_para()

+{

+    g_log_sdcard_para.max_file_size = 1024 * 1024 * 100;

+    //g_log_sdcard_para.max_file_num = 8;

+    g_log_sdcard_para.log_overwrite = 1;

+    g_log_sdcard_para.compress_log_files = 1;

+    g_log_sdcard_para.file_counts = 0;

+    g_log_sdcard_para.output_fd = -1;

+	g_log_sdcard_para.free_space_limit = 1024 * 1024 * 1;

+

+	memset(g_log_sdcard_para.rule_path, 0, sizeof(g_log_sdcard_para.rule_path));

+	strcpy(g_log_sdcard_para.rule_path, ZCAT_SDCARD_RULE_PATH);

+}

+

+/**

+ * @brief ³õʼ»¯sd¿¨normalģʽ²ÎÊý

+ * @return void

+ * @note

+ * @see 

+ */

+static int init_sdcard_flash_mode()

+{

+	memset(g_log_sdcard_para.log_dir, 0, sizeof(g_log_sdcard_para.log_dir));

+    strcpy(g_log_sdcard_para.log_dir, ZCAT_SDCARD_LOG_PATH);

+

+    if(test_dir_exist(g_log_sdcard_para.log_dir) < 0)//´´½¨ÈÕÖ¾Îļþ¼Ð

+    {

+        printf("[zcat] test %s dir exist failed. \n", g_log_sdcard_para.log_dir);

+        return -1;

+    }

+    return 0;

+}

+

+/**

+ * @brief ³õʼ»¯sd¿¨uÅÌģʽ²ÎÊý

+ * @return void

+ * @note

+ * @see 

+ */

+static int init_sdcard_u_mode()

+{

+	memset(g_log_sdcard_para.log_dir, 0, sizeof(g_log_sdcard_para.log_dir));

+    strcpy(g_log_sdcard_para.log_dir, ZCAT_SDCARD_LOG_PATH);

+    if(test_dir_exist(ZCAT_SDCARD_LOG_PATH) < 0)//ÅжÏËùÓÐÈÕ־Ŀ¼ÊÇ·ñ´æÔÚ

+    {

+        printf("[zcat] test_dir_exist failed:%s. \n", ZCAT_SDCARD_LOG_PATH);

+        return -1;

+    }

+    /*if(test_dir_exist(MODEM_LOG_PATH) < 0)//ÅжÏcpÈÕ־Ŀ¼ÊÇ·ñ´æÔÚ

+    {

+        printf("test_dir_exist failed:%s. \n", MODEM_LOG_PATH);

+        return -1;

+    }*/

+    return 0;

+}

+

+int zCat_MountSd()

+{    

+    char cmd[100] = { 0 };

+    

+    if(test_dir_exist(ZCAT_SDCARD_MOUNT_PATH) < 0) // ´´½¨¹ÒÔØµÄÁÙʱÎļþ¼Ð

+    {

+        printf("[zcat] create %s fail.\n", ZCAT_SDCARD_MOUNT_PATH);

+        return -1;

+    }

+

+    printf("[zcat] init sd output dir successs.\n");

+

+    memset(cmd, 0, sizeof(cmd));

+    sprintf(cmd, "mount -t vfat %s %s", USB_DEV_SDCARD_PATH, ZCAT_SDCARD_MOUNT_PATH); 

+    if(0 != zxic_system(cmd))

+    {

+        printf("[zcat] cmd %s fail!\n", cmd);

+

+        memset(cmd, 0, sizeof(cmd));

+        sprintf(cmd, "mount -t vfat %s %s", USB_DEV_SDCARD_PATH_BACK, ZCAT_SDCARD_MOUNT_PATH); 

+        if(0 != system(cmd))

+        {

+            printf("[zcat] cmd %s fail, mount error!\n", cmd);

+            return -1;

+        }

+    }

+    

+    return 0;

+}

+

+/**

+ * @brief ɾ³ýĿ¼ÏÂÔçÆÚ´´½¨µÄÎļþ\n

+ *        ¸ù¾ÝÎļþÃûÅжϴ´½¨Ê±¼ä£¬É¾³ý×îÏÈ´´½¨µÄÄǸöÎļþ

+ * @param[in] dir_path ÎÄĿ¼·¾¶

+ * @return void

+ * @note

+ * @see 

+ */

+static void delete_oldest_file(char* dir_path)

+{

+    DIR *p_dir = NULL;

+    struct dirent *p_entry = NULL;

+    char oldest_file[64] = "99999999999999";    //ÈÕÆÚµÄ×î´óÖµ

+    char file_name[MAX_STRING_LENGTH] = {0};

+    p_dir = opendir(dir_path);

+

+    if(p_dir)

+    {

+	    while ((p_entry = readdir(p_dir)) != NULL)

+	    {

+	        if (strncmp(p_entry->d_name, ".", 1) == 0)

+	            continue;

+

+	        if (strcmp(p_entry->d_name, oldest_file) < 0)

+	        {

+	            strncpy(oldest_file, p_entry->d_name, 64 - 1);

+	        }

+	    }

+

+	    snprintf(file_name, MAX_STRING_LENGTH, "%s/%s", dir_path, oldest_file);

+	    if(remove(file_name) != 0)

+	    {

+	        printf("[zcat] remove %s fail!errno=%d(%s)\n",file_name,errno,strerror(errno));

+	    }

+	    closedir(p_dir);

+    }

+}

+

+

+/**

+ * @brief ÔÚdir_pathĿ¼Ï´ò¿ªlogÊä³öÎļþ²¢·µ»ØÎļþ¾ä±ú,\n

+ *        ÒÔµ±Ç°Ê±¼äΪÎļþÃû£¬´´½¨logÊä³öÎļþ¡£logÎļþ×î´óÊýÁ¿ÓÉLOG_FILE_MAX_NO¾ö¶¨£¬

+ *        Èôµ±Ç°ÎļþÊýÒÑ´ïÉÏÏÞ£¬É¾³ý×îÏÈ´´½¨µÄÎļþ,ÔÙÒÔµ±Ç°Ê±¼äΪÎļþÃû´´½¨Îļþ

+ * @param[in] log_sdcard_para ÈÕÖ¾´æT¿¨²ÎÊý

+ * @return ´ò¿ªµÄlogÎļþÃèÊö·û

+ * @note

+ * @see 

+ */

+static int open_log_file(T_LOG_SDCARD_PARA* log_sdcard_para)

+{

+    int fd = -1;

+    char file_name[MAX_STRING_LENGTH] = {0};

+    struct tm *cur_time;

+    time_t now;

+

+    now = time(NULL);

+    cur_time = localtime(&now);

+

+	if(cur_time != NULL)

+		snprintf(file_name, MAX_STRING_LENGTH, "%s/%d_%02d%02d_%02d%02d%02d%s", log_sdcard_para->log_dir, cur_time->tm_year + 1900,

+             cur_time->tm_mon + 1, cur_time->tm_mday, cur_time->tm_hour, cur_time->tm_min,

+             cur_time->tm_sec, ".log");

+

+    if (log_sdcard_para->log_overwrite)

+    {

+        log_sdcard_para->file_counts++;

+

+		struct statfs diskInfo;

+		statfs(g_log_sdcard_para.log_dir, &diskInfo);

+

+		if (diskInfo.f_bfree * diskInfo.f_bsize < log_sdcard_para->free_space_limit)

+        //if (log_sdcard_para->file_counts > log_sdcard_para->max_file_num)

+        {

+            delete_oldest_file(log_sdcard_para->log_dir);

+            log_sdcard_para->file_counts--;

+        }

+    }

+

+    fd = open(file_name, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR | S_IWGRP | S_IRGRP | S_IWOTH | S_IROTH);

+

+    if (fd >= 0)

+    {

+        fchmod(fd, S_IRUSR | S_IWUSR | S_IRGRP |S_IWGRP | S_IROTH |S_IWOTH);

+    }

+    strncpy(log_sdcard_para->log_name, file_name, MAX_STRING_LENGTH-1);

+

+    return fd;

+}

+

+/**

+ * @brief ³õʼ»¯logµÄĿ¼

+ * @param[in] n/a

+ * @return 0 on success, errno otherwise

+ * @note

+ * @see 

+ */

+int init_fs_log_dir()

+{

+	struct statfs diskInfo;

+

+	(void)(diskInfo);

+	

+    g_log_sdcard_para.max_file_size = 1024 * 1024 * 10;

+    //g_log_sdcard_para.max_file_num = 5;

+    g_log_sdcard_para.log_overwrite = 1;

+    g_log_sdcard_para.compress_log_files = 1;

+    g_log_sdcard_para.file_counts = 0;

+    g_log_sdcard_para.output_fd = -1;

+	g_log_sdcard_para.free_space_limit = 1024 * 1024 * 1;

+

+	memset(g_log_sdcard_para.rule_path, 0, sizeof(g_log_sdcard_para.rule_path));

+	strcpy(g_log_sdcard_para.rule_path, ZCAT_FS_RULE_PATH);

+	

+	memset(g_log_sdcard_para.log_dir, 0, sizeof(g_log_sdcard_para.log_dir));

+    strcpy(g_log_sdcard_para.log_dir, ZCAT_FS_PATH);

+

+    if(test_dir_exist(g_log_sdcard_para.log_dir) < 0)//´´½¨ÈÕÖ¾Îļþ¼Ð

+    {

+        printf("[zcat] test %s dir exist failed. \n", g_log_sdcard_para.log_dir);

+        return -1;

+    }

+

+    g_log_sdcard_para.output_fd = open_log_file(&g_log_sdcard_para);//´ò¿ªÈÕÖ¾Îļþ

+    if (g_log_sdcard_para.output_fd == -1)

+    {

+        printf("[zcat] failed to open log file!\n");

+        return -1;

+    }

+    return 0;

+}

+

+/**

+ * @brief ³õʼ»¯sd¿¨´ælogµÄĿ¼

+ * @param[in] mode normalģʽ/uÅÌģʽ

+ * @return 0 on success, errno otherwise

+ * @note

+ * @see 

+ */

+int init_sdcard_log_dir(E_FLASH_MODE mode)

+{   

+    init_sdcard_para();

+    

+    if(mode == FLASH_MODE_U)

+    {       

+        if(init_sdcard_u_mode() < 0)

+        {

+            printf("[zcat] init_sdcard_u_mode failed!\n");

+            return -1;

+        }

+    }

+    else

+    {

+        if(init_sdcard_flash_mode() < 0)

+        {

+            printf("[zcat] init_sdcard_flash_mode failed!\n");

+            return -1;

+        }

+    }

+

+    g_log_sdcard_para.output_fd = open_log_file(&g_log_sdcard_para);//´ò¿ªÈÕÖ¾Îļþ

+    if (g_log_sdcard_para.output_fd == -1)

+    {

+        printf("[zcat] failed to open log file!\n");

+        return -1;

+    }

+    return 0;

+}

+

+/**

+ * @brief дlogµ½SD¿¨.\n

+ * @param[in] fd ÉÏÒ»´ÎдÈësd¿¨ÖеÄzlfÎļþÃèÊö·û

+ * @param[in] buf ´ýдÈëµÄÊý¾ÝÖ¸Õë

+ * @param[in] len ´ýдÈëµÄÊý¾ÝÖ¸³¤¶È

+ * @param[in] log_sdcard_para sd¿¨²ÎÊý

+ * @return ʵ¼ÊдÈëµÄ³¤¶È

+ * @note

+ * @see 

+ */

+static int output_log_to_sdcard(int fd, unsigned char *buf, int len, T_LOG_SDCARD_PARA* log_sdcard_para)

+{

+    int output_fd = fd;

+    int write_len = 0;

+

+    //static int file_size = 0;

+    log_sdcard_para->file_size += len;

+

+    // Èç¹ûÎļþ´óС´ïµ½×î´óÎļþ³ß´ç£¬Ôòн¨Ò»¸öÎļþ

+    if (log_sdcard_para->file_size > log_sdcard_para->max_file_size)

+    {

+        close(fd);

+

+        if (log_sdcard_para->compress_log_files)

+        {

+            //compress_log_files(g_log_dir);

+        }

+

+        output_fd = open_log_file(log_sdcard_para);

+        if (output_fd == -1)

+        {

+            return -1;

+        }

+        log_sdcard_para->output_fd = output_fd;

+        log_sdcard_para->file_size = len;

+    }

+

+    write_len = write(output_fd, buf, len);

+    if(write_len != len) // Èç¹ûT¿¨Ð´Âú£¬Ôòɾ³ý֮ǰµÄlogÎļþ

+    {

+        delete_oldest_file(log_sdcard_para->log_dir);

+        log_sdcard_para->file_counts--;

+        write_len = write(output_fd, buf, len);

+        if(write_len != len)

+        {

+            return -1;

+        }

+    }

+

+    return write_len;

+}

+

+/**

+ * @brief bufferÄÚÈÝдÈëµ½T¿¨

+ * @param[in] buffer ´ýдÈëÊý¾ÝÖ¸Õë

+ * @param[in] buffer_len ´ýдÈëÊý¾Ý³¤¶È

+ * @return ʵ¼ÊдÈëµÄ³¤¶È

+ * @note

+ * @see 

+ */

+int send_message_to_sdcard(unsigned char* buf, int len)

+{

+    return output_log_to_sdcard(g_log_sdcard_para.output_fd, buf, len, &g_log_sdcard_para);

+}

+

+/**

+ * @brief ·¢Ë͹æÔòÎļþµ½cp.\n

+ * @param[in] fd ¹æÔòÎļþÃèÊö·û

+ * @param[in] offset ÎļþÆ«ÒÆ

+ * @param[in] length ·¢ËÍÊý¾Ý³¤¶È

+ * @return 0 on success, -1 otherwise

+ * @note

+ * @see 

+ */

+static int send_rules_to_cp(int fd, int offset, int length)

+{

+    char buf[1024] = {0};

+    int left_len = 0;

+    int next_buf_len = 0;

+    int read_len = 0;

+    

+    if(lseek(fd, offset, SEEK_SET) == -1)

+    {

+        printf("[zcat] rules file lseek to pos %d failed (%s)\n", offset, strerror(errno));

+        return -1; 

+    }

+    

+    left_len = length;

+    next_buf_len = sizeof(buf) < left_len ? sizeof(buf) : left_len;

+    while((read_len = read(fd, buf, next_buf_len)) > 0)

+    {

+        int write_len = write(cplog_fd, buf, read_len);

+        if (write_len != read_len)

+        {

+            printf("[zcat] send_rule error, write_len = %d, len = %d.\n", write_len, read_len);

+            return -1;

+        }

+        left_len -= read_len;

+        next_buf_len = sizeof(buf) < left_len ? sizeof(buf) : left_len;

+    }

+    return 0;

+}

+

+

+/**

+ * @brief ·¢Ë͹æÔòÎļþµ½ap, app devºÍkernel dev.\n

+ * @param[in] fd ¹æÔòÎļþÃèÊö·û

+ * @param[in] offset ÎļþÆ«ÒÆ

+ * @param[in] length ·¢ËÍÊý¾Ý³¤¶È

+ * @return 0 on success, -1 otherwise

+ * @note

+ * @see 

+ */

+static int send_rules_to_ap(int fd, int offset, int length)

+{

+    unsigned char buf[1024] = {0};

+    int left_len = 0;

+    int next_buf_len = 0;

+    int read_len = 0;

+    

+    if(lseek(fd, offset, SEEK_SET) == -1)

+    {

+        printf("[zcat] rules file lseek to pos %d failed (%s)\n", offset, strerror(errno));

+        return -1; 

+    }

+    

+    left_len = length;

+    next_buf_len = sizeof(buf) < left_len ? sizeof(buf) : left_len;

+    while((read_len = read(fd, buf, next_buf_len)) > 0)

+    {

+        deal_with_encoded_data(buf, read_len);

+        next_buf_len = sizeof(buf) < left_len ? sizeof(buf) : left_len;

+    }

+    return 0;

+}

+

+/**

+ * @brief ¼ì¹æÔòÎļþºÏ·¨ÐÔ£¬¶ÁȡժҪÐÅÏ¢.\n

+ * @param[in] fd ¹æÔòÎļþÃèÊö·û

+ * @param[out] rule_info ¹æÔòÎļþ¸ÅÒªÐÅÏ¢

+ * @return ¹æÔòÎļþµÄ´óС

+ * @note

+ * @see 

+ */

+static int get_rule(int fd, rule_struct *rule_info)

+{

+    int len = 0;

+    

+    len = read(fd, rule_info, sizeof(rule_struct));

+    if(len <= 0)

+    {

+        printf("[zcat] rule file len = %d\n", len);

+        return len;

+    }

+    printf("[zcat] rule_info\n\theartbeat_pos : %d\n\theartbeat_len : %d\n\trule_pos      : %d\n\trule_len      : %d\n",

+        rule_info->heartbeat_pos,

+        rule_info->heartbeat_len,

+        rule_info->rule_pos,

+        rule_info->rule_len

+        );

+

+    if(rule_info->heartbeat_len > sizeof(g_heartbeat_buff))

+    {

+        printf("[zcat] check_rule, heartbeat voerload %d error.\n", sizeof(g_heartbeat_buff));

+        return -1;

+    }

+

+    // ¶ÁÈ¡¹æÔòÎļþÖеÄÐÄÌø°üÊý¾Ý£¬Ì滻ĬÈÏÐÄÌøÊý¾Ý

+    if(lseek(fd, rule_info->heartbeat_pos, SEEK_SET) == -1)

+    {

+        printf("[zcat] check_rule, lseek to heartbeat_pos error.\n");

+        return -1;

+    }

+    if(read(fd, g_heartbeat_buff, rule_info->heartbeat_len) <= 0)

+    {

+        printf("[zcat] check_rule, read heartbeat data error.\n");

+        return -1;

+    }

+    

+    return len;

+}

+

+/**

+ * @brief ¹æÔòºÍÐÄÌø·¢ËÍỊ̈߳¬\n

+ *        ¶ÁÈ¡sd¿¨ÖеĹæÔòÎļþ·¢Ë͸øpc£¬ÖÜÆÚÐԵķ¢ËÍÐÄÌø.

+ * @param[in] arg sd¿¨ÎļþÃèÊö·û

+ * @return void

+ * @note

+ * @see 

+ */

+static void rule_heartbeat_entry(void *arg)

+{

+    BOOL bSendRule = FALSE;

+    int rule_file_fd = 0;

+    int rule_len = 0;

+    rule_struct rule_info = { {0} };

+    char* heartbeat_buf = g_heartbeat_buff;

+    int heartbeat_len = sizeof(g_heartbeat_buff);

+

+    prctl(PR_SET_NAME, "heartbeat");

+    

+    while(TRUE)

+    {

+        int write_len = write(cplog_fd, heartbeat_buf, heartbeat_len);

+        if (write_len != heartbeat_len)

+        {

+            printf("[zcat] send heartbeat failed! %d, %d, %d\n", cplog_fd, heartbeat_len, write_len);

+        }

+        

+        sleep(2);

+        if(bSDSet == TRUE && bSendRule == FALSE)

+        {

+             rule_file_fd = open(g_log_sdcard_para.rule_path, O_RDONLY, S_IRUSR);

+             if (rule_file_fd < 0)

+             {

+                printf("[zcat] failed to open rule file %s.\n", g_log_sdcard_para.rule_path);

+                return;

+             }

+

+             // ¼ì²é¹æÔòÎļþºÏ·¨ÐÔ

+             rule_len = get_rule(rule_file_fd, &rule_info);

+             if(rule_len <= 0)

+             {

+				close(rule_file_fd);

+				return;

+             }

+             printf("[zcat] check rule success,len is %d\n", rule_len);

+

+             // ·¢ËÍcp¹æÔò

+             send_rules_to_cp(rule_file_fd, rule_info.rule_pos, rule_info.rule_len);

+             printf("[zcat] send rules to cp %d bytes,position %d\n",

+                rule_info.rule_len,

+                rule_info.rule_pos);

+             // ·¢ËÍap¹æÔò

+             send_rules_to_cp(rule_file_fd, rule_info.ap_rule_pos, rule_info.ap_rule_len);

+             printf("[zcat] send rules to cp %d bytes,position %d\n", 

+                rule_info.ap_rule_len,

+                rule_info.ap_rule_pos);

+             

+             close(rule_file_fd);

+             bSendRule = TRUE;

+        }

+    }

+}

+

+#if 0

+/**

+ * @brief »ñÈ¡sdcardģʽ

+ * @param[in] void

+ * @return sdcardģʽ

+ * @note

+ * @see 

+ */

+static E_FLASH_MODE get_flash_mode()

+{

+    E_FLASH_MODE flash_mode = FLASH_MODE_NOMAL;

+

+    return flash_mode;

+}

+#endif

+

+/**

+ * @brief ³õʼ»¯sdcardģʽ£¬´´½¨¹æÔòºÍÐÄÌø·¢ËÍÏß³Ì.

+ * @param[in] void

+ * @return 0 on success, errno otherwise

+ * @note

+ * @see 

+ */

+int init_sdcard_mode()

+{

+    //E_FLASH_MODE flash_mode = FLASH_MODE_NOMAL;

+    

+    //flash_mode = get_flash_mode();

+    pthread_create(&rule_heartbeat_thread, NULL, (void*)rule_heartbeat_entry, NULL);

+    

+    return 0;

+}

diff --git a/ap/app/zte_log_agent/log_agent_tool.c b/ap/app/zte_log_agent/log_agent_tool.c
new file mode 100644
index 0000000..a5ec0f2
--- /dev/null
+++ b/ap/app/zte_log_agent/log_agent_tool.c
@@ -0,0 +1,605 @@
+/**

+ * 

+ * @file      log_agent_tool.c

+ * @brief     

+ *            This file is part of ZCAT.

+ *            zcatÓ¦Óòãlog_agent´¦ÀíÊý¾ÝÔ´µÄ°ïÖúº¯Êý

+ *            

+ * @details   

+ * @author    Tools Team.

+ * @email     

+ * @copyright Copyright (C) 2013 Sanechips Technology Co., Ltd.

+ * @warning   

+ * @date      2019/02/02

+ * @version   1.2

+ * @pre       

+ * @post      

+ *            

+ * @par       

+ * Change History :

+ * ---------------------------------------------------------------------------

+ * date        version  author         description

+ * ---------------------------------------------------------------------------

+ * 2017/07/17  1.0      hou.bing       Create file

+ * 2019/01/24  1.1      jiang.fenglin  1.Ìí¼Óusblog¶ÁÐ´Ëø

+ *                                     2.Ìí¼ÓÏß³ÌÃû³Æ

+ * 2019/02/02  1.2      jiang.fenglin  ÐÞ¸Ä×¢ÊÍ·½Ê½Îªdoxygen

+ * 2019/07/08  1.3      jiang.fenglin  Ôö¼ÓAPFS/CPFSģʽ

+ * ---------------------------------------------------------------------------

+ * 

+ * 

+ */

+

+

+/**

+* Í·Îļþ°üº¬

+*/

+#include <string.h>

+#include <signal.h>

+#include <time.h>

+#include <pthread.h>

+#include <sys/time.h>

+#include <sys/ioctl.h>

+#include "log_agent.h"

+

+#define MAX_PACKET_LEN            (0x10000)

+#define MAX_ENCODE_PACKET_LEN     (MAX_PACKET_LEN * 2)

+#define COMM_MDLNO_ZCAT_FLAG      115

+#define COMM_MDLNO_RAMDUMP_FLAG   119

+#define MAX_AP_LOG_BUFF_LEN       2048

+

+extern E_ZCAT_MODE g_log_dir;

+extern E_ZCAT_STATE g_log_state;

+

+extern int send_message_to_client(unsigned char* buf, int len);

+extern int send_message_to_usblog(unsigned char* buf, int len);

+extern int send_message_to_sdcard(unsigned char* buf, int len);

+extern int init_sdcard_log_dir(E_FLASH_MODE mode);

+extern int init_fs_log_dir();

+extern int zCat_MountSd();

+extern BOOL hdlc_encode(T_HDLC_BUFFER_TYPE *dest, const T_HDLC_BUFFER_TYPE *src);

+extern BOOL hdlc_decode(T_HDLC_BUFFER_TYPE *dest, T_HDLC_BUFFER_TYPE *src);

+

+

+int deal_with_encoded_data(unsigned char* buffer, int buf_len);

+

+int hb_flag = 0;

+int bFirst = 1;

+/*É豸¾ä±ú*/

+extern int ramdump_fd;

+extern int kernellog_fd;

+extern int applog_fd;

+extern int cplog_fd;

+

+/*Ï̻߳¥³âËø*/

+static pthread_mutex_t  mutex_AP;

+static pthread_mutex_t  mutex_SD;

+

+static T_HDLC_BUFFER_TYPE  g_recvBuf = {0}; 

+

+static unsigned int gCommEncodeBuffer[MAX_ENCODE_PACKET_LEN / 4] = {0};

+static unsigned int gCommDecodeBuffer[MAX_ENCODE_PACKET_LEN / 4] = {0};

+static unsigned int gCommRecvBuffer[MAX_ENCODE_PACKET_LEN / 4] = {0};

+

+BOOL bSDSet = FALSE;

+

+void init_log_agent_tools()

+{

+    g_recvBuf.buf = (unsigned char *)gCommRecvBuffer;

+    g_recvBuf.bufIndex = 0;

+    g_recvBuf.bufSize  = 0;

+    pthread_mutex_init(&mutex_AP, NULL);

+    pthread_mutex_init(&mutex_SD, NULL);

+}

+

+int g_cp_log_count = 0;

+int g_ap_log_count = 0;

+

+/**

+ * @brief ´òӡʱ¼äµÄ°ïÖúº¯Êý

+ * @param[in] void

+ * @return void

+ * @note

+ * @see 

+ */

+char* zte_time()

+{

+    time_t timep;

+    struct tm *p;

+    static char buf[22];

+    memset(buf, 0, 22);

+    time(&timep);

+    p =localtime(&timep);

+	if(p != NULL)

+		snprintf(buf,21,"%4d/%02d/%02d %02d:%02d:%02d ",1900 + p->tm_year,1 + p->tm_mon,p->tm_mday,p->tm_hour,p->tm_min,p->tm_sec);

+    return buf;

+}

+

+/**

+ * @brief ½«¹æÔòÎļþ¡¢ÐÄÌø°üµÄÏÂÐÐÊý¾Ý·¢Ë͵½cp

+ * @param[in] buf ´ý·¢Ë͵ÄÊý¾ÝÖ¸Õë

+ * @param[in] len ´ý·¢Ë͵ÄÊý¾Ý³¤¶È

+ * @return ʵ¼Ê·¢Ë͵ÄÊý¾Ý³¤¶È

+ * @note

+ * @see 

+ */

+int send_log_to_cp(unsigned char *buf, int len)

+{

+    int write_len = 0;  

+    if(buf == NULL || cplog_fd == -1)

+    {

+        printf("[zcat] send_log_to_cp fail\n");

+        return 0;

+    }

+    write_len = write(cplog_fd, buf, len);

+

+    return write_len;

+}

+

+/**

+ * @brief ¸ù¾Ýzcat_mode£¬·¢ËÍlogµ½²»Í¬µÄÍâÉ裺usb¡¢Íø¿¨¡¢sd¿¨

+ * @param[in] buf ´ý·¢Ë͵ÄÊý¾ÝÖ¸Õë

+ * @param[in] len ´ý·¢Ë͵ÄÊý¾Ý³¤¶È

+ * @return void

+ * @note

+ * @see 

+ */

+void send_log_out(unsigned char* buf, int len)

+{

+    if(g_log_state != ZCAT_STATE_RUNNING)

+    {

+        printf("[zcat] send_log_out fail, state = %d.\n", g_log_state);

+        return;

+    }

+    

+    if(g_log_dir == ZCAT_MODE_AP_NET)

+    {

+        send_message_to_client(buf, len);

+    }

+    else if(g_log_dir == ZCAT_MODE_AP_USB)

+    {

+        int i;

+        int cnt = len / MAX_AP_LOG_BUFF_LEN;

+        

+        for(i = 0; i < cnt; i++)

+        {

+            g_cp_log_count++;

+            send_message_to_usblog(buf + i * MAX_AP_LOG_BUFF_LEN, MAX_AP_LOG_BUFF_LEN);

+        }

+                    

+        cnt = len % MAX_AP_LOG_BUFF_LEN;

+        if(cnt > 0)

+        {

+            g_cp_log_count++;

+            send_message_to_usblog(buf + i * MAX_AP_LOG_BUFF_LEN, cnt);

+        }

+    }

+    else if(g_log_dir == ZCAT_MODE_AP_TF)

+    {

+        if(bSDSet == FALSE )

+        {

+            if(zCat_MountSd())

+                return;

+            

+            bSDSet = TRUE;

+            if(init_sdcard_log_dir(FLASH_MODE_NOMAL) < 0) //³õʼ»¯cpÊä³öÎļþ¼Ð¼°²ÎÊý

+            {

+                bSDSet = FALSE;

+                return;

+            }

+            hb_flag = 1;

+            return;

+        }

+        if(bSDSet == TRUE)

+        {

+            pthread_mutex_lock(&mutex_SD); 

+            send_message_to_sdcard(buf, len);

+            pthread_mutex_unlock(&mutex_SD); 

+        }

+    }

+	else if(g_log_dir == ZCAT_MODE_AP_FS)

+	{

+		if(bSDSet == FALSE )

+        {

+            bSDSet = TRUE;

+            if(init_fs_log_dir() < 0) //³õʼ»¯cpÊä³öÎļþ¼Ð¼°²ÎÊý

+            {

+                bSDSet = FALSE;

+                return;

+            }

+            hb_flag = 1;

+            return;

+        }

+        if(bSDSet == TRUE)

+        {

+            pthread_mutex_lock(&mutex_SD); 

+            send_message_to_sdcard(buf, len);

+            pthread_mutex_unlock(&mutex_SD); 

+        }

+	}

+    else

+    {

+        deal_with_encoded_data(buf, len);

+    }

+}

+

+/**

+ * @brief ½«ap²àprintf¡¢printk²úÉúµÄlogÊý¾Ý·¢ËͳöÈ¥

+ * @param[in] commHeader ´ý·¢Ë͵ÄÊý¾Ý

+ * @return void

+ * @note

+ * @see 

+ */

+static void send_ap_log_out(T_COMM_TYPE *commHeader)

+{

+    T_HDLC_BUFFER_TYPE srcBuf  = {0};

+    //T_ZCAT_HEADER *zcatHeader = (T_ZCAT_HEADER *)(((unsigned char*)commHeader) + sizeof(T_COMM_TYPE));

+    T_HDLC_BUFFER_TYPE destBuf = {(unsigned char *)gCommEncodeBuffer, 0, MAX_ENCODE_PACKET_LEN};

+    //int cmd_code = zcatHeader->cmd_code;

+

+    //UINT16 times = 0;

+    //UINT16 ipLast = 0;

+

+    srcBuf.buf       = (unsigned char *)(commHeader);

+    srcBuf.bufIndex  = 0;

+    srcBuf.bufSize   = sizeof(T_COMM_TYPE) + commHeader->buf_len;

+    destBuf.bufIndex = 0;

+    if(g_log_state != ZCAT_STATE_RUNNING)

+    {

+         free((void*)commHeader);

+         return;

+    }

+    pthread_mutex_lock(&mutex_AP);   // ¼Ó»¥³âËø£¬·Àֹͬʱ²Ù×÷gCommEncodeBuffer

+    if (hdlc_encode(&destBuf, &srcBuf)) // ±àÂë

+    {

+        if(g_log_dir == ZCAT_MODE_CP_USB || g_log_dir == ZCAT_MODE_CP_TF || g_log_dir == ZCAT_MODE_CP_FS)

+        {

+            send_log_to_cp(destBuf.buf, destBuf.bufIndex);

+        }

+        else

+        {

+            send_log_out(destBuf.buf, destBuf.bufIndex);

+        }   

+    }

+    pthread_mutex_unlock(&mutex_AP); // ½â³ý»¥³âËø

+    free((void*)commHeader);

+}

+

+/**

+ * @brief ·¢ËÍÊý¾Ýµ½"ͳһ»º´æ"ÖÐ

+ * @param[in] buf           ·¢ËÍÊý¾Ý(±ØÐëÊÇÓÉComm_MallocÉêÇëµÄÄÚ´æ!!!)

+ * @param[in] buf_len       ·¢ËÍÊý¾ÝµÄ³¤¶È

+ * @param[in] tgt_mdl_no    Ä¿±êÄ£¿éºÅ£¬ÊÖ»ú»òPCµÈ

+ * @param[in] tgt_submdl_no Ä¿±ê×ÓÄ£¿éºÅ

+ * @param[in] src_submdl_no Ô´×ÓÄ£¿éºÅ

+ * @return ³É¹¦·µ»ØZOSS_SUCCESS, ·ñÔò·µ»ØZOSS_ERROR

+ * @note

+ * @see 

+ */

+unsigned int zTools_SendData(unsigned char *buf, unsigned int buf_len,

+                       unsigned char tgt_mdl_no, unsigned char tgt_submdl_no, unsigned char src_submdl_no)

+{

+    T_COMM_TYPE *commHeader = NULL;

+

+    /* Èë²ÎÅÐ¶Ï */

+    if (buf == NULL || buf_len == 0 || tgt_mdl_no == 0 || tgt_submdl_no == 0 || src_submdl_no == 0)

+    {

+        return -1;

+    }

+

+    commHeader = (T_COMM_TYPE *)(buf - sizeof(T_COMM_TYPE));

+

+    commHeader->msg_type      = 1;

+    commHeader->pad           = 0xAA;

+    commHeader->reserved      = 0xAAAA;

+    commHeader->tgt_mdl_no    = tgt_mdl_no;      // Ä¿±êÄ£¿é

+    commHeader->tgt_submdl_no = tgt_submdl_no;   // Ä¿±ê×ÓÄ£¿é

+    commHeader->src_mdl_no    = MDL_PHONE;       // Ô´Ä£¿é

+    commHeader->src_submdl_no = src_submdl_no;   // Ô´×ÓÄ£¿é

+    commHeader->buf_len       = buf_len;         // Êý¾ÝÇø³¤¶È

+

+    send_ap_log_out(commHeader);

+    return 0;

+}

+

+/**

+ * @brief ZCATÏûϢͷ³õʼ»¯

+ * @param[out] zcatHeader ÏûϢͷָÕë

+ * @param[in] cmd_code ÏûÏ¢Âë

+ * @param[in] len ÏûÏ¢³¤¶È

+ * @return N/A

+ * @note

+ * @see 

+ */

+VOID zCatAgt_HeaderInit(T_ZCAT_HEADER *zcatHeader, unsigned char cmd_code, unsigned int len)

+{

+    struct timeval tmpTimeVal = {0};

+

+    zcatHeader->cmd_code    = cmd_code;

+    zcatHeader->reserved    = 0xBBBB;

+    zcatHeader->timeStamp[1] = 0;

+    zcatHeader->length      = len;

+    zcatHeader->timeStamp[0] = 0;//corem»ñȡʱ¼ä

+    gettimeofday(&tmpTimeVal, NULL);

+    zcatHeader->timeStamp[1] = tmpTimeVal.tv_sec;

+}

+

+/**

+ * @brief ·¢ËÍZCATÏûÏ¢µ½"ÍâÉè"

+ * @param[in] cmd_code ÏûÏ¢Âë

+ * @param[in] buf ÏûÏ¢Êý¾ÝÖ¸Õë

+ * @param[in] len ÏûÏ¢Êý¾Ý³¤¶È

+ * @return ³É¹¦·µ»ØZOSS_SUCCESS, ·ñÔò·µ»ØZOSS_ERROR

+ * @note

+ * @see 

+ */

+unsigned int zCatAgt_SendMsg(unsigned char cmd_code, unsigned char *buf, unsigned int len)

+{

+    T_ZCAT_HEADER *zcatHeader = (T_ZCAT_HEADER *)(buf - sizeof(T_ZCAT_HEADER));

+

+    zCatAgt_HeaderInit(zcatHeader, cmd_code, len);

+    

+    return zTools_SendData((unsigned char *)zcatHeader, sizeof(T_ZCAT_HEADER) + len, MDL_ZCAT, 1, SUBMDL_ZCATAGT);

+}

+

+/**

+ * @brief »ñȡģ¿éºÍµÈ¼¶

+ * @param[in] buf ÏûÏ¢Êý¾ÝÖ¸Õë

+ * @param[in] bufLen ÏûÏ¢Êý¾Ý³¤¶È

+ * @param[in] priority ÏûÏ¢µÈ¼¶

+ * @param[in] mod Ä£¿é±àºÅ

+ * @return void

+ * @note

+ * @see 

+ */

+VOID zCatAgt_Ap_GetModAndPri(unsigned char **buf, unsigned short *bufLen, unsigned char *pPriority, unsigned char *pMod)

+{

+    unsigned char *p = *buf;

+    unsigned short len = *bufLen;

+

+    if (len > 3 && p[0] == '<' && p[1] >= '0' && p[1] <= '7' && p[2] == '>')

+    {

+        *pPriority = p[1] - '0';

+        p += 3;

+        len -= 3;

+

+        if (len > 3 && p[0] == '<' && p[1] > '0' && p[1] <= '9')

+        {

+            if (p[2] == '>')

+            {

+                *pMod = p[1] - '0';

+                p += 3;

+                len -= 3;

+            }

+            else if (len > 4 && p[2] >= '0' && p[2] <= '9')

+            {

+                if (p[3] == '>')

+                {

+                    *pMod = (p[1] - '0') * 10 + (p[2] - '0');

+                    p += 4;

+                    len -= 4;

+                }

+                else if (len > 5 && p[3] >= '0' && p[3] <= '9' && p[4] == '>')

+                {

+                    *pMod = (p[1] - '0') * 100 + (p[2] - '0') * 10 + (p[3] - '0');

+                    p += 5;

+                    len -= 5;

+                }

+            }

+        }

+    }

+

+    *buf = p;

+    *bufLen = len;

+}

+

+/**

+ * @brief ·¢ËÍAP LOGµ½"ͳһ»º´æ"ÖÐ

+ * @param[in] cmd_code ÏûÏ¢Âë

+ * @param[in] priority ÏûÏ¢µÈ¼¶

+ * @param[in] mod Ä£¿é±àºÅ

+ * @param[in] buf ÏûÏ¢Êý¾ÝÖ¸Õë

+ * @param[in] len ÏûÏ¢Êý¾Ý³¤¶È

+ * @return ³É¹¦·µ»ØZOSS_SUCCESS, ·ñÔò·µ»ØZOSS_ERROR

+ * @note

+ * @see 

+ */

+unsigned int zCatAgt_Ap_SendMsg(unsigned char cmd_code, unsigned char priority, unsigned char mod, unsigned char *buf, unsigned int len)

+{

+    T_ZCAT_APLOG_HEADER *apHeader = NULL;

+    unsigned char *newBuffer = malloc(sizeof(T_ZCAT_APLOG_HEADER) + sizeof(T_ZCAT_HEADER) + sizeof(T_COMM_TYPE) + len);

+

+    if(newBuffer == NULL)

+    {

+        printf("[zcat] malloc buffer failed!\n");

+        return -1;

+    }   

+    apHeader = (T_ZCAT_APLOG_HEADER *)(newBuffer + sizeof(T_ZCAT_HEADER) + sizeof(T_COMM_TYPE));

+	#if 0

+    if (apHeader == NULL)

+    {

+        printf("[zcat] apHeader is null.\n");

+        return -1;

+    }

+    else

+	#endif

+    {   

+        apHeader->priority = priority;

+        apHeader->mod = mod;

+        apHeader->len = len;

+        memcpy(apHeader + 1, buf, len);

+        return zCatAgt_SendMsg(cmd_code, (unsigned char *)apHeader, sizeof(T_ZCAT_APLOG_HEADER) + len);

+    }   

+    

+}

+

+/**

+ * @brief ·ÖÎöAP LOG£¬°´»»ÐÐÖØÐ·ָî

+ * @param[in] src Ô´

+ * @param[in] dst Ä¿µÄ

+ * @return Èç¹û³É¹¦·µ»ØTRUE, ·ñÔò·µ»ØFALSE

+ * @note

+ * @see 

+ */

+BOOL zCatAgt_Ap_ReadBuffer(T_AP_SRC_BUFFER_TYPE *src, T_AP_DEST_BUFFER_TYPE *dest)

+{

+    if (src != NULL && src->buf != NULL && src->bufSize > src->beginIndex && dest != NULL )

+    {

+        unsigned char *src_buf  = src->buf + src->beginIndex;

+        unsigned int src_length = src->bufSize - src->beginIndex;

+        unsigned int buf_length = src_length > AP_LOG_MAX_LENGTH ? AP_LOG_MAX_LENGTH : src_length;

+        unsigned int i = 0;

+

+        for (; i < buf_length; i++)

+        {

+            if (src_buf[i] == '\n')

+            {

+                i++;

+                dest->newLine = 1;

+                break;

+            }

+        }

+

+        dest->buf = src->buf + src->beginIndex;

+        dest->len = i;

+        src->beginIndex += i;

+

+        return TRUE;

+    }

+

+    return FALSE;

+}

+

+void timer(int sig)

+{   

+    hb_flag = 0;

+    

+    return;

+}

+

+/**

+ * @brief ´¦Àíδ±àÂëµÄÊý¾Ý£¬¸ù¾ÝÀàÐÍ·Ö±ð½øÐÐÏàÓ¦´¦Àí

+ * @param[in] buffer »º´æÖ¸Õë

+ * @param[in] buf_len »º´æ³¤¶È

+ * @return ³É¹¦·µ»Ø0£»Ê§°Ü·µ»Ø-1

+ * @note

+ * @see 

+ */

+void deal_with_rawdata(unsigned char* buf, unsigned short buf_len)

+{

+    T_COMM_TYPE commHeader = {0};

+    

+    if(buf_len > sizeof(T_COMM_TYPE))

+    {

+        memcpy(&commHeader, buf, sizeof(T_COMM_TYPE));

+        if(commHeader.src_mdl_no == COMM_MDLNO_ZCAT_FLAG)  //aplogÏûÏ¢£¬È¥³ýcomÍ·zcatÍ·diagÍ·

+        {

+            T_ZCAT_HEADER  *zcatHeader = (T_ZCAT_HEADER*)(buf+sizeof(T_COMM_TYPE));

+            if(zcatHeader->cmd_code >= ZCAT_CMDCODE_MAX)

+            {

+                printf("[zcat] zcatHeader->cmd_code:%d > ZCAT_CMDCODE_MAX\n", zcatHeader->cmd_code);

+                return;

+            }                   

+            else if(zcatHeader->cmd_code == ZCAT_DIAG_REPORT)

+            {

+                hb_flag = 1;

+                if(bFirst)

+                {

+                    signal(SIGALRM, timer);

+                    bFirst = 0;

+                }

+                alarm(5);

+                

+                T_ZCAT_DIAG_HEADER *zdiagHeader = (T_ZCAT_DIAG_HEADER*)(buf + sizeof(T_COMM_TYPE)+sizeof(T_ZCAT_HEADER));

+                if (zdiagHeader->diag_id == DIAG_FILTER_CONFIG)

+                {

+                    T_ZCAT_DIAG_CONFIG_REQ *diag_config = (T_ZCAT_DIAG_CONFIG_REQ *)(zdiagHeader + 1);

+                    int headerLen = sizeof(T_COMM_TYPE)+sizeof(T_ZCAT_HEADER)+sizeof(T_ZCAT_DIAG_HEADER);                           

+                    if(diag_config->type == ZCAT_AP_APP_TYPE)

+                    {                                       

+                         ioctl(applog_fd, 5, buf + headerLen);

+                    }

+                    else if(diag_config->type == ZCAT_AP_KERNEL_TYPE)

+                    {                                               

+                         ioctl(kernellog_fd, 5, buf + headerLen);

+                    }

+                }

+            }

+        }

+    }

+}

+

+/**

+ * @brief ´¦Àí±àÂëºóµÄÊý¾Ý£¬¸ù¾ÝÀàÐÍ·Ö±ð½øÐÐÏàÓ¦´¦Àí

+ * @param[in] buffer »º´æÖ¸Õë

+ * @param[in] buf_len »º´æ³¤¶È

+ * @return ³É¹¦·µ»Ø0£»Ê§°Ü·µ»Ø-1

+ * @note

+ * @see 

+ */

+int deal_with_encoded_data(unsigned char* buffer, int buf_len)

+{    

+    static T_HDLC_BUFFER_TYPE dest = {(unsigned char *)gCommDecodeBuffer, 0, MAX_ENCODE_PACKET_LEN};

+    T_HDLC_BUFFER_TYPE *src =  &g_recvBuf;

+    unsigned int remainLen = 0;

+    BOOL ret_decode = FALSE;

+    

+    if(buffer == NULL)

+    {

+        printf("[zcat] deal_with_encoded_data input error!\n");

+        return -1;

+    }

+

+    src->bufIndex=0;

+

+      // ½«ÐÂÏûÏ¢Êý¾Ý¿½È뻺³åÇø

+    if (src->bufSize + buf_len <= MAX_ENCODE_PACKET_LEN)

+    {

+        memcpy(src->buf + src->bufSize, buffer, buf_len);

+        src->bufSize += buf_len;

+    }

+    else if (buf_len <= MAX_ENCODE_PACKET_LEN)

+    {

+        memcpy(src->buf, buffer, buf_len);

+        src->bufSize = buf_len;

+    }

+    else

+    {

+        src->bufSize = 0;

+    }

+

+    remainLen = src->bufSize - src->bufIndex;

+

+    while (remainLen > 0)

+    {

+        ret_decode = hdlc_decode(&dest, src);

+        if(!ret_decode)

+        {

+            if (dest.bufIndex != 0 || src->bufSize - src->bufIndex == remainLen)

+            {

+                break;

+            }

+        }

+        else

+        {

+            deal_with_rawdata(dest.buf, dest.bufIndex);

+            dest.bufIndex = 0;

+        }               

+        remainLen = src->bufSize - src->bufIndex;

+    }//end while

+    if (dest.bufSize <= dest.bufIndex)

+    {

+        dest.bufIndex = 0;

+    }

+    if (src->bufSize > src->bufIndex)

+    {

+        src->bufSize -= src->bufIndex;

+        memmove(src->buf, src->buf + src->bufIndex, src->bufSize);

+    }

+    else

+    {

+        src->bufSize = 0;

+    }

+    src->bufIndex = 0;

+    return 0;

+}

diff --git a/ap/app/zte_log_agent/log_agent_usb.c b/ap/app/zte_log_agent/log_agent_usb.c
new file mode 100644
index 0000000..b88eb08
--- /dev/null
+++ b/ap/app/zte_log_agent/log_agent_usb.c
@@ -0,0 +1,33 @@
+/**

+ * 

+ * @file      log_agent_usb.c

+ * @brief     

+ *            This file is part of ZCAT.

+ *            zcatÓ¦Óòãlog_agent´¦Àíͨ¹ýusbµÄÊý¾ÝÁ÷

+ *            

+ * @details   

+ * @author    Tools Team.

+ * @email     

+ * @copyright Copyright (C) 2013 Sanechips Technology Co., Ltd.

+ * @warning   

+ * @date      2019/02/02

+ * @version   1.1

+ * @pre       

+ * @post      

+ *            

+ * @par       

+ * Change History :

+ * ---------------------------------------------------------------------------

+ * date        version  author         description

+ * ---------------------------------------------------------------------------

+ * 2017/07/17  1.0      hou.bing       Create file

+ * 2019/02/02  1.1      jiang.fenglin  ÐÞ¸Ä×¢ÊÍ·½Ê½Îªdoxygen

+ * 2019/02/12  1.2      jiang.fenglin  empty log_agent_usb.c

+ * ---------------------------------------------------------------------------

+ * 

+ * 

+ */

+

+/* This file is empty. */

+

+

diff --git a/ap/app/zte_log_agent/log_agent_usblog.c b/ap/app/zte_log_agent/log_agent_usblog.c
new file mode 100644
index 0000000..ee491be
--- /dev/null
+++ b/ap/app/zte_log_agent/log_agent_usblog.c
@@ -0,0 +1,382 @@
+/**

+ * 

+ * @file      log_agent_usblog.c

+ * @brief     

+ *            This file is part of ZCAT.

+ *            zcatÓ¦Óòãlog_agent´¦Àíͨ¹ýusbµÄÊý¾ÝÁ÷

+ *            

+ * @details   

+ * @author    Tools Team.

+ * @email     

+ * @copyright Copyright (C) 2013 Sanechips Technology Co., Ltd.

+ * @warning   

+ * @date      2019/02/22

+ * @version   1.4

+ * @pre       

+ * @post      

+ *            

+ * @par       

+ * Change History :

+ * ---------------------------------------------------------------------------

+ * date        version  author         description

+ * ---------------------------------------------------------------------------

+ * 2017/07/17  1.0      hou.bing       Create file

+ * 2019/01/24  1.1      jiang.fenglin  1.Ìí¼Óusblog¶ÁÐ´Ëø

+ *                                     2.Ìí¼ÓÏß³ÌÃû³Æ

+ * 2019/01/25  1.2      jiang.fenglin  Ôö¼ÓAPUSBģʽÏÂtty·¾¶ÅäÖù¦ÄÜ

+ * 2019/02/02  1.3      jiang.fenglin  ÐÞ¸Ä×¢ÊÍ·½Ê½Îªdoxygen

+ * 2019/02/22  1.4      jiang.fenglin  ¶¯Ì¬¿ÉÅäÖÃLOG¶Ë¿Ú,log¶Ë¿Ú¶¯Ì¬ÅäÖÃÖ»Õë¶ÔusbÅäÖÃΪÕý³£Ä£Ê½µÄÇé¿ö£¬¹¤³§Ä£Ê½±£³Ö²»±ä

+ * ---------------------------------------------------------------------------

+ * 

+ * 

+ */

+

+#include <unistd.h>

+#include <pthread.h>

+#include <stdio.h>

+#include <string.h>

+#include <sys/prctl.h>

+#include "cfg_api.h"

+#include "log_agent.h"

+#include "port_com.h"

+

+

+#define ZCAT_FACTORY_PATH "/sys/devices/virtual/android_usb/android0/f_acm/instances"

+#define ZCAT_DEFAULT_TTY  "ttyGS2"

+char g_zcat_usblog[8] = { 't', 't', 'y', 'G', 'S', '2' };

+

+int usblog_fd = -1;

+pthread_t read_usb_thread = 0;

+unsigned char g_UsbLogBuf[2048 + 1] = { 0 };

+const struct timespec notimer_interval = {0, 300000}; // 20ms

+pthread_rwlock_t usblog_rwlock = PTHREAD_RWLOCK_INITIALIZER;

+

+extern int send_log_to_cp(unsigned char *buf, int len);

+extern int deal_with_encoded_data(unsigned char *buffer, int buf_len);

+extern int init_monitor_hotplug();

+extern int hb_flag;

+

+/**

+ * @brief ·¢ËÍÊý¾Ýµ½usbµÄlog¿Ú

+ * @param[in] buf ´ý·¢Ë͵ÄÊý¾Ý»º´æÖ¸Õë

+ * @param[in] len ´ý·¢Ë͵ÄÊý¾Ý³¤¶È

+ * @return void

+ * @note

+ * @see 

+ */

+int send_message_to_usblog(unsigned char* buf, int len)

+{

+    int write_len = 0;  

+    int i = 0;

+    int ret = -1;

+

+    if ( buf && len )

+    {

+        for(i = 0; i < 100; i++)

+        {

+            pthread_rwlock_rdlock(&usblog_rwlock);

+            if ( usblog_fd >= 0 )

+            {

+                write_len = write(usblog_fd, buf, len);

+            }

+            pthread_rwlock_unlock(&usblog_rwlock);

+

+            //printf("send_message_to_usblog %8d,%8d\n", len, write_len);

+

+            if ( write_len == len )

+            {

+                ret = 0;

+                break;

+            }

+            else if( write_len )

+            {

+                len -= write_len;

+            }

+            else

+            {

+                nanosleep(&notimer_interval, NULL);

+            }

+        }

+    }

+    

+    return ret;

+}

+

+/**

+ * @brief ÐÄÌø°üºÍ¹æÔòÎļþ´¦ÀíÏ̺߳¯Êý£¬\n

+ *        ½ÓÊÕpc´«Ë͵½ueµÄÊý¾Ý£¬×ª·¢¸ø¹æÔò´¦ÀíºÍÐÄÌø¼à²â

+ * @param[in] args Ï̺߳¯Êý²ÎÊý

+ * @return void

+ * @note

+ * @see 

+ */

+static void *read_usblog(void *args)

+{

+    unsigned char *pbuf = NULL;

+    int read_len = 0;

+    

+    pbuf = g_UsbLogBuf;

+	/*

+    if(pbuf == NULL)

+    {

+        printf("[zcat] read_usblog fail.\n");

+        return NULL;

+    }*/

+

+    prctl(PR_SET_NAME, "read_usblog");

+    

+    while(1)

+    {

+        pthread_rwlock_rdlock(&usblog_rwlock);

+        if( usblog_fd >= 0)

+        {

+            read_len = read(usblog_fd, pbuf, 2*1024);

+        }

+        pthread_rwlock_unlock(&usblog_rwlock);

+

+        if(read_len > 0)

+        {

+            //printf("[zcat] read_usblog %d bytes\n",read_len);

+            send_log_to_cp(pbuf, read_len); // Ïòcp·¢Ë͹æÔò

+            deal_with_encoded_data(pbuf, read_len); // Ïòap·¢Ë͹æÔò

+        }

+

+        if( usblog_fd < 0 || read_len <= 0 )

+        {

+            //printf("[zcat] read_usblog sleep 2\n");

+            sleep(2);

+        }

+    }

+

+    return NULL;

+}

+

+

+/**

+ * @brief »ñÈ¡Îļþ´óС

+ * @param[in] fp ÊäÈëÎļþÖ¸Õë

+ * @return Îļþ´óС£¬µ¥Î»×Ö½Ú

+ * @note

+ * @see 

+ */

+int filelength(FILE *fp)

+{

+    int num;

+    fseek(fp, 0, SEEK_END);

+    num = ftell(fp);

+    fseek(fp, 0, SEEK_SET);

+    return num;

+}

+

+/**

+ * @brief ¶ÁÈ¡ÎļþÄÚÈÝ

+ * @param[in] path ÊäÈëÎļþ·¾¶

+ * @param[out] buf »º´æÖ¸Õë

+ * @param[in] len »º´æµÄ¿Õ¼ä´óС

+ * @return Îļþʵ¼Ê´óС£¬µ¥Î»×Ö½Ú

+ * @note

+ * @see 

+ */

+static int readfile(char *path, char* buf, unsigned len)

+{

+    FILE *fp;

+    int length;

+    if((fp = fopen(path, "r")) == NULL)

+    {

+        printf("[zcat] open file %s error.\n", path);

+        return -1;

+    }

+    length = filelength(fp);

+    length = length > len ? len : length;

+    //ch=(char *)malloc(length+1);

+    fread(buf, (unsigned int)length, 1, fp);

+    fclose(fp);

+    *(buf + length) = '\0';

+    return length;

+}

+

+/**

+ * @brief ÅжÏÊÇ·ñΪ¹¤³§Ä£Ê½

+ * @param[in] void

+ * @return 1 - ¹¤³§Ä£Ê½£¬0 - Õý³£Ä£Ê½

+ * @note

+ * @see 

+ */

+static int is_factory_mode()

+{

+    char buf[2] = { 0 };

+    int itemp;

+    

+    readfile(ZCAT_FACTORY_PATH, buf, 1);

+

+    itemp = atoi(buf);

+    printf("[zcat] ZCAT_FACTORY_PATH : %d\n", itemp);

+

+    if(itemp == 2)

+        return 1;

+    else

+        return 0;

+}

+

+#if 0

+/**

+ * @brief дÎļþÄÚÈÝ

+ * @param[in] path ÊäÈëÎļþ·¾¶

+ * @param[in] buf »º´æÖ¸Õë

+ * @param[in] len »º´æµÄ¿Õ¼ä´óС

+ * @return ʵ¼ÊдÈëµÄ³¤¶È£¬µ¥Î»×Ö½Ú

+ * @note

+ * @see 

+ */

+static int writefile(char*path, char*buf, unsigned len)

+{

+    FILE *fp;

+    int rtv;

+    

+    if((fp = fopen(path, "w")) == NULL)

+    {

+        printf("[zcat] open file %s error.\n", path);

+        return -1;

+    }

+    rtv = fwrite(buf, len, 1, fp);

+    fclose(fp);

+    return rtv;

+}

+#endif

+

+/**

+ * @brief »ñÈ¡usblogµÄtty·¾¶

+ * @param[in] void

+ * @return void

+ * @note

+ * @see 

+ */

+void get_usblog_tty_path()

+{

+    int isFactory = is_factory_mode();

+    

+    memset(g_zcat_usblog, 0, sizeof(g_zcat_usblog));

+    

+    if(isFactory)

+    {

+        sprintf(g_zcat_usblog, ZCAT_DEFAULT_TTY);

+        g_zcat_usblog[5] = '1'; // ¹¤³§Ä£Ê½ÏÂlog¿Ú¹Ì¶¨ÎªttyGS1£¬°´ÐèÇó²»Ö¸¶¨

+    }

+    else

+    {

+        // Èç¹ûÉèÖÃÁËtty·¾¶£¬ÔòʹÓÃÉèÖõÄ·¾¶£¬·ñÔòʹÓÃĬÈϵÄ

+        cfg_get_item("zcat_usblog", g_zcat_usblog, sizeof(g_zcat_usblog) - 1);

+        if (strlen(g_zcat_usblog) < 3)

+        {

+            sprintf(g_zcat_usblog, ZCAT_DEFAULT_TTY);

+        }

+    }

+}

+

+/**

+ * @brief ¹Ø±ÕusbÉ豸

+ * @param[in] void

+ * @return 0 on success, errno otherwise

+ * @note

+ * @see 

+ */

+int close_usblog()

+{

+    int ret = -1;

+

+    pthread_rwlock_wrlock(&usblog_rwlock); // Ð´Ëø£¬¹Ø±Õ¶Ë¿Ú¹ý³ÌÖв»ÔÊÐí¶Áд

+    if(usblog_fd >= 0)

+    {

+        ret = close(usblog_fd);

+        if (ret < 0)

+        {

+            printf("[zcat] close usblog_dev faild, ret = %d, error = %s\n", ret, strerror(errno));

+			pthread_rwlock_unlock(&usblog_rwlock);

+            return ret;  

+        }

+        else

+        {

+            usblog_fd = -1;

+        }

+    }

+    pthread_rwlock_unlock(&usblog_rwlock);

+    

+    return 0;

+}

+

+/**

+ * @brief ´ò¿ªusbÉ豸

+ * @param[in] void

+ * @return ·µ»ØÉ豸ÃèÊö·û

+ * @note

+ * @see 

+ */

+int open_usblog()

+{

+    int fd = -1;

+    char usblog_dev[16] = { 0 };

+

+    if ( usblog_fd >= 0 ) {

+        close_usblog();

+    }

+

+    sprintf(usblog_dev, "/dev/%s", g_zcat_usblog);

+    

+    fd = open(usblog_dev, O_RDWR);

+    if ( fd < 0 )

+    {

+        printf("[zcat] open %s error!\n", usblog_dev);

+        return -1;

+    }

+    printf("[zcat] open %s\n", usblog_dev);

+    

+    usblog_fd = fd;

+    

+    PortSet(fd);

+

+    return fd;

+}

+

+/**

+ * @brief ³õʼ»¯usbģʽ£¬\n

+ *        ¶ÁÈ¡usbÐéÄâµÄtty·¾¶.

+ *        ´ò¿ªtty£¬¶ÁÈ¡pc²à·¢¹ýÀ´µÄÐÄÌø°ü¡¢¹æÔòÎļþµÈÊý¾Ý

+ *        ´´½¨usbÈȲå°Î¼à²âÏß³Ì

+ * @param[in] void

+ * @return 0 on success, errno otherwise

+ * @note

+ * @see 

+ */

+int init_usblog_mode()

+{

+    int ret = 0;

+

+    ret = pthread_rwlock_init(&usblog_rwlock, NULL);

+    if(ret)

+    {

+        printf("[zcat] usblog_rwlock init error.\n"); 

+        return -1;

+    }

+    else

+    {

+        ret = init_monitor_hotplug();

+        if(ret < 0)

+        {

+            printf("[zcat] init_monitor_hotplug error.\n"); 

+            goto __exit;

+        }

+

+        ret = pthread_create(&read_usb_thread, NULL, read_usblog, NULL);

+        if(ret != 0)

+        {   

+            printf("[zcat] create read_usb_thread error.\n");

+            goto __exit;

+        }

+        return ret;

+    __exit:

+        pthread_rwlock_destroy(&usblog_rwlock);

+        return ret;

+    }

+}

+

+

diff --git a/ap/app/zte_log_agent/monitor.c b/ap/app/zte_log_agent/monitor.c
new file mode 100644
index 0000000..f797bba
--- /dev/null
+++ b/ap/app/zte_log_agent/monitor.c
@@ -0,0 +1,179 @@
+/**
+ * 
+ * @file      monitor.c
+ * @brief     
+ *            This file is part of ZCAT.
+ *            zcatÓ¦Óòãlog_agent¼à²âusb/tf/netµÈÍâÉè²å°Îʼþ
+ *            
+ * @details   
+ * @author    Tools Team.
+ * @email     
+ * @copyright Copyright (C) 2013 Sanechips Technology Co., Ltd.
+ * @warning   
+ * @date      2019/02/02
+ * @version   1.3
+ * @pre       
+ * @post      
+ *            
+ * @par       
+ * Change History :
+ * ---------------------------------------------------------------------------
+ * date        version  author         description
+ * ---------------------------------------------------------------------------
+ * 2017/07/17  1.0      hou.bing       Create file
+ * 2019/01/24  1.1      jiang.fenglin  1.Ìí¼Óusblog¶ÁÐ´Ëø
+ *                                     2.Ìí¼ÓÏß³ÌÃû³Æ
+ * 2019/01/25  1.2      jiang.fenglin  Ôö¼ÓAPUSBģʽÏÂtty·¾¶ÅäÖù¦ÄÜ
+ * 2019/02/02  1.3      jiang.fenglin  ÐÞ¸Ä×¢ÊÍ·½Ê½Îªdoxygen
+ * ---------------------------------------------------------------------------
+ * 
+ * 
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/prctl.h>
+#include <linux/types.h>
+#include <linux/netlink.h>
+#include <errno.h>
+#include <unistd.h>
+#include "../include/message.h"
+#include "cfg_api.h"
+#include "log_agent.h"
+
+#define BUFFER_SIZE     2048
+#define TIME_WAIT       30   /*³öÏÖÒì³£»Ö¸´Ê±¼ä*/
+
+pthread_t monitor_hotplug_thread = 0;
+
+#define ZCAT_DETECT_USB_HOTREMOVE  "offline@/devices/platform/zx29_hsotg.0/gadget/tty/ttyGS2"
+#define ZCAT_DETECT_USB_HOTADD      "online@/devices/platform/zx29_hsotg.0/gadget/tty/ttyGS2"
+#define ZCAT_DETECT_USB_HOTREMOVE1 "offline@/devices/platform/zx29_hsotg.0/gadget/tty/ttyGS1"
+#define ZCAT_DETECT_USB_HOTADD1     "online@/devices/platform/zx29_hsotg.0/gadget/tty/ttyGS1"
+#define ZCAT_DETECT_HOTPLUG               "@/devices/platform/zx29_hsotg.0/gadget/tty/"
+
+extern void get_usblog_tty_path();
+extern int close_usblog();
+extern int open_usblog();
+
+extern BOOL g_cp_trap_flag;
+extern int hb_flag;
+extern char g_zcat_usblog[8];
+
+static int g_hotplug_sock = -1;
+
+/**
+ * @brief ³õʼ»¯ÈȲå°Î¼àÊÓʼþ.
+ * @param[in] void
+ * @return ÎļþÃèÊö·û
+ * @note
+ * @see 
+ */
+static int init_hotplug_sock()
+{
+    const int buffersize = BUFFER_SIZE;
+    int ret;
+
+    struct sockaddr_nl snl;
+    bzero(&snl, sizeof(struct sockaddr_nl));
+    snl.nl_family = AF_NETLINK;
+    snl.nl_pid = getpid();
+    snl.nl_groups = 1;
+
+    int s = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
+    if (s == -1)
+    {
+        perror("socket");
+        return -1;
+    }
+    ret = setsockopt(s, SOL_SOCKET, SO_RCVBUF, &buffersize, sizeof(buffersize));
+	if(ret != 0)
+	{
+	    perror("setsockopt");
+	}
+
+    ret = bind(s, (struct sockaddr *)&snl, sizeof(struct sockaddr_nl));
+    if (ret < 0)
+    {
+        perror("bind");
+        close(s);
+        return -1;
+    }
+
+    return s;
+}
+
+/**
+ * @brief ÈȲå°Î¼àÊÓÏ̺߳¯Êý.
+ * @param[in] args Ï̺߳¯Êý²ÎÊý
+ * @return void
+ * @note
+ * @see 
+ */
+static void *monitor_hotplug(void* args)
+{
+    char buf[BUFFER_SIZE] = { 0 };
+    int ret = 0;
+
+    prctl(PR_SET_NAME, "monitor_hotplug");
+    
+    while(1)
+    {
+        memset(buf, 0, sizeof(buf));
+        
+        get_usblog_tty_path();
+        
+        ret = recv(g_hotplug_sock, &buf, sizeof(buf) - 1, 0);
+        printf("[zcat] hotplug msg, ret = %d, msg = %s\n", ret, buf);
+        
+        if (strstr(buf, ZCAT_DETECT_HOTPLUG))
+        {
+            if(strstr(buf, g_zcat_usblog))
+            {
+                if(strstr(buf, "offline"))
+                {
+                    hb_flag = 0;
+                    close_usblog();
+                    continue;
+                }
+
+                if(strstr(buf, "online"))
+                {
+                    if(open_usblog() < 0)
+                    {
+                        printf("[zcat] open_usblog error!\n");
+                        continue;
+                        //return -1;
+                    }
+                }
+            }
+        }
+    }
+	return NULL;
+}
+
+/**
+ * @brief ³õʼ»¯ÈȲå°Î¼àÊÓÏß³Ì.
+ * @param[in] void
+ * @return 0 on success, errno otherwise
+ * @note
+ * @see 
+ */
+int init_monitor_hotplug()
+{
+    int ret = -1;
+    
+	g_hotplug_sock = init_hotplug_sock();  
+    printf("[zcat] init_hotplug_sock %d\n", g_hotplug_sock);
+    if(g_hotplug_sock < 0)
+        return -1;
+    
+    ret = pthread_create(&monitor_hotplug_thread, NULL, monitor_hotplug, NULL);
+    if(ret != 0)
+    {   
+        printf("[zcat] create monitor_hotplug_thread error\n");
+        return -1;
+    }
+    return ret;
+}
diff --git a/ap/app/zte_log_agent/port_com.c b/ap/app/zte_log_agent/port_com.c
new file mode 100644
index 0000000..dfdd869
--- /dev/null
+++ b/ap/app/zte_log_agent/port_com.c
@@ -0,0 +1,272 @@
+/**

+ * ±¾³ÌÐò·ûºÏGPLÌõÔ¼

+ * Beneboy 2003-5-16

+ */

+#include <stdio.h>              // printf

+#include <fcntl.h>              // open

+#include <string.h>             // bzero

+#include <stdlib.h>             // exit

+#include <termios.h>            //termios, tcgetattr(), tcsetattr()

+#include <unistd.h>

+#include "port_com.h"

+

+// ½ÓÊÕ³¬Ê±

+#define TIMEOUT_SEC(buflen,baud) (buflen*20/baud+1)

+#define TIMEOUT_USEC 0

+

+// serial port information

+portinfo_t  g_sPortInfo =

+{

+    '0',      // print prompt after receiving

+    115200,   // baudrate: 115200

+    '8',      // databit: 8

+    '0',      // debug: off

+    '0',      // echo: off

+    '0',      // flow control: software

+    '0',      // default tty: COM1

+    '0',      // parity: none

+    '1',      // stopbit: 1

+     0        // reserved

+};

+

+/**

+ * ²¨ÌØÂÊת»¯×ª»»º¯Êý

+ */

+int convbaud(unsigned long int baudrate)

+{

+    switch (baudrate)

+    {

+        case 2400:

+            return B2400;

+        case 4800:

+            return B4800;

+        case 9600:

+            return B9600;

+        case 19200:

+            return B19200;

+        case 38400:

+            return B38400;

+        case 57600:

+            return B57600;

+        case 115200:

+            return B115200;

+        default:

+            return B9600;

+    }

+}

+

+/**

+ * Setup comm attr

+ * fd: ´®¿ÚÎļþÃèÊö·û, pportinfo: ´ýÉèÖõĶ˿ÚÐÅÏ¢s

+ *

+ */

+int PortSet(int fd)

+{

+    struct termios  termios_old, termios_new;

+    int             baudrate, tmp;

+    char            databit, stopbit, parity, fctl;

+    bzero(&termios_old, sizeof(termios_old));

+    bzero(&termios_new, sizeof(termios_new));

+    cfmakeraw(&termios_new);

+    tcgetattr(fd, &termios_old);         //get the serial port attributions

+    /*------------ÉèÖö˿ÚÊôÐÔ----------------*/

+    //baudrates

+    baudrate = convbaud(g_sPortInfo.baudrate);

+	cfsetispeed(&termios_new, baudrate);    // ÌîÈë´®¿ÚÊäÈë¶Ë²¨ÌØÂÊ

+	cfsetospeed(&termios_new, baudrate);    // ÌîÈë´®¿ÚÊä³ö¶Ë²¨ÌØÂÊ

+	termios_new.c_cflag |= CLOCAL;          // ¿ØÖÆÄ£Ê½, ±£Ö¤³ÌÐò²»»á³ÉΪ¶Ë¿ÚµÄÕ¼ÓÐÕß

+	termios_new.c_cflag |= CREAD;           // ¿ØÖÆÄ£Ê½, ʹÄܶ˿ڶÁÈ¡ÊäÈëµÄÊý¾Ý

+	// ¿ØÖÆÄ£Ê½, flow control

+    fctl = g_sPortInfo.fctl;

+    switch (fctl)

+    {

+        case '0':

+        {

+            termios_new.c_cflag &= ~CRTSCTS;        //no flow control

+        }

+        break;

+        case '1':

+        {

+            termios_new.c_cflag |= CRTSCTS;         //hardware flow control

+        }

+        break;

+        case '2':

+        {

+            termios_new.c_iflag |= IXON | IXOFF | IXANY;    //software flow control

+        }

+        break;

+        default:

+        {

+            printf("Unknown fctl %c\n", fctl);

+            break;

+        }

+    }

+    

+    // ¿ØÖÆÄ£Ê½, data bits

+    termios_new.c_cflag &= ~CSIZE;     // ¿ØÖÆÄ£Ê½, ÆÁ±Î×Ö·û´óСλ

+    databit = g_sPortInfo.databit;

+    switch (databit)

+    {

+        case '5':

+            termios_new.c_cflag |= CS5;

+            //lint -fallthrough

+        case '6':

+            termios_new.c_cflag |= CS6;

+            //lint -fallthrough

+        case '7':

+            termios_new.c_cflag |= CS7;

+            //lint -fallthrough

+        default:

+            termios_new.c_cflag |= CS8;

+    }

+    

+    // ¿ØÖÆÄ£Ê½ parity check

+    parity = g_sPortInfo.parity;

+    switch (parity)

+    {

+        case '0':

+        {

+            termios_new.c_cflag &= ~PARENB;     // no parity check

+        }

+        break;

+        case '1':

+        {

+            termios_new.c_cflag |= PARENB;      // odd check

+            termios_new.c_cflag &= ~PARODD;

+        }

+        break;

+        case '2':

+        {

+            termios_new.c_cflag |= PARENB;      // even check

+            termios_new.c_cflag |= PARODD;

+        }

+        break;

+        default:

+        {

+            printf("Unknown parity %c\n", parity);

+            break;

+        }

+    }

+

+    // ¿ØÖÆÄ£Ê½, stop bits

+    stopbit = g_sPortInfo.stopbit;

+    if (stopbit == '2')

+    {

+        termios_new.c_cflag |= CSTOPB;  // 2 stop bits

+    }

+    else

+    {

+        termios_new.c_cflag &= ~CSTOPB; // 1 stop bits

+    }

+

+    //other attributions default

+    termios_new.c_oflag &= ~OPOST;  // Êä³öģʽ, ԭʼÊý¾ÝÊä³ö

+    termios_new.c_cc[VMIN] = 1;     // ¿ØÖÆ×Ö·û, ËùÒª¶ÁÈ¡×Ö·ûµÄ×îСÊýÁ¿

+    termios_new.c_cc[VTIME] = 1;    // ¿ØÖÆ×Ö·û, ¶ÁÈ¡µÚÒ»¸ö×Ö·ûµÄµÈ´ýʱ¼ä,   unit: (1/10)second

+    tcflush(fd, TCIFLUSH);          // Òç³öµÄÊý¾Ý¿ÉÒÔ½ÓÊÕ,µ«²»¶Á

+    tmp = tcsetattr(fd, TCSANOW, &termios_new);  // ÉèÖÃÐÂÊôÐÔ, TCSANOW: ËùÓɸıäÁ¢¼´ÉúЧ

+    tcgetattr(fd, &termios_old);

+    return(tmp);

+}

+

+/**

+ * Open serial port

+ * tty: ¶Ë¿ÚºÅ ttyS0, ttyS1, ....

+ * ·µ»ØÖµÎª´®¿ÚÎļþÃèÊö·û

+ */

+int PortOpen(pportinfo_t pportinfo, int mode)

+{

+    return 0;

+}

+

+/**

+ * Close serial port

+ */

+void PortClose(int fd)

+{

+    close(fd);

+}

+

+/**

+ * PortSend

+ *  fd: ´®¿ÚÃèÊö·û,

+ *  data: ´ý·¢ËÍÊý¾ÝÖ¸Õë

+ *  datalen: Êý¾Ý³¤¶È

+ *  flag: ·¢ËÍ·½Ê½±êʶ

+ *  ·µ»ØÊµ¼Ê·¢Ëͳ¤¶È

+ */

+int PortSend(int fd, unsigned char* data, int datalen)

+{

+	int len = 0;

+

+	len = write(fd, data, datalen);  //ʵ¼ÊдÈëµÄ³¤¶È

+	if (len == datalen)

+	{

+		return (len);

+	}

+	else

+	{

+		tcflush(fd, TCOFLUSH);

+		return -1;

+	}

+}

+

+/**

+ * PortRecv

+ *  ²ÎÊý£º

+ *  fd: ´®¿ÚÃèÊö·û,

+ *  data: ´ý½ÓÊÕÊý¾ÝÖ¸Õë

+ *  datalen: Êý¾Ý³¤¶È

+ *  flag: ½ÓÊÕ·½Ê½±êʶ

+ *  ·µ»ØÊµ¼Ê¶ÁÈëµÄ×Ö½ÚÊý

+ */

+int PortRecv(int fd, unsigned char* data, int datalen)

+{

+#if 0

+	int             readlen, fs_sel;

+	fd_set          fs_read;

+	struct timeval  tv_timeout;

+	FD_ZERO(&fs_read);

+	FD_SET(fd, &fs_read);

+

+    /*RAT ¸ÃÖµÓ¦¸Ã¼õСÒÔÌá¸ßÏìÓ¦ËÙ¶È*/

+	tv_timeout.tv_sec = 0;/*TIMEOUT_SEC(datalen, baudrate);*/

+

+	tv_timeout.tv_usec = 200;/*TIMEOUT_USEC;*/

+

+	fs_sel = select(fd + 1, &fs_read, NULL, NULL, &tv_timeout);

+	if (fs_sel)

+	{

+

+		printf("rpmsg: portrecv fd =%d\n",fd);

+		readlen = read(fd, data, datalen);

+		return(readlen);

+	}

+	else

+	{

+		return(0);

+	}

+#else

+   int readlen = read(fd, data, datalen);

+   return(readlen);

+#endif

+}

+

+int tty_set_log_port(int fd)

+{

+    if (fd < 0)

+	{

+		printf("tty_set_port failed. %d\n", fd);

+		return 0;

+	}

+	printf("tty_set_port ok.\n");

+	//ioctl(g_AtProxy_RpProxyFd, (('R'<<8)|6|(0x4004<<16)), 0x400);

+	//printf("rpmsg: ap port open fd = %d\n",fd);//add shideyou

+	//ioctl(fd, (('R'<<8)|1|(0x4004<<16)), 0x400);

+	//ioctl(fd, (('R'<<8)|4|(0x4004<<16)), 0);

+    PortSet(fd);

+    //ZTE_LOG(LOG_DEBUG, "port is open!"); 

+    return 1;

+}

+

+

diff --git a/ap/app/zte_log_agent/port_com.h b/ap/app/zte_log_agent/port_com.h
new file mode 100644
index 0000000..b198331
--- /dev/null
+++ b/ap/app/zte_log_agent/port_com.h
@@ -0,0 +1,67 @@
+/**

+ * ±¾³ÌÐò·ûºÏGPLÌõÔ¼

+ * Ò»×é²Ù×÷´®¿ÚµÄº¯Êý

+ * Beneboy 2003-5-16

+ */

+

+#ifndef comH

+#define comH

+

+

+typedef struct

+{

+    char prompt;    // prompt after reciving data

+    int  baudrate;  // baudrate

+    char databit;   // data bits, 5, 6, 7, 8

+    char debug;     // debug mode, 0: none, 1: debug

+    char echo;      // echo mode, 0: none, 1: echo

+    char fctl;      // flow control, 0: none, 1: hardware, 2: software

+    char tty;       // tty: 0, 1, 2, 3, 4, 5, 6, 7

+    char parity;    // parity 0: none, 1: odd, 2: even

+    char stopbit;   // stop bits, 1, 2

+    int  reserved;  // reserved, must be zero

+} portinfo_t, *pportinfo_t;

+

+

+/**

+ *  ´ò¿ª´®¿Ú, ·µ»ØÎļþÃèÊö·û

+ *  pportinfo: ´ýÉèÖõĴ®¿ÚÐÅÏ¢

+ */

+int PortOpen(pportinfo_t pportinfo,int mode);

+

+/**

+ *  ¶Ë¿Ú³õʼ»¯

+ */

+int PortInit(int mode);

+/**

+ *  ÉèÖô®¿Ú

+ *  fdcom: ´®¿ÚÎļþÃèÊö·û, pportinfo: ´ýÉèÖõĴ®¿ÚÐÅÏ¢

+ */

+int PortSet(int fd);

+/**

+ *  ¹Ø±Õ´®¿Ú

+ *  fdcom: ´®¿ÚÎļþÃèÊö·û

+ */

+void PortClose(int fd);

+

+/**

+ * PortSend

+ *  fd: ´®¿ÚÃèÊö·û,

+ *  data: ´ý·¢ËÍÊý¾ÝÖ¸Õë

+ *  datalen: Êý¾Ý³¤¶È

+ *  ·µ»ØÊµ¼Ê·¢Ëͳ¤¶È

+ */

+int PortSend(int fd, unsigned char* data, int datalen);

+

+/**

+ * PortRecv

+ *  ²ÎÊý£º

+ *  fd: ´®¿ÚÃèÊö·û,

+ *  data: ´ý½ÓÊÕÊý¾ÝÖ¸Õë

+ *  datalen: Êý¾Ý³¤¶È

+ *  ·µ»ØÊµ¼Ê¶ÁÈëµÄ×Ö½ÚÊý

+ */

+int PortRecv(int fd, unsigned char* data, int datalen);

+

+#endif

+