summaryrefslogtreecommitdiff
path: root/zup.h
blob: 463f1211763d5a58194738cd17bac5ce68d67b30 (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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
#ifndef ZUP_H
#define ZUP_H

#include <stdio.h>
#include <stdarg.h>
#include <stdint.h>
#include <stddef.h>
#include <assert.h>

#include <termios.h>

#define LEN(x) (sizeof(x) / sizeof(x[0]))

enum error {
    ERR_TIMEOUT = -1,
    ERR_READ = -2,
    ERR_WRITE = -3,
    ERR_NACK = -4,
    ERR_ARGS = -5
};

struct param {
    char port[32];
    speed_t baud;
    unsigned int repl : 1;
    unsigned int human_readable : 1;
    unsigned int verbose : 2;
};

#ifdef __GNUC__
#define PACKED __attribute__((packed))
#else
#define PACKED
#endif

enum header_type {
    CMD_PING,
    CMD_INFO,
    CMD_BOOT,
    CMD_READ,
    CMD_WRITE,
    CMD_IO_READ,
    CMD_IO_WRITE,
    CMD_ECHO
};

struct header {
    uint8_t type;
    uint8_t bank;
    uint16_t address;
    uint16_t length;
    uint16_t checksum;
} PACKED;

static_assert(sizeof(struct header) == 8, "struct header is not PACKED");

enum ack {
    ACK = 0x00,
    NACK = 0xFF
};

static inline int
max(int x, int y)
{
    return x > y ? x : y;
}

static inline int
min(int x, int y)
{
    return x > y ? y : x;
}

extern struct param param;

static inline void
msg(int level, const char *fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);
    if (param.verbose >= level) {
        fprintf(stderr, "DEBUG [%d]: ", level);
        vfprintf(stderr, fmt, ap);
    }
    va_end(ap);
}

uint16_t
crc16(const void *buf, size_t len);

int
z_boot(int fd, uint8_t bank, uint16_t address);

int
z_read(int fd, uint8_t bank, uint16_t address, uint16_t length, uint8_t *buf);

int
z_write(int fd, uint8_t bank, uint16_t address, uint16_t length,
        const uint8_t *buf);

int
z_echo(int fd, uint16_t length, uint8_t *buf);

int
open_tty(const char *port, int baud);

int
run_commands(int fd, int ncmd, char **cmds);

int
run_line(int fd, char *line, const char *sep);

void
repl(int fd);

void
print_error(int error);

void
hexdump(size_t start_address, size_t len, const uint8_t *buf);

#define MAX_ARGS 5
#define MAX_PACKET_SIZE 256
#define MAX_ATTEMPTS 3
#define MAX_TRANS_ATTEMPTS 5

#define VERSION "1.0.0"

#define DEBUG_MODE 1

#endif // ZUP_H