| 1 |
// Copyright (c) Microsoft. All rights reserved. |
| 2 |
// Licensed under the MIT license. See LICENSE file in the project root for full license information. |
| 3 |
|
| 4 |
#include "mbed.h" |
| 5 |
#include "azure_c_shared_utility/optimize_size.h" |
| 6 |
#include "azure_c_shared_utility/tickcounter.h" |
| 7 |
|
| 8 |
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////// |
| 9 |
// The tick counter from mbed OS will be overflow (go back to zero) after approximately 70 minutes (4294s). |
| 10 |
// So here extend the tick counter 64bit. |
| 11 |
static Ticker *cycle_ticker = NULL; |
| 12 |
static volatile uint32_t last_ticker_us = 0; |
| 13 |
static volatile uint64_t long_ticker_ms = 0; |
| 14 |
|
| 15 |
#define TICKER_INTERVAL 60.0 |
| 16 |
|
| 17 |
static uint64_t system_tick_counter_read(void) |
| 18 |
{ |
| 19 |
uint64_t result; |
| 20 |
uint32_t t; |
| 21 |
|
| 22 |
core_util_critical_section_enter(); |
| 23 |
t = us_ticker_read(); |
| 24 |
if (t < last_ticker_us) |
| 25 |
{ |
| 26 |
// overflowed |
| 27 |
long_ticker_ms += 0xFFFFFFFF / 1000; |
| 28 |
} |
| 29 |
last_ticker_us = t; |
| 30 |
|
| 31 |
result = long_ticker_ms + t / 1000; |
| 32 |
core_util_critical_section_exit(); |
| 33 |
|
| 34 |
return result; |
| 35 |
} |
| 36 |
|
| 37 |
static void cycle_accumulator(void) |
| 38 |
{ |
| 39 |
system_tick_counter_read(); |
| 40 |
} |
| 41 |
|
| 42 |
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////// |
| 43 |
// The tickcounter |
| 44 |
typedef struct TICK_COUNTER_INSTANCE_TAG |
| 45 |
{ |
| 46 |
uint64_t current_ms; |
| 47 |
} TICK_COUNTER_INSTANCE; |
| 48 |
|
| 49 |
TICK_COUNTER_HANDLE tickcounter_create(void) |
| 50 |
{ |
| 51 |
core_util_critical_section_enter(); |
| 52 |
if (cycle_ticker == NULL) |
| 53 |
{ |
| 54 |
cycle_ticker = new Ticker(); |
| 55 |
cycle_ticker->attach(cycle_accumulator, TICKER_INTERVAL); |
| 56 |
} |
| 57 |
core_util_critical_section_exit(); |
| 58 |
|
| 59 |
TICK_COUNTER_INSTANCE *result; |
| 60 |
result = new TICK_COUNTER_INSTANCE; |
| 61 |
result->current_ms = system_tick_counter_read(); |
| 62 |
return result; |
| 63 |
} |
| 64 |
|
| 65 |
void tickcounter_destroy(TICK_COUNTER_HANDLE tick_counter) |
| 66 |
{ |
| 67 |
if (tick_counter != NULL) |
| 68 |
{ |
| 69 |
delete tick_counter; |
| 70 |
} |
| 71 |
} |
| 72 |
|
| 73 |
int tickcounter_get_current_ms(TICK_COUNTER_HANDLE tick_counter, tickcounter_ms_t *current_ms) |
| 74 |
{ |
| 75 |
int result; |
| 76 |
if (tick_counter == NULL || current_ms == NULL) |
| 77 |
{ |
| 78 |
result = MU_FAILURE; |
| 79 |
} |
| 80 |
else |
| 81 |
{ |
| 82 |
tick_counter->current_ms = system_tick_counter_read(); |
| 83 |
*current_ms = tick_counter->current_ms; |
| 84 |
|
| 85 |
result = 0; |
| 86 |
} |
| 87 |
return result; |
| 88 |
} |