options.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. /*
  2. * Copyright (c) 2013 IBM Corp.
  3. *
  4. * All rights reserved. This program and the accompanying materials
  5. * are made available under the terms of the Eclipse Public License v1.0
  6. * which accompanies this distribution, and is available at
  7. * http://www.eclipse.org/legal/epl-v10.html
  8. *
  9. * Contributors:
  10. * Seth Hoenig
  11. * Allan Stockdill-Mander
  12. * Mike Robertson
  13. */
  14. package mqtt
  15. import (
  16. "crypto/tls"
  17. "net/url"
  18. "time"
  19. )
  20. // MessageHandler is a callback type which can be set to be
  21. // executed upon the arrival of messages published to topics
  22. // to which the client is subscribed.
  23. type MessageHandler func(*Client, Message)
  24. // ConnectionLostHandler is a callback type which can be set to be
  25. // executed upon an unintended disconnection from the MQTT broker.
  26. // Disconnects caused by calling Disconnect or ForceDisconnect will
  27. // not cause an OnConnectionLost callback to execute.
  28. type ConnectionLostHandler func(*Client, error)
  29. // OnConnectHandler is a callback that is called when the client
  30. // state changes from unconnected/disconnected to connected. Both
  31. // at initial connection and on reconnection
  32. type OnConnectHandler func(*Client)
  33. // ClientOptions contains configurable options for an Client.
  34. type ClientOptions struct {
  35. Servers []*url.URL
  36. ClientID string
  37. Username string
  38. Password string
  39. CleanSession bool
  40. Order bool
  41. WillEnabled bool
  42. WillTopic string
  43. WillPayload []byte
  44. WillQos byte
  45. WillRetained bool
  46. ProtocolVersion uint
  47. protocolVersionExplicit bool
  48. TLSConfig tls.Config
  49. KeepAlive time.Duration
  50. ConnectTimeout time.Duration
  51. MaxReconnectInterval time.Duration
  52. AutoReconnect bool
  53. Store Store
  54. DefaultPublishHander MessageHandler
  55. OnConnect OnConnectHandler
  56. OnConnectionLost ConnectionLostHandler
  57. WriteTimeout time.Duration
  58. }
  59. // NewClientOptions will create a new ClientClientOptions type with some
  60. // default values.
  61. // Port: 1883
  62. // CleanSession: True
  63. // Order: True
  64. // KeepAlive: 30 (seconds)
  65. // ConnectTimeout: 30 (seconds)
  66. // MaxReconnectInterval 10 (minutes)
  67. // AutoReconnect: True
  68. func NewClientOptions() *ClientOptions {
  69. o := &ClientOptions{
  70. Servers: nil,
  71. ClientID: "",
  72. Username: "",
  73. Password: "",
  74. CleanSession: true,
  75. Order: true,
  76. WillEnabled: false,
  77. WillTopic: "",
  78. WillPayload: nil,
  79. WillQos: 0,
  80. WillRetained: false,
  81. ProtocolVersion: 0,
  82. protocolVersionExplicit: false,
  83. TLSConfig: tls.Config{},
  84. KeepAlive: 30 * time.Second,
  85. ConnectTimeout: 30 * time.Second,
  86. MaxReconnectInterval: 10 * time.Minute,
  87. AutoReconnect: true,
  88. Store: nil,
  89. OnConnect: nil,
  90. OnConnectionLost: DefaultConnectionLostHandler,
  91. WriteTimeout: 0, // 0 represents timeout disabled
  92. }
  93. return o
  94. }
  95. // AddBroker adds a broker URI to the list of brokers to be used. The format should be
  96. // scheme://host:port
  97. // Where "scheme" is one of "tcp", "ssl", or "ws", "host" is the ip-address (or hostname)
  98. // and "port" is the port on which the broker is accepting connections.
  99. func (o *ClientOptions) AddBroker(server string) *ClientOptions {
  100. brokerURI, _ := url.Parse(server)
  101. o.Servers = append(o.Servers, brokerURI)
  102. return o
  103. }
  104. // SetClientID will set the client id to be used by this client when
  105. // connecting to the MQTT broker. According to the MQTT v3.1 specification,
  106. // a client id mus be no longer than 23 characters.
  107. func (o *ClientOptions) SetClientID(id string) *ClientOptions {
  108. o.ClientID = id
  109. return o
  110. }
  111. // SetUsername will set the username to be used by this client when connecting
  112. // to the MQTT broker. Note: without the use of SSL/TLS, this information will
  113. // be sent in plaintext accross the wire.
  114. func (o *ClientOptions) SetUsername(u string) *ClientOptions {
  115. o.Username = u
  116. return o
  117. }
  118. // SetPassword will set the password to be used by this client when connecting
  119. // to the MQTT broker. Note: without the use of SSL/TLS, this information will
  120. // be sent in plaintext accross the wire.
  121. func (o *ClientOptions) SetPassword(p string) *ClientOptions {
  122. o.Password = p
  123. return o
  124. }
  125. // SetCleanSession will set the "clean session" flag in the connect message
  126. // when this client connects to an MQTT broker. By setting this flag, you are
  127. // indicating that no messages saved by the broker for this client should be
  128. // delivered. Any messages that were going to be sent by this client before
  129. // diconnecting previously but didn't will not be sent upon connecting to the
  130. // broker.
  131. func (o *ClientOptions) SetCleanSession(clean bool) *ClientOptions {
  132. o.CleanSession = clean
  133. return o
  134. }
  135. // SetOrderMatters will set the message routing to guarantee order within
  136. // each QoS level. By default, this value is true. If set to false,
  137. // this flag indicates that messages can be delivered asynchronously
  138. // from the client to the application and possibly arrive out of order.
  139. func (o *ClientOptions) SetOrderMatters(order bool) *ClientOptions {
  140. o.Order = order
  141. return o
  142. }
  143. // SetTLSConfig will set an SSL/TLS configuration to be used when connecting
  144. // to an MQTT broker. Please read the official Go documentation for more
  145. // information.
  146. func (o *ClientOptions) SetTLSConfig(t *tls.Config) *ClientOptions {
  147. o.TLSConfig = *t
  148. return o
  149. }
  150. // SetStore will set the implementation of the Store interface
  151. // used to provide message persistence in cases where QoS levels
  152. // QoS_ONE or QoS_TWO are used. If no store is provided, then the
  153. // client will use MemoryStore by default.
  154. func (o *ClientOptions) SetStore(s Store) *ClientOptions {
  155. o.Store = s
  156. return o
  157. }
  158. // SetKeepAlive will set the amount of time (in seconds) that the client
  159. // should wait before sending a PING request to the broker. This will
  160. // allow the client to know that a connection has not been lost with the
  161. // server.
  162. func (o *ClientOptions) SetKeepAlive(k time.Duration) *ClientOptions {
  163. o.KeepAlive = k
  164. return o
  165. }
  166. // SetProtocolVersion sets the MQTT version to be used to connect to the
  167. // broker. Legitimate values are currently 3 - MQTT 3.1 or 4 - MQTT 3.1.1
  168. func (o *ClientOptions) SetProtocolVersion(pv uint) *ClientOptions {
  169. if pv >= 3 && pv <= 4 {
  170. o.ProtocolVersion = pv
  171. o.protocolVersionExplicit = true
  172. }
  173. return o
  174. }
  175. // UnsetWill will cause any set will message to be disregarded.
  176. func (o *ClientOptions) UnsetWill() *ClientOptions {
  177. o.WillEnabled = false
  178. return o
  179. }
  180. // SetWill accepts a string will message to be set. When the client connects,
  181. // it will give this will message to the broker, which will then publish the
  182. // provided payload (the will) to any clients that are subscribed to the provided
  183. // topic.
  184. func (o *ClientOptions) SetWill(topic string, payload string, qos byte, retained bool) *ClientOptions {
  185. o.SetBinaryWill(topic, []byte(payload), qos, retained)
  186. return o
  187. }
  188. // SetBinaryWill accepts a []byte will message to be set. When the client connects,
  189. // it will give this will message to the broker, which will then publish the
  190. // provided payload (the will) to any clients that are subscribed to the provided
  191. // topic.
  192. func (o *ClientOptions) SetBinaryWill(topic string, payload []byte, qos byte, retained bool) *ClientOptions {
  193. o.WillEnabled = true
  194. o.WillTopic = topic
  195. o.WillPayload = payload
  196. o.WillQos = qos
  197. o.WillRetained = retained
  198. return o
  199. }
  200. // SetDefaultPublishHandler sets the MessageHandler that will be called when a message
  201. // is received that does not match any known subscriptions.
  202. func (o *ClientOptions) SetDefaultPublishHandler(defaultHandler MessageHandler) *ClientOptions {
  203. o.DefaultPublishHander = defaultHandler
  204. return o
  205. }
  206. // SetOnConnectHandler sets the function to be called when the client is connected. Both
  207. // at initial connection time and upon automatic reconnect.
  208. func (o *ClientOptions) SetOnConnectHandler(onConn OnConnectHandler) *ClientOptions {
  209. o.OnConnect = onConn
  210. return o
  211. }
  212. // SetConnectionLostHandler will set the OnConnectionLost callback to be executed
  213. // in the case where the client unexpectedly loses connection with the MQTT broker.
  214. func (o *ClientOptions) SetConnectionLostHandler(onLost ConnectionLostHandler) *ClientOptions {
  215. o.OnConnectionLost = onLost
  216. return o
  217. }
  218. // SetWriteTimeout puts a limit on how long a mqtt publish should block until it unblocks with a
  219. // timeout error. A duration of 0 never times out. Default 30 seconds
  220. func (o *ClientOptions) SetWriteTimeout(t time.Duration) *ClientOptions {
  221. o.WriteTimeout = t
  222. return o
  223. }
  224. // SetConnectTimeout limits how long the client will wait when trying to open a connection
  225. // to an MQTT server before timeing out and erroring the attempt. A duration of 0 never times out.
  226. // Default 30 seconds. Currently only operational on TCP/TLS connections.
  227. func (o *ClientOptions) SetConnectTimeout(t time.Duration) *ClientOptions {
  228. o.ConnectTimeout = t
  229. return o
  230. }
  231. // SetMaxReconnectInterval sets the maximum time that will be waited between reconnection attempts
  232. // when connection is lost
  233. func (o *ClientOptions) SetMaxReconnectInterval(t time.Duration) *ClientOptions {
  234. o.MaxReconnectInterval = t
  235. return o
  236. }
  237. // SetAutoReconnect sets whether the automatic reconnection logic should be used
  238. // when the connection is lost, even if disabled the ConnectionLostHandler is still
  239. // called
  240. func (o *ClientOptions) SetAutoReconnect(a bool) *ClientOptions {
  241. o.AutoReconnect = a
  242. return o
  243. }