Lua Scripting

Last update: September 2017

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+

Updated 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+

Updated 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+

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+

New i2c

I2C operation.

4.00.00+

New search

File search function.

4.00.00+

New control("time")

Save date and time memo.

4.00.00+

New control("fioget")

Get wireless LAN On/Off status.

4.00.00+

New control("fioset")

Wireless LAN On/Off.

4.00.00+

New ConnectedSTA

Number of connected stations at AP connection.

4.00.00+

New websocket

WebSocket function.

4.00.00+

request

Issues an HTTP (Hyper Text Transfer Protocol) request.

Syntax

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

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.

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~(232 - 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 wrriten 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)

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

I2C operation is done from FlashAir. i2c works as Master.

Syntax

res, data1, data2, data3, ... = fa.i2c(table)
res, string = fa.i2c(table)

Parameters

table
There are the following fields.
mode
string. Attributes of I2C operation.
freq
string. I2C 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.
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.
Device initializationSend start conditionSend restart conditionRead data from connected deviceWrite data to connected deviceSend a stop condition and close the connection
mode"init""start""restart""read""write""stop"
freqOptionalUnnecessaryUnnecessaryUnnecessaryUnnecessaryUnnecessary
timeoutOptionalUnnecessaryUnnecessaryUnnecessaryUnnecessaryUnnecessary
addressUnnecessaryRequiredRequiredUnnecessaryUnnecessaryUnnecessary
directionUnnecessaryRequiredRequiredUnnecessaryUnnecessaryUnnecessary
dataUnnecessaryUnnecessaryUnnecessaryUnnecessaryRequiredUnnecessary
bytesUnnecessaryUnnecessaryUnnecessaryOptionalOptionalUnnecessary
typeUnnecessaryUnnecessaryUnnecessaryOptionalUnnecessaryUnnecessary

Notes

Bit Allocation
  • CMD: SCL
  • D0: SDA

Pull up SCL / SDA.
Pull down CLK.

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.

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

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).
openSend MessegeReceive messageClose
mode"open""send""recv""close"
addressRequiredUnnecessaryUnnecessaryUnnecessary
payloadUnnecessaryRequiredUnnecessaryUnnecessary
typeUnnecessaryOptionalUnnecessaryUnnecessary
lengthUnnecessaryOptionalUnnecessaryUnnecessary
toutUnnecessaryUnnecessaryOptionalUnnecessary

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