summaryrefslogtreecommitdiffstats
path: root/taptoser.c
blob: 263e4d5b85c8467d9a3a69aaec3b4c62f7b0c5a3 (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
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <getopt.h>
#include <termios.h>
#include <error.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/signal.h>
#include <fcntl.h>
#include <poll.h>

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


// SERIAL
char MODEMDEVICE[64];
FILE *tapout_fd = NULL;
int is_outfile = 0;
int baud_rate = 0;
#define FILENAME_LENGTH 400
char output_dump_file[FILENAME_LENGTH];
char tap_file[FILENAME_LENGTH];
unsigned char in_buff[65538];
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;


void usage(void) {
	printf ("Tap file over serial port uploader/downloader. (c)2012-2015 Pavel Vymetálek <pavel@vym.cz>\n");
	printf ("Based on utility tapheader: http://zeroteam.sk/tapheader.html (c)2012 Michal Jurica <mike@zeroteam.sk>\n");
	printf ("Usage:\ntaptoser [-v] [-h] [-o filename.tap] [-b|--baud baud_rate] -d /dev/serial tap_file\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. 4800Bd, 9600Bd, 19200Bd and 57600Bd (default) are supported\n");
	printf ("\t-B, --binary\tBinary output - received tap from ZX Spectrum will save without all tap's specific mishmash\n");
	printf ("\t-o, --outfile\tOutput file. Usualy *.tap or *.bin with in --binary mode\n");
}

void Set_DTR(unsigned short level) {
	int status;
	ioctl(serial_fd, TIOCMGET, &status);
	if (level) {
		status |= TIOCM_DTR;
	} else {
		status &= ~TIOCM_DTR;
	}
	ioctl(serial_fd, TIOCMSET, &status);
}

void TestCts(void) {
	int status;
	do {
		ioctl(serial_fd, TIOCMGET, &status);
		if (status & 0x20) break;
		usleep (100);
		if (is_continue == 0) return;
		//		printf ("status: %X\n",status);
	} while (1);
}


void TestArgs (int argc, char *argv[])
{
	int c;
	while (1) {
		int option_index = 0;
		static struct option long_options[] = {
 			{"outfile", required_argument, NULL, 'o'},
			{"device", required_argument, NULL, 'd'},
			{"baud", required_argument, NULL, 'b'},
			{"binary", no_argument, NULL, 'B'},
			{"version", no_argument, NULL, 'v'},
			{"help", no_argument, NULL, 'h'},
			{0, 0, 0, 0}
		};
		c = getopt_long (argc, argv, "o:d:b:Bvh", long_options, &option_index);
		if (c == -1) {
			// konec parametru
			break;
		}
		switch (c) {
			case 'h':
				usage();
				exit(1);
				break;
			case 'b':
				baud_rate = atoi(optarg);
				break;
			case 'd':
				strncpy(MODEMDEVICE, optarg, strlen(optarg));
// 				printf ("Serial port: %s\n", MODEMDEVICE);
				break;
			case 'o':
				strncpy (output_dump_file, optarg, strlen(optarg));
				is_outfile = 1;
				break;
			case 'B':
				printf ("Running in binary output mode\n");
				is_binary = 1;
				break;
			case 'v':
				printf ("Version 0.9.1 2015-07-22\n");
				exit(1);
				break;
			default:
				break;
		}
	}
	if (optind < argc) {
		while (optind < argc){
			strncpy (&tap_file[0], argv[optind++], 63);		// input tap file name - without option switch
		}
	}
}


// from tapheader utility
unsigned int h_len;

unsigned int getword(unsigned char* data) {
	return *data + 256 * (*(data + 1));
}

void tooshort(FILE *fd) {
	printf("Input file too short.\n\n");
	fclose(fd);
	exit(2);
}

// decode header1
void decode(unsigned char *header) {
	char name[11];
	unsigned int n;
	printf("\n");
	strncpy(name, (char*)(header+2), 10);
	name[10] = '\0';
	printf("Filename: %12s \n", name);
	printf("Flag: %4u ", (unsigned int)*header);
	n = getword(header+14);
	h_len = getword(header+12);

	switch(*(header+1)) {
		case '\0':
			printf("Type: 0 => program\nProgram length: %6u bytes ", h_len);
			if (n < 32768)	printf("Runs from line %5u\t", n);
			printf("Length without variables: %5u bytes ", getword(header+16));
			break;
		case '\1':
			printf("Type: 1 => number array\tLength: %6u bytes", h_len);
			break;
		case '\2':
			printf("Type: 2 => character array\tLength: %6u bytes", h_len);
			break;
		case '\3':
			if (n == 16384 && h_len == 6912)
				printf("Type: 3 => screen image\n");
			else
				printf("Type: 3 => bytes  "
					"Start address: %5u\t"
					"Length: %6u bytes\t3rd param: %4u",
					n, h_len, getword(header+16));
			break;
	}
	printf("\n");
}

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);
}

#define HEADER_RAW_LEN	21

void RecvTap() {
	unsigned int err;
	size_t len;
	int result;
	size_t block_pos = 0, last_block_pos = 0;
	size_t block_len = 10000;
	size_t tap_pos = 0;
	unsigned char xor_csum, xor_csum_ok;
	unsigned char *p_write;
	unsigned char block_type;				// typ bloku 255 data  0 - hlavicka
	unsigned char recv_status = 0;			// 0 - zacatek, 1 - hlavicka nactena,  2 - blok se nacita, 3- header less
	tapout_fd = fopen (output_dump_file, "a");
	if (tapout_fd == NULL) {
		err = errno;
		error (1, err, "can't open output file");
	}
	printf("Output file is: %s\n", output_dump_file);
	p_buff = in_buff;
	p_write = in_buff;
	while (is_continue) {
		result = poll (spolfd_serial, 1, 200);		// 200ms timeout
		if (result == 0) {
			// nic neprislo
			continue;
		}
		if (spolfd_serial[0].revents & POLLIN) {
			len = read (serial_fd, p_buff, 256);
			block_pos += len;
			p_buff += len;
			if (is_binary == 0) {
				// ulozeni dat ze seriaku jako tap file
				while (len) {
					fputc(*p_write, tapout_fd);
					p_write++;
					len--;
				}
			}
			if (block_pos != last_block_pos && recv_status >= 2) {
				last_block_pos = block_pos;
				DoProgress(block_pos, block_len+2, PROGRESS_PERCENT);
			}
			if (block_pos >= HEADER_RAW_LEN && recv_status == 0) {
				recv_status = 1;		// hlavicka nactena
				block_len = getword(in_buff);
				block_type = *(in_buff + 2);
				if (block_type == 0) {
					// Hlavicka komplet
					decode (in_buff + 2);
					block_len = 0;
					block_pos = 0;
					xor_csum = 0;
					recv_status = 0;
					p_buff = in_buff;
					p_write = in_buff;
				} else if (block_type == 255) {
					// data block
					printf ("Data block len: %6zu\n", block_len-2);
					recv_status = 3;
				}
				continue;
			}
			if (block_pos > HEADER_RAW_LEN + 3 && recv_status == 1) {
				// nactena delka dalsiho bloku
				recv_status = 2;
				block_len = getword(in_buff + HEADER_RAW_LEN);
				block_type = *(in_buff + HEADER_RAW_LEN + 2);
				printf ("Block len: %zu Block type: %d\n", block_len, block_type);
				continue;
			}
			if (block_len + 2 == block_pos && recv_status > 2) {
				// Blok komplet nacten cekej novy
				block_len = getword(in_buff);
				block_type = *(in_buff + 2);
				for (tap_pos = 0; tap_pos < block_len -1; tap_pos++) {
					xor_csum ^= *(in_buff + 2 + tap_pos);
				}
				xor_csum_ok = *(in_buff + 2 + block_len - 1);
				if (xor_csum == xor_csum_ok) {
					DoProgress(block_pos, block_len+2, PROGRESS_COMPLETTE);	// vypis jeste OK
					if (is_binary == 1) {
						// binarni vystup do souboru
						for (tap_pos = 0; tap_pos < block_len - 2; tap_pos++){
							fputc(*(in_buff + 3 + tap_pos), tapout_fd);	// uloz do souboru
						}
						DoProgress(tap_pos, block_len - 2, PROGRESS_COMPLETTE);
					}
// 					printf ("Checksum OK\n");
				} else {
					DoProgress(block_pos, block_len+2, PROGRESS_ERROR_CSUM);	// vypis error CSUM
				}
				block_len = 0;
				block_pos = 0;
				xor_csum = 0;
				recv_status = 0;
				p_buff = in_buff;
				p_write = in_buff;
				continue;
			}
		}
	}
	fclose (tapout_fd);
	printf ("\n\nulozeno...\n");
}

void SendByte(unsigned char *p_dato) {
	TestCts();
	write (serial_fd, p_dato, 1);
// 	tcdrain(serial_fd);		// better solution, but usleep at the next line is
	usleep (200);			// faster solution, TODO change sleep time according to serial communication speed  200us is for 57600Bd
}

void SendTap() {
	FILE *tap_fd;
	unsigned int err, no, len;
	struct stat st;
	unsigned char header[19];

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

	tap_fd = fopen(tap_file, "r");
	if (tap_fd == NULL)	{
		err = errno;
		error(1, err, "can't open input file");
	}
	while (pos < st.st_size) {
		if (is_continue == 0) break;
		pos += no = fread(header, 1, 2, tap_fd);
		if (no != 2)
			tooshort(tap_fd);
		for (out_indx = 0; out_indx < 2; out_indx++) {
			SendByte(&header[out_indx]);
		}
		no = getword(header);
		if (no == 19) /* HEADER */
		{
			pos += no = fread(header, 1, 19, tap_fd);
			if (no != 19)
				tooshort(tap_fd);
// 			printf ("Header len: %d\n", no);
			decode(header);
			for (out_indx = 0; out_indx < 19; out_indx++) {
				SendByte(&header[out_indx]);
			}
			usleep (400000);
		} else {
			if (h_len != no - 2) { /* zobrazuj iba bloky bez hl. */
				len = no;
				printf ("NO datablock without header: %d\n", no);
				printf("Type: datablock\nLength: %u\n", len - 2);
				pos += no = fread(header, 1, 1, tap_fd);
				SendByte(header);
				DoProgress(1, no, PROGRESS_PERCENT);
				if (no != 1) tooshort(tap_fd);
				printf("Flag: %u\n\n", (int)*header);
				len--;
			} else {
				len = no;
			}
			pos += len;
			for (out_indx = 0; out_indx < len; out_indx++) {
				fread(header, 1, 1, tap_fd);
				SendByte(header);
				DoProgress(out_indx+1, len, PROGRESS_PERCENT);
				if (is_continue == 0) break;
			}
			printf ("\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 < 3) {
		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){
		default:
			baud_rate = 57600;			// default speed
			newtio.c_cflag = B57600 | CS8 | CLOCAL | CREAD | CSTOPB;// | CRTSCTS;
			break;
		case 57600:
			newtio.c_cflag = B57600 | CS8 | CLOCAL | CREAD | CSTOPB | CRTSCTS;
			break;
		case 19200:
			newtio.c_cflag = B19200 | CS8 | CLOCAL | CREAD | CSTOPB | CRTSCTS;
			break;
		case 9600:
			newtio.c_cflag = B9600 | CS8 | CLOCAL | CREAD | CSTOPB | CRTSCTS;
			break;
		case 4800:
			newtio.c_cflag = B4800 | CS8 | CLOCAL | CREAD | CSTOPB | CRTSCTS;
			break;
	}
	printf ("Serial device: %s, communication speed is: %d Bd\n", MODEMDEVICE, baud_rate);
// 	newtio.c_iflag &= ~(IXON | IXOFF | IXANY);	// vypne XON/XOFF
	newtio.c_iflag = 0;IGNPAR | IXOFF;
	newtio.c_oflag = 0;
// 	newtio.c_oflag &= ~OPOST;
	newtio.c_lflag = 0; //NOFLSH;
	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

	Set_DTR(true);		// PC can read data from speccy everytime
	if (is_outfile) {
		RecvTap();	// cteni tap souboru ze seriaku a zapis na disk pocitace
	} else {
		SendTap();	// poslat na seriak tap soubor do spectra
	}
	close (serial_fd);
	return 0;
}