#include "websocket_handle.h" #include "mongoose.h" #include "pthread.h" #include "elog.h" #include "common.h" #include "sys.h" #define WS_MAX 10 typedef struct mg_mgr mg_mgr_t; typedef struct mg_connection mg_conn_t; typedef struct mg_ws_message mg_ws_msg_t; typedef struct mg_http_message mg_http_msg_t; typedef struct { mg_mgr_t mgr; char wpath[200]; char root[200]; mg_conn_t *c; int inited; pthread_mutex_t mutex; }ws_handle_t; static ws_handle_t wsHandle; static void read_ipaddr(ws_handle_t *h) { sprintf(h->wpath,"ws://%s:6785", getLocalIpAddress("eth0")); printf("____ ws path: %s\n", h->wpath); } static void fn(mg_conn_t *c, int ev, void *ev_data) { ws_handle_t *wh=&wsHandle; switch(ev) { case MG_EV_OPEN: { } break; case MG_EV_CLOSE: { } break; case MG_EV_HTTP_MSG: { static int ws_cnt=0; mg_http_msg_t *hm = (mg_http_msg_t *) ev_data; if (mg_http_match_uri(hm, "/websocket/PDU-WebSocket")) { mg_ws_upgrade(c, hm, NULL); wh->c = c; } else if (mg_http_match_uri(hm, "/rest")) { // Serve REST response mg_http_reply(c, 200, "", "{\"result\": %d}\n", 123); } else { wh->c = NULL; } } break; case MG_EV_WS_MSG: { struct mg_ws_message *wm = (struct mg_ws_message *) ev_data; mg_ws_send(c, wm->data.ptr, wm->data.len, WEBSOCKET_OP_TEXT); } break; } } void* websocket_thread(void* arg) { int r; thread_handle_t *h=(thread_handle_t*)arg; ws_handle_t *wh=(ws_handle_t*)h->arg; mg_mgr_init(&wh->mgr); // Initialise event manager mg_http_listen(&wh->mgr, wh->wpath, fn, NULL); // Create HTTP listener wh->inited = 1; while(h->quit==0) { mg_mgr_poll(&wh->mgr, 1000); // Infinite event loop } wh->inited = 0; mg_mgr_free(&wh->mgr); pthread_exit(NULL); } int websocket_init(void) { ws_handle_t *wh=&wsHandle; memset(wh, 0, sizeof(ws_handle_t)); read_ipaddr(wh); sys_start_thread(THREAD_ID_WS, websocket_thread, wh); return 0; } int websocket_send(void *data, int len) { int i; ws_handle_t *wh=&wsHandle; if(!wh->inited) { return -1; } mg_ws_send(wh->c, data, len, WEBSOCKET_OP_TEXT); return 0; } int websocket_isok(void) { ws_handle_t *wh=&wsHandle; return (wh->c)?1:0; }