Я не получаю сообщение на iOS при использовании протокола Mqtt с raspberry pi - PullRequest
0 голосов
/ 08 мая 2020

Я пытаюсь отправить данные из 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}


}

1 Ответ

0 голосов
/ 08 мая 2020

Вам необходимо установить контроллер представления в качестве клиента MQTT delegate, иначе функция делегата didReceiveMessage не будет вызываться.

Вам необходимо указать, что ваш класс соответствует CocoaMQTTDelegate, а затем назначить делегата

class ViewController: UIViewController, CocoaMQTTDelegate {


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.mqttClient.delegate = self
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...