Washing Machine State Machine

Thx all contributing to this thread - helped me a lot during the last days.
There I had some confusions changing the state model for a slightly different case, I swapped to a different pattern of coding.
I put the priority to the states and then evaluating thresholds.
I know it’ s not so efficient and contains more lines - but maybe it could help somebody else…

val Number STATE_OFF = 0
val Number STATE_STANDBY = 1
val Number STATE_ACTIVE = 2
val Number STATE_FINISHED = 3

val Number THRESHOLD_OFF = 5
val Number THRESHOLD_STANDBY = 20
val Number THRESHOLD_ACTIVE = 30

var java.util.concurrent.locks.ReentrantLock finishLock  = new java.util.concurrent.locks.ReentrantLock()

rule "Washingmachine_StateMachine"
when
    Item WashingMachine_Consumption changed
then
	switch WashingMachine_OpState.state	{
		case STATE_OFF: {
			 	if (WashingMachine_Consumption.state > THRESHOLD_STANDBY){
					WashingMachine_OpState.postUpdate(STATE_STANDBY)
				} 
				if (WashingMachine_Consumption.state > THRESHOLD_ACTIVE) {
					WashingMachine_OpState.postUpdate(STATE_ACTIVE)
				}
			}			
		case STATE_STANDBY: {
				if (WashingMachine_Consumption.state > THRESHOLD_ACTIVE) {
					WashingMachine_OpState.postUpdate(STATE_ACTIVE)
				}
				if (WashingMachine_Consumption.state < THRESHOLD_STANDBY) {
					WashingMachine_OpState.postUpdate(STATE_OFF)
				}
			}			
		case STATE_ACTIVE: {
				if (WashingMachine_Consumption.state < THRESHOLD_ACTIVE)	{
					finishLock.lock()
		            try {
		                Thread::sleep(10000) // Debounce for 10 seconds
		                if (WashingMachine_Consumption.state < THRESHOLD_ACTIVE) {
		                	 WashingMachine_OpState.postUpdate(STATE_FINISHED)
		               	} 
		            } finally {
		                finishLock.unlock()
		            }
				}
			}				
		case STATE_FINISHED: {
				if (WashingMachine_Consumption.state < THRESHOLD_STANDBY){
					WashingMachine_OpState.postUpdate(STATE_OFF)
				} 
				if (WashingMachine_Consumption.state > THRESHOLD_ACTIVE) {
					WashingMachine_OpState.postUpdate(STATE_ACTIVE)
				}	
			}		
		default: WashingMachine_OpState.postUpdate(STATE_OFF)
	}
end

I’m interested to hear your opinions…

5 Likes