1# Copyright 2014 The Android Open Source Project
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#      http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15import time
16
17import its.caps
18import its.device
19import its.objects
20
21
22def main():
23    """Test if image and motion sensor events are in the same time domain.
24    """
25
26    with its.device.ItsSession() as cam:
27        props = cam.get_camera_properties()
28
29        # Only run test if the appropriate caps are claimed.
30        its.caps.skip_unless(its.caps.sensor_fusion(props) and
31                             its.caps.backward_compatible(props))
32
33        # Get the timestamp of a captured image.
34        if its.caps.manual_sensor(props):
35            req, fmt = its.objects.get_fastest_manual_capture_settings(props)
36        else:
37            req, fmt = its.objects.get_fastest_auto_capture_settings(props)
38        cap = cam.do_capture(req, fmt)
39        ts_image0 = cap['metadata']['android.sensor.timestamp']
40
41        # Get the timestamps of motion events.
42        print 'Reading sensor measurements'
43        sensors = cam.get_sensors()
44        cam.start_sensor_events()
45        time.sleep(2.0)
46        events = cam.get_sensor_events()
47        ts_sensor_first = {}
48        ts_sensor_last = {}
49        for sensor, existing in sensors.iteritems():
50            if existing:
51                assert events[sensor], '%s sensor has no events!' % sensor
52                ts_sensor_first[sensor] = events[sensor][0]['time']
53                ts_sensor_last[sensor] = events[sensor][-1]['time']
54
55        # Get the timestamp of another image.
56        cap = cam.do_capture(req, fmt)
57        ts_image1 = cap['metadata']['android.sensor.timestamp']
58
59        print 'Image timestamps:', ts_image0, ts_image1
60
61        # The motion timestamps must be between the two image timestamps.
62        for sensor, existing in sensors.iteritems():
63            if existing:
64                print '%s timestamps: %d %d' % (sensor, ts_sensor_first[sensor],
65                                                ts_sensor_last[sensor])
66                assert ts_image0 < ts_sensor_first[sensor] < ts_image1
67                assert ts_image0 < ts_sensor_last[sensor] < ts_image1
68
69if __name__ == '__main__':
70    main()
71
72