forked from w3c/sensors
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.bs
1583 lines (1251 loc) · 57.2 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
Shortname: generic-sensor
Status: ED
Group: dap
ED: https://w3c.github.io/sensors/
TR: https://www.w3.org/TR/generic-sensor/
Previous Version: https://www.w3.org/TR/2017/WD-generic-sensor-20170130/
Editor: Tobie Langel 78102, Intel Corporation, http://tobie.me, [email protected]
Editor: Rick Waldron 50572, JS Foundation
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.
!Feedback: <a href="https://github.com/w3c/sensors">GitHub</a> (<a href="https://github.com/w3c/sensors/issues/new">new issue</a>, <a href="https://github.com/w3c/sensors/milestone/2">level 1 issues</a>, <a href="https://github.com/w3c/sensors/issues">all issues</a>)
!Other: <a href="https://github.com/w3c/web-platform-tests/tree/master/generic-sensor">Test suite</a>, <a href="https://github.com/w3c/sensors/commits/gh-pages/index.bs">version history</a>
Indent: 2
Repository: w3c/sensors
Markup Shorthands: markdown on
Boilerplate: omit issues-index, omit conformance, omit feedback-header
Default Biblio Status: current
</pre>
<pre class="anchors">
urlPrefix: https://dom.spec.whatwg.org; spec: DOM
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: task; url: concept-task
text: fire a simple event
text: trusted; url: concept-events-trusted
urlPrefix: browsers.html
text: origin; url: origin-2
text: navigating; url: navigate
text: browsing context
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/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>
<pre class=link-defaults>
spec: webidl; type:dfn; text:attribute
</pre>
<h2 id="intro">Introduction</h2>
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.
Issue: This lacks an informative section with examples for developers.
Should contain different use of the API,
including using it in conjunction with `requestAnimationFrame`.
<h2 id="scope">Scope</h2>
<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 (e.g. Bluetooth)
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.
<h2 id="background">Background</h2>
<em>This section is non-normative</em>.
Issue: This section is ill-named.
It principally covers default sensors
and explains the reasoning behind them.
It should be renamed accordingly and moved,
either to another section of the spec
or to an external explainer document.
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 = [sensor.latitude, sensor.longitude];
updateMap(null, coords, sensor.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">
var sensor = new DirectTirePressureSensor({ position: "rear", side: "left" });
sensor.onchange = _ => console.log(sensor.pressure);
sensor.start();
</pre>
</div>
<h2 id="feature-detection">A note on Feature Detection of Hardware Features</h2>
<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.
var sensor = new GeolocationSensor();
sensor.start();
sensor.onerror = error => gracefullyDegrade(error);
sensor.onchange = _ => updatePosition(sensor.latitude, sensor.longitude);
} catch(error) {
gracefullyDegrade(error);
}
</pre>
</div>
<h2 id="security-and-privacy">Security and privacy considerations</h2>
Issue: This section needs to be reorganized.
It probably needs a section that lists threats
and one that lists mitigation strategies,
with links between both.
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?
Frequency polling in [=periodic=] [=reporting mode=]
might allow the fingerprinting of hardware or implementation types,
by probing which actual frequencies are supported by the platform.
Minimizing the accuracy of a sensor's readout
generally decreases the risk of fingerprinting.
User agents should not provide unnecessarily verbose readouts of sensors data.
Each [=sensor type=] should be assessed individually.
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.
Additionally, user agents may consider
allowing the user to verify past and current sensor use patterns.
Web application developers that use [=sensors=] should
perform a privacy impact 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 for 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.
<h3 id="browsing-context">Browsing Context</h3>
[=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.
Note: [Feature Policy](https://docs.google.com/document/d/1k0Ua-ZWlM_PsFCFdLMa8kaVTo32PeNZ4G7FFHqpFx4E/edit)
should allow securely lifting those restrictions once it matures.
<h3 id="secure-context">Secure Context</h3>
[=Sensor readings=] are explicitly flagged by the
Secure Contexts specification [[POWERFUL-FEATURES]]
as a high-value target for network attackers.
Thus all interfaces defined by this specification
or extension specifications
must only be available within a [=secure context=].
<h3 id="permissioning">Obtaining Explicit User Permission</h3>
Permission to access [=sensor readings=] must be obtained
through the Permissions API [[!PERMISSIONS]].
<h2 id="concepts">Concepts</h2>
<h3 id="concepts-sensors">Sensors</h3>
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.
Each [=raw sensor reading|reading=] is composed of the <dfn lt="reading value">values</dfn>
of the different physical quantities measured by the [=sensor=]
at time <var ignore>t<sub>n</sub></var>.
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=].
<h3 id="concepts-sensor-types">Sensor Types</h3>
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).
<h3 id="concepts-reporting-modes">Reporting Modes</h3>
Issue: **This feature is at risk.**
It is not clear whether there is value
in splitting up [=sensor types=] between
those that fire events at regular intervals
and those which don't.
[=Sensors=] have different <dfn>reporting modes</dfn>.
When [=sensor readings=] are reported at regular intervals,
at an adjustable <dfn>frequency</dfn> measured in hertz (Hz),
the [=reporting mode=] is said to be <dfn>periodic</dfn>.
On [=sensor types=] with support for [=periodic|periodic reporting mode=],
[=periodic|periodic reporting mode=] is triggered
by requesting a specific [=frequency=].
[=Sensor types=] which do not support [=periodic|periodic reporting mode=]
are said to operate in an <dfn>implementation specific</dfn> way.
When the [=reporting mode=] is [=implementation specific=],
[=sensor readings=] may be provided at regular intervals, irregularly,
or only when a [=sensor readings|reading=] change is observed.
This allows user agents more latitude to
carry out power- or CPU-saving strategies,
and support multiple hardware configurations.
[=periodic|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.
[=Sensors=] which support [=periodic|periodic reporting mode=]
<dfn>fallback</dfn> to [=implementation specific|implementation specific reporting mode=]
when no requirements are made as to what [=frequency=] they should operate at.
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 [=implementation specific=].
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.
Issue: This lacks a description of
the different data acquisition modes,
notably polling vs. on change,
both at the platform and HW layer.
Issue: It would be useful to describe
the process of sensor polling and
how increased sensor polling frequency decreases latency.
Issue: A definition of sensor accuracy and
how it affects threshold,
and thus "on change" sensors would be useful.
<h2 id="model">Model</h2>
Issue: A diagram would really help here.
<h3 id="model-sensor-type">Sensor Type</h3>
A <dfn>sensor type</dfn> has an associated [=interface=]
whose [=inherited interfaces=] contains {{Sensor}}.
A [=sensor type=] has a [=ordered set|set=] of <dfn export>associated sensors</dfn>.
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=] may have a <dfn export>default sensor</dfn>.
A [=sensor type=] has an associated {{PermissionName}}.
Note: multiple [=sensor types=] may share the same {{PermissionName}}.
A [=sensor type=] has a [=permission revocation algorithm=].
<div algorithm>
To invoke the <dfn lt="generic sensor permission revocation algorithm">permission revocation algorithm</dfn>
with {{PermissionName}} |permission_name|, run the following steps:
1. For each |sensor_type| which has an associated {{PermissionName}} |permission_name|:
1. [=set/For each=] |sensor| in |sensor_type|'s [=ordered set|set=] of [=associated sensors=],
1. Invoke the [=revoke sensor permission=] abstract operation with |sensor| as argument.
</div>
<h3 id="model-sensor">Sensor</h3>
A <dfn id=concept-sensor>sensor</dfn> has an associated [=ordered set|set=]
of <dfn>activated Sensor objects</dfn>.
This set is initially [=set/is empty|empty=].
A [=sensor=] has an associated <dfn>latest reading</dfn> [=ordered map|map=]
which holds the latest available [=sensor readings=].
Issue: does the [=latest reading=] map need to be
tied to an origin?
The [=latest reading=] [=ordered map|map=]
contains an [=map/entry=]
whose [=map/key=] is "timestamp" and
whose [=map/value=] is a high resolution timestamp of the time
at which the [=latest reading=] was obtained
expressed in milliseconds that passed since the [=time origin=].
[=latest reading=]["timestamp"] is initially set to `null`,
unless the [=latest reading=] [=ordered map|map=] caches a previous [=sensor readings|reading=].
The other [=map/entries=] of the [=latest reading=] [=ordered map|map=]
hold the values of the different quantities measured by the [=sensor=].
The [=map/keys=] of these [=map/entries=] must match
the [=attribute=] names defined by
the [=sensor type=]'s associated interface,
so that the getter of the `foo` attribute
can simply return [=latest reading=]["foo"].
The [map/value] of all [=latest reading=] [=map/entries=]
is initially set to `null`.
<!-- ,
unless the [=latest reading=] [=ordered map|map=]
caches a previous [=sensor readings|reading=].
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=] <dfn>supports periodic reporting mode</dfn> if
its associated [=sensor type=] does.
A [=sensor=] has an associated <dfn>reporting flag</dfn> which is initially unset.
A [=sensor=] has an associated <dfn>periodic reporting mode flag</dfn> which is initially unset.
A [=sensor=] has an associated <dfn>current polling frequency</dfn> which is initially `null`.
<h2 id="api">API</h2>
<h3 id="the-sensor-interface">The Sensor Interface</h3>
<pre class="idl">
[SecureContext]
interface Sensor : EventTarget {
readonly attribute SensorState state;
readonly attribute DOMHighResTimeStamp? timestamp;
void start();
void stop();
attribute EventHandler onchange;
attribute EventHandler onactivate;
attribute EventHandler onerror;
};
dictionary SensorOptions {
double? frequency;
};
enum SensorState {
"unconnected",
"activating",
"activated",
"idle",
"errored"
};
</pre>
A {{Sensor}} object has an associated [=sensor=].
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 internal slots ### {#sensor-internal-slots}
Instances of {{Sensor}} are created
with the internal slots described in the following table:
<table id="sensor-slots" class="vert data">
<thead>
<tr><th>Internal Slot</th><th>Description (non-normative)</th></tr>
</thead>
<tbody>
<tr>
<td><dfn export>\[[state]]</dfn></td>
<td>The current state of {{Sensor}} object which is one of
<a enum-value>"unconnected"</a>,
<a enum-value>"activating"</a>,
<a enum-value>"activated"</a>,
<a enum-value>"idle"</a>, and
<a enum-value>"errored"</a>.
It is initially <a enum-value>"unconnected"</a>.
</td>
</tr>
<tr>
<td><dfn>\[[desiredPollingFrequency]]</dfn></td>
<td>The requested polling frequency. It is initially unset.</td>
</tr>
<tr>
<td><dfn>\[[lastEventFiredAt]]</dfn></td>
<td>the high resolution timestamp of the latest [=sensor reading=]
that was sent to observers of the {{Sensor}} object,
expressed in milliseconds that passed since the [=time origin=].
It is initially `null`.
</td>
</tr>
<tr>
<td><dfn>\[[waitingForUpdate]]</dfn></td>
<td>A boolean which indicates wether the observers have been updated
or whether the object is waiting for a new reading to do so.
It is initially `true`.</td>
</tr>
<tr>
<td><dfn>\[[identifyingParameters]]</dfn></td>
<td>
A [=sensor type=]-epecific group of [=dictionary members=]
used to select the correct [=sensor=]
to associate to this {{Sensor}} object.
</td>
</tr>
</tbody>
</table>
### Sensor.state ### {#sensor-state}
The getter of the {{Sensor/state!!attribute}} attribute returns <emu-val>this</emu-val>.\[[state]].
### Sensor.timestamp ### {#sensor-timestamp}
The getter of the {{Sensor/timestamp!!attribute}} attribute returns
[=latest reading=]["timestamp"].
### Sensor.start() ### {#sensor-start}
<div algorithm="to start a sensor">
The {{Sensor/start()}} method must run these steps or their [=equivalent=]:
1. Let |sensor_state| be the value of sensor_instance|.[=[[state]]=].
1. If |sensor_state| is either <a enum-value>"activating"</a>
or <a enum-value>"activated"</a>, then return.
1. Set |sensor_instance|.[=[[state]]=] to <a enum-value>"activating"</a>.
1. Run these sub-steps [=in parallel=]:
1. If |sensor_state| is <a enum-value>"unconnected"</a>, then:
1. let |connected| be the result of invoking
the [=Connect to Sensor=] abstract operation.
1. If |connected| is `false`, then abort these steps.
1. Let |permission_state| be the result of invoking
the [=Request Sensor Access=] abstract operation,
passing it |sensor_instance| as argument.
1. If |permission_state| is "granted",
1. Invoke [=Register a Sensor Object=] passing it |sensor_instance| as argument.
1. Otherwise, if |permission_state| is "denied",
1. let |e| be the result of [=created|creating=]
a "{{NotAllowedError!!exception}}" {{DOMException}}.
1. Invoke the [=Handle Errors=] abstract operation,
passing it |e| and |sensor_instance| as arguments.
</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|.[=[[state]]=] is neither <a enum-value>"activating"</a>
nor <a enum-value>"activated"</a>, then return.
1. Set |sensor_instance|.[=[[state]]=] to <a enum-value>"idle"</a>.
1. Run these sub-steps [=in parallel=]:
1. Invoke [=Unregister a Sensor=] passing it |sensor_instance| as argument.
</div>
### Sensor.onchange ### {#sensor-onchange}
{{Sensor/onchange}} is an {{EventHandler}} which is called whenever a new [=sensor reading|reading=] is available.
Issue: Should this be renamed `onreading`?
Should we instead add an `ondata` {{EventHandler}} for continuous data
and use `onchange` when the data changed?
### Sensor.onactivate ### {#sensor-onactivate}
{{Sensor/onactivate}} is an {{EventHandler}} which is called when <emu-val>this</emu-val>.[=[[state]]=] transitions from <a enum-value>"activating"</a> to <a enum-value>"activated"</a>.
### Sensor.onerror ### {#sensor-onerror}
{{Sensor/onerror}} is an {{EventHandler}} which is called whenever an [=exception type|exception=] cannot be handled synchronously.
### 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>onactivate</code></strong></td>
<td><code>activate</code></td>
</tr>
<tr>
<td><strong><code>onerror</code></strong></td>
<td><code>error</code></td>
</tr>
</tbody>
</table>
<h3 id="the-sensor-error-event-interface">The SensorErrorEvent Interface</h3>
<pre class="idl">
[SecureContext, 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}
Gets the {{Error}} object passed to {{SensorErrorEventInit}}.
<h2 id="abstract-operations">Abstract Operations</h2>
<h3 dfn export>Construct Sensor Object</h3>
<div algorithm="construct sensor object">
: input
:: |options|, a {{SensorOptions}} 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. Let |sensor_instance| be a new {{Sensor}} object,
1. If [=sensor=] [=supports periodic reporting mode=] and
|options|.{{frequency!!dict-member}} is [=present=], then
1. Set |sensor_instance|.[=[[desiredPollingFrequency]]=] to |options|.{{frequency!!dict-member}}.
Note: there is not guarantee that the requested |options|.{{frequency!!dict-member}}
can be respected. The actual [=frequency=] can be calculated using
{{Sensor}} {{Sensor/timestamp!!attribute}} attributes.
1. If [=identifying parameters=] in |options| are set, then:
1. Set |sensor_instance|.[=[[identifyingParameters]]=] to [=identifying parameters=].
1. Set |sensor_instance|.[=[[state]]=] to <a enum-value>"unconnected"</a>.
1. Return |sensor_instance|.
</div>
<h3 dfn export>Connect to Sensor</h3>
<div algorithm="connect to sensor">
: input
:: |sensor_instance|, a {{Sensor} object.
: output
:: a boolean.
1. If |sensor_instance|.[=[[identifyingParameters]]=] is set and
|sensor_instance|.[=[[identifyingParameters]]=] allows
a unique [=sensor=] to be identified, then:
1. let |sensor| be that [=sensor=],
1. associate |sensor_instance| with |sensor|.
1. Return `true`.
1. If the [=sensor type=] of |sensor_instance| has an associated [=default sensor=]
and there is a corresponding [=sensor=] on the device, then
1. associate |sensor_instance| with [=default sensor=].
1. Return `true`.
1. let |e| be the result of [=created|creating=] a
"{{NotReadableError!!exception}}" {{DOMException}}.
<!-- Note: user agents may decide to use a
"{{NotAllowedError!!exception}}" {{DOMException}},
here instead, possibly after a random but bounded delay,
to simulate the user denying the permission request,
rather than giving away physical characteristics of the device
which might be used for fingerprinting or profiling.
This would of course prevent the developer from
correctly diagnosing the reason for the rejection
and might lead to confusing instructions to the user,
but it is a tradeoff some User Agent might choose to make. -->
1. Invoke the [=Handle Errors=] abstract operation,
passing it |e| and |sensor_instance| as arguments.
1. Return `false`.
</div>
<h3 dfn>Register a Sensor Object</h3>
<div algorithm="register a sensor object">
: 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 |latest_reading| be |sensor|'s associated [=latest reading=] [ordered map|map].
1. If |current_reading|["timestamp"] is not `null` and |sensor_instance|'s state is still <a enum-value>"activating"</a>, then
1. invoke the [=Update Observers=] operation, passing it
|sensor_instance| and |current_reading| as arguments. -->
</div>
<h3 dfn>Unregister a Sensor</h3>
<div algorithm="unregister a sensor">
: 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. Unset the [=periodic reporting mode flag=].
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 [=sensor readings|readings=].
1. Abort these steps.
1. Invoke the [=Set Sensor Settings=] abstract operation,
passing it |sensor| as argument.
</div>
<h3 dfn>Revoke sensor permission</h3>
<div algorithm="revoke sensor permission">
: input
:: |sensor|, a [=sensor=].
: output
:: None
1. let |activated_sensors| be |sensor|'s associated [=ordered set|set=] of [=activated Sensor objects=].
1. [=set/For each=] |s| of |activated_sensors|,
1. [=set/Remove=] |s| from |activated_sensors|.
1. let |e| be the result of [=created|creating=]
a "{{NotAllowedError!!exception}}" {{DOMException}}.
1. Invoke the [=Handle Errors=] abstract operation,
passing it |e| and |s| as arguments.
1. Unset |sensor|'s [=periodic reporting mode flag=].
1. Set |sensor|'s [=current polling frequency=] to `null`.
1. Update the user-agent-specific way in which [=sensor readings=] are obtained from |sensor|
to no longer provide [=sensor readings|readings=].
</div>
<h3 dfn>Set Sensor Settings</h3>
<div algorithm="set sensor settings">
: input
:: |sensor|, a [=sensor=].
: output
:: None
1. Let |settings_changed| be `false`.
1. Let |is_periodic| be the result of invoking
the [=Is Current Reporting Mode Periodic=] abstract operation,
with |sensor| as argument.
1. If |is_periodic| is `false` and the [=periodic reporting mode flag=] is set, then
1. set |settings_changed| to `true`.
1. Unset the [=periodic reporting mode flag=].
1. Otherwise if |is_periodic| is `true` and the [=periodic reporting mode flag=] is unset, then
1. set |settings_changed| to `true`.
1. Set the [=periodic reporting mode flag=].
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.
Issue: This abstract operation needs to return |settings_changed|
instead of the [=Observe a Sensor=] abstract operation itself.
</div>
<h3 dfn>Observe a Sensor</h3>
<div algorithm="observe a sensor">
Issue: This needs to be refactored in an abstract operation
that has access to the {{Sensor}} instance |sensor_instance|
that just got started.
: input
:: |sensor|, a [=sensor=].
: output
:: None
<!-- 1. Immediately invoke the [=Update latest reading=] abstract operation
to report fresh [=sensor readings|readings=],
passing it |sensor| and [=latest reading=]["timestamp"] as arguments. -->
1. If |sensor|'s |latest reading|["timestamp"] is not `null`,
invoke the [=update observers=] abstract operation passing it |sensor_instance|
and |latest reading|["timestamp"] as arguments.
1. Otherwise, poll |sensor| immediately.
Issue: How do we handle this for [=sensors=] that
do not provide values immediately?
Fire a dedicated event to signal brokenness?
1. If |sensor|'s [=periodic reporting mode flag=] is set,
1. let |frequency| be the [=current polling frequency=],
capped by the upper and lower bounds of the underlying hardware.
Issue: Should this max polling frequency be reflected in the {{Sensor}} interface?
E.g. Through a dedicated attribute?
Issue: Does the max polling frequency affect the reporting frequency?
If so, should we advise the developer of this issue?
E.g. via a dedicated event?