ForeignHaiRoboticsService.php 16 KB

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