autobahn
Posts: 2
Joined: Sun Aug 05, 2018 9:00 am

Re: [GUIDE] Communicate between iOS and Raspberry Pi using MQTT

Sun Aug 05, 2018 9:14 am

Thanks for a great tutorial, got the led blinking from my iPhone!

I already have DHT11 temperature sensor connected to my rpi and tried to read the CocoaMQTT documentation about receiving messages but as I'm still a noob :geek: in swift I'd appreciate any suggestions to make iOS device to receive messages from MQTT server too as some other forum members have requested here also.

autobahn
Posts: 2
Joined: Sun Aug 05, 2018 9:00 am

Re: [GUIDE] Communicate between iOS and Raspberry Pi using MQTT

Mon Aug 06, 2018 5:32 pm

autobahn wrote:
Sun Aug 05, 2018 9:14 am
Thanks for a great tutorial, got the led blinking from my iPhone!

I already have DHT11 temperature sensor connected to my rpi and tried to read the CocoaMQTT documentation about receiving messages but as I'm still a noob :geek: in swift I'd appreciate any suggestions to make iOS device to receive messages from MQTT server too as some other forum members have requested here also.
I figured it out myself. To let you roast my code or just to help other noobs, I post it here:

ViewController Class

Code: Select all

import UIKit

class ViewController: UIViewController, didReceiveMessageDelegate {
    @IBOutlet weak var temperatureLabel: UILabel!
    
    let mqtt = MQTT()
    
    func setMessage(message: String) {
        temperatureLabel.text = message
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        mqtt.delegate = self
        let notificationCenter = NotificationCenter.default
        notificationCenter.addObserver(self, selector: #selector(appMovedToBackground), name: Notification.Name.UIApplicationWillResignActive, object: nil)
        notificationCenter.addObserver(self, selector: #selector(appMovedToForeground), name: Notification.Name.UIApplicationWillEnterForeground, object: nil)
        
        mqtt.connect()
    }
    
    @objc func appMovedToBackground() {
        print("App moved to background. Disconnecting.")
        mqtt.disconnect()
    }

    @objc func appMovedToForeground() {
        print("App moved to foreground. Connecting...")
        mqtt.connect()
    }
    @IBAction func ledSwitch(_ sender: UISwitch) {
        if sender.isOn {
            mqtt.publish(topic: "rpi/GPIO", message: "on")
        }
        else {
            mqtt.publish(topic: "rpi/GPIO", message: "off")
        }
    }
}
MQTT class

Code: Select all

import Foundation
import CocoaMQTT

protocol didReceiveMessageDelegate {
    func setMessage(message: String)
}

class MQTT: CocoaMQTTDelegate {
    
    var delegate: didReceiveMessageDelegate?
    let mqttClient = CocoaMQTT(clientID: "iOS Device", host: "192.168.1.111", port: 1883)
    
    func connect() {
        mqttClient.delegate = self
        mqttClient.connect()
        print("Connecting...")
    }
    
    func disconnect() {
        mqttClient.disconnect()
        print("Disconnected")
    }
    
    func publish(topic: String, message: String) {
        mqttClient.publish(topic, withString: message)
    }
    
    func mqtt(_ mqtt: CocoaMQTT, didConnectAck ack: CocoaMQTTConnAck) {
        print("Connected")
        mqttClient.subscribe("rpi/DHT")
    }
    
    func mqtt(_ mqtt: CocoaMQTT, didPublishMessage message: CocoaMQTTMessage, id: UInt16) {
        
    }
    
    func mqtt(_ mqtt: CocoaMQTT, didPublishAck id: UInt16) {
        
    }
    
    func mqtt(_ mqtt: CocoaMQTT, didReceiveMessage message: CocoaMQTTMessage, id: UInt16) {
        let messageDecoded = String(bytes: message.payload, encoding: .utf8)
        print("Did receive a message: \(messageDecoded!)")
        delegate?.setMessage(message: "\(messageDecoded!) ºC")
        
    }
    
    func mqtt(_ mqtt: CocoaMQTT, didSubscribeTopic topic: String) {
        print("Did subscribe to \(topic)")
    }
    
    func mqtt(_ mqtt: CocoaMQTT, didUnsubscribeTopic topic: String) {
        
    }
    
    func mqttDidPing(_ mqtt: CocoaMQTT) {
        
    }
    
    func mqttDidReceivePong(_ mqtt: CocoaMQTT) {

    }
    
    func mqttDidDisconnect(_ mqtt: CocoaMQTT, withError err: Error?) {
        
    }
}

krishdhar
Posts: 2
Joined: Wed Jul 25, 2018 10:26 pm

Re: [GUIDE] Communicate between iOS and Raspberry Pi using MQTT

Fri Aug 10, 2018 7:02 pm

Hi, thank you for the great tutorial

I am having trouble with one part
No matter what I do, it still says that there is an error with me importing CocoaMQTT and the build doesn't work
I have reinstalled cocoapods and even restarted my entire app and I haven't found any errors

Can anybody please help

Basouel
Posts: 1
Joined: Sat Sep 15, 2018 4:01 pm

Re: [GUIDE] Communicate between iOS and Raspberry Pi using MQTT

Sat Sep 15, 2018 4:16 pm

Hi,

Thanks a lot for that tutorial, really easy to follow and complete every steps.

My project is a bit different, I use all of that to control my camera from my phone and so far I managed to adapt all of that for it.
Now I would like it to work outside and it’s where I’m a bit stuck. I though that it could work if i just share the connexion from my phone, set the pi to connect automatically to it, change the IP address (for the app and for the python script) to the one used by the pi when connected to my phone, but the all server is now not working. The connect button doesn’t do anything with that so I wonder why and if you guys could know a solution.
(The IP address given by my phone is starting with 172.XXX.XX.XX)

Thanks

charbelsalloum
Posts: 1
Joined: Sat Oct 06, 2018 6:16 pm

Re: [GUIDE] Communicate between iOS and Raspberry Pi using MQTT

Sat Oct 06, 2018 6:20 pm

If we have two iOS devices connected, and one user changed the state of a pin will the state of the switch on the second iOS device changes too ?

informed
Posts: 128
Joined: Mon Oct 26, 2015 6:24 pm

Re: [GUIDE] Communicate between iOS and Raspberry Pi using MQTT

Wed Nov 21, 2018 1:08 pm

Hi,

looking to implement something similar using C#.

May I ask before I start to translate on what medium the messages are sent? I mean are you relying on the home users wireless hub to send and receive?

thanks

philip100
Posts: 4
Joined: Fri Feb 01, 2019 4:44 pm

Re: [GUIDE] Communicate between iOS and Raspberry Pi using MQTT

Fri Feb 01, 2019 5:42 pm

Hello :-)

Good job with the tutorial :!:

I'm working on a project where I have to control 2 stepper motors wirelessly using an iPhone app and I'm thinking of implementing MQTT.

I made the app, and as for now, connected it with Pi using BLE. But the latency (as for a "real time" application) is unacceptable.
Sending short command (optimized to be as short as possible, yet still decodable) is not a big deal since it arrives with about 100-200ms latency - acceptable for things like "turn this on" / "turn this off"...
But if I have 100 commands to send within - say - one second (motors speed based on slider position in the app), the bluetooth buffer get stuck and the last command arrives after few seconds. Now imagine thousand commands send within one second :|

So, Before I'll try to implement this, I'd like to ask wheather or not is there any noticeable latency in communication between Pi and iPhone (back and forth) using MQTT? Will it be faster than BLE?

Thanks,
Artur.

mattmiller
Posts: 2116
Joined: Thu Feb 05, 2015 11:25 pm

Re: [GUIDE] Communicate between iOS and Raspberry Pi using MQTT

Fri Feb 01, 2019 6:48 pm

MQTT is not designed for speed or any sort of guaranteed time of delivery of the messages

raymondantoine
Posts: 3
Joined: Sat Feb 02, 2019 6:07 pm

Re: [GUIDE] Communicate between iOS and Raspberry Pi using MQTT

Sat Feb 02, 2019 6:14 pm

GhostRaider wrote:
Sat Jan 20, 2018 12:56 am
axopax wrote:
Sat Jan 20, 2018 12:47 am
Hey,

Thanks for the great tutorial. I just had a few issues I wanted to verify.

After i wrote make in the mosquitto terminal, I got so many warnings. Mainly :

../lib/tls_mosq.c:130:5: warning: ‘ASN1_STRING_data’ is deprecated [-Wdeprecated-declarations]
data = ASN1_STRING_data(nval->d.dNSName);
^~~~

Second, when I added the "mosquitto -v" command, I got :1516409129:

mosquitto version 1.4.14 (build date 2018-01-20 00:39:52+0000) starting
1516409129: Using default config.
1516409129: Opening ipv4 listen socket on port 1883.
1516409129: Error: Address already in use

Could you please help as I am a beginner
Warnings are expected. What matters is whether it runs or not. Normally when you get "Address already in use", it means that Mosquitto is already running. You can restart your Raspberry Pi to start fresh and try "mosquitto -v" again.
I had this problem and honestly, i tried different config, tried rebooting, and disabling mosquitto and set it back up. I read online a lot of people have had problems with the more recent versions. It's been a headscratcher all morning for me. Now for future references, because this guide is awesome, i did manage to make it work, use the following:

Code: Select all

sudo pkill mosquitto
mosquitto -v 
should work now.

philip100
Posts: 4
Joined: Fri Feb 01, 2019 4:44 pm

Re: [GUIDE] Communicate between iOS and Raspberry Pi using MQTT

Sat Feb 02, 2019 8:28 pm

Yeah...
After some lecture and tests, I see I can't rely on MQTT protocol for my purposes (at least not at my stage of understanding the topic)
Too bad, because I thought I could save serial port on my pi and use it to connect arduino.

I'm rethinking my app and I think I found a solution for BLE latency and buffer. I'll use some sort of "prediction". Instead of sending all values, I'll send values periodically based on how fast the user moves a slider. Theoretically, if he moves slider in constant speed, I can actually predict where it will be at a given time and set the acceleration/decceleration programatically. I can put some threshold on the speed changes so it will supress any jerky moves on the slider as well, and make motors speed up/down smoothly, without noticeable latency 8-)

Premature optimization is evil! :twisted:

Thanks!

raymondantoine
Posts: 3
Joined: Sat Feb 02, 2019 6:07 pm

Re: [GUIDE] Communicate between iOS and Raspberry Pi using MQTT

Wed Feb 06, 2019 3:19 pm

Would there be a way to connect to the server from the iOS app without the use of a button?

For example, when the app launches, or whenever it's active the app sends a connect request.
Anyway, for the disconnecting button, I don't see the use either, since shutting the app would close the connection automatically, wouldn't it?

Bear in mind this is my first rapsberry pi and my first program that doesn't just print "Hello world" or plays some random dumb quizz. I do this for fun, so I have no real scholar background in programming.

raymondantoine
Posts: 3
Joined: Sat Feb 02, 2019 6:07 pm

Re: [GUIDE] Communicate between iOS and Raspberry Pi using MQTT

Wed Feb 06, 2019 3:25 pm

philip100 wrote:
Sat Feb 02, 2019 8:28 pm
Yeah...
After some lecture and tests, I see I can't rely on MQTT protocol for my purposes (at least not at my stage of understanding the topic)
Too bad, because I thought I could save serial port on my pi and use it to connect arduino.

I'm rethinking my app and I think I found a solution for BLE latency and buffer. I'll use some sort of "prediction". Instead of sending all values, I'll send values periodically based on how fast the user moves a slider. Theoretically, if he moves slider in constant speed, I can actually predict where it will be at a given time and set the acceleration/decceleration programatically. I can put some threshold on the speed changes so it will supress any jerky moves on the slider as well, and make motors speed up/down smoothly, without noticeable latency 8-)

Premature optimization is evil! :twisted:

Thanks!
Why is that?

I was planning on using the rapsberry pi as a server and the brain for managing an Adruino which has relays and other sorts of electronics connected to it. What is the problem of having serial port on the raspberry pi communicating to the server? Is it JUST latency?

philip100
Posts: 4
Joined: Fri Feb 01, 2019 4:44 pm

Re: [GUIDE] Communicate between iOS and Raspberry Pi using MQTT

Mon Feb 11, 2019 9:26 pm

I was planning the same

But I ended up eliminating raspberry from my setup :(
Even when it comes to BLE communication, arduino is about 20-30% faster, organoleptically.
I was considering raspberry because of "the unlimited possibilities", but it turns out that this "sweetness" is paid by bugs, crashes and error handlings (Try to hookup pi and Arduino with i2c! I did it, but I certainly can't name it as any kind of proper connection :lol: 90% error handling, 10% talking )

If you really need to rely on machine, it cannot be any kind of self-running system, but just a simple microcontroller, which you can hardcode ;)

However, I'm not gonna give up un the good Pi board itself, because it seems that there is to be a tiny light in the tunnel (Ultibo).

mattmiller
Posts: 2116
Joined: Thu Feb 05, 2015 11:25 pm

Re: [GUIDE] Communicate between iOS and Raspberry Pi using MQTT

Mon Feb 11, 2019 9:35 pm

We all have different experiences

I run 6 PiZero around the house all communicating with each other using MQTT. (Controlling Neopixel lights and used as TV remote repeaters)

Like any electronic device some of them go wrong occasionally - others have been running for two years without a single hiccup - which is good as one of them is stuck underneath a plinth in the kitchen :)

philip100
Posts: 4
Joined: Fri Feb 01, 2019 4:44 pm

Re: [GUIDE] Communicate between iOS and Raspberry Pi using MQTT

Mon Feb 11, 2019 9:57 pm

mattmiller wrote:
Mon Feb 11, 2019 9:35 pm
We all have different experiences (...)
100%
Though, we all went through simple "led blink" example :D
It's fun to learn, try new things and understand where they fall at the end

kishant
Posts: 1
Joined: Fri Mar 15, 2019 2:41 pm

Re: [GUIDE] Communicate between iOS and Raspberry Pi using MQTT

Fri Mar 15, 2019 2:48 pm

Thank you for such a wonderful guide.
I am a noob in swift.
I would like to receive messages published by other clients on the IOS app.
It would be great if anyone could share a simple code to receive messages on the app.
I am using this for my project and need to submit it this month.
Please help.

GhostRaider
Posts: 53
Joined: Fri Jan 22, 2016 9:04 pm

Re: [GUIDE] Communicate between iOS and Raspberry Pi using MQTT

Sun Jun 02, 2019 4:05 am

MQTT was mostly designed to be used with an Internet connection. Many applicances use MQTT to transmit small bits of information from one subscriber to another, i.e. a refrigerator telling you the temperature on your iPhone, Android, etc. Most devices use Wi-Fi these days which allows wireless communication from anywhere at any distance.

Of course the Internet might not be available everywhere so the other option is to use a cellular module, or use the Bluetooth protocol. For my personal projects, I don't use Bluetooth other than to use it for wireless audio.

It really depends on the project.
Guides I have created on the Raspberry Pi Forums:

1) [GUIDE] Raspbian Lite with PIXEL/LXDE/XFCE/MATE/Openbox/i3
2) [GUIDE] Communicate between iOS and Raspberry Pi using MQTT

Return to “Automation, sensing and robotics”