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.
Related
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.
I am learning AWS and as part of that I am trying to create a Lambda using node.js.
I am trying to invoke a webpage using the following, please correct me. What I am missing?
const opn = require('opn');
opn('http://google.com', {app: 'firefox'});
I wrote up a post detailing how to set this up if you only want to hit URLs with Lambda. You can find it here.
If you already know how to setup IAM permissions and scheduling with CloudWatch, the code I used accomplished this with Node.js 6.10 runtime:
exports.handler = (event, context, callback) => {
var urls = event.urls;
var http = require("http");
var https = require("https");
for (var i = 0; i < urls.length; i++) {
var protocol = urls[i].Protocol;
var domain = urls[i].Domain;
var queryString = urls[i].QueryString;
var url = protocol + "://" + domain + queryString;
if (protocol.toLowerCase() === "http") {
var j = i;
http.get(url, function(res) {
// Get around async.
var requestUrl = urls[j].Protocol + "://" + urls[j].Domain + urls[j].QueryString;
console.log("Response from " + requestUrl + ": ");
console.log(res.statusCode);
console.log(res.statusMessage);
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
} else if (protocol.toLowerCase() === "https") {
https.get(url, function(res) {
var j = i;
// Get around async.
var requestUrl = urls[j].Protocol + "://" + urls[j].Domain + urls[j].QueryString;
console.log("Response from " + requestUrl + ": ");
console.log(res.statusCode);
console.log(res.statusMessage);
}).on('error', function(e) {
console.log("Encountered error: " + e.message);
});
}
// Force break due to async -> output.
if ((i+1) == urls.length) {
break;
}
}
};
You would define the URLs you would like to invoke by passing an event object that is similar to the following:
{"urls": [{
"Protocol": "HTTP",
"Domain": "www.aaronmedacco.com",
"QueryString": ""}, {
"Protocol": "HTTPS",
"Domain": "www.google.com",
"QueryString": "?key=value"}]}
Again, if you want a step by step, check out this post. Simple to set up.
When a developer checks in code through a GIT push to AWS codecommit, I want to register an event in our ERP package Exact Online. This allows a project manager to review from within the ERP package the commits.
AWS Codecommit only supports triggers through SNS and Lambda; there is no hookup for batch files or so. I've been playing around with AWS Lambda and managed to post an event from AWS Codecommit to Slack, but to Exact Online it seems harder.
How can I post the GIT event of code commit to a business object in Exact Online?
The best way is to use a combination of AWS Lambda and Invantive Data Access Point, using a script such as:
console.log('Loading function codecommit2slack.');
const aws = require('aws-sdk');
const codecommit = new aws.CodeCommit({ apiVersion: '2015-04-13', region: 'eu-west-1' });
const querystring = require('querystring');
const https = require('https');
const url = require('url');
//
// To get the slack hook url, go into slack admin and create a new "Incoming Webhook" integration.
//
const slack_url = 'https://hooks.slack.com/services/SECRET/STUFF';
const slack_req_opts = url.parse(slack_url);
slack_req_opts.method = 'POST';
slack_req_opts.headers = {'Content-Type': 'application/json'};
exports.handler = function(event, context)
{
console.log('Run codecommit2slack.');
(event.Records || []).forEach(function (rec)
{
var details = rec.codecommit.references[0];
var commitId = details.commit;
var ref = details.ref;
var repository = rec.eventSourceARN.split(":")[5];
console.log("Repo " + repository + ", commit ID " + commitId + " on " + ref);
var params =
{ commitId: commitId
, repositoryName: repository
};
codecommit.getCommit
( params
, function(err, data)
{
if (err) console.log(err, err.stack); // an error occurred
else
{
var commitMessage = data.commit.message;
var authorName = data.commit.author.name;
var committerName = data.commit.committer.name;
console.log(commitMessage);
var postData = querystring.stringify
(
{ 'connection': 'PUBLIC\\Exact Online (nl)'
, 'format': 'Xml'
, 'query': "insert into events(description, enddate, notes, startdate, status) values ('" + repository + ": " + commitMessage.replace(/[^\x20-\x7E]/gmi, "") + "', sysdate, '" + committerName + " / " + commitId + "', sysdate, 50)"
}
)
;
var daphttpoptions =
{ host: "data-access-point.com"
, port: 443
, path: '/eol/stable/dap/Results'
, auth: 'EXACT-ONLINE-USER' + ":" + 'EXACT-ONLINE-PASSWORD'
, method: 'POST'
, headers:
{ 'Content-Type': 'application/x-www-form-urlencoded'
, 'Content-Length': Buffer.byteLength(postData)
}
}
var dapreq = https.request
( daphttpoptions
, function (res)
{
if (res.statusCode === 200)
{
console.log('posted to DAP');
context.succeed('posted to DAP');
}
else
{
console.log('post to DAP failed with status code: ' + res.statusCode);
context.fail('status code: ' + res.statusCode);
}
}
);
dapreq.on
( 'error'
, function(e)
{
console.log('problem with DAP request: ' + e.message);
context.fail(e.message);
}
);
//
// Send to Data Access Point.
//
dapreq.write(postData);
dapreq.end();
var req = https.request
( slack_req_opts
, function (res)
{
if (res.statusCode === 200)
{
console.log('posted to slack');
context.succeed('posted to slack');
}
else
{
console.log('post to slack failed with status code: ' + res.statusCode);
context.fail('status code: ' + res.statusCode);
}
}
);
req.on
( 'error'
, function(e)
{
console.log('problem with Slack request: ' + e.message);
context.fail(e.message);
}
);
//
// Send to development-audit channel.
//
req.write(JSON.stringify({username: committerName, as_user: true, text: commitMessage + " on " + repository + " (ID: " + commitId + ", ref " + ref + ")", channel: '#development-audit'}));
req.end();
}
}
);
});
};
console.log('Finished loading function codecommit2slack.');
This script also includes a post to Slack. First version of code based upon https://gist.github.com/vgeshel/1dba698aed9e8b39a464, thx.
The result in Exact Online will look something like this, but ofcourse you can also use it to create for instance an article or a Serial Number for each new commit or tag:
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>
I have developed a ASP.NET MVC application with signalr to display the records on the page.
My table has five columns (jobid [int], name[varchar], lastexecutiondate[datetime],status[int],imageurl[string])
Here is my markup from view page:
<script type="text/javascript">
$(function () {
// Proxy created on the fly
var job = $.connection.jobHub;
// Declare a function on the job hub so the server can invoke it
job.client.displayStatus = function () {
getData();
};
// Start the connection
$.connection.hub.start();
getData();
});
function getData() {
var $tbl = $('#tblJobInfo');
$.ajax({
url: '../api/values',
type: 'GET',
datatype: 'json',
success: function (data) {
if (data.length > 0) {
$tbl.empty();
$tbl.append(' <tr><th>ID</th><th>Name</th><th>Last Executed Date</th><th>Status</th><th>Image URL</th></tr>');
var rows = [];
for (var i = 0; i < data.length; i++) {
rows.push(' <tr><td>' + data[i].JobID + '</td><td>' + data[i].Name + '</td><td>' + data[i].LastExecutionDate.toString().substr(0, 10) + '</td><td>' + data[i].Status + '</td><td>' + data[i].imageurl + '</td></tr>');
}
$tbl.append(rows.join(''));
}
}
});
}
</script>
</head>
<body>
<div>
<table id="tblJobInfo" style="text-align:center;margin-left:10px">
</table>
</div>
</body>
And below is my code to get the data from database
SqlDependency.Start(connection.ConnectionString);
using (var reader = command.ExecuteReader())
return reader.Cast<IDataRecord>()
.Select(x => new JobInfo()
{
JobID = x.GetInt32(0),
Name = x.GetString(1),
LastExecutionDate = x.GetDateTime(2),
Status = x.GetString(3),
imageurl = x.GetString(4)
}).ToList();
I want to display the image instead of the URL.
You should just need to create an image tag in your JavaScript table row function:
for (var i = 0; i < data.length; i++) {
rows.push(' <tr><td>' + data[i].JobID + '</td><td>' + data[i].Name + '</td><td>' + data[i].LastExecutionDate.toString().substr(0, 10) + '</td><td>' + data[i].Status + '</td><td><img src="' + data[i].imageurl + '"/></td></tr>');
}
I can think of a couple of ways to address your comment below. In code, create a helper function to do this for you:
SqlDependency.Start(connection.ConnectionString);
using (var reader = command.ExecuteReader())
return reader.Cast<IDataRecord>()
.Select(x => new JobInfo()
{
JobID = x.GetInt32(0),
Name = x.GetString(1),
LastExecutionDate = x.GetDateTime(2),
Status = x.GetString(3),
imageurl = GetImageUrl(x.GetString(3))
}).ToList();
private string GetImageUrl(int status){
switch(status){
case 1:
return "some.jpg"
case 2:
return "someother.jpg"
default:
return "blank.jpg"
}
}
I don't know your code that well, so this assumes that your select is not being cast to a SQL statement (it doesn't appear that it is).
To do the same thing client side, you would implement the GetImageUrl function as a JavaScript function and to the same type of thing.
for (var i = 0; i < data.length; i++) {
rows.push(' <tr><td>' + data[i].JobID + '</td><td>' + data[i].Name + '</td><td>' + data[i].LastExecutionDate.toString().substr(0, 10) + '</td><td>' + data[i].Status + '</td><td><img src="' + GetImageUrl(data[i].Status) + '"/></td></tr>');
}
function GetImageUrl(status){
switch(status){
case 1:
return "some.jpg"
case 2:
return "someother.jpg"
default:
return "blank.jpg"
}
}