filetransfer.c 9.22 KB
Newer Older
Hauke Mehrtens's avatar
Hauke Mehrtens committed
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
/*
 * BLE (Bluetooth Low energy) file transfer service.
 *
 * This file provides a BLE service and a characteristic which allows to 
 * write the content of the mytest.py file over BLE into the file system. 
 * We haven't found any existing BLE service which provides such a 
 * functionality so we implemented our own service.

 * The service uses the UUID in fileTransSvc
 * The characteristic uses the UUID in attTxChConfigUuid

 * BLE point to point links use a pretty small MTU (min 23 bytes, max 244
 * bytes) which is negotiated between the central and the peripheral (card10).
 * 
 * The first byte of each message is the type of message being send,
 * different types are supported and based on this type the next bytes
 * have different meaning.
 * 
 * TODOs:
 * * File deletion
 * * File read
 * * Directory creation
 * * Directory listing
 */

#include "wsf_types.h"
#include "wsf_os.h"
#include "wsf_buf.h"
#include "wsf_timer.h"
#include "wsf_trace.h"
#include "app_ui.h"
#include "fit/fit_api.h"
#include "hci_vs.h"

#include <epicardium.h>

#include "util/bstream.h"
#include "att_api.h"

#include "FreeRTOS.h"
#include "crc32.h"

#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <machine/endian.h>

/*!< \brief Service start handle. */
#define FILE_TRANS_START_HDL 0x820
/*!< \brief Service end handle. */
#define FILE_TRANS_END_HDL (FILE_TRANS_MAX_HDL - 1)

#define FILE_TRANS_UUID_SUFFIX                                                 \
	0x42, 0x23, 0x42, 0x23, 0x42, 0x23, 0x42, 0x23, 0x42, 0x23, 0x42, 0x23
#define FILE_TRANS_UUID_PREFIX 0x01, 0x23, 0x42

/*
 * This has to match in order and number of members to the functions
 * called in fileTransAddGroupDyn() otherwise the stack breaks.
 */
enum {
	/*!< \brief File transfer service declaration */
	FILE_TRANS_SVC_HDL = FILE_TRANS_START_HDL,
	/*!< \brief File transfer Central tx characteristic */
	FILE_TRANS_CENTRAL_TX_CH_HDL,
	/*!< \brief File transfer Central tx value */
	FILE_TRANS_CENTRAL_TX_VAL_HDL,
	/*!< \brief File transfer Central rx characteristic */
	FILE_TRANS_CENTRAL_RX_CH_HDL,
	/*!< \brief File transfer Central rx value */
	FILE_TRANS_CENTRAL_RX_VAL_HDL,
	/*!< \brief File transfer Central rx notification characteristic */
	FILE_TRANS_CENTRAL_RX_CCC_HDL,
	/*!< \brief Maximum handle. */
	FILE_TRANS_MAX_HDL
};

/* BLE File transfer Service UUID */
static const uint8_t fileTransSvc[] = { FILE_TRANS_UUID_SUFFIX,
					0x00,
					FILE_TRANS_UUID_PREFIX };

/* BLE File transfer Central TX configuration */
static const uint8_t txChConfig[] = { ATT_PROP_WRITE_NO_RSP,
				      UINT16_TO_BYTES(
					      FILE_TRANS_CENTRAL_TX_VAL_HDL),
				      FILE_TRANS_UUID_SUFFIX,
				      0x01,
				      FILE_TRANS_UUID_PREFIX };
/* BLE File transfer Central TX UUID */
static const uint8_t attTxChConfigUuid[] = { FILE_TRANS_UUID_SUFFIX,
					     0x01,
					     FILE_TRANS_UUID_PREFIX };

/* BLE File transfer Central RX configuration */
static const uint8_t rxChConfig[] = { ATT_PROP_READ | ATT_PROP_NOTIFY,
				      UINT16_TO_BYTES(
					      FILE_TRANS_CENTRAL_RX_VAL_HDL),
				      FILE_TRANS_UUID_SUFFIX,
				      0x02,
				      FILE_TRANS_UUID_PREFIX };
/* BLE File transfer Central RX UUID */
static const uint8_t attRxChConfigUuid[] = { FILE_TRANS_UUID_SUFFIX,
					     0x02,
					     FILE_TRANS_UUID_PREFIX };

/* File descriptor of the currently transferred file */
static int file_fd = -1;

/*
 * Create the BLE service description. 
 */
static void *fileTransAddGroupDyn(void)
{
	void *pSHdl;
	uint8_t initCcc[] = { UINT16_TO_BYTES(0x0000) };

	/* Create the service */
	pSHdl = AttsDynCreateGroup(FILE_TRANS_START_HDL, FILE_TRANS_END_HDL);

	if (pSHdl != NULL) {
		/* Primary service */
		AttsDynAddAttrConst(
			pSHdl,
			attPrimSvcUuid,
			fileTransSvc,
			sizeof(fileTransSvc),
			0,
			ATTS_PERMIT_READ
		);

		/* File transfer Central TX characteristic */
		AttsDynAddAttrConst(
			pSHdl,
			attChUuid,
			txChConfig,
			sizeof(txChConfig),
			0,
			ATTS_PERMIT_READ
		);

		/* File transfer Central TX, this contains information about the real data */
		AttsDynAddAttr(
			pSHdl,
			attTxChConfigUuid,
			NULL,
			0,
			128,
			ATTS_SET_WRITE_CBACK | ATTS_SET_VARIABLE_LEN,
			ATTS_PERMIT_WRITE
		);

		/* File transfer Central RX characteristic */
		AttsDynAddAttrConst(
			pSHdl,
			attChUuid,
			rxChConfig,
			sizeof(rxChConfig),
			0,
			ATTS_PERMIT_READ
		);

		/* File transfer Central RX, this contains information about the real data */
		AttsDynAddAttr(
			pSHdl,
			attRxChConfigUuid,
			NULL,
			0,
			64,
			ATTS_SET_READ_CBACK,
			ATTS_PERMIT_READ
		);

		/* File transfer Central RX notification channel */
		AttsDynAddAttr(
			pSHdl,
			attCliChCfgUuid,
			initCcc,
			sizeof(uint16_t),
			sizeof(uint16_t),
			ATTS_SET_CCC,
			ATTS_PERMIT_READ | ATTS_PERMIT_WRITE
		);
	}

	return pSHdl;
}

/**
 * Send a repose with an optional CRC.
 * 
 * The Central RX characteristic is filled and a notification is send in addition.
 * If msg is given message is added in addition.
 */
static void sendCrcResponse(
	dmConnId_t connId,
	char code,
	uint16_t crcLen,
	uint8_t *crcData,
	const char *msg
) {
	uint32_t crc;
	uint16_t len = 1;
	uint8_t answer[24];

	answer[0] = code;

	if (crcData) {
		crc = __htonl(CalcCrc32(0xffffffff, crcLen, crcData));
		memcpy(answer + len, &crc, sizeof(crc));
		len += 4;
	}

	if (msg) {
		if (strlen(msg) < sizeof(answer) - len) {
			strncpy((char *)answer + len,
				msg,
				sizeof(answer) - len);
			len += strlen(msg);
			printf("BLE file transfer: %s\n", msg);
		} else {
			printf("error message \"%s\" too long\n", msg);
		}
	}

	AttsSetAttr(FILE_TRANS_CENTRAL_RX_VAL_HDL, len, answer);
	AttsHandleValueNtf(connId, FILE_TRANS_CENTRAL_RX_VAL_HDL, len, answer);
}

static uint8_t bleFileOpen(dmConnId_t connId, uint8_t *pValue, uint16_t len)
{
	char filepath[100];

	if (len > sizeof(filepath)) {
		sendCrcResponse(connId, 'e', 0, NULL, "path too long");
		return ATT_ERR_RESOURCES;
	}

	/* Copy only file path and not type, make sure this is NULL terminated */
	strncpy(filepath, (char *)pValue + 1, len - 1);

	if (file_fd != -1)
		epic_file_close(file_fd);

	file_fd = epic_file_open(filepath, "w");
	if (file_fd < 0) {
		sendCrcResponse(connId, 'e', 0, NULL, "open failed");
		return ATT_ERR_RESOURCES;
	}
	sendCrcResponse(connId, 'S', len, pValue, NULL);
	return ATT_SUCCESS;
}

static uint8_t bleFileWrite(dmConnId_t connId, uint8_t *pValue, uint16_t len)
{
	uint32_t fileOffsetNet;
	uint32_t fileOffset;
	int res;

	if (len < 6) {
		sendCrcResponse(connId, 'e', 0, NULL, "msg too short");
		return ATT_ERR_LENGTH;
	}

	memcpy(&fileOffsetNet, pValue + 1, sizeof(fileOffsetNet));
	fileOffset = __ntohl(fileOffsetNet);

	res = epic_file_seek(file_fd, fileOffset, SEEK_SET);
	if (res) {
		sendCrcResponse(connId, 'e', 0, NULL, "seek failed");
		return ATT_ERR_RESOURCES;
	}

	res = epic_file_write(file_fd, pValue + 5, len - 5);
	if (res != (len - 5)) {
		sendCrcResponse(connId, 'e', 0, NULL, "write failed");
		return ATT_ERR_RESOURCES;
	}

	sendCrcResponse(connId, 'C', len, pValue, NULL);
	return ATT_SUCCESS;
}

/*
 * Handle the Central TX characteristic which is used by the central to
 * issues file transfer commands on this peripheral.
 */
static uint8_t handleCentralTX(
	dmConnId_t connId,
	uint16_t handle,
	uint8_t operation,
	uint16_t offset,
	uint16_t len,
	uint8_t *pValue,
	attsAttr_t *pAttr
) {
	if (len < 1) {
		sendCrcResponse(connId, 'e', 0, NULL, "msg too short");
		return ATT_ERR_LENGTH;
	}

	if (operation == ATT_PDU_PREP_WRITE_REQ) {
		/* In case of relaiable write, just return success and wait for exec. */
		return ATT_SUCCESS;
	} else if (
		operation != ATT_PDU_EXEC_WRITE_REQ &&
		operation != ATT_PDU_WRITE_CMD) {
		printf("operation 0x%x not supported, try normal write\n",
		       operation);
		return ATT_ERR_INVALID_PDU;
	}

	switch (pValue[0]) {
	case 's':
		return bleFileOpen(connId, pValue, len);

	case 'c':
		return bleFileWrite(connId, pValue, len);

	case 'f':
		if (file_fd != -1) {
			epic_file_close(file_fd);
			file_fd = -1;
		}
		sendCrcResponse(connId, 'F', 0, NULL, NULL);
		return ATT_SUCCESS;

	case 'e':
		if (file_fd != -1) {
			epic_file_close(file_fd);
			file_fd = -1;
		}
		sendCrcResponse(connId, 'E', 0, NULL, NULL);
		return ATT_SUCCESS;

	case 'E':
		printf("Error was acked");
		return ATT_SUCCESS;

	default:
		sendCrcResponse(connId, 'e', 0, NULL, "unkown command");
		return ATT_ERR_NOT_SUP;
	}
	return ATT_ERR_NOT_SUP;
}

/*
 * BLE file transfer write callback.
 * 
 * This gets called when data is written by a BLE central to our BLE
 * peripheral. Here we take care of handling the received data.
 */
static uint8_t writeCallback(
	dmConnId_t connId,
	uint16_t handle,
	uint8_t operation,
	uint16_t offset,
	uint16_t len,
	uint8_t *pValue,
	attsAttr_t *pAttr
) {
	switch (handle) {
	case FILE_TRANS_CENTRAL_TX_VAL_HDL:
		return handleCentralTX(
			connId, handle, operation, offset, len, pValue, pAttr
		);
	default:
		printf("unsupported characteristic: %c\n", handle);
		return ATT_ERR_HANDLE;
	}
}

static uint8_t readCallback(
	dmConnId_t connId,
	uint16_t handle,
	uint8_t operation,
	uint16_t offset,
	attsAttr_t *pAttr
) {
	printf("read callback\n");
	return ATT_SUCCESS;
}

/*
 * This registers and starts the BLE file transfer service.
 */
void bleFileTransfer_init(void)
{
	void *pSHdl = fileTransAddGroupDyn();
	AttsDynRegister(pSHdl, readCallback, writeCallback);
}