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

Merge pull request #1336 from nodemcu/dev

1.5.1 master drop
parents c8037568 2e109686
......@@ -806,6 +806,9 @@ static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
return nptr;
}
LUALIB_API void luaL_assertfail(const char *file, int line, const char *message) {
c_printf("ASSERT@%s(%d): %s\n", file, line, message);
}
static int panic (lua_State *L) {
(void)L; /* to avoid warnings */
......
......@@ -100,7 +100,7 @@ LUALIB_API const char *(luaL_gsub) (lua_State *L, const char *s, const char *p,
LUALIB_API const char *(luaL_findtable) (lua_State *L, int idx,
const char *fname, int szhint);
LUALIB_API void luaL_assertfail(const char *file, int line, const char *message);
/*
......
......@@ -11,6 +11,8 @@
#include "c_string.h"
#include "flash_fs.h"
#include "user_version.h"
#include "driver/readline.h"
#include "driver/uart.h"
#define lua_c
......@@ -466,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);
}
......
......@@ -19,6 +19,7 @@
#include "c_stdarg.h"
#include "c_stddef.h"
#include "c_types.h"
#include <ctype.h>
#endif
#include "luaconf.h"
......
......@@ -632,7 +632,7 @@ extern int readline4lua(const char *prompt, char *buffer, int length);
/*
@@ The luai_num* macros define the primitive operations over numbers.
*/
#if defined(LUA_CORE)
#if defined(LUA_CORE) || defined(LUA_LIB)
#ifdef LUA_CROSS_COMPILER
#include <math.h>
#else
......@@ -880,10 +880,6 @@ union luai_Cast { double l_d; long l_l; };
#define LUA_INTFRMLEN "l"
#define LUA_INTFRM_T long
#ifndef LUA_CROSS_COMPILER
typedef short int16_t;
typedef long int32_t;
#endif
#endif
......
......@@ -847,7 +847,7 @@ espconn_get_connection_info(struct espconn *pespconn, remot_info **pcon_info, ui
break;
case ESPCONN_UDP:
while(plist != NULL){
if (plist->pespconn && plist->pespconn->type == ESPCONN_UDP){
if (plist->pespconn == pespconn){
premot[pespconn->link_cnt].state = plist->pespconn->state;
premot[pespconn->link_cnt].remote_port = plist->pcommon.remote_port;
os_memcpy(premot[pespconn->link_cnt].remote_ip, plist->pcommon.remote_ip, 4);
......@@ -860,6 +860,8 @@ espconn_get_connection_info(struct espconn *pespconn, remot_info **pcon_info, ui
break;
}
*pcon_info = premot;
if (pespconn->link_cnt == 0)
return ESPCONN_ARG;
return ESPCONN_OK;
}
......@@ -954,12 +956,43 @@ espconn_disconnect(struct espconn *espconn)
/*protect for redisconnection*/
if (espconn->state == ESPCONN_CLOSE)
return ESPCONN_INPROGRESS;
espconn_tcp_disconnect(pnode);
espconn_tcp_disconnect(pnode,0); //1 force, 0 normal
return ESPCONN_OK;
} else
return ESPCONN_ARG;
}
/******************************************************************************
* FunctionName : espconn_abort
* Description : Forcely abort with host
* Parameters : espconn -- the espconn used to disconnect the connection
* Returns : none
*******************************************************************************/
sint8 ICACHE_FLASH_ATTR
espconn_abort(struct espconn *espconn)
{
espconn_msg *pnode = NULL;
bool value = false;
if (espconn == NULL) {
return ESPCONN_ARG;;
} else if (espconn ->type != ESPCONN_TCP)
return ESPCONN_ARG;
/*Find the node depend on the espconn message*/
value = espconn_find_connection(espconn, &pnode);
if (value){
/*protect for redisconnection*/
if (espconn->state == ESPCONN_CLOSE)
return ESPCONN_INPROGRESS;
espconn_tcp_disconnect(pnode,1); //1 force, 0 normal
return ESPCONN_OK;
} else
return ESPCONN_ARG;
}
/******************************************************************************
* FunctionName : espconn_get_packet_info
* Description : get the packet info with host
......@@ -1215,7 +1248,7 @@ espconn_port(void)
static uint32 randnum = 0;
do {
port = system_get_time();
port = os_random();
if (port < 0) {
port = os_random() - port;
......
......@@ -38,12 +38,12 @@ os_event_t espconn_TaskQueue[espconn_TaskQueueLen];
static err_t
espconn_client_recv(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err);
static void
espconn_client_close(void *arg, struct tcp_pcb *pcb);
espconn_client_close(void *arg, struct tcp_pcb *pcb,u8 type);
static err_t
espconn_server_recv(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err);
static void
espconn_server_close(void *arg, struct tcp_pcb *pcb);
espconn_server_close(void *arg, struct tcp_pcb *pcb,u8 type);
///////////////////////////////common function/////////////////////////////////
/******************************************************************************
......@@ -495,14 +495,14 @@ espconn_tcp_sent(void *arg, uint8 *psent, uint16 length)
* Parameters : arg -- Additional argument to pass to the callback function
* Returns : none
*******************************************************************************/
void ICACHE_FLASH_ATTR espconn_tcp_disconnect(espconn_msg *pdiscon)
void ICACHE_FLASH_ATTR espconn_tcp_disconnect(espconn_msg *pdiscon,u8 type)
{
if (pdiscon != NULL){
/*disconnect with the host by send the FIN frame*/
if (pdiscon->preverse != NULL)
espconn_server_close(pdiscon, pdiscon->pcommon.pcb);
espconn_server_close(pdiscon, pdiscon->pcommon.pcb,type);
else
espconn_client_close(pdiscon, pdiscon->pcommon.pcb);
espconn_client_close(pdiscon, pdiscon->pcommon.pcb,type);
} else{
espconn_printf("espconn_tcp_disconnect err.\n");
}
......@@ -517,7 +517,7 @@ void ICACHE_FLASH_ATTR espconn_tcp_disconnect(espconn_msg *pdiscon)
* Returns : none
*******************************************************************************/
static void ICACHE_FLASH_ATTR
espconn_client_close(void *arg, struct tcp_pcb *pcb)
espconn_client_close(void *arg, struct tcp_pcb *pcb, u8 type)
{
err_t err;
espconn_msg *pclose = arg;
......@@ -525,7 +525,11 @@ espconn_client_close(void *arg, struct tcp_pcb *pcb)
pclose->pcommon.pcb = pcb;
/*avoid recalling the disconnect function*/
tcp_recv(pcb, NULL);
if(type == 0)
err = tcp_close(pcb);
else
{tcp_abort(pcb); err = ERR_OK;}
if (err != ERR_OK) {
/* closing failed, try again later */
......@@ -647,7 +651,7 @@ espconn_client_recv(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err)
}
if (err == ERR_OK && p == NULL) {
espconn_client_close(precv_cb, pcb);
espconn_client_close(precv_cb, pcb,0);
}
return ERR_OK;
......@@ -943,7 +947,7 @@ espconn_tcp_client(struct espconn *espconn)
* Returns : none
*******************************************************************************/
static void ICACHE_FLASH_ATTR
espconn_server_close(void *arg, struct tcp_pcb *pcb)
espconn_server_close(void *arg, struct tcp_pcb *pcb,u8 type)
{
err_t err;
espconn_msg *psclose = arg;
......@@ -951,7 +955,11 @@ espconn_server_close(void *arg, struct tcp_pcb *pcb)
psclose->pcommon.pcb = pcb;
/*avoid recalling the disconnect function*/
tcp_recv(pcb, NULL);
if(type ==0)
err = tcp_close(pcb);
else
{tcp_abort(pcb); err = ERR_OK;}
if (err != ERR_OK) {
/* closing failed, try again later */
......@@ -1024,7 +1032,7 @@ espconn_server_recv(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err)
pbuf_free(p);
}
espconn_server_close(precv_cb, pcb);
espconn_server_close(precv_cb, pcb,0);
}
return ERR_OK;
......@@ -1086,7 +1094,7 @@ espconn_server_poll(void *arg, struct tcp_pcb *pcb)
if (pspoll_cb->pcommon.timeout != 0){/*no data sent in one active connection's set timeout, close.*/
if (pspoll_cb->pcommon.recv_check >= pspoll_cb->pcommon.timeout) {
pspoll_cb->pcommon.recv_check = 0;
espconn_server_close(pspoll_cb, pcb);
espconn_server_close(pspoll_cb, pcb,0);
}
} else {
espconn_msg *ptime_msg = pserver_list;
......@@ -1095,7 +1103,7 @@ espconn_server_poll(void *arg, struct tcp_pcb *pcb)
if (ptime_msg->pcommon.timeout != 0){/*no data sent in server's set timeout, close.*/
if (pspoll_cb->pcommon.recv_check >= ptime_msg->pcommon.timeout){
pspoll_cb->pcommon.recv_check = 0;
espconn_server_close(pspoll_cb, pcb);
espconn_server_close(pspoll_cb, pcb,0);
}
} else {/*don't close for ever*/
pspoll_cb->pcommon.recv_check = 0;
......@@ -1106,7 +1114,7 @@ espconn_server_poll(void *arg, struct tcp_pcb *pcb)
}
}
} else {
espconn_server_close(pspoll_cb, pcb);
espconn_server_close(pspoll_cb, pcb,0);
}
return ERR_OK;
......
......@@ -301,7 +301,7 @@ espconn_udp_recv(void *arg, struct udp_pcb *upcb, struct pbuf *p,
if (wifi_get_opmode() != 1) {
wifi_get_ip_info(1, &ipconfig);
if (!ip_addr_netcmp((struct ip_addr *)precv->pespconn->proto.udp->remote_ip, &ipconfig.ip, &ipconfig.netmask)) {
if (!ip_addr_netcmp(addr, &ipconfig.ip, &ipconfig.netmask)) {
wifi_get_ip_info(0, &ipconfig);
}
} else {
......
......@@ -193,8 +193,8 @@ static char host_name[MDNS_NAME_LENGTH];
static char service_name[MDNS_NAME_LENGTH];
static char server_name[MDNS_NAME_LENGTH];
//static char puck_datasheet[PUCK_DATASHEET_SIZE];
static struct udp_pcb *mdns_pcb;
static struct udp_pcb *mdns_pcb = NULL;
static struct mdns_info * ms_info = NULL;
static struct ip_addr multicast_addr;
static struct ip_addr host_addr;
static uint8 register_flag = 0;
......@@ -887,7 +887,7 @@ mdns_recv(void *arg, struct udp_pcb *pcb, struct pbuf *p, struct ip_addr *addr,
}
goto memerr2;
memerr2:
mem_free(mdns_payload);
os_memset(mdns_payload , 0 ,DNS_MSG_SIZE);
memerr1:
/* free pbuf */
pbuf_free(p);
......@@ -900,8 +900,12 @@ mdns_recv(void *arg, struct udp_pcb *pcb, struct pbuf *p, struct ip_addr *addr,
void ICACHE_FLASH_ATTR
mdns_close(void)
{
if (mdns_pcb != NULL)
if (mdns_pcb != NULL && ms_info != NULL)
udp_remove(mdns_pcb);
os_free(ms_info);
mdns_pcb = NULL;
ms_info = NULL;
}
void ICACHE_FLASH_ATTR
......@@ -1030,26 +1034,33 @@ mdns_init(struct mdns_info *info) {
multicast_addr.addr = DNS_MULTICAST_ADDRESS;
struct ip_addr ap_host_addr;
struct ip_info ipconfig;
if (info->ipAddr == 0) {
ms_info = (struct mdns_info *)os_zalloc(sizeof(struct mdns_info));
if (ms_info != NULL) {
os_memcpy(ms_info,info,sizeof(struct mdns_info));
} else {
os_printf("ms_info alloc failed\n");
return;
}
if (ms_info->ipAddr == 0) {
os_printf("mdns ip error!\n ");
return;
}
host_addr.addr = info->ipAddr ;
host_addr.addr = ms_info->ipAddr ;
LWIP_DEBUGF(DNS_DEBUG, ("dns_init: initializing\n"));
//get the datasheet from PUCK
mdns_set_hostname(info->host_name);
mdns_set_servername(info->server_name);
mdns_set_name(info->host_name);
mdns_set_hostname(ms_info->host_name);
mdns_set_servername(ms_info->server_name);
mdns_set_name(ms_info->host_name);
// get the host name as instrumentName_serialNumber for MDNS
// set the name of the service, the same as host name
os_printf("host_name = %s\n", host_name);
os_printf("server_name = %s\n", PUCK_SERVICE);
if (info->server_port == 0)
if (ms_info->server_port == 0)
{
PUCK_PORT = 80;
} else {
PUCK_PORT = info->server_port;
PUCK_PORT = ms_info->server_port;
}
/* initialize mDNS */
......@@ -1080,14 +1091,14 @@ mdns_init(struct mdns_info *info) {
/*loopback function for the multicast(224.0.0.251) messages received at port 5353*/
// mdns_enable();
udp_recv(mdns_pcb, mdns_recv, info);
udp_recv(mdns_pcb, mdns_recv, ms_info);
mdns_flag = 1;
/*
* Register the name of the instrument
*/
os_timer_disarm(&mdns_timer);
os_timer_setfn(&mdns_timer, (os_timer_func_t *)mdns_reg,info);
os_timer_setfn(&mdns_timer, (os_timer_func_t *)mdns_reg,ms_info);
os_timer_arm(&mdns_timer, 1000, 1);
}
}
......
......@@ -632,15 +632,19 @@ tcp_new_port(void)
int i;
struct tcp_pcb *pcb;
#ifndef TCP_LOCAL_PORT_RANGE_START
#define TCP_LOCAL_PORT_RANGE_START 4096
#define TCP_LOCAL_PORT_RANGE_START 1024
#define TCP_LOCAL_PORT_RANGE_END 0x7fff
#endif
static u16_t port __attribute__((section(".port"))) = TCP_LOCAL_PORT_RANGE_START;
static u16_t port = TCP_LOCAL_PORT_RANGE_START;
again:
if (++port >= TCP_LOCAL_PORT_RANGE_END) {
port = TCP_LOCAL_PORT_RANGE_START;
}
// if (++port >= TCP_LOCAL_PORT_RANGE_END) {
// port = TCP_LOCAL_PORT_RANGE_START;
// }
port = os_random();
port %= TCP_LOCAL_PORT_RANGE_END;
if (port < TCP_LOCAL_PORT_RANGE_START)
port += TCP_LOCAL_PORT_RANGE_START;
/* Check all PCB lists. */
for (i = 0; i < NUM_TCP_PCB_LISTS; i++) {
for(pcb = *tcp_pcb_lists[i]; pcb != NULL; pcb = pcb->next) {
......
......@@ -15,6 +15,8 @@ ifndef PDIR
GEN_LIBS = libmodules.a
endif
STD_CFLAGS=-std=gnu11 -Wimplicit
#############################################################
# Configuration i.e. compile options etc.
# Target specific stuff (defines etc.) goes in here!
......@@ -45,11 +47,11 @@ INCLUDES += -I ../u8glib
INCLUDES += -I ../ucglib
INCLUDES += -I ../lua
INCLUDES += -I ../platform
INCLUDES += -I ../wofs
INCLUDES += -I ../spiffs
INCLUDES += -I ../smart
INCLUDES += -I ../cjson
INCLUDES += -I ../dhtlib
INCLUDES += -I ../http
PDIR := ../$(PDIR)
sinclude $(PDIR)Makefile
......@@ -24,10 +24,49 @@ static int adc_readvdd33( lua_State* L )
return 1;
}
// Lua: adc.force_init_mode(x)
static int adc_init107( lua_State *L )
{
uint8_t byte107 = luaL_checkinteger (L, 1);
uint32 init_sector = flash_safe_get_sec_num () - 4;
// Note 32bit alignment so we can safely cast to uint32 for the flash api
char init_data[SPI_FLASH_SEC_SIZE] __attribute__((aligned(4)));
if (SPI_FLASH_RESULT_OK != flash_safe_read (
init_sector * SPI_FLASH_SEC_SIZE,
(uint32 *)init_data, sizeof(init_data)))
return luaL_error(L, "flash read error");
// If it's already the correct value, we don't need to force it
if (init_data[107] == byte107)
{
lua_pushboolean (L, false);
return 1;
}
// Nope, it differs, we need to rewrite it
init_data[107] = byte107;
if (SPI_FLASH_RESULT_OK != flash_safe_erase_sector (init_sector))
return luaL_error(L, "flash erase error");
if (SPI_FLASH_RESULT_OK != flash_safe_write (
init_sector * SPI_FLASH_SEC_SIZE,
(uint32 *)init_data, sizeof(init_data)))
return luaL_error(L, "flash write error");
lua_pushboolean (L, true);
return 1;
}
// Module function map
static const LUA_REG_TYPE adc_map[] = {
{ LSTRKEY( "read" ), LFUNCVAL( adc_sample ) },
{ LSTRKEY( "readvdd33" ), LFUNCVAL( adc_readvdd33) },
{ LSTRKEY( "readvdd33" ), LFUNCVAL( adc_readvdd33 ) },
{ LSTRKEY( "force_init_mode" ), LFUNCVAL( adc_init107 ) },
{ LSTRKEY( "INIT_ADC" ), LNUMVAL( 0x00 ) },
{ LSTRKEY( "INIT_VDD33" ),LNUMVAL( 0xff ) },
{ LNILKEY, LNILVAL }
};
......
/*
* app/modules/am2320.c
*
* Copyright (c) 2016 Henk Vergonet <Henk.Vergonet@gmail.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "module.h"
#include "lauxlib.h"
#include "platform.h"
#include "lwip/udp.h"
#include <errno.h>
static const uint32_t am2320_i2c_id = 0;
static const uint8_t am2320_i2c_addr = 0xb8 >> 1;
static uint16_t crc16(uint8_t *ptr, unsigned int len)
{
uint16_t crc =0xFFFF;
uint8_t i;
while(len--) {
crc ^= *ptr++;
for(i=0;i<8;i++) {
if(crc & 0x01) {
crc >>= 1;
crc ^= 0xA001;
} else {
crc >>= 1;
}
}
}
return crc;
}
/* make sure buf has lenght len+2 in order to accommodate for extra bytes */
static int _read(uint32_t id, void *buf, uint8_t len, uint8_t off)
{
int i;
uint8_t *b = (uint8_t *)buf;
uint16_t crc;
// step 1: Wake sensor
platform_i2c_send_start(id);
platform_i2c_send_address(id, am2320_i2c_addr, PLATFORM_I2C_DIRECTION_TRANSMITTER);
os_delay_us(800);
platform_i2c_send_stop(id);
// step 2: Send read command
platform_i2c_send_start(id);
platform_i2c_send_address(id, am2320_i2c_addr, PLATFORM_I2C_DIRECTION_TRANSMITTER);
platform_i2c_send_byte(id, 0x03);
platform_i2c_send_byte(id, off);
platform_i2c_send_byte(id, len);
platform_i2c_send_stop(id);
// step 3: Read the data
os_delay_us(1500);
platform_i2c_send_start(id);
platform_i2c_send_address(id, am2320_i2c_addr, PLATFORM_I2C_DIRECTION_RECEIVER);
os_delay_us(30);
for(i=0; i<len+2; i++)
b[i] = platform_i2c_recv_byte(id,1);
crc = platform_i2c_recv_byte(id,1);
crc |= platform_i2c_recv_byte(id,0) << 8;
platform_i2c_send_stop(id);
if(b[0] != 0x3 || b[1] != len)
return -EIO;
if(crc != crc16(b,len+2))
return -EIO;
return 0;
}
static int am2320_init(lua_State* L)
{
uint32_t sda;
uint32_t scl;
int ret;
struct {
uint8_t cmd;
uint8_t len;
uint16_t model;
uint8_t version;
uint32_t id;
} nfo;
if (!lua_isnumber(L, 1) || !lua_isnumber(L, 2)) {
return luaL_error(L, "wrong arg range");
}
sda = luaL_checkinteger(L, 1);
scl = luaL_checkinteger(L, 2);
if (scl == 0 || sda == 0) {
return luaL_error(L, "no i2c for D0");
}
platform_i2c_setup(am2320_i2c_id, sda, scl, PLATFORM_I2C_SPEED_SLOW);
os_delay_us(1500); // give some time to settle things down
ret = _read(am2320_i2c_id, &nfo, sizeof(nfo)-2, 0x08);
if(ret)
return luaL_error(L, "transmission error");
lua_pushinteger(L, ntohs(nfo.model));
lua_pushinteger(L, nfo.version);
lua_pushinteger(L, ntohl(nfo.id));
return 3;
}
static int am2320_read(lua_State* L)
{
int ret;
struct {
uint8_t cmd;
uint8_t len;
uint16_t rh;
uint16_t temp;
} nfo;
ret = _read(am2320_i2c_id, &nfo, sizeof(nfo)-2, 0x00);
if(ret)
return luaL_error(L, "transmission error");
ret = ntohs(nfo.temp);
if(ret & 0x8000)
ret = -(ret & 0x7fff);
lua_pushinteger(L, ntohs(nfo.rh));
lua_pushinteger(L, ret);
return 2;
}
static const LUA_REG_TYPE am2320_map[] = {
{ LSTRKEY( "read" ), LFUNCVAL( am2320_read )},
{ LSTRKEY( "init" ), LFUNCVAL( am2320_init )},
{ LNILKEY, LNILVAL}
};
NODEMCU_MODULE(AM2320, "am2320", am2320_map, NULL);
#include "c_stdlib.h"
#include "c_string.h"
#include "lualib.h"
#include "lauxlib.h"
#include "lrotable.h"
#include "module.h"
#include "platform.h"
#include "user_interface.h"
#define NOP asm volatile(" nop \n\t")
static inline void apa102_send_byte(uint32_t data_pin, uint32_t clock_pin, uint8_t byte) {
int i;
for (i = 0; i < 8; i++) {
if (byte & 0x80) {
GPIO_OUTPUT_SET(data_pin, PLATFORM_GPIO_HIGH); // Set pin high
} else {
GPIO_OUTPUT_SET(data_pin, PLATFORM_GPIO_LOW); // Set pin low
}
GPIO_OUTPUT_SET(clock_pin, PLATFORM_GPIO_HIGH); // Set pin high
byte <<= 1;
NOP;
NOP;
GPIO_OUTPUT_SET(clock_pin, PLATFORM_GPIO_LOW); // Set pin low
NOP;
NOP;
}
}
static void apa102_send_buffer(uint32_t data_pin, uint32_t clock_pin, uint32_t *buf, uint32_t nbr_frames) {
int i;
// Send 32-bit Start Frame that's all 0x00
apa102_send_byte(data_pin, clock_pin, 0x00);
apa102_send_byte(data_pin, clock_pin, 0x00);
apa102_send_byte(data_pin, clock_pin, 0x00);
apa102_send_byte(data_pin, clock_pin, 0x00);
// Send 32-bit LED Frames
for (i = 0; i < nbr_frames; i++) {
uint8_t *byte = (uint8_t *) buf++;
// Set the first 3 bits of that byte to 1.
// This makes the lua interface easier to use since you
// don't have to worry about creating invalid LED Frames.
byte[0] |= 0xE0;
apa102_send_byte(data_pin, clock_pin, byte[0]);
apa102_send_byte(data_pin, clock_pin, byte[1]);
apa102_send_byte(data_pin, clock_pin, byte[2]);
apa102_send_byte(data_pin, clock_pin, byte[3]);
}
// Send 32-bit End Frames
uint32_t required_postamble_frames = (nbr_frames + 1) / 2;
for (i = 0; i < required_postamble_frames; i++) {
apa102_send_byte(data_pin, clock_pin, 0xFF);
apa102_send_byte(data_pin, clock_pin, 0xFF);
apa102_send_byte(data_pin, clock_pin, 0xFF);
apa102_send_byte(data_pin, clock_pin, 0xFF);
}
}
// Lua: apa102.write(data_pin, clock_pin, "string")
// Byte quads in the string are interpreted as (brightness, B, G, R) values.
// Only the first 5 bits of the brightness value is actually used (0-31).
// This function does not corrupt your buffer.
//
// apa102.write(1, 3, string.char(31, 0, 255, 0)) uses GPIO5 for DATA and GPIO0 for CLOCK and sets the first LED green, with the brightness 31 (out of 0-32)
// apa102.write(5, 6, string.char(255, 0, 0, 255):rep(10)) uses GPIO14 for DATA and GPIO12 for CLOCK and sets ten LED to red, with the brightness 31 (out of 0-32).
// Brightness values are clamped to 0-31.
static int apa102_write(lua_State* L) {
uint8_t data_pin = luaL_checkinteger(L, 1);
MOD_CHECK_ID(gpio, data_pin);
uint32_t alt_data_pin = pin_num[data_pin];
uint8_t clock_pin = luaL_checkinteger(L, 2);
MOD_CHECK_ID(gpio, clock_pin);
uint32_t alt_clock_pin = pin_num[clock_pin];
size_t buf_len;
const char *buf = luaL_checklstring(L, 3, &buf_len);
uint32_t nbr_frames = buf_len / 4;
if (nbr_frames > 100000) {
return luaL_error(L, "The supplied buffer is too long, and might cause the callback watchdog to bark.");
}
// Initialize the output pins
platform_gpio_mode(data_pin, PLATFORM_GPIO_OUTPUT, PLATFORM_GPIO_FLOAT);
GPIO_OUTPUT_SET(alt_data_pin, PLATFORM_GPIO_HIGH); // Set pin high
platform_gpio_mode(clock_pin, PLATFORM_GPIO_OUTPUT, PLATFORM_GPIO_FLOAT);
GPIO_OUTPUT_SET(alt_clock_pin, PLATFORM_GPIO_LOW); // Set pin low
// Send the buffers
apa102_send_buffer(alt_data_pin, alt_clock_pin, (uint32_t *) buf, (uint32_t) nbr_frames);
return 0;
}
const LUA_REG_TYPE apa102_map[] =
{
{ LSTRKEY( "write" ), LFUNCVAL( apa102_write )},
{ LNILKEY, LNILVAL}
};
LUALIB_API int luaopen_apa102(lua_State *L) {
LREGISTER(L, "apa102", apa102_map);
return 0;
}
NODEMCU_MODULE(APA102, "apa102", apa102_map, luaopen_apa102);
// ***************************************************************************
// BMP280 module for ESP8266 with nodeMCU
//
// Written by Lukas Voborsky, @voborsky
//
// MIT license, http://opensource.org/licenses/MIT
// ***************************************************************************
//#define NODE_DEBUG
#include "module.h"
#include "lauxlib.h"
#include "platform.h"
#include "c_math.h"
/****************************************************/
/**\name registers definition */
/***************************************************/
#define BME280_REGISTER_CONTROL (0xF4)
#define BME280_REGISTER_CONTROL_HUM (0xF2)
#define BME280_REGISTER_CONFIG (0xF5)
#define BME280_REGISTER_CHIPID (0xD0)
#define BME280_REGISTER_VERSION (0xD1)
#define BME280_REGISTER_SOFTRESET (0xE0)
#define BME280_REGISTER_CAL26 (0xE1)
#define BME280_REGISTER_TEMP (0xFA)
#define BME280_REGISTER_PRESS (0xF7)
#define BME280_REGISTER_HUM (0xFD)
#define BME280_REGISTER_DIG_T (0x88)
#define BME280_REGISTER_DIG_P (0x8E)
#define BME280_REGISTER_DIG_H1 (0xA1)
#define BME280_REGISTER_DIG_H2 (0xE1)
/****************************************************/
/**\name I2C ADDRESS DEFINITIONS */
/***************************************************/
#define BME280_I2C_ADDRESS1 (0x76)
#define BME280_I2C_ADDRESS2 (0x77)
/****************************************************/
/**\name POWER MODE DEFINITIONS */
/***************************************************/
/* Sensor Specific constants */
#define BME280_SLEEP_MODE (0x00)
#define BME280_FORCED_MODE (0x01)
#define BME280_NORMAL_MODE (0x03)
#define BME280_SOFT_RESET_CODE (0xB6)
/****************************************************/
/**\name OVER SAMPLING DEFINITIONS */
/***************************************************/
#define BME280_OVERSAMP_1X (0x01)
#define BME280_OVERSAMP_2X (0x02)
#define BME280_OVERSAMP_4X (0x03)
#define BME280_OVERSAMP_8X (0x04)
#define BME280_OVERSAMP_16X (0x05)
/****************************************************/
/**\name STANDBY DEFINITIONS */
/***************************************************/
#define BME280_STANDBY_TIME_1_MS (0x00)
#define BME280_STANDBY_TIME_63_MS (0x01)
#define BME280_STANDBY_TIME_125_MS (0x02)
#define BME280_STANDBY_TIME_250_MS (0x03)
#define BME280_STANDBY_TIME_500_MS (0x04)
#define BME280_STANDBY_TIME_1000_MS (0x05)
#define BME280_STANDBY_TIME_10_MS (0x06)
#define BME280_STANDBY_TIME_20_MS (0x07)
/****************************************************/
/**\name FILTER DEFINITIONS */
/***************************************************/
#define BME280_FILTER_COEFF_OFF (0x00)
#define BME280_FILTER_COEFF_2 (0x01)
#define BME280_FILTER_COEFF_4 (0x02)
#define BME280_FILTER_COEFF_8 (0x03)
#define BME280_FILTER_COEFF_16 (0x04)
/****************************************************/
/**\data type definition */
/***************************************************/
#define BME280_S32_t int32_t
#define BME280_U32_t uint32_t
#define BME280_S64_t int64_t
#define BME280_SAMPLING_DELAY 113 //maximum measurement time in ms for maximum oversampling for all measures = 1.25 + 2.3*16 + 2.3*16 + 0.575 + 2.3*16 + 0.575 ms
#define r16s(reg) ((int16_t)r16u(reg))
#define r16sLE(reg) ((int16_t)r16uLE(reg))
#define bme280_adc_T(void) r24u(BME280_REGISTER_TEMP)
#define bme280_adc_P(void) r24u(BME280_REGISTER_PRESS)
#define bme280_adc_H(void) r16u(BME280_REGISTER_HUM)
static const uint32_t bme280_i2c_id = 0;
static uint8_t bme280_i2c_addr = BME280_I2C_ADDRESS1;
static uint8_t bme280_isbme = 0; // 1 if the chip is BME280, 0 for BMP280
static uint8_t bme280_mode = 0; // stores oversampling settings
static uint8_t bme280_ossh = 0; // stores humidity oversampling settings
os_timer_t bme280_timer; // timer for forced mode readout
int lua_connected_readout_ref; // callback when readout is ready
static struct {
uint16_t dig_T1;
int16_t dig_T2;
int16_t dig_T3;
uint16_t dig_P1;
int16_t dig_P2;
int16_t dig_P3;
int16_t dig_P4;
int16_t dig_P5;
int16_t dig_P6;
int16_t dig_P7;
int16_t dig_P8;
int16_t dig_P9;
uint8_t dig_H1;
int16_t dig_H2;
uint8_t dig_H3;
int16_t dig_H4;
int16_t dig_H5;
int8_t dig_H6;
} bme280_data;
static BME280_S32_t bme280_t_fine;
static uint32_t bme280_h = 0;
static double bme280_hc = 0.0;
static uint8_t r8u(uint8_t reg) {
uint8_t ret;
platform_i2c_send_start(bme280_i2c_id);
platform_i2c_send_address(bme280_i2c_id, bme280_i2c_addr, PLATFORM_I2C_DIRECTION_TRANSMITTER);
platform_i2c_send_byte(bme280_i2c_id, reg);
platform_i2c_send_stop(bme280_i2c_id);
platform_i2c_send_start(bme280_i2c_id);
platform_i2c_send_address(bme280_i2c_id, bme280_i2c_addr, PLATFORM_I2C_DIRECTION_RECEIVER);
ret = platform_i2c_recv_byte(bme280_i2c_id, 0);
platform_i2c_send_stop(bme280_i2c_id);
//NODE_DBG("reg:%x, value:%x \n", reg, ret);
return ret;
}
static uint8_t w8u(uint8_t reg, uint8_t val) {
platform_i2c_send_start(bme280_i2c_id);
platform_i2c_send_address(bme280_i2c_id, bme280_i2c_addr, PLATFORM_I2C_DIRECTION_TRANSMITTER);
platform_i2c_send_byte(bme280_i2c_id, reg);
platform_i2c_send_byte(bme280_i2c_id, val);
platform_i2c_send_stop(bme280_i2c_id);
}
static uint16_t r16u(uint8_t reg) {
uint8_t high = r8u(reg);
uint8_t low = r8u(++reg);
return (high << 8) | low;
}
static uint16_t r16uLE(uint8_t reg) {
uint8_t low = r8u(reg);
uint8_t high = r8u(++reg);
return (high << 8) | low;
}
static uint32_t r24u(uint8_t reg) {
uint8_t high = r8u(reg);
uint8_t mid = r8u(++reg);
uint8_t low = r8u(++reg);
return (uint32_t)(((high << 16) | (mid << 8) | low) >> 4);
}
// Returns temperature in DegC, resolution is 0.01 DegC. Output value of “5123” equals 51.23 DegC.
// t_fine carries fine temperature as global value
static BME280_S32_t bme280_compensate_T(BME280_S32_t adc_T) {
BME280_S32_t var1, var2, T;
var1 = ((((adc_T>>3) - ((BME280_S32_t)bme280_data.dig_T1<<1))) * ((BME280_S32_t)bme280_data.dig_T2)) >> 11;
var2 = (((((adc_T>>4) - ((BME280_S32_t)bme280_data.dig_T1)) * ((adc_T>>4) - ((BME280_S32_t)bme280_data.dig_T1))) >> 12) *
((BME280_S32_t)bme280_data.dig_T3)) >> 14;
bme280_t_fine = var1 + var2;
T = (bme280_t_fine * 5 + 128) >> 8;
return T;
}
// Returns pressure in Pa as unsigned 32 bit integer in Q24.8 format (24 integer bits and 8 fractional bits).
// Output value of “24674867” represents 24674867/256 = 96386.2 Pa = 963.862 hPa
static BME280_U32_t bme280_compensate_P(BME280_S32_t adc_P) {
BME280_S64_t var1, var2, p;
var1 = ((BME280_S64_t)bme280_t_fine) - 128000;
var2 = var1 * var1 * (BME280_S64_t)bme280_data.dig_P6;
var2 = var2 + ((var1*(BME280_S64_t)bme280_data.dig_P5)<<17);
var2 = var2 + (((BME280_S64_t)bme280_data.dig_P4)<<35);
var1 = ((var1 * var1 * (BME280_S64_t)bme280_data.dig_P3)>>8) + ((var1 * (BME280_S64_t)bme280_data.dig_P2)<<12);
var1 = (((((BME280_S64_t)1)<<47)+var1))*((BME280_S64_t)bme280_data.dig_P1)>>33;
if (var1 == 0) {
return 0; // avoid exception caused by division by zero
}
p = 1048576-adc_P;
p = (((p<<31)-var2)*3125)/var1;
var1 = (((BME280_S64_t)bme280_data.dig_P9) * (p>>13) * (p>>13)) >> 25;
var2 = (((BME280_S64_t)bme280_data.dig_P8) * p) >> 19;
p = ((p + var1 + var2) >> 8) + (((BME280_S64_t)bme280_data.dig_P7)<<4);
p = (p * 10) >> 8;
return (BME280_U32_t)p;
}
// Returns humidity in %RH as unsigned 32 bit integer in Q22.10 format (22 integer and 10 fractional bits).
// Output value of “47445” represents 47445/1024 = 46.333 %RH
static BME280_U32_t bme280_compensate_H(BME280_S32_t adc_H) {
BME280_S32_t v_x1_u32r;
v_x1_u32r = (bme280_t_fine - ((BME280_S32_t)76800));
v_x1_u32r = (((((adc_H << 14) - (((BME280_S32_t)bme280_data.dig_H4) << 20) - (((BME280_S32_t)bme280_data.dig_H5) * v_x1_u32r)) +
((BME280_S32_t)16384)) >> 15) * (((((((v_x1_u32r * ((BME280_S32_t)bme280_data.dig_H6)) >> 10) * (((v_x1_u32r *
((BME280_S32_t)bme280_data.dig_H3)) >> 11) + ((BME280_S32_t)32768))) >> 10) + ((BME280_S32_t)2097152)) *
((BME280_S32_t)bme280_data.dig_H2) + 8192) >> 14));
v_x1_u32r = (v_x1_u32r - (((((v_x1_u32r >> 15) * (v_x1_u32r >> 15)) >> 7) * ((BME280_S32_t)bme280_data.dig_H1)) >> 4));
v_x1_u32r = (v_x1_u32r < 0 ? 0 : v_x1_u32r);
v_x1_u32r = (v_x1_u32r > 419430400 ? 419430400 : v_x1_u32r);
v_x1_u32r = v_x1_u32r>>12;
return (BME280_U32_t)((v_x1_u32r * 1000)>>10);
}
static int bme280_lua_init(lua_State* L) {
uint8_t sda;
uint8_t scl;
uint8_t config;
uint8_t ack;
uint8_t const bit3 = 0b111;
uint8_t const bit2 = 0b11;
if (!lua_isnumber(L, 1) || !lua_isnumber(L, 2)) {
return luaL_error(L, "wrong arg range");
}
sda = luaL_checkinteger(L, 1);
scl = luaL_checkinteger(L, 2);
bme280_mode = (!lua_isnumber(L, 6)?BME280_NORMAL_MODE:(luaL_checkinteger(L, 6)&bit2)) // 6-th parameter: power mode
| ((!lua_isnumber(L, 4)?BME280_OVERSAMP_16X:(luaL_checkinteger(L, 4)&bit3)) << 2) // 4-th parameter: pressure oversampling
| ((!lua_isnumber(L, 3)?BME280_OVERSAMP_16X:(luaL_checkinteger(L, 3)&bit3)) << 5); // 3-rd parameter: temperature oversampling
bme280_ossh = (!lua_isnumber(L, 5))?BME280_OVERSAMP_16X:(luaL_checkinteger(L, 5)&bit3); // 5-th parameter: humidity oversampling
config = ((!lua_isnumber(L, 7)?BME280_STANDBY_TIME_20_MS:(luaL_checkinteger(L, 7)&bit3))<< 4) // 7-th parameter: inactive duration in normal mode
| ((!lua_isnumber(L, 8)?BME280_FILTER_COEFF_16:(luaL_checkinteger(L, 8)&bit3)) << 1); // 8-th parameter: IIR filter
NODE_DBG("mode: %x\nhumidity oss: %x\nconfig: %x\n", bme280_mode, bme280_ossh, config);
platform_i2c_setup(bme280_i2c_id, sda, scl, PLATFORM_I2C_SPEED_SLOW);
bme280_i2c_addr = BME280_I2C_ADDRESS1;
platform_i2c_send_start(bme280_i2c_id);
ack = platform_i2c_send_address(bme280_i2c_id, bme280_i2c_addr, PLATFORM_I2C_DIRECTION_TRANSMITTER);
platform_i2c_send_stop(bme280_i2c_id);
if (!ack) {
NODE_DBG("No ACK on address: %x\n", bme280_i2c_addr);
bme280_i2c_addr = BME280_I2C_ADDRESS2;
platform_i2c_send_start(bme280_i2c_id);
ack = platform_i2c_send_address(bme280_i2c_id, bme280_i2c_addr, PLATFORM_I2C_DIRECTION_TRANSMITTER);
platform_i2c_send_stop(bme280_i2c_id);
if (!ack) {
NODE_DBG("No ACK on address: %x\n", bme280_i2c_addr);
return 0;
}
}
uint8_t chipid = r8u(BME280_REGISTER_CHIPID);
NODE_DBG("chip_id: %x\n", chipid);
bme280_isbme = (chipid == 0x60);
uint8_t reg = BME280_REGISTER_DIG_T;
bme280_data.dig_T1 = r16uLE(reg); reg+=2;
bme280_data.dig_T2 = r16sLE(reg); reg+=2;
bme280_data.dig_T3 = r16sLE(reg);
//NODE_DBG("dig_T: %d\t%d\t%d\n", bme280_data.dig_T1, bme280_data.dig_T2, bme280_data.dig_T3);
reg = BME280_REGISTER_DIG_P;
bme280_data.dig_P1 = r16uLE(reg); reg+=2;
bme280_data.dig_P2 = r16sLE(reg); reg+=2;
bme280_data.dig_P3 = r16sLE(reg); reg+=2;
bme280_data.dig_P4 = r16sLE(reg); reg+=2;
bme280_data.dig_P5 = r16sLE(reg); reg+=2;
bme280_data.dig_P6 = r16sLE(reg); reg+=2;
bme280_data.dig_P7 = r16sLE(reg); reg+=2;
bme280_data.dig_P8 = r16sLE(reg); reg+=2;
bme280_data.dig_P9 = r16sLE(reg);
// NODE_DBG("dig_P: %d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\n", bme280_data.dig_P1, bme280_data.dig_P2, bme280_data.dig_P3, bme280_data.dig_P4, bme280_data.dig_P5, bme280_data.dig_P6, bme280_data.dig_P7, bme280_data.dig_P8, bme280_data.dig_P9);
w8u(BME280_REGISTER_CONFIG, config);
if (bme280_isbme) {
reg = BME280_REGISTER_DIG_H1;
bme280_data.dig_H1 = r8u(reg);
reg = BME280_REGISTER_DIG_H2;
bme280_data.dig_H2 = r16sLE(reg); reg+=2;
bme280_data.dig_H3 = r8u(reg); reg++;
bme280_data.dig_H4 = ((int16_t)r8u(reg) << 4 | (r8u(reg+1) & 0xF)); reg+=2;
bme280_data.dig_H5 = ((int16_t)r8u(reg+1) << 4 | (r8u(reg) >> 4)); reg+=2;
bme280_data.dig_H6 = (int8_t)r8u(reg);
// NODE_DBG("dig_H: %d\t%d\t%d\t%d\t%d\t%d\n", bme280_data.dig_H1, bme280_data.dig_H2, bme280_data.dig_H3, bme280_data.dig_H4, bme280_data.dig_H5, bme280_data.dig_H6);
w8u(BME280_REGISTER_CONTROL_HUM, bme280_ossh);
lua_pushinteger(L, 2);
} else {
lua_pushinteger(L, 1);
}
w8u(BME280_REGISTER_CONTROL, bme280_mode);
return 1;
}
static void bme280_readoutdone (void *arg)
{
NODE_DBG("timer out\n");
lua_State *L = arg;
lua_rawgeti (L, LUA_REGISTRYINDEX, lua_connected_readout_ref);
lua_call (L, 0, 0);
luaL_unref (L, LUA_REGISTRYINDEX, lua_connected_readout_ref);
os_timer_disarm (&bme280_timer);
}
static int bme280_lua_startreadout(lua_State* L) {
uint32_t delay;
if (lua_isnumber(L, 1)) {
delay = luaL_checkinteger(L, 1);
if (!delay) {delay = BME280_SAMPLING_DELAY;} // if delay is 0 then set the default delay
}
if (!lua_isnoneornil(L, 2)) {
lua_pushvalue(L, 2);
lua_connected_readout_ref = luaL_ref(L, LUA_REGISTRYINDEX);
} else {
lua_connected_readout_ref = LUA_NOREF;
}
w8u(BME280_REGISTER_CONTROL_HUM, bme280_ossh);
w8u(BME280_REGISTER_CONTROL, (bme280_mode & 0xFC) | BME280_FORCED_MODE);
NODE_DBG("control old: %x, control: %x, delay: %d\n", bme280_mode, (bme280_mode & 0xFC) | BME280_FORCED_MODE, delay);
if (lua_connected_readout_ref != LUA_NOREF) {
NODE_DBG("timer armed\n");
os_timer_disarm (&bme280_timer);
os_timer_setfn (&bme280_timer, (os_timer_func_t *)bme280_readoutdone, L);
os_timer_arm (&bme280_timer, delay, 0); // trigger callback when readout is ready
}
return 0;
}
static int bme280_lua_temp(lua_State* L) {
uint32_t adc_T = bme280_adc_T();
if (adc_T == 0x80000 || adc_T == 0xfffff)
return 0;
lua_pushinteger(L, bme280_compensate_T(adc_T));
lua_pushinteger(L, bme280_t_fine);
return 2;
}
static int bme280_lua_baro(lua_State* L) {
uint32_t adc_T = bme280_adc_T();
uint32_t T = bme280_compensate_T(adc_T);
uint32_t adc_P = bme280_adc_P();
if (adc_T == 0x80000 || adc_T == 0xfffff || adc_P ==0x80000 || adc_P == 0xfffff)
return 0;
lua_pushinteger(L, bme280_compensate_P(adc_P));
lua_pushinteger(L, T);
return 2;
}
static int bme280_lua_humi(lua_State* L) {
if (!bme280_isbme) return 0;
uint32_t adc_T = bme280_adc_T();
uint32_t T = bme280_compensate_T(adc_T);
uint32_t adc_H = bme280_adc_H();
if (adc_T == 0x80000 || adc_T == 0xfffff || adc_H == 0x8000 || adc_H == 0xffff)
return 0;
lua_pushinteger(L, bme280_compensate_H(adc_H));
lua_pushinteger(L, T);
return 2;
}
static int bme280_lua_qfe2qnh(lua_State* L) {
if (!lua_isnumber(L, 2)) {
return luaL_error(L, "wrong arg range");
}
int32_t qfe = luaL_checkinteger(L, 1);
int32_t h = luaL_checkinteger(L, 2);
double hc;
if (bme280_h == h) {
hc = bme280_hc;
} else {
hc = pow((double)(1.0 - 2.25577e-5 * h), (double)(-5.25588));
bme280_hc = hc; bme280_h = h;
}
double qnh = (double)qfe * hc;
lua_pushinteger(L, (int32_t)(qnh + 0.5));
return 1;
}
static int bme280_lua_altitude(lua_State* L) {
if (!lua_isnumber(L, 2)) {
return luaL_error(L, "wrong arg range");
}
int32_t P = luaL_checkinteger(L, 1);
int32_t qnh = luaL_checkinteger(L, 2);
double h = (1.0 - pow((double)P/(double)qnh, 1.0/5.25588)) / 2.25577e-5 * 100.0;
lua_pushinteger(L, (int32_t)(h + (((h<0)?-1:(h>0)) * 0.5)));
return 1;
}
static double ln(double x) {
double y = (x-1)/(x+1);
double y2 = y*y;
double r = 0;
for (int8_t i=33; i>0; i-=2) { //we've got the power
r = 1.0/(double)i + y2 * r;
}
return 2*y*r;
}
static int bme280_lua_dewpoint(lua_State* L) {
const double c243 = 243.5;
const double c17 = 17.67;
if (!lua_isnumber(L, 2)) {
return luaL_error(L, "wrong arg range");
}
double H = luaL_checkinteger(L, 1)/100000.0;
double T = luaL_checkinteger(L, 2)/100.0;
double c = ln(H) + ((c17 * T) / (c243 + T));
double d = (c243 * c)/(c17 - c) * 100.0;
lua_pushinteger(L, (int32_t)(d + (((d<0)?-1:(d>0)) * 0.5)));
return 1;
}
static const LUA_REG_TYPE bme280_map[] = {
{ LSTRKEY( "init" ), LFUNCVAL(bme280_lua_init)},
{ LSTRKEY( "temp" ), LFUNCVAL(bme280_lua_temp)},
{ LSTRKEY( "baro" ), LFUNCVAL(bme280_lua_baro)},
{ LSTRKEY( "humi" ), LFUNCVAL(bme280_lua_humi)},
{ LSTRKEY( "startreadout" ), LFUNCVAL(bme280_lua_startreadout)},
{ LSTRKEY( "qfe2qnh" ), LFUNCVAL(bme280_lua_qfe2qnh)},
{ LSTRKEY( "altitude" ), LFUNCVAL(bme280_lua_altitude)},
{ LSTRKEY( "dewpoint" ), LFUNCVAL(bme280_lua_dewpoint)},
{ LNILKEY, LNILVAL}
};
NODEMCU_MODULE(BME280, "bme280", bme280_map, NULL);
......@@ -74,7 +74,7 @@ static int ICACHE_FLASH_ATTR bmp085_init(lua_State* L) {
bmp085_data.MC = r16(bmp085_i2c_id, 0xBC);
bmp085_data.MD = r16(bmp085_i2c_id, 0xBE);
return 1;
return 0;
}
static uint32_t bmp085_temperature_raw_b5(void) {
......
......@@ -43,6 +43,7 @@
#include "c_limits.h"
#include "lauxlib.h"
#include "flash_api.h"
#include "ctype.h"
#include "strbuf.h"
#include "cjson_mem.h"
......
......@@ -326,7 +326,7 @@ static int coap_request( lua_State* L, coap_method_t m )
stack++;
pesp_conn = cud->pesp_conn;
ip_addr_t ipaddr;
uint8_t host[32];
uint8_t host[64];
unsigned t;
if ( lua_isnumber(L, stack) )
......@@ -348,6 +348,9 @@ static int coap_request( lua_State* L, coap_method_t m )
coap_uri_t *uri = coap_new_uri(url, l); // should call free(uri) somewhere
if (uri == NULL)
return luaL_error( L, "uri wrong format." );
if (uri->host.length + 1 /* for the null */ > sizeof(host)) {
return luaL_error(L, "host too long");
}
pesp_conn->proto.udp->remote_port = uri->port;
NODE_DBG("UDP port is set: %d.\n", uri->port);
......@@ -372,7 +375,7 @@ static int coap_request( lua_State* L, coap_method_t m )
if(!pdu){
if(uri)
c_free(uri);
return;
return luaL_error (L, "alloc fail");
}
const char *payload = NULL;
......
// Module for cryptography
#include <c_errno.h>
#include "module.h"
#include "lauxlib.h"
#include "platform.h"
#include "c_types.h"
#include "c_stdlib.h"
#include "flash_fs.h"
#include "../crypto/digests.h"
#include "../crypto/mech.h"
#include "user_interface.h"
......@@ -34,7 +37,29 @@ static int crypto_sha1( lua_State* L )
return 1;
}
#ifdef LUA_USE_MODULES_ENCODER
static int call_encoder( lua_State* L, const char *function ) {
if (lua_gettop(L) != 1) {
luaL_error(L, "%s must have one argument", function);
}
lua_getfield(L, LUA_GLOBALSINDEX, "encoder");
if (!lua_istable(L, -1) && !lua_isrotable(L, -1)) { // also need table just in case encoder has been overloaded
luaL_error(L, "Cannot find encoder.%s", function);
}
lua_getfield(L, -1, function);
lua_insert(L, 1); //move function below the argument
lua_pop(L, 1); //and dump the encoder rotable from stack.
lua_call(L,1,1); // call encoder.xxx(string)
return 1;
}
static int crypto_base64_encode (lua_State* L) {
return call_encoder(L, "toBase64");
}
static int crypto_hex_encode (lua_State* L) {
return call_encoder(L, "toHex");
}
#else
static const char* bytes64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/**
* encoded = crypto.toBase64(raw)
......@@ -81,7 +106,7 @@ static int crypto_hex_encode( lua_State* L)
c_free(out);
return 1;
}
#endif
/**
* masked = crypto.mask(message, mask)
*
......@@ -102,10 +127,9 @@ static int crypto_mask( lua_State* L )
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"); }
static inline int bad_file (lua_State *L) { return luaL_error (L, "file does not exist"); }
/* rawdigest = crypto.hash("MD5", str)
* strdigest = crypto.toHex(rawdigest)
......@@ -126,6 +150,132 @@ static int crypto_lhash (lua_State *L)
return 1;
}
typedef struct digest_user_datum_t {
const digest_mech_info_t *mech_info;
void *ctx;
} digest_user_datum_t;
/* General Usage for extensible hash functions:
* sha = crypto.new_hash("MD5")
* sha.update("Data")
* sha.update("Data2")
* strdigest = crypto.toHex(sha.finalize())
*/
/* crypto.new_hash("MECHTYPE") */
static int crypto_new_hash (lua_State *L)
{
const digest_mech_info_t *mi = crypto_digest_mech (luaL_checkstring (L, 1));
if (!mi)
return bad_mech (L);
void *ctx = os_malloc (mi->ctx_size);
if (ctx==NULL)
return bad_mem (L);
mi->create (ctx);
// create a userdataum with specific metatable
digest_user_datum_t *dudat = (digest_user_datum_t *)lua_newuserdata(L, sizeof(digest_user_datum_t));
luaL_getmetatable(L, "crypto.hash");
lua_setmetatable(L, -2);
// Set pointers to the mechanics and CTX
dudat->mech_info = mi;
dudat->ctx = ctx;
return 1; // Pass userdata object back
}
/* Called as object, params:
1 - userdata "this"
2 - new string to add to the hash state */
static int crypto_hash_update (lua_State *L)
{
NODE_DBG("enter crypto_hash_update.\n");
digest_user_datum_t *dudat;
size_t sl;
dudat = (digest_user_datum_t *)luaL_checkudata(L, 1, "crypto.hash");
luaL_argcheck(L, dudat, 1, "crypto.hash expected");
const digest_mech_info_t *mi = dudat->mech_info;
size_t len = 0;
const char *data = luaL_checklstring (L, 2, &len);
mi->update (dudat->ctx, data, len);
return 0; // No return value
}
/* Called as object, no params. Returns digest of default size. */
static int crypto_hash_finalize (lua_State *L)
{
NODE_DBG("enter crypto_hash_update.\n");
digest_user_datum_t *dudat;
size_t sl;
dudat = (digest_user_datum_t *)luaL_checkudata(L, 1, "crypto.hash");
luaL_argcheck(L, dudat, 1, "crypto.hash expected");
const digest_mech_info_t *mi = dudat->mech_info;
uint8_t digest[mi->digest_size]; // Allocate as local
mi->finalize (digest, dudat->ctx);
lua_pushlstring (L, digest, sizeof (digest));
return 1;
}
/* Frees memory for the user datum and CTX hash state */
static int crypto_hash_gcdelete (lua_State *L)
{
NODE_DBG("enter crypto_hash_delete.\n");
digest_user_datum_t *dudat;
dudat = (digest_user_datum_t *)luaL_checkudata(L, 1, "crypto.hash");
luaL_argcheck(L, dudat, 1, "crypto.hash expected");
os_free(dudat->ctx);
return 0;
}
/* rawdigest = crypto.hash("MD5", filename)
* strdigest = crypto.toHex(rawdigest)
*/
static int crypto_flhash (lua_State *L)
{
const digest_mech_info_t *mi = crypto_digest_mech (luaL_checkstring (L, 1));
if (!mi)
return bad_mech (L);
const char *filename = luaL_checkstring (L, 2);
// Open the file
int file_fd = fs_open (filename, FS_RDONLY);
if(file_fd < FS_OPEN_OK) {
return bad_file(L);
}
// Compute hash
uint8_t digest[mi->digest_size];
int returncode = crypto_fhash (mi, &fs_read, file_fd, digest);
// Finish up
fs_close(file_fd);
if (returncode == ENOMEM)
return bad_mem (L);
else if (returncode == EINVAL)
return bad_mech(L);
else
lua_pushlstring (L, digest, sizeof (digest));
return 1;
}
/* rawsignature = crypto.hmac("SHA1", str, key)
* strsignature = crypto.toHex(rawsignature)
......@@ -149,6 +299,78 @@ static int crypto_lhmac (lua_State *L)
}
static const crypto_mech_t *get_mech (lua_State *L, int idx)
{
const char *name = luaL_checkstring (L, idx);
const crypto_mech_t *mech = crypto_encryption_mech (name);
if (mech)
return mech;
luaL_error (L, "unknown cipher: %s", name);
__builtin_unreachable ();
}
static int crypto_encdec (lua_State *L, bool enc)
{
const crypto_mech_t *mech = get_mech (L, 1);
size_t klen;
const char *key = luaL_checklstring (L, 2, &klen);
size_t dlen;
const char *data = luaL_checklstring (L, 3, &dlen);
size_t ivlen;
const char *iv = luaL_optlstring (L, 4, "", &ivlen);
size_t bs = mech->block_size;
size_t outlen = ((dlen + bs -1) / bs) * bs;
char *buf = (char *)os_zalloc (outlen);
if (!buf)
return luaL_error (L, "crypto init failed");
crypto_op_t op =
{
key, klen,
iv, ivlen,
data, dlen,
buf, outlen,
enc ? OP_ENCRYPT : OP_DECRYPT
};
if (!mech->run (&op))
{
os_free (buf);
return luaL_error (L, "crypto op failed");
}
else
{
lua_pushlstring (L, buf, outlen);
// note: if lua_pushlstring runs out of memory, we leak buf :(
os_free (buf);
return 1;
}
}
static int lcrypto_encrypt (lua_State *L)
{
return crypto_encdec (L, true);
}
static int lcrypto_decrypt (lua_State *L)
{
return crypto_encdec (L, false);
}
// Hash function map
static const LUA_REG_TYPE crypto_hash_map[] = {
{ LSTRKEY( "update" ), LFUNCVAL( crypto_hash_update ) },
{ LSTRKEY( "finalize" ), LFUNCVAL( crypto_hash_finalize ) },
{ LSTRKEY( "__gc" ), LFUNCVAL( crypto_hash_gcdelete ) },
{ LSTRKEY( "__index" ), LROVAL( crypto_hash_map ) },
{ LNILKEY, LNILVAL }
};
// Module function map
static const LUA_REG_TYPE crypto_map[] = {
{ LSTRKEY( "sha1" ), LFUNCVAL( crypto_sha1 ) },
......@@ -156,8 +378,18 @@ static const LUA_REG_TYPE crypto_map[] = {
{ LSTRKEY( "toHex" ), LFUNCVAL( crypto_hex_encode ) },
{ LSTRKEY( "mask" ), LFUNCVAL( crypto_mask ) },
{ LSTRKEY( "hash" ), LFUNCVAL( crypto_lhash ) },
{ LSTRKEY( "fhash" ), LFUNCVAL( crypto_flhash ) },
{ LSTRKEY( "new_hash" ), LFUNCVAL( crypto_new_hash ) },
{ LSTRKEY( "hmac" ), LFUNCVAL( crypto_lhmac ) },
{ LSTRKEY( "encrypt" ), LFUNCVAL( lcrypto_encrypt ) },
{ LSTRKEY( "decrypt" ), LFUNCVAL( lcrypto_decrypt ) },
{ LNILKEY, LNILVAL }
};
NODEMCU_MODULE(CRYPTO, "crypto", crypto_map, NULL);
int luaopen_crypto ( lua_State *L )
{
luaL_rometatable(L, "crypto.hash", (void *)crypto_hash_map); // create metatable for crypto.hash
return 0;
}
NODEMCU_MODULE(CRYPTO, "crypto", crypto_map, luaopen_crypto);
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