package main.java.com.sxfxenergy;
import java.io.IOException;
import org.eclipse.paho.client.mqttv3.MqttException;
public class MqttClient {
public static void main(String[] args) throws MqttException, IOException {
// ClientMQTT client = new ClientMQTT(); client.start();
// client.start();
ClientMQTT2 client = new ClientMQTT2();
client.init();
}
}
package main.java.com.sxfxenergy;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.UUID;
import java.util.concurrent.ScheduledExecutorService;
import javax.annotation.PostConstruct;
public class ClientMQTT2 {
private static Logger logger = LoggerFactory.getLogger(PushCallback.class);
public static String HOST = ""; // 作为服务器使用(收集客户端发送的消息)
// public static String TOPIC = ""; //定义消息的主题,客户端接收消息的根据
private static String clientid = "";
private MqttClient client;
private MqttConnectOptions options;
// 生成配置对象,用户名,密码等
public MqttConnectOptions getOptions() {
MqttConnectOptions options = new MqttConnectOptions();
options.setCleanSession(true);
options.setConnectionTimeout(10);
options.setKeepAliveInterval(20);
return options;
}
public void connect() throws MqttException, IOException {
Properties properties = new Properties();
properties.load(JDBCUtil.class.getResourceAsStream("/db.properties"));
// TOPIC=tt;
HOST = properties.getProperty("mq.host");
clientid = properties.getProperty("mq.clientid");
// 防止重复创建MQTTClient实例
if (client == null) {
client = new MqttClient(HOST, clientid, new MemoryPersistence());
client.setCallback(new PushCallback2(client, getOptions()));
}
MqttConnectOptions options = getOptions();
// 判断拦截状态,这里注意一下,如果没有这个判断,是非常坑的
if (!client.isConnected()) {
client.connect(options);
} else {// 这里的逻辑是如果连接成功就重新连接
client.disconnect();
client.connect(options);
}
}
public void init() throws MqttException, IOException {
connect();
Properties properties = new Properties();
properties.load(JDBCUtil.class.getResourceAsStream("/db.properties"));
String notePath=properties.getProperty("note_path");
File file = new File(notePath);
String[] res = FTPUtil.txt2String(file).split("\\s+");
List<String> sAttr = new ArrayList<>(res.length);
List<Integer> Qos = new ArrayList<>(res.length);
for (String r : res) {
String str = r.trim();
if (str.isEmpty()) {
continue;
}
sAttr.add(str);
}
int[] ids_int = new int[sAttr.size()];
for (int i = 0; i < sAttr.size(); i++) {
ids_int[i] = 1;
}
client.subscribe(sAttr.toArray(new String[sAttr.size()]), ids_int);
}
}
package main.java.com.sxfxenergy;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttSecurityException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.PascalNameFilter;
import main.java.com.mqttDto.RequestMqData;
import main.java.com.mqttDto.ResponDataBase;
import main.java.com.utils.DateUtil;
import main.java.com.utils.MQTT_V1;
import scala.Tuple3;
/**
* 发布消息的回调类
*
* 必须实现MqttCallback的接口并实现对应的相关接口方法CallBack 类将实现 MqttCallBack。
* 每个客户机标识都需要一个回调实例。在此示例中,构造函数传递客户机标识以另存为实例数据。 在回调中,将它用来标识已经启动了该回调的哪个实例。
* 必须在回调类中实现三个方法:
*
* public void messageArrived(MqttTopic topic, MqttMessage message)接收已经预订的发布。
*
* public void connectionLost(Throwable cause)在断开连接时调用。
*
* public void deliveryComplete(MqttDeliveryToken token)) 接收到已经发布的 QoS 1 或 QoS 2
* 消息的传递令牌时调用。 由 MqttClient.connect 激活此回调。
*
*/
public class PushCallback2 implements MqttCallback {
private ScheduledExecutorService service;
private static Logger logger = LoggerFactory.getLogger(PushCallback2.class);
public PushCallback2() {
}
private MqttClient client;
private MqttConnectOptions options;
public PushCallback2(MqttClient client, MqttConnectOptions options) {
this.client = client;
this.options = options;
}
public void connectionLost(Throwable cause) {
while (true) {
try {// 如果没有发生异常说明连接成功,如果发生异常,则死循环
Thread.sleep(1000);
System.err.println("重新連接,,,,,,,,,,,,,,,,,");
ThreadGroup currentGroup = Thread.currentThread().getThreadGroup();
int noThreads = currentGroup.activeCount();
Thread[] lstThreads = new Thread[noThreads];
currentGroup.enumerate(lstThreads);
for (int i = 0; i < noThreads; i++) {
System.err.println("线程号:" + i + " = " + lstThreads[i].getName() + "name=" + lstThreads[i].getId());
}
client.connect(options);
Properties properties = new Properties();
properties.load(JDBCUtil.class.getResourceAsStream("/db.properties"));
String notePath = properties.getProperty("note_path");
File file = new File(notePath);
String[] res = FTPUtil.txt2String(file).split("\\s+");
List<String> sAttr = new ArrayList<>(res.length);
List<Integer> Qos = new ArrayList<>(res.length);
for (String r : res) {
String str = r.trim();
if (str.isEmpty()) {
continue;
}
sAttr.add(str);
}
int[] ids_int = new int[sAttr.size()];
for (int i = 0; i < sAttr.size(); i++) {
ids_int[i] = 1;
}
client.subscribe(sAttr.toArray(new String[sAttr.size()]), ids_int);
break;
} catch (Exception e) {
continue;
}
}
}
public void deliveryComplete(IMqttDeliveryToken token) {
logger.info("deliveryComplete---------" + token.isComplete());
}
public void messageArrived(String topic, MqttMessage message) throws Exception {
// subscribe后得到的消息会执行到这里面
logger.info("接收消息主题 : " + topic);
// logger.info("接收消息Qos:" + message.getQos());
// 收到消息并设置返回字符串格式,有时候会出现乱码,所以格式一定要设置
// String string = new String(message.getPayload(), "UTF-8");
byte[] payload = message.getPayload();
// logger.info("testttttttt:"+payload);
Tuple3<String, Long, Object>[] tuple3 = MQTT_V1.parse(payload);
RequestMqData rqm = new RequestMqData();
// String
// str1="/iot/v1/shitoushuini_0114573230/TYSTSN_BYQ_01/8c8a03469e9a_Modbus_7/property/up";
// 用户
String userstarStr = AnalysUtil.extractString(topic, "/", 3);
String[] userStr = userstarStr.split("/");
String userAndUserId = userStr[0].toString();
String userId = (userAndUserId.split("_"))[1];
String s = AnalysUtil.extractString(topic, "/", 5);
String str2 = s.substring(0, s.indexOf("/"));
// logger.info(str2);
String macAdress = s.substring(0, str2.indexOf("_"));
String macAndEqId = AnalysUtil.extractString(str2, "_", 1);
String modlBus = macAndEqId.substring(0, macAndEqId.indexOf("_"));
String eqId01 = AnalysUtil.extractString(macAndEqId, "_", 2);
Integer eqId02 = Integer.parseInt(eqId01);
String eqId = eqId02 + "";
for (Tuple3<String, Long, Object> i : tuple3) {
// 判断时间戳
// logger.info("返回时间"+i._2().toString());
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long lt = new Long(i._2().toString());
Date date = new Date(lt);
logger.info("返回时间:" + simpleDateFormat.format(date));
String jugeDate = DateUtil.getWholePointDate(i._2().toString());
// String jugeDate="2020-04-13 11:30:00";
// logger.info("开始判断:jugeDate:"+jugeDate);
if (!"false".equals(jugeDate)) {
rqm.setMacAddress(macAdress.substring(0, 2) + ":" + macAdress.substring(2, 4) + ":"
+ macAdress.substring(4, 6) + ":" + macAdress.substring(6, 8) + ":" + macAdress.substring(8, 10)
+ ":" + macAdress.substring(10, 12));
rqm.setMeterAddress(eqId);
rqm.setEnterpriseCode(userId);
rqm.setTime(jugeDate);
ResponDataBase enD1 = new ResponDataBase();
String parm = AnalysUtil.extractString(i._1().toString(), ".", 4);
String[] parmAtr = parm.split("[.]");
enD1.setParamCode(parm);
// enD1.setParamCode("B630");
enD1.setParamVal(i._3() + "");
List<ResponDataBase> dataList = new ArrayList<>();
dataList.add(enD1);
rqm.setParamCode(dataList);
// logger.info("接收设备的内容 :"+ rqm.toString());
String requestBTMDataJson = JSON.toJSONString(rqm, new PascalNameFilter());
logger.info("传参:::" + requestBTMDataJson);
Properties properties = new Properties();
// 加载配置文件
properties.load(JDBCUtil.class.getResourceAsStream("/db.properties"));
String fxRouteUrl = properties.getProperty("fx.routeUrl");
// logger.info("服务器地址:"+fxRouteUrl);
HttpPost.post(fxRouteUrl, requestBTMDataJson);
}
}
// excSqlServer("");
/*
* logger.info("转换前消息:"+string); String str = strTo16(string);
* logger.info("转化后的16进制消息:"+str); logger.info("转化后的字符串消息:"+toStringHex2(str));
*/
/*
* if(!"636c6f7365".equals(str)){ MQResponDto mqr= AnalysUtil.analys(str);
* logger.info("eqid::::"+mqr.getEqID()); excSqlServer(""); }
*/
// 将16进制转换成字节数组
/*
* byte[] stringByte=hexToByteArray(str); //将字节数组转换成字符
* logger.info("将字节数组转换成字符"+byteToString(stringByte));
* logger.info("转化后的字符串消息:"+toStringHex2(str)); //解析数据 //BeanContext fromJson =
* new Gson().fromJson(string,BeanContext.class); // MessageFormat fromJson =
* new Gson().fromJson(string, MessageFormat.class); logger.info("接收消息内容 : " +
* new String(message.getPayload(), "GBK"));
*/
// RequestBTMData requestBTMDataObject = (RequestBTMData)
// JSONObject.parse("");强制转化成实体
/*
* RequestBTMData requestBTMData= new RequestBTMData();
* requestBTMData.setUserId(1111);
* requestBTMData.setTime("2020-01-19 11:43:00"); DataBase dataBase= new
* DataBase(); dataBase.setBF(41); dataBase.setD(0); dataBase.setDT(1); DataBase
* dataBase01= new DataBase(); dataBase01.setBF(42); dataBase01.setD(0);
* dataBase01.setDT(1); List<DataBase> dblist= new ArrayList<DataBase>();
* dblist.add(dataBase); dblist.add(dataBase01); requestBTMData.setData(dblist);
* String requestBTMDataJson=JSON.toJSONString(requestBTMData,new
* PascalNameFilter()); Properties properties=new Properties(); //加载配置文件
* properties.load(JDBCUtil.class.getResourceAsStream("/db.properties")); String
* fxRouteUrl=properties.getProperty("fx.routeUrl");
* logger.info("服务器地址:"+fxRouteUrl);
*/
// HttpPost.post(fxRouteUrl,requestBTMDataJson);
// 操作数据库
// JDBCUtil.executeCount("SELECT * from test01; ");
}
//字节数组转换成字符串
private static String byteToString(byte[] data) {
String str = null;
try {
str = new String(data, "utf-8");
} catch (UnsupportedEncodingException e) {
}
return str;
}
//字符串转换成16进制
public static String strTo16(String s) {
String str = "";
for (int i = 0; i < s.length(); i++) {
int ch = (int) s.charAt(i);
String s4 = Integer.toHexString(ch);
str = str + s4;
}
return str;
}
public static byte hexToByte(String inHex) {
return (byte) Integer.parseInt(inHex, 16);
}
//16进制转换成字节数组
public static byte[] hexToByteArray(String inHex) {
int hexlen = inHex.length();
byte[] result;
if (hexlen % 2 == 1) {
// 奇数
hexlen++;
result = new byte[(hexlen / 2)];
inHex = "0" + inHex;
} else {
// 偶数
result = new byte[(hexlen / 2)];
}
int j = 0;
for (int i = 0; i < hexlen; i += 2) {
result[j] = hexToByte(inHex.substring(i, i + 2));
j++;
}
return result;
}
// 转化十六进制编码为字符串
public static String toStringHex2(String s) {
byte[] baKeyword = new byte[s.length() / 2];
for (int i = 0; i < baKeyword.length; i++) {
try {
baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));
} catch (Exception e) {
e.printStackTrace();
}
}
try {
s = new String(baKeyword, "utf-8");// UTF-16le:Not
} catch (Exception e1) {
e1.printStackTrace();
}
return s;
}
public static void excSqlServer(String sqlStr) {
Connection connection = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
// 加载驱动
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
// 获取连接
connection = DriverManager.getConnection("jdbc:sqlserver://47.92.200.102;databaseName = DomesticDinoTech",
"sa", "fxck.1709");
// 3.发送sql语句
ps = connection.prepareStatement("SELECT * from users");
rs = ps.executeQuery();
while (rs.next()) {
logger.info("name:" + rs.getString(2));
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String eqId01 = "080";
Integer eqId02 = Integer.parseInt(eqId01);
String eqId = eqId02 + "";
}
}