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

Merge pull request #1336 from nodemcu/dev

1.5.1 master drop
parents c8037568 2e109686
// Module encoders
#include "module.h"
#include "lauxlib.h"
#include "lmem.h"
#include "c_string.h"
#define BASE64_INVALID '\xff'
#define BASE64_PADDING '='
#define ISBASE64(c) (unbytes64[c] != BASE64_INVALID)
static const uint8 b64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static uint8 *toBase64 ( lua_State* L, const uint8 *msg, size_t *len){
size_t i, n = *len;
if (!n) // handle empty string case
return NULL;
uint8 * q, *out = (uint8 *)luaM_malloc(L, (n + 2) / 3 * 4);
uint8 bytes64[sizeof(b64)];
c_memcpy(bytes64, b64, sizeof(b64)); //Avoid lots of flash unaligned fetches
for (i = 0, q = out; i < n; i += 3) {
int a = msg[i];
int b = (i + 1 < n) ? msg[i + 1] : 0;
int c = (i + 2 < n) ? msg[i + 2] : 0;
*q++ = bytes64[a >> 2];
*q++ = bytes64[((a & 3) << 4) | (b >> 4)];
*q++ = (i + 1 < n) ? bytes64[((b & 15) << 2) | (c >> 6)] : BASE64_PADDING;
*q++ = (i + 2 < n) ? bytes64[(c & 63)] : BASE64_PADDING;
}
*len = q - out;
return out;
}
static uint8 *fromBase64 ( lua_State* L, const uint8 *enc_msg, size_t *len){
int i, n = *len, blocks = (n>>2), pad = 0;
const uint8 *p;
uint8 unbytes64[UCHAR_MAX+1], *msg, *q;
if (!n) // handle empty string case
return NULL;
if (n & 3)
luaL_error (L, "Invalid base64 string");
c_memset(unbytes64, BASE64_INVALID, sizeof(unbytes64));
for (i = 0; i < sizeof(b64)-1; i++) unbytes64[b64[i]] = i; // sequential so no exceptions
if (enc_msg[n-1] == BASE64_PADDING) {
pad = (enc_msg[n-2] != BASE64_PADDING) ? 1 : 2;
blocks--; //exclude padding block
}
for (i = 0; i < n - pad; i++) if (!ISBASE64(enc_msg[i])) luaL_error (L, "Invalid base64 string");
unbytes64[BASE64_PADDING] = 0;
msg = q = (uint8 *) luaM_malloc(L, 1+ (3 * n / 4));
for (i = 0, p = enc_msg; i<blocks; i++) {
uint8 a = unbytes64[*p++];
uint8 b = unbytes64[*p++];
uint8 c = unbytes64[*p++];
uint8 d = unbytes64[*p++];
*q++ = (a << 2) | (b >> 4);
*q++ = (b << 4) | (c >> 2);
*q++ = (c << 6) | d;
}
if (pad) { //now process padding block bytes
uint8 a = unbytes64[*p++];
uint8 b = unbytes64[*p++];
*q++ = (a << 2) | (b >> 4);
if (pad == 1) *q++ = (b << 4) | (unbytes64[*p] >> 2);
}
*len = q - msg;
return msg;
}
static inline uint8 to_hex_nibble(uint8 b) {
return b + ( b < 10 ? '0' : 'a' - 10 );
}
static uint8 *toHex ( lua_State* L, const uint8 *msg, size_t *len){
int i, n = *len;
uint8 *q, *out = (uint8 *)luaM_malloc(L, n * 2);
for (i = 0, q = out; i < n; i++) {
*q++ = to_hex_nibble(msg[i] >> 4);
*q++ = to_hex_nibble(msg[i] & 0xf);
}
*len = 2*n;
return out;
}
static uint8 *fromHex ( lua_State* L, const uint8 *msg, size_t *len){
int i, n = *len;
const uint8 *p;
uint8 b, *q, *out = (uint8 *)luaM_malloc(L, n * 2);
uint8 c;
if (n &1)
luaL_error (L, "Invalid hex string");
for (i = 0, p = msg, q = out; i < n; i++) {
if (*p >= '0' && *p <= '9') {
b = *p++ - '0';
} else if (*p >= 'a' && *p <= 'f') {
b = *p++ - ('a' - 10);
} else if (*p >= 'A' && *p <= 'F') {
b = *p++ - ('A' - 10);
} else {
luaL_error (L, "Invalid hex string");
}
if ((i&1) == 0) {
c = b<<4;
} else {
*q++ = c+ b;
}
}
*len = n>>1;
return out;
}
// All encoder functions are of the form:
// Lua: output_string = encoder.function(input_string)
// Where input string maybe empty, but not nil
// Hence these all call the do_func wrapper
static int do_func (lua_State *L, uint8 * (*conv_func)(lua_State *, const uint8 *, size_t *)) {
size_t l;
const uint8 *input = luaL_checklstring(L, 1, &l);
// luaL_argcheck(L, l>0, 1, "input string empty");
uint8 *output = conv_func(L, input, &l);
if (output) {
lua_pushlstring(L, output, l);
luaM_free(L, output);
} else {
lua_pushstring(L, "");
}
return 1;
}
#define DECLARE_FUNCTION(f) static int encoder_ ## f (lua_State *L) \
{ return do_func(L, f); }
DECLARE_FUNCTION(fromBase64);
DECLARE_FUNCTION(toBase64);
DECLARE_FUNCTION(fromHex);
DECLARE_FUNCTION(toHex);
// Module function map
static const LUA_REG_TYPE encoder_map[] = {
{ LSTRKEY("fromBase64"), LFUNCVAL(encoder_fromBase64) },
{ LSTRKEY("toBase64"), LFUNCVAL(encoder_toBase64) },
{ LSTRKEY("fromHex"), LFUNCVAL(encoder_fromHex) },
{ LSTRKEY("toHex"), LFUNCVAL(encoder_toHex) },
{ LNILKEY, LNILVAL }
};
NODEMCU_MODULE(ENCODER, "encoder", encoder_map, NULL);
......@@ -29,19 +29,27 @@
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Robert Foss <dev@robertfoss.se>
*
* Additions & fixes: Johny Mattsson <jmattsson@dius.com.au>
*/
#include "module.h"
#include "lauxlib.h"
#include "lmem.h"
#include "platform.h"
#include "c_stdlib.h"
#include "c_stdio.h"
#include "c_string.h"
#include "ctype.h"
#include "user_interface.h"
#include "espconn.h"
#include "lwip/tcp.h"
#include "lwip/pbuf.h"
#include "flash_fs.h"
#include "task/task.h"
#define MIN(x, y) (((x) < (y)) ? (x) : (y))
#define LITLEN(strliteral) (sizeof (strliteral) -1)
#define ENDUSER_SETUP_ERR_FATAL (1 << 0)
#define ENDUSER_SETUP_ERR_NONFATAL (1 << 1)
......@@ -69,84 +77,257 @@ static const char dns_body[] = { 0x00, 0x01, 0x00, 0x01,
/* DNS Answer Part |LBL OFFS| | TYPE | | CLASS | | TTL | | RD LEN | */
0xC0, 0x0C, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x78, 0x00, 0x04 };
static const char http_html_filename[] = "index.html";
static const char http_header_200[] = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n";
static const char http_header_404[] = "HTTP/1.1 404 Not Found\r\n";
static const char http_html_backup[] = "<!DOCTYPE html><html><head><meta charset=utf-8><meta name=viewport content='width=380'><title>Connect gadget to you WiFi</title><style media=screen type=text/css>*{margin:0;padding:0}html{height:100%;background:linear-gradient(rgba(196,102,0,.2),rgba(155,89,182,.2)),url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEYAAAA8AgMAAACm+SSwAAAADFBMVEVBR1FFS1VHTlg8Q0zU/YXIAAADVElEQVQ4yy1TTYvTUBQ9GTKiYNoodsCF4MK6U4TZChOhiguFWHyBFzqlLl4hoeNvEBeCrlrhBVKq1EUKLTP+hvi1GyguXqBdiZCBzGqg20K8L3hDQnK55+OeJNguHx6UujYl3dL5ALn4JOIUluAqeAWciyGaSdvngOWzNT+G0UyGUOxVOAdqkjXDCbBiUyjZ5QzYEbGadYAi6kHxth+kthXNVNCDofwhGv1D4QGGiM9iAjbCHgr2iUUpDJbs+VPQ4xAr2fX7KXbkOJMdok965Ksb+6lrjdkem8AshIuHm9Nyu19uTunYlOXDTQqi8VgeH0kBXH2xq/ouiMZPzuMukymutrBmulUTovC6HqNFW2ZOiqlpSXZOTvSUeUPxChjxol8BLbRy4gJuhV7OR4LRVBs3WQ9VVAU7SXgK2HeUrOj7bC8YsUgr3lEV/TXB7hK90EBnxaeg1Ov15bY80M736ekCGesGAaGvG0Ct4WRkVQVHIgIM9xJgvSFfPay8Q6GNv7VpR7xUnkvhnMQCJDYkYOtNLihV70tCU1Sk+BQrpoP+HLHUrJkuta40C6LP5GvBv+Hqo10ATxxFrTPvNdPr7XwgQud6RvQN/sXjBGzqbU27wcj9cgsyvSTrpyXV8gKpXeNJU3aFl7MOdldzV4+HfO19jBa5f2IjWwx1OLHIvFHkqbBj20ro1g7nDfY1DpScvDRUNARgjMMVO0zoMjKxJ6uWCPP+YRAWbGoaN8kXYHmLjB9FXLGOazfFVCvOgqzfnicNPrHtPKlex2ye824gMza0cTZ2sS2Xm7Qst/UfFw8O6vVtmUKxZy9xFgzMys5cJ5fxZw4y37Ufk1Dsfb8MqOjYxE3ZMWxiDcO0PYUaD2ys+8OW1pbB7/e3sfZeGVCL0Q2aMjjPdm2sxADuejZxHJAd8dO9DSUdA0V8/NggRRanDkBrANn8yHlEQOn/MmwoQfQF7xgmKDnv520bS/pgylP67vf3y2V5sCwfoCEMkZClgOfJAFX9eXefR2RpnmRs4CDVPceaRfoFzCkJVJX27vWZnoqyvmtXU3+dW1EIXIu8Qg5Qta4Zlv7drUCoWe8/8MXzaEwux7ESE9h6qnHj3mIO0/D9RvzfxPmjWiQ1vbeSk4rrHwhAre35EEVaAAAAAElFTkSuQmCC)}body{font-family:arial,verdana}div{position:absolute;margin:auto;top:0;right:0;bottom:0;left:0;width:320px;height:274px}form{width:320px;text-align:center;position:relative}form fieldset{background:#fff;border:0 none;border-radius:5px;box-shadow:0 0 15px 1px rgba(0,0,0,.4);padding:20px 30px;box-sizing:border-box}form input{padding:15px;border:1px solid #ccc;border-radius:3px;margin-bottom:10px;width:100%;box-sizing:border-box;font-family:montserrat;color:#2C3E50;font-size:13px}form .action-button{width:100px;background:#27AE60;font-weight:700;color:#fff;border:0 none;border-radius:3px;cursor:pointer;padding:10px 5px;margin:10px 5px}#msform .action-button:focus,form .action-button:hover{box-shadow:0 0 0 2px #fff,0 0 0 3px #27AE60}.fs-title{font-size:15px;text-transform:uppercase;color:#2C3E50;margin-bottom:10px}.fs-subtitle{font-weight:400;font-size:13px;color:#666;margin-bottom:20px}</style><body><div><form method='post'><fieldset><h2 class=fs-title>WiFi Login</h2><h3 class=fs-subtitle>Connect gadget to your WiFi</h3><input autocorrect=off autocapitalize=none name=wifi_ssid placeholder='WiFi Name'> <input type=password name=wifi_password placeholder='Password'1> <input type=submit name=save class='submit action-button' value='Save'></fieldset></form></div>";
static const char http_html_filename[] = "enduser_setup.html";
static const char http_header_200[] = "HTTP/1.1 200 OK\r\nCache-control:no-cache\r\nContent-Type: text/html\r\n"; /* Note single \r\n here! */
static const char http_header_204[] = "HTTP/1.1 204 No Content\r\n\r\n";
static const char http_header_302[] = "HTTP/1.1 302 Moved\r\nLocation: /\r\n\r\n";
static const char http_header_401[] = "HTTP/1.1 401 Bad request\r\n\r\n";
static const char http_header_404[] = "HTTP/1.1 404 Not found\r\n\r\n";
static const char http_header_500[] = "HTTP/1.1 500 Internal Error\r\n\r\n";
/* The below is the un-minified version of the http_html_backup[] string.
* Minified using https://kangax.github.io/html-minifier/
* Note: using method="get" due to iOS not always sending body in same
* packet as the HTTP header, and us thus missing it in that case
*/
#if 0
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<meta name="viewport" content="width=380">
<title>WiFi Login</title>
<style media="screen" type="text/css">
*{margin:0;padding:0}
html{height:100%;background:linear-gradient(rgba(196,102,0,.2),rgba(155,89,182,.2)),url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEYAAAA8AgMAAACm+SSwAAAADFBMVEVBR1FFS1VHTlg8Q0zU/YXIAAADVElEQVQ4yy1TTYvTUBQ9GTKiYNoodsCF4MK6U4TZChOhiguFWHyBFzqlLl4hoeNvEBeCrlrhBVKq1EUKLTP+hvi1GyguXqBdiZCBzGqg20K8L3hDQnK55+OeJNguHx6UujYl3dL5ALn4JOIUluAqeAWciyGaSdvngOWzNT+G0UyGUOxVOAdqkjXDCbBiUyjZ5QzYEbGadYAi6kHxth+kthXNVNCDofwhGv1D4QGGiM9iAjbCHgr2iUUpDJbs+VPQ4xAr2fX7KXbkOJMdok965Ksb+6lrjdkem8AshIuHm9Nyu19uTunYlOXDTQqi8VgeH0kBXH2xq/ouiMZPzuMukymutrBmulUTovC6HqNFW2ZOiqlpSXZOTvSUeUPxChjxol8BLbRy4gJuhV7OR4LRVBs3WQ9VVAU7SXgK2HeUrOj7bC8YsUgr3lEV/TXB7hK90EBnxaeg1Ov15bY80M736ekCGesGAaGvG0Ct4WRkVQVHIgIM9xJgvSFfPay8Q6GNv7VpR7xUnkvhnMQCJDYkYOtNLihV70tCU1Sk+BQrpoP+HLHUrJkuta40C6LP5GvBv+Hqo10ATxxFrTPvNdPr7XwgQud6RvQN/sXjBGzqbU27wcj9cgsyvSTrpyXV8gKpXeNJU3aFl7MOdldzV4+HfO19jBa5f2IjWwx1OLHIvFHkqbBj20ro1g7nDfY1DpScvDRUNARgjMMVO0zoMjKxJ6uWCPP+YRAWbGoaN8kXYHmLjB9FXLGOazfFVCvOgqzfnicNPrHtPKlex2ye824gMza0cTZ2sS2Xm7Qst/UfFw8O6vVtmUKxZy9xFgzMys5cJ5fxZw4y37Ufk1Dsfb8MqOjYxE3ZMWxiDcO0PYUaD2ys+8OW1pbB7/e3sfZeGVCL0Q2aMjjPdm2sxADuejZxHJAd8dO9DSUdA0V8/NggRRanDkBrANn8yHlEQOn/MmwoQfQF7xgmKDnv520bS/pgylP67vf3y2V5sCwfoCEMkZClgOfJAFX9eXefR2RpnmRs4CDVPceaRfoFzCkJVJX27vWZnoqyvmtXU3+dW1EIXIu8Qg5Qta4Zlv7drUCoWe8/8MXzaEwux7ESE9h6qnHj3mIO0/D9RvzfxPmjWiQ1vbeSk4rrHwhAre35EEVaAAAAAElFTkSuQmCC)}
body{font-family:arial,verdana}
div{position:absolute;margin:auto;top:-150px;right:0;bottom:0;left:0;width:320px;height:304px}
form{width:320px;text-align:center;position:relative}
form fieldset{background:#fff;border:0 none;border-radius:5px;box-shadow:0 0 15px 1px rgba(0,0,0,.4);padding:20px 30px;box-sizing:border-box}
form input{padding:15px;border:1px solid #ccc;border-radius:3px;margin-bottom:10px;width:100%;box-sizing:border-box;font-family:montserrat;color:#2C3E50;font-size:13px}
form .action-button{border:0 none;border-radius:3px;cursor:pointer;}
#msform .submit:focus,form .action-button:hover{box-shadow:0 0 0 2px #fff,0 0 0 3px #27AE60;}
#formFrame{display: none;}
#aplist{display: block;}
select{width:100%;margin-bottom: 20px;padding: 10px 5px; border:1px solid #ccc;display:none;}
.fs-title{font-size:15px;text-transform:uppercase;color:#2C3E50;margin-bottom:10px}
.fs-subtitle{font-weight:400;font-size:13px;color:#666;margin-bottom:20px}
.fs-status{font-weight:400;font-size:13px;color:#666;margin-bottom:10px;padding-top:20px; border-top:1px solid #ccc}
.submit{width:100px;background: #27AE60; color: #fff;font-weight:700;margin:10px 5px; padding: 10px 5px; }
</style>
</head>
<body>
<div>
<form id="credentialsForm" method="get" action="/update" target="formFrame">
<fieldset>
<iframe id="formFrame" src="" name="formFrame"></iframe> <!-- Used to submit data, needed to prevent re-direction after submission -->
<h2 class="fs-title">WiFi Login</h2>
<h3 class="fs-subtitle">Connect gadget to your WiFi network</h3>
<input id="wifi_ssid" autocorrect="off" autocapitalize="none" name="wifi_ssid" placeholder="WiFi Name">
<select id="aplist" name="aplist" size="1" disabled>
<option>Scanning for networks...</option>
</select>
<input name="wifi_password" placeholder="Password" type="password">
<input type=submit name=save class="action-button submit" value="Save">
<h3 class="fs-status">Status: <span id="status">Updating...</span></h3>
</fieldset>
<h3 id="dbg"></h3>
</form>
</div>
<script>
function fetch(url, method, callback)
{
var xhr = new XMLHttpRequest();
xhr.onreadystatechange=check_ready;
function check_ready()
{
if (xhr.readyState === 4)
{
callback(xhr.status === 200 ? xhr.responseText : null);
}
}
xhr.open(method, url, true);
xhr.send();
}
function new_status(stat)
{
if (stat)
{
var e = document.getElementById("status");
e.innerHTML = stat;
}
}
function new_status_repeat(stat)
{
new_status(stat);
setTimeout(refresh_status, 750);
}
function new_ap_list(json)
{
if (json)
{
var list = JSON.parse(json);
list.sort(function(a, b){ return b.rssi - a.rssi; });
var ssids = list.map(function(a) { return a.ssid; }).filter(function(item, pos, self) { return self.indexOf(item)==pos; });
var sel = document.getElementById("aplist");
sel.innerHTML = "";
sel.setAttribute("size", Math.max(Math.min(3, list.length), 1));
sel.removeAttribute("disabled");
for (var i = 0; i < ssids.length; ++i)
{
var o = document.createElement("option");
o.innerHTML = ssids[i];
sel.options.add(o);
}
sel.style.display = 'block';
}
}
function new_ap_list_repeat(json)
{
new_ap_list(json);
setTimeout(refresh_ap_list, 3000);
}
function refresh_status()
{
fetch('/status','GET', new_status_repeat);
}
function refresh_ap_list()
{
fetch('/aplist','GET', new_ap_list_repeat);
}
function set_ssid_field() {
var sel = document.getElementById("aplist");
document.getElementById("wifi_ssid").value = sel.value;
}
window.onload = function()
{
refresh_status();
refresh_ap_list();
document.getElementById("aplist").onclick = set_ssid_field;
document.getElementById("aplist").onchange = set_ssid_field;
document.getElementById("credentialsForm").addEventListener("submit", function(){
fetch('/status','GET', new_status);
});
}
</script>
</body>
</html>
#endif
static const char http_html_backup[] =
"<!DOCTYPE html><meta http-equiv=content-type content='text/html; charset=UTF-8'><meta charset=utf-8><meta name=viewport content='width=380'><title>WiFi Login</title><style media=screen type=text/css>*{margin:0;padding:0}html{height:100%;background:linear-gradient(rgba(196,102,0,.2),rgba(155,89,182,.2)),url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEYAAAA8AgMAAACm+SSwAAAADFBMVEVBR1FFS1VHTlg8Q0zU/YXIAAADVElEQVQ4yy1TTYvTUBQ9GTKiYNoodsCF4MK6U4TZChOhiguFWHyBFzqlLl4hoeNvEBeCrlrhBVKq1EUKLTP+hvi1GyguXqBdiZCBzGqg20K8L3hDQnK55+OeJNguHx6UujYl3dL5ALn4JOIUluAqeAWciyGaSdvngOWzNT+G0UyGUOxVOAdqkjXDCbBiUyjZ5QzYEbGadYAi6kHxth+kthXNVNCDofwhGv1D4QGGiM9iAjbCHgr2iUUpDJbs+VPQ4xAr2fX7KXbkOJMdok965Ksb+6lrjdkem8AshIuHm9Nyu19uTunYlOXDTQqi8VgeH0kBXH2xq/ouiMZPzuMukymutrBmulUTovC6HqNFW2ZOiqlpSXZOTvSUeUPxChjxol8BLbRy4gJuhV7OR4LRVBs3WQ9VVAU7SXgK2HeUrOj7bC8YsUgr3lEV/TXB7hK90EBnxaeg1Ov15bY80M736ekCGesGAaGvG0Ct4WRkVQVHIgIM9xJgvSFfPay8Q6GNv7VpR7xUnkvhnMQCJDYkYOtNLihV70tCU1Sk+BQrpoP+HLHUrJkuta40C6LP5GvBv+Hqo10ATxxFrTPvNdPr7XwgQud6RvQN/sXjBGzqbU27wcj9cgsyvSTrpyXV8gKpXeNJU3aFl7MOdldzV4+HfO19jBa5f2IjWwx1OLHIvFHkqbBj20ro1g7nDfY1DpScvDRUNARgjMMVO0zoMjKxJ6uWCPP+YRAWbGoaN8kXYHmLjB9FXLGOazfFVCvOgqzfnicNPrHtPKlex2ye824gMza0cTZ2sS2Xm7Qst/UfFw8O6vVtmUKxZy9xFgzMys5cJ5fxZw4y37Ufk1Dsfb8MqOjYxE3ZMWxiDcO0PYUaD2ys+8OW1pbB7/e3sfZeGVCL0Q2aMjjPdm2sxADuejZxHJAd8dO9DSUdA0V8/NggRRanDkBrANn8yHlEQOn/MmwoQfQF7xgmKDnv520bS/pgylP67vf3y2V5sCwfoCEMkZClgOfJAFX9eXefR2RpnmRs4CDVPceaRfoFzCkJVJX27vWZnoqyvmtXU3+dW1EIXIu8Qg5Qta4Zlv7drUCoWe8/8MXzaEwux7ESE9h6qnHj3mIO0/D9RvzfxPmjWiQ1vbeSk4rrHwhAre35EEVaAAAAAElFTkSuQmCC)}body{font-family:arial,verdana}div{position:absolute;margin:auto;top:-150px;right:0;bottom:0;left:0;width:320px;height:304px}form{width:320px;text-align:center;position:relative}form fieldset{background:#fff;border:0 none;border-radius:5px;box-shadow:0 0 15px 1px rgba(0,0,0,.4);padding:20px 30px;box-sizing:border-box}form input{padding:15px;border:1px solid #ccc;border-radius:3px;margin-bottom:10px;width:100%;box-sizing:border-box;font-family:montserrat;color:#2C3E50;font-size:13px}form .action-button{border:0 none;border-radius:3px;cursor:pointer}#msform .submit:focus,form .action-button:hover{box-shadow:0 0 0 2px #fff,0 0 0 3px #27AE60}#formFrame{display:none}#aplist{display:block}select{width:100%;margin-bottom:20px;padding:10px 5px;border:1px solid #ccc;display:none}.fs-title{font-size:15px;text-transform:uppercase;color:#2C3E50;margin-bottom:10px}.fs-subtitle{font-weight:400;font-size:13px;color:#666;margin-bottom:20px}.fs-status{font-weight:400;font-size:13px;color:#666;margin-bottom:10px;padding-top:20px;border-top:1px solid #ccc}.submit{width:100px;background:#27AE60;color:#fff;font-weight:700;margin:10px 5px;padding:10px 5px}</style><div><form id=credentialsForm action=/update target=formFrame><fieldset><iframe id=formFrame src=''name=formFrame></iframe><h2 class=fs-title>WiFi Login</h2><h3 class=fs-subtitle>Connect gadget to your WiFi network</h3><input id=wifi_ssid autocorrect=off autocapitalize=none name=wifi_ssid placeholder='WiFi Name'><select id=aplist name=aplist size=1 disabled><option>Scanning for networks...</select><input name=wifi_password placeholder=Password type=password> <input type=submit name=save class='action-button submit'value=Save><h3 class=fs-status>Status: <span id=status>Updating...</span></h3></fieldset><h3 id=dbg></h3></form></div><script>function fetch(t,e,n){function s(){4===i.readyState&&n(200===i.status?i.responseText:null)}var i=new XMLHttpRequest;i.onreadystatechange=s,i.open(e,t,!0),i.send()}function new_status(t){if(t){var e=document.getElementById('status');e.innerHTML=t}}function new_status_repeat(t){new_status(t),setTimeout(refresh_status,750)}function new_ap_list(t){if(t){var e=JSON.parse(t);e.sort(function(t,e){return e.rssi-t.rssi});var n=e.map(function(t){return t.ssid}).filter(function(t,e,n){return n.indexOf(t)==e}),s=document.getElementById('aplist');s.innerHTML='',s.setAttribute('size',Math.max(Math.min(3,e.length),1)),s.removeAttribute('disabled');for(var i=0;i<n.length;++i){var a=document.createElement('option');a.innerHTML=n[i],s.options.add(a)}s.style.display='block'}}function new_ap_list_repeat(t){new_ap_list(t),setTimeout(refresh_ap_list,3e3)}function refresh_status(){fetch('/status','GET',new_status_repeat)}function refresh_ap_list(){fetch('/aplist','GET',new_ap_list_repeat)}function set_ssid_field(){var t=document.getElementById('aplist');document.getElementById('wifi_ssid').value=t.value}window.onload=function(){refresh_status(),refresh_ap_list(),document.getElementById('aplist').onclick=set_ssid_field,document.getElementById('aplist').onchange=set_ssid_field,document.getElementById('credentialsForm').addEventListener('submit',function(){fetch('/status','GET',new_status)})}</script>";
typedef struct scan_listener
{
struct tcp_pcb *conn;
struct scan_listener *next;
} scan_listener_t;
typedef struct
{
lua_State *lua_L;
struct espconn *espconn_dns_udp;
struct espconn *espconn_http_tcp;
struct tcp_pcb *http_pcb;
char *http_payload_data;
uint32_t http_payload_len;
os_timer_t check_station_timer;
os_timer_t shutdown_timer;
int lua_connected_cb_ref;
int lua_err_cb_ref;
int lua_dbg_cb_ref;
scan_listener_t *scan_listeners;
} enduser_setup_state_t;
static enduser_setup_state_t *state;
static bool manual = false;
static task_handle_t do_station_cfg_handle;
static int enduser_setup_manual(lua_State* L);
static int enduser_setup_start(lua_State* L);
static int enduser_setup_stop(lua_State* L);
static void enduser_setup_station_start(void);
static void enduser_setup_stop_callback(void *ptr);
static void enduser_setup_station_start(void);
static void enduser_setup_ap_start(void);
static void enduser_setup_ap_stop(void);
static void enduser_setup_check_station(void);
static void enduser_setup_debug(lua_State *L, const char *str);
static void enduser_setup_check_station(void *p);
static void enduser_setup_debug(int line, const char *str);
#define ENDUSER_SETUP_DEBUG_ENABLE 0
#if ENDUSER_SETUP_DEBUG_ENABLE
#define ENDUSER_SETUP_DEBUG(l, str) enduser_setup_debug(l, str)
#define ENDUSER_SETUP_DEBUG(str) enduser_setup_debug(__LINE__, str)
#else
#define ENDUSER_SETUP_DEBUG(l, str)
#define ENDUSER_SETUP_DEBUG(str) do {} while(0)
#endif
static void enduser_setup_debug(lua_State *L, const char *str)
#define ENDUSER_SETUP_ERROR(str, err, err_severity) \
do { \
ENDUSER_SETUP_DEBUG(str); \
if (err_severity & ENDUSER_SETUP_ERR_FATAL) enduser_setup_stop(lua_getstate());\
enduser_setup_error(__LINE__, str, err);\
if (!(err_severity & ENDUSER_SETUP_ERR_NO_RETURN)) \
return err; \
} while (0)
#define ENDUSER_SETUP_ERROR_VOID(str, err, err_severity) \
do { \
ENDUSER_SETUP_DEBUG(str); \
if (err_severity & ENDUSER_SETUP_ERR_FATAL) enduser_setup_stop(lua_getstate());\
enduser_setup_error(__LINE__, str, err);\
if (!(err_severity & ENDUSER_SETUP_ERR_NO_RETURN)) \
return; \
} while (0)
static void enduser_setup_debug(int line, const char *str)
{
if(state != NULL && L != NULL && state->lua_dbg_cb_ref != LUA_NOREF)
lua_State *L = lua_getstate();
if(state != NULL && state->lua_dbg_cb_ref != LUA_NOREF)
{
lua_rawgeti(L, LUA_REGISTRYINDEX, state->lua_dbg_cb_ref);
lua_pushstring(L, str);
lua_pushfstring(L, "%d: \t%s", line, str);
lua_call(L, 1, 0);
}
}
#define ENDUSER_SETUP_ERROR(str, err, err_severity) if (err_severity & ENDUSER_SETUP_ERR_FATAL) enduser_setup_stop(state->lua_L);\
enduser_setup_error(state->lua_L, str, err);\
if (!(err_severity & ENDUSER_SETUP_ERR_NO_RETURN)) return err
#define ENDUSER_SETUP_ERROR_VOID(str, err, err_severity) if (err_severity & ENDUSER_SETUP_ERR_FATAL) enduser_setup_stop(state->lua_L);\
enduser_setup_error(state->lua_L, str, err);\
if (!(err_severity & ENDUSER_SETUP_ERR_NO_RETURN)) return
static void enduser_setup_error(lua_State *L, const char *str, int err)
static void enduser_setup_error(int line, const char *str, int err)
{
ENDUSER_SETUP_DEBUG(L, "enduser_setup_error");
ENDUSER_SETUP_DEBUG("enduser_setup_error");
if (state != NULL && L != NULL && state->lua_err_cb_ref != LUA_NOREF)
lua_State *L = lua_getstate();
if (state != NULL && state->lua_err_cb_ref != LUA_NOREF)
{
lua_rawgeti (L, LUA_REGISTRYINDEX, state->lua_err_cb_ref);
lua_pushnumber(L, err);
lua_pushstring(L, str);
lua_pushfstring(L, "%d: \t%s", line, str);
lua_call (L, 2, 0);
}
}
static void enduser_setup_connected_callback(lua_State *L)
static void enduser_setup_connected_callback()
{
ENDUSER_SETUP_DEBUG(L, "enduser_setup_connected_callback");
ENDUSER_SETUP_DEBUG("enduser_setup_connected_callback");
if(state != NULL && L != NULL && state->lua_connected_cb_ref != LUA_NOREF)
lua_State *L = lua_getstate();
if (state != NULL && state->lua_connected_cb_ref != LUA_NOREF)
{
lua_rawgeti(L, LUA_REGISTRYINDEX, state->lua_connected_cb_ref);
lua_call(L, 0, 0);
......@@ -156,8 +337,7 @@ static void enduser_setup_connected_callback(lua_State *L)
static void enduser_setup_check_station_start(void)
{
ENDUSER_SETUP_DEBUG(state->lua_L, "enduser_setup_check_station_start");
ENDUSER_SETUP_DEBUG("enduser_setup_check_station_start");
os_timer_setfn(&(state->check_station_timer), enduser_setup_check_station, NULL);
os_timer_arm(&(state->check_station_timer), 1*1000, TRUE);
......@@ -166,9 +346,12 @@ static void enduser_setup_check_station_start(void)
static void enduser_setup_check_station_stop(void)
{
ENDUSER_SETUP_DEBUG(state->lua_L, "enduser_setup_check_station_stop");
ENDUSER_SETUP_DEBUG("enduser_setup_check_station_stop");
if (state != NULL)
{
os_timer_disarm(&(state->check_station_timer));
}
}
......@@ -177,8 +360,11 @@ static void enduser_setup_check_station_stop(void)
*
* Check that we've successfully entered station mode.
*/
static void enduser_setup_check_station(void)
static void enduser_setup_check_station(void *p)
{
ENDUSER_SETUP_DEBUG("enduser_setup_check_station");
(void)p;
struct ip_info ip;
c_memset(&ip, 0, sizeof(struct ip_info));
......@@ -196,14 +382,77 @@ static void enduser_setup_check_station(void)
return;
}
struct station_config cnf;
wifi_station_get_config(&cnf);
enduser_setup_check_station_stop();
enduser_setup_connected_callback();
enduser_setup_connected_callback(state->lua_L);
enduser_setup_stop(NULL);
/* Trigger shutdown, but allow time for HTTP client to fetch last status. */
if (!manual)
{
os_timer_setfn(&(state->shutdown_timer), enduser_setup_stop_callback, NULL);
os_timer_arm(&(state->shutdown_timer), 10*1000, FALSE);
}
}
/* --- Connection closing handling ----------------------------------------- */
/* It is far more memory efficient to let the other end close the connection
* first and respond to that, than us initiating the closing. The latter
* seems to leave the pcb in a fin_wait state for a long time, which can
* starve us of memory over time.
*
* By instead using the poll function to schedule a hard abort a few seconds
* from now we achieve a deadline close. The downside is a (very) slight
* risk of dropping the connection early, but in this application that's
* hidden by the retries on the JavaScript side anyway.
*/
/* Callback on timeout to hard-close a connection */
static err_t force_abort (void *arg, struct tcp_pcb *pcb)
{
(void)arg;
tcp_poll (pcb, 0, 0);
tcp_abort (pcb);
return ERR_ABRT;
}
/* Callback to detect a remote-close of a connection */
static err_t handle_remote_close (void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err)
{
(void)arg; (void)err;
if (p) /* server sent us data, just ACK and move on */
{
tcp_recved (pcb, p->tot_len);
pbuf_free (p);
}
else /* hey, remote end closed, we can do a soft close safely, yay! */
{
tcp_recv (pcb, 0);
tcp_poll (pcb, 0, 0);
tcp_close (pcb);
}
return ERR_OK;
}
/* Set up a deferred close of a connection, as discussed above. */
static inline void deferred_close (struct tcp_pcb *pcb)
{
tcp_poll (pcb, force_abort, 15); /* ~3sec from now */
tcp_recv (pcb, handle_remote_close);
tcp_sent (pcb, 0);
}
/* Convenience function to queue up a close-after-send. */
static err_t close_once_sent (void *arg, struct tcp_pcb *pcb, u16_t len)
{
(void)arg; (void)len;
deferred_close (pcb);
return ERR_OK;
}
/* ------------------------------------------------------------------------- */
/**
* Search String
*
......@@ -213,25 +462,15 @@ static void enduser_setup_check_station(void)
*/
static int enduser_setup_srch_str(const char *str, const char *srch_str)
{
int srch_str_len = c_strlen(srch_str);
int first_hit = INT_MAX;
int i;
for (i = 0; i < srch_str_len; ++i)
{
char *char_ptr = strchr(str, srch_str[i]);
if (char_ptr == NULL)
char *found = strpbrk (str, srch_str);
if (!found)
{
continue;
}
int char_idx = char_ptr - str;
first_hit = MIN(first_hit, char_idx);
return -1;
}
if (first_hit == INT_MAX)
else
{
return -1;
return found - str;
}
return first_hit;
}
......@@ -244,18 +483,21 @@ static int enduser_setup_srch_str(const char *str, const char *srch_str)
*/
static int enduser_setup_http_load_payload(void)
{
ENDUSER_SETUP_DEBUG(state->lua_L, "enduser_setup_http_load_payload");
ENDUSER_SETUP_DEBUG("enduser_setup_http_load_payload");
int f = fs_open(http_html_filename, fs_mode2flag("r"));
int err = fs_seek(f, 0, FS_SEEK_END);
int file_len = (int) fs_tell(f);
int err2 = fs_seek(f, 0, FS_SEEK_SET);
const char cl_hdr[] = "Content-length:%5d\r\n\r\n";
const size_t cl_len = LITLEN(cl_hdr) + 3; /* room to expand %4d */
if (f == 0 || err == -1 || err2 == -1)
{
ENDUSER_SETUP_DEBUG(state->lua_L, "enduser_setup_http_load_payload unable to load file index.html, loading backup HTML.");
ENDUSER_SETUP_DEBUG("enduser_setup_http_load_payload unable to load file enduser_setup.html, loading backup HTML.");
int payload_len = sizeof(http_header_200) + sizeof(http_html_backup);
int payload_len = LITLEN(http_header_200) + cl_len + LITLEN(http_html_backup);
state->http_payload_len = payload_len;
state->http_payload_data = (char *) c_malloc(payload_len);
if (state->http_payload_data == NULL)
......@@ -264,14 +506,15 @@ static int enduser_setup_http_load_payload(void)
}
int offset = 0;
c_memcpy(&(state->http_payload_data[offset]), &(http_header_200), sizeof(http_header_200));
offset += sizeof(http_header_200);
c_memcpy(&(state->http_payload_data[offset]), &(http_html_backup), sizeof(http_html_backup));
c_memcpy(&(state->http_payload_data[offset]), &(http_header_200), LITLEN(http_header_200));
offset += LITLEN(http_header_200);
offset += c_sprintf(state->http_payload_data + offset, cl_hdr, LITLEN(http_html_backup));
c_memcpy(&(state->http_payload_data[offset]), &(http_html_backup), LITLEN(http_html_backup));
return 1;
}
int payload_len = sizeof(http_header_200) + file_len;
int payload_len = LITLEN(http_header_200) + cl_len + file_len;
state->http_payload_len = payload_len;
state->http_payload_data = (char *) c_malloc(payload_len);
if (state->http_payload_data == NULL)
......@@ -280,8 +523,9 @@ static int enduser_setup_http_load_payload(void)
}
int offset = 0;
c_memcpy(&(state->http_payload_data[offset]), &(http_header_200), sizeof(http_header_200));
offset += sizeof(http_header_200);
c_memcpy(&(state->http_payload_data[offset]), &(http_header_200), LITLEN(http_header_200));
offset += LITLEN(http_header_200);
offset += c_sprintf(state->http_payload_data + offset, cl_hdr, file_len);
fs_read(f, &(state->http_payload_data[offset]), file_len);
return 0;
......@@ -292,12 +536,18 @@ static int enduser_setup_http_load_payload(void)
* De-escape URL data
*
* Parse escaped and form encoded data of request.
*
* @return - return 0 iff the HTTP parameter is decoded into a valid string.
*/
static void enduser_setup_http_urldecode(char *dst, const char *src, int src_len)
static int enduser_setup_http_urldecode(char *dst, const char *src, int src_len, int dst_len)
{
ENDUSER_SETUP_DEBUG("enduser_setup_http_urldecode");
char *dst_start = dst;
char *dst_last = dst + dst_len - 1; /* -1 to reserve space for last \0 */
char a, b;
int i;
for (i = 0; i < src_len && *src; ++i)
for (i = 0; i < src_len && *src && dst < dst_last; ++i)
{
if ((*src == '%') && ((a = src[1]) && (b = src[2])) && (isxdigit(a) && isxdigit(b)))
{
......@@ -338,6 +588,33 @@ static void enduser_setup_http_urldecode(char *dst, const char *src, int src_len
}
}
*dst++ = '\0';
return (i < src_len); /* did we fail to process all the input? */
}
/**
* Task to do the actual station configuration.
* This config *cannot* be done in the network receive callback or serious
* issues like memory corruption occur.
*/
static void do_station_cfg (task_param_t param, uint8_t prio)
{
struct station_config *cnf = (struct station_config *)param;
(void)prio;
/* Best-effort disconnect-reconfig-reconnect. If the device is currently
* connected, the disconnect will work but the connect will report failure
* (though it will actually start connecting). If the devices is not
* connected, the disconnect may fail but the connect will succeed. A
* solid head-in-the-sand approach seems to be the best tradeoff on
* functionality-vs-code-size.
* TODO: maybe use an error callback to at least report if the set config
* call fails.
*/
wifi_station_disconnect ();
wifi_station_set_config (cnf);
wifi_station_connect ();
luaM_free(lua_getstate(), cnf);
}
......@@ -350,62 +627,54 @@ static void enduser_setup_http_urldecode(char *dst, const char *src, int src_len
*/
static int enduser_setup_http_handle_credentials(char *data, unsigned short data_len)
{
ENDUSER_SETUP_DEBUG(state->lua_L, "enduser_setup_http_handle_credentials");
ENDUSER_SETUP_DEBUG("enduser_setup_http_handle_credentials");
char *name_str = (char *) ((uint32_t)strstr(&(data[6]), "wifi_ssid="));
char *pwd_str = (char *) ((uint32_t)strstr(&(data[6]), "wifi_password="));
if (name_str == NULL || pwd_str == NULL)
{
ENDUSER_SETUP_DEBUG("Password or SSID string not found");
return 1;
}
int name_field_len = sizeof("wifi_ssid=") - 1;
int pwd_field_len = sizeof("wifi_password=") - 1;
int name_field_len = LITLEN("wifi_ssid=");
int pwd_field_len = LITLEN("wifi_password=");
char *name_str_start = name_str + name_field_len;
char *pwd_str_start = pwd_str + pwd_field_len;
int name_str_len = enduser_setup_srch_str(name_str_start, "& ");
int pwd_str_len = enduser_setup_srch_str(pwd_str_start, "& ");
if (name_str_len == -1 || pwd_str_len == -1 || name_str_len > 31 || pwd_str_len > 63)
if (name_str_len == -1 || pwd_str_len == -1)
{
ENDUSER_SETUP_DEBUG("Password or SSID HTTP paramter divider not found");
return 1;
}
struct station_config cnf;
c_memset(&cnf, 0, sizeof(struct station_config));
enduser_setup_http_urldecode(cnf.ssid, name_str_start, name_str_len);
enduser_setup_http_urldecode(cnf.password, pwd_str_start, pwd_str_len);
int err = wifi_set_opmode(STATION_MODE | wifi_get_opmode());
if (err == FALSE)
{
wifi_set_opmode(~STATION_MODE & wifi_get_opmode());
ENDUSER_SETUP_ERROR("enduser_setup_station_start failed. wifi_set_opmode failed.", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_FATAL);
}
err = wifi_station_set_config(&cnf);
if (err == FALSE)
{
wifi_set_opmode(~STATION_MODE & wifi_get_opmode());
ENDUSER_SETUP_ERROR("enduser_setup_station_start failed. wifi_station_set_config failed.", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_FATAL);
}
err = wifi_station_disconnect();
if (err == FALSE)
{
ENDUSER_SETUP_ERROR_VOID("enduser_setup_station_start failed. wifi_station_disconnect failed.", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_NONFATAL);
}
err = wifi_station_connect();
if (err == FALSE)
struct station_config *cnf = luaM_malloc(lua_getstate(), sizeof(struct station_config));
c_memset(cnf, 0, sizeof(struct station_config));
int err;
err = enduser_setup_http_urldecode(cnf->ssid, name_str_start, name_str_len, sizeof(cnf->ssid));
err |= enduser_setup_http_urldecode(cnf->password, pwd_str_start, pwd_str_len, sizeof(cnf->password));
if (err != 0)
{
ENDUSER_SETUP_ERROR("enduser_setup_station_start failed. wifi_station_connect failed.\n", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_FATAL);
ENDUSER_SETUP_DEBUG("Unable to decode HTTP parameter to valid password or SSID");
return 1;
}
ENDUSER_SETUP_DEBUG(state->lua_L, "WiFi Credentials Stored");
ENDUSER_SETUP_DEBUG(state->lua_L, "-----------------------");
ENDUSER_SETUP_DEBUG(state->lua_L, "name: ");
ENDUSER_SETUP_DEBUG(state->lua_L, cnf.ssid);
ENDUSER_SETUP_DEBUG(state->lua_L, "pass: ");
ENDUSER_SETUP_DEBUG(state->lua_L, cnf.password);
ENDUSER_SETUP_DEBUG(state->lua_L, "-----------------------");
ENDUSER_SETUP_DEBUG("");
ENDUSER_SETUP_DEBUG("WiFi Credentials Stored");
ENDUSER_SETUP_DEBUG("-----------------------");
ENDUSER_SETUP_DEBUG("name: ");
ENDUSER_SETUP_DEBUG(cnf->ssid);
ENDUSER_SETUP_DEBUG("pass: ");
ENDUSER_SETUP_DEBUG(cnf->password);
ENDUSER_SETUP_DEBUG("-----------------------");
ENDUSER_SETUP_DEBUG("");
task_post_medium(do_station_cfg_handle, (task_param_t) cnf);
return 0;
}
......@@ -416,25 +685,58 @@ static int enduser_setup_http_handle_credentials(char *data, unsigned short data
*
* @return - return 0 iff html was served successfully
*/
static int enduser_setup_http_serve_header(struct espconn *http_client, char *header, uint32_t header_len)
static int enduser_setup_http_serve_header(struct tcp_pcb *http_client, const char *header, uint32_t header_len)
{
ENDUSER_SETUP_DEBUG(state->lua_L, "enduser_setup_http_serve_404");
ENDUSER_SETUP_DEBUG("enduser_setup_http_serve_header");
int8_t err = espconn_sent(http_client, header, header_len);
if (err == ESPCONN_MEM)
err_t err = tcp_write (http_client, header, header_len, TCP_WRITE_FLAG_COPY);
if (err != ERR_OK)
{
ENDUSER_SETUP_ERROR("enduser_setup_http_serve_header failed. espconn_send out of memory", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_NONFATAL);
deferred_close (http_client);
ENDUSER_SETUP_ERROR("http_serve_header failed on tcp_write", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_NONFATAL);
}
else if (err == ESPCONN_ARG)
return 0;
}
static err_t streamout_sent (void *arg, struct tcp_pcb *pcb, u16_t len)
{
(void)len;
unsigned offs = (unsigned)arg;
if (!state || !state->http_payload_data)
{
ENDUSER_SETUP_ERROR("enduser_setup_http_serve_header failed. espconn_send can't find network transmission", ENDUSER_SETUP_ERR_CONNECTION_NOT_FOUND, ENDUSER_SETUP_ERR_NONFATAL);
tcp_abort (pcb);
return ERR_ABRT;
}
else if (err != 0)
unsigned wanted_len = state->http_payload_len - offs;
unsigned buf_free = tcp_sndbuf (pcb);
if (buf_free < wanted_len)
wanted_len = buf_free;
/* no-copy write */
err_t err = tcp_write (pcb, state->http_payload_data + offs, wanted_len, 0);
if (err != ERR_OK)
{
ENDUSER_SETUP_ERROR("enduser_setup_http_serve_header failed. espconn_send failed", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_NONFATAL);
ENDUSER_SETUP_DEBUG("streaming out html failed");
tcp_abort (pcb);
return ERR_ABRT;
}
return 0;
offs += wanted_len;
if (offs >= state->http_payload_len)
{
tcp_sent (pcb, 0);
deferred_close (pcb);
}
else
tcp_arg (pcb, (void *)offs);
return ERR_OK;
}
......@@ -443,172 +745,431 @@ static int enduser_setup_http_serve_header(struct espconn *http_client, char *he
*
* @return - return 0 iff html was served successfully
*/
static int enduser_setup_http_serve_html(struct espconn *http_client)
static int enduser_setup_http_serve_html(struct tcp_pcb *http_client)
{
ENDUSER_SETUP_DEBUG(state->lua_L, "enduser_setup_http_serve_html");
ENDUSER_SETUP_DEBUG("enduser_setup_http_serve_html");
if (state->http_payload_data == NULL)
{
enduser_setup_http_load_payload();
}
int8_t err = espconn_sent(http_client, state->http_payload_data, state->http_payload_len);
if (err == ESPCONN_MEM)
unsigned chunklen = tcp_sndbuf (http_client);
tcp_arg (http_client, (void *)chunklen);
tcp_recv (http_client, 0); /* avoid confusion about the tcp_arg */
tcp_sent (http_client, streamout_sent);
/* Begin the no-copy stream-out here */
err_t err = tcp_write (http_client, state->http_payload_data, chunklen, 0);
if (err != 0)
{
ENDUSER_SETUP_ERROR("enduser_setup_http_serve_html failed. espconn_send out of memory", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_NONFATAL);
ENDUSER_SETUP_ERROR("http_serve_html failed. tcp_write failed", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_NONFATAL);
}
else if (err == ESPCONN_ARG)
return 0;
}
static void serve_status(struct tcp_pcb *conn)
{
ENDUSER_SETUP_DEBUG("enduser_setup_serve_status");
const char fmt[] =
"HTTP/1.1 200 OK\r\n"
"Cache-control:no-cache\r\n"
"Connection:close\r\n"
"Content-type:text/plain\r\n"
"Content-length: %d\r\n"
"\r\n"
"%s%s";
const char *state[] =
{
ENDUSER_SETUP_ERROR("enduser_setup_http_serve_html failed. espconn_send can't find network transmission", ENDUSER_SETUP_ERR_CONNECTION_NOT_FOUND, ENDUSER_SETUP_ERR_NONFATAL);
}
else if (err != 0)
"Idle.",
"Connecting to \"%s\".",
"Failed to connect to \"%s\" - Wrong password.",
"Failed to connect to \"%s\" - Network not found.",
"Failed to connect.",
"Connected to \"%s\"."
};
const size_t num_states = sizeof(state)/sizeof(state[0]);
uint8_t curr_state = wifi_station_get_connect_status ();
if (curr_state < num_states)
{
switch (curr_state)
{
ENDUSER_SETUP_ERROR("enduser_setup_http_serve_html failed. espconn_send failed", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_NONFATAL);
case STATION_CONNECTING:
case STATION_WRONG_PASSWORD:
case STATION_NO_AP_FOUND:
case STATION_GOT_IP:
{
const char *s = state[curr_state];
struct station_config config;
wifi_station_get_config(&config);
config.ssid[31] = '\0';
int state_len = c_strlen(s);
int ssid_len = c_strlen(config.ssid);
int status_len = state_len + ssid_len + 1;
char status_buf[status_len];
memset(status_buf, 0, status_len);
status_len = c_sprintf(status_buf, s, config.ssid);
int buf_len = sizeof(fmt) + status_len + 10; //10 = (9+1), 1 byte is '\0' and 9 are reserved for length field
char buf[buf_len];
memset(buf, 0, buf_len);
int output_len = c_sprintf(buf, fmt, status_len, status_buf);
enduser_setup_http_serve_header(conn, buf, output_len);
}
break;
return 0;
/* Handle non-formatted strings */
default:
{
const char *s = state[curr_state];
int status_len = c_strlen(s);
int buf_len = sizeof(fmt) + status_len + 10; //10 = (9+1), 1 byte is '\0' and 9 are reserved for length field
char buf[buf_len];
memset(buf, 0, buf_len);
int output_len = c_sprintf(buf, fmt, status_len, s);
enduser_setup_http_serve_header(conn, buf, output_len);
}
break;
}
}
else
{
enduser_setup_http_serve_header(conn, http_header_500, LITLEN(http_header_500));
}
}
/**
* Disconnect HTTP client
*
* End TCP connection and free up resources.
*/
static void enduser_setup_http_disconnect(struct espconn *espconn)
/* --- WiFi AP scanning support -------------------------------------------- */
static void free_scan_listeners (void)
{
ENDUSER_SETUP_DEBUG(state->lua_L, "enduser_setup_http_disconnect");
//TODO: Construct and maintain os task queue(?) to be able to issue system_os_task with espconn_disconnect.
if (!state || !state->scan_listeners)
{
return;
}
scan_listener_t *l = state->scan_listeners , *next = 0;
while (l)
{
next = l->next;
c_free (l);
l = next;
}
state->scan_listeners = 0;
}
static void enduser_setup_http_recvcb(void *arg, char *data, unsigned short data_len)
static void remove_scan_listener (scan_listener_t *l)
{
ENDUSER_SETUP_DEBUG(state->lua_L, "enduser_setup_http_recvcb");
struct espconn *http_client = (struct espconn *) arg;
int retval;
if (state)
{
scan_listener_t **sl = &state->scan_listeners;
while (*sl)
{
/* Remove any and all references to the closed conn from the scan list */
if (*sl == l)
{
*sl = l->next;
c_free (l);
/* No early exit to guard against multi-entry on list */
}
else
sl = &(*sl)->next;
}
}
}
if (c_strncmp(data, "POST ", 5) == 0)
static char *escape_ssid (char *dst, const char *src)
{
for (int i = 0; i < 32 && src[i]; ++i)
{
retval = enduser_setup_http_handle_credentials(data, data_len);
if (retval == 0)
if (src[i] == '\\' || src[i] == '"')
{
enduser_setup_http_serve_header(http_client, (char *) http_header_200, sizeof(http_header_200));
enduser_setup_http_disconnect(http_client);
return;
*dst++ = '\\';
}
*dst++ = src[i];
}
else if (retval == 2)
return dst;
}
static void notify_scan_listeners (const char *payload, size_t sz)
{
if (!state)
{
ENDUSER_SETUP_ERROR_VOID("enduser_setup_http_recvcb failed. Failed to handle wifi credentials.", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_NONFATAL);
return;
}
if (retval != 1)
for (scan_listener_t *l = state->scan_listeners; l; l = l->next)
{
if (tcp_write (l->conn, payload, sz, TCP_WRITE_FLAG_COPY) != ERR_OK)
{
ENDUSER_SETUP_ERROR_VOID("enduser_setup_http_recvcb failed. Unknown error code.", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_NONFATAL);
ENDUSER_SETUP_DEBUG("failed to send wifi list");
tcp_abort (l->conn);
}
else
tcp_sent (l->conn, close_once_sent); /* TODO: time-out sends? */
l->conn = 0;
}
else if (c_strncmp(data, "GET ", 4) == 0)
{
/* Reject requests that probably aren't relevant to free up resources. */
if (c_strncmp(data, "GET / ", 6) != 0)
free_scan_listeners ();
}
static void on_scan_done (void *arg, STATUS status)
{
if (!state || !state->scan_listeners)
{
ENDUSER_SETUP_DEBUG(state->lua_L, "enduser_setup_http_recvcb received too specific request.");
enduser_setup_http_serve_header(http_client, (char *) http_header_404, sizeof(http_header_404));
enduser_setup_http_disconnect(http_client);
return;
}
retval = enduser_setup_http_serve_html(http_client);
if (retval != 0)
if (status == OK)
{
unsigned num_nets = 0;
for (struct bss_info *wn = arg; wn; wn = wn->next.stqe_next)
{
enduser_setup_http_disconnect(http_client);
ENDUSER_SETUP_ERROR_VOID("enduser_setup_http_recvcb failed. Unable to send HTML.", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_NONFATAL);
++num_nets;
}
const char header_fmt[] =
"HTTP/1.1 200 OK\r\n"
"Connection:close\r\n"
"Cache-control:no-cache\r\n"
"Content-type:application/json\r\n"
"Content-length:%4d\r\n"
"\r\n";
const size_t hdr_sz = sizeof (header_fmt) +1 -1; /* +expand %4d, -\0 */
/* To be able to safely escape a pathological SSID, we need 2*32 bytes */
const size_t max_entry_sz = sizeof("{\"ssid\":\"\",\"rssi\":},") + 2*32 + 6;
const size_t alloc_sz = hdr_sz + num_nets * max_entry_sz + 3;
char *http = os_zalloc (alloc_sz);
if (!http)
{
goto serve_500;
}
else
char *p = http + hdr_sz; /* start body where we know it will be */
/* p[0] will be clobbered when we print the header, so fill it in last */
++p;
for (struct bss_info *wn = arg; wn; wn = wn->next.stqe_next)
{
enduser_setup_http_serve_header(http_client, (char *) http_header_404, sizeof(http_header_404));
enduser_setup_http_disconnect(http_client);
if (wn != arg)
{
*p++ = ',';
}
const char entry_start[] = "{\"ssid\":\"";
strcpy (p, entry_start);
p += sizeof (entry_start) -1;
p = escape_ssid (p, wn->ssid);
const char entry_mid[] = "\",\"rssi\":";
strcpy (p, entry_mid);
p += sizeof (entry_mid) -1;
p += c_sprintf (p, "%d", wn->rssi);
*p++ = '}';
}
*p++ = ']';
size_t body_sz = (p - http) - hdr_sz;
c_sprintf (http, header_fmt, body_sz);
http[hdr_sz] = '['; /* Rewrite the \0 with the correct start of body */
notify_scan_listeners (http, hdr_sz + body_sz);
c_free (http);
return;
}
serve_500:
notify_scan_listeners (http_header_500, LITLEN(http_header_500));
}
/* ---- end WiFi AP scan support ------------------------------------------- */
static void enduser_setup_http_connectcb(void *arg)
static err_t enduser_setup_http_recvcb(void *arg, struct tcp_pcb *http_client, struct pbuf *p, err_t err)
{
ENDUSER_SETUP_DEBUG(state->lua_L, "enduser_setup_http_connectcb");
struct espconn *callback_espconn = (struct espconn *) arg;
ENDUSER_SETUP_DEBUG("enduser_setup_http_recvcb");
int8_t err = 0;
err |= espconn_regist_recvcb(callback_espconn, enduser_setup_http_recvcb);
if (!state || err != ERR_OK)
{
if (!state)
ENDUSER_SETUP_DEBUG("ignoring received data while stopped");
tcp_abort (http_client);
return ERR_ABRT;
}
if (err != 0)
if (!p) /* remote side closed, close our end too */
{
ENDUSER_SETUP_ERROR_VOID("enduser_setup_http_connectcb failed. Callback registration failed.", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_NONFATAL);
ENDUSER_SETUP_DEBUG("connection closed");
scan_listener_t *l = arg; /* if it's waiting for scan, we have a ptr here */
if (l)
remove_scan_listener (l);
deferred_close (http_client);
return ERR_OK;
}
}
char *data = os_zalloc (p->tot_len + 1);
if (!data)
return ERR_MEM;
static int enduser_setup_http_start(void)
{
ENDUSER_SETUP_DEBUG(state->lua_L, "enduser_setup_http_start");
state->espconn_http_tcp = (struct espconn *) c_malloc(sizeof(struct espconn));
if (state->espconn_http_tcp == NULL)
unsigned data_len = pbuf_copy_partial (p, data, p->tot_len, 0);
tcp_recved (http_client, p->tot_len);
pbuf_free (p);
err_t ret = ERR_OK;
if (c_strncmp(data, "GET ", 4) == 0)
{
if (c_strncmp(data + 4, "/ ", 2) == 0)
{
if (enduser_setup_http_serve_html(http_client) != 0)
{
ENDUSER_SETUP_ERROR("http_recvcb failed. Unable to send HTML.", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_NONFATAL);
}
else
{
ENDUSER_SETUP_ERROR("enduser_setup_http_start failed. Memory allocation failed (espconn_http_tcp == NULL).", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_FATAL);
goto free_out; /* streaming now in progress */
}
esp_tcp *esp_tcp_data = (esp_tcp *) c_malloc(sizeof(esp_tcp));
if (esp_tcp_data == NULL)
}
else if (c_strncmp(data + 4, "/aplist ", 8) == 0)
{
scan_listener_t *l = os_malloc (sizeof (scan_listener_t));
if (!l)
{
ENDUSER_SETUP_ERROR("enduser_setup_http_start failed. Memory allocation failed (esp_udp == NULL).", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_FATAL);
ENDUSER_SETUP_ERROR("out of memory", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_NONFATAL);
}
c_memset(state->espconn_http_tcp, 0, sizeof(struct espconn));
c_memset(esp_tcp_data, 0, sizeof(esp_tcp));
state->espconn_http_tcp->proto.tcp = esp_tcp_data;
state->espconn_http_tcp->type = ESPCONN_TCP;
state->espconn_http_tcp->state = ESPCONN_NONE;
esp_tcp_data->local_port = 80;
bool already = (state->scan_listeners != NULL);
int8_t err;
err = espconn_regist_connectcb(state->espconn_http_tcp, enduser_setup_http_connectcb);
if (err != 0)
tcp_arg (http_client, l);
/* TODO: check if also need a tcp_err() cb, or if recv() is enough */
l->conn = http_client;
l->next = state->scan_listeners;
state->scan_listeners = l;
if (!already)
{
if (!wifi_station_scan(NULL, on_scan_done))
{
enduser_setup_http_serve_header(http_client, http_header_500, LITLEN(http_header_500));
deferred_close (l->conn);
l->conn = 0;
free_scan_listeners();
}
}
goto free_out; /* request queued */
}
else if (c_strncmp(data + 4, "/status ", 8) == 0)
{
serve_status(http_client);
}
else if (c_strncmp(data + 4, "/update?", 8) == 0)
{
switch (enduser_setup_http_handle_credentials(data, data_len))
{
case 0:
enduser_setup_http_serve_header(http_client, http_header_302, LITLEN(http_header_302));
break;
case 1:
enduser_setup_http_serve_header(http_client, http_header_401, LITLEN(http_header_401));
break;
default:
ENDUSER_SETUP_ERROR("http_recvcb failed. Failed to handle wifi credentials.", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_NONFATAL);
break;
}
}
else if (c_strncmp(data + 4, "/generate_204 ", 14) == 0)
{
/* Convince Android devices that they have internet access to avoid pesky dialogues. */
enduser_setup_http_serve_header(http_client, http_header_204, LITLEN(http_header_204));
}
else
{
ENDUSER_SETUP_ERROR("enduser_setup_http_start failed. Couldn't add receive callback.", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_FATAL);
ENDUSER_SETUP_DEBUG("serving 404");
ENDUSER_SETUP_DEBUG(data + 4);
enduser_setup_http_serve_header(http_client, http_header_404, LITLEN(http_header_404));
}
}
else /* not GET */
{
enduser_setup_http_serve_header(http_client, http_header_401, LITLEN(http_header_401));
}
err = espconn_accept(state->espconn_http_tcp);
if (err == ESPCONN_ISCONN)
deferred_close (http_client);
free_out:
os_free (data);
return ret;
}
static err_t enduser_setup_http_connectcb(void *arg, struct tcp_pcb *pcb, err_t err)
{
ENDUSER_SETUP_DEBUG("enduser_setup_http_connectcb");
if (!state)
{
ENDUSER_SETUP_ERROR("enduser_setup_http_start failed. Couldn't create connection, already listening for that connection.", ENDUSER_SETUP_ERR_SOCKET_ALREADY_OPEN, ENDUSER_SETUP_ERR_FATAL);
ENDUSER_SETUP_DEBUG("connect callback but no state?!");
tcp_abort (pcb);
return ERR_ABRT;
}
else if (err == ESPCONN_MEM)
tcp_accepted (state->http_pcb);
tcp_recv (pcb, enduser_setup_http_recvcb);
tcp_nagle_disable (pcb);
return ERR_OK;
}
static int enduser_setup_http_start(void)
{
ENDUSER_SETUP_DEBUG("enduser_setup_http_start");
struct tcp_pcb *pcb = tcp_new ();
if (pcb == NULL)
{
ENDUSER_SETUP_ERROR("enduser_setup_http_start failed. Couldn't create connection, out of memory.", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_FATAL);
ENDUSER_SETUP_ERROR("http_start failed. Memory allocation failed (http_pcb == NULL).", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_FATAL);
}
else if (err == ESPCONN_ARG)
if (tcp_bind (pcb, IP_ADDR_ANY, 80) != ERR_OK)
{
ENDUSER_SETUP_ERROR("enduser_setup_http_start failed. Can't find connection from espconn argument", ENDUSER_SETUP_ERR_CONNECTION_NOT_FOUND, ENDUSER_SETUP_ERR_FATAL);
ENDUSER_SETUP_ERROR("http_start bind failed", ENDUSER_SETUP_ERR_SOCKET_ALREADY_OPEN, ENDUSER_SETUP_ERR_FATAL);
}
else if (err != 0)
state->http_pcb = tcp_listen (pcb);
if (!state->http_pcb)
{
ENDUSER_SETUP_ERROR("enduser_setup_http_start failed. Unknown error", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_FATAL);
tcp_abort(pcb); /* original wasn't freed for us */
ENDUSER_SETUP_ERROR("http_start listen failed", ENDUSER_SETUP_ERR_SOCKET_ALREADY_OPEN, ENDUSER_SETUP_ERR_FATAL);
}
tcp_accept (state->http_pcb, enduser_setup_http_connectcb);
/* TODO: check lwip tcp timeouts */
#if 0
err = espconn_regist_time(state->espconn_http_tcp, 2, 0);
if (err == ESPCONN_ARG)
{
ENDUSER_SETUP_ERROR("enduser_setup_http_start failed. Unable to set TCP timeout.", ENDUSER_SETUP_ERR_CONNECTION_NOT_FOUND, ENDUSER_SETUP_ERR_NONFATAL | ENDUSER_SETUP_ERR_NO_RETURN);
ENDUSER_SETUP_ERROR("http_start failed. Unable to set TCP timeout.", ENDUSER_SETUP_ERR_CONNECTION_NOT_FOUND, ENDUSER_SETUP_ERR_NONFATAL | ENDUSER_SETUP_ERR_NO_RETURN);
}
#endif
err = enduser_setup_http_load_payload();
int err = enduser_setup_http_load_payload();
if (err == 1)
{
ENDUSER_SETUP_DEBUG(state->lua_L, "enduser_setup_http_start info. Loaded backup HTML.");
ENDUSER_SETUP_DEBUG("enduser_setup_http_start info. Loaded backup HTML.");
}
else if (err == 2)
{
ENDUSER_SETUP_ERROR("enduser_setup_http_start failed. Unable to allocate memory for HTTP payload.", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_FATAL);
ENDUSER_SETUP_ERROR("http_start failed. Unable to allocate memory for HTTP payload.", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_FATAL);
}
return 0;
......@@ -617,17 +1178,18 @@ static int enduser_setup_http_start(void)
static void enduser_setup_http_stop(void)
{
ENDUSER_SETUP_DEBUG(state->lua_L, "enduser_setup_http_stop");
ENDUSER_SETUP_DEBUG("enduser_setup_http_stop");
if (state != NULL && state->espconn_http_tcp != NULL)
if (state && state->http_pcb)
{
espconn_delete(state->espconn_http_tcp);
tcp_close (state->http_pcb); /* cannot fail for listening sockets */
state->http_pcb = 0;
}
}
static void enduser_setup_ap_stop(void)
{
ENDUSER_SETUP_DEBUG(state->lua_L, "enduser_setup_station_stop");
ENDUSER_SETUP_DEBUG("enduser_setup_station_stop");
wifi_set_opmode(~SOFTAP_MODE & wifi_get_opmode());
}
......@@ -635,7 +1197,7 @@ static void enduser_setup_ap_stop(void)
static void enduser_setup_ap_start(void)
{
ENDUSER_SETUP_DEBUG(state->lua_L, "enduser_setup_ap_start");
ENDUSER_SETUP_DEBUG("enduser_setup_ap_start");
struct softap_config cnf;
c_memset(&(cnf), 0, sizeof(struct softap_config));
......@@ -645,33 +1207,27 @@ static void enduser_setup_ap_start(void)
#endif
char ssid[] = ENDUSER_SETUP_AP_SSID;
int ssid_name_len = c_strlen(ENDUSER_SETUP_AP_SSID);
int ssid_name_len = c_strlen(ssid);
c_memcpy(&(cnf.ssid), ssid, ssid_name_len);
uint8_t mac[6];
wifi_get_macaddr(SOFTAP_IF, mac);
cnf.ssid[ssid_name_len] = '_';
cnf.ssid[ssid_name_len + 1] = (char) (65 + (0x0F & mac[3]));
cnf.ssid[ssid_name_len + 2] = (char) (65 + ((0xF0 & mac[3]) >> 4));
cnf.ssid[ssid_name_len + 3] = (char) (65 + (0x0F & mac[4]));
cnf.ssid[ssid_name_len + 4] = (char) (65 + ((0xF0 & mac[4]) >> 4));
cnf.ssid[ssid_name_len + 5] = (char) (65 + (0x0F & mac[5]));
cnf.ssid[ssid_name_len + 6] = (char) (65 + ((0xF0 & mac[5]) >> 4));
cnf.ssid_len = c_strlen(ssid) + 7;
c_sprintf(cnf.ssid + ssid_name_len + 1, "%02X%02X%02X", mac[3], mac[4], mac[5]);
cnf.ssid_len = ssid_name_len + 7;
cnf.channel = 1;
cnf.authmode = AUTH_OPEN;
cnf.ssid_hidden = 0;
cnf.max_connection = 5;
cnf.beacon_interval = 100;
wifi_set_opmode(STATIONAP_MODE);
wifi_softap_set_config(&cnf);
wifi_set_opmode(SOFTAP_MODE | wifi_get_opmode());
}
static void enduser_setup_dns_recv_callback(void *arg, char *recv_data, unsigned short recv_len)
{
ENDUSER_SETUP_DEBUG(state->lua_L, "enduser_setup_dns_recv_callback.");
ENDUSER_SETUP_DEBUG("enduser_setup_dns_recv_callback.");
struct espconn *callback_espconn = arg;
struct ip_info ip_info;
......@@ -683,20 +1239,20 @@ static void enduser_setup_dns_recv_callback(void *arg, char *recv_data, unsigned
uint8_t if_mode = wifi_get_opmode();
if ((if_mode & SOFTAP_MODE) == 0)
{
ENDUSER_SETUP_ERROR_VOID("enduser_setup_dns_recv_callback failed. Interface mode not supported.", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_FATAL);
ENDUSER_SETUP_ERROR_VOID("dns_recv_callback failed. Interface mode not supported.", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_FATAL);
}
uint8_t if_index = (if_mode == STATION_MODE? STATION_IF : SOFTAP_IF);
if (wifi_get_ip_info(if_index , &ip_info) == false)
{
ENDUSER_SETUP_ERROR_VOID("enduser_setup_dns_recv_callback failed. Unable to get interface IP.", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_FATAL);
ENDUSER_SETUP_ERROR_VOID("dns_recv_callback failed. Unable to get interface IP.", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_FATAL);
}
char *dns_reply = (char *) c_malloc(dns_reply_len);
if (dns_reply == NULL)
{
ENDUSER_SETUP_ERROR_VOID("enduser_setup_dns_recv_callback failed. Failed to allocate memory.", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_NONFATAL);
ENDUSER_SETUP_ERROR_VOID("dns_recv_callback failed. Failed to allocate memory.", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_NONFATAL);
}
uint32_t insert_byte = 0;
......@@ -714,38 +1270,42 @@ static void enduser_setup_dns_recv_callback(void *arg, char *recv_data, unsigned
remot_info *pr = 0;
if (espconn_get_connection_info(callback_espconn, &pr, 0) != ESPCONN_OK)
{
ENDUSER_SETUP_ERROR_VOID("enduser_setup_dns_recv_callback failed. Unable to get IP of UDP sender.", ENDUSER_SETUP_ERR_CONNECTION_NOT_FOUND, ENDUSER_SETUP_ERR_FATAL);
ENDUSER_SETUP_ERROR_VOID("dns_recv_callback failed. Unable to get IP of UDP sender.", ENDUSER_SETUP_ERR_CONNECTION_NOT_FOUND, ENDUSER_SETUP_ERR_FATAL);
}
callback_espconn->proto.udp->remote_port = pr->remote_port;
os_memmove(callback_espconn->proto.udp->remote_ip, pr->remote_ip, 4);
int8_t err;
err = espconn_sent(callback_espconn, dns_reply, dns_reply_len);
err = espconn_send(callback_espconn, dns_reply, dns_reply_len);
c_free(dns_reply);
if (err == ESPCONN_MEM)
{
ENDUSER_SETUP_ERROR_VOID("enduser_setup_dns_recv_callback failed. Failed to allocate memory for send.", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_FATAL);
ENDUSER_SETUP_ERROR_VOID("dns_recv_callback failed. Failed to allocate memory for send.", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_FATAL);
}
else if (err == ESPCONN_ARG)
{
ENDUSER_SETUP_ERROR_VOID("enduser_setup_dns_recv_callback failed. Can't execute transmission.", ENDUSER_SETUP_ERR_CONNECTION_NOT_FOUND, ENDUSER_SETUP_ERR_FATAL);
ENDUSER_SETUP_ERROR_VOID("dns_recv_callback failed. Can't execute transmission.", ENDUSER_SETUP_ERR_CONNECTION_NOT_FOUND, ENDUSER_SETUP_ERR_FATAL);
}
else if (err != 0)
{
ENDUSER_SETUP_ERROR_VOID("enduser_setup_dns_recv_callback failed. espconn_send failed", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_FATAL);
ENDUSER_SETUP_ERROR_VOID("dns_recv_callback failed. espconn_send failed", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_FATAL);
}
}
static void enduser_setup_free(void)
{
ENDUSER_SETUP_DEBUG(state->lua_L, "enduser_setup_free");
ENDUSER_SETUP_DEBUG("enduser_setup_free");
if (state == NULL)
{
return;
}
/* Make sure no running timers are left. */
os_timer_disarm(&(state->check_station_timer));
os_timer_disarm(&(state->shutdown_timer));
if (state->espconn_dns_udp != NULL)
{
if (state->espconn_dns_udp->proto.udp != NULL)
......@@ -755,15 +1315,10 @@ static void enduser_setup_free(void)
c_free(state->espconn_dns_udp);
}
if (state->espconn_http_tcp != NULL)
{
if (state->espconn_http_tcp->proto.tcp != NULL)
{
c_free(state->espconn_http_tcp->proto.tcp);
}
c_free(state->espconn_http_tcp);
}
c_free(state->http_payload_data);
free_scan_listeners ();
c_free(state);
state = NULL;
}
......@@ -771,22 +1326,22 @@ static void enduser_setup_free(void)
static int enduser_setup_dns_start(void)
{
ENDUSER_SETUP_DEBUG(state->lua_L, "enduser_setup_dns_start");
ENDUSER_SETUP_DEBUG("enduser_setup_dns_start");
if (state->espconn_dns_udp != NULL)
{
ENDUSER_SETUP_ERROR("enduser_setup_dns_start failed. Appears to already be started (espconn_dns_udp != NULL).", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_FATAL);
ENDUSER_SETUP_ERROR("dns_start failed. Appears to already be started (espconn_dns_udp != NULL).", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_FATAL);
}
state->espconn_dns_udp = (struct espconn *) c_malloc(sizeof(struct espconn));
if (state->espconn_dns_udp == NULL)
{
ENDUSER_SETUP_ERROR("enduser_setup_dns_start failed. Memory allocation failed (espconn_dns_udp == NULL).", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_FATAL);
ENDUSER_SETUP_ERROR("dns_start failed. Memory allocation failed (espconn_dns_udp == NULL).", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_FATAL);
}
esp_udp *esp_udp_data = (esp_udp *) c_malloc(sizeof(esp_udp));
if (esp_udp_data == NULL)
{
ENDUSER_SETUP_ERROR("enduser_setup_dns_start failed. Memory allocation failed (esp_udp == NULL).", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_FATAL);
ENDUSER_SETUP_ERROR("dns_start failed. Memory allocation failed (esp_udp == NULL).", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_FATAL);
}
c_memset(state->espconn_dns_udp, 0, sizeof(struct espconn));
......@@ -800,21 +1355,21 @@ static int enduser_setup_dns_start(void)
err = espconn_regist_recvcb(state->espconn_dns_udp, enduser_setup_dns_recv_callback);
if (err != 0)
{
ENDUSER_SETUP_ERROR("enduser_setup_dns_start failed. Couldn't add receive callback, unknown error.", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_FATAL);
ENDUSER_SETUP_ERROR("dns_start failed. Couldn't add receive callback, unknown error.", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_FATAL);
}
err = espconn_create(state->espconn_dns_udp);
if (err == ESPCONN_ISCONN)
{
ENDUSER_SETUP_ERROR("enduser_setup_dns_start failed. Couldn't create connection, already listening for that connection.", ENDUSER_SETUP_ERR_SOCKET_ALREADY_OPEN, ENDUSER_SETUP_ERR_FATAL);
ENDUSER_SETUP_ERROR("dns_start failed. Couldn't create connection, already listening for that connection.", ENDUSER_SETUP_ERR_SOCKET_ALREADY_OPEN, ENDUSER_SETUP_ERR_FATAL);
}
else if (err == ESPCONN_MEM)
{
ENDUSER_SETUP_ERROR("enduser_setup_dns_start failed. Couldn't create connection, out of memory.", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_FATAL);
ENDUSER_SETUP_ERROR("dns_start failed. Couldn't create connection, out of memory.", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_FATAL);
}
else if (err != 0)
{
ENDUSER_SETUP_ERROR("enduser_setup_dns_start failed. Couldn't create connection, unknown error.", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_FATAL);
ENDUSER_SETUP_ERROR("dns_start failed. Couldn't create connection, unknown error.", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_FATAL);
}
return 0;
......@@ -823,9 +1378,9 @@ static int enduser_setup_dns_start(void)
static void enduser_setup_dns_stop(void)
{
ENDUSER_SETUP_DEBUG(state->lua_L, "enduser_setup_dns_stop");
ENDUSER_SETUP_DEBUG("enduser_setup_dns_stop");
if (state->espconn_dns_udp != NULL)
if (state != NULL && state->espconn_dns_udp != NULL)
{
espconn_delete(state->espconn_dns_udp);
}
......@@ -834,23 +1389,22 @@ static void enduser_setup_dns_stop(void)
static int enduser_setup_init(lua_State *L)
{
ENDUSER_SETUP_DEBUG(L, "enduser_setup_init");
ENDUSER_SETUP_DEBUG("enduser_setup_init");
if (state != NULL)
{
enduser_setup_error(L, "enduser_setup_init failed. Appears to already be started.", ENDUSER_SETUP_ERR_UNKOWN_ERROR);
ENDUSER_SETUP_ERROR("init failed. Appears to already be started.", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_FATAL);
return ENDUSER_SETUP_ERR_UNKOWN_ERROR;
}
state = (enduser_setup_state_t *) os_malloc(sizeof(enduser_setup_state_t));
state = (enduser_setup_state_t *) os_zalloc(sizeof(enduser_setup_state_t));
if (state == NULL)
{
enduser_setup_error(L, "enduser_setup_init failed. Unable to allocate memory.", ENDUSER_SETUP_ERR_OUT_OF_MEMORY);
ENDUSER_SETUP_ERROR("init failed. Unable to allocate memory.", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_FATAL);
return ENDUSER_SETUP_ERR_OUT_OF_MEMORY;
}
c_memset(state, 0, sizeof(enduser_setup_state_t));
state->lua_L = L;
state->lua_connected_cb_ref = LUA_NOREF;
state->lua_err_cb_ref = LUA_NOREF;
state->lua_dbg_cb_ref = LUA_NOREF;
......@@ -889,39 +1443,73 @@ static int enduser_setup_init(lua_State *L)
}
static int enduser_setup_manual(lua_State *L)
{
if (!lua_isnoneornil (L, 1))
{
manual = lua_toboolean (L, 1);
}
lua_pushboolean (L, manual);
return 1;
}
static int enduser_setup_start(lua_State *L)
{
ENDUSER_SETUP_DEBUG(L, "enduser_setup_start");
ENDUSER_SETUP_DEBUG("enduser_setup_start");
if (!do_station_cfg_handle)
{
do_station_cfg_handle = task_get_id(do_station_cfg);
}
if(enduser_setup_init(L))
{
enduser_setup_stop(L);
return 0;
goto failed;
}
enduser_setup_check_station_start();
if (!manual)
{
enduser_setup_ap_start();
}
if(enduser_setup_dns_start())
{
enduser_setup_stop(L);
return 0;
goto failed;
}
if(enduser_setup_http_start())
{
enduser_setup_stop(L);
return 0;
goto failed;
}
goto out;
failed:
enduser_setup_stop(lua_getstate());
out:
return 0;
}
/**
* A wrapper needed for type-reasons strictness reasons.
*/
static void enduser_setup_stop_callback(void *ptr)
{
enduser_setup_stop(lua_getstate());
}
static int enduser_setup_stop(lua_State* L)
{
enduser_setup_check_station_stop();
ENDUSER_SETUP_DEBUG("enduser_setup_stop");
if (!manual)
{
enduser_setup_ap_stop();
}
enduser_setup_dns_stop();
enduser_setup_http_stop();
enduser_setup_free();
......@@ -931,6 +1519,7 @@ static int enduser_setup_stop(lua_State* L)
static const LUA_REG_TYPE enduser_setup_map[] = {
{ LSTRKEY( "manual" ), LFUNCVAL( enduser_setup_manual )},
{ LSTRKEY( "start" ), LFUNCVAL( enduser_setup_start )},
{ LSTRKEY( "stop" ), LFUNCVAL( enduser_setup_stop )},
{ LNILKEY, LNILVAL}
......
......@@ -20,8 +20,8 @@ static int file_open( lua_State* L )
}
const char *fname = luaL_checklstring( L, 1, &len );
if( len > FS_NAME_MAX_LENGTH )
return luaL_error(L, "filename too long");
luaL_argcheck(L, len < FS_NAME_MAX_LENGTH && c_strlen(fname) == len, 1, "filename invalid");
const char *mode = luaL_optstring(L, 2, "r");
file_fd = fs_open(fname, fs_mode2flag(mode));
......@@ -61,22 +61,7 @@ static int file_format( lua_State* L )
return 0;
}
#if defined(BUILD_WOFS)
// Lua: list()
static int file_list( lua_State* L )
{
uint32_t start = 0;
size_t act_len = 0;
char fsname[ FS_NAME_MAX_LENGTH + 1 ];
lua_newtable( L );
while( FS_FILE_OK == wofs_next(&start, fsname, FS_NAME_MAX_LENGTH, &act_len) ){
lua_pushinteger(L, act_len);
lua_setfield( L, -2, fsname );
}
return 1;
}
#elif defined(BUILD_SPIFFS)
#if defined(BUILD_SPIFFS)
extern spiffs fs;
......@@ -114,13 +99,27 @@ static int file_seek (lua_State *L)
return 1;
}
// Lua: exists(filename)
static int file_exists( lua_State* L )
{
size_t len;
const char *fname = luaL_checklstring( L, 1, &len );
luaL_argcheck(L, len <= FS_NAME_MAX_LENGTH, 1, "filename too long");
spiffs_stat stat;
int rc = SPIFFS_stat(&fs, (char *)fname, &stat);
lua_pushboolean(L, (rc == SPIFFS_OK ? 1 : 0));
return 1;
}
// Lua: remove(filename)
static int file_remove( lua_State* L )
{
size_t len;
const char *fname = luaL_checklstring( L, 1, &len );
if( len > FS_NAME_MAX_LENGTH )
return luaL_error(L, "filename too long");
luaL_argcheck(L, len <= FS_NAME_MAX_LENGTH, 1, "filename too long");
file_close(L);
SPIFFS_remove(&fs, (char *)fname);
return 0;
......@@ -157,12 +156,10 @@ static int file_rename( lua_State* L )
}
const char *oldname = luaL_checklstring( L, 1, &len );
if( len > FS_NAME_MAX_LENGTH )
return luaL_error(L, "filename too long");
luaL_argcheck(L, len <= FS_NAME_MAX_LENGTH, 1, "filename too long");
const char *newname = luaL_checklstring( L, 2, &len );
if( len > FS_NAME_MAX_LENGTH )
return luaL_error(L, "filename too long");
luaL_argcheck(L, len <= FS_NAME_MAX_LENGTH, 2, "filename too long");
if(SPIFFS_OK==myspiffs_rename( oldname, newname )){
lua_pushboolean(L, 1);
......@@ -175,7 +172,7 @@ static int file_rename( lua_State* L )
// Lua: fsinfo()
static int file_fsinfo( lua_State* L )
{
uint32_t total, used;
u32_t total, used;
SPIFFS_info(&fs, &total, &used);
NODE_DBG("total: %d, used:%d\n", total, used);
if(total>0x7FFFFFFF || used>0x7FFFFFFF || used > total)
......@@ -295,6 +292,13 @@ static int file_writeline( lua_State* L )
return 1;
}
static int file_fscfg (lua_State *L)
{
lua_pushinteger (L, fs.cfg.phys_addr);
lua_pushinteger (L, fs.cfg.phys_size);
return 2;
}
// Module function map
static const LUA_REG_TYPE file_map[] = {
{ LSTRKEY( "list" ), LFUNCVAL( file_list ) },
......@@ -305,13 +309,14 @@ static const LUA_REG_TYPE file_map[] = {
{ LSTRKEY( "read" ), LFUNCVAL( file_read ) },
{ LSTRKEY( "readline" ), LFUNCVAL( file_readline ) },
{ LSTRKEY( "format" ), LFUNCVAL( file_format ) },
#if defined(BUILD_SPIFFS) && !defined(BUILD_WOFS)
#if defined(BUILD_SPIFFS)
{ LSTRKEY( "remove" ), LFUNCVAL( file_remove ) },
{ LSTRKEY( "seek" ), LFUNCVAL( file_seek ) },
{ LSTRKEY( "flush" ), LFUNCVAL( file_flush ) },
//{ LSTRKEY( "check" ), LFUNCVAL( file_check ) },
{ LSTRKEY( "rename" ), LFUNCVAL( file_rename ) },
{ LSTRKEY( "fsinfo" ), LFUNCVAL( file_fsinfo ) },
{ LSTRKEY( "fscfg" ), LFUNCVAL( file_fscfg ) },
{ LSTRKEY( "exists" ), LFUNCVAL( file_exists ) },
#endif
{ LNILKEY, LNILVAL }
};
......
......@@ -2,82 +2,101 @@
#include "module.h"
#include "lauxlib.h"
#include "lmem.h"
#include "platform.h"
#include "user_interface.h"
#include "c_types.h"
#include "c_string.h"
#include "gpio.h"
#define PULLUP PLATFORM_GPIO_PULLUP
#define FLOAT PLATFORM_GPIO_FLOAT
#define OUTPUT PLATFORM_GPIO_OUTPUT
#define OPENDRAIN PLATFORM_GPIO_OPENDRAIN
#define INPUT PLATFORM_GPIO_INPUT
#define INTERRUPT PLATFORM_GPIO_INT
#define HIGH PLATFORM_GPIO_HIGH
#define LOW PLATFORM_GPIO_LOW
#ifdef GPIO_INTERRUPT_ENABLE
static int gpio_cb_ref[GPIO_PIN_NUM];
static lua_State* gL = NULL;
void lua_gpio_unref(unsigned pin){
if(gpio_cb_ref[pin] != LUA_NOREF){
if(gL!=NULL)
luaL_unref(gL, LUA_REGISTRYINDEX, gpio_cb_ref[pin]);
}
gpio_cb_ref[pin] = LUA_NOREF;
}
// We also know that the non-level interrupt types are < LOLEVEL, and that
// HILEVEL is > LOLEVEL. Since this is burned into the hardware it is not
// going to change.
#define INTERRUPT_TYPE_IS_LEVEL(x) ((x) >= GPIO_PIN_INTR_LOLEVEL)
void gpio_intr_callback( unsigned pin, unsigned level )
static int gpio_cb_ref[GPIO_PIN_NUM];
// This task is scheduled by the ISR and is used
// to initiate the Lua-land gpio.trig() callback function
// It also re-enables the pin interrupt, so that we get another callback queued
static void gpio_intr_callback_task (task_param_t param, uint8 priority)
{
unsigned pin = param >> 1;
unsigned level = param & 1;
UNUSED(priority);
NODE_DBG("pin:%d, level:%d \n", pin, level);
if(gpio_cb_ref[pin] == LUA_NOREF)
return;
if(!gL)
return;
lua_rawgeti(gL, LUA_REGISTRYINDEX, gpio_cb_ref[pin]);
lua_pushinteger(gL, level);
lua_call(gL, 1, 0);
if(gpio_cb_ref[pin] != LUA_NOREF) {
// GPIO callbacks are run in L0 and inlcude the level as a parameter
lua_State *L = lua_getstate();
NODE_DBG("Calling: %08x\n", gpio_cb_ref[pin]);
//
if (!INTERRUPT_TYPE_IS_LEVEL(pin_int_type[pin])) {
// Edge triggered -- re-enable the interrupt
platform_gpio_intr_init(pin, pin_int_type[pin]);
}
// Do the actual callback
lua_rawgeti(L, LUA_REGISTRYINDEX, gpio_cb_ref[pin]);
lua_pushinteger(L, level);
lua_call(L, 1, 0);
if (INTERRUPT_TYPE_IS_LEVEL(pin_int_type[pin])) {
// Level triggered -- re-enable the callback
platform_gpio_intr_init(pin, pin_int_type[pin]);
}
}
}
// Lua: trig( pin, type, function )
static int lgpio_trig( lua_State* L )
{
unsigned type;
unsigned pin;
size_t sl;
unsigned pin = luaL_checkinteger( L, 1 );
static const char * const opts[] = {"none", "up", "down", "both", "low", "high", NULL};
static const int opts_type[] = {
GPIO_PIN_INTR_DISABLE, GPIO_PIN_INTR_POSEDGE, GPIO_PIN_INTR_NEGEDGE,
GPIO_PIN_INTR_ANYEDGE, GPIO_PIN_INTR_LOLEVEL, GPIO_PIN_INTR_HILEVEL
};
luaL_argcheck(L, platform_gpio_exists(pin) && pin>0, 1, "Invalid interrupt pin");
int old_pin_ref = gpio_cb_ref[pin];
int type = opts_type[luaL_checkoption(L, 2, "none", opts)];
if (type == GPIO_PIN_INTR_DISABLE) {
// "none" clears the callback
gpio_cb_ref[pin] = LUA_NOREF;
pin = luaL_checkinteger( L, 1 );
MOD_CHECK_ID( gpio, pin );
if(pin==0)
return luaL_error( L, "no interrupt for D0" );
const char *str = luaL_checklstring( L, 2, &sl );
if (str == NULL)
return luaL_error( L, "wrong arg type" );
if(sl == 2 && c_strcmp(str, "up") == 0){
type = GPIO_PIN_INTR_POSEDGE;
}else if(sl == 4 && c_strcmp(str, "down") == 0){
type = GPIO_PIN_INTR_NEGEDGE;
}else if(sl == 4 && c_strcmp(str, "both") == 0){
type = GPIO_PIN_INTR_ANYEDGE;
}else if(sl == 3 && c_strcmp(str, "low") == 0){
type = GPIO_PIN_INTR_LOLEVEL;
}else if(sl == 4 && c_strcmp(str, "high") == 0){
type = GPIO_PIN_INTR_HILEVEL;
}else{
type = GPIO_PIN_INTR_DISABLE;
}
} else if (lua_gettop(L)==2 && old_pin_ref != LUA_NOREF) {
// keep the old one if no callback
old_pin_ref = LUA_NOREF;
// luaL_checkanyfunction(L, 3);
if (lua_type(L, 3) == LUA_TFUNCTION || lua_type(L, 3) == LUA_TLIGHTFUNCTION){
lua_pushvalue(L, 3); // copy argument (func) to the top of stack
if(gpio_cb_ref[pin] != LUA_NOREF)
luaL_unref(L, LUA_REGISTRYINDEX, gpio_cb_ref[pin]);
} else if (lua_type(L, 3) == LUA_TFUNCTION || lua_type(L, 3) == LUA_TLIGHTFUNCTION) {
// set up the new callback if present
lua_pushvalue(L, 3);
gpio_cb_ref[pin] = luaL_ref(L, LUA_REGISTRYINDEX);
} else {
// invalid combination, so clear down any old callback and throw an error
if(old_pin_ref != LUA_NOREF) luaL_unref(L, LUA_REGISTRYINDEX, old_pin_ref);
luaL_argcheck(L, 0, 3, "invalid callback type");
}
// unreference any overwritten callback
if(old_pin_ref != LUA_NOREF) luaL_unref(L, LUA_REGISTRYINDEX, old_pin_ref);
NODE_DBG("Pin data: %d %d %08x, %d %d %d, %08x\n",
pin, type, pin_mux[pin], pin_num[pin], pin_func[pin], pin_int_type[pin], gpio_cb_ref[pin]);
platform_gpio_intr_init(pin, type);
return 0;
}
......@@ -86,68 +105,61 @@ static int lgpio_trig( lua_State* L )
// Lua: mode( pin, mode, pullup )
static int lgpio_mode( lua_State* L )
{
unsigned mode, pullup = FLOAT;
unsigned pin;
unsigned pin = luaL_checkinteger( L, 1 );
unsigned mode = luaL_checkinteger( L, 2 );
unsigned pullup = luaL_optinteger( L, 3, FLOAT );
luaL_argcheck(L, platform_gpio_exists(pin) && (mode!=INTERRUPT || pin>0), 1, "Invalid pin");
luaL_argcheck(L, mode==OUTPUT || mode==OPENDRAIN || mode==INPUT
#ifdef GPIO_INTERRUPT_ENABLE
|| mode==INTERRUPT
#endif
, 2, "wrong arg type" );
if(pullup!=FLOAT) pullup = PULLUP;
NODE_DBG("pin,mode,pullup= %d %d %d\n",pin,mode,pullup);
NODE_DBG("Pin data at mode: %d %08x, %d %d %d, %08x\n",
pin, pin_mux[pin], pin_num[pin], pin_func[pin], pin_int_type[pin], gpio_cb_ref[pin]);
pin = luaL_checkinteger( L, 1 );
MOD_CHECK_ID( gpio, pin );
mode = luaL_checkinteger( L, 2 );
if ( mode!=OUTPUT && mode!=INPUT && mode!=INTERRUPT)
return luaL_error( L, "wrong arg type" );
if(pin==0 && mode==INTERRUPT)
return luaL_error( L, "no interrupt for D0" );
if(lua_isnumber(L, 3))
pullup = lua_tointeger( L, 3 );
if(pullup!=FLOAT)
pullup = PULLUP;
#ifdef GPIO_INTERRUPT_ENABLE
gL = L; // save to local gL, for callback function
if (mode!=INTERRUPT){ // disable interrupt
if (mode != INTERRUPT){ // disable interrupt
if(gpio_cb_ref[pin] != LUA_NOREF){
luaL_unref(L, LUA_REGISTRYINDEX, gpio_cb_ref[pin]);
}
gpio_cb_ref[pin] = LUA_NOREF;
}
}
#endif
int r = platform_gpio_mode( pin, mode, pullup );
if( r<0 )
if( platform_gpio_mode( pin, mode, pullup ) < 0 )
return luaL_error( L, "wrong pin num." );
return 0;
}
// Lua: read( pin )
static int lgpio_read( lua_State* L )
{
unsigned pin;
pin = luaL_checkinteger( L, 1 );
unsigned pin = luaL_checkinteger( L, 1 );
MOD_CHECK_ID( gpio, pin );
unsigned level = platform_gpio_read( pin );
lua_pushinteger( L, level );
lua_pushinteger( L, platform_gpio_read( pin ) );
return 1;
}
// Lua: write( pin, level )
static int lgpio_write( lua_State* L )
{
unsigned level;
unsigned pin;
unsigned pin = luaL_checkinteger( L, 1 );
unsigned level = luaL_checkinteger( L, 2 );
pin = luaL_checkinteger( L, 1 );
MOD_CHECK_ID( gpio, pin );
level = luaL_checkinteger( L, 2 );
if ( level!=HIGH && level!=LOW )
return luaL_error( L, "wrong arg type" );
luaL_argcheck(L, level==HIGH || level==LOW, 2, "wrong level type" );
platform_gpio_write(pin, level);
return 0;
}
#define DELAY_TABLE_MAX_LEN 256
#define noInterrupts ets_intr_lock
#define interrupts ets_intr_unlock
#define delayMicroseconds os_delay_us
#define DIRECT_WRITE(pin, level) (GPIO_OUTPUT_SET(GPIO_ID_PIN(pin_num[pin]), level))
// Lua: serout( pin, firstLevel, delay_table, [repeatNum] )
// -- serout( pin, firstLevel, delay_table, [repeatNum] )
// gpio.mode(1,gpio.OUTPUT,gpio.PULLUP)
......@@ -160,61 +172,40 @@ static int lgpio_write( lua_State* L )
// gpio.serout(1,1,{8,18},8) -- serial 30% pwm 38k, lasts 8 cycles
static int lgpio_serout( lua_State* L )
{
unsigned level;
unsigned pin;
unsigned table_len = 0;
unsigned repeat = 0;
int delay_table[DELAY_TABLE_MAX_LEN];
pin = luaL_checkinteger( L, 1 );
MOD_CHECK_ID( gpio, pin );
level = luaL_checkinteger( L, 2 );
if ( level!=HIGH && level!=LOW )
return luaL_error( L, "wrong arg type" );
if( lua_istable( L, 3 ) )
{
table_len = lua_objlen( L, 3 );
if (table_len <= 0 || table_len>DELAY_TABLE_MAX_LEN)
return luaL_error( L, "wrong arg range" );
int i;
for( i = 0; i < table_len; i ++ )
{
unsigned clocks_per_us = system_get_cpu_freq();
unsigned pin = luaL_checkinteger( L, 1 );
unsigned level = luaL_checkinteger( L, 2 );
unsigned repeats = luaL_optint( L, 4, 1 );
unsigned table_len, i, j;
luaL_argcheck(L, platform_gpio_exists(pin), 1, "Invalid pin");
luaL_argcheck(L, level==HIGH || level==LOW, 2, "Wrong arg type" );
luaL_argcheck(L, lua_istable( L, 3 ) &&
((table_len = lua_objlen( L, 3 )<DELAY_TABLE_MAX_LEN)), 3, "Invalid table" );
luaL_argcheck(L, repeats<256, 4, "repeats >= 256" );
uint32 *delay_table = luaM_newvector(L, table_len*repeats, uint32);
for( i = 1; i <= table_len; i++ ) {
lua_rawgeti( L, 3, i + 1 );
delay_table[i] = ( int )luaL_checkinteger( L, -1 );
unsigned delay = (unsigned) luaL_checkinteger( L, -1 );
if (delay > 1000000) return luaL_error( L, "delay %u must be < 1,000,000 us", i );
delay_table[i-1] = delay;
lua_pop( L, 1 );
if( delay_table[i] < 0 || delay_table[i] > 1000000 ) // can not delay more than 1000000 us
return luaL_error( L, "delay must < 1000000 us" );
}
} else {
return luaL_error( L, "wrong arg range" );
}
if(lua_isnumber(L, 4))
repeat = lua_tointeger( L, 4 );
if( repeat < 0 || repeat > DELAY_TABLE_MAX_LEN )
return luaL_error( L, "delay must < 256" );
if(repeat==0)
repeat = 1;
int j;
bool skip_loop = true;
do
{
if(skip_loop){ // skip the first loop.
skip_loop = false;
for( i = 0; i <= repeats; i++ ) {
if (!i) // skip the first loop (presumably this is some form of icache priming??).
continue;
}
for(j=0;j<table_len;j++){
noInterrupts();
// platform_gpio_write(pin, level);
DIRECT_WRITE(pin, level);
interrupts();
for( j = 0;j < table_len; j++ ){
/* Direct Write is a ROM function which already disables interrupts for the atomic bit */
GPIO_OUTPUT_SET(GPIO_ID_PIN(pin_num[pin]), level);
delayMicroseconds(delay_table[j]);
level=!level;
level = level==LOW ? HIGH : LOW;
}
}
repeat--;
} while (repeat>0);
luaM_freearray(L, delay_table, table_len, uint32);
return 0;
}
#undef DELAY_TABLE_MAX_LEN
......@@ -230,6 +221,7 @@ static const LUA_REG_TYPE gpio_map[] = {
{ LSTRKEY( "INT" ), LNUMVAL( INTERRUPT ) },
#endif
{ LSTRKEY( "OUTPUT" ), LNUMVAL( OUTPUT ) },
{ LSTRKEY( "OPENDRAIN" ), LNUMVAL( OPENDRAIN ) },
{ LSTRKEY( "INPUT" ), LNUMVAL( INPUT ) },
{ LSTRKEY( "HIGH" ), LNUMVAL( HIGH ) },
{ LSTRKEY( "LOW" ), LNUMVAL( LOW ) },
......@@ -244,7 +236,7 @@ int luaopen_gpio( lua_State *L ) {
for(i=0;i<GPIO_PIN_NUM;i++){
gpio_cb_ref[i] = LUA_NOREF;
}
platform_gpio_init(gpio_intr_callback);
platform_gpio_init(task_get_id(gpio_intr_callback_task));
#endif
return 0;
}
......
/******************************************************************************
* HTTP module for NodeMCU
* vowstar@gmail.com
* 2015-12-29
*******************************************************************************/
#include "module.h"
#include "lauxlib.h"
#include "platform.h"
#include "cpu_esp8266.h"
#include "httpclient.h"
static int http_callback_registry = LUA_NOREF;
static void http_callback( char * response, int http_status, char * full_response )
{
#if defined(HTTPCLIENT_DEBUG_ON)
c_printf( "http_status=%d\n", http_status );
if ( http_status != HTTP_STATUS_GENERIC_ERROR )
{
if (full_response != NULL) {
c_printf( "strlen(full_response)=%d\n", strlen( full_response ) );
}
c_printf( "response=%s<EOF>\n", response );
}
#endif
if (http_callback_registry != LUA_NOREF)
{
lua_State *L = lua_getstate();
lua_rawgeti(L, LUA_REGISTRYINDEX, http_callback_registry);
lua_pushnumber(L, http_status);
if ( http_status != HTTP_STATUS_GENERIC_ERROR && response)
{
lua_pushstring(L, response);
}
else
{
lua_pushnil(L);
}
lua_call(L, 2, 0); // With 2 arguments and 0 result
luaL_unref(L, LUA_REGISTRYINDEX, http_callback_registry);
http_callback_registry = LUA_NOREF;
}
}
// Lua: http.request( url, method, header, body, function(status, reponse) end )
static int http_lapi_request( lua_State *L )
{
int length;
const char * url = luaL_checklstring(L, 1, &length);
const char * method = luaL_checklstring(L, 2, &length);
const char * headers = NULL;
const char * body = NULL;
// Check parameter
if ((url == NULL) || (method == NULL))
{
return luaL_error( L, "wrong arg type" );
}
if (lua_isstring(L, 3))
{
headers = luaL_checklstring(L, 3, &length);
}
if (lua_isstring(L, 4))
{
body = luaL_checklstring(L, 4, &length);
}
if (lua_type(L, 5) == LUA_TFUNCTION || lua_type(L, 5) == LUA_TLIGHTFUNCTION) {
lua_pushvalue(L, 5); // copy argument (func) to the top of stack
if (http_callback_registry != LUA_NOREF)
luaL_unref(L, LUA_REGISTRYINDEX, http_callback_registry);
http_callback_registry = luaL_ref(L, LUA_REGISTRYINDEX);
}
http_request(url, method, headers, body, http_callback);
return 0;
}
// Lua: http.post( url, header, body, function(status, reponse) end )
static int http_lapi_post( lua_State *L )
{
int length;
const char * url = luaL_checklstring(L, 1, &length);
const char * headers = NULL;
const char * body = NULL;
// Check parameter
if ((url == NULL))
{
return luaL_error( L, "wrong arg type" );
}
if (lua_isstring(L, 2))
{
headers = luaL_checklstring(L, 2, &length);
}
if (lua_isstring(L, 3))
{
body = luaL_checklstring(L, 3, &length);
}
if (lua_type(L, 4) == LUA_TFUNCTION || lua_type(L, 4) == LUA_TLIGHTFUNCTION) {
lua_pushvalue(L, 4); // copy argument (func) to the top of stack
if (http_callback_registry != LUA_NOREF)
luaL_unref(L, LUA_REGISTRYINDEX, http_callback_registry);
http_callback_registry = luaL_ref(L, LUA_REGISTRYINDEX);
}
http_post(url, headers, body, http_callback);
return 0;
}
// Lua: http.put( url, header, body, function(status, reponse) end )
static int http_lapi_put( lua_State *L )
{
int length;
const char * url = luaL_checklstring(L, 1, &length);
const char * headers = NULL;
const char * body = NULL;
// Check parameter
if ((url == NULL))
{
return luaL_error( L, "wrong arg type" );
}
if (lua_isstring(L, 2))
{
headers = luaL_checklstring(L, 2, &length);
}
if (lua_isstring(L, 3))
{
body = luaL_checklstring(L, 3, &length);
}
if (lua_type(L, 4) == LUA_TFUNCTION || lua_type(L, 4) == LUA_TLIGHTFUNCTION) {
lua_pushvalue(L, 4); // copy argument (func) to the top of stack
if (http_callback_registry != LUA_NOREF)
luaL_unref(L, LUA_REGISTRYINDEX, http_callback_registry);
http_callback_registry = luaL_ref(L, LUA_REGISTRYINDEX);
}
http_put(url, headers, body, http_callback);
return 0;
}
// Lua: http.delete( url, header, body, function(status, reponse) end )
static int http_lapi_delete( lua_State *L )
{
int length;
const char * url = luaL_checklstring(L, 1, &length);
const char * headers = NULL;
const char * body = NULL;
// Check parameter
if ((url == NULL))
{
return luaL_error( L, "wrong arg type" );
}
if (lua_isstring(L, 2))
{
headers = luaL_checklstring(L, 2, &length);
}
if (lua_isstring(L, 3))
{
body = luaL_checklstring(L, 3, &length);
}
if (lua_type(L, 4) == LUA_TFUNCTION || lua_type(L, 4) == LUA_TLIGHTFUNCTION) {
lua_pushvalue(L, 4); // copy argument (func) to the top of stack
if (http_callback_registry != LUA_NOREF)
luaL_unref(L, LUA_REGISTRYINDEX, http_callback_registry);
http_callback_registry = luaL_ref(L, LUA_REGISTRYINDEX);
}
http_delete(url, headers, body, http_callback);
return 0;
}
// Lua: http.get( url, header, function(status, reponse) end )
static int http_lapi_get( lua_State *L )
{
int length;
const char * url = luaL_checklstring(L, 1, &length);
const char * headers = NULL;
// Check parameter
if ((url == NULL))
{
return luaL_error( L, "wrong arg type" );
}
if (lua_isstring(L, 2))
{
headers = luaL_checklstring(L, 2, &length);
}
if (lua_type(L, 3) == LUA_TFUNCTION || lua_type(L, 3) == LUA_TLIGHTFUNCTION) {
lua_pushvalue(L, 3); // copy argument (func) to the top of stack
if (http_callback_registry != LUA_NOREF)
luaL_unref(L, LUA_REGISTRYINDEX, http_callback_registry);
http_callback_registry = luaL_ref(L, LUA_REGISTRYINDEX);
}
http_get(url, headers, http_callback);
return 0;
}
// Module function map
static const LUA_REG_TYPE http_map[] = {
{ LSTRKEY( "request" ), LFUNCVAL( http_lapi_request ) },
{ LSTRKEY( "post" ), LFUNCVAL( http_lapi_post ) },
{ LSTRKEY( "put" ), LFUNCVAL( http_lapi_put ) },
{ LSTRKEY( "delete" ), LFUNCVAL( http_lapi_delete ) },
{ LSTRKEY( "get" ), LFUNCVAL( http_lapi_get ) },
{ LSTRKEY( "OK" ), LNUMVAL( 0 ) },
{ LSTRKEY( "ERROR" ), LNUMVAL( HTTP_STATUS_GENERIC_ERROR ) },
{ LNILKEY, LNILVAL }
};
NODEMCU_MODULE(HTTP, "http", http_map, NULL);
......@@ -57,7 +57,12 @@ 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;
......
// Module for access to the nodemcu_mdns functions
#include "module.h"
#include "lauxlib.h"
#include "c_string.h"
#include "c_stdlib.h"
#include "c_types.h"
#include "mem.h"
#include "lwip/ip_addr.h"
#include "nodemcu_mdns.h"
#include "user_interface.h"
//
// mdns.close()
//
static int mdns_close(lua_State *L)
{
nodemcu_mdns_close();
return 0;
}
//
// mdns.register(hostname [, { attributes} ])
//
static int mdns_register(lua_State *L)
{
struct nodemcu_mdns_info info;
memset(&info, 0, sizeof(info));
info.host_name = luaL_checkstring(L, 1);
info.service_name = "http";
info.service_port = 80;
info.host_desc = info.host_name;
if (lua_gettop(L) >= 2) {
luaL_checktype(L, 2, LUA_TTABLE);
lua_pushnil(L); // first key
int slot = 0;
while (lua_next(L, 2) != 0 && slot < sizeof(info.txt_data) / sizeof(info.txt_data[0])) {
luaL_checktype(L, -2, LUA_TSTRING);
const char *key = luaL_checkstring(L, -2);
if (c_strcmp(key, "port") == 0) {
info.service_port = luaL_checknumber(L, -1);
} else if (c_strcmp(key, "service") == 0) {
info.service_name = luaL_checkstring(L, -1);
} else if (c_strcmp(key, "description") == 0) {
info.host_desc = luaL_checkstring(L, -1);
} else {
int len = c_strlen(key) + 1;
const char *value = luaL_checkstring(L, -1);
char *p = alloca(len + c_strlen(value) + 1);
strcpy(p, key);
strcat(p, "=");
strcat(p, value);
info.txt_data[slot++] = p;
}
lua_pop(L, 1);
}
}
struct ip_info ipconfig;
uint8_t mode = wifi_get_opmode();
if (!wifi_get_ip_info((mode == 2) ? SOFTAP_IF : STATION_IF, &ipconfig) || !ipconfig.ip.addr) {
return luaL_error(L, "No network connection");
}
// Close up the old session (if any). This cannot fail
// so no chance of losing the memory in 'result'
mdns_close(L);
// Save the result as it appears that nodemcu_mdns_init needs
// to have the data valid while it is running.
if (!nodemcu_mdns_init(&info)) {
mdns_close(L);
return luaL_error(L, "Unable to start mDns daemon");
}
return 0;
}
// Module function map
static const LUA_REG_TYPE mdns_map[] = {
{ LSTRKEY("register"), LFUNCVAL(mdns_register) },
{ LSTRKEY("close"), LFUNCVAL(mdns_close) },
{ LNILKEY, LNILVAL }
};
NODEMCU_MODULE(MDNS, "mdns", mdns_map, NULL);
......@@ -15,6 +15,8 @@
#include "mqtt_msg.h"
#include "msg_queue.h"
#include "user_interface.h"
#define MQTT_BUF_SIZE 1024
#define MQTT_DEFAULT_KEEPALIVE 60
#define MQTT_MAX_CLIENT_LEN 64
......@@ -53,13 +55,14 @@ typedef struct mqtt_state_t
typedef struct lmqtt_userdata
{
lua_State *L;
struct espconn *pesp_conn;
int self_ref;
int cb_connect_ref;
int cb_connect_fail_ref;
int cb_disconnect_ref;
int cb_message_ref;
int cb_suback_ref;
int cb_unsuback_ref;
int cb_puback_ref;
mqtt_state_t mqtt_state;
mqtt_connect_info_t connect_info;
......@@ -73,9 +76,10 @@ typedef struct lmqtt_userdata
tConnState connState;
}lmqtt_userdata;
static void socket_connect(struct espconn *pesp_conn);
static sint8 socket_connect(struct espconn *pesp_conn);
static void mqtt_socket_reconnected(void *arg, sint8_t err);
static void mqtt_socket_connected(void *arg);
static void mqtt_connack_fail(lmqtt_userdata * mud, int reason_code);
static void mqtt_socket_disconnected(void *arg) // tcp only
{
......@@ -90,11 +94,13 @@ static void mqtt_socket_disconnected(void *arg) // tcp only
os_timer_disarm(&mud->mqttTimer);
lua_State *L = lua_getstate();
if(mud->connected){ // call back only called when socket is from connection to disconnection.
mud->connected = false;
if((mud->L != NULL) && (mud->cb_disconnect_ref != LUA_NOREF) && (mud->self_ref != LUA_NOREF)) {
lua_rawgeti(mud->L, LUA_REGISTRYINDEX, mud->cb_disconnect_ref);
lua_rawgeti(mud->L, LUA_REGISTRYINDEX, mud->self_ref); // pass the userdata(client) to callback func in lua
if((mud->cb_disconnect_ref != LUA_NOREF) && (mud->self_ref != LUA_NOREF)) {
lua_rawgeti(L, LUA_REGISTRYINDEX, mud->cb_disconnect_ref);
lua_rawgeti(L, LUA_REGISTRYINDEX, mud->self_ref); // pass the userdata(client) to callback func in lua
call_back = true;
}
}
......@@ -119,18 +125,12 @@ static void mqtt_socket_disconnected(void *arg) // tcp only
mud->pesp_conn = NULL;
}
if(mud->L == NULL)
return;
lua_gc(mud->L, LUA_GCSTOP, 0);
if(mud->self_ref != LUA_NOREF){ // TODO: should we unref the client and delete it?
luaL_unref(mud->L, LUA_REGISTRYINDEX, mud->self_ref);
luaL_unref(L, LUA_REGISTRYINDEX, mud->self_ref);
mud->self_ref = LUA_NOREF; // unref this, and the mqtt.socket userdata will delete it self
}
lua_gc(mud->L, LUA_GCRESTART, 0);
}
if((mud->L != NULL) && call_back){
lua_call(mud->L, 1, 0);
if(call_back){
lua_call(L, 1, 0);
}
NODE_DBG("leave mqtt_socket_disconnected.\n");
......@@ -149,6 +149,8 @@ static void mqtt_socket_reconnected(void *arg, sint8_t err)
os_timer_disarm(&mud->mqttTimer);
mud->event_timeout = 0; // no need to count anymore
if(mud->mqtt_state.auto_reconnect){
pesp_conn->proto.tcp->remote_port = mud->mqtt_state.port;
pesp_conn->proto.tcp->local_port = espconn_port();
......@@ -176,25 +178,74 @@ static void deliver_publish(lmqtt_userdata * mud, uint8_t* message, int length)
return;
if(mud->self_ref == LUA_NOREF)
return;
if(mud->L == NULL)
return;
lua_State *L = lua_getstate();
if(event_data.topic && (event_data.topic_length > 0)){
lua_rawgeti(mud->L, LUA_REGISTRYINDEX, mud->cb_message_ref);
lua_rawgeti(mud->L, LUA_REGISTRYINDEX, mud->self_ref); // pass the userdata to callback func in lua
lua_pushlstring(mud->L, event_data.topic, event_data.topic_length);
lua_rawgeti(L, LUA_REGISTRYINDEX, mud->cb_message_ref);
lua_rawgeti(L, LUA_REGISTRYINDEX, mud->self_ref); // pass the userdata to callback func in lua
lua_pushlstring(L, event_data.topic, event_data.topic_length);
} else {
NODE_DBG("get wrong packet.\n");
return;
}
if(event_data.data && (event_data.data_length > 0)){
lua_pushlstring(mud->L, event_data.data, event_data.data_length);
lua_call(mud->L, 3, 0);
lua_pushlstring(L, event_data.data, event_data.data_length);
lua_call(L, 3, 0);
} else {
lua_call(mud->L, 2, 0);
lua_call(L, 2, 0);
}
NODE_DBG("leave deliver_publish.\n");
}
static void mqtt_connack_fail(lmqtt_userdata * mud, int reason_code)
{
if(mud->cb_connect_fail_ref == LUA_NOREF || mud->self_ref == LUA_NOREF)
{
return;
}
lua_State *L = lua_getstate();
lua_rawgeti(L, LUA_REGISTRYINDEX, mud->cb_connect_fail_ref);
lua_rawgeti(L, LUA_REGISTRYINDEX, mud->self_ref); // pass the userdata(client) to callback func in lua
lua_pushinteger(L, reason_code);
lua_call(L, 2, 0);
}
static sint8 mqtt_send_if_possible(struct espconn *pesp_conn)
{
if(pesp_conn == NULL)
return ESPCONN_OK;
lmqtt_userdata *mud = (lmqtt_userdata *)pesp_conn->reverse;
if(mud == NULL)
return ESPCONN_OK;
sint8 espconn_status = ESPCONN_OK;
// This indicates if we have sent something and are waiting for something to
// happen
if (mud->event_timeout == 0) {
msg_queue_t *pending_msg = msg_peek(&(mud->mqtt_state.pending_msg_q));
if (pending_msg) {
mud->event_timeout = MQTT_SEND_TIMEOUT;
NODE_DBG("Sent: %d\n", pending_msg->msg.length);
#ifdef CLIENT_SSL_ENABLE
if( mud->secure )
{
espconn_status = espconn_secure_send( pesp_conn, pending_msg->msg.data, pending_msg->msg.length );
}
else
#endif
{
espconn_status = espconn_send( pesp_conn, pending_msg->msg.data, pending_msg->msg.length );
}
mud->keep_alive_tick = 0;
}
}
NODE_DBG("send_if_poss, queue size: %d\n", msg_size(&(mud->mqtt_state.pending_msg_q)));
return espconn_status;
}
static void mqtt_socket_received(void *arg, char *pdata, unsigned short len)
{
NODE_DBG("enter mqtt_socket_received.\n");
......@@ -202,7 +253,6 @@ static void mqtt_socket_received(void *arg, char *pdata, unsigned short len)
uint8_t msg_type;
uint8_t msg_qos;
uint16_t msg_id;
msg_queue_t *node = NULL;
int length = (int)len;
// uint8_t in_buffer[MQTT_BUF_SIZE];
uint8_t *in_buffer = (uint8_t *)pdata;
......@@ -222,9 +272,13 @@ READPACKET:
uint8_t temp_buffer[MQTT_BUF_SIZE];
mqtt_msg_init(&mud->mqtt_state.mqtt_connection, temp_buffer, MQTT_BUF_SIZE);
mqtt_message_t *temp_msg = NULL;
lua_State *L = lua_getstate();
switch(mud->connState){
case MQTT_CONNECT_SENDING:
case MQTT_CONNECT_SENT:
mud->event_timeout = 0;
if(mqtt_get_type(in_buffer) != MQTT_MSG_TYPE_CONNACK){
NODE_DBG("MQTT: Invalid packet\r\n");
mud->connState = MQTT_INIT;
......@@ -238,6 +292,31 @@ READPACKET:
{
espconn_disconnect(pesp_conn);
}
mqtt_connack_fail(mud, MQTT_CONN_FAIL_NOT_A_CONNACK_MSG);
break;
} else if (mqtt_get_connect_ret_code(in_buffer) != MQTT_CONNACK_ACCEPTED) {
NODE_DBG("MQTT: CONNACK REFUSED (CODE: %d)\n", mqtt_get_connect_ret_code(in_buffer));
mud->connState = MQTT_INIT;
#ifdef CLIENT_SSL_ENABLE
if(mud->secure)
{
espconn_secure_disconnect(pesp_conn);
}
else
#endif
{
espconn_disconnect(pesp_conn);
}
mqtt_connack_fail(mud, mqtt_get_connect_ret_code(in_buffer));
break;
} else {
mud->connState = MQTT_DATA;
NODE_DBG("MQTT: Connected\r\n");
......@@ -245,11 +324,9 @@ READPACKET:
break;
if(mud->self_ref == LUA_NOREF)
break;
if(mud->L == NULL)
break;
lua_rawgeti(mud->L, LUA_REGISTRYINDEX, mud->cb_connect_ref);
lua_rawgeti(mud->L, LUA_REGISTRYINDEX, mud->self_ref); // pass the userdata(client) to callback func in lua
lua_call(mud->L, 1, 0);
lua_rawgeti(L, LUA_REGISTRYINDEX, mud->cb_connect_ref);
lua_rawgeti(L, LUA_REGISTRYINDEX, mud->self_ref); // pass the userdata(client) to callback func in lua
lua_call(L, 1, 0);
break;
}
break;
......@@ -278,28 +355,34 @@ READPACKET:
break;
if (mud->self_ref == LUA_NOREF)
break;
if(mud->L == NULL)
break;
lua_rawgeti(mud->L, LUA_REGISTRYINDEX, mud->cb_suback_ref);
lua_rawgeti(mud->L, LUA_REGISTRYINDEX, mud->self_ref);
lua_call(mud->L, 1, 0);
lua_rawgeti(L, LUA_REGISTRYINDEX, mud->cb_suback_ref);
lua_rawgeti(L, LUA_REGISTRYINDEX, mud->self_ref);
lua_call(L, 1, 0);
}
break;
case MQTT_MSG_TYPE_UNSUBACK:
if(pending_msg && pending_msg->msg_type == MQTT_MSG_TYPE_UNSUBSCRIBE && pending_msg->msg_id == msg_id){
NODE_DBG("MQTT: UnSubscribe successful\r\n");
msg_destroy(msg_dequeue(&(mud->mqtt_state.pending_msg_q)));
if (mud->cb_unsuback_ref == LUA_NOREF)
break;
if (mud->self_ref == LUA_NOREF)
break;
lua_rawgeti(L, LUA_REGISTRYINDEX, mud->cb_unsuback_ref);
lua_rawgeti(L, LUA_REGISTRYINDEX, mud->self_ref);
lua_call(L, 1, 0);
}
break;
case MQTT_MSG_TYPE_PUBLISH:
if(msg_qos == 1){
temp_msg = mqtt_msg_puback(&mud->mqtt_state.mqtt_connection, msg_id);
node = msg_enqueue(&(mud->mqtt_state.pending_msg_q), temp_msg,
msg_enqueue(&(mud->mqtt_state.pending_msg_q), temp_msg,
msg_id, MQTT_MSG_TYPE_PUBACK, (int)mqtt_get_qos(temp_msg->data) );
}
else if(msg_qos == 2){
temp_msg = mqtt_msg_pubrec(&mud->mqtt_state.mqtt_connection, msg_id);
node = msg_enqueue(&(mud->mqtt_state.pending_msg_q), temp_msg,
msg_enqueue(&(mud->mqtt_state.pending_msg_q), temp_msg,
msg_id, MQTT_MSG_TYPE_PUBREC, (int)mqtt_get_qos(temp_msg->data) );
}
if(msg_qos == 1 || msg_qos == 2){
......@@ -315,21 +398,19 @@ READPACKET:
break;
if(mud->self_ref == LUA_NOREF)
break;
if(mud->L == NULL)
break;
lua_rawgeti(mud->L, LUA_REGISTRYINDEX, mud->cb_puback_ref);
lua_rawgeti(mud->L, LUA_REGISTRYINDEX, mud->self_ref); // pass the userdata to callback func in lua
lua_call(mud->L, 1, 0);
lua_rawgeti(L, LUA_REGISTRYINDEX, mud->cb_puback_ref);
lua_rawgeti(L, LUA_REGISTRYINDEX, mud->self_ref); // pass the userdata to callback func in lua
lua_call(L, 1, 0);
}
break;
case MQTT_MSG_TYPE_PUBREC:
if(pending_msg && pending_msg->msg_type == MQTT_MSG_TYPE_PUBLISH && pending_msg->msg_id == msg_id){
NODE_DBG("MQTT: Publish with QoS = 2 Received PUBREC\r\n");
// Note: actrually, should not destroy the msg until PUBCOMP is received.
// Note: actually, should not destroy the msg until PUBCOMP is received.
msg_destroy(msg_dequeue(&(mud->mqtt_state.pending_msg_q)));
temp_msg = mqtt_msg_pubrel(&mud->mqtt_state.mqtt_connection, msg_id);
node = msg_enqueue(&(mud->mqtt_state.pending_msg_q), temp_msg,
msg_enqueue(&(mud->mqtt_state.pending_msg_q), temp_msg,
msg_id, MQTT_MSG_TYPE_PUBREL, (int)mqtt_get_qos(temp_msg->data) );
NODE_DBG("MQTT: Response PUBREL\r\n");
}
......@@ -338,7 +419,7 @@ READPACKET:
if(pending_msg && pending_msg->msg_type == MQTT_MSG_TYPE_PUBREC && pending_msg->msg_id == msg_id){
msg_destroy(msg_dequeue(&(mud->mqtt_state.pending_msg_q)));
temp_msg = mqtt_msg_pubcomp(&mud->mqtt_state.mqtt_connection, msg_id);
node = msg_enqueue(&(mud->mqtt_state.pending_msg_q), temp_msg,
msg_enqueue(&(mud->mqtt_state.pending_msg_q), temp_msg,
msg_id, MQTT_MSG_TYPE_PUBCOMP, (int)mqtt_get_qos(temp_msg->data) );
NODE_DBG("MQTT: Response PUBCOMP\r\n");
}
......@@ -351,16 +432,14 @@ READPACKET:
break;
if(mud->self_ref == LUA_NOREF)
break;
if(mud->L == NULL)
break;
lua_rawgeti(mud->L, LUA_REGISTRYINDEX, mud->cb_puback_ref);
lua_rawgeti(mud->L, LUA_REGISTRYINDEX, mud->self_ref); // pass the userdata to callback func in lua
lua_call(mud->L, 1, 0);
lua_rawgeti(L, LUA_REGISTRYINDEX, mud->cb_puback_ref);
lua_rawgeti(L, LUA_REGISTRYINDEX, mud->self_ref); // pass the userdata to callback func in lua
lua_call(L, 1, 0);
}
break;
case MQTT_MSG_TYPE_PINGREQ:
temp_msg = mqtt_msg_pingresp(&mud->mqtt_state.mqtt_connection);
node = msg_enqueue(&(mud->mqtt_state.pending_msg_q), temp_msg,
msg_enqueue(&(mud->mqtt_state.pending_msg_q), temp_msg,
msg_id, MQTT_MSG_TYPE_PINGRESP, (int)mqtt_get_qos(temp_msg->data) );
NODE_DBG("MQTT: Response PINGRESP\r\n");
break;
......@@ -389,21 +468,7 @@ READPACKET:
break;
}
if(node && (1==msg_size(&(mud->mqtt_state.pending_msg_q))) && mud->event_timeout == 0){
mud->event_timeout = MQTT_SEND_TIMEOUT;
NODE_DBG("Sent: %d\n", node->msg.length);
#ifdef CLIENT_SSL_ENABLE
if( mud->secure )
{
espconn_secure_sent( pesp_conn, node->msg.data, node->msg.length );
}
else
#endif
{
espconn_sent( pesp_conn, node->msg.data, node->msg.length );
}
}
NODE_DBG("receive, queue size: %d\n", msg_size(&(mud->mqtt_state.pending_msg_q)));
mqtt_send_if_possible(pesp_conn);
NODE_DBG("leave mqtt_socket_received.\n");
return;
}
......@@ -425,29 +490,33 @@ static void mqtt_socket_sent(void *arg)
if(mud->connState == MQTT_CONNECT_SENDING){
mud->connState = MQTT_CONNECT_SENT;
mud->event_timeout = MQTT_SEND_TIMEOUT;
// MQTT_CONNECT not queued.
return;
}
NODE_DBG("sent1, queue size: %d\n", msg_size(&(mud->mqtt_state.pending_msg_q)));
uint8_t try_send = 1;
// qos = 0, publish and forgot.
msg_queue_t *node = msg_peek(&(mud->mqtt_state.pending_msg_q));
if(node && node->msg_type == MQTT_MSG_TYPE_PUBLISH && node->publish_qos == 0) {
msg_destroy(msg_dequeue(&(mud->mqtt_state.pending_msg_q)));
if(mud->cb_puback_ref == LUA_NOREF)
return;
if(mud->self_ref == LUA_NOREF)
return;
if(mud->L == NULL)
return;
lua_rawgeti(mud->L, LUA_REGISTRYINDEX, mud->cb_puback_ref);
lua_rawgeti(mud->L, LUA_REGISTRYINDEX, mud->self_ref); // pass the userdata to callback func in lua
lua_call(mud->L, 1, 0);
if(mud->cb_puback_ref != LUA_NOREF && mud->self_ref != LUA_NOREF) {
lua_State *L = lua_getstate();
lua_rawgeti(L, LUA_REGISTRYINDEX, mud->cb_puback_ref);
lua_rawgeti(L, LUA_REGISTRYINDEX, mud->self_ref); // pass the userdata to callback func in lua
lua_call(L, 1, 0);
}
} else if(node && node->msg_type == MQTT_MSG_TYPE_PUBACK) {
msg_destroy(msg_dequeue(&(mud->mqtt_state.pending_msg_q)));
} else if(node && node->msg_type == MQTT_MSG_TYPE_PUBCOMP) {
msg_destroy(msg_dequeue(&(mud->mqtt_state.pending_msg_q)));
} else if(node && node->msg_type == MQTT_MSG_TYPE_PINGREQ) {
msg_destroy(msg_dequeue(&(mud->mqtt_state.pending_msg_q)));
} else {
try_send = 0;
}
if (try_send) {
mqtt_send_if_possible(mud->pesp_conn);
}
NODE_DBG("sent2, queue size: %d\n", msg_size(&(mud->mqtt_state.pending_msg_q)));
NODE_DBG("leave mqtt_socket_sent.\n");
......@@ -477,12 +546,12 @@ static void mqtt_socket_connected(void *arg)
#ifdef CLIENT_SSL_ENABLE
if(mud->secure)
{
espconn_secure_sent(pesp_conn, temp_msg->data, temp_msg->length);
espconn_secure_send(pesp_conn, temp_msg->data, temp_msg->length);
}
else
#endif
{
espconn_sent(pesp_conn, temp_msg->data, temp_msg->length);
espconn_send(pesp_conn, temp_msg->data, temp_msg->length);
}
mud->keep_alive_tick = 0;
......@@ -521,10 +590,13 @@ void mqtt_socket_timer(void *arg)
if(mud->connState == MQTT_INIT){ // socket connect time out.
NODE_DBG("Can not connect to broker.\n");
// Never goes here.
os_timer_disarm(&mud->mqttTimer);
mqtt_connack_fail(mud, MQTT_CONN_FAIL_SERVER_NOT_FOUND);
} else if(mud->connState == MQTT_CONNECT_SENDING){ // MQTT_CONNECT send time out.
NODE_DBG("sSend MQTT_CONNECT failed.\n");
mud->connState = MQTT_INIT;
mqtt_connack_fail(mud, MQTT_CONN_FAIL_TIMEOUT_SENDING);
#ifdef CLIENT_SSL_ENABLE
if(mud->secure)
{
......@@ -536,47 +608,36 @@ void mqtt_socket_timer(void *arg)
espconn_disconnect(mud->pesp_conn);
}
mud->keep_alive_tick = 0; // not need count anymore
} else if(mud->connState == MQTT_CONNECT_SENT){ // wait for CONACK time out.
NODE_DBG("MQTT_CONNECT failed.\n");
} else if(mud->connState == MQTT_DATA){
msg_queue_t *pending_msg = msg_peek(&(mud->mqtt_state.pending_msg_q));
if(pending_msg){
mud->event_timeout = MQTT_SEND_TIMEOUT;
} else if(mud->connState == MQTT_CONNECT_SENT) { // wait for CONACK time out.
NODE_DBG("MQTT_CONNECT timeout.\n");
mud->connState = MQTT_INIT;
#ifdef CLIENT_SSL_ENABLE
if(mud->secure)
{
espconn_secure_sent(mud->pesp_conn, pending_msg->msg.data, pending_msg->msg.length);
espconn_secure_disconnect(mud->pesp_conn);
}
else
#endif
{
espconn_sent(mud->pesp_conn, pending_msg->msg.data, pending_msg->msg.length);
espconn_disconnect(mud->pesp_conn);
}
mud->keep_alive_tick = 0;
NODE_DBG("id: %d - qos: %d, length: %d\n", pending_msg->msg_id, pending_msg->publish_qos, pending_msg->msg.length);
mqtt_connack_fail(mud, MQTT_CONN_FAIL_TIMEOUT_RECEIVING);
} else if(mud->connState == MQTT_DATA){
msg_queue_t *pending_msg = msg_peek(&(mud->mqtt_state.pending_msg_q));
if(pending_msg){
mqtt_send_if_possible(mud->pesp_conn);
} else {
// no queued event.
mud->keep_alive_tick ++;
if(mud->keep_alive_tick > mud->mqtt_state.connect_info->keepalive){
mud->event_timeout = MQTT_SEND_TIMEOUT;
uint8_t temp_buffer[MQTT_BUF_SIZE];
mqtt_msg_init(&mud->mqtt_state.mqtt_connection, temp_buffer, MQTT_BUF_SIZE);
NODE_DBG("\r\nMQTT: Send keepalive packet\r\n");
mqtt_message_t* temp_msg = mqtt_msg_pingreq(&mud->mqtt_state.mqtt_connection);
msg_queue_t *node = msg_enqueue( &(mud->mqtt_state.pending_msg_q), temp_msg,
0, MQTT_MSG_TYPE_PINGREQ, (int)mqtt_get_qos(temp_msg->data) );
// only one message in queue, send immediately.
#ifdef CLIENT_SSL_ENABLE
if(mud->secure)
{
espconn_secure_sent(mud->pesp_conn, temp_msg->data, temp_msg->length);
}
else
#endif
{
espconn_sent(mud->pesp_conn, temp_msg->data, temp_msg->length);
}
mud->keep_alive_tick = 0;
mqtt_send_if_possible(mud->pesp_conn);
}
}
}
......@@ -606,13 +667,14 @@ static int mqtt_socket_client( lua_State* L )
// create a object
mud = (lmqtt_userdata *)lua_newuserdata(L, sizeof(lmqtt_userdata));
// pre-initialize it, in case of errors
mud->L = NULL;
mud->self_ref = LUA_NOREF;
mud->cb_connect_ref = LUA_NOREF;
mud->cb_connect_fail_ref = LUA_NOREF;
mud->cb_disconnect_ref = LUA_NOREF;
mud->cb_message_ref = LUA_NOREF;
mud->cb_suback_ref = LUA_NOREF;
mud->cb_unsuback_ref = LUA_NOREF;
mud->cb_puback_ref = LUA_NOREF;
mud->pesp_conn = NULL;
#ifdef CLIENT_SSL_ENABLE
......@@ -631,8 +693,6 @@ static int mqtt_socket_client( lua_State* L )
luaL_getmetatable(L, "mqtt.socket");
lua_setmetatable(L, -2);
mud->L = L; // L for mqtt module.
if( lua_isstring(L,stack) ) // deal with the clientid string
{
clientId = luaL_checklstring( L, stack, &idl );
......@@ -655,7 +715,7 @@ static int mqtt_socket_client( lua_State* L )
}
if(username == NULL)
unl = 0;
NODE_DBG("lengh username: %d\r\n", unl);
NODE_DBG("length username: %d\r\n", unl);
if(lua_isstring( L, stack )){
password = luaL_checklstring( L, stack, &pwl );
......@@ -663,7 +723,7 @@ static int mqtt_socket_client( lua_State* L )
}
if(password == NULL)
pwl = 0;
NODE_DBG("lengh password: %d\r\n", pwl);
NODE_DBG("length password: %d\r\n", pwl);
if(lua_isnumber( L, stack ))
{
......@@ -773,73 +833,80 @@ static int mqtt_delete( lua_State* L )
// -------
// free (unref) callback ref
if(LUA_NOREF!=mud->cb_connect_ref){
luaL_unref(L, LUA_REGISTRYINDEX, mud->cb_connect_ref);
mud->cb_connect_ref = LUA_NOREF;
}
if(LUA_NOREF!=mud->cb_disconnect_ref){
luaL_unref(L, LUA_REGISTRYINDEX, mud->cb_connect_fail_ref);
mud->cb_connect_fail_ref = LUA_NOREF;
luaL_unref(L, LUA_REGISTRYINDEX, mud->cb_disconnect_ref);
mud->cb_disconnect_ref = LUA_NOREF;
}
if(LUA_NOREF!=mud->cb_message_ref){
luaL_unref(L, LUA_REGISTRYINDEX, mud->cb_message_ref);
mud->cb_message_ref = LUA_NOREF;
}
if(LUA_NOREF!=mud->cb_suback_ref){
luaL_unref(L, LUA_REGISTRYINDEX, mud->cb_suback_ref);
mud->cb_suback_ref = LUA_NOREF;
}
if(LUA_NOREF!=mud->cb_puback_ref){
luaL_unref(L, LUA_REGISTRYINDEX, mud->cb_unsuback_ref);
mud->cb_unsuback_ref = LUA_NOREF;
luaL_unref(L, LUA_REGISTRYINDEX, mud->cb_puback_ref);
mud->cb_puback_ref = LUA_NOREF;
}
lua_gc(L, LUA_GCSTOP, 0);
if(LUA_NOREF!=mud->self_ref){
luaL_unref(L, LUA_REGISTRYINDEX, mud->self_ref);
mud->self_ref = LUA_NOREF;
}
lua_gc(L, LUA_GCRESTART, 0);
NODE_DBG("leave mqtt_delete.\n");
return 0;
}
static void socket_connect(struct espconn *pesp_conn)
static sint8 socket_connect(struct espconn *pesp_conn)
{
NODE_DBG("enter socket_connect.\n");
sint8 espconn_status;
if(pesp_conn == NULL)
return;
return ESPCONN_CONN;
lmqtt_userdata *mud = (lmqtt_userdata *)pesp_conn->reverse;
if(mud == NULL)
return;
return ESPCONN_ARG;
mud->event_timeout = MQTT_CONNECT_TIMEOUT;
mud->connState = MQTT_INIT;
#ifdef CLIENT_SSL_ENABLE
if(mud->secure)
{
espconn_secure_connect(pesp_conn);
espconn_secure_set_size(ESPCONN_CLIENT, 5120); /* set SSL buffer size */
espconn_status = espconn_secure_connect(pesp_conn);
}
else
#endif
{
espconn_connect(pesp_conn);
espconn_status = espconn_connect(pesp_conn);
}
os_timer_arm(&mud->mqttTimer, 1000, 1);
NODE_DBG("leave socket_connect.\n");
return espconn_status;
}
static void socket_dns_found(const char *name, ip_addr_t *ipaddr, void *arg);
static dns_reconn_count = 0;
static sint8 socket_dns_found(const char *name, ip_addr_t *ipaddr, void *arg);
static int dns_reconn_count = 0;
static ip_addr_t host_ip; // for dns
static void socket_dns_found(const char *name, ip_addr_t *ipaddr, void *arg)
/* wrapper for using socket_dns_found() as callback function */
static void socket_dns_foundcb(const char *name, ip_addr_t *ipaddr, void *arg)
{
socket_dns_found(name, ipaddr, arg);
}
static sint8 socket_dns_found(const char *name, ip_addr_t *ipaddr, void *arg)
{
NODE_DBG("enter socket_dns_found.\n");
sint8 espconn_status = ESPCONN_OK;
struct espconn *pesp_conn = arg;
if(pesp_conn == NULL){
NODE_DBG("pesp_conn null.\n");
return;
return -1;
}
if(ipaddr == NULL)
......@@ -848,13 +915,21 @@ static void socket_dns_found(const char *name, ip_addr_t *ipaddr, void *arg)
if( dns_reconn_count >= 5 ){
NODE_ERR( "DNS Fail!\n" );
// Note: should delete the pesp_conn or unref self_ref here.
struct espconn *pesp_conn = arg;
if(pesp_conn != NULL) {
lmqtt_userdata *mud = (lmqtt_userdata *)pesp_conn->reverse;
if(mud != NULL) {
mqtt_connack_fail(mud, MQTT_CONN_FAIL_DNS);
}
}
mqtt_socket_disconnected(arg); // although not connected, but fire disconnect callback to release every thing.
return;
return -1;
}
NODE_ERR( "DNS retry %d!\n", dns_reconn_count );
host_ip.addr = 0;
espconn_gethostbyname(pesp_conn, name, &host_ip, socket_dns_found);
return;
return espconn_gethostbyname(pesp_conn, name, &host_ip, socket_dns_foundcb);
}
// ipaddr->addr is a uint32_t ip
......@@ -865,12 +940,14 @@ static void socket_dns_found(const char *name, ip_addr_t *ipaddr, void *arg)
NODE_DBG("TCP ip is set: ");
NODE_DBG(IPSTR, IP2STR(&(ipaddr->addr)));
NODE_DBG("\n");
socket_connect(pesp_conn);
espconn_status = socket_connect(pesp_conn);
}
NODE_DBG("leave socket_dns_found.\n");
return espconn_status;
}
// Lua: mqtt:connect( host, port, secure, auto_reconnect, function(client) )
// Lua: mqtt:connect( host, port, secure, auto_reconnect, function(client), function(client, connect_return_code) )
static int mqtt_socket_connect( lua_State* L )
{
NODE_DBG("enter mqtt_socket_connect.\n");
......@@ -882,6 +959,7 @@ static int mqtt_socket_connect( lua_State* L )
int stack = 1;
unsigned secure = 0, auto_reconnect = 0;
int top = lua_gettop(L);
sint8 espconn_status;
mud = (lmqtt_userdata *)luaL_checkudata(L, stack, "mqtt.socket");
luaL_argcheck(L, mud, stack, "mqtt.socket expected");
......@@ -980,19 +1058,26 @@ static int mqtt_socket_connect( lua_State* L )
// call back function when a connection is obtained, tcp only
if ((stack<=top) && (lua_type(L, stack) == LUA_TFUNCTION || lua_type(L, stack) == LUA_TLIGHTFUNCTION)){
lua_pushvalue(L, stack); // copy argument (func) to the top of stack
if(mud->cb_connect_ref != LUA_NOREF)
luaL_unref(L, LUA_REGISTRYINDEX, mud->cb_connect_ref);
mud->cb_connect_ref = luaL_ref(L, LUA_REGISTRYINDEX);
}
stack++;
// call back function when a connection fails
if ((stack<=top) && (lua_type(L, stack) == LUA_TFUNCTION || lua_type(L, stack) == LUA_TLIGHTFUNCTION)){
lua_pushvalue(L, stack); // copy argument (func) to the top of stack
luaL_unref(L, LUA_REGISTRYINDEX, mud->cb_connect_fail_ref);
mud->cb_connect_fail_ref = luaL_ref(L, LUA_REGISTRYINDEX);
stack++;
}
lua_pushvalue(L, 1); // copy userdata to the top of stack
if(mud->self_ref != LUA_NOREF)
luaL_unref(L, LUA_REGISTRYINDEX, mud->self_ref);
mud->self_ref = luaL_ref(L, LUA_REGISTRYINDEX);
espconn_regist_connectcb(pesp_conn, mqtt_socket_connected);
espconn_regist_reconcb(pesp_conn, mqtt_socket_reconnected);
espconn_status = espconn_regist_connectcb(pesp_conn, mqtt_socket_connected);
espconn_status |= espconn_regist_reconcb(pesp_conn, mqtt_socket_reconnected);
os_timer_disarm(&mud->mqttTimer);
os_timer_setfn(&mud->mqttTimer, (os_timer_func_t *)mqtt_socket_timer, mud);
......@@ -1002,17 +1087,23 @@ static int mqtt_socket_connect( lua_State* L )
{
host_ip.addr = 0;
dns_reconn_count = 0;
if(ESPCONN_OK == espconn_gethostbyname(pesp_conn, domain, &host_ip, socket_dns_found)){
socket_dns_found(domain, &host_ip, pesp_conn); // ip is returned in host_ip.
if(ESPCONN_OK == espconn_gethostbyname(pesp_conn, domain, &host_ip, socket_dns_foundcb)){
espconn_status |= socket_dns_found(domain, &host_ip, pesp_conn); // ip is returned in host_ip.
}
}
else
{
socket_connect(pesp_conn);
espconn_status |= socket_connect(pesp_conn);
}
NODE_DBG("leave mqtt_socket_connect.\n");
return 0;
if (espconn_status == ESPCONN_OK) {
lua_pushboolean(L, 1);
} else {
lua_pushboolean(L, 0);
}
return 1;
}
// Lua: mqtt:close()
......@@ -1025,37 +1116,44 @@ static int mqtt_socket_close( lua_State* L )
mud = (lmqtt_userdata *)luaL_checkudata(L, 1, "mqtt.socket");
luaL_argcheck(L, mud, 1, "mqtt.socket expected");
if(mud == NULL)
return 0;
if(mud->pesp_conn == NULL)
return 0;
if (mud == NULL || mud->pesp_conn == NULL) {
lua_pushboolean(L, 0);
return 1;
}
// Send disconnect message
mqtt_message_t* temp_msg = mqtt_msg_disconnect(&mud->mqtt_state.mqtt_connection);
NODE_DBG("Send MQTT disconnect infomation, data len: %d, d[0]=%d \r\n", temp_msg->length, temp_msg->data[0]);
sint8 espconn_status;
#ifdef CLIENT_SSL_ENABLE
if(mud->secure)
espconn_secure_sent(mud->pesp_conn, temp_msg->data, temp_msg->length);
espconn_status = espconn_secure_send(mud->pesp_conn, temp_msg->data, temp_msg->length);
else
#endif
espconn_sent(mud->pesp_conn, temp_msg->data, temp_msg->length);
espconn_status = espconn_send(mud->pesp_conn, temp_msg->data, temp_msg->length);
mud->mqtt_state.auto_reconnect = 0; // stop auto reconnect.
#ifdef CLIENT_SSL_ENABLE
if(mud->secure){
if(mud->pesp_conn->proto.tcp->remote_port || mud->pesp_conn->proto.tcp->local_port)
espconn_secure_disconnect(mud->pesp_conn);
espconn_status |= espconn_secure_disconnect(mud->pesp_conn);
}
else
#endif
{
if(mud->pesp_conn->proto.tcp->remote_port || mud->pesp_conn->proto.tcp->local_port)
espconn_disconnect(mud->pesp_conn);
espconn_status |= espconn_disconnect(mud->pesp_conn);
}
NODE_DBG("leave mqtt_socket_close.\n");
return 0;
if (espconn_status == ESPCONN_OK) {
lua_pushboolean(L, 1);
} else {
lua_pushboolean(L, 0);
}
return 1;
}
// Lua: mqtt:on( "method", function() )
......@@ -1080,15 +1178,12 @@ static int mqtt_socket_on( lua_State* L )
lua_pushvalue(L, 3); // copy argument (func) to the top of stack
if( sl == 7 && c_strcmp(method, "connect") == 0){
if(mud->cb_connect_ref != LUA_NOREF)
luaL_unref(L, LUA_REGISTRYINDEX, mud->cb_connect_ref);
mud->cb_connect_ref = luaL_ref(L, LUA_REGISTRYINDEX);
}else if( sl == 7 && c_strcmp(method, "offline") == 0){
if(mud->cb_disconnect_ref != LUA_NOREF)
luaL_unref(L, LUA_REGISTRYINDEX, mud->cb_disconnect_ref);
mud->cb_disconnect_ref = luaL_ref(L, LUA_REGISTRYINDEX);
}else if( sl == 7 && c_strcmp(method, "message") == 0){
if(mud->cb_message_ref != LUA_NOREF)
luaL_unref(L, LUA_REGISTRYINDEX, mud->cb_message_ref);
mud->cb_message_ref = luaL_ref(L, LUA_REGISTRYINDEX);
}else{
......@@ -1099,6 +1194,118 @@ static int mqtt_socket_on( lua_State* L )
return 0;
}
// Lua: bool = mqtt:unsubscribe(topic, function())
static int mqtt_socket_unsubscribe( lua_State* L ) {
NODE_DBG("enter mqtt_socket_unsubscribe.\n");
uint8_t stack = 1;
uint16_t msg_id = 0;
const char *topic;
size_t il;
lmqtt_userdata *mud;
mud = (lmqtt_userdata *) luaL_checkudata( L, stack, "mqtt.socket" );
luaL_argcheck( L, mud, stack, "mqtt.socket expected" );
stack++;
if(mud==NULL){
NODE_DBG("userdata is nil.\n");
lua_pushboolean(L, 0);
return 1;
}
if(mud->pesp_conn == NULL){
NODE_DBG("mud->pesp_conn is NULL.\n");
lua_pushboolean(L, 0);
return 1;
}
if(!mud->connected){
luaL_error( L, "not connected" );
lua_pushboolean(L, 0);
return 1;
}
uint8_t temp_buffer[MQTT_BUF_SIZE];
mqtt_msg_init(&mud->mqtt_state.mqtt_connection, temp_buffer, MQTT_BUF_SIZE);
mqtt_message_t *temp_msg = NULL;
if( lua_istable( L, stack ) ) {
NODE_DBG("unsubscribe table\n");
lua_pushnil( L ); /* first key */
int topic_count = 0;
uint8_t overflow = 0;
while( lua_next( L, stack ) != 0 ) {
topic = luaL_checkstring( L, -2 );
if (topic_count == 0) {
temp_msg = mqtt_msg_unsubscribe_init( &mud->mqtt_state.mqtt_connection, &msg_id );
}
temp_msg = mqtt_msg_unsubscribe_topic( &mud->mqtt_state.mqtt_connection, topic );
topic_count++;
NODE_DBG("topic: %s - length: %d\n", topic, temp_msg->length);
if (temp_msg->length == 0) {
lua_pop(L, 1);
overflow = 1;
break; // too long message for the outbuffer.
}
lua_pop( L, 1 );
}
if (topic_count == 0){
return luaL_error( L, "no topics found" );
}
if (overflow != 0){
return luaL_error( L, "buffer overflow, can't enqueue all unsubscriptions" );
}
temp_msg = mqtt_msg_unsubscribe_fini( &mud->mqtt_state.mqtt_connection );
if (temp_msg->length == 0) {
return luaL_error( L, "buffer overflow, can't enqueue all unsubscriptions" );
}
stack++;
} else {
NODE_DBG("unsubscribe string\n");
topic = luaL_checklstring( L, stack, &il );
stack++;
if( topic == NULL ){
return luaL_error( L, "need topic name" );
}
temp_msg = mqtt_msg_unsubscribe( &mud->mqtt_state.mqtt_connection, topic, &msg_id );
}
if( lua_type( L, stack ) == LUA_TFUNCTION || lua_type( L, stack ) == LUA_TLIGHTFUNCTION ) { // TODO: this will overwrite the previous one.
lua_pushvalue( L, stack ); // copy argument (func) to the top of stack
luaL_unref( L, LUA_REGISTRYINDEX, mud->cb_unsuback_ref );
mud->cb_unsuback_ref = luaL_ref( L, LUA_REGISTRYINDEX );
}
msg_queue_t *node = msg_enqueue( &(mud->mqtt_state.pending_msg_q), temp_msg,
msg_id, MQTT_MSG_TYPE_UNSUBSCRIBE, (int)mqtt_get_qos(temp_msg->data) );
NODE_DBG("topic: %s - id: %d - qos: %d, length: %d\n", topic, node->msg_id, node->publish_qos, node->msg.length);
NODE_DBG("msg_size: %d, event_timeout: %d\n", msg_size(&(mud->mqtt_state.pending_msg_q)), mud->event_timeout);
sint8 espconn_status = ESPCONN_IF;
espconn_status = mqtt_send_if_possible(mud->pesp_conn);
if(!node || espconn_status != ESPCONN_OK){
lua_pushboolean(L, 0);
} else {
lua_pushboolean(L, 1); // enqueued succeed.
}
NODE_DBG("unsubscribe, queue size: %d\n", msg_size(&(mud->mqtt_state.pending_msg_q)));
NODE_DBG("leave mqtt_socket_unsubscribe.\n");
return 1;
}
// Lua: bool = mqtt:subscribe(topic, qos, function())
static int mqtt_socket_subscribe( lua_State* L ) {
NODE_DBG("enter mqtt_socket_subscribe.\n");
......@@ -1139,44 +1346,49 @@ static int mqtt_socket_subscribe( lua_State* L ) {
NODE_DBG("subscribe table\n");
lua_pushnil( L ); /* first key */
uint8_t temp_buf[MQTT_BUF_SIZE];
uint32_t temp_pos = 0;
int topic_count = 0;
uint8_t overflow = 0;
while( lua_next( L, stack ) != 0 ) {
topic = luaL_checkstring( L, -2 );
qos = luaL_checkinteger( L, -1 );
temp_msg = mqtt_msg_subscribe( &mud->mqtt_state.mqtt_connection, topic, qos, &msg_id );
if (topic_count == 0) {
temp_msg = mqtt_msg_subscribe_init( &mud->mqtt_state.mqtt_connection, &msg_id );
}
temp_msg = mqtt_msg_subscribe_topic( &mud->mqtt_state.mqtt_connection, topic, qos );
topic_count++;
NODE_DBG("topic: %s - qos: %d, length: %d\n", topic, qos, temp_msg->length);
if (temp_pos + temp_msg->length > MQTT_BUF_SIZE){
if (temp_msg->length == 0) {
lua_pop(L, 1);
overflow = 1;
break; // too long message for the outbuffer.
}
c_memcpy( temp_buf + temp_pos, temp_msg->data, temp_msg->length );
temp_pos += temp_msg->length;
lua_pop( L, 1 );
}
if (temp_pos == 0){
luaL_error( L, "invalid data" );
lua_pushboolean(L, 0);
return 1;
if (topic_count == 0){
return luaL_error( L, "no topics found" );
}
if (overflow != 0){
return luaL_error( L, "buffer overflow, can't enqueue all subscriptions" );
}
temp_msg = mqtt_msg_subscribe_fini( &mud->mqtt_state.mqtt_connection );
if (temp_msg->length == 0) {
return luaL_error( L, "buffer overflow, can't enqueue all subscriptions" );
}
c_memcpy( temp_buffer, temp_buf, temp_pos );
temp_msg->data = temp_buffer;
temp_msg->length = temp_pos;
stack++;
} else {
NODE_DBG("subscribe string\n");
topic = luaL_checklstring( L, stack, &il );
stack++;
if( topic == NULL ){
luaL_error( L, "need topic name" );
lua_pushboolean(L, 0);
return 1;
return luaL_error( L, "need topic name" );
}
qos = luaL_checkinteger( L, stack );
temp_msg = mqtt_msg_subscribe( &mud->mqtt_state.mqtt_connection, topic, qos, &msg_id );
......@@ -1185,7 +1397,6 @@ static int mqtt_socket_subscribe( lua_State* L ) {
if( lua_type( L, stack ) == LUA_TFUNCTION || lua_type( L, stack ) == LUA_TLIGHTFUNCTION ) { // TODO: this will overwrite the previous one.
lua_pushvalue( L, stack ); // copy argument (func) to the top of stack
if( mud->cb_suback_ref != LUA_NOREF )
luaL_unref( L, LUA_REGISTRYINDEX, mud->cb_suback_ref );
mud->cb_suback_ref = luaL_ref( L, LUA_REGISTRYINDEX );
}
......@@ -1194,24 +1405,13 @@ static int mqtt_socket_subscribe( lua_State* L ) {
msg_id, MQTT_MSG_TYPE_SUBSCRIBE, (int)mqtt_get_qos(temp_msg->data) );
NODE_DBG("topic: %s - id: %d - qos: %d, length: %d\n", topic, node->msg_id, node->publish_qos, node->msg.length);
NODE_DBG("msg_size: %d, event_timeout: %d\n", msg_size(&(mud->mqtt_state.pending_msg_q)), mud->event_timeout);
if(node && (1==msg_size(&(mud->mqtt_state.pending_msg_q))) && mud->event_timeout == 0){
mud->event_timeout = MQTT_SEND_TIMEOUT;
NODE_DBG("Sent: %d\n", node->msg.length);
#ifdef CLIENT_SSL_ENABLE
if( mud->secure )
{
espconn_secure_sent( mud->pesp_conn, node->msg.data, node->msg.length );
}
else
#endif
{
espconn_sent( mud->pesp_conn, node->msg.data, node->msg.length );
}
mud->keep_alive_tick = 0;
}
sint8 espconn_status = ESPCONN_IF;
if(!node){
espconn_status = mqtt_send_if_possible(mud->pesp_conn);
if(!node || espconn_status != ESPCONN_OK){
lua_pushboolean(L, 0);
} else {
lua_pushboolean(L, 1); // enqueued succeed.
......@@ -1230,6 +1430,7 @@ static int mqtt_socket_publish( lua_State* L )
size_t l;
uint8_t stack = 1;
uint16_t msg_id = 0;
mud = (lmqtt_userdata *)luaL_checkudata(L, stack, "mqtt.socket");
luaL_argcheck(L, mud, stack, "mqtt.socket expected");
stack++;
......@@ -1246,17 +1447,13 @@ static int mqtt_socket_publish( lua_State* L )
}
if(!mud->connected){
luaL_error( L, "not connected" );
lua_pushboolean(L, 0);
return 1;
return luaL_error( L, "not connected" );
}
const char *topic = luaL_checklstring( L, stack, &l );
stack ++;
if (topic == NULL){
luaL_error( L, "need topic" );
lua_pushboolean(L, 0);
return 1;
return luaL_error( L, "need topic" );
}
const char *payload = luaL_checklstring( L, stack, &l );
......@@ -1275,7 +1472,6 @@ static int mqtt_socket_publish( lua_State* L )
if (lua_type(L, stack) == LUA_TFUNCTION || lua_type(L, stack) == LUA_TLIGHTFUNCTION){
lua_pushvalue(L, stack); // copy argument (func) to the top of stack
if(mud->cb_puback_ref != LUA_NOREF)
luaL_unref(L, LUA_REGISTRYINDEX, mud->cb_puback_ref);
mud->cb_puback_ref = luaL_ref(L, LUA_REGISTRYINDEX);
}
......@@ -1283,23 +1479,11 @@ static int mqtt_socket_publish( lua_State* L )
msg_queue_t *node = msg_enqueue(&(mud->mqtt_state.pending_msg_q), temp_msg,
msg_id, MQTT_MSG_TYPE_PUBLISH, (int)qos );
if(node && (1==msg_size(&(mud->mqtt_state.pending_msg_q))) && mud->event_timeout == 0){
mud->event_timeout = MQTT_SEND_TIMEOUT;
NODE_DBG("Sent: %d\n", node->msg.length);
#ifdef CLIENT_SSL_ENABLE
if( mud->secure )
{
espconn_secure_sent( mud->pesp_conn, node->msg.data, node->msg.length );
}
else
#endif
{
espconn_sent( mud->pesp_conn, node->msg.data, node->msg.length );
}
mud->keep_alive_tick = 0;
}
sint8 espconn_status = ESPCONN_OK;
if(!node){
espconn_status = mqtt_send_if_possible(mud->pesp_conn);
if(!node || espconn_status != ESPCONN_OK){
lua_pushboolean(L, 0);
} else {
lua_pushboolean(L, 1); // enqueued succeed.
......@@ -1394,6 +1578,7 @@ static const LUA_REG_TYPE mqtt_socket_map[] = {
{ LSTRKEY( "close" ), LFUNCVAL( mqtt_socket_close ) },
{ LSTRKEY( "publish" ), LFUNCVAL( mqtt_socket_publish ) },
{ LSTRKEY( "subscribe" ), LFUNCVAL( mqtt_socket_subscribe ) },
{ LSTRKEY( "unsubscribe" ), LFUNCVAL( mqtt_socket_unsubscribe ) },
{ LSTRKEY( "lwt" ), LFUNCVAL( mqtt_socket_lwt ) },
{ LSTRKEY( "on" ), LFUNCVAL( mqtt_socket_on ) },
{ LSTRKEY( "__gc" ), LFUNCVAL( mqtt_delete ) },
......@@ -1401,8 +1586,22 @@ static const LUA_REG_TYPE mqtt_socket_map[] = {
{ LNILKEY, LNILVAL }
};
static const LUA_REG_TYPE mqtt_map[] = {
{ LSTRKEY( "Client" ), LFUNCVAL( mqtt_socket_client ) },
{ LSTRKEY( "CONN_FAIL_SERVER_NOT_FOUND" ), LNUMVAL( MQTT_CONN_FAIL_SERVER_NOT_FOUND ) },
{ LSTRKEY( "CONN_FAIL_NOT_A_CONNACK_MSG" ), LNUMVAL( MQTT_CONN_FAIL_NOT_A_CONNACK_MSG ) },
{ LSTRKEY( "CONN_FAIL_DNS" ), LNUMVAL( MQTT_CONN_FAIL_DNS ) },
{ LSTRKEY( "CONN_FAIL_TIMEOUT_RECEIVING" ), LNUMVAL( MQTT_CONN_FAIL_TIMEOUT_RECEIVING ) },
{ LSTRKEY( "CONN_FAIL_TIMEOUT_SENDING" ), LNUMVAL( MQTT_CONN_FAIL_TIMEOUT_SENDING ) },
{ LSTRKEY( "CONNACK_ACCEPTED" ), LNUMVAL( MQTT_CONNACK_ACCEPTED ) },
{ LSTRKEY( "CONNACK_REFUSED_PROTOCOL_VER" ), LNUMVAL( MQTT_CONNACK_REFUSED_PROTOCOL_VER ) },
{ LSTRKEY( "CONNACK_REFUSED_ID_REJECTED" ), LNUMVAL( MQTT_CONNACK_REFUSED_ID_REJECTED ) },
{ LSTRKEY( "CONNACK_REFUSED_SERVER_UNAVAILABLE" ), LNUMVAL( MQTT_CONNACK_REFUSED_SERVER_UNAVAILABLE ) },
{ LSTRKEY( "CONNACK_REFUSED_BAD_USER_OR_PASS" ), LNUMVAL( MQTT_CONNACK_REFUSED_BAD_USER_OR_PASS ) },
{ LSTRKEY( "CONNACK_REFUSED_NOT_AUTHORIZED" ), LNUMVAL( MQTT_CONNACK_REFUSED_NOT_AUTHORIZED ) },
{ LSTRKEY( "__metatable" ), LROVAL( mqtt_map ) },
{ LNILKEY, LNILVAL }
};
......
......@@ -3,6 +3,7 @@
#include "module.h"
#include "lauxlib.h"
#include "platform.h"
#include "lmem.h"
#include "c_string.h"
#include "c_stdlib.h"
......@@ -13,18 +14,19 @@
#include "espconn.h"
#include "lwip/dns.h"
#ifdef CLIENT_SSL_ENABLE
unsigned char *default_certificate;
unsigned int default_certificate_len = 0;
unsigned char *default_private_key;
unsigned int default_private_key_len = 0;
#endif
#define TCP ESPCONN_TCP
#define UDP ESPCONN_UDP
static ip_addr_t host_ip; // for dns
#ifdef HAVE_SSL_SERVER_CRT
#include HAVE_SSL_SERVER_CRT
#else
__attribute__((section(".servercert.flash"))) unsigned char net_server_cert_area[INTERNAL_FLASH_SECTOR_SIZE];
#endif
__attribute__((section(".clientcert.flash"))) unsigned char net_client_cert_area[INTERNAL_FLASH_SECTOR_SIZE];
#if 0
static int expose_array(lua_State* L, char *array, unsigned short len);
#endif
......@@ -594,6 +596,7 @@ static void socket_connect(struct espconn *pesp_conn)
{
#ifdef CLIENT_SSL_ENABLE
if(nud->secure){
espconn_secure_set_size(ESPCONN_CLIENT, 5120); /* set SSL buffer size */
espconn_secure_connect(pesp_conn);
}
else
......@@ -610,7 +613,7 @@ static void socket_connect(struct espconn *pesp_conn)
}
static void socket_dns_found(const char *name, ip_addr_t *ipaddr, void *arg);
static dns_reconn_count = 0;
static int dns_reconn_count = 0;
static void socket_dns_found(const char *name, ip_addr_t *ipaddr, void *arg)
{
NODE_DBG("socket_dns_found is called.\n");
......@@ -1431,6 +1434,201 @@ static int net_multicastLeave( lua_State* L )
return net_multicastJoinLeave(L,0);
}
// Returns NULL on success, error message otherwise
static const char *append_pem_blob(const char *pem, const char *type, uint8_t **buffer_p, uint8_t *buffer_limit, const char *name) {
char unb64[256];
memset(unb64, 0xff, sizeof(unb64));
int i;
for (i = 0; i < 64; i++) {
unb64["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[i]] = i;
}
if (!pem) {
return "No PEM blob";
}
// Scan for -----BEGIN CERT
pem = strstr(pem, "-----BEGIN ");
if (!pem) {
return "No PEM header";
}
if (strncmp(pem + 11, type, strlen(type))) {
return "Wrong PEM type";
}
pem = strchr(pem, '\n');
if (!pem) {
return "Incorrect PEM format";
}
//
// Base64 encoded data starts here
// Get all the base64 data into a single buffer....
// We will use the back end of the buffer....
//
uint8_t *buffer = *buffer_p;
uint8_t *dest = buffer + 32 + 2; // Leave space for name and length
int bitcount = 0;
int accumulator = 0;
for (; *pem && dest < buffer_limit; pem++) {
int val = unb64[*(uint8_t*) pem];
if (val & 0xC0) {
// not a base64 character
if (isspace(*(uint8_t*) pem)) {
continue;
}
if (*pem == '=') {
// just ignore -- at the end
bitcount = 0;
continue;
}
if (*pem == '-') {
break;
}
return "Invalid character in PEM";
} else {
bitcount += 6;
accumulator = (accumulator << 6) + val;
if (bitcount >= 8) {
bitcount -= 8;
*dest++ = accumulator >> bitcount;
}
}
}
if (dest >= buffer_limit || strncmp(pem, "-----END ", 9) || strncmp(pem + 9, type, strlen(type)) || bitcount) {
return "Invalid PEM format data";
}
size_t len = dest - (buffer + 32 + 2);
memset(buffer, 0, 32);
strcpy(buffer, name);
buffer[32] = len & 0xff;
buffer[33] = (len >> 8) & 0xff;
*buffer_p = dest;
return NULL;
}
static const char *fill_page_with_pem(lua_State *L, const unsigned char *flash_memory, int flash_offset, const char **types, const char **names)
{
uint8_t *buffer = luaM_malloc(L, INTERNAL_FLASH_SECTOR_SIZE);
uint8_t *buffer_base = buffer;
uint8_t *buffer_limit = buffer + INTERNAL_FLASH_SECTOR_SIZE;
int argno;
for (argno = 1; argno <= lua_gettop(L) && types[argno - 1]; argno++) {
const char *pem = lua_tostring(L, argno);
const char *error = append_pem_blob(pem, types[argno - 1], &buffer, buffer_limit, names[argno - 1]);
if (error) {
luaM_free(L, buffer_base);
return error;
}
}
memset(buffer, 0xff, buffer_limit - buffer);
// Lets see if it matches what is already there....
if (c_memcmp(buffer_base, flash_memory, INTERNAL_FLASH_SECTOR_SIZE) != 0) {
// Starts being dangerous
if (platform_flash_erase_sector(flash_offset / INTERNAL_FLASH_SECTOR_SIZE) != PLATFORM_OK) {
luaM_free(L, buffer_base);
return "Failed to erase sector";
}
if (platform_s_flash_write(buffer_base, flash_offset, INTERNAL_FLASH_SECTOR_SIZE) != INTERNAL_FLASH_SECTOR_SIZE) {
luaM_free(L, buffer_base);
return "Failed to write sector";
}
// ends being dangerous
}
luaM_free(L, buffer_base);
return NULL;
}
// Lua: net.cert.auth(true / false | PEM data [, PEM data] )
static int net_cert_auth(lua_State *L)
{
int enable;
uint32_t flash_offset = platform_flash_mapped2phys((uint32_t) &net_client_cert_area[0]);
if ((flash_offset & 0xfff) || flash_offset > 0xff000 || INTERNAL_FLASH_SECTOR_SIZE != 0x1000) {
// THis should never happen
return luaL_error( L, "bad offset" );
}
if (lua_type(L, 1) == LUA_TSTRING) {
const char *types[3] = { "CERTIFICATE", "RSA PRIVATE KEY", NULL };
const char *names[2] = { "certificate", "private_key" };
const char *error = fill_page_with_pem(L, &net_client_cert_area[0], flash_offset, types, names);
if (error) {
return luaL_error(L, error);
}
enable = 1;
} else {
enable = lua_toboolean(L, 1);
}
bool rc;
if (enable) {
// See if there is a cert there
if (net_client_cert_area[0] == 0x00 || net_client_cert_area[0] == 0xff) {
return luaL_error( L, "no certificates found" );
}
rc = espconn_secure_cert_req_enable(1, flash_offset / INTERNAL_FLASH_SECTOR_SIZE);
} else {
rc = espconn_secure_cert_req_disable(1);
}
lua_pushboolean(L, rc);
return 1;
}
// Lua: net.cert.verify(true / false | PEM data [, PEM data] )
static int net_cert_verify(lua_State *L)
{
int enable;
uint32_t flash_offset = platform_flash_mapped2phys((uint32_t) &net_server_cert_area[0]);
if ((flash_offset & 0xfff) || flash_offset > 0xff000 || INTERNAL_FLASH_SECTOR_SIZE != 0x1000) {
// THis should never happen
return luaL_error( L, "bad offset" );
}
if (lua_type(L, 1) == LUA_TSTRING) {
const char *types[2] = { "CERTIFICATE", NULL };
const char *names[1] = { "certificate" };
const char *error = fill_page_with_pem(L, &net_server_cert_area[0], flash_offset, types, names);
if (error) {
return luaL_error(L, error);
}
enable = 1;
} else {
enable = lua_toboolean(L, 1);
}
bool rc;
if (enable) {
// See if there is a cert there
if (net_server_cert_area[0] == 0x00 || net_server_cert_area[0] == 0xff) {
return luaL_error( L, "no certificates found" );
}
rc = espconn_secure_ca_enable(1, flash_offset / INTERNAL_FLASH_SECTOR_SIZE);
} else {
rc = espconn_secure_ca_disable(1);
}
lua_pushboolean(L, rc);
return 1;
}
// Lua: s = net.dns.setdnsserver(ip_addr, [index])
static int net_setdnsserver( lua_State* L )
......@@ -1538,6 +1736,14 @@ static const LUA_REG_TYPE net_array_map[] = {
};
#endif
static const LUA_REG_TYPE net_cert_map[] = {
{ LSTRKEY( "verify" ), LFUNCVAL( net_cert_verify ) },
#ifdef CLIENT_SSL_CERT_AUTH_ENABLE
{ LSTRKEY( "auth" ), LFUNCVAL( net_cert_auth ) },
#endif
{ LNILKEY, LNILVAL }
};
static const LUA_REG_TYPE net_dns_map[] = {
{ LSTRKEY( "setdnsserver" ), LFUNCVAL( net_setdnsserver ) },
{ LSTRKEY( "getdnsserver" ), LFUNCVAL( net_getdnsserver ) },
......@@ -1551,6 +1757,9 @@ static const LUA_REG_TYPE net_map[] = {
{ LSTRKEY( "multicastJoin"), LFUNCVAL( net_multicastJoin ) },
{ LSTRKEY( "multicastLeave"), LFUNCVAL( net_multicastLeave ) },
{ LSTRKEY( "dns" ), LROVAL( net_dns_map ) },
#ifdef CLIENT_SSL_ENABLE
{ LSTRKEY( "cert" ), LROVAL(net_cert_map) },
#endif
{ LSTRKEY( "TCP" ), LNUMVAL( TCP ) },
{ LSTRKEY( "UDP" ), LNUMVAL( UDP ) },
{ LSTRKEY( "__metatable" ), LROVAL( net_map ) },
......
......@@ -9,6 +9,7 @@
#include "lmem.h"
#include "lobject.h"
#include "lstate.h"
#include "legc.h"
#include "lopcodes.h"
#include "lstring.h"
......@@ -18,13 +19,14 @@
#include "lrodefs.h"
#include "c_types.h"
#include "romfs.h"
#include "c_string.h"
#include "driver/uart.h"
#include "user_interface.h"
#include "flash_api.h"
#include "flash_fs.h"
#include "user_version.h"
#include "rom.h"
#include "task/task.h"
#define CPU80MHZ 80
#define CPU160MHZ 160
......@@ -39,7 +41,8 @@ static int node_restart( lua_State* L )
// Lua: dsleep( us, option )
static int node_deepsleep( lua_State* L )
{
s32 us, option;
uint32 us;
uint8 option;
//us = luaL_checkinteger( L, 1 );
// Set deleep option, skip if nil
if ( lua_isnumber(L, 2) )
......@@ -48,12 +51,12 @@ static int node_deepsleep( lua_State* L )
if ( option < 0 || option > 4)
return luaL_error( L, "wrong arg range" );
else
deep_sleep_set_option( option );
system_deep_sleep_set_option( option );
}
// Set deleep time, skip if nil
if ( lua_isnumber(L, 1) )
{
us = lua_tointeger(L, 1);
us = luaL_checknumber(L, 1);
// if ( us <= 0 )
if ( us < 0 )
return luaL_error( L, "wrong arg range" );
......@@ -143,8 +146,6 @@ static int node_heap( lua_State* L )
return 1;
}
static lua_State *gL = NULL;
#ifdef DEVKIT_VERSION_0_9
static int led_high_count = LED_HIGH_COUNT_DEFAULT;
static int led_low_count = LED_LOW_COUNT_DEFAULT;
......@@ -172,27 +173,25 @@ static void default_short_press(void *arg) {
}
static void key_long_press(void *arg) {
lua_State *L = lua_getstate();
NODE_DBG("key_long_press is called.\n");
if (long_key_ref == LUA_NOREF) {
default_long_press(arg);
return;
}
if (!gL)
return;
lua_rawgeti(gL, LUA_REGISTRYINDEX, long_key_ref);
lua_call(gL, 0, 0);
lua_rawgeti(L, LUA_REGISTRYINDEX, long_key_ref);
lua_call(L, 0, 0);
}
static void key_short_press(void *arg) {
lua_State *L = lua_getstate();
NODE_DBG("key_short_press is called.\n");
if (short_key_ref == LUA_NOREF) {
default_short_press(arg);
return;
}
if (!gL)
return;
lua_rawgeti(gL, LUA_REGISTRYINDEX, short_key_ref);
lua_call(gL, 0, 0);
lua_rawgeti(L, LUA_REGISTRYINDEX, short_key_ref);
lua_call(L, 0, 0);
}
static void update_key_led (void *p)
......@@ -284,7 +283,6 @@ static int node_key( lua_State* L )
} else {
ref = &short_key_ref;
}
gL = L;
// luaL_checkanyfunction(L, 2);
if (lua_type(L, 2) == LUA_TFUNCTION || lua_type(L, 2) == LUA_TLIGHTFUNCTION) {
lua_pushvalue(L, 2); // copy argument (func) to the top of stack
......@@ -303,6 +301,7 @@ static int node_key( lua_State* L )
#endif
extern lua_Load gLoad;
extern bool user_process_input(bool force);
// Lua: input("string")
static int node_input( lua_State* L )
{
......@@ -319,7 +318,7 @@ static int node_input( lua_State* L )
NODE_DBG("Get command:\n");
NODE_DBG(load->line); // buggy here
NODE_DBG("\nResult(if any):\n");
system_os_post (LUA_TASK_PRIO, LUA_PROCESS_LINE_SIG, 0);
user_process_input(true);
}
}
return 0;
......@@ -328,12 +327,13 @@ static int node_input( lua_State* L )
static int output_redir_ref = LUA_NOREF;
static int serial_debug = 1;
void output_redirect(const char *str) {
lua_State *L = lua_getstate();
// if(c_strlen(str)>=TX_BUFF_SIZE){
// NODE_ERR("output too long.\n");
// return;
// }
if (output_redir_ref == LUA_NOREF || !gL) {
if (output_redir_ref == LUA_NOREF || !L) {
uart0_sendStr(str);
return;
}
......@@ -342,15 +342,14 @@ void output_redirect(const char *str) {
uart0_sendStr(str);
}
lua_rawgeti(gL, LUA_REGISTRYINDEX, output_redir_ref);
lua_pushstring(gL, str);
lua_call(gL, 1, 0); // this call back function should never user output.
lua_rawgeti(L, LUA_REGISTRYINDEX, output_redir_ref);
lua_pushstring(L, str);
lua_call(L, 1, 0); // this call back function should never user output.
}
// Lua: output(function(c), debug)
static int node_output( lua_State* L )
{
gL = L;
// luaL_checkanyfunction(L, 1);
if (lua_type(L, 1) == LUA_TFUNCTION || lua_type(L, 1) == LUA_TLIGHTFUNCTION) {
lua_pushvalue(L, 1); // copy argument (func) to the top of stack
......@@ -450,6 +449,42 @@ static int node_compile( lua_State* L )
return 0;
}
// Task callback handler for node.task.post()
static task_handle_t do_node_task_handle;
static void do_node_task (task_param_t task_fn_ref, uint8_t prio)
{
lua_State* L = lua_getstate();
lua_rawgeti(L, LUA_REGISTRYINDEX, (int)task_fn_ref);
luaL_unref(L, LUA_REGISTRYINDEX, (int)task_fn_ref);
lua_pushinteger(L, prio);
lua_call(L, 1, 0);
}
// Lua: node.task.post([priority],task_cb) -- schedule a task for execution next
static int node_task_post( lua_State* L )
{
int n = 1, Ltype = lua_type(L, 1);
unsigned priority = TASK_PRIORITY_MEDIUM;
if (Ltype == LUA_TNUMBER) {
priority = (unsigned) luaL_checkint(L, 1);
luaL_argcheck(L, priority <= TASK_PRIORITY_HIGH, 1, "invalid priority");
Ltype = lua_type(L, ++n);
}
luaL_argcheck(L, Ltype == LUA_TFUNCTION || Ltype == LUA_TLIGHTFUNCTION, n, "invalid function");
lua_pushvalue(L, n);
int task_fn_ref = luaL_ref(L, LUA_REGISTRYINDEX);
if (!do_node_task_handle) // bind the task handle to do_node_task on 1st call
do_node_task_handle = task_get_id(do_node_task);
if(!task_post(priority, do_node_task_handle, (task_param_t)task_fn_ref)) {
luaL_unref(L, LUA_REGISTRYINDEX, task_fn_ref);
luaL_error(L, "Task queue overflow. Task not posted");
}
return 0;
}
// Lua: setcpufreq(mhz)
// mhz is either CPU80MHZ od CPU160MHZ
static int node_setcpufreq(lua_State* L)
......@@ -468,18 +503,24 @@ static int node_setcpufreq(lua_State* L)
return 1;
}
// Lua: code = bootreason()
// Lua: code, reason [, exccause, epc1, epc2, epc3, excvaddr, depc ] = bootreason()
static int node_bootreason (lua_State *L)
{
lua_pushnumber (L, rtc_get_reset_reason ());
return 1;
const struct rst_info *ri = system_get_rst_info ();
uint32_t arr[8] = {
rtc_get_reset_reason(),
ri->reason,
ri->exccause, ri->epc1, ri->epc2, ri->epc3, ri->excvaddr, ri->depc
};
int i, n = ((ri->reason != REASON_EXCEPTION_RST) ? 2 : 8);
for (i = 0; i < n; ++i)
lua_pushinteger (L, arr[i]);
return n;
}
// Lua: restore()
static int node_restore (lua_State *L)
{
flash_init_data_default();
flash_init_data_blank();
system_restore();
return 0;
}
......@@ -547,7 +588,52 @@ static int node_stripdebug (lua_State *L) {
}
#endif
// Lua: node.egc.setmode( mode, [param])
// where the mode is one of the node.egc constants NOT_ACTIVE , ON_ALLOC_FAILURE,
// ON_MEM_LIMIT, ALWAYS. In the case of ON_MEM_LIMIT an integer parameter is reqired
// See legc.h and lecg.c.
static int node_egc_setmode(lua_State* L) {
unsigned mode = luaL_checkinteger(L, 1);
unsigned limit = luaL_optinteger (L, 2, 0);
luaL_argcheck(L, mode <= (EGC_ON_ALLOC_FAILURE | EGC_ON_MEM_LIMIT | EGC_ALWAYS), 1, "invalid mode");
luaL_argcheck(L, !(mode & EGC_ON_MEM_LIMIT) || limit>0, 1, "limit must be non-zero");
legc_set_mode( L, mode, limit );
return 0;
}
//
// Lua: osprint(true/false)
// Allows you to turn on the native Espressif SDK printing
static int node_osprint( lua_State* L )
{
if (lua_toboolean(L, 1)) {
system_set_os_print(1);
} else {
system_set_os_print(0);
}
return 0;
}
// Module function map
static const LUA_REG_TYPE node_egc_map[] = {
{ LSTRKEY( "setmode" ), LFUNCVAL( node_egc_setmode ) },
{ LSTRKEY( "NOT_ACTIVE" ), LNUMVAL( EGC_NOT_ACTIVE ) },
{ LSTRKEY( "ON_ALLOC_FAILURE" ), LNUMVAL( EGC_ON_ALLOC_FAILURE ) },
{ LSTRKEY( "ON_MEM_LIMIT" ), LNUMVAL( EGC_ON_MEM_LIMIT ) },
{ LSTRKEY( "ALWAYS" ), LNUMVAL( EGC_ALWAYS ) },
{ LNILKEY, LNILVAL }
};
static const LUA_REG_TYPE node_task_map[] = {
{ LSTRKEY( "post" ), LFUNCVAL( node_task_post ) },
{ LSTRKEY( "LOW_PRIORITY" ), LNUMVAL( TASK_PRIORITY_LOW ) },
{ LSTRKEY( "MEDIUM_PRIORITY" ), LNUMVAL( TASK_PRIORITY_MEDIUM ) },
{ LSTRKEY( "HIGH_PRIORITY" ), LNUMVAL( TASK_PRIORITY_HIGH ) },
{ LNILKEY, LNILVAL }
};
static const LUA_REG_TYPE node_map[] =
{
{ LSTRKEY( "restart" ), LFUNCVAL( node_restart ) },
......@@ -574,6 +660,11 @@ static const LUA_REG_TYPE node_map[] =
#ifdef LUA_OPTIMIZE_DEBUG
{ 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
// Combined to dsleep(us, option)
// { LSTRKEY( "dsleepsetoption" ), LFUNCVAL( node_deepsleep_setoption) },
......
//
// This module allows performance monitoring by looking at
// the PC at regular intervals and building a histogram
//
// perf.start(start, end, nbins[, pc offset on stack])
// perf.stop() -> total sample, samples outside range, table { addr -> count , .. }
#include "ets_sys.h"
#include "os_type.h"
#include "osapi.h"
#include "c_stdlib.h"
#include "module.h"
#include "lauxlib.h"
#include "platform.h"
#include "hw_timer.h"
#include "cpu_esp8266.h"
typedef struct {
int ref;
uint32_t start;
uint32_t bucket_shift;
uint32_t bucket_count;
uint32_t total_samples;
uint32_t outside_samples;
uint32_t pc_offset;
uint32_t bucket[1];
} DATA;
static DATA *data;
extern char _flash_used_end[];
#define TIMER_OWNER ((os_param_t) 'p')
static void ICACHE_RAM_ATTR hw_timer_cb(os_param_t p)
{
(void) p;
uint32_t stackaddr;
if (data) {
uint32_t pc = *(&stackaddr + data->pc_offset);
uint32_t bucket_number = (pc - data->start) >> data->bucket_shift;
if (bucket_number < data->bucket_count) {
data->bucket[bucket_number]++;
} else {
data->outside_samples++;
}
data->total_samples++;
}
}
static int perf_start(lua_State *L)
{
uint32_t start = luaL_optinteger(L, 1, 0x40000000);
uint32_t end = luaL_optinteger(L, 2, (uint32_t) _flash_used_end);
uint32_t bins = luaL_optinteger(L, 3, 1024);
if (end <= start) {
luaL_error(L, "end must be larger than start");
}
uint32_t binsize = (end - start + bins - 1) / bins;
// Round up to a power of two
int shift;
binsize = binsize - 1;
for (shift = 0; binsize > 0; shift++) {
binsize >>= 1;
}
bins = (end - start + (1 << shift) - 1) / (1 << shift);
int pc_offset = 20; // This appears to be correct
if (lua_gettop(L) >= 4) {
pc_offset = luaL_checkinteger(L, 4);
}
size_t data_size = sizeof(DATA) + bins * sizeof(uint32_t);
DATA *d = (DATA *) lua_newuserdata(L, data_size);
memset(d, 0, data_size);
d->ref = luaL_ref(L, LUA_REGISTRYINDEX);
d->start = start;
d->bucket_shift = shift;
d->bucket_count = bins;
d->pc_offset = pc_offset;
if (data) {
lua_unref(L, data->ref);
}
data = d;
// Start the timer
if (!platform_hw_timer_init(TIMER_OWNER, NMI_SOURCE, TRUE)) {
// Failed to init the timer
data = NULL;
lua_unref(L, d->ref);
luaL_error(L, "Unable to initialize timer");
}
platform_hw_timer_set_func(TIMER_OWNER, hw_timer_cb, 0);
platform_hw_timer_arm_us(TIMER_OWNER, 50);
return 0;
}
static int perf_stop(lua_State *L)
{
if (!data) {
return 0;
}
// stop the timer
platform_hw_timer_close(TIMER_OWNER);
DATA *d = data;
data = NULL;
lua_pushnumber(L, d->total_samples);
lua_pushnumber(L, d->outside_samples);
lua_newtable(L);
int i;
uint32_t addr = d->start;
for (i = 0; i < d->bucket_count; i++, addr += (1 << d->bucket_shift)) {
if (d->bucket[i]) {
lua_pushnumber(L, addr);
lua_pushnumber(L, d->bucket[i]);
lua_settable(L, -3);
}
}
lua_pushnumber(L, 1 << d->bucket_shift);
lua_unref(L, d->ref);
return 4;
}
static const LUA_REG_TYPE perf_map[] = {
{ LSTRKEY( "start" ), LFUNCVAL( perf_start ) },
{ LSTRKEY( "stop" ), LFUNCVAL( perf_stop ) },
{ LNILKEY, LNILVAL }
};
NODEMCU_MODULE(PERF, "perf", perf_map, NULL);
......@@ -47,7 +47,9 @@ static int lpwm_start( lua_State* L )
unsigned id;
id = luaL_checkinteger( L, 1 );
MOD_CHECK_ID( pwm, id );
platform_pwm_start( id );
if (!platform_pwm_start( id )) {
return luaL_error(L, "Unable to start PWM output");
}
return 0;
}
......@@ -120,6 +122,11 @@ static int lpwm_getduty( lua_State* L )
return 1;
}
int lpwm_open( lua_State *L ) {
platform_pwm_init();
return 0;
}
// Module function map
static const LUA_REG_TYPE pwm_map[] = {
{ LSTRKEY( "setup" ), LFUNCVAL( lpwm_setup ) },
......@@ -133,4 +140,4 @@ static const LUA_REG_TYPE pwm_map[] = {
{ LNILKEY, LNILVAL }
};
NODEMCU_MODULE(PWM, "pwm", pwm_map, NULL);
NODEMCU_MODULE(PWM, "pwm", pwm_map, lpwm_open);
#include "module.h"
#include "lauxlib.h"
#include "platform.h"
#include "rom.h"
//#include "driver/easygpio.h"
//static Ping_Data pingA;
#define defPulseLen 185
......
/*
* Module for interfacing with cheap rotary switches that
* are much used in the automtive industry as the cntrols for
* CD players and the like.
*
* Philip Gladstone, N1DQ
*/
#include "module.h"
#include "lauxlib.h"
#include "platform.h"
#include "c_types.h"
#include "user_interface.h"
#include "driver/rotary.h"
#include "../libc/c_stdlib.h"
#define MASK(x) (1 << ROTARY_ ## x ## _INDEX)
#define ROTARY_PRESS_INDEX 0
#define ROTARY_LONGPRESS_INDEX 1
#define ROTARY_RELEASE_INDEX 2
#define ROTARY_TURN_INDEX 3
#define ROTARY_CLICK_INDEX 4
#define ROTARY_DBLCLICK_INDEX 5
#define ROTARY_ALL 0x3f
#define LONGPRESS_DELAY_US 500000
#define CLICK_DELAY_US 500000
#define CALLBACK_COUNT 6
#ifdef LUA_USE_MODULES_ROTARY
#if !defined(GPIO_INTERRUPT_ENABLE) || !defined(GPIO_INTERRUPT_HOOK_ENABLE)
#error Must have GPIO_INTERRUPT and GPIO_INTERRUPT_HOOK if using ROTARY module
#endif
#endif
typedef struct {
int lastpos;
int last_recent_event_was_press : 1;
int last_recent_event_was_release : 1;
int timer_running : 1;
int possible_dbl_click : 1;
uint8_t id;
int click_delay_us;
int longpress_delay_us;
uint32_t last_event_time;
int callback[CALLBACK_COUNT];
ETSTimer timer;
} DATA;
static DATA *data[ROTARY_CHANNEL_COUNT];
static task_handle_t tasknumber;
static void lrotary_timer_done(void *param);
static void lrotary_check_timer(DATA *d, uint32_t time_us, bool dotimer);
static void callback_free_one(lua_State *L, int *cb_ptr)
{
if (*cb_ptr != LUA_NOREF) {
luaL_unref(L, LUA_REGISTRYINDEX, *cb_ptr);
*cb_ptr = LUA_NOREF;
}
}
static void callback_free(lua_State* L, unsigned int id, int mask)
{
DATA *d = data[id];
if (d) {
int i;
for (i = 0; i < CALLBACK_COUNT; i++) {
if (mask & (1 << i)) {
callback_free_one(L, &d->callback[i]);
}
}
}
}
static int callback_setOne(lua_State* L, int *cb_ptr, int arg_number)
{
if (lua_type(L, arg_number) == LUA_TFUNCTION || lua_type(L, arg_number) == LUA_TLIGHTFUNCTION) {
lua_pushvalue(L, arg_number); // copy argument (func) to the top of stack
callback_free_one(L, cb_ptr);
*cb_ptr = luaL_ref(L, LUA_REGISTRYINDEX);
return 0;
}
return -1;
}
static int callback_set(lua_State* L, int id, int mask, int arg_number)
{
DATA *d = data[id];
int result = 0;
int i;
for (i = 0; i < CALLBACK_COUNT; i++) {
if (mask & (1 << i)) {
result |= callback_setOne(L, &d->callback[i], arg_number);
}
}
return result;
}
static void callback_callOne(lua_State* L, int cb, int mask, int arg, uint32_t time)
{
if (cb != LUA_NOREF) {
lua_rawgeti(L, LUA_REGISTRYINDEX, cb);
lua_pushinteger(L, mask);
lua_pushinteger(L, arg);
lua_pushinteger(L, time);
lua_call(L, 3, 0);
}
}
static void callback_call(lua_State* L, DATA *d, int cbnum, int arg, uint32_t time)
{
if (d) {
callback_callOne(L, d->callback[cbnum], 1 << cbnum, arg, time);
}
}
int platform_rotary_exists( unsigned int id )
{
return (id < ROTARY_CHANNEL_COUNT);
}
// Lua: setup(id, phase_a, phase_b [, press])
static int lrotary_setup( lua_State* L )
{
unsigned int id;
id = luaL_checkinteger( L, 1 );
MOD_CHECK_ID( rotary, id );
if (rotary_close(id)) {
return luaL_error( L, "Unable to close switch." );
}
callback_free(L, id, ROTARY_ALL);
if (!data[id]) {
data[id] = (DATA *) c_zalloc(sizeof(DATA));
if (!data[id]) {
return -1;
}
}
DATA *d = data[id];
memset(d, 0, sizeof(*d));
os_timer_setfn(&d->timer, lrotary_timer_done, (void *) d);
int i;
for (i = 0; i < CALLBACK_COUNT; i++) {
d->callback[i] = LUA_NOREF;
}
d->click_delay_us = CLICK_DELAY_US;
d->longpress_delay_us = LONGPRESS_DELAY_US;
int phase_a = luaL_checkinteger(L, 2);
luaL_argcheck(L, platform_gpio_exists(phase_a) && phase_a > 0, 2, "Invalid pin");
int phase_b = luaL_checkinteger(L, 3);
luaL_argcheck(L, platform_gpio_exists(phase_b) && phase_b > 0, 3, "Invalid pin");
int press;
if (lua_gettop(L) >= 4) {
press = luaL_checkinteger(L, 4);
luaL_argcheck(L, platform_gpio_exists(press) && press > 0, 4, "Invalid pin");
} else {
press = -1;
}
if (lua_gettop(L) >= 5) {
d->longpress_delay_us = 1000 * luaL_checkinteger(L, 5);
luaL_argcheck(L, d->longpress_delay_us > 0, 5, "Invalid timeout");
}
if (lua_gettop(L) >= 6) {
d->click_delay_us = 1000 * luaL_checkinteger(L, 6);
luaL_argcheck(L, d->click_delay_us > 0, 6, "Invalid timeout");
}
if (rotary_setup(id, phase_a, phase_b, press, tasknumber)) {
return luaL_error(L, "Unable to setup rotary switch.");
}
return 0;
}
// Lua: close( id )
static int lrotary_close( lua_State* L )
{
unsigned int id;
id = luaL_checkinteger( L, 1 );
MOD_CHECK_ID( rotary, id );
callback_free(L, id, ROTARY_ALL);
DATA *d = data[id];
if (d) {
data[id] = NULL;
c_free(d);
}
if (rotary_close( id )) {
return luaL_error( L, "Unable to close switch." );
}
return 0;
}
// Lua: on( id, mask[, cb] )
static int lrotary_on( lua_State* L )
{
unsigned int id;
id = luaL_checkinteger( L, 1 );
MOD_CHECK_ID( rotary, id );
int mask = luaL_checkinteger(L, 2);
if (lua_gettop(L) >= 3) {
if (callback_set(L, id, mask, 3)) {
return luaL_error( L, "Unable to set callback." );
}
} else {
callback_free(L, id, mask);
}
return 0;
}
// Lua: getpos( id ) -> pos, PRESS/RELEASE
static int lrotary_getpos( lua_State* L )
{
unsigned int id;
id = luaL_checkinteger( L, 1 );
MOD_CHECK_ID( rotary, id );
int pos = rotary_getpos(id);
if (pos == -1) {
return 0;
}
lua_pushnumber(L, (pos << 1) >> 1);
lua_pushnumber(L, (pos & 0x80000000) ? MASK(PRESS) : MASK(RELEASE));
return 2;
}
// Returns TRUE if there maybe/is more stuff to do
static bool lrotary_dequeue_single(lua_State* L, DATA *d)
{
bool something_pending = FALSE;
if (d) {
// This chnnel is open
rotary_event_t result;
if (rotary_getevent(d->id, &result)) {
int pos = result.pos;
lrotary_check_timer(d, result.time_us, 0);
if (pos != d->lastpos) {
// We have something to enqueue
if ((pos ^ d->lastpos) & 0x7fffffff) {
// Some turning has happened
callback_call(L, d, ROTARY_TURN_INDEX, (pos << 1) >> 1, result.time_us);
}
if ((pos ^ d->lastpos) & 0x80000000) {
// pressing or releasing has happened
callback_call(L, d, (pos & 0x80000000) ? ROTARY_PRESS_INDEX : ROTARY_RELEASE_INDEX, (pos << 1) >> 1, result.time_us);
if (pos & 0x80000000) {
// Press
if (d->last_recent_event_was_release && result.time_us - d->last_event_time < d->click_delay_us) {
d->possible_dbl_click = 1;
}
d->last_recent_event_was_press = 1;
d->last_recent_event_was_release = 0;
} else {
// Release
d->last_recent_event_was_press = 0;
if (d->possible_dbl_click) {
callback_call(L, d, ROTARY_DBLCLICK_INDEX, (pos << 1) >> 1, result.time_us);
d->possible_dbl_click = 0;
// Do this to suppress the CLICK event
d->last_recent_event_was_release = 0;
} else {
d->last_recent_event_was_release = 1;
}
}
d->last_event_time = result.time_us;
}
d->lastpos = pos;
}
something_pending = rotary_has_queued_event(d->id);
}
lrotary_check_timer(d, system_get_time(), 1);
}
return something_pending;
}
static void lrotary_timer_done(void *param)
{
DATA *d = (DATA *) param;
d->timer_running = 0;
lrotary_check_timer(d, system_get_time(), 1);
}
static void lrotary_check_timer(DATA *d, uint32_t time_us, bool dotimer)
{
uint32_t delay = time_us - d->last_event_time;
if (d->timer_running) {
os_timer_disarm(&d->timer);
d->timer_running = 0;
}
int timeout = -1;
if (d->last_recent_event_was_press) {
if (delay > d->longpress_delay_us) {
callback_call(lua_getstate(), d, ROTARY_LONGPRESS_INDEX, (d->lastpos << 1) >> 1, d->last_event_time + d->longpress_delay_us);
d->last_recent_event_was_press = 0;
} else {
timeout = (d->longpress_delay_us - delay) / 1000;
}
}
if (d->last_recent_event_was_release) {
if (delay > d->click_delay_us) {
callback_call(lua_getstate(), d, ROTARY_CLICK_INDEX, (d->lastpos << 1) >> 1, d->last_event_time + d->click_delay_us);
d->last_recent_event_was_release = 0;
} else {
timeout = (d->click_delay_us - delay) / 1000;
}
}
if (dotimer && timeout >= 0) {
d->timer_running = 1;
os_timer_arm(&d->timer, timeout + 1, 0);
}
}
static void lrotary_task(os_param_t param, uint8_t prio)
{
(void) param;
(void) prio;
uint8_t *task_queue_ptr = (uint8_t*) param;
if (task_queue_ptr) {
// Signal that new events may need another task post
*task_queue_ptr = 0;
}
int id;
bool need_to_post = FALSE;
lua_State *L = lua_getstate();
for (id = 0; id < ROTARY_CHANNEL_COUNT; id++) {
DATA *d = data[id];
if (d) {
if (lrotary_dequeue_single(L, d)) {
need_to_post = TRUE;
}
}
}
if (need_to_post) {
// If there is pending stuff, queue another task
task_post_medium(tasknumber, 0);
}
}
static int rotary_open(lua_State *L)
{
tasknumber = task_get_id(lrotary_task);
return 0;
}
// Module function map
static const LUA_REG_TYPE rotary_map[] = {
{ LSTRKEY( "setup" ), LFUNCVAL( lrotary_setup ) },
{ LSTRKEY( "close" ), LFUNCVAL( lrotary_close ) },
{ LSTRKEY( "on" ), LFUNCVAL( lrotary_on ) },
{ LSTRKEY( "getpos" ), LFUNCVAL( lrotary_getpos) },
{ LSTRKEY( "TURN" ), LNUMVAL( MASK(TURN) ) },
{ LSTRKEY( "PRESS" ), LNUMVAL( MASK(PRESS) ) },
{ LSTRKEY( "RELEASE" ), LNUMVAL( MASK(RELEASE) ) },
{ LSTRKEY( "LONGPRESS" ),LNUMVAL( MASK(LONGPRESS) ) },
{ LSTRKEY( "CLICK" ), LNUMVAL( MASK(CLICK) ) },
{ LSTRKEY( "DBLCLICK" ), LNUMVAL( MASK(DBLCLICK)) },
{ LSTRKEY( "ALL" ), LNUMVAL( ROTARY_ALL ) },
{ LNILKEY, LNILVAL }
};
NODEMCU_MODULE(ROTARY, "rotary", rotary_map, rotary_open);
......@@ -87,7 +87,7 @@ static void do_sleep_opt (lua_State *L, int idx)
uint32_t opt = lua_tonumber (L, idx);
if (opt < 0 || opt > 4)
luaL_error (L, "unknown sleep option");
deep_sleep_set_option (opt);
system_deep_sleep_set_option (opt);
}
}
......
// Module for interfacing with sigma-delta hardware
#include "module.h"
#include "lauxlib.h"
#include "platform.h"
// Lua: setup( pin )
static int sigma_delta_setup( lua_State *L )
{
int pin = luaL_checkinteger( L, 1 );
MOD_CHECK_ID(sigma_delta, pin);
platform_sigma_delta_setup( pin );
return 0;
}
// Lua: close( pin )
static int sigma_delta_close( lua_State *L )
{
int pin = luaL_checkinteger( L, 1 );
MOD_CHECK_ID(sigma_delta, pin);
platform_sigma_delta_close( pin );
return 0;
}
// Lua: setpwmduty( duty_cycle )
static int sigma_delta_setpwmduty( lua_State *L )
{
int duty = luaL_checkinteger( L, 1 );
if (duty < 0 || duty > 255) {
return luaL_error( L, "wrong arg range" );
}
platform_sigma_delta_set_pwmduty( duty );
return 0;
}
// Lua: setprescale( value )
static int sigma_delta_setprescale( lua_State *L )
{
int prescale = luaL_checkinteger( L, 1 );
if (prescale < 0 || prescale > 255) {
return luaL_error( L, "wrong arg range" );
}
platform_sigma_delta_set_prescale( prescale );
return 0;
}
// Lua: settarget( value )
static int sigma_delta_settarget( lua_State *L )
{
int target = luaL_checkinteger( L, 1 );
if (target < 0 || target > 255) {
return luaL_error( L, "wrong arg range" );
}
platform_sigma_delta_set_target( target );
return 0;
}
// Module function map
static const LUA_REG_TYPE sigma_delta_map[] =
{
{ LSTRKEY( "setup" ), LFUNCVAL( sigma_delta_setup ) },
{ LSTRKEY( "close" ), LFUNCVAL( sigma_delta_close ) },
{ LSTRKEY( "setpwmduty" ), LFUNCVAL( sigma_delta_setpwmduty ) },
{ LSTRKEY( "setprescale" ), LFUNCVAL( sigma_delta_setprescale ) },
{ LSTRKEY( "settarget" ), LFUNCVAL( sigma_delta_settarget ) },
{ LNILKEY, LNILVAL }
};
NODEMCU_MODULE(SIGMA_DELTA, "sigma_delta", sigma_delta_map, NULL);
......@@ -41,6 +41,7 @@
#include "c_stdlib.h"
#include "user_modules.h"
#include "lwip/dns.h"
#include "user_interface.h"
#ifdef LUA_USE_MODULES_RTCTIME
#include "rtc/rtctime.h"
......@@ -57,6 +58,14 @@
# define sntp_dbg(...)
#endif
typedef enum {
NTP_NO_ERR = 0,
NTP_DNS_ERR,
NTP_MEM_ERR,
NTP_SEND_ERR,
NTP_TIMEOUT_ERR
} ntp_err_t;
typedef struct
{
uint32_t sec;
......@@ -93,6 +102,8 @@ typedef struct
static sntp_state_t *state;
static ip_addr_t server;
static void on_timeout (void *arg);
static void cleanup (lua_State *L)
{
os_timer_disarm (&state->timer);
......@@ -104,14 +115,15 @@ static void cleanup (lua_State *L)
}
static void handle_error (lua_State *L)
static void handle_error (lua_State *L, ntp_err_t err)
{
sntp_dbg("sntp: handle_error\n");
if (state->err_cb_ref != LUA_NOREF)
{
lua_rawgeti (L, LUA_REGISTRYINDEX, state->err_cb_ref);
lua_pushinteger (L, err);
cleanup (L);
lua_call (L, 0, 0);
lua_call (L, 1, 0);
}
else
cleanup (L);
......@@ -120,12 +132,19 @@ static void handle_error (lua_State *L)
static void sntp_dosend (lua_State *L)
{
if (state->attempts == 0)
{
os_timer_disarm (&state->timer);
os_timer_setfn (&state->timer, on_timeout, NULL);
os_timer_arm (&state->timer, 1000, 1);
}
++state->attempts;
sntp_dbg("sntp: attempt %d\n", state->attempts);
struct pbuf *p = pbuf_alloc (PBUF_TRANSPORT, sizeof (ntp_frame_t), PBUF_RAM);
if (!p)
handle_error (L);
handle_error (L, NTP_MEM_ERR);
ntp_frame_t req;
os_memset (&req, 0, sizeof (req));
......@@ -146,17 +165,19 @@ static void sntp_dosend (lua_State *L)
sntp_dbg("sntp: send: %d\n", ret);
pbuf_free (p);
if (ret != ERR_OK)
handle_error (L);
handle_error (L, NTP_SEND_ERR);
}
static void sntp_dns_found(const char *name, ip_addr_t *ipaddr, void *arg)
{
lua_State *L = arg;
(void)arg;
lua_State *L = lua_getstate ();
if (ipaddr == NULL)
{
NODE_ERR("DNS Fail!\n");
handle_error(L);
sntp_dbg("DNS Fail!\n");
handle_error(L, NTP_DNS_ERR);
}
else
{
......@@ -168,10 +189,11 @@ static void sntp_dns_found(const char *name, ip_addr_t *ipaddr, void *arg)
static void on_timeout (void *arg)
{
(void)arg;
sntp_dbg("sntp: timer\n");
lua_State *L = arg;
lua_State *L = lua_getstate ();
if (state->attempts >= MAX_ATTEMPTS)
handle_error (L);
handle_error (L, NTP_TIMEOUT_ERR);
else
sntp_dosend (L);
}
......@@ -319,8 +341,8 @@ static int sntp_sync (lua_State *L)
if (!state->pcb)
sync_err ("out of memory");
if (udp_bind (state->pcb, IP_ADDR_ANY, NTP_PORT) != ERR_OK)
sync_err ("ntp port in use");
if (udp_bind (state->pcb, IP_ADDR_ANY, 0) != ERR_OK)
sync_err ("no port available");
udp_recv (state->pcb, on_recv, L);
......@@ -340,10 +362,6 @@ static int sntp_sync (lua_State *L)
else
state->err_cb_ref = LUA_NOREF;
os_timer_disarm (&state->timer);
os_timer_setfn (&state->timer, on_timeout, L);
os_timer_arm (&state->timer, 1000, 1);
state->attempts = 0;
// use last server, unless new one specified
......@@ -353,7 +371,7 @@ static int sntp_sync (lua_State *L)
const char *hostname = luaL_checklstring(L, 1, &l);
if (l>128 || hostname == NULL)
sync_err("need <128 hostname");
err_t err = dns_gethostbyname(hostname, &server, sntp_dns_found, &L);
err_t err = dns_gethostbyname(hostname, &server, sntp_dns_found, state);
if (err == ERR_INPROGRESS)
return 0; // Callback function sntp_dns_found will handle sntp_dosend for us
else if (err == ERR_ARG)
......
......@@ -30,10 +30,6 @@ static int spi_setup( lua_State *L )
if (cpol != PLATFORM_SPI_CPOL_LOW && cpol != PLATFORM_SPI_CPOL_HIGH) {
return luaL_error( L, "wrong arg type" );
}
// CPOL_HIGH is not implemented, see app/driver/spi.c spi_master_init()
if (cpol == PLATFORM_SPI_CPOL_HIGH) {
return luaL_error( L, "cpol=high is not implemented" );
}
if (cpha != PLATFORM_SPI_CPHA_LOW && cpha != PLATFORM_SPI_CPHA_HIGH) {
return luaL_error( L, "wrong arg type" );
......@@ -296,7 +292,7 @@ static int spi_transaction( lua_State *L )
return luaL_error( L, "dummy_bitlen out of range" );
}
if (miso_bitlen < -512 || miso_bitlen > 511) {
if (miso_bitlen < -512 || miso_bitlen > 512) {
return luaL_error( L, "miso_bitlen out of range" );
}
......
/*
** {======================================================
** Library for packing/unpacking structures.
** $Id: struct.c,v 1.4 2012/07/04 18:54:29 roberto Exp $
** See Copyright Notice at the end of this file
** =======================================================
*/
// Original: http://www.inf.puc-rio.br/~roberto/struct/
// This was ported to NodeMCU by Philip Gladstone, N1DQ
/*
** Valid formats:
** > - big endian
** < - little endian
** ![num] - alignment
** x - pading
** b/B - signed/unsigned byte
** h/H - signed/unsigned short
** l/L - signed/unsigned long
** T - size_t
** i/In - signed/unsigned integer with size `n' (default is size of int)
** cn - sequence of `n' chars (from/to a string); when packing, n==0 means
the whole string; when unpacking, n==0 means use the previous
read number as the string length
** s - zero-terminated string
** f - float
** d - double
** ' ' - ignored
*/
#include <assert.h>
#include <ctype.h>
#include <limits.h>
#include <stddef.h>
#include <string.h>
#include "module.h"
#include "lua.h"
#include "lauxlib.h"
/* basic integer type */
#if !defined(STRUCT_INT)
#define STRUCT_INT long
#endif
typedef STRUCT_INT Inttype;
/* corresponding unsigned version */
typedef unsigned STRUCT_INT Uinttype;
/* maximum size (in bytes) for integral types */
#ifdef LUA_NUMBER_INTEGRAL
#ifdef LUA_INTEGRAL_LONGLONG
#define MAXINTSIZE 8
#else
#define MAXINTSIZE 4
#endif
#else
#define MAXINTSIZE 32
#endif
/* is 'x' a power of 2? */
#define isp2(x) ((x) > 0 && ((x) & ((x) - 1)) == 0)
/* dummy structure to get alignment requirements */
struct cD {
char c;
double d;
};
#define PADDING (sizeof(struct cD) - sizeof(double))
#define MAXALIGN (PADDING > sizeof(int) ? PADDING : sizeof(int))
/* endian options */
#define BIG 0
#define LITTLE 1
static union {
int dummy;
char endian;
} const native = {1};
typedef struct Header {
int endian;
int align;
} Header;
static int getnum (const char **fmt, int df) {
if (!isdigit(**fmt)) /* no number? */
return df; /* return default value */
else {
int a = 0;
do {
a = a*10 + *((*fmt)++) - '0';
} while (isdigit(**fmt));
return a;
}
}
#define defaultoptions(h) ((h)->endian = native.endian, (h)->align = 1)
static size_t optsize (lua_State *L, char opt, const char **fmt) {
switch (opt) {
case 'B': case 'b': return sizeof(char);
case 'H': case 'h': return sizeof(short);
case 'L': case 'l': return sizeof(long);
case 'T': return sizeof(size_t);
#ifndef LUA_NUMBER_INTEGRAL
case 'f': return sizeof(float);
case 'd': return sizeof(double);
#endif
case 'x': return 1;
case 'c': return getnum(fmt, 1);
case 'i': case 'I': {
int sz = getnum(fmt, sizeof(int));
if (sz > MAXINTSIZE)
luaL_error(L, "integral size %d is larger than limit of %d",
sz, MAXINTSIZE);
return sz;
}
default: return 0; /* other cases do not need alignment */
}
}
/*
** return number of bytes needed to align an element of size 'size'
** at current position 'len'
*/
static int gettoalign (size_t len, Header *h, int opt, size_t size) {
if (size == 0 || opt == 'c') return 0;
if (size > (size_t)h->align)
size = h->align; /* respect max. alignment */
return (size - (len & (size - 1))) & (size - 1);
}
/*
** options to control endianess and alignment
*/
static void controloptions (lua_State *L, int opt, const char **fmt,
Header *h) {
switch (opt) {
case ' ': return; /* ignore white spaces */
case '>': h->endian = BIG; return;
case '<': h->endian = LITTLE; return;
case '!': {
int a = getnum(fmt, MAXALIGN);
if (!isp2(a))
luaL_error(L, "alignment %d is not a power of 2", a);
h->align = a;
return;
}
default: {
const char *msg = lua_pushfstring(L, "invalid format option '%c'", opt);
luaL_argerror(L, 1, msg);
}
}
}
static void putinteger (lua_State *L, luaL_Buffer *b, int arg, int endian,
int size) {
lua_Number n = luaL_checknumber(L, arg);
Uinttype value;
char buff[MAXINTSIZE];
if (n < 0)
value = (Uinttype)(Inttype)n;
else
value = (Uinttype)n;
if (endian == LITTLE) {
int i;
for (i = 0; i < size; i++) {
buff[i] = (value & 0xff);
value >>= 8;
}
}
else {
int i;
for (i = size - 1; i >= 0; i--) {
buff[i] = (value & 0xff);
value >>= 8;
}
}
luaL_addlstring(b, buff, size);
}
static void correctbytes (char *b, int size, int endian) {
if (endian != native.endian) {
int i = 0;
while (i < --size) {
char temp = b[i];
b[i++] = b[size];
b[size] = temp;
}
}
}
static int b_pack (lua_State *L) {
luaL_Buffer b;
const char *fmt = luaL_checkstring(L, 1);
Header h;
int arg = 2;
size_t totalsize = 0;
defaultoptions(&h);
lua_pushnil(L); /* mark to separate arguments from string buffer */
luaL_buffinit(L, &b);
while (*fmt != '\0') {
int opt = *fmt++;
size_t size = optsize(L, opt, &fmt);
int toalign = gettoalign(totalsize, &h, opt, size);
totalsize += toalign;
while (toalign-- > 0) luaL_addchar(&b, '\0');
switch (opt) {
case 'b': case 'B': case 'h': case 'H':
case 'l': case 'L': case 'T': case 'i': case 'I': { /* integer types */
putinteger(L, &b, arg++, h.endian, size);
break;
}
case 'x': {
luaL_addchar(&b, '\0');
break;
}
#ifndef LUA_NUMBER_INTEGRAL
case 'f': {
float f = (float)luaL_checknumber(L, arg++);
correctbytes((char *)&f, size, h.endian);
luaL_addlstring(&b, (char *)&f, size);
break;
}
case 'd': {
double d = luaL_checknumber(L, arg++);
correctbytes((char *)&d, size, h.endian);
luaL_addlstring(&b, (char *)&d, size);
break;
}
#endif
case 'c': case 's': {
size_t l;
const char *s = luaL_checklstring(L, arg++, &l);
if (size == 0) size = l;
luaL_argcheck(L, l >= (size_t)size, arg, "string too short");
luaL_addlstring(&b, s, size);
if (opt == 's') {
luaL_addchar(&b, '\0'); /* add zero at the end */
size++;
}
break;
}
default: controloptions(L, opt, &fmt, &h);
}
totalsize += size;
}
luaL_pushresult(&b);
return 1;
}
static lua_Number getinteger (const char *buff, int endian,
int issigned, int size) {
Uinttype l = 0;
int i;
if (endian == BIG) {
for (i = 0; i < size; i++) {
l <<= 8;
l |= (Uinttype)(unsigned char)buff[i];
}
}
else {
for (i = size - 1; i >= 0; i--) {
l <<= 8;
l |= (Uinttype)(unsigned char)buff[i];
}
}
if (!issigned)
return (lua_Number)l;
else { /* signed format */
Uinttype mask = (Uinttype)(~((Uinttype)0)) << (size*8 - 1);
if (l & mask) /* negative value? */
l |= mask; /* signal extension */
return (lua_Number)(Inttype)l;
}
}
static int b_unpack (lua_State *L) {
Header h;
const char *fmt = luaL_checkstring(L, 1);
size_t ld;
const char *data = luaL_checklstring(L, 2, &ld);
size_t pos = luaL_optinteger(L, 3, 1) - 1;
defaultoptions(&h);
lua_settop(L, 2);
while (*fmt) {
int opt = *fmt++;
size_t size = optsize(L, opt, &fmt);
pos += gettoalign(pos, &h, opt, size);
luaL_argcheck(L, pos+size <= ld, 2, "data string too short");
luaL_checkstack(L, 1, "too many results");
switch (opt) {
case 'b': case 'B': case 'h': case 'H':
case 'l': case 'L': case 'T': case 'i': case 'I': { /* integer types */
int issigned = islower(opt);
lua_Number res = getinteger(data+pos, h.endian, issigned, size);
lua_pushnumber(L, res);
break;
}
case 'x': {
break;
}
#ifndef LUA_NUMBER_INTEGRAL
case 'f': {
float f;
memcpy(&f, data+pos, size);
correctbytes((char *)&f, sizeof(f), h.endian);
lua_pushnumber(L, f);
break;
}
case 'd': {
double d;
memcpy(&d, data+pos, size);
correctbytes((char *)&d, sizeof(d), h.endian);
lua_pushnumber(L, d);
break;
}
#endif
case 'c': {
if (size == 0) {
if (!lua_isnumber(L, -1))
luaL_error(L, "format `c0' needs a previous size");
size = lua_tonumber(L, -1);
lua_pop(L, 1);
luaL_argcheck(L, pos+size <= ld, 2, "data string too short");
}
lua_pushlstring(L, data+pos, size);
break;
}
case 's': {
const char *e = (const char *)memchr(data+pos, '\0', ld - pos);
if (e == NULL)
luaL_error(L, "unfinished string in data");
size = (e - (data+pos)) + 1;
lua_pushlstring(L, data+pos, size - 1);
break;
}
default: controloptions(L, opt, &fmt, &h);
}
pos += size;
}
lua_pushinteger(L, pos + 1);
return lua_gettop(L) - 2;
}
static int b_size (lua_State *L) {
Header h;
const char *fmt = luaL_checkstring(L, 1);
size_t pos = 0;
defaultoptions(&h);
while (*fmt) {
int opt = *fmt++;
size_t size = optsize(L, opt, &fmt);
pos += gettoalign(pos, &h, opt, size);
if (opt == 's')
luaL_argerror(L, 1, "option 's' has no fixed size");
else if (opt == 'c' && size == 0)
luaL_argerror(L, 1, "option 'c0' has no fixed size");
if (!isalnum(opt))
controloptions(L, opt, &fmt, &h);
pos += size;
}
lua_pushinteger(L, pos);
return 1;
}
/* }====================================================== */
static const LUA_REG_TYPE thislib[] = {
{LSTRKEY("pack"), LFUNCVAL(b_pack)},
{LSTRKEY("unpack"), LFUNCVAL(b_unpack)},
{LSTRKEY("size"), LFUNCVAL(b_size)},
{LNILKEY, LNILVAL}
};
NODEMCU_MODULE(STRUCT, "struct", thislib, NULL);
/******************************************************************************
* Copyright (C) 2010-2012 Lua.org, PUC-Rio. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
******************************************************************************/
......@@ -52,6 +52,7 @@ tmr.softwd(int)
#include "lauxlib.h"
#include "platform.h"
#include "c_types.h"
#include "user_interface.h"
#define TIMER_MODE_OFF 3
#define TIMER_MODE_SINGLE 0
......@@ -59,54 +60,55 @@ tmr.softwd(int)
#define TIMER_MODE_AUTO 1
#define TIMER_IDLE_FLAG (1<<7)
//well, the following are my assumptions
//why, oh why is there no good documentation
//chinese companies should learn from Atmel
extern void ets_timer_arm_new(os_timer_t* t, uint32_t milliseconds, uint32_t repeat_flag, uint32_t isMstimer);
extern void ets_timer_disarm(os_timer_t* t);
extern void ets_timer_setfn(os_timer_t* t, os_timer_func_t *f, void *arg);
extern void ets_delay_us(uint32_t us);
extern uint32_t system_get_time();
extern uint32_t platform_tmr_exists(uint32_t t);
extern uint32_t system_rtc_clock_cali_proc();
extern uint32_t system_get_rtc_time();
extern void system_restart();
extern void system_soft_wdt_feed();
//in fact lua_State is constant, it's pointless to pass it around
//but hey, whatever, I'll just pass it, still we waste 28B here
#define STRINGIFY_VAL(x) #x
#define STRINGIFY(x) STRINGIFY_VAL(x)
// assuming system_timer_reinit() has *not* been called
#define MAX_TIMEOUT_DEF 6870947 //SDK 1.5.3 limit (0x68D7A3)
static const uint32 MAX_TIMEOUT=MAX_TIMEOUT_DEF;
static const char* MAX_TIMEOUT_ERR_STR = "Range: 1-"STRINGIFY(MAX_TIMEOUT_DEF);
typedef struct{
os_timer_t os;
lua_State* L;
sint32_t lua_ref;
uint32_t interval;
uint8_t mode;
}timer_struct_t;
typedef timer_struct_t* timer_t;
//everybody just love unions! riiiiight?
static union {
uint64_t block;
uint32_t part[2];
} rtc_time;
// The previous implementation extended the rtc counter to 64 bits, and then
// applied rtc2sec with the current calibration value to that 64 bit value.
// This means that *ALL* clock ticks since bootup are counted with the *current*
// clock period. In extreme cases (long uptime, sudden temperature change), this
// could result in tmr.time() going backwards....
// This implementation instead applies rtc2usec to short time intervals only (the
// longest being around 1 second), and then accumulates the resulting microseconds
// in a 64 bit counter. That's guaranteed to be monotonic, and should be a lot closer
// to representing an actual uptime.
static uint32_t rtc_time_cali=0;
static uint32_t last_rtc_time=0;
static uint64_t last_rtc_time_us=0;
static sint32_t soft_watchdog = -1;
static timer_struct_t alarm_timers[NUM_TMR];
static os_timer_t rtc_timer;
static void alarm_timer_common(void* arg){
timer_t tmr = &alarm_timers[(uint32_t)arg];
if(tmr->lua_ref == LUA_NOREF || tmr->L == NULL)
lua_State* L = lua_getstate();
if(tmr->lua_ref == LUA_NOREF)
return;
lua_rawgeti(tmr->L, LUA_REGISTRYINDEX, tmr->lua_ref);
lua_rawgeti(L, LUA_REGISTRYINDEX, tmr->lua_ref);
//if the timer was set to single run we clean up after it
if(tmr->mode == TIMER_MODE_SINGLE){
luaL_unref(tmr->L, LUA_REGISTRYINDEX, tmr->lua_ref);
luaL_unref(L, LUA_REGISTRYINDEX, tmr->lua_ref);
tmr->lua_ref = LUA_NOREF;
tmr->mode = TIMER_MODE_OFF;
}else if(tmr->mode == TIMER_MODE_SEMI){
tmr->mode |= TIMER_IDLE_FLAG;
}
lua_call(tmr->L, 0, 0);
lua_call(L, 0, 0);
}
// Lua: tmr.delay( us )
......@@ -136,15 +138,13 @@ static int tmr_now(lua_State* L){
// Lua: tmr.register( id, interval, mode, function )
static int tmr_register(lua_State* L){
uint32_t id = luaL_checkinteger(L, 1);
MOD_CHECK_ID(tmr, id);
sint32_t interval = luaL_checkinteger(L, 2);
uint32_t interval = luaL_checkinteger(L, 2);
uint8_t mode = luaL_checkinteger(L, 3);
//validate arguments
uint8_t args_valid = interval <= 0
|| (mode != TIMER_MODE_SINGLE && mode != TIMER_MODE_SEMI && mode != TIMER_MODE_AUTO)
|| (lua_type(L, 4) != LUA_TFUNCTION && lua_type(L, 4) != LUA_TLIGHTFUNCTION);
if(args_valid)
return luaL_error(L, "wrong arg range");
//Check if provided parameters are valid
MOD_CHECK_ID(tmr, id);
luaL_argcheck(L, (interval > 0 && interval <= MAX_TIMEOUT), 2, MAX_TIMEOUT_ERR_STR);
luaL_argcheck(L, (mode == TIMER_MODE_SINGLE || mode == TIMER_MODE_SEMI || mode == TIMER_MODE_AUTO), 3, "Invalid mode");
luaL_argcheck(L, (lua_type(L, 4) == LUA_TFUNCTION || lua_type(L, 4) == LUA_TLIGHTFUNCTION), 4, "Must be function");
//get the lua function reference
lua_pushvalue(L, 4);
sint32_t ref = luaL_ref(L, LUA_REGISTRYINDEX);
......@@ -157,7 +157,6 @@ static int tmr_register(lua_State* L){
tmr->lua_ref = ref;
tmr->mode = mode|TIMER_IDLE_FLAG;
tmr->interval = interval;
tmr->L = L;
ets_timer_setfn(&tmr->os, alarm_timer_common, (void*)id);
return 0;
}
......@@ -219,9 +218,8 @@ static int tmr_interval(lua_State* L){
uint8_t id = luaL_checkinteger(L, 1);
MOD_CHECK_ID(tmr,id);
timer_t tmr = &alarm_timers[id];
sint32_t interval = luaL_checkinteger(L, 2);
if(interval <= 0)
return luaL_error(L, "wrong arg range");
uint32_t interval = luaL_checkinteger(L, 2);
luaL_argcheck(L, (interval > 0 && interval <= MAX_TIMEOUT), 2, MAX_TIMEOUT_ERR_STR);
if(tmr->mode != TIMER_MODE_OFF){
tmr->interval = interval;
if(!(tmr->mode&TIMER_IDLE_FLAG)){
......@@ -262,28 +260,33 @@ static int tmr_wdclr( lua_State* L ){
//it tells how many rtc clock ticks represent 1us.
//the high 64 bits of the uint64_t multiplication
//are unnedded (I did the math)
static uint32_t rtc2sec(uint64_t rtc){
uint64_t aku = system_rtc_clock_cali_proc();
aku *= rtc;
return (aku>>12)/1000000;
static uint32_t rtc2usec(uint64_t rtc){
return (rtc*rtc_time_cali)>>12;
}
//the following function workes, I just wrote it and didn't use it.
/*static uint64_t sec2rtc(uint32_t sec){
uint64_t aku = (1<<20)/system_rtc_clock_cali_proc();
aku *= sec;
return (aku>>8)*1000000;
}*/
// This returns the number of microseconds uptime. Note that it relies on the rtc clock,
// which is notoriously temperature dependent
inline static uint64_t rtc_timer_update(bool do_calibration){
if (do_calibration || rtc_time_cali==0)
rtc_time_cali=system_rtc_clock_cali_proc();
inline static void rtc_timer_update(){
uint32_t current = system_get_rtc_time();
if(rtc_time.part[0] > current) //overflow check
rtc_time.part[1]++;
rtc_time.part[0] = current;
uint32_t since_last=current-last_rtc_time; // This will transparently deal with wraparound
uint32_t us_since_last=rtc2usec(since_last);
uint64_t now=last_rtc_time_us+us_since_last;
// Only update if at least 100ms has passed since we last updated.
// This prevents the rounding errors in rtc2usec from accumulating
if (us_since_last>=100000)
{
last_rtc_time=current;
last_rtc_time_us=now;
}
return now;
}
void rtc_callback(void *arg){
rtc_timer_update();
rtc_timer_update(true);
if(soft_watchdog > 0){
soft_watchdog--;
if(soft_watchdog == 0)
......@@ -293,8 +296,8 @@ void rtc_callback(void *arg){
// Lua: tmr.time() , return rtc time in second
static int tmr_time( lua_State* L ){
rtc_timer_update();
lua_pushinteger(L, rtc2sec(rtc_time.block));
uint64_t us=rtc_timer_update(false);
lua_pushinteger(L, us/1000000);
return 1;
}
......@@ -332,7 +335,9 @@ int luaopen_tmr( lua_State *L ){
alarm_timers[i].mode = TIMER_MODE_OFF;
ets_timer_disarm(&alarm_timers[i].os);
}
rtc_time.block = 0;
last_rtc_time=system_get_rtc_time(); // Right now is time 0
last_rtc_time_us=0;
ets_timer_disarm(&rtc_timer);
ets_timer_setfn(&rtc_timer, rtc_callback, NULL);
ets_timer_arm_new(&rtc_timer, 1000, 1, 1);
......
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