2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.automation.pwm.internal.handler.state;
15 import java.time.Instant;
16 import java.time.temporal.ChronoUnit;
17 import java.util.concurrent.ScheduledFuture;
18 import java.util.concurrent.TimeUnit;
20 import org.eclipse.jdt.annotation.NonNullByDefault;
21 import org.eclipse.jdt.annotation.Nullable;
24 * Active when, the PWM period ended with a duty cycle set to 100%.
26 * @author Fabian Wolter - Initial Contribution
29 public class DutycycleHundredState extends State {
30 private ScheduledFuture<?> periodTimer;
31 private @Nullable ScheduledFuture<?> offTimer;
32 private Instant enabledAt = Instant.now();
33 private boolean dutyCycleChanged;
35 public DutycycleHundredState(StateMachine context) {
40 periodTimer = scheduler.schedule(this::periodEnded, context.getPeriodMs(), TimeUnit.MILLISECONDS);
43 private void periodEnded() {
44 long dutycycleRounded = Math.round(context.getDutycycle());
46 if (!dutyCycleChanged && dutycycleRounded <= 0) {
47 nextState(AlwaysOffState::new);
48 } else if (!dutyCycleChanged && dutycycleRounded >= 100) {
49 nextState(AlwaysOnState::new);
51 nextState(OnState::new);
56 public void dutyCycleChanged() {
57 dutyCycleChanged = true;
59 long newOnTimeMs = calculateOnTimeMs(context.getDutycycle());
60 long elapsedMs = enabledAt.until(Instant.now(), ChronoUnit.MILLIS);
62 if (elapsedMs - newOnTimeMs > 0) {
65 ScheduledFuture<?> timer = offTimer;
69 offTimer = scheduler.schedule(() -> controlOutput(false), newOnTimeMs - elapsedMs, TimeUnit.MILLISECONDS);
74 protected void dutyCycleUpdated() {
79 public void dispose() {
80 periodTimer.cancel(false);
82 ScheduledFuture<?> timer = offTimer;