Unverified Commit b41667b8 authored by Marcel Stör's avatar Marcel Stör Committed by GitHub
Browse files

Master drop #2486

Dev -> Master Release 10
parents f99f295d 0abb2617
......@@ -31,6 +31,7 @@
#define c_freopen freopen
#define c_getc getc
#define c_getenv getenv
#define c_malloc malloc
#define c_memcmp memcmp
#define c_memcpy memcpy
#define c_printf printf
......@@ -56,9 +57,10 @@
#define c_strrchr strrchr
#define c_strstr strstr
double c_strtod(const char *__n, char **__end_PTR);
#define c_strtoul strtoul
#define c_ungetc ungetc
#define c_strtol strtol
#define c_strtoul strtoul
#define dbg_printf printf
#else
#define C_HEADER_ASSERT "c_assert.h"
......
#
# This Make file is called from the core Makefile hierarchy which is a hierarchical
# make which uses parent callbacks to implement inheritance. However if luac_cross
# build stands outside this it uses the host toolchain to implement a separate
# host build of the luac.cross image.
#
.NOTPARALLEL:
CCFLAGS:= -I.. -I../../include -I../../../include -I ../../libc
LDFLAGS:= -L$(SDK_DIR)/lib -L$(SDK_DIR)/ld -lm -ldl -Wl,-Map=mapfile
CCFLAGS += -Wall
DEFINES += -DLUA_CROSS_COMPILER -DLUA_OPTIMIZE_MEMORY=2
TARGET = host
ifeq ($(FLAVOR),debug)
CCFLAGS += -O0 -g
TARGET_LDFLAGS += -O0 -g
else
FLAVOR = release
CCFLAGS += -O2
TARGET_LDFLAGS += -O2
endif
LUACSRC := luac.c lflashimg.c liolib.c loslib.c print.c
LUASRC := lapi.c lauxlib.c lbaselib.c lcode.c ldblib.c ldebug.c \
ldo.c ldump.c lfunc.c lgc.c linit.c llex.c \
lmathlib.c lmem.c loadlib.c lobject.c lopcodes.c lparser.c \
lrotable.c lstate.c lstring.c lstrlib.c ltable.c ltablib.c \
ltm.c lundump.c lvm.c lzio.c
LIBCSRC := c_stdlib.c
#
# This relies on the files being unique on the vpath
#
SRC := $(LUACSRC) $(LUASRC) $(LIBCSRC)
vpath %.c .:..:../../libc
ODIR := .output/$(TARGET)/$(FLAVOR)/obj
OBJS := $(SRC:%.c=$(ODIR)/%.o)
DEPS := $(SRC:%.c=$(ODIR)/%.d)
CFLAGS = $(CCFLAGS) $(DEFINES) $(EXTRA_CCFLAGS) $(STD_CFLAGS) $(INCLUDES)
DFLAGS = $(CCFLAGS) $(DDEFINES) $(EXTRA_CCFLAGS) $(STD_CFLAGS) $(INCLUDES)
CC := $(WRAPCC) gcc
ECHO := echo
BUILD_TYPE := $(shell $(CC) $(EXTRA_CCFLAGS) -E -dM - <../../../app/include/user_config.h | grep LUA_NUMBER_INTEGRAL | wc -l)
ifeq ($(BUILD_TYPE),0)
IMAGE := ../../../luac.cross
else
IMAGE := ../../../luac.cross.int
endif
.PHONY: test clean all
all: $(DEPS) $(IMAGE)
$(IMAGE) : $(OBJS)
$(CC) $(OBJS) -o $@ $(LDFLAGS)
test :
@echo CC: $(CC)
@echo SRC: $(SRC)
@echo OBJS: $(OBJS)
@echo DEPS: $(DEPS)
@echo IMAGE: $(IMAGE)
clean :
$(RM) -r $(ODIR)
ifneq ($(MAKECMDGOALS),clean)
-include $(DEPS)
endif
$(ODIR)/%.o: %.c
@mkdir -p $(ODIR);
$(CC) $(if $(findstring $<,$(DSRCS)),$(DFLAGS),$(CFLAGS)) $(COPTS_$(*F)) -o $@ -c $<
$(ODIR)/%.d: %.c
@mkdir -p $(ODIR);
@echo DEPEND: $(CC) -M $(CFLAGS) $<
@set -e; rm -f $@; \
$(CC) -M $(CFLAGS) $< > $@.$$$$; \
sed 's,\($*\.o\)[ :]*,$(ODIR)/\1 $@ : ,g' < $@.$$$$ > $@; \
rm -f $@.$$$$
/*
** lflashimg.c
** Dump a compiled Proto hiearchy to a RO (FLash) image file
** See Copyright Notice in lua.h
*/
#define LUAC_CROSS_FILE
#include "luac_cross.h"
#include C_HEADER_CTYPE
#include C_HEADER_STDIO
#include C_HEADER_STDLIB
#include C_HEADER_STRING
#define lflashimg_c
#define LUA_CORE
#include "lobject.h"
#include "lstring.h"
#undef LUA_FLASH_STORE
#define LUA_FLASH_STORE
#include "lflash.h"
//#define LOCAL_DEBUG
#if INT_MAX != 2147483647
# error "luac.cross requires C toolchain with 4 byte word size"
#endif
#define WORDSIZE ((int) sizeof(int))
#define ALIGN(s) (((s)+(WORDSIZE-1)) & (-(signed) WORDSIZE))
#define WORDSHIFT 2
typedef unsigned int uint;
#define FLASH_WORDS(t) (sizeof(t)/sizeof(FlashAddr))
/*
*
* This dumper is a variant of the standard ldump, in that instead of producing a
* binary loader format that lundump can load, it produces an image file that can be
* directly mapped or copied into addressable memory. The typical application is on
* small memory IoT devices which support programmable flash storage such as the
* ESP8266. A 64 Kb LFS image has 16Kb words and will enable all program-related
* storage to be accessed directly from flash, leaving the RAM for true R/W
* application data.
*
* The start address of the Lua Flash Store (LFS) is build-dependent, and the cross
* compiler '-a' option allows the developer to fix the LFS at a defined flash memory
* address. Alternatively and by default the cross compilation adopts a position
* independent image format, which permits the on-device image loader to load the LFS
* image at an appropriate base within the flash address space. As all objects in the
* LFS can be treated as multiples of 4-byte words, also all address fields are both
* word aligned, and any address references within the LFS are also word-aligned,
* such addresses are stored in a special format, where each PI address is two
* 16-bit unsigned offsets:
*
* Bits 0-15 is the offset into the LFS that this address refers to
* Bits 16-31 is the offset linking to the PIC next address.
*
* Hence the LFS can be up to 256Kb in length and the flash loader can use the forward
* links to chain down PI address from the mainProto address at offet 3 to all image
* addresses during load and convert them to the corresponding correct absolute memory
* addresses. This reloation process is skipped for absolute addressed images (which
* are identified by the FLASH_SIG_ABSOLUTE bit setting in the flash signature.
*
* The flash image has a standard header detailed in lflash.h
*
* Note that luac.cross may be compiled on any little-endian machine with 32 or 64 bit
* word length so Flash addresses can't be handled as standard C pointers as size_t
* and int may not have the same size. Hence addresses with the must be declared as
* the FlashAddr type rather than typed C pointers and must be accessed through macros.
*
* ALso note that image built with a given LUA_PACK_TVALUES / LUA_NUNBER_INTEGRAL
* combination must be loaded into a corresponding firmware build. Hence these
* configuration options are also included in the FLash Signature.
*
* The Flash image is assembled up by first building the RO stringtable containing
* all strings used in the compiled proto hierarchy. This is followed by the Protos.
*
* The storage is allocated bottom up using a serial allocator and the algortihm for
* building the image essentially does a bottom-uo serial enumeration so that any
* referenced storage has already been allocated in the image, and therefore (with the
* exception of the Flash Header) all pointer references are backwards.
*
* As addresses are 4 byte on the target and either 4 or (typically) 8 bytes on the
* host so any structures containing address fields (TStrings, TValues, Protos, other
* address vectors) need repacking.
*/
typedef struct flashts { /* This is the fixed 32-bit equivalent of TString */
FlashAddr next;
lu_byte tt;
lu_byte marked;
int hash;
int len;
} FlashTS;
#ifndef LUA_MAX_FLASH_SIZE
#define LUA_MAX_FLASH_SIZE 0x10000 //in words
#endif
static uint curOffset = 0;
static uint flashImage[LUA_MAX_FLASH_SIZE];
static unsigned char flashAddrTag[LUA_MAX_FLASH_SIZE/WORDSIZE];
#define fatal luac_fatal
extern void __attribute__((noreturn)) luac_fatal(const char* message);
#ifdef LOCAL_DEBUG
#define DBG_PRINT(...) printf(__VA_ARGS__)
#else
#define DBG_PRINT(...) ((void)0)
#endif
/*
* Serial allocator. Throw a luac-style out of memory error is allocaiton fails.
*/
static void *flashAlloc(lua_State* L, size_t n) {
void *p = (void *)(flashImage + curOffset);
curOffset += ALIGN(n)>>WORDSHIFT;
if (curOffset > LUA_MAX_FLASH_SIZE) {
fatal("Out of Flash memmory");
}
return p;
}
/*
* Convert an absolute address pointing inside the flash image to offset form.
* This macro form also takes the lvalue destination so that this can be tagged
* as a relocatable address.
*/
#define toFlashAddr(l, pd, s) _toFlashAddr(l, &(pd), s)
static void _toFlashAddr(lua_State* L, FlashAddr *a, void *p) {
uint doffset = cast(char *, a) - cast(char *,flashImage);
lua_assert(!(doffset & (WORDSIZE-1)));
doffset >>= WORDSHIFT;
lua_assert(doffset <= curOffset);
if (p) {
uint poffset = cast(char *, p) - cast(char *,flashImage);
lua_assert(!(poffset & (WORDSIZE-1)));
poffset >>= WORDSHIFT;
lua_assert(poffset <= curOffset);
flashImage[doffset] = poffset; // Set the pointer to the offset
flashAddrTag[doffset] = 1; // And tag as an address
} else { // Special case for NULL pointer
flashImage[doffset] = 0;
}
}
/*
* Convert an image address in offset form back to (host) absolute form
*/
static void *fromFashAddr(FlashAddr a) {
return a ? cast(void *, flashImage + a) : NULL;
}
/*
* Add a TS found in the Proto Load to the table at the ToS
*/
static void addTS(lua_State *L, TString *ts) {
lua_assert(ts->tsv.tt==LUA_TSTRING);
lua_pushnil(L);
setsvalue(L, L->top-1, ts);
lua_pushinteger(L, 1);
lua_rawset(L, -3);
DBG_PRINT("Adding string: %s\n",getstr(ts));
}
/*
* Enumerate all of the Protos in the Proto hiearchy and scan contents to collect
* all referenced strings in a Lua Array at ToS.
*/
static void scanProtoStrings(lua_State *L, const Proto* f) {
/* Table at L->Top[-1] is used to collect the strings */
int i;
if (f->source)
addTS(L, f->source);
#ifdef LUA_OPTIMIZE_DEBUG
if (f->packedlineinfo)
addTS(L, luaS_new(L, cast(const char *, f->packedlineinfo)));
#endif
for (i = 0; i < f->sizek; i++) {
if (ttisstring(f->k + i))
addTS(L, rawtsvalue(f->k + i));
}
for (i = 0; i < f->sizeupvalues; i++) addTS(L, f->upvalues[i]);
for (i = 0; i < f->sizelocvars; i++) addTS(L, f->locvars[i].varname);
for (i = 0; i < f->sizep; i++) scanProtoStrings(L, f->p[i]);
}
/*
* Use the collected strings table to build the new ROstrt in the Flash Image
*
* The input is an array of {"SomeString" = 1, ...} on the ToS.
* The output is an array of {"SomeString" = FlashOffset("SomeString"), ...} on ToS
*/
static void createROstrt(lua_State *L, FlashHeader *fh) {
/* Table at L->Top[-1] on input is hash used to collect the strings */
/* Count the number of strings. Can't use objlen as this is a hash */
fh->nROuse = 0;
lua_pushnil(L); /* first key */
while (lua_next(L, -2) != 0) {
fh->nROuse++;
DBG_PRINT("Found: %s\n",getstr(rawtsvalue(L->top-2)));
lua_pop(L, 1); // dump the value
}
fh->nROsize = 2<<luaO_log2(fh->nROuse);
FlashAddr *hashTab = flashAlloc(L, fh->nROsize * WORDSIZE);
toFlashAddr(L, fh->pROhash, hashTab);
/* Now iterate over the strings to be added to the RO string table and build it */
lua_newtable(L); // add output table
lua_pushnil(L); // First key
while (lua_next(L, -3) != 0) { // replaces key, pushes value
TString *ts = rawtsvalue(L->top - 2); // key.ts
const char *p = getstr(ts); // C string of key
uint hash = ts->tsv.hash; // hash of key
size_t len = ts->tsv.len; // and length
DBG_PRINT("2nd pass: %s\n",p);
FlashAddr *e = hashTab + lmod(hash, fh->nROsize);
FlashTS *last = cast(FlashTS *, fromFashAddr(*e));
FlashTS *fts = cast(FlashTS *, flashAlloc(L, sizeof(FlashTS)));
toFlashAddr(L, *e, fts); // add reference to TS to lookup vector
toFlashAddr(L, fts->next, last); // and chain to previous entry if any
fts->tt = LUA_TSTRING; // Set as String
fts->marked = bitmask(LFSBIT); // LFS string with no Whitebits set
fts->hash = hash; // add hash
fts->len = len; // and length
memcpy(flashAlloc(L, ALIGN(len+1)), p, ALIGN(len+1)); // copy string
// include the trailing null char
lua_pop(L, 1); // Junk the value
lua_pushvalue(L, -1); // Dup the key as rawset dumps its copy
lua_pushinteger(L, cast(FlashAddr*,fts)-flashImage); // Value is new TS offset.
lua_rawset(L, -4); // Add to new table
}
/* At this point the old hash is done to derefence for GC */
lua_remove(L, -2);
}
/*
* Convert a TString reference in the host G(L)->strt entry into the corresponding
* TString address in the flashImage using the lookup table at ToS
*/
static void *resolveTString(lua_State* L, TString *s) {
if (!s)
return NULL;
lua_pushnil(L);
setsvalue(L, L->top-1, s);
lua_rawget(L, -2);
lua_assert(!lua_isnil(L, -1));
void *ts = fromFashAddr(lua_tointeger(L, -1));
lua_pop(L, 1);
return ts;
}
/*
* In order to simplify repacking of structures from the host format to that target
* format, this simple copy routine is data-driven by a simple format specifier.
* n Number of consecutive records to be processed
* fmt A string of A, I, S, V specifiers spanning the record.
* src Source of record
* returns Address of destination record
*/
#if defined(LUA_PACK_TVALUES)
#define TARGET_TV_SIZE (sizeof(lua_Number)+sizeof(lu_int32))
#else
#define TARGET_TV_SIZE (2*sizeof(lua_Number))
#endif
static void *flashCopy(lua_State* L, int n, const char *fmt, void *src) {
/* ToS is the string address mapping table */
if (n == 0)
return NULL;
int i, recsize;
void *newts;
/* A bit of a botch because fmt is either "V" or a string of WORDSIZE specifiers */
/* The size 8 / 12 / 16 bytes for integer builds, packed TV and default TVs resp */
if (fmt[0]=='V') {
lua_assert(fmt[1] == 0); /* V formats must be singetons */
recsize = TARGET_TV_SIZE;
} else {
recsize = WORDSIZE * strlen(fmt);
}
uint *d = cast(uint *, flashAlloc(L, n * recsize));
uint *dest = d;
uint *s = cast(uint *, src);
for (i = 0; i < n; i++) {
const char *p = fmt;
while (*p) {
/* All input address types (A,S,V) are aligned to size_t boundaries */
if (*p != 'I' && ((size_t)s)&(sizeof(size_t)-1))
s++;
switch (*p++) {
case 'A':
toFlashAddr(L, *d, *cast(void**, s));
s += FLASH_WORDS(size_t);
d++;
break;
case 'I':
*d++ = *s++;
break;
case 'S':
newts = resolveTString(L, *cast(TString **, s));
toFlashAddr(L, *d, newts);
s += FLASH_WORDS(size_t);
d++;
break;
case 'V':
/* This code has to work for both Integer and Float build variants */
memset(d, 0, TARGET_TV_SIZE);
TValue *sv = cast(TValue *, s);
if (ttisstring(sv)) {
toFlashAddr(L, *d, resolveTString(L, rawtsvalue(sv)));
} else { /* non-collectable types all of size lua_Number */
lua_assert(!iscollectable(sv));
*cast(lua_Number*,d) = *cast(lua_Number*,s);
}
*cast(int *,cast(lua_Number*,d)+1) = ttype(sv);
s += FLASH_WORDS(TValue);
d += TARGET_TV_SIZE/WORDSIZE;
break;
default:
lua_assert (0);
}
}
}
return dest;
}
/* The debug optimised version has a different Proto layout */
#ifdef LUA_OPTIMIZE_DEBUG
#define PROTO_COPY_MASK "AIAAAAAASIIIIIIIAI"
#else
#define PROTO_COPY_MASK "AIAAAAAASIIIIIIIIAI"
#endif
/*
* Do the actual prototype copy.
*/
static void *functionToFlash(lua_State* L, const Proto* orig) {
Proto f;
int i;
memcpy (&f, orig, sizeof(Proto));
f.gclist = NULL;
f.next = NULL;
l_setbit(f.marked, LFSBIT); /* OK to set the LFSBIT on a stack-cloned copy */
if (f.sizep) { /* clone included Protos */
Proto **p = luaM_newvector(L, f.sizep, Proto *);
for (i=0; i<f.sizep; i++)
p[i] = cast(Proto *, functionToFlash(L, f.p[i]));
f.p = cast(Proto **, flashCopy(L, f.sizep, "A", p));
luaM_freearray(L, p, f.sizep, Proto *);
}
f.k = cast(TValue *, flashCopy(L, f.sizek, "V", f.k));
f.code = cast(Instruction *, flashCopy(L, f.sizecode, "I", f.code));
#ifdef LUA_OPTIMIZE_DEBUG
if (f.packedlineinfo) {
TString *ts=luaS_new(L, cast(const char *,f.packedlineinfo));
f.packedlineinfo = cast(unsigned char *, resolveTString(L, ts)) + sizeof (FlashTS);
}
#else
f.lineinfo = cast(int *, flashCopy(L, f.sizelineinfo, "I", f.lineinfo));
#endif
f.locvars = cast(struct LocVar *, flashCopy(L, f.sizelocvars, "SII", f.locvars));
f.upvalues = cast(TString **, flashCopy(L, f.sizeupvalues, "S", f.upvalues));
return cast(void *, flashCopy(L, 1, PROTO_COPY_MASK, &f));
}
/*
* Scan through the tagged addresses. This operates in one of two modes.
* - If address is non-zero then the offset is converted back into an absolute
* mapped flash address using the specified address base.
*
* - If the address is zero then form a form linked chain with the upper 16 bits
* the link to the last offset. As the scan is backwards, this 'last' address
* becomes forward reference for the on-chip LFS loader.
*/
void linkAddresses(lu_int32 address){
int i, last = 0;
for (i = curOffset-1 ; i >= 0; i--) {
if (flashAddrTag[i]) {
lua_assert(flashImage[i]<curOffset);
if (address) {
flashImage[i] = 4*flashImage[i] + address;
} else {
flashImage[i] |= last<<16;
last = i;
}
}
}
}
uint dumpToFlashImage (lua_State* L, const Proto *main, lua_Writer w,
void* data, int strip, lu_int32 address) {
// parameter strip is ignored for now
lua_newtable(L);
FlashHeader *fh = cast(FlashHeader *, flashAlloc(L, sizeof(FlashHeader)));
scanProtoStrings(L, main);
createROstrt(L, fh);
toFlashAddr(L, fh->mainProto, functionToFlash(L, main));
fh->flash_sig = FLASH_SIG + (address ? FLASH_SIG_ABSOLUTE : 0);
fh->flash_size = curOffset*WORDSIZE;
linkAddresses(address);
lua_unlock(L);
int status = w(L, flashImage, curOffset * sizeof(uint), data);
lua_lock(L);
return status;
}
......@@ -5,14 +5,14 @@
*/
// #include "c_errno.h"
#include "c_stdio.h"
#include "c_stdlib.h"
#include "c_string.h"
#include "vfs.h"
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define liolib_c
#define LUA_LIB
#define LUA_OPTIMIZE_MEMORY 2
#include "lua.h"
......@@ -20,26 +20,21 @@
#include "lualib.h"
#include "lrotable.h"
#define IO_INPUT 1
#define IO_OUTPUT 2
#define IO_STDERR 0
#if LUA_OPTIMIZE_MEMORY != 2
#define LUA_IO_GETFIELD(f) lua_rawgeti(L, LUA_ENVIRONINDEX, f)
#define LUA_IO_SETFIELD(f) lua_rawseti(L, LUA_ENVIRONINDEX, f)
#else
#define LUA_IO_GETFIELD(f) lua_rawgeti(L, LUA_REGISTRYINDEX, liolib_keys[f])
#define LUA_IO_SETFIELD(f) lua_rawseti(L, LUA_REGISTRYINDEX, liolib_keys[f])
#define LUA_IO_GETFIELD(f) lua_rawgeti(L, LUA_REGISTRYINDEX,(int)(liolib_keys[f]))
#define LUA_IO_SETFIELD(f) lua_rawseti(L, LUA_REGISTRYINDEX,(int)(liolib_keys[f]))
/* "Pseudo-random" keys for the registry */
static const int liolib_keys[] = {(int)&luaL_callmeta, (int)&luaL_typerror, (int)&luaL_argerror};
#endif
static const size_t liolib_keys[] = {(size_t)&luaL_callmeta, (size_t)&luaL_typerror, (size_t)&luaL_argerror};
static const char *const fnames[] = {"input", "output"};
static int pushresult (lua_State *L, int i, const char *filename) {
int en = vfs_ferrno(0); /* calls to Lua API may change this value */
int en = errno; /* calls to Lua API may change this value */
if (i) {
lua_pushboolean(L, 1);
return 1;
......@@ -47,9 +42,9 @@ static int pushresult (lua_State *L, int i, const char *filename) {
else {
lua_pushnil(L);
if (filename)
lua_pushfstring(L, "%s: err(%d)", filename, en);
lua_pushfstring(L, "%s: %s", filename, strerror(en));
else
lua_pushfstring(L, "err(%d)", en);
lua_pushfstring(L, "%s", strerror(en));
lua_pushinteger(L, en);
return 3;
}
......@@ -57,12 +52,12 @@ static int pushresult (lua_State *L, int i, const char *filename) {
static void fileerror (lua_State *L, int arg, const char *filename) {
lua_pushfstring(L, "%s: err(%d)", filename, vfs_ferrno(0));
lua_pushfstring(L, "%s: %s", filename, strerror(errno));
luaL_argerror(L, arg, lua_tostring(L, -1));
}
#define tofilep(L) ((int *)luaL_checkudata(L, 1, LUA_FILEHANDLE))
#define tofilep(L) ((FILE **)luaL_checkudata(L, 1, LUA_FILEHANDLE))
static int io_type (lua_State *L) {
......@@ -72,7 +67,7 @@ static int io_type (lua_State *L) {
lua_getfield(L, LUA_REGISTRYINDEX, LUA_FILEHANDLE);
if (ud == NULL || !lua_getmetatable(L, 1) || !lua_rawequal(L, -2, -1))
lua_pushnil(L); /* not a file */
else if (*((int *)ud) < FS_OPEN_OK)
else if (*((FILE **)ud) == NULL)
lua_pushliteral(L, "closed file");
else
lua_pushliteral(L, "file");
......@@ -80,9 +75,9 @@ static int io_type (lua_State *L) {
}
static int tofile (lua_State *L) {
int *f = tofilep(L);
if (*f < FS_OPEN_OK)
static FILE *tofile (lua_State *L) {
FILE **f = tofilep(L);
if (*f == NULL)
luaL_error(L, "attempt to use a closed file");
return *f;
}
......@@ -94,91 +89,52 @@ static int tofile (lua_State *L) {
** before opening the actual file; so, if there is a memory error, the
** file is not left opened.
*/
static int *newfile (lua_State *L) {
int *pf = (int *)lua_newuserdata(L, sizeof(int));
*pf = FS_OPEN_OK - 1; /* file handle is currently `closed' */
static FILE **newfile (lua_State *L) {
FILE **pf = (FILE **)lua_newuserdata(L, sizeof(FILE *));
*pf = NULL; /* file handle is currently `closed' */
luaL_getmetatable(L, LUA_FILEHANDLE);
lua_setmetatable(L, -2);
return pf;
}
#if LUA_OPTIMIZE_MEMORY != 2
/*
** function to (not) close the standard files stdin, stdout, and stderr
*/
static int io_noclose (lua_State *L) {
lua_pushnil(L);
lua_pushliteral(L, "cannot close standard file");
return 2;
}
#if 0
/*
** function to close 'popen' files
*/
static int io_pclose (lua_State *L) {
int *p = tofilep(L);
int ok = lua_pclose(L, *p);
*p = FS_OPEN_OK - 1;
return pushresult(L, ok, NULL);
}
#endif
/*
** function to close regular files
*/
static int io_fclose (lua_State *L) {
int *p = tofilep(L);
int ok = (vfs_close(*p) == 0);
*p = FS_OPEN_OK - 1;
return pushresult(L, ok, NULL);
}
#endif
static int aux_close (lua_State *L) {
#if LUA_OPTIMIZE_MEMORY != 2
lua_getfenv(L, 1);
lua_getfield(L, -1, "__close");
return (lua_tocfunction(L, -1))(L);
#else
int *p = tofilep(L);
if(*p == c_stdin || *p == c_stdout || *p == c_stderr)
FILE **p = tofilep(L);
if(*p == stdin || *p == stdout || *p == stderr)
{
lua_pushnil(L);
lua_pushliteral(L, "cannot close standard file");
return 2;
return 2;
}
int ok = (vfs_close(*p) == 0);
*p = FS_OPEN_OK - 1;
int ok = (fclose(*p) == 0);
*p = NULL;
return pushresult(L, ok, NULL);
#endif
}
static int io_close (lua_State *L) {
if (lua_isnone(L, 1))
LUA_IO_GETFIELD(IO_OUTPUT);
lua_rawgeti(L, LUA_ENVIRONINDEX, IO_OUTPUT);
tofile(L); /* make sure argument is a file */
return aux_close(L);
}
static int io_gc (lua_State *L) {
int f = *tofilep(L);
FILE *f = *tofilep(L);
/* ignore closed files */
if (f != FS_OPEN_OK - 1)
if (f != NULL)
aux_close(L);
return 0;
}
static int io_tostring (lua_State *L) {
int f = *tofilep(L);
if (f == FS_OPEN_OK - 1)
FILE *f = *tofilep(L);
if (f == NULL)
lua_pushliteral(L, "file (closed)");
else
lua_pushfstring(L, "file (%i)", f);
lua_pushfstring(L, "file (%p)", f);
return 1;
}
......@@ -186,42 +142,19 @@ static int io_tostring (lua_State *L) {
static int io_open (lua_State *L) {
const char *filename = luaL_checkstring(L, 1);
const char *mode = luaL_optstring(L, 2, "r");
int *pf = newfile(L);
*pf = vfs_open(filename, mode);
return (*pf == FS_OPEN_OK - 1) ? pushresult(L, 0, filename) : 1;
FILE **pf = newfile(L);
*pf = fopen(filename, mode);
return (*pf == NULL) ? pushresult(L, 0, filename) : 1;
}
/*
** this function has a separated environment, which defines the
** correct __close for 'popen' files
*/
#if 0
static int io_popen (lua_State *L) {
const char *filename = luaL_checkstring(L, 1);
const char *mode = luaL_optstring(L, 2, "r");
int *pf = newfile(L);
*pf = lua_popen(L, filename, fs_mode2flags(mode));
return (*pf == FS_OPEN_OK - 1) ? pushresult(L, 0, filename) : 1;
}
static int io_tmpfile (lua_State *L) {
int *pf = newfile(L);
*pf = tmpfile();
return (*pf == FS_OPEN_OK - 1) ? pushresult(L, 0, NULL) : 1;
}
#endif
static int getiofile (lua_State *L, int findex) {
int *pf;
LUA_IO_GETFIELD(findex);
pf = (int *)lua_touserdata(L, -1);
if (pf == NULL || *pf == FS_OPEN_OK - 1){
luaL_error(L, "default %s file is closed", fnames[findex - 1]);
return FS_OPEN_OK - 1;
}
return *pf;
static FILE *getiofile (lua_State *L, int findex) {
FILE *f;
lua_rawgeti(L, LUA_ENVIRONINDEX, findex);
f = *(FILE **)lua_touserdata(L, -1);
if (f == NULL)
luaL_error(L, "standard %s file is closed", fnames[findex - 1]);
return f;
}
......@@ -229,19 +162,19 @@ static int g_iofile (lua_State *L, int f, const char *mode) {
if (!lua_isnoneornil(L, 1)) {
const char *filename = lua_tostring(L, 1);
if (filename) {
int *pf = newfile(L);
*pf = vfs_open(filename, mode);
if (*pf == FS_OPEN_OK - 1)
FILE **pf = newfile(L);
*pf = fopen(filename, mode);
if (*pf == NULL)
fileerror(L, 1, filename);
}
else {
tofile(L); /* check that it's a valid file handle */
lua_pushvalue(L, 1);
}
LUA_IO_SETFIELD(f);
lua_rawseti(L, LUA_ENVIRONINDEX, f);
}
/* return current value */
LUA_IO_GETFIELD(f);
lua_rawgeti(L, LUA_ENVIRONINDEX, f);
return 1;
}
......@@ -276,14 +209,14 @@ static int f_lines (lua_State *L) {
static int io_lines (lua_State *L) {
if (lua_isnoneornil(L, 1)) { /* no arguments? */
/* will iterate over default input */
LUA_IO_GETFIELD(IO_INPUT);
lua_rawgeti(L, LUA_ENVIRONINDEX, IO_INPUT);
return f_lines(L);
}
else {
const char *filename = luaL_checkstring(L, 1);
int *pf = newfile(L);
*pf = vfs_open(filename, "r");
if (*pf == FS_OPEN_OK - 1)
FILE **pf = newfile(L);
*pf = fopen(filename, "r");
if (*pf == NULL)
fileerror(L, 1, filename);
aux_lines(L, lua_gettop(L), 1);
return 1;
......@@ -297,10 +230,10 @@ static int io_lines (lua_State *L) {
** =======================================================
*/
#if 0
static int read_number (lua_State *L, int f) {
static int read_number (lua_State *L, FILE *f) {
lua_Number d;
if (fs_scanf(f, LUA_NUMBER_SCAN, &d) == 1) {
if (fscanf(f, LUA_NUMBER_SCAN, &d) == 1) {
lua_pushnumber(L, d);
return 1;
}
......@@ -309,27 +242,27 @@ static int read_number (lua_State *L, int f) {
return 0; /* read fails */
}
}
#endif
static int test_eof (lua_State *L, int f) {
int c = vfs_getc(f);
vfs_ungetc(c, f);
static int test_eof (lua_State *L, FILE *f) {
int c = getc(f);
ungetc(c, f);
lua_pushlstring(L, NULL, 0);
return (c != EOF);
}
#if 0
static int read_line (lua_State *L, int f) {
static int read_line (lua_State *L, FILE *f) {
luaL_Buffer b;
luaL_buffinit(L, &b);
for (;;) {
size_t l;
char *p = luaL_prepbuffer(&b);
if (fs_gets(p, LUAL_BUFFERSIZE, f) == NULL) { /* eof? */
if (fgets(p, LUAL_BUFFERSIZE, f) == NULL) { /* eof? */
luaL_pushresult(&b); /* close buffer */
return (lua_objlen(L, -1) > 0); /* check whether read something */
}
l = c_strlen(p);
l = strlen(p);
if (l == 0 || p[l-1] != '\n')
luaL_addsize(&b, l);
else {
......@@ -339,27 +272,9 @@ static int read_line (lua_State *L, int f) {
}
}
}
#else
static int read_line (lua_State *L, int f) {
luaL_Buffer b;
luaL_buffinit(L, &b);
signed char c;
do {
c = (signed char)vfs_getc(f);
if (c==EOF) {
break;
}
if (c != '\n') {
luaL_addchar(&b, c);
}
} while (c != '\n');
luaL_pushresult(&b); /* close buffer */
return (lua_objlen(L, -1) > 0); /* check whether read something */
}
#endif
static int read_chars (lua_State *L, int f, size_t n) {
static int read_chars (lua_State *L, FILE *f, size_t n) {
size_t rlen; /* how much to read */
size_t nr; /* number of chars actually read */
luaL_Buffer b;
......@@ -368,7 +283,7 @@ static int read_chars (lua_State *L, int f, size_t n) {
do {
char *p = luaL_prepbuffer(&b);
if (rlen > n) rlen = n; /* cannot read more than asked */
nr = vfs_read(f, p, rlen);
nr = fread(p, sizeof(char), rlen, f);
luaL_addsize(&b, nr);
n -= nr; /* still have to read `n' chars */
} while (n > 0 && nr == rlen); /* until end of count or eof */
......@@ -377,11 +292,11 @@ static int read_chars (lua_State *L, int f, size_t n) {
}
static int g_read (lua_State *L, int f, int first) {
static int g_read (lua_State *L, FILE *f, int first) {
int nargs = lua_gettop(L) - 1;
int success;
int n;
//vfs_clearerr(f);
clearerr(f);
if (nargs == 0) { /* no arguments? */
success = read_line(L, f);
n = first+1; /* to return 1 result */
......@@ -398,11 +313,9 @@ static int g_read (lua_State *L, int f, int first) {
const char *p = lua_tostring(L, n);
luaL_argcheck(L, p && p[0] == '*', n, "invalid option");
switch (p[1]) {
#if 0
case 'n': /* number */
success = read_number(L, f);
break;
#endif
case 'l': /* line */
success = read_line(L, f);
break;
......@@ -416,7 +329,7 @@ static int g_read (lua_State *L, int f, int first) {
}
}
}
if (vfs_ferrno(f))
if (ferror(f))
return pushresult(L, 0, NULL);
if (!success) {
lua_pop(L, 1); /* remove last result */
......@@ -437,15 +350,13 @@ static int f_read (lua_State *L) {
static int io_readline (lua_State *L) {
int *pf = (int *)lua_touserdata(L, lua_upvalueindex(1));
FILE *f = *(FILE **)lua_touserdata(L, lua_upvalueindex(1));
int sucess;
if (pf == NULL || *pf == FS_OPEN_OK - 1){ /* file is already closed? */
if (f == NULL) /* file is already closed? */
luaL_error(L, "file is already closed");
return 0;
}
sucess = read_line(L, *pf);
if (vfs_ferrno(*pf))
return luaL_error(L, "err(%d)", vfs_ferrno(*pf));
sucess = read_line(L, f);
if (ferror(f))
return luaL_error(L, "%s", strerror(errno));
if (sucess) return 1;
else { /* EOF */
if (lua_toboolean(L, lua_upvalueindex(2))) { /* generator created file? */
......@@ -460,22 +371,19 @@ static int io_readline (lua_State *L) {
/* }====================================================== */
static int g_write (lua_State *L, int f, int arg) {
static int g_write (lua_State *L, FILE *f, int arg) {
int nargs = lua_gettop(L) - 1;
int status = 1;
for (; nargs--; arg++) {
#if 0
if (lua_type(L, arg) == LUA_TNUMBER) {
/* optimization: could be done exactly as for strings */
status = status &&
fs_printf(f, LUA_NUMBER_FMT, lua_tonumber(L, arg)) > 0;
fprintf(f, LUA_NUMBER_FMT, lua_tonumber(L, arg)) > 0;
}
else
#endif
{
else {
size_t l;
const char *s = luaL_checklstring(L, arg, &l);
status = status && (vfs_write(f, s, l) == l);
status = status && (fwrite(s, sizeof(char), l, f) == l);
}
}
return pushresult(L, status, NULL);
......@@ -493,159 +401,103 @@ static int f_write (lua_State *L) {
static int f_seek (lua_State *L) {
static const int mode[] = {VFS_SEEK_SET, VFS_SEEK_CUR, VFS_SEEK_END};
static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END};
static const char *const modenames[] = {"set", "cur", "end", NULL};
int f = tofile(L);
FILE *f = tofile(L);
int op = luaL_checkoption(L, 2, "cur", modenames);
long offset = luaL_optlong(L, 3, 0);
op = vfs_lseek(f, offset, mode[op]);
op = fseek(f, offset, mode[op]);
if (op)
return pushresult(L, 0, NULL); /* error */
else {
lua_pushinteger(L, vfs_tell(f));
lua_pushinteger(L, ftell(f));
return 1;
}
}
#if 0
static int f_setvbuf (lua_State *L) {
static const int mode[] = {_IONBF, _IOFBF, _IOLBF};
static const char *const modenames[] = {"no", "full", "line", NULL};
int f = tofile(L);
FILE *f = tofile(L);
int op = luaL_checkoption(L, 2, NULL, modenames);
lua_Integer sz = luaL_optinteger(L, 3, LUAL_BUFFERSIZE);
int res = setvbuf(f, NULL, mode[op], sz);
return pushresult(L, res == 0, NULL);
}
#endif
static int io_flush (lua_State *L) {
return pushresult(L, vfs_flush(getiofile(L, IO_OUTPUT)) == 0, NULL);
return pushresult(L, fflush(getiofile(L, IO_OUTPUT)) == 0, NULL);
}
static int f_flush (lua_State *L) {
return pushresult(L, vfs_flush(tofile(L)) == 0, NULL);
return pushresult(L, fflush(tofile(L)) == 0, NULL);
}
#undef MIN_OPT_LEVEL
#define MIN_OPT_LEVEL 2
#include "lrodefs.h"
#if LUA_OPTIMIZE_MEMORY == 2
const LUA_REG_TYPE iolib_funcs[] = {
#else
const LUA_REG_TYPE iolib[] = {
#endif
{LSTRKEY("close"), LFUNCVAL(io_close)},
{LSTRKEY("flush"), LFUNCVAL(io_flush)},
{LSTRKEY("input"), LFUNCVAL(io_input)},
{LSTRKEY("lines"), LFUNCVAL(io_lines)},
{LSTRKEY("open"), LFUNCVAL(io_open)},
{LSTRKEY("output"), LFUNCVAL(io_output)},
// {LSTRKEY("popen"), LFUNCVAL(io_popen)},
{LSTRKEY("read"), LFUNCVAL(io_read)},
// {LSTRKEY("tmpfile"), LFUNCVAL(io_tmpfile)},
{LSTRKEY("type"), LFUNCVAL(io_type)},
{LSTRKEY("write"), LFUNCVAL(io_write)},
{LSTRKEY("close"), LFUNCVAL(io_close)},
{LSTRKEY("flush"), LFUNCVAL(io_flush)},
{LSTRKEY("input"), LFUNCVAL(io_input)},
{LSTRKEY("lines"), LFUNCVAL(io_lines)},
{LSTRKEY("open"), LFUNCVAL(io_open)},
{LSTRKEY("output"), LFUNCVAL(io_output)},
{LSTRKEY("read"), LFUNCVAL(io_read)},
{LSTRKEY("type"), LFUNCVAL(io_type)},
{LSTRKEY("write"), LFUNCVAL(io_write)},
{LSTRKEY("__index"), LROVAL(iolib_funcs)},
{LNILKEY, LNILVAL}
};
#if LUA_OPTIMIZE_MEMORY == 2
static int luaL_index(lua_State *L)
/* Note that IO objects use a RAM metatable created to allow extensibility */
static int io_index(lua_State *L)
{
return luaR_findfunction(L, iolib_funcs);
}
const luaL_Reg iolib[] = {
{"__index", luaL_index},
{"__index", io_index},
{NULL, NULL}
};
#endif
#undef MIN_OPT_LEVEL
#define MIN_OPT_LEVEL 1
#include "lrodefs.h"
const LUA_REG_TYPE flib[] = {
{LSTRKEY("close"), LFUNCVAL(io_close)},
{LSTRKEY("flush"), LFUNCVAL(f_flush)},
{LSTRKEY("lines"), LFUNCVAL(f_lines)},
{LSTRKEY("read"), LFUNCVAL(f_read)},
{LSTRKEY("seek"), LFUNCVAL(f_seek)},
// {LSTRKEY("setvbuf"), LFUNCVAL(f_setvbuf)},
{LSTRKEY("write"), LFUNCVAL(f_write)},
{LSTRKEY("__gc"), LFUNCVAL(io_gc)},
{LSTRKEY("close"), LFUNCVAL(io_close)},
{LSTRKEY("flush"), LFUNCVAL(f_flush)},
{LSTRKEY("lines"), LFUNCVAL(f_lines)},
{LSTRKEY("read"), LFUNCVAL(f_read)},
{LSTRKEY("seek"), LFUNCVAL(f_seek)},
{LSTRKEY("setvbuf"), LFUNCVAL(f_setvbuf)},
{LSTRKEY("write"), LFUNCVAL(f_write)},
{LSTRKEY("__gc"), LFUNCVAL(io_gc)},
{LSTRKEY("__tostring"), LFUNCVAL(io_tostring)},
#if LUA_OPTIMIZE_MEMORY > 0
{LSTRKEY("__index"), LROVAL(flib)},
#endif
{LSTRKEY("__index"), LROVAL(flib)},
{LNILKEY, LNILVAL}
};
static void createmeta (lua_State *L) {
#if LUA_OPTIMIZE_MEMORY == 0
luaL_newmetatable(L, LUA_FILEHANDLE); /* create metatable for file handles */
lua_pushvalue(L, -1); /* push metatable */
lua_setfield(L, -2, "__index"); /* metatable.__index = metatable */
luaL_register(L, NULL, flib); /* file methods */
#else
luaL_rometatable(L, LUA_FILEHANDLE, (void*)flib); /* create metatable for file handles */
#endif
}
static void createstdfile (lua_State *L, int f, int k, const char *fname) {
static void createstdfile (lua_State *L, FILE *f, int k, const char *fname) {
*newfile(L) = f;
#if LUA_OPTIMIZE_MEMORY != 2
if (k > 0) {
lua_pushvalue(L, -1);
lua_rawseti(L, LUA_ENVIRONINDEX, k);
}
lua_pushvalue(L, -2); /* copy environment */
lua_setfenv(L, -2); /* set it */
lua_setfield(L, -3, fname);
#else
lua_pushvalue(L, -1);
lua_rawseti(L, LUA_REGISTRYINDEX, liolib_keys[k]);
lua_rawseti(L, LUA_REGISTRYINDEX, (int)(liolib_keys[k]));
lua_setfield(L, -2, fname);
#endif
}
#if LUA_OPTIMIZE_MEMORY != 2
static void newfenv (lua_State *L, lua_CFunction cls) {
lua_createtable(L, 0, 1);
lua_pushcfunction(L, cls);
lua_setfield(L, -2, "__close");
}
#endif
LUALIB_API int luaopen_io (lua_State *L) {
createmeta(L);
#if LUA_OPTIMIZE_MEMORY != 2
/* create (private) environment (with fields IO_INPUT, IO_OUTPUT, __close) */
newfenv(L, io_fclose);
lua_replace(L, LUA_ENVIRONINDEX);
/* open library */
luaL_register(L, LUA_IOLIBNAME, iolib);
newfenv(L, io_noclose); /* close function for default files */
#else
luaL_rometatable(L, LUA_FILEHANDLE, (void*)flib); /* create metatable for file handles */
luaL_register_light(L, LUA_IOLIBNAME, iolib);
lua_pushvalue(L, -1);
lua_setmetatable(L, -2);
#endif
#if 0
/* create (and set) default files */
createstdfile(L, c_stdin, IO_INPUT, "stdin");
createstdfile(L, c_stdout, IO_OUTPUT, "stdout");
createstdfile(L, c_stderr, IO_STDERR, "stderr");
#if LUA_OPTIMIZE_MEMORY != 2
lua_pop(L, 1); /* pop environment for default files */
lua_getfield(L, -1, "popen");
newfenv(L, io_pclose); /* create environment for 'popen' */
lua_setfenv(L, -2); /* set fenv for 'popen' */
lua_pop(L, 1); /* pop 'popen' */
#endif
#endif
createstdfile(L, stdin, IO_INPUT, "stdin");
createstdfile(L, stdout, IO_OUTPUT, "stdout");
createstdfile(L, stderr, 0, "stderr");
return 1;
}
......@@ -11,13 +11,14 @@
#include C_HEADER_STDIO
#include C_HEADER_STDLIB
#include C_HEADER_STRING
#include <time.h>
#define luac_c
#define LUA_CORE
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
#include "ldo.h"
#include "lfunc.h"
#include "lmem.h"
......@@ -31,17 +32,23 @@
static int listing=0; /* list bytecodes? */
static int dumping=1; /* dump bytecodes? */
static int stripping=0; /* strip debug information? */
static int stripping=0; /* strip debug information? */
static int flash=0; /* output flash image */
static lu_int32 address=0; /* output flash image at absolute location */
static int lookup=0; /* output lookup-style master combination header */
static char Output[]={ OUTPUT }; /* default output file name */
static const char* output=Output; /* actual output file name */
static const char* execute; /* executed a Lua file */
static const char* progname=PROGNAME; /* actual program name */
static DumpTargetInfo target;
static void fatal(const char* message)
void luac_fatal(const char* message)
{
fprintf(stderr,"%s: %s\n",progname,message);
exit(EXIT_FAILURE);
}
#define fatal(s) luac_fatal(s)
static void cannot(const char* what)
{
......@@ -61,18 +68,21 @@ static void usage(const char* message)
" - process stdin\n"
" -l list\n"
" -o name output to file " LUA_QL("name") " (default is \"%s\")\n"
" -e name execute a lua source file\n"
" -f output a flash image file\n"
" -a addr generate an absolute, rather than position independent flash image file\n"
" -i generate lookup combination master (default with option -f)\n"
" -p parse only\n"
" -s strip debug information\n"
" -v show version information\n"
" -cci bits cross-compile with given integer size\n"
" -ccn type bits cross-compile with given lua_Number type and size\n"
" -cce endian cross-compile with given endianness ('big' or 'little')\n"
" -- stop handling options\n",
progname,Output);
exit(EXIT_FAILURE);
}
#define IS(s) (strcmp(argv[i],s)==0)
#define IROM0_SEG 0x40210000ul
#define IROM0_SEGMAX 0x00100000ul
static int doargs(int argc, char* argv[])
{
......@@ -89,8 +99,28 @@ static int doargs(int argc, char* argv[])
if (version) ++version;
break;
}
else if (IS("-")) /* end of options; use stdin */
else if (IS("-")) /* end of options; use stdin */
break;
else if (IS("-e")) /* execute a lua source file file */
{
execute=argv[++i];
if (execute ==NULL || *execute==0 || *execute=='-' )
usage(LUA_QL("-e") " needs argument");
}
else if (IS("-f")) /* Flash image file */
{
flash=lookup=1;
}
else if (IS("-a")) /* Absolue flash image file */
{
flash=lookup=1;
address=strtol(argv[++i],NULL,0);
size_t offset = (unsigned) (address -IROM0_SEG);
if (offset > IROM0_SEGMAX)
usage(LUA_QL("-e") " absolute address must be valid flash address");
}
else if (IS("-i")) /* lookup */
lookup = 1;
else if (IS("-l")) /* list */
++listing;
else if (IS("-o")) /* output file */
......@@ -99,42 +129,17 @@ static int doargs(int argc, char* argv[])
if (output==NULL || *output==0) usage(LUA_QL("-o") " needs argument");
if (IS("-")) output=NULL;
}
else if (IS("-p")) /* parse only */
dumping=0;
dumping=0;
else if (IS("-s")) /* strip debug information */
stripping=1;
else if (IS("-v")) /* show version */
++version;
else if (IS("-cci")) /* target integer size */
{
int s = target.sizeof_int = atoi(argv[++i])/8;
if (!(s==1 || s==2 || s==4)) fatal(LUA_QL("-cci") " must be 8, 16 or 32");
}
else if (IS("-ccn")) /* target lua_Number type and size */
{
const char *type=argv[++i];
if (strcmp(type,"int")==0) target.lua_Number_integral=1;
else if (strcmp(type,"float")==0) target.lua_Number_integral=0;
else if (strcmp(type,"float_arm")==0)
{
target.lua_Number_integral=0;
target.is_arm_fpa=1;
}
else fatal(LUA_QL("-ccn") " type must be " LUA_QL("int") " or " LUA_QL("float") " or " LUA_QL("float_arm"));
int s = target.sizeof_lua_Number = atoi(argv[++i])/8;
if (target.lua_Number_integral && !(s==1 || s==2 || s==4)) fatal(LUA_QL("-ccn") " size must be 8, 16, or 32 for int");
if (!target.lua_Number_integral && !(s==4 || s==8)) fatal(LUA_QL("-ccn") " size must be 32 or 64 for float");
}
else if (IS("-cce")) /* target endianness */
{
const char *val=argv[++i];
if (strcmp(val,"big")==0) target.little_endian=0;
else if (strcmp(val,"little")==0) target.little_endian=1;
else fatal(LUA_QL("-cce") " must be " LUA_QL("big") " or " LUA_QL("little"));
}
else /* unknown option */
usage(argv[i]);
usage(argv[i]);
}
if (i==argc && (listing || !dumping))
{
dumping=0;
......@@ -150,30 +155,99 @@ static int doargs(int argc, char* argv[])
#define toproto(L,i) (clvalue(L->top+(i))->l.p)
static const Proto* combine(lua_State* L, int n)
static TString *corename(lua_State *L, const TString *filename)
{
if (n==1)
const char *fn = getstr(filename)+1;
const char *s = strrchr(fn, '/');
s = s ? s + 1 : fn;
while (*s == '.') s++;
const char *e = strchr(s, '.');
int l = e ? e - s: strlen(s);
return l ? luaS_newlstr (L, s, l) : luaS_new(L, fn);
}
/*
* If the luac command line includes multiple files or has the -f option
* then luac generates a main function to reference all sub-main prototypes.
* This is one of two types:
* Type 0 The standard luac combination main
* Type 1 A lookup wrapper that facilitates indexing into the generated protos
*/
static const Proto* combine(lua_State* L, int n, int type)
{
if (n==1 && type == 0)
return toproto(L,-1);
else
{
int i,pc;
int i;
Instruction *pc;
Proto* f=luaF_newproto(L);
setptvalue2s(L,L->top,f); incr_top(L);
f->source=luaS_newliteral(L,"=(" PROGNAME ")");
f->maxstacksize=1;
pc=2*n+1;
f->code=luaM_newvector(L,pc,Instruction);
f->sizecode=pc;
f->p=luaM_newvector(L,n,Proto*);
f->sizep=n;
for (i=0; i<n; i++)
f->p[i]=toproto(L,i-n-1);
pc=0;
for (i=0; i<n; i++)
{
f->p[i]=toproto(L,i-n-1);
f->code[pc++]=CREATE_ABx(OP_CLOSURE,0,i);
f->code[pc++]=CREATE_ABC(OP_CALL,0,1,1);
if (type == 0) {
/*
* Type 0 is as per the standard luac, which is just a main routine which
* invokes all of the compiled functions sequentially. This is fine if
* they are self registering modules, but useless otherwise.
*/
f->numparams = 0;
f->maxstacksize = 1;
f->sizecode = 2*n + 1 ;
f->sizek = 0;
f->code = luaM_newvector(L, f->sizecode , Instruction);
f->k = luaM_newvector(L,f->sizek,TValue);
for (i=0, pc = f->code; i<n; i++) {
*pc++ = CREATE_ABx(OP_CLOSURE,0,i);
*pc++ = CREATE_ABC(OP_CALL,0,1,1);
}
*pc++ = CREATE_ABC(OP_RETURN,0,1,0);
} else {
/*
* The Type 1 main() is a lookup which takes a single argument, the name to
* be resolved. If this matches root name of one of the compiled files then
* a closure to this file main is returned. Otherwise the Unixtime of the
* compile and the list of root names is returned.
*/
if (n > LFIELDS_PER_FLUSH) {
#define NO_MOD_ERR_(n) ": Number of modules > " #n
#define NO_MOD_ERR(n) NO_MOD_ERR_(n)
usage(LUA_QL("-f") NO_MOD_ERR(LFIELDS_PER_FLUSH));
}
f->numparams = 1;
f->maxstacksize = n + 3;
f->sizecode = 5*n + 5 ;
f->sizek = n + 1;
f->sizelocvars = 0;
f->code = luaM_newvector(L, f->sizecode , Instruction);
f->k = luaM_newvector(L,f->sizek,TValue);
for (i=0, pc = f->code; i<n; i++)
{
/* if arg1 == FnameA then return function (...) -- funcA -- end end */
setsvalue2n(L,f->k+i,corename(L, f->p[i]->source));
*pc++ = CREATE_ABC(OP_EQ,0,0,RKASK(i));
*pc++ = CREATE_ABx(OP_JMP,0,MAXARG_sBx+2);
*pc++ = CREATE_ABx(OP_CLOSURE,1,i);
*pc++ = CREATE_ABC(OP_RETURN,1,2,0);
}
setnvalue(f->k+n, (lua_Number) time(NULL));
*pc++ = CREATE_ABx(OP_LOADK,1,n);
*pc++ = CREATE_ABC(OP_NEWTABLE,2,luaO_int2fb(i),0);
for (i=0; i<n; i++)
*pc++ = CREATE_ABx(OP_LOADK,i+3,i);
*pc++ = CREATE_ABC(OP_SETLIST,2,i,1);
*pc++ = CREATE_ABC(OP_RETURN,1,3,0);
*pc++ = CREATE_ABC(OP_RETURN,0,1,0);
}
f->code[pc++]=CREATE_ABC(OP_RETURN,0,1,0);
lua_assert((pc-f->code) == f->sizecode);
return f;
}
}
......@@ -189,6 +263,9 @@ struct Smain {
char** argv;
};
extern uint dumpToFlashImage (lua_State* L,const Proto *main, lua_Writer w,
void* data, int strip, lu_int32 address);
static int pmain(lua_State* L)
{
struct Smain* s = (struct Smain*)lua_touserdata(L, 1);
......@@ -197,19 +274,39 @@ static int pmain(lua_State* L)
const Proto* f;
int i;
if (!lua_checkstack(L,argc)) fatal("too many input files");
if (execute)
{
if (luaL_loadfile(L,execute)!=0) fatal(lua_tostring(L,-1));
luaL_openlibs(L);
lua_pushstring(L, execute);
if (lua_pcall(L, 1, 1, 0)) fatal(lua_tostring(L,-1));
if (!lua_isfunction(L, -1))
{
lua_pop(L,1);
if(argc == 0) return 0;
execute = NULL;
}
}
for (i=0; i<argc; i++)
{
const char* filename=IS("-") ? NULL : argv[i];
if (luaL_loadfile(L,filename)!=0) fatal(lua_tostring(L,-1));
}
f=combine(L,argc);
f=combine(L,argc + (execute ? 1: 0), lookup);
if (listing) luaU_print(f,listing>1);
if (dumping)
{
int result;
FILE* D= (output==NULL) ? stdout : fopen(output,"wb");
if (D==NULL) cannot("open");
lua_lock(L);
int result=luaU_dump_crosscompile(L,f,writer,D,stripping,target);
if (flash)
{
result=dumpToFlashImage(L,f,writer, D, stripping, address);
} else
{
result=luaU_dump_crosscompile(L,f,writer,D,stripping,target);
}
lua_unlock(L);
if (result==LUA_ERR_CC_INTOVERFLOW) fatal("value too big or small for target integer type");
if (result==LUA_ERR_CC_NOTINTEGER) fatal("target lua_Number is integral but fractional value found");
......@@ -234,7 +331,7 @@ int main(int argc, char* argv[])
int i=doargs(argc,argv);
argc-=i; argv+=i;
if (argc<=0) usage("no input files given");
if (argc<=0 && execute==0) usage("no input files given");
L=lua_open();
if (L==NULL) fatal("not enough memory for state");
s.argc=argc;
......
......@@ -38,6 +38,11 @@
#define LUA_WIN
#endif
#if defined(LUA_CROSS_COMPILER)
#define LUA_USE_LINUX
#endif
#if defined(LUA_USE_LINUX)
#define LUA_USE_POSIX
#define LUA_USE_DLOPEN /* needs an extra library: -ldl */
......@@ -59,7 +64,7 @@
#if defined(LUA_USE_POSIX)
#define LUA_USE_MKSTEMP
#define LUA_USE_ISATTY
#define LUA_USE_POPEN
//#define LUA_USE_POPEN
#define LUA_USE_ULONGJMP
#endif
......@@ -167,7 +172,7 @@
#define LUA_INTEGER ptrdiff_t
#else
#if !defined LUA_INTEGRAL_LONGLONG
#define LUA_INTEGER long
#define LUA_INTEGER int
#else
#define LUA_INTEGER long long
#endif // #if !defined LUA_INTEGRAL_LONGLONG
......@@ -487,7 +492,7 @@ extern int readline4lua(const char *prompt, char *buffer, int length);
/* 16-bit ints */
#define LUAI_UINT32 unsigned long
#define LUAI_INT32 long
#define LUAI_MAXINT32 LONG_MAX
#define LUAI_MAXINT32 INT_MAX
#define LUAI_UMEM unsigned long
#define LUAI_MEM long
#endif
......@@ -607,8 +612,8 @@ extern int readline4lua(const char *prompt, char *buffer, int length);
*/
#if defined LUA_NUMBER_INTEGRAL
#if !defined LUA_INTEGRAL_LONGLONG
#define LUA_NUMBER_SCAN "%ld"
#define LUA_NUMBER_FMT "%ld"
#define LUA_NUMBER_SCAN "%d"
#define LUA_NUMBER_FMT "%d"
#else
#define LUA_NUMBER_SCAN "%lld"
#define LUA_NUMBER_FMT "%lld"
......@@ -894,7 +899,7 @@ union luai_Cast { double l_d; long l_l; };
/* If you define the next macro you'll get the ability to set rotables as
metatables for tables/userdata/types (but the VM might run slower)
*/
#if (LUA_OPTIMIZE_MEMORY == 2) && !defined(LUA_CROSS_COMPILER)
#if (LUA_OPTIMIZE_MEMORY == 2)
#define LUA_META_ROTABLES
#endif
......
......@@ -172,7 +172,7 @@ static TString* LoadString(LoadState* S)
} else {
s = (char*)luaZ_get_crt_address(S->Z);
LoadBlock(S,NULL,size);
return luaS_newrolstr(S->L,s,size-1);
return luaS_newlstr(S->L,s,size-1);
}
}
}
......@@ -280,7 +280,7 @@ static Proto* LoadFunction(LoadState* S, TString* p)
Proto* f;
if (++S->L->nCcalls > LUAI_MAXCCALLS) error(S,"code too deep");
f=luaF_newproto(S->L);
if (luaZ_direct_mode(S->Z)) proto_readonly(f);
if (luaZ_direct_mode(S->Z)) l_setbit((f)->marked, READONLYBIT);
setptvalue2s(S->L,S->L->top,f); incr_top(S->L);
f->source=LoadString(S); if (f->source==NULL) f->source=p;
f->linedefined=LoadInt(S);
......
......@@ -41,7 +41,7 @@ LUA_NUMBER luai_ipow(LUA_NUMBER a, LUA_NUMBER b) {
LUA_NUMBER c = 1;
for (;;) {
if (b & 1)
c *= a;
c *= a;
b = b >> 1;
if (b == 0)
return c;
......
......@@ -689,6 +689,7 @@ static void ICACHE_FLASH_ATTR handle_dhcp(void *arg,
os_printf("dhcps: handle_dhcp-> DHCPD_STATE_ACK\n");
#endif
send_ack(pmsg_dhcps, malloc_len);
wifi_softap_set_station_info(pmsg_dhcps->chaddr, &client_address.addr);
break;
case DHCPS_STATE_NAK://4
#if DHCPS_DEBUG
......@@ -1199,7 +1200,6 @@ uint32 ICACHE_FLASH_ATTR wifi_softap_dhcps_client_update(u8 *bssid, struct ip_ad
node_insert_to_list(&plist,pback_node);
}
}
wifi_softap_set_station_info(bssid, &pdhcps_pool->ip);
return pdhcps_pool->ip.addr;
}
......@@ -1105,6 +1105,8 @@ espconn_set_opt(struct espconn *espconn, uint8 opt)
if (value) {
pnode->pcommon.espconn_opt |= opt;
tpcb = pnode->pcommon.pcb;
if (NULL == tpcb)
return ESPCONN_OK;
if (espconn_delay_disabled(pnode))
tcp_nagle_disable(tpcb);
......@@ -1143,7 +1145,8 @@ espconn_clear_opt(struct espconn *espconn, uint8 opt)
tpcb = pnode->pcommon.pcb;
if (espconn_keepalive_enabled(pnode))
espconn_keepalive_disable(tpcb);
if (NULL == tpcb)
return ESPCONN_OK;
if (espconn_delay_enabled(pnode))
tcp_nagle_enable(tpcb);
......@@ -1176,6 +1179,8 @@ sint8 ICACHE_FLASH_ATTR espconn_set_keepalive(struct espconn *espconn, uint8 lev
value = espconn_find_connection(espconn, &pnode);
if (value && espconn_keepalive_disabled(pnode)) {
struct tcp_pcb *pcb = pnode->pcommon.pcb;
if (NULL == pcb)
return ESPCONN_OK;
switch (level){
case ESPCONN_KEEPIDLE:
pcb->keep_idle = 1000 * (u32_t)(*(int*)optarg);
......@@ -1221,6 +1226,8 @@ sint8 ICACHE_FLASH_ATTR espconn_get_keepalive(struct espconn *espconn, uint8 lev
value = espconn_find_connection(espconn, &pnode);
if (value && espconn_keepalive_disabled(pnode)) {
struct tcp_pcb *pcb = pnode->pcommon.pcb;
if (NULL == pcb)
return ESPCONN_OK;
switch (level) {
case ESPCONN_KEEPIDLE:
*(int*)optarg = (int)(pcb->keep_idle/1000);
......
......@@ -43,14 +43,14 @@ INCLUDES += -I ./
INCLUDES += -I ../libc
INCLUDES += -I ../coap
INCLUDES += -I ../mqtt
INCLUDES += -I ../u8glib
INCLUDES += -I ../u8g2lib/u8g2/src/clib
INCLUDES += -I ../ucglib
INCLUDES += -I ../lua
INCLUDES += -I ../pcm
INCLUDES += -I ../platform
INCLUDES += -I ../spiffs
INCLUDES += -I ../smart
INCLUDES += -I ../dhtlib
INCLUDES += -I ../dht
INCLUDES += -I ../fatfs
INCLUDES += -I ../http
INCLUDES += -I ../sjson
......
......@@ -214,18 +214,53 @@ static int file_open( lua_State* L )
static int file_list( lua_State* L )
{
vfs_dir *dir;
const char *pattern;
struct vfs_stat stat;
int pcres;
lua_settop(L, 1);
pattern = luaL_optstring(L, 1, NULL); /* Pattern (arg) or nil (not) at 1 */
dir = vfs_opendir("");
if (dir == NULL) {
return 0;
}
lua_newtable( L ); /* Table at 2 */
if (pattern) {
/*
* We know that pattern is a string, and so the "match" method will always
* exist. No need to check return value here
*/
luaL_getmetafield( L, 1, "match" ); /* Function at 3 */
}
if (dir = vfs_opendir("")) {
lua_newtable( L );
struct vfs_stat stat;
while (vfs_readdir(dir, &stat) == VFS_RES_OK) {
lua_pushinteger(L, stat.size);
lua_setfield(L, -2, stat.name);
while (vfs_readdir(dir, &stat) == VFS_RES_OK) {
if (pattern) {
lua_settop( L, 3 ); /* Ensure nothing else on stack */
/* Construct and pcall(string.match,name,pattern) */
lua_pushvalue( L, 3 );
lua_pushstring( L, stat.name );
lua_pushvalue( L, 1 );
pcres = lua_pcall( L, 2, 1, 0 );
if (pcres != 0) {
vfs_closedir(dir);
lua_error( L );
}
if (lua_isnil( L, -1 )) {
continue;
}
}
vfs_closedir(dir);
return 1;
lua_pushinteger( L, stat.size );
lua_setfield( L, 2, stat.name );
}
return 0;
/* Shed everything back to Table */
lua_settop( L, 2 );
vfs_closedir(dir);
return 1;
}
static int get_file_obj( lua_State *L, int *argpos )
......
......@@ -2,7 +2,8 @@
* This module, when enabled with the LUA_USE_MODULES_GDBSTUB define causes
* the gdbstub code to be included and enabled to handle all fatal exceptions.
* This allows you to use the lx106 gdb to catch the exception and then poke
* around. You can't continue from an exception (at least not easily).
* around. You can continue from a break, but attempting to continue from an
* exception usually fails.
*
* This should not be included in production builds as any exception will
* put the nodemcu into a state where it is waiting for serial input and it has
......@@ -41,8 +42,8 @@ static int lgdbstub_open(lua_State *L) {
static const LUA_REG_TYPE gdbstub_map[] = {
{ LSTRKEY( "brk" ), LFUNCVAL( lgdbstub_break ) },
{ LSTRKEY( "gdboutput" ), LFUNCVAL( lgdbstub_gdboutput) },
{ LSTRKEY( "open" ), LFUNCVAL( lgdbstub_open) },
{ LNILKEY, LNILVAL }
};
NODEMCU_MODULE(GDBSTUB, "gdbstub", gdbstub_map, lgdbstub_open);
NODEMCU_MODULE(GDBSTUB, "gdbstub", gdbstub_map, NULL);
/*
** $Id: linit.c,v 1.14.1.1 2007/12/27 13:02:25 roberto Exp $
** Initialization of libraries for lua.c
** See Copyright Notice in lua.h
*/
#define linit_c
#define LUA_LIB
#define LUAC_CROSS_FILE
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
#include "luaconf.h"
#include "module.h"
BUILTIN_LIB_INIT( BASE, "", luaopen_base);
BUILTIN_LIB_INIT( LOADLIB, LUA_LOADLIBNAME, luaopen_package);
#if defined(LUA_USE_BUILTIN_IO)
BUILTIN_LIB_INIT( IO, LUA_IOLIBNAME, luaopen_io);
#endif
#if defined (LUA_USE_BUILTIN_STRING)
extern const luaR_entry strlib[];
BUILTIN_LIB_INIT( STRING, LUA_STRLIBNAME, luaopen_string);
BUILTIN_LIB( STRING, LUA_STRLIBNAME, strlib);
#endif
#if defined(LUA_USE_BUILTIN_TABLE)
extern const luaR_entry tab_funcs[];
BUILTIN_LIB_INIT( TABLE, LUA_TABLIBNAME, luaopen_table);
BUILTIN_LIB( TABLE, LUA_TABLIBNAME, tab_funcs);
#endif
#if defined(LUA_USE_BUILTIN_DEBUG) || defined(LUA_USE_BUILTIN_DEBUG_MINIMAL)
extern const luaR_entry dblib[];
BUILTIN_LIB_INIT( DBG, LUA_DBLIBNAME, luaopen_debug);
BUILTIN_LIB( DBG, LUA_DBLIBNAME, dblib);
#endif
#if defined(LUA_USE_BUILTIN_OS)
extern const luaR_entry syslib[];
BUILTIN_LIB( OS, LUA_OSLIBNAME, syslib);
#endif
#if defined(LUA_USE_BUILTIN_COROUTINE)
extern const luaR_entry co_funcs[];
BUILTIN_LIB( CO, LUA_COLIBNAME, co_funcs);
#endif
#if defined(LUA_USE_BUILTIN_MATH)
extern const luaR_entry math_map[];
BUILTIN_LIB( MATH, LUA_MATHLIBNAME, math_map);
#endif
#ifdef LUA_CROSS_COMPILER
const luaL_Reg lua_libs[] = {{NULL, NULL}};
const luaR_table lua_rotable[] = {{NULL, NULL}};
#else
extern const luaL_Reg lua_libs[];
#endif
void luaL_openlibs (lua_State *L) {
const luaL_Reg *lib = lua_libs;
for (; lib->name; lib++) {
if (lib->func)
{
lua_pushcfunction(L, lib->func);
lua_pushstring(L, lib->name);
lua_call(L, 1, 0);
}
}
}
......@@ -17,7 +17,9 @@
#include "platform.h"
#include "lrodefs.h"
#ifdef LUA_FLASH_STORE
#include "lflash.h"
#endif
#include "c_types.h"
#include "c_string.h"
#include "driver/uart.h"
......@@ -149,7 +151,6 @@ static int node_chipid( lua_State* L )
// lua_pushinteger(L, vdd33);
// return 1;
// }
// Lua: flashid()
static int node_flashid( lua_State* L )
{
......@@ -178,26 +179,16 @@ static int node_heap( lua_State* L )
return 1;
}
extern lua_Load gLoad;
extern int lua_put_line(const char *s, size_t l);
extern bool user_process_input(bool force);
// Lua: input("string")
static int node_input( lua_State* L )
{
static int node_input( lua_State* L ) {
size_t l = 0;
const char *s = luaL_checklstring(L, 1, &l);
if (s != NULL && l > 0 && l < LUA_MAXINPUT - 1)
{
lua_Load *load = &gLoad;
if (load->line_position == 0) {
c_memcpy(load->line, s, l);
load->line[l + 1] = '\0';
load->line_position = c_strlen(load->line) + 1;
load->done = 1;
NODE_DBG("Get command:\n");
NODE_DBG(load->line); // buggy here
NODE_DBG("\nResult(if any):\n");
user_process_input(true);
}
if (lua_put_line(s, l)) {
NODE_DBG("Result (if any):\n");
user_process_input(true);
}
return 0;
}
......@@ -609,6 +600,13 @@ static const LUA_REG_TYPE node_task_map[] = {
static const LUA_REG_TYPE node_map[] =
{
{ LSTRKEY( "heap" ), LFUNCVAL( node_heap ) },
{ LSTRKEY( "info" ), LFUNCVAL( node_info ) },
{ LSTRKEY( "task" ), LROVAL( node_task_map ) },
#ifdef LUA_FLASH_STORE
{ LSTRKEY( "flashreload" ), LFUNCVAL( luaN_reload_reboot ) },
{ LSTRKEY( "flashindex" ), LFUNCVAL( luaN_index ) },
#endif
{ LSTRKEY( "restart" ), LFUNCVAL( node_restart ) },
{ LSTRKEY( "dsleep" ), LFUNCVAL( node_deepsleep ) },
{ LSTRKEY( "dsleepMax" ), LFUNCVAL( dsleepMax ) },
......@@ -616,11 +614,9 @@ static const LUA_REG_TYPE node_map[] =
#ifdef PMSLEEP_ENABLE
PMSLEEP_INT_MAP,
#endif
{ LSTRKEY( "info" ), LFUNCVAL( node_info ) },
{ LSTRKEY( "chipid" ), LFUNCVAL( node_chipid ) },
{ LSTRKEY( "flashid" ), LFUNCVAL( node_flashid ) },
{ LSTRKEY( "flashsize" ), LFUNCVAL( node_flashsize) },
{ LSTRKEY( "heap" ), LFUNCVAL( node_heap ) },
{ LSTRKEY( "input" ), LFUNCVAL( node_input ) },
{ LSTRKEY( "output" ), LFUNCVAL( node_output ) },
// Moved to adc module, use adc.readvdd33()
......@@ -637,7 +633,6 @@ static const LUA_REG_TYPE node_map[] =
{ LSTRKEY( "stripdebug" ), LFUNCVAL( node_stripdebug ) },
#endif
{ LSTRKEY( "egc" ), LROVAL( node_egc_map ) },
{ LSTRKEY( "task" ), LROVAL( node_task_map ) },
#ifdef DEVELOPMENT_TOOLS
{ LSTRKEY( "osprint" ), LFUNCVAL( node_osprint ) },
#endif
......
File mode changed from 100755 to 100644
// Module for U8glib
#include "module.h"
#include "lauxlib.h"
#include "lmem.h"
#include "u8g.h"
#include "u8g_glue.h"
#include "u8g_config.h"
// helper function: retrieve and check userdata argument
static lu8g_userdata_t *get_lud( lua_State *L )
{
lu8g_userdata_t *lud = (lu8g_userdata_t *)luaL_checkudata(L, 1, "u8g.display");
luaL_argcheck(L, lud, 1, "u8g.display expected");
return lud;
}
// helper function: retrieve given number of integer arguments
static void lu8g_get_int_args( lua_State *L, uint8_t stack, uint8_t num, u8g_uint_t *args)
{
while (num-- > 0)
{
*args++ = luaL_checkinteger( L, stack++ );
}
}
// Lua: u8g.begin( self )
static int lu8g_begin( lua_State *L )
{
lu8g_userdata_t *lud;
if ((lud = get_lud( L )) == NULL)
return 0;
u8g_Begin( LU8G );
return 0;
}
// Lua: u8g.setFont( self, font )
static int lu8g_setFont( lua_State *L )
{
lu8g_userdata_t *lud;
if ((lud = get_lud( L )) == NULL)
return 0;
u8g_fntpgm_uint8_t *font = (u8g_fntpgm_uint8_t *)lua_touserdata( L, 2 );
if (font != NULL)
u8g_SetFont( LU8G, font );
else
luaL_argerror(L, 2, "font data expected");
return 0;
}
// Lua: u8g.setFontRefHeightAll( self )
static int lu8g_setFontRefHeightAll( lua_State *L )
{
lu8g_userdata_t *lud;
if ((lud = get_lud( L )) == NULL)
return 0;
u8g_SetFontRefHeightAll( LU8G );
return 0;
}
// Lua: u8g.setFontRefHeightExtendedText( self )
static int lu8g_setFontRefHeightExtendedText( lua_State *L )
{
lu8g_userdata_t *lud;
if ((lud = get_lud( L )) == NULL)
return 0;
u8g_SetFontRefHeightExtendedText( LU8G );
return 0;
}
// Lua: u8g.setFontRefHeightText( self )
static int lu8g_setFontRefHeightText( lua_State *L )
{
lu8g_userdata_t *lud;
if ((lud = get_lud( L )) == NULL)
return 0;
u8g_SetFontRefHeightText( LU8G );
return 0;
}
// Lua: u8g.setDefaultBackgroundColor( self )
static int lu8g_setDefaultBackgroundColor( lua_State *L )
{
lu8g_userdata_t *lud;
if ((lud = get_lud( L )) == NULL)
return 0;
u8g_SetDefaultBackgroundColor( LU8G );
return 0;
}
// Lua: u8g.setDefaultForegroundColor( self )
static int lu8g_setDefaultForegroundColor( lua_State *L )
{
lu8g_userdata_t *lud;
if ((lud = get_lud( L )) == NULL)
return 0;
u8g_SetDefaultForegroundColor( LU8G );
return 0;
}
// Lua: u8g.setFontPosBaseline( self )
static int lu8g_setFontPosBaseline( lua_State *L )
{
lu8g_userdata_t *lud;
if ((lud = get_lud( L )) == NULL)
return 0;
u8g_SetFontPosBaseline( LU8G );
return 0;
}
// Lua: u8g.setFontPosBottom( self )
static int lu8g_setFontPosBottom( lua_State *L )
{
lu8g_userdata_t *lud;
if ((lud = get_lud( L )) == NULL)
return 0;
u8g_SetFontPosBottom( LU8G );
return 0;
}
// Lua: u8g.setFontPosCenter( self )
static int lu8g_setFontPosCenter( lua_State *L )
{
lu8g_userdata_t *lud;
if ((lud = get_lud( L )) == NULL)
return 0;
u8g_SetFontPosCenter( LU8G );
return 0;
}
// Lua: u8g.setFontPosTop( self )
static int lu8g_setFontPosTop( lua_State *L )
{
lu8g_userdata_t *lud;
if ((lud = get_lud( L )) == NULL)
return 0;
u8g_SetFontPosTop( LU8G );
return 0;
}
// Lua: int = u8g.getFontAscent( self )
static int lu8g_getFontAscent( lua_State *L )
{
lu8g_userdata_t *lud;
if ((lud = get_lud( L )) == NULL)
return 0;
lua_pushinteger( L, u8g_GetFontAscent( LU8G ) );
return 1;
}
// Lua: int = u8g.getFontDescent( self )
static int lu8g_getFontDescent( lua_State *L )
{
lu8g_userdata_t *lud;
if ((lud = get_lud( L )) == NULL)
return 0;
lua_pushinteger( L, u8g_GetFontDescent( LU8G ) );
return 1;
}
// Lua: int = u8g.getFontLineSpacing( self )
static int lu8g_getFontLineSpacing( lua_State *L )
{
lu8g_userdata_t *lud;
if ((lud = get_lud( L )) == NULL)
return 0;
lua_pushinteger( L, u8g_GetFontLineSpacing( LU8G ) );
return 1;
}
// Lua: int = u8g.getMode( self )
static int lu8g_getMode( lua_State *L )
{
lu8g_userdata_t *lud;
if ((lud = get_lud( L )) == NULL)
return 0;
lua_pushinteger( L, u8g_GetMode( LU8G ) );
return 1;
}
// Lua: u8g.setContrast( self, constrast )
static int lu8g_setContrast( lua_State *L )
{
lu8g_userdata_t *lud;
if ((lud = get_lud( L )) == NULL)
return 0;
u8g_SetContrast( LU8G, luaL_checkinteger( L, 2 ) );
return 0;
}
// Lua: u8g.setColorIndex( self, color )
static int lu8g_setColorIndex( lua_State *L )
{
lu8g_userdata_t *lud;
if ((lud = get_lud( L )) == NULL)
return 0;
u8g_SetColorIndex( LU8G, luaL_checkinteger( L, 2 ) );
return 0;
}
// Lua: int = u8g.getColorIndex( self )
static int lu8g_getColorIndex( lua_State *L )
{
lu8g_userdata_t *lud;
if ((lud = get_lud( L )) == NULL)
return 0;
lua_pushinteger( L, u8g_GetColorIndex( LU8G ) );
return 1;
}
static int lu8g_generic_drawStr( lua_State *L, uint8_t rot )
{
lu8g_userdata_t *lud;
if ((lud = get_lud( L )) == NULL)
return 0;
u8g_uint_t args[2];
lu8g_get_int_args( L, 2, 2, args );
const char *s = luaL_checkstring( L, (1+2) + 1 );
if (s == NULL)
return 0;
switch (rot)
{
case 1:
lua_pushinteger( L, u8g_DrawStr90( LU8G, args[0], args[1], s ) );
break;
case 2:
lua_pushinteger( L, u8g_DrawStr180( LU8G, args[0], args[1], s ) );
break;
case 3:
lua_pushinteger( L, u8g_DrawStr270( LU8G, args[0], args[1], s ) );
break;
default:
lua_pushinteger( L, u8g_DrawStr( LU8G, args[0], args[1], s ) );
break;
}
return 1;
}
// Lua: pix_len = u8g.drawStr( self, x, y, string )
static int lu8g_drawStr( lua_State *L )
{
return lu8g_generic_drawStr( L, 0 );
}
// Lua: pix_len = u8g.drawStr90( self, x, y, string )
static int lu8g_drawStr90( lua_State *L )
{
return lu8g_generic_drawStr( L, 1 );
}
// Lua: pix_len = u8g.drawStr180( self, x, y, string )
static int lu8g_drawStr180( lua_State *L )
{
return lu8g_generic_drawStr( L, 2 );
}
// Lua: pix_len = u8g.drawStr270( self, x, y, string )
static int lu8g_drawStr270( lua_State *L )
{
return lu8g_generic_drawStr( L, 3 );
}
// Lua: u8g.drawLine( self, x1, y1, x2, y2 )
static int lu8g_drawLine( lua_State *L )
{
lu8g_userdata_t *lud;
if ((lud = get_lud( L )) == NULL)
return 0;
u8g_uint_t args[4];
lu8g_get_int_args( L, 2, 4, args );
u8g_DrawLine( LU8G, args[0], args[1], args[2], args[3] );
return 0;
}
// Lua: u8g.drawTriangle( self, x0, y0, x1, y1, x2, y2 )
static int lu8g_drawTriangle( lua_State *L )
{
lu8g_userdata_t *lud;
if ((lud = get_lud( L )) == NULL)
return 0;
u8g_uint_t args[6];
lu8g_get_int_args( L, 2, 6, args );
u8g_DrawTriangle( LU8G, args[0], args[1], args[2], args[3], args[4], args[5] );
return 0;
}
// Lua: u8g.drawBox( self, x, y, width, height )
static int lu8g_drawBox( lua_State *L )
{
lu8g_userdata_t *lud;
if ((lud = get_lud( L )) == NULL)
return 0;
u8g_uint_t args[4];
lu8g_get_int_args( L, 2, 4, args );
u8g_DrawBox( LU8G, args[0], args[1], args[2], args[3] );
return 0;
}
// Lua: u8g.drawRBox( self, x, y, width, height, radius )
static int lu8g_drawRBox( lua_State *L )
{
lu8g_userdata_t *lud;
if ((lud = get_lud( L )) == NULL)
return 0;
u8g_uint_t args[5];
lu8g_get_int_args( L, 2, 5, args );
u8g_DrawRBox( LU8G, args[0], args[1], args[2], args[3], args[4] );
return 0;
}
// Lua: u8g.drawFrame( self, x, y, width, height )
static int lu8g_drawFrame( lua_State *L )
{
lu8g_userdata_t *lud;
if ((lud = get_lud( L )) == NULL)
return 0;
u8g_uint_t args[4];
lu8g_get_int_args( L, 2, 4, args );
u8g_DrawFrame( LU8G, args[0], args[1], args[2], args[3] );
return 0;
}
// Lua: u8g.drawRFrame( self, x, y, width, height, radius )
static int lu8g_drawRFrame( lua_State *L )
{
lu8g_userdata_t *lud;
if ((lud = get_lud( L )) == NULL)
return 0;
u8g_uint_t args[5];
lu8g_get_int_args( L, 2, 5, args );
u8g_DrawRFrame( LU8G, args[0], args[1], args[2], args[3], args[4] );
return 0;
}
// Lua: u8g.drawDisc( self, x0, y0, rad, opt = U8G_DRAW_ALL )
static int lu8g_drawDisc( lua_State *L )
{
lu8g_userdata_t *lud;
if ((lud = get_lud( L )) == NULL)
return 0;
u8g_uint_t args[3];
lu8g_get_int_args( L, 2, 3, args );
u8g_uint_t opt = luaL_optinteger( L, (1+3) + 1, U8G_DRAW_ALL );
u8g_DrawDisc( LU8G, args[0], args[1], args[2], opt );
return 0;
}
// Lua: u8g.drawCircle( self, x0, y0, rad, opt = U8G_DRAW_ALL )
static int lu8g_drawCircle( lua_State *L )
{
lu8g_userdata_t *lud;
if ((lud = get_lud( L )) == NULL)
return 0;
u8g_uint_t args[3];
lu8g_get_int_args( L, 2, 3, args );
u8g_uint_t opt = luaL_optinteger( L, (1+3) + 1, U8G_DRAW_ALL );
u8g_DrawCircle( LU8G, args[0], args[1], args[2], opt );
return 0;
}
// Lua: u8g.drawEllipse( self, x0, y0, rx, ry, opt = U8G_DRAW_ALL )
static int lu8g_drawEllipse( lua_State *L )
{
lu8g_userdata_t *lud;
if ((lud = get_lud( L )) == NULL)
return 0;
u8g_uint_t args[4];
lu8g_get_int_args( L, 2, 4, args );
u8g_uint_t opt = luaL_optinteger( L, (1+4) + 1, U8G_DRAW_ALL );
u8g_DrawEllipse( LU8G, args[0], args[1], args[2], args[3], opt );
return 0;
}
// Lua: u8g.drawFilledEllipse( self, x0, y0, rx, ry, opt = U8G_DRAW_ALL )
static int lu8g_drawFilledEllipse( lua_State *L )
{
lu8g_userdata_t *lud;
if ((lud = get_lud( L )) == NULL)
return 0;
u8g_uint_t args[4];
lu8g_get_int_args( L, 2, 4, args );
u8g_uint_t opt = luaL_optinteger( L, (1+4) + 1, U8G_DRAW_ALL );
u8g_DrawFilledEllipse( LU8G, args[0], args[1], args[2], args[3], opt );
return 0;
}
// Lua: u8g.drawPixel( self, x, y )
static int lu8g_drawPixel( lua_State *L )
{
lu8g_userdata_t *lud;
if ((lud = get_lud( L )) == NULL)
return 0;
u8g_uint_t args[2];
lu8g_get_int_args( L, 2, 2, args );
u8g_DrawPixel( LU8G, args[0], args[1] );
return 0;
}
// Lua: u8g.drawHLine( self, x, y, width )
static int lu8g_drawHLine( lua_State *L )
{
lu8g_userdata_t *lud;
if ((lud = get_lud( L )) == NULL)
return 0;
u8g_uint_t args[3];
lu8g_get_int_args( L, 2, 3, args );
u8g_DrawHLine( LU8G, args[0], args[1], args[2] );
return 0;
}
// Lua: u8g.drawVLine( self, x, y, width )
static int lu8g_drawVLine( lua_State *L )
{
lu8g_userdata_t *lud;
if ((lud = get_lud( L )) == NULL)
return 0;
u8g_uint_t args[3];
lu8g_get_int_args( L, 2, 3, args );
u8g_DrawVLine( LU8G, args[0], args[1], args[2] );
return 0;
}
// Lua: u8g.drawXBM( self, x, y, width, height, data )
static int lu8g_drawXBM( lua_State *L )
{
lu8g_userdata_t *lud;
if ((lud = get_lud( L )) == NULL)
return 0;
u8g_uint_t args[4];
lu8g_get_int_args( L, 2, 4, args );
const char *xbm_data = luaL_checkstring( L, (1+4) + 1 );
if (xbm_data == NULL)
return 0;
u8g_DrawXBM( LU8G, args[0], args[1], args[2], args[3], (const uint8_t *)xbm_data );
return 0;
}
// Lua: u8g.drawBitmap( self, x, y, count, height, data )
static int lu8g_drawBitmap( lua_State *L )
{
lu8g_userdata_t *lud;
if ((lud = get_lud( L )) == NULL)
return 0;
u8g_uint_t args[4];
lu8g_get_int_args( L, 2, 4, args );
const char *bm_data = luaL_checkstring( L, (1+4) + 1 );
if (bm_data == NULL)
return 0;
u8g_DrawBitmap( LU8G, args[0], args[1], args[2], args[3], (const uint8_t *)bm_data );
return 0;
}
// Lua: u8g.setScale2x2( self )
static int lu8g_setScale2x2( lua_State *L )
{
lu8g_userdata_t *lud;
if ((lud = get_lud( L )) == NULL)
return 0;
u8g_SetScale2x2( LU8G );
return 0;
}
// Lua: u8g.undoScale( self )
static int lu8g_undoScale( lua_State *L )
{
lu8g_userdata_t *lud;
if ((lud = get_lud( L )) == NULL)
return 0;
u8g_UndoScale( LU8G );
return 0;
}
// Lua: u8g.firstPage( self )
static int lu8g_firstPage( lua_State *L )
{
lu8g_userdata_t *lud;
if ((lud = get_lud( L )) == NULL)
return 0;
u8g_FirstPage( LU8G );
return 0;
}
// Lua: bool = u8g.nextPage( self )
static int lu8g_nextPage( lua_State *L )
{
lu8g_userdata_t *lud;
if ((lud = get_lud( L )) == NULL)
return 0;
lua_pushboolean( L, u8g_NextPage( LU8G ) );
return 1;
}
// Lua: u8g.sleepOn( self )
static int lu8g_sleepOn( lua_State *L )
{
lu8g_userdata_t *lud;
if ((lud = get_lud( L )) == NULL)
return 0;
u8g_SleepOn( LU8G );
return 0;
}
// Lua: u8g.sleepOff( self )
static int lu8g_sleepOff( lua_State *L )
{
lu8g_userdata_t *lud;
if ((lud = get_lud( L )) == NULL)
return 0;
u8g_SleepOff( LU8G );
return 0;
}
// Lua: u8g.setRot90( self )
static int lu8g_setRot90( lua_State *L )
{
lu8g_userdata_t *lud;
if ((lud = get_lud( L )) == NULL)
return 0;
u8g_SetRot90( LU8G );
return 0;
}
// Lua: u8g.setRot180( self )
static int lu8g_setRot180( lua_State *L )
{
lu8g_userdata_t *lud;
if ((lud = get_lud( L )) == NULL)
return 0;
u8g_SetRot180( LU8G );
return 0;
}
// Lua: u8g.setRot270( self )
static int lu8g_setRot270( lua_State *L )
{
lu8g_userdata_t *lud;
if ((lud = get_lud( L )) == NULL)
return 0;
u8g_SetRot270( LU8G );
return 0;
}
// Lua: u8g.undoRotation( self )
static int lu8g_undoRotation( lua_State *L )
{
lu8g_userdata_t *lud;
if ((lud = get_lud( L )) == NULL)
return 0;
u8g_UndoRotation( LU8G );
return 0;
}
// Lua: width = u8g.getWidth( self )
static int lu8g_getWidth( lua_State *L )
{
lu8g_userdata_t *lud;
if ((lud = get_lud( L )) == NULL)
return 0;
lua_pushinteger( L, u8g_GetWidth( LU8G ) );
return 1;
}
// Lua: height = u8g.getHeight( self )
static int lu8g_getHeight( lua_State *L )
{
lu8g_userdata_t *lud;
if ((lud = get_lud( L )) == NULL)
return 0;
lua_pushinteger( L, u8g_GetHeight( LU8G ) );
return 1;
}
// Lua: width = u8g.getStrWidth( self, string )
static int lu8g_getStrWidth( lua_State *L )
{
lu8g_userdata_t *lud;
if ((lud = get_lud( L )) == NULL)
return 0;
const char *s = luaL_checkstring( L, 2 );
if (s == NULL)
return 0;
lua_pushinteger( L, u8g_GetStrWidth( LU8G, s ) );
return 1;
}
// Lua: u8g.setFontLineSpacingFactor( self, factor )
static int lu8g_setFontLineSpacingFactor( lua_State *L )
{
lu8g_userdata_t *lud;
if ((lud = get_lud( L )) == NULL)
return 0;
u8g_uint_t factor = luaL_checkinteger( L, 2 );
u8g_SetFontLineSpacingFactor( LU8G, factor );
return 0;
}
// device destructor
static int lu8g_close_display( lua_State *L )
{
lu8g_userdata_t *lud;
if ((lud = get_lud( L )) == NULL)
return 0;
if (lud->cb_ref != LUA_NOREF) {
// this is the fb_rle device
u8g_dev_t *fb_dev = LU8G->dev;
u8g_pb_t *fb_dev_pb = (u8g_pb_t *)(fb_dev->dev_mem);
uint8_t *fb_dev_buf = fb_dev_pb->buf;
luaM_free( L, fb_dev_buf );
luaM_free( L, fb_dev_pb );
luaM_free( L, fb_dev );
luaL_unref( L, lud->cb_ref, LUA_REGISTRYINDEX );
}
return 0;
}
// ***************************************************************************
// Device constructors
//
//
// I2C based devices will use this function template to implement the Lua binding.
#undef U8G_DISPLAY_TABLE_ENTRY
#define U8G_DISPLAY_TABLE_ENTRY(device) \
static int lu8g_ ## device( lua_State *L ) \
{ \
unsigned addr = luaL_checkinteger( L, 1 ); \
unsigned del = luaL_optinteger( L, 2, 0 ); \
\
if (addr == 0) \
return luaL_error( L, "i2c address required" ); \
\
lu8g_userdata_t *lud = (lu8g_userdata_t *) lua_newuserdata( L, sizeof( lu8g_userdata_t ) ); \
lud->cb_ref = LUA_NOREF; \
\
lud->i2c_addr = (uint8_t)addr; \
lud->use_delay = del > 0 ? 1 : 0; \
\
u8g_InitI2C( LU8G, &u8g_dev_ ## device, U8G_I2C_OPT_NONE); \
\
/* set its metatable */ \
luaL_getmetatable(L, "u8g.display"); \
lua_setmetatable(L, -2); \
\
return 1; \
}
//
// Unroll the display table and insert binding functions for I2C based displays.
U8G_DISPLAY_TABLE_I2C
//
//
//
// SPI based devices will use this function template to implement the Lua binding.
#undef U8G_DISPLAY_TABLE_ENTRY
#define U8G_DISPLAY_TABLE_ENTRY(device) \
static int lu8g_ ## device( lua_State *L ) \
{ \
unsigned cs = luaL_checkinteger( L, 1 ); \
if (cs == 0) \
return luaL_error( L, "CS pin required" ); \
unsigned dc = luaL_checkinteger( L, 2 ); \
if (dc == 0) \
return luaL_error( L, "D/C pin required" ); \
unsigned res = luaL_optinteger( L, 3, U8G_PIN_NONE ); \
unsigned del = luaL_optinteger( L, 4, 0 ); \
\
lu8g_userdata_t *lud = (lu8g_userdata_t *) lua_newuserdata( L, sizeof( lu8g_userdata_t ) ); \
lud->cb_ref = LUA_NOREF; \
\
lud->use_delay = del > 0 ? 1 : 0; \
\
u8g_InitHWSPI( LU8G, &u8g_dev_ ## device, cs, dc, res ); \
\
/* set its metatable */ \
luaL_getmetatable(L, "u8g.display"); \
lua_setmetatable(L, -2); \
\
return 1; \
}
//
// Unroll the display table and insert binding functions for SPI based displays.
U8G_DISPLAY_TABLE_SPI
//
//
//
// This display forwards the framebuffer contents as run-length encoded chunks to a Lua callback
static int lu8g_fb_rle( lua_State *L ) {
lu8g_userdata_t *lud;
if ((lua_type( L, 1 ) != LUA_TFUNCTION) &&
(lua_type( L, 1 ) != LUA_TLIGHTFUNCTION)) {
luaL_typerror( L, 1, "function" );
}
int width = luaL_checkint( L, 2 );
int height = luaL_checkint( L, 3 );
luaL_argcheck( L, (width > 0) && (width < 256) && ((width % 8) == 0), 2, "invalid width" );
luaL_argcheck( L, (height > 0) && (height < 256) && ((height % 8) == 0), 3, "invalid height" );
// construct display device structures manually because width and height are configurable
uint8_t *fb_dev_buf = (uint8_t *)luaM_malloc( L, width );
u8g_pb_t *fb_dev_pb = (u8g_pb_t *)luaM_malloc( L, sizeof( u8g_pb_t ) );
fb_dev_pb->p.page_height = 8;
fb_dev_pb->p.total_height = height;
fb_dev_pb->p.page_y0 = 0;
fb_dev_pb->p.page_y1 = 0;
fb_dev_pb->p.page = 0;
fb_dev_pb->width = width;
fb_dev_pb->buf = fb_dev_buf;
u8g_dev_t *fb_dev = (u8g_dev_t *)luaM_malloc( L, sizeof( u8g_dev_t ) );
fb_dev->dev_fn = u8g_dev_gen_fb_fn;
fb_dev->dev_mem = fb_dev_pb;
fb_dev->com_fn = u8g_com_esp8266_fbrle_fn;
lud = (lu8g_userdata_t *) lua_newuserdata( L, sizeof( lu8g_userdata_t ) );
lua_pushvalue( L, 1 ); // copy argument (func) to the top of stack
lud->cb_ref = luaL_ref( L, LUA_REGISTRYINDEX );
/* set metatable for userdata */
luaL_getmetatable(L, "u8g.display");
lua_setmetatable(L, -2);
u8g_Init8BitFixedPort( LU8G, fb_dev, width, height, 0, 0, 0);
return 1;
}
//
// ***************************************************************************
// Module function map
static const LUA_REG_TYPE lu8g_display_map[] = {
{ LSTRKEY( "begin" ), LFUNCVAL( lu8g_begin ) },
{ LSTRKEY( "drawBitmap" ), LFUNCVAL( lu8g_drawBitmap ) },
{ LSTRKEY( "drawBox" ), LFUNCVAL( lu8g_drawBox ) },
{ LSTRKEY( "drawCircle" ), LFUNCVAL( lu8g_drawCircle ) },
{ LSTRKEY( "drawDisc" ), LFUNCVAL( lu8g_drawDisc ) },
{ LSTRKEY( "drawEllipse" ), LFUNCVAL( lu8g_drawEllipse ) },
{ LSTRKEY( "drawFilledEllipse" ), LFUNCVAL( lu8g_drawFilledEllipse ) },
{ LSTRKEY( "drawFrame" ), LFUNCVAL( lu8g_drawFrame ) },
{ LSTRKEY( "drawHLine" ), LFUNCVAL( lu8g_drawHLine ) },
{ LSTRKEY( "drawLine" ), LFUNCVAL( lu8g_drawLine ) },
{ LSTRKEY( "drawPixel" ), LFUNCVAL( lu8g_drawPixel ) },
{ LSTRKEY( "drawRBox" ), LFUNCVAL( lu8g_drawRBox ) },
{ LSTRKEY( "drawRFrame" ), LFUNCVAL( lu8g_drawRFrame ) },
{ LSTRKEY( "drawStr" ), LFUNCVAL( lu8g_drawStr ) },
{ LSTRKEY( "drawStr90" ), LFUNCVAL( lu8g_drawStr90 ) },
{ LSTRKEY( "drawStr180" ), LFUNCVAL( lu8g_drawStr180 ) },
{ LSTRKEY( "drawStr270" ), LFUNCVAL( lu8g_drawStr270 ) },
{ LSTRKEY( "drawTriangle" ), LFUNCVAL( lu8g_drawTriangle ) },
{ LSTRKEY( "drawVLine" ), LFUNCVAL( lu8g_drawVLine ) },
{ LSTRKEY( "drawXBM" ), LFUNCVAL( lu8g_drawXBM ) },
{ LSTRKEY( "firstPage" ), LFUNCVAL( lu8g_firstPage ) },
{ LSTRKEY( "getColorIndex" ), LFUNCVAL( lu8g_getColorIndex ) },
{ LSTRKEY( "getFontAscent" ), LFUNCVAL( lu8g_getFontAscent ) },
{ LSTRKEY( "getFontDescent" ), LFUNCVAL( lu8g_getFontDescent ) },
{ LSTRKEY( "getFontLineSpacing" ), LFUNCVAL( lu8g_getFontLineSpacing ) },
{ LSTRKEY( "getHeight" ), LFUNCVAL( lu8g_getHeight ) },
{ LSTRKEY( "getMode" ), LFUNCVAL( lu8g_getMode ) },
{ LSTRKEY( "getStrWidth" ), LFUNCVAL( lu8g_getStrWidth ) },
{ LSTRKEY( "getWidth" ), LFUNCVAL( lu8g_getWidth ) },
{ LSTRKEY( "nextPage" ), LFUNCVAL( lu8g_nextPage ) },
{ LSTRKEY( "setContrast" ), LFUNCVAL( lu8g_setContrast ) },
{ LSTRKEY( "setColorIndex" ), LFUNCVAL( lu8g_setColorIndex ) },
{ LSTRKEY( "setDefaultBackgroundColor" ), LFUNCVAL( lu8g_setDefaultBackgroundColor ) },
{ LSTRKEY( "setDefaultForegroundColor" ), LFUNCVAL( lu8g_setDefaultForegroundColor ) },
{ LSTRKEY( "setFont" ), LFUNCVAL( lu8g_setFont ) },
{ LSTRKEY( "setFontLineSpacingFactor" ), LFUNCVAL( lu8g_setFontLineSpacingFactor ) },
{ LSTRKEY( "setFontPosBaseline" ), LFUNCVAL( lu8g_setFontPosBaseline ) },
{ LSTRKEY( "setFontPosBottom" ), LFUNCVAL( lu8g_setFontPosBottom ) },
{ LSTRKEY( "setFontPosCenter" ), LFUNCVAL( lu8g_setFontPosCenter ) },
{ LSTRKEY( "setFontPosTop" ), LFUNCVAL( lu8g_setFontPosTop ) },
{ LSTRKEY( "setFontRefHeightAll" ), LFUNCVAL( lu8g_setFontRefHeightAll ) },
{ LSTRKEY( "setFontRefHeightExtendedText" ), LFUNCVAL( lu8g_setFontRefHeightExtendedText ) },
{ LSTRKEY( "setFontRefHeightText" ), LFUNCVAL( lu8g_setFontRefHeightText ) },
{ LSTRKEY( "setRot90" ), LFUNCVAL( lu8g_setRot90 ) },
{ LSTRKEY( "setRot180" ), LFUNCVAL( lu8g_setRot180 ) },
{ LSTRKEY( "setRot270" ), LFUNCVAL( lu8g_setRot270 ) },
{ LSTRKEY( "setScale2x2" ), LFUNCVAL( lu8g_setScale2x2 ) },
{ LSTRKEY( "sleepOff" ), LFUNCVAL( lu8g_sleepOff ) },
{ LSTRKEY( "sleepOn" ), LFUNCVAL( lu8g_sleepOn ) },
{ LSTRKEY( "undoRotation" ), LFUNCVAL( lu8g_undoRotation ) },
{ LSTRKEY( "undoScale" ), LFUNCVAL( lu8g_undoScale ) },
{ LSTRKEY( "__gc" ), LFUNCVAL( lu8g_close_display ) },
{ LSTRKEY( "__index" ), LROVAL( lu8g_display_map ) },
{ LNILKEY, LNILVAL }
};
#undef U8G_DISPLAY_TABLE_ENTRY
#undef U8G_FONT_TABLE_ENTRY
static const LUA_REG_TYPE lu8g_map[] = {
#define U8G_DISPLAY_TABLE_ENTRY(device) \
{ LSTRKEY( #device ), LFUNCVAL ( lu8g_ ##device ) },
U8G_DISPLAY_TABLE_I2C
U8G_DISPLAY_TABLE_SPI
// Register fonts
#define U8G_FONT_TABLE_ENTRY(font) \
{ LSTRKEY( #font ), LUDATA( (void *)(u8g_ ## font) ) },
U8G_FONT_TABLE
//
{ LSTRKEY( "fb_rle" ), LFUNCVAL( lu8g_fb_rle ) },
// Options for circle/ ellipse drawing
{ LSTRKEY( "DRAW_UPPER_RIGHT" ), LNUMVAL( U8G_DRAW_UPPER_RIGHT ) },
{ LSTRKEY( "DRAW_UPPER_LEFT" ), LNUMVAL( U8G_DRAW_UPPER_LEFT ) },
{ LSTRKEY( "DRAW_LOWER_RIGHT" ), LNUMVAL( U8G_DRAW_LOWER_RIGHT ) },
{ LSTRKEY( "DRAW_LOWER_LEFT" ), LNUMVAL( U8G_DRAW_LOWER_LEFT ) },
{ LSTRKEY( "DRAW_ALL" ), LNUMVAL( U8G_DRAW_ALL ) },
// Display modes
{ LSTRKEY( "MODE_BW" ), LNUMVAL( U8G_MODE_BW ) },
{ LSTRKEY( "MODE_GRAY2BIT" ), LNUMVAL( U8G_MODE_GRAY2BIT ) },
{ LSTRKEY( "__metatable" ), LROVAL( lu8g_map ) },
{ LNILKEY, LNILVAL }
};
int luaopen_u8g( lua_State *L ) {
luaL_rometatable(L, "u8g.display", (void *)lu8g_display_map); // create metatable
return 0;
}
NODEMCU_MODULE(U8G, "u8g", lu8g_map, luaopen_u8g);
// Module for binding the u8g2 library
// Note: This file is intended to be shared between esp8266 and esp32 platform
// Do not use the code from u8g2 submodule and skip the complete source here
// if the u8g2 module is not selected.
// Reason: The whole u8g2 submodule code tree might not even exist in this case.
#include "user_modules.h"
#if defined(LUA_USE_MODULES_U8G2) || defined(ESP_PLATFORM)
#include "module.h"
#include "lauxlib.h"
#define U8X8_USE_PINS
#include "u8g2.h"
#include "u8x8_nodemcu_hal.h"
#include "u8g2_displays.h"
#include "u8g2_fonts.h"
#ifdef ESP_PLATFORM
// ESP32
#include "spi_common.h"
#include "sdkconfig.h"
#endif
#ifndef CONFIG_LUA_MODULE_U8G2
// ignore unused functions if u8g2 module will be skipped anyhow
#pragma GCC diagnostic ignored "-Wunused-function"
#endif
typedef struct {
int font_ref;
int host_ref;
u8g2_nodemcu_t u8g2;
} u8g2_ud_t;
#define GET_U8G2() \
u8g2_ud_t *ud = (u8g2_ud_t *)luaL_checkudata( L, 1, "u8g2.display" ); \
u8g2_t *u8g2 = (u8g2_t *)(&(ud->u8g2));
static int lu8g2_clearBuffer( lua_State *L )
{
GET_U8G2();
u8g2_ClearBuffer( u8g2 );
return 0;
}
static int lu8g2_drawBox( lua_State *L )
{
GET_U8G2();
int stack = 1;
int x = luaL_checkint( L, ++stack );
int y = luaL_checkint( L, ++stack );
int w = luaL_checkint( L, ++stack );
int h = luaL_checkint( L, ++stack );
u8g2_DrawBox( u8g2, x, y, w, h );
return 0;
}
static int lu8g2_drawCircle( lua_State *L )
{
GET_U8G2();
int stack = 1;
int x0 = luaL_checkint( L, ++stack );
int y0 = luaL_checkint( L, ++stack );
int rad = luaL_checkint( L, ++stack );
int opt = luaL_optint( L, ++stack, U8G2_DRAW_ALL );
u8g2_DrawCircle( u8g2, x0, y0, rad, opt );
return 0;
}
static int lu8g2_drawDisc( lua_State *L )
{
GET_U8G2();
int stack = 1;
int x0 = luaL_checkint( L, ++stack );
int y0 = luaL_checkint( L, ++stack );
int rad = luaL_checkint( L, ++stack );
int opt = luaL_optint( L, ++stack, U8G2_DRAW_ALL );
u8g2_DrawDisc( u8g2, x0, y0, rad, opt );
return 0;
}
static int lu8g2_drawEllipse( lua_State *L )
{
GET_U8G2();
int stack = 1;
int x0 = luaL_checkint( L, ++stack );
int y0 = luaL_checkint( L, ++stack );
int rx = luaL_checkint( L, ++stack );
int ry = luaL_checkint( L, ++stack );
int opt = luaL_optint( L, ++stack, U8G2_DRAW_ALL );
u8g2_DrawEllipse( u8g2, x0, y0, rx, ry, opt );
return 0;
}
static int lu8g2_drawFilledEllipse( lua_State *L )
{
GET_U8G2();
int stack = 1;
int x0 = luaL_checkint( L, ++stack );
int y0 = luaL_checkint( L, ++stack );
int rx = luaL_checkint( L, ++stack );
int ry = luaL_checkint( L, ++stack );
int opt = luaL_optint( L, ++stack, U8G2_DRAW_ALL );
u8g2_DrawFilledEllipse( u8g2, x0, y0, rx, ry, opt );
return 0;
}
static int lu8g2_drawFrame( lua_State *L )
{
GET_U8G2();
int stack = 1;
int x = luaL_checkint( L, ++stack );
int y = luaL_checkint( L, ++stack );
int w = luaL_checkint( L, ++stack );
int h = luaL_checkint( L, ++stack );
u8g2_DrawFrame( u8g2, x, y, w, h );
return 0;
}
static int lu8g2_drawGlyph( lua_State *L )
{
GET_U8G2();
int stack = 1;
int x = luaL_checkint( L, ++stack );
int y = luaL_checkint( L, ++stack );
int enc = luaL_checkint( L, ++stack );
u8g2_DrawGlyph( u8g2, x, y, enc );
return 0;
}
static int lu8g2_drawHLine( lua_State *L )
{
GET_U8G2();
int stack = 1;
int x = luaL_checkint( L, ++stack );
int y = luaL_checkint( L, ++stack );
int w = luaL_checkint( L, ++stack );
u8g2_DrawHLine( u8g2, x, y, w );
return 0;
}
static int lu8g2_drawLine( lua_State *L )
{
GET_U8G2();
int stack = 1;
int x0 = luaL_checkint( L, ++stack );
int y0 = luaL_checkint( L, ++stack );
int x1 = luaL_checkint( L, ++stack );
int y1 = luaL_checkint( L, ++stack );
u8g2_DrawLine( u8g2, x0, y0, x1, y1 );
return 0;
}
static int lu8g2_drawPixel( lua_State *L )
{
GET_U8G2();
int stack = 1;
int x = luaL_checkint( L, ++stack );
int y = luaL_checkint( L, ++stack );
u8g2_DrawPixel( u8g2, x, y );
return 0;
}
static int lu8g2_drawRBox( lua_State *L )
{
GET_U8G2();
int stack = 1;
int x = luaL_checkint( L, ++stack );
int y = luaL_checkint( L, ++stack );
int w = luaL_checkint( L, ++stack );
int h = luaL_checkint( L, ++stack );
int r = luaL_checkint( L, ++stack );
u8g2_DrawRBox( u8g2, x, y, w, h, r );
return 0;
}
static int lu8g2_drawRFrame( lua_State *L )
{
GET_U8G2();
int stack = 1;
int x = luaL_checkint( L, ++stack );
int y = luaL_checkint( L, ++stack );
int w = luaL_checkint( L, ++stack );
int h = luaL_checkint( L, ++stack );
int r = luaL_checkint( L, ++stack );
u8g2_DrawRFrame( u8g2, x, y, w, h, r );
return 0;
}
static int lu8g2_drawStr( lua_State *L )
{
GET_U8G2();
int stack = 1;
int x = luaL_checkint( L, ++stack );
int y = luaL_checkint( L, ++stack );
const char *str = luaL_checkstring( L, ++stack );
u8g2_DrawStr( u8g2, x, y, str );
return 0;
}
static int lu8g2_drawTriangle( lua_State *L )
{
GET_U8G2();
int stack = 1;
int x0 = luaL_checkint( L, ++stack );
int y0 = luaL_checkint( L, ++stack );
int x1 = luaL_checkint( L, ++stack );
int y1 = luaL_checkint( L, ++stack );
int x2 = luaL_checkint( L, ++stack );
int y2 = luaL_checkint( L, ++stack );
u8g2_DrawTriangle( u8g2, x0, y0, x1, y1, x2, y2 );
return 0;
}
static int lu8g2_drawUTF8( lua_State *L )
{
GET_U8G2();
int stack = 1;
int x = luaL_checkint( L, ++stack );
int y = luaL_checkint( L, ++stack );
const char *str = luaL_checkstring( L, ++stack );
u8g2_DrawUTF8( u8g2, x, y, str );
return 0;
}
static int lu8g2_drawVLine( lua_State *L )
{
GET_U8G2();
int stack = 1;
int x = luaL_checkint( L, ++stack );
int y = luaL_checkint( L, ++stack );
int h = luaL_checkint( L, ++stack );
u8g2_DrawVLine( u8g2, x, y, h );
return 0;
}
static int lu8g2_drawXBM( lua_State *L )
{
GET_U8G2();
int stack = 1;
int x = luaL_checkint( L, ++stack );
int y = luaL_checkint( L, ++stack );
int w = luaL_checkint( L, ++stack );
int h = luaL_checkint( L, ++stack );
size_t len;
const char *bitmap = luaL_checklstring( L, ++stack, &len );
u8g2_DrawXBM( u8g2, x, y, w, h, (uint8_t *)bitmap );
return 0;
}
static int lu8g2_getAscent( lua_State *L )
{
GET_U8G2();
lua_pushinteger( L, u8g2_GetAscent( u8g2 ) );
return 1;
}
static int lu8g2_getDescent( lua_State *L )
{
GET_U8G2();
lua_pushinteger( L, u8g2_GetDescent( u8g2 ) );
return 1;
}
static int lu8g2_getStrWidth( lua_State *L )
{
GET_U8G2();
int stack = 1;
const char *s = luaL_checkstring( L, ++stack );
lua_pushinteger( L, u8g2_GetStrWidth( u8g2, s ) );
return 1;
}
static int lu8g2_getUTF8Width( lua_State *L )
{
GET_U8G2();
int stack = 1;
const char *s = luaL_checkstring( L, ++stack );
lua_pushinteger( L, u8g2_GetUTF8Width( u8g2, s ) );
return 1;
}
static int lu8g2_sendBuffer( lua_State *L )
{
GET_U8G2();
u8g2_SendBuffer( u8g2 );
return 0;
}
static int lu8g2_setBitmapMode( lua_State *L )
{
GET_U8G2();
int stack = 1;
int is_transparent = luaL_checkint( L, ++stack );
u8g2_SetBitmapMode( u8g2, is_transparent );
return 0;
}
static int lu8g2_setContrast( lua_State *L )
{
GET_U8G2();
int stack = 1;
int value = luaL_checkint( L, ++stack );
u8g2_SetContrast( u8g2, value );
return 0;
}
static int lu8g2_setDisplayRotation( lua_State *L )
{
GET_U8G2();
int stack = 1;
const u8g2_cb_t *u8g2_cb = (u8g2_cb_t *)lua_touserdata( L, ++stack );
u8g2_SetDisplayRotation( u8g2, u8g2_cb );
return 0;
}
static int lu8g2_setDrawColor( lua_State *L )
{
GET_U8G2();
int stack = 1;
int col = luaL_checkint( L, ++stack );
u8g2_SetDrawColor( u8g2, col );
return 0;
}
static int lu8g2_setFlipMode( lua_State *L )
{
GET_U8G2();
int stack = 1;
int is_enable = luaL_checkint( L, ++stack );
u8g2_SetFlipMode( u8g2, is_enable );
return 0;
}
static int lu8g2_setFont( lua_State *L )
{
GET_U8G2();
int stack = 1;
const uint8_t *font = NULL;
luaL_unref( L, LUA_REGISTRYINDEX, ud->font_ref );
ud->font_ref = LUA_NOREF;
if (lua_islightuserdata( L, ++stack )) {
font = (const uint8_t *)lua_touserdata( L, stack );
} else if (lua_isstring( L, stack )) {
// ref the font string to safe it in case the string variable gets gc'ed
lua_pushvalue( L, stack );
ud->font_ref = luaL_ref( L, LUA_REGISTRYINDEX );
size_t len;
font = (const uint8_t *)luaL_checklstring( L, stack, &len );
}
luaL_argcheck( L, font != NULL, stack, "invalid font" );
u8g2_SetFont( u8g2, font );
return 0;
}
static int lu8g2_setFontDirection( lua_State *L )
{
GET_U8G2();
int stack = 1;
int dir = luaL_checkint( L, ++stack );
u8g2_SetFontDirection( u8g2, dir );
return 0;
}
static int lu8g2_setFontMode( lua_State *L )
{
GET_U8G2();
int stack = 1;
int is_transparent = luaL_checkint( L, ++stack );
u8g2_SetFontMode( u8g2, is_transparent );
return 0;
}
static int lu8g2_setFontPosBaseline( lua_State *L )
{
GET_U8G2();
u8g2_SetFontPosBaseline( u8g2 );
return 0;
}
static int lu8g2_setFontPosBottom( lua_State *L )
{
GET_U8G2();
u8g2_SetFontPosBottom( u8g2 );
return 0;
}
static int lu8g2_setFontPosTop( lua_State *L )
{
GET_U8G2();
u8g2_SetFontPosTop( u8g2 );
return 0;
}
static int lu8g2_setFontPosCenter( lua_State *L )
{
GET_U8G2();
u8g2_SetFontPosCenter( u8g2 );
return 0;
}
static int lu8g2_setFontRefHeightAll( lua_State *L )
{
GET_U8G2();
u8g2_SetFontRefHeightAll( u8g2 );
return 0;
}
static int lu8g2_setFontRefHeightExtendedText( lua_State *L )
{
GET_U8G2();
u8g2_SetFontRefHeightExtendedText( u8g2 );
return 0;
}
static int lu8g2_setFontRefHeightText( lua_State *L )
{
GET_U8G2();
u8g2_SetFontRefHeightText( u8g2 );
return 0;
}
static int lu8g2_setPowerSave( lua_State *L )
{
GET_U8G2();
int stack = 1;
int is_enable = luaL_checkint( L, ++stack );
u8g2_SetPowerSave( u8g2, is_enable );
return 0;
}
static const LUA_REG_TYPE lu8g2_display_map[] = {
{ LSTRKEY( "clearBuffer" ), LFUNCVAL( lu8g2_clearBuffer ) },
{ LSTRKEY( "drawBox" ), LFUNCVAL( lu8g2_drawBox ) },
{ LSTRKEY( "drawCircle" ), LFUNCVAL( lu8g2_drawCircle ) },
{ LSTRKEY( "drawDisc" ), LFUNCVAL( lu8g2_drawDisc ) },
{ LSTRKEY( "drawEllipse" ), LFUNCVAL( lu8g2_drawEllipse ) },
{ LSTRKEY( "drawFilledEllipse" ), LFUNCVAL( lu8g2_drawFilledEllipse ) },
{ LSTRKEY( "drawFrame" ), LFUNCVAL( lu8g2_drawFrame ) },
{ LSTRKEY( "drawGlyph" ), LFUNCVAL( lu8g2_drawGlyph ) },
{ LSTRKEY( "drawHLine" ), LFUNCVAL( lu8g2_drawHLine ) },
{ LSTRKEY( "drawLine" ), LFUNCVAL( lu8g2_drawLine ) },
{ LSTRKEY( "drawPixel" ), LFUNCVAL( lu8g2_drawPixel ) },
{ LSTRKEY( "drawRBox" ), LFUNCVAL( lu8g2_drawRBox ) },
{ LSTRKEY( "drawRFrame" ), LFUNCVAL( lu8g2_drawRFrame ) },
{ LSTRKEY( "drawStr" ), LFUNCVAL( lu8g2_drawStr ) },
{ LSTRKEY( "drawTriangle" ), LFUNCVAL( lu8g2_drawTriangle ) },
{ LSTRKEY( "drawUTF8" ), LFUNCVAL( lu8g2_drawUTF8 ) },
{ LSTRKEY( "drawVLine" ), LFUNCVAL( lu8g2_drawVLine ) },
{ LSTRKEY( "drawXBM" ), LFUNCVAL( lu8g2_drawXBM ) },
{ LSTRKEY( "getAscent" ), LFUNCVAL( lu8g2_getAscent ) },
{ LSTRKEY( "getDescent" ), LFUNCVAL( lu8g2_getDescent ) },
{ LSTRKEY( "getStrWidth" ), LFUNCVAL( lu8g2_getStrWidth ) },
{ LSTRKEY( "getUTF8Width" ), LFUNCVAL( lu8g2_getUTF8Width ) },
{ LSTRKEY( "sendBuffer" ), LFUNCVAL( lu8g2_sendBuffer ) },
{ LSTRKEY( "setBitmapMode" ), LFUNCVAL( lu8g2_setBitmapMode ) },
{ LSTRKEY( "setContrast" ), LFUNCVAL( lu8g2_setContrast ) },
{ LSTRKEY( "setDisplayRotation" ), LFUNCVAL( lu8g2_setDisplayRotation ) },
{ LSTRKEY( "setDrawColor" ), LFUNCVAL( lu8g2_setDrawColor ) },
{ LSTRKEY( "setFlipMode" ), LFUNCVAL( lu8g2_setFlipMode ) },
{ LSTRKEY( "setFont" ), LFUNCVAL( lu8g2_setFont ) },
{ LSTRKEY( "setFontDirection" ), LFUNCVAL( lu8g2_setFontDirection ) },
{ LSTRKEY( "setFontMode" ), LFUNCVAL( lu8g2_setFontMode ) },
{ LSTRKEY( "setFontPosBaseline" ), LFUNCVAL( lu8g2_setFontPosBaseline ) },
{ LSTRKEY( "setFontPosBottom" ), LFUNCVAL( lu8g2_setFontPosBottom ) },
{ LSTRKEY( "setFontPosTop" ), LFUNCVAL( lu8g2_setFontPosTop ) },
{ LSTRKEY( "setFontPosCenter" ), LFUNCVAL( lu8g2_setFontPosCenter ) },
{ LSTRKEY( "setFontRefHeightAll" ), LFUNCVAL( lu8g2_setFontRefHeightAll ) },
{ LSTRKEY( "setFontRefHeightExtendedText" ), LFUNCVAL( lu8g2_setFontRefHeightExtendedText ) },
{ LSTRKEY( "setFontRefHeightText" ), LFUNCVAL( lu8g2_setFontRefHeightText ) },
{ LSTRKEY( "setPowerSave" ), LFUNCVAL( lu8g2_setPowerSave ) },
//{ LSTRKEY( "__gc" ), LFUNCVAL( lu8g2_display_free ) },
{ LSTRKEY( "__index" ), LROVAL( lu8g2_display_map ) },
{LNILKEY, LNILVAL}
};
uint8_t u8x8_d_overlay(u8x8_t *u8x8, uint8_t msg, uint8_t arg_int, void *arg_ptr);
typedef void (*display_setup_fn_t)(u8g2_t *u8g2, const u8g2_cb_t *rotation, u8x8_msg_cb byte_cb, u8x8_msg_cb gpio_and_delay_cb);
// ***************************************************************************
// Device constructors
//
// I2C based devices will use this function template to implement the Lua binding.
//
static int ldisplay_i2c( lua_State *L, display_setup_fn_t setup_fn )
{
int stack = 0;
int id = -1;
int i2c_addr = -1;
int rfb_cb_ref = LUA_NOREF;
if (lua_type( L, ++stack) == LUA_TNUMBER) {
/* hardware display connected */
id = luaL_checkint( L, stack );
i2c_addr = luaL_checkint( L, ++stack );
luaL_argcheck( L, i2c_addr >= 0 && i2c_addr <= 0x7f, stack, "invalid i2c address" );
} else
stack--;
if (lua_isfunction( L, ++stack )) {
lua_pushvalue( L, stack );
rfb_cb_ref = luaL_ref( L, LUA_REGISTRYINDEX );
}
if (id < 0 && rfb_cb_ref == LUA_NOREF)
return luaL_error( L, "wrong args" );
u8g2_ud_t *ud = (u8g2_ud_t *)lua_newuserdata( L, sizeof( u8g2_ud_t ) );
u8g2_nodemcu_t *ext_u8g2 = &(ud->u8g2);
ud->font_ref = LUA_NOREF;
ud->host_ref = LUA_NOREF;
/* the i2c driver id is forwarded in the hal member */
ext_u8g2->hal = id >= 0 ? (void *)id : NULL;
u8g2_t *u8g2 = (u8g2_t *)ext_u8g2;
u8x8_t *u8x8 = (u8x8_t *)u8g2;
setup_fn( u8g2, U8G2_R0, u8x8_byte_nodemcu_i2c, u8x8_gpio_and_delay_nodemcu );
/* prepare overlay data */
if (rfb_cb_ref != LUA_NOREF) {
ext_u8g2->overlay.template_display_cb = u8x8->display_cb;
ext_u8g2->overlay.hardware_display_cb = NULL;
ext_u8g2->overlay.rfb_cb_ref = LUA_NOREF;
u8x8->display_cb = u8x8_d_overlay;
}
if (id >= 0) {
/* hardware device specific initialization */
u8x8_SetI2CAddress( u8x8, i2c_addr );
ext_u8g2->overlay.hardware_display_cb = ext_u8g2->overlay.template_display_cb;
}
u8g2_InitDisplay( (u8g2_t *)u8g2 );
u8g2_ClearDisplay( (u8g2_t *)u8g2 );
u8g2_SetPowerSave( (u8g2_t *)u8g2, 0 );
if (rfb_cb_ref != LUA_NOREF) {
/* finally enable rfb display driver */
ext_u8g2->overlay.rfb_cb_ref = rfb_cb_ref;
}
/* set its metatable */
luaL_getmetatable(L, "u8g2.display");
lua_setmetatable(L, -2);
return 1;
}
//
// SPI based devices will use this function template to implement the Lua binding.
//
static int ldisplay_spi( lua_State *L, display_setup_fn_t setup_fn )
{
int stack = 0;
#ifndef ESP_PLATFORM
// ESP8266
typedef struct {
int host;
} lspi_host_t;
lspi_host_t host_elem;
lspi_host_t *host = &host_elem;
#else
// ESP32
lspi_host_t *host = NULL;
#endif
int host_ref = LUA_NOREF;
int cs = -1;
int dc = -1;
int res = -1;
int rfb_cb_ref = LUA_NOREF;
int get_spi_pins;
if (lua_type( L, ++stack ) == LUA_TUSERDATA) {
host = (lspi_host_t *)luaL_checkudata( L, stack, "spi.master" );
/* reference host object to avoid automatic gc */
lua_pushvalue( L, stack );
host_ref = luaL_ref( L, LUA_REGISTRYINDEX );
get_spi_pins = 1;
} else if (lua_type( L, stack ) == LUA_TNUMBER) {
host->host = luaL_checkint( L, stack );
get_spi_pins = 1;
} else {
get_spi_pins = 0;
stack--;
}
if (get_spi_pins) {
cs = luaL_checkint( L, ++stack );
dc = luaL_checkint( L, ++stack );
res = luaL_optint( L, ++stack, -1 );
}
if (lua_isfunction( L, ++stack )) {
lua_pushvalue( L, stack );
rfb_cb_ref = luaL_ref( L, LUA_REGISTRYINDEX );
}
if (!host && rfb_cb_ref == LUA_NOREF)
return luaL_error( L, "wrong args" );
u8g2_ud_t *ud = (u8g2_ud_t *)lua_newuserdata( L, sizeof( u8g2_ud_t ) );
u8g2_nodemcu_t *ext_u8g2 = &(ud->u8g2);
ud->font_ref = LUA_NOREF;
ud->host_ref = host_ref;
/* the spi host id is forwarded in the hal member */
ext_u8g2->hal = host ? (void *)(host->host) : NULL;
u8g2_t *u8g2 = (u8g2_t *)ext_u8g2;
u8x8_t *u8x8 = (u8x8_t *)u8g2;
setup_fn( u8g2, U8G2_R0, u8x8_byte_nodemcu_spi, u8x8_gpio_and_delay_nodemcu );
/* prepare overlay data */
if (rfb_cb_ref != LUA_NOREF) {
ext_u8g2->overlay.template_display_cb = u8x8->display_cb;
ext_u8g2->overlay.hardware_display_cb = NULL;
ext_u8g2->overlay.rfb_cb_ref = LUA_NOREF;
u8x8->display_cb = u8x8_d_overlay;
}
if (host) {
/* hardware specific device initialization */
u8x8_SetPin( u8x8, U8X8_PIN_CS, cs );
u8x8_SetPin( u8x8, U8X8_PIN_DC, dc );
if (res >= 0)
u8x8_SetPin( u8x8, U8X8_PIN_RESET, res );
ext_u8g2->overlay.hardware_display_cb = ext_u8g2->overlay.template_display_cb;
}
u8g2_InitDisplay( (u8g2_t *)u8g2 );
u8g2_ClearDisplay( (u8g2_t *)u8g2 );
u8g2_SetPowerSave( (u8g2_t *)u8g2, 0 );
if (rfb_cb_ref != LUA_NOREF) {
/* finally enable rfb display driver */
ext_u8g2->overlay.rfb_cb_ref = rfb_cb_ref;
}
/* set its metatable */
luaL_getmetatable(L, "u8g2.display");
lua_setmetatable(L, -2);
return 1;
}
//
//
#undef U8G2_DISPLAY_TABLE_ENTRY
#define U8G2_DISPLAY_TABLE_ENTRY(function, binding) \
static int l ## binding( lua_State *L ) \
{ \
return ldisplay_i2c( L, function ); \
}
//
// Unroll the display table and insert binding functions for I2C based displays.
U8G2_DISPLAY_TABLE_I2C
//
//
#undef U8G2_DISPLAY_TABLE_ENTRY
#define U8G2_DISPLAY_TABLE_ENTRY(function, binding) \
static int l ## binding( lua_State *L ) \
{ \
return ldisplay_spi( L, function ); \
}
//
// Unroll the display table and insert binding functions for SPI based displays.
U8G2_DISPLAY_TABLE_SPI
//
#undef U8G2_FONT_TABLE_ENTRY
#undef U8G2_DISPLAY_TABLE_ENTRY
#define U8G2_DISPLAY_TABLE_ENTRY(function, binding) \
{ LSTRKEY( #binding ), LFUNCVAL( l ## binding ) },
static const LUA_REG_TYPE lu8g2_map[] = {
U8G2_DISPLAY_TABLE_I2C
U8G2_DISPLAY_TABLE_SPI
//
// Register fonts
#define U8G2_FONT_TABLE_ENTRY(font) \
{ LSTRKEY( #font ), LUDATA( (void *)(u8g2_ ## font) ) },
U8G2_FONT_TABLE
//
{ LSTRKEY( "DRAW_UPPER_RIGHT" ), LNUMVAL( U8G2_DRAW_UPPER_RIGHT ) },
{ LSTRKEY( "DRAW_UPPER_LEFT" ), LNUMVAL( U8G2_DRAW_UPPER_LEFT ) },
{ LSTRKEY( "DRAW_LOWER_RIGHT" ), LNUMVAL( U8G2_DRAW_LOWER_RIGHT ) },
{ LSTRKEY( "DRAW_LOWER_LEFT" ), LNUMVAL( U8G2_DRAW_LOWER_LEFT ) },
{ LSTRKEY( "DRAW_ALL" ), LNUMVAL( U8G2_DRAW_ALL ) },
{ LSTRKEY( "R0" ), LUDATA( (void *)U8G2_R0 ) },
{ LSTRKEY( "R1" ), LUDATA( (void *)U8G2_R1 ) },
{ LSTRKEY( "R2" ), LUDATA( (void *)U8G2_R2 ) },
{ LSTRKEY( "R3" ), LUDATA( (void *)U8G2_R3 ) },
{ LSTRKEY( "MIRROR" ), LUDATA( (void *)U8G2_MIRROR ) },
{LNILKEY, LNILVAL}
};
int luaopen_u8g2( lua_State *L ) {
luaL_rometatable(L, "u8g2.display", (void *)lu8g2_display_map);
return 0;
}
NODEMCU_MODULE(U8G2, "u8g2", lu8g2_map, luaopen_u8g2);
#endif /* defined(LUA_USE_MODULES_U8G2) || defined(ESP_PLATFORM) */
/*
Functions for integrating U8glib into the nodemcu platform.
*/
#include "lauxlib.h"
#include "platform.h"
#include "c_stdlib.h"
#include "u8g.h"
#include "u8g_glue.h"
// ------------------------------------------------------------
// comm functions
//
#define I2C_CMD_MODE 0x000
#define I2C_DATA_MODE 0x040
#define ESP_I2C_ID 0
static uint8_t do_i2c_start(uint8_t id, uint8_t sla)
{
platform_i2c_send_start( id );
// ignore return value -> tolerate missing ACK
platform_i2c_send_address( id, sla, PLATFORM_I2C_DIRECTION_TRANSMITTER );
return 1;
}
static uint8_t u8g_com_esp8266_ssd_start_sequence(struct _lu8g_userdata_t *lu8g)
{
/* are we requested to set the a0 state? */
if ( lu8g->u8g.pin_list[U8G_PI_SET_A0] == 0 )
return 1;
/* setup bus, might be a repeated start */
if ( do_i2c_start( ESP_I2C_ID, lu8g->i2c_addr ) == 0 )
return 0;
if ( lu8g->u8g.pin_list[U8G_PI_A0_STATE] == 0 )
{
// ignore return value -> tolerate missing ACK
if ( platform_i2c_send_byte( ESP_I2C_ID, I2C_CMD_MODE ) == 0 )
; //return 0;
}
else
{
platform_i2c_send_byte( ESP_I2C_ID, I2C_DATA_MODE );
}
lu8g->u8g.pin_list[U8G_PI_SET_A0] = 0;
return 1;
}
static void lu8g_digital_write( struct _lu8g_userdata_t *lu8g, uint8_t pin_index, uint8_t value )
{
uint8_t pin;
pin = lu8g->u8g.pin_list[pin_index];
if ( pin != U8G_PIN_NONE )
platform_gpio_write( pin, value );
}
void u8g_Delay(u8g_t *u8g, uint16_t msec)
{
struct _lu8g_userdata_t *lu8g = (struct _lu8g_userdata_t *)u8g;
const uint16_t chunk = 50;
if (lu8g->use_delay == 0)
return;
while (msec > chunk)
{
os_delay_us( chunk*1000 );
msec -= chunk;
}
if (msec > 0)
os_delay_us( msec*1000 );
}
void u8g_MicroDelay(void)
{
os_delay_us( 1 );
}
void u8g_10MicroDelay(void)
{
os_delay_us( 10 );
}
uint8_t u8g_com_esp8266_hw_spi_fn(u8g_t *u8g, uint8_t msg, uint8_t arg_val, void *arg_ptr)
{
struct _lu8g_userdata_t *lu8g = (struct _lu8g_userdata_t *)u8g;
switch(msg)
{
case U8G_COM_MSG_STOP:
break;
case U8G_COM_MSG_INIT:
// we assume that the SPI interface was already initialized
// just care for the /CS and D/C pins
lu8g_digital_write( lu8g, U8G_PI_CS, PLATFORM_GPIO_HIGH );
platform_gpio_mode( lu8g->u8g.pin_list[U8G_PI_CS], PLATFORM_GPIO_OUTPUT, PLATFORM_GPIO_FLOAT );
platform_gpio_mode( lu8g->u8g.pin_list[U8G_PI_A0], PLATFORM_GPIO_OUTPUT, PLATFORM_GPIO_FLOAT );
break;
case U8G_COM_MSG_ADDRESS: /* define cmd (arg_val = 0) or data mode (arg_val = 1) */
lu8g_digital_write( lu8g, U8G_PI_A0, arg_val == 0 ? PLATFORM_GPIO_LOW : PLATFORM_GPIO_HIGH );
break;
case U8G_COM_MSG_CHIP_SELECT:
if (arg_val == 0)
{
/* disable */
lu8g_digital_write( lu8g, U8G_PI_CS, PLATFORM_GPIO_HIGH );
}
else
{
/* enable */
lu8g_digital_write( lu8g, U8G_PI_CS, PLATFORM_GPIO_LOW );
}
break;
case U8G_COM_MSG_RESET:
if ( lu8g->u8g.pin_list[U8G_PI_RESET] != U8G_PIN_NONE )
lu8g_digital_write( lu8g, U8G_PI_RESET, arg_val == 0 ? PLATFORM_GPIO_LOW : PLATFORM_GPIO_HIGH );
break;
case U8G_COM_MSG_WRITE_BYTE:
platform_spi_send( 1, 8, arg_val );
break;
case U8G_COM_MSG_WRITE_SEQ:
case U8G_COM_MSG_WRITE_SEQ_P:
{
register uint8_t *ptr = arg_ptr;
while( arg_val > 0 )
{
platform_spi_send( 1, 8, *ptr++ );
arg_val--;
}
}
break;
}
return 1;
}
uint8_t u8g_com_esp8266_ssd_i2c_fn(u8g_t *u8g, uint8_t msg, uint8_t arg_val, void *arg_ptr)
{
struct _lu8g_userdata_t *lu8g = (struct _lu8g_userdata_t *)u8g;
switch(msg)
{
case U8G_COM_MSG_INIT:
// we assume that the i2c bus was already initialized
//u8g_i2c_init(u8g->pin_list[U8G_PI_I2C_OPTION]);
break;
case U8G_COM_MSG_STOP:
break;
case U8G_COM_MSG_RESET:
/* Currently disabled, but it could be enable. Previous restrictions have been removed */
/* u8g_com_arduino_digital_write(u8g, U8G_PI_RESET, arg_val); */
break;
case U8G_COM_MSG_CHIP_SELECT:
lu8g->u8g.pin_list[U8G_PI_A0_STATE] = 0;
lu8g->u8g.pin_list[U8G_PI_SET_A0] = 1; /* force a0 to set again, also forces start condition */
if ( arg_val == 0 )
{
/* disable chip, send stop condition */
platform_i2c_send_stop( ESP_I2C_ID );
}
else
{
/* enable, do nothing: any byte writing will trigger the i2c start */
}
break;
case U8G_COM_MSG_WRITE_BYTE:
//u8g->pin_list[U8G_PI_SET_A0] = 1;
if ( u8g_com_esp8266_ssd_start_sequence(lu8g) == 0 )
return platform_i2c_send_stop( ESP_I2C_ID ), 0;
// ignore return value -> tolerate missing ACK
if ( platform_i2c_send_byte( ESP_I2C_ID, arg_val) == 0 )
; //return platform_i2c_send_stop( ESP_I2C_ID ), 0;
// platform_i2c_send_stop( ESP_I2C_ID );
break;
case U8G_COM_MSG_WRITE_SEQ:
case U8G_COM_MSG_WRITE_SEQ_P:
//u8g->pin_list[U8G_PI_SET_A0] = 1;
if ( u8g_com_esp8266_ssd_start_sequence(lu8g) == 0 )
return platform_i2c_send_stop( ESP_I2C_ID ), 0;
{
register uint8_t *ptr = arg_ptr;
while( arg_val > 0 )
{
// ignore return value -> tolerate missing ACK
if ( platform_i2c_send_byte( ESP_I2C_ID, *ptr++) == 0 )
; //return platform_i2c_send_stop( ESP_I2C_ID ), 0;
arg_val--;
}
}
// platform_i2c_send_stop( ESP_I2C_ID );
break;
case U8G_COM_MSG_ADDRESS: /* define cmd (arg_val = 0) or data mode (arg_val = 1) */
lu8g->u8g.pin_list[U8G_PI_A0_STATE] = arg_val;
lu8g->u8g.pin_list[U8G_PI_SET_A0] = 1; /* force a0 to set again */
break;
}
return 1;
}
// ***************************************************************************
// Generic framebuffer device and RLE comm driver
//
uint8_t u8g_dev_gen_fb_fn(u8g_t *u8g, u8g_dev_t *dev, uint8_t msg, void *arg)
{
switch(msg)
{
case U8G_DEV_MSG_PAGE_FIRST:
// tell comm driver to start new framebuffer
u8g_SetChipSelect(u8g, dev, 1);
break;
case U8G_DEV_MSG_PAGE_NEXT:
{
u8g_pb_t *pb = (u8g_pb_t *)(dev->dev_mem);
if ( u8g_pb_WriteBuffer(pb, u8g, dev) == 0 )
return 0;
}
break;
}
return u8g_dev_pb8v1_base_fn(u8g, dev, msg, arg);
}
static int bit_at( uint8_t *buf, int line, int x )
{
uint8_t byte = buf[x];
return buf[x] & (1 << line) ? 1 : 0;
}
struct _lu8g_fbrle_item
{
uint8_t start_x;
uint8_t len;
};
struct _lu8g_fbrle_line
{
uint8_t num_valid;
struct _lu8g_fbrle_item items[0];
};
uint8_t u8g_com_esp8266_fbrle_fn(u8g_t *u8g, uint8_t msg, uint8_t arg_val, void *arg_ptr)
{
struct _lu8g_userdata_t *lud = (struct _lu8g_userdata_t *)u8g;
switch(msg)
{
case U8G_COM_MSG_INIT:
// allocate memory -> done
// init buffer
break;
case U8G_COM_MSG_CHIP_SELECT:
if (arg_val == 1) {
// new frame starts
if (lud->cb_ref != LUA_NOREF) {
// fire callback with nil argument
lua_State *L = lua_getstate();
lua_rawgeti( L, LUA_REGISTRYINDEX, lud->cb_ref );
lua_pushnil( L );
lua_call( L, 1, 0 );
}
}
break;
case U8G_COM_MSG_WRITE_SEQ:
case U8G_COM_MSG_WRITE_SEQ_P:
{
uint8_t xwidth = u8g->pin_list[U8G_PI_EN];
size_t fbrle_line_size = sizeof( struct _lu8g_fbrle_line ) + sizeof( struct _lu8g_fbrle_item ) * (xwidth/2);
int num_lines = arg_val / (xwidth/8);
uint8_t *buf = (uint8_t *)arg_ptr;
struct _lu8g_fbrle_line *fbrle_line;
if (!(fbrle_line = (struct _lu8g_fbrle_line *)c_malloc( fbrle_line_size ))) {
break;
}
for (int line = 0; line < num_lines; line++) {
int start_run = -1;
fbrle_line->num_valid = 0;
for (int x = 0; x < xwidth; x++) {
if (bit_at( buf, line, x ) == 0) {
if (start_run >= 0) {
// inside run, end it and enter result
fbrle_line->items[fbrle_line->num_valid].start_x = start_run;
fbrle_line->items[fbrle_line->num_valid++].len = x - start_run;
//NODE_ERR( " line: %d x: %d len: %d\n", line, start_run, x - start_run );
start_run = -1;
}
} else {
if (start_run < 0) {
// outside run, start it
start_run = x;
}
}
if (fbrle_line->num_valid >= xwidth/2) break;
}
// active run?
if (start_run >= 0 && fbrle_line->num_valid < xwidth/2) {
fbrle_line->items[fbrle_line->num_valid].start_x = start_run;
fbrle_line->items[fbrle_line->num_valid++].len = xwidth - start_run;
}
// line done, trigger callback
if (lud->cb_ref != LUA_NOREF) {
lua_State *L = lua_getstate();
lua_rawgeti( L, LUA_REGISTRYINDEX, lud->cb_ref );
lua_pushlstring( L, (const char *)fbrle_line, fbrle_line_size );
lua_call( L, 1, 0 );
}
}
c_free( fbrle_line );
}
break;
}
return 1;
}
#ifndef _U8G_GLUE_H_
#define _U8G_GLUE_H_
#include "u8g.h"
struct _lu8g_userdata_t
{
u8g_t u8g;
uint8_t i2c_addr;
uint8_t use_delay;
int cb_ref;
};
typedef struct _lu8g_userdata_t lu8g_userdata_t;
// shorthand macro for the u8g structure inside the userdata
#define LU8G (&(lud->u8g))
uint8_t u8g_com_esp8266_fbrle_fn(u8g_t *u8g, uint8_t msg, uint8_t arg_val, void *arg_ptr);
uint8_t u8g_dev_gen_fb_fn(u8g_t *u8g, u8g_dev_t *dev, uint8_t msg, void *arg);
#endif
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