Clean up & Add connection setup
This commit is contained in:
@@ -1,34 +1,46 @@
|
||||
import * as socketIO from 'socket.io'
|
||||
const http = require('http')
|
||||
|
||||
import { TopicProperties, Tree, TreeNodeFactory } from './Model'
|
||||
import { addMqttConnectionEvent, backendEvents, makeConnectionStateEvent, makeConnectionMessageEvent, AddMqttConnection } from '../../events'
|
||||
import { MqttSource, DataSource } from './DataSource'
|
||||
|
||||
const options = { url: 'mqtt://nodered' }
|
||||
const dataSource = new MqttSource()
|
||||
class ConnectionManager {
|
||||
private connections: {[s: string]: DataSource<any>} = {}
|
||||
|
||||
const a: any[] = []
|
||||
|
||||
const server = http.createServer()
|
||||
const io = socketIO(server)
|
||||
io.on('connection', (client) => {
|
||||
console.log('connection')
|
||||
a.forEach((b) => {
|
||||
io.emit('message', b)
|
||||
})
|
||||
client.on('disconnect', () => { /* … */ })
|
||||
})
|
||||
server.listen(3000)
|
||||
|
||||
const state = dataSource.connect(options)
|
||||
dataSource.onMessage((topic: string, payload: Buffer) => {
|
||||
let buffer = payload
|
||||
if (a.length < 30) {
|
||||
a.push({ topic, payload: buffer.toString('base64') })
|
||||
}
|
||||
if (buffer.length > 10000) {
|
||||
buffer = buffer.slice(0, 10000)
|
||||
public manageConnections() {
|
||||
backendEvents.subscribe(addMqttConnectionEvent, this.handleConnectionRequest)
|
||||
}
|
||||
|
||||
io.emit('message', { topic, payload: buffer.toString('base64') })
|
||||
})
|
||||
private handleConnectionRequest = (event: AddMqttConnection) => {
|
||||
console.log(event)
|
||||
const connectionId = event.id
|
||||
const options = event.options
|
||||
const connection = new MqttSource()
|
||||
this.connections[connectionId] = connection
|
||||
|
||||
connection.stateMachine.onUpdate.subscribe((state) => {
|
||||
backendEvents.emit(makeConnectionStateEvent(connectionId), state)
|
||||
})
|
||||
|
||||
connection.connect(options)
|
||||
this.handleNewMessagesForConnection(connectionId, connection)
|
||||
}
|
||||
|
||||
private handleNewMessagesForConnection(connectionId: string, connection: MqttSource) {
|
||||
const messageEvent = makeConnectionMessageEvent(connectionId)
|
||||
connection.onMessage((topic: string, payload: Buffer) => {
|
||||
let buffer = payload
|
||||
if (buffer.length > 10000) {
|
||||
buffer = buffer.slice(0, 10000)
|
||||
}
|
||||
backendEvents.emit(messageEvent, { topic, payload: buffer.toString('base64') })
|
||||
})
|
||||
}
|
||||
|
||||
public removeConnection(hash: string) {
|
||||
const connection = this.connections[hash]
|
||||
connection.stateMachine
|
||||
connection.disconnect()
|
||||
delete this.connections[hash]
|
||||
}
|
||||
}
|
||||
|
||||
const connectionManager = new ConnectionManager()
|
||||
connectionManager.manageConnections()
|
||||
|
||||
Reference in New Issue
Block a user