1 // Copyright 2023 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 15 #include "pw_thread/sleep.h" 16 17 #include <algorithm> 18 #include <limits> 19 20 #include "pw_assert/check.h" 21 #include "pw_chrono/system_clock.h" 22 #include "pw_chrono_zephyr/system_clock_constants.h" 23 24 using pw::chrono::SystemClock; 25 26 namespace pw::this_thread { 27 sleep_until(SystemClock::time_point wakeup_time)28void sleep_until(SystemClock::time_point wakeup_time) { 29 SystemClock::time_point now = chrono::SystemClock::now(); 30 31 // Check if the expiration deadline has already passed, yield. 32 if (wakeup_time <= now) { 33 k_yield(); 34 return; 35 } 36 37 // The maximum amount of time we should sleep for in a single command. 38 constexpr chrono::SystemClock::duration kMaxTimeoutMinusOne = 39 pw::chrono::zephyr::kMaxTimeout - SystemClock::duration(1); 40 41 while (now < wakeup_time) { 42 // Sleep either the full remaining duration or the maximum timout 43 k_sleep(Z_TIMEOUT_TICKS( 44 std::min((wakeup_time - now).count(), kMaxTimeoutMinusOne.count()))); 45 46 // Check how much time has passed, the scheduler can wake us up early. 47 now = SystemClock::now(); 48 } 49 } 50 51 } // namespace pw::this_thread 52