Lua Scripting

Last update: July 2019

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.

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:

  • Coroutine Manipulation
  • Operating System Facilities
  • The Debug Library

Lua Function Reference

Function Name Description Firmware Versions
Bridge Enables Wireless LAN in Internet passthrough mode. 3.00.00+
Connect Enables Wireless LAN in STA mode. 3.00.00+
ConnectedSTA Number of connected stations at AP connection. 4.00.00+
control("fioget") Get wireless LAN On/Off status. 4.00.00+
control("fioset") Wireless LAN On/Off. 4.00.00+
control("hid_change_pass") Changing the password set for saving to the hidden area 4.00.04+
control("hid_clear") Delete all script files saved by password, API 4.00.04+
control("hid_get") Retrieve script saved in confidential area 4.00.04+
control("hid_hash") Create a hash string from the set password and the specified character string 4.00.04+
control("hid_set_pass") Set password for saving to hidden area 4.00.04+
control("hid_store") Save script to hidden area 4.00.04+
control("time") Save date and time memo. 4.00.00+
Disconnect Disables Wireless LAN. 3.00.00+
Establish Enables Wireless LAN in AP mode. 3.00.00+
ftp Downloads or upload a file by FTP. 3.00.00+
GetScanInfo Gets results of SSID scan. 3.00.00+
hash Generates hash. 3.00.00+
HTTPGetFile Downloads a file by HTTP. 3.00.00+
Update i2c I 2C operation. 4.00.00+
ip Gets or sets IP Address. 3.00.00+
Update MailSend Sends email by FlashAir. 3.00.01+
deleted md5 Generates MD5. 3.00.00
ping Issue PING to specified IP. 3.00.00+
pio Controls SD interface as a PIO. 3.00.00+
New pwm("duty") Set frequency and duty ratio at pwm operation 4.00.03+
New pwm("init") Enable pwm, set number of channels 4.00.03+
New pwm("start") Operate specified channel at pwm operation 4.00.03+
New pwm("stop") Stop specified channel at pwm operation 4.00.03+
ReadStatusReg Gets the status register contents of the FlashAir. 3.00.00+
remove Removes a file. 3.00.00+
rename Renames a file. 3.00.00+
Updated request Issues an HTTP Request. 3.00.00+
Scan Scans SSID. 3.00.00+
search File search function. 4.00.00+
New serial("init") Enable serial, set baudrate 4.00.03+
New serial("read") Receive data during serial operation 4.00.03+
New serial("write") Send data during serial operation 4.00.03+
SetCert Sets root certification by file. 3.00.00+
SetChannel Sets the wireless channels. 3.00.01+
sharedmemory Gets data from shared memory or writes data to shared memory. 3.00.00+
sleep Stops execution of the script during the specified timespan. 3.00.00+
spi Sets the SPI by FlashAir. 3.00.01+
spi("bit") Specify the number of transfer bits 4.00.03+
spi("cs") Control of chip select signal 4.00.03+
spi("init") Initialize the interface and change the clock cycle 4.00.03+
spi("mode") SPI mode specification 4.00.03+
spi("read") Write and read 4.00.03+
spi("write") Write and read 4.00.03+
strconvert Converts the string. 3.00.00+
New udp UDP transmission 4.00.04+
New udp {mode="recv"} UDP reception 4.00.04+
New udp {mode="send"} UDP transmission 4.00.04+
New udp {mode="send_interval"} UDP specified interval transmission 4.00.04+
New udp {mode="stop"} UDP transmission stop 4.00.04+
New udp("state") UDP transmit / receive status acquisition 4.00.04+
watchdog("event") WatchDog timer reset 4.00.03+
watchdog("start") WatchDog timer start 4.00.03+
watchdog("status") Get state of WatchDog 4.00.03+
watchdog("stop") WatchDog timer stop 4.00.03+
websocket WebSocket function. 4.00.00+
WlanLink Confirms the connection. 3.00.00+

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.

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.

ConnectedSTA

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

control("fioget")

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")

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.

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_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_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_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.

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_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("time")

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

Disconnect

Disables Wireless LAN.

Syntax

fa.Disconnect()

Parameters

None.

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

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.

Notes

  • FlashAir's compatible data transfer mode is passive (PASV) mode only.
  • If you use FTPS connection, you can do it by setting the URL to ftps://. Both implicit and explicit modes are available.
  • For port designation, add a port number after the host name.

Example

result = fa.ftp("get", "ftp://user:pass@ftp.test.com:21/test.txt", "test.txt");
result = fa.ftp("put", "ftps://user:pass@ftp.test.com:990/test.txt;implicit", "test.txt");
result = fa.ftp("put", "ftps://user:pass@ftp.test.com:990/test.txt;explicit", "test.txt");

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=0,count-1 do
    ssid,other = fa.GetScanInfo(i)
    for key, val in pairs(other) do
        print(key, val)
    end
end

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.

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.

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.

i2c

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
number. 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. When type is "binary", values from 1 to 16 can be specified. When type is "string", the minimum value is 1 and the maximum value is memory dependent. By default, 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, 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"}

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")

MailSend

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

Syntax

fa.MailSend(table)

Parameters

table
There are the following fields.
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).
port 4.00.03
number. Specifies the port number. The default is 465.

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"
}

md5

This is obsolete. Use hash.

ping

Issue PING to specified IP.

Syntax

result = fa.ping(ip)

Parameters

ip
string. IP Address.

Response

result
number.
1
Success.
nil
Error.

Example

result = fa.ping("192.168.130.1")

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

pwm("duty") 4.00.03

Set the frequency and duty ratio when doing PWM operation with FlashAir.

Syntax

res = fa.pwm("duty", ch, freq, duty)

Parameters

ch
number. Pin information to specify operation. 04 channels can be specified.
freq
number. Frequency (in Hz). It can be specified by floating point.
duty
number. Duty ratio (0 to 100%). It can be specified by floating point.

Return values

res
number.
1
Success.
nil
Error.

pwm("init") 4.00.03

Enable pwm and set the number of channels when using pwm with FlashAir.

Syntax

ret = fa.pwm("init", ch, enable)

Parameters

ch
number. Specify one channel to set pwm mode. 04 channels can be specified.
enable
number. Specify 1 or 0.
1
Enable pwm mode.
0
Disable pwm mode.

Return values

res
number.
1
Success.
nil
Error.

Precautions

  • Requires IFMODE=1 in CONFIG.
  • Bit Allocation
    • CMD: 0ch
    • D0: 1ch
    • D1: 2ch
    • D2: 3ch
    • D3: 4ch

pwm("start") 4.00.03

Operates the specified channel when performing pwm operation with FlashAir. 0~4 channels can be specified.

Syntax

res = fa.pwm("start", ch)

Parameters

ch
number. Pin information to specify operation. 04 channels can be specified.

Return values

res
number.
1
Success.
nil
Error.

pwm("stop") 4.00.03

Stop the specified channel when performing pwm operation with FlashAir. 0~4 channels can be specified.

Syntax

res = fa.pwm("stop", ch)

Parameters

ch
number. Pin information to stop and specify.04 channels can be specified.

Return values

res
number.
1
Success.
nil
Error.

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)

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")

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.( 3.00.02 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.

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.

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).

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

serial("init") 4.00.03

Set serial enable and baudrate when using serial operation with FlashAir.

Syntax

fa.serial("init", [boudrate])

Parameters

boudrate
number. BaudRate (115,200 baud when not set).

Return values

None

Precautions

  • Requires IFMODE=1 in CONFIG.
  • Bit Allocation
    • CMD: RX
    • D0: TX
    • GND: GND
  • There is no flow control function.

serial("read") 4.00.03

Receive data when performing serial operation with FlashAir.

Syntax

data = fa.serial("read")

Parameters

None

Return values

data
number. Acquired data. Data is acquired in 1byte, number format. If the receive buffer is empty, nil is returned.

serial("write") 4.00.03

Send data when using performing serial operation with FlashAir.

Syntax

fa.serial("write", data)

Parameters

data
string or number(0~255) or table. Send data.

Return values

None

SetCert

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

Syntax

fa.SetCert(filename)

Parameters

filename
string. Specify the DER file path and file name. Clears the certificate when an empty string is specified.

Return values

result
number.
1
Successful.
nil
Failure.

Example

-- Certificate registration
res = fa.SetCert("DerSha256.cer")
if res == nil then
    print("certificate registration error")
end

-- Clear certificate
res = fa.SetCert("")
if res == nil then
    print("certificate clear error")
end

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")

sharedmemory

Gets data from shared memory or writes data to shared memory.
4.00.03 Added support for write and read null characters.

Syntax

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

Parameters

command
string. Execution command(write, read).
addr
number. Address(0~511)(0~2047).
len
number. Data length(0~512)(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

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.

spi

Sets the SPI by FlashAir.

Syntax

fa.spi(command,data)

command

init
Changes the clock period(default:1000).

Bit Allocation

  • D0 : CLK
  • D1 : CS
  • D2 : MISO
  • CMD : MOSI
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("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("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)

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("read") 4.00.03

Write and read. It can rotate multiple times and get all lead results. Transmission data transmits fixed value repeatedly.

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 0s are transmitted.

In Syntax of fa.spi("read", xfer_num, data_num), data_num is sent repeatedly.

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("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.

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)

udp 4.00.04

Send UDP.

Syntax

res = fa.udp(address, port, type, data)

Parameters

address
string. Destination address.
port
number. Destination port.
type
string. data type.
  • "message":Send a string.
  • "file": Send file.
data
string. Send data when type = "message", file name to send when type = "file".

Response

res
number or nil.
1

Successful.

nil

Failure.

Example

Send string

res = fa.udp("192.168.0.11", 50000, "message", "hello")

Send file

res = fa.udp("192.168.0.11", 50000, "file", "hello.txt")

Notes

  • It will be an asynchronous function call.
  • If UDP transmission / reception is already in progress, execution will fail.

udp {mode="recv"} 4.00.04

Receive UDP.

Syntax

res = fa.udp(table)

Parameters

table
There are the following fields:
mode
string. UDP operation attribute. Specify "recv".
address
string. Receive only from the specified address. Optional. If omitted, it receives from all addresses.
port
number. Waiting port for reception.
file
string. File name to save received data. If "sharedmemory" is specified, it will be stored in shared memory.
offset
number. Offset within sharedmemory. This can be specified only when "sharedmemory" is specified in file. Optional. The default is 0.
size
number. Receive size. The reception operation stops after receiving the specified size. Optional. When size is received when receiving to a file, the received size is unlimited. When receiving in shared memory and size is omitted, 2048-offset is the size value.
timeout
number. Timeout time (seconds). Reception operation stops after the specified time. Default is no timeout.

Required / abbreviated list of each field

Receive
mode "recv"
address Optional
port Required
file Required
offset Can be specified only when "sharedmemory" is specified for file (Optional)
size Optional
timeout Optional

Response

res
number or nil.
1

Successful.

nil

Failure.

Example

Receive to shared memory (address 100 to 10 bytes)

res = fa.udp {mode = "recv",
  port = 50000,
  file = "sharedmemory",
  offset = 100,
  size = 10
}

Receive to file (end with 100 bytes, timeout 30 seconds)

res = fa.udp {mode = "recv",
  port = 50000,
  file = "recv.txt",
  size = 100,
  timeout = 30
}

Notes

  • It will be an asynchronous function call.
  • If UDP transmission / reception is already in progress, execution will fail.
  • If a file name is specified for file, the received data is added to the file.
  • If a file name is specified for file, it will not be reflected in the file until reception is completed.
  • When a file name is specified for file, the maximum size that can be received in one packet is 1460 bytes.
  • Reception operation stops under the following conditions.
    • The number of received bytes reaches the size specified by size (when size is specified)
    • The time specified by timeout elapses (when timeout is specified)
    • execute fa.udp {mode = "stop"}

udp {mode="send"} 4.00.04

Send UDP.

Syntax

res = fa.udp(table)

Parameters

table
There are the following fields:
mode
string. UDP operation attribute. Specify "send".
address
string. Destination address.
port
number. Destination port.
file
string. File name where transmission data is stored. Specify "sharedmemory" to send from shared memory. It can not be specified when message is specified.
message
string. String to send. It can not be specified when file is specified.
offset
number. Offset within sharedmemory. This can be specified only when "sharedmemory" is specified in file. Optional. The default is 0.
size
number. Send size. Optional. By default, all contents specified in file or message are sent. When "sharedmemory" is specified for file and size is omitted, all contents after the position of offset are transmitted.

Required / abbreviated list of each field

Send
mode "send"
address Required
port Required
file Specify only one of file and message
message Specify only one of file and message
offset Can be specified only when "sharedmemory" is specified for file (Optional)
size Optional

Response

res
number or nil.
1

Successful.

nil

Failure.

Example

Send string

res = fa.udp {mode = "send",
  address = "192.168.0.11",
  port = 50000,
  message = "hello"
}

Send file contents

res = fa.udp {mode = "send",
  address = "192.168.0.11",
  port = 50000,
  file = "hello.txt"
}

Send shared memory contents

fa.sharedmemory("write", 2, 17, "from sharedmemory")
res = fa.udp {mode = "send",
  address = "192.168.0.11",
  port = 50000,
  file = "sharedmemory",
  offset = 2,
  size = 17
}

Notes

  • It will be an asynchronous function call.
  • If UDP transmission / reception is already in progress, execution will fail.
  • Specify either file or message.

udp {mode="send_interval"} 4.00.04

Send UDP at specified intervals.

Syntax

res = fa.udp(table)

Parameters

table
There are the following fields:
mode
string. UDP operation attribute. Specify "send_interval".
address
string. Destination address.
port
number. Destination port.
file
string. File name where transmission data is stored. Specify "sharedmemory" to send from shared memory. It can not be specified when message is specified.
message
string. String to send. It can not be specified when file is specified.
offset
number. Offset within sharedmemory. This can be specified only when "sharedmemory" is specified in file. Optional. The default is 0.
size
number. Send size. Optional. By default, all contents specified in file or message are sent. When "sharedmemory" is specified for file and size is omitted, all contents after the position of offset are transmitted.
interval
number. Transmission interval (seconds). Optional. The default value is 5.
timeout
number. Timeout time (seconds). Default is no timeout.

Required / abbreviated list of each field

Specified interval transmission
mode "send_interval"
address Required
port Required
file Specify only one of file and message
message Specify only one of file and message
offset Can be specified only when "sharedmemory" is specified for file (Optional)
size Optional
interval Optional
timeout Optional

Response

res
number or nil.
1

Successful.

nil

Failure.

Example

Send for 10 seconds at 1 second intervals

res = fa.udp {mode = "send_interval",
  address = "192.168.0.11",
  port = 50000,
  file = "hello.txt",
  interval = 1,
  timeout = 10
}

Notes

  • It will be an asynchronous function call.
  • If UDP transmission / reception is already in progress, execution will fail.
  • Specify either file or message.
  • The specified interval transmission operation is stopped under the following conditions.
    • The time specified by timeout elapses (when timeout is specified)
    • execute fa.udp {mode = "stop"}

udp {mode="stop"} 4.00.04

Stops UDP reception operation or specified interval transmission operation.

Syntax

res = fa.udp(table)

Parameters

table
There are the following fields:
mode
string. UDP operation attribute. Specify "stop".

Response

res
number or nil.
1

Successful.

nil

Failure.

udp("state") 4.00.04

Gets the UDP send / receive status.

Syntax

state, count = fa.udp("state")

Parameters

The first parameter is fixed to "state".

Response

state
number.
1

UDP transmission and reception is operating asynchronously.

0

UDP transmission and reception is not working.

count
number or string.
number

Number of transmit and receive bytes from the start of transmit and receive.

string: "destination unreachable\n"

Response when transmission size is 0 and connection device can not be found.

Example

Wait until UDP transmission / reception is completed

for i=1, 1000 do
  local state, count = fa.udp("state")
  if state == 0 then
    break
  end
  sleep(20)
end

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("start") 4.00.03

Start the timer of WatchDog. FlashAir restarts when it times out.

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("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.

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.

websocket

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). 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"}

Confirms the FlashAir is wirelessly connected to the network.

Syntax

result = fa.WlanLink()

Parameters

None.

Return values

result
number.
1
Connected.
0
Disconnected.

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")