• 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     while ((p = readdir(dir)) != NULL) {
190 #ifdef HOST_LINUX
191         if (p->d_name[0] != '.' && string(p->d_name).find("tty") != std::string::npos) {
192 #else
193         if (p->d_name[0] != '.' && string(p->d_name).find("serial") != std::string::npos) {
194 #endif
195             string port = "/dev/" + string(p->d_name);
196             if (port.find("/dev/ttyUSB") == 0 || port.find("/dev/ttySerial") == 0 || port.find("/dev/cu.") == 0) {
197                 newPortInfo.push_back(port);
198                 auto it = std::find(serialPortInfo.begin(), serialPortInfo.end(), port);
199                 if (it == serialPortInfo.end()) {
200                     portChange = true;
201                     WRITE_LOG(LOG_DEBUG, "new port:%s", port.c_str());
202                 }
203             }
204         }
205     }
206     closedir(dir);
207 #endif
208     for (auto &oldPort : serialPortInfo) {
209         auto it = std::find(newPortInfo.begin(), newPortInfo.end(), oldPort);
210         if (it == newPortInfo.end()) {
211             // not found in new port list
212             // we need remove the connect info
213             serialPortRemoved.emplace_back(oldPort);
214         }
215     }
216 
217     if (!portChange) {
218         // new scan empty , same as port changed
219         if (serialPortInfo.size() != newPortInfo.size()) {
220             portChange = true;
221         }
222     }
223     if (portChange) {
224         serialPortInfo.swap(newPortInfo);
225     }
226     return bRet;
227 }
228 
229 #ifdef HOST_MINGW
230 std::string WstringToString(const std::wstring &wstr)
231 {
232     if (wstr.empty()) {
233         return std::string();
234     }
235     int size = WideCharToMultiByte(CP_ACP, 0, &wstr[0], (int)wstr.size(), NULL, 0, NULL, NULL);
236     std::string ret = std::string(size, 0);
237     WideCharToMultiByte(CP_ACP, 0, &wstr[0], (int)wstr.size(), &ret[0], size, NULL,
238                         NULL); // CP_UTF8
239     return ret;
240 }
241 
242 // review rename for same func from linux
243 int HdcHostUART::WinSetSerial(HUART hUART, string serialPort, int byteSize, int eqBaudRate)
244 {
245     int winRet = RET_SUCCESS;
246     COMMTIMEOUTS timeouts;
247     GetCommTimeouts(hUART->devUartHandle, &timeouts);
248     int interTimeout = 5;
249     timeouts.ReadIntervalTimeout = interTimeout;
250     timeouts.ReadTotalTimeoutMultiplier = 0;
251     timeouts.ReadTotalTimeoutConstant = 0;
252     timeouts.WriteTotalTimeoutMultiplier = 0;
253     timeouts.WriteTotalTimeoutConstant = 0;
254     SetCommTimeouts(hUART->devUartHandle, &timeouts);
255     constexpr int max = DEFAULT_BAUD_RATE_VALUE / 8 * 2; // 2 second buffer size
256     do {
257         if (!SetupComm(hUART->devUartHandle, max, max)) {
258             WRITE_LOG(LOG_WARN, "SetupComm %s fail, err:%d.", serialPort.c_str(), GetLastError());
259             winRet = ERR_GENERIC;
260             break;
261         }
262         DCB dcb;
263         if (!GetCommState(hUART->devUartHandle, &dcb)) {
264             WRITE_LOG(LOG_WARN, "GetCommState %s fail, err:%d.", serialPort.c_str(),
265                       GetLastError());
266             winRet = ERR_GENERIC;
267         }
268         dcb.DCBlength = sizeof(DCB);
269         dcb.BaudRate = eqBaudRate;
270         dcb.Parity = 0;
271         dcb.ByteSize = byteSize;
272         dcb.StopBits = ONESTOPBIT;
273         if (!SetCommState(hUART->devUartHandle, &dcb)) {
274             WRITE_LOG(LOG_WARN, "SetCommState %s fail, err:%d.", serialPort.c_str(),
275                       GetLastError());
276             winRet = ERR_GENERIC;
277             break;
278         }
279         if (!PurgeComm(hUART->devUartHandle,
280                        PURGE_RXCLEAR | PURGE_TXCLEAR | PURGE_RXABORT | PURGE_TXABORT)) {
281             WRITE_LOG(LOG_WARN, "PurgeComm  %s fail, err:%d.", serialPort.c_str(), GetLastError());
282             winRet = ERR_GENERIC;
283             break;
284         }
285         DWORD dwError;
286         COMSTAT cs;
287         if (!ClearCommError(hUART->devUartHandle, &dwError, &cs)) {
288             WRITE_LOG(LOG_WARN, "ClearCommError %s fail, err:%d.", serialPort.c_str(),
289                       GetLastError());
290             winRet = ERR_GENERIC;
291             break;
292         }
293     } while (false);
294     if (winRet != RET_SUCCESS) {
295         CloseSerialPort(hUART);
296     }
297     return winRet;
298 }
299 #endif // HOST_MINGW
300 
301 bool HdcHostUART::WaitUartIdle(HdcUART &uart, bool retry)
302 {
303     std::vector<uint8_t> readBuf;
304     WRITE_LOG(LOG_DEBUG, "%s clear read", __FUNCTION__);
305     ssize_t ret = ReadUartDev(readBuf, 1, uart);
306     if (ret == 0) {
307         WRITE_LOG(LOG_DEBUG, "%s port read timeout", __FUNCTION__);
308         return true;
309     } else {
310         WRITE_LOG(LOG_WARN, "%s port read something %zd", __FUNCTION__, ret);
311         if (retry) {
312             // we will read again , but only retry one time
313             return WaitUartIdle(uart, false);
314         } else {
315             return false;
316         }
317     }
318     return false;
319 }
320 
321 int HdcHostUART::OpenSerialPort(const std::string &connectKey)
322 {
323     HdcUART uart;
324     std::string portName;
325     uint32_t baudRate;
326     static int ret = 0;
327 
328     if (memset_s(&uart, sizeof(HdcUART), 0, sizeof(HdcUART)) != EOK) {
329         return -1;
330     }
331 
332     if (!GetPortFromKey(connectKey, portName, baudRate)) {
333         WRITE_LOG(LOG_ALL, "%s unknown format %s", __FUNCTION__, connectKey.c_str());
334         return -1;
335     }
336     do {
337         ret = 0;
338         WRITE_LOG(LOG_ALL, "%s try to open %s with rate %u", __FUNCTION__, portName.c_str(),
339                   baudRate);
340 
341 #ifdef HOST_MINGW
342         constexpr int numTmp = 2;
343         // review change to wstring ?
344         TCHAR apiBuf[PORT_NAME_LEN * numTmp];
345 #ifdef UNICODE
346         _stprintf_s(apiBuf, MAX_PATH, _T("\\\\.\\%S"), port.c_str());
347 #else
348         _stprintf_s(apiBuf, MAX_PATH, _T("\\\\.\\%s"), portName.c_str());
349 #endif
350         DWORD dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED;
351         uart.devUartHandle = CreateFile(apiBuf, GENERIC_READ | GENERIC_WRITE, 0, NULL,
352                                         OPEN_EXISTING, dwFlagsAndAttributes, NULL);
353         if (uart.devUartHandle == INVALID_HANDLE_VALUE) {
354             ret = ERR_GENERIC;
355             WRITE_LOG(LOG_DEBUG, "%s CreateFile %s err:%d.", __FUNCTION__, portName.c_str(),
356                       GetLastError());
357             break; // review for onethan one uart , here we need change to continue?
358         } else {
359             uart.serialPort = portName;
360         }
361         ret = WinSetSerial(&uart, uart.serialPort, UART_BIT2, baudRate);
362         if (ret != RET_SUCCESS) {
363             WRITE_LOG(LOG_WARN, "%s WinSetSerial:%s fail.", __FUNCTION__, uart.serialPort.c_str());
364             break;
365         }
366 #endif
367 
368 #if defined(HOST_LINUX)||defined(HOST_MAC)
369         string uartName = Base::CanonicalizeSpecPath(portName);
370         uart.devUartHandle = open(uartName.c_str(), O_RDWR | O_NOCTTY | O_NONBLOCK);
371         if (uart.devUartHandle < 0) {
372             constexpr int bufSize = 1024;
373             char buf[bufSize] = { 0 };
374             strerror_r(errno, buf, bufSize);
375             WRITE_LOG(LOG_WARN, "Linux open serial port failed, serialPort:%s, Message : %s",
376                       uart.serialPort.c_str(), buf);
377             ret = ERR_GENERIC;
378             break;
379         }
380         {
381             uart.serialPort = portName;
382         }
383         SetSerial(uart.devUartHandle, baudRate, UART_BIT2, 'N', 1);
384 #endif
385         // if the dev is idle
386         if (!WaitUartIdle(uart)) {
387             ret = ERR_GENERIC;
388             WRITE_LOG(LOG_INFO, "This is not a Idle UART port: %s", uart.serialPort.c_str());
389             break;
390         }
391         if (!ConnectMyNeed(&uart, connectKey)) {
392             WRITE_LOG(LOG_WARN, "ConnectMyNeed failed");
393             ret = ERR_GENERIC;
394             break;
395         } else {
396             uartOpened = true;
397             WRITE_LOG(LOG_INFO,
398                       "Serial Open Successfully! uart.serialPort:%s "
399                       "devUartHandle:%d",
400                       uart.serialPort.c_str(), uart.devUartHandle);
401         }
402         break;
403     } while (false);
404     if (ret != RET_SUCCESS) {
405         CloseSerialPort(&uart);
406     }
407     return ret;
408 }
409 
410 void HdcHostUART::UpdateUARTDaemonInfo(const std::string &connectKey, HSession hSession,
411                                        ConnStatus connStatus)
412 {
413     // add to list
414     HdcDaemonInformation diNew;
415     HDaemonInfo diNewPtr = &diNew;
416     diNew.connectKey = connectKey;
417     diNew.connType = CONN_SERIAL;
418     diNew.connStatus = connStatus;
419     diNew.hSession = hSession;
420     WRITE_LOG(LOG_DEBUG, "%s uart connectKey :%s session %s change to %d", __FUNCTION__,
421               connectKey.c_str(),
422               hSession == nullptr ? "<null>" : hSession->ToDebugString().c_str(), connStatus);
423     if (connStatus == STATUS_UNKNOW) {
424         server.AdminDaemonMap(OP_REMOVE, connectKey, diNewPtr);
425         if (hSession != nullptr and hSession->hUART != nullptr) {
426             connectedPorts.erase(hSession->hUART->serialPort);
427         }
428     } else {
429         if (connStatus == STATUS_CONNECTED) {
430             if (hSession != nullptr and hSession->hUART != nullptr) {
431                 connectedPorts.emplace(hSession->hUART->serialPort);
432             }
433         }
434         HDaemonInfo diOldPtr = nullptr;
435         server.AdminDaemonMap(OP_QUERY, connectKey, diOldPtr);
436         if (diOldPtr == nullptr) {
437             WRITE_LOG(LOG_DEBUG, "%s add new di", __FUNCTION__);
438             server.AdminDaemonMap(OP_ADD, connectKey, diNewPtr);
439         } else {
440             server.AdminDaemonMap(OP_UPDATE, connectKey, diNewPtr);
441         }
442     }
443 }
444 
445 bool HdcHostUART::StartUartReadThread(HSession hSession)
446 {
447     try {
448         HUART hUART = hSession->hUART;
449         hUART->readThread = std::thread(&HdcHostUART::UartReadThread, this, hSession);
450     } catch (...) {
451         server.FreeSession(hSession->sessionId);
452         UpdateUARTDaemonInfo(hSession->connectKey, hSession, STATUS_UNKNOW);
453         WRITE_LOG(LOG_WARN, "%s failed err", __FUNCTION__);
454         return false;
455     }
456 
457     WRITE_LOG(LOG_INFO, "%s success.", __FUNCTION__);
458     return true;
459 }
460 
461 bool HdcHostUART::StartUartSendThread()
462 {
463     WRITE_LOG(LOG_DEBUG, "%s.", __FUNCTION__);
464     try {
465         sendThread = std::thread(&HdcHostUART::UartWriteThread, this);
466     } catch (...) {
467         WRITE_LOG(LOG_WARN, "%s sendThread create failed", __FUNCTION__);
468         return false;
469     }
470 
471     WRITE_LOG(LOG_INFO, "%s success.", __FUNCTION__);
472     return true;
473 }
474 
475 // Determines that daemonInfo must have the device
476 HSession HdcHostUART::ConnectDaemonByUart(const HSession hSession, const HDaemonInfo)
477 {
478     if (!uartOpened) {
479         WRITE_LOG(LOG_DEBUG, "%s non uart opened.", __FUNCTION__);
480         return nullptr;
481     }
482     HUART hUART = hSession->hUART;
483     UpdateUARTDaemonInfo(hSession->connectKey, hSession, STATUS_READY);
484     WRITE_LOG(LOG_DEBUG, "%s :%s", __FUNCTION__, hUART->serialPort.c_str());
485     if (!StartUartReadThread(hSession)) {
486         WRITE_LOG(LOG_DEBUG, "%s StartUartReadThread fail.", __FUNCTION__);
487         return nullptr;
488     }
489 
490     externInterface.StartWorkThread(&server.loopMain, server.SessionWorkThread,
491                                     Base::FinishWorkThread, hSession);
492     // wait for thread up
493     while (hSession->childLoop.active_handles == 0) {
494         uv_sleep(1);
495     }
496     auto ctrl = server.BuildCtrlString(SP_START_SESSION, 0, nullptr, 0);
497     externInterface.SendToStream((uv_stream_t *)&hSession->ctrlPipe[STREAM_MAIN], ctrl.data(),
498                                  ctrl.size());
499     return hSession;
500 }
501 
502 RetErrCode HdcHostUART::StartupUARTWork()
503 {
504     WRITE_LOG(LOG_DEBUG, "%s", __FUNCTION__);
505     devUartWatcher.data = this;
506     constexpr int interval = 3000;
507     constexpr int delay = 1000;
508     if (externInterface.UvTimerStart(&devUartWatcher, UvWatchUartDevPlugin, delay, interval) != 0) {
509         WRITE_LOG(LOG_FATAL, "devUartWatcher start fail");
510         return ERR_GENERIC;
511     }
512     if (!StartUartSendThread()) {
513         WRITE_LOG(LOG_DEBUG, "%s StartUartSendThread fail.", __FUNCTION__);
514         return ERR_GENERIC;
515     }
516     return RET_SUCCESS;
517 }
518 
519 HSession HdcHostUART::ConnectDaemon(const std::string &connectKey)
520 {
521     WRITE_LOG(LOG_DEBUG, "%s", __FUNCTION__);
522     OpenSerialPort(connectKey);
523     return nullptr;
524 }
525 
526 /*
527 This function does the following:
528 1. Existing serial device, check whether a session is established, if not, go to establish
529 2. The connection is established but the serial device does not exist, delete the session
530 */
531 void HdcHostUART::WatchUartDevPlugin()
532 {
533     std::lock_guard<std::mutex> lock(semUartDevCheck);
534     bool portChange = false;
535 
536     if (!EnumSerialPort(portChange)) {
537         WRITE_LOG(LOG_WARN, "%s enumDetailsSerialPorts fail.", __FUNCTION__);
538     } else if (portChange) {
539         for (const auto &port : serialPortInfo) {
540             WRITE_LOG(LOG_INFO, "%s found uart port :%s", __FUNCTION__, port.c_str());
541             // check port have session
542             HDaemonInfo hdi = nullptr;
543             server.AdminDaemonMap(OP_QUERY, port, hdi);
544             if (hdi == nullptr and connectedPorts.find(port) == connectedPorts.end()) {
545                 UpdateUARTDaemonInfo(port, nullptr, STATUS_READY);
546             }
547         }
548         for (const auto &port : serialPortRemoved) {
549             WRITE_LOG(LOG_INFO, "%s remove uart port :%s", __FUNCTION__, port.c_str());
550             // check port have session
551             HDaemonInfo hdi = nullptr;
552             server.AdminDaemonMap(OP_QUERY, port, hdi);
553             if (hdi != nullptr and hdi->hSession == nullptr) {
554                 // we only remove the empty port
555                 UpdateUARTDaemonInfo(port, nullptr, STATUS_UNKNOW);
556             }
557         }
558     }
559 }
560 
561 bool HdcHostUART::ConnectMyNeed(HUART hUART, std::string connectKey)
562 {
563     // we never use port to connect, we use connect key
564     if (connectKey.empty()) {
565         connectKey = hUART->serialPort;
566     }
567     if (connectKey != hUART->serialPort) {
568         UpdateUARTDaemonInfo(hUART->serialPort, nullptr, STATUS_UNKNOW);
569     }
570     UpdateUARTDaemonInfo(connectKey, nullptr, STATUS_READY);
571 
572     HSession hSession = server.MallocSession(true, CONN_SERIAL, this);
573     hSession->connectKey = connectKey;
574 #if defined(HOST_LINUX)||defined(HOST_MAC)
575     hSession->hUART->devUartHandle = hUART->devUartHandle;
576 #elif defined(HOST_MINGW)
577     hSession->hUART->devUartHandle = hUART->devUartHandle;
578 #endif
579 
580     hSession->isCheck = isCheck;
581     hSession->hUART->serialPort = hUART->serialPort;
582     WRITE_LOG(LOG_DEBUG, "%s connectkey:%s,port:%s", __FUNCTION__, hSession->connectKey.c_str(),
583               hUART->serialPort.c_str());
584     uv_timer_t *waitTimeDoCmd = new(std::nothrow) uv_timer_t;
585     if (waitTimeDoCmd == nullptr) {
586         WRITE_LOG(LOG_FATAL, "ConnectMyNeed new waitTimeDoCmd failed");
587         return false;
588     }
589     uv_timer_init(&server.loopMain, waitTimeDoCmd);
590     waitTimeDoCmd->data = hSession;
591     if (externInterface.UvTimerStart(waitTimeDoCmd, server.UartPreConnect, UV_TIMEOUT, UV_REPEAT) !=
592         RET_SUCCESS) {
593         WRITE_LOG(LOG_DEBUG, "%s for %s:%s fail.", __FUNCTION__, hSession->connectKey.c_str(),
594                   hUART->serialPort.c_str());
595         return false;
596     }
597     WRITE_LOG(LOG_DEBUG, "%s %s register a session", __FUNCTION__, hUART->serialPort.c_str());
598 
599     return true;
600 }
601 
602 void HdcHostUART::KickoutZombie(HSession hSession)
603 {
604     if (hSession == nullptr or hSession->hUART == nullptr or hSession->isDead) {
605         return;
606     }
607 #ifdef _WIN32
608     if (hSession->hUART->devUartHandle == INVALID_HANDLE_VALUE) {
609         return;
610     }
611 #else
612     if (hSession->hUART->devUartHandle < 0) {
613         return;
614     }
615 #endif
616     WRITE_LOG(LOG_DEBUG, "%s FreeSession %s", __FUNCTION__, hSession->ToDebugString().c_str());
617     server.FreeSession(hSession->sessionId);
618 }
619 
620 HSession HdcHostUART::GetSession(const uint32_t sessionId, bool)
621 {
622     return server.AdminSession(OP_QUERY, sessionId, nullptr);
623 }
624 void HdcHostUART::CloseSerialPort(const HUART hUART)
625 {
626     WRITE_LOG(LOG_DEBUG, "%s try to close dev handle %d", __FUNCTION__, hUART->devUartHandle);
627 
628 #ifdef _WIN32
629     if (hUART->devUartHandle != INVALID_HANDLE_VALUE) {
630         CloseHandle(hUART->devUartHandle);
631         hUART->devUartHandle = INVALID_HANDLE_VALUE;
632     }
633 #else
634     if (hUART->devUartHandle != -1) {
635         Base::CloseFd(hUART->devUartHandle);
636         hUART->devUartHandle = -1;
637     }
638 #endif
639 }
640 
641 void HdcHostUART::OnTransferError(const HSession session)
642 {
643     if (session != nullptr) {
644         WRITE_LOG(LOG_FATAL, "%s:%s", __FUNCTION__, session->ToDebugString().c_str());
645         if (session->hUART != nullptr) {
646             if (IsDeviceOpened(*session->hUART)) {
647                 // same device dont echo twice to client
648                 string echoStr = "ERR: uart link layer transmission error.\n";
649                 server.EchoToClientsForSession(session->sessionId, echoStr);
650             }
651             // 1. dev opened by other application
652             // 2. dev is plug out
653             // 3. dev line is broken ?
654             // we set the status to empty
655             // watcher will reopen it if it can find this again
656             CloseSerialPort(session->hUART);
657             UpdateUARTDaemonInfo(session->connectKey, session, STATUS_OFFLINE);
658         }
659 
660         server.FreeSession(session->sessionId);
661         ClearUARTOutMap(session->sessionId);
662     }
663 }
664 
665 // review what about merge Restartession with OnTransferError ?
666 void HdcHostUART::Restartession(const HSession session)
667 {
668     HdcUARTBase::Restartession(session);
669     // allow timer watcher make a new session.
670     if (session != nullptr and session->hUART != nullptr) {
671         WRITE_LOG(LOG_FATAL, "%s reset serialPort:%s", __FUNCTION__,
672                   session->hUART->serialPort.c_str());
673         CloseSerialPort(session->hUART); // huart will free , so we must clost it here
674         server.EchoToClientsForSession(session->sessionId,
675                                        "uart link released by daemon. need connect again.");
676     }
677 }
678 
679 void HdcHostUART::StopSession(HSession hSession)
680 {
681     if (hSession == nullptr) {
682         WRITE_LOG(LOG_FATAL, "%s hSession is null", __FUNCTION__);
683         return;
684     }
685     WRITE_LOG(LOG_DEBUG, "%s hSession %s will be stop and free", __FUNCTION__,
686               hSession->ToDebugString().c_str());
687     HUART hUART = hSession->hUART;
688     if (hUART == nullptr) {
689         WRITE_LOG(LOG_FATAL, "%s hUART is null", __FUNCTION__);
690     } else {
691 #ifdef _WIN32
692         CancelIoEx(hUART->devUartHandle, NULL);
693 #endif
694         // we make select always have a timeout in linux
695         // also we make a mark here
696         // ReadUartDev will return for this flag
697         hUART->ioCancel = true;
698 
699         if (hUART->readThread.joinable()) {
700             WRITE_LOG(LOG_DEBUG, "wait readThread Stop");
701             hUART->readThread.join();
702         } else {
703             WRITE_LOG(LOG_FATAL, "readThread is not joinable");
704         }
705     }
706 
707     // call the base side
708     HdcUARTBase::StopSession(hSession);
709 }
710 
711 std::vector<std::string> HdcHostUART::StringSplit(std::string source, std::string split)
712 {
713     std::vector<std::string> result;
714 
715     // find
716     if (!split.empty()) {
717         size_t pos = 0;
718         while ((pos = source.find(split)) != std::string::npos) {
719             // split
720             std::string token = source.substr(0, pos);
721             if (!token.empty()) {
722                 result.push_back(token);
723             }
724             source.erase(0, pos + split.length());
725         }
726     }
727     // add last token
728     if (!source.empty()) {
729         result.push_back(source);
730     }
731     return result;
732 }
733 
734 bool HdcHostUART::GetPortFromKey(const std::string &connectKey, std::string &portName,
735                                  uint32_t &baudRate)
736 {
737     // we support UART_NAME:UART_RATE format
738     // like COM5:115200
739     constexpr size_t TWO_ARGS = 2;
740     std::vector<std::string> result = StringSplit(connectKey, ",");
741     if (result.size() == TWO_ARGS) {
742         portName = result[0];
743         try {
744             baudRate = static_cast<uint32_t>(std::stoul(result[1]));
745         } catch (...) {
746             return false;
747         }
748         return true;
749     } else if (result.size() == 1) {
750         portName = result[0];
751         baudRate = DEFAULT_BAUD_RATE_VALUE;
752         return true;
753     } else {
754         return false;
755     }
756 }
757 
758 void HdcHostUART::SendUartSoftReset(HSession hSession, uint32_t sessionId)
759 {
760     UartHead resetPackage(sessionId, PKG_OPTION_RESET);
761     resetPackage.dataSize = sizeof(UartHead);
762     RequestSendPackage(reinterpret_cast<uint8_t *>(&resetPackage), sizeof(UartHead), false);
763 }
764 
765 void HdcHostUART::Stop()
766 {
767     WRITE_LOG(LOG_DEBUG, "%s Stop!", __FUNCTION__);
768     if (!stopped) {
769         externInterface.TryCloseHandle((uv_handle_t *)&devUartWatcher);
770         uartOpened = false;
771         stopped = true;
772         // just click it for exit
773         NotifyTransfer();
774         if (sendThread.joinable()) {
775             WRITE_LOG(LOG_DEBUG, "%s wait sendThread Stop!", __FUNCTION__);
776             sendThread.join();
777         } else {
778             WRITE_LOG(LOG_FATAL, "%s sendThread is not joinable", __FUNCTION__);
779         }
780     }
781 }
782 } // namespace Hdc
783 #endif // HDC_SUPPORT_UART
784