ForeignHaiRoboticsService.php 21 KB

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