Erlang Token Ring Simulator, updated

ErlangThere’s a directory on my machine called ~/Archives. It’s not exactly… organised. :) It contains bits and pieces from the last 20 or more years – and along with the usual documents, notes and datasheets on the 74 series TTL chipset (computer engineer and computer scientist had rather different flavours in TCD back then), there’s a fair amount of code. Some of that code I can remember, other bits I look at now and think “I wrote that? Eeek…” – but there’s a small amount of code that I look at and think “Hey, I wasn’t all bad back then”. Over the new year’s holiday, I was digging around in there and came across some bits and pieces from the latter category that I thought I’d put up here for kicks, seeing as how I’d put up stuff from the PhD work and other bits and bobs already. I’ll start with this one, it’s a token ring network simulator written in Erlang somewhere in the first half of my final year in college (so late 1996 to early 1997). Erlang back then was fairly new, it was the first functional language I ever worked in (but not the first I’d heard about, I mean, it’s an older concept than I am and Haskell was going strong even back then). I’d actually heard about Erlang two summers earlier while interning at Ericsson from some of the guys working on the MXE training courses (though they weren’t using it, just wishing they were, IIRC – that was 20 years ago and my memory’s only human).

It’s actually not horrible for a piece of final year labwork, but since my notes for that course are long since gone, I don’t have any of the original design notes to hand.

tr.original.erl


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% 4D1 Project 1
%% Token Ring simulator
%%
%% Mark Dennehy
%% S.S. C.Eng. 93369425
%% mdennehy@tcd.ie
%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Known Bugs :
%% Creating a network with too many nodes can cause timeout-related
%%    problems that prevent the network from ever starting up.
%% Crashing the monitor node can lead to anomolous behaviour
%%    under apparently random sets of circumstances.
%% Malicous attempts to crash the network will usually succeed.
%%

-module(tr).
-export([start/1,ring/0,ring/1,stop/0,trnode/2,nodesearch/1,send/3,crash/1,add/1,del/1,recover/0]).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Starts up a simulated network with 3 nodes
%% ring(N)
%%    N : Number of nodes, default = 3

ring() ->
   start(3).

ring(N) ->
   start(N).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Main startup function
%% start(N)
%%    N = Number of nodes, must be positive integer

start(N) when integer(N),N>0 ->
   S = gs:start(),
   register(main,self()),
   register(firstnode,init(1,N,S)),
   io:format("Awaiting ready signals ~n",[]),
   readywait(N),
   recover(),
   firstnode!{"Token",self()},
   receive
      {"TokenReceived",RxPID} ->
         io:format("First Node acknowleging token receipt~n",[])
   end.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Spawns off the node processes

init(N,Total,S) when N<Total ->
   spawn(tr,trnode,[N,S]),
   init(N+1,Total,S);

init(N,Total,S) when N==Total ->
   spawn(tr,trnode,[N,S]).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Delay function that does not return until all the nodes have
%% completed initialisation and reported ready

readywait(N) when N>0 ->
   receive
      {"Ready",PID,N} ->
         io:format("Process ~w [Node ~w] reports ready~n",[PID,N]),
         readywait(N-1)
   end;

readywait(N) when N=<0 ->
   true.
   
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Safely stops the network
%% stop()

stop()->
    firstnode!{"Data",-1,1,"Stopping...",false,0},
    firstnode!{"Bye"},
      timer:sleep(3500),
    gs:stop(),
    exit(normal).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Find an arbitary node (requires firstnode to be defined)
%% nodesearch(N)
%%    N = Node number (must be positive integer)

nodesearch(N) when N==1 ->
   io:format("nodesearch(~w)~n",[N]),
   firstnode;

nodesearch(N) when integer(N),N>1 ->
   io:format("nodesearch(~w)~n",[N]),
   nf(N,firstnode).

%% internal process called by nodesearch()
nf(N,PID) when integer(N),N>1 ->
   io:format("nf(~w,~w)~n",[N,PID]),
   PID!{"GetDnStream",self()},
   receive
      {"DownStreamNode",P,RetPID} ->
         io:format("nf-Rx(~w,~w)~n",[P,RetPID]),
         Tmp=0
   end,
   nf(N-1,RetPID);

nf(N,PID) when N==1 ->
   io:format("nf(~w,~w)~n",[N,PID]),
   PID.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Wrapper function to get an arbitarty node to send a message to an
%% arbitary node
%% send(Nto,Nfrom,Data)
%%    Nto = Node to send message to  (must be integer greater than -1)
%%    Nfrom = Node to send message from (must be positive integer)
%%    Data = Data to send in message

send(Nto,Nfrom,Data) when integer(Nto),integer(Nfrom),Nto>-1,Nfrom>0 ->
   nodesearch(Nfrom)!{"Message",Nto,Data}.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Function to cause an arbitary node to fail, simulating a transciever
%% failure
crash(N) ->
   nodesearch(N)!{"Die"}.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Function to recover a network which has lost cohesion.
%% recover()

recover() ->
   io:format("Checking for nodes ... ~n~w~n",[processes()]),
   KeyList = find_nodes(processes(),[]),
   case lists:member(firstnode, registered()) of
      true ->
         unregister(firstnode),
         register(firstnode,element(2,get(hd(KeyList))));
      false ->
         register(firstnode,element(2,get(hd(KeyList))))
   end,
   rebuild_ends(KeyList),
   rebuild_middle(KeyList),
   firstnode!{"ElectMonitor"}.

%% internal process called by recover
rebuild_ends(KeyList) when length(KeyList) >1 ->
   A = hd(KeyList),
   B = lists:last(KeyList),
   Anode = element(2,get(A)),
   Bnode = element(2,get(B)),
   Anode!{"SetUpStream",Bnode},
   Bnode!{"SetDownStream",Anode};

%% internal process called by recover
rebuild_ends(KeyList) when length(KeyList)==1 ->
   A = get(element(1,list_to_tuple(KeyList))),
   element(2,A)!{"SetUpStream",element(2,A)},
   element(2,A)!{"SetDownStream",element(2,A)}.

%% internal process called by recover
rebuild_middle(KeyList) when length(KeyList) >1 ->
   A = hd(KeyList),
   NewKeyList = tl(KeyList),
   B = hd(NewKeyList),
   link(A,B),
   rebuild_middle(NewKeyList);

%% internal process called by recover
rebuild_middle(KeyList) when length(KeyList)==1 ->
   true.

%% internal process called by recover
link(A,B) ->
   Anode = element(2,get(A)),
   Bnode = element(2,get(B)),
   Anode!{"SetDownStream",Bnode},
   Bnode!{"SetUpStream",Anode}.

%% internal process called by recover
find_nodes([],KeyList) ->
   lists:sort(KeyList);

%% internal process called by recover
find_nodes(ProcList,KeyList) ->
   Test = hd(ProcList),
   Test!{"StatusReport",self()},
   receive
      {"NodeStatusReport",ThisPID,N,UpPID,DownPID}->
         put(N,{UpPID,ThisPID,DownPID}),
         NewKeyList = lists:append(KeyList,[N]),
         io:format("Process ~w : Node ~w : UpPID = ~w : DownPID = ~w~n",[ThisPID,N,UpPID,DownPID]),
         find_nodes(tl(ProcList),NewKeyList)

      %% The longest response time should be a little over 200 msec %%%%%%
      %% (the longest delay call in trnodeloop(...)%%%%%%%%%%%%%%%%%%%%%%%
      after 250 ->
         io:format("~nProcess ~w : No node info response received~n",[Test]),
         find_nodes(tl(ProcList),KeyList)
   end.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Adds a new node after node N
%% add(N)
%%    N = Node to insert new node after (must be positive integer)

add(N) when integer(N),N>0->
   UpPID = nodesearch(N),
   UpPID!{"GetDnStream",self()},
   receive
      {"DownStreamNode",P,DnPID} ->
         Tmp=0
   end,
   NewNode=spawn(tr,trnode,[N+1,gs:start()]),
    NewNode!{"SetUpStream",UpPID},
    NewNode!{"SetDownStream",DnPID},
   UpPID!{"SetDownStream",NewNode},
   DnPID!{"SetUpStream",NewNode},
   DnPID!{"IncrementN"}.
   
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Removes node N from the network
%% del(N)
%%    N = Node to remove from network (must be positive integer)

del(N) when integer(N),N>0 ->
   ExPID = nodesearch(N),
   ExPID!{"GetDnStream",self()},
   receive
      {"DownStreamNode",P,DnPID} ->
         Tmp=0
   end,
   ExPID!{"GetUpStream",self()},
   receive
      {"UpStreamNode",Q,UpPID} ->
         Tmp2=0
   end,
   UpPID!{"SetDownStream",DnPID},
   DnPID!{"SetUpStream",UpPID},
   DnPID!{"DecrementN"},
   ExPID!{"Die"}.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Node initialisation function
%% called internally - Do Not Touch !
%% trnode(N,S)
%%    N = Number to assign to new node
%%    S = return from gs:start()

trnode(N,S) ->
   io:format("Token Ring Node ~w Started : PID ~w ~n",[N,self()]),
   Info = io_lib:format("Process ~w~nNode ~w~n------------~n~n",[self(),N]),
   Title = io_lib:format("Token Ring Simulator : Process ~w [Node ~w]",[self(),N]),

   %% Create GUI components  
   W = gs:create(window,S,[{width,400},{height,200},{bg,black},{title,Title},{map,false}]),
   C = gs:create(canvas,W,[{width,400},{height,200},{bg,{70,70,85}}]),
   T = gs:create(oval,C,[{coords,[{350,20},{390,50}]},{bw,5},{fg,{128,128,128}},{fill,{0,0,0}}]),
   Text = gs:create(editor,W,[{vscroll,left},{bg,black},{fg,green},{insertpos,'end'},{wrap,word},{x,0},{y,0},{width,340},{height,200},{insert,{{0,0},Info}}]),
   Bclear = gs:create(button,W,[{click,true},{label,{text,"Cls"}},{height,25},{width,40},{x,350},{y,110}]),
   Bdie = gs:create(button,W,[{click,true},{label,{text,"Die"}},{height,25},{width,40},{x,350},{y,170}]),
   Bfail = gs:create(button,W,[{click,true},{label,{text,"Fail"}},{height,25},{width,40},{x,350},{y,140}]),

  %% Draw node's window and start message loop 
   gs:config(W,{map,true}),
   main!{"Ready",self(),N},
   trnodeloop(N,self(),self(),W,C,T,Bdie,Bfail,Bclear,Text,0,false,"Message",0,false,0,timer:send_after(30000,{"MonitorWatchdog"}),false,0,0,0,false,false,false).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Main node loop
%% called internally - Do Not Touch !
%% trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,
%%                   Bfail,Bclear,Text,MsgCount,MsgFlag,Msg,
%%                   MsgTo,TokenFlag,TimeoutCounter,WatchdogRef,
%%                   MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,
%%                   MFdata,MFnet)
%%    N = Node number
%%    UpStreamPID = PID of process representing the node upstream of
%%                   this node in the network
%%    DownStreamPID = PID of process representing the node downstream of
%%                   this node in the network
%%    W = Window reference
%%    C = Canvas reference
%%    T = Token Indicator reference
%%    Bdie = 'Die' button reference
%%    Bfail = 'Fail' button reference
%%    Bclear = 'Clear' button reference
%%    Text = editor window reference
%%    MsgCount = internal node count of the number of messages received
%%    MsgFlag = boolean flag indicating the node has data to transmit
%%    Msg = data the node has ready to transmit
%%    MsgTo = the address the node wishes to send it's data to
%%    TokenFlag = boolead flag indicating possession of the token
%%    TimeoutCounter = counter indicating the number of timeouts since
%%                   the last message was recieved by the node
%%    WatchdogRef = the reference of the watchdog timer that a normal node
%%                   uses to check for a monitor failure
%%    MonitorFlag = boolean flag indicating status of node as monitor
%%    RBtoken = 'Show Token' radiobutton reference
%%    RBdata = 'Show Data' radiobutton reference
%%    RBnetcheck = 'Show network messages' radiobutton reference
%%    MFtoken = MonitorFlag (boolean flag used only by monitor) to
%%                   show/hide token data
%%    MFdata = MonitorFlag (boolean flag used only by monitor) to
%%                   show/hide data packets
%%    MFnet = MonitorFlag (boolean flag used only by monitor) to
%%                   show/hide network messages

trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount,MsgFlag,Msg,MsgTo,TokenFlag,TimeoutCounter,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet) ->
   case TokenFlag of
      %% Have Token, Have Message to transmit%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
      true when MsgFlag==true ->
         tokenicon(W,C,T,"data"),
         DownStreamPID!{"Data",MsgTo,N,Msg,false,0},
         trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount,false,Msg,MsgTo,false,0,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);
         
      %% Have token, don't have Message to transmit%%%%%%%%%%%%%%%%%%%%%%%
      true when MsgFlag==false ->
         DownStreamPID!{"Token",self()},
         trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount,MsgFlag,Msg,MsgTo,false,0,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

      %% Don't have Token%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
      false ->
         receive
            %% Token processing
            {"Token",PID} ->
               case MFnet of
                  true ->
                     print(Text,io_lib:format("[~w] {Token,~w}",[MsgCount,PID]));
                  false ->
                     Tmp=0
               end,
               case MFtoken of
                  true ->
                     print(Text,"Token passing Monitor Node");
                  false ->
                     Tmp1 = 0
               end,
               tokenicon(W,C,T,"token"),
               if
                  PID==UpStreamPID ->
                     trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,true,0,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);
                  PID/=UpStreamPID ->
                     PID!{"TokenReceived",self()},
                     print(Text,io_lib:format("Node ~w receiving token from process ~w",[N,PID])),
                     trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,true,0,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet)
               end;
   
            %% Request to send message to arbitary node%%%%%%%%%%%%%%%%%%%%%
            {"Message",Nto,Data} ->
               case MFnet of
                  true ->
                     print(Text,io_lib:format("[~w] {Message,~w,~s}",[MsgCount,Nto,Data]));
                  false ->
                     Tmp = 0
               end,
               trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,true,Data,Nto,false,0,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

            %% Data Packet processing%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            {"Data",Nto,Nfrom,Data,ReadFlag,MonCount} when Nfrom==N ->
               case MFnet of
                  true ->
                     print(Text,io_lib:format("[~w] {Data,~w,~w,~s,~w,~w}",[MsgCount,Nto,Nfrom,Data,ReadFlag,MonCount]));
                  false ->
                     Tmp2=0
               end,
               case MFdata of
                  true ->
                     print(Text,io_lib:format("~nNode ~w : Receipt of self-originated Message : Nto = ~w : ~s",[N,Nto,Data]));
                  false ->
                     Tmp3 = 0
               end,
               tokenicon(W,C,T,"data"),
               case ReadFlag of  
                  true when Nto==-1 ->
                     print(Text,io_lib:format("> ~s",[Data])),
                     io:format("Node ~w : Eating Data, passing token~n",[N]),
                     DownStreamPID!{"Token",self()},
                     trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,0,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);
                     
                  true when Nto>0 ->
                     io:format("Node ~w : Eating Data, passing token~n",[N]),
                     DownStreamPID!{"Token",self()},
                     trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,0,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

                  false ->
                     case MonitorFlag of
                        true when MonCount<5 ->
                           NewMonCount=MonCount+1,
                           DownStreamPID!{"Data",Nto,Nfrom,Data,ReadFlag,NewMonCount};
                        true when MonCount>=5 ->
                           print(Text,io_lib:format("Data Packet {Data,~w,~w,~s,~w,~w} ~nhas circulated 5 times, removing from Network",[Nto,Nfrom,Data,ReadFlag,MonCount])),
                           self()!{"Token",self()};
                        false ->
                           DownStreamPID!{"Data",Nto,Nfrom,Data,ReadFlag,MonCount}
                     end,
                     trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,0,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet)
               end;

            {"Data",Nto,Nfrom,Data,ReadFlag,MonCount} when Nto==-1 ->
               case MFnet of
                  true ->
                     print(Text,io_lib:format("[~w] {Data,~w,~w,~s,~w,~w}",[MsgCount,Nto,Nfrom,Data,ReadFlag,MonCount]));
                  false ->
                     Tmp4=0
               end,
               case MFdata of
                  true ->
                     print(Text, io_lib:format("~nNode ~w : Receipt of Message : Nto = ~w : ~s~n",[N,Nto,Data]));
                  false ->
                     Tmp5 = 0
               end,
               tokenicon(W,C,T,"data"),
               print(Text,io_lib:format("> ~s",[Data])),
               case MonitorFlag of
                  true when MonCount<5 ->
                     NewMonCount=MonCount+1,
                     DownStreamPID!{"Data",Nto,Nfrom,Data,true,NewMonCount};
                  true when MonCount>=5 ->
                     print(Text,io_lib:format("Data Packet {Data,~w,~w,~s,~w,~w} ~nhas circulated 5 times, removing from Network",[Nto,Nfrom,Data,ReadFlag,MonCount])),
                     self()!{"Token",self()};
                  false ->
                     DownStreamPID!{"Data",Nto,Nfrom,Data,true,MonCount}
               end,
               trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,0,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

            {"Data",Nto,Nfrom,Data,ReadFlag,MonCount} when Nto==N ->
               case MFnet of
                  true ->
                     print(Text,io_lib:format("[~w] {Data,~w,~w,~s,~w,~w}",[MsgCount,Nto,Nfrom,Data,ReadFlag,MonCount]));
                  false ->
                     Tmp=0
               end,
               case MFdata of
                  true ->
                     print(Text, io_lib:format("~nNode ~w : Receipt of Message : Nto = ~w : ~s",[N,Nto,Data]));
                  false ->
                     Tmp1 = 0
               end,
               tokenicon(W,C,T,"data"),
               print(Text,io_lib:format("> ~s",[Data])),
               case MonitorFlag of
                  true when MonCount<5 ->
                     NewMonCount=MonCount+1,
                     DownStreamPID!{"Data",Nto,Nfrom,Data,true,NewMonCount};
                  true when MonCount>=5 ->
                     print(Text,io_lib:format("Data Packet {Data,~w,~w,~s,~w,~w} ~nhas circulated 5 times, removing from Network",[Nto,Nfrom,Data,ReadFlag,MonCount])),
                     self()!{"Token",self()};
                  false ->
                     DownStreamPID!{"Data",Nto,Nfrom,Data,true,MonCount}
               end,
               trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,0,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

            {"Data",Nto,Nfrom,Data,ReadFlag,MonCount}  ->
               case MFnet of
                  true ->
                     print(Text,io_lib:format("[~w] {Data,~w,~w,~s,~w,~w}",[MsgCount,Nto,Nfrom,Data,ReadFlag,MonCount]));
                  false ->
                     Tmp=0
               end,
               case MFdata of
                  true ->
                     print(Text, io_lib:format("~nNode ~w : Receipt of Message : Nto = ~w : ~s",[N,Nto,Data]));
                  false ->
                     Tmp1 = 0
               end,
               tokenicon(W,C,T,"data"),
               case MonitorFlag of
                  true when MonCount<5 ->
                     NewMonCount=MonCount+1,
                     DownStreamPID!{"Data",Nto,Nfrom,Data,ReadFlag,NewMonCount};
                  true when MonCount>=5 ->
                     print(Text,io_lib:format("Data Packet {Data,~w,~w,~s,~w,~w} ~nhas circulated 5 times, removing from Network",[Nto,Nfrom,Data,ReadFlag,MonCount])),
                     self()!{"Token",self()};
                  false ->
                     DownStreamPID!{"Data",Nto,Nfrom,Data,ReadFlag,MonCount}
               end,
               trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,0,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

            %% To safely shut down a ring %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            {"Bye"} ->
               case MFnet of
                  true ->
                     print(Text,io_lib:format("[~w] {Bye}",[MsgCount]));
                  false ->
                     Tmp=0
               end,
               DownStreamPID!{"Bye"},
               print(Text,"Received Termination Instruction, Quitting ..."),
               timer:sleep(2000),
               true;

            %% Up- and Down- stream node value functions%%%%%%%%%%%%%%%%%%%%
            {"SetUpStream",UpPID} ->
               case MFnet of
                  true ->
                     print(Text,io_lib:format("[~w] {SetUpStream,~w}",[MsgCount,UpPID]));
                  false ->
                     Tmp=0
               end,
               io:format("TRNode ~w : Setting Upstream node : ~w ~n",[N,UpPID]),
               print(Text,io_lib:format("Setting Upstream Node : ~w",[UpPID])),
               trnodeloop(N,UpPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,TimeoutCounter,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

            {"SetDownStream",DnPID} ->
               case MFnet of
                  true ->
                     print(Text,io_lib:format("[~w] {SetDownStream,~w}",[MsgCount,DnPID]));
                  false ->
                     Tmp=0
               end,
               io:format("TRNode ~w : Setting Downstream node : ~w ~n",[N,DnPID]),
               print(Text,io_lib:format("Setting Downstream Node : ~w",[DnPID])),
               trnodeloop(N,UpStreamPID,DnPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,TimeoutCounter,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

            {"GetUpStream",RetPID} ->
               case MFnet of
                  true ->
                     print(Text,io_lib:format("[~w] {GetUpStream,~w}",[MsgCount,RetPID]));
                  false ->
                     Tmp=0
               end,
               RetPID!{"UpStreamNode",N,UpStreamPID},
               trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,TimeoutCounter,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);
               
            {"GetDnStream",RetPID} ->
               case MFnet of
                  true ->
                     print(Text,io_lib:format("[~w] {GetDnStream,~w}",[MsgCount,RetPID]));
                  false ->
                     Tmp=0
               end,
               RetPID!{"DownStreamNode",N,DownStreamPID},
               trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,TimeoutCounter,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

            %% To crash a node from the GUI %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            {gs,Bdie,click,_,_} ->
               print(Text,"Dying!"),
               tokenicon(W,C,T,"failure"),
               true;

            %% To crash a node from the shell %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            {"Die"} ->
               print(Text,"Dying!"),
               tokenicon(W,C,T,"failure"),
               true;

            %% To fail a node from the GUI %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            {gs,Bfail,click,_,_} ->
               print(Text,"Node Failure!"),
               tokenicon(W,C,T,"failure"),
               failednodeloop(DownStreamPID,Bdie);

            %% To fail a node from the shell %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            {"Fail"} ->
               print(Text,"Node Failure!"),
               tokenicon(W,C,T,"failure"),
               failednodeloop(DownStreamPID,Bdie);

            %% For finding lost nodes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            {"StatusReport",RepPID} ->
               case MFnet of
                  true ->
                     print(Text,io_lib:format("[~w] {StatusReport,~w}",[MsgCount,RepPID]));
                  false ->
                     Tmp=0
               end,
               RepPID!{"NodeStatusReport",self(),N,UpStreamPID,DownStreamPID},
               trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,TimeoutCounter,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

            %% For Re-Numbering the nodes after network re-configuration %%%
            {"DecrementN"} when N==1 ->
               case MFnet of
                  true ->
                     print(Text,io_lib:format("[~w] {DecrementN}",[MsgCount]));
                  false ->
                     Tmp=0
               end,
               trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,TimeoutCounter,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

            {"DecrementN"} ->
               case MFnet of
                  true ->
                     print(Text,io_lib:format("[~w] {DecrementN}",[MsgCount]));
                  false ->
                     Tmp=0
               end,
               DownStreamPID!{"DecrementN"},
               Info = io_lib:format("Process ~w~nNode ~w~n------------~n~n",[self(),N-1]),
               Title = io_lib:format("Token Ring Simulator : Process ~w [Node ~w]",[self(),N-1]),
               gs:config(Text,[clear]),
               print(Text,Info),
               gs:config(W,{title,Title}),
               trnodeloop(N-1,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,TimeoutCounter,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

            {"IncrementN"} when MonitorFlag==true ->
               case MFnet of
                  true ->
                     print(Text,io_lib:format("[~w] {IncrementN}",[MsgCount]));
                  false ->
                     Tmp=0
               end,
               trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,TimeoutCounter,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

            {"IncrementN"} ->
               case MFnet of
                  true ->
                     print(Text,io_lib:format("[~w] {IncrementN}",[MsgCount]));
                  false ->
                     Tmp=0
               end,
               DownStreamPID!{"IncrementN"},
               Info = io_lib:format("Process ~w~nNode ~w~n------------~n~n",[self(),N+1]),
               Title = io_lib:format("Token Ring Simulator : Process ~w [Node ~w]",[self(),N+1]),
               gs:config(Text,[clear]),
               print(Text,Info),
               gs:config(W,{title,Title}),
               trnodeloop(N+1,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,TimeoutCounter,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

            %% Monitor Election Functions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            {"BecomeMonitor"} ->
               case MFnet of
                  true ->
                     print(Text,io_lib:format("[~w] {BecomeMonitor}",[MsgCount]));
                  false ->
                     Tmp=0
               end,
               case MonitorFlag of
                  true ->
                     trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,0,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);
                  false ->
                     print(Text,"Becoming Monitor ..."),
                     DownStreamPID!{"NewMonitor",N},
                     tr2mon(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,0,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet)
               end;

            {"NewMonitor",Nrx} ->
               case MFnet of
                  true ->
                     print(Text,io_lib:format("[~w] {NewMonitor,~w}",[MsgCount,N]));
                  false ->
                     Tmp=0
               end,
               case MonitorFlag of
                  true when Nrx > N ->
                     DownStreamPID!{"NewMonitor",N};
                  true when Nrx < N ->
                     self()!{"ResignMonitor"};
                  true when Nrx==N ->
                     Tmp1=0;
                  false ->
                     DownStreamPID!{"NewMonitor",Nrx}
               end,
               trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,0,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

            {"ResignMonitor"} when MonitorFlag==true ->
               print(Text,"Resigning from monitorhood"),
               mon2tr(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,TimeoutCounter,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

            {"ElectMonitor"} ->
               case MFnet of
                  true ->
                     print(Text,io_lib:format("[~w] {ElectMonitor}",[MsgCount]));
                  false ->
                     Tmp=0
               end,
               DownStreamPID!{"MonitorClaim",N},
               trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,0,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

            {"MonitorClaim",Nrx} when MonitorFlag==true ->
               case MFnet of
                  true ->
                     print(Text,io_lib:format("[~w] {MonitorClaim,~w}",[MsgCount,Nrx]));
                  false ->
                     Tmp=0
               end,
               trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,0,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);
               
            {"MonitorClaim",Nrx} when Nrx == N ->
               case MFnet of
                  true ->
                     print(Text,io_lib:format("[~w] {MonitorClaim,~w}",[MsgCount,Nrx]));
                  false ->
                     Tmp=0
               end,
               self()!{"BecomeMonitor"},
               trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,0,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

            {"MonitorClaim",Nrx} when Nrx > N ->
               case MFnet of
                  true ->
                     print(Text,io_lib:format("[~w] {MonitorClaim,~w}",[MsgCount,Nrx]));
                  false ->
                     Tmp=0
               end,
               DownStreamPID!{"MonitorClaim",N},
               trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,0,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);
               
            {"MonitorClaim",Nrx} when Nrx < N ->
               case MFnet of
                  true ->
                     print(Text,io_lib:format("[~w] {MonitorClaim,~w}",[MsgCount,Nrx]));
                  false ->
                     Tmp=0
               end,
               DownStreamPID!{"MonitorClaim",Nrx},
               trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,0,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

            %% Monitor Failure Detection %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            {"MonitorWatchdog"} when MonitorFlag==false ->
               spawn(tr,recover,[]),
               trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount,MsgFlag,Msg,MsgTo,false,TimeoutCounter,timer:send_after(14500,{"MonitorWatchdog"}),MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

            {"MonitorPet"} when MonitorFlag==true ->
               case MFnet of
                  true ->
                     print(Text,io_lib:format("[~w] {MonitorPet}",[MsgCount]));
                  false ->
                     Tmp=0
               end,
               trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount,MsgFlag,Msg,MsgTo,false,TimeoutCounter,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

            {"MonitorPet"} when MonitorFlag==false ->
               timer:cancel(element(2,WatchdogRef)),
               DownStreamPID!{"MonitorPet"},
               trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,TimeoutCounter,timer:send_after(30000,{"MonitorWatchdog"}),MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

            {"WatchdogPet"} when MonitorFlag==true ->
               case MFnet of
                  true ->
                     print(Text,io_lib:format("[~w] {WatchdogPet}",[MsgCount]));
                  false ->
                     Tmp=0
               end,
               timer:send_after(10000,{"WatchdogPet"}),
               DownStreamPID!{"MonitorPet"},
               trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount,MsgFlag,Msg,MsgTo,false,TimeoutCounter,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);
               
            %% Clear Screen %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            {gs,Bclear,click,_,_} ->
               case MonitorFlag of
                  true ->
                     Info = io_lib:format("Process ~w~nMonitor Node ~w~n------------~n~n",[self(),N]);
                  false ->
                     Info = io_lib:format("Process ~w~nNode ~w~n------------~n~n",[self(),N])
               end,
               gs:config(Text,[clear]),
               print(Text,Info),
               trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,TimeoutCounter,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);
           
            %% Toggle token monitoring %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            {gs,RBtoken,click,_,_} ->
               case MFtoken of
                  true ->
                     trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,TimeoutCounter,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,false,MFdata,MFnet);
                  false ->
                     trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,TimeoutCounter,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,true,MFdata,MFnet)
               end;
               
            %% Toggle data packet monitoring %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            {gs,RBdata,click,_,_} ->
               case MFdata of
                  true ->
                     trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,TimeoutCounter,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,false,MFnet);
                  false ->
                     trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,TimeoutCounter,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,true,MFnet)
               end;

            %% Toggle network message monitoring %%%%%%%%%%%%%%%%%%%%%%%%%%%
            {gs,RBnetcheck,click,_,_} ->
               case MFnet of
                  true ->
                     trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,TimeoutCounter,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,false);
                  false ->
                     trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,TimeoutCounter,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,true)
               end

            %% Non-receipt Timeout %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            after 5000 ->
               case MonitorFlag of
                  %% First Timeout on Monitor %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                  true when TimeoutCounter==0 ->
                     gs:config(Text,[{insert,{{5,0},io_lib:format("~nTimeout",[])}}]),
                     trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount,MsgFlag,Msg,MsgTo,false,1,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

                  %% First 4 Monitor Timeouts %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                  true when TimeoutCounter < 4 ->
                     gs:config(Text,[{insert,{insert,"."}}]),
                     trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount,MsgFlag,Msg,MsgTo,false,TimeoutCounter+1,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

                  %% Re-inject token to counter Lost Token Problem %%%%%%%%%%%
                  true when TimeoutCounter == 4 ->
                     gs:config(Text,[{insert,{insert,"Injecting Token"}}]),
                     DownStreamPID!{"Token",self()},
                     trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount,MsgFlag,Msg,MsgTo,false,TimeoutCounter+1,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

                  %% Token hasn't re-appeared, attempt to recover network %%%%
                  true when TimeoutCounter == 5 ->
                     gs:config(Text,[{insert,{insert,"Net Down, Attempting to Recover"}}]),
                     spawn(tr,recover,[]),
                     trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount,MsgFlag,Msg,MsgTo,false,TimeoutCounter+1,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

                  %% Wait for network re-configuration to succeed %%%%%%%%%%%%
                  true when TimeoutCounter>5, TimeoutCounter=<10 ->
                     gs:config(Text,[{insert,{insert,"."}}]),
                     trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount,MsgFlag,Msg,MsgTo,false,TimeoutCounter+1,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

                  %% Network Re-configuration has failed, enter failed loop %%
                  true when TimeoutCounter > 10 ->
                     print(Text,"Unrecoverable Network Failure"),
                     failednodeloop(DownStreamPID,Bdie);

                  %% First non-Monitor Timeout %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                  false when TimeoutCounter==0 ->
                     gs:config(Text,[{insert,{insert,io_lib:format("~nTimeout",[])}}]),
                     trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount,MsgFlag,Msg,MsgTo,false,1,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);
                     
                  %% Non-first, non-monitor timeouts %%%%%%%%%%%%%%%%%%%%%%%%%   
                  false when TimeoutCounter>0 ->
                     gs:config(Text,[{insert,{insert,"."}}]),
                     trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount,MsgFlag,Msg,MsgTo,false,TimeoutCounter+1,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet)
               end
         end
   end.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Loop to simulate a hardware failure that does not prevent echo mode
%% on the transciever
%% called internally - Do Not Touch !

failednodeloop(DownStreamPID,Bdie) ->
   receive
      %% To crash a node from the GUI %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
      {gs,Bdie,click,_,_} ->
         true;

      %% To crash a node from the shell %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
      {"Die"} ->
         true;

      %% Watchdog timer %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
      {"MonitorWatchdog"} ->
         failednodeloop(DownStreamPID,Bdie);

      %% Echo anything else straight away %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
      Any ->
         DownStreamPID!Any,
         failednodeloop(DownStreamPID,Bdie)
   end.
   
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Prints text on the node's window
%% called internally - Do Not Touch !
%% print(Text,Data)
%%    Text = reference to editor window to print in
%%    Data = text to print in window

print(Text,Data) ->
   gs:config(Text,[{insert,{{5,0},io_lib:format("~s~n",[Data])}}]),
   Text.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Manages the Token/Data indicator
%% called internally - Do Not Touch !
%% tokenicon(W,C,T,Type)
%%    W = window reference
%%    C = canvas reference
%%    T = token indicator reference
%%    Type = what to indicate

tokenicon(W,C,T,Type) ->
   case Type of
      "token" ->
         gs:config(T,{fill,{0,128,0}}),
         timer:sleep(200),
         gs:config(T,{fill,{0,0,0}});
      "failure" ->
         gs:config(T,{fill,{255,0,0}});
      "data" ->
         gs:config(T,{fill,{255,255,0}}),
         timer:sleep(200),
         gs:config(T,{fill,{0,0,0}})
   end.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Handles reconfiguration of a node's window and sundry from Normal
%% to Monitor node
%% called internally - Do Not Touch !
%% tr2mon(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,
%%                   Bfail,Bclear,Text,MsgCount,MsgFlag,Msg,
%%                   MsgTo,TokenFlag,TimeoutCounter,WatchdogRef,
%%                   MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,
%%                   MFdata,MFnet)
%%    N = Node number
%%    UpStreamPID = PID of process representing the node upstream of
%%                   this node in the network
%%    DownStreamPID = PID of process representing the node downstream of
%%                   this node in the network
%%    W = Window reference
%%    C = Canvas reference
%%    T = Token Indicator reference
%%    Bdie = 'Die' button reference
%%    Bfail = 'Fail' button reference
%%    Bclear = 'Clear' button reference
%%    Text = editor window reference
%%    MsgCount = internal node count of the number of messages received
%%    MsgFlag = boolean flag indicating the node has data to transmit
%%    Msg = data the node has ready to transmit
%%    MsgTo = the address the node wishes to send it's data to
%%    TokenFlag = boolead flag indicating possession of the token
%%    TimeoutCounter = counter indicating the number of timeouts since
%%                   the last message was recieved by the node
%%    WatchdogRef = the reference of the watchdog timer that a normal node
%%                   uses to check for a monitor failure
%%    MonitorFlag = boolean flag indicating status of node as monitor
%%    RBtoken = 'Show Token' radiobutton reference
%%    RBdata = 'Show Data' radiobutton reference
%%    RBnetcheck = 'Show network messages' radiobutton reference
%%    MFtoken = MonitorFlag (boolean flag used only by monitor) to
%%                   show/hide token data
%%    MFdata = MonitorFlag (boolean flag used only by monitor) to
%%                   show/hide data packets
%%    MFnet = MonitorFlag (boolean flag used only by monitor) to
%%                   show/hide network messages

tr2mon(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount,MsgFlag,Msg,MsgTo,TokenFlag,TimeoutCounter,WatchdogRef,MonitorFlag,0,0,0,MFtoken,MFdata,MFnet) ->
   X = gs:read(W,x),
   Y = gs:read(W,y),
   gs:config(W,{map,false}),
   gs:config(W,{height,600}),
   gs:config(C,{height,600}),
   gs:config(W,{width,610}),
   gs:config(C,{width,610}),
   gs:config(Text,[{height,600},{width,400}]),
   gs:config(T,{coords,[{550,20},{590,50}]}),
   gs:config(Bdie,[{y,565},{x,560}]),
   gs:config(Bclear,[{y,505},{x,560}]),
   gs:config(Bfail,[{y,535},{x,560}]),
   gs:config(W,[{x,X},{y,Y}]),
   RBtoken = gs:create(checkbutton,W,[{label,{text,"Tokens"}},{align,w},{width,200},{x,400},{y,100}]),
   RBdata = gs:create(checkbutton,W,[{label,{text,"Data Packets"}},{align,w},{width,200},{x,400},{y,130}]),
   RBnetcheck =gs:create(checkbutton,W,[{label,{text,"Net Msgs"}},{align,w},{width,200},{x,400},{y,160}]),
   timer:send_after(10000,{"WatchdogPet"}),
   gs:config(W,raise),
   gs:config(W,{map,true}),
   print(Text,io_lib:format("Node ~w becoming Monitor Node~n",[N])),
   trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount,MsgFlag,Msg,MsgTo,TokenFlag,TimeoutCounter,WatchdogRef,true,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Handles reconfiguration of a node's window and sundry from Monitor
%% to Normal node
%% called internally - Do Not Touch !
%% tr2mon(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,
%%                   Bfail,Bclear,Text,MsgCount,MsgFlag,Msg,
%%                   MsgTo,TokenFlag,TimeoutCounter,WatchdogRef,
%%                   MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,
%%                   MFdata,MFnet)
%%    N = Node number
%%    UpStreamPID = PID of process representing the node upstream of
%%                   this node in the network
%%    DownStreamPID = PID of process representing the node downstream of
%%                   this node in the network
%%    W = Window reference
%%    C = Canvas reference
%%    T = Token Indicator reference
%%    Bdie = 'Die' button reference
%%    Bfail = 'Fail' button reference
%%    Bclear = 'Clear' button reference
%%    Text = editor window reference
%%    MsgCount = internal node count of the number of messages received
%%    MsgFlag = boolean flag indicating the node has data to transmit
%%    Msg = data the node has ready to transmit
%%    MsgTo = the address the node wishes to send it's data to
%%    TokenFlag = boolead flag indicating possession of the token
%%    TimeoutCounter = counter indicating the number of timeouts since
%%                   the last message was recieved by the node
%%    WatchdogRef = the reference of the watchdog timer that a normal node
%%                   uses to check for a monitor failure
%%    MonitorFlag = boolean flag indicating status of node as monitor
%%    RBtoken = 'Show Token' radiobutton reference
%%    RBdata = 'Show Data' radiobutton reference
%%    RBnetcheck = 'Show network messages' radiobutton reference
%%    MFtoken = MonitorFlag (boolean flag used only by monitor) to
%%                   show/hide token data
%%    MFdata = MonitorFlag (boolean flag used only by monitor) to
%%                   show/hide data packets
%%    MFnet = MonitorFlag (boolean flag used only by monitor) to
%%                   show/hide network messages

mon2tr(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount,MsgFlag,Msg,MsgTo,TokenFlag,TimeoutCounter,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet) ->
   X = gs:read(W,x),
   Y = gs:read(W,y),
   gs:config(W,{map,false}),
   gs:config(W,[{width,400},{height,200},{bg,black}]),
   gs:config(C,[{width,400},{height,200},{bg,{70,70,85}}]),
   gs:config(T,[{coords,[{350,20},{390,50}]},{bw,5},{fg,{128,128,128}},{fill,{0,0,0}}]),
   gs:config(Text,[{vscroll,left},{bg,black},{fg,green},{insertpos,{5,0}},{wrap,word},{x,0},{y,0},{width,340},{height,200}]),
   gs:config(Bdie,[{click,true},{label,{text,"Cls"}},{height,25},{width,40},{x,350},{y,110}]),
   gs:config(Bfail,[{click,true},{label,{text,"Die"}},{height,25},{width,40},{x,350},{y,170}]),
   gs:config(Bclear,[{click,true},{label,{text,"Fail"}},{height,25},{width,40},{x,350},{y,140}]),
   gs:config(W,[{x,X},{y,Y}]),
   gs:config(W,raise),
   gs:config(W,{map,true}),
   trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount,MsgFlag,Msg,MsgTo,TokenFlag,TimeoutCounter,WatchdogRef,false,0,0,0,false,false,false).

Nice formatting, lots of comments… yeah, I didn’t party much in college :D

You can tell how old it is though – some easily fixed things like the integer() call which is one of a set of calls to test datatype which were replaced years ago by the is_integer() call and its ilk. And of course some things which are a bit more work – like gs, which isn’t the preferred graphics library anymore (wx has since replaced it). And there’s some sort of difference between the linux erlang implementation of gs and the solaris one (this code was all developed on a SPARCstation 4, which is why my wrists needed icing and I had to switch to an ergonomic keyboard by year’s end – I don’t know who designed those things’ keyboards, but I swear he hated the human hand and loved to cause carpal tunnel syndrome); because while this ran perfectly well on the solaris version in ’97, it doesn’t even fire up properly now; the nodesearch() call pings every erlang process running and the linux gs implementation responds to that ping with a failure exit :D

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
=ERROR REPORT==== 17-Jan-2014::02:41:34 ===
Supervisor received unexpected message: {"StatusReport",}

Process : No node info response received

Process : No node info response received
GS frontend. Last mgs in was:{"StatusReport",}
exit:{"StatusReport",}
Reason: {'EXIT',
{function_clause,
[{gs_frontend,doit,
[{"StatusReport",},
{state,16400,,43,undefined,undefined,}],
[{file,"gs_frontend.erl"},{line,145}]},
{gs_frontend,loop,1,[{file,"gs_frontend.erl"},{line,127}]}]}}
** exception exit: {'EXIT',{function_clause,[{gs_frontend,doit,
[{"StatusReport",},
{state,16400,,43,undefined,undefined,}],
[{file,"gs_frontend.erl"},{line,145}]},
{gs_frontend,loop,1,
[{file,"gs_frontend.erl"},{line,127}]}]}}

Okay, so quick fix is to filter that list of processes and only ping processes that are running the token ring simulator code (they’ll all be running trnode/2 as the initial call). This isn’t the most idiomatic chunk of erlang but I’m knocking off 20 years of rust here!


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
%% internal process called by recover
find_nodes(ProcList,KeyList) ->
   Test = hd(ProcList),
   Info = erlang:process_info(Test, initial_call),
   Call = element(2,element(2,Info)),
   if
      Call == trnode -> Test!{"StatusReport",self()},
      receive
         {"NodeStatusReport",ThisPID,N,UpPID,DownPID}->
            put(N,{UpPID,ThisPID,DownPID}),
            NewKeyList = lists:append(KeyList,[N]),
            io:format("Process ~w : Node ~w : UpPID = ~w : DownPID = ~w~n",[ThisPID,N,UpPID,DownPID]),
            find_nodes(tl(ProcList),NewKeyList)

         %% The longest response time should be a little over 200 msec %%%%%%
         %% (the longest delay call in trnodeloop(...)%%%%%%%%%%%%%%%%%%%%%%%
         after 250 ->
            io:format("~nProcess ~w : No node info response received~n",[Test]),
            find_nodes(tl(ProcList),KeyList)
      end;

      true -> find_nodes(tl(ProcList),KeyList)
   end.

And success!

Screenshot

And it runs properly too!

ScreenshotWell, that was a bit of fun :) I’d forgotten how different the mindset was in practice when programming in Erlang, and it’s interesting to break your rut if you’ve been programming in one language for any length of time (and I’ve been writing C/C++/Java/Python code for the last six years or so straight, and compared to Erlang, that stuff might as well all be the same). Definitely a cobweb-clearing kind of activity, and I’d recommend it for anyone with a few cycles to burn. I’m not done with this yet either – the next job is to port it over to wx from gs. That’ll take a bit more grepping through docs, looking at the difference between the two graphics engines. I’m guessing it won’t be rocket science, but it’s competing for keyboard time with some tweaking I’m doing to SCID so I don’t have a timeline for it. But there’s a certain kind of satisfaction in seeing this kind of thing brought back from almost 20 years of bitrot so it’s not getting dropped :)

 

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


Switch to our mobile site

Stochastic Geometry is Stephen Fry proof thanks to caching by WP Super Cache