{Copyright or © or Copr. :

CNRS - Laboratoire Mouvement & Perception
franck.buloup@univmed.fr

This software is a computer program whose purpose is to highly simplify  
the use of ADwinPro realtime systems when you develop experimental
protocols  on life's sciences area.

This software is governed by the CeCILL  license under French law and
abiding by the rules of distribution of free software.  You can  use, 
modify and/ or redistribute the software under the terms of the CeCILL
license as circulated by CEA, CNRS and INRIA at the following URL
"http://www.cecill.info". 

As a counterpart to the access to the source code and  rights to copy,
modify and redistribute granted by the license, users are provided only
with a limited warranty  and the software's author,  the holder of the
economic rights,  and the successive licensors  have only  limited
liability. 

In this respect, the user's attention is drawn to the risks associated
with loading,  using,  modifying and/or developing or reproducing the
software by the user in light of its specific status of free software,
that may mean  that it is complicated to manipulate,  and  that  also
therefore means  that it is reserved for developers  and  experienced
professionals having in-depth computer knowledge. Users are therefore
encouraged to load and test the software's suitability as regards their
requirements in conditions enabling the security of their systems and/or 
data to be ensured and,  more generally, to use and operate it in the 
same conditions as regards security. 

The fact that you are presently reading this means that you have had
knowledge of the CeCILL license and that you accept its terms.}
unit UCalibMonitor;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, OleCtrls, ADWINCONTROLLib_TLB, ComCtrls, StdCtrls, ExtCtrls,
  TeEngine, Series, TeeProcs, Chart, ToolWin, Math, UCalibMonitorThread;                     

type
  TCalibMonitorForm = class(TForm)
    ADwin: TADwin;
    StatusBar: TStatusBar;
    procedure FormShow(Sender: TObject);
    procedure ADwinErrorOccur(ASender: TObject;
      const FunctionName: WideString; Code: Integer);
    procedure FormDestroy(Sender: TObject);
    procedure FormResize(Sender: TObject);
    //procedure TimerCalibMonTimer(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
  private
		{ Déclarations privées }
		ADWinError : boolean;
		procedure BootADWinPro;
		procedure Tile(mode : TTileMode);
		procedure createIHM;
		procedure terminateCalibMonitorThread(Sender : TObject);
	public
		{ Déclarations publiques }
		inForm : TForm;
		outForm : TForm;
  end;

var
	CalibMonitorForm: TCalibMonitorForm;
	CalibMonitorThread : TCalibMonitorThread;

implementation

uses UDocometre, UinFrame, UOutFrame, XMLClasses, UGLobal;

{$R *.dfm}

procedure TCalibMonitorForm.BootADWinPro;
var Version : integer;
begin
  ADWin.DeviceNo := Link_Address;
	StatusBar.SimpleText := 'L''ADWinPro est prêt';
	version := Adwin.Test_Version;
  if Version <> 0 then
  begin

   if((SystemType = 'ADWINPRO') or (SystemType = 'ADWINGOLD')) then
    begin
      ADWin.Boot('c:\ADWin\ADwin9.btl');
    end;

    if(SystemType = 'ADWINPRO II') then
    begin
      ADWin.Boot('c:\ADWin\ADwin11.btl');
    end;

    if(SystemType = 'ADWINPRO II Old Cards') then
    begin
      ADWin.Boot('c:\ADWin\ADwin11.btl');
    end;

  end;
	{
	if not ADWinError then
	begin
		if DocDOCOMETRE.CTRLEAN.SEDIFF = 'SE'
		then ADWin.Set_Par(12,0)
		else ADWin.Set_Par(12,1);

		ADWin.Load_Process(rep_racine+'calibration.t9' + inttostr(Num_Process));
	end;
	}
end;

procedure TCalibMonitorForm.FormShow(Sender: TObject);
var SaveCursor : TCursor;
    priorityLevel : TThreadPriority;
		//i,DIOPROG,DIOPROG1,DIOPROG2 : integer;

begin
  ADWinError := false;
  SaveCursor := Screen.Cursor;
  Screen.Cursor := crHourGlass;
  BootADWinPro;
  Screen.Cursor := SaveCursor;
  if not ADWinError then
  begin
		createIHM;
		//Run calibthread
		//tpIdle, tpLowest, tpLower, tpNormal, tpHigher, tpHighest, tpTimeCritical
		//priorityLevel := tpNormal;
		{if Level_RecupGene = 'Idle' then priorityLevel := tpIdle;
    if Level_RecupGene = 'Lowest' then priorityLevel := tpLowest;
    if Level_RecupGene = 'Lower' then priorityLevel := tpLower;
    if Level_RecupGene = 'Normal' then priorityLevel := tpNormal;
    if Level_RecupGene = 'Higher' then priorityLevel := tpHigher;
    if Level_RecupGene = 'Highest' then priorityLevel := tpHighest;
    if Level_RecupGene = 'TimeCritical' then priorityLevel := tpTimeCritical;}
    //On force le thread calib à idle
    priorityLevel := tpIdle;
		CalibMonitorThread := TCalibMonitorThread.Create(true,priorityLevel);
		CalibMonitorThread.OnTerminate := TerminateCalibMonitorThread;
		CalibMonitorThread.Resume;
		{
		//Préparation programation des entrées/sorties numériques
		DIOPROG := 0;
		for i := 0 to DocDOCOMETRE.SNUM.Count - 1
		do DIOPROG := DIOPROG + round(power(2,DocDOCOMETRE.SNUM[i].NUMERO-1));
		DIOPROG1 := DIOPROG and 65535;
		DIOPROG2 := DIOPROG shr 16;
		//Programation des entrées/sorties numériques
		ADwin.Set_Par(10,DIOPROG1);
		ADwin.Set_Par(11,DIOPROG2);
		ADwin.Set_Par(9,1);

		//TimerCalibMon.Enabled := true;
		ADWin.Start_Process(1);  }
  end;

end;

procedure TCalibMonitorForm.ADwinErrorOccur(ASender: TObject;
  const FunctionName: WideString; Code: Integer);
var S : string;
begin
  if (FunctionName <> 'Test_Version') then
	begin
		S := 'Erreur ADWinPro - Erreur dans la fonction  "' + FunctionName + '" avec le message "' +
					ADWin.Get_Last_Error_Text(Code) + '"';
		showmessage(S);
		StatusBar.SimpleText := S;
		ADWinError := true;
	end;
end;

procedure TCalibMonitorForm.createIHM;
var newInFrame : TinFrame;
    newOutFrame : TOutFrame;
    InfoCanaux : TInfoCanaux;
    i,index,maxInWidth,maxOutWidth : integer;
begin
  maxInWidth := 0;
  maxOutWidth := 0;

  InfoCanaux := DocDOCOMETRE.RendreListeInfoCanaux;
  //DocoForm.ConfigHardFrame.RendreListeInfoCanaux;

  if inForm = nil then
  begin
    inForm := TForm.CreateParented(Self.Handle);
    inForm.Parent := Self;
    inForm.BorderStyle :=  bsSizeToolWin;
    inForm.BorderIcons := [];
    inForm.Caption := 'Entrées';
    // show Form
    inForm.Show;
    // make Form active
    SendMessage(inForm.Handle, WM_NCACTIVATE, Ord(True), 0);

    for i := 0 to DocDOCOMETRE.EAN.Count - 1 do
    begin
      index := InfoCanaux.Nom.IndexOf(DocDOCOMETRE.EAN[i].NOM);

      newInFrame := TInFrame.CreateInFrame(Self,inForm,InfoCanaux.Nom[index],false,
                                    strtoint(InfoCanaux.NumCanalCarteES[index]),
                                    DocDOCOMETRE.CTRLEAN.AMPLITUDE);

      newInFrame.setNumInDocDOCOMETRE(index);

      if newInFrame.NomCanalLabel.Width > maxInWidth
      then maxInWidth := newInFrame.NomCanalLabel.Width;
    end;

    for i := 0 to DocDOCOMETRE.ENUM.Count - 1 do
    begin
      index := InfoCanaux.Nom.IndexOf(DocDOCOMETRE.ENUM[i].NOM);

      newInFrame := TInFrame.CreateInFrame(Self,inForm,InfoCanaux.Nom[index],true,
                                    strtoint(InfoCanaux.NumCanalCarteES[index]),'');
                                    
      newInFrame.setNumInDocDOCOMETRE(index);

      if newInFrame.NomCanalLabel.Width > maxInWidth
      then maxInWidth := newInFrame.NomCanalLabel.Width;
    end;

  end;

  if outForm = nil then
  begin
    outForm := TForm.CreateParented(Self.Handle);
    outForm.Parent := Self;
    outForm.BorderStyle :=  bsSizeToolWin;
    outForm.BorderIcons := [];
    // show Form2
    outForm.Show;
    outForm.Caption := 'Sorties';
    // make Form2 active
    SendMessage(outForm.Handle, WM_NCACTIVATE, Ord(True), 0);

    for i := 0 to DocDOCOMETRE.SAN.Count - 1 do
    begin
      index := InfoCanaux.Nom.IndexOf(DocDOCOMETRE.SAN[i].NOM);

      newOutFrame := TOutFrame.CreateOutFrame(Self,OutForm,InfoCanaux.Nom[index],false,
                                    strtoint(InfoCanaux.NumCanalCarteES[index]),
                                    DocDOCOMETRE.CTRLSAN.AMPLITUDE);

      newOutFrame.setNumInDocDOCOMETRE(index);

      if newOutFrame.NomCanalLabel.Width > maxOutWidth
      then maxOutWidth := newOutFrame.NomCanalLabel.Width;

      //newOutFrame.maj_Chart;
    end;

    for i := 0 to DocDOCOMETRE.SNUM.Count - 1 do
    begin
      index := InfoCanaux.Nom.IndexOf(DocDOCOMETRE.SNUM[i].NOM);

      newOutFrame := TOutFrame.CreateOutFrame(Self,OutForm,InfoCanaux.Nom[index],true,
                                    strtoint(InfoCanaux.NumCanalCarteES[index]),'');

      newOutFrame.setNumInDocDOCOMETRE(index);

      if newOutFrame.NomCanalLabel.Width > maxOutWidth
      then maxOutWidth := newOutFrame.NomCanalLabel.Width;

      //newOutFrame.maj_Chart;
    end;


  end;
  Tile(tbVertical);

  for i := 0 to inForm.ControlCount - 1 do
  begin
    if inForm.Controls[i].ClassNameIs('TInFrame') then
    begin
      (inForm.Controls[i] as TInFrame).NomCanalLabel.AutoSize := false;
      (inForm.Controls[i] as TInFrame).NomCanalLabel.Width := maxInWidth;
      (inForm.Controls[i] as TInFrame).Panel2.Left := 1000;
    end;
  end;

  for i := 0 to outForm.ControlCount - 1 do
  begin
    if outForm.Controls[i].ClassNameIs('TOutFrame') then
    begin
      (outForm.Controls[i] as TOutFrame).NomCanalLabel.AutoSize := false;
      (outForm.Controls[i] as TOutFrame).NomCanalLabel.Width := maxOutWidth;
      (outForm.Controls[i] as TOutFrame).Panel2.Left :=
      (outForm.Controls[i] as TOutFrame).Panel1.Width;
    end;
  end;

  InfoCanaux.Free;
end;

procedure TCalibMonitorForm.FormDestroy(Sender: TObject);
begin
  if inForm <> nil then inForm.Close;
  if outForm <> nil then outForm.Close;
end;

procedure TCalibMonitorForm.FormResize(Sender: TObject);
begin
  Tile(tbVertical);
end;

procedure TCalibMonitorForm.Tile(mode : TTileMode);
var i,nbForms,TheHeight,n : integer;
begin
  nbForms := 0;
  for i := 0 to Self.ControlCount - 1 do
  begin
    if Self.Controls[i].ClassName = 'TForm'
    then if (Self.Controls[i] as TControl).Visible then inc(nbForms);
  end;
  TheHeight := self.ClientHeight - StatusBar.Height;

  n := 0;
  for i := 0 to Self.ControlCount - 1 do
  begin
    if Self.Controls[i].ClassName = 'TForm' then
    begin
      if mode = tbHorizontal then
      begin
        (Self.Controls[i] as TForm).Height := TheHeight div nbForms;
        (Self.Controls[i] as TForm).Width := self.ClientWidth;
        (Self.Controls[i] as TForm).Left := 0;
        (Self.Controls[i] as TForm).Top := n*(TheHeight div nbForms);
      end else
      begin
        (Self.Controls[i] as TForm).Height := Self.ClientHeight - statusBar.Height;
        (Self.Controls[i] as TForm).Width := self.ClientWidth div nbForms;
        (Self.Controls[i] as TForm).Left :=  n*(self.ClientWidth div nbForms);
        (Self.Controls[i] as TForm).Top := 0;
      end;
      inc(n);
    end;
  end;

end;

{procedure TCalibMonitorForm.TimerCalibMonTimer(Sender: TObject);
var i : integer;
begin

	for i := 0 to inForm.ControlCount - 1 do
	begin
		if inForm.Controls[i].ClassNameIs('TInFrame') then
		begin
			(inForm.Controls[i] as TInFrame).maj_Chart;
		end;
	end;

	for i := 0 to outForm.ControlCount - 1 do
	begin
		if outForm.Controls[i].ClassNameIs('TOutFrame') then
		begin
			(outForm.Controls[i] as TOutFrame).maj_Chart;
		end;
	end;
end;      }

procedure TCalibMonitorForm.terminateCalibMonitorThread(Sender : TObject);
begin
  CalibMonitorThread := nil;
end;


procedure TCalibMonitorForm.FormClose(Sender: TObject;
	var Action: TCloseAction);
var c1,c2,freq : int64;
		time : double;
begin
	if not ADWinError then
	begin
		if ADwin.Process_Status(num_process) = 1 then
		begin
			ADwin.Stop_Process(num_process);
			if CalibMonitorThread <> nil then
			begin
				QueryPerformanceFrequency(Freq);
				QueryPerformanceCounter(c1);
				c2 := c1;
				repeat
					QueryPerformanceCounter(c2);
					time := (c2-c1)/freq;
					if CalibMonitorThread <> nil
					then WaitForSingleObject(CalibMonitorThread.Handle,10);
					Application.ProcessMessages;
				until (time > 1.0);
			end;
		end;    
  end;
end;

end.
