ESP8266 Read/Write To Text File (Persistent Data Storage)

I created the below Lua functions so that I can easily read and write data to a text file (i.e. persistent data storage).


You need to create a text file called "ConfigureWebpage.txt" and upload it to the ESP8266 (I'm using a HUZZAH 8266). The below code then reads/writes to this text file on the ESP8266.

Here is the Lua code:

function ConvertFileToArray(NameOfTextFile)
local TempArrayOfValuesFromFile = {} --array of values from file
file.open(NameOfTextFile, 'r+')
    while true do
       local line = file.readline()
       if (line == nil) then break end
      table.insert (TempArrayOfValuesFromFile, line);
     end
     file.close()
     return TempArrayOfValuesFromFile
end

function SaveArrayToFile(NameOfArray,NameOfTextFile)
    file.open(NameOfTextFile, 'w')
    for arrayCount = 1, #NameOfArray do 
          print (NameOfArray[arrayCount])
          file.write(NameOfArray[arrayCount].."\n")
        end
    file.close()
end

function PrintArray(NameOfArray)
    for arrayCount = 1, #NameOfArray do
      print (NameOfArray[arrayCount])
    end
end

function PrintOutFileContents(NameOfTextFile)
    file.open(NameOfTextFile, "r")
    while true do
       local line = file.readline()
       if (line == nil) then break end
       print(line)
     end
     file.close()
end

print("** Read the file: **")
ArrayOfValuesFromFile=ConvertFileToArray("ConfigureWebpage.txt") --put textfile lines into Global array called ArrayOfValuesFromFile 
PrintArray(ArrayOfValuesFromFile) --output array
print("** Change array to the following: **")
ArrayOfValuesFromFile[1]="admin" -- change an array value
ArrayOfValuesFromFile[2]="1234" -- change an array value
ArrayOfValuesFromFile[3]="admin@somedomainname.com" -- change an array value
PrintArray(ArrayOfValuesFromFile) --print array with the change

tmr.delay(1000000) -- do nothing for 1 second

print("** Write over the original file with the new array values: **")
SaveArrayToFile(ArrayOfValuesFromFile,"ConfigureWebpage.txt")

tmr.delay(1000000) -- do nothing for 1 second

print("** Read back the file: **")
PrintOutFileContents("ConfigureWebpage.txt")

print("Username = "..ArrayOfValuesFromFile[1])
print("Password = "..ArrayOfValuesFromFile[2])
print("Email = "..ArrayOfValuesFromFile[3])

No comments:

Post a Comment