public void DisconnectOnReadByteBlockedReadAgain() { using (SerialPortStream serialSource = new SerialPortStream(SourcePort, 115200, 8, Parity.None, StopBits.One)) { serialSource.Open(); int c = serialSource.ReadByte(); Console.WriteLine("{0} byte read", c); Assert.That( () => { c = serialSource.ReadByte(); Console.WriteLine("{0} byte read again", c); }, Throws.InstanceOf <System.IO.IOException>()); // Device should still be open. Assert.That(serialSource.IsOpen, Is.True); serialSource.Close(); } }
public void DisconnectOnReadByteBlocked() { using (SerialPortStream serialSource = new SerialPortStream(SourcePort, 115200, 8, Parity.None, StopBits.One)) { serialSource.Open(); int c = serialSource.ReadByte(); Console.WriteLine("{0} byte read", c); // Device should still be open. Assert.That(serialSource.IsOpen, Is.True); serialSource.Close(); } }
public void ReadToResetWithMbcs3() { using (SerialPortStream src = new SerialPortStream(SourcePort, 115200, 8, Parity.None, StopBits.One)) using (SerialPortStream dst = new SerialPortStream(DestPort, 115200, 8, Parity.None, StopBits.One)) { src.WriteTimeout = TimeOut; src.ReadTimeout = TimeOut; dst.WriteTimeout = TimeOut; dst.ReadTimeout = TimeOut; src.Open(); Assert.That(src.IsOpen, Is.True); dst.Open(); Assert.That(dst.IsOpen, Is.True); src.Write(new byte[] { 0xE2, 0x82, 0xAC, 0x40, 0x41, 0x62 }, 0, 6); Assert.That(() => { dst.ReadLine(); }, Throws.Exception.TypeOf <TimeoutException>()); Assert.That(dst.ReadChar(), Is.EqualTo((int)'€')); Assert.That(dst.ReadByte(), Is.EqualTo(0x40)); Assert.That(dst.ReadExisting(), Is.EqualTo("Ab")); } }
public void ReadToResetWithMbcs2() { using (SerialPortStream src = new SerialPortStream(SourcePort, 115200, 8, Parity.None, StopBits.One)) using (SerialPortStream dst = new SerialPortStream(DestPort, 115200, 8, Parity.None, StopBits.One)) { src.WriteTimeout = TimeOut; src.ReadTimeout = TimeOut; dst.WriteTimeout = TimeOut; dst.ReadTimeout = TimeOut; src.Open(); Assert.That(src.IsOpen, Is.True); dst.Open(); Assert.That(dst.IsOpen, Is.True); src.Write(new byte[] { 0xE2, 0x82, 0xAC, 0x40, 0x41, 0x62 }, 0, 6); Assert.That(() => { dst.ReadLine(); }, Throws.Exception.TypeOf <TimeoutException>()); // So now we should have data in the character cache, but we'll ready a byte. Assert.That(dst.ReadByte(), Is.EqualTo(0xE2)); Assert.That(dst.ReadExisting(), Is.EqualTo("��@Ab")); } }
public void ReadToWithMbcs() { using (SerialPortStream src = new SerialPortStream(SourcePort, 115200, 8, Parity.None, StopBits.One)) using (SerialPortStream dst = new SerialPortStream(DestPort, 115200, 8, Parity.None, StopBits.One)) { src.WriteTimeout = TimeOut; src.ReadTimeout = TimeOut; dst.WriteTimeout = TimeOut; dst.ReadTimeout = TimeOut; src.Open(); Assert.That(src.IsOpen, Is.True); dst.Open(); Assert.That(dst.IsOpen, Is.True); src.Write(new byte[] { 0x61, 0xE2, 0x82, 0xAC, 0x40, 0x41 }, 0, 6); Assert.That(dst.ReadChar(), Is.EqualTo((int)'a')); Assert.That(dst.ReadByte(), Is.EqualTo((0xE2))); Assert.That(dst.ReadChar(), Is.EqualTo((int)'�')); Assert.That(dst.ReadChar(), Is.EqualTo((int)'�')); Assert.That(dst.ReadChar(), Is.EqualTo((int)'@')); Assert.That(dst.ReadChar(), Is.EqualTo((int)'A')); } }
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e) { switch (state) { case 1: int b = portStream.ReadByte(); if (b == 0) { Invoke(new VoidDel(ReceiveError)); break; } if (dataIndex >= data.Length) { state = 0; dataIndex = 0; Invoke(new VoidDel(() => { statLabel.Text = "Program transmitted"; progressBar.SetState(1); })); break; } Invoke(new VoidDel(() => progressBar.Value = dataIndex)); var value = data[dataIndex++]; if (value > 0xff) { dataAddr = value & 0x7fff; portStream.Write(new byte[] { 1 }, 0, 1); } else { portStream.Write(new byte[] { 0, (byte)(dataAddr >> 8), (byte)dataAddr++, 0, (byte)value }, 0, 5); Debug.WriteLine("Written to address: " + Convert.ToString(dataAddr, 16)); } break; default: break; } }
private bool _readInProgress = false; //TODO: this maybe better as a lock object //private void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) //{ // Task.Run(async () => // { // if (!_readInProgress) // { // _readInProgress = true; // do // { // await PacketHandler.ReadPacketAsync(IoPort); // } while (IoPort.BytesToRead > 0); // //this is necessary as some packets are sent so close together that the dataReceived event is not fired. // _readInProgress = false; // } // }); //} public async Task Connect() { IoPort.PortName = Port; InitialiseConnection(); if (IoPort.IsOpen) { await Disconnect(); } State = ConnectionState.Connecting; Console.Out.WriteLine("Connecting using Port: {0}", IoPort.PortName); await Task.Run(() => IoPort.OpenDirect()); var msg = new CommandPacket(CommandPacket.Command.TestConnection); char resp; var initialisationDateTime = DateTime.Now; var timeout = false; await msg.SendAsync(IoPort); do { resp = (char)IoPort.ReadByte(); if (DateTime.Now > initialisationDateTime.AddMilliseconds(1000)) { timeout = true; } } while (resp != 'k' && timeout == false); if (timeout == true) { State = ConnectionState.Error; throw new Exception("Connection didn't initiate properly (failed to get software version)"); } State = ConnectionState.Connected; }
private void DataReceived(object sender, SerialDataReceivedEventArgs e) { SerialPortStream sp = (SerialPortStream)sender; double temp = 0; if (sp.BytesToRead == 26) { inputChannel[0] = Convert.ToUInt32(sp.ReadByte()) << 24; inputChannel[0] = inputChannel[0] | (Convert.ToUInt32(sp.ReadByte()) << 16); inputChannel[0] = inputChannel[0] | (Convert.ToUInt32(sp.ReadByte()) << 8); inputChannel[0] = inputChannel[0] | Convert.ToUInt32(sp.ReadByte()); temp = Convert.ToDouble(inputChannel[0]); lc0.Enqueue(temp); inputChannel[0] = Convert.ToUInt32(lc0.q.Average()); inputChannel[1] = Convert.ToUInt32(sp.ReadByte()) << 24; inputChannel[1] = inputChannel[1] | (Convert.ToUInt32(sp.ReadByte()) << 16); inputChannel[1] = inputChannel[1] | (Convert.ToUInt32(sp.ReadByte()) << 8); inputChannel[1] = inputChannel[1] | Convert.ToUInt32(sp.ReadByte()); inputChannel[2] = Convert.ToUInt32(sp.ReadByte()) << 24; inputChannel[2] = inputChannel[2] | (Convert.ToUInt32(sp.ReadByte()) << 16); inputChannel[2] = inputChannel[2] | (Convert.ToUInt32(sp.ReadByte()) << 8); inputChannel[2] = inputChannel[2] | Convert.ToUInt32(sp.ReadByte()); temp = Convert.ToDouble(inputChannel[2]); pt0.Enqueue(temp); inputChannel[2] = Convert.ToUInt32(pt0.q.Average()); inputChannel[3] = Convert.ToUInt32(sp.ReadByte()) << 24; inputChannel[3] = inputChannel[3] | (Convert.ToUInt32(sp.ReadByte()) << 16); inputChannel[3] = inputChannel[3] | (Convert.ToUInt32(sp.ReadByte()) << 8); inputChannel[3] = inputChannel[3] | Convert.ToUInt32(sp.ReadByte()); inputChannel[4] = Convert.ToUInt32(sp.ReadByte()) << 24; inputChannel[4] = inputChannel[4] | (Convert.ToUInt32(sp.ReadByte()) << 16); inputChannel[4] = inputChannel[4] | (Convert.ToUInt32(sp.ReadByte()) << 8); inputChannel[4] = inputChannel[4] | Convert.ToUInt32(sp.ReadByte()); inputChannel[5] = Convert.ToUInt32(sp.ReadByte()) << 24; inputChannel[5] = inputChannel[5] | (Convert.ToUInt32(sp.ReadByte()) << 16); inputChannel[5] = inputChannel[5] | (Convert.ToUInt32(sp.ReadByte()) << 8); inputChannel[5] = inputChannel[5] | Convert.ToUInt32(sp.ReadByte()); inputChannel[6] = Convert.ToUInt32(sp.ReadByte()); inputChannel[7] = Convert.ToUInt32(sp.ReadByte()); //System.Threading.Thread.Sleep(10); writeReadDevice(); } }
private void readDevice() { double temp = 0; inputChannel[0] = Convert.ToUInt32(pressSerialPort.ReadByte()) << 24; inputChannel[0] = inputChannel[0] | (Convert.ToUInt32(pressSerialPort.ReadByte()) << 16); inputChannel[0] = inputChannel[0] | (Convert.ToUInt32(pressSerialPort.ReadByte()) << 8); inputChannel[0] = inputChannel[0] | Convert.ToUInt32(pressSerialPort.ReadByte()); temp = Convert.ToDouble(inputChannel[0]); lc0.Enqueue(temp); inputChannel[0] = Convert.ToUInt32(lc0.q.Average()); inputChannel[1] = Convert.ToUInt32(pressSerialPort.ReadByte()) << 24; inputChannel[1] = inputChannel[1] | (Convert.ToUInt32(pressSerialPort.ReadByte()) << 16); inputChannel[1] = inputChannel[1] | (Convert.ToUInt32(pressSerialPort.ReadByte()) << 8); inputChannel[1] = inputChannel[1] | Convert.ToUInt32(pressSerialPort.ReadByte()); inputChannel[2] = Convert.ToUInt32(pressSerialPort.ReadByte()) << 24; inputChannel[2] = inputChannel[2] | (Convert.ToUInt32(pressSerialPort.ReadByte()) << 16); inputChannel[2] = inputChannel[2] | (Convert.ToUInt32(pressSerialPort.ReadByte()) << 8); inputChannel[2] = inputChannel[2] | Convert.ToUInt32(pressSerialPort.ReadByte()); temp = Convert.ToDouble(inputChannel[2]); pt0.Enqueue(temp); inputChannel[2] = Convert.ToUInt32(pt0.q.Average()); inputChannel[3] = Convert.ToUInt32(pressSerialPort.ReadByte()) << 24; inputChannel[3] = inputChannel[3] | (Convert.ToUInt32(pressSerialPort.ReadByte()) << 16); inputChannel[3] = inputChannel[3] | (Convert.ToUInt32(pressSerialPort.ReadByte()) << 8); inputChannel[3] = inputChannel[3] | Convert.ToUInt32(pressSerialPort.ReadByte()); inputChannel[4] = Convert.ToUInt32(pressSerialPort.ReadByte()) << 24; inputChannel[4] = inputChannel[4] | (Convert.ToUInt32(pressSerialPort.ReadByte()) << 16); inputChannel[4] = inputChannel[4] | (Convert.ToUInt32(pressSerialPort.ReadByte()) << 8); inputChannel[4] = inputChannel[4] | Convert.ToUInt32(pressSerialPort.ReadByte()); inputChannel[5] = Convert.ToUInt32(pressSerialPort.ReadByte()) << 24; inputChannel[5] = inputChannel[5] | (Convert.ToUInt32(pressSerialPort.ReadByte()) << 16); inputChannel[5] = inputChannel[5] | (Convert.ToUInt32(pressSerialPort.ReadByte()) << 8); inputChannel[5] = inputChannel[5] | Convert.ToUInt32(pressSerialPort.ReadByte()); inputChannel[6] = Convert.ToUInt32(pressSerialPort.ReadByte()); inputChannel[7] = Convert.ToUInt32(pressSerialPort.ReadByte()); writeReadDevice(); }
private async Task <EnOceanPacket> ReadFrameInternal() { try { var firstChar = (byte)_stream.ReadByte(); await Task.Delay(100); if (firstChar == EnOcean.SyncByte) { var dataLen = new byte[2]; var dataLenRead = await _stream.ReadAsync(dataLen, 0, 2); if (dataLenRead == 2) { var dataLenShort = BitConverter.ToUInt16(dataLen.Reverse().ToArray(), 0); var optLen = (byte)_stream.ReadByte(); var packetType = (byte)_stream.ReadByte(); var crc8Header = (byte)_stream.ReadByte(); var header = new byte[] { firstChar, dataLen[0], dataLen[1], optLen, packetType, crc8Header }; var data = new byte[dataLenShort]; Memory <byte> dataMemory = new Memory <byte>(data); var read = await _stream.ReadAsync(dataMemory); if (read == dataLenShort) { var optData = new byte[optLen]; Memory <byte> optMemory = new Memory <byte>(optData); read = await _stream.ReadAsync(optMemory); if (read == optLen) { var crcData = (byte)_stream.ReadByte(); var packet = EnOceanPacket.Parse(new Memory <byte>(header), dataMemory, optMemory, crcData); Logger.Logger.Instance.LogHexIn(packet.RawData); return(packet); } } else { Logger.Logger.Instance.LogDebug($"In buffer length to short {read}/{dataLenShort}"); } } else { Logger.Logger.Instance.LogDebug($"Could not read length of package"); } } else { Logger.Logger.Instance.LogDebug($"Invalid sync byte received {firstChar}"); if (_stream.BytesToRead > 0) { return(await ReadFrameInternal()); } } } catch (IOException ioe) { Logger.Logger.Instance.LogError($"Could not read frame {ioe}", ioe); Close(); Thread.Sleep(100); Open(); } catch (Exception e) { Logger.Logger.Instance.LogError($"Could not read frame {e}", e); } return(null); }
private async Task <MBusFrame> ReadFrameInternal() { try { int firstChar = _stream.ReadByte(); if (firstChar == MBus.ShortFrameStart) { Logger.LogDebug("Start parsing short frame..."); Thread.Sleep(100); byte[] shortFrame = new byte[5]; shortFrame[0] = (byte)firstChar; var bytesRead = await _stream.ReadAsync(shortFrame, 1, 4); if (bytesRead != 4) { Logger.LogDebug($"Could not parse short frame (read bytes {bytesRead}/4)"); return(null); } Logger.LogDebug("Short frame in..."); Logger.LogHexIn(shortFrame); var frame = MBusFrame.FromByteArray(MBusFrameType.ShortFrame, Logger, shortFrame); return(frame); } if (firstChar == MBus.SingleCharFrame) { Logger.LogDebug("Ack frame in..."); return(new AckFrame()); } if (firstChar == MBus.ControlFrameLongFrameStart) { Logger.LogDebug("Start parsing long frame..."); Thread.Sleep(200); byte[] headerBuffer = new byte[4]; headerBuffer[0] = (byte)firstChar; var bytesRead = await _stream.ReadAsync(headerBuffer, 1, 3); Logger.LogHexIn(headerBuffer); if (bytesRead != 3) { Logger.LogDebug($"Could not read header...read {bytesRead}/3"); return(null); } if (headerBuffer[0] == 0x68 && headerBuffer[0] == headerBuffer[3] && headerBuffer[1] == headerBuffer[2]) { int lengthToRead = headerBuffer[1] + 2; //read with checksum and stop byte byte[] data = new byte[lengthToRead]; var dataMemory = new Memory <byte>(data); bytesRead = await _stream.ReadAsync(dataMemory); Logger.LogHexIn(dataMemory); if (bytesRead != lengthToRead) { Logger.LogDebug($"Invalid length of read data...({bytesRead}/{lengthToRead})"); return(null); //invalid length of data read } if (data[data.Length - 1] != 0x16) { Logger.LogDebug("Invalid stop byte..."); return(null); //invalid stop byte } var packageType = headerBuffer[2] == 3 ? MBusFrameType.ControlFrame : MBusFrameType.LongFrame; return(MBusFrame.FromSpan(packageType, Logger, headerBuffer.AsSpan(), dataMemory.Span)); } } } catch (IOException ioe) { Logger.LogError($"Could not read frame {ioe}", ioe); Close(); Thread.Sleep(100); Open(); } catch (Exception e) { Logger.LogError($"Could not read frame {e}", e); } return(null); }
public static void Main(string[] args) { if (args.Length != 1) { Console.WriteLine("Usage: PMS5003.exe <port>"); return; } var portName = args[0]; using (var port = new SerialPortStream(portName)) { port.BaudRate = 9600; port.Parity = Parity.None; port.Open(); while (true) { // search for header byte1 while (port.ReadByte() != 0x42) { } if (port.ReadByte() != 0x4D) { Console.WriteLine("WARNING: Bad header"); continue; } // Frame length var fmLength = GetShort((byte)port.ReadByte(), (byte)port.ReadByte()); // Datas var buffer = new byte[fmLength]; port.Read(buffer, 0, buffer.Length); // Read as ushort var data = new ushort[fmLength / 2]; for (int i = 0; i < buffer.Length; i += 2) { data[i / 2] = GetShort(buffer[i], buffer[i + 1]); } // Checksum ushort receiveSum = 0x42 + 0x4D + 28; for (byte i = 0; i < (buffer.Length - 2); i++) { receiveSum += buffer[i]; } if (receiveSum - data[13] != 0) { Console.WriteLine("WARNING: Bad Checksum"); continue; } Console.WriteLine($"PM1.0 ug / m3: {data[0]}"); Console.WriteLine($"PM2.5 ug / m3: {data[1]}"); Console.WriteLine($"PM10 ug/ m3: {data[2]}"); Console.WriteLine($"PM1.0 ug / m3(atmos env): {data[3]}"); Console.WriteLine($"PM2.5 ug / m3(atmos env): {data[4]}"); Console.WriteLine($"PM10 ug/ m3(atmos env): {data[5]}"); Console.WriteLine($"> 0.3um in 0.1L air: {data[6]}"); Console.WriteLine($"> 0.5um in 0.1L air: {data[7]}"); Console.WriteLine($"> 1.0um in 0.1L air: {data[8]}"); Console.WriteLine($"> 2.5um in 0.1L air: {data[9]}"); Console.WriteLine($"> 5.0um in 0.1L air: {data[10]}"); Console.WriteLine($"> 10um in 0.1L air: {data[11]}"); } port.Close(); } }
public int WriteBytes(DeviceAddress address, byte[] bit) { var data = WriteMultipleRegister(address.Start, bit); _serialPort.Write(data, 0, data.Length); _serialPort.ReadByte(); var chr = _serialPort.ReadByte(); return((chr & 0x80) > 0 ? -1 : 0); }
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e) { switch (state) { case 1: int b = portStream.ReadByte(); //Debug.WriteLine("Received: " + b); if (b == 0) { Invoke(new VoidDel(ReceiveError)); break; } if (seg > 8191) { state = 2; seg = 0; Invoke(new VoidDel(() => statLabel.Text = "Checking data correctness")); portStream.ReceivedBytesThreshold = 8192; portStream.Write(new byte[] { 0, 0, 0, 0x20, 0 }, 0, 5); break; } Invoke(new VoidDel(() => progressBar.Value = seg)); if (data[seg] != oldData[seg]) { portStream.Write(new byte[] { 1, (byte)(seg >> 8), (byte)seg, 0 }, 0, 4); portStream.Write(data, seg, 1); Debug.WriteLine("Written to address: " + Convert.ToString(seg, 16)); } else { portStream.Write(new byte[] { 3 }, 0, 1); //Debug.WriteLine("Omitting address " + seg); } while (++seg < 8192 && data[seg] == oldData[seg]) { ; } break; case 2: state = 0; var buf = new byte[8192]; portStream.Read(buf, 0, 8192); if (buf.SequenceEqual(data)) { Invoke(new VoidDel(() => { statLabel.Text = "Transmitted successfully"; progressBar.SetState(1); })); } else { Invoke(new VoidDel(() => { statLabel.Text = "Error: Received incorrect data"; progressBar.SetState(2); })); } portStream.ReceivedBytesThreshold = 1; Invoke(new VoidDel(() => { transmitButton.Enabled = true; chipSelect.Enabled = true; portSelect.Enabled = true; checkDiffButton.Enabled = true; })); break; case 3: state = 0; var dBuf = new byte[8192]; portStream.Read(dBuf, 0, 8192); int diff = 0; for (int i = 0; i < 8192; i++) { if (dBuf[i] != data[i]) { diff++; Debug.WriteLine(Convert.ToString(i, 16) + ": " + Convert.ToString(data[i], 16) + ", old: " + Convert.ToString(dBuf[i], 16)); } } portStream.ReceivedBytesThreshold = 1; Invoke(new VoidDel(() => { statLabel.Text = "Data differs by " + diff + "/8192 bytes."; transmitButton.Enabled = true; chipSelect.Enabled = true; portSelect.Enabled = true; checkDiffButton.Enabled = true; })); break; case 4: state = 1; portStream.Read(oldData, 0, 8192); portStream.ReceivedBytesThreshold = 1; Invoke(new VoidDel(() => { statLabel.Text = "Transmitting"; })); portStream.Write(new byte[] { 2, 0 }, 0, 2); break; default: break; } }