Improve connection making

This commit is contained in:
Thomas Nordquist
2019-01-08 02:21:55 +01:00
parent e72696dc57
commit bb0f96028d
3 changed files with 89 additions and 28 deletions

View File

@@ -1,12 +1,13 @@
import { Client, connect as mqttConnect } from 'mqtt'
import { DataSource, DataSourceStateMachine } from './'
import * as Url from 'url'
export interface MqttOptions {
url: string
username?: string
password?: string
ssl: boolean
sslValidation: boolean
tls: boolean
certValidation: boolean
}
export class MqttSource implements DataSource<MqttOptions> {
@@ -22,13 +23,25 @@ export class MqttSource implements DataSource<MqttOptions> {
public connect(options: MqttOptions): DataSourceStateMachine {
this.stateMachine.setConnecting()
const client = mqttConnect(options.url, {
const urlStr = options.tls ? options.url.replace(/^(mqtt|ws):/, '$1s:') : options.url
let url
try {
url = Url.parse(urlStr)
} catch (error) {
this.stateMachine.setError(error)
throw error
}
const client = mqttConnect(url, {
resubscribe: false,
rejectUnauthorized: !options.certValidation,
})
this.client = client
client.on('error', (error: Error) => {
console.log(error)
this.stateMachine.setError(error)
})

View File

@@ -1,4 +1,8 @@
import { addMqttConnectionEvent, backendEvents, makeConnectionStateEvent, makeConnectionMessageEvent, AddMqttConnection } from '../../events'
import {
addMqttConnectionEvent, backendEvents,
makeConnectionStateEvent, removeConnection,
makeConnectionMessageEvent, AddMqttConnection
} from '../../events'
import { MqttSource, DataSource } from './DataSource'
class ConnectionManager {
@@ -6,17 +10,18 @@ class ConnectionManager {
public manageConnections() {
backendEvents.subscribe(addMqttConnectionEvent, this.handleConnectionRequest)
backendEvents.subscribe(removeConnection, (connectionId) => this.removeConnection(connectionId))
}
private handleConnectionRequest = (event: AddMqttConnection) => {
console.log(event)
const connectionId = event.id
const options = event.options
const connection = new MqttSource()
this.connections[connectionId] = connection
const connectionStateEvent = makeConnectionStateEvent(connectionId)
connection.stateMachine.onUpdate.subscribe((state) => {
backendEvents.emit(makeConnectionStateEvent(connectionId), state)
backendEvents.emit(connectionStateEvent, state)
})
connection.connect(options)
@@ -36,7 +41,6 @@ class ConnectionManager {
public removeConnection(hash: string) {
const connection = this.connections[hash]
connection.stateMachine
connection.disconnect()
delete this.connections[hash]
}