• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2021 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #ifdef HDC_SUPPORT_UART
17 
18 #include "host_uart.h"
19 
20 #include <mutex>
21 #include <thread>
22 
23 #include "server.h"
24 
25 using namespace std::chrono_literals;
26 namespace Hdc {
HdcHostUART(HdcServer & serverIn,ExternInterface & externInterface)27 HdcHostUART::HdcHostUART(HdcServer &serverIn, ExternInterface &externInterface)
28     : HdcUARTBase(serverIn, externInterface), server(serverIn)
29 {
30     uv_timer_init(&server.loopMain, &devUartWatcher);
31 }
32 
~HdcHostUART()33 HdcHostUART::~HdcHostUART()
34 {
35     Stop();
36 }
37 
Initial()38 int HdcHostUART::Initial()
39 {
40     uartOpened = false; // modRunning
41     return StartupUARTWork();
42 }
43 
NeedStop(const HSession hSession)44 bool HdcHostUART::NeedStop(const HSession hSession)
45 {
46     return (!uartOpened or (hSession->isDead and hSession->ref == 0));
47 }
48 
IsDeviceOpened(const HdcUART & uart)49 bool HdcHostUART::IsDeviceOpened(const HdcUART &uart)
50 {
51     // review why not use uartOpened?
52 #ifdef HOST_MINGW
53     return uart.devUartHandle != INVALID_HANDLE_VALUE;
54 #else
55     return uart.devUartHandle >= 0;
56 #endif
57 }
58 
UartWriteThread()59 void HdcHostUART::UartWriteThread()
60 {
61     // this thread don't care session.
62     while (true) {
63         WRITE_LOG(LOG_DEBUG, "%s wait sendLock.", __FUNCTION__);
64         transfer.Wait();
65         // it almost in wait , so we check stop after wait.
66         if (stopped) {
67             break;
68         }
69         SendPkgInUARTOutMap();
70     }
71     WRITE_LOG(LOG_INFO, "Leave %s", __FUNCTION__);
72     return;
73 }
74 
UartReadThread(HSession hSession)75 void HdcHostUART::UartReadThread(HSession hSession)
76 {
77     HUART hUART = hSession->hUART;
78     vector<uint8_t> dataReadBuf; // each thread/session have it own data buff
79     // If something unexpected happens , max buffer size we allow
80     WRITE_LOG(LOG_DEBUG, "%s devUartHandle:%d", __FUNCTION__, hUART->devUartHandle);
81     size_t expectedSize = 0;
82     while (dataReadBuf.size() < MAX_READ_BUFFER) {
83         if (NeedStop(hSession)) {
84             WRITE_LOG(LOG_FATAL, "%s stop ", __FUNCTION__);
85             break;
86         }
87         ssize_t bytesRead = ReadUartDev(dataReadBuf, expectedSize, *hUART);
88         if (bytesRead < 0) {
89             WRITE_LOG(LOG_INFO, "%s read got fail , free the session", __FUNCTION__);
90             OnTransferError(hSession);
91         } else if (bytesRead == 0) {
92             WRITE_LOG(LOG_DEBUG, "%s read %zd, clean the data try read again.", __FUNCTION__,
93                       bytesRead);
94             // drop current cache
95             expectedSize = 0;
96             dataReadBuf.clear();
97             continue;
98         }
99 
100         WRITE_LOG(LOG_DEBUG, "%s bytesRead:%d, dataReadBuf.size():%d.", __FUNCTION__, bytesRead,
101                   dataReadBuf.size());
102 
103         if (dataReadBuf.size() < sizeof(UartHead)) {
104             continue; // no enough ,read again
105         }
106         WRITE_LOG(LOG_DEBUG, "%s PackageProcess dataReadBuf.size():%d.", __FUNCTION__,
107                   dataReadBuf.size());
108         expectedSize = PackageProcess(dataReadBuf, hSession);
109     }
110     WRITE_LOG(LOG_INFO, "Leave %s", __FUNCTION__);
111     return;
112 }
113 
114 // review why not use QueryDosDevice ?
EnumSerialPort(bool & portChange)115 bool HdcHostUART::EnumSerialPort(bool &portChange)
116 {
117     std::vector<string> newPortInfo;
118     serialPortRemoved.clear();
119     bool bRet = true;
120 
121 #ifdef HOST_MINGW
122     constexpr int MAX_KEY_LENGTH = 255;
123     constexpr int MAX_VALUE_NAME = 16383;
124     HKEY hKey;
125     TCHAR achValue[MAX_VALUE_NAME];    // buffer for subkey name
126     DWORD cchValue = MAX_VALUE_NAME;   // size of name string
127     TCHAR achClass[MAX_PATH] = _T(""); // buffer for class name
128     DWORD cchClassName = MAX_PATH;     // size of class string
129     DWORD cSubKeys = 0;                // number of subkeys
130     DWORD cbMaxSubKey;                 // longest subkey size
131     DWORD cchMaxClass;                 // longest class string
132     DWORD cKeyNum;                     // number of values for key
133     DWORD cchMaxValue;                 // longest value name
134     DWORD cbMaxValueData;              // longest value data
135     DWORD cbSecurityDescriptor;        // size of security descriptor
136     FILETIME ftLastWriteTime;          // last write time
137     LSTATUS iRet = -1;
138     std::string port;
139     TCHAR strDSName[MAX_VALUE_NAME];
140     if (memset_s(strDSName, sizeof(TCHAR) * MAX_VALUE_NAME, 0, sizeof(TCHAR) * MAX_VALUE_NAME) !=
141         EOK) {
142         return false;
143     }
144     DWORD nValueType = 0;
145     DWORD nBuffLen = 10;
146     if (ERROR_SUCCESS == RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("HARDWARE\\DEVICEMAP\\SERIALCOMM"), 0,
147                                       KEY_READ, &hKey)) {
148         // Get the class name and the value count.
149         iRet = RegQueryInfoKey(hKey, achClass, &cchClassName, NULL, &cSubKeys, &cbMaxSubKey,
150                                &cchMaxClass, &cKeyNum, &cchMaxValue, &cbMaxValueData,
151                                &cbSecurityDescriptor, &ftLastWriteTime);
152         // Enumerate the key values.
153         if (ERROR_SUCCESS == iRet) {
154             for (DWORD i = 0; i < cKeyNum; i++) {
155                 cchValue = MAX_VALUE_NAME;
156                 achValue[0] = '\0';
157                 nBuffLen = MAX_KEY_LENGTH;
158                 if (ERROR_SUCCESS == RegEnumValue(hKey, i, achValue, &cchValue, NULL, NULL,
159                                                   (LPBYTE)strDSName, &nBuffLen)) {
160 #ifdef UNICODE
161                     strPortName = WstringToString(strDSName);
162 #else
163                     port = std::string(strDSName);
164 #endif
165                     newPortInfo.push_back(port);
166                     auto it = std::find(serialPortInfo.begin(), serialPortInfo.end(), port);
167                     if (it == serialPortInfo.end()) {
168                         portChange = true;
169                         WRITE_LOG(LOG_DEBUG, "%s:new port %s", __FUNCTION__, port.c_str());
170                     }
171                 } else {
172                     bRet = false;
173                     WRITE_LOG(LOG_DEBUG, "%s RegEnumValue fail. %d", __FUNCTION__, GetLastError());
174                 }
175             }
176         } else {
177             bRet = false;
178             WRITE_LOG(LOG_DEBUG, "%s RegQueryInfoKey failed %d", __FUNCTION__, GetLastError());
179         }
180     } else {
181         bRet = false;
182         WRITE_LOG(LOG_DEBUG, "%s RegOpenKeyEx fail %d", __FUNCTION__, GetLastError());
183     }
184     RegCloseKey(hKey);
185 #endif
186 #if defined(HOST_LINUX)||defined(HOST_MAC)
187     DIR *dir = opendir("/dev");
188     dirent *p = NULL;
189 
190     while (dir != nullptr && ((p = readdir(dir)) != nullptr)) {
191 #ifdef HOST_LINUX
192         if (p->d_name[0] != '.' && string(p->d_name).find("tty") != std::string::npos) {
193 #else
194         if (p->d_name[0] != '.' && string(p->d_name).find("serial") != std::string::npos) {
195 #endif
196             string port = "/dev/" + string(p->d_name);
197             if (port.find("/dev/ttyUSB") == 0 || port.find("/dev/ttySerial") == 0 || port.find("/dev/cu.") == 0) {
198                 newPortInfo.push_back(port);
199                 auto it = std::find(serialPortInfo.begin(), serialPortInfo.end(), port);
200                 if (it == serialPortInfo.end()) {
201                     portChange = true;
202                     WRITE_LOG(LOG_DEBUG, "new port:%s", port.c_str());
203                 }
204             }
205         }
206     }
207     if (dir != nullptr) {
208         closedir(dir);
209     }
210 #endif
211     for (auto &oldPort : serialPortInfo) {
212         auto it = std::find(newPortInfo.begin(), newPortInfo.end(), oldPort);
213         if (it == newPortInfo.end()) {
214             // not found in new port list
215             // we need remove the connect info
216             serialPortRemoved.emplace_back(oldPort);
217         }
218     }
219 
220     if (!portChange) {
221         // new scan empty , same as port changed
222         if (serialPortInfo.size() != newPortInfo.size()) {
223             portChange = true;
224         }
225     }
226     if (portChange) {
227         serialPortInfo.swap(newPortInfo);
228     }
229     return bRet;
230 }
231 
232 #ifdef HOST_MINGW
233 std::string WstringToString(const std::wstring &wstr)
234 {
235     if (wstr.empty()) {
236         return std::string();
237     }
238     int size = WideCharToMultiByte(CP_ACP, 0, &wstr[0], (int)wstr.size(), NULL, 0, NULL, NULL);
239     std::string ret = std::string(size, 0);
240     WideCharToMultiByte(CP_ACP, 0, &wstr[0], (int)wstr.size(), &ret[0], size, NULL,
241                         NULL); // CP_UTF8
242     return ret;
243 }
244 
245 // review rename for same func from linux
246 int HdcHostUART::WinSetSerial(HUART hUART, string serialPort, int byteSize, int eqBaudRate)
247 {
248     int winRet = RET_SUCCESS;
249     COMMTIMEOUTS timeouts;
250     GetCommTimeouts(hUART->devUartHandle, &timeouts);
251     int interTimeout = 5;
252     timeouts.ReadIntervalTimeout = interTimeout;
253     timeouts.ReadTotalTimeoutMultiplier = 0;
254     timeouts.ReadTotalTimeoutConstant = 0;
255     timeouts.WriteTotalTimeoutMultiplier = 0;
256     timeouts.WriteTotalTimeoutConstant = 0;
257     SetCommTimeouts(hUART->devUartHandle, &timeouts);
258     constexpr int max = DEFAULT_BAUD_RATE_VALUE / 8 * 2; // 2 second buffer size
259     do {
260         if (!SetupComm(hUART->devUartHandle, max, max)) {
261             WRITE_LOG(LOG_WARN, "SetupComm %s fail, err:%d.", serialPort.c_str(), GetLastError());
262             winRet = ERR_GENERIC;
263             break;
264         }
265         DCB dcb;
266         if (!GetCommState(hUART->devUartHandle, &dcb)) {
267             WRITE_LOG(LOG_WARN, "GetCommState %s fail, err:%d.", serialPort.c_str(),
268                       GetLastError());
269             winRet = ERR_GENERIC;
270         }
271         dcb.DCBlength = sizeof(DCB);
272         dcb.BaudRate = eqBaudRate;
273         dcb.Parity = 0;
274         dcb.ByteSize = byteSize;
275         dcb.StopBits = ONESTOPBIT;
276         if (!SetCommState(hUART->devUartHandle, &dcb)) {
277             WRITE_LOG(LOG_WARN, "SetCommState %s fail, err:%d.", serialPort.c_str(),
278                       GetLastError());
279             winRet = ERR_GENERIC;
280             break;
281         }
282         if (!PurgeComm(hUART->devUartHandle,
283                        PURGE_RXCLEAR | PURGE_TXCLEAR | PURGE_RXABORT | PURGE_TXABORT)) {
284             WRITE_LOG(LOG_WARN, "PurgeComm  %s fail, err:%d.", serialPort.c_str(), GetLastError());
285             winRet = ERR_GENERIC;
286             break;
287         }
288         DWORD dwError;
289         COMSTAT cs;
290         if (!ClearCommError(hUART->devUartHandle, &dwError, &cs)) {
291             WRITE_LOG(LOG_WARN, "ClearCommError %s fail, err:%d.", serialPort.c_str(),
292                       GetLastError());
293             winRet = ERR_GENERIC;
294             break;
295         }
296     } while (false);
297     if (winRet != RET_SUCCESS) {
298         CloseSerialPort(hUART);
299     }
300     return winRet;
301 }
302 #endif // HOST_MINGW
303 
304 bool HdcHostUART::WaitUartIdle(HdcUART &uart, bool retry)
305 {
306     std::vector<uint8_t> readBuf;
307     WRITE_LOG(LOG_DEBUG, "%s clear read", __FUNCTION__);
308     ssize_t ret = ReadUartDev(readBuf, 1, uart);
309     if (ret == 0) {
310         WRITE_LOG(LOG_DEBUG, "%s port read timeout", __FUNCTION__);
311         return true;
312     } else {
313         WRITE_LOG(LOG_WARN, "%s port read something %zd", __FUNCTION__, ret);
314         if (retry) {
315             // we will read again , but only retry one time
316             return WaitUartIdle(uart, false);
317         } else {
318             return false;
319         }
320     }
321     return false;
322 }
323 
324 int HdcHostUART::OpenSerialPort(const std::string &connectKey)
325 {
326     HdcUART uart;
327     std::string portName;
328     uint32_t baudRate;
329     static int ret = 0;
330 
331     if (memset_s(&uart, sizeof(HdcUART), 0, sizeof(HdcUART)) != EOK) {
332         return -1;
333     }
334 
335     if (!GetPortFromKey(connectKey, portName, baudRate)) {
336         WRITE_LOG(LOG_ALL, "%s unknown format %s", __FUNCTION__, connectKey.c_str());
337         return -1;
338     }
339     do {
340         ret = 0;
341         WRITE_LOG(LOG_ALL, "%s try to open %s with rate %u", __FUNCTION__, portName.c_str(),
342                   baudRate);
343 
344 #ifdef HOST_MINGW
345         constexpr int numTmp = 2;
346         // review change to wstring ?
347         TCHAR apiBuf[PORT_NAME_LEN * numTmp];
348 #ifdef UNICODE
349         _stprintf_s(apiBuf, MAX_PATH, _T("\\\\.\\%S"), port.c_str());
350 #else
351         _stprintf_s(apiBuf, MAX_PATH, _T("\\\\.\\%s"), portName.c_str());
352 #endif
353         DWORD dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED;
354         uart.devUartHandle = CreateFile(apiBuf, GENERIC_READ | GENERIC_WRITE, 0, NULL,
355                                         OPEN_EXISTING, dwFlagsAndAttributes, NULL);
356         if (uart.devUartHandle == INVALID_HANDLE_VALUE) {
357             ret = ERR_GENERIC;
358             WRITE_LOG(LOG_DEBUG, "%s CreateFile %s err:%d.", __FUNCTION__, portName.c_str(),
359                       GetLastError());
360             break; // review for onethan one uart , here we need change to continue?
361         } else {
362             uart.serialPort = portName;
363         }
364         ret = WinSetSerial(&uart, uart.serialPort, UART_BIT2, baudRate);
365         if (ret != RET_SUCCESS) {
366             WRITE_LOG(LOG_WARN, "%s WinSetSerial:%s fail.", __FUNCTION__, uart.serialPort.c_str());
367             break;
368         }
369 #endif
370 
371 #if defined(HOST_LINUX)||defined(HOST_MAC)
372         string uartName = Base::CanonicalizeSpecPath(portName);
373         uart.devUartHandle = open(uartName.c_str(), O_RDWR | O_NOCTTY | O_NONBLOCK);
374         if (uart.devUartHandle < 0) {
375             constexpr int bufSize = 1024;
376             char buf[bufSize] = { 0 };
377             strerror_r(errno, buf, bufSize);
378             WRITE_LOG(LOG_WARN, "Linux open serial port failed, serialPort:%s, Message : %s",
379                       uart.serialPort.c_str(), buf);
380             ret = ERR_GENERIC;
381             break;
382         }
383         {
384             uart.serialPort = portName;
385         }
386         SetSerial(uart.devUartHandle, baudRate, UART_BIT2, 'N', 1);
387 #endif
388         // if the dev is idle
389         if (!WaitUartIdle(uart)) {
390             ret = ERR_GENERIC;
391             WRITE_LOG(LOG_INFO, "This is not a Idle UART port: %s", uart.serialPort.c_str());
392             break;
393         }
394         if (!ConnectMyNeed(&uart, connectKey)) {
395             WRITE_LOG(LOG_WARN, "ConnectMyNeed failed");
396             ret = ERR_GENERIC;
397             break;
398         } else {
399             uartOpened = true;
400             WRITE_LOG(LOG_INFO,
401                       "Serial Open Successfully! uart.serialPort:%s "
402                       "devUartHandle:%d",
403                       uart.serialPort.c_str(), uart.devUartHandle);
404         }
405         break;
406     } while (false);
407     if (ret != RET_SUCCESS) {
408         CloseSerialPort(&uart);
409     }
410     return ret;
411 }
412 
413 void HdcHostUART::UpdateUARTDaemonInfo(const std::string &connectKey, HSession hSession,
414                                        ConnStatus connStatus)
415 {
416     // add to list
417     HdcDaemonInformation diNew;
418     HDaemonInfo diNewPtr = &diNew;
419     diNew.connectKey = connectKey;
420     diNew.connType = CONN_SERIAL;
421     diNew.connStatus = connStatus;
422     diNew.hSession = hSession;
423     WRITE_LOG(LOG_DEBUG, "%s uart connectKey :%s session %s change to %d", __FUNCTION__,
424               connectKey.c_str(),
425               hSession == nullptr ? "<null>" : hSession->ToDebugString().c_str(), connStatus);
426     if (connStatus == STATUS_UNKNOW) {
427         server.AdminDaemonMap(OP_REMOVE, connectKey, diNewPtr);
428         if (hSession != nullptr and hSession->hUART != nullptr) {
429             connectedPorts.erase(hSession->hUART->serialPort);
430         }
431     } else {
432         if (connStatus == STATUS_CONNECTED) {
433             if (hSession != nullptr and hSession->hUART != nullptr) {
434                 connectedPorts.emplace(hSession->hUART->serialPort);
435             }
436         }
437         HDaemonInfo diOldPtr = nullptr;
438         server.AdminDaemonMap(OP_QUERY, connectKey, diOldPtr);
439         if (diOldPtr == nullptr) {
440             WRITE_LOG(LOG_DEBUG, "%s add new di", __FUNCTION__);
441             server.AdminDaemonMap(OP_ADD, connectKey, diNewPtr);
442         } else {
443             server.AdminDaemonMap(OP_UPDATE, connectKey, diNewPtr);
444         }
445     }
446 }
447 
448 bool HdcHostUART::StartUartReadThread(HSession hSession)
449 {
450     try {
451         HUART hUART = hSession->hUART;
452         hUART->readThread = std::thread(&HdcHostUART::UartReadThread, this, hSession);
453     } catch (...) {
454         server.FreeSession(hSession->sessionId);
455         UpdateUARTDaemonInfo(hSession->connectKey, hSession, STATUS_UNKNOW);
456         WRITE_LOG(LOG_WARN, "%s failed err", __FUNCTION__);
457         return false;
458     }
459 
460     WRITE_LOG(LOG_INFO, "%s success.", __FUNCTION__);
461     return true;
462 }
463 
464 bool HdcHostUART::StartUartSendThread()
465 {
466     WRITE_LOG(LOG_DEBUG, "%s.", __FUNCTION__);
467     try {
468         sendThread = std::thread(&HdcHostUART::UartWriteThread, this);
469     } catch (...) {
470         WRITE_LOG(LOG_WARN, "%s sendThread create failed", __FUNCTION__);
471         return false;
472     }
473 
474     WRITE_LOG(LOG_INFO, "%s success.", __FUNCTION__);
475     return true;
476 }
477 
478 // Determines that daemonInfo must have the device
479 HSession HdcHostUART::ConnectDaemonByUart(const HSession hSession, const HDaemonInfo)
480 {
481     if (!uartOpened) {
482         WRITE_LOG(LOG_DEBUG, "%s non uart opened.", __FUNCTION__);
483         return nullptr;
484     }
485     HUART hUART = hSession->hUART;
486     UpdateUARTDaemonInfo(hSession->connectKey, hSession, STATUS_READY);
487     WRITE_LOG(LOG_DEBUG, "%s :%s", __FUNCTION__, hUART->serialPort.c_str());
488     if (!StartUartReadThread(hSession)) {
489         WRITE_LOG(LOG_DEBUG, "%s StartUartReadThread fail.", __FUNCTION__);
490         return nullptr;
491     }
492 
493     externInterface.StartWorkThread(&server.loopMain, server.SessionWorkThread,
494                                     Base::FinishWorkThread, hSession);
495     // wait for thread up
496     while (hSession->childLoop.active_handles == 0) {
497         uv_sleep(1);
498     }
499     auto ctrl = server.BuildCtrlString(SP_START_SESSION, 0, nullptr, 0);
500     externInterface.SendToPollFd(hSession->ctrlFd[STREAM_MAIN], ctrl.data(), ctrl.size());
501     return hSession;
502 }
503 
504 RetErrCode HdcHostUART::StartupUARTWork()
505 {
506     WRITE_LOG(LOG_DEBUG, "%s", __FUNCTION__);
507     devUartWatcher.data = this;
508     constexpr int interval = 3000;
509     constexpr int delay = 1000;
510     if (externInterface.UvTimerStart(&devUartWatcher, UvWatchUartDevPlugin, delay, interval) != 0) {
511         WRITE_LOG(LOG_FATAL, "devUartWatcher start fail");
512         return ERR_GENERIC;
513     }
514     if (!StartUartSendThread()) {
515         WRITE_LOG(LOG_DEBUG, "%s StartUartSendThread fail.", __FUNCTION__);
516         return ERR_GENERIC;
517     }
518     return RET_SUCCESS;
519 }
520 
521 HSession HdcHostUART::ConnectDaemon(const std::string &connectKey)
522 {
523     WRITE_LOG(LOG_DEBUG, "%s", __FUNCTION__);
524     OpenSerialPort(connectKey);
525     return nullptr;
526 }
527 
528 /*
529 This function does the following:
530 1. Existing serial device, check whether a session is established, if not, go to establish
531 2. The connection is established but the serial device does not exist, delete the session
532 */
533 void HdcHostUART::WatchUartDevPlugin()
534 {
535     std::lock_guard<std::mutex> lock(semUartDevCheck);
536     bool portChange = false;
537 
538     if (!EnumSerialPort(portChange)) {
539         WRITE_LOG(LOG_WARN, "%s enumDetailsSerialPorts fail.", __FUNCTION__);
540     } else if (portChange) {
541         for (const auto &port : serialPortInfo) {
542             WRITE_LOG(LOG_INFO, "%s found uart port :%s", __FUNCTION__, port.c_str());
543             // check port have session
544             HDaemonInfo hdi = nullptr;
545             server.AdminDaemonMap(OP_QUERY, port, hdi);
546             if (hdi == nullptr and connectedPorts.find(port) == connectedPorts.end()) {
547                 UpdateUARTDaemonInfo(port, nullptr, STATUS_READY);
548             }
549         }
550         for (const auto &port : serialPortRemoved) {
551             WRITE_LOG(LOG_INFO, "%s remove uart port :%s", __FUNCTION__, port.c_str());
552             // check port have session
553             HDaemonInfo hdi = nullptr;
554             server.AdminDaemonMap(OP_QUERY, port, hdi);
555             if (hdi != nullptr and hdi->hSession == nullptr) {
556                 // we only remove the empty port
557                 UpdateUARTDaemonInfo(port, nullptr, STATUS_UNKNOW);
558             }
559         }
560     }
561 }
562 
563 bool HdcHostUART::ConnectMyNeed(HUART hUART, std::string connectKey)
564 {
565     // we never use port to connect, we use connect key
566     if (connectKey.empty()) {
567         connectKey = hUART->serialPort;
568     }
569     if (connectKey != hUART->serialPort) {
570         UpdateUARTDaemonInfo(hUART->serialPort, nullptr, STATUS_UNKNOW);
571     }
572     UpdateUARTDaemonInfo(connectKey, nullptr, STATUS_READY);
573 
574     HSession hSession = server.MallocSession(true, CONN_SERIAL, this);
575     if (!hSession) {
576         WRITE_LOG(LOG_FATAL, "malloc serial session failed for %s", connectKey.c_str());
577         return false;
578     }
579     hSession->connectKey = connectKey;
580 #if defined(HOST_LINUX)||defined(HOST_MAC)
581     hSession->hUART->devUartHandle = hUART->devUartHandle;
582 #elif defined(HOST_MINGW)
583     hSession->hUART->devUartHandle = hUART->devUartHandle;
584 #endif
585 
586     hSession->isCheck = isCheck;
587     hSession->hUART->serialPort = hUART->serialPort;
588     WRITE_LOG(LOG_DEBUG, "%s connectkey:%s,port:%s", __FUNCTION__, hSession->connectKey.c_str(),
589               hUART->serialPort.c_str());
590     uv_timer_t *waitTimeDoCmd = new(std::nothrow) uv_timer_t;
591     if (waitTimeDoCmd == nullptr) {
592         WRITE_LOG(LOG_FATAL, "ConnectMyNeed new waitTimeDoCmd failed");
593         server.FreeSession(hSession->sessionId);
594         return false;
595     }
596     uv_timer_init(&server.loopMain, waitTimeDoCmd);
597     waitTimeDoCmd->data = hSession;
598     if (externInterface.UvTimerStart(waitTimeDoCmd, server.UartPreConnect, UV_TIMEOUT, UV_REPEAT) !=
599         RET_SUCCESS) {
600         WRITE_LOG(LOG_DEBUG, "%s for %s:%s fail.", __FUNCTION__, hSession->connectKey.c_str(),
601                   hUART->serialPort.c_str());
602         server.FreeSession(hSession->sessionId);
603         return false;
604     }
605     WRITE_LOG(LOG_DEBUG, "%s %s register a session", __FUNCTION__, hUART->serialPort.c_str());
606 
607     return true;
608 }
609 
610 void HdcHostUART::KickoutZombie(HSession hSession)
611 {
612     if (hSession == nullptr or hSession->hUART == nullptr or hSession->isDead) {
613         return;
614     }
615 #ifdef _WIN32
616     if (hSession->hUART->devUartHandle == INVALID_HANDLE_VALUE) {
617         return;
618     }
619 #else
620     if (hSession->hUART->devUartHandle < 0) {
621         return;
622     }
623 #endif
624     WRITE_LOG(LOG_DEBUG, "%s FreeSession %s", __FUNCTION__, hSession->ToDebugString().c_str());
625     server.FreeSession(hSession->sessionId);
626 }
627 
628 HSession HdcHostUART::GetSession(const uint32_t sessionId, bool)
629 {
630     return server.AdminSession(OP_QUERY, sessionId, nullptr);
631 }
632 void HdcHostUART::CloseSerialPort(const HUART hUART)
633 {
634     WRITE_LOG(LOG_DEBUG, "%s try to close dev handle %d", __FUNCTION__, hUART->devUartHandle);
635 
636 #ifdef _WIN32
637     if (hUART->devUartHandle != INVALID_HANDLE_VALUE) {
638         CloseHandle(hUART->devUartHandle);
639         hUART->devUartHandle = INVALID_HANDLE_VALUE;
640     }
641 #else
642     if (hUART->devUartHandle != -1) {
643         Base::CloseFd(hUART->devUartHandle);
644         hUART->devUartHandle = -1;
645     }
646 #endif
647 }
648 
649 void HdcHostUART::OnTransferError(const HSession session)
650 {
651     if (session != nullptr) {
652         WRITE_LOG(LOG_FATAL, "%s:%s", __FUNCTION__, session->ToDebugString().c_str());
653         if (session->hUART != nullptr) {
654             if (IsDeviceOpened(*session->hUART)) {
655                 // same device dont echo twice to client
656                 string echoStr = "ERR: uart link layer transmission error.\n";
657                 server.EchoToClientsForSession(session->sessionId, echoStr);
658             }
659             // 1. dev opened by other application
660             // 2. dev is plug out
661             // 3. dev line is broken ?
662             // we set the status to empty
663             // watcher will reopen it if it can find this again
664             CloseSerialPort(session->hUART);
665             UpdateUARTDaemonInfo(session->connectKey, session, STATUS_OFFLINE);
666         }
667 
668         server.FreeSession(session->sessionId);
669         ClearUARTOutMap(session->sessionId);
670     }
671 }
672 
673 // review what about merge Restartession with OnTransferError ?
674 void HdcHostUART::Restartession(const HSession session)
675 {
676     HdcUARTBase::Restartession(session);
677     // allow timer watcher make a new session.
678     if (session != nullptr and session->hUART != nullptr) {
679         WRITE_LOG(LOG_FATAL, "%s reset serialPort:%s", __FUNCTION__,
680                   session->hUART->serialPort.c_str());
681         CloseSerialPort(session->hUART); // huart will free , so we must clost it here
682         server.EchoToClientsForSession(session->sessionId,
683                                        "uart link released by daemon. need connect again.");
684     }
685 }
686 
687 void HdcHostUART::StopSession(HSession hSession)
688 {
689     if (hSession == nullptr) {
690         WRITE_LOG(LOG_FATAL, "%s hSession is null", __FUNCTION__);
691         return;
692     }
693     WRITE_LOG(LOG_DEBUG, "%s hSession %s will be stop and free", __FUNCTION__,
694               hSession->ToDebugString().c_str());
695     HUART hUART = hSession->hUART;
696     if (hUART == nullptr) {
697         WRITE_LOG(LOG_FATAL, "%s hUART is null", __FUNCTION__);
698     } else {
699 #ifdef _WIN32
700         CancelIoEx(hUART->devUartHandle, NULL);
701 #endif
702         // we make select always have a timeout in linux
703         // also we make a mark here
704         // ReadUartDev will return for this flag
705         hUART->ioCancel = true;
706 
707         if (hUART->readThread.joinable()) {
708             WRITE_LOG(LOG_DEBUG, "wait readThread Stop");
709             hUART->readThread.join();
710         } else {
711             WRITE_LOG(LOG_FATAL, "readThread is not joinable");
712         }
713     }
714 
715     // call the base side
716     HdcUARTBase::StopSession(hSession);
717 }
718 
719 std::vector<std::string> HdcHostUART::StringSplit(std::string source, std::string split)
720 {
721     std::vector<std::string> result;
722 
723     // find
724     if (!split.empty()) {
725         size_t pos = 0;
726         while ((pos = source.find(split)) != std::string::npos) {
727             // split
728             std::string token = source.substr(0, pos);
729             if (!token.empty()) {
730                 result.push_back(token);
731             }
732             source.erase(0, pos + split.length());
733         }
734     }
735     // add last token
736     if (!source.empty()) {
737         result.push_back(source);
738     }
739     return result;
740 }
741 
742 bool HdcHostUART::GetPortFromKey(const std::string &connectKey, std::string &portName,
743                                  uint32_t &baudRate)
744 {
745     // we support UART_NAME:UART_RATE format
746     // like COM5:115200
747     constexpr size_t TWO_ARGS = 2;
748     std::vector<std::string> result = StringSplit(connectKey, ",");
749     if (result.size() == TWO_ARGS) {
750         portName = result[0];
751         try {
752             baudRate = static_cast<uint32_t>(std::stoul(result[1]));
753         } catch (...) {
754             return false;
755         }
756         return true;
757     } else if (result.size() == 1) {
758         portName = result[0];
759         baudRate = DEFAULT_BAUD_RATE_VALUE;
760         return true;
761     } else {
762         return false;
763     }
764 }
765 
766 void HdcHostUART::SendUartSoftReset(HSession hSession, uint32_t sessionId)
767 {
768     UartHead resetPackage(sessionId, PKG_OPTION_RESET);
769     resetPackage.dataSize = sizeof(UartHead);
770     RequestSendPackage(reinterpret_cast<uint8_t *>(&resetPackage), sizeof(UartHead), false);
771 }
772 
773 void HdcHostUART::Stop()
774 {
775     WRITE_LOG(LOG_DEBUG, "%s Stop!", __FUNCTION__);
776     if (!stopped) {
777         externInterface.TryCloseHandle((uv_handle_t *)&devUartWatcher);
778         uartOpened = false;
779         stopped = true;
780         // just click it for exit
781         NotifyTransfer();
782         if (sendThread.joinable()) {
783             WRITE_LOG(LOG_DEBUG, "%s wait sendThread Stop!", __FUNCTION__);
784             sendThread.join();
785         } else {
786             WRITE_LOG(LOG_FATAL, "%s sendThread is not joinable", __FUNCTION__);
787         }
788     }
789 }
790 } // namespace Hdc
791 #endif // HDC_SUPPORT_UART
792