| | |
| | | @Autowired |
| | | private ISysConfigService sysConfigService; |
| | | |
| | | @PostConstruct |
| | | // @PostConstruct |
| | | public void init() { |
| | | //获取电磁锁地址 |
| | | String mqttUrl = sysConfigService.selectConfigByKey("ElectromagneticLockUrl"); |
| | | List<ArdSyCarRtu> rtus = ardSyCarRtuService.allCarTopicList(); |
| | | for (int i = 0; i < rtus.size(); i++) { |
| | | ArdSyCarRtu rtu = rtus.get(i); |
| | | String carId = rtu.getCarId(); |
| | | String subscribe = rtu.getTopicSubscribe(); |
| | | try { |
| | | MqttClient client = getMqttClient(carId); |
| | | MqttConnectOptions options = getMqttConnectOptions(); |
| | | client.setCallback(new MqttOnceCallback(client,options,subscribe,2)); |
| | | // log.debug("--添加车辆电磁锁回调处理类"); |
| | | client.connect(options); |
| | | }catch (Exception e) { |
| | | e.printStackTrace(); |
| | | } |
| | | } |
| | | } |
| | | |
| | | public void subscribeCar(ArdSyCarRtu ardSyCarRtu){ |
| | | String carId = ardSyCarRtu.getCarId(); |
| | | String subscribe = ardSyCarRtu.getTopicSubscribe(); |
| | | try { |
| | | MqttClient client = getMqttClient(carId); |
| | | MqttConnectOptions options = getMqttConnectOptions(); |
| | | client.setCallback(new MqttOnceCallback(client,options,subscribe,2)); |
| | | // log.debug("--添加车辆电磁锁回调处理类"); |
| | | client.connect(options); |
| | | }catch (Exception e) { |
| | | e.printStackTrace(); |
| | | } |
| | | } |
| | | |
| | | public MqttClient getMqttClient(String carId) throws MqttException { |
| | | //获取电磁锁地址 |
| | | String mqttUrl = sysConfigService.selectConfigByKey("ElectromagneticLockUrl"); |
| | | MqttClient client = new MqttClient(mqttUrl,carId); |
| | | // log.debug("--创建"+carId+"号车辆电子锁mqtt客户端"); |
| | | return client; |
| | | } |
| | | |
| | | public MqttConnectOptions getMqttConnectOptions(){ |
| | | MqttConnectOptions options = new MqttConnectOptions(); |
| | | //设置用户名密码 |
| | | options.setUserName("admin"); |
| | |
| | | // 是否清除session |
| | | options.setCleanSession(true); |
| | | // log.debug("--生成"+carId+"号车辆电子锁mqtt配置对象"); |
| | | client.setCallback(new MqttOnceCallback(client,options,subscribe,2)); |
| | | // log.debug("--添加车辆电磁锁回调处理类"); |
| | | client.connect(options); |
| | | }catch (Exception e) { |
| | | e.printStackTrace(); |
| | | return options; |
| | | } |
| | | |
| | | public String publishCar(String carId,String topic,String message,String type) throws MqttException { |
| | | MqttClient client = getMqttClient(carId); |
| | | MqttConnectOptions options = getMqttConnectOptions(); |
| | | MqttMessage msg = new MqttMessage(message.getBytes()); |
| | | msg.setQos(2); |
| | | client.publish(topic,msg); |
| | | client.disconnect(); |
| | | return "发布"+type+"指令成功!"; |
| | | } |
| | | // MqttConsumer mqttConsumer = new MqttConsumer(); |
| | | // for (int i = 0; i < topic.length; i++) { |
| | | // mqttConsumer.subscribe(topic[i],2); |
| | | // } |
| | | // log.info("mqtt订阅清淤车辆锁信息:"+Arrays.toString(topic)); |
| | | } |
| | | |
| | | } |