unit HIDBarcodeReader;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, BaseUnix, keyboard;
type
TInputEvent = packed record
Time: timeval;
Atype: cuint16;
Code: cuint16;
Value: cint32;
end;
{ THIDBarcodeReader }
THIDBarcodeReader = class(TObject)
private
FDeviceName: String;
FEnable: Boolean;
FTimeOut: Integer;
procedure SetEnable(AValue: Boolean);
protected
FHandle: cint;
procedure DoOpen;
procedure DoClose;
public
constructor Create;
destructor Destroy; override;
function ReadChar(var C: Char): Boolean;
property Enable: Boolean read FEnable write SetEnable;
property DeviceName: String read FDeviceName write FDeviceName;
property TimeOut: Integer read FTimeOut write FTimeOut;
end;
implementation
const
EVIOCGRAB = $40044590;
ScancodeLookup: array [0..$3F] of Char = (
// 0 1 2 3 4 5 6 7 8 9 A B C D E F
#0,'?','1','2','3','4','5','6','7','8','9','0','?','?','?','?',
'Q','W','E','R','T','Y','U','I','O','P','?','?',#13,'?','A','S',
'D','F','G','H','J','K','L','?','?','?', #0,'?','Z','X','C','V',
'B','N','M','?','?','?','?','?','?','?','?','?','?','?','?','?');
{ THIDBarcodeReader }
procedure THIDBarcodeReader.SetEnable(AValue: Boolean);
begin
if FEnable=AValue then
Exit;
if AValue then
DoOpen
else
DoClose;
end;
procedure THIDBarcodeReader.DoOpen;
begin
FHandle:= FpOpen(DeviceName,O_RDONLY);
if FHandle>=0 then
begin
FpIOCtl(FHandle,EVIOCGRAB,Pointer(1));
FEnable:= True;
end;
end;
procedure THIDBarcodeReader.DoClose;
begin
FEnable:= False;
if FHandle>=0 then
begin
FpIOCtl(FHandle,EVIOCGRAB,Nil);
FpClose(FHandle);
FHandle:= -1;
end;
end;
function THIDBarcodeReader.ReadChar(var C: Char): Boolean;
var
Buffer: TInputEvent;
FDS: TFDSet;
begin
Result:= False;
C:= #0;
while True do
begin
fpFD_ZERO(FDS);
fpFD_SET(FHandle,FDS);
if fpSelect(FHandle+1,@FDS,Nil,Nil,TimeOut) > 0 then
begin
if FpRead(FHandle,Buffer{%H-},SizeOf(TInputEvent)) > 0 then
begin
case Buffer.Atype of
0 : begin
if Buffer.Value=0 then
Result:= True;
Break;
end;
1 : if (Buffer.Value=0) and (Buffer.Code<Length(ScancodeLookup)) then
C:= ScancodeLookup[Buffer.Code];
end;
end;
end
else
Break;
end;
end;
constructor THIDBarcodeReader.Create;
begin
FHandle:= -1;
FTimeOut:= 1000;
end;
destructor THIDBarcodeReader.Destroy;
begin
DoClose;
inherited Destroy;
end;
end.