package xiaoqu.home.open.mqtt;

import org.apache.log4j.Logger;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import xiaoqu.home.open.service.RedisService4;

@Component
public class PushCallback implements MqttCallbackExtended {
	private static final Logger log = Logger.getLogger("mqtt");

	@Autowired
	private RedisService4 redisService4;
	@Autowired
	private MqttPushClient mqttPushClient;


	public void connectionLost(Throwable throwable) {
		log.error("连接断开，可以做重连=" + throwable.getMessage(), throwable);
	}

	public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
		String data = new String(mqttMessage.getPayload());
		if (topic.contains("$SYS/brokers")) {
			if (data.contains("watch")) {//手表端链接  手表端用的用户名是watch
				this.redisService4.lPush("WatchConnectList", data);
				log.info("接收手表端建立连接消息主题 :" + topic + "接收消息Qos:" + mqttMessage.getQos() + "接收消息内容: "+data);
			}
		} 
	}

	public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
//		try {
//			log.info("消息:"+iMqttDeliveryToken.getMessage().toString() +"->投递结果="+ iMqttDeliveryToken.isComplete());
//		} catch (MqttException e) {
//			e.printStackTrace();
//		}
	}
	@Override
	public void connectComplete(boolean reconnect, String serverURI) {
		mqttPushClient.subscribe("$SYS/brokers/+/clients/#", 1);
		
	}
	
}
