webpack.dev.js 19 KB

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