Commit 4911d2db authored by Arnim Läuger's avatar Arnim Läuger
Browse files

Merge pull request #1336 from nodemcu/dev

1.5.1 master drop
parents c8037568 2e109686
# APA102 Module
| Since | Origin / Contributor | Maintainer | Source |
| :----- | :-------------------- | :---------- | :------ |
| 2016-01-26 | [Robert Foss](https://github.com/robertfoss)| [Robert Foss](https://github.com/robertfoss)| [apa102.c](../../../app/modules/apa102.c)|
This module provides Lua access to [APA102 RGB LEDs](https://youtu.be/UYvC-hukz-0) which are similar in function to the common [WS2812](ws2812) addressable LEDs.
> DotStar LEDs are 5050-sized LEDs with an embedded micro controller inside the LED. You can set the color/brightness of each LED to 24-bit color (8 bits each red green and blue). Each LED acts like a shift register, reading incoming color data on the input pins, and then shifting the previous color data out on the output pin. By sending a long string of data, you can control an infinite number of LEDs, just tack on more or cut off unwanted LEDs at the end.
source: [Adafruit](https://www.adafruit.com/products/2343)
## apa102.write()
Send ABGR data in 8 bits to a APA102 chain.
#### Syntax
`apa102.write(data_pin, clock_pin, string)`
#### Parameters
- `data_pin` any GPIO pin 0, 1, 2, ...
- `clock_pin` any GPIO pin 0, 1, 2, ...
- `string` payload to be sent to one or more APA102 LEDs.
It should be composed from a AGRB quadruplet per element.
- `A1` the first pixel's Intensity channel (0-31)
- `B1` the first pixel's Blue channel (0-255)<br />
- `G1` the first pixel's Green channel (0-255)
- `R1` the first pixel's Red channel (0-255)
... You can connect a lot of APA102 ...
- `A2`, `G2`, `R2`, `B2` are the next APA102s Intensity, Blue, Green and channel parameters
#### Returns
`nil`
#### Example
```lua
a = 31
g = 0
r = 255
b = 0
led_abgr = string.char(a, g, r, b, a, g, r, b)
apa102.write(2, 3, leds_abgr) -- turn two APA102s to red, connected to data_pin 2 and clock_pin 3
```
# bit Module
| Since | Origin / Contributor | Maintainer | Source |
| :----- | :-------------------- | :---------- | :------ |
| 2014-12-24 | [https://github.com/LuaDist/bitlib](https://github.com/LuaDist/bitlib), [Zeroday](https://github.com/funshine) | [Zeroday](https://github.com/funshine) | [bit.c](../../../app/modules/bit.c)|
Bit manipulation support, on 32bit integers.
## bit.arshift()
Arithmetic right shift a number equivalent to `value >> shift` in C.
####Syntax
`bit.arshift(value, shift)`
####Parameters
- `value` the value to shift
- `shift` positions to shift
####Returns
the number shifted right (arithmetically)
## bit.band()
Bitwise AND, equivalent to `val1 & val2 & ... & valn` in C.
####Syntax
`bit.band(val1, val2 [, ... valn])`
####Parameters
- `val1` first AND argument
- `val2` second AND argument
- `...valn` ...nth AND argument
####Returns
the bitwise AND of all the arguments (number)
## bit.bit()
Generate a number with a 1 bit (used for mask generation). Equivalent to `1 << position` in C.
####Syntax
`bit.bit(position)`
####Parameters
`position` position of the bit that will be set to 1
####Returns
a number with only one 1 bit at position (the rest are set to 0)
## bit.bnot()
Bitwise negation, equivalent to `~value in C.
####Syntax
`bit.bnot(value)`
####Parameters
`value` the number to negate
####Returns
the bitwise negated value of the number
## bit.bor()
Bitwise OR, equivalent to `val1 | val2 | ... | valn` in C.
####Syntax
`bit.bor(val1, val2 [, ... valn])`
####Parameters
- `val1` first OR argument.
- `val2` second OR argument.
- `...valn` ...nth OR argument
####Returns
the bitwise OR of all the arguments (number)
## bit.bxor()
Bitwise XOR, equivalent to `val1 ^ val2 ^ ... ^ valn` in C.
####Syntax
`bit.bxor(val1, val2 [, ... valn])`
####Parameters
- `val1` first XOR argument
- `val2` second XOR argument
- `...valn` ...nth XOR argument
####Returns
the bitwise XOR of all the arguments (number)
## bit.clear()
Clear bits in a number.
####Syntax
`bit.clear(value, pos1 [, ... posn])`
####Parameters
- `value` the base number
- `pos1` position of the first bit to clear
- `...posn` position of thet nth bit to clear
####Returns
the number with the bit(s) cleared in the given position(s)
## bit.isclear()
Test if a given bit is cleared.
####Syntax
`bit.isclear(value, position)`
####Parameters
- `value` the value to test
- `position` bit position to test
####Returns
true if the bit at the given position is 0, false othewise
## bit.isset()
Test if a given bit is set.
####Syntax
`bit.isset(value, position)`
####Parameters
- `value` the value to test
- `position` bit position to test
####Returns
true if the bit at the given position is 1, false otherwise
## bit.lshift()
Left-shift a number, equivalent to `value << shift` in C.
####Syntax
`bit.lshift(value, shift)`
####Parameters
- `value` the value to shift
- `shift` positions to shift
####Returns
the number shifted left
## bit.rshift()
Logical right shift a number, equivalent to `( unsigned )value >> shift` in C.
####Syntax
`bit.rshift(value, shift)`
####Parameters
- `value` the value to shift.
- `shift` positions to shift.
####Returns
the number shifted right (logically)
## bit.set()
Set bits in a number.
####Syntax
`bit.set(value, pos1 [, ... posn ])`
####Parameters
- `value` the base number.
- `pos1` position of the first bit to set.
- `...posn` position of the nth bit to set.
####Returns
the number with the bit(s) set in the given position(s)
# BME280 module
| Since | Origin / Contributor | Maintainer | Source |
| :----- | :-------------------- | :---------- | :------ |
| 2016-02-21 | [vsky279](https://github.com/vsky279) | [vsky279](https://github.com/vsky279) | [bit.c](../../../app/modules/bme280.c)|
This module provides a simple interface to [BME280/BMP280 temperature/air presssure/humidity sensors](http://www.bosch-sensortec.com/bst/products/all_products/bme280) (Bosch Sensortec).
Note that you must call [`init()`](#bme280init) before you can start reading values!
## bme280.altitude()
For given air pressure and sea level air pressure returns the altitude in meters as an integer multiplied with 100, i.e. altimeter function.
#### Syntax
`bme280.altitude(P, QNH)`
#### Parameters
- `P` measured pressure
- `QNH` current sea level pressure
#### Returns
altitude in meters of measurement point
## bme280.baro()
Reads the sensor and returns the air temperature in hectopascals as an integer multiplied with 1000 or `nil` when readout is not successful.
Current temperature is needed to calculate the air pressure so temperature reading is performed prior reading pressure data. Second returned variable is therefore current temperature.
#### Syntax
`bme280.baro()`
#### Parameters
none
#### Returns
- `P` air pressure in hectopascals multiplied by 1000
- `T` temperature in celsius as an integer multiplied with 100
## bme280.dewpoint()
For given temperature and relative humidity returns the dew point in celsius as an integer multiplied with 100.
#### Syntax
`bme280.dewpoint(H, T)`
#### Parameters
- `H` relative humidity in percent multiplied by 1000.
- `T` temperate in celsius multiplied by 100.
#### Returns
dew point in celsisus
## bme280.humi()
Reads the sensor and returns the air relative humidity in percents as an integer multiplied with 100 or `nil` when readout is not successful.
Current temperature is needed to calculate the relative humidity so temperature reading is performed prior reading pressure data. Second returned variable is therefore current temperature.
#### Syntax
`bme280.humi()`
#### Parameters
none
#### Returns
- `H` last relative humidity reading in % times 1000
- `T` temperature in celsius as an integer multiplied with 100
## bme280.init()
Initializes module. Initialization is mandatory before read values.
#### Syntax
`bme280.init(sda, scl, [temp_oss, press_oss, humi_oss, power_mode, inactive_duration, IIR_filter])`
#### Parameters
- `sda` - SDA pin
- `scl` - SCL pin
- (optional) `temp_oss` - Controls oversampling of temperature data. Default oversampling is 16x.
- (optional) `press_oss` - Controls oversampling of pressure data. Default oversampling is 16x.
- (optional) `humi_oss` - Controls oversampling of humidity data. Default oversampling is 16x
- (optional) `sensor_mode` - Controls the sensor mode of the device. Default sensor more is normal.
- (optional) `inactive_duration` - Controls inactive duration in normal mode. Default inactive duration is 20ms.
- (optional) `IIR_filter` - Controls the time constant of the IIR filter. Default fitler coefficient is 16.
|`temp_oss`, `press_oss`, `humi_oss`|Data oversampling|
|-----|-----------------|
|0|Skipped (output set to 0x80000)|
|1|oversampling ×1|
|2|oversampling ×2|
|3|oversampling ×4|
|4|oversampling ×8|
|**5**|**oversampling ×16**|
|`sensor_mode`|Sensor mode|
|-----|-----------------|
|0|Sleep mode|
|1 and 2|Forced mode|
|**3**|**Normal mode**|
Using forced mode is recommended for applications which require low sampling rate or hostbased synchronization. The sensor enters into sleep mode after a forced readout. Please refer to BME280 Final Datasheet for more details.
|`inactive_duration`|t standby (ms)|
|-----|-----------------|
|0|0.5|
|1|62.5|
|2|125|
|3|250|
|4|500|
|5|1000|
|6|10|
|**7**|**20**|
|`IIR_filter`|Filter coefficient |
|-----|-----------------|
|0|Filter off|
|1|2|
|2|4|
|3|8|
|**4**|**16**|
#### Returns
`nil` if initialization has failed (no sensor connected?), `2` if sensor is BME280, `1` if sensor is BMP280
#### Example
```lua
alt=320 -- altitude of the measurement place
bme280.init(3, 4)
P, T = bme280.baro()
print(string.format("QFE=%d.%03d", P/1000, P%1000))
-- convert measure air pressure to sea level pressure
QNH = bme280.qfe2qnh(P, alt)
print(string.format("QNH=%d.%03d", QNH/1000, QNH%1000))
H, T = bme280.humi()
print(string.format("T=%d.%02d", T/100, T%100))
print(string.format("humidity=%d.%03d%%", H/1000, H%1000))
D = bme280.dewpoint(H, T)
print(string.format("dew_point=%d.%02d", D/100, D%100))
-- altimeter function - calculate altitude based on current sea level pressure (QNH) and measure pressure
P = bme280.baro()
curAlt = bme280.altitude(P, QNH)
print(string.format("altitude=%d.%02d", curAlt/100, curAlt%100))
```
Use `bme280.init(sda, scl, 1, 3, 0, 3, 0, 4)` for "game mode" - Oversampling settings pressure ×4, temperature ×1, humidity ×0, sensor mode: normal mode, inactive duration = 0.5 ms, IIR filter settings filter coefficient 16.
Example of readout in forced mode (asynchronous)
```lua
bme280.init(3, 4, nil, nil, nil, 0) -- initialize to sleep mode
bme280.startreadout(0, function ()
T = bme280.temp()
print(string.format("T=%d.%02d", T/100, T%100))
end)
```
## bme280.qfe2qnh()
For given altitude converts the air pressure to sea level air pressure.
#### Syntax
`bme280.qfe2qnh(P, altitude)`
#### Parameters
- `P` measured pressure
- `altitude` altitude in meters of measurement point
#### Returns
sea level pressure
## bme280.startreadout()
Starts readout (turns the sensor into forced mode). After the readout the sensor turns to sleep mode.
#### Syntax
`bme280.startreadout(delay, callback)`
#### Parameters
- `delay` sets sensor to forced mode and calls the `callback` (if provided) after given number of milliseconds. For 0 the default delay is set to 113ms (sufficient time to perform reading for oversampling settings 16x). For different oversampling setting please refer to [BME280 Final Datasheet - Appendix B: Measurement time and current calculation](http://ae-bst.resource.bosch.com/media/_tech/media/datasheets/BST-BME280_DS001-11.pdf#page=51).
- `callback` if provided it will be invoked after given `delay`. The sensor reading should be finalized by then so.
#### Returns
`nil`
## bme280.temp()
Reads the sensor and returns the temperature in celsius as an integer multiplied with 100.
#### Syntax
`bme280.temp()`
#### Parameters
none
#### Returns
- `T` temperature in celsius as an integer multiplied with 100 or `nil` when readout is not successful
- `t_fine` temperature measure used in pressure and humidity compensation formulas (generally no need to use this value)
\ No newline at end of file
# BMP085 Module
| Since | Origin / Contributor | Maintainer | Source |
| :----- | :-------------------- | :---------- | :------ |
| 2015-08-03 | [Konrad Beckmann](https://github.com/kbeckmann) | [Konrad Beckmann](https://github.com/kbeckmann) | [bmp085.c](../../../app/modules/bmp085.c)|
This module provides access to the [BMP085](https://www.sparkfun.com/tutorials/253) temperature and pressure sensor. The module also works with BMP180.
## bmp085.init()
Initializes the module and sets the pin configuration.
#### Syntax
`bmp085.init(sda, scl)`
#### Parameters
- `sda` data pin
- `scl` clock pin
#### Returns
`nil`
## bmp085.temperature()
Samples the sensor and returns the temperature in celsius as an integer multiplied with 10.
#### Syntax
`bmp085.temperature()`
#### Returns
temperature multiplied with 10 (integer)
#### Example
```lua
bmp085.init(1, 2)
local t = bmp085.temperature()
print(string.format("Temperature: %s.%s degrees C", t / 10, t % 10))
```
## bmp085.pressure()
Samples the sensor and returns the pressure in pascal as an integer.
The optional `oversampling_setting` parameter determines for how long time the sensor samples data.
The default is `3` which is the longest sampling setting. Possible values are 0, 1, 2, 3.
See the data sheet for more information.
#### Syntax
`bmp085.pressure(oversampling_setting)`
#### Parameters
`oversampling_setting` integer that can be 0, 1, 2 or 3
#### Returns
pressure in pascals (integer)
#### Example
```lua
bmp085.init(1, 2)
local p = bmp085.pressure()
print(string.format("Pressure: %s.%s mbar", p / 100, p % 100))
```
## bmp085.pressure_raw()
Samples the sensor and returns the raw pressure in internal units. Might be useful if you need higher precision.
#### Syntax
`bmp085.pressure_raw(oversampling_setting)`
#### Parameters
`oversampling_setting` integer that can be 0, 1, 2 or 3
#### Returns
raw pressure sampling value (integer)
# CJSON Module
| Since | Origin / Contributor | Maintainer | Source |
| :----- | :-------------------- | :---------- | :------ |
| 2015-03-16 | [Mark Pulford](http://kyne.com.au/~mark/software/lua-cjson.php), [Zeroday](https://github.com/funshine) | [Zeroday](https://github.com/funshine) | [cjson](../../../app/modules/cjson.c) |
The JSON support module. Allows encoding and decoding to/from JSON.
Please note that nested tables can require a lot of memory to encode. To catch out-of-memory errors, use `pcall()`.
## cjson.encode()
Encode a Lua table to a JSON string. For details see the [documentation of the original Lua library](http://kyne.com.au/~mark/software/lua-cjson-manual.html#encode).
####Syntax
`cjson.encode(table)`
####Parameters
`table` data to encode
While it also is possible to encode plain strings and numbers rather than a table, it is not particularly useful to do so.
####Returns
JSON string
####Example
```lua
ok, json = pcall(cjson.encode, {key="value"})
if ok then
print(json)
else
print("failed to encode!")
end
```
## cjson.decode()
Decode a JSON string to a Lua table. For details see the [documentation of the original Lua library](http://kyne.com.au/~mark/software/lua-cjson-manual.html#_decode).
####Syntax
`cjson.decode(str)`
####Parameters
`str` JSON string to decode
####Returns
Lua table representation of the JSON data
####Example
```lua
t = cjson.decode('{"key":"value"}')
for k,v in pairs(t) do print(k,v) end
```
# CoAP Module
| Since | Origin / Contributor | Maintainer | Source |
| :----- | :-------------------- | :---------- | :------ |
| 2015-02-04 | Toby Jaffey <toby@1248.io>, [Zeroday](https://github.com/funshine) | [Zeroday](https://github.com/funshine) | [coap.c](../../../app/modules/coap.c) |
The CoAP module provides a simple implementation according to [CoAP](http://tools.ietf.org/html/rfc7252) protocol.
The basic endpoint server part is based on [microcoap](https://github.com/1248/microcoap), and many other code reference [libcoap](https://github.com/obgm/libcoap).
This module implements both the client and the server side. GET/PUT/POST/DELETE is partially supported by the client. Server can register Lua functions and varibles. No observe or discover supported yet.
## Caution
This module is only in the very early stage and not complete yet.
## Constants
Constants for various functions.
`coap.CON`, `coap.NON` represent the request types.
`coap.TEXT_PLAIN`, `coap.LINKFORMAT`, `coap.XML`, `coap.OCTET_STREAM`, `coap.EXI`, `coap.JSON` represent content types.
## coap.Client()
Creates a CoAP client.
#### Syntax
`coap.Client()`
#### Parameters
none
#### Returns
CoAP client
#### Example
```lua
cc = coap.Client()
-- assume there is a coap server at ip 192.168.100
cc:get(coap.CON, "coap://192.168.18.100:5683/.well-known/core")
-- GET is not complete, the result/payload only print out in console.
cc:post(coap.NON, "coap://192.168.18.100:5683/", "Hello")
```
## coap.Server()
Creates a CoAP server.
#### Syntax
`coap.Server()`
#### Parameters
none
#### Returns
CoAP server
#### Example
```lua
-- use copper addon for firefox
cs=coap.Server()
cs:listen(5683)
myvar=1
cs:var("myvar") -- get coap://192.168.18.103:5683/v1/v/myvar will return the value of myvar: 1
all='[1,2,3]'
cs:var("all", coap.JSON) -- sets content type to json
-- function should tack one string, return one string.
function myfun(payload)
print("myfun called")
respond = "hello"
return respond
end
cs:func("myfun") -- post coap://192.168.18.103:5683/v1/f/myfun will call myfun
```
# CoAP Client
## coap.client:get()
Issues a GET request to the server.
#### Syntax
`coap.client:get(type, uri[, payload])`
#### Parameters
- `type` `coap.CON`, `coap.NON`, defaults to CON. If the type is CON and request fails, the library retries four more times before giving up.
- `uri` the URI such as "coap://192.168.18.103:5683/v1/v/myvar", only IP addresses are supported i.e. no hostname resoltion.
- `payload` optional, the payload will be put in the payload section of the request.
#### Returns
`nil`
## coap.client:put()
Issues a PUT request to the server.
#### Syntax
`coap.client:put(type, uri[, payload])`
#### Parameters
- `type` `coap.CON`, `coap.NON`, defaults to CON. If the type is CON and request fails, the library retries four more times before giving up.
- `uri` the URI such as "coap://192.168.18.103:5683/v1/v/myvar", only IP addresses are supported i.e. no hostname resoltion.
- `payload` optional, the payload will be put in the payload section of the request.
#### Returns
`nil`
## coap.client:post()
Issues a POST request to the server.
#### Syntax
`coap.client:post(type, uri[, payload])`
#### Parameters
- `type` coap.CON, coap.NON, defaults to CON. when type is CON, and request failed, the request will retry another 4 times before giving up.
- `uri` the uri such as coap://192.168.18.103:5683/v1/v/myvar, only IP is supported.
- `payload` optional, the payload will be put in the payload section of the request.
#### Returns
`nil`
## coap.client:delete()
Issues a DELETE request to the server.
#### Syntax
`coap.client:delete(type, uri[, payload])`
#### Parameters
- `type` `coap.CON`, `coap.NON`, defaults to CON. If the type is CON and request fails, the library retries four more times before giving up.
- `uri` the URI such as "coap://192.168.18.103:5683/v1/v/myvar", only IP addresses are supported i.e. no hostname resoltion.
- `payload` optional, the payload will be put in the payload section of the request.
#### Returns
`nil`
# CoAP Server
## coap.server:listen()
Starts the CoAP server on the given port.
#### Syntax
`coap.server:listen(port[, ip])`
#### Parameters
- `port` server port (number)
- `ip` optional IP address
#### Returns
`nil`
## coap.server:close()
Closes the CoAP server.
#### Syntax
`coap.server:close()`
#### Parameters
none
#### Returns
`nil`
## coap.server:var()
Registers a Lua variable as an endpoint in the server. the variable value then can be retrieved by a client via GET method, represented as an [URI](http://tools.ietf.org/html/rfc7252#section-6) to the client. The endpoint path for varialble is '/v1/v/'.
#### Syntax
`coap.server:var(name[, content_type])`
#### Parameters
- `name` the Lua variable's name
- `content_type` optional, defaults to `coap.TEXT_PLAIN`, see [Content Negotiation](http://tools.ietf.org/html/rfc7252#section-5.5.4)
#### Returns
`nil`
#### Example
```lua
-- use copper addon for firefox
cs=coap.Server()
cs:listen(5683)
myvar=1
cs:var("myvar") -- get coap://192.168.18.103:5683/v1/v/myvar will return the value of myvar: 1
-- cs:var(myvar), WRONG, this api accept the name string of the varialbe. but not the variable itself.
all='[1,2,3]'
cs:var("all", coap.JSON) -- sets content type to json
```
## coap.server:func()
Registers a Lua function as an endpoint in the server. The function then can be called by a client via POST method. represented as an [URI](http://tools.ietf.org/html/rfc7252#section-6) to the client. The endpoint path for function is '/v1/f/'.
When the client issues a POST request to this URI, the payload will be passed to the function as parameter. The function's return value will be the payload in the message to the client.
The function registered SHOULD accept ONLY ONE string type parameter, and return ONE string value or return nothing.
#### Syntax
`coap.server:func(name[, content_type])`
#### Parameters
- `name` the Lua function's name
- `content_type` optional, defaults to `coap.TEXT_PLAIN`, see [Content Negotiation](http://tools.ietf.org/html/rfc7252#section-5.5.4)
#### Returns
`nil`
#### Example
```lua
-- use copper addon for firefox
cs=coap.Server()
cs:listen(5683)
-- function should take only one string, return one string.
function myfun(payload)
print("myfun called")
respond = "hello"
return respond
end
cs:func("myfun") -- post coap://192.168.18.103:5683/v1/f/myfun will call myfun
-- cs:func(myfun), WRONG, this api accept the name string of the function. but not the function itself.
```
# crypto Module
| Since | Origin / Contributor | Maintainer | Source |
| :----- | :-------------------- | :---------- | :------ |
| 2015-06-02 | [DiUS](https://github.com/DiUS), [Johny Mattsson](https://github.com/jmattsson) | [Johny Mattsson](https://github.com/jmattsson) | [crypto.c](../../../app/modules/crypto.c)|
The crypto modules provides various functions for working with cryptographic algorithms.
## crypto.encrypt()
Encrypts Lua strings.
#### Syntax
`crypto.encrypt(algo, key, plain [, iv])`
#### Parameters
- `algo` the name of the encryption algorithm to use, one of
- `"AES-ECB"` for 128-bit AES in ECB mode
- `"AES-CBC"` for 128-bit AES in CBC mode
- `key` the encryption key as a string; for AES encryption this *MUST* be 16 bytes long
- `plain` the string to encrypt; it will be automatically zero-padded to a 16-byte boundary if necessary
- `iv` the initilization vector, if using AES-CBC; defaults to all-zero if not given
#### Returns
The encrypted data as a binary string. For AES this is always a multiple of 16 bytes in length.
#### Example
```lua
print(crypto.toHex(crypto.encrypt("AES-ECB", "1234567890abcdef", "Hi, I'm secret!")))
```
#### See also
- [`crypto.decrypt()`](#cryptodecrypt)
## crypto.decrypt()
Decrypts previously encrypted data.
#### Syntax
`crypto.decrypt(algo, key, cipher [, iv])`
#### Parameters
- `algo` the name of the encryption algorithm to use, one of
- `"AES-ECB"` for 128-bit AES in ECB mode
- `"AES-CBC"` for 128-bit AES in CBC mode
- `key` the encryption key as a string; for AES encryption this *MUST* be 16 bytes long
- `cipher` the cipher text to decrypt (as obtained from `crypto.encrypt()`)
- `iv` the initilization vector, if using AES-CBC; defaults to all-zero if not given
#### Returns
The decrypted string.
Note that the decrypted string may contain extra zero-bytes of padding at the end. One way of stripping such padding is to use `:match("(.-)%z*$")` on the decrypted string. Additional care needs to be taken if working on binary data, in which case the real length likely needs to be encoded with the data, and at which point `:sub(1, n)` can be used to strip the padding.
#### Example
```lua
key = "1234567890abcdef"
cipher = crypto.encrypt("AES-ECB", key, "Hi, I'm secret!")
print(crypto.toHex(cipher))
print(crypto.decrypt("AES-ECB", key, cipher))
```
#### See also
- [`crypto.encrypt()`](#cryptoencrypt)
## crypto.fhash()
Compute a cryptographic hash of a a file.
#### Syntax
`hash = crypto.fhash(algo, filename)`
#### Parameters
- `algo` the hash algorithm to use, case insensitive string
- `filename` the path to the file to hash
Supported hash algorithms are:
- MD2 (not available by default, has to be explicitly enabled in `app/include/user_config.h`)
- MD5
- SHA1
- SHA256, SHA384, SHA512 (unless disabled in `app/include/user_config.h`)
#### Returns
A binary string containing the message digest. To obtain the textual version (ASCII hex characters), please use [`crypto.toHex()`](#cryptotohex ).
#### Example
```lua
print(crypto.toHex(crypto.fhash("sha1","myfile.lua")))
```
## crypto.hash()
Compute a cryptographic hash of a Lua string.
#### Syntax
`hash = crypto.hash(algo, str)`
#### Parameters
`algo` the hash algorithm to use, case insensitive string
`str` string to hash contents of
Supported hash algorithms are:
- MD2 (not available by default, has to be explicitly enabled in `app/include/user_config.h`)
- MD5
- SHA1
- SHA256, SHA384, SHA512 (unless disabled in `app/include/user_config.h`)
#### Returns
A binary string containing the message digest. To obtain the textual version (ASCII hex characters), please use [`crypto.toHex()`](#cryptotohex ).
#### Example
```lua
print(crypto.toHex(crypto.hash("sha1","abc")))
```
## crypto.new_hash()
Create a digest/hash object that can have any number of strings added to it. Object has `update` and `finalize` functions.
#### Syntax
`hashobj = crypto.new_hash(algo)`
#### Parameters
`algo` the hash algorithm to use, case insensitive string
Supported hash algorithms are:
- MD2 (not available by default, has to be explicitly enabled in `app/include/user_config.h`)
- MD5
- SHA1
- SHA256, SHA384, SHA512 (unless disabled in `app/include/user_config.h`)
#### Returns
Userdata object with `update` and `finalize` functions available.
#### Example
```lua
hashobj = crypto.new_hash("SHA1")
hashobj:update("FirstString"))
hashobj:update("SecondString"))
digest = hashobj:finalize()
print(crypto.toHex(digest))
```
## crypto.hmac()
Compute a [HMAC](https://en.wikipedia.org/wiki/Hash-based_message_authentication_code) (Hashed Message Authentication Code) signature for a Lua string.
#### Syntax
`signature = crypto.hmac(algo, str, key)`
#### Parameters
- `algo` hash algorithm to use, case insensitive string
- `str` data to calculate the hash for
- `key` key to use for signing, may be a binary string
Supported hash algorithms are:
- MD2 (not available by default, has to be explicitly enabled in `app/include/user_config.h`)
- MD5
- SHA1
- SHA256, SHA384, SHA512 (unless disabled in `app/include/user_config.h`)
#### Returns
A binary string containing the HMAC signature. Use [`crypto.toHex()`](#cryptotohex ) to obtain the textual version.
#### Example
```lua
print(crypto.toHex(crypto.hmac("sha1","abc","mysecret")))
```
## crypto.mask()
Applies an XOR mask to a Lua string. Note that this is not a proper cryptographic mechanism, but some protocols may use it nevertheless.
#### Syntax
`crypto.mask(message, mask)`
#### Parameters
- `message` message to mask
- `mask` the mask to apply, repeated if shorter than the message
#### Returns
The masked message, as a binary string. Use [`crypto.toHex()`](#cryptotohex) to get a textual representation of it.
#### Example
```lua
print(crypto.toHex(crypto.mask("some message to obscure","X0Y7")))
```
## crypto.toBase64()
Provides a Base64 representation of a (binary) Lua string.
#### Syntax
`b64 = crypto.toBase64(binary)`
#### Parameters
`binary` input string to Base64 encode
#### Return
A Base64 encoded string.
#### Example
```lua
print(crypto.toBase64(crypto.hash("sha1","abc")))
```
## crypto.toHex()
Provides an ASCII hex representation of a (binary) Lua string. Each byte in the input string is represented as two hex characters in the output.
#### Syntax
`hexstr = crypto.toHex(binary)`
#### Parameters
`binary` input string to get hex representation for
#### Returns
An ASCII hex string.
#### Example
```lua
print(crypto.toHex(crypto.hash("sha1","abc")))
```
# DHT Module
| Since | Origin / Contributor | Maintainer | Source |
| :----- | :-------------------- | :---------- | :------ |
| 2015-06-17 | [RobTillaart](https://github.com/RobTillaart/Arduino/tree/master/libraries/DHTlib) | [Vowstar](https://github.com/vowstar) | [dhtlib](../../../app/dhtlib/)|
## Constants
Constants for various functions.
`dht.OK`, `dht.ERROR_CHECKSUM`, `dht.ERROR_TIMEOUT` represent the potential values for the DHT read status
## dht.read()
Read all kinds of DHT sensors, including DHT11, 21, 22, 33, 44 humidity temperature combo sensor.
#### Syntax
`dht.read(pin)`
#### Parameters
`pin` pin number of DHT sensor (can't be 0), type is number
#### Returns
- `status` as defined in Constants
- `temp` temperature (see note below)
- `humi` humidity (see note below)
- `temp_dec` temperature decimal
- `humi_dec` humidity decimal
!!! note "Note:"
If using float firmware then `temp` and `humi` are floating point numbers. On an integer firmware, the final values have to be concatenated from `temp` and `temp_dec` / `humi` and `hum_dec`.
#### Example
```lua
pin = 5
status, temp, humi, temp_dec, humi_dec = dht.read(pin)
if status == dht.OK then
-- Integer firmware using this example
print(string.format("DHT Temperature:%d.%03d;Humidity:%d.%03d\r\n",
math.floor(temp),
temp_dec,
math.floor(humi),
humi_dec
))
-- Float firmware using this example
print("DHT Temperature:"..temp..";".."Humidity:"..humi)
elseif status == dht.ERROR_CHECKSUM then
print( "DHT Checksum error." )
elseif status == dht.ERROR_TIMEOUT then
print( "DHT timed out." )
end
```
## dht.read11()
Read DHT11 humidity temperature combo sensor.
#### Syntax
`dht.read11(pin)`
#### Parameters
`pin` pin number of DHT11 sensor (can't be 0), type is number
#### Returns
- `status` as defined in Constants
- `temp` temperature (see note below)
- `humi` humidity (see note below)
- `temp_dec` temperature decimal
- `humi_dec` humidity decimal
!!! note "Note:"
If using float firmware then `temp` and `humi` are floating point numbers. On an integer firmware, the final values have to be concatenated from `temp` and `temp_dec` / `humi` and `hum_dec`.
#### See also
[dht.read()](#dhtread)
## dht.readxx()
Read all kinds of DHT sensors, except DHT11.
####Syntax
`dht.readxx(pin)`
#### Parameters
`pin` pin number of DHT sensor (can't be 0), type is number
#### Returns
- `status` as defined in Constants
- `temp` temperature (see note below)
- `humi` humidity (see note below)
- `temp_dec` temperature decimal
- `humi_dec` humidity decimal
!!! note "Note:"
If using float firmware then `temp` and `humi` are floating point numbers. On an integer firmware, the final values have to be concatenated from `temp` and `temp_dec` / `humi` and `hum_dec`.
#### See also
[dht.read()](#dhtread)
# encoder Module
| Since | Origin / Contributor | Maintainer | Source |
| :----- | :-------------------- | :---------- | :------ |
| 2016-02-26 | [Terry Ellison](https://github.com/TerryE) | [Terry Ellison](https://github.com/TerryE) | [encoder.c](../../../app/modules/encoder.c)|
The encoder modules provides various functions for encoding and decoding byte data.
## encoder.toBase64()
Provides a Base64 representation of a (binary) Lua string.
#### Syntax
`b64 = encoder.toBase64(binary)`
#### Parameters
`binary` input string to Base64 encode
#### Return
A Base64 encoded string.
#### Example
```lua
print(encoder.toBase64(crypto.hash("sha1","abc")))
```
## encoder.fromBase64()
Decodes a Base64 representation of a (binary) Lua string back into the original string. An error is
thrown if the string is not a valid base64 encoding.
#### Syntax
`binary_string = encoder.toBase64(b64)`
#### Parameters
`b64` Base64 encoded input string
#### Return
The decoded Lua (binary) string.
#### Example
```lua
print(encoder.fromBase64(encoder.toBase64("hello world")))
```
## encoder.toHex()
Provides an ASCII hex representation of a (binary) Lua string. Each byte in the input string is
represented as two hex characters in the output.
#### Syntax
`hexstr = encoder.toHex(binary)`
#### Parameters
`binary` input string to get hex representation for
#### Returns
An ASCII hex string.
#### Example
```lua
print(encoder.toHex(crypto.hash("sha1","abc")))
```
## encoder.fromHex()
Returns the Lua binary string decode of a ASCII hex string. Each byte in the output string is
represented as two hex characters in the input. An error is thrown if the string is not a
valid base64 encoding.
#### Syntax
`binary = encoder.fromHex(hexstr)`
#### Parameters
`hexstr` An ASCII hex string.
#### Returns
Decoded string of hex representation.
#### Example
```lua
print(encoder.fromHex("6a6a6a")))
```
# enduser setup Module
| Since | Origin / Contributor | Maintainer | Source |
| :----- | :-------------------- | :---------- | :------ |
| 2015-09-02 | [Robert Foss](https://github.com/robertfoss) | [Robert Foss](https://github.com/robertfoss) | [enduser_setup.c](../../../app/modules/enduser_setup.c)|
This module provides a simple way of configuring ESP8266 chips without using a serial interface or pre-programming WiFi credentials onto the chip.
![enduser setup config dialog](../../img/enduser-setup.jpg "enduser setup config dialog")
After running [`enduser_setup.start()`](#enduser_setupstart) a portal like the above can be accessed through a wireless network called SetupGadget_XXXXXX. The portal is used to submit the credentials for the WiFi of the enduser.
After an IP address has been successfully obtained this module will stop as if [`enduser_setup.stop()`](#enduser_setupstop) had been called.
Alternative HTML can be served by placing a file called `enduser_setup.html` in the filesystem. This file will be kept in RAM, so keep it as small as possible.
## enduser_setup.manual()
Controls whether manual AP configuration is used.
By default the `enduser_setup` module automatically configures an open access point when starting, and stops it when the device has been successfully joined to a WiFi network. If manual mode has been enabled, neither of this is done. The device must be manually configured for `wifi.SOFTAP` mode prior to calling `enduser_setup.start()`. Additionally, the portal is not stopped after the device has successfully joined to a WiFi network.
#### Syntax
`enduser_setup.manual([on_off])`
#### Parameters
- `on_off` a boolean value indicating whether to use manual mode; if not given, the function only returns the current setting.
#### Returns
The current setting, true if manual mode is enabled, false if it is not.
#### Example
```lua
wifi.setmode(wifi.STATIONAP)
wifi.ap.config({ssid="MyPersonalSSID",auth=wifi.AUTH_OPEN})
enduser_setup.manual(true)
enduser_setup.start(
function()
print("Connected to wifi as:" .. wifi.sta.getip())
end,
function(err, str)
print("enduser_setup: Err #" .. err .. ": " .. str)
end
);
```
## enduser_setup.start()
Starts the captive portal.
#### Syntax
`enduser_setup.start([onConnected()], [onError(err_num, string)], [onDebug(string)])`
#### Parameters
- `onConnected()` callback will be fired when an IP-address has been obtained, just before the enduser_setup module will terminate itself
- `onError()` callback will be fired if an error is encountered. `err_num` is a number describing the error, and `string` contains a description of the error.
- `onDebug()` callback is disabled by default. It is intended to be used to find internal issues in the module. `string` contains a description of what is going on.
#### Returns
`nil`
#### Example
```lua
enduser_setup.start(
function()
print("Connected to wifi as:" .. wifi.sta.getip())
end,
function(err, str)
print("enduser_setup: Err #" .. err .. ": " .. str)
end
);
```
## enduser_setup.stop()
Stops the captive portal.
#### Syntax
`enduser_setup.stop()`
#### Parameters
none
#### Returns
`nil`
# file Module
| Since | Origin / Contributor | Maintainer | Source |
| :----- | :-------------------- | :---------- | :------ |
| 2014-12-22 | [Zeroday](https://github.com/funshine) | [Zeroday](https://github.com/funshine) | [file.c](../../../app/modules/file.c)|
The file module provides access to the file system and its individual files.
The file system is a flat file system, with no notion of directories/folders.
Only one file can be open at any given time.
## file.close()
Closes the open file, if any.
#### Syntax
`file.close()`
#### Parameters
none
#### Returns
`nil`
#### Example
```lua
-- open 'init.lua', print the first line.
file.open("init.lua", "r")
print(file.readline())
file.close()
```
#### See also
[`file.open()`](#fileopen)
## file.exists()
Determines whether the specified file exists.
#### Syntax
`file.exists(filename)`
#### Parameters
- `filename` file to check
#### Returns
true of the file exists (even if 0 bytes in size), and false if it does not exist
#### Example
```lua
files = file.list()
if files["device.config"] then
print("Config file exists")
end
if file.exists("device.config") then
print("Config file exists")
end
```
#### See also
[`file.list()`](#filelist)
## file.flush()
Flushes any pending writes to the file system, ensuring no data is lost on a restart. Closing the open file using [`file.close()`](#fileclose) performs an implicit flush as well.
#### Syntax
`file.flush()`
#### Parameters
none
#### Returns
`nil`
#### Example
```lua
-- open 'init.lua' in 'a+' mode
file.open("init.lua", "a+")
-- write 'foo bar' to the end of the file
file.write('foo bar')
file.flush()
-- write 'baz' too
file.write('baz')
file.close()
```
#### See also
[`file.close()`](#fileclose)
## file.format()
Format the file system. Completely erases any existing file system and writes a new one. Depending on the size of the flash chip in the ESP, this may take several seconds.
#### Syntax
`file.format()`
#### Parameters
none
#### Returns
`nil`
#### See also
[`file.remove()`](#fileremove)
## file.fscfg ()
Returns the flash address and physical size of the file system area, in bytes.
#### Syntax
`file.fscfg()`
#### Parameters
none
#### Returns
- `flash address` (number)
- `size` (number)
#### Example
```lua
print(string.format("0x%x", file.fscfg()))
```
## file.fsinfo()
Return size information for the file system, in bytes.
#### Syntax
`file.fsinfo()`
#### Parameters
none
#### Returns
- `remaining` (number)
- `used` (number)
- `total` (number)
#### Example
```lua
-- get file system info
remaining, used, total=file.fsinfo()
print("\nFile system info:\nTotal : "..total.." Bytes\nUsed : "..used.." Bytes\nRemain: "..remaining.." Bytes\n")
```
## file.list()
Lists all files in the file system.
#### Syntax
`file.list()`
#### Parameters
none
#### Returns
a lua table which contains the {file name: file size} pairs
#### Example
```lua
l = file.list();
for k,v in pairs(l) do
print("name:"..k..", size:"..v)
end
```
## file.open()
Opens a file for access, potentially creating it (for write modes).
When done with the file, it must be closed using `file.close()`.
#### Syntax
`file.open(filename, mode)`
#### Parameters
- `filename` file to be opened, directories are not supported
- `mode`:
- "r": read mode (the default)
- "w": write mode
- "a": append mode
- "r+": update mode, all previous data is preserved
- "w+": update mode, all previous data is erased
- "a+": append update mode, previous data is preserved, writing is only allowed at the end of file
#### Returns
`nil` if file not opened, or not exists (read modes). `true` if file opened ok.
#### Example
```lua
-- open 'init.lua', print the first line.
file.open("init.lua", "r")
print(file.readline())
file.close()
```
#### See also
- [`file.close()`](#fileclose)
- [`file.readline()`](#filereadline)
## file.read()
Read content from the open file.
#### Syntax
`file.read([n_or_str])`
#### Parameters
- `n_or_str`:
- if nothing passed in, read up to `LUAL_BUFFERSIZE` bytes (default 1024) or the entire file (whichever is smaller)
- if passed a number n, then read the file until the lesser of `n` bytes, `LUAL_BUFFERSIZE` bytes, or EOF is reached. Specifying a number larger than the buffer size will read the buffer size.
- if passed a string `str`, then read until `str` appears next in the file, `LUAL_BUFFERSIZE` bytes have been read, or EOF is reached
#### Returns
File content as a string, or nil when EOF
#### Example
```lua
-- print the first line of 'init.lua'
file.open("init.lua", "r")
print(file.read('\n'))
file.close()
-- print the first 5 bytes of 'init.lua'
file.open("init.lua", "r")
print(file.read(5))
file.close()
```
#### See also
- [`file.open()`](#fileopen)
- [`file.readline()`](#filereadline)
## file.readline()
Read the next line from the open file. Lines are defined as zero or more bytes ending with a EOL ('\n') byte. If the next line is longer than `LUAL_BUFFERSIZE`, this function only returns the first `LUAL_BUFFERSIZE` bytes (this is 1024 bytes by default).
#### Syntax
`file.readline()`
#### Parameters
none
#### Returns
File content in string, line by line, including EOL('\n'). Return `nil` when EOF.
#### Example
```lua
-- print the first line of 'init.lua'
file.open("init.lua", "r")
print(file.readline())
file.close()
```
#### See also
- [`file.open()`](#fileopen)
- [`file.close()`](#fileclose)
- [`file.read()`](#filereade)
## file.remove()
Remove a file from the file system. The file must not be currently open.
###Syntax
`file.remove(filename)`
#### Parameters
`filename` file to remove
#### Returns
`nil`
#### Example
```lua
-- remove "foo.lua" from file system.
file.remove("foo.lua")
```
#### See also
[`file.open()`](#fileopen)
## file.rename()
Renames a file. If a file is currently open, it will be closed first.
#### Syntax
`file.rename(oldname, newname)`
#### Parameters
- `oldname` old file name
- `newname` new file name
#### Returns
`true` on success, `false` on error.
#### Example
```lua
-- rename file 'temp.lua' to 'init.lua'.
file.rename("temp.lua","init.lua")
```
## file.seek()
Sets and gets the file position, measured from the beginning of the file, to the position given by offset plus a base specified by the string whence.
#### Syntax
`file.seek([whence [, offset]])`
#### Parameters
- `whence`
- "set": base is position 0 (beginning of the file)
- "cur": base is current position (default value)
- "end": base is end of file
- `offset` default 0
If no parameters are given, the function simply returns the current file offset.
#### Returns
the resulting file position, or `nil` on error
#### Example
```lua
file.open("init.lua", "r")
-- skip the first 5 bytes of the file
file.seek("set", 5)
print(file.readline())
file.close()
```
#### See also
[`file.open()`](#fileopen)
## file.write()
Write a string to the open file.
#### Syntax
`file.write(string)`
#### Parameters
`string` content to be write to file
#### Returns
`true` if the write is ok, `nil` on error
#### Example
```lua
-- open 'init.lua' in 'a+' mode
file.open("init.lua", "a+")
-- write 'foo bar' to the end of the file
file.write('foo bar')
file.close()
```
#### See also
- [`file.open()`](#fileopen)
- [`file.writeline()`](#filewriteline)
## file.writeline()
Write a string to the open file and append '\n' at the end.
#### Syntax
`file.writeline(string)`
#### Parameters
`string` content to be write to file
#### Returns
`true` if write ok, `nil` on error
#### Example
```lua
-- open 'init.lua' in 'a+' mode
file.open("init.lua", "a+")
-- write 'foo bar' to the end of the file
file.writeline('foo bar')
file.close()
```
#### See also
- [`file.open()`](#fileopen)
- [`file.readline()`](#filereadline)
# GPIO Module
| Since | Origin / Contributor | Maintainer | Source |
| :----- | :-------------------- | :---------- | :------ |
| 2014-12-22 | [Zeroday](https://github.com/funshine) | [Zeroday](https://github.com/funshine) | [gpio.c](../../../app/modules/gpio.c)|
This module provides access to the [GPIO](https://en.wikipedia.org/wiki/General-purpose_input/output) (General Purpose Input/Output) subsystem.
All access is based on the I/O index number on the NodeMCU dev kits, not the internal GPIO pin. For example, the D0 pin on the dev kit is mapped to the internal GPIO pin 16.
If not using a NodeMCU dev kit, please refer to the below GPIO pin maps for the index↔gpio mapping.
| IO index | ESP8266 pin | IO index | ESP8266 pin |
|---------:|:------------|---------:|:------------|
| 0 [*] | GPIO16 | 7 | GPIO13 |
| 1 | GPIO5 | 8 | GPIO15 |
| 2 | GPIO4 | 9 | GPIO3 |
| 3 | GPIO0 | 10 | GPIO1 |
| 4 | GPIO2 | 11 | GPIO9 |
| 5 | GPIO14 | 12 | GPIO10 |
| 6 | GPIO12 | | |
** [*] D0(GPIO16) can only be used as gpio read/write. No support for open-drain/interrupt/pwm/i2c/ow. **
## gpio.mode()
Initialize pin to GPIO mode, set the pin in/out direction, and optional internal weak pull-up.
#### Syntax
`gpio.mode(pin, mode [, pullup])`
#### Parameters
- `pin` pin to configure, IO index
- `mode` one of gpio.OUTPUT, gpio.OPENDRAIN, gpio.INPUT, or gpio.INT (interrupt mode)
- `pullup` gpio.PULLUP enables the weak pull-up resistor; default is gpio.FLOAT
#### Returns
`nil`
#### Example
```lua
gpio.mode(0, gpio.OUTPUT)
```
#### See also
- [`gpio.read()`](#gpioread)
- [`gpio.write()`](#gpiowrite)
## gpio.read()
Read digital GPIO pin value.
#### Syntax
`gpio.read(pin)`
#### Parameters
`pin` pin to read, IO index
#### Returns
a number, 0 = low, 1 = high
#### Example
```lua
-- read value of gpio 0.
gpio.read(0)
```
#### See also
[`gpio.mode()`](#gpiomode)
## gpio.serout()
Serialize output based on a sequence of delay-times. After each delay, the pin is toggled.
#### Syntax
`gpio.serout(pin, start_level, delay_times [, repeat_num])`
#### Parameters
- `pin` pin to use, IO index
- `start_level` level to start on, either `gpio.HIGH` or `gpio.LOW`
- `delay_times` an array of delay times between each toggle of the gpio pin.
- `repeat_num` an optional number of times to run through the sequence.
Note that this function blocks, and as such any use of it must adhere to the SDK guidelines of time spent blocking the stack (10-100ms). Failure to do so may lead to WiFi issues or outright crashes/reboots.
#### Returns
`nil`
#### Example
```lua
gpio.mode(1,gpio.OUTPUT,gpio.PULLUP)
gpio.serout(1,1,{30,30,60,60,30,30}) -- serial one byte, b10110010
gpio.serout(1,1,{30,70},8) -- serial 30% pwm 10k, lasts 8 cycles
gpio.serout(1,1,{3,7},8) -- serial 30% pwm 100k, lasts 8 cycles
gpio.serout(1,1,{0,0},8) -- serial 50% pwm as fast as possible, lasts 8 cycles
gpio.serout(1,0,{20,10,10,20,10,10,10,100}) -- sim uart one byte 0x5A at about 100kbps
gpio.serout(1,1,{8,18},8) -- serial 30% pwm 38k, lasts 8 cycles
```
## gpio.trig()
Establish or clear a callback function to run on interrupt for a pin.
This function is not available if GPIO_INTERRUPT_ENABLE was undefined at compile time.
#### Syntax
`gpio.trig(pin, [type [, callback_function]])`
#### Parameters
- `pin` **1-12**, pin to trigger on, IO index. Note that pin 0 does not support interrupts.
- `type` "up", "down", "both", "low", "high", which represent *rising edge*, *falling edge*, *both
edges*, *low level*, and *high level* trigger modes respectivey. If the type is "none" or omitted
then the callback function is removed and the interrupt is disabled.
- `callback_function(level)` callback function when trigger occurs. The level of the specified pin
at the interrupt passed as the parameter to the callback. The previous callback function will be
used if the function is omitted.
#### Returns
`nil`
#### Example
```lua
do
-- use pin 1 as the input pulse width counter
local pin, pulse1, du, now, trig = 1, 0, 0, tmr.now, gpio.trig
gpio.mode(pin,gpio.INT)
local function pin1cb(level)
local pulse2 = now()
print( level, pulse2 - pulse1 )
pulse1 = pulse2
trig(pin, level == gpio.HIGH and "down" or "up")
end
trig(pin, "down", pin1cb)
end
```
#### See also
[`gpio.mode()`](#gpiomode)
## gpio.write()
Set digital GPIO pin value.
#### Syntax
`gpio.write(pin, level)`
#### Parameters
- `pin` pin to write, IO index
- `level` `gpio.HIGH` or `gpio.LOW`
#### Returns
`nil`
#### Example
```lua
-- set pin index 1 to GPIO mode, and set the pin to high.
pin=1
gpio.mode(pin, gpio.OUTPUT)
gpio.write(pin, gpio.HIGH)
```
#### See also
- [`gpio.mode()`](#gpiomode)
- [`gpio.read()`](#gpioread)
# HTTP Module
| Since | Origin / Contributor | Maintainer | Source |
| :----- | :-------------------- | :---------- | :------ |
| 2016-01-15 | [esphttpclient](https://github.com/Caerbannog/esphttpclient) / [Vowstar](https://github.com/vowstar) | [Vowstar](https://github.com/vowstar) | [http.c](../../../app/modules/http.c)|
Basic HTTP *client* module that provides an interface to do GET/POST/PUT/DELETE over HTTP(S), as well as customized requests. Due to the memory constraints on ESP8266, the supported page/body size is limited by available memory. Attempting to receive pages larger than this will fail. If larger page/body sizes are necessary, consider using [`net.createConnection()`](net.md#netcreateconnection) and stream in the data.
!!! note "Note:"
It is **not** possible to execute concurrent HTTP requests using this module. Starting a new request before the previous has completed will result in undefined behavior.
Each request method takes a callback which is invoked when the response has been received from the server. The first argument is the status code, which is either a regular HTTP status code, or -1 to denote a DNS, connection or out-of-memory failure, or a timeout (currently at 10 seconds).
For each operation it is also possible to include custom headers. Note that following headers *can not* be overridden however:
- Host
- Connection
- User-Agent
The `Host` header is taken from the URL itself, the `Connection` is always set to `close`, and the `User-Agent` is `ESP8266`.
**SSL/TLS support**
Take note of constraints documented in the [net module](net.md).
## http.delete()
Executes a HTTP DELETE request. Note that concurrent requests are not supported.
#### Syntax
`http.delete(url, headers, body, callback)`
#### Parameters
- `url` The URL to fetch, including the `http://` or `https://` prefix
- `headers` Optional additional headers to append, *including \r\n*; may be `nil`
- `body` The body to post; must already be encoded in the appropriate format, but may be empty
- `callback` The callback function to be invoked when the response has been received; it is invoked with the arguments `status_code` and `body`
#### Returns
`nil`
#### Example
```lua
http.delete('http://httpbin.org/delete',
"",
"",
function(code, data)
if (code < 0) then
print("HTTP request failed")
else
print(code, data)
end
end)
```
## http.get()
Executes a HTTP GET request. Note that concurrent requests are not supported.
#### Syntax
`http.get(url, headers, callback)`
#### Parameters
- `url` The URL to fetch, including the `http://` or `https://` prefix
- `headers` Optional additional headers to append, *including \r\n*; may be `nil`
- `callback` The callback function to be invoked when the response has been received; it is invoked with the arguments `status_code` and `body`
#### Returns
`nil`
#### Example
```lua
http.get("http://httpbin.org/ip", nil, function(code, data)
if (code < 0) then
print("HTTP request failed")
else
print(code, data)
end
end)
```
## http.post()
Executes a HTTP POST request. Note that concurrent requests are not supported.
#### Syntax
`http.post(url, headers, body, callback)`
#### Parameters
- `url` The URL to fetch, including the `http://` or `https://` prefix
- `headers` Optional additional headers to append, *including \r\n*; may be `nil`
- `body` The body to post; must already be encoded in the appropriate format, but may be empty
- `callback` The callback function to be invoked when the response has been received; it is invoked with the arguments `status_code` and `body`
#### Returns
`nil`
#### Example
```lua
http.post('http://httpbin.org/post',
'Content-Type: application/json\r\n',
'{"hello":"world"}',
function(code, data)
if (code < 0) then
print("HTTP request failed")
else
print(code, data)
end
end)
```
## http.put()
Executes a HTTP PUT request. Note that concurrent requests are not supported.
#### Syntax
`http.put(url, headers, body, callback)`
#### Parameters
- `url` The URL to fetch, including the `http://` or `https://` prefix
- `headers` Optional additional headers to append, *including \r\n*; may be `nil`
- `body` The body to post; must already be encoded in the appropriate format, but may be empty
- `callback` The callback function to be invoked when the response has been received; it is invoked with the arguments `status_code` and `body`
#### Returns
`nil`
#### Example
```lua
http.put('http://httpbin.org/put',
'Content-Type: text/plain\r\n',
'Hello!\nStay a while, and listen...\n',
function(code, data)
if (code < 0) then
print("HTTP request failed")
else
print(code, data)
end
end)
```
## http.request()
Execute a custom HTTP request for any HTTP method. Note that concurrent requests are not supported.
#### Syntax
`http.request(url, method, headers, body, callback)`
#### Parameters
- `url` The URL to fetch, including the `http://` or `https://` prefix
- `method` The HTTP method to use, e.g. "GET", "HEAD", "OPTIONS" etc
- `headers` Optional additional headers to append, *including \r\n*; may be `nil`
- `body` The body to post; must already be encoded in the appropriate format, but may be empty
- `callback` The callback function to be invoked when the response has been received; it is invoked with the arguments `status_code` and `body`
#### Returns
`nil`
#### Example
```lua
http.request("http://httpbin.org", "HEAD", "", "",
function(code, data)
if (code < 0) then
print("HTTP request failed")
else
print(code, data)
end
end)
```
# HX711 Module
| Since | Origin / Contributor | Maintainer | Source |
| :----- | :-------------------- | :---------- | :------ |
| 2015-10-09 | [Chris Takahashi](https://github.com/christakahashi) | [Chris Takahashi](https://github.com/christakahashi) | [hx711.c](../../../app/modules/hx711.c)|
This module provides access to an [HX711 load cell amplifier/ADC](https://learn.sparkfun.com/tutorials/load-cell-amplifier-hx711-breakout-hookup-guide). The HX711 is an inexpensive 24bit ADC with programmable 128x, 64x, and 32x gain. Currently only channel A at 128x gain is supported.
Note: To save ROM image space, this module is not compiled into the firmware by default.
## hx711.init()
Initialize io pins for hx711 clock and data.
#### Syntax
`hx711.init(clk, data)`
#### Parameters
- `clk` pin the hx711 clock signal is connected to
- `data` pin the hx711 data signal is connected to
#### Returns
`nil`
#### Example
```lua
-- Initialize the hx711 with clk on pin 5 and data on pin 6
hx711.init(5,6)
```
## hx711.read()
Read digital loadcell ADC value.
#### Syntax
`hx711.read(mode)`
#### Parameters
`mode` ADC mode. This parameter is currently ignored and reserved to ensure backward compatability if support for additional modes is added. Currently only channel A @ 128 gain is supported.
|mode | channel | gain |
|-----|---------|------|
| 0 | A | 128 |
#### Returns
a number (24 bit signed ADC value extended to the machine int size)
#### Example
```lua
-- Read ch A with 128 gain.
raw_data = hx711.read(0)
```
# I²C Module
| Since | Origin / Contributor | Maintainer | Source |
| :----- | :-------------------- | :---------- | :------ |
| 2014-12-22 | [Zeroday](https://github.com/funshine) | [Zeroday](https://github.com/funshine) | [i2c.c](../../../app/modules/i2c.c)|
## i2c.address()
Setup I²C address and read/write mode for the next transfer.
#### Syntax
`i2c.address(id, device_addr, direction)`
#### Parameters
- `id` always 0
- `device_addr` device address
- `direction` `i2c.TRANSMITTER` for writing mode , `i2c. RECEIVER` for reading mode
#### Returns
`true` if ack received, `false` if no ack received.
#### See also
[i2c.read()](#i2cread)
## i2c.read()
Read data for variable number of bytes.
#### Syntax
`i2c.read(id, len)`
#### Parameters
- `id` always 0
- `len` number of data bytes
#### Returns
`string` of received data
#### Example
```lua
id = 0
sda = 1
scl = 2
-- initialize i2c, set pin1 as sda, set pin2 as scl
i2c.setup(id, sda, scl, i2c.SLOW)
-- user defined function: read from reg_addr content of dev_addr
function read_reg(dev_addr, reg_addr)
i2c.start(id)
i2c.address(id, dev_addr, i2c.TRANSMITTER)
i2c.write(id, reg_addr)
i2c.stop(id)
i2c.start(id)
i2c.address(id, dev_addr, i2c.RECEIVER)
c = i2c.read(id, 1)
i2c.stop(id)
return c
end
-- get content of register 0xAA of device 0x77
reg = read_reg(0x77, 0xAA)
print(string.byte(reg))
```
####See also
[i2c.write()](#i2cwrite)
## i2c.setup()
Initialize the I²C module.
#### Syntax
`i2c.setup(id, pinSDA, pinSCL, speed)`
####Parameters
- `id` always 0
- `pinSDA` 1~12, IO index
- `pinSCL` 1~12, IO index
- `speed` only `i2c.SLOW` supported
#### Returns
`speed` the selected speed
####See also
[i2c.read()](#i2cread)
## i2c.start()
Send an I²C start condition.
#### Syntax
`i2c.start(id)`
#### Parameters
`id` always 0
#### Returns
`nil`
####See also
[i2c.read()](#i2cread)
## i2c.stop()
Send an I²C stop condition.
#### Syntax
`i2c.stop(id)`
####Parameters
`id` always 0
#### Returns
`nil`
####See also
[i2c.read()](#i2cread)
## i2c.write()
Write data to I²C bus. Data items can be multiple numbers, strings or lua tables.
####Syntax
`i2c.write(id, data1[, data2[, ..., datan]])`
####Parameters
- `id` always 0
- `data` data can be numbers, string or lua table.
#### Returns
`number` number of bytes written
#### Example
```lua
i2c.write(0, "hello", "world")
```
#### See also
[i2c.read()](#i2cread)
# mDNS Module
| Since | Origin / Contributor | Maintainer | Source |
| :----- | :-------------------- | :---------- | :------ |
| 2016-02-24 | [Philip Gladstone](https://github.com/pjsg) | [Philip Gladstone](https://github.com/pjsg) | [mdns.c](../../../app/modules/mdns.c)|
[Multicast DNS](https://en.wikipedia.org/wiki/Multicast_DNS) is used as part of Bonjour / Zeroconf. This allows system to identify themselves and the services that they provide on a local area network. Clients are then able to discover these systems and connect to them.
## mdns.register()
Register a hostname and start the mDNS service. If the service is already running, then it will be restarted with the new parameters.
#### Syntax
`mdns.register(hostname [, attributes])`
#### Parameters
- `hostname` The hostname for this device. Alphanumeric characters are best.
- `attributes` A optional table of options. The keys must all be strings.
The `attributes` contains two sorts of attributes -- those with specific names, and those that are service specific. [RFC 6763](https://tools.ietf.org/html/rfc6763#page-13)
defines how extra, service specific, attributes are encoded into the DNS. One example is that if the device supports printing, then the queue name can
be specified as an additional attribute. This module supports up to 10 such attributes.
The specific names are:
- `port` The port number for the service. Default value is 80.
- `service` The name of the service. Default value is 'http'.
- `dscription` A short phrase (under 63 characters) describing the service. Default is the hostname.
#### Returns
`nil`
#### Errors
Various errors can be generated during argument validation. The NodeMCU must have an IP address at the time of the call, otherwise an error is thrown.
#### Example
mdns.register("fishtank", {hardware='NodeMCU'})
Using `dns-sd` on OS X, you can see `fishtank.local` as providing the `_http._tcp` service. You can also browse directly to `fishtank.local`. In Safari you can get all the mDNS web pages as part of your bookmarks menu.
mdns.register("fishtank", { description="Top Fishtank", service="http", port=80, location='Living Room' })
## mdns.close()
Shut down the mDNS service. This is not normally needed.
#### Syntax
`mdns.close()`
#### Parameters
none
#### Returns
`nil`
# MQTT Module
| Since | Origin / Contributor | Maintainer | Source |
| :----- | :-------------------- | :---------- | :------ |
| 2015-01-23 | [Stephen Robinson](https://github.com/esar/contiki-mqtt), [Tuan PM](https://github.com/tuanpmt/esp_mqtt) | [Vowstar](https://github.com/vowstar) | [mqtt.c](../../../app/modules/mqtt.c)|
The client adheres to version 3.1.1 of the [MQTT](https://en.wikipedia.org/wiki/MQTT) protocol. Make sure that your broker supports and is correctly configured for version 3.1.1. The client is backwards incompatible with brokers running MQTT 3.1.
## mqtt.Client()
Creates a MQTT client.
#### Syntax
`mqtt.Client(clientid, keepalive, username, password[, cleansession])`
#### Parameters
- `clientid` client ID
- `keepalive` keepalive seconds
- `username` user name
- `password` user password
- `cleansession` 0/1 for `false`/`true`
#### Returns
MQTT client
#### Example
```lua
-- init mqtt client with keepalive timer 120sec
m = mqtt.Client("clientid", 120, "user", "password")
-- setup Last Will and Testament (optional)
-- Broker will publish a message with qos = 0, retain = 0, data = "offline"
-- to topic "/lwt" if client don't send keepalive packet
m:lwt("/lwt", "offline", 0, 0)
m:on("connect", function(client) print ("connected") end)
m:on("offline", function(client) print ("offline") end)
-- on publish message receive event
m:on("message", function(client, topic, data)
print(topic .. ":" )
if data ~= nil then
print(data)
end
end)
-- for TLS: m:connect("192.168.11.118", secure-port, 1)
m:connect("192.168.11.118", 1883, 0, function(client) print("connected") end,
function(client, reason) print("failed reason: "..reason) end)
-- Calling subscribe/publish only makes sense once the connection
-- was successfully established. In a real-world application you want
-- move those into the 'connect' callback or make otherwise sure the
-- connection was established.
-- subscribe topic with qos = 0
m:subscribe("/topic",0, function(client) print("subscribe success") end)
-- publish a message with data = hello, QoS = 0, retain = 0
m:publish("/topic","hello",0,0, function(client) print("sent") end)
m:close();
-- you can call m:connect again
```
# MQTT Client
## mqtt.client:close()
Closes connection to the broker.
#### Syntax
`mqtt:close()`
#### Parameters
none
#### Returns
`true` on success, `false` otherwise
## mqtt.client:connect()
Connects to the broker specified by the given host, port, and secure options.
#### Syntax
`mqtt:connect(host[, port[, secure[, autoreconnect]]][, function(client)[, function(client, reason)]])`
#### Parameters
- `host` host, domain or IP (string)
- `port` broker port (number), default 1883
- `secure` 0/1 for `false`/`true`, default 0. Take note of constraints documented in the [net module](net.md).
- `autoreconnect` 0/1 for `false`/`true`, default 0
- `function(client)` callback function for when the connection was established
- `function(client, reason)` callback function for when the connection could not be established
#### Returns
`true` on success, `false` otherwise
#### Connection failure callback reason codes:
| Constant | Value | Description |
|----------|-------|-------------|
|`mqtt.CONN_FAIL_SERVER_NOT_FOUND`|-5|There is no broker listening at the specified IP Address and Port|
|`mqtt.CONN_FAIL_NOT_A_CONNACK_MSG`|-4|The response from the broker was not a CONNACK as required by the protocol|
|`mqtt.CONN_FAIL_DNS`|-3|DNS Lookup failed|
|`mqtt.CONN_FAIL_TIMEOUT_RECEIVING`|-2|Timeout waiting for a CONNACK from the broker|
|`mqtt.CONN_FAIL_TIMEOUT_SENDING`|-1|Timeout trying to send the Connect message|
|`mqtt.CONNACK_ACCEPTED`|0|No errors. _Note: This will not trigger a failure callback._|
|`mqtt.CONNACK_REFUSED_PROTOCOL_VER`|1|The broker is not a 3.1.1 MQTT broker.|
|`mqtt.CONNACK_REFUSED_ID_REJECTED`|2|The specified ClientID was rejected by the broker. (See `mqtt.Client()`)|
|`mqtt.CONNACK_REFUSED_SERVER_UNAVAILABLE`|3|The server is unavailable.|
|`mqtt.CONNACK_REFUSED_BAD_USER_OR_PASS`|4|The broker refused the specified username or password.|
|`mqtt.CONNACK_REFUSED_NOT_AUTHORIZED`|5|The username is not authorized.|
## mqtt.client:lwt()
Setup [Last Will and Testament](http://www.hivemq.com/blog/mqtt-essentials-part-9-last-will-and-testament) (optional). A broker will publish a message with qos = 0, retain = 0, data = "offline" to topic "/lwt" if client does not send keepalive packet.
#### Syntax
`mqtt:lwt(topic, message[, qos[, retain]])`
#### Parameters
- `topic` the topic to publish to (string)
- `message` the message to publish, (buffer or string)
- `qos` QoS level, default 0
- `retain` retain flag, default 0
#### Returns
`nil`
## mqtt.client:on()
Registers a callback function for an event.
#### Syntax
`mqtt:on(event, function(client[, topic[, message]]))`
#### Parameters
- `event` can be "connect", "message" or "offline"
- `function(client[, topic[, message]])` callback function. The first parameter is the client. If event is "message", the 2nd and 3rd param are received topic and message (strings).
#### Returns
`nil`
## mqtt.client:publish()
Publishes a message.
#### Syntax
`mqtt:publish(topic, payload, qos, retain[, function(client)])`
#### Parameters
- `topic` the topic to publish to ([topic string](http://www.hivemq.com/blog/mqtt-essentials-part-5-mqtt-topics-best-practices))
- `message` the message to publish, (buffer or string)
- `qos` QoS level
- `retain` retain flag
- `function(client)` optional callback fired when PUBACK received. NOTE: When calling publish() more than once, the last callback function defined will be called for ALL publish commands.
#### Returns
`true` on success, `false` otherwise
## mqtt.client:subscribe()
Subscribes to one or several topics.
#### Syntax
`mqtt:subscribe(topic, qos[, function(client)])`
`mqtt:subscribe(table[, function(client)])`
#### Parameters
- `topic` a [topic string](http://www.hivemq.com/blog/mqtt-essentials-part-5-mqtt-topics-best-practices)
- `qos` QoS subscription level, default 0
- `table` array of 'topic, qos' pairs to subscribe to
- `function(client)` optional callback fired when subscription(s) succeeded. NOTE: When calling subscribe() more than once, the last callback function defined will be called for ALL subscribe commands.
#### Returns
`true` on success, `false` otherwise
#### Example
```lua
-- subscribe topic with qos = 0
m:subscribe("/topic",0, function(conn) print("subscribe success") end)
-- or subscribe multiple topic (topic/0, qos = 0; topic/1, qos = 1; topic2 , qos = 2)
m:subscribe({["topic/0"]=0,["topic/1"]=1,topic2=2}, function(conn) print("subscribe success") end)
```
## mqtt.client:unsubscribe()
Unsubscribes from one or several topics.
#### Syntax
`mqtt:unsubscribe(topic[, function(client)])`
`mqtt:unsubscribe(table[, function(client)])`
#### Parameters
- `topic` a [topic string](http://www.hivemq.com/blog/mqtt-essentials-part-5-mqtt-topics-best-practices)
- `table` array of 'topic, anything' pairs to unsubscribe from
- `function(client)` optional callback fired when unsubscription(s) succeeded. NOTE: When calling unsubscribe() more than once, the last callback function defined will be called for ALL unsubscribe commands.
#### Returns
`true` on success, `false` otherwise
#### Example
```lua
-- unsubscribe topic
m:unsubscribe("/topic", function(conn) print("unsubscribe success") end)
-- or unsubscribe multiple topic (topic/0; topic/1; topic2)
m:unsubscribe({["topic/0"]=0,["topic/1"]=0,topic2="anything"}, function(conn) print("unsubscribe success") end)
```
# net Module
| Since | Origin / Contributor | Maintainer | Source |
| :----- | :-------------------- | :---------- | :------ |
| 2014-12-22 | [Zeroday](https://github.com/funshine) | [Zeroday](https://github.com/funshine) | [net.c](../../../app/modules/net.c)|
**SSL/TLS support**
Secure connections use **TLS 1.1** with the following cipher suites:
- `TLS_RSA_WITH_AES_128_CBC_SHA`
- `TLS_RSA_WITH_AES_256_CBC_SHA`
- `TLS_RSA_WITH_RC4_128_SHA`
- `TLS_RSA_WITH_RC4_128_MD5`
This specification is imposed by the [axTLS library](http://axtls.sourceforge.net/specifications.htm) used by the SDK.
## Constants
Constants to be used in other functions: `net.TCP`, `net.UDP`
## net.createConnection()
Creates a client.
#### Syntax
`net.createConnection(type, secure)`
#### Parameters
- `type` `net.TCP` or `net.UDP`
- `secure` 1 for encrypted, 0 for plain
#### Returns
net.socket sub module
#### Example
```lua
net.createConnection(net.UDP, 0)
```
#### See also
[`net.createServer()`](#netcreateserver)
## net.createServer()
Creates a server.
#### Syntax
`net.createServer(type, timeout)`
#### Parameters
- `type` `net.TCP` or `net.UDP`
- `timeout` for a TCP server timeout is 1~28'800 seconds (for an inactive client to be disconnected)
#### Returns
net.server sub module
#### Example
```lua
net.createServer(net.TCP, 30) -- 30s timeout
```
#### See also
[`net.createConnection()`](#netcreateconnection)
## net.multicastJoin()
Join multicast group.
#### Syntax
`net.multicastJoin(if_ip, multicast_ip)`
#### Parameters
- `if_ip` string containing the interface ip to join the multicast group. "any" or "" affects all interfaces.
- `multicast_ip` of the group to join
#### Returns
`nil`
## net.multicastLeave()
Leave multicast group.
#### Syntax
`net.multicastLeave(if_ip, multicast_ip)`
#### Parameters
- `if_ip` string containing the interface ip to leave the multicast group. "any" or "" affects all interfaces.
- `multicast_ip` of the group to leave
#### Returns
`nil`
# net.server Module
## net.server:close()
Closes the server.
#### Syntax
`net.server.close()`
#### Parameters
none
#### Returns
`nil`
#### Example
```lua
-- creates a server
sv = net.createServer(net.TCP, 30)
-- closes the server
sv:close()
```
#### See also
[`net.createServer()`](#netcreateserver)
## net.server:listen()
Listen on port from IP address.
#### Syntax
`net.server.listen(port,[ip],function(net.socket))`
#### Parameters
- `port` port number
- `ip` IP address string, can be omitted
- `function(net.socket)` callback function, pass to caller function as param if a connection is created successfully
#### Returns
`nil`
#### Example
```lua
-- 30s time out for a inactive client
sv = net.createServer(net.TCP, 30)
-- server listens on 80, if data received, print data to console and send "hello world" back to caller
sv:listen(80, function(c)
c:on("receive", function(c, pl)
print(pl)
end)
c:send("hello world")
end)
```
#### See also
[`net.createServer()`](#netcreateserver)
## net.server:on()
UDP server only: Register callback functions for specific events.
#### See also
[`net.socket:on()`](#netsocketon)
## net.server:send()
UDP server only: Sends data to remote peer.
#### See also
[`net.socket:send()`](#netsocketsend)
# net.socket Module
## net.socket:close()
Closes socket.
#### Syntax
`close()`
#### Parameters
none
#### Returns
`nil`
#### See also
[`net.createServer()`](#netcreateserver)
## net.socket:connect()
Connect to a remote server.
#### Syntax
`connect(port, ip|domain)`
#### Parameters
- `port` port number
- `ip` IP address or domain name string
#### Returns
`nil`
#### See also
[`net.socket:on()`](#netsocketon)
## net.socket:dns()
Provides DNS resolution for a hostname.
#### Syntax
`dns(domain, function(net.socket, ip))`
#### Parameters
- `domain` domain name
- `function(net.socket, ip)` callback function. The first parameter is the socket, the second parameter is the IP address as a string.
#### Returns
`nil`
#### Example
```lua
sk = net.createConnection(net.TCP, 0)
sk:dns("www.nodemcu.com", function(conn, ip) print(ip) end)
sk = nil
```
#### See also
[`net.createServer()`](#netcreateserver)
## net.socket:getpeer()
Retrieve port and ip of peer.
#### Syntax
`getpeer()`
#### Parameters
none
#### Returns
- `ip` of peer
- `port` of peer
## net.socket:hold()
Throttle data reception by placing a request to block the TCP receive function. This request is not effective immediately, Espressif recommends to call it while reserving 5*1460 bytes of memory.
#### Syntax
`hold()`
#### Parameters
none
#### Returns
`nil`
#### See also
[`net.socket:unhold()`](#netsocketunhold)
## net.socket:on()
Register callback functions for specific events.
#### Syntax
`on(event, function())`
#### Parameters
- `event` string, which can be "connection", "reconnection", "disconnection", "receive" or "sent"
- `function(net.socket[, string])` callback function. The first parameter is the socket. If event is "receive", the second parameter is the received data as string.
#### Returns
`nil`
#### Example
```lua
srv = net.createConnection(net.TCP, 0)
srv:on("receive", function(sck, c) print(c) end)
srv:connect(80,"192.168.0.66")
srv:on("connection", function(sck, c)
-- Wait for connection before sending.
sck:send("GET / HTTP/1.1\r\nHost: 192.168.0.66\r\nConnection: keep-alive\r\nAccept: */*\r\n\r\n")
end)
```
#### See also
- [`net.createServer()`](#netcreateserver)
- [`net.socket:hold()`](#netsockethold)
## net.socket:send()
Sends data to remote peer.
#### Syntax
`send(string[, function(sent)])`
`sck:send(data, fnA)` is functionally equivalent to `sck:send(data) sck:on("sent", fnA)`.
#### Parameters
- `string` data in string which will be sent to server
- `function(sent)` callback function for sending string
#### Returns
`nil`
#### Note
Multiple consecutive `send()` calls aren't guaranteed to work (and often don't) as network requests are treated as separate tasks by the SDK. Instead, subscribe to the "sent" event on the socket and send additional data (or close) in that callback. See [#730](https://github.com/nodemcu/nodemcu-firmware/issues/730#issuecomment-154241161) for details.
#### Example
```lua
srv = net.createServer(net.TCP)
srv:listen(80, function(conn)
conn:on("receive", function(sck, req)
local response = {}
-- if you're sending back HTML over HTTP you'll want something like this instead
-- local response = {"HTTP/1.0 200 OK\r\nServer: NodeMCU on ESP8266\r\nContent-Type: text/html\r\n\r\n"}
response[#response + 1] = "lots of data"
response[#response + 1] = "even more data"
response[#response + 1] = "e.g. content read from a file"
-- sends and removes the first element from the 'response' table
local function send(sk)
if #response > 0
then sk:send(table.remove(response, 1))
else
sk:close()
response = nil
end
end
-- triggers the send() function again once the first chunk of data was sent
sck:on("sent", send)
send(sck)
end)
end)
```
If you do not or can not keep all the data you send back in memory at one time (remember that `response` is an aggregation) you may use explicit callbacks instead of building up a table like so:
```lua
sck:send(header, function()
local data1 = "some large chunk of dynamically loaded data"
sck:send(data1, function()
local data2 = "even more dynamically loaded data"
sck:send(data2, function(sk)
sk:close()
end)
end)
end)
```
#### See also
[`net.socket:on()`](#netsocketon)
## net.socket:unhold()
Unblock TCP receiving data by revocation of a preceding `hold()`.
#### Syntax
`unhold()`
#### Parameters
none
#### Returns
`nil`
#### See also
[`net.socket:hold()`](#netsockethold)
# net.dns Module
## net.dns.getdnsserver()
Gets the IP address of the DNS server used to resolve hostnames.
#### Syntax
`net.dns.getdnsserver(dns_index)`
#### Parameters
dns_index which DNS server to get (range 0~1)
#### Returns
IP address (string) of DNS server
#### Example
```lua
print(net.dns.getdnsserver(0)) -- 208.67.222.222
print(net.dns.getdnsserver(1)) -- nil
net.dns.setdnsserver("8.8.8.8", 0)
net.dns.setdnsserver("192.168.1.252", 1)
print(net.dns.getdnsserver(0)) -- 8.8.8.8
print(net.dns.getdnsserver(1)) -- 192.168.1.252
```
#### See also
[`net.dns:setdnsserver()`](#netdnssetdnsserver)
## net.dns.resolve()
Resolve a hostname to an IP address. Doesn't require a socket like [`net.socket.dns()`](#netsocketdns).
#### Syntax
`net.dns.resolve(host, function(ip))`
#### Parameters
- `host` hostname to resolve
- `function(sk, ip)` callback called when the name was resolved. Don't use `sk`, it's a socket used internally to resolve the hostname.
#### Returns
`nil`
#### Example
```lua
net.dns.resolve("www.google.com", function(sk, ip)
if (ip == nil) then print("DNS fail!") else print(ip) end
end)
```
#### See also
[`net.socket:dns()`](#netsocketdns)
## net.dns.setdnsserver()
Sets the IP of the DNS server used to resolve hostnames. Default: resolver1.opendns.com (208.67.222.222). You can specify up to 2 DNS servers.
#### Syntax
`net.dns.setdnsserver(dns_ip_addr, dns_index)`
#### Parameters
- `dns_ip_addr` IP address of a DNS server
- `dns_index` which DNS server to set (range 0~1). Hence, it supports max. 2 servers.
#### Returns
`nil`
#### See also
[`net.dns:getdnsserver()`](#netdnsgetdnsserver)
# net.cert Module
This controls certificate verification when SSL is in use.
## net.cert.verify()
Controls the vertificate verification process when the Nodemcu makes a secure connection.
#### Syntax
`net.cert.verify(enable)`
`net.cert.verify(pemdata)`
#### Parameters
- `enable` A boolean which indicates whether verification should be enabled or not. The default at boot is `false`.
- `pemdata` A string containing the CA certificate to use for verification.
#### Returns
`true` if it worked.
Can throw a number of errors if invalid data is supplied.
#### Example
Make a secure https connection and verify that the certificate chain is valid.
```
net.cert.verify(true)
http.get("https://example.com/info", nil, function (code, resp) print(code, resp) end)
```
Load a certificate into the flash chip and make a request. This is the [startssl](https://startssl.com) root certificate. They provide free
certificates.
```
net.cert.verify([[
-----BEGIN CERTIFICATE-----
MIIHyTCCBbGgAwIBAgIBATANBgkqhkiG9w0BAQUFADB9MQswCQYDVQQGEwJJTDEW
MBQGA1UEChMNU3RhcnRDb20gTHRkLjErMCkGA1UECxMiU2VjdXJlIERpZ2l0YWwg
Q2VydGlmaWNhdGUgU2lnbmluZzEpMCcGA1UEAxMgU3RhcnRDb20gQ2VydGlmaWNh
dGlvbiBBdXRob3JpdHkwHhcNMDYwOTE3MTk0NjM2WhcNMzYwOTE3MTk0NjM2WjB9
MQswCQYDVQQGEwJJTDEWMBQGA1UEChMNU3RhcnRDb20gTHRkLjErMCkGA1UECxMi
U2VjdXJlIERpZ2l0YWwgQ2VydGlmaWNhdGUgU2lnbmluZzEpMCcGA1UEAxMgU3Rh
cnRDb20gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUA
A4ICDwAwggIKAoICAQDBiNsJvGxGfHiflXu1M5DycmLWwTYgIiRezul38kMKogZk
pMyONvg45iPwbm2xPN1yo4UcodM9tDMr0y+v/uqwQVlntsQGfQqedIXWeUyAN3rf
OQVSWff0G0ZDpNKFhdLDcfN1YjS6LIp/Ho/u7TTQEceWzVI9ujPW3U3eCztKS5/C
Ji/6tRYccjV3yjxd5srhJosaNnZcAdt0FCX+7bWgiA/deMotHweXMAEtcnn6RtYT
Kqi5pquDSR3l8u/d5AGOGAqPY1MWhWKpDhk6zLVmpsJrdAfkK+F2PrRt2PZE4XNi
HzvEvqBTViVsUQn3qqvKv3b9bZvzndu/PWa8DFaqr5hIlTpL36dYUNk4dalb6kMM
Av+Z6+hsTXBbKWWc3apdzK8BMewM69KN6Oqce+Zu9ydmDBpI125C4z/eIT574Q1w
+2OqqGwaVLRcJXrJosmLFqa7LH4XXgVNWG4SHQHuEhANxjJ/GP/89PrNbpHoNkm+
Gkhpi8KWTRoSsmkXwQqQ1vp5Iki/untp+HDH+no32NgN0nZPV/+Qt+OR0t3vwmC3
Zzrd/qqc8NSLf3Iizsafl7b4r4qgEKjZ+xjGtrVcUjyJthkqcwEKDwOzEmDyei+B
26Nu/yYwl/WL3YlXtq09s68rxbd2AvCl1iuahhQqcvbjM4xdCUsT37uMdBNSSwID
AQABo4ICUjCCAk4wDAYDVR0TBAUwAwEB/zALBgNVHQ8EBAMCAa4wHQYDVR0OBBYE
FE4L7xqkQFulF2mHMMo0aEPQQa7yMGQGA1UdHwRdMFswLKAqoCiGJmh0dHA6Ly9j
ZXJ0LnN0YXJ0Y29tLm9yZy9zZnNjYS1jcmwuY3JsMCugKaAnhiVodHRwOi8vY3Js
LnN0YXJ0Y29tLm9yZy9zZnNjYS1jcmwuY3JsMIIBXQYDVR0gBIIBVDCCAVAwggFM
BgsrBgEEAYG1NwEBATCCATswLwYIKwYBBQUHAgEWI2h0dHA6Ly9jZXJ0LnN0YXJ0
Y29tLm9yZy9wb2xpY3kucGRmMDUGCCsGAQUFBwIBFilodHRwOi8vY2VydC5zdGFy
dGNvbS5vcmcvaW50ZXJtZWRpYXRlLnBkZjCB0AYIKwYBBQUHAgIwgcMwJxYgU3Rh
cnQgQ29tbWVyY2lhbCAoU3RhcnRDb20pIEx0ZC4wAwIBARqBl0xpbWl0ZWQgTGlh
YmlsaXR5LCByZWFkIHRoZSBzZWN0aW9uICpMZWdhbCBMaW1pdGF0aW9ucyogb2Yg
dGhlIFN0YXJ0Q29tIENlcnRpZmljYXRpb24gQXV0aG9yaXR5IFBvbGljeSBhdmFp
bGFibGUgYXQgaHR0cDovL2NlcnQuc3RhcnRjb20ub3JnL3BvbGljeS5wZGYwEQYJ
YIZIAYb4QgEBBAQDAgAHMDgGCWCGSAGG+EIBDQQrFilTdGFydENvbSBGcmVlIFNT
TCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTANBgkqhkiG9w0BAQUFAAOCAgEAFmyZ
9GYMNPXQhV59CuzaEE44HF7fpiUFS5Eyweg78T3dRAlbB0mKKctmArexmvclmAk8
jhvh3TaHK0u7aNM5Zj2gJsfyOZEdUauCe37Vzlrk4gNXcGmXCPleWKYK34wGmkUW
FjgKXlf2Ysd6AgXmvB618p70qSmD+LIU424oh0TDkBreOKk8rENNZEXO3SipXPJz
ewT4F+irsfMuXGRuczE6Eri8sxHkfY+BUZo7jYn0TZNmezwD7dOaHZrzZVD1oNB1
ny+v8OqCQ5j4aZyJecRDjkZy42Q2Eq/3JR44iZB3fsNrarnDy0RLrHiQi+fHLB5L
EUTINFInzQpdn4XBidUaePKVEFMy3YCEZnXZtWgo+2EuvoSoOMCZEoalHmdkrQYu
L6lwhceWD3yJZfWOQ1QOq92lgDmUYMA0yZZwLKMS9R9Ie70cfmu3nZD0Ijuu+Pwq
yvqCUqDvr0tVk+vBtfAii6w0TiYiBKGHLHVKt+V9E9e4DGTANtLJL4YSjCMJwRuC
O3NJo2pXh5Tl1njFmUNj403gdy3hZZlyaQQaRwnmDwFWJPsfvw55qVguucQJAX6V
um0ABj6y6koQOdjQK/W/7HW/lwLFCRsI3FU34oH7N4RDYiDK51ZLZer+bMEkkySh
NOsF/5oirpt9P/FlUQqmMGqz9IgcgA38corog14=
-----END CERTIFICATE-----
]])
http.get("https://pskreporter.info/gen404", nil, function (code, resp) print(code, resp) end)
```
#### Notes
The certificate needed for verification is stored in the flash chip. The `net.cert.verify` call with `true`
enables verification against the value stored in the flash.
The certificate can be loaded into the flash chip in two ways -- one at firmware build time, and the other at initial boot
of the firmware. In order to load the certificate at build time, just place a file containing the CA certificate (in PEM format)
at `server-ca.crt` in the root of the nodemcu-firmware build tree. The build scripts will incorporate this into the resulting
firmware image.
The alternative approach is easier for development, and that is to supply the PEM data as a string value to `net.cert.verify`. This
will store the certificate into the flash chip and turn on verification for that certificate. Subsequent boots of the nodemcu can then
use `net.cert.verify(true)` and use the stored certificate.
# node Module
| Since | Origin / Contributor | Maintainer | Source |
| :----- | :-------------------- | :---------- | :------ |
| 2014-12-22 | [Zeroday](https://github.com/funshine) | [Zeroday](https://github.com/funshine) | [node.c](../../../app/modules/node.c)|
The node module provides access to system-level features such as sleep, restart and various info and IDs.
## node.bootreason()
Returns the boot reason and extended reset info.
The first value returned is the raw code, not the new "reset info" code which was introduced in recent SDKs. Values are:
- 1, power-on
- 2, reset (software?)
- 3, hardware reset via reset pin
- 4, WDT reset (watchdog timeout)
The second value returned is the extended reset cause. Values are:
- 0, power-on
- 1, hardware watchdog reset
- 2, exception reset
- 3, software watchdog reset
- 4, software restart
- 5, wake from deep sleep
- 6, external reset
In general, the extended reset cause supercedes the raw code. The raw code is kept for backwards compatibility only. For new applications it is highly recommended to use the extended reset cause instead.
In case of extended reset cause 3 (exception reset), additional values are returned containing the crash information. These are, in order, EXCCAUSE, EPC1, EPC2, EPC3, EXCVADDR, and DEPC.
#### Syntax
`node.bootreason()`
#### Parameters
none
#### Returns
`rawcode, reason [, exccause, epc1, epc2, epc3, excvaddr, depc ]`
#### Example
```lua
_, reset_reason = node.bootreason()
if reset_reason == 0 then print("Power UP!") end
```
## node.chipid()
Returns the ESP chip ID.
#### Syntax
`node.chipid()`
#### Parameters
none
#### Returns
chip ID (number)
## node.compile()
Compiles a Lua text file into Lua bytecode, and saves it as .lc file.
#### Syntax
`node.compile("file.lua")`
#### Parameters
`filename` name of Lua text file
#### Returns
`nil`
#### Example
```lua
file.open("hello.lua","w+")
file.writeline([[print("hello nodemcu")]])
file.writeline([[print(node.heap())]])
file.close()
node.compile("hello.lua")
dofile("hello.lua")
dofile("hello.lc")
```
## node.dsleep()
Enters deep sleep mode, wakes up when timed out.
The maximum sleep time is 4294967295us, ~71 minutes. This is an SDK limitation.
Firmware from before 05 Jan 2016 have a maximum sleeptime of ~35 minutes.
!!! note "Note:"
This function can only be used in the condition that esp8266 PIN32(RST) and PIN8(XPD_DCDC aka GPIO16) are connected together. Using sleep(0) will set no wake up timer, connect a GPIO to pin RST, the chip will wake up by a falling-edge on pin RST.
#### Syntax
`node.dsleep(us, option)`
#### Parameters
- `us` number (integer) or `nil`, sleep time in micro second. If `us == 0`, it will sleep forever. If `us == nil`, will not set sleep time.
- `option` number (integer) or `nil`. If `nil`, it will use last alive setting as default option.
- 0, init data byte 108 is valuable
- \> 0, init data byte 108 is valueless
- 0, RF_CAL or not after deep-sleep wake up, depends on init data byte 108
- 1, RF_CAL after deep-sleep wake up, there will belarge current
- 2, no RF_CAL after deep-sleep wake up, there will only be small current
- 4, disable RF after deep-sleep wake up, just like modem sleep, there will be the smallest current
#### Returns
`nil`
#### Example
```lua
--do nothing
node.dsleep()
--sleep μs
node.dsleep(1000000)
--set sleep option, then sleep μs
node.dsleep(1000000, 4)
--set sleep option only
node.dsleep(nil,4)
```
## node.flashid()
Returns the flash chip ID.
#### Syntax
`node.flashid()`
#### Parameters
none
#### Returns
flash ID (number)
## node.heap()
Returns the current available heap size in bytes. Note that due to fragmentation, actual allocations of this size may not be possible.
#### Syntax
`node.heap()`
#### Parameters
none
#### Returns
system heap size left in bytes (number)
## node.info()
Returns NodeMCU version, chipid, flashid, flash size, flash mode, flash speed.
#### Syntax
`node.info()`
#### Parameters
none
#### Returns
- `majorVer` (number)
- `minorVer` (number)
- `devVer` (number)
- `chipid` (number)
- `flashid` (number)
- `flashsize` (number)
- `flashmode` (number)
- `flashspeed` (number)
#### Example
```lua
majorVer, minorVer, devVer, chipid, flashid, flashsize, flashmode, flashspeed = node.info()
print("NodeMCU "..majorVer.."."..minorVer.."."..devVer)
```
## node.input()
Submits a string to the Lua interpreter. Similar to `pcall(loadstring(str))`, but without the single-line limitation.
!!! note "Note:"
This function only has an effect when invoked from a callback. Using it directly on the console **does not work**.
#### Syntax
`node.input(str)`
#### Parameters
`str` Lua chunk
#### Returns
`nil`
#### Example
```lua
sk:on("receive", function(conn, payload) node.input(payload) end)
```
#### See also
[`node.output()`](#nodeoutput)
## node.key() --deprecated
Defines action to take on button press (on the old devkit 0.9), button connected to GPIO 16.
This function is only available if the firmware was compiled with DEVKIT_VERSION_0_9 defined.
#### Syntax
`node.key(type, function())`
#### Parameters
- `type`: type is either string "long" or "short". long: press the key for 3 seconds, short: press shortly(less than 3 seconds)
- `function`: user defined function which is called when key is pressed. If nil, remove the user defined function. Default function: long: change LED blinking rate, short: reset chip
#### Returns
`nil`
#### Example
```lua
node.key("long", function() print('hello world') end)
```
#### See also
[`node.led()`](#nodeled-deprecated)
## node.led() --deprecated
Sets the on/off time for the LED (on the old devkit 0.9), with the LED connected to GPIO16, multiplexed with [`node.key()`](#nodekey-deprecated).
This function is only available if the firmware was compiled with DEVKIT_VERSION_0_9 defined.
#### Syntax
`node.led(low, high)`
#### Parameters
- `low` LED off time, LED keeps on when low=0. Unit: milliseconds, time resolution: 80~100ms
- `high` LED on time. Unit: milliseconds, time resolution: 80~100ms
#### Returns
`nil`
#### Example
```lua
-- turn led on forever.
node.led(0)
```
#### See also
[`node.key()`](#nodekey-deprecated)
## node.output()
Redirects the Lua interpreter output to a callback function. Optionally also prints it to the serial console.
!!! note "Note:"
Do **not** attempt to `print()` or otherwise induce the Lua interpreter to produce output from within the callback function. Doing so results in infinite recursion, and leads to a watchdog-triggered restart.
#### Syntax
`node.output(function(str), serial_debug)`
#### Parameters
- `output_fn(str)` a function accept every output as str, and can send the output to a socket (or maybe a file).
- `serial_debug` 1 output also show in serial. 0: no serial output.
#### Returns
`nil`
#### Example
```lua
function tonet(str)
sk:send(str)
end
node.output(tonet, 1) -- serial also get the lua output.
```
```lua
-- a simple telnet server
s=net.createServer(net.TCP)
s:listen(2323,function(c)
con_std = c
function s_output(str)
if(con_std~=nil)
then con_std:send(str)
end
end
node.output(s_output, 0) -- re-direct output to function s_ouput.
c:on("receive",function(c,l)
node.input(l) -- works like pcall(loadstring(l)) but support multiple separate line
end)
c:on("disconnection",function(c)
con_std = nil
node.output(nil) -- un-regist the redirect output function, output goes to serial
end)
end)
```
#### See also
[`node.input()`](#nodeinput)
## node.readvdd33() --deprecated
Moved to [`adc.readvdd33()`](adc/#adcreadvdd33).
## node.restart()
Restarts the chip.
#### Syntax
`node.restart()`
#### Parameters
none
#### Returns
`nil`
## node.restore()
Restores system configuration to defaults using the SDK function `system_restore()`, which doesn't document precisely what it erases/restores.
#### Syntax
`node.restore()`
#### Parameters
none
#### Returns
`nil`
#### Example
```lua
node.restore()
node.restart() -- ensure the restored settings take effect
```
## node.setcpufreq()
Change the working CPU Frequency.
#### Syntax
`node.setcpufreq(speed)`
#### Parameters
`speed` constant 'node.CPU80MHZ' or 'node.CPU160MHZ'
#### Returns
target CPU frequency (number)
#### Example
```lua
node.setcpufreq(node.CPU80MHZ)
```
## node.stripdebug()
Controls the amount of debug information kept during [`node.compile()`](#nodecompile), and allows removal of debug information from already compiled Lua code.
Only recommended for advanced users, the NodeMCU defaults are fine for almost all use cases.
####Syntax
`node.stripdebug([level[, function]])`
#### Parameters
- `level`
- 1, don't discard debug info
- 2, discard Local and Upvalue debug info
- 3, discard Local, Upvalue and line-number debug info
- `function` a compiled function to be stripped per setfenv except 0 is not permitted.
If no arguments are given then the current default setting is returned. If function is omitted, this is the default setting for future compiles. The function argument uses the same rules as for `setfenv()`.
#### Returns
If invoked without arguments, returns the current level settings. Otherwise, `nil` is returned.
#### Example
```lua
node.stripdebug(3)
node.compile('bigstuff.lua')
```
#### See also
[`node.compile()`](#nodecompile)
## node.osprint()
Controls whether the debugging output from the Espressif SDK is printed. Note that this is only available if
the firmware is build with DEVELOPMENT_TOOLS defined.
####Syntax
`node.osprint(enabled)`
#### Parameters
- `enabled` This is either `true` to enable printing, or `false` to disable it. The default is `false`.
#### Returns
Nothing
#### Example
```lua
node.osprint(true)
```
# node.egc module
## node.egc.setmode()
Sets the Emergency Garbage Collector mode. [The EGC whitepaper](http://www.eluaproject.net/doc/v0.9/en_elua_egc.html)
provides more detailed information on the EGC.
####Syntax
`node.egc.setmode(mode, [param])`
#### Parameters
- `mode`
- `node.egc.NOT_ACTIVE` EGC inactive, no collection cycle will be forced in low memory situations
- `node.egc.ON_ALLOC_FAILURE` Try to allocate a new block of memory, and run the garbage collector if the allocation fails. If the allocation fails even after running the garbage collector, the allocator will return with error.
- `node.egc.ON_MEM_LIMIT` Run the garbage collector when the memory used by the Lua script goes beyond an upper `limit`. If the upper limit can't be satisfied even after running the garbage collector, the allocator will return with error.
- `node.egc.ALWAYS` Run the garbage collector before each memory allocation. If the allocation fails even after running the garbage collector, the allocator will return with error. This mode is very efficient with regards to memory savings, but it's also the slowest.
- `level` in the case of `node.egc.ON_MEM_LIMIT`, this specifies the memory limit.
#### Returns
`nil`
#### Example
`node.egc.setmode(node.egc.ALWAYS, 4096) -- This is the default setting at startup.`
`node.egc.setmode(node.egc.ON_ALLOC_FAILURE) -- This is the fastest activeEGC mode.`
# node.task module
## node.task.post()
Enable a Lua callback or task to post another task request. Note that as per the
example multiple tasks can be posted in any task, but the highest priority is
always delivered first.
If the task queue is full then a queue full error is raised.
####Syntax
`node.task.post([task_priority], function)`
#### Parameters
- `task_priority` (optional)
- `node.task.LOW_PRIORITY` = 0
- `node.task.MEDIUM_PRIORITY` = 1
- `node.task.HIGH_PRIORITY` = 2
- `function` a callback function to be executed when the task is run.
If the priority is omitted then this defaults to `node.task.MEDIUM_PRIORITY`
#### Returns
`nil`
#### Example
```lua
for i = node.task.LOW_PRIORITY, node.task.HIGH_PRIORITY do
node.task.post(i,function(p2)
print("priority is "..p2)
end)
end
```
prints
```
priority is 2
priority is 1
priority is 0
```
# 1-Wire Module
| Since | Origin / Contributor | Maintainer | Source |
| :----- | :-------------------- | :---------- | :------ |
| 2014-12-22 | [Zeroday](https://github.com/funshine) | [Zeroday](https://github.com/funshine) | [ow.c](../../../app/modules/ow.c)|
This module provides functions to work with the [1-Wire](https://en.wikipedia.org/wiki/1-Wire) device communications bus system.
## ow.check_crc16()
Computes the 1-Wire CRC16 and compare it against the received CRC.
#### Syntax
`ow.check_crc16(buf, inverted_crc0, inverted_crc1[, crc])`
#### Parameters
- `buf` string value, data to be calculated check sum in string
- `inverted_crc0` LSB of received CRC
- `inverted_crc1` MSB of received CRC
- `crc` CRC starting value (optional)
#### Returns
true if the CRC matches, false otherwise
## ow.crc16()
Computes a Dallas Semiconductor 16 bit CRC. This is required to check the integrity of data received from many 1-Wire devices. Note that the CRC computed here is **not** what you'll get from the 1-Wire network, for two reasons:
1. The CRC is transmitted bitwise inverted.
2. Depending on the endian-ness of your processor, the binary representation of the two-byte return value may have a different byte order than the two bytes you get from 1-Wire.
#### Syntax
`ow.crc16(buf[, crc])`
#### Parameters
- `buf` string value, data to be calculated check sum in string
- `crc` CRC starting value (optional)
#### Returns
the CRC16 as defined by Dallas Semiconductor
## ow.crc8()
Computes a Dallas Semiconductor 8 bit CRC, these are used in the ROM and scratchpad registers.
#### Syntax
`ow.crc8(buf)`
#### Parameters
`buf` string value, data to be calculated check sum in string
#### Returns
CRC result as byte
## ow.depower()
Stops forcing power onto the bus. You only need to do this if you used the 'power' flag to `ow.write()` or used a `ow.write_bytes()` and aren't about to do another read or write.
#### Syntax
`ow.depower(pin)`
#### Parameters
`pin` 1~12, I/O index
#### Returns
`nil`
####See also
- [ow.write()](#owwrite)
- [ow.write_bytes()](#owwrite_bytes)
## ow.read()
Reads a byte.
####Syntax
`ow.read(pin)`
#### Parameters
`pin` 1~12, I/O index
#### Returns
byte read from slave device
## ow.read_bytes()
Reads multi bytes.
#### Syntax
`ow.read_bytes(pin, size)`
#### Parameters
- `pin` 1~12, I/O index
- `size` number of bytes to be read from slave device
#### Returns
`string` bytes read from slave device
## ow.reset()
Performs a 1-Wire reset cycle.
#### Syntax
`ow.reset(pin)`
#### Parameters
`pin` 1~12, I/O index
#### Returns
- `1` if a device responds with a presence pulse
- `0` if there is no device or the bus is shorted or otherwise held low for more than 250 µS
## ow.reset_search()
Clears the search state so that it will start from the beginning again.
#### Syntax
`ow.reset_search(pin)`
#### Parameters
`pin` 1~12, I/O index
#### Returns
`nil`
## ow.search()
Looks for the next device.
#### Syntax
`ow.search(pin)`
#### Parameters
`pin` 1~12, I/O index
#### Returns
`rom_code` string with length of 8 upon success. It contains the rom code of slave device. Returns `nil` if search was unsuccessful.
#### See also
[ow.target_search()](#owtargetsearch)
## ow.select()
Issues a 1-Wire rom select command. Make sure you do the `ow.reset(pin)` first.
#### Syntax
`ow.select(pin, rom)`
#### Parameters
- `pin` 1~12, I/O index
- `rom` string value, len 8, rom code of the salve device
#### Returns
`nil`
#### Example
```lua
-- 18b20 Example
pin = 9
ow.setup(pin)
count = 0
repeat
count = count + 1
addr = ow.reset_search(pin)
addr = ow.search(pin)
tmr.wdclr()
until (addr ~= nil) or (count > 100)
if addr == nil then
print("No more addresses.")
else
print(addr:byte(1,8))
crc = ow.crc8(string.sub(addr,1,7))
if crc == addr:byte(8) then
if (addr:byte(1) == 0x10) or (addr:byte(1) == 0x28) then
print("Device is a DS18S20 family device.")
repeat
ow.reset(pin)
ow.select(pin, addr)
ow.write(pin, 0x44, 1)
tmr.delay(1000000)
present = ow.reset(pin)
ow.select(pin, addr)
ow.write(pin,0xBE,1)
print("P="..present)
data = nil
data = string.char(ow.read(pin))
for i = 1, 8 do
data = data .. string.char(ow.read(pin))
end
print(data:byte(1,9))
crc = ow.crc8(string.sub(data,1,8))
print("CRC="..crc)
if crc == data:byte(9) then
t = (data:byte(1) + data:byte(2) * 256) * 625
t1 = t / 10000
t2 = t % 10000
print("Temperature="..t1.."."..t2.."Centigrade")
end
tmr.wdclr()
until false
else
print("Device family is not recognized.")
end
else
print("CRC is not valid!")
end
end
```
####See also
[ow.reset()](#owreset)
## ow.setup()
Sets a pin in onewire mode.
#### Syntax
`ow.setup(pin)`
#### Parameters
`pin` 1~12, I/O index
#### Returns
`nil`
## ow.skip()
Issues a 1-Wire rom skip command, to address all on bus.
#### Syntax
`ow.skip(pin)`
#### Parameters
`pin` 1~12, I/O index
#### Returns
`nil`
## ow.target_search()
Sets up the search to find the device type `family_code`. The search itself has to be initiated with a subsequent call to `ow.search()`.
#### Syntax
`ow.target_search(pin, family_code)`
#### Parameters
- `pin` 1~12, I/O index
- `family_code` byte for family code
#### Returns
`nil`
####See also
[ow.search()](#owsearch)
## ow.write()
Writes a byte. If `power` is 1 then the wire is held high at the end for parasitically powered devices. You are responsible for eventually depowering it by calling `ow.depower()` or doing another read or write.
#### Syntax
`ow.write(pin, v, power)`
#### Parameters
- `pin` 1~12, I/O index
- `v` byte to be written to salve device
- `power` 1 for wire being held high for parasitically powered devices
#### Returns
`nil`
####See also
[ow.depower()](#owdepower)
## ow.write_bytes()
Writes multi bytes. If `power` is 1 then the wire is held high at the end for parasitically powered devices. You are responsible for eventually depowering it by calling `ow.depower()` or doing another read or write.
#### Syntax
`ow.write_bytes(pin, buf, power)`
#### Parameters
- `pin` 1~12, IO index
- `buf` string to be written to slave device
- `power` 1 for wire being held high for parasitically powered devices
#### Returns
`nil`
####See also
[ow.depower()](#owdepower)
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment