element14 Community
element14 Community
    Register Log In
  • Site
  • Search
  • Log In Register
  • About Us
  • Community Hub
    Community Hub
    • What's New on element14
    • Feedback and Support
    • Benefits of Membership
    • Personal Blogs
    • Members Area
    • Achievement Levels
  • Learn
    Learn
    • Ask an Expert
    • eBooks
    • element14 presents
    • Learning Center
    • Tech Spotlight
    • STEM Academy
    • Webinars, Training and Events
    • Learning Groups
  • Technologies
    Technologies
    • 3D Printing
    • FPGA
    • Industrial Automation
    • Internet of Things
    • Power & Energy
    • Sensors
    • Technology Groups
  • Challenges & Projects
    Challenges & Projects
    • Design Challenges
    • element14 presents Projects
    • Project14
    • Arduino Projects
    • Raspberry Pi Projects
    • Project Groups
  • Products
    Products
    • Arduino
    • Avnet Boards Community
    • Dev Tools
    • Manufacturers
    • Multicomp Pro
    • Product Groups
    • Raspberry Pi
    • RoadTests & Reviews
  • Store
    Store
    • Visit Your Store
    • Choose another store...
      • Europe
      •  Austria (German)
      •  Belgium (Dutch, French)
      •  Bulgaria (Bulgarian)
      •  Czech Republic (Czech)
      •  Denmark (Danish)
      •  Estonia (Estonian)
      •  Finland (Finnish)
      •  France (French)
      •  Germany (German)
      •  Hungary (Hungarian)
      •  Ireland
      •  Israel
      •  Italy (Italian)
      •  Latvia (Latvian)
      •  
      •  Lithuania (Lithuanian)
      •  Netherlands (Dutch)
      •  Norway (Norwegian)
      •  Poland (Polish)
      •  Portugal (Portuguese)
      •  Romania (Romanian)
      •  Russia (Russian)
      •  Slovakia (Slovak)
      •  Slovenia (Slovenian)
      •  Spain (Spanish)
      •  Sweden (Swedish)
      •  Switzerland(German, French)
      •  Turkey (Turkish)
      •  United Kingdom
      • Asia Pacific
      •  Australia
      •  China
      •  Hong Kong
      •  India
      •  Korea (Korean)
      •  Malaysia
      •  New Zealand
      •  Philippines
      •  Singapore
      •  Taiwan
      •  Thailand (Thai)
      • Americas
      •  Brazil (Portuguese)
      •  Canada
      •  Mexico (Spanish)
      •  United States
      Can't find the country/region you're looking for? Visit our export site or find a local distributor.
  • Translate
  • Profile
  • Settings
Pi IoT
  • Challenges & Projects
  • Design Challenges
  • Pi IoT
  • More
  • Cancel
Pi IoT
Blog [Pi IoT] Thuis #10: MQTT User Interface components for iOS
  • Blog
  • Forum
  • Documents
  • Polls
  • Files
  • Events
  • Mentions
  • Sub-Groups
  • Tags
  • More
  • Cancel
  • New
  • Share
  • More
  • Cancel
Group Actions
  • Group RSS
  • More
  • Cancel
Engagement
  • Author Author: rhe123
  • Date Created: 11 Aug 2016 12:34 PM Date Created
  • Views 1789 views
  • Likes 5 likes
  • Comments 9 comments
  • user-interface
  • uikit
  • piiot
  • winners
  • ios
  • swift
  • thuis
Related
Recommended

[Pi IoT] Thuis #10: MQTT User Interface components for iOS

rhe123
rhe123
11 Aug 2016

How useful would a home automation system be where you could only interact through MQTT messages? Not very, so that's why we'll start working on the User Interface today. The goal is to create some generic UI elements, which can be linked to the MQTT topic. The element will display the current status clearly and will let the user interact with it.

 

For now there will be three types of UI elements, which can be placed in a grid of tiles. These elements are:

  • Button – a simple push button. The background visualizes the state and tapping it will toggle the state.
  • Slider – a slider to be used for e.g. a dimmer module. The position on the slider shows the current state. Minimum and maximum values can be defined.
  • Info – a tile without any interaction. Just displays the current state of for example the temperature.

Each tile can have some properties defining how it looks. Options include a title, an icon, a value and the selected state.

 

ps: if you're familiar with Swift and UIKit, you might notice that – for the purpose of learning – I'm using Swift 3 and iOS 10. They are still in beta and will be available in fall.

 

MQTT Client

Before we can define the UI elements, we need a connection to MQTT. For this we'll use Moscapsule, a MQTT library written in Swift. Making a connection is quite simple. We do this by creating a configuration, adding some callback blocks and opening the connection:

import Moscapsule

class MQTT {

    var mqttClient: MQTTClient?

    init() {
        let mqttConfig = MQTTConfig(
            clientId: "iOS" + UIDevice.current().identifierForVendor!.uuidString,
            host: "thuis-server-core.internal.thuisapp.com",
            port: 1883,
            keepAlive: 60
        )

        mqttConfig.onMessageCallback = { message in
            print("Message received on \(message.topic): \(message.payloadString)")
        }
        
        mqttConfig.onConnectCallback = { returnCode in
            print("MQTT connected")
        }       

        var mqttClient = Moscapsule.MQTT.newConnection(mqttConfig)
    }
}

 

As you can see we don't do anything yet in the callbacks, except for logging. We'll arrange that later; let's firstly create the UI elements themselves.

 

Tiles: data model

All types of tiles share some attributes. One of these is an array of MQTT topics to which this tile will be subscribed. The common attributes are defined in the base class Tile, including an enum for annotating topics and a protocol for making a tile selectable:

class Tile {
    let title: String
    var icon: UIImage?
    var value: String?

    let topics: [TopicType: String]

    init(title: String, icon: UIImage, topics: [TopicType: String]) { ... }
    convenience init(title: String, icon: ionicon, topics: [TopicType: String]) { ... }
}

enum TopicType {
    case status
    case set
    case icon
}

protocol Selectable {
    var isSelected: Bool { get set }
}

 

For each type of Tile a subclass exists. They describe any additional properties needed, plus they define what happens when a MQTT message is received. Let's take the button as an example:

class ButtonTile: Tile, Selectable, MQTTSubscriber {
    var isSelected = false

    init(title: String, icon: UIImage, topic: String) {
        var topics = [TopicType: String]()
        topics[.status] = topic
        topics[.set] = "\(topic)/set"
        
        super.init(title: title, icon: icon, topics: topics)
    }

    convenience init(title: String, icon: ionicon, topic: String) {
        self.init(title: title, icon: UIImage.imageWithIonicon(icon, color: UIColor.black, iconSize: 42, imageSize: CGSize(width: 45, height: 45)), topic: topic)
    }

    func didReceiveMessage(_ message: MQTTMessage) {
        if topics.values.contains(message.topic) {
            switch (message.payloadString) {
            case .some("on"):
                isSelected = true
                break;
            case .some("off"):
                isSelected = false
                break;
            default:
                print("Received invalid message for topic '\(message.topic)': \(message.payloadString)")
            }
        }
    }
}

 

User Interface

The model doesn't say anything about how the tile will look on screen, it just focusses on managing the status. So what about the UI? For that we use the TileCollectionViewCell, which is a subclass of UICollectionViewCell. It is defined using a nib-file and structured by using Stackviews:

image

 

The corresponding class is a simple subclass of UICollectionViewCell which takes care of the border radius and hides the value label if there is no text defined (due to the Stackview that results in the icon being centered above the title). The heavy lifting happens in the TilesViewController, which is a UICollectionViewController. It has a property to hold a list of Tile objects. To high light a few parts: in viewDidLoad all tiles are subscribed to their respective MQTT topics:

override func viewDidLoad() {
    super.viewDidLoad()
    ...

    // Subscribe tiles to MQTT topics
    for tile in tiles where tile as? MQTTSubscriber != nil {
        for (type, topic) in tile.topics where type != .set {
            MQTT.sharedInstance.subscribe(topic, subscriber: tile as! MQTTSubscriber)
            MQTT.sharedInstance.subscribe(topic, subscriber: self)
        }
    }
}

 

It also subscribes itself to the same topic, so it can reload the UI when new messages are coming in:

extension TilesCollectionViewController: MQTTSubscriber {
    func didReceiveMessage(_ message: MQTTMessage) {
        DispatchQueue.main.async {
            self.collectionView!.reloadData()
        }
    }
}

 

The only part missing is the interaction. When you select one of the cells it will publish a message to the defined 'set'-topic and update the internal state of the tile:

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let tile = tiles[indexPath.row]
    guard var selectable = tile as? Selectable else {
        return;
    }

    selectable.isSelected = !(selectable.isSelected)
    if let topic = tile.topics[.set] {
        let payloadString = selectable.isSelected ? "on" : "off"
        MQTT.sharedInstance.publish(payloadString, topic: topic, retain: false)
    }
    collectionView.reloadItems(at: [indexPath])
}

 

Putting it together

To put it together we create multiple instances of the TilesCollectionViewController and add them to a UITabBarController. Each instances overrides a single method defining the tiles. For the icons we use a library which enables us to use IonIcons instead of images. The home screen displays the most-used tiles:

class HomeViewController: TilesCollectionViewController {
    override func initTiles() -> [Tile] {
        return [
            InfoTile(title: "Indoor", icon: .Thermometer, topics: [.status: "Thuis/weatherIndoor/temperature", .icon: "Thuis/weatherIndoor/icon"]),
            InfoTile(title: "Weather", icon: .Thermometer, topics: [.status: "Thuis/weather/temperature", .icon: "Thuis/weather/icon"]),
            ButtonTile(title: "Home Theater", icon: .FilmMarker, topic: "Thuis/scene/homeTheater"),
            ButtonTile(title: "YouTube", icon: .SocialYoutube, topic: "Thuis/scene/youTube"),
            ButtonTile(title: "Mood", icon: .Flame, topic: "Thuis/scene/mood"),
            ButtonTile(title: "Radio", icon: .MusicNote, topic: "Thuis/scene/radio")
        ]
    }
}

 

This brings us the result of this blog post: a working iPhone app which communicates with Thuis through MQTT.

image

 

When messages arrive on the status-topics, the selected-status of the button-tiles and the value of the info-tiles are updated. When one of the button-tiles is tapped a message is send to the set-topic with the new status. As described in Publishing activity from Z-Way to MQTT this is already picked up and executed.

 

You probably do notice that it looks very plain yet: we'll fix this in a next blog post. We'll also add some more controls, like slider, which can be used for dimmers and a volume control.

 

ps: greetings from sunny and warm Bulgaria image

  • Sign in to reply

Top Comments

  • rhe123
    rhe123 over 8 years ago in reply to Robert Peter Oakes +4
    Ah, note the word ' only' here. MQTT is great as the central communication channel and a great way to connect your UI with the controller, however just on its own it's not great as a user interface. This…
  • rhe123
    rhe123 over 9 years ago in reply to fvan +2
    Pleasure, two weeks of holiday on the coast! For Thuis not too efficient, but I can quite easily do some work on the iOS part. Installed a local Mosquitto broker on my MacBook, so I can emulate the rest…
  • fvan
    fvan over 9 years ago +1
    Enjoy Bulgaria! Trip for pleasure or for work?
Parents
  • Robert Peter Oakes
    Robert Peter Oakes over 8 years ago

    i would like to understand why you think MQTT is not a good choice, I know of many successful project that are centered on MQTT and used for home of office / industrial automation. it is easy to have edge devices use it and integrate with a central controller based on Node-Red for instance (Though there are many other choices). The phone apps can also leverage MQTT if needed to grab data and display or change values

    • Cancel
    • Vote Up +1 Vote Down
    • Sign in to reply
    • More
    • Cancel
  • rhe123
    rhe123 over 8 years ago in reply to Robert Peter Oakes

    Hi Robert Peter Oakes, I'm not sure which comment you're referring to. I'm at least very much in favor of using MQTT!

    • Cancel
    • Vote Up +1 Vote Down
    • Sign in to reply
    • More
    • Cancel
  • Robert Peter Oakes
    Robert Peter Oakes over 8 years ago in reply to rhe123

    This

     

    How useful would a home automation system be where you could only interact through MQTT messages? Not very

     

    Gave me that impression ?

     

    Regards

    Peter

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • More
    • Cancel
  • rhe123
    rhe123 over 8 years ago in reply to Robert Peter Oakes

    Ah, note the word 'only' here. MQTT is great as the central communication channel and a great way to connect your UI with the controller, however just on its own it's not great as a user interface. image This blog is about creating user interface components which are usable for a human being, but which communicate with the rest of the system through MQTT messages.

    • Cancel
    • Vote Up +4 Vote Down
    • Sign in to reply
    • More
    • Cancel
Comment
  • rhe123
    rhe123 over 8 years ago in reply to Robert Peter Oakes

    Ah, note the word 'only' here. MQTT is great as the central communication channel and a great way to connect your UI with the controller, however just on its own it's not great as a user interface. image This blog is about creating user interface components which are usable for a human being, but which communicate with the rest of the system through MQTT messages.

    • Cancel
    • Vote Up +4 Vote Down
    • Sign in to reply
    • More
    • Cancel
Children
No Data
element14 Community

element14 is the first online community specifically for engineers. Connect with your peers and get expert answers to your questions.

  • Members
  • Learn
  • Technologies
  • Challenges & Projects
  • Products
  • Store
  • About Us
  • Feedback & Support
  • FAQs
  • Terms of Use
  • Privacy Policy
  • Legal and Copyright Notices
  • Sitemap
  • Cookies

An Avnet Company © 2025 Premier Farnell Limited. All Rights Reserved.

Premier Farnell Ltd, registered in England and Wales (no 00876412), registered office: Farnell House, Forge Lane, Leeds LS12 2NE.

ICP 备案号 10220084.

Follow element14

  • X
  • Facebook
  • linkedin
  • YouTube