/*
 * Task that provides the input and output for the FreeRTOS+CLI command
 * interpreter.  In this case a UDP port is used.  See the URL in the comments
 * within main.c for the location of the online documentation.
 */
void vUDPCommandInterpreterTask( void *pvParameters )
{
long lBytes, lByte;
signed char cInChar, cInputIndex = 0;
static char cInputString[ cmdMAX_INPUT_SIZE ], cOutputString[ cmdMAX_OUTPUT_SIZE ], cLocalBuffer[ cmdSOCKET_INPUT_BUFFER_SIZE ];
portBASE_TYPE xMoreDataToFollow;
struct freertos_sockaddr xClient;
socklen_t xClientAddressLength = 0; /* This is required as a parameter to maintain the sendto() Berkeley sockets API - but it is not actually used so can take any value. */
xSocket_t xSocket;

	/* Just to prevent compiler warnings. */
	( void ) pvParameters;

	/* Attempt to open the socket.  The port number is passed in the task
	parameter.  The strange casting is to remove compiler warnings on 32-bit
	machines. */
	xSocket = prvOpenUDPServerSocket( ( uint16_t ) ( ( uint32_t ) pvParameters ) & 0xffffUL );

	if( xSocket != FREERTOS_INVALID_SOCKET )
	{
		for( ;; )
		{
			/* Wait for incoming data on the opened socket. */
			lBytes = FreeRTOS_recvfrom( xSocket, ( void * ) cLocalBuffer, sizeof( cLocalBuffer ), 0, &xClient, &xClientAddressLength );

			if( lBytes != FREERTOS_SOCKET_ERROR )
			{
				/* Process each received byte in turn. */
				lByte = 0;
				while( lByte < lBytes )
				{
					/* The next character in the input buffer. */
					cInChar = cLocalBuffer[ lByte ];
					lByte++;

					/* Newline characters are taken as the end of the command
					string. */
					if( cInChar == '\n' )
					{
						/* Process the input string received prior to the
						newline. */
						do
						{
							/* Pass the string to FreeRTOS+CLI. */
							xMoreDataToFollow = FreeRTOS_CLIProcessCommand( cInputString, cOutputString, cmdMAX_OUTPUT_SIZE );

							/* Send the output generated by the command's
							implementation. */
							FreeRTOS_sendto( xSocket, cOutputString,  strlen( cOutputString ), 0, &xClient, xClientAddressLength );

						} while( xMoreDataToFollow != pdFALSE ); /* Until the command does not generate any more output. */

						/* All the strings generated by the command processing
						have been sent.  Clear the input string ready to receive
						the next command. */
						cInputIndex = 0;
						memset( cInputString, 0x00, cmdMAX_INPUT_SIZE );

						/* Transmit a spacer, just to make the command console
						easier to read. */
						FreeRTOS_sendto( xSocket, "\r\n",  strlen( "\r\n" ), 0, &xClient, xClientAddressLength );
					}
					else
					{
						if( cInChar == '\r' )
						{
							/* Ignore the character.  Newlines are used to
							detect the end of the input string. */
						}
						else if( cInChar == '\b' )
						{
							/* Backspace was pressed.  Erase the last character
							in the string - if any. */
							if( cInputIndex > 0 )
							{
								cInputIndex--;
								cInputString[ cInputIndex ] = '\0';
							}
						}
						else
						{
							/* A character was entered.  Add it to the string
							entered so far.  When a \n is entered the complete
							string will be passed to the command interpreter. */
							if( cInputIndex < cmdMAX_INPUT_SIZE )
							{
								cInputString[ cInputIndex ] = cInChar;
								cInputIndex++;
							}
						}
					}
				}
			}
		}
	}
	else
	{
		/* The socket could not be opened. */
		vTaskDelete( NULL );
	}
}
static void prvDemonstrateTaskStateAndHandleGetFunctions( void )
{
TaskHandle_t xIdleTaskHandle, xTimerTaskHandle;
char *pcTaskName;
static portBASE_TYPE xPerformedOneShotTests = pdFALSE;
TaskHandle_t xTestTask;

	/* Demonstrate the use of the xTimerGetTimerDaemonTaskHandle() and
	xTaskGetIdleTaskHandle() functions.  Also try using the function that sets
	the task number. */
	xIdleTaskHandle = xTaskGetIdleTaskHandle();
	xTimerTaskHandle = xTimerGetTimerDaemonTaskHandle();

	/* This is the idle hook, so the current task handle should equal the
	returned idle task handle. */
	if( xTaskGetCurrentTaskHandle() != xIdleTaskHandle )
	{
		pcStatusMessage = "Error:  Returned idle task handle was incorrect";
	}

	/* Check the timer task handle was returned correctly. */
	pcTaskName = pcTaskGetTaskName( xTimerTaskHandle );
	if( strcmp( pcTaskName, "Tmr Svc" ) != 0 )
	{
		pcStatusMessage = "Error:  Returned timer task handle was incorrect";
	}

	/* This task is running, make sure it's state is returned as running. */
	if( eTaskStateGet( xIdleTaskHandle ) != eRunning )
	{
		pcStatusMessage = "Error:  Returned idle task state was incorrect";
	}

	/* If this task is running, then the timer task must be blocked. */
	if( eTaskStateGet( xTimerTaskHandle ) != eBlocked )
	{
		pcStatusMessage = "Error:  Returned timer task state was incorrect";
	}

	/* Other tests that should only be performed once follow.  The test task
	is not created on each iteration because to do so would cause the death
	task to report an error (too many tasks running). */
	if( xPerformedOneShotTests == pdFALSE )
	{
		/* Don't run this part of the test again. */
		xPerformedOneShotTests = pdTRUE;

		/* Create a test task to use to test other eTaskStateGet() return values. */
		if( xTaskCreate( prvTestTask, "Test", configMINIMAL_STACK_SIZE, NULL, tskIDLE_PRIORITY, &xTestTask ) == pdPASS )
		{
			/* If this task is running, the test task must be in the ready state. */
			if( eTaskStateGet( xTestTask ) != eReady )
			{
				pcStatusMessage = "Error: Returned test task state was incorrect 1";
			}

			/* Now suspend the test task and check its state is reported correctly. */
			vTaskSuspend( xTestTask );
			if( eTaskStateGet( xTestTask ) != eSuspended )
			{
				pcStatusMessage = "Error: Returned test task state was incorrect 2";
			}

			/* Now delete the task and check its state is reported correctly. */
			vTaskDelete( xTestTask );
			if( eTaskStateGet( xTestTask ) != eDeleted )
			{
				pcStatusMessage = "Error: Returned test task state was incorrect 3";
			}
		}
	}
}
Esempio n. 3
0
/**
 * Ethernet to UART task
 *
 * @param none  
 * @return none
 */
void
BRIDGE_UART_Task( void *pvParameters )
{
    /*tcp/ip struct holding connection information*/
    struct tcp_pcb *pcb;
    /*buffer to hold serial information*/
    static int8 *serial_receive_array;
    /*client mode: connect to this server address*/
    struct ip_addr ServerIPAddr;
    
    /* Parameters are not used - suppress compiler error */
    ( void )pvParameters;

    /*wait until tcp/ip stack has a valid IP address*/
    while( (uint8)get_lwip_ready() == FALSE )
    {
       /*Leave execution for 1000 ticks*/
       vTaskDelay(1000);
    }

    /*array space*/
    if( (serial_receive_array=(static int8 *)mem_malloc( UART_BUFFER_LIMIT>>1 )) == NULL )
    {
      /*Task no longer needed*/
      vTaskDelete(NULL);
    }

    /*FSL: create semaphore that will allow to sleep process*/
    vSemaphoreCreateBinary(xUARTSemaphore);
    
    /*FSL: create mutex for shared resource*/
    UARTmutex = xSemaphoreCreateMutex();

    /**********************FSL: serial start-up*******************************/
    //if UARThandle NULL, serial cannot be used!!!
    UARThandle = xUARTinit((eCOMPort)board_get_uart_port()/*serCOM1*/, 
                             (eBaud)board_get_uart_baud()/*ser19200*/, 
                             (eParity)board_get_uart_parity()/*serNO_PARITY*/, 
                             (eDataBits)board_get_uart_number_of_bits()/*serBITS_8*/, 
                             (eStopBits)board_get_uart_stop_bits()/*serSTOP_1*/,
                             (eFlowControl)board_get_uart_flow_control()/*serFlowControlXONXOFF*/,
                             (eCOMsemaphore)serSemaphoreON,/*Turn on semaphore ON activity*/  
                             UART_BUFFER_LIMIT/*defined at header file*/);
    
    /*if handle cant be created*/
    if( UARThandle == NULL )
    {
      /*Task no longer needed*/
      vTaskDelete(NULL);      
    }

    /**********************FSL: low level start-up****************************/

    /* Create a new TCP PCB. */
    pcb = tcp_new();
    
    /*check for server or client init*/
    if( !(uint8)board_get_bridge_tcp_server() )
    {
      /*server*/
      /* Bind the PCB to specified TCP port. */
      tcp_bind(pcb, IP_ADDR_ANY, (uint16)board_get_bridge_tcp_port());
      /* Change TCP state to LISTEN */
      pcb = tcp_listen(pcb);
      /* callback when a new connection arrives */
      tcp_accept(pcb, BRIDGE_UART_Accept);      
    }
    else
    {
      /*get server address*/
      ServerIPAddr.addr = (uint32)board_get_eth_server_add();
      /*client connection*/
      if( tcp_connect(pcb,&ServerIPAddr,(uint16)board_get_bridge_tcp_port(),BRIDGE_UART_Accept) != ERR_OK )
      {
        /*Task no longer needed*/
        vTaskDelete(NULL);        
      }
    }

    /*************************************************************************/

    /* Loop forever */
    for( ;; )
    {	       
       /*Block task until UART first character arrives*/
       xSemaphoreTake( xUARTSemaphore, portMAX_DELAY );

       /*FSL:available elements from UART ready to send to MAC buffers*/
       BRIDGE_UART_ETH_TX(serial_receive_array);
    }
      
    return;/*FSL:never get here!!*/
}
void taskClient( void *pvParameters ){
BsdTcpClient(PORT_NUM);
UART_PRINT("taskClient over\r\n"); 
vTaskDelete(NULL);
}
Esempio n. 5
0
void
http_get_task(void *pvParameters)
{
    coap_packet_t request[1]; /* This way the packet can be treated as pointer as usual. */
    int failures = 0;

    // create network socket
    struct addrinfo hints;
    struct addrinfo *res;

    // Use an UDP socket
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_DGRAM;

    // Get host/port from request URL
    // should call free(uri) somewhere
    coap_uri_t *uri = coap_new_uri((unsigned char*)URI, strlen(URI));   
    if (uri == NULL) {
        COAP_PRINTF("coap_new_uri(): URI failed\n");
        vTaskDelete(NULL);
    }

    // DNS lookup
    int err;
    char port[6];
    char host[32];
    char path[64];

    sprintf(port, "%d", uri->port);
    sprintf(path, "%s", uri->path.s);
    memcpy(host, uri->host.s, uri->host.length);
    host[uri->host.length] = '\0';

    COAP_PRINTF("URI Path: %s\n", path);
    COAP_PRINTF("URI Host: %s\n", host);
    COAP_PRINTF("URI Port: %s\n", port);

    printf("Running DNS lookup for %s...\r\n", host);

    while (1) {
        err = getaddrinfo(host, port, &hints, &res);
        if (err == 0)
            break;
        freeaddrinfo(res);
        printf("DNS lookup failed err=%d res=%p\r\n", err, res);
        vTaskDelay(3000 / portTICK_RATE_MS);
    }

    /* Note: inet_ntoa is non-reentrant, look at ipaddr_ntoa_r for "real" code */
    struct in_addr *addr = &((struct sockaddr_in *)res->ai_addr)->sin_addr;
    char *ip = inet_ntoa(*addr);
    printf("DNS lookup succeeded. HOST=%s, IP=%s\r\n", host, ip);

    // init a HTTP POST message and set message header
    coap_init_message(request, COAP_TYPE_CON, COAP_POST, 0);
    coap_set_header_uri_path(request, path);
    coap_set_header_uri_host(request, host);

    // Create a local socket
    int s = socket(res->ai_family, res->ai_socktype, 0);
    if(s < 0) {
        printf("... Failed to allocate socket.\r\n");
        freeaddrinfo(res);
        vTaskDelete(NULL);
    }

    printf("... allocated socket\r\n");

    int a;
    int ret;
    char payload[128];
    struct request_state_t state[1];
    ip_addr_t ipaddr;

    ipaddr.addr = ipaddr_addr(ip);

    while(1) {
        if(connect(s, res->ai_addr, res->ai_addrlen) != 0) {
            close(s);
            freeaddrinfo(res);
            printf("... socket connect failed.\r\n");
            vTaskDelay(3000 / portTICK_RATE_MS);
            failures++;
            continue;
        }

        printf("... connected\r\n");
        freeaddrinfo(res);
repeat:
        vTaskDelay(5000 / portTICK_RATE_MS);

        // read sensor data from ESP8266 A0
        a = sdk_system_adc_read();

        sprintf(payload, "{ \"quality\": %d }\n", a);
        COAP_PRINTF("Payload: %s\n", payload);

        // CoAP payload
        coap_set_payload(request, payload, strlen(payload));

        // Make CoAP transaction
        request->mid = coap_get_mid();

        if ((state->transaction = coap_new_transaction(request->mid, &ipaddr, uri->port)))
        {
            state->transaction->callback = coap_blocking_request_callback;
            state->transaction->callback_data = state;

            if (state->block_num > 0)
            {
                coap_set_header_block2(request, state->block_num, 0, REST_MAX_CHUNK_SIZE);
            }

            // Build CoAP header and Options
            state->transaction->packet_len = coap_serialize_message(request, state->transaction->packet);

            COAP_PRINTF("Header dump: [0x%02X %02X %02X %02X]. Size: %d\n",
                request->buffer[0],
                request->buffer[1],
                request->buffer[2],
                request->buffer[3],
                state->transaction->packet_len
            );

            COAP_PRINTF("Requested #%u (MID %u)\n", state->block_num, request->mid);

            // Transmit
            ret = write(s, state->transaction->packet, state->transaction->packet_len);
            //ret = sendto(s, state->transaction->packet, state->transaction->packet_len);
            if (ret < 0) {
                printf("[RET: %d] CoAP packet send failed.\n", ret);
                continue;
            }
        }
        else
        {
          COAP_PRINTF("Could not allocate transaction buffer");
        }

        goto repeat;
    }
}
Esempio n. 6
0
void spp_wr_task_shut_down(void)
{
    vTaskDelete(NULL);
}
void WlanStationMode( void *pvParameters )
{
    int iTestResult = 0;
    unsigned long ulIP = 0;
    unsigned long ulSubMask = 0;
    unsigned long ulDefaultGateway = 0;
    unsigned long ulDNSServer = 0;
    unsigned char ucDHCP = 0;
    char cMode;
    char* buff="hhhhhh\n\r";
    unsigned char currentMacAddress[SL_MAC_ADDR_LEN];
    
    //UART_PRINT(" in WlanStationMode  \n\r"); 
    
/*  for(int a = 0; a<5; ++a){
    Z_DelayS(30);
    *buff=a+'0';
    UART_PRINT(buff);   
    }
 */   
    
    

    
    
    
    
    
    
 
    
    
  char deviceRole = ROLE_STA;  
    
  deviceRole = sl_Start(NULL,NULL,InitCallback);
 /* deviceRole = sl_Start(NULL,NULL,NULL);
    
    if(deviceRole < 0 ){
      UART_PRINT("sl_Start error  \n\r");
      return;
    }
    else if(deviceRole == ROLE_STA)
        UART_PRINT("in station mode  \n\r"); 
          else{
            UART_PRINT("in wrong mode  \n\r"); 
            return;
          }
 */     
    
 /*  if((cMode = sl_Start(NULL,NULL,NULL)) != ROLE_STA){
      UART_PRINT("hellow  \n\r"); 
      
      *buff=cMode+'0';
      UART_PRINT(buff);
      *buff=ROLE_STA+'0';
      UART_PRINT(buff);
      
 //     SL_WLAN_SET_MODE_STA();
    }
     
    UART_PRINT("hellow i am in station mode now \n\r"); 
    
  */   
    
 while(!g_uiSimplelinkstarted)
 {
        //looping till simplelink starts
  Z_DelayS(1);
  // ; 
   UART_PRINT("i am starting now \n\r"); 
 } 
             
   UART_PRINT("i am started   \n\r");          
             
    // Connecting to WLAN AP - Set with static parameters defined at the top
	// After this call we will be connected and have IP address */
    WlanConnect();
  

  
    
   UART_PRINT("i'm connected! \n\r"); 
    
    //get mac addr from s-flash
    
    SL_MAC_ADDR_GET(currentMacAddress);   
    Z_MACDispaly(currentMacAddress);
    
    
    SL_STA_IPV4_ADDR_GET(&ulIP,&ulSubMask,&ulDefaultGateway,&ulDNSServer,
                       &ucDHCP);
    
    
    
    Z_IPDispaly(&ulIP);
    MyIP=ulIP;
    Z_IPDispaly(&ulSubMask);
    Z_IPDispaly(&ulDefaultGateway);

    
    
    
    /*
    
    UNUSED(ulIP);
    UNUSED(ulSubMask);
    UNUSED(ulDNSServer);
    UNUSED(ucDHCP);
    */
    
   // iTestResult = PingTest(ulDefaultGateway);
  //  UNUSED(iTestResult);
    
 //BsdTcpServer(PORT_NUM); 
    
 //mqtt_pub();
    UART_PRINT("WlanStationMode\r\n"); 
    vTaskDelete(NULL);
    UART_PRINT("WlanStationMode\r\n"); 
 return;
 
 
    
    
    
    
    
}
Esempio n. 8
0
/**
 ******************************************************************************
 * @brief      delete a task.
 * @param[in]
 *              tid : task ID of task to delete
 *
 * @details
 *
 * @note
 ******************************************************************************
 */
extern void
taskDelete(TASK_ID tid)
{
    vTaskDelete((xTaskHandle) tid);
}
/**
 * Ethernet to PERF task
 *
 * @param none  
 * @return none
 */
void
BRIDGE_PERF_Task( void *pvParameters )
{   
    struct ip_addr  xIpAddr, xNetMast, xGateway;
    extern err_t ethernetif_init( struct netif *netif );

    SIM_SCGC6 |= SIM_SCGC6_PIT_MASK;//enable PIT
    
    /* Parameters are not used - suppress compiler error */
    ( void )pvParameters;
    
    tcpip_init( NULL, NULL );

    /* Create and configure the FEC interface. */
    IP4_ADDR( &xIpAddr, configIP_ADDR0, configIP_ADDR1, configIP_ADDR2, configIP_ADDR3 );
    IP4_ADDR( &xNetMast, configNET_MASK0, configNET_MASK1, configNET_MASK2, configNET_MASK3 );
    IP4_ADDR( &xGateway, configGW_ADDR0, configGW_ADDR1, configGW_ADDR2, configGW_ADDR3 );
    netif_add( &ENET_if, &xIpAddr, &xNetMast, &xGateway, NULL, ethernetif_init, tcpip_input );    
    
    /* make it the default interface */
    netif_set_default( &ENET_if );

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

#if BENCHMARK_PROTOCOL
//**********************************UDP**********************************//
    {
     struct udp_pcb *remote_pcb;
      
     remote_pcb = udp_new();
    
     if(!remote_pcb)
         vTaskDelete(NULL);  /*FSL: error during buffer creation*/

#if BENCHMARK_SEND_TO_PC
//**********************************TX***********************************//
     {  
       uint16 i;
       /*client mode: connect to this server address*/
       struct ip_addr ServerIPAddr;
       struct pbuf *p; 
       
       /*Fill the array*/
       for(i=0;i<sizeof(array);i++)
         array[i] = i%256;//dummy sequence
       
       /*Server IP address to connect*/
       IP4_ADDR(&ServerIPAddr,192,168,0,1);

       printf("Starting UDP TX Client\n");
    
       if( udp_connect(remote_pcb, &ServerIPAddr, (u16_t)BENCHMARK_PORT) != ERR_OK )
         vTaskDelete(NULL);  /*FSL: error during socket creation*/
    
       if( (p = pbuf_alloc(PBUF_TRANSPORT,0,PBUF_REF)) == NULL )
         vTaskDelete(NULL);  /*FSL: error during buffer creation*/
    
       p->payload = &array[0];
       p->len = p->tot_len = BENCHMARK_PACKET_LENGTH;
    
       /*FSL: send selected number of packets*/
       for(pkt_counter=0;pkt_counter<BENCHMARK_NUMBER_OF_PACKETS;pkt_counter++)
       {
          if( udp_send(remote_pcb, p) != ERR_OK )
            break;//error: abort
       }
    
       /*FSL: send ending frames*/
       p->len = p->tot_len = 1;
       /*FSL: send 10 times*/
       udp_send(remote_pcb, p);
       udp_send(remote_pcb, p);
       udp_send(remote_pcb, p);
       udp_send(remote_pcb, p);
       udp_send(remote_pcb, p);
       udp_send(remote_pcb, p);
       udp_send(remote_pcb, p);
       udp_send(remote_pcb, p);
       udp_send(remote_pcb, p);
       udp_send(remote_pcb, p);
    
       //FSL: remove connection
       pbuf_free(p);
       udp_remove(remote_pcb);
    
       printf("Leaving UDP Tx Benchmark Test\n");
       vTaskDelete(NULL);  /*FSL: task no longer needed*/
     }
#else
//**********************************RX***********************************//
     {
       printf("Starting UDP RX Server\n");
       
       PIT_TCTRL0 = PIT_TCTRL_TEN_MASK;//enable timer
       PIT_MCR &= ~PIT_MCR_MDIS_MASK;
       PIT_LDVAL0 = 0xFFFFFFFF;//max value
       load_value = PIT_LDVAL0;
       PIT_TCTRL0 = 0;
    
       if( udp_bind(remote_pcb, IP_ADDR_ANY, BENCHMARK_PORT) != ERR_OK )
         printf("Wrong bind to UDP port\n");
       udp_recv(remote_pcb, udp_receive_fnc, NULL);
       /*Task no longer needed*/
       vTaskDelete(NULL);
     }
#endif
    } 
#else
//**********************************TCP**********************************//
    
#if BENCHMARK_SEND_TO_PC
//**********************************TX***********************************//
    {
      struct netconn *conn;
      uint16 i;
    
      /*client mode: connect to this server address*/
      struct ip_addr ServerIPAddr;
      
      /*Fill the array*/
      for(i=0;i<sizeof(array);i++)
         array[i] = i%256;//dummy sequence
      
      /*Server IP address to connect*/
      IP4_ADDR(&ServerIPAddr,192,168,0,1);
      
      printf("Starting TCP Tx Benchmark Test\n");

      /*FSL: wait forever until getting a connection to a valid server*/
      do
      {
        printf("Trying to connect to server...\n");
        
        /* Create a new TCP PCB. */
        conn = netconn_new(NETCONN_TCP);

        /*client connection*/
        if( netconn_connect(conn, &ServerIPAddr, (uint16)BENCHMARK_PORT) != ERR_OK )
        {
          /*close connection for a new SYN process*/
          netconn_close(conn);
          netconn_delete(conn);
          vTaskDelay(2000);
        }
        else
          break;
      }
      while(1);/*infinite loop until getting a valid SYN/SYN-ACK/ACK*/

      printf("Connected to server\n");
      
      /*FSL: send selected number of packets*/
      pkt_counter = BENCHMARK_NUMBER_OF_PACKETS;//will send in a moment
      
      /*FSL: only send when connection is established, otherwise close*/
      while( pkt_counter-- )
      {
        netconn_write(conn, &array[0], sizeof(array), NETCONN_NOCOPY);
      }
      
      /*FSL: no more packets*/
      netconn_close(conn);
      netconn_delete(conn);
      
      printf("Leaving TCP Tx Benchmark Test\n");
      
      /*FSL: good bye*/
      vTaskDelete(NULL);
    }
#else
//**********************************RX***********************************//
  for(;;)
  {
    struct netconn *conn, *newconn;
    struct netbuf *inbuf;
    uint32 total_length_received = 0;
    double final_result;
      
    /* Create a new TCP PCB. */
    conn = netconn_new(NETCONN_TCP);
      
    if( netconn_bind(conn,IP_ADDR_ANY,(uint16)BENCHMARK_PORT) != ERR_OK )
    {
        /*close connection for a new SYN process*/
        netconn_close(conn);
        netconn_delete(conn);
        /*FSL: good bye*/
        vTaskDelete(NULL);
    }
        
      printf("Starting TCP Rx Benchmark Test\n");
      
      /* Put the connection into LISTEN state. */
      netconn_listen(conn);
      
      PIT_TCTRL0 = PIT_TCTRL_TEN_MASK;//enable timer
      PIT_MCR &= ~PIT_MCR_MDIS_MASK;
      PIT_LDVAL0 = 0xFFFFFFFF;//max value
      load_value = PIT_LDVAL0;
      PIT_TCTRL0 = 0;
      
      /* waiting for connection from client */
      newconn = netconn_accept(conn);
      
      PIT_TCTRL0 = PIT_TCTRL_TEN_MASK;//enable timer
      
      for(;;)
      {
        if( (inbuf = netconn_recv(newconn)) != NULL )
        {
           /*data is not touch: inbuf->ptr and inbuf->ptr->tot_len*/
           total_length_received += inbuf->ptr->tot_len;
           /*free pbuf memory*/
           netbuf_delete(inbuf);
        }
        else
        {
           current_timer = PIT_CVAL0;//get last time
           break;/*connection closed*/
        }
      }

      /*FSL: no more packets*/
      netconn_close(newconn);
      netconn_delete(newconn);
      
      netconn_close(conn);
      netconn_delete(conn);
      
      /*calculate*/
      time_sfw = (load_value + 1 - current_timer);
      PIT_TCTRL0 = 0;//stop the timer
        
      printf("Benchmark results for TCP Rx:\n\n");
      printf("Number of bytes received = %d\n",total_length_received);
      printf("Number of ticks = %d\n",time_sfw);
      printf("Frequency of ticks = %d\n",(configCPU_CLOCK_HZ/2));
      printf("Calculate benchmark: Bytes/sec\n\n");
      
      final_result = (double)total_length_received * (configCPU_CLOCK_HZ/2) /(double)time_sfw;
      printf("Measured throughput is %9.2f Bytes/sec\n",final_result);
  }
#endif
#endif
}
Esempio n. 10
0
/**
 * Record sensor data and capture images.
 * Activity is recorded to DATA.LOG to be picked up by the Skywire task.
 */
void
camera_task(void * pvParameters) {

	int low_pow = 0;

	/* Initialize the peripherals and state for this task. */
	if (!camera_task_setup()) {
		trace_printf("camera_task: setup failed\n");
		vTaskDelete(NULL);
		return;
	} else {
		trace_printf("camera_task: started\n");
	}

	/* Initialize timing for capture sub-tasks. */
	TickType_t lastReading, lastCapture;
	lastReading = lastCapture = xTaskGetTickCount();

	/* Initialize the sample buffer. */
	samples.Count = 0;

	for (;;) {
		TickType_t currentTicks = xTaskGetTickCount();

		if ((currentTicks - lastReading) >= SAMPLE_RATE_MS) {
			capture_sample(&lastReading);
		}

		//point at which image is captured from camera
		if (arduCamInstalled) {
			if ((currentTicks - lastCapture) >= IMAGE_RATE_MS) {
				//if camera is currently in low power mode, exit low power mode before taking image
				if (low_pow == 1){
					if(arducam_low_power_remove() != DEVICES_OK){
						trace_printf("Error removing low power mode \n");
					}
					else{
						low_pow = 0;
					}
				}

				//only try taking image if low power has been properly disabled
				if (low_pow == 0){
					capture_image(&lastCapture);
				}

				//after image has been taken, put camera down into low-power mode
				if (low_pow == 0){
					if(arducam_low_power_set() != DEVICES_OK){
						trace_printf("Error setting low power mode \n");
					}
					else{
						trace_printf("Low power mode set \n");
						low_pow = 1;
					}
				}
			}
			vTaskDelay(100);
		}
	}

}
Esempio n. 11
0
void vBasicSocketsCommandInterpreterTask( void *pvParameters )
{
long lSocket, lClientFd, lBytes, lAddrLen = sizeof( struct sockaddr_in ), lInputIndex;
struct sockaddr_in sLocalAddr;
struct sockaddr_in client_addr;
const char *pcWelcomeMessage = "FreeRTOS command server - connection accepted.\r\nType Help to view a list of registered commands.\r\n\r\n>";
char cInChar;
static char cInputString[ cmdMAX_INPUT_SIZE ], cOutputString[ cmdMAX_OUTPUT_SIZE ];
portBASE_TYPE xReturned;
extern void vRegisterSampleCLICommands( void );

	( void ) pvParameters;

	/* Register the standard CLI commands. */
	vRegisterSampleCLICommands();

	lSocket = lwip_socket(AF_INET, SOCK_STREAM, 0);

	if( lSocket >= 0 )
	{
		memset((char *)&sLocalAddr, 0, sizeof(sLocalAddr));
		sLocalAddr.sin_family = AF_INET;
		sLocalAddr.sin_len = sizeof(sLocalAddr);
		sLocalAddr.sin_addr.s_addr = htonl(INADDR_ANY);
		sLocalAddr.sin_port = ntohs( ( ( unsigned short ) 23 ) );

		if( lwip_bind( lSocket, ( struct sockaddr *) &sLocalAddr, sizeof( sLocalAddr ) ) < 0 )
		{
			lwip_close( lSocket );
			vTaskDelete( NULL );
		}

		if( lwip_listen( lSocket, 20 ) != 0 )
		{
			lwip_close( lSocket );
			vTaskDelete( NULL );
		}

		for( ;; )
		{

			lClientFd = lwip_accept(lSocket, ( struct sockaddr * ) &client_addr, ( u32_t * ) &lAddrLen );

			if( lClientFd > 0L )
			{
				lwip_send( lClientFd, pcWelcomeMessage, strlen( ( const char * ) pcWelcomeMessage ), 0 );

				lInputIndex = 0;
				memset( cInputString, 0x00, cmdMAX_INPUT_SIZE );

				do
				{
					lBytes = lwip_recv( lClientFd, &cInChar, sizeof( cInChar ), 0 );

					if( lBytes > 0L )
					{
						if( cInChar == '\n' )
						{
							/* The input string has been terminated.  Was the
							input a quit command? */
							if( strcmp( "quit", ( const char * ) cInputString ) == 0 )
							{
								/* Set lBytes to 0 to close the connection. */
								lBytes = 0L;
							}
							else
							{
								/* The input string was not a quit command.
								Pass the string to the command interpreter. */
								do
								{
									/* Get the next output string from the command interpreter. */
									xReturned = FreeRTOS_CLIProcessCommand( cInputString, cOutputString, cmdMAX_INPUT_SIZE );
									lwip_send( lClientFd, cOutputString, strlen( ( const char * ) cOutputString ), 0 );

								} while( xReturned != pdFALSE );


								/* All the strings generated by the input
								command have been sent.  Clear the input
								string ready to receive the next command. */
								lInputIndex = 0;
								memset( cInputString, 0x00, cmdMAX_INPUT_SIZE );
								lwip_send( lClientFd, "\r\n>", strlen( "\r\n>" ), 0 );
							}
						}
						else
						{
							if( cInChar == '\r' )
							{
								/* Ignore the character. */
							}
							else if( cInChar == '\b' )
							{
								/* Backspace was pressed.  Erase the last
								character in the string - if any. */
								if( lInputIndex > 0 )
								{
									lInputIndex--;
									cInputString[ lInputIndex ] = '\0';
								}
							}
							else if( ( cInChar >= ' ' ) && ( cInChar <= 'z' ) )
							{
								/* A character was entered.  Add it to the string
								entered so far.  When a \n is entered the complete
								string will be passed to the command interpreter. */
								if( lInputIndex < cmdMAX_INPUT_SIZE )
								{
									cInputString[ lInputIndex ] = cInChar;
									lInputIndex++;
								}
							}
						}
					}

				} while( lBytes > 0L );

				 lwip_close( lClientFd );
			}
		}
	}

	/* Will only get here if a listening socket could not be created. */
	vTaskDelete( NULL );
}
Esempio n. 12
0
void aws_iot_task(void *param) {
    IoT_Error_t rc = FAILURE;

    char JsonDocumentBuffer[MAX_LENGTH_OF_UPDATE_JSON_BUFFER];
    size_t sizeOfJsonDocumentBuffer = sizeof(JsonDocumentBuffer) / sizeof(JsonDocumentBuffer[0]);
    float temperature = 0.0;

    bool windowOpen = false;
    jsonStruct_t windowActuator;
    windowActuator.cb = windowActuate_Callback;
    windowActuator.pData = &windowOpen;
    windowActuator.pKey = "windowOpen";
    windowActuator.type = SHADOW_JSON_BOOL;

    jsonStruct_t temperatureHandler;
    temperatureHandler.cb = NULL;
    temperatureHandler.pKey = "temperature";
    temperatureHandler.pData = &temperature;
    temperatureHandler.type = SHADOW_JSON_FLOAT;

    ESP_LOGI(TAG, "AWS IoT SDK Version %d.%d.%d-%s", VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH, VERSION_TAG);

    // initialize the mqtt client
    AWS_IoT_Client mqttClient;

    ShadowInitParameters_t sp = ShadowInitParametersDefault;
    sp.pHost = AWS_IOT_MQTT_HOST;
    sp.port = AWS_IOT_MQTT_PORT;

#if defined(CONFIG_EXAMPLE_EMBEDDED_CERTS)
    sp.pClientCRT = (const char *)certificate_pem_crt_start;
    sp.pClientKey = (const char *)private_pem_key_start;
    sp.pRootCA = (const char *)aws_root_ca_pem_start;
#elif defined(CONFIG_EXAMPLE_FILESYSTEM_CERTS)
    sp.pClientCRT = DEVICE_CERTIFICATE_PATH;
    sp.pClientKey = DEVICE_PRIVATE_KEY_PATH;
    sp.pRootCA = ROOT_CA_PATH;
#endif
    sp.enableAutoReconnect = false;
    sp.disconnectHandler = NULL;

#ifdef CONFIG_EXAMPLE_SDCARD_CERTS
    ESP_LOGI(TAG, "Mounting SD card...");
    sdmmc_host_t host = SDMMC_HOST_DEFAULT();
    sdmmc_slot_config_t slot_config = SDMMC_SLOT_CONFIG_DEFAULT();
    esp_vfs_fat_sdmmc_mount_config_t mount_config = {
        .format_if_mount_failed = false,
        .max_files = 3,
    };
    sdmmc_card_t* card;
    esp_err_t ret = esp_vfs_fat_sdmmc_mount("/sdcard", &host, &slot_config, &mount_config, &card);
    if (ret != ESP_OK) {
        ESP_LOGE(TAG, "Failed to mount SD card VFAT filesystem.");
        abort();
    }
#endif

    /* Wait for WiFI to show as connected */
    xEventGroupWaitBits(wifi_event_group, CONNECTED_BIT,
                        false, true, portMAX_DELAY);

    ESP_LOGI(TAG, "Shadow Init");
    rc = aws_iot_shadow_init(&mqttClient, &sp);
    if(SUCCESS != rc) {
        ESP_LOGE(TAG, "aws_iot_shadow_init returned error %d, aborting...", rc);
        abort();
    }

    ShadowConnectParameters_t scp = ShadowConnectParametersDefault;
    scp.pMyThingName = CONFIG_AWS_EXAMPLE_THING_NAME;
    scp.pMqttClientId = CONFIG_AWS_EXAMPLE_CLIENT_ID;
    scp.mqttClientIdLen = (uint16_t) strlen(CONFIG_AWS_EXAMPLE_CLIENT_ID);

    ESP_LOGI(TAG, "Shadow Connect");
    rc = aws_iot_shadow_connect(&mqttClient, &scp);
    if(SUCCESS != rc) {
        ESP_LOGE(TAG, "aws_iot_shadow_connect returned error %d, aborting...", rc);
        abort();
    }

    /*
     * Enable Auto Reconnect functionality. Minimum and Maximum time of Exponential backoff are set in aws_iot_config.h
     *  #AWS_IOT_MQTT_MIN_RECONNECT_WAIT_INTERVAL
     *  #AWS_IOT_MQTT_MAX_RECONNECT_WAIT_INTERVAL
     */
    rc = aws_iot_shadow_set_autoreconnect_status(&mqttClient, true);
    if(SUCCESS != rc) {
        ESP_LOGE(TAG, "Unable to set Auto Reconnect to true - %d, aborting...", rc);
        abort();
    }

    rc = aws_iot_shadow_register_delta(&mqttClient, &windowActuator);

    if(SUCCESS != rc) {
        ESP_LOGE(TAG, "Shadow Register Delta Error");
    }
    temperature = STARTING_ROOMTEMPERATURE;

    // loop and publish a change in temperature
    while(NETWORK_ATTEMPTING_RECONNECT == rc || NETWORK_RECONNECTED == rc || SUCCESS == rc) {
        rc = aws_iot_shadow_yield(&mqttClient, 200);
        if(NETWORK_ATTEMPTING_RECONNECT == rc || shadowUpdateInProgress) {
            rc = aws_iot_shadow_yield(&mqttClient, 1000);
            // If the client is attempting to reconnect, or already waiting on a shadow update,
            // we will skip the rest of the loop.
            continue;
        }
        ESP_LOGI(TAG, "=======================================================================================");
        ESP_LOGI(TAG, "On Device: window state %s", windowOpen ? "true" : "false");
        simulateRoomTemperature(&temperature);

        rc = aws_iot_shadow_init_json_document(JsonDocumentBuffer, sizeOfJsonDocumentBuffer);
        if(SUCCESS == rc) {
            rc = aws_iot_shadow_add_reported(JsonDocumentBuffer, sizeOfJsonDocumentBuffer, 2, &temperatureHandler,
                                             &windowActuator);
            if(SUCCESS == rc) {
                rc = aws_iot_finalize_json_document(JsonDocumentBuffer, sizeOfJsonDocumentBuffer);
                if(SUCCESS == rc) {
                    ESP_LOGI(TAG, "Update Shadow: %s", JsonDocumentBuffer);
                    rc = aws_iot_shadow_update(&mqttClient, CONFIG_AWS_EXAMPLE_THING_NAME, JsonDocumentBuffer,
                                               ShadowUpdateStatusCallback, NULL, 4, true);
                    shadowUpdateInProgress = true;
                }
            }
        }
        ESP_LOGI(TAG, "*****************************************************************************************");
        vTaskDelay(1000 / portTICK_RATE_MS);
    }

    if(SUCCESS != rc) {
        ESP_LOGE(TAG, "An error occurred in the loop %d", rc);
    }

    ESP_LOGI(TAG, "Disconnecting");
    rc = aws_iot_shadow_disconnect(&mqttClient);

    if(SUCCESS != rc) {
        ESP_LOGE(TAG, "Disconnect error %d", rc);
    }

    vTaskDelete(NULL);
}

static void initialise_wifi(void)
{
    tcpip_adapter_init();
    wifi_event_group = xEventGroupCreate();
    ESP_ERROR_CHECK( esp_event_loop_init(event_handler, NULL) );
    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
    ESP_ERROR_CHECK( esp_wifi_init(&cfg) );
    ESP_ERROR_CHECK( esp_wifi_set_storage(WIFI_STORAGE_RAM) );
    wifi_config_t wifi_config = {
        .sta = {
            .ssid = EXAMPLE_WIFI_SSID,
            .password = EXAMPLE_WIFI_PASS,
        },
    };
    ESP_LOGI(TAG, "Setting WiFi configuration SSID %s...", wifi_config.sta.ssid);
    ESP_ERROR_CHECK( esp_wifi_set_mode(WIFI_MODE_STA) );
    ESP_ERROR_CHECK( esp_wifi_set_config(WIFI_IF_STA, &wifi_config) );
    ESP_ERROR_CHECK( esp_wifi_start() );
}
Esempio n. 13
0
/*!
 * \brief Supervisor task.
 *
 * \return never
 */
static portTASK_FUNCTION( vSupervisorTask, pvParameters )
{
   portTickType xDelayLength = SUPERVISOR_DEFAULT_PERIOD;
   portTickType xLastFocusTime;
#if configHEAP_INIT == 1
#if defined(__GNUC__)
   portLONG     lCheckHeapDelay = 1;
#endif
#endif
#if configCTRLPANEL_TRACE == 1
   portLONG     lPrintTrace = 3;
#endif
   portLONG     lUpdateTimeDelay = 1;
#ifdef MMILCD_ENABLE
   portLONG     lUpdateMMITimeDelay = 1;
   portCHAR DateTime[21];
   struct tm *pxDate;
   bool ms_connected_displayed = pdFALSE;
   bool enum_connected_displayed = pdFALSE;
#endif

   /* The parameters are not used. */
   ( void )pvParameters;

#if configCTRLPANEL_TRACE == 1
   /* Initialize the dump port COM2. */
   itracedump_Init();
#endif

#ifdef MMILCD_ENABLE
   // The MMI module.
   if( pdFALSE == bMMI_start() )
   {
      // vParTestSetLED( ERROR_LED_ID, pdTRUE );
      while( 1 );
   }
#endif

   // Create the SHELL mutex.
   vSemaphoreCreateBinary( xSHELLFSMutex );
   if( NULL == xSHELLFSMutex )
   { // The mutex creation failed.
      // TODO: Add msg on LCD.
      // vParTestSetLED( ERROR_LED_ID, pdTRUE );
      while( 1 );
   }
   // Start the COM1 Shell module.
   vStartCom1Shell( mainCOMSH_TASK_PRIORITY );

   // Create the CFG mutex.
   vSemaphoreCreateBinary( xCFGMutex );
   if( NULL == xCFGMutex )
   { // The mutex creation failed.
      // TODO: Add msg on LCD.
      // vParTestSetLED( ERROR_LED_ID, pdTRUE );
      while( 1 );
   }

   // Start the sensor module.
   if( false == bsensor_start() )
   {
      // TODO: Add msg on LCD.
      // vParTestSetLED( ERROR_LED_ID, pdTRUE );
      while( 1 );
   }

#if NW_INTEGRATED_IN_CONTROL_PANEL
   // Create the Web server mutex.
   vSemaphoreCreateBinary( xWEBMutex );
   if( NULL == xWEBMutex )
   { // The mutex creation failed.
      // TODO: Add msg on LCD.
      // vParTestSetLED( ERROR_LED_ID, pdTRUE );
      while( 1 );
   }
   // Start network tasks.
   vStartEthernetTaskLauncher( tskIDLE_PRIORITY + 1 );
#endif

   // Create the LOG mutex.
   vSemaphoreCreateBinary( xLOGMutex );
   if( NULL == xLOGMutex )
   { // The mutex creation failed.
      // TODO: Add msg on LCD.
      // vParTestSetLED( ERROR_LED_ID, pdTRUE );
      while( 1 );
   }
   // Start the data logger module.
   if( false == bdatalog_start( mainDATALOG_TASK_PRIORITY ) )
   {
      // TODO: Add msg on LCD.
      // vParTestSetLED( ERROR_LED_ID, pdTRUE );
      while( 1 );
   }

#ifdef USB_ENABLE
#if USB_DEVICE_FEATURE == true
   // Create the USB mutex.
   vSemaphoreCreateBinary( xUSBMutex );
   if( NULL == xUSBMutex )
   { // The mutex creation failed.
      // TODO: Add msg on LCD.
      // vParTestSetLED( ERROR_LED_ID, pdTRUE );
      while( 1 );
   }
   // Immediately take the USB mutex. i.e. when we're a Mass Storage device,
   // we'll refuse to give r/w access to the host until a user action. This user
   // action will make the Ctrl Panel device switch to maintenance mode, in which
   // the Mass Storage USB host has r/w access to the Ctrl Panel file system.
   while( pdFALSE == x_supervisor_SemaphoreTake( xUSBMutex, 0 ) );
#endif
   // Start the USB module tasks.
   if( false == b_usbsys_start() )
   {
      // TODO: Add msg on LCD.
      // vParTestSetLED( ERROR_LED_ID, pdTRUE );
      while( 1 );
   }
#endif

#ifdef MMILCD_ENABLE
   // Create the supervisor queue to deal with MMI actions
   xSUPERVISORQueue = xQueueCreate( SUPERVISOR_QUEUE_SIZE, sizeof(bool *) );
   if( 0 == xSUPERVISORQueue )
   {
      // TODO: Add msg on LCD.
      // vParTestSetLED( ERROR_LED_ID, pdTRUE );
      while( 1 );
   }

   /* Get a File System navigator for MMI actions. */
   fsaccess_take_mutex();
   sMmiNavId = fsaccess_alloc_nav_id();
   nav_select( sMmiNavId );   // Select the navigator.
   fsaccess_give_mutex();

   /* Spawn the User Action task. */
   if( pdPASS != xTaskCreate( vSupervisorUserActionTask,
                              ( const signed portCHAR * )"MMIACT",
                              SUPERVISOR_USER_ACTION_STACK_SIZE, NULL, SUPERVISOR_USER_ACTION_TASK_PRIORITY,
                              &xSupervisorUserActionHndl ) )
   {
      vTaskDelete( xSupervisorUserActionHndl );
      // TODO: Add msg on LCD.
      // vParTestSetLED( ERROR_LED_ID, pdTRUE );
      while( 1 );
   }
#endif // #ifdef MMILCD_ENABLE

   /* We need to initialise xLastFlashTime prior to the first call to vTaskDelayUntil(). */
   xLastFocusTime = xTaskGetTickCount();

#if defined(__GNUC__)
   NAKED_TRACE_COM2( "heap start @=%d, heap end @=%d", \
                     (portBASE_TYPE *)&__heap_start__, \
                     (portBASE_TYPE *)&__heap_end__ );
#endif

   /* Enable the watchdog timer. */
   // wdt_enable( SUPERVISOR_WDT_TIMEOUT );

   for(;;)
   {
      /* Delay for the flash period then check. */
      vTaskDelayUntil( &xLastFocusTime, xDelayLength );

      // wdt_clear(); // Kick the watchdog!

      /* MMI USB management. */
#ifdef MMILCD_ENABLE
#ifdef USB_ENABLE
/*** Start of Host behaviour ***/
      // first occurrence of MS connection, Host mode
      if (ms_connected == true && ms_connected_displayed == pdFALSE)
      {
        // display connected logo
        ms_connected_displayed = pdTRUE;
        vMMI_DisplayUSBState(ms_connected_displayed);
        // Display User Menu
        vMMI_SetUserMenuMode(eUserMenuUSBHost, pdTRUE);

      }
      // first occurrence of MS disconnection, end of Host mode
      if (ms_connected == false && ms_connected_displayed == pdTRUE)
      {
        // remove connected logo
        ms_connected_displayed = pdFALSE;
        vMMI_DisplayUSBState(ms_connected_displayed);
        // clear User Menu
        vMMI_SetUserMenuMode(eUserMenuIdle, pdTRUE);
      }
/*** End of Host behaviour ***/
/*** Start of Device behaviour ***/
#if USB_DEVICE_FEATURE == true
      // first occurrence of Device connection, Device mode
      if (Is_device_enumerated() && ( enum_connected_displayed == pdFALSE ) )
      {
        if( true == bIsInMaintenance )
        {
          // display connected logo
          enum_connected_displayed = pdTRUE;
          vMMI_DisplayUSBState(enum_connected_displayed);
          // Display User Menu
          vMMI_SetUserMenuMode(eUserMenuUSBDevice, pdTRUE);
        }
      }
      // first occurrence of Device disconnection, end of Device mode
      else if (!Is_device_enumerated() && enum_connected_displayed == pdTRUE)
      {
        // remove connected logo
        enum_connected_displayed = pdFALSE;
        vMMI_DisplayUSBState(enum_connected_displayed);
        // clear User Menu
        vMMI_SetUserMenuMode(eUserMenuIdle, pdTRUE);
      }
      else
      {
        // remove connected logo => this makes the USB logo blink when the Control
        // Panel is behaving as a USB key.
        enum_connected_displayed = pdFALSE;
        vMMI_DisplayUSBState(enum_connected_displayed);
      }
/*** End of Device behaviour ***/
#endif // #if USB_DEVICE_FEATURE == true
#endif // #ifdef USB_ENABLE
#endif // #ifdef MMILCD_ENABLE

      /* update time every SUPERVISOR_DELAY_TIMEUPDATE seconds. */
      if( 0 == --lUpdateTimeDelay )
      {
         /* Update the local time. */
         lUpdateTimeDelay = SUPERVISOR_DELAY_TIMEUPDATE;
         xcptime_LocalTime++;
         // v_cptime_UpdateLocalTime();
      }

#ifdef MMILCD_ENABLE
      /* Update time displayed on the LCD. */
      if( 0 == --lUpdateMMITimeDelay)
      {
         // Get the broken-down representation of the current date.
         pxDate = gmtime( &xcptime_LocalTime );

         // WARNING: pxDate->tm_year == number of years since 1900.
         // For years >= 2000, we'll display the last 2 digits only.
         if( pxDate->tm_year >= 100 )  pxDate->tm_year -= 100;
#if DISPLAY_MMI_SECOND == 1
         sprintf( DateTime, "%02d/%02d/20%02d  %02d:%02d:%02d", pxDate->tm_mon +1, pxDate->tm_mday,
                            pxDate->tm_year, pxDate->tm_hour, pxDate->tm_min, pxDate->tm_sec );
#else
         sprintf( DateTime, "%02d/%02d/20%02d     %02d:%02d", pxDate->tm_mon +1, pxDate->tm_mday,
                            pxDate->tm_year, pxDate->tm_hour, pxDate->tm_min );
#endif
         vMMI_DisplayDateAndTime(DateTime);
         lUpdateMMITimeDelay = SUPERVISOR_DELAY_MMI_TIMEUPDATE;
      }

      // Manage MMI
      vMMI_Manage();

      // Manage MMI user action
      prv_v_manage_user_action();
#endif // #ifdef MMILCD_ENABLE

#ifdef USB_ENABLE
      if( true == bOutOfMaintenance )
      {
         prv_v_leave_maintenance_mode();
      }
#endif

      /* Execute a scheduled command if expiration date is up. */
      v_cptime_ExecuteScheduledCmd();

#if configHEAP_INIT == 1
#if defined(__GNUC__)
      /* Record the malloc() heap highest consumption every SUPERVISOR_DELAY_HEAPCHECK seconds. */
      if( 0 == --lCheckHeapDelay )
      {
         lCheckHeapDelay = SUPERVISOR_DELAY_HEAPCHECK;
         prvCheckMallocHeap();
      }
#endif
#endif

#if configCTRLPANEL_TRACE == 1
      // Display traces on USART1 every SUPERVISOR_DELAY_PRINTTASKLIST seconds.
      if( 0 == --lPrintTrace )
      {
         lPrintTrace = SUPERVISOR_DELAY_PRINTTASKLIST; // Restart the delay.
         v_syscmds_display_traces();
      }
#endif

   } // for(;;)
} /*lint !e715 !e818 !e830 Function definition must be standard for task creation. */
Esempio n. 14
0
static void mqtt_client_thread(void *pvParameters)
{
    char *payload = NULL;
    MQTTClient client;
    Network network;
    int rc = 0;
    char clientID[32] = {0};
    uint32_t count = 0;

    ESP_LOGI(TAG, "ssid:%s passwd:%s sub:%s qos:%u pub:%s qos:%u pubinterval:%u payloadsize:%u",
             CONFIG_WIFI_SSID, CONFIG_WIFI_PASSWORD, CONFIG_MQTT_SUB_TOPIC,
             CONFIG_DEFAULT_MQTT_SUB_QOS, CONFIG_MQTT_PUB_TOPIC, CONFIG_DEFAULT_MQTT_PUB_QOS,
             CONFIG_MQTT_PUBLISH_INTERVAL, CONFIG_MQTT_PAYLOAD_BUFFER);

    ESP_LOGI(TAG, "ver:%u clientID:%s keepalive:%d username:%s passwd:%s session:%d level:%u",
             CONFIG_DEFAULT_MQTT_VERSION, CONFIG_MQTT_CLIENT_ID,
             CONFIG_MQTT_KEEP_ALIVE, CONFIG_MQTT_USERNAME, CONFIG_MQTT_PASSWORD,
             CONFIG_DEFAULT_MQTT_SESSION, CONFIG_DEFAULT_MQTT_SECURITY);

    ESP_LOGI(TAG, "broker:%s port:%u", CONFIG_MQTT_BROKER, CONFIG_MQTT_PORT);

    ESP_LOGI(TAG, "sendbuf:%u recvbuf:%u sendcycle:%u recvcycle:%u",
             CONFIG_MQTT_SEND_BUFFER, CONFIG_MQTT_RECV_BUFFER,
             CONFIG_MQTT_SEND_CYCLE, CONFIG_MQTT_RECV_CYCLE);

    MQTTPacket_connectData connectData = MQTTPacket_connectData_initializer;

    NetworkInit(&network);

    if (MQTTClientInit(&client, &network, 0, NULL, 0, NULL, 0) == false) {
        ESP_LOGE(TAG, "mqtt init err");
        vTaskDelete(NULL);
    }

    payload = malloc(CONFIG_MQTT_PAYLOAD_BUFFER);

    if (!payload) {
        ESP_LOGE(TAG, "mqtt malloc err");
    } else {
        memset(payload, 0x0, CONFIG_MQTT_PAYLOAD_BUFFER);
    }

    for (;;) {
        ESP_LOGI(TAG, "wait wifi connect...");
        xEventGroupWaitBits(wifi_event_group, CONNECTED_BIT, false, true, portMAX_DELAY);

        if ((rc = NetworkConnect(&network, CONFIG_MQTT_BROKER, CONFIG_MQTT_PORT)) != 0) {
            ESP_LOGE(TAG, "Return code from network connect is %d", rc);
            continue;
        }

        connectData.MQTTVersion = CONFIG_DEFAULT_MQTT_VERSION;

        sprintf(clientID, "%s_%u", CONFIG_MQTT_CLIENT_ID, esp_random());

        connectData.clientID.cstring = clientID;
        connectData.keepAliveInterval = CONFIG_MQTT_KEEP_ALIVE;

        connectData.username.cstring = CONFIG_MQTT_USERNAME;
        connectData.password.cstring = CONFIG_MQTT_PASSWORD;

        connectData.cleansession = CONFIG_DEFAULT_MQTT_SESSION;

        ESP_LOGI(TAG, "MQTT Connecting");

        if ((rc = MQTTConnect(&client, &connectData)) != 0) {
            ESP_LOGE(TAG, "Return code from MQTT connect is %d", rc);
            network.disconnect(&network);
            continue;
        }

        ESP_LOGI(TAG, "MQTT Connected");

#if defined(MQTT_TASK)

        if ((rc = MQTTStartTask(&client)) != pdPASS) {
            ESP_LOGE(TAG, "Return code from start tasks is %d", rc);
        } else {
            ESP_LOGI(TAG, "Use MQTTStartTask");
        }

#endif

        if ((rc = MQTTSubscribe(&client, CONFIG_MQTT_SUB_TOPIC, CONFIG_DEFAULT_MQTT_SUB_QOS, messageArrived)) != 0) {
            ESP_LOGE(TAG, "Return code from MQTT subscribe is %d", rc);
            network.disconnect(&network);
            continue;
        }

        ESP_LOGI(TAG, "MQTT subscribe to topic %s OK", CONFIG_MQTT_SUB_TOPIC);

        for (;;) {
            MQTTMessage message;

            message.qos = CONFIG_DEFAULT_MQTT_PUB_QOS;
            message.retained = 0;
            message.payload = payload;
            sprintf(payload, "message number %d", ++count);
            message.payloadlen = strlen(payload);

            if ((rc = MQTTPublish(&client, CONFIG_MQTT_PUB_TOPIC, &message)) != 0) {
                ESP_LOGE(TAG, "Return code from MQTT publish is %d", rc);
            } else {
                ESP_LOGI(TAG, "MQTT published topic %s, len:%u heap:%u", CONFIG_MQTT_PUB_TOPIC, message.payloadlen, esp_get_free_heap_size());
            }

            if (rc != 0) {
                break;
            }

            vTaskDelay(CONFIG_MQTT_PUBLISH_INTERVAL / portTICK_RATE_MS);
        }

        network.disconnect(&network);
    }

    ESP_LOGW(TAG, "mqtt_client_thread going to be deleted");
    vTaskDelete(NULL);
    return;
}
Esempio n. 15
0
static void prvDemonstrateTaskStateAndHandleGetFunctions( void )
{
TaskHandle_t xIdleTaskHandle, xTimerTaskHandle;
char *pcTaskName;
static portBASE_TYPE xPerformedOneShotTests = pdFALSE;
TaskHandle_t xTestTask;
TaskStatus_t xTaskInfo;
extern StackType_t uxTimerTaskStack[];

	/* Demonstrate the use of the xTimerGetTimerDaemonTaskHandle() and
	xTaskGetIdleTaskHandle() functions.  Also try using the function that sets
	the task number. */
	xIdleTaskHandle = xTaskGetIdleTaskHandle();
	xTimerTaskHandle = xTimerGetTimerDaemonTaskHandle();

	/* This is the idle hook, so the current task handle should equal the
	returned idle task handle. */
	if( xTaskGetCurrentTaskHandle() != xIdleTaskHandle )
	{
		pcStatusMessage = "Error:  Returned idle task handle was incorrect";
	}

	/* Check the same handle is obtained using the idle task's name.  First try
	with the wrong name, then the right name. */
	if( xTaskGetHandle( "Idle" ) == xIdleTaskHandle )
	{
		pcStatusMessage = "Error:  Returned handle for name Idle was incorrect";
	}

	if( xTaskGetHandle( "IDLE" ) != xIdleTaskHandle )
	{
		pcStatusMessage = "Error:  Returned handle for name Idle was incorrect";
	}

	/* Check the timer task handle was returned correctly. */
	pcTaskName = pcTaskGetName( xTimerTaskHandle );
	if( strcmp( pcTaskName, "Tmr Svc" ) != 0 )
	{
		pcStatusMessage = "Error:  Returned timer task handle was incorrect";
	}

	if( xTaskGetHandle( "Tmr Svc" ) != xTimerTaskHandle )
	{
		pcStatusMessage = "Error:  Returned handle for name Tmr Svc was incorrect";
	}

	/* This task is running, make sure it's state is returned as running. */
	if( eTaskStateGet( xIdleTaskHandle ) != eRunning )
	{
		pcStatusMessage = "Error:  Returned idle task state was incorrect";
	}

	/* If this task is running, then the timer task must be blocked. */
	if( eTaskStateGet( xTimerTaskHandle ) != eBlocked )
	{
		pcStatusMessage = "Error:  Returned timer task state was incorrect";
	}

	/* Also with the vTaskGetInfo() function. */
	vTaskGetInfo( xTimerTaskHandle, /* The task being queried. */
					  &xTaskInfo,		/* The structure into which information on the task will be written. */
					  pdTRUE,			/* Include the task's high watermark in the structure. */
					  eInvalid );		/* Include the task state in the structure. */

	/* Check the information returned by vTaskGetInfo() is as expected. */
	if( ( xTaskInfo.eCurrentState != eBlocked )						 ||
		( strcmp( xTaskInfo.pcTaskName, "Tmr Svc" ) != 0 )			 ||
		( xTaskInfo.uxCurrentPriority != configTIMER_TASK_PRIORITY ) ||
		( xTaskInfo.pxStackBase != uxTimerTaskStack )				 ||
		( xTaskInfo.xHandle != xTimerTaskHandle ) )
	{
		pcStatusMessage = "Error:  vTaskGetInfo() returned incorrect information about the timer task";
	}

	/* Other tests that should only be performed once follow.  The test task
	is not created on each iteration because to do so would cause the death
	task to report an error (too many tasks running). */
	if( xPerformedOneShotTests == pdFALSE )
	{
		/* Don't run this part of the test again. */
		xPerformedOneShotTests = pdTRUE;

		/* Create a test task to use to test other eTaskStateGet() return values. */
		if( xTaskCreate( prvTestTask, "Test", configMINIMAL_STACK_SIZE, NULL, tskIDLE_PRIORITY, &xTestTask ) == pdPASS )
		{
			/* If this task is running, the test task must be in the ready state. */
			if( eTaskStateGet( xTestTask ) != eReady )
			{
				pcStatusMessage = "Error: Returned test task state was incorrect 1";
			}

			/* Now suspend the test task and check its state is reported correctly. */
			vTaskSuspend( xTestTask );
			if( eTaskStateGet( xTestTask ) != eSuspended )
			{
				pcStatusMessage = "Error: Returned test task state was incorrect 2";
			}

			/* Now delete the task and check its state is reported correctly. */
			vTaskDelete( xTestTask );
			if( eTaskStateGet( xTestTask ) != eDeleted )
			{
				pcStatusMessage = "Error: Returned test task state was incorrect 3";
			}
		}
	}
}
/**
  * @brief  LwIP_DHCP_Process_Handle
  * @param  None
  * @retval None
  */
void LwIP_DHCP_task(void * pvParameters)
{
  struct ip_addr ipaddr;
  struct ip_addr netmask;
  struct ip_addr gw;
  uint32_t IPaddress;
  uint8_t iptab[4];
  uint8_t iptxt[20];
  uint8_t DHCP_state;  
  DHCP_state = DHCP_START;

  for (;;)
  {
    switch (DHCP_state)
    {
      case DHCP_START:
      {
        dhcp_start(&xnetif);
        IPaddress = 0;
        DHCP_state = DHCP_WAIT_ADDRESS;
#ifdef USE_LCD
        LCD_DisplayStringLine(Line4, (uint8_t*)"     Looking for    ");
        LCD_DisplayStringLine(Line5, (uint8_t*)"     DHCP server    ");
        LCD_DisplayStringLine(Line6, (uint8_t*)"     please wait... ");
#endif
      }
      break;

      case DHCP_WAIT_ADDRESS:
      {
        /* Read the new IP address */
        IPaddress = xnetif.ip_addr.addr;

        if (IPaddress!=0) 
        {
          DHCP_state = DHCP_ADDRESS_ASSIGNED;	
          
          /* Stop DHCP */
          dhcp_stop(&xnetif);

#ifdef USE_LCD      
          iptab[0] = (uint8_t)(IPaddress >> 24);
          iptab[1] = (uint8_t)(IPaddress >> 16);
          iptab[2] = (uint8_t)(IPaddress >> 8);
          iptab[3] = (uint8_t)(IPaddress);

          sprintf((char*)iptxt, "  %d.%d.%d.%d", iptab[3], iptab[2], iptab[1], iptab[0]);  

          LCD_ClearLine(Line4);
          LCD_ClearLine(Line5);
          LCD_ClearLine(Line6);
          /* Display the IP address */
          LCD_DisplayStringLine(Line7, (uint8_t*)"IP address assigned ");
          LCD_DisplayStringLine(Line8, (uint8_t*)"  by a DHCP server  ");
          LCD_DisplayStringLine(Line9, iptxt);
#endif  
          /* end of DHCP process: LED1 stays ON*/
          STM_EVAL_LEDOn(LED1);
          vTaskDelete(NULL);
        }
        else
        {
          /* DHCP timeout */
          if (xnetif.dhcp->tries > MAX_DHCP_TRIES)
          {
            DHCP_state = DHCP_TIMEOUT;

            /* Stop DHCP */
            dhcp_stop(&xnetif);

            /* Static address used */
            IP4_ADDR(&ipaddr, IP_ADDR0 ,IP_ADDR1 , IP_ADDR2 , IP_ADDR3 );
            IP4_ADDR(&netmask, NETMASK_ADDR0, NETMASK_ADDR1, NETMASK_ADDR2, NETMASK_ADDR3);
            IP4_ADDR(&gw, GW_ADDR0, GW_ADDR1, GW_ADDR2, GW_ADDR3);
            netif_set_addr(&xnetif, &ipaddr , &netmask, &gw);

#ifdef USE_LCD   
            LCD_DisplayStringLine(Line7, (uint8_t*)"    DHCP timeout    ");

            iptab[0] = IP_ADDR3;
            iptab[1] = IP_ADDR2;
            iptab[2] = IP_ADDR1;
            iptab[3] = IP_ADDR0;

            sprintf((char*)iptxt, "  %d.%d.%d.%d", iptab[3], iptab[2], iptab[1], iptab[0]); 

            LCD_ClearLine(Line4);
            LCD_ClearLine(Line5);
            LCD_ClearLine(Line6);
            LCD_DisplayStringLine(Line8, (uint8_t*)"  Static IP address   ");
            LCD_DisplayStringLine(Line9, iptxt);
#endif
            /* end of DHCP process: LED1 stays ON*/
            STM_EVAL_LEDOn(LED1);
            vTaskDelete(NULL);
          }
        }
      }
      break;

      default: break;
    }
Esempio n. 17
0
int iBoilKey(int xx, int yy)
{
  static BoilMessage xMessage;

  xMessage.ucFromTask = 0;
  xMessage.iBrewStep = 0;
  static int zero = 0;
  static uint8_t w = 5,h = 5;
  static uint16_t last_window = 0;
  if (xx > DUTY_UP_X1+1 && xx < DUTY_UP_X2-1 && yy > DUTY_UP_Y1+1 && yy < DUTY_UP_Y2-1)
    {
      diag_duty+=1;

      //printf("Duty Cycle is now %d\r\n\0", diag_duty);
      if (uiBoilState == BOILING)
        {
          xMessage.iDutyCycle = diag_duty;
          xQueueSendToBack(xBoilQueue, &xMessage, 0);
        }
    }
  else if (xx > DUTY_DN_X1+1 && xx < DUTY_DN_X2-1 && yy > DUTY_DN_Y1+1 && yy < DUTY_DN_Y2-1)
    {
      if (diag_duty == 0)
        diag_duty = 0;
      else diag_duty-=1;
      //printf("Duty Cycle is now %d\r\n\0", diag_duty);
      if (uiBoilState == BOILING)
        {
          xMessage.iDutyCycle = diag_duty;
          xQueueSendToBack(xBoilQueue, &xMessage, 0);
        }
    }
  else if (xx > STOP_HEATING_X1+1 && xx < STOP_HEATING_X2-1 && yy > STOP_HEATING_Y1+1 && yy < STOP_HEATING_Y2-1)
    {
      xMessage.iDutyCycle = zero;
      xQueueSendToBack(xBoilQueue, &xMessage, 0);
    }
  else if (xx > START_HEATING_X1+1 && xx < START_HEATING_X2-1 && yy > START_HEATING_Y1+1 && yy < START_HEATING_Y2-1)
    {
      xMessage.iDutyCycle = diag_duty;
      xQueueSendToBack(xBoilQueue, &xMessage, 0);

    }
  else if (xx > BAK_X1 && yy > BAK_Y1 && xx < BAK_X2 && yy < BAK_Y2)
    {
      //try to take the semaphore from the display applet. wait here if we cant take it.
      xSemaphoreTake(xAppletRunningSemaphore, portMAX_DELAY);
      //delete the display applet task if its been created.
      if (xBoilAppletDisplayHandle != NULL)
        {
          vTaskDelete(xBoilAppletDisplayHandle);
          vTaskDelay(100);
          xBoilAppletDisplayHandle = NULL;
        }

      //return the semaphore for taking by another task.
      xSemaphoreGive(xAppletRunningSemaphore);
      return 1;
    }
  vTaskDelay(10);
  return 0;
}
static void prvOldStyleUserModeTask( void *pvParameters )
{
extern unsigned long __privileged_data_start__[];
extern unsigned long __privileged_data_end__[];
extern unsigned long __SRAM_segment_end__[];
extern unsigned long __privileged_functions_end__[];
extern unsigned long __FLASH_segment_start__[];
extern unsigned long __FLASH_segment_end__[];
const volatile unsigned long *pulStandardPeripheralRegister = ( volatile unsigned long * ) 0x400FC0C4; /* PCONP */
volatile unsigned long *pul;
volatile unsigned long ulReadData;

/* The following lines are commented out to prevent the unused variable 
compiler warnings when the tests that use the variable are also commented out.
extern unsigned long __privileged_functions_start__[];
const volatile unsigned long *pulSystemPeripheralRegister = ( volatile unsigned long * ) 0xe000e014; */

	( void ) pvParameters;

	/* This task is created in User mode using the original xTaskCreate() API
	function.  It should have access to all Flash and RAM except that marked
	as Privileged access only.  Reading from the start and end of the non-
	privileged RAM should not cause a problem (the privileged RAM is the first
	block at the bottom of the RAM memory). */
	pul = __privileged_data_end__ + 1;
	ulReadData = *pul;
	pul = __SRAM_segment_end__ - 1;
	ulReadData = *pul;

	/* Likewise reading from the start and end of the non-privileged Flash
	should not be a problem (the privileged Flash is the first block at the
	bottom of the Flash memory). */
	pul = __privileged_functions_end__ + 1;
	ulReadData = *pul;
	pul = __FLASH_segment_end__ - 1;
	ulReadData = *pul;

	/* Standard peripherals are accessible. */
	ulReadData = *pulStandardPeripheralRegister;

	/* System peripherals are not accessible.  Uncomment the following line
	to test.  Also uncomment the declaration of pulSystemPeripheralRegister
	at the top of this function. */
    /* ulReadData = *pulSystemPeripheralRegister; */

	/* Reading from anywhere inside the privileged Flash or RAM should cause a
	fault.  This can be tested by uncommenting any of the following pairs of
	lines.  Also uncomment the declaration of __privileged_functions_start__
	at the top of this function. */

	/* pul = __privileged_functions_start__;
	ulReadData = *pul; */
	
	/* pul = __privileged_functions_end__ - 1;
	ulReadData = *pul; */

	/* pul = __privileged_data_start__;
	ulReadData = *pul; */ 
	
	/* pul = __privileged_data_end__ - 1;
	ulReadData = *pul; */

	/* Must not just run off the end of a task function, so delete this task. 
	Note that because this task was created using xTaskCreate() the stack was
	allocated dynamically and I have not included any code to free it again. */
	vTaskDelete( NULL );
}
/******************************************************************************
 * FunctionName : user_devicefind_init
 * Description  : the espconn struct parame init
 * Parameters   : none
 * Returns      : none
*******************************************************************************/
LOCAL void  
user_devicefind_task(void *pvParameters)
{
    struct sockaddr_in server_addr;
    int32 ret;
    
    struct sockaddr_in from;
    socklen_t   fromlen;
    struct ip_info ipconfig;
    
    char  *udp_msg;
    bool ValueFromReceive = false;
    portBASE_TYPE xStatus;

    int nNetTimeout=10000;// 1 Sec
    int stack_counter=0;

    memset(&ipconfig, 0, sizeof(ipconfig));
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;       
    server_addr.sin_addr.s_addr = INADDR_ANY;
    server_addr.sin_port = htons(UDF_SERVER_PORT);
    server_addr.sin_len = sizeof(server_addr);

    udp_msg = (char*)malloc(len_udp_msg);

    do{
        sock_fd = socket(AF_INET, SOCK_DGRAM, 0);
        if (sock_fd == -1) {
            os_printf("ERROR:devicefind failed to create sock!\n");
            vTaskDelay(1000/portTICK_RATE_MS);
        }
    }while(sock_fd == -1);

    do{
        ret = bind(sock_fd, (struct sockaddr *)&server_addr, sizeof(server_addr));
        if (ret != 0) {
            os_printf("ERROR:devicefind failed to bind sock!\n");
            vTaskDelay(1000/portTICK_RATE_MS);
        }
    }while(ret != 0);


    while(1){
        
        xStatus = xQueueReceive(QueueStop,&ValueFromReceive,0);
        if ( pdPASS == xStatus && TRUE == ValueFromReceive){
            os_printf("user_devicefind_task rcv exit signal!\n");
            break;
        }

        memset(udp_msg, 0, len_udp_msg);
        memset(&from, 0, sizeof(from));
        
        setsockopt(sock_fd,SOL_SOCKET,SO_RCVTIMEO,(char *)&nNetTimeout,sizeof(int));
        fromlen = sizeof(struct sockaddr_in);
        ret = recvfrom(sock_fd, (u8 *)udp_msg, len_udp_msg, 0,(struct sockaddr *)&from,(socklen_t *)&fromlen);
        if (ret > 0) {
            os_printf("recieve from->port %d  %s\n",ntohs(from.sin_port),inet_ntoa(from.sin_addr));
            user_devicefind_data_process(udp_msg,ret,&from);
        }
        
        if(stack_counter++ ==1){
            stack_counter=0;
            DF_DEBUG("user_devicefind_task %d word left\n",uxTaskGetStackHighWaterMark(NULL));
        }
    }

    if(udp_msg)free(udp_msg);

    close(sock_fd);
    vQueueDelete(QueueStop);
    QueueStop = NULL;
    vTaskDelete(NULL);

}
static void prvDeleteMe( void )
{
	vTaskDelete( NULL );
}
void taskServer( void *pvParameters ){
BsdTcpServer(PORT_NUM);
UART_PRINT("taskServer over\r\n"); 
vTaskDelete(NULL);
}
Esempio n. 22
0
Task::~Task() {
    vTaskDelete(mTaskHandle);
}
Esempio n. 23
0
/**	
	Delete an existing task.
	@param task A pointer to the handle of the task to be deleted.
*/
void TaskDelete( void* task )
{
  vTaskDelete( task );
}
Esempio n. 24
0
////////////////////////////////////////////////////////////////////////////
// Interfacing Function
////////////////////////////////////////////////////////////////////////////
void vTaskDS1820Convert( void *pvParameters ){
    char buf[30];
    static char print_buf[80];
    int ii = 0;
    static float fTemp[NUM_SENSORS] = {0.0, 0.0}, fLastTemp[NUM_SENSORS] = {0.0, 0.0};

    // initialise the bus
    ds1820_init();
    if (ds1820_reset() ==PRESENCE_ERROR)
    {
        ds1820_error(PRESENCE_ERROR);
        vConsolePrint("Presence Error, Deleting DS1820 Task\r\n\0");
        vTaskDelete(NULL); // if this task fails... delete it
    }
  
    // Allocate memory for sensors
    b[HLT] = (char *) pvPortMalloc (sizeof(rom)+1);
    b[MASH] = (char *) pvPortMalloc (sizeof(rom)+1);
   // b[CABINET] = (char *) malloc (sizeof(rom)+1);



    // Copy default values
    memcpy(b[HLT], HLT_TEMP_SENSOR, sizeof(HLT_TEMP_SENSOR)+1);
    memcpy(b[MASH], MASH_TEMP_SENSOR, sizeof(MASH_TEMP_SENSOR)+1);
   // memcpy(b[CABINET], CABINET_TEMP_SENSOR, sizeof(CABINET_TEMP_SENSOR)+1);

    ds1820_search();

    //if (rom[0] == 0x10)
      if (rom[0] != 0)
      {
        sprintf(print_buf, "%02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x\r\n\0",rom[0],
            rom[1], rom[2], rom[3], rom[4], rom[5], rom[6], rom[7]);
        vConsolePrint(print_buf);
      }
    else
      {
        vConsolePrint("NO SENSOR\r\n\0");
      }

    for (;;)
    {
        ds1820_convert();
        vTaskDelay(850/portTICK_RATE_MS); // wait for conversion

        // save values in array for use by application
        for (ii = 0 ; ii < NUM_SENSORS; ii++)
        {
            fTemp[ii] = ds1820_read_device(b[ii]);
            if (fTemp[ii] < 105.0 && fTemp[ii] > 0.0)
              {
                if ((fTemp[ii] < (temps[ii] + 5.0)) || (fTemp[ii] > (temps[ii] - 5.0)) || (fTemp[ii] <= 85.0 && fTemp[ii] >= 86.0))
                  {
                    portENTER_CRITICAL(); // so that other task cannot access temps[] while we are saving.
                    temps[ii] = fTemp [ii];
                    portEXIT_CRITICAL();
                  }

              }
            if (fTemp[ii] == 0.0)
              {
                vConsolePrint("zero values. Temp Bus Resetting\r\n\0");
                ds1820_power_reset();
                ds1820_reset();
              }
        }
        taskYIELD();
    }
    
}
/* See the comments at the top of main.c. */
void vSecureTCPServerTask( void *pvParameters )
{
BaseType_t xReturned;
long lBytes;
uint8_t cReceivedString[ 60 ];
struct sockaddr_in xClient;
int xClientAddressLength = sizeof( struct sockaddr_in );
SOCKET xListeningSocket, xConnectedSocket;
CYASSL* xCyaSSL_Object; /* Only one connection is accepted at a time, so only one object is needed at a time. */

	/* Just to prevent compiler warnings. */
	( void ) pvParameters;

	/* Perform the initialisation necessary before CyaSSL can be used. */
	prvInitialiseCyaSSL();
	configASSERT( xCyaSSL_ServerContext );

	/* Attempt to open the socket. */
	xListeningSocket = prvOpenServerSocket();

	/* Now the server socket has been created and the CyaSSL library has been
	initialised, the task that implements the client side can be created. */
	xTaskCreate( vSecureTCPClientTask, "Client", configMINIMAL_STACK_SIZE, NULL, sstSECURE_CLIENT_TASK_PRIORITY, NULL );

	if( xListeningSocket != INVALID_SOCKET )
	{
		for( ;; )
		{
			/* Wait until the client connects. */
			printf( "Waiting for new connection\r\n" );
			xConnectedSocket = accept( xListeningSocket, ( struct sockaddr * ) &xClient, &xClientAddressLength );

			if( xConnectedSocket != INVALID_SOCKET )
			{
				printf( "Connection established\r\n" );

				/* A connection has been accepted by the server.  Create a 
				CyaSSL object for use with the newly connected socket. */
				xCyaSSL_Object = NULL;
				xCyaSSL_Object = CyaSSL_new( xCyaSSL_ServerContext );
    
				if( xCyaSSL_Object != NULL )
				{
					/* Associate the created CyaSSL object with the connected 
					socket. */
					xReturned = CyaSSL_set_fd( xCyaSSL_Object, xConnectedSocket );
					configASSERT( xReturned == SSL_SUCCESS );

					do
					{
						/* The next line is the secure equivalent to the 
						standard sockets call:
						lBytes = recv( xConnectedSocket, cReceivedString, 50, 0 ); */
						lBytes = CyaSSL_read( xCyaSSL_Object, cReceivedString, sizeof( cReceivedString ) );
						
						/* Print the received characters. */
						if( lBytes > 0 )
						{
							printf( "Received by the secure server: %s\r\n", cReceivedString );
						}

					} while ( lBytes > 0 );

					/* The connection was closed, close the socket and free the
					CyaSSL object. */
					closesocket( xConnectedSocket );					
					CyaSSL_free( xCyaSSL_Object );
					printf( "Connection closed, back to start\r\n\r\n" );
				}								
			}
		} 
	}
	else
	{
		/* The socket could not be opened. */
		vTaskDelete( NULL );
	}
}
/*******************************************************************************
 * TASK: taskStandbyWatchdog
 *
 * DESCRIPTIONS:
 * Watchdog for system standby. Lock the screen after timeout.
 *
 *******************************************************************************/
void taskStandbyWatchdog (void *pvParameters)
{
    xTaskHandle xShutdownWatchdogTask = NULL;
    portTickType xTimeoutPeriod;
    
    
    
    while (1) {
        // Read the stack watermark and record it if it's below threshold.
        unsigned portBASE_TYPE uxHighWaterMark = uxTaskGetStackHighWaterMark(NULL);
        if (uxHighWaterMark < MIN_STACK_WATERMARK) {
            xSystemError.bStackLowError = 1;

            // Only log it when the watermark value changed.
            static portBASE_TYPE uxPreviousWatermark = 0;
            if (uxHighWaterMark != uxPreviousWatermark) {
                vLogStackWatermark("Standby Watchdog Task", (unsigned short)uxHighWaterMark);
            }
            uxPreviousWatermark = uxHighWaterMark;
        }
        
        
        
        // Kill the shutdown watchdog task if it's running.
        if (xShutdownWatchdogTask != NULL) {
            vTaskDelete(xShutdownWatchdogTask);
            xShutdownWatchdogTask = NULL;
        }
        
        
        
        // Timeout should be shorter while the screen is still locked.
        // Delay a while before we check for the flag to let it get updated. The flag is only updated when the screen is not pressed.
        vTaskDelay(100 / portTICK_RATE_MS);
        if (xSystemState.bStandby != 0) {
            xTimeoutPeriod = SHORT_STANDBY_TIMEOUT - DIM_SCREEN_PERIOD;
        }
        
        // Get the timeout period base on auto sleep setting.
        else {
            switch (eAutoSleep) {
                case AUTO_SLEEP_15_SEC: xTimeoutPeriod = (15000 / portTICK_RATE_MS) - DIM_SCREEN_PERIOD;    break;
                case AUTO_SLEEP_30_SEC: xTimeoutPeriod = (30000 / portTICK_RATE_MS) - DIM_SCREEN_PERIOD;    break;
                case AUTO_SLEEP_1_MIN:  xTimeoutPeriod = (60000 / portTICK_RATE_MS) - DIM_SCREEN_PERIOD;    break;
                case AUTO_SLEEP_2_MIN:  xTimeoutPeriod = (120000 / portTICK_RATE_MS) - DIM_SCREEN_PERIOD;   break;
                case AUTO_SLEEP_5_MIN:  xTimeoutPeriod = (300000 / portTICK_RATE_MS) - DIM_SCREEN_PERIOD;   break;
                case AUTO_SLEEP_10_MIN: xTimeoutPeriod = (600000 / portTICK_RATE_MS) - DIM_SCREEN_PERIOD;   break;
                
                case AUTO_SLEEP_NEVER:
                    // Create the shutdown watchdog task if auto sleep is disabled.
                    xTaskCreate(taskShutdownWatchdog, "Shutdown", configMINIMAL_STACK_SIZE, NULL, tskIDLE_PRIORITY + 2, &xShutdownWatchdogTask);
                    xTimeoutPeriod = portMAX_DELAY;
                    break;
            }
        }
        
        
        
        // Turn on the backlight.
        SetDCOC1PWM(BLight);
        
        // Wait for touch semaphore.
        // Loop back if the screen is touched before timeout.
        if (xSemaphoreTake(xTouchSemaphore, xTimeoutPeriod) == pdTRUE) continue;
        
        
        
        // Dim the backlight.
        SetDCOC1PWM(300);
        
        // Wait for touch semaphore again.
        // Loop back if the screen is touched before timeout.
        if (xSemaphoreTake(xTouchSemaphore, DIM_SCREEN_PERIOD) == pdTRUE) continue;
        
        
        
        // Turn off backlight and lock the screen.
        SetDCOC1PWM(0);
        vLockScreen();
        
        // Start the auto shutdown task.
        xTaskCreate(taskShutdownWatchdog, "Shutdown", configMINIMAL_STACK_SIZE, NULL, tskIDLE_PRIORITY + 2, &xShutdownWatchdogTask);
        
        // Wait forever until the screen is touched.
        xSemaphoreTake(xTouchSemaphore, portMAX_DELAY);
        
    }   // End of while(1).
}
void usb_task(void *pvParameters)
{
#endif  // FREERTOS_USED
  // Register the USB interrupt handler to the interrupt controller and enable
  // the USB interrupt.
  cpu_irq_disable();
  irq_register_handler(usb_general_interrupt, AVR32_USBB_IRQ, USB_INT_LEVEL);
  cpu_irq_enable();

#ifdef FREERTOS_USED
  while (true)
  {
    // Wait for the semaphore
    while (!xSemaphoreTake(usb_tsk_semphr, portMAX_DELAY));

#endif  // FREERTOS_USED
// ---- DUAL-ROLE DEVICE/HOST USB MODE -----------------------------------------
#if USB_DEVICE_FEATURE == true && USB_HOST_FEATURE == true
  #ifdef FREERTOS_USED
    if (usb_device_tsk) vTaskDelete(usb_device_tsk), usb_device_tsk = NULL;
    if (usb_host_tsk) vTaskDelete(usb_host_tsk), usb_host_tsk = NULL;
  #endif
    Usb_input_id_pin();
    Usb_enable_id_pin();
    if (Is_usb_id_device())
    {
      g_usb_mode = USB_MODE_DEVICE;
      usb_device_task_init();
    }
    else
    {
      private_sof_counter = 0;
      g_usb_mode = USB_MODE_HOST;
      usb_host_task_init();
    }
    g_old_usb_mode = g_usb_mode;  // Store current USB mode, for mode change detection
    Usb_raise_id_transition();  // Check no ID transition has been missed during initialization
    Usb_enable_id_interrupt();
    cpu_irq_enable();
// -----------------------------------------------------------------------------

// ---- DEVICE-ONLY USB MODE ---------------------------------------------------
#elif USB_DEVICE_FEATURE == true
  #ifdef FREERTOS_USED
    if (usb_device_tsk) vTaskDelete(usb_device_tsk), usb_device_tsk = NULL;
  #endif
    Usb_force_device_mode();
    usb_device_task_init();
// -----------------------------------------------------------------------------

// ---- REDUCED-HOST-ONLY USB MODE ---------------------------------------------
#elif USB_HOST_FEATURE == true
  #ifdef FREERTOS_USED
    if (usb_host_tsk) vTaskDelete(usb_host_tsk), usb_host_tsk = NULL;
  #endif
    private_sof_counter = 0;
    Usb_force_host_mode();
    usb_host_task_init();
// -----------------------------------------------------------------------------

// ---- ERROR, NO MODE ENABLED -------------------------------------------------
#else
#endif
// -----------------------------------------------------------------------------
#ifdef FREERTOS_USED
  }
#endif
}
Esempio n. 28
0
void Task_WifiScan(void* params)
{
    (void)params; //avoid unused error
    long retval;
    unsigned char policy;
    unsigned int policy_len;

    LOG(LOG_VERBOSE, "Starting WiFi network scan...");

    SetLEDBlink(LED_1, LED_BLINK_PATTERN_WIFI_SCANNING);

    if(WifiDefaultSettings() == RET_FAILURE) {
        goto error;
    }

    retval = sl_Start(0,0,0);
    if(retval<0)  {
        goto error;
    }

    //first, delete current connection policy
    policy = SL_CONNECTION_POLICY(0,0,0,0,0);
    retval = sl_WlanPolicySet(SL_POLICY_CONNECTION, policy, NULL, 0);
    if(retval<0)  {
        goto error;
    }

    //make scan policy
    policy = SL_SCAN_POLICY(1);
    policy_len = WIFI_SCAN_TIME_S;
    retval = sl_WlanPolicySet(SL_POLICY_SCAN, policy, (unsigned char*)&policy_len, sizeof(policy_len));
    if(retval<0)  {
        goto error;
    }

    //wait for the scan to complete
    const TickType_t delay = (1100*WIFI_SCAN_TIME_S) / portTICK_PERIOD_MS;
    vTaskDelay(delay);

    //get the results back
    unsigned char index = 0;
    retval = sl_WlanGetNetworkList(index, (unsigned char)WIFI_NUM_NETWORKS, &(wifi_state.networks[index]));

    //retval holds the number of networks now, and they are saved in the state.

    //disable the scan
    policy = SL_SCAN_POLICY(0);
    retval = sl_WlanPolicySet(SL_POLICY_SCAN, policy, NULL, 0);
    if(retval<0)  {
        goto error;
    }

    //disable SimpleLink altogether
    retval = sl_Stop(SL_STOP_TIMEOUT);
    if(retval<0)  {
        goto error;
    }

    LOG(LOG_VERBOSE, "WiFi network scan complete.");

    ClearLED(LED_1);

#ifdef DO_STACK_CHECK
    wifi_state.stack_watermark = uxTaskGetStackHighWaterMark(NULL);
#endif

    //exit (delete this task)
    WifiTaskEndCallback(&Task_WifiScan);
    vTaskDelete(NULL);

    return;

error:
    SetLEDBlink(LED_1, LED_BLINK_PATTERN_WIFI_FAILED);
    TASK_RETURN_ERROR(ERROR_UNKNOWN, "WIFI scan fail");
    return;
}
Esempio n. 29
0
static void tcp_server_task(void *pvParameters)
{
    char rx_buffer[128];
    char addr_str[128];
    int addr_family;
    int ip_protocol;

    while (1) {

#ifdef CONFIG_EXAMPLE_IPV4
        struct sockaddr_in destAddr;
        destAddr.sin_addr.s_addr = htonl(INADDR_ANY);
        destAddr.sin_family = AF_INET;
        destAddr.sin_port = htons(PORT);
        addr_family = AF_INET;
        ip_protocol = IPPROTO_IP;
        inet_ntoa_r(destAddr.sin_addr, addr_str, sizeof(addr_str) - 1);
#else // IPV6
        struct sockaddr_in6 destAddr;
        bzero(&destAddr.sin6_addr.un, sizeof(destAddr.sin6_addr.un));
        destAddr.sin6_family = AF_INET6;
        destAddr.sin6_port = htons(PORT);
        addr_family = AF_INET6;
        ip_protocol = IPPROTO_IPV6;
        inet6_ntoa_r(destAddr.sin6_addr, addr_str, sizeof(addr_str) - 1);
#endif

        int listen_sock = socket(addr_family, SOCK_STREAM, ip_protocol);
        if (listen_sock < 0) {
            ESP_LOGE(TAG, "Unable to create socket: errno %d", errno);
            break;
        }
        ESP_LOGI(TAG, "Socket created");

        int err = bind(listen_sock, (struct sockaddr *)&destAddr, sizeof(destAddr));
        if (err != 0) {
            ESP_LOGE(TAG, "Socket unable to bind: errno %d", errno);
            break;
        }
        ESP_LOGI(TAG, "Socket binded");

        err = listen(listen_sock, 1);
        if (err != 0) {
            ESP_LOGE(TAG, "Error occured during listen: errno %d", errno);
            break;
        }
        ESP_LOGI(TAG, "Socket listening");

#ifdef CONFIG_EXAMPLE_IPV6
        struct sockaddr_in6 sourceAddr; // Large enough for both IPv4 or IPv6
#else
        struct sockaddr_in sourceAddr;
#endif
        uint addrLen = sizeof(sourceAddr);
        int sock = accept(listen_sock, (struct sockaddr *)&sourceAddr, &addrLen);
        if (sock < 0) {
            ESP_LOGE(TAG, "Unable to accept connection: errno %d", errno);
            break;
        }
        ESP_LOGI(TAG, "Socket accepted");

        while (1) {
            int len = recv(sock, rx_buffer, sizeof(rx_buffer) - 1, 0);
            // Error occured during receiving
            if (len < 0) {
                ESP_LOGE(TAG, "recv failed: errno %d", errno);
                break;
            }
            // Connection closed
            else if (len == 0) {
                ESP_LOGI(TAG, "Connection closed");
                break;
            }
            // Data received
            else {
#ifdef CONFIG_EXAMPLE_IPV6
                // Get the sender's ip address as string
                if (sourceAddr.sin6_family == PF_INET) {
                    inet_ntoa_r(((struct sockaddr_in *)&sourceAddr)->sin_addr.s_addr, addr_str, sizeof(addr_str) - 1);
                } else if (sourceAddr.sin6_family == PF_INET6) {
                    inet6_ntoa_r(sourceAddr.sin6_addr, addr_str, sizeof(addr_str) - 1);
                }
#else
                inet_ntoa_r(((struct sockaddr_in *)&sourceAddr)->sin_addr.s_addr, addr_str, sizeof(addr_str) - 1);
#endif

                rx_buffer[len] = 0; // Null-terminate whatever we received and treat like a string
                ESP_LOGI(TAG, "Received %d bytes from %s:", len, addr_str);
                ESP_LOGI(TAG, "%s", rx_buffer);

                int err = send(sock, rx_buffer, len, 0);
                if (err < 0) {
                    ESP_LOGE(TAG, "Error occured during sending: errno %d", errno);
                    break;
                }
            }
        }

        if (sock != -1) {
            ESP_LOGE(TAG, "Shutting down socket and restarting...");
            shutdown(sock, 0);
            close(sock);
        }
    }
    vTaskDelete(NULL);
}
Esempio n. 30
0
void BT_kTaskDelete(void *pTaskHandle) {
	vTaskDelete(pTaskHandle);
}