Navigation

    Logo
    • Register
    • Login
    • Search
    • Recent
    • Tags
    • Unread
    • Categories
    • Unreplied
    • Popular
    • GitHub
    • Docu
    • Hilfe
    1. Home
    2. Русский
    3. ioBroker
    4. Скрипты
    5. ioBroker скрипты
    6. Вопросы по написанию скриптов

    NEWS

    • 15. 05. Wartungsarbeiten am ioBroker Forum

    • Monatsrückblick - April 2025

    • Minor js-controller 7.0.7 Update in latest repo

    Вопросы по написанию скриптов

    This topic has been deleted. Only users with topic management privileges can see it.
    • Bluefox
      Bluefox last edited by

      @spectrekr:

      В скрипте подключаю модуль и создаю переменную:

      var mysql = require('mysql');
      
      var connection = mysql.createConnection({
          host:     'localhost',
          user:     'login',
          password: 'pass',
          database: 'bd',
          socketPath: '/var/run/mysqld/mysqld.sock'
      });
      
      

      Потом подписываюсь на некую переменную.

      on({id: 'javascript.0.sms.id', change: 'any'}, function (obj) {
      	count = obj.newState.val - obj.oldState.val;
      	log("чего-то");
      }
      
      

      Как передать переменную connection в подписку? `
      Обе части кода просто должны быть в одном скрипте. Тогда connection видна везде:

      var mysql = require('mysql');
      
      var connection = mysql.createConnection({
          host:     'localhost',
          user:     'login',
          password: 'pass',
          database: 'bd',
          socketPath: '/var/run/mysqld/mysqld.sock'
      });
      
      on({id: 'javascript.0.sms.id', change: 'any'}, function (obj) {
      	count = obj.newState.val - obj.oldState.val;
      	log("чего-то");
      	connection.query('INSERT table...');
      });
      
      1 Reply Last reply Reply Quote 0
      • S
        spectrekr last edited by

        Так и написано

        ! connection.query('SELECT max(id) AS id FROM inbox', function(err, res_id, fields) { if (err) throw err; setState('sms.id', res_id[0].id); log(getState('sms.id').val); }); ! on({id: 'javascript.0.sms.id', change: 'any'}, function (obj) { if (obj.oldState.val < obj.newState.val){ count = obj.newState.val - obj.oldState.val; } log(count); if (count > 1){ connection.query('SELECT UDH FROM inbox WHERE ID = ?', [getState('sms.id').val], function(err, res_udh, fields) { if (err) throw err; log(res_udh[0].UDH); if(res_udh[0].UDH !== ''){ setState('sms.udh', res_udh[0].UDH.substring(0, res[0].UDH.length - 1)); log(getState('sms.udh').val); } }); } }); !
        Первый запрос выполняется и внем все прекрасно получает, потом производит подписку и внутри уже выдает ошибку.

        ! Error: Cannot enqueue Query after invoking quit. at Protocol._validateEnqueue (/opt/iobroker/node_modules/iobroker.javascript/node_modules/mysql/lib/protocol/Protocol.js:202:16) at Protocol._enqueue (/opt/iobroker/node_modules/iobroker.javascript/node_modules/mysql/lib/protocol/Protocol.js:135:13) at Connection.query (/opt/iobroker/node_modules/iobroker.javascript/node_modules/mysql/lib/Connection.js:201:25) at Object. (script.js.SMS:41:20) at Object.subs.callback (/opt/iobroker/node_modules/iobroker.javascript/javascript.js:1206:48) at /opt/iobroker/node_modules/iobroker.javascript/javascript.js:541:48 at getObjectEnums (/opt/iobroker/node_modules/iobroker.javascript/javascript.js:2430:17) at checkPatterns (/opt/iobroker/node_modules/iobroker.javascript/javascript.js:537:17) at Object.utils.adapter.stateChange (/opt/iobroker/node_modules/iobroker.javascript/javascript.js:215:17) at Object.that.states.States.change (/opt/iobroker/node_modules/iobroker.js-controller/lib/adapter.js:1969:80) at Socket.StatesInMemClient.client.on.connectionTimeout (/opt/iobroker/node_modules/iobroker.js-controller/lib/states/statesInMemClient.js:45:30) at Socket.Emitter.emit (/opt/iobroker/node_modules/iobroker.js-controller/node_modules/socket.io-client/node_modules/component-emitter/index.js:131:20) at Socket.onevent (/opt/iobroker/node_modules/iobroker.js-controller/node_modules/socket.io-client/lib/socket.js:263:10) at Socket.onpacket (/opt/iobroker/node_modules/iobroker.js-controller/node_modules/socket.io-client/lib/socket.js:221:12) at Manager. (/opt/iobroker/node_modules/iobroker.js-controller/node_modules/socket.io-client/node_modules/component-bind/index.js:21:15) at Manager.Emitter.emit (/opt/iobroker/node_modules/iobroker.js-controller/node_modules/socket.io-client/node_modules/component-emitter/index.js:131:20) at Manager.ondecoded (/opt/iobroker/node_modules/iobroker.js-controller/node_modules/socket.io-client/lib/manager.js:333:8) at Decoder. (/opt/iobroker/node_modules/iobroker.js-controller/node_modules/socket.io-client/node_modules/component-bind/index.js:21:15) at Decoder.Emitter.emit (/opt/iobroker/node_modules/iobroker.js-controller/node_modules/socket.io-client/node_modules/socket.io-parser/node_modules/component-emitter/index.js:134:20) at Decoder.add (/opt/iobroker/node_modules/iobroker.js-controller/node_modules/socket.io-client/node_modules/socket.io-parser/index.js:247:12) at Manager.ondata (/opt/iobroker/node_modules/iobroker.js-controller/node_modules/socket.io-client/lib/manager.js:323:16) at Socket. (/opt/iobroker/node_modules/iobroker.js-controller/node_modules/socket.io-client/node_modules/component-bind/index.js:21:15) at Socket.Emitter.emit (/opt/iobroker/node_modules/iobroker.js-controller/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/component-emitter/index.js:134:20) at Socket.onPacket (/opt/iobroker/node_modules/iobroker.js-controller/node_modules/socket.io-client/node_modules/engine.io-client/lib/socket.js:441:14) at WS. (/opt/iobroker/node_modules/iobroker.js-controller/node_modules/socket.io-client/node_modules/engine.io-client/lib/socket.js:258:10) at WS.Emitter.emit (/opt/iobroker/node_modules/iobroker.js-controller/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/component-emitter/index.js:134:20) at WS.Transport.onPacket (/opt/iobroker/node_modules/iobroker.js-controller/node_modules/socket.io-client/node_modules/engine.io-client/lib/transport.js:143:8) at WS.Transport.onData (/opt/iobroker/node_modules/iobroker.js-controller/node_modules/socket.io-client/node_modules/engine.io-client/lib/transport.js:135:8) at WebSocket.ws.onmessage (/opt/iobroker/node_modules/iobroker.js-controller/node_modules/socket.io-client/node_modules/engine.io-client/lib/transports/websocket.js:132:10) at WebSocket.onMessage (/opt/iobroker/node_modules/iobroker.js-controller/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/ws/lib/WebSocket.js:418:14) at WebSocket.emit (events.js:98:17) at Receiver.ontext (/opt/iobroker/node_modules/iobroker.js-controller/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/ws/lib/WebSocket.js:816:10) at /opt/iobroker/node_modules/iobroker.js-controller/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/ws/lib/Receiver.js:477:18 at Receiver.applyExtensions (/opt/iobroker/node_modules/iobroker.js-controller/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/ws/lib/Receiver.js:364:5) at /opt/iobroker/node_modules/iobroker.js-controller/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/ws/lib/Receiver.js:466:14 at Receiver.flush (/opt/iobroker/node_modules/iobroker.js-controller/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/ws/lib/Receiver.js:340:3) at Receiver.opcodes.1.finish (/opt/iobroker/node_modules/iobroker.js-controller/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/ws/lib/Receiver.js:482:12) at Receiver. (/opt/iobroker/node_modules/iobroker.js-controller/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/ws/lib/Receiver.js:457:31) at Receiver.add (/opt/iobroker/node_modules/iobroker.js-controller/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/ws/lib/Receiver.js:95:24) at Socket.realHandler (/opt/iobroker/node_modules/iobroker.js-controller/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/ws/lib/WebSocket.js:800:20) at Socket.emit (events.js:95:17) at Socket. (stream_readable.js:765:14) at Socket.emit (events.js:92:17) at emitReadable (_stream_readable.js:427:10) at emitReadable (_stream_readable.js:423:5) at readableAddChunk (_stream_readable.js:166:9) at Socket.Readable.push (_stream_readable.js:128:10) at TCP.onread (net.js:529:21)
        На драйвер пока знаний не хватает, пытаюсь написать скрипт, а потом уже буду пытаться преобразовать все в драйвер.

        UPD: Разобрался, он закрывал соединение не зависимо от подписки.

        1 Reply Last reply Reply Quote 0
        • I
          instalator last edited by

          есть переменная

          var menu = [
              [
                  ['Заказываем как обычно?', 'да', 'нет', [0,0,2]],
                  ['На какой день?', 'сегодня', 'завтра'],
                  ['На какое время?', 'утро', 'обед', 'вечер'],
                  ['Я делаю заказ'],
          
              ],
              [
                  ['На какой день?', 'сегодня', 'завтра'],
                  ['На какое время?', 'утро', 'обед', 'вечер'],
                  ['Какое количество?'],
              ]
          ];
          
          

          Пытаюсь узнать длину массива menu[0][0]

          log('menu[0][0].length' + menu[0][0].length);
          

          Выдает 14, целый час бился. Перезапускал даже IoB.

          Но после того как узнал длину следующего элемента, все встало на свои места

          ! ````
          23:25:39.178 [info] javascript.0 Start javascript script.js.МЕНЮ
          23:25:39.185 [info] javascript.0 script.js.МЕНЮ: menu[0][0].length-14
          23:25:39.185 [info] javascript.0 script.js.МЕНЮ: registered 1 subscription and 0 schedules
          23:25:58.064 [info] javascript.0 Stop script script.js.МЕНЮ
          23:25:58.243 [info] javascript.0 Start javascript script.js.МЕНЮ
          23:25:58.250 [info] javascript.0 script.js.МЕНЮ: menu[1][0].length3
          23:25:58.250 [info] javascript.0 script.js.МЕНЮ: registered 1 subscription and 0 schedules
          23:26:14.320 [info] javascript.0 Stop script script.js.МЕНЮ
          23:26:14.512 [info] javascript.0 Start javascript script.js.МЕНЮ
          23:26:14.525 [info] javascript.0 script.js.МЕНЮ: menu[0][1].length3
          23:26:14.525 [info] javascript.0 script.js.МЕНЮ: registered 1 subscription and 0 schedules
          23:26:24.575 [info] javascript.0 Stop script script.js.МЕНЮ
          23:26:24.828 [info] javascript.0 Start javascript script.js.МЕНЮ
          23:26:24.835 [info] javascript.0 script.js.МЕНЮ: menu[0][0].length4
          23:26:24.835 [info] javascript.0 script.js.МЕНЮ: registered 1 subscription and 0 schedules

          Это из-за чего такие глюки происходят в js?
          
          Добавлено.
          
          В скрипте так и продолжает выдавать 14.
          
          есть еще массив с одним элементом выдает длину 23:34:38.188 [info] javascript.0 script.js.МЕНЮ: result.length-11
          1 Reply Last reply Reply Quote 0
          • H
            Haus last edited by

            Всем привет, нужна помощь это кусочек скрипта работает нормально, где то на третьем вычислении circ_temp_water + temp_corr получаю Дом: Повышаем расчетную температуру подачи на 0.1: 32.300000000000004 должно быть "32.3"

            function startt() {
                 var room   = 'Heat_control';
                 var ctwid  = getIdByName(room + '.circ_temp_water');
                 var circ_temp_water = getState(ctwid).val;
                 var temp_corr;
            
                 if ( circ_temp_water_real < circ_temp_water - 1 )
                 log(circ_title + ': Фактическая температура подачи значительно отличается от расчетной. Ждем, когда t достигнет нормы.');
                 else if ( temp_trend == '+' )
                 log(circ_title + ': Температура в помещении повышается (' + past_temp + ' -> ' + cur_temp + '). Наблюдаем');
                 else
                 {
                       temp_corr = 0.1;
                       circ_temp_water = circ_temp_water + temp_corr;
                       setState(ctwid, circ_temp_water);
                       log(circ_title + ': Повышаем расчетную температуру подачи на ' + temp_corr + ': ' + circ_temp_water);
                 }
            }
            setInterval(function() {
                startt();
            },30000);
            
            
            1 Reply Last reply Reply Quote 0
            • Bluefox
              Bluefox last edited by

              @Haus:

              Всем привет, нужна помощь это кусочек скрипта работает нормально, где то на третьем вычислении circ_temp_water + temp_corr получаю Дом: Повышаем расчетную температуру подачи на 0.1: 32.300000000000004 должно быть "32.3"

              function startt() {
                   var room   = 'Heat_control';
                   var ctwid  = getIdByName(room + '.circ_temp_water');
                   var circ_temp_water = getState(ctwid).val;
                   var temp_corr;
                   
                   if ( circ_temp_water_real < circ_temp_water - 1 )
                   log(circ_title + ': Фактическая температура подачи значительно отличается от расчетной. Ждем, когда t достигнет нормы.');
                   else if ( temp_trend == '+' )
                   log(circ_title + ': Температура в помещении повышается (' + past_temp + ' -> ' + cur_temp + '). Наблюдаем');
                   else
                   {
                         temp_corr = 0.1;
                         circ_temp_water = circ_temp_water + temp_corr;
                         setState(ctwid, circ_temp_water);
                         log(circ_title + ': Повышаем расчетную температуру подачи на ' + temp_corr + ': ' + circ_temp_water);
                   }
              }
              setInterval(function() {
                  startt();
              },30000);
               
              ```` `  
              
              circ_temp_water = Math.round((circ_temp_water + temp_corr) * 10)) / 10;
              
              1 Reply Last reply Reply Quote 0
              • H
                Haus last edited by

                Как сделать выполнение скрипта через пять минут после его завершения. В этом варианте circ_flap_duration2 одна или две секунды , но есть в скрипте и 35; 140 секунд. То Есть чтобы код подождал пока выполнится setTimeout действие.

                function startt() {
                        {
                                if ( circ_temp_water_real > circ_temp_water + 3 )
                	        circ_flap_duration = circ_mix_step * 2;
                	        else
                	        circ_flap_duration = circ_mix_step;
                                circ_flap_duration2 = circ_flap_duration * 1000;
                	        setState(cmuid, 0);
                	        setState(cmdid, 1);
                	        setTimeout(function () {setState(cmdid, 0);}, circ_flap_duration2);
                	        circ_flap = circ_flap - circ_flap_duration;
                                setState(cfid, circ_flap);
                        }
                 }
                setInterval(function() {
                    startt();
                },300000);               
                
                
                1 Reply Last reply Reply Quote 0
                • Bluefox
                  Bluefox last edited by

                  @Haus:

                  Как сделать выполнение скрипта через пять минут после его завершения. В этом варианте circ_flap_duration2 одна или две секунды , но есть в скрипте и 35; 140 секунд. То Есть чтобы код подождал пока выполнится setTimeout действие.

                  function startt() {
                          {
                                  if ( circ_temp_water_real > circ_temp_water + 3 )
                  	        circ_flap_duration = circ_mix_step * 2;
                  	        else
                  	        circ_flap_duration = circ_mix_step;
                                  circ_flap_duration2 = circ_flap_duration * 1000;
                  	        setState(cmuid, 0);
                  	        setState(cmdid, 1);
                  	        setTimeout(function () {setState(cmdid, 0);}, circ_flap_duration2);
                  	        circ_flap = circ_flap - circ_flap_duration;
                                  setState(cfid, circ_flap);
                          }
                   }
                  setInterval(function() {
                      startt();
                  },300000);               
                  
                  ```` `  
                  

                  Код не может подождать. Надо снова вызывать setTimeout. В каком месте надо подождать?

                  function startt(cb) {
                          {
                                  if ( circ_temp_water_real > circ_temp_water + 3 )
                  	        circ_flap_duration = circ_mix_step * 2;
                  	        else
                  	        circ_flap_duration = circ_mix_step;
                                  circ_flap_duration2 = circ_flap_duration * 1000;
                  	        setState(cmuid, 0);
                  	        setState(cmdid, 1);
                  	        setTimeout(function () {setState(cmdid, 0); cb && cb();}, circ_flap_duration2);
                  	        circ_flap = circ_flap - circ_flap_duration;
                                  setState(cfid, circ_flap);
                  
                          }
                   }
                  setInterval(function() {
                      startt(function () {
                          log('едем дальше');
                       });
                  },300000);               
                  
                  
                  1 Reply Last reply Reply Quote 0
                  • H
                    Haus last edited by

                    @Bluefox:

                    @Haus:

                    Как сделать выполнение скрипта через пять минут после его завершения. В этом варианте circ_flap_duration2 одна или две секунды , но есть в скрипте и 35; 140 секунд. То Есть чтобы код подождал пока выполнится setTimeout действие.

                    function startt() {
                            {
                                    if ( circ_temp_water_real > circ_temp_water + 3 )
                    	        circ_flap_duration = circ_mix_step * 2;
                    	        else
                    	        circ_flap_duration = circ_mix_step;
                                    circ_flap_duration2 = circ_flap_duration * 1000;
                    	        setState(cmuid, 0);
                    	        setState(cmdid, 1);
                    	        setTimeout(function () {setState(cmdid, 0);}, circ_flap_duration2);
                    	        circ_flap = circ_flap - circ_flap_duration;
                                    setState(cfid, circ_flap);
                            }
                     }
                    setInterval(function() {
                        startt();
                    },300000);               
                    
                    ```` `  
                    

                    Код не может подождать. Надо снова вызывать setTimeout. В каком месте надо подождать?

                    function startt(cb) {
                            {
                                    if ( circ_temp_water_real > circ_temp_water + 3 )
                    	        circ_flap_duration = circ_mix_step * 2;
                    	        else
                    	        circ_flap_duration = circ_mix_step;
                                    circ_flap_duration2 = circ_flap_duration * 1000;
                    	        setState(cmuid, 0);
                    	        setState(cmdid, 1);
                    	        setTimeout(function () {setState(cmdid, 0); cb && cb();}, circ_flap_duration2);
                    	        circ_flap = circ_flap - circ_flap_duration;
                                    setState(cfid, circ_flap);
                                    
                            }
                     }
                    setInterval(function() {
                        startt(function () {
                            log('едем дальше');
                         });
                    },300000);               
                    
                    ```` `  
                    

                    setState(cmdid, 1);

                    setTimeout(function () {setState(cmdid, 0); cb && cb();}, 140000);

                    }

                    чтобы код идущий дальше выполнялся по завершению этого действия, просто дальше по коду есть условия if (circ_flap < 10) сделай то и то …

                    В PHP из которого я переделал это выглядит так

                    key_sw($circ_mix_up, 0);
                    key_sw($circ_mix_down, 1);
                    sleep(120);
                    key_sw($circ_mix_down, 0);
                    
                    

                    и по логу видно как время смищается

                    1 Reply Last reply Reply Quote 0
                    • Bluefox
                      Bluefox last edited by

                      @Haus:

                      @Bluefox:

                      @Haus:

                      Как сделать выполнение скрипта через пять минут после его завершения. В этом варианте circ_flap_duration2 одна или две секунды , но есть в скрипте и 35; 140 секунд. То Есть чтобы код подождал пока выполнится setTimeout действие.

                      function startt() {
                              {
                                      if ( circ_temp_water_real > circ_temp_water + 3 )
                      	        circ_flap_duration = circ_mix_step * 2;
                      	        else
                      	        circ_flap_duration = circ_mix_step;
                                      circ_flap_duration2 = circ_flap_duration * 1000;
                      	        setState(cmuid, 0);
                      	        setState(cmdid, 1);
                      	        setTimeout(function () {setState(cmdid, 0);}, circ_flap_duration2);
                      	        circ_flap = circ_flap - circ_flap_duration;
                                      setState(cfid, circ_flap);
                              }
                       }
                      setInterval(function() {
                          startt();
                      },300000);               
                      
                      ```` `  
                      

                      Код не может подождать. Надо снова вызывать setTimeout. В каком месте надо подождать?

                      function startt(cb) {
                              {
                                      if ( circ_temp_water_real > circ_temp_water + 3 )
                      	        circ_flap_duration = circ_mix_step * 2;
                      	        else
                      	        circ_flap_duration = circ_mix_step;
                                      circ_flap_duration2 = circ_flap_duration * 1000;
                      	        setState(cmuid, 0);
                      	        setState(cmdid, 1);
                      	        setTimeout(function () {setState(cmdid, 0); cb && cb();}, circ_flap_duration2);
                      	        circ_flap = circ_flap - circ_flap_duration;
                                      setState(cfid, circ_flap);
                                      
                              }
                       }
                      setInterval(function() {
                          startt(function () {
                              log('едем дальше');
                           });
                      },300000);               
                      
                      ```` `  
                      

                      setState(cmdid, 1);

                      setTimeout(function () {setState(cmdid, 0); cb && cb();}, 140000);

                      }

                      чтобы код идущий дальше выполнялся по завершению этого действия, просто дальше по коду есть условия if (circ_flap < 10) сделай то и то …

                      В PHP из которого я переделал это выглядит так

                      key_sw($circ_mix_up, 0);
                      key_sw($circ_mix_down, 1);
                      sleep(120);
                      key_sw($circ_mix_down, 0);
                      
                      

                      и по логу видно как время смищается `
                      Я же показал код. Посмотри там где написано 'едем дальше'

                      А твой PHP вот так бы выглядел в JS:

                      key_sw($circ_mix_up, 0);
                      key_sw($circ_mix_down, 1);
                      setTimeout(function () {
                            key_sw($circ_mix_down, 0);
                      }, 120);
                      
                      1 Reply Last reply Reply Quote 0
                      • I
                        instalator last edited by

                        А по моей проблемам какие идеи?

                        1 Reply Last reply Reply Quote 0
                        • S
                          spectrekr last edited by

                          А как можно вывести все поля объекта? Когда подписываюсь на изменения объекта, например чтоб не только по полю val проверять, а например, и по времени изменения?

                          1 Reply Last reply Reply Quote 0
                          • I
                            instalator last edited by

                            @spectrekr:

                            А как можно вывести все поля объекта? Когда подписываюсь на изменения объекта, например чтоб не только по полю val проверять, а например, и по времени изменения? `
                            Вместо val напиши ts. Описание на дравйвер смотри на гите

                            1 Reply Last reply Reply Quote 0
                            • S
                              spectrekr last edited by

                              В чем ошибка?

                              on({id: 'javascript.0.sms.in.time', change: 'any'}, function (obj) {
                                  log(obj.oldState.ts);
                                  log(getObject('javascript.0.sms.in.time').oldState.ts);
                              });
                              

                              Вроде бы должно в обоих случаях вывести одинаковое число, а по факту первый лог выводит, а второй дает ошибку что ts не существует.

                              1 Reply Last reply Reply Quote 0
                              • I
                                instalator last edited by

                                @spectrekr:

                                В чем ошибка?

                                on({id: 'javascript.0.sms.in.time', change: 'any'}, function (obj) {
                                    log(obj.oldState.ts);
                                    log(getObject('javascript.0.sms.in.time').oldState.ts);
                                });
                                

                                Вроде бы должно в обоих случаях вывести одинаковое число, а по факту первый лог выводит, а второй дает ошибку что ts не существует. `
                                getState (id)

                                Returns state of id in form {val: value, ack: true/false, ts: timestamp, lc: lastchanged, from: origin}

                                Отсюда следует что колбек getState возвращает только текущее состояние. А вот on возвращает много чего.

                                1 Reply Last reply Reply Quote 0
                                • I
                                  instalator last edited by

                                  Имеем массив с данными

                                  data-product="{"id":2104,"price":250,"discountPrice":240,"isBottle":true,"type":"product","count":1}",

                                  data-product="{"id":1204,"price":190,"discountPrice":180,"isBottle":true,"type":"product","count":1}",

                                  data-product="{"id":1041,"price":170,"discountPrice":160,"isBottle":true,"type":"product","count":1}",

                                  data-product="{"id":3,"price":160,"discountPrice":150,"isBottle":true,"type":"product","count":1}",

                                  data-product="{"id":1203,"price":120,"discountPrice":120,"isBottle":true,"type":"product","count":1}"

                                  log(JSON.parse(itm)) выдает данные как строку а не как объект, это особенность JSON.parse для массивов?

                                  `m.forEach(function(itm, i, arr) {
                                                      result[i] = JSON.stringify((itm.replace('data-product="', '').replace(/"/g, '"').slice(0, -1)));
                                  
                                                      if (i >= arr.length - 1){
                                                          result.forEach(function(itm, i, arr) {
                                                          log(JSON.parse(itm));    
                                  
                                                          });
                                                      }
                                                  });` [/i]
                                  
                                  1 Reply Last reply Reply Quote 0
                                  • Bluefox
                                    Bluefox last edited by

                                    @instalator:

                                    Имеем массив с данными

                                    data-product="{"id":2104,"price":250,"discountPrice":240,"isBottle":true,"type":"product","count":1}",

                                    data-product="{"id":1204,"price":190,"discountPrice":180,"isBottle":true,"type":"product","count":1}",

                                    data-product="{"id":1041,"price":170,"discountPrice":160,"isBottle":true,"type":"product","count":1}",

                                    data-product="{"id":3,"price":160,"discountPrice":150,"isBottle":true,"type":"product","count":1}",

                                    data-product="{"id":1203,"price":120,"discountPrice":120,"isBottle":true,"type":"product","count":1}"

                                    log(JSON.parse(itm)) выдает данные как строку а не как объект, это особенность JSON.parse для массивов?

                                    `m.forEach(function(itm, i, arr) {
                                                        result[i] = JSON.stringify((itm.replace('data-product="', '').replace(/"/g, '"').slice(0, -1)));
                                                        
                                                        if (i >= arr.length - 1){
                                                            result.forEach(function(itm, i, arr) {
                                                            log(JSON.parse(itm));    
                                    
                                                            });
                                                        }
                                                    });` 
                                    Ты не даешь полной информации. Как конкретно выглядит m?[/i]
                                    ``` ` 
                                    1 Reply Last reply Reply Quote 0
                                    • I
                                      instalator last edited by

                                      @Bluefox:

                                      @instalator:

                                      Имеем массив с данными

                                      data-product="{"id":2104,"price":250,"discountPrice":240,"isBottle":true,"type":"product","count":1}",

                                      data-product="{"id":1204,"price":190,"discountPrice":180,"isBottle":true,"type":"product","count":1}",

                                      data-product="{"id":1041,"price":170,"discountPrice":160,"isBottle":true,"type":"product","count":1}",

                                      data-product="{"id":3,"price":160,"discountPrice":150,"isBottle":true,"type":"product","count":1}",

                                      data-product="{"id":1203,"price":120,"discountPrice":120,"isBottle":true,"type":"product","count":1}"

                                      log(JSON.parse(itm)) выдает данные как строку а не как объект, это особенность JSON.parse для массивов?

                                      `m.forEach(function(itm, i, arr) {
                                                          result[i] = JSON.stringify((itm.replace('data-product="', '').replace(/"/g, '"').slice(0, -1)));
                                                          
                                                          if (i >= arr.length - 1){
                                                              result.forEach(function(itm, i, arr) {
                                                              log(JSON.parse(itm));    
                                      
                                                              });
                                                          }
                                                      });` 
                                      Ты не даешь полной информации. Как конкретно выглядит m?
                                      Так и выглядит. Только вместо кавычек quote лог автоматом преобразовывет
                                      
                                      `~~[code]~~var m = body.match(/data-product="(.*)"/g);[/code]`
                                      `~~[code]~~{"id":1204,"price":190,"discountPrice":180,"isBottle":true,"type":"product","count":1}[/code]`[/i]
                                      ``` `  ` 
                                      1 Reply Last reply Reply Quote 0
                                      • Bluefox
                                        Bluefox last edited by

                                        @instalator:

                                        @Bluefox:

                                        @instalator:

                                        Имеем массив с данными

                                        data-product="{"id":2104,"price":250,"discountPrice":240,"isBottle":true,"type":"product","count":1}",

                                        data-product="{"id":1204,"price":190,"discountPrice":180,"isBottle":true,"type":"product","count":1}",

                                        data-product="{"id":1041,"price":170,"discountPrice":160,"isBottle":true,"type":"product","count":1}",

                                        data-product="{"id":3,"price":160,"discountPrice":150,"isBottle":true,"type":"product","count":1}",

                                        data-product="{"id":1203,"price":120,"discountPrice":120,"isBottle":true,"type":"product","count":1}"

                                        log(JSON.parse(itm)) выдает данные как строку а не как объект, это особенность JSON.parse для массивов?

                                        `m.forEach(function(itm, i, arr) {
                                                            result[i] = JSON.stringify((itm.replace('data-product="', '').replace(/"/g, '"').slice(0, -1)));
                                                            
                                                            if (i >= arr.length - 1){
                                                                result.forEach(function(itm, i, arr) {
                                                                log(JSON.parse(itm));    
                                        
                                                                });
                                                            }
                                                        });` 
                                        Ты не даешь полной информации. Как конкретно выглядит m?
                                        Так и выглядит. Только вместо кавычек quote лог автоматом преобразовывет
                                        
                                        `~~[code]~~var m = body.match(/data-product="(.*)"/g);[/code]`
                                        `~~[code]~~{"id":1204,"price":190,"discountPrice":180,"isBottle":true,"type":"product","count":1}[/code]`
                                        один stringify лишний
                                        `~~[code]~~result[i] = itm.replace('data-product="', '').replace(/"/g, '"').slice(0, -1);` [/i][/code][/i]
                                        ``` `  `  ` 
                                        1 Reply Last reply Reply Quote 0
                                        • I
                                          instalator last edited by

                                          @Bluefox:

                                          @instalator:

                                          @Bluefox:

                                          Ты не даешь полной информации. Как конкретно выглядит m? `
                                          Так и выглядит. Только вместо кавычек quote лог автоматом преобразовывет

                                          var m = body.match(/data-product="(.*)"/g);
                                          
                                          {"id":1204,"price":190,"discountPrice":180,"isBottle":true,"type":"product","count":1}
                                          ```` `  
                                          

                                          один stringify лишний

                                          `result[i] = itm.replace('data-product="', '').replace(/"/g, '"').slice(0, -1);` 
                                           :) Решил перестраховаться, а он оказывается может напортачить[/i]
                                          ``` ` 
                                          1 Reply Last reply Reply Quote 0
                                          • H
                                            Haus last edited by

                                            Народ помогайте, маленький кусочек скрипта. Проблема, сделал пока костыль на PHP чтобы дёргать из базы средние значения температур за определённый период времени. Таких request штук 10 в скрипте все прописаны в начале скрипта, так вот в временном log('Текущая ' + body), log('Средняя ' + body) инфа актуальная но она как бы запаздывает и лог log(circ_title + ': Расчет: ' + temp_base + ', Сред: ' + temp_in + ', Тек: ' + cur_temp) отображает прошлый request из переменных temp_in и cur_temp. Что можно сделать?

                                            var room  = 'Heat_control';
                                            var tbid    = getIdByName(room + '.temp_base');
                                            var shaid  = getIdByName(room + '.temp_in_stair_hall_avr_30min');
                                            var ctid    = getIdByName(room + '.cur_temp');
                                            
                                            function startt() {    
                                                var request       = require('request');
                                                var circ_title    = 'Дом';
                                                var temp_base  = getState(tbid).val;
                                                var temp_in      = getState(shaid).val;
                                                var cur_temp    = getState(ctid).val;
                                                request('http://192.168.1.11/cur_temp.php', function (error, response, body) {
                                            	if (!error && response.statusCode == 200) {
                                                         setState(ctid, body);
                                                         log('Текущая ' + body);
                                                    }
                                                });
                                                // Средняя температура в помещении за 30 минут
                                                request('http://192.168.1.11/avr_temp_in_stair_hall.php', function (error, response, body) {
                                                    if (!error && response.statusCode == 200) {
                                                         setState(shaid, body);
                                                         log('Средняя ' + body);
                                                    }
                                                });
                                                // Отладка. Выводим информацию по температурам
                                                log(circ_title + ': Расчет: ' + temp_base + ', Сред: ' + temp_in + ', Тек: ' + cur_temp);
                                            }
                                            setInterval(function() {
                                                startt();
                                            },30000);
                                            
                                            
                                            1 Reply Last reply Reply Quote 0
                                            • First post
                                              Last post

                                            Support us

                                            ioBroker
                                            Community Adapters
                                            Donate

                                            499
                                            Online

                                            31.6k
                                            Users

                                            79.4k
                                            Topics

                                            1.3m
                                            Posts

                                            29
                                            358
                                            83112
                                            Loading More Posts
                                            • Oldest to Newest
                                            • Newest to Oldest
                                            • Most Votes
                                            Reply
                                            • Reply as topic
                                            Log in to reply
                                            Community
                                            Impressum | Datenschutz-Bestimmungen | Nutzungsbedingungen
                                            The ioBroker Community 2014-2023
                                            logo