Плагин HTTP-Client



  • Господа, имеется ответ от девайса в виде массива JSOn вида:

     "onew_temp": [
        {
          "id": "1",
          "adr_hex": "28BC6B2D09000066",
          "name": "S6",
          "t": "25.31"
        },
        {
          "id": "2",
          "adr_hex": "28AADE403D1401D6",
          "name": "S2",
          "t": "25.06"
        },
    

    Как правильно написать выражение для извлечения данных, что бы оно извлекало t там, где name="S6" ?
    Понятно что,
    data.onew_temp[0].t
    извлечет то что нужно, но дело в том что нет уверенности что эти данные всгда будут на этом месте. А вот "name": "S6" будет всегда.



  • Участник @alesle написал в Плагин HTTP-Client:

    но дело в том что нет уверенности что эти данные всгда будут на этом месте. > А вот "name": "S6" будет всегда.

    Если "name": "S6" будет всегда, то можно так:

    data.onew_temp.filter(item => item.name=="S6")[0].t
    


  • Блин, работает!!!
    Я правда нифига не вкурил как , но - работает!!!
    Буду разбираться..
    Спасибо огромное!



  • @alesle пожалуйста 🙂
    Вот вариант еще короче

    data.onew_temp.find(item => item.name=="S6").t
    

    Современный javascript мощный и гибкий язык, особенно если использовать синтаксис ES6 (или ES2015, что одно и то же) , в данном случае стрелочные функции.
    Магия этих выражений раскрывается в 2 шага

    1. Массивы в JS имеют встроенные методы для поиска по заданному критерию, в частности filter, find

      • find - ищет первый элемент массива, возвращает найденный объект
      • filter - сюрприз 🙂 - фильтрует входной массив и возвращает все найденные элементы (learn.javascript.ru/array-methods)
    2. Методу нужно передать критерий отбора - функцию для обработки элемента массива.

      Если писать, используя синтаксис классических функций, то получится так:

       arr.filter( function (item) {
         return item.name == 'S6';  
      });
      

      Функция вызывается по очереди для каждого элемента массива (item), если возвращает true, то элемент берется в новый массив

      С введением в ES6 стрелочных функций все стало компактнее:

       function (item) {return item.name == 'S6';} 
      

      можно заменить на

       (item)  => item.name == 'S6' 
      

      Что произошло

    • убрали function
    • грубо говоря return заменили на =>
    • если входной аргумент ровно один - то и скобки можно не ставить

    Подробнее https://learn.javascript.ru/arrow-functions
    Получаем:

     arr.filter( item => item.name == 'S6' );
    

    Ну и надо иметь в виду, что возвращает метод массива.
    Если результат - массив, то берем свойство его первого элемента

    data.onew_temp.filter(item => item.name=="S6")[0].t
    

    Если результат - объект, то просто берем свойство t

    data.onew_temp.find(item => item.name=="S6").t
    


  • Спасибо за доходчивое объяснение!



  • Здравствуйте.
    А как действовать, если веб страница скриптами заполняется?
    Выглядит так
    alt text
    а внутри
    Текст ссылки

    Как вытащить, например, напряжение на входе?



  • @Erik а SNMP у него нет?



  • @homa

    В него нужно какую то плату вставить, а я их в продаже не нашел.
    Без платы нет.
    Подключается по USB к компьютеру, и через веб-сервер на этом компьютере можно смотреть и настраивать хоть локально, хоть с другого ПК.



  • @Erik Добрый день, обычно в таком случае в отладчике хрома, в разделе network можно найти запросы типа JSON



  • @dev
    там только xhr
    alt text



  • @Erik Добрый день, reqMonitorData похоже он и есть, можно выбрать любой запрос и посмотреть вкладку response



  • там

    {"capability":{"capableA":true,"capableB":true,"capableC":true,"capableD":false,"capableE":false,"capableF":false,"capableG":false,"capableH":true,"capableI":false,"capableJ":false,"capableK":false,"capableL":false,"capableN":false,"capableO":false,"capableP":true,"capableQ":false,"capableR":true,"capableS":true,"capableT":false,"capableV":false,"capableW":false,"capableZ":true,"capablea":false,"capableb":false,"capablec":false,"capabled":false,"capablee":false,"capablef":false,"capableg":false,"capableh":false,"capablei":false,"capablej":false,"capablek":false,"capablel":false,"capablem":false,"capableo":false,"capablep":false,"capabler":false,"capables":false,"capableu":false,"capablev":false,"capablex":false,"capabley":false,"capablez":false,"enableA":true,"enableB":true,"enableC":true,"enableD":false,"enableE":true,"enableF":true,"enableG":true,"enableH":true,"enableI":false,"enableJ":true,"enableK":false,"enableL":true,"enableN":false,"enableO":true,"enableP":true,"enableQ":false,"enableR":true,"enableS":true,"enableT":false,"enableV":true,"enableW":false,"enableZ":true,"enablea":false,"enableb":false,"enablec":false,"enabled":false,"enablee":false,"enablef":false,"enableg":false,"enableh":false,"enablei":false,"enablej":false,"enablek":false,"enablel":false,"enablem":false,"enableo":false,"enablep":false,"enabler":false,"enables":false,"enableu":false,"enablev":false,"enablex":false,"enabley":false,"enablez":false},"customer":"ViewPower","customerLogo":"","customerViewpower":"ViewPower","customized":"ViewPower","eventFileName":"","historyColumns":{"colid":0,"columns":[{"datafield":"currentTime","headertext":"[text.mv.col1]","id":"","labelFunction":"displayDate"},{"datafield":"inputVoltage","headertext":"[text.inputV]","id":"inputV1","labelFunction":""},{"datafield":"inputFrequency","headertext":"[text.inputF]","id":"","labelFunction":"displayInputFrequency"},{"datafield":"outputVoltage","headertext":"[text.outputV]","id":"outputVR","labelFunction":""},{"datafield":"outputFrequency","headertext":"[text.outputF]","id":"","labelFunction":""},{"datafield":"outputCurrent","headertext":"[text.loadEle]","id":"","labelFunction":"displayOutputCurrent"},{"datafield":"outputLoadPercent","headertext":"[label.loadPercents]","id":"","labelFunction":"displayOutpuLoadPercents"},{"datafield":"batteryVoltage","headertext":"[text.BTV]","id":"","labelFunction":""},{"datafield":"temperatureView","headertext":"[text.upsTemperature]","id":"","labelFunction":"calTemp"}]},"hostName":"192.168.13.33","menuList":{"menuList":[{"data":"system","items":[{"item":{"data":"password","groupName":"menu","label":"[label.passwordSet]","type":""},"items":[]},{"item":{"data":"mobile","groupName":"menu","label":"[label.smsinfoSet]","type":""},"items":[]},{"item":{"data":"email","groupName":"menu","label":"[label.emailSet]","type":""},"items":[]},{"item":{"data":"eleEvent","groupName":"menu","label":"[label.electricEventSet]","type":""},"items":[]},{"item":{"data":"network","groupName":"menu","label":"[label.netWeakUPSet]","type":""},"items":[]},{"item":{"data":"setcom","groupName":"menu","label":"[label.setcom]","type":""},"items":[]},{"item":{"data":"recorddata","groupName":"menu","label":"[label.recorddata]","type":""},"items":[]},{"item":{"data":"modbus","groupName":"menu","label":"[label.modbussetting]","type":""},"items":[]}],"label":"[label.config] ViewPower"},{"data":"config","items":[{"item":{"data":"loadClose","groupName":"menu","label":"[label.shutdownParamSet]","type":""},"items":[]},{"item":{"data":"remoteLoadClose","groupName":"menu","label":"[label.remoteShutdownParamSet]","type":""},"items":[]},{"item":{"data":"controlPara","groupName":"menu","label":"[label.controlParamSet]","type":""},"items":[]},{"item":{"data":"buy","groupName":"menu","label":"[label.upsBurInfoSet]","type":""},"items":[]}],"label":"[label.upsSet]"},{"data":"control","items":[{"item":{"data":"onOff","groupName":"menu","label":"[label.realTimeCtrl]","type":""},"items":[]},{"item":{"data":"onOffPlan","groupName":"menu","label":"[label.powerPlan]","type":""},"items":[]},{"item":{"data":"testPlan","groupName":"menu","label":"[label.autoTestPlan]","type":""},"items":[]}],"label":"[label.controlPlatform]"},{"data":"monitor","items":[{"item":{"data":"immediately","groupName":"menu","label":"[label.realInfoView]","type":""},"items":[]},{"item":{"data":"historyInfo","groupName":"menu","label":"[label.historyInfoView]","type":""},"items":[]}],"label":"[label.upsWatch]"},{"data":"top","items":[{"item":{"data":"temperature","groupName":"","label":"[label.temperatureUnit]","type":""},"items":[{"data":"celsiur","groupName":"temp","label":"[label.Celsius]","type":"radio"},{"data":"fahrenheit","groupName":"temp","label":"[label.Fahrenheit]","type":"radio"}]},{"item":{"data":"requireState","groupName":"","label":"[label.dateFormat]","type":""},"items":[{"data":"YYYY-MM-DD","groupName":"date","label":"YYYY-MM-DD","type":"radio"},{"data":"YYYY/MM/DD","groupName":"date","label":"YYYY/MM/DD","type":"radio"},{"data":"YYYY:MM:DD","groupName":"date","label":"YYYY:MM:DD","type":"radio"},{"data":"MM-DD-YYYY","groupName":"date","label":"MM-DD-YYYY","type":"radio"},{"data":"MM/DD/YYYY","groupName":"date","label":"MM/DD/YYYY","type":"radio"},{"data":"MM:DD:YYYY","groupName":"date","label":"MM:DD:YYYY","type":"radio"},{"data":"DD-MM-YYYY","groupName":"date","label":"DD-MM-YYYY","type":"radio"},{"data":"DD/MM/YYYY","groupName":"date","label":"DD/MM/YYYY","type":"radio"},{"data":"DD:MM:YYYY","groupName":"date","label":"DD:MM:YYYY","type":"radio"}]}],"label":"[label.systemStyle]"},{"data":"top","items":[{"item":{"data":"English","groupName":"language","label":"English","type":"radio"},"items":[]},{"item":{"data":"French","groupName":"language","label":"French","type":"radio"},"items":[]},{"item":{"data":"German","groupName":"language","label":"German","type":"radio"},"items":[]},{"item":{"data":"Italian","groupName":"language","label":"Italian","type":"radio"},"items":[]},{"item":{"data":"Polish","groupName":"language","label":"Polish","type":"radio"},"items":[]},{"item":{"data":"Portuguese","groupName":"language","label":"Portuguese","type":"radio"},"items":[]},{"item":{"data":"Russian","groupName":"language","label":"Russian","type":"radio"},"items":[]},{"item":{"data":"Spanish","groupName":"language","label":"Spanish","type":"radio"},"items":[]},{"item":{"data":"Ukrainian","groupName":"language","label":"Ukrainian","type":"radio"},"items":[]},{"item":{"data":"Turkish","groupName":"language","label":"Turkish","type":"radio"},"items":[]},{"item":{"data":"Czech","groupName":"language","label":"Czech","type":"radio"},"items":[]},{"item":{"data":"Chinese","groupName":"language","label":"Chinese(Simplified)","type":"radio"},"items":[]},{"item":{"data":"ChineseTW","groupName":"language","label":"Chinese(Traditional)","type":"radio"},"items":[]}],"label":"[label.language]"},{"data":"top","items":[{"item":{"data":"copyRight","groupName":"","label":"[label.copyRight]","type":""},"items":[]},{"item":{"data":"systemHelp_en","groupName":"","label":"[label.systemHelp]","type":""},"items":[]}],"label":"[label.Help]"}]},"modules":null,"portName":"USBusbdev2","protocolType":"P01","refreshSearchUPSTree":"","refreshSearchingUPS":false,"refreshTree":"2020-02-22 15:29:05","selectDevice":"","serverName":"ViewPower","showLocalUPS":true,"showNetSNMP":false,"snmp":false,"snmpInfo":{"janitorWarning1":"","janitorWarning1Unit":"","janitorWarning2":"","janitorWarning2Unit":"","janitorWarning3":"","janitorWarning3Unit":"","janitorWarning4":"","janitorWarning4Unit":"","smogPercent":"","smogPercentUnit":"","workHumidity":"","workHumidityUnit":"","workTemperature":"","workTemperatureUnit":""},"statuspowerflow":{"battery":[{"caption":"[text.BTV]:","textvalue":"{workInfo.batteryVoltage}","unit":"V"},{"caption":"[text.BatteryPercent]:","textvalue":"{workInfo.batteryCapacity}","unit":"%"},{"caption":"[text.batteryRemaining]:","textvalue":"{workInfo.batteryRemainTime}","unit":"Min"}],"bypassInfoLines":[],"input":[{"caption":"[text.inputV]:","textvalue":"{workInfo.inputVoltage}","unit":"V"},{"caption":"[text.inputF]:","textvalue":"{workInfo.inputFrequency}","unit":"Hz"}],"inverterInfoLines":[],"output":[{"caption":"[text.outputV]:","textvalue":"{workInfo.outputVoltage}","unit":"V"},{"caption":"[text.outputF]:","textvalue":"{workInfo.outputFrequency}","unit":"Hz"},{"caption":"[label.loadPercents]:","textvalue":"{workInfo.outputLoadPercent}","unit":"%"},{"caption":"[text.loadEle]:","textvalue":"{workInfo.outputCurrent}","unit":"A"}],"solarInfoLines":[],"upsInfo":[{"caption":"[text.workMod]:","textvalue":"{workInfo.workMode}","unit":""},{"caption":"[text.internalTp]:","textvalue":"{workInfo.temperatureView}","unit":" ℃"}]},"statusupsinfo":{"info":[{"label":"[label.inputInfo]","lines":[{"caption":"[text.inputV]","textvalue":"{workInfo.inputVoltage}","unit":"V"},{"caption":"[text.inputF]","textvalue":"{workInfo.inputFrequency}","unit":"Hz"}]},{"label":"[label.upsInfo]","lines":[{"caption":"[text.workMod]","textvalue":"{workInfo.workMode}","unit":""},{"caption":"[text.upsTemperature]","textvalue":"{workInfo.temperatureView}","unit":" ℃"},{"caption":"[label.autoReboot]","textvalue":"{workInfo.autoReboot}","unit":""},{"caption":"[label.converterMode]","textvalue":"{workInfo.converterMode}","unit":""},{"caption":"[label.eCOMode]","textvalue":"{workInfo.ecomode}","unit":""},{"caption":"[label.bypassOff]","textvalue":"{workInfo.bypassOff}","unit":""},{"caption":"[label.bypassNotAllowed]","textvalue":"{workInfo.bypassNotAllowed}","unit":""},{"caption":"[label.faultType]","textvalue":"{workInfo.faultType}","unit":""},{"caption":"[label.warn]","textvalue":"{workInfo.warnings}","unit":""}]},{"label":"[label.batteryInfo]","lines":[{"caption":"[text.BTV]","textvalue":"{workInfo.batteryVoltage}","unit":"V"},{"caption":"[text.BatteryPercent]","textvalue":"{workInfo.batteryCapacity}","unit":"%"},{"caption":"[text.batteryRemaining]","textvalue":"{workInfo.batteryRemainTime}","unit":"Min"}]},{"label":"[label.outputInfo]","lines":[{"caption":"[text.outputV]","textvalue":"{workInfo.outputVoltage}","unit":"V"},{"caption":"[text.outputF]","textvalue":"{workInfo.outputFrequency}","unit":"Hz"},{"caption":"[label.loadLevel]","textvalue":"{workInfo.outputLoadPercent}","unit":"%"},{"caption":"[text.loadEle]","textvalue":"{workInfo.outputCurrent}","unit":"A"}]}]},"supportBatNum":true,"version":"ViewPowerHTML V1.03","webMapping":null,"workInfo":{"autoReboot":"[label.enable]","batChargingCurrentN":"","batChargingCurrentP":"","batDisChargingCurrentN":"","batDisChargingCurrentP":"","batteryCapacity":100,"batteryCapacityReal":0,"batteryCapacitys":[100,100,100,100,100,100,100,100,100,100],"batteryLife":"","batteryRemainTime":1800,"batteryTemp":"","batteryVoltage":"027.1","buzzerCtrl":true,"bypassActive":false,"bypassCurrent":"","bypassCurrentS":"","bypassCurrentT":"","bypassFrequency":"","bypassNotAllowed":"[label.disable]","bypassOff":"[label.disable]","bypassVoltage":"","bypassVoltageL1L2":"","bypassVoltageL1L3":"","bypassVoltageL2L3":"","bypassVoltageS":"","bypassVoltageT":"","cabinetTemp":"","canBatteryTest":false,"chargeCurr":"","chargeON":false,"clear":false,"converterMode":"[label.disable]","currentTime":{"date":25,"day":2,"hours":13,"minutes":3,"month":1,"seconds":56,"time":1582625036976,"timezoneOffset":-180,"year":120},"deviceId":"0000000000000000","dischargeCurr":"","dual":false,"ecomode":"[label.disable]","enableOutlet1":true,"enableOutlet2":false,"faultKind":"","faultType":"","first":false,"groupNum":"22","heatsinkTemp1":"","heatsinkTemp2":"","inType":0,"independentBat":false,"inputCurrentR":"","inputCurrentS":"","inputCurrentT":"","inputFrequency":"50.0","inputPowerPV":"","inputScaleFactor":"","inputVoltage":"241.0","inputVoltage2":"","inputVoltageL1L2":"","inputVoltageL1L3":"","inputVoltageL2L3":"","inputVoltagePV":"","inputVoltageS":"0","inputVoltageS2":"","inputVoltageT":"0","inputVoltageT2":"","inputWireType":"","insertBypass":false,"insertInput":false,"insertOutput":false,"intputAngle":"","inverterHT":"","inverterHTView":"","inverterVoltage":"","inverterVoltageS":"","inverterVoltageT":"","ioPhase":"1/1","lastfaultID":"","loadLevel":"","loadLevelS":"","loadLevelT":"","modul":0,"modulesInfo":[],"morphological":"on-line","negativeBatteryCurrent":"","negativeBatteryVoltage":"","outType":"","outputAngle":"","outputCurrent":"0.0","outputCurrentS":"","outputCurrentT":"","outputFrequency":"50.0","outputLoadPercent":"004","outputON":false,"outputPowerFactorL1":"","outputPowerFactorL2":"","outputPowerFactorL3":"","outputRatingVoltage":230,"outputScaleFactor":"","outputVoltage":"229.6","outputVoltageL1L2":"","outputVoltageL1L3":"","outputVoltageL2L3":"","outputVoltageS":"0","outputVoltageT":"0","outputWireType":"","p1outlet":"[label.enable]","parallelRack":false,"positiveBatteryCurrent":"","positiveBatteryVoltage":"","ptid":"P01","rectifierHt":"","rectifierHtView":"","settingChanged":false,"showLabel":false,"shutdownActive":false,"solar":false,"solarON":false,"temp1":"","temp2":"","temperature":"20.5","temperatureView":"20.5","upsType":"","warnings":[],"workId":0,"workMode":"Line mode"}}
    

    есть "inputVoltage":"241.0",



  • @Erik Добрый день, там приходит объект, в workInfo есть все необходимое. Для удобства воспользуйтесь сервисом, вставьте текст в левую колонку и нажмите COPY >

    Снимок экрана 2020-02-25 в 13.16.44.png

    • удалены ненужные поля для наглядности


  • Пользователь @Erik написал в Плагин HTTP-Client:

    inputVoltage

    Я и более простое не понимаю.
    Со стороны плагина.
    url ставлю http://192.168.13.33:15178/ViewPower/monitor?805
    метод запроса get?

    Канал
    выбираю аналоговый актуатор (создал InputV)
    тип обработки - json
    извлечение данных json что писать? inputVoltage?



  • @Erik Добрый день, для начала нужно уточнить, есть ли у веб интерфейса форма авторизации ?



  • @dev
    есть, но показывает и без авторизации.
    авторизация для настройки нужна.



  • @Erik Добрый день, все верно,
    Вы попробуйте еще в инкогнито открыть http://192.168.13.33:15178/ViewPower/monitor?805 если данные отображаются, то настраивайте дальше:
    запрос - GET
    URL - http://192.168.13.33:15178/ViewPower/monitor?805
    тип обработки - json
    извлечение данных json - data.workInfo.inputVoltage

    data - ваш объект (корень) дальше через точку обращаетесь к кусту с именем



  • Пользователь @dev написал в Плагин HTTP-Client:

    data.workInfo.inputVoltage

    инкогнито показывает, так настроил, но значение не присваивает актуатору. Остается 0 всегда.



  • @Erik Добрый день, нужно в отладчике смотреть



  • Пользователь @dev написал в Плагин HTTP-Client:

    @Erik Добрый день, нужно в отладчике смотреть

    вот

    25.02 13:44:41.169 IH: get [ { dn: 'ACTORA81',
        err: 'Unexpected token < in JSON at position 4' } ]
    set { ACTORA81: { err: 'Unexpected token < in JSON at position 4' } }
    

Авторизуйтесь, чтобы ответить