Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- --- Program : Computercraft Library (name MarquitoLuaUtils)
- --- Author : LightKnight51
- --- last modification : 18/04/2023
- --- Variables
- -- Log level
- LogLevel = {INFO = "INFO", ERROR = "ERROR"}
- -- Device type
- DeviceType = {COMPUTER = "COMPUTER", COMMAND_COMPUTER="COMMAND_COMPUTER", PAD = "PAD", TURTLE="TURTLE"}
- -- Turtle type
- TurtleType = {NONE="NONE", MINING="MINING", MELEE = "MELEE", FARM="FARM", FELLING="FELLING", CRAFT="CRAFT", DIG="DIG", NOISY="NOISY"}
- -- Turtle type
- --- Functions
- ---- Main functions
- -- Program exist in this machine ?
- function ProgramExistInLocal(programName)
- return fs.exists(programName)
- end
- -- Download program
- function DownloadProgram(pastebinCode, programName)
- if ProgramExistInLocal(programName) then
- fs.delete(programName)
- end
- shell.run("pastebin get " .. pastebinCode .. " " .. programName)
- end
- -- Get content code of a program
- function GetProgramContent(programName)
- local programContent = ""
- io.input(programName)
- programContent = io.read("a")
- return programContent
- end
- -- Check if a list of values contain a specific value
- function ListContain(searchValue, ...)
- local arg = { ... }
- local contain = false
- local argValue = arg[1]
- local i = 0
- while argValue ~= nil do
- if argValue == searchValue then
- contain = true
- break
- end
- i = i + 1
- argValue = arg[i]
- end
- return contain
- end
- -- Return true if a variable is an array
- function IsAnArray(varToCheck)
- return varToCheck ~= nil and type(varToCheck) == "table"
- end
- -- Split a string into an array, with a specific separator
- function Split(stringToSplit, separator)
- if separator == nil then
- separator = "%s"
- end
- local splitArray = {}
- for str in string.gmatch(stringToSplit, "([^" .. separator .. "]+)") do
- table.insert(splitArray, str)
- end
- return splitArray
- end
- -- Get size of the array
- function GetArraySize(array)
- local arraySize = 0
- if IsAnArray(array) then
- arraySize = table.getn(array)
- end
- return arraySize
- end
- -- Replace a string inside the first string, by another (or empty string if stringToReplace equal nil)
- function Replace(stringWhereReplace, stringToRemove, stringToReplace)
- if stringToReplace == nil then
- stringToReplace = ""
- end
- --return stringWhereReplace:gsub("%"..stringToRemove, stringToReplace)
- local newString = string.gsub(stringWhereReplace, stringToRemove, stringToReplace)
- return newString
- end
- -- Print and log an error occur with specific item
- function Error(itemID)
- print("Error occurs with : " .. itemID)
- Log("Error occurs with : " .. itemID, LogLevel.ERROR)
- end
- -- Get the device type
- function GetDeviceType()
- local deviceType
- if turtle then
- deviceType = DeviceType.TURTLE
- elseif pocket then
- deviceType = DeviceType.PAD
- elseif commands then
- deviceType = DeviceType.COMMAND_COMPUTER
- else
- deviceType = DeviceType.COMPUTER
- end
- return deviceType
- end
- ---- File functions
- -- Read a file
- function ReadFileContent(filePath, fileName, fileExtension)
- local fileContent = ""
- if fs.exists(filePath .. "/" .. fileName .. "." .. "txt") then
- fileContent = fs.open(filePath .. "/" .. fileName .. "." .. "txt", "r").readAll()
- end
- return fileContent
- end
- -- Move a file
- function MoveFile(currentFilePath, currentFileName, fileExtension, newFilePath, newFileName)
- local fileContent = fs.open(currentFilePath .. "/" .. currentFileName .. "." .. fileExtension, "r").readAll()
- fs.delete(currentFilePath .. "/" .. currentFileName .. "." .. fileExtension)
- local newFile = fs.open(newFilePath .. "/" .. newFileName .. "." .. fileExtension, "w")
- newFile.write(fileContent)
- end
- -- Get or create a file with his file path
- function GetOrCreateFile(filePath, fileName, fileExtension)
- local file = fs.open(filePath .. "/" .. fileName .. "." .. fileExtension, "w")
- return file
- end
- ---- Logs functions
- -- Get or create a log file with his file path
- function GetOrCreateLogFile(filePath, fileName)
- local isNewLog = fs.exists(filePath .. "/" .. fileName .. "." .. "txt") == false
- local logFile = fs.open(filePath .. "/" .. fileName .. "." .. "txt", "a")
- if isNewLog then
- logFile.writeLine("-- LogFile --")
- logFile.writeLine("-- MarquitoLuaUtils --")
- logFile.writeLine("-- Log created on : ".. GetLocalDateTime())
- logFile.writeLine("-- Computer ID : ".. os.getComputerID())
- logFile.writeLine("----------------------")
- end
- logFile.close()
- end
- -- Log data, with a log level (info or error)
- function Log(logLevel, dataToLog)
- GetOrCreateLogFile("/logs", "logFile")
- -- Open the file
- local logFile = fs.open("/logs" .. "/" .. "logFile" .. "." .. "txt", "a")
- logFile.writeLine("[" .. GetLocalDateTime() .. "] - " .. logLevel .. " " .. dataToLog)
- logFile.close()
- end
- -- End the current file log
- function EndLog()
- local endDateTime = GetLocalDateTime()
- local logFile = fs.open("/logs" .. "/" .. "logFile" .. "." .. "txt", "a")
- logFile.writeLine("[" .. endDateTime .. "] - End of this log file")
- logFile.close()
- local logName = os.getComputerID() .. "_" .. string.gsub(endDateTime, " ", "_")
- MoveFile("/logs", "logFile", "txt", "/logs/archive", logName)
- end
- ---- Configuration functions
- -- Get or create a log file with his file path
- function GetOrCreateConfFile()
- local isNewConf = fs.exists("/conf" .. "/" .. "confFile" .. "." .. "conf") == false
- if isNewConf then
- local confFile = fs.open("/conf" .. "/" .. "confFile" .. "." .. "conf", "w")
- confFile.writeLine("-- ConfFile --")
- confFile.writeLine("-- MarquitoLuaUtils --")
- confFile.writeLine("-- Conf created on : ".. GetLocalDateTime())
- confFile.writeLine("-- Computer ID : ".. os.getComputerID())
- confFile.writeLine("----------------------")
- confFile.close()
- end
- end
- -- Get conf value
- function GetConfValue(confName)
- local confValue = ""
- GetOrCreateConfFile()
- -- Conf file
- local confFile = fs.open("/conf" .. "/" .. "confFile" .. "." .. "conf", "r")
- local confFileLines = Split(confFile.readAll(),"\n")
- confFile.close()
- if GetArraySize(confFileLines) > 0 then
- for lineNumber, line in ipairs(confFileLines) do
- if lineNumber > 5 then
- if string.find(line, confName .. "=") then
- confValue = Replace(line, confName .. "=", "")
- break
- end
- end
- end
- end
- return confValue
- end
- -- Set conf value
- function SetConfValue(confName, confValue)
- GetOrCreateConfFile()
- -- Conf file
- local confFile = fs.open("/conf" .. "/" .. "confFile" .. "." .. "conf", "r")
- local confFileLines = Split(confFile.readAll(),"\n")
- confFile.close()
- confFile = fs.open("/conf" .. "/" .. "confFile" .. "." .. "conf", "w")
- local confFound = false
- if GetArraySize(confFileLines) > 0 then
- for _, line in ipairs(confFileLines) do
- if string.find(line, confName .. "=") then
- confFile.writeLine(confName .. "=" .. confValue)
- confFound = true
- else
- confFile.writeLine(line)
- end
- end
- if not confFound then
- confFile.writeLine(confName .. "=" .. tostring(confValue))
- end
- confFile.close()
- end
- end
- ---- Date time functions
- -- Get the current local date time (not minecraft but system)
- function GetLocalDateTime()
- return os.date('%d-%m-%Y %H:%M:%S', GetCurrentLocalTimeStamp() / 1000)
- end
- -- Get the current local date (not minecraft but system)
- function GetLocalDate()
- return os.date('%d-%m-%Y', GetCurrentLocalTimeStamp() / 1000)
- end
- -- Get the current local time (not minecraft but system)
- function GetLocalTime()
- return os.date('%H:%M:%S', GetCurrentLocalTimeStamp() / 1000)
- end
- -- Get the current local timestamp (not minecraft but system)
- function GetCurrentLocalTimeStamp()
- return os.epoch("utc")
- end
- ---- Http functions
- -- Get the request for this url
- function GetDownloadRequest(url, isBinary)
- return http.get(url, nil, isBinary)
- end
- -- Get and save the file from the request
- function SaveFileFromRequest(request, filePath, fileName, fileExtension)
- local file = fs.open(filePath .. "/" .. fileName .. "." .. fileExtension, "w")
- -- Write data to the file
- file.write(request.readAll())
- -- Close the request
- request.close()
- -- Close the file
- file.close()
- end
- -- Download a file from http url, and return the file path if exist
- function DownloadAndGetFile(url, filePath, fileName, fileExtension)
- local request = GetDownloadRequest(url, false)
- SaveFileFromRequest(request, filePath, fileName, fileExtension)
- return filePath .. "/" .. fileName .. "." .. fileExtension
- end
- -- Download a finary file from http url, and return the file path if exist
- function DownloadAndGetBinaryFile(url, filePath, fileName, fileExtension)
- local request = GetDownloadRequest(url, true)
- SaveFileFromRequest(request, filePath, fileName, fileExtension)
- return filePath .. "/" .. fileName .. "." .. fileExtension
- end
- -- Download an audio file from http url, and return the file path if exist
- function DownloadAndGetAudioFile(url, fileName)
- return DownloadAndGetBinaryFile(url, "/data/audio", fileName, "dfpwm")
- end
- ---- Rednet functions
- -- Find rednet wireless modem
- function FindWirelessRednetModem()
- local wirelessRednetModem = peripheral.find("modem")
- if wirelessRednetModem ~= nil then
- if wirelessRednetModem.isWireless() ~= true then
- wirelessRednetModem = nil
- end
- end
- return wirelessRednetModem
- end
- -- Find the side of the wireless modem
- function GetWirelessRednetModemSide()
- local modemSide = nil
- local wirelessRednetModem = FindWirelessRednetModem()
- if wirelessRednetModem ~= nil then
- modemSide = peripheral.getName(wirelessRednetModem)
- end
- return modemSide
- end
- -- Open rednet if wireless modem has found, and return if operation is successfull
- function OpenWirelessRednetModem()
- local modemIsReady = false
- local wirelessRednetModem = FindWirelessRednetModem()
- if wirelessRednetModem ~= nil then
- local wirelessModemSide = peripheral.getName(wirelessRednetModem)
- if rednet.isOpen(wirelessModemSide) ~= true then
- rednet.open(wirelessModemSide)
- end
- modemIsReady = true
- end
- return modemIsReady
- end
- -- Open rednet if wireless modem has found
- function CloseWirelessRednetModem()
- local wirelessRednetModem = FindWirelessRednetModem()
- if wirelessRednetModem ~= nil then
- local wirelessModemSide = peripheral.getName(wirelessRednetModem)
- if rednet.isOpen(wirelessModemSide) then
- rednet.close(wirelessModemSide)
- end
- end
- end
- -- Receive data from rednet
- function ReceiveDataFromRednet(optionalProtocol)
- local dataResult = nil
- local senderId, message, protocol = rednet.receive()
- if optionalProtocol == nil or protocol == optionalProtocol then
- dataResult = message
- end
- return dataResult
- end
- -- Send data to one device with rednet
- function SendDataWithRednetForOneDevice(deviceId, data, optionalProtocol)
- if optionalProtocol == nil then
- rednet.send(tonumber(deviceId), data)
- else
- rednet.send(tonumber(deviceId), data, optionalProtocol)
- end
- end
- -- Send data to multiples devices with rednet
- function SendDataWithRednetForMultiplesDevices(deviceIds, data, optionalProtocol)
- if IsAnArray(deviceIds) then
- for _, deviceId in ipairs(deviceIds) do
- SendDataWithRednetForOneDevice(deviceId, data, optionalProtocol)
- end
- end
- end
- -- Send data to multiples devices with rednet
- function BroadcastDataWithRednet(data, optionalProtocol)
- if optionalProtocol == nil then
- rednet.broadcast(data)
- else
- rednet.broadcast(data, optionalProtocol)
- end
- end
- ---- Turtle functions
- -- Get the turtle type
- function GetTurtleType()
- local turtleType = TurtleType.NONE
- -- The current slot
- local currentSlot = turtle.getSelectedSlot()
- -- The empty slot for find current equipment
- local emptySlot = FindEmptySlot()
- if emptySlot then
- turtle.select(emptySlot)
- local modemSide = GetWirelessRednetModemSide()
- local item = ""
- if modemSide then
- if modemSide == "left" then
- -- Check right side
- turtle.equipRight()
- item = turtle.getItemDetail(emptySlot)
- turtle.equipRight()
- turtleType = CheckTurtleType(item)
- else
- -- Check left side
- turtle.equipLeft()
- item = turtle.getItemDetail(emptySlot)
- turtle.equipLeft()
- turtleType = CheckTurtleType(item)
- end
- else
- -- Check right side
- turtle.equipRight()
- item = turtle.getItemDetail(emptySlot)
- turtle.equipRight()
- if item then
- turtleType = CheckTurtleType(item)
- else
- -- Check left side
- turtle.equipLeft()
- item = turtle.getItemDetail(emptySlot)
- turtle.equipLeft()
- turtleType = CheckTurtleType(item)
- end
- end
- else
- Log(LogLevel.ERROR, "No empty slot was found for detect turtle type")
- -- TODO
- end
- turtle.select(currentSlot)
- return turtleType
- end
- -- Check the turtle type
- function CheckTurtleType(item)
- local turtleType = TurtleType.NONE
- if item then
- if string.find(item.name, "_sword") then
- turtleType = TurtleType.MELEE
- elseif string.find(item.name, "_pickaxe") then
- turtleType = TurtleType.MINING
- elseif string.find(item.name, "_axe") then
- turtleType = TurtleType.FELLING
- elseif string.find(item.name, "_hoe") then
- turtleType = TurtleType.FARM
- elseif string.find(item.name, "_shovel") then
- turtleType = TurtleType.DIG
- elseif string.find(item.name, "speaker") then
- turtleType = TurtleType.NOISY
- elseif string.find(item.name, "crafting_table") then
- turtleType = TurtleType.CRAFT
- end
- end
- return turtleType
- end
- -- Return the first empty slot, nil if no slot found
- function FindEmptySlot()
- local emptySlot = nil
- for i = 1, 16 do
- local data = turtle.getItemDetail(i)
- if data == nil then
- emptySlot = i
- break
- end
- end
- return emptySlot
- end
- -- Select an item inside the turtle with is minecraft ID
- function SelectionID(itemID)
- return FindIDContains(itemID, true)
- end
- -- Find an item inside the turtle with is minecraft ID, or a part of a minecraft ID
- function FindIDContains(searchItemID, isEntireId, logError)
- j = nil
- for i = 1, 16 do
- data = turtle.getItemDetail(i)
- if data then
- bCondition = false
- if isEntireId then
- bCondition = (data.name == searchItemID)
- else
- bCondition = (string.find(data.name,searchItemID) ~= nil)
- end
- if bCondition then
- j = i
- exit = false
- break
- elseif i == 16 and data.name ~= searchItemID then
- if logError == true or logError == nil then
- Error(searchItemID)
- end
- j = nil
- end
- end
- end
- return j
- end
- -- Refuel the turtle
- function Refuel()
- while not exit do
- fuel = turtle.getFuelLevel()
- if fuel < 25 then
- blazeRodID = SelectionID("minecraft:blaze_rod")
- coalID = SelectionID("minecraft:coal")
- fuelID = nil
- if blazeRodID ~= nil then
- fuelID = blazeRodID
- elseif coalID ~= nil then
- fuelID = coalID
- end
- if fuelID ~= nil then
- turtle.select(fuelID)
- turtle.refuel(1)
- else
- Error("fuelError")
- os.shutdown()
- end
- end
- sleep(0.5)
- end
- end
- -- Detect if we have a block on a specific side, and return the bloc name, or a boolean is just detection
- -- (true if the turtle don't need to dig this block)
- function BlockDetection(position, justDetection)
- success, detectionBlock = nil
- block_name = ""
- if position == "right" then
- turtle.turnRight()
- success, detectionBlock = turtle.inspect()
- turtle.turnLeft()
- if success then
- block_name = RecognizeLiquidAirBlocks(detectionBlock, justDetection)
- end
- elseif position == "left" then
- turtle.turnLeft()
- turtle.turnRight()
- success, detectionBlock = turtle.inspect()
- if success then
- block_name = RecognizeLiquidAirBlocks(detectionBlock, justDetection)
- end
- elseif position == "bottom" then
- turtle.turnRight()
- turtle.turnRight()
- success, detectionBlock = turtle.inspect()
- turtle.turnRight()
- turtle.turnRight()
- if success then
- block_name = RecognizeLiquidAirBlocks(detectionBlock, justDetection)
- end
- elseif position == "front" then
- success, detectionBlock = turtle.inspect()
- if success then
- block_name = RecognizeLiquidAirBlocks(detectionBlock, justDetection)
- end
- elseif position == "down" then
- success, detectionBlock = turtle.inspectDown()
- if success then
- block_name = RecognizeLiquidAirBlocks(detectionBlock, justDetection)
- end
- elseif position == "up" then
- success, detectionBlock = turtle.inspectUp()
- if success then
- block_name = RecognizeLiquidAirBlocks(detectionBlock, justDetection)
- end
- else
- block_name = "minecraft:?"
- end
- return block_name
- end
- -- Recognize a block and return his name
- -- (true if this block is air, water or lava)
- function RecognizeLiquidAirBlocks(detectionBlock, justDetection)
- block_name = ""
- if justDetection == true then
- if detectionBlock.name == "minecraft:air" or detectionBlock.name == "minecraft:flowing_water" or detectionBlock.name == "minecraft:water" or detectionBlock.name == "minecraft:flowing_lava" or detectionBlock.name == "minecraft:lava" then
- block_name = true
- else
- block_name = false
- end
- elseif justDetection == false then
- block_name = detectionBlock.name
- end
- return block_name
- end
- -- Drop every items down or up
- function DropAllItems(dropDown, excludingItems)
- -- Array size
- local arraySize = table.getn(excludingItems)
- -- Loop each items inside the turtle
- for m = 1, 16 do
- local canBeDrop = true
- -- Get item name in current slot
- local turtleCurrentItemName = nil
- if turtle.getItemDetail(m) ~= nil then
- turtleCurrentItemName = turtle.getItemDetail(m).name
- end
- if turtleCurrentItemName ~= nil and arraySize ~= nil and arraySize > 0 then
- for s = 1, arraySize do
- local current
- if string.find(turtleCurrentItemName, excludingItems[s]) then
- canBeDrop = false
- break
- end
- end
- end
- if canBeDrop then
- turtle.select(m)
- if dropDown then
- turtle.dropDown()
- else
- turtle.dropUp()
- end
- end
- end
- local direction = "up"
- if dropDown then
- direction = "down"
- end
- Log(LogLevel.INFO, "Items has moved " .. direction)
- end
- -- Drop every items down or up in chest
- function DropAllItemsInChest(dropDown, excludingItems)
- local direction = "up"
- if dropDown then
- direction = "down"
- end
- if string.find(BlockDetection(direction, false), "chest") then
- DropAllItems(dropDown, excludingItems)
- Log(LogLevel.INFO, "Items has moved to chest " .. direction)
- else
- Log(LogLevel.ERROR, "Chest not found ")
- end
- end
- ---- Monitor screen functions
- -- Find screen
- function FindScreen()
- return peripheral.find("monitor")
- end
- -- Get screen size
- function GetScreenSize(screen)
- return screen.getSize()
- end
- -- Get center of screen
- function GetCenterOfScreen(screen)
- local screenWidth, screenHeight = GetScreenSize(screen)
- return screenWidth / 2, screenHeight / 2
- end
- ---- Speaker functions
- -- Find speaker
- function FindSpeaker()
- return peripheral.find("speaker")
- end
- -- Launch new music
- function LaunchMusic(dfpwmLib, speaker, musicFileName)
- local dfpwm = require("cc.audio.dfpwm")
- local decoder = dfpwm.make_decoder()
- for chunk in io.lines("/data/audio/" .. musicFileName .. ".dfpwm", 16 * 1024) do
- local buffer = decoder(chunk)
- while not speaker.playAudio(buffer) do
- os.pullEvent("speaker_audio_empty")
- end
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement