1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef CONTENT_RENDERER_DEVICE_SENSORS_DEVICE_SENSOR_EVENT_PUMP_H_
6 #define CONTENT_RENDERER_DEVICE_SENSORS_DEVICE_SENSOR_EVENT_PUMP_H_
8 #include "base/memory/shared_memory.h"
9 #include "base/time/time.h"
10 #include "base/timer/timer.h"
11 #include "content/public/renderer/platform_event_observer.h"
15 template <typename ListenerType
>
16 class CONTENT_EXPORT DeviceSensorEventPump
17 : NON_EXPORTED_BASE(public PlatformEventObserver
<ListenerType
>) {
19 // Default rate for firing events.
20 static const int kDefaultPumpFrequencyHz
= 60;
21 static const int kDefaultPumpDelayMicroseconds
=
22 base::Time::kMicrosecondsPerSecond
/ kDefaultPumpFrequencyHz
;
24 // PlatformEventObserver
25 void Start(blink::WebPlatformEventListener
* listener
) override
{
26 DVLOG(2) << "requested start";
28 if (state_
!= STOPPED
)
31 DCHECK(!timer_
.IsRunning());
33 PlatformEventObserver
<ListenerType
>::Start(listener
);
34 state_
= PENDING_START
;
37 void Stop() override
{
40 if (state_
== STOPPED
)
43 DCHECK((state_
== PENDING_START
&& !timer_
.IsRunning()) ||
44 (state_
== RUNNING
&& timer_
.IsRunning()));
46 if (timer_
.IsRunning())
48 PlatformEventObserver
<ListenerType
>::Stop();
53 explicit DeviceSensorEventPump(RenderThread
* thread
)
54 : PlatformEventObserver
<ListenerType
>(thread
),
55 pump_delay_microseconds_(kDefaultPumpDelayMicroseconds
),
58 ~DeviceSensorEventPump() override
{
59 PlatformEventObserver
<ListenerType
>::StopIfObserving();
62 // The pump is a tri-state automaton with allowed transitions as follows:
63 // STOPPED -> PENDING_START
64 // PENDING_START -> RUNNING
65 // PENDING_START -> STOPPED
73 void OnDidStart(base::SharedMemoryHandle handle
) {
74 DVLOG(2) << "did start sensor event pump";
76 if (state_
!= PENDING_START
)
79 DCHECK(!timer_
.IsRunning());
81 if (InitializeReader(handle
)) {
82 timer_
.Start(FROM_HERE
,
83 base::TimeDelta::FromMicroseconds(pump_delay_microseconds_
),
85 &DeviceSensorEventPump::FireEvent
);
90 virtual void FireEvent() = 0;
91 virtual bool InitializeReader(base::SharedMemoryHandle handle
) = 0;
93 int pump_delay_microseconds_
;
95 base::RepeatingTimer
<DeviceSensorEventPump
> timer_
;
97 DISALLOW_COPY_AND_ASSIGN(DeviceSensorEventPump
);
100 } // namespace content
102 #endif // CONTENT_RENDERER_DEVICE_SENSORS_DEVICE_SENSOR_EVENT_PUMP_H_