#Create a cable network with multiple CM's
#
#     UDP Monitor                                                   UDP Monitor
#     ping                                                          ping
#             1000Mbps     CMTS (27Mbpsdown/5.12mbps up)    CM      
# 10.109.12.5 $n2 --------    cmts(n0)  -------------------------- n1   
#             $n4                              |-CM-1
#             $n5                              |-CM-2
#                                              |-CM-3
#
#  There are two steps to setting up the application traffic.
#  First, you setup the applications running on the n1 monitor node.
#  Second, you setup the applications running on each CM.
#  If numberCMs.tcl is 0, then only the n1 CM  exists
#
#  For all cases the 'client' side is determined by the tcl varialbe
#     TRAFFIC_DIRECTION:  0 means upstream, 1 means downstream
#
#  To turn on the different flows at node n1
#      set doPINGMONITOR 1
#
#  set UDP_MONITOR_TYPE  
#     Value:0 no UDP monitor
#     Value:1 CBR traffic source to a UGS service flow
#     Value:2 CBR traffic source to the default BE service flow
#     Value:3 CBR traffic source to a VBR service flow
#
#  To turn on and adjust the per CM flows
#      numberCMs.tcl : if > 0 creates a TCP flow for each
#      set ALL_UDP :  value 0: all TCP   value 1: all UDP
#      set UDP_TRAFFIC : value 0: CBR   value 1 EXP
#            If TCP traffic is selected it will be FTP
# 
#



#Invoke a new ns object
set ns [new Simulator]


source networks.tcl
source docsis-helper.tcl
source ping-helper.tcl
source goruns.dat
source numberCMs.tcl 
source cleanup.tcl

source simulation.tcl

#Setup application traffic

set CMBKSCALE 1

#Set to 1 to turn on the ping
set doPINGMONITOR 1

# The UDP_MONITOR_TYPE variable sets the details
# of the UDP flow attached to the n1 CM
#  Value:0 no UDP monitor
#  Value:1 CBR traffic source to a UGS service flow
#  Value:2 CBR traffic source to the default BE service flow
#  Value:3 CBR traffic source to a VBR service flow
set UDP_MONITOR_TYPE 2 


#if 1, all UDP.  If 0, all TCP
set ALL_UDP 1

# value 0: CBR   value 1 EXP  value 2 Pareto
set UDP_TRAFFIC 0

#If 1, all application flow is DS (else 0 upstream)
set TRAFFIC_DIRECTION 1

#Done setting up application traffic

if {$ALL_UDP == 1} {
  puts "Start a run with $numberCMs CMs,, all UDP traffic and direction $TRAFFIC_DIRECTION "
} elseif {$ALL_UDP == 0} {
  puts "Start a run with $numberCMs CMs,, all TCP traffic and direction $TRAFFIC_DIRECTION "
} else {
    puts "ERROR:  ALL_UDP not set correctly: $ALL_UDP "
    exit 0
}

cleanup


#TCP flow settings
#PROTID
#   1: Reno
#   2: Newreno
#   3: Vegas (CAM only)
#   7: ECN
#   8: Full TCP
set PACKETSIZE 1000
set BURSTTIME .08
#set BURSTTIME .008
set IDLETIME  .5
set BURSTRATE     10000000
set SHAPE 0

#set protID 9
#set WRTprotID 1
set WRTprotID 9
set protID 9

#32K buffer
#set WINDOW 22

#64K buffer
#set WINDOW 44

#1 Mbyte buffer
set WINDOW 685

#2.25 Mbyte buffer
#set WINDOW 1500



#UDP flow settings
# 1000 bytes and .008 seconds is 1 mbps
# 1000 bytes and .004 seconds is 2 mbps
# 1000 bytes and .002 seconds is 4 mbps
# 1000 bytes and .0008 seconds is 10 mbps
# 1000 bytes and .0004 seconds is 20 mbps
# 1000 bytes and .0003 seconds is 26.7 mbps
# 1000 bytes and .0002 seconds is 40 mbps
# 1000 bytes and .0001 seconds is 80 mbps
# 1460 bytes at .04 = 292,000 bps
#set INTERVAL .0008

#80Mmbps
#set INTERVAL .0001

#60Mbps
#set INTERVAL .00015

#40Mbps
#set INTERVAL .0002

#12.0Mbps
#set INTERVAL .000666

#1 Mbps
set INTERVAL .008

#512Kbps
#set INTERVAL .016

# 1000 bytes and .002 seconds is 4 mbps
#set INTERVAL .002

#set stoptime 100.5
set printtime [expr $stoptime - .00000001]
#set printtime $stoptime 


#build basic topology (n1 is a CM, n0 the CMTS, n2 a tcp sink)
# n2 --------    n0 -------------------------- n1
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n4 [$ns node]
set n5 [$ns node]

#Adjust the prop delay to make it be 60ms rtt
#for this model, make it 1.5mbps (a T1 link)
#$ns duplex-link $n0 $n2 1.5Mb 24ms DropTail

$ns simplex-link $n2 $n0 1000Mb .5ms DropTail
$ns simplex-link $n0 $n2 1000Mb .5ms DropTail


$ns queue-limit $n2 $n0 200 
$ns queue-limit $n0 $n2 200 

#I HERE
set loss_modulexnet [new ErrorModel]
$loss_modulexnet set errModelId 2
# .03 is 3%
#$loss_modulexnet set rate_ 0.03

$loss_modulexnet set rate_ 0.0
#$loss_modulexnet set rate_ 0.01

$loss_modulexnet unit pkt
$loss_modulexnet ranvar [new RandomVariable/Uniform]
$loss_modulexnet drop-target [new Agent/Null]
$ns lossmodel $loss_modulexnet $n0 $n2

$ns duplex-link $n0 $n4 1000Mb 24ms DropTail
$ns duplex-link $n0 $n5 1000Mb 24ms DropTail


#node n0 will be made as the CMTS of the network
#node n1 will be made as the test CM  of the network
#node n2 will be made as the test node on the wired network
#neither n0 or n1 are in the CMnodes array
lappend CMnodelist $n0
lappend CMnodelist $n1


for {set i 0} {$i < $numberCMs} {incr i} {
   set CMnodes($i) [$ns node]
   lappend CMnodelist $CMnodes($i)
}

#puts "Create these nodes: $CMnodelist"

#assumes the first in the list is the CMTS
#set p [$ns make-lan $CMnodelist 10Mb 2ms LL Queue/DropTail Mac/DocsisCM ] 
# <upstream-channel params = "updatarate ticks maxburst upstream-overhead prop-delay">
#<downstream-channel params = ""downdatarate downstre#am overhead prop-delay">

set curDir [pwd]
set CmBgUs "$curDir/CMBGUS.dat"
set CmBgDs "$curDir/CMBGDS.dat"
set BgProp "$curDir/BG.dat"
set ChProp "$curDir/channels.dat"
set p [$ns make-docsislan $CMnodelist $defaultDSChannel $defaultUSChannel 2ms LL $CmBgDs $CmBgUs $BgProp $ChProp $TURN_ON_TCL_DEBUG]


# configure-cm node priority rng_msg_interval status_msg_freq debug on/off cmbackoffscale
$p configure-cm $n1 1 1.0 200.0 $TURN_ON_n1_DEBUG $CMBKOFF 
for {set i 0} {$i < $numberCMs} {incr i} {
#   set cmID [expr $i + 2]
#   puts "configure-cm:  config cm with this id: $cmID
   $p configure-cm $CMnodes($i) 1 1.0 200.0 $TURN_ON_DEBUG $CMBKOFF 
}

#configure-upflows node "schedtype dst-node pkt-type phs-type  Bonding Group number
#  frag-enable concat-enable concat_threshhold piggyback-enable 
#  grant-size grant-interval queue size debug on/off US rate control on ,  US rate"
$p configure-defaultup $n1  "$BESCHED $n2 $PT_WILDCARD $PHS_NO_SUPRESSION $BG5 $FRAG_FLAG $CONCAT_FLAG $CONCAT_THRESHOLD $PIGGYBACKING_FLAG 0 0 $UPSTREAM_SID_QUEUE_SIZE $TURN_ON_n1_DEBUG $US_RATE_CONTROL $UPSTREAM_SERVICE_RATE $USSCHEDQType $USSCHEDQSize $USSCHEDQDiscipline $FlowPriority0 $FlowQuantum2 $FlowWeight1 $USMinRate $USMinLatency"     

#optionally create a UGS flow (note: we disable concatenation) 
#  Value:0 no UDP monitor
#  Value:1 CBR traffic source to a UGS service flow
#  Value:2 CBR traffic source to the default BE service flow
#  Value:3 CBR traffic source to a VBR service flow
#   set UDP_MONITOR_TYPE  2
if {$UDP_MONITOR_TYPE  == 1} {
  puts "config SINGLE UGS flow "
#Also, we don't support a tolerated grant jitter or a tolerated poll jitter
  $p configure-upflows $n1  "$UGSSCHED $n2 $PT_CBR $PHS_NO_SUPRESSION $BG5 $FRAG_FLAG 0 $CONCAT_THRESHOLD $PIGGYBACKING_FLAG 250 0.02 $UPSTREAM_SID_QUEUE_SIZE $TURN_ON_n1_DEBUG $US_RATE_CONTROL $UPSTREAM_SERVICE_RATE $USSCHEDQType $USSCHEDQSize $USSCHEDQDiscipline $FlowPriority0 $FlowQuantum2 $FlowWeight1 $USMinRate $USMinLatency"     
}

#optionally create a VBR flow 
if {$UDP_MONITOR_TYPE  == 3 } {
  puts "config SINGLE VBR flow "
# in "":  "sched_type,src,dst,pkt_type, Physical profile,Frag bit, piggy bit
#  gsize, ginterval,qsize,debug bit,USRate bit, US rate    
#For RTPS, we the ginterval but not the gsize 
#Also, we don't support a tolerated grant jitter or a tolerated poll jitter
  $p configure-upflows $n1  "$RTPSSCHED $n2 $PT_CBR $PHS_NO_SUPRESSION $BG5 $FRAG_FLAG 0 $CONCAT_THRESHOLD $PIGGYBACKING_FLAG 0 0.05 $UPSTREAM_SID_QUEUE_SIZE $TURN_ON_n1_DEBUG $US_RATE_CONTROL $UPSTREAM_SERVICE_RATE $USSCHEDQType $USSCHEDQSize $USSCHEDQDiscipline $FlowPriority0 $FlowQuantum2 $FlowWeight1 $USMinRate $USMinLatency"     
}
for {set i 0} {$i < $numberCMs} {incr i} {
   $p configure-defaultup $CMnodes($i)  "$BESCHED $n2 $PT_WILDCARD $PHS_NO_SUPRESSION $BG5 $FRAG_FLAG $CONCAT_FLAG $CONCAT_THRESHOLD $PIGGYBACKING_FLAG 0 0 $UPSTREAM_SID_QUEUE_SIZE $TURN_ON_DEBUG $US_RATE_CONTROL $UPSTREAM_SERVICE_RATE $USSCHEDQType $USSCHEDQSize $USSCHEDQDiscipline $FlowPriority0 $FlowQuantum2 $FlowWeight1$USMinRate $USMinLatency"     
}

#configure-defaultdown node "dst-node pkt-type phs-type rate-control on/off rate tokenqlen bucket"
$p configure-defaultdown $n1  "$n2 $PT_WILDCARD $PHS_NO_SUPRESSION $BG3 $RATE_CONTROL $DOWNSTREAM_SERVICE_RATE $DOWNSTREAM_SID_QUEUE_SIZE $BUCKET_LENGTH $DSSCHEDQType $DSSCHEDQSize $DSSCHEDQDiscipline $FlowPriority0 $FlowQuantum2 $FlowWeight1 $DSMinRate $DSMinLatency $ReseqFlow $ReseqWindow $ReseqTimeout"     
#CMnodes(0) is the CMTS, so start with 1
#for {set i 0} {$i < $numberCMs} {incr i} {
for {set i 0} {$i < $numberCMs} {incr i} {

  if {$i  == 0} {
   puts "config flow #$i for BG # $BG1"
   $p configure-defaultdown $CMnodes($i)  "$n2 $PT_WILDCARD $PHS_NO_SUPRESSION $BG1 $RATE_CONTROL $DOWNSTREAM_SERVICE_RATE $DOWNSTREAM_SID_QUEUE_SIZE $BUCKET_LENGTH $DSSCHEDQType $DSSCHEDQSize $DSSCHEDQDiscipline $FlowPriority0 $FlowQuantum2 $FlowWeight1 $DSMinRate $DSMinLatency $ReseqFlow $ReseqWindow $ReseqTimeout"     
  } elseif {$i  == 7} {
   puts "config flow #$i for BG # $BG1"
   $p configure-defaultdown $CMnodes($i)  "$n2 $PT_WILDCARD $PHS_NO_SUPRESSION $BG1 $RATE_CONTROL $DOWNSTREAM_SERVICE_RATE $DOWNSTREAM_SID_QUEUE_SIZE $BUCKET_LENGTH $DSSCHEDQType $DSSCHEDQSize $DSSCHEDQDiscipline $FlowPriority0 $FlowQuantum2 $FlowWeight1 $DSMinRate $DSMinLatency $ReseqFlow $ReseqWindow $ReseqTimeout"     
  } else {
   puts "config flow #$i for BG # $BG1 "
   $p configure-defaultdown $CMnodes($i)  "$n2 $PT_WILDCARD $PHS_NO_SUPRESSION $BG1 $RATE_CONTROL $DOWNSTREAM_SERVICE_RATE $DOWNSTREAM_SID_QUEUE_SIZE $BUCKET_LENGTH $DSSCHEDQType $DSSCHEDQSize $DSSCHEDQDiscipline $FlowPriority0 $FlowQuantum2 $FlowWeight1 $DSMinRate $DSMinLatency $ReseqFlow $ReseqWindow $ReseqTimeout"     
  }

}


#configure-mgmtparams cmts-node sync-msg-interval rng-msg-interval ucd-msg-interval 
$p configure-mgmtparams $n0 2.0 1.0 3.0 

#Key params:   num CS's, contention bkoff-end
#configure-mapparams cmts-node time-covered map-interval num-SM permap
#num-contention-slots permap short-grant-limit long-grant-limit bkoff-start bkoff-end proportion Map_lookahead
$p configure-mapparams $n0 $MAP_TIME $MAP_FREQUENCY $NUMBER_MANAGEMENT_SLOTS $NUMBER_CONTENTION_SLOTS 55 66 $BKOFF_START $BKOFF_END 0.5  $MAP_LOOKAHEAD     

$p configure-DSScheduler $n0  $DSSchedMode $DefaultSchedQSize $DefaultSchedQType
$p configure-USScheduler $n0  $USSchedMode $DefaultSchedQSize $DefaultSchedQType


#trace the BW
#Note: this calls dumpBWCM which also calls dumpUGSJitter creating
#entries in UGSJitterCM.out
TraceCMBW $p $ns $n1 2.0 CM-BW-CM1.out


$ns at $printtime "dumpCMStats $p $ns $n1 CMstats.out"


#loop through each CM
#  and configure stats stuff

for {set i 0} {$i < $numberCMs} {incr i} {
   set outfilename "CM-BW-CM[expr $i + 2].out"
   TraceCMBW $p $ns $CMnodes($i) 1.0 $outfilename
   $ns at $printtime "dumpCMStats $p $ns $CMnodes($i) CMstats.out"
   if { $i == 0} {
     TraceDOCSISQueue $p $ns $CMnodes($i) .1  CM3QUEUE.out
   } 
}

#trace the downstream and upstream queues
#CMTS
TraceDOCSISQueue $p $ns $n0 .1 CMTS-DS-QUEUE.out 
#CM
TraceDOCSISQueue $p $ns $n1 .1  CM1QUEUE.out


# start the simulation(starts the registration phase)
$p startsim

#trace CMTS throughput
#Note: this calls dumpBWCMTS which also calls dumpUGSJitter creating
#entries in UGSJitterCMTS.out
TraceCMTSBW $p $ns $n0 1.0 CMTS-BW.out


set numberFLOWS $numberCMs
for {set i 0} {$i < $numberFLOWS} {incr i} {

  set CXN [expr $i + 10]
  set flowStartTime [expr 0.001 + [uniform 0 2]]


if { $ALL_UDP == 1 } {
if { $TRAFFIC_DIRECTION == 0 } {
puts "ALL UDP UPSTREAM"  
# value 0: CBR   value 1 EXP
  if {$UDP_TRAFFIC == 0} {
    if {$i  == 1} {
       BuildUDPCBRCxs $ns $CMnodes($i) $n2  1 $PACKETSIZE $INTERVAL $CXN $flowStartTime $printtime 
#       BuildUDPCBRCxs $ns $CMnodes($i) $n2  1 $PACKETSIZE [expr $INTERVAL * 4]  $CXN $flowStartTime $printtime 
     } else {
       BuildUDPCBRCxs $ns $CMnodes($i) $n2  1 $PACKETSIZE $INTERVAL $CXN $flowStartTime $printtime 
     }
  }
  if {$UDP_TRAFFIC == 1} {
    BuildUDPExpCxs $ns $CMnodes($i) $n2  1 $PACKETSIZE $BURSTTIME $IDLETIME $BURSTRATE $CXN $flowStartTime $printtime 
  }
  if {$UDP_TRAFFIC == 2} {
    BuildUDPParetoCxs $ns $CMnodes($i) $n2  1 $PACKETSIZE  $BURSTTIME $IDLETIME $BURSTRATE $SHAPE $CXN $flowStartTime $printtime 
  }
} else {
puts "ALL UDP DOWNSTREAM"
  if {$UDP_TRAFFIC == 0} {
    if {$i  == 1} {
#      BuildUDPCBRCxs $ns $n2 $CMnodes($i)  1 $PACKETSIZE [expr $INTERVAL * 4]  $CXN $flowStartTime $printtime 
      BuildUDPCBRCxs $ns $n2 $CMnodes($i)  1 $PACKETSIZE $INTERVAL $CXN $flowStartTime $printtime 
    } else {
      BuildUDPCBRCxs $ns $n2 $CMnodes($i)  1 $PACKETSIZE $INTERVAL $CXN $flowStartTime $printtime 
    }
  }
  if {$UDP_TRAFFIC == 1} {
    BuildUDPExpCxs $ns $n2 $CMnodes($i)  1 $PACKETSIZE $BURSTTIME $IDLETIME $BURSTRATE $CXN $flowStartTime $printtime 
  }
  if {$UDP_TRAFFIC == 2} {
    BuildUDPParetoCxs $ns $n2 $CMnodes($i) 1 $PACKETSIZE $BURSTTIME $IDLETIME $BURSTRATE $SHAPE $CXN $flowStartTime $printtime 
  }
}

} else {

  set newFileOut "TCPthru$CXN.out"
if {$TURN_ON_TCL_DEBUG == 1} {
  puts "Build a TCP Cx with out file  TCPthru$CXN.out"
}
# Use this for upstream traffic
if { $TRAFFIC_DIRECTION == 0 } {
  BuildTCPCx $ns $CMnodes($i) $n2  1 $PACKETSIZE $BURSTTIME $IDLETIME $BURSTRATE $CXN  $flowStartTime $printtime $newFileOut  $WINDOW  $SHAPE  $protID
} else {
# Use this for downstream traffic
  BuildTCPCx $ns $n2 $CMnodes($i)  1 $PACKETSIZE $BURSTTIME $IDLETIME $BURSTRATE $CXN $flowStartTime $printtime $newFileOut  $WINDOW  $SHAPE  $protID
}
}
}


if {$doPINGMONITOR > 0} {
#setup the ping process at n1.

#Create two ping agents and attach them to the nodes n1 (first CM) and n2 (the sink)
#p0 will be the client,  p1 will be the ping server
set p0 [new Agent/Ping]
set p1 [new Agent/Ping]

if { $TRAFFIC_DIRECTION == 0 } {
$ns attach-agent $n1 $p0
$ns attach-agent $n2 $p1
} else {
$ns attach-agent $n2 $p0
$ns attach-agent $n1 $p1
}

#Connect the two agents
$ns connect $p0 $p1

#can call startPingProcess which does a ping every interval
#or have the recv schedule doPing ....
startPingProcess $ns $p0 1.1

#to see ping summary
$ns at $printtime "doPingStats"

}

#setup the CBR flow that will use the UGS/VBR service
if {$UDP_MONITOR_TYPE  > 0} {

  set udp0 [new Agent/UDP]
  set udpsinkexp0 [new Agent/UDPSink]


  if { $TRAFFIC_DIRECTION == 0 } {
	#Upstream
    $ns attach-agent $n2 $udpsinkexp0
    $ns attach-agent $n1 $udp0
  } else {
    #Downstream
    $ns attach-agent $n1 $udpsinkexp0
    $ns attach-agent $n2 $udp0
  }

  set cbr0 [new Application/Traffic/CBR]
#  $cbr0 set packetSize_ 210
#  $cbr0 set interval_ 0.02
  $cbr0 set packetSize_  210
  $cbr0 set interval_ 0.01
#mode_ 1 will create CBR.send - see ./tools/cbr_traffic.cc
  $cbr0 set mode_ 1
  $cbr0 attach-agent $udp0

  $ns connect $udp0 $udpsinkexp0
  $udpsinkexp0 set fid_  1
#Will create CBR.recv
  $udpsinkexp0 set SinkId_  1
  set newUDPFileOut "UDPsink.out"
  exec rm -f $newUDPFileOut

  UDPTraceThroughput $ns $udpsinkexp0  .5 $newUDPFileOut
  $ns at .53210 "$cbr0 start"
}

#trace the DS and US utilization as observed by the CMTS
#TraceDOCSISUtilization $p $ns $n0 1.0 CMTS-DS-util.out $RAW_DOWNSPEED $RAW_UPSPEED

$ns at $stoptime "dumpCMTSStats $p $ns $n0 CMTSstats.out"


$ns at $stoptime "finish"


proc finish {} {
global ns 
#    dumpCMTSStats $p $ns $n0 CMTSstats.out $RAW_DOWNSPEED $RAW_UPSPEED
    $ns flush-trace
    exit 0
}

#Start the simulator
$ns run


exit 0


