fork download
  1. //взял отсюда https://g...content-available-to-author-only...b.com/patrick--/node-omron-fins
  2. const fins = require('omron-fins');
  3. const furnaceConst = require('./checkOmronConst.js');
  4.  
  5. const http = require('http');
  6. const port = 6500;
  7.  
  8.  
  9. function humanize(x){
  10. return (x ? x.toFixed(3).replace(/\.?0*$/,'') : null);
  11. }
  12. const makeDt = function (dt) { //дату в формате "yyyy-MM-dd hh:mm:ss"
  13. let tzoffset = (new Date()).getTimezoneOffset() * 60000; //offset in milliseconds
  14. let localISOTime = (new Date(dt - tzoffset)).toISOString().slice(0, 19).replace('T', ' ');
  15. let mySqlDT = localISOTime;
  16. return mySqlDT;
  17. }
  18.  
  19. const bcd2number = function(bcd) {
  20. let d0 = (bcd & 0xF);
  21. let d1 = (bcd & 0xF0) >> 4;
  22. let d2 = (bcd & 0xF00) >> 8;
  23. let d3 = (bcd & 0xF000) >> 12;
  24. return (d3*1000 + d2*100 + d1*10 + d0);
  25. }
  26.  
  27. const getOmron = function(adr, tags0){
  28. let client = fins.FinsClient(9600, adr);
  29.  
  30. // Setting up our error listener
  31. client.on('error',function(error) {
  32. console.log('Error: ', error);
  33. });
  34.  
  35. //подготовка выходного массива
  36. let tags = tags0.map(t => {return { "tagNum": Number(String(t.tag).slice(2)),
  37. "tag": t.tag, "value":null, "lastTime":null, "name": t.name, "units": t.units, "k": t.k}});
  38.  
  39. //объединение подряд идущих ячеек
  40. let tagsS = []; //сокращенный массив без подряд-идущих значений
  41. for (let pos=tags.length-2, cnt=1; pos>=-1; pos--, cnt++) //с конца в начало
  42. if (pos<0 || tags[pos].tagNum != tags[pos+1].tagNum-1) //pos==-1 чтобы сработало для [0]-элемента
  43. { tagsS.push({"tagNum": tags[pos+1].tagNum, "cnt": cnt, "index": pos+1}); cnt=0;}
  44.  
  45. //в цикле ниже с задержкой делаем запросы
  46. var tm = setTimeout(reqOmron, 0);
  47.  
  48. //вызывается на ответе от ПЛК, ans отсюда идёт ниже в reqOmron
  49. let ans=[];
  50. client.on('reply',function(msg) {
  51. if (msg.values && msg.values.length) //иногда считывается "ничего"(wi-fi плохой)
  52. ans=msg.values.slice(0);
  53.  
  54. clearTimeout(tm);
  55. tm = setTimeout(reqOmron, 0);//сокращаем ожидание ответа
  56. });
  57.  
  58. //надо как-то сделать эту функцию с promise, с учетом ожиданий
  59. let st = 0; pos = 0;
  60. function reqOmron(){
  61. //switch-case последовательного опроса с задержкой?
  62. switch(st){
  63. case 0:
  64. st++;
  65. ans.length=0;
  66. client.read('D' +String(tagsS[pos].tagNum), tagsS[pos].cnt); //запрос
  67. //ждём ответа на запрос, или таймаут 2 секунды (таймаут в ответе сбрасывается).
  68. tm = setTimeout(reqOmron, 2000); //таймаут до 2 секунд
  69. break;
  70. case 1:
  71. //заполняем из массива ответов
  72. for (let i=0; i<ans.length; i++)
  73. tags[tagsS[pos].index + i].value=bcd2number(ans[i]);
  74.  
  75. st++;
  76. if (pos<tagsS.length-1) { //проходим сокращенный массив
  77. pos++;
  78. st=0;
  79. }
  80. tm = setTimeout(reqOmron, 0); //надо немного подождать перед следующей посылкой
  81. break;
  82. default:
  83. let dt = new Date();
  84. console.log (makeDt(dt) +"> "+ (tags.filter(t=> t.value).length)+'/'+tags.length);
  85. //заполняем только успешно считанные ячейки
  86. tags.forEach( function(t){ if (t.value) {t.value *= t.k; t.lastTime = dt;} });
  87.  
  88. tags.forEach( function(t,i){ if (t.value) {furnace4data[i].value = t.value; furnace4data[i].lastTime = t.lastTime;}});
  89. }
  90. }
  91. return tags;
  92. }
  93.  
  94. var furnace4data = furnaceConst.furnace4const.map( function(t){ return {"tag": t.tag, "value":null, "lastTime":null, "name": t.name, "units": t.units, "k": t.k}} );
  95.  
  96. getOmron("192.168.0.69", furnaceConst.furnace4const);
  97. setInterval(function() { getOmron("192.168.0.69", furnaceConst.furnace4const); }, 30000);
  98. //furnace4data - дальше в JSON на http-сервер
  99.  
  100. let server = new http.Server();
  101. server.listen(port, (err) => {
  102. if (err) { return console.log('server Http error!', err); } }
  103. );
  104. server.on('request', function(req, res){
  105. let s = "<!DOCTYPE html><html><head><meta charset='utf-8' /></head><body><table border=1>";
  106. furnace4data.forEach( function(t){ s+="<tr><td>"+makeDt(t.lastTime)+"</td><td>"+t.tag+"</td><td>"+humanize(t.value)+"</td><td>"+t.units+"</td><td>"+t.name+"</td></tr>"; } );
  107. s+="</table></body></html>";
  108. res.end(s);
  109. });
  110.  
  111.  
  112. let serverJSON = new http.Server();
  113. serverJSON.listen(6501, (err) => {
  114. if (err) { return console.log('server JSON error!', err); }
  115. });
  116. serverJSON.on('request', function(req, res){
  117. let t = {"data" : furnace4data.map( (t)=>{return {'tag': t.tag, 'value': humanize(t.value)}})};
  118. res.end( JSON.stringify( t ) );
  119. });
  120.  
Runtime error #stdin #stdout #stderr 0.02s 712192KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
module.js:472
    throw err;
    ^

Error: Cannot find module 'omron-fins'
    at Function.Module._resolveFilename (module.js:470:15)
    at Function.Module._load (module.js:418:25)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/home/KkNkx8/prog.js:2:14)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)