Is it possible to get the atomic clock timestamp from the iphone GPS? - iphone

I'm looking for a reliable way to get the time. It can't be tampered with and it needs to work offline. So no internet time , no user time setup in settings and no BSD uptime time since last reboot. I was wondering since GPS works using atomic clock, whether I could access that information.
Thank you

This works to get the GPS time:
#import <CoreLocation/CoreLocation.h>
CLLocation* gps = [[CLLocation alloc]
initWithLatitude:(CLLocationDegrees) 0.0
longitude:(CLLocationDegrees) 0.0];
NSDate* now = gps.timestamp;
It doesn't seem to be tamper-proof though.
I tried this code on an iPhone 4 in airplane mode (iOS 6.1), and even then it gives a time all right. But unfortunately this time seems to change with the system clock. Ugh.
Funny thing that I found (still in airplane mode) is that if you tamper with the system clock (after turning to off Time & Date's Set Automatically), and then turn Set Automatically back to on, the machine restores the real (original) time without a hitch. this works even after cycling the phone's power. So it seems that there is something like a tamper-proof time the device maintains internally. But how to access this?
P.S. A discussion of this from 2010. The author of the penultimate comment tried this in a fallout shelter: so it's clear the phone is not getting the pristine time from any external source.
Addendum, July 2013
Found a few more posts (here, here and here) about another kind of time measure: system kernel boot time. It's accessed through a call something like this: sysctlbyname("kern.boottime", &boottime, &size, NULL, 0);. Unfortunately it too changes with the user-adjusted data and time, even without reboot. Another function gettimeofday() is similarly dependent on user-defined time.

NSDate and it's CF counterpart are all based on the user controllable time, and thereby aren't tamper proof.
As far as I know, there is no open API for either GPS time or carrier time directly. However, you can check the mach_absolute_time to get untampered time since last boot up, and perhaps use it to at least be aware of how much time has passed since the app has been awoken (without having the potential for that time to be tampered with while the app is running).
mach_absolute_time depends on the processor of the device. It returns ticks since the device was last rebooted (otherwise known as uptime). In order to get it in a human readable form, you have to modify it by the result from mach_timebase_info (a ratio), which will return billionth of seconds (or nanoseconds). To make this more usable I use a function like the one below:
#include <mach/mach_time.h>
int getUptimeInMilliseconds()
{
static const int64_t kOneMillion = 1000 * 1000;
static mach_timebase_info_data_t s_timebase_info;
if (s_timebase_info.denom == 0) {
(void) mach_timebase_info(&s_timebase_info);
}
// mach_absolute_time() returns billionth of seconds,
// so divide by one million to get milliseconds
return (int)((mach_absolute_time() * s_timebase_info.numer) / (kOneMillion * s_timebase_info.denom));
}

Even if you can get hold of the time from GPS you should be aware that GPS time is not quite the same as UTC. The GPS receiver in the iPhone might take care of that for you though.

This gets you the current date and time:
NSDate *now = [NSDate date];
This will be as reliable as you can get. The internal clock on the iPhone will be updated when it can get access to an NTP server. If the phone uses GPS as a time sync source it'll also be used to update the same system-wide clock which is accessible via the above method.
The CoreFoundation equivalent is something like:
CFAbsoluteTime now = CFAbsoluteTimeGetCurrent();
Which returns the CoreFoundation equivalent of the normal UNIX seconds-since-epoch timestamp.

The gold standard of timekeeping are the various government time observatories in the U.S. and worldwide. They provide Atomic time. That is used world wide. Apple should be using that. If the want to sync w/ the cell towers, there should be an Alternate internal time. If the tower or GPS system malfunctions all are left with incorrect time.

Related

How to reset time for data logging in micro:bit micropython

I would like to start data logging in a bbc micro:bit with the press of its button_a, in order to be able to synchronize the timestamps with an external clock.
The idea is that, if I press the button at 12:10 o'clock, I would know that the first row of data (with 0.00 timestamp) was taken at that time (+/- human reaction time, of course).
The problem is that the zero time of the timestamps begin when the bbc micro:bit is turn on (or reset); so the first timestamp in the log file is not 0.00.
Of course, I could synchronize with that turning-on, but I think it would not be that accurate (I'm using the micro:bit with a robotbit board, which has a big 'on-off' switch.)
What I would like would be some kind of reset_time() method. :)
The code is this:
from microbit import *
import log
log.set_labels('altitude', 'azimuth', 'measure', timestamp=log.SECONDS)
# Wait until Button 'A' is pressed. This way, we can sinchronize the measures with an external clock or watch
while not button_a.was_pressed():
pass
for altitude in...
for azimuth in...
measure=take_reading()
log.add({
'altitude': altitude,
'azimuth': azimuth,
'measure': measure
})
The full code is here: https://github.com/lopezsolerluis/foto-teodolito-log

How do I use system time as a trigger in codesys ladder?

Programming a raspberry pi with codesys, using mostly ladder, basically I need to write all data that is currently in a couple arrays to a csv file at midnight, so i'd like to be able to use a dt value as a trigger. I can't figure out how to use that value in ladder, however. I can display the local time on visualizer, but if i wanted something like "if localTime=#value" then coil 'Write' turns on, where is the actual variable for system time?
As far as I know, you need to read the clock from local system using function blocks, for example GetDateAndTime from CAA DTUtil Extern Library. Then you need to keep it up-to-date by using a function block, for example RTC from Standard libary
The following reads the system local time and then updates it with a RTC function block. Works at least on Windows, couldn't test with Raspberry. Please note that if the local time changes for some reason, this won't update it again. So you need to run the GetDateAndTime call every now and then, for example.
First, a program that updates and provides the local time:
PROGRAM PRG_UpdateSystemTime
VAR_OUTPUT
SystemDateTime : DT;
END_VAR
VAR
ReadLocalTime : DTU.GetDateAndTime; //Reads local time from system
RtcBlock : RTC; //Real-time clock - updates the previously received local time
END_VAR
//NOTE: Output is UTC time
//The block that reads local time. NOTE: Error handling is missing
ReadLocalTime(xExecute:= TRUE);
//Running real-time clock
RtcBlock(
EN := ReadLocalTime.xDone AND NOT ReadLocalTime.xError,
PDT := ReadLocalTime.dtDateAndTime,
CDT => SystemDateTime
);
And then one example for ladder. I think there are millions of ways. Note that the "DoSomething" will be TRUE for the whole second, so you should probably use rising edge detection.

CSLogItem timestamp format (NSTimeInterval since when?)

I'm logging CMAccelerometerData on the iphone. CMAcceleration is a subclass of CMLogItem, which defines a timestamp. The timestamp is very important to me, as I have to match CMAcceleration data to positions obtain via GPS. GPS gives me a NSDate object, which is good; but CMLogItem gives me a number that I cant relate to anything.
It's not UNIX time for sure. This morning (17/11/2010 at 11H17am, in Australia), it was at 4090 seconds.
Any ideas of what that could be?
Nevermind I found out, CMLogItem timestamp is a NSTimeInterval starting when the phone last boot up.

IPhone: different system timers?

I have been using mach_absolute_time() for all my timing functions so far. calculating how long between frames etc.
I now want to get the exact time touch input events happen using event.timestamp in the touch callbacks.
the problem is these two seem to use completely different timers. sure, you can get them both in seconds, but their origins are different and seemingly random...
is there any way to sync the two different timers?
or is there anyway to get access to the same timer that the touch input uses to generate that timestamp property? otherwise its next to useless.
Had some trouble with this myself. There isn't a lot of good documentation, so I went with experimentation. Here's what I was able to determine:
mach_absolute_time depends on the processor of the device. It returns ticks since the device was last rebooted (otherwise known as uptime). In order to get it in a human readable form, you have to modify it by the result from mach_timebase_info (a ratio), which will return billionth of seconds (or nanoseconds). To make this more usable I use a function like the one below:
#include <mach/mach_time.h>
int getUptimeInMilliseconds()
{
static const int64_t kOneMillion = 1000 * 1000;
static mach_timebase_info_data_t s_timebase_info;
if (s_timebase_info.denom == 0) {
(void) mach_timebase_info(&s_timebase_info);
}
// mach_absolute_time() returns billionth of seconds,
// so divide by one million to get milliseconds
return (int)((mach_absolute_time() * s_timebase_info.numer) / (kOneMillion * s_timebase_info.denom));
}
Get the initial difference between two i.e
what is returned by mach_absolute_time() initally when your application starts and also get the event.timestamp initially at the same time...
store the difference... it would remain same through out the time your application runs.. so you can use this time difference to convert one to another...
How about CFAbsoluteTimeGetCurrent?

How can I detect whether the iphone has been rebooted since last time app started

I'd like to detect from within my app whether the iPhone has been rebooted since last time my app was started. I need to do this because my app uses the timer since last system reboot to clock a user's time and I want to detect reboot so I can invalidate the time.
Is there anywhere I could extract the information from the system console log like reboot , crashes ? The organizer in xcode can access it , maybe I can too.
If not , can you think of other ways to get this information?
This seems like it would work:
get the time since last reboot, and for this example, let's store it in a variable called 'tslr' (duration in milliseconds I guess, BTW, how do you get that?)
get the current time, store it in variable 'ct' for example
compute the last reboot time (let's call it 'lr'), we have: lr = ct - tslr
store 'lr'
Next time your application gets started, load the previous value for 'lr', compute the new one, and if they differ, you have detected a reboot (you'll probably have to tolerate a small difference there... a couple milliseconds perhaps).
I think it would be pretty tough to fool that... the user would have to tamper their phone time very precisely, and they would have to start your application at a very precise moment on top of that, exactly when the new 'lr' would be identical to the previous one... pretty tough to do, the probability of them being able to do that is very close to 0 I think. And you don't need any internet connection to do that...
The new 'lr' would be identical to the previous one in the following cases only:
phone was not rebooted, and time was not changed
time was tampered with, AND the user managed to start your application at the precise millisecond to fool your algorithm (chances of that happening more than ultraslim)
// Returns true if device has rebooted since last time
private func deviceRebootedSinceLastTime() -> Bool {
let userDefaults = NSUserDefaults.standardUserDefaults()
let systemUptime = NSProcessInfo.processInfo().systemUptime;
let timeNow = NSDate().timeIntervalSince1970
let dateOfLastReboot = NSDate(timeIntervalSince1970: timeNow-systemUptime)
var didDeviceRebootSinceLastTime = false
if let storedDateOfLastReboot:NSDate = userDefaults.objectForKey("deviceLastRebootDate") as? NSDate {
if Int(dateOfLastReboot.timeIntervalSinceDate(storedDateOfLastReboot)) < 1 { //
print("Reboot time didn't change - date: \(dateOfLastReboot)");
}
else {
print("Reboot time has changed - from: \(storedDateOfLastReboot) to \(dateOfLastReboot)");
didDeviceRebootSinceLastTime = true
}
}
else {
print("Reboot time is saved for the first time")
didDeviceRebootSinceLastTime = true // first time we save value
}
userDefaults.setObject(dateOfLastReboot, forKey: "deviceLastRebootDate")
userDefaults.synchronize() // don't forget this!!!
return didDeviceRebootSinceLastTime;
}
Zoran's answer is the right way to go; it's the closest you are going to get without a network connection. (neither the cellular subsystem, nor the syslog are accessible for security reasons)
If you are looking to prevent malicious users from generating fake time data, have some central server (or trusted local server for enterprise deployments) track time-related events for you.
Get and save the time either from the iPhone or from NIST and the current runtime from the BSD uptime function. For NIST time see How can I get the real time in iPhone, not the time set by user in Settings?
When you want to check for a reboot get new values of these, compute the elapsed time for each and compare the elapsed times. Based on the difference you should be able to determine a reboot.
Here is one I made. It takes the current time in GMT and the time since last reboot to extrapolate a date for when the device was last restarted. Then it keeps track of this date in memory using NSUserDefaults. Enjoy!
Note: Since you want to check this since last time app was started, you need to make sure you call the method anytime the app is started. The easiest way would be to call the method below in +(void)initialize { and then also whenever you need to check it manually
#define nowInSeconds CFAbsoluteTimeGetCurrent()//since Jan 1 2001 00:00:00 GMT
#define secondsSinceDeviceRestart ((int)round([[NSProcessInfo processInfo] systemUptime]))
#define storage [NSUserDefaults standardUserDefaults]
#define DISTANCE(__valueOne, __valueTwo) ((((__valueOne)-(__valueTwo))>=0)?((__valueOne)-(__valueTwo)):((__valueTwo)-(__valueOne)))
+(BOOL)didDeviceReset {
static BOOL didDeviceReset;
static dispatch_once_t onceToken;
int currentRestartDate = nowInSeconds-secondsSinceDeviceRestart;
int previousRestartDate = (int)[((NSNumber *)[storage objectForKey:#"previousRestartDate"]) integerValue];
int dateVarianceThreshold = 10;
dispatch_once(&onceToken, ^{
if (!previousRestartDate || DISTANCE(currentRestartDate, previousRestartDate) > dateVarianceThreshold) {
didDeviceReset = YES;
} else {
didDeviceReset = NO;
}
});
[storage setObject:#(currentRestartDate) forKey:#"previousRestartDate"];
[storage synchronize];
return didDeviceReset;
}