import crypto from 'crypto' import mqtt from './mqtt' const host = '39.98.253.192' const url = `wx://${host}/mqtt` export function getMQTTClient(productId, deviceName, deviceSecret) { const clientId = 'iotx_admin_' + Math.random().toString(16).substr(2, 8) const content = productId + deviceName + clientId const hmac = crypto.createHmac('md5', deviceSecret) const up = hmac.update(content) const sign = up.digest('hex') const options = { keepalive: 200, clean: true, reconnectPeriod: 5000, connectTimeout: 5000, clientId: clientId, username: `${deviceName}&${productId}`, password: sign } const client = mqtt.connect(url, options) client.on('error', (e) => { console.log(e) client.end() }) let reconnectCount = 1 client.on('reconnect', () => { console.log(clientId + ' reconnect ' + reconnectCount + ' times') reconnectCount++ if (reconnectCount > 3) { client.end() console.log(clientId + ' reconnect failed') } }) client.on('close', () => { console.log(clientId + ' disconnected') }) return client }