Commit 8044014f authored by Vowstar's avatar Vowstar
Browse files

Merge pull request #471 from nodemcu/dev

Merge dev into dev096
parents 3118fa57 c5a07d43
......@@ -37,7 +37,8 @@ SUBDIRS= \
wofs \
modules \
spiffs \
cjson
cjson \
crypto \
endif # } PDIR
......@@ -86,6 +87,7 @@ COMPONENTS_eagle.app.v6 = \
wofs/wofs.a \
spiffs/spiffs.a \
cjson/libcjson.a \
crypto/libcrypto.a \
modules/libmodules.a
LINKFLAGS_eagle.app.v6 = \
......
#############################################################
# Required variables for each makefile
# Discard this section from all parent makefiles
# Expected variables (with automatic defaults):
# CSRCS (all "C" files in the dir)
# SUBDIRS (all subdirs with a Makefile)
# GEN_LIBS - list of libs to be generated ()
# GEN_IMAGES - list of images to be generated ()
# COMPONENTS_xxx - a list of libs/objs in the form
# subdir/lib to be extracted and rolled up into
# a generated lib/image xxx.a ()
#
ifndef PDIR
GEN_LIBS = libcrypto.a
endif
#############################################################
# Configuration i.e. compile options etc.
# Target specific stuff (defines etc.) goes in here!
# Generally values applying to a tree are captured in the
# makefile at its root level - these are then overridden
# for a subtree within the makefile rooted therein
#
#DEFINES +=
#############################################################
# Recursion Magic - Don't touch this!!
#
# Each subtree potentially has an include directory
# corresponding to the common APIs applicable to modules
# rooted at that subtree. Accordingly, the INCLUDE PATH
# of a module can only contain the include directories up
# its parent path, and not its siblings
#
# Required for each makefile to inherit from the parent
#
INCLUDES := $(INCLUDES) -I $(PDIR)include
INCLUDES += -I ./
INCLUDES += -I ../libc
PDIR := ../$(PDIR)
sinclude $(PDIR)Makefile
/*
* Copyright (c) 2015, DiUS Computing Pty Ltd (jmattsson@dius.com.au)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
* 3. Neither the name of the copyright holder nor the names of contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTOR(S) ``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 AUTHOR OR CONTRIBUTOR(S) 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.
*
*/
#include "digests.h"
#include "user_config.h"
#include "rom.h"
#include "lwip/mem.h"
#include <string.h>
#include <c_errno.h>
#ifdef MD2_ENABLE
#include "ssl/ssl_crypto.h"
#endif
#ifdef SHA2_ENABLE
#include "sha2.h"
#endif
typedef char ensure_int_and_size_t_same[(sizeof(int)==sizeof(size_t)) ? 0 : -1];
/* None of the functions match the prototype fully due to the void *, and in
some cases also the int vs size_t len, so wrap declarations in a macro. */
#define MECH(pfx, u, ds, bs) \
{ #pfx, \
(create_ctx_fn)pfx ## u ## Init, \
(update_ctx_fn)pfx ## u ## Update, \
(finalize_ctx_fn)pfx ## u ## Final, \
sizeof(pfx ## _CTX), \
ds, \
bs }
static const digest_mech_info_t hash_mechs[] ICACHE_RODATA_ATTR =
{
#ifdef MD2_ENABLE
MECH(MD2, _ , MD2_SIZE, 16),
#endif
MECH(MD5, , MD5_DIGEST_LENGTH, 64)
,MECH(SHA1, , SHA1_DIGEST_LENGTH, 64)
#ifdef SHA2_ENABLE
,MECH(SHA256, _ , SHA256_DIGEST_LENGTH, SHA256_BLOCK_LENGTH)
,MECH(SHA384, _ , SHA384_DIGEST_LENGTH, SHA384_BLOCK_LENGTH)
,MECH(SHA512, _ , SHA512_DIGEST_LENGTH, SHA512_BLOCK_LENGTH)
#endif
};
#undef MECH
const digest_mech_info_t *ICACHE_FLASH_ATTR crypto_digest_mech (const char *mech)
{
if (!mech)
return 0;
size_t i;
for (i = 0; i < (sizeof (hash_mechs) / sizeof (digest_mech_info_t)); ++i)
{
const digest_mech_info_t *mi = hash_mechs + i;
if (strcasecmp (mech, mi->name) == 0)
return mi;
}
return 0;
}
const char crypto_hexbytes[] = "0123456789abcdef";
// note: supports in-place encoding
void ICACHE_FLASH_ATTR crypto_encode_asciihex (const char *bin, size_t binlen, char *outbuf)
{
size_t aidx = binlen * 2 -1;
int i;
for (i = binlen -1; i >= 0; --i)
{
outbuf[aidx--] = crypto_hexbytes[bin[i] & 0xf];
outbuf[aidx--] = crypto_hexbytes[bin[i] >> 4];
}
}
int ICACHE_FLASH_ATTR crypto_hash (const digest_mech_info_t *mi,
const char *data, size_t data_len,
uint8_t *digest)
{
if (!mi)
return EINVAL;
void *ctx = os_malloc (mi->ctx_size);
if (!ctx)
return ENOMEM;
mi->create (ctx);
mi->update (ctx, data, data_len);
mi->finalize (digest, ctx);
os_free (ctx);
return 0;
}
int ICACHE_FLASH_ATTR crypto_hmac (const digest_mech_info_t *mi,
const char *data, size_t data_len,
const char *key, size_t key_len,
uint8_t *digest)
{
if (!mi)
return EINVAL;
void *ctx = os_malloc (mi->ctx_size);
if (!ctx)
return ENOMEM;
// If key too long, it needs to be hashed before use
if (key_len > mi->block_size)
{
mi->create (ctx);
mi->update (ctx, key, key_len);
mi->finalize (digest, ctx);
key = digest;
key_len = mi->block_size;
}
const size_t bs = mi->block_size;
uint8_t k_ipad[bs];
uint8_t k_opad[bs];
os_memset (k_ipad, 0x36, bs);
os_memset (k_opad, 0x5c, bs);
size_t i;
for (i = 0; i < key_len; ++i)
{
k_ipad[i] ^= key[i];
k_opad[i] ^= key[i];
}
mi->create (ctx);
mi->update (ctx, k_ipad, bs);
mi->update (ctx, data, data_len);
mi->finalize (digest, ctx);
mi->create (ctx);
mi->update (ctx, k_opad, bs);
mi->update (ctx, digest, mi->digest_size);
mi->finalize (digest, ctx);
os_free (ctx);
return 0;
}
#ifndef _CRYPTO_DIGESTS_H_
#define _CRYPTO_DIGESTS_H_
#include <c_types.h>
typedef void (*create_ctx_fn)(void *ctx);
typedef void (*update_ctx_fn)(void *ctx, const uint8_t *msg, int len);
typedef void (*finalize_ctx_fn)(uint8_t *digest, void *ctx);
/**
* Description of a message digest mechanism.
*
* Typical usage (if not using the crypto_xxxx() functions below):
* digest_mech_info_t *mi = crypto_digest_mech (chosen_algorithm);
* void *ctx = os_malloc (mi->ctx_size);
* mi->create (ctx);
* mi->update (ctx, data, len);
* ...
* uint8_t *digest = os_malloc (mi->digest_size);
* mi->finalize (digest, ctx);
* ...
* os_free (ctx);
* os_free (digest);
*/
typedef struct
{
/* Note: All entries are 32bit to enable placement using ICACHE_RODATA_ATTR.*/
const char * name;
create_ctx_fn create;
update_ctx_fn update;
finalize_ctx_fn finalize;
uint32_t ctx_size;
uint32_t digest_size;
uint32_t block_size;
} digest_mech_info_t;
/**
* Looks up the mech data for a specified digest algorithm.
* @param mech The name of the algorithm, e.g. "MD5", "SHA256"
* @returns The mech data, or null if the mech is unknown.
*/
const digest_mech_info_t *crypto_digest_mech (const char *mech);
/**
* Wrapper function for performing a one-in-all hashing operation.
* @param mi A mech from @c crypto_digest_mech(). A null pointer @c mi
* is harmless, but will of course result in an error return.
* @param data The data to create a digest for.
* @param data_len Number of bytes at @c data to digest.
* @param digest Output buffer, must be at least @c mi->digest_size in size.
* @return 0 on success, non-zero on error.
*/
int crypto_hash (const digest_mech_info_t *mi, const char *data, size_t data_len, uint8_t *digest);
/**
* Generate a HMAC signature.
* @param mi A mech from @c crypto_digest_mech(). A null pointer @c mi
* is harmless, but will of course result in an error return.
* @param data The data to generate a signature for.
* @param data_len Number of bytes at @c data to process.
* @param key The key to use.
* @param key_len Number of bytes the @c key comprises.
* @param digest Output buffer, must be at least @c mi->digest_size in size.
* @return 0 on success, non-zero on error.
*/
int crypto_hmac (const digest_mech_info_t *mi, const char *data, size_t data_len, const char *key, size_t key_len, uint8_t *digest);
/**
* Perform ASCII Hex encoding. Does not null-terminate the buffer.
*
* @param bin The buffer to ascii-hex encode.
* @param bin_len Number of bytes in @c bin to encode.
* @param outbuf Output buffer, must be at least @c bin_len*2 bytes in size.
* Note that in-place encoding is supported, and as such
* bin==outbuf is safe, provided the buffer is large enough.
*/
void crypto_encode_asciihex (const char *bin, size_t bin_len, char *outbuf);
/** Text string "0123456789abcdef" */
const char crypto_hexbytes[17];
#endif
This diff is collapsed.
#ifndef __SHA2_H__
#define __SHA2_H__
#include <c_types.h>
/**************************************************************************
* SHA256/384/512 declarations
**************************************************************************/
#define SHA256_BLOCK_LENGTH 64
#define SHA256_DIGEST_LENGTH 32
typedef struct
{
uint32_t state[8];
uint64_t bitcount;
uint8_t buffer[SHA256_BLOCK_LENGTH];
} SHA256_CTX;
void SHA256_Init(SHA256_CTX *);
void SHA256_Update(SHA256_CTX *, const uint8_t *msg, size_t len);
void SHA256_Final(uint8_t[SHA256_DIGEST_LENGTH], SHA256_CTX*);
#define SHA384_BLOCK_LENGTH 128
#define SHA384_DIGEST_LENGTH 48
typedef struct
{
uint64_t state[8];
uint64_t bitcount[2];
uint8_t buffer[SHA384_BLOCK_LENGTH];
} SHA384_CTX;
void SHA384_Init(SHA384_CTX*);
void SHA384_Update(SHA384_CTX*, const uint8_t *msg, size_t len);
void SHA384_Final(uint8_t[SHA384_DIGEST_LENGTH], SHA384_CTX*);
#define SHA512_BLOCK_LENGTH 128
#define SHA512_DIGEST_LENGTH 64
typedef SHA384_CTX SHA512_CTX;
void SHA512_Init(SHA512_CTX*);
void SHA512_Update(SHA512_CTX*, const uint8_t *msg, size_t len);
void SHA512_Final(uint8_t[SHA512_DIGEST_LENGTH], SHA512_CTX*);
#endif
// Headers to the various functions in the rom (as we discover them)
// SHA1 is assumed to match the netbsd sha1.h headers
#define SHA1_DIGEST_LENGTH 20
#define SHA1_DIGEST_STRING_LENGTH 41
typedef struct {
uint32_t state[5];
uint32_t count[2];
uint8_t buffer[64];
} SHA1_CTX;
extern void SHA1Transform(uint32_t[5], const uint8_t[64]);
extern void SHA1Init(SHA1_CTX *);
extern void SHA1Final(uint8_t[SHA1_DIGEST_LENGTH], SHA1_CTX *);
extern void SHA1Update(SHA1_CTX *, const uint8_t *, unsigned int);
// MD5 is assumed to match the NetBSD md5.h header
#define MD5_DIGEST_LENGTH 16
typedef struct
{
uint32_t state[5];
uint32_t count[2];
uint8_t buffer[64];
} MD5_CTX;
extern void MD5Init(MD5_CTX *);
extern void MD5Update(MD5_CTX *, const unsigned char *, unsigned int);
extern void MD5Final(unsigned char[MD5_DIGEST_LENGTH], MD5_CTX *);
// base64_encode/decode derived by Cal
// Appears to match base64.h from netbsd wpa utils.
extern unsigned char * base64_encode(const unsigned char *src, size_t len, size_t *out_len);
extern unsigned char * base64_decode(const unsigned char *src, size_t len, size_t *out_len);
// Unfortunately it that seems to require the ROM memory management to be
// initialized because it uses mem_malloc
extern void mem_init(void * start_addr);
......@@ -41,6 +41,8 @@
#define CLIENT_SSL_ENABLE
#define GPIO_INTERRUPT_ENABLE
//#define MD2_ENABLE
#define SHA2_ENABLE
// #define BUILD_WOFS 1
#define BUILD_SPIFFS 1
......
......@@ -31,6 +31,7 @@
#define LUA_USE_MODULES_U8G
#define LUA_USE_MODULES_WS2812
#define LUA_USE_MODULES_CJSON
#define LUA_USE_MODULES_CRYPTO
#endif /* LUA_USE_MODULES */
#endif /* __USER_MODULES_H__ */
// Module for cryptography
//#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
#include "platform.h"
#include "auxmods.h"
#include "lrotable.h"
#include "c_types.h"
#include "c_stdlib.h"
#include "../crypto/digests.h"
#include "user_interface.h"
#include "rom.h"
/**
* hash = crypto.sha1(input)
*
* Calculates raw SHA1 hash of input string.
* Input is arbitrary string, output is raw 20-byte hash as string.
*/
static int crypto_sha1( lua_State* L )
{
SHA1_CTX ctx;
uint8_t digest[20];
// Read the string from lua (with length)
int len;
const char* msg = luaL_checklstring(L, 1, &len);
// Use the SHA* functions in the rom
SHA1Init(&ctx);
SHA1Update(&ctx, msg, len);
SHA1Final(digest, &ctx);
// Push the result as a lua string
lua_pushlstring(L, digest, 20);
return 1;
}
static const char* bytes64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/**
* encoded = crypto.toBase64(raw)
*
* Encodes raw binary string as base64 string.
*/
static int crypto_base64_encode( lua_State* L )
{
int len;
const char* msg = luaL_checklstring(L, 1, &len);
int blen = (len + 2) / 3 * 4;
char* out = (char*)c_malloc(blen);
int j = 0, i;
for (i = 0; i < len; i += 3) {
int a = msg[i];
int b = (i + 1 < len) ? msg[i + 1] : 0;
int c = (i + 2 < len) ? msg[i + 2] : 0;
out[j++] = bytes64[a >> 2];
out[j++] = bytes64[((a & 3) << 4) | (b >> 4)];
out[j++] = (i + 1 < len) ? bytes64[((b & 15) << 2) | (c >> 6)] : 61;
out[j++] = (i + 2 < len) ? bytes64[(c & 63)] : 61;
}
lua_pushlstring(L, out, j);
c_free(out);
return 1;
}
/**
* encoded = crypto.toHex(raw)
*
* Encodes raw binary string as hex string.
*/
static int crypto_hex_encode( lua_State* L)
{
int len;
const char* msg = luaL_checklstring(L, 1, &len);
char* out = (char*)c_malloc(len * 2);
int i, j = 0;
for (i = 0; i < len; i++) {
out[j++] = crypto_hexbytes[msg[i] >> 4];
out[j++] = crypto_hexbytes[msg[i] & 0xf];
}
lua_pushlstring(L, out, len*2);
c_free(out);
return 1;
}
/**
* masked = crypto.mask(message, mask)
*
* Apply a mask (repeated if shorter than message) as XOR to each byte.
*/
static int crypto_mask( lua_State* L )
{
int len, mask_len;
const char* msg = luaL_checklstring(L, 1, &len);
const char* mask = luaL_checklstring(L, 2, &mask_len);
int i;
char* copy = (char*)c_malloc(len);
for (i = 0; i < len; i++) {
copy[i] = msg[i] ^ mask[i % 4];
}
lua_pushlstring(L, copy, len);
c_free(copy);
return 1;
}
static inline int bad_mech (lua_State *L) { return luaL_error (L, "unknown hash mech"); }
static inline int bad_mem (lua_State *L) { return luaL_error (L, "insufficient memory"); }
/* rawdigest = crypto.hash("MD5", str)
* strdigest = crypto.toHex(rawdigest)
*/
static int crypto_lhash (lua_State *L)
{
const digest_mech_info_t *mi = crypto_digest_mech (luaL_checkstring (L, 1));
if (!mi)
return bad_mech (L);
size_t len = 0;
const char *data = luaL_checklstring (L, 2, &len);
uint8_t digest[mi->digest_size];
if (crypto_hash (mi, data, len, digest) != 0)
return bad_mem (L);
lua_pushlstring (L, digest, sizeof (digest));
return 1;
}
/* rawsignature = crypto.hmac("SHA1", str, key)
* strsignature = crypto.toHex(rawsignature)
*/
static int crypto_lhmac (lua_State *L)
{
const digest_mech_info_t *mi = crypto_digest_mech (luaL_checkstring (L, 1));
if (!mi)
return bad_mech (L);
size_t len = 0;
const char *data = luaL_checklstring (L, 2, &len);
size_t klen = 0;
const char *key = luaL_checklstring (L, 3, &klen);
uint8_t digest[mi->digest_size];
if (crypto_hmac (mi, data, len, key, klen, digest) != 0)
return bad_mem (L);
lua_pushlstring (L, digest, sizeof (digest));
return 1;
}
// Module function map
#define MIN_OPT_LEVEL 2
#include "lrodefs.h"
const LUA_REG_TYPE crypto_map[] =
{
{ LSTRKEY( "sha1" ), LFUNCVAL( crypto_sha1 ) },
{ LSTRKEY( "toBase64" ), LFUNCVAL( crypto_base64_encode ) },
{ LSTRKEY( "toHex" ), LFUNCVAL( crypto_hex_encode ) },
{ LSTRKEY( "mask" ), LFUNCVAL( crypto_mask ) },
{ LSTRKEY( "hash" ), LFUNCVAL( crypto_lhash ) },
{ LSTRKEY( "hmac" ), LFUNCVAL( crypto_lhmac ) },
#if LUA_OPTIMIZE_MEMORY > 0
#endif
{ LNILKEY, LNILVAL }
};
LUALIB_API int luaopen_crypto( lua_State *L )
{
#if LUA_OPTIMIZE_MEMORY > 0
return 0;
#else // #if LUA_OPTIMIZE_MEMORY > 0
luaL_register( L, AUXLIB_CRYPTO, crypto_map );
// Add constants
return 1;
#endif // #if LUA_OPTIMIZE_MEMORY > 0
}
......@@ -149,6 +149,14 @@
#define ROM_MODULES_CJSON
#endif
#if defined(LUA_USE_MODULES_CRYPTO)
#define MODULES_CRYPTO "crypto"
#define ROM_MODULES_CRYPTO \
_ROM(MODULES_CRYPTO, luaopen_crypto, crypto_map)
#else
#define ROM_MODULES_CRYPTO
#endif
#define LUA_MODULES_ROM \
ROM_MODULES_GPIO \
ROM_MODULES_PWM \
......@@ -167,7 +175,8 @@
ROM_MODULES_OW \
ROM_MODULES_BIT \
ROM_MODULES_WS2812 \
ROM_MODULES_CJSON
ROM_MODULES_CJSON \
ROM_MODULES_CRYPTO
#endif
......@@ -28,11 +28,17 @@ static void ICACHE_FLASH_ATTR send_ws_1(uint8_t gpio) {
i = 6; while (i--) GPIO_REG_WRITE(GPIO_OUT_W1TC_ADDRESS, 1 << gpio);
}
// Lua: ws2812.write(pin, "string")
// Lua: ws2812.writergb(pin, "string")
// Byte triples in the string are interpreted as R G B values and sent to the hardware as G R B.
// ws2812.write(4, string.char(255, 0, 0)) uses GPIO2 and sets the first LED red.
// ws2812.write(3, string.char(0, 0, 255):rep(10)) uses GPIO0 and sets ten LEDs blue.
// ws2812.write(4, string.char(0, 255, 0, 255, 255, 255)) first LED green, second LED white.
// WARNING: this function scrambles the input buffer :
// a = string.char(255,0,128)
// ws212.writergb(3,a)
// =a.byte()
// (0,255,128)
// ws2812.writergb(4, string.char(255, 0, 0)) uses GPIO2 and sets the first LED red.
// ws2812.writergb(3, string.char(0, 0, 255):rep(10)) uses GPIO0 and sets ten LEDs blue.
// ws2812.writergb(4, string.char(0, 255, 0, 255, 255, 255)) first LED green, second LED white.
static int ICACHE_FLASH_ATTR ws2812_writergb(lua_State* L)
{
const uint8_t pin = luaL_checkinteger(L, 1);
......@@ -78,11 +84,43 @@ static int ICACHE_FLASH_ATTR ws2812_writergb(lua_State* L)
return 0;
}
// Lua: ws2812.write(pin, "string")
// Byte triples in the string are interpreted as G R B values.
// This function does not corrupt your buffer.
//
// ws2812.write(4, string.char(0, 255, 0)) uses GPIO2 and sets the first LED red.
// ws2812.write(3, string.char(0, 0, 255):rep(10)) uses GPIO0 and sets ten LEDs blue.
// ws2812.write(4, string.char(255, 0, 0, 255, 255, 255)) first LED green, second LED white.
static int ICACHE_FLASH_ATTR ws2812_writegrb(lua_State* L) {
const uint8_t pin = luaL_checkinteger(L, 1);
size_t length;
const char *buffer = luaL_checklstring(L, 2, &length);
platform_gpio_mode(pin, PLATFORM_GPIO_OUTPUT, PLATFORM_GPIO_FLOAT);
platform_gpio_write(pin, 0);
os_delay_us(10);
os_intr_lock();
const char * const end = buffer + length;
while (buffer != end) {
uint8_t mask = 0x80;
while (mask) {
(*buffer & mask) ? send_ws_1(pin_num[pin]) : send_ws_0(pin_num[pin]);
mask >>= 1;
}
++buffer;
}
os_intr_unlock();
return 0;
}
#define MIN_OPT_LEVEL 2
#include "lrodefs.h"
const LUA_REG_TYPE ws2812_map[] =
{
{ LSTRKEY( "writergb" ), LFUNCVAL( ws2812_writergb )},
{ LSTRKEY( "write" ), LFUNCVAL( ws2812_writegrb )},
{ LNILKEY, LNILVAL}
};
......
--
-- Light sensor on ADC(0), RGB LED connected to gpio12(6) Green, gpio13(7) Blue & gpio15(8) Red.
-- This works out of the box on the typical ESP8266 evaluation boards with Battery Holder
--
-- It uses the input from the sensor to drive a "rainbow" effect on the RGB LED
-- Includes a very "pseudoSin" function
--
function led(r,Sg,b)
pwm.setduty(8,r)
pwm.setduty(6,g)
pwm.setduty(7,b)
end
-- this is perhaps the lightest weight sin function in existance
-- Given an integer from 0..128, 0..512 appximating 256 + 256 * sin(idx*Pi/256)
-- This is first order square approximation of sin, it's accurate around 0 and any multiple of 128 (Pi/2),
-- 92% accurate at 64 (Pi/4).
function pseudoSin (idx)
idx = idx % 128
lookUp = 32 - idx % 64
val = 256 - (lookUp * lookUp) / 4
if (idx > 64) then
val = - val;
end
return 256+val
end
pwm.setup(6,500,512)
pwm.setup(7,500,512)
pwm.setup(8,500,512)
pwm.start(6)
pwm.start(7)
pwm.start(8)
tmr.alarm(1,20,1,function()
idx = 3 * adc.read(0) / 2
r = pseudoSin(idx)
g = pseudoSin(idx + 43)
b = pseudoSin(idx + 85)
led(r,g,b)
idx = (idx + 1) % 128
end)
--
-- Simple NodeMCU web server (done is a not so nodeie fashion :-)
--
-- Highly modified by Bruce Meacham, based on work by Scott Beasley 2015
-- Open and free to change and use. Enjoy. [Beasley/Meacham 2015]
--
-- Meacham Update: I streamlined/improved the parsing to focus on simple HTTP GET request and their simple parameters
-- Also added the code to drive a servo/light. Comment out as you see fit.
--
-- Usage:
-- Change SSID and SSID_PASSPHRASE for your wifi network
-- Download to NodeMCU
-- node.compile("http_server.lua")
-- dofile("http_server.lc")
-- When the server is esablished it will output the IP address.
-- http://{ip address}/?s0=1200&light=1
-- s0 is the servo position (actually the PWM hertz), 500 - 2000 are all good values
-- light chanel high(1)/low(0), some evaluation boards have LEDs pre-wired in a "pulled high" confguration, so '0' ground the emitter and turns it on backwards.
--
-- Add to init.lua if you want it to autoboot.
--
-- Your Wifi connection data
local SSID = "YOUR WIFI SSID"
local SSID_PASSWORD = "YOUR SSID PASSPHRASE"
-- General setup
local pinLight = 2 -- this is GPIO4
gpio.mode(pinLight,gpio.OUTPUT)
gpio.write(pinLight,gpio.HIGH)
servo = {}
servo.pin = 4 --this is GPIO2
servo.value = 1500
servo.id = "servo"
gpio.mode(servo.pin, gpio.OUTPUT)
gpio.write(servo.pin, gpio.LOW)
-- This alarm drives the servo
tmr.alarm(0,10,1,function() -- 50Hz
if servo.value then -- generate pulse
gpio.write(servo.pin, gpio.HIGH)
tmr.delay(servo.value)
gpio.write(servo.pin, gpio.LOW)
end
end)
local function connect (conn, data)
local query_data
conn:on ("receive",
function (cn, req_data)
params = get_http_req (req_data)
cn:send("HTTP/1.1 200/OK\r\nServer: NodeLuau\r\nContent-Type: text/html\r\n\r\n")
cn:send ("<h1>ESP8266 Servo &amp; Light Server</h1>\r\n")
if (params["light"] ~= nil) then
if ("0" == params["light"]) then
gpio.write(pinLight, gpio.LOW)
else
gpio.write(pinLight, gpio.HIGH)
end
end
if (params["s0"] ~= nil) then
servo.value = tonumber(params["s0"]);
end
-- Close the connection for the request
cn:close ( )
end)
end
-- Build and return a table of the http request data
function get_http_req (instr)
local t = {}
local str = string.sub(instr, 0, 200)
local v = string.gsub(split(str, ' ')[2], '+', ' ')
parts = split(v, '?')
local params = {}
if (table.maxn(parts) > 1) then
for idx,part in ipairs(split(parts[2], '&')) do
parmPart = split(part, '=')
params[parmPart[1]] = parmPart[2]
end
end
return params
end
-- Source: http://lua-users.org/wiki/MakingLuaLikePhp
-- Credit: http://richard.warburton.it/
function split(str, splitOn)
if (splitOn=='') then return false end
local pos,arr = 0,{}
for st,sp in function() return string.find(str,splitOn,pos,true) end do
table.insert(arr,string.sub(str,pos,st-1))
pos = sp + 1
end
table.insert(arr,string.sub(str,pos))
return arr
end
-- Configure the ESP as a station (client)
wifi.setmode (wifi.STATION)
wifi.sta.config (SSID, SSID_PASSWORD)
wifi.sta.autoconnect (1)
-- Hang out until we get a wifi connection before the httpd server is started.
tmr.alarm (1, 800, 1, function ( )
if wifi.sta.getip ( ) == nil then
print ("Waiting for Wifi connection")
else
tmr.stop (1)
print ("Config done, IP is " .. wifi.sta.getip ( ))
end
end)
-- Create the httpd server
svr = net.createServer (net.TCP, 30)
-- Server listening on port 80, call connect function if a request is received
svr:listen (80, connect)
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