-- Copyright (C) 1985  by Xerox Corporation. All rights reserved. 
-- EtherWatcher.mesa, HGM, 31-May-85  0:58:19

DIRECTORY
  Display USING [Bitmap, Invert, replaceFlags, White],
  Format USING [],  -- Needed by Put.Number
  FormSW USING [
    ClientItemsProcType, ProcType, AllocateItemDescriptor, newLine, CommandItem,
    StringItem, NumberItem],
  FileSW USING [GetFile, IsIt, SetFile],
  MFile USING [Acquire, Error, GetLength, Handle, Release],
  MsgSW USING [Post],
  MStream USING [GetLength, Handle, IsIt, Log, SetAccess, SetLength, SetLogReadLength],
  Process USING [Detach, MsecToTicks, Pause, SetTimeout],
  Put USING [Char, CR, Line, Number, Text],
  Runtime USING [GetBcdTime],
  Stream USING [GetByteProcedure, GetWordProcedure, GetProcedure, Handle],
  String USING [AppendLongNumber, AppendNumber, AppendString, Equivalent],
  System USING [GreenwichMeanTime, GetGreenwichMeanTime, AdjustGreenwichMeanTime],
  Time USING [Append, AppendCurrent, Unpack],
  Tool USING [
    Create, MakeSWsProc, UnusedLogName, MakeMsgSW, MakeFormSW, MakeFileSW,
    AddThisSW],
  ToolWindow USING [CreateSubwindow, DisplayProcType, nullBox, TransitionProcType],
  Window USING [Handle, Box],

  Buffer USING [AccessHandle, DestroyPool, GetBuffer, MakePool, ReturnBuffer],
  GateControlDefs USING [pupStatsAck, pupStatsNak, pupStatsSend],
  EthernetFormat USING [EtherStatsEntry, ethernetStatsReply, etherVersion],
  PupWireFormat USING [BcplToMesaLongNumber],
  PupDefs USING [
    AppendPupAddress, PupPackageMake, PupPackageDestroy, PupBuffer,
    PupAddress, GetPupAddress,
    PupNameTrouble, SetPupContentsWords, PupSocket, PupSocketDestroy,
    PupSocketMake, MsToTocks],
  PupTypes USING [fillInSocketID, statSoc],
  Driver;

EtherWatcher: MONITOR
  IMPORTS
    Display, FileSW, FormSW, MFile, MsgSW, MStream, Process, Put,
    Runtime, String, System, Time, Tool, ToolWindow,
    Buffer, PupDefs, PupWireFormat
  SHARES Driver =
  BEGIN OPEN PupDefs;

  msg, form, boxes, log: Window.Handle;

  running: BOOLEAN ← FALSE;
  pleaseStop: BOOLEAN ← FALSE;
  indicator: {left, right, off} ← off;
  seconds: CARDINAL ← 60;
  target: LONG STRING ← [30];
  netNumber: CARDINAL ← 7;
  where: PupAddress ← [[0], [0], PupTypes.statSoc];

  pool: Buffer.AccessHandle;
  soc: PupSocket;
  
  overheadPerPacket: CARDINAL = 2; -- CRC
  
  Start: FormSW.ProcType =
    BEGIN
    oldLogFileName: LONG STRING ← FileSW.GetFile[log].name;
    newLogFileName: STRING = [100];
    IF running THEN { MsgSW.Post[msg, "Somebody is already running..."L]; RETURN; };
    String.AppendString[newLogFileName, target];
    String.AppendString[newLogFileName, "-"L];
    String.AppendNumber[newLogFileName, netNumber, 8];
    String.AppendString[newLogFileName, ".data"L];
    IF ~String.Equivalent[oldLogFileName, newLogFileName] THEN
      BEGIN -- All this to get append mode. Yetch.
      fh: MFile.Handle ← NIL;
      bytes: LONG CARDINAL ← 0;
      sh: MStream.Handle;
      fh ← MFile.Acquire[newLogFileName, anchor, [] ! MFile.Error => CONTINUE];
      IF fh # NIL THEN {
        bytes ← MFile.GetLength[fh];
        MFile.Release[fh]; };
      sh ← MStream.Log[newLogFileName, []];
      IF bytes # 0 THEN {
        getByte: Stream.GetByteProcedure = sh.getByte;
        getWord: Stream.GetWordProcedure = sh.getWord;
        get: Stream.GetProcedure = sh.get;
        MStream.SetAccess[sh, writeOnly];
        MStream.SetLength[sh, bytes];
        MStream.SetAccess[sh, log];
        sh.getByte ← getByte;
        sh.getWord ← getWord;
        sh.get ← get; };
      FileSW.SetFile[log, newLogFileName, sh];
      IF fh = NIL THEN Put.Line[log, -- New File: Insert header for ChartPlot (and people)
"
*                         Packets      Pkts/Sec     Errors
Date       Time     P-Sent P-Recv   Sent   Recv Send Over Recv  Off
"L];
      END;
    Put.CR[log];
    Put.Text[log, "*  Watching net "L];
    O[netNumber];
    Put.Text[log, " on "L];
    IF ~FindPath[] THEN RETURN;
    running ← TRUE;
    Process.Detach[FORK Watch[seconds]];
    END;

  Stop: FormSW.ProcType = BEGIN Off[]; END;

  Off: PROCEDURE =
    BEGIN
    IF ~running THEN RETURN;
    pleaseStop ← TRUE;
    WHILE running DO Process.Pause[1]; ENDLOOP;
    pleaseStop ← FALSE;
    END;

  FindPath: PROCEDURE RETURNS [BOOLEAN] =
    BEGIN
    Put.Text[log, target];
    Put.Char[log, '=];
    GetPupAddress[
      @where, target !
      PupNameTrouble =>
        BEGIN MsgSW.Post[msg, e]; Put.Line[log, e]; GOTO Trouble; END];
    PrintPupAddress[where];
    Put.Line[log, "."L];
    RETURN[TRUE];
    EXITS Trouble => RETURN[FALSE];
    END;


  Watch: ENTRY PROCEDURE [seconds: CARDINAL] =
    BEGIN
    startTime, stopTime, targetTime: System.GreenwichMeanTime;
    actual: LONG CARDINAL;
    pause: CONDITION;
    MakeConnection[];
    SetupBoxes[];
    Process.SetTimeout[@pause, Process.MsecToTicks[500]];
    UNTIL pleaseStop DO -- Wait until even multiple of seconds
      targetTime ← System.GetGreenwichMeanTime[];
      IF (targetTime MOD seconds) = 0 THEN EXIT;
      WAIT pause;
      ENDLOOP;
    startTime ← targetTime;
    GetInfo[];
    oldInfo ← newInfo;
    Put.CR[log];
    UNTIL pleaseStop DO
      WHILE System.GetGreenwichMeanTime[] - targetTime >= seconds DO
        IF targetTime > System.GetGreenwichMeanTime[] THEN EXIT;  -- Clock set backwards ==> hang
        -- Oops, it took us more than a cycle to process everything.
        -- Maybe we were sitting in the debugger.
        targetTime ← System.AdjustGreenwichMeanTime[targetTime, seconds];
        ENDLOOP;
      UNTIL pleaseStop OR (System.GetGreenwichMeanTime[] - targetTime) >= seconds DO
        WAIT pause; ENDLOOP;
      IF pleaseStop THEN EXIT;
      GetInfo[];
      stopTime ← System.GetGreenwichMeanTime[];
      actual ← stopTime - startTime;
      IF pleaseStop THEN EXIT;
      PrintInfo[actual];
      oldInfo ← newInfo;
      startTime ← stopTime;
      targetTime ← System.AdjustGreenwichMeanTime[targetTime, seconds];
      ENDLOOP;
    SetDownBoxes[];
    KillConnection[];
    running ← FALSE;
    END;

  EtherInfo: TYPE = RECORD [
    packetsSent: LONG CARDINAL,
    badSendStatus: LONG CARDINAL,
    overruns: LONG CARDINAL,
    packetsRecv: LONG CARDINAL,
    badRecvStatus: LONG CARDINAL,
    inputOff: LONG CARDINAL ];
    
  oldInfo, newInfo: EtherInfo;

  thisID: CARDINAL ← 0;
  GetInfo: PROCEDURE =
    BEGIN
    b: PupBuffer;
    thisID ← thisID + 1;
    DO  -- until we get the answer
      b ← Buffer.GetBuffer[pup, pool, send];
      b.pup.pupID ← [thisID, thisID];
      b.pup.pupType ← GateControlDefs.pupStatsSend;
      b.pup.pupWords[0] ← netNumber;
      SetPupContentsWords[b, 1];
      soc.put[b];
      FlipBoxes[];
      DO
        b ← soc.get[];
        IF b = NIL THEN EXIT;
        IF b.pup.pupType = error OR b.pup.pupType = GateControlDefs.pupStatsNak
          OR b.pup.pupID.b # thisID THEN BEGIN Buffer.ReturnBuffer[b]; LOOP; END;
        IF b.pup.pupType # GateControlDefs.pupStatsAck THEN ERROR;
        IF b.pup.pupWords[0] # EthernetFormat.ethernetStatsReply THEN ERROR;
        IF b.pup.pupWords[1] # EthernetFormat.etherVersion THEN ERROR;
        EXIT;
	ENDLOOP;
      IF b # NIL THEN EXIT;
      IF pleaseStop THEN RETURN;
      LOOP;
      ENDLOOP;
    FlipBoxes[];
    CopyData[b];
    Buffer.ReturnBuffer[b];
    END;

  CopyData: PROCEDURE [b: PupBuffer] =
    BEGIN
    ese: LONG POINTER TO EthernetFormat.EtherStatsEntry ← LOOPHOLE[@b.pup.pupWords[1]];
    newInfo ← [
      packetsSent: PupWireFormat.BcplToMesaLongNumber[ese.packetsSent],
      badSendStatus: PupWireFormat.BcplToMesaLongNumber[ese.badSendStatus],
      overruns: PupWireFormat.BcplToMesaLongNumber[ese.overruns],
      packetsRecv: PupWireFormat.BcplToMesaLongNumber[ese.packetsRecv],
      badRecvStatus: PupWireFormat.BcplToMesaLongNumber[ese.badRecvStatus],
      inputOff: PupWireFormat.BcplToMesaLongNumber[ese.inputOff] ];
    END;

  PrintInfo: PROCEDURE [actual: LONG CARDINAL] =
    BEGIN
    temp: EtherInfo ← [
      packetsSent: newInfo.packetsSent-oldInfo.packetsSent,
      badSendStatus: newInfo.badSendStatus-oldInfo.badSendStatus,
      overruns: newInfo.overruns-oldInfo.overruns,
      packetsRecv: newInfo.packetsRecv-oldInfo.packetsRecv,
      badRecvStatus: newInfo.badRecvStatus-oldInfo.badRecvStatus,
      inputOff: newInfo.inputOff-oldInfo.inputOff ];
    PrintTime[];
    Put.Text[log, " "];
    IF LOOPHOLE[temp.packetsSent, LONG INTEGER] < 0 THEN temp.packetsSent ← 0;
    IF LOOPHOLE[temp.badSendStatus, LONG INTEGER] < 0 THEN temp.badSendStatus ← 0;
    IF LOOPHOLE[temp.overruns, LONG INTEGER] < 0 THEN temp.overruns ← 0;
    IF LOOPHOLE[temp.packetsRecv, LONG INTEGER] < 0 THEN temp.packetsRecv ← 0;
    IF LOOPHOLE[temp.badRecvStatus, LONG INTEGER] < 0 THEN temp.badRecvStatus ← 0;
    IF LOOPHOLE[temp.inputOff, LONG INTEGER] < 0 THEN temp.inputOff ← 0;
    LD7[temp.packetsSent];
    LD7[temp.packetsRecv];
    LD7[temp.packetsSent/actual];
    LD7[temp.packetsRecv/actual];
    IF TRUE OR (temp.badSendStatus # 0) OR (temp.badRecvStatus # 0) THEN
        BEGIN
	LD5[temp.badSendStatus];
	LD5[temp.overruns];
	LD5[temp.badRecvStatus];
	LD5[temp.inputOff];
	END;
    Put.CR[log];
    ForceOutInfo[log];
    END;

  PrintTime: PROCEDURE =
    BEGIN
    text: STRING = [20];
    Time.AppendCurrent[text];
    Put.Text[log, text]
    END;

  PrintPupAddress: PROCEDURE [a: PupAddress] =
    BEGIN
    text: STRING = [20];
    AppendPupAddress[text, a];
    Put.Text[log, text];
    END;

  O: PROCEDURE [n: CARDINAL] =
    BEGIN
    Put.Number[log, n, [8, FALSE, TRUE, 0]];
    END;

  O2: PROCEDURE [n: CARDINAL] =
    BEGIN
    Put.Char[log, ' ];
    Put.Number[log, n, [8, FALSE, TRUE, 1]];
    END;

  O3: PROCEDURE [n: CARDINAL] =
    BEGIN
    Put.Char[log, ' ];
    Put.Number[log, n, [8, FALSE, TRUE, 2]];
    END;

  D: PROCEDURE [n: CARDINAL] =
    BEGIN
    Put.Number[log, n, [10, FALSE, TRUE, 0]];
    END;

  D2: PROCEDURE [n: CARDINAL] =
    BEGIN
    Put.Char[log, ' ];
    Put.Number[log, n, [10, FALSE, TRUE, 1]];
    END;

  D3: PROCEDURE [n: CARDINAL] =
    BEGIN
    Put.Char[log, ' ];
    Put.Number[log, n, [10, FALSE, TRUE, 2]];
    END;

  D4: PROCEDURE [n: CARDINAL] =
    BEGIN
    Put.Char[log, ' ];
    Put.Number[log, n, [10, FALSE, TRUE, 3]];
    END;

  LD2: PROCEDURE [num: LONG INTEGER] =
    BEGIN
    s: STRING = [20];
    Put.Char[log, ' ];
    String.AppendLongNumber[s, num, 10];
    THROUGH [s.length..1) DO Put.Char[log, ' ]; ENDLOOP;
    Put.Text[log, s];
    END;

  LD3: PROCEDURE [num: LONG INTEGER] =
    BEGIN
    s: STRING = [20];
    Put.Char[log, ' ];
    String.AppendLongNumber[s, num, 10];
    THROUGH [s.length..2) DO Put.Char[log, ' ]; ENDLOOP;
    Put.Text[log, s];
    END;

  LD5: PROCEDURE [num: LONG INTEGER] =
    BEGIN
    s: STRING = [20];
    Put.Char[log, ' ];
    String.AppendLongNumber[s, num, 10];
    THROUGH [s.length..4) DO Put.Char[log, ' ]; ENDLOOP;
    Put.Text[log, s];
    END;

  LD7: PROCEDURE [num: LONG INTEGER] =
    BEGIN
    s: STRING = [20];
    Put.Char[log, ' ];
    String.AppendLongNumber[s, num, 10];
    THROUGH [s.length..6) DO Put.Char[log, ' ]; ENDLOOP;
    Put.Text[log, s];
    END;

  LD9: PROCEDURE [num: LONG INTEGER] =
    BEGIN
    s: STRING = [20];
    String.AppendLongNumber[s, num, 10];
    Put.Char[log, ' ];
    THROUGH [s.length..8) DO Put.Char[log, ' ]; ENDLOOP;
    Put.Text[log, s];
    END;

  MakeConnection: PROCEDURE =
    BEGIN
    pool ← Buffer.MakePool[send: 1, receive: 10];
    soc ← PupSocketMake[PupTypes.fillInSocketID, where, MsToTocks[1000]];
    END;

  KillConnection: PROCEDURE =
    BEGIN
    PupSocketDestroy[soc];
    Buffer.DestroyPool[pool];
    END;

  indicatorBox: Window.Box = [[25, 10], [16, 16]];
  DisplayBoxes: ToolWindow.DisplayProcType =
    BEGIN
    pattern: ARRAY [0..1] OF ARRAY [0..8) OF WORD;
    left: WORD = 177400B;
    right: WORD = 000377B;
    SELECT indicator FROM
      left => pattern ← [ALL[left], ALL[right]];
      right => pattern ← [ALL[right], ALL[left]];
      off => pattern ← [ALL[0], ALL[0]];
      ENDCASE;
    Display.Bitmap[window, indicatorBox, [@pattern, 0, 0], 16, Display.replaceFlags]
    END;

  SetupBoxes: PROCEDURE = BEGIN indicator ← left; DisplayBoxes[boxes]; END;

  FlipBoxes: PROCEDURE =
    BEGIN
    SELECT indicator FROM
      left => indicator ← right;
      off, right => indicator ← left;
      ENDCASE;
    Display.Invert[boxes, indicatorBox];
    END;

  SetDownBoxes: PROCEDURE =
    BEGIN indicator ← off; Display.White[boxes, indicatorBox]; END;

  MakeBoxesSW: PROCEDURE [window: Window.Handle] =
    BEGIN
    box: Window.Box ← ToolWindow.nullBox;
    box.dims.h ← 36;
    boxes ← ToolWindow.CreateSubwindow[parent: window, display: DisplayBoxes, box: box];
    Tool.AddThisSW[window: window, sw: boxes, swType: vanilla];
    END;

  MakeSWs: Tool.MakeSWsProc =
    BEGIN
    logFileName: STRING = [40];
    msg ← Tool.MakeMsgSW[window: window, lines: 5];
    form ← Tool.MakeFormSW[window: window, formProc: MakeForm];
    MakeBoxesSW[window];
    Tool.UnusedLogName[logFileName, "EtherWatcher.log$"L];
    log ← Tool.MakeFileSW[window: window, name: logFileName, allowTypeIn: FALSE];
    END;

  MakeForm: FormSW.ClientItemsProcType =
    BEGIN
    nParams: CARDINAL = 5;
    items ← FormSW.AllocateItemDescriptor[nParams];
    items[0] ← FormSW.CommandItem[
      tag: "Stop"L, proc: Stop, place: FormSW.newLine];
    items[1] ← FormSW.CommandItem[tag: "Start"L, proc: Start];
    items[2] ← FormSW.NumberItem[tag: "Seconds"L, value: @seconds, default: 60];
    items[3] ← FormSW.NumberItem[
      tag: "NetNumber"L, value: @netNumber, default: 7, radix: octal];
    items[4] ← FormSW.StringItem[tag: "Target"L, string: @target];
    RETURN[items, TRUE];
    END;

  ClientTransition: ToolWindow.TransitionProcType =
    BEGIN
    SELECT TRUE FROM
      old = inactive =>
        BEGIN
	IF target.length = 0 THEN String.AppendString[target, "ME"L];
	PupDefs.PupPackageMake[];
	END;
      new = inactive =>
        BEGIN IF running THEN Off[]; PupDefs.PupPackageDestroy[]; END;
      ENDCASE;
    END;

  ForceOutInfo: PROCEDURE [wh: Window.Handle] =
    BEGIN
    sh: Stream.Handle;
    IF ~FileSW.IsIt[wh] THEN RETURN;
    sh ← FileSW.GetFile[wh].s;
    IF ~MStream.IsIt[sh] THEN RETURN;
    MStream.SetLogReadLength[sh, MStream.GetLength[sh]];
    END;

  Init: PROCEDURE =
    BEGIN
    herald: STRING = [100];
    String.AppendString[herald, "EtherWatcher of  "L];
    Time.Append[herald, Time.Unpack[Runtime.GetBcdTime[]]];
    [] ← Tool.Create[
      name: herald, makeSWsProc: MakeSWs, clientTransition: ClientTransition];
    END;

  Init[];

  END.