ForeignHaiRoboticsService.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. <?php
  2. namespace App\Services;
  3. use App\Exceptions\ErrorException;
  4. use App\MaterialBox;
  5. use App\StationCacheShelfGrid;
  6. use App\StationTaskMaterialBox;
  7. use Illuminate\Support\Collection;
  8. use Illuminate\Support\Facades\DB;
  9. use Illuminate\Support\Facades\Http;
  10. use App\Traits\ServiceAppAop;
  11. class ForeignHaiRoboticsService
  12. {
  13. use ServiceAppAop;
  14. // protected $modelClass=ForeignHaiRobotics::class;
  15. /** @var $stationTaskMaterialBoxService StationTaskMaterialBoxService */
  16. private $stationTaskMaterialBoxService;
  17. /** @var $stationTaskBatchService StationTaskBatchService */
  18. private $stationTaskBatchService;
  19. /** @var $stationTaskCommoditiesService StationTaskCommodityService */
  20. private $stationTaskCommoditiesService;
  21. /** @var $materialBoxService MaterialBoxService */
  22. private $materialBoxService;
  23. /** @var $stationTaskService StationTaskService */
  24. private $stationTaskService;
  25. /** @var $stationService StationService */
  26. private $stationService;
  27. public function __construct()
  28. {
  29. $this->stationTaskMaterialBoxService=null;
  30. $this->materialBoxService=null;
  31. $this->stationService=null;
  32. }
  33. /**
  34. * @param string $modeName '输送线入立架'|'立架出至输送线'|'移动立架内位置'|'缓存架入立架'|'立架出至缓存架'
  35. * @param string $fromLocation
  36. * @param string $toLocation
  37. * @param Collection $taskMaterialBoxes
  38. * @param string $groupId
  39. * @param int $priority
  40. * @param int $isSequenced
  41. * @return array
  42. */
  43. private function makeJson_move(
  44. Collection $taskMaterialBoxes,
  45. string $modeName,
  46. string $fromLocation='',
  47. string $toLocation='',
  48. $groupId=''
  49. , $priority=10
  50. , $isSequenced=1
  51. ): array
  52. {
  53. $timestampSuffix = microtime(true);
  54. $taskMode=(function()use($modeName){
  55. switch ($modeName){
  56. case '输送线入立架': return 1;
  57. case '立架出至输送线': return 2;
  58. case '移动立架内位置': return 3;
  59. case '缓存架入立架':
  60. case '立架出至缓存架': return 6;
  61. default: throw new \Exception('发至海柔的移料箱请求,模式不存在');
  62. }
  63. })();
  64. $bins=$taskMaterialBoxes->map(function (StationTaskMaterialBox $taskMaterialBox)use($timestampSuffix,$fromLocation,$toLocation){
  65. return [
  66. "taskCode" =>$taskMaterialBox['id'].'_'.$timestampSuffix,
  67. "binCode" => $taskMaterialBox['materialBox']['code'],
  68. "fromLocCode" => $fromLocation??'',
  69. "toLocCode" => $toLocation??'',
  70. ];
  71. });
  72. return [[
  73. "taskMode" =>$taskMode,
  74. "bins"=>$bins,
  75. "groupCode"=>$groupId.'_'.$timestampSuffix,
  76. "priority"=>$priority,
  77. "sequenceFlag"=>$isSequenced,
  78. ]];
  79. }
  80. public function fetchGroup($toLocation, Collection $taskMaterialBoxes, $groupIdPrefix=''): bool
  81. {
  82. LogService::log(__METHOD__,'runMany','波次任务分配6.r5f0:');
  83. LogService::log(__METHOD__,'runMany','波次任务分配6.r5f1:'.json_encode($toLocation).json_encode($taskMaterialBoxes).json_encode($groupIdPrefix));
  84. $dataToPost=$this->makeJson_move(
  85. $taskMaterialBoxes,
  86. '立架出至输送线',
  87. '',
  88. $toLocation??'',
  89. $groupIdPrefix
  90. );
  91. LogService::log(__METHOD__,'runMany','波次任务分配6.r5f2:'.json_encode($dataToPost));
  92. return $this->controlHaiRobot($dataToPost);
  93. }
  94. public function moveBin(){
  95. }
  96. public function markBinProcessed(
  97. $workStation,
  98. $binCode,
  99. $success,
  100. $created_at,
  101. $exception,
  102. $is_in_plan
  103. ): bool
  104. {
  105. LogService::log('海柔请求','markBinProcessed1.1',
  106. '');
  107. $this->instant($this->stationService,'StationService');
  108. $this->instant($this->materialBoxService,'MaterialBoxService');
  109. $this->instant($this->stationTaskMaterialBoxService,'StationTaskMaterialBoxService');
  110. $this->instant($this->stationTaskCommoditiesService,'StationTaskCommodityService');
  111. $this->instant($this->stationTaskBatchService,'StationTaskBatchService');
  112. try{
  113. LogService::log('海柔请求','markBinProcessed1.2',
  114. json_encode([$binCode,$success,$exception,$is_in_plan]));
  115. if($failed
  116. =!$success)
  117. throw new ErrorException('海柔任务失败:'.$exception);
  118. LogService::log('海柔请求','markBinProcessed1.3',
  119. $failed);
  120. // if($NotInPlan
  121. // =!$is_in_plan)
  122. // throw new ErrorException('海柔认为是计划外的料箱:'.$exception);
  123. LogService::log('海柔请求','markBinProcessed1.4',
  124. '$NotInPlan');
  125. $materialBox=
  126. $this->materialBoxService->get(['code'=>$binCode])->first();
  127. LogService::log('海柔请求','markBinProcessed1.5',
  128. json_encode($materialBox));
  129. $stationTaskMaterialBox
  130. =(function()use($materialBox){
  131. return $stationTaskMaterialBox=
  132. $this->stationTaskMaterialBoxService
  133. ->get(
  134. [
  135. 'material_box_id'=>$materialBox['id'],
  136. 'status'=>['处理中','待处理','异常','处理队列'],
  137. ]
  138. )->first();
  139. })();
  140. LogService::log('海柔请求','markBinProcessed1.6',
  141. json_encode($stationTaskMaterialBox));
  142. if(!$stationTaskMaterialBox){
  143. throw new ErrorException($binCode.'该料箱没有安排在处理队列中.');
  144. }
  145. LogService::log('海柔请求','markBinProcessed1.7',
  146. json_encode($stationTaskMaterialBox));
  147. DB::transaction(function ()use($stationTaskMaterialBox){
  148. $stationTaskMaterialBox_next=
  149. $this->stationTaskMaterialBoxService
  150. ->processNextQueued($stationTaskMaterialBox); //找到队列中下一个料箱,并标记为处理中
  151. $this->stationTaskCommoditiesService
  152. ->markProcessed($stationTaskMaterialBox['stationTaskCommodities']);
  153. LogService::log('海柔请求','markBinProcessed1.8',
  154. json_encode($stationTaskMaterialBox));
  155. if($stationTaskMaterialBox_next)
  156. $this->stationTaskCommoditiesService
  157. ->markProcessing($stationTaskMaterialBox_next['stationTaskCommodities']);//因为上边商品任务被标记完成了,所以这里要将队列中找出正在处理的料箱对应的标记为“处理中”
  158. $this->stationTaskMaterialBoxService
  159. ->markProcessed($stationTaskMaterialBox);
  160. $notProcessedBoxTasks = $this->stationTaskMaterialBoxService->getNotProcessedSiblings($stationTaskMaterialBox);
  161. if($notProcessedBoxTasks->isEmpty()){
  162. $this->instant($this->stationTaskService,'StationTaskService');
  163. LogService::log('海柔请求','markBinProcessed1.81',
  164. json_encode($stationTaskMaterialBox['stationTaskBatch']));
  165. $stationTaskMaterialBox->loadMissing('stationTaskBatch');
  166. $this->stationTaskBatchService->markProcessed($stationTaskMaterialBox['stationTaskBatch']);
  167. LogService::log('海柔请求','markBinProcessed1.82',
  168. json_encode($stationTaskMaterialBox['stationTaskBatch']));
  169. $this->stationTaskService->markProcessed($stationTaskMaterialBox['stationTask']);
  170. }
  171. $this->storeBox($stationTaskMaterialBox)
  172. ?true
  173. :(function(){throw new ErrorException('呼叫机器人回收U型线料箱失败');})();
  174. LogService::log('海柔请求','markBinProcessed1.9',
  175. json_encode($stationTaskMaterialBox));
  176. $this->stationService->broadcastBinMonitor($stationTaskMaterialBox['station_id'],$stationTaskMaterialBox['stationTask']);
  177. LogService::log('海柔请求','markBinProcessed1.99',
  178. json_encode($stationTaskMaterialBox));
  179. });
  180. return true;
  181. }catch (\Exception $e){
  182. $this->instant($this->stationTaskMaterialBoxService,'StationTaskMaterialBoxService');
  183. $stationTaskMaterialBox_toStore=
  184. $this->stationTaskMaterialBoxService->create([
  185. 'station_id' => $this->stationService->getStation_byType('立库')['id'],
  186. 'material_box_id' => $stationTaskMaterialBox['materialBox']['id'],
  187. 'status' => '处理中'
  188. ] );
  189. $dataToPost=$this->makeJson_move(
  190. collect([$stationTaskMaterialBox_toStore]),
  191. '输送线入立架',
  192. 'BIN-IN1',//TODO:这里应该是动态取得,参考出立架getULineExit()方法,不然不能从站获得对应的出口,而且要改Station的child为children
  193. '',
  194. $stationTaskMaterialBox['stationTaskBatch']['id']
  195. );
  196. $this->controlHaiRobot($dataToPost);
  197. $stationTaskMaterialBox = $stationTaskMaterialBox??$materialBox??null;
  198. if($stationTaskMaterialBox && get_class($stationTaskMaterialBox)==MaterialBox::class){
  199. $stationTaskMaterialBox = StationTaskMaterialBox::query()
  200. ->where('material_box_id',$stationTaskMaterialBox['id'])
  201. ->where('status','<>','完成')
  202. ->where('created_at','>',now()->format('Y-m-d'))
  203. ->first();
  204. }
  205. if($stationTaskMaterialBox)
  206. $this->stationTaskMaterialBoxService
  207. ->excepted($stationTaskMaterialBox);
  208. return $e->getMessage();
  209. }
  210. }
  211. public function storeBox(?StationTaskMaterialBox $stationTaskMaterialBox): bool
  212. {
  213. LogService::log('海柔请求','putBinToStore1',
  214. '');
  215. LogService::log('海柔请求','putBinToStore2',
  216. json_encode($stationTaskMaterialBox));
  217. $this->instant($this->stationService,'StationService');
  218. $this->instant($this->stationTaskMaterialBoxService,'StationTaskMaterialBoxService');
  219. $stationTaskMaterialBox_toStore=
  220. $this->stationTaskMaterialBoxService->create([
  221. 'station_id' => $this->stationService->getStation_byType('立库')['id'],
  222. 'material_box_id' => $stationTaskMaterialBox['materialBox']['id'],
  223. 'status' => '处理中'
  224. ] );
  225. $dataToPost=$this->makeJson_move(
  226. collect([$stationTaskMaterialBox_toStore]),
  227. '输送线入立架',
  228. 'BIN-IN1',//TODO:这里应该是动态取得,参考出立架getULineExit()方法,不然不能从站获得对应的出口,而且要改Station的child为children
  229. '',
  230. $stationTaskMaterialBox['stationTaskBatch']['id']
  231. );
  232. LogService::log('海柔请求','putBinToStore3',
  233. json_encode($dataToPost));
  234. $controlSuccess = $this->controlHaiRobot($dataToPost);
  235. if($controlSuccess){
  236. }
  237. return $controlSuccess;
  238. }
  239. /** 缓存架入立架 料箱 任务
  240. * @param StationTaskMaterialBox|null $stationTaskMaterialBox
  241. * @return bool
  242. * @throws ErrorException
  243. */
  244. public function putBinToStore_fromCacheShelf(?StationTaskMaterialBox $stationTaskMaterialBox): bool
  245. {
  246. LogService::log('海柔请求','putBinToStore_fromCacheShelf1', '');
  247. LogService::log('海柔请求','putBinToStore_fromCacheShelf2', json_encode($stationTaskMaterialBox));
  248. $this->instant($this->stationService,'StationService');
  249. // 缓存架格口
  250. $formLocation = StationCacheShelfGrid::getLocation($stationTaskMaterialBox['station'],$stationTaskMaterialBox['station']['grids']->first());
  251. /** 创建料箱 从缓存架 到 立架任务 */
  252. $dataToPost=$this->makeJson_move(
  253. collect([$stationTaskMaterialBox]),
  254. '缓存架入立架',
  255. $formLocation, //TODO:通过计算StationCacheShelfGrid 的 Grid_id 获取格口的编号
  256. ''
  257. );
  258. LogService::log('海柔请求','putBinToStore_fromCacheShelf3', json_encode($dataToPost));
  259. /** 控制海柔机器人执行任务 */
  260. $controlSuccess = $this->controlHaiRobot($dataToPost);
  261. if($controlSuccess){
  262. $this->instant($this->stationTaskMaterialBoxService,'StationTaskMaterialBoxService');
  263. $this->stationTaskMaterialBoxService->set($stationTaskMaterialBox,[
  264. 'id' => $stationTaskMaterialBox['id'],
  265. 'status' => $stationTaskMaterialBox['status']='处理中',
  266. 'station_id' => $stationTaskMaterialBox['station']['id']?? '',
  267. ]);
  268. }
  269. return $controlSuccess;
  270. }
  271. public function taskUpdate(
  272. // $groupCode,
  273. $stationTaskMaterialBox_id, //实际对应传入的字段 taskCode, 这里用料箱任务号做taskCode
  274. $updateEventType, //0:task_begin(取货)1:task_end(放货)
  275. $status, //0:任务成功1:任务失败
  276. $binCode
  277. ):bool{
  278. LogService::log('海柔请求','taskUpdateIn',
  279. json_encode([
  280. $stationTaskMaterialBox_id,
  281. $updateEventType,
  282. $status,
  283. $binCode
  284. ]));
  285. $this->instant($this->stationTaskMaterialBoxService,'StationTaskMaterialBoxService');
  286. try{
  287. if(($failed
  288. =$status)==1){
  289. throw new ErrorException('海柔任务失败');
  290. }
  291. if($料箱不匹配=
  292. !$stationTaskMaterialBox
  293. =(function()use($stationTaskMaterialBox_id,$binCode){
  294. $stationTaskMaterialBox=StationTaskMaterialBox::query()->find($id=$stationTaskMaterialBox_id);
  295. if($stationTaskMaterialBox['materialBox']['code']==$binCode)return $stationTaskMaterialBox;
  296. return null;
  297. })()){
  298. throw new ErrorException('发回的料箱和任务号(ID)不匹配:$stationTaskMaterialBox_id:'
  299. .$stationTaskMaterialBox_id.' $binCode:'.$binCode. ' '.
  300. StationTaskMaterialBox::query()
  301. ->where('id', $id=$stationTaskMaterialBox_id)
  302. ->get()
  303. ->toJson());
  304. }
  305. if(($标记已放置=
  306. function()use($updateEventType,$stationTaskMaterialBox){
  307. if(($isPut
  308. =$updateEventType)==1){
  309. $this->stationTaskMaterialBoxService->markHasPut($stationTaskMaterialBox);
  310. return true;
  311. }return false;
  312. })())
  313. return true;
  314. ($标记已取出=
  315. function()use($updateEventType,$stationTaskMaterialBox){
  316. if(($isGet
  317. =$updateEventType)==0){
  318. $this->stationTaskMaterialBoxService->markHasTaken($stationTaskMaterialBox);
  319. }
  320. })();
  321. }catch (\Exception $e){
  322. $this->excepted($stationTaskMaterialBox_id, $binCode, $e->getMessage());
  323. return false;
  324. }
  325. return true;
  326. }
  327. // public function markHasPut($taskCode,$binCode):bool{
  328. // try{
  329. // //标记料箱进入位置
  330. //// $taskMaterialBoxesService->markDone();//
  331. // }catch (\Exception $e){
  332. // switch ($e->getCode()){
  333. // case 'taskBinNotMatch';
  334. // case 'taskGetFailed';
  335. // }
  336. // }
  337. //
  338. // }
  339. public function excepted($taskCode='',$binCode='', $msg=''):bool{
  340. try{
  341. throw new ErrorException(
  342. "taskCode任务号:$taskCode , binCode箱号:$binCode 海柔运行报错: $msg"
  343. );
  344. }catch (\Exception $e){
  345. return true;
  346. }
  347. }
  348. /**
  349. * @param array $dataToPost
  350. * @return bool
  351. */
  352. public function controlHaiRobot(array $dataToPost): bool
  353. {
  354. LogService::log('海柔请求','runMany','波次任务分配6.r5f2c1:'.json_encode($dataToPost));
  355. try{
  356. LogService::log('海柔请求','runMany','波次任务分配6.r5f2c1.51:');
  357. $a = json_encode($dataToPost);
  358. $response = Http::post(config('api.haiq.storage.moveBin'), $dataToPost);
  359. if(isset($response->json()['code'])&&$response->json()['code']==500)
  360. throw new ErrorException('机器人500错误:'.json_encode($response->json()));
  361. $b=json_encode($response->json());
  362. LogService::log('海柔请求','runMany','波次任务分配6.r5f2c1.52:');
  363. LogService::log(__METHOD__,'runMany','波次任务分配6.r5f2c1.53:'.json_encode($response->json()));
  364. }catch (\Exception $e){
  365. LogService::log('海柔请求','runMany','波次任务分配6.r5f2c1.54:'.json_encode($dataToPost).$e->getMessage());
  366. throw new ErrorException('海柔机器人任务执行失败:'.json_encode($dataToPost).$e->getMessage());
  367. }
  368. LogService::log('海柔请求','runMany','波次任务分配6.r5f2c2:'.json_encode($dataToPost));
  369. $errMsg = (function () use ($response) {
  370. if ($response->ok()) return '';
  371. $errMsg = '错误: ';
  372. if (!$response) {
  373. return $errMsg . '没有返回内容,检查连接或目标服务器';
  374. }
  375. switch (((string)$response["code"])[0]) {
  376. case 5:
  377. $errMsg .= '目标服务器代码错误,请联系对方';
  378. break;
  379. case 4:
  380. $errMsg .= '权限不足以请求资源,请检查对方服务器规范';
  381. break;
  382. default:
  383. $errMsg .= '出现未知请求错误';
  384. break;
  385. }
  386. $responseDetails = ' code:' . $response["code"]
  387. . ' header:' . $response->body()
  388. . ' response:' . json_encode($response->headers());
  389. return $errMsg . $responseDetails;
  390. })();
  391. LogService::log('海柔请求','runMany','波次任务分配6.r5f2c3:'.json_encode($errMsg));
  392. LogService::log(__METHOD__, __FUNCTION__,
  393. $errMsg ?? ''
  394. . '请求:' . json_encode($dataToPost)
  395. . '调用堆栈c:' . json_encode(array_slice(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS), 0, 3))
  396. );
  397. return $isSuccess = !$errMsg;
  398. }
  399. }