Navigation

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

    NEWS

    • Neuer Blog: Fotos und Eindrücke aus Solingen

    • ioBroker@Smart Living Forum Solingen, 14.06. - Agenda added

    • ioBroker goes Matter ... Matter Adapter in Stable

    Не работает поток в node-red

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

      Создал поток в node-red, согласно документации https://github.com/mrkrasser/MercurySta … adme.ru.md

      сам поток в файле https://github.com/mrkrasser/MercurySta ... Stats.json

      Есть статус "connected" в свойствах порта (зелёный кружочек).

      Ошибок в логах нет, но так как поток разорван - работает только первая часть (включил лог в функции "BinaryRequest" - лог пишется).

      Вставил логирование в функции "Parser" в первой строке кода - оно не срабатывает.

      Из чего делаю вывод что вторая часть потока вообще не запускается.

      В чём может быть проблема?

      Задача простая - передать строку в com-порт , а затем считать ответ с таймаутом 500 мсек.

      При попытке работать в javascript с портом напрямую:

      var SerialPort = require('serialport');
      var port = new SerialPort('/dev/ttyUSB1', {
          parser: SerialPort.parsers.byteLength(4)
      });
      var sendcmd = new Buffer("000774BE63", "hex"); 
      port.on('open', function() {
        port.write(sendcmd, function(err) {
          if (err) {
            return console.log('Error on write: ', err.message);
          }
          log('message written');
        });
      });
      
      port.on('data', function (data) {
        log('Data: ' + data);
      });
      
      

      периодически выходит ошибка:

      Error: 2016-09-16 13:43:58.055 error Error Resource temporarily unavailable Cannot lock port

      uncaught 2016-09-16 13:43:58.054 error exception: Error Resource temporarily unavailable Cannot lock port

      Ответа (данных от порта) нет, возможно из-за отсутствия таймаута на считывание с порта, не знаю как правильно поставить.

      Скрипт на php с этим портом работает стабильно.

      1 Reply Last reply Reply Quote 0
      • A
        andrey99986 last edited by

        Не работает функция port.close() - порт остаётся открытым :

        lsof | grep /dev/ttyUSB1

        io.javasc 29819              root   14uW     CHR              188,1       0t0      11147 /dev/ttyUSB1
        nodejs    29819 29820        root   14uW     CHR              188,1       0t0      11147 /dev/ttyUSB1
        V8        29819 29821        root   14uW     CHR              188,1       0t0      11147 /dev/ttyUSB1
        V8        29819 29822        root   14uW     CHR              188,1       0t0      11147 /dev/ttyUSB1
        V8        29819 29823        root   14uW     CHR              188,1       0t0      11147 /dev/ttyUSB1
        V8        29819 29824        root   14uW     CHR              188,1       0t0      11147 /dev/ttyUSB1
        nodejs    29819 29825        root   14uW     CHR              188,1       0t0      11147 /dev/ttyUSB1
        nodejs    29819 29826        root   14uW     CHR              188,1       0t0      11147 /dev/ttyUSB1
        nodejs    29819 29827        root   14uW     CHR              188,1       0t0      11147 /dev/ttyUSB1
        nodejs    29819 29828        root   14uW     CHR              188,1       0t0      11147 /dev/ttyUSB1
        
        

        Помогает только рестарт драйвера javascript…

        Задержку считывания сделал:

        setStateDelayed('s1', false, 500, false, function () {
            port.on('data', function (data) {
            log('Data after 500 ms: ' + data);
            });
        });
        

        Но ответа нет…

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

          @andrey99986:

          Не работает функция port.close() - порт остаётся открытым :

          lsof | grep /dev/ttyUSB1

          io.javasc 29819              root   14uW     CHR              188,1       0t0      11147 /dev/ttyUSB1
          nodejs    29819 29820        root   14uW     CHR              188,1       0t0      11147 /dev/ttyUSB1
          V8        29819 29821        root   14uW     CHR              188,1       0t0      11147 /dev/ttyUSB1
          V8        29819 29822        root   14uW     CHR              188,1       0t0      11147 /dev/ttyUSB1
          V8        29819 29823        root   14uW     CHR              188,1       0t0      11147 /dev/ttyUSB1
          V8        29819 29824        root   14uW     CHR              188,1       0t0      11147 /dev/ttyUSB1
          nodejs    29819 29825        root   14uW     CHR              188,1       0t0      11147 /dev/ttyUSB1
          nodejs    29819 29826        root   14uW     CHR              188,1       0t0      11147 /dev/ttyUSB1
          nodejs    29819 29827        root   14uW     CHR              188,1       0t0      11147 /dev/ttyUSB1
          nodejs    29819 29828        root   14uW     CHR              188,1       0t0      11147 /dev/ttyUSB1
          
          

          Помогает только рестарт драйвера javascript…

          Задержку считывания сделал:

          setStateDelayed('s1', false, 500, false, function () {
              port.on('data', function (data) {
              log('Data after 500 ms: ' + data);
              });
          });
          

          Но ответа нет… `
          А где код, который делает port.close ?

          1 Reply Last reply Reply Quote 0
          • A
            andrey99986 last edited by

            > А где код, который делает port.close ?
            В такой комбинации порт начал закрываться:

            port.pause();
            port.close();
            
            

            Смог подключиться своим скриптом к GSM- розетке,имеющей вход RS232 (через другой USB порт), получаю нормальный ответ.

            Осталось разобраться с Меркурием.

            Возможно не верно формируется строка запроса.

            на php:

            hex2bin ('000774BE6354e7');

            на js -?

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

              ` > hex2bin ('000774BE6354e7');

              на js -? `

              var sendcmd = new Buffer("000774BE6354e7", "hex"); 
              
              1 Reply Last reply Reply Quote 0
              • A
                andrey99986 last edited by

                На js заработало, код:

                createState('s1');
                
                schedule("*/10 * * * *", function () {
                var cmd1 = new Buffer ([0x00,0x07,0x74,0xBE,0x63,0x54,0xE7]);
                
                var SerialPort = require('serialport');
                var port = new SerialPort('/dev/ttyUSB1', {
                
                parser: SerialPort.parsers.byteLength(14),
                  baudrate: 9600,
                  dataBits: 8,
                  parity: 'none'
                }, function (err) {
                  if (err) {
                    return console.log('Error: ', err.message);
                  }
                  port.write(cmd1, function(err) {
                    if (err) {
                      return console.log('Error on write: ', err.message);
                    }
                    //console.log('message written');
                  });
                });
                
                setStateDelayed('s1', false, 10, false, function () {
                    port.on('data', function (data) {
                	setState('Uv', Number(data.toString('hex',5,7)/10));
                	setState('Ia', Number(data.toString('hex',7,9)/100));
                	setState('Ew', Number(data.toString('hex',9,12)/1));
                      });
                
                    });
                setStateDelayed('s1', false, 1000, false, function () {
                    port.pause();
                    port.close();
                    log('Port is closed');
                     });
                });
                
                
                1 Reply Last reply Reply Quote 0
                • Bluefox
                  Bluefox last edited by

                  А так работает?

                  var cmd1 = new Buffer ([0x00,0x07,0x74,0xBE,0x63,0x54,0xE7]);
                  var SerialPort = require('serialport');
                  
                  schedule("*/10 * * * *", function () {
                  	var port = new SerialPort('/dev/ttyUSB1', 
                  		{
                  			parser:   SerialPort.parsers.byteLength(14),
                  			baudrate: 9600,
                  			dataBits: 8,
                  			parity:   'none'
                  		}, 
                  		function (err) {
                  			if (err) return console.log('Error: ', err.message);
                  
                  			port.on('data', function (data) {
                  				setState('Uv', Number(data.toString('hex', 5,  7) / 10));
                  				setState('Ia', Number(data.toString('hex', 7,  9) / 100));
                  				setState('Ew', Number(data.toString('hex', 9, 12) / 1));
                  
                  				setTimeout(function () {
                  					port.pause();
                  					port.close(function (err) {
                  						if (err) console.error(err);
                  						//port is really closed
                  						console.log('Port is closed)
                  						port = null; // speed up garbage collector
                  					});
                  				}, 100);
                  			});
                  
                  			port.write(cmd1, function(err) {
                  				if (err) {
                  					port.pause();
                  					port.close();
                  					return console.log('Error on write: ', err.message);
                  				}
                  				//console.log('message written');
                  			});
                  		});
                  });
                  
                  1 Reply Last reply Reply Quote 0
                  • A
                    andrey99986 last edited by

                    Работает.

                    Правильнее сначала слушатель запустить с таймаутом 100 мс и только потом отправить комманду в порт?

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

                      @andrey99986:

                      Работает.

                      Правильнее сначала слушатель запустить с таймаутом 100 мс и только потом отправить комманду в порт? `
                      Да.

                      Вот только "слушатель" запускается не с таймаутом, а просто перед тем, как послать команду. И после ответа порт по таймауту закрывается.

                      1 Reply Last reply Reply Quote 0
                      • First post
                        Last post

                      Support us

                      ioBroker
                      Community Adapters
                      Donate

                      885
                      Online

                      31.8k
                      Users

                      80.0k
                      Topics

                      1.3m
                      Posts

                      2
                      9
                      3115
                      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