-
Notifications
You must be signed in to change notification settings - Fork 1
/
xmodem.c
1959 lines (1629 loc) · 51.9 KB
/
xmodem.c
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
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//////////////////////////////////////////////////////////////////////////////
// //
// _ //
// __ __ _ __ ___ ___ __| | ___ _ __ ___ ___ //
// \ \/ /| '_ ` _ \ / _ \ / _` | / _ \| '_ ` _ \ / __| //
// > < | | | | | || (_) || (_| || __/| | | | | | _| (__ //
// /_/\_\|_| |_| |_| \___/ \__,_| \___||_| |_| |_|(_)\___| //
// //
// //
//////////////////////////////////////////////////////////////////////////////
// //
// Copyright (c) 2012 by S.F.T. Inc. - All rights reserved //
// Use, copying, and distribution of this software are licensed according //
// to the GPLv2, LGPLv2, or BSD license, as appropriate (see COPYING) //
// //
//////////////////////////////////////////////////////////////////////////////
// XMODEM adapted for arduino and POSIX systems. Windows code incomplete
#include "xmodem.h"
// special I/O when linked into 'SFTARDCAL' application
#ifdef SFTARDCAL
int my_read(SERIAL_TYPE iFile, void *pBuf, int cbBuf);
int my_write(SERIAL_TYPE iFile, const void *pBuf, int cbBuf);
void my_flush(SERIAL_TYPE iFile);
#endif // SFTARDCAL
// internal structure definitions
// Windows requires a different way of specifying structure packing
#ifdef WIN32
#define PACKED
#pragma pack(push,1)
#else // POSIX, ARDUINO
#define PACKED __attribute__((__packed__))
#endif // WIN32 vs THE REST OF THE WORLD
#define _SOH_ 1 /* start of packet - note XMODEM-1K uses '2' */
#define _EOT_ 4
#define _ENQ_ 5
#define _ACK_ 6
#define _NAK_ 21 /* NAK character */
#define _CAN_ 24 /* CAN character CTRL+X */
/** \file xmodem.c
* \brief main source file for S.F.T. XMODEM library
*
* S.F.T. XMODEM library
**/
/** \ingroup xmodem_internal
* \brief Structure defining an XMODEM CHECKSUM packet
*
\code
typedef struct _XMODEM_BUF_
{
char cSOH; // ** SOH byte goes here **
unsigned char aSEQ, aNotSEQ; // ** 1st byte = seq#, 2nd is ~seq# **
char aDataBuf[128]; // ** the actual data itself! **
unsigned char bCheckSum; // ** checksum gets 1 byte **
} PACKED XMODEM_BUF;
\endcode
*
**/
typedef struct _XMODEM_BUF_
{
char cSOH; ///< SOH byte goes here
unsigned char aSEQ, aNotSEQ; ///< 1st byte = seq#, 2nd is ~seq#
char aDataBuf[128]; ///< the actual data itself!
unsigned char bCheckSum; ///< checksum gets 1 byte
} PACKED XMODEM_BUF;
/** \ingroup xmodem_internal
* \brief Structure defining an XMODEM CRC packet
*
\code
typedef struct _XMODEMC_BUF_
{
char cSOH; // ** SOH byte goes here **
unsigned char aSEQ, aNotSEQ; // ** 1st byte = seq#, 2nd is ~seq# **
char aDataBuf[128]; // ** the actual data itself! **
unsigned short wCRC; // ** CRC gets 2 bytes, high endian **
} PACKED XMODEMC_BUF;
\endcode
*
**/
typedef struct _XMODEMC_BUF_
{
char cSOH; ///< SOH byte goes here
unsigned char aSEQ, aNotSEQ; ///< 1st byte = seq#, 2nd is ~seq#
char aDataBuf[128]; ///< the actual data itself!
unsigned short wCRC; ///< CRC gets 2 bytes, high endian
} PACKED XMODEMC_BUF;
#ifdef WIN32
// restore default packing
#pragma pack(pop)
#endif // WIN32
/** \ingroup xmodem_internal
* \brief Structure that identifies the XMODEM communication state
*
\code
typedef struct _XMODEM_
{
SERIAL_TYPE ser; // identifies the serial connection, data type is OS-dependent
FILE_TYPE file; // identifies the file handle, data type is OS-dependent
union
{
XMODEM_BUF xbuf; // XMODEM CHECKSUM buffer
XMODEMC_BUF xcbuf; // XMODEM CRC buffer
} buf; // union of both buffers, total length 133 bytes
unsigned char bCRC; // non-zero for CRC, zero for checksum
} XMODEM;
\endcode
*
**/
typedef struct _XMODEM_
{
SERIAL_TYPE ser; ///< identifies the serial connection, data type is OS-dependent
FILE_TYPE file; ///< identifies the file handle, data type is OS-dependent
union
{
XMODEM_BUF xbuf; ///< XMODEM CHECKSUM buffer
XMODEMC_BUF xcbuf; ///< XMODEM CRC buffer
} buf; ///< union of both buffers, total length 133 bytes
unsigned char bCRC; ///< non-zero for CRC, zero for checksum
} XMODEM;
#ifdef DEBUG_CODE
static char szERR[32]; // place for error messages, up to 16 characters
const char *XMGetError(void)
{
return szERR;
}
#endif // DEBUG_CODE
#if defined(STAND_ALONE) && defined(DEBUG_CODE)
void debug_dump_buffer(int iDir, const void *pBuf, int cbBuf)
{
int i1, i2;
const unsigned char *p1, *p2;
if(cbBuf <= 0)
{
return;
}
p1 = p2 = (const unsigned char *)pBuf;
for(i1=0, i2=0; i1 <= cbBuf; i1++, p1++)
{
if(!i1 || i2 >= 16 || i1 == cbBuf)
{
if(i1)
{
while(i2 < 16)
{
fputs(" ", stderr); // fill up spaces where data would be
i2++;
}
fputs(" : ", stderr);
while(p2 < p1)
{
if(*p2 >= 32 && *p2 <= 127)
{
fputc(*p2, stderr);
}
else
{
fputc('.', stderr);
}
p2++;
}
fputc('\n', stderr);
}
if(!i1 && iDir > 0)
{
fputs("--> ", stderr);
}
else if(!i1 && iDir < 0)
{
fputs("<-- ", stderr);
}
else
{
fputs(" ", stderr);
}
i2 = 0;
p2 = p1; // make sure
}
if(i1 < cbBuf)
{
if(!i2)
{
fprintf(stderr, "%02x: %02x", i1, *p1);
}
else
{
fprintf(stderr, ", %02x", *p1);
}
i2++;
}
}
fputc('\n', stderr);
fflush(stderr);
}
#endif // STAND_ALONE, DEBUG_CODE
//char iBinaryTransfer = 0, iDisableRXOVER = 0;
/** \ingroup xmodem_internal
* \brief Calculate checksum for XMODEM packet
*
* \param lpBuf A pointer to the XMODEM data buffer
* \param cbBuf The length of the XMODEM data buffer (typically 128)
* \return An unsigned char value to be assigned to the 'checksum' element in the XMODEM packet
*
**/
unsigned char CalcCheckSum(const char *lpBuf, short cbBuf)
{
short iC, i1;
iC = 0;
for(i1 = 0; i1 < cbBuf; i1++)
{
iC += lpBuf[i1];
}
return (unsigned char)(iC & 0xff);
}
/** \ingroup xmodem_internal
* \brief Calculate checksum for XMODEM packet
*
* \param sVal An unsigned short integer to be made 'high endian' by flipping bytes (as needed)
* \return A (possibly) byte-flipped high-endian unsigned short integer
*
* This function assumes low-endian for Arduino, and performs a universal operation
* for 'indeterminate' architectures.
**/
static unsigned short my_htons(unsigned short sVal)
{
union
{
unsigned char aVal[2];
unsigned short sVal;
} a, b;
// tweeked for size and speed. enjoy.
b.sVal = sVal;
#ifdef ARDUINO
a.aVal[0] = b.aVal[1]; // no math involved, pre-optimized code
a.aVal[1] = b.aVal[0];
#else
a.aVal[0] = (unsigned char)(sVal >> 8); // less optimized but universal code
a.aVal[1] = (unsigned char)(sVal & 0xff);
#endif // ARDUINO
return a.sVal;
}
/** \ingroup xmodem_internal
* \brief Calculate 16-bit CRC for XMODEM packet
*
* \param lpBuf A pointer to the XMODEM data buffer
* \param cbBuf The length of the XMODEM data buffer (typically 128)
* \return A high-endian 16-bit (unsigned short) value to be assigned to the 'CRC' element in the XMODEM packet
*
* This method uses the 'long way' which is SMALLER CODE for microcontrollers, but eats up a bit more CPU.
* Otherwise, you'd have to pre-build the 256 byte table and use "the table lookup" method.
**/
unsigned short CalcCRC(const char *lpBuf, short cbBuf)
{
unsigned short wCRC;
short i1, i2, iAX;
char cAL;
// ** this function returns 2-byte string containing
// ** the CRC calculation result, as high endian
wCRC = 0;
for(i1=0; i1 < cbBuf; i1++)
{
cAL = lpBuf[i1];
iAX = (unsigned short)cAL << 8;
wCRC = iAX ^ wCRC;
for(i2=0; i2 < 8; i2++)
{
iAX = wCRC;
if(iAX & 0x8000)
{
wCRC <<= 1;
wCRC ^= 0x1021; // this is the 'polynomial' - it is in 'normal' order.
// for explanation, and different ways this might be expressed mathematically, see
// https://en.wikipedia.org/wiki/Cyclic_redundancy_check#Polynomial_representations_of_cyclic_redundancy_checks
//
// it is known as CRC-16-CCITT or CRC-CCITT and sometimes expressed as x^16 + x^12 + x^5 + 1
//
// reversed forward
// 1111111000000000 0000000001111111
// 6543210987654321 1234567890123456
//
// 1000010000001000 8408H 0001000000100001 1021H (normal)
// 1000100000010000 8810H 0000100000010001 0811H (reciprocal)
// ^^^ this appears to translate from the polynomial equation as bit coefficients assuming the '+1' is bit 0
// that is, bits 16, 12, 5, and 0 are all '1'
//
// this equation may be better explained on the abovementioned web page.
}
else
{
wCRC <<= 1;
}
}
}
return my_htons(wCRC);
}
//void WaitASecond()
//{
//#ifdef ARDUINO
// delay(1000);
//#elif defined(WIN32)
// Sleep(1000);
//#else //
// usleep(1000000);
//#endif // ARDUINO
//}
#ifndef ARDUINO
#ifdef WIN32
#define MyMillis GetTickCount
#else // WIN32
/** \ingroup xmodem_internal
* \brief Return internal 'milliseconds' value for timing purposes
*
* \return A calculated 'milliseconds' value as an unsigned long integer
*
* This function returns the 'unsigned long' integer value for elapsed time based
* on the result of the 'gettimeofday()' API function. On 32-bit and Windows systems
* the value might wrap around, so you should be careful with your time comparisons (see the
* code _I_ wrote for the right way to do it). On 64-bit POSIX systems, this value will
* always increase.\n
* NOTE: Win32 defines this as a macro (see above) for the 'GetTickCount()' api, which
* returns a 32-bit value. POSIX x86 returns 32-bit, x64 returns 64-bit. YMMV.
**/
unsigned long MyMillis(void)
{
struct timeval tv;
gettimeofday(&tv, NULL); // 2nd parameter is obsolete anyway
// NOTE: this won't roll over the way 'GetTickCount' does in WIN32 so I'll truncate it
// down to a 32-bit value to make it happen. Everything that uses 'MyGetTickCount'
// must handle this rollover properly using 'int' and not 'long' (or cast afterwards)
return((unsigned int)((unsigned long)tv.tv_sec * 1000L + (unsigned long)tv.tv_usec / 1000L));
}
#endif // WIN32
#endif // ARDUINO
//Function GenerateSEQ (wSeq%) As String
//
// GenerateSEQ = Chr$(wSeq%) + Chr$(Not (wSeq%) And &HFF)
//
//End Function
/** \ingroup xmodem_internal
* \brief Generate a sequence number pair, place into XMODEM_BUF
*
* \param pBuf A pointer to an XMODEM_BUF structure
* \param bSeq An unsigned char, typically cast from an unsigned long 'block number'
*
* This function generates the sequence pair for the XMODEM packet. The 'block number'
* is initially assigned a value of '1', and increases by 1 for each successful packet.
* That value is 'truncated' to a single byte and assigned as a sequence number for the
* packet itself.
**/
void GenerateSEQ(XMODEM_BUF *pBuf, unsigned char bSeq)
{
pBuf->aSEQ = bSeq;
pBuf->aNotSEQ = ~bSeq;
}
/** \ingroup xmodem_internal
* \brief Generate a sequence number pair, place into XMODEMC_BUF (the CRC version)
*
* \param pBuf A pointer to an XMODEM_BUF structure
* \param bSeq An unsigned char, typically cast from an unsigned long 'block number'
*
* This function generates the sequence pair for the XMODEM packet. The 'block number'
* is initially assigned a value of '1', and increases by 1 for each successful packet.
* That value is 'truncated' to a single byte and assigned as a sequence number for the
* packet itself.
**/
void GenerateSEQC(XMODEMC_BUF *pBuf, unsigned char bSeq)
{
pBuf->aSEQ = bSeq;
pBuf->aNotSEQ = (255 - bSeq);//~bSeq; these should be the same but for now I do this...
}
/** \ingroup xmodem_internal
* \brief Get an XMODEM block from the serial device
*
* \param ser A 'SERIAL_TYPE' identifier for the serial connection
* \param pBuf A pointer to the buffer that receives the data
* \param cbSize The number of bytes/chars to read
* \return The number of bytes/chars read, 0 if timed out (no data), < 0 on error
*
* Call this function to read data from the serial port, specifying the number of
* bytes to read. This function times out after no data transferred (silence) for
* a period of 'SILENCE_TIMEOUT' milliseconds. This allows spurious data transfers
* to continue as long as there is LESS THAN 'SILENCE_TIMEOUT' between bytes, and
* also allows VERY SLOW BAUD RATES (as needed). However, if the transfer takes longer
* than '10 times SILENCE_TIMEOUT', the function will return the total number of bytes
* that were received within that time.\n
* The default value of 5 seconds, extended to 50 seconds, allows a worst-case baud
* rate of about 20. This should not pose a problem. If it does, edit the code.
**/
short GetXmodemBlock(SERIAL_TYPE ser, char *pBuf, short cbSize)
{
unsigned long ulCur;
short cb1;
// ** This function obtains a buffer of 'cbSize' bytes, **
// ** waiting a maximum of 5 seconds (of silence) to get it. **
// ** It returns the data within 'pBuf', returning the actual **
// ** number of bytes transferred. **
#ifdef ARDUINO
char *p1;
short i1;
p1 = pBuf;
cb1 = 0;
ulCur = millis();
ser->setTimeout(SILENCE_TIMEOUT); // 5 seconds [of silence]
for(i1=0; i1 < cbSize; i1++)
{
if(ser->readBytes(p1, 1) != 1) // 5 seconds of "silence" is what fails this
{
break;
}
cb1++;
p1++;
if((millis() - ulCur) > (unsigned long)(10L * SILENCE_TIMEOUT)) // 10 times SILENCE TIMEOUT for TOTAL TIMEOUT
{
break; // took too long, I'm going now
}
}
#elif defined(SFTARDCAL)
#ifndef WIN32
struct pollfd aFD[2];
#endif // WIN32
int i1;
unsigned long ulStart;
ulStart = ulCur = MyMillis();
cb1 = 0;
do
{
#ifndef WIN32
aFD[0].fd = ser;
aFD[0].events = POLLIN | POLLERR;
aFD[0].revents = 0;
i1 = poll(aFD, 1, 100);
if(!i1)
{
continue;
}
if(i1 < 0)
{
fprintf(stderr, "poll error %d\n", errno);
return -1;
}
#endif // WIN32
#ifdef WIN32
if(my_pollin(ser) > 0)
#else // WIN32
if(aFD[0].revents & POLLIN)
#endif // WIN32
{
i1 = my_read(ser, pBuf + cb1, cbSize - cb1);
if(i1 > 0)
{
cb1 += i1;
ulCur = MyMillis();
}
}
else
{
MySleep(1);
}
} while(!QuitFlag() &&
cb1 < cbSize &&
(MyMillis() - ulCur) < SILENCE_TIMEOUT &&
(MyMillis() - ulStart) < (unsigned long)10L * SILENCE_TIMEOUT);
#elif defined(WIN32)
#error no win32 code yet
#else // POSIX
unsigned long ulStart;
char *p1;
int i1, i2;
if(fcntl(ser, F_SETFL, O_NONBLOCK) == -1)
{
static int iFailFlag = 0;
if(!iFailFlag)
{
fprintf(stderr, "Warning: 'fcntl(O_NONBLOCK)' failed, errno = %d\n", errno);
fflush(stderr);
iFailFlag = 1;
}
}
p1 = pBuf;
cb1 = 0;
ulStart = ulCur = MyMillis();
for(i1=0; i1 < cbSize; i1++)
{
while((i2 = read(ser, p1, 1)) != 1)
{
if(i2 < 0 && errno != EAGAIN)
{
// read error - exit now
// return cb1; // how many bytes I actually read
goto the_end;
}
else
{
usleep(1000); // 1 msec
if((MyMillis() - ulCur) > SILENCE_TIMEOUT || // too much silence?
(MyMillis() - ulStart) > 10 * SILENCE_TIMEOUT) // too long for transfer
{
// return cb1; // finished (return how many bytes I actually read)
goto the_end;
}
}
}
// here it succeeds
cb1++;
p1++;
if((MyMillis() - ulStart) > 10 * SILENCE_TIMEOUT) // 10 times SILENCE TIMEOUT for TOTAL TIMEOUT
{
break; // took too long, I'm going now
}
}
the_end:
#if defined(STAND_ALONE) && defined(DEBUG_CODE)
fprintf(stderr, "GetXmodemBlock - request %d, read %d errno=%d\n", cbSize, cb1, errno);
fflush(stderr);
//#ifdef DEBUG_CODE
debug_dump_buffer(-1, pBuf, cb1);
//#endif // DEBUG_CODE
#endif // STAND_ALONE
#endif // ARDUINO
return cb1; // what I actually read
}
/** \ingroup xmodem_internal
* \brief Write a single character to the serial device
*
* \param ser A 'SERIAL_TYPE' identifier for the serial connection
* \param bVal The byte to send
* \return The number of bytes/chars written, or < 0 on error
*
* Call this function to write one byte of data to the serial port. Typically
* this is used to send things like an ACK or NAK byte.
**/
int WriteXmodemChar(SERIAL_TYPE ser, unsigned char bVal)
{
int iRval;
#ifdef ARDUINO
iRval = ser->write(bVal);
// ser->flush(); // force sending it
#elif defined(SFTARDCAL)
char buf[2]; // use size of '2' to avoid warnings about array size of '1'
buf[0] = (char)bVal;
return (short)my_write(ser, buf, 1);
#elif defined(WIN32)
#error no win32 code yet
#else // POSIX
char buf[2]; // use size of '2' to avoid warnings about array size of '1'
if(fcntl(ser, F_SETFL, 0) == -1) // set blocking mode
{
static int iFailFlag = 0;
if(!iFailFlag)
{
fprintf(stderr, "Warning: 'fcntl(O_NONBLOCK)' failed, errno = %d\n", errno);
iFailFlag = 1;
}
}
buf[0] = bVal; // in case args are passed by register
iRval = write(ser, buf, 1);
#if defined(STAND_ALONE) && defined(DEBUG_CODE)
fprintf(stderr, "WriteXmodemChar - returns %d\n", iRval);
if(iRval > 0)
{
debug_dump_buffer(1, buf, 1);
}
#endif // STAND_ALONE, DEBUG_CODE
#endif // ARDUINO
return iRval;
}
/** \ingroup xmodem_internal
* \brief Send an XMODEM block via the serial device
*
* \param ser A 'SERIAL_TYPE' identifier for the serial connection
* \param pBuf A pointer to the buffer that receives the data
* \param cbSize The number of bytes/chars to write
* \return The number of bytes/chars written, < 0 on error
*
* Call this function to write data via the serial port, specifying the number of
* bytes to write.
**/
int WriteXmodemBlock(SERIAL_TYPE ser, const void *pBuf, int cbSize)
{
int iRval;
#ifdef ARDUINO
iRval = ser->write((const uint8_t *)pBuf, cbSize);
// ser->flush(); // force sending it before returning
#elif defined(SFTARDCAL)
return (short)my_write(ser, pBuf, cbSize);
#elif defined(WIN32)
#error no win32 code yet
#else // POSIX
if(fcntl(ser, F_SETFL, 0) == -1) // set blocking mode
{
static int iFailFlag = 0;
if(!iFailFlag)
{
fprintf(stderr, "Warning: 'fcntl(O_NONBLOCK)' failed, errno = %d\n", errno);
fflush(stderr);
iFailFlag = 1;
}
}
iRval = write(ser, pBuf, cbSize);
#if defined(STAND_ALONE) && defined(DEBUG_CODE)
fprintf(stderr, "\r\nWriteXmodemBlock - returns %d\n", iRval);
fflush(stderr);
if(iRval > 0)
{
debug_dump_buffer(1, pBuf, cbSize);
}
#endif // STAND_ALONE, DEBUG_CODE
#endif
return iRval;
}
/** \ingroup xmodem_internal
* \brief Read all input from the serial port until there is 1 second of 'silence'
*
* \param ser A 'SERIAL_TYPE' identifier for the serial connection
*
* Call this function to read ALL data from the serial port, until there is a period
* with no data (i.e. 'silence') for 1 second. At that point the function will return.\n
* Some operations require that any bad data be flushed out of the input to prevent
* synchronization problems. By using '1 second of silence' it forces re-synchronization
* to occur in one shot, with the possible exception of VERY noisy lines. The down side
* is that it may slow down transfers with a high data rate.
**/
void XModemFlushInput(SERIAL_TYPE ser)
{
#ifdef ARDUINO
unsigned long ulStart;
ulStart = millis();
do
{
if(ser->available())
{
ser->read(); // don't care about the data
ulStart = millis(); // reset time
}
else
{
delay(1);
}
} while((millis() - ulStart) < 1000);
#elif defined(SFTARDCAL)
my_flush(ser);
#elif defined(WIN32)
#error no win32 code yet
#else // POSIX
unsigned long ulStart;
int i1;
#ifdef DEBUG_CODE
unsigned char buf[16];
int cbBuf;
#else // DEBUG_CODE
unsigned char buf[2];
#endif // DEBUG_CODE
if(fcntl(ser, F_SETFL, O_NONBLOCK) == -1)
{
static int iFailFlag = 0;
if(!iFailFlag)
{
fprintf(stderr, "Warning: 'fcntl(O_NONBLOCK)' failed, errno = %d\n", errno);
iFailFlag = 1;
}
}
ulStart = MyMillis();
#ifdef DEBUG_CODE
cbBuf = 0;
#endif // DEBUG_CODE
while((MyMillis() - ulStart) < 1000)
{
#ifdef DEBUG_CODE
i1 = read(ser, &(buf[cbBuf]), 1);
#else // DEBUG_CODE
i1 = read(ser, buf, 1);
#endif // DEBUG_CODE
if(i1 == 1)
{
#if defined(STAND_ALONE) && defined(DEBUG_CODE)
cbBuf++;
if(cbBuf >= sizeof(buf))
{
debug_dump_buffer(-1, buf, cbBuf);
cbBuf = 0;
}
#endif // STAND_ALONE, DEBUG_CODE
ulStart = MyMillis();
}
else
{
usleep(1000);
}
}
#if defined(STAND_ALONE) && defined(DEBUG_CODE)
if(cbBuf > 0)
{
debug_dump_buffer(-1, buf, cbBuf);
}
#endif // STAND_ALONE, DEBUG_CODE
#endif // ARDUINO
}
/** \ingroup xmodem_internal
* \brief Terminate the XMODEM connection
*
* \param pX A pointer to the 'XMODEM' object identifying the transfer
*
* Call this function prior to ending the XMODEM transfer. Currently the only
* thing it does is flush the input.
**/
void XmodemTerminate(XMODEM *pX)
{
XModemFlushInput(pX->ser);
// TODO: close files?
}
/** \ingroup xmodem_internal
* \brief Validate the sequence number of a received XMODEM block
*
* \param pX A pointer to an 'XMODEM_BUF'
* \param bSeq The expected sequence number (block & 255)
* \return A zero value on success, non-zero otherwise
*
* Call this function to validate a packet's sequence number against the block number
**/
short ValidateSEQ(XMODEM_BUF *pX, unsigned char bSeq)
{
return pX->aSEQ != 255 - pX->aNotSEQ || // ~(pX->aNotSEQ) ||
pX->aSEQ != bSeq; // returns TRUE if not valid
}
/** \ingroup xmodem_internal
* \brief Validate the sequence number of a received XMODEM block (CRC version)
*
* \param pX A pointer to an 'XMODEMC_BUF'
* \param bSeq The expected sequence number (block & 255)
* \return A zero value on success, non-zero otherwise
*
* Call this function to validate a packet's sequence number against the block number
**/
short ValidateSEQC(XMODEMC_BUF *pX, unsigned char bSeq)
{
return pX->aSEQ != 255 - pX->aNotSEQ || // ~(pX->aNotSEQ) ||
pX->aSEQ != bSeq; // returns TRUE if not valid
}
/** \ingroup xmodem_internal
* \brief Generic function to receive a file via XMODEM (CRC or Checksum)
*
* \param pX A pointer to an 'XMODEM_BUF' with valid bCRC, ser, and file members
* \return A zero value on success, negative on error, positive on cancel
*
* The calling function will need to poll for an SOH from the server using 'C' and 'NAK'
* characters (as appropriate) until an SOH is received. That value must be assigned
* to the 'buf' union (as appropriate), and the bCRC member assigned to non-zero if
* the server responded to 'C', or zero if it responded to 'NAK'. With the bCRC,
* ser, and file members correctly assigned, call THIS function to receive content
* via XMODEM and write it to 'file'.\n
* This function will return zero on success, a negative value on error, and a positive
* value if the transfer was canceled by the server.
**/
int ReceiveXmodem(XMODEM *pX)
{
#ifdef WIN32
DWORD cbWrote;
#endif // WIN32
int ecount, ec2;
long etotal, filesize, block;
unsigned char cY; // the char to send in response to a packet
// NOTE: to allow debugging the CAUSE of an xmodem block's failure, i1, i2, and i3
// are assigned to function return values and reported in error messages.
#ifdef DEBUG_CODE
short i1, i2, i3;
#define DEBUG_I1 i1 =
#define DEBUG_I2 i2 =
#define DEBUG_I3 i3 =
#else // DEBUG_CODE
#define DEBUG_I1 /*normally does nothing*/
#define DEBUG_I2 /*normally does nothing*/
#define DEBUG_I3 /*normally does nothing*/
#endif // DEBUG_CODE
ecount = 0;
etotal = 0;
filesize = 0;
block = 1;
// ** already got the first 'SOH' character on entry to this function **
// Form2.Show 0 '** modeless show of form2 (CANSEND) **
// Form2!Label1.FloodType = 0
// Form2.Caption = "* XMODEM(Checksum) BINARY RECEIVE *"
// Form2!Label1.Caption = "Errors: 0 Bytes: 0"
pX->buf.xbuf.cSOH = (char)1; // assumed already got this, put into buffer
do
{
if(!pX->bCRC &&
((DEBUG_I1 GetXmodemBlock(pX->ser, ((char *)&(pX->buf.xbuf)) + 1, sizeof(pX->buf.xbuf) - 1))
!= sizeof(pX->buf.xbuf) - 1 ||
(DEBUG_I2 ValidateSEQ(&(pX->buf.xbuf), block & 255)) ||
(DEBUG_I3 CalcCheckSum(pX->buf.xbuf.aDataBuf, sizeof(pX->buf.xbuf.aDataBuf)) != pX->buf.xbuf.bCheckSum)))
{
// did not receive properly
// TODO: deal with repeated packet, sequence number for previous packet
#ifdef DEBUG_CODE
sprintf(szERR,"A%ld,%d,%d,%d,%d,%d",block,i1,i2,i3,pX->buf.xbuf.aSEQ, pX->buf.xbuf.aNotSEQ);
//#ifdef STAND_ALONE
// fprintf(stderr, "TEMPORARY (csum): seq=%x, ~seq=%x i1=%d, i2=%d, i3=%d\n", pX->buf.xbuf.aSEQ, pX->buf.xbuf.aNotSEQ, i1, i2, i3);
//#endif // STAND_ALONE
#endif // DEBUG_CODE
XModemFlushInput(pX->ser); // necessary to avoid problems
cY = _NAK_; // send NAK (to get the checksum version)
ecount ++; // for this packet
etotal ++;
}
else if(pX->bCRC &&
((DEBUG_I1 GetXmodemBlock(pX->ser, ((char *)&(pX->buf.xcbuf)) + 1, sizeof(pX->buf.xcbuf) - 1))
!= sizeof(pX->buf.xcbuf) - 1 ||
(DEBUG_I2 ValidateSEQC(&(pX->buf.xcbuf), block & 255)) ||
(DEBUG_I3 CalcCRC(pX->buf.xcbuf.aDataBuf, sizeof(pX->buf.xbuf.aDataBuf)) != pX->buf.xcbuf.wCRC)))
{
// did not receive properly
// TODO: deal with repeated packet, sequence number for previous packet
#ifdef DEBUG_CODE
sprintf(szERR,"B%ld,%d,%d,%d,%d,%d",block,i1,i2,i3,pX->buf.xcbuf.aSEQ, pX->buf.xcbuf.aNotSEQ);
//#ifdef STAND_ALONE
// fprintf(stderr, "TEMPORARY (CRC): seq=%x, ~seq=%x i1=%d, i2=%d, i3=%d\n", pX->buf.xcbuf.aSEQ, pX->buf.xcbuf.aNotSEQ, i1, i2, i3);
//#endif // STAND_ALONE
#endif // DEBUG_CODE
XModemFlushInput(pX->ser); // necessary to avoid problems
if(block > 1)
{
cY = _NAK_; // TODO do I need this?
}
else
{
cY = 'C'; // send 'CRC' NAK (the character 'C') (to get the CRC version)
}
ecount ++; // for this packet
etotal ++;
}
else
{
#ifdef ARDUINO
if(pX->file.write((const uint8_t *)&(pX->buf.xbuf.aDataBuf), sizeof(pX->buf.xbuf.aDataBuf)) != sizeof(pX->buf.xbuf.aDataBuf))
{
return -2; // write error on output file
}
#elif defined(WIN32)
cbWrote = 0;
if(!WriteFile(pX->file, &(pX->buf.xbuf.aDataBuf), sizeof(pX->buf.xbuf.aDataBuf),
&cbWrote, NULL)
|| cbWrote != sizeof(pX->buf.xbuf.aDataBuf))
{