瀏覽代碼

更新mongoose到最新版,还是会崩溃,原因需继续排查

guohui 1 年之前
父節點
當前提交
fa0e60f788
共有 37 個文件被更改,包括 46043 次插入 和 19828 次删除
  1. 3 2
      f407/applications/board.c
  2. 3 2
      f407/applications/cfg.h
  3. 6 0
      f407/applications/datadef.h
  4. 1 2
      f407/applications/dflt.c
  5. 1 1
      f407/applications/fs.c
  6. 4 70
      f407/applications/lock.c
  7. 4 26
      f407/applications/lock.h
  8. 8 8
      f407/applications/log.h
  9. 17 20
      f407/applications/main.c
  10. 3 8
      f407/applications/mb.c
  11. 24 19
      f407/applications/packages/iniparser/src/iniparser.c
  12. 20307 0
      f407/applications/packages/mongoose-v6.7/7.16/mongoose.c
  13. 3286 0
      f407/applications/packages/mongoose-v6.7/7.16/mongoose.h
  14. 5 34
      f407/applications/packages/mongoose-v6.7/mg_locals.h
  15. 18221 13080
      f407/applications/packages/mongoose-v6.7/mongoose.c
  16. 2628 5177
      f407/applications/packages/mongoose-v6.7/mongoose.h
  17. 20 18
      f407/applications/paras.c
  18. 262 171
      f407/applications/power.c
  19. 4 5
      f407/applications/power.h
  20. 2 9
      f407/applications/rtconfig.h
  21. 1 0
      f407/applications/sys.c
  22. 44 40
      f407/applications/thread.c
  23. 8 12
      f407/applications/thread.h
  24. 38 42
      f407/applications/ui/lcd.c
  25. 36 23
      f407/applications/ui/lcd.h
  26. 218 426
      f407/applications/ui/st7789.c
  27. 3 11
      f407/applications/ui/ui.c
  28. 340 55
      f407/applications/web.c
  29. 1 1
      f407/applications/web.h
  30. 1 1
      f407/drivers/libraries/CMSIS/Device/ST/STM32F4xx/Source/startup_stm32f407xx.s
  31. 410 460
      f407/project/app/app.uvoptx
  32. 6 11
      f407/project/app/app.uvprojx
  33. 1 1
      f407/rt-thread/src/ipc.c
  34. 3 3
      f407/tools/web/data.js
  35. 2 11
      f407/tools/web/index.html
  36. 1 1
      f407/tools/webServer/EasyWebSvr.ini
  37. 121 78
      f407/tools/wsServer/mg.cpp

+ 3 - 2
f407/applications/board.c

@@ -12,15 +12,16 @@
 #include <board.h>
 #include <drv_common.h>
 
-static struct rt_memheap system_heap2;
+
 void rt_hw_board_init()
 {
+    struct rt_memheap heap;
     extern void hw_board_init(char *clock_src, int32_t clock_src_freq, int32_t clock_target_freq);
 
     /* Heap initialization */
 #if defined(RT_USING_HEAP)
     rt_system_heap_init((void *) HEAP_BEGIN1, (void *) HEAP_END1);
-    rt_memheap_init(&system_heap2, "sram", (void *)RAM2_START, RAM2_SIZE);
+    rt_memheap_init(&heap, "sram2", (void *)RAM2_START, RAM2_SIZE);
 #endif
 
     hw_board_init(BSP_CLOCK_SOURCE, BSP_CLOCK_SOURCE_FREQ_MHZ, BSP_CLOCK_SYSTEM_FREQ_MHZ);

+ 3 - 2
f407/applications/cfg.h

@@ -48,8 +48,9 @@
     
     #define CHANNEL_DELAY                       8
 
-    #define PROD_TYPE                           PDU_AC_I3O3
-
+    //#define PROD_TYPE                           PDU_AC_I3O3
+    #define PROD_TYPE                           PDU_AC_I3O1_H
+    
     //#define USE_UI
 
 

+ 6 - 0
f407/applications/datadef.h

@@ -55,6 +55,12 @@ enum {
     ALARM_P_UPPER     = (1<<10),
 };
 
+enum {
+    ALARM_ACT_CLOSE_CH=1,
+    ALARM_ACT_MESG,
+    ALARM_ACT_CLOSE_CHALL,
+};
+
 enum {
     THRESHOLD_V_UPPER = (1<<0), //电压超上限
     THRESHOLD_V_LOWER = (1<<1), //电压超下限

+ 1 - 2
f407/applications/dflt.c

@@ -1,8 +1,7 @@
 #include "datadef.h"
 #include "cfg.h"
 
-
-paras_data_t DFLT_PARAS={
+const paras_data_t DFLT_PARAS={
 
         .prod = {
             .id         = 1011,

+ 1 - 1
f407/applications/fs.c

@@ -117,7 +117,7 @@ static int do_mount(fs_handle_t *h, char *dev, int flag)
                 }
             }
             else {
-                LOGD("%s fs inited\n");
+                LOGD("%s fs inited\n", info->mpath);
             }
         }
         else {

+ 4 - 70
f407/applications/lock.c

@@ -10,73 +10,7 @@
 #define FREE      free
 
 
-//static global lock 
-
-static pthread_mutex_t *mutex_pool[LOCK_ID_MAX]={0};
-int lock_s_init(void)
-{
-    int i,r;
-    pthread_mutex_t *m=NULL;
-    
-    for(i=0; i<LOCK_ID_MAX; i++) {
-        m = MALLOC(sizeof(pthread_mutex_t));
-        if(m) {
-            r = pthread_mutex_init(m, NULL);
-            if(r) {
-                LOGE("lock_s_init %d failed\n", i);
-                FREE(m); m = NULL;
-            }
-            mutex_pool[i] = m;
-        }
-    }
-    
-    return 0;
-}
-
-
-int lock_s_deinit(void)
-{
-    int i,r;
-    
-    for(i=0; i<LOCK_ID_MAX; i++) {
-        if(mutex_pool[i]) {
-            r = pthread_mutex_destroy(mutex_pool[i]);
-            if(r) {
-                LOGE("lock_s_deinit %d failed\n", i);
-                continue;
-            }
-            
-            mutex_pool[i] = NULL;
-        }
-    }
-    
-    return 0;
-}
-
-
-int lock_s_hold(int id)
-{
-    if(id<0 || id>=LOCK_ID_MAX || !mutex_pool[id]) {
-        return -1;
-    }
-    
-     return pthread_mutex_lock(mutex_pool[id]);
-}
-
-
-int lock_s_release(int id)
-{
-    if(id<0 || id>=LOCK_ID_MAX || !mutex_pool[id]) {
-        return -1;
-    }
-    
-    return pthread_mutex_unlock(mutex_pool[id]);
-}
-
-
-///////////////////////////////////////////////////////
-
-lock_t lock_d_init(void)
+lock_t lock_init(void)
 {
     int r;
     pthread_mutex_t *m=MALLOC(sizeof(pthread_mutex_t));
@@ -94,7 +28,7 @@ lock_t lock_d_init(void)
 }
 
 
-int lock_d_deinit(lock_t h)
+int lock_deinit(lock_t h)
 {
     int r;
     
@@ -108,7 +42,7 @@ int lock_d_deinit(lock_t h)
 }
 
 
-int lock_d_hold(lock_t h)
+int lock_on(lock_t h)
 {
     if(!h) {
         return -1;
@@ -118,7 +52,7 @@ int lock_d_hold(lock_t h)
 }
 
 
-int lock_d_release(lock_t h)
+int lock_off(lock_t h)
 {
     if(!h) {
         return -1;

+ 4 - 26
f407/applications/lock.h

@@ -2,35 +2,13 @@
 #define __LOCK_Hx__
 
 
-enum {
-    LOCK_ID_DB=0,
-    LOCK_ID_MQTT,
-    LOCK_ID_MAIL,
-    LOCK_ID_PARAS,
-    LOCK_ID_SENSOR,
-    LOCK_ID_BREAKER,
-    LOCK_ID_NETSWITCH,
-    LOCK_ID_POWER_TIMER,
-    LOCK_ID_POWER_UPDATE,
-    
-    LOCK_ID_MAX
-};
-
-
-//static lock
-int lock_s_init(void);
-int lock_s_deinit(void);
-int lock_s_hold(int id);
-int lock_s_release(int id);
-
-
 //dynamic lock
 typedef unsigned long lock_t;
 
-lock_t lock_d_init(void);
-int lock_d_deinit(lock_t h);
-int lock_d_hold(lock_t h);
-int lock_d_release(lock_t h);
+lock_t lock_init(void);
+int lock_deinit(lock_t h);
+int lock_on(lock_t h);
+int lock_off(lock_t h);
 
 
 #endif

+ 8 - 8
f407/applications/log.h

@@ -10,17 +10,17 @@
     #define LOGI   LOG_I
     #define LOGE   LOG_E
 #else
-    #define LOGD   printf
-    #define LOGW   printf
-    #define LOGI   printf
-    #define LOGE   printf
+    #define LOGD   rt_kprintf
+    #define LOGW   rt_kprintf
+    #define LOGI   rt_kprintf
+    #define LOGE   rt_kprintf
 #endif
     
 #else
-    #define LOGD   printf
-    #define LOGW   printf
-    #define LOGI   printf
-    #define LOGE   printf
+    #define LOGD   rt_kprintf
+    #define LOGW   rt_kprintf
+    #define LOGI   rt_kprintf
+    #define LOGE   rt_kprintf
 #endif
                                 
 #endif

+ 17 - 20
f407/applications/main.c

@@ -3,6 +3,7 @@
 #include <drv_gpio.h>
 #include <drv_usbh.h>
 #include <dfs_fs.h>
+#include <unistd.h>
 #include <sys/socket.h>
 #include <netdb.h>
 #include <unistd.h>
@@ -92,12 +93,17 @@ __exit:
 static int sd_mount(void)
 {
     int r=1,n=0;
-    r = mmcsd_wait_cd_changed(500);
-    if(r==MMCSD_HOST_PLUGED) {
-        r = fs_mount("sd", 1);
-    }
-    else if(r==MMCSD_HOST_UNPLUGED) {
-        r = fs_mount("sd", 0);
+    while(n<10) {
+        r = mmcsd_wait_cd_changed(500);
+        if(r==MMCSD_HOST_PLUGED) {
+            r = fs_mount("sd", 1);
+        }
+        else if(r==MMCSD_HOST_UNPLUGED) {
+            r = fs_mount("sd", 0);
+        }
+        
+        if(r<=0) break;
+        n++;
     }
     return r;
 }
@@ -105,22 +111,14 @@ static int sd_mount(void)
 
 static int user_init(void)
 {
-    int r,n=0;
-    
     //ui_init();
-    //rt_hw_lcd_init();
-    //net_init("0.0.0.0", SERVER_PORT);
+    sd_mount();
     
+LOGD("___ user 111\n");
     power_init();
-    while(n<10) {
-        r = sd_mount();
-        if(r<=0) {
-            break;
-        }
-        
-        n++;
-    }
+LOGD("___ user 222\n");
     web_init();
+LOGD("___ user 333\n");
     
     return 0;
 }
@@ -132,7 +130,6 @@ int main(void)
     sys_init();
     user_init();
     while (1) {
-        
-        rt_thread_mdelay(5000);
+        sleep(10);
     }
 }

+ 3 - 8
f407/applications/mb.c

@@ -189,9 +189,6 @@ int mb_read(void *h, uint8_t addr, uint16_t reg, uint16_t *data, int cnt, int ti
     if(sz==cnt) {
         r = 0;
     }
-    else {
-        r = -1;
-    }
 #endif
     
     return r;
@@ -200,9 +197,10 @@ int mb_read(void *h, uint8_t addr, uint16_t reg, uint16_t *data, int cnt, int ti
 
 int mb_write(void *h, uint8_t addr, uint16_t reg, uint16_t *data, int cnt)
 {
-    int r,sz;
+    int r=-1,sz;
     mb_handle_t *mh=(mb_handle_t*)h;
-    if(!mh) {
+    
+    if(!mh || !data || cnt<=0) {
         return -1;
     }
 
@@ -214,9 +212,6 @@ int mb_write(void *h, uint8_t addr, uint16_t reg, uint16_t *data, int cnt)
     if(sz==cnt) {
         r = 0;
     }
-    else {
-        r = -1;
-    }
 #endif
     
     return r;

+ 24 - 19
f407/applications/packages/iniparser/src/iniparser.c

@@ -803,76 +803,79 @@ static line_status iniparser_line(
   The returned dictionary must be freed using iniparser_freedict().
  */
 /*--------------------------------------------------------------------------*/
-dictionary * iniparser_load_file(FILE * in, const char * ininame)
-{
+typedef struct {
     char line    [ASCIILINESZ+1] ;
     char section [ASCIILINESZ+1] ;
     char key     [ASCIILINESZ+1] ;
     char tmp     [(ASCIILINESZ * 2) + 2] ;
     char val     [ASCIILINESZ+1] ;
+}dic_buf_t;
 
+dictionary * iniparser_load_file(FILE * in, const char * ininame)
+{
     int  last=0 ;
     int  len ;
     int  lineno=0 ;
     int  errs=0;
     int  mem_err=0;
-
     dictionary * dict ;
+    dic_buf_t *pbuf=malloc(sizeof(dic_buf_t));
 
+    if(!pbuf) return NULL;
+    
     dict = dictionary_new(0) ;
     if (!dict) {
+        free(pbuf);
         return NULL ;
     }
 
-    memset(line,    0, ASCIILINESZ);
-    memset(section, 0, ASCIILINESZ);
-    memset(key,     0, ASCIILINESZ);
-    memset(val,     0, ASCIILINESZ);
+    memset(pbuf, 0, sizeof(dic_buf_t));
     last=0 ;
 
-    while (fgets(line+last, ASCIILINESZ-last, in)!=NULL) {
+    while (fgets(pbuf->line+last, ASCIILINESZ-last, in)!=NULL) {
         lineno++ ;
-        len = (int)strlen(line)-1;
+        len = (int)strlen(pbuf->line)-1;
         if (len<=0)
             continue;
         /* Safety check against buffer overflows */
-        if (line[len]!='\n' && !feof(in)) {
+        if (pbuf->line[len]!='\n' && !feof(in)) {
             iniparser_error_callback(
               "iniparser: input line too long in %s (%d)\n",
               ininame,
               lineno);
             dictionary_del(dict);
+            free(pbuf);
             return NULL ;
         }
         /* Get rid of \n and spaces at end of line */
         while ((len>=0) &&
-                ((line[len]=='\n') || (isspace(line[len])))) {
-            line[len]=0 ;
+                ((pbuf->line[len]=='\n') || (isspace(pbuf->line[len])))) {
+            pbuf->line[len]=0 ;
             len-- ;
         }
         if (len < 0) { /* Line was entirely \n and/or spaces */
             len = 0;
         }
         /* Detect multi-line */
-        if (line[len]=='\\') {
+        if (pbuf->line[len]=='\\') {
             /* Multi-line value */
             last=len ;
             continue ;
         } else {
             last=0 ;
         }
-        switch (iniparser_line(line, section, key, val)) {
+        switch (iniparser_line(pbuf->line, pbuf->section, pbuf->key, pbuf->val)) {
             case LINE_EMPTY:
             case LINE_COMMENT:
             break ;
 
             case LINE_SECTION:
-            mem_err = dictionary_set(dict, section, NULL);
+            mem_err = dictionary_set(dict, pbuf->section, NULL);
             break ;
 
             case LINE_VALUE:
-            sprintf(tmp, "%s:%s", section, key);
-            mem_err = dictionary_set(dict, tmp, val);
+            sprintf(pbuf->tmp, "%s:%s", pbuf->section, pbuf->key);
+            mem_err = dictionary_set(dict, pbuf->tmp, pbuf->val);
             break ;
 
             case LINE_ERROR:
@@ -880,14 +883,14 @@ dictionary * iniparser_load_file(FILE * in, const char * ininame)
               "iniparser: syntax error in %s (%d):\n-> %s\n",
               ininame,
               lineno,
-              line);
+              pbuf->line);
             errs++ ;
             break;
 
             default:
             break ;
         }
-        memset(line, 0, ASCIILINESZ);
+        memset(pbuf->line, 0, ASCIILINESZ);
         last=0;
         if (mem_err<0) {
             iniparser_error_callback("iniparser: memory allocation failure\n");
@@ -898,6 +901,8 @@ dictionary * iniparser_load_file(FILE * in, const char * ininame)
         dictionary_del(dict);
         dict = NULL ;
     }
+    free(pbuf);
+    
     return dict ;
 }
 

文件差異過大導致無法顯示
+ 20307 - 0
f407/applications/packages/mongoose-v6.7/7.16/mongoose.c


文件差異過大導致無法顯示
+ 3286 - 0
f407/applications/packages/mongoose-v6.7/7.16/mongoose.h


+ 5 - 34
f407/applications/packages/mongoose-v6.7/mg_locals.h

@@ -58,41 +58,12 @@
 #define MG_STRDUP                                rt_strdup
 #define WEAK                                     rt_weak
 
-#if defined(PKG_MONGOOSE_ENABLE_HTTP_WEBSOCKET)
-    #define MG_ENABLE_HTTP_WEBSOCKET             1
-#else
-    #define MG_ENABLE_HTTP_WEBSOCKET             0
-#endif
-
-#if defined(PKG_MONGOOSE_ENABLE_FILESYSTEM)
-    #define MG_ENABLE_FILESYSTEM                 1
-#else
-    #define MG_ENABLE_FILESYSTEM                 0
-#endif
-
-#if defined(PKG_MONGOOSE_ENABLE_HTTP_STREAMING_MULTIPART)
-    #define MG_ENABLE_HTTP_STREAMING_MULTIPART   1
-#else
-    #define MG_ENABLE_HTTP_STREAMING_MULTIPART   0
-#endif
+#define MG_ENABLE_HTTP_WEBSOCKET                 1
+#define MG_ENABLE_FILESYSTEM                     1
+#define MG_ENABLE_HTTP_STREAMING_MULTIPART       1
+#define MG_ENABLE_MQTT                           1
+#define MG_ENABLE_COAP                           0
 
-#if defined(PKG_MONGOOSE_ENABLE_MQTT)
-    #define MG_ENABLE_MQTT                       1
-#else
-    #define MG_ENABLE_MQTT                       0
-#endif
-
-#if defined(PKG_MONGOOSE_ENABLE_COAP)
-    #define MG_ENABLE_COAP                       1
-#else
-    #define MG_ENABLE_COAP                       0
-#endif
-
-#if defined(PKG_MONGOOSE_ENABLE_HEXDUMP)
-    #define MG_ENABLE_HEXDUMP                    1
-#else
-    #define MG_ENABLE_HEXDUMP                    0
-#endif
 
 #define fcntl(s,cmd,val)                         lwip_fcntl(s,cmd,val)
 

文件差異過大導致無法顯示
+ 18221 - 13080
f407/applications/packages/mongoose-v6.7/mongoose.c


文件差異過大導致無法顯示
+ 2628 - 5177
f407/applications/packages/mongoose-v6.7/mongoose.h


+ 20 - 18
f407/applications/paras.c

@@ -30,12 +30,14 @@ enum {
     PARAS_CREATE,
 };
 
-extern paras_data_t DFLT_PARAS;
+extern const paras_data_t DFLT_PARAS;
 
 typedef struct {
     dictionary          *dic;
     paras_data_t        paras;
-    char                path[200];
+    char                path[100];
+    
+    lock_t              lck;
 }paras_handle_t;
 static paras_handle_t  paraHandle={0};
 
@@ -3012,7 +3014,7 @@ static dictionary* ini_load(char *path, paras_data_t *info)
     if(dic == NULL){
         return NULL;
     }
-    
+   
     r = proc_prod(dic, PARAS_READ, &info->prod);
     if(r) {
         LOGE("___proc_prod failed\n");
@@ -3232,8 +3234,8 @@ int paras_init(void)
     int r=0;
     paras_handle_t  *h=&paraHandle;
     
-    lock_s_hold(LOCK_ID_PARAS);
-    memset(&paraHandle, 0, sizeof(paraHandle));
+    memset(h, 0, sizeof(paraHandle));
+    h->lck = lock_init();
     h->paras = DFLT_PARAS;
     get_prod(&h->paras);
     sprintf(h->path, "/cfg/%s", INI_NAME);
@@ -3241,7 +3243,6 @@ int paras_init(void)
     if(h->dic==NULL) {
         r = ini_reset(h);
     }
-    lock_s_release(LOCK_ID_PARAS);
     
     return r;
 }
@@ -3252,9 +3253,8 @@ int paras_deinit(void)
     int r=0;
     paras_handle_t *h=&paraHandle;
     
-    lock_s_hold(LOCK_ID_PARAS);
     r = ini_free(h);
-    lock_s_release(LOCK_ID_PARAS);
+    lock_deinit(h->lck);
     
     return 0;
 }
@@ -3270,10 +3270,11 @@ paras_data_t* paras_get(void)
 int paras_check(char *path)
 {
     int r=0;
+    paras_handle_t *h=&paraHandle;
     
-    lock_s_hold(LOCK_ID_PARAS);
+    lock_on(h->lck);
     r = ini_check(path);
-    lock_s_release(LOCK_ID_PARAS);
+    lock_off(h->lck);
     
     return r;
 }
@@ -3284,11 +3285,11 @@ int paras_load(char *path)
     int r=-1;
     paras_handle_t *h=&paraHandle;
 
-    lock_s_hold(LOCK_ID_PARAS);
+    lock_on(h->lck);
     ini_free(h);
     h->dic = ini_load(path, &h->paras);
     if(h->dic) r = 0;
-    lock_s_release(LOCK_ID_PARAS);
+    lock_off(h->lck);
     
     return r;
 }
@@ -3299,9 +3300,9 @@ int paras_reset(void)
     int r=0;
     paras_handle_t *h=&paraHandle;
     
-    lock_s_hold(LOCK_ID_PARAS);
+    lock_on(h->lck);
     ini_reset(h);
-    lock_s_release(LOCK_ID_PARAS);
+    lock_off(h->lck);
     
     return r;
 }
@@ -3310,10 +3311,11 @@ int paras_reset(void)
 int paras_copy(char *dst, char *src)
 {
     int r=-1;
+    paras_handle_t *h=&paraHandle;
 
-    lock_s_hold(LOCK_ID_PARAS);
+    lock_on(h->lck);
     r = fs_copy(dst, src);
-    lock_s_release(LOCK_ID_PARAS);
+    lock_off(h->lck);
 
     return r;
 }
@@ -3324,9 +3326,9 @@ int paras_save(void)
     int r=0;
     paras_handle_t *h=&paraHandle;
     
-    lock_s_hold(LOCK_ID_PARAS);
+    lock_on(h->lck);
     r = ini_save(h);
-    lock_s_release(LOCK_ID_PARAS);
+    lock_off(h->lck);
     
     return r;
 }

+ 262 - 171
f407/applications/power.c

@@ -8,8 +8,10 @@
 #include "thread.h"
 #include "datadef.h"
 
-#define BRD_NUM         3 //BRD_MAX
-#define BRD_TIMEOUT     100
+
+#define BRD_NUM             3 //BRD_MAX
+#define BRD_TIMEOUT         200
+#define RETRY_TIMES         3
 
 #define LIMIT_HOF(x)  (x*1.1f)
 #define LIMIT_LOF(x)  (x*0.9f)
@@ -30,9 +32,25 @@ typedef struct {
     power_total_t   ttl;
     
     product_data_t *prod;
+    power_data_t   pdat;
 }power_handle_t;
 power_handle_t pwrHandle={0};
 
+
+
+static int alarm_evt_handle(power_handle_t *h, power_ch_t *pch, uint32_t flag)
+{
+    alarm_data_t ad;
+    
+    ad.ch = pch->info.ch;
+    ad.alarm = pch->alarm;
+    ad.time = pch->time;
+    web_post(PKT_TYPE_ALARM, &ad, sizeof(ad));
+    
+    return 0;
+}
+
+
 static void memswap(uint8_t *buf, int len)
 {
     int i;
@@ -45,11 +63,21 @@ static void memswap(uint8_t *buf, int len)
 }
 static int read_reg(power_handle_t *h, uint8_t addr, uint16_t reg, uint16_t *data, int cnt)
 {
-    return mb_read(h->mb, addr, reg, data, cnt, BRD_TIMEOUT);
+    int i,r;
+    for(i=0; i<RETRY_TIMES; i++) {
+        r = mb_read(h->mb, addr, reg, data, cnt, BRD_TIMEOUT);
+        if(r==0) break;
+    }
+    return r;
 }
 static int write_reg(power_handle_t *h, uint8_t addr, uint16_t reg, uint16_t *data, int cnt)
 {
-    return mb_write(h->mb, addr, reg, data, cnt);
+    int i,r;
+    for(i=0; i<RETRY_TIMES; i++) {
+        r = mb_write(h->mb, addr, reg, data, cnt);
+        if(r==0) break;
+    }
+    return r;
 }
 ////////////////////////////////////////////////////////////////////
 static int get_key(power_handle_t *h, uint8_t addr, board_key_t *key)
@@ -57,17 +85,20 @@ static int get_key(power_handle_t *h, uint8_t addr, board_key_t *key)
     int i,r=-1;
     uint16_t tmp[2];
     
-    r = read_reg(h, addr, POWER_DC_INFO, tmp, 2);
-    if(r==0) {
-        key->type = (tmp[0]>>8)&0xFF;
-        key->chs = tmp[0]&0xFF;
-        return 0;
+    if(h->prod->pwr_type==PDU_AC_I1O1 || h->prod->pwr_type==PDU_AC_I3O1_H) {
+        r = read_reg(h, addr, POWER_AC_GET_INFO, tmp, 1);
+        if(r==0) {
+            key->type = (tmp[0]>>8)&0xFF;
+            key->chs = tmp[0]&0xFF;
+        }
     }
-    
-    r = read_reg(h, addr, POWER_AC_GET_INFO, tmp, 2);
-    if(r==0) {
-        key->type = (tmp[0]>>8)&0xFF;
-        key->chs = tmp[0]&0xFF;
+    else {
+        r = read_reg(h, addr, POWER_DC_INFO, tmp, 2);
+        if(r==0) {
+            key->type = (tmp[0]>>8)&0xFF;
+            key->chs = tmp[0]&0xFF;
+            return 0;
+        }
     }
     
     return r;
@@ -215,7 +246,7 @@ static int threshold_proc(power_handle_t *h, board_data_t *pbrd)
             
             //设置为输出三相且三相有缺失则报警
             if(pch->info.ph_val && pbrd->ph_loss) {
-                //trigger alarm event here ...
+                alarm_evt_handle(h, pch, THRESHOLD_V_UPPER);
             }
         }
         
@@ -224,13 +255,13 @@ static int threshold_proc(power_handle_t *h, board_data_t *pbrd)
                 if(pch->power[j].voltage>pch->thr.v_upper.val) {
                     if(pch->alarm.v_upper==0) {
                         pch->alarm.v_upper = 1;
-                        //trigger alarm event here ...
+                        alarm_evt_handle(h, pch, THRESHOLD_V_UPPER);
                     }
                 }
                 else if(pch->power[j].voltage<pch->thr.v_lower.val) {
                     if(pch->alarm.v_lower==0) {
                         pch->alarm.v_lower = 1;
-                        //trigger alarm event here ...
+                        alarm_evt_handle(h, pch, THRESHOLD_V_LOWER);
                     }
                 }
                 else {
@@ -243,7 +274,7 @@ static int threshold_proc(power_handle_t *h, board_data_t *pbrd)
                 if(pch->power[j].current>pch->thr.c_upper.val) {
                     if(pch->alarm.c_upper==0) {
                         pch->alarm.c_upper = 1;
-                        //trigger alarm event here ...
+                        alarm_evt_handle(h, pch, THRESHOLD_C_UPPER);
                     }
                 }
                 else {
@@ -255,7 +286,7 @@ static int threshold_proc(power_handle_t *h, board_data_t *pbrd)
                 if(pch->power[j].power>pch->thr.p_upper.val) {
                     if(pch->alarm.p_upper==0) {
                         pch->alarm.p_upper = 1;
-                        //trigger alarm event here ...
+                        alarm_evt_handle(h, pch, THRESHOLD_P_UPPER);
                     }
                 }
                 else {
@@ -267,7 +298,7 @@ static int threshold_proc(power_handle_t *h, board_data_t *pbrd)
                 if(pch->power[j].current>pch->thr.w_upper.val) {
                     if(pch->alarm.w_upper==0) {
                         pch->alarm.w_upper = 1;
-                        //trigger alarm event here ...
+                        alarm_evt_handle(h, pch, THRESHOLD_W_UPPER);
                     }
                 }
                 else {
@@ -286,7 +317,7 @@ static int total_proc(power_handle_t *h)
     power_ch_t *pch=NULL;
     board_data_t *pbrd=NULL;
     
-    lock_d_hold(h->lck);
+    lock_on(h->lck);
     if(h->prod->pwr_type==PDU_AC_I3O3) times = 3;
     for(i=0; i<h->brd_max; i++) {
         if(h->pbrd[i]) {
@@ -317,7 +348,7 @@ static int total_proc(power_handle_t *h)
     
     h->ttl.type = h->prod->pwr_type;
     memcpy(h->ttl.total, tmp, sizeof(tmp));
-    lock_d_release(h->lck);
+    lock_off(h->lck);
     
     return 0;
 }
@@ -328,16 +359,18 @@ static int board_read(power_handle_t *h, board_data_t *pbrd)
     uint16_t offset,tmp[144];
     power_ch_t *pch=NULL;
     
-    lock_d_hold(h->lck);
+    lock_on(h->lck);
     if(pbrd) {
         switch(pbrd->type) {
             case AC_SINGLE_S_TYPE:
             case AC_SINGLE_B_TYPE:
             {
                 uint32_t val;
-                r = read_reg(h, pbrd->addr, POWER_AC_CUR_INFO_L, tmp, pbrd->chs);
+                
+                offset = POWER_AC_CUR_INFO_L;
+                r = read_reg(h, pbrd->addr, offset, tmp, pbrd->chs*12);
                 if (r<0) {
-                    LOGE("get_board, addr:%d offset:%d r=%d\n", pbrd->addr, offset, r);
+                    LOGE("read_reg failed, addr:%d reg:0x%04x/%d cnt:%d\n", pbrd->addr, offset, offset, pbrd->chs*12);
                     break;
                 }
                 
@@ -363,10 +396,11 @@ static int board_read(power_handle_t *h, board_data_t *pbrd)
                     val = (tmp[11 + idx] << 16) | tmp[10 + idx];
                     pwr->factor = val / 1000.0;
                 }
-                
-                r = read_reg(h, pbrd->addr, POWER_AC_STAT_INFO_L, tmp, pbrd->chs);
+
+                offset = POWER_AC_STAT_INFO_L;
+                r = read_reg(h, pbrd->addr, offset, tmp, pbrd->chs);
                 if (r<0) {
-                    LOGE("get_board, addr:%d offset:%d r=%d\n", pbrd->addr, offset, r);
+                    LOGE("read_reg failed, addr:%d reg:0x%04x/%d cnt:%d\n", pbrd->addr, offset, offset, pbrd->chs);
                     break;
                 }
  
@@ -386,11 +420,12 @@ static int board_read(power_handle_t *h, board_data_t *pbrd)
             case DCPDU_TYPE:
             {
                 uint32_t flag;
-                offset = POWER_DC_OUT_INFO + 16;
                 uint16_t *ptmp = tmp + 32;
+                
+                offset = POWER_DC_OUT_INFO + 16;
                 r = read_reg(h, pbrd->addr, offset, ptmp, 32);
                 if (r<0) {
-                    LOGE("get_board, addr:%d offset:%d r=%d\n", pbrd->addr, offset, r);
+                    LOGE("read_reg failed, addr:%d reg:0x%04x/%d cnt:%d\n", pbrd->addr, offset, offset, 32);
                     break;
                 }
                 
@@ -417,7 +452,7 @@ static int board_read(power_handle_t *h, board_data_t *pbrd)
                 offset = POWER_DC_STAT_INFO;
                 r = read_reg(h, pbrd->addr, offset, tmp, 2);
                 if (r<0) {
-                    LOGE("get_board, addr:%d offset:%d r=%d\n", pbrd->addr, offset, r);
+                    LOGE("read_reg failed, addr:%d reg:0x%04x/%d cnt:%d\n", pbrd->addr, offset, offset, 2);
                     break;
                 }
                 
@@ -430,7 +465,7 @@ static int board_read(power_handle_t *h, board_data_t *pbrd)
                 offset = POWER_DC_WARNING;
                 r = read_reg(h, pbrd->addr, offset, tmp, 16);
                 if (r<0) {
-                    LOGE("get_board, addr:%d offset:%d r=%d\n", pbrd->addr, offset, r);
+                    LOGE("read_reg failed, addr:%d reg:0x%04x/%d cnt:%d\n", pbrd->addr, offset, offset, 16);
                     break;
                 }
                 
@@ -452,7 +487,7 @@ static int board_read(power_handle_t *h, board_data_t *pbrd)
                 offset = POWER_AC3_OUT_INFO;
                 r = read_reg(h, pbrd->addr, offset, tmp, 80);
                 if (r < 0) {
-                    LOGE("get_board, addr:%d offset:%d r=%d\n", pbrd->addr, offset, r);
+                    LOGE("read_reg failed, addr:%d reg:0x%04x/%d cnt:%d\n", pbrd->addr, offset, offset, 80);
                     break;
                 }
                 
@@ -460,7 +495,7 @@ static int board_read(power_handle_t *h, board_data_t *pbrd)
                 uint16_t* ptmp=tmp+80;
                 r = read_reg(h, pbrd->addr, offset, ptmp, 64);
                 if (r < 0) {
-                    LOGE("get_board, addr:%d offset:%d r=%d\n", pbrd->addr, offset, r);
+                    LOGE("read_reg failed, addr:%d reg:0x%04x/%d cnt:%d\n", pbrd->addr, offset, offset, 64);
                     break;
                 }
                 
@@ -503,7 +538,7 @@ static int board_read(power_handle_t *h, board_data_t *pbrd)
                 offset = POWER_AC3_OUT_ENABLE;
                 r = read_reg(h, pbrd->addr, offset, tmp, 20);
                 if (r < 0) {
-                    LOGE("get_board, addr:%d offset:%d r=%d\n", pbrd->addr, offset, r);
+                    LOGE("read_reg failed, addr:%d reg:0x%04x/%d cnt:%d\n", pbrd->addr, offset, offset, 20);
                     break;
                 }
                 for (i=0; i<pbrd->chs; i++) {
@@ -516,7 +551,7 @@ static int board_read(power_handle_t *h, board_data_t *pbrd)
                 offset = POWER_AC3_OUT_ERROR;
                 r = read_reg(h, pbrd->addr, offset, tmp, 18);
                 if (r < 0) {
-                    LOGE("get_board, addr:%d offset:%d r=%d\n", pbrd->addr, offset, r);
+                    LOGE("read_reg failed, addr:%d reg:0x%04x/%d cnt:%d\n", pbrd->addr, offset, offset, 18);
                     break;
                 }
                 for (i=0; i<pbrd->chs; i++) {
@@ -532,7 +567,7 @@ static int board_read(power_handle_t *h, board_data_t *pbrd)
                 offset = POWER_AC3_ALARM_MISSING_PH;
                 r = read_reg(h, pbrd->addr, offset, tmp, pbrd->chs);
                 if (r < 0) {
-                    LOGE("get_board, addr:%d offset:%d r=%d\n", pbrd->addr, offset, r);
+                    LOGE("read_reg failed, addr:%d reg:0x%04x/%d cnt:%d\n", pbrd->addr, offset, offset, pbrd->chs);
                     break;
                 }
                 
@@ -559,10 +594,33 @@ static int board_read(power_handle_t *h, board_data_t *pbrd)
             threshold_proc(h, pbrd);
         }
     }
-    lock_d_release(h->lck);
+    lock_off(h->lck);
     
     return r;
 }
+static int power_copy(power_handle_t *h)
+{
+    int i,r=-1;
+    power_data_t *pd=&h->pdat;
+    
+    if(h->chs>0) {
+        if(!pd->pch || pd->chs!=h->chs) {
+            if(pd->pch) free(pd->pch);
+            pd->chs = 0;
+            pd->pch = malloc(sizeof(power_ch_t)*h->chs);
+        }
+        
+        if(pd->pch) {
+            pd->chs = h->chs;
+            for(i=0; i<pd->chs; i++) {
+                pd->pch[i] = *h->pch[i];
+            }
+        }
+    }
+    pd->ttl = h->ttl;
+    
+    return 0;
+}
 static int board_query(power_handle_t *h)
 {
     int i,r;
@@ -571,22 +629,24 @@ static int board_query(power_handle_t *h)
         r = board_read(h, h->pbrd[i]);
     }
     total_proc(h);
+    power_copy(h);
     
     return r;
 }
-static void *power_thread(void *arg)
+static void power_thread(void *arg)
 {
     int r;
     board_data_t *pbrd=NULL;
     thread_handle_t *th=(thread_handle_t*)arg;
-    power_handle_t *h=(power_handle_t*)th->arg;;
+    power_handle_t *h=(power_handle_t*)th->attr->arg;;
     
-    power_scan();
     while(th->quit==0) {
+        LOGD("___ board_query 111\n");
         board_query(h);
+        LOGD("___ board_query 222\n");
         sleep(1);
+        LOGD("___ board_query 333\n");
     }
-    pthread_exit(NULL);
 }
 
 
@@ -609,7 +669,7 @@ int power_init(void)
     };
     
     memset(h, 0, sizeof(power_handle_t));
-    h->lck = lock_d_init();
+    h->lck = lock_init();
     h->mb = mb_init(&para);
     if(!h->mb) {
         return -1;
@@ -617,6 +677,9 @@ int power_init(void)
     h->cur_addr = 0;
     h->brd_max = BRD_NUM;
     h->prod = &paras_get()->prod;
+    
+    power_scan();
+    power_set_all_sw(1);
     thread_start(THREAD_ID_POWER, power_thread, h);
     
     return 0;
@@ -627,40 +690,44 @@ int power_deinit(void)
 {
     power_handle_t *h=&pwrHandle;
     
-    lock_d_deinit(h->lck);
+    lock_deinit(h->lck);
     mb_deinit(h->mb);
     
     return 0;
 }
 
-
-int power_get_ch(int ch, power_ch_t *pch)
+static int get_ch(power_handle_t *h, uint8_t ch, power_ch_t *pch)
 {
-    power_handle_t *h=&pwrHandle;
-    
-    lock_d_hold(h->lck);
     if(!pch || !h->pch || !h->chs || !h->pch[ch]) {
-        lock_d_release(h->lck);
         return -1;
     }
     *pch = *h->pch[ch];
-    lock_d_release(h->lck);
-    
     return 0;
 }
+int power_get_ch(uint8_t ch, power_ch_t *pch)
+{
+    int r;
+    power_handle_t *h=&pwrHandle;
+    
+    lock_on(h->lck);
+    r = get_ch(h, ch, pch);
+    lock_off(h->lck);
+    
+    return r;
+}
 
 
 int power_get_board(board_data_t *pb)
 {
     power_handle_t *h=&pwrHandle;
     
-    lock_d_hold(h->lck);
+    lock_on(h->lck);
     if(!pb || !h->pch || !h->cnt || !h->pbrd[pb->addr]) {
-        lock_d_release(h->lck);
+        lock_off(h->lck);
         return -1;
     }
     *pb = *h->pbrd[pb->addr];
-    lock_d_release(h->lck);
+    lock_off(h->lck);
     
     return 0;
 }
@@ -670,18 +737,18 @@ int power_set(int ch, power_ch_t *pch)
 {
     power_handle_t *h=&pwrHandle;
     
-    lock_d_hold(h->lck);
+    lock_on(h->lck);
     if(!pch || !h->pch || !h->chs || !h->pch[pch->info.ch]) {
-        lock_d_release(h->lck);
+        lock_off(h->lck);
         return -1;
     }
     *h->pch[pch->info.ch] = *pch;
-    lock_d_release(h->lck);
+    lock_off(h->lck);
     
     return 0;
 }
 
-static int pch_map(power_handle_t *h, int chs)
+static int power_map(power_handle_t *h, int chs)
 {
     int i,j,r,idx=0;
     board_data_t *pbrd=NULL;
@@ -706,22 +773,46 @@ static int pch_map(power_handle_t *h, int chs)
     return 0;
 }
 
+static int power_clear(power_handle_t *h)
+{
+    int i,j;
+    for(i=0; i<=h->brd_max; i++) {
+        if(h->pbrd[i]) {
+            for(j=0; j<h->pbrd[i]->chs; j++) {
+                if(h->pbrd[i]->pch) {
+                    free(h->pbrd[i]->pch);
+                    h->pbrd[i]->pch = NULL;
+                }
+                h->pbrd[i]->chs = 0;
+            }
+            free(h->pbrd[i]);
+            h->pbrd[i] = NULL;
+        }
+    }
+    memset(h->key, 0, sizeof(h->key));
+    h->cnt = 0;
+    h->cur_addr = 0;
+    
+    return 0;
+}
 int power_scan(void)
 {
-    int r,i,j,chs=0;
+    int r,i,j,total_chs=0;
     int ch_idx=0,brd_idx=0;
-    power_handle_t *h=&pwrHandle;
+    power_ch_t *pch=NULL;
     board_key_t *pkey=NULL;
+    board_data_t *pbrd=NULL;
+    power_handle_t *h=&pwrHandle;
     uint16_t times,nGroups=h->prod->ch_delay;
     
-    power_clear();
+    lock_on(h->lck);
+    power_clear(h);
     
-    lock_d_hold(h->lck);
-    h->cur_addr = 0;
     for(i=1; i<=h->brd_max; i++) {
         r = get_key(h, i, &h->key[i]);
         if(r==0) {
             LOGD("___ power_scan addr %d ok, type: %d, chs: %d\n", i, h->key[i].type, h->key[i].chs);
+            h->cnt++;
         }
         else {
             LOGE("___ power_scan addr %d failed\n", i);
@@ -731,73 +822,55 @@ int power_scan(void)
     for(i=1; i<h->brd_max; i++) {
         pkey = &h->key[i];
         if(pkey->chs>0) {
-            h->pbrd[i] = (board_data_t*)calloc(1, sizeof(board_data_t));
-            if(h->pbrd[i]) {
-                h->pbrd[i]->type = pkey->type;
-                h->pbrd[i]->chs  = pkey->chs;
-                h->pbrd[i]->addr = i;
-                h->pbrd[i]->ch0 = ch_idx;
-                h->pbrd[i]->pch = (power_ch_t*)calloc(1, sizeof(power_ch_t)*pkey->chs);
-                if(h->pbrd[i]->pch) {
-                    times = (ch_idx+1)%nGroups?(ch_idx+1):nGroups;
-                    for(j=0; j<pkey->chs; j++) {
-                        h->pbrd[i]->pch[j].info.addr = i;
-                        h->pbrd[i]->pch[j].info.sch  = j;                    //序号从0开始
-                        h->pbrd[i]->pch[j].info.type = pkey->type;
-                        h->pbrd[i]->pch[j].info.start_delay = 1000*times;
-                        h->pbrd[i]->pch[j].info.stop_delay  = 1000*times;
-                        
-                        if(h->prod->pwr_type==PDU_AC_I3O3) {
-                            h->pbrd[i]->pch[j].info.ch  = ch_idx+j/3;       //序号程序从0开始
-                            h->pbrd[i]->pch[j].info.ph_id = j%3;
-                        }
-                        else {
-                            h->pbrd[i]->pch[j].info.ch  = ch_idx+j;         //序号程序从0开始
-                            h->pbrd[i]->pch[j].info.ph_id = 0;
-                        }
-                    }
-                    
-                    if(h->prod->pwr_type==PDU_AC_I3O3) {
-                        ch_idx += pkey->chs/3;
-                    }
-                    else {
-                        ch_idx += pkey->chs;
-                    }
-                }
-                brd_idx++;
+            pbrd = (board_data_t*)calloc(1, sizeof(board_data_t));
+            if(!pbrd) {
+                LOGE("___ power_scan, calloc pbrd %d failed\n", i);
+                return -1;
             }
-            chs += pkey->chs;
-        }
-    }
-    pch_map(h, chs);
-    lock_d_release(h->lck);
-    
-    return 0;
-}
-
-
-int power_clear(void)
-{
-    int i,j;
-    power_handle_t *h=&pwrHandle;
-    
-    lock_d_hold(h->lck);
-    for(i=0; i<=h->brd_max; i++) {
-        if(h->pbrd[i]) {
-            for(j=0; j<h->pbrd[i]->chs; j++) {
-                if(h->pbrd[i]->pch) {
-                    free(h->pbrd[i]->pch);
-                    h->pbrd[i]->pch = NULL;
+            
+            pbrd->type = pkey->type;
+            pbrd->chs  = pkey->chs;
+            pbrd->addr = i;
+            pbrd->ch0 = ch_idx;
+            pch = (power_ch_t*)calloc(1, sizeof(power_ch_t)*pkey->chs);
+            if(!pch) {
+                LOGE("___ power_scan, calloc pch failed\n");
+                return -1;
+            }
+            
+            times = (ch_idx+1)%nGroups?(ch_idx+1):nGroups;
+            for(j=0; j<pkey->chs; j++) {
+                pch[j].info.addr = i;
+                pch[j].info.sch  = j;                    //序号从0开始
+                pch[j].info.type = pkey->type;
+                pch[j].info.start_delay = 1000*times;
+                pch[j].info.stop_delay  = 1000*times;
+                
+                if(h->prod->pwr_type==PDU_AC_I3O3) {
+                    pch[j].info.ch  = ch_idx+j/3;       //序号程序从0开始
+                    pch[j].info.ph_id = j%3;
+                }
+                else {
+                    pch[j].info.ch  = ch_idx+j;         //序号程序从0开始
+                    pch[j].info.ph_id = 0;
                 }
-                h->pbrd[i]->chs = 0;
             }
-            free(h->pbrd[i]);
-            h->pbrd[i] = NULL;
+            
+            if(h->prod->pwr_type==PDU_AC_I3O3) {
+                ch_idx += pkey->chs/3;
+            }
+            else {
+                ch_idx += pkey->chs;
+            }
+            brd_idx++;
+            
+            pbrd->pch = pch;
+            h->pbrd[i] = pbrd;
+            total_chs += pkey->chs;
         }
     }
-    memset(h->key, 0, sizeof(h->key));
-    h->cnt = 0;
-    lock_d_release(h->lck);
+    power_map(h, total_chs);
+    lock_off(h->lck);
     
     return 0;
 }
@@ -810,7 +883,7 @@ int power_reset(void)
     power_handle_t *h=&pwrHandle;
     board_data_t *pbrd=NULL;
     
-    lock_d_hold(h->lck);
+    lock_on(h->lck);
     for(i=0; i<=h->brd_max; i++) {
         pbrd = h->pbrd[i];
         if(pbrd) {
@@ -885,18 +958,26 @@ int power_reset(void)
             }
         }
     }
-    lock_d_release(h->lck);
+    lock_off(h->lck);
     
     return r;
 }
 
 
-int power_set_sw(power_ch_t *pch)
+int power_set_ch_sw(uint8_t ch, uint8_t on)
 {
     int r;
-    power_ch_t pc;
+    power_ch_t pc,*pch;
     power_handle_t *h=&pwrHandle;
-    uint16_t offset,tmp[2]={0},st=pch->power[0].status;
+    uint16_t offset,tmp[2]={0},st=on;
+    
+    lock_on(h->lck);
+    r = get_ch(h, ch, &pc);
+    if(r) {
+        lock_off(h->lck);
+        return -1;
+    }
+    pch = &pc;
     
     if (pch->thr.v_upper.en == 1)
         st |= ENABLE_AC3_V_UP;
@@ -909,13 +990,12 @@ int power_set_sw(power_ch_t *pch)
     if (pch->thr.w_upper.en == 1)
         st |= ENABLE_AC3_W_UP;
     
-    lock_d_hold(h->lck);
     switch(pch->info.type) {
         case AC_SINGLE_S_TYPE:
         case AC_SINGLE_B_TYPE:
         {
             offset = POWER_AC_CH_STAT_L + pch->info.ch;
-            tmp[0] = pch->power[0].status; tmp[1] = 0;
+            tmp[0] = st; tmp[1] = 0;
             r = write_reg(h, pc.info.addr, offset, tmp, 2);
         }
         break;
@@ -949,11 +1029,49 @@ int power_set_sw(power_ch_t *pch)
         }
         break;
     }
-    lock_d_release(h->lck);
+    lock_off(h->lck);
     
     return r;
 }
 
+
+static int set_board_sw(board_data_t *pbrd, uint8_t on)
+{
+    int i,r;
+    power_ch_t pc;
+    power_handle_t *h=&pwrHandle;
+    
+    if(!pbrd) {
+        return -1;
+    }
+    
+    for(i=0; i<pbrd->chs; i++) {
+        r = get_ch(h, i, &pc);
+        if(r==0) {
+            power_set_ch_sw(pc.info.ch, on);
+        }
+    }
+    
+    return 0;
+}
+
+
+int power_set_all_sw(uint8_t on)
+{
+    int i,r;
+    
+    power_handle_t *h=&pwrHandle;
+    
+    for(i=0; i<h->brd_max; i++) {
+        set_board_sw(h->pbrd[i], on);
+    }
+    
+    return 0;
+}
+
+
+
+
 int power_set_alarm(power_ch_t *pch)
 {
     int r=0;
@@ -961,7 +1079,7 @@ int power_set_alarm(power_ch_t *pch)
     uint16_t nStatus = 0;
     power_handle_t *h=&pwrHandle;
     
-    lock_d_hold(h->lck);
+    lock_on(h->lck);
     switch(pch->info.type) {
         case AC_SINGLE_S_TYPE:
         case AC_SINGLE_B_TYPE:
@@ -1009,7 +1127,7 @@ int power_set_alarm(power_ch_t *pch)
         if(pch->thr.w_upper.act==1) nStatus |= BIT(4);
         r = write_reg(h, pch->info.addr, offset, &nStatus, 1);
     }
-    lock_d_release(h->lck);
+    lock_off(h->lck);
     
     return r;
 }
@@ -1021,7 +1139,7 @@ int power_set_threshold(power_ch_t *pch)
     uint16_t offset;
     power_handle_t *h=&pwrHandle;
     
-    lock_d_hold(h->lck);
+    lock_on(h->lck);
     switch(pch->info.type) {
         case AC_SINGLE_S_TYPE:
         case AC_SINGLE_B_TYPE:
@@ -1186,7 +1304,7 @@ int power_set_threshold(power_ch_t *pch)
         r = -1;
         break;
     }
-    lock_d_release(h->lck);
+    lock_off(h->lck);
     
     return r;
 }
@@ -1198,7 +1316,7 @@ int power_set_start_delay(power_ch_t *pch)
     uint16_t tmp[2],reg,offset;
     power_handle_t *h=&pwrHandle;
     
-    lock_d_hold(h->lck);
+    lock_on(h->lck);
     switch(pch->info.type) {
         case AC_SINGLE_S_TYPE:
         case AC_SINGLE_B_TYPE:
@@ -1247,7 +1365,7 @@ int power_set_start_delay(power_ch_t *pch)
         default:
         r = -1;
     }
-    lock_d_release(h->lck);
+    lock_off(h->lck);
     
     return r;
 }
@@ -1257,7 +1375,7 @@ int power_set_stop_delay(power_ch_t *pch)
     uint16_t tmp[2],reg,offset;
     power_handle_t *h=&pwrHandle;
     
-    lock_d_hold(h->lck);
+    lock_off(h->lck);
     switch(pch->info.type) {
         case AC_SINGLE_S_TYPE:
         case AC_SINGLE_B_TYPE:
@@ -1305,44 +1423,17 @@ int power_set_stop_delay(power_ch_t *pch)
         r = -1;
         break;
     }
-    lock_d_release(h->lck);
+    lock_on(h->lck);
     
     return r;
 }
 
 
-int power_data_copy(power_data_t *pd, int flag)
+power_data_t power_data_get(void)
 {
-    int i,r=-1;
     power_handle_t *h=&pwrHandle;
     
-    lock_d_hold(h->lck);
-    if(flag&1) {
-        if(h->chs>0) {
-            if(!pd->pch || pd->chs!=h->chs) {
-                if(pd->pch) free(pd->pch);
-                pd->chs = 0;
-                pd->pch = malloc(sizeof(power_ch_t)*h->chs);
-            }
-            
-            if(pd->pch) {
-                pd->chs = h->chs;
-                for(i=0; i<pd->chs; i++) {
-                    pd->pch[i] = *h->pch[i];
-                }
-            }
-        }
-    }
-    
-    if(flag&2) {
-        pd->ttl = h->ttl;
-    }
-    lock_d_release(h->lck);
-    
-    return 0;
+    return h->pdat;
 }
 
 
-
-
-

+ 4 - 5
f407/applications/power.h

@@ -157,20 +157,19 @@ typedef struct {
 
 int power_init(void);
 int power_deinit(void);
-int power_clear(void);
 
 int power_scan(void);
-int power_get_ch(int ch, power_ch_t *pch);
+int power_get_ch(uint8_t ch, power_ch_t *pch);
 int power_get_board(board_data_t *pb);
 
-int power_set_sw(power_ch_t *pch);
+int power_set_ch_sw(uint8_t ch, uint8_t on);
+int power_set_all_sw(uint8_t on);
 int power_set_alarm(power_ch_t *pch);
 int power_set_threshold(power_ch_t *pch);
 int power_set_start_delay(power_ch_t *pch);
 int power_set_stop_delay(power_ch_t *pch);
 int power_reset(void);
 
-int power_data_copy(power_data_t *pd, int flag);
-
+power_data_t power_data_get(void);
 #endif
 

+ 2 - 9
f407/applications/rtconfig.h

@@ -28,7 +28,7 @@
 
 
 // kservice optimization
-#define RT_USING_DEBUG
+//#define RT_USING_DEBUG
 #define RT_DEBUGING_COLOR
 #define RT_DEBUGING_CONTEXT
 
@@ -75,7 +75,7 @@
 //RT-Thread Components
 #define RT_USING_COMPONENTS_INIT
 #define RT_USING_USER_MAIN
-#define RT_MAIN_THREAD_STACK_SIZE 2048
+#define RT_MAIN_THREAD_STACK_SIZE (1024*4)
 #define RT_MAIN_THREAD_PRIORITY 10
 
 #define RT_USING_MSH
@@ -230,13 +230,6 @@
 #define RT_USING_POSIX_TIMER
 #endif
 
-#define PKG_USING_MONGOOSE
-#define PKG_MONGOOSE_ENABLE_HTTP_WEBSOCKET
-#define PKG_MONGOOSE_ENABLE_FILESYSTEM
-#define PKG_MONGOOSE_ENABLE_HTTP_STREAMING_MULTIPART
-#define PKG_MONGOOSE_ENABLE_MQTT
-#define PKG_USING_MONGOOSE_V607
-
 
 #define PKG_USING_SQLITE
 #define PKG_SQLITE_SQL_MAX_LEN 1024

+ 1 - 0
f407/applications/sys.c

@@ -6,6 +6,7 @@
 #include <limits.h>
 #include "log.h"
 #include "sys.h"
+#include "lock.h"
 #include "paras.h"
 #include "cfg.h"
 #include "fs.h"

+ 44 - 40
f407/applications/thread.c

@@ -1,29 +1,41 @@
 #include "thread.h"
 
+
+
 static thread_attr_t thdAttrs[THREAD_ID_MAX]={
     //name          fn              arg             stacksize       prio
-    {"ws",          NULL,           NULL,           2*KB,           1},
-    {"web",         NULL,           NULL,           4*KB,           1},
-    {"snmp",        NULL,           NULL,           2*KB,           1},
-    {"power",       NULL,           NULL,           2*KB,           1},
-    {"polling",     NULL,           NULL,           2*KB,           1},
-    {"mqtt",        NULL,           NULL,           2*KB,           1},
-    {"mail",        NULL,           NULL,           2*KB,           1},
-    {"ui",          NULL,           NULL,           2*KB,           1},
+    {"web",         NULL,           NULL,           8*KB,           20},
+    {"snmp",        NULL,           NULL,           2*KB,           20},
+    {"power",       NULL,           NULL,           2*KB,           20},
+    {"polling",     NULL,           NULL,           2*KB,           20},
+    {"mqtt",        NULL,           NULL,           2*KB,           20},
+    {"mail",        NULL,           NULL,           2*KB,           20},
+    {"ui",          NULL,           NULL,           2*KB,           20},
 };
 static thread_handle_t thdHandles[THREAD_ID_MAX]={0};
+static void* thread_fn(void *arg)
+{
+    thread_handle_t *h=(thread_handle_t*)arg;
+    
+    h->running = 1;
+    if(h->attr->fn) {
+        h->attr->fn(h);
+    }
+    h->running = 0;
+    h->quit = 0;
+    pthread_exit(NULL);
+}
 
-
-int thread_start(int id, thread_fn fn, void *arg)
+int thread_start(int id, thread_fn_t fn, void *arg)
 {
     if(id<0 || id>=THREAD_ID_MAX || !fn) {
         return -1;
     }
-    thread_attr_t *attr=&thdAttrs[id];
+    thread_attr_t attr=thdAttrs[id];
 
-    attr->fn = fn;
-    attr->arg = arg;
-    return thread_startEx(id, attr->name, attr->fn, attr->arg, attr->stksz, attr->prio);
+    attr.fn = fn;
+    attr.arg = arg;
+    return thread_startEx(id, &attr);
 }
 
 
@@ -37,7 +49,7 @@ int thread_start2(int id)
         return -1;
     }
 
-    return thread_startEx(id, attr->name, attr->fn, attr->arg, attr->stksz, attr->prio);
+    return thread_startEx(id, attr);
 }
 
 
@@ -52,17 +64,17 @@ int thread_restart(int id)
     }
 
     thread_stop(id);
-    return thread_startEx(id, attr->name, attr->fn, attr->arg, attr->stksz, attr->prio);
+    return thread_startEx(id, attr);
 }
 
 
-int thread_startEx(int id, const char *name, thread_fn fn, void *arg, int stksz, int prio)
+int thread_startEx(int id, thread_attr_t *attr)
 {
-    int r;
-    pthread_attr_t attr;
+    int r=-1;
     thread_handle_t *h=NULL;
+    pthread_attr_t attr2;
 
-    if(id<0 || id>=THREAD_ID_MAX || !fn) {
+    if(id<0 || id>=THREAD_ID_MAX || !attr || !attr->fn) {
         return -1;
     }
     h = &thdHandles[id];
@@ -71,35 +83,32 @@ int thread_startEx(int id, const char *name, thread_fn fn, void *arg, int stksz,
         return -1;
     }
 
-    h->name = name;
-    h->arg  = arg;
     h->quit = 0;
-    r = pthread_attr_init(&attr);
+    h->attr = NULL;
+    r = pthread_attr_init(&attr2);
     if(r) {
-        printf("____ thread %d attr init failed\n", id);
+        LOGE("____ thread %d attr init failed\n", id);
         return -1;
     }
 
-#if 1
-    r = pthread_attr_setstacksize(&attr, stksz);
+    r = pthread_attr_setstacksize(&attr2, attr->stksz);
     if(r) {
-        printf("____ thread %d attr setstacksize %d failed\n", id, stksz);
+        LOGE("____ thread %d attr setstacksize %d failed\n", id, attr->stksz);
     }
-#endif
     
-    r = pthread_create(&h->tid, &attr, fn, h);
+    r = pthread_create(&h->tid, &attr2, thread_fn, h);
     if(r==0) {
         h->running = 1;
+        thdAttrs[id] = *attr;
+        h->attr = &thdAttrs[id];
 #if 0
-        r = pthread_setschedprio(h->tid, prio);
+        r = pthread_setschedprio(h->tid, attr->prio);
         if(r) {
-            printf("____ set thread prio %d failed\n", prio);
+            LOGE("____ set thread prio %d failed\n", prio);
         }
 #endif
     }
-
-
-    pthread_attr_destroy(&attr);
+    pthread_attr_destroy(&attr2);
 
     return r;
 }
@@ -112,12 +121,8 @@ int thread_stop(int id)
     thread_handle_t *h=&thdHandles[id];
 
     h->quit = 1;
-    //pthread_detach();
     pthread_join(h->tid, NULL);
     h->tid = 0;
-    h->running = 0;
-    h->arg = NULL;
-    h->fn  = NULL;
     
     return 0;
 }
@@ -146,7 +151,7 @@ int thread_is_running(int id)
 }
 
 
-int thread_start_simp(thread_fn fn, void *arg, int stksz)
+int thread_start_simp(thread_fn_t fn, void *arg, int stksz)
 {
     int r;
     pthread_t tid;
@@ -157,7 +162,6 @@ int thread_start_simp(thread_fn fn, void *arg, int stksz)
     
     r = pthread_create(&tid, &attr, fn, arg);
     pthread_attr_destroy(&attr);
-
     return r;
 }
 

+ 8 - 12
f407/applications/thread.h

@@ -3,6 +3,7 @@
 
 #include <pthread.h>
 #include <stdio.h>
+#include "log.h"
 
 #ifdef __cplusplus
 extern "C" {
@@ -13,8 +14,7 @@ extern "C" {
 
 
 enum {
-    THREAD_ID_WS=0,
-    THREAD_ID_WEB,
+    THREAD_ID_WEB=0,
     THREAD_ID_SNMP,
     THREAD_ID_POWER,
     THREAD_ID_POLL,
@@ -25,37 +25,33 @@ enum {
     THREAD_ID_MAX
 };
 
-typedef void *(*thread_fn)(void *arg);
+typedef void (*thread_fn_t)(void *arg);
 
 
 typedef struct {
     const char *name;
-    thread_fn  fn;
+    thread_fn_t  fn;
     void       *arg;
     int        stksz;
     int        prio;
 }thread_attr_t;
 
 typedef struct {
-    const char *name;
     pthread_t  tid;
     int        quit;
     int        running;
-    void       *arg;
-    thread_fn  fn;
-    void       *stk;
+    thread_attr_t *attr;
 }thread_handle_t;
 
-
-int thread_start(int id, thread_fn fn, void *arg);
+int thread_start(int id, thread_fn_t fn, void *arg);
 int thread_start2(int id);
 int thread_restart(int id);
-int thread_startEx(int id, const char *name, thread_fn fn, void *arg, int stksz, int prio);
+int thread_startEx(int id, thread_attr_t *attr);
 int thread_stop(int id);
 int thread_stop_all(void);
 
 int thread_is_running(int id);
-int thread_start_simp(thread_fn fn, void *arg, int stksz);
+int thread_start_simp(thread_fn_t fn, void *arg, int stksz);
 int thread_print_stacksize(void);
 
 #ifdef __cplusplus

+ 38 - 42
f407/applications/ui/lcd.c

@@ -2,15 +2,9 @@
 #include <stdlib.h>
 #include <string.h>
 #include <unistd.h>
-#include "gpio.h"
 #include "lcd.h"
 #include "log.h"
 
-#define CS_GPIO      GET_PIN(B, 12)
-#define BK_GPIO      GET_PIN(D, 9)     //PD9
-#define DC_GPIO      GET_PIN(D, 8)     //PD8
-#define RST_GPIO     GET_PIN(B, 14)    //PB14
-
 
 #define BIT(x)              (1<<x)
 #define SWAP16(a)           ((uint16_t)((a<<8)|(a>>8)))
@@ -28,37 +22,12 @@ typedef struct {
 
 static lcd_handle_t lcdHandle={0};
 
+extern int st7789_init(lcd_handle_t *h);
+extern int st7789_deinit(lcd_handle_t *h);
+extern void st7789_refresh(lcd_handle_t *hd, uint16_t x, uint16_t y, uint16_t w, uint16_t h, void *data, uint32_t len);
+extern void st7789_rotate(lcd_handle_t *h, int rotate);
 
 
-static int lcd_reset(void)
-{
-    gpio_set(RST_GPIO, 0);
-    usleep(100*1000);
-    gpio_set(RST_GPIO, 1);
-    
-    return 0;
-}
-
-int lcd_hw_init(lcd_handle_t *h, uint32_t freq)
-{
-    
-
-    return 0;
-}
-
-static int lcd_hw_deinit(lcd_handle_t *h)
-{
-    gpio_deinit(CS_GPIO);
-    gpio_deinit(BK_GPIO);
-    gpio_deinit(DC_GPIO);
-    gpio_deinit(RST_GPIO);
-    
-    free(h->buf);
-    //close(h->fd);
-    
-    return 0;
-}
-
 static inline int set_point(lcd_handle_t *h, int x, int y, uint32_t data)
 {
     int pos,bit;
@@ -76,9 +45,11 @@ static inline int set_point(lcd_handle_t *h, int x, int y, uint32_t data)
     else {
         h->buf[pos*h->width+x] &= ~BIT(bit);        		/* set 0 */
     }
-	
+    
 	return 0;
 }
+
+
 static int get_color_bits(int color)
 {
     if(color==COLOR_WB) {
@@ -104,18 +75,16 @@ void lcd_init(int width, int height, uint32_t color)
     h->color  = color;
     h->rotate = 0;
     
-    gpio_init(BK_GPIO, GPIO_OUT, 0);
-    gpio_init(DC_GPIO, GPIO_OUT, 0);
-    gpio_init(RST_GPIO, GPIO_OUT, 0);
-    lcd_reset();
+    st7789_init(h);
     
+    //lcd_draw_string(0, 0, LCD_WIDTH, LCD_HEIGHT/10, "SmartPDU", FONT_12, COLOR_WHITE, COLOR_BLACK, HORIZONTAL_CENTER, VERTICAL_CENTER);
     //lcd_hw_init(h);
 }
 
 void lcd_deinit(void)
 {
     lcd_handle_t *h=&lcdHandle;
-    lcd_hw_deinit(h);
+    //lcd_hw_deinit(h);
 }
 
 
@@ -282,6 +251,7 @@ int lcd_draw_char(lcd_handle_t *hd, int x, int y, int w, int h, uint8_t *c, int
         y = y0;
     }
     
+#if 0
     for(i=0; i<fdata.dlen; i++)  {
         tmp = fdata.data[i];
         for(j=0; j<8; j++)  {
@@ -303,6 +273,32 @@ int lcd_draw_char(lcd_handle_t *hd, int x, int y, int w, int h, uint8_t *c, int
             }
         }
     }
+#else
+    for(i=0; i<fdata.dlen; i++)  {
+        tmp = fdata.data[i];
+        for(j=0; j<8; j++)  {
+            if((x<x1 && x<hd->width) && (y<y1 && y<hd->height)) 
+            {
+                int x1=x-x0,y1=y-y0;
+                
+                if(tmp&0x01) {
+                    hd->buf[y1*fdata.width+x1] = color;
+                }
+                else {
+                    hd->buf[y1*fdata.width+x1] = bgcolor;
+                }
+            }
+            tmp >>= 1;
+            y++;
+
+            if((y-y0)>=fdata.height) {
+                y=y0; x++;
+                break;
+            }
+        }
+    }
+    st7789_refresh(hd, x0, y0, fdata.width, fdata.height, hd->buf, fdata.width*fdata.height*2);
+#endif
 
     return fdata.width;
 }
@@ -315,7 +311,7 @@ void lcd_draw_string(int x, int y, int w, int h, char *str, int font, uint32_t c
     uint8_t *pstr=(uint8_t*)str;
     lcd_handle_t *h2=&lcdHandle;
 
-   sw = font_width_str(font, pstr);
+    sw = font_width_str(font, pstr);
     if(sw>w) {
         sw = w;
     }

+ 36 - 23
f407/applications/ui/lcd.h

@@ -3,38 +3,51 @@
 
 #include <rtthread.h>
 #include <rtdevice.h>
-#include "drivers/spi.h"
+#include "gpio.h"
+#include "drv_spi.h"
 #include "font.h"
 
 
 enum {
-    COLOR_WHITE=0,
-    COLOR_BLACK,
-    COLOR_BLUE,
-    COLOR_BRED,
-    COLOR_GRED,
-    COLOR_GBLUE,
-    COLOR_RED,
-    COLOR_MAGENTA,
-    COLOR_GREEN,
-    COLOR_CYAN,
-    COLOR_YELLOW,
-    COLOR_BROWN,
-    COLOR_BRRED,
-    COLOR_GRAY,
+    COLOR_ID_WHITE=0,
+    COLOR_ID_BLACK,
+    COLOR_ID_BLUE,
+    COLOR_ID_BRED,
+    COLOR_ID_GRED,
+    COLOR_ID_GBLUE,
+    COLOR_ID_RED,
+    COLOR_ID_MAGENTA,
+    COLOR_ID_GREEN,
+    COLOR_ID_CYAN,
+    COLOR_ID_YELLOW,
+    COLOR_ID_BROWN,
+    COLOR_ID_BRRED,
+    COLOR_ID_GRAY,
     
-    COLOR_MAX,
+    COLOR_ID_MAX,
 };
 
-#define LCD_COLOR   COLOR_WB
+#define CS_PIN      GET_PIN(B, 12)
+#define BK_PIN      GET_PIN(D, 9)     //PD9
+#define DC_PIN      GET_PIN(D, 8)     //PD8
+#define RST_PIN     GET_PIN(B, 14)    //PB14
+
+
+
+#define LCD_COLOR   COLOR_RGB565
+
+#if 0
 #define LCD_WIDTH   128
 #define LCD_HEIGHT  64
+#else
+#define LCD_WIDTH   240
+#define LCD_HEIGHT  240
+#endif
+
+
 
 /* 颜色 */
-#if (LCD_COLOR==COLOR_WB)
-    #define COLOR_WHITE         	 1
-    #define COLOR_BLACK         	 0	  
-#elif (LCD_COLOR==COLOR_RGB565)
+#if 1
     #define COLOR_WHITE         	 0xFFFF
     #define COLOR_BLACK         	 0x0000	  
     #define COLOR_BLUE               0x001F  
@@ -86,8 +99,8 @@ typedef struct {
     int         color;
     int         rotate;
 
-    rt_device_t dev;
-    uint8_t     *buf;
+    struct rt_spi_device *dev;
+    uint16_t     *buf;
     int         buflen;
 }lcd_handle_t;
 

+ 218 - 426
f407/applications/ui/st7789.c

@@ -1,25 +1,12 @@
-/*
- * Copyright (c) 2006-2023, RT-Thread Development Team
- *
- * SPDX-License-Identifier: Apache-2.0
- *
- * Change Logs:
- * Date           Author        Notes
- * 2023-06-10     Vandoul       First version
- */
-
-#include "rtthread.h"
-#include "lcd_st7789.h"
-
-#define DBG_TAG "st7789"
-#define DBG_LVL DBG_INFO
-#include <rtdbg.h>
-
-#ifdef PKG_USING_ST7789
-
-#define LCD_CMD_COL_ADDR_SET                0x2A
-#define LCD_CMD_ROW_ADDR_SET                0x2B
-#define LCD_CMD_MEMORY_WRITE                0x2C
+#include "lcd.h"
+#include "log.h"
+
+
+#define DIV_NUM         10
+
+#define COL_ADDR_SET            0x2A
+#define ROW_ADDR_SET            0x2B
+#define MEMORY_WRITE            0x2C
 /**
  * MADCTL(36H):
  * +---------------------------------------+
@@ -28,7 +15,7 @@
  * +---------------------------------------+
  * [3] 0=RGB,1=BGR
 */
-#define LCD_CMD_MEMORY_DATA_ACCESS_CTRL     0x36
+#define DATA_ACCESS             0x36
 /**
  * COLMOD(3AH):
  * +---------------------------------------+
@@ -44,462 +31,267 @@
  *      110=18bit/pixel
  *      111=16M truncated
 */
-#define LCD_CMD_INTERFACE_PIXEL_FORMAT      0x3A
+#define PIXEL_FORMAT            0x3A
 
+#define delay_ms(x)             rt_thread_mdelay(x)
 
-typedef struct
-{
-    struct rt_device parent;
-    uint16_t width;   /* LCD width */
-    uint16_t height;  /* LCD high */
-    uint32_t id;      /* LCD ID */
-    uint8_t dir;      /* 0:Vertical | 1:Vertical */
-} _lcd_dev;
-
-/* LCD param */
-_lcd_dev lcddev;
-static struct rt_spi_device *lcd_dev;
-static uint16_t frame_buf[LCD_H][LCD_W];
-static void LCD_RESET(void)
-{
-    LCD_RES_CLR;
-    DELAY(100);
-    LCD_RES_SET;
-    DELAY(100);
-}
+static void st7789_fill(lcd_handle_t *h, uint16_t color);
 
-static void LCD_WR_REG(uint8_t reg)
+static void write_reg(lcd_handle_t *h, uint8_t reg)
 {
-    LCD_DC_CLR;
-    rt_spi_send(lcd_dev, &reg, 1);
-    LCD_DC_SET;
+    gpio_set(DC_PIN, 0);
+    rt_spi_send(h->dev, &reg, 1);
 }
-
-static void LCD_WR_DATA(uint8_t data)
+static void write_data(lcd_handle_t *h, uint8_t data)
 {
-    LCD_DC_SET;
-    rt_spi_send(lcd_dev, &data, 1);
+    gpio_set(DC_PIN, 1);
+    rt_spi_send(h->dev, &data, 1);
 }
-
-static void LCD_ReadData(uint8_t *data, uint16_t length)
+static void write_reg_data(lcd_handle_t *h, uint8_t reg, uint16_t data)
 {
-    LCD_DC_SET;
-    rt_spi_transfer(lcd_dev, RT_NULL, &data, length);
+    write_reg(h,reg);
+    write_data(h,data);
 }
-
-static void LCD_WriteReg(uint8_t reg, uint16_t regdata)
+static void read_data(lcd_handle_t *h, uint8_t *data, int length)
 {
-    LCD_WR_REG(reg);
-    LCD_WR_DATA(regdata);
+    gpio_set(DC_PIN, 1);
+    rt_spi_transfer(h->dev, RT_NULL, data, length);
 }
-
-static void LCD_WriteRAM_Prepare(void)
-{
-    LCD_WR_REG(LCD_CMD_MEMORY_WRITE);
-}
-
-static void LCD_WriteData_16Bit(uint16_t Data)
+static void write_16bit(lcd_handle_t *h, uint16_t data)
 {
     uint8_t buf[2];
-    LCD_DC_SET;
-    buf[0] = Data >> 8;
-    buf[1] = Data & 0xff;
-    rt_spi_send(lcd_dev, buf, 2);
+    
+    buf[0] = data >> 8;
+    buf[1] = data & 0xff;
+    
+    gpio_set(DC_PIN, 1);
+    rt_spi_send(h->dev, buf, 2);
 }
 
-void LCD_direction(uint8_t direction)
+void st7789_rotate(lcd_handle_t *h, int rotate)
 {
-    switch (direction)
+    switch (rotate)
     {
-    case 0:
-        lcddev.width = LCD_W;
-        lcddev.height = LCD_H;
-        LCD_WriteReg(LCD_CMD_MEMORY_DATA_ACCESS_CTRL, (0 << 3) | (0 << 5) | (0 << 6) | (0 << 7)); /* BGR==0,MV==0,MX==0,MY==0 */
+        case 0:
+        //h->width = LCD_W;
+        //h->height = LCD_H;
+        write_reg_data(h, DATA_ACCESS, (0 << 3) | (0 << 5) | (0 << 6) | (0 << 7)); /* BGR==0,MV==0,MX==0,MY==0 */
         break;
-    case 1:
-        lcddev.width = LCD_H;
-        lcddev.height = LCD_W;
-        LCD_WriteReg(LCD_CMD_MEMORY_DATA_ACCESS_CTRL, (0 << 3) | (1 << 5) | (1 << 6) | (0 << 7)); /* BGR==0,MV==1,MX==0,MY==1 */
+        
+        case 90:
+        //h->width = LCD_H;
+        //h->height = LCD_W;
+        write_reg_data(h, DATA_ACCESS, (0 << 3) | (1 << 5) | (1 << 6) | (0 << 7)); /* BGR==0,MV==1,MX==0,MY==1 */
         break;
-    case 2:
-        lcddev.width = LCD_W;
-        lcddev.height = LCD_H;
-        LCD_WriteReg(LCD_CMD_MEMORY_DATA_ACCESS_CTRL, (0 << 3) | (0 << 5) | (1 << 6) | (1 << 7)); /* BGR==0,MV==0,MX==1,MY==1 */
+        
+        case 180:
+        //h->width = LCD_W;
+        //h->height = LCD_H;
+        write_reg_data(h, DATA_ACCESS, (0 << 3) | (0 << 5) | (1 << 6) | (1 << 7)); /* BGR==0,MV==0,MX==1,MY==1 */
         break;
-    case 3:
-        lcddev.width = LCD_H;
-        lcddev.height = LCD_W;
-        LCD_WriteReg(LCD_CMD_MEMORY_DATA_ACCESS_CTRL, (0 << 3) | (1 << 5) | (0 << 6) | (1 << 7)); /* BGR==0,MV==1,MX==0,MY==1 */
+        
+        case 270:
+        //h->width = LCD_H;
+        //h->height = LCD_W;
+        write_reg_data(h, DATA_ACCESS, (0 << 3) | (1 << 5) | (0 << 6) | (1 << 7)); /* BGR==0,MV==1,MX==0,MY==1 */
         break;
-    default:
+        
+        default:
         break;
     }
 }
 
-void LCD_SetWindows(uint16_t xStar, uint16_t yStar, uint16_t xEnd, uint16_t yEnd)
+static void st7789_set_win(lcd_handle_t *hd, int x, int y, int w, int h)
 {
-    LCD_WR_REG(LCD_CMD_COL_ADDR_SET);
-    LCD_WR_DATA(xStar >> 8);
-    LCD_WR_DATA(0x00FF & xStar);
-    LCD_WR_DATA(xEnd >> 8);
-    LCD_WR_DATA(0x00FF & xEnd);
-
-    LCD_WR_REG(LCD_CMD_ROW_ADDR_SET);
-    LCD_WR_DATA(yStar >> 8);
-    LCD_WR_DATA(0x00FF & yStar);
-    LCD_WR_DATA(yEnd >> 8);
-    LCD_WR_DATA(0x00FF & yEnd);
-
-    LCD_WriteRAM_Prepare();
+    write_reg(hd,COL_ADDR_SET);
+    write_data(hd,x>>8);
+    write_data(hd,x&0xff);
+    write_data(hd,(x+w-1)>>8);
+    write_data(hd,(x+w-1)&0xff);
+
+    write_reg(hd,ROW_ADDR_SET);
+    write_data(hd,y>>8);
+    write_data(hd,y&0xff);
+    write_data(hd,(y+h-1)>>8);
+    write_data(hd,(y+h-1)&0xff);
+
+    write_reg(hd,MEMORY_WRITE);
 }
 
-void LCD_SetCursor(uint16_t Xpos, uint16_t Ypos)
-{
-    LCD_SetWindows(Xpos, Ypos, Xpos, Ypos);
-}
-
-void LCD_Clear(uint16_t Color)
-{
-    unsigned int i, m;
-
-    LCD_SetWindows(0, 0, lcddev.width - 1, lcddev.height - 1);
-
-    LCD_DC_SET;
-    for (i = 0; i < lcddev.height; i++)
-    {
-        for (m = 0; m < lcddev.width; m++)
-        {
-            frame_buf[i][m] = Color;
-        }
-        for (m = 0; m < lcddev.width;)
-        {
-            m += 40;
-            rt_spi_send(lcd_dev, (uint8_t *)&frame_buf[i][m], 80);
-        }
-    }
-}
 
-void LCD_Fill(uint16_t xsta, uint16_t ysta, uint16_t xend, uint16_t yend, uint16_t color)
-{
-    uint16_t i, j;
-    LCD_SetWindows(xsta, ysta, xend - 1, yend - 1);
-    for (i = ysta; i < yend; i++)
-    {
-        for (j = xsta; j < xend; j++)
-        {
-            frame_buf[i][j] = color;
-            LCD_WriteData_16Bit(color);
-        }
-    }
-}
 
-void LCD_Sync_fb(uint16_t x, uint16_t y, uint16_t w, uint16_t h)
+void st7789_refresh(lcd_handle_t *hd, uint16_t x, uint16_t y, uint16_t w, uint16_t h, void *data, uint32_t len)
 {
-    uint16_t i, j;
-    LCD_SetWindows(x, y, x + w - 1, y + h - 1);
-    LCD_DC_SET;
-    for (i = 0; i < h; i++)
-    {
-        rt_spi_send(lcd_dev, (uint8_t *)&frame_buf[y+i][x], w * 2);
-    }
+    int r;
+    
+    st7789_set_win(hd, x, y, x + w - 1, y + h - 1);
+    gpio_set(DC_PIN, 1);
+    r = rt_spi_send(hd->dev, data, len);
 }
 
-void lcd_fill_array_spi(uint16_t Xstart, uint16_t Ystart, uint16_t Xend, uint16_t Yend, uint16_t *Image)
-{
-    rt_uint32_t size = 0;
-    uint16_t *pImage = Image;
 
-    size = (Xend - Xstart + 1) * (Yend - Ystart + 1) * 2;/*16bit*/
-    LCD_SetWindows(Xstart, Ystart, Xend, Yend);
-    LCD_DC_SET;
-
-    for(int i=0; i<(Yend - Ystart); i++)
-    {
-        for(int j=0; j<(Xend - Xstart); j++)
-        {
-            frame_buf[i + Ystart][j + Xstart] = *pImage++;
-        }
-    }
-    rt_spi_send(lcd_dev, Image, size);
-}
-
-static void _st7789_init(void)
+static void st7789_reg_init(lcd_handle_t *h)
 {
-    LCD_WR_REG(LCD_CMD_MEMORY_DATA_ACCESS_CTRL);
-    LCD_WR_DATA(0x00);
-
-    LCD_WR_REG(LCD_CMD_INTERFACE_PIXEL_FORMAT);
-    LCD_WR_DATA(0X05); //03=RGB444,05=RGB565,06=RGB666
-
-    LCD_WR_REG(0xB2); //Porch Setting
-    LCD_WR_DATA(0x0C);
-    LCD_WR_DATA(0x0C);
-    LCD_WR_DATA(0X00);
-    LCD_WR_DATA(0X33);
-    LCD_WR_DATA(0X33);
-
-    LCD_WR_REG(0xB7); //Gate Control
-    LCD_WR_DATA(0x46);
-
-    LCD_WR_REG(0xBB); //VCOM Setting
-    LCD_WR_DATA(0x1B);
-
-    LCD_WR_REG(0xC0); //LCM Control
-    LCD_WR_DATA(0x2C);
-
-    LCD_WR_REG(0xC2); //VDV and VRH Command Enable
-    LCD_WR_DATA(0x01);
-
-    LCD_WR_REG(0xC3); //VRH set
-    LCD_WR_DATA(0x0F);
-
-    LCD_WR_REG(0xC4); //VDV set
-    LCD_WR_DATA(0x20);
-
-    LCD_WR_REG(0xC6); //Frame Rate Control
-    LCD_WR_DATA(0x0F);
-
-    LCD_WR_REG(0xD0); //Power Control 1
-    LCD_WR_DATA(0xA4);
-    LCD_WR_DATA(0xA1);
-
-    LCD_WR_REG(0xD6);
-    LCD_WR_DATA(0xA1);
-
-    LCD_WR_REG(0xE0);   /* set Positive Voltage Gamma */
-    LCD_WR_DATA(0xF0);
-    LCD_WR_DATA(0x00);
-    LCD_WR_DATA(0x06);
-    LCD_WR_DATA(0x04);
-    LCD_WR_DATA(0x05);
-    LCD_WR_DATA(0x05);
-    LCD_WR_DATA(0x31);
-    LCD_WR_DATA(0x44);
-    LCD_WR_DATA(0x48);
-    LCD_WR_DATA(0x36);
-    LCD_WR_DATA(0x12);
-    LCD_WR_DATA(0x12);
-    LCD_WR_DATA(0x2B);
-    LCD_WR_DATA(0x34);
-
-    LCD_WR_REG(0xE1);   /* set Negative Voltage Gamma */
-    LCD_WR_DATA(0XF0);
-    LCD_WR_DATA(0X0B);
-    LCD_WR_DATA(0X0F);
-    LCD_WR_DATA(0X0F);
-    LCD_WR_DATA(0X0D);
-    LCD_WR_DATA(0X26);
-    LCD_WR_DATA(0X31);
-    LCD_WR_DATA(0X43);
-    LCD_WR_DATA(0X47);
-    LCD_WR_DATA(0X38);
-    LCD_WR_DATA(0X14);
-    LCD_WR_DATA(0X14);
-    LCD_WR_DATA(0X2C);
-    LCD_WR_DATA(0X32);
-
-    LCD_WR_REG(0x21); // Dispaly Inversion On
-
-    LCD_WR_REG(0x29); // Display On
-
-    LCD_WR_REG(LCD_CMD_MEMORY_WRITE); // Memory Write
+    write_reg(h, DATA_ACCESS);
+    write_data(h, 0x00);
+
+    write_reg(h, PIXEL_FORMAT);
+    write_data(h, 0X05); //03=RGB444,05=RGB565,06=RGB666
+
+    write_reg(h, 0xB2); //Porch Setting
+    write_data(h, 0x0C);
+    write_data(h, 0x0C);
+    write_data(h, 0X00);
+    write_data(h, 0X33);
+    write_data(h, 0X33);
+
+    write_reg(h, 0xB7); //Gate Control
+    write_data(h, 0x46);
+
+    write_reg(h, 0xBB); //VCOM Setting
+    write_data(h, 0x1B);
+
+    write_reg(h, 0xC0); //LCM Control
+    write_data(h, 0x2C);
+
+    write_reg(h, 0xC2); //VDV and VRH Command Enable
+    write_data(h, 0x01);
+
+    write_reg(h, 0xC3); //VRH set
+    write_data(h, 0x0F);
+
+    write_reg(h, 0xC4); //VDV set
+    write_data(h, 0x20);
+
+    write_reg(h, 0xC6); //Frame Rate Control
+    write_data(h, 0x0F);
+
+    write_reg(h, 0xD0); //Power Control 1
+    write_data(h, 0xA4);
+    write_data(h, 0xA1);
+
+    write_reg(h, 0xD6);
+    write_data(h, 0xA1);
+
+    write_reg(h, 0xE0);   /* set Positive Voltage Gamma */
+    write_data(h, 0xF0);
+    write_data(h, 0x00);
+    write_data(h, 0x06);
+    write_data(h, 0x04);
+    write_data(h, 0x05);
+    write_data(h, 0x05);
+    write_data(h, 0x31);
+    write_data(h, 0x44);
+    write_data(h, 0x48);
+    write_data(h, 0x36);
+    write_data(h, 0x12);
+    write_data(h, 0x12);
+    write_data(h, 0x2B);
+    write_data(h, 0x34);
+
+    write_reg(h, 0xE1);   /* set Negative Voltage Gamma */
+    write_data(h, 0XF0);
+    write_data(h, 0X0B);
+    write_data(h, 0X0F);
+    write_data(h, 0X0F);
+    write_data(h, 0X0D);
+    write_data(h, 0X26);
+    write_data(h, 0X31);
+    write_data(h, 0X43);
+    write_data(h, 0X47);
+    write_data(h, 0X38);
+    write_data(h, 0X14);
+    write_data(h, 0X14);
+    write_data(h, 0X2C);
+    write_data(h, 0X32);
+
+    write_reg(h, 0x21); // Dispaly Inversion On
+
+    write_reg(h, 0x29); // Display On
+
+    write_reg(h,MEMORY_WRITE); // Memory Write
 }
 
-static void Lcd_pin_init(void)
+static void st7789_reset(lcd_handle_t *h)
 {
-    rt_pin_mode(PKG_ST_7789_DC_PIN, PIN_MODE_OUTPUT);
-    rt_pin_mode(PKG_ST_7789_RES_PIN, PIN_MODE_OUTPUT);
-    rt_pin_mode(PKG_ST_7789_BLK_PIN, PIN_MODE_OUTPUT);
+    gpio_set(RST_PIN, 0);        /* LCD Hardware Reset */
+    delay_ms(100);
+    gpio_set(RST_PIN, 1);
+    delay_ms(120);         /* Delay 120ms */
+    write_reg(h,0x11);   /* Sleep out */
+    delay_ms(120);         /* Delay 120ms */
 }
 
-static void LCD_Init(void)
+static void set_color(lcd_handle_t *h, uint16_t color)
 {
-    Lcd_pin_init();
-
-    LCD_RESET();        /* LCD Hardware Reset */
-    DELAY(120);         /* Delay 120ms */
-    LCD_WR_REG(0x11);   /* Sleep out */
-    DELAY(120);         /* Delay 120ms */
-    _st7789_init();    /* IlI9341 init */
-    LCD_BLK_CLR;        /* Open Backlight */
-
-    LCD_direction(USE_DIRECTION);
+    int i,cnt=h->buflen/2;
+    for(i=0; i<cnt; i++) {
+        h->buf[i] = color;
+    }
 }
-
-rt_err_t spi_device_attach(const char *bus_name, const char *device_name, rt_base_t cs_pin)
+static void st7789_fill(lcd_handle_t *h, uint16_t color)
 {
-    RT_ASSERT(bus_name != RT_NULL);
-    RT_ASSERT(device_name != RT_NULL);
-
-    rt_err_t result = RT_EOK;
-    struct rt_spi_device *spi_device;
-
-    /* attach the device to spi bus*/
-    spi_device = (struct rt_spi_device *)rt_malloc(sizeof(struct rt_spi_device));
-    RT_ASSERT(spi_device != RT_NULL);
-
-    result = rt_spi_bus_attach_device_cspin(spi_device, device_name, bus_name, cs_pin, RT_NULL);
-    if (RT_EOK != result)
-    {
-        LOG_E("%s attach to %s faild, %d\n", device_name, bus_name, result);
-    }
-    else
-    {
-        LOG_I("%s attach to %s done", device_name, bus_name);
+    int i;
+    int height=h->height/DIV_NUM;
+    
+    set_color(h, color);
+    for(i=0; i<DIV_NUM; i++) {
+        st7789_refresh(h, 0, i*height, h->width, height, h->buf, h->buflen);
     }
-
-    return result;
+    
 }
 
-rt_err_t spi_lcd_init(uint32_t freq)
-{
-    rt_err_t res = RT_EOK;
 
-    spi_device_attach(PKG_ST_7789_SPI_BUS_NAME, PKG_ST_7789_SPI_DEVICE_NAME, PKG_ST_7789_CS_PIN);
-    lcd_dev = (struct rt_spi_device *)rt_device_find(PKG_ST_7789_SPI_DEVICE_NAME);
-    if (lcd_dev != RT_NULL)
-    {
-        struct rt_spi_configuration spi_config;
-        spi_config.data_width = 8;
-        spi_config.max_hz = freq * 1000 * 1000;
-        spi_config.mode = RT_SPI_MASTER | RT_SPI_MODE_0 | RT_SPI_MSB;
-        rt_spi_configure(lcd_dev, &spi_config);
+#define SPI_BUS  "spi2"
+#define SPI_DEV_NAME   "spi2.0"
+int st7789_init(lcd_handle_t *h)
+{
+    int r;
+    struct rt_spi_configuration sc;
+    
+    gpio_init(BK_PIN, GPIO_OUT, 0);
+    gpio_init(DC_PIN, GPIO_OUT, 0);
+    gpio_init(RST_PIN, GPIO_OUT, 0);
+    
+    r = rt_hw_spi_device_attach(SPI_BUS, SPI_DEV_NAME, CS_PIN);
+    if(r!=RT_EOK) {
+        return -1;
     }
-    else
-    {
-        res = -RT_ERROR;
+    
+    h->dev = (struct rt_spi_device*)rt_device_find(SPI_DEV_NAME);
+    if(h->dev==NULL) {
+        return -1;
     }
+    
+    sc.data_width = 8;
+    sc.max_hz = 5 * 1000 * 1000;
+    sc.mode = RT_SPI_MASTER | RT_SPI_MODE_0 | RT_SPI_MSB;
+    r = rt_spi_configure(h->dev, &sc);
+    
+    h->buflen = (h->width*h->height*2)/DIV_NUM;
+    h->buf = (uint16_t*)malloc(h->buflen);
+    if (!h->buf) {
+        LOGE("malloc buffer falied\n");
+        return -1;
+    }
+    
+    st7789_reset(h);
+    st7789_reg_init(h);
+    gpio_set(BK_PIN, 1);
+    st7789_fill(h, COLOR_GREEN);
 
-    LCD_Init();
-
-    return res;
-}
-
-static void lcd_ops_blit_line(const char *pixel, int x, int y, rt_size_t size)
-{
-    LCD_SetWindows(x, y, x + size, y);
-    rt_spi_send(lcd_dev, pixel, size * 2);
-}
-struct rt_device_graphic_ops lcd_graphic_ops =
-{
-    .set_pixel  = RT_NULL,//lcd_ops_set_pixel ,
-    .get_pixel  = RT_NULL,//lcd_ops_get_pixel ,
-    .draw_hline = RT_NULL,//lcd_ops_draw_hline,
-    .draw_vline = RT_NULL,//lcd_ops_draw_vline,
-    .blit_line  = lcd_ops_blit_line ,
-};
-rt_err_t lcd_dev_ops_init(rt_device_t dev)
-{
-    spi_lcd_init(25);
-    return RT_EOK;
+    return 0;
 }
-rt_err_t lcd_dev_ops_open(rt_device_t dev, rt_uint16_t oflag)
+int st7789_deinit(lcd_handle_t *h)
 {
-    return RT_EOK;
-}
-rt_err_t lcd_dev_ops_close(rt_device_t dev)
-{
-    return RT_EOK;
-}
-rt_ssize_t lcd_dev_ops_read(rt_device_t dev, rt_off_t pos, void *buffer, rt_size_t size)
-{
-    rt_memcpy(buffer, &((uint16_t *)frame_buf)[pos], size * 2);
-    return RT_EOK;
-}
-rt_ssize_t lcd_dev_ops_write(rt_device_t dev, rt_off_t pos, const void *buffer, rt_size_t size)
-{
-    rt_memcpy(&((uint16_t *)frame_buf)[pos], buffer, size * 2);
-    return RT_EOK;
-}
-rt_err_t lcd_dev_ops_control(rt_device_t dev, int cmd, void *args)
-{
-    switch(cmd)
-    {
-        case RTGRAPHIC_CTRL_RECT_UPDATE:
-        {
-            struct rt_device_rect_info *rect_info = (struct rt_device_rect_info *)args;
-            LCD_Sync_fb(rect_info->x, rect_info->y, rect_info->width, rect_info->height);
-        }
-        case RTGRAPHIC_CTRL_GET_INFO:
-        {
-            struct rt_device_graphic_info *info = args;
-            if(info == RT_NULL)
-            {
-                return -RT_ERROR;
-            }
-            info->pixel_format   = RTGRAPHIC_PIXEL_FORMAT_RGB565; /**< graphic format */
-            info->bits_per_pixel = 16; /**< bits per pixel */
-            info->pitch          = 0; /**< bytes per line */
-            info->width          = lcddev.width; /**< width of graphic device */
-            info->height         = lcddev.height; /**< height of graphic device */
-            info->framebuffer    = (void *)frame_buf; /**< frame buffer */
-            info->smem_len       = sizeof(frame_buf); /**< allocated frame buffer size */
-        }
-    }
-    return RT_EOK;
+    gpio_deinit(BK_PIN);
+    gpio_deinit(DC_PIN);
+    gpio_deinit(RST_PIN);
+    
+    free(h->buf);
+    
+    return 0;
 }
 
-static int lcd_dev_init(void)
-{
-    lcddev.parent.init    = lcd_dev_ops_init   ;
-    lcddev.parent.open    = lcd_dev_ops_open   ;
-    lcddev.parent.close   = lcd_dev_ops_close  ;
-    lcddev.parent.read    = lcd_dev_ops_read   ;
-    lcddev.parent.write   = lcd_dev_ops_write  ;
-    lcddev.parent.control = lcd_dev_ops_control;
-
-    lcddev.parent.type = RT_Device_Class_Graphic;
-    lcddev.parent.user_data = &lcd_graphic_ops;
-    rt_device_register(&lcddev.parent, "lcd", RT_DEVICE_FLAG_RDWR);
-    return RT_EOK;
-}
-INIT_DEVICE_EXPORT(lcd_dev_init);
 
-static int lcd_spi_test(int argc, char *argv[])
-{
-    rt_device_t lcd = rt_device_find("lcd");
-    if(lcd)
-    {
-        uint8_t index = 0;
-        rt_device_open(lcd, RT_DEVICE_FLAG_RDWR);
-        if(rt_strcmp(argv[1], "clear") == 0)
-        {
-            for (index = 0; index < sizeof(color_array) / sizeof(color_array[0]); index++)
-            {
-                LCD_Clear(color_array[index]);
-                LOG_I("lcd clear color: 0x%04x", color_array[index]);
-                DELAY(2000);
-            }
-        }
-        else if(rt_strcmp(argv[1], "line") == 0)
-        {
-            if(argc > 5)
-            {
-                int x = _str2hex(argv[2]);
-                int y = _str2hex(argv[3]);
-                int size = _str2hex(argv[4]);
-                volatile uint8_t buf[size*2];
-                uint16_t color = _str2hex(argv[5]);
-                for(int i=0; i<size; i++)
-                {
-                    buf[i*2] = color>>8;
-                    buf[i*2+1] = color&0xFF;
-                }
-                lcd_ops_blit_line((void *)buf, x, y, size);
-            }
-            else
-            {
-                rt_kprintf("<> line <x> <y> <size> <color>\r\n");
-            }
-        }
-        rt_device_close(lcd);
-    }
-    else
-    {
-        LOG_E("lcd not found.");
-    }
 
-    return RT_EOK;
-}
-MSH_CMD_EXPORT(lcd_spi_test, lcd will fill color => you need init lcd first);
-#endif

+ 3 - 11
f407/applications/ui/ui.c

@@ -7,14 +7,6 @@
 #include "cfg.h"
 
 
-#if 1
-    #define LOGD  log_d
-    #define LOGE  log_e
-#else
-    #define LOGD  printf
-    #define LOGE  printf
-#endif
-
 
 typedef struct {
     int fd;
@@ -31,7 +23,7 @@ static void *ui_thread(void *arg)
 {
     int r;
     thread_handle_t *th=(thread_handle_t*)arg;
-    ui_handle_t *h=(ui_handle_t*)th->arg;
+    ui_handle_t *h=(ui_handle_t*)th->attr->arg;
     
     menu_init();
     while(th->quit==0) {
@@ -47,8 +39,8 @@ static void *ui_thread(void *arg)
 int ui_init(void)
 {
     ui_handle_t *h=&uiHandle;
-
-#if 1//def USE_UI
+menu_init();
+#if 0//def USE_UI
     thread_start(THREAD_ID_UI, ui_thread, h);
 #endif
 

+ 340 - 55
f407/applications/web.c

@@ -11,8 +11,10 @@
 #define TIMER_INTERVAL     1000
 typedef void (*http_fn_t)(void *arg);
 
+#define USE_MG716
 
-#ifdef USE_MG714
+
+#ifdef USE_MG716
 typedef struct mg_tls_opts mg_tls_t;
 #else
 typedef struct mg_serve_http_opts mg_opts_t;
@@ -29,13 +31,12 @@ typedef struct {
     pthread_t       tid;
     
     struct mg_mgr   mgr;
-#ifdef USE_MG714
+#ifdef USE_MG716
     mg_tls_t        tls;
 #else
     mg_opts_t       opts;
 #endif
     
-    power_data_t    pdat;
     handle_t        list;
     char            rootDir[MG_PATH_MAX];
     char            *buf;
@@ -43,30 +44,16 @@ typedef struct {
 }web_handle_t;
 static web_handle_t webHandle={0};
 
-static void set_timer(struct mg_connection *c, int ms)
-{
-    mg_set_timer(c, mg_time()+ms/1000.0f);
-}
+
 
 static int ws_send(web_handle_t *h, struct mg_connection *c, uint8_t type, void *data, int len, int isbin)
 {
     pkt_hdr_t *hdr=NULL;
     
-    if(!h->buf) {
-        LOGE("____ h->buf is NULL\n");
+    if(!h->buf || !len || h->buflen<sizeof(pkt_hdr_t)+len) {
+        LOGE("____ws_send, para are invalid\n");
         return -1;
     }
-    if(h->buflen<sizeof(pkt_hdr_t)+len) {
-        h->buf = realloc(h->buf, sizeof(pkt_hdr_t)+len);
-        if(h->buf) {
-            h->buflen = sizeof(pkt_hdr_t)+len;
-        }
-        else {
-            h->buflen = 0;
-            LOGE("____ realloc failed\n");
-            return -1;
-        }
-    }
     hdr = (pkt_hdr_t*)h->buf;
     
     hdr->magic = PKT_MAGIC;
@@ -74,40 +61,57 @@ static int ws_send(web_handle_t *h, struct mg_connection *c, uint8_t type, void
     hdr->nack  = 0;
     hdr->dlen  = len;
     memcpy(hdr->data, data, len);
+#ifdef USE_MG716
+    mg_ws_send(c, hdr, len+sizeof(pkt_hdr_t), isbin?WEBSOCKET_OP_BINARY:WEBSOCKET_OP_TEXT);
+#else
     mg_send_websocket_frame(c, isbin?WEBSOCKET_OP_BINARY:WEBSOCKET_OP_TEXT, hdr, len+sizeof(pkt_hdr_t));
+#endif
+    
     return 0;
 }
 static void send_powerc(web_handle_t *h, struct mg_connection *c)
 {
     int i,r;
-    r = power_data_copy(&h->pdat, 1);
-    if(r==0) {
-        for(i=0; i<h->pdat.chs; i++) {
-            ws_send(h, c, PKT_TYPE_POWER_CH, &h->pdat.pch[i], sizeof(power_ch_t), 1);
-        }
+    power_data_t pd=power_data_get();
+    
+    for(i=0; i<pd.chs; i++) {
+        ws_send(h, c, PKT_TYPE_POWER_CH, &pd.pch[i], sizeof(power_ch_t), 1);
     }
 }
 static void send_powert(web_handle_t *h, struct mg_connection *c)
 {
     int i,r;
-    r = power_data_copy(&h->pdat, 2);
+    power_data_t pd=power_data_get();
+    
     if(r==0) {
-        ws_send(h, c, PKT_TYPE_POWER_TOTAL, &h->pdat.ttl, sizeof(power_total_t), 1);
+        ws_send(h, c, PKT_TYPE_POWER_TOTAL, &pd.ttl, sizeof(power_total_t), 1);
     }
 }
 
 
-
+static int is_websocket(struct mg_connection *c)
+{
+    int r=0;
+#ifdef USE_MG716
+    r = c->is_websocket;
+#else
+    r = (c->flags & MG_F_IS_WEBSOCKET)?1:0;
+#endif
+}
 static int ws_handle(web_handle_t *h, pkt_hdr_t *hdr, struct mg_connection *c)
 {
     int r=0;
     
+    if (!is_websocket(c)) {
+        return -1;
+    }
+    
     if(hdr->magic!=PKT_MAGIC) {
         LOGE("___ magic: 0x%x is wrong!, correct is: 0x%x\n", hdr->magic, PKT_MAGIC);
         return -1;
     }
     
-    LOGD("_____ ws handle, type: %d, flag: %d\n", hdr->type, hdr->flag);
+    //LOGD("_____ ws handle, type: %d, flag: %d\n", hdr->type, hdr->flag);
     switch(hdr->type) {
         case PKT_TYPE_PARAS:
         {
@@ -122,7 +126,7 @@ static int ws_handle(web_handle_t *h, pkt_hdr_t *hdr, struct mg_connection *c)
                 switch(hdr->subtype) {
                     case SUB_TYPE_POWER_SWITCH:
                     {
-                        r = power_set_sw(pch);
+                        r = power_set_ch_sw(pch->info.ch, pch->power[0].status);
                     }
                     break;
                     
@@ -160,26 +164,26 @@ static int ws_handle(web_handle_t *h, pkt_hdr_t *hdr, struct mg_connection *c)
         
         case PKT_TYPE_POWER_TOTAL:
         {
+            LOGD("_____ send_powert\n");
             send_powert(h, c);
         }
         break;
         
         case PKT_TYPE_CH_ALL:
         {
-            //hdr->flag;
-            
+            power_set_all_sw(hdr->flag);
         }
         break;
         
         case PKT_TYPE_POWER_RESET:
         {
-            //r = power_reset_consump(addr);
+            r = power_reset();
         }
         break;
         
         case PKT_TYPE_SCAN:
         {
-            //r = power_scan();
+            r = power_scan();
         }
         break;
         
@@ -214,18 +218,30 @@ static void http_fn(struct mg_connection *c, int ev, void *ev_data)
 {
     int r,flag=0;
     web_handle_t *h=&webHandle;
-    mg_stream_t s={c,ev,ev_data};
 
-#ifdef USE_MG714
+#ifdef USE_MG716
     if (ev == MG_EV_HTTP_MSG) {
-        struct mg_http_serve_opts opts = {.root_dir = h->rootDir};
-        mg_http_serve_dir(c, ev_data, &opts);
+        struct mg_http_message *hm = (struct mg_http_message *) ev_data;
+        if (mg_match(hm->uri, mg_str("/ws"), NULL)) {
+            mg_ws_upgrade(c, hm, NULL);
+        } else if (mg_match(hm->uri, mg_str("/rest"), NULL)) {
+            // Serve REST response
+            mg_http_reply(c, 200, "", "{\"result\": %d}\n", 123);
+        } else {
+            struct mg_http_serve_opts opts = {.root_dir = h->rootDir};
+            mg_http_serve_dir(c, ev_data, &opts);
+        }
     }
     else if(ev == MG_EV_ACCEPT) {
         if (c->fn_data) {
             mg_tls_init(c, &h->tls);
         }
     }
+    else if(ev == MG_EV_WS_MSG) {
+        struct mg_ws_message *wm = (struct mg_ws_message *) ev_data;
+        pkt_hdr_t *hdr=(pkt_hdr_t*)wm->data.buf;
+        ws_handle(h, hdr, c);
+    }
 #else
     if (ev == MG_EV_HTTP_REQUEST) {
         mg_serve_http(c, (struct http_message *)ev_data, h->opts);
@@ -241,40 +257,63 @@ static void http_fn(struct mg_connection *c, int ev, void *ev_data)
         ws_handle(h, hdr, c);
     }
     else if(ev==MG_EV_TIMER) {
+        
+    #if 0
         list_node_t *ln=NULL;
         r = list_take_node(h->list, &ln, 0);
         if(r==0) {
             node_t *n=&ln->data;
             ws_send(h, c, n->tp, n->buf, n->dlen, 1);
-            list_back_node(list_append, ln);
+            list_back_node(h->list, ln);
         }
+   #endif
     }
 #endif
 }
-static void *web_thread(void *arg)
+static void timer_fn(void *arg)
+{
+    int r;
+    web_handle_t *h=(web_handle_t*)arg;
+    list_node_t *ln=NULL;
+    struct mg_connection* c;
+    
+    r = list_take_node(h->list, &ln, 0);
+    if(r==0) {
+        node_t *n=&ln->data;
+#ifdef USE_MG716
+        for (c = h->mgr.conns; c != NULL; c = c->next) {
+#else
+        for (c = mg_next(&h->mgr, NULL); c != NULL; c = mg_next(&h->mgr, c)) {
+#endif
+            ws_send(h, c, n->tp, n->buf, n->dlen, 1);
+        }
+        list_back_node(h->list, ln);
+    }
+}
+static void web_thread(void *arg)
 {
     struct mg_connection *nc;
     const char *http_addr="http://[::]:80";
     const char *https_addr="https://[::]:443";
-    thread_handle_t *th=(thread_handle_t*)arg;
-    web_handle_t *h=(web_handle_t*)th->arg;
+    //thread_handle_t *th=(thread_handle_t*)arg;
+    //web_handle_t *h=(web_handle_t*)th->attr->arg;
+    web_handle_t *h=&webHandle;
 
-#ifdef USE_MG714
-    //mg_log_set(MG_LL_DEBUG);
-    mg_mgr_init(&mgr);
+#ifdef USE_MG716
+    mg_log_set(MG_LL_DEBUG);
+    mg_mgr_init(&h->mgr);
 
     //sys_get_path(mh->rootDir, WEB_ROOT);
     strcpy(h->rootDir, "/web");
 
-    if (mg_http_listen(&mgr, http_addr, http_fn, NULL) == NULL) {
+    mg_timer_add(&h->mgr, TIMER_INTERVAL, MG_TIMER_REPEAT, timer_fn, h);
+    if (mg_http_listen(&h->mgr, http_addr, http_fn, NULL) == NULL) {
         MG_ERROR(("cannot listen on %s\n", http_addr));
-        return NULL;
     }
 
-    if (mg_http_listen(&mgr, https_addr, http_fn, (void*)1) == NULL) {
-        MG_ERROR(("cannot listen on %s\n", https_addr));
-        return NULL;
-    }
+    //if (mg_http_listen(&h->mgr, https_addr, http_fn, (void*)1) == NULL) {
+    //    MG_ERROR(("cannot listen on %s\n", https_addr));
+    //}
     
     //mh->tls.cert = mg_str(file_load2("/root/run/app/cert/server.crt",0));
     //mh->tls.key = mg_str(file_load2("/root/run/app/cert/server.key",0));
@@ -290,12 +329,11 @@ static void *web_thread(void *arg)
     h->opts.enable_directory_listing = "yes";
 #endif
     
-    while(th->quit==0) {
+    //while(th->quit==0) {
+    while(1) {
         mg_mgr_poll(&h->mgr, 300);
     }
     mg_mgr_free(&h->mgr);
-    
-    pthread_exit(NULL);
 }
 
 
@@ -310,13 +348,14 @@ int web_init(void)
     h->buflen = sizeof(pkt_hdr_t)+sizeof(power_ch_t)+32;
     h->buf = (char*)malloc(h->buflen);
     
+    //web_thread(0);
     thread_start(THREAD_ID_WEB, web_thread, h);
     return 0;
 }
 
 
 
-int web_post_bin(int type, void *data, int len)
+int web_post(int type, void *data, int len)
 {
     struct mg_connection *c;
     web_handle_t *h=&webHandle;
@@ -324,5 +363,251 @@ int web_post_bin(int type, void *data, int len)
     return list_append(h->list, type, data, len);
 }
 
+#if 1
+void WWDG_IRQHandler() {
+    LOGD("___0\n");
+}    
+void PVD_IRQHandler() {
+    LOGD("___1\n");
+}    
+void TAMP_STAMP_IRQHandler(){
+    LOGD("___2\n");
+}    
+void RTC_WKUP_IRQHandler(){
+    LOGD("___3\n");
+}    
+void FLASH_IRQHandler(){
+    LOGD("___4\n");
+}    
+void RCC_IRQHandler(){
+    LOGD("___5\n");
+}    
+//void EXTI0_IRQHandler(){
+//    LOGD("___6\n");
+//}    
+//void EXTI1_IRQHandler(){
+//    LOGD("___7\n");
+//}    
+//void EXTI2_IRQHandler(){
+//    LOGD("___8\n");
+//}    
+//void EXTI3_IRQHandler(){
+//    LOGD("___9\n");
+//}    
+//void EXTI4_IRQHandler(){
+//    LOGD("___a\n");
+//}    
+void DMA1_Stream0_IRQHandler(){
+    LOGD("___b\n");
+}    
+void DMA1_Stream1_IRQHandler(){
+    LOGD("___c\n");
+}    
+void DMA1_Stream2_IRQHandler(){
+    LOGD("___d\n");
+}    
+void DMA1_Stream3_IRQHandler(){
+    LOGD("___e\n");
+}    
+void DMA1_Stream4_IRQHandler(){
+    LOGD("___f\n");
+}    
+void DMA1_Stream5_IRQHandler(){
+    LOGD("___g\n");
+}    
+void DMA1_Stream6_IRQHandler(){
+    LOGD("___h\n");
+}    
+void ADC_IRQHandler(){
+    LOGD("___i\n");
+}    
+void CAN1_TX_IRQHandler(){
+    LOGD("___j\n");
+}    
+void CAN1_RX0_IRQHandler(){
+    LOGD("___k\n");
+}    
+void CAN1_RX1_IRQHandler(){
+    LOGD("___l\n");
+}    
+void CAN1_SCE_IRQHandler(){
+    LOGD("___m\n");
+}    
+//void EXTI9_5_IRQHandler(){
+//    LOGD("___n\n");
+//}    
+void TIM1_BRK_TIM9_IRQHandler(){
+    LOGD("___o\n");
+}    
+void TIM1_UP_TIM10_IRQHandler(){
+    LOGD("___p\n");
+}    
+void TIM1_TRG_COM_TIM11_IRQHandler(){
+    LOGD("___q\n");
+}    
+void TIM1_CC_IRQHandler(){
+    LOGD("___r\n");
+}    
+void TIM2_IRQHandler(){
+    LOGD("___s\n");
+}    
+void TIM3_IRQHandler(){
+    LOGD("___t\n");
+}    
+void TIM4_IRQHandler(){
+    LOGD("___u\n");
+}    
+void I2C1_EV_IRQHandler(){
+    LOGD("___v\n");
+}    
+void I2C1_ER_IRQHandler(){
+    LOGD("___w\n");
+}    
+void I2C2_EV_IRQHandler(){
+    LOGD("___x\n");
+}    
+void I2C2_ER_IRQHandler(){
+    LOGD("___y\n");
+}    
+void SPI1_IRQHandler(){
+    LOGD("___z\n");
+}    
+void SPI2_IRQHandler(){
+    LOGD("___a1\n");
+}    
+//void USART1_IRQHandler(){
+//    LOGD("___a2\n");
+//}    
+//void USART2_IRQHandler(){
+//    LOGD("___a3\n");
+//}    
+//void USART3_IRQHandler(){
+//    LOGD("___a4\n");
+//}    
+//void EXTI15_10_IRQHandler(){
+//    LOGD("___a5\n");
+//}    
+void RTC_Alarm_IRQHandler(){
+    LOGD("___a6\n");
+}    
+void OTG_FS_WKUP_IRQHandler(){
+    LOGD("___a7\n");
+}    
+void TIM8_BRK_TIM12_IRQHandler(){
+    LOGD("___a8\n");
+}    
+void TIM8_UP_TIM13_IRQHandler(){
+    LOGD("___a9\n");
+}    
+void TIM8_TRG_COM_TIM14_IRQHandler(){
+    LOGD("___aa\n");
+}    
+void TIM8_CC_IRQHandler(){
+    LOGD("___ab\n");
+}    
+void DMA1_Stream7_IRQHandler(){
+    LOGD("___ac\n");
+}    
+void FMC_IRQHandler(){
+    LOGD("___ad\n");
+}    
+//void SDIO_IRQHandler(){
+//    LOGD("___ae\n");
+//}    
+void TIM5_IRQHandler(){
+    LOGD("___af\n");
+}    
+void SPI3_IRQHandler(){
+    LOGD("___ag\n");
+}    
+void UART4_IRQHandler(){
+    LOGD("___ah\n");
+}    
+void UART5_IRQHandler(){
+    LOGD("___b1\n");
+}    
+void TIM6_DAC_IRQHandler(){
+    LOGD("___b2\n");
+}    
+void TIM7_IRQHandler(){
+    LOGD("___b3\n");
+}    
+void DMA2_Stream0_IRQHandler(){
+    LOGD("___b4\n");
+}    
+void DMA2_Stream1_IRQHandler(){
+    LOGD("___b5\n");
+}    
+void DMA2_Stream2_IRQHandler(){
+    LOGD("___b6\n");
+}    
+void DMA2_Stream3_IRQHandler(){
+    LOGD("___b7\n");
+}    
+void DMA2_Stream4_IRQHandler(){
+    LOGD("___b8\n");
+}    
+//void ETH_IRQHandler(){
+//    LOGD("___b9\n");
+//}    
+void ETH_WKUP_IRQHandler(){
+    LOGD("___c1\n");
+}    
+void CAN2_TX_IRQHandler(){
+    LOGD("___c2\n");
+}    
+void CAN2_RX0_IRQHandler(){
+    LOGD("___c3\n");
+}    
+void CAN2_RX1_IRQHandler(){
+    LOGD("___c4\n");
+}    
+void CAN2_SCE_IRQHandler(){
+    LOGD("___c5\n");
+}    
+void OTG_FS_IRQHandler(){
+    LOGD("___c6\n");
+}    
+void DMA2_Stream5_IRQHandler(){
+    LOGD("___c7\n");
+}    
+void DMA2_Stream6_IRQHandler(){
+    LOGD("___c8\n");
+}    
+void DMA2_Stream7_IRQHandler(){
+    LOGD("___c9\n");
+}    
+//void USART6_IRQHandler(){
+//    LOGD("___d1\n");
+//}    
+void I2C3_EV_IRQHandler(){
+    LOGD("___d2\n");
+}    
+void I2C3_ER_IRQHandler(){
+    LOGD("___d3\n");
+}    
+void OTG_HS_EP1_OUT_IRQHandler(){
+    LOGD("___d4\n");
+}    
+void OTG_HS_EP1_IN_IRQHandler(){
+    LOGD("___d5\n");
+}    
+void OTG_HS_WKUP_IRQHandler(){
+    LOGD("___d6\n");
+}    
+void OTG_HS_IRQHandler(){
+    LOGD("___d7\n");
+}    
+void DCMI_IRQHandler(){
+    LOGD("___d8\n");
+}    
+void HASH_RNG_IRQHandler(){
+    LOGD("___d9\n");
+}    
+void FPU_IRQHandler(){
+    LOGD("___e1\n");
+}    
+#endif
+
 
 

+ 1 - 1
f407/applications/web.h

@@ -3,7 +3,7 @@
 
 
 int web_init(void);
-int web_post_bin(int type, void *data, int len);
+int web_post(int type, void *data, int len);
 
 #endif
 

+ 1 - 1
f407/drivers/libraries/CMSIS/Device/ST/STM32F4xx/Source/startup_stm32f407xx.s

@@ -30,7 +30,7 @@
 ;   <o> Stack Size (in Bytes) <0x0-0xFFFFFFFF:8>
 ; </h>
 
-Stack_Size      EQU     0x00000800
+Stack_Size      EQU     0x00001000
 
                 AREA    STACK, NOINIT, READWRITE, ALIGN=3
 Stack_Mem       SPACE   Stack_Size

文件差異過大導致無法顯示
+ 410 - 460
f407/project/app/app.uvoptx


+ 6 - 11
f407/project/app/app.uvprojx

@@ -374,7 +374,7 @@
             <ScatterFile>.\linker_scripts\link.sct</ScatterFile>
             <IncludeLibs></IncludeLibs>
             <IncludeLibsPath></IncludeLibsPath>
-            <Misc></Misc>
+            <Misc>--info stack</Misc>
             <LinkerInputFile></LinkerInputFile>
             <DisabledWarnings></DisabledWarnings>
           </LDads>
@@ -753,6 +753,11 @@
               <FileType>1</FileType>
               <FilePath>..\..\applications\ui\ui.c</FilePath>
             </File>
+            <File>
+              <FileName>st7789.c</FileName>
+              <FileType>1</FileType>
+              <FilePath>..\..\applications\ui\st7789.c</FilePath>
+            </File>
           </Files>
         </Group>
         <Group>
@@ -912,21 +917,11 @@
         <Group>
           <GroupName>packages/mg</GroupName>
           <Files>
-            <File>
-              <FileName>mg_port.c</FileName>
-              <FileType>1</FileType>
-              <FilePath>..\..\applications\packages\mongoose-v6.7\mg_port.c</FilePath>
-            </File>
             <File>
               <FileName>mongoose.c</FileName>
               <FileType>1</FileType>
               <FilePath>..\..\applications\packages\mongoose-v6.7\mongoose.c</FilePath>
             </File>
-            <File>
-              <FileName>mg_locals.h</FileName>
-              <FileType>5</FileType>
-              <FilePath>..\..\applications\packages\mongoose-v6.7\mg_locals.h</FilePath>
-            </File>
           </Files>
         </Group>
         <Group>

+ 1 - 1
f407/rt-thread/src/ipc.c

@@ -1328,7 +1328,7 @@ static rt_err_t _rt_mutex_take(rt_mutex_t mutex, rt_int32_t timeout, int suspend
 
     /* this function must not be used in interrupt even if time = 0 */
     /* current context checking */
-    RT_DEBUG_SCHEDULER_AVAILABLE(RT_TRUE);
+    //RT_DEBUG_SCHEDULER_AVAILABLE(RT_TRUE);
 
     /* parameter check */
     RT_ASSERT(mutex != RT_NULL);

+ 3 - 3
f407/tools/web/data.js

@@ -1,4 +1,4 @@
-
+const MAGIC=0xdead;
 const PKT_TYPE=function(){
     var len = 0;
     return {
@@ -68,7 +68,7 @@ function mk_hdr(type,flag)
     var buffer = new ArrayBuffer(13);
 
     tmp = new DataView(buffer, length);
-    var t = 0xdead;
+    var t = MAGIC;
     tmp.setUint16(0,t,true);//magic
     length += 2;
 
@@ -370,7 +370,7 @@ function bin_to_alarmd(bin) {
     this.ch = tmp.getUint8(0,true);
     length += 1;
     
-    this.alarm = new bin_to_alarm(bin.slice(leng));
+    this.alarm = new bin_to_alarm(bin.slice(length));
     length += this.alarm.len;
     
     tmp = new DataView(bin, length);

+ 2 - 11
f407/tools/web/index.html

@@ -11,16 +11,7 @@
     
     function on_ws_msg(bin){
         var j = BIN.hdr.b2j(bin);
-        
-        j.chall = 1;
-        j.type = PKT_TYPE.PKT_TYPE_CH_ALL;
-        
-        console.log(j);
-        var b = BIN.hdr.j2b(j);
-        
-        console.log(b);
-        ws.send(b);
-        
+        console.log(j);   
     }
     function ws_hdr(){
         var proto = window.location.protocol,ws;
@@ -34,7 +25,7 @@
 
 
 
-    ws = new WS("ws://192.168.234.132/ws",on_ws_msg);
+    var ws = new WS("ws://192.168.234.132/ws",on_ws_msg);
 
     
     

+ 1 - 1
f407/tools/webServer/EasyWebSvr.ini

@@ -1,5 +1,5 @@
 [WebServer]
-RootDir=..\web
+RootDir=F:\pdu\SmartPDCode\f407\tools\web
 ListenPort=80
 MaxThreadNum=100
 Timeout=5000

+ 121 - 78
f407/tools/wsServer/mg.cpp

@@ -25,48 +25,39 @@ static int ws_send(struct mg_connection* c, int type, void *data, int len)
     h->dlen = len;
     memcpy(h->data, data, len);
     mg_ws_send(c, (const void*)h, sizeof(pkt_hdr_t) + len, WEBSOCKET_OP_BINARY);
+    free(h);
 
     return 0;
 }
-
-
-// This RESTful server implements the following endpoints:
-//   /websocket - upgrade to Websocket, and implement websocket echo server
-//   /rest - respond with JSON string {"result": 123}
-//   any other URI serves static files from s_web_root
-static void fn(struct mg_connection *c, int ev, void *ev_data) {
-  if (ev == MG_EV_WS_OPEN) {
-      
-  } else if (ev == MG_EV_HTTP_MSG) {
-        struct mg_http_message *hm = (struct mg_http_message *) ev_data;
-        if (mg_match(hm->uri, mg_str("/ws"), NULL)) {
-            // Upgrade to websocket. From now on, a connection is a full-duplex
-            // Websocket connection, which will receive MG_EV_WS_MSG events.
-            mg_ws_upgrade(c, hm, NULL);
-        } else if (mg_match(hm->uri, mg_str("/rest"), NULL)) {
-            // Serve REST response
-            mg_http_reply(c, 200, "", "{\"result\": %d}\n", 123);
-        } else {
-            // Serve static files
-            struct mg_http_serve_opts opts = {.root_dir = s_web_root};
-            mg_http_serve_dir(c, (struct mg_http_message*)ev_data, &opts);
-        }
-  } else if (ev == MG_EV_WS_MSG) {
-    // Got websocket frame. Received data is wm->data. Echo it back!
-    struct mg_ws_message *wm = (struct mg_ws_message *) ev_data;
-     pkt_hdr_t *h= (pkt_hdr_t*)wm->data.buf;
-     power_total_t* pt = (power_total_t*)h->data;
-
-    //mg_ws_send(c, wm->data.buf, wm->data.len, WEBSOCKET_OP_TEXT);
-  }
+static void thrval_set(thr_val_t* tv)
+{
+    tv->en = 0;
+    tv->val = 100.0f;
+    tv->act = 0;
+    memset(tv->para, 0, 14);
+}
+static void thr_set(thr_t* thr)
+{
+    thrval_set(&thr->v_upper);
+    thrval_set(&thr->v_lower);
+    thrval_set(&thr->c_upper);
+    thrval_set(&thr->p_upper);
+    thrval_set(&thr->w_upper);
+}
+static void alarm_set(alarm_t* a)
+{
+    a->v_upper = 1;
+    a->v_lower = 0;
+    a->c_upper = 0;
+    a->p_upper = 0;
+    a->w_upper = 0;
 }
-
 static float rand_float(float min, float max) {
-    return ((float)rand()/(float)RAND_MAX) * (max - min) + min;
+    return ((float)rand() / (float)RAND_MAX) * (max - min) + min;
 }
-static void powert_rand(power_total_t *pt)
+static void powert_rand(power_total_t* pt)
 {
-    int i,cnt = 1;
+    int i, cnt = 1;
 #if 0
     pt->voltage = 1.1f;
     pt->current = 2.2f;
@@ -88,38 +79,12 @@ static void powert_rand(power_total_t *pt)
         pt->total[i].consump = rand_float(1.0f, 100.0f);
         pt->total[i].active = rand_float(1.0f, 100.0f);
         pt->total[i].reactive = rand_float(1.0f, 100.0f);
-        pt->total[i].apparent = rand_float(1.0f, 100.0f);
     }
 #endif
 }
-
-
-static void thrval_set(thr_val_t* tv)
-{
-    tv->en = 0;
-    tv->val = 100.0f;
-    tv->act = 0;
-    memset(tv->para, 0, 14);
-}
-static void thr_set(thr_t *thr)
-{
-    thrval_set(&thr->v_upper);
-    thrval_set(&thr->v_lower);
-    thrval_set(&thr->c_upper);
-    thrval_set(&thr->p_upper);
-    thrval_set(&thr->w_upper);
-}
-static void alarm_set(alarm_t* a)
-{
-    a->v_upper = 0;
-    a->v_lower = 0;
-    a->c_upper = 0;
-    a->p_upper = 0;
-    a->w_upper = 0;
-}
 static void powerc_rand(power_ch_t* pc, uint8_t addr, uint8_t ch, uint8_t sch)
 {
-    int i,cnt = 1;
+    int i, cnt = 1;
 
     pc->info.type = PWR_TYPE;
     pc->info.addr = addr;
@@ -128,7 +93,7 @@ static void powerc_rand(power_ch_t* pc, uint8_t addr, uint8_t ch, uint8_t sch)
     pc->info.ph_id = 0;
     pc->info.start_delay = 0;
     pc->info.stop_delay = 0;
-    
+
     thr_set(&pc->thr);
     alarm_set(&pc->alarm);
 
@@ -149,26 +114,26 @@ static void powerc_rand(power_ch_t* pc, uint8_t addr, uint8_t ch, uint8_t sch)
 
     pc->time = 0;
 }
-static void send_powerc(struct mg_connection *c)
+static void send_powerc(struct mg_connection* c)
 {
-    int i,j,ch=0;
+    int i, j, ch = 0;
     power_ch_t pc;
 #if 1
-    #define BOARD_CNT       2
-    #define BOARC_CH_CNT    2
+#define BOARD_CNT       2
+#define BOARC_CH_CNT    2
 
     //uint8_t addr[BOARD_CNT] = {2,4,6,7,8};
-    uint8_t addr[BOARD_CNT] = { 2,4};
+    uint8_t addr[BOARD_CNT] = { 2,4 };
 #else
-    #define BOARD_CNT       1
-    #define BOARC_CH_CNT    1
+#define BOARD_CNT       1
+#define BOARC_CH_CNT    1
 
     uint8_t addr[BOARD_CNT] = { 2 };
 #endif
     for (i = 0; i < BOARD_CNT; i++) {
         for (j = 0; j < BOARC_CH_CNT; j++) {
             powerc_rand(&pc, addr[i], ch, j);
-            ws_send(c, PKT_TYPE_POWER_CH , &pc, sizeof(pc));
+            ws_send(c, PKT_TYPE_POWER_CH, &pc, sizeof(pc));
             ch++;
         }
     }
@@ -176,9 +141,9 @@ static void send_powerc(struct mg_connection *c)
 static void send_powert(struct mg_connection* c)
 {
     power_total_t pt;
-    
+
     powert_rand(&pt);
-    ws_send(c, PKT_TYPE_POWER_TOTAL , &pt, sizeof(pt));
+    ws_send(c, PKT_TYPE_POWER_TOTAL, &pt, sizeof(pt));
 }
 static void send_alarm(struct mg_connection* c)
 {
@@ -193,18 +158,96 @@ static void send_alarm(struct mg_connection* c)
     a.time = 0;
     ws_send(c, PKT_TYPE_ALARM, &a, sizeof(a));
 }
+static int ws_handle(pkt_hdr_t* hdr, struct mg_connection* c)
+{
+    int r = 0;
+
+    if (!c->is_websocket) {
+        printf("___ not a websocket\n");
+        return -1;
+    }
+
+    if (hdr->magic != PKT_MAGIC) {
+        printf("___ magic: 0x%x is wrong!, correct is: 0x%x\n", hdr->magic, PKT_MAGIC);
+        return -1;
+    }
+
+    printf("_____ ws handle, type:%d, subtype:%d, flag:%d\n", hdr->type, hdr->subtype, hdr->flag);
+    switch (hdr->type) {
+        case PKT_TYPE_PARAS:
+        {
+            //setup
+        }
+        break;
+
+        case PKT_TYPE_POWER_CH:
+        {
+            printf("_____ send_powerc\n");
+            send_powerc(c);
+        }
+        break;
+
+        case PKT_TYPE_POWER_TOTAL:
+        {
+            printf("_____ send_powert\n");
+            send_powert(c);
+        }
+        break;
+
+        case PKT_TYPE_CH_ALL:
+        {
+            
+        }
+        break;
+    }
+
+    return 0;
+}
+
+
+// This RESTful server implements the following endpoints:
+//   /websocket - upgrade to Websocket, and implement websocket echo server
+//   /rest - respond with JSON string {"result": 123}
+//   any other URI serves static files from s_web_root
+static void fn(struct mg_connection *c, int ev, void *ev_data) {
+  if (ev == MG_EV_WS_OPEN) {
+      
+  } else if (ev == MG_EV_HTTP_MSG) {
+        struct mg_http_message *hm = (struct mg_http_message *) ev_data;
+        if (mg_match(hm->uri, mg_str("/ws"), NULL)) {
+            // Upgrade to websocket. From now on, a connection is a full-duplex
+            // Websocket connection, which will receive MG_EV_WS_MSG events.
+            mg_ws_upgrade(c, hm, NULL);
+        } else if (mg_match(hm->uri, mg_str("/rest"), NULL)) {
+            // Serve REST response
+            mg_http_reply(c, 200, "", "{\"result\": %d}\n", 123);
+        } else {
+            // Serve static files
+            struct mg_http_serve_opts opts = {.root_dir = s_web_root};
+            mg_http_serve_dir(c, (struct mg_http_message*)ev_data, &opts);
+        }
+  } else if (ev == MG_EV_WS_MSG) {
+    // Got websocket frame. Received data is wm->data. Echo it back!
+    struct mg_ws_message *wm = (struct mg_ws_message *) ev_data;
+     pkt_hdr_t *hdr= (pkt_hdr_t*)wm->data.buf;
+     ws_handle(hdr, c);
+
+    //mg_ws_send(c, wm->data.buf, wm->data.len, WEBSOCKET_OP_TEXT);
+  }
+}
+
+
+
 
 static void timer_fn(void* arg)
 {
     static uint32_t cnt = 0;
     struct mg_mgr* mgr = (struct mg_mgr*)arg;
+    struct mg_connection* c;
 
     cnt++;
-    for (struct mg_connection* c = mgr->conns; c != NULL; c = c->next) {
-        send_powerc(c);
-        send_powert(c);
-
-        if (cnt%10==0) {
+    if (cnt%10==0) {
+        for (c = mgr->conns; c != NULL; c = c->next) {
             send_alarm(c);
         }
     }