From 78b23f4863f1678c4f5acedd870e54d35216c22b Mon Sep 17 00:00:00 2001 From: Samuele Locatelli Date: Sun, 6 Mar 2022 12:40:18 +0100 Subject: [PATCH] Simulatore multithread OK come primo test (manca reset...) --- MachineSim/Program.cs | 64 ++++++++++++++++++++++++++++++++++++++----- 1 file changed, 57 insertions(+), 7 deletions(-) diff --git a/MachineSim/Program.cs b/MachineSim/Program.cs index 6403cfc..dec365e 100644 --- a/MachineSim/Program.cs +++ b/MachineSim/Program.cs @@ -5,23 +5,73 @@ using System.Configuration; string lineSep = "------------------------------------------------------"; string redisConf = "127.0.0.1:6379"; +Random rand = new Random(); + Console.WriteLine(lineSep); Console.WriteLine($"Starting Machine SIM - redis server on {redisConf}!"); Console.WriteLine(lineSep); Console.WriteLine(""); +Console.WriteLine("Running - press CTRL-C to stop SIM"); +Console.WriteLine(""); //Create a connection -using (ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("127.0.0.1:6379")) +ConnectionMultiplexer redis = ConnectionMultiplexer.Connect(redisConf); +ISubscriber sub = redis.GetSubscriber(); + + + +#if false +// ciclo principale +string input; +do { - ISubscriber sub = redis.GetSubscriber(); + input = Console.ReadLine(); + sub.Publish("allarmi", input); +} while (input != "exit"); +#endif - Console.WriteLine("please enter any character and exit to exit"); +// avvio tutti i thread... +Thread threadStatus = new Thread(simStatus); +Thread threadAlarms = new Thread(simAlarms); - string input; +threadStatus.Start(); +threadAlarms.Start(); + + + +void simStatus() +{ + int minPeriod = 2000; + int maxPeriod = 3000; + + do { + var statusCode = rand.Next(1, 5); + saveAndSendMessage("Machine:Status:Current", $"{statusCode} | Stato {statusCode:00}", "status", $"{statusCode}"); + // attesa random + Thread.Sleep(rand.Next(minPeriod, maxPeriod)); + } while (true); +} +void simAlarms() +{ + int minPeriod = 1000; + int maxPeriod = 2000; do { - input = Console.ReadLine(); - sub.Publish("allarmi", input); - } while (input != "exit"); + var alarmCode = rand.Next(1, 100); + saveAndSendMessage("Machine:Alarms:Current", $"{alarmCode:000} | Allarme PLC {alarmCode}", "allarmi", $"{alarmCode:000}"); + // attesa random + Thread.Sleep(rand.Next(minPeriod, maxPeriod)); + } while (true); +} + + +void saveAndSendMessage(string memKey, string value, string notifyChannel, string message) +{ + // effettuo la scrittura nell'area di memoria indicata + redis.GetDatabase().SetAdd(memKey, value); + + // invio notifica tramite il canale richiesto + sub.Publish(notifyChannel, message); + Console.WriteLine($"[{notifyChannel}] key: {memKey} | val: {value} | message: {message}"); } \ No newline at end of file