I have a thingsboard UI available at "thingsboard.MYDOMAIN.io:8080". I'm using NodeJS and MQTT.js. I can connect using the sample code on that page. But I don't know what URL i would use in that connect string. I've tried using that URL and putting MQTT:// on the front of it to no avail.
It's just one device coming into a thingsboard. I wouldn't think i would need to add anything other than the default thingsboard.
If someone could tell what the expect default URL would be?
The default MQTT port number is 1883 so something like
mqtt://thingsboard.mydomain.io:1883
would be a good starting point. You should even be able to leave the port number off e.g.
mqtt://thingsboard.mydomain.io
Connection code should be something like this:
var mqtt = require('mqtt');
const thingsboardHost = "127.0.0.1";
const ACCESS_TOKEN = "**********";
// Initialization of mqtt client using Thingsboard host and device access token
console.log('Connecting to: %s using access token: %s', thingsboardHost, ACCESS_TOKEN);
var client = mqtt.connect('mqtt://'+ thingsboardHost, { username: ACCESS_TOKEN });
The default MQTT port number is 1883, but you don't have to manually set that value. Take a look at the source code.
https://github.com/mqttjs/MQTT.js
Related
I am not new here but this is my first question.
I have searched a lot and quite frankly can't understand how this is supposed to work.
I get data periodically (temperature) to my ESP32 and while having it set as a WiFi client, connect to my router and somehow store this data on my Laptop(or somewhere else, like a local/web site, don't know if that's possible/better).
How is the connection supposed to work? I have installed XAMPP and run the Apache and MySQL servers and I tried to connect to my Laptop with some sketches from Arduino using the ESP32 libraries
// Use WiFiClient class to create TCP connections
WiFiClient client;
const int httpPort = 80;
const char* host = "192.168.1.109"; //The local IP of my Laptop
if (!client.connect(host, httpPort)) {
Serial.println("connection failed");
return;
}
but it doesn't connect.
Can someone please explain to me how this connection is supposed to take form or is this question too vague? I really just wanna know the "how-things-should-work-together" in this situation.
Thank you in advance.
OK, so after a lot of research and trying, I managed to work it out. I can now send an HTTP request (like GET or POST) from my ESP32 to a local server that is running on my laptop using XAMP and get a response. I can also connect to my local IP from my mobile phone (which is also in the same WiFi network).
Just for anyone else who wants to connect to a location in a server hosted on a PC in a local network, the steps are:
Create a local server on your PC, laptop whatever using an application like XAMPP (I have Windows 10 so WAMP would also work), download, install, open and start Apache.
Make sure that the Firewall lets your requests pass through (for me it was open by default, but I had seen elsewhere Firewall being an issue)
Go to your network settings, select the network that your devices(ESP32, phone, etc.)are connected and change its profile to Private, meaning that you trust this network, making your PC discoverable and able to accept requests. (That is really simple but took me hours to find)
Now, in order to connect from your phone to your PC, open a browser and enter the local IP (that is the IP that is given to your PC from the router as a local network name) of your PC to a browser and that's it, you are connected.
If you installed and ran XAMP, when connecting to your local IP(from same PC or other local device), it will forward you to 192.168.x.x/dashboard. If you want to create new workspaces and files, browse the XAMP folder in the installed location and inside the '/htdocs' subfolder do your testing.
For the ESP32 communication in Arduino(basic steps, not full code):
#include <WiFi.h>
#include <HTTPClient.h>
String host = "http://192.168.x.x/testfolder/";
String file_to_access = "test_post.php";
String URL = host + file_to_access;
void setup(){
WiFi.begin(ssid, password); //Connect to WiFi
HTTPClient http;
bool http_begin = http.begin(URL);
String message_name = "message_sent";
String message_value = "This is the value of a message sent by the ESP32 to local server
via HTTP POST request";
String payload_request = message_name + "=" + message_value; //Combine the name and value
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
int httpResponseCode = http.sendRequest("POST", payload_request);
String payload_response = http.getString();
}
In the test_post.php (located in "C:\xampp\htdocs\testfolder\") file I used a simple script to echo a message received using a POST request, so it's only 'readable' from POST requests. Connecting to it from your browser will give you the "Sorry, accepting..." message.
<?php
$message_received = "";
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$message_received = $_POST["message_sent"];
echo "Welcome ESP32, the message you sent me is: " . $message_received;
}
else {
echo "Sorry, accepting only POST requests...";
}
?>
Finally, using Serial prints, the output is:
Response Code: 200
Payload: Welcome ESP32, the message you sent me is: This is the value of a message sent by the ESP32 to local server via HTTP POST request
There it is, hope that this helps someone.
I'm trying to make a program that sends SNMP queries to some switches in the network.
Using the Net-snmp tools, I can send get requests to the switch using its name, and it works fine. But SNMP4J requires an IP address in CommunityTarget, so I get an IllegalArgumentException.
This is the relevant part of the code:
TransportMapping transport = new DefaultUdpTransportMapping();
transport.listen();
CommunityTarget comtarget = new CommunityTarget();
comtarget.setCommunity(new OctetString("public"));
comtarget.setVersion(SnmpConstants.version1);
comtarget.setAddress(new UdpAddress("switchName")); // exception happens here
comtarget.setRetries(2);
comtarget.setTimeout(1000);
How can I work around this?
You can get the IP address by using DNS resolution, like this answer says:
InetAddress address = InetAddress.getByName(switchName);
System.out.println(address.getHostAddress());
I've setup a perfectly functioning application (in VB) that allows user to access his Google Sheets.
The application follows Google's OAuth documentation for displaying a sign-in dialog in a web browser, obtains user's permission and access codes, uses access codes to obtain access token, and then uses the Google Sheet's Query service to get hold of Google Sheets. Very simple. Works fine.
Problem occurs on computers that have internet proxy defined on them. In the rest of my application and most of Google Sheets API, I can define a manual internet proxy. GData's RequestFactory allows manually configuring proxy server. The only line of code that doesn't support (to my current knowledge) is the OAuthUtil library used for obtaining access token. It doesn't allow defining internet proxy server, hence it is unable to resolve host on computers behind proxy environment. Following is my pseudo code:
Dim parameters As New OAuth2Parameters
parameters.ClientId = CLIENT_ID
parameters.ClientSecret = CLIENT_SECRET
parameters.RedirectUri = REDIRECT_URI
parameters.Scope = SCOPE
>>Show browser window and obtain access code
parameters.AccessCode = login.Token
OAuthUtil.GetAccessToken(parameters) '<< Point of failure
Dim requestFactory As GOAuth2RequestFactory = New GOAuth2RequestFactory(Nothing, My.Application.Info.ProductName, parameters)
requestFactory.Proxy = GetProxySettings() '<< my code for defining proxy
myService = New SpreadsheetsService("Application")
myService.RequestFactory = requestFactory
Another important aspect is that my application works on Mac OSX as well using Wine (for web browser I use GeckoFX). If internet proxy is globally defined on the environment then the OAuthUtil works fine, but this doesn't work for Wine. I have tried setting internet proxy in the command-line environment, or in the registry and refreshed system settings, still the applications running in Wine do not understand that proxy is defined. Hence proxy has to be manually defined.
I need help to figure out a solution by any of the following:
* A way to forcefully/manually define proxy for OAuthUtil for obtaining access token
* Any other way to obtain OAuth access token if proxy cannot be defined as above (maybe WebClient can be used?)
* Some way to define global internet proxy in Wine so applications like GData API read and understand the proxy setting. Though I'd rather prefer manually defined proxy at application level.
Any ideas folks?
Regards
F.A.
I've figured it out. Turns out that the 'OAuthUtil.GetAccessToken' only uses system-defined proxy. There is no way to manually define internet proxy, like RequestFactory supports. So there is a work-around using WebClient:
Try
'// Get access token from code
Using WC As New WebClient
' Define proxy
WC.Proxy = GetProxySettings()
' Set parameters
WC.Headers(HttpRequestHeader.ContentType) = "application/x-www-form-urlencoded"
' Get response
Dim postURL = "https://www.googleapis.com/oauth2/v4/token"
Dim postParams = "code=" & parameters.AccessCode &
"&client_id=" & Uri.EscapeDataString(CLIENT_ID) &
"&client_secret=" & Uri.EscapeDataString(CLIENT_SECRET) &
"&redirect_uri=" & Uri.EscapeDataString(REDIRECT_URI) &
"&grant_type=authorization_code"
Dim responsebody As String = WC.UploadString(postURL, postParams)
' Read response
Dim jObj As JObject = JsonConvert.DeserializeObject(responsebody)
' Store token
parameters.AccessToken = jObj("access_token").ToString
parameters.RefreshToken = jObj("refresh_token").ToString
parameters.TokenType = jObj("token_type").ToString
parameters.TokenExpiry = Now().AddSeconds(CDbl(jObj("expires_in").ToString))
End Using
Catch ex As Exception
MsgBox("Error obtaining access token: " & ex.Message, MsgBoxStyle.Critical)
Return Nothing
End Try
how do you get cloudfoundry to assign a port? I am adding applications and I'd like to have a different port for each but VCAP_APP_PORT is not set. VCAP_APP_HOST is set but VCAP_APP_PORT is not.
Take a look at http://show-env.cloudfoundry.com/
It's a node application I knocked together just to output the environment and the request headers when you call it, the code looks like this;
var http = require('http');
var util = require('util');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write(util.inspect(process.env));
res.write("\n\n************\n\n");
res.end(util.inspect(req.headers));
}).listen(3000);
You can see the VCAP_APP_PORT in the output;
It would be handy to know which framework you are using, however, all these variables should be stored in the system environment so it shouldn't really matter.
Cloud Foundry will automatically assign each application instance an IP address and port and these values are accessible in the VCAP_* variable as Dan describes. You don't get to tell Cloud Foundry which port you prefer. Each instance of your app may receive a different IP address and port, so you should always interrogate the environment to find out what they are if you need that information.
We have an app that invokes various remote methods on MBeans using MBeanServerConnection.invoke.
Occasionally one of these methods hangs.
Is there any way to have a timeout on the call? so that it will return with an exception if the call takes too long?
Or do I have to move all those calls into separate threads so they don't lock up the UI and require killing the app?
See http://weblogs.java.net/blog/emcmanus/archive/2007/05/making_a_jmx_co.html
===== Update =====
I was thinking about this stuff when I first responded, but I was on my mobile and I can't type worth a damn on it.....
This is really an RMI problem, and unless you use a different protocol, there's not much you can do, except, as you say, move all those calls into separate threads so they don't lock up the UI.
But.... if you have the option of fiddling with the target server and you can customize the connecting client, you have at least 1 option which is to customize the JMXConnectorServer on your target servers.
The standard JMXConnectorServer implementation is the RMIConnectorServer. Part of it's specification is that when you create a new instance using any of the constructors (like RMIConnectorServer(JMXServiceURL url, Map environment)), the environment map can contain a key/value pair where the key is RMIConnectorServer.RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE and the value is a RMIClientSocketFactory. Therefore, you can specify a socket factory method like this:
RMIClientSocketFactory clientSocketFatory = new RMIClientSocketFactory() {
public Socket createSocket(String host, int port) {
Socket s = new Socket(host, port);
s.setSoTimeout(3000);
}
};
This factory creates a Socket and then sets its SO_TIMEOUT using setSoTimeout, so when the client connects using this socket, all operations, including connecting, will timeout after 3000 ms.
You could also checkout the JMXMP connector and server in the jmx-optional package of the OpenDMK. (links are to my github mavenized). No built in solution, mind you, but they're super easy to extend and JMXMP is simple TCP socket based rather than RMI, so this type of customization would be trivial.
Cheers.
# Nicholas : The above code is not working.I mean request is not getting timeout after 3000. ms.
map.put(RMIConnectorServer.RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE , new RMIClientSocketFactory() {
#Override
public Socket createSocket(String host, int port) throws IOException {
if(logger.isInfoEnabled() ){
logger.info("JMXManager inside createSocket..." + host + ": port :" + port);
}
Socket s = new Socket(host, port);
s.setSoTimeout(3000);
return s;
}
});
cs = JMXConnectorServerFactory.newJMXConnectorServer(url,map,mbeanServer);
As I answered on: How to set request timeout for JMX Connector the RMI properties can help you. All the properties are on Oracle documentation site:
http://docs.oracle.com/javase/7/docs/technotes/guides/rmi/sunrmiproperties.html.
For example: -Dsun.rmi.transport.tcp.responseTimeout=60000 is a client side tcp response timeout. There are also properties for connect timeout and for server side connections.
I also am not happy how the JMX/RMI/TCP stack hides important settings from lower level protocols, and makes it not available for a single connection.