webpack.dev.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. /* eslint-disable */
  2. var path = require('path');
  3. const merge = require('webpack-merge');
  4. const common = require('./webpack.common.js');
  5. const bodyParser = require('body-parser')
  6. const MiniCssExtractPlugin = require('mini-css-extract-plugin');
  7. const { config } = require('process');
  8. const HtmlWebPackPlugin = require('html-webpack-plugin');
  9. const SpriteLoaderPlugin = require('svg-sprite-loader/plugin');
  10. const { Command } = require('commander');
  11. let cmdLines= { };
  12. var { parseArgsStringToArgv } = require('string-argv');
  13. const data = {
  14. messages: require("../mock/messages.json"),
  15. messagequeue: require("../mock/messages.json"),
  16. message_queue_sequence: [],
  17. status_queue_sequence:[],
  18. message_queue_sequence_post_empty: null,
  19. status_queue_sequence_post_empty: null,
  20. commands: require("../mock/commands.json"),
  21. scan: require("../mock/scan.json"),
  22. ap: require("../mock/ap.json"),
  23. config: require("../mock/config.json"),
  24. statusdefinition: require("../mock/statusdefinition.json"),
  25. status: require("../mock/status.json"),
  26. messages_ota_fail: require("../mock/messages_ota_fail.json"),
  27. messages_ota_flash: require("../mock/messages_ota_flash.json"),
  28. messages_ota: require("../mock/messages_ota.json")
  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 requeueMessages(){
  43. data.messagequeue = [];
  44. data.messagequeue.push(...data.messages);
  45. console.log(`Re-queued ${data.messages.length} messages. Total queue length is: ${data.messagequeue.length}`);
  46. }
  47. function sendMessaging(cmdname,msgtype,msgClass,msg){
  48. let message_txt=`${cmdname}\n${msg}`;
  49. var d = new Date();
  50. var n = d.getMilliseconds();
  51. data.messagequeue.push({
  52. message: message_txt,
  53. type: msgtype,
  54. class: msgClass,
  55. sent_time: n,
  56. current_time: n});
  57. console.log(`Queued message ~${data.messagequeue.length} type ${msgtype}, class ${msgClass}: ${message_txt}`);
  58. }
  59. Array.prototype.filter = function(fun /*, thisp*/) {
  60. var len = this.length >>> 0;
  61. if (typeof fun != "function")
  62. throw new TypeError();
  63. var res = [];
  64. var thisp = arguments[1];
  65. for (var i = 0; i < len; i++) {
  66. if (i in this) {
  67. var val = this[i];
  68. if (fun.call(thisp, val, i, this))
  69. res.push(val);
  70. }
  71. }
  72. return res;
  73. };
  74. for(const cmdIdx in data.commands.commands){
  75. const cmd = data.commands.commands[cmdIdx];
  76. //console.log(`Creating command structure for ${cmd.name}`);
  77. cmdLines[cmd.name] = {
  78. cmd: new Command(),
  79. };
  80. cmdLines[cmd.name].cmd
  81. .storeOptionsAsProperties(true)
  82. .name(cmd.name)
  83. .exitOverride();
  84. for(const argIdx in cmd.argtable){
  85. const arg=cmd.argtable[argIdx];
  86. const optstr=((arg.shortopts?'-'+arg.shortopts:'')+
  87. (arg.shortopts && arg.longopts?', ':'')+
  88. (arg.longopts?'--'+arg.longopts:'') +
  89. (arg.hasvalue?`${(arg.shortopts || arg.longopts?' ':'')}<${arg.datatype.replace(/[<>]/gm,'')}>`:''));
  90. //console.log(` Option: ${optstr}, Glossary: ${arg.glossary}`);
  91. if(arg.mincount>0){
  92. cmdLines[cmd.name].cmd.requiredOption( optstr,arg.glossary);
  93. }
  94. else {
  95. cmdLines[cmd.name].cmd.option( optstr,arg.glossary);
  96. }
  97. }
  98. }
  99. const connectReturnCode = {
  100. UPDATE_CONNECTION_OK : 0,
  101. UPDATE_FAILED_ATTEMPT : 1,
  102. UPDATE_USER_DISCONNECT : 2,
  103. UPDATE_LOST_CONNECTION : 3,
  104. UPDATE_FAILED_ATTEMPT_AND_RESTORE : 4
  105. }
  106. module.exports = merge(common, {
  107. mode: 'development',
  108. devtool: 'inline-source-map',
  109. entry: {
  110. test: './src/test.ts'
  111. },
  112. devServer: {
  113. contentBase: path.join(__dirname, 'dist'),
  114. publicPath: '/',
  115. port: 9100,
  116. host: '127.0.0.1',//your ip address
  117. disableHostCheck: true,
  118. headers: {'Access-Control-Allow-Origin': '*',
  119. 'Accept-Encoding': 'identity'},
  120. overlay: true,
  121. before: function(app) {
  122. app.use(bodyParser.json()) // for parsing application/json
  123. app.use(bodyParser.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded
  124. app.get('/ap.json', function(req, res) { res.json( data.ap ); });
  125. app.get('/scan.json', function(req, res) { res.json( data.scan ); });
  126. app.get('/config.json', function(req, res) {
  127. if(data.status.recovery==1 && (data.status.mock_old_recovery??'')!==''){
  128. res.json( data.config.config );
  129. console.log('Mock old recovery - return config structure without gpio');
  130. }
  131. else {
  132. res.json( data.config );
  133. }
  134. });
  135. app.get('/status.json', function(req, res) {
  136. if(data.status_queue_sequence.length>0){
  137. const curstatus = JSON.parse(data.status_queue_sequence_queue_sequence.shift());
  138. data.status.ota_pct=curstatus.ota_pct??0;
  139. data.status.ota_dsc=curstatus.ota_dsc??'';
  140. console.log(`Mock firmware update @${data.status.ota_pct}%, ${data.status.ota_dsc}`)
  141. }
  142. else if (data.status_queue_sequence_post_empty){
  143. data.status_queue_sequence_post_emptyy();
  144. console.log(`Mock old firmware update: simulating a restart`);
  145. data.status_queue_sequence_post_empty = null;
  146. }
  147. else if(data.status.ota_pct!=undefined || data.status.ota_dsc!=undefined) {
  148. if(data.status.ota_pct!=undefined) delete data.status.ota_pct;
  149. if(data.status.ota_dsc!=undefined) delete data.status.ota_dsc;
  150. }
  151. if(data.status.message) delete data.status.message;
  152. if(data.status.recovery==1 && (data.status.mock_old_recovery??'')!==''){
  153. if(data.message_queue_sequence.length>0){
  154. const msgpayload = JSON.parse(data.message_queue_sequence.shift());
  155. data.status.message = msgpayload.message??'';
  156. console.log(`Mocking recovery, setting status message to ${data.status.message}`)
  157. }
  158. else if (data.message_queue_sequence_post_empty){
  159. data.message_queue_sequence_post_empty();
  160. data.message_queue_sequence_post_empty = null;
  161. }
  162. }
  163. res.json( data.status );
  164. });
  165. app.get('/plugins/SqueezeESP32/firmware/-99', function(req, res) {
  166. let has_proxy= data.status.mock_plugin_has_proxy ?? 'n';
  167. const statusCode='xy'.includes((has_proxy).toLowerCase())?200:500;
  168. console.log(`Checking if plugin has proxy enabled with option mock_plugin_has_proxy = ${data.status.mock_plugin_has_proxy}. Returning status ${statusCode} `);
  169. res.status(statusCode ).json();
  170. });
  171. app.get('/messages.json', function(req, res) {
  172. if(data.status.recovery==1 && (data.status.mock_old_recovery??'')!==''){
  173. console.log('Mocking old recovery, with no commands backend' );
  174. res.status(404).end();
  175. return;
  176. }
  177. if(data.message_queue_sequence.length>0){
  178. data.messagequeue.push(data.message_queue_sequence.shift());
  179. }
  180. else if (data.message_queue_sequence_post_empty){
  181. data.message_queue_sequence_post_empty();
  182. data.message_queue_sequence_post_empty = null;
  183. }
  184. res.json( data.messagequeue ) ;
  185. data.messagequeue=[];
  186. });
  187. app.get('/statusdefinition.json', function(req, res) { res.json( data.statusdefinition ); });
  188. app.get('/commands.json', function(req, res) {
  189. if(data.status.recovery==1 && (data.status.mock_old_recovery??'')!==''){
  190. console.log('Mocking old recovery, with no commands backend' );
  191. res.status(404).end();
  192. }
  193. else {
  194. res.json( data.commands );
  195. }
  196. });
  197. app.post('/commands.json', function(req, res) {
  198. if(data.status.recovery==1 && (data.status.mock_old_recovery??'')!==''){
  199. console.log('Mocking old recovery, with no commands backend' );
  200. res.status(404).end();
  201. return;
  202. }
  203. console.log(req.body.command);
  204. try {
  205. const cmdName=req.body.command.split(" ")[0];
  206. const args=parseArgsStringToArgv(req.body.command,'node ');
  207. let cmd=cmdLines[cmdName].cmd;
  208. if(cmd){
  209. for (const property in cmd.opts()) {
  210. delete cmd[property];
  211. }
  212. cmd.parse(args);
  213. const msg=`Received Options: ${JSON.stringify(cmd.opts())}\n`;
  214. console.log('Options: ', cmd.opts());
  215. console.log('Remaining arguments: ', cmd.args);
  216. sendMessaging(cmdName,messagingTypes.MESSAGING_INFO,messagingClass.MESSAGING_CLASS_CFGCMD,msg);
  217. }
  218. } catch (error) {
  219. console.error(error);
  220. }
  221. res.json( { 'Result' : 'Success' } );
  222. });
  223. app.post('/config.json', function(req, res) {
  224. var fwurl='';
  225. console.log(`Processing config.json with request body: ${req.body}`);
  226. console.log(data.config);
  227. for (const property in req.body.config) {
  228. console.log(`${property}: ${req.body.config[property].value}`);
  229. if(property=='fwurl'){
  230. fwurl=req.body.config[property].value;
  231. }
  232. else {
  233. if(data.config[property]=== undefined){
  234. console.log(`Added config value ${property} [${req.body.config[property].value}]`);
  235. data.config[property] = {value: req.body.config[property].value};
  236. }
  237. else if (data.config[property].value!=req.body.config[property].value){
  238. console.log(`Updated config value ${property}\nFrom: ${data.config[property].value}\nTo: ${req.body.config[property].value}]`);
  239. data.config[property].value=req.body.config[property].value;
  240. }
  241. }
  242. }
  243. res.json( {} );
  244. if(fwurl!=='' ){
  245. const ota_msg_list= ((data.status.mock_fail_fw_update ?? '')!=='')?data.messages_ota_fail:data.messages_ota;
  246. if(data.status.recovery!=1) {
  247. // we're not yet in recovery. Simulate reboot to recovery
  248. data.status.recovery=1;
  249. if((data.status.mock_old_recovery??'')===''){
  250. // older recovery partitions possibly aren't
  251. // sending messages
  252. requeueMessages();
  253. }
  254. }
  255. var targetQueue='message_queue_sequence';
  256. var targetPostEmpty='message_queue_sequence_post_empty';
  257. if((data.status.mock_old_recovery??'')!==''){
  258. console.log('Mocking old firmware flashing mechanism. Starting!');
  259. targetQueue='status_queue_sequence';
  260. targetPostEmpty='status_queue_sequence_post_empty';
  261. }
  262. console.log(`queuing ${ota_msg_list.length} ota messages `);
  263. data[targetQueue].push(...ota_msg_list);
  264. data[targetPostEmpty] = function(){
  265. data.status.recovery=0;
  266. requeueMessages();
  267. }
  268. }
  269. });
  270. app.post('/status.json', function(req, res) {
  271. for (const property in req.body.status) {
  272. if(data.status[property]=== undefined){
  273. console.log(`Added status value ${property} [${req.body.status[property]}]`);
  274. data.status[property] = {value: req.body.status[property]};
  275. }
  276. else if (data.status[property]!==req.body.status[property]){
  277. console.log(`Updated status value ${property}\nFrom: ${data.status[property]}\nTo: ${req.body.status[property]}`);
  278. data.status[property]=req.body.status[property];
  279. }
  280. }
  281. res.json( {} );
  282. });
  283. app.post('/connect.json', function(req, res) {
  284. setTimeout(function(r){
  285. if(r.body.ssid.search('fail')>=0){
  286. if(data.status.ssid){
  287. // in this case, the same ssid will be reused - the ESP32 would restore its previous state on failure
  288. data.status.urc=connectReturnCode.UPDATE_FAILED_ATTEMPT_AND_RESTORE;
  289. }
  290. else {
  291. data.status.urc=connectReturnCode.UPDATE_FAILED_ATTEMPT;
  292. }
  293. }
  294. else {
  295. data.status.ssid=r.body.ssid;
  296. data.status.urc=connectReturnCode.UPDATE_CONNECTION_OK;
  297. }
  298. }, 1000, req);
  299. res.json( {} );
  300. });
  301. app.post('/reboot_ota.json', function(req, res) {
  302. data.status.recovery=0;
  303. requeueMessages();
  304. res.json( {} );
  305. });
  306. app.post('/reboot.json', function(req, res) {
  307. res.json( {} );
  308. requeueMessages();
  309. });
  310. app.post('/recovery.json', function(req, res) {
  311. if((data.status.mock_fail_recovery ?? '')!==''){
  312. res.status(404).end();
  313. }
  314. else {
  315. data.status.recovery=1;
  316. requeueMessages();
  317. res.json( { } );
  318. }
  319. });
  320. app.post('/flash.json', function(req, res) {
  321. if(data.status.recovery>0){
  322. if((data.status.mock_fail_fw_update ?? '')!=='' || (data.status.mock_old_recovery??'')!==''){
  323. console.log('Old recovery mock, or fw fail requested' );
  324. res.status(404).end();
  325. }
  326. else {
  327. console.log(`queuing ${data.messages_ota_flash.length} flash ota messages `);
  328. data.message_queue_sequence.push(...data.messages_ota_flash);
  329. data.message_queue_sequence_post_empty = function(){
  330. data.status.recovery=0;
  331. requeueMessages();
  332. }
  333. res.json({});
  334. }
  335. }
  336. else {
  337. res.status(404).end();
  338. }
  339. });
  340. app.delete('/connect.json', function(req, res) {
  341. data.status.ssid='';
  342. res.json( {} ); });
  343. app.get('/reboot', function(req, res) { res.json( {} ); });
  344. },
  345. },
  346. plugins: [
  347. new MiniCssExtractPlugin({
  348. filename: 'css/[name].css',
  349. chunkFilename: 'css/[id].css' ,
  350. }),
  351. new HtmlWebPackPlugin({
  352. title: 'SqueezeESP32-test',
  353. template: './src/test.ejs',
  354. filename: 'test',
  355. minify: false,
  356. excludeChunks: ['index'],
  357. })
  358. ],
  359. });