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. 4 5 #ifndef CONTENT_RENDERER_DEVICE_SENSORS_DEVICE_SENSOR_EVENT_PUMP_H_ 6 #define CONTENT_RENDERER_DEVICE_SENSORS_DEVICE_SENSOR_EVENT_PUMP_H_ 7 8 #include "base/memory/shared_memory.h" 9 #include "base/timer/timer.h" 10 #include "content/public/renderer/platform_event_observer.h" 11 12 namespace content { 13 14 template <typename ListenerType> 15 class CONTENT_EXPORT DeviceSensorEventPump NON_EXPORTED_BASE(public PlatformEventObserver<ListenerType>)16 : NON_EXPORTED_BASE(public PlatformEventObserver<ListenerType>) { 17 public: 18 // Default delay between subsequent firing of events. 19 static const int kDefaultPumpDelayMillis = 50; 20 21 // PlatformEventObserver 22 virtual void Start(blink::WebPlatformEventListener* listener) OVERRIDE { 23 DVLOG(2) << "requested start"; 24 25 if (state_ != STOPPED) 26 return; 27 28 DCHECK(!timer_.IsRunning()); 29 30 PlatformEventObserver<ListenerType>::Start(listener); 31 state_ = PENDING_START; 32 } 33 34 virtual void Stop() OVERRIDE { 35 DVLOG(2) << "stop"; 36 37 if (state_ == STOPPED) 38 return; 39 40 DCHECK((state_ == PENDING_START && !timer_.IsRunning()) || 41 (state_ == RUNNING && timer_.IsRunning())); 42 43 if (timer_.IsRunning()) 44 timer_.Stop(); 45 PlatformEventObserver<ListenerType>::Stop(); 46 state_ = STOPPED; 47 } 48 49 protected: 50 explicit DeviceSensorEventPump(RenderThread* thread) 51 : PlatformEventObserver<ListenerType>(thread), 52 pump_delay_millis_(kDefaultPumpDelayMillis), 53 state_(STOPPED) { 54 } 55 56 virtual ~DeviceSensorEventPump() { 57 } 58 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 63 // RUNNING -> STOPPED 64 enum PumpState { 65 STOPPED, 66 RUNNING, 67 PENDING_START 68 }; 69 70 void OnDidStart(base::SharedMemoryHandle handle) { 71 DVLOG(2) << "did start sensor event pump"; 72 73 if (state_ != PENDING_START) 74 return; 75 76 DCHECK(!timer_.IsRunning()); 77 78 if (InitializeReader(handle)) { 79 timer_.Start(FROM_HERE, 80 base::TimeDelta::FromMilliseconds(pump_delay_millis_), 81 this, &DeviceSensorEventPump::FireEvent); 82 state_ = RUNNING; 83 } 84 } 85 86 virtual void FireEvent() = 0; 87 virtual bool InitializeReader(base::SharedMemoryHandle handle) = 0; 88 89 int pump_delay_millis_; 90 PumpState state_; 91 base::RepeatingTimer<DeviceSensorEventPump> timer_; 92 93 DISALLOW_COPY_AND_ASSIGN(DeviceSensorEventPump); 94 }; 95 96 } // namespace content 97 98 #endif // CONTENT_RENDERER_DEVICE_SENSORS_DEVICE_SENSOR_EVENT_PUMP_H_ 99