public override int Read(byte[] dest, int timeoutMillis) { var totalRead = 0; var watch = new Stopwatch(); watch.Start(); while (totalRead < dest.Length) { var max = Math.Min(_buffer.Length, dest.Length - totalRead); var read = _connection.BulkTransfer(_readEndpoint, _buffer, max, timeoutMillis); if (read == -1) { return(totalRead); } if (read > 0) { Buffer.BlockCopy(_buffer, 0, dest, totalRead, read); totalRead += read; } else if (watch.ElapsedMilliseconds > timeoutMillis) { return(totalRead); } } return(totalRead); }
public override int Read(byte[] dest, int timeoutMillis) { lock (ReadBufferLock) { var numBytesRead = _connection.BulkTransfer(_readEndpoint, dest, dest.Length, timeoutMillis); if (numBytesRead >= 0) { return(numBytesRead); } // This sucks: we get -1 on timeout, not 0 as preferred. // We *should* use UsbRequest, except it has a bug/api oversight // where there is no way to determine the number of bytes read // in response :\ -- http://b.android.com/28023 if (timeoutMillis == int.MaxValue) { // Hack: Special case "~infinite timeout" as an error. return(-1); } if (numBytesRead == -1) { return(-1); } return(0); } }
public async Task <byte[]> ReadPeripheralResponsePacketAsync(uint bytesToRead) { if (!connected) { return(new byte[bytesToRead]); } byte[] data = new byte[bytesToRead]; int res = connection.BulkTransfer(peripheralResponseEndpoint, data, (int)bytesToRead, 1000); return(data); }
public byte[] Read() { byte[] ReceivedBuffer = new byte[65]; if (Connection != null) { if (Endpoint != null) { Connection.BulkTransfer(Endpoint, ReceivedBuffer, 1, 64, 300); } } return(ReceivedBuffer); }
public void WriteControlBytesBulk(byte[] message, int offset, int length, bool async = false) { //try to send data try { byte[] buffer; if (offset == 0 && length == message.Length) { buffer = message; } else { buffer = new byte[length]; Array.ConstrainedCopy(message, offset, buffer, 0, length); } int bytesWritten = usbConnection.BulkTransfer(commandWriteEndpoint, buffer, buffer.Length, TIMEOUT); if (bytesWritten != buffer.Length) { Logger.Error(String.Format("Writing control bytes failed - wrote {0} out of {1} bytes", bytesWritten, buffer.Length)); } } catch (Exception ex) { Logger.Error("Writing control bytes failed" + ex.Message); } }
/// <summary> /// 发送数据包 /// </summary> /// <param name="command"></param> private bool sendPackage(byte[] command) { if (myDeviceConnection == null) { return(false); } int len = command.Length; //分批发送2 int packageLength = 1024; Dictionary <int, byte[]> data = new System.Collections.Generic.Dictionary <int, byte[]>(); int num = len / packageLength + 1; for (int i = 0; i < num; i++) { byte[] da = new byte[packageLength]; for (int j = 0; j < packageLength; j++) { int index = i * packageLength + j; if (index >= len) { break; } da[j] = command[index]; } data.Add(i, da); } foreach (KeyValuePair <int, byte[]> kvp in data) { int res = myDeviceConnection.BulkTransfer(epOut, kvp.Value, kvp.Value.Length, 10000); System.Threading.Thread.Sleep(5); if (res != kvp.Value.Length) { return(false); } } return(true); }
private T SendAndReceiveResponse <T>(ICcidRequest request) where T : ICcidResponse, new() { var message = request.ToBytes(_sequence++); var bytesTransferred = _connection.BulkTransfer(_bulkOutPipe, message, message.Length, 0); if (bytesTransferred < 10) { throw new Exception("Transfer did not send all bytes"); } var bytesReceived = _connection.BulkTransfer(_bulkInPipe, _receiveBuffer, _receiveBuffer.Length, 0); if (bytesReceived < 10) { throw new Exception("Did not receive expected number of bytes"); } var response = new T(); response.Parse(_receiveBuffer); return(response); }
private void sendPackage(byte[] command) { int ret = -100; int len = command.Length; byte[] recive = new byte[20]; /* * // 组织准备命令 * byte[] sendOut = Commands.OUT_S; * sendOut[8] = (byte)(len & 0xff); * sendOut[9] = (byte)((len >> 8) & 0xff); * sendOut[10] = (byte)((len >> 16) & 0xff); * sendOut[11] = (byte)((len >> 24) & 0xff); * * // 1,发送准备命令 * ret = myDeviceConnection.BulkTransfer(epOut, sendOut, 31, 10000); * if (ret != 31) * { * return; * } */ // 2,发送COM ret = myDeviceConnection.BulkTransfer(epOut, command, len, 10000); if (ret != len) { return; } // 3,接收发送成功信息 ret = myDeviceConnection.BulkTransfer(epIn, recive, 13, 10000); if (ret != 13) { return; } }
public async Task <bool> OpenAsync() { if (connected) { return(false); } //usbManager.RequestPermission(usbDevice, PendingIntent.GetBroadcast(ConnectionService.Instance.Context, 0, new Intent(ConnectionService.Instance.ActionUsbPermission), PendingIntentFlags.CancelCurrent)); UsbInterface intf = usbDevice.GetInterface(0); pinReportEndpoint = intf.GetEndpoint(0); peripheralResponseEndpoint = intf.GetEndpoint(1); pinConfigEndpoint = intf.GetEndpoint(2); peripheralConfigEndpoint = intf.GetEndpoint(3); connection = usbManager.OpenDevice(usbDevice); if (connection != null) { bool intfClaimed = connection.ClaimInterface(intf, true); if (intfClaimed) { connected = true; pinListenerThread = new Thread( () => { byte[] data = new byte[64]; pinListenerThreadRunning = true; while (pinListenerThreadRunning) { int res = connection.BulkTransfer(pinReportEndpoint, data, 41, 100); // pin reports are 41 bytes long now if (res > 0) { this.PinEventDataReceived?.Invoke(data); } } }); pinListenerThread.Start(); return(true); } } return(false); }
public void Run() { if (!_scanMode) { System.Diagnostics.Debug.WriteLine($"Setting channel to {_channel + 1}"); Write(GetChannelByte(0)); Write(GetChannelByte((byte)(_channel + 1))); } byte[] buffer = new byte[100]; while (!_token.IsCancellationRequested) { //Changing channel if (_scanMode && (!_sw.IsRunning || _sw.ElapsedMilliseconds > 2500)) { System.Diagnostics.Debug.WriteLine($"Setting channel to {_channel + 1}"); Write(GetChannelByte(0)); Write(GetChannelByte((byte)(_channel + 1))); _channel = ++_channel % 14; _sw.Restart(); } //Reading data int count = _connection.BulkTransfer(_readEndpoint, buffer, buffer.Length, 1000); if (count > 0 && !_token.IsCancellationRequested) { dataString += Encoding.ASCII.GetString(buffer, 0, count); int termPos1, termPos2; do { //Check if string contains the terminator termPos1 = dataString.IndexOf((char)_terminator1); termPos2 = dataString.IndexOf((char)_terminator2); //Console.WriteLine("RAW: '" + tString + "'" + // " termPoses=" + termPos1 + " " + termPos2 + // " len " + tString.Length ); if (termPos2 > -1 && termPos2 > -1) { string workingString = dataString.Substring(0, termPos2); dataString = dataString.Substring(termPos2 + 1); //Console.WriteLine("NEXT: '" + tString + "'" + " len " + tString.Length); workingString = workingString.Trim(trimChars); //Console.WriteLine("RAW: '" + workingString + "'"); //System.Diagnostics.Debug.WriteLine(workingString); try { BeaconInfoData info = BeaconInfoData.FromString(workingString); System.Diagnostics.Debug.WriteLine(info); var msg = _handler.ObtainMessage(111); msg.Data.PutString("raw", workingString); _handler.SendMessage(msg); if (!_scanMode && info.wifiChan != _channel) { System.Diagnostics.Debug.WriteLine($"Setting channel to {_channel}"); Write(GetChannelByte(0)); Write(GetChannelByte((byte)_channel)); } } catch { } } } while (termPos1 > -1 && termPos2 > -1); } } }
public void SetDevice(Intent intent, UsbDevice usbDevice) { int packetSize = 0; IsReading = true; if (usbDevice != null && intent.GetBooleanExtra(UsbManager.ExtraPermissionGranted, false)) { connection = mUsbManager.OpenDevice(usbDevice); intf = usbDevice.GetInterface(0); if (null == connection) { Log.Debug("DEBUG", "unable to establish connection)\n"); } else { connection.ClaimInterface(intf, true); } try { if (UsbAddressing.DirMask == intf.GetEndpoint(0).Direction) { endPointRead = intf.GetEndpoint(0); packetSize = endPointRead.MaxPacketSize; } else { Log.Debug("####### DEBUG #######", "######### Cagou geral !!! ############"); } } catch (Exception e) { Log.Debug("endPointWrite", "Device have no endPointRead" + e); } var cancellationTokenSource = new CancellationTokenSource(); new Thread(new ThreadStart(delegate { try { if (connection != null && endPointRead != null) { while (IsReading) { byte[] buffer = new byte[packetSize]; int status = connection.BulkTransfer(endPointRead, buffer, packetSize, 100); if (status > 0) { var count = bufferReaded.Count(x => x != 0x00); Buffer.BlockCopy(buffer, 0, bufferReaded, count, buffer.Length); Log.Debug("####### DEBUG #######", "COPIEEEI!"); } } } } catch (Exception e) { Log.Debug(TAG, "Error in receive thread" + e.Message); } })).Start(); //usbThreadDataReceiver = Task.Factory.StartNew(a => //{ // try // { // if (connection != null && endPointRead != null) // { // while (IsReading) // { // byte[] buffer = new byte[packetSize]; // int status = connection.BulkTransfer(endPointRead, buffer, packetSize, 100); // if (status > 0) // { // var count = bufferReaded.Count(x => x != 0x00); // Buffer.BlockCopy(buffer, 0, bufferReaded, count, buffer.Length); // } // } // } // } // catch (Exception e) // { // Log.Debug(TAG, "Error in receive thread" + e.Message); // } //}, TaskCreationOptions.LongRunning, cancellationTokenSource.Token ); new Thread(new ThreadStart(delegate { try { while (IsReading) { if (bufferReaded.Count(x => x != 0x00) > 150) { int n = 0; while ((bufferReaded[bufferReaded.Count(x => x != 0x00) - 2] != 0x7c) && (bufferReaded[bufferReaded.Count(x => x != 0x00) - 1] != 0x41)) { if (bufferReaded.Count(x => x != 0x00) >= 255) { Array.Clear(bufferReaded, 0, bufferReaded.Length); break; } } var count = bufferReaded.Count(x => x != 0x00); StringBuilder stringBuilder = new StringBuilder(); int i = 0; for (; i < bufferReaded.Length && bufferReaded[i] != 0; i++) { stringBuilder.Append(Convert.ToString((char)bufferReaded[i])); } Array.Clear(bufferReaded, 0, bufferReaded.Length); //Task.Factory.StartNew(() => //{ OnUsbDataReceiver?.Invoke(new object(), stringBuilder.ToString()); Log.Debug("####### DEBUG #######", stringBuilder.ToString()); //}).ConfigureAwait(false); } } } catch (Exception e) { Log.Debug(TAG, "Error verify buffer" + e.Message); } })).Start(); //verificaPacoteLido = Task.Factory.StartNew(a => //{ // try // { // while (IsReading) // { // if (bufferReaded.Count(x => x != 0x00) > 150) // { // int n = 0; // while ((bufferReaded[bufferReaded.Count(x => x != 0x00) - 2] != 0x7c) && (bufferReaded[bufferReaded.Count(x => x != 0x00) - 1] != 0x41)) // { // if (bufferReaded.Count(x => x != 0x00) >= 255) // { // Array.Clear(bufferReaded, 0, bufferReaded.Length); // break; // } // } // var count = bufferReaded.Count(x => x != 0x00); // StringBuilder stringBuilder = new StringBuilder(); // int i = 0; // for (; i < bufferReaded.Length && bufferReaded[i] != 0; i++) // { // stringBuilder.Append(Convert.ToString((char)bufferReaded[i])); // } // Array.Clear(bufferReaded, 0, bufferReaded.Length); // //Task.Factory.StartNew(() => // //{ // //OnUsbDataReceiver?.Invoke(new object(), stringBuilder.ToString()); // Log.Debug("####### DEBUG #######", stringBuilder.ToString()); // //}).ConfigureAwait(false); // } // } // } // catch (Exception e) // { // Log.Debug(TAG, "Error verify buffer" + e.Message); // } //}, TaskCreationOptions.LongRunning, cancellationTokenSource.Token); } }