Exemple #1
0
static int processSrqIo(user_data_t * user_data) {
    struct netbuf *inbuf;
    char* buf;
    u16_t buflen;    

    if (netconn_recv(user_data->control_io, &inbuf) != ERR_OK) {
        goto fail1;
    }
    if (netconn_err(user_data->control_io) != ERR_OK) {
        goto fail2;
    }
    
    netbuf_data(inbuf, (void**) &buf, &buflen);

    if (buflen > 0) {
        // TODO process control
    } else {
        //goto fail2;
    }
    
    netbuf_delete(inbuf);

    return 0;
    
fail2:
    netbuf_delete(inbuf);
fail1:
    closeSrqIo(user_data);
    
    return 0;
}
Exemple #2
0
static int processIo(user_data_t * user_data) {
    struct netbuf *inbuf;
    char* buf;
    u16_t buflen;    

    if (netconn_recv(user_data->io, &inbuf) != ERR_OK) {
        goto fail1;
    }
    if (netconn_err(user_data->io) != ERR_OK) {
        goto fail2;
    }
    
    netbuf_data(inbuf, (void**) &buf, &buflen);

    if (buflen > 0) {
        SCPI_Input(&scpi_context, buf, buflen);
    } else {
        //goto fail2;
    }
    
    netbuf_delete(inbuf);
    
    return 0;
    
fail2:
    netbuf_delete(inbuf);
fail1:
    closeIo(user_data);
    
    return 0;
}
/**
  * @brief serve tcp connection  
  * @param conn: pointer on connection structure 
  * @retval None
  */
void http_server_serve(struct netconn *conn) 
{
  struct netbuf *inbuf;
  err_t recv_err;
  char* buf;
  u16_t buflen;
  struct fs_file * file;
  
  /* Read the data from the port, blocking if nothing yet there. 
   We assume the request (the part we care about) is in one netbuf */
  recv_err = netconn_recv(conn, &inbuf);
  
  if (recv_err == ERR_OK)
  {
    if (netconn_err(conn) == ERR_OK) 
    {
      netbuf_data(inbuf, (void**)&buf, &buflen);
    
      /* Is this an HTTP GET command? (only check the first 5 chars, since
      there are other formats for GET, and we're keeping it very simple )*/
      if ((buflen >=5) && (strncmp(buf, "GET /", 5) == 0))
      {
        /* Check if request to get ST.gif */ 
        if (strncmp((char const *)buf,"GET /STM32F4xx_files/ST.gif",27)==0)
        {
          file = fs_open("/STM32F4xx_files/ST.gif"); 
          netconn_write(conn, (const unsigned char*)(file->data), (size_t)file->len, NETCONN_NOCOPY);
          fs_close(file);
        }   
        /* Check if request to get stm32.jpeg */
        else if (strncmp((char const *)buf,"GET /STM32F4xx_files/stm32.jpg",30)==0)
        {
          file = fs_open("/STM32F4xx_files/stm32.jpg"); 
          netconn_write(conn, (const unsigned char*)(file->data), (size_t)file->len, NETCONN_NOCOPY);
          fs_close(file);
        }
        else if (strncmp((char const *)buf,"GET /STM32F4xx_files/logo.jpg", 29) == 0)                                           
        {
          /* Check if request to get ST logo.jpg */
          file = fs_open("/STM32F4xx_files/logo.jpg"); 
          netconn_write(conn, (const unsigned char*)(file->data), (size_t)file->len, NETCONN_NOCOPY);
          fs_close(file);
        }
        else if(strncmp(buf, "GET /STM32F4xxTASKS.html", 24) == 0)
        {
           /* Load dynamic page */
           DynWebPage(conn);
        }
        else if((strncmp(buf, "GET /STM32F4xx.html", 19) == 0)||(strncmp(buf, "GET / ", 6) == 0)) 
        {
          /* Load STM32F4x7 page */
          file = fs_open("/STM32F4xx.html"); 
          netconn_write(conn, (const unsigned char*)(file->data), (size_t)file->len, NETCONN_NOCOPY);
          fs_close(file);
        }
        else 
        {
          /* Load Error page */
          file = fs_open("/404.html"); 
          netconn_write(conn, (const unsigned char*)(file->data), (size_t)file->len, NETCONN_NOCOPY);
          fs_close(file);
        }
      }      
    }
  }
  /* Close the connection (server closes in HTTP) */
  netconn_close(conn);
  
  /* Delete the buffer (netconn_recv gives us ownership,
   so we have to make sure to deallocate the buffer) */
  netbuf_delete(inbuf);
}
Exemple #4
0
/*
 * Read data from socket.
 *
 * The read return the bytes that had been received if they are less than we request too.
 * Otherwise if the byte that we want read are less that the received bytes, we return only
 * the requested bytes. To get the remaning bytes we need to make an others read, until the
 * buffer is empty.
 * When there are not any more bytes, a new read takes data from remote socket.
 */
static size_t tcpsocket_read(KFile *fd, void *buf, size_t len)
{
	TcpSocket *socket = TCPSOCKET_CAST(fd);

	char *data;
	uint16_t read_len = 0;

	if (socket->remaning_data_len <= 0)
	{
		LOG_INFO("No byte left.\n");
		netbuf_delete(socket->rx_buf_conn);
	}
	else /* We had byte into buffer use that */
	{
		LOG_INFO("Read stored bytes.\n");
		if (!socket->rx_buf_conn)
		{
			LOG_ERR("Byte stored are corrupted!\n");
			socket->remaning_data_len = 0;
			return 0;
		}
		uint16_t tot_data_len = 0;
		netbuf_data(socket->rx_buf_conn, (void **)&data, &tot_data_len);

		if (data)
		{
			ASSERT(((int)tot_data_len - (int)socket->remaning_data_len) >= 0);
			size_t chunk_len = MIN((size_t)(socket->remaning_data_len), len);
			memcpy((char *)buf, &data[tot_data_len - socket->remaning_data_len], chunk_len);

			socket->remaning_data_len -= chunk_len;
			return chunk_len;
		}
		else
		{
			LOG_ERR("No valid data to read\n");
			socket->remaning_data_len = 0;
			netbuf_delete(socket->rx_buf_conn);
			return 0;
		}
	}

	/* Try reconnecting if our socket isn't valid */
	if ((socket->sock == NULL) && !tcpsocket_reconnect(socket))
		return 0;

	while (len)
	{
		LOG_INFO("Get bytes from socket.\n");
		socket->rx_buf_conn = netconn_recv(socket->sock);

		socket->error = netconn_err(socket->sock);
		if (socket->error != ERR_OK)
		{
			LOG_ERR("While recv %d\n", socket->error);
			close_socket(socket);
			return 0;
		}

		size_t chunk_len = 0;
		uint16_t data_len = 0;
		if (socket->rx_buf_conn)
		{
			netbuf_data(socket->rx_buf_conn, (void **)&data, &data_len);

			if (data)
			{
				chunk_len = MIN((size_t)data_len, len);
				memcpy(buf, data, chunk_len);

				socket->remaning_data_len = data_len - chunk_len;
			}

			if (socket->remaning_data_len <= 0)
			{
				netbuf_delete(socket->rx_buf_conn);
				socket->rx_buf_conn = NULL;
				socket->remaning_data_len = 0;
				return chunk_len;
			}
		}

		len -= chunk_len;
		read_len += chunk_len;
	}

	return read_len;
}
/**
  * @brief serve tcp connection  
  * @param conn: pointer on connection structure 
  * @retval None
  */
void http_server_serve(struct netconn *conn) 
{
  struct netbuf *inbuf;
  err_t recv_err;
  char* buf;
  u16_t buflen;
  //struct fs_file * file;
  
  /* Read the data from the port, blocking if nothing yet there. 
   We assume the request (the part we care about) is in one netbuf */
  recv_err = netconn_recv(conn, &inbuf);
  
  if (recv_err == ERR_OK)
  {
    if (netconn_err(conn) == ERR_OK) 
    {
      netbuf_data(inbuf, (void**)&buf, &buflen);
    
      /* Is this an HTTP GET command? (only check the first 5 chars, since
      there are other formats for GET, and we're keeping it very simple )*/
      if ((buflen >=5) && (strncmp(buf, "GET /", 5) == 0))
      {
        
        if(strncmp(buf, "GET /task", 9) == 0)
        {
           /* Load dynamic page */
           DynWebPage(conn);
        }
				
				else if((strncmp(buf, "GET /light.html?code=1", 15) == 0)||(strncmp(buf, "GET / ", 6) == 0)) 
        {
          netconn_write(conn, (const unsigned char*)(file__light_html->data), (size_t)file__light_html->len, NETCONN_NOCOPY);
					OnActive = 1;
					OnActive = 1;
        }
				else if((strncmp(buf, "GET /light.html?code=0", 15) == 0)||(strncmp(buf, "GET / ", 6) == 0)) 
        {
          netconn_write(conn, (const unsigned char*)(file__light_html->data), (size_t)file__light_html->len, NETCONN_NOCOPY);
					OffActive = 1;
        }
				 else if((strncmp(buf, "GET /light.html", 15) == 0)||(strncmp(buf, "GET / ", 6) == 0)) 
        {
          netconn_write(conn, (const unsigned char*)(file__light_html->data), (size_t)file__light_html->len, NETCONN_NOCOPY);
        }
        else 
        {
          /* Load Error page */
          //file = fs_open("/404.html"); 
          netconn_write(conn, (const unsigned char*)(file__404_html->data), (size_t)file__404_html->len, NETCONN_NOCOPY);
          //fs_close(file);
        }
      }      
    }
  }
  /* Close the connection (server closes in HTTP) */
  netconn_close(conn);
  
  /* Delete the buffer (netconn_recv gives us ownership,
   so we have to make sure to deallocate the buffer) */
  netbuf_delete(inbuf);
}
void wanwuyun_task(void * pvParameters)
{
	//创建Queue
	SENSOR_STRUCT *pRxSensorFrame;
	portBASE_TYPE  xStatus; 
	struct ip_addr WanWuYunIPaddr;
	static err_t err,recv_err;
	
	//网络相关结构体
	struct   netbuf *inbuf;
	uint8_t  *buf;
	uint16_t buflen;
	//成功发送 = true,其他状态为 = false	
	bool wan_send_success_flag = false;	
	
	//创建Json的结构体
	cJSON   *DataUpReqJson, *RowJson, *DataUpResJson,*fld;
	char 	*DataOut;
	
	char double_string[]={0};
#if 0	
	cJSON   *SignInReqJson ,*SignInResJson;
	SignInReqJson=cJSON_CreateObject();
	cJSON_AddStringToObject(SignInReqJson, "username", "jackeyjiang");
	cJSON_AddStringToObject(SignInReqJson, "accessid", "AMFJA2V5AMLHBMCXNDI5NZE2NDIXMTMW");
	cJSON_AddStringToObject(SignInReqJson, "appid", "9785739981");
	cJSON_AddStringToObject(SignInReqJson, "dev_id", "stm32_test");
	DataOut = cJSON_Print(DataUpReqJson);
	cJSON_Delete(SignInReqJson);
	vPortFree(DataOut);
	
	DataUpReqJson=cJSON_CreateArray();
	cJSON_AddItemToObject(DataUpReqJson,NULL,fld = cJSON_CreateObject());
	cJSON_AddStringToObject(fld, "seckey", "HgqoOLTlav5jTsefyj3nL5AkRu8UAFRf");
	cJSON_AddItemToObject(fld, "row", RowJson=cJSON_CreateObject());
	cJSON_AddStringToObject(RowJson, "DEV_ID", "stm32_test");
	cJSON_AddNumberToObject(RowJson, "TEMPERATURE", 12.5);
	cJSON_AddNumberToObject(RowJson, "LATITUDE", 12.7);
	cJSON_AddNumberToObject(RowJson, "LONGITUDE", 12.8);
	//转换数据为cJSON数据
	DataOut = cJSON_Print(DataUpReqJson);
	cJSON_Delete(DataUpReqJson);
	printf("%s",DataOut);
	vPortFree(DataOut);	

	//解析返回的Json数据
	SignInResJson = cJSON_Parse(SignInResponse);
	if (!SignInResJson) 
	vPrintString("Error before: [%s]\n",cJSON_GetErrorPtr());
	else {};
	DataUpResJson = cJSON_Parse(DataUpResponse);
	if (!DataUpResJson) vPrintString("Error before: [%s]\n",cJSON_GetErrorPtr());
	else {};	
#endif	
	//创建传感器队列
	pRxSensor_xQueue = xQueueCreate( 2, sizeof(  struct _SENSOR_STRUCT * ) );

	//建立短连接,接收到队列传过来的数据,将其打包成json数据传送到万物云。
	IP4_ADDR( &WanWuYunIPaddr, WANWUYUN_IP_ADDR0, WANWUYUN_IP_ADDR1, WANWUYUN_IP_ADDR2, WANWUYUN_IP_ADDR3 );
	
	while(1)
	{
		/* Create a new connection identifier. */
		STM_EVAL_LEDOff(LED2);
		wanwuyun_clientconn = netconn_new_with_callback(NETCONN_TCP,wanwuyun_callback); //测试
		if (wanwuyun_clientconn!=NULL)
		{  
			/*built a connect to wanwuyun.com server*/
			//netconn_set_nonblocking(wanwuyun_clientconn, 1); //测试
			err = netconn_connect(wanwuyun_clientconn,&WanWuYunIPaddr,WANWUYUN_SERVER_PORT);
			if (err != ERR_OK)  netconn_delete(wanwuyun_clientconn); 
			else if (err == ERR_OK)
			{
				STM_EVAL_LEDOn(LED2);
				vPrintString("netconn_connect wanwuyun_clientconn\r\n");
				/*timeout to wait for new data to be received <Avoid death etc.> */
				netconn_set_sendtimeout(wanwuyun_clientconn,300);
				netconn_set_recvtimeout(wanwuyun_clientconn,700);
				while(!ERR_IS_FATAL(wanwuyun_clientconn->last_err)) 
				{
					STM_EVAL_LEDToggle(LED3);
					xStatus = xQueueReceive(pRxSensor_xQueue,&(pRxSensorFrame),( portTickType ) 1 );
					if(xStatus == pdPASS)
					{	
						//提取结构体中的数据
						DataUpReqJson=cJSON_CreateArray();
						cJSON_AddItemToObject(DataUpReqJson,NULL,fld = cJSON_CreateObject());
						cJSON_AddStringToObject(fld, "seckey", "HgqoOLTlav5jTsefyj3nL5AkRu8UAFRf");
						cJSON_AddItemToObject(fld, "row", RowJson=cJSON_CreateObject());
						cJSON_AddStringToObject(RowJson, "DEV_ID", "stm32_test");
						sprintf(double_string,"%f",pRxSensorFrame->temperature[0]);
						cJSON_AddStringToObject(RowJson, "TEMPERATURE", double_string);
						sprintf(double_string,"%f",pRxSensorFrame->latitude[0]);
						cJSON_AddStringToObject(RowJson, "LATITUDE", double_string);
						sprintf(double_string,"%f",pRxSensorFrame->longitude[0]);
						cJSON_AddStringToObject(RowJson, "LONGITUDE", double_string);
						//转换数据为cJSON数据
						DataOut = cJSON_Print(DataUpReqJson);
						//printf("%d",strlen(DataOut));
						cJSON_Delete(DataUpReqJson);
						vPrintString("%s\r\n",DataOut);
						//vPortFree(DataOut);					
						err=netconn_write(wanwuyun_clientconn,\
							DataOut,strlen(DataOut),\
							NETCONN_COPY);	
						if(err != ERR_OK)  
						{
							vPortFree(DataOut);
							vPrintString("StatuUploadReq erro code is %d\r\n",err);
							break;
						}	
						else
						{
							wan_send_success_flag = true; //表示数据已经发送了
							vPortFree(DataOut);	
						}
					}
					//netconn_recved(wanwuyun_clientconn,100); //测试
					recv_err = netconn_recv(wanwuyun_clientconn, &inbuf);
					if (recv_err == ERR_OK)
					{
						if (netconn_err(wanwuyun_clientconn) == ERR_OK)
						{ 
							netbuf_data(inbuf, (void**)&buf, &buflen);
							DataUpResJson = cJSON_Parse((char *)buf);
							DataOut = cJSON_Print(DataUpResJson);
							vPrintString("%s\r\n",DataOut);
							netbuf_delete(inbuf);
							wan_send_success_flag = false;
							//使用短链接,成功后跳出while(1)
							//break;
						}
						else
						{
							vPrintString("recv_err != ERR_OK \r\n");
						}
					}
					#if 1  //测试当断开连接的时候的状态
					else if((recv_err == ERR_TIMEOUT)&&(wan_send_success_flag == true)) 
					{
						wan_send_success_flag = false;
						vPrintString("recv_err == %d\r\n",recv_err);
						netconn_close(wanwuyun_clientconn);
						netbuf_delete(inbuf);
						netconn_delete(wanwuyun_clientconn);
						//为发送的数据重新入队
						xQueueSendToFront(pRxSensor_xQueue,&(pRxSensorFrame),( portTickType )1);
						break;
					}
					#endif
				}
			}
		}
	}	
}
/**
  * @brief serve tcp connection  
  * @param conn: pointer on connection structure 
  * @retval None
  */
void http_server_serve(struct netconn *conn) 
{
  struct netbuf *inbuf;
  err_t recv_err;
  char* buf;
  u16_t buflen;

  /* Read the data from the port, blocking if nothing yet there. 
   We assume the request (the part we care about) is in one netbuf */
  recv_err = netconn_recv(conn, &inbuf);
  
  if (recv_err == ERR_OK)
  {
    if (netconn_err(conn) == ERR_OK) 
    {
      netbuf_data(inbuf, (void**)&buf, &buflen);
    
      /* Is this an HTTP GET command? (only check the first 5 chars, since
      there are other formats for GET, and we're keeping it very simple )*/
      if ((buflen >=5) && (strncmp(buf, "GET /", 5) == 0))
      {
    	  if (strncmp((char const *)buf,"GET /index.html",15)==0) {
    		  netconn_write(conn, (const unsigned char*)index_html, index_html_len, NETCONN_NOCOPY);
    	  }
    	  if (strncmp((char const *)buf,"GET /led1", 9) == 0) {
    		  HAL_GPIO_TogglePin(LD1_GPIO_Port, LD1_Pin);
    	  }
    	  if (strncmp((char const *)buf,"GET /led2", 9) == 0) {
    		  HAL_GPIO_TogglePin(LD2_GPIO_Port, LD2_Pin);
    	  }
    	  if (strncmp((char const *)buf,"GET /led3", 9) == 0) {
    		  HAL_GPIO_TogglePin(LD3_GPIO_Port, LD3_Pin);
    	  }
    	  if (strncmp((char const *)buf,"GET /btn1", 9) == 0) {
    		  if(HAL_GPIO_ReadPin(User_Blue_Button_GPIO_Port, User_Blue_Button_Pin) == GPIO_PIN_SET)
    			  netconn_write(conn, (const unsigned char*)"ON", 2, NETCONN_NOCOPY);
    		  else
    			  netconn_write(conn, (const unsigned char*)"OFF", 3, NETCONN_NOCOPY);
    	  }
    	  if (strncmp((char const *)buf,"GET /adc", 8) == 0) {
  			  uint8_t id;
			  float humidity;
			  uint8_t status;
			  extern  void *HTS221_H_0_handle;

    		  BSP_HUMIDITY_Get_Instance( HTS221_H_0_handle, &id );
    		  BSP_HUMIDITY_IsInitialized( HTS221_H_0_handle, &status );

    		  if ( status == 1 )
    		  {
    		    if ( BSP_HUMIDITY_Get_Hum( HTS221_H_0_handle, &humidity ) == COMPONENT_ERROR )
    		    	humidity = 0.0f;
				sprintf(buf, "Humidity: %f\r\n", humidity);
	    		netconn_write(conn, (const unsigned char*)buf, strlen(buf), NETCONN_NOCOPY);
    		  }
    	  }
      }
    }
  }
  /* Close the connection (server closes in HTTP) */
  netconn_close(conn);
  
  /* Delete the buffer (netconn_recv gives us ownership,
   so we have to make sure to deallocate the buffer) */
  netbuf_delete(inbuf);
}
Exemple #8
0
/**
  * @brief serve tcp connection  
  * @param conn: pointer on connection structure 
  * @retval None
  */
static void http_ipcam_serve(struct netconn *conn)
{
  struct netbuf *inbuf;
  char* buf;
  uint16_t buflen;
  uint16_t index;
  struct fs_file * file;
  static  uint32_t RequestIndex = 0;


 /* Read the data from the port, blocking if nothing yet there. 
   We assume the request (the part we care about) is in one netbuf */
  inbuf = netconn_recv(conn);

  if (inbuf != NULL)
  {
    if (netconn_err(conn) == ERR_OK)
    {
      netbuf_data(inbuf, (void**)&buf, &buflen);

      /* Is this an HTTP GET command? (only check the first 5 chars, since
      there are other formats for GET, and we're keeping it very simple )*/
      if ((buflen >=5) && (strncmp(buf, "GET /", 5) == 0))
      {
        if((Global_Config.b.DistantControlEnabled != 0) && \
           (Global_Config.b.BackgroundModeEnabled != 0) && \
           (EthernetSettings.DistantControlEnabled == 1))
        {
          if (strncmp(buf, "GET /cmds", 9) == 0)
          {
            index = 9;
            DC_Global_Config.d32 = 0;

            while(buf[index] != 0x20) /* */
            {
              index++; 
              if (buf[index] == 0x63) /* c */
              {
                index++;
                if (buf[index] ==  0x6d) /* m */
                {
                  index++;
                  if (buf[index] ==  0x64) /* d*/
                  {
                    index+=2;

                    if(buf[index]==0x31) /* 1: Distant Control Cmd */
                    {
                      DC_Global_Config.b.DistantControlEnabled = 1;
                    }
                    if(buf[index]==0x32) /* 2: Background Mode Cmd */
                    {
                      DC_Global_Config.b.BackgroundModeEnabled = 1;
                    }
                    if(buf[index]==0x33) /* 3: Low Power Mode Cmd */
                    {
                      DC_Global_Config.b.LowPowerModeEnabled = 1;
                    }
                    if(buf[index]==0x34) /* 4: LCD Power Saving Cmd */
                    {
                      DC_Global_Config.b.LCDPowerSavingEnabled = 1;
                    }
                  }
                }
              }
            }
            if(Global_Config.b.LCDPowerSavingEnabled != DC_Global_Config.b.LCDPowerSavingEnabled)
            {
              Global_Config.b.LCDPowerSavingEnabled = DC_Global_Config.b.LCDPowerSavingEnabled;
              MOD_SetParam(GLOBAL_SETTINGS_MEM , &Global_Config.d32);
              Global_Config.b.Configuration_Changed = 1;
              SYSTEM_RefreshSetting();
            }

            if(DC_Global_Config.b.DistantControlEnabled == 0)
            {
              EthernetSettings.DisableDControlLater = 1;
            }

            if(DC_Global_Config.b.BackgroundModeEnabled == 0)
            {
              EthernetSettings.DisableBackgroundLater = 1;
            }

            /* Open the STM32DC.html */
            file = fs_open("/STM32DC.html");
            netconn_write(conn, (const unsigned char*)(file->data), (size_t)file->len, NETCONN_NOCOPY);
            fs_close(file);
          }
          /* Check if request to get ST logo.jpg */
          else if (strncmp((char const *)buf, "GET /STM32_files/logo.jpg", 25) == 0)
          {
            file = fs_open("/STM32_files/logo.jpg");
            netconn_write(conn, (const unsigned char*)(file->data), (size_t)file->len, NETCONN_NOCOPY);
            fs_close(file);
          }
          /* Check if request to get STM32TASKS.html */
          else if((strncmp(buf, "GET /STM32TASKS.html", 20) == 0)||(strncmp(buf, "GET /STM32TASKSDC.html", 22) == 0))
          {
            /* Load dynamic page */
            DynWebPage(conn);
          }
          /* Check if request to get STM32DC.html */
          else if((strncmp(buf, "GET /STM32DC.html", 17) == 0) || (strncmp(buf, "GET / ", 6) == 0))
          {
            file = fs_open("/STM32DC.html");
            netconn_write(conn, (const unsigned char*)(file->data), (size_t)file->len, NETCONN_NOCOPY);
            fs_close(file);
          }
          /* Load Error page */
          else
          {
            file = fs_open("/404.html");
            netconn_write(conn, (const unsigned char*)(file->data), (size_t)file->len, NETCONN_NOCOPY);
            fs_close(file);
          }
        }
        else
        {
          if ((strncmp((char const *)buf, "GET /STM32_files/CamImage.bmp", 29)==0)||(strncmp(buf, "GET /CamImage.bmp", 17) == 0))
          {
            if(IPCAM_ImageBuffer.BufferStatus == BUFFER_FILLED)
            {
              /* Prepare the received image for transfer */
              IPCAM_PrepareImage();
              netconn_write(conn, (const unsigned char*)(IPCAM_ImageBuffer.ImageHeader), (size_t)IPCAM_ImageBuffer.ImageHeaderLen, NETCONN_NOCOPY);
              netconn_write(conn, (const unsigned char*)IPCAM_ImageBuffer.ImageData, IPCAM_ImageBuffer.MaxImageLen, NETCONN_NOCOPY);

              /* Start new image capture */
              IPCAM_CaptureNextImage();
              RequestIndex = 0;
            }
            else
            {
              RequestIndex++;
              if(RequestIndex == 10)
              {
                RequestIndex = 0;
                file = fs_open("/STM32F4x7_files/Error.jpg");
                netconn_write(conn, (const unsigned char*)(file->data), (size_t)file->len, NETCONN_NOCOPY);
                fs_close(file);
              }
              /* Start new image capture */
              IPCAM_CaptureNextImage();
              netconn_close(conn);
              netbuf_delete(inbuf);
            }
          }
          /* Check if request to get ST.gif */ 
          else if (strncmp((char const *)buf, "GET /STM32_files/ST.gif", 23)==0)
          {
            file = fs_open("/STM32_files/ST.gif"); 
            netconn_write(conn, (const unsigned char*)(file->data), (size_t)file->len, NETCONN_NOCOPY);
            fs_close(file);
          }
          /* Check if request to get stm32f4.jpeg */
          else if (strncmp((char const *)buf, "GET /STM32_files/stm32f4.jpg", 28)==0)
          {
            file = fs_open("/STM32_files/stm32f4.jpg"); 
            netconn_write(conn, (const unsigned char*)(file->data), (size_t)file->len, NETCONN_NOCOPY);
            fs_close(file);
          }
          /* Check if request to get stm32f2.jpeg */
          else if (strncmp((char const *)buf, "GET /STM32_files/stm32f2.jpg", 28)==0)
          {
            file = fs_open("/STM32_files/stm32f2.jpg");
            netconn_write(conn, (const unsigned char*)(file->data), (size_t)file->len, NETCONN_NOCOPY);
            fs_close(file);
          }
          /* Check if request to get ST logo.jpg */
          else if (strncmp((char const *)buf, "GET /STM32_files/logo.jpg", 25) == 0)
          {
            file = fs_open("/STM32_files/logo.jpg"); 
            netconn_write(conn, (const unsigned char*)(file->data), (size_t)file->len, NETCONN_NOCOPY);
            fs_close(file);
          }
          /* Check if request to get STM32TASKS.html */
          else if((strncmp(buf, "GET /STM32TASKS.html", 20) == 0)||(strncmp(buf, "GET /STM32TASKSDC.html", 22) == 0))
          {
            /* Load dynamic page */
            DynWebPage(conn);
          }
          /* Check if request to get STM32IPCAM.html */
          else if(strncmp(buf, "GET /STM32IPCAM.html", 20) == 0)
          {
            file = fs_open("/STM32IPCAM.html");
            netconn_write(conn, (const unsigned char*)(file->data), (size_t)file->len, NETCONN_NOCOPY);
            fs_close(file);
          }
          /* Check if request to get STM32F4x7.html */
          else if((strncmp(buf, "GET /index.html", 15) == 0)||(strncmp(buf, "GET / ", 6) == 0))
          {
            #if defined (STM32F2XX)
             file = fs_open("/STM32F2x7.html");
            #elif defined (STM32F4XX)
             file = fs_open("/STM32F4x7.html");
            #endif
            netconn_write(conn, (const unsigned char*)(file->data), (size_t)file->len, NETCONN_NOCOPY);
            fs_close(file);
          }
          /* Load Error page */
          else
          {
            file = fs_open("/404.html");
            netconn_write(conn, (const unsigned char*)(file->data), (size_t)file->len, NETCONN_NOCOPY);
            fs_close(file);
          }
        }
      }
    }
  }
  netconn_close(conn);
  netconn_delete(conn);
  netbuf_delete(inbuf);
}
Exemple #9
0
/**
  * @brief serve tcp connection  
  * @param conn: pointer on connection structure 
  * @retval None
  */
void http_server_serve(struct netconn *conn) 
{
  struct netbuf *inbuf;
  err_t recv_err;
  char* buf;
  u16_t buflen;
  struct fs_file * file;
  
  /* Read the data from the port, blocking if nothing yet there. 
   We assume the request (the part we care about) is in one netbuf */
  recv_err = netconn_recv(conn, &inbuf);
  
  if (recv_err == ERR_OK)
  {
    if (netconn_err(conn) == ERR_OK) 
    {
      netbuf_data(inbuf, (void**)&buf, &buflen);
    
      /* Is this an HTTP GET command? (only check the first 5 chars, since
      there are other formats for GET, and we're keeping it very simple )*/
      if ((buflen >=5) && (strncmp(buf, "GET /", 5) == 0))
      {

					 if (strncmp((char const *)buf,"GET /main_test.html",19)==0||(strncmp(buf, "GET / ", 6) == 0)) 
        {
          file = fs_open("/main_test.html"); 
          netconn_write(conn, (const unsigned char*)(file->data), (size_t)file->len, NETCONN_NOCOPY);
          fs_close(file);
        }  
						else if((strncmp(buf, "GET /stats_12345678.html", 24) == 0)) 
							{
								/* Load STM32F4x7 page */
								file = fs_open("/stats_12345678.html"); 
								netconn_write(conn, (const unsigned char*)(file->data), (size_t)file->len, NETCONN_NOCOPY);
								fs_close(file);
							}
							
													else if((strncmp(buf, "GET /style.css", 14) == 0)) 
							{
								/* Load STM32F4x7 page */
								file = fs_open("/style.css"); 
								netconn_write(conn, (const unsigned char*)(file->data), (size_t)file->len, NETCONN_NOCOPY);
								fs_close(file);
							}
							
						else if(strncmp(buf, "GET /control.html", 17) == 0)
								{
									 DynWebPage(conn);
								}
									else if(strncmp(buf, "GET /script.js", 14) == 0)
									{
										file = fs_open("/script.js"); 
										netconn_write(conn, (const unsigned char*)(file->data), (size_t)file->len, NETCONN_NOCOPY);
										fs_close(file);
									}								
								
						else if(strncmp(buf, "GET /table", 10) == 0)
								{

									char PAGE_BODY[35];
									uint32_t temp,*p ;
									static uint32_t count=0;
									p=&temp;
									uint8_t *Mem= "Mem", *Time = "Time", *Param = "Param";
									uint8_t table[35];
									memset(PAGE_BODY, 0,35);
									strcpy(table, Mem);
									strcpy(table + 9, Time);
									strcpy(table + 22, Param);
									temp = xPortGetFreeHeapSize();
									temp = 40560;
									sprintf(table + 3,"%d",temp);
									sprintf(table + 13,"%d",87654321);
									sprintf(table + 27,"%d",(count++)&0xFFFF);
									
									for(uint8_t i = 0; i < 28; i++)
											if(table[i] == 0)
													table[i] = 1;
											
									memcpy(PAGE_BODY, table, sizeof(table) );	
									netconn_write(conn, PAGE_BODY, strlen((char*)PAGE_BODY), NETCONN_COPY);
								}
        else 
        {
          /* Load Error page */
         // file = fs_open("/404.html"); 
         // netconn_write(conn, (const unsigned char*)(file->data), (size_t)file->len, NETCONN_NOCOPY);
         // fs_close(file);
        }
      }      
    }
  }
  /* Close the connection (server closes in HTTP) */
  netconn_close(conn);
  
  /* Delete the buffer (netconn_recv gives us ownership,
   so we have to make sure to deallocate the buffer) */
  netbuf_delete(inbuf);
}
/**
 * SNTP request
 */
time_t sntp_request(void)
{
	unsigned char * sntp_request;
	unsigned char * sntp_response;
	struct ip_addr sntp_server_address;
	time_t timestamp = 0;

	struct netconn * sendUDPNetConn;
	struct netbuf * sendUDPNetBuf;
	struct netbuf * receiveUDPNetBuf;

	u16_t dataLen;

	err_t errLWIP;

	/* initialize SNTP server address */
	sntp_server_address.addr = SNTP_SERVER_ADDRESS;

	/* if we got a valid SNTP server address... */
	if (sntp_server_address.addr != 0)
	{
		/* create new socket */
		sendUDPNetConn = netconn_new( NETCONN_UDP );
		sendUDPNetBuf = netbuf_new();
		// Create data space for netbuf, if we can.
		sntp_request = (unsigned char *) netbuf_alloc(sendUDPNetBuf, SNTP_MAX_DATA_LEN);

		if ((NULL != sendUDPNetConn) && (NULL != sendUDPNetBuf) && (NULL != sntp_request))
		{
			errLWIP = netconn_connect(sendUDPNetConn, &sntp_server_address, SNTP_PORT);
			if(ERR_OK == errLWIP)
			{
				/* prepare SNTP request */
				memset(sntp_request, 0, SNTP_MAX_DATA_LEN);
				sntp_request[0] = SNTP_LI_NO_WARNING | SNTP_VERSION | SNTP_MODE_CLIENT;

				errLWIP = netconn_send(sendUDPNetConn, sendUDPNetBuf);
				// Send SNTP request to server.
				if (ERR_OK == errLWIP)
				{
					// Set recv timeout.
					sendUDPNetConn->recv_timeout = SNTP_RECV_TIMEOUT;
					// Receive SNTP server response.
					receiveUDPNetBuf = netconn_recv(sendUDPNetConn);

					if (NULL != receiveUDPNetBuf)
					{
						// Get pointer to response data.
						netbuf_data(receiveUDPNetBuf, (void **) &sntp_response,(u16_t *) &dataLen);

						// If the response size is good.
						if (dataLen == SNTP_MAX_DATA_LEN)
						{
							// If this is a SNTP response...
							if (((sntp_response[0] & SNTP_MODE_MASK) == SNTP_MODE_SERVER) || ((sntp_response[0]
									& SNTP_MODE_MASK) == SNTP_MODE_BROADCAST))
							{
								/* extract GMT time from response */
								memcpy(&timestamp, (sntp_response + SNTP_RCV_TIME_OFS), sizeof(timestamp));
								timestamp = (ntohl(timestamp) - DIFF_SEC_1900_1970);

								syslog(LOG_DEBUG | LOG_USER, "Received timestamp %u", timestamp);
							}
							else
							{
								syslog(LOG_INFO | LOG_USER, "Received data did not match frame code");
							}
						}
						else
						{
							syslog(LOG_NOTICE | LOG_USER, "Length of data did not match SNTP_MAX_DATA_LEN, received len %u", dataLen);
						}
					}
					else
					{
						syslog(LOG_WARNING | LOG_USER, "Netconn receive failed with %d", netconn_err(sendUDPNetConn));
					}
				} // netconn_send(sendUDPNetConn, sendUDPNetBuf);
				else
				{
					syslog(LOG_WARNING | LOG_USER, "Netconn sendto failed with %d", errLWIP);
				}
			} //netconn_connect(sendUDPNetConn, &sntp_server_address, SNTP_PORT);
			else
			{
				syslog(LOG_WARNING | LOG_USER, "Netconn connect to server %X, port %u failed with %d", sntp_server_address.addr, SNTP_PORT, errLWIP);
			}
		} // if ((NULL != sendUDPNetConn) && (NULL != sendUDPNetBuf) && (NULL != sntp_request))
		else
		{
			syslog(LOG_ERR | LOG_USER, "Netconn or netbuf or data allocation failed.");
		}
	} //if (sntp_server_address != 0)
	else
	{
		syslog(LOG_WARNING | LOG_USER, "Invalid NTP server address %X", SNTP_SERVER_ADDRESS);
	}

	netbuf_delete(sendUDPNetBuf);
	netbuf_delete(receiveUDPNetBuf);
	netconn_delete(sendUDPNetConn);

	return timestamp;
}