Ejemplo n.º 1
0
/*-----------------------------------------------------------------------------------*/
struct
netconn *netconn_new_with_callback(enum netconn_type t,
                                   void (*callback)(struct netconn *, enum netconn_evt, u32_t len))
{
    struct netconn *conn;
    
    /* get a netconn and then initialize callback pointer and socket */
    conn = netconn_new(t);
    if (conn)
        conn->callback = callback;
    return conn;
}
Ejemplo n.º 2
0
msg_t data_udp_send_thread(void *p) {
	void * arg __attribute__ ((unused)) = p;

	err_t                 err;
	uint8_t               count = 0;

	struct     netconn    *conn;
	struct     netbuf     *buf;

	char*                  data;
	char                   msg[DATA_UDP_MSG_SIZE] ;

	ip_addr_t              ip_addr_sensor;
	ip_addr_t              ip_addr_fc;

	IMU_A_IP_ADDR(&ip_addr_sensor);
	IP_PSAS_FC(&ip_addr_fc);

	chRegSetThreadName("data_udp_send_thread");

	conn   = netconn_new( NETCONN_UDP );

	/* Bind to the local address, or to ANY address */
	//	netconn_bind(conn, NULL, DATA_UDP_TX_THREAD_PORT ); //local port, NULL is bind to ALL ADDRESSES! (IP_ADDR_ANY)
	err    = netconn_bind(conn, &ip_addr_sensor, IMU_A_TX_PORT ); //local port

	if (err == ERR_OK) {
		/* Connect to specific address or a broadcast address */
		/*
		 * \todo Understand why a UDP needs a connect...
		 *   This may be a LwIP thing that chooses between tcp_/udp_/raw_ connections internally.
		 *
		 */
		//	netconn_connect(conn, IP_ADDR_BROADCAST, DATA_UDP_TX_THREAD_PORT );
		err = netconn_connect(conn, &ip_addr_fc, FC_LISTEN_PORT_IMU_A );
		if(err == ERR_OK) {
			for( ;; ){
				buf     =  netbuf_new();
				data    =  netbuf_alloc(buf, sizeof(msg));
				sprintf(msg, "sensor tx: %d", count++);
				memcpy (data, msg, sizeof (msg));
				netconn_send(conn, buf);
				netbuf_delete(buf); // De-allocate packet buffer
				chThdSleepMilliseconds(500);
			}
			return RDY_OK;
		} else {
			return RDY_RESET;
		}
	} else {
		return RDY_RESET;
	}
}
Ejemplo n.º 3
0
/**
 * Init tcp server whit kfile interface.
 *
 * Start a tcp server on registered ethernet interface, and it calls the user handler
 * when receive data from accepted connection socket.
 *
 * \note Use the tcpsocket_serverPoll() function to process al connections.
 *
 * \param socket tcp socket context.
 * \param local_addr device ip address.
 * \param listen_addr ip address to listen
 * \param port tcp socket port to listen
 * \param handler user handler that server calls every time we recive a data from
 * socket. To the handler the server will pass the kfile context and user could choose
 * to make an explicit connection close, otherwise the server keep alive the connection.
 */
void tcpsocket_serverInit(TcpSocket *socket, struct ip_addr *local_addr, struct ip_addr *listen_addr, uint16_t port, tcphandler_t handler)
{
	tcpsocket_init(socket, local_addr, listen_addr, port);
	socket->handler = handler;

	socket->server_sock = netconn_new(NETCONN_TCP);
	socket->error = netconn_bind(socket->server_sock, listen_addr, port);
	socket->error = netconn_listen(socket->server_sock);

	if(socket->error != ERR_OK)
		LOG_ERR("Init server\n");
}
Ejemplo n.º 4
0
/**
 * \brief HTTP task core function.
 *
 * \param pvParameters Junk parameter.
 */
static void http_task(void *pvParameters)
{
	struct netconn *conn, *newconn;
	err_t err;
	/* Just to avoid compiler warnings. */
	UNUSED(pvParameters);

	/* Wait for user to read instructions. */
	WAIT_FOR_TOUCH_EVENT;

#if LWIP_STATS
	configure_timer_for_bandwidth_stats();
#endif

	/* Create a new TCP connection handle */
	conn = netconn_new(NETCONN_TCP);
	if (conn == NULL)
	{
		printf("http_task: invalid conn\n");

		/* Delete the calling task. */
		vTaskDelete(NULL);
	}

	/* Bind to port 80 (HTTP) with default IP address */
	netconn_bind(conn, NULL, 80);

	/* Put the connection into LISTEN state */
	netconn_listen(conn);

	do {
		err = netconn_accept(conn, &newconn);
		if (err == ERR_OK) {
		/* Try to instanciate a new HTTP-req task to handle the HTTP request. */
			if (NULL == sys_thread_new("HTTP-req", http_request, newconn,
					mainHTTP_TASK_STACK_SIZE, mainHTTP_TASK_PRIORITY)) {
				/* Failed to instanciate task, free netconn socket. */
				netconn_close(newconn);
				netconn_delete(newconn);
			}
		}
	} while (err == ERR_OK);

	printf("http_task: netconn_accept received error %d, shutting down\n", err);

	/* Free Netconn resource. */
	netconn_close(conn);
	netconn_delete(conn);

	/* Delete the calling task. */
	vTaskDelete(NULL);
}
/*-----------------------------------------------------------------------------------*/
static void tcpecho_thread(void *arg)
{
  struct netconn *conn, *newconn;
  err_t err;

  LWIP_UNUSED_ARG(arg);

  /* Create a new connection identifier. */
  conn = netconn_new(NETCONN_TCP);
  
  if (conn!=NULL) {  
    /* Bind connection to well known port number 7. */
    err = netconn_bind(conn, NULL, 7);
    
    if (err == ERR_OK) {
      /* Tell connection to go into listening mode. */
      netconn_listen(conn);
    
      while (1) {
        /* Grab new connection. */
        newconn = netconn_accept(conn);
    
        /* Process the new connection. */
        if (newconn) {
          struct netbuf *buf;
          void *data;
          u16_t len;
      
          while ((buf = netconn_recv(newconn)) != NULL) {
            do {
              netbuf_data(buf, &data, &len);
              netconn_write(newconn, data, len, NETCONN_COPY);
          
            } while (netbuf_next(buf) >= 0);
          
            netbuf_delete(buf);
          }
        
          /* Close connection and discard connection identifier. */
          netconn_close(newconn);
          netconn_delete(newconn);
        }
      }
    } else {
      printf(" can not bind TCP netconn");
    }
  } else {
    printf("can not create TCP netconn");
  }
}
Ejemplo n.º 6
0
void ICACHE_FLASH_ATTR
_setBulbState(int idx, uint16_t state) {
  struct netconn * sendconn;
  struct netbuf * sendbuf;
  char * data;
  err_t ret;

  if (!network_ready) return;

  sendconn = netconn_new( NETCONN_UDP );
  if (sendconn == NULL) {
    os_printf("[setbulb] Couldn't get netconn\r\n");
    return;
  }
  sendbuf = netbuf_new();
  if (sendbuf == NULL) {
    os_printf("[setbulb] couldn't get sendbuff\r\n");
    return;
  }
  data = netbuf_alloc(sendbuf, 38);
  if (data == NULL) {
    os_printf("[setbulb] couldn't alloc data\r\n");
    return;
  }

  getPktSetBulbPower(data, 38, idx, state);

  ret = netconn_bind(sendconn, &myaddr, 34435);
  if (ret != ERR_OK) {
    os_printf("[setbulb] connect error: %d\r\n", ret);
    return;
  }

  netconn_set_recvtimeout( sendconn, 1000);
  ret = netconn_connect(sendconn, getBulbAddr(idx), 56700);
  if (ret != ERR_OK) {
    os_printf("[setbulb] connect error: %d\r\n", ret);
    return;
  }
  ret = netconn_send(sendconn, sendbuf);
  if (ret != ERR_OK) {
    os_printf("[setbulb] send error: %d\r\n", ret);
  } else {
  }

  netbuf_free(sendbuf);
  netbuf_delete(sendbuf);
  netconn_disconnect(sendconn);
  netconn_delete(sendconn);
}
Ejemplo n.º 7
0
Archivo: main.c Proyecto: DINKIN/bertos
int main(void)
{
	struct netconn *server;

	/* Hardware initialization */
	init();

	proc_new(monitor_process, NULL, KERN_MINSTACKSIZE * 2, NULL);

	dhcp_start(&netif);
	/*
	 * Here we wait for an ip address, but it's not strictly
	 * necessary. The address is obtained in background and
	 * as long as we don't use network functions, we could go
	 * on with initialization
	 */
	while (!netif.ip_addr.addr)
		timer_delay(200);
	kprintf(">>> dhcp ok: ip = ip = %s (kernel %s)\n",
		ip_ntoa(&netif.ip_addr.addr),
		CONFIG_KERN_PREEMPT ? "preempt" : "coop");

	server = netconn_new(NETCONN_TCP);
	netconn_bind(server, IP_ADDR_ANY, 80);
	netconn_listen(server);

	while (1)
	{
		struct netconn *client;
		struct netbuf *rx_buf_conn;
		char *rx_buf;
		u16_t len;

		client = netconn_accept(server);
		if (!client)
			continue;

		tot_req++;
		rx_buf_conn = netconn_recv(client);
		if (rx_buf_conn)
		{
			netbuf_data(rx_buf_conn, (void **)&rx_buf, &len);
			if (rx_buf)
				netconn_write(client, rx_buf, len, NETCONN_COPY);
			netbuf_delete(rx_buf_conn);
		}
		while (netconn_delete(client) != ERR_OK)
			cpu_relax();
	}
}
Ejemplo n.º 8
0
int main(void)
{
    ip6_addr_t addr;
    struct netconn *conn;
    struct netbuf *buf;

    xtimer_sleep(5U);   /* wait 5 sec to bootstrap network */

    ip6addr_aton(TCP_SERVER_ADDR, &addr);
    conn = netconn_new(NETCONN_TYPE_IPV6 | NETCONN_TCP);
    netconn_connect(conn, &addr, TCP_SERVER_PORT);
    puts("Kill TCP server now");
    netconn_recv(conn, &buf);

    return 0;
}
Ejemplo n.º 9
0
/*-----------------------------------------------------------------------------------*/
static void 
tcpecho_thread(void *arg)
{
  struct netconn *conn, *newconn;
  err_t err;
  LWIP_UNUSED_ARG(arg);

  /* Create a new connection identifier. */
  conn = netconn_new(NETCONN_TCP);

  /* Bind connection to well known port number TCP_ECHO_PORT. */
  netconn_bind(conn, IP_ADDR_ANY, TCP_ECHO_PORT);

  /* Tell connection to go into listening mode. */
  netconn_listen(conn);

  while (1) {

    /* Grab new connection. */
    newconn = netconn_accept(conn);
    printf("accepted new connection %p\n", newconn);
    /* Process the new connection. */
    if (newconn != NULL) {
      struct netbuf *buf;
      void *data;
      u16_t len;
      
      while ((buf = netconn_recv(newconn)) != NULL) {
        printf("Recved\n");
        do {
             netbuf_data(buf, &data, &len);
             err = netconn_write(newconn, data, len, NETCONN_COPY);
#if 0
            if (err != ERR_OK) {
              printf("tcpecho: netconn_write: error \"%s\"\n", lwip_strerr(err));
            }
#endif
        } while (netbuf_next(buf) >= 0);
        netbuf_delete(buf);
      }
      printf("Got EOF, looping\n"); 
      /* Close connection and discard connection identifier. */
      netconn_close(newconn);
      netconn_delete(newconn);
    }
  }
}
Ejemplo n.º 10
0
void vBasicWEBServer( void *pvParameters )
{
struct netconn *pxHTTPListener, *pxNewConnection;
struct ip_addr xIpAddr, xNetMast, xGateway;
extern err_t ethernetif_init( struct netif *netif );
static struct netif EMAC_if;

	/* Parameters are not used - suppress compiler error. */
	( void ) pvParameters;


	/* Create and configure the EMAC interface. */
	IP4_ADDR(&xIpAddr,emacIPADDR0,emacIPADDR1,emacIPADDR2,emacIPADDR3);
	IP4_ADDR(&xNetMast,emacNET_MASK0,emacNET_MASK1,emacNET_MASK2,emacNET_MASK3);
	IP4_ADDR(&xGateway,emacGATEWAY_ADDR0,emacGATEWAY_ADDR1,emacGATEWAY_ADDR2,emacGATEWAY_ADDR3);
	netif_add(&EMAC_if, &xIpAddr, &xNetMast, &xGateway, NULL, ethernetif_init, tcpip_input);

	/* make it the default interface */
    netif_set_default(&EMAC_if);

	/* bring it up */
    netif_set_up(&EMAC_if);

	/* Create a new tcp connection handle */

 	pxHTTPListener = netconn_new( NETCONN_TCP );
	netconn_bind(pxHTTPListener, NULL, webHTTP_PORT );
	netconn_listen( pxHTTPListener );

	/* Loop forever */
	for( ;; )
	{
		/* Wait for connection. */
		pxNewConnection = netconn_accept(pxHTTPListener);

		if(pxNewConnection != NULL)
		{
			/* Service connection. */
			vProcessConnection( pxNewConnection );
			while( netconn_delete( pxNewConnection ) != ERR_OK )
			{
				vTaskDelay( webSHORT_DELAY );
			}
		}
	}
}
Ejemplo n.º 11
0
void uart_wifi_debug_init()
{
    uart_wifi_debug_buf=netbuf_new();

 //   int ret;
    if(NULL == (uart_wifi_debug_base_conn = netconn_new(NETCONN_UDP)))
    {
        LOG_WARN( "conn new err...\r\n");
  //      ret = STATE_ERROR;
    }


    if(netconn_bind(uart_wifi_debug_base_conn, IP_ADDR_ANY, 1112) != ERR_OK)
    {
        LOG_WARN( "bind err...\r\n");
    }

}
Ejemplo n.º 12
0
/*!
 * data_udp_rx  thread.
 */
msg_t data_udp_receive_thread(void *p) {
	void * arg __attribute__ ((unused)) = p;

	err_t             err;

	struct netconn    *conn;

	ip_addr_t         ip_addr_sensor;

	chRegSetThreadName("data_udp_receive_thread");

	IMU_A_IP_ADDR(&ip_addr_sensor);

	/*
	 *  Create a new UDP connection handle
	 */
	conn = netconn_new(NETCONN_UDP);
	LWIP_ERROR("data_udp_receive_thread: invalid conn", (conn != NULL), return RDY_RESET;);
Ejemplo n.º 13
0
msg_t data_udp_send_thread(void *p) {
	void * arg __attribute__ ((unused)) = p;

	static const evhandler_t evhndl_mpu9150[]       = {
			data_udp_send_mpu9150_data
	};
	struct EventListener     evl_mpu9150;

	err_t                  err;

	ip_addr_t              ip_addr_sensor;
	ip_addr_t              ip_addr_fc;

	chRegSetThreadName("data_udp_send_thread");

	chEvtRegister(&mpu9150_data_event,           &evl_mpu9150,         0);

	IMU_A_IP_ADDR(&ip_addr_sensor);
	IP_PSAS_FC(&ip_addr_fc);

	mpu9150_mac_info.conn   = netconn_new( NETCONN_UDP );

	/* Bind to the local address, or to ANY address */
	//	netconn_bind(conn, NULL, DATA_UDP_TX_THREAD_PORT ); //local port, NULL is bind to ALL ADDRESSES! (IP_ADDR_ANY)
	err    = netconn_bind(mpu9150_mac_info.conn, &ip_addr_sensor, IMU_A_TX_PORT ); //local port

	if (err == ERR_OK) {
		/* Connect to specific address or a broadcast address */
		/*
		 * \todo Understand why a UDP needs a connect...
		 *   This may be a LwIP thing that chooses between tcp_/udp_/raw_ connections internally.
		 *
		 */
		//	netconn_connect(conn, IP_ADDR_BROADCAST, DATA_UDP_TX_THREAD_PORT );
		err = netconn_connect(mpu9150_mac_info.conn, &ip_addr_fc, FC_LISTEN_PORT_IMU_A );
		if(err == ERR_OK) {
			while (TRUE) {
				chEvtDispatch(evhndl_mpu9150, chEvtWaitOneTimeout(EVENT_MASK(0), MS2ST(50)));
			}
		}
		return RDY_RESET;
	}
	return RDY_RESET;
}
Ejemplo n.º 14
0
static bool tcpsocket_reconnect(TcpSocket *socket)
{
	LOG_ERR("Reconnecting..\n");

	/* Close socket if was open */
	close_socket(socket);

	/* If we are in server mode we do nothing */
	if (socket->handler)
		return false;

	/* Start with new connection */
	socket->sock = netconn_new(NETCONN_TCP);
	if(!socket->sock)
	{
		LOG_ERR("Unabe to alloc new connection\n");
		socket->error = -1;
		goto error;
	}

	socket->error = netconn_bind(socket->sock, socket->local_addr, socket->port);
	if(socket->error != ERR_OK)
	{
		LOG_ERR("Connection error\n");
		goto error;
	}

	socket->error = netconn_connect(socket->sock, socket->remote_addr, socket->port);
	if(socket->error != ERR_OK)
	{
		LOG_ERR("Cannot create socket\n");
		goto error;
	}

	LOG_INFO("connected ip=%d.%d.%d.%d\n", IP_ADDR_TO_INT_TUPLE(socket->remote_addr->addr));
	return true;

error:
	netconn_delete(socket->sock);
	socket->sock = NULL;
	return false;
}
Ejemplo n.º 15
0
void telnet_thread(void *arg)
{
	struct netconn *conn, *newconn;
	struct ip_addr l_ip;
	IP4_ADDR(&l_ip, 192,168,1,2);
  	/* Create a new connection identifier. */
	conn = netconn_new(NETCONN_TCP);

	/* Bind connection to well known port number 7. */
	netconn_bind(conn, &l_ip, 23);

  	/* Tell connection to go into listening mode. */
	netconn_listen(conn);

	while(1)
	{
		newconn = netconn_accept(conn);
		server_client(newconn);
	}
}
Ejemplo n.º 16
0
void tcpecho_entry(void *parameter)
{
	struct netconn *conn, *newconn;
	err_t err;

	/* Create a new connection identifier. */
	conn = netconn_new(NETCONN_TCP);

	/* Bind connection to well known port number 7. */
	netconn_bind(conn, NULL, TCP_ECHO_PORT);

	/* Tell connection to go into listening mode. */
	netconn_listen(conn);

	while(1)
	{
		/* Grab new connection. */
		newconn = netconn_accept(conn);
		/* Process the new connection. */
		if(newconn != NULL)
		{
			struct netbuf *buf;
			void *data;
			u16_t len;

			while((buf = netconn_recv(newconn)) != NULL)
			{
				do
				{
					netbuf_data(buf, &data, &len);
					err = netconn_write(newconn, data, len, NETCONN_COPY);
					if(err != ERR_OK){}
				}
				while(netbuf_next(buf) >= 0);
				netbuf_delete(buf);
			}
			/* Close connection and discard connection identifier. */
			netconn_delete(newconn);
		}
	}
}
Ejemplo n.º 17
0
void 
udpecho_thread(void *arg)
{
  struct netconn *conn;
  struct netbuf *buf;
  struct ip_addr *addr;
  unsigned short port;
  
  conn = netconn_new(NETCONN_UDP);
  netconn_bind(conn, NULL, 7);

  while(1) {
    buf = netconn_recv(conn);
    addr = netbuf_fromaddr(buf);
    port = netbuf_fromport(buf);
    netconn_connect(conn, addr, port);
    netconn_send(conn, buf);
    netbuf_copy(buf, buffer, sizeof(buffer));
    netbuf_delete(buf);
  }
}
Ejemplo n.º 18
0
/**
  * @brief  http server thread 
  * @param arg: pointer on argument(not used here) 
  * @retval None
  */
static void http_server_netconn_thread(void *arg)
{ 
  struct netconn *conn, *newconn;
  err_t err;
  
  /* Create a new TCP connection handle */
  conn = netconn_new(NETCONN_TCP);
  
  if (conn!= NULL)
  {
    /* Bind to port 80 (HTTP) with default IP address */
    err = netconn_bind(conn, NULL, 80);
    
    if (err == ERR_OK)
    {
      /* Put the connection into LISTEN state */
      netconn_listen(conn);
  
      while(1) 
      {
        /* accept any icoming connection */
        newconn = netconn_accept(conn);
      
        /* serve connection */
        http_server_serve(newconn);
      
        /* delete connection */
        netconn_delete(newconn);
      }
    }
    else
    {
      printf("can not bind netconn");
    }
  }
  else
  {
    printf("can not create netconn");
  }
}
Ejemplo n.º 19
0
char* simple_test(void) {
    ip_addr_t destination, self_ip;
    printf("%s()\n", __FUNCTION__);
    struct netconn *conn;
    err_t err;
    struct netbuf *buf;
    void *data;
    u16_t len;

    const char *test_str = "data\n";

    /* Create a new connection identifier. */
    conn = netconn_new(NETCONN_TCP);

    /* Sets the device we want to connect to. */
    IP4_ADDR(&destination, 10, 0, 0, 2);
    IP4_ADDR(&self_ip, 10, 0, 0, 3);

    /* Bind connection to well known port number 7. */
    netconn_bind(conn, &self_ip, 1235);

    printf("Connecting...\n");
    err = netconn_connect(conn, &destination, 1235);

    TEST_ASSERT("TCP connection failed.", err == ERR_OK);

    /* Don't send final \0 */
    err = netconn_write(conn, test_str, strlen(test_str), NETCONN_NOCOPY);

    TEST_ASSERT("Netconn write failed.\n", err == ERR_OK);

    err = netconn_recv(conn, &buf);
    TEST_ASSERT("Recv failed.", err == ERR_OK);

    netbuf_data(buf, &data, &len);
    TEST_ASSERT("Data is not echoed correctly", !strcmp(data, test_str));

    netconn_close(conn);
    return TEST_SUCCESS;
}
Ejemplo n.º 20
0
/**
 * UDP echo server thread.
 */
msg_t udp_echo_server(void *p)
{
  err_t err, recv_err;
  
  LWIP_UNUSED_ARG(p);

  conn = netconn_new(NETCONN_UDP);
  if (conn!= NULL)
  {
    err = netconn_bind(conn, IP_ADDR_ANY, UDP_THREAD_PORT);
    if (err == ERR_OK)
    {
      while (1) 
      {
        recv_err = netconn_recv(conn, &buf);
      
        if (recv_err == ERR_OK) 
        {
          addr = netbuf_fromaddr(buf);
          port = netbuf_fromport(buf);
          netconn_connect(conn, addr, port);
          buf->addr.addr = 0;
          netconn_send(conn,buf);
          netbuf_delete(buf);
        }
      }
    }
    else
    {
      netconn_delete(conn);
      // printf("can not bind netconn");
    }
  }
  else
  {
    // printf("can create new UDP netconn");
  }
  return RDY_OK;
}
static void udpecho_thread(void *arg)
{
    static struct netconn *conn;
    static struct netbuf *buf;
    char buffer[100];
    err_t err;

    LWIP_UNUSED_ARG(arg);
    netif_set_up(&fsl_netif0);
    conn = netconn_new(NETCONN_UDP);
    LWIP_ASSERT("con != NULL", conn != NULL);
    netconn_bind(conn, NULL, 7);
    while (1)
    {
        err = netconn_recv(conn, &buf);
        if (err == ERR_OK)
        {
            if (netbuf_copy(buf, buffer, buf->p->tot_len) != buf->p->tot_len)
            {
                LWIP_DEBUGF(UDPECHO_DBG, ("netbuf_copy failed\r\n"));
            }
            else
            {
                buffer[buf->p->tot_len] = '\0';
                err = netconn_send(conn, buf);
                if (err != ERR_OK)
                {
                    LWIP_DEBUGF(UDPECHO_DBG, ("netconn_send failed: %d\r\n", (int)err));
                }
                else
                {
                    LWIP_DEBUGF(UDPECHO_DBG, ("got %s\r\n", buffer));
                }
            }
            netbuf_delete(buf);
        }
    }
}
Ejemplo n.º 22
0
/*-----------------------------------------------------------------------------------*/
static void udpecho_thread(void *arg)
{
  err_t err, recv_err;
  
  LWIP_UNUSED_ARG(arg);

  conn = netconn_new(NETCONN_UDP);
  if (conn!= NULL)
  {
    err = netconn_bind(conn, IP_ADDR_ANY, 7);
    if (err == ERR_OK)
    {
      while (1) 
      {
        recv_err = netconn_recv(conn, &buf);
      
        if (recv_err == ERR_OK) 
        {
          addr = netbuf_fromaddr(buf);
          port = netbuf_fromport(buf);
          netconn_connect(conn, addr, port);
          buf->addr.addr = 0;
          netconn_send(conn,buf);
          netbuf_delete(buf);
        }
      }
    }
    else
    {
      netconn_delete(conn);
      printf("can not bind netconn");
    }
  }
  else
  {
    printf("can create new UDP netconn");
  }
}
Ejemplo n.º 23
0
/*-----------------------------------------------------------------------------------*/
static void
udpecho_thread(void *arg)
{
  static struct netconn *conn;
  static struct netbuf *buf;
  static ip_addr_t *addr;
  static unsigned short port;
  char buffer[4096];
  err_t err;
  LWIP_UNUSED_ARG(arg);

  conn = netconn_new(NETCONN_UDP);
  LWIP_ASSERT("con != NULL", conn != NULL);
  netconn_bind(conn, NULL, 7);

  while (1) {
    err = netconn_recv(conn, &buf);
    if (err == ERR_OK) {
      addr = netbuf_fromaddr(buf);
      port = netbuf_fromport(buf);
      /*  no need netconn_connect here, since the netbuf contains the address */
      if(netbuf_copy(buf, buffer, buf->p->tot_len) != buf->p->tot_len) {
        LWIP_DEBUGF(LWIP_DBG_ON, ("netbuf_copy failed\n"));
      } else {
        buffer[buf->p->tot_len] = '\0';
        err = netconn_send(conn, buf);
        if(err != ERR_OK) {
          LWIP_DEBUGF(LWIP_DBG_ON, ("netconn_send failed: %d\n", (int)err));
        } else {
          LWIP_DEBUGF(LWIP_DBG_ON, ("got %s\n", buffer));
        }
      }
      netbuf_delete(buf);
    }
  }
}
Ejemplo n.º 24
0
static msg_t rawd_loop(void *data)
{
	struct netconn *nc, *ncnew;
	int ret;

	chRegSetThreadName("net/rawd");

	nc = netconn_new(NETCONN_TCP);
	if (!nc)
		return 1;

	netconn_bind(nc, NULL, RAW_PORT);
	netconn_listen(nc);

	for (;;) {
		ret = netconn_accept(nc, &ncnew);
		if (ret)
			continue;

		rawd_new(ncnew);
	}

	return 0;
}
Ejemplo n.º 25
0
/*-----------------------------------------------------------------------------------*/
void 
udpecho_thread(void *arg)
{
  static struct netconn *conn;
  static struct netbuf *buf;
  static struct ip_addr *addr;
  static unsigned short port;
  char buffer[4096];
  
  conn = netconn_new(NETCONN_UDP);
  netconn_bind(conn, NULL, 7);

  while (1) {
    buf = netconn_recv(conn);
    addr = netbuf_fromaddr(buf);
    port = netbuf_fromport(buf);
    netconn_connect(conn, addr, port);
    netbuf_copy(buf, buffer, buf->p->tot_len);
    buffer[buf->p->tot_len] = '\0';
    netconn_send(conn, buf);
    printf("got %s\n", buffer);
    netbuf_delete(buf);
  }
}
Ejemplo n.º 26
0
static void LwipInitTask(void* pvArguments) {
    err_t err;
  struct netif fsl_netif0;
  ip_addr_t fsl_netif0_ipaddr, fsl_netif0_netmask, fsl_netif0_gw;

  char msg[] = "This is my message";

  (void)pvArguments;

  // Init lwip stack
  tcpip_init(NULL,NULL);
  printf("%s: lwip init called ..\n", __FUNCTION__);

  // Setup IP Config for DHCP ...
  IP4_ADDR(&fsl_netif0_ipaddr, 0,0,0,0);
  IP4_ADDR(&fsl_netif0_netmask, 0,0,0,0);
  IP4_ADDR(&fsl_netif0_gw, 0,0,0,0);

  /* Add a network interface to the list of lwIP netifs. */
  netif_add(&fsl_netif0, &fsl_netif0_ipaddr, &fsl_netif0_netmask, &fsl_netif0_gw, NULL, ethernetif_init, ethernet_input);
  /* Set the network interface as the default network interface. */
  netif_set_default(&fsl_netif0);
  /* obtain the IP address, default gateway and subnet mask by using DHCP*/
  err = dhcp_start(&fsl_netif0);

  printf("%s : Started DCHP request (%s)\n", __FUNCTION__, lwip_strerr(err));

  for(int i=0; i < DHCP_TIMEOUT && fsl_netif0.dhcp->state != DHCP_BOUND; i++) {
    printf("%s : Current DHCP State : %d\n", __FUNCTION__, fsl_netif0.dhcp->state);
    // Wait a second
    vTaskDelay(1000/portTICK_PERIOD_MS);
  }

  // Make it active ...
  netif_set_up(&fsl_netif0);

  printf("%s : Interface is up : %d\n", __FUNCTION__, fsl_netif0.dhcp->state);
  printf("%s : IP %s\n", __FUNCTION__, ipaddr_ntoa(&fsl_netif0.ip_addr));
  printf("%s : NM %s\n", __FUNCTION__, ipaddr_ntoa(&fsl_netif0.netmask));
  printf("%s : GW %s\n", __FUNCTION__, ipaddr_ntoa(&fsl_netif0.gw));

  if (fsl_netif0.dhcp->state == DHCP_BOUND) {
    // Send out some UDP data
    struct netconn* pConnection;

    // Create UDP connection
    pConnection = netconn_new(NETCONN_UDP);
    // Connect to local port
    err = netconn_bind(pConnection, IP_ADDR_ANY, 12345);
    printf("%s : Bound to IP_ADDR_ANY port 12345 (%s)\n", __FUNCTION__, lwip_strerr(err));

    err = netconn_connect(pConnection, IP_ADDR_BROADCAST, 12346 );
    printf("%s : Connected to IP_ADDR_BROADCAST port 12346 (%s)\n", __FUNCTION__, lwip_strerr(err));

    for(int i = 0; i < 10; i++ ){
      struct netbuf* buf = netbuf_new();
        void* data = netbuf_alloc(buf, sizeof(msg));

        memcpy (data, msg, sizeof (msg));
        err = netconn_send(pConnection, buf);
      printf("%s : Sending to IP_ADDR_BROADCAST port 12346 (%s)\n", __FUNCTION__, lwip_strerr(err));

        netbuf_delete(buf); // De-allocate packet buffer

        // Wait a second
      vTaskDelay(1000/portTICK_PERIOD_MS);
    }

    err = netconn_disconnect(pConnection);
    printf("%s : Disconnected from IP_ADDR_BROADCAST port 12346 (%s)\n", __FUNCTION__, lwip_strerr(err));

    err = netconn_delete(pConnection);
    printf("%s : Deleted connection (%s)\n", __FUNCTION__, lwip_strerr(err));
  }
  // Wait a second
  vTaskDelay(1000/portTICK_PERIOD_MS);

  /* finish the lease of the IP address */
  err = dhcp_release(&fsl_netif0);
  printf("%s : DHCP Release (%s)\n", __FUNCTION__, lwip_strerr(err));

  for(;;) {};
}
Ejemplo n.º 27
0
/* telnet server thread entry */
void telnet_thread(void* parameter)
{
    rt_err_t result,err;
    rt_uint32_t event;
    struct netbuf *buf;
    struct netconn *conn, *newconn;

    /* Create a new connection identifier. */
    conn = netconn_new(NETCONN_TCP);

    /* Bind connection to well known port number 7. */
    netconn_bind(conn, NULL, TELNET_PORT);

    /* Tell connection to go into listening mode. */
    netconn_listen(conn);

    /* register telnet device */
    telnet->device.type     = RT_Device_Class_Char;
    telnet->device.init     = telnet_init;
    telnet->device.open     = telnet_open;
    telnet->device.close    = telnet_close;
    telnet->device.read     = telnet_read;
    telnet->device.write    = telnet_write;
    telnet->device.control  = telnet_control;

    /* no private */
    telnet->device.user_data = RT_NULL;

    /* register telnet device */
    rt_device_register(&telnet->device, "telnet",
                       RT_DEVICE_FLAG_RDWR | RT_DEVICE_FLAG_STREAM);

    while (1)
    {
        rt_kprintf("telnet server waiting for connection\n");

        /* Grab new connection. */
        err = netconn_accept(conn, &newconn);
        //if (err == RT_EOK) continue;

        /* set network rx call back */
        newconn->callback = rx_callback;

        rt_kprintf("new telnet connection, switch console to telnet...\n");

        /* Process the new connection. */
        /* set console */
        rt_console_set_device("telnet");
        /* set finsh device */
        finsh_set_device("telnet");

        /* set init state */
        telnet->state = STATE_NORMAL;

        telnet->echo_mode = finsh_get_echo();
        /* disable echo mode */
        finsh_set_echo(0);

        while (1)
        {
            /* try to send all data in tx ringbuffer */
            telnet_process_tx(telnet, newconn);

            /* receive network event */
            result = rt_event_recv(telnet->nw_event,
                                   NW_MASK, RT_EVENT_FLAG_OR | RT_EVENT_FLAG_CLEAR,
                                   RT_TICK_PER_SECOND, &event);
            if (result == RT_EOK)
            {
                /* get event successfully */
                if (event & NW_RX)
                {
                    /* do a rx procedure */
                    err= netconn_recv(newconn, &buf);
                    if (buf != RT_NULL)
                    {
                        rt_uint8_t *data;
                        rt_uint16_t length;

                        /* get data */
                        netbuf_data(buf, (void**)&data, &length);
                        telnet_process_rx(telnet, data, length);
                        /* release buffer */
                        netbuf_delete(buf);
                    }
                    else
                    {
                        if (newconn->last_err == ERR_CLSD)
                        {
                            /* close connection */
                            telnet_process_close(telnet, newconn);
                            break;
                        }
                    }
                }

                if (event & NW_TX)
                    telnet_process_tx(telnet, newconn);

                if (event & NW_CLOSED)
                {
                    /* process close */
                    telnet_process_close(telnet, newconn);
                    break;
                }
            }
            else if (result == -RT_ETIMEOUT)
            {
                if (newconn->state == NETCONN_CLOSE)
                {
                    telnet_process_close(telnet, newconn);
                    break;
                }
            }
        }
    }
}
Ejemplo n.º 28
0
void broadcast_temperature(void *pvParameters)
{

    uint8_t amount = 0;
    uint8_t sensors = 1;
    ds18b20_addr_t addrs[sensors];
    float results[sensors];
    
    // Use GPIO 13 as one wire pin. 
    uint8_t GPIO_FOR_ONE_WIRE = 13;

    char msg[100];

    // Broadcaster part
    err_t err;

    while(1) {

        // Send out some UDP data
        struct netconn* conn;

        // Create UDP connection
        conn = netconn_new(NETCONN_UDP);

        // Connect to local port
        err = netconn_bind(conn, IP_ADDR_ANY, 8004);

        if (err != ERR_OK) {
            netconn_delete(conn);
            printf("%s : Could not bind! (%s)\n", __FUNCTION__, lwip_strerr(err));
            continue;
        }

        err = netconn_connect(conn, IP_ADDR_BROADCAST, 8005);

        if (err != ERR_OK) {
            netconn_delete(conn);
            printf("%s : Could not connect! (%s)\n", __FUNCTION__, lwip_strerr(err));
            continue;
        }

        for(;;) {
            // Search all DS18B20, return its amount and feed 't' structure with result data.
            amount = ds18b20_scan_devices(GPIO_FOR_ONE_WIRE, addrs, sensors);

            if (amount < sensors){
                printf("Something is wrong, I expect to see %d sensors \nbut just %d was detected!\n", sensors, amount);
            }

            ds18b20_measure_and_read_multi(GPIO_FOR_ONE_WIRE, addrs, sensors, results);
            for (int i = 0; i < sensors; ++i)
            {
                // ("\xC2\xB0" is the degree character (U+00B0) in UTF-8)
                sprintf(msg, "Sensor %08x%08x reports: %f \xC2\xB0""C\n", (uint32_t)(addrs[i] >> 32), (uint32_t)addrs[i], results[i]);
                printf("%s", msg);

                struct netbuf* buf = netbuf_new();
                void* data = netbuf_alloc(buf, strlen(msg));

                memcpy (data, msg, strlen(msg));
                err = netconn_send(conn, buf);

                if (err != ERR_OK) {
                    printf("%s : Could not send data!!! (%s)\n", __FUNCTION__, lwip_strerr(err));
                    continue;
                }
                netbuf_delete(buf); // De-allocate packet buffer
            }
            vTaskDelay(1000/portTICK_PERIOD_MS);
        }

        err = netconn_disconnect(conn);
        printf("%s : Disconnected from IP_ADDR_BROADCAST port 12346 (%s)\n", __FUNCTION__, lwip_strerr(err));

        err = netconn_delete(conn);
        printf("%s : Deleted connection (%s)\n", __FUNCTION__, lwip_strerr(err));

        vTaskDelay(1000/portTICK_PERIOD_MS);
    }
}
/**
  * @brief  TCP server thread 
  * @param arg: pointer on argument(not used here) 
  * @retval None
  * TCP 连接线程,有它创建其他线程
  */
static void tcp_netconn_thread(void *arg)
{ 
  struct netconn *conn, *newconn;
  err_t err;
  int i;
  //char disp[20]="get a connect!\0";
  char thread_name[16];
  int thread_num=0;
  /* Create a new TCP connection handle */
  /*创建返回数据处理进程,该进程处理feedback数据*/
  xTaskCreate(NetFeedBack_thread, "FEEDBACKPROCESS", NET_FEEDBACK_THREAD_STACKSIZE, NULL,FEED_BACK_PRIO, NULL);
  conn = netconn_new(NETCONN_TCP);
  conn->recv_timeout = 10000;              //等待连接超时时间为10s

  if (conn!= NULL)
  {
    /* Bind to port 10000 with default IP address */
    err = netconn_bind(conn, NULL, 10000);
    
    if (err == ERR_OK)
    {
      /* Put the connection into LISTEN state */
      netconn_listen(conn);
  	  printf(" start to listen the connect \r\n");
      while(1) 
      {
        /* accept any icoming connection */
        newconn = netconn_accept(conn);
		if(NULL != newconn)					  //成功连接
		{
			printf("a client connected to the server ");
	      	if(client_used<MAX_CLIENT_NUM)    //连接数小于最大连接数
			{
				client_used++;
				for(i=0;i<MAX_CLIENT_NUM;i++)
				{
					if(user_info[i].conn==NULL)
					{
						user_info[i].conn =  newconn;
					    user_info[i].is_used = 1;
						user_info[i].user_id = ++thread_num;
						user_info[i].period = 0;
						/*设定新任务名字*/
						sprintf(thread_name,"USERPROCESS%d\0",thread_num);
						/*创建新任务*/
						LCD_DisplayStringLine(Line3, (uint8_t*)thread_name);
						printf(thread_name);
						printf("  new client thread\r\n");
						//netconn_write(newconn,thread_name,13,NETCONN_NOCOPY);
						xTaskCreate(NetUserProcess_thread, thread_name, NET_USERPROCESS_STACKSIZE ,(void*)&user_info[i], USERPROCESS_THREAD_PRIO,NULL);
						break;
					}
				}	
			}
			else
			{
				//超出最大连接数据,关闭连接
				netconn_write(newconn,"net user is reach the max number\r\n\0",32,NETCONN_COPY);
				netconn_close(newconn);
				printf("net user is reach the max number,close it\r\n\0");
			}
		}
		else
		{
			  vTaskDelay(100);
		} 
        /* serve connection */
        //http_server_serve(newconn);
      
        /* delete connection */
        //netconn_delete(newconn);
      }
    }
    else
    {
      printf("can not bind netconn");
    }
  }
  else
  {
     printf("can not create netconn");
  }
}
Ejemplo n.º 30
0
/*! \brief WEB server main task
 *         check for incoming connection and process it
 *
 */
portTASK_FUNCTION( vBasicWEBServer, pvParameters )
{
  struct netconn  *pxHTTPListener, *pxNewConnection;
  portCHAR        token[6];
  portSHORT       TaskIdx;
  portLONG        err_count;


  /* initialize current nb connection */
  sCurrentNbHTTPConn = 0;
  vSemaphoreCreateBinary( xMutexNbHTTPConn );

  x_default_page_len = strlen( pcDefaultPage );

  /* HTTP configuration. */
  // Get the xCFGMutex.
  if( pdFALSE == x_supervisor_SemaphoreTake( xCFGMutex, 0 ) )
  {
    // Failed to get the CFG mutex, use the default HTTP config.
    webHttpPort = webHTTP_PORT;
  }
  // Mutex has been taken
  else
  {
    // get the field value for port number
    if (config_file_get_value(HTTP_CONFIG_FILE, "port" , token) >= 0)
    {
      sscanf(token, "%u", &webHttpPort);
    }
    // if it does not exist, use the default value
    else
    {
      webHttpPort = webHTTP_PORT;
    }
    // Release the xCFGMutex.
    x_supervisor_SemaphoreGive( xCFGMutex );
  }

  // Create a new tcp connection handle
  pxHTTPListener = netconn_new( NETCONN_TCP );
  netconn_bind(pxHTTPListener, NULL, webHttpPort );
  netconn_listen( pxHTTPListener );
  // Loop forever
  for( ;; )
  {
#if ( (LWIP_VERSION) == ((1U << 24) | (3U << 16) | (2U << 8) | (LWIP_VERSION_RC)) )
    /* Wait for a first connection. */
    pxNewConnection = netconn_accept(pxHTTPListener);
#else
    while(netconn_accept(pxHTTPListener, &pxNewConnection) != ERR_OK)
    {
		vTaskDelay( webSHORT_DELAY );
	}
#endif
    if(pxNewConnection != NULL)
    {
      /* read the nb of connection, no need to use Mutex */
      while( webHTTP_NB_CONN == sCurrentNbHTTPConn )
      {
        vTaskDelay( webSHORT_DELAY );
      }

      // Take the xWEBMutex if there are no active connections.
      if( 0 == sCurrentNbHTTPConn )
      {
         if( pdFALSE == x_supervisor_SemaphoreTake( xWEBMutex, 0 ) )
         {
            prvweb_SendErrorPage( pxNewConnection, 503, "", "AVR32 UC3 Web server under maintenance." );
            // Close the connection.
            vTaskDelay( 50 );
            err_count = 4;
            while( netconn_close( pxNewConnection ) != ERR_OK )
            {
               if (--err_count == 0) break;
               vTaskDelay( webSHORT_DELAY );
            }
            err_count = 4;
            while( netconn_delete( pxNewConnection ) != ERR_OK )
            {
               if (--err_count == 0) break;
               vTaskDelay( webSHORT_DELAY );
            }
            continue;
         }
      }

      // Find an available spot in the tTaskHandle[] array.
      // We're sure to find one because sCurrentNbHTTPConn < webHTTP_NB_CONN.
      TaskIdx = 0;
      while( NULL != tTaskHandle[TaskIdx] ) TaskIdx++;

      while( xSemaphoreTake(xMutexNbHTTPConn , portMAX_DELAY ) != pdTRUE );
      sCurrentNbHTTPConn++;
      // Release the mutex.
      xSemaphoreGive( xMutexNbHTTPConn );

      // TRACE_COM2( "nb http conn:%d",sCurrentNbHTTPConn );

      if( xTaskCreate( prvweb_ProcessSingleConnection,
                                ( signed portCHAR * )"WCONN",
                                webHTTP_CONNECTION_STACK_SIZE, pxNewConnection,
                                webHTTP_CONNECTION_PRIORITY,
                                &tTaskHandle[TaskIdx] ) != pdPASS)
      {
          TRACE_COM2( "xTaskCreate() alloc error" );

          /* delete connection */
          err_count = 4;
          while( netconn_close( pxNewConnection ) != ERR_OK )
          {
            if (--err_count == 0) break;
            vTaskDelay( webSHORT_DELAY );
          }
          err_count = 4;
          while( netconn_delete( pxNewConnection ) != ERR_OK )
          {
            if (--err_count == 0) break;
            vTaskDelay( webSHORT_DELAY );
          }

          while( xSemaphoreTake(xMutexNbHTTPConn , portMAX_DELAY ) != pdTRUE );
          sCurrentNbHTTPConn--;
          // Release the xWEBMutex if there are no active connections.
          if( 0 == sCurrentNbHTTPConn )
          {
             x_supervisor_SemaphoreGive( xWEBMutex );
          }
          // Release the mutex.
          xSemaphoreGive( xMutexNbHTTPConn );
      }// end if task not created
    }// end if new connection

  }// end infinite loop
}