Thursday, November 22, 2012

netdriver (OpenWrt) C source code


This code is from project: Android tablet controlling stepper motor

main.h

#ifndef _H_MAIN_H
#define _H_MAIN_H




#endif

main.c

#include "main.h"
#include "server.h"
#include "serial.h"

#include <stdio.h>

/****************************************************************************/
/* Main                                                                     */
/****************************************************************************/
int main(int argc, char **argv) {


   printf("Started\n");
   
   initSerial(SERIAL_DEVICE);
   
   serialCmd(35, 10);
 
   // start server on port 8000
   runServer(8000);

   closeSerial();

   return 0;
}

serial.h

#ifndef _H_SERIAL_H
#define _H_SERIAL_H


#define SERIAL_DEVICE      "/dev/ttyATH0"
#define SERIAL_SPEED       B9600

#define RECV_RST           1
#define RECV_ERR           2
#define RECV_OK            3
#define RECV_TIMEOUT       4


int initSerial(char *);
int writeCmd(char *);
int readAnswer(int);
int closeSerial(void);
int serialCmd(unsigned char, unsigned char);


#endif

serial.c

#include <stdio.h>
#include <string.h>
#include <termios.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <time.h>

#include "serial.h"


static int devHandle = -2;


/****************************************************************************/
/* Init serial port                                                         */
/****************************************************************************/
int initSerial(char *device) {
   
   struct termios opt;
   
   devHandle = open(device, O_RDWR| O_NOCTTY | O_NDELAY | O_SYNC);

   if (devHandle == -1) {
      perror("Unable to open device");
      return 1;
   }
   
   fcntl(devHandle, F_SETFL, FNDELAY);

   if (tcgetattr(devHandle, &opt) == -1) {
      perror("Unable to obtain device info");
      return 1;      
   }
   
   if (cfsetispeed(&opt, SERIAL_SPEED) !=0 ) {
      perror("Unable to set RX speed");
      return 1; 
   }

   if (cfsetospeed(&opt, SERIAL_SPEED) != 0) {
      perror("Unable to set TX speed");
      return 1;       
   }

   opt.c_cflag |= (CLOCAL | CREAD);

   opt.c_cflag &= ~PARENB;
   opt.c_cflag &= ~CSTOPB;
   opt.c_cflag &= ~CSIZE;
   opt.c_cflag |= CS8;
   
   opt.c_lflag &= ~(ICANON | ECHO);
   opt.c_oflag &= ~OPOST;

   if (tcsetattr(devHandle, TCSANOW, &opt) == -1) {
      perror("Unable to setup port");
      return 1;      
   }

   // cleaning rs232 buffer
   printf("Cleaning buffer, timeout is ok.\n");
   readAnswer(2); 

   return 0;
}


/****************************************************************************/
/* Write string to port                                                     */
/****************************************************************************/
int writeCmd(char *s) {
   
    if (write(devHandle, s, strlen(s)) == -1) {
      perror("Write error");
      return 1;
   }

   return 0;
}


/****************************************************************************/
/* Read answers from RS232 port                                             */
/****************************************************************************/
int readAnswer(int readSecWait) {
   
   char recvBuff = ' '; 
   int readBytes= 0;
   
   time_t   startTime;
   time_t   currentTime;
   
   time(&startTime);
   time(¤tTime);
      
   while(1) {
      recvBuff = ' ';      

      readBytes = read(devHandle, &recvBuff, 1);

      if (readBytes > 0) {
         
         switch(recvBuff) {
            
            case 'R': {
               return RECV_RST;
            } break;
            
            case 'O': {
               return RECV_OK;
            } break;
            
            case 'E': {
               printf("Communication error\n");
               return RECV_ERR;
            } break;
            
            default: {
               printf("Unknown answer\n");
               return RECV_ERR;
            }
         };
      }
      
      if (difftime(currentTime, startTime) >= readSecWait)
         break;
      
      time(¤tTime);
   }

   printf("Read timeout\n");
   return RECV_TIMEOUT;
}


/****************************************************************************/
/* Sending command to device connected to RS232                             */
/****************************************************************************/
int serialCmd(unsigned char x, unsigned char readWait) {
   
   char cmdBuff[4];
  
   // send 'R' - start transmission 
   writeCmd("R");

   if(readAnswer(readWait) == RECV_RST) {
      
      // prepare and send position information
      sprintf(cmdBuff, "%02dV", x);   
      writeCmd(cmdBuff);

      if(readAnswer(readWait) == RECV_OK)
         return 0;
      else
         printf("Without position confirmation !\n"); 
   } else
      printf("Without restet confirmation !\n"); 

   return 1;   
}


/****************************************************************************/
/* Cleanup                                                                  */
/****************************************************************************/
int closeSerial() {

   if(devHandle != -2 && close(devHandle) != 0) {
      perror("Closing device handle");
         return 1;
   }
   
   return 0;
}

server.h

#ifndef _H_SERVER_H
#define _H_SERVER_H


#define MAX_READ_SIZE 80

unsigned char runServer(short);

unsigned char getData(int *);

#endif

server.c

#include "server.h"
#include "serial.h"

#include <sys/types.h> 
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <error.h>
#include <errno.h>
#include <stdio.h>

unsigned char getData(int *sockFd) {
   
   ssize_t     readBytes;
   char        buff[MAX_READ_SIZE];
   
   float       x, y, z;
   static unsigned char xPos=45;
   
   memset(&buff, 0, MAX_READ_SIZE);
   
   // get data from socket
   if ( (readBytes = read(*sockFd, buff, MAX_READ_SIZE)) == 0) {
      printf("Connection closed by client\n");
      return 0;
   }
   
   x = 0;
   y = 0;
   z = 0;
   
   //printf("Debug: |%s|\n", buff);
   
   // if sscanf coud match format, then process data
   if(sscanf(buff, "%f %f %f\r\n", &x, &y, &z) == 3) {
      printf("Received % 2.4f, % 2.4f, % 2.4f\n", x, y, z);
      
      
      // ugly bugfix for to fast transmission, sscanf was matching
      // format, but nubers was to big, setting position is blocking
      // someday I will put in in a thread, but this is only 'hello accel'
      // program so why bother ...
      if(x < 6 ) {
         
         
         // rotated to the right
         if(x > 2) {
            xPos++;
         }
                                 
         // rotated to the left
         if(x < -2) {
            xPos--;
         }   

         // if we are in the range, set position
         if(xPos >=0 && xPos <91)
               serialCmd(xPos, 2);
      }
   }
   
   return 1;
}


unsigned char runServer(short port) {
   
   int                  listenFd, sockFd;
   
   socklen_t            cliLen;
   struct sockaddr_in   cliAddr, servAddr;
   
   if ( (listenFd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
      perror("Socket: ");
      return 1;
   }
   
   
   memset(&servAddr, 0, sizeof(struct sockaddr_in));
   
   servAddr.sin_family        = AF_INET;
   servAddr.sin_addr.s_addr   = htonl(INADDR_ANY);
   servAddr.sin_port          = htons(port);

   if( bind(listenFd, (struct sockaddr *) &servAddr, sizeof(struct sockaddr_in)) == -1) {
      perror("Bind: ");
      return 1;      
   } 
   
   if( listen(listenFd, 1) == -1) {
      perror("Listen: ");
      return 1;      
   }
   
   while( 1 ) {
      
      cliLen = sizeof(struct sockaddr_in);
      
      if ( (sockFd = accept(listenFd, (struct sockaddr *) &cliAddr, &cliLen)) < 0) {
         
         if (errno == EINTR)
            continue;
         
         perror("Accept: ");
         return 1;
      }
      
      printf("Connection from %s\n", inet_ntoa(cliAddr.sin_addr));
      
      while(getData(&sockFd));
      
      close(sockFd);
   }
   
   
   return 0;
}

Makefile

PROJECT_NAME=netdriver

OBJECTS=main.o server.o serial.o

INCLUDES=
#LIBS=-lpthread
LIBS=
MACROS= 


all: clean cls $(PROJECT_NAME)

$(PROJECT_NAME): $(OBJECTS)
 $(CC) -o $(PROJECT_NAME) $(OBJECTS) $(LDFLAGS) $(LIBS) $(MARCOS) $(INCLUDES)
  
main.o: main.c main.h
 $(CC) $(CFLAGS) $(INCLUDES) $(MACROS) -c main.c
 
server.o: server.c server.h
 $(CC) $(CFLAGS) $(INCLUDES) $(MACROS) -c server.c
 
serial.o: serial.c serial.h
 $(CC) $(CFLAGS) $(INCLUDES) $(MACROS) -c serial.c

clean:
  rm -f $(PROJECT_NAME) $(OBJECTS)

cls:
  clear

1 comment: