httpServer.ino 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782
  1. //extern ESP8266WebServer httpServer;
  2. static const char html_head_part1[] PROGMEM =
  3. "<html><head>"
  4. "<meta charset='utf-8'>"
  5. "<meta name='viewport' content='width=device-width,initial-scale=1,user-scalable=no'/>"
  6. "<title>WiFi-PC-Controller - ";
  7. static const char html_head_part2[] PROGMEM =
  8. "</title>"
  9. "<style>div,fieldset,input,select{padding:5px;font-size:1em;}fieldset{background:#f2f2f2;}p{margin:0.5em 0;}input{width:100%;box-sizing:border-box;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;background:#ffffff;color:#000000;}input[type=checkbox],input[type=radio]{width:1em;margin-right:6px;vertical-align:-1px;}input[type=range]{width:99%;}select{width:100%;background:#ffffff;color:#000000;}textarea{resize:none;width:98%;height:318px;padding:5px;overflow:auto;background:#ffffff;color:#000000;}body{text-align:center;font-family:verdana,sans-serif;background:#ffffff;}td{padding:0px;}button{border:0;border-radius:0.3rem;background:#1fa3ec;color:#ffffff;line-height:2.4rem;font-size:1.2rem;width:100%;-webkit-transition-duration:0.4s;transition-duration:0.4s;cursor:pointer;}button:hover{background:#0e70a4;}.bred{background:#d43535;}.bred:hover{background:#931f1f;}.bgrn{background:#47c266;}.bgrn:hover{background:#5aaf6f;}a{color:#1fa3ec;text-decoration:none;}.p{float:left;text-align:left;}.q{float:right;text-align:right;}.r{border-radius:0.3em;padding:2px;margin:6px 2px;}</style>";
  10. static const char html_root_script[] PROGMEM = R"(
  11. <script>
  12. function g(i) { return document.getElementById(i) };
  13. var xhttp, updateTime, reqTime, reqFin;
  14. function sendBtn(btn, conf) {
  15. var frmn='BtnFrm'+btn;
  16. var form = g(frmn);
  17. if(conf !== undefined) {
  18. if(confirm(conf)) return transmit(form);
  19. else return false;
  20. }
  21. else return transmit(form);
  22. }
  23. function transmit(f) {
  24. if (!xhttp) {
  25. reqTime = 0;
  26. reqFin = false;
  27. xhttp = new XMLHttpRequest();
  28. xhttp.timeout = 1000;
  29. xhttp.overrideMimeType("application/json");
  30. xhttp.open('POST', 'api');
  31. xhttp.send(f ? (new FormData(f)) : '');
  32. xhttp.onreadystatechange = function () {
  33. if (xhttp.readyState === XMLHttpRequest.DONE && xhttp.status === 200) {
  34. var data = JSON.parse(xhttp.responseText);
  35. g('PCstate').innerHTML = data.PCstate;
  36. if(data.PCstate == "ON") {
  37. g('PCstate').style.fontWeight = "bold";
  38. }
  39. else g('PCstate').style.fontWeight = "normal";
  40. if(data.ssid !== undefined) g('ssid').innerHTML = data.ssid;
  41. if(data.mqttstate !== undefined) {
  42. if(data.mqttstate == "CONNECTED" && data.mqtthost !== undefined) {
  43. g('mqttstate').innerHTML = data.mqttstate + ' to <i>' + data.mqtthost + '</i>';
  44. }
  45. else g('mqttstate').innerHTML = data.mqttstate;
  46. }
  47. if(data.uptime !== undefined) g('uptime').innerHTML = data.uptime;
  48. if(data.mqttreconn !== undefined) g('mqttreconn').innerHTML = data.mqttreconn;
  49. xhttp = null;
  50. updateTime = 0;
  51. reqFin = true;
  52. }
  53. else {
  54. if(!reqFin && reqTime > 10) {
  55. xhttp = null;
  56. reqFin = true;
  57. }
  58. }
  59. }
  60. }
  61. return false;
  62. }
  63. function init() {
  64. transmit();
  65. }
  66. setInterval(transmit, 2500);
  67. </script>
  68. )"; // html_root_script
  69. static const char html_confweb_script[] PROGMEM = R"(
  70. <script>
  71. function g(i) { return document.getElementById(i) };
  72. function sp(i){g(i).type=(g(i).type==='text'?'password':'text');}
  73. var xhttp, reqTime, reqFin;
  74. function setCbx(el, da) {
  75. if(da == '1') {
  76. el.checked = true;
  77. el.style.visibility = 'visible';
  78. }
  79. else {
  80. el.checked = false;
  81. el.style.visibility = 'visible';
  82. }
  83. }
  84. function updCbxVal(el) {
  85. if (el.checked) el.value = '1';
  86. else {
  87. el.checked = true;
  88. el.value = '0';
  89. el.style.visibility = 'hidden';
  90. }
  91. }
  92. function transmit(f) {
  93. if (!xhttp) {
  94. reqTime = 0;
  95. reqFin = false;
  96. updCbxVal(g('httpAuth'));
  97. xhttp = new XMLHttpRequest();
  98. xhttp.timeout = 1000;
  99. xhttp.overrideMimeType('application/json');
  100. xhttp.open('POST', 'confdweb');
  101. xhttp.send(f ? (new FormData(f)) : '');
  102. xhttp.onreadystatechange = function () {
  103. if (xhttp.readyState === XMLHttpRequest.DONE && xhttp.status === 200) {
  104. var data = JSON.parse(xhttp.responseText);
  105. g('devName').value = data.devName;
  106. g('apiToken').value = data.apiToken;
  107. g('httpUA').value = data.httpUA;
  108. setCbx(g('httpAuth'), data.httpAuth);
  109. g('httpU1').value = data.httpU1;
  110. g('httpU2').value = data.httpU2;
  111. xhttp = null;
  112. reqFin = true;
  113. }
  114. else {
  115. if(!reqFin && reqTime > 10) {
  116. xhttp = null;
  117. reqFin = true;
  118. }
  119. }
  120. }
  121. }
  122. return false;
  123. }
  124. //transmit();
  125. function saveConf() {
  126. updCbxVal(g('httpAuth'));
  127. if(g('httpPA').value != g('httpPAC').value) {
  128. alert("Admin password verification failed!");
  129. }
  130. else g('frmConf').submit();
  131. }
  132. function init() {
  133. transmit();
  134. setCbx(g('httpPASet'), 0);
  135. setCbx(g('httpP1Set'), 0);
  136. setCbx(g('httpP2Set'), 0);
  137. }
  138. setInterval(function () { ++reqTime; }, 1000);
  139. </script>
  140. )"; // html_confweb_script
  141. static const char html_confmqtt_script[] PROGMEM = R"(
  142. <script>
  143. function g(i) { return document.getElementById(i) };
  144. function sp(i){g(i).type=(g(i).type==='text'?'password':'text');}
  145. var xhttp, reqTime, reqFin;
  146. function setCbx(el, da) {
  147. if(da == '1') {
  148. el.checked = true;
  149. el.style.visibility = 'visible';
  150. }
  151. else {
  152. el.checked = false;
  153. el.style.visibility = 'visible';
  154. }
  155. }
  156. function updCbxVal(el) {
  157. if (el.checked) el.value = '1';
  158. else {
  159. el.checked = true;
  160. el.value = '0';
  161. el.style.visibility = 'hidden';
  162. }
  163. }
  164. function transmit(f) {
  165. if (!xhttp) {
  166. reqTime = 0;
  167. reqFin = false;
  168. updCbxVal(g('outRet'));
  169. updCbxVal(g('willRet'));
  170. xhttp = new XMLHttpRequest();
  171. xhttp.timeout = 1000;
  172. xhttp.overrideMimeType('application/json');
  173. xhttp.open('POST', 'confdmqtt');
  174. xhttp.send(f ? (new FormData(f)) : '');
  175. xhttp.onreadystatechange = function () {
  176. if (xhttp.readyState === XMLHttpRequest.DONE && xhttp.status === 200) {
  177. var data = JSON.parse(xhttp.responseText);
  178. g('mqttHost').value = data.mqttHost;
  179. g('mqttPort').value = data.mqttPort;
  180. g('mqttUser').value = data.mqttUser;
  181. g('inTop').value = data.inTop;
  182. g('outTop').value = data.outTop;
  183. g('willTop').value = data.willTop;
  184. g('willQos').value = data.willQos;
  185. setCbx(g('outRet'), data.outRet);
  186. setCbx(g('willRet'), data.willRet);
  187. g('willMsg').value = data.willMsg;
  188. g('connMsg').value = data.connMsg;
  189. xhttp = null;
  190. reqFin = true;
  191. }
  192. else {
  193. if(!reqFin && reqTime > 10) {
  194. xhttp = null;
  195. reqFin = true;
  196. }
  197. }
  198. }
  199. }
  200. return false;
  201. }
  202. //transmit();
  203. function saveConf() {
  204. updCbxVal(g('outRet'));
  205. updCbxVal(g('willRet'));
  206. g('frmConf').submit();
  207. }
  208. function init() {
  209. transmit();
  210. setCbx(g('mqttPassSet'), 0);
  211. }
  212. setInterval(function () { ++reqTime; }, 1000);
  213. </script>
  214. )"; // html_confmqtt_script
  215. static const char html_head_part3[] PROGMEM =
  216. R"(</head>)"; // html_head_part3
  217. static const char html_bodytag_jsinit[] PROGMEM = R"(
  218. <body onload='init()'>)";
  219. static const char html_bodytag[] PROGMEM = R"(
  220. <body>)";
  221. static const char html_body_part1[] PROGMEM = R"(
  222. <div style='text-align:left;display:inline-block;color:#000000;min-width:340px;'>
  223. <div style='text-align:center;color:#000000;'><noscript>Please enable JavaScript<br></noscript>
  224. <h3>WiFi-PC-Controller</h3>
  225. <h2>
  226. )"; // html_body_part1
  227. static const char html_body_part2[] PROGMEM = R"(</h2>
  228. </div>)"; // html_body_part2
  229. static const char html_root_body[] PROGMEM = R"(
  230. <div id="PCstate" style="text-align:center;font-weight:normal;font-size:50px"></div>
  231. <p><form id='BtnFrmPwr'><input type='hidden' name='BtnPwr' value='1'><button onclick='return sendBtn("Pwr")'>PC Power-Button</button></form></p>
  232. <p><form id='BtnFrmPwrH'><input type='hidden' name='BtnPwrH' value='1'><button onclick='return sendBtn("PwrH","Confirm PC Power Hold")' class='button bred'>PC Power-Button HOLD</button></form></p>
  233. <p><form id='BtnFrmRes'><input type='hidden' name='BtnRes' value='1'><button onclick='return sendBtn("Res", "Confirm PC Reset")' class='button bred'>PC Reset-Button</button></form></p>
  234. <div></div>
  235. <div></div>
  236. )"; // html_root_body
  237. static const char html_root_body_adminonly[] PROGMEM = R"(
  238. <p><form action='conf' method='get'><button>Configuration</button></form></p>
  239. <p><form action='update' method='get'><button>Firmware update</button></form></p>
  240. )"; // html_root_body_adminonly
  241. static const char html_root_body2[] PROGMEM = R"(
  242. <p><form action='/' method='get' onsubmit='return confirm("Confirm Restart");'><button name='restart' class='button bred'>Restart</button></form></p>
  243. <hr/>
  244. <p>WiFi connected to <i><span id='ssid'></span></i></p>
  245. <p>MQTT <span id='mqttstate'></span></p>
  246. <p>MQTT reconnects: <span id='mqttreconn'></span></p>
  247. <p>Uptime: <span id='uptime'></span></p>
  248. )"; // html_root_body2
  249. static const char html_conf_body[] PROGMEM = R"(
  250. <p><form action='wifi.htm' method='get'><button>Configure WiFi</button></form></p>
  251. <p><form action='confweb' method='get'><button>Configure Web</button></form></p>
  252. <p><form action='confmqtt' method='get'><button>Configure MQTT</button></form></p>
  253. <div></div>
  254. <p><form action='/' method='get' onsubmit='return confirm("Confirm Restart");'><button name='restart' class='button bred'>Restart</button></form></p>
  255. <p><form action='./' method='get'><button>Main Menu</button></form></p>
  256. )"; // html_conf_body
  257. static const char html_confweb_body[] PROGMEM = R"(
  258. <fieldset>
  259. <legend><b>&nbsp;Web Configuration&nbsp;</b></legend>
  260. <form id='frmConf' action='setConfWeb' method='POST'>
  261. <p><b>Device Name</b><br><input type='text' name='devName' id='devName'></p>
  262. <p><b>API Token</b><br><input type='text' name='apiToken' id='apiToken'></p>
  263. <div><hr></div>
  264. <p><b>HTTP Admin Username *</b><br><input type='text' name='httpUA' id='httpUA'></p>
  265. <p><b>HTTP Admin Password *</b><input type='checkbox' id='httpPASet' name='httpPASet' onclick='sp("httpPA")'><br><input type='password' name='httpPA' id='httpPA'></p>
  266. <p><b>Confirm Password *</b><br><input type='password' name='httpPAC' id='httpPAC'></p>
  267. <div><hr></div>
  268. <p><b>Enable User-Authentication *</b>&nbsp;<input type='checkbox' name='httpAuth' id='httpAuth'></p>
  269. <p><b>HTTP User 1 *</b><br><input type='text' name='httpU1' id='httpU1'></p>
  270. <p><b>HTTP User 1 Password *</b><input type='checkbox' id='httpP1Set' name='httpP1Set' onclick='sp("httpP1")'><br><input type='password' name='httpP1' id='httpP1'></p>
  271. <div><hr></div>
  272. <p><b>HTTP User 2 *</b><br><input type='text' name='httpU2' id='httpU2'></p>
  273. <p><b>HTTP User 2 Password *</b><input type='checkbox' id='httpP2Set' name='httpP2Set' onclick='sp("httpP2")'><br><input type='password' name='httpP2' id='httpP2'></p>
  274. </form>
  275. <p><button onclick='return saveConf()'>Save</button></p>
  276. <p><button onclick='return transmit()'>Reload</button></p>
  277. </fieldset>
  278. <p><form action='conf' method='get'><button>Configuration</button></form></p>
  279. <p><form action='/' method='get' onsubmit='return confirm("Confirm Restart");'><button name='restart' class='button bred'>Restart</button></form></p>
  280. )"; // html_confweb_body
  281. static const char html_confmqtt_body[] PROGMEM = R"(
  282. <fieldset>
  283. <legend><b>&nbsp;MQTT Configuration&nbsp;</b></legend>
  284. <form id='frmConf' action='setConfMqtt' method='POST'>
  285. <p><b>MQTT Server *</b><br><input type='text' name='mqttHost' id='mqttHost'></p>
  286. <p><b>MQTT Port *</b><br><input type='number' name='mqttPort' id='mqttPort'></p>
  287. <p><b>MQTT User *</b><br><input type='text' name='mqttUser' id='mqttUser'></p>
  288. <p><b>MQTT Password *</b><input type='checkbox' id='mqttPassSet' name='mqttPassSet' onclick='sp("mqttPass")'><br><input type='password' name='mqttPass' id='mqttPass'></p>
  289. <p><b>In Topic *</b><br><input type='text' name='inTop' id='inTop'></p>
  290. <p><b>Out Topic</b><br><input type='text' name='outTop' id='outTop'></p>
  291. <p><b>Out Retain *</b>&nbsp;<input type='checkbox' name='outRet' id='outRet'></p>
  292. <p><b>LastWill Topic *</b><br><input type='text' name='willTop' id='willTop'></p>
  293. <p><b>LastWill Qos *</b><br><select name='willQos' id='willQos'><option>0</option><option>1</option><option selected='selected'>2</option></select></p>
  294. <p><b>LastWill Retain *</b>&nbsp;<input type='checkbox' name='willRet' id='willRet'></p>
  295. <p><b>LastWill Message *</b><br><input type='text' name='willMsg' id='willMsg'></p>
  296. <p><b>Connect Message *</b><br><input type='text' name='connMsg' id='connMsg'></p>
  297. </form>
  298. <p><button onclick='return saveConf()'>Save</button></p>
  299. <p><button onclick='return transmit()'>Reload</button></p>
  300. </fieldset>
  301. <p><form action='conf' method='get'><button>Configuration</button></form></p>
  302. <p><form action='/' method='get' onsubmit='return confirm("Confirm Restart");'><button name='restart' class='button bred'>Restart</button></form></p>
  303. )"; // html_confmqtt_body
  304. static const char html_confsaved_body[] PROGMEM = R"(
  305. <script>setTimeout(function(){window.location.href = '.';}, 7000);</script>
  306. <div>Config saved. Restarting...</div>
  307. <p><form action='./' method='get'><button>Main Menu</button></form></p>
  308. )"; // html_confsaved_body
  309. static const char html_restarting_body[] PROGMEM = R"(
  310. <script>setTimeout(function(){window.location.href = '.';}, 7000);</script>
  311. <div>Restarting...</div>
  312. <p><form action='./' method='get'><button>Main Menu</button></form></p>
  313. )"; // html_restarting_body
  314. static const char html_footer[] PROGMEM = R"(
  315. <div style='text-align:right;font-size:11px;'><hr/><a href='https://git.flokra.at/WiFiPCController' target='_blank' style='color:#aaa;'>WiFi-PC-Controller 1.0.0 by Flo Kra</a></div>
  316. </div></body></html>
  317. )";
  318. void httpServerHandleRoot() {
  319. //httpServer.send_P(200, "text/html", httpRoot);
  320. httpServer.setContentLength(CONTENT_LENGTH_UNKNOWN); //Enable Chunked Transfer
  321. httpServer.send(200, "text/html", html_head_part1);
  322. httpServer.sendContent(deviceName);
  323. httpServer.sendContent_P(html_head_part2);
  324. httpServer.sendContent_P(html_root_script);
  325. httpServer.sendContent_P(html_head_part3);
  326. httpServer.sendContent_P(html_bodytag_jsinit);
  327. httpServer.sendContent_P(html_body_part1);
  328. httpServer.sendContent(deviceName);
  329. httpServer.sendContent_P(html_body_part2);
  330. httpServer.sendContent_P(html_root_body);
  331. if(httpIsAuthenticatedAdmin()) httpServer.sendContent_P(html_root_body_adminonly);
  332. httpServer.sendContent_P(html_root_body2);
  333. httpServer.sendContent_P(html_footer);
  334. httpServer.sendContent("");
  335. httpServer.client().stop();
  336. }
  337. void httpServerHandleConfPage() {
  338. //httpServer.send_P(200, "text/html", httpConfPage);
  339. httpServer.setContentLength(CONTENT_LENGTH_UNKNOWN); //Enable Chunked Transfer
  340. httpServer.send(200, "text/html", html_head_part1);
  341. httpServer.sendContent(deviceName);
  342. httpServer.sendContent_P(html_head_part2);
  343. //httpServer.sendContent_P(html_conf_script);
  344. httpServer.sendContent_P(html_head_part3);
  345. httpServer.sendContent_P(html_bodytag);
  346. httpServer.sendContent_P(html_body_part1);
  347. httpServer.sendContent(deviceName);
  348. httpServer.sendContent_P(html_body_part2);
  349. httpServer.sendContent_P(html_conf_body);
  350. httpServer.sendContent_P(html_footer);
  351. httpServer.sendContent("");
  352. httpServer.client().stop();
  353. }
  354. void httpServerHandleConfWebPage() {
  355. //httpServer.send_P(200, "text/html", httpConfPage);
  356. httpServer.setContentLength(CONTENT_LENGTH_UNKNOWN); //Enable Chunked Transfer
  357. httpServer.send(200, "text/html", html_head_part1);
  358. httpServer.sendContent(deviceName);
  359. httpServer.sendContent_P(html_head_part2);
  360. httpServer.sendContent_P(html_confweb_script);
  361. httpServer.sendContent_P(html_head_part3);
  362. httpServer.sendContent_P(html_bodytag_jsinit);
  363. httpServer.sendContent_P(html_body_part1);
  364. httpServer.sendContent(deviceName);
  365. httpServer.sendContent_P(html_body_part2);
  366. httpServer.sendContent_P(html_confweb_body);
  367. httpServer.sendContent_P(html_footer);
  368. httpServer.sendContent("");
  369. httpServer.client().stop();
  370. }
  371. void httpServerHandleConfMqttPage() {
  372. //httpServer.send_P(200, "text/html", httpConfPage);
  373. httpServer.setContentLength(CONTENT_LENGTH_UNKNOWN); //Enable Chunked Transfer
  374. httpServer.send(200, "text/html", html_head_part1);
  375. httpServer.sendContent(deviceName);
  376. httpServer.sendContent_P(html_head_part2);
  377. httpServer.sendContent_P(html_confmqtt_script);
  378. httpServer.sendContent_P(html_head_part3);
  379. httpServer.sendContent_P(html_bodytag_jsinit);
  380. httpServer.sendContent_P(html_body_part1);
  381. httpServer.sendContent(deviceName);
  382. httpServer.sendContent_P(html_body_part2);
  383. httpServer.sendContent_P(html_confmqtt_body);
  384. httpServer.sendContent_P(html_footer);
  385. httpServer.sendContent("");
  386. httpServer.client().stop();
  387. }
  388. void httpServerHandleNotFound() {
  389. // if (strlen(http_user) > 0 && strlen(http_pass) > 0) {
  390. // if (!httpServer.authenticate(http_user, http_pass))
  391. // return httpServer.requestAuthentication();
  392. httpServer.send(404, "text/plain", "");
  393. //}
  394. }
  395. boolean httpIsAuthenticated() {
  396. if(http_user_auth) {
  397. boolean auth=false;
  398. if ((strlen(http_user) > 0 && strlen(http_pass) > 0) || (strlen(http_user1) > 0 && strlen(http_pass1) > 0) || (strlen(http_user2) > 0 && strlen(http_pass2) > 0)) auth=true;
  399. if (auth) {
  400. if (!httpServer.authenticate(http_user, http_pass) && !httpServer.authenticate(http_user1, http_pass1) && !httpServer.authenticate(http_user2, http_pass2)) return false;
  401. else return true;
  402. }
  403. else return true;
  404. }
  405. else return true;
  406. }
  407. boolean httpIsAuthenticatedAdmin() {
  408. boolean auth=false;
  409. if ((strlen(http_user) > 0 && strlen(http_pass) > 0)) auth=true;
  410. if(auth) {
  411. if (!httpServer.authenticate(http_user, http_pass)) return false;
  412. else return true;
  413. }
  414. else return true;
  415. }
  416. void httpSendUnauthorized() {
  417. httpServer.send (401, "text/plain", "UNAUTHORIZED");
  418. }
  419. void httpSend200OK() {
  420. httpServer.send (200, "text/plain", "OK");
  421. }
  422. boolean httpCheckToken() {
  423. if (http_token[0] != '\0') { // dont accept empty token
  424. if (httpServer.hasArg("token")) {
  425. char buf[20];
  426. httpServer.arg("token").toCharArray(buf, 20);
  427. if (strcmp(buf, http_token) == 0) return true;
  428. else return false;
  429. }
  430. }
  431. }
  432. void httpServerInit() {
  433. httpServer.on("/delconf", []() {
  434. Serial.println("httpServer.on /delconf");
  435. if ( httpIsAuthenticatedAdmin() || (!httpIsAuthenticatedAdmin() && httpCheckToken()) ) {
  436. deleteConfig();
  437. }
  438. else {
  439. httpSendUnauthorized();
  440. }
  441. });
  442. httpServer.on("/api", []() {
  443. if ( httpIsAuthenticated() || (!httpIsAuthenticated() && httpCheckToken()) ) {
  444. //Serial.println("httpServer.on /api");
  445. if (httpServer.hasArg("BtnPwr")) {
  446. Serial.println("web BtnPwr");
  447. PC_pwrSwitchShort();
  448. }
  449. if (httpServer.hasArg("BtnPwrH")) {
  450. Serial.println("web BtnPwrH");
  451. PC_pwrSwitchHold();
  452. }
  453. if (httpServer.hasArg("BtnRes")) {
  454. Serial.println("web BtnRes");
  455. PC_resSwitch();
  456. }
  457. yield();
  458. //build json object of program data
  459. StaticJsonBuffer<200> jsonBuffer;
  460. JsonObject &json = jsonBuffer.createObject();
  461. json["ssid"] = WiFi.SSID();
  462. json["devname"] = deviceName;
  463. json["uptime"] = uptimeStr;
  464. json["freeheap"] = ESP.getFreeHeap();
  465. //if(mqttclient.state() == 0) json["mqttstate"] = "connected";
  466. //else json["mqttstate"] = mqttclient.state();
  467. if(mqttclient.state() == -4) json["mqttstate"] = "CONNECTION_TIMEOUT";
  468. else if(mqttclient.state() == -3) json["mqttstate"] = "CONNECTION_LOST";
  469. else if(mqttclient.state() == -2) json["mqttstate"] = "CONNECT_FAILED";
  470. else if(mqttclient.state() == -1) json["mqttstate"] = "DISCONNECTED";
  471. else if(mqttclient.state() == 0) json["mqttstate"] = "CONNECTED";
  472. else if(mqttclient.state() == 1) json["mqttstate"] = "CONNECT_BAD_PROTOCOL";
  473. else if(mqttclient.state() == 2) json["mqttstate"] = "CONNECT_BAD_CLIENT_ID";
  474. else if(mqttclient.state() == 3) json["mqttstate"] = "CONNECT_UNAVAILABLE";
  475. else if(mqttclient.state() == 4) json["mqttstate"] = "CONNECT_BAD_CREDENTIALS";
  476. else if(mqttclient.state() == 5) json["mqttstate"] = "CONNECT_UNAUTHORIZED";
  477. json["mqtthost"] = mqtt_server;
  478. json["mqttreconn"] = mqttReconnects - 1;
  479. if (PCstate == 0) json["PCstate"] = "OFF";
  480. else if (PCstate == 1) json["PCstate"] = "ON";
  481. else if (PCstate == 2) json["PCstate"] = "SLEEP";
  482. else json["PCstate"] = "unknown";
  483. yield();
  484. char jsonchar[200];
  485. json.printTo(jsonchar); //print to char array, takes more memory but sends in one piece
  486. httpServer.send(200, "application/json", jsonchar);
  487. }
  488. else {
  489. httpSendUnauthorized();
  490. }
  491. }); //httpServer.on /api
  492. // httpServer.on("/restart", []() {
  493. // if ( httpIsAuthenticated() || (!httpIsAuthenticated() && httpCheckToken()) ) {
  494. // //Serial.println("web triggered restart");
  495. // ESP.restart();
  496. // }
  497. // else httpSendUnauthorized();
  498. // });
  499. httpServer.on("/mqttReconnect", []() {
  500. if ( httpIsAuthenticated() || (!httpIsAuthenticated() && httpCheckToken()) ) {
  501. //Serial.println("web triggered mqttReconnect");
  502. mqttReconnect();
  503. httpServer.sendHeader("Location", "/", true);
  504. httpServer.send(303);
  505. }
  506. else httpSendUnauthorized();
  507. });
  508. httpServer.on("/confdweb", []() {
  509. if (!httpIsAuthenticatedAdmin()) httpSendUnauthorized();
  510. else {
  511. Serial.println("httpServer.on /confdata");
  512. //build json object of program data
  513. StaticJsonBuffer<1000> jsonBuffer;
  514. JsonObject &json = jsonBuffer.createObject();
  515. json["devName"] = deviceName;
  516. json["apiToken"] = http_token;
  517. json["httpUA"] = http_user;
  518. //json["httpPA"] = http_pass;
  519. if(http_user_auth) json["httpAuth"] = "1";
  520. else json["httpAuth"] = "0";
  521. json["httpU1"] = http_user1;
  522. //json["httpP1"] = http_pass1;
  523. json["httpU2"] = http_user2;
  524. //json["httpP2"] = http_pass2;
  525. yield();
  526. char jsonchar[1000];
  527. json.printTo(jsonchar); //print to char array, takes more memory but sends in one piece
  528. httpServer.send(200, "application/json", jsonchar);
  529. }
  530. }); //httpServer.on /confdweb
  531. httpServer.on("/confdmqtt", []() {
  532. if (!httpIsAuthenticatedAdmin()) httpSendUnauthorized();
  533. else {
  534. Serial.println("httpServer.on /confdata");
  535. //build json object of program data
  536. StaticJsonBuffer<1000> jsonBuffer;
  537. JsonObject &json = jsonBuffer.createObject();
  538. json["mqttHost"] = mqtt_server;
  539. json["mqttPort"] = mqtt_port;
  540. json["mqttUser"] = mqtt_user;
  541. //json["mqttPass"] = mqtt_pass;
  542. json["inTop"] = mqtt_topic_in;
  543. json["outTop"] = mqtt_topic_out;
  544. if(mqtt_outRetain) json["outRet"] = "1";
  545. else json["outRet"] = "0";
  546. json["willTop"] = mqtt_willTopic;
  547. json["willQos"] = mqtt_willQos;
  548. if(mqtt_willRetain) json["willRet"] = "1";
  549. else json["willRet"] = "0";
  550. json["willMsg"] = mqtt_willMsg;
  551. json["connMsg"] = mqtt_connMsg;
  552. yield();
  553. char jsonchar[1000];
  554. json.printTo(jsonchar); //print to char array, takes more memory but sends in one piece
  555. httpServer.send(200, "application/json", jsonchar);
  556. }
  557. }); //httpServer.on /confdmqtt
  558. httpServer.on("/setConfWeb", []() {
  559. if (!httpIsAuthenticatedAdmin()) httpSendUnauthorized();
  560. else {
  561. Serial.println("httpServer.on /setConfWeb");
  562. bool httpPASet, httpP1Set, httpP2Set;
  563. httpPASet = false;
  564. httpP1Set = false;
  565. httpP2Set = false;
  566. if(httpServer.hasArg("httpPASet")) httpPASet = true;
  567. if(httpServer.hasArg("httpP1Set")) httpP1Set = true;
  568. if(httpServer.hasArg("httpP2Set")) httpP2Set = true;
  569. for (int i = 0; i < httpServer.args(); i++) {
  570. char bufName[20];
  571. char bufValue[101];
  572. httpServer.argName(i).toCharArray(bufName, 20);
  573. httpServer.arg(i).toCharArray(bufValue, 101);
  574. if (strlen(bufName) > 0) {
  575. Serial.print("web update ");
  576. Serial.print(bufName);
  577. Serial.print(" = ");
  578. Serial.println(bufValue);
  579. if(strcmp(bufName, "httpUA") == 0 || strcmp(bufName, "httpPA") == 0) {
  580. if(httpPASet) setConfig(bufName, bufValue);
  581. }
  582. else if(strcmp(bufName, "httpU1") == 0 || strcmp(bufName, "httpP1") == 0) {
  583. if(httpP1Set) setConfig(bufName, bufValue);
  584. }
  585. else if(strcmp(bufName, "httpU2") == 0 || strcmp(bufName, "httpP2") == 0) {
  586. if(httpP2Set) setConfig(bufName, bufValue);
  587. }
  588. else if(strcmp(bufName, "httpPASet") != 0 && strcmp(bufName, "httpP1Set") != 0 && strcmp(bufName, "httpP2Set") != 0) setConfig(bufName, bufValue);
  589. //else setConfig(bufName, bufValue);
  590. }
  591. saveConfigWebToFlash = true; // will be saved in next loop()
  592. Serial.println("web triggered saveConfigWebToFlash");
  593. }
  594. yield();
  595. saveConfigWeb();
  596. httpServer.setContentLength(CONTENT_LENGTH_UNKNOWN); //Enable Chunked Transfer
  597. httpServer.send(200, "text/html", html_head_part1);
  598. httpServer.sendContent(deviceName);
  599. httpServer.sendContent_P(html_head_part2);
  600. httpServer.sendContent_P(html_head_part3);
  601. httpServer.sendContent_P(html_bodytag_jsinit);
  602. httpServer.sendContent_P(html_body_part1);
  603. httpServer.sendContent(deviceName);
  604. httpServer.sendContent_P(html_body_part2);
  605. httpServer.sendContent_P(html_confsaved_body);
  606. httpServer.sendContent_P(html_footer);
  607. httpServer.sendContent("");
  608. httpServer.client().stop();
  609. yield();
  610. ESP.restart();
  611. }
  612. }); //httpServer.on /setConfWeb
  613. httpServer.on("/setConfMqtt", []() {
  614. if (!httpIsAuthenticatedAdmin()) httpSendUnauthorized();
  615. else {
  616. Serial.println("httpServer.on /setConfMqtt");
  617. bool mqttPassSet;
  618. mqttPassSet = false;
  619. if(httpServer.hasArg("mqttPassSet")) mqttPassSet = true;
  620. for (int i = 0; i < httpServer.args(); i++) {
  621. char bufName[20];
  622. char bufValue[101];
  623. httpServer.argName(i).toCharArray(bufName, 20);
  624. httpServer.arg(i).toCharArray(bufValue, 101);
  625. if (strlen(bufName) > 0) {
  626. Serial.print("web update ");
  627. Serial.print(bufName);
  628. Serial.print(" = ");
  629. Serial.println(bufValue);
  630. if(strcmp(bufName, "mqttUser") == 0 || strcmp(bufName, "mqttPass") == 0) {
  631. if(mqttPassSet) setConfig(bufName, bufValue);
  632. }
  633. else setConfig(bufName, bufValue);
  634. }
  635. saveConfigMqttToFlash = true; // will be saved in next loop()
  636. Serial.println("web triggered saveConfigMqttToFlash");
  637. }
  638. yield();
  639. saveConfigMqtt();
  640. httpServer.setContentLength(CONTENT_LENGTH_UNKNOWN); //Enable Chunked Transfer
  641. httpServer.send(200, "text/html", html_head_part1);
  642. httpServer.sendContent(deviceName);
  643. httpServer.sendContent_P(html_head_part2);
  644. httpServer.sendContent_P(html_head_part3);
  645. httpServer.sendContent_P(html_bodytag);
  646. httpServer.sendContent_P(html_body_part1);
  647. httpServer.sendContent(deviceName);
  648. httpServer.sendContent_P(html_body_part2);
  649. httpServer.sendContent_P(html_confsaved_body);
  650. httpServer.sendContent_P(html_footer);
  651. httpServer.sendContent("");
  652. httpServer.client().stop();
  653. yield();
  654. ESP.restart();
  655. }
  656. }); //httpServer.on /setConfMqtt
  657. httpServer.on("/", []() {
  658. if (httpServer.hasArg("restart")) {
  659. httpServer.setContentLength(CONTENT_LENGTH_UNKNOWN); //Enable Chunked Transfer
  660. httpServer.send(200, "text/html", html_head_part1);
  661. httpServer.sendContent(deviceName);
  662. httpServer.sendContent_P(html_head_part2);
  663. httpServer.sendContent_P(html_head_part3);
  664. httpServer.sendContent_P(html_bodytag);
  665. httpServer.sendContent_P(html_body_part1);
  666. httpServer.sendContent(deviceName);
  667. httpServer.sendContent_P(html_body_part2);
  668. httpServer.sendContent_P(html_restarting_body);
  669. httpServer.sendContent_P(html_footer);
  670. httpServer.sendContent("");
  671. httpServer.client().stop();
  672. yield();
  673. ESP.restart();
  674. }
  675. else if (!httpIsAuthenticated()) return httpServer.requestAuthentication();
  676. else {
  677. httpServerHandleRoot();
  678. }
  679. });
  680. httpServer.on("/conf", []() {
  681. if (!httpIsAuthenticatedAdmin()) return httpServer.requestAuthentication();
  682. else {
  683. httpServerHandleConfPage();
  684. }
  685. });
  686. httpServer.on("/confweb", []() {
  687. if (!httpIsAuthenticatedAdmin()) return httpServer.requestAuthentication();
  688. else {
  689. httpServerHandleConfWebPage();
  690. }
  691. });
  692. httpServer.on("/confmqtt", []() {
  693. if (!httpIsAuthenticatedAdmin()) return httpServer.requestAuthentication();
  694. else {
  695. httpServerHandleConfMqttPage();
  696. }
  697. });
  698. httpServer.onNotFound([]() {
  699. httpServerHandleNotFound();
  700. }); //httpServer.onNotFound
  701. // HTTP Updater at /update
  702. httpUpdater.setup(&httpServer, "/update", http_user, http_pass);
  703. httpServer.begin();
  704. }