TCP communication with cRIO

I’ve been trying to get TCP connections working with the cRIO. I have an Android app and robot code setup. I’ve gotten them to connect to each other, but every time I spawn a process it crashes the whole thing. This is my code, is there any options that I’m getting wrong?

App code:


public class BotSmithsAppActivity extends Activity 
{
	static final int PORT_NUMBER = 1500;
	static final String IP_ADDR = "10.43.9.2";
	
	static final int MOVE_ARM_UP = 0;
	static final int MOVE_ARM_DOWN = 1;
	
	//Inits socket
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        //Arm up button
        final Button upButton = (Button)findViewById(R.id.ARM_UP);
        upButton.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v) 
            {
                sendAction(MOVE_ARM_UP);
            }
        });
        
        //Arm down button
        final Button downButton = (Button)findViewById(R.id.ARM_DOWN);
        downButton.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v) 
            {
                sendAction(MOVE_ARM_DOWN);
            }
        });
    }
    
    void sendAction(int actionType)
    {
    	try
        {
			Socket s = new Socket(IP_ADDR, PORT_NUMBER);
			OutputStream out = s.getOutputStream();
			
			out.write(actionType);
			
			s.close();
		} 
        catch (UnknownHostException e) 
		{
			e.printStackTrace();
		} 
        catch (IOException e) 
		{
			e.printStackTrace();
		}
    }
}

Robot code:


VOID tcpServerWorkTask(int sFd, char* address, u_short port);

#define MOVE_ARM_UP 0
#define MOVE_ARM_DOWN 1

class AppControl;

AppControl* g_appCtrl = NULL;

class AppControl : public IterativeRobot
{
public:
	
	static const unsigned int MAX_CONNECTIONS = 1;
	static const unsigned int SERVER_WORK_PRIORITY = 100;
	static const unsigned int SERVER_STACK_SIZE = 1000;
	
	sockaddr_in m_serverAddr;
	int m_sFd;
	
	char m_workName[16];
	
	std::auto_ptr<Jaguar> m_armMotor;
	
	AppControl(void)
		:m_disabled(false)
	{
		g_appCtrl = this;
		
		m_armMotor.reset(new Jaguar(3));
	}

	void TeleopInit()
	{
		m_disabled = false;
		
		int sockAddrSize = sizeof(struct sockaddr_in);
		
		//Fill out server address
		m_serverAddr.sin_family = AF_INET;
		m_serverAddr.sin_len = sockAddrSize;
		m_serverAddr.sin_port = 1500;
		m_serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
		
		//Init socket.
		if ((m_sFd = socket(AF_INET, SOCK_STREAM, 0)) == ERROR) 
		{ 
			perror("socket"); 
			printf("
 Error connecting to socket.

");
			return;
		}
		printf("Initialized socket.
");
		
		//Bind to socket
		if (bind(m_sFd, (struct sockaddr*)&m_serverAddr, sockAddrSize) == ERROR) 
		{ 
			perror("bind");
			close(m_sFd);
			printf("
 Error binding to socket.

");
			return;
		}
		printf("Bound socket
");
		
		//Set socket to listen for connections.
		if (listen(m_sFd, MAX_CONNECTIONS) == ERROR)
		{ 
			perror("listen");
			close(m_sFd);
			printf("
 Error setting socket to listen mode.

");
			return;
		}
		printf("Listening on socket 1500
");
		
		//Wait for connections
		FOREVER
		{
			if ( m_disabled )
			{
				break;
			}
			
			sockaddr_in clientAddr;
			int newFd = 0;
			
			//Accept connection from client
			if ((newFd = accept (m_sFd, (struct sockaddr*)&clientAddr, &sockAddrSize)) == ERROR) 
			{
				perror("accept");
				close(m_sFd);
				printf("
 Error accepting connection

");
				return;
			}
			
			//Spawn work task
			printf("Spawning work task
");
			if (taskSpawn(m_workName, SERVER_WORK_PRIORITY, 0, SERVER_STACK_SIZE,
			(FUNCPTR)tcpServerWorkTask, newFd,
			(int)inet_ntoa(clientAddr.sin_addr), ntohs(clientAddr.sin_port), 
			0, 0, 0, 0, 0, 0, 0) == ERROR)
			{ 
				perror("taskSpawn");
				printf("
Error spawning task closing new file descriptor

");
				close(newFd);
			}
		}
		
		printf("closing server socket.
");
		close(m_sFd);
	}
	
	void TeleopDisabled()
	{
		m_disabled = true;
	}
	
	bool m_disabled;
	
	friend VOID tcpServerWorkTask(int sFd, char* address, u_short port);
};

VOID tcpServerWorkTask(int sFd, char* address, u_short port)
{
	unsigned int i = 0;
	read(sFd, (char*)&i, sizeof(unsigned int));
	
	std::cout << "Data: " << i << "
";
	std::cout << "Port: " << (int)port << "
";
	std::cout << "Address: " << address << "
";
 	
	if ( g_appCtrl != NULL )
	{
		if ( i == MOVE_ARM_UP )
		{
			printf("Arm up
");
			//g_appCtrl->m_armMotor->Set(-0.5f);
		}
		else if ( i == MOVE_ARM_DOWN )
		{
			printf("Arm down
");
			//g_appCtrl->m_armMotor->Set(0.5f);
		}
	}
	
	printf("freeing address
");
	free(address);
	printf("Closing file descriptor.
");
	close(sFd);
	printf("Closed file descriptor.
");
}

START_ROBOT_CLASS(AppControl);

I left out includes and imports. I get some Task Exited error. The error code is 1114118.

I’m not sure exactly what is wrong but I think you need a different architecture for your tcp server code on the robot. We were able to get things working using the examples on this website:

http://beej.us/guide/bgnet/

In particular, our “server” code uses ‘select’ to see if any of the clients have anything to say. We can then “poll” rather than putting our robot code inside of an infinite loop like you’re having to do. This page has some information on using ‘select’:

http://beej.us/guide/bgnet/output/html/multipage/advanced.html#select

Using this, our server code was all inside a function call rather than the other way around and we didn’t have to spawn any tasks.

Hope this helps!

The VxWorks taskSpawn command has great flexibility, but on the down-side, it gives you plenty power to shoot yourself in the foot.

I looked up the error code and didn’t quite find it. http://www.vxdev.com/docs/vx55man/vxworks/errno/errnoNumList.html has memlib errors that go up to 1114117, but no …8. All of those are related to a bad pointer or access to memory you aren’t supposed to access. I don’t have vxworks dev tools at home. Try searching for the error code. I suspect you’ll find it in the memlib header file and it will give a hint as to the issue.

Meanwhile, the easiest problems to have with spawning a task are to make the stack too small or to leave floating point registers out of the stack frame which will lead to a corruption once you accidentally use floats. Try adding a zero to the stack size and reviewing all of the other jillion parameters to spawn to see if any of them sound necessary.

Greg McKaskle

Okay, I’ll test that out when I can actually access the robot.

I’m certainly not an expert when it comes to TCP packets and IP addresses as the such… But if your team number is 4309 shouldn’t your ip address in the code be 10.43.09.2?? I believe you are representing yourself in the code as team 439. I’m probably wrong but that is my guess!

static final String IP_ADDR = “10.43.9.2”;

I can connect just fine using that ip address with everything else. But you might be right, I’ll change it and see what happens. I’ve been able to spawn tasks, they just crash.

Um, no.
009 or 09 or 9 are all identical numbers.
The .9. translates into a bit pattern padded with leading zeros to fill out the field.
Adding more leading zeros has no effect.

That is what I figured, logically though it confuses me. For sake of argument let’s say we have team 439, 4309 and 4390 on the field all at the same time, what happens to communications then?

The IP addresses are all distinct:

Team 439: 10.4.39.X
Team 4309: 10.43.9.X
Team 4390: 10.43.90.X

I have code that we used last year to have the driverstation send data to the crio. It spawns a task, and while it wasn’t used to move the robot, it may help with what you are trying to do.

I’ll post it when I get home. It is udp, not tcp because I didn’t think we need the over head for what we were doing, and could afford to lose messages if need be. And it’s not really robust but …

Here’s the code that we used. Worked fine for what we needed, and hopefully helps you.


#include "WPILib.h"
#include "Tracker.h"
#include "sockLib.h" 
#include "inetLib.h" 
#include "stdioLib.h" 
#include "strLib.h" 
#include "ioLib.h" 
#include "fioLib.h"

#define BAD_ANGLE			361.0
#define BAD_DISTANCE		-1.0

struct request { 
	char message[1023];     /* message buffer */ 
};

int
udpServer(Tracker *p) 
{ 
	struct sockaddr_in  serverAddr;    /* server's socket address */ 
	struct sockaddr_in  clientAddr;    /* client's socket address */ 
	struct request      clientRequest; /* request/Message from client */ 
	int                 sockAddrSize;  /* size of socket address structure */ 
	int                 sFd;           /* socket file descriptor */ 
	char                inetAddr[INET_ADDR_LEN];
	Tracker::targetInfo_t 		myinfo;
	

	sockAddrSize = sizeof(struct sockaddr_in); 
    bzero((char *)&serverAddr, sockAddrSize);
    serverAddr.sin_family = AF_INET; 
    serverAddr.sin_port = htons(p->getPort()); 
    serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
    
	if((sFd = socket(AF_INET, SOCK_DGRAM, 0)) == ERROR) { 
		perror("socket"); 
		return ERROR;
	}
	
    if(bind(sFd, (struct sockaddr *)&serverAddr, sockAddrSize) == ERROR) { 
    	perror("bind");
    	close(sFd);
    	return ERROR;
    }
    for(;;) {
       	char *ptr = clientRequest.message;
 
        if(recvfrom(sFd, (char *)&clientRequest, sizeof(clientRequest), 0, 
            (struct sockaddr *)&clientAddr, &sockAddrSize) == ERROR) {
            perror("recvfrom");
            close(sFd);
            return ERROR;
        }
        
        inet_ntoa_b(clientAddr.sin_addr, inetAddr);
        
        p->packetsReceived++;
       	memcpy((char *)&(myinfo.angle),    ptr, sizeof(myinfo.angle));    ptr += sizeof(myinfo.angle);
       	memcpy((char *)&(myinfo.distance), ptr, sizeof(myinfo.distance)); ptr += sizeof(myinfo.distance);
       	myinfo.isvalid = *ptr++;
       	p->setTarget(&myinfo);
	} 
 }

Tracker::Tracker(Solenoid *inner, Solenoid *outer, ushort port)
{
	m_semaphore = semBCreate(SEM_Q_PRIORITY, SEM_FULL);
	m_tinfo.isvalid  = false;
	m_tinfo.angle    = BAD_ANGLE;
	m_tinfo.distance = BAD_DISTANCE;
	m_port  = port;
	m_inner = inner;
	m_outer = outer;
	m_needFree = false;
	m_task = new Task("udpDashInfo", (FUNCPTR)udpServer);
	m_task->Start((UINT32)this);
	packetsReceived = 0;
	return;
}

Tracker::Tracker(Solenoid &inner, Solenoid &outer, ushort port)
{
	m_semaphore = semBCreate(SEM_Q_PRIORITY, SEM_FULL);
	m_tinfo.isvalid  = false;
	m_tinfo.angle    = BAD_ANGLE;
	m_tinfo.distance = BAD_DISTANCE;
	m_port  = port;
	m_inner = &inner;
	m_outer = &outer;
	m_needFree = false;
	m_task = new Task("udpDashInfo", (FUNCPTR)udpServer);
	m_task->Start((UINT32)this);
	packetsReceived = 0;
	return;
}

Tracker::Tracker(UINT8 inner, UINT8 outer, ushort port)
{
	m_semaphore = semBCreate(SEM_Q_PRIORITY, SEM_FULL);
	m_tinfo.isvalid  = false;
	m_tinfo.angle    = BAD_ANGLE;
	m_tinfo.distance = BAD_DISTANCE;
	m_port  = port;
	m_inner = new Solenoid(inner);
	m_outer = new Solenoid(outer);
	m_needFree = true;
	m_task = new Task("udpDashInfo", (FUNCPTR)udpServer);
	m_task->Start((UINT32)this);
	packetsReceived = 0;
	return;
}

Tracker::~Tracker()
{
	semFlush(m_semaphore);
	if(m_task) {
		m_task->Stop();
		delete m_task;
	}
	if(m_needFree) {
		delete m_inner;
		delete m_outer;
	}
	return;
}

bool
Tracker::targetAquired()
{
	return m_tinfo.isvalid;
}

float
Tracker::getAngle()
{
	targetInfo_t t;
	
	getTarget(&t);
	return t.angle;
}

float
Tracker::getDistance()
{
	targetInfo_t t;
	
	getTarget(&t);
	return t.distance;
}

ushort
Tracker::getPort()
{
	return m_port;
}

void
Tracker::getTarget(targetInfo_t *t)
{
	CRITICAL_REGION(m_semaphore)
	{
		memcpy((char *)t, (char *)&m_tinfo, sizeof(*t));
		if(!m_tinfo.isvalid) {
			t->angle    = BAD_ANGLE;
			t->distance = BAD_DISTANCE;
		}
	}
	END_REGION;
	return;
}

void
Tracker::setTarget(targetInfo_t *t)
{
	CRITICAL_REGION(m_semaphore)
	{
		m_tinfo = *t;
		if(!m_tinfo.isvalid) {
			t->angle    = BAD_ANGLE;
			t->distance = BAD_DISTANCE;
		}
	}
	END_REGION;
}

void
Tracker::illuminateTarget(bool on)
{
	m_inner->Set(on);
	m_outer->Set(on);
	return;
}