Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android BLE: Convert ScanResult timestampNanos to System nanoTime

When scanning for Bluetooth Low Energy packets I receive ScanCallback with ScanResult being set. I can get "Device timestamp when the scan result was observed" with result.getTimestampNanos() but this time is not aligned with the Systems.nanoTime(). Is there a way to convert from one to the other?

like image 725
hebeha Avatar asked Feb 09 '23 04:02

hebeha


2 Answers

Use the following code to convert the getTimestampNanos() to system millis by using SystemClock.elapsedRealtime():

long rxTimestampMillis = System.currentTimeMillis() - 
                         SystemClock.elapsedRealtime() +
                         scanResult.getTimestampNanos() / 1000000;

This can be converted easily to a Date object:

Date rxDate = new Date(rxTimestampMillis);

Then you then get the time as a string:

String sDate = new SimpleDateFormat("HH:mm:ss.SSS").format(rxDate);
like image 53
Glenn Avatar answered Apr 09 '23 16:04

Glenn


More elegant way to do that

long actualTime = System.currentTimeMillis() - TimeUnit.MILLISECONDS.convert(SystemClock.elapsedRealtimeNanos() - scanResult.getTimestampNanos(), TimeUnit.NANOSECONDS)```
like image 28
Dmytro Batyuk Avatar answered Apr 09 '23 16:04

Dmytro Batyuk