UL агента Fiware IoT: отправить command_value через mqtt на устройство

Я использую IoT-агент для сверхлегкого освещения и хочу отправить команду (включая определенное значение) обратно на свое IoT-устройство. Если я последую примеру умной двери, здесь Я могу отправить что-то вроде:

curl -iX PATCH \
  'http://localhost:1026/v2/entities/urn:ngsi-ld:pysense:002/attrs' \
  -H 'Content-Type: application/json' \
  -H 'fiware-service: openiot' \
  -H 'fiware-servicepath: /' \
  -d '{
    "color": {
    "type" : "command",
    "value" : "100"
    }
  }'

Fiware публикует полезную нагрузку urn: ngsi-ld: pysense: 002 @ color | моему mqtt-брокеру. Но я бы ожидал, что значение «100» тоже будет передано?

Я также нашел эту документацию в Git относительно mqtt-команды. Но тот не уточняет, куда и как это отправлять? Я полагаю, он использует тот же URL, что и этот запрос: http://localhost:4041/v1/updateContext ?? Это современный способ отдавать команды?

Я использую Orion-ld и iotagent-ul: 1.8.0.

Может ли кто-нибудь помочь мне добавить значение «цвет» в mqtt-сообщение?

Спасибо!

РЕДАКТИРОВАТЬ1:

Я просто попробовал orion: 2.2.0 и перерегистрировал команду следующим образом:

{
  "description": "Setting LED",
  "dataProvided": {
    "entities": [
      {
        "id": "urn:ngsi-ld:pysense:002", "type": "pysense"
      }
    ],
    "attrs": ["color", "brightness"]
  },
  "provider": {
    "http": {"url": "http://orion:1026/v2"},
    "legacyForwarding": true
  }
}

Если я попытаюсь отправить команду, orion-logs сходят с ума (продолжайте прокрутку) со следующим текстом:

fiware-orion   | INFO@06:42:33  logMsg.h[1844]: Starting transaction from 172.18.1.1:35800/v2/entities/urn:ngsi-ld:pysense:002/attrs
fiware-orion   | INFO@06:42:33  rest.cpp[885]: Service Path 0: '/dresden'
fiware-orion   | INFO@06:42:33  connectionOperations.cpp[239]: Database Operation Successful (count: { _id.id: "urn:ngsi-ld:pysense:002", _id.servicePath: { $in: [ /^/dresden$/ ] } })
fiware-orion   | INFO@06:42:33  connectionOperations.cpp[94]: Database Operation Successful (query: { _id.id: "urn:ngsi-ld:pysense:002", _id.servicePath: { $in: [ /^/dresden$/ ] } })
fiware-orion   | INFO@06:42:33  connectionOperations.cpp[94]: Database Operation Successful (query: { $or: [ { entities.id: "urn:ngsi-ld:pysense:002", $or: [ { entities.type: "pysense" }, { entities.type: { $exists: false } } ], entities.isPattern: "false", entities.isTypePattern: { $ne: true }, expiration: { $gt: 1559716953 }, status: { $ne: "inactive" }, servicePath: { $in: [ /^$|^/#$|^/dresden/#$|^/dresden$/, null ] } }, { entities.isPattern: "true", entities.isTypePattern: { $ne: true }, expiration: { $gt: 1559716953 }, status: { $ne: "inactive" }, servicePath: { $in: [ /^$|^/#$|^/dresden/#$|^/dresden$/, null ] }, $where: function(){for (var i=0; i < this.entities.length; i++) {if (this.enti... }, { entities.isPattern: "false", entities.isTypePattern: true, expiration: { $gt: 1559716953 }, status: { $ne: "inactive" }, servicePath: { $in: [ /^$|^/#$|^/dresden/#$|^/dresden$/, null ] }, $where: function(){for (var i=0; i < this.entities.length; i++) {if (this.enti... }, { entities.isPattern: "true", entities.isTypePattern: true, expiration: { $gt: 1559716953 }, status: { $ne: "inactive" }, servicePath: { $in: [ /^$|^/#$|^/dresden/#$|^/dresden$/, null ] }, $where: function(){for (var i=0; i < this.entities.length; i++) {if (this.enti... } ] })
fiware-orion   | INFO@06:42:33  connectionOperations.cpp[177]: Database Operation Successful (query: { query: { $or: [ { contextRegistration.entities: { $in: [ { id: "urn:ngsi-ld:pysense:002", type: "pysense" }, { type: "pysense", id: "urn:ngsi-ld:pysense:002" } ] } }, { contextRegistration.entities.id: { $in: [] } } ], expiration: { $gt: 1559716953 }, contextRegistration.attrs.name: { $in: [ "color" ] }, servicePath: { $in: [ /^/dresden$/ ] } }, orderby: { _id: 1 } })
fiware-orion   | ERROR@06:42:33  postUpdateContext.cpp[553]: Internal Error (attribute 'color' not found)
fiware-orion   | INFO@06:42:33  logMsg.h[1844]: Starting transaction to http://orion:1026/v1/updateContext
fiware-orion   | INFO@06:42:33  httpRequestSend.cpp[592]: Sending message 8 to HTTP server: sending message of 433 bytes to HTTP server
fiware-orion   | INFO@06:42:33  logMsg.h[1844]: Starting transaction from 172.18.1.7:46738/v1/updateContext
fiware-orion   | INFO@06:42:33  rest.cpp[885]: Service Path 0: '/dresden'
fiware-orion   | INFO@06:42:33  connectionOperations.cpp[94]: Database Operation Successful (query: { _id.id: "urn:ngsi-ld:pysense:002", _id.type: "pysense", _id.servicePath: { $in: [ /^/dresden$/ ] } })
fiware-orion   | INFO@06:42:34  connectionOperations.cpp[94]: Database Operation Successful (query: { $or: [ { entities.id: "urn:ngsi-ld:pysense:002", $or: [ { entities.type: "pysense" }, { entities.type: { $exists: false } } ], entities.isPattern: "false", entities.isTypePattern: { $ne: true }, expiration: { $gt: 1559716953 }, status: { $ne: "inactive" }, servicePath: { $in: [ /^$|^/#$|^/dresden/#$|^/dresden$/, null ] } }, { entities.isPattern: "true", entities.isTypePattern: { $ne: true }, expiration: { $gt: 1559716953 }, status: { $ne: "inactive" }, servicePath: { $in: [ /^$|^/#$|^/dresden/#$|^/dresden$/, null ] }, $where: function(){for (var i=0; i < this.entities.length; i++) {if (this.enti... }, { entities.isPattern: "false", entities.isTypePattern: true, expiration: { $gt: 1559716953 }, status: { $ne: "inactive" }, servicePath: { $in: [ /^$|^/#$|^/dresden/#$|^/dresden$/, null ] }, $where: function(){for (var i=0; i < this.entities.length; i++) {if (this.enti... }, { entities.isPattern: "true", entities.isTypePattern: true, expiration: { $gt: 1559716953 }, status: { $ne: "inactive" }, servicePath: { $in: [ /^$|^/#$|^/dresden/#$|^/dresden$/, null ] }, $where: function(){for (var i=0; i < this.entities.length; i++) {if (this.enti... } ] })
fiware-orion   | INFO@06:42:34  connectionOperations.cpp[177]: Database Operation Successful (query: { query: { $or: [ { contextRegistration.entities: { $in: [ { id: "urn:ngsi-ld:pysense:002", type: "pysense" }, { type: "pysense", id: "urn:ngsi-ld:pysense:002" } ] } }, { contextRegistration.entities.id: { $in: [] } } ], expiration: { $gt: 1559716954 }, contextRegistration.attrs.name: { $in: [ "color" ] }, servicePath: { $in: [ /^/dresden$/ ] } }, orderby: { _id: 1 } })
fiware-orion   | INFO@06:42:34  logMsg.h[1844]: Starting transaction to http://orion:1026/v1/updateContext
...

И я получаю в ответ в почтальоне следующую ошибку:

{
    "error": "NotFound",
    "description": "The requested entity has not been found. Check type and id"
}

Когда orion регистрирует команду самостоятельно, это выглядит следующим образом с iot-агентом в качестве провайдера вместо orion / v1:

    {
        "id": "5cf677b7c7ecc4737e1e0ec9",
        "expires": "2020-06-04T13:52:55.00Z",
        "dataProvided": {
            "entities": [
                {
                    "id": "urn:ngsi-ld:pysense:002",
                    "type": "pysense"
                }
            ],
            "attrs": [
                "color",
                "brightness"
            ]
        },
        "provider": {
            "http": {
                "url": "http://iot-agent:4041"
            },
            "supportedForwardingMode": "all",
            "legacyForwarding": true
        },
        "status": "active"
    }

Таким образом, я могу отправить команду, но она все равно пропускает значение. :(

EDIT2: кое-что, что я нашел в обширных журналах отладки orion:

fiware-orion   | INFO@07:35:09  connectionOperations.cpp[177]: Database Operation Successful (query: { query: { $or: [ { contextRegistration.entities: { $in: [ { id: "urn:ngsi-ld:pysense:002", type: "pysense" }, { type: "pysense", id: "urn:ngsi-ld:pysense:002" } ] } }, { contextRegistration.entities.id: { $in: [] } } ], expiration: { $gt: 1559720109 }, contextRegistration.attrs.name: { $in: [ "color" ] }, servicePath: { $in: [ /^/dresden$/ ] } }, orderby: { _id: 1 } })
fiware-orion   | ERROR@07:35:09  postUpdateContext.cpp[553]: Internal Error (attribute 'color' not found)

После этого IoT-Agent обновляет контекст, но без значения.


person Sweeman    schedule 03.06.2019    source источник
comment
Вы тестировали тот же сценарий с официальным Orion вместо Orion-LD (например, Orion 2.2.0)? С этим работает или поведение такое же? Спасибо!   -  person fgalan    schedule 04.06.2019
comment
Спасибо за предложение! Я просто попробовал, просто изменив docker-compose и заставив воссоздать. Этого достаточно? Потому что это дает тот же результат. Я отредактирую первый пост с подробной информацией для удобства чтения.   -  person Sweeman    schedule 05.06.2019
comment
Чтобы проверить, правильно ли вы используете Orion, не могли бы вы сделать GET /version на порте CB и сказать, какой ответ вы получите, пожалуйста? Спасибо!   -  person fgalan    schedule 05.06.2019
comment
Ответ: `` {orion: {version: 2.2.0, uptime: 0 d, 3 h, 59 m, 37 s, git_hash: 5a46a70de9e0b809cce1a1b7295027eea0aa757f, compile_time: Mon Feb 25 15:15:27 UTC 2019, compiled_by: root , compiled_in: 37fdc92c3e97, release_date: Mon Feb 25 15:15:27 UTC 2019, doc: fiware-orion.rtfd.io/en/2.2.0}} ``   -  person Sweeman    schedule 05.06.2019
comment
Привет, фгалан, я нашел решение своей проблемы! Я отредактирую его в своем первоначальном посте. Спасибо за помощь! Очень признателен.   -  person Sweeman    schedule 05.06.2019
comment
Приятно знать, что вы решили! Но вместо того, чтобы включать решение в сам вопрос, я бы рекомендовал вам ответить на него самостоятельно. Я имею в виду, вырезать и вставить эту часть из сообщения с вопросом, чтобы ответить. Это обычный способ сделать в SOF.   -  person fgalan    schedule 05.06.2019
comment
Не могли бы вы снова протестировать с помощью PATCH, добавив тип объекта в запрос? Я хочу использовать http://localhost:1026/v2/entities/urn:ngsi-ld:pysense:002/attrs?type=pysense и сказать мне, работает ли он, пожалуйста? Спасибо!   -  person fgalan    schedule 05.06.2019
comment
Привет, фгалан, поменяю пост соответственно. Спасибо за совет! Я также пробовал предложенный вами метод с помощью? Type = pysense, и он действительно работает! Спасибо!   -  person Sweeman    schedule 06.06.2019


Ответы (1)


Есть два решения этой проблемы. Первое, что отличается от учебника, - это провайдер, который необходимо зарегистрировать с помощью команды. Вместо orion: 1026 / v1 зарегистрируйте IoT-Agent. Это должно выглядеть примерно так с IOTA_PROVIDER_URL из вашего docker-compose.yml в качестве провайдера:

{
        "description": "Setting LED",
        "dataProvided": {
            "entities": [
                {
                    "id": "urn:ngsi-ld:pysense:002",
                    "type": "pysense"
                }
            ],
            "attrs": [
                "color",
                "brightness"
            ]
        },
        "provider": {
            "http": {
                "url": "http://iot-agent:4041"
            },
            "supportedForwardingMode": "all",
            "legacyForwarding": true
        },
        "status": "active"
    }

Теперь вы можете отправить команду двумя способами. Первый - прямо к северному порту IoT-агента с помощью команды POST в orion / v1 / updateContext. Второй - обновить команду в контексте, отправив команду PATCH атрибутам сущностей, указав тип сущности в запросе.

1: POST для updateContext

curl -iX POST \
  'http://localhost:1026/v1/updateContext' \
  -H 'Content-Type: application/json' \
  -H 'fiware-service: openiot' \
  -H 'fiware-servicepath: /' \
  -d '{
    "contextElements": [
        {
            "type": "pysense",
            "isPattern": "false",
            "id": "urn:ngsi-ld:pysense:002",
            "attributes": [
                {
                    "name": "color",
                    "type": "command",
                    "value": "25"
                }
            ]
        }
    ],
    "updateAction": "UPDATE"
}

2: ПАТЧ, добавляющий тип объекта

curl -iX PATCH \
  'http://localhost:1026/v2/entities/urn_ngsi-ld:pysense:002/attrs?type=pysense' \
  -H 'Content-Type: application/json' \
  -H 'fiware-service: openiot' \
  -H 'fiware-servicepath: /' \
  -d '{
  "color": {
      "type" : "command",
      "value" : "90"
  }
}

Спасибо fgalan за помощь!

person Sweeman    schedule 06.06.2019
comment
Что касается PATCH, то документально подтверждена необходимость использования типа сущности. Из fiware-orion.readthedocs.io/en/master/user / context_providers /: при пересылке любой тип объекта в обновлении / запросе NGSIv2 соответствует регистрации без типа объекта. Однако обратное не работает, поэтому, если у вас есть регистрации с типами, вы должны использовать ?type в обновлении / запросе NGSIv2, чтобы получить совпадение. - person fgalan; 06.06.2019