I'm using a VPS and I'm sending data from my Arduino to the server via MQTT.
Mosquitto print payloads via terminal successfully but when I try to print it in real time via a web page nothing happens.
Knowing that I've already allowed websockets in Mosquitto conf, if I run :
sudo netstat -plnt
I get :
tcp 0 0 0.0.0.0:1883 0.0.0.0:* LISTEN
13248/mosquitto
tcp 0 0 0.0.0.0:1884 0.0.0.0:* LISTEN
20169/mosquitto
tcp6 0 0 :::1883 :::* LISTEN 13248/mosquitto
the topic I'm sending name : /pression and the code I'm using is:
<script>
var websocket="myserver.ovh.net";
var port= 1884;
var user="username";
var pass="password";
client = new Paho.MQTT.Client(websocket, port, "innovation");
// set callback handlers
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;
var options = {
useSSL: false,
userName: user,
password: pass,
onSuccess:onConnect,
onFailure:doFail
}
// connect the client
client.connect(options);
// called when the client connects
function onConnect() {
// Once a connection has been made, make a subscription and send a
message.
document.getElementById("connstatus").innerHTML = "Mqtt Connected";
console.log("Mqtt Connected");
client.subscribe("/pression");
}
function doFail(e){
console.log(e);
}
// called when the client loses its connection
function onConnectionLost(responseObject) {
document.getElementById("connstatus").innerHTML = "Mqtt Not Connected";
if (responseObject.errorCode !== 0) {
console.log("onConnectionLost:"+responseObject.errorMessage);
}
}
function onMessageArrived(message) {
console.log("Pression is :");
document.getElementById("connstatus").innerHTML = message.payloadString;
console.log(message.payloadString);
}
</script>
when I run the script it says "Mqtt Connected" than nothing happened.
However if I run in the terminal :
mosquitto_sub -t '/pression'
I get the pressure values.
if I keep the web page on for some minutes I get this message :
Mqtt Connected
test.html:76 onConnectionLost:AMQJS0008I Socket closed.
config file :
# Place your local configuration in /etc/mosquitto/conf.d/
#
# A full description of the configuration file is at
# /usr/share/doc/mosquitto/examples/mosquitto.conf.example
pid_file /var/run/mosquitto.pid
persistence true
persistence_location /var/lib/mosquitto/
log_dest file /var/log/mosquitto/mosquitto.log
include_dir /etc/mosquitto/conf.d
#password_file /etc/mosquitto/passwd
#allow_anonymous false
listener 1884
protocol websockets
mosquitto log :
1557922249: Config loaded from /etc/mosquitto/mosquitto.conf.
1557922249: Opening websockets listen socket on port 1884.
1557922254: New client connected from xx.xx.11.163 as innovation (c1, k60, u'innovation').
1557922279: Socket error on client innovation, disconnecting.
1557922279: New client connected from xx.xx.11.163 as innovation (c1, k60, u'innovation').
1557922318: Socket error on client innovation, disconnecting.
1557922318: New client connected from xx.xx.11.163 as innovation (c1, k60, u'innovation').
1557922346: Socket error on client innovation, disconnecting.
1557922346: New client connected from xx.xx.11.163 as innovation (c1, k60, u'innovation').
1557922363: Socket error on client innovation, disconnecting.
1557922364: New client connected from xx.xx.11.163 as innovation (c1, k60, u'innovation').
1557922463: Socket error on client innovation, disconnecting.
OK, the problem here is most likely that you are using a fixed client id (innovation) in the HTML.
You can only ever have 1 client connected with a given client id, so the broker will disconnect the oldest one when a new client with the same id connects (e.g. when you reload the page).
Try changing the connection line to something like this:
var clientID = "innovation_" + new Date().getTime();
client = new Paho.MQTT.Client(websocket, port, clientID);
Related
I am using Vertx for my backend.
This is a TCP server and the server is connected to several clients.
I am trying to disconnect the client when reaching a certain condition.
The code that I used is as follows.
vertx.createNetServer(new NetServerOptions().setIdleTimeout(601))
.connectHandler(socket -> {
Instant start = Instant.now();
writerId = socket.writeHandlerID();
log.info("[TCPServerVerticle] first Tcp Server Instance Id : {}", serverId);
socket.handler(input -> { // input을 받았을 때 실행
writerId = socket.writeHandlerID();
SocketAddress localAddr = socket.localAddress();
SocketAddress remoteAddr = socket.remoteAddress();
central.setWriterId(writerId);
byte[] bytes = input.getBytes();
String inputString = Utils.byteArrayToHex(bytes);
central.inputMessage(inputString, writerId, vertx, localAddr, remoteAddr, versionMap).onComplete(ok -> {
String result = ok.result();
if (result.equals("nak")) {
socket.close();
}
});
});
When I execute this code, when the condition for "nak" is met, the server seems to restart and not the client.
Would there be a way to close the connection to the client without restarting the server?
Thank you in advance
I'm trying to implement MQTT in my program using M2MQTT v4.3.0.0 (github), but when I try to connect using signed certificates my code cannot establish a connection. I'm on a Windows 10 system, and using C# with .NET 4.8. The version of Mosquitto I have installed is 2.0.10.
To make the server certificate I followed this tutorial:
http://www.steves-internet-guide.com/mosquitto-tls/#server
To make the client certificate I followed this tutorial:
http://www.steves-internet-guide.com/creating-and-using-client-certificates-with-mqtt-and-mosquitto/
I also made a host name in my etc/hosts file for 127.0.0.1 that points to localhost.conrad.com.
The configuration for my Mosquitto Broker is:
bind_address localhost.conrad.com
port 8883
allow_anonymous true
cafile C:/mosquitto/certs/ca.crt
keyfile C:/mosquitto/certs/server.key
certfile C:/mosquitto/certs/server.crt
require_certificate true
tls_version tlsv1.2
log_dest file C:/mosquitto/log/mosquitto.log
log_type error
log_type warning
log_type notice
log_type information
I successfully tested that this configuration works using Mosquitto's command line publish tool with
mosquitto_pub --cafile C:\mosquitto\certs\ca.crt --cert C:\mosquitto\certs\client.crt --key C:\mosquitto\certs\client.key -d -h localhost.conrad.com -p 8883 -t herp/derp/test -m "hi"
I received this message after using the command.
Client (null) sending CONNECT
Client (null) received CONNACK (0)
Client (null) sending PUBLISH (d0, q0, r0, m1, 'herp/derp/test', ... (2 bytes))
Client (null) sending DISCONNECT
My Mosquitto log confirms a successful connection:
1621547553: New connection from 127.0.0.1:57874 on port 8883.
1621547553: New client connected from 127.0.0.1:57874 as auto-6A8387C3-E091-0EC6-CED7-0A78BAA63099 (p2, c1, k60).
1621547553: Client auto-6A8387C3-E091-0EC6-CED7-0A78BAA63099 disconnected.
However when I try to connect using M2MQTT I run into a problem when trying to connect using signed certificates. My code is as follows:
int securePort = 8883;
MqttClient client = null;
string subTopic1 = "herp/derp/test";
string subTopic2 = "herp/derp/test2";
X509Certificate caCert = new X509Certificate("C:/mosquitto/certs/ca.crt");
X509Certificate clientCert = new X509Certificate("C:/mosquitto/certs/client.crt");
string clientID = "TestClientID";
public MQTTTest()
{
try
{
client = new MqttClient("localhost.conrad.com", securePort, true, caCert, clientCert, MqttSslProtocols.TLSv1_2, RemoteCertificateValidationCallback);
client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
client.MqttMsgPublished += client_MqttMsgPublished;
client.MqttMsgSubscribed += client_MqttMsgSubscribed;
client.ConnectionClosed += client_ConnectionClosed;
client.Connect(clientID, "", "", true, 1000);
client.Subscribe(new string[] { subTopic1, subTopic2 }, new byte[] { MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE, MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE });
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
I get the following exception when trying at client.Connect.
Exception message: "A call to SSPI failed, see inner exception."
Inner exception: "The message received was unexpected or badly formatted"
My Mosquitto logs show:
1621547793: New connection from 127.0.0.1:57896 on port 8883.
1621547793: OpenSSL Error[0]: error:1417C0C7:SSL routines:tls_process_client_certificate:peer did not return a certificate
1621547793: Client <unknown> disconnected: protocol error.
I can establish insecure connections just fine. As it is written my code also connects when I set require_certificate to false in my Mosquitto config file; however I am worried that if require_certificate is set to false that I won't have the security I want. Any help would be greatly appreciated.
Thanks to Brits' comment I was able to figure it out (link to answer). I made a pfx certificate and used that instead of using a crt.
Instead of...
X509Certificate caCert = new X509Certificate("C:/mosquitto/certs/ca.crt");
X509Certificate clientCert = new X509Certificate("C:/mosquitto/certs/client.crt");
I used...
X509Certificate2 caCert = new X509Certificate2("C:/mosquitto/certs/ca.pfx", "password");
X509Certificate2 clientCert = new X509Certificate2("C:/mosquitto/certs/client.pfx", "password");
I'm new at IoT & MQTT communication protocol. I'm trying to connect my broker which runs at Amazon Ec2 from my Vue web app via Websockets. I have started mosquitto with:
root#ip-xxx-xx-xx-xx:~# mosquitto -c /etc/mosquitto/conf.d/default.conf
1618518468: mosquitto version 1.6.7 starting
1618518468: Config loaded from /etc/mosquitto/conf.d/default.conf.
1618518468: Opening ipv4 listen socket on port 1883.
1618518468: Opening ipv6 listen socket on port 1883.
1618518468: Opening websockets listen socket on port 9001.
/etc/mosquitto/conf.d/default.conf file contains:
listener 1883
protocol mqtt
allow_anonymous true
listener 9001
protocol websockets
allow_anonymous true
My test js file is:
var mqtt = require('mqtt');
var count =0;
var client = mqtt.connect("mqtt://xx.xxx.xxx.xxx",{clientId:"mqttjs01"});
console.log("connected flag " + client.connected);
//handle incoming messages
client.on('message',function(topic, message, packet){
console.log("message is "+ message);
console.log("topic is "+ topic);
});
client.on("connect",function(){
console.log("connected "+ client.connected);
})
//handle errors
client.on("error",function(error){
console.log("Can't connect" + error);
process.exit(1)});
//publish
function publish(topic,msg,options){
console.log("publishing",msg);
if (client.connected == true){
client.publish(topic,msg,options);
}
count+=1;
if (count==2) //ens script
clearTimeout(timer_id); //stop timer
client.end();
}
//////////////
var options={
retain:true,
qos:1};
var topic="acs";
var message="test message";
var topic_list=["topic2","topic3","topic4"];
var topic_o={"topic22":0,"topic33":1,"topic44":1};
console.log("subscribing to topics");
client.subscribe(topic,{qos:0}); //single topic
client.subscribe(topic_list,{qos:1}); //topic list
client.subscribe(topic_o); //object
var timer_id=setInterval(function(){publish(topic,message,options);},5000);
//notice this is printed even before we connect
console.log("end of script");
But I'm getting this error:
New client connected from 176.xxx.xxx.xx as mqttjs01 (p2, c1, k60).
1618518546: Socket error on client mqttjs01, disconnecting.
I have installed libwebsockets, I have tried with various mosquitto versions. Current version is: 1.6.7.
Is there any problem with my client or broker? How can I fix this?
At the end of the publish() function the if statement is missing enclosing braces so it doesn't do what you think it does.
function publish(topic,msg,options){
console.log("publishing",msg);
if (client.connected == true){
client.publish(topic,msg,options);
}
count+=1;
if (count==2) //ens script
clearTimeout(timer_id); //stop timer
client.end();
}
Lets fix the indentation so we can see more clearly.
function publish(topic,msg,options){
console.log("publishing",msg);
if (client.connected == true){
client.publish(topic,msg,options);
}
count+=1;
if (count==2) //ens script
clearTimeout(timer_id); //stop timer
client.end();
}
As you can see client.end() will ALWAYS be called when ever publish() is called. If you only want to publish twice you need to wrap the 2 statements in the braces (this is not python where whitespace has meaning)
if (count==2) { //ens script
clearTimeout(timer_id); //stop timer
client.end();
}
You really should indent all your code properly it will make it much easier to read and to spot errors like this.
Also as #JDAllen mentioned you are not making use of the WebSocket connection, unless this code is running in the browser, where the sandbox will force it to be a WebSocket connection even if you specify mqtt:// as the schema in the URL, and you will have to include the port number to make it actually connect. e.g.
ws://xxx.xxx.xxx.xxx:9001
I have the following program through which I can detect the connection failure i.e doBeforeRetry.
Can someone tell me how to detect the successful connection or reconnection. I want to integrate a Health Check program that monitors this connection, but I am unable to capture the event that informs the connections is successfull.
Thanks
requester = RSocketRequester.builder()
.rsocketConnector(connector -> {
connector.reconnect(Retry
.fixedDelay(Integer.MAX_VALUE,Duration.ofSeconds(1))
.doBeforeRetry(e-> System.out.println("doBeforeRetry===>"+e))
.doAfterRetry(e-> System.out.println("doAfterRetry===>"+e))
);
connector.payloadDecoder(PayloadDecoder.ZERO_COPY);
}
).dataMimeType(MediaType.APPLICATION_CBOR)
.rsocketStrategies(strategies)
.tcp("localhost", 7999);
I achieved the detection of successful connection or reconnection with the following approach.
Client Side (Connection initialization)
Mono<RSocketRequester> requester = Mono.just(RSocketRequester.builder()
.rsocketConnector(
// connector configuration goes here
)
.dataMimeType(MediaType.APPLICATION_CBOR)
.setupRoute("client-handshake")
.setupData("caller-name")
.tcp("localhost", 7999)));
One the server side
#ConnectMapping("client-handshake")
public void connect(RSocketRequester requester, #Payload String callerName) {
LOG.info("Client Connection Handshake: [{}]", callerName);
requester
.route("server-handshake")
.data("I am server")
.retrieveMono(Void.class)
.subscribe();
}
On the client side, when I receive the callback on the below method, I detect the connection is successfull.
#MessageMapping("server-handshake")
public Mono<ConsumerPreference> handshake(final String response){
LOG.info("Server Connection Handshake received : Server message [{}]", response.getCallerName());
connectionSuccess.set(true);
return Mono.empty();
}else{
throw new InitializationException("Invalid response message received from Server");
}
}
Additionally, created a application level heartbeat to ensure, the liveliness of the connection.
If you want to know if it's actually healthy, you should probably have a side task that is polling the health of the RSocket, by sending something like a custom ping protocol to your backend. You could time that and confirm that you have a healthy connection, record latencies and success/failures.
We are facing issue in MQTT connection in HTTPS server. Sometime it is working fine and some time it is getting error like below.
WebSocket connection to 'wss://MYHOST:8083/mqtt' failed: Error in connection establishment: net::ERR_INSECURE_RESPONSE
Let me share with you my mosquitto.conf file.
pid_file /var/run/mosquitto.pid
persistence true
persistence_location /var/lib/mosquitto/
log_dest file /var/log/mosquitto/mosquitto.log
include_dir /etc/mosquitto/conf.d
listener 1883
listener 8083
protocol websockets
certfile /etc/mosquitto/certs/myhost.crt
cafile /etc/mosquitto/certs/ca.crt
keyfile /etc/mosquitto/certs/myhost.key
My Mosquitto WebSocket config file:
host = 'MYHOST'; // hostname or IP address
port = 8083;
topic = 'TOPIC'; // topic to subscribe to
useTLS = true;
username = "";
password = "";
path = "/mqtt";
cleansession = true;
Thanks.