unit ModbusActivexTest;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, Grids, ValEdit, modbus, comobj, ExtCtrls, StdCtrls, Spin;

type
  TForm1 = class(TForm)
    ModbusTags: TValueListEditor;
    ReadModbusTagsTimer: TTimer;
    Memo1: TMemo;
    Label4: TLabel;
    ComPortSpinEdit: TSpinEdit;
    RunButton: TButton;
    procedure FormCreate(Sender: TObject);
    procedure ReadModbusTagsTimerTimer(Sender: TObject);
    procedure RunButtonClick(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure ComPortSpinEditChange(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  mbserver: variant;
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.FormCreate(Sender: TObject);
begin
   mbserver := Createoleobject('ModbusSrv.ModbusSrv.1'); // Create server as ole object
end;

procedure TForm1.ReadModbusTagsTimerTimer(Sender: TObject);
var
   data: Variant;
   i: byte;
begin
   data := VarArrayCreate([0, 20], varvariant);
   mbserver.ReadInputRegisters(1, 0, 20, data, varword); // device, address, quantity, data, type
   for i := 0 to 19 do
   begin
      ModbusTags.Values[IntToStr(i)] := IntToStr(data[i]);
   end;
end;

procedure TForm1.RunButtonClick(Sender: TObject);
begin
   mbserver.openconnection('Serial', mblocal);  // open serial connection
   mbserver.comport := ComPortSpinEdit.Value;
   mbserver.baudrate := 19200;
   mbserver.parity:=mbEVENPARITY;
   mbserver.FlowControl := mbFC_NONE;
   mbserver.SilentInterval := 20;
   mbserver.TimeOut := 1000;
   mbserver.TransmissionMode := mbMODE_ASCII;
   mbserver.ByteSize := 7;
   mbserver.StopBits := mbONESTOPBIT;
   mbserver.raiseerror := false;

   if (mbserver.connect = true_bool) then // if connected to serial device
      ReadModbusTagsTimer.enabled := true
   else
   begin
      beep;
      MessageDlg('COM'+inttostr(mbserver.comport)+ ' could not be opened, check your port settings', mtInformation, [mbOK], 0);
   end;
end;

procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
   ReadModbusTagsTimer.Enabled := false;
   mbserver.closeconnection;
end;

procedure TForm1.ComPortSpinEditChange(Sender: TObject);
begin
   ReadModbusTagsTimer.Enabled := false;
   mbserver.closeconnection;
end;

end.
