| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143 |
- #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;
- }
-
|