How to use ControlledTimer method of Microsoft.Coyote.Samples.CoffeeMachineTasks.ControlledTimer class

Best Coyote code snippet using Microsoft.Coyote.Samples.CoffeeMachineTasks.ControlledTimer.ControlledTimer

MockSensors.cs

Source:MockSensors.cs Github

copy

Full Screen

...70 private double PortaFilterCoffeeLevel;71 private bool ShotButton;72 private readonly bool DoorOpen;73 private readonly Generator RandomGenerator;74 private ControlledTimer WaterHeaterTimer;75 private ControlledTimer CoffeeLevelTimer;76 private ControlledTimer ShotTimer;77 public bool RunSlowly;78 private readonly LogWriter Log = LogWriter.Instance;79 public event EventHandler<double> WaterTemperatureChanged;80 public event EventHandler<bool> WaterHot;81 public event EventHandler<double> PortaFilterCoffeeLevelChanged;82 public event EventHandler<bool> HopperEmpty;83 public event EventHandler<bool> ShotComplete;84 public event EventHandler<bool> WaterEmpty;85 public MockSensors(bool runSlowly)86 {87 this.Lock = new AsyncLock();88 this.RunSlowly = runSlowly;89 this.RandomGenerator = Generator.Create();90 // The use of randomness here makes this mock a more interesting test as it will91 // make sure the coffee machine handles these values correctly.92 this.WaterLevel = this.RandomGenerator.NextInteger(100);93 this.HopperLevel = this.RandomGenerator.NextInteger(100);94 this.WaterHeaterButton = false;95 this.WaterTemperature = this.RandomGenerator.NextInteger(50) + 30;96 this.GrinderButton = false;97 this.PortaFilterCoffeeLevel = 0;98 this.ShotButton = false;99 this.DoorOpen = this.RandomGenerator.NextInteger(5) is 0;100 this.WaterHeaterTimer = new ControlledTimer("WaterHeaterTimer", TimeSpan.FromSeconds(0.1), this.MonitorWaterTemperature);101 }102 public Task TerminateAsync()103 {104 StopTimer(this.WaterHeaterTimer);105 StopTimer(this.CoffeeLevelTimer);106 StopTimer(this.ShotTimer);107 return Task.CompletedTask;108 }109 public async Task<bool> GetPowerSwitchAsync()110 {111 // to model real async behavior we insert a delay here.112 await Task.Delay(1);113 return this.PowerOn;114 }115 public async Task<double> GetWaterLevelAsync()116 {117 await Task.Delay(1);118 return this.WaterLevel;119 }120 public async Task<double> GetHopperLevelAsync()121 {122 await Task.Delay(1);123 return this.HopperLevel;124 }125 public async Task<double> GetWaterTemperatureAsync()126 {127 await Task.Delay(1);128 return this.WaterTemperature;129 }130 public async Task<double> GetPortaFilterCoffeeLevelAsync()131 {132 await Task.Delay(1);133 return this.PortaFilterCoffeeLevel;134 }135 public async Task<bool> GetReadDoorOpenAsync()136 {137 await Task.Delay(1);138 return this.DoorOpen;139 }140 public async Task SetPowerSwitchAsync(bool value)141 {142 await Task.Delay(1);143 // NOTE: you should not use C# locks that interact with Tasks (like Task.Run) because144 // it can result in deadlocks, instead use the Coyote AsyncLock as follows.145 using (await this.Lock.AcquireAsync())146 {147 this.PowerOn = value;148 if (!this.PowerOn)149 {150 // Master power override then also turns everything else off for safety!151 this.WaterHeaterButton = false;152 this.GrinderButton = false;153 this.ShotButton = false;154 StopTimer(this.CoffeeLevelTimer);155 this.CoffeeLevelTimer = null;156 StopTimer(this.ShotTimer);157 this.ShotTimer = null;158 }159 }160 }161 public async Task SetWaterHeaterButtonAsync(bool value)162 {163 await Task.Delay(1);164 using (await this.Lock.AcquireAsync())165 {166 this.WaterHeaterButton = value;167 // Should never turn on the heater when there is no water to heat.168 if (this.WaterHeaterButton && this.WaterLevel <= 0)169 {170 Specification.Assert(false, "Please do not turn on heater if there is no water");171 }172 }173 }174 public async Task SetGrinderButtonAsync(bool value)175 {176 await Task.Delay(1);177 await this.OnGrinderButtonChanged(value);178 }179 private async Task OnGrinderButtonChanged(bool value)180 {181 using (await this.Lock.AcquireAsync())182 {183 this.GrinderButton = value;184 if (this.GrinderButton)185 {186 // Should never turn on the grinder when there is no coffee to grind.187 if (this.HopperLevel <= 0)188 {189 Specification.Assert(false, "Please do not turn on grinder if there are no beans in the hopper");190 }191 }192 if (value && this.CoffeeLevelTimer == null)193 {194 // Start monitoring the coffee level.195 this.CoffeeLevelTimer = new ControlledTimer("CoffeeLevelTimer", TimeSpan.FromSeconds(0.1), this.MonitorGrinder);196 }197 else if (!value && this.CoffeeLevelTimer != null)198 {199 StopTimer(this.CoffeeLevelTimer);200 this.CoffeeLevelTimer = null;201 }202 }203 }204 public async Task SetShotButtonAsync(bool value)205 {206 await Task.Delay(1);207 using (await this.Lock.AcquireAsync())208 {209 this.ShotButton = value;210 if (this.ShotButton)211 {212 // Should never turn on the make shots button when there is no water.213 if (this.WaterLevel <= 0)214 {215 Specification.Assert(false, "Please do not turn on shot maker if there is no water");216 }217 }218 if (value && this.ShotTimer == null)219 {220 // Start monitoring the coffee level.221 this.ShotTimer = new ControlledTimer("ShotTimer", TimeSpan.FromSeconds(1), this.MonitorShot);222 }223 else if (!value && this.ShotTimer != null)224 {225 StopTimer(this.ShotTimer);226 this.ShotTimer = null;227 }228 }229 }230 public async Task SetDumpGrindsButtonAsync(bool value)231 {232 await Task.Delay(1);233 if (value)234 {235 // This is a toggle button, in no time grinds are dumped (just for simplicity).236 this.PortaFilterCoffeeLevel = 0;237 }238 }239 private void MonitorWaterTemperature()240 {241 double temp = this.WaterTemperature;242 if (this.WaterHeaterButton)243 {244 // Note: when running in production mode we run forever, and it is fun to245 // watch the water heat up and cool down. But in test mode this creates too246 // many async events to explore which makes the test slow. So in test mode247 // we short circuit this process and jump straight to the boundary conditions.248 if (!this.RunSlowly && temp < 99)249 {250 temp = 99;251 }252 // Every time interval the temperature increases by 10 degrees up to 100 degrees.253 if (temp < 100)254 {255 temp = (int)temp + 10;256 this.WaterTemperature = temp;257 this.WaterTemperatureChanged?.Invoke(this, this.WaterTemperature);258 }259 else260 {261 this.WaterHot?.Invoke(this, true);262 }263 }264 else265 {266 // Then it is cooling down to room temperature, more slowly.267 if (temp > 70)268 {269 temp -= 0.1;270 this.WaterTemperature = temp;271 }272 }273 // Start another callback.274 this.WaterHeaterTimer = new ControlledTimer("WaterHeaterTimer", TimeSpan.FromSeconds(0.1), this.MonitorWaterTemperature);275 }276 private void MonitorGrinder()277 {278 // Every time interval the porta filter fills 10%. When it's full the grinder turns off279 // automatically, unless the hopper is empty in which case grinding does nothing!280 Task.Run(async () =>281 {282 bool changed = false;283 bool notifyEmpty = false;284 bool turnOffGrinder = false;285 using (await this.Lock.AcquireAsync())286 {287 double hopperLevel = this.HopperLevel;288 if (hopperLevel > 0)289 {290 double level = this.PortaFilterCoffeeLevel;291 // Note: when running in production mode we run in real time, and it is fun292 // to watch the porta filter filling up. But in test mode this creates too293 // many async events to explore which makes the test slow. So in test mode294 // we short circuit this process and jump straight to the boundary conditions.295 if (!this.RunSlowly && level < 99)296 {297 hopperLevel -= 98 - (int)level;298 this.Log.WriteLine("### HopperLevel: RunSlowly = {0}, level = {1}", this.RunSlowly, hopperLevel);299 level = 99;300 }301 if (level < 100)302 {303 level += 10;304 this.PortaFilterCoffeeLevel = level;305 changed = true;306 if (level >= 100)307 {308 turnOffGrinder = true;309 }310 }311 // And the hopper level drops by 0.1 percent.312 hopperLevel -= 1;313 this.HopperLevel = hopperLevel;314 }315 if (this.HopperLevel <= 0)316 {317 hopperLevel = 0;318 notifyEmpty = true;319 StopTimer(this.CoffeeLevelTimer);320 this.CoffeeLevelTimer = null;321 }322 }323 if (turnOffGrinder)324 {325 // Turning off the grinder is automatic.326 await this.OnGrinderButtonChanged(false);327 }328 // Event callbacks should not be inside the lock otherwise we could get deadlocks.329 if (notifyEmpty && this.HopperEmpty != null)330 {331 this.HopperEmpty(this, true);332 }333 if (changed && this.PortaFilterCoffeeLevelChanged != null)334 {335 this.PortaFilterCoffeeLevelChanged(this, this.PortaFilterCoffeeLevel);336 }337 if (this.HopperLevel <= 0 && this.HopperEmpty != null)338 {339 this.HopperEmpty(this, true);340 }341 // Start another callback.342 this.CoffeeLevelTimer = new ControlledTimer("WaterHeaterTimer", TimeSpan.FromSeconds(0.1), this.MonitorGrinder);343 });344 }345 private void MonitorShot()346 {347 Task.Run(async () =>348 {349 // One second of running water completes the shot.350 using (await this.Lock.AcquireAsync())351 {352 this.WaterLevel -= 1;353 // Turn off the water.354 this.ShotButton = false;355 this.ShotTimer = null;356 }357 // Event callbacks should not be inside the lock otherwise we could get deadlocks.358 if (this.WaterLevel > 0)359 {360 this.ShotComplete?.Invoke(this, true);361 }362 else363 {364 this.WaterEmpty?.Invoke(this, true);365 }366 });367 }368 private static void StopTimer(ControlledTimer timer)369 {370 if (timer != null)371 {372 timer.Stop();373 }374 }375 }376}...

Full Screen

Full Screen

FailoverDriver.cs

Source:FailoverDriver.cs Github

copy

Full Screen

...25 private ICoffeeMachine CoffeeMachine;26 private bool IsInitialized;27 private bool RunForever;28 private int Iterations;29 private ControlledTimer HaltTimer;30 private readonly Generator RandomGenerator;31 private readonly LogWriter Log = LogWriter.Instance;32 public FailoverDriver(bool runForever)33 {34 this.RunForever = runForever;35 this.RandomGenerator = Generator.Create();36 this.Sensors = new MockSensors(runForever);37 }38 public async Task RunTest()39 {40 bool halted = true;41 while (this.RunForever || this.Iterations <= 1)42 {43 this.Log.WriteLine("#################################################################");44 // Create a new CoffeeMachine instance.45 string error = null;46 if (halted)47 {48 this.Log.WriteLine("starting new CoffeeMachine iteration {0}.", this.Iterations);49 this.IsInitialized = false;50 this.CoffeeMachine = new CoffeeMachine();51 halted = false;52 this.IsInitialized = await this.CoffeeMachine.InitializeAsync(this.Sensors);53 if (!this.IsInitialized)54 {55 error = "init failed";56 }57 }58 if (error == null)59 {60 // Setup a timer to randomly kill the coffee machine. When the timer fires we61 // will restart the coffee machine and this is testing that the machine can62 // recover gracefully when that happens.63 this.HaltTimer = new ControlledTimer("HaltTimer", TimeSpan.FromSeconds(this.RandomGenerator.NextInteger(7) + 1), new Action(this.OnStopTest));64 // Request a coffee!65 var shots = this.RandomGenerator.NextInteger(3) + 1;66 error = await this.CoffeeMachine.MakeCoffeeAsync(shots);67 }68 if (string.Compare(error, "<halted>", StringComparison.OrdinalIgnoreCase) == 0)69 {70 // Then OnStopTest did it's thing, so it is time to create new coffee machine.71 this.Log.WriteWarning("CoffeeMachine is halted.");72 halted = true;73 }74 else if (!string.IsNullOrEmpty(error))75 {76 this.Log.WriteWarning("CoffeeMachine reported an error.");77 // No point trying to make more coffee....

Full Screen

Full Screen

ControlledTimer.cs

Source:ControlledTimer.cs Github

copy

Full Screen

...8 /// <summary>9 /// This class provides a Timer that is similar to how the Actor model timers work that10 /// has delays that can be controlled by Coyote tester.11 /// </summary>12 internal class ControlledTimer13 {14 private readonly CancellationTokenSource Source = new CancellationTokenSource();15 private readonly TimeSpan StartDelay;16 private readonly TimeSpan? Interval;17 private readonly Action Handler;18 private bool Stopped;19 private readonly string Name;20 public ControlledTimer(string name, TimeSpan startDelay, TimeSpan interval, Action handler)21 {22 this.Name = name;23 this.StartDelay = startDelay;24 this.Interval = interval;25 this.Handler = handler;26 this.StartTimer(startDelay);27 }28 public ControlledTimer(string name, TimeSpan dueTime, Action handler)29 {30 this.Name = name;31 this.StartDelay = dueTime;32 this.Handler = handler;33 this.StartTimer(dueTime);34 }35 private void StartTimer(TimeSpan dueTime)36 {37 Task.Run(async () =>38 {39 await Task.Delay(dueTime, this.Source.Token);40 this.OnTick();41 });42 }...

Full Screen

Full Screen

ControlledTimer

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using Microsoft.Coyote;4using Microsoft.Coyote.Samples.CoffeeMachineTasks;5using Microsoft.Coyote.Tasks;6{7 {8 private ControlledTimer timer = new ControlledTimer();9 private int waterLevel = 0;10 private int beansLevel = 0;11 private bool isOn = false;12 public async Task RunAsync()13 {14 while (true)15 {16 var e = await ReceiveEventAsync();17 switch (e)18 {19 this.isOn = true;20 break;21 this.isOn = false;22 break;23 this.waterLevel += addWater.Amount;24 break;25 this.beansLevel += addBeans.Amount;26 break;27 if (this.waterLevel < 10 || this.beansLevel < 10)28 {29 break;30 }31 this.waterLevel -= 10;32 this.beansLevel -= 10;33 await this.timer.ControlledDelayAsync(TimeSpan.FromSeconds(10));34 break;35 }36 }37 }38 private async Task<object> ReceiveEventAsync()39 {40 await Task.CompletedTask;41 return null;42 }43 }44}45using System;46using System.Threading.Tasks;47using Microsoft.Coyote;48using Microsoft.Coyote.Samples.CoffeeMachineTasks;49using Microsoft.Coyote.Tasks;50{51 {52 private ControlledTimer timer = new ControlledTimer();53 private int waterLevel = 0;54 private int beansLevel = 0;55 private bool isOn = false;56 public async Task RunAsync()57 {58 while (true)59 {60 var e = await ReceiveEventAsync();61 switch (e)62 {63 this.isOn = true;64 break;65 this.isOn = false;66 break;67 this.waterLevel += addWater.Amount;68 break;

Full Screen

Full Screen

ControlledTimer

Using AI Code Generation

copy

Full Screen

1using System.Threading.Tasks;2using Microsoft.Coyote;3using Microsoft.Coyote.Tasks;4{5 {6 public static async Task Main(string[] args)7 {8 var config = Configuration.Create();9 config.MaxSchedulingSteps = 100000;10 config.EnableCycleDetection = true;11 config.EnableDataRaceDetection = true;12 config.EnableIntegerOverflowChecks = true;13 config.EnableBuggyWaitOperationsChecks = true;14 config.EnableDeadlockDetection = true;15 config.EnableOperationCanceledExceptionSupport = true;16 config.EnableObjectDisposedExceptionSupport = true;17 config.EnableTaskCanceledExceptionSupport = true;

Full Screen

Full Screen

ControlledTimer

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using Microsoft.Coyote.Samples.CoffeeMachineTasks;4{5 {6 static async Task Main(string[] args)7 {8 Console.WriteLine("Hello World!");9 var timer = new ControlledTimer();10 while (true)11 {12 Console.WriteLine("Waiting for 5 seconds");13 await timer.DelayAsync(5000);14 Console.WriteLine("5 seconds elapsed");15 }16 }17 }18}

Full Screen

Full Screen

ControlledTimer

Using AI Code Generation

copy

Full Screen

1 using System;2 using System.Threading.Tasks;3 using Microsoft.Coyote.Samples.CoffeeMachineTasks;4 {5 {6 public ControlledTimer()7 {8 }9 public static Task Delay(TimeSpan delay)10 {11 return Task.Delay(delay);12 }13 }14 }15 using System;16 using System.Threading.Tasks;17 using Microsoft.Coyote.Samples.CoffeeMachineTasks;18 {19 {20 public static async Task Main()21 {22 Console.WriteLine("Press any key to start the timer.");23 Console.ReadKey();24 await ControlledTimer.Delay(TimeSpan.FromSeconds(5));25 Console.WriteLine("5 seconds have elapsed.");26 }27 }28 }29 using System;30 using System.Threading.Tasks;31 using Microsoft.Coyote;32 using Microsoft.Coyote.Samples.CoffeeMachineTasks;33 {34 {35 public static async Task Main()36 {37 Console.WriteLine("Press any key to start the timer.");38 Console.ReadKey();39 await ControlledTimer.Delay(TimeSpan.FromSeconds(5));40 Console.WriteLine("5 seconds have elapsed.");41 }42 }43 }44In this example, the test is executed in two phases: (1) the first phase executes the program in a controlled manner, and (2) the second phase executes the program in a non-deterministic manner. The first phase is executed by default, and the second phase is executed when the --non-deterministic flag is passed to the Coyote runtime. The following is the output of the test when the --non-deterministic flag is passed:

Full Screen

Full Screen

ControlledTimer

Using AI Code Generation

copy

Full Screen

1using Microsoft.Coyote.Samples.CoffeeMachineTasks;2using System;3using System.Threading;4using System.Threading.Tasks;5{6 {7 static void Main(string[] args)8 {9 Console.WriteLine("Hello World!");10 Console.WriteLine("Press enter to start");11 Console.ReadLine();12 ControlledTimer timer = new ControlledTimer();13 timer.StartTimer(10000);14 Console.WriteLine("Timer started");15 timer.WaitTimer();16 Console.WriteLine("Timer completed");17 Console.ReadLine();18 }19 }20}21using Microsoft.Coyote.Samples.CoffeeMachineTasks;22using System;23using System.Threading;24using System.Threading.Tasks;25{26 {27 static void Main(string[] args)28 {29 Console.WriteLine("Hello World!");30 Console.WriteLine("Press enter to start");31 Console.ReadLine();32 ControlledTimer timer = new ControlledTimer();33 timer.StartTimer(10000);34 Console.WriteLine("Timer started");35 timer.WaitTimer();36 Console.WriteLine("Timer completed");37 Console.ReadLine();38 }39 }40}41using Microsoft.Coyote.Samples.CoffeeMachineTasks;42using System;43using System.Threading;44using System.Threading.Tasks;45{46 {47 static void Main(string[] args)48 {49 Console.WriteLine("Hello World!");50 Console.WriteLine("Press enter to start");51 Console.ReadLine();52 ControlledTimer timer = new ControlledTimer();53 timer.StartTimer(10000);54 Console.WriteLine("Timer started");55 timer.WaitTimer();56 Console.WriteLine("Timer completed");57 Console.ReadLine();58 }59 }60}61using Microsoft.Coyote.Samples.CoffeeMachineTasks;62using System;63using System.Threading;64using System.Threading.Tasks;65{66 {67 static void Main(string[] args)68 {69 Console.WriteLine("Hello

Full Screen

Full Screen

ControlledTimer

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using Microsoft.Coyote;4using Microsoft.Coyote.Samples.CoffeeMachineTasks;5using Microsoft.Coyote.Tasks;6{7 {8 public static async Task Main()9 {10 using (var timer = new ControlledTimer(1))11 {12 timer.Start();13 await timer.WaitAsync();14 }15 }16 }17}18using System;19using System.Threading.Tasks;20using Microsoft.Coyote;21using Microsoft.Coyote.Samples.CoffeeMachineTasks;22using Microsoft.Coyote.Tasks;23{24 {25 public static async Task Main()26 {27 using (var timer = new ControlledTimer(1))28 {29 timer.Start();30 await timer.WaitAsync();31 }32 }33 }34}35using System;36using System.Threading.Tasks;37using Microsoft.Coyote;38using Microsoft.Coyote.Samples.CoffeeMachineTasks;39using Microsoft.Coyote.Tasks;40{41 {42 public static async Task Main()43 {44 using (var timer = new ControlledTimer(1))45 {46 timer.Start();47 await timer.WaitAsync();48 }49 }50 }51}52using System;53using System.Threading.Tasks;54using Microsoft.Coyote;

Full Screen

Full Screen

ControlledTimer

Using AI Code Generation

copy

Full Screen

1ControlledTimer timer = new ControlledTimer();2timer.Stop();3ControlledTimer timer = new ControlledTimer();4timer.Stop();5ControlledTimer timer = new ControlledTimer();6timer.Stop();7ControlledTimer timer = new ControlledTimer();8timer.Stop();9ControlledTimer timer = new ControlledTimer();10timer.Stop();11ControlledTimer timer = new ControlledTimer();12timer.Stop();13ControlledTimer timer = new ControlledTimer();14timer.Stop();15ControlledTimer timer = new ControlledTimer();16timer.Stop();17ControlledTimer timer = new ControlledTimer();

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Coyote automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful