/src/

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
-- init code for LW timetable env

-- stop, scheduled departure every
-- d_int: Departure every n seconds (epoch modulo)
-- d_off: Departure time offset
function F.stop_sd(st_name, doors, departcommand, minstoptime, d_int, d_off)
	if event.train then
		local timenow = os.time()
		local timerdy = timenow + minstoptime
		local wait = d_int - ((timerdy-d_off) % d_int)
   local waitcorr = math.floor(wait*0.66)
		digiline_send("monitor", "Departure scheduled for: | "..os.date("%H:%M:%S", timenow+wait))
		atc_send("B0 W O"..doors.." D"..waitcorr.." OCD1"..departcommand)
	else
		local timenow = os.time()
		digiline_send("monitor", "Time: "..os.date("%H:%M:%S", timenow))
	end
end

function F.stop_sd_sched(st_name, doors, departcommand, minstoptime, d_int, d_off)
  depart = false
	if event.train then
   local time_now = rwt.now()
		local next_dep_time = rwt.next_rpt(rwt.add(time_now, minstoptime), d_int, d_off)
		digiline_send("monitor", "Departure scheduled for: | "..rwt.to_string(next_dep_time, true))
   atc_set_text_inside(st_name.."\nDeparture: "..rwt.to_string(next_dep_time, true))
		atc_send("B0 W O"..doors)
    schedule(next_dep_time, "depart")
  elseif event.schedule then
    atc_send("OCD1"..departcommand)
	  digiline_send("monitor", "Last Departure: | "..rwt.to_string(rwt.now(), true))
    atc_set_text_inside("")
    depart = true
	end
end

function F.timedisplay()
digiline_send("time", "Time: | "..rwt.to_string(rwt.now(),true).." | "..os.date("%H:%M:%S"))
schedule(rwt.next_rpt(rwt.now(),5,0), "")
end

-- Stat counter and timetaking utilities
-- Stat from subway
F.stat=function(line, init)
--statistics
-- init
if init then
reftrain = atc_id
a_tbt = 30
a_tbtmax = 30
a_rtt = 500
a_not = 0
c_not = 0
c_tbtmax = 0
time_lt = os.time()
time_rt=os.time()
end
if not a_tbtmax then a_tbtmax = 30 end
if not c_tbtmax then c_tbtmax = 0 end
--real code
if event.train then
local time = os.time()
c_not = c_not + 1
a_tbt = (a_tbt + (time - time_lt)) / 2
c_tbtmax = math.max(c_tbtmax, (time - time_lt))
if atc_id == reftrain then
  a_rtt = (a_rtt*0.2 + (time - time_rt)*0.8)
  a_not = c_not
  c_not = 0
  a_tbtmax = (a_tbtmax + c_tbtmax) / 2
  c_tbtmax = 0
end
  digiline_send("stats", "Stat: "..line..
    " NoT:"..a_not.."("..c_not..")"..
    " TbT:"..math.floor(a_tbt).."("..(time-time_lt)..")"..
    " Tmx:"..math.floor(a_tbtmax).."("..c_tbtmax..")"..
    " R:"..math.floor(a_rtt).."("..(time - time_rt)..")"
    )
time_lt = time
if atc_id == reftrain then
  time_rt = time
end
end
end

S.timetake = {}
function F.timetake_start(ttname)
  if not atc_id then return end
  local nouw = rwt.to_secs(rwt.now())
  if not S.timetake[ttname] then
    S.timetake[ttname] = {}
  end
  S.timetake[ttname][atc_id] = nouw
end

--L100
function F.timetake_end(ttname)
  if not atc_id then return end
  if not S.timetake[ttname] or not S.timetake[ttname][atc_id] then
    digiline_send("timetake", "No start time for "..atc_id)
    return
  end
  local first = S.timetake[ttname][atc_id]
  local nouw = rwt.to_secs(rwt.now())
  local tdiff = nouw - first
  local cavg = S.timetake[ttname].avg
  local cmax = S.timetake[ttname].max
  local cmin = S.timetake[ttname].min
  if cavg and cmax and cmin then
    S.timetake[ttname].avg = tdiff*0.1 + cavg*0.9
    S.timetake[ttname].min = math.min(tdiff, cmin)
    S.timetake[ttname].max = math.max(tdiff, cmax)
  else
    S.timetake[ttname].avg = tdiff
    S.timetake[ttname].min = tdiff
    S.timetake[ttname].max = tdiff    
  end
  digiline_send("timetake", ttname..
    " this:"..tdiff..
    " min:"..math.floor(S.timetake[ttname].min)..
    " avg:"..math.floor(S.timetake[ttname].avg)..
    " max:"..math.floor(S.timetake[ttname].max)
    )

end

--== Timetable prototype (TTP) ===
--[[ table structures:
F.ttp - static timetable data - see below
S.ttp[tt_name] = { - dynamic tt data
  recording_train = <id of the train that is recording travel times, or nil>
  travel_times = {
    <station name> = <time in seconds from initial departure at first station of the line to departure at this station>
  }
  station_order = { <station 1>, <station 2>...}
}
S.ttt[train_id] = { - trains
      timetable = <timetable ID that the train is currently using>,
      initial_dep = <departure at first station of the line>,
      location = <Station where the train was last seen>,
      desired_dep = <Departure time as in timetable>,
      planned_dep = <real departure time calculated as the train reaches station>,
      actual_dep = <actual departure time at last station. is nil while train is stopped>,
      last_delay = <last known delay of the train - calculated every departure>,
    }
}
]]

local STOP_TIME = 10
local STOPCMD="B0WO"
local DEPCMD="A1OCD1SM"
local RDEPCMD="RA1OCD1SM"
local DYNAMIC_THR = 15
local DYNAMIC_EN = true

if not S.ttp then S.ttp = {} end
if not S.ttt then S.ttt = {} end
F.ttp={
  CFE_N = {
    outside_text = "[CFE] Warmoneaye\nvia Ehlodex, Personhood West, Crystal Farms",
    inside_line_desc = "CFE to Warmoneaye",
    stn_display = "CFE Warmoneaye  ",
  },
  CFE_S = {
    outside_text = "[CFE] Origin\nvia Crystal Farms, Personhood West, Ehlodex",
    inside_line_desc = "CFE to Origin",
    stn_display = "CFE Origin North",
  },
  NRG_E = {
    outside_text = "[NRG] Azena Transirejo",
    inside_line_desc = "NRG to Azena Transirejo",
    stn_display = "NRG Azena Trans.",
  },
  NRG_W = {
    outside_text = "[NRG] New Roses Gardens",
    inside_line_desc = "NRG to New Roses Gardens",
    stn_display = "NRG N.Roses Gdns",
  },
  NX_S = {
    outside_text = "[NX] Trisiston\nvia Personhood West, Ehlodex, South Forest, Melinka",
    inside_line_desc = "NX to Trisiston",
    stn_display = "NX  Trisiston   ",
  },
  NX_N = {
    outside_text = "[NX] Stopsleyhood\nvia Ehlodex, Personhood West",
    inside_line_desc = "NX to Stopsleyhood",
    stn_display = "NX  Stopsleyhood",
  },
  E1_S = {
    outside_text = "[E1] Melinka\nvia The Cube, Ehlodex, Spawn Main, Mom Junction",
    inside_line_desc = "E1 to Melinka",
    stn_display = "E1  Melinka     ",
  },
  E1_N = {
    outside_text = "[E1] Personhood\nvia Mom Junction, Spawn Main, Ehlodex, The Cube",
    inside_line_desc = "E1 to Personhood",
    stn_display = "E1  Personhood  ",
  },
  S12_S = {
    outside_text = "[S12] Spawn Main\nvia Ehlodex, Schwarzschild St., Anju Crossing, Lesnoi",
    inside_line_desc = "S12 to Spawn Main",
    stn_display = "S12 Spawn Main  ",
  },
  S12_N = {
    outside_text = "[S12] Silver Coast\nvia Lesnoi, Anju Crossing, Schwarzschild St., Ehlodex",
    inside_line_desc = "S12 to Silver Coast",
    stn_display = "S12 Silver Coast",
  },
  E85_N = {
    outside_text = "[BAK] Namespace Mountains",
    inside_line_desc = "Baka Express (BAK) to Namespace Mountains",
    stn_display = "BAK Namespace M.",
  },
  E85_S = {
    outside_text = "[BAK] Morija North",
    inside_line_desc = "Baka Express (BAK) to Morija North",
    stn_display = "BAK Morija North",
  },
  E11_E = {
    outside_text = "[OEX] Oasis",
    inside_line_desc = "OEX to Oasis",
    stn_display = "OEX Oasis       ",
  },
  E11_W = {
    outside_text = "[OEX] Personhood",
    inside_line_desc = "OEX to Personhood",
    stn_display = "OEX Personhood  ",
  },
  E16_E = {
    outside_text = "[E16] Cat-o-Land (By The Way)\nC&C Rail",
    inside_line_desc = "E16 to Cat-o-Land (By The Way)",
    stn_display = "E16 Cat-o-Land  ",
  },
  E16_W = {
    outside_text = "[E16] Personhood\nC&C Rail",
    inside_line_desc = "E16 to Personhood",
    stn_display = "E16 Personhood  ",
  },
  KVE_N = {
    outside_text = "[KVE] Kangasvarkaa Express\n->Kangasvarkaan Rata",
    inside_line_desc = "KVE to Kangasvarkaa",
    stn_display = "KVE Kangasvarkaa",
  },
  KVE_S = {
    outside_text = "[KVE] Kangasvarkaa Express\n->Spawn Main Station",
    inside_line_desc = "KVE to Spawn Main Station",
    stn_display = "KVE Spawn Main  ",
  },
  DTLE1_N = {
    outside_text = "[DTLE1] Banana Place",
    inside_line_desc = "Dario Train Lines Express 1 (DTLE1) to Banana Place",
    stn_display = "DTLE1 Banana Pl.",
  },
  DTLE1_S = {
    outside_text = "[BAK] Morija North",
    inside_line_desc = "Baka Express (BAK) to Morija North",
    stn_display = "DTLE1 Morija N. ",
  },
}

--[[
Timetable entry point. The train finalizes its last timetable and
registers itself on the given timetable instance. It departs at the next time slot
(given by interval and offset).
F.ttp_begin({
 stn = "Warmoneaye", -- station name
 tt = "CFE_S", -- timetable ID
 depint = "05;00", --departure slot interval
 depoff = "00;00", --departure slot offset
 doorside = "L",
 reverse = true,
 only_lines = nil, --if given a table, only trains where only_lines[get_line()] is true are considered
 force_tt_reset = false, -- force reset of travel times for this timetable
})
]]
-- Make train depart at the next time slot, and save its start time
function F.ttp_begin(p)
  __approach_callback_mode = 1

  if not F.ttp[p.tt] then error("No TT instance "..p.tt) end
  if not atc_id then
    print(p.stn,"missing train!",event)
    return
  end
  if not atc_arrow then return end
  if p.only_lines and not p.only_lines[get_line()] then return end
  if not S.ttp[p.tt] then S.ttp[p.tt] = {} end
  local tti = S.ttp[p.tt]
--L150
  if event.approach and not event.has_entered then
    -- make the train stop
    atc_set_ars_disable(true)
    atc_set_lzb_tsr(2)
    atc_set_text_inside("Next stop: "..p.stn.."\nTerminal Station.\nThis train continues as "..F.ttp[p.tt].inside_line_desc)
  end
  if event.train then
    -- train arrived, planning departure
		atc_send(STOPCMD..p.doorside)

    local time_now = rwt.now()
    -- Train might have had another TT before, do the cleanup from ttp_end here.
    local trno = S.ttt[atc_id]
    if trno then
      local ttio = S.ttp[trno.timetable]
      if ttio.recording_train == atc_id then
        ttio.travel_times[p.stn] = rwt.diff(trno.initial_dep, time_now)
        ttio.station_order[#ttio.station_order+1] = p.stn
        print(atc_id,"for",p.tt,"at",p.stn,"-> travel time",rwt.to_string(ttio.travel_times[p.stn]),"-route end")
      end
    end
    local next_dep_time = rwt.next_rpt(rwt.add(time_now, 10), p.depint, p.depoff)
    schedule(next_dep_time, "departure")
    S.ttt[atc_id] = {
      timetable = p.tt,
      initial_dep = next_dep_time,
      location = p.stn,
      desired_dep = next_dep_time,
      planned_dep = next_dep_time,
      last_delay = 0,
    }
    -- if no travel times are available yet, set this train as recording
    if not tti.travel_times or p.force_tt_reset or tti.force_tt_reset then
      tti.travel_times = {}
      tti.station_order = {p.stn}
      tti.recording_train = atc_id
      tti.force_tt_reset = false
      print(atc_id,"starting TT recording for",p.tt)
    elseif tti.recording_train == atc_id then
      tti.recording_train = nil
    end
    atc_set_text_outside(F.ttp[p.tt].outside_text)
    atc_set_text_inside(p.stn.."\nArr: "
        ..rwt.to_string(time_now, true).." Dep: "
        ..rwt.to_string(next_dep_time, true))
  end
  if event.schedule then
    -- departure. save actual departure time in tt
    if S.ttt[atc_id] then -- failsafe: if entry is deleted externally somehow, train just departs and is not tracked by tt (makes resetting S.ttt possible)
     S.ttt[atc_id].actual_dep = rwt.now()
     local delay = rwt.diff(S.ttt[atc_id].desired_dep, S.ttt[atc_id].actual_dep)
     atc_set_text_inside(F.ttp[p.tt].inside_line_desc
       .."\nDelay: "..rwt.to_string(delay, true))
     S.ttt[atc_id].last_delay = delay
    end
    if p.reverse then
      atc_send(RDEPCMD)
    else
      atc_send(DEPCMD)
    end
  end
end
--[[
Generic stop on timetable. Any train that has a TT instance registered
stops here, waits STOP_TIME and continues. Behavior can be altered by options:
F.ttp_stop({
 stn = "Personhood West", -- station name
 doorside = "L",
 only_lines = nil, --if given a table, only trains where only_lines[get_line()] is true are considered
 end_of_tt = { TT_ID = true },
   -- if present and key is true for a TT identifier, this is the last station on this timetable. Trains will stop recording timetable and be deregistered.
 departure = { TT_ID = RWT relative to initial departure },
   -- If present, override desired departure time. Defaults to travel time + STOP_TIME if not provided
 no_disable_ars = nil,
   -- if true, does not disable ARS on approach (used for example at INTERCAL)
})
]]function F.ttp_stop(p)
  -- set my approach callback mode
  __approach_callback_mode = 1
  if not atc_id then
    print(p.stn,"missing train!",event)
    return
  end
  if not S.ttt[atc_id] then return end
  if p.only_lines and not p.only_lines[get_line()] then return end
  local trn = S.ttt[atc_id]
  local tt = trn.timetable
  if not F.ttp[tt] then
    S.ttt[atc_id] = nil
  end
  local tti = S.ttp[tt]
  if event.approach and not event.has_entered then
    -- make the train stop
    if not p.no_disable_ars then
     atc_set_ars_disable(true)
    end
    atc_set_lzb_tsr(2)
    atc_set_text_inside("Next stop: "..p.stn)
  end

--!-- disaster recovery --!--
--  if event.approach and event.has_entered then
--    print(atc_id,p.stn,"Disaster Recovery...")
--    atc_send(DEPCMD)
--  end


  if event.train then
    -- train arrived, planning departure
		atc_send(STOPCMD..p.doorside)
    local time_now = rwt.now()
    -- update our location and determine desired and planned departure
--L200
    local next_dep_time = rwt.add(time_now, STOP_TIME)
    trn.location = p.stn
    trn.desired_dep = nil
    trn.actual_dep = nil

    -- calculate desired departure nouw
    if p.departure and p.departure[tt] then
      trn.desired_dep = rwt.add(trn.initial_dep or 0, 
          p.departure[tt])      
    elseif tti.travel_times[p.stn] then
      trn.desired_dep = rwt.add(trn.initial_dep or 0, 
          tti.travel_times[p.stn] + STOP_TIME)
      -- dyn travel time
      if DYNAMIC_EN then
        local ttpd = rwt.diff(next_dep_time, trn.desired_dep)
        if ttpd > DYNAMIC_THR then
          local new_trav = rwt.diff(trn.initial_dep, time_now) + DYNAMIC_THR
          print(atc_id,tt,"arrived at",p.stn,ttpd,"s early, TT",tti.travel_times[p.stn],"->",new_trav)
          tti.travel_times[p.stn] = new_trav
          trn.desired_dep = rwt.add(trn.initial_dep or 0, 
              new_trav + STOP_TIME)
        end
      end
    end

    if trn.desired_dep then