ForeignHaiRoboticsService.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. <?php
  2. namespace App\Services;
  3. use App\Components\ErrorPush;
  4. use App\Exceptions\ErrorException;
  5. use App\Exceptions\Exception;
  6. use App\Jobs\CacheShelfTaskJob;
  7. use App\MaterialBox;
  8. use App\Station;
  9. use App\StationTask;
  10. use App\StationTaskMaterialBox;
  11. use Carbon\Carbon;
  12. use Illuminate\Support\Collection;
  13. use Illuminate\Support\Facades\Cache;
  14. use Illuminate\Support\Facades\DB;
  15. use Illuminate\Support\Facades\Http;
  16. use App\Traits\ServiceAppAop;
  17. class ForeignHaiRoboticsService
  18. {
  19. use ServiceAppAop,ErrorPush;
  20. /** @var $stationTaskMaterialBoxService StationTaskMaterialBoxService */
  21. private $stationTaskMaterialBoxService;
  22. /** @var $stationTaskBatchService StationTaskBatchService */
  23. private $stationTaskBatchService;
  24. /** @var $stationTaskCommoditiesService StationTaskCommodityService */
  25. private $stationTaskCommoditiesService;
  26. /** @var $materialBoxService MaterialBoxService */
  27. private $materialBoxService;
  28. /** @var $stationTaskService StationTaskService */
  29. private $stationTaskService;
  30. /** @var $stationService StationService */
  31. private $stationService;
  32. public function __construct()
  33. {
  34. $this->stationTaskMaterialBoxService=null;
  35. $this->materialBoxService=null;
  36. $this->stationService=null;
  37. }
  38. /**
  39. * @param string $modeName '输送线入立架'|'立架出至输送线'|'移动立架内位置'|'缓存架入立架'|'立架出至缓存架'
  40. * @param string $fromLocation
  41. * @param string $toLocation
  42. * @param Collection $taskMaterialBoxes
  43. * @param string $groupId
  44. * @param int $priority
  45. * @param int $isSequenced
  46. * @return array
  47. */
  48. private function makeJson_move(
  49. Collection $taskMaterialBoxes,
  50. string $modeName,
  51. string $fromLocation='',
  52. string $toLocation='',
  53. $groupId=''
  54. , $priority=10
  55. , $isSequenced=1
  56. ): array
  57. {
  58. $timestampSuffix = microtime(true);
  59. $taskMode=$this->getTaskMode($modeName);
  60. $bins=$taskMaterialBoxes->map(function (StationTaskMaterialBox $taskMaterialBox)use($timestampSuffix,$fromLocation,$toLocation){
  61. return [
  62. "taskCode" =>$taskMaterialBox['id'].'_'.$timestampSuffix,
  63. "binCode" => $taskMaterialBox['materialBox']['code'],
  64. "fromLocCode" => $fromLocation??'',
  65. "toLocCode" => $toLocation??'',
  66. ];
  67. });
  68. return [[
  69. "taskMode" =>$taskMode,
  70. "bins"=>$bins,
  71. "groupCode"=>$groupId.'_'.$timestampSuffix,
  72. "priority"=>$priority,
  73. "sequenceFlag"=>$isSequenced,
  74. ]];
  75. }
  76. public function makeJson_move_multi(
  77. Collection $taskMaterialBoxes,
  78. string $modeName,
  79. Collection $fromLocation=null,
  80. Collection $toLocations=null,
  81. $groupId=''
  82. , $priority=10
  83. , $isSequenced=1
  84. ): array
  85. {
  86. if((!$toLocations||($toLocations->count()!=$taskMaterialBoxes->count())) && (!$fromLocation || ($fromLocation->count()!=$taskMaterialBoxes->count())))throw new Exception('元素数量必须和料箱任务不一致');
  87. $timestampSuffix = microtime(true);
  88. $taskMode=$this->getTaskMode($modeName);
  89. $bins=$taskMaterialBoxes->map(function (StationTaskMaterialBox $taskMaterialBox,$i)use($timestampSuffix,$fromLocation,$toLocations){
  90. return [
  91. "taskCode" =>$taskMaterialBox['id'].'_'.$timestampSuffix,
  92. "binCode" => $taskMaterialBox['materialBox']['code'],
  93. "fromLocCode" => $fromLocation ? $fromLocation[$i] : '',
  94. "toLocCode" => $toLocations ? $toLocations[$i] : '',
  95. ];
  96. });
  97. return [[
  98. "taskMode" =>$taskMode,
  99. "bins"=>$bins,
  100. "groupCode"=>$groupId.'_'.$timestampSuffix,
  101. "priority"=>$priority,
  102. "sequenceFlag"=>$isSequenced,
  103. ]];
  104. }
  105. private function getTaskMode($modeName){
  106. switch ($modeName){
  107. case '输送线入立架': return 1;
  108. case '立架出至输送线': return 2;
  109. case '移动立架内位置': return 3;
  110. case '立架出至缓存架':
  111. case '缓存架入立架':return 6;
  112. default: throw new \Exception('发至海柔的移料箱请求,模式不存在');
  113. }
  114. }
  115. public function fetchGroup($toLocation, Collection $taskMaterialBoxes, $groupIdPrefix='',$mode='立架出至输送线'): bool
  116. {
  117. $dataToPost=$this->makeJson_move(
  118. $taskMaterialBoxes,
  119. $mode,
  120. '',
  121. $toLocation??'',
  122. $groupIdPrefix
  123. );
  124. return $this->controlHaiRobot($dataToPost,$taskMaterialBoxes,$mode);
  125. }
  126. /**
  127. * @param Collection $toLocations //库位和料箱任务一一对应,一个库位对应一个料箱
  128. * @param Collection $taskMaterialBoxes
  129. * @param string $groupIdPrefix
  130. * @param string $mode
  131. * @return bool
  132. * @throws ErrorException|Exception
  133. */
  134. public function fetchGroup_multiLocation(Collection $toLocations, Collection $taskMaterialBoxes, $groupIdPrefix='', $mode='立架出至输送线', int $priority = 10): bool
  135. {
  136. $dataToPost=$this->makeJson_move_multi(
  137. $taskMaterialBoxes,
  138. $mode,
  139. null,
  140. $toLocations,
  141. $groupIdPrefix,
  142. $priority
  143. );
  144. return $this->controlHaiRobot($dataToPost,$taskMaterialBoxes,$mode);
  145. }
  146. public function markBinProcessed(
  147. $workStation,
  148. $binCode,
  149. $success,
  150. $created_at,
  151. $exception,
  152. $is_in_plan
  153. ): bool
  154. {
  155. LogService::log('海柔请求','markBinProcessed1.1',
  156. $binCode.'|'.$success.'|'.$exception.'|'.$is_in_plan);
  157. $this->instant($this->stationService,'StationService');
  158. $this->instant($this->materialBoxService,'MaterialBoxService');
  159. $this->instant($this->stationTaskMaterialBoxService,'StationTaskMaterialBoxService');
  160. $this->instant($this->stationTaskCommoditiesService,'StationTaskCommodityService');
  161. $this->instant($this->stationTaskBatchService,'StationTaskBatchService');
  162. try{
  163. LogService::log('海柔请求','markBinProcessed1.2',
  164. json_encode([$binCode,$success,$exception,$is_in_plan]));
  165. if($failed
  166. =!$success)
  167. throw new ErrorException('海柔任务失败:'.$exception);
  168. LogService::log('海柔请求','markBinProcessed1.3',
  169. $failed);
  170. $materialBox=
  171. $this->materialBoxService->get(['code'=>$binCode])->first();
  172. /** @var StationTaskMaterialBox $stationTaskMaterialBox */
  173. $stationTaskMaterialBox
  174. =(function()use($materialBox){
  175. return $stationTaskMaterialBox=
  176. StationTaskMaterialBox::query()
  177. ->where('material_box_id',$materialBox['id'])
  178. ->where('created_at','>',Carbon::now()->subDay())
  179. ->whereIn('status',['处理中','待处理','异常','处理队列'])
  180. ->orderBy('id','desc')
  181. ->first();
  182. })();
  183. if(!$stationTaskMaterialBox){
  184. throw new ErrorException($binCode.'该料箱没有安排在处理队列中.');
  185. }
  186. DB::transaction(function ()use($stationTaskMaterialBox,$binCode){
  187. $stationTaskMaterialBox_next=
  188. $this->stationTaskMaterialBoxService
  189. ->processNextQueued($stationTaskMaterialBox); //找到队列中下一个料箱,并标记为处理中
  190. $this->stationTaskCommoditiesService
  191. ->markProcessed($stationTaskMaterialBox['stationTaskCommodities']);
  192. LogService::log('海柔请求','markBinProcessed1.8',
  193. json_encode($stationTaskMaterialBox).'|'.$binCode);
  194. if($stationTaskMaterialBox_next)
  195. $this->stationTaskCommoditiesService
  196. ->markProcessing($stationTaskMaterialBox_next['stationTaskCommodities']);//因为上边商品任务被标记完成了,所以这里要将队列中找出正在处理的料箱对应的标记为“处理中”
  197. $this->stationTaskMaterialBoxService
  198. ->markProcessed($stationTaskMaterialBox);
  199. $notProcessedBoxTasks = $this->stationTaskMaterialBoxService->getNotProcessedSiblings($stationTaskMaterialBox);
  200. if($notProcessedBoxTasks->isEmpty()){
  201. $this->instant($this->stationTaskService,'StationTaskService');
  202. LogService::log('海柔请求','markBinProcessed1.81',
  203. json_encode($stationTaskMaterialBox['stationTaskBatch']).'|'.$binCode);
  204. $stationTaskMaterialBox->loadMissing('stationTaskBatch');
  205. $this->stationTaskBatchService->markProcessed($stationTaskMaterialBox['stationTaskBatch']);
  206. $this->stationTaskService->markProcessed($stationTaskMaterialBox['stationTask']);
  207. }
  208. $this->storeBox($stationTaskMaterialBox)
  209. ?true
  210. :(function(){throw new ErrorException('呼叫机器人回收U型线料箱失败');})();
  211. LogService::log('海柔请求','markBinProcessed1.9',
  212. json_encode($stationTaskMaterialBox).'|'.$binCode);
  213. $this->stationService->broadcastBinMonitor($stationTaskMaterialBox['station_id'],$stationTaskMaterialBox['stationTask']);
  214. LogService::log('海柔请求','markBinProcessed1.99',
  215. json_encode($stationTaskMaterialBox).'|'.$binCode);
  216. });
  217. return true;
  218. }catch (\Exception $e){
  219. LogService::log('海柔请求','markBinProcessed E1',
  220. $binCode);
  221. $this->instant($this->stationTaskMaterialBoxService,'StationTaskMaterialBoxService');
  222. $this->instant($this->materialBoxService,'MaterialBoxService');
  223. $box=$this->materialBoxService->firstOrCreate(['code'=>$binCode]);
  224. $stationTaskMaterialBox_toStore=
  225. $this->stationTaskMaterialBoxService->create([
  226. 'station_id' => $this->stationService->getStation_byType('立库')['id'],
  227. 'material_box_id' => $box['id'],
  228. 'status' => '处理中'
  229. ] );
  230. $dataToPost=$this->makeJson_move(
  231. collect([$stationTaskMaterialBox_toStore]),
  232. '输送线入立架',
  233. 'BIN-IN1',//TODO:这里应该是动态取得,参考出立架getULineExit()方法,不然不能从站获得对应的出口,而且要改Station的child为children
  234. '',
  235. $stationTaskMaterialBox_toStore['stationTaskBatch']['id']
  236. );
  237. $this->controlHaiRobot($dataToPost,collect([$stationTaskMaterialBox_toStore]),'输送线入立架');
  238. LogService::log('海柔请求','markBinProcessed E2',
  239. $binCode);
  240. $stationTaskMaterialBox = $stationTaskMaterialBox_toStore??$materialBox??null;
  241. if($stationTaskMaterialBox && get_class($stationTaskMaterialBox)==MaterialBox::class){
  242. $stationTaskMaterialBox = StationTaskMaterialBox::query()
  243. ->where('material_box_id',$stationTaskMaterialBox['id'])
  244. ->where('status','<>','完成')
  245. ->where('created_at','>',now()->format('Y-m-d'))
  246. ->first();
  247. }
  248. if($stationTaskMaterialBox)
  249. $this->stationTaskMaterialBoxService
  250. ->excepted($stationTaskMaterialBox);
  251. return $e->getMessage();
  252. }
  253. }
  254. public function storeBox(?StationTaskMaterialBox $stationTaskMaterialBox): bool
  255. {
  256. LogService::log('海柔请求','putBinToStore1',
  257. '');
  258. $this->instant($this->stationService,'StationService');
  259. $this->instant($this->stationTaskMaterialBoxService,'StationTaskMaterialBoxService');
  260. $stationTaskMaterialBox_toStore=
  261. $this->stationTaskMaterialBoxService->firstOrCreate([
  262. 'station_id' => $this->stationService->getStation_byType('立库')['id'],
  263. 'material_box_id' => $stationTaskMaterialBox['materialBox']['id'],
  264. 'status' => '处理中',
  265. 'type' => '放',
  266. ]);
  267. LogService::log('海柔请求','putBinToStore2',
  268. json_encode($stationTaskMaterialBox));
  269. $dataToPost=$this->makeJson_move(
  270. collect([$stationTaskMaterialBox_toStore]),
  271. '输送线入立架',
  272. 'BIN-IN1',//TODO:这里应该是动态取得,参考出立架getULineExit()方法,不然不能从站获得对应的出口,而且要改Station的child为children
  273. '',
  274. $stationTaskMaterialBox['stationTaskBatch']['id']
  275. );
  276. LogService::log('海柔请求','putBinToStore3',
  277. json_encode($dataToPost));
  278. $controlSuccess = $this->controlHaiRobot($dataToPost,collect([$stationTaskMaterialBox_toStore]),'输送线入立架');
  279. return $controlSuccess;
  280. }
  281. /** 缓存架入立架 料箱 任务
  282. * @param StationTaskMaterialBox|null $stationTaskMaterialBox
  283. * @param Station|\stdClass|null $station
  284. * @return bool
  285. * @throws ErrorException
  286. */
  287. public function putBinToStore_fromCacheShelf(?StationTaskMaterialBox $stationTaskMaterialBox,
  288. $station): bool
  289. {
  290. $formLocation = $station->code;
  291. if ($station && $station->parent_id){
  292. //缓存标记 推入延时队列 等待三秒决定是否执行
  293. $key = "cacheShelfTask_".$station->parent_id;
  294. if (Cache::has($key)){
  295. list($task,$location) = Cache::get($key);
  296. $task->add($stationTaskMaterialBox);
  297. $location->add($formLocation);
  298. }else{
  299. $task = collect([$stationTaskMaterialBox]);
  300. $location = collect([$formLocation]);
  301. }
  302. Cache::forever($key,array($task,$location));
  303. CacheShelfTaskJob::dispatch($key,$task->count())->delay(now()->addSeconds(config("haiRou.cacheShelf.callAwait")));
  304. return true;
  305. }
  306. $dataToPost=$this->makeJson_move(collect([$stationTaskMaterialBox]), '缓存架入立架', $formLocation, '');
  307. $controlSuccess = $this->controlHaiRobot($dataToPost,collect([$stationTaskMaterialBox]),'缓存架入立架');
  308. if($controlSuccess){
  309. $this->instant($this->stationTaskMaterialBoxService,'StationTaskMaterialBoxService');
  310. $this->stationTaskMaterialBoxService->set($stationTaskMaterialBox,['status' => '处理中']);
  311. }
  312. return $controlSuccess;
  313. }
  314. /**
  315. * 任务变更时的动作
  316. *
  317. * @param $stationTaskMaterialBox_id
  318. * @param $updateEventType
  319. * @param $status
  320. * @param $binCode
  321. * @return bool
  322. */
  323. public function taskUpdate(
  324. $stationTaskMaterialBox_id, //实际对应传入的字段 taskCode, 这里用料箱任务号做taskCode
  325. $updateEventType, //0:task_begin(取货)1:task_end(放货)
  326. $status, //0:任务成功1:任务失败
  327. $binCode
  328. ):bool{
  329. $this->instant($this->stationTaskMaterialBoxService,'StationTaskMaterialBoxService');
  330. //获取下达任务
  331. /** @var StationTaskMaterialBox|\stdClass $stationTaskMaterialBox */
  332. $stationTaskMaterialBox = $stationTaskMaterialBox_id ? StationTaskMaterialBox::query()->with("materialBox:id,code")
  333. ->find($stationTaskMaterialBox_id) : null;
  334. if (!$stationTaskMaterialBox || !$stationTaskMaterialBox->materialBox){
  335. $this->push(__METHOD__."->".__LINE__,"海柔任务不存在",json_encode(request()->input()));
  336. return false;
  337. }
  338. if ($status==1){ //海柔失败
  339. $this->push(__METHOD__."->".__LINE__,"海柔任务异常",json_encode(request()->input()));
  340. $stationTaskMaterialBox->update(['status'=>"异常"]);
  341. return false;
  342. }
  343. if ($stationTaskMaterialBox->materialBox->code != $binCode){
  344. $this->push(__METHOD__."->".__LINE__,"海柔任务料箱号不匹配",json_encode(request()->input()));
  345. return false;
  346. }
  347. try {
  348. switch ($updateEventType){
  349. case 0://已取出
  350. $this->stationTaskMaterialBoxService->markHasTaken($stationTaskMaterialBox);
  351. break;
  352. case 1://已放置
  353. $this->stationTaskMaterialBoxService->markHasPut($stationTaskMaterialBox);
  354. break;
  355. default:
  356. throw new \Exception("任务进行状态错误,未捕获");
  357. }
  358. }catch (\Exception $err){
  359. $this->push(__METHOD__."->".__LINE__,"海柔任务通知失败",json_encode(request()->input())." | ".$err->getMessage());
  360. return false;
  361. }
  362. return true;
  363. }
  364. public function excepted($taskCode='',$binCode='', $msg=''):bool{
  365. try{
  366. throw new ErrorException(
  367. "taskCode任务号:$taskCode , binCode箱号:$binCode 海柔运行报错: $msg"
  368. );
  369. }catch (\Exception $e){
  370. return true;
  371. }
  372. }
  373. /**
  374. * @param array $dataToPost
  375. * @return bool
  376. */
  377. public function controlHaiRobot(array $dataToPost,Collection $taskMaterialBoxes,$modeName): bool
  378. {
  379. LogService::log('海柔请求','runMany','波次任务分配6.r5f2c1:'.json_encode($dataToPost));
  380. try{
  381. LogService::log('海柔请求','runMany','波次任务分配6.r5f2c1.51:');
  382. $response = Http::post(config('api.haiq.storage.moveBin'), $dataToPost);
  383. if(isset($response->json()['code'])&&$response->json()['code']==500)
  384. throw new ErrorException('机器人500错误:'.json_encode($response->json()));
  385. LogService::log('海柔请求','runMany','波次任务分配6.r5f2c1.52:');
  386. LogService::log(__METHOD__,'runMany','波次任务分配6.r5f2c1.53:'.json_encode($response->json()));
  387. }catch (\Exception $e){
  388. LogService::log('海柔请求','runMany','波次任务分配6.r5f2c1.54:'.json_encode($dataToPost).$e->getMessage());
  389. throw new ErrorException('海柔机器人任务执行失败:'.json_encode($dataToPost).$e->getMessage());
  390. }
  391. LogService::log('海柔请求','runMany','波次任务分配6.r5f2c2:'.json_encode($dataToPost));
  392. $errMsg = (function () use ($response) {
  393. if ($response->ok()) return '';
  394. $errMsg = '错误: ';
  395. if (!$response) {
  396. return $errMsg . '没有返回内容,检查连接或目标服务器';
  397. }
  398. switch (((string)$response["code"])[0]) {
  399. case 5:
  400. $errMsg .= '目标服务器代码错误,请联系对方';
  401. break;
  402. case 4:
  403. $errMsg .= '权限不足以请求资源,请检查对方服务器规范';
  404. break;
  405. default:
  406. $errMsg .= '出现未知请求错误';
  407. break;
  408. }
  409. $responseDetails = ' code:' . $response["code"]
  410. . ' header:' . $response->body()
  411. . ' response:' . json_encode($response->headers());
  412. return $errMsg . $responseDetails;
  413. })();
  414. LogService::log('海柔请求','runMany','波次任务分配6.r5f2c3:'.json_encode($errMsg));
  415. LogService::log(__METHOD__, __FUNCTION__,
  416. $errMsg ?? ''
  417. . '请求:' . json_encode($dataToPost)
  418. . '调用堆栈c:' . json_encode(array_slice(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS), 0, 3))
  419. );
  420. $isSuccess = !$errMsg;
  421. $标记料箱状态=(function() use ($taskMaterialBoxes,$modeName){
  422. foreach ($taskMaterialBoxes as $taskMaterialBox){
  423. switch ($modeName){
  424. case '缓存架入立架':
  425. case '输送线入立架':
  426. case '移动立架内位置':
  427. $taskMaterialBox->materialBox['status']='在入库中';break;
  428. case '立架出至输送线':
  429. case '立架出至缓存架':
  430. $taskMaterialBox->materialBox['status']='在出库中';break;
  431. default:
  432. $taskMaterialBox->materialBox['status']='未知';break;
  433. }
  434. $taskMaterialBox->materialBox->update();
  435. }
  436. })();
  437. return $isSuccess;
  438. }
  439. /**
  440. * 填充缓存架
  441. *
  442. * @param \Illuminate\Database\Eloquent\Collection $stations
  443. *
  444. * @return bool
  445. *
  446. * @throws
  447. */
  448. public function paddingCacheShelf(Collection $stations):?bool
  449. {
  450. $collection = new Collection();
  451. $stationCollection = new Collection();
  452. $blacklist = [];
  453. foreach ($stations as $station){
  454. $box = app("MaterialBoxService")->getAnEmptyBoxSortedByOwner(null,$blacklist);
  455. if (!$box)break;
  456. $task = StationTask::query()->create([
  457. 'status' => "待处理",
  458. 'station_id' => $station->id,
  459. ]);
  460. $collection->add(StationTaskMaterialBox::query()->create([
  461. 'station_id' => $station->id,
  462. 'material_box_id'=>$box->id,
  463. 'status'=>"待处理",
  464. 'type' => '放',
  465. 'station_task_id' => $task->id,
  466. ]));
  467. $stationCollection->add($station->code);
  468. $blacklist[] = $box->id;
  469. }
  470. if ($stationCollection->count()>0){
  471. if (!$this->fetchGroup_multiLocation($stationCollection,$collection,'','立架出至缓存架')) return null;
  472. app("StationService")->locationOccupyMulti($stationCollection->toArray());
  473. $stationCollection->each(function ($code){
  474. app("CacheShelfService")->lightUp($code,'3','0',["title"=>"机器人取箱中,禁止操作"]);
  475. });
  476. }
  477. return $stations->count()==$stationCollection->count();
  478. }
  479. }