/// <summary> /// Enqueues provided text to perform a TTS asinchronously /// </summary> /// <param name="textToSay">text to speech out</param> /// <returns>true if provided text was enqueued, false otherwise</returns> public virtual bool SpeakAsync(string textToSay) { //if (speechQueue.Count >= speechQueue.Capacity) // return false; speechQueue.Produce(new SpeechTextTask(textToSay)); return(true); }
void StopRecording(int channelIndex) { //Detach ourselves from the sample read event queue if (IsRecordingCh1) { HardwareManager.DaqBoard.ReadDone -= RecordSamples; //add end of recording to signal to our queue ChannelReadDataChunk end_chunk = new ChannelReadDataChunk(); end_chunk.StartIndex = 0; end_chunk.Data = null; _record_dataQueue.Produce(end_chunk); //wait for our file writing to finish if (_recordTask != null && !_recordTask.IsCompleted) { if (!_recordTask.Wait(1000)) { System.Diagnostics.Debug.WriteLine("Timed out waiting on record task to end"); } } _recordTask = null; } if (channelIndex == 1) { IsRecordingCh1 = false; } }
public override void Fight(IDynamicObject other) { // a local Action for the winner and the loser void act(IDynamicObject winner, IDynamicObject loser) { // add 2 to the strength of the winner winner.AddStrength(2); // the loser is now depressed loser.SetState(State.Depressed); ProducerConsumer.Produce(String.Format("Object number {0} won agains object number {1}", winner.Id, loser.Id)); } /// the winner of the fight is the object with more strength. if the strengths of objects are the same /// than there is no winner if (Strength > other.Strength || other.DeBuff == DeBuff.Cocoon) { act(this, other); } else if (other.Strength > Strength) { act(other, this); } }
/// <summary> /// Stores the received packet in a ProducerConsumer queue /// </summary> /// <param name="cnnMan">The ConnectionManager source of the data</param> /// <param name="packet">The received TCP packet</param> private void cnnMan_DataReceived(ConnectionManager cnnMan, TcpPacket packet) { if (!packet.IsAnsi) { return; } dataReceived.Produce(packet); }
/// <summary> /// Performs operations when data is received trough socket /// </summary> /// <param name="p">TCP Packet received</param> protected void client_DataReceived(TcpPacket p) { lastDataInTime = DateTime.Now; dataReceived.Produce(p); string dString = p.DataString; #if DEBUG this.Parent.Log.WriteLine(9, this.Name + ": received " + p.Data.Length + "bytes {" + dString + "}"); #endif }
public override void ActOnStaticObject(Food obj) { ProducerConsumer.Produce(String.Format("Spider number {0} ate food!", Id)); Strength++; agilityProgress++; if (agilityProgress == 2) { agilityProgress = 0; Agility++; } }
/// <summary> /// Plays an audio file asynchronously /// </summary> /// <param name="audioFilePath">Audio object to play</param> /// <returns>true if audio file was loaded and enqueued successfully, false otherwise</returns> public bool PlayAsync(string audioFilePath) { if (playQueue.Count >= playQueue.Capacity) { return(false); } PlayAudioTask audioTask; try { audioTask = new PlayAudioTask(audioFilePath); } catch { return(false); } if (audioTask != null) { playQueue.Produce(audioTask); return(true); } return(false); }
/// <summary> /// Event handler whenever a bunch of new samples is acquired /// </summary> /// <param name="samples">The samples received</param> void SampleAcquired(ReadDoneEventArgs args) { for (int i = 0; i < args.Data.GetLength(1); i++) { _liveDump.Produce(args.Data[ChannelIndex, i]); if (SealTest) { _sealTestDump.Produce(new IndexedSample(args.Data[ChannelIndex, i], args.StartIndex + i)); } } }
static void Main() { queue = new ProducerConsumer(); new Thread(new ThreadStart(ConsumerJob)).Start(); Random rng = new Random(0); for (int i = 0; i < 10; i++) { Console.WriteLine("Producing {0}", i); queue.Produce(i); Thread.Sleep(rng.Next(1000)); } }
static void Main() { ProducerConsumer<ActionWrapper> pc = new ProducerConsumer<ActionWrapper>(1, 10000, 1000, 5, 1, 5000); pc.OnConsume += OnConsume; for (int i = 0; i < 100; i++) { ActionWrapper wrapper = new ActionWrapper(); wrapper.Parameter = i.ToString(); wrapper.DoAction = GetAction(); pc.Produce(wrapper); } Console.ReadLine(); }
private void FightDifferentObject(IDynamicObject other) { if (other.DeBuff == DeBuff.Cocoon) { agilityProgress = 0; Strength++; other.SetState(State.Dead); ProducerConsumer.Produce(String.Format("Spider number {0} ate another object with id {1}", Id, other.Id)); } else { other.DeBuff = DeBuff.Cocoon; ProducerConsumer.Produce(String.Format("object number {0} became a cocoon", other.Id)); } }
public override IShortestPathResult Process(uint @from, uint to) { _result = new BfsConcurrentResult(from, to); INode <T, TEdgeCustom> nodeFrom = Graph[from]; nodeFrom.Distance = 0; _table.Initialise = () => _table.Produce(nodeFrom); _table.Producing = node => { if (node.Key != _result.ToNode) { for (int i = 0; i < node.Children.Count; i++) { Edge <T, TEdgeCustom> e = node.Children[i]; _table.Consume(new MapReduceJob(node.Key, e.Node.Key, node.Distance, e.Cost)); } } }; _table.Consuming = job => { if (Reduce(job.From, Graph[job.To], job.Distance)) { _table.Produce(Graph[job.To]); } }; _table.Work(); _result.Distance = Graph[to].Distance; return(_result); }
protected override void ActDepressedObject() { var dynamicObjects = BoardFunctions.GetNearObjects(X, Y, 1); /// if the number of adjacent objects are in the range of [info.MinObjectsPerArea,info.MaxObjectsPerArea] /// than the given object will no longer be depressed. if (dynamicObjects.Count >= info.MinObjectsPerArea && dynamicObjects.Count <= info.MaxObjectsPerArea) { ProducerConsumer.Produce(String.Format("Object number {0} is no longer depressed, found {1} objects near it", Id, dynamicObjects.Count)); SetState(State.Alive); } else { ProducerConsumer.Produce(String.Format("Object number {0} is still depressed, found {1} objects near it", Id, dynamicObjects.Count)); } }
/// <summary> /// Sends a command to the module /// </summary> /// <param name="command">Response to send</param> /// <returns>true if the command has been sent, false otherwise</returns> public override bool Send(ITextCommand command) { // Check if this module is the destination module for the command if (this != command.Destination) { throw new Exception("Command marked to be sent through other module"); } // Check if module is not busy nor running and command is not a priority command if (!running || (Busy && !command.Prototype.HasPriority)) { return(false); } // Send the command commandsReceived.Produce(command); return(true); }
private void FightSpider(IDynamicObject spider) { if (spider.DeBuff == DeBuff.Cocoon) { agilityProgress = 0; Strength += 2; Agility++; spider.SetState(State.Dead); BoardFunctions.ClearDynamicObjectOnTile(spider.X, spider.Y); ProducerConsumer.Produce(String.Format("Spider number {0} ate another spider with id {1}", Id, spider.Id)); } else if (Agility > spider.Agility) { spider.DeBuff = DeBuff.Cocoon; ProducerConsumer.Produce(String.Format("Spider number {0} became a cocoone", spider.Id)); } }
public override IShortestPathResult Process(uint @from, uint to) { _result = new BfsConcurrentResult(from, to); INode <T, TEdgeCustom> nodeFrom = Graph[from]; nodeFrom.Distance = 0; _table.Initialise = () => _table.Produce(nodeFrom); _table.Producing = node => { if (node.Key != _result.ToNode) { node.EachChild((in Edge <T, TEdgeCustom> e) => { _table.Consume(new MapReduceJob(node.Key, e.Node.Key, node.Distance, e.Cost)); }); }
private void PlayAudioThreadTask() { PlayAudioTask audioTask; running = true; while (running) { try { audioTask = playQueue.Consume(); if ((audioTask == null) || (audioTask.Audio == null)) { continue; } if (!Play(audioTask)) { playQueue.Produce(audioTask); } } catch (ThreadAbortException taex) { Console.WriteLine(taex.Message); playQueue.Clear(); return; } catch (ThreadInterruptedException tiex) { Console.WriteLine(tiex.Message); continue; } catch { Thread.Sleep(100); continue; } } }
static void Main() { queue = new ProducerConsumer(); new Thread(new ThreadStart(ConsumerJob)).Start(); Random rng = new Random(0); for (int i = 0; i < 10; i++) { Console.WriteLine("Producing {0}", i); queue.Produce(i); Thread.Sleep(rng.Next(1000)); } }
private void cnnMan_DataReceived(ConnectionManager cnnMan, TcpPacket packet) { dataReceived.Produce(new ReceivedPacket(cnnMan, packet)); }
public void WriteAndReadThreadSafeDataToAcquisitionFile() { string filename = Path.Combine(folder, "testWithThreadsDataAcquisition.H5"); int nr50samples = 1000; try { using (var writer = new Hdf5AcquisitionFileWriter(filename)) { var pc = new ProducerConsumer(writer); var header = FillHeader(writer.Header); var data = new List <double[]>(); for (int j = 0; j < nr50samples; j++) { for (int i = 0; i < header.Recording.NrOfChannels; i++) { var row = Enumerable.Range(0, 50).Select(x => i + j + x / 50.0).ToArray(); data.Add(row); } pc.Produce(data); Thread.Sleep(10); data.Clear(); } //for (int i = 0; i < header.Recording.NrOfChannels; i++) //{ // var row = Enumerable.Range(0, 50).Select(x => i + 1 + x / 50.0).ToArray(); // data.Add(row); //} //pc.Produce(data); Thread.Sleep(1000); pc.Done(); /*header.Recording.NrOfSamples = 100; * for (int i = 0; i < header.Channels.Length; i++) * { * header.Channels[i].NrOfSamples = header.Recording.NrOfSamples; * }*/ } } catch (Exception ex) { CreateExceptionAssert(ex); } try { using (var reader = new Hdf5AcquisitionFileReader(filename)) { var header = reader.Header; Assert.IsTrue(header.Patient.Name == "Robert"); ulong samps = Convert.ToUInt64(50 * nr50samples); Assert.IsTrue(header.Recording.NrOfSamples == samps); Assert.IsTrue(header.Channels.Select(c => c.Label).SequenceEqual(new string[] { "DC01", "DC02", "DC03", "DC04", "DC05" })); Assert.IsTrue(header.Channels.Select(c => c.NrOfSamples).SequenceEqual(new ulong[] { samps, samps, samps, samps, samps })); var data = reader.ReadDouble(0, 49); var sig = data.First().Take(5); Assert.IsTrue(sig.Similar(new double[] { 0, 1 / 50f, 2 / 50f, 3 / 50f, 4 / 50f })); data = reader.ReadDouble(50, 99); sig = data.First().Take(5); Assert.IsTrue(sig.Similar(new double[] { 50 / 50f, 51 / 50f, 52 / 50f, 53 / 50f, 54 / 50f })); } } catch (Exception ex) { CreateExceptionAssert(ex); } }
public override void ActOnStaticObject(Food x) { ProducerConsumer.Produce(String.Format("Ant number {0} ate food!", Id)); Strength += 2; }
public void Execute() { queue = new ProducerConsumer(); Thread consumer=new Thread(new ThreadStart(ConsumerJob)); consumer.Start(); Random rng = new Random(0); for (int i = 0; i < 10; i++) { Console.WriteLine("Producing {0}", i); queue.Produce(i); Thread.Sleep(rng.Next(100)); } Console.WriteLine("Waiting for consumer to finish...."); consumer.Join(); Console.WriteLine("Consumer finished his job...."); }
private void server_DataReceived(TcpPacket p) { dataReceived.Produce(p); }
public void Check() { StatusReportList = new List <Report>(); var clusters = _setting.General.Kafka.Clusters; var connectionTimeoutSec = _setting.General.Kafka.ConnectionTimeoutSec; var topicNameFromSettings = _setting.General.Kafka.TopicName; var certificateLocation = _setting.General.Kafka.SslCertificateLocation; var certificateSubject = _setting.General.Kafka.SslCertificateSubject; var date = DateTime.Now.ToString("dd.MM.yyyy.HH.m"); if (File.Exists(certificateLocation)) { // delete an old certificate File.Delete(certificateLocation); } var counter = 0; foreach (var cluster in clusters) { counter++; string topicName; var kafkaStatus = ReportStatus.Undefined; var mongoDbStatus = ReportStatus.Undefined; var statusReport = new Report(); statusReport.Number = counter; statusReport.EnvName = cluster.Name; _logger.Info($" [{counter}] from [{clusters.Count}]. " + $"Work with the '{cluster.Name}' cluster"); // Check Mongo _logger.Info($"Checking Mongo DB:"); var mongoDbHelper = new MongoDbHelper(); var mongoDbConnectionStr = cluster.MongoDb; mongoDbStatus = mongoDbHelper.Ping(mongoDbConnectionStr, connectionTimeoutSec); // Check Kafka _logger.Info("Checking Kafka:"); var bootStrapServers = string.Join(",", cluster.BootstrapServers); _logger.Info($" bootstrap servers: {bootStrapServers}"); var clientConfig = new ClientConfig { BootstrapServers = bootStrapServers, SocketTimeoutMs = connectionTimeoutSec * 1000, }; topicName = $"{topicNameFromSettings}.{date}"; if (cluster.SslEnabled) { _logger.Info("SSL connection is enabled for this cluster"); if (!File.Exists(certificateLocation)) { try { var certificate = CertificateHelper.GetCertificate(certificateSubject); CertificateHelper.ExportToPEMFile(certificate, certificateLocation); } catch (CertificateException ce) { _logger.Error(ce.Message); kafkaStatus = ReportStatus.CertificateError; _logger.Warn($" Kafka status - [{kafkaStatus}]"); WriteClusterStatus(cluster, statusReport, mongoDbStatus, kafkaStatus); StatusReportList.Add(statusReport); continue; } } clientConfig.SslCaLocation = certificateLocation; clientConfig.SecurityProtocol = SecurityProtocol.Ssl; clientConfig.Debug = "security"; topicName = $"{topicNameFromSettings}.ssl.{date}"; } var bootstrapServersCount = cluster.BootstrapServers.Count; var topicHelper = new TopicHelper(); var producerConsumer = new ProducerConsumer(); var connectionIsOk = topicHelper .CheckConnectivity(clientConfig, bootstrapServersCount); if (connectionIsOk) { var topicWasCreated = topicHelper .CreateTopic(clientConfig, bootstrapServersCount, topicName); if (topicWasCreated) { _logger.Info(string.Empty); var producedMessageCount = producerConsumer.Produce(clientConfig, topicName); var consumedMessageCount = producerConsumer.Consume(clientConfig, topicName); if (producedMessageCount == consumedMessageCount) { _logger.Info($" * Produced messages == consumed messages: '{consumedMessageCount}' - [ok]"); kafkaStatus = ReportStatus.Ok; } else { _logger.Error($" * Produced messages != consumed messages: '{consumedMessageCount}' - [error]"); kafkaStatus = ReportStatus.Error; } } } else { kafkaStatus = ReportStatus.Error; } _logger.Info($" Kafka status - [{kafkaStatus}]"); WriteClusterStatus(cluster, statusReport, mongoDbStatus, kafkaStatus); StatusReportList.Add(statusReport); _logger.Info(string.Empty); } new HtmlReportHelper().PopulateTemplate(StatusReportList); }