1 // Copyright 2022 The Pigweed Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not 4 // use this file except in compliance with the License. You may obtain a copy of 5 // the License at 6 // 7 // https://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 // License for the specific language governing permissions and limitations under 13 // the License. 14 #pragma once 15 16 #include "pw_chrono/system_clock.h" 17 #include "pw_chrono/system_timer.h" 18 19 namespace pw::rpc::fuzz { 20 21 /// Represents a timer that invokes a callback on timeout. Once started, it will 22 /// invoke the callback after a provided duration unless it is restarted, 23 /// canceled, or destroyed. 24 class AlarmTimer { 25 public: AlarmTimer(chrono::SystemTimer::ExpiryCallback && on_timeout)26 AlarmTimer(chrono::SystemTimer::ExpiryCallback&& on_timeout) 27 : timer_(std::move(on_timeout)) {} 28 timeout()29 chrono::SystemClock::duration timeout() const { return timeout_; } 30 31 /// "Arms" the timer. The callback will be invoked if `timeout` elapses 32 /// without a call to `Restart`, `Cancel`, or the destructor. Calling `Start` 33 /// again restarts the timer, possibly with a different `timeout` value. Start(chrono::SystemClock::duration timeout)34 void Start(chrono::SystemClock::duration timeout) { 35 timeout_ = timeout; 36 Restart(); 37 } 38 39 /// Restarts the timer. This is equivalent to calling `Start` with the same 40 /// `timeout` as passed previously. Does nothing if `Start` has not been 41 /// called. Restart()42 void Restart() { 43 Cancel(); 44 timer_.InvokeAfter(timeout_); 45 } 46 47 /// "Disarms" the timer. The callback will not be invoked unless `Start` is 48 /// called again. Does nothing if `Start` has not been called. Cancel()49 void Cancel() { timer_.Cancel(); } 50 51 private: 52 chrono::SystemTimer timer_; 53 chrono::SystemClock::duration timeout_; 54 }; 55 56 } // namespace pw::rpc::fuzz 57