Commit 82b19c4c authored by Marcel Stör's avatar Marcel Stör
Browse files

Merge branch 'newdocs' into dev

parents 7e8c5489 96a05dcd
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
[![Join the chat at https://gitter.im/nodemcu/nodemcu-firmware](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/nodemcu/nodemcu-firmware?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![Join the chat at https://gitter.im/nodemcu/nodemcu-firmware](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/nodemcu/nodemcu-firmware?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![Build Status](https://travis-ci.org/nodemcu/nodemcu-firmware.svg)](https://travis-ci.org/nodemcu/nodemcu-firmware) [![Build Status](https://travis-ci.org/nodemcu/nodemcu-firmware.svg)](https://travis-ci.org/nodemcu/nodemcu-firmware)
[![Documentation Status](https://readthedocs.org/projects/nodemcu/badge/?version=newdocs)](http://nodemcu.readthedocs.org/en/newdocs/?badge=newdocs)
###A lua based firmware for wifi-soc esp8266 ###A lua based firmware for wifi-soc esp8266
- Build on [ESP8266 NONOS SDK 1.5.1](http://bbs.espressif.com/viewtopic.php?f=46&p=5315) - Build on [ESP8266 NONOS SDK 1.5.1](http://bbs.espressif.com/viewtopic.php?f=46&p=5315)
...@@ -411,173 +412,6 @@ Victor Brutskiy's [ESPlorer](https://github.com/4refr0nt/ESPlorer) is written in ...@@ -411,173 +412,6 @@ Victor Brutskiy's [ESPlorer](https://github.com/4refr0nt/ESPlorer) is written in
package.loaded["ds18b20"]=nil package.loaded["ds18b20"]=nil
``` ```
####Operate a display with u8glib
u8glib is a graphics library with support for many different displays. The nodemcu firmware supports a subset of these.
Both I2C and SPI:
* sh1106_128x64
* ssd1306 - 128x64 and 64x48 variants
* ssd1309_128x64
* ssd1327_96x96_gr
* uc1611 - dogm240 and dogxl240 variants
SPI only:
* ld7032_60x32
* pcd8544_84x48
* pcf8812_96x65
* ssd1322_nhd31oled - bw and gr variants
* ssd1325_nhd27oled - bw and gr variants
* ssd1351_128x128 - gh and hicolor variants
* st7565_64128n - variants 64128n, dogm128/132, lm6059/lm6063, c12832/c12864
* uc1601_c128032
* uc1608 - 240x128 and 240x64 variants
* uc1610_dogxl160 - bw and gr variants
* uc1611 - dogm240 and dogxl240 variants
* uc1701 - dogs102 and mini12864 variants
U8glib v1.18.1
#####I2C connection
Hook up SDA and SCL to any free GPIOs. Eg. [u8g_graphics_test.lua](lua_examples/u8glib/u8g_graphics_test.lua) expects SDA=5 (GPIO14) and SCL=6 (GPIO12). They are used to set up nodemcu's I2C driver before accessing the display:
```lua
sda = 5
scl = 6
i2c.setup(0, sda, scl, i2c.SLOW)
```
#####SPI connection
The HSPI module is used ([more information](http://d.av.id.au/blog/esp8266-hardware-spi-hspi-general-info-and-pinout/)), so certain pins are fixed:
* HSPI CLK = GPIO14
* HSPI MOSI = GPIO13
* HSPI MISO = GPIO12 (not used)
All other pins can be assigned to any available GPIO:
* CS
* D/C
* RES (optional for some displays)
Also refer to the initialization sequence eg in [u8g_graphics_test.lua](lua_examples/u8glib/u8g_graphics_test.lua):
```lua
spi.setup(1, spi.MASTER, spi.CPOL_LOW, spi.CPHA_LOW, 8, 8)
```
#####Library usage
The Lua bindings for this library closely follow u8glib's object oriented C++ API. Based on the u8g class, you create an object for your display type.
SSD1306 via I2C:
```lua
sla = 0x3c
disp = u8g.ssd1306_128x64_i2c(sla)
```
SSD1306 via SPI:
```lua
cs = 8 -- GPIO15, pull-down 10k to GND
dc = 4 -- GPIO2
res = 0 -- GPIO16, RES is optional YMMV
disp = u8g.ssd1306_128x64_hw_spi(cs, dc, res)
```
This object provides all of u8glib's methods to control the display.
Again, refer to [u8g_graphics_test.lua](lua_examples/u8glib/u8g_graphics_test.lua) to get an impression how this is achieved with Lua code. Visit the [u8glib homepage](https://github.com/olikraus/u8glib) for technical details.
#####Displays
I2C and HW SPI based displays with support in u8glib can be enabled. To get access to the respective constructors, add the desired entries to the I2C or SPI display tables in [app/include/u8g_config.h](app/include/u8g_config.h):
```c
#define U8G_DISPLAY_TABLE_I2C \
U8G_DISPLAY_TABLE_ENTRY(ssd1306_128x64_i2c) \
#define U8G_DISPLAY_TABLE_SPI \
U8G_DISPLAY_TABLE_ENTRY(ssd1306_128x64_hw_spi) \
U8G_DISPLAY_TABLE_ENTRY(pcd8544_84x48_hw_spi) \
U8G_DISPLAY_TABLE_ENTRY(pcf8812_96x65_hw_spi) \
```
An exhaustive list of available displays can be found in the [u8g module wiki entry](https://github.com/nodemcu/nodemcu-firmware/wiki/nodemcu_api_en#u8g-module).
#####Fonts
u8glib comes with a wide range of fonts for small displays. Since they need to be compiled into the firmware image, you'd need to include them in [app/include/u8g_config.h](app/include/u8g_config.h) and recompile. Simply add the desired fonts to the font table:
```c
#define U8G_FONT_TABLE \
U8G_FONT_TABLE_ENTRY(font_6x10) \
U8G_FONT_TABLE_ENTRY(font_chikita)
```
They'll be available as `u8g.<font_name>` in Lua.
#####Bitmaps
Bitmaps and XBMs are supplied as strings to `drawBitmap()` and `drawXBM()`. This off-loads all data handling from the u8g module to generic methods for binary files. See [u8g_bitmaps.lua](lua_examples/u8glib/u8g_bitmaps.lua).
In contrast to the source code based inclusion of XBMs into u8glib, it's required to provide precompiled binary files. This can be performed online with [Online-Utility's Image Converter](http://www.online-utility.org/image_converter.jsp): Convert from XBM to MONO format and upload the binary result with [nodemcu-uploader.py](https://github.com/kmpm/nodemcu-uploader).
#####Unimplemented functions
- [ ] Cursor handling
- [ ] disableCursor()
- [ ] enableCursor()
- [ ] setCursorColor()
- [ ] setCursorFont()
- [ ] setCursorPos()
- [ ] setCursorStyle()
- [ ] General functions
- [ ] setContrast()
- [ ] setPrintPos()
- [ ] setHardwareBackup()
- [ ] setRGB()
- [ ] setDefaultMidColor()
####Operate a display with ucglib
Ucglib is a graphics library with support for color TFT displays.
Ucglib v1.3.3
#####SPI connection
The HSPI module is used ([more information](http://d.av.id.au/blog/esp8266-hardware-spi-hspi-general-info-and-pinout/)), so certain pins are fixed:
* HSPI CLK = GPIO14
* HSPI MOSI = GPIO13
* HSPI MISO = GPIO12 (not used)
All other pins can be assigned to any available GPIO:
* CS
* D/C
* RES (optional for some displays)
Also refer to the initialization sequence eg in [GraphicsTest.lua](lua_examples/ucglib/GraphicsRest.lua):
```lua
spi.setup(1, spi.MASTER, spi.CPOL_LOW, spi.CPHA_LOW, 8, 8)
```
#####Library usage
The Lua bindings for this library closely follow ucglib's object oriented C++ API. Based on the ucg class, you create an object for your display type.
ILI9341 via SPI:
```lua
cs = 8 -- GPIO15, pull-down 10k to GND
dc = 4 -- GPIO2
res = 0 -- GPIO16, RES is optional YMMV
disp = ucg.ili9341_18x240x320_hw_spi(cs, dc, res)
```
This object provides all of ucglib's methods to control the display.
Again, refer to [GraphicsTest.lua](lua_examples/ucglib/GraphicsTest.lua) to get an impression how this is achieved with Lua code. Visit the [ucglib homepage](https://github.com/olikraus/ucglib) for technical details.
#####Displays
To get access to the display constructors, add the desired entries to the display table in [app/include/ucg_config.h](app/include/ucg_config.h):
```c
#define UCG_DISPLAY_TABLE \
UCG_DISPLAY_TABLE_ENTRY(ili9341_18x240x320_hw_spi, ucg_dev_ili9341_18x240x320, ucg_ext_ili9341_18) \
UCG_DISPLAY_TABLE_ENTRY(st7735_18x128x160_hw_spi, ucg_dev_st7735_18x128x160, ucg_ext_st7735_18) \
```
#####Fonts
ucglib comes with a wide range of fonts for small displays. Since they need to be compiled into the firmware image, you'd need to include them in [app/include/ucg_config.h](app/include/ucg_config.h) and recompile. Simply add the desired fonts to the font table:
```c
#define UCG_FONT_TABLE \
UCG_FONT_TABLE_ENTRY(font_7x13B_tr) \
UCG_FONT_TABLE_ENTRY(font_helvB12_hr) \
UCG_FONT_TABLE_ENTRY(font_helvB18_hr) \
UCG_FONT_TABLE_ENTRY(font_ncenR12_tr) \
UCG_FONT_TABLE_ENTRY(font_ncenR14_hr)
```
They'll be available as `ucg.<font_name>` in Lua.
####Control a WS2812 based light strip ####Control a WS2812 based light strip
```lua ```lua
-- set the color of one LED on GPIO2 to red -- set the color of one LED on GPIO2 to red
......
...@@ -74,7 +74,7 @@ static int ICACHE_FLASH_ATTR bmp085_init(lua_State* L) { ...@@ -74,7 +74,7 @@ static int ICACHE_FLASH_ATTR bmp085_init(lua_State* L) {
bmp085_data.MC = r16(bmp085_i2c_id, 0xBC); bmp085_data.MC = r16(bmp085_i2c_id, 0xBC);
bmp085_data.MD = r16(bmp085_i2c_id, 0xBE); bmp085_data.MD = r16(bmp085_i2c_id, 0xBE);
return 1; return 0;
} }
static uint32_t bmp085_temperature_raw_b5(void) { static uint32_t bmp085_temperature_raw_b5(void) {
...@@ -128,7 +128,7 @@ static int32_t ICACHE_FLASH_ATTR bmp085_pressure_raw(int oss) { ...@@ -128,7 +128,7 @@ static int32_t ICACHE_FLASH_ATTR bmp085_pressure_raw(int oss) {
p3 = r8u(bmp085_i2c_id, 0xF8); p3 = r8u(bmp085_i2c_id, 0xF8);
p = (p1 << 16) | (p2 << 8) | p3; p = (p1 << 16) | (p2 << 8) | p3;
p = p >> (8 - oss); p = p >> (8 - oss);
return p; return p;
} }
...@@ -159,7 +159,7 @@ static int ICACHE_FLASH_ATTR bmp085_lua_pressure(lua_State* L) { ...@@ -159,7 +159,7 @@ static int ICACHE_FLASH_ATTR bmp085_lua_pressure(lua_State* L) {
oss = 3; oss = 3;
} }
} }
p = bmp085_pressure_raw(oss); p = bmp085_pressure_raw(oss);
B5 = bmp085_temperature_raw_b5(); B5 = bmp085_temperature_raw_b5();
......
blockquote {
padding: 0 15px;
color: #777;
border-left: 4px solid #ddd;
}
.rst-content blockquote {
margin: 0;
}
/*shifts the nested subnav label to the left to align it with the regular nav item labels*/
ul.subnav ul.subnav span {
padding-left: 1.3em;
}
body {
font-size: 100%;
}
p {
line-height: 20px;
margin-bottom: 16px;
}
h1, h2 {
border-bottom: 1px solid #eee;
line-height: 1.2;
margin-top: 1.2em;
margin-bottom: 16px;
}
h3, h4, h5, h6 {
margin: 1em 0 0.7em 0;
}
code {
font-size: 85%;
margin-right: 3px;
}
table.docutils td code {
font-size: 100%;
}
.wy-plain-list-disc, .rst-content .section ul, .rst-content .toctree-wrapper ul, article ul {
line-height: 20px;
margin-bottom: 16px;
}
\ No newline at end of file
# NodeMCU Dokumentation
NodeMCU ist eine [eLua](http://www.eluaproject.net/)-basierende firmware für den [ESP8266 WiFi SOC von Espressif](http://espressif.com/en/products/esp8266/). Dies ist ein Partnerprojekt für die beliebten [NodeMCU dev kits](https://github.com/nodemcu/nodemcu-devkit-v1.0) - open source NodeMCU boards mit ESP8266-12E chips.
Diese firmware nutzt das Espressif NON-OS SDK, das Dateisystem basiert auf [spiffs](https://github.com/pellepl/spiffs).
There are essentially three ways to build your NodeMCU firmware: cloud build service, Docker image, dedicated Linux environment (possibly VM).
## Cloud Build Service
NodeMCU "application developers" just need a ready-made firmware. There's a [cloud build service](http://nodemcu-build.com/) with a nice UI and configuration options for them.
## Docker Image
Occasional NodeMCU firmware hackers don't need full control over the complete tool chain. They might not want to setup a Linux VM with the build environment. Docker to the rescue. Give [Docker NodeMCU build](https://hub.docker.com/r/marcelstoer/nodemcu-build/) a try.
## Linux Build Environment
NodeMCU firmware developers commit or contribute to the project on GitHub and might want to build their own full fledged build environment with the complete tool chain. There is a [post in the esp8266.com Wiki](http://www.esp8266.com/wiki/doku.php?id=toolchain#how_to_setup_a_vm_to_host_your_toolchain) that describes this.
\ No newline at end of file
This diff is collapsed.
Adafruit provides a really nice [firmware flashing tutorial](https://learn.adafruit.com/building-and-running-micropython-on-the-esp8266/flash-firmware). Below you'll find just the basics for the two popular tools esptool and NodeMCU Flasher.
!!! note "Note:"
Keep in mind that the ESP8266 needs to be put into flash mode before you can flash a new firmware!
To enable ESP8266 firmware flashing GPIO0 pin must be pulled low before the device is reset. Conversely, for a normal boot, GPIO0 must be pulled high or floating.
If you have a [NodeMCU dev kit](https://github.com/nodemcu/nodemcu-devkit-v1.0) then you don't need to do anything, as the USB connection can pull GPIO0 low by asserting DTR and reset your board by asserting RTS.
If you have an ESP-01 or other device without built-in USB, you will need to enable flashing yourself by pulling GPIO0 low or pressing a "flash" switch.
## esptool
> A cute Python utility to communicate with the ROM bootloader in Espressif ESP8266. It is intended to be a simple, platform independent, open source replacement for XTCOM.
Source: [https://github.com/themadinventor/esptool](https://github.com/themadinventor/esptool)
Supported platforms: OS X, Linux, Windows, anything that runs Python
**Running esptool.py**
Run the following command to flash an *aggregated* binary as is produced for example by the [cloud build service](build.md#cloud-build-service) or the [Docker image](build.md#docker-image).
`esptool.py --port <USB-port-with-ESP8266> write_flash 0x00000 <nodemcu-firmware>.bin`
## NodeMCU Flasher
> A firmware Flash tool for NodeMCU...We are working on next version and will use QT framework. It will be cross platform and open-source.
Source: [https://github.com/nodemcu/nodemcu-flasher](https://github.com/nodemcu/nodemcu-flasher)
Supported platforms: Windows
\ No newline at end of file
# NodeMCU Documentation
NodeMCU is an [eLua](http://www.eluaproject.net/) based firmware for the [ESP8266 WiFi SOC from Espressif](http://espressif.com/en/products/esp8266/). The firmware is based on the Espressif NON-OS SDK and uses a file system based on [spiffs](https://github.com/pellepl/spiffs). The code repository consists of 98.1% C-code that glues the thin Lua veneer to the SDK.
The NodeMCU *firmware* is a companion project to the popular [NodeMCU dev kits](https://github.com/nodemcu/nodemcu-devkit-v1.0), ready-made open source development boards with ESP8266-12E chips.
## Programming Model
The NodeMCU programming model is similar to that of [Node.js](https://en.wikipedia.org/wiki/Node.js), only in Lua. It is asynchronous and event-driven. Many functions, therefore, have parameters for callback functions. To give you an idea what a NodeMCU program looks like study the short snippets below. For more extensive examples have a look at the `/lua_examples` folder in the repository on GitHub.
```lua
-- a simple HTTP server
srv = net.createServer(net.TCP)
srv:listen(80, function(conn)
conn:on("receive", function(conn, payload)
print(payload)
conn:send("<h1> Hello, NodeMCU.</h1>")
end)
conn:on("sent", function(conn) conn:close() end)
end)
```
```lua
-- connect to WiFi access point
wifi.setmode(wifi.STATION)
wifi.sta.config("SSID", "password")
```
```lua
-- register event callbacks for WiFi events
wifi.sta.eventMonReg(wifi.STA_CONNECTING, function(previous_state)
if(previous_state==wifi.STA_GOTIP) then
print("Station lost connection with access point. Attempting to reconnect...")
else
print("STATION_CONNECTING")
end
end)
```
```lua
-- manipulate hardware like with Arduino
pin = 1
gpio.mode(pin, gpio.OUTPUT)
gpio.write(pin, gpio.HIGH)
print(gpio.read(pin))
```
## Getting Started
1. [Build the firmeware](build.md) with the modules you need.
1. [Flash the firmware](flash.md) to the chip.
1. [Upload code](upload.md) to the firmware.
# ADC Module
The ADC module provides access to the in-built ADC.
On the ESP8266 there is only a single-channel, which is multiplexed with the battery voltage. Depending on the setting in the "esp init data" (byte 107) one can either use the ADC to read an external voltage, or to read the system voltage, but not both.
The default setting in the NodeMCU firmware can be controlled via user_config.h at compile time, by defining one of ESP_INIT_DATA_ENABLE_READVDD33, ESP_INIT_DATA_ENABLE_READADC or ESP_INIT_DATA_FIXED_VDD33_VALUE. To change the setting at a later date, use Espressif's flash download tool to create a new init data block.
## adc.read()
Samples the ADC.
####Syntax
`adc.read(channel)`
####Parameters
`channel` always 0 on the ESP8266
####Returns
the sampled value (number)
####Example
```lua
val = adc.read(0)
```
## adc.readvdd33()
Reads the system voltage.
####Syntax
`adc.readvdd33()`
####Parameters
none
####Returns
system voltage in millivolts (number)
If the ESP8266 has been configured to use the ADC for sampling the external pin, this function will always return 65535. This is a hardware and/or SDK limitation.
\ No newline at end of file
# bit Module
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)
\ No newline at end of file
# BMP085 Module
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
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
```
\ No newline at end of file
# CoAP Module
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
The crypto modules provides various functions for working with cryptographic algorithms.
## 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
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.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
## Constants
`dht.OK` (0), `dht.ERROR_CHECKSUM` (1), `dht.ERROR_TIMEOUT` (2)
## 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_deci,
math.floor(humi),
humi_deci
))
-- 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)
# enduser setup Module
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.
## enduser_setup.start()
Starts the captive portal.
#### Syntax
`enduser_setup.start([onConfigured()], [onError(err_num, string)], [onDebug(string)])`
#### Parameters
- `onConfigured()` 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`
\ No newline at end of file
# file Module
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.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.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 all byte in file
- if pass a number n, then read n bytes from file, or EOF is reached
- if pass a string "str", then read until 'str' or EOF is reached
#### Returns
fdile content in 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 byte 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.
#### Syntax
`file.readline()`
#### Parameters
none
#### Returns
File content in string, line by line, include 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)
\ No newline at end of file
# GPIO Module
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 interrupt support. No pwm/i2c/ow support. **
## gpio.mode()
Initialize pin to GPIO mode, set the pin in/out direction, and optional internal pullup.
#### Syntax
`gpio.mode(pin, mode [, pullup])`
#### Parameters
- `pin` pin to configure, IO index
- `mode` one of gpio.OUTPUT or gpio.INPUT, or gpio.INT(interrupt mode)
- `pullup` gpio.PULLUP or gpio.FLOAT; 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 a callback function to run on interrupt for a pin.
There is currently no support for unregistering the callback.
This function is not available if GPIO_INTERRUPT_ENABLE was undefined at compile time.
#### Syntax
`gpio.trig(pin, type [, function(level)])`
#### Parameters
- `pin` **1~12**, IO index, pin D0 does not support interrupt.
- `type` "up", "down", "both", "low", "high", which represent rising edge, falling edge, both edge, low level, high level trig mode correspondingly.
- `function(level)` callback function when triggered. The gpio level is the param. Use previous callback function if undefined here.
#### Returns
`nil`
#### Example
```lua
-- use pin 1 as the input pulse width counter
pin = 1
pulse1 = 0
du = 0
gpio.mode(pin,gpio.INT)
function pin1cb(level)
du = tmr.now() - pulse1
print(du)
pulse1 = tmr.now()
if level == gpio.HIGH then gpio.trig(pin, "down") else gpio.trig(pin, "up") end
end
gpio.trig(pin, "down", pin1cb)
```
#### 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)
\ No newline at end of file
# HTTP Module
Basic HTTP client module.
Provides an interface to do basic 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 to 1k. Attempting to receive pages larger than this limit will fail. If larger page/body sizes are necessary, consider using `net.createConnection()` and stream in the data.
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`.
Note that 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 behaviour.
#### See also
- [`net.createConnection()`](#netcreateconnection)
## http.delete()
Executes a HTTP delete request.
#### 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('https://connor.example.com/john',
"",
"",
function(code, data)
if (code < 0)
print("HTTP request failed")
else
print(code, data)
end
end)
```
## http.get()
Executes a HTTP GET request.
#### 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("https://www.vowstar.com/nodemcu/", nil, function(code, data)
if (code < 0)
print("HTTP request failed")
else
print(code, data)
end
end)
```
## http.post()
Executes a HTTP POST request.
#### 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://json.example.com/something',
'Content-Type: application/json\r\n',
'{"hello":"world"}',
function(code, data)
if (code < 0)
print("HTTP request failed")
else
print(code, data)
end
end)
```
## http.put()
Executes a HTTP PUT request.
#### 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://db.example.com/items.php?key=deckard',
'Content-Type: text/plain\r\n',
'Hello!\nStay a while, and listen...\n',
function(code, data)
if (code < 0)
print("HTTP request failed")
else
print(code, data)
end
end)
```
## http.request()
Execute a custom HTTP request for any HTTP method.
#### 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("https://www.example.com", "HEAD", "", "", function(code, data)
function(code, data)
if (code < 0)
print("HTTP request failed")
else
print(code, data)
end
end)
```
# HX711 Module
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)
```
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