blob: 10f37a4cb591915f48bacce0394fea1387bf9030 [file] [log] [blame]
Adrien Destugues613f8592017-06-05 20:19:46 +02001/*
2 * Copyright 2017, Adrien Destugues, pulkomandy@pulkomandy.tk
3 * Distributed under terms of the MIT license.
4 */
5
6
7#include "cfs-fatfs.h"
8
9#include "cfs.h"
10#include "cfs-service.h"
11
12#include "fatfs/ff.h"
13
14#include <stdlib.h>
15
16static int s_open(const char *n, int f);
17static void s_close(int f);
18static int s_read(int f, char *b, unsigned int l);
19static int s_write(int f, char *b, unsigned int l);
20static int s_opendir(struct cfs_dir *p, const char *n);
21static int s_readdir(struct cfs_dir *p, struct cfs_dirent *e);
22static int s_closedir(struct cfs_dir *p);
23
24static const struct cfs_service_interface interface =
25 {
26 CFS_SERVICE_VERSION,
27 s_open,
28 s_close,
29 s_read,
30 s_write,
31 f_opendir,
32 s_readdir,
33 f_closedir
34 };
35
36EK_EVENTHANDLER(eventhandler, ev, data);
37EK_PROCESS(proc, CFS_SERVICE_NAME, EK_PRIO_NORMAL,
38 eventhandler, NULL, (void *)&interface);
39/*---------------------------------------------------------------------------*/
40EK_PROCESS_INIT(cfs_fatfs_init, arg)
41{
42 arg_free(arg);
43 ek_service_start(CFS_SERVICE_NAME, &proc);
44}
45/*---------------------------------------------------------------------------*/
46EK_EVENTHANDLER(eventhandler, ev, data)
47{
48 switch(ev) {
49 case EK_EVENT_INIT:
50 break;
51 case EK_EVENT_REQUEST_REPLACE:
52 ek_replace((struct ek_proc *)data, &interface);
53 break;
54 case EK_EVENT_REQUEST_EXIT:
55 ek_exit();
56 break;
57 }
58}
59/*---------------------------------------------------------------------------*/
60
61static int s_open(const char* n, int f)
62{
63 int mode;
64 if (f == CFS_READ)
65 mode = FA_READ | FA_OPEN_EXISTING;
66 else
67 mode = FA_WRITE | FA_CREATE_ALWAYS;
68 FIL* ptr = malloc(sizeof(FIL));
69 FRESULT r = f_open(ptr, n, mode);
70
71 if (r != FR_OK) {
72 free(ptr);
73 return -1;
74 }
75 return ptr;
76}
77
78static void
79s_close(int f)
80{
81 f_close(f);
82 free(f);
83}
84
85static int s_read(int f, char* b, unsigned int l)
86{
87 if (f == -1)
88 return -1;
89
90 int r = 0;
91 f_read(f, b, l, &r);
92 return r;
93}
94
95static int s_write(int f, char* b, unsigned int l)
96{
97 int r = 0;
98 f_write(f, b, l, &r);
99 return r;
100}
101
102
103static int s_readdir(struct cfs_dir *p, struct cfs_dirent *e)
104{
105 FILINFO info;
106 f_readdir(p, &info);
107
108 strncpy(e->name, info.fname, 13);
109 e->size = info.fsize;
110
111 return 0;
112}