Sending data to Spark Core from a Visual C++ console application

Hello all,

I have a VC++ console application which reads data from a Depth camera, based on the depth data, I am tracking certain behaviors and I am trying to send data to a Spark Core to control vibration motors. I wanted to know if there are any resources to use the console application as a server and several spark cores as clients which receive data from the pc.

I cannot use any other tool for development because of the limited depth camera resources.

Thanks.

Hi Sarang,

Have you heard of Casablanca? It’s an open source C++ REST SDK that Microsoft develops. You could have your VC++ console app use Casablance to make REST calls to your cores through the Spark Cloud. I’ve experimented a bit with this in my own application, and it seems like a good way to bring RESTful services into C++. The Casablanca site is here:

If you didn’t want to use the Spark Cloud, perhaps you could have your console app act as a TCP server, and the cores could connect to it directly.

Hope that helps,

John

2 Likes

@Sarang, you can try UDP broadcast also along with @jmdaly suggested.

1 Like

@jmdaly

Thanks for replying.

I prefer not to use the spark cloud.

I am looking for a simple console application which acts as a server and Spark Cores as the clients and then send data to the cores. I am very new to client-server programming and I don’t know how to implement a server in C++. Any ideas how that can be done. any resources would be appreciated.

Thanks again.

@Sarang, I suppose you are using VC++ here, the following describes how to open a TCP socket and listens for clients, you may have to modify it according to your needs.

http://msdn.microsoft.com/en-us/library/windows/desktop/ms737593(v=vs.85).aspx

1 Like

Thanks so much. I will try it and let you know if it works.

@krvarma

I tried using winsock and used the Server code to try to connect the core to it.

The server runs fine, the client runs fine(I checked it on the serial monitor) but the client is not able to connect to the server.

On the serial monitor, it says

connecting.....

connection failed.

disconnecting.

and this continues

Here is the server code

#undef UNICODE

#define WIN32_LEAN_AND_MEAN

#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>

// Need to link with Ws2_32.lib
#pragma comment (lib, "Ws2_32.lib")
// #pragma comment (lib, "Mswsock.lib")

#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "5555"

int __cdecl main(void) 
{
    WSADATA wsaData;
    int iResult;

    SOCKET ListenSocket = INVALID_SOCKET;
    SOCKET ClientSocket = INVALID_SOCKET;

    struct addrinfo *result = NULL;
    struct addrinfo hints;

    int iSendResult;
    char recvbuf[DEFAULT_BUFLEN];
    int recvbuflen = DEFAULT_BUFLEN;
    
    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (iResult != 0) {
        printf("WSAStartup failed with error: %d\n", iResult);
        return 1;
    }

    ZeroMemory(&hints, sizeof(hints));
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
    hints.ai_flags = AI_PASSIVE;

    // Resolve the server address and port
    iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
    if ( iResult != 0 ) {
        printf("getaddrinfo failed with error: %d\n", iResult);
        WSACleanup();
        return 1;
    }

    // Create a SOCKET for connecting to server
    ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
    if (ListenSocket == INVALID_SOCKET) {
        printf("socket failed with error: %ld\n", WSAGetLastError());
        freeaddrinfo(result);
        WSACleanup();
        return 1;
    }

    // Setup the TCP listening socket
    iResult = bind( ListenSocket, result->ai_addr, (int)result->ai_addrlen);
    if (iResult == SOCKET_ERROR) {
        printf("bind failed with error: %d\n", WSAGetLastError());
        freeaddrinfo(result);
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }

    freeaddrinfo(result);

    iResult = listen(ListenSocket, SOMAXCONN);
    if (iResult == SOCKET_ERROR) {
        printf("listen failed with error: %d\n", WSAGetLastError());
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }

    // Accept a client socket
    ClientSocket = accept(ListenSocket, NULL, NULL);
    if (ClientSocket == INVALID_SOCKET) {
        printf("accept failed with error: %d\n", WSAGetLastError());
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }

    // No longer need server socket
    closesocket(ListenSocket);

    // Receive until the peer shuts down the connection
    do {

        iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);
        if (iResult > 0) {
            printf("Bytes received: %d\n", iResult);

        // Echo the buffer back to the sender
            iSendResult = send( ClientSocket, recvbuf, iResult, 0 );
            if (iSendResult == SOCKET_ERROR) {
                printf("send failed with error: %d\n", WSAGetLastError());
                closesocket(ClientSocket);
                WSACleanup();
                return 1;
            }
            printf("Bytes sent: %d\n", iSendResult);
        }
        else if (iResult == 0)
            printf("Connection closing...\n");
        else  {
            printf("recv failed with error: %d\n", WSAGetLastError());
            closesocket(ClientSocket);
            WSACleanup();
            return 1;
        }

    } while (iResult > 0);

    // shutdown the connection since we're done
    iResult = shutdown(ClientSocket, SD_SEND);
    if (iResult == SOCKET_ERROR) {
        printf("shutdown failed with error: %d\n", WSAGetLastError());
        closesocket(ClientSocket);
        WSACleanup();
        return 1;
    }

    // cleanup
    closesocket(ClientSocket);
    WSACleanup();

    return 0;
}

here’s the client code

TCPClient client;
byte server[] = { 192, 168, 1, 172 };
byte c;
int port = 5555;
int led = D7;
void setup()
{
  Serial.begin(9600);
  delay(10000);
  pinMode(led, OUTPUT);
}

void loop()
{
    Serial.println("connecting...");
    if (client.connect(server, port))
    {
        Serial.println("connected");
        delay(1000);
        if(client.read() == 49)
        {
            Serial.println("data readed");
            digitalWrite(led, HIGH);
            delay(10000);    
        }
        else
        {
            Serial.println("data not readed");
            digitalWrite(led, LOW);
        }
    }
    else
    {
        Serial.println("connection failed");
        digitalWrite(led, LOW);
    }
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
}

@Sarang, I modified the VC++ code and is working fine. The problem I was, I think the VC++ Server accepts and read bytes, if no bytes read then disconnects the client and shutdown the server. I modified it to accept and send command without reading anything. Here it is:

#include "stdafx.h"

#undef UNICODE

#define WIN32_LEAN_AND_MEAN

#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>

#pragma comment (lib, "Ws2_32.lib")

#define DEFAULT_PORT "5555"

int __cdecl main(void){
    WSADATA wsaData;
    int iResult;

    SOCKET ListenSocket = INVALID_SOCKET;
    SOCKET ClientSocket = INVALID_SOCKET;

    struct addrinfo *result = NULL;
    struct addrinfo hints;

    char cmd = 49;

    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (iResult != 0) {
        printf("WSAStartup failed with error: %d\n", iResult);
        return 1;
    }

    ZeroMemory(&hints, sizeof(hints));
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
    hints.ai_flags = AI_PASSIVE;

    // Resolve the server address and port
    iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
    if ( iResult != 0 ) {
        printf("getaddrinfo failed with error: %d\n", iResult);
        WSACleanup();
        return 1;
    }

    // Create a SOCKET for connecting to server
    ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
    if (ListenSocket == INVALID_SOCKET) {
        printf("socket failed with error: %ld\n", WSAGetLastError());
        freeaddrinfo(result);
        WSACleanup();
        return 1;
    }

    // Setup the TCP listening socket
    iResult = bind( ListenSocket, result->ai_addr, (int)result->ai_addrlen);
    if (iResult == SOCKET_ERROR) {
        printf("bind failed with error: %d\n", WSAGetLastError());
        freeaddrinfo(result);
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }

    freeaddrinfo(result);

    iResult = listen(ListenSocket, SOMAXCONN);
    if (iResult == SOCKET_ERROR) {
        printf("listen failed with error: %d\n", WSAGetLastError());
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }

    // Receive until the peer shuts down the connection
    do {
		// Accept a client socket
		ClientSocket = accept(ListenSocket, NULL, NULL);
		if (ClientSocket == INVALID_SOCKET) {
			printf("accept failed with error: %d\n", WSAGetLastError());
			closesocket(ListenSocket);
			WSACleanup();
			return 1;
		}

		printf("Sending %c...", cmd);

		iResult = send( ClientSocket, &cmd, 1, 0 );
		if (iResult == SOCKET_ERROR) {
			printf("send failed with error: %d\n", WSAGetLastError());
			closesocket(ClientSocket);
			WSACleanup();
			return 1;
		}
		printf(" bytes sent: %d\n", iResult);

		cmd = (cmd == 49) ? 48 : 49;
    } while (iResult > 0);

	// No longer need server socket
    closesocket(ListenSocket);

    // shutdown the connection since we're done
    iResult = shutdown(ClientSocket, SD_SEND);
    if (iResult == SOCKET_ERROR) {
        printf("shutdown failed with error: %d\n", WSAGetLastError());
        closesocket(ClientSocket);
        WSACleanup();
        return 1;
    }

    // cleanup
    closesocket(ClientSocket);
    WSACleanup();

    return 0;
}

And the Spark Core code, I just added a delay and client.flush()

TCPClient client;
byte server[] = { 192, 168, 0, 11 };
byte c;
int port = 5555;
int led = D7;
void setup()
{
  Serial.begin(9600);
  delay(10000);
  pinMode(led, OUTPUT);
}

void loop()
{
    Serial.println("connecting...");
    
    if (client.connect(server, port)){
        Serial.println("connected");
        
        delay(1000);
        
        if(client.read() == 49){
            Serial.println("data readed");
            digitalWrite(led, HIGH);
            delay(10000);    
        }
        else{
            Serial.println("data not readed");
            digitalWrite(led, LOW);
        }
    }
    else{
        Serial.println("connection failed");
        digitalWrite(led, LOW);
    }
    
    Serial.println();
    Serial.println("disconnecting.");
    
    client.flush();
    client.stop();
    
    delay(2000);
}

The code just blinks the on-board LED, can you try this?

1 Like

@ krvarma, I tried it… I am still getting this.

are there any specific needs to run this code. Like network and stuff?

Do I need to make any changes to the code other than the IP address?

@krvarma
It worked… I had some firewall issues… thank you very much…!!!

2 Likes

Good to know it is working!