Merge branch 'dev' into mqtt-connack

This commit is contained in:
jfollas 2016-03-17 19:59:02 -04:00
commit 354b9e9684
60 changed files with 1007 additions and 318 deletions

1
.gitignore vendored
View File

@ -1,3 +1,4 @@
sdk/
cache/
user_config.h
server-ca.crt

View File

@ -132,7 +132,7 @@ CCFLAGS += \
# -Wall
ifneq ($(wildcard $(TOP_DIR)/user_config.h),)
INCLUDES := $(INCLUDES) -include "$(TOP_DIR)/user_config.h"
INCLUDES += -include "$(TOP_DIR)/user_config.h"
endif
CFLAGS = $(CCFLAGS) $(DEFINES) $(EXTRA_CCFLAGS) $(STD_CFLAGS) $(INCLUDES)
@ -175,7 +175,7 @@ $(BINODIR)/%.bin: $(IMAGEODIR)/%.out
# Should be done in top-level makefile only
#
all: sdk_extracted .subdirs $(OBJS) $(OLIBS) $(OIMAGES) $(OBINS) $(SPECIAL_MKTARGETS)
all: sdk_extracted pre_build .subdirs $(OBJS) $(OLIBS) $(OIMAGES) $(OBINS) $(SPECIAL_MKTARGETS)
.PHONY: sdk_extracted
@ -222,6 +222,18 @@ endif
endif
endif
.PHONY: pre_build
ifneq ($(wildcard $(TOP_DIR)/server-ca.crt),)
pre_build:
python $(TOP_DIR)/tools/make_server_cert.py $(TOP_DIR)/server-ca.crt > $(TOP_DIR)/app/modules/server-ca.crt.h
DEFINES += -DHAVE_SSL_SERVER_CRT=\"server-ca.crt.h\"
else
pre_build:
@-rm -f $(TOP_DIR)/app/modules/server-ca.crt.h
endif
$(OBJODIR)/%.o: %.c
@mkdir -p $(OBJODIR);
$(CC) $(if $(findstring $<,$(DSRCS)),$(DFLAGS),$(CFLAGS)) $(COPTS_$(*F)) -o $@ -c $<

View File

@ -64,7 +64,7 @@ The following sections explain some of the options you have if you want to [buil
### Select Modules
Disable modules you won't be using to reduce firmware size and free up some RAM. The ESP8266 is quite limited in available RAM and running out of memory can cause a system panic.
Disable modules you won't be using to reduce firmware size and free up some RAM. The ESP8266 is quite limited in available RAM and running out of memory can cause a system panic. The default configuration is designed to run on all ESP modules including the 512 KB modules like ESP-01 and only includes general purpose interface modules which require at most two GPIO pins.
Edit `app/include/user_modules.h` and comment-out the `#define` statement for modules you don't need. Example:
@ -89,8 +89,8 @@ Identify your firmware builds by editing `app/include/user_version.h`
### Set UART Bit Rate
The initial baud rate at boot time is 9600bps. You can change this by
editing `BIT_RATE_DEFAULT` in `app/include/user_config.h`:
The initial baud rate at boot time is 115200bps. You can change this by
editing `BIT_RATE_DEFAULT` in `app/include/user_config.h`:
```c
#define BIT_RATE_DEFAULT BIT_RATE_115200
@ -103,5 +103,3 @@ To enable runtime debug messages to serial console edit `app/include/user_config
```c
#define DEVELOP_VERSION
```
`DEVELOP_VERSION` changes the startup baud rate to 74880bps.

View File

@ -437,10 +437,10 @@ static void ICACHE_FLASH_ATTR http_dns_callback( const char * hostname, ip_addr_
{
HTTPCLIENT_DEBUG( "DNS found %s " IPSTR "\n", hostname, IP2STR( addr ) );
struct espconn * conn = (struct espconn *) os_malloc( sizeof(struct espconn) );
struct espconn * conn = (struct espconn *) os_zalloc( sizeof(struct espconn) );
conn->type = ESPCONN_TCP;
conn->state = ESPCONN_NONE;
conn->proto.tcp = (esp_tcp *) os_malloc( sizeof(esp_tcp) );
conn->proto.tcp = (esp_tcp *) os_zalloc( sizeof(esp_tcp) );
conn->proto.tcp->local_port = espconn_port();
conn->proto.tcp->remote_port = req->port;
conn->reverse = req;
@ -473,7 +473,7 @@ void ICACHE_FLASH_ATTR http_raw_request( const char * hostname, int port, bool s
{
HTTPCLIENT_DEBUG( "DNS request\n" );
request_args_t * req = (request_args_t *) os_malloc( sizeof(request_args_t) );
request_args_t * req = (request_args_t *) os_zalloc( sizeof(request_args_t) );
req->hostname = esp_strdup( hostname );
req->port = port;
req->secure = secure;
@ -558,6 +558,11 @@ void ICACHE_FLASH_ATTR http_request( const char * url, const char * method, cons
colon = NULL; /* Limit the search to characters before the path. */
}
if (path - url >= sizeof(hostname)) {
HTTPCLIENT_DEBUG( "hostname is too long %s\n", url );
return;
}
if ( colon == NULL ) /* The port is not present. */
{
os_memcpy( hostname, url, path - url );

View File

@ -21,9 +21,8 @@
#ifdef DEVELOP_VERSION
#define NODE_DEBUG
#define COAP_DEBUG
#define BIT_RATE_DEFAULT BIT_RATE_74880
#else
#define BIT_RATE_DEFAULT BIT_RATE_9600
#define BIT_RATE_DEFAULT BIT_RATE_115200
#endif /* DEVELOP_VERSION */
@ -54,7 +53,7 @@
#define NO_INTR_CODE inline
#endif
#define CLIENT_SSL_ENABLE
//#define CLIENT_SSL_ENABLE
//#define MD2_ENABLE
#define SHA2_ENABLE

View File

@ -13,21 +13,25 @@
#ifndef LUA_CROSS_COMPILER
// The default configuration is designed to run on all ESP modules including the 512 KB modules like ESP-01 and only
// includes general purpose interface modules which require at most two GPIO pins.
// See https://github.com/nodemcu/nodemcu-firmware/pull/1127 for discussions.
// New modules should be disabled by default and added in alphabetical order.
#define LUA_USE_MODULES_ADC
//#define LUA_USE_MODULES_AM2320
//#define LUA_USE_MODULES_APA102
#define LUA_USE_MODULES_BIT
//#define LUA_USE_MODULES_BMP085
//#define LUA_USE_MODULES_BME280
#define LUA_USE_MODULES_CJSON
#define LUA_USE_MODULES_COAP
#define LUA_USE_MODULES_CRYPTO
//#define LUA_USE_MODULES_CJSON
//#define LUA_USE_MODULES_COAP
//#define LUA_USE_MODULES_CRYPTO
#define LUA_USE_MODULES_DHT
#define LUA_USE_MODULES_ENCODER
//#define LUA_USE_MODULES_ENCODER
//#define LUA_USE_MODULES_ENDUSER_SETUP // USE_DNS in dhcpserver.h needs to be enabled for this module to work.
#define LUA_USE_MODULES_FILE
#define LUA_USE_MODULES_GPIO
#define LUA_USE_MODULES_HTTP
//#define LUA_USE_MODULES_HTTP
//#define LUA_USE_MODULES_HX711
#define LUA_USE_MODULES_I2C
//#define LUA_USE_MODULES_MDNS
@ -36,24 +40,24 @@
#define LUA_USE_MODULES_NODE
#define LUA_USE_MODULES_OW
//#define LUA_USE_MODULES_PERF
#define LUA_USE_MODULES_PWM
#define LUA_USE_MODULES_RC
//#define LUA_USE_MODULES_PWM
//#define LUA_USE_MODULES_RC
//#define LUA_USE_MODULES_ROTARY
#define LUA_USE_MODULES_RTCFIFO
#define LUA_USE_MODULES_RTCMEM
#define LUA_USE_MODULES_RTCTIME
//#define LUA_USE_MODULES_RTCFIFO
//#define LUA_USE_MODULES_RTCMEM
//#define LUA_USE_MODULES_RTCTIME
//#define LUA_USE_MODULES_SIGMA_DELTA
#define LUA_USE_MODULES_SNTP
//#define LUA_USE_MODULES_SNTP
#define LUA_USE_MODULES_SPI
//#define LUA_USE_MODULES_STRUCT
#define LUA_USE_MODULES_TMR
#define LUA_USE_MODULES_TSL2561
#define LUA_USE_MODULES_U8G
//#define LUA_USE_MODULES_TSL2561
//#define LUA_USE_MODULES_U8G
#define LUA_USE_MODULES_UART
//#define LUA_USE_MODULES_UCG
#define LUA_USE_MODULES_WIFI
//#define LUA_USE_MODULES_WS2801
#define LUA_USE_MODULES_WS2812
//#define LUA_USE_MODULES_WS2812
#endif /* LUA_CROSS_COMPILER */

View File

@ -468,7 +468,7 @@ int lua_main (int argc, char **argv) {
void lua_handle_input (bool force)
{
if (force || readline (&gLoad))
if (gLoad.L && (force || readline (&gLoad)))
dojob (&gLoad);
}

1
app/modules/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
server-ca.crt.h

View File

@ -3,6 +3,7 @@
#include "module.h"
#include "lauxlib.h"
#include "platform.h"
#include "lmem.h"
#include "c_string.h"
#include "c_stdlib.h"
@ -13,18 +14,19 @@
#include "espconn.h"
#include "lwip/dns.h"
#ifdef CLIENT_SSL_ENABLE
unsigned char *default_certificate;
unsigned int default_certificate_len = 0;
unsigned char *default_private_key;
unsigned int default_private_key_len = 0;
#endif
#define TCP ESPCONN_TCP
#define UDP ESPCONN_UDP
static ip_addr_t host_ip; // for dns
#ifdef HAVE_SSL_SERVER_CRT
#include HAVE_SSL_SERVER_CRT
#else
__attribute__((section(".servercert.flash"))) unsigned char net_server_cert_area[INTERNAL_FLASH_SECTOR_SIZE];
#endif
__attribute__((section(".clientcert.flash"))) unsigned char net_client_cert_area[INTERNAL_FLASH_SECTOR_SIZE];
#if 0
static int expose_array(lua_State* L, char *array, unsigned short len);
#endif
@ -1432,6 +1434,201 @@ static int net_multicastLeave( lua_State* L )
return net_multicastJoinLeave(L,0);
}
// Returns NULL on success, error message otherwise
static const char *append_pem_blob(const char *pem, const char *type, uint8_t **buffer_p, uint8_t *buffer_limit, const char *name) {
char unb64[256];
memset(unb64, 0xff, sizeof(unb64));
int i;
for (i = 0; i < 64; i++) {
unb64["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[i]] = i;
}
if (!pem) {
return "No PEM blob";
}
// Scan for -----BEGIN CERT
pem = strstr(pem, "-----BEGIN ");
if (!pem) {
return "No PEM header";
}
if (strncmp(pem + 11, type, strlen(type))) {
return "Wrong PEM type";
}
pem = strchr(pem, '\n');
if (!pem) {
return "Incorrect PEM format";
}
//
// Base64 encoded data starts here
// Get all the base64 data into a single buffer....
// We will use the back end of the buffer....
//
uint8_t *buffer = *buffer_p;
uint8_t *dest = buffer + 32 + 2; // Leave space for name and length
int bitcount = 0;
int accumulator = 0;
for (; *pem && dest < buffer_limit; pem++) {
int val = unb64[*(uint8_t*) pem];
if (val & 0xC0) {
// not a base64 character
if (isspace(*(uint8_t*) pem)) {
continue;
}
if (*pem == '=') {
// just ignore -- at the end
bitcount = 0;
continue;
}
if (*pem == '-') {
break;
}
return "Invalid character in PEM";
} else {
bitcount += 6;
accumulator = (accumulator << 6) + val;
if (bitcount >= 8) {
bitcount -= 8;
*dest++ = accumulator >> bitcount;
}
}
}
if (dest >= buffer_limit || strncmp(pem, "-----END ", 9) || strncmp(pem + 9, type, strlen(type)) || bitcount) {
return "Invalid PEM format data";
}
size_t len = dest - (buffer + 32 + 2);
memset(buffer, 0, 32);
strcpy(buffer, name);
buffer[32] = len & 0xff;
buffer[33] = (len >> 8) & 0xff;
*buffer_p = dest;
return NULL;
}
static const char *fill_page_with_pem(lua_State *L, const unsigned char *flash_memory, int flash_offset, const char **types, const char **names)
{
uint8_t *buffer = luaM_malloc(L, INTERNAL_FLASH_SECTOR_SIZE);
uint8_t *buffer_base = buffer;
uint8_t *buffer_limit = buffer + INTERNAL_FLASH_SECTOR_SIZE;
int argno;
for (argno = 1; argno <= lua_gettop(L) && types[argno - 1]; argno++) {
const char *pem = lua_tostring(L, argno);
const char *error = append_pem_blob(pem, types[argno - 1], &buffer, buffer_limit, names[argno - 1]);
if (error) {
luaM_free(L, buffer_base);
return error;
}
}
memset(buffer, 0xff, buffer_limit - buffer);
// Lets see if it matches what is already there....
if (c_memcmp(buffer_base, flash_memory, INTERNAL_FLASH_SECTOR_SIZE) != 0) {
// Starts being dangerous
if (platform_flash_erase_sector(flash_offset / INTERNAL_FLASH_SECTOR_SIZE) != PLATFORM_OK) {
luaM_free(L, buffer_base);
return "Failed to erase sector";
}
if (platform_s_flash_write(buffer_base, flash_offset, INTERNAL_FLASH_SECTOR_SIZE) != INTERNAL_FLASH_SECTOR_SIZE) {
luaM_free(L, buffer_base);
return "Failed to write sector";
}
// ends being dangerous
}
luaM_free(L, buffer_base);
return NULL;
}
// Lua: net.cert.auth(true / false | PEM data [, PEM data] )
static int net_cert_auth(lua_State *L)
{
int enable;
uint32_t flash_offset = platform_flash_mapped2phys((uint32_t) &net_client_cert_area[0]);
if ((flash_offset & 0xfff) || flash_offset > 0xff000 || INTERNAL_FLASH_SECTOR_SIZE != 0x1000) {
// THis should never happen
return luaL_error( L, "bad offset" );
}
if (lua_type(L, 1) == LUA_TSTRING) {
const char *types[3] = { "CERTIFICATE", "RSA PRIVATE KEY", NULL };
const char *names[2] = { "certificate", "private_key" };
const char *error = fill_page_with_pem(L, &net_client_cert_area[0], flash_offset, types, names);
if (error) {
return luaL_error(L, error);
}
enable = 1;
} else {
enable = lua_toboolean(L, 1);
}
bool rc;
if (enable) {
// See if there is a cert there
if (net_client_cert_area[0] == 0x00 || net_client_cert_area[0] == 0xff) {
return luaL_error( L, "no certificates found" );
}
rc = espconn_secure_cert_req_enable(1, flash_offset / INTERNAL_FLASH_SECTOR_SIZE);
} else {
rc = espconn_secure_cert_req_disable(1);
}
lua_pushboolean(L, rc);
return 1;
}
// Lua: net.cert.verify(true / false | PEM data [, PEM data] )
static int net_cert_verify(lua_State *L)
{
int enable;
uint32_t flash_offset = platform_flash_mapped2phys((uint32_t) &net_server_cert_area[0]);
if ((flash_offset & 0xfff) || flash_offset > 0xff000 || INTERNAL_FLASH_SECTOR_SIZE != 0x1000) {
// THis should never happen
return luaL_error( L, "bad offset" );
}
if (lua_type(L, 1) == LUA_TSTRING) {
const char *types[2] = { "CERTIFICATE", NULL };
const char *names[1] = { "certificate" };
const char *error = fill_page_with_pem(L, &net_server_cert_area[0], flash_offset, types, names);
if (error) {
return luaL_error(L, error);
}
enable = 1;
} else {
enable = lua_toboolean(L, 1);
}
bool rc;
if (enable) {
// See if there is a cert there
if (net_server_cert_area[0] == 0x00 || net_server_cert_area[0] == 0xff) {
return luaL_error( L, "no certificates found" );
}
rc = espconn_secure_ca_enable(1, flash_offset / INTERNAL_FLASH_SECTOR_SIZE);
} else {
rc = espconn_secure_ca_disable(1);
}
lua_pushboolean(L, rc);
return 1;
}
// Lua: s = net.dns.setdnsserver(ip_addr, [index])
static int net_setdnsserver( lua_State* L )
@ -1539,6 +1736,14 @@ static const LUA_REG_TYPE net_array_map[] = {
};
#endif
static const LUA_REG_TYPE net_cert_map[] = {
{ LSTRKEY( "verify" ), LFUNCVAL( net_cert_verify ) },
#ifdef CLIENT_SSL_CERT_AUTH_ENABLE
{ LSTRKEY( "auth" ), LFUNCVAL( net_cert_auth ) },
#endif
{ LNILKEY, LNILVAL }
};
static const LUA_REG_TYPE net_dns_map[] = {
{ LSTRKEY( "setdnsserver" ), LFUNCVAL( net_setdnsserver ) },
{ LSTRKEY( "getdnsserver" ), LFUNCVAL( net_getdnsserver ) },
@ -1552,6 +1757,9 @@ static const LUA_REG_TYPE net_map[] = {
{ LSTRKEY( "multicastJoin"), LFUNCVAL( net_multicastJoin ) },
{ LSTRKEY( "multicastLeave"), LFUNCVAL( net_multicastLeave ) },
{ LSTRKEY( "dns" ), LROVAL( net_dns_map ) },
#ifdef CLIENT_SSL_ENABLE
{ LSTRKEY( "cert" ), LROVAL(net_cert_map) },
#endif
{ LSTRKEY( "TCP" ), LNUMVAL( TCP ) },
{ LSTRKEY( "UDP" ), LNUMVAL( UDP ) },
{ LSTRKEY( "__metatable" ), LROVAL( net_map ) },

View File

@ -94,6 +94,8 @@ typedef struct
static sntp_state_t *state;
static ip_addr_t server;
static void on_timeout (void *arg);
static void cleanup (lua_State *L)
{
os_timer_disarm (&state->timer);
@ -121,6 +123,13 @@ static void handle_error (lua_State *L)
static void sntp_dosend (lua_State *L)
{
if (state->attempts == 0)
{
os_timer_disarm (&state->timer);
os_timer_setfn (&state->timer, on_timeout, NULL);
os_timer_arm (&state->timer, 1000, 1);
}
++state->attempts;
sntp_dbg("sntp: attempt %d\n", state->attempts);
@ -153,7 +162,9 @@ static void sntp_dosend (lua_State *L)
static void sntp_dns_found(const char *name, ip_addr_t *ipaddr, void *arg)
{
lua_State *L = arg;
(void)arg;
lua_State *L = lua_getstate ();
if (ipaddr == NULL)
{
NODE_ERR("DNS Fail!\n");
@ -169,8 +180,9 @@ static void sntp_dns_found(const char *name, ip_addr_t *ipaddr, void *arg)
static void on_timeout (void *arg)
{
(void)arg;
sntp_dbg("sntp: timer\n");
lua_State *L = arg;
lua_State *L = lua_getstate ();
if (state->attempts >= MAX_ATTEMPTS)
handle_error (L);
else
@ -341,10 +353,6 @@ static int sntp_sync (lua_State *L)
else
state->err_cb_ref = LUA_NOREF;
os_timer_disarm (&state->timer);
os_timer_setfn (&state->timer, on_timeout, L);
os_timer_arm (&state->timer, 1000, 1);
state->attempts = 0;
// use last server, unless new one specified
@ -354,7 +362,7 @@ static int sntp_sync (lua_State *L)
const char *hostname = luaL_checklstring(L, 1, &l);
if (l>128 || hostname == NULL)
sync_err("need <128 hostname");
err_t err = dns_gethostbyname(hostname, &server, sntp_dns_found, &L);
err_t err = dns_gethostbyname(hostname, &server, sntp_dns_found, state);
if (err == ERR_INPROGRESS)
return 0; // Callback function sntp_dns_found will handle sntp_dosend for us
else if (err == ERR_ARG)

View File

@ -1,5 +1,9 @@
There are essentially three ways to build your NodeMCU firmware: cloud build service, Docker image, dedicated Linux environment (possibly VM).
**Building manually**
Note that the *default configuration in the C header files* (`user_config.h`, `user_modules.h`) is designed to run on all ESP modules including the 512 KB modules like ESP-01 and only includes general purpose interface modules which require at most two GPIO pins.
## 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.

View File

@ -1,4 +1,8 @@
# ADC Module
| Since | Origin / Contributor | Maintainer | Source |
| :----- | :-------------------- | :---------- | :------ |
| 2014-12-24 | [Zeroday](https://github.com/funshine) | [Zeroday](https://github.com/funshine) | [adc.c](../../../app/modules/adc.c)|
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.
@ -36,4 +40,4 @@ 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.
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.

View File

@ -1,4 +1,8 @@
# AM2320 Module
| Since | Origin / Contributor | Maintainer | Source |
| :----- | :-------------------- | :---------- | :------ |
| 2016-02-14 | [Henk Vergonet](https://github.com/hvegh) | [Henk Vergonet](https://github.com/hvegh) | [am2320.c](../../../app/modules/am2320.c)|
This module provides access to the [AM2320](https://akizukidenshi.com/download/ds/aosong/AM2320.pdf) humidity and temperature sensor, using the i2c interface.

View File

@ -1,4 +1,8 @@
# 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.

View File

@ -1,4 +1,8 @@
# 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.
@ -167,4 +171,4 @@ Set bits in a number.
- `...posn` position of the nth bit to set.
####Returns
the number with the bit(s) set in the given position(s)
the number with the bit(s) set in the given position(s)

View File

@ -1,4 +1,7 @@
# 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).

View File

@ -1,4 +1,8 @@
# 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.

View File

@ -1,4 +1,7 @@
# 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.
@ -46,4 +49,4 @@ Lua table representation of the JSON data
```lua
t = cjson.decode('{"key":"value"}')
for k,v in pairs(t) do print(k,v) end
```
```

View File

@ -1,224 +1,228 @@
# 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.
# 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.
```
`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.
```

View File

@ -1,4 +1,7 @@
# 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.

View File

@ -1,4 +1,7 @@
# 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.

View File

@ -1,4 +1,7 @@
# 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.

View File

@ -1,4 +1,8 @@
# 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")

View File

@ -1,4 +1,8 @@
# 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.

View File

@ -1,4 +1,8 @@
# 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.

View File

@ -1,8 +1,11 @@
# HTTP Module
| Since | Origin / Contributor | Maintainer | Source |
| :----- | :-------------------- | :---------- | :------ |
| 2016-01-15 | [Vowstar](https://github.com/vowstar) | [Vowstar](https://github.com/vowstar) | [http.c](../../../app/modules/http.c)|
Basic HTTP client 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 by available memory. Attempting to receive pages larger than this will fail. If larger page/body sizes are necessary, consider using `net.createConnection()` and stream in the data.
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 by available memory. Attempting to receive pages larger than this will fail. If larger page/body sizes are necessary, consider using [`net.createConnection()`](#netcreateconnection) 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).
@ -13,10 +16,7 @@ For each operation it is also possible to include custom headers. Note that foll
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)
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 behavior.
## http.delete()

View File

@ -1,4 +1,7 @@
# 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.

View File

@ -1,4 +1,7 @@
# 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.

View File

@ -1,4 +1,7 @@
# 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.

View File

@ -1,4 +1,8 @@
# 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.

View File

@ -1,7 +1,11 @@
# 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)|
## Constants
`net.TCP`, `net.UDP`
Constants to be used in other functions: `net.TCP`, `net.UDP`
## net.createConnection()
@ -282,3 +286,100 @@ Sets the IP of the DNS server used to resolve hostnames. Default: resolver1.open
#### 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.

View File

@ -1,4 +1,8 @@
# 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()

View File

@ -1,4 +1,7 @@
# 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.

View File

@ -1,12 +1,11 @@
# perf Module
| Since | Origin / Contributor | Maintainer | Source |
| :----- | :-------------------- | :---------- | :------ |
| 2016-02-26 | [Philip Gladstone](https://github.com/pjsg) | [Philip Gladstone](https://github.com/pjsg) | [perf.c](../../../app/modules/perf.c)|
This module provides simple performance measurement for an application.
It samples the program counter roughly every 50 microseconds and builds
a histogram of the values that it finds. Since there is only a small amount
of memory to store the histogram, the user can specify which area of code
is of interest. The default is the enitre flash which contains code. Once the hotspots are
identified, then the run can then be repeated with different areas and at different
resolutions to get as much information as required.
This module provides simple performance measurement for an application. It samples the program counter roughly every 50 microseconds and builds a histogram of the values that it finds. Since there is only a small amount
of memory to store the histogram, the user can specify which area of code is of interest. The default is the entire flash which contains code. Once the hotspots are identified, then the run can then be repeated with different areas and at different resolutions to get as much information as required.
## perf.start()
Starts a performance monitoring session.

View File

@ -1,4 +1,7 @@
# PWM Module
| Since | Origin / Contributor | Maintainer | Source |
| :----- | :-------------------- | :---------- | :------ |
| 2014-12-22 | [Zeroday](https://github.com/funshine) | [Zeroday](https://github.com/funshine) | [pwm.c](../../../app/modules/pwm.c)|
## pwm.close()
Quit PWM mode for the specified GPIO pin.

4
docs/en/modules/rc.md Normal file
View File

@ -0,0 +1,4 @@
# RC Module
| Since | Origin / Contributor | Maintainer | Source |
| :----- | :-------------------- | :---------- | :------ |
| 2015-06-12 | [Mike Wen](https://github.com/mikewen) | - | [rc.c](../../../app/modules/rc.c)|

View File

@ -1,14 +1,12 @@
# rotary Module
| Since | Origin / Contributor | Maintainer | Source |
| :----- | :-------------------- | :---------- | :------ |
| 2016-03-01 | [Philip Gladstone](https://github.com/pjsg) | [Philip Gladstone](https://github.com/pjsg) | [rotary.c](../../../app/modules/rotary.c)|
This module can read the state of cheap rotary encoder switches. These are available at
all the standard places for a dollar or two. They are five pin devices where three are used
for a gray code encoder for rotation, and two are used for the push switch. These switches
are commonly used in car audio systems.
These switches do not have absolute positioning, but only encode the number of positions
rotated clockwise / anticlockwise. To make use of this module, connect the common pin on the quadrature
encoder to ground and the A and B phases to the nodemcu. One pin of the push switch should
also be grounded and the other pin connected to the nodemcu.
This module can read the state of cheap rotary encoder switches. These are available at all the standard places for a dollar or two. They are five pin devices where three are used for a gray code encoder for rotation, and two are used for the push switch. These switches are commonly used in car audio systems.
These switches do not have absolute positioning, but only encode the number of positions rotated clockwise / anti-clockwise. To make use of this module, connect the common pin on the quadrature encoder to ground and the A and B phases to the NodeMCU. One pin of the push switch should also be grounded and the other pin connected to the NodeMCU.
## Sources for parts

View File

@ -1,4 +1,7 @@
# rtcfifo Module
# RTC FIFO Module
| Since | Origin / Contributor | Maintainer | Source |
| :----- | :-------------------- | :---------- | :------ |
| 2015-06-26 | [DiUS](https://github.com/DiUS), [Johny Mattsson](https://github.com/jmattsson), Bernd Meyer <bmeyer@dius.com.au> | [Johny Mattsson](https://github.com/jmattsson) | [rtcfifo.c](../../../app/modules/rtcfifo.c)|
The rtcfifo module implements a first-in,first-out storage intended for sensor readings. As the name suggests, it is backed by the [RTC](https://en.wikipedia.org/wiki/Real-time_clock) user memory and as such survives deep sleep cycles. Conceptually it can be thought of as a cyclic array of `{ timestamp, name, value }` tuples. Internally it uses a space-optimized storage format to allow the greatest number of samples to be kept. This comes with several trade-offs, and as such is not a one-solution-fits-all. Notably:
- Timestamps are stored with second-precision.

View File

@ -1,4 +1,8 @@
# rtcmem Module
# RTC User Memory Module
| Since | Origin / Contributor | Maintainer | Source |
| :----- | :-------------------- | :---------- | :------ |
| 2015-06-25 | [DiUS](https://github.com/DiUS), [Johny Mattsson](https://github.com/jmattsson) | [Johny Mattsson](https://github.com/jmattsson) | [rtcmem.c](../../../app/modules/rtcmem.c)|
The rtcmem module provides basic access to the [RTC](https://en.wikipedia.org/wiki/Real-time_clock) (Real Time Clock) memory.
The RTC in the ESP8266 contains memory registers which survive a deep sleep, making them highly useful for keeping state across sleep cycles. Some of this memory is reserved for system use, but 128 slots (each 32bit wide) are available for application use. This module provides read and write access to these.

View File

@ -1,4 +1,7 @@
# rtctime Module
# RTC Time Module
| Since | Origin / Contributor | Maintainer | Source |
| :----- | :-------------------- | :---------- | :------ |
| 2015-06-25 | [DiUS](https://github.com/DiUS), [Johny Mattsson](https://github.com/jmattsson), Bernd Meyer <bmeyer@dius.com.au> | [Johny Mattsson](https://github.com/jmattsson) | [rtctime.c](../../../app/modules/rtctime.c)|
The rtctime module provides advanced timekeeping support for NodeMCU, including keeping time across deep sleep cycles (provided [`rtctime.dsleep()`](#rtctimedsleep) is used instead of [`node.dsleep()`](node.md#nodedsleep)). This can be used to significantly extend battery life on battery powered sensor nodes, as it is no longer necessary to fire up the RF module each wake-up in order to obtain an accurate timestamp.

View File

@ -1,5 +1,9 @@
# sigma delta Module
This module provides access to the sigma-delta component. It's a hardware signal generator that can be routed to any of the GPIOs except pin 0.
# Sigma-delta Module
| Since | Origin / Contributor | Maintainer | Source |
| :----- | :-------------------- | :---------- | :------ |
| 2016-02-20 | [Arnim Läuger](https://github.com/devsaurus), [Espressif example](http://bbs.espressif.com/viewtopic.php?t=49) | [Arnim Läuger](https://github.com/devsaurus) | [sigma_delta.c](../../../app/modules/sigma_delta.c)|
This module provides access to the [sigma-delta](https://en.wikipedia.org/wiki/Delta-sigma_modulation) component. It's a hardware signal generator that can be routed to any of the GPIOs except pin 0.
The signal generation is controlled by the [`setprescale()`](#sigma_deltasetprescale) and [`settarget()`](#sigma_deltasettarget) functions.

View File

@ -1,4 +1,7 @@
# SNTP Module
| Since | Origin / Contributor | Maintainer | Source |
| :----- | :-------------------- | :---------- | :------ |
| 2015-06-30 | [DiUS](https://github.com/DiUS), [Johny Mattsson](https://github.com/jmattsson) | [Johny Mattsson](https://github.com/jmattsson) | [sntp.c](../../../app/modules/sntp.c)|
The SNTP module implements a [Simple Network Time Procotol](https://en.wikipedia.org/wiki/Network_Time_Protocol#SNTP) client. This includes support for the "anycast" [NTP](https://en.wikipedia.org/wiki/Network_Time_Protocol) mode where, if supported by the NTP server(s) in your network, it is not necessary to even know the IP address of the NTP server.

View File

@ -1,4 +1,8 @@
# SPI Module
| Since | Origin / Contributor | Maintainer | Source |
| :----- | :-------------------- | :---------- | :------ |
| 2015-01-16 | [Ibrahim Abd Elkader](https://github.com/iabdalkader) | [Arnim Läuger](https://github.com/devsaurus) | [spi.c](../../../app/modules/spi.c)|
All transactions for sending and receiving are most-significant-bit first and least-significant last.
For technical details of the underlying hardware refer to [metalphreak's ESP8266 HSPI articles](http://d.av.id.au/blog/tag/hspi/).

View File

@ -1,20 +1,13 @@
# struct module
# Struct Module
| Since | Origin / Contributor | Maintainer | Source |
| :----- | :-------------------- | :---------- | :------ |
| 2015-02-13 | [Roberto Ierusalimschy](http://www.inf.puc-rio.br/~roberto/struct/), [Philip Gladstone](https://github.com/pjsg) | [Philip Gladstone](https://github.com/pjsg) | [struct.c](../../../app/modules/struct.c)|
This module offers basic facilities to convert Lua values to and from C
structs. Its main functions are `struct.pack`, which packs multiple Lua
values into a struct-like string; and `struct.unpack`, which unpacks
multiple Lua values from a given struct-like string.
This module offers basic facilities to convert Lua values to and from C structs. Its main functions are `struct.pack`, which packs multiple Lua values into a struct-like string; and `struct.unpack`, which unpacks multiple Lua values from a given struct-like string.
The first argument to both functions is a *format string*, which
describes the layout of the structure. The format string is a sequence
of conversion elements, which respect the current endianess and the
current alignment requirements. Initially, the current endianess is the
machine's native endianness and the current alignment requirement is 1
(meaning no alignment at all). You can change these settings with
appropriate directives in the format string.
The first argument to both functions is a *format string*, which describes the layout of the structure. The format string is a sequence of conversion elements, which respect the current endianess and the current alignment requirements. Initially, the current endianess is the machine's native endianness and the current alignment requirement is 1 (meaning no alignment at all). You can change these settings with appropriate directives in the format string.
Note that the float and double conversions are only available with
a floating point NodeMCU build.
Note that the float and double conversions are only available with a floating point NodeMCU build.
### Format String

View File

@ -1,4 +1,7 @@
# tmr Module
# Timer Module
| Since | Origin / Contributor | Maintainer | Source |
| :----- | :-------------------- | :---------- | :------ |
| 2014-12-12 | [Zeroday](https://github.com/funshine) | [dnc40085](https://github.com/dnc40085) | [tmr.c](../../../app/modules/tmr.c)|
The tmr module allows access to simple timers, the system counter and uptime.

View File

@ -1,4 +1,7 @@
# TSL2561 Module
| Since | Origin / Contributor | Maintainer | Source |
| :----- | :-------------------- | :---------- | :------ |
| 2015-08-22 | [Michael Lucas](https://github.com/Aeprox) | [Michael Lucas](https://github.com/Aeprox) | [tsl2561.c](../../../app/modules/tsl2561.c)|
## tsl2561.getlux()
Reads sensor values from the device and returns calculated lux value.
@ -128,4 +131,4 @@ if status == tsl2561.TSL2561_OK then
lux = tsl2561.getlux()
print("Illuminance: "..lux.." lx")
end
```
```

View File

@ -1,4 +1,8 @@
# u8g Module
| Since | Origin / Contributor | Maintainer | Source |
| :----- | :-------------------- | :---------- | :------ |
| 2015-01-30 | [Oli Kraus](https://github.com/olikraus/u8glib), [Arnim Läuger](https://github.com/devsaurus) | [Arnim Läuger](https://github.com/devsaurus) | [u8glib](../../../app/u8glib/)|
U8glib is a graphics library developed at [olikraus/u8glib](https://github.com/olikraus/u8glib) with support for many different displays. The NodeMCU firmware supports a subset of these.
I²C and SPI mode:

View File

@ -1,4 +1,8 @@
# UART Module
| Since | Origin / Contributor | Maintainer | Source |
| :----- | :-------------------- | :---------- | :------ |
| 2014-12-22 | [Zeroday](https://github.com/funshine) | [Zeroday](https://github.com/funshine) | [uart.c](../../../app/modules/uart.c)|
The [UART](https://en.wikipedia.org/wiki/Universal_asynchronous_receiver/transmitter) (Universal asynchronous receiver/transmitter) module allows configuration of and communication over the UART serial port.
## uart.alt()

View File

@ -1,4 +1,8 @@
# ucg Module
| Since | Origin / Contributor | Maintainer | Source |
| :----- | :-------------------- | :---------- | :------ |
| 2015-08-05 | [Oli Kraus](https://github.com/olikraus/ucglib), [Arnim Läuger](https://github.com/devsaurus) | [Arnim Läuger](https://github.com/devsaurus) | [ucglib](../../../app/ucglib/)|
Ucglib is a graphics library developed at [olikraus/ucglib](https://github.com/olikraus/ucglib) with support for color TFT displays. The NodeMCU firmware supports a subset of these:
- ILI9163

View File

@ -1,4 +1,8 @@
# WiFi Module
| Since | Origin / Contributor | Maintainer | Source |
| :----- | :-------------------- | :---------- | :------ |
| 2015-05-12 | [Zeroday](https://github.com/funshine) | [dnc40085](https://github.com/dnc40085) | [wifi.c](../../../app/modules/wifi.c)|
The NodeMCU WiFi control is spread across several tables:
- `wifi` for overall WiFi configuration

View File

@ -1,4 +1,8 @@
# WS2801 Module
| Since | Origin / Contributor | Maintainer | Source |
| :----- | :-------------------- | :---------- | :------ |
| 2015-07-12 | [Espressif example](https://github.com/CHERTS/esp8266-devkit/blob/master/Espressif/examples/EspLightNode/user/ws2801.c), [Konrad Beckmann](https://github.com/kbeckmann) | [Konrad Beckmann](https://github.com/kbeckmann) | [ws2801.c](../../../app/modules/ws2801.c)|
## ws2801.init()
Initializes the module and sets the pin configuration.

View File

@ -1,4 +1,8 @@
# WS2812 Module
| Since | Origin / Contributor | Maintainer | Source |
| :----- | :-------------------- | :---------- | :------ |
| 2015-02-05 | [Till Klocke](https://github.com/dereulenspiegel) | [Till Klocke](https://github.com/dereulenspiegel) | [ws2812.c](../../../app/modules/ws2812.c)|
## ws2812.write()
Send GRB data in 8 bits to a WS2812 chain.

View File

@ -1,7 +1,6 @@
As with [flashing](flash.md) there are several ways to upload code from your computer to the device.
Note that the NodeMCU serial interface uses 9600 bps at boot time. To increase the speed after booting, issue `uart.setup(0,115200,8,0,1,1)`. ESPlorer will do this automatically when changing the speed in the dropdown list.
If the device panics and resets at any time, errors will be written to the serial interface at 115200 bps.
Note that the NodeMCU serial interface uses 115200bps at boot time. To change the speed after booting, issue `uart.setup(0,9600,8,0,1,1)`. ESPlorer will do this automatically when changing the speed in the dropdown list. If the device panics and resets at any time, errors will be written to the serial interface at 115200 bps.
# ESPlorer

View File

@ -10,6 +10,7 @@ var nodemcu = nodemcu || {};
addToc();
hideNavigationForAllButSelectedLanguage();
addLanguageSelectorToRtdFlyOutMenu();
replaceRelativeLinksWithStaticGitHubUrl();
});
/**
@ -104,6 +105,20 @@ var nodemcu = nodemcu || {};
}
}
/**
* The module doc pages contain relative links to artifacts in the GitHub repository. For those links to work both
* on GitHub (i.e. when the page is viewed on GitHub) and on RTD they are defined with a relative URL. This function
* replaces the relative path with an absolute path based on the selected branch.
*/
function replaceRelativeLinksWithStaticGitHubUrl() {
var relativePath = "../../../..";
var gitHubPath = "https://github.com/nodemcu/nodemcu-firmware/tree/" + determineSelectedBranch();
var gitHubLinks = $("a[href^='" + relativePath + "']").each(function (index) {
var url = $(this).attr('href');
$(this).attr('href', url.replace(relativePath, gitHubPath));
});
}
function createLanguageLinkFor(languageCode, isCurrentlySelected) {
var strong;
// split[0] is an '' because the path starts with the separator
@ -146,6 +161,23 @@ var nodemcu = nodemcu || {};
return selectedLanguageCode;
}
/**
* Analyzes the URL of the current page to find out what the selected GitHub branch is. It's usually
* part of the location path. The code needs to distinguish between running MkDocs standalone
* and docs served from RTD. If no valid branch could be determined 'dev' returned.
*
* @returns GitHub branch name
*/
function determineSelectedBranch() {
var branch = 'dev', path = window.location.pathname;
if (window.location.origin.indexOf('readthedocs') > -1) {
// path is like /en/<branch>/<lang>/build/ -> extract 'lang'
// split[0] is an '' because the path starts with the separator
branch = path.split('/')[2];
}
return branch;
}
function values(associativeArray) {
var values = [];
for (var key in associativeArray) {

View File

@ -71,9 +71,11 @@ SECTIONS
_dport0_data_end = ABSOLUTE(.);
} >dport0_0_seg :dport0_0_phdr
.irom0.text : ALIGN(4)
.irom0.text : ALIGN(0x1000)
{
_irom0_text_start = ABSOLUTE(.);
*(.servercert.flash)
*(.clientcert.flash)
*(.irom0.literal .irom.literal .irom.text.literal .irom0.text .irom.text)
*(.literal.* .text.*)
*(.rodata*)
@ -95,7 +97,7 @@ SECTIONS
_irom0_text_end = ABSOLUTE(.);
_flash_used_end = ABSOLUTE(.);
} >irom0_0_seg :irom0_0_phdr
} >irom0_0_seg :irom0_0_phdr =0xffffffff
.data : ALIGN(4)
{

View File

@ -57,10 +57,11 @@ pages:
- 'ow (1-Wire)': 'en/modules/ow.md'
- 'perf': 'en/modules/perf.md'
- 'pwm' : 'en/modules/pwm.md'
- 'rc' : 'en/modules/rc.md'
- 'rotary' : 'en/modules/rotary.md'
- 'rtcfifo': 'en/modules/rtcfifo.md'
- 'rtcmem': 'en/modules/rtcmem.md'
- 'rtctime': 'en/modules/rtctime.md'
- 'rtcfifo': 'en/modules/rtcfifo.md'
- 'sigma delta': 'en/modules/sigma-delta.md'
- 'sntp': 'en/modules/sntp.md'
- 'spi': 'en/modules/spi.md'

3
tools/.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
TLS.*
private_key.h
cert.h

42
tools/make_cert.py Normal file
View File

@ -0,0 +1,42 @@
import os
class Cert(object):
def __init__(self, name, buff):
self.name = name
self.len = len(buff)
self.buff = buff
pass
def __str__(self):
out_str = ['\0']*32
for i in range(len(self.name)):
out_str[i] = self.name[i]
out_str = "".join(out_str)
out_str += str(chr(self.len & 0xFF))
out_str += str(chr((self.len & 0xFF00) >> 8))
out_str += self.buff
return out_str
pass
def main():
cert_list = []
file_list = os.listdir(os.getcwd())
cert_file_list = []
for _file in file_list:
pos = _file.find(".cer")
if pos != -1:
cert_file_list.append(_file[:pos])
for cert_file in cert_file_list:
with open(cert_file+".cer", 'rb') as f:
buff = f.read()
cert_list.append(Cert(cert_file, buff))
with open('esp_ca_cert.bin', 'wb+') as f:
for _cert in cert_list:
f.write("%s" % _cert)
pass
if __name__ == '__main__':
main()

69
tools/make_server_cert.py Normal file
View File

@ -0,0 +1,69 @@
import os
import argparse
import base64
import re
import sys
class Cert(object):
def __init__(self, name, buff):
self.name = name
self.len = len(buff)
self.buff = buff
pass
def __str__(self):
out_str = ['\0']*32
for i in range(len(self.name)):
out_str[i] = self.name[i]
out_str = "".join(out_str)
out_str += str(chr(self.len & 0xFF))
out_str += str(chr((self.len & 0xFF00) >> 8))
out_str += self.buff
return out_str
def main():
parser = argparse.ArgumentParser(description='Convert PEM file(s) into C source file.')
parser.add_argument('--section',
default='.servercert.flash',
help='specify the section for the data (default is .servercert.flash)')
parser.add_argument('--name',
default='net_server_cert_area',
help='specify the variable name for the data (default is net_server_cert_area)')
parser.add_argument('file', nargs='+',
help='One or more PEM files')
args = parser.parse_args()
cert_list = []
cert_file_list = []
for cert_file in args.file:
with open(cert_file, 'r') as f:
buff = f.read()
m = re.search(r"-----BEGIN ([A-Z ]+)-----([^-]+?)-----END \1-----", buff, flags=re.DOTALL)
if not m:
sys.exit("Input file was not in PEM format")
if "----BEGIN" in buff[m.end(0):]:
sys.exit("Input file contains more than one PEM object")
cert_list.append(Cert(m.group(1), base64.b64decode(''.join(m.group(2).split()))))
print '__attribute__((section("%s"))) unsigned char %s[INTERNAL_FLASH_SECTOR_SIZE] = {' % (args.section, args.name)
for _cert in cert_list:
col = 0
for ch in str(_cert):
print ("0x%02x," % ord(ch)),
if col & 15 == 15:
print
col = col + 1
print '\n0xff};\n'
if __name__ == '__main__':
main()

89
tools/makefile.sh Executable file → Normal file
View File

@ -1,11 +1,92 @@
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the axTLS project nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
# TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#
# Generate the certificates and keys for testing.
#
PROJECT_NAME="Nodemcu Project"
# Generate the openssl configuration files.
cat > ca_cert.conf << EOF
[ req ]
distinguished_name = req_distinguished_name
prompt = no
[ req_distinguished_name ]
O = $PROJECT_NAME Dodgy Certificate Authority
EOF
cat > certs.conf << EOF
[ req ]
distinguished_name = req_distinguished_name
prompt = no
[ req_distinguished_name ]
O = $PROJECT_NAME
CN = Nodemcu Client cert
EOF
cat > device_cert.conf << EOF
[ req ]
distinguished_name = req_distinguished_name
prompt = no
[ req_distinguished_name ]
O = $PROJECT_NAME Device Certificate
EOF
# private key generation
openssl genrsa -out TLS.ca_key.pem 2048
openssl genrsa -out TLS.key_2048.pem 2048
# convert private keys into DER format
openssl rsa -in TLS.key_2048.pem -out TLS.key_2048 -outform DER
# cert requests
openssl req -out TLS.ca_x509.req -sha256 -key TLS.ca_key.pem -new \
-config ./ca_cert.conf
openssl req -out TLS.x509_2048.req -sha256 -key TLS.key_2048.pem -new \
-config ./certs.conf
# generate the actual certs.
openssl x509 -req -in TLS.ca_x509.req -sha256 -out TLS.ca_x509.pem \
-sha1 -days 5000 -signkey TLS.ca_key.pem
openssl x509 -req -in TLS.x509_2048.req -sha256 -out TLS.x509_2048.pem \
-sha1 -CAcreateserial -days 5000 \
-CA TLS.ca_x509.pem -CAkey TLS.ca_key.pem
# some cleanup
rm TLS*.req
rm *.conf
openssl x509 -in TLS.ca_x509.pem -outform DER -out TLS.ca_x509.cer
openssl x509 -in TLS.x509_2048.pem -outform DER -out TLS.x509_2048.cer
#
# Generate the certificates and keys for encrypt.
#
# set default cert for use in the client
xxd -i client.cer | sed -e \
"s/client_cer/default_certificate/" > cert.h
xxd -i TLS.x509_2048.cer | sed -e \
"s/TLS_x509_2048_cer/default_certificate/" > cert.h
# set default key for use in the server
xxd -i server.key_1024 | sed -e \
"s/server_key_1024/default_private_key/" > private_key.h
xxd -i TLS.key_2048 | sed -e \
"s/TLS_key_2048/default_private_key/" > private_key.h