Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- ___ _ _ ___ _ _
- -- | _ \ __ _ (_) | | / __| | |_ __ _ | |_ _ _ ___
- -- | / / _` | | | | | \__ \ | _| / _` | | _| | +| | (_-<
- -- |_|_\ \__,_| _|_|_ _|_|_ |___/ _\__| \__,_| _\__| \_,_| /__/_
- -- _|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|
- -- "`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'
- --
- -- RailStatus : IG Server
- --
- -- La seconde génération de RailStatus (http://pastebin.com/js3pN87r), un programme permettant
- -- de connaître en temps réel et en jeu (in game) le statut des aiguillages d'un réseau ferroviaire en
- -- utilisant RailCraft, ComputerCraft et RedPower
- --
- -- Utilisation :
- -- 1. Dans un ordinateur, importer ce programme depuis Pastebin :
- -- pastebin get KAy0Kqfw railstatusigs
- -- 2. Lancer le programme :
- -- railstatusig [ID de la carte] [URL de base d'appel vers l'API]
- -- Exemple : railstatusigs 1 http://exemple.fr/api
- --
- -- Client : http://pastebin.com/KsJ9gukb
- -- Dépôt Github : https://github.com/EaSyCompanyFr/RailStatus
- term.clear()
- term.setCursorPos(1,1)
- print("RailStatus : IG Server is starting...")
- -- Arguments passés au programme
- args = {...}
- if table.getn(args) < 2 then
- print(" One or more parameters are missing")
- return
- end
- -- --------------------------------------------------------
- -- Constantes
- -- Tableau de correspondance nom de couleur > identifiant décimal
- COLORS_ARRAY = {}
- COLORS_ARRAY["white"] = colors.white
- COLORS_ARRAY["orange"] = colors.orange
- COLORS_ARRAY["magenta"] = colors.magenta
- COLORS_ARRAY["lightBlue"] = colors.lightBlue
- COLORS_ARRAY["yellow"] = colors.yellow
- COLORS_ARRAY["lime"] = colors.lime
- COLORS_ARRAY["pink"] = colors.pink
- COLORS_ARRAY["gray"] = colors.gray
- COLORS_ARRAY["lightGray"] = colors.lightGray
- COLORS_ARRAY["cyan"] = colors.cyan
- COLORS_ARRAY["purple"] = colors.purple
- COLORS_ARRAY["blue"] = colors.blue
- COLORS_ARRAY["brown"] = colors.brown
- COLORS_ARRAY["green"] = colors.green
- COLORS_ARRAY["red"] = colors.red
- COLORS_ARRAY["black"] = colors.black
- -- Récupération du premier type de périphérique détecté
- function getFirstPeripheralSide(peripheral_type)
- for k,side in pairs(redstone.getSides()) do
- if peripheral.isPresent(side) and peripheral.getType(side) == peripheral_type then
- return side
- end
- end
- return false
- end
- -- De quel côté est branché le moniteur avancé pour afficher la carte
- MONITOR_SIDE = getFirstPeripheralSide("monitor")
- if not MONITOR_SIDE then
- print(" Advanced monitor not detected on this computer")
- return
- end
- MONITOR = peripheral.wrap(MONITOR_SIDE)
- -- Si le moniteur n'est pas de type avancé
- if not MONITOR.isColor() then
- print(" And advanced monitor is required")
- return
- end
- print(" Advanced monitor side : "..MONITOR_SIDE)
- -- Modem
- MODEM_SIDE = getFirstPeripheralSide("modem")
- if not MODEM_SIDE then
- print(" Modem not detected on this computer")
- return
- end
- print(" Modem side : "..MODEM_SIDE)
- -- ID de la carte à utiliser
- MAP_ID = args[1]
- print(" Map ID : "..MAP_ID)
- -- URL de base d'appel vers l'API
- API_ENDPOINT = args[2]
- print(" Endpoint : "..API_ENDPOINT)
- print(" Computer ID : "..os.getComputerID())
- print("")
- print("To stop RailStatus : IG, hold CTRL+T for some seconds.")
- -- --------------------------------------------------------
- -- Fonctions et librairies
- -- JSON4Lua: JSON encoding / decoding support for the Lua language.
- -- json Module.
- -- Author: Craig Mason-Jones
- -- Homepage: http://json.luaforge.net/
- -- Version: 0.9.40
- -- This module is released under the MIT License (MIT).
- local base = _G
- local decode_scanArray
- local decode_scanComment
- local decode_scanConstant
- local decode_scanNumber
- local decode_scanObject
- local decode_scanString
- local decode_scanWhitespace
- local encodeString
- local isArray
- local isEncodable
- local function encode (v)
- -- Handle nil values
- if v==nil then
- return "null"
- end
- local vtype = base.type(v)
- -- Handle strings
- if vtype=='string' then
- return '"' .. encodeString(v) .. '"' -- Need to handle encoding in string
- end
- -- Handle booleans
- if vtype=='number' or vtype=='boolean' then
- return base.tostring(v)
- end
- -- Handle tables
- if vtype=='table' then
- local rval = {}
- -- Consider arrays separately
- local bArray, maxCount = isArray(v)
- if bArray then
- for i = 1,maxCount do
- table.insert(rval, encode(v[i]))
- end
- else -- An object, not an array
- for i,j in base.pairs(v) do
- if isEncodable(i) and isEncodable(j) then
- table.insert(rval, '"' .. encodeString(i) .. '":' .. encode(j))
- end
- end
- end
- if bArray then
- return '[' .. table.concat(rval,',') ..']'
- else
- return '{' .. table.concat(rval,',') .. '}'
- end
- end
- -- Handle null values
- if vtype=='function' and v==null then
- return 'null'
- end
- base.assert(false,'encode attempt to encode unsupported type ' .. vtype .. ':' .. base.tostring(v))
- end
- local function decode(s, startPos)
- startPos = startPos and startPos or 1
- startPos = decode_scanWhitespace(s,startPos)
- base.assert(startPos<=string.len(s), 'Unterminated JSON encoded object found at position in [' .. s .. ']')
- local curChar = string.sub(s,startPos,startPos)
- -- Object
- if curChar=='{' then
- return decode_scanObject(s,startPos)
- end
- -- Array
- if curChar=='[' then
- return decode_scanArray(s,startPos)
- end
- -- Number
- if string.find("+-0123456789.e", curChar, 1, true) then
- return decode_scanNumber(s,startPos)
- end
- -- String
- if curChar==[["]] or curChar==[[']] then
- return decode_scanString(s,startPos)
- end
- if string.sub(s,startPos,startPos+1)=='/*' then
- return decode(s, decode_scanComment(s,startPos))
- end
- -- Otherwise, it must be a constant
- return decode_scanConstant(s,startPos)
- end
- local function null()
- return null -- so json.null() will also return null ;-)
- end
- function decode_scanArray(s,startPos)
- local array = {} -- The return value
- local stringLen = string.len(s)
- base.assert(string.sub(s,startPos,startPos)=='[','decode_scanArray called but array does not start at position ' .. startPos .. ' in string:\n'..s )
- startPos = startPos + 1
- -- Infinite loop for array elements
- repeat
- startPos = decode_scanWhitespace(s,startPos)
- base.assert(startPos<=stringLen,'JSON String ended unexpectedly scanning array.')
- local curChar = string.sub(s,startPos,startPos)
- if (curChar==']') then
- return array, startPos+1
- end
- if (curChar==',') then
- startPos = decode_scanWhitespace(s,startPos+1)
- end
- base.assert(startPos<=stringLen, 'JSON String ended unexpectedly scanning array.')
- object, startPos = decode(s,startPos)
- table.insert(array,object)
- until false
- end
- function decode_scanComment(s, startPos)
- base.assert( string.sub(s,startPos,startPos+1)=='/*', "decode_scanComment called but comment does not start at position " .. startPos)
- local endPos = string.find(s,'*/',startPos+2)
- base.assert(endPos~=nil, "Unterminated comment in string at " .. startPos)
- return endPos+2
- end
- function decode_scanConstant(s, startPos)
- local consts = { ["true"] = true, ["false"] = false, ["null"] = nil }
- local constNames = {"true","false","null"}
- for i,k in base.pairs(constNames) do
- --print ("[" .. string.sub(s,startPos, startPos + string.len(k) -1) .."]", k)
- if string.sub(s,startPos, startPos + string.len(k) -1 )==k then
- return consts[k], startPos + string.len(k)
- end
- end
- base.assert(nil, 'Failed to scan constant from string ' .. s .. ' at starting position ' .. startPos)
- end
- function decode_scanNumber(s,startPos)
- local endPos = startPos+1
- local stringLen = string.len(s)
- local acceptableChars = "+-0123456789.e"
- while (string.find(acceptableChars, string.sub(s,endPos,endPos), 1, true)
- and endPos<=stringLen
- ) do
- endPos = endPos + 1
- end
- local stringValue = 'return ' .. string.sub(s,startPos, endPos-1)
- local stringEval = base.loadstring(stringValue)
- base.assert(stringEval, 'Failed to scan number [ ' .. stringValue .. '] in JSON string at position ' .. startPos .. ' : ' .. endPos)
- return stringEval(), endPos
- end
- function decode_scanObject(s,startPos)
- local object = {}
- local stringLen = string.len(s)
- local key, value
- base.assert(string.sub(s,startPos,startPos)=='{','decode_scanObject called but object does not start at position ' .. startPos .. ' in string:\n' .. s)
- startPos = startPos + 1
- repeat
- startPos = decode_scanWhitespace(s,startPos)
- base.assert(startPos<=stringLen, 'JSON string ended unexpectedly while scanning object.')
- local curChar = string.sub(s,startPos,startPos)
- if (curChar=='}') then
- return object,startPos+1
- end
- if (curChar==',') then
- startPos = decode_scanWhitespace(s,startPos+1)
- end
- base.assert(startPos<=stringLen, 'JSON string ended unexpectedly scanning object.')
- -- Scan the key
- key, startPos = decode(s,startPos)
- base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key)
- startPos = decode_scanWhitespace(s,startPos)
- base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key)
- base.assert(string.sub(s,startPos,startPos)==':','JSON object key-value assignment mal-formed at ' .. startPos)
- startPos = decode_scanWhitespace(s,startPos+1)
- base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key)
- value, startPos = decode(s,startPos)
- object[key]=value
- until false -- infinite loop while key-value pairs are found
- end
- function decode_scanString(s,startPos)
- base.assert(startPos, 'decode_scanString(..) called without start position')
- local startChar = string.sub(s,startPos,startPos)
- base.assert(startChar==[[']] or startChar==[["]],'decode_scanString called for a non-string')
- local escaped = false
- local endPos = startPos + 1
- local bEnded = false
- local stringLen = string.len(s)
- repeat
- local curChar = string.sub(s,endPos,endPos)
- -- Character escaping is only used to escape the string delimiters
- if not escaped then
- if curChar==[[\]] then
- escaped = true
- else
- bEnded = curChar==startChar
- end
- else
- -- If we're escaped, we accept the current character come what may
- escaped = false
- end
- endPos = endPos + 1
- base.assert(endPos <= stringLen+1, "String decoding failed: unterminated string at position " .. endPos)
- until bEnded
- local stringValue = 'return ' .. string.sub(s, startPos, endPos-1)
- local stringEval = base.loadstring(stringValue)
- base.assert(stringEval, 'Failed to load string [ ' .. stringValue .. '] in JSON4Lua.decode_scanString at position ' .. startPos .. ' : ' .. endPos)
- return stringEval(), endPos
- end
- function decode_scanWhitespace(s,startPos)
- local whitespace=" \n\r\t"
- local stringLen = string.len(s)
- while ( string.find(whitespace, string.sub(s,startPos,startPos), 1, true) and startPos <= stringLen) do
- startPos = startPos + 1
- end
- return startPos
- end
- function encodeString(s)
- s = string.gsub(s,'\\','\\\\')
- s = string.gsub(s,'"','\\"')
- s = string.gsub(s,'\n','\\n')
- s = string.gsub(s,'\t','\\t')
- return s
- end
- function isArray(t)
- -- Next we count all the elements, ensuring that any non-indexed elements are not-encodable
- -- (with the possible exception of 'n')
- local maxIndex = 0
- for k,v in base.pairs(t) do
- if (base.type(k)=='number' and math.floor(k)==k and 1<=k) then -- k,v is an indexed pair
- if (not isEncodable(v)) then return false end -- All array elements must be encodable
- maxIndex = math.max(maxIndex,k)
- else
- if (k=='n') then
- if v ~= table.getn(t) then return false end -- False if n does not hold the number of elements
- else -- Else of (k=='n')
- if isEncodable(v) then return false end
- end -- End of (k~='n')
- end -- End of k,v not an indexed pair
- end -- End of loop across all pairs
- return true, maxIndex
- end
- function isEncodable(o)
- local t = base.type(o)
- return (t=='string' or t=='boolean' or t=='number' or t=='nil' or t=='table') or (t=='function' and o==null)
- end
- -- Convertit un table en chaîne de caractères paramètres POST
- function tableToURIString(t)
- local ret = ""
- local i = 1
- for key,value in pairs(t) do
- ret = ret..textutils.urlEncode(key).."="..textutils.urlEncode(value)
- if table.getn(t) ~= i then
- ret = ret.."&"
- end
- i = i + 1
- end
- return ret
- end
- -- Explose une chaîne de caractères selon un séparateur
- function split(pString, pPattern)
- local Table = {}
- local fpat = "(.-)" .. pPattern
- local last_end = 1
- local s, e, cap = pString:find(fpat, 1)
- while s do
- if s ~= 1 or cap ~= "" then
- table.insert(Table,cap)
- end
- last_end = e+1
- s, e, cap = pString:find(fpat, last_end)
- end
- if last_end <= #pString then
- cap = pString:sub(last_end)
- table.insert(Table, cap)
- end
- return Table
- end
- -- --------------------------------------------------------
- -- Démarrage du programme
- rednet.open(MODEM_SIDE)
- MONITOR.setTextScale(0.5);
- -- Récupération de la carte
- raw = http.get(API_ENDPOINT.."/"..MAP_ID)
- if raw == nil then
- print("Unable to get the map data")
- return
- end
- map_data = decode(raw.readAll())
- term.redirect(MONITOR)
- term.clear()
- -- Tableau contenant la liste des positions des aiguillages en fonction de l'identifiant de l'ordi et de la couleur de l'aiguillage
- SWITCH_LIST = {}
- -- Tableau contenant la liste des aiguillages en fonction de leur position
- SWITCH_LIST_POS = {}
- -- Affichage de la carte du réseau ferroviaire
- for iy = 1, map_data["map_height"], 1 do
- for ix = 1, map_data["map_width"], 1 do
- local block = map_data["map_data"][iy..""][ix..""]
- if block["type"] == "switch" then
- color = colors.red
- if SWITCH_LIST[block["computer-id"]] == nil then
- SWITCH_LIST[block["computer-id"]] = {}
- end
- if SWITCH_LIST[block["computer-id"]][block["switch-color"]] == nil then
- SWITCH_LIST[block["computer-id"]][block["switch-color"]] = {}
- end
- SWITCH_LIST[block["computer-id"]][block["switch-color"]]["x"] = ix;
- SWITCH_LIST[block["computer-id"]][block["switch-color"]]["y"] = iy;
- if SWITCH_LIST_POS[iy..""] == nil then
- SWITCH_LIST_POS[iy..""] = {}
- end
- if SWITCH_LIST_POS[iy..""][ix..""] == nil then
- SWITCH_LIST_POS[iy..""][ix..""] = {}
- end
- SWITCH_LIST_POS[iy..""][ix..""]["computer-id"] = block["computer-id"];
- SWITCH_LIST_POS[iy..""][ix..""]["switch-color"] = block["switch-color"];
- elseif block["type"] == "rail" or block["type"] == "rail-bottom" or block["type"] == "rail-top" or block["type"] == "rail-left" or block["type"] == "rail-right" then
- color = colors.brown
- elseif block["type"] == "group" then
- color = colors.white
- else
- color = colors.black
- end
- paintutils.drawPixel(ix, iy, color)
- end
- end
- -- Mise à jour de la carte si aiguillage changé
- while true do
- local event, p1, p2, p3 = os.pullEvent()
- if event == 'rednet_message' then
- local senderId = p1
- local message = p2
- local distance = p3
- local message_splitted = split(message, "|")
- local computer_sender_id = message_splitted[1]..""
- local bundled_cable = textutils.unserialize(message_splitted[2])
- local real_computer_id = message_splitted[3]
- for key,value in pairs(bundled_cable) do
- if SWITCH_LIST[computer_sender_id][key] ~= nil then
- if value == 1 then
- color = colors.lime
- else
- color = colors.red
- end
- local x = SWITCH_LIST[computer_sender_id][key]["x"]..""
- local y = SWITCH_LIST[computer_sender_id][key]["y"]..""
- SWITCH_LIST_POS[y][x]["real_computer_id"] = real_computer_id
- paintutils.drawPixel(SWITCH_LIST[computer_sender_id][key]["x"], SWITCH_LIST[computer_sender_id][key]["y"], color)
- end
- end
- http.request(API_ENDPOINT, "ci="..computer_sender_id.."&"..tableToURIString(bundled_cable)) -- Mise à jour de la carte web
- elseif event == 'monitor_touch' then
- local side = p1
- local xPos = p2..""
- local yPos = p3..""
- if SWITCH_LIST_POS[yPos] ~= nil and SWITCH_LIST_POS[yPos][xPos] ~= nil then
- rednet.send(tonumber(SWITCH_LIST_POS[yPos][xPos]["real_computer_id"]), COLORS_ARRAY[SWITCH_LIST_POS[yPos][xPos]["switch-color"]], true)
- end
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement