I initialazed DeviceWatcher ... works fine, I add Honeywell Ring Scanner it raises event deviceWatcher. When I remove Honeywell USB Ring Scanner it raises event DeviceWatcher_Removed where I null ClaimedBarcodeScanner and BarcodeScanner object and DeviceWatcher_Updated where return status was STOP
After I connect Ring Scanner nothing happened in App. If I restart the app it's work until I disconnect and connect Ring Scanner.
I need to release BrcodeScanner from app.
I try on Honeywell D75e Win 10 iot and Honeywell Ring Scanner 8620903
I also try free memory ...
GC.Collect();
GC.WaitForPendingFinalizers();
I try to do Dispose of ClaimedBarcodeScanner
When you disconnect the device, it will raise the device removed event, but all pending operations need to be canceled properly, and all of the resources need to clean up. Please refer to following code in EventHandlerForDevice. The callback in the code is used to close the device explicitly is to clean up resources, to properly handle errors,and stop talking to the disconnected device.
private async void CloseCurrentlyConnectedDevice()
{
if (device != null)
{
// Notify callback that we're about to close the device
if (deviceCloseCallback != null)
{
deviceCloseCallback(this, deviceInformation);
}
// This closes the handle to the device
device.Dispose();
device = null;
}
}
Related
I want to check if a Serial port is disconnected or not after clicking a button in C# WinForms.
Eg:
private void btn_Click()
{
if("code to check device disconnected")
{
Do this;
}
else
{
Do this;
}}
PS: Is there any way to check that the device is disconnected when the application is running.
SerialPinchanged, ErrorRecieved, DataRecieved don't help.
Thank you in advance
It depends on the specifications of the target device connected to the COM port.
For example, if RTS/CTS or DTR/DSR are cross-connected, or if the device equivalent to a modem has a DCD or RI valid signal line, and the CTS/DSR/DCD/RI signal line shows valid connection information. , There may be a case where there is a command/response specification for health check or keep alive.
As an alternative, if the COM port is a USB Serial converter, you can check whether or not the device with the corresponding VID and PID exists, but make sure that the device is actually connected at the end of the converter. There is no guarantee.
It is simple logic that whenever SerialPort is disconnected, serialPort.IsOpen turns to false.
private void btn_Click()
{
if(!SerialPort.IsOpen)//If SerialPort is not open
{
Do this;
}
else//Else if SerialPort is open
{
Do this;
}
}
Morning all,
I'm developing a C# WPF application which continuously reads barcodes (about one every minute) from a DATALOGIC scanner (DS4800-1000) and send them to a server which replies with details about that specific barcode. This scanner is connected to a tablet running Windows 8.1 (non RT) through a USB-to-serial converter from MOXA (model UPort 1100).
Whenever a new barcode is read, the DataReceived event is fired and handled with the following method:
private void port1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Log.log(Log.LogLevel.Info, "MainScreen.port1_DataReceived");
Thread.Sleep(100);
String data = "";
// If the com port has been closed, do nothing
if (!comport1.IsOpen)
{
Log.log(Log.LogLevel.Info, "MainScreen.port1_DataReceived - COM CLOSED");
data = "COM CLOSED"; // Must be < 16 chars
}
else
{
// Obtain the number of bytes waiting in the port's buffer
int bytes = comport1.BytesToRead;
// Create a byte array buffer to hold the incoming data
byte[] buffer = new byte[bytes];
// Read the data from the port and store it in our buffer
comport1.Read(buffer, 0, bytes);
data = Encoding.Default.GetString(buffer);
Log.log(Log.LogLevel.Info, "Data received from barcode scanner number 1: " + data);
}
// COM port is handled by a different thread; this.Dispatcher calls the original thread
this.Dispatcher.Invoke((Action)(() =>
{
ExtractBarcodeData(data);
} ));
}
I'm observing a strange behavior: at random times, I see no reaction at all on the application, although the scanner actually reads a new barcode, while I would expect a new DataReceived event as the previous barcodes. Logs say me that the port is actually open and I can also close it using a specific button which closes and reopen it. Here comes the exception (on the Open() call): A device attached to the system is not functioning.
I can not reproduce this error in no way, it's totally unpredictable and random! Anyone has got any idea why the DataReceived event is not triggering?
Thanks,
FZ
Most USB-to-serial converters have this problem. They may disappear from the system and appear again. All opened handles at this situation become invalid.
Please, open the Device Manager and verify the power management tab for each USB hubs there. The system should not power off the hub.
I am doing a Bluetooth LE app on wp8.1 runtime app.
I have registered a value change event to listen when new data are coming.
heartRateMeasurementCharacteristic.ValueChanged += heartRateMeasurement_DataChanged;
private void heartRateMeasurement_DataChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
{
//do things
}
after a while the event is not triggered anymore, and rpgram throw NO exception(I checked runtime, memory etc). How can I debug this? Is that possible the event thread is down leaves without any exception?
under condition that BLE device is keep sending signal.
It's an old post, but the answer is to set heartRateMeasurementCharacteristic as a global variable.
I'm using this(link) library to detect attach and detach events of USB devices. After detecting the right device attached(identified with specific VID/PID combination) I open a serial port connection and similarly when the device is detached I close the serial port connection.
My attach event works great and at the end I get a serial port that I can use but I'm having problems inside the detach event. The detach event fires correctly but when code execution reaches closeCOM(serialPort1) point it jumps to wndProc override loop and prevents execution of closeCOM() and whatever follows.
The library needs WndProc messages to detect the events and my code is implemented like this:
//Catch Windows messages and pass them to the USBClass class
protected override void WndProc(ref Message m)
{
USBPort.ProcessWindowsMessage(ref m);
base.WndProc(ref m);
}
Then I have a detach event which executes the following code:
if (!USBClass.GetUSBDevice(VID, PID, ref USBDeviceProperties, false) && USBDeviceConnected)
{
//Device is removed
USBDeviceConnected = false;
//Close COM port just in case we forgot to disconnect
closeCOM(serialPort1);
//update status strip
strip_device_status.Text = "Disconnected";
}
and here is the closeCOM function:
//This function handles COM port closing.
private void closeCOM(SerialPort port)
{
// If a serial port is open, disconnect it
if (port.IsOpen)
{
// close the serial port
port.Close();
}
//update com port status flag
COMConnected = false;
//update status strip
strip_COM_status.Text = "Disconnected";
}
It is closeCOM() in particular that's causing this "conflict" because if I comment out that line everything works, except I'm left with an open serial port possibly causing errors later on. What am I doing wrong that's causing the code to jump to WndProc override instead of normal execution? I would like to be able to do the port closing in the detach event.
I'm using the .NET TWAIN code from http://www.codeproject.com/KB/dotnet/twaindotnet.aspx?msg=1007385#xx1007385xx in my application.
When I try to scan an image when the scanner is not plugged in, the application freezes.
How can I check if the device is plugged in, using the TWAIN driver?
Maybe I'm taking the question too literally, but using the TWAIN API, it is not possible to check if a device is plugged in i.e. connected and powered on. The TWAIN standard does define a capability for this purpose called CAP_DEVICEONLINE, but this feature is so poorly conceived and so few drivers implement it correctly that it is useless in practice.
The closest you can get is this: Open the device (MSG_OPENDS): Almost all drivers will check for device-ready when they are opened, and will display an error dialog to the user. There is no TWAIN mechanism for suppressing or detecting this dialog Some drivers will allow the user to correct the problem and continue, in which case you (your app) will never know there was a problem. Some drivers will allow the user to cancel, in which case the MSG_OPENDS operation will fail, probably returning TWRC_CANCEL but maybe TWRC_FAILURE
A few TWAIN drivers will open without error even though the device is off-line. Such a driver may return FALSE to a query of CAP_DEVICEONLINE. Such a driver will probably do the device-online check when you enable the device with MSG_ENABLEDS, and then if the device is not on-line, you get the error dialog to the user, and so on as above.
Aside and IMPO: WIA is 'more modern' but also much less comprehensive for scanning than TWAIN, and in my experience unusable for multipage scanning from a document feeder. WIA's designers and maintainers seem not to understand or care about scanners other than low-end consumer flatbeds. It's good for cameras.
I started of with the same source code that you downloaded from CodeProject, but moved most of the code in MainFrame.cs that initiates the scanning to a Scanner class. In order to check for scan errors I call the following method in stead of calling Twain.Acquire directly:
enum AcquireResult
{
OK = 0,
InitFailed = 1,
DeviceIDFailed = 2,
CapabilityFailed = 3,
UserInterfaceError = 4
}
private void StartScan()
{
if (!_msgFilter)
{
_parent.Enabled = false;
_msgFilter = true;
Application.AddMessageFilter(this);
}
AcquireResult ar = _twain.Acquire();
if (ar != AcquireResult.OK)
{
EndingScan();
switch (ar)
{
case AcquireResult.CapabilityFailed:
throw new Exception("Scanner capability setup failed");
case AcquireResult.DeviceIDFailed:
throw new Exception("Unable to determine device identity");
case AcquireResult.InitFailed:
throw new Exception("Scanner initialisation failed");
case AcquireResult.UserInterfaceError:
throw new Exception("Error with the Twain user interface");
default:
throw new Exception("Document scanning failed");
}
}
}
I usually initiate the scan event on a seperate thread in order for the app not to freeze while scanning is in progress.
just add this code on your TwainCommand (cmd)
case TwainCommand.Null:
{
EndingScan();
tw.CloseSrc();
Msgbox("There is no device or the scannning has been cancelled.");
break;
}
this will appear if the systems detect no device or the scanning has been cancelled.
You can check in the registry. In:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Class\{6bdd1fc6-810f-11d0-bec7-08002be2092f} each scanner that's ever been detected is enumerated there in the subkeys.
Starting with 0000, go through and check if the CreateFileName value is blank or has data.
If it has data, it's a connected scanner, if it's blank, it's not connected.
i try do this but dont work good with TWAIN mybe try WIA
mybe try this:
on buton run scanner
timer1.Interval = 30000;
switch (cmd)
{
case TwainCommand.TransferReady:
{
..........
}
default:
{
timer1.Start();
break;
}
on event timer tick
{
EndingScan();
tw.CloseSrc();
}