Move kfile interface to the io/ directory.
[bertos.git] / bertos / net / pocketbus.c
1 /**
2  * \file
3  * <!--
4  * This file is part of BeRTOS.
5  *
6  * Bertos is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19  *
20  * As a special exception, you may use this file as part of a free software
21  * library without restriction.  Specifically, if other files instantiate
22  * templates or use macros or inline functions from this file, or you compile
23  * this file and link it with other files to produce an executable, this
24  * file does not by itself cause the resulting executable to be covered by
25  * the GNU General Public License.  This exception does not however
26  * invalidate any other reasons why the executable file might be covered by
27  * the GNU General Public License.
28  *
29  * Copyright 2007 Develer S.r.l. (http://www.develer.com/)
30  * -->
31  *
32  * \brief pocketBus protocol implementation.
33  *
34  * pocketBus protocol is a simple strictly master-slave protocol, usable
35  * in embedded systems.
36  * pocketBus frame is as follows:
37  * <pre>
38  * +----------------------------------------+
39  * | STX | VER | ADDR | PAYLOAD | CKS | ETX |
40  * +----------------------------------------+
41  * |     |     |      |         |     |     |
42  * + 1B  + 1B  +  2B  + N Byte  + 2B  + 1B  +
43  * </pre>
44  *
45  * - STX, 1 byte (0x02), packet start
46  * - VER, 1 byte, packet version
47  * - ADDR, 2 byte, slave address
48  * - PAYLOAD, N byte, data field
49  * - CKS, 2 byte, checksum
50  * - ETX, 1 byte, (0x03) packet end
51  *
52  * Protocol parsing start on STX reception. When the receiving routine
53  * finds an STX char, it starts to read characters from the bus
54  * until an ETX is received. Once a packet is received,
55  * the parser checks packet correctness and checksum. If all is OK
56  * the payload is returned.
57  *
58  * STX (0x02), ETX(0x03) and ESC(0x1B) are special characters and cannot be
59  * transmitted inside payload without escaping them.
60  * To escape a character you must precede it by the ESC char.
61  * E.G. STX -> ESC + STX
62  *      ETX -> ESC + ETX
63  *      ESC -> ESC + ESC
64  *
65  * In the ADDR field is always specified the slave address.
66  * In the case of master trasmitting, ADDR contains the slave destination
67  * address.
68  * In case of slave replying, ADDR contains the slave address itself.
69  * Thus, the master device does not have an address. Packet must be routed to
70  * master by hardware bus design.
71  *
72  * The checksum algorithm used is rotating hash algortihm, quite simple but more
73  * reliable than simple checksum.
74  * The checksum in computed on all fields excluding STX, ETX and CHK fields itself.
75  * Checksum is computed on the packet *before* escaping.
76  * Escape sequence counts for 1 character only (the escaped one).
77  */
78
79 #include "pocketbus.h"
80
81 #include "cfg/cfg_pocketbus.h"
82
83 // Define logging setting (for cfg/log.h module).
84 #define LOG_LEVEL         POCKETBUS_LOG_LEVEL
85 #define LOG_VERBOSITY     POCKETBUS_LOG_FORMAT
86 #include <cfg/log.h>
87 #include <cfg/debug.h>
88 #include <cfg/macros.h>
89
90 #include <io/kfile.h>
91
92 #include <cpu/byteorder.h>
93
94 #include <string.h>
95
96 /**
97  * Send a character over pocketBus channel stream, handling escape mode.
98  */
99 void pocketbus_putchar(struct PocketBusCtx *ctx, uint8_t c)
100 {
101         /* Update checksum */
102         rotating_update1(c, &ctx->out_cks);
103
104         /* Escape characters with special meaning */
105         if (c == POCKETBUS_ESC || c == POCKETBUS_STX || c == POCKETBUS_ETX)
106                 kfile_putc(POCKETBUS_ESC, ctx->fd);
107
108         kfile_putc(c, ctx->fd);
109 }
110
111 /**
112  * Send pocketBus packet header.
113  */
114 void pocketbus_begin(struct PocketBusCtx *ctx, pocketbus_addr_t addr)
115 {
116         PocketBusHdr hdr;
117
118         hdr.ver = POCKETBUS_VER;
119         hdr.addr = cpu_to_be16(addr);
120         rotating_init(&ctx->out_cks);
121
122         /* Send STX */
123         kfile_putc(POCKETBUS_STX, ctx->fd);
124
125         /* Send header */
126         pocketbus_write(ctx, &hdr, sizeof(hdr));
127 }
128
129 /**
130  * Send buffer \a _data over bus, handling escape.
131  */
132 void pocketbus_write(struct PocketBusCtx *ctx, const void *_data, size_t len)
133 {
134         const uint8_t *data = (const uint8_t *)_data;
135
136         while (len--)
137                 pocketbus_putchar(ctx, *data++);
138 }
139
140 /**
141  * Send pocketBus packet tail.
142  */
143 void pocketbus_end(struct PocketBusCtx *ctx)
144 {
145         /* Send checksum */
146         rotating_t cks = cpu_to_be16(ctx->out_cks);
147         pocketbus_write(ctx, &cks, sizeof(cks));
148
149         /* Send ETX */
150         kfile_putc(POCKETBUS_ETX, ctx->fd);
151 }
152
153 /**
154  * Send buffer of \a data to address \a addr with a pocketBus packet over channel stream.
155  */
156 void pocketbus_send(struct PocketBusCtx *ctx, pocketbus_addr_t addr, const void *data, size_t len)
157 {
158         pocketbus_begin(ctx, addr);
159
160         /* Send data */
161         pocketbus_write(ctx, data, len);
162
163         pocketbus_end(ctx);
164 }
165
166
167 /**
168  * Try to read a packet from the pocketBus.
169  * \return true if a packet is received, false otherwise.
170  */
171 bool pocketbus_recv(struct PocketBusCtx *ctx, struct PocketMsg *msg)
172 {
173         int c;
174
175         /* Process incoming characters until buffer is not empty */
176         while ((c = kfile_getc(ctx->fd)) != EOF)
177         {
178                 /* Look for STX char */
179                 if (c == POCKETBUS_STX && !ctx->escape)
180                 {
181                         /* When an STX is found, inconditionally start a new packet */
182                         if (ctx->sync)
183                                 kprintf("pocketBus double sync!\n");
184
185                         ctx->sync = true;
186                         ctx->len = 0;
187                         rotating_init(&ctx->in_cks);
188                         continue;
189                 }
190
191                 if (ctx->sync)
192                 {
193                         /* Handle escape mode */
194                         if (c == POCKETBUS_ESC && !ctx->escape)
195                         {
196                                 ctx->escape = true;
197                                 continue;
198                         }
199
200                         /* Handle message end */
201                         if (c == POCKETBUS_ETX && !ctx->escape)
202                         {
203                                 ctx->sync = false;
204
205                                 /* Check minimum size */
206                                 if (ctx->len < sizeof(PocketBusHdr) + sizeof(rotating_t))
207                                 {
208                                         kprintf("pocketBus short pkt!\n");
209                                         continue;
210                                 }
211
212                                 /* Remove checksum bytes from packet len */
213                                 ctx->len -= sizeof(rotating_t);
214
215                                 /* Compute checksum */
216                                 rotating_update(ctx->buf, ctx->len, &ctx->in_cks);
217                                 uint8_t cks_h = *(ctx->buf + ctx->len);
218                                 uint8_t cks_l = *(ctx->buf + ctx->len + 1);
219
220                                 rotating_t recv_cks = (cks_h << 8) | cks_l;
221
222                                 /* Checksum check */
223                                 if (recv_cks == ctx->in_cks)
224                                 {
225                                         PocketBusHdr *hdr = (PocketBusHdr *)ctx;
226
227                                         /* Check packet version */
228                                         if (hdr->ver == POCKETBUS_VER)
229                                         {
230                                                 /* Packet received, set msg fields */
231                                                 msg->payload = ctx->buf + sizeof(PocketBusHdr);
232                                                 msg->addr = be16_to_cpu(hdr->addr);
233                                                 msg->len = ctx->len - sizeof(PocketBusHdr);
234                                                 msg->ctx = ctx;
235                                                 return true;
236                                         }
237                                         else
238                                         {
239                                                 kprintf("pocketBus version mismatch, here[%d], there[%d]\n", POCKETBUS_VER, hdr->ver);
240                                                 continue;
241                                         }
242                                 }
243                                 else
244                                 {
245                                         kprintf("pocketBus cks error, here[%04X], there[%04X]\n", ctx->in_cks, recv_cks);
246                                         continue;
247                                 }
248
249                         }
250
251                         ctx->escape = false;
252
253                         /* Check buffer overflow: simply ignore
254                            received data and go to unsynced state. */
255                         if (ctx->len >= CONFIG_POCKETBUS_BUFLEN)
256                         {
257                                 kprintf("pocketBus buffer overflow\n");
258                                 ctx->sync = false;
259                                 continue;
260                         }
261
262                         /* Put received data in the buffer */
263                         ctx->buf[ctx->len] = c;
264                         ctx->len++;
265                 }
266         }
267
268         /*
269          * Check stream status.
270          */
271         if (kfile_error(ctx->fd))
272         {
273                 LOG_ERR("fd status[%04X]\n", kfile_error(ctx->fd));
274                 kfile_clearerr(ctx->fd);
275         }
276
277         return false;
278 }
279
280
281 /**
282  * Initialize pocketBus protocol handler.
283  */
284 void pocketbus_init(struct PocketBusCtx *ctx, struct KFile *fd)
285 {
286         ASSERT(ctx);
287         ASSERT(fd);
288
289         memset(ctx, 0, sizeof(*ctx));
290         ctx->fd = fd;
291 }