summaryrefslogtreecommitdiff
path: root/recipes-extended/multitech/set-rs485/set-rs485.c
blob: 1e5309296c0150a6f39d6683afb084cc4c97598f (plain)
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
73
74
75
76
77
78
79
80
81
#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <linux/serial.h>

int openserial(char *devicename)
{
    int fd;

    if ((fd = open(devicename, O_RDWR)) == -1) {
        perror("openserial(): open()");
        return 0;
    }

    return fd;
}

int setRS485(int fd, int state)
{
    struct serial_rs485 rs485;

    if (ioctl(fd, TIOCGRS485, &rs485) == -1) {
        perror("TIOCGRS485");
        return 0;
    }

    //printf("Old RS485 flags %x\n", rs485.flags);

    if (state)
        rs485.flags |= SER_RS485_ENABLED;
    else
        rs485.flags &= ~SER_RS485_ENABLED;

    if (ioctl(fd, TIOCSRS485, &rs485) == -1) {
        perror("TIOCSRS485");
        return 0;
    }

    //printf("New RS485 flags %x\n", rs485.flags);

    return 1;
}

int main(int argc, char *argv[])
{
    int fd;

    if (argc != 3) {
        printf("Usage: set_rs485hd tty 0|1\n");
        return 1;
    }

    char *serialdev = argv[1];
    char *state_str = argv[2];

    int state = atoi(state_str);

    fd = openserial(serialdev);
    if (!fd) {
        fprintf(stderr, "Error while initializing %s.\n", serialdev);
        return 1;
    }

    printf("%s: setting RS485 to ", serialdev);

    if (state)
        printf("%s\n", "enabled");
    else
        printf("%s\n", "disabled");

    if (setRS485(fd, state))
        return 0;
    else
        return 1;
}