NEWS
Вопросы по написанию скриптов
-
есть переменная
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 -
Всем привет, нужна помощь это кусочек скрипта работает нормально, где то на третьем вычислении 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 + 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; -
Как сделать выполнение скрипта через пять минут после его завершения. В этом варианте 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); -
Как сделать выполнение скрипта через пять минут после его завершения. В этом варианте 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); -
Как сделать выполнение скрипта через пять минут после его завершения. В этом варианте 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);и по логу видно как время смищается
-
Как сделать выполнение скрипта через пять минут после его завершения. В этом варианте 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); -
А по моей проблемам какие идеи?
-
А как можно вывести все поля объекта? Когда подписываюсь на изменения объекта, например чтоб не только по полю val проверять, а например, и по времени изменения? `
Вместо val напиши ts. Описание на дравйвер смотри на гите -
В чем ошибка?
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 не существует.
-
В чем ошибка?
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 возвращает много чего.
-
Имеем массив с данными
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] -
Имеем массив с данными
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] ``` ` -
Имеем массив с данными
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] ``` ` ` -
Имеем массив с данными
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] ``` ` ` ` -
Ты не даешь полной информации. Как конкретно выглядит 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] ``` ` -
Народ помогайте, маленький кусочек скрипта. Проблема, сделал пока костыль на 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); -
var request = require('request'); 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 printDebug() { var circ_title = 'Дом'; var temp_base = getState(tbid).val; var temp_in = getState(shaid).val; var cur_temp = getState(ctid).val; log(circ_title + ': Расчет: ' + temp_base + ', Сред: ' + temp_in + ', Тек: ' + cur_temp); } function startt() { var count = 0; count++; request('http://192.168.1.11/cur_temp.php', function (error, response, body) { if (!error && response.statusCode == 200) { setState(ctid, body); log('Текущая ' + body); } count--; if (!count) printDebug(); }); // Средняя температура в помещении за 30 минут count++; 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); } count--; if (!count) printDebug(); }); } setInterval(function() { startt(); },30000);А надо ли вызывать скрипт каждые 30 секунд?
-
var request = require('request'); 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 printDebug() { var circ_title = 'Дом'; var temp_base = getState(tbid).val; var temp_in = getState(shaid).val; var cur_temp = getState(ctid).val; log(circ_title + ': Расчет: ' + temp_base + ', Сред: ' + temp_in + ', Тек: ' + cur_temp); } function startt() { var count = 0; count++; request('http://192.168.1.11/cur_temp.php', function (error, response, body) { if (!error && response.statusCode == 200) { setState(ctid, body); log('Текущая ' + body); } count--; if (!count) printDebug(); }); // Средняя температура в помещении за 30 минут count++; 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); } count--; if (!count) printDebug(); }); } setInterval(function() { startt(); },30000);А надо ли вызывать скрипт каждые 30 секунд? `
Не, вызывается каждые 5 минут это я для отладки 30 сек поставил
Hey! Du scheinst an dieser Unterhaltung interessiert zu sein, hast aber noch kein Konto.
Hast du es satt, bei jedem Besuch durch die gleichen Beiträge zu scrollen? Wenn du dich für ein Konto anmeldest, kommst du immer genau dorthin zurück, wo du zuvor warst, und kannst dich über neue Antworten benachrichtigen lassen (entweder per E-Mail oder Push-Benachrichtigung). Du kannst auch Lesezeichen speichern und Beiträge positiv bewerten, um anderen Community-Mitgliedern deine Wertschätzung zu zeigen.
Mit deinem Input könnte dieser Beitrag noch besser werden 💗
Registrieren Anmelden