libusbdotnet can not find RFIDeas USB HID device - usb

I am running windows 7x64 connecting to a RFIDeas USB reader (Part# RDR-80582AKU). Using device manager, I found its vendor & product ID as HID\VID_0C27&PID_3BFA&REV_1623.
My .NEt app referenced Libusdotnet,LibUsb.Common, also installed libusb-win32-driver. When running , it show "Device Not Found", I searched and did not find anything related my problem, below is my code. TIA.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LibUsbDotNet;
using LibUsbDotNet.Info;
using LibUsbDotNet.Main;
using System.Collections.ObjectModel;
namespace RFIDeas_cs
{
class Program
{
public static UsbDevice MyUsbDevice;
#region SET YOUR USB Vendor and Product ID!
public static UsbDeviceFinder MyUsbFinder = new UsbDeviceFinder(0x0c27, 0x3bfa);
#endregion
static void Main(string[] args)
{
ErrorCode ec = ErrorCode.None;
try
{
// Find and open the usb device.
MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);
// If the device is open and ready
if (MyUsbDevice == null) throw new Exception("Device Not Found.");
// If this is a "whole" usb device (libusb-win32, linux libusb-1.0)
// it exposes an IUsbDevice interface. If not (WinUSB) the
// 'wholeUsbDevice' variable will be null indicating this is
// an interface of a device; it does not require or support
// configuration and interface selection.
IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
if (!ReferenceEquals(wholeUsbDevice, null))
{
// This is a "whole" USB device. Before it can be used,
// the desired configuration and interface must be selected.
// Select config #1
wholeUsbDevice.SetConfiguration(1);
// Claim interface #0.
wholeUsbDevice.ClaimInterface(0);
}
// open read endpoint 1.
UsbEndpointReader reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01);
byte[] readBuffer = new byte[1024];
while (ec == ErrorCode.None)
{
int bytesRead;
// If the device hasn't sent data in the last 5 seconds,
// a timeout error (ec = IoTimedOut) will occur.
ec = reader.Read(readBuffer, 5000, out bytesRead);
if (bytesRead == 0) throw new Exception(string.Format("{0}:No more bytes!", ec));
Console.WriteLine("{0} bytes read", bytesRead);
// Write that output to the console.
Console.Write(Encoding.Default.GetString(readBuffer, 0, bytesRead));
}
Console.WriteLine("\r\nDone!\r\n");
}
catch (Exception ex)
{
Console.WriteLine();
Console.WriteLine((ec != ErrorCode.None ? ec + ":" : String.Empty) + ex.Message);
}
finally
{
if (MyUsbDevice != null)
{
if (MyUsbDevice.IsOpen)
{
// If this is a "whole" usb device (libusb-win32, linux libusb-1.0)
// it exposes an IUsbDevice interface. If not (WinUSB) the
// 'wholeUsbDevice' variable will be null indicating this is
// an interface of a device; it does not require or support
// configuration and interface selection.
IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
if (!ReferenceEquals(wholeUsbDevice, null))
{
// Release interface #0.
wholeUsbDevice.ReleaseInterface(0);
}
MyUsbDevice.Close();
}
MyUsbDevice = null;
// Free usb resources
UsbDevice.Exit();
}
// Wait for user input..
Console.ReadKey();
}
}
}
}

I solved my problem with Filter Enabled.
Download & run setup LibUsbDotNet_Setup.2.2.8.exe
select appropriate filter for your input device, in my case vendor ID 0c27

Related

Azure IoT Edge Offline capabilities Example

I'm a little bit confused on how to use IoT Edge Offline mode. I though it was out-of-box!
The location of my IoT Hub is in West US. When I disconnect my Edge device from the network nothing happen. The datas is not saved or resend after reconnecting it online.
I got only one module that send data to the IoT Hub, I can see the datas flowing with Device Explorer Twin app and I saved the data in a database.
After disconnecting, wait 5 minutes and reconnecting, I don't see the datas that I was trying to send during offline mode in the database.
All messages while offline are missing (I'm sequencing the message with datetime stamp).
Did I missed a configuration?
Any idea why the offline mode doesn't work for me?
I'm using Iot Edge Runtime v1.0.6 and Windows Containers.
Here the source code of my testing module:
using Microsoft.Azure.Devices.Client;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Runtime.Loader;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
class Program
{
static int monitoringInterval { get; set; } = 60;// 60 seconds
static System.Timers.Timer testTimer;
static ModuleClient ioTHubModuleClient;
static void Main(string[] args)
{
Init().Wait();
StartTestTimer();
// Wait until the app unloads or is cancelled
var cts = new CancellationTokenSource();
AssemblyLoadContext.Default.Unloading += (ctx) => cts.Cancel();
Console.CancelKeyPress += (sender, cpe) => cts.Cancel();
WhenCancelled(cts.Token).Wait();
}
/// <summary>
/// Handles cleanup operations when app is cancelled or unloads
/// </summary>
public static Task WhenCancelled(CancellationToken cancellationToken)
{
var tcs = new TaskCompletionSource<bool>();
cancellationToken.Register(s => ((TaskCompletionSource<bool>)s).SetResult(true), tcs);
return tcs.Task;
}
/// <summary>
/// Initializes the ModuleClient and sets up the callback to receive
/// messages containing temperature information
/// </summary>
static async Task Init()
{
AmqpTransportSettings amqpSetting = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only);
ITransportSettings[] settings = { amqpSetting };
// Open a connection to the Edge runtime
ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings);
await ioTHubModuleClient.OpenAsync();
Console.WriteLine("IoT Hub module client initialized.");
}
static void StartTestTimer()
{
Console.WriteLine("Start Monitoring Timer: " + monitoringInterval + " seconds");
// Set up a timer that triggers every minute.
testTimer = new System.Timers.Timer();
testTimer.Interval = monitoringInterval * 1000; // 60 seconds
testTimer.Elapsed += new System.Timers.ElapsedEventHandler(SendEvent);
testTimer.Start();
SendEvent(null, null);
}
async static void SendEvent(object sender, System.Timers.ElapsedEventArgs args)
{
DateTime today = DateTime.Now;
Console.WriteLine("[" + today + "] Send Data has started...");
try
{
//IoT device connection string
string connectionString = "HostName=xxxxxx.azure-devices.net;DeviceId=IOT-Device1;SharedAccessKey=ett8xxxxxxxxx";
// Connect to the IoT hub using the MQTT protocol
DeviceClient _DeviceClient = DeviceClient.CreateFromConnectionString(connectionString, TransportType.Mqtt);
_DeviceClient.OperationTimeoutInMilliseconds = 10000;
Dictionary<string, Object> telemetryDataPoint = new Dictionary<string, Object>();
string dateTime = DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString();
telemetryDataPoint.Add("DateTime", dateTime);
string messageString = JsonConvert.SerializeObject(telemetryDataPoint);
Message message = new Message(Encoding.ASCII.GetBytes(messageString));
// Send the telemetry message
Console.WriteLine("\n*> Sending message: {0}", messageString);
await _DeviceClient.SendEventAsync(message).ConfigureAwait(false);
Console.WriteLine("Message sent!");
}
catch (Exception e)
{
Console.WriteLine("Message not sent. Connection error to Iot Hub:" + e.Message);
}
}
}
Why is the code creating a moduleClient in Init(), but then attempting to send an a message directly to IoT Hub using a deviceClient in SendEvent()? This bypasses the edge runtime (specifically edgeHub) completely which is what facilitates offline store and forward.
Here is an example of the right way to do this: https://github.com/Azure/iotedge/blob/ad41fec507bb91a2e57a07cd32e287ada0ca08d8/edge-modules/SimulatedTemperatureSensor/src/Program.cs#L95

Azure IoT Edge module direct method responses shows as [object Object]

When invoking a direct method on a specific module I just receive the result [object Object] in the azure portal and I don't know what I'm doing wrong.
Note that when I did exactly the same using the azure IoT SDK for c# (without running the azure iot runtime), I properly received the JSON object and it was not just shown as [object Object].
Note that I'm developing this in c# and the docker containers (used for IoT edge runtime and it's modules) is running Linux as OS.
I have the following sample method that I've registered as a direct method.
In the iot edge runtime Init() function I do the following:
await ioTHubModuleClient.SetMethodHandlerAsync("Sample1", Sample1, null);
The sample method looks like:
private static Task<MethodResponse> Sample1(MethodRequest methodRequest, object userContext)
{
// Get data but don't do anything with it... Works fine!
var data = Encoding.UTF8.GetString(methodRequest.Data);
var methodResponse = new MethodResponse(Encoding.UTF8.GetBytes("{\"status\": \"ok\"}"), 200);
return Task.FromResult(methodResponse);
}
I can monitor this module in the debug mode by setting breakpoints in the Sample1 method. I can't find what I'm doing wrong? Why is the response returned from this Sample1 method just shown as [object Object] and why don't I see the JSON-object {"status": "ok"} as I did when not using the Azure IoT Edge runtime?
The callback result for the Direct Method is object Task< MethodResponse >.It does not serialize to Json string to show in the Azure Portal. But you can use the Service Client Sdk to get the callback response and then serialize to JSON string.
The latest Microsoft Azure IoT Hub SDK for C# supports Modules and IoT Edge. You can refer to this sample with using the SDK.
Update:
In the latest Azure IoT Hub SDK(Microsoft.Azure.Devices.Client 1.18), please use ModuleClinet instead of DeviceClient. You can refer to the following code in module.
namespace SampleModuleA
{
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.Loader;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Devices.Client.Transport.Mqtt;
using Microsoft.Azure.Devices.Client;
using Newtonsoft.Json;
class Program
{
static int counter;
static void Main(string[] args)
{
Init().Wait();
// Wait until the app unloads or is cancelled
var cts = new CancellationTokenSource();
AssemblyLoadContext.Default.Unloading += (ctx) => cts.Cancel();
Console.CancelKeyPress += (sender, cpe) => cts.Cancel();
WhenCancelled(cts.Token).Wait();
}
/// <summary>
/// Handles cleanup operations when app is cancelled or unloads
/// </summary>
public static Task WhenCancelled(CancellationToken cancellationToken)
{
var tcs = new TaskCompletionSource<bool>();
cancellationToken.Register(s => ((TaskCompletionSource<bool>)s).SetResult(true), tcs);
return tcs.Task;
}
/// <summary>
/// Initializes the ModuleClient and sets up the callback to receive
/// messages containing temperature information
/// </summary>
static async Task Init()
{
MqttTransportSettings mqttSetting = new MqttTransportSettings(TransportType.Mqtt_WebSocket_Only);
ITransportSettings[] settings = { mqttSetting };
// Open a connection to the Edge runtime
ModuleClient ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings);
await ioTHubModuleClient.OpenAsync();
Console.WriteLine("[{0:HH:mm:ss ffff}]IoT Hub SampleModuleA client initialized.", DateTime.Now);
await ioTHubModuleClient.SetMethodHandlerAsync("DirectMethod1", DirectMethod1, ioTHubModuleClient);
// Register callback to be called when a message is received by the module
await ioTHubModuleClient.SetInputMessageHandlerAsync("input1", PipeMessage, ioTHubModuleClient);
}
static async Task<MethodResponse> DirectMethod1(MethodRequest methodRequest, object moduleClient)
{
Console.WriteLine("Call DirectMethod1.");
MethodResponse resp = null;
//to do Something
return resp;
}
/// <summary>
/// This method is called whenever the module is sent a message from the EdgeHub.
/// It just pipe the messages without any change.
/// It prints all the incoming messages.
/// </summary>
static async Task<MessageResponse> PipeMessage(Message message, object userContext)
{
int counterValue = Interlocked.Increment(ref counter);
var moduleClient = userContext as ModuleClient;
if (moduleClient == null)
{
throw new InvalidOperationException("UserContext doesn't contain " + "expected values");
}
byte[] messageBytes = message.GetBytes();
string messageString = Encoding.UTF8.GetString(messageBytes);
Console.WriteLine($"Received message: {counterValue}, Body: [{messageString}]");
if (!string.IsNullOrEmpty(messageString))
{
var pipeMessage = new Message(messageBytes);
foreach (var prop in message.Properties)
{
pipeMessage.Properties.Add(prop.Key, prop.Value);
}
await moduleClient.SendEventAsync("output1", pipeMessage);
Console.WriteLine("Received message sent");
}
return MessageResponse.Completed;
}
}
}

Send many byte array from server to UWP as a stream

I have a WCF service that updates the byte array from camera continuous like this:
private void ImageGrabbedCamera(object sender, ImageGrabbedEventArgs e)
{
try
{
if (e.GrabResult.GrabSucceeded)
{
//This variable is updated continuous from the camera
result = e.GrabResult.Clone();
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
And I call this method from the UWP client app to get the byte array from the server
public Stream GetStreamCamera()
{
MemoryStream ms;
if (result != null)
{
ms = new MemoryStream(ObjectToByteArray(result.PixelData as byte[]));
ms.Position = 0;
return ms;
}
else
{
return new MemoryStream();
}
}
In client app, I call while(true) to GetStreamCamera() method to get the frame but it not OK because the capacity is very big and it's not only 1 camera, it about 10 cameras with resolution (1280 * 960). So do we have any protocol that UWP support to stream the image from the server to UWP client?
I don't want to call while(true) to get 1 frame/call anymore.

How will USB get devices information

how can i in a UWP app get devices information connected via usb port ,at which port also. and how can i check in case of phone. can i also check that device external power source ,means device is charging via adapter or via usb cable .
You can check the remarks and code from here UsbDevice class
See the following code:
protected override async void OnLaunched1(LaunchActivatedEventArgs args)
{
UInt32 vid = 0x045E;
UInt32 pid = 0x078F;
string aqs = UsbDevice.GetDeviceSelector(vid, pid);
var myDevices = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(aqs, null);
if (myDevices.Count == 0)
{
ShowError("Device not found!");
return;
}
UsbDevice device = await UsbDevice.FromIdAsync(myDevices[0].Id);
// Send a control transfer.
UsbSetupPacket initSetupPacket = new UsbSetupPacket()
{
Request = initRequest,
RequestType = new UsbControlRequestType() {
Recipient = UsbControlRecipient.DefaultInterface,
ControlTransferType = UsbControlTransferType.Vendor
}
};
await device.SendOutControlTransferAsync(initSetupPacket);
}
From which you can loop the deviceinformation for details. Please check if you can find the info you want.

How to send Ctrl+C signal to a console process created with CreateNoWindow flag

If I use Process.Kill(), the process is killed. However, I would like to terminate it.
I tried with GenerateConsoleCtrlEvent(ConsoleCtrlEvent.CTRL_C, Process.Id) API, without success.
If I set False to CreateNoWindow flag, when I send Ctrl+C from keyboard, the program says "Caught signal: 2; Terminating". So it wait a "2" signal to terminate.
How can I do that?
There is a solution. I will try to describe it for you:
When you write the application which wraps the entire console - console into can't receive control codes for some reason (question going to Microsoft), but the console can still receive those events. How? From an external app.
This is the code for cas.exe
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace ConsoleAppStopper
{
class cas
{
[STAThread]
static void Main( string[] args )
{
if (args.Length < 2)
{
Help ();
return;
}
int processId = int.Parse (args[0]);
ConsoleCtrlEvent CtrlEvent = (ConsoleCtrlEvent)int.Parse(args[1]);
FreeConsole ();
AttachConsole (processId);
GenerateConsoleCtrlEvent (CtrlEvent, 0);
}
static void Help()
{
Console.BackgroundColor = ConsoleColor.Black;
Console.ForegroundColor = ConsoleColor.DarkYellow;
Console.WriteLine ("Console Application Eventer(Stopper)");
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine ("cas.exe ProcessId ControlEvent");
Console.WriteLine ("Events:");
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine ("\tCTRL_C - 0");
Console.WriteLine ("\tCTRL_BREAK - 1");
Console.WriteLine ("\tCTRL_LOGOFF - 5");
Console.ResetColor ();
}
public enum ConsoleCtrlEvent
{
CTRL_C = 0, // From wincom.h
CTRL_BREAK = 1,
CTRL_CLOSE = 2,
CTRL_LOGOFF = 5,
CTRL_SHUTDOWN = 6
}
[DllImport ("kernel32.dll")]
static extern bool GenerateConsoleCtrlEvent( ConsoleCtrlEvent sigevent,
int dwProcessGroupId );
[DllImport ("kernel32.dll")]
static extern bool FreeConsole();
[DllImport ("kernel32.dll")]
static extern bool AttachConsole( int dwProcessId );
}
}
and how to use it:
public void SendConsoleEvent( ConsoleCtrlEvent ev )
{
if (!Running)
return;
try
{
String current_dir = System.Environment.CurrentDirectory;
String stopper = "cas.exe";
String args = pr.Id + " " + (int)ev;
CommandExecutor ex = new CommandExecutor (null, null);
ex.Start (current_dir, stopper, args);
// sometimes stop prevent CAS do work. just throw cas and forget about
//Timer.DelayCall (TimeSpan.FromSeconds (10), ex.Stop);
//ex.Stop ();
}
catch (Exception e)
{
Log ("SendConsoleEvent: " + e.ToString ());
}
}
Here, CommandExecutor is my threaded wrapper around Process.
pr.Id is the ID of previously started using Process console (where we need to send our CTRL_C or other events