client.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  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 provides an MQTT v3.1.1 client library.
  15. package mqtt
  16. import (
  17. "errors"
  18. "fmt"
  19. "git.eclipse.org/gitroot/paho/org.eclipse.paho.mqtt.golang.git/packets"
  20. "net"
  21. "sync"
  22. "time"
  23. )
  24. // ClientInt is the interface definition for a Client as used by this
  25. // library, the interface is primarily to allow mocking tests.
  26. type ClientInt interface {
  27. IsConnected() bool
  28. Connect() Token
  29. Disconnect(uint)
  30. disconnect()
  31. Publish(string, byte, bool, interface{}) Token
  32. Subscribe(string, byte, MessageHandler) Token
  33. SubscribeMultiple(map[string]byte, MessageHandler) Token
  34. Unsubscribe(...string) Token
  35. }
  36. // Client is an MQTT v3.1.1 client for communicating
  37. // with an MQTT server using non-blocking methods that allow work
  38. // to be done in the background.
  39. // An application may connect to an MQTT server using:
  40. // A plain TCP socket
  41. // A secure SSL/TLS socket
  42. // A websocket
  43. // To enable ensured message delivery at Quality of Service (QoS) levels
  44. // described in the MQTT spec, a message persistence mechanism must be
  45. // used. This is done by providing a type which implements the Store
  46. // interface. For convenience, FileStore and MemoryStore are provided
  47. // implementations that should be sufficient for most use cases. More
  48. // information can be found in their respective documentation.
  49. // Numerous connection options may be specified by configuring a
  50. // and then supplying a ClientOptions type.
  51. type Client struct {
  52. sync.RWMutex
  53. messageIds
  54. conn net.Conn
  55. ibound chan packets.ControlPacket
  56. obound chan *PacketAndToken
  57. oboundP chan *PacketAndToken
  58. msgRouter *router
  59. stopRouter chan bool
  60. incomingPubChan chan *packets.PublishPacket
  61. errors chan error
  62. stop chan struct{}
  63. persist Store
  64. options ClientOptions
  65. lastContact lastcontact
  66. pingOutstanding bool
  67. connected bool
  68. workers sync.WaitGroup
  69. }
  70. // NewClient will create an MQTT v3.1.1 client with all of the options specified
  71. // in the provided ClientOptions. The client must have the Start method called
  72. // on it before it may be used. This is to make sure resources (such as a net
  73. // connection) are created before the application is actually ready.
  74. func NewClient(o *ClientOptions) *Client {
  75. c := &Client{}
  76. c.options = *o
  77. if c.options.Store == nil {
  78. c.options.Store = NewMemoryStore()
  79. }
  80. switch c.options.ProtocolVersion {
  81. case 3, 4:
  82. c.options.protocolVersionExplicit = true
  83. default:
  84. c.options.ProtocolVersion = 4
  85. c.options.protocolVersionExplicit = false
  86. }
  87. c.persist = c.options.Store
  88. c.connected = false
  89. c.messageIds = messageIds{index: make(map[uint16]Token)}
  90. c.msgRouter, c.stopRouter = newRouter()
  91. c.msgRouter.setDefaultHandler(c.options.DefaultPublishHander)
  92. return c
  93. }
  94. // IsConnected returns a bool signifying whether
  95. // the client is connected or not.
  96. func (c *Client) IsConnected() bool {
  97. c.RLock()
  98. defer c.RUnlock()
  99. return c.connected
  100. }
  101. func (c *Client) setConnected(status bool) {
  102. c.Lock()
  103. defer c.Unlock()
  104. c.connected = status
  105. }
  106. //ErrNotConnected is the error returned from function calls that are
  107. //made when the client is not connected to a broker
  108. var ErrNotConnected = errors.New("Not Connected")
  109. // Connect will create a connection to the message broker
  110. // If clean session is false, then a slice will
  111. // be returned containing Receipts for all messages
  112. // that were in-flight at the last disconnect.
  113. // If clean session is true, then any existing client
  114. // state will be removed.
  115. func (c *Client) Connect() Token {
  116. var err error
  117. t := newToken(packets.Connect).(*ConnectToken)
  118. DEBUG.Println(CLI, "Connect()")
  119. go func() {
  120. var rc byte
  121. cm := newConnectMsgFromOptions(&c.options)
  122. for _, broker := range c.options.Servers {
  123. CONN:
  124. DEBUG.Println(CLI, "about to write new connect msg")
  125. c.conn, err = openConnection(broker, &c.options.TLSConfig, c.options.ConnectTimeout)
  126. if err == nil {
  127. DEBUG.Println(CLI, "socket connected to broker")
  128. switch c.options.ProtocolVersion {
  129. case 3:
  130. DEBUG.Println(CLI, "Using MQTT 3.1 protocol")
  131. cm.ProtocolName = "MQIsdp"
  132. cm.ProtocolVersion = 3
  133. default:
  134. DEBUG.Println(CLI, "Using MQTT 3.1.1 protocol")
  135. c.options.ProtocolVersion = 4
  136. cm.ProtocolName = "MQTT"
  137. cm.ProtocolVersion = 4
  138. }
  139. cm.Write(c.conn)
  140. rc = c.connect()
  141. if rc != packets.Accepted {
  142. c.conn.Close()
  143. c.conn = nil
  144. //if the protocol version was explicitly set don't do any fallback
  145. if c.options.protocolVersionExplicit {
  146. ERROR.Println(CLI, "Connecting to", broker, "CONNACK was not CONN_ACCEPTED, but rather", packets.ConnackReturnCodes[rc])
  147. continue
  148. }
  149. if c.options.ProtocolVersion == 4 {
  150. DEBUG.Println(CLI, "Trying reconnect using MQTT 3.1 protocol")
  151. c.options.ProtocolVersion = 3
  152. goto CONN
  153. }
  154. }
  155. break
  156. } else {
  157. ERROR.Println(CLI, err.Error())
  158. WARN.Println(CLI, "failed to connect to broker, trying next")
  159. rc = packets.ErrNetworkError
  160. }
  161. }
  162. if c.conn == nil {
  163. ERROR.Println(CLI, "Failed to connect to a broker")
  164. t.returnCode = rc
  165. if rc != packets.ErrNetworkError {
  166. t.err = packets.ConnErrors[rc]
  167. } else {
  168. t.err = fmt.Errorf("%s : %s", packets.ConnErrors[rc], err)
  169. }
  170. t.flowComplete()
  171. return
  172. }
  173. c.lastContact.update()
  174. c.persist.Open()
  175. c.obound = make(chan *PacketAndToken, 100)
  176. c.oboundP = make(chan *PacketAndToken, 100)
  177. c.ibound = make(chan packets.ControlPacket)
  178. c.errors = make(chan error)
  179. c.stop = make(chan struct{})
  180. c.incomingPubChan = make(chan *packets.PublishPacket, 100)
  181. c.msgRouter.matchAndDispatch(c.incomingPubChan, c.options.Order, c)
  182. c.workers.Add(1)
  183. go outgoing(c)
  184. go alllogic(c)
  185. c.connected = true
  186. DEBUG.Println(CLI, "client is connected")
  187. if c.options.OnConnect != nil {
  188. go c.options.OnConnect(c)
  189. }
  190. if c.options.KeepAlive != 0 {
  191. c.workers.Add(1)
  192. go keepalive(c)
  193. }
  194. // Take care of any messages in the store
  195. //var leftovers []Receipt
  196. if c.options.CleanSession == false {
  197. //leftovers = c.resume()
  198. } else {
  199. c.persist.Reset()
  200. }
  201. // Do not start incoming until resume has completed
  202. c.workers.Add(1)
  203. go incoming(c)
  204. DEBUG.Println(CLI, "exit startClient")
  205. t.flowComplete()
  206. }()
  207. return t
  208. }
  209. // internal function used to reconnect the client when it loses its connection
  210. func (c *Client) reconnect() {
  211. DEBUG.Println(CLI, "enter reconnect")
  212. var rc byte = 1
  213. var sleep uint = 1
  214. var err error
  215. for rc != 0 {
  216. cm := newConnectMsgFromOptions(&c.options)
  217. for _, broker := range c.options.Servers {
  218. CONN:
  219. DEBUG.Println(CLI, "about to write new connect msg")
  220. c.conn, err = openConnection(broker, &c.options.TLSConfig, c.options.ConnectTimeout)
  221. if err == nil {
  222. DEBUG.Println(CLI, "socket connected to broker")
  223. switch c.options.ProtocolVersion {
  224. case 3:
  225. DEBUG.Println(CLI, "Using MQTT 3.1 protocol")
  226. cm.ProtocolName = "MQIsdp"
  227. cm.ProtocolVersion = 3
  228. default:
  229. DEBUG.Println(CLI, "Using MQTT 3.1.1 protocol")
  230. c.options.ProtocolVersion = 4
  231. cm.ProtocolName = "MQTT"
  232. cm.ProtocolVersion = 4
  233. }
  234. cm.Write(c.conn)
  235. rc = c.connect()
  236. if rc != packets.Accepted {
  237. c.conn.Close()
  238. c.conn = nil
  239. //if the protocol version was explicitly set don't do any fallback
  240. if c.options.protocolVersionExplicit {
  241. ERROR.Println(CLI, "Connecting to", broker, "CONNACK was not Accepted, but rather", packets.ConnackReturnCodes[rc])
  242. continue
  243. }
  244. if c.options.ProtocolVersion == 4 {
  245. DEBUG.Println(CLI, "Trying reconnect using MQTT 3.1 protocol")
  246. c.options.ProtocolVersion = 3
  247. goto CONN
  248. }
  249. }
  250. break
  251. } else {
  252. ERROR.Println(CLI, err.Error())
  253. WARN.Println(CLI, "failed to connect to broker, trying next")
  254. rc = packets.ErrNetworkError
  255. }
  256. }
  257. if rc != 0 {
  258. DEBUG.Println(CLI, "Reconnect failed, sleeping for", sleep, "seconds")
  259. time.Sleep(time.Duration(sleep) * time.Second)
  260. if sleep <= uint(c.options.MaxReconnectInterval.Seconds()) {
  261. sleep *= 2
  262. }
  263. }
  264. }
  265. c.lastContact.update()
  266. c.stop = make(chan struct{})
  267. c.workers.Add(1)
  268. go outgoing(c)
  269. go alllogic(c)
  270. c.setConnected(true)
  271. DEBUG.Println(CLI, "client is reconnected")
  272. if c.options.OnConnect != nil {
  273. go c.options.OnConnect(c)
  274. }
  275. if c.options.KeepAlive != 0 {
  276. c.workers.Add(1)
  277. go keepalive(c)
  278. }
  279. c.workers.Add(1)
  280. go incoming(c)
  281. }
  282. // This function is only used for receiving a connack
  283. // when the connection is first started.
  284. // This prevents receiving incoming data while resume
  285. // is in progress if clean session is false.
  286. func (c *Client) connect() byte {
  287. DEBUG.Println(NET, "connect started")
  288. ca, err := packets.ReadPacket(c.conn)
  289. if err != nil {
  290. ERROR.Println(NET, "connect got error", err)
  291. return packets.ErrNetworkError
  292. }
  293. if ca == nil {
  294. ERROR.Println(NET, "received nil packet")
  295. return packets.ErrNetworkError
  296. }
  297. msg, ok := ca.(*packets.ConnackPacket)
  298. if !ok {
  299. ERROR.Println(NET, "received msg that was not CONNACK")
  300. return packets.ErrNetworkError
  301. }
  302. DEBUG.Println(NET, "received connack")
  303. return msg.ReturnCode
  304. }
  305. // Disconnect will end the connection with the server, but not before waiting
  306. // the specified number of milliseconds to wait for existing work to be
  307. // completed.
  308. func (c *Client) Disconnect(quiesce uint) {
  309. if !c.IsConnected() {
  310. WARN.Println(CLI, "already disconnected")
  311. return
  312. }
  313. DEBUG.Println(CLI, "disconnecting")
  314. c.setConnected(false)
  315. dm := packets.NewControlPacket(packets.Disconnect).(*packets.DisconnectPacket)
  316. dt := newToken(packets.Disconnect)
  317. c.oboundP <- &PacketAndToken{p: dm, t: dt}
  318. // wait for work to finish, or quiesce time consumed
  319. dt.WaitTimeout(time.Duration(quiesce) * time.Millisecond)
  320. c.disconnect()
  321. }
  322. // ForceDisconnect will end the connection with the mqtt broker immediately.
  323. func (c *Client) forceDisconnect() {
  324. if !c.IsConnected() {
  325. WARN.Println(CLI, "already disconnected")
  326. return
  327. }
  328. c.setConnected(false)
  329. c.conn.Close()
  330. DEBUG.Println(CLI, "forcefully disconnecting")
  331. c.disconnect()
  332. }
  333. func (c *Client) internalConnLost(err error) {
  334. close(c.stop)
  335. c.conn.Close()
  336. c.workers.Wait()
  337. if c.IsConnected() {
  338. if c.options.OnConnectionLost != nil {
  339. go c.options.OnConnectionLost(c, err)
  340. }
  341. if c.options.AutoReconnect {
  342. go c.reconnect()
  343. } else {
  344. c.setConnected(false)
  345. }
  346. }
  347. }
  348. func (c *Client) disconnect() {
  349. select {
  350. case <-c.stop:
  351. //someone else has already closed the channel, must be error
  352. default:
  353. close(c.stop)
  354. }
  355. c.conn.Close()
  356. c.workers.Wait()
  357. close(c.stopRouter)
  358. DEBUG.Println(CLI, "disconnected")
  359. c.persist.Close()
  360. }
  361. // Publish will publish a message with the specified QoS
  362. // and content to the specified topic.
  363. // Returns a read only channel used to track
  364. // the delivery of the message.
  365. func (c *Client) Publish(topic string, qos byte, retained bool, payload interface{}) Token {
  366. token := newToken(packets.Publish).(*PublishToken)
  367. DEBUG.Println(CLI, "enter Publish")
  368. if !c.IsConnected() {
  369. token.err = ErrNotConnected
  370. token.flowComplete()
  371. return token
  372. }
  373. pub := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket)
  374. pub.Qos = qos
  375. pub.TopicName = topic
  376. pub.Retain = retained
  377. switch payload.(type) {
  378. case string:
  379. pub.Payload = []byte(payload.(string))
  380. case []byte:
  381. pub.Payload = payload.([]byte)
  382. default:
  383. token.err = errors.New("Unknown payload type")
  384. token.flowComplete()
  385. return token
  386. }
  387. DEBUG.Println(CLI, "sending publish message, topic:", topic)
  388. c.obound <- &PacketAndToken{p: pub, t: token}
  389. return token
  390. }
  391. // Subscribe starts a new subscription. Provide a MessageHandler to be executed when
  392. // a message is published on the topic provided.
  393. func (c *Client) Subscribe(topic string, qos byte, callback MessageHandler) Token {
  394. token := newToken(packets.Subscribe).(*SubscribeToken)
  395. DEBUG.Println(CLI, "enter Subscribe")
  396. if !c.IsConnected() {
  397. token.err = ErrNotConnected
  398. token.flowComplete()
  399. return token
  400. }
  401. sub := packets.NewControlPacket(packets.Subscribe).(*packets.SubscribePacket)
  402. if err := validateTopicAndQos(topic, qos); err != nil {
  403. token.err = err
  404. return token
  405. }
  406. sub.Topics = append(sub.Topics, topic)
  407. sub.Qoss = append(sub.Qoss, qos)
  408. DEBUG.Println(sub.String())
  409. if callback != nil {
  410. c.msgRouter.addRoute(topic, callback)
  411. }
  412. token.subs = append(token.subs, topic)
  413. c.oboundP <- &PacketAndToken{p: sub, t: token}
  414. DEBUG.Println(CLI, "exit Subscribe")
  415. return token
  416. }
  417. // SubscribeMultiple starts a new subscription for multiple topics. Provide a MessageHandler to
  418. // be executed when a message is published on one of the topics provided.
  419. func (c *Client) SubscribeMultiple(filters map[string]byte, callback MessageHandler) Token {
  420. var err error
  421. token := newToken(packets.Subscribe).(*SubscribeToken)
  422. DEBUG.Println(CLI, "enter SubscribeMultiple")
  423. if !c.IsConnected() {
  424. token.err = ErrNotConnected
  425. token.flowComplete()
  426. return token
  427. }
  428. sub := packets.NewControlPacket(packets.Subscribe).(*packets.SubscribePacket)
  429. if sub.Topics, sub.Qoss, err = validateSubscribeMap(filters); err != nil {
  430. token.err = err
  431. return token
  432. }
  433. if callback != nil {
  434. for topic := range filters {
  435. c.msgRouter.addRoute(topic, callback)
  436. }
  437. }
  438. token.subs = make([]string, len(sub.Topics))
  439. copy(token.subs, sub.Topics)
  440. c.oboundP <- &PacketAndToken{p: sub, t: token}
  441. DEBUG.Println(CLI, "exit SubscribeMultiple")
  442. return token
  443. }
  444. // Unsubscribe will end the subscription from each of the topics provided.
  445. // Messages published to those topics from other clients will no longer be
  446. // received.
  447. func (c *Client) Unsubscribe(topics ...string) Token {
  448. token := newToken(packets.Unsubscribe).(*UnsubscribeToken)
  449. DEBUG.Println(CLI, "enter Unsubscribe")
  450. if !c.IsConnected() {
  451. token.err = ErrNotConnected
  452. token.flowComplete()
  453. return token
  454. }
  455. unsub := packets.NewControlPacket(packets.Unsubscribe).(*packets.UnsubscribePacket)
  456. unsub.Topics = make([]string, len(topics))
  457. copy(unsub.Topics, topics)
  458. c.oboundP <- &PacketAndToken{p: unsub, t: token}
  459. for _, topic := range topics {
  460. c.msgRouter.deleteRoute(topic)
  461. }
  462. DEBUG.Println(CLI, "exit Unsubscribe")
  463. return token
  464. }
  465. //DefaultConnectionLostHandler is a definition of a function that simply
  466. //reports to the DEBUG log the reason for the client losing a connection.
  467. func DefaultConnectionLostHandler(client *Client, reason error) {
  468. DEBUG.Println("Connection lost:", reason.Error())
  469. }