import mqtt from 'mqtt';

//连接
const mqttConnect = () => {
  return mqtt.connect({
    keepalive: 30,
    protocolId: 'MQTT',
    // protocolVersion: 4,
    protocol: 'tcp',
    hostname: '114.115.161.162',
    clean: true,
    reconnectPeriod: 1000,
    port: 8083,
    path: '/mqtt',
    connectTimeout: 30 * 1000,
    clientId: 'yongxu-web',
  });
};

//断开连接
const mqttDisconnect = (client: any) => {
  if (client) {
    client.end();
  }
};

//消息发布
const mqttPublish = (client: any, context: any) => {
  if (client) {
    const { topic, qos, payload } = context;
    client.publish(topic, payload, { qos }, (error: any) => {
      if (error) {
        console.log('Publish error: ', error);
      }
    });
  }
};

//订阅主题
const mqttSub = (client: any, subscription: any) => {
  if (client) {
    const { topic, qos } = subscription;
    client.subscribe(topic, { qos }, (error: any) => {
      if (error) {
        console.log('Subscribe to topics error', error);
        return;
      }
    });
  }
};

//取消订阅
const mqttUnSub = (client: any, subscription: any) => {
  if (client) {
    const { topic } = subscription;
    client.unsubscribe(topic, (error: any) => {
      if (error) {
        console.log('Unsubscribe error', error);
        return;
      }
    });
  }
};

export { mqttConnect, mqttDisconnect, mqttPublish, mqttSub, mqttUnSub };
