Paho MQTT (C++) client fails to connect to Mosquitto - c++

I've got C++ code using the Paho MQTTPacket Embedded C++ library to connect to an MQTT broker. When that broker is io.adafruit.com, it works perfectly fine. But when it's my own Mosquitto instance running on my Raspberry Pi, the connection fails. I've narrowed it down to this line in MQTTClient.h, in the MQTT::Client::connect method:
// this will be a blocking call, wait for the connack
if (waitfor(CONNACK, connect_timer) == CONNACK)
The app hangs here for about 30 seconds, and then gets a result other than CONNACK (specifically 0 rather than 2).
I have tried both protocol version 3 (i.e. 3.1) and 4 (i.e. 3.1.1); same result.
My Mosquitto instance has no authentication or passwords set up. I've tried turning on debug messages in the Mosquitto log, but they're not showing anything useful. I'm at a loss. Why might I be unable to connect to Mosquitto from my C++ Paho code?
EDIT: Here's the client code... again, this works fine with Adafruit, but when I point it to my Mosquitto at localhost, it hangs as described. (I've elided the username and password -- I am sending them, but I really don't think those are the issue, since with mosquitto_pub or mosquitto_sub on the command line, I can connect regardless of this, since mosquitto is configured to allow anonymous connections.)
const char* host = "127.0.0.1";
int port = 1883;
const char* clientId = "ZoomBridge";
const char* username = "...";
const char* password = "...";
MQTT::QoS subsqos = MQTT::QOS2;
ipstack = new IPStack();
client = new MQTT::Client<IPStack, Countdown, 30000>(*ipstack);
MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
data.willFlag = 1;
data.MQTTVersion = 3;
data.clientID.cstring = (char*)clientId;
data.username.cstring = (char*)username;
data.password.cstring = (char*)password;
data.keepAliveInterval = 20;
data.cleansession = 1;
int rc = ipstack->connect(host, port);
if (rc != MQTT::SUCCESS) {
cout << "Failed [1] (result " << rc << ")" << endl;
return rc;
}
rc = client->connect(data);
if (rc != MQTT::SUCCESS) {
cout << "Failed [2] (result " << rc << ")" << endl;
ipstack->disconnect();
return rc;
}

As hashed out in the comments.
It looks like you are setting the flag to indicate you want to set a Last Will and Testament for the client (data.willFlag = 1;) but then not passing any topic or payload for the LWT.
If you don't need the LWT then set the flag to 0 (or remove the line settings flag) as it should default to disabled.
Also worth pointing out to clarity, this is all with the Paho Embedded C++ MQTTPacket client not the full blown Paho C++ client.

Related

C++ OpenSSL: libssl fails to verify certificates on Windows

I've done a lot of looking around but I can't seem to find a decent solution to this problem. Many of the StackOverflow posts are regarding Ruby, but I'm using OpenSSL more or less directly (via the https://gitlab.com/eidheim/Simple-Web-Server library) for a C++ application/set of libraries, and need to work out how to fix this completely transparently for users (they should not need to hook up any custom certificate verification file in order to use the application).
On Windows, when I attempt to use the SimpleWeb HTTPS client, connections fail if I have certificate verification switched on, because the certificate for the connection fails to validate. This is not the case on Linux, where verification works fine.
I was advised to follow this solution to import the Windows root certificates into OpenSSL so that they could be used by the verification routines. However, this doesn't seem to make any difference as far as I can see. I have dug into the guts of the libssl verification functions to try and understand exactly what's going on, and although the above answer recommends adding the Windows root certificates to a new X509_STORE, it appears that the SSL connection context has its own store which is set up when the connection is initialised. This makes me think that simply creating a new X509_STORE and adding certificates there is not helping because the connection doesn't actually use that store.
It may well be that I've spent so much time debugging the minutiae of libssl that I'm missing what the actual approach to solving this problem should be. Does OpenSSL provide a canonical way of looking up system certificates that I'm not setting? Alternatively, could the issue be the way that the SimpleWeb library/ASIO is initialising OpenSSL? I know that the library allows you to provide a path for a "verify file" for certificates, but I feel like this wouldn't be an appropriate solution since I as a developer should be using the certificates found on the end user's system, rather than hard-coding my own.
EDIT: For context, this is the code I'm using in a tiny example application:
#define MY_ENCODING_TYPE (PKCS_7_ASN_ENCODING | X509_ASN_ENCODING)
static void LoadSystemCertificates()
{
HCERTSTORE hStore;
PCCERT_CONTEXT pContext = nullptr;
X509 *x509 = nullptr;
X509_STORE *store = X509_STORE_new();
hStore = CertOpenSystemStore(NULL, "ROOT");
if (!hStore)
{
return;
}
while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) != nullptr)
{
const unsigned char* encodedCert = reinterpret_cast<const unsigned char*>(pContext->pbCertEncoded);
x509 = d2i_X509(nullptr, &encodedCert, pContext->cbCertEncoded);
if (x509)
{
X509_STORE_add_cert(store, x509);
X509_free(x509);
}
}
CertCloseStore(hStore, 0);
}
static void MakeRequest(const std::string& address)
{
using Client = SimpleWeb::Client<SimpleWeb::HTTPS>;
Client httpsClient(address);
httpsClient.io_service = std::make_shared<asio::io_service>();
std::cout << "Making request to: " << address << std::endl;
bool hasResponse = false;
httpsClient.request("GET", [address, &hasResponse](std::shared_ptr<Client::Response> response, const SimpleWeb::error_code& error)
{
hasResponse = true;
if ( error )
{
std::cerr << "Got error from " << address << ": " << error.message() << std::endl;
}
else
{
std::cout << "Got response from " << address << ":\n" << response->content.string() << std::endl;
}
});
while ( !hasResponse )
{
httpsClient.io_service->poll();
httpsClient.io_service->reset();
std::this_thread::sleep_for(std::chrono::milliseconds(20));
}
}
int main(int, char**)
{
LoadSystemCertificates();
MakeRequest("google.co.uk");
return 0;
}
The call returns me: Got error from google.co.uk: certificate verify failed
OK, to anyone who this might help in future, this is how I solved this issue. This answer to a related question helped.
It turns out that the issue was indeed that the SSL context was not making use of the certificate store that I'd set up. Everything else was OK, bu the missing piece of the puzzle was a call to SSL_CTX_set_cert_store(), which takes the certificate store and provides it to the SSL context.
In the context of the SimpleWeb library, the easiest way to do this appeared to be to subclass the SimpleWeb::Client<SimpleWeb::HTTPS> class and add the following to the constructor:
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <wincrypt.h>
class MyClient : public SimpleWeb::Client<SimpleWeb::HTTPS>
{
public:
MyClient( /* ... */ ) :
SimpleWeb::Client<SimpleWeb::HTTPS>( /* ... */ )
{
AddWindowsRootCertificates();
}
private:
using OpenSSLContext = asio::ssl::context::native_handle_type;
void AddWindowsRootCertificates()
{
// Get the SSL context from the SimpleWeb class.
OpenSSLContext sslContext = context.native_handle();
// Get a certificate store populated with the Windows root certificates.
// If this fails for some reason, the function returns null.
X509_STORE* certStore = GetWindowsCertificateStore();
if ( sslContext && certStore )
{
// Set this store to be used for the SSL context.
SSL_CTX_set_cert_store(sslContext, certStore);
}
}
static X509_STORE* GetWindowsCertificateStore()
{
// To avoid populating the store every time, we keep a static
// pointer to the store and just initialise it the first time
// this function is called.
static X509_STORE* certificateStore = nullptr;
if ( !certificateStore )
{
// Not initialised yet, so do so now.
// Try to open the root certificate store.
HCERTSTORE rootStore = CertOpenSystemStore(0, "ROOT");
if ( rootStore )
{
// The new store is reference counted, so we can create it
// and keep the pointer around for later use.
certificateStore = X509_STORE_new();
PCCERT_CONTEXT pContext = nullptr;
while ( (pContext = CertEnumCertificatesInStore(rootStore, pContext)) != nullptr )
{
// d2i_X509() may modify the pointer, so make a local copy.
const unsigned char* content = pContext->pbCertEncoded;
// Convert the certificate to X509 format.
X509 *x509 = d2i_X509(NULL, &content, pContext->cbCertEncoded);
if ( x509 )
{
// Successful conversion, so add to the store.
X509_STORE_add_cert(certificateStore, x509);
// Release our reference.
X509_free(x509);
}
}
// Make sure to close the store.
CertCloseStore(rootStore, 0);
}
}
return certificateStore;
}
};
Obviously GetWindowsCertificateStore() would need to be abstracted out to somewhere platform-specific if your class needs to compile on multiple platforms.

MT166-С connection not responding. С++ Library

I have a MT166-C dispenser. I am writing C ++ code to manage a dispenser.
In development use SDK (attach the link) and I have a problem.
To work with the dispenser, I open the COM port. Code:
int input_port;
string com_str = "\\\\.\\COM";
std::cin >> input_port;
std::cout << "\nInput COM value: " << input_port << std::endl;
com_str = com_str + to_string(input_port);
char* cstr = &com_str[0];
char* port_com = cstr;
HANDLE port = CommOpenWithBaut(port_com, 9600);
if (port == 0)
{
std::cout << "Cannot open connect!\n\n" << std::endl;
return -1;
}
After I use the HANDLE port to call methods.
int iRetn = 0;
BYTE byStatus = 0;
string str = "";
iRetn = MT166_GetStatus(hPortHandle, 0x98, byStatus);
Similar to documentation (p. 3.1 in MT166-C.docx - Link Too)
DLLEXPORT int APIENTRY MT166_GetStatus(HANDLE hComHandle, BYTE CardNum,BYTE &byStatus)
///Parameter:
// hComHandle: Input parameter, serial port handle, obtained by opening the serial port
// CarderNum: Input parameter, card dispenser NO. Default is 0x98
// byStatus: output parameter, card dispenser status word
//Return value:
//Succeed, return value is 0
//failed, return value is not 0 = -1 no communication
In response, I get the code -1 - no communication. For other methods, the situation is the same.
I do not understand why there is no answer from the dispenser (no communication). I would be very grateful for any help.
I use connections via rs232 cable or USB adapter rs232 - without change.
Thank you for your time.
First of all, you need to check the physical availability of an external device.
Check baud speed, data bits, stop bits, row control parameters...
Check the OS hardware list for driver correctness.

Cannot log a pointer C++

I'm programming on Visual Studio 2017 and i'm fed up with an error which took my entire day.
More precisely, i'm working on an Serial Communication project.
The code will send on every port availiable (GetPortName()) a string.
I installed a log header (plog) which will log all actions.
For each port, the program will log ("Testing port" port).
The variable which stands for port is "s".
The problem is when i lauch : LOGI << s; everything mess up and got a big error.
I tried "&s" instead of simply "s" on LOGI and i have not got any error but there's an adress like 0059EBF0 instead of the port.
I search and research but found nothing.
Can someone help me please ?
Thanks
for each (String^ s in SerialPort::GetPortNames())
{
SerialPort^ mySerialPort = gcnew SerialPort();
LOGI << &s;
mySerialPort->PortName = s;
mySerialPort->BaudRate = 115200;
mySerialPort->Open();
mySerialPort->Write("q");
String^ incom = mySerialPort->ReadLine();
if (incom == "Okay") {
LOGI << "Tt va bien mon fwewe";
setup = false;
}
mySerialPort->Close();
_getch();
}

Chrome native host in C++, cannot communicate with Chrome

I am trying to implement a Chrome extension using runtime.connectNative and postMessage. I am following the Chrome documentation, downloaded the native messaging example, and changed the native app to using C++.
However, the native app cannot receive the message from the Chrome extension.
Meanwhile, when the native app using the printf function write message to chrome extension, the extension can not receive and the message just shown in the console.
Any ideas how to solve the problem?
You didn't provide a lot information about what you actually tried, so I will do my best to explain the steps needed to implement Chrome Extension, Native Messaging host and establish communication between them. (Please examine the following link to obtain more information about Chrome Native Messaging: Chrome Native Messaging How to.
CHROME EXTENSION
Firstly, we need to set up Chrome extension. As this will be very simple extension, we need only manifest.json file (please note this is extension's manifest file - native host will have its own manifest file as well) and background.js javascript implementation.
The following is sample manifest.json file:
{
"name": "Test extension",
"description": "Native messaging test",
"permissions": [
"nativeMessaging",
"tabs",
"activeTab",
"background",
"http://*/", "https://*/"
],
"background": {
"scripts": ["background.js"]
},
"version": "1.0",
"minimum_chrome_version": "29",
"manifest_version": 2
}
Important things here are that implementation will be provided in background.js, minimum supported Chrome version is 29 and HTTP and HTTPS are both supported.
Next, background.js file has the following content:
var port = chrome.runtime.connectNative('com.dolby.native_messaging_host');
port.onMessage.addListener(function(msg) {
console.log(msg.text);
});
port.onDisconnect.addListener(function() {
console.log("Disconnected");
});
port.postMessage({"text":"This is message from Chrome extension"});
The code itself is pretty self-explanatory - we try to connect to native host identified by com.dolby.native_messaging_host key (I will come to this in a minute). Then, we register a listener for onMessage event (this event is triggered when native host sends a message to the chrome extension). We also register a listener for disconnect event (for example when native host dies this event will be triggered). And finally, we send a message using postMessage method.
NATIVE MESSAGING HOST
Now, native host also has its own manifest.json file. Very simple manifest.json file for native host is as follows:
{
"name": "com.dolby.native_messaging_host",
"description": "Native messaging host",
"path": "C:\\Users\\dbajg\\Desktop\\Native-messaging-host\\Debug\\Native-messaging-host.exe",
"type": "stdio",
"allowed_origins": [
"chrome-extension://bjgnpdfhbcpjdfjoplajcmbleickphpg/"
]
}
Couple of interesting things here: name identifies the key under which this native host is registered. Path is full path to native host executable. Type of communication stdio means we are using standard input/output for communication (only type currently supported). And finally, allowed_origins specify which extensions can communicate with this native host - so you have to find out what is your extension's key!.
The next step is to register this Native Messaging host in registry (for Windows) and specify the location to its manifest file. The following screenshots explains how to this for Windows (examine provided link to find out how to do this in OSX and Linux):
After you've added registry entry for your native host the only remaining thing is to write your native host. The following C++ code implements simple native host that reads messages from the standard input and writes response to standard output (when you send #STOP# message the native host exits):
#include <iostream>
#include <string>
int main(){
std::string oneLine = "";
while (1){
unsigned int length = 0;
//read the first four bytes (=> Length)
/*for (int i = 0; i < 4; i++)
{
int read_char = getchar();
length += read_char * (int) pow(2.0, i*8);
std::string s = std::to_string((long long)read_char) + "\n";
fwrite(s.c_str(), sizeof(char), s.size(), f);
fflush(f);
}*/
//Neat way!
for (int i = 0; i < 4; i++)
{
unsigned int read_char = getchar();
length = length | (read_char << i*8);
}
//read the json-message
std::string msg = "";
for (int i = 0; i < length; i++)
{
msg += getchar();
}
std::string message = "{\"text\":\"This is a response message\"}";
// Collect the length of the message
unsigned int len = message.length();
// Now we can output our message
if (msg == "{\"text\":\"#STOP#\"}"){
message = "{\"text\":\"EXITING...\"}";
len = message.length();
std::cout << char(len>>0)
<< char(len>>8)
<< char(len>>16)
<< char(len>>24);
std::cout << message;
break;
}
// return stdin message
len = length;
std::cout << char(len>>0)
<< char(len>>8)
<< char(len>>16)
<< char(len>>24);
std::cout << msg << std::flush;
// return response message
// std::cout << char(len>>0)
// << char(len>>8)
// << char(len>>16)
// << char(len>>24);
//
// std::cout << message << std::flush;
}
return 0;
}
Messages sent by extension to native host is formed in a way that first byte stores the number of bytes in the message. So the first thing native host must do is to read the first 4 bytes and calculate the size of the message. I explained how to do this in another post that can be found here:
How to calculate size of the message sent by chrome extension
For future Google people, here's how I do it:
C style
Reading
char bInLen[4];
read(0, bInLen, 4); // 0 is stdin
unsigned int inLen = *(unsigned int *)bInLen;
char *inMsg = (char *)malloc(inLen);
read(0, inMsg, inLen);
inMsg[inLen] = '\0';
...
free(inMsg);
Writing
char *outMsg = "{\"text\":\"This is a response message\"}";
unsigned int outLen = strlen(outMsg);
char *bOutLen = (char *)&outLen;
write(1, bOutLen, 4); // 1 is stdout
write(1, outMsg, outLen);
fflush(stdout);
C++ style
Reading
char bInLen[4];
cin.read(bInLen, 4);
unsigned int inLen = *reinterpret_cast<unsigned int *>(bInLen);
char *inMsg = new char[inLen];
cin.read(inMsg, inLen);
string inStr(inMsg); // if you have managed types, use them!
delete[] inMsg;
Writing
string outMsg = "{\"text\":\"This is a response message\"}";
unsigned int outLen = outMsg.length();
char *bOutLen = reinterpret_cast<char *>(&outLen);
cout.write(bOutLen, 4);
cout << outMsg << flush;

modbus communication decrease wait time to timeout

I'm writing a C++ app that will need to connect to various PLCs over modbus, the IPs of these PLCs is given by user input. Currently when the user puts in an IP that cannot be connected to, my program hangs for around 2 minutes in an attempt to connect and having my app hang for 2 minutes is not an option.
An example program illustrates the issue and my attempted fixes:
#include <modbus/modbus.h>
#include <string>
#include <errno.h>
#include <iostream>
#define PRINT_TIMEVAL(timeval) std::cout << "timeval sec: " << timeval.tv_sec << " usec: " << timeval.tv_usec << std::endl;
int main()
{
std::string ip = "192.168.2.5";
int port = 502;
int slaveNum = 1;
int address = 1;
int nb = 1;
struct timeval currentTimeout;
struct timeval responseTimeout;
responseTimeout.tv_sec = 1;
responseTimeout.tv_usec = 0;
struct timeval byteTimeout;
byteTimeout.tv_sec = 1;
byteTimeout.tv_usec = 0;
modbus_t *mb = modbus_new_tcp(ip.c_str(), port);
modbus_set_debug(mb, true);
modbus_set_error_recovery(mb, MODBUS_ERROR_RECOVERY_NONE);
modbus_flush(mb);
modbus_set_slave(mb, slaveNum);
modbus_get_response_timeout(mb, &currentTimeout);
PRINT_TIMEVAL(currentTimeout);
modbus_set_response_timeout(mb, &responseTimeout);
modbus_get_response_timeout(mb, &currentTimeout);
PRINT_TIMEVAL(currentTimeout);
modbus_get_byte_timeout(mb, &currentTimeout);
PRINT_TIMEVAL(currentTimeout);
modbus_set_byte_timeout(mb, &byteTimeout);
modbus_get_byte_timeout(mb, &currentTimeout);
PRINT_TIMEVAL(currentTimeout);
std::cout << "About to connect to " << ip << std::endl;
int errno;
if((errno = modbus_connect(mb)))
{
std::cout << "Error when connecting: " << modbus_strerror(errno) << std::endl;
}
std::cout << "Done connecting to " << ip << std::endl;
modbus_close(mb);
modbus_free(mb);
return 0;
}
As you can see I've tried setting both the response and byte timeout variables to 1 second (I've also tried 500 and 5000 microseconds). When I read the timeout values they have been set properly so I'm assuming that they don't have anything to do with the initial connection attempt. I've also tried explicitly setting the error recovery mode to none in case it was trying to reconnect on its own.
I would like something that will either stop modbus_connect after x amount of time or another command that will allow me to check to see if the IP is valid before attempting to connect through modbus, this would also need to timeout after a short amount of time.
I'm using libmodbus version 3.0.1-2
The issue was with my version of libmodbus (3.0.1), which is the current release version. In that version they were using the linux connect command but they weren't passing a NONBLOCKING flag, thus connect would become blocked for 2m7s. We resolved this issue by upgrading to libmodbus v3.1.1 which is marked as unstable but is not under active development (they're developing on v3.1.2). Unfortunately that version of libmodbus does not work for windows.
Use threads to listen for each device and push those messages into a queue that can be processed without holding up the other threads.