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