libduck.c 1.38 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <err.h>
#include <stdlib.h>
#include <termios.h>
#include <stdarg.h>
#include "libduck.h"

#ifndef DUCK_BAUD
# define DUCK_BAUD B115200
#endif /* DUCK_BAUD */

static int duckfd = 0;

void open_duck(const char *fname)
{
     duckfd = open(fname, O_NOCTTY | O_RDWR);
     
     if (duckfd == -1) {
	  err(EXIT_FAILURE, "Failed to open '%s'", fname);
     }
}

void configure_duck(void)
{
     struct termios tio;
     if (tcgetattr(duckfd, &tio)) {
	  err(EXIT_FAILURE, "tcgetattr failed");
     }
     cfsetospeed(&tio, DUCK_BAUD);

     if (tcsetattr(duckfd, TCSANOW, &tio)) {
	  err(EXIT_FAILURE, "tcsetattr failed");
     }
}

static int duck_printf(const char *fmt, ...)
{
     va_list ap;
     va_start(ap, fmt);
     return vdprintf(duckfd, fmt, ap) < 0;
}

static int validate_motor(int motor)
{
     return motor >= 1 && motor <= 3;
}

int duck_set_position(int motor, int angle)
{
     if (!validate_motor(motor)) return -1;
     if (abs(angle) > 180) return -1;
     return duck_printf("s %d %d\n", motor, angle);
}

int duck_delay(int ms)
{
     return duck_printf("d %d\n", ms);
}

int duck_set_velocity(int motor, int deg_per_sec)
{
     if (!validate_motor(motor)) return -1;
     if (abs(deg_per_sec) > 1000) return -1;
     return duck_printf("v %d %d\n", motor, deg_per_sec);
}

void close_duck(void)
{
     close(duckfd);
}