DirectiveServiceImpl.java 13.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
package com.bsth.service.directive;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bsth.common.ResponseCode;
import com.bsth.data.BasicData;
import com.bsth.data.directive.DayOfDirectives;
import com.bsth.data.directive.DirectiveCreator;
import com.bsth.data.directive.GatewayHttpUtils;
import com.bsth.data.gpsdata.GpsRealData;
import com.bsth.data.gpsdata.GpsEntity;
import com.bsth.data.pilot80.PilotReport;
import com.bsth.data.schedule.DayOfSchedule;
import com.bsth.entity.directive.D60;
import com.bsth.entity.directive.D64;
import com.bsth.entity.directive.D80;
import com.bsth.entity.directive.DC0_A3;
import com.bsth.entity.directive.Directive;
import com.bsth.entity.realcontrol.ScheduleRealInfo;
import com.bsth.entity.sys.SysUser;
import com.bsth.repository.directive.D60Repository;
import com.bsth.repository.directive.D64Repository;
import com.bsth.repository.directive.D80Repository;
import com.bsth.security.util.SecurityUtils;
import com.bsth.service.impl.BaseServiceImpl;
import com.bsth.websocket.handler.RealControlSocketHandler;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Splitter;

@Service
public class DirectiveServiceImpl extends BaseServiceImpl<D60, Integer> implements DirectiveService {

	Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	D60Repository d60Repository;

	@Autowired
	GpsRealData gpsRealDataBuffer;

	@Autowired
	D64Repository d64Repository;

	@Autowired
	RealControlSocketHandler socketHandler;

	@Autowired
	D80Repository d80Repository;
	
	@Autowired
	DayOfDirectives dayOfDirectives;
	
	@Autowired
	PilotReport pilotReport;
	
	@Autowired
	DayOfSchedule dayOfSchedule;
	
	//static Long schDiff = 1000 * 60 * 60L;

	private static DateTimeFormatter fmtHHmm = DateTimeFormat.forPattern("HH:mm")
				,fmtHHmm_CN = DateTimeFormat.forPattern("HH点mm分");

	@Override
	public int send60Phrase(String nbbm, String text, String sender) {
		D60 d60 = null;
		try {
			d60 = create60Data(nbbm, text, (short) 0x00, null);
		} catch (Exception e) {
			logger.error("发送消息短语出现异常", e);
			return -1;
		}

		if (null == d60)
			return -1;

		// 发送指令
		int code = GatewayHttpUtils.postJson(JSON.toJSONString(d60));
		if(null != sender)
			d60.setSender(sender);
		d60.setHttpCode(code);
		// 添加到缓存
		dayOfDirectives.put60(d60);

		if (code != 0) {
			d60.setErrorText("网关通讯失败, code: " + code);
			d60Repository.save(d60);
		}
		return code;
	}

	@Override
	public int send60Dispatch(ScheduleRealInfo sch, int finish, String sender) {
		D60 d60 = null;
		try {
			if(sch.isDestroy()){
				logger.warn("烂班不允许发送调度指令....");
				return -1;
			}
			String text = "已完成" + finish + "个班次,下一发车时间" + fmtHHmm_CN.print(sch.getDfsjT()) + ",由"
					+ sch.getQdzName() + "发往" + sch.getZdzName();

			//下发0x02指令  调度指令(闹钟有效)
			Long alarmTime = System.currentTimeMillis() + 1000 * 30;
			d60 = new DirectiveCreator().createD60_02(sch.getClZbh(), text, Integer.parseInt(sch.getXlDir())
					, 0, new Date(alarmTime));
		} catch (Exception e) {
			logger.error("生成调度指令时出现异常", e);
			return -1;
		}
		
		if (null == d60)
			return -1;
		
		d60.setSender(sender);
		
		JSONObject jObj = JSON.parseObject(JSON.toJSONString(d60));
		
		//进场或者出场班次时,附加lock 标识
		if(null != sch.getBcType()
				&& (sch.getBcType().equals("out") || sch.getBcType().equals("in"))){
			
			jObj.put("lock", 1);
		}
		
		// 发送指令
		int code = GatewayHttpUtils.postJson(jObj.toJSONString());

		// 添加到缓存,等待入库
		d60.setDispatch(true);
		d60.setSch(sch);
		d60.setHttpCode(code);
		dayOfDirectives.put60(d60);

		if (code == 0) {
			sch.setDirectiveState(60);
			// 通知页面
			sendD60ToPage(sch);
		}
		else{
			d60.setErrorText("网关通讯失败, code: " + code);
			d60Repository.save(d60);
		}
		return code;
	}

	/**
	 * 
	 * @Title: sendDirectiveState @Description: TODO(向页面推送班次指令状态) @throws
	 */
	@Override
	public void sendD60ToPage(ScheduleRealInfo sch) {
		Map<String, Object> map = new HashMap<>();
		map.put("fn", "directive");
		map.put("t", sch);
		
		ObjectMapper mapper = new ObjectMapper();
		
		try {
			socketHandler.sendMessageToLine(sch.getXlBm(), mapper.writeValueAsString(map));
		} catch (JsonProcessingException e) {
			logger.error("", e);
		}
	}

	@Override
	public int send60Dispatch(Long id, String sender) {
		ScheduleRealInfo sch = dayOfSchedule.get(id);
		// 车辆已完成班次
		int finish = dayOfSchedule.doneSum(sch.getClZbh());
		return send60Dispatch(sch, finish, sender);
	}

	@Override
	public int send60Operation(String nbbm, int state, int upDown, ScheduleRealInfo sch, String sender) {
		logger.info("切换运营状态, nbbm: " + nbbm + " ,state: " + state + " ,upDown:" + upDown);

		String text = "切换为 " + (upDown == 0 ? "上行" : "下行") + (state == 0 ? "营运" : "未营运");
		D60 d60 = new DirectiveCreator().createD60(nbbm, text, (short) 0x03, upDown, state);

		if (null == d60)
			return -1;
		if(null != sender)
			d60.setSender(sender);
		else
			d60.setSender("系统");
		// 发送指令
		int code = GatewayHttpUtils.postJson(JSON.toJSONString(d60));
		// 添加到缓存,等待入库
		d60.setHttpCode(code);
		if (null != sch)
			d60.setSch(sch);
		dayOfDirectives.put60(d60);

		if (code != 0) {
			d60.setErrorText("网关通讯失败, code: " + code);
			d60Repository.save(d60);
		}
		return code;
	}

	/**
	 * 线路切换
	 */
	@Override
	public int lineChange(String nbbm, String lineCode, String sender) {
		DirectiveCreator crt = new DirectiveCreator();
		
		Long t = System.currentTimeMillis();
		//生成64数据包
		D64 d64 = crt.createD64(nbbm, lineCode, t);
		
		if(null != sender)
			d64.setSender(sender);
		else
			d64.setSender("系统");

		String deviceId = d64.getDeviceId();
		int code = GatewayHttpUtils.postJson(JSON.toJSONString(d64));
		// 入库
		d64.setHttpCode(code);
		d64.getData().setTxtContent("切换线路[" + lineCode + "]");
		dayOfDirectives.put64(d64);

		// 通知设备刷新线路文件,忽略结果
		if (code == 0)
			GatewayHttpUtils.postJson(crt.createDeviceRefreshData(deviceId, lineCode));
		else
			d64.setErrorText(" 网关通讯失败, code: " + code);

		d64Repository.save(d64);
		return code;
	}

	public D60 create60Data(String nbbm, String text, Short dispatchInstruct, ScheduleRealInfo sch) {

		String deviceId = BasicData.deviceId2NbbmMap.inverse().get(nbbm);
		if (null == deviceId) {
			logger.error("没有设备号对照的车辆:" + nbbm);
			return null;
		}
		// 根据当前GPS确定 上下行和营运状态
		Integer upDown = null, state = null;
		if (null == sch) {
			GpsEntity gpsData = gpsRealDataBuffer.findByDeviceId(deviceId);
			if (null == gpsData) {
				/*
				 * 短语指令不会变更设备状态,所以在没有gps状态对照的情况下可以下发
				 * 其他指令在不确定状态的情况下,一律不允许
				 */
				if(dispatchInstruct == 0){
					upDown = 0;
					state = 0;
				}
				else{
					logger.error("没有找到gps对照,无法确认营运状态和上下行:" + nbbm);
					return null;
				}
			}
			else{
				upDown = gpsData.getUpDown();
				state = gpsData.getState();
			}
		} else {
			upDown = Integer.parseInt(sch.getXlDir());
			state = 0;
		}

		return new DirectiveCreator().createD60(nbbm, text, dispatchInstruct, upDown, state);
	}

	@Override
	public int upDownChange(String nbbm, Integer upDown, String sender) {
		return send60Operation(nbbm, 0, upDown, null, sender);
	}


	@Override
	public Map<String, List<D80>> findNoCofm80(String lineCodes) {
		List<String> lineList = Splitter.on(",").trimResults().splitToList(lineCodes);

		Map<String, List<D80>> rs = new HashMap<>();
		for (String code : lineList) 
			rs.put(code, pilotReport.unconfirmed80(Integer.parseInt(code)));

		return rs;
	}

	@Override
	public Map<String, Object> reply80(int id, int reply) {
		Map<String, Object> rs = new HashMap<>();

		D80 d80 = pilotReport.findById(id);
		if (null == d80) {
			rs.put("status", ResponseCode.ERROR);
			rs.put("msg", "服务器没有找到对应数据!");
		} else if (d80.isConfirm()) {
			rs.put("status", ResponseCode.ERROR);
			rs.put("msg", "该数据已经被处理了!");
		} else {
			SysUser user = SecurityUtils.getCurrentUser();
			d80.setC0(reply, user.getUserName());
			// 入库
			d80Repository.save(d80);
			//回复网关
			int code = GatewayHttpUtils.postJson(JSON.toJSONString(d80.getC0()));

			rs.put("status", ResponseCode.SUCCESS);
			if (code != 0)
				rs.put("msg", "发送C0响应指令到车载设备失败,但该操作已经被系统记录!");

			pilotReport.reply(d80);
			// 通知页面
			Map<String, Object> sockMap = new HashMap<>();
			sockMap.put("fn", "d80Confirm");
			sockMap.put("id", d80.getId());
			socketHandler.sendMessageToLine(d80.getData().getLineId().toString(), JSON.toJSONString(sockMap));
		}

		return rs;
	}

	@Override
	public Map<String, Object> findDirective(String nbbm, int dType, int page, int size) {
		Map<String, Object> rsMap = new HashMap<>();
		List<Directive> list = new ArrayList<>();
		
		switch (dType) {
		case -1:
			//所有指令
			list = new ArrayList<>(dayOfDirectives.all());
			break;
		case 0:
			//调度指令
			Collection<D60> dptArray = dayOfDirectives.all60();
			for(D60 d60 : dptArray){
				if(d60.isDispatch())
					list.add(d60);
			}
			break;
		case 1: 
			//运营指令
			Collection<D60> yyArray = dayOfDirectives.all60();
			for(D60 d60 : yyArray){
				if(d60 != null && d60.getData().getDispatchInstruct() == (short)0x03
						&& !d60.isDispatch())
					list.add(d60);
			}
			break;
		case 2:
			//线路切换指令
			list.addAll(dayOfDirectives.all64());
			break;
		case 3:
			//消息短语
			Collection<D60> dyArray = dayOfDirectives.all60();
			for(D60 d60 : dyArray){
				if(d60 != null && d60.getData().getDispatchInstruct() == (short)0x00
						&& !d60.isDispatch())
					list.add(d60);
			}
			break;
		}

		// 时间倒序
		Collections.sort(list, new DayOfDirectives.DComparator());
		if(StringUtils.isNotBlank(nbbm)){
			String deviceId = BasicData.deviceId2NbbmMap.inverse().get(nbbm);
			//按车辆过滤
			List<Directive> subList = new ArrayList<>();
			for(Directive d : list){
				if(d.getDeviceId().equals(deviceId)){
					subList.add(d);
				}
			}
			list = subList;
		}
		
		int count = list.size();
		// 分页
		int s = page * size, e = s + size;

		if (e > count)
			e = count;

		List<Directive> rs = list.subList(s, e);

		// 时间格式化,车辆自编号转换
		for (Directive d : rs) {
			if (d.getTimeHHmm() == null)
				d.setTimeHHmm(fmtHHmm.print(d.getTimestamp()));
			if (d.getNbbm() == null)
				d.setNbbm(BasicData.deviceId2NbbmMap.get(d.getDeviceId()));
		}

		rsMap.put("list", rs);
		rsMap.put("totalPages", count % size == 0 ? (count / size - 1) : count / size);
		rsMap.put("page", page);
		return rsMap;
	}

	@Override
	public Map<String, Object> findAll80(Map<String, Object> map, int page, int size) {
		List<D80> d80s = new ArrayList<>();
		
		Object nbbm = map.get("nbbm");
		if(null != nbbm && StringUtils.isNotEmpty(nbbm.toString())){
			d80s.addAll(pilotReport.findByCar(nbbm.toString()));
		}
		else{
			d80s.addAll(pilotReport.findAll());
		}
		
		Short requestCode = Short.parseShort(map.get("requestCode").toString());
		if(requestCode != -1){
			List<D80> temps = new ArrayList<>();
			for(D80 d80 : d80s){
				if(d80.getData().getRequestCode().equals(requestCode))
					temps.add(d80);
			}
			d80s = temps;
		}
		
		//排序
		Collections.sort(d80s, new Comparator<D80>() {
			@Override
			public int compare(D80 o1, D80 o2) {
				return (int) (o2.getTimestamp() - o1.getTimestamp());
			}
		});
		
		//分页
		int count = d80s.size();
		// 分页
		int s = page * size, e = s + size;

		if (e > count)
			e = count;

		//SimpleDateFormat sdfHHmm = new SimpleDateFormat("HH:mm");
		List<D80> rs = d80s.subList(s, e);
		for(D80 d80 : rs){
			d80.setTimeStr(fmtHHmm.print(d80.getTimestamp()));
		}
		
		Map<String, Object> rsMap = new HashMap<>();
		rsMap.put("list", rs);
		rsMap.put("totalPages", count % size == 0 ? count / size : count / size + 1);
		rsMap.put("page", page);
		
		return rsMap;
	}

	@Override
	public D64 save64(D64 d64) {
		return d64Repository.save(d64);
	}

	@Override
	public int sendC0A4(String nbbm) {
		String deviceId = BasicData.deviceId2NbbmMap.inverse().get(nbbm);
		
		Map<String, Object> c0a4 = new HashMap<>();
		c0a4.put("deviceId", deviceId);
		c0a4.put("timestamp", System.currentTimeMillis());
		c0a4.put("operCode", (short)0xC0);
		
		Map<String, Object> data = new HashMap<>();
		data.put("deviceId", deviceId);
		data.put("operCode2", (short)0xA4);
		c0a4.put("data", data);
		
		return GatewayHttpUtils.postJson(JSON.toJSONString(c0a4));
	}

	@Override
	public int sendC0A3(DC0_A3 c0a3) {
		GatewayHttpUtils.postJson(JSON.toJSONString(c0a3));
		return 0;
	}

	@Override
	public int sendC0A5(String json) {
		return GatewayHttpUtils.postJson(json);
	}
}