Commit d515dfd8 authored by Johny Mattsson's avatar Johny Mattsson
Browse files

Merge pull request #1138 from robertfoss/enduser_setup_improvements

Improve overall enduser_setup user experience.
parents 117df40f e1fffe6a
...@@ -35,6 +35,7 @@ ...@@ -35,6 +35,7 @@
#include "module.h" #include "module.h"
#include "lauxlib.h" #include "lauxlib.h"
#include "lmem.h"
#include "platform.h" #include "platform.h"
#include "c_stdlib.h" #include "c_stdlib.h"
#include "c_stdio.h" #include "c_stdio.h"
...@@ -42,6 +43,8 @@ ...@@ -42,6 +43,8 @@
#include "ctype.h" #include "ctype.h"
#include "user_interface.h" #include "user_interface.h"
#include "espconn.h" #include "espconn.h"
#include "lwip/tcp.h"
#include "lwip/pbuf.h"
#include "flash_fs.h" #include "flash_fs.h"
#include "task/task.h" #include "task/task.h"
...@@ -76,6 +79,7 @@ static const char dns_body[] = { 0x00, 0x01, 0x00, 0x01, ...@@ -76,6 +79,7 @@ static const char dns_body[] = { 0x00, 0x01, 0x00, 0x01,
static const char http_html_filename[] = "index.html"; static const char http_html_filename[] = "index.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_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_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_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_404[] = "HTTP/1.1 404 Not found\r\n\r\n";
...@@ -98,40 +102,40 @@ static const char http_header_500[] = "HTTP/1.1 500 Internal Error\r\n\r\n"; ...@@ -98,40 +102,40 @@ static const char http_header_500[] = "HTTP/1.1 500 Internal Error\r\n\r\n";
*{margin:0;padding:0} *{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)} 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} body{font-family:arial,verdana}
div{position:absolute;margin:auto;top:0;right:0;bottom:0;left:0;width:320px;height:304px} 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{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 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 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;} 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;} #msform .submit:focus,form .action-button:hover{box-shadow:0 0 0 2px #fff,0 0 0 3px #27AE60;}
#msform .wifitoggle:focus,form .wifitoggle:hover{box-shadow:0 0 0 2px #fff,0 0 0 3px #ccc;} #formFrame{display: none;}
#aplist{display: block;}
select{width:100%;margin-bottom: 20px;padding: 10px 5px; border:1px solid #ccc;display:none;} 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-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-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} .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; } .submit{width:100px;background: #27AE60; color: #fff;font-weight:700;margin:10px 5px; padding: 10px 5px; }
.wifitoggle{float:right;clear:both;max-width:75%; font-size:11px;background:#ccc; color: #000; margin: 0 0 10px; 0; padding: 5px 10px;}
</style> </style>
</head> </head>
<body> <body>
<div> <div>
<form method="get" action="/update"> <form id="credentialsForm" method="get" action="/update" target="formFrame">
<fieldset> <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> <h2 class="fs-title">WiFi Login</h2>
<h3 class="fs-subtitle">Connect gadget to your WiFi network</h3> <h3 class="fs-subtitle">Connect gadget to your WiFi network</h3>
<input autocorrect="off" autocapitalize="none" name="wifi_ssid" id="ssid" placeholder="WiFi Name"> <input id="wifi_ssid" autocorrect="off" autocapitalize="none" name="wifi_ssid" placeholder="WiFi Name">
<button type='button' class="action-button wifitoggle" id="apbutton" disabled>Searching for networks...</button> <select id="aplist" name="aplist" size="1" disabled>
<select name="aplist" id="aplist" size="2"> <option>Scanning for networks...</option>
</select> </select>
<input name="wifi_password" placeholder="Password" type="password"> <input name="wifi_password" placeholder="Password" type="password">
<input type=submit name=save class='action-button submit' value='Save'> <input type=submit name=save class="action-button submit" value="Save">
<h3 class="fs-status">Status: <span id="status">Updating...</span></h3> <h3 class="fs-status">Status: <span id="status">Updating...</span></h3>
</fieldset> </fieldset>
<h3 id="dbg"></h3>
</form> </form>
</div> </div>
<script> <script>
function aplist() { return document.getElementById("aplist"); }
function fetch(url, method, callback) function fetch(url, method, callback)
{ {
var xhr = new XMLHttpRequest(); var xhr = new XMLHttpRequest();
...@@ -139,12 +143,15 @@ static const char http_header_500[] = "HTTP/1.1 500 Internal Error\r\n\r\n"; ...@@ -139,12 +143,15 @@ static const char http_header_500[] = "HTTP/1.1 500 Internal Error\r\n\r\n";
function check_ready() function check_ready()
{ {
if (xhr.readyState === 4) if (xhr.readyState === 4)
{
callback(xhr.status === 200 ? xhr.responseText : null); callback(xhr.status === 200 ? xhr.responseText : null);
} }
}
xhr.open(method, url, true); xhr.open(method, url, true);
xhr.send(); xhr.send();
} }
function new_status(stat) function new_status(stat)
{ {
if (stat) if (stat)
...@@ -152,91 +159,91 @@ static const char http_header_500[] = "HTTP/1.1 500 Internal Error\r\n\r\n"; ...@@ -152,91 +159,91 @@ static const char http_header_500[] = "HTTP/1.1 500 Internal Error\r\n\r\n";
var e = document.getElementById("status"); var e = document.getElementById("status");
e.innerHTML = stat; e.innerHTML = stat;
} }
setTimeout(refresh_status, 3000);
} }
function refresh_status()
{
fetch('/status','GET',new_status);
}
function refresh_ap_list() function new_status_repeat(stat)
{ {
var sel = aplist (); new_status(stat);
sel.innerHTML = '<option value="" disabled>Scanning...</option>'; setTimeout(refresh_status, 750);
fetch('/aplist','GET', got_ap_list);
} }
function toggle_aplist(ev, force)
{
var sel = aplist();
var btn = document.getElementById("apbutton");
if (force || sel.style.display == 'block')
{
sel.style.display = 'none';
btn.innerHTML = 'Show networks';
}
else
{
sel.style.display = 'block';
btn.innerHTML = 'Hide networks';
}
}
function got_ap_list(json) function new_ap_list(json)
{ {
var btn = document.getElementById("apbutton");
if (json) if (json)
{ {
var list = JSON.parse(json); var list = JSON.parse(json);
list.sort(function(a,b){ return b.rssi - a.rssi; }); 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 ssids = list.map(function(a) { return a.ssid; }).filter(function(item, pos, self) { return self.indexOf(item)==pos; });
var sel = aplist(); var sel = document.getElementById("aplist");
sel.innerHTML = ""; sel.innerHTML = "";
sel.setAttribute("size", Math.max(Math.min(5, list.length), 2)); sel.setAttribute("size", Math.max(Math.min(3, list.length), 1));
sel.removeAttribute("disabled");
for (var i = 0; i < ssids.length; ++i) for (var i = 0; i < ssids.length; ++i)
{ {
var o = document.createElement("option"); var o = document.createElement("option");
sel.options.add(o);
o.innerHTML = ssids[i]; o.innerHTML = ssids[i];
sel.options.add(o);
} }
btn.disabled = false; sel.style.display = 'block';
toggle_aplist(null, true);
btn.onclick = toggle_aplist;
} }
else }
function new_ap_list_repeat(json)
{
new_ap_list(json);
setTimeout(refresh_ap_list, 3000);
}
function refresh_status()
{ {
btn.innerHTML = "No networks found"; fetch('/status','GET', new_status_repeat);
} }
function refresh_ap_list()
{
fetch('/aplist','GET', new_ap_list_repeat);
} }
window.onload=function()
window.onload = function()
{ {
refresh_status(); refresh_status();
refresh_ap_list(); refresh_ap_list();
aplist().onchange = function() { document.getElementById("ssid").value = aplist().value; } document.getElementById("aplist").onchange = function() {
var sel = document.getElementById("aplist");
document.getElementById("wifi_ssid").value = sel.value;
}
document.getElementById("credentialsForm").addEventListener("submit", function(){
fetch('/status','GET', new_status);
});
} }
</script> </script>
</body> </body>
</html> </html>
#endif #endif
static const char http_html_backup[] = static const char http_html_backup[] =
"<!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:0;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}#msform .wifitoggle:focus,form .wifitoggle:hover{box-shadow:0 0 0 2px #fff,0 0 0 3px #ccc}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}.wifitoggle{float:right;clear:both;max-width:75%;font-size:11px;background:#ccc;color:#000;margin:0 0 10px;padding:5px 10px}</style><body><div><form action=/update><fieldset><h2 class=fs-title>WiFi Login</h2><h3 class=fs-subtitle>Connect gadget to your WiFi network</h3><input autocorrect=off autocapitalize=none name=wifi_ssid id=ssid placeholder=\"WiFi Name\"> <button type=button class=\"action-button wifitoggle\" id=apbutton disabled>Searching for networks...</button><select name=aplist id=aplist size=2></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></form></div><script>function aplist(){return document.getElementById(\"aplist\")}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}setTimeout(refresh_status,3e3)}function refresh_status(){fetch(\"/status\",\"GET\",new_status)}function refresh_ap_list(){var t=aplist();t.innerHTML='<option value=\"\" disabled>Scanning...</option>',fetch(\"/aplist\",\"GET\",got_ap_list)}function toggle_aplist(t,e){var n=aplist(),s=document.getElementById(\"apbutton\");e||\"block\"==n.style.display?(n.style.display=\"none\",s.innerHTML=\"Show networks\"):(n.style.display=\"block\",s.innerHTML=\"Hide networks\")}function got_ap_list(t){var e=document.getElementById(\"apbutton\");if(t){var n=JSON.parse(t);n.sort(function(t,e){return e.rssi-t.rssi});var s=n.map(function(t){return t.ssid}).filter(function(t,e,n){return n.indexOf(t)==e}),i=aplist();i.innerHTML=\"\",i.setAttribute(\"size\",Math.max(Math.min(5,n.length),2));for(var a=0;a<s.length;++a){var o=document.createElement(\"option\");i.options.add(o),o.innerHTML=s[a]}e.disabled=!1,toggle_aplist(null,!0),e.onclick=toggle_aplist}else e.innerHTML=\"No networks found\"}window.onload=function(){refresh_status(),refresh_ap_list(),aplist().onchange=function(){document.getElementById(\"ssid\").value=aplist().value}};</script>"; "<!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===a.readyState&&n(200===a.status?a.responseText:null)}var a=new XMLHttpRequest;a.onreadystatechange=s,a.open(e,t,!0),a.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 a=0;a<n.length;++a){var i=document.createElement('option');i.innerHTML=n[a],s.options.add(i)}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)}window.onload=function(){refresh_status(),refresh_ap_list(),document.getElementById('aplist').onchange=function(){var t=document.getElementById('aplist');document.getElementById('wifi_ssid').value=t.value},document.getElementById('credentialsForm').addEventListener('submit',function(){fetch('/status','GET',new_status)})}</script>";
typedef struct scan_listener typedef struct scan_listener
{ {
struct tcp_pcb *conn;
struct scan_listener *next; struct scan_listener *next;
int remote_port;
uint8 remote_ip[4];
} scan_listener_t; } scan_listener_t;
typedef struct typedef struct
{ {
struct espconn *espconn_dns_udp; struct espconn *espconn_dns_udp;
struct espconn *espconn_http_tcp; struct tcp_pcb *http_pcb;
char *http_payload_data; char *http_payload_data;
uint32_t http_payload_len; uint32_t http_payload_len;
os_timer_t check_station_timer; os_timer_t check_station_timer;
os_timer_t shutdown_timer;
int lua_connected_cb_ref; int lua_connected_cb_ref;
int lua_err_cb_ref; int lua_err_cb_ref;
int lua_dbg_cb_ref; int lua_dbg_cb_ref;
...@@ -247,71 +254,78 @@ static enduser_setup_state_t *state; ...@@ -247,71 +254,78 @@ static enduser_setup_state_t *state;
static bool manual = false; static bool manual = false;
static task_handle_t do_station_cfg_handle; 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_start(lua_State* L);
static int enduser_setup_stop(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_station_start(void);
static void enduser_setup_ap_start(void); static void enduser_setup_ap_start(void);
static void enduser_setup_ap_stop(void); static void enduser_setup_ap_stop(void);
static void enduser_setup_check_station(void *p); static void enduser_setup_check_station(void *p);
static void enduser_setup_debug(lua_State *L, const char *str); static void enduser_setup_debug(int line, const char *str);
#define ENDUSER_SETUP_DEBUG_ENABLE 0 #define ENDUSER_SETUP_DEBUG_ENABLE 0
#if ENDUSER_SETUP_DEBUG_ENABLE #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 #else
#define ENDUSER_SETUP_DEBUG(l, str) do {} while(0) #define ENDUSER_SETUP_DEBUG(str) do {} while(0)
#endif #endif
static void enduser_setup_debug(lua_State *L, const char *str)
{
if(state != NULL && L != NULL && state->lua_dbg_cb_ref != LUA_NOREF)
{
lua_rawgeti(L, LUA_REGISTRYINDEX, state->lua_dbg_cb_ref);
lua_pushstring(L, str);
lua_call(L, 1, 0);
}
}
#define ENDUSER_SETUP_ERROR(str, err, err_severity) \ #define ENDUSER_SETUP_ERROR(str, err, err_severity) \
do { \ do { \
ENDUSER_SETUP_DEBUG(str); \
if (err_severity & ENDUSER_SETUP_ERR_FATAL) enduser_setup_stop(lua_getstate());\ if (err_severity & ENDUSER_SETUP_ERR_FATAL) enduser_setup_stop(lua_getstate());\
enduser_setup_error(lua_getstate(), str, err);\ enduser_setup_error(__LINE__, str, err);\
if (!(err_severity & ENDUSER_SETUP_ERR_NO_RETURN)) \ if (!(err_severity & ENDUSER_SETUP_ERR_NO_RETURN)) \
return err; \ return err; \
} while (0) } while (0)
#define ENDUSER_SETUP_ERROR_VOID(str, err, err_severity) \ #define ENDUSER_SETUP_ERROR_VOID(str, err, err_severity) \
do { \ do { \
ENDUSER_SETUP_DEBUG(str); \
if (err_severity & ENDUSER_SETUP_ERR_FATAL) enduser_setup_stop(lua_getstate());\ if (err_severity & ENDUSER_SETUP_ERR_FATAL) enduser_setup_stop(lua_getstate());\
enduser_setup_error(lua_getstate(), str, err);\ enduser_setup_error(__LINE__, str, err);\
if (!(err_severity & ENDUSER_SETUP_ERR_NO_RETURN)) \ if (!(err_severity & ENDUSER_SETUP_ERR_NO_RETURN)) \
return; \ return; \
} while (0) } while (0)
static void enduser_setup_error(lua_State *L, const char *str, int err) static void enduser_setup_debug(int line, const char *str)
{ {
ENDUSER_SETUP_DEBUG(L, "enduser_setup_error"); 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_pushfstring(L, "%d: \t%s", line, str);
lua_call(L, 1, 0);
}
}
if (state != NULL && L != NULL && state->lua_err_cb_ref != LUA_NOREF) static void enduser_setup_error(int line, const char *str, int err)
{
ENDUSER_SETUP_DEBUG("enduser_setup_error");
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_rawgeti (L, LUA_REGISTRYINDEX, state->lua_err_cb_ref);
lua_pushnumber(L, err); lua_pushnumber(L, err);
lua_pushfstring(L, "enduser_setup: %s", str); lua_pushfstring(L, "%d: \t%s", line, str);
lua_call (L, 2, 0); 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_rawgeti(L, LUA_REGISTRYINDEX, state->lua_connected_cb_ref);
lua_call(L, 0, 0); lua_call(L, 0, 0);
...@@ -321,7 +335,7 @@ static void enduser_setup_connected_callback(lua_State *L) ...@@ -321,7 +335,7 @@ static void enduser_setup_connected_callback(lua_State *L)
static void enduser_setup_check_station_start(void) static void enduser_setup_check_station_start(void)
{ {
ENDUSER_SETUP_DEBUG(lua_getstate(), "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_setfn(&(state->check_station_timer), enduser_setup_check_station, NULL);
os_timer_arm(&(state->check_station_timer), 1*1000, TRUE); os_timer_arm(&(state->check_station_timer), 1*1000, TRUE);
...@@ -330,10 +344,12 @@ static void enduser_setup_check_station_start(void) ...@@ -330,10 +344,12 @@ static void enduser_setup_check_station_start(void)
static void enduser_setup_check_station_stop(void) static void enduser_setup_check_station_stop(void)
{ {
ENDUSER_SETUP_DEBUG(lua_getstate(), "enduser_setup_check_station_stop"); ENDUSER_SETUP_DEBUG("enduser_setup_check_station_stop");
if (state != NULL) if (state != NULL)
{
os_timer_disarm(&(state->check_station_timer)); os_timer_disarm(&(state->check_station_timer));
}
} }
...@@ -344,6 +360,8 @@ static void enduser_setup_check_station_stop(void) ...@@ -344,6 +360,8 @@ static void enduser_setup_check_station_stop(void)
*/ */
static void enduser_setup_check_station(void *p) static void enduser_setup_check_station(void *p)
{ {
ENDUSER_SETUP_DEBUG("enduser_setup_check_station");
(void)p; (void)p;
struct ip_info ip; struct ip_info ip;
c_memset(&ip, 0, sizeof(struct ip_info)); c_memset(&ip, 0, sizeof(struct ip_info));
...@@ -362,8 +380,15 @@ static void enduser_setup_check_station(void *p) ...@@ -362,8 +380,15 @@ static void enduser_setup_check_station(void *p)
return; return;
} }
enduser_setup_connected_callback(lua_getstate()); enduser_setup_check_station_stop();
enduser_setup_stop(NULL); enduser_setup_connected_callback();
/* 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);
}
} }
...@@ -378,9 +403,13 @@ static int enduser_setup_srch_str(const char *str, const char *srch_str) ...@@ -378,9 +403,13 @@ static int enduser_setup_srch_str(const char *str, const char *srch_str)
{ {
char *found = strpbrk (str, srch_str); char *found = strpbrk (str, srch_str);
if (!found) if (!found)
{
return -1; return -1;
}
else else
{
return found - str; return found - str;
}
} }
...@@ -393,7 +422,7 @@ static int enduser_setup_srch_str(const char *str, const char *srch_str) ...@@ -393,7 +422,7 @@ static int enduser_setup_srch_str(const char *str, const char *srch_str)
*/ */
static int enduser_setup_http_load_payload(void) static int enduser_setup_http_load_payload(void)
{ {
ENDUSER_SETUP_DEBUG(lua_getstate(), "enduser_setup_http_load_payload"); ENDUSER_SETUP_DEBUG("enduser_setup_http_load_payload");
int f = fs_open(http_html_filename, fs_mode2flag("r")); int f = fs_open(http_html_filename, fs_mode2flag("r"));
int err = fs_seek(f, 0, FS_SEEK_END); int err = fs_seek(f, 0, FS_SEEK_END);
...@@ -405,7 +434,7 @@ static int enduser_setup_http_load_payload(void) ...@@ -405,7 +434,7 @@ static int enduser_setup_http_load_payload(void)
if (f == 0 || err == -1 || err2 == -1) if (f == 0 || err == -1 || err2 == -1)
{ {
ENDUSER_SETUP_DEBUG(lua_getstate(), "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 index.html, loading backup HTML.");
int payload_len = LITLEN(http_header_200) + cl_len + LITLEN(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_len = payload_len;
...@@ -446,9 +475,14 @@ static int enduser_setup_http_load_payload(void) ...@@ -446,9 +475,14 @@ static int enduser_setup_http_load_payload(void)
* De-escape URL data * De-escape URL data
* *
* Parse escaped and form encoded data of request. * 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 a, b; char a, b;
int i; int i;
for (i = 0; i < src_len && *src; ++i) for (i = 0; i < src_len && *src; ++i)
...@@ -490,8 +524,15 @@ static void enduser_setup_http_urldecode(char *dst, const char *src, int src_len ...@@ -490,8 +524,15 @@ static void enduser_setup_http_urldecode(char *dst, const char *src, int src_len
} }
*dst++ = c; *dst++ = c;
} }
if ((dst - dst_start) >= dst_len - 1)
{
/* Try to leave a valid string even in the case of errors. */
*dst = '\0';
return 1;
}
} }
*dst++ = '\0'; *dst++ = '\0';
return 0;
} }
...@@ -517,7 +558,7 @@ static void do_station_cfg (task_param_t param, uint8_t prio) ...@@ -517,7 +558,7 @@ static void do_station_cfg (task_param_t param, uint8_t prio)
wifi_station_disconnect (); wifi_station_disconnect ();
wifi_station_set_config (cnf); wifi_station_set_config (cnf);
wifi_station_connect (); wifi_station_connect ();
os_free (cnf); luaM_free(lua_getstate(), cnf);
} }
...@@ -530,12 +571,13 @@ static void do_station_cfg (task_param_t param, uint8_t prio) ...@@ -530,12 +571,13 @@ static void do_station_cfg (task_param_t param, uint8_t prio)
*/ */
static int enduser_setup_http_handle_credentials(char *data, unsigned short data_len) static int enduser_setup_http_handle_credentials(char *data, unsigned short data_len)
{ {
ENDUSER_SETUP_DEBUG(lua_getstate(), "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 *name_str = (char *) ((uint32_t)strstr(&(data[6]), "wifi_ssid="));
char *pwd_str = (char *) ((uint32_t)strstr(&(data[6]), "wifi_password=")); char *pwd_str = (char *) ((uint32_t)strstr(&(data[6]), "wifi_password="));
if (name_str == NULL || pwd_str == NULL) if (name_str == NULL || pwd_str == NULL)
{ {
ENDUSER_SETUP_DEBUG("Password or SSID string not found");
return 1; return 1;
} }
...@@ -546,24 +588,37 @@ static int enduser_setup_http_handle_credentials(char *data, unsigned short data ...@@ -546,24 +588,37 @@ static int enduser_setup_http_handle_credentials(char *data, unsigned short data
int name_str_len = enduser_setup_srch_str(name_str_start, "& "); int name_str_len = enduser_setup_srch_str(name_str_start, "& ");
int pwd_str_len = enduser_setup_srch_str(pwd_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; return 1;
} }
struct station_config *cnf = os_zalloc(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);
task_post_medium(do_station_cfg_handle, (task_param_t)cnf); struct station_config *cnf = luaM_malloc(lua_getstate(), sizeof(struct station_config));
c_memset(cnf, 0, sizeof(struct station_config));
ENDUSER_SETUP_DEBUG(lua_getstate(), "WiFi Credentials Stored"); int err;
ENDUSER_SETUP_DEBUG(lua_getstate(), "-----------------------"); err = enduser_setup_http_urldecode(cnf->ssid, name_str_start, name_str_len, 64);
ENDUSER_SETUP_DEBUG(lua_getstate(), "name: "); err |= enduser_setup_http_urldecode(cnf->password, pwd_str_start, pwd_str_len, 32);
ENDUSER_SETUP_DEBUG(lua_getstate(), cnf->ssid); if (err != 0)
ENDUSER_SETUP_DEBUG(lua_getstate(), "pass: "); {
ENDUSER_SETUP_DEBUG(lua_getstate(), cnf->password); ENDUSER_SETUP_DEBUG("Unable to decode HTTP parameter to valid password or SSID");
ENDUSER_SETUP_DEBUG(lua_getstate(), "-----------------------"); return 1;
}
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; return 0;
} }
...@@ -574,25 +629,58 @@ static int enduser_setup_http_handle_credentials(char *data, unsigned short data ...@@ -574,25 +629,58 @@ static int enduser_setup_http_handle_credentials(char *data, unsigned short data
* *
* @return - return 0 iff html was served successfully * @return - return 0 iff html was served successfully
*/ */
static int enduser_setup_http_serve_header(struct espconn *http_client, const 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(lua_getstate(), "enduser_setup_http_serve_header"); ENDUSER_SETUP_DEBUG("enduser_setup_http_serve_header");
int8_t err = espconn_send(http_client, (char *)header, header_len); err_t err = tcp_write (http_client, header, header_len, TCP_WRITE_FLAG_COPY);
if (err == ESPCONN_MEM) if (err != ERR_OK)
{ {
ENDUSER_SETUP_ERROR("http_serve_header failed. espconn_send out of memory", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_NONFATAL); tcp_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("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("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);
tcp_close (pcb);
}
else
tcp_arg (pcb, (void *)offs);
return ERR_OK;
} }
...@@ -601,36 +689,33 @@ static int enduser_setup_http_serve_header(struct espconn *http_client, const ch ...@@ -601,36 +689,33 @@ static int enduser_setup_http_serve_header(struct espconn *http_client, const ch
* *
* @return - return 0 iff html was served successfully * @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(lua_getstate(), "enduser_setup_http_serve_html"); ENDUSER_SETUP_DEBUG("enduser_setup_http_serve_html");
if (state->http_payload_data == NULL) if (state->http_payload_data == NULL)
{ {
enduser_setup_http_load_payload(); enduser_setup_http_load_payload();
} }
int8_t err = espconn_send(http_client, state->http_payload_data, state->http_payload_len); unsigned chunklen = tcp_sndbuf (http_client);
if (err == ESPCONN_MEM) tcp_arg (http_client, (void *)chunklen);
{ tcp_recv (http_client, 0); /* avoid confusion about the tcp_arg */
ENDUSER_SETUP_ERROR("http_serve_html failed. espconn_send out of memory", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_NONFATAL); tcp_sent (http_client, streamout_sent);
} /* Begin the no-copy stream-out here */
else if (err == ESPCONN_ARG) err_t err = tcp_write (http_client, state->http_payload_data, chunklen, 0);
{ if (err != 0)
ENDUSER_SETUP_ERROR("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)
{ {
ENDUSER_SETUP_ERROR("http_serve_html failed. espconn_send failed", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_NONFATAL); ENDUSER_SETUP_ERROR("http_serve_html failed. tcp_write failed", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_NONFATAL);
} }
return 0; return 0;
} }
static void serve_status (struct espconn *conn) static void serve_status(struct tcp_pcb *conn)
{ {
ENDUSER_SETUP_DEBUG(lua_getstate(), "enduser_setup_serve_status"); ENDUSER_SETUP_DEBUG("enduser_setup_serve_status");
const char fmt[] = const char fmt[] =
"HTTP/1.1 200 OK\r\n" "HTTP/1.1 200 OK\r\n"
...@@ -641,56 +726,77 @@ static void serve_status (struct espconn *conn) ...@@ -641,56 +726,77 @@ static void serve_status (struct espconn *conn)
"%s%s"; "%s%s";
const char *state[] = const char *state[] =
{ {
"Idle", "Idle.",
"Connecting...", "Connecting to \"%s\".",
"Failed to connect - wrong password", "Failed to connect to \"%s\" - Wrong password.",
"Failed to connect - network not found", "Failed to connect to \"%s\" - Network not found.",
"Failed to connect" "Failed to connect.",
"Connected to \"%s\"."
}; };
const size_t num_states = sizeof(state)/sizeof(state[0]);
uint8_t which = wifi_station_get_connect_status (); const size_t num_states = sizeof(state)/sizeof(state[0]);
if (which < num_states) uint8_t curr_state = wifi_station_get_connect_status ();
if (curr_state < num_states)
{
switch (curr_state)
{ {
const char *s = state[which]; case STATION_CONNECTING:
int len = c_strlen (s); case STATION_WRONG_PASSWORD:
char buf[sizeof (fmt) + 10 + len]; /* more than enough for the formatted */ case STATION_NO_AP_FOUND:
len = c_sprintf (buf, fmt, len, s, ""); case STATION_GOT_IP:
enduser_setup_http_serve_header (conn, buf, len); {
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);
} }
else if (which == num_states) break;
/* Handle non-formatted strings */
default:
{ {
struct station_config cnf = { 0, }; const char *s = state[curr_state];
wifi_station_get_config (&cnf); int status_len = c_strlen(s);
const char successmsg[] = "WiFi successfully connected to "; int buf_len = sizeof(fmt) + status_len + 10; //10 = (9+1), 1 byte is '\0' and 9 are reserved for length field
int len = LITLEN(successmsg) + c_strlen (cnf.ssid); char buf[buf_len];
char buf[sizeof (fmt) + sizeof (successmsg) + 32]; // max-ssid memset(buf, 0, buf_len);
len = c_sprintf (buf, fmt, len, successmsg, cnf.ssid); int output_len = c_sprintf(buf, fmt, status_len, s);
enduser_setup_http_serve_header (conn, buf, len);
enduser_setup_http_serve_header(conn, buf, output_len);
}
break;
}
} }
else else
enduser_setup_http_serve_header (conn, http_header_500, LITLEN(http_header_500)); {
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)
{
ENDUSER_SETUP_DEBUG(lua_getstate(), "enduser_setup_http_disconnect");
//TODO: Construct and maintain os task queue(?) to be able to issue system_os_task with espconn_disconnect.
}
/* --- WiFi AP scanning support -------------------------------------------- */ /* --- WiFi AP scanning support -------------------------------------------- */
static void free_scan_listeners (void) static void free_scan_listeners (void)
{ {
if (!state || !state->scan_listeners) if (!state || !state->scan_listeners)
{
return; return;
}
scan_listener_t *l = state->scan_listeners , *next = 0; scan_listener_t *l = state->scan_listeners , *next = 0;
while (l) while (l)
...@@ -703,25 +809,15 @@ static void free_scan_listeners (void) ...@@ -703,25 +809,15 @@ static void free_scan_listeners (void)
} }
static inline bool same_remote (uint8 addr1[4], int port1, uint8 addr2[4], int port2) static void remove_scan_listener (scan_listener_t *l)
{ {
return (port1 == port2) && (c_memcmp (addr1, addr2, 4) == 0); if (state)
}
static void on_disconnect (void *arg)
{
struct espconn *conn = arg;
if (conn->type == ESPCONN_TCP && state && state->scan_listeners)
{ {
scan_listener_t **sl = &state->scan_listeners; scan_listener_t **sl = &state->scan_listeners;
while (*sl) while (*sl)
{ {
/* Remove any and all references to the closed conn from the scan list */ /* Remove any and all references to the closed conn from the scan list */
scan_listener_t *l = *sl; if (*sl == l)
if (same_remote (
l->remote_ip, l->remote_port,
conn->proto.tcp->remote_ip, conn->proto.tcp->remote_port))
{ {
*sl = l->next; *sl = l->next;
c_free (l); c_free (l);
...@@ -733,12 +829,15 @@ static void on_disconnect (void *arg) ...@@ -733,12 +829,15 @@ static void on_disconnect (void *arg)
} }
} }
static char *escape_ssid (char *dst, const char *src) static char *escape_ssid (char *dst, const char *src)
{ {
for (int i = 0; i < 32 && src[i]; ++i) for (int i = 0; i < 32 && src[i]; ++i)
{ {
if (src[i] == '\\' || src[i] == '"') if (src[i] == '\\' || src[i] == '"')
{
*dst++ = '\\'; *dst++ = '\\';
}
*dst++ = src[i]; *dst++ = src[i];
} }
return dst; return dst;
...@@ -748,21 +847,20 @@ static char *escape_ssid (char *dst, const char *src) ...@@ -748,21 +847,20 @@ static char *escape_ssid (char *dst, const char *src)
static void notify_scan_listeners (const char *payload, size_t sz) static void notify_scan_listeners (const char *payload, size_t sz)
{ {
if (!state) if (!state)
{
return; return;
if (!state->espconn_http_tcp) }
goto cleanup;
struct espconn *conn = state->espconn_http_tcp;
for (scan_listener_t *l = state->scan_listeners; l; l = l->next) for (scan_listener_t *l = state->scan_listeners; l; l = l->next)
{ {
c_memcpy (conn->proto.tcp->remote_ip, l->remote_ip, 4); if (tcp_write (l->conn, payload, sz, TCP_WRITE_FLAG_COPY) != ERR_OK)
conn->proto.tcp->remote_port = l->remote_port; {
if (espconn_send(conn, (char *)payload, sz) != ESPCONN_OK) ENDUSER_SETUP_DEBUG("failed to send wifi list");
ENDUSER_SETUP_DEBUG(lua_getstate(), "failed to send wifi list"); }
enduser_setup_http_disconnect(conn); tcp_close (l->conn);
l->conn = 0;
} }
cleanup:
free_scan_listeners (); free_scan_listeners ();
} }
...@@ -770,13 +868,17 @@ cleanup: ...@@ -770,13 +868,17 @@ cleanup:
static void on_scan_done (void *arg, STATUS status) static void on_scan_done (void *arg, STATUS status)
{ {
if (!state || !state->scan_listeners) if (!state || !state->scan_listeners)
{
return; return;
}
if (status == OK) if (status == OK)
{ {
unsigned num_nets = 0; unsigned num_nets = 0;
for (struct bss_info *wn = arg; wn; wn = wn->next.stqe_next) for (struct bss_info *wn = arg; wn; wn = wn->next.stqe_next)
{
++num_nets; ++num_nets;
}
const char header_fmt[] = const char header_fmt[] =
"HTTP/1.1 200 OK\r\n" "HTTP/1.1 200 OK\r\n"
...@@ -792,7 +894,9 @@ static void on_scan_done (void *arg, STATUS status) ...@@ -792,7 +894,9 @@ static void on_scan_done (void *arg, STATUS status)
const size_t alloc_sz = hdr_sz + num_nets * max_entry_sz + 3; const size_t alloc_sz = hdr_sz + num_nets * max_entry_sz + 3;
char *http = os_zalloc (alloc_sz); char *http = os_zalloc (alloc_sz);
if (!http) if (!http)
{
goto serve_500; goto serve_500;
}
char *p = http + hdr_sz; /* start body where we know it will be */ 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[0] will be clobbered when we print the header, so fill it in last */
...@@ -800,7 +904,9 @@ static void on_scan_done (void *arg, STATUS status) ...@@ -800,7 +904,9 @@ static void on_scan_done (void *arg, STATUS status)
for (struct bss_info *wn = arg; wn; wn = wn->next.stqe_next) for (struct bss_info *wn = arg; wn; wn = wn->next.stqe_next)
{ {
if (wn != arg) if (wn != arg)
{
*p++ = ','; *p++ = ',';
}
const char entry_start[] = "{\"ssid\":\""; const char entry_start[] = "{\"ssid\":\"";
strcpy (p, entry_start); strcpy (p, entry_start);
...@@ -834,50 +940,82 @@ serve_500: ...@@ -834,50 +940,82 @@ serve_500:
/* ---- end WiFi AP scan support ------------------------------------------- */ /* ---- end WiFi AP scan support ------------------------------------------- */
static void enduser_setup_http_recvcb(void *arg, char *data, unsigned short data_len) static err_t enduser_setup_http_recvcb(void *arg, struct tcp_pcb *http_client, struct pbuf *p, err_t err)
{ {
ENDUSER_SETUP_DEBUG(lua_getstate(), "enduser_setup_http_recvcb"); ENDUSER_SETUP_DEBUG("enduser_setup_http_recvcb");
if (!state || err != ERR_OK)
{
if (!state) if (!state)
ENDUSER_SETUP_DEBUG("ignoring received data while stopped");
tcp_abort (http_client);
return ERR_ABRT;
}
if (!p) /* remote side closed, close our end too */
{ {
ENDUSER_SETUP_DEBUG(lua_getstate(), "ignoring received data while stopped"); ENDUSER_SETUP_DEBUG("connection closed");
return; scan_listener_t *l = arg; /* if it's waiting for scan, we have a ptr here */
if (l)
remove_scan_listener (l);
tcp_close (http_client);
return ERR_OK;
} }
struct espconn *http_client = (struct espconn *) arg; char *data = os_zalloc (p->tot_len + 1);
if (!data)
return ERR_MEM;
unsigned data_len = pbuf_copy_partial (p, data, p->tot_len, 0);
tcp_recved (http_client, p->tot_len);
pbuf_free (p);
if (c_strncmp(data, "GET ", 4) == 0) if (c_strncmp(data, "GET ", 4) == 0)
{ {
if (c_strncmp(data + 4, "/ ", 2) == 0) if (c_strncmp(data + 4, "/ ", 2) == 0)
{ {
if (enduser_setup_http_serve_html(http_client) != 0) if (enduser_setup_http_serve_html(http_client) != 0)
ENDUSER_SETUP_ERROR_VOID("http_recvcb failed. Unable to send HTML.", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_NONFATAL); {
ENDUSER_SETUP_ERROR("http_recvcb failed. Unable to send HTML.", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_NONFATAL);
}
else
{
os_free (data);
return ERR_OK; /* streaming now in progress */
}
} }
else if (c_strncmp(data + 4, "/aplist ", 8) == 0) else if (c_strncmp(data + 4, "/aplist ", 8) == 0)
{ {
scan_listener_t *l = os_malloc (sizeof (scan_listener_t)); scan_listener_t *l = os_malloc (sizeof (scan_listener_t));
if (!l) if (!l)
ENDUSER_SETUP_ERROR_VOID("out of memory", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_NONFATAL); {
ENDUSER_SETUP_ERROR("out of memory", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_NONFATAL);
c_memcpy (l->remote_ip, http_client->proto.tcp->remote_ip, 4); }
l->remote_port = http_client->proto.tcp->remote_port;
bool already = (state->scan_listeners != NULL); bool already = (state->scan_listeners != NULL);
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; l->next = state->scan_listeners;
state->scan_listeners = l; state->scan_listeners = l;
if (!already) if (!already)
{ {
if (!wifi_station_scan (NULL, on_scan_done)) if (!wifi_station_scan(NULL, on_scan_done))
{ {
enduser_setup_http_serve_header (http_client, http_header_500, LITLEN(http_header_500)); enduser_setup_http_serve_header(http_client, http_header_500, LITLEN(http_header_500));
free_scan_listeners (); tcp_close (l->conn);
l->conn = 0;
free_scan_listeners();
} }
} }
return; os_free (data);
return ERR_OK;
} }
else if (c_strncmp(data + 4, "/status ", 8) == 0) else if (c_strncmp(data + 4, "/status ", 8) == 0)
{ {
serve_status (http_client); serve_status(http_client);
} }
else if (c_strncmp(data + 4, "/update?", 8) == 0) else if (c_strncmp(data + 4, "/update?", 8) == 0)
{ {
...@@ -890,13 +1028,19 @@ static void enduser_setup_http_recvcb(void *arg, char *data, unsigned short data ...@@ -890,13 +1028,19 @@ static void enduser_setup_http_recvcb(void *arg, char *data, unsigned short data
enduser_setup_http_serve_header(http_client, http_header_401, LITLEN(http_header_401)); enduser_setup_http_serve_header(http_client, http_header_401, LITLEN(http_header_401));
break; break;
default: default:
ENDUSER_SETUP_ERROR_VOID("http_recvcb failed. Failed to handle wifi credentials.", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_NONFATAL); ENDUSER_SETUP_ERROR("http_recvcb failed. Failed to handle wifi credentials.", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_NONFATAL);
break; 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 else
{ {
ENDUSER_SETUP_DEBUG(lua_getstate(), "serving 404"); ENDUSER_SETUP_DEBUG("serving 404");
ENDUSER_SETUP_DEBUG(data + 4);
enduser_setup_http_serve_header(http_client, http_header_404, LITLEN(http_header_404)); enduser_setup_http_serve_header(http_client, http_header_404, LITLEN(http_header_404));
} }
} }
...@@ -905,82 +1049,70 @@ static void enduser_setup_http_recvcb(void *arg, char *data, unsigned short data ...@@ -905,82 +1049,70 @@ static void enduser_setup_http_recvcb(void *arg, char *data, unsigned short data
enduser_setup_http_serve_header(http_client, http_header_401, LITLEN(http_header_401)); enduser_setup_http_serve_header(http_client, http_header_401, LITLEN(http_header_401));
} }
enduser_setup_http_disconnect (http_client); os_free (data);
#if 0
/* being nice apparently costs us a lot of pcbs in time_wait state :( */
tcp_close (http_client);
return ERR_OK;
#else
tcp_abort (http_client);
return ERR_ABRT;
#endif
} }
static void enduser_setup_http_connectcb(void *arg) static err_t enduser_setup_http_connectcb(void *arg, struct tcp_pcb *pcb, err_t err)
{ {
ENDUSER_SETUP_DEBUG(lua_getstate(), "enduser_setup_http_connectcb"); ENDUSER_SETUP_DEBUG("enduser_setup_http_connectcb");
struct espconn *callback_espconn = (struct espconn *) arg; if (!state)
int8_t err = 0;
err |= espconn_regist_recvcb(callback_espconn, enduser_setup_http_recvcb);
err |= espconn_regist_disconcb(callback_espconn, on_disconnect);
if (err != 0)
{ {
ENDUSER_SETUP_ERROR_VOID("http_connectcb failed. Callback registration failed.", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_NONFATAL); ENDUSER_SETUP_DEBUG("connect callback but no state?!");
tcp_abort (pcb);
return ERR_ABRT;
} }
tcp_accepted (state->http_pcb);
tcp_recv (pcb, enduser_setup_http_recvcb);
return ERR_OK;
} }
static int enduser_setup_http_start(void) static int enduser_setup_http_start(void)
{ {
ENDUSER_SETUP_DEBUG(lua_getstate(), "enduser_setup_http_start"); ENDUSER_SETUP_DEBUG("enduser_setup_http_start");
state->espconn_http_tcp = (struct espconn *) c_malloc(sizeof(struct espconn)); struct tcp_pcb *pcb = tcp_new ();
if (state->espconn_http_tcp == NULL) if (pcb == NULL)
{ {
ENDUSER_SETUP_ERROR("http_start failed. Memory allocation failed (espconn_http_tcp == NULL).", 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);
} }
esp_tcp *esp_tcp_data = (esp_tcp *) c_malloc(sizeof(esp_tcp));
if (esp_tcp_data == NULL)
{
ENDUSER_SETUP_ERROR("http_start failed. Memory allocation failed (esp_udp == NULL).", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_FATAL);
}
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;
int8_t err; if (tcp_bind (pcb, IP_ADDR_ANY, 80) != ERR_OK)
err = espconn_regist_connectcb(state->espconn_http_tcp, enduser_setup_http_connectcb);
if (err != 0)
{ {
ENDUSER_SETUP_ERROR("http_start failed. Couldn't add receive callback.", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_FATAL); ENDUSER_SETUP_ERROR("http_start bind failed", ENDUSER_SETUP_ERR_SOCKET_ALREADY_OPEN, ENDUSER_SETUP_ERR_FATAL);
} }
err = espconn_accept(state->espconn_http_tcp); state->http_pcb = tcp_listen (pcb);
if (err == ESPCONN_ISCONN) if (!state->http_pcb)
{ {
ENDUSER_SETUP_ERROR("http_start failed. Couldn't create connection, already listening for that connection.", ENDUSER_SETUP_ERR_SOCKET_ALREADY_OPEN, 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);
else if (err == ESPCONN_MEM)
{
ENDUSER_SETUP_ERROR("http_start failed. Couldn't create connection, out of memory.", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_FATAL);
}
else if (err == ESPCONN_ARG)
{
ENDUSER_SETUP_ERROR("http_start failed. Can't find connection from espconn argument", ENDUSER_SETUP_ERR_CONNECTION_NOT_FOUND, ENDUSER_SETUP_ERR_FATAL);
}
else if (err != 0)
{
ENDUSER_SETUP_ERROR("http_start failed. Unknown error", ENDUSER_SETUP_ERR_UNKOWN_ERROR, 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); err = espconn_regist_time(state->espconn_http_tcp, 2, 0);
if (err == ESPCONN_ARG) if (err == ESPCONN_ARG)
{ {
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); 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) if (err == 1)
{ {
ENDUSER_SETUP_DEBUG(lua_getstate(), "enduser_setup_http_start info. Loaded backup HTML."); ENDUSER_SETUP_DEBUG("enduser_setup_http_start info. Loaded backup HTML.");
} }
else if (err == 2) else if (err == 2)
{ {
...@@ -993,17 +1125,18 @@ static int enduser_setup_http_start(void) ...@@ -993,17 +1125,18 @@ static int enduser_setup_http_start(void)
static void enduser_setup_http_stop(void) static void enduser_setup_http_stop(void)
{ {
ENDUSER_SETUP_DEBUG(lua_getstate(), "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) static void enduser_setup_ap_stop(void)
{ {
ENDUSER_SETUP_DEBUG(lua_getstate(), "enduser_setup_station_stop"); ENDUSER_SETUP_DEBUG("enduser_setup_station_stop");
wifi_set_opmode(~SOFTAP_MODE & wifi_get_opmode()); wifi_set_opmode(~SOFTAP_MODE & wifi_get_opmode());
} }
...@@ -1011,7 +1144,7 @@ static void enduser_setup_ap_stop(void) ...@@ -1011,7 +1144,7 @@ static void enduser_setup_ap_stop(void)
static void enduser_setup_ap_start(void) static void enduser_setup_ap_start(void)
{ {
ENDUSER_SETUP_DEBUG(lua_getstate(), "enduser_setup_ap_start"); ENDUSER_SETUP_DEBUG("enduser_setup_ap_start");
struct softap_config cnf; struct softap_config cnf;
c_memset(&(cnf), 0, sizeof(struct softap_config)); c_memset(&(cnf), 0, sizeof(struct softap_config));
...@@ -1041,7 +1174,7 @@ static void enduser_setup_ap_start(void) ...@@ -1041,7 +1174,7 @@ static void enduser_setup_ap_start(void)
static void enduser_setup_dns_recv_callback(void *arg, char *recv_data, unsigned short recv_len) static void enduser_setup_dns_recv_callback(void *arg, char *recv_data, unsigned short recv_len)
{ {
ENDUSER_SETUP_DEBUG(lua_getstate(), "enduser_setup_dns_recv_callback."); ENDUSER_SETUP_DEBUG("enduser_setup_dns_recv_callback.");
struct espconn *callback_espconn = arg; struct espconn *callback_espconn = arg;
struct ip_info ip_info; struct ip_info ip_info;
...@@ -1109,13 +1242,17 @@ static void enduser_setup_dns_recv_callback(void *arg, char *recv_data, unsigned ...@@ -1109,13 +1242,17 @@ static void enduser_setup_dns_recv_callback(void *arg, char *recv_data, unsigned
static void enduser_setup_free(void) static void enduser_setup_free(void)
{ {
ENDUSER_SETUP_DEBUG(lua_getstate(), "enduser_setup_free"); ENDUSER_SETUP_DEBUG("enduser_setup_free");
if (state == NULL) if (state == NULL)
{ {
return; 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 != NULL)
{ {
if (state->espconn_dns_udp->proto.udp != NULL) if (state->espconn_dns_udp->proto.udp != NULL)
...@@ -1125,14 +1262,6 @@ static void enduser_setup_free(void) ...@@ -1125,14 +1262,6 @@ static void enduser_setup_free(void)
c_free(state->espconn_dns_udp); 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); c_free(state->http_payload_data);
free_scan_listeners (); free_scan_listeners ();
...@@ -1144,7 +1273,7 @@ static void enduser_setup_free(void) ...@@ -1144,7 +1273,7 @@ static void enduser_setup_free(void)
static int enduser_setup_dns_start(void) static int enduser_setup_dns_start(void)
{ {
ENDUSER_SETUP_DEBUG(lua_getstate(), "enduser_setup_dns_start"); ENDUSER_SETUP_DEBUG("enduser_setup_dns_start");
if (state->espconn_dns_udp != NULL) if (state->espconn_dns_udp != NULL)
{ {
...@@ -1196,7 +1325,7 @@ static int enduser_setup_dns_start(void) ...@@ -1196,7 +1325,7 @@ static int enduser_setup_dns_start(void)
static void enduser_setup_dns_stop(void) static void enduser_setup_dns_stop(void)
{ {
ENDUSER_SETUP_DEBUG(lua_getstate(), "enduser_setup_dns_stop"); ENDUSER_SETUP_DEBUG("enduser_setup_dns_stop");
if (state != NULL && state->espconn_dns_udp != NULL) if (state != NULL && state->espconn_dns_udp != NULL)
{ {
...@@ -1207,18 +1336,18 @@ static void enduser_setup_dns_stop(void) ...@@ -1207,18 +1336,18 @@ static void enduser_setup_dns_stop(void)
static int enduser_setup_init(lua_State *L) static int enduser_setup_init(lua_State *L)
{ {
ENDUSER_SETUP_DEBUG(L, "enduser_setup_init"); ENDUSER_SETUP_DEBUG("enduser_setup_init");
if (state != NULL) if (state != NULL)
{ {
enduser_setup_error(L, "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; return ENDUSER_SETUP_ERR_UNKOWN_ERROR;
} }
state = (enduser_setup_state_t *) os_zalloc(sizeof(enduser_setup_state_t)); state = (enduser_setup_state_t *) os_zalloc(sizeof(enduser_setup_state_t));
if (state == NULL) if (state == NULL)
{ {
enduser_setup_error(L, "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; return ENDUSER_SETUP_ERR_OUT_OF_MEMORY;
} }
c_memset(state, 0, sizeof(enduser_setup_state_t)); c_memset(state, 0, sizeof(enduser_setup_state_t));
...@@ -1261,10 +1390,12 @@ static int enduser_setup_init(lua_State *L) ...@@ -1261,10 +1390,12 @@ static int enduser_setup_init(lua_State *L)
} }
static int enduser_setup_manual (lua_State *L) static int enduser_setup_manual(lua_State *L)
{ {
if (!lua_isnoneornil (L, 1)) if (!lua_isnoneornil (L, 1))
{
manual = lua_toboolean (L, 1); manual = lua_toboolean (L, 1);
}
lua_pushboolean (L, manual); lua_pushboolean (L, manual);
return 1; return 1;
} }
...@@ -1272,40 +1403,58 @@ static int enduser_setup_manual (lua_State *L) ...@@ -1272,40 +1403,58 @@ static int enduser_setup_manual (lua_State *L)
static int enduser_setup_start(lua_State *L) 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) if (!do_station_cfg_handle)
{
do_station_cfg_handle = task_get_id(do_station_cfg); do_station_cfg_handle = task_get_id(do_station_cfg);
}
if(enduser_setup_init(L)) if(enduser_setup_init(L))
{
goto failed; goto failed;
}
enduser_setup_check_station_start();
if (!manual) if (!manual)
{ {
enduser_setup_check_station_start();
enduser_setup_ap_start(); enduser_setup_ap_start();
} }
if(enduser_setup_dns_start()) if(enduser_setup_dns_start())
{
goto failed; goto failed;
}
if(enduser_setup_http_start()) if(enduser_setup_http_start())
{
goto failed; goto failed;
}
goto out; goto out;
failed: failed:
enduser_setup_stop(L); enduser_setup_stop(lua_getstate());
out: out:
return 0; 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) static int enduser_setup_stop(lua_State* L)
{ {
ENDUSER_SETUP_DEBUG("enduser_setup_stop");
if (!manual) if (!manual)
{ {
enduser_setup_check_station_stop();
enduser_setup_ap_stop(); enduser_setup_ap_stop();
} }
enduser_setup_dns_stop(); enduser_setup_dns_stop();
......
...@@ -10,13 +10,14 @@ This module provides a simple way of configuring ESP8266 chips without using a s ...@@ -10,13 +10,14 @@ This module provides a simple way of configuring ESP8266 chips without using a s
After running [`enduser_setup.start()`](#enduser_setupstart) a portal like the above can be accessed through a wireless network called SetupGadget_XXXXXX. The portal is used to submit the credentials for the WiFi of the enduser. After running [`enduser_setup.start()`](#enduser_setupstart) a portal like the above can be accessed through a wireless network called SetupGadget_XXXXXX. The portal is used to submit the credentials for the WiFi of the enduser.
After an IP address has been successfully obtained this module will stop as if [`enduser_setup.stop()`](#enduser_setupstop) had been called. After an IP address has been successfully obtained this module will stop as if [`enduser_setup.stop()`](#enduser_setupstop) had been called.
Alternative HTML can be served by placing a file called `index.html` in the filesystem. This file will be kept in RAM, so keep it as small as possible.
## enduser_setup.manual() ## enduser_setup.manual()
Controls whether manual AP configuration is used. Controls whether manual AP configuration is used.
By default the `enduser_setup` module automatically configures an open access point when starting, and stops it when the device has been successfully joined to a WiFi network. If manual mode has been enabled, neither of this is done. The device must be manually configured for `wifi.SOFTAP` mode prior to calling `enduser_setup.start()`. Additionally, the portal is not stopped after the device has successfully joined to a WiFi network. By default the `enduser_setup` module automatically configures an open access point when starting, and stops it when the device has been successfully joined to a WiFi network. If manual mode has been enabled, neither of this is done. The device must be manually configured for `wifi.SOFTAP` mode prior to calling `enduser_setup.start()`. Additionally, the portal is not stopped after the device has successfully joined to a WiFi network.
Most importantly, *the `onConfigured()` callback is not supported in manual mode*. This limitation may disappear in the future.
#### Syntax #### Syntax
`enduser_setup.manual([on_off])` `enduser_setup.manual([on_off])`
...@@ -27,15 +28,30 @@ Most importantly, *the `onConfigured()` callback is not supported in manual mode ...@@ -27,15 +28,30 @@ Most importantly, *the `onConfigured()` callback is not supported in manual mode
#### Returns #### Returns
The current setting, true if manual mode is enabled, false if it is not. The current setting, true if manual mode is enabled, false if it is not.
#### Example
```lua
wifi.setmode(wifi.STATIONAP)
wifi.ap.config({ssid="MyPersonalSSID",auth=wifi.AUTH_OPEN})
enduser_setup.manual(true)
enduser_setup.start(
function()
print("Connected to wifi as:" .. wifi.sta.getip())
end,
function(err, str)
print("enduser_setup: Err #" .. err .. ": " .. str)
end
);
```
## enduser_setup.start() ## enduser_setup.start()
Starts the captive portal. Starts the captive portal.
#### Syntax #### Syntax
`enduser_setup.start([onConfigured()], [onError(err_num, string)], [onDebug(string)])` `enduser_setup.start([onConnected()], [onError(err_num, string)], [onDebug(string)])`
#### Parameters #### Parameters
- `onConfigured()` callback will be fired when an IP-address has been obtained, just before the enduser_setup module will terminate itself - `onConnected()` callback will be fired when an IP-address has been obtained, just before the enduser_setup module will terminate itself
- `onError()` callback will be fired if an error is encountered. `err_num` is a number describing the error, and `string` contains a description of the error. - `onError()` callback will be fired if an error is encountered. `err_num` is a number describing the error, and `string` contains a description of the error.
- `onDebug()` callback is disabled by default. It is intended to be used to find internal issues in the module. `string` contains a description of what is going on. - `onDebug()` callback is disabled by default. It is intended to be used to find internal issues in the module. `string` contains a description of what is going on.
......
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