Lua Scripting

Last update: May 2018

FlashAir supports the execution of programs written in Lua, which allows a lot of advanced features such as:

  • Uploading a file directly from FlashAir to a server.

  • Generating data files on FlashAir.

  • Dynamically generated HTML.

Lua scripting is available in Firmware Versions 3.00.00+.

About Lua

Lua is a powerful, fast, lightweight, embeddable scripting language.

Lua combines simple procedural syntax with powerful data description constructs based on associative arrays and extensible semantics. Lua is dynamically typed, runs by interpreting bytecode for a register-based virtual machine, and has automatic memory management with incremental garbage collection - making it ideal for configuration, scripting, and rapid prototyping.

 —  Lua: about

For more about the Lua language, see:

Available Libraries

The following library functions are available in FlashAir Lua scripting:

Limitations

The following functions in the standard library are not available because of the memory limitations:

Update Mathematical functions are now available on FlashAir W-04.
  • Coroutine Manipulation

  • Operating System Facilities

  • The Debug Library

Lua Function Reference

The contents are subject to change without notice.
Function Name Description Firmware Versions

Updated request

Issues an HTTP Request.

3.00.00+

HTTPGetFile

Downloads a file by HTTP.

3.00.00+

pio

Controls SD interface as a PIO.

3.00.00+

ftp

Downloads or upload a file by FTP.

3.00.00+

deleted md5

Generates MD5.

3.00.00

hash

Generates hash.

3.00.00+

Scan

Scans SSID.

3.00.00+

GetScanInfo

Gets results of SSID scan.

3.00.00+

Connect

Enables Wireless LAN in STA mode.

3.00.00+

Establish

Enables Wireless LAN in AP mode.

3.00.00+

Bridge

Enables Wireless LAN in Internet passthrough mode.

3.00.00+

Disconnect

Disables Wireless LAN.

3.00.00+

sleep

Stops execution of the script during the specified timespan.

3.00.00+

sharedmemory

Gets data from shared memory or writes data to shared memory.

3.00.00+

SetCert

Sets root certification by file.

3.00.00+

strconvert

Converts the string.

3.00.00+

SetChannel

Sets the wireless channels.

3.00.01+

MailSend

Sends email by FlashAir.

3.00.01+

spi

Sets the SPI by FlashAir.

3.00.01+

New spi("init")

Initialize the interface and change the clock cycle

4.00.03+

New spi("mode")

SPI mode specification

4.00.03+

New spi("bit")

Specify the number of transfer bits

4.00.03+

New spi("write")

Write and read

4.00.03+

New spi("read")

Write and read

4.00.03+

New spi("cs")

Control of chip select signal

4.00.03+

ReadStatusReg

Gets the status register contents of the FlashAir.

3.00.00+

ip

Gets or sets IP Address.

3.00.00+

WlanLink

Confirms the connection.

3.00.00+

remove

Removes a file.

3.00.00+

rename

Renames a file.

3.00.00+

Update i2c

I 2C operation.

4.00.00+

search

File search function.

4.00.00+

control("time")

Save date and time memo.

4.00.00+

control("fioget")

Get wireless LAN On/Off status.

4.00.00+

control("fioset")

Wireless LAN On/Off.

4.00.00+

ConnectedSTA

Number of connected stations at AP connection.

4.00.00+

websocket

WebSocket function.

4.00.00+

New watchdog("start")

WatchDog timer start

4.00.03+

New watchdog("stop")

WatchDog timer stop

4.00.03+

New watchdog("event")

WatchDog timer reset

4.00.03+

New watchdog("status")

Get state of WatchDog

4.00.03+

New control("hid_set_pass")

Set password for saving to hidden area

4.00.03+

New control("hid_change_pass")

Changing the password set for saving to the hidden area

4.00.03+

New control("hid_store")

Save script to hidden area

4.00.03+

New control("hid_get")

Retrieve script saved in confidential area

4.00.03+

New control("hid_clear")

Delete all script files saved by password, API

4.00.03+

New control("hid_hash")

Create a hash string from the set password and the specified character string

4.00.03+

request

Issues an HTTP (Hyper Text Transfer Protocol) request.

Syntax

b, c, h = fa.request(url [, method [, headers [, file [, body [, bufsize [, redirect [, rcvbuff [, rcvfile]]]]]]]])

Parameters

url

string. A URL.( 4.00.00 Port can be specified: 8080)

method

string. HTTP request method. "GET" is used if a method not specified.

headers

table. You can add header field information for HTTP requests.

file

string. Add the specified file to the body of the HTTP request and send it.

body

string. It adds the specified character string to the body of the HTTP request and sends it. When used in conjunction with the file option, it replaces the character string inside the body <!--WLANSDFILE--> with a file and sends it. If body is not specified, just file will be sent.

bufsize

number. Transmit buffer size of HTTP request. When sending to flickr server, set this value to 1460 * 10.

redirect

boolean. Controls validity / invalidity of redirect operation of HTTP. If you omit it is assumed to be specified true.

rcvbuff 4.00.03

string. Secure memory on Lua's stack and save the received data in secured memory.

rcvfile 4.00.03

string. It saves the received HTTP response data to the specified file.

Return values

b

string. HTTP response body.

c

number. HTTP status code.

h

string. HTTP response header.

Example

boundary = "--61141483716826"
contenttype = "multipart/form-data; boundary=" .. boundary
filepath = "sample.txt"
mes = "--".. boundary .. "¥r¥n"
 .."Content-Disposition: form-data; name=¥"file¥"; filename=¥""..file .."¥"¥r¥n"
 .."Content-Type: text/plain¥r¥n"
 .."¥r¥n"
 .."<!--WLANSDFILE-->¥r¥n"
 .."--" .. boundary .. "--¥r¥n"

blen = lfs.attributes(file,"size") + string.len(mes) - 17
b,c,h = fa.request{url = "http://192.168.0.1/upload.cgi:8080",
 method = "POST",
 headers = {["Content-Length"] = tostring(blen),
 ["Content-Type"] = contenttype},
 file = filepath,
 body = mes
 }

Notes

  • The maximum payload size of an HTTP request is 3KB.

  • A request may be canceled by TCP reset - especially when uploading a file to Flickr. Try to reduce the sending buffer size by setting bufsize to 1460 * 10 to avoid this issue.

4.00.00 Precautions

  • When executing HTTPS communication with this function, it is recommended to set the root certificate with fa.SetCert function before execution. When HTTPS communication is executed without setting the root certificate, communication is performed without verifying the server certificate using the root certificate.

  • If the validation fails as a result of verifying the server certificate using the root certificate, execution of this function will fail.

HTTPGetFile

Downloads a file by HTTP.

Syntax

result = fa.HTTPGetFile(uri, filepath [, user, pass])

Parameters

uri

string. The URI of the source.

filepath

string. Destination file name.

user

string. User string in Basic authentication.

pass

string. Pass string in basic authentication.

Return values

result

number.

1

Success.

nil

Error.

4.00.00 Precautions

  • When executing HTTPS communication with this function, it is recommended to set the root certificate with fa.SetCert function before execution. When HTTPS communication is executed without setting the root certificate, communication is performed without verifying the server certificate using the root certificate.

  • If the validation fails as a result of verifying the server certificate using the root certificate, execution of this function will fail.

pio

Controls the SD interface with PIO (Programmed Input/Output).

Syntax

s, indata = fa.pio(ctrl, data)

Parameters

ctrl

number. Pin input / output specification. Specify 0 for the bit corresponding to the pin to be read and 1 for the bit corresponding to the pin to be written.

data

number. Specify the output pin state. When 0 is set for each bit corresponding to the pin to be written, Low is output, and when it is set to 1 , High is output.

Return values

s

number. State of interface control.

1

Success.

0

Error.

indata

number. The input.

Notes

Bit assignment.

  • CMD : 0x01

  • D0 : 0x02

  • D1 : 0x04

  • D2 : 0x08

  • D3 : 0x10

ftp

Download or upload a file via FTP (File Transfer Protocol).

Syntax

result = fa.ftp(cmd, uri, filename)

Parameters

cmd

string. FTP command.

"get"

Download.

"put"

Upload.

url

string. A URI of an FTP server.

filename

string. A path to a file on a FlashAir.

Return values

result

number.

1

Success.

nil

Error.

Example

fa.ftp("get", "ftp://user:pass@ftp.test.com:21/test", "test");

md5

This is obsolete. Use hash.

hash

Generates a hash value.

Syntax

hash=fa.hash(name, data, key)

Parameters

name

string. select hash's type (md5, sha1, sha256, hmac-sha256).

data

string. data.

key

string. secret key(used if name was hmac-sha256).

Return values

hash

string. Hash value in hexadecimal notation.

Scan

Scans SSID. Call GetScanInfo() to retrieve scan results.

Syntax

count = fa.Scan([ssid])

Parameters

ssid

string. Scan the specified SSID. Or, find nearby SSIDs if none specified.

Return values

count

number. The number of APs found in the scan.

Notes

This command is unavailable if the wireless LAN is enabled (by Connect, Establish, or Bridge).

GetScanInfo

Gets results of SSID scan.

Syntax

ssid, other = fa.GetScanInfo(num)

Parameters

num

number. An index of the item in the scan result.

Return values

ssid

string. SSID.

other

table. AP information.

Notes

This command is unavailable if the wireless LAN is enabled (by Connect, Establish, or Bridge).

Example

count = fa.Scan()
for i=1,count do
  ssid,other = fa.GetScanInfo(i)
 for key, val in pairs(other) do
    print(key, val)
  end
end

Connect

Enables Wireless LAN in STA mode.

Syntax

fa.Connect(ssid, networkkey)

Parameters

ssid

string. SSID of AP that the FlashAir will connect to.

networkkey

string. Security key of AP that the FlashAir will connect to.

Return values

None.

Establish

Enables Wireless LAN in AP mode.

Syntax

fa.Establish(ssid, networkkey, encmode)

Parameters

ssid

string. SSID of AP that a FlashAir establishes.

networkkey

string. Security key of AP that a FlashAir establishes.

encmode

number. Encoding mode of AP that a FlashAir establishes.

Return values

None.

Notes

Encmode must be one of the following values:

Value Description

0

Open system, No encryption.

1

Open system, WEP

3

WPA-PSK、TKIP

4

WPA-PSK、AES

5

WPA2-PSK、TKIP

6

WPA2-PSK、AES

Bridge

Enables Wireless LAN in Internet passthrough mode.

Syntax

fa.Bridge(ssid, networkkey, encmode, brgssid, brgnetworkkey)

Parameters

ssid

string. FlashAir's SSID.

networkkey

string. The security key of FlashAir.

encmode

string. FlashAir security mode. See Notes section of Establish command.

brgssid

string. SSID of AP that the FlashAir will connects to.

brgnetworkkey

string. Security key of AP that the FlashAir will connects to.

Return values

None.

Disconnect

Disables Wireless LAN.

Syntax

fa.Disconnect()

Parameters

None.

Return values

None.

sleep

Stops execution of the script during the specified timespan.

Syntax

sleep(msec)

Parameters

msec

number. Duration to sleep between 0~(2 32 - 1) in millisecond.

Return values

None.

sharedmemory

Gets data from shared memory or writes data to shared memory.

Syntax

fa.sharedmemory(command, addr, len, wdata)

Parameters

command

string. Execution command(write, read).

addr

number. Address(0~511)( 4.00.00 0~2047).

len

number. Data length(0~512)( 4.00.00 1~2048).

wdata

string. The string of written data(Enabled by write command).

Response

write ⇒  Failure: nil  Successful: 1
read  ⇒  Failure: nil  Successful: the string of read data

Example

res1 = fa.sharedmemory("write", 0, 8, "12345678")
res2 = fa.sharedmemory("read", 1, 4, 0)
print("res=",res2)
  
 Result:res=2345

SetCert

Sets or clears root certification by file(X.509 binary encode with DER).

Syntax

fa.SetCert(filename)

Parameters

filename

string. Sets the DER file's path and the file name,Clears the root certification if omitted.

Return values

result

number.

1

Successful.

nil

Failure.

Example

lres = fa.SetCert("DerSha256.cer")
	if (res == nil) then
		print("cert err")
	end

strconvert

Converts the SJIS characters to UTF-8 , and the utf8 characters to SJIS.

Syntax

fa.strconvert(format, orgstr)

Parameters

format

string. Converts the SJIS characters to UTF-8 if specify 「sjis2utf8」, and converts the UTF-8 characters to SJIS if specify 「utf82sjis」.

orgstr

string. The original data before convert.

Response

Successful: Converted strings.
Failure: nil

Example

str = "あかさたなはまやらわ"
print("testStr=", str)
a = fa.strconvert("sjis2utf8", str )
print("toUTF8=", a)
b = fa.strconvert("utf82sjis", a)
print("toSJIS=", b)

SetChannel

Sets the wireless channels.

Syntax

fa.SetChannel(channelNo)

Parameters

channelNo

number. Channel(0~11 or 0x0~0xb, specify 0 is AUTO).

Return values

None.

Example

fa.Disconnect()
fa.SetChannel("0xB")
fa.Establish("flashair3", "12345678", "6")

MailSend

Sends email by FlashAir(enables to attach a file).

Syntax

fa.MailSend(from,headers,body,server,user,password, attachment, ContentType)

Parameters

from

string. Sender e-mail address.

headers

string. E-mail header.

body

string. Message body.

server

string. Mail server(smtp).

user

string. User's ID.

password

string. Password.

attachment

string. Selects the file attachment(OPTION).

ContentType

string. Selects a type of the contents(REQUIRED only when attachment is valid).

Response

Successful: MailSend is success.
Failure: nil(failed to send).

Example

from = "fromaddr@yahoo.co.jp"
rcpt = "toaddr@gmail.com"
a = fa.MailSend {
  from = from,
  headers = "To: "..rcpt.."\r\nFrom: "..from.."\r\nSubject: test",
  body = "HELLO HELLO",
  server = "smtp.mail.yahoo.co.jp",
  user = "flashair",
  password ="1234567890",
  attachment = "FBYF.jpg",
  ContentType = "image/jpg"
}

spi

Sets the SPI by FlashAir.

Syntax

fa.spi(command,data)

command

init

Changes the clock period(default:1000).

mode

Select the mode of the SPI(value:0~3. default:3).

bit

The number of assigned bits for transmit(default:8).

write

Write command.

read

Read command.

cs

Controls the signals of Chip Select(CS=ON if 1, CS=OFF if 0).

Response

write : The received data when write command was issued.
read : The read data when read command was issued.
otherwise: Any status.

Example

fa.spi("init", 1001)

spi("init") 4.00.03

Initialize the interface and change the clock cycle (default value: 1000). CS becomes High.

Syntax

res = fa.spi("init"[, period])

Parameters

period

number. Optional. Clock period.

Response

res

number.

1

Successful.

0

Failure.

spi("mode") 4.00.03

Sets the SPI mode. (Default value: 3)

Syntax

res = fa.spi("mode", mode)

Parameters

mode

number. Range 03 . SPI mode.

Response

res

number.

1

Successful.

0

Failure.

Notes

Execute spi("mode") before executing spi("init").

spi("bit") 4.00.03

Sets the number of transfer bits. (Default value: 8)

Syntax

res = fa.spi("bit", bit)

Parameters

bit

number. Range 132 . Number of transfer bits.

Response

res

number.

1

Successful.

0

Failure.

Notes

When specifying a character string with spi("write"), it can not be used with bit specification.

spi("write") 4.00.03

Write and read. Although it can be transferred more than once, the read result can be acquired only once last.

Syntax

res = fa.spi("write", data_num)
res = fa.spi("write", data_str, xfer_num)

Parameters

data_num

number. Transmission data.

data_str

string. Specify transmission data as a character string. It is transferred in multiple bytes each byte.

xfer_num

number. Number of bytes transmitted. When the character string length of data_str is exceeded, the transmission data is 0x00.

Response

res

number. Leaded value. (If data was transferred multiple times with one function call, the last read value)

Example

res = fa.spi("write", 0x12)
result = fa.spi("write", "hello", 8)

Notes

When data_str is used, it can not be used with bit specification.

spi("read") 4.00.03

Write and read. It can transfer multiple times and all read results can be acquired. Transmission data is repeatedly transmitted dummy data.

Syntax

res_num = fa.spi("read")
res_tbl = fa.spi("read", xfer_num, data_num)

Parameters

xfer_num

number. Number of transfers.

data_num

number. Transmission data.

Response

res_num

number. Leaded value.

res_tbl

table. Array of read values.

About transmission data

In Syntax of fa.spi("read"), all bits 0 are transmitted as dummy data.

In Syntax of fa.spi("read", xfer_num, data_num), data_num is transmitted as dummy data.

Example

res_num = fa.spi("read")
print(res_num)
res_tbl = fa.spi("read", 10, 0xff)
for i, v in ipairs(res_tbl) do
  print(i, v)
end

spi("cs") 4.00.03

Controls the chip select signal.

Syntax

fa.spi("cs", cs_level)

Parameters

cs_level

number. 1: High, 0: Low.

Example

local CS_ASSERT=0
local CS_NEGATE=1
fa.spi("mode", 2)
fa.spi("init", 1000)
fa.spi("cs", CS_ASSERT)
fa.spi("write", "hello", 5)
fa.spi("cs", CS_NEGATE)

ReadStatusReg

Gets the status register contents of the FlashAir.

Syntax

reg = fa.ReadStatusReg()

Parameters

None.

Return values

Returns the wireless LAN application status register contents as a string. Refer to Wireless LAN Application Status Register for details.

Example

Get IP address of the card.

local ipaddress = string.sub(fa.ReadStatusReg(),160,168)

ip

Gets or sets IP Address of FlashAir.

Syntax

ip, mask, gw = fa.ip(ipaddress, subnetmask, gateway)

Parameters

ipaddress

string. IP Address of FlashAir.

subnetmask

string. subnet mask.

gateway

string. IP Address of gateway.

Return values

ip

string. IP Address.

mask

string. Subnet mask.

gw

string. Gateway.

Example

-- When getting values
ip, mask, gw = fa.ip()
-- When setting values
fa.ip("192.168.11.2", "255.255.255.0", "192.168.11.1")

Confirms the FlashAir is wirelessly connected to the network.

Syntax

result = fa.WlanLink()

Parameters

None.

Return values

result

number.

1

Connected.

0

Disconnected.

remove

Removes a file.

Syntax

fa.remove(filepath)

Parameters

filepath

string. The file to be removed.

Return values

None.

Example

fa.remove("/DCIM/100__TSB/DSC_100.JPG")

rename

Moves or renames a file or a directory.

Syntax

fa.rename(oldfile, newfile)

Parameters

oldfile

string. Old file path.

newfile

string. New file path.

Return values

None.

Example

fa.rename("/DCIM/100__TSB/DSC_100.JPG","/DCIM/100__TSB/DSC_101.JPG")

i2c 4.00.00

I 2C operation is done from FlashAir. i2c works as Master.

Syntax

res, data1, data2, data3, ... = fa.i2c(table)
res, string = fa.i2c(table)
res, data, ctrl = fa.i2c{mode = "getpio"}

Parameters

table
There are the following fields.
mode
string. Attributes of I 2C operation.
freq
string. I 2C clock frequency (unit: kHz). Four possible values that can be set are "45", "100", "189", and "400". "100" is set when omitted.
timeout
number. Timeout time of slave response (unit: msec). When omitted, 10 is set.
address
number. Specify the slave address of the connecting device.
direction
string. Specify the data direction. Possible values are "read" and "write". When "read" is specified, data is read from the connected device. If "write" is specified, data is sent to the connected device.
data
string or number. Set transmission data. If specified in string format, send all set data. When specified in number format, you can set a value between 0 and 255. For "setpio", specify 0 or 1 to output PIO.
4.00.03 Support for null characters.
bytes
number. Specify the receive data size. If omitted, 1 is set.
type
string. Specify the receive data format. Possible values are "binary" and "string". By default, "binary" is set.
ctrl 4.00.03
number. Sets the direction of PIO. 0 is input, and 1 is output.
Device initialization Send start condition Send restart condition Read data from connected device Write data to connected device Send a stop condition and close the connection 4.00.03
PIO setting
4.00.03
PIO acquisition
mode "init" "start" "restart" "read" "write" "stop" "setpio" "getpio"
freq Optional Unnecessary Unnecessary Unnecessary Unnecessary Unnecessary Unnecessary Unnecessary
timeout Optional Unnecessary Unnecessary Unnecessary Unnecessary Unnecessary Unnecessary Unnecessary
address Unnecessary Required Required Unnecessary Unnecessary Unnecessary Unnecessary Unnecessary
direction Unnecessary Required Required Unnecessary Unnecessary Unnecessary Unnecessary Unnecessary
data Unnecessary Unnecessary Unnecessary Unnecessary Required Unnecessary Required Unnecessary
bytes Unnecessary Unnecessary Unnecessary Optional Optional Unnecessary Unnecessary Unnecessary
type Unnecessary Unnecessary Unnecessary Optional Unnecessary Unnecessary Unnecessary Unnecessary
ctrl Unnecessary Unnecessary Unnecessary Unnecessary Unnecessary Unnecessary Required Unnecessary

Notes

Bit Allocation
  • CMD: SCL
  • D0: SDA

Pull up SCL / SDA.
Pull down CLK.
4.00.03 D1 can be used with "setpio" / "getpio".

Multiple byte transmission
If you want to transmit multiple bytes of binary data, by executing continue to data writing, it is possible to transmit multiple bytes.

Return values

res
string. On success it returns "OK". On failure it returns other strings.
data1, data2, data3, ...
number. Values from 0 to 255 are stored. It is used only when data is read from the connected device and type = "binary" is specified.
string
string. Received data is stored. It is used only when data is read out from the connected device and type = "string" is specified.
data 4.00.03
number. The acquired value of PIO is stored. It is used only when type = "getpio" is specified.
control 4.00.03
number. The PIO direction setting value is stored. 0 is input, and 1 is output. It is used only when type = "getpio" is specified.

Example

res = fa.i2c{mode = "init", freq = "100"}
res = fa.i2c{mode = "start", address = 50, direction = "write"}
res = fa.i2c{mode = "restart", address = 50, direction = "read"}
res, data1, data2, data3, ... = fa.i2c{mode = "read", type = "binary"}
res, string = fa.i2c{mode = "read", type = "string"}
res = fa.i2c{mode = "write", data = 0}
res = fa.i2c{mode = "stop"}
Read 5 bytes from slave at address 50
res = fa.i2c{mode = "init", freq = "100"}
res = fa.i2c{mode = "start", address = 50, direction = "read"}
res, r0, r1, r2, r3, r4, r5 = fa.i2c{mode = "read", bytes = 5, type = "binary"}
res = fa.i2c{mode = "stop"}
Writes 0 to the slave at address 50 and reads 1 byte
res = fa.i2c{mode = "init", freq = "100"}
res = fa.i2c{mode = "start", address = 50, direction = "write"}
res = fa.i2c{mode = "write", data = 0}
res = fa.i2c{mode = "restart", address = 50, direction = "read"}
res, data = fa.i2c{mode = "read", bytes = 1, type = "binary"}
fa.i2c{mode = "stop"}
Operation of PIO 4.00.03
res = fa.i2c {mode ="init", freq="100"}
res = fa.i2c {mode ="setpio", data=1, ctrl=1} -- Output High
res = fa.i2c {mode ="setpio", data=0, ctrl=1} -- Output Low
                               
res = fa.i2c {mode ="setpio", data=0, ctrl=0} -- Input
res, data, ctrl = fa.i2c {mode="getpio"}

It searches for files based on the updated date and time in the specified directory. It is possible to search for a file whose with the latest date and time, or to search for a file with the update date specified by argument.

Syntax

result, filelist, time = fa.search(type, path, searchtime)

Parameters

type
string. Search type. Fixed file.
  • file:Search files
path
string. Search target directory.
searchtime
number. Update target date and time. -1 or FAT format date and time.
  • When -1 is specified, the file with the latest date and time is searched.
  • If a value other than -1 is specified, both of the following are searched.
    • Files that match the specified update date and time
    • The oldest file of the specified update date and time than the new file (the next in a new file with the specified date and time)
  • About date and time in FAT format
    • It is a 32-bit integer value, the upper 16 bits are the date and the lower 16 bits are the time
    • The date and time are the same format as the value that can be obtained when op = 100 of command.cgi

Return values

result
number. Status.
1 Successful
-1 Overflow when creating file list
  • If you specify -1 to searchtime, the string buffer in the list of "update date and time is the latest file" overflow
  • If you specify searchtime other than -1, the string buffer overflows in list creation of "the oldest file out of the specified update date and time"
-2 Overflow at creation of file list (There is a possibility of returning it only when specifying -1 for searchtime)
  • Overflow of the string buffer in the list of "file that matches the specified update date and time"
-3 Directory open error
-4 Directory read error
filelist
string. Comma separated list of files.
  • Return a list of files matching the conditions as a comma-delimited string.
  • If searchtime is other than -1, it returns a string concatenating the list of "files matching the specified update date and time" and the "list of the oldest files out of the specified update date and time".
  • If there is no such file, "" (empty string) is returned.
  • In the case of error other than the overflow returns nil.
time
number. Search result date and time.
  • If -1 is specified for searchtime, the update date and time of "file with latest update time" is returned.
  • If searchtime is other than -1, it returns the update date and time of "the oldest file out of the specified update date and time".
  • If there is no file matching the condition, 0 is returned.
  • In the case of error other than the overflow returns nil.
Notes
  • If it exceeds 512 characters when creating the file list, a buffer overflow occurs and the list is aborted halfway.
  • Search directory depth is up to 3 levels.

Example

Search for the latest file from "/DCIM".
local result, filelist, time = fa.search("file", "/DCIM", -1)
if result ~= 1 then
    print("error: ", result)
end
if filelist ~= nil then
    for f in string.gmatch(filelist, '(.-),') do
        print(f)
    end
end
if time ~= nil then
    print(string.format("time: 0x%08x", time))
end
Search from "DCIM" for the file whose update date and time is 2017/06/01 12:34:56 and the oldest file among those newer than that date / time.
local result, filelist, time = fa.search("file", "/DCIM", 0x4ac1645c)
if result ~= 1 then
    print("error: ", result)
end
if filelist ~= nil then
    for f in string.gmatch(filelist, '(.-),') do
        print(f)
    end
end
if time ~= nil then
    print(string.format("time: 0x%08x", time))
end

Notes

Example of date and time conversion in FAT format
Convert the date and time of the string to FAT format
local function StringToFatDateTime(datetime_str)
    local pattern = '(%d+)/(%d+)/(%d+)%s+(%d+):(%d+):(%d+)'
    local year,month,day,hour,min,sec = string.match(datetime_str, pattern)
    year = year - 1980
    sec = bit32.rshift(sec, 1)
    local date_fat = bit32.bor(bit32.lshift(year, 9),
                               bit32.lshift(month, 5),
                               day)
    local time_fat = bit32.bor(bit32.lshift(hour, 11),
                               bit32.lshift(min, 5),
                               sec)
    local datetime_fat = bit32.bor(bit32.lshift(date_fat, 16),
                                   time_fat)
    return datetime_fat
end
Convert date and time in FAT format to character string
local function FatDateTimeToString(datetime_fat)
    local function getbits(x, from, to)
        local mask = bit32.lshift(1, to - from + 1) - 1
        local shifted = bit32.rshift(x, from)
        return bit32.band(shifted, mask)
    end
    local fatdate = bit32.rshift(datetime_fat, 16)
    local day = getbits(fatdate, 0, 4)
    local month = getbits(fatdate, 5, 8)
    local year = getbits(fatdate, 9, 15) + 1980

    local fattime = getbits(datetime_fat, 0, 15)
    local sec = getbits(fattime, 0, 4) * 2
    local min = getbits(fattime, 5, 10)
    local hour = getbits(fattime, 11, 15)

    return string.format('%02d/%02d/%02d %02d:%02d:%02d', year, month, day, hour, min, sec)
end

control("time") 4.00.00

Saves or acquires the date and time memo.

Syntax

result = fa.control("time"[, savetime])

Parameters

The first argument is "time" fixed.
savetime
number. Date and time to save. It is specified in FAT format.
  • savetime If there is an argument, save the specified date and time.
  • savetime If there is no argument, get the saved date and time.
  • About date and time in FAT format
    • It is a 32-bit integer value, the upper 16 bits are the date and the lower 16 bits are the time.
    • The date and time are the same format as the value that can be obtained when op = 100 of command.cgi.

Return values

result
number. Date and time acquired.
  • If the savetime argument is given, it returns the specified date and time itself.
  • savetime If there is no argument, it returns the saved date and time.
    • If the date and time are not stored, -1 is returned.
  • In case of error, it returns nil.

Example

Save "2017/06/01 12:34:56".
result = fa.control("time", 0x4ac1645c)
Retrieve the saved date and time.
result = fa.control("time")
if result ~= nil then
    print(string.format("time: 0x%08x", result))
end

control("fioget") 4.00.00

Get on/off state of wireless LAN.

Syntax

result = fa.control("fioget")

Parameters

The first argument "fioget" is fixed.

Return values

result
number. The state of the current wireless LAN.
  • 1:Wireless LAN on.
  • 0:Wireless LAN is Off.

control("fioset") 4.00.00

Turn on / off the wireless LAN.

Syntax

result = fa.control("fioset", enable)

Parameters

The first argument "fioset" is fixed.
enable
number. Specify 1 or 0.
  • 1:Turn on the wireless LAN. Settings such as mode and the SSID is the contents of the CONFIG file is applied.
  • 0:Turn off wireless LAN.

Return values

result
number. The state of the current wireless LAN.
  • 1:Wireless LAN on.
  • 0:Wireless LAN is Off.

ConnectedSTA 4.00.00

Returns the number of connected stations at the time of AP connection, ip, mac.

Syntax

cnt,tbl = fa.ConnectedSTA()

Return values

cnt
Return the number of connected stations.
Tbl
Return the table of the acquired client. If cnt is 0, return nil.

Example

Confirm how many units are connected when starting AP.
local cnt, tbl = fa.ConnectedSTA()
print(cnt,tbl)
for i,t in ipairs(tbl) do 
  for k,v in pairs(t) do
    print(k,v)
  end
end
result
   1       table: 856B1C
   mac     40:48:0f:7b:37:92
   ip      192.168.0.11

websocket 4.00.00

WebSocket communication.

Syntax

res, type, payload = fa.websocket(table)

Parameters

table
There are the following fields.
mode
string. Attributes of WebSocket connection.
address
string. The server address of the connection destination.
payload
string or table. Message content (character string, array).
type
number. Message type (text = 1, binary = 2, PING = 9, default = automatic determination).
length
number. Message length (default = payload object length).
tout
number. Timeout time (unit: msec).
open Send Messege Receive message Close
mode "open" "send" "recv" "close"
address Required Unnecessary Unnecessary Unnecessary
payload Unnecessary Required Unnecessary Unnecessary
type Unnecessary Optional Unnecessary Unnecessary
length Unnecessary Optional Unnecessary Unnecessary
tout Unnecessary Unnecessary Optional Unnecessary

Return values

res
number. When reception is successful, 0 or positive number is returned. When reception fails, it returns a negative number.
type
number. Message type (text = 1, binary = 2). When reception fails, nil is returned. It is used only when receiving a message.
payload
string or table. Received message. When reception fails, nil is returned. It is used only when receiving a message.

Example

res = fa.websocket{mode = "open", address = "ws://localhost/socket"}
res = fa.websocket{mode = "send", payload = "hello!", type = 1}
res, type, payload = fa.websocket{mode = "recv", tout = 5000}
fa.websocket{mode = "close"}

watchdog("start") 4.00.03

Start the timer of WatchDog.

Syntax

result = fa.watchdog("start", cycle)

Parameters

First Parameters is fixed "start".
cycle

number. Specify watchdog issue in seconds.

Return values

result
number.
1

Timer started.

0

Timer waiting time not set yet.

Notes

WatchDog is a timer to ensure that the system will continue to function correctly. If an abnormal situation occurs in the system after starting the WatchDog timer and it is not able to be reset, restarting FlashAir is the proper course of action.

Example

  1. Add LUA_RUN_SCRIPT=/HelloWorld.lua to the CONFIG file. Save HelloWorld.lua used in this tutorial on the FlashAir route. If you already have Hello.txt on the route please rename or delete it.
  2. Save the following code on the FlashAir route.
    /WatchDog.lua
    fa.watchdog("start", 10)
    print("watchdog start")
    for i = 1, 30 do
      result = fa.watchdog("status")
      print("watchdog status:"..result)
    end
    result, filelist, time = fa.search("file", "/DCIM", -1)
    if filelist ~= nill then
      result = fa.watchdog("event")
      print("watchdog restart")
    else
      fa.watchdog("stop")    
      print("watchdog stop")                    
    end
    while 0 ~= fa.watchdog("status") do
      result = fa.watchdog("status")
      print("watchdog status:"..result)
    end
    This script starts the Watchdog timer at 10 second intervals, checks the Watchdog status several times, restarts the Watchdog timer when there is /DCIM, and also continues printing until the Watchdog status is 0.
  3. Pull out the FlashAir.
  4. Check the Hello.txt file created by HelloWorld.lua. (Hello There! Should be displayed on one line)
  5. Run WatchDog.lua from your browser.
  6. When the content output by the print statement is displayed in the browser, check the Hello.txt file without inserting / removing it. (There should be two rows of Hello There!)
    You can check that FlashAir has restarted and that the LUA_RUN_SCRIPT is running.

watchdog("stop") 4.00.03

Stop the WatchDog timer.

Syntax

result = fa.watchdog("stop")

Parameters

First Parameters is fixed "stop".

Return values

result
number.
0

Timer stop.

watchdog("event") 4.00.03

Reset the timer of WatchDog.

Syntax

result = fa.watchdog("event")

Parameters

First Parameters is fixed "event".

Return values

result
number.
1

Timer restart.

0

You have not started watchdog (timer waiting time not set).

watchdog("status") 4.00.03

Get the state of WatchDog.

Syntax

result = fa.watchdog("status")

Parameters

First Parameters is fixed "status".

Return values

result
number.
0 or more

watchdog Time remaining until the timer is activated.

0

The remaining time until activation is less than 1 second.

-1

Watchdog timer waiting.

control("hid_set_pass") 4.00.03

Sets the password for the preservation of the secret area.

Syntax

fa.control("hid_set_pass", password)

Parameters

First Parameters is fixed "hid_set_pass".
password
string. Password.

Return values

None.

control("hid_change_pass") 4.00.03

Change the password set for the hidden area.

Syntax

ret = fa.control("hid_change_pass", old_password, new_password)

Parameters

First Parameters is fixed "hid_change_pass".
old_password
string. The configured password.
new_password
string. New password.

Return values

ret
number.
0

Successful.

1

Configuration error.

-1

Password length error.

control("hid_store") 4.00.03

Save the script to the hidden area.

Syntax

fa.control("hid_store", filename, password)

Parameters

First Parameters is fixed "hid_store".
filename
string. Script to save.
password
string. Password.

Return values

None.

Example

fa.control("hid_store", "test.lua", "12345678")

Set the saved file with CONFIG

LUA_RUN_SCRIPT=H:filename
LUA_SD_EVNET=H:filename

control("hid_get") 4.00.03

Get the script saved in the hidden area.

Syntax

fa.control("hid_get", filename , dstfilename, password)

Parameters

First Parameters is fixed "hid_get".
filename
string. Saved script.
dstfilename
string. Name of the destination file.
password
string. Password.

Return values

None.

Example

fa.control("hid_get", "h:sys.lua", "tmp/option.lua", "mysecret")

Notes

  • You can not access files saved in confidential area from Lua script executed in the area accessible from the host.

control("hid_clear") 4.00.03

Delete all script files saved by password, API.

Syntax

fa.control("hid_clear")

Parameters

First Parameters is fixed "hid_clear".

Return values

None.

control("hid_hash") 4.00.03

Create a hash string from the password set in the hidden area and the specified character string.

Syntax

ret = fa.control("hid_hash", string)

Parameters

First Parameters is fixed "hid_change_pass".
string
string. Setting string.

Return values

ret
string. Hash value.

Partition operation 4.00.03

You can access the second partition. The second partition is an area where Lua's internal logs are saved and there is no effect from file access from the host device.
It is possible to specify the partition by the drive letter.

Syntax

"p" --1st partition (omitted)
"s" --2nd Partition
"h" --Secret area

Other

Partition creation can be divided using host equipment such as Linux, Win10.

Example

local file = io.open("s:\flashair.log", "a")