aboutsummaryrefslogtreecommitdiff
path: root/advtrains_interlocking/models
diff options
context:
space:
mode:
Diffstat (limited to 'advtrains_interlocking/models')
0 files changed, 0 insertions, 0 deletions
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
-- environment_far.lua
--[[
local STOP_TIME = 40
local STOPCMD="B0WO"
local DEPCMD="A1OCD1SM"
local RDEPCMD="RA1OCD1SM"
local DYNAMIC_THR = 10
local DYNAMIC_EN = false
]]

if S.trains == nil then S.trains = {} end
if S.d == nil then S.d = {} end
if S.datetime == nil then S.datetime = "" end
if S.stop_display == nil then S.stop_display = false end
if S.show_farpass_only == nil then S.show_farpass_only = false end
if S.timetake == nil then S.timetake = {} end
if S.ttp == nil then S.ttp = {} end
if S.ttt == nil then S.ttt = {} end

F.ttp={
  FAR_E = {
    outside_text = "[FAR] Fareast End\nvia Halfway, Bayonne, Fucking",
    inside_line_desc = "FAR to Fareast End",
    stn_display = "FAR Fareast End",
  },
  FAR_W = {
    outside_text = "[FAR] Salt Factory\nvia Fucking,  Bayonne, Halfway",
    inside_line_desc = "FAR to Salt Factory",
    stn_display = "FAR Salt Factory",
  },
}

F.print = function (str) if F.debug then print("".. (str or "nil") ) end end
F.isempty = function (s) return s == nil or s == "" end
F.get_rc_safe = function() return get_rc() or "" end
F.get_line_safe = function() return get_line() or "" end
F.get_train_length_safe = function() return train_length() or 0 end

F.avg = function(t)
  local sum = 0
  local count = 0
  for k,v in pairs(t) do
    if type(v) == "number" then
      sum = sum + v
      count = count + 1
    end
  end
  return (sum / count)
end

if event.init then
  F.debug = true
  F.printAllTrainsInfo = true
  F.max_displays = 15
  F.STOP_TIME = 40
  F.STOPCMD="B0WO"
  F.DEPCMD="A1OCD1SM"
  F.RDEPCMD="RA1OCD1SM"
  F.DYNAMIC_THR = 10
  F.DYNAMIC_EN = false
  F.print("Initialized")
end

--[[
  EXAMPLE: F.has_rc("LILSHUNTER", F.get_rc_safe() )
  Merged F.has_rc and F.does_train_have_rc
  F.does_train_have_rc is deprecated
]]
F.has_rc = function(query,rc_list) -- query = string, single entry
  for word in rc_list:gmatch("[^%s]+") do
    if word == query then return true end
  end
  return false
end

F.send_route = function(passive_name, route, show_print)
  local message = ""
  local return_value = false
  if can_set_route(passive_name, route) then
    set_route(passive_name, route)
    message = passive_name .. " has been set to " .. route
    return_value = true
  else
    message = route .. " cannot be set for " .. passive_name .. ". Try another."
    return_value = false
  end
  if show_print == true then F.print(message) end
  return return_value
end

--[[
F.save_train(POS(26201,24,1417), "east")
]]

F.save_train = function(pos, direction)
  if event.train then
    if not atc_id then return end
    if S.trains then
      if F.isempty(pos) then
        pos_string = ""
      else
        pos_string = pos["x"] .. "," .. pos["y"] .. "," .. pos["z"]
      end
      if F.has_rc("FAREAST", F.get_rc_safe()) then
        if direction == nil or direction == "" then
          S.trains[atc_id] = { ["id"] = atc_id, ["rc"] = F.get_rc_safe(), ["ln"] = F.get_line_safe(), ["cars_count"] = F.get_train_length_safe(), ["pos"] = pos_string , ["direction"] = nil }
        else
          S.trains[atc_id] = { ["id"] = atc_id, ["rc"] = F.get_rc_safe(), ["ln"] = F.get_line_safe(), ["cars_count"] = F.get_train_length_safe(), ["pos"] = pos_string , ["direction"] = direction }
        end
        -- F.print("Train ID: " .. S.trains[atc_id]["id"] .. " at " .. S.trains[atc_id]["pos"])
        -- remote_track = POS(30919,13,1812)
        -- interrupt_pos(remote_track, "display")
      end
    end
  end
  return
end

F.get_real_split_count = function(train_length_count, split_count)
  if split_count then
    if split_count == "all" then
      return 2
    else
      F.print("train_length_count (" .. train_length_count .. ") - split_count (" .. split_count .. ")")
      train_length_count = train_length_count + 1
      split_count = train_length_count - split_count
      return split_count
    end
  else
    return nil
  end
end

F.delete_train_info = function(train_id)
  if S.trains[train_id] then
    S.trains[train_id] = nil
    F.print("Deleted train id: " .. train_id)
  end
end

F.clear_main_depot_displays = function() for i = 1, F.max_displays, 1 do digiline_send("train_display" .. i, " ") end end
F.send_update_displays = function() for i = 1, F.max_displays, 1 do digiline_send("train_display" .. i, "Updating...") end end

F.date_formatted = function()
  date = os.date("%Y-%m-%d")
  return date
end

F.time_formatted = function()
  time = os.date("*t")
  return string.format("%02d:%02d:%02d %s", time.hour, time.min, time.sec, (time.isdst and "CEST") or "CET")
end

F.list_trains = function(print_info)
  if S.trains then
    number_of_displays = F.max_displays
    F.clear_main_depot_displays()
    number_of_displays = number_of_displays + 1
    count_keys = 0
    direction_display = ""
    trains_table = {}
    for k in pairs(S.trains) do
      table.insert(trains_table, k)
      count_keys = count_keys + 1
    end
    table.sort(trains_table)
    -- x = number_of_displays - count_keys
    x = 1

    for _, k in ipairs(trains_table) do
      if S.trains[k] then
        v = S.trains[k]
        if S.show_farpass_only == true and not F.has_rc("FARPASS", v["rc"]) then
          F.delete_train_info(v["id"])
        end
        if F.has_rc("LILSHUNTER", v["rc"]) or F.has_rc("LIL", v["rc"]) then
          F.delete_train_info(v["id"])
        else
          if v["ln"] == nil or v["ln"] == "" then
            line_number = ""
          else
            line_number = "| LN: [" .. v["ln"] .. "]"
          end
          if v["pos"] == nil or v["pos"] == "" then
            pos_string = ""
          else
            pos_string = "| POS: [" .. v["pos"] .. "]"
          end
          if v["rc"] == nil or v["rc"] == "" then
            rc_display = ""
          else
            rc_list = v["rc"]
            rc_list_cleansed = ""
            rc_list_unknown = ""
            rc_list_table = {}
            if F.has_rc("ERSTAZI", rc_list) and F.has_rc("FREIGHT", rc_list) then
              rc_list_cleansed = "ERSTAZI FREIGHT |"
            else
              rc_list_cleansed = "NO E,F |"
            end
            for rc in rc_list:gmatch("[^%s]+") do
              if rc == "ERSTAZI" or rc == "ERSTAZIDEPOT" or rc == "FREIGHT" then
                -- leaving for future use
                do_nothing = true
              else
                rc_list_unknown = rc_list_unknown .. " " .. rc
              end
            end
            rc_display = ""
            if not F.isempty(rc_list_unknown) then
              rc_display = rc_display .. "| RC:" .. rc_list_unknown
            end
          end
          if v["direction"] == nil or v["direction"] == "" then
            direction_display = " D: ??"
          else
            direction_display = " D: " .. v["direction"]
          end
          if v["cars_count"] == nil or v["cars_count"] == "" then
            cars_count_display = " L: 0"
          else
            cars_count = tonumber(v["cars_count"])
            cars_count_display = " L: " .. cars_count
          end
          message = " ID: " .. v["id"] .. cars_count_display .. direction_display .. rc_display ..  line_number .. pos_string
          if x > 0 then digiline_send("train_display" .. x, message) end
          if print_info then
            F.print(x .. ": " .. message)
          end
          x = x + 1
        end
      end
    end

    -- S.datetime = os.date("%Y-%m-%d %H:%M:%S")
    -- digiline_send("time", "  \n    " .. S.datetime)

  else
    if print_info then
      F.print("no trains saved in S.trains")
    end
  end
end

F.slow_train_down = function(id)
  result = atc_send_to_train(id, "B1")
  if result == false then
    F.print("Train ID " .. id .. " does not exist")
  else
    F.print("Train ID " .. id .. " is slowed down to B1")
  end
end

-- init code for FAR 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

  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

  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

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

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>,
    }
}
]]

--[[
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 = "12;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
})


F.ttp_begin({
 stn = "Salt Factory", -- station name
 tt = "FAR_E", -- timetable ID
 depint = "12;00", --departure slot interval
 depoff = "00;00", --departure slot offset
 doorside = "L",
 reverse = true,
 only_lines = {['FAR'] = true},
 force_tt_reset = false,
 pos = POS(1755,8,1570),
 direction = "west",
})
]]
-- 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
    if p.pos and p.direction then
      F.save_train(p.pos, p.direction)
    end
    -- train arrived, planning departure
    atc_send(F.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(F.RDEPCMD)
    else
      atc_send(F.DEPCMD)
    end
  end
end
--[[
Generic stop on timetable. Any train that has a TT instance registered
stops here, waits F.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 + F.STOP_TIME if not provided
 no_disable_ars = nil,
   -- if true, does not disable ARS on approach (used for example at INTERCAL)
 pos = POS(1,1,1),
 direction = "east",
})

F.ttp_stop({
  stn = "The Cube",
  doorside = "R",
  pos = POS(1,1,1),
  direction = "east",
})

]]
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(F.DEPCMD)
--  end


  if event.train then
    if p.pos and p.direction then
      F.save_train(p.pos, p.direction)
    end
    -- train arrived, planning departure
    atc_send(F.STOPCMD..p.doorside)
    local time_now = rwt.now()
    -- update our location and determine desired and planned departure
    local next_dep_time = rwt.add(time_now, F.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] + F.STOP_TIME)
      -- dyn travel time
      if F.DYNAMIC_EN then
        local ttpd = rwt.diff(next_dep_time, trn.desired_dep)
        if ttpd > F.DYNAMIC_THR then
          local new_trav = rwt.diff(trn.initial_dep, time_now) + F.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 + F.STOP_TIME)
        end
      end
    end

    if trn.desired_dep then
      -- if we had a source for desired departure, update planned daparture time
      if rwt.to_secs(next_dep_time) < rwt.to_secs(trn.desired_dep) then
        -- don't depart before the planned departure time
        next_dep_time = trn.desired_dep
      end
      atc_set_text_inside(p.stn.."\nArr: "
        ..rwt.to_string(time_now, true).." Plan: "
        ..rwt.to_string(trn.desired_dep, true).." Dep: "
        ..rwt.to_string(next_dep_time, true))

      local delay = rwt.diff(trn.desired_dep, next_dep_time)
      trn.last_delay = delay
    else
      atc_set_text_inside(p.stn.."\nAa "
        ..rwt.to_string(time_now, true).." Dd ? Da"
        ..rwt.to_string(next_dep_time, true))
    end

    if tti.recording_train == atc_id then
      -- we are recording. save travel time
      tti.travel_times[p.stn] = rwt.diff(trn.initial_dep or 0, time_now)
      print(atc_id,"for",tt,"at",p.stn,"-> travel time",rwt.to_string(tti.travel_times[p.stn]))
      tti.station_order[#tti.station_order+1] = p.stn
      atc_set_text_inside(p.stn.."\nRec TT "
        ..rwt.to_string(tti.travel_times[p.stn], true).." Da"
        ..rwt.to_string(next_dep_time, true))
    end

    trn.planned_dep = next_dep_time
    schedule(next_dep_time, "departure")
  end
  if event.schedule then
    -- departure. save actual departure time in tt
    trn.actual_dep = rwt.now()
    local delay = rwt.diff(trn.desired_dep or trn.actual_dep, trn.actual_dep)
    atc_set_text_inside(F.ttp[tt].inside_line_desc
      .."\nDelay: "..rwt.to_string(delay, true))
    S.ttt[atc_id].last_delay = delay
    atc_send(F.DEPCMD)
    if p.end_of_tt and p.end_of_tt[tt] then
      -- end of timetable. Deregister train
      if tti.recording_train == atc_id then
        tti.recording_train = nil
      end
      S.ttt[atc_id] = nil
    end
  end
end


function F.ttp_info_times(tt, starttime)
  local ttf = F.ttp[tt]
  local tti = S.ttp[tt]
  local p = {}
  if tti.recording_train then
    p[#p+1] = ("recording "..tti.recording_train)
  end
  p[#p+1] = ("Di "..rwt.to_string(starttime, false).." "..tti.station_order[1])
  for i=2,#tti.station_order do
    local ap = rwt.add(starttime, tti.travel_times[tti.station_order[i]])
    p[#p+1] = ("Ap "..rwt.to_string(ap, true)..
      " Dp "..rwt.to_string(rwt.add(ap, F.STOP_TIME), false)..
      " "..tti.station_order[i])
  end
  return p
end

function F.ttp_info_trains(tt, starttime)
  local ttf = F.ttp[tt]
  local tti = S.ttp[tt]
  local p = {}
  for tid,trn in pairs(S.ttt) do
    if trn.timetable==tt then
      if trn.actual_dep then
        p[#p+1] = ("Trn "..tid..
          " after "..trn.location..
          " Dd "..rwt.to_string(trn.desired_dep or 0, false)..
          " Da "..rwt.to_string(trn.actual_dep, false)..
          " Delay "..rwt.to_string(trn.last_delay or "59;59"))
      else
        p[#p+1] = ("Trn "..tid..
          " at "..trn.location..
          " Dd "..rwt.to_string(trn.desired_dep or 0, false)..
          " Delay "..rwt.to_string(trn.last_delay or "59;59"))
      end
    end
  end
  return p
end

--[[F.ttp_station_display({
 lines = {"CFE_S", "NX_S", "E1_S"},
 departure = {},
 station = "The Cube",
 title = "The Cube (Track 2)",
 interval = 30,
 display1 = "d1",
 display2 = "d2",
 display3 = "d3",
 show_trainid = false,
}]]
function F.ttp_station_display(p)
  -- { dep, text }
  local next_trains = {}
  local function is_past_station(tstn, stnorder)
    for _,s in ipairs(stnorder) do
      if s==p.station then return true end
      if s==tstn then return false end
    end
    return true
  end

  local function add_train(deptime, line, train, tid)
    local tent = {dep = deptime, text =
       rwt.to_string(deptime,true)
       .." "..(p.show_trainid and tid.." " or "")
       ..F.ttp[line].stn_display
       .." +"..train.last_delay}
    for i,ntrn in ipairs(next_trains) do
      if rwt.diff(ntrn.dep, deptime)<0 then
        table.insert(next_trains, i, tent)
        return
      end
    end
    table.insert(next_trains, tent)
  end

  for _,line in ipairs(p.lines) do
    local fttp = F.ttp[line]
    local sttp = S.ttp[line]
    -- find all trains on this line
    for id, train in pairs(S.ttt) do
      if train.timetable == line then
        if train.location == p.station and not train.actual_dep then
          -- the train is currently standing at this station
          add_train(train.planned_dep, line, train, id)
        elseif not is_past_station(train.location, sttp.station_order) then
          -- train is still approaching, calculate arrival time
          local trav_dep = rwt.add(train.initial_dep, (sttp.travel_times[p.station] or 0) + F.STOP_TIME)
          local act_dep = rwt.add(trav_dep, train.last_delay)
          if p.departure and p.departure[line] then
            local plan_dep = rwt.add(train.initial_dep, p.departure[line])
            if rwt.to_secs(act_dep) < rwt.to_secs(plan_dep) then
              act_dep = plan_dep
            end
          end
          add_train(act_dep, line, train, id)
        end
      end
    end
  end

  -- make output
  local i
  local text1 = p.title .. " * "..rwt.to_string(rwt.now(), true).." * "
  for i=1,3 do
    if next_trains[i] then
      text1 = text1 .. "\n".. next_trains[i].text
    end
  end

  digiline_send(p.display1, text1)
  if p.display2 then
    local text2 = ""
    for i=4,7 do
      if next_trains[i] then
        text2 = text2 .. next_trains[i].text .. "\n"
      end
    end
    digiline_send(p.display2, text2)
  end

  if p.display3 then
    local text3 = ""
    for i=8,11 do
      if next_trains[i] then
        text3 = text3 .. next_trains[i].text .. "\n"
      end
    end
    digiline_send(p.display3, text3)
  end
  --if not p.notimer then
  --  schedule_in(p.interval or 30,"foo")
  --end
end