A device attached to the system is not functioning - c#

I'm working on an UWP application (Universal Windows) and I got this problem, I'm hoping that your talent will help me a lot. The problem is I plugged an headset HidDevice to read Firmware Version from that headset.
Here is my code:
public async void ReadFirmwareVersion()
{
if (DeviceManagerEventHandler.Current.HidDevice != null)
{
HidOutputReport outReport = DeviceManagerEventHandler.Current.HidDevice.CreateOutputReport();
byte[] buffer = queryVersion();
DataWriter dataWriter = new DataWriter();
dataWriter.WriteBytes(buffer);
outReport.Data = dataWriter.DetachBuffer();
await DeviceManagerEventHandler.Current.HidDevice.SendOutputReportAsync(outReport);
HidInputReport inReport = await DeviceManagerEventHandler.Current.HidDevice.GetInputReportAsync();
if (inReport != null)
{
UInt16 id = inReport.Id;
var bytes = new byte[64];
DataReader dataReader = DataReader.FromBuffer(inReport.Data);
dataReader.ReadBytes(bytes);
}
else
{
rootPage.NotifyUser("Invalid input report received", NotifyType.ErrorMessage);
}
}
}
public static Byte[] queryVersion()
{
Byte[] cmd = new Byte[64];
cmd[0] = 0x0B;
cmd[1] = 0x11;
return cmd;
}
I got an error at
outReport.Data = dataWriter.DetachBuffer();
they said
Value does not fall within the expected range
and 1 more error at HidInputReport inReport = await DeviceManagerEventHandler.Current.HidDevice.GetInputReportAsync(); is
A device attached to the system is not functioning
I tried to get the headset firmware version but it didn't work out due to these errors. Please help, I spent 2 days almost. Did I do something wrong?

Related

How to fix GattStatus: 3 - WriteNotPermitted exception for BLE Xamarin forms application?

I am working on a BLE application. I am able to connect to MI band and get the services through my Xamarin forms BLE app. But when I am trying to write characteristics I am getting exception. I'm getting exception
Characteristic does not support write.
for the method WriteAsync(). This is my code where I am writing to characteristics:
private async Task<string> ProcessDeviceInformationService(IService deviceInfoService)
{
try
{
await adapter.ConnectToDeviceAsync(device);
var sb = new StringBuilder("Getting information from Device Information service: \n");
var characteristics = await deviceInfoService.GetCharacteristicsAsync();
var characteristic = await deviceInfoService.GetCharacteristicAsync(Guid.Parse("00002A27-0000-1000-8000-00805F9B34FB"));
// characteristic.CanWrite = true;
//foreach (var characteristic in characteristics)
//{
try
{
// await Task.Delay(300);
var bytes = await characteristic.ReadAsync();
var str = Encoding.UTF8.GetString(bytes, 0, 0);
ManufacturerLabel.Text = str;
//var characteristic = await deviceInfoService.GetCharacteristicAsync(GattCharacteristicIdentifiers.DataExchange);
if (characteristic != null)
{
byte[] senddata = Encoding.UTF8.GetBytes(string.IsNullOrEmpty(SendMessageLabel.Text) ? "jenx.si was here" : SendMessageLabel.Text);
await Task.Delay(300);
var newbytes = await characteristic.WriteAsync(senddata);
var strnew = Encoding.UTF8.GetString(senddata, 0, 0);
ManufacturerLabel.Text = newbytes.ToString();
//var strnew = Encoding.UTF8.GetString(newbytes, 0, 0);
}
// ManufacturerLabel.Text = str;
}
catch (Exception ex)
{
return ex.Message;
}
//}
return sb.ToString();
}
I have no clue how to fix this any suggestions?
I resolved this. First of all we need to check if the Characteristic has the write operation in it for that you can download an app called BLE scanner from play store and connect to that device. When we connect to that BLE we will be able to see the available services and characteristics of the BLE Peripheral. And there we need to check which characteristics has write operation. So if you try to do write characteristics for characteristics which doesn't have a write operation in peripheral it will give exception write not permitted.

ZeroMQ C# Ironhouse example

I am fairly new to ZeroMQ and have been comparing security of messages using the ZeroMQ NuGet package and the NetMQ & NetMQ Security NuGet packages.
So far, I have not been able to find a C# version of the Ironhouse example using Curve Security. There is a "todo" item on the ZGuides repo but so far nothing implemented. (https://github.com/metadings/zguide/issues/1)
I am also trying to determine whether the NetMQ.Security approach to security is better than the curve security approach that is built into ZeroMQ 4. It seems like most information about Curve is at least from 2014 or earlier.
Any information would be greatly appreciated!
Both publisher and subscriber need to use its own set of public\private keys. In your sample code for subscriber you set CurvePublicKey (to that of server, which is wrong but still) but do not set CurveSecretKey - that's why you get "cannot open client INITIATE vouch". Here is your sample from another question fixed:
public class Program
{
static void Main(string[] args) {
using (var context = new ZContext()) {
Console.WriteLine($"Curve Supported: {ZeroMQ.ZContext.Has("curve")}");
byte[] serverPublicKey;
byte[] serverSecretKey;
Z85.CurveKeypair(out serverPublicKey, out serverSecretKey);
var publisher = new ZSocket(context, ZSocketType.PUB);
publisher.CurvePublicKey = serverPublicKey;
publisher.CurveSecretKey = serverSecretKey;
publisher.CurveServer = true;
publisher.Bind("tcp://*:5050");
var subscriber = new ZSocket(context, ZSocketType.SUB);
byte[] subPublicKey;
byte[] subSecretKey;
Z85.CurveKeypair(out subPublicKey, out subSecretKey);
subscriber.CurvePublicKey = subPublicKey;
subscriber.CurveSecretKey = subSecretKey;
subscriber.CurveServerKey = serverPublicKey;
ZError connectError;
subscriber.Connect("tcp://mybox:5050", out connectError);
if (connectError != null) {
Console.WriteLine($"Connection error: {connectError.Name} - {connectError.Number} - {connectError.Text}");
}
subscriber.SubscribeAll();
// Publish some messages
Task.Run(() => {
for (var i = 1; i <= 5; i++) {
var msg = $"Pub msg: {Guid.NewGuid().ToString()}";
using (var frame = new ZFrame(msg)) {
publisher.Send(frame);
}
}
});
Task.Run(() => {
// Receive some messages
while (true) {
using (var frame = subscriber.ReceiveFrame()) {
var msg = frame.ReadString();
Console.WriteLine($"Received: {msg}");
}
}
});
Console.WriteLine("Press ENTER to exit");
Console.ReadLine();
ZError subError;
subscriber.Disconnect("tcp://mybox:5050", out subError);
subscriber.Dispose();
ZError pubError;
publisher.Disconnect("tcp://*:5050", out pubError);
publisher.Dispose();
}
}
}
Indeed, there are not much C# examples with NetMQ. I found this that works "CurveTests.cs":
public void CurveTest()
{
var serverPair = new NetMQCertificate();
using var server = new DealerSocket();
server.Options.CurveServer = true;
server.Options.CurveCertificate = serverPair;
server.Bind($"tcp://127.0.0.1:55367");
var clientPair = new NetMQCertificate();
using var client = new DealerSocket();
client.Options.CurveServerKey = serverPair.PublicKey;
client.Options.CurveCertificate = clientPair;
client.Connect("tcp://127.0.0.1:55367");
for (int i = 0; i < 100; i++)
{
client.SendFrame("Hello");
var hello = server.ReceiveFrameString();
Assert.Equal("Hello", hello);
server.SendFrame("World");
var world = client.ReceiveFrameString();
Assert.Equal("World", world);
}
}
Important note - if you want to share server public key between different applications, don't use string representation (serverPair.PublicKeyZ85), because encryption won't work. I assume it related to encoding. Better save byte array representation to some file and share it instead:
File.WriteAllBytes("serverPublicKey.txt", serverPair.PublicKey);

C# Weird issue with BinaryFormatter serialize/deserialize

I'm currently having a VERY weird issue with BinaryFormatter serialize / deserialize i hope i can get some help with.
Right now, i'm currently working on learning Game Development with Unity 5.5 for the last 2 months. I decided to challenge myself and create a multiplayer game in which i've created the network part all by myself.
Around a week ago, i tested it over the internet with a friend and all was working as expected, but yesterday i found a problem which is making it unplayable.
[Serializable]
public class Packet
{
//Remeber to change Packet function if changing something here
public List<string> Gdata;
public int PacketInt;
public bool PacketBool;
public string senderID;
public PacketType packetType;
public Packet(PacketType type, string senderID)
{
Gdata = new List<string>();
this.senderID = senderID;
this.packetType = type;
}
public Packet(byte[] packetBytes)
{
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream(packetBytes);
Console.WriteLine(packetBytes);
Packet p = (Packet)bf.Deserialize(ms);
ms.Close();
this.Gdata = p.Gdata;
this.PacketInt = p.PacketInt;
this.PacketBool = p.PacketBool;
this.senderID = p.senderID;
this.packetType = p.packetType;
}
public byte[] ToBytes()
{
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, this);
byte[] bytes = ms.ToArray();
ms.Close();
return bytes;
}
public static string GetIP4Address()
{
IPAddress[] ips = Dns.GetHostAddresses(Dns.GetHostName());
foreach (IPAddress i in ips)
{
if (i.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
return i.ToString();
}
return "127.0.0.1";
}
}
public enum PacketType
{
/* Connection */
Connecting,
Handshake,
ConnectionComfirmed,
DataRequest,
NewClient, // Sent from the server to all players online when a new player has connected, containing revelant data to sync the new player.
Disconnecting,
/* Errors */
ServerError,
/* Updates */
Movement,
PositionUpdate,
/* Chat */
Chat
}
The problem i'm describing below happends on the line Packet p = (Packet)bf.Deserialize(ms);
This is what i'm using to handle the packets. It's inside a DLL which i have attached to both the server software and the game i'm creating. An example on how it works is this:
void DataManager(Packet p)
{
switch (p.packetType)
{
case PacketType.Connecting:
if (p.Gdata[1] == ServerHandshake)
{
_clientID = p.senderID;
Packet sp = new Packet(PacketType.Handshake, _clientID);
sp.Gdata.Add(ClientHandshake);
_socket.Send(sp.ToBytes());
}
break;
}
}
When testing it locally, it's working without a problem and has been working fine for the last 2 months. Also, as i wrote above, i tested it a little over a week ago without a problem what so ever.
However, the problem now is that for some reason, at the exact same moment, i get the error 'The input stream is not a valid binary format' whenever someone connected over the internet is moving. The code for this part is below:
if (movement_vector != Vector2.zero)
{
anim.SetBool("iswalking", true);
anim.SetFloat("input_x", movement_vector.x);
anim.SetFloat("input_y", movement_vector.y);
Packet p = new Packet(PacketType.Movement, GetComponent<Script_PlayerData>().Player_GUID);
p.Gdata.Add(movement_vector.x.ToString());
p.Gdata.Add(movement_vector.y.ToString());
p.Gdata.Add(player.position.x.ToString());
p.Gdata.Add(player.position.y.ToString());
GameObject.Find("GameScripts").GetComponent<Script_Network>()._socket.Send(p.ToBytes());
if (HasMoved == 0) HasMoved = 1;
}
Before this part is even executed, the server and game client is sending several packets back and forth, and that is working completly fine. Even the chat i've added to the game is working as intended but as soon as a player connected over the internet is moving to any direction, i get the 'The input stream is not a valid binary format' exception thrown, even though it's working fine locally with atleast up to 10 clients connected.
I've been looking around on the internet for hours trying to find a solution to this issue but nothing i've tested or read so far has been working for me.
I haven't modified this code at all since the first time i tested it with remote players connected. I also update the DLL in the Unity project every time after i have compiled the DLL.
So as a last resort, i'm asking here. Anyone knows what possibly could make it behave like this, and does anyone knows a solution to it?
EDIT: Apparently forgot to specify it's TCP. Code Snippets below that might help you understand better how it works:
Server Program:
void SetupSocket()
{
ConsoleMessage("Initializing socket...");
_listenerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ip = new IPEndPoint(IPAddress.Parse(s_config.ServerIP), s_config.ServerPort);
ConsoleMessage("Binding server to " + s_config.ServerIP + ":" + s_config.ServerPort);
_listenerSocket.Bind(ip);
_listenerThread = new Thread(ListenThread);
_listenerThread.Start();
}
void NetworkListener(Socket _socket, string GUID) // Threaded for each client connected
{
OnlinePlayers++;
byte[] Buffer;
int readBytes;
try
{
for (;;)
{
int l = GetPlayerIndexSlot(GUID);
if (l == -1) break;
Buffer = new byte[_socket.SendBufferSize];
readBytes = _socket.Receive(Buffer);
if (readBytes > 0)
{
Packet packet = new Packet(Buffer);
DataManager(_socket, packet);
}
}
}
catch (SocketException ex)
{
ConsoleMessage("Socket error: " + ex.ErrorCode + ", Client id: " + GUID);
if (ex.ErrorCode == 10054) // WSAECONNRESET - Connection reset by peer
{
OnPlayerDisconnecting(_socket, 5);
}
}
}
void DataManager(Socket _socket, Packet p)
{
switch (p.packetType)
{
case PacketType.Connecting: ConnectingPacket(_socket, p.Gdata[0]); break;
case PacketType.Handshake: HandshakeProcess(p.senderID, _socket, p.Gdata[0]); break;
case PacketType.Disconnecting: OnPlayerDisconnecting(_socket, 0); break;
case PacketType.DataRequest: DataRequest(p.Gdata[0], _socket, p.senderID); break;
case PacketType.Movement: PlayerMovement(p.senderID, _socket, p.Gdata[0], p.Gdata[1], p.Gdata[2], p.Gdata[3]); break;
case PacketType.PositionUpdate: PlayerPositionUpdate(p.senderID, _socket, p.Gdata[0], p.Gdata[1]); break;
case PacketType.Chat: ChatMessage(p.senderID, _socket, p.Gdata[0]); break;
}
}

C# : Bluetooth GATT communication. GattCharacteristic.ValueChanged doesnt gets hit after sometime

I am working on wpf application that uses GATT for bluetooth communication. I am using GattCharacteristic.ValueChanged to handle any value from device. It works for sometime and the event handler doesnt gets called after 1 minute. This problem observed in windows 8.1, but working in windows 10.
I am made GattCharacteristic member variable, so the GC doesnt collect the variable. Still the problem exists.
Can anyone tell me what could be the potential problem here?
private GattCharacteristic m_DataSenderCharacteristics;
foreach (var service in serviceInfo)
{
var uuid = MjGattDeviceService.UuidFromServiceInformation(service);
//Battery Service
if (uuid.ToString() == BatteryUUID)
{
var bService = await GattDeviceService.FromIdAsync(service.Id);
m_Device.batteryService = bService;
}
if (uuid.ToString() == CustomServiceUUID)
{
m_Device.gattService = await GattDeviceService.FromIdAsync(service.Id);
Guid controlGUID = new Guid(ControlUUID);
var controlGattCharacteristics = m_Device.gattService.GetCharacteristics(controlGUID);
Byte[] bsdata = new Byte[] { 0x0b, 0x00, 0x02 };
IBuffer buffUTF8 = CryptographicBuffer.CreateFromByteArray(bsdata);
GattCommunicationStatus status = await controlGattCharacteristics[0].WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);
if (status == GattCommunicationStatus.Unreachable)
{
m_Device.isConnected = false;
nextPage = "Unreachable";
}
else if (status == GattCommunicationStatus.Success)
{
var ctrlStatus = await controlGattCharacteristics[0].WriteValueAsync(buffUTF8);
Guid guuid1 = new Guid(DataSenderUUID);
m_DataSenderCharacteristics = m_Device.gattService.GetCharacteristics(guuid1)[0];
GattCommunicationStatus notifyStatus = await m_DataSenderCharacteristics.
WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);
//This event handler will be called for some 1 minute. After it falls dead
m_DataSenderCharacteristics[0].ValueChanged += GestureValueChanged;
if (notifyStatus == GattCommunicationStatus.Success)
{
nextPage = "Connected";
}
}
}
}

StreamSocket crash on Windows 8.1 store app

I have a server-client connection which works on both sides with Windows.Networking.Sockets.StreamSocket. On Windows 10, as Universal App, the connection is successful and data flows in back and forth without problems. On Windows 8.1, as a Windows Store app, the reading part of the StreamSocket fails at first attempt to read incoming data. The app closes and VS 2015 do not report any Exception nor the Output Window contains any useful information, other than Program has exited with code 1. Also, putting a breakpoint and then stepping through code doesn't work. Locals are not displayed and VS shows a message dialog:
Unable to start debugging. The object invoked has disconnected from its clients.
Here is the reading code:
public IAsyncAction Read()
{
return Task.Run(() =>
{
try
{
const uint length = 65536;
string request = string.Empty;
var socket = _signalingSocketService.GetSocket();
var readBuf = new Windows.Storage.Streams.Buffer(length);
var readOp = socket.InputStream.ReadAsync(readBuf, length, InputStreamOptions.Partial);
readOp.Completed = (IAsyncOperationWithProgress<IBuffer, uint> asyncAction, AsyncStatus asyncStatus) =>
{
if(asyncStatus == AsyncStatus.Completed)
{
var localBuffer = asyncAction.GetResults();
var dataReader = DataReader.FromBuffer(localBuffer);
request = dataReader.ReadString(dataReader.UnconsumedBufferLength);
_signalingSocketService.HandoffSocket(socket);
List<string> requests;
var fileTask = BufferFileExists().AsTask();
fileTask.Wait();
if (fileTask.Result)
{
var bufferFileTask = GetBufferFile().AsTask();
bufferFileTask.Wait();
var bufferFile = bufferFileTask.Result;
var task = FileIO.AppendTextAsync(bufferFile, request).AsTask();
task.Wait();
var readLinesTask = FileIO.ReadLinesAsync(bufferFile).AsTask();
readLinesTask.Wait();
requests = (readLinesTask.Result).ToList();
var deleteTask = bufferFile.DeleteAsync().AsTask();
deleteTask.Wait();
}
else
{
requests =
request.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).ToList();
}
} // if (asyncStatus == AsyncStatus.Completed)
}; // readOp.Completed
}
catch (Exception ex)
{
}
}
}
What can cause such an odd behavior?

Categories