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