unit SPDAu;
{ Interface to B&B Electronics RS-232 Data Acquisition Module Model 232SPDA
  for CHROMuLAN. }

interface

implementation
uses
  SysUtils, Classes,
  Fifou, Timer, IniFiles, IniClassu,
  UlanType, GenDevu
  ; //proputl iniobju

type
  TSPDAs = class(TGenDevs)
  private
    FChannelCount: integer;
  protected
    procedure SetDefault;override;
    function GetDeviceList: string; override;
  published
    property ChannelCount: integer read FChannelCount write FChannelCount;
  end;

procedure TSPDAs.SetDefault;
begin
  FChannelCount := 8;
end;

function TSPDAs.GetDeviceList: string;
var i: integer;
begin
  Result := '';
  for i := 0 to ChannelCount - 1 do begin
    Result := Result + 'Input' + IntToStr(i);
    if i < ChannelCount - 1 then
      Result := Result + ',';
  end;
  //FDeviceList := 'Input0,Input1,Input2,Input3,Input4,Input5,Input6,Input7';
end;


type
  TSPDADrv = class(TGenDev)
  private
    //FChannelCount: integer;
    //FChannel: integer;
    FRepeatPktReqStrCount: integer;
    function GetChannel: integer;
    function GetChannelCount: integer;
  protected
    //function DoCharIn(ch: char): integer; override;
    function IsInputPacketFinished: boolean; override;
    function ExtractCurVal: boolean; override;
    procedure DoAfterCreate; override;
    procedure SetDefaults; override;

    property Channel: integer read GetChannel;
  public
    property ChannelCount: integer read GetChannelCount;
  published
    property RepeatPktReqStrCount: integer read FRepeatPktReqStrCount write FRepeatPktReqStrCount;
  end;


function TSPDADrv.GetChannelCount: integer;
begin
  Result := TSPDAs(Owner).ChannelCount;
end;

procedure TSPDADrv.SetDefaults;
begin
  //FChannelCount := 1;
  FRepeatPktReqStrCount := 1;
end;


function TSPDADrv.GetChannel: integer;
var
  i, code: integer;
begin
  val(copy(Name, 6, 1), i, code);
  Result := i;
end;

procedure TSPDADrv.DoAfterCreate;
var i: integer; s: string;
begin
  //if FChannelCount <= 0 then
  //  FChannelCount := 1;
  FPktReqStr := '!0RA' + chr(ChannelCount-1);
  FPktReqStrConstant := true;
  if FRepeatPktReqStrCount = 0 then
    FRepeatPktReqStrCount := 1;

  if FRepeatPktReqStrCount > 1 then begin
    s := FPktReqStr;
    for i := 1 to FRepeatPktReqStrCount  do begin
      FPktReqStr := FPktReqStr + s;
    end;
  end;
end;

function TSPDADrv.IsInputPacketFinished: boolean;
begin
  Result := length(FCurPkt) >= 2 * ChannelCount;
end;

function TSPDADrv.ExtractCurVal: boolean;
begin
  if length(FCurPkt) >= 2 * ChannelCount then begin
    FCurVal := ord(FCurPkt[Channel * 2 + 1]) * 256 + ord(FCurPkt[Channel * 2 + 2]);
    FCurPkt := copy(FCurPkt, 2 * ChannelCount + 1, length(FCurPkt));
    Result := true;
  end else begin
    Result := false;
  end;
end;

initialization
  GenDevClass := TSPDADrv;
  GenDevsClass := TSPDAs;
finalization
end.
