webpack.dev.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. /* eslint-disable */
  2. var path = require('path');
  3. const bodyParser = require('body-parser')
  4. const { config } = require('process');
  5. const HtmlWebPackPlugin = require('html-webpack-plugin');
  6. const { Command } = require('commander');
  7. let cmdLines= { };
  8. var { parseArgsStringToArgv } = require('string-argv');
  9. const PORT = 5000;
  10. const data = {
  11. messages: require("../mock/messages.json"),
  12. messagequeue: require("../mock/messages.json"),
  13. message_queue_sequence: [],
  14. status_queue_sequence:[],
  15. message_queue_sequence_post_empty: null,
  16. status_queue_sequence_post_empty: null,
  17. commands: require("../mock/commands.json"),
  18. scan: require("../mock/scan.json"),
  19. ap: require("../mock/ap.json"),
  20. config: require("../mock/config.json"),
  21. statusdefinition: require("../mock/statusdefinition.json"),
  22. status: require("../mock/status.json"),
  23. messages_ota_fail: require("../mock/messages_ota_fail.json"),
  24. messages_ota_flash: require("../mock/messages_ota_flash.json"),
  25. messages_ota: require("../mock/messages_ota.json"),
  26. rebooting: false,
  27. reboottime: Date.now(),
  28. devServer:{}
  29. };
  30. const messagingTypes= {
  31. MESSAGING_INFO : 'MESSAGING_INFO',
  32. MESSAGING_WARNING : 'MESSAGING_WARNING',
  33. MESSAGING_ERROR : 'MESSAGING_ERROR'
  34. };
  35. const messagingClass= {
  36. MESSAGING_CLASS_OTA : 'MESSAGING_CLASS_OTA',
  37. MESSAGING_CLASS_SYSTEM : 'MESSAGING_CLASS_SYSTEM',
  38. MESSAGING_CLASS_STATS : 'MESSAGING_CLASS_STATS',
  39. MESSAGING_CLASS_CFGCMD: 'MESSAGING_CLASS_CFGCMD',
  40. MESSAGING_CLASS_BT: 'MESSAGING_CLASS_BT'
  41. } ;
  42. function rebooting(){
  43. let duration=10000;
  44. console.log(`Simulating a reboot of ${duration}ms`);
  45. data.reboottime = Date.now() + duration;
  46. data.rebooting=true;
  47. setTimeout(() => {
  48. data.rebooting=false;
  49. console.log("Reboot completed!");
  50. }, duration);
  51. }
  52. function sleep(milliseconds) {
  53. const date = Date.now();
  54. let currentDate = null;
  55. do {
  56. currentDate = Date.now();
  57. } while (currentDate - date < milliseconds);
  58. }
  59. function waitForReboot(){
  60. while(Date.now() < data.reboottime){
  61. sleep(500);
  62. console.log(`Waiting for reboot to finish.`);
  63. }
  64. }
  65. function requeueMessages(){
  66. data.messagequeue = [];
  67. data.messagequeue.push(...data.messages);
  68. console.log(`Re-queued ${data.messages.length} messages. Total queue length is: ${data.messagequeue.length}`);
  69. }
  70. function sendMessaging(cmdname,msgtype,msgClass,msg){
  71. let message_txt=`${cmdname}\n${msg}`;
  72. var d = new Date();
  73. var n = d.getMilliseconds();
  74. data.messagequeue.push({
  75. message: message_txt,
  76. type: msgtype,
  77. class: msgClass,
  78. sent_time: n,
  79. current_time: n});
  80. console.log(`Queued message ~${data.messagequeue.length} type ${msgtype}, class ${msgClass}: ${message_txt}`);
  81. }
  82. Array.prototype.filter = function(fun /*, thisp*/) {
  83. var len = this.length >>> 0;
  84. if (typeof fun != "function")
  85. throw new TypeError();
  86. var res = [];
  87. var thisp = arguments[1];
  88. for (var i = 0; i < len; i++) {
  89. if (i in this) {
  90. var val = this[i];
  91. if (fun.call(thisp, val, i, this))
  92. res.push(val);
  93. }
  94. }
  95. return res;
  96. };
  97. for(const cmdIdx in data.commands.commands){
  98. const cmd = data.commands.commands[cmdIdx];
  99. //console.log(`Creating command structure for ${cmd.name}`);
  100. cmdLines[cmd.name] = {
  101. cmd: new Command(),
  102. };
  103. cmdLines[cmd.name].cmd
  104. .storeOptionsAsProperties(true)
  105. .name(cmd.name)
  106. .exitOverride();
  107. for(const argIdx in cmd.argtable){
  108. const arg=cmd.argtable[argIdx];
  109. const optstr=((arg.shortopts?'-'+arg.shortopts:'')+
  110. (arg.shortopts && arg.longopts?', ':'')+
  111. (arg.longopts?'--'+arg.longopts:'') +
  112. (arg.hasvalue?`${(arg.shortopts || arg.longopts?' ':'')}<${arg.datatype.replace(/[<>]/gm,'')}>`:''));
  113. //console.log(` Option: ${optstr}, Glossary: ${arg.glossary}`);
  114. if(arg.remark) continue;
  115. if(arg.mincount>0){
  116. cmdLines[cmd.name].cmd.requiredOption( optstr,arg.glossary);
  117. }
  118. else {
  119. cmdLines[cmd.name].cmd.option( optstr,arg.glossary);
  120. }
  121. }
  122. }
  123. const connectReturnCode = {
  124. UPDATE_CONNECTION_OK : 0,
  125. UPDATE_FAILED_ATTEMPT : 1,
  126. UPDATE_USER_DISCONNECT : 2,
  127. UPDATE_LOST_CONNECTION : 3,
  128. UPDATE_FAILED_ATTEMPT_AND_RESTORE : 4
  129. }
  130. module.exports ={
  131. entry: {
  132. test: './src/test.ts'
  133. },
  134. devServer: {
  135. static: {
  136. directory: path.resolve(__dirname, './dist'),
  137. staticOptions: {},
  138. // Don't be confused with `devMiddleware.publicPath`, it is `publicPath` for static directory
  139. // Can be:
  140. // publicPath: ['/static-public-path-one/', '/static-public-path-two/'],
  141. publicPath: "/",
  142. // Can be:
  143. // serveIndex: {} (options for the `serveIndex` option you can find https://github.com/expressjs/serve-index)
  144. serveIndex: true,
  145. // Can be:
  146. // watch: {} (options for the `watch` option you can find https://github.com/paulmillr/chokidar)
  147. watch: true,
  148. },
  149. devMiddleware: {
  150. publicPath: "/",
  151. },
  152. open: true,
  153. compress: true,
  154. port: PORT,
  155. host: '0.0.0.0',
  156. allowedHosts: "all",
  157. headers: {'Access-Control-Allow-Origin': '*', 'Accept-Encoding': 'identity'},
  158. client: {
  159. logging: "verbose",
  160. // Can be used only for `errors`/`warnings`
  161. //
  162. // overlay: {
  163. // errors: true,
  164. // warnings: true,
  165. // }
  166. overlay: true,
  167. progress: true,
  168. },
  169. onListening: function (devServer) {
  170. if (!devServer) {
  171. throw new Error('webpack-dev-server is not defined');
  172. }
  173. const PORT = devServer.server.address().port;
  174. // get the path to the test page
  175. const compiler = devServer.compiler;
  176. const entry = compiler.options.entry;
  177. const testEntry = entry['test'].import[0];
  178. const testPath = testEntry.replace('./src/', '').replace('.ts', '.html');
  179. // open the test page
  180. import('open').then((open) => open.default(`http://localhost:${PORT}/${testPath}`));
  181. },
  182. onBeforeSetupMiddleware: function (devServer) {
  183. data.devServer=devServer;
  184. devServer.app.use(bodyParser.json()) // for parsing application/json
  185. devServer.app.use(bodyParser.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded
  186. devServer.app.get('/ap.json', function(req, res) { waitForReboot(); res.json( data.ap ); });
  187. devServer.app.get('/scan.json', function(req, res) { waitForReboot(); res.json( data.scan ); });
  188. devServer.app.get('/config.json', function(req, res) {
  189. waitForReboot();
  190. if(data.status.recovery==1 && (data.status.mock_old_recovery??'')!==''){
  191. res.json( data.config.config );
  192. console.log('Mock old recovery - return config structure without gpio');
  193. }
  194. else {
  195. res.json( data.config );
  196. }
  197. });
  198. devServer.app.get('/status.json', function(req, res) {
  199. waitForReboot();
  200. if(data.status_queue_sequence.length>0){
  201. const curstatus = JSON.parse(data.status_queue_sequence_queue_sequence.shift());
  202. data.status.ota_pct=curstatus.ota_pct??0;
  203. data.status.ota_dsc=curstatus.ota_dsc??'';
  204. console.log(`Mock firmware update @${data.status.ota_pct}%, ${data.status.ota_dsc}`)
  205. }
  206. else if (data.status_queue_sequence_post_empty){
  207. data.status_queue_sequence_post_emptyy();
  208. console.log(`Mock old firmware update: simulating a restart`);
  209. data.status_queue_sequence_post_empty = null;
  210. }
  211. else if(data.status.ota_pct!=undefined || data.status.ota_dsc!=undefined) {
  212. if(data.status.ota_pct!=undefined) delete data.status.ota_pct;
  213. if(data.status.ota_dsc!=undefined) delete data.status.ota_dsc;
  214. }
  215. if(data.status.message) delete data.status.message;
  216. if(data.status.recovery==1 && (data.status.mock_old_recovery??'')!==''){
  217. if(data.message_queue_sequence.length>0){
  218. const msgpayload = JSON.parse(data.message_queue_sequence.shift());
  219. data.status.message = msgpayload.message??'';
  220. console.log(`Mocking recovery, setting status message to ${data.status.message}`)
  221. }
  222. else if (data.message_queue_sequence_post_empty){
  223. data.message_queue_sequence_post_empty();
  224. data.message_queue_sequence_post_empty = null;
  225. }
  226. }
  227. res.json( data.status );
  228. });
  229. devServer.app.get('/plugins/SqueezeESP32/firmware/-99', function(req, res) {
  230. waitForReboot();
  231. let has_proxy= data.status.mock_plugin_has_proxy ?? 'n';
  232. const statusCode='xy'.includes((has_proxy).toLowerCase())?200:500;
  233. console.log(`Checking if plugin has proxy enabled with option mock_plugin_has_proxy = ${data.status.mock_plugin_has_proxy}. Returning status ${statusCode} `);
  234. res.status(statusCode ).json();
  235. });
  236. devServer.app.get('/messages.json', function(req, res) {
  237. waitForReboot();
  238. if(data.status.recovery==1 && (data.status.mock_old_recovery??'')!==''){
  239. console.log('Mocking old recovery, with no commands backend' );
  240. res.status(404).end();
  241. return;
  242. }
  243. if(data.message_queue_sequence.length>0){
  244. data.messagequeue.push(data.message_queue_sequence.shift());
  245. }
  246. else if (data.message_queue_sequence_post_empty){
  247. data.message_queue_sequence_post_empty();
  248. data.message_queue_sequence_post_empty = null;
  249. }
  250. res.json( data.messagequeue ) ;
  251. data.messagequeue=[];
  252. });
  253. devServer.app.get('/statusdefinition.json', function(req, res) {
  254. waitForReboot();
  255. res.json( data.statusdefinition );
  256. });
  257. devServer.app.get('/commands.json', function(req, res) {
  258. waitForReboot();
  259. if(data.status.recovery==1 && (data.status.mock_old_recovery??'')!==''){
  260. console.log('Mocking old recovery, with no commands backend' );
  261. res.status(404).end();
  262. }
  263. else {
  264. res.json( data.commands );
  265. }
  266. });
  267. devServer.app.post('/commands.json', function(req, res) {
  268. waitForReboot();
  269. if(data.status.recovery==1 && (data.status.mock_old_recovery??'')!==''){
  270. console.log('Mocking old recovery, with no commands backend' );
  271. res.status(404).end();
  272. return;
  273. }
  274. console.log(req.body.command);
  275. try {
  276. const cmdName=req.body.command.split(" ")[0];
  277. const args=parseArgsStringToArgv(req.body.command,'node ');
  278. let cmd=cmdLines[cmdName].cmd;
  279. if(cmd){
  280. for (const property in cmd.opts()) {
  281. delete cmd[property];
  282. }
  283. cmd.parse(args);
  284. const msg=`Received Options: ${JSON.stringify(cmd.opts())}\n`;
  285. console.log('Options: ', cmd.opts());
  286. console.log('Remaining arguments: ', cmd.args);
  287. sendMessaging(cmdName,messagingTypes.MESSAGING_INFO,messagingClass.MESSAGING_CLASS_CFGCMD,msg);
  288. }
  289. } catch (error) {
  290. console.error(error);
  291. }
  292. res.json( { 'Result' : 'Success' } );
  293. });
  294. devServer.app.post('/config.json', function(req, res) {
  295. waitForReboot();
  296. var fwurl='';
  297. console.log(`Processing config.json with request body: ${req.body}`);
  298. console.log(data.config.config);
  299. for (const property in req.body.config) {
  300. console.log(`${property}: ${req.body.config[property].value}`);
  301. if(property=='fwurl'){
  302. fwurl=req.body.config[property].value;
  303. }
  304. else {
  305. if(data.config.config[property]=== undefined){
  306. console.log(`Added config value ${property} [${req.body.config[property].value}]`);
  307. data.config.config[property] = {value: req.body.config[property].value};
  308. }
  309. else if (data.config.config[property].value!=req.body.config[property].value){
  310. console.log(`Updated config value ${property}\n From: ${data.config.config[property].value}\n To: ${req.body.config[property].value}]`);
  311. data.config.config[property].value=req.body.config[property].value;
  312. }
  313. }
  314. }
  315. res.json( {"result" : "OK" });
  316. if(fwurl!=='' ){
  317. const ota_msg_list= ((data.status.mock_fail_fw_update ?? '')!=='')?data.messages_ota_fail:data.messages_ota;
  318. if(data.status.recovery!=1) {
  319. // we're not yet in recovery. Simulate reboot to recovery
  320. data.status.recovery=1;
  321. if((data.status.mock_old_recovery??'')===''){
  322. // older recovery partitions possibly aren't
  323. // sending messages
  324. requeueMessages();
  325. }
  326. }
  327. var targetQueue='message_queue_sequence';
  328. var targetPostEmpty='message_queue_sequence_post_empty';
  329. if((data.status.mock_old_recovery??'')!==''){
  330. console.log('Mocking old firmware flashing mechanism. Starting!');
  331. targetQueue='status_queue_sequence';
  332. targetPostEmpty='status_queue_sequence_post_empty';
  333. }
  334. console.log(`queuing ${ota_msg_list.length} ota messages `);
  335. data[targetQueue].push(...ota_msg_list);
  336. data[targetPostEmpty] = function(){
  337. data.status.recovery=0;
  338. requeueMessages();
  339. }
  340. }
  341. });
  342. devServer.app.post('/status.json', function(req, res) {
  343. waitForReboot();
  344. for (const property in req.body.status) {
  345. if(data.status[property]=== undefined){
  346. console.log(`Added status value ${property} [${req.body.status[property]}]`);
  347. data.status[property] = {value: req.body.status[property]};
  348. }
  349. else if (data.status[property]!==req.body.status[property]){
  350. console.log(`Updated status value ${property}\nFrom: ${data.status[property]}\nTo: ${req.body.status[property]}`);
  351. data.status[property]=req.body.status[property];
  352. }
  353. }
  354. res.json( {"result" : "OK" } );
  355. });
  356. devServer.app.post('/connect.json', function(req, res) {
  357. waitForReboot();
  358. setTimeout(function(r){
  359. if(r.body.ssid.search('fail')>=0){
  360. if(data.status.ssid){
  361. // in this case, the same ssid will be reused - the ESP32 would restore its previous state on failure
  362. data.status.urc=connectReturnCode.UPDATE_FAILED_ATTEMPT_AND_RESTORE;
  363. }
  364. else {
  365. data.status.urc=connectReturnCode.UPDATE_FAILED_ATTEMPT;
  366. }
  367. }
  368. else {
  369. data.status.ssid=r.body.ssid;
  370. data.status.urc=connectReturnCode.UPDATE_CONNECTION_OK;
  371. }
  372. }, 1000, req);
  373. res.json( {"result" : "OK" } );
  374. });
  375. devServer.app.post('/reboot_ota.json', function(req, res) {
  376. waitForReboot();
  377. data.status.recovery=0;
  378. requeueMessages();
  379. rebooting();
  380. res.json( {"result" : "OK" } );
  381. });
  382. devServer.app.post('/reboot.json', function(req, res) {
  383. waitForReboot();
  384. res.json( {"result" : "OK" } );
  385. rebooting();
  386. requeueMessages();
  387. });
  388. devServer.app.post('/recovery.json', function(req, res) {
  389. waitForReboot();
  390. if((data.status.mock_fail_recovery ?? '')!==''){
  391. res.status(404).end();
  392. }
  393. else {
  394. data.status.recovery=1;
  395. requeueMessages();
  396. rebooting();
  397. res.json( {"result" : "OK" } );
  398. }
  399. });
  400. devServer.app.post('/flash.json', function(req, res) {
  401. waitForReboot();
  402. if(data.status.recovery>0){
  403. if((data.status.mock_fail_fw_update ?? '')!=='' || (data.status.mock_old_recovery??'')!==''){
  404. console.log('Old recovery mock, or fw fail requested' );
  405. res.status(404).end();
  406. }
  407. else {
  408. console.log(`queuing ${data.messages_ota_flash.length} flash ota messages `);
  409. data.message_queue_sequence.push(...data.messages_ota_flash);
  410. data.message_queue_sequence_post_empty = function(){
  411. data.status.recovery=0;
  412. rebooting();
  413. requeueMessages();
  414. }
  415. res.json({"result" : "OK" });
  416. }
  417. }
  418. else {
  419. res.status(404).end();
  420. }
  421. });
  422. devServer.app.delete('/connect.json', function(req, res) {
  423. waitForReboot();
  424. data.status.ssid='';
  425. res.json({"result" : "OK" }); });
  426. devServer.app.get('/reboot', function(req, res) {
  427. waitForReboot();
  428. res.json({"result" : "OK" }); });
  429. },
  430. },
  431. plugins: [
  432. new HtmlWebPackPlugin({
  433. title: 'SqueezeESP32-test',
  434. template: './src/test.ejs',
  435. filename: 'test.html',
  436. minify: false,
  437. inject: 'body',
  438. excludeChunks: ['index','main'],
  439. })
  440. ],
  441. }