private void USBWrite(int opcode, byte[] payload) { if (serialPort.IsOpen) { byte[] packet = DAQPacket.Encode(opcode, payload); serialPort.Write(packet, 0, packet.Length); } }
private int USBRXProcessing(DAQPacket packet) { switch (packet.opcode) { case Opcodes.txAnalogInA: { int channel = packet.payload[0]; if (channel < 1 || channel > (analogInChannels.Length / 2)) { return(1); } if (analogInChannels[channel - 1] != null) { int sampleNum = (packet.payloadLength - 1) / 2; int[] values = new int[sampleNum]; for (int i = 0; i < sampleNum; i++) { values[i] = (packet.payload[1 + (2 * i)] << 8) + packet.payload[1 + (2 * i + 1)]; } analogInChannels[channel - 1].AddValues(values); } break; } case Opcodes.txAnalogInB: { int channel = packet.payload[0]; if (channel < 1 || channel > (analogInChannels.Length / 2)) { return(1); } channel += 8; if (analogInChannels[channel - 1] != null) { int sampleNum = (packet.payloadLength - 1) / 2; int[] values = new int[sampleNum]; for (int i = 0; i < sampleNum; i++) { values[i] = (packet.payload[1 + (2 * i)] << 8) + packet.payload[1 + (2 * i + 1)]; } analogInChannels[channel - 1].AddValues(values); } break; } } return(0); }
private void USBRXThread() { DAQPacket rxPacket = new DAQPacket(); int index = 0; int rxDataPacketLength = 0; byte[] rxDataPacket = new byte[550]; byte[] rxBuffer = new byte[1024]; while (rxUSBThreadRun) { if (serialPort.IsOpen) { int rxLength = 0; try { //rxLength = await serialPort.BaseStream.ReadAsync(rxBuffer, 0, rxBuffer.Length); rxLength = serialPort.BaseStream.Read(rxBuffer, 0, rxBuffer.Length); } catch { return; } for (int i = 0; i < rxLength; i++) { if (index == 0) { //First Byte of package is the Opcode rxDataPacket[index++] = rxBuffer[i]; } else if (index == 1) { //Second and Third byte of package is the length rxDataPacket[index++] = rxBuffer[i]; rxDataPacketLength = (rxBuffer[i] << 8); } else if (index == 2) { //Second and Third byte of package is the length rxDataPacket[index++] = rxBuffer[i]; rxDataPacketLength += rxBuffer[i]; if (rxDataPacketLength > 512) { //RX Buffer overflow index = 0; usbRXErrorCount += 1; } } else if (index < (rxDataPacketLength + 3 + 2)) { //Rest bytes are payload rxDataPacket[index++] = rxBuffer[i]; } else { //Full packet received rxPacket.Decode(rxDataPacket); if (USBRXProcessing(rxPacket) != 0) { //Packet Processing Error usbRXErrorCount += 1; } usbRXPacketCount += 1; index = 0; } } usbRXByteCount += rxLength; if (usbRXStopwatch.ElapsedMilliseconds > 1000) { usbRXDatarate = (float)usbRXByteCount; usbRXByteCount = 0; usbRXErrorRate = (float)usbRXErrorCount; usbRXErrorCount = 0; usbRXStopwatch.Restart(); } } } }