1 #include <rtthread.h>
2 #include <ymodem.h>
3 #include <dfs_posix.h>
4 #include <stdlib.h>
5
6 #include <board.h>
7
8 struct custom_ctx
9 {
10 struct rym_ctx parent;
11 int fd;
12 int flen;
13 char fpath[256];
14 };
15
_rym_bg(struct rym_ctx * ctx,rt_uint8_t * buf,rt_size_t len)16 static enum rym_code _rym_bg(
17 struct rym_ctx *ctx,
18 rt_uint8_t *buf,
19 rt_size_t len)
20 {
21 struct custom_ctx *cctx = (struct custom_ctx*)ctx;
22 cctx->fpath[0] = '/';
23 /* the buf should be the file name */
24 strcpy(&(cctx->fpath[1]), (const char*)buf);
25 cctx->fd = open(cctx->fpath, O_CREAT | O_WRONLY | O_TRUNC, 0);
26 if (cctx->fd < 0)
27 {
28 rt_err_t err = rt_get_errno();
29 rt_kprintf("error creating file: %d\n", err);
30 rt_kprintf("abort transmission\n");
31 return RYM_CODE_CAN;
32 }
33
34 cctx->flen = atoi((const char*)buf+strlen((const char*)buf)+1);
35 if (cctx->flen == 0)
36 cctx->flen = -1;
37 return RYM_CODE_ACK;
38 }
39
_rym_tof(struct rym_ctx * ctx,rt_uint8_t * buf,rt_size_t len)40 static enum rym_code _rym_tof(
41 struct rym_ctx *ctx,
42 rt_uint8_t *buf,
43 rt_size_t len)
44 {
45 struct custom_ctx *cctx = (struct custom_ctx*)ctx;
46 RT_ASSERT(cctx->fd >= 0);
47 if (cctx->flen == -1)
48 {
49 write(cctx->fd, buf, len);
50 }
51 else
52 {
53 int wlen = len > cctx->flen ? cctx->flen : len;
54 write(cctx->fd, buf, wlen);
55 cctx->flen -= wlen;
56 }
57 return RYM_CODE_ACK;
58 }
59
_rym_end(struct rym_ctx * ctx,rt_uint8_t * buf,rt_size_t len)60 static enum rym_code _rym_end(
61 struct rym_ctx *ctx,
62 rt_uint8_t *buf,
63 rt_size_t len)
64 {
65 struct custom_ctx *cctx = (struct custom_ctx*)ctx;
66
67 RT_ASSERT(cctx->fd >= 0);
68 close(cctx->fd);
69 cctx->fd = -1;
70
71 return RYM_CODE_ACK;
72 }
73
rym_write_to_file(rt_device_t idev)74 rt_err_t rym_write_to_file(rt_device_t idev)
75 {
76 rt_err_t res;
77 struct custom_ctx *ctx = rt_malloc(sizeof(*ctx));
78
79 RT_ASSERT(idev);
80
81 rt_kprintf("entering RYM mode\n");
82
83 res = rym_recv_on_device(&ctx->parent, idev, RT_DEVICE_OFLAG_RDWR | RT_DEVICE_FLAG_INT_RX,
84 _rym_bg, _rym_tof, _rym_end, 1000);
85
86 /* there is no Ymodem traffic on the line so print out info. */
87 rt_kprintf("leaving RYM mode with code %d\n", res);
88 rt_kprintf("file %s has been created.\n", ctx->fpath);
89
90 rt_free(ctx);
91
92 return res;
93 }
94
95 #ifdef RT_USING_FINSH
96 #include <finsh.h>
ry(char * dname)97 rt_err_t ry(char *dname)
98 {
99 rt_err_t res;
100
101 rt_device_t dev = rt_device_find(dname);
102 if (!dev)
103 {
104 rt_kprintf("could not find device:%s\n", dname);
105 return -RT_ERROR;
106 }
107
108 res = rym_write_to_file(dev);
109
110 return res;
111 }
112 FINSH_FUNCTION_EXPORT(ry, receive files by ymodem protocol);
113 #endif
114