control_sensor.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. #define WIN32_LEAN_AND_MEAN
  2. #include <WinSock2.h>
  3. #include "PCANBasic.h"
  4. #include "./include/EgoInterface.h"
  5. #include "EgoClient.h"
  6. #include "EgoWindow.h"
  7. #include "protocol.pb.h"
  8. #include "../common/iobuffer.h"
  9. #include "protocol.pb.h"
  10. #include "control_sensor.h"
  11. #include <algorithm>
  12. #include <string>
  13. #include<json/json.h>
  14. std::string CControlSensor::m_userID; // 在类外定义静态成员变量
  15. int32_t CControlSensor::m_carID;
  16. #define MAX_DGREE (int32_t)(4096/6)
  17. inline int16_t make_int16(int8_t h, int8_t l)
  18. {
  19. int16_t hi = (int16_t)(h & 0x00FF);
  20. int16_t low = (int16_t)(l & 0x00FF);
  21. return (hi << 8) | low;
  22. }
  23. inline int8_t hi_byte(int16_t value)
  24. {
  25. int8_t hi =(int8_t)((value & 0xFF00) >> 8);
  26. return hi;
  27. }
  28. inline int8_t lo_byte(int16_t value)
  29. {
  30. int8_t lo = (int8_t)(value & 0xff);
  31. return lo;
  32. }
  33. CControlSensor::CControlSensor(CMessageQueue* q)
  34. {
  35. _window = static_cast<CEgoWindow*>(q);
  36. _collection = Sensor_Collection::Sensor_None;
  37. }
  38. void CControlSensor::Notify(TPCANMsg& canmsg,uint64_t timestamp)
  39. {
  40. //OutputDebugString(str);
  41. //OutputDebugString(ret.c_str());
  42. //发送座椅信号给下位机
  43. switch (canmsg.ID)
  44. {
  45. case 0x181:
  46. {
  47. //接收181msg
  48. frames[0].canid = canmsg.ID;
  49. frames[0].dlc = canmsg.LEN;
  50. memcpy(&frames[0].data, canmsg.DATA, sizeof(canmsg.DATA));
  51. //flag收到181
  52. _collection = (Sensor_Collection)(_collection | Sensor_Collection::Sensor_181);
  53. }
  54. break;
  55. case 0x182:
  56. {
  57. //接收182msg
  58. frames[1].canid = canmsg.ID;
  59. frames[1].dlc = canmsg.LEN;
  60. memcpy(&frames[1].data, canmsg.DATA, sizeof(canmsg.DATA));
  61. //flag收到182
  62. _collection = (Sensor_Collection)(_collection | Sensor_Collection::Sensor_182);
  63. }
  64. break;
  65. case 0x183:
  66. { //接收183msg
  67. frames[2].canid = canmsg.ID;
  68. frames[2].dlc = canmsg.LEN;
  69. memcpy(&frames[2].data, canmsg.DATA, sizeof(canmsg.DATA));
  70. //flag收到183
  71. _collection = (Sensor_Collection)(_collection | Sensor_Collection::Sensor_183);
  72. }
  73. break;
  74. case 0x184:
  75. //case 0x611:
  76. {
  77. //接收184msg
  78. frames[3].canid = canmsg.ID;
  79. frames[3].dlc = canmsg.LEN;
  80. memcpy(&frames[3].data, canmsg.DATA, sizeof(canmsg.DATA));
  81. //flag收到184
  82. _collection = (Sensor_Collection)(_collection | Sensor_Collection::Sensor_184);
  83. //
  84. //解读184信号,发送到Qt显示(灯光与档位状态和声音的改变)
  85. bool cautionLight = frames[3].data[0] & 0x4;
  86. bool lightL = frames[3].data[0] & 0x8;
  87. bool lightR = frames[3].data[0] & 0x10;
  88. bool gearF = frames[3].data[0] & 0x20;
  89. bool gearR = frames[3].data[0] & 0x40;
  90. bool carPark = frames[3].data[1] & 0x1;
  91. bool buzzerPlay = frames[3].data[1] & 0x2;
  92. bool lightFront = frames[3].data[2] & 0x10;
  93. bool lightWork = frames[3].data[2] & 0x20;
  94. bool emergency = frames[3].data[3] & 0x2;
  95. _window->GetEgoClient()->OnCautionLight(cautionLight);
  96. _window->GetEgoClient()->OnLightL(lightL);
  97. _window->GetEgoClient()->OnLightR(lightR);
  98. _window->GetEgoClient()->OnGearF(gearF);
  99. _window->GetEgoClient()->OnGearR(gearR);
  100. _window->GetEgoClient()->OnCarPark(carPark);
  101. _window->GetEgoClient()->OnBuzzerPlay(buzzerPlay);
  102. _window->GetEgoClient()->OnLightFront(lightFront);
  103. _window->GetEgoClient()->OnLightWork(lightWork);
  104. _window->GetEgoClient()->OnEmergency(emergency);
  105. }
  106. break;
  107. case 0x185:
  108. {
  109. //接收185msg
  110. frames[4].canid = canmsg.ID;
  111. frames[4].dlc = canmsg.LEN;
  112. memcpy(&frames[4].data, canmsg.DATA, sizeof(canmsg.DATA));
  113. //flag收到185
  114. _collection = (Sensor_Collection)(_collection | Sensor_Collection::Sensor_185);
  115. }
  116. break;
  117. }
  118. if (_window->GetControlState() == ControlState::Process && _collection == Sensor_Collection::Sensor_All)
  119. {
  120. static DWORD tick = GetTickCount();
  121. RemoNet::CCCanMsg req;
  122. for (int32_t i = 0; i < _countof(frames); i++)
  123. {
  124. if (frames[i].canid != 0)
  125. {
  126. RemoNet::can_net_frame* frame = req.add_frams();
  127. frame->set_canid(frames[i].canid);
  128. frame->set_dlc(frames[i].dlc);
  129. frame->set_data(frames[i].data, frames[i].dlc);
  130. }
  131. }
  132. MessageHead Head;
  133. CIOBuffer pBuffer;
  134. Head.Command = RemoNet::CC_CANMSG;
  135. Head.Length = req.ByteSizeLong();
  136. Head.Serialize(pBuffer.Buffer);
  137. auto ptr = pBuffer.Buffer + MessageHead::Size();
  138. req.SerializeToArray(ptr, Head.Length);
  139. pBuffer.Length = MessageHead::Size() + Head.Length;
  140. _window->SendData(pBuffer);
  141. _collection = Sensor_Collection::Sensor_None;
  142. /*DWORD diff = GetTickCount() - tick;
  143. tick = GetTickCount();
  144. std::string str = std::to_string(diff);
  145. str += "\n";
  146. OutputDebugStringA(str.c_str());
  147. */
  148. //mqtt
  149. //_window->GetEgoClient()->OnMqttData(frames);
  150. }
  151. }
  152. void CControlSensor::NotifyMqtt()
  153. {
  154. std::string userID = m_userID;
  155. int32_t vehicleID = m_carID;
  156. auto timeStamp = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
  157. int keyStatus = ((frames[3].data[2] >> 7) & 0x01) * 2 + ((frames[3].data[3] >> 0) & 0x01) * 1;
  158. int gearControl = ((frames[3].data[0] >> 6) & 0x01) * 2 + ((frames[3].data[0] >> 5) & 0x01) * 1;
  159. int travelLight = ((frames[3].data[0] >> 0) & 0x01) * 2 + ((frames[3].data[0] >> 1) & 0x01) * 1;
  160. std::string accPedal = std::to_string(frames[0].data[0]) + " AND " + std::to_string(frames[0].data[1]) +
  161. " || " + std::to_string(frames[0].data[2]) + " AND " + std::to_string(frames[0].data[3]);
  162. std::string brakePedal = std::to_string(frames[0].data[4]) + " AND " + std::to_string(frames[0].data[5]);
  163. std::string steeringWheel = std::to_string(frames[2].data[2]) + " AND " + std::to_string(frames[2].data[3]);
  164. int turnSignal = ((frames[3].data[0] >> 4) & 0x01) * 2 + ((frames[3].data[0] >> 3) & 0x01) * 1;
  165. int turnMode = ((frames[3].data[3] >> 6) & 0x01) * 4 + ((frames[3].data[3] >> 5) & 0x01) * 3 +
  166. ((frames[3].data[3] >> 4) & 0x01) * 2 + ((frames[3].data[3] >> 3) & 0x01) * 1;
  167. int workLight = ((frames[3].data[2] >> 5) & 0x01) * 2 + ((frames[3].data[2] >> 4) & 0x01) * 1;
  168. int baseLegSwitch = ((frames[3].data[1] >> 5) & 0x01) * 8 + ((frames[3].data[1] >> 4) & 0x01) * 4 +
  169. ((frames[3].data[1] >> 3) & 0x01) * 2 + ((frames[3].data[1] >> 2) & 0x01) * 1;
  170. std::string baseLegControl = std::to_string(frames[0].data[6]) + " AND " + std::to_string(frames[0].data[7]);
  171. std::string taskJoint_1 = std::to_string(frames[1].data[0]) + " AND " + std::to_string(frames[1].data[1]);
  172. std::string taskJoint_2 = std::to_string(frames[1].data[6]) + " AND " + std::to_string(frames[1].data[7]);
  173. std::string taskJoint_3 = std::to_string(frames[1].data[2]) + " AND " + std::to_string(frames[1].data[3]);
  174. std::string endJoint = std::to_string(frames[2].data[0]) + " AND " + std::to_string(frames[2].data[1]);
  175. std::string toolControl = std::to_string(frames[1].data[4]) + " AND " + std::to_string(frames[1].data[5]);
  176. int cabLift = ((frames[3].data[1] >> 7) & 0x01) * 2 + ((frames[3].data[1] >> 6) & 0x01) * 1;
  177. int coopSignal = ((frames[3].data[4] >> 4) & 0x01) * 2 + ((frames[3].data[4] >> 3) & 0x01) * 1;
  178. int errAccPedal = ((frames[3].data[5] >> 7) & 0x01) * 2 + ((frames[3].data[5] >> 6) & 0x01) * 1;
  179. int errHandle = ((frames[3].data[5] >> 4) & 0x01) * 16 + ((frames[3].data[5] >> 3) & 0x01) * 8 + ((frames[3].data[5] >> 2) & 0x01) * 4 +
  180. ((frames[3].data[5] >> 1) & 0x01) * 2 + ((frames[3].data[5] >> 0) & 0x01) * 1;
  181. Json::Value pcanRoot;
  182. pcanRoot["cockpitID"] = Json::Value("Cop001");
  183. pcanRoot["userID"] = Json::Value(userID);
  184. pcanRoot["vehicleID"] = Json::Value(vehicleID);
  185. pcanRoot["timeStamp"] = Json::Value(timeStamp);
  186. Json::Value basRoot;
  187. basRoot["keyStatus"] = Json::Value(keyStatus);
  188. basRoot["parkControl"] = Json::Value(frames[3].data[1] >> 0 & 0x01);
  189. basRoot["travelMode"] = Json::Value(frames[3].data[3] >> 2 & 0x01);
  190. basRoot["eStop"] = Json::Value(frames[3].data[3] >> 1 & 0x01);
  191. basRoot["directSwitch"] = Json::Value(frames[3].data[4] >> 2 & 0x01);
  192. basRoot["gearControl"] = Json::Value(gearControl);
  193. basRoot["hazardLight"] = Json::Value(frames[3].data[0] >> 2 & 0x01);
  194. basRoot["travelLight"] = Json::Value(travelLight);
  195. basRoot["vehicleHorn"] = Json::Value(frames[3].data[1] >> 1 & 0x01);
  196. basRoot["silencedAlarm"] = Json::Value(frames[3].data[2] >> 6 & 0x01);
  197. pcanRoot["basControl"] = Json::Value(basRoot);
  198. Json::Value driveRoot;
  199. driveRoot["accPedal"] = Json::Value(accPedal);
  200. driveRoot["brakePedal"] = Json::Value(brakePedal);
  201. driveRoot["steeringWheel"] = Json::Value(steeringWheel);
  202. driveRoot["turnSignal"] = Json::Value(turnSignal);
  203. driveRoot["turnMode"] = Json::Value(turnMode);
  204. pcanRoot["driverControl"] = Json::Value(driveRoot);
  205. Json::Value taskRoot;
  206. taskRoot["enableHydraulic"] = Json::Value(frames[3].data[2] >> 0 & 0x01);
  207. taskRoot["workLight"] = Json::Value(workLight);
  208. taskRoot["bypassSwitch"] = Json::Value(frames[3].data[2] >> 1 & 0x01);
  209. taskRoot["baseLegSwitch"] = Json::Value(baseLegSwitch);
  210. taskRoot["baseLegControl"] = Json::Value(baseLegControl);
  211. taskRoot["taskJoint_1"] = Json::Value(taskJoint_1);
  212. taskRoot["taskJoint_2"] = Json::Value(taskJoint_2);
  213. taskRoot["taskJoint_3"] = Json::Value(taskJoint_3);
  214. taskRoot["endJoint"] = Json::Value(endJoint);
  215. taskRoot["toolControl"] = Json::Value(toolControl);
  216. taskRoot["suckerSelect"] = Json::Value(frames[3].data[2] >> 2 & 0x01);
  217. taskRoot["cabLift"] = Json::Value(cabLift);
  218. taskRoot["esCabLift"] = Json::Value(frames[3].data[2] >> 3 & 0x01);
  219. taskRoot["coopSignal"] = Json::Value(coopSignal);
  220. pcanRoot["taskControl"] = Json::Value(taskRoot);
  221. Json::Value errRoot;
  222. errRoot["errBasOperation"] = Json::Value("");
  223. errRoot["errAccPedal"] = Json::Value(errAccPedal);
  224. errRoot["errBrakePedal"] = Json::Value(frames[3].data[6] >> 0 & 0x01);
  225. errRoot["errSteeringWheel"] = Json::Value(frames[3].data[6] >> 1 & 0x01);
  226. errRoot["errHandle"] = Json::Value(errHandle);
  227. errRoot["errEndTool"] = Json::Value(frames[3].data[5] >> 5 & 0x01);
  228. errRoot["errOther"] = Json::Value("");
  229. pcanRoot["errCode"] = Json::Value(errRoot);
  230. // 转换 JSON 对象为字符串
  231. std::string jsonPcan = Json::writeString(Json::StreamWriterBuilder(), pcanRoot);
  232. //设置mqtt客户端
  233. mqtt::async_client client("10.10.60.237:41883", "clientPcan");
  234. callback cb;
  235. client.set_callback(cb);
  236. //配置 MQTT 连接的遗嘱消息
  237. mqtt::connect_options conopts; //配置 MQTT 连接的选项
  238. /*mqtt::message willmsg("Cockpit/CanBus/CanId001/Cop001", "Last will and testament", 1, true);
  239. mqtt::will_options will(willmsg);
  240. conopts.set_will(will);*/
  241. try {
  242. mqtt::token_ptr conntok = client.connect(conopts); //使用之前配置的conopts与MQTT 代理连接
  243. conntok->wait(); //等待连接的确认消息,确保连接成功建立
  244. mqtt::delivery_token_ptr pubtok; //跟踪消息的发布状态的指针
  245. pubtok = client.publish("Cockpit/CanBus/CanId001/Cop001", jsonPcan.c_str(), jsonPcan.length(), 1, false); //将消息发布到 MQTT 代理,设置参数
  246. //pubtok->wait_for(1);
  247. //检查MQTT客户端是否有发送失败的消息
  248. auto toks = client.get_pending_delivery_tokens(); //返回一个包含所有待处理投递令牌的容器
  249. if (!toks.empty())
  250. std::cout << "Error: There are pending delivery tokens!" << std::endl;
  251. }
  252. //异常处理块,用于捕获和处理 MQTT 相关的异常
  253. catch (const mqtt::exception& exc) {
  254. std::cerr << exc.what() << std::endl;
  255. }
  256. }
  257. ControlStatus CControlSensor::CheckStatus()
  258. {
  259. return ControlStatus::Ok;
  260. }
  261. bool CControlSensor::Start()
  262. {
  263. int iBuffer;
  264. TPCANStatus stsResult;
  265. TPCANHandle _HandlesArray[16];
  266. _HandlesArray[0] = PCAN_USBBUS1;
  267. _HandlesArray[1] = PCAN_USBBUS2;
  268. _HandlesArray[2] = PCAN_USBBUS3;
  269. _HandlesArray[3] = PCAN_USBBUS4;
  270. _HandlesArray[4] = PCAN_USBBUS5;
  271. _HandlesArray[5] = PCAN_USBBUS6;
  272. _HandlesArray[6] = PCAN_USBBUS7;
  273. _HandlesArray[7] = PCAN_USBBUS8;
  274. _HandlesArray[8] = PCAN_USBBUS9;
  275. _HandlesArray[9] = PCAN_USBBUS10;
  276. _HandlesArray[10] = PCAN_USBBUS11;
  277. _HandlesArray[11] = PCAN_USBBUS12;
  278. _HandlesArray[12] = PCAN_USBBUS13;
  279. _HandlesArray[13] = PCAN_USBBUS14;
  280. _HandlesArray[14] = PCAN_USBBUS15;
  281. _HandlesArray[15] = PCAN_USBBUS16;
  282. for (int i = 0; i < (sizeof(_HandlesArray) / sizeof(TPCANHandle)); i++)
  283. {
  284. stsResult = CAN_GetValue(_HandlesArray[i], PCAN_CHANNEL_CONDITION, &iBuffer, sizeof(iBuffer));
  285. if (((stsResult) == PCAN_ERROR_OK) && ((iBuffer & PCAN_CHANNEL_AVAILABLE) == PCAN_CHANNEL_AVAILABLE))
  286. {
  287. stsResult = CAN_GetValue((TPCANHandle)_HandlesArray[i], PCAN_CHANNEL_FEATURES, (void*)&iBuffer, sizeof(iBuffer));
  288. _isFD = (stsResult == PCAN_ERROR_OK) && (iBuffer & FEATURE_FD_CAPABLE);
  289. _handle = _HandlesArray[i];
  290. break;
  291. }
  292. }
  293. if (_handle != -1)
  294. {
  295. TPCANStatus stsResult = CAN_Initialize(_handle, PCAN_BAUD_250K);
  296. //使用雷达盒子测试用500k
  297. //TPCANStatus stsResult = CAN_Initialize(_handle, PCAN_BAUD_500K);
  298. if (stsResult != PCAN_ERROR_OK)
  299. {
  300. return false;
  301. }
  302. _thread = std::thread(&CControlSensor::Run, this);
  303. }
  304. return _handle != -1;
  305. }
  306. void CControlSensor::Run()
  307. {
  308. _run = true;
  309. while (_run)
  310. {
  311. for (int32_t i = 0; i < sizeof(frames) / sizeof(cannet_frame); i++)
  312. {
  313. frames[i].canid = 0;
  314. }
  315. Sleep(10);
  316. ReadMessages();
  317. }
  318. CAN_Uninitialize(_handle);
  319. }
  320. void CControlSensor::ReadMessages()
  321. {
  322. TPCANStatus stsResult;
  323. // We read at least one time the queue looking for messages. If a message is found, we look again trying to
  324. // find more. If the queue is empty or an error occurr, we get out from the dowhile statement.
  325. do
  326. {
  327. ReadMessage();
  328. if (stsResult != PCAN_ERROR_OK && stsResult != PCAN_ERROR_QRCVEMPTY)
  329. {
  330. //ShowStatus(stsResult);
  331. return;
  332. }
  333. } while (!(stsResult & PCAN_ERROR_QRCVEMPTY));
  334. }
  335. TPCANStatus CControlSensor::ReadMessage()
  336. {
  337. TPCANMsg CANMsg;
  338. TPCANTimestamp CANTimeStamp;
  339. // We execute the "Read" function of the PCANBasic
  340. TPCANStatus stsResult = CAN_Read(_handle, &CANMsg, &CANTimeStamp);
  341. if (stsResult != PCAN_ERROR_QRCVEMPTY)
  342. { // We process the received message
  343. uint64_t newTimestamp = (CANTimeStamp.micros + 1000 * CANTimeStamp.millis + 0x100000000 * 1000 * CANTimeStamp.millis_overflow);
  344. Notify(CANMsg, newTimestamp);
  345. NotifyMqtt();
  346. }
  347. return stsResult;
  348. }
  349. //将PCAN信号传回座椅PLC中
  350. TPCANStatus CControlSensor::SendCANMessage(TPCANMsg* CANMsg)
  351. {
  352. // 执行PCANBasic的“写入”功能
  353. TPCANStatus stsResult = CAN_Write(_handle, CANMsg);
  354. return stsResult;
  355. }
  356. void CControlSensor::Stop()
  357. {
  358. _run = false;
  359. _thread.join();
  360. }
  361. void CControlSensor::SetEngineRPM(int32_t value)
  362. {
  363. _rpm = value;
  364. }
  365. std::string CControlSensor::setSCSignUuid(std::string user_uuid)
  366. {
  367. m_userID = user_uuid;
  368. return m_userID;
  369. }
  370. int32_t CControlSensor :: setCarID(int32_t CarID)
  371. {
  372. m_carID = CarID;
  373. return m_carID;
  374. }