ua_network_pubsub_mqtt.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  4. *
  5. * Copyright (c) 2018 Fraunhofer IOSB (Author: Lukas Meling)
  6. */
  7. /**
  8. * This uses the mqtt/ua_mqtt_adapter.h to call mqtt functions.
  9. * Currently only ua_mqtt_adapter.c implements this
  10. * interface and maps them to the specific "MQTT-C" library functions.
  11. * Another mqtt lib could be used.
  12. * "ua_mqtt_pal.c" forwards the network calls (send/recv) to UA_Connection (TCP).
  13. */
  14. #include "mqtt/ua_mqtt_adapter.h"
  15. #include "open62541/plugin/log_stdout.h"
  16. static UA_StatusCode
  17. UA_uaQos_toMqttQos(UA_BrokerTransportQualityOfService uaQos, UA_Byte *qos){
  18. switch (uaQos){
  19. case UA_BROKERTRANSPORTQUALITYOFSERVICE_BESTEFFORT:
  20. *qos = 0;
  21. break;
  22. case UA_BROKERTRANSPORTQUALITYOFSERVICE_ATLEASTONCE:
  23. *qos = 1;
  24. break;
  25. case UA_BROKERTRANSPORTQUALITYOFSERVICE_ATMOSTONCE:
  26. *qos = 2;
  27. break;
  28. default:
  29. break;
  30. }
  31. return UA_STATUSCODE_GOOD;
  32. }
  33. /**
  34. * Open mqtt connection based on the connectionConfig.
  35. *
  36. *
  37. * @return ref to created channel, NULL on error
  38. */
  39. static UA_PubSubChannel *
  40. UA_PubSubChannelMQTT_open(const UA_PubSubConnectionConfig *connectionConfig) {
  41. UA_NetworkAddressUrlDataType address;
  42. memset(&address, 0, sizeof(UA_NetworkAddressUrlDataType));
  43. if(UA_Variant_hasScalarType(&connectionConfig->address, &UA_TYPES[UA_TYPES_NETWORKADDRESSURLDATATYPE])){
  44. address = *(UA_NetworkAddressUrlDataType *)connectionConfig->address.data;
  45. } else {
  46. UA_LOG_ERROR(UA_Log_Stdout, UA_LOGCATEGORY_SERVER, "PubSub MQTT Connection creation failed. Invalid Address.");
  47. return NULL;
  48. }
  49. /* allocate and init memory for the Mqtt specific internal data */
  50. UA_PubSubChannelDataMQTT * channelDataMQTT =
  51. (UA_PubSubChannelDataMQTT *) UA_calloc(1, (sizeof(UA_PubSubChannelDataMQTT)));
  52. if(!channelDataMQTT){
  53. UA_LOG_ERROR(UA_Log_Stdout, UA_LOGCATEGORY_SERVER, "PubSub MQTT Connection creation failed. Out of memory.");
  54. return NULL;
  55. }
  56. /* set default values */
  57. UA_String mqttClientId = UA_STRING("open62541_pub");
  58. memcpy(channelDataMQTT, &(UA_PubSubChannelDataMQTT){address, 2000,2000, NULL, NULL,&mqttClientId, NULL, NULL, NULL}, sizeof(UA_PubSubChannelDataMQTT));
  59. /* iterate over the given KeyValuePair paramters */
  60. UA_String sendBuffer = UA_STRING("sendBufferSize"), recvBuffer = UA_STRING("recvBufferSize"), clientId = UA_STRING("mqttClientId");
  61. for(size_t i = 0; i < connectionConfig->connectionPropertiesSize; i++){
  62. if(UA_String_equal(&connectionConfig->connectionProperties[i].key.name, &sendBuffer)){
  63. if(UA_Variant_hasScalarType(&connectionConfig->connectionProperties[i].value, &UA_TYPES[UA_TYPES_UINT32])){
  64. channelDataMQTT->mqttSendBufferSize = *(UA_UInt32 *) connectionConfig->connectionProperties[i].value.data;
  65. }
  66. } else if(UA_String_equal(&connectionConfig->connectionProperties[i].key.name, &recvBuffer)){
  67. if(UA_Variant_hasScalarType(&connectionConfig->connectionProperties[i].value, &UA_TYPES[UA_TYPES_UINT32])){
  68. channelDataMQTT->mqttRecvBufferSize = *(UA_UInt32 *) connectionConfig->connectionProperties[i].value.data;
  69. }
  70. } else if(UA_String_equal(&connectionConfig->connectionProperties[i].key.name, &clientId)){
  71. if(UA_Variant_hasScalarType(&connectionConfig->connectionProperties[i].value, &UA_TYPES[UA_TYPES_STRING])){
  72. channelDataMQTT->mqttClientId = (UA_String *) connectionConfig->connectionProperties[i].value.data;
  73. }
  74. } else {
  75. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_SERVER, "PubSub MQTT Connection creation. Unknown connection parameter.");
  76. }
  77. }
  78. /* Create a new channel */
  79. UA_PubSubChannel *newChannel = (UA_PubSubChannel *) UA_calloc(1, sizeof(UA_PubSubChannel));
  80. if(!newChannel){
  81. UA_LOG_ERROR(UA_Log_Stdout, UA_LOGCATEGORY_SERVER, "PubSub MQTT Connection creation failed. Out of memory.");
  82. UA_free(channelDataMQTT);
  83. return NULL;
  84. }
  85. /* Allocate memory for mqtt receive buffer */
  86. if(channelDataMQTT->mqttRecvBufferSize > 0){
  87. channelDataMQTT->mqttRecvBuffer = (uint8_t*)UA_calloc(channelDataMQTT->mqttRecvBufferSize, sizeof(uint8_t));
  88. if(channelDataMQTT->mqttRecvBuffer == NULL){
  89. UA_free(channelDataMQTT);
  90. UA_free(newChannel);
  91. return NULL;
  92. }
  93. }
  94. /* Allocate memory for mqtt send buffer */
  95. if(channelDataMQTT->mqttSendBufferSize > 0){
  96. channelDataMQTT->mqttSendBuffer = (uint8_t*)UA_calloc(channelDataMQTT->mqttSendBufferSize, sizeof(uint8_t));
  97. if(channelDataMQTT->mqttSendBuffer == NULL){
  98. if(channelDataMQTT->mqttRecvBufferSize > 0){
  99. UA_free(channelDataMQTT->mqttRecvBuffer);
  100. }
  101. UA_free(channelDataMQTT);
  102. UA_free(newChannel);
  103. return NULL;
  104. }
  105. }
  106. /*link channel and internal channel data*/
  107. newChannel->handle = channelDataMQTT;
  108. /* MQTT Client connect call. */
  109. UA_StatusCode ret = connectMqtt(channelDataMQTT);
  110. if(ret != UA_STATUSCODE_GOOD){
  111. /* try to disconnect tcp */
  112. disconnectMqtt(channelDataMQTT);
  113. UA_free(channelDataMQTT->mqttSendBuffer);
  114. UA_free(channelDataMQTT->mqttRecvBuffer);
  115. UA_free(channelDataMQTT);
  116. UA_free(newChannel);
  117. return NULL;
  118. }
  119. newChannel->state = UA_PUBSUB_CHANNEL_RDY;
  120. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_SERVER, "PubSub MQTT Connection established.");
  121. return newChannel;
  122. }
  123. /**
  124. * Subscribe to topic specified in brokerTransportSettings->queueName.
  125. *
  126. * @return UA_STATUSCODE_GOOD on success
  127. */
  128. static UA_StatusCode
  129. UA_PubSubChannelMQTT_regist(UA_PubSubChannel *channel, UA_ExtensionObject *transportSettings,
  130. void (*callback)(UA_ByteString *encodedBuffer, UA_ByteString *topic)) {
  131. if(channel->state != UA_PUBSUB_CHANNEL_RDY){
  132. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_SERVER, "PubSub MQTT regist failed. Channel closed.");
  133. return UA_STATUSCODE_BADCONNECTIONCLOSED;
  134. }
  135. UA_PubSubChannelDataMQTT *channelDataMQTT = (UA_PubSubChannelDataMQTT *) channel->handle;
  136. channelDataMQTT->callback = callback;
  137. if(transportSettings != NULL && transportSettings->encoding == UA_EXTENSIONOBJECT_DECODED
  138. && transportSettings->content.decoded.type->typeIndex == UA_TYPES_BROKERWRITERGROUPTRANSPORTDATATYPE){
  139. UA_BrokerWriterGroupTransportDataType *brokerTransportSettings =
  140. (UA_BrokerWriterGroupTransportDataType*)transportSettings->content.decoded.data;
  141. UA_Byte qos = 0;
  142. UA_uaQos_toMqttQos(brokerTransportSettings->requestedDeliveryGuarantee, &qos);
  143. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_SERVER, "PubSub MQTT: register");
  144. return subscribeMqtt(channelDataMQTT, brokerTransportSettings->queueName, qos);
  145. }else{
  146. return UA_STATUSCODE_BADARGUMENTSMISSING;
  147. }
  148. }
  149. /**
  150. * Remove subscription specified in brokerTransportSettings->queueName.
  151. *
  152. * @return UA_STATUSCODE_GOOD on success
  153. */
  154. static UA_StatusCode
  155. UA_PubSubChannelMQTT_unregist(UA_PubSubChannel *channel, UA_ExtensionObject *transportSettings) {
  156. if(channel->state != UA_PUBSUB_CHANNEL_RDY){
  157. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_SERVER, "PubSub MQTT: unregister failed. Channel closed.");
  158. return UA_STATUSCODE_BADCONNECTIONCLOSED;
  159. }
  160. UA_PubSubChannelDataMQTT * channelDataMQTT = (UA_PubSubChannelDataMQTT *) channel->handle;
  161. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_SERVER, "PubSub MQTT: unregister");
  162. if(transportSettings != NULL && transportSettings->encoding == UA_EXTENSIONOBJECT_DECODED
  163. && transportSettings->content.decoded.type->typeIndex == UA_TYPES_BROKERWRITERGROUPTRANSPORTDATATYPE){
  164. UA_BrokerWriterGroupTransportDataType *brokerTransportSettings =
  165. (UA_BrokerWriterGroupTransportDataType*)transportSettings->content.decoded.data;
  166. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_SERVER, "PubSub MQTT: unregister");
  167. return unSubscribeMqtt(channelDataMQTT, brokerTransportSettings->queueName);
  168. }else{
  169. return UA_STATUSCODE_BADARGUMENTSMISSING;
  170. }
  171. }
  172. /**
  173. * Send a message.
  174. *
  175. * @return UA_STATUSCODE_GOOD if success
  176. */
  177. static UA_StatusCode
  178. UA_PubSubChannelMQTT_send(UA_PubSubChannel *channel, UA_ExtensionObject *transportSettings, const UA_ByteString *buf) {
  179. if(channel->state != UA_PUBSUB_CHANNEL_RDY){
  180. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_SERVER, "PubSub MQTT: sending failed. Invalid state.");
  181. return UA_STATUSCODE_BADCONNECTIONCLOSED;
  182. }
  183. UA_PubSubChannelDataMQTT *channelDataMQTT = (UA_PubSubChannelDataMQTT *) channel->handle;
  184. UA_StatusCode ret = UA_STATUSCODE_GOOD;
  185. UA_Byte qos = 0;
  186. if(transportSettings != NULL && transportSettings->encoding == UA_EXTENSIONOBJECT_DECODED
  187. && transportSettings->content.decoded.type->typeIndex == UA_TYPES_BROKERWRITERGROUPTRANSPORTDATATYPE){
  188. UA_BrokerWriterGroupTransportDataType *brokerTransportSettings = (UA_BrokerWriterGroupTransportDataType*)transportSettings->content.decoded.data;
  189. UA_uaQos_toMqttQos(brokerTransportSettings->requestedDeliveryGuarantee, &qos);
  190. UA_String topic;
  191. topic = brokerTransportSettings->queueName;
  192. ret = publishMqtt(channelDataMQTT, topic, buf, qos);
  193. if(ret){
  194. channel->state = UA_PUBSUB_CHANNEL_ERROR;
  195. UA_LOG_ERROR(UA_Log_Stdout, UA_LOGCATEGORY_SERVER, "PubSub MQTT: Publish failed");
  196. }else{
  197. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_SERVER, "PubSub MQTT: Publish");
  198. }
  199. }else{
  200. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_SERVER, "PubSub MQTT: Transport settings not found.");
  201. }
  202. return ret;
  203. }
  204. /**
  205. * Close channel and free the channel data.
  206. *
  207. * @return UA_STATUSCODE_GOOD if success
  208. */
  209. static UA_StatusCode
  210. UA_PubSubChannelMQTT_close(UA_PubSubChannel *channel) {
  211. /* already closed */
  212. if(channel->state == UA_PUBSUB_CHANNEL_CLOSED)
  213. return UA_STATUSCODE_GOOD;
  214. UA_PubSubChannelDataMQTT *channelDataMQTT = (UA_PubSubChannelDataMQTT *) channel->handle;
  215. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_SERVER, "PubSub MQTT: Closing PubSubChannel.");
  216. disconnectMqtt(channelDataMQTT);
  217. UA_free(channelDataMQTT);
  218. UA_free(channel);
  219. return UA_STATUSCODE_GOOD;
  220. }
  221. /**
  222. * Calls the send and receive functions of the mqtt network stack.
  223. *
  224. * @return UA_STATUSCODE_GOOD if success
  225. */
  226. static UA_StatusCode
  227. UA_PubSubChannelMQTT_yield(UA_PubSubChannel *channel, UA_UInt16 timeout){
  228. UA_StatusCode ret = UA_STATUSCODE_BADINVALIDARGUMENT;
  229. if(channel == NULL){
  230. return ret;
  231. }
  232. if(channel->state == UA_PUBSUB_CHANNEL_ERROR){
  233. return UA_STATUSCODE_BADINTERNALERROR;
  234. }
  235. UA_PubSubChannelDataMQTT *channelDataMQTT = (UA_PubSubChannelDataMQTT *) channel->handle;
  236. ret = yieldMqtt(channelDataMQTT, timeout);
  237. if(ret != UA_STATUSCODE_GOOD){
  238. channel->state = UA_PUBSUB_CHANNEL_ERROR;
  239. return ret;
  240. }
  241. return ret;
  242. }
  243. /**
  244. * Generate a new MQTT channel. Based on the given configuration. Uses yield and no recv call.
  245. *
  246. * @param connectionConfig connection configuration
  247. * @return ref to created channel, NULL on error
  248. */
  249. static UA_PubSubChannel *
  250. TransportLayerMQTT_addChannel(UA_PubSubConnectionConfig *connectionConfig) {
  251. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_USERLAND, "PubSub MQTT: channel requested.");
  252. UA_PubSubChannel * pubSubChannel = UA_PubSubChannelMQTT_open(connectionConfig);
  253. if(pubSubChannel){
  254. pubSubChannel->regist = UA_PubSubChannelMQTT_regist;
  255. pubSubChannel->unregist = UA_PubSubChannelMQTT_unregist;
  256. pubSubChannel->send = UA_PubSubChannelMQTT_send;
  257. pubSubChannel->close = UA_PubSubChannelMQTT_close;
  258. pubSubChannel->yield = UA_PubSubChannelMQTT_yield;
  259. pubSubChannel->connectionConfig = connectionConfig;
  260. }
  261. return pubSubChannel;
  262. }
  263. //MQTT channel factory
  264. UA_PubSubTransportLayer
  265. UA_PubSubTransportLayerMQTT(){
  266. UA_PubSubTransportLayer pubSubTransportLayer;
  267. pubSubTransportLayer.transportProfileUri = UA_STRING("http://opcfoundation.org/UA-Profile/Transport/pubsub-mqtt");
  268. pubSubTransportLayer.createPubSubChannel = &TransportLayerMQTT_addChannel;
  269. return pubSubTransportLayer;
  270. }
  271. #undef _POSIX_C_SOURCE