ForeignHaiRoboticsService.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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. $this->instant($this->materialBoxService,'MaterialBoxService');
  184. $box=$this->materialBoxService->firstOrCreate(['code'=>$binCode]);
  185. $stationTaskMaterialBox_toStore=
  186. $this->stationTaskMaterialBoxService->create([
  187. 'station_id' => $this->stationService->getStation_byType('立库')['id'],
  188. 'material_box_id' => $box['id'],
  189. 'status' => '处理中'
  190. ] );
  191. $dataToPost=$this->makeJson_move(
  192. collect([$stationTaskMaterialBox_toStore]),
  193. '输送线入立架',
  194. 'BIN-IN1',//TODO:这里应该是动态取得,参考出立架getULineExit()方法,不然不能从站获得对应的出口,而且要改Station的child为children
  195. '',
  196. $stationTaskMaterialBox['stationTaskBatch']['id']
  197. );
  198. $this->controlHaiRobot($dataToPost);
  199. $stationTaskMaterialBox = $stationTaskMaterialBox??$materialBox??null;
  200. if($stationTaskMaterialBox && get_class($stationTaskMaterialBox)==MaterialBox::class){
  201. $stationTaskMaterialBox = StationTaskMaterialBox::query()
  202. ->where('material_box_id',$stationTaskMaterialBox['id'])
  203. ->where('status','<>','完成')
  204. ->where('created_at','>',now()->format('Y-m-d'))
  205. ->first();
  206. }
  207. if($stationTaskMaterialBox)
  208. $this->stationTaskMaterialBoxService
  209. ->excepted($stationTaskMaterialBox);
  210. return $e->getMessage();
  211. }
  212. }
  213. public function storeBox(?StationTaskMaterialBox $stationTaskMaterialBox): bool
  214. {
  215. LogService::log('海柔请求','putBinToStore1',
  216. '');
  217. $this->instant($this->stationService,'StationService');
  218. $this->instant($this->stationTaskMaterialBoxService,'StationTaskMaterialBoxService');
  219. $stationTaskMaterialBox_toStore=
  220. $this->stationTaskMaterialBoxService->firstOrCreate([
  221. 'station_id' => $this->stationService->getStation_byType('立库')['id'],
  222. 'material_box_id' => $stationTaskMaterialBox['materialBox']['id'],
  223. 'status' => '处理中',
  224. 'type' => '放',
  225. ]);
  226. LogService::log('海柔请求','putBinToStore2',
  227. json_encode($stationTaskMaterialBox));
  228. $dataToPost=$this->makeJson_move(
  229. collect([$stationTaskMaterialBox_toStore]),
  230. '输送线入立架',
  231. 'BIN-IN1',//TODO:这里应该是动态取得,参考出立架getULineExit()方法,不然不能从站获得对应的出口,而且要改Station的child为children
  232. '',
  233. $stationTaskMaterialBox['stationTaskBatch']['id']
  234. );
  235. LogService::log('海柔请求','putBinToStore3',
  236. json_encode($dataToPost));
  237. $controlSuccess = $this->controlHaiRobot($dataToPost);
  238. if($controlSuccess){
  239. }
  240. return $controlSuccess;
  241. }
  242. /** 缓存架入立架 料箱 任务
  243. * @param StationTaskMaterialBox|null $stationTaskMaterialBox
  244. * @return bool
  245. * @throws ErrorException
  246. */
  247. public function putBinToStore_fromCacheShelf(?StationTaskMaterialBox $stationTaskMaterialBox): bool
  248. {
  249. LogService::log('海柔请求','putBinToStore_fromCacheShelf1', '');
  250. LogService::log('海柔请求','putBinToStore_fromCacheShelf2', json_encode($stationTaskMaterialBox));
  251. $this->instant($this->stationService,'StationService');
  252. // 缓存架格口
  253. $formLocation = StationCacheShelfGrid::getLocation($stationTaskMaterialBox['station'],$stationTaskMaterialBox['station']['grids']->first());
  254. /** 创建料箱 从缓存架 到 立架任务 */
  255. $dataToPost=$this->makeJson_move(
  256. collect([$stationTaskMaterialBox]),
  257. '缓存架入立架',
  258. $formLocation, //TODO:通过计算StationCacheShelfGrid 的 Grid_id 获取格口的编号
  259. ''
  260. );
  261. LogService::log('海柔请求','putBinToStore_fromCacheShelf3', json_encode($dataToPost));
  262. /** 控制海柔机器人执行任务 */
  263. $controlSuccess = $this->controlHaiRobot($dataToPost);
  264. if($controlSuccess){
  265. $this->instant($this->stationTaskMaterialBoxService,'StationTaskMaterialBoxService');
  266. $this->stationTaskMaterialBoxService->set($stationTaskMaterialBox,[
  267. 'id' => $stationTaskMaterialBox['id'],
  268. 'status' => $stationTaskMaterialBox['status']='处理中',
  269. 'station_id' => $stationTaskMaterialBox['station']['id']?? '',
  270. ]);
  271. }
  272. return $controlSuccess;
  273. }
  274. public function taskUpdate(
  275. // $groupCode,
  276. $stationTaskMaterialBox_id, //实际对应传入的字段 taskCode, 这里用料箱任务号做taskCode
  277. $updateEventType, //0:task_begin(取货)1:task_end(放货)
  278. $status, //0:任务成功1:任务失败
  279. $binCode
  280. ):bool{
  281. LogService::log('海柔请求','taskUpdateIn',
  282. json_encode([
  283. $stationTaskMaterialBox_id,
  284. $updateEventType,
  285. $status,
  286. $binCode
  287. ]));
  288. $this->instant($this->stationTaskMaterialBoxService,'StationTaskMaterialBoxService');
  289. try{
  290. if(($failed
  291. =$status)==1){
  292. throw new ErrorException('海柔任务失败');
  293. }
  294. if($料箱不匹配=
  295. !$stationTaskMaterialBox
  296. =(function()use($stationTaskMaterialBox_id,$binCode){
  297. $stationTaskMaterialBox=StationTaskMaterialBox::query()->find($id=$stationTaskMaterialBox_id);
  298. if($stationTaskMaterialBox['materialBox']['code']==$binCode)return $stationTaskMaterialBox;
  299. return null;
  300. })()){
  301. throw new ErrorException('发回的料箱和任务号(ID)不匹配:$stationTaskMaterialBox_id:'
  302. .$stationTaskMaterialBox_id.' $binCode:'.$binCode. ' '.
  303. StationTaskMaterialBox::query()
  304. ->where('id', $id=$stationTaskMaterialBox_id)
  305. ->get()
  306. ->toJson());
  307. }
  308. if(($标记已放置=
  309. function()use($updateEventType,$stationTaskMaterialBox){
  310. if(($isPut
  311. =$updateEventType)==1){
  312. $this->stationTaskMaterialBoxService->markHasPut($stationTaskMaterialBox);
  313. return true;
  314. }return false;
  315. })())
  316. return true;
  317. ($标记已取出=
  318. function()use($updateEventType,$stationTaskMaterialBox){
  319. if(($isGet
  320. =$updateEventType)==0){
  321. $this->stationTaskMaterialBoxService->markHasTaken($stationTaskMaterialBox);
  322. }
  323. })();
  324. }catch (\Exception $e){
  325. $this->excepted($stationTaskMaterialBox_id, $binCode, $e->getMessage());
  326. return false;
  327. }
  328. return true;
  329. }
  330. // public function markHasPut($taskCode,$binCode):bool{
  331. // try{
  332. // //标记料箱进入位置
  333. //// $taskMaterialBoxesService->markDone();//
  334. // }catch (\Exception $e){
  335. // switch ($e->getCode()){
  336. // case 'taskBinNotMatch';
  337. // case 'taskGetFailed';
  338. // }
  339. // }
  340. //
  341. // }
  342. public function excepted($taskCode='',$binCode='', $msg=''):bool{
  343. try{
  344. throw new ErrorException(
  345. "taskCode任务号:$taskCode , binCode箱号:$binCode 海柔运行报错: $msg"
  346. );
  347. }catch (\Exception $e){
  348. return true;
  349. }
  350. }
  351. /**
  352. * @param array $dataToPost
  353. * @return bool
  354. */
  355. public function controlHaiRobot(array $dataToPost): bool
  356. {
  357. LogService::log('海柔请求','runMany','波次任务分配6.r5f2c1:'.json_encode($dataToPost));
  358. try{
  359. LogService::log('海柔请求','runMany','波次任务分配6.r5f2c1.51:');
  360. $response = Http::post(config('api.haiq.storage.moveBin'), $dataToPost);
  361. if(isset($response->json()['code'])&&$response->json()['code']==500)
  362. throw new ErrorException('机器人500错误:'.json_encode($response->json()));
  363. LogService::log('海柔请求','runMany','波次任务分配6.r5f2c1.52:');
  364. LogService::log(__METHOD__,'runMany','波次任务分配6.r5f2c1.53:'.json_encode($response->json()));
  365. }catch (\Exception $e){
  366. LogService::log('海柔请求','runMany','波次任务分配6.r5f2c1.54:'.json_encode($dataToPost).$e->getMessage());
  367. throw new ErrorException('海柔机器人任务执行失败:'.json_encode($dataToPost).$e->getMessage());
  368. }
  369. LogService::log('海柔请求','runMany','波次任务分配6.r5f2c2:'.json_encode($dataToPost));
  370. $errMsg = (function () use ($response) {
  371. if ($response->ok()) return '';
  372. $errMsg = '错误: ';
  373. if (!$response) {
  374. return $errMsg . '没有返回内容,检查连接或目标服务器';
  375. }
  376. switch (((string)$response["code"])[0]) {
  377. case 5:
  378. $errMsg .= '目标服务器代码错误,请联系对方';
  379. break;
  380. case 4:
  381. $errMsg .= '权限不足以请求资源,请检查对方服务器规范';
  382. break;
  383. default:
  384. $errMsg .= '出现未知请求错误';
  385. break;
  386. }
  387. $responseDetails = ' code:' . $response["code"]
  388. . ' header:' . $response->body()
  389. . ' response:' . json_encode($response->headers());
  390. return $errMsg . $responseDetails;
  391. })();
  392. LogService::log('海柔请求','runMany','波次任务分配6.r5f2c3:'.json_encode($errMsg));
  393. LogService::log(__METHOD__, __FUNCTION__,
  394. $errMsg ?? ''
  395. . '请求:' . json_encode($dataToPost)
  396. . '调用堆栈c:' . json_encode(array_slice(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS), 0, 3))
  397. );
  398. return $isSuccess = !$errMsg;
  399. }
  400. }