HiveMQ MQTT Websocket - can't subscribe to sub topics - websocket

I have a code that subscribes whatever user inputs in a form to an MQTT broker. Everything works fine, the data get published and show in the broker. However, I can't subscribe to sub topics.
Here is the MQTT part of the code:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="http://www.hivemq.com/demos/websocket-client/js/mqttws31.js" ></script>
<script type="text/javascript">
//Create a new Client object with your broker's hostname, port and your own clientId
var client = new Messaging.Client("broker.mqttdashboard.com", 8000, "clientId-9HL7JvIJNb");
var publish = function (payload, topic, qos) {
//Send your message (also possible to serialize it as JSON or protobuf or just use a string, no limitations)
var message = new Messaging.Message(payload);
message.destinationName = "sssmarthome/";
message.qos = qos;
client.send(message);
}
var options = {
//connection attempt timeout in seconds
timeout: 3,
//Gets Called if the connection has successfully been established
onSuccess: function () {
alert("Connected");
},
//Gets Called if the connection could not be established
onFailure: function (message) {
alert("Connection failed: " + message.errorMessage);
}
};
//Attempt to connect
client.connect(options);
</script>
As you can see, the destination name is "sssmarthome/" and that is the only topic I can subscribe to.
Here is the form code:
<form id="settingsForm" method="GET">
Temperature(low, °C): <input type="text" name="templow" id="templow">
Temperature(high, °C): <input type="text" name="temphigh" id="temphigh">
Humidity(low, %): <input type="text" name="humlow" id="humlow">
Humidity(high, %): <input type="text" name="humhigh" id="humhigh"><br>
<input type="button" value="Change" onclick="submitForm()">
</form>
<script>
function submitForm(){
publish(document.getElementById("templow").value, 'sssmarthome/templow',2)
publish(document.getElementById("temphigh").value, 'sssmarthome/temphigh',2)
publish(document.getElementById("humlow").value, 'sssmarthome/humlow',2)
publish(document.getElementById("humhigh").value, 'sssmarthome/humhigh',2)
So each of the inputs has their own subtopic. But if I go to the website and fill out the form, this is what I get on the broker:
As you can see on the picture, it doesn't show the names of the sub topics, just the main topic.
I tried subscribing to the sub topics in the broker, but nothing will get published then, the only topic that works is the default destination name. Any idea how to be able to subscribe to topics and have actually stuff published on them, with proper topic and sub topic? Thank you!

Just to put this out here as an answer, per my comment:
The code below this line:
var publish = function(payload, topic, qos)
never uses 'topic'....so since you set message.destinationName = "sssmarthome/"; and then publish, your GUI is showing just that. The outcome is exactly what your code is asking for.
The fix is to change that one line to:
message.destinationName = "sssmarthome/" + topic;
This is assuming that topic is a string.

Related

Prompt User to Upload file in Dialog Flow with MS Bot Framwork v4

I have a dialog flow that will require a user to upload a file/files. I would like to prompt the user and have them click on a button to open a file browse window to select the file they want to upload. I do not want to use the file chooser in the WebChat window text entry box (Users find this confusing). Is this possible? I saw in the documentation for v3 that there is a AttachmentPrompt dialog. However in the documentation for v4 I only see it mentioned in a one liner here... https://learn.microsoft.com/en-us/azure/bot-service/bot-builder-concept-dialog?view=azure-bot-service-4.0 however other than that which sounds promising there appears to be no documentation on this functionality.
Thanks for any help you can provide!
PromptAttachment does not define client side rendering, or client side file upload code. In order to have the WebChat control respond to a custom button, you will need to provide an Attachment Middleware for the Web Chat control, and have the bot send a custom attachment type.
Custom Attachment:
private class FileUpload : Attachment
{
public FileUpload()
: base("application/uploadAttachment") { }
}
Replying with FileUpload attachment:
var reply = activity.CreateReply("Upload a File");
reply.Attachments.Add(new FileUpload());
await connector.Conversations.SendToConversationAsync(reply);
Page hosting Web Chat:
<!DOCTYPE html>
<html>
<body>
<div id="webchat" />
<script src="https://unpkg.com/babel-standalone#6/babel.min.js"></script>
<script src="https://unpkg.com/react#16.5.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom#16.5.0/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/react-redux#5.0.7/dist/react-redux.min.js"></script>
<script src="https://cdn.botframework.com/botframework-webchat/latest/webchat.js"></script>
<script>
function uploadFile() {
document.querySelector('[title="Upload file"]').click();
}
</script>
<script type="text/babel">
var chatbot = new WebChat.createDirectLine({
token: 'YourToken',
webSocket: true,
});
const attachmentMiddleware = () => next => card => {
switch (card.attachment.contentType) {
case 'application/uploadAttachment':
return (<button type="button" onClick={uploadFile}>Upload file</button>);
default:
return next(card);
}
};
WebChat.renderWebChat({
directLine: chatbot,
botAvatarInitials: 'Bot',
attachmentMiddleware,
}, document.getElementById('webchat'));
</script>
</body>
</html>

Ajax POST issue with comment system

I downloaded a php/ajax comment script almost 2 years ago and been having this small issue since day one. I tried to contact the author, but he's no where to be found.
Sometimes when I click the "Send" button, the button stays disabled and nothing happens at all. It just continues to show the animated busy picture. I do not receive any error messages at all.
I'm wondering if any of you pros can help me with this?
Here is the relevant code :
<div class="comment_heading">Leave a Comment</div>
<div class="post_comment">
<textarea name="txtpostcomment" id="txtpostcomment-'.$postid.'" class="txtpostcomment"></textarea>
<button class="btnpostcomment" id="btnpostcomment-'.$postid.'" onclick="comment('.$postid.');" type="button">Send</button>
<input type="hidden" name="token" id="token" value="'.$_SESSION['token'].'">
<script>document.getElementById("txtpostcomment-'.$postid.'").focus();</script>
</div>
comment = function(postid1)
{
var txt = $('#txtpostcomment-'+postid1);
var btn = $('#btnpostcomment-'+postid1);
var comment1 = $(txt).val();
var token = $("#token").val();
$(btn).css('background-image', 'url(/comments/submit-busy.gif)');
$(btn).attr('disabled', true);
$.post("/comments/submit.php",{commenting:1, postid:postid1, comment: comment1, name: name, token: token},
function(msg)
{
if(msg.status)
{
$('.post_comment .error_msg').remove();
$('.comment-list-'+postid1).prepend(msg.html);
$(txt).val('');
$('.comChars').empty();
}
else
{
$('.post_comment .error_msg').remove();
$('.error_msg').clone().appendTo('.post_comment');
$('.error_msg:last').append(msg.error);
}
$(btn).css('background-image', 'none');
$(btn).attr('disabled', false);
$(txt).attr('disabled', false);
},'json');
}
It appears that your code is not checking for error conditions just in case the Ajax request fails (due to network disconnection, server error etc). Check your javascript console for any js errors. Since it is using $.post you might want to extend the code to add error handling if the jQuery version that you are using supports it. Or, alternatively, use $.ajax. For more info see http://api.jquery.com/jquery.post or http://api.jquery.com/jquery.ajax

Send all Form Data in WordPress ajax

<?php
add_action( 'admin_footer', 'my_action_javascript' );
function my_action_javascript() {
?>
<script type="text/javascript" >
jQuery(document).ready(function($) {
var data = {
action: 'my_action',
email:email
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
$.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
});
</script>
<?php
}
?>
Hi , I tried the ajax integration in wordpress. The above example is from codex of wordpress. I am not sure. How to send the form data in ajax.
Previously i tried like
var data = {
action: 'my_action',
email:email
};
That above data only send the value to db and it save perfect, but i need to store all those value like for example
Here is the form:
<form action="" method="post">
<label></label>
<input type="text" name="fname" value=""/>
</form>
I also tried to send all value like
var data= {
action: 'my_action',
email:email,
fname:fname
};
But it doesn't work. For individually email only send and enter properly in db. Is the way to send all value through ajax.
Thanks.
You will need to get the values of each input
var fname = $('input[name="fname"]').val();
if you only have a few inputs this can be done with a few of these statments but if you have loads and of different types you will need to loop through them. There are number of good post on here for doing that.
e.g. jquery get all input from specific form

signalr chat rooms

i am trying to create a chat application and i've read that signalr is a good thing to use. i looked for examples of it and so far, i've done this:
<script src="Scripts/jquery-1.6.2.min.js" type="text/javascript"></script>
<script src="Scripts/jquery.signalR.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
var connection = $.connection('echo');
connection.received(function (data) {
$('#messages').append('<li>' + data + '</li>');
});
connection.start();
$("#broadcast").click(function () {
connection.send($('#msg').val());
});
});
</script>
<input id="msg">
<input id="broadcast" type="button">
<ul id="messages"></ul>
this only creates a single connection. i want to create multiple chat rooms, how can i make another connection and store those connections, lets say, in a database so i can have a record of those connections.
I don't think you need multiple connctions, but for a great example you can check out jabbr.net on gitHub an opensource chatapplication build with signalR and created by the same person that created SignalR.
The great example of web-based chat using signalr and ASP.NET MVC is http://jabbr.net. It has chatrooms, commands, smiles and other useful features. Just explore its source code which is available here: https://github.com/davidfowl/JabbR

Can I use this Ajax script to communicate and exchange data between client and server?

This block of code is for client.html (it is located in this www.client.com/client.html) - client side.
The I have the code below that goes something like this:
ajaxRequest.open("GET", "http://www.server.com/ajax.php", true);
This is how I call the file ajax.php located in the server. Unfortunately I have no luck at all. It cannot connect to the server I'm calling. BTW, the ips /test site I've been using are all no restrictions, and is accessible to all.
However, I tried to simulate by putting both client.html and ajax.php in same site and it works well.
So my question is does this script works only if you are in same site? or does it work also in client-server scenario? What else do I have to do in order to make this work?
//client.html
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.myForm.time.value = ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "http://www.server.com/ajax.php", true);
ajaxRequest.send(null);
}
//-->
</script>
<form name='myForm'>
Name: <input type='text' onChange="ajaxFunction();" name='username' /> <br />
Time: <input type='text' name='time' />
</form>
</body>
</html>
// ajax.php
<?php
echo date("H:i:s");
?>
Browser follow the same origin policy for security reasons. So you will not be able to make an AJAX request to a different domain.
If you have control to the server, you can send special headers that allows cross-domain AJAX. Otherwise I think you have to find different methods.
Another thing you can do is to add a script to your page, whose source resides on www.server.com. Then in the source you can transmit data, for instance by assigning it to a new variable. In this way you are not constrained by cross-domain restrictions, but will only be able to do a GET request (not POST, PUT, DELETE...). Moreover there needs to be some collaboration from the server. Unlike in AJAX requests, the server will not spit out any page, but has to output valid javascript.
Usually the server actually encodes the data in JSON, and passes it to a given function, so the response may look like
someCallback({foo: 'bar', bar: 'foo'});
This techique is called JSONP, and you can find more details here.

Resources