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/timer/timer.h"
10 #include "content/public/renderer/platform_event_observer.h"
14 template <typename ListenerType
>
15 class CONTENT_EXPORT DeviceSensorEventPump
16 : NON_EXPORTED_BASE(public PlatformEventObserver
<ListenerType
>) {
18 // Default delay between subsequent firing of events.
19 static const int kDefaultPumpDelayMillis
= 50;
21 // PlatformEventObserver
22 virtual void Start(blink::WebPlatformEventListener
* listener
) OVERRIDE
{
23 DVLOG(2) << "requested start";
25 if (state_
!= STOPPED
)
28 DCHECK(!timer_
.IsRunning());
30 PlatformEventObserver
<ListenerType
>::Start(listener
);
31 state_
= PENDING_START
;
34 virtual void Stop() OVERRIDE
{
37 if (state_
== STOPPED
)
40 DCHECK((state_
== PENDING_START
&& !timer_
.IsRunning()) ||
41 (state_
== RUNNING
&& timer_
.IsRunning()));
43 if (timer_
.IsRunning())
45 PlatformEventObserver
<ListenerType
>::Stop();
50 explicit DeviceSensorEventPump(RenderThread
* thread
)
51 : PlatformEventObserver
<ListenerType
>(thread
),
52 pump_delay_millis_(kDefaultPumpDelayMillis
),
56 virtual ~DeviceSensorEventPump() {
59 // The pump is a tri-state automaton with allowed transitions as follows:
60 // STOPPED -> PENDING_START
61 // PENDING_START -> RUNNING
62 // PENDING_START -> STOPPED
70 void OnDidStart(base::SharedMemoryHandle handle
) {
71 DVLOG(2) << "did start sensor event pump";
73 if (state_
!= PENDING_START
)
76 DCHECK(!timer_
.IsRunning());
78 if (InitializeReader(handle
)) {
79 timer_
.Start(FROM_HERE
,
80 base::TimeDelta::FromMilliseconds(pump_delay_millis_
),
81 this, &DeviceSensorEventPump::FireEvent
);
86 virtual void FireEvent() = 0;
87 virtual bool InitializeReader(base::SharedMemoryHandle handle
) = 0;
89 int pump_delay_millis_
;
91 base::RepeatingTimer
<DeviceSensorEventPump
> timer_
;
93 DISALLOW_COPY_AND_ASSIGN(DeviceSensorEventPump
);
96 } // namespace content
98 #endif // CONTENT_RENDERER_DEVICE_SENSORS_DEVICE_SENSOR_EVENT_PUMP_H_