{
  Damit USB Geräte für den Normalen benutzer zugänglich sind
  http://www.linux-club.de/viewtopic.php?f=61&t=112190

  vid = $147a;
  pid = $e019;

}

unit uPlUSB;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils, libusb, ExtCtrls, Forms, contnrs, LCLIntf;

type
  TPLUSB = class;
  TPLUSBDevice = class;
  TPLonData = procedure (str:string; USBDevice:TPLUSBDevice) of Object;

  { TPLRemoteKey }
  TPLRemoteKey = class
  private

  protected

  public
    Name, KeyCode, RunApp:String;
    constructor Create;
    destructor Destroy; override;
  published
  end; // TPLRemoteKey

  { TPLRemoteKeyList }
  TPLRemoteKeyList = class
  private
    function GetKeyCode(index: Integer): TPLRemoteKey;
  protected

  public
    Name:String;
    KeyList:TObjectList;
    constructor Create;
    destructor Destroy; override;

    function AddKey(const aName, aKeyCode, aRunApp:String):TPLRemoteKey;
    function FindKeyCode(const aKeyCode:String):TPLRemoteKey;
    property KeyCode[index:Integer]:TPLRemoteKey read GetKeyCode;
  published
  end; // TPLRemoteKeyList

  { TMyThread }
  TMyThread = class(TThread)
  private
    procedure OnData;
  protected
    procedure Execute; override;
  public
    b,LastB:String;
    LastTime:DWord;
    d:TPLUSBDevice;
    PLUSB:TPLUSB;
    constructor Create(CreateSuspended : boolean);
    procedure _Suspend;
  end; // TMyThread

  { TPLUSBDevice }
  TPLUSBDevice = class
  private

  protected

  public
    FUsbDevHandle: Pusb_dev_handle;
    Pid: u_int16_t;
    Vid: u_int16_t;
    id: u_int16_t;
    dev : pusbdevice;
    bus : Pusb_bus;
    b:string;
    index:Integer;
    thread:TMyThread;
    Name:String;

    RemoteKeyList:TPLRemoteKeyList;
    constructor Create;
    destructor Destroy; override;
  published
  end; // TPLUSBDevice

  { TPLUSB }
  TPLUSB = class
    fOnData: TPLonData;
  private
    function GetDevice(index: integer): TPLUSBDevice;
  protected

  public
    DeviceList:TObjectList;
    b:String;
    AppDir, ConfigDir:String;

    constructor Create;
    destructor Destroy; override;

    function FindDevice(d:TPLUSBDevice):pusbdevice;
    procedure Init;
    function AddDevice(Name:String; Pid, Vid:u_int16_t):TPLUSBDevice;

    procedure LoadFromRemoteFile(USBDevice:TPLUSBDevice);

    procedure SaveToAppRemoteFile;
    procedure LoadAppRemoteFile(USBDevice:TPLUSBDevice);

    procedure onRemoteKey(str:string; USBDevice:TPLUSBDevice);
    property Device[index:integer]:TPLUSBDevice read GetDevice;
   published
    property onData:TPLonData read fOnData write FonData;
  end;

implementation

function StrToInt2(const aStr:String):String;
var
  x,z:Integer;
  s1,h:String;
begin
  z:=0;
  for x:=1 to Length(aStr)-1 do begin
    s1:=s1+IntTostr(ord(aStr[x]));
    if x = 1 then
      h:=hexStr(ord(aStr[x]),2)
    else
      h:=h+'.'+hexStr(ord(aStr[x]),2);
  end; // for x

  result:=h;
end;

{ TPLRemoteKeyList }

function TPLRemoteKeyList.GetKeyCode(index: Integer): TPLRemoteKey;
begin
  result:=KeyList[index] as TPLRemoteKey;
end; // TPLRemoteKeyList.GetKeyCode

constructor TPLRemoteKeyList.Create;
begin
  inherited Create;
  KeyList:=TObjectList.Create;
end; // TPLRemoteKeyList.Create

destructor TPLRemoteKeyList.Destroy;
begin
  KeyList.Free;
  inherited Destroy;
end; // TPLRemoteKeyList.Destroy

function TPLRemoteKeyList.AddKey(const aName, aKeyCode, aRunApp: String): TPLRemoteKey;
begin
  Result:=KeyList[KeyList.Add(TPLRemoteKey.Create)] as TPLRemoteKey;
  Result.Name:=aName;
  Result.KeyCode:=aKeyCode;
  Result.RunApp:=aRunApp;
end; // TPLRemoteKeyList.AddKey

function TPLRemoteKeyList.FindKeyCode(const aKeyCode: String): TPLRemoteKey;
var
  i:integer;
begin
  result:=nil;
  for i:=0 to KeyList.Count-1 do begin
    if KeyCode[i].KeyCode = aKeyCode then begin
      result:=KeyCode[i];
      break;
    end;
  end; // for i
end; // TPLRemoteKeyList.FindKeyCode

{ TPLRemoteKey }

constructor TPLRemoteKey.Create;
begin
  inherited Create;
end; // TPLRemoteKey.Create

destructor TPLRemoteKey.Destroy;
begin
  inherited Destroy;
end; // TPLRemoteKey.Destroy

{ TPLUSBDevice }

constructor TPLUSBDevice.Create;
begin
  inherited Create;
  index:=0;
  RemoteKeyList:=nil;
end; // TPLUSBDevice.Create

destructor TPLUSBDevice.Destroy;
begin
  thread.Terminate;
  inherited Destroy;
end; // TPLUSBDevice.Destroy

function TPLUSB.GetDevice(index: integer): TPLUSBDevice;
begin
  result:=TPLUSBDevice(DeviceList[index]);
end; // TPLUSB.GetDevice

constructor TPLUSB.Create;
begin
  inherited Create;
  AppDir:=ExtractFileDir(ParamStr(0))+DirectorySeparator;
  ConfigDir:=AppDir+'config'+DirectorySeparator;
  if not DirectoryExists(ConfigDir) then MkDir(ConfigDir);

  usb_init();
  usb_find_busses();
  usb_find_devices();
  DeviceList:=TObjectList.Create;
  sleep(5);
end;

destructor TPLUSB.Destroy;
var
  i:Integer;
begin
  SaveToAppRemoteFile;
  for i:=0 to DeviceList.Count-1 do usb_close(Device[i].FUsbDevHandle);
  DeviceList.Free;
  inherited Destroy;
end;

function TPLUSB.FindDevice(d:TPLUSBDevice):pusbdevice;
begin
  d.bus:=usb_get_busses;
  while d.bus<>nil do begin
    d.dev:=d.bus^.devices;
    while d.dev<>nil do begin
      if (d.dev^.descriptor.idVendor=d.vid) and (d.dev^.descriptor.idProduct=d.pid) then begin
        result:=d.dev;
        exit;
      end;
      d.dev:=d.dev^.next;
    end;
    d.bus:=d.bus^.next;
  end;
  result:=nil;
end;

procedure TPLUSB.Init;
var
  ret:Integer;
  buf:PChar;
  r,r2:Integer;
  driver:array[0..20] of Char;
  s2:Longint;
  e,i:Integer;
  d:TPLUSBDevice;
begin
  for i:=0 to DeviceList.Count-1 do begin
    d:=Device[i];
    d.dev:=FindDevice(d);
    if d.dev <> NIL then begin
      d.FusbDevHandle:=usb_open(d.dev);
      sleep(5);
      if d.FUsbDevHandle<>nil then begin
        driver:='';
        e:= usb_get_driver_np(d.FUsbDevHandle, 0, driver, 20);
        if e > -1 then begin
          usb_detach_kernel_driver_np(d.FUsbDevHandle, 0);
          usb_set_configuration(d.FusbDevHandle, 1);
        end;
        usb_claim_interface(d.FusbDevHandle, 0);
        usb_set_altinterface(d.FusbDevHandle, 0);
     end;
     d.thread.Resume;
    end
    else
      writeln('nicht gefunden:',usb_strerror)
  end; // for i
end;

function TPLUSB.AddDevice(Name:String; Pid, Vid: u_int16_t): TPLUSBDevice;
var
  str:string;
begin
  result:=DeviceList[DeviceList.Add(TPLUSBDevice.Create)] as TPLUSBDevice;
  result.Pid:=pid;
  result.Vid:=Vid;
  str:=IntTostr(pid)+IntToStr(vid);
  result.id:=u_int16_t(StrToint(str));
  result.index:=DeviceList.Count;
  result.Name:=Name;
  result.thread:=TMyThread.Create(True);
  result.thread.PLUSB:=self;
  result.thread.d:=result;

  LoadFromRemoteFile(Result);
  LoadAppRemoteFile(Result);
end; // TPLUSB.AddDevice

procedure TPLUSB.LoadFromRemoteFile(USBDevice:TPLUSBDevice);
var
  StrList:TStrings;
  i,x:Integer;
  str,str1,str2,FileName:String;
begin
  FileName:=IntToStr(USBDevice.id)+'.conf';
  if FileExists(ConfigDir+FileName) then begin
    StrList:=TStringList.Create;
    StrList.LoadFromFile(ConfigDir+FileName);
    if Assigned(USBDevice.RemoteKeyList) then
      USBDevice.RemoteKeyList.KeyList.Clear
    else
      USBDevice.RemoteKeyList:=TPLRemoteKeyList.Create;

    USBDevice.RemoteKeyList.Name:=IntToStr(USBDevice.id);
    for i:=0 to StrList.Count-1 do begin
      str:=StrList[i];
      x:=Pos('=',str);
      str1:=Copy(str,1,x-1);
      str2:=Copy(str,x+1,Length(str)-x);
      USBDevice.RemoteKeyList.AddKey(str1,str2,'');
    end; // for i
    StrList.Free;
  end;
end; // TPLUSB.LoadFromRemoteFile

procedure TPLUSB.SaveToAppRemoteFile;
var
  i,x:integer;
  StrList:TStrings;
  str, str1,str2, FileName:String;
  USBDevice: TPLUSBDevice;
begin
  StrList:=TStringList.Create;
  for x:=0 to DeviceList.Count-1 do begin
    USBDevice:=Device[x];
    StrList.Clear;
    for i:=0 to USBDevice.RemoteKeyList.KeyList.Count-1 do begin
      str1:=USBDevice.RemoteKeyList.KeyCode[i].KeyCode;
      str2:=USBDevice.RemoteKeyList.KeyCode[i].RunApp;
      StrList.Add(str1+'='+str2);
    end; // for i
    FileName:=IntToStr(USBDevice.id)+'.conf2';
    if FileExists(ConfigDir+FileName) then DeleteFile(ConfigDir+FileName);
    StrList.SaveToFile(ConfigDir+FileName);
  end; // for x
  StrList.Free;
end; // TPLUSB.SaveToAppRemoteFile

procedure TPLUSB.LoadAppRemoteFile(USBDevice:TPLUSBDevice);
var
  x,i:integer;
  str,str1,str2,FileName:String;
  StrList:TStrings;
  RemoteKey:TPLRemoteKey;
begin
  StrList:=TStringList.Create;
  FileName:=IntToStr(USBDevice.id)+'.conf2';
  if FileExists(ConfigDir+FileName) then begin
    StrList.LoadFromFile(ConfigDir+FileName);
    for i:=0 to StrList.Count-1 do begin
      str:=StrList[i];
      x:=Pos('=',str);
      str1:=Copy(str,1,x-1);
      str2:=Copy(str,x+1,Length(str)-x);
      RemoteKey:=USBDevice.RemoteKeyList.FindKeyCode(str1);
      if Assigned(RemoteKey) then RemoteKey.RunApp:=str2;
    end;
  end;
  StrList.Free;
end; // TPLUSB.LoadAppRemoteFile

procedure TPLUSB.onRemoteKey(str: string; USBDevice: TPLUSBDevice);
begin
  if Assigned(onData) then onData(str,USBDevice);
end; // TPLUSB.onRemoteKey

{ TMyThread }
procedure TMyThread.OnData;
begin
  if (LastTime = 0) or  (b <> LastB) or (GetTickCount-LastTime > 180) then begin
    LastTime:=GetTickCount;
    PLUSB.onRemoteKey(StrToInt2(b), d);
    LastTime:=GetTickCount;
    LastB:=b;
  end;
end; // TMyThread.TMyThread

procedure TMyThread.Execute;
var
  i:integer;
begin
  while not Terminated do begin
    SetLength(b,4);
    if usb_interrupt_read(d.FUsbDevHandle, 1, PChar(b), 4, 0) > -1 then
      Synchronize(@OnData);
  end;

end;

constructor TMyThread.Create(CreateSuspended: boolean);
begin
  FreeOnTerminate:=False;
  inherited Create(CreateSuspended);
  SetLength(b,4);
  SetLength(LastB,4);
  LastTime:=0;
end;

procedure TMyThread._Suspend;
begin
  Suspend;
end;

end.

