{"id":3010,"date":"2016-06-13T06:54:13","date_gmt":"2016-06-13T12:54:13","guid":{"rendered":"http:\/\/dev.iachieved.it\/iachievedit\/?p=3010"},"modified":"2016-06-13T06:54:13","modified_gmt":"2016-06-13T12:54:13","slug":"mqtt-subscriptions-with-swift-on-linux","status":"publish","type":"post","link":"https:\/\/dev.iachieved.it\/iachievedit\/mqtt-subscriptions-with-swift-on-linux\/","title":{"rendered":"Handling MQTT Subscriptions with Swift on Linux"},"content":{"rendered":"<p>In our last <a href=\"http:\/\/dev.iachieved.it\/iachievedit\/mqtt-with-swift-on-linux\/\">post<\/a> we looked at a Swift MQTT client which published information to a <a href=\"http:\/\/www.hivemq.com\">HiveMQ<\/a> broker.  Now let&#8217;s turn our attention to writing an MQTT client that <i>subscribes<\/i> to a topic.<\/p>\n<p>Again, we&#8217;ll be using <a href=\"https:\/\/github.com\/iachievedit\/MQTT\">MQTT<\/a>, code that aims to provide a solid MQTT client library implementation in Swift.  If you haven&#8217;t yet read the <a href=\"http:\/\/dev.iachieved.it\/iachievedit\/mqtt-with-swift-on-linux\/\">tutorial on building an MQTT publisher<\/a> with it, I suggest you do so before proceeding!<\/p>\n<p>There are two basic components to writing an MQTT client that subscribes to a topic:<\/p>\n<ul>\n<li>subscribing to a topic\n<li>handling a published message from the broker\n<\/ul>\n<p>Ignoring the boilerplate connection logic for a moment, let&#8217;s look at subscribing:<\/p>\n<pre class=\"lang:swift\">\n_ = nc.addObserverForName(\"ConnectedNotification\", object:nil, queue:nil) {_ in\n  _ = client.subscribe(topic:\"\/\\(hostname)\/cpu\/temperature\/value\")\n}\n<\/pre>\n<p>There&#8217;s nothing earth shattering here:  upon receiving a <code>ConnectedNotification<\/code> a call is made to subscribe to the topic <code>\/hostname\/cpu\/temperature\/value<\/code> (where <i>hostname<\/i> is obtained from the OS).  Now when the broker receives a message published to this topic it will broadcast it to our client.  This is the <a href=\"https:\/\/en.wikipedia.org\/wiki\/Publish\u2013subscribe_pattern\">pub-sub<\/a> pattern in action.<\/p>\n<h3><a href=\"https:\/\/www.youtube.com\/watch?v=ScJvQhWL7Lg&#038;t=23s\">This Transmission is Coming To You<\/a><\/h3>\n<p>To receive an MQTT message we need to handle the <code>MQTTDelegate<\/code> method <code>func mqtt(mqtt: MQTT, didReceiveMessage message: MQTTMessage, id: UInt16 )<\/code>.  This can be readily accomplished using an <code>NSNotification<\/code> with accompanying <code>userInfo<\/code>:<\/p>\n<pre class=\"lang:swift\">\nfunc mqtt(mqtt: MQTT, didReceiveMessage message: MQTTMessage, id: UInt16 ) {\n  let userInfo:[NSObject:AnyObject] = [\"message\" as NSString:message]\n  NSNotificationCenter.defaultCenter().postNotificationName(\"MessageNotification\",\n                                                             object:nil,\n                                                             userInfo:userInfo)\n    \n}\n<\/pre>\n<p>Unfortunately for us much the <code>userInfo<\/code> dictionary remains grounded in using <code>NSObject<\/code>s as keys, so care must taken to cast <code>String<\/code> as an <code>NSString<\/code> when assembling.<\/p>\n<p>In the <code>main.swift<\/code> implementation we listen for a <code>MessageNotification<\/code>:<\/p>\n<pre class=\"lang:swift\">\n_ = nc.addObserverForName(\"MessageNotification\", object:nil, queue:nil){ notification in\n  if let userInfo = notification.userInfo,\n     let message  = userInfo[\"message\" as NSString] as? MQTTMessage {\n    if let string   = message.string {\n      print(\"Received \\(string) for topic \\(message.topic)\")\n    }\n  }\n}\n<\/pre>\n<p>For details on the <code>MQTTMessage<\/code> class, see <a href=\"https:\/\/github.com\/iachievedit\/MQTT\/blob\/master\/Sources\/MQTTMessage.swift\">the source<\/a>, but we can gather from the above that two properties are of interest here:<\/p>\n<ul>\n<li>`topic:String` &#8211; the topic to which the message was delivered\n<li>`string:String?` &#8211; the message contents, if any, delivered as a `String`\n<\/ul>\n<h3>Get the Code<\/h3>\n<p><a href=\"https:\/\/github.com\/iachievedit\/MQTTSub\">MQTTSub<\/a> is an example implementation of an MQTT client that subscribes to our CPU temperature topic.  Obtain it and compile with:<\/p>\n<pre class=\"crayon:false\">\n# git clone https:\/\/github.com\/iachievedit\/MQTTSub\n# cd MQTTSub\n# swift build\n# .build\/debug\/MQTTSub\n<\/pre>\n<p>You will, of course, want to be running the publishing client as well:<\/p>\n<pre class=\"crayon:false\">\n# git clone https:\/\/github.com\/iachievedit\/PubSysTemp\n# cd PubSysTemp\n# swift build\n# .build\/debug\/PubSysTemp\n<\/pre>\n<p><i>If<\/i> your publishing client is running, you&#8217;ll see something like:<\/p>\n<pre class=\"crayon:false\" style=\"font-size: 9px\">\n2016-06-13 02:55:43 +0000 - INFO    - Connecting to broker\n2016-06-13 02:55:43 +0000 - INFO    - MQTT client has connected to broker.hivemq.com:1883\n2016-06-13 02:55:43 +0000 - INFO    - Subscribe to topic\n2016-06-13 02:55:43 +0000 - INFO    - didConnectAck\n2016-06-13 02:55:43 +0000 - INFO    - didSubscribeTopic \/darthvader\/cpu\/temperature\/value\n2016-06-13 02:55:44 +0000 - INFO    - Received 33.0 for topic \/darthvader\/cpu\/temperature\/value\n<\/pre>\n<p>If you want to have fun, try stress testing your system while running the publisher and subscriber.  After <code>stress -c 8<\/code> was started up:<\/p>\n<p><code>PubSysTemp<\/code><\/p>\n<pre class=\"crayon:false\" style=\"font-size: 9px\">\n2016-06-13 03:04:55 +0000 - INFO    - Published temperature to 34.0\n2016-06-13 03:05:05 +0000 - INFO    - Published temperature to 37.0\n2016-06-13 03:05:15 +0000 - INFO    - Published temperature to 42.0\n2016-06-13 03:05:25 +0000 - INFO    - Published temperature to 45.0\n2016-06-13 03:05:35 +0000 - INFO    - Published temperature to 47.0\n<\/pre>\n<p><code>MQTTSub<\/code><\/p>\n<pre class=\"crayon:false\" style=\"font-size: 9px\">\n2016-06-13 03:04:55 +0000 - INFO    - Received 34.0 for topic \/darthvader\/cpu\/temperature\/value\n2016-06-13 03:05:05 +0000 - INFO    - Received 37.0 for topic \/darthvader\/cpu\/temperature\/value\n2016-06-13 03:05:15 +0000 - INFO    - Received 42.0 for topic \/darthvader\/cpu\/temperature\/value\n2016-06-13 03:05:25 +0000 - INFO    - Received 45.0 for topic \/darthvader\/cpu\/temperature\/value\n2016-06-13 03:05:35 +0000 - INFO    - Received 47.0 for topic \/darthvader\/cpu\/temperature\/value\n<\/pre>\n<h2>What&#8217;s Next?<\/h2>\n<p>If you peruse the MQTT library you&#8217;ll notice it is lacking SSL support.  That&#8217;s what&#8217;s next!  In addition, we&#8217;ll be looking at writing additional MQTT tutorials that explore constructing topic hierarchies, using MQTT with real-world sensors, home automation devices, and more.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In our last post we looked at a Swift MQTT client which published information to a HiveMQ broker. Now let&#8217;s turn our attention to writing an MQTT client that subscribes to a topic. Again, we&#8217;ll be using MQTT, code that aims to provide a solid MQTT client library implementation in Swift. If you haven&#8217;t yet [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":3001,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[19,5],"tags":[30,27,26,29,7],"class_list":["post-3010","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-linux","category-swift","tag-iot","tag-linux","tag-mqtt","tag-mqtt-swift","tag-swift-2"],"_links":{"self":[{"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/posts\/3010"}],"collection":[{"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/comments?post=3010"}],"version-history":[{"count":10,"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/posts\/3010\/revisions"}],"predecessor-version":[{"id":3020,"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/posts\/3010\/revisions\/3020"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/media\/3001"}],"wp:attachment":[{"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/media?parent=3010"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/categories?post=3010"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/tags?post=3010"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}