Nodejs web application for mqtt using jquery - javascript

I want to design a web app capable of publishing message on mqtt broker when a switch state is changed or a form is filled and submitted etc. I am able to publish the message using mqtt library on node. I am also able to detect the normal switch state when it is changed on html page using javascript and jquery. Now I want to call the mqtt publish function from node app here. How will I do it?
Here is the normal html file switch.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="switch.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="switch.js"></script>
</head>
<body>
<h2>Toggle Switch</h2>
<label class="switch" id = "switchLabel1">
<input type="checkbox" id = "switch1">
<div class="slider round"></div>
</label>
</body>
</html>
The javascript that detects the switch state switch.js
$( document ).ready(function() {
$('#switch1').attr('checked', true);
$('#switch1').click(function(){
if($(this).prop("checked") == true){
console.log("switch1 is checked.");
}
else if($(this).prop("checked") == false){
console.log("switch1 is unchecked.");
}
});
});
The Nodejs app publishing message to mqtt index.js. MQTT library is installed using npm.
var mqtt = require('mqtt')
var client = mqtt.connect('mqtt://192.168.15.3')
client.on('connect', function () {
client.subscribe('mqtt_node_subscribe')
client.publish('mqtt_node_publish', 'Hello mqtt')
})
client.on('message', function (topic, message) {
// message is Buffer
console.log(message.toString())
})
What I want to do is call client.publish("topic", "message") when instead of console.log in switch.js
When I do that it says client not defined, so I tried merging both js and running node, it says $ not defined. I tried including jquery in node app, it says window missing. So I need a method to serve this web application using node and use jquery etc as is.

MQTT over a websocket is a difficult approach. The same work can be done using socket.io. It is a js based library giving capabilities of topics publish and subscribe messages. Give it a try.

Related

Apache Guacamole JS not rendering in web application

I'm using the apache guacamole-common-js library to allow rdp access to VMs within my web application via Apache Guacamole. I have an instance of guacamole and the client up and running on a server and I'm attempting to connect to tunnel to my instance via web sockets. I can see from the developer tools and server side logs that the web socket connection is working and that commands are being passed b/t my web application and the server, however the UI is never displayed.
I'm following all the examples I've been able to find, to no avail. I am testing this locally with a connection to the server, so it is a cross domain scenario, however as I mentioned the traffic b/t client and server appears to be working as expected. It's simply not rendering anything visually. When I look at the DOM, I can see elements injected that represent the guacamole client display elements. My code is as follows:
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" type="text/css" href="guacamole.css">
<title>Guacamole (EXAMPLE)</title>
</head>
<body>
<!-- Display -->
<div id="display" style="background-color: #f0f0f0; height: 500px; width: 500px;"></div>
<!-- Guacamole JavaScript API -->
<script type="text/javascript" src="https://myserver.com/guacamole-common-js/all.min.js"></script>
<!-- Init -->
<script type="text/javascript"> /* <![CDATA[ */
// Get display div from document
var display = document.getElementById("display");
var wsFullUrl = "wss://myserver.com/websocket-tunnel?token=CB3A548656A5A0F5470AD0A51BE79883B864A4FF8B0308F87F53F8FBC49BA74F&GUAC_DATA_SOURCE=mysql&GUAC_ID=3&GUAC_TYPE=c&GUAC_WIDTH=500&GUAC_HEIGHT=500&GUAC_DPI=192&GUAC_TIMEZONE=America/Chicago&GUAC_AUDIO=audio/L8&GUAC_AUDIO=audio/L16&GUAC_IMAGE=image/jpeg&GUAC_IMAGE=image/png&GUAC_IMAGE=image/webp";
// Instantiate client, using an HTTP tunnel for communications.
var guac = new Guacamole.Client(
new Guacamole.WebSocketTunnel(wsFullUrl)
);
var element = guac.getDisplay().getElement();
// Add client to display div
display.appendChild(element);
// Error handler
guac.onerror = function (error) {
alert(error);
};
// Connect
guac.connect();
// Disconnect on close
window.onunload = function () {
guac.disconnect();
}
// Mouse
var mouse = new Guacamole.Mouse(guac.getDisplay().getElement());
mouse.onEach(['mousedown', 'mouseup', 'mousemove'], function sendMouseEvent(e) {
guac.sendMouseState(e.state);
});
// Keyboard
var keyboard = new Guacamole.Keyboard(document);
keyboard.onkeydown = function (keysym) {
guac.sendKeyEvent(1, keysym);
};
keyboard.onkeyup = function (keysym) {
guac.sendKeyEvent(0, keysym);
};
/* ]]> */</script>
</body>
</html>
Any insight anyone might have would be much appreciated!

Using Cordova webview

I wish to find out, for mobile developing using Cordova, is there a way to open a remote web app, and when a button is click in the remote web app, it execute a java script in Cordova environment?
For example, my mobile app opened up a web page hosted in the app server through web view, to ask the user to acknowledge he read and accept the license. The user need to click "Accept" or "Not Accept" on the web page.
If the user click "Accept", I hope to run a javascript that can bring up another page in the mobile app for the user to proceed to use the mobile app.
Is this possible?
Thanks!
Firstly, it's not a good idea to have a mobile app that is totally reliant on a remote server in order to function properly: what if the user's internet connection cuts out or is intermittent? (that happens plenty where I live).
However, one solution would be use an iframe to load the remote webapp content and cross-frame messaging to communicate the outcome of the UI interactions with the remote webapp back to your Cordova app. You will have to appropriately whitelist your remote webapp URL.
Something like this:
Cordova app index.html
<html>
<head>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript">
function onDeviceReady(){
window.addEventListener("message", onFrameMessage, false);
}
function onFrameMessage(event){
var eventName = event.data[0];
if(eventName === "terms_result"){
var accepted = event.data[1] == 1; // == will match 1 or "1"
if(accepted){
// Do something - e.g. change to homepage
}else{
// Do something else - e.g. display an error message
}
}
}
document.addEventListener("deviceready", onDeviceReady);
</script>
</head>
<body>
<div data-role="page" id="terms">
<iframe src="http://example.com/my/remote/webapp" style="border: 0; width: 100%; height: 100%"></iframe>
</div>
<div data-role="page" id="home">
<!-- Your home page content -->
</div>
</body>
</html>
Remote webapp html
<html>
<head>
<script type="text/javascript">
function accept(result){
window.parent.postMessage(["terms_result", result], "*");
}
</script>
</head>
<body>
<button onclick="accept(1)">Accept</button>
<button onclick="accept(0)">Not Accept</button>
</body>
</html>

Integrating Javascript Libraries with Google App Engine

Just starting to learn web programming (taking class CS 253 on Udacity).
My question is how does integrating JS and google app engine work? I know this is may be a fundamental question about web programming, but I really need some guidance on how to understand this concept.
I am trying to incorporate the Twitch Javascript API into Google App Engine. Basically, I would like to have a small website where users can login via Twitch and it stores their info into a database. I really do not understand how this is possible, since Twitch only has a Javascript API.
Here is the script that I have that works perfectly for connecting to Twitch (from the examples on their git page):
<html>
<head>
<meta charset="utf-8">
<title>TwitchTV SDK Example App</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="https://ttv-api.s3.amazonaws.com/twitch.min.js"></script>
<script>
window.CLIENT_ID = '';
$(function() {
// Initialize. If we are already logged in, there is no
// need for the connect button
Twitch.init({clientId: CLIENT_ID}, function(error, status) {
if (status.authenticated) {
// we're logged in :)
$('.status input').val('Logged in! Allowed scope: ' + status.scope);
// Show the data for logged-in users
$('.authenticated').removeClass('hidden');
} else {
$('.status input').val('Not Logged in! Better connect with Twitch!');
// Show the twitch connect button
$('.authenticate').removeClass('hidden');
}
});
$('.twitch-connect').click(function() {
Twitch.login({
scope: ['user_read', 'channel_read']
});
})
$('#logout button').click(function() {
Twitch.logout();
// Reload page and reset url hash. You shouldn't
// need to do this.
window.location = window.location.pathname
})
$('#get-name button').click(function() {
Twitch.api({method: 'user'}, function(error, user) {
$('#get-name input').val(user.display_name);
});
})
$('#get-stream-key button').click(function() {
Twitch.api({method: 'channel'}, function(error, channel) {
$('#get-stream-key input').val(channel.stream_key);
});
})
});
</script>
<style type="text/css">
.hidden {
display: none;
}
</style>
</head>
<body>
<h1>TwitchTV SDK Example App</h1>
<div class="status">
Status: <input readonly="readonly" size="60" val="Unknown"/>
</div>
<div class="authenticate hidden">
<img src="http://ttv-api.s3.amazonaws.com/assets/connect_dark.png" class="twitch-connect" href="#" />
</div>
<h2 class="authenticated hidden">Authenticated</h2>
<div class="authenticated hidden">
<div id="logout">
<button>Log Out</button>
</div>
<div id="get-name">
<button>Get TwitchTV Name</button>
<input readonly="readonly" size="50" value="Unknown"/>
</div>
<div id="get-stream-key">
<button>Get TwitchTV Stream Key</button>
<input readonly="readonly" size="50" value="Unknown"/>
</div>
</div>
</body>
</html>
How can I communicate data between this client side javascript and Google App Engine? Thanks!
Very broad question. But in general, regarding your case:
You should set up a receiving end (handler) on your App Engine application. It will handle the requests from your client side JavaScript (Hello, world example)
Second, you will need to actually send the data to the server. I see that you're using jQuery. In order to call the server we've seen in the Hello, world example, you'll write something like this: $.get('/', function(data) {console.log(data);}). This will call the server and print to the console the message you got from the server.

How do i remote include a javascript file in Titanium appcelerator and use the functions of that file?

I am required to remotely include into my appcelerator project, a javascript file available at a particular link, and use the function declared in that file to process some data.
What i would like to achieve is something like the following in html -
<script src="https://some-link/Data.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
var testVariable = someMethod(localdata);
});
//use testVariable as necessary
</script>
//someMethod() is declared in remotely available Data.js
I am a newb at Appcelerator and im not really able to follow some of the threads i have come across, so some detailed help would be really appreciated. Thank you in advance.
Well according to me , you should first understand few points first :
You want to include a remote file hosted at some server , now as the Titanium code converts to native code at compile time , you cannot include Titanium API's from remote file.
If you want to include a remote file , then only option which I see is loading that file in webview.
Now coming to your problem , as you said that you want to fetch some data only from remote server by triggering some JS function from remote file. So following is what would I do :-
a/ Create a hidden webview in my main window with a EventListener of webview. Something like :
var webview = Titanium.UI.createWebView({url:'localHtmlFile.html'});
//event listener to handle the response from webview
Ti.App.addEventListener('fromWebView', function(e)
{
var testVariable = e.data;
});
b/ In localHtmlFile.html file :
<!DOCTYPE html>
<html>
<body>
<script src="https://some-link/Data.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
var testVariable = someMethod();
//respond the fetch data to the main window via fireEvent
Ti.App.fireEvent( 'fromWebView', { data : testVariable } );
});
</script>
</body>
</html>
PS : This is just a logic to begin with , you have to edit code according to your requirements

io.connect not working on local html page

I have an html page that needs to connect to a node.js server via socket.
The code works when in an html page that's hosted on my EC2 however, it's not working when I have it on an HTML page on my machine. Here's my code:
<script type="text/javascript src="http://54.213.92.113:8080/socket.io/socket.io.js"></script>
<script type="text/javascript src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
var socket = io.connect('http://54.213.92.113:8080');
$(document).ready(function(){
socket.on('jqplot', function(sentdata){
alert(sentdata);
});
});
</script>
I have no idea why this isn't working...I feel like i've don't everything correctly!
The javascript works when I comment out the line var socket = io.connect('http://54.213.92.113:8080');
Is 54.213.92.113 external EC2 address?
Is 8080 port of instance(security group) opened?
ping - use external or ElasticIP
nmap(I check, it inaccessible) - add 8080 to instance assigned security group

Categories

Resources