I have a C# application/windows service (and the source code) that is trying to an external USB device over serial and I want to replace the physical USB device with a virtual one made by me (another C# service/app). That would normally be straightforward as I have done that multiple times before using com0com to connect the COM port of my program with the COM port of another.
My problem is that the service uses WMI (Windows Management Instrumentation) to check for both the insertion of an USB device with a specific VID and PID (in the "PNPDeviceID"/"DeviceID") ...
this.USBInsertWatcher = new ManagementEventWatcher();
WqlEventQuery wqlEventQuery1 = new WqlEventQuery("SELECT * FROM __InstanceCreationEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_USBHub'");
this.USBInsertWatcher.EventArrived += new EventArrivedEventHandler(this.OnUSBDeviceInserted);
this.USBInsertWatcher.Query = (EventQuery) wqlEventQuery1;
this.USBInsertWatcher.Start();
... and for the associated COM port ("DeviceID") to connect to.
private string GetComPort()
{
using (ManagementObjectCollection instances = new ManagementClass("Win32_SerialPort").GetInstances())
{
foreach (ManagementBaseObject managementBaseObject in instances)
{
string str = managementBaseObject["PNPDeviceID"].ToString();
if (str.Contains(this.vendorIdStr) && str.Contains(this.productIdStr))
return managementBaseObject["DeviceID"].ToString();
}
return (string) null;
}
}
This means that I
can't choose the COM port the service connects to and
can't get the service to connect to anything in the first place :/
What I believe I need is some kind of driver that simulates a COM to USB adapter. I already have a virtual com port (opened by my other C# program)
I'm open to any kind of solution, but I should be usable on a non-virtualized Windows machine, also I can't recompile the binary because of (license/building) issues and the solution should be free.
Thank you!
Related
I'm facing a very strange three-way headache. I'm using Unity Engine and a BrainLink Bluetooth device as a source of input. I connect to the BrainLink device automatically via code using a library called Neurosky.ThinkGear and so far these two work fine together, but that's assuming the device has been paired manually via Bluetooth & Other Devices window.
Now I've been asked to also PAIR the device automatically, and this is where I hit a snag. Because using Unity Engine I can't use the windows runtime stuff (like Windows.Enumeration.Devices), I've decided to use the InTheHand 32Feet solution for Bluetooth devices and it seems to kind of work. The device appears as listed in Bluetooth & Other Devices if it wasn't already and it's listed as Paired as well. The problem is that when paired via code and not manually, the library that handles connecting to the device (aforementioned Neurosky.ThinkGear) can't connect to the device. It only connects if the device is removed and paired again via Bluetooth & Oher Devices window.
The Code I'm currently testing is as follows:
private void Start()
{
Debug.Log("Operation Start");
//btClient is a class field
btClient = new BluetoothClient();
//Search for existing paired devices that contain "brainlink" in their name
BluetoothDeviceInfo btDevice = CheckExistingPairedDevices();
if (btDevice == null)
{
Debug.Log("No paired device found, trying to discover");
//Try to discover devices in range with "brainlink" in their name
btDevice = TryDiscoverDevice();
}
if(btDevice!= null)
{
Debug.Log("Found Device " + btDevice.DeviceName+", checking for pairing");
bool paired = AttemptPair(btDevice);
Debug.Log("Pair Status: " + paired);
}
else
{
Debug.Log("Could not discover device");
}
CloseClient();
}
This is the method that handles pairing. At the moment, I never pass a value to pin but it's there just in case I need to support other devices in the future.
private bool AttemptPair(BluetoothDeviceInfo btDevice, string pin = null)
{
//Check if this device has been paired before
if (btDevice.Authenticated)
return true;
bool result = BluetoothSecurity.PairRequest(btDevice.DeviceAddress, pin);
btDevice.Refresh();
return result;
}
I have zero knowledge about your devices/tools, but what I know is that to establish a Bluetooth connection, we need to discover devices first.
The reason is that such a discovery creates an object that is later used on Bluetooth actions (e.g., pairing, connecting).
The device appears as listed in Bluetooth & Other Devices if it wasn't
already and it's listed as Paired as well.
I think by this, what you mean is previously paired devices. The device appearing on the list might not mean that the device is currently discovered. I suggest change your code accordingly where you perform discovery first.
I've been building a program to easily configure newly imaged computers (setting DNS servers, IP address, gateway, adding to AD, adding optional printers, etc). I had it working in PowerShell, but I've been trying to port it to C#, mainly to combine lots of small scripts in one, add a nice user interface, and as practice to get better at C#. It's been going well so far, but I've been having some trouble with adding a printer.
Here's the PowerShell script I was using to configure the network printer:
Add-PrinterPort -name ESDPRT500 -PrinterHostAddress $ReceiptPrinterIP
Set-Printer -Name "EPSON TM-T88IV Receipt" -PortName ESDPRT500
I've been looking at the following C# code, but it appears to only set a printer by TCP/IP port, whereas I believe my port is under "EPSON Port Handler"?
ManagementClass portClass = new ManagementClass("Win32_TCPIPPrinterPort");
ManagementObject portObject = portClass.CreateInstance();
portObject["Name"] = portName;
portObject["HostAddress"] = "174.30.164.15";
portObject["PortNumber"] = portNumber;
portObject["Protocol"] = 1;
portObject["SNMPCommunity"] = "public";
portObject["SNMPEnabled"] = true;
portObject["SNMPDevIndex"] = 1;
PutOptions options = new PutOptions();
options.Type = PutType.UpdateOrCreate;
portObject.Put(options);
Could anyone point me in the right direction given how my printer is configured? I've found examples for installing drivers and adding printers via TCP/IP port #s, but haven't had much luck with this. Thanks!
I have some C# code scanning for plug and play devices and then filtering out 2 USB devices (call them dev1 and dev2) by matching VID and PID.
Now, dev1 is directly connected to a USB port of my laptop, while dev2 is connected to a USB Hub, that is connected to my docking station, that is connected to a different laptop USB port than dev1.
Dev1 and Dev2 are different hardware and VID+PID are therefore different for both. My script does detect the 2 different hardware with the correct (and different) VID+PID.
However, the GUID is the same for both Hardware. How can this be possible? Should they not be always different?
For info, here is how I am extracting the GUID and the VID+PID:
ManagementObjectCollection collection;
using (var searcher = new ManagementObjectSearcher(#"Select * From Win32_PnPEntity"))
collection = searcher.Get();
foreach (var device in collection)
{
string deviceIdValue = (string)device.GetPropertyValue("DeviceID"); // Provides VID and PID
string guidValue = (string)device.GetPropertyValue("ClassGuid"); // Provide the GUID
...
}
That's because ClassGuid is not an object identifier but a class identifier.
If you check out the PnPClass property you'll notice that it is the same when the ClassGuid is the same.
Check this link. It lists all the ClassGuid types.
The ClassGuid is not tigh to one piece of hardware, but rather to the type of class your hardware refers to.
For instance, two difference hardware of type USB, will both have the same ClassGuid {36FC9E60-C465-11CF-8056-444553540000} as per reference.
I am writting console Application using C# and 32feet library. I want connect via bluetooth to phone device. I was following this code : link I came across a problem while pairing two devices. I am using this line to request connection:
bool isPaired = BluetoothSecurity.PairRequest(device.DeviceAddress, DEVICE_PIN);
Now auth request shows up on my phone, but there is a problem, becouse auth-code on phone is slighlty different than DEVICE_PIN. Computer trying to connect with phone, but after few minutes I get "Connection failed" info.
This is my method to pair
public void pair(int index)
{
BluetoothClient client = new BluetoothClient();
devices = client.DiscoverDevices();
BluetoothDeviceInfo device = devices[index];
bool isPaired = BluetoothSecurity.PairRequest(device.DeviceAddress, "8080");
if (isPaired)
{
Console.WriteLine("Paired: ");
}
else
{
Console.WriteLine("Not paired: ");
}
}
Try stopping the Bluetooth Windows services on your computer one by one and test.
After you stop a Windows Service, make sure to disable/enable the Bluetooth radio on your computer to take effect.
Update: This may not be "Pairing". This may just need to have a service started and bound to a port. However, this code is not storing it either. I need the device to be stored even after the application is closed.
I am building a program specifically suited for Zebra RW 420's on a Windows Mobile 6 Handheld device. The application needs to allow a mobile device to pair with the printer on COM1. I believe I am very close to getting it, but I can't get the pair request to work.
I am able to communicate with the printer and even print by directly connecting and printing, but I can't get the mobile device to actually pair with it. I've tried a variation of pins to include null, "1", "0000", and "1234". No matter what, the method always returns false. Any suggestions or ideas why this might be failing? I can pair the device just find in the WM6 Bluetooth menu, but not in my application.
It might be important to note that the little light bulb icon on the printer comes on when the program says it is attempting to pair, but after about 5 to 10 seconds, it fails.
BluetoothSecurity.PairRequest(device, "1"))
Additional Information:
I've successfully paired with my Android phone using this code.
I then logged in and set a PIN on the Zebra printer. However, this code still fails to pair with the printer even when I know the pin is correct / set in the printer.
From https://km.zebra.com/kb/index?page=answeropen&type=open&searchid=1336682809706&answerid=16777216&iqaction=5&url=https%3A%2F%2Fkm.zebra.com%2Fkb%2Findex%3Fpage%3Dcontent%26id%3DSO8031%26actp%3Dsearch%26viewlocale%3Den_US&highlightinfo=6292341,26,43#
Zebra Bluetooth enabled mobile printers are 'slave' devices only. The printers will pair with any 'master' device that tries to make a valid connection. Since only a master device can initiate a connection, the printer does not store pairing data, that function is always done on the master device. The printer can only be connected to one master device at a time, but any number of master devices that have stored pairing information for the printer would be able to initiate a connection to the printer without having to rediscover it.
I'm guessing that this means the InTheHand.Net BluetoothSecurity.PairRequest might not work for this type of pairing?
In the Bluetooth section of the WM handheld, under the "Devices" tab, I can add the device. I need to essentially do that. I need to register the device in that list and then set it to use COM 1 in the "COM Ports" section. The application I am using doesn't actually print. It's sole purpose is to prepare the printer for other applications.
The quote from Zebra make it sounds as pairing is actually not required at all. Are you printing from your app? If so just connect to the SPP service and send the text.
BluetoothAddress addr = ...
Guid serviceClass;
serviceClass = BluetoothService.SerialPort;
var ep = new BluetoothEndPoint(addr, serviceClass);
var cli = new BluetoothClient();
cli.Connect(ep);
Stream peerStream = cli.GetStream();
peerStream.Write ...
(From General Bluetooth Data Connections)
The Zebra Mobile Printer needed to be properly configured before pairing with this method will work. Here is what I did:
First, I ran the following commands on the printer:
.
! U1 setvar "bluetooth.authentication" "setpin"
! U1 getvar "bluetooth.authentication"
! U1 getvar "bluetooth.enable"
! U1 getvar "bluetooth.discoverable"
! U1 setvar "bluetooth.bluetooth_pin" "0000"
! U1 getvar "bluetooth.bluetooth_pin"
Then, the application with this code ran successfully.
.
int pair_req = 0;
try
{
if (BluetoothSecurity.SetPin(device, "0000")) {
while (status == false && pair_req < 3)
{
++pair_req;
status_box.Text = status_box.Text + '\n' + "Attempt " + pair_req.ToString();
status_box.Update();
if (BluetoothSecurity.PairRequest(device, "0000"))
{
status = true;
client.Refresh();
status_box.Text = "Paired Successfully.";
status_box.Update();
Thread.Sleep(5000);
}
else
{
status = false;
}
}
}
}
catch (ArgumentNullException e)
{
status_box.Text = "Pair failed.";
status_box.Update();
Thread.Sleep(5000);
}
status_box.Update();
Thread.Sleep(400);