Ejemplo n.º 1
0
 /* ---------------------------------------------------------------------------------------------
  * Send the payload to the associated server to keep the server alive in the master-list.
 */
 void Update(mg_mgr * manager)
 {
     // Is there a connection already waiting response and are we allowed to update?
     if (m_Conn || !m_Valid)
     {
         return; // Keep waiting for a reply and ignore this request
     }
     // Attempt to create a connection to the associated master-server
     m_Conn = mg_connect(manager, m_Addr.Addr(), EventHandler);
     // Make sure that the connection could be created
     if (!m_Conn)
     {
         MtVerboseError("Unable to create connection for '%s'", m_Addr.Addr());
         // This operation failed
         Failed();
     }
     else
     {
         // Set associated connection user data to this instance
         m_Conn->user_data = this;
         // Attach the HTTP protocol component
         mg_set_protocol_http_websocket(m_Conn);
         // Send the payload data
         mg_printf(m_Conn, "%s", m_Data);
         // Verbose status
         MtVerboseMessage("Connection created for '%s'", m_Addr.Addr());
     }
 }
Ejemplo n.º 2
0
struct mg_connection * TestHttpClient::Connect(const std::string & address,
                                               const std::string & uri) {

  boost::mutex mutex;
  boost::condition_variable cond;

  struct mg_connection * conn;
  on_connected_ = [&](struct mg_connection * ws) {
      assert(conn == ws);
      boost::mutex::scoped_lock lock(mutex);
      cond.notify_one();
    };

  conn = mg_connect(&mgr_, address.c_str(), callback);
  mg_set_protocol_http_websocket(conn);
  mg_send_websocket_handshake(conn, uri.c_str(), nullptr);

  const boost::chrono::seconds d(10);
  boost::mutex::scoped_lock lock(mutex);
  const auto timeout = cond.wait_for(lock, d);
  if (boost::cv_status::timeout == timeout) {
    mg_send_websocket_frame(conn, WEBSOCKET_OP_CLOSE, nullptr, 0);
    return nullptr;
  }

  return conn;
}
Ejemplo n.º 3
0
int main(int argc, char *argv[]) {
  struct mg_mgr mgr;
  char *addr = argv[1];

  if (argc < 2) {
    fprintf(stderr, "Usage: %s <server_address>\n", argv[0]);
    exit(EXIT_FAILURE);
  }

  /* Start separate thread that generates MJPG data */
  mg_start_thread(generate_mjpg_data_thread_func, NULL);

  printf("Streaming [%s] to [%s]\n", s_mjpg_file, addr);

  mg_mgr_init(&mgr, NULL);

  for (;;) {
    mg_mgr_poll(&mgr, s_poll_interval_ms);

    /* Reconnect if disconnected */
    if (!client) {
      sleep(1); /* limit reconnections frequency */
      printf("Reconnecting to %s...\n", addr);
      client = mg_connect(&mgr, addr, ev_handler);
      if (client) mg_set_protocol_http_websocket(client);
    }
  }

  return EXIT_SUCCESS;
}
Ejemplo n.º 4
0
int main(int argc, char *argv[]) {
  struct mg_mgr mgr;
  struct mg_connection *nc;
  char *address = s_default_address;

  if (argc > 1) {
    address = argv[1];
  }

  printf("Using %s as CoAP server\n", address);

  mg_mgr_init(&mgr, 0);

  nc = mg_connect(&mgr, address, coap_handler);
  if (nc == NULL) {
    printf("Unable to connect to %s\n", address);
    return -1;
  }

  mg_set_protocol_coap(nc);

  while (!s_time_to_exit) {
    mg_mgr_poll(&mgr, 1000000);
  }

  mg_mgr_free(&mgr);

  return 0;
}
Ejemplo n.º 5
0
int main(int argc, char **argv) {
  struct mg_mgr mgr;
  int i;

  mg_mgr_init(&mgr, NULL);

  /* Parse command line arguments */
  for (i = 1; i < argc; i++) {
    if (strcmp(argv[i], "-h") == 0) {
      s_address = argv[++i];
    } else if (strcmp(argv[i], "-u") == 0) {
      s_user_name = argv[++i];
    } else if (strcmp(argv[i], "-t") == 0) {
      s_topic = argv[++i];
    } else if (strcmp(argv[i], "-p") == 0) {
      s_password = argv[++i];
    }
  }

  if (mg_connect(&mgr, s_address, ev_handler) == NULL) {
    fprintf(stderr, "mg_connect(%s) failed\n", s_address);
    exit(EXIT_FAILURE);
  }

  for (;;) {
    mg_mgr_poll(&mgr, 1000);
  }
}
Ejemplo n.º 6
0
	void ouroboros_server::establish_connection(var_field* aResponse)
	{
		if (mpSendServer->mResponseUrls.count(aResponse))
		{
			std::string url = mpSendServer->mResponseUrls[aResponse];
			mg_connection *client;
			client = mg_connect(mpSendServer->mpServer, url.c_str());
			client->connection_param = aResponse;
		}
	}
Ejemplo n.º 7
0
static const char *test_mg_connect(void) {
  char buf2[40] = "", buf3[40] = "", buf4[40] = "";
  struct mg_server *server = mg_create_server(NULL);

  ASSERT(mg_set_option(server, "listening_port", LISTENING_ADDR) == NULL);
  ASSERT(mg_set_option(server, "document_root", ".") == NULL);
  mg_add_uri_handler(server, "/x", cb4h);
  ASSERT(mg_connect(server, "", 0, 0, NULL, NULL) == 0);
  ASSERT(mg_connect(server, "127.0.0.1", atoi(HTTP_PORT), 0, cb2, buf2) == 1);
  ASSERT(mg_connect(server, "127.0.0.1", 29, 0, cb3, buf3) == 1);
  ASSERT(mg_connect(server, "127.0.0.1", atoi(HTTP_PORT), 0, cb4, buf4) == 1);

  { int i; for (i = 0; i < 50; i++) mg_poll_server(server, 0); }

  ASSERT(strcmp(buf2, "add") == 0);
  ASSERT(strcmp(buf3, "1") == 0);
  ASSERT(strcmp(buf4, "500 Server Error\nPOST size > 999") == 0);
  mg_destroy_server(&server);

  return NULL;
}
Ejemplo n.º 8
0
/*
* Construct a new WebSocket object:
*
* url: url where to connect to
* protocol: websocket subprotocol
*
* Example:
* ws = new WebSocket('wss://localhost:1234');
* ws.onopen = function(ev) {
*     print("ON OPEN", ev);
* }
*
* ws.onclose = function(ev) {
*     print("ON CLOSE", ev);
* }
*
* ws.onmessage = function(ev) {
*     print("ON MESSAGE", ev);
* }
*
* ws.onerror = function(ev) {
*     print("ON ERROR", ev);
* }
*
*/
static v7_val_t sj_ws_ctor(struct v7 *v7, v7_val_t this_obj, v7_val_t args) {
  struct mg_connection *nc;
  struct user_data *ud;
  v7_val_t urlv = v7_array_get(v7, args, 0);
  v7_val_t subprotov = v7_array_get(v7, args, 1);
  (void) this_obj;
  (void) args;

  if (!v7_is_string(urlv)) {
    v7_throw(v7, "invalid ws url string");
  }

  if (v7_is_object(this_obj) && this_obj != v7_get_global_object(v7)) {
    int use_ssl = 0;
    size_t len;
    const char *url = v7_to_string(v7, &urlv, &len);

    if (strncmp(url, "ws://", 5) == 0) {
      url += 5;
    } else if (strncmp(url, "wss://", 6) == 0) {
      url += 6;
      use_ssl = 1;
    }

    nc = mg_connect(&sj_mgr, url, ws_ev_handler);
    if (nc == NULL) v7_throw(v7, "error creating the connection");
#ifdef NS_ENABLE_SSL
    if (use_ssl) {
      mg_set_ssl(nc, NULL, NULL);
    }
#endif

    (void) use_ssl;
    mg_set_protocol_http_websocket(nc);

    ud = calloc(1, sizeof(*ud));
    ud->v7 = v7;
    ud->ws = this_obj;
    nc->user_data = ud;
    v7_own(v7, &ud->ws);

    if (v7_is_string(subprotov)) {
      size_t len;
      const char *proto = v7_to_string(v7, &subprotov, &len);
      ud->proto = strdup(proto);
    }

  } else {
    v7_throw(v7, "WebSocket ctor called without new");
  }

  return v7_create_undefined();
}
Ejemplo n.º 9
0
static const char *test_server(void) {
  char buf1[100] = "", buf2[100] = "";
  struct mg_server *server = mg_create_server((void *) "foo");

  ASSERT(server != NULL);
  ASSERT(mg_set_option(server, "listening_port", LISTENING_ADDR) == NULL);
  ASSERT(mg_set_option(server, "document_root", ".") == NULL);
  mg_add_uri_handler(server, "/cb1", cb1);
  mg_set_http_error_handler(server, error_handler);

  ASSERT(mg_connect(server, "127.0.0.1", atoi(HTTP_PORT),  0, ts1, buf1) == 1);
  ASSERT(mg_connect(server, "127.0.0.1", atoi(HTTP_PORT), 0, ts2, buf2) == 1);

  { int i; for (i = 0; i < 50; i++) mg_poll_server(server, 0); }
  ASSERT(strcmp(buf1, "foo ? 127.0.0.1") == 0);
  ASSERT(strcmp(buf2, "404 ERR: 404") == 0);

  ASSERT(strcmp(static_config_options[URL_REWRITES * 2], "url_rewrites") == 0);
  mg_destroy_server(&server);
  ASSERT(server == NULL);
  return NULL;
}
Ejemplo n.º 10
0
static const char *test_server(void) {
  char buf1[100] = "1", buf2[100] = "2";
  struct mg_server *server = mg_create_server((void *) "foo", evh1);
  struct mg_connection *conn;

  ASSERT(server != NULL);
  ASSERT(mg_set_option(server, "listening_port", LISTENING_ADDR) == NULL);
  ASSERT(mg_set_option(server, "document_root", ".") == NULL);

  ASSERT((conn = mg_connect(server, "127.0.0.1", atoi(HTTP_PORT), 0)) != NULL);
  conn->connection_param = buf1;
  ASSERT((conn = mg_connect(server, "127.0.0.1", atoi(HTTP_PORT), 0)) != NULL);
  conn->connection_param = buf2;

  { int i; for (i = 0; i < 50; i++) mg_poll_server(server, 1); }
  ASSERT(strcmp(buf1, "1foo ? 127.0.0.1") == 0);
  ASSERT(strcmp(buf2, "2ERR: 404") == 0);

  ASSERT(strcmp(static_config_options[URL_REWRITES * 2], "url_rewrites") == 0);
  mg_destroy_server(&server);
  ASSERT(server == NULL);
  return NULL;
}
Ejemplo n.º 11
0
int main(void) {
    struct mg_mgr mgr;
    const char *address = "localhost:1883";

    mg_mgr_init(&mgr, NULL);

    if (mg_connect(&mgr, address, ev_handler) == NULL) {
        fprintf(stderr, "mg_connect(%s) failed\n", address);
        exit(EXIT_FAILURE);
    }

    for(;;) {
        mg_mgr_poll(&mgr, 1000);
    }
}
Ejemplo n.º 12
0
static const char *test_ssl(void) {
  static const char *ssl_cert = "examples/ssl_cert.pem";
  char buf1[100] = "";
  struct mg_server *server = mg_create_server(NULL);

  ASSERT(mg_set_option(server, "listening_port", LISTENING_ADDR) == NULL);
  ASSERT(mg_set_option(server, "document_root", ".") == NULL);
  ASSERT(mg_set_option(server, "ssl_certificate", ssl_cert) == NULL);

  ASSERT(mg_connect(server, "127.0.0.1", atoi(HTTP_PORT), 1, us1, buf1) == 1);

  { int i; for (i = 0; i < 50; i++) mg_poll_server(server, 1000); }
  ASSERT(strcmp(buf1, "1") == 0);
  mg_destroy_server(&server);
  return NULL;
}
Ejemplo n.º 13
0
static const char *test_rewrites(void) {
  char buf1[100] = "xx";
  struct mg_server *server = mg_create_server(NULL, evh2);
  struct mg_connection *conn;
  const char *port;

  ASSERT(mg_set_option(server, "listening_port", "0") == NULL);
  ASSERT(mg_set_option(server, "document_root", ".") == NULL);
  ASSERT(mg_set_option(server, "url_rewrites", "/xx=unit_test.c") == NULL);
  ASSERT((port = mg_get_option(server, "listening_port")) != NULL);
  ASSERT((conn = mg_connect(server, "127.0.0.1", atoi(port), 0)) != NULL);
  conn->connection_param = buf1;

  { int i; for (i = 0; i < 50; i++) mg_poll_server(server, 1); }

  ASSERT(strcmp(buf1, "1 ?") == 0);
  mg_destroy_server(&server);
  return NULL;
}
Ejemplo n.º 14
0
int clubby_proto_connect(struct mg_mgr *mgr) {
  if (s_clubby_conn != NULL) {
    /* We support only one connection to cloud */
    LOG(LL_ERROR, ("Clubby already connected"));

    /* TODO(alashkin): handle this */
    return 1;
  }

  LOG(LL_DEBUG, ("Connecting to %s", get_cfg()->clubby.server_address));

  s_clubby_conn =
      mg_connect(mgr, get_cfg()->clubby.server_address, clubby_proto_handler);
  if (s_clubby_conn == NULL) {
    LOG(LL_DEBUG, ("Cannot connect to %s", get_cfg()->clubby.server_address));
    struct clubby_event evt;
    evt.ev = CLUBBY_CONNECT;
    evt.net_connect.success = 0;
    s_clubby_cb(&evt);
    return 0;
  }

#ifdef SSL_KRYPTON
  if (s_cfg->tls_ena) {
    char *ca_file =
        get_cfg()->tls->tls_ca_file[0] ? get_cfg()->tls->tls_ca_file : NULL;
    char *server_name = get_cfg()->tls->tls_server_name;
    mg_set_ssl(s_clubby_conn, NULL, ca_file);
    if (server_name[0] == '\0') {
      char *p;
      server_name = strdup(get_cfg()->tls->server_address);
      p = strchr(server_name, ':');
      if (p != NULL) *p = '\0';
    }
    SSL_CTX_kr_set_verify_name(s_clubby_conn->ssl_ctx, server_name);
    if (server_name != get_cfg()->tls->tls_server_name) free(server_name);
  }
#endif

  mg_set_protocol_http_websocket(s_clubby_conn);

  return 1;
}
Ejemplo n.º 15
0
int main(int argc, char *argv[]) {
  struct mg_mgr mgr;

  if (argc != 3) {
    fprintf(stderr, "Usage: %s <port> <client|server>\n", argv[0]);
    exit(EXIT_FAILURE);
  } else if (strcmp(argv[2], "client") == 0) {
    sock_t fds[2];
    struct mg_connection *ioconn, *server_conn;

    mg_mgr_init(&mgr, NULL);

    // Connect to the pubsub server
    server_conn = mg_connect(&mgr, argv[1], client_handler);
    if (server_conn == NULL) {
      fprintf(stderr, "Cannot connect to port %s\n", argv[1]);
      exit(EXIT_FAILURE);
    }
    server_conn->flags |= MG_F_USER_2;  // Mark this as a client connection

    // Create a socketpair and give one end to the thread that reads stdin
    mg_socketpair(fds, SOCK_STREAM);
    mg_start_thread(stdin_thread, &fds[1]);

    // The other end of a pair goes inside the server
    ioconn = mg_add_sock(&mgr, fds[0], client_handler);
    ioconn->flags |= MG_F_USER_1;  // Mark this so we know this is a stdin
    ioconn->user_data = server_conn;

  } else {
    // Server code path
    mg_mgr_init(&mgr, NULL);
    mg_bind(&mgr, argv[1], server_handler);
    printf("Starting pubsub server on port %s\n", argv[1]);
  }

  for (;;) {
    mg_mgr_poll(&mgr, 1000);
  }
  mg_mgr_free(&mgr);

  return EXIT_SUCCESS;
}
Ejemplo n.º 16
0
/*
 * choose_backend parses incoming HTTP request and routes it to the appropriate
 * backend. It assumes that clients don't do HTTP pipelining, handling only
 * one request request for each connection. To give a hint to backend about
 * this it inserts "Connection: close" header into each forwarded request.
 */
static int connect_backend(struct conn_data *conn, struct http_message *hm) {
  struct mg_connection *nc = conn->client.nc;
  struct http_backend *be = choose_backend(hm);

  write_log("%ld %.*s %.*s backend=%s\n", (long) time(NULL),
            (int) hm->method.len, hm->method.p, (int) hm->uri.len, hm->uri.p,
            be ? be->host_port : "not defined");

  if (be == NULL) return 0;
  if (be->redirect != 0) {
    mg_printf(nc, "HTTP/1.1 302 Found\r\nLocation: %s\r\n\r\n", be->host_port);
    return 1;
  }
  struct be_conn *bec = get_conn(be);
  if (bec != NULL) {
    bec->nc->handler = ev_handler;
#ifdef DEBUG
    write_log("conn=%p to %p (%s) reusing bec=%p\n", conn, be, be->host_port,
              bec);
#endif
  } else {
    bec = malloc(sizeof(*conn->be_conn));
    memset(bec, 0, sizeof(*bec));
    bec->nc = mg_connect(nc->mgr, be->host_port, ev_handler);
#ifdef DEBUG
    write_log("conn=%p new conn to %p (%s) bec=%p\n", conn, be, be->host_port,
              bec);
#endif
    if (bec->nc == NULL) {
      free(bec);
      write_log("Connection to [%s] failed\n", be->host_port);
      return 0;
    }
  }
  bec->be = be;
  conn->be_conn = bec;
  conn->backend.nc = bec->nc;
  conn->backend.nc->user_data = conn;
  mg_set_protocol_http_websocket(conn->backend.nc);
  return 1;
}
Ejemplo n.º 17
0
struct mg_connection *mg_download(const char *host, int port, int use_ssl,
                                  char *ebuf, size_t ebuf_len,
                                  const char *fmt, ...) {
  struct mg_connection *conn;
  va_list ap;

  va_start(ap, fmt);
  ebuf[0] = '\0';
  if ((conn = mg_connect(host, port, use_ssl, ebuf, ebuf_len)) == NULL) {
  } else if (mg_vprintf(conn, fmt, ap) <= 0) {
    snprintf(ebuf, ebuf_len, "%s", "Error sending request");
  } else {
    getreq(conn, ebuf, ebuf_len);
  }
  if (ebuf[0] != '\0' && conn != NULL) {
    mg_close_connection(conn);
    conn = NULL;
  }

  return conn;
}
Ejemplo n.º 18
0
void imcs_thread() {
	{
		mg_mgr_init(imcs_mgmgrHandle, NULL);
	}
	
	{
		imcs_mgconnectionHandle = mg_connect(imcs_mgmgrHandle, imcs_charServer, imcs_handler);
	}
	
	{
		do {
			mg_mgr_poll(imcs_mgmgrHandle, 1000);
		} while (pthread_mutex_trylock(&imcs_pthreadmutexRunning) != 0);
		
		pthread_mutex_unlock(&imcs_pthreadmutexRunning);
	}
	
	{
		mg_mgr_free(imcs_mgmgrHandle);
	}
}
Ejemplo n.º 19
0
int main(int argc, char* argv[]) {
  #ifdef SENSORTRACER
  printf("sensortracer\n");
  sensortracer_init();
  #endif
  char *address = s_default_address;

  if (argc > 1) {
    address = argv[1];
  }

  printf("Using %s as CoAP server\n", address); 

	while(1) {
		struct mg_mgr mgr;
		struct mg_connection *nc;
		memset(&mgr, 0, sizeof(struct mg_mgr));
		mg_mgr_init(&mgr, 0);

		nc = mg_connect(&mgr, address, coap_handler);
		if (nc == NULL) {
			printf("Unable to connect to %s\n", address);
			return -1;
		}

		mg_set_protocol_coap(nc);

		while (!s_time_to_exit) {
			mg_mgr_poll(&mgr, 1);
		}

		mg_mgr_free(&mgr);
		sleep(3);
		s_time_to_exit = 0;
  }
  
  return 0;
}
Ejemplo n.º 20
0
static void disp_task(void *params) {
  struct mg_connection *conn = NULL;
  struct conn_ctx ctx;
  printf("Starting network test...\n");
  memset(data, 'A', sizeof(data));
  memset(&ctx, 0, sizeof(ctx));
  wifi_connect();
  int i = 0;
  while (1) {
    mongoose_poll(2);
    if (!wifi_connected) continue;
    switch (ctx.state) {
      case DISCONNECTED:
        memset(&ctx, 0, sizeof(ctx));
        conn = mg_connect(&sj_mgr, ADDR_TO_CONNECT, conn_handler);
        if (conn == NULL) {
          vTaskDelay(100);
          printf("reconnecting\n");
          continue;
        }
        printf("conn = %p\n", conn);
        conn->user_data = &ctx;
        ctx.state = CONNECTING;
        break;
      case CONNECTING:
        break;
      case CONNECTED:
        i++;
        if (i % 10000 == 0) {
          printf("sent %u, recv %u heap free: %u uptime %d\n", ctx.num_sent,
                 ctx.num_received, system_get_free_heap_size(),
                 system_get_time() / 1000000);
        }
        break;
    }
  }
}
Ejemplo n.º 21
0
void imcs_handler(struct mg_connection* mgconnectionHandle, int intEvent, void* voidData) {
	if (intEvent == MG_EV_CONNECT) {
		{
			printf("imcs: connected\n");
		}
		
		{
			imcs_boolConnected = true;
			
			imcs_boolAuthorized = false;
			
			webserver_broadcast("imcs_status", NULL);
		}
		
	} else if (intEvent == MG_EV_CLOSE) {
		{
			printf("imcs: disconnected\n");
		}
		
		{
			imcs_boolConnected = false;
			
			imcs_boolAuthorized = false;
			
			webserver_broadcast("imcs_status", NULL);
		}
		
		{
			imcs_mgconnectionHandle = mg_connect(imcs_mgmgrHandle, imcs_charServer, imcs_handler);
		}
		
	} else if (intEvent == MG_EV_RECV) {
		{
			mgconnectionHandle->recv_mbuf.buf[mgconnectionHandle->recv_mbuf.len] = '\0';
		}
		
		{
			if (strstr(mgconnectionHandle->recv_mbuf.buf, "201 hello") != NULL) {
				imcs_boolAuthorized = true;
				
				webserver_broadcast("imcs_status", NULL);
				
			} else if (strstr(mgconnectionHandle->recv_mbuf.buf, "202 hello new user") != NULL) {
				imcs_boolAuthorized = true;
				
				webserver_broadcast("imcs_status", NULL);
				
			}
		}
		
		{
			webserver_broadcast("imcs_buffer", mgconnectionHandle->recv_mbuf.buf);
		}
		
		{
			strncat(imcs_charBuffer, mgconnectionHandle->recv_mbuf.buf, mgconnectionHandle->recv_mbuf.len);
		}
		
		{
			int intSplit = 0;
			char charSplit[256][1024] = { };
			
			intSplit += 1;
			strcpy(charSplit[0], imcs_charBuffer);
			
			for (int intFor1 = 1; strstr(charSplit[intFor1 - 1], "\r\n") != NULL; intFor1 += 1) {
				intSplit += 1;
				strcpy(charSplit[intFor1], strstr(charSplit[intFor1 - 1], "\r\n") + strlen("\r\n"));
				
				strstr(charSplit[intFor1 - 1], "\r\n")[0] = '\0';
			}
			
			for (int intFor1 = 0; intFor1 < intSplit; intFor1 += 1) {
				if (strncmp(charSplit[intFor1], "105", strlen("105")) == 0) {
					chess_reset();
					
				} else if (strncmp(charSplit[intFor1], "106", strlen("106")) == 0) {
					chess_reset();
					
				} else if (strncmp(charSplit[intFor1], "230", strlen("230")) == 0) {
					webserver_broadcast("imcs_operation", "competition");
					
					imcs_charBuffer[0] = '\0';
					
				} else if (strncmp(charSplit[intFor1], "231", strlen("231")) == 0) {
					webserver_broadcast("imcs_operation", "competition");
					
					imcs_charBuffer[0] = '\0';
					
				} else if (strncmp(charSplit[intFor1], "232", strlen("232")) == 0) {
					webserver_broadcast("imcs_operation", "competition");
					
					imcs_charBuffer[0] = '\0';
					
				} else if (strncmp(charSplit[intFor1], "408", strlen("408")) == 0) {
					webserver_broadcast("imcs_operation", "competition");
					
					imcs_charBuffer[0] = '\0';
					
				} else if (strncmp(charSplit[intFor1], "?", strlen("?")) == 0) {
					char charMove[1024] = { };
					
					{
						char charBuffer[1024] = { };
						
						strcpy(charBuffer, charSplit[intFor1 - 1]);
						
						chess_boardSet(charBuffer);
						
						webserver_broadcast("imcs_board", charBuffer);
					}
					
					{
						int intTime = 0;
						
						intTime += (charSplit[intFor1][2] - '0') * 600000;
						intTime += (charSplit[intFor1][3] - '0') * 60000;
						intTime += (charSplit[intFor1][5] - '0') * 10000;
						intTime += (charSplit[intFor1][6] - '0') * 1000;
						intTime += (charSplit[intFor1][8] - '0') * 100;
						intTime += (charSplit[intFor1][9] - '0') * 10;
						intTime += (charSplit[intFor1][10] - '0') * 1;
						
						chess_moveAlphabeta(charMove, -1, intTime);
					}
					
					{
						char charBuffer[1024] = { };
						
						sprintf(charBuffer, ">>> move %.5s\n", charMove);
						
						webserver_broadcast("imcs_buffer", charBuffer);
					}
					
					{
						mg_printf(imcs_mgconnectionHandle, "%.5s\r\n", charMove);
					}
					
					{
						char charBuffer[1024] = { };
						
						chess_boardGet(charBuffer);
						
						webserver_broadcast("imcs_board", charBuffer);
					}
					
					{
						imcs_charBuffer[0] = '\0';
					}
					
				}
			}
		}
		
		{
			if (imcs_charTermination[0] != '\0') {
				if (strstr(imcs_charBuffer, imcs_charTermination) != NULL) {
					webserver_broadcast("imcs_operation", imcs_charOperation);
					
					imcs_charBuffer[0] = '\0';
					imcs_charOperation[0] = '\0';
					imcs_charTermination[0] = '\0';
				}
			}
		}
		
		{
			mbuf_remove(&mgconnectionHandle->recv_mbuf, mgconnectionHandle->recv_mbuf.len);
		}
		
	}
}
Ejemplo n.º 22
0
void APP_Tasks(void) {
    /*
     * Processing CC3100 Tasks
     * It looks like SYS task and might be processed in SYS_Tasks
     * But for this demo it is here to make this call
     * visible
     */
    _SlNonOsMainLoopTask();

    /* Check the application's current state. */
    switch (appData.state) {
    /* Application's initial state. */
    case APP_STATE_INIT: {
        SYS_PRINT("\n\r*** PIC32 MQTT CLIENT ***\n\r");

        SYS_PRINT("\n\rInitializing CC3100\n\r");
        int res = sl_Start(NULL, NULL, NULL);
        if (res != 0) {
            SYS_PRINT("FAILED\n\r");
            appData.state = APP_STATE_DONE;
            break;
        }

        SlSecParams_t sec_params;
        memset(&sec_params, 0, sizeof(sec_params));
        sec_params.Key = NET_PWD;
        sec_params.KeyLen = sizeof(NET_PWD) - 1;
        sec_params.Type = NET_SECURITY;

        SYS_PRINT("Connecting to WiFi\n\r");

        sl_WlanConnect(NET_SSID, sizeof(NET_SSID) - 1, 0, &sec_params, NULL);

        SYS_PRINT("Initialization done\n\r");

        appData.state = APP_STATE_SERVICE_TASKS;

        break;
    }

    case APP_STATE_CONNECT_BROKER: {
        if (mg_connect(&mgr, MQTT_BROKER_ADDRESS, ev_handler) == NULL) {
            SYS_PRINT("Failed to create connection\n\r");
            appData.state = APP_STATE_DONE;
        } else {
            appData.state = APP_STATE_SERVICE_TASKS;
        }
        break;
    }
    case APP_STATE_SERVICE_TASKS: {
        static uint32_t prev_poll_time = 0;
        uint32_t now = DRV_RTCC_TimeGet();
        if (now - prev_poll_time > 100) {
            /*
             * We cannot call mg_mgr_poll every cycle
             * it leads to SPI overload (internaly mg_mgr_poll calls
             * CC3100 via SPI
             */
            mg_mgr_poll(&mgr, 1);
            prev_poll_time = now;
        }
        break;
    }

    case APP_STATE_DONE: {
        /* Do nothing here */
        break;
    }
    default: {
        /* TODO: Handle error in application's state machine. */
        break;
    }
    }
}
Ejemplo n.º 23
0
/*
 * Make a new MQTT client.
 *
 * Arguments:
 * url: url where to connect to
 * opts: option object
 *
 * Recognized option object properties:
 *
 * - clientId: string; mqtt client id. defaults to
 *             Math.random().toString(16).substr(2, 10)
 *
 * Example:
 *
 * var client = MQTT.connect('mqtt://test.mosquitto.org');
 *
 * client.on('connect', function () {
 *   client.subscribe('presence');
 *   client.publish('presence', 'Hello mqtt');
 * });
 *
 * client.on('message', function (topic, message) {
 *   console.log(message);
 * });
 *
 * TLS can be enabled by choosing the `mqtts://` protocol. In that
 * case the default port is 8883 as defined by IANA.
 *
 * The API is modeled after https://www.npmjs.com/package/mqtt.
 *
 */
enum v7_err sj_mqtt_connect(struct v7 *v7, v7_val_t *res) {
  enum v7_err rcode = V7_OK;
  const char *url;
  size_t len;
  struct mg_str host, scheme;
  unsigned int port;
  struct mg_connection *nc;
  struct user_data *ud;
  char *url_with_port = NULL;
  int use_ssl = 0;
  v7_val_t urlv = v7_arg(v7, 0), opts = v7_arg(v7, 1);
  v7_val_t client_id;
  v7_val_t proto =
      v7_get(v7, v7_get(v7, v7_get_global(v7), "MQTT", ~0), "proto", ~0);

  if (!v7_is_string(urlv)) {
    rcode = v7_throwf(v7, "Error", "invalid url string");
    goto clean;
  }

  url = v7_get_string(v7, &urlv, &len);

  if (mg_parse_uri(mg_mk_str(url), &scheme, NULL, &host, &port, NULL, NULL,
                   NULL) < 0) {
    rcode = v7_throwf(v7, "Error", "invalid url string");
    goto clean;
  }

  if (mg_vcmp(&scheme, "mqtt") == 0) {
    url += sizeof("mqtt://") - 1;
  } else if (mg_vcmp(&scheme, "mqtts") == 0) {
    url += sizeof("mqtts://") - 1;
    use_ssl = 1;
  } else {
    rcode = v7_throwf(v7, "Error", "unsupported protocol");
    goto clean;
  }

  client_id = v7_get(v7, opts, "clientId", ~0);
  if (v7_is_undefined(client_id)) {
    rcode = v7_exec(v7, "Math.random().toString(16).substr(2,8)", &client_id);
    if (rcode != V7_OK) {
      goto clean;
    }
  }

  if (port == 0) {
    if (asprintf(&url_with_port, "%.*s%s", (int) host.len, host.p,
                 (use_ssl ? ":8883" : ":1883")) < 0) {
      rcode = v7_throwf(v7, "Error", "Out of memory");
      goto clean;
    }
  }

  nc =
      mg_connect(&sj_mgr, url_with_port ? url_with_port : url, mqtt_ev_handler);
  if (nc == NULL) {
    rcode = v7_throwf(v7, "Error", "cannot create connection");
    goto clean;
  }

  if (use_ssl) {
#ifdef MG_ENABLE_SSL
    mg_set_ssl(nc, NULL, NULL);
#else
    rcode = v7_throwf(v7, "Error", "SSL not enabled");
    goto clean;
#endif
  }
  mg_set_protocol_mqtt(nc);

  *res = v7_mk_object(v7);
  v7_set_proto(v7, *res, proto);

  ud = calloc(1, sizeof(*ud));
  if (ud == NULL) {
    rcode = v7_throwf(v7, "Error", "Out of memory");
    goto clean;
  }
  ud->v7 = v7;
  ud->client = *res;
  ud->client_id = strdup(v7_get_cstring(v7, &client_id));
  if (ud->client_id == NULL) {
    free(ud);
    rcode = v7_throwf(v7, "Error", "Out of memory");
    goto clean;
  }
  nc->user_data = ud;
  v7_own(v7, &ud->client);

  v7_def(v7, *res, "_nc", ~0, _V7_DESC_HIDDEN(1), v7_mk_foreign(v7, nc));

clean:
  free(url_with_port);

  return rcode;
}