ymodem.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. /*
  2. * Copyright 2015 Omid Sakhi (www.omidsakhi.com)
  3. * All rights reserved.
  4. * Redistribution and use in source and binary forms, with or without
  5. * modification, are permitted provided that the following conditions are met:
  6. *
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the University of California, Berkeley nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. #include "ymodem.h"
  28. #include <QDebug>
  29. #include <QSerialPort>
  30. #include <QFile>
  31. #include <QFileInfo>
  32. #include <QBuffer>
  33. #include <QEventLoop>
  34. #include <QTimer>
  35. #include <QDateTime>
  36. #include <m_loger.h>
  37. #include <QCoreApplication>
  38. YMODEM::YMODEM( QSerialPort *port, QObject *parent): QObject(parent),
  39. m_serialPort(port)
  40. {
  41. percent = 0.0;
  42. m_cancel = false;
  43. }
  44. static const unsigned short crc16tab[256]= {
  45. /* Copyright 2001-2010 Georges Menie (www.menie.org) */
  46. 0x0000,0x1021,0x2042,0x3063,0x4084,0x50a5,0x60c6,0x70e7,
  47. 0x8108,0x9129,0xa14a,0xb16b,0xc18c,0xd1ad,0xe1ce,0xf1ef,
  48. 0x1231,0x0210,0x3273,0x2252,0x52b5,0x4294,0x72f7,0x62d6,
  49. 0x9339,0x8318,0xb37b,0xa35a,0xd3bd,0xc39c,0xf3ff,0xe3de,
  50. 0x2462,0x3443,0x0420,0x1401,0x64e6,0x74c7,0x44a4,0x5485,
  51. 0xa56a,0xb54b,0x8528,0x9509,0xe5ee,0xf5cf,0xc5ac,0xd58d,
  52. 0x3653,0x2672,0x1611,0x0630,0x76d7,0x66f6,0x5695,0x46b4,
  53. 0xb75b,0xa77a,0x9719,0x8738,0xf7df,0xe7fe,0xd79d,0xc7bc,
  54. 0x48c4,0x58e5,0x6886,0x78a7,0x0840,0x1861,0x2802,0x3823,
  55. 0xc9cc,0xd9ed,0xe98e,0xf9af,0x8948,0x9969,0xa90a,0xb92b,
  56. 0x5af5,0x4ad4,0x7ab7,0x6a96,0x1a71,0x0a50,0x3a33,0x2a12,
  57. 0xdbfd,0xcbdc,0xfbbf,0xeb9e,0x9b79,0x8b58,0xbb3b,0xab1a,
  58. 0x6ca6,0x7c87,0x4ce4,0x5cc5,0x2c22,0x3c03,0x0c60,0x1c41,
  59. 0xedae,0xfd8f,0xcdec,0xddcd,0xad2a,0xbd0b,0x8d68,0x9d49,
  60. 0x7e97,0x6eb6,0x5ed5,0x4ef4,0x3e13,0x2e32,0x1e51,0x0e70,
  61. 0xff9f,0xefbe,0xdfdd,0xcffc,0xbf1b,0xaf3a,0x9f59,0x8f78,
  62. 0x9188,0x81a9,0xb1ca,0xa1eb,0xd10c,0xc12d,0xf14e,0xe16f,
  63. 0x1080,0x00a1,0x30c2,0x20e3,0x5004,0x4025,0x7046,0x6067,
  64. 0x83b9,0x9398,0xa3fb,0xb3da,0xc33d,0xd31c,0xe37f,0xf35e,
  65. 0x02b1,0x1290,0x22f3,0x32d2,0x4235,0x5214,0x6277,0x7256,
  66. 0xb5ea,0xa5cb,0x95a8,0x8589,0xf56e,0xe54f,0xd52c,0xc50d,
  67. 0x34e2,0x24c3,0x14a0,0x0481,0x7466,0x6447,0x5424,0x4405,
  68. 0xa7db,0xb7fa,0x8799,0x97b8,0xe75f,0xf77e,0xc71d,0xd73c,
  69. 0x26d3,0x36f2,0x0691,0x16b0,0x6657,0x7676,0x4615,0x5634,
  70. 0xd94c,0xc96d,0xf90e,0xe92f,0x99c8,0x89e9,0xb98a,0xa9ab,
  71. 0x5844,0x4865,0x7806,0x6827,0x18c0,0x08e1,0x3882,0x28a3,
  72. 0xcb7d,0xdb5c,0xeb3f,0xfb1e,0x8bf9,0x9bd8,0xabbb,0xbb9a,
  73. 0x4a75,0x5a54,0x6a37,0x7a16,0x0af1,0x1ad0,0x2ab3,0x3a92,
  74. 0xfd2e,0xed0f,0xdd6c,0xcd4d,0xbdaa,0xad8b,0x9de8,0x8dc9,
  75. 0x7c26,0x6c07,0x5c64,0x4c45,0x3ca2,0x2c83,0x1ce0,0x0cc1,
  76. 0xef1f,0xff3e,0xcf5d,0xdf7c,0xaf9b,0xbfba,0x8fd9,0x9ff8,
  77. 0x6e17,0x7e36,0x4e55,0x5e74,0x2e93,0x3eb2,0x0ed1,0x1ef0
  78. };
  79. unsigned short YMODEM::crc16_ccitt( const unsigned char *buf, unsigned int len )
  80. //{
  81. // /* Copyright 2001-2010 Georges Menie (www.menie.org) */
  82. // int counter;
  83. // unsigned short crc = 0;
  84. // for( counter = 0; counter < len; counter++)
  85. // crc = (crc<<8) ^ crc16tab[((crc>>8) ^ *(char *)buf++)&0x00FF];
  86. // return crc;
  87. //}
  88. {
  89. /* Copyright 2001-2010 Georges Menie (www.menie.org) */
  90. int counter;
  91. unsigned short crc = 0;
  92. while(len--){
  93. crc = crc ^ *buf++ << 8;
  94. for (counter = 0; counter < 8; counter++) {
  95. if (crc & 0x8000) {
  96. crc = crc << 1 ^ 0x1021;
  97. } else {
  98. crc = crc << 1;
  99. }
  100. }
  101. }
  102. return crc;
  103. }
  104. int YMODEM::yTransmitRead( unsigned short timeout )
  105. {
  106. char byte;
  107. int byte_int = static_cast<unsigned char>(byte);
  108. m_serialPort->waitForReadyRead(timeout);
  109. m_serialPort->getChar(&byte);
  110. byte_int = byte;
  111. DEBUG("串口接收到: {} int: {}", QChar(byte).toLatin1(), byte_int);
  112. return byte_int;
  113. }
  114. void YMODEM::yTransmitWrite(const QByteArray &ba )
  115. {
  116. m_serialPort->write(ba);
  117. m_serialPort->waitForBytesWritten(1000);
  118. }
  119. void YMODEM::yTransmitWrite( int c )
  120. {
  121. QByteArray ba;
  122. QChar charValue(c);
  123. ba.append(c);
  124. m_serialPort->write(ba);
  125. m_serialPort->waitForBytesWritten(1000);
  126. }
  127. void YMODEM::yTransmitFlush()
  128. {
  129. m_serialPort->readAll();
  130. }
  131. bool YMODEM::isConnected()
  132. {
  133. return m_serialPort->isOpen();
  134. }
  135. void YMODEM::cancel()
  136. {
  137. m_cancel = true;
  138. }
  139. // 配置串口为协议专用模式
  140. void YMODEM::configureForProtocolMode(bool enable)
  141. {
  142. if (enable) {
  143. // 禁用所有缓冲和非必要功能
  144. m_serialPort->setReadBufferSize(128);
  145. m_serialPort->clearError();
  146. // 在 Windows 上禁用底层缓冲
  147. #ifdef Q_OS_WIN
  148. DCB dcb;
  149. if (GetCommState(m_serialPort->handle(), &dcb)) {
  150. dcb.fOutX = FALSE; // 禁用 XON/XOFF
  151. dcb.fInX = FALSE;
  152. dcb.fErrorChar = FALSE;
  153. dcb.fNull = TRUE; // 丢弃 NULL 字符
  154. dcb.fAbortOnError = TRUE;
  155. SetCommState(m_serialPort->handle(), &dcb);
  156. }
  157. #endif
  158. } else {
  159. // 恢复原始设置
  160. m_serialPort->setReadBufferSize(0);
  161. }
  162. }
  163. int YMODEM::yTransmit()
  164. {
  165. LOG("Starting YMODEM transmission...");
  166. // 进入协议专用模式
  167. m_serialPort->setDataTerminalReady(false);
  168. m_serialPort->clear(QSerialPort::AllDirections);
  169. // 配置特殊串口模式(忽略非协议字符)
  170. configureForProtocolMode(true);
  171. if (!isConnected()) {
  172. ERROR("串口未打开!");
  173. return -1;
  174. }
  175. QFile file(m_fp);
  176. if (!file.exists())
  177. {
  178. ERROR("MODEM_FILE_NOT_FOUND_ERROR!");
  179. return MODEM_FILE_NOT_FOUND_ERROR;
  180. }
  181. QFileInfo fileInfo(m_fp);
  182. if (!file.open(QIODevice::ReadOnly))
  183. {
  184. ERROR("MODEM_FILE_NOT_OPEN_ERROR!");
  185. return MODEM_FILE_NOT_OPEN_ERROR;
  186. }
  187. // 预计算文件大小和块数
  188. qint64 fileSize = file.size();
  189. int totalBlocks = (fileSize + 1023) / 1024;
  190. int currentBlock = 0;
  191. quint32 payloadSize = 1024; // 1K
  192. int response = 0;
  193. //尝试30次收不到C则返回
  194. for(int retry = 0; retry < 30; ++retry)
  195. {
  196. int c;
  197. if ((c = yTransmitRead((DLY_1S)<<1)) >= 0) {
  198. if(c==67){
  199. response++;
  200. if(response==3){ //连续收到3个C再往下执行
  201. break;
  202. }
  203. }
  204. }
  205. }
  206. if(67!=yTransmitRead((DLY_1S)<<1)){
  207. emit modem_result(MODEM_TIMEOUT);
  208. return MODEM_TIMEOUT;
  209. }
  210. downloadStart(QString("Sending %1 (%2 bytes)").arg(fileInfo.fileName()).arg(file.size()));
  211. for(int retry = 0; retry < 10 && !m_cancel; ++retry)
  212. {
  213. int c;
  214. if ((c = yTransmitRead((DLY_1S)<<1)) >= 0) {
  215. switch (c) {
  216. case '\0':
  217. case 'c':
  218. DEBUG("Received 'c'");
  219. case 'C':
  220. DEBUG("Received 'C'");
  221. case NAK:
  222. DEBUG("NAK");
  223. response = yTransmitPacket(fileInfo,file,payloadSize);
  224. if (response == MODEM_RESTART)
  225. {
  226. file.seek(0);
  227. retry = 0;
  228. continue;
  229. }
  230. return response;
  231. break;
  232. case CAN:
  233. if ((c = yTransmitRead(DLY_1S)) == CAN) {
  234. yTransmitWrite(ACK);
  235. yTransmitFlush();
  236. WARN("XMODEM::yTransmit - canceled by remote");
  237. return MODEM_REMOTE_CANCEL;
  238. }
  239. break;
  240. default:
  241. m_serialPort->clear(QSerialPort::Input);
  242. WARN("XYMODEM::yTransmit - Unknown: {}", m_serialPort->readAll().toStdString());
  243. break;
  244. }
  245. }
  246. }
  247. yTransmitWrite(CAN);
  248. yTransmitWrite(CAN);
  249. yTransmitWrite(CAN);
  250. yTransmitFlush();
  251. file.close();
  252. if (m_cancel)
  253. {
  254. WARN("XMODEM::yTransmit - canceled by user");
  255. emit modem_result(MODEM_LOCAL_CANCEL);
  256. return MODEM_LOCAL_CANCEL;
  257. }
  258. else
  259. {
  260. WARN("XMODEM::yTransmit - no sync");
  261. emit modem_result(MODEM_NO_SYNC);
  262. return MODEM_NO_SYNC;
  263. }
  264. }
  265. int YMODEM::yTransmitPacket(const QFileInfo &fileInfo, QIODevice &dev, const quint32 &payloadSize, quint8 sequenceNum, bool firstPacket)
  266. {
  267. QByteArray payload;
  268. int res;
  269. if (dev.atEnd())
  270. {
  271. int ACK_T = 0;
  272. payload.clear();
  273. //第一个EOT,发10次
  274. for (int retry = 0; retry < 10; ++retry) {
  275. yTransmitWrite(EOT);
  276. if ((res = yTransmitRead((DLY_1S)<<1)) == ACK){
  277. DEBUG("EOT");
  278. }
  279. if ((res = yTransmitRead((DLY_1S)<<1)) == 67){
  280. return yTransmitClose();
  281. }
  282. }
  283. emit modem_result((res == ACK)?MODEM_SUCCESS:MODEM_EOT_ERROR);
  284. return (res == ACK)?MODEM_SUCCESS:MODEM_EOT_ERROR;
  285. }
  286. if (firstPacket)
  287. {
  288. QString filesize = QString::number(fileInfo.size());
  289. payload.append(fileInfo.fileName().toStdString());
  290. payload.append(QString(CTRLZ).toStdString());
  291. payload.append(filesize.toStdString());
  292. DEBUG("文件大小:{}", fileInfo.size());
  293. payload += QString(CTRLZ).repeated(128 - payload.size()).toStdString();
  294. //payload += (quint32) fileInfo.fileTime(QFileDevice::FileBirthTime).toSecsSinceEpoch();//.created().toTime_t();
  295. }
  296. else
  297. {
  298. payload = dev.read(payloadSize);
  299. payload += QString(CTRLZ).repeated(payloadSize - payload.size()).toStdString();
  300. }
  301. QByteArray packet;
  302. if (firstPacket){
  303. packet.append(QString(SOH).toStdString());
  304. }else{
  305. packet.append(QString(STX).toStdString());
  306. }
  307. packet.append(sequenceNum);
  308. packet.append(~sequenceNum);
  309. packet.append(payload);
  310. unsigned short ccrc = crc16_ccitt((unsigned char*)payload.constData(),payload.size());
  311. qWarning () <<"ccrc:" <<ccrc <<"size:" << payload.size();
  312. packet.append((ccrc>>8) & 0xFF);
  313. packet.append(ccrc & 0xFF);
  314. int pos = dev.pos();
  315. //qWarning () <<"数据包:" <<packet.toHex();
  316. int dtotal = (int)floor((float)fileInfo.size()/payloadSize + 0.5f);
  317. DEBUG("XMODEM:xBeginTransmit - Packet # : {}/{}/{}", pos, pos/payloadSize, dtotal);
  318. //emit message(QString("Sending Packet %1/%2").arg(pos/payloadSize).arg((int)floor((float)fileInfo.size()/payloadSize)));
  319. emit progress(pos/payloadSize,dtotal);
  320. QCoreApplication::processEvents();
  321. Q_ASSERT(packet.size() == 1029);
  322. for (int retry = 0; retry < 10 && !m_cancel; ++retry) {
  323. yTransmitWrite(packet);
  324. int time_read = 0;
  325. while (firstPacket){
  326. time_read++;
  327. m_serialPort->waitForReadyRead(100);
  328. dataBuf.append(m_serialPort->readAll());
  329. LOG("Serial Read ALL:{}",dataBuf.constData());
  330. if(dataBuf.contains("Size")||time_read>5){
  331. break;
  332. }
  333. }
  334. if ((res = yTransmitRead(DLY_1S)) >= 0 ) {
  335. switch (res) {
  336. case ACK:
  337. WARN("ACK");
  338. return yTransmitPacket(fileInfo,dev,payloadSize,sequenceNum+1,false);
  339. case CAN:
  340. WARN("CAN");
  341. if ((res = yTransmitRead(DLY_1S)) == CAN) {
  342. yTransmitWrite(ACK);
  343. yTransmitFlush();
  344. DEBUG("XMODEM::xBeginTransmit - canceled by remote");
  345. emit modem_result(MODEM_REMOTE_CANCEL);
  346. return MODEM_REMOTE_CANCEL;
  347. }
  348. break;
  349. case NAK:
  350. WARN("NAK");
  351. break;
  352. case 'c':
  353. case 'C':
  354. WARN("C");
  355. return yTransmitPacket(fileInfo,dev,payloadSize,sequenceNum+1,false);
  356. retry--;
  357. continue;
  358. case '>':
  359. return MODEM_RESTART;
  360. case '\0':
  361. WARN('\0');
  362. break;
  363. default:
  364. ERROR("XYMODEM::yTransmitPacket - Unknown {}",res);
  365. break;
  366. }
  367. }
  368. }
  369. yTransmitWrite(CAN);
  370. yTransmitWrite(CAN);
  371. yTransmitWrite(CAN);
  372. yTransmitFlush();
  373. if (m_cancel){
  374. emit modem_result(MODEM_LOCAL_CANCEL);
  375. return MODEM_LOCAL_CANCEL;
  376. }else{
  377. emit modem_result(MODEM_PACKET_FAILED);
  378. return MODEM_PACKET_FAILED;
  379. }
  380. }
  381. int YMODEM::yTransmitClose()
  382. {
  383. QByteArray payload;
  384. payload.append(QString(CTRLZ).repeated(128).toStdString());
  385. QByteArray packet;
  386. packet.append(QString(SOH).toStdString());
  387. int sequenceNum = 0;
  388. packet.append(sequenceNum);
  389. packet.append(~sequenceNum);
  390. packet.append(payload);
  391. unsigned short ccrc = crc16_ccitt((unsigned char*)payload.constData(),128);
  392. packet.append((ccrc>>8) & 0xFF);
  393. packet.append(ccrc & 0xFF);
  394. DEBUG("last packet: {}", packet.toHex().toStdString());
  395. int res;
  396. for (int retry = 0; retry < 10; ++retry)
  397. {
  398. yTransmitWrite(packet);
  399. if ((res = yTransmitRead((DLY_1S)<<1)) == ACK) break;
  400. }
  401. emit modem_result((res == ACK)?MODEM_SUCCESS:MODEM_EOT_ERROR);
  402. return (res == ACK)?MODEM_SUCCESS:MODEM_EOT_ERROR;
  403. }