public Serial(SerialPortSettings serialPortSettings, IDisk disk, ILogger log, CancellationTokenSource cancelTokenSource, bool compressionIsEnabled) { _localDisk = disk; _logger = log; _listenTokenSource = cancelTokenSource; _compressionIsEnabled = compressionIsEnabled; _isRLERun = false; try { _serialPort = InitializeSerialPort(serialPortSettings); _serialPort.Open(); _serialPort.DiscardOutBuffer(); _serialPort.DiscardInBuffer(); } catch (Exception portException) when(portException is IOException || portException is UnauthorizedAccessException) { _logger.LogException(portException, $"Error opening serial port {serialPortSettings.PortName}"); throw; } _state = ReceiverState.ReceiveStartMagic; StartListening(); }
/// <summary> /// Opens the serial port. /// </summary> /// <param name="commPort">The comm port.</param> private void OpenSerialPort(string commPort) { lock (this.portLock) { // Open the serial port connection this.serialPort = new SerialPort() { PortName = commPort, BaudRate = BAUDRATE, DataBits = DATABITS, StopBits = STOPBITS, Parity = PARITY, WriteTimeout = WRITETIMEOUT, Handshake = HANDSHAKE }; Trace.TraceInformation("{0}.OpenSerialPort: CommPort={1}", CLASSNAME, this.serialPort.PortName); try { this.serialPort.Open(); } catch (Exception ex) { Trace.TraceError("{0}.OpenSerialPort: CommPort={1} Exception={2}", CLASSNAME, this.serialPort.PortName, ex.GetBaseException()); throw; } this.serialBuffer = new byte[BUFFERSIZE]; this.bufferPosition = 0; this.receiverState = ReceiverState.Waiting; this.serialPort.DataReceived += this.SerialPort_DataReceived; this.serialPort.ErrorReceived += this.SerialPort_ErrorReceived; GC.SuppressFinalize(this.serialPort.BaseStream); // Work around, see http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/8a1825d2-c84b-4620-91e7-3934a4d47330 } // end lock }
public override void Send(byte[] data, string to = "") { try { var endpoint = IPEndPoint.Parse(to); var state = new ReceiverState { Port = endpoint.Port, Socket = ServerSocket, Ip = endpoint.Address.ToString() }; ServerSocket.BeginSendTo(data, 0, data.Length, SocketFlags.None, endpoint, OnSendToCallback, state); OnReportingStatus(StatusCode.Info, $"Started sending {data.Length} bytes to {endpoint} via UDP socket"); } catch (ObjectDisposedException) { } catch (SocketException socketException) { OnCaughtException(socketException, EventCode.Send); } catch (Exception e) { OnCaughtException(e, EventCode.Other); } }
/// <summary> /// Performs k many 1-out-of-2 OTs on k bits for the receiver, where k is the security parameter, using the base OT implementation. /// /// These are subsequently expanded into m many 1oo2 OTs on arbitrarily long messages /// by the ReceiveAsync method, where m is only bounded by the amount of secure randomness the random /// oracle implementation can produce. /// </summary> public async Task ExecuteReceiverBaseOTAsync() { _receiverState = new ReceiverState(); // generating _securityParameter many pairs of random seeds of length _securityParameter Pair <byte[]>[] seeds = new Pair <byte[]> [SecurityParameter]; for (int k = 0; k < SecurityParameter; ++k) { seeds[k] = new Pair <byte[]>( RandomNumberGenerator.GetBits(SecurityParameter).ToBytes(), RandomNumberGenerator.GetBits(SecurityParameter).ToBytes() ); } // base OTs as _sender_ with the seeds as inputs int requiredBytes = BitArray.RequiredBytes(SecurityParameter); Task sendTask = _baseOT.SendAsync(seeds, SecurityParameter, requiredBytes); // initializing a random oracle based on each seed _receiverState.SeededRandomOracles = new Pair <IEnumerable <byte> > [SecurityParameter]; for (int k = 0; k < SecurityParameter; ++k) { _receiverState.SeededRandomOracles[k] = new Pair <IEnumerable <byte> >( RandomOracleProvider.Create().Invoke(seeds[k][0]), RandomOracleProvider.Create().Invoke(seeds[k][1]) ); } ; await sendTask; }
/// <summary> /// Closes the serial port. /// </summary> private void CloseSerialPort() { lock (this.portLock) { Trace.TraceInformation("{0}.CloseSerialPort: CommPort={1}", CLASSNAME, this.serialPort.PortName); if (this.serialPort != null) { this.serialPort.DataReceived -= this.SerialPort_DataReceived; this.serialPort.ErrorReceived -= this.SerialPort_ErrorReceived; if (this.serialPort.IsOpen) { try { this.serialPort.Close(); } catch (IOException) { } catch (Exception ex) { Trace.TraceError("{0}.CloseSerialPort: CommPort={1} Exception={2}", CLASSNAME, this.serialPort.PortName, ex.GetBaseException()); throw; } } this.serialPort.Dispose(); this.serialPort = null; this.serialBuffer = null; this.bufferPosition = 0; this.receiverState = ReceiverState.NoDeviceFound; } } // end lock }
private void Receive(Socket socket) { ReceiverState state = new ReceiverState(); state.WorkSocket = socket; socket.BeginReceive(state.Buffer, 0, state.Buffer.Length, 0, new AsyncCallback(ReceiveCallback), state); }
private void ReceiveCallback(IAsyncResult ar) { ReceiverState receiverState = (ReceiverState)ar.AsyncState; try { if (isRouterUp) { int bytesRead = receiverState.WorkSocket.EndReceive(ar); NetworkPackage networkPackage = DeserializeMessage(receiverState, bytesRead); if (networkPackage.helloMessage) { TimeStamp.WriteLine("Connected to cloud"); } if (networkPackage.managementMessage) { ProcessReceivedManagementMessage(networkPackage); } if (!networkPackage.managementMessage && !networkPackage.helloMessage) { ProcessReceivedClientMessage(networkPackage); } } else { Console.WriteLine("Router is down. Message discarded"); } receiverState.WorkSocket.BeginReceive(receiverState.Buffer, 0, receiverState.Buffer.Length, 0, new AsyncCallback(ReceiveCallback), receiverState); } catch (Exception e) { TimeStamp.WriteLine(e.Message); } }
public void changefinishstate() { receiverState = ReceiverState.LoggingFinished; Debug.Log("state : Finished"); onLoggingFinished.Invoke(logCollection); // Reset receiverState to Standby. receiverState = ReceiverState.Standby; }
public void Stop() { logger.Debug("RtpReceiver::Stop()"); if (state == ReceiverState.Running) { state = ReceiverState.Closing; } }
private void Send(Socket socket, NetworkPackage received) { ReceiverState state = new ReceiverState(); state.WorkSocket = socket; state.Buffer = SerializeMessage(received); socket.BeginSend(state.Buffer, 0, state.Buffer.Length, 0, new AsyncCallback(SendCallback), state); }
public void OnDisable() { StopCoroutine(ReadIncomingData()); receiverState = ReceiverState.Standby; returnbutton.interactable = true; isLoggingStarted = false; connectToArduino.CloseConnection(); }
public TwoChoicesExtendedObliviousTransferChannelBase(ITwoChoicesObliviousTransferChannel baseOT, int securityParameter, CryptoContext cryptoContext) { RandomNumberGenerator = new ThreadsafeRandomNumberGenerator(cryptoContext.RandomNumberGenerator); RandomOracleProvider = new HashRandomOracleProvider(cryptoContext.HashAlgorithmProvider); SecurityParameter = securityParameter; _baseOT = baseOT; _senderState = new SenderState(); _receiverState = new ReceiverState(); }
public void TransmissionExit() { if (state == ReceiverState.TOUCHING) { OnTransmissionExit.Invoke(); DisableGlow(); state = ReceiverState.IDLE; } }
public void publishlog() { receiverState = ReceiverState.DatabaseSending; Debug.Log("state : sending"); LoggingManager.SaveAllLogs(true, TargetType.MySql); pushdata.Invoke(logCollection); // Reset receiverState to Standby. receiverState = ReceiverState.Standby; }
public void ReceiveTransmission() { OnReceiveTransmission.Invoke(); // Call all the functions under this event in the editor state = ReceiverState.ACTIVATED; //isAlreadyActivated = true; // Toggle this on, so that it can't get activated again (temp to avoid multiple physics calls per frame) EnableGlow(Color.green); // For debugging //this.GetComponent<MeshRenderer>().material.color = Color.green; }
public void Send(NetworkPackage networkPackage) { sendDone.Reset(); ReceiverState state = new ReceiverState(); state.WorkSocket = clientSocket; state.Buffer = SerializeMessage(networkPackage); clientSocket.BeginSend(state.Buffer, 0, state.Buffer.Length, 0, new AsyncCallback(SendCallback), state); sendDone.WaitOne(); }
private void SendBIOSParameterBlock() { _logger.Log($"Sending BIOS parameter block.", LoggingLevel.Debug); _serialPort.BaseStream.Write(_localDisk.Parameters.BIOSParameterBlock, 0, _localDisk.Parameters.BIOSParameterBlock.Length); _state = ReceiverState.ReceiveStartMagic; _logger.Log($"Receiver state: {_state}", LoggingLevel.Debug); }
public void TransmissionEnter() { if (state == ReceiverState.IDLE) { OnTransmissionEnter.Invoke(); EnableGlow(Color.yellow); AudioManager.instance.PlayRandomSFX(.5f, "successmirror1", "successmirror2", "successmirror3"); state = ReceiverState.TOUCHING; } }
private NetworkPackage DeserializeMessage(ReceiverState receiverState, int byteRead) { using (var memoryStream = new MemoryStream()) { var bf = new BinaryFormatter(); memoryStream.Write(receiverState.Buffer, 0, byteRead); memoryStream.Seek(0, SeekOrigin.Begin); NetworkPackage obj = (NetworkPackage)bf.Deserialize(memoryStream); return(obj); } }
private void Close() { logger.Debug("RtpTcpReceiver::Close()"); if (socket != null) { socket.Close(); socket = null; } state = ReceiverState.Closed; }
private void SendCallback(IAsyncResult ar) { try { ReceiverState state = (ReceiverState)ar.AsyncState; state.WorkSocket.EndSend(ar); sendDone.Set(); } catch (Exception e) { Console.WriteLine(e.ToString()); } }
public void OnConnect() { if (_commandsSenderThread != null) { throw new InvalidOperationException("Already connected"); } _receiverState = ReceiverState.WaitingForFirstByte; StopWaitingForResponse(); _commandsQueue.Clear(); _commandsSenderThread = new Thread(() => CommandsSenderThreadEntryPoint()); _commandsSenderThread.Start(); }
public Task Start() { logger.Debug("RtpUdpReceiver::Start()"); if (state != ReceiverState.Initialized) { throw new InvalidOperationException("Invalid state " + state); } return(Task.Run(() => { logger.Debug("UdpReceiver thread started..."); state = ReceiverState.Running; try { byte[] buf = new byte[16256]; while (state == ReceiverState.Running) { int bytesReceived = socket.Receive(buf, SocketFlags.None); if (bytesReceived > 0) { //byte[] udp = new byte[bytesReceived]; //Array.Copy(buf, udp, bytesReceived); //DataReceived(buf, bytesReceived); RtpPacket rtpPacket = RtpPacket.Create(buf, bytesReceived, session); if (rtpPacket != null) { OnRtpPacketReceived(rtpPacket); } } } } catch (ObjectDisposedException) { logger.Warn("UdpReceiver::ObjectDisposedException"); } catch (Exception ex) { logger.Error(ex); } finally { Close(); logger.Debug("UdpReceiver thread stopped..."); } })); }
public void Open(NetworkSettings settings) { if (state != ReceiverState.Closed) { throw new InvalidOperationException("Invalid receiver state " + state); } var address = settings.LocalAddr; var port = settings.LocalPort; var ttl = settings.MulticastTimeToLive; logger.Debug("RtpUdpReceiver::Open(...) " + address + " " + port + " " + ttl); try { IPAddress localAddress = IPAddress.Parse(address); bool isMulicast = Utils.NetTools.IsMulticastIpAddr(localAddress); RemoteEndpoint = new IPEndPoint(localAddress, port); LocalEndpoint = new IPEndPoint(IPAddress.Any, port); socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); socket.ReceiveBufferSize = 100 * 1024;//int.MaxValue;//32 * 1024 * 1024; socket.Bind(LocalEndpoint); if (isMulicast) { mcastOption = new MulticastOption(RemoteEndpoint.Address, LocalEndpoint.Address); socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, mcastOption); socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, ttl); } state = ReceiverState.Initialized; logger.Info("Client started: " + LocalEndpoint.ToString() + " " + RemoteEndpoint.ToString()); } catch (Exception ex) { logger.Error(ex); Close(); throw; } }
public bool VerifyState(BrokerState expectedBrokerState, ReceiverState expectedSymbolState, SymbolInfo symbol, int timeout) { if (debug) { log.Debug("VerifyFeed"); } if (SyncTicks.Enabled) { tickSync = SyncTicks.GetTickSync(symbol.BinaryIdentifier); } long startTime = Factory.TickCount; count = 0; TickBinary binary = new TickBinary(); while (Factory.TickCount - startTime < timeout * 1000) { if (propagateException != null) { throw propagateException; } try { if (!tickQueue.TryDequeue(ref binary)) { Thread.Sleep(100); } else { if (SyncTicks.Enabled) { tickSync.RemoveTick(); } } } catch (QueueException ex) { if (HandleQueueException(ex)) { break; } } if (brokerState == expectedBrokerState && receiverState == expectedSymbolState) { return(true); } } return(false); }
public void Close() { if (socket != null) { if (mcastOption != null) { socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.DropMembership, mcastOption); } socket.Close(); socket = null; } state = ReceiverState.Closed; }
private void AcceptCallback(IAsyncResult ar) { // Signal the main thread to continue. AllDone.Set(); // Get the socket that handles the client request. Socket listener = (Socket)ar.AsyncState; Socket handler = listener.EndAccept(ar); // Create the state object. ReceiverState state = new ReceiverState(); state.WorkSocket = handler; handler.BeginReceive(state.Buffer, 0, ReceiverState.BufferSize, 0, new AsyncCallback(ReadCallback), state); }
private bool HandleQueueException(QueueException ex) { log.Notice("QueueException: " + ex.EntryType); switch (ex.EntryType) { case EventType.StartHistorical: receiverState = ReceiverState.Historical; isRealTime = false; break; case EventType.EndHistorical: receiverState = ReceiverState.Ready; isRealTime = false; break; case EventType.StartRealTime: receiverState = ReceiverState.RealTime; isRealTime = true; break; case EventType.EndRealTime: receiverState = ReceiverState.Ready; isRealTime = false; break; case EventType.StartBroker: brokerState = BrokerState.Connected; isRealTime = true; break; case EventType.EndBroker: brokerState = BrokerState.Disconnected; isRealTime = false; break; case EventType.Terminate: receiverState = ReceiverState.Stop; isRealTime = false; return(true); default: throw new ApplicationException("Unexpected QueueException: " + ex.EntryType); } return(false); }
private void ReadCallback(IAsyncResult ar) { // Odbiór pakietu try { ReceiverState receiverState = (ReceiverState)ar.AsyncState; Socket handler = receiverState.WorkSocket; int bytesRead = handler.EndReceive(ar); NetworkPackage received = Deserialize(receiverState, bytesRead); ProcessPackageAndResponse(handler, received); handler.BeginReceive(receiverState.Buffer, 0, receiverState.Buffer.Length, 0, new AsyncCallback(ReadCallback), receiverState); } catch (Exception e) { } }
private void ReceiveCRC32(byte data) { if (_receivedDataCounter == 0) { _logger.Log($"Receiving CRC32...", LoggingLevel.Debug); _receiverDataIndex = 0; _receivedCRC32 = 0; } _receivedCRC32 = (_receivedCRC32 << 8) + data; _receiverDataIndex++; Console.Write($"\rReceived [{_receiverDataIndex} / 4] CRC32 bytes"); if (_receiverDataIndex == 4) { Console.WriteLine(); var calculatedCRC32 = CRC32.CalculateCRC32(_receiverDataBuffer); if (calculatedCRC32 == _receivedCRC32) { _logger.Log($"CRC32 match. Local:{calculatedCRC32} Remote:{_receivedCRC32}", LoggingLevel.Debug); _serialPort.BaseStream.WriteByte(Flags.CRC32Match); _localDisk.WriteSectors(_receiverDataBuffer.Length, (int)_receivedSectorIndex, _receiverDataBuffer); _state = ReceiverState.ReceiveStartMagic; } else { _logger.Log($"CRC32 mismatch. Local:{calculatedCRC32} Remote:{_receivedCRC32}", LoggingLevel.Debug); _serialPort.BaseStream.WriteByte(Flags.CRC32Mismatch); _state = ReceiverState.ReceiveData; } _receivedDataCounter = -1; _logger.Log($"Receiver state: {_state}", LoggingLevel.Debug); } }
/// <summary> /// Opens the serial port. /// </summary> /// <param name="commPort">The comm port.</param> private void OpenSerialPort(string commPort) { lock (this.portLock) { // Open the serial port connection this.serialPort = new SerialPort() { PortName = commPort, BaudRate = BAUDRATE, DataBits = DATABITS, StopBits = STOPBITS, Parity = PARITY, WriteTimeout = WRITETIMEOUT, Handshake = HANDSHAKE }; Trace.TraceInformation("{0}.OpenSerialPort: CommPort={1}", CLASSNAME, this.serialPort.PortName); try { this.serialPort.Open(); } catch (Exception ex) { Trace.TraceError("{0}.OpenSerialPort: CommPort={1} Exception={2}", CLASSNAME, this.serialPort.PortName, ex.GetBaseException()); throw; } this.serialBuffer = new byte[BUFFERSIZE]; this.bufferPosition = 0; this.receiverState = ReceiverState.Waiting; this.serialPort.DataReceived += this.SerialPort_DataReceived; this.serialPort.ErrorReceived += this.SerialPort_ErrorReceived; GC.SuppressFinalize(this.serialPort.BaseStream); // Work around, see http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/8a1825d2-c84b-4620-91e7-3934a4d47330 } // end lock }
/// <summary> /// Closes the serial port. /// </summary> private void CloseSerialPort() { lock (this.portLock) { Trace.TraceInformation("{0}.CloseSerialPort: CommPort={1}", CLASSNAME, this.serialPort.PortName); if (this.serialPort != null) { this.serialPort.DataReceived -= this.SerialPort_DataReceived; this.serialPort.ErrorReceived -= this.SerialPort_ErrorReceived; if (this.serialPort.IsOpen) { try { this.serialPort.Close(); } catch (IOException) { } catch (Exception ex) { Trace.TraceError("{0}.CloseSerialPort: CommPort={1} Exception={2}", CLASSNAME, this.serialPort.PortName, ex.GetBaseException()); throw; } } this.serialPort.Dispose(); this.serialPort = null; this.serialBuffer = null; this.bufferPosition = 0; this.receiverState = ReceiverState.NoDeviceFound; } } // end lock }
public virtual void SetReady() { _state = ReceiverState.Ready; _event.Set(); }
public virtual void SetError(string msg) { _errorMessage = msg; _state = ReceiverState.Error; _event.Set(); }
public virtual void SetClosed() { _state = ReceiverState.Closed; _event.Set(); }
/// <summary> /// Handles the ErrorReceived event of the serialPort control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.IO.Ports.SerialErrorReceivedEventArgs"/> instance containing the event data.</param> private void SerialPort_ErrorReceived(object sender, SerialErrorReceivedEventArgs e) { this.receiverState = ReceiverState.Waiting; }
/// <summary> /// Handles the DataReceived event of the serialPort control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.IO.Ports.SerialDataReceivedEventArgs"/> instance containing the event data.</param> private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { // Data format: STX COUNT DATA ... this.checkSum ETX DataPacketReceivedEventArgs eventData = null; lock (this.portLock) { try { while (this.serialPort.BytesToRead > 0) { byte data = (byte)this.serialPort.ReadByte(); switch (this.receiverState) { case ReceiverState.Waiting: if (data == 0x02) { this.receiverState = ReceiverState.PacketLength; } break; case ReceiverState.PacketLength: this.checkSum = data; this.dataLength = data - 1; this.bufferPosition = 0; this.serialBuffer.Initialize(); this.receiverState = ReceiverState.PacketData; break; case ReceiverState.PacketData: if (this.bufferPosition < this.dataLength) { this.serialBuffer[this.bufferPosition++] = data; this.checkSum ^= data; } if (this.bufferPosition == this.dataLength) { this.receiverState = ReceiverState.checkSum; } break; case ReceiverState.checkSum: if (this.checkSum != data) { Trace.TraceWarning("{0}.SerialPort_DataReceived: this.checkSum mismatch. Expected={1} Actual={2}", CLASSNAME, this.checkSum, data); this.receiverState = ReceiverState.Waiting; } else { this.receiverState = ReceiverState.Received; } break; case ReceiverState.Received: if (data == 0x03) { // We got a message! eventData = new DataPacketReceivedEventArgs() { CommPort = this.serialPort.PortName, DataLength = this.dataLength, DataPacket = new byte[this.bufferPosition] }; Array.Copy(this.serialBuffer, 0, eventData.DataPacket, 0, this.bufferPosition); this.receiverState = ReceiverState.Waiting; } break; default: Trace.TraceError("{0}.SerialPort_DataReceived: Unknown receive state, resetting state"); this.receiverState = ReceiverState.Waiting; break; } } } catch (InvalidOperationException ex) { Trace.TraceError("{0}.SerialPort_DataReceived: CommPort={1} Exception={2}", CLASSNAME, this.serialPort.PortName, ex.GetBaseException()); } } // end lock // Fire event if we have data (we are outside our lock here) if (eventData != null) { this.OnDataPacketReceived(eventData); } }