Commit dc46c783 LN

部分mes对接代码

1 个父辈 23ed044d
...@@ -115,7 +115,7 @@ public class DataInitManager { ...@@ -115,7 +115,7 @@ public class DataInitManager {
TaskShelfUtil.dataCache=dataCache; TaskShelfUtil.dataCache=dataCache;
TaskShelfUtil.initShelfMap(); TaskShelfUtil.initData();
} catch (Exception exception) { } catch (Exception exception) {
log.error("初始化环境出错..." + exception.toString(),exception); log.error("初始化环境出错..." + exception.toString(),exception);
......
package com.neotel.smfcore.common.mqtt; package com.neotel.smfcore.common.mqtt;
import com.neotel.smfcore.custom.gree20242.api.GreeMsgHandlerImpl;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions; import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
...@@ -15,11 +16,8 @@ import org.springframework.integration.mqtt.core.MqttPahoClientFactory; ...@@ -15,11 +16,8 @@ import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter; import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler; import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter; import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
import org.springframework.integration.mqtt.support.MqttHeaders;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel; import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler; import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;
/** /**
...@@ -73,29 +71,33 @@ public class MqttboundConfiguration { ...@@ -73,29 +71,33 @@ public class MqttboundConfiguration {
log.info("inbound:监听topic:"+mqttProperties.getTopics()); log.info("inbound:监听topic:"+mqttProperties.getTopics());
return adapter; return adapter;
} }
@Bean
@ServiceActivator(inputChannel = "mqttInputChannel")
public MessageHandler mqttHandler(GreeMsgHandlerImpl messageHandler) {
return message -> messageHandler.handleMessage(message);
}
// //通过通道获取数据
//通过通道获取数据 // @Bean
@Bean // @ServiceActivator(inputChannel = "mqttInputChannel") //异步处理
@ServiceActivator(inputChannel = "mqttInputChannel") //异步处理 // public MessageHandler handler() {
public MessageHandler handler() { // return new MessageHandler() {
return new MessageHandler() { // @Override
@Override // public void handleMessage(Message<?> message) throws MessagingException {
public void handleMessage(Message<?> message) throws MessagingException { //// System.out.println("message:"+message);
// System.out.println("message:"+message); // log.info("---------handleMessage-------------");
log.info("---------handleMessage-------------"); // log.info("收到消息:message:"+message.getPayload());
log.info("收到消息:message:"+message.getPayload()); // log.info("收到消息:PacketId:"+message.getHeaders().getId());
log.info("收到消息:PacketId:"+message.getHeaders().getId()); // log.info("收到消息:Qos:"+message.getHeaders().get(MqttHeaders.QOS));
log.info("收到消息:Qos:"+message.getHeaders().get(MqttHeaders.QOS)); //
// String topic = (String) message.getHeaders().get(MqttHeaders.RECEIVED_TOPIC);
String topic = (String) message.getHeaders().get(MqttHeaders.RECEIVED_TOPIC); // log.info("收到消息:topic:"+topic);
log.info("收到消息:topic:"+topic); //
// }
} // };
}; // }
}
@Bean @Bean
@ServiceActivator(inputChannel = "mqttOutboundChannel") @ServiceActivator(inputChannel = "mqttOutboundChannel")
......
...@@ -76,6 +76,9 @@ public class SmfApi { ...@@ -76,6 +76,9 @@ public class SmfApi {
@Value("${api.fetchOrderUrl:}") @Value("${api.fetchOrderUrl:}")
protected String fetchOrderUrl = ""; protected String fetchOrderUrl = "";
@Value("${api.arriveLineUrl:}")
protected String arriveLineUrl="";
@PostConstruct @PostConstruct
public void init(){ public void init(){
apiName = dataCache.getConfigCache("api.name",apiName); apiName = dataCache.getConfigCache("api.name",apiName);
...@@ -89,6 +92,7 @@ public class SmfApi { ...@@ -89,6 +92,7 @@ public class SmfApi {
fetchInListUrl = dataCache.getConfigCache("api.fetchInListUrl",fetchInListUrl); fetchInListUrl = dataCache.getConfigCache("api.fetchInListUrl",fetchInListUrl);
fetchOrderUrl = dataCache.getConfigCache("api.fetchOrderUrl",fetchOrderUrl); fetchOrderUrl = dataCache.getConfigCache("api.fetchOrderUrl",fetchOrderUrl);
loginCheckUrl=dataCache.getConfigCache("api.loginCheckUrl",loginCheckUrl); loginCheckUrl=dataCache.getConfigCache("api.loginCheckUrl",loginCheckUrl);
arriveLineUrl=dataCache.getConfigCache("api.arriveLineUrl",arriveLineUrl);
} }
/** /**
...@@ -238,6 +242,24 @@ public class SmfApi { ...@@ -238,6 +242,24 @@ public class SmfApi {
} }
return true; return true;
} }
public void shelfArriveLine( LiteOrder liteOrder,String shelfId)throws ValidateException {
if (shelfId == null || liteOrder == null) {
return;
}
if (isUrlExist(arriveLineUrl)) {
for (ISmfApiListener apiListener : apiListenerList) {
if (apiListener.isForThisApi(apiName)) {
try {
apiListener.shelfArriveLine(arriveLineUrl, liteOrder, shelfId);
} catch (Exception e) {
throw new ValidateException("smfcore.api.error", "API Error:" + e.getMessage());
}
}
}
}
}
/** /**
* 判断URL是否存在,如果不存在不需要进行发送 * 判断URL是否存在,如果不存在不需要进行发送
* @param url * @param url
......
...@@ -114,6 +114,10 @@ public abstract class BaseSmfApiListener implements ISmfApiListener { ...@@ -114,6 +114,10 @@ public abstract class BaseSmfApiListener implements ISmfApiListener {
public boolean canLogin(String loginCheckUrl, String userName, String pwd) throws ValidateException { public boolean canLogin(String loginCheckUrl, String userName, String pwd) throws ValidateException {
return true; return true;
} }
@Override
public void shelfArriveLine(String arriveLineUrl, LiteOrder liteOrder,String shelfId) {
}
protected String getData(Map<String, Object> dataMap, String dataKey) { protected String getData(Map<String, Object> dataMap, String dataKey) {
Object data = dataMap.get(dataKey); Object data = dataMap.get(dataKey);
if (data == null) { if (data == null) {
......
...@@ -61,4 +61,12 @@ public interface ISmfApiListener { ...@@ -61,4 +61,12 @@ public interface ISmfApiListener {
* 是否可以登陆 * 是否可以登陆
*/ */
boolean canLogin(String loginCheckUrl, String userName,String pwd) throws ValidateException; boolean canLogin(String loginCheckUrl, String userName,String pwd) throws ValidateException;
/**
* 料架到达产线
* @param arriveLineUrl
* @param liteOrder
* @param shelfId
*/
void shelfArriveLine(String arriveLineUrl, LiteOrder liteOrder,String shelfId) ;
} }
...@@ -629,4 +629,25 @@ public class DeviceController { ...@@ -629,4 +629,25 @@ public class DeviceController {
data.put("plateH", pos.getBarcode().getHeight() + ""); data.put("plateH", pos.getBarcode().getHeight() + "");
return ResultBean.newOkResult(data); return ResultBean.newOkResult(data);
} }
@ApiOperation("更新设备数据")
@PostMapping(value = "/updateData")
@ResponseBody
@AnonymousAccess
public ResultBean updateData(HttpServletRequest request) {
String key = request.getParameter("key");
Object value = request.getParameter("value");
DevicesStatusUtil.updateDData(key,value);
return ResultBean.newOkResult(key);
}
@ApiOperation("获取设备数据")
@PostMapping(value = "/getData")
@ResponseBody
@AnonymousAccess
public ResultBean getData(HttpServletRequest request) {
String key = request.getParameter("key");
Object value = DevicesStatusUtil.getDDate(key);
return ResultBean.newOkResult(value);
}
} }
...@@ -27,12 +27,35 @@ public class TaskShelfUtil { ...@@ -27,12 +27,35 @@ public class TaskShelfUtil {
*/ */
public static Map<String, Map<String, ShelfInfo>> taskShelfMap =null; public static Map<String, Map<String, ShelfInfo>> taskShelfMap =null;
public static Map<String,String> shelfLocMap=null;
private static String HSERIAL_SHELF_MAP_KEY = "HSERIAL_SHELF_MAP_KEY"; private static String HSERIAL_SHELF_MAP_KEY = "HSERIAL_SHELF_MAP_KEY";
private static String SHELF_LOC_MAP_KEY = "SHELF_LOC_MAP_KEY";
private static String DEFAULT_ORDERNO = "1"; private static String DEFAULT_ORDERNO = "1";
public static void initData(){
initShelfMap();
initShelfLocMap();
}
private static void initShelfLocMap() {
if (shelfLocMap == null) {
shelfLocMap = dataCache.getCache(SHELF_LOC_MAP_KEY);
if(shelfLocMap ==null){
shelfLocMap =new ConcurrentHashMap<>();
}
}
}
private static void saveShelfLocMap(Map<String, String> map) {
dataCache.updateCache(SHELF_LOC_MAP_KEY, map);
}
public static void initShelfMap() { private static void initShelfMap() {
if (taskShelfMap == null) { if (taskShelfMap == null) {
taskShelfMap = dataCache.getCache(HSERIAL_SHELF_MAP_KEY); taskShelfMap = dataCache.getCache(HSERIAL_SHELF_MAP_KEY);
if(taskShelfMap ==null){ if(taskShelfMap ==null){
...@@ -418,4 +441,12 @@ public class TaskShelfUtil { ...@@ -418,4 +441,12 @@ public class TaskShelfUtil {
} }
return null; return null;
} }
public static void updateShelfLoc(String rfid,String loc){
shelfLocMap.put(rfid,loc);
saveShelfLocMap(shelfLocMap);
}
} }
package com.neotel.smfcore.core.shelf.rest;
import com.neotel.smfcore.common.bean.ResultBean;
import com.neotel.smfcore.core.api.SmfApi;
import com.neotel.smfcore.core.order.LiteOrderCache;
import com.neotel.smfcore.core.order.service.po.LiteOrder;
import com.neotel.smfcore.core.shelf.TaskShelfUtil;
import com.neotel.smfcore.core.shelf.bean.ShelfInfo;
import com.neotel.smfcore.security.annotation.AnonymousAccess;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
@Slf4j
@RestController
@Api(tags = "20242:格力agv取放料架接口")
@RequestMapping("/rest/api/agv")
public class AgvShelfController {
@Autowired
private LiteOrderCache liteOrderCache;
@Autowired
private SmfApi smfApi;
@ApiOperation("agv获取指定料架的目标位置")
@PostMapping(value = "/getShelfTargetLoc")
@ResponseBody
@AnonymousAccess
public ResultBean getShelfTargetLoc(HttpServletRequest request) {
String rfid = request.getParameter("rfid");
ShelfInfo shelfInfo = TaskShelfUtil.findShelfByRealRfid(rfid);
if (shelfInfo != null) {
String orderNo = shelfInfo.getOrderNo();
LiteOrder order = liteOrderCache.getLiteOrder(orderNo);
if (order != null) {
String line = order.getLine();
log.info("getShelfTargetLoc 料架 ,rfid=[" + rfid + "],目标位置:[" + line + "]");
return ResultBean.newOkResult(line);
}
} else {
log.info("getShelfTargetLoc 未找到料架 ,rfid=[" + rfid + "]");
}
return ResultBean.newErrorResult(99, "smfcore.agvShelf.noLoc", "未找到料架{0}目标位置", new String[]{rfid});
}
@ApiOperation("料架到达产线位置")
@PostMapping(value = "/shelfArriveLine")
@ResponseBody
@AnonymousAccess
public ResultBean shelfArriveLine(HttpServletRequest request) {
String rfid = request.getParameter("rfid");
String loc = request.getParameter("loc");
ShelfInfo shelfInfo = TaskShelfUtil.findShelfByRealRfid(rfid);
if (shelfInfo != null) {
} else {
log.info("updateShelfLoc 未找到料架 ,rfid=[" + rfid + "]");
return ResultBean.newErrorResult(99,"smfcore.agvShelf.noshelf","未找到料架{0}",new String[]{rfid});
}
//更新记录
TaskShelfUtil.updateShelfLoc(rfid, loc);
log.info("updateShelfLoc 更新料架【" + rfid + "】位置=【" + loc + "】");
String orderNo=shelfInfo.getOrderNo();
LiteOrder order = liteOrderCache.getLiteOrder(orderNo);
if (order != null) {
//如果目标位置是产线,通知mes
smfApi.shelfArriveLine(order,rfid);
}
return ResultBean.newOkResult("ok");
}
}
...@@ -9,6 +9,7 @@ import com.neotel.smfcore.core.message.util.DeviceMessageUtil; ...@@ -9,6 +9,7 @@ import com.neotel.smfcore.core.message.util.DeviceMessageUtil;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
...@@ -221,4 +222,13 @@ public class DevicesStatusUtil { ...@@ -221,4 +222,13 @@ public class DevicesStatusUtil {
log.error("设备状态定时器执行出错:", ex); log.error("设备状态定时器执行出错:", ex);
} }
} }
private static Map<String,Object> deviceClientDataMap=new HashMap<>();
public static void updateDData(String key,Object value){
deviceClientDataMap.put(key,value);
}
public static Object getDDate(String key) {
Object value = deviceClientDataMap.getOrDefault(key, "");
return value;
}
} }
package com.neotel.smfcore.custom.gree20242;
import org.springframework.stereotype.Service;
@Service
public class GreeApiHandler {
}
package com.neotel.smfcore.custom.gree20242;
import cn.hutool.core.util.ObjectUtil;
import com.neotel.smfcore.common.bean.ResultBean;
import com.neotel.smfcore.core.device.util.DataCache;
import com.neotel.smfcore.core.system.service.po.DataLog;
import com.neotel.smfcore.core.system.util.TaskService;
import com.neotel.smfcore.security.annotation.AnonymousAccess;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
@Slf4j
@RestController
@Api(tags = "20242:格力流水线设备接口")
@RequestMapping("/rest/gree/device")
public class GreeDeviceController {
@Autowired
private TaskService taskService;
@Autowired
private DataCache dataCache;
@ApiOperation("更新任务状态")
@PostMapping(value = "/updateLocInfo")
@ResponseBody
@AnonymousAccess
public ResultBean updateLocInfo(HttpServletRequest request) {
String taskId = request.getParameter("taskId");
String barcode = request.getParameter("barcode");
String statusStr = request.getParameter("status");
String locInfo = request.getParameter("locInfo");
log.info("收到taskId[" + taskId + "],料盘[" + barcode + "]更新位置指令[" + statusStr + "]=" + locInfo);
if (ObjectUtil.isEmpty(locInfo)) {
locInfo = statusStr;
}
DataLog opTask = null;
List<DataLog> allTasks = taskService.getAllTasks();
for (DataLog task : allTasks) {
if (task.isFinished()) {
continue;
}
if (ObjectUtil.isNotEmpty(task) && task.getId().equals(taskId)) {
opTask = task;
break;
} else if (ObjectUtil.isNotEmpty(barcode) && task.getBarcode().equals(barcode)) {
opTask = task;
break;
}
}
//如果任务为空,重新查找已完成的任务
if (opTask == null) {
for (DataLog task : allTasks) {
if (ObjectUtil.isNotEmpty(task) && task.getId().equals(taskId)) {
opTask = task;
break;
} else if (ObjectUtil.isNotEmpty(barcode) && task.getBarcode().equals(barcode)) {
opTask = task;
break;
}
}
}
if (opTask == null) {
log.info(" taskId[" + taskId + "],料盘[" + barcode + "]更新位置指令[" + statusStr + "]=" + locInfo + ",失败:任务不存在");
return ResultBean.newErrorResult(301, "smfcore.task.notExist", "任务不存在");
}
if (opTask.isFinished()) {
log.info(" taskId[" + taskId + "],料盘[" + barcode + "]更新位置指令[" + statusStr + "]=" + locInfo + ",失败:任务已完成");
return ResultBean.newErrorResult(302, "smfcore.task.hasEnd", "任务已完成");
}
if (opTask.isCancel()) {
return ResultBean.newErrorResult(303, "smfcore.task.hasCancel", "更新状态时{0}的任务[{1}]已被取消", new String[]{opTask.getBarcode(), opTask.getId()});
}
statusStr = statusStr.toUpperCase();
String inouType = opTask.isCheckOutTask() ? "出库" : "入库";
//若已经在此状态,不需要再更新
if (opTask.getStatus().equals(statusStr) && opTask.getLocInfo().equals(locInfo)) {
log.warn("更新料盘[" + barcode + "]的[" + inouType + "]任务状态已是[" + opTask.getStatus() + "=" + opTask.getLocInfo() + "]不需要重复更新为[" + statusStr + "=" + locInfo + "]");
} else {
log.info("更新料盘[" + barcode + "]的[" + inouType + "]任务状态[" + opTask.getStatus() + "=" + opTask.getLocInfo() + "]为[" + statusStr + "=" + locInfo + "]");
opTask.setStatus(statusStr);
opTask.setLocInfo(locInfo);
if (opTask.isPutInTask()) {
taskService.updateQueueTask(opTask);
} else {
if (opTask.isFinished()) {
taskService.removeQueueTask(opTask);
}
taskService.updateFinishedTask(opTask);
}
// try{
// if (opTask.isInRobot() || opTask.isInLine() || opTask.isBoxdoor()) {
// //保存状态
// MaterialLog m = new MaterialLog(opTask.getBarcode(), opTask.getPosName(), opTask.getType(), opTask.getStatus(), opTask.getLocInfo());
// log.info("记录料盘[" + inouType + "]日志[" + m.getBarcode() + "," + m.getPosName() + "," + m.getStatus() + "," + m.getLocInfo() + "]");
//
// materialLogManager.save(m);
// }}catch (Exception ex){
// log.info("记录料盘[" + inouType + "]日志[" + opTask.getBarcode() + "," + opTask.getPosName() + "," + opTask.getStatus() + "," + opTask.getLocInfo() + "]出错:"+ex.getMessage());
// }
}
return ResultBean.newOkResult("");
}
@ApiOperation("料盘到达出料机构入口")
@PostMapping(value = "/reelArriveOutBound")
@ResponseBody
@AnonymousAccess
public ResultBean reelArriveOutBound(HttpServletRequest request) {
String barcode = request.getParameter("barcode");
String statusStr = request.getParameter("status");//OUTBOUND
if(ObjectUtil.isEmpty(statusStr)){
statusStr="OUTBOUND";
}
String locInfo = request.getParameter("locInfo");//1=上层,2=下层,
log.info("收到 reelArriveOutBound 料盘[" + barcode + "]更新位置指令[" + statusStr + "]=" + locInfo);
String key="OUTBOUND_IN_"+ locInfo +"_REEL_KEY";
dataCache.updateCache(key,barcode);
return ResultBean.newOkResult("");
}
@ApiOperation("获取出料机构入口的料")
@PostMapping(value = "/reelArriveOutBound")
@ResponseBody
@AnonymousAccess
public ResultBean getOutBoundReel(HttpServletRequest request) {
String statusStr = request.getParameter("status");//OUTBOUND
String locInfo = request.getParameter("locInfo");//1=上层,2=下层,
String key = "OUTBOUND_IN_" + locInfo + "_REEL_KEY";
String barcode = dataCache.getCache(key);
return ResultBean.newOkResult(barcode);
}
}
package com.neotel.smfcore.custom.gree20242; package com.neotel.smfcore.custom.gree20242.api;
import com.neotel.smfcore.common.mqtt.MqttGateway;
import com.neotel.smfcore.common.utils.JsonUtil;
import com.neotel.smfcore.core.api.listener.BaseSmfApiListener; import com.neotel.smfcore.core.api.listener.BaseSmfApiListener;
import com.neotel.smfcore.core.order.service.po.LiteOrder; import com.neotel.smfcore.core.order.service.po.LiteOrder;
import com.neotel.smfcore.core.system.service.po.DataLog; import com.neotel.smfcore.core.system.service.po.DataLog;
import com.neotel.smfcore.custom.gree20242.bean.GreeRequestMsg; import com.neotel.smfcore.custom.gree20242.bean.GreeRequestMsg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@Slf4j
public class GreeApi extends BaseSmfApiListener { public class GreeApi extends BaseSmfApiListener {
@Override @Override
public boolean isForThisApi(String apiName) { public boolean isForThisApi(String apiName) {
return apiName != null && apiName.equalsIgnoreCase("20242"); return apiName != null && apiName.equalsIgnoreCase("20242");
} }
@Autowired
private MqttGateway mqttGateway;
@Override @Override
public void inTaskStatusChange(String inNotifyUrl, DataLog task) { public void inTaskStatusChange(String inNotifyUrl, DataLog task) {
if (task.isPutInTask() && task.isFinished()) { if (task.isPutInTask() && task.isFinished()) {
...@@ -23,39 +31,46 @@ public class GreeApi extends BaseSmfApiListener { ...@@ -23,39 +31,46 @@ public class GreeApi extends BaseSmfApiListener {
params.put("slot", task.getPosName()); params.put("slot", task.getPosName());
params.put("deviceId", task.getStorageId()); params.put("deviceId", task.getStorageId());
GreeRequestMsg msg = GreeRequestMsg.newMsg(inNotifyUrl, params); GreeRequestMsg msg = GreeRequestMsg.newMsg(inNotifyUrl, params);
boolean result= SendMsg(inNotifyUrl,msg); boolean result= SendMsg(inNotifyUrl,msg );
} }
} }
@Override @Override
public void onOrderStatusChange(String orderNotifyUrl, LiteOrder liteOrder) { public void onOrderStatusChange(String orderNotifyUrl, LiteOrder liteOrder) {
Map<String, String> params = new HashMap<>(); if(liteOrder.isClosed()||liteOrder.isTaskFinished()) {
params.put("shelfId", liteOrder.getOrderNo()); Map<String, String> params = new HashMap<>();
params.put("hSerial", liteOrder.getOrderNo()); params.put("shelfId", liteOrder.getOrderNo());
params.put("so", liteOrder.getSo()); params.put("hSerial", liteOrder.getOrderNo());
params.put("line", liteOrder.getLine()); params.put("so", liteOrder.getSo());
params.put("line", liteOrder.getLine());
GreeRequestMsg msg = GreeRequestMsg.newMsg(orderNotifyUrl, params); GreeRequestMsg msg = GreeRequestMsg.newMsg(orderNotifyUrl, params);
boolean result= SendMsg(orderNotifyUrl,msg); boolean result = SendMsg(orderNotifyUrl, msg);
}
} }
public void ShelfArriveLine(String arriveLineUrl, LiteOrder liteOrder) { @Override
public void shelfArriveLine(String arriveLineUrl, LiteOrder liteOrder,String shelfId) {
Map<String, String> params = new HashMap<>(); Map<String, String> params = new HashMap<>();
params.put("shelfId", liteOrder.getOrderNo()); params.put("shelfId", shelfId);
params.put("hSerial", liteOrder.getOrderNo()); params.put("hSerial", liteOrder.getOrderNo());
params.put("so", liteOrder.getSo()); params.put("so", liteOrder.getSo());
params.put("line", liteOrder.getLine()); params.put("line", liteOrder.getLine());
GreeRequestMsg msg = GreeRequestMsg.newMsg(arriveLineUrl, params); GreeRequestMsg msg = GreeRequestMsg.newMsg(arriveLineUrl, params);
boolean result= SendMsg(arriveLineUrl,msg); boolean result= SendMsg(arriveLineUrl,msg );
} }
public boolean SendMsg(String url,GreeRequestMsg msg){ public boolean SendMsg(String url,GreeRequestMsg msgBean ) {
return true; //url地址配置为发送主题
String msg = JsonUtil.toJsonStr(msgBean);
mqttGateway.sendToMqtt(url, msg);
log.info("GreeApi SendMsg: topic=[" + url + "],sendData=" + msg);
GreeMsgCache.addSendMsg(msgBean);
return true;
} }
} }
package com.neotel.smfcore.custom.gree20242.api;
import com.neotel.smfcore.custom.gree20242.bean.GreeRequestMsg;
import java.util.HashMap;
import java.util.Map;
public class GreeMsgCache {
private static Map<String, GreeRequestMsg> sendEndMsgMap=new HashMap<>();
private static Map<String, GreeRequestMsg> sendMsgMap=new HashMap<>();
public static void addSendMsg(GreeRequestMsg msg){
sendMsgMap.put(msg.getId(),msg);
}
public static boolean isSendId(String id){
GreeRequestMsg msg= sendMsgMap.get(id);
if(msg!=null){
//放入发送结束的msg
sendEndMsgMap.put(id,msg);
return true;
}
return false;
}
}
package com.neotel.smfcore.custom.gree20242.api;
import cn.hutool.core.util.ObjectUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.neotel.smfcore.common.mqtt.MqttGateway;
import com.neotel.smfcore.common.utils.JsonUtil;
import com.neotel.smfcore.common.utils.StorageConstants;
import com.neotel.smfcore.core.device.bean.BoxStatusBean;
import com.neotel.smfcore.core.device.bean.StatusBean;
import com.neotel.smfcore.core.device.util.DataCache;
import com.neotel.smfcore.core.order.LiteOrderCache;
import com.neotel.smfcore.core.order.service.manager.ILiteOrderManager;
import com.neotel.smfcore.core.order.service.po.LiteOrder;
import com.neotel.smfcore.core.order.service.po.LiteOrderItem;
import com.neotel.smfcore.core.storage.bean.UsageItem;
import com.neotel.smfcore.core.storage.service.po.Storage;
import com.neotel.smfcore.core.system.util.DevicesStatusUtil;
import com.neotel.smfcore.custom.gree20242.bean.GreeRequestMsg;
import com.neotel.smfcore.custom.gree20242.bean.GreeResponseMsg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.mqtt.support.MqttHeaders;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Service;
import java.util.*;
@Service
@Slf4j
public class GreeMsgHandlerImpl implements MessageHandler {
@Autowired
protected ILiteOrderManager liteOrderManager;
@Autowired
protected LiteOrderCache liteOrderCache;
@Autowired
private DataCache dataCache;
@Autowired
private MqttGateway mqttGateway;
// 当然可以,您可以在一个新的类中创建一个新的处理方法,然后将其注入到主类中,这样可以使代码更加模块化和易于管理。例如: ```java @Component
// public class MessageHandlerImpl implements MessageHandler {
@Override
public void handleMessage(Message message) throws MessagingException {
try {
// your implementation
System.out.println("message:" + message);
log.info("---------handleMessage-------------");
String msgStr = (String) message.getPayload();
UUID packetId = message.getHeaders().getId();
Integer qos = 0;
try {
Integer.parseInt(message.getHeaders().get(MqttHeaders.QOS).toString());
}catch (Exception ex){
}
String topic = (String) message.getHeaders().get(MqttHeaders.RECEIVED_TOPIC);
log.info("收到消息:topic:["+topic+"],packetId["+packetId+"],qos:["+qos+"],message:[" + message.getPayload()+"]");
//判断消息类型
GreeResponseMsg responseMsg =GreeResponseMsg.newMsg(null,99,"数据解析失败","") ;
try {
GreeRequestMsg requestMsg = JsonUtil.toObj(msgStr, GreeRequestMsg.class);
if(ObjectUtil.isNotEmpty((requestMsg.getId()))&& ObjectUtil.isNotEmpty(requestMsg.getSubject())) {
//如果id是自己发出来的
if(GreeMsgCache.isSendId(requestMsg.getId())){
log.info("标记 id=["+requestMsg.getId()+"]的消息发送完成");
return;
}
//判断是否是获取
responseMsg = deviceStatusMsgPro(topic, packetId, requestMsg);
String responseStr=JsonUtil.toJsonStr(responseMsg);
log.info("返回消息:topic:["+topic+"],packetId["+packetId+"],qos:["+qos+"],message:[" + responseStr+"]");
mqttGateway.sendToMqtt(topic,qos,responseStr);
}else{
log.info("收到消息: message:[" + message.getPayload()+"] 主题或ID为空,暂不处理" );
}
}catch (Exception ex){
log.info("收到消息: message:[" + message.getPayload()+"] 数据解析失败:"+ex.toString());
}
} catch (Exception ex) {
log.error("GreeMsgHandlerImpl 处理消息["+message+"]出错:" + ex.toString());
}
}
//接收到需求单
public GreeResponseMsg outInfoMsgPro(String topic, UUID packetId, GreeRequestMsg rMsg) {
// GreeRequestMsg rMsg = JsonUtil.toObj(message, GreeRequestMsg.class);
Map<String, Object> data = (Map<String, Object>) rMsg.getData();
if (!data.isEmpty()) {
if (data.get("hSerial") == null) {
return GreeResponseMsg.newMsg(rMsg, 1, "hSerial 不能为空", data);
}
if (data.get("outItems") == null) {
return GreeResponseMsg.newMsg(rMsg, 1, "outItems 不能为空", data);
}
String orderNo = data.get("hSerial").toString(); //需求单号
LiteOrder order = liteOrderManager.findByOrderNo(orderNo);
if (order != null) {
return GreeResponseMsg.newMsg(rMsg, 1, "需求单" + orderNo + "已存在", data);
}
String line = data.get("line") == null ? "" : data.get("line").toString(); //线别
String so = data.get("so") == null ? "" : data.get("so").toString(); //工单号
//需求单详情数据
List<LiteOrderItem> orderItemList = new ArrayList<>();
List<Map> outItemList = JsonUtil.toList(data.get("outItems").toString(), Map.class);
if (!outItemList.isEmpty()) {
for (Map outItem : outItemList) {
LiteOrderItem orderItem = new LiteOrderItem();
if (outItem.get("reelId") != null) {
String reelId = outItem.get("reelId").toString();
orderItem.setRi(reelId); //料盘唯一码
orderItem.setNeedNum(1);
orderItem.setNeedReelCount(1);
}
if (outItem.get("feeder") != null) {
String feeder = outItem.get("feeder").toString();
orderItem.setFeederInfo(feeder);
}
orderItemList.add(orderItem);
}
}
//开始保存数据
LiteOrder liteOrder = new LiteOrder();
liteOrder.setOrderNo(orderNo);
liteOrder.setLine(line);
liteOrder.setSo(so);
liteOrder.setOrderItems(orderItemList);
liteOrder = liteOrderManager.createWithItems(liteOrder);
liteOrderCache.addOrderToMap(liteOrder);
log.info("创建需求单[" + liteOrder.getOrderNo() + "][" + liteOrder.getSo() + "][" + liteOrder.getLine() + "]完成,共[" + orderItemList.size() + "]条item");
return GreeResponseMsg.newOkMsg(rMsg, data);
}
return GreeResponseMsg.newMsg(rMsg, 1, "需求单信息不能为空", data);
}
public GreeResponseMsg deviceStatusMsgPro(String topic,UUID packetId,GreeRequestMsg rMsg) {
// GreeRequestMsg rMsg = JsonUtil.toObj(message, GreeRequestMsg.class);
Map<String, Object> data = (Map<String, Object>) rMsg.getData();
List<String> deviceKeyList = null;
Collection<Storage> storageList = Lists.newArrayList();
if (!data.isEmpty()) {
deviceKeyList = data.get("deviceKeyList") == null ? null : JsonUtil.toList(data.get("deviceKeyList").toString(), String.class);
//如果没有的话 就查询所有的
if (deviceKeyList == null || deviceKeyList.size() < 1) {
storageList.addAll(dataCache.getAllStorage().values());
} else {
for (String cid : deviceKeyList) {
Storage storage = dataCache.getStorage(cid);
storageList.add(storage);
}
}
}
List<Map<String, Object>> results = Lists.newArrayList();
for (Storage storage : storageList) {
StatusBean statusBean = DevicesStatusUtil.getStatusBean(storage.getCid());
if (statusBean == null) {
statusBean = new StatusBean();
}
Map<String, BoxStatusBean> boxStatusMap = statusBean.getBoxStatus();
int status = -1;
if (boxStatusMap != null) {
BoxStatusBean boxStatusBean = boxStatusMap.get("1");
if (boxStatusBean != null) {
status = boxStatusBean.getStatus();
}
}
int storageStatus = status;
if (status == StorageConstants.STATUS.OFFLINE || statusBean.timeOut()) {
//离线
storageStatus = -1;
}
String msg = statusBean.getMsg();
String msgType = statusBean.getDeviceType();
Map<String, Object> itemMap = new HashMap<>();
itemMap.put("deviceKey", storage.getType() + "." + storage.getCid());
itemMap.put("name", storage.getName());
itemMap.put("msgType", msgType);
itemMap.put("msg", msg);
itemMap.put("status", storageStatus);
itemMap.put("startTime", storage.getCreateDate());
itemMap.put("updateTime", storage.getUpdateDate());
Map<String, Object> deviceDataMap = new HashMap<>();
Map<String, Object> emptySlotMap = Maps.newHashMap();
Map<String, Object> totalSlotMap = Maps.newHashMap();
Map<String, UsageItem> usageMap = storage.getUsageMap();
for (UsageItem usageItem : usageMap.values()) {
String sizeStr = usageItem.getSizeStr();
int total = usageItem.getTotalCount();
int used = usageItem.getUsedCount();
totalSlotMap.put(sizeStr, total);
emptySlotMap.put(sizeStr, total - used);
}
deviceDataMap.put("towerId", storage.getCid());
deviceDataMap.put("barcode", statusBean.getData().get("barcode"));
deviceDataMap.put("status", statusBean.getStatus());
deviceDataMap.put("name", storage.getName());
deviceDataMap.put("doorReelSignal", statusBean.getDoorReelSingnal());
deviceDataMap.put("emptySlot", emptySlotMap);
deviceDataMap.put("totalSlot", totalSlotMap);
itemMap.put("deviceData", deviceDataMap);
results.add(itemMap);
}
return GreeResponseMsg.newOkMsg(rMsg, results);
}
}
...@@ -5,21 +5,30 @@ import lombok.Data; ...@@ -5,21 +5,30 @@ import lombok.Data;
import java.io.Serializable; import java.io.Serializable;
import java.util.Date; import java.util.Date;
import java.util.HashMap; import java.util.UUID;
import java.util.Map;
@Data @Data
public class GreeRequestMsg implements Serializable { public class GreeRequestMsg<T> implements Serializable {
public static GreeRequestMsg newMsg(String suject,Map<String,String> params){ public static String getUUID() {
System.out.println(UUID.randomUUID());
String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
return uuid;
}
public static GreeRequestMsg newMsg(String suject,Object params){
GreeRequestMsg msg=new GreeRequestMsg() ; GreeRequestMsg msg=new GreeRequestMsg() ;
msg.setSpecVersion("1.0");
msg.setType("com.github.pull_request.opened");
msg.setSource("https://github.com/cloudevents/spec/pull");
msg.setSubject("pull_request");
msg.setDatacontentType("application/json");
msg.setSubject(suject); msg.setSubject(suject);
msg.setData(params); msg.setData(params);
String time=DateUtil.toDateString(new Date(),"yyyy-MM-dd HH:mm:ss"); String time=DateUtil.toDateString(new Date(),"yyyy-MM-dd HH:mm:ss");
String uid=DateUtil.toDateString(new Date(),"yyyyMMddHHmmss"); // String uid=DateUtil.toDateString(new Date(),"yyyyMMddHHmmss");
msg.setTime(time); msg.setTime(time);
msg.setId(uid); msg.setId(getUUID());
return msg; return msg;
} }
...@@ -29,33 +38,35 @@ public class GreeRequestMsg implements Serializable { ...@@ -29,33 +38,35 @@ public class GreeRequestMsg implements Serializable {
/** /**
* specVersion CloudEvents 规范版本 String 是"1.0" * specVersion CloudEvents 规范版本 String 是"1.0"
*/ */
private String specVersion = "1.0"; private String specVersion;
/** /**
* type 事件类型 String 是 com.github.pull_request.opened * type 事件类型 String 是 com.github.pull_request.opened
*/ */
private String type = "com.github.pull_request.opened"; private String type;
/** /**
* source 事件来源上下文 String 是 https://github.com/cloudevents/spec/pull * source 事件来源上下文 String 是 https://github.com/cloudevents/spec/pull
*/ */
private String source = "https://github.com/cloudevents/spec/pull"; private String source ;
/** /**
* subject 事件主题 String 是 pull_request * subject 事件主题 String 是 pull_request
*/ */
private String subject = "pull_request"; private String subject ;
/** /**
* id 事件 ID String 是 UUID 标识唯一 * id 事件 ID String 是 UUID 标识唯一
*/ */
private String id = "UUID 标识唯一"; private String id;
/** /**
* time 事件时间 String 是 格式:yyyy-MM-dd HH:mm:ss * time 事件时间 String 是 格式:yyyy-MM-dd HH:mm:ss
*/ */
private String time = "格式:yyyy-MM-dd HH:mm:ss"; private String time ;
/** /**
* datacontentType 数据格式类型 String 是 application/json * datacontentType 数据格式类型 String 是 application/json
*/ */
private String datacontentType = "application/json"; private String datacontentType ;
/** /**
* *
*/ */
private Map<String, String> data = new HashMap<>(); private T data ;
} }
package com.neotel.smfcore.custom.gree20242.bean; package com.neotel.smfcore.custom.gree20242.bean;
import com.neotel.smfcore.common.utils.DateUtil;
import lombok.Data; import lombok.Data;
import java.io.Serializable; import java.io.Serializable;
import java.util.Date;
@Data @Data
public class GreeResponseMsg implements Serializable { public class GreeResponseMsg<T> implements Serializable {
/** /**
* id 事件 ID String 是 与请求的事件 ID 一一对应 * id 事件 ID String 是 与请求的事件 ID 一一对应
...@@ -17,7 +20,7 @@ public class GreeResponseMsg implements Serializable { ...@@ -17,7 +20,7 @@ public class GreeResponseMsg implements Serializable {
/** /**
* code 结果码 Integer 是 0=成功, 其他为失败(如1001为参数错误) * code 结果码 Integer 是 0=成功, 其他为失败(如1001为参数错误)
*/ */
private String code; private Integer code=-1;
/** /**
* message 消息内容 String 是 消息内容 * message 消息内容 String 是 消息内容
*/ */
...@@ -25,5 +28,22 @@ public class GreeResponseMsg implements Serializable { ...@@ -25,5 +28,22 @@ public class GreeResponseMsg implements Serializable {
/** /**
* data 返回的数据 Object 是 JSON 格式 * data 返回的数据 Object 是 JSON 格式
*/ */
private String data; private T data;
public static GreeResponseMsg newOkMsg( GreeRequestMsg requestMsg, Object data){
return GreeResponseMsg.newMsg(requestMsg,0,"",data);
}
public static GreeResponseMsg newMsg( GreeRequestMsg requestMsg, Integer code,String message,Object data){
GreeResponseMsg msg=new GreeResponseMsg();
msg.setCode(code);
if(requestMsg!=null) {
msg.setId(requestMsg.getId());
}
String time= DateUtil.toDateString(new Date(),"yyyy-MM-dd HH:mm:ss");
msg.setFeedbackTime(time);
msg.setData(data);
msg.setMessage(message);
return msg;
}
} }
...@@ -7,6 +7,19 @@ api: ...@@ -7,6 +7,19 @@ api:
outNotifyUrl: outNotifyUrl:
inNotifyUrl: inNotifyUrl:
#mqtt配置
com:
mqtt:
url: tcp://127.0.0.1:1883
clientId: mqtt_smf-core_20242
topics: topic01,topic02
username: admin
password: admin
timeout: 10
keepalive: 20
hella: hella:
#host: 127.0.0.1 #host: 127.0.0.1
#port: 3333 #port: 3333
...@@ -34,6 +47,7 @@ spring: ...@@ -34,6 +47,7 @@ spring:
encoding: utf-8 encoding: utf-8
main: main:
allow-circular-references: true allow-circular-references: true
allow-bean-definition-overriding: true
#密码加密传输,前端公钥加密,后端私钥解密 #密码加密传输,前端公钥加密,后端私钥解密
rsa: rsa:
...@@ -48,3 +62,5 @@ menu: ...@@ -48,3 +62,5 @@ menu:
show: show:
hide: hide:
支持 Markdown 格式
你添加了 0 到此讨论。请谨慎行事。
Finish editing this message first!