I have to catch barcode from bluetooth SPP scanner. I can open the com port and catch all scans, however after 2 minutes the scanner goes sleep. When the scanner wakes up, it's not connected anymore but the com port still open. I need a way to find out, if the scanner still connected, or gone to sleep and close/re-open the com port when the scanner wake up again.
I pair the scanner with the pc in win10, which creates an input com port (com4). I can open that port and listen to messages. The problem is, the scanner use only 1 way communication and seems it does not send anything to say "i disconnect now", it just go sleep and disconnect. Is any way to see the scanner still connected, or gone to sleep, or anything to hook up to? The scanner is WASP WWS550i.
_serialPort = New SerialPort(PortName, BaudRate, Parity.None, 8, StopBits.One)
_serialPort.PortName = PortName
_serialPort.Parity = Parity.None
_serialPort.DataBits = 8
_serialPort.BaudRate = BaudRate
_serialPort.StopBits = StopBits.One
AddHandler _serialPort.DataReceived, AddressOf sp_DataReceived
_serialPort.Open()
Private Sub sp_DataReceived(ByVal sender As Object, ByVal e As SerialDataReceivedEventArgs)
_LastDataReceived = _serialPort.ReadLine()
End Sub
I had exactly same problem with Pos tablet scanner. ASP.CORE 3 WORKER SERVICE
I solved this issue by reopen the serial port after wake up. Also if I tried to reopen the port, the port says Port is unavailable because port was not properly closed (dispose).
My solution
I wrote 1 second checker which check the port if is still open. If is not then call close()
on previous instance of serial port, after that reopen the port.
Now I can scanning after wake up.
public class Worker : BackgroundService
{
private static SerialPort SERIAL_PORT;
// constructor DI
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
}
public override Task StartAsync(CancellationToken cancellationToken)
{
// create serial port connection
_logger.LogInformation($"-- open serial port {PORT_NAME}");
SERIAL_PORT = SerialPortFactory.Create(PORT_NAME);
SERIAL_PORT.Open();
_logger.LogInformation($"-- serial port {PORT_NAME} opened");
Task.Run(() => Checker(_logger)); // run port checker on another thread
return base.StartAsync(cancellationToken);
}
public override Task StopAsync(CancellationToken cancellationToken)
{
SERIAL_PORT.Close();
return base.StopAsync(cancellationToken);
}
public static void Checker(ILogger<Worker> _logger)
{
for (;;)
{
_logger.LogInformation("Sleep for 1 second!");
Thread.Sleep(1000);
try
{
_logger.LogInformation(SERIAL_PORT.IsOpen.ToString());
if(!SERIAL_PORT.IsOpen)
{
SERIAL_PORT.Close();
Thread.Sleep(100); // is not necessary but ...
SERIAL_PORT = SerialPortFactory.Create(PORT_NAME);
SERIAL_PORT.Open();
_logger.LogInformation($"-- serial port {PORT_NAME} opened");
}
} catch(Exception e)
{
_logger.LogError(e.Message);
}
}
}
}
SerialPortFactory - is only my simple wrapper class for new SerialPort from MS doc