繁体   English   中英

在使用带有树莓派的 Mqtt 协议时,我没有在 iOS 上收到回复消息

[英]I'm not receiving a message back on iOS while using Mqtt protocol with raspberry pi

我正在尝试将数据从 RPI 发送到 iOS 应用程序,该消息显示在 RPI 上,但不在 iOS 中

//this is the code on RPI
import paho.mqtt.client as MQTT
def connectionStatus(client, userdata, flag, rc):
print("Connecting...")
mqttClient.subscribe("rpi/hello")
def messageDecoder(client, userdata, msg):
message = msg.payload.decode(encoding='UTF-8')
 if message == "this is iPhone":
    print("Sending reply...")
    mqttClient.publish("rpi/world", "this is 3b+")
 clientName = "Pi"
 serverAddress = "192.168.1.101"
mqttClient = MQTT.Client(clientName)
mqttClient.on_connect = connectionStatus
mqttClient.on_message = messageDecoder
mqttClient.connect(serverAddress)
mqttClient.loop_forever()

这里和 swift 上的代码我在这里尝试了很多方法,有人可以帮我解决这个问题!

import UIKit
import CocoaMQTT
protocol didReceiveMessageDelegate {
func setMessage(message: String)}
class ViewController: UIViewController {

let mqttClient = CocoaMQTT(clientID: "iOS Device", host: "192.168.1.101", port: 1883)

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}


@IBAction func connect(_ sender: UIButton) {
    mqttClient.connect()
}


@IBAction func disconnect(_ sender: UIButton) {
    mqttClient.disconnect()
}

@IBOutlet weak var labelshow: UILabel!

@IBAction func send(_ sender: UIButton) {
    mqttClient.publish("rpi/hello", withString: "this is iphone")
    mqttClient.subscribe("rpi/world")

          }

func mqtt(_ mqtt: CocoaMQTT, didReceiveMessage message: CocoaMQTTMessage, id: UInt16 ) {
    let messageDecoded = String(bytes: message.payload, encoding: .utf8)
    print("Did receive a message: \(messageDecoded!)")
 }

func setMessage(message: String) {
    labelshow.text = message}


}

您需要将视图 controller 设置为 MQTT 客户端的delegate ,否则不会调用didReceiveMessage委托 function。

您需要 state 使您的 class 符合CocoaMQTTDelegate然后分配委托

class ViewController: UIViewController, CocoaMQTTDelegate {


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.mqttClient.delegate = self
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM