public void ParseSingleLongPacketDleIsLast() { List <byte[]> packets = new List <byte[]>(); IPacketsHandler messagesHandler = Substitute.For <IPacketsHandler>(); ILoggerService loggerService = Substitute.For <ILoggerService>(); messagesHandler.WhenForAnyArgs(m => m.Push(null)).Do(ci => packets.Add(ci.ArgAt <byte[]>(0))); ICommunicationChannel handler = new CommunicationChannel(loggerService, null); handler.Init(DependencyInjectionFixture.BufferManager, messagesHandler); byte[] packet1 = new byte[] { 0x45, 0x65, CommunicationChannel.DLE }; byte[] packet2 = new byte[] { CommunicationChannel.STX, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xaa, 0xbb, 0xcc, 0xdd, 0x44 }; byte[] packet3 = new byte[] { 0x03, 0x00, 0xaa, 0xbb, 0xcc, 0xdd, 0x44 }; byte[] parsedPacket = new byte[] { 0xaa, 0xbb, 0xcc, 0xdd, 0x44, 0x03, 0x00, 0xaa, 0xbb }; handler.PushForParsing(packet1, 0, packet1.Length); handler.PushForParsing(packet2, 0, packet2.Length); handler.PushForParsing(packet3, 0, packet3.Length); Thread.Sleep(100); handler.Close(); Assert.True(packets.Count == 1); byte[] messagePacket = packets.First(); Assert.Equal(messagePacket, parsedPacket); }
public void CanConnect() { using (var server = new CommunicationServer("testConnect")) { var count = 0; var lck = new object(); server.Listen(); server.RaiseNewClientEvent += (x, e) => { lock (lck) { count++; Monitor.Pulse(lck); } }; using (var client = CommunicationChannel.Client(server.PipeName)) { Assert.True(client.IsConnected); Assert.True(WaitFor(lck, () => count == 1, 1000)); } using (var client = CommunicationChannel.Client(server.PipeName)) { Assert.True(client.IsConnected); Assert.True(WaitFor(lck, () => count == 2, 1000)); } } }
public BaseDoubleWordVerilatedPeripheral(Machine machine, long frequency, string simulationFilePathLinux = null, string simulationFilePathWindows = null, string simulationFilePathMacOS = null, ulong limitBuffer = LimitBuffer, int timeout = DefaultTimeout) { this.machine = machine; this.msTimeout = timeout; pauseMRES = new ManualResetEventSlim(initialState: true); allTicksProcessedARE = new AutoResetEvent(initialState: false); mainSocket = new CommunicationChannel(this, msTimeout); asyncEventsSocket = new CommunicationChannel(this, Timeout.Infinite); receiveThread = new Thread(ReceiveLoop) { IsBackground = true, Name = "Verilated.Receiver" }; timer = new LimitTimer(machine.ClockSource, frequency, this, LimitTimerName, limitBuffer, enabled: false, eventEnabled: true, autoUpdate: true); timer.LimitReached += () => { Send(ActionType.TickClock, 0, limitBuffer); this.NoisyLog("Tick: TickClock sent, waiting for the verilated peripheral..."); allTicksProcessedARE.WaitOne(); this.NoisyLog("Tick: Verilated peripheral finished evaluating the model."); }; SimulationFilePathLinux = simulationFilePathLinux; SimulationFilePathWindows = simulationFilePathWindows; SimulationFilePathMacOS = simulationFilePathMacOS; }
public void Send(Guid channelId, string message) { if (message == "") { return; } if (!CurrentUserMemberOfChannel(channelId)) { return; } CommunicationChannel communicationChannel = db.CommunicationChannels.Where(ch => ch.Id == channelId).Include(ch => ch.ApplicationUser).First(); if (communicationChannel.Open == false) { return; } var user = db.Users.Where(u => u.UserName == Context.User.Identity.Name).First(); CommunicationChannelMessage communicationChannelMessage = new CommunicationChannelMessage() { ApplicationUserId = user.Id, ChannelId = channelId, Created = DateTime.Now, Message = message, Id = Guid.NewGuid() }; db.CommunicationChannelMessages.Add(communicationChannelMessage); db.SaveChanges(); Clients.Group(channelId.ToString()).addNewMessage(user.Name, message); }
private async void Page_Loaded(object sender, RoutedEventArgs e) { commChannel = new CommunicationChannel(); commChannel.MessageReceived += CommChannel_MessageReceived; commChannel.ErrorMessage += CommChannel_ErrorMessage; commChannel.Initialize(); commChannel.Listen(); mainpagecontext.UpdateIPaddress(commChannel.IPAddress, commChannel.PortNo); SerialPortCommchannel = new SerialPortComm(); Watchdog = new DispatcherTimer(); Watchdog.Tick += Watchdog_Tick; Watchdog.Interval = new TimeSpan(0, 0, 0, 0, 500); DataacqAppComm = new DataacquistionappComm(); DataacqAppComm.MessageReceived += CommChannel_MessageReceived; // DataacqAppComm.Initialize(); // await DataacqAppComm.Connect(); await DataacqAppComm.ResetCommFiles(); DataacqAppComm.SendMessageToDataacquistionapp(CommunicationCommands.DATAACQUISTIONAPPCONNECTION); Watchdog.Start(); // scokcomm.Initialize(); // scokcomm.Connect(); }
private Task MessageLoopAsync(CommunicationChannel channel, CancellationToken cancellationToken) { Exception error = null; // Set read timeout to avoid blocking receive raw message while (channel != null && !cancellationToken.IsCancellationRequested && this.jsProcess.IsAlive) { try { var task = channel.ReceiveMessageAsync(cancellationToken); task.Wait(); this.onMessageReceived(task.Result); } catch (Exception exception) { EqtTrace.Error( "Socket: Message loop: failed to receive message {0}", exception); error = exception; break; } } return(Task.FromResult(0)); }
public void CanConnect() { using (var server = new CommunicationServer("testConnect")) { var count = 0; var lck = new object(); server.Listen(); server.RaiseNewClientEvent += (x, e) => { lock (lck) { count++; Monitor.Pulse(lck); } }; using (var client = CommunicationChannel.Client(server.PipeName)) { client.IsConnected.ShouldBeTrue("First client could not connect to server pipe"); WaitFor(lck, () => count == 1, 1000).ShouldBeTrue("First client connection event was not raised"); } using (var client = CommunicationChannel.Client(server.PipeName)) { client.IsConnected.ShouldBeTrue("Second client could not connect to server pipe"); WaitFor(lck, () => count == 2, 1000).ShouldBeTrue("First client connection event was not raised"); } } }
public void Command_with_invalid_CommunicationChannel_fails(CommunicationChannel communicationChannel) { // Arrange var id = EnrollmentAggregate.EnrollmentId.New; var enrollment = new EnrollmentAggregate(id); var training = CreateTrainingInFutureWithId(1); var recordingCoordinator = new Models.Users.ApplicationUser() { Id = Guid.NewGuid() }; var command = new RecordAcceptedTrainingInvitation.Command() { EnrollmentId = id.GetGuid(), CommunicationChannel = communicationChannel, SelectedTrainingID = 1, AdditionalNotes = "brak notatek" }; // Act var result = enrollment.RecordCandidateAcceptedTrainingInvitation(command, recordingCoordinator, new[] { training }, NodaTime.SystemClock.Instance.GetCurrentInstant()); // Assert Assert.False(result.IsSuccess); var error = Assert.IsType <Error.ValidationFailed>(result.Error); var failure = Assert.Single(error.Failures); Assert.Equal(nameof(command.CommunicationChannel), failure.PropertyName); Assert.Single(failure.Errors); }
public static void InitCoverage() { ActiveMutation = int.Parse(Environment.GetEnvironmentVariable("ActiveMutation") ?? "-1"); if (channel != null) { channel.Dispose(); channel = null; } string coverageMode = Environment.GetEnvironmentVariable(EnvironmentPipeName) ?? string.Empty; if (coverageMode.StartsWith("pipe:")) { pipeName = coverageMode.Substring(5); usePipe = true; captureCoverage = true; channel = CommunicationChannel.Client(pipeName, 100); channel.SetLogger(Log); channel.RaiseReceivedMessage += Channel_RaiseReceivedMessage; channel.Start(); } else if (coverageMode.StartsWith("env:")) { envName = coverageMode.Substring(4); captureCoverage = true; usePipe = false; } if (captureCoverage) { _coveredMutants = new HashSet <int>(); _staticMutants = new HashSet <int>(); } }
public ActionResult Create([Bind(Include = "Id,Title")] CommunicationChannel communicationChannel) { var user = db.Users.Where(u => u.UserName == User.Identity.Name).First(); communicationChannel.ApplicationUserId = user.Id; communicationChannel.Created = DateTime.Now; int cost = db.Prices.First().Cost; if (user.NumberOfTokens < cost) { return(RedirectToAction("Index", new { Message = "You do not have enough tokens to create a Communication Channel!" })); } if (ModelState.IsValid) { communicationChannel.Id = Guid.NewGuid(); user.NumberOfTokens -= cost; db.CommunicationChannels.Add(communicationChannel); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(communicationChannel)); }
protected bool CurrentUserMemberOfChannel(Guid id) { CommunicationChannel communicationChannel = db.CommunicationChannels.Where(ch => ch.Id == id).Include(ch => ch.ApplicationUser).First(); return(db.AgentChannels.Any(ac => ac.AgentUserName == Context.User.Identity.Name && ac.ChannelId == id) || communicationChannel.ApplicationUser.UserName == Context.User.Identity.Name); }
private void ConnectionEstablished(object s, ConnectionEventArgs e) { lock (_lck) { _client = e.Client; _client.RaiseReceivedMessage += ReceivedMutant; Monitor.Pulse(_lck); } }
private IPEndPoint InitializeChannel() { this.channel = new CommunicationChannel(); var endpoint = channel.HostServer(new IPEndPoint(IPAddress.Loopback, 0)); Task.Run(() => channel.AcceptClientAsync()); return(endpoint); }
/// <summary> /// sends the given string message to the player via the given channel. /// Also sets current channel to be given channel. /// </summary> /// <param name="message"></ /// <param name="channel"></param> private void SendMessageToPlayer(string message, CommunicationChannel channel) { if (channel == null) { throw new Exception("channel was null"); } aiCommState = AICommunicationState.InCommunication; currentCommChannel = channel; channel.StartCommunicationWithPlayer(player, this, message); }
// In MainAgentController ACC and AM agents has to be created explicitly protected override void OnStart() { CommunicationChannel acc = new CommunicationChannel(ID, CommunicationChannel.LOCAL_NAME); AgentManager ams = new AgentManager(ID, AgentManager.LOCAL_NAME); DirectoryFacilitator df = new DirectoryFacilitator(ID, DirectoryFacilitator.LOCAL_NAME); ams.Start(); df.Start(); acc.Start(); IsStarted = true; }
public BaseDoubleWordVerilatedPeripheral(Machine machine, string simulationFilePath, long frequency, ulong limitBuffer = LimitBuffer, double timeout = DefaultTimeout) { mainSocket = new CommunicationChannel(timeout); asyncEventsSocket = new CommunicationChannel(timeout); receiveThread = new Thread(ReceiveLoop) { IsBackground = true, Name = "Verilated.Receiver" }; SimulationFilePath = simulationFilePath; InitTimer(machine.ClockSource, frequency, limitBuffer); }
public ContactOccured(Guid recordingUserId, CommunicationChannel communicationChannel, string content, string additionalNotes) { Guard.Against.Default(recordingUserId, nameof(recordingUserId)); Guard.Against.Default(communicationChannel, nameof(communicationChannel)); Guard.Against.NullOrWhiteSpace(content, nameof(content)); Guard.Against.Null(additionalNotes, nameof(additionalNotes)); RecordingUserId = recordingUserId; CommunicationChannel = communicationChannel; Content = content; AdditionalNotes = additionalNotes; }
public ActionResult Leave(Guid id) { if (CurrentUserMemberOfChannel(id)) { var agentChannel = db.AgentChannels.Where(ac => ac.AgentUserName == User.Identity.Name && ac.ChannelId == id).First(); CommunicationChannel communicationChannel = db.CommunicationChannels.Where(ch => ch.Id == id).Include(ch => ch.ApplicationUser).First(); communicationChannel.NumberOfAgents--; db.AgentChannels.Remove(agentChannel); db.SaveChanges(); } return(RedirectToAction("Index")); }
Task <ExitCode> IJustTestOrchestrator.OrchestrateTest( string bundleIdentifier, TestTargetOs target, string?deviceName, TimeSpan timeout, TimeSpan launchTimeout, CommunicationChannel communicationChannel, XmlResultJargon xmlResultJargon, IEnumerable <string> singleMethodFilters, IEnumerable <string> classMethodFilters, bool includeWirelessDevices, bool enableLldb, bool signalAppEnd, IReadOnlyCollection <(string, string)> environmentalVariables,
public ActionResult Join(Guid id) { CommunicationChannel communicationChannel = db.CommunicationChannels.Where(ch => ch.Id == id).Include(ch => ch.ApplicationUser).First(); var agentChannel = new AgentChannel() { AgentUserName = User.Identity.Name, ChannelId = communicationChannel.Id }; db.AgentChannels.Add(agentChannel); communicationChannel.NumberOfAgents++; db.SaveChanges(); return(RedirectToAction("Details", new { id = communicationChannel.Id })); }
// GET: UserCommunicationChannels/Details/5 public ActionResult Details(Guid id) { CommunicationChannel communicationChannel = db.CommunicationChannels.Where(ch => ch.Id == id).Include(ch => ch.ApplicationUser).First(); if (!CurrentUserMemberOfChannel(id)) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } if (communicationChannel == null) { return(HttpNotFound()); } ViewBag.Messages = db.CommunicationChannelMessages.Where(ccm => ccm.ChannelId == id) .Include(ccm => ccm.ApplicationUser).OrderBy(ccm => ccm.Created).ToArray(); return(View(communicationChannel)); }
public BaseDoubleWordVerilatedPeripheral(Machine machine, long frequency, string simulationFilePath = null, ulong limitBuffer = LimitBuffer, double timeout = DefaultTimeout) { mainSocket = new CommunicationChannel(timeout); asyncEventsSocket = new CommunicationChannel(timeout); receiveThread = new Thread(ReceiveLoop) { IsBackground = true, Name = "Verilated.Receiver" }; timer = new LimitTimer(machine.ClockSource, frequency, this, LimitTimerName, limitBuffer, enabled: false, eventEnabled: true, autoUpdate: true); timer.LimitReached += () => { Send(ActionType.TickClock, 0, limitBuffer); }; SimulationFilePath = simulationFilePath; }
private static void SendData(CommunicationChannel communicationManager) { // Having less than the buffer size in SocketConstants.BUFFERSIZE. var dataBytes = new byte[2048]; for (int i = 0; i < dataBytes.Length; i++) { dataBytes[i] = 0x65; } var dataBytesStr = Encoding.UTF8.GetString(dataBytes); for (int i = 0; i < 5; i++) { communicationManager.SendMessage(dataBytesStr); } }
public async Task <CommunicationChannelDto> Handle(CreateCommunicationChannelCommand request, CancellationToken cancellationToken) { // Vytvořím entitu naplněnou daty z příkazu. var entity = new CommunicationChannel() { Name = request.Name, Description = request.Description }; // Přidám aktuálně přihlášeného uživatele do seznamu uživatelů ve skupině. entity.Users.Add(_currentUserService.User); // Přidám záznam do datového zdroje a uložím. await _communicationChannelRepository.AddOrUpdateAsync(entity, cancellationToken); await _unitOfWork.SaveChangesAsync(cancellationToken); // Vrátím Id vytvořeného záznamu. return(_mapper.Map <CommunicationChannelDto>(entity)); }
public BaseDoubleWordVerilatedPeripheral(Machine machine, long frequency, string simulationFilePathLinux = null, string simulationFilePathWindows = null, string simulationFilePathMacOS = null, ulong limitBuffer = LimitBuffer, int timeout = DefaultTimeout) { this.machine = machine; pauseMRES = new ManualResetEventSlim(initialState: true); mainSocket = new CommunicationChannel(this, timeout); asyncEventsSocket = new CommunicationChannel(this, Timeout.Infinite); receiveThread = new Thread(ReceiveLoop) { IsBackground = true, Name = "Verilated.Receiver" }; timer = new LimitTimer(machine.ClockSource, frequency, this, LimitTimerName, limitBuffer, enabled: false, eventEnabled: true, autoUpdate: true); timer.LimitReached += () => { Send(ActionType.TickClock, 0, limitBuffer); }; SimulationFilePathLinux = simulationFilePathLinux; SimulationFilePathWindows = simulationFilePathWindows; SimulationFilePathMacOS = simulationFilePathMacOS; }
private Task MessageLoopAsync(CommunicationChannel channel, CancellationToken cancellationToken) { // Set read timeout to avoid blocking receive raw message while (channel != null && !cancellationToken.IsCancellationRequested && this.jsProcess.IsAlive && !this.executionComplete.IsSet) { try { var task = channel.ReceiveMessageAsync(cancellationToken); task.Wait(); this.OnMessageReceived(task.Result); } catch (Exception exception) { EqtTrace.Error("RuntimeManager: Communication error: {0}", exception); Console.Error.WriteLine("JSTest: Communucation error: {0}", exception.Message); } } return(Task.FromResult(0)); }
public void CanSend() { using (var server = new CommunicationServer("test")) { var lck = new object(); var message = string.Empty; CommunicationChannel serverSide = null; server.Listen(); server.RaiseNewClientEvent += (o, e) => { lock (lck) { serverSide = e.Client; serverSide.RaiseReceivedMessage += (o2, msg) => { lock (lck) { message = msg; Monitor.Pulse(lck); } }; Monitor.Pulse(lck); } }; using (var client = CommunicationChannel.Client(server.PipeName)) { Assert.True(client.IsConnected); Assert.True(WaitFor(lck, () => serverSide != null, 1000)); client.Start(); client.RaiseReceivedMessage += (o, msg) => { client.SendText(msg); }; serverSide.SendText("it works"); Assert.True(WaitFor(lck, () => !string.IsNullOrEmpty(message), 1000)); Assert.Equal("it works", message); } } }
public void CanSend() { using (var server = new CommunicationServer("test")) { var lck = new object(); var message = string.Empty; CommunicationChannel serverSide = null; server.Listen(); server.RaiseNewClientEvent += (o, e) => { lock (lck) { serverSide = e.Client; serverSide.RaiseReceivedMessage += (o2, msg) => { lock (lck) { message = msg; Monitor.Pulse(lck); } }; Monitor.Pulse(lck); } }; using (var client = CommunicationChannel.Client(server.PipeName)) { client.IsConnected.ShouldBeTrue("Client could not connect to server pipe"); WaitFor(lck, () => serverSide != null, 1000).ShouldBeTrue("Client connection event was not raised"); client.Start(); client.RaiseReceivedMessage += (o, msg) => { client.SendText(msg); }; serverSide.SendText("it works"); WaitFor(lck, () => !string.IsNullOrEmpty(message), 1000).ShouldBeTrue("Client message received event was not raised"); message.ShouldBe("it works"); } } }
private void Page_Loaded(object sender, RoutedEventArgs e) { SMCCommChannel = new CommunicationChannel(); SMCCommChannel.Initialize(); Utility ut = new Utility(); var result = Task.Run(async() => { return(await ut.ReadIPaddress()); }).Result; SMCCommChannel.IPAddress = mainpagecontext.TxtIpAddress; // "192.168.0.33"; SMCCommChannel.PortNo = mainpagecontext.TxtProtNo; // "9856"; SMCCommChannel.MessageReceived += SMCCommChannel_MessageReceived; mainpagecontext.IsSMCConnected = false; SMCCommChannel.Connect(); SMCCommChannel.SendMessage(CommunicationCommands.MCCConnection); watchdog = new DispatcherTimer(); watchdog.Tick += Watchdog_Tick; watchdog.Interval = new TimeSpan(0, 0, 1); watchdog.Start(); CommToDataAcq.MessageReceived += SMCCommChannel_MessageReceived; CommToDataAcq.Initialize(); CommToDataAcq.Connect(); }
public static void InitCoverage() { ActiveMutation = int.Parse(Environment.GetEnvironmentVariable("ActiveMutation") ?? "-1"); string coverageMode = Environment.GetEnvironmentVariable(EnvironmentPipeName) ?? string.Empty; #if !STRYKER_NO_PIPE if (channel != null) { channel.Dispose(); channel = null; } if (coverageMode.StartsWith("pipe:")) { Log("Use pipe for data transmission"); pipeName = coverageMode.Substring(5); usePipe = true; captureCoverage = true; channel = CommunicationChannel.Client(pipeName, 100); channel.SetLogger(Log); channel.RaiseReceivedMessage += Channel_RaiseReceivedMessage; channel.Start(); } #else if (coverageMode.StartsWith("env:")) { Log("Use env for data transmission"); envName = coverageMode.Substring(4); captureCoverage = true; usePipe = false; } #endif if (captureCoverage) { ResetCoverage(); } }
private static void SendMessage(CommunicationChannel communicationChannel, int message) { try { SendMessage(communicationChannel, BitConverter.GetBytes(message)); } catch (Exception e) { } }
private static void SendMessage(CommunicationChannel communicationChannel, byte[] message) { try { int bytesSent = NetworkHelper.SendUdp(UdpSockets[communicationChannel],message, message.Length, EndPoints[communicationChannel]); } catch (Exception e) { } }
private void Update() { //if in communcation, check for response, call handler on response if there if (aiCommState == AICommunicationState.InCommunication) { if (currentCommChannel != null && currentCommChannel.IsResponseReceived()) { playerResponse = currentCommChannel.GetResponse(); //end communcation and reset state currentCommChannel.EndCommuncation(); currentCommChannel = null; aiCommState = AICommunicationState.NotInCommuncation; //handle whatever the response was HandleResponse(playerResponse); } } else if (!openingDone) { Debug.LogError("about to close doors in cell opening"); maze.CloseDoorsInCell(playerCurrentCoords); SendMessageToPlayer(GameLinesTextGetter.OpeningMonologue(), oneWayCommChannel); } else if (playerCurrentCoords != player.MazeCellCoords && DistanceBetweenPlayerAndRoom(player.MazeCellCoords) < 0.4) { //neutral ending. ends on reaching the ladder if (player.MazeCellCoords == maze.exitCoords && !aiAlignmentState.ToString().StartsWith("Very")) { FlyoverMonologueEnding(); } //very friendly ending. end condition on the last room else if (aiAlignmentState == AIAlignmentState.VeryFriendly && player.MazeCellCoords.z == (maze.size.z - 1)) { maze.TurnAllLightsRed(); Debug.LogError("about to close doors in cell friendlyending"); maze.CloseDoorsInCell(player.MazeCellCoords); gameOver = true; } //the standard case. do a reaction or request else { //for the single hallway ending. close doors behind you. if (aiAlignmentState == AIAlignmentState.VeryFriendly) { Debug.LogError("about to close doors in cell friendlyending close behind"); maze.CloseDoorsInCell(playerCurrentCoords); } playerCurrentCoords = player.MazeCellCoords; if (!firstInterchangeDone) { Neutral_Request_AskPlayerToTouchCorners(); firstInterchangeDone = true; } else { if (reactToPlayer) { ExecuteRandomAction(perStateReactionList[aiAlignmentState]); //react to player next time only if VeryHostile, VeryFriendly and there are reactions left reactToPlayer = (aiAlignmentState.ToString().StartsWith("Very")) && perStateReactionList[aiAlignmentState].Count > 0; } else { if (!roomsRequestedIn.ContainsKey(playerCurrentCoords)) { ExecuteRandomAction(perStateRequestActionList[aiAlignmentState]); roomsRequestedIn[playerCurrentCoords] = true; } //on occasion, prompt a reaction from the AI on the next room reactToPlayer = (UnityEngine.Random.Range(0, 1f) < 0.75f); } } } } }
/// <summary> /// sends the given string message to the player via the given channel. /// Also sets current channel to be given channel. /// </summary> /// <param name="message"></ /// <param name="channel"></param> private void SendMessageToPlayer(string message, CommunicationChannel channel) { if (channel == null) { throw new Exception("channel was null"); } aiCommState = AICommunicationState.InCommunication; currentCommChannel = channel; channel.StartCommunicationWithPlayer(player, this, message); }
private static void SendMessage(CommunicationChannel communicationChannel, string message) { try { byte[] buffer = Encoding.UTF8.GetBytes(message); SendMessage(communicationChannel, buffer); } catch (Exception e) { } }