forked from w3c/sensors
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.bs
1235 lines (1001 loc) · 46.5 KB
/
index.bs
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<pre class="metadata">
Title: Generic Sensor API
Level: 1
Status: ED
ED: https://w3c.github.io/sensors/
Shortname: generic-sensor
TR: https://www.w3.org/TR/generic-sensor/
Previous Version: https://www.w3.org/TR/2016/WD-generic-sensor-20160324/
Previous Version: https://www.w3.org/TR/2015/WD-generic-sensor-20151015/
Editor: Tobie Langel 78102, Intel Corporation, [email protected]
Editor: Rick Waldron 50572, jQuery Foundation
Group: dap
Abstract:
This specification defines a framework for exposing sensor data
to the Open Web Platform in a consistent way.
It does so by defining a blueprint for writing
specifications of concrete sensors along with an abstract Sensor interface
that can be extended to accommodate different sensor types.
Version History: https://github.com/w3c/sensors/commits/gh-pages/index.bs
!Bug Reports: <a href="https://www.github.com/w3c/sensors/issues/new">via the w3c/sensors repository on GitHub</a>
Indent: 2
Repository: w3c/sensors
Markup Shorthands: markdown on
!Issue Tracking: <a href="https://github.com/w3c/sensors/milestones/Level%201">Level 1 Issues</a>
!Issue Tracking: <a href="https://github.com/w3c/sensors/milestones/Level%202">Level 2 Issues</a>
!Test Suite: <a href="https://github.com/w3c/web-platform-tests/tree/master/generic-sensor">web-platform-tests on GitHub</a>
Boilerplate: omit issues-index, omit conformance
Default Biblio Status: current
</pre>
<pre class="anchors">
urlPrefix: https://dom.spec.whatwg.org; spec: DOM
type: interface
text: EventTarget; url: interface-eventtarget
type: dfn
text: dispatch; url: concept-event-dispatch
text: event; url: concept-event
urlPrefix: https://html.spec.whatwg.org/multipage/; spec: HTML
type: dfn
urlPrefix: webappapis.html
text: incumbent settings object
text: event handlers
text: event handler event type
text: queue a task
text: task source
text: task; url: concept-task
text: event loop
text: fire a simple event
text: trusted; url: concept-events-trusted
urlPrefix: infrastructure.html
text: in parallel
urlPrefix: browsers.html
text: origin; url: origin-2
text: navigating; url: navigate
text: browsing context
text: top-level browsing context
type: interface
urlPrefix: webappapis.html
text: EventHandler
urlPrefix: http://w3c.github.io/hr-time/; spec: HR-TIME-2
type: interface
text: DOMHighResTimeStamp; url: dom-domhighrestimestamp
type: dfn
text: time origin
urlPrefix: https://w3c.github.io/webappsec/specs/powerfulfeatures/; spec: POWERFUL-FEATURES
type: dfn
text: secure context
urlPrefix: https://heycam.github.io/webidl/; spec: WEBIDL
type: dfn
text: throw; url: dfn-throw
text: creating an exception; url: dfn-create-exception
text: InvalidStateError
text: NotAllowedError
text: Error
urlPrefix: https://w3c.github.io/permissions/; spec: PERMISSIONS
type: dfn
text: permission state; url: idl-def-PermissionState
text: permission; url: idl-def-Permission
text: PermissionDescriptor; url: idl-def-PermissionDescriptor
type: dfn
text: associated PermissionDescriptor; url: dfn-associated-permissiondescriptor
text: retrieving the permission state; url: dfn-retrieve-the-permission-state
urlPrefix: https://w3c.github.io/page-visibility; spec: PAGE-VISIBILITY
type: dfn
text: visibility states; url: dfn-visibility-states
text: steps to determine the visibility state; url: dfn-steps-to-determine-the-visibility-state
</pre>
Introduction {#intro}
=====================
Increasingly, sensor data is used in application development to
enable new use cases such as geolocation,
counting steps or head-tracking.
This is especially true on mobile devices where new sensors are added regularly.
Exposing sensor data to the Web
has so far been both slow-paced and ad-hoc.
Few sensors are already exposed to the Web.
When they are, it is often in ways that limit their possible use cases
(for example by exposing abstractions that are too [=high-level=]
and which don't perform well enough).
APIs also vary greatly from one sensor to the next
which increases the cognitive burden of Web application developers
and slows development.
The goal of the Generic Sensor API is to
promote consistency across sensor APIs,
enable advanced use cases thanks to performant [=low-level=] APIs,
and increase the pace at which new sensors can be exposed to the Web
by simplifying the specification and implementation processes.
Scope {#scope}
=====
<em>This section is non-normative</em>.
The scope of this specification is currently limited
to specifying primitives
which enable expose data from local sensors.
Exposing remote sensors
or sensors found on personal area networks
is out of scope.
As work in these areas mature,
it is possible that common, lower-level primitives be found,
in which case this specification will be updated accordingly.
This should have little to no effects on implementations, however.
This specification also does not currently expose a
sensor discovery API.
This is because the limited number of sensors currently available to User Agents
does not warrant such an API.
Using feature detection, such as described in [[#feature-detection]],
is good enough for now.
A subsequent version of this specification might specify such an API,
and the current API has been designed with this in mind.
Background {#background}
==========
<em>This section is non-normative</em>.
The Generic Sensor API is designed to make the most common use cases straightforward
while still enabling more complex use cases.
Most devices deployed today do not carry more than one
[=sensor=] of each [=sensor type|sensor types=].
This shouldn't come as a surprise since use cases for more than
a [=sensor=] of a given [=sensor types|type=] are rare
and generally limited to specific [=sensor types=] such as
proximity sensors.
The API therefore makes it easy to interact with
the device's default (and often unique) [=sensor=]
for each [=sensor types|type=]
simply by instantiating the corresponding {{Sensor}} subclass.
Indeed, without specific information identifying a particular [=sensor=]
of a given [=sensor type|type=],
the default [=sensor=] is chosen.
<div class="example">
Listening to geolocation changes:
<pre highlight="js">
let sensor = new GeolocationSensor({ accuracy: "high" });
sensor.onchange = function(event) {
var coords = [event.reading.latitude, event.reading.longitude];
updateMap(null, coords, event.reading.accuracy);
};
sensor.onerror = function(error) {
updateMap(error);
};
sensor.start();
</pre>
</div>
Note: extension to this specification may choose not to define a default sensor
when doing so wouldn't make sense.
For example, it might be difficult to agree on an obvious default [=sensor=] for
proximity [=sensors=].
In cases where
multiple [=sensors=] of the same [=sensor type|type=]
may coexist on the same device,
specification extension will have to
define ways to uniquely identify each one.
<div class="example">
For example checking the pressure of the left rear tire:
<pre highlight="js">
let sensor = new DirectTirePressureSensor({ position: "rear", side: "left" });
sensor.onchange = event => console.log(event.reading.pressure);
sensor.start();
</pre>
</div>
A note on Feature Detection of Hardware Features {#feature-detection}
================================================
<em>This section is non-normative.</em>
Feature detection is an established Web development best practice.
Resources on the topic are plentiful on and offline and
the purpose of this section is not to discuss it further,
but rather to put it in the context of detecting hardware-dependent features.
Consider the below feature detection examples:
<div class="example">
<pre highlight="js">
if (typeof Gyroscope === "function") {
// run in circles...
}
if ("ProximitySensor" in window) {
// watch out!
}
if (window.AmbientLightSensor) {
// go dark...
}
// etc.
</pre>
</div>
All of these tell you something about the presence
and possible characteristics of an API.
They do not tell you anything, however, about whether
that API is actually connected to a real hardware sensor,
whether that sensor works,
if its still connected,
or even whether the user is going to allow you to access it.
Note you can check the latter using the Permissions API [[PERMISSIONS]].
In an ideal world, information about the underlying status
would be available upfront.
The problem with this is twofold.
First, getting this information out of the hardware is costly,
in both performance and battery time,
and would sit in the critical path.
Secondly, the status of the underlying hardware can evolve over time.
The user can revoke permission, the connection to the sensor be severed,
the operating system may decide to limit sensor usage below a certain battery threshold,
etc.
Therefore, an effective strategy is to combine feature detection,
which checks whether an API for the sought-after sensor actually exists,
and defensive programming which includes:
1. checking for error thrown when instantiating a {{Sensor}} object,
2. listening to errors emitted by it,
3. handling all of the above graciously so that the user's experience is
enhanced by the possible usage of a sensor, not degraded by its
absence.
<div class="example">
<pre highlight="js">
try { // No need to feature detect thanks to try..catch block.
let sensor = new GeolocationSensor({});
sensor.start();
sensor.onerror = error => gracefullyDegrade(error);
sensor.onchange = event => updatePosition(event.reading.coords);
} catch(error) {
gracefullyDegrade(error);
}
</pre>
</div>
Security and privacy considerations {#security-and-privacy}
===================================
Privacy risks can arise when [=sensors=] are used
with each other,
in combination with other functionality,
or when used over time,
specifically with the risk of correlation of data
and user identification through fingerprinting.
Web application developers using these JavaScript APIs should
consider how this information might be correlated with other information
and the privacy risks that might be created.
The potential risks of collection of such data over a longer period of time
should also be considered.
Variations in [=sensor readings=]
as well as event firing rates
offer the possibility of fingerprinting to identify users.
User agents may reduce the risk by
limiting event rates available to web application developers.
Note: do we really want this mitigation strategy?
If the same JavaScript code using the API can be
used simultaneously in different window contexts on the same device
it may be possible for that code to correlate the user across those two contexts,
creating unanticipated tracking mechanisms.
User agents should consider providing the user
an indication of when the [=sensor=] is used
and allowing the user to disable it.
Web application developers that use [=sensors=] should
perform a privacy assessment of their application
taking all aspects of their application into consideration.
Ability to detect a full working set of sensors on a device can form an
identifier and could be used to fingerprinting.
A combination of selected sensors can potentially be used to form an out of
band communication channel between devices.
Sensors can potentially be used in cross-device linking and tracking of a user.
Browsing Context {#browsing-context}
----------------
[=Sensor readings=] must only be available in the
[=top-level browsing context=] to avoid the privacy risk of
sharing the information defined in this specification
(and specifications extending it)
with contexts unfamiliar to the user.
For example, a mobile device will only fire the event on
the active tab, and not on the background tabs or within iframes.
Secure Context {#secure-context}
--------------
[=Sensor readings=] are explicitly flagged by the
Secure Contexts specification [[POWERFUL-FEATURES]]
as a high-value target for network attackers.
As such, [=sensor readings=] must only be available
within a [=secure context=].
Obtaining Explicit User Permission {#permissioning}
----------------------------------
Permission to access [=sensor readings=] must be obtained
through the Permissions API [[!PERMISSIONS]].
Concepts {#concepts}
========
A [=sensor=] measures different physical quantities
and provide corresponding <dfn>raw sensor readings</dfn>
which are a source of information about the user and their environment.
Known, <em>predictable</em> discrepancies between [=raw sensor readings=]
and the corresponding physical quantities being measured
are corrected through <dfn>calibration</dfn>.
Known but <em>unpredictable</em> discrepancies need to be addressed dynamically
through a process called [=sensor fusion=].
[=calibration|Calibrated=] [=raw sensor readings=] are referred to as <dfn>sensor readings</dfn>,
whether or not they have undergone [=sensor fusion=].
Different [=sensor types=] measure different physical quantities
such as temperature, air pressure, heart-rate, or luminosity.
For the purpose of this specification we distinguish between
[=high-level=] and [=low-level=] [=sensor types=].
[=Sensor types=] which are characterized by their implementation
are referred to as <dfn>low-level</dfn> sensors.
For example a Gyroscope is a [=low-level=] [=sensor type=].
[=Sensors=] named after their [=sensor readings|readings=],
regardless of the implementation,
are said to be <dfn>high-level</dfn> sensors.
For instance, geolocation sensors provide information about the user's location,
but the precise means by which this data is obtained
is purposefully left opaque
(it could come from a GPS chip, network cell triangulation,
wifi networks, etc. or any combination of the above)
and depends on various, implementation-specific heuristics.
[=High-level=] sensors are generally the fruits of
applying algorithms to [=low-level=] sensors--
for example, a pedometer can be built using only the output of a gyroscope--
or of [=sensor fusion=].
That said, the distinction between
[=high-level=] and [=low-level=] [=sensor types=]
is somewhat arbitrary and the line between the two is often blurred.
For instance, a barometer, which measures air pressure,
would be considered [=low-level=] for most common purposes,
even though it is the product of the [=sensor fusion=] of
resistive piezo-electric pressure and temperature sensors.
Exposing the sensors that compose it would serve no practical purpose;
who cares about the temperature of a piezo-electric sensor?
A pressure-altimeter would probably fall in the same category,
while a nondescript altimeter--
which could get its data from either a barometer or a GPS signal--
would clearly be categorized as a [=high-level=] [=sensor type=].
Because the distinction is somewhat blurry,
extensions to this specification (see [[#extensibility]])
are encouraged to provide domain-specific definitions of
[=high-level=] and [=low-level=] sensors
for the given [=sensor types=] they are targeting.
[=Sensor readings=] from different [=sensor types=] can be combined together
through a process called <dfn>sensor fusion</dfn>.
This process provides [=high-level|higher-level=] or
more accurate data (often at the cost of increased latency).
For example, the [=sensor readings|readings=] of a three-axis magnetometer
needs to be combined with the [=sensor readings|readings=] of an accelerometer
to provide a correct bearing.
<dfn>Smart sensors</dfn> and <dfn>sensor hubs</dfn>
have built-in compute resources which allow them
to carry out [=calibration=] and [=sensor fusion=] at the hardware level,
freeing up CPU resources
and lowering battery consumption
in the process.
But [=sensor fusion=] can also be carried out in software.
This is particularly useful when performance requirements can only be met
by relying on application-specific data.
For example, head tracking for virtual or augmented reality applications,
requires extremely low latency
to avoid causing motion sickness.
That low-latency is best provided
by using the raw output of a gyroscope,
and waiting for quick rotational movements of the head
to compensate for drift.
Note: [=sensors=] created through [=sensor fusion=] are sometimes
called virtual or synthetic sensors.
However, the specification doesn't make any practical differences between them,
preferring instead to differentiate [=sensors=] as to whether they describe
the kind of [=sensor readings|readings=] produced--these are [=high-level=] sensors--
or how the sensor is implemented ([=low-level=] sensors).
[=Sensors=] have different <dfn>reporting modes</dfn>.
When [=sensor readings=] are reported at regular intervals,
at an ajustable <dfn>frequency</dfn> measured in hertz (Hz),
the [=reporting mode=] is said to be <dfn>periodic</dfn>.
When it is only reported upon measurable change,
the [=sensor=] is said to be in <dfn>auto</dfn> [=reporting mode=].
[=Auto=] [=reporting mode=] can give the user agent
more latitude to carry out power- or CPU-saving strategies
and should generally be favored.
[=Periodic=] [=reporting mode=], on the other hand,
allows a much more fine-grained approach
and is essential for use cases with, for example,
low latency requirements.
Note: [=reporting mode=] is distinct from,
but related to,
[=sensor readings=] acquisition.
If [=sensors=] are polled at regular interval,
as is generally the case,
[=reporting mode=] can be either [=periodic=] or [=auto=].
However, when the underlying implementation itself only provides [=sensor readings=]
when it measures change,
perhaps because is is relying on [=smart sensors=] or a [=sensor hubs=],
the [=reporting mode=] cannot be [=periodic=],
as that would require data inference.
Model {#model}
=====
Sensor Type {#model-sensor-type}
-----------
A <dfn>sensor type</dfn> has one or many associated [=sensors=].
A [=sensor type=] has an associated <dfn export>Sensor subclass</dfn>.
A [=sensor type=] has an associated <dfn export>SensorReading subclass</dfn>.
Attributes of the [=SensorReading subclass=] subclass that
hold [=sensor readings=] must be readonly.
A [=sensor type=] may have a <dfn export>default sensor</dfn>.
A [=sensor type=] has an associated set of <dfn export>supported reporting modes</dfn>,
which cannot be empty and must be picked from the following:
[=auto=] and [=periodic=].
If a [=sensor type=] has more than one [=sensor=],
it must have a set of associated <dfn export>identifying parameters</dfn>
to select the right [=sensor=] to associate to each new {{Sensor}} objects.
A [=sensor type=] has an associated abstract operation to
<dfn export lt="Construct SensorReading Object">construct a SensorReading object</dfn>
which takes the [=sensor readings=] emitted by the [=sensor=] and
returns an initialized {{SensorReading}} object
which uses the [=sensor type=]'s associated [=SensorReading subclass=].
Sensor {#model-sensor}
------
A <dfn id=concept-sensor>sensor</dfn> has an associated set of <dfn>activated Sensor objects</dfn>. This set is initially empty.
A [=sensor=] has an associated <dfn>current reading</dfn>,
which can initially be `null` or
be set to a {{SensorReading}} object, that was cached in a user-agent-specific way.
Note: there are additional privacy concerns when using cached [=sensor readings|readings=]
which predate either [=navigating=] to resources in the current [=origin=],
or being granted permission to access the [=sensor=].
A [=sensor=] is said to <dfn lt="supports periodic reporting mode">support periodic reporting mode</dfn> if
its associated [=sensor type=]'s [=supported reporting modes=]
contains the [=periodic=] [=reporting mode=].
A [=sensor=] has an associated <dfn>reporting flag</dfn> which is initially unset.
A [=sensor=] has an associated <dfn>current reporting mode</dfn> which is initially `undefined`.
A [=sensor=] has an associated <dfn>current polling frequency</dfn> which is initially `null`.
A [=sensor=] has an associated abstract operation to
<dfn export lt="retrieve the sensor permission">retrieve its permission</dfn> which
takes a {{Sensor}} object as input and
returns a [=permission=] and, eventually, its [=associated PermissionDescriptor=].
API {#api}
===
The Sensor Interface {#the-sensor-interface}
--------------------
<pre class="idl">
interface Sensor : EventTarget {
readonly attribute SensorState state;
readonly attribute SensorReading? reading;
void start();
void stop();
attribute EventHandler onchange;
attribute EventHandler onstatechange;
attribute EventHandler onerror;
};
dictionary SensorOptions {
double? frequency;
};
enum SensorState {
"idle",
"activating",
"active",
"errored"
};
</pre>
A {{Sensor}} object has an associated [=sensor=].
A {{Sensor}} object has an associated <dfn>state</dfn>,
which is one of <a enum-value>"idle"</a>, <a enum-value>"activating"</a>, <a enum-value>"active"</a>, and <a enum-value>"errored"</a>. It is initially <a enum-value>"idle"</a>.
A {{Sensor}} object has an associated <dfn>desired frequency</dfn>. It is initially `null`.
Each {{Sensor}} object has a [=task source=]
called a <dfn>sensor task source</dfn>, initially empty.
A [=sensor task source=] can be enabled or disabled, and is initially enabled.
When enabled, the [=event loop=] must use it as one of its [=task sources=].
The [=task source=] for the [=tasks=] mentioned in this specification is the [=sensor task source=].
When the [=visibility state=] of the [=Document=] in the [=top-level browsing context=] changes,
let |current_visibility_state| be the result of running the [=steps to determine the visibility state=]
of the [=Document=].
If |current_visibility_state| is "visible", enable the sensor task source, otherwise, disable it.
Note: user agents are encouraged to stop sensor polling
when [=sensor task sources=] are disabled in order
to save battery.
### Sensor.state ### {#sensor-state}
The <a attribute for="Sensor">state</a> attribute represents a {{Sensor}} object's [=state=].
### Sensor.reading ### {#sensor-reading}
When a {{Sensor}}'s [=state=] is <a enum-value>"active"</a>,
its <a attribute for="Sensor">reading</a> attribute must always point to the [=current reading=]
whatever the [=frequency=] so that
the <a attribute for="Sensor">reading</a> attribute of two instances of the same {{Sensor}} interface
associated with the same [=sensor=]
hold the same {{SensorReading}} during a single [=event loop=] turn.
### Sensor.start() ### {#sensor-start}
<div algorithm="to start a sensor">
The {{Sensor/start()}} method must run these steps or their [=equivalent=]:
1. If |sensor_instance|'s [=state=] is neither <a enum-value>"idle"</a> nor <a enum-value>"errored"</a>,
1. throw an "[=InvalidStateError=]" exception and abort these steps.
1. Invoke the [=update state=] algorithm passing |sensor_instance| and <a enum-value>"activating"</a> as the arguments.
1. Run these sub-steps [=in parallel=]:
1. Let |state| be the result of invoking the [=Request Sensor Access=] abstract operation,
passing it |sensor_instance| as argument.
1. If |state| is "granted",
1. Invoke [=Register a Sensor=] passing it |sensor_instance| as argument.
1. Abort these sub-steps.
1. If |state| is "denied",
1. let |e| be the result of [=creating an exception=] named [=NotAllowedError=].
1. Invoke the [=Handle Errors=] abstract operation,
passing it |e| and |sensor_instance| as arguments.
1. Abort these sub-steps.
1. return `undefined`.
</div>
### Sensor.stop() ### {#sensor-stop}
<div algorithm="to stop a sensor">
The {{Sensor/stop()}} method must run these steps or their [=equivalent=]:
1. If |sensor_instance|'s [=state=] is either <a enum-value>"idle"</a> or <a enum-value>"errored"</a>, then
1. throw an "[=InvalidStateError=]" exception and abort these steps.
1. Set |sensor_instance|’s <a attribute for="Sensor">reading</a> to `null`.
1. Invoke the [=update state=] algorithm passing |sensor_instance| and <a enum-value>"idle"</a> as the arguments.
1. Run these sub-steps [=in parallel=]:
1. Invoke [=Unregister a Sensor=] passing it |sensor_instance| as argument.
1. return `undefined`.
</div>
### Sensor.onerror ### {#sensor-onerror}
### Sensor.onchange ### {#sensor-onchange}
### Sensor.onstatechange ### {#sensor-onstatechange}
### Event handlers ### {#event-handlers}
The following are the [=event handlers=]
(and their corresponding [=event handler event types=])
that must be supported as attributes by the objects implementing the [=Sensor=] interface:
<table class="simple">
<thead>
<tr>
<th>event handler</th>
<th>event handler event type</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong><code>onchange</code></strong></td>
<td><code>change</code></td>
</tr>
<tr>
<td><strong><code>onstatechange</code></strong></td>
<td><code>statechange</code></td>
</tr>
<tr>
<td><strong><code>onerror</code></strong></td>
<td><code>error</code></td>
</tr>
</tbody>
</table>
The SensorReading Interface {#the-sensor-reading-interface}
---------------------------
<pre class="idl">
interface SensorReading {
readonly attribute DOMHighResTimeStamp timeStamp;
};
</pre>
A {{SensorReading}} represents the state of a [=sensor=] at a given point in time.
### SensorReading.timeStamp ### {#sensor-reading-timestamp}
Returns a timestamp of the time
at which the [=sensor reading|reading=] was obtained from the [=sensor=]
expressed in milliseconds that passed since the [=time origin=].
Issue(101):
The SensorReadingEvent Interface {#the-sensor-reading-event-interface}
--------------------------------
<pre class="idl">
[Constructor(DOMString type, SensorReadingEventInit eventInitDict)]
interface SensorReadingEvent : Event {
readonly attribute SensorReading reading;
};
dictionary SensorReadingEventInit : EventInit {
required SensorReading reading;
};
</pre>
### SensorReadingEvent.reading ### {#sensor-reading-event-reading}
The <dfn attribute for=SensorReadingEvent>reading</dfn> attribute references
the [=current reading=] at the time of [=dispatch|event dispatch=].
The SensorErrorEvent Interface {#the-sensor-error-event-interface}
------------------------------
<pre class="idl">
[Constructor(DOMString type, SensorErrorEventInit errorEventInitDict)]
interface SensorErrorEvent : Event {
readonly attribute Error error;
};
dictionary SensorErrorEventInit : EventInit {
required Error error;
};
</pre>
### SensorErrorEvent.error ### {#sensor-error-event-error}
Abstract Operations {#abstract-operations}
===================
<h3 export algorithm dfn>Construct Sensor Object</h3>
: input
:: |options|, a <a dictionary>SensorOptions</a> object.
: output
:: |sensor_instance|, a {{Sensor}} object.
1. If the [=incumbent settings object=] is not a [=secure context=], then:
1. [=throw=] a SecurityError.
1. If the [=browsing context=] is not a [=top-level browsing context=], then:
1. [=throw=] a SecurityError.
1. Otherwise, if [=identifying parameters=] in |options| are set, then:
1. If these [=identifying parameters=] allow a unique [=sensor=] to be identified, then:
1. let |sensor| be that [=sensor=],
1. let |sensor_instance| be a new {{Sensor}} object,
1. associate |sensor_instance| with |sensor|.
1. Otherwise, [=throw=] a TypeError.
1. Otherwise, if a [=default sensor=] exists for this [=sensor type=]:
1. let |sensor| be that [=sensor=],
1. let |sensor_instance| be a new {{Sensor}} object,
1. associate |sensor_instance| with |sensor|.
1. Otherwise, [=throw=] a TypeError.
1. Let |frequency| be the value of the <a dict-member>frequency</a> member of |options|.
1. If |frequency| is not `null`,
1. If |sensor| [=supports periodic reporting mode=],
1. Set |sensor_instance|'s [=desired frequency=] to |frequency|.
1. Otherwise,
1. [=throw=] a TypeError.
1. Set |sensor_instance|'s <a for="Sensor" attribute>reading</a> attribute to `null`.
1. Set |sensor_instance|'s [=state=] to <a enum-value>"idle"</a>.
1. return |sensor_instance|.
<h3 algorithm dfn>Register a Sensor</h3>
: input
:: |sensor_instance|, a {{Sensor}} object.
: output
:: None
1. Let |sensor| be the [=sensor=] associated with |sensor_instance|.
1. Add |sensor_instance| to |sensor|'s set of [=activated Sensor objects=].
1. Invoke the [=Set Sensor Settings=] abstract operation,
passing it |sensor| as argument.
1. Let |current_reading| be |sensor|'s associated [=current reading=].
1. If |current_reading| is not `null` and |sensor_instance|'s state is still <a enum-value>"activating"</a>, then
1. invoke the [=Update Reading=] operation, passing it
|sensor_instance| and |current_reading| as arguments.
<h3 algorithm dfn>Unregister a Sensor</h3>
: input
:: |sensor_instance|, a {{Sensor}} object.
: output
:: None
1. Let |sensor| be the [=sensor=] associated with |sensor_instance|.
1. Remove |sensor_instance| from |sensor|'s set of [=activated Sensor objects=].
1. If |sensor|'s set of [=activated Sensor objects=] is empty,
1. Set [=current reporting mode=] to `undefined`.
1. Set [=current polling frequency=] to `null`.
1. Update the user-agent-specific way in which [=sensor readings=] are obtained from |sensor|
to no longer provide <a lt ="sensor readings">readings</a>.
1. Abort these steps.
1. Invoke the [=Set Sensor Settings=] abstract operation,
passing it |sensor| as argument.
<h3 algorithm dfn>Set Sensor Settings</h3>
: input
:: |sensor|, a [=sensor=].
: output
:: None
1. Let |settings_changed| be `false`.
1. Let |mode| be the result of invoking the [=find current reporting mode of a sensor=] abstract operation,
with |sensor| as argument.
1. If |mode| is different from |sensor|'s [=current reporting mode=],
1. set |settings_changed| to `true`.
1. Set [=current reporting mode=] to |mode|.
1. Let |frequency| be the result of invoking the [=Find the polling frequency of a Sensor=] abstract operation,
with |sensor| as argument.
1. If |frequency| is different from |sensor|'s [=current polling frequency=],
1. set |settings_changed| to `true`.
1. Set [=current polling frequency=] to |frequency|.
1. If |settings_changed| is `true`
1. Invoke the [=Observe a Sensor=] abstract operation, passing it |sensor| as argument.
<h3 algorithm dfn>Observe a Sensor</h3>
: input
:: |sensor|, a [=sensor=].
: output
:: None
1. If |sensor|'s [=current reporting mode=] is [=periodic=],
1. let |frequency| be the [=current polling frequency=],
capped by the upper and lower bounds of the underlying hardware.
1. Invoke the [=Update Current Reading=] abstract operation
at a [=frequency=] of |frequency| passing it |sensor| and
the latest [=sensor reading=] as arguments.
Note: there is not guarantee that the [=current polling frequency=]
can be respected. The actual [=frequency=] can be calculated using
{{SensorReading}} <a attribute for=SensorReading>timeStamp</a> attributes.
1. If the [=current reporting mode=] is set to [=auto=],
1. the user-agent can decide on the best reporting strategy
for this particular |sensor| and [=sensor type=].
1. The user-agent must invoke the [=Update Current Reading=] abstract operation
at to report fresh [=sensor readings|readings=],
passing it |sensor| and the latest [=sensor reading=] as arguments.
<h3 algorithm dfn>Find Current Reporting Mode of a Sensor</h3>
: input
:: |sensor|, a [=sensor=].
: output
:: |mode|, a [=reporting mode=].
1. let |mode| be [=auto=].
1. For each |sensor_instance| in |sensor|'s set of [=activated Sensor objects=]:
1. if |sensor_instance|'s [=frequency=] is not `null`,
1. set |mode| to [=periodic=]
1. return |mode|.
<h3 algorithm dfn>Find the polling frequency of a Sensor</h3>
: input
:: |sensor|, a [=sensor=].
: output
:: |frequency|, a [=frequency=].
1. let |frequency| be `null`.
1. For each |sensor_instance| in |sensor|'s set of [=activated Sensor objects=]:
1. let |f| be |sensor_instance|'s [=frequency=].
1. if |f| is not `null` and |f| is greater than |frequency|,
1. set |frequency| to |f|.
1. return |frequency|.
<h3 algorithm dfn>Update State</h3>
: input
:: |sensor_instance|, a {{Sensor}} object.
:: |state|, a {{Sensor}} object's [=state=].
: output
:: None
1. Set |sensor_instance|’s <a attribute>state</a> to |state|.
1. [=Queue a task=] to [=fire a simple event=] named `statechange` at |sensor_instance|.
<h3 algorithm dfn>Update Current Reading</h3>
: input
:: |sensor|, a [=sensor=].
:: |reading|, a [=sensor reading=].
: output
:: None
1. If |sensor|’s [=reporting flag=] is set,
1. abort these steps.
1. Set |sensor|’s [=reporting flag=].
1. Let |reading_instance| be the result of invoking [=sensor type=]'s associated
[=Construct SensorReading Object=] operation,
passing it |reading| as argument.
1. Set |sensor|’s [=current reading=] to |reading_instance|.
1. For each |sensor_instance| in |sensor|'s set of [=activated Sensor objects=]:
1. Invoke the [=update reading=] algorithm passing |sensor_instance|
and |reading_instance| as arguments.
1. Unset |sensor|’s [=reporting flag=].
<h3 algorithm dfn>Update Reading</h3>
: input
:: |sensor_instance|, a {{Sensor}} object.
:: |reading|, a {{SensorReading}} object.
: output
:: None
1. Set |sensor_instance|’s <a attribute for="Sensor">reading</a> to |reading|.
1. If |sensor_instance|'s <a attribute>state</a> is <a enum-value>"activating"</a>:
1. Invoke the [=update state=] algorithm passing |sensor_instance|
and <a enum-value>"active"</a> as the arguments.
1. Create an [=event=] |e| that uses the {{SensorReadingEvent}} interface,
with the event type `reading`, which does not bubble, is not cancelable, is [=trusted=], and has no default action.
1. Let the <a attribute for=SensorReadingEvent>reading</a> attribute of |e| be initialized to |reading|.
1. [=Queue a task=] to [=dispatch=] |e| at |sensor_instance|.
<h3 algorithm dfn>Handle Errors</h3>
: input
:: |sensor_instance|, a {{Sensor}} object.
:: |error|, an [=Error=] object.
: output
:: None
1. Set |sensor_instance|’s <a attribute for="Sensor">reading</a> to `null`.
1. Invoke the [=update state=] algorithm passing |sensor_instance| and <a enum-value>"errored"</a> as the arguments.
1. Create an [=event=] |e| that uses the {{SensorErrorEvent}} interface,
with the event type `error`, which does not bubble, is not cancelable, is [=trusted=], and has no default action.
1. Let the <a attribute for=SensorErrorEvent>error</a> attribute of |e| be initialized to |error|.
1. [=Queue a task=] to [=dispatch=] |e| at |sensor_instance|.
<h3 algorithm dfn>Request Sensor Access</h3>
: input
:: |sensor_instance|, a {{Sensor}} object.
: output
:: |state|, a [=permission state=].
1. Let |sensor| be the [=sensor=] associated with |sensor_instance|.
1. let |permission| be the result of invoking the abstract operation [=retrieve the sensor permission=] associated with |sensor|,
passing it |sensor_instance| as argument.
1. Let |state| be the result of [=retrieving the permission state=] for |permission|.
1. If |state| is "prompt",
1. prompt the user in a user-agent-specific manner for permission to provide access to |sensor|.
1. If permission is granted,
1. set |state| to "granted",
1. else,
1. set |state| to "denied".
1. return |state|.
Extensibility {#extensibility}
=============
<em>This section is non-normative.</em>
Its purpose is to describe
how this specification can be extended to specify APIs for
different [=sensor types=].
Extension specifications are encouraged to focus on a single [=sensor type=],
exposing both [=high-level|high=] and [=low-level|low=] level
as appropriate.
Naming {#naming}
------
{{Sensor}} interfaces for [=low-level=] sensors should be
named after their associated [=sensor=].
So for example, the interface associated with a gyroscope
should be simply named `Gyroscope`.
{{Sensor}} interfaces for [=high-level=] sensors should be
named by combining the physical quantity the [=sensor=] measures
with the "Sensor" suffix.
For example, a [=sensor=] measuring
the distance at which an object is from it
may see its associated interface called `ProximitySensor`.
Attributes of the {{SensorReading}} subclass that
hold [=sensor readings=] values
should be named after the full name of these values.
For example, the `TemperatureSensorReading` interface should hold
the [=sensor reading=]'s value in
a `temperature` attribute (and not a `value` or `temp` attribute).
A good starting point for naming are the
Quantities, Units, Dimensions and Data Types Ontologies [[QUDT]].
Unit {#unit}
----
Extension specification must specify the unit of [=sensor readings=].
As per the Technical Architecure Group's (TAG) API Design Principles [[API-DESIGN-PRINCIPLES]],
all time measurement should be in milliseconds.
All other units should be specified using,
in order of preference,
and with the exception of temperature (for which Celsius should be favored over Kelvin),
the International System of Units (SI),
SI derived units, and
Non-SI units accepted for use with the SI,
as described in the SI Brochure [[SI]].
Exposing High-Level vs. Low-Level Sensors {#high-vs-low-level}
-----------------------------------------
So far, specifications exposing sensors to the Web platform
have focused on [=high-level=] sensors APIs. [[GEOLOCATION-API]] [[ORIENTATION-EVENT]]
This was a reasonable approach for a number of reasons.
Indeed, [=high-level=] sensors: