Hi there... I have a piece of code that transmits a string via MQTT:
B4X:
Dim m As String = "Test Message"
mqtt.Publish("TextComment", Serializator.ConvertObjectToBytes(m))
And I have a piece of code that responds to this:
B4X:
Private Sub mqtt_MessageArrived (Topic As String, Payload() As Byte)
Log("Message arrived: " & Topic)
Log(BytesToString(Payload, 0, Payload.Length, "utf8"))
End Sub
Problem is, I don't get "Test message" back - I get a load of characters. How do I use the B4XSerializator to send a string and then how do I decode it?
Don't serialize (In B4J/A/i). Use a String's GetBytes method to turn the string into bytes. Then
1) In your first example, BytesToString should work
2) In B4R, just keep it as a byte array (from what I can tell, Strings in B4R are just byte arrays. I'm going from my interpretation of this: https://www.b4x.com/android/forum/threads/strings-and-bytes.66729/)
Note: Looking at the link in #2, looks like unicode is not really supported. So you may consider sticking to ASCII when using GetBytes when creating the byte arrays for B4R and for BytesToString when receiving strings from B4R.
Disclaimer: I have 0 experience with B4R, so all this may just be bah humbug
Private Sub mqtt_MessageArrived (Topic As String, Payload() As Byte)
Dim be(20) As Object 'used as a storage buffer. Can be a global variable
'A Message has been received from the MQTT server
Log("Message Received!!")
Dim MQTTMessagePayload() As Object = Serializator.ConvertBytesToArray(Payload, be)
Dim Message As String = MQTTMessagePayload(0)
Log("MQTT message is: ", Message)
End Sub