Skip to content
Snippets Groups Projects
Commit 41cd74b3 authored by Park Tae hyeon's avatar Park Tae hyeon
Browse files

Upload New File

parent da9692c1
No related branches found
No related tags found
No related merge requests found
server.c 0 → 100644
#include <arpa/inet.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>
#include <dirent.h>
#include <wiringPiI2C.h>
#include <wiringPi.h>
#include <sys/wait.h>
#define BUFFER_MAX 3
#define DIRECTION_MAX 56
#define VALUE_MAX 256
#define IN 0
#define OUT 1
#define PWM 0
#define LOW 0
#define HIGH 1
#define DISTANCE 5
#define POUT_UL 23
#define PIN_UL 24
#define POUT_LED 17
// Define some device parameters
#define I2C_ADDR 0x27 // I2C device address
// Define some device constants
#define LCD_CHR 1 // Mode - Sending data
#define LCD_CMD 0 // Mode - Sending command
#define LINE1 0x80 // 1st line
#define LINE2 0xC0 // 2nd line
#define LCD_BACKLIGHT 0x08 // On
// LCD_BACKLIGHT = 0x00 # Off
#define ENABLE 0b00000100 // Enable bit
char msg[3];
int led = 0;
int fd;
void typeFloat(float myFloat);
void typeInt(int i);
void ClrLcd(void);
void lcdLoc(int line);
void typeChar(char val);
void typeln(const char *s);
void lcd_byte(int bits, int mode);
void lcd_toggle_enable(int bits);
void lcd_init();
void error_handling(char *message) {
fputs(message, stderr);
fputc('\n', stderr);
exit(1);
}
int flag = 0;
// float to string
void typeFloat(float myFloat) {
char buffer[20];
sprintf(buffer, "%4.2f", myFloat);
typeln(buffer);
}
// int to string
void typeInt(int i) {
char array1[20];
sprintf(array1, "%d", i);
typeln(array1);
}
// clr lcd go home loc 0x80
void ClrLcd(void) {
lcd_byte(0x01, LCD_CMD);
lcd_byte(0x02, LCD_CMD);
}
// go to location on LCD
void lcdLoc(int line) {
lcd_byte(line, LCD_CMD);
}
// out char to LCD at current position
void typeChar(char val) {
lcd_byte(val, LCD_CHR);
}
// this allows use of any size string
void typeln(const char *s) {
while ( *s ) lcd_byte(*(s++), LCD_CHR);
}
void lcd_byte(int bits, int mode) {
//Send byte to data pins
// bits = the data
// mode = 1 for data, 0 for command
int bits_high;
int bits_low;
// uses the two half byte writes to LCD
bits_high = mode | (bits & 0xF0) | LCD_BACKLIGHT ;
bits_low = mode | ((bits << 4) & 0xF0) | LCD_BACKLIGHT ;
// High bits
wiringPiI2CReadReg8(fd, bits_high);
lcd_toggle_enable(bits_high);
// Low bits
wiringPiI2CReadReg8(fd, bits_low);
lcd_toggle_enable(bits_low);
}
void lcd_toggle_enable(int bits) {
// Toggle enable pin on LCD display
delayMicroseconds(500);
wiringPiI2CReadReg8(fd, (bits | ENABLE));
delayMicroseconds(500);
wiringPiI2CReadReg8(fd, (bits & ~ENABLE));
delayMicroseconds(500);
}
void lcd_init() {
// Initialise display
lcd_byte(0x33, LCD_CMD); // Initialise
lcd_byte(0x32, LCD_CMD); // Initialise
lcd_byte(0x06, LCD_CMD); // Cursor move direction
lcd_byte(0x0C, LCD_CMD); // 0x0F On, Blink Off
lcd_byte(0x28, LCD_CMD); // Data length, number of lines, font size
lcd_byte(0x01, LCD_CMD); // Clear display
delayMicroseconds(500);
}
static int GPIOExport(int pin) {
char buffer[BUFFER_MAX];
ssize_t bytes_written;
int fd;
fd = open("/sys/class/gpio/export", O_WRONLY);
if (-1 == fd) {
fprintf(stderr, "Failed to open export for writing!\n");
return (-1);
}
bytes_written = snprintf(buffer, BUFFER_MAX, "%d", pin);
write(fd, buffer, bytes_written);
close(fd);
return (0);
}
static int GPIOUnexport(int pin) {
char buffer[BUFFER_MAX];
ssize_t bytes_written;
int fd;
fd = open("/sys/class/gpio/unexport", O_WRONLY);
if (-1 == fd) {
fprintf(stderr, "Failed to open unexport for writing!\n");
return (-1);
}
bytes_written = snprintf(buffer, BUFFER_MAX, "%d", pin);
write(fd, buffer, bytes_written);
close(fd);
return (0);
}
static int GPIODirection(int pin, int dir) {
static const char s_directions_str[] = "in\0out";
char path[DIRECTION_MAX] = "/sys/class/gpio/gpio%d/direction";
int fd;
snprintf(path, DIRECTION_MAX, "/sys/class/gpio/gpio%d/direction", pin);
fd = open(path, O_WRONLY);
if (-1 == fd) {
fprintf(stderr, "Failed to open gpio direction for writing!\n");
return (-1);
}
if (-1 ==
write(fd, &s_directions_str[IN == dir ? 0 : 3], IN == dir ? 2 : 3)) {
fprintf(stderr, "Failed to set direction!\n");
return (-1);
}
close(fd);
return (0);
}
static int GPIORead(int pin) {
char path[VALUE_MAX];
char value_str[3];
int fd;
snprintf(path, VALUE_MAX, "/sys/class/gpio/gpio%d/value", pin);
fd = open(path, O_RDONLY);
if (-1 == fd) {
fprintf(stderr, "Failed to open gpio value for reading!\n");
return (-1);
}
if (-1 == read(fd, value_str, 3)) {
fprintf(stderr, "Failed to read value!\n");
return (-1);
}
close(fd);
return (atoi(value_str));
}
static int GPIOWrite(int pin, int value) {
static const char s_values_str[] = "01";
char path[VALUE_MAX];
int fd;
snprintf(path, VALUE_MAX, "/sys/class/gpio/gpio%d/value", pin);
fd = open(path, O_WRONLY);
if (-1 == fd) {
fprintf(stderr, "Failed to open gpio value for writing!\n");
return (-1);
}
if (1 != write(fd, &s_values_str[LOW == value ? 0 : 1], 1)) {
fprintf(stderr, "Failed to write value!\n");
return (-1);
close(fd);
return (0);
}
}
void* thread_situation(){//상황등
char msg[200] = {0};
if (GPIOExport(POUT_LED) == -1) {
exit(1);
}
if (GPIODirection(POUT_LED, OUT) == -1) {
exit(1);
}
while(1){
if(led == 1){
if (GPIOWrite(POUT_LED, 1) == -1) {
exit(1);
}
}else{
if (GPIOWrite(POUT_LED, 0) == -1) {
exit(1);
}
}
usleep(500 * 1000);
}
if (GPIOUnexport(POUT_LED) == -1) {
exit(1);
}
}
void* thread_ultrasonic(){//초음파 센서
char msg[200] = {0};
clock_t start_t, end_t;
double time;
if (-1 == GPIOExport(POUT_UL) || -1 == GPIOExport(PIN_UL)) {
printf("gpio export err\n");
exit(1);
}2
usleep(100000);
if (-1 == GPIODirection(POUT_UL, OUT) || -1 == GPIODirection(PIN_UL, IN)) {
printf("gpio direction err\n");
exit(1);
}
GPIOWrite(POUT_UL, 0);
usleep(10000);
// start
while (1){
if (-1 == GPIOWrite(POUT_UL, 1)) {
printf("gpio write/trigger err\n");
exit(1);
}
// 1sec == 1000000ultra_sec, 1ms = 1000ultra_sec
usleep(10);
GPIOWrite(POUT_UL, 0);
while (GPIORead(PIN_UL) == 0) {
start_t = clock();
}
while (GPIORead(PIN_UL) == 1) {
end_t = clock();
}
time = (double)(end_t - start_t) / CLOCKS_PER_SEC; // ms
if(time/2*34000<DISTANCE){
ClrLcd();
lcdLoc(LINE1);
typeln("Process Start");
led = 1;
flag = 1;
}else if(flag == 1){
ClrLcd();
lcdLoc(LINE1);
typeln("Processing...");
}else{
ClrLcd();
lcdLoc(LINE1);
typeln("waiting");
led = 0;
}
usleep(1000000);
}
if (-1 == GPIOUnexport(POUT_UL) || -1 == GPIOUnexport(PIN_UL)) exit(1);
}
void* thread_LCD(){
if (wiringPiSetup () == -1) exit (1);
fd = wiringPiI2CSetup(I2C_ADDR);
printf("fd = %d ", fd);
lcd_init(); // setup LCD
}
void* action(void* arg){
int clnt_sock = *((int*)arg);
char msg[100] = {0};
pid_t var;
int state;
int count = 0;
var = fork(); //자식프로세스 생성
if(var==0){
printf("[pid:%d] redirect client fd\n",getpid(),clnt_sock);//클라이언트에 대한 정보 호출
while(1){
read(clnt_sock,msg,sizeof(msg)); //클라이언트로 부터 정보를 받아옴
if(!strcmp(msg,"END")){
ClrLcd();
lcdLoc(LINE1);
typeln("drone check");
lcdLoc(LINE2);
typeln("complete");
flag = 0;
}else if(!strcmp(msg,"NO")){
count++;
if(count >= 5){
ClrLcd();
lcdLoc(LINE1);
typeln("Belt Maifunction");
count = 0;
flag = 0;
}
}
}
}else{
printf("[pid:%d] process forekd\n",getpid());
wait(&state);//자식프로세스가 종료 할 때 까지 대기
}
close(clnt_sock);
}
void* do_clnt(void* arg){
int thr_id;
struct sockaddr_in clnt_addr;
socklen_t clnt_addr_size;
int serv_sock = *((int*)arg);
int clnt_sock[55]; //클라이언트 연결을 위해 선언
int i = 0;
pthread_t tid[2];
while (1) {
clnt_sock[i] = -1;
clnt_addr_size = sizeof(clnt_addr);
clnt_sock[i] =
accept(serv_sock, (struct sockaddr *)&clnt_addr, &clnt_addr_size);
if (clnt_sock[i] == -1) error_handling("accept() error");
printf("[*] client join\n");
printf("[*] wait for client\n");
pthread_create(&tid[i],NULL,action,(void*)&clnt_sock[i]); //멀티스레드를 사용하여 shell함수 호출
pthread_detach(tid[i]);//스레드 종료
i++;
}
close(serv_sock);//소켓 종료
}
int main(int argc, char *argv[]) {
int serv_sock;
struct sockaddr_in serv_addr;
int status;
int thr_id;
if (argc != 2) {
printf("Usage : %s <port>\n", argv[0]);
}
serv_sock = socket(PF_INET, SOCK_STREAM, 0);
if (serv_sock == -1) error_handling("socket() error");
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(atoi(argv[1]));
if (bind(serv_sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) == -1)
error_handling("bind() error");
if (listen(serv_sock, 5) == -1) error_handling("listen() error");
printf("[*] socket initialized\n");
printf("[*] wait for client\n");
pthread_t tid[4];
thr_id = pthread_create(&tid[0], NULL, thread_LCD, NULL);//멀티스레드로 LCD 작동
if (thr_id < 0) {
perror("thread create error : ");
exit(0);
}
thr_id = pthread_create(&tid[1], NULL, thread_situation, NULL);//멀티스레드로 상황등 관리
if (thr_id < 0) {
perror("thread create error : ");
exit(0);
}
thr_id = pthread_create(&tid[2], NULL, thread_ultrasonic, NULL);//멀티스레드로 초음파 측정
if (thr_id < 0) {
perror("thread create error : ");
exit(0);
}
thr_id = pthread_create(&tid[3], NULL, do_clnt, (void *)&serv_sock);//클라이언트와 통신
if (thr_id < 0) {
perror("thread create error : ");
exit(0);
}
pthread_join(tid[0], (void **)&status);
pthread_join(tid[1], (void **)&status);
pthread_join(tid[2], (void **)&status);
pthread_join(tid[3], (void **)&status);//스레드가 종료하여 결합할 때까지 대기
printf("[*] session closed\n");
close(serv_sock);//소켓종료
return (0);
}
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment