Best Coyote code snippet using Microsoft.Coyote.Samples.CoffeeMachineTasks.LivenessMonitor
CoffeeMachine.cs
Source:CoffeeMachine.cs  
...72            if (this.Halted)73            {74                return "Ignoring MakeCoffeeAsync on halted Coffee machine";75            }76            Specification.Monitor<LivenessMonitor>(new LivenessMonitor.BusyEvent());77            if (!this.RefillRequired && !this.Halted)78            {79                // Make sure water is hot enough.80                await this.StartHeatingWater();81            }82            this.Log.WriteLine($"Coffee requested, shots={shots}");83            this.ShotsRequested = shots;84            // Grind beans until porta filter is full. Turn on shot button for desired time dump the85            // grinds, while checking for error conditions, e.g. out of water or coffee beans.86            if (!this.RefillRequired && !this.Halted)87            {88                await this.GrindBeans();89            }90            if (!this.RefillRequired && !this.Halted)91            {92                await this.MakeShotsAsync();93            }94            await this.CleanupAsync();95            if (this.Halted)96            {97                return "<halted>";98            }99            return this.Error;100        }101        public async Task CheckSensors()102        {103            this.Log.WriteLine("checking initial state of sensors...");104            // When this state machine starts it has to figure out the state of the sensors.105            if (!await this.Sensors.GetPowerSwitchAsync())106            {107                // Coffee machine was off, so this is the easy case, simply turn it on!108                await this.Sensors.SetPowerSwitchAsync(true);109            }110            // Make sure grinder, shot maker and water heater are off.111            await this.Sensors.SetGrinderButtonAsync(false);112            await this.Sensors.SetShotButtonAsync(false);113            await this.Sensors.SetWaterHeaterButtonAsync(false);114            // Need to check water and hopper levels and if the porta filter115            // has coffee in it we need to dump those grinds.116            await this.CheckWaterLevelAsync();117            await this.CheckHopperLevelAsync();118            await this.CheckPortaFilterCoffeeLevelAsync();119            await this.CheckDoorOpenAsync();120        }121        private async Task CheckWaterLevelAsync()122        {123            this.WaterLevel = await this.Sensors.GetWaterLevelAsync();124            this.Log.WriteLine("Water level is {0} %", (int)this.WaterLevel.Value);125            if ((int)this.WaterLevel.Value <= 0)126            {127                this.OnRefillRequired("is out of water");128            }129        }130        private async Task CheckHopperLevelAsync()131        {132            this.HopperLevel = await this.Sensors.GetHopperLevelAsync();133            this.Log.WriteLine("Hopper level is {0} %", (int)this.HopperLevel.Value);134            if ((int)this.HopperLevel.Value == 0)135            {136                this.OnRefillRequired("out of coffee beans");137            }138        }139        private async Task CheckPortaFilterCoffeeLevelAsync()140        {141            this.PortaFilterCoffeeLevel = await this.Sensors.GetPortaFilterCoffeeLevelAsync();142            if (this.PortaFilterCoffeeLevel > 0)143            {144                // Dump these grinds because they could be old, we have no idea how long145                // the coffee machine was off (no real time clock sensor).146                this.Log.WriteLine("Dumping old smelly grinds!");147                await this.Sensors.SetDumpGrindsButtonAsync(true);148            }149        }150        private async Task CheckDoorOpenAsync()151        {152            this.DoorOpen = await this.Sensors.GetReadDoorOpenAsync();153            if (this.DoorOpen.Value != false)154            {155                this.Log.WriteLine("Cannot safely operate coffee machine with the door open!");156                this.OnError();157            }158        }159        private async Task StartHeatingWater()160        {161            if (!this.Halted)162            {163                // Start heater and keep monitoring the water temp till it reaches 100!164                this.Log.WriteLine("Warming the water to 100 degrees");165                Specification.Monitor<LivenessMonitor>(new LivenessMonitor.BusyEvent());166                await this.MonitorWaterTemperature();167            }168            else169            {170                this.Log.WriteLine("Ignoring StartHeatingWater on a Halted Coffee machine");171            }172        }173        private async Task OnWaterHot()174        {175            this.Log.WriteLine("Coffee machine water temperature is now 100");176            if (this.Heating)177            {178                this.Heating = false;179                // Turn off the heater so we don't overheat it!180                await this.Sensors.SetWaterHeaterButtonAsync(false);181                this.Log.WriteLine("Turning off the water heater");182            }183            this.OnReady();184        }185        private async Task MonitorWaterTemperature()186        {187            while (!this.IsBroken)188            {189                this.WaterTemperature = await this.Sensors.GetWaterTemperatureAsync();190                if (this.WaterTemperature.Value >= 100)191                {192                    await this.OnWaterHot();193                    break;194                }195                else196                {197                    if (!this.Heating)198                    {199                        this.Heating = true;200                        // Turn on the heater and wait for WaterHotEvent.201                        this.Log.WriteLine("Turning on the water heater");202                        await this.Sensors.SetWaterHeaterButtonAsync(true);203                    }204                }205                this.Log.WriteLine("Coffee machine is warming up ({0} degrees)...", this.WaterTemperature);206                await Task.Delay(TimeSpan.FromSeconds(0.1));207            }208        }209        private void OnReady()210        {211            Specification.Monitor<LivenessMonitor>(new LivenessMonitor.IdleEvent());212            this.Log.WriteLine("Coffee machine is ready to make coffee (green light is on)");213        }214        private async Task GrindBeans()215        {216            // Grind beans until porta filter is full.217            this.Log.WriteLine("Grinding beans...");218            // Turn on the grinder!219            await this.Sensors.SetGrinderButtonAsync(true);220            // We now receive a stream of PortaFilterCoffeeLevelChanged events so we keep monitoring221            // the porta filter till it is full, and the bean level in case we get empty.222            await this.MonitorPortaFilter();223        }224        private async Task MonitorPortaFilter()225        {226            while (this.PortaFilterCoffeeLevel < 100 && !this.RefillRequired && !this.IsBroken)227            {228                await Task.Delay(TimeSpan.FromSeconds(0.1));229            }230        }231        private async Task OnHopperEmpty()232        {233            await this.Sensors.SetGrinderButtonAsync(false);234            this.OnRefillRequired("out of coffee beans");235        }236        private Task MakeShotsAsync()237        {238            // Pour the shots.239            this.Log.WriteLine("Making shots...");240            // First we assume user placed a new cup in the machine, and so the shot count is zero.241            this.PreviousShotCount = 0;242            // Wait for shots to be completed.243            return this.MonitorShotsAsync();244        }245        private async Task MonitorShotsAsync()246        {247            try248            {249                while (!this.IsBroken)250                {251                    this.Log.WriteLine("Shot count is {0}", this.PreviousShotCount);252                    // So we can wait for async event to come back from the sensors.253                    var completion = new TaskCompletionSource<bool>();254                    this.ShotCompleteSource = completion;255                    // Request another shot!256                    await this.Sensors.SetShotButtonAsync(true);257                    if (!this.IsBroken)258                    {259                        await completion.Task;260                        if (!this.IsBroken)261                        {262                            this.PreviousShotCount++;263                            if (this.PreviousShotCount >= this.ShotsRequested && !this.IsBroken)264                            {265                                this.Log.WriteLine("{0} shots completed and {1} shots requested!", this.PreviousShotCount, this.ShotsRequested);266                                if (this.PreviousShotCount > this.ShotsRequested)267                                {268                                    Specification.Assert(false, "Made the wrong number of shots");269                                }270                                break;271                            }272                        }273                    }274                }275            }276            catch (OperationCanceledException)277            {278                // Cancelled.279            }280        }281        private Task CleanupAsync()282        {283            // Dump the grinds.284            this.Log.WriteLine("Dumping the grinds!");285            return this.Sensors.SetDumpGrindsButtonAsync(true);286        }287        private void OnRefillRequired(string message)288        {289            this.Error = message;290            this.RefillRequired = true;291            Specification.Monitor<LivenessMonitor>(new LivenessMonitor.IdleEvent());292            this.Log.WriteError(message);293        }294        private void OnError()295        {296            this.Error = "Coffee machine needs fixing!";297            Specification.Monitor<LivenessMonitor>(new LivenessMonitor.IdleEvent());298            this.Log.WriteError(this.Error);299        }300        public async Task TerminateAsync()301        {302            this.Halted = true;303            this.Log.WriteLine("Coffee Machine Terminating...");304            var sensors = this.Sensors;305            if (sensors != null)306            {307                await sensors.SetPowerSwitchAsync(false);308            }309            var src = this.ShotCompleteSource;310            if (src != null)311            {312                src.TrySetCanceled();313            }314            // Stop listening to the sensors.315            this.RegisterSensorEvents(false);316            Specification.Monitor<LivenessMonitor>(new LivenessMonitor.IdleEvent());317            this.Log.WriteWarning("#################################################################");318            this.Log.WriteWarning("# Coffee Machine Halted                                         #");319            this.Log.WriteWarning("#################################################################");320            this.Log.WriteLine(string.Empty);321        }322        private void RegisterSensorEvents(bool register)323        {324            if (register)325            {326                this.Sensors.HopperEmpty += this.OnHopperEmpty;327                this.Sensors.PortaFilterCoffeeLevelChanged += this.OnPortaFilterCoffeeLevelChanged;328                this.Sensors.ShotComplete += this.OnShotComplete;329                this.Sensors.WaterEmpty += this.OnWaterEmpty;330                this.Sensors.WaterHot += this.OnWaterHot;...Program.cs
Source:Program.cs  
...26        public static async Task Execute(ICoyoteRuntime runtime)27        {28            LogWriter.Initialize(runtime.Logger, RunForever);29            runtime.OnFailure += OnRuntimeFailure;30            Specification.RegisterMonitor<LivenessMonitor>();31            IFailoverDriver driver = new FailoverDriver(RunForever);32            await driver.RunTest();33        }34    }35}...LivenessMonitor.cs
Source:LivenessMonitor.cs  
...6    /// <summary>7    /// This monitors the coffee machine to make sure it always finishes the job,8    /// either by making the requested coffee or by requesting a refill.9    /// </summary>10    internal class LivenessMonitor : Monitor11    {12        public class BusyEvent : Event { }13        public class IdleEvent : Event { }14        [Start]15        [Cold]16        [OnEventGotoState(typeof(BusyEvent), typeof(Busy))]17        [IgnoreEvents(typeof(IdleEvent))]18        private class Idle : State { }19        [Hot]20        [OnEventGotoState(typeof(IdleEvent), typeof(Idle))]21        [IgnoreEvents(typeof(BusyEvent))]22        private class Busy : State { }23    }24}...LivenessMonitor
Using AI Code Generation
1using Microsoft.Coyote.Samples.CoffeeMachineTasks;2using Microsoft.Coyote.Samples.CoffeeMachineTasks;3using Microsoft.Coyote.Samples.CoffeeMachineTasks;4using Microsoft.Coyote.Samples.CoffeeMachineTasks;5using Microsoft.Coyote.Samples.CoffeeMachineTasks;6using Microsoft.Coyote.Samples.CoffeeMachineTasks;7using Microsoft.Coyote.Samples.CoffeeMachineTasks;8using Microsoft.Coyote.Samples.CoffeeMachineTasks;9using Microsoft.Coyote.Samples.CoffeeMachineTasks;10using Microsoft.Coyote.Samples.CoffeeMachineTasks;11using Microsoft.Coyote.Samples.CoffeeMachineTasks;12using Microsoft.Coyote.Samples.CoffeeMachineTasks;13using Microsoft.Coyote.Samples.CoffeeMachineTasks;14using Microsoft.Coyote.Samples.CoffeeMachineTasks;15using Microsoft.Coyote.Samples.CoffeeMachineTasks;LivenessMonitor
Using AI Code Generation
1using Microsoft.Coyote.Samples.CoffeeMachineTasks;2using Microsoft.Coyote.Samples.CoffeeMachineTasks;3using Microsoft.Coyote.Samples.CoffeeMachineTasks;4using Microsoft.Coyote.Samples.CoffeeMachineTasks;5using Microsoft.Coyote.Samples.CoffeeMachineTasks;6using Microsoft.Coyote.Samples.CoffeeMachineTasks;7using Microsoft.Coyote.Samples.CoffeeMachineTasks;8using Microsoft.Coyote.Samples.CoffeeMachineTasks;9using Microsoft.Coyote.Samples.CoffeeMachineTasks;10using Microsoft.Coyote.Samples.CoffeeMachineTasks;11using Microsoft.Coyote.Samples.CoffeeMachineTasks;12using Microsoft.Coyote.Samples.CoffeeMachineTasks;13using Microsoft.Coyote.Samples.CoffeeMachineTasks;14using Microsoft.Coyote.Samples.CoffeeMachineTasks;15using Microsoft.Coyote.Samples.CoffeeMachineTasks;LivenessMonitor
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using Microsoft.Coyote;4using Microsoft.Coyote.Samples.CoffeeMachineTasks;5using Microsoft.Coyote.Tasks;6{7    {8        static void Main(string[] args)9        {10            var coffeeMachine = new CoffeeMachine();11            var monitor = new LivenessMonitor();12            var machineConfig = Configuration.Create().WithMonitor<LivenessMonitor>(monitor);13            RunAsync(coffeeMachine, machineConfig).Wait();14        }15        static async Task RunAsync(CoffeeMachine coffeeMachine, Configuration machineConfig)16        {17            await Task.Run(() =>18            {19                using (var runtime = RuntimeFactory.Create(machineConfig))20                {21                    runtime.Start();22                    runtime.CreateMachine(coffeeMachine);23                    runtime.Wait();24                }25            });26        }27    }28}29using System;30using System.Threading.Tasks;31using Microsoft.Coyote;32using Microsoft.Coyote.Samples.CoffeeMachineTasks;33using Microsoft.Coyote.Tasks;34{35    {36        static void Main(string[] args)37        {38            var coffeeMachine = new CoffeeMachine();39            var monitor = new LivenessMonitor();40            var machineConfig = Configuration.Create().WithMonitor<LivenessMonitor>(monitor);41            RunAsync(coffeeMachine, machineConfig).Wait();42        }43        static async Task RunAsync(CoffeeMachine coffeeMachine, Configuration machineConfig)44        {45            await Task.Run(() =>46            {47                using (var runtime = RuntimeFactory.Create(machineConfig))48                {49                    runtime.Start();50                    runtime.CreateMachine(coffeeMachine);51                    runtime.Wait();52                }53            });54        }55    }56}57using System;58using System.Threading.Tasks;59using Microsoft.Coyote;60using Microsoft.Coyote.Samples.CoffeeMachineTasks;61using Microsoft.Coyote.Tasks;62{63    {LivenessMonitor
Using AI Code Generation
1using Microsoft.Coyote.Samples.CoffeeMachineTasks;2using System;3{4    {5        static void Main(string[] args)6        {7            var monitor = new LivenessMonitor();8            monitor.Run();9        }10    }11}12using Microsoft.Coyote.Samples.CoffeeMachineTasks;13using System;14{15    {16        static void Main(string[] args)17        {18            var monitor = new LivenessMonitor();19            monitor.Run();20        }21    }22}23using Microsoft.Coyote.Samples.CoffeeMachineTasks;24using System;25{26    {27        static void Main(string[] args)28        {29            var monitor = new LivenessMonitor();30            monitor.Run();31        }32    }33}34using Microsoft.Coyote.Samples.CoffeeMachineTasks;35using System;36{37    {38        static void Main(string[] args)39        {40            var monitor = new LivenessMonitor();41            monitor.Run();42        }43    }44}45using Microsoft.Coyote.Samples.CoffeeMachineTasks;46using System;47{48    {49        static void Main(string[] args)50        {51            var monitor = new LivenessMonitor();52            monitor.Run();53        }54    }55}56using Microsoft.Coyote.Samples.CoffeeMachineTasks;57using System;58{59    {60        static void Main(string[] args)61        {62            var monitor = new LivenessMonitor();63            monitor.Run();64        }65    }66}LivenessMonitor
Using AI Code Generation
1using Microsoft.Coyote.Samples.CoffeeMachineTasks;2using Microsoft.Coyote.Samples.CoffeeMachineTasks;3{4    {5        static void Main(string[] args)6        {7            CoffeeMachineTasks machine = new CoffeeMachineTasks();8            LivenessMonitor monitor = new LivenessMonitor(machine);9            monitor.Start();10            Thread t = new Thread(new ThreadStart(machine.Run));11            t.Start();12            t.Join();13            monitor.Stop();14        }15    }16}17using Microsoft.Coyote;18using Microsoft.Coyote.Actors;19using Microsoft.Coyote.Runtime;20using Microsoft.Coyote.Samples.CoffeeMachineTasks;21using System;22using System.Threading;23{24    {25        private CoffeeMachineTasks Machine;26        private Thread MonitorThread;27        public LivenessMonitor(CoffeeMachineTasks machine)28        {29            this.Machine = machine;30        }31        public void Start()32        {33            this.MonitorThread = new Thread(new ThreadStart(this.Monitor));34            this.MonitorThread.Start();35        }36        public void Stop()37        {38            this.MonitorThread.Join();39        }40        private void Monitor()41        {42            while (true)43            {44                Thread.Sleep(1000);45                if (this.Machine.State == CoffeeMachineTasksState.Brewing)46                {47                    if (this.Machine.BrewTime.ElapsedMilliseconds > 30000)48                    {49                        this.Machine.RaiseFault(new CoffeeMachineTasksFault("Coffee brewing timed out."));50                    }51                }52                else if (this.Machine.State == CoffeeMachineTasksState.Boiling)53                {54                    if (this.Machine.BoilTime.ElapsedMilliseconds > 30000)55                    {56                        this.Machine.RaiseFault(new CoffeeMachineTasksFault("Water boiling timed out."));57                    }58                }59                else if (thisLivenessMonitor
Using AI Code Generation
1using Microsoft.Coyote.Samples.CoffeeMachineTasks;2using System;3using System.Threading.Tasks;4{5    {6        static void Main(string[] args)7        {8            LivenessMonitor livenessMonitor = new LivenessMonitor();9            Console.WriteLine("Hello World!");10        }11    }12}13The next step is to create a Coyote test project. This is done by creating a new project in Visual Studio and selecting the “Coyote Test Project” template. This template is available in the “Coyote Test Project (.NET Core)” category. The project template creates a new project with the following structure:14using Microsoft.Coyote.Samples.CoffeeMachineTasks;15using System;16using System.Threading.Tasks;17{18    {19        static void Main(string[] args)20        {21            LivenessMonitor livenessMonitor = new LivenessMonitor();22            Console.WriteLine("Hello World!");23        }24    }25}LivenessMonitor
Using AI Code Generation
1using Microsoft.Coyote.Samples.CoffeeMachineTasks;2using Microsoft.Coyote;3using Microsoft.Coyote.Runtime;4using Microsoft.Coyote.Tasks;5using Microsoft.Coyote.Actors;6using Microsoft.Coyote.Actors.Timers;7using Microsoft.Coyote.Actors.SharedObjects;8using Microsoft.Coyote.Actors.SharedObjects.SharedDictionary;9using Microsoft.Coyote.Actors.SharedObjects.SharedList;10using Microsoft.Coyote.Actors.SharedObjects.SharedQueue;11using Microsoft.Coyote.Actors.SharedObjects.SharedStack;12using Microsoft.Coyote.Actors.SharedObjects.SharedHashSet;13using Microsoft.Coyote.Actors.SharedObjects.SharedCounter;14using Microsoft.Coyote.Actors.SharedObjects.SharedEvent;15using Microsoft.Coyote.Actors.SharedObjects.SharedChannel;16using Microsoft.Coyote.Actors.SharedObjects.SharedChannel.SharedChannelWriter;17using Microsoft.Coyote.Actors.SharedObjects.SharedChannel.SharedChannelReader;18using Microsoft.Coyote.Actors.SharedObjects.SharedChannel.SharedChannelUnbounded;19using Microsoft.Coyote.Actors.SharedObjects.SharedChannel.SharedChannelBounded;LivenessMonitor
Using AI Code Generation
1using System;2using System.Collections.Generic;3using System.Linq;4using System.Threading.Tasks;5using Microsoft.Coyote;6using Microsoft.Coyote.Actors;7using Microsoft.Coyote.Samples.CoffeeMachineTasks;8{9    {10        static void Main(string[] args)11        {12            var monitor = new LivenessMonitor();13            var runtime = CoyoteRuntime.Create();14            runtime.RegisterMonitor(monitor);15            var coffeeMachine = runtime.CreateActor(typeof(CoffeeMachine));16            runtime.SendEvent(coffeeMachine, new MakeCoffee());17            Console.ReadKey();18            runtime.Dispose();19        }20    }21}22using System;23using System.Collections.Generic;24using System.Linq;25using System.Threading.Tasks;26using Microsoft.Coyote;27using Microsoft.Coyote.Actors;28using Microsoft.Coyote.Samples.CoffeeMachineTasks;29{30    {31        static void Main(string[] args)32        {33            var monitor = new LivenessMonitor();34            var runtime = CoyoteRuntime.Create();35            runtime.RegisterMonitor(monitor);36            var coffeeMachine = runtime.CreateActor(typeof(CoffeeMachine));37            runtime.SendEvent(coffeeMachine, new MakeCoffee());38            Console.ReadKey();39            runtime.Dispose();40        }41    }42}43using System;44using System.Collections.Generic;45using System.Linq;46using System.Threading.Tasks;47using Microsoft.Coyote;48using Microsoft.Coyote.Actors;49using Microsoft.Coyote.Samples.CoffeeMachineTasks;50{LivenessMonitor
Using AI Code Generation
1using Microsoft.Coyote.Samples.CoffeeMachineTasks;2using System.Threading.Tasks;3{4    {5        public static async Task Main()6        {7            var livenessMonitor = new LivenessMonitor();8            await livenessMonitor.RunAsync();9        }10    }11}12using Microsoft.Coyote.Samples.CoffeeMachineTasks;13using System.Threading.Tasks;14{15    {16        public static async Task Main()17        {18            var livenessMonitor = new LivenessMonitor();19            await livenessMonitor.RunAsync();20        }21    }22}23using Microsoft.Coyote.Samples.CoffeeMachineTasks;24using System.Threading.Tasks;25{26    {27        public static async Task Main()28        {29            var livenessMonitor = new LivenessMonitor();30            await livenessMonitor.RunAsync();31        }32    }33}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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
