Skip to content

Instantly share code, notes, and snippets.

@Solidedge
Last active February 15, 2022 10:25
Show Gist options
  • Save Solidedge/2a3f69d6743f5f29a51a084c80f47747 to your computer and use it in GitHub Desktop.
Save Solidedge/2a3f69d6743f5f29a51a084c80f47747 to your computer and use it in GitHub Desktop.
Convert incoming BLE-MIDI timestamp to localtime, or delayed local time. Functional with https://github.com/BLE-MIDI
/** Convert incoming BLE-MIDI timestamp to localtime, or delay.
* Timestamp out is in microseconds.*/
static uint16_t convert_timestamp(uint16_t received_ts, uint16_t conn_interval, uint16_t time_of_rx) {
static uint16_t prev_received_ts;
static uint32_t prev_time_of_rx;
static uint32_t prev_returned_ts;
static bool first_timestamp = true;
if (first_timestamp) {
prev_time_of_rx = time_of_rx;
prev_received_ts = received_ts;
prev_returned_ts = k_ticks_to_us_near64(k_uptime_ticks()); // Time in µs
first_timestamp = false;
return prev_returned_ts;
}
/** Time since last event */
uint32_t time_span_between_evt =
(uint32_t)(((received_ts - prev_received_ts) & 8191)
* 1000
+ ((((time_of_rx - prev_time_of_rx)
- (uint32_t)((received_ts - prev_received_ts) & 8191)
* 1000)
+ 4096000)
/ 8192000)
* 8192);
/** Time until event is in sync */
int16_t added_delay =
(time_span_between_evt -
(k_ticks_to_us_near64(k_uptime_ticks()) - prev_returned_ts));
if (added_delay < 0) {
/** Event can't be synced back in time */
added_delay = 0;
}
if (added_delay > (conn_interval)) {
/** Event shouldn't be scheduled too far into the future */
added_delay = (conn_interval);
}
/** Update stored values */
prev_time_of_rx = time_of_rx;
prev_received_ts = received_ts;
prev_returned_ts = k_ticks_to_us_near64(k_uptime_ticks()) + added_delay;
return (uint16_t)prev_returned_ts;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment