IBM Watson IoT - Unable to get response from topic with parameters using ESP8266 - ibm-watson

From several days I searched for this problem:
I want to do a connected device (IoT) using Watson IoT Platform and ESP32 (or similar). This device have some relays on board.
On Watson dashboard I created the device type, the physical/logical interface, I connected the ESP with the platform.
I created a custom action on the dashboard that has a param to identify the relay that I want to switch (switch2) and also a simple custom action (switch) without param.
The problem is that if I generate the action without the param (switch) I see the callback print, if I generate the action with a param (switch2) nothing happens.
I tried also to use the built-in Watson action "firmware update/download", if I use firmware download (that want some params such as uri, version, etc.) nothing happens, if I use firmware update (that don't want params), I see the callback of subscription.
Here you can see the code arduino like for the ESP
// --------------- HEADERS -------------------
#include <Arduino_JSON.h>
#include <EEPROM.h>
#include <WiFi.h>
#include <WiFiClient.h>
#include <WebServer.h>
#include <ESPmDNS.h>
#include <PubSubClient.h> //https://github.com/knolleary/pubsubclient/releases/tag/v2.3
WebServer server(80);
char wifi_ssid[100] = "xxxxxx";
char wifi_psw[200] = "xxxxxxx";
// ----- Watson IBM parameters
#define ORG "xxxx"
#define DEVICE_TYPE "Relay"
#define DEVICE_ID "xxxx"
#define TOKEN "xxxxxxxxxxxxxxxx"
char ibmServer[] = ORG ".messaging.internetofthings.ibmcloud.com";
char authMethod[] = "use-token-auth";
char token[] = TOKEN;
char clientId[] = "d:" ORG ":" DEVICE_TYPE ":" DEVICE_ID;
const char switchTopic[] = "iotdm-1/mgmt/custom/switch-actions-v1/switch2";
const char testTopic[] = "iotdm-1/mgmt/custom/switch-actions-v1/switch"; //"iot-2/cmd/+/fmt/+";
const char observeTopic[] = "iotdm-1/observe";
const char publishTopic[] = "iot-2/evt/status/fmt/json";
const char responseTopic[] = "iotdm-1/response";
const char deviceResponseTopic[] = "iotdevice-1/response";
const char manageTopic[] = "iotdevice-1/mgmt/manage";
const char updateTopic[] = "iotdm-1/mgmt/initiate/firmware/update";
void callback(char* topic, byte* payload, unsigned int payloadLength);
WiFiClient wifiClient;
PubSubClient client(ibmServer, 1883, callback, wifiClient);
bool outputEnable = false;
bool oldOutputEnable = false;
void setup() {
// put your setup code here, to run once:
//Init la porta seriale ed aspetta che si avii
Serial.begin(115200);
while(!Serial) {
delay(1);
}
setupWiFi();
}
void loop() {
// put your main code here, to run repeatedly:
if (!client.loop()) {
mqttConnect();
initManagedDevice();
}
delay(100);
}
// WiFi Settings
void setupWiFi() {
bool state = false;
Serial.println("---- Setup WiFi ----");
Serial.println(wifi_ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(wifi_ssid, wifi_psw);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
mqttConnect();
initManagedDevice();
publishStatus();
Serial.println("");
Serial.print("Connected to ");
Serial.println(wifi_ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
// IBM IoT
void mqttConnect() {
if (!!!client.connected()) {
Serial.print("Reconnecting MQTT client to "); Serial.println(ibmServer);
while (!!!client.connect(clientId, authMethod, token)) {
Serial.print(".");
delay(500);
}
Serial.println();
}
}
void initManagedDevice() {
if (client.subscribe("iotdm-1/response")) {
Serial.println("subscribe to responses OK");
} else {
Serial.println("subscribe to responses FAILED");
}
if (client.subscribe("iotdm-1/device/update")) {
Serial.println("subscribe to update OK");
} else {
Serial.println("subscribe to update FAILED");
}
if (client.subscribe(observeTopic)) {
Serial.println("subscribe to observe OK");
} else {
Serial.println("subscribe to observe FAILED");
}
if (client.subscribe(switchTopic)) {
Serial.println("subscribe to switch OK");
} else {
Serial.println("subscribe to switch FAILED");
}
if (client.subscribe(testTopic)) {
Serial.println("subscribe to Test OK");
} else {
Serial.println("subscribe to Test FAILED");
}
JSONVar root;
JSONVar d;
JSONVar supports;
supports["deviceActions"] = true;
supports["firmwareActions"] = true;
supports["switch-actions-v1"] = true;
d["supports"] = supports;
root["d"] = d;
char buff[300] = "";
JSON.stringify(root).toCharArray(buff, 300);
Serial.println("publishing device metadata:"); Serial.println(buff);
if (client.publish(manageTopic, buff)) {
Serial.println("device Publish ok");
} else {
Serial.print("device Publish failed:");
}
}
void callback(char* topic, byte* payload, unsigned int payloadLength) {
Serial.print("callback invoked for topic: "); Serial.println(topic);
if (strcmp (responseTopic, topic) == 0) {
return; // just print of response for now
}
if (strcmp (updateTopic, topic) == 0) {
handleUpdate(payload);
}
if (strcmp(switchTopic, topic) == 0) {
handleRemoteSwitch(payload);
}
if(strcmp(observeTopic, topic) == 0) {
handleObserve(payload);
}
}
void sendSuccessResponse(const char* reqId) {
JSONVar payload;
payload["rc"] = 200;
payload["reqId"] = reqId;
char buff[300] = "";
JSON.stringify(payload).toCharArray(buff, 300);
if (client.publish(deviceResponseTopic, buff)) {
Serial.println("Success sended");
} else {
Serial.print("Success failed:");
}
}
void publishStatus() {
String payload = "{\"relayStatus\":";
payload += outputEnable;
payload += "}";
Serial.print("Sending payload: "); Serial.println(payload);
if (client.publish(publishTopic, (char*) payload.c_str())) {
Serial.println("Publish OK");
} else {
Serial.println("Publish FAILED");
}
}
void handleUpdate(byte* payload) {
Serial.println("handle Update");
}
void handleObserve(byte* payload) {
JSONVar request = JSON.parse((char*)payload);
JSONVar d = request["d"];
JSONVar fields = d["fields"];
const char* field = fields[0]["field"];
if(strcmp(field, "mgmt.firmware") == 0) {
Serial.println("Upadete the firmware");
sendSuccessResponse(request["reqId"]);
} else {
Serial.println("Unmanaged observe");
Serial.println(request);
}
}
void handleRemoteSwitch(byte* payload) {
Serial.println("handle remote switching");
//invertedSwitch = !invertedSwitch;
outputEnable = !outputEnable;
JSONVar request = JSON.parse((char*)payload);
const char* id = request["reqId"];
sendSuccessResponse(id);
}
Thanks to everyone that wants to try to help me.

After several days I solved the issue, I post here de response for someone with the same problem:
The problem is the PubSubClient library, that accept only 128 bytes response message (including header). The Watson IBM produce longer response message than 128 bytes.
To change the buffer size for the response message, you need to modify the PubSubClient.h file at line
#define MQTT_MAX_PACKET_SIZE 128
And change the 128 byte with bigger number (eg. 1024).

Related

Firmware over the air algorithm

I'm doing firmware over the air update, but I don't know how long will it take to download the firmware and upgrade the device. So what I have tried is to go into infinite loop while(1) and check if the firmware is finished upgrading. That fcked up the devices on the street... The other option is to do timeout but for how long? It's unpredictable.
The question is, how to ensure realiability and do it correctly?
Here is what I have tried:
signed char wait_commands(vu32 timeout, char*command, const char *result_command, int valueToCheck)
{
char *result = NULL;
timer_1sec = 0;
while(timer_1sec < timeout)
{
if( GSMGetString(tempdata, 5) == OK)
{
result = strstr(tempdata, command);
if ( result != NULL)
{
int value;
if ( result_command != NULL)
{
if( valueToCheck != -1)
{
if (sscanf(result, result_command, &value) > 0)
{
if (value != valueToCheck)
{
return FEHLER;
}
else
{
return OK;
}
}
}
}
else
{
return OK;
}
}
}
}
return FEHLER;
}
u8 isUpdated(void)
{
char *currentFirmwareVersion = "BG96MAR02A07M1G_01.019.01.019";
while (GSMCommand("+QGMR", tempdata, 20) != AT_OK)
;
if (strncmp(tempdata, currentFirmwareVersion, strlen(currentFirmwareVersion))==0)
{
isBG96Updated = 1;
}
else
{
isBG96Updated = 0;
}
return isBG96Updated;
}
signed char updateBG96FirmwareVersion(vu32 timeout)
{
char *url = "\"http://10.10.169.1/dfota/upgrade.bin\"";
char command[150] = {0};
signed char res = FEHLER;
if(isUpdated())
return OK;
sprintf(command, "AT+QFOTADL=%s", url);
PutStringUART(UART_GSM, command);
PutCharUART(UART_GSM, '\r');
res = wait_commands(timeout, "\"FOTA\",\"HTTPSTART\"", NULL, -1);
res = wait_commands(timeout, "\"FOTA\",\"END\"", "\"FOTA\",\"END\",%d", 0);
return res;
}
I have no experience with the Quectel BG96 chip, specifically, but it appears to support DFOTA, and there is also an official guide that you can view/download here.
This guide contains the AT commands necessary to upgrade the firmware over-the-air. Plus, I think it may clarify your doubts about the upgrade procedure.

Saving Custum Paramter with WifiManager & Arduinojson 6

I'm trying to save an additional custom parameter to wifimanager which is the mqtt server address but all codes available in the library and all over the internet are for Arduinojson 5, I tried upgrading to Arduinojson 6 to the best of my ability. The code runs with no issues, however, when I restart the esp, it is gone. For somereason, it is not saved.
#include <FS.h> //this needs to be first, or it all crashes and burns...
#include <ESP8266WiFi.h> //https://github.com/esp8266/Arduino
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h> //https://github.com/tzapu/WiFiManager
#include <ArduinoJson.h> //https://github.com/bblanchon/ArduinoJson
#define TRIGGER_PIN 16
char mqtt_server[40];
bool shouldSaveConfig = false;
void saveConfigCallback () { Serial.println("Should save config"); shouldSaveConfig = true; }
WiFiManager wifiManager;
WiFiManagerParameter custom_mqtt_server("server", "mqtt server", mqtt_server, 40);
void setup() {
Serial.begin(115200);
Serial.println("\n Starting");
pinMode(TRIGGER_PIN, INPUT);
//clean FS, for testing
//SPIFFS.format();
if (SPIFFS.begin()) {
Serial.println("** Mounting file system **");
if (SPIFFS.exists("/config.json")) {
//file exists, reading and loading
Serial.println("** Reading config file **");
File configFile = SPIFFS.open("/config.json", "r");
if (configFile) {
size_t size = configFile.size();
// Allocate a buffer to store contents of the file.
std::unique_ptr<char[]> buf(new char[size]);
configFile.readBytes(buf.get(), size);
DynamicJsonDocument doc(1024);
DeserializationError error = deserializeJson(doc, buf.get());
// Test if parsing succeeds.
if (error) {
Serial.print(F("deserializeJson() failed: "));
Serial.println(error.c_str());
return;
}
strcpy(mqtt_server, doc["mqtt_server"]); //get the mqtt_server <== you need one of these for each param
} else {
Serial.println("** Failed to load json config **");
}
configFile.close();
Serial.println("** Closed file **");
}
}
else {
Serial.println("** Failed to mount FS **");
}
wifiManager.setSaveConfigCallback(saveConfigCallback);
wifiManager.addParameter(&custom_mqtt_server);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
resetbtn();
}
Serial.println("connected...yeey :)");
//read updated parameters
strcpy(mqtt_server, custom_mqtt_server.getValue());
//save the custom parameters to FS
if (shouldSaveConfig) {
Serial.println("saving config");
DynamicJsonDocument doc(1024);
doc["mqtt_server"] = mqtt_server;
File configFile = SPIFFS.open("/config.json", "w");
if (!configFile) {
Serial.println("failed to open config file for writing");
}
serializeJson(doc, Serial);
serializeJson(doc, configFile);
configFile.close();
//end save
}
}
void loop() {
resetbtn();
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
resetbtn();
}
Serial.println("Connected");
wifiManager.process();
saveParamsCallback();
delay(3000);
}
void resetbtn() { if ( digitalRead(TRIGGER_PIN) == HIGH ) { wifiManager.startConfigPortal("Horray"); Serial.println("connected...yeey :)"); } }
void saveParamsCallback () {
Serial.println("Get Params:");
Serial.print(custom_mqtt_server.getID());
Serial.print(" : ");
Serial.println(custom_mqtt_server.getValue());
}
for same purpose instead of using: serializeJson(doc, configFile);
i'm using this function and for me work pretty well
// for writing
bool writeFile(const char * path, const char * message, unsigned int len){
File file = SPIFFS.open(path, FILE_WRITE);
if(!file){
return false;
}
if(!file.write((const uint8_t *)message, len)){
return false;
}
return true;
}
for reading i'm using this function
// for reading
int readFile(const char * path, char ** text){
// retval int - number of characters in the file
// in case of empty file 0
// in case of directory or not found -1
File file = SPIFFS.open(path);
if(!file || file.isDirectory()){
return -1;
}
int file_lenght = file.size();
*text = (char*) malloc(file_lenght*sizeof(char));
for(int i = 0; i < file_lenght; i++){
(*text)[i] = file.read();
}
return file_lenght;
}
you can use this function in this way:
#define WIFI_credential_filename "/config.json"
char * wifi_credentials;
int file_len = readFile(WIFI_credential_filename, &wifi_credentials);
// at this point "wifi_credentials" is filled with the content of
"/config.json" file
this is my implementation, surely it can be improved but I have tested it and it works

Switch from Wifi Access Point mode to station mode using esp32

I am making my esp32 an access point and once the client connects with access point, it shares it's Home wifi credentials (ssid and password). Then I use this ssid and password to connect the esp32 with Home wifi.
But It is not connecting with Home wifi. I try to disconnect/stop access point but got no luck.
Arduino Code:
#include <WiFi.h>
#include "aWOT.h"
#include "StaticFiles.h"
#define LED_BUILTIN 2
const char* ssid = "SSID";
const char* password = "Password";
WiFiServer server(80);
Application app;
String CompleteSSID="";
String CompletePassword="";
//Read SSID from web
void readSSID(Request &req, Response &res) {
res.print(CompleteSSID);
}
void updateSSID(Request &req, Response &res) {
while(req.available())
{
char currentword=req.read();
CompleteSSID+=currentword;
}
Serial.println(CompleteSSID);
//digitalWrite(LED_BUILTIN, '1');
return readSSID(req, res);
}
void readPassword(Request &req, Response &res) {
res.print(CompletePassword);
}
void updatePassword(Request &req, Response &res) {
while(req.available())
{
char currentword=req.read();
CompletePassword+=currentword;
}
Serial.println(CompletePassword);
//digitalWrite(LED_BUILTIN, '1');
ConnectToHomeWiFi();
return readPassword(req, res);
}
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
Serial.begin(115200);
WiFi.softAP(ssid, password);
IPAddress IP = WiFi.softAPIP();
Serial.println(IP);
app.get("/ssid", &readSSID);
app.put("/ssid", &updateSSID);
app.get("/password", &readPassword);
app.put("/password", &updatePassword);
app.route(staticFiles());
server.begin();
}
void ConnectToHomeWiFi()
{
char* ssid_n;
char* pass_n;
CompleteSSID.toCharArray(ssid_n, CompleteSSID.length());
CompletePassword.toCharArray(pass_n, CompletePassword.length());
//WiFi.softAPdisconnect();
WiFi.disconnect(true);
WiFi.persistent(false);
//WiFi.setAutoConnect(false);
//WiFi.mode(WIFI_OFF);
//WiFi.setOutputPower(0);
//WiFi.reconnect();
WiFi.mode(WIFI_STA);
delay(100);
WiFi.begin(ssid_n, pass_n);
Serial.print("Connecting to ");
Serial.println(CompleteSSID);
uint8_t i = 0;
while (WiFi.status() != WL_CONNECTED)
{
Serial.print('.');
delay(500);
if ((++i % 16) == 0)
{
Serial.println(F(" still trying to connect"));
}
}
Serial.print(F("Connected. My IP address is: "));
Serial.println(WiFi.localIP());
}
void loop() {
WiFiClient client = server.available();
if (client.connected()) {
app.process(&client);
}
}
What am I doing wrong in disconnecting SoftAp or connecting with home wifi?
Thanks!
Here is the solution of this issue:
void setup(){
.....
WiFi.softAP(ssid, password);
IPAddress IP = WiFi.softAPIP();
Serial.println(IP);
....
server.begin();
}
void ConnectToHomeWiFi()
{
....
WiFi.begin(ssid_n,pass_n);
....
}
There is no need of disconnecting Access point, changing the mode and then using WiFi.begin. By using only WiFi.begin, we can connect to any WiFi.

questions about PacketAcknowledgements in nesC,TinyOS

In order to learn how to use the interface PacketAcknowledgements,i try to modify the example in apps/RadioCountToLeds,but there are some problem,the transmit of data can't be done and it seems there is no ack back to the sender.
the file RadioCountToLedsC is as follows:
#include "Timer.h"
#include "RadioCountToLeds.h"
module RadioCountToLedsC #safe() {
uses {
interface Leds;
interface Boot;
interface Receive;
interface AMSend;
interface Timer<TMilli> as MilliTimer;
interface SplitControl as AMControl;
interface Packet;
interface PacketAcknowledgements;
interface AMPacket;
}
}
implementation {
message_t packet;
bool locked = FALSE;
uint16_t counter = 0;
event void Boot.booted() {
dbg("Boot","Application booted.\n");
call AMControl.start();
}
event void AMControl.startDone(error_t err) {
if (err == SUCCESS) {
if(TOS_NODE_ID==0)
{
call MilliTimer.startPeriodic(1000);
}
}
else {
call AMControl.start();
}
}
event void AMControl.stopDone(error_t err) {
// do nothing
}
event void MilliTimer.fired() {
counter++;
dbg("RadioCountToLedsC", "RadioCountToLedsC: timer fired, counter is %hu.\n", counter);
if (locked==TRUE) {
return;
}
else {
radio_count_msg_t* rcm = (radio_count_msg_t*)call Packet.getPayload(&packet, sizeof(radio_count_msg_t));
if (rcm == NULL) {
return;
}
rcm->counter = counter;
call PacketAcknowledgements.requestAck(&packet);
if (call AMSend.send(AM_BROADCAST_ADDR, &packet, sizeof(radio_count_msg_t)) == SUCCESS) {
dbg("RadioCountToLedsC", "RadioCountToLedsC: packet sent.\n", counter);
locked = TRUE;
}
}
}
event message_t* Receive.receive(message_t* bufPtr, void* payload, uint8_t len) {
if (len != sizeof(radio_count_msg_t)) {return bufPtr;}
else {
radio_count_msg_t* rcm = (radio_count_msg_t*)payload;
dbg("RadioCountToLedsC", "Received packet of counter %u.\n", rcm->counter);
if (rcm->counter & 0x1) {
call Leds.led0On();
}
else {
call Leds.led0Off();
}
if (rcm->counter & 0x2) {
call Leds.led1On();
}
else {
call Leds.led1Off();
}
if (rcm->counter & 0x4) {
call Leds.led2On();
}
else {
call Leds.led2Off();
}
return bufPtr;
}
}
event void AMSend.sendDone(message_t* bufPtr, error_t error) {
if(call PacketAcknowledgements.wasAcked(bufPtr)){
dbg("RadioCountToLedsC", "ACKED!\n");
locked = FALSE;
}
else
{
dbg("RadioCountToLedsC", "NOT ACKED!\n");
}
}
}
i want to know where the error is.
by the way,can anyone give me an example about how to use the interface PacketAcknowledgements?
thanks very much.
the configuration file are as follows:
configuration RadioCountToLedsAppC {}
implementation {
components MainC, RadioCountToLedsC as App, LedsC;
components new AMSenderC(AM_RADIO_COUNT_MSG);
components new AMReceiverC(AM_RADIO_COUNT_MSG);
components new TimerMilliC();
components ActiveMessageC;
App.Boot -> MainC.Boot;
App.PacketAcknowledgements ->AMSenderC.Acks;
App.Receive -> AMReceiverC;
App.AMSend -> AMSenderC;
App.AMControl -> ActiveMessageC;
App.Leds -> LedsC;
App.MilliTimer -> TimerMilliC;
App.Packet -> AMSenderC;
App.AMPacket ->ActiveMessageC;
}

wxWidgets: Client connects to the server, but the server does not recognize

I'm creating (at the time, to learn how) two applications console: a server and a client.
The client can connect to the server. If the server is not available, the application terminates with error.
The server waits make a connection, on line socketServer->Accept(1);. When the client connects, the code continues.. The problem is that the "if" following (if (socketServer->IsConnected()) {) evaluates to false.
Full source
Client
#include <wx/wxprec.h>
#include <wx/cmdline.h>
#include <wx/socket.h>
#include <wx/app.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
static const wxCmdLineEntryDesc cmdLineDesc[] = {
{ wxCMD_LINE_SWITCH, "h", "help", "show this help message",
wxCMD_LINE_VAL_NONE, wxCMD_LINE_OPTION_HELP },
{ wxCMD_LINE_OPTION, "ip", NULL, "set ip; the default values is 127.0.0.1", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL },
{ wxCMD_LINE_OPTION, "p", "port", "set port; the default values is 3000", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL },
{ wxCMD_LINE_NONE }
};
int main(int argc, char **argv) {
// Startup
wxApp::CheckBuildOptions(WX_BUILD_OPTIONS_SIGNATURE, "program");
wxInitializer initializer;
if (!initializer) {
fprintf(stderr, "Failed to initialize the wxWidgets library, aborting.\n");
return -1;
}
// Default variables
wxString ip = "127.0.0.1";
wxString port = "3000";
// Parse
wxCmdLineParser parser(cmdLineDesc, argc, argv);
switch (parser.Parse()) {
case -1:
return 0;
break;
case 0:
parser.Found("ip", &ip);
parser.Found("p", &port);
break;
default:
break;
}
// Socket
wxPrintf("Creating socket...\n");
wxSocketClient *socketClient = new wxSocketClient(wxSOCKET_NONE);
wxPrintf("Addressing...\n");
wxPrintf("Usando ip %s\n", ip);
wxIPV4address addr;
if (!addr.Hostname(ip)) {
wxPrintf("Could not set hostname !\n");
return 1;
}
wxPrintf("Usando porta %s\n", port);
if (!addr.Service(port)) {
wxPrintf("Could not set service !\n");
return 1;
}
wxPrintf("Trying to make connection...\n");
if (socketClient->Connect(addr, true)) {
wxPrintf("Success\n");
} else {
wxPrintf("Error!\n");
return 1;
}
// Tell the server which test we are running
wxPrintf("Sending...\n");
unsigned char c = 0xDE;
socketClient->Write(&c, 1);
// This test also is similar to the first one but it sends a
// large buffer so that wxSocket is actually forced to split
// it into pieces and take care of sending everything before
// returning.
socketClient->SetFlags(wxSOCKET_WAITALL);
// Note that len is in kbytes here!
const unsigned char len = 32;
wxCharBuffer buf1(len * 1024);
for (size_t i = 0; i < len * 1024; i++)
buf1.data()[i] = (char) (i % 256);
socketClient->Write(&len, 1);
socketClient->Write(buf1, len * 1024);
wxPrintf("End!\n");
while (1) {
}
return 0;
}
Server
#include <wx/wxprec.h>
#include <wx/cmdline.h>
#include <wx/socket.h>
#include <wx/app.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
static const wxCmdLineEntryDesc cmdLineDesc[] = {
{ wxCMD_LINE_SWITCH, "h", "help", "show this help message",
wxCMD_LINE_VAL_NONE, wxCMD_LINE_OPTION_HELP},
{ wxCMD_LINE_SWITCH, "d", "dummy", "a dummy switch"},
// ... your other command line options here...
{ wxCMD_LINE_NONE}
};
int main(int argc, char **argv) {
// Startup
wxApp::CheckBuildOptions(WX_BUILD_OPTIONS_SIGNATURE, "program");
wxInitializer initializer;
if (!initializer) {
fprintf(stderr, "Failed to initialize the wxWidgets library, aborting.\n");
return -1;
}
// Creat socket
wxPrintf("Criando socket...\n");
wxSocketServer *socketServer;
wxIPV4address addr;
if (!addr.Hostname("127.0.0.1")) {
wxPrintf("Could not set hostname !\n");
return 1;
}
if (!addr.Service(3000)) {
wxPrintf("Could not set service !\n");
return 1;
}
socketServer = new wxSocketServer(addr);
if (!socketServer->IsOk()) {
wxPrintf("Could not listen at the specified port !\n");
return 1;
}
// Efetuar conexao
wxPrintf("Waiting for connection...\n");
socketServer->Accept(1);
if (socketServer->IsConnected()) {
wxPrintf("Success\n");
} else {
wxPrintf("Not connected\n");
}
while (1) {
}
return 0;
}
After hours studying and trying, I solved the problem.
wxPrintf("Waiting for connection...\n");
wxSocketBase socketTest;
socketServer->AcceptWith(socketTest, true);
if (socketTest.IsConnected()) {
wxPrintf("Success\n");
} else {
wxPrintf("Not connected\n");
}
In the manual is written a detail that had not understood:
Accepts an incoming connection request, and creates a new wxSocketBase
object which represents the server-side of the connection.

Resources