iOS Question iMQTT Connection Error Detection

VTSinLincoln

Member
Licensed User
Longtime User
I have a custom MQTT broker that can reject connection attempts and return specific codes depending on the situation (unknown users, invalid credentials etc). With the Android MQTT library, LastException shows the reason for the rejected connection.

MQTT (B4a) LastExcpection:
(MqttSecurityException) Not authorized to connect (5)

The iMQTT library shows this for a failed connection attempt when I examine LastException:
iMQTT (B4i) LastExcepction:
<B4IExceptionWrapper: (null)>

I can inspect the mqttClient instance in the B4i code with the debugger and I can see a _lastErrorCode field:
iMQTT error code.png


How can I retrieve this information programmatically in B4i?


V
 

VTSinLincoln

Member
Licensed User
Longtime User
After a bit of trial and error, I can now get the connection error code in the connection handler.
Connect Error Code in B4i Connect Handler:
Dim no As NativeObject = mqttClient
Dim noClient As NativeObject = no.GetField("client")
Sleep(0) 'noErrorCode is never initialised otherwise
Dim noErrorCode As NativeObject = noClient.GetField("lastErrorCode")
If noErrorCode.IsInitialized Then
    connectErrCode = noErrorCode.RunMethod("code", Null).AsNumber
    connectErrDesc = noErrorCode.AsString
    Log ($"${connectErrDesc} (${connectErrCode})"$)
End If

I had to split out the client to get it to compile. However, if I chain the GetField methods as in your suggestion, error code is always uninitialised. It was still uninitialsed when split into separate calls. Adding the sleep before getting the error code got a valid value (I only discovered that after changing the code while at a break point - the previously unintialised object returned a value when saved and run). Sleep appears to allow the disconnect handler to run - then I can get a valid code.

Is this an acceptable solution, or is it a bit of a hack?

V
 
Upvote 1
Top