Added Client ID generator

This commit is contained in:
selva.andre
2012-08-09 23:14:29 +02:00
parent 937a7b7060
commit 5540805570
@@ -1,6 +1,8 @@
package org.dna.mqtt.moquette.client; package org.dna.mqtt.moquette.client;
import java.net.InetAddress;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
@@ -46,8 +48,8 @@ import org.slf4j.LoggerFactory;
* The API to connect to a MQTT server. * The API to connect to a MQTT server.
* *
* Pass to the constructor the host and port to connect, invoke the connect * Pass to the constructor the host and port to connect, invoke the connect
* message, invoke publish to send notifications messages, invoke subscribe * message, invoke publish to send notifications messages, invoke subscribe with
* with a callback to be notified when something happen on the desired topic. * a callback to be notified when something happen on the desired topic.
* *
* @author andrea * @author andrea
*/ */
@@ -62,29 +64,27 @@ public final class Client {
private static final int NUM_SCHEDULER_TIMER_THREAD = 1; private static final int NUM_SCHEDULER_TIMER_THREAD = 1;
final static int DEFAULT_RETRIES = 3; final static int DEFAULT_RETRIES = 3;
private int m_connectRetries = DEFAULT_RETRIES; private int m_connectRetries = DEFAULT_RETRIES;
private String m_hostname; private String m_hostname;
private int m_port; private int m_port;
//internal mangement used for conversation with the server //internal mangement used for conversation with the server
private IoConnector m_connector; private IoConnector m_connector;
private IoSession m_session; private IoSession m_session;
private CountDownLatch m_connectBarrier; private CountDownLatch m_connectBarrier;
private CountDownLatch m_subscribeBarrier; private CountDownLatch m_subscribeBarrier;
private byte m_returnCode; private byte m_returnCode;
//TODO synchronize the access //TODO synchronize the access
//Refact the da model should be a list of callback for each topic //Refact the da model should be a list of callback for each topic
private Map<String, IPublishCallback> m_subscribersList = new HashMap<String, IPublishCallback>(); private Map<String, IPublishCallback> m_subscribersList = new HashMap<String, IPublishCallback>();
private ScheduledExecutorService m_scheduler; private ScheduledExecutorService m_scheduler;
private ScheduledFuture m_pingerHandler; private ScheduledFuture m_pingerHandler;
private String m_macAddress;
final Runnable pingerDeamon = new Runnable() { final Runnable pingerDeamon = new Runnable() {
public void run() { public void run() {
LOG.debug("Pingreq sent"); LOG.debug("Pingreq sent");
//send a ping req //send a ping req
m_session.write(new PingReqMessage()); m_session.write(new PingReqMessage());
} }
}; };
public Client(String host, int port) { public Client(String host, int port) {
m_hostname = host; m_hostname = host;
@@ -116,6 +116,8 @@ public final class Client {
m_connector.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, Server.DEFAULT_CONNECT_TIMEOUT); m_connector.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, Server.DEFAULT_CONNECT_TIMEOUT);
m_scheduler = Executors.newScheduledThreadPool(NUM_SCHEDULER_TIMER_THREAD); m_scheduler = Executors.newScheduledThreadPool(NUM_SCHEDULER_TIMER_THREAD);
m_macAddress = readMACAddress();
} }
public void connect() throws MQTTException { public void connect() throws MQTTException {
@@ -127,7 +129,7 @@ public final class Client {
future.awaitUninterruptibly(); future.awaitUninterruptibly();
m_session = future.getSession(); m_session = future.getSession();
} catch (RuntimeIoException e) { } catch (RuntimeIoException e) {
LOG.debug("Failed to connect, retry " + retries + " of ("+m_connectRetries+")", e); LOG.debug("Failed to connect, retry " + retries + " of (" + m_connectRetries + ")", e);
} }
if (retries == m_connectRetries) { if (retries == m_connectRetries) {
@@ -139,7 +141,7 @@ public final class Client {
//send a message over the session //send a message over the session
ConnectMessage connMsg = new ConnectMessage(); ConnectMessage connMsg = new ConnectMessage();
connMsg.setKeepAlive(KEEPALIVE_SECS); connMsg.setKeepAlive(KEEPALIVE_SECS);
connMsg.setClientID("FAKE_MSG_ID1"); //TODO create a generator for the ID connMsg.setClientID(generateClientID());
m_session.write(connMsg); m_session.write(connMsg);
//suspend until the server respond with CONN_ACK //suspend until the server respond with CONN_ACK
@@ -187,7 +189,7 @@ public final class Client {
* Publish to the connected server the payload message to the given topic. * Publish to the connected server the payload message to the given topic.
* It's admitted to publish a 0 -length payload. * It's admitted to publish a 0 -length payload.
*/ */
public void publish(String topic, byte[] payload) throws PublishException{ public void publish(String topic, byte[] payload) throws PublishException {
PublishMessage msg = new PublishMessage(); PublishMessage msg = new PublishMessage();
msg.setTopicName(topic); msg.setTopicName(topic);
msg.setPayload(payload); msg.setPayload(payload);
@@ -214,7 +216,7 @@ public final class Client {
public void subscribe(String topic, IPublishCallback publishCallback) { public void subscribe(String topic, IPublishCallback publishCallback) {
LOG.info("subscribe invoked"); LOG.info("subscribe invoked");
SubscribeMessage msg = new SubscribeMessage(); SubscribeMessage msg = new SubscribeMessage();
msg.addSubscription(new SubscribeMessage.Couple((byte)AbstractMessage.QOSType.MOST_ONE.ordinal(), topic)); msg.addSubscription(new SubscribeMessage.Couple((byte) AbstractMessage.QOSType.MOST_ONE.ordinal(), topic));
msg.setQos(AbstractMessage.QOSType.LEAST_ONE); msg.setQos(AbstractMessage.QOSType.LEAST_ONE);
WriteFuture wf = m_session.write(msg); WriteFuture wf = m_session.write(msg);
@@ -256,9 +258,8 @@ public final class Client {
//TODO check the ACK messageID //TODO check the ACK messageID
} }
/** /**
* TODO extract this SPI method in a SPI * TODO extract this SPI method in a SPI
*/ */
protected void connectionAckCallback(byte returnCode) { protected void connectionAckCallback(byte returnCode) {
LOG.info("connectionAckCallback invoked"); LOG.info("connectionAckCallback invoked");
@@ -266,18 +267,15 @@ public final class Client {
m_connectBarrier.countDown(); m_connectBarrier.countDown();
} }
protected void subscribeAckCallback() { protected void subscribeAckCallback() {
LOG.info("subscribeAckCallback invoked"); LOG.info("subscribeAckCallback invoked");
m_subscribeBarrier.countDown(); m_subscribeBarrier.countDown();
} }
protected void publishCallback(String topic, byte[] payload) { protected void publishCallback(String topic, byte[] payload) {
m_subscribersList.get(topic).published(topic, payload); m_subscribersList.get(topic).published(topic, payload);
} }
/** /**
* In the current pinger is not ye executed, then cancel it and schedule * In the current pinger is not ye executed, then cancel it and schedule
* another by KEEPALIVE_SECS * another by KEEPALIVE_SECS
@@ -289,6 +287,26 @@ public final class Client {
m_pingerHandler = m_scheduler.scheduleWithFixedDelay(pingerDeamon, KEEPALIVE_SECS, KEEPALIVE_SECS, TimeUnit.SECONDS); m_pingerHandler = m_scheduler.scheduleWithFixedDelay(pingerDeamon, KEEPALIVE_SECS, KEEPALIVE_SECS, TimeUnit.SECONDS);
} }
private String readMACAddress() {
try {
NetworkInterface network = NetworkInterface.getNetworkInterfaces().nextElement();
byte[] mac = network.getHardwareAddress();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mac.length; i++) {
sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
}
return sb.toString();
} catch (Exception ex) {
throw new MQTTException("Can't retrieve host MAC address", ex);
}
}
private String generateClientID() {
double rnd = Math.random();
return "Moquette-client_" + m_macAddress + Math.round(rnd*1000);
}
public void close() { public void close() {
//stop the pinger //stop the pinger