public byte[] ReadMemoryCardFrame(ushort frameNumber) { // Split the 16-bit frame number into two bytes _readFrameCommand[8] = (byte)(frameNumber >> 8); _readFrameCommand[9] = (byte)(frameNumber & 0xFF); // Output a command to request the desired frame int bytesWritten; LastErrorCode = _writer.Write(_readFrameCommand, Timeout, out bytesWritten); if (LastErrorCode != ErrorCode.None || bytesWritten != ReadCommandLength) { return(null); } // Read the frame data from the memory card int bytesRead; LastErrorCode = _reader.Read(_buffer, Timeout, out bytesRead); if (LastErrorCode != ErrorCode.None || bytesRead != ReadCommandLength || _buffer[0] != 0x55 || _buffer[1] != 0x5A) { return(null); } // Strip the header data and return the requested frame byte[] frame = new byte[128]; Array.Copy(_buffer, 14, frame, 0, 128); return(frame); }
private void timer1_Tick(object sender, EventArgs e) { if (connected == true) { try { usb_command[0] = 1; ec = writer.Write(usb_command, 1000, out actual_length); ec = reader.Read(usb_command, 1000, out actual_length); if (usb_command[0] == 0xCE && usb_command[1] == 0xED) { timer1.Enabled = false; mode = 4; backgroundWorker1.RunWorkerAsync(); } else { Scan_b.Enabled = true; DumpRAM_b.Enabled = false; DumpROM_b.Enabled = false; WriteRAM_b.Enabled = false; Banks_l.Text = "Banks: "; MBC_l.Text = "MBC: "; RAM_l.Text = "RAM Size: "; Size_l.Text = "Size:"; Title_l.Text = "Title:"; } } catch (Exception ex) { MessageBox.Show((ec != ErrorCode.None ? ec + ":" : String.Empty) + ex.Message); } } }
public void CollectOscillData() { byte[] sendArray = new byte[2]; byte[] recieveAr = new byte[64]; sendArray[0] = Konstants.COLLECT_OSC_DATA; writer.Write(sendArray, 1000, out int out_l); reader.Read(recieveAr, 1000, out out_l); // we need to fill 256 by 64. // so 'x' is counter for DoneArray int x = 0; for (int i = 0; i < 4; i++) { sendArray[0] = Konstants.READ_OSC_DATA; sendArray[1] = (byte)i; writer.Write(sendArray, 1000, out out_l); reader.Read(recieveAr, 1000, out out_l); for (int j = 0; j < 64; j++, x++) { DoneArray[x] = recieveAr[j]; } } }
/// <summary> /// 打印文本 /// </summary> /// <param name="mess"></param> /// <returns></returns> public int PrintString(string mess) { int err = 0; ErrorCode ec = ErrorCode.None; if (!String.IsNullOrEmpty(mess) && MyUsbDevice.IsOpen) { byte[] OutBuffer;//数据 int BufferSize; Encoding targetEncoding; //将[UNICODE编码]转换为[GB码],仅使用于简体中文版mobile targetEncoding = Encoding.GetEncoding(0); //得到简体中文字码页的编码方式,因为是简体中文操作系统,参数用0就可以,用936也行。 BufferSize = targetEncoding.GetByteCount(mess); //计算对指定字符数组中的所有字符进行编码所产生的字节数 OutBuffer = new byte[BufferSize]; OutBuffer = targetEncoding.GetBytes(mess); //将指定字符数组中的所有字符编码为一个字节序列,完成后outbufer里面即为简体中文编码 int bytesWritten; ec = Writer.Write(OutBuffer, 2000, out bytesWritten); if (ec != ErrorCode.None) { err = (int)PrintError.SendFailure; return(err); } else if (bytesWritten != OutBuffer.Length) { err = (int)PrintError.SendFailure; return(err); } byte[] readBuffer = new byte[1024]; while (ec == ErrorCode.None) { int bytesRead; // If the device hasn't sent data in the last 100 milliseconds, // a timeout error (ec = IoTimedOut) will occur. ec = Reader.Read(readBuffer, 100, out bytesRead); if (bytesRead == 0) { } } err = 1; return(err); } else { err = (int)PrintError.SendNull; return(err); } }
/// <summary> /// Read single byte from slave, send ACK /// </summary> /// <returns>Byte from slave</returns> public byte ReadByteAck() { byte[] r = new byte[1]; var read_command = I2CcommandBuilder.ReadCommandACK(); Write(read_command); var err = reader.Read(r, 0, 1, I2CTimeout, out int transferLength); if (err != ErrorCode.Ok || transferLength != 1) { throw new ReadException(err); } return(r[0]); }
private void readUSBHID() { byte[] buffReadPolling = new byte[rxBuferSize]; int rxLength = 0; ErrorCode reazRead; while (true) { if (!setStetOffStream) { return; } getStetOffStream = true; try { reazRead = reader.Read(buffReadPolling, 50, out rxLength); } catch { return; } if (rxLength != 0) { libUSBRxCallback(buffReadPolling, rxLength); } getStetOffStream = false; } }
public static void Update(Record Record) { if (MyUsbDevice == null) { /* we failed to connect to M4ATX device, nothing to do here */ return; } UsbEndpointWriter writer = MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep01); // specify data to send ec = writer.Write(new byte[] { 0x81, 0x00 }, 5000, out bytesWritten); if (ec != ErrorCode.None) { throw new Exception("M4ATX: Error sending command: " + ec); } // open read endpoint 1. UsbEndpointReader reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01); // If the device hasn't sent data in the last 5 seconds, // a timeout error (ec = IoTimedOut) will occur. reader.Read(readBuffer, 3000, out bytesRead); if (ec != ErrorCode.None || bytesRead != readBuffer.Length) { var msg = string.Format("M4ATX: Error reading result, error {0}, got {1} bytes", ec, bytesRead); throw new Exception(msg); } Record.Set(Record.DataPoint.M4ATXTemperature, readBuffer[12]); Record.Set(Record.DataPoint.M4ATXVoltageIn, readBuffer[2]); }
public override bool Read(ref string RdBuf, ref int RdCount) { bool bRe = false; ErrorCode ec = ErrorCode.None; while (true) { int bytesRead = -1; // If the device hasn't sent data in the last nReadTimeOut milliseconds, // a timeout error (ec = IoTimedOut) will occur. ec = m_UsbReader.Read(byteRecv, nReadTimeOut, out bytesRead); RdBuf += Encoding.ASCII.GetString(byteRecv, 0, bytesRead); RdCount += bytesRead; if (bytesRead == 0 && ec == ErrorCode.IoTimedOut) { break; } } if (ec == ErrorCode.None) { bRe = true; } return(bRe); }
public byte[] Read(uint size) { Flush(); var index = 0; var tempBuffer = new byte[size]; var packetSize = size >= MaxPacketSIZE ? MaxPacketSIZE : MinPacketSIZE; var packetBuffer = new byte[packetSize]; while (index < size) { if (size - index < packetSize) { packetSize = MinPacketSIZE; Array.Resize(ref packetBuffer, packetSize); } int tLength; var eCode = _epReader.Read(packetBuffer, RxTimeout, out tLength); Debug.Assert(eCode == ErrorCode.None, string.Format("Read error! {0}", eCode)); Debug.Assert(tLength > 0, "Nothing received!"); Buffer.BlockCopy(packetBuffer, 0, tempBuffer, index, size - index >= packetSize ? packetSize : (int)size - index); index += size - index >= packetSize ? packetSize : (int)size - index; } return(tempBuffer); }
/// <summary> /// When the poll timer elapses, this function retrieves data from the controller, and passes /// the raw data to both the raw data event (so applications can analyze the raw data if needed), /// and passes the data to the private CheckStateChanged function. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> /// <remarks> /// Please note - the poll timer is stopped until all events have been processed...so /// keep your event handlers optimized for analyzing the controller data. /// </remarks> private void pollTimer_Elapsed(object sender, ElapsedEventArgs e) { pollTimer.Stop(); int readByteCount = 0; byte[] buf = new byte[64]; reader.Read(buf, 0, 64, 1000, out readByteCount); if (this.RawData != null) { RawData(this, buf); } CheckStateChanged(buf); Array.Copy(buf, 0, rawControlData, 0, readByteCount); //moved this section out of CheckStateChanged since we want this to go off after the data from buf has been copied over to rawControlData if ((Enum.GetValues(typeof(ButtonEnum)).Length > 0) && (this.ButtonStateChanged != null)) { ButtonStateChanged(this, stateChangedArray); } //Console.WriteLine(ConvertToHex(rawControlData, rawControlData.Length)); pollTimer.Start(); }
private void Read() { byte[] readBuffer = new byte[32]; int uiTransmitted; ErrorCode eReturn; Program.quitFlag = false; int total = 0; while ((eReturn = rdr.Read(readBuffer, 1000, out uiTransmitted)) == ErrorCode.None) { // showBytes(readBuffer, uiTransmitted); total += uiTransmitted; richTextBox1.Text = total + " bytes read."; WriteDiagnostics(total.ToString()); if (Program.quitFlag) { Program.quitFlag = false; richTextBox1.Text += "User quit"; closeDevice(); return; } Application.DoEvents(); } richTextBox1.Text += "Data stream ended! " + eReturn; closeDevice(); }
public int Read(out Packet packet, out byte[] packet_data) { int packet_header_size = Marshal.SizeOf(typeof(Packet)); int packet_size = packet_header_size + 1024; byte[] buffer = new byte[packet_size]; ErrorCode error_code; int bytes_read; error_code = Reader.Read(buffer, 0, buffer.Length, 100, out bytes_read); if (error_code != ErrorCode.None) { throw new Exception(UsbDevice.LastErrorString); } if (bytes_read == 0) { throw new Exception(UsbDevice.LastErrorString); } byte[] packet_header_bytes = new byte[packet_header_size]; Array.Copy(buffer, packet_header_bytes, packet_header_size); packet = Protocol.ByteArrayToStructure <Packet>(packet_header_bytes); packet_data = new byte[packet.size]; Array.Copy(buffer, packet_header_size, packet_data, 0, packet.size); return(bytes_read); }
private byte ReadByte() { int ret; var buf = new byte[1]; var res = _reader.Read(buf, 1500, out ret); if (res == ErrorCode.None) { return(buf[0]); } if (res == ErrorCode.Win32Error) { throw new Win32Exception(); } throw new Exception(res.ToString()); }
public byte[] SendData(byte[] packetData) { if (!IsOpen) { const string message = "Crazyradio USB dongle is not open."; Log.Error(message); throw new CrazyradioDriverException(message); } var lengthTransferred = -1; var sendPacketErrorCode = _crazyradioDataEndpointWriter.Write(packetData, 0, packetData.Length, 1000, out lengthTransferred); var sendPacketFailed = sendPacketErrorCode != ErrorCode.None; if (sendPacketFailed) { var message = string.Format("Error sending packet to Crazyradio USB dongle. ErrorCode: {0}, LengthTransferred: {1}.", sendPacketErrorCode, lengthTransferred); Log.Error(message); throw new CrazyradioDriverException(UsbDevice.LastErrorString); } else { Log.DebugFormat("Succesfully sent packet to Crazyradio USB dongle. PacketData: {0}, LengthTransferred: {1}.", BitConverter.ToString(packetData), lengthTransferred); var readAckBuffer = new byte[32]; var readAckErrorCode = _crazyradioDataEndpointReader.Read(readAckBuffer, 100, out lengthTransferred); var readAckFailed = readAckErrorCode != ErrorCode.None; var ackPacketData = readAckFailed ? null : readAckBuffer.Take(lengthTransferred).ToArray(); Log.DebugFormat("Succesfully read ACK packet from Crazyradio USB dongle. PacketData: {0}, LengthTransferred: {1}.", ackPacketData == null ? "NULL" : BitConverter.ToString(ackPacketData), lengthTransferred); return(ackPacketData); } }
public _radio_ack send_packet(byte[] dataOut) { _radio_ack ackIn = null; int transferred; writer.Write(dataOut, 1000, out transferred); if (transferred == dataOut.Length) { byte[] data = new byte[64]; reader.Read(data, 1000, out transferred); if (transferred > 0) { ackIn = new _radio_ack(); if (data[0] != 0) { ackIn.ack = (data[0] & 0x01) != 0; ackIn.powerDet = (data[0] & 0x02) != 0; ackIn.retry = data[0] >> 4; ackIn.data = data.Take(transferred).Skip(1).ToArray(); } else { ackIn.retry = this.arc; } } } return(ackIn); }
public override T ReceiveData <T>() { object ret = default(T); byte[] readBuffer = new byte[1024]; try { _reader.Read(readBuffer, 100, out int bytesRead); if (bytesRead == 0) { throw new Exception("No more bytes!"); } if (typeof(T) == typeof(byte[])) { ret = bytesRead; } if (typeof(T) == typeof(string)) { ret = Encoding.Default.GetString(readBuffer, 0, bytesRead); } } catch (Exception ex) { throw new Exception(ex.ToString()); } return((T)ret); }
/// <summary> /// Polls the controller for input /// </summary> internal void Poll() { if (DenshaDeGoInput.LibUsbIssue) { return; } try { // Ask for input if (ReadBuffer.Length > 0) { int readCount; ErrorCode readError = ControllerReader.Read(ReadBuffer, 0, ReadBuffer.Length, 100, out readCount); if (readError == ErrorCode.DeviceNotFound || readError == ErrorCode.Win32Error || readError == ErrorCode.MonoApiError) { // If the device is not found during read, mark it as disconnected IsConnected = false; } } // Send output buffer if (WriteBuffer.Length > 0) { int bytesWritten; ControllerDevice.ControlTransfer(ref LibUsb.setupPacket, WriteBuffer, WriteBuffer.Length, out bytesWritten); } } catch { DenshaDeGoInput.LibUsbIssue = true; DenshaDeGoInput.CurrentHost.AddMessage(MessageType.Error, false, "The DenshaDeGo! Input Plugin encountered a critical error whilst attempting to poll controller " + activeControllerGuid); } }
public byte[] Read(int ReadLen) { var readBuffer = new byte[ReadLen]; Reader.Read(readBuffer, TIMEOUT, out int txLen); return(readBuffer); }
public ScannerOutput Read() { byte[] readBuffer = new byte[1024]; int bytesRead; var error = reader.Read(readBuffer, 5000, out bytesRead); return(new ScannerOutput(readBuffer, bytesRead, error)); }
public void writeTagBlock(byte block, byte[] data) { int bytesWritten; int bytesRead; ec = writer.Write(new byte[] { 0x04, block, data[0], data[1], data[2], data[3] }, 2000, out bytesWritten); if (ec != ErrorCode.None) { throw new Exception(UsbDevice.LastErrorString); } byte[] readBuffer = new byte[4]; ec = reader.Read(readBuffer, 1000, out bytesRead); if (bytesRead != 1) { throw new Exception("Read error. We was expecting 1 bytes. We read " + bytesRead + " bytes!"); } Thread.Sleep(15); }
/************************************************* * Methods for talking to the device * * sendCommand() should not be called directly * *************************************************/ /// <summary> /// Send command with no command bytes in the writeBuffer /// </summary> /// <param name="cmd">USB command</param> /// <param name="readBuffer">Pre-allocated byte array</param> /// <returns>False if read or write error. True otherwise</returns> private bool sendCommand(USBcommand cmd, byte[] readBuffer) { int bytesRead, bytesWritten; byte[] writeBuffer = { (byte)cmd }; this.ec = writer.Write(writeBuffer, Constants.TIMEOUT, out bytesWritten); if (this.ec != ErrorCode.None) { return(false); } this.ec = reader.Read(readBuffer, Constants.TIMEOUT, out bytesRead); if (this.ec != ErrorCode.None) { return(false); } return(true); }
public byte[] SendData(byte[] data) { if (!IsOpen) { const string message = "CrazyradioDriver is not open for communication."; Log.Error(message); throw new CrazyradioDriverException(message); } Log.Debug("CrazyradioDriver is open for communication."); var lengthTransferred = -1; var dataLength = data != null ? data.Length : 0; Log.DebugFormat("Writing data to UsbDevice. Data: {0}, DataLength: {1}.", data == null ? "NULL" : BitConverter.ToString(data), dataLength); var sendErrorCode = _crazyradioDataEndpointWriter.Write(data, 0, dataLength, 1000, out lengthTransferred); var sendFailed = sendErrorCode != ErrorCode.None; Log.DebugFormat("Write data success? {0}. LengthTransferred: {1}. ErrorCode: {2}.", !sendFailed, lengthTransferred, sendErrorCode); if (sendFailed) { var message = string.Format("Error writing data to UsbDevice. ErrorCode: {0}, LengthTransferred: {1}.", sendErrorCode, lengthTransferred); Log.Error(message); throw new CrazyradioDriverException(UsbDevice.LastErrorString); } else { Log.DebugFormat("Succesfully wrote data to UsbDevice. Data: {0}, LengthTransferred: {1}.", data == null ? "NULL" : BitConverter.ToString(data), lengthTransferred); var responseBuffer = new byte[32]; Log.DebugFormat("Reading data from UsbDevice."); var readErrorCode = _crazyradioDataEndpointReader.Read(responseBuffer, 100, out lengthTransferred); var readFailed = readErrorCode != ErrorCode.None; var response = readFailed ? null : responseBuffer.Take(lengthTransferred).ToArray(); Log.DebugFormat("Read data success? {0}. ErrorCode: {1}.", !readFailed, readErrorCode); if (readFailed) { Log.WarnFormat("Error reading data from UsbDevice. ErrorCode: {0}.", readErrorCode); return(null); } else { Log.DebugFormat("Succesfully read data from UsbDevice. Data: {0}, LengthTransferred: {1}.", response == null ? "NULL" : BitConverter.ToString(response), lengthTransferred); return(response); } } }
internal byte[] receiveCommsResponsePacket() { byte[] returnVal = new byte[64]; int transferLength; if (CommsReceive != null) { CommsReceive.Read(returnVal, 1000, out transferLength); } return(returnVal); }
public async Task <byte[]> ReadAsync() { return(await Task.Run(() => { var buffer = new byte[ReadPacketSize]; _UsbEndpointReader.Read(buffer, Timeout, out var bytesRead); return buffer; })); }
public bool Read() { bool bRe = false; int nReadCount = 0; byte[] readBuffer = new byte[nReadBufSize]; ErrorCode ec = ErrorCode.None; while (true) { int bytesRead = -1; // If the device hasn't sent data in the last nReadTimeOut milliseconds, // a timeout error (ec = IoTimedOut) will occur. ec = reader.Read(readBuffer, nReadTimeOut, out bytesRead); nReadCount += bytesRead; if (bytesRead == 0 && ec == ErrorCode.IoTimedOut) { break; } } if (nReadCount != 0) { USB_ReadString += (byteToHexStr(readBuffer) + "\n"); } else { USB_ReadString += ""; } //USB_ReadString += Encoding.Default.GetString(readBuffer, 0, nReadCount).TrimEnd('\0'); if (ec == ErrorCode.None) { bRe = true; } return(bRe); }
void pinState_DataReceived(object sender, EndpointDataEventArgs e) { int transferLength; pinState.Read(pinStateBuffer, 1000, out transferLength); if (pinStateBuffer[0] == (byte)DeviceResponse.CurrentReadings) { Pin1.UpdateValue(pinStateBuffer[1], pinStateBuffer[2]); Pin2.UpdateValue(pinStateBuffer[3], pinStateBuffer[4]); Pin3.UpdateValue(pinStateBuffer[5], pinStateBuffer[6]); Pin4.UpdateValue(pinStateBuffer[7], pinStateBuffer[8]); Pin5.UpdateValue(pinStateBuffer[9], pinStateBuffer[10]); Pin6.UpdateValue(pinStateBuffer[11], pinStateBuffer[12]); Pin7.UpdateValue(pinStateBuffer[13], pinStateBuffer[14]); Pin8.UpdateValue(pinStateBuffer[15], pinStateBuffer[16]); Pin9.UpdateValue(pinStateBuffer[17], pinStateBuffer[18]); Pin10.UpdateValue(pinStateBuffer[19], pinStateBuffer[20]); Pin11.UpdateValue(pinStateBuffer[21], pinStateBuffer[22]); Pin12.UpdateValue(pinStateBuffer[23], pinStateBuffer[24]); Pin13.UpdateValue(pinStateBuffer[25], pinStateBuffer[26]); Pin14.UpdateValue(pinStateBuffer[27], pinStateBuffer[28]); /// Pin interrupts. /// TODO: This is really hacky and needs to be cleaned up. int PortAInterrupt = pinStateBuffer[29]; int PortBInterrupt = pinStateBuffer[30]; if ((PortAInterrupt & (1 << 4)) > 0) // RA4 = Pin1 { Pin1.RaiseDigitalInValueChanged(); } if ((PortAInterrupt & (1 << 5)) > 0) // RA5 = Pin14 { Pin14.RaiseDigitalInValueChanged(); } if ((PortBInterrupt & (1 << 7)) > 0) // RB7 = Pin8 { Pin8.RaiseDigitalInValueChanged(); } if ((PortBInterrupt & (1 << 7)) > 0) // RB5 = Pin9 { Pin9.RaiseDigitalInValueChanged(); } if ((PortBInterrupt & (1 << 7)) > 0) // RB4 = Pin10 { Pin10.RaiseDigitalInValueChanged(); } if ((PortBInterrupt & (1 << 7)) > 0) // RB6 = Pin11 { Pin11.RaiseDigitalInValueChanged(); } } }
private BinaryReader readPacket() { if (!isConnected()) { throw new IOException("USB accessory not connected"); } int numBytesRead; byte[] readPacket = new byte[MAX_PACKET_BYTES]; ErrorCode ecRead; BinaryReader output = null; do { ecRead = reader.Read(readPacket, 1000, out numBytesRead); //TransportLog("Read :{0} ErrorCode:{1}", numBytesRead, ecRead); if (ecRead != ErrorCode.Success && ecRead != ErrorCode.IoTimedOut && ecRead != ErrorCode.IoCancelled) { throw new IOException("Error reading USB message: " + ecRead.ToString()); } }while (numBytesRead <= 0 && !shutdown); if (!shutdown) { if (numBytesRead < PACKET_HEADER_SIZE) { throw new IOException("Read failed, " + numBytesRead + " bytes returned"); } BinaryReader inPacketBuffer = new BinaryReader(new MemoryStream(readPacket)); short inDataSize = IPAddress.NetworkToHostOrder( inPacketBuffer.ReadInt16() ); if (inDataSize <= 0) { throw new IOException("Invalid data size " + inDataSize + " bytes"); } if (numBytesRead - PACKET_HEADER_SIZE < inDataSize) { throw new IOException("Data size is " + inDataSize + " bytes but packet only contains " + numBytesRead + " bytes"); } output = new BinaryReader(new MemoryStream(readPacket, PACKET_HEADER_SIZE, inDataSize)); } return(output); }
public override int Read(byte[] buffer, int offset, int count) { int length = 0; var errorCode = _reader?.Read(buffer, _timeout, out length) ?? ErrorCode.None; if (errorCode != ErrorCode.Success) { System.Diagnostics.Debug.WriteLine("Error Reading from USB Device: " + errorCode); } return(length); }
private int ReadFromUSB(byte[] buffer, int offset, int length) { int l; var result = epReader.Read(buffer, offset, length, ReadTimeout, out l); if (result != ErrorCode.Ok) throw new Exception("USB read error: " + result.ToString()); #if VERY_DEBUG Debug.WriteLine("<-[FEL] " + BitConverter.ToString(buffer)); #endif Debug.WriteLine(string.Format("<- {0} bytes", length)); return l; }
/// <summary> /// Checks whether the DAC is ready to receive a new frame. NB: Not optional, must be polled and return true before every frame can be sent. /// </summary> /// <returns>true if the DAC is ready to receive a new frame, false otherwise.</returns> public bool GetStatus() { // Status OK if we send {0x03, 0} and get {0x83, 1} in return try { if (!mutex.WaitOne(3000)) { throw new Exception("Could not acquire mutex."); } var errorCode = interruptEndpointWriter.Write(new byte[] { 0x03, 0 }, 16, out int writeTransferLength); if (errorCode == ErrorCode.Ok && writeTransferLength == 2) { byte[] readData = new byte[32]; errorCode = interruptEndpointReader.Read(readData, 16, out int readTransferLength); if (errorCode == ErrorCode.Ok && readTransferLength > 1 && readData[0] == 0x83) { return(readData[1] != 0); } else { return(false); } } else { throw new Exception("Failed to send USB interrupt packet. Error code: " + errorCode.ToString()); } } catch (Exception e) { throw e; } finally { mutex.ReleaseMutex(); } }