@@ -1062,36 +1062,40 @@ proc connectBroker(ctx: MqttCtx) {.async.} =
10621062
10631063 if ctx.verbosity >= 1 :
10641064 ctx.dbg " Connecting to " & ctx.host & " :" & $ ctx.port
1065- try :
1066- ctx.s = await asyncnet.dial (ctx.host, ctx.port)
1067- if ctx.sslOn:
1068- when defined (ssl):
1069- ctx.ssl = newContext (protSSLv23, CVerifyNone , ctx.sslCert, ctx.sslKey)
1070- wrapConnectedSocket (ctx.ssl, ctx.s, handshakeAsClient)
1071- else :
1072- ctx.wrn " Requested SSL session but ssl is not enabled"
1073- await ctx.close (" SSL not enabled" )
1074- ctx.state = Error
1075- let ok = await ctx.sendConnect ()
1076- if ok:
1077- asyncCheck ctx.runRx ()
1078- asyncCheck ctx.runPing ()
1079- except OSError as e:
1080- if ctx.verbosity >= 1 or not ctx.beenConnected:
1081- ctx.dbg " Error connecting to " & ctx.host
1082- if ctx.verbosity >= 2 :
1083- echo e.msg
1084- ctx.state = Error
1065+
1066+ ctx.state = Error # set to Connecting by sendConnect
1067+
1068+ ctx.s = await asyncnet.dial (ctx.host, ctx.port)
1069+ if ctx.sslOn:
1070+ when defined (ssl):
1071+ ctx.ssl = newContext (protSSLv23, CVerifyNone , ctx.sslCert, ctx.sslKey)
1072+ wrapConnectedSocket (ctx.ssl, ctx.s, handshakeAsClient)
1073+ else :
1074+ ctx.wrn " Requested SSL session but ssl is not enabled"
1075+ await ctx.close (" SSL not enabled" )
1076+
1077+ let ok = await ctx.sendConnect ()
1078+ if ok:
1079+ asyncCheck ctx.runRx ()
1080+ asyncCheck ctx.runPing ()
1081+
10851082
10861083proc runConnect (ctx: MqttCtx ) {.async .} =
10871084 # # Auto-connect and reconnect to broker
1088- await ctx.connectBroker ()
10891085
10901086 while true :
10911087 if ctx.state == Disabled :
10921088 break
10931089 elif ctx.state in [Disconnected , Error ]:
1094- await ctx.connectBroker ()
1090+ try :
1091+ await ctx.connectBroker ()
1092+ except OSError as e:
1093+ if ctx.verbosity >= 1 or not ctx.beenConnected:
1094+ ctx.dbg " Error connecting to " & ctx.host
1095+ if ctx.verbosity >= 2 :
1096+ echo e.msg
1097+ ctx.state = Error
1098+
10951099 # If the client has been disconnect, it is necessary to tell the broker,
10961100 # that we still want to be Subscribed. PubCallbacks still holds the
10971101 # callbacks, but we need to re-Subscribe to the broker.
@@ -1111,7 +1115,7 @@ proc runConnect(ctx: MqttCtx) {.async.} =
11111115
11121116proc newMqttCtx * (clientId: string ): MqttCtx =
11131117 # # Initiate a new MQTT client
1114- MqttCtx (clientId: clientId)
1118+ MqttCtx (clientId: clientId, state: Disconnected )
11151119
11161120proc set_ping_interval * (ctx: MqttCtx , txInterval: int = 60 ) =
11171121 # # Set the clients ping interval in seconds. Default is 60 seconds.
0 commit comments