aboutsummaryrefslogtreecommitdiffstats
path: root/sercp.c
blob: 545f7254aa1698652950c1d9b84f239c40a5c1ca (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
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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <stdint.h>
#include <libgen.h>
#include <getopt.h>
#include <termios.h>
#include <error.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/signal.h>
#include <signal.h>
#include <fcntl.h>
#include <poll.h>

#define false 0
#define FALSE 0
#define true 1
#define TRUE 1

const char* _version = "v0.2";
// SERIAL
char MODEMDEVICE[64];
FILE *tapout_fd = NULL;
int is_outfile = 0;
int baud_rate = 0;
int wait_us = 200;
int wait_ms	= 800;
char *path;
char sercp_file[FILENAME_MAX];
unsigned char buff[32768];
unsigned char *p_buff;
unsigned int is_continue = 1;
unsigned int is_binary = 0;
struct pollfd spolfd_serial[1];	  // pole descriptoru pro poll

static int inp_indx = 0;
int serial_fd;
size_t out_indx;
struct sigaction saterm;           /* definition of signal action */

float width;		// width of terminal
long pos = 0;
int scp = 0;
int is_scp_read = 0;

typedef struct {
	uint16_t block_len;
	uint8_t  block_xor;
	uint8_t  block_sum;
} __attribute__((packed))  fi_sum;

typedef struct {
	uint16_t length;		// delka dat ve fileinfo
	uint8_t h_xor;			// xor bajtu fileinfa od fi_numblocks
	uint8_t h_sum;			// sum bajtu fileinfa od fi_numblocks
	uint8_t fi_numblocks;	// pocet bloku
	uint8_t fi_name[64];	// jmeno souboru - prozatim musi byt ve fromatu 8.3 - kvuli esxdosu
	uint8_t fi_date[8];		// nepouzito
	uint8_t fi_time[8];		// nepouzito
	fi_sum fi_blocks[256];	// delky a soucty bloku
} __attribute__((packed)) FILEINFO;

FILEINFO fileinfo;

void usage(void) {
	printf ("sercp %s (c)2018-2019 Pavel Vymetálek <pavel@vym.cz>\n", _version);
	printf ("serial copy for transfering file to/from ZX Spectrum 128 AY's RS232\n");
	printf ("Uses 1109bytes of fileinfo - blocks sums, filename, etc.\n");
	printf ("Usage:\nsercp [-v] [-h] -d /dev/serial [-b baud_rate] [-w time] [-r] <filename>\n");
	printf ("\t-v, --version\tShow version info\n");
	printf ("\t-h, --help\tShow this text\n");
	printf ("\t-d, --device\tCommunication device\n");
	printf ("\t-b, --baud\tSet the communication speed. Default 38400Bd\n");
	printf ("\t-w, --wait\tWaiting in milliseconds between transmitted blocks. Default is -w 800 milliseconds\n");
	printf ("\t-r, --read\tRead file from serial port\n");
}

// fileinfo 1109bytes
/************************************************************************/
void TestArgs (int argc, char *argv[])
{
	int c;
	while (1) {
		int option_index = 0;
		static struct option long_options[] = {
			{"device", required_argument, NULL, 'd'},
			{"baud", required_argument, NULL, 'b'},
			{"wait", required_argument, NULL, 'w'},
			{"read", no_argument, NULL, 'r'},
			{"version", no_argument, NULL, 'v'},
			{"help", no_argument, NULL, 'h'},
			{0, 0, 0, 0}
		};
		c = getopt_long (argc, argv, "d:b:w:rvh", long_options, &option_index);
		if (c == -1) {
			// konec parametru
			break;
		}
		switch (c) {
			case 'd':
				strncpy(MODEMDEVICE, optarg, strlen(optarg));
				// 				printf ("Serial port: %s\n", MODEMDEVICE);
				break;
			case 'b':
				baud_rate = atoi(optarg);
				break;
			case 'w':
				wait_us = atoi(optarg);
				wait_ms = atoi(optarg);
				break;
			case 'r':
				is_scp_read = 1;
				break;
			case 'v':
				printf ("%s\n", _version);
				exit(1);
				break;
			case 'h':
				usage();
				exit(1);
				break;
			default:
				break;
		}
	}
	if (optind < argc) {
		while (optind < argc){
			strncpy (&sercp_file[0], argv[optind++], 63);		// input file name or path - without option switch
		}
	}
}


/************************************************************************/

void signal_handler_sigterm (int status) {
	// CTRL+C pressed
	is_continue = 0; 	// do not continue
}

/************************************************************************/
int GetTerminalWidth(void) {
	struct winsize termsize;
	ioctl (STDOUT_FILENO, TIOCGWINSZ, &termsize);
	return (termsize.ws_col);
}

#define PROGRESS_PERCENT	0
#define PROGRESS_COMPLETTE	1
#define PROGRESS_ERROR_CSUM	2

/************************************************************************/
void DoProgress(size_t pos, size_t max, unsigned char csum_ok) {
	width = GetTerminalWidth();
	float percent, p, m;
	int imax = width - 40;
	int ipercent;
	int px;
	char progress_char;
	p = pos;
	m = max;
	percent = 100 / m * p;
	ipercent = percent / 100 * imax;
	if (is_binary) progress_char = '#';
	else  progress_char = '=';
	printf ("Proceed bytes: %6d/%6d [", (int) pos, (int)max);
	for (px = 0; px < imax; px++) {
		if (px < ipercent) printf ("%c", progress_char);
		else printf (" ");
	}
	if (csum_ok == 0) {
		printf ("] %3d %%\r", (int)percent);
	} else if (csum_ok == 1) {
		printf ("]  OK  \r");
	} else {
		printf ("]  ERR \r");
	}
	fflush (stdout);
}

/************************************************************************/

int CheckFileInfo(FILEINFO* p_fi) {
	unsigned char *p_fiinfo = (unsigned char*)p_fi;
	uint16_t fi_len;
	uint8_t fi_xor = 0;
	uint8_t fi_sum = 0;
	fi_len = p_fi->length;
	p_fiinfo += 4;			// suma se bude pocitat od offsetu 4
	for (uint16_t indx = 0; indx < (fi_len-4); indx++) {
		fi_xor ^= *p_fiinfo;
		fi_sum += *p_fiinfo;
		p_fiinfo++;
	}
	if (fi_xor == p_fi->h_xor && fi_sum == p_fi->h_sum) {
		return 0;
	}
	return -1;
}

/************************************************************************/
void CountFileInfoChecksum(FILEINFO* p_fi) {
	unsigned char *p_fiinfo = (unsigned char*)p_fi;
	uint16_t fi_len;
	uint8_t fi_xor = 0;
	uint8_t fi_sum = 0;
	fi_len = p_fi->length;
	p_fiinfo += 4;			// suma se bude pocitat od offsetu 4
	for (uint16_t indx = 0; indx < (fi_len-4); indx++) {
		fi_xor ^= *p_fiinfo;
		fi_sum += *p_fiinfo;
		p_fiinfo++;
	}
	p_fi->h_xor = fi_xor;
	p_fi->h_sum = fi_sum;
}

/************************************************************************/
int CheckSumBlock(FILEINFO* p_fi, uint8_t block_indx, uint8_t *p_buffer) {
	uint16_t block_len;
	uint8_t b_xor = 0;
	uint8_t b_sum = 0;
	uint8_t block_xor;
	uint8_t block_sum;
	block_len = p_fi->fi_blocks[block_indx].block_len;
	block_sum = p_fi->fi_blocks[block_indx].block_sum;
	block_xor = p_fi->fi_blocks[block_indx].block_xor;
	for (uint16_t indx = 0; indx < block_len; indx++) {
		b_xor ^= *p_buffer;
		b_sum += *p_buffer;
		p_buffer++;
	}
	if (b_xor == block_xor && b_sum == block_sum) {
		return 0;	// vrat se, je to v poradku
	}
	return -1;		// vrat se s chybou bloku
}

/************************************************************************/
void CountSumBlock(FILEINFO* p_fi, uint8_t block_indx, uint8_t *p_buffer, uint16_t block_len) {
	uint8_t block_xor = 0;
	uint8_t block_sum = 0;
	for (uint16_t indx = 0; indx < block_len; indx++) {
		block_xor ^= *p_buffer;
		block_sum += *p_buffer;
		p_buffer++;
	}
	p_fi->fi_blocks[block_indx].block_len = block_len;
	p_fi->fi_blocks[block_indx].block_sum = block_sum;
	p_fi->fi_blocks[block_indx].block_xor = block_xor;
}


/************************************************************************/
uint32_t GetOverallLen(FILEINFO *p_fi) {
	uint32_t overall_len = 0;
	uint8_t block_num = p_fi->fi_numblocks;
	for (uint8_t indx = 0; indx < block_num; indx++) {
		overall_len += p_fi->fi_blocks[indx].block_len;
	}
	return overall_len;
}

/************************************************************************/
void RecvSCP(void) {
	int recv_phase = 0;			// 0 - fileinfo, 1 - blok 16kiB, 2 - posledni blok
	uint8_t block_index = 0;
	int result;
	uint16_t len;
	uint16_t length = 0;
	uint16_t expected_len = 0;
// 	uint8_t expected_xor;
// 	uint8_t expected_sum;
	uint32_t overall_length = 0;		// celkova delka souboru
	uint32_t recv_length = 0;			// zatim prijatych dat ze souboru
	int err;

	FILEINFO *p_fileinfo = &fileinfo;
	unsigned char *p_buff = buff;
	tapout_fd = NULL;

	memset (p_fileinfo, 0, sizeof(fileinfo));
	while (is_continue) {
		result = poll (spolfd_serial, 1, 200);		// 200ms timeout
		if (result == 0) {
			// nic neprislo
			continue;
		}
		switch (recv_phase) {
			case 0:
				// prijem fileinfo
				if (spolfd_serial[0].revents & POLLIN) {
					len = read (serial_fd, p_buff, sizeof(fileinfo));
					p_buff += len;
					length += len;
					if (length == sizeof(fileinfo)) {
						memcpy((unsigned char*) p_fileinfo, buff, sizeof(fileinfo));
						if (CheckFileInfo(p_fileinfo) == 0) {
							printf("Prijato fileinfo\n");
							overall_length = GetOverallLen(p_fileinfo);
							printf("Nazev souboru: \"%s\" pocet bloku:%d, delka souboru: %u\n", p_fileinfo->fi_name, p_fileinfo->fi_numblocks, overall_length);
							recv_phase++;			// priste se uz prijimaji bloky
							block_index = 0;		// zacina se prvnim blokem
							p_buff = buff;			// buffer na zacatek
							length = 0;
							expected_len = p_fileinfo->fi_blocks[block_index].block_len;


							tapout_fd = fopen ((char*)p_fileinfo->fi_name, "w");
							if (tapout_fd == NULL) {
								err = errno;
								error (1, err, "can't open output file");
							}
						} else {
							printf("Fileinfo neni v cajku. Koncim...\n");
							break;
						}
						break;
					} else if (length > sizeof(fileinfo)){
						len = read (serial_fd, p_buff, sizeof(fileinfo));
						printf("Nejaky bordel. Koncim...\n");
						break;
					}
				}
				break;
			case 1:
				// prijem datoveho bloku - max. delka 16kiB
				if (spolfd_serial[0].revents & POLLIN) {
					len = read (serial_fd, p_buff, expected_len);
					p_buff += len;
					expected_len -= len;
					length += len;
					recv_length += len;
					DoProgress(recv_length, overall_length, PROGRESS_PERCENT);
					if (length == p_fileinfo->fi_blocks[block_index].block_len) {
						// prijaty prvni block
// 						printf("Prijaty blok c.%d delky: %d\n", block_index, length);
						if (CheckSumBlock(p_fileinfo, block_index, buff) == 0) {
							// blok je v cajku - zapsat do souboru
							if (tapout_fd) fwrite(buff, length, 1, tapout_fd);
						}
						length = 0;
						p_buff = buff;
						block_index++;
						expected_len = p_fileinfo->fi_blocks[block_index].block_len;
					}
					if (expected_len == 0 || block_index == 255) {
						printf ("\nKonec prenosu\n");
						recv_phase++;
						is_continue = 0;
						break;
					}
				} else if (length > 16384) {
						len = read (serial_fd, p_buff, 16384);
						printf("Nejaky bordel. Koncim...\n");
						break;
				}
			}
	}
	if (tapout_fd) fclose (tapout_fd);
	printf ("\n\nulozeno...\n");
}

/************************************************************************/
void SendSCP(void) {
	FILE *tap_fd;
	char *bname, *basec;			// pinter na kopii nazvu souboru - basename
	char *shortfilename;
	size_t fn_len;
	unsigned int err, no, len;
	struct stat st;
	FILEINFO *p_fileinfo = &fileinfo;
	unsigned char *p_buff = buff;
	uint32_t file_len;
	uint8_t num_blocks = 0;
	ssize_t odeslano;
	uint32_t len_sent;
	uint16_t sent_size;
	uint32_t overall_sent;


	no = stat(sercp_file, &st);
	if (no != 0) {
		err = errno;
		error(1, err, "can't stat input file");
	}

	tap_fd = fopen(sercp_file, "r");
	if (tap_fd == NULL)	{
		err = errno;
		error(1, err, "can't open input file");
	}
	if (st.st_size == 0) {
		printf ("Zero length of file. End\n");
		return;
	}
	printf ("File %s, length: %ld\n", sercp_file, st.st_size);
	memset (p_fileinfo, 0, sizeof(fileinfo));		// smazat fileinfo

	basec = strdup (sercp_file);
	bname = basename (basec);
	if (strlen(bname) > 12) {
		printf ("Short filename: ");
		shortfilename = strdup(bname);
		fn_len = strlen(shortfilename);
		memcpy(shortfilename+4, shortfilename+fn_len-8, 8);
		*(shortfilename+12) = 0;
		printf ("%s\n", shortfilename);
		bname = shortfilename;
	}

	memcpy(p_fileinfo->fi_name, bname, strlen(bname));
	file_len = (uint32_t) st.st_size;
	while (file_len) {
		len = fread(buff, 1, 16384, tap_fd);			// precti 16kiB dat
		CountSumBlock(p_fileinfo, num_blocks, buff, len);
// 		printf ("Blok c. %d, delka: %d\n", num_blocks, len);
		file_len -= len;
		num_blocks++;
	}
	p_fileinfo->fi_numblocks = num_blocks;
	p_fileinfo->length = num_blocks*4 + 85;
	CountFileInfoChecksum(p_fileinfo);
	odeslano = write (serial_fd, (void*)p_fileinfo, sizeof(fileinfo));
	tcdrain(serial_fd);
	printf("Fileinfo sent with filename: %s\n", bname);
	// TODO Cekat pauzu mezi bloky
	usleep (wait_ms * 1000);

	rewind(tap_fd);				// prenaseny soubor na zacatek
	file_len = (uint32_t) st.st_size;
	overall_sent = 0;
	while (file_len && is_continue) {
		len = fread(buff, 1, 16384, tap_fd);			// precti 16kiB dat
		p_buff = buff;
		sent_size = 256;
		len_sent = len;
		while (len_sent && is_continue) {
			odeslano = write (serial_fd, (void*)p_buff, sent_size);
			tcdrain(serial_fd);
			p_buff += odeslano;
			overall_sent += odeslano;
			len_sent -= odeslano;
			if (len_sent < 256) {
				sent_size = len_sent;
			}
			DoProgress(overall_sent, st.st_size, PROGRESS_PERCENT);
		}
		usleep (wait_ms * 1000);
		file_len -= len;
	}
	printf("\nFile sent...\n");
	fclose(tap_fd);
}

/************************************************************************/
/************************************************************************/
int main(int argc, char** argv, char** env)
{
	// osetreni breaku ^C
	saterm.sa_handler = signal_handler_sigterm;
	saterm.sa_flags = 0;
	sigaction (SIGINT, &saterm, NULL);
	width = GetTerminalWidth();

	// nastaveni serioveho portu
	struct termios oldtio, newtio;
	inp_indx = 0;
	if (argc < 2) {
		printf("You must specify the Serial device and file\n");
		usage();
		exit(1);
	}
	TestArgs (argc, argv);
	/* open the device to be non-blocking (read will return immediatly) */
	serial_fd = open(MODEMDEVICE, O_RDWR | O_NOCTTY | O_NONBLOCK);
	if (serial_fd < 0) {
		perror(MODEMDEVICE);
		return(-1);
	}
	tcgetattr(serial_fd, &oldtio); /* save current port settings */
	switch (baud_rate){
		case 115200:
			newtio.c_cflag = B115200 | CS8 | CLOCAL | CREAD;
			break;
		case 57600:
			newtio.c_cflag = B57600 | CS8 | CLOCAL | CREAD;
			break;
		default:
			baud_rate = 38400;
		case 38400:
			newtio.c_cflag = B38400 | CS8 | CLOCAL | CREAD;	// dva stopbity jsou nastaveny vsude, ale tady ne
			break;
		case 19200:
			newtio.c_cflag = B19200 | CS8 | CLOCAL | CREAD;
			break;
		case 9600:
			newtio.c_cflag = B9600 | CS8 | CLOCAL | CREAD;
			break;
		case 4800:
			newtio.c_cflag = B4800 | CS8 | CLOCAL | CREAD;
			break;
		case 2400:
			newtio.c_cflag = B2400 | CS8 | CLOCAL | CREAD;
			break;
		case 1200:
			newtio.c_cflag = B1200 | CS8 | CLOCAL | CREAD;
			break;
	}
	newtio.c_cflag |= CRTSCTS;		// CSTOPB - dva stop bity NEE
	printf ("Serial device: %s, communication speed is: %d Bd\n", MODEMDEVICE, baud_rate);
	newtio.c_iflag = 0;
	newtio.c_oflag = 0;
	newtio.c_lflag = 0;
	newtio.c_cc[VMIN] = 0;
	newtio.c_cc[VTIME] = 10;
	tcsetattr(serial_fd, TCSANOW, &newtio);
	tcflush(serial_fd, TCIOFLUSH);
	spolfd_serial[0].fd = serial_fd;		// nastaveni hlidaneho descriptoru
	spolfd_serial[0].events = POLLIN;		// hlidaji se data na vstupu

	// serial copy activated
	if (is_scp_read) {
		RecvSCP();
	} else {
		SendSCP();
	}
	close (serial_fd);
	return 0;
}