I'm using pusher for push notifications in my laravel production web with cloud server. It's was working on localhost, then stopped working on localhost too and giving the error in console that channel is not defined.
Header:
<meta name="csrf-token" content="{{ csrf_token() }}">
<link rel="stylesheet" type="text/css"
href="//cdn.jsdelivr.net/npm/bootstrap-notifications#1.0.3/dist/stylesheets/bootstrap-notifications.min.css">
Body:
<script>
var notificationsWrapper = $('.dropdown');
var notificationsToggle = notificationsWrapper.find('a[data-toggle]');
var notificationsCountElem = notificationsToggle.find('i[data-count]');
var notificationsCount = parseInt(notificationsCountElem.data('count'));
var notifications = notificationsWrapper.find('ul.dropdown-menu');
if (notificationsCount <= 0) {
notificationsWrapper.hide();
}
// Enable pusher logging - don't include this in production
// Pusher.logToConsole = true;
const pusher = new Pusher('PUSHER_APP_KEY', {
cluster: 'ap2',
encrypted: true
});
// Bind a function to a Event (the full Laravel class)
channel.bind('App\\Events\\StatusLiked', function (data) {
var existingNotifications = notifications.html();
var avatar = Math.floor(Math.random() * (71 - 20 + 1)) + 20;
var newNotificationHtml = "" +
"<li class='notification active'><div class='media'>" +
"<div class='media-left'>" +
"<div class='media-object'>" +
"<img src='https://api.adorable.io/avatars/71/" + avatar + ".png' class='img-circle' alt='50x50' style='width: 50px; height: 50px;'>" +
"</div>" +
"</div>" +
"<div class='media-body'>" +
"<strong class='notification-title'>" + data.message + "</strong><!--p class='notification-desc'>Extra description can go here</p-->" +
"<div class='notification-meta'>" +
"<small class='timestamp'>about a minute ago</small>" +
"</div>" +
"</div>" +
"</div>" +
"</li>";
notifications.html(newNotificationHtml + existingNotifications).trigger('create');
notificationsCount += 1;
notificationsCountElem.attr('data-count', notificationsCount);
notificationsWrapper.find('.notif-count').text(notificationsCount);
notificationsWrapper.show();
});
</script>
The console prints Channel is is not defined.
You need to subscribe to a channel before binding to events on the channel. The Channels flow is:
1. Connect to the Channels service
2. Subscribe to channel(s)
3. Bind to events on the subscribed chanels.
As you have not included an Auth URL parameter to your Pusher object I can assume you are using public channels. You can subscribe to public channels using:
var channel = pusher.subscribe('CHANNEL-NAME');
NOTE: any published events are published to a channel, so you will need to ensure the channel you are subscribing to on the client matches the channel that you are publishing events to from the server.
Related
I am trying to mention a user in ms teams channel with the help of an adaptive card but there is no proper documentation for it and examples of the solution that is given here is not working? Has anybody has tried it please help with it
Are you using JS? I just posted a similar question, but it has a working solution for Users. I'm attempting to mention a bot though. Here is the post I just submitted
CardFactory.adaptiveCard({
$schema: 'http://adaptivecards.io/schemas/adaptive-card.json',
type: 'AdaptiveCard',
msteams: {
entites: [
{
type: 'mention',
text: '<at>(username)</at>',
mentioned: {
id: <userID>,
name: <username>,
role: 'user'
}
}
]
}
body: [
{
type: 'TextBlock',
text: '<at>(userName)</at>',
}
]
});
This is the example I give
I used to use html to format cards in conversation bot. I think html is very flexible and here is my code.
private async Task showTeamStatus(ITurnContext<IMessageActivity> turnContext, CancellationToken cancellationToken)
{
MyInfo myInfo = new MyInfo();
List <BotDataEntity> res = await myInfo.RunAsync();
var card = new HeroCard();
card.Title = "xxxx";
var html = "<div>" +
"<div style='height:40px;line-height:40px;text-align:center;'>" +
"<div style='width:26%;float:left;text-align:left;'>Name</div>" +
"<div style='width:20%;float:left;'>Log</div>" +
"<div style='width:14%;float:left;'>Case</div>" +
"<div style='width:14%;float:left;'>Task</div>" +
"<div style='width:26%;float:left;'>IPD</div>" +
"</div>";
for (int i = 0; i < res.Count; i++)
{
html += "<div style='height:28px;line-height:28px;text-align:center;'>" +
"<div style='float:left;width:26%;font-size:10px;text-align:left;'>" + res[i].userName + "</div>" +
"<div style='float:left;width:20%;'>" + res[i].log + "</div>" +
"<div style='float:left;width:14%;'>" + res[i].case + "</div>" +
"<div style='float:left;width:14%;'>" + res[i].task + "</div>" +
"<div style='float:left;width:26%;'>" + res[i].ipd + "</div>" +
"</div>";
}
html += "</div> ";
card.Text = html;
var activity = MessageFactory.Attachment(card.ToAttachment());
await turnContext.SendActivityAsync(activity, cancellationToken);
}
You want to 'mention a user in ms teams channel', I think this document may help you. It provides a sample on 'Post a proactive message in a Teams channel and mention a user in it'.
I have a collection of beacons that I want to show on a map. I want their positions to be synchronized between all instances of the application.
That is, when I move a beacons to another position I want this change to be reflected in the other instances of the application.
This using the Parse javascript SDK in its version 1.11.0.
I have defined the following Parse model, which represents each object in the collection saved on the server:
var Baliza = Parse.Object.extend("Balizas");
Baliza.prototype.show = function(){
var self = this;
var start= '<div class="row" style="width: 350px;">\n' +
' <div class="control-group" id="fields">\n' +
' <label class="control-label" style="text-align: center;" for="field1">Introducir Mac Asociadas a Ese Punto</label>\n' +
' <div class="controls">\n' +
' <form id="form" role="form" autocomplete="off">';
var tmp = '';
tmp = tmp + '<div class="entry input-group col-xs-12">\n' +
' <input class="form-control" name="fields[]" type="text" value="'+self.get("mac")[0]+'">\n' +
' <span class="input-group-btn">\n' +
' <button baliza-id='+self.id+' class="btn btn-success btn-add" type="button">\n' +
' <span class="glyphicon glyphicon-plus"></span>\n' +
' </button>\n' +
' </span>\n' +
' </div>';
if (self.get("mac").length>1){
for (var i=1; i<self.get("mac").length; i++) {
tmp = tmp + '<div class="entry input-group col-xs-12">\n' +
' <input class="form-control" name="fields[]" type="text" value="'+self.get("mac")[i]+'">\n' +
' <span class="input-group-btn">\n' +
' <button baliza-id='+self.id+' class="btn btn-remove col-xs-12" type="button">\n' +
' <span class="glyphicon glyphicon-minus"></span>\n' +
' </button>\n' +
' </span>\n' +
' </div>';
}
}
var end = '</form>\n' +
' <br>\n' +
' <button type="button" baliza-id='+self.id+' class="btn btn-block btn-info btn-sm ">Salvar</button>\n' +
' <button type="button" baliza-id='+self.id+' class="btn btn-block btn-danger btn-sm ">Eliminar</button>\n' +
' </div>\n' +
' </div>\n' +
'</div>';
//console.log('impirmiendo marker');
//console.log(this.marker);
console.log("Localización -> ", self.get("localizacion"));
if(self.marker != null) {
self.marker.setLatLng(new L.LatLng(self.get("localizacion").latitude, self.get("localizacion").longitude),{draggable:'true'});
} else {
self.marker = new L.marker([ self.get("localizacion").latitude, self.get("localizacion").longitude], {
icon: L.AwesomeMarkers.icon({icon: 'certificate', prefix: 'glyphicon', markerColor: 'blue'}),
draggable: 'true'
}).bindPopup("", {maxWidth: 560});
self.marker.on('dragend', function(event){
var position = event.target.getLatLng();
console.log("Notify new Location -> ", position.lat, position.lng);
//Enviamos El Dato a Parse
this.set("localizacion", new Parse.GeoPoint(position.lat, position.lng));
this.save(null, {
success: function (balizaSaved) {
console.log("Baliza Guardad con éxito: ", balizaSaved);
},
error: function (baliza, error) {
alert('Failed to create new object, with error code: ' + error.message);
}
});
}.bind(this));
map.addLayer(self.marker);
}
self.marker.getPopup().setContent(start+tmp+end);
};
The code responsible for notifying the change of position in the map is the following:
self.marker.on('dragend', function(event){
var position = event.target.getLatLng();
console.log("Notify new Location -> ", position.lat, position.lng);
//Enviamos El Dato a Parse
this.set("localizacion", new Parse.GeoPoint(position.lat, position.lng));
this.save(null, {
success: function (balizaSaved) {
console.log("Baliza Guardad con éxito: ", balizaSaved);
},
error: function (baliza, error) {
alert('Failed to create new object, with error code: ' + error.message);
}
});
}.bind(this));
The subscription was created as follows,
var query = new Parse.Query(Baliza);
var subscription = query.subscribe();
var mapaBalizasParse = new Map();
// After specifying the Monster subclass...
//Parse.Object.registerSubclass('Balizas',Baliza);
subscription.on('create', function (balizaCreated) {
console.log("New baliza created -> ", balizaCreated.toJSON());
var baliza = new Baliza(balizaCreated.toJSON());
baliza.show();
mapaBalizasParse.set(baliza.id, baliza);
});
subscription.on('update', function (balizaSaved) {
console.log('BALIZA ACTUALIZADA -> ', balizaSaved.toJSON());
var baliza = mapaBalizasParse.get(balizaSaved.id);
baliza.set("mac", balizaSaved.get("mac"));
baliza.set("localizacion", balizaSaved.get("localizacion"));
baliza.show();
});
subscription.on('delete', function (baliza) {
//console.log(mapaBalizasParse.get(baliza.id));
map.removeLayer(mapaBalizasParse.get(baliza.id).marker);
mapaBalizasParse.delete(baliza.id);
});
subscription.on('leave', function (balizaLeave) {
console.log('Leave called -> ', balizaLeave.id, balizaLeave.get("localizacion"));
});
subscription.on('enter', function (balizaCalled) {
console.log('Enter called -> ', balizaCalled.id, balizaCalled.get("localizacion"));
});
Each time I click on a position on the map I create a Beacons as follows:
function onMapClick(e) {
var baliza = new Baliza();
baliza.set("localizacion",new Parse.GeoPoint(e.latlng.lat, e.latlng.lng));
baliza.set("mac",["11:22:33:44:55:10"]);
baliza.set("editando",true);
baliza.save(null, {
success: function(baliza) {
//Añadimos La Baliza Al Mapa Interno
//mapaBalizasParse.set(baliza.id,baliza);
//baliza.show();
},
error: function(baliza, error) {
alert('Failed to create new object, with error code: ' + error.message);
}
});
}
The list of currently registered "beacons" is shown as follows:
query.find({
success: function(results) {
console.log("Total Balizas -> " + results.length);
for (var i = 0; i < results.length; i++) {
var currentBaliza = results[i];
console.log("Baliza " + i + " -> ", currentBaliza);
currentBaliza.show();
mapaBalizasParse.set(currentBaliza.id, currentBaliza);
}
},
error: function(error) {
console.log("Error: " + error.code + " " + error.message);
}
});
The problem is if for example I move the beacon from position ( latitude: 40.961229844235234, longitude: -5.669621229171753 ) to another point in the map (latitude: 40.9604196476232, longitude: -5.6707102060318)
The other instances of the application receive in the update event the old version of the object, its location field has not changed ( latitude: 40.961229844235234, longitude: -5.669621229171753 )
Someone can tell me what I'm doing wrong in the code.
Thanks in advance.
I have been doing some test with minimal configuration and this is that I saw:
In the callback for loading all beacons in the map set you use this code:
var beacon = new Baliza({id: baliza.id, localizacion:
baliza.get("localizacion") , mac: baliza.get("mac"), editando:
baliza.get("editando")});
but when you add a new beacon created in the callback of 'create' event, you use this one:
var beacon = new Baliza();
beacon.id = baliza.id;
beacon.localizacion = baliza.get("localizacion");
beacon.mac = baliza.get("mac");
beacon.editando = baliza.get("editando");
In my tests, if you use the first code the beacons updates normally, but if you use the second one, a old version of the beacon is logged in javascript console.
It seems that something special happens in the empty constructor that you are not including in the overloaded constructor.
I hope that it helps you. :)
Here my complete code:
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Simple test parse JS</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<input type="text" id="txtIndex" class="textbox" value="1">
<button type="button" class="btn-add">Add beacon</button>
<button type="button" class="btn-modify">Modify beacon</button>
<button type="button" class="btn-remove">Remove beacon</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="http://chancejs.com/chance.min.js"></script>
<script src="https://unpkg.com/parse#1.11.0/dist/parse.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!-- Own JS-->
<script src="./js/demo_parse.js"></script>
</body>
</html>
JS
var mapBeacons = new Map();
var query;
var subscription;
var Baliza;
function loadAllBeacons(){
query.find({
success: function(results) {
for (var i = 0; i < results.length; i++) {
//Vamos Creando Los Objetos Que Recibimos
var beacon = new Baliza();
beacon.id = results[i].id;
beacon.localizacion = results[i].get("localizacion");
beacon.mac = results[i].get("mac");
mapBeacons.set(beacon.id,beacon);
}
},
error: function(error) {
console.log("Error: " + error.code + " " + error.message);
}
});
}
function modifyBeacon(){
var key = $("#txtIndex").val();
var baliza = mapBeacons.get(key);
var my_chance = new Chance();
var randomLocation = new Parse.GeoPoint(my_chance.latitude(), my_chance.longitude())
baliza.set("localizacion",randomLocation);
baliza.save(null, {
success: function(baliza) {
// Execute any logic that should take place after the object is saved.
mapBeacons.set(baliza.id,baliza);
},
error: function(baliza, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and message.
alert('Failed to remove new object, with error code: ' + error.message);
}
});
}
function removeBeacon(){
var key = $("#txtIndex").val();
var baliza = mapBeacons.get(key);
baliza.destroy({
success: function(myObject) {
// The object was deleted from the Parse Cloud.
//map.removeLayer(baliza.marker);
//mapaBalizasParse.delete($(this).attr('id'));
console.log("Beacon removed sucessfully");
console.log(myObject);
},
error: function(myObject, error) {
// The delete failed.
// error is a Parse.Error with an error code and message.
}
});
}
function addNewBeacon(){
var baliza = new Baliza();
var my_chance = new Chance();
var randomLocation = new Parse.GeoPoint(my_chance.latitude(), my_chance.longitude())
baliza.set("localizacion",randomLocation);
baliza.set("mac",["11:22:33:44:55:10"]);
baliza.set("editando",true);
baliza.save(null, {
success: function(baliza) {
console.log("OnSave Beacon saved sucessfully");
console.log(baliza);
},
error: function(baliza, error) {
alert('Failed to create new object, with error code: ' + error.message);
}
});
}
$(function() {
console.log( "ready!" );
//Init parse
Parse.initialize("6xuPkPgqEfCdzXwaxAfUuKbTAglJL5ALa1mmY8de");
Parse.serverURL = 'http://encelocalizacion.com:1337/parse';
//Objeto Ppara interacturar con el Objeto Baliza de Parser
Baliza = Parse.Object.extend("Balizas", {
/**
* Instance properties go in an initialize method
*/
id: '',
localizacion: '',
mac:'',
marker:'',
popup:'',
initialize: function (attr, options) {
}
});
query = new Parse.Query(Baliza);
subscription = query.subscribe();
// Subscription for create
subscription.on('create', function (baliza) {
// TODO CHANGE THIS
var beacon = new Baliza({id: baliza.id, localizacion: baliza.get("localizacion") , mac: baliza.get("mac"), editando: baliza.get("editando")});
/*
var beacon = new Baliza();
beacon.id = baliza.id;
beacon.localizacion = baliza.get("localizacion");
beacon.mac = baliza.get("mac");
beacon.editando = baliza.get("editando");
*/
mapBeacons.set(beacon.id,beacon);
console.log("New beacon added to BBDD")
console.log(mapBeacons)
});
// Subscription for update
subscription.on('update', function (kk) {
console.log('Updated beacon:' + kk.get("localizacion").latitude + " " + kk.get("localizacion").longitude + " " + kk.get("mac")+ " " + kk.get("id"));
});
// Subscription for delete
subscription.on('delete', function (kk) {
mapBeacons.delete(kk.id);
console.log('Deleted beacon:' + kk.get("localizacion").latitude + " " + kk.get("localizacion").longitude + " " + kk.get("mac"));
console.log(mapBeacons)
});
loadAllBeacons();
$(document).on('click', '.btn-add', function(e) {
addNewBeacon();
}).on('click', '.btn-remove', function(e) {
removeBeacon();
return false;
}).on('click', '.btn-modify', function(e) {
modifyBeacon();
});
});
i'm developping a chat application using gos socketBundle i'm trying to show connected users using this code in javascript .
when the subscribe is done to the channel connected users always connectedUsers are null?? could any one help me please ?
{{ ws_client()}}
<script type="text/javascript">
var websocket = WS.connect("ws://127.0.0.1:8080");
//var websocket = WS.connect("ws://{#{{ wsUrl }}#})");
websocket.on("socket/connect", function (session) {
session.subscribe("connected-users/channel", function (uri, payload) {
console.log(session);
console.log(payload);
var connectedUsers = JSON.parse(payload.connectedUsers);
var newtml = '';
connectedUsers.forEach(function (user) {
newtml += '<a name="toggle" class="connectedUserLink" onclick="talkToUser(\'' + user.id + '\', \'' + user.username + '\')">' + user.username + '</a>';
});
$('#connectedUserNbr').html(connectedUsers.length);
$('#connectedUserList').html(newtml);
});
});
websocket.on("socket/disconnect", function (error) {
//error provides us with some insight into the disconnection: error.reason and error.code
console.log("Disconnected for " + error.reason + " with code " + error.code);
});
</script>
This question has been asked several times, but any of the answers is a solution to my problem.
issue:
There will be multiple accounts, and accounds will have multible users. In one specific account, the users will do some realtime updates - but the other accounts will be not affected from those real time changes, every accounts will be private.
We are planing to create room names for each account from cookie
Also we are using node in PHP project.
Sorry for my broken English!
// client side code
$( "#messageForm" ).submit( function() {
var nameVal = $( "#nameInput" ).val();
var msg = $("#messageInput").val();
socket.emit( 'message', { name: nameVal, message: msg } );
// Ajax call for saving datas
$.ajax({
url: "./ajax/insertMessage.php",
type: "POST",
data: { name: nameVal, message: msg },
success: function(data) {
}
});
return false;
});
socket.on( 'message', function( data ) {
var actualContent = $( "#messages" ).html();
var newMsgContent = '<li> <strong>' + data.name + '</strong> : ' + data.message + '</li>';
var content = newMsgContent + actualContent;
$( "#messages" ).append( newMsgContent );
});
//server side codes
var socket = require( 'socket.io' );
var express = require( 'express' );
var http = require( 'http' );
var app = express();
var server = http.createServer( app );
var io = socket.listen( server );
io.sockets.on( 'connection', function( client ) {
console.log( "New client !" );
client.on( 'message', function( data ) {
console.log( 'Message received ' + data.name + ":" + data.message );
//client.broadcast.emit( 'message', { name: data.name, message: data.message } );
io.sockets.emit( 'message', { name: data.name, message: data.message } );
});
});
server.listen( 8080 );
You can create private chat rooms as below.
Server side code
// usernames which are currently connected to the chat
var usernames = {};
// rooms which are currently available in chat
var rooms = ['room1','room2','room3'];
io.sockets.on('connection', function (socket) {
// when the client emits 'adduser', this listens and executes
socket.on('adduser', function(username){
// store the username in the socket session for this client
socket.username = username;
// store the room name in the socket session for this client
socket.room = 'room1';
// add the client's username to the global list
usernames[username] = username;
// send client to room 1
socket.join('room1');
// echo to client they've connected
socket.emit('updatechat', 'SERVER', 'you have connected to room1');
// echo to room 1 that a person has connected to their room
socket.broadcast.to('room1').emit('updatechat', 'SERVER', username + ' has connected to this room');
socket.emit('updaterooms', rooms, 'room1');
});
// when the client emits 'sendchat', this listens and executes
socket.on('sendchat', function (data) {
// we tell the client to execute 'updatechat' with 2 parameters
io.sockets.in(socket.room).emit('updatechat', socket.username, data);
});
socket.on('switchRoom', function(newroom){
// leave the current room (stored in session)
socket.leave(socket.room);
// join new room, received as function parameter
socket.join(newroom);
socket.emit('updatechat', 'SERVER', 'you have connected to '+ newroom);
// sent message to OLD room
socket.broadcast.to(socket.room).emit('updatechat', 'SERVER', socket.username+' has left this room');
// update socket session room title
socket.room = newroom;
socket.broadcast.to(newroom).emit('updatechat', 'SERVER', socket.username+' has joined this room');
socket.emit('updaterooms', rooms, newroom);
});
// when the user disconnects.. perform this
socket.on('disconnect', function(){
// remove the username from global usernames list
delete usernames[socket.username];
// update list of users in chat, client-side
io.sockets.emit('updateusers', usernames);
// echo globally that this client has left
socket.broadcast.emit('updatechat', 'SERVER', socket.username + ' has disconnected');
socket.leave(socket.room);
});
});
Client side code
var socket = io.connect('http://localhost:8080');
// on connection to server, ask for user's name with an anonymous callback
socket.on('connect', function(){
// call the server-side function 'adduser' and send one parameter (value of prompt)
socket.emit('adduser', prompt("What's your name?"));
});
// listener, whenever the server emits 'updatechat', this updates the chat body
socket.on('updatechat', function (username, data) {
$('#conversation').append('<b>'+username + ':</b> ' + data + '<br>');
});
// listener, whenever the server emits 'updaterooms', this updates the room the client is in
socket.on('updaterooms', function(rooms, current_room) {
$('#rooms').empty();
$.each(rooms, function(key, value) {
if(value == current_room){
$('#rooms').append('<div>' + value + '</div>');
}
else {
$('#rooms').append('<div>' + value + '</div>');
}
});
});
function switchRoom(room){
socket.emit('switchRoom', room);
}
// on load of page
$(function(){
// when the client clicks SEND
$('#datasend').click( function() {
var message = $('#data').val();
$('#data').val('');
// tell server to execute 'sendchat' and send along one parameter
socket.emit('sendchat', message);
});
// when the client hits ENTER on their keyboard
$('#data').keypress(function(e) {
if(e.which == 13) {
$(this).blur();
$('#datasend').focus().click();
}
});
});
</script>
<div style="float:left;width:100px;border-right:1px solid black;height:300px;padding:10px;overflow:scroll-y;">
<b>ROOMS</b>
<div id="rooms"></div>
</div>
<div style="float:left;width:300px;height:250px;overflow:scroll-y;padding:10px;">
<div id="conversation"></div>
<input id="data" style="width:200px;" />
<input type="button" id="datasend" value="send" />
</div>
Reference Link:
http://psitsmike.com/2011/10/node-js-and-socket-io-multiroom-chat-tutorial/
is it possible to work with websockets and cloudmqtt?
I have following code but nothing is working.
First I use the mqttw31.js from Paho and in my host file I define all the connection details.
src="js/mqttws31.js" type="text/javascript">
src="js/host.js" type="text/javascript">
var mqtt;
var reconnectTimeout = 2000;
function MQTTconnect() {
mqtt = new Paho.MQTT.Client(
host,
port,
"web_" + parseInt(Math.random() * 100,
10));
var options = {
timeout: 3,
useSSL: useTLS,
cleanSession: cleansession,
onSuccess: onConnect,
onFailure: function (message) {
$('#status').val("Connection failed: " + message.errorMessage + "Retrying");
setTimeout(MQTTconnect, reconnectTimeout);
}
};
mqtt.onConnectionLost = onConnectionLost;
mqtt.onMessageArrived = onMessageArrived;
if (username != null) {
options.userName = username;
options.password = password;
}
console.log("Host="+ host + ", port=" + port + " TLS = " + useTLS + " username=" + username + " password=" + password);
mqtt.connect(options);
}
function onConnect() {
$('#status').val('Connected to ' + host + ':' + port);
// Connection succeeded; subscribe to our topic
mqtt.subscribe(topic, {qos: 0});
$('#topic').val(topic);
mqtt.publish("/arduino/commando/", "test Intel");
}
function onConnectionLost(response) {
setTimeout(MQTTconnect, reconnectTimeout);
$('#status').val("connection lost: " + responseObject.errorMessage + ". Reconnecting");
};
function onMessageArrived(message) {
var topic = message.destinationName;
var payload = message.payloadString;
$('#ws').prepend('<li>' + topic + ' = ' + payload + '</li>');
};
$(document).ready(function() {
MQTTconnect();
});
<header>
<h2>MQTT Test</h2>
</header>
<div>
Subscribed to <input type='text' id='topic' disabled />
Status: <input type='text' id='status' size="80" disabled />
<ul id='ws' style="font-family: 'Courier New', Courier, monospace;"></ul>
</div>
In the host file:
host = 'm20.cloudmqtt.com'; // hostname or IP address
port = 13365;
topic = '/arduino/status/'; // topic to subscribe to
useTLS = false;
username = "test";
password = "test";
cleansession = true;
Use port 33365 and set useTLS to true.
A quick look at the cloudmqtt.com doc doesn't mention websockets anywhere.
Assuming they are running Mosquitto 1.4, this does not use the same port for native MQTT and MQTT over websockets so if they are only providing you with 1 port number then it really isn't going to work.