program ExampleCallback;

{$ifdef MSWINDOWS}{$apptype CONSOLE}{$endif}
{$ifdef FPC}{$mode OBJFPC}{$H+}{$endif}

uses
  SysUtils, IPConnection, BrickletDistanceUS, BrickletSegmentDisplay4x7, StrUtils;

type
  TExample = class
  private
    ipcon: TIPConnection;
    dr: TBrickletDistanceUS;
    sd4x7: TBrickletSegmentDisplay4x7;
    segments: TArray0To3OfUInt8;
  public
    procedure DistanceCB(sender: TBrickletDistanceUS; const distance: word);
    procedure Execute;
  end;

const
  HOST = '127.0.0.1';
  PORT = 4223;

  UID_dr = 'q4h';
  UID_sd = 'kTT';

  DIGITS : array[0..15] of byte = ($3f,$06,$5b,$4f,
                                   $66,$6d,$7d,$07,
                                   $7f,$6f,$77,$7c,
                                   $39,$5e,$79,$71);

var
  e: TExample;

{ Callback function for distance value }
procedure TExample.DistanceCB(sender: TBrickletDistanceUS; const distance: word);
var s, temp: String; i: Integer;
begin
  temp := RightStr('0000' + Format('%d', [distance]), 4);
  for i:=1 to 4 do begin
    s := Copy(temp,i,1);
    segments[i-1] := DIGITS[StrToInt(s)];
  end;
  sd4x7.SetSegments(segments, 0, false);
end;

procedure TExample.Execute;
begin
  ipcon := TIPConnection.Create;

  sd4x7 := TBrickletSegmentDisplay4x7.Create(UID_sd, ipcon);
  dr := TBrickletDistanceUS.Create(UID_dr, ipcon);

  ipcon.Connect(HOST, PORT);

  segments[0] := DIGITS[0];
  segments[1] := DIGITS[0];
  segments[2] := DIGITS[0];
  segments[3] := DIGITS[0];
  sd4x7.SetSegments(segments, 0, false);

  dr.SetDistanceCallbackPeriod(150);

  dr.OnDistance := {$ifdef FPC}@{$endif}DistanceCB;

  WriteLn('Press key to exit');
  ReadLn;
  ipcon.Destroy;
end;

begin
  e := TExample.Create;
  e.Execute;
  e.Destroy;
end.
