Esempio n. 1
1
/* SW2: PTC1 (near USB)
 * SW3: PTB17
 */
static void ButtonTask(void *pvParameters) {
  (void)pvParameters;
  g = 3.5;
  floatFunc(5.5);
  for(;;) {
    if (SW2IsPressed()) { /* SW2 pressed */
      PrintButtonPressed(2, TRUE);
      vTaskDelay(pdMS_TO_TICKS(50)); /* debounce */
      while(SW2IsPressed()) { /* wait until released */
        //vTaskDelay(pdMS_TO_TICKS(50)); /*! \todo 4 Add delay of 50 ms */
      }
      PrintButtonPressed(2, FALSE);
      (void)xSemaphoreGive(semSW2); /* send message to toggle USB */
      (void)xSemaphoreGive(semMouse); /* send message to toggle USB */
      (void)xSemaphoreGive(semKbd); /* send message to toggle USB */
    }
    if (SW3IsPressed()) { /* SW3 pressed */
      PrintButtonPressed(3, TRUE);
      vTaskDelay(pdMS_TO_TICKS(50)); /* debounce */
      while(SW3IsPressed()) { /* wait until released */
        //vTaskDelay(pdMS_TO_TICKS(50)); /*! \todo 5 Add delay of 50 ms */
      }
      PrintButtonPressed(3, FALSE);
      (void)xSemaphoreGive(semSW3); /* send message */
      (void)xSemaphoreGive(semLED); /* send message to change LED */
    }
    //vTaskDelay(pdMS_TO_TICKS(10)); /*! \todo 2 Add delay of 10 ms */
  }
}
Esempio n. 2
0
void SWT_Init(void) {
  BaseType_t res;

  led = 0; /* red */
#if configSUPPORT_STATIC_ALLOCATION
  handle = xTimerCreateStatic(
      "swtimer", /* debug name of task */
      pdMS_TO_TICKS(500), /* period */
      pdTRUE, /* auto-reload */
      NULL, /* no timer ID */
      vTimerCallback, /* callback */
      &xTimerBuffer
      );
#else /* configSUPPORT_DYNAMIC_ALLOCATION */
  handle = xTimerCreate(
      "swtimer", /* debug name of task */
      pdMS_TO_TICKS(500), /* period */
      pdTRUE, /* auto-reload */
      NULL, /* no timer ID */
      vTimerCallback /* callback */
      );
#endif
  if (handle==NULL) {
    for(;;); /* error creating timer */
  }
  res = xTimerStart(handle, 0);
  if (res==pdFAIL) {
    for(;;); /* error starting timer */
  }
}
Esempio n. 3
0
/**************************************************************************//**
 * @brief  Main function
 *****************************************************************************/
int main(void)
{
  /* Chip errata */
  CHIP_Init();
  /* If first word of user data page is non-zero, enable eA Profiler trace */
  BSP_TraceProfilerSetup();

  /* Initialize LED driver */
  BSP_LedsInit();
  /* Setting state of leds*/
  BSP_LedSet(0);
  BSP_LedSet(1);

  /* Initialize SLEEP driver, no calbacks are used */
  SLEEP_Init(NULL, NULL);
#if (configSLEEP_MODE < 3)
  /* do not let to sleep deeper than define */
  SLEEP_SleepBlockBegin((SLEEP_EnergyMode_t)(configSLEEP_MODE+1));
#endif

  /* Parameters value for taks*/
  static TaskParams_t parametersToTask1 = { pdMS_TO_TICKS(1000), 0 };
  static TaskParams_t parametersToTask2 = { pdMS_TO_TICKS(500), 1 };

  /*Create two task for blinking leds*/
  xTaskCreate( LedBlink, (const char *) "LedBlink1", STACK_SIZE_FOR_TASK, &parametersToTask1, TASK_PRIORITY, NULL);
  xTaskCreate( LedBlink, (const char *) "LedBlink2", STACK_SIZE_FOR_TASK, &parametersToTask2, TASK_PRIORITY, NULL);

  /*Start FreeRTOS Scheduler*/
  vTaskStartScheduler();

  return 0;
}
Esempio n. 4
0
void test_runner(void *arg)
{
    PUBNUB_UNUSED(arg);

    for (;;) {
        unsigned next_test = 0;
        unsigned failed_count = 0;
        unsigned passed_count = 0;
        unsigned indete_count = 0;
        unsigned tests_in_progress = 0;

        FreeRTOS_printf(("Starting Run of %d tests\n", TEST_COUNT));

        while (failed_count + passed_count + indete_count < TEST_COUNT) {
            struct TestResultMessage msg;
            if ((tests_in_progress < g_max_conc_tests) && (next_test < TEST_COUNT)) {
                start_test(next_test++);
                ++tests_in_progress;
            }
            if (pdTRUE == xQueueReceive(m_TestResultQueue, &msg, pdMS_TO_TICKS(20))) {
                switch (msg.result) {
                case trFail:
                    FreeRTOS_printf(("\n !!!!!!! The %d. test ('%s') failed!\n\n", msg.test + 1, m_aTest[msg.test].name));
                    ++failed_count;
                    break;
                case trPass:
                    ++passed_count;
                    break;
                case trIndeterminate:
                    ++indete_count;
                    FreeRTOS_printf((" Indeterminate %d. test ('%s') of %d\t", msg.test+1, m_aTest[msg.test].name, TEST_COUNT));
                    /* Should restart the test... */
                    //FreeRTOS_printf((" ReStarting %d. test of %ld\t", msg.test + 1, TEST_COUNT));
                    break;
                }
#ifdef INCLUDE_vTaskDelete
                vTaskDelete(m_aTest[msg.test].task);
#endif
                --tests_in_progress;
            }
        }

        FreeRTOS_printf(("Test run over.\n"));
        if (passed_count == TEST_COUNT) {
            FreeRTOS_printf(("\n All %d tests passed\n", TEST_COUNT));
        }
        else {
            FreeRTOS_printf(("\n\n %d tests passed, %d tests failed, %d tests indeterminate\n", 
                    passed_count,
                    failed_count,
                    indete_count
                ));
        }

        vTaskDelay(pdMS_TO_TICKS(10 * 1000));
    }
}
Esempio n. 5
0
void vStartNTPTask( uint16_t usTaskStackSize, UBaseType_t uxTaskPriority )
{
	/* The only public function in this module: start a task to contact
	some NTP server. */

	if( xNTPTaskhandle != NULL )
	{
		switch( xStatus )
		{
		case EStatusPause:
			xStatus = EStatusAsking;
			vSignalTask();
			break;
		case EStatusLookup:
			FreeRTOS_printf( ( "NTP looking up server\n" ) );
			break;
		case EStatusAsking:
			FreeRTOS_printf( ( "NTP still asking\n" ) );
			break;
		case EStatusFailed:
			FreeRTOS_printf( ( "NTP failed somehow\n" ) );
			ulIPAddressFound = 0ul;
			xStatus = EStatusLookup;
			vSignalTask();
			break;
		}
	}
	else
	{
		xUDPSocket = FreeRTOS_socket( FREERTOS_AF_INET, FREERTOS_SOCK_DGRAM, FREERTOS_IPPROTO_UDP );
		if( xUDPSocket != NULL )
		{
		struct freertos_sockaddr xAddress;
		#if( ipconfigUSE_CALLBACKS != 0 )
			BaseType_t xReceiveTimeOut = pdMS_TO_TICKS( 0 );
		#else
			BaseType_t xReceiveTimeOut = pdMS_TO_TICKS( 5000 );
		#endif

			xAddress.sin_addr = 0ul;
			xAddress.sin_port = FreeRTOS_htons( NTP_PORT );

			FreeRTOS_bind( xUDPSocket, &xAddress, sizeof( xAddress ) );
			FreeRTOS_setsockopt( xUDPSocket, 0, FREERTOS_SO_RCVTIMEO, &xReceiveTimeOut, sizeof( xReceiveTimeOut ) );
			xTaskCreate( 	prvNTPTask,						/* The function that implements the task. */
							( const char * ) "NTP client",	/* Just a text name for the task to aid debugging. */
							usTaskStackSize,				/* The stack size is defined in FreeRTOSIPConfig.h. */
							NULL,							/* The task parameter, not used in this case. */
							uxTaskPriority,					/* The priority assigned to the task is defined in FreeRTOSConfig.h. */
							&xNTPTaskhandle );				/* The task handle. */
		}
		else
		{
			FreeRTOS_printf( ( "Creating socket failed\n" ) );
		}
	}
}
Esempio n. 6
0
void
main_thread(void *pdata) {
    try_flash();
    if (user_vtor[1] == 0xFFFFFFFF) {
        serial_puts(&Serial1, "No application loaded, trying to load again in 10 seconds\r\n");
        vTaskDelay(pdMS_TO_TICKS(10000));
        NVIC_SystemReset();
    } else {
        serial_puts(&Serial1, "Booting application\r\n");
        vTaskDelay(pdMS_TO_TICKS(250));
        reset_and_jump();
    }
}
Esempio n. 7
0
BaseType_t xPhyCheckLinkStatus( EthernetPhy_t *pxPhyObject, BaseType_t xHadReception )
{
uint32_t ulStatus, ulBitMask = 1u;
BaseType_t xPhyIndex;
BaseType_t xNeedCheck = pdFALSE;

	if( xHadReception > 0 )
	{
		/* A packet was received. No need to check for the PHY status now,
		but set a timer to check it later on. */
		vTaskSetTimeOutState( &( pxPhyObject->xLinkStatusTimer ) );
		pxPhyObject->xLinkStatusRemaining = pdMS_TO_TICKS( ipconfigPHY_LS_HIGH_CHECK_TIME_MS );
	}
	else if( xTaskCheckForTimeOut( &( pxPhyObject->xLinkStatusTimer ), &( pxPhyObject->xLinkStatusRemaining ) ) != pdFALSE )
	{
		for( xPhyIndex = 0; xPhyIndex < pxPhyObject->xPortCount; xPhyIndex++, ulBitMask <<= 1 )
		{
		BaseType_t xPhyAddress = pxPhyObject->ucPhyIndexes[ xPhyIndex ];

			if( pxPhyObject->fnPhyRead( xPhyAddress, phyREG_01_BMSR, &ulStatus ) == 0 )
			{
				if( !!( pxPhyObject->ulLinkStatusMask & ulBitMask ) != !!( ulStatus & phyBMSR_LINK_STATUS ) )
				{
					if( ( ulStatus & phyBMSR_LINK_STATUS ) != 0 )
					{
						pxPhyObject->ulLinkStatusMask |= ulBitMask;
					}
					else
					{
						pxPhyObject->ulLinkStatusMask &= ~( ulBitMask );
					}
					FreeRTOS_printf( ( "xPhyCheckLinkStatus: PHY LS now %02lX\n", pxPhyObject->ulLinkStatusMask ) );
					eventLogAdd( "PHY LS now %02lX", pxPhyObject->ulLinkStatusMask );
					xNeedCheck = pdTRUE;
				}
			}
		}
		vTaskSetTimeOutState( &( pxPhyObject->xLinkStatusTimer ) );
		if( ( pxPhyObject->ulLinkStatusMask & phyBMSR_LINK_STATUS ) != 0 )
		{
			pxPhyObject->xLinkStatusRemaining = pdMS_TO_TICKS( ipconfigPHY_LS_HIGH_CHECK_TIME_MS );
		}
		else
		{
			pxPhyObject->xLinkStatusRemaining = pdMS_TO_TICKS( ipconfigPHY_LS_LOW_CHECK_TIME_MS );
		}
	}
	return xNeedCheck;
}
Esempio n. 8
0
static void
cliWriteConfig(void) {
    int16_t result;
    if (!HAS_FEATURE(PPSEN) && (cfg.flags & FLAG_PPSEN)) {
        cli_puts("WARNING: PPS output not available on this hardware\r\n");
        cfg.flags &= ~FLAG_PPSEN;
    }
    if ((cfg.flags & (FLAG_GPSEXT | FLAG_GPSOUT)) == (FLAG_GPSEXT | FLAG_GPSOUT)) {
        cli_puts("WARNING: gps_ext_in and gps_ext_out are mutually exclusive.\r\n");
        cfg.flags &= ~FLAG_GPSOUT;
    }
    /* Check for more than one ntpkey type */
    result = 0;
    if (cfg.flags & FLAG_NTPKEY_MD5) {
        result++;
    }
    if (cfg.flags & FLAG_NTPKEY_SHA1) {
        result++;
    }
    if (result > 1) {
        cli_puts("WARNING: More than one ntpkey type specified\r\n");
        cfg.flags &= ~(FLAG_NTPKEY_MD5 | FLAG_NTPKEY_SHA1);
    }
    cli_puts("Writing EEPROM...\r\n");
    result = eeprom_write_cfg();
    if (result == EERR_OK) {
        cli_puts("OK\r\n");
        serial_drain(cl_out);
        vTaskDelay(pdMS_TO_TICKS(1000));
        NVIC_SystemReset();
    } else {
        show_eeprom_error(result);
    }
}
Esempio n. 9
0
File: main.c Progetto: Eclo/FreeRTOS
static void prvCheckTask( void *pvParameters )
{
const TickType_t xCycleFrequency = pdMS_TO_TICKS( 2500UL );
static char *pcStatusMessage = "No errors";

	/* Just to remove compiler warning. */
	( void ) pvParameters;

	for( ;; )
	{
		/* Place this task in the blocked state until it is time to run again. */
		vTaskDelay( xCycleFrequency );

		/* Check the tasks that use static allocation are still executing. */
		if( xAreStaticAllocationTasksStillRunning() != pdPASS )
		{
			pcStatusMessage = "Error: Static allocation";
		}

		/* This is the only task that uses stdout so its ok to call printf()
		directly. */
		printf( "%s - tick count %d - number of tasks executing %d\r\n",
													pcStatusMessage,
													xTaskGetTickCount(),
													uxTaskGetNumberOfTasks() );
	}
}
Esempio n. 10
0
static void prvQueueReceiveTask( void *pvParameters )
{
uint32_t ulReceivedValue;
const uint32_t ulExpectedValue = 100UL;
const TickType_t xShortDelay = pdMS_TO_TICKS( 10 );

	/* Remove compiler warning about unused parameter. */
	( void ) pvParameters;

	for( ;; )
	{
		/* Wait until something arrives in the queue - this task will block
		indefinitely provided INCLUDE_vTaskSuspend is set to 1 in
		FreeRTOSConfig.h. */
		xQueueReceive( xQueue, &ulReceivedValue, portMAX_DELAY );

		/*  To get here something must have been received from the queue, but
		is it the expected value?  If it is, toggle the LED. */
		if( ulReceivedValue == ulExpectedValue )
		{
			/* Blip the LED briefly to show the demo is running, but without
			leaving the LED on too long as energy is being conserved. */
			mainTOGGLE_LED();
			vTaskDelay( xShortDelay );
			mainTOGGLE_LED();

			ulReceivedValue = 0U;
		}
	}
}
Esempio n. 11
0
static Socket_t prvCreateDNSSocket( void )
{
static Socket_t xSocket = NULL;
struct freertos_sockaddr xAddress;
BaseType_t xReturn;
TickType_t xTimeoutTime = pdMS_TO_TICKS( 200 );

	/* This must be the first time this function has been called.  Create
	the socket. */
	xSocket = FreeRTOS_socket( FREERTOS_AF_INET, FREERTOS_SOCK_DGRAM, FREERTOS_IPPROTO_UDP );

	/* Auto bind the port. */
	xAddress.sin_port = 0u;
	xReturn = FreeRTOS_bind( xSocket, &xAddress, sizeof( xAddress ) );

	/* Check the bind was successful, and clean up if not. */
	if( xReturn != 0 )
	{
		FreeRTOS_closesocket( xSocket );
		xSocket = NULL;
	}
	else
	{
		/* Set the send and receive timeouts. */
		FreeRTOS_setsockopt( xSocket, 0, FREERTOS_SO_RCVTIMEO, ( void * ) &xTimeoutTime, sizeof( TickType_t ) );
		FreeRTOS_setsockopt( xSocket, 0, FREERTOS_SO_SNDTIMEO, ( void * ) &xTimeoutTime, sizeof( TickType_t ) );
	}

	return xSocket;
}
Esempio n. 12
0
/**
 * @brief Handle when a pattern has been detected by UART
 *
 * @param esp_dte ESP32 Modem DTE object
 */
static void esp_handle_uart_pattern(esp_modem_dte_t *esp_dte)
{
    int pos = uart_pattern_pop_pos(esp_dte->uart_port);
    int read_len = 0;
    if (pos != -1) {
        if (pos < ESP_MODEM_LINE_BUFFER_SIZE - 1) {
            /* read one line(include '\n') */
            read_len = pos + 1;
        } else {
            ESP_LOGW(MODEM_TAG, "ESP Modem Line buffer too small");
            read_len = ESP_MODEM_LINE_BUFFER_SIZE - 1;
        }
        read_len = uart_read_bytes(esp_dte->uart_port, esp_dte->buffer, read_len, pdMS_TO_TICKS(100));
        if (read_len) {
            /* make sure the line is a standard string */
            esp_dte->buffer[read_len] = '\0';
            /* Send new line to handle */
            esp_dte_handle_line(esp_dte);
        } else {
            ESP_LOGE(MODEM_TAG, "uart read bytes failed");
        }
    } else {
        ESP_LOGW(MODEM_TAG, "Pattern Queue Size too small");
        uart_flush(esp_dte->uart_port);
    }
}
Esempio n. 13
0
/**
 * @brief Send data and wait for prompt from DCE
 *
 * @param dte Modem DTE object
 * @param data data buffer
 * @param length length of data to send
 * @param prompt pointer of specific prompt
 * @param timeout timeout value (unit: ms)
 * @return esp_err_t
 *      ESP_OK on success
 *      ESP_FAIL on error
 */
static esp_err_t esp_modem_dte_send_wait(modem_dte_t *dte, const char *data, uint32_t length,
        const char *prompt, uint32_t timeout)
{
    MODEM_CHECK(data, "data is NULL", err_param);
    MODEM_CHECK(prompt, "prompt is NULL", err_param);
    esp_modem_dte_t *esp_dte = __containerof(dte, esp_modem_dte_t, parent);
    // We'd better disable pattern detection here for a moment in case prompt string contains the pattern character
    uart_disable_pattern_det_intr(esp_dte->uart_port);
    // uart_disable_rx_intr(esp_dte->uart_port);
    MODEM_CHECK(uart_write_bytes(esp_dte->uart_port, data, length) >= 0, "uart write bytes failed", err_write);
    uint32_t len = strlen(prompt);
    uint8_t *buffer = calloc(len + 1, sizeof(uint8_t));
    int res = uart_read_bytes(esp_dte->uart_port, buffer, len, pdMS_TO_TICKS(timeout));
    MODEM_CHECK(res >= len, "wait prompt [%s] timeout", err, prompt);
    MODEM_CHECK(!strncmp(prompt, (const char *)buffer, len), "get wrong prompt: %s", err, buffer);
    free(buffer);
    uart_enable_pattern_det_intr(esp_dte->uart_port, '\n', 1, MIN_PATTERN_INTERVAL, MIN_POST_IDLE, MIN_PRE_IDLE);
    return ESP_OK;
err:
    free(buffer);
err_write:
    uart_enable_pattern_det_intr(esp_dte->uart_port, '\n', 1, MIN_PATTERN_INTERVAL, MIN_POST_IDLE, MIN_PRE_IDLE);
err_param:
    return ESP_FAIL;
}
Esempio n. 14
0
BaseType_t xNetworkInterfaceInitialise( void )
{
const TickType_t x5_Seconds = 5000UL;

	if( xEMACTaskHandle == NULL )
	{
		prvGMACInit();

		/* Wait at most 5 seconds for a Link Status in the PHY. */
		xGMACWaitLS( pdMS_TO_TICKS( x5_Seconds ) );

		/* The handler task is created at the highest possible priority to
		ensure the interrupt handler can return directly to it. */
		xTaskCreate( prvEMACHandlerTask, "EMAC", configEMAC_TASK_STACK_SIZE, NULL, configMAX_PRIORITIES - 1, &xEMACTaskHandle );
		configASSERT( xEMACTaskHandle );
	}

	if( xTxBufferQueue == NULL )
	{
		xTxBufferQueue = xQueueCreate( GMAC_TX_BUFFERS, sizeof( void * ) );
		configASSERT( xTxBufferQueue );
	}

	if( xTXDescriptorSemaphore == NULL )
	{
		xTXDescriptorSemaphore = xSemaphoreCreateCounting( ( UBaseType_t ) GMAC_TX_BUFFERS, ( UBaseType_t ) GMAC_TX_BUFFERS );
		configASSERT( xTXDescriptorSemaphore );
	}
	/* When returning non-zero, the stack will become active and
    start DHCP (in configured) */
	return ( ulPHYLinkStatus & BMSR_LINK_STATUS ) != 0;
}
Esempio n. 15
0
File: main.c Progetto: Eclo/FreeRTOS
void vApplicationTickHook( void )
{
static uint32_t ulCallCount = 0;
const uint32_t ulCallsBetweenSends = pdMS_TO_TICKS( 1000 );
const uint32_t ulMessage = configPRINT_SYSTEM_STATUS;
portBASE_TYPE xDummy;

	/* If configUSE_TICK_HOOK is set to 1 then this function will get called
	from each RTOS tick.  It is called from the tick interrupt and therefore
	will be executing in the privileged state. */

	ulCallCount++;

	/* Is it time to print out the pass/fail message again? */
	if( ulCallCount >= ulCallsBetweenSends )
	{
		ulCallCount = 0;

		/* Send a message to the check task to command it to check that all
		the tasks are still running then print out the status.

		This is running in an ISR so has to use the "FromISR" version of
		xQueueSend().  Because it is in an ISR it is running with privileges
		so can access xGlobalScopeCheckQueue directly. */
		xQueueSendFromISR( xGlobalScopeCheckQueue, &ulMessage, &xDummy );
	}
}
Esempio n. 16
0
/**
 * SIM800 IP configuration commands fail if the IP application is running,
 * even though the configuration settings are already right. The following
 * monkey dance is therefore needed.
 */
static int sim800_config(struct cellular *modem, const char *option, const char *value, int attempts)
{
    at_set_timeout(modem->at, 10);

    for (int i=0; i<attempts; i++) {
        /* Blindly try to set the configuration option. */
        at_command(modem->at, "AT+%s=%s", option, value);

        /* Query the setting status. */
        const char *response = at_command(modem->at, "AT+%s?", option);
        /* Bail out on timeouts. */
        if (response == NULL)
            return -1;

        /* Check if the setting has the correct value. */
        char expected[16];
        if (snprintf(expected, sizeof(expected), "+%s: %s", option, value) >= (int) sizeof(expected)) {
            return -1;
        }
        if (!strcmp(response, expected))
            return 0;

        vTaskDelay(pdMS_TO_TICKS(1000));
    }

    return -1;
}
Esempio n. 17
0
static void prvQueueReceiveTask( void *pvParameters )
{
    uint32_t ulReceivedValue;
    const uint32_t ulExpectedValue = 100UL;
    const TickType_t xShortDelay = pdMS_TO_TICKS( 10 );

    /* Remove compiler warning about unused parameter. */
    ( void ) pvParameters;

    for( ;; ) {
        /* Wait until something arrives in the queue - this task will block
        indefinitely provided INCLUDE_vTaskSuspend is set to 1 in
        FreeRTOSConfig.h. */
        xQueueReceive( xQueue, &ulReceivedValue, portMAX_DELAY );

        /*  To get here something must have been received from the queue, but
        is it the expected value?  If it is, toggle the LED. */
        if( ulReceivedValue == ulExpectedValue ) {
            /* Turn the LED on for a brief time only so it doens't distort the
            energy reading. */
            BSP_LedSet( mainTASK_LED );
            vTaskDelay( xShortDelay );
            BSP_LedClear( mainTASK_LED );
            ulReceivedValue = 0U;
        }
    }
}
Esempio n. 18
0
static int sim800_socket_connect(struct cellular *modem, int connid, const char *host, uint16_t port)
{
    struct cellular_sim800 *priv = (struct cellular_sim800 *) modem;

    if(connid == SIM800_NSOCKETS) {
      return !(SIM800_SOCKET_STATUS_CONNECTED == priv->spp_status);
    } else if(connid < SIM800_NSOCKETS) {
      /* Send connection request. */
      at_set_timeout(modem->at, SET_TIMEOUT);
      priv->socket_status[connid] = SIM800_SOCKET_STATUS_UNKNOWN;
      cellular_command_simple_pdp(modem, "AT+CIPSTART=%d,TCP,\"%s\",%d", connid, host, port);

      /* Wait for socket status URC. */
      for (int i=0; i<SIM800_CONNECT_TIMEOUT; i++) {
          if (priv->socket_status[connid] == SIM800_SOCKET_STATUS_CONNECTED) {
              return 0;
          } else if (priv->socket_status[connid] == SIM800_SOCKET_STATUS_ERROR) {
              return -1;
          }
          vTaskDelay(pdMS_TO_TICKS(1000));
      }
    }

    return -1;
}
Esempio n. 19
0
static void prvQueueReceiveTask( void *pvParameters )
{
unsigned long ulReceivedValue;
static const TickType_t xShortBlock = pdMS_TO_TICKS( 50 );

	/* Check the task parameter is as expected. */
	configASSERT( ( ( unsigned long ) pvParameters ) == mainQUEUE_RECEIVE_PARAMETER );

	for( ;; )
	{
		/* Wait until something arrives in the queue - this task will block
		indefinitely provided INCLUDE_vTaskSuspend is set to 1 in
		FreeRTOSConfig.h. */
		xQueueReceive( xQueue, &ulReceivedValue, portMAX_DELAY );

		/*  To get here something must have been received from the queue, but
		is it the expected value?  If it is, toggle the LED. */
		if( ulReceivedValue == 100UL )
		{
			/* Blip the LED for a short while so as not to use too much
			power. */
			configTOGGLE_LED();
			vTaskDelay( xShortBlock );
			configTOGGLE_LED();
			ulReceivedValue = 0U;
		}
	}
}
Esempio n. 20
0
static int sim800_ftp_get(struct cellular *modem, const char *filename)
{
    struct cellular_sim800 *priv = (struct cellular_sim800 *) modem;

    /* Configure filename. */
    at_command_simple(modem->at, "AT+FTPGETPATH=\"/\"");
    at_command_simple(modem->at, "AT+FTPGETNAME=\"%s\"", filename);

    /* Try to open the connection. */
    priv->ftpget1_status = -1;
    cellular_command_simple_pdp(modem, "AT+FTPGET=1");

    /* Wait for the operation result. */
    for (int i=0; i<SIM800_FTP_TIMEOUT; i++) {
        if (priv->ftpget1_status == 1)
            return 0;

        if (priv->ftpget1_status != -1) {
            return -1;
        }

        vTaskDelay(pdMS_TO_TICKS(1000));
    }

    return -1;
}
/* Function required in order to link UARTCommandConsole.c - which is used by
multiple different demo application. */
void vSerialPutString( xComPortHandle pxPort, const signed char * const pcString, unsigned short usStringLength )
{
const TickType_t xMaxBlockTime = pdMS_TO_TICKS( 5000 );

    /* Only one port is supported. */
    ( void ) pxPort;

    /* Clear the flag before initiating a new transmission */
    sci1_txdone = FALSE;

    /* Don't send the string unless the previous string has been sent. */
    if( ( xSendingTask == NULL ) && ( usStringLength > 0 ) )
    {
        /* Ensure the calling task's notification state is not already
        pending. */
        xTaskNotifyStateClear( NULL );

        /* Store the handle of the transmitting task.  This is used to unblock
        the task when the transmission has completed. */
        xSendingTask = xTaskGetCurrentTaskHandle();

        /* Send the string using the auto-generated API. */
        R_SCI1_Serial_Send( ( uint8_t * ) pcString, usStringLength );

        /* Wait in the Blocked state (so not using any CPU time) until the
        transmission has completed. */
        ulTaskNotifyTake( pdTRUE, xMaxBlockTime );
    }
}
Esempio n. 22
0
static void prvQueueSendTask( void *pvParameters )
{
TickType_t xNextWakeTime;
const unsigned long ulValueToSend = 100UL;
const TickType_t xBlockTime = pdMS_TO_TICKS( mainQUEUE_SEND_FREQUENCY_MS );

	/* Remove compiler warning in the case that configASSERT() is not
	defined. */
	( void ) pvParameters;

	/* Check the task parameter is as expected. */
	configASSERT( ( ( unsigned long ) pvParameters ) == mainQUEUE_SEND_PARAMETER );

	/* Initialise xNextWakeTime - this only needs to be done once. */
	xNextWakeTime = xTaskGetTickCount();

	for( ;; )
	{
		/* Place this task in the blocked state until it is time to run again.
		The block time is specified in ticks, the constant used converts ticks
		to ms.  While in the Blocked state this task will not consume any CPU
		time. */
		vTaskDelayUntil( &xNextWakeTime, xBlockTime );

		/* Send to the queue - causing the queue receive task to unblock and
		toggle the LED.  0 is used as the block time so the sending operation
		will not block - it shouldn't need to block as the queue should always
		be empty at this point in the code. */
		xQueueSend( xQueue, &ulValueToSend, 0U );
	}
}
Esempio n. 23
0
void vInterruptSemaphorePeriodicTest( void )
{
    static TickType_t xLastGiveTime = 0;
    BaseType_t xHigherPriorityTaskWoken = pdFALSE;
    TickType_t xTimeNow;

    /* No mutual exclusion on xOkToGiveMutex, but this is only test code (and
    only executed on a 32-bit architecture) so ignore that in this case. */
    xTimeNow = xTaskGetTickCountFromISR();
    if( ( ( TickType_t ) ( xTimeNow - xLastGiveTime ) ) >= pdMS_TO_TICKS( intsemINTERRUPT_MUTEX_GIVE_PERIOD_MS ) ) {
        configASSERT( xISRMutex );
        if( xOkToGiveMutex != pdFALSE ) {
            /* Null is used as the second parameter in this give, and non-NULL
            in the other gives for code coverage reasons. */
            xSemaphoreGiveFromISR( xISRMutex, NULL );

            /* Second give attempt should fail. */
            configASSERT( xSemaphoreGiveFromISR( xISRMutex, &xHigherPriorityTaskWoken ) == pdFAIL );
        }

        if( xOkToGiveCountingSemaphore != pdFALSE ) {
            xSemaphoreGiveFromISR( xISRCountingSemaphore, &xHigherPriorityTaskWoken );
        }
        xLastGiveTime = xTimeNow;
    }

    /* Remove compiler warnings about the value being set but not used. */
    ( void ) xHigherPriorityTaskWoken;
}
Esempio n. 24
0
signed portBASE_TYPE xSerialPutChar( xComPortHandle pxPort, signed char cOutChar, TickType_t xBlockTime )
{
const TickType_t xMaxWaitTime = pdMS_TO_TICKS( 20UL );

	/* Only a single port is supported. */
	( void ) pxPort;

	/* Note there is no mutual exclusion at the driver level.  If more than one
	task is using the serial port then mutual exclusion should be provided where
	this function is called. */

	/* Ensure notifications are not already waiting. */
	( void ) ulTaskNotifyTake( pdTRUE, 0 );

	/* Remember which task is sending the byte. */
	xTransmittingTask = xTaskGetCurrentTaskHandle();

	/* Mark the start and end of the data being sent - in this case just a
	single byte. */
	pcStringStart = &cOutChar;
	pcStringEnd = pcStringStart + sizeof( cOutChar );

	/* Start to send the byte. */
	pxUARTA0->rTXBUF.r = ( uint_fast8_t ) cOutChar;

	/* Enable the interrupt then wait for the byte to be sent.  The interrupt
	will be disabled again in the ISR. */
	MAP_UART_enableInterrupt( EUSCI_A0_MODULE, EUSCI_A_UART_TRANSMIT_INTERRUPT );
	ulTaskNotifyTake( pdTRUE, xMaxWaitTime );

	return pdPASS;
}
Esempio n. 25
0
uint8_t FLOPPY_Steps(FLOPPY_DriveHandle drive, int steps) {
  if (steps>=0) {
    FLOPPY_SetDirection(drive, TRUE); /* go forward */
  } else if (steps<0) {
    FLOPPY_SetDirection(drive, FALSE); /* go backward */
  }
  while(steps!=0) {
    if (drive->pos==FLOPPY_MAX_STEPS) {
      FLOPPY_SetDirection(drive, FALSE); /* go backward */
    } else if (drive->pos==0) {
      FLOPPY_SetDirection(drive, TRUE); /* go forward */
    }
    /* do a step */
    drive->StepSetVal();
    WAIT1_Waitus(5);
    drive->StepClearVal();
    if (steps>0) {
      steps--;
    } else {
      steps++;
    }
    if (drive->forward) {
      drive->pos++;
    } else {
      drive->pos--;
    }
    vTaskDelay(pdMS_TO_TICKS(5));
  } /* while */
  return ERR_OK;
}
Esempio n. 26
0
void vSerialPutString( xComPortHandle pxPort, const signed char * const pcString, unsigned short usStringLength )
{
const TickType_t xMaxWaitTime = pdMS_TO_TICKS( 20UL * ( uint32_t ) usStringLength );

	/* Only a single port is supported. */
	( void ) pxPort;

	/* Note there is no mutual exclusion at the driver level.  If more than one
	task is using the serial port then mutual exclusion should be provided where
	this function is called. */

	/* Ensure notifications are not already waiting. */
	( void ) ulTaskNotifyTake( pdTRUE, 0 );

	/* Remember which task is sending the byte. */
	xTransmittingTask = xTaskGetCurrentTaskHandle();

	/* Mark the start and end of the data being sent. */
	pcStringStart = pcString;
	pcStringEnd = pcStringStart + usStringLength;

	/* Start to send the first byte. */
	pxUARTA0->rTXBUF.r = ( uint_fast8_t ) *pcString;

	/* Enable the interrupt then wait for the byte to be sent.  The interrupt
	will be disabled again in the ISR. */
	MAP_UART_enableInterrupt( EUSCI_A0_MODULE, EUSCI_A_UART_TRANSMIT_INTERRUPT );
	ulTaskNotifyTake( pdTRUE, xMaxWaitTime );
}
enum pubnub_res pbpal_resolv_and_connect(pubnub_t *pb)
{
    struct freertos_sockaddr addr;

    PUBNUB_ASSERT(pb_valid_ctx_ptr(pb));
    PUBNUB_ASSERT_OPT((pb->state == PBS_IDLE) || (pb->state == PBS_WAIT_DNS));
    
    addr.sin_port = FreeRTOS_htons(HTTP_PORT);
    addr.sin_addr = FreeRTOS_gethostbyname(PUBNUB_ORIGIN_SETTABLE ? pb->origin : PUBNUB_ORIGIN);
    if (addr.sin_addr == 0) {
        return PNR_CONNECT_FAILED;
    }

    pb->pal.socket = FreeRTOS_socket(FREERTOS_AF_INET, FREERTOS_SOCK_STREAM, FREERTOS_IPPROTO_TCP);
    if (pb->pal.socket == SOCKET_INVALID) {
        return PNR_CONNECT_FAILED;
    }
    if (FreeRTOS_connect(pb->pal.socket, &addr, sizeof addr) != 0) {
        FreeRTOS_closesocket(pb->pal.socket);
        pb->pal.socket = SOCKET_INVALID;
        return PNR_CONNECT_FAILED;
    }

    {
        TickType_t tmval = pdMS_TO_TICKS(pb->transaction_timeout_ms);
        FreeRTOS_setsockopt(pb->pal.socket, 0, FREERTOS_SO_RCVTIMEO, &tmval, sizeof tmval);
    }

    return PNR_OK;
}
Esempio n. 28
0
static void vInterruptCountingSemaphoreTask( void *pvParameters )
{
    BaseType_t xCount;
    const TickType_t xDelay = pdMS_TO_TICKS( intsemINTERRUPT_MUTEX_GIVE_PERIOD_MS ) * ( intsemMAX_COUNT + 1 );

    ( void ) pvParameters;

    for( ;; ) {
        /* Expect to start with the counting semaphore empty. */
        if( uxQueueMessagesWaiting( ( QueueHandle_t ) xISRCountingSemaphore ) != 0 ) {
            xErrorDetected = pdTRUE;
        }

        /* Wait until it is expected that the interrupt will have filled the
        counting semaphore. */
        xOkToGiveCountingSemaphore = pdTRUE;
        vTaskDelay( xDelay );
        xOkToGiveCountingSemaphore = pdFALSE;

        /* Now it is expected that the counting semaphore is full. */
        if( uxQueueMessagesWaiting( ( QueueHandle_t ) xISRCountingSemaphore ) != intsemMAX_COUNT ) {
            xErrorDetected = pdTRUE;
        }

        if( uxQueueSpacesAvailable( ( QueueHandle_t ) xISRCountingSemaphore ) != 0 ) {
            xErrorDetected = pdTRUE;
        }

        ulCountingSemaphoreLoops++;

        /* Expect to be able to take the counting semaphore intsemMAX_COUNT
        times.  A block time of 0 is used as the semaphore should already be
        there. */
        xCount = 0;
        while( xSemaphoreTake( xISRCountingSemaphore, 0 ) == pdPASS ) {
            xCount++;
        }

        if( xCount != intsemMAX_COUNT ) {
            xErrorDetected = pdTRUE;
        }

        /* Now raise the priority of this task so it runs immediately that the
        semaphore is given from the interrupt. */
        vTaskPrioritySet( NULL, configMAX_PRIORITIES - 1 );

        /* Block to wait for the semaphore to be given from the interrupt. */
        xOkToGiveCountingSemaphore = pdTRUE;
        xSemaphoreTake( xISRCountingSemaphore, portMAX_DELAY );
        xSemaphoreTake( xISRCountingSemaphore, portMAX_DELAY );
        xOkToGiveCountingSemaphore = pdFALSE;

        /* Reset the priority so as not to disturbe other tests too much. */
        vTaskPrioritySet( NULL, tskIDLE_PRIORITY );

        ulCountingSemaphoreLoops++;
    }
}
Esempio n. 29
0
static void prvStartRx( void )
{
    const TickType_t xFailedReadDelay = pdMS_TO_TICKS( 150UL );

    while( CDCDSerialDriver_Read( pcRxBuffer, cmdMAX_INPUT_SIZE, ( TransferCallback ) prvCDCDataReceivedCallback, 0 ) != USBD_STATUS_SUCCESS ) {
        /* Maybe the CDC is not connected. */
        vTaskDelay( xFailedReadDelay );
    }
}
Esempio n. 30
0
void StatusScreen::init()
{
	lcd.init();
	// setup timer
	if(status_timer_handle == nullptr) {
		status_timer_handle= xTimerCreate("StatusTimer", pdMS_TO_TICKS(1000/1), pdTRUE, (void*)this, statusTimerCallback);
		xTimerStart(status_timer_handle, 10);
	}
}