Commit 1b0f2cfd authored by caotao's avatar caotao

1.重写车辆轨迹生成逻辑。

2.车辆超速信息增加分页功能。
parent c531aa85
......@@ -1475,8 +1475,8 @@ public class CarController extends AbstractBaseController {
@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
@RequestMapping(value = "/getCarWarningRecord", method = RequestMethod.GET)
@ApiOperation(httpMethod = "GET", value = "车辆统计-获取超速信息", notes = "车辆统计-获取超速信息")
public Page<CarSpeedWarningRecord> getCarWarningRecord(@RequestParam(required = false) String keyWord,@RequestParam String flag) {
return iCarService.getCarWarningRecord(keyWord);
public BasicTableDataDto getCarWarningRecord(@RequestParam(required = false) String keyWord,@RequestParam Integer current, @RequestParam Integer size) {
return iCarService.getCarWarningRecord(keyWord,current,size);
}
@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
@RequestMapping(value = "/getBizOrgName", method = RequestMethod.GET)
......
package com.yeejoin.equipmanage.initbean;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yeejoin.equipmanage.common.entity.Car;
import com.yeejoin.equipmanage.common.entity.WlCarMileage;
import com.yeejoin.equipmanage.service.ICarService;
import com.yeejoin.equipmanage.service.impl.WlCarMileageServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.TimeUnit;
@Component
@Slf4j
public class JxiopCarReCountTimeBean {
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private WlCarMileageServiceImpl wlCarMileageServiceImpl;
@Autowired
private ICarService iCarService;
@PostConstruct
public void reCountTime() {
log.info("---------------------车辆重新开始计时::开始-------------------------");
List<WlCarMileage> wlCarMileageList = wlCarMileageServiceImpl.list(new QueryWrapper<WlCarMileage>().isNull("end_time"));
for (int i = 0; i < wlCarMileageList.size(); i++) {
Car car = iCarService.getOne(new QueryWrapper<Car>().eq("iot_code", wlCarMileageList.get(i).getIotCode()));
if(ObjectUtils.isNotEmpty(car)){
String coordinate = String.valueOf(car.getLongitude()) + "," + String.valueOf(car.getLatitude());
redisTemplate.opsForValue().set(car.getIotCode(), coordinate, 10, TimeUnit.MINUTES);
}
}
log.info("---------------------车辆重新开始计时::结束-------------------------");
}
}
......@@ -13,7 +13,7 @@ import com.yeejoin.equipmanage.fegin.IotFeign;
import com.yeejoin.equipmanage.mapper.WlCarSpeedWaringRecordMapper;
import com.yeejoin.equipmanage.service.ICarService;
import com.yeejoin.equipmanage.service.IWlCarMileageService;
import com.yeejoin.equipmanage.thread.ThreadCar;
import com.yeejoin.equipmanage.service.impl.JxiopCarIotListerServiceImpl;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
......@@ -39,34 +39,36 @@ import java.util.concurrent.ConcurrentHashMap;
@Component
public class CarIotNewListener extends EmqxListener {
Logger logger = LoggerFactory.getLogger(CarIotNewListener.class);
@Autowired
private IWlCarMileageService iWlCarMileageService;
@Autowired
private ICarService iCarService;
@Autowired
private IotFeign iotFeign;
@Autowired
private WlCarSpeedWaringRecordMapper wlCarSpeedWaringRecordMapper;
@Value("${mileage.clippingtime:600000}")
private Long clipping_time;
@Value("${default.maxspeed:70.0}")
private Double defaultMaxSpeed;
private final String GUIDE_KEY = "813684495d9a3981dd2c7694916fe404";
private final String GUIDE_URL = "https://restapi.amap.com/v3/geocode/regeo?";
@Autowired
private EmqKeeper emqkeeper;
private JxiopCarIotListerServiceImpl jxiopCarIotListerServiceImpl;
private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 用于根据topicId 也就是物联设备id 存储对应的线程来进行计时
public static final ConcurrentHashMap<String, ThreadCar> deviceInfo = new ConcurrentHashMap();
public static final ConcurrentHashMap<String, String> deviceLastInfo = new ConcurrentHashMap();
// @Autowired
// private IWlCarMileageService iWlCarMileageService;
//
// @Autowired
// private ICarService iCarService;
//
// @Autowired
// private IotFeign iotFeign;
// @Autowired
// private WlCarSpeedWaringRecordMapper wlCarSpeedWaringRecordMapper;
// @Value("${mileage.clippingtime:600000}")
// private Long clipping_time;
//
// @Value("${default.maxspeed:70.0}")
// private Double defaultMaxSpeed;
// private final String GUIDE_KEY = "813684495d9a3981dd2c7694916fe404";
//
// private final String GUIDE_URL = "https://restapi.amap.com/v3/geocode/regeo?";
//
// @Autowired
// private EmqKeeper emqkeeper;
//
// private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//
// // 用于根据topicId 也就是物联设备id 存储对应的线程来进行计时
// public static final ConcurrentHashMap<String, ThreadCar> deviceInfo = new ConcurrentHashMap();
// public static final ConcurrentHashMap<String, String> deviceLastInfo = new ConcurrentHashMap();
@Override
@Async
......@@ -74,198 +76,200 @@ public class CarIotNewListener extends EmqxListener {
logger.info("----收到物联消息::topic---------------" + topic);
logger.info("----收到物联消息::message---------------" + message);
String measurement = topic.split("/")[0];
String deviceName = topic.split("/")[1];
//根据topic 组装iotCode
String iotCode = measurement + deviceName;
//对于收到的消息进行数据转换
JSONObject jsonObject = JSONObject.parseObject(message.toString());
//通过消息存电量到扩展字段2
this.updateEquipBattery(jsonObject, iotCode);
logger.info("当前设备信息info" + JSON.toJSONString(deviceInfo));
//判断是否有效坐标
if (!ObjectUtils.isEmpty(jsonObject.get("FireCar_Longitude")) && !ObjectUtils.isEmpty(jsonObject.get("FireCar_Latitude"))) {
//判断是否存在未结束进程,如果不存在,则进入判断插入开始节点
if (iWlCarMileageService.getUncompleteMileagByIotCode(iotCode)) {
WlCarMileage wlCarMileage = new WlCarMileage();
wlCarMileage.setIotCode(iotCode);
wlCarMileage.setDate(new Date());
// 获取开始坐标
double startLongitude = jsonObject.getDoubleValue("FireCar_Longitude");
double startLatitude = jsonObject.getDoubleValue("FireCar_Latitude");
// String currentTime = "20"+jsonObject.getString("currentTime");
wlCarMileage.setStartLongitude(startLongitude);
wlCarMileage.setStartLatitude(startLatitude);
// Date startTime = UTCToCST();
//时间值被mysql自动转换
Date startTime = new Date((jsonObject.getLong("time") / 1000) * 1000);
wlCarMileage.setStartTime(startTime);
wlCarMileage.setStartName(getAddress(startLongitude, startLatitude));
wlCarMileage.setStartSpeed(Double.valueOf(jsonObject.getDoubleValue("FireCar_Speed")).intValue());
logger.info("新增数据信息如下::" + JSONObject.toJSONString(wlCarMileage));
try {
iWlCarMileageService.save(wlCarMileage);
} catch (Exception e) {
e.printStackTrace();
iWlCarMileageService.save(wlCarMileage);
}
}
this.updateCarLocation(jsonObject, iotCode);
//如果map中已经存在该设备或者该设备有但是线程已经执行了
//存储上报上来的经纬度信息
String coordinate = jsonObject.getString("FireCar_Longitude")+ jsonObject.getString("FireCar_Latitude");
logger.info("----收到经纬度消息::coordinate---------------" + coordinate);
//判断缓存中是否已经存在该设备对应的倒计时线程
if (!deviceInfo.containsKey(iotCode)) {
logger.info("topic---------------------" + topic + "开启计时线程");
ThreadCar threadCar = new ThreadCar(topic, jsonObject, this.iWlCarMileageService, this.iotFeign, this.iCarService, clipping_time);
deviceInfo.put(iotCode, threadCar);
threadCar.start();
}
//判断缓存中是否已经存在该设备对应的经纬度信息
if (!deviceLastInfo.containsKey(iotCode)) {
deviceLastInfo.put(iotCode, coordinate);
}
//如果当前时间减去上报时间大小于配置的时间并且之前没包含上报的数据
logger.info("----收到上次经纬度消息::coordinate---------------" + deviceLastInfo.get(iotCode));
//判断本次上报的经纬度信息是否与当前上报的经纬度信息相同
if ((!deviceLastInfo.get(iotCode).equals(coordinate))) {
try {
//销毁线程后移除
deviceInfo.get(iotCode).interrupt();
deviceInfo.remove(iotCode);
} catch (Exception e) {
deviceInfo.remove(iotCode);
}
logger.info("topic---------------------" + topic + "销毁后,开启计时线程");
ThreadCar threadCar = new ThreadCar(topic, jsonObject, this.iWlCarMileageService, this.iotFeign, this.iCarService, clipping_time);
deviceInfo.put(iotCode, threadCar);
//更新车辆的最新坐标数据
deviceLastInfo.put(iotCode, coordinate);
threadCar.start();
}
}
}
public String getAddress(double longitude, double lantitude) {
StringBuilder api = new StringBuilder(GUIDE_URL);
api.append("key=").append(GUIDE_KEY).append("&location=").append(longitude).append(",").append(lantitude).append("&radius=1000").append("&batch=false").append("&extensions=base").append("&roadlevel=0").append("&batch=false");
StringBuilder res = new StringBuilder();
BufferedReader in = null;
try {
System.out.println(api.toString());
URL url = new URL(api.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
res.append(line).append("\n");
}
JSONObject object = JSONObject.parseObject(res.toString());
System.out.println(object);
JSONObject regeocode = object.getJSONObject("regeocode");
String address = regeocode.getString("formatted_address");
if ("[]".equals(address)) {
logger.info("===============无效坐标:" + longitude + "," + lantitude);
address = "无效坐标";
}
res = new StringBuilder(address);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return res.toString();
}
jxiopCarIotListerServiceImpl.processMessage(topic,message);
// String measurement = topic.split("/")[0];
// String deviceName = topic.split("/")[1];
// //根据topic 组装iotCode
// String iotCode = measurement + deviceName;
// //对于收到的消息进行数据转换
// JSONObject jsonObject = JSONObject.parseObject(message.toString());
// //通过消息存电量到扩展字段2
// this.updateEquipBattery(jsonObject, iotCode);
// logger.info("当前设备信息info" + JSON.toJSONString(deviceInfo));
// //判断是否有效坐标
// if (!ObjectUtils.isEmpty(jsonObject.get("FireCar_Longitude")) && !ObjectUtils.isEmpty(jsonObject.get("FireCar_Latitude"))) {
// //判断是否存在未结束进程,如果不存在,则进入判断插入开始节点
// if (iWlCarMileageService.getUncompleteMileagByIotCode(iotCode)) {
// WlCarMileage wlCarMileage = new WlCarMileage();
// wlCarMileage.setIotCode(iotCode);
// wlCarMileage.setDate(new Date());
// // 获取开始坐标
// double startLongitude = jsonObject.getDoubleValue("FireCar_Longitude");
// double startLatitude = jsonObject.getDoubleValue("FireCar_Latitude");
// // String currentTime = "20"+jsonObject.getString("currentTime");
// wlCarMileage.setStartLongitude(startLongitude);
// wlCarMileage.setStartLatitude(startLatitude);
// // Date startTime = UTCToCST();
// //时间值被mysql自动转换
// Date startTime = new Date((jsonObject.getLong("time") / 1000) * 1000);
// wlCarMileage.setStartTime(startTime);
// wlCarMileage.setStartName(getAddress(startLongitude, startLatitude));
// wlCarMileage.setStartSpeed(Double.valueOf(jsonObject.getDoubleValue("FireCar_Speed")).intValue());
// logger.info("新增数据信息如下::" + JSONObject.toJSONString(wlCarMileage));
// try {
// iWlCarMileageService.save(wlCarMileage);
// } catch (Exception e) {
// e.printStackTrace();
// iWlCarMileageService.save(wlCarMileage);
// }
// }
// this.updateCarLocation(jsonObject, iotCode);
// //如果map中已经存在该设备或者该设备有但是线程已经执行了
// //存储上报上来的经纬度信息
// String coordinate = jsonObject.getString("FireCar_Longitude")+ jsonObject.getString("FireCar_Latitude");
// logger.info("----收到经纬度消息::coordinate---------------" + coordinate);
// //判断缓存中是否已经存在该设备对应的倒计时线程
// if (!deviceInfo.containsKey(iotCode)) {
// logger.info("topic---------------------" + topic + "开启计时线程");
// ThreadCar threadCar = new ThreadCar(topic, jsonObject, this.iWlCarMileageService, this.iotFeign, this.iCarService, clipping_time);
// deviceInfo.put(iotCode, threadCar);
// threadCar.start();
// }
// //判断缓存中是否已经存在该设备对应的经纬度信息
// if (!deviceLastInfo.containsKey(iotCode)) {
// deviceLastInfo.put(iotCode, coordinate);
// }
// //如果当前时间减去上报时间大小于配置的时间并且之前没包含上报的数据
// logger.info("----收到上次经纬度消息::coordinate---------------" + deviceLastInfo.get(iotCode));
// //判断本次上报的经纬度信息是否与当前上报的经纬度信息相同
// if ((!deviceLastInfo.get(iotCode).equals(coordinate))) {
// try {
// //销毁线程后移除
// deviceInfo.get(iotCode).interrupt();
// deviceInfo.remove(iotCode);
// } catch (Exception e) {
// deviceInfo.remove(iotCode);
// }
// logger.info("topic---------------------" + topic + "销毁后,开启计时线程");
// ThreadCar threadCar = new ThreadCar(topic, jsonObject, this.iWlCarMileageService, this.iotFeign, this.iCarService, clipping_time);
// deviceInfo.put(iotCode, threadCar);
// //更新车辆的最新坐标数据
// deviceLastInfo.put(iotCode, coordinate);
// threadCar.start();
// }
// }
public Date UTCToCST(String UTCStr) throws ParseException {
Date date = sdf.parse(UTCStr);
System.out.println("UTC时间: " + date);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR, calendar.get(Calendar.HOUR) + 8);
return calendar.getTime();
}
public void updateCarLocation(JSONObject jsonObject, String iotCode) {
if (jsonObject.containsKey("FireCar_Longitude") && jsonObject.containsKey("FireCar_Latitude")) {
// 获取开始坐标
double startLongitude = jsonObject.getDoubleValue("FireCar_Longitude");
double startLatitude = jsonObject.getDoubleValue("FireCar_Latitude");
int direction = jsonObject.getIntValue("direction");
String waringDate = jsonObject.getString("createdTime");
Double speed=jsonObject.getDoubleValue("fireCar_Speed")>0?jsonObject.getDoubleValue("fireCar_Speed"):jsonObject.getDoubleValue("FireCar_Speed");
Double maxSpeed = defaultMaxSpeed;
// 地图推送消息
Car car = iCarService.getOne(new LambdaQueryWrapper<Car>().eq(Car::getIotCode, iotCode));
if (car != null && startLongitude != 0 && startLatitude != 0) {
JSONArray sendArr = new JSONArray();
JSONObject sendObj = new JSONObject();
sendObj.put("id", String.valueOf(car.getId()));
sendObj.put("direction", direction);
sendObj.put("longitude", String.valueOf(startLongitude));
sendObj.put("latitude", String.valueOf(startLatitude));
sendObj.put("carNum", car.getCarNum());
sendObj.put("bizOrgName", car.getBizOrgName());
sendArr.add(sendObj);
MqttMessage mqttMessage = new MqttMessage();
mqttMessage.setPayload(sendArr.toJSONString().getBytes());
car.setLongitude(startLongitude);
car.setLatitude(startLatitude);
if(!ObjectUtils.isEmpty(car.getMaxSpeed())){
maxSpeed =car.getMaxSpeed();
}
iCarService.updateById(car);
logger.info("车牌号::"+car.getCarNum()+"最大车速:"+car.getMaxSpeed()+"当前车速::"+speed);
if(speed > maxSpeed){
CarSpeedWarningRecord carSpeedWarningRecord = new CarSpeedWarningRecord();
carSpeedWarningRecord.setCarNum(car.getCarNum());
carSpeedWarningRecord.setDriver(car.getDriver());
carSpeedWarningRecord.setPhone(car.getPhone());
carSpeedWarningRecord.setOverSpeed(speed-maxSpeed);
carSpeedWarningRecord.setOwnership(car.getOwnership());
carSpeedWarningRecord.setBizOrgName(car.getBizOrgName());
carSpeedWarningRecord.setWaringDate(DateUtil.parse(waringDate, DatePattern.NORM_DATETIME_PATTERN));
wlCarSpeedWaringRecordMapper.insert(carSpeedWarningRecord);
logger.info("-----------触发车辆超速告警成功--------");
}
logger.info("-----------推送车辆位置消息到到地图成功--------");
try {
emqkeeper.getMqttClient().publish("car/location", mqttMessage);
} catch (MqttException e) {
throw new RuntimeException(e);
}
}
}
}
// public String getAddress(double longitude, double lantitude) {
// StringBuilder api = new StringBuilder(GUIDE_URL);
// api.append("key=").append(GUIDE_KEY).append("&location=").append(longitude).append(",").append(lantitude).append("&radius=1000").append("&batch=false").append("&extensions=base").append("&roadlevel=0").append("&batch=false");
// StringBuilder res = new StringBuilder();
// BufferedReader in = null;
// try {
// System.out.println(api.toString());
// URL url = new URL(api.toString());
// HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// conn.setDoOutput(true);
// conn.setRequestMethod("POST");
// in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
// String line;
// while ((line = in.readLine()) != null) {
// res.append(line).append("\n");
// }
// JSONObject object = JSONObject.parseObject(res.toString());
// System.out.println(object);
// JSONObject regeocode = object.getJSONObject("regeocode");
// String address = regeocode.getString("formatted_address");
// if ("[]".equals(address)) {
// logger.info("===============无效坐标:" + longitude + "," + lantitude);
// address = "无效坐标";
// }
// res = new StringBuilder(address);
// } catch (Exception e) {
// e.printStackTrace();
// } finally {
// try {
// if (in != null) {
// in.close();
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// return res.toString();
// }
//存储设备电量到扩展字段2
public void updateEquipBattery(JSONObject jsonObject, String iotCode) {
Integer power = 0;
if (jsonObject.containsKey("additionalInformations") && jsonObject.get("additionalInformations") != null) {
JSONObject jsonObject1 = JSONObject.parseObject(jsonObject.get("additionalInformations").toString());
if (jsonObject1 != null) {
JSONObject jsonObject2 = JSONObject.parseObject(jsonObject1.get("additionalInformations").toString());
if (jsonObject2 != null && jsonObject2.containsKey("power")) {
power = jsonObject2.getInteger("power");
}
}
}
// public Date UTCToCST(String UTCStr) throws ParseException {
// Date date = sdf.parse(UTCStr);
// System.out.println("UTC时间: " + date);
// Calendar calendar = Calendar.getInstance();
// calendar.setTime(date);
// calendar.set(Calendar.HOUR, calendar.get(Calendar.HOUR) + 8);
// return calendar.getTime();
// }
//
// public void updateCarLocation(JSONObject jsonObject, String iotCode) {
// if (jsonObject.containsKey("FireCar_Longitude") && jsonObject.containsKey("FireCar_Latitude")) {
// // 获取开始坐标
// double startLongitude = jsonObject.getDoubleValue("FireCar_Longitude");
// double startLatitude = jsonObject.getDoubleValue("FireCar_Latitude");
// int direction = jsonObject.getIntValue("direction");
// String waringDate = jsonObject.getString("createdTime");
// Double speed=jsonObject.getDoubleValue("fireCar_Speed")>0?jsonObject.getDoubleValue("fireCar_Speed"):jsonObject.getDoubleValue("FireCar_Speed");
// Double maxSpeed = defaultMaxSpeed;
// // 地图推送消息
// Car car = iCarService.getOne(new LambdaQueryWrapper<Car>().eq(Car::getIotCode, iotCode));
// if (car != null && startLongitude != 0 && startLatitude != 0) {
// JSONArray sendArr = new JSONArray();
// JSONObject sendObj = new JSONObject();
// sendObj.put("id", String.valueOf(car.getId()));
// sendObj.put("direction", direction);
// sendObj.put("longitude", String.valueOf(startLongitude));
// sendObj.put("latitude", String.valueOf(startLatitude));
// sendObj.put("carNum", car.getCarNum());
// sendObj.put("bizOrgName", car.getBizOrgName());
// sendArr.add(sendObj);
// MqttMessage mqttMessage = new MqttMessage();
// mqttMessage.setPayload(sendArr.toJSONString().getBytes());
// car.setLongitude(startLongitude);
// car.setLatitude(startLatitude);
// if(!ObjectUtils.isEmpty(car.getMaxSpeed())){
// maxSpeed =car.getMaxSpeed();
// }
// iCarService.updateById(car);
// logger.info("车牌号::"+car.getCarNum()+"最大车速:"+car.getMaxSpeed()+"当前车速::"+speed);
// if(speed > maxSpeed){
// CarSpeedWarningRecord carSpeedWarningRecord = new CarSpeedWarningRecord();
// carSpeedWarningRecord.setCarNum(car.getCarNum());
// carSpeedWarningRecord.setDriver(car.getDriver());
// carSpeedWarningRecord.setPhone(car.getPhone());
// carSpeedWarningRecord.setOverSpeed(speed-maxSpeed);
// carSpeedWarningRecord.setOwnership(car.getOwnership());
// carSpeedWarningRecord.setBizOrgName(car.getBizOrgName());
// carSpeedWarningRecord.setWaringDate(DateUtil.parse(waringDate, DatePattern.NORM_DATETIME_PATTERN));
// wlCarSpeedWaringRecordMapper.insert(carSpeedWarningRecord);
// logger.info("-----------触发车辆超速告警成功--------");
// }
// logger.info("-----------推送车辆位置消息到到地图成功--------");
// try {
// emqkeeper.getMqttClient().publish("car/location", mqttMessage);
// } catch (MqttException e) {
// throw new RuntimeException(e);
// }
// }
// }
// }
Car car = iCarService.getOne(new LambdaQueryWrapper<Car>().eq(Car::getIotCode, iotCode));
if (car != null && power != 0) {
car.setExtra2(power.toString());
iCarService.updateById(car);
logger.info(iotCode+"-----------更新车辆设备电池电量成功--------");
}
}
// //存储设备电量到扩展字段2
// public void updateEquipBattery(JSONObject jsonObject, String iotCode) {
// Integer power = 0;
// if (jsonObject.containsKey("additionalInformations") && jsonObject.get("additionalInformations") != null) {
// JSONObject jsonObject1 = JSONObject.parseObject(jsonObject.get("additionalInformations").toString());
// if (jsonObject1 != null) {
// JSONObject jsonObject2 = JSONObject.parseObject(jsonObject1.get("additionalInformations").toString());
// if (jsonObject2 != null && jsonObject2.containsKey("power")) {
// power = jsonObject2.getInteger("power");
// }
// }
// }
//
// Car car = iCarService.getOne(new LambdaQueryWrapper<Car>().eq(Car::getIotCode, iotCode));
// if (car != null && power != 0) {
// car.setExtra2(power.toString());
// iCarService.updateById(car);
// logger.info(iotCode+"-----------更新车辆设备电池电量成功--------");
// }
// }
}
......@@ -2,6 +2,9 @@ package com.yeejoin.equipmanage.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.yeejoin.equipmanage.common.entity.CarSpeedWarningRecord;
import org.apache.ibatis.annotations.Select;
public interface WlCarSpeedWaringRecordMapper extends BaseMapper<CarSpeedWarningRecord> {
@Select("select count(1) from wl_car_speed_warning_record")
Integer getCountOfRecords();
}
......@@ -202,7 +202,7 @@ public interface ICarService extends IService<Car> {
List<CarExportDto> exportCarMileageInfoByMoth(String date,String keyWord);
ZZChartsDto getCarMileageInfoByMothOFDay(String iotCode);
Page<CarExceptionDto> getCarExcepitonTrack(Integer type,String keyWord);
Page<CarSpeedWarningRecord> getCarWarningRecord(String keyWord);
BasicTableDataDto getCarWarningRecord(String keyWord,Integer current, Integer pageSize);
List<Map<String,String>> getBizOrgName();
/**
......
......@@ -1709,7 +1709,7 @@ public class CarServiceImpl extends ServiceImpl<CarMapper, Car> implements ICarS
LocalDate localDate = LocalDate.now(ZoneId.of("+8"));
String endDate = localDate.toString();
String startDate = localDate.plusDays((0 - type)).toString();
List<Car> list =carMapper.selectList(new QueryWrapper<>()) ;
List<Car> list = carMapper.selectList(new QueryWrapper<>());
if (StringUtils.isNotEmpty(keyWord)) {
list = list.stream().filter(car -> car.getBizOrgName().contains(keyWord)).collect(Collectors.toList());
}
......@@ -1734,22 +1734,29 @@ public class CarServiceImpl extends ServiceImpl<CarMapper, Car> implements ICarS
}
@Override
public Page<CarSpeedWarningRecord> getCarWarningRecord(String keyWord) {
public BasicTableDataDto getCarWarningRecord(String keyWord, Integer current, Integer pageSize) {
BasicTableDataDto basicTableDataDto=new BasicTableDataDto();
Page<CarSpeedWarningRecord> carSpeedWarningRecordPage = new Page<>();
List<ColModel> colModels = new ArrayList<>();
colModels.add(new ColModel("carNum", "车牌号"));
colModels.add(new ColModel("bizOrgName", "所属单位"));
colModels.add(new ColModel("waringDate", "超速时间"));
colModels.add(new ColModel("overSpeed", "超速值(Km/h)"));
Date date = new Date();
String endTime = DateUtil.format(date, DatePattern.NORM_DATETIME_FORMAT);
date = DateUtil.offsetDay(date, -15);
date = DateUtil.offsetDay(date, -5);
String startTime = DateUtil.format(date, DatePattern.NORM_DATETIME_FORMAT);
List<CarSpeedWarningRecord> list = wlCarSpeedWaringRecordMapper.selectList(new QueryWrapper<CarSpeedWarningRecord>().ge("waring_date", startTime).le("waring_date", endTime));
QueryWrapper queryWrapper = new QueryWrapper<CarSpeedWarningRecord>();
if (StringUtils.isNotEmpty(keyWord)) {
list = list.stream().filter(carSpeedWarningRecord -> carSpeedWarningRecord.getBizOrgName().contains(keyWord) || carSpeedWarningRecord.getOwnership().contains(keyWord)).collect(Collectors.toList());
}
Collections.sort(list, (e1, e2) -> e2.getOverSpeed().compareTo(e1.getOverSpeed()));
carSpeedWarningRecordPage.setRecords(list);
carSpeedWarningRecordPage.setTotal(list.size());
carSpeedWarningRecordPage.setSize(1);
carSpeedWarningRecordPage.setCurrent(1);
return carSpeedWarningRecordPage;
queryWrapper.like("biz_org_name", keyWord);
}
queryWrapper.orderByDesc("over_speed");
queryWrapper.last("limit "+ (current-1)*pageSize+","+current*pageSize);
List<CarSpeedWarningRecord> list = wlCarSpeedWaringRecordMapper.selectList(queryWrapper);
DataGridMock dataGridMock = new DataGridMock(current,wlCarSpeedWaringRecordMapper.getCountOfRecords(),true,current,list);
basicTableDataDto.setDataGridMock(dataGridMock);
basicTableDataDto.setColModel(colModels);
return basicTableDataDto;
}
@Override
......
package com.yeejoin.equipmanage.service.impl;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yeejoin.equipmanage.common.entity.Car;
import com.yeejoin.equipmanage.common.entity.CarSpeedWarningRecord;
import com.yeejoin.equipmanage.common.entity.WlCarMileage;
import com.yeejoin.equipmanage.fegin.IotFeign;
import com.yeejoin.equipmanage.mapper.WlCarSpeedWaringRecordMapper;
import com.yeejoin.equipmanage.service.ICarService;
import com.yeejoin.equipmanage.service.IWlCarMileageService;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.typroject.tyboot.component.emq.EmqKeeper;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
@Service
public class JxiopCarIotListerServiceImpl {
private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private final String GUIDE_KEY = "813684495d9a3981dd2c7694916fe404";
private final String GUIDE_URL = "https://restapi.amap.com/v3/geocode/regeo?";
Logger logger = LoggerFactory.getLogger(JxiopCarIotListerServiceImpl.class);
@Autowired
private IWlCarMileageService iWlCarMileageService;
@Autowired
private ICarService iCarService;
@Autowired
private IotFeign iotFeign;
@Autowired
private WlCarSpeedWaringRecordMapper wlCarSpeedWaringRecordMapper;
@Value("${mileage.clippingtime:600000}")
private Long clipping_time;
@Value("${default.maxspeed:70.0}")
private Double defaultMaxSpeed;
@Autowired
private EmqKeeper emqkeeper;
@Autowired
private RedisTemplate redisTemplate;
// 用于根据topicId 也就是物联设备id 存储对应的线程来进行计时
// public static final ConcurrentHashMap<String, ThreadCar> deviceInfo = new ConcurrentHashMap();
// public static final ConcurrentHashMap<String, String> deviceLastInfo = new ConcurrentHashMap();
// @Async("equipAsyncExecutor")
public void processMessage(String topic, MqttMessage message) throws Exception {
logger.info("----收到物联消息::topic---------------" + topic);
logger.info("----收到物联消息::message---------------" + message);
String measurement = topic.split("/")[0];
String deviceName = topic.split("/")[1];
//根据topic 组装iotCode
String iotCode = measurement + deviceName;
//对于收到的消息进行数据转换
JSONObject jsonObject = JSONObject.parseObject(message.toString());
//通过消息存电量到扩展字段2
this.updateEquipBattery(jsonObject, iotCode);
// logger.info("当前设备信息info" + JSON.toJSONString(deviceInfo));
//判断是否有效坐标
if (!ObjectUtils.isEmpty(jsonObject.get("FireCar_Longitude")) && !ObjectUtils.isEmpty(jsonObject.get("FireCar_Latitude"))) {
//判断是否存在未结束进程,如果不存在,则进入判断插入开始节点
if (iWlCarMileageService.getUncompleteMileagByIotCode(iotCode)) {
WlCarMileage wlCarMileage = new WlCarMileage();
wlCarMileage.setIotCode(iotCode);
wlCarMileage.setDate(new Date());
// 获取开始坐标
double startLongitude = jsonObject.getDoubleValue("FireCar_Longitude");
double startLatitude = jsonObject.getDoubleValue("FireCar_Latitude");
// String currentTime = "20"+jsonObject.getString("currentTime");
wlCarMileage.setStartLongitude(startLongitude);
wlCarMileage.setStartLatitude(startLatitude);
// Date startTime = UTCToCST();
//时间值被mysql自动转换
Date startTime = new Date((jsonObject.getLong("time") / 1000) * 1000);
wlCarMileage.setStartTime(startTime);
wlCarMileage.setStartName(getAddress(startLongitude, startLatitude));
wlCarMileage.setStartSpeed(Double.valueOf(jsonObject.getDoubleValue("FireCar_Speed")).intValue());
logger.info("新增数据信息如下::" + JSONObject.toJSONString(wlCarMileage));
try {
iWlCarMileageService.save(wlCarMileage);
} catch (Exception e) {
e.printStackTrace();
iWlCarMileageService.save(wlCarMileage);
}
}
this.updateCarLocation(jsonObject, iotCode);
String coordinate = jsonObject.getString("FireCar_Longitude") + "," + jsonObject.getString("FireCar_Latitude");
if (!String.valueOf(redisTemplate.opsForValue().get(iotCode)).equals(coordinate)) {
redisTemplate.opsForValue().set(iotCode, coordinate, 10, TimeUnit.MINUTES);
}
//如果map中已经存在该设备或者该设备有但是线程已经执行了
//存储上报上来的经纬度信息
// logger.info("----收到经纬度消息::coordinate---------------" + coordinate);
//判断缓存中是否已经存在该设备对应的倒计时线程
// if (!deviceInfo.containsKey(iotCode)) {
// logger.info("topic---------------------" + topic + "开启计时线程");
// ThreadCar threadCar = new ThreadCar(topic, jsonObject, this.iWlCarMileageService, this.iotFeign, this.iCarService, clipping_time);
// deviceInfo.put(iotCode, threadCar);
// threadCar.start();
// }
//判断缓存中是否已经存在该设备对应的经纬度信息
// if (!deviceLastInfo.containsKey(iotCode)) {
// deviceLastInfo.put(iotCode, coordinate);
// }
//如果当前时间减去上报时间大小于配置的时间并且之前没包含上报的数据
// logger.info("----收到上次经纬度消息::coordinate---------------" + deviceLastInfo.get(iotCode));
//判断本次上报的经纬度信息是否与当前上报的经纬度信息相同
// if ((!deviceLastInfo.get(iotCode).equals(coordinate))) {
// try {
// //销毁线程后移除
// deviceInfo.get(iotCode).interrupt();
// deviceInfo.remove(iotCode);
// } catch (Exception e) {
// deviceInfo.remove(iotCode);
// }
// logger.info("topic---------------------" + topic + "销毁后,开启计时线程");
// ThreadCar threadCar = new ThreadCar(topic, jsonObject, this.iWlCarMileageService, this.iotFeign, this.iCarService, clipping_time);
// deviceInfo.put(iotCode, threadCar);
// //更新车辆的最新坐标数据
// deviceLastInfo.put(iotCode, coordinate);
// threadCar.start();
// }
}
}
public String getAddress(double longitude, double lantitude) {
StringBuilder api = new StringBuilder(GUIDE_URL);
api.append("key=").append(GUIDE_KEY).append("&location=").append(longitude).append(",").append(lantitude).append("&radius=1000").append("&batch=false").append("&extensions=base").append("&roadlevel=0").append("&batch=false");
StringBuilder res = new StringBuilder();
BufferedReader in = null;
try {
System.out.println(api.toString());
URL url = new URL(api.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
res.append(line).append("\n");
}
JSONObject object = JSONObject.parseObject(res.toString());
System.out.println(object);
JSONObject regeocode = object.getJSONObject("regeocode");
String address = regeocode.getString("formatted_address");
if ("[]".equals(address)) {
logger.info("===============无效坐标:" + longitude + "," + lantitude);
address = "无效坐标";
}
res = new StringBuilder(address);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return res.toString();
}
public Date UTCToCST(String UTCStr) throws ParseException {
Date date = sdf.parse(UTCStr);
System.out.println("UTC时间: " + date);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR, calendar.get(Calendar.HOUR) + 8);
return calendar.getTime();
}
public void updateCarLocation(JSONObject jsonObject, String iotCode) {
if (jsonObject.containsKey("FireCar_Longitude") && jsonObject.containsKey("FireCar_Latitude")) {
// 获取开始坐标
double startLongitude = jsonObject.getDoubleValue("FireCar_Longitude");
double startLatitude = jsonObject.getDoubleValue("FireCar_Latitude");
int direction = jsonObject.getIntValue("direction");
String waringDate = jsonObject.getString("createdTime");
Double speed = jsonObject.getDoubleValue("fireCar_Speed") > 0 ? jsonObject.getDoubleValue("fireCar_Speed") : jsonObject.getDoubleValue("FireCar_Speed");
Double maxSpeed = defaultMaxSpeed;
// 地图推送消息
Car car = iCarService.getOne(new LambdaQueryWrapper<Car>().eq(Car::getIotCode, iotCode));
if (car != null && startLongitude != 0 && startLatitude != 0) {
JSONArray sendArr = new JSONArray();
JSONObject sendObj = new JSONObject();
sendObj.put("id", String.valueOf(car.getId()));
sendObj.put("direction", direction);
sendObj.put("longitude", String.valueOf(startLongitude));
sendObj.put("latitude", String.valueOf(startLatitude));
sendObj.put("carNum", car.getCarNum());
sendObj.put("bizOrgName", car.getBizOrgName());
sendArr.add(sendObj);
MqttMessage mqttMessage = new MqttMessage();
mqttMessage.setPayload(sendArr.toJSONString().getBytes());
car.setLongitude(startLongitude);
car.setLatitude(startLatitude);
if (!ObjectUtils.isEmpty(car.getMaxSpeed())) {
maxSpeed = car.getMaxSpeed();
}
iCarService.updateById(car);
logger.info("车牌号::" + car.getCarNum() + "最大车速:" + car.getMaxSpeed() + "当前车速::" + speed);
if (speed > maxSpeed) {
List<CarSpeedWarningRecord> list = wlCarSpeedWaringRecordMapper.selectList(new QueryWrapper<CarSpeedWarningRecord>().eq("car_num",car.getCarNum()).between("waring_date",DateUtil.offsetMinute(new Date(),10),new Date()));
if(!(list.size() >0)) {
CarSpeedWarningRecord carSpeedWarningRecord = new CarSpeedWarningRecord();
carSpeedWarningRecord.setCarNum(car.getCarNum());
carSpeedWarningRecord.setDriver(car.getDriver());
carSpeedWarningRecord.setPhone(car.getPhone());
carSpeedWarningRecord.setOverSpeed(speed - maxSpeed);
carSpeedWarningRecord.setOwnership(car.getOwnership());
carSpeedWarningRecord.setBizOrgName(car.getBizOrgName());
carSpeedWarningRecord.setWaringDate(DateUtil.parse(waringDate, DatePattern.NORM_DATETIME_PATTERN));
wlCarSpeedWaringRecordMapper.insert(carSpeedWarningRecord);
logger.info("-----------触发车辆超速告警成功--------");
}
}
logger.info("-----------推送车辆位置消息到到地图成功--------");
try {
emqkeeper.getMqttClient().publish("car/location", mqttMessage);
} catch (MqttException e) {
throw new RuntimeException(e);
}
}
}
}
//存储设备电量到扩展字段2
public void updateEquipBattery(JSONObject jsonObject, String iotCode) {
Integer power = 0;
if (jsonObject.containsKey("additionalInformations") && jsonObject.get("additionalInformations") != null) {
JSONObject jsonObject1 = JSONObject.parseObject(jsonObject.get("additionalInformations").toString());
if (jsonObject1 != null) {
JSONObject jsonObject2 = JSONObject.parseObject(jsonObject1.get("additionalInformations").toString());
if (jsonObject2 != null && jsonObject2.containsKey("power")) {
power = jsonObject2.getInteger("power");
}
}
}
Car car = iCarService.getOne(new LambdaQueryWrapper<Car>().eq(Car::getIotCode, iotCode));
if (car != null && power != 0) {
car.setExtra2(power.toString());
iCarService.updateById(car);
logger.info(iotCode + "-----------更新车辆设备电池电量成功--------");
}
}
}
......@@ -13,13 +13,13 @@ import com.yeejoin.equipmanage.common.entity.WlCarMileage;
import com.yeejoin.equipmanage.common.utils.CoordinateUtil;
import com.yeejoin.equipmanage.common.utils.DateUtils;
import com.yeejoin.equipmanage.common.utils.HttpUtil;
import com.yeejoin.equipmanage.common.utils.RedisUtil;
import com.yeejoin.equipmanage.controller.Coordinate;
import com.yeejoin.equipmanage.fegin.IotFeign;
import com.yeejoin.equipmanage.listener.CarIotNewListener;
import com.yeejoin.equipmanage.mapper.WlCarMileageMapper;
import com.yeejoin.equipmanage.service.ICarService;
import com.yeejoin.equipmanage.service.IWlCarMileageService;
import com.yeejoin.equipmanage.thread.ThreadCarMileageTreatment;
import org.apache.commons.lang3.ObjectUtils;
import org.checkerframework.checker.units.qual.Speed;
import org.slf4j.Logger;
......@@ -27,6 +27,7 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
......@@ -73,6 +74,8 @@ public class WlCarMileageServiceImpl extends ServiceImpl<WlCarMileageMapper, WlC
IotFeign iotFeign;
@Autowired
ICarService iCarService;
@Autowired
WlCarMileageMapper wlCarMileageMapper;
@Value("${car.max.speed:100}")
private Integer CAR_MAX_SPEED;
@Value("${mileage.parameter}")
......@@ -82,6 +85,9 @@ public class WlCarMileageServiceImpl extends ServiceImpl<WlCarMileageMapper, WlC
@Autowired
@Lazy
private IWlCarMileageService iWlCarMileageService;
@Autowired
private RedisTemplate redisTemplate;
public static List<String> getDayByMonth(Date date) {
List<String> data = new ArrayList<>();
try {
......@@ -249,7 +255,7 @@ public class WlCarMileageServiceImpl extends ServiceImpl<WlCarMileageMapper, WlC
// coordinate.setSpeed(speeed);
// coordinates.add(coordinate);
// }
coordinates = giveSpeedToCoordinate(objects,points1);
coordinates = giveSpeedToCoordinate(objects, points1);
}
}
......@@ -314,24 +320,26 @@ public class WlCarMileageServiceImpl extends ServiceImpl<WlCarMileageMapper, WlC
log.info("轨迹切分定时任务数据过滤时间.............{}", nowDate);
List<WlCarMileage> list = this.baseMapper.list(nowDate);
log.info("需要切分数据, {}", list);
//销毁所有线程和所有上次坐标
//销毁所有线程
log.info("销毁所有有效线程开始");
CarIotNewListener.deviceInfo.keySet().forEach(s -> {
try {
CarIotNewListener.deviceInfo.get(s).interrupt();
} catch (Exception e) {
log.info("销毁有效线程失败" + e.getMessage());
}
});
CarIotNewListener.deviceInfo.clear();
log.info("销毁所有有效线程成功");
//销毁所有的坐标信息
log.info("销毁所有坐标信息开始");
CarIotNewListener.deviceLastInfo.clear();
// log.info("销毁所有有效线程开始");
// JxiopCarIotListerServiceImpl.deviceInfo.keySet().forEach(s -> {
// try {
// JxiopCarIotListerServiceImpl.deviceInfo.get(s).interrupt();
// } catch (Exception e) {
// log.info("销毁有效线程失败" + e.getMessage());
// }
// });
// JxiopCarIotListerServiceImpl.deviceInfo.clear();
// log.info("销毁所有有效线程成功");
// //销毁所有的坐标信息
// log.info("销毁所有坐标信息开始");
// JxiopCarIotListerServiceImpl.deviceLastInfo.clear();
log.info("销毁所有坐标信息成功");
log.info("------------------开始切分里程-------------------------------");
list.forEach(item -> {
redisTemplate.delete(item.getIotCode());
Calendar calendar = Calendar.getInstance();
calendar.setTime(item.getDate());
calendar.add(Calendar.DATE, 1);
......@@ -380,20 +388,26 @@ public class WlCarMileageServiceImpl extends ServiceImpl<WlCarMileageMapper, WlC
start.getDoubleValue("FireCar_Longitude"), end.getDoubleValue("FireCar_Latitude"),
end.getDoubleValue("FireCar_Longitude"));
}
// 查询车辆最新位置
String address = getAddress(startLongitude, startLatitude);
// 里程耗时
long takeTime = (date.getTime()) - (item.getStartTime().getTime());
// 修改0点未结束里程记录
item.setEndSpeed(v.intValue());
item.setEndTime(date);
item.setEndLatitude(startLatitude);
item.setEndLongitude(startLongitude);
item.setEndName(address);
item.setTravel(new BigDecimal(travel / 1000).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue());
item.setTakeTime(takeTime);
this.getBaseMapper().updateById(item);
// 查询车辆最新位置
// 修改0点未结束里程记录
item.setEndSpeed(v.intValue());
item.setEndTime(date);
item.setEndLatitude(startLatitude);
item.setEndLongitude(startLongitude);
item.setEndName("无效坐标");
if(travel>0.5){
String address = getAddress(startLongitude, startLatitude);
item.setEndName(address);
}
item.setTravel(new BigDecimal(travel / 1000).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue());
item.setTakeTime(takeTime);
this.getBaseMapper().updateById(item);
log.info("-----------结束里程成功:::" + JSONObject.toJSONString(item) + "-----------------");
// // 从0点开启新里程
// item.setStartName(address);
......@@ -438,6 +452,87 @@ public class WlCarMileageServiceImpl extends ServiceImpl<WlCarMileageMapper, WlC
// log.info("-------------------对于切割完成的数据进行倒计时结束----------------------------------");
}
@Scheduled(cron = "${mileage.splitmileage.cron}")
@Async
public void endCarMileageTask() {
List<WlCarMileage> list = wlCarMileageMapper.selectList(new QueryWrapper<WlCarMileage>().isNull("end_time").isNotNull("start_time"));
list.forEach(item -> {
if (ObjectUtils.isEmpty(redisTemplate.opsForValue().get(item.getIotCode()))) {
if (!ObjectUtils.isEmpty(item.getIotCode()) && item.getIotCode().length() > 8) {
// 查询车辆上报信息
Date date =new Date();
ResponseModel<List<Object>> result = iotFeign.getLiveData(item.getIotCode().substring(0, 8), item.getIotCode().substring(8),
item.getStartTime(), new Date(new Date().getTime() + 2000));
List<Object> list1 = result.getResult();
// 获取最后一个有坐标的数据
JSONObject lastObj = null;
// 过滤空坐标
List<Object> filterList = new ArrayList<Object>();
for (int i = 0; i < list1.size(); i++) {
JSONObject Obj = JSONObject.parseObject(JSONObject.toJSONString(list1.get(i)));
if (Obj.get("FireCar_Longitude") != null && Obj.get("FireCar_Latitude") != null
&& Obj.getDoubleValue("FireCar_Longitude") != 0
&& Obj.getDoubleValue("FireCar_Latitude") != 0) {
filterList.add(list1.get(i));
// 获取第一个不为空的坐标
if (lastObj == null) {
lastObj = Obj;
}
}
}
if (lastObj == null) {
lastObj = new JSONObject();
lastObj.put("FireCar_Longitude", 0.0);
lastObj.put("FireCar_Latitude", 0.0);
lastObj.put("time", 0);
lastObj.put("FireCar_Speed", 0);
}
// 当前坐标
double startLongitude = lastObj.getDoubleValue("FireCar_Longitude");
double startLatitude = lastObj.getDoubleValue("FireCar_Latitude");
// 当前速度
Double v = lastObj.getDoubleValue("FireCar_Speed");
item.setStartSpeed(v.intValue());
double travel = 0.0;
// 获取里程
for (int i = 0; i < filterList.size() - 1; i++) {
JSONObject start = JSONObject.parseObject(JSONObject.toJSONString(filterList.get(i)));
JSONObject end = JSONObject.parseObject(JSONObject.toJSONString(filterList.get(i + 1)));
travel += CoordinateUtil.distance(start.getDoubleValue("FireCar_Latitude"),
start.getDoubleValue("FireCar_Longitude"), end.getDoubleValue("FireCar_Latitude"),
end.getDoubleValue("FireCar_Longitude"));
}
// 里程耗时
long takeTime = (date.getTime()) - (item.getStartTime().getTime());
// 查询车辆最新位置
// 修改0点未结束里程记录
item.setEndSpeed(v.intValue());
item.setEndTime(date);
item.setEndLatitude(startLatitude);
item.setEndLongitude(startLongitude);
item.setEndName("无效坐标");
if(travel>0.5){
String address = getAddress(startLongitude, startLatitude);
item.setEndName(address);
}
item.setTravel(new BigDecimal(travel / 1000).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue());
item.setTakeTime(takeTime);
this.getBaseMapper().updateById(item);
log.info("-----------结束里程成功:::" + JSONObject.toJSONString(item) + "-----------------");
Car car = iCarService.getOne(new QueryWrapper<Car>().eq("iot_code", item.getIotCode()));
car.setLongitude(startLongitude);
car.setLatitude(startLatitude);
iCarService.saveOrUpdate(car);
log.info("-----------更新车辆坐标成功:::" + JSONObject.toJSONString(item) + "-----------------");
}
}
});
log.info("轨迹切分任务执行完成..............");
}
@Override
public Boolean getUncompleteMileagByIotCode(String iotCode) {
Integer integer = this.count(new QueryWrapper<WlCarMileage>().select("1").lambda().eq(WlCarMileage::getIotCode, iotCode).isNull(WlCarMileage::getEndTime));
......@@ -485,20 +580,20 @@ public class WlCarMileageServiceImpl extends ServiceImpl<WlCarMileageMapper, WlC
@Override
public Double getTotalTravelByIotCodeAndDate(String date, String iotCode) {
if(StringUtils.isEmpty(date)){
date = DateUtil.format(new Date(),"yyyy-MM");
if (StringUtils.isEmpty(date)) {
date = DateUtil.format(new Date(), "yyyy-MM");
}
Double totalTravel = 0.0;
LambdaQueryWrapper<WlCarMileage> wrapper = new LambdaQueryWrapper<WlCarMileage>();
wrapper.eq(WlCarMileage::getIotCode,iotCode);
wrapper.eq(WlCarMileage::getIotCode, iotCode);
wrapper.ge(WlCarMileage::getTravel, 0.5);
wrapper.isNotNull(WlCarMileage::getEndTime);
wrapper.isNotNull(WlCarMileage::getStartTime);
wrapper.like(WlCarMileage::getStartTime,date);
List<WlCarMileage> list = iWlCarMileageService.list(wrapper);
wrapper.like(WlCarMileage::getStartTime, date);
List<WlCarMileage> list = iWlCarMileageService.list(wrapper);
for (WlCarMileage wl : list) {
//判断当前车辆全程是否异常,如果时速小于阈值 则对数据进行返回 否则不予返回
if (!org.springframework.util.ObjectUtils.isEmpty(wl.getTakeTime()) && !org.springframework.util.ObjectUtils.isEmpty(wl.getTravel()) && ((wl.getTravel() / (wl.getTakeTime() / 3600000.0)) < CAR_MAX_SPEED)) {
if (!org.springframework.util.ObjectUtils.isEmpty(wl.getTakeTime()) && !org.springframework.util.ObjectUtils.isEmpty(wl.getTravel()) && ((wl.getTravel() / (wl.getTakeTime() / 3600000.0)) < CAR_MAX_SPEED)) {
totalTravel += wl.getTravel();
}
}
......@@ -509,16 +604,16 @@ public class WlCarMileageServiceImpl extends ServiceImpl<WlCarMileageMapper, WlC
public Double getTotalTravelByIotCodeAndDateProd(String startDate, String endDate, String iotCode) {
Double totalTravel = 0.0;
LambdaQueryWrapper<WlCarMileage> wrapper = new LambdaQueryWrapper<WlCarMileage>();
wrapper.eq(WlCarMileage::getIotCode,iotCode);
wrapper.eq(WlCarMileage::getIotCode, iotCode);
wrapper.ge(WlCarMileage::getTravel, 0.5);
wrapper.isNotNull(WlCarMileage::getEndTime);
wrapper.isNotNull(WlCarMileage::getStartTime);
wrapper.ge(WlCarMileage::getDate,startDate);
wrapper.le(WlCarMileage::getDate,endDate);
List<WlCarMileage> list = iWlCarMileageService.list(wrapper);
wrapper.ge(WlCarMileage::getDate, startDate);
wrapper.le(WlCarMileage::getDate, endDate);
List<WlCarMileage> list = iWlCarMileageService.list(wrapper);
for (WlCarMileage wl : list) {
//判断当前车辆全程是否异常,如果时速小于阈值 则对数据进行返回 否则不予返回
if (!org.springframework.util.ObjectUtils.isEmpty(wl.getTakeTime()) && !org.springframework.util.ObjectUtils.isEmpty(wl.getTravel()) && ((wl.getTravel() / (wl.getTakeTime() / 3600000.0)) < CAR_MAX_SPEED)) {
if (!org.springframework.util.ObjectUtils.isEmpty(wl.getTakeTime()) && !org.springframework.util.ObjectUtils.isEmpty(wl.getTravel()) && ((wl.getTravel() / (wl.getTakeTime() / 3600000.0)) < CAR_MAX_SPEED)) {
totalTravel += wl.getTravel();
}
}
......@@ -526,29 +621,28 @@ public class WlCarMileageServiceImpl extends ServiceImpl<WlCarMileageMapper, WlC
}
/**
* @descrip 获取纠偏后数据应该展示的数据
* @param objects 纠偏下之前的数据
* @param startLatitude 纠偏之后的经度
* @param objects 纠偏下之前的数据
* @param startLatitude 纠偏之后的经度
* @param startLongitude 纠偏之后的纬度
* @param index 当前纠偏数据的索引
* @return 当前数据应该展示的速度
* @descrip 获取纠偏后数据应该展示的数据
*/
public Double getSpeedByOriginalData(JSONArray objects, Double startLatitude, Double startLongitude) {
Double speed = 0.0;
for (int i = 0; i < objects.size() - 1; i++) {
JSONObject jsonObject1 = objects.getJSONObject(i);
JSONObject jsonObject2 = objects.getJSONObject(i+1);
JSONObject jsonObject2 = objects.getJSONObject(i + 1);
Double travel1 = CoordinateUtil.distance(startLatitude, startLongitude, jsonObject1.getDoubleValue("x"), jsonObject1.getDoubleValue("y"));
Double travel2 = CoordinateUtil.distance(startLatitude, startLongitude, jsonObject2.getDoubleValue("x"), jsonObject2.getDoubleValue("y"));
log.info("travel1:"+travel1+"travel2:"+travel2);
if (travel2 >travel1) {
log.info("travel1:"+travel1+"travel2:"+travel2);
log.info("lat:"+startLatitude+"long:"+startLongitude);
log.info("lat:"+jsonObject1.getDoubleValue("x")+"long:"+jsonObject1.getDoubleValue("y"));
log.info("travel1:" + travel1 + "travel2:" + travel2);
if (travel2 > travel1) {
log.info("travel1:" + travel1 + "travel2:" + travel2);
log.info("lat:" + startLatitude + "long:" + startLongitude);
log.info("lat:" + jsonObject1.getDoubleValue("x") + "long:" + jsonObject1.getDoubleValue("y"));
speed = jsonObject1.getDoubleValue("sp");
break;
}else{
} else {
speed = jsonObject2.getDoubleValue("sp");
}
}
......@@ -556,16 +650,15 @@ public class WlCarMileageServiceImpl extends ServiceImpl<WlCarMileageMapper, WlC
}
/**
*
* @param originalPoints 原始数据点位
* @param aMapPoints 高德纠偏之后的数据点位
* @param aMapPoints 高德纠偏之后的数据点位
* @return List<Coordinate> 处理之后的数据
*/
public ArrayList<Coordinate> giveSpeedToCoordinate(JSONArray originalPoints,JSONArray aMapPoints ){
public ArrayList<Coordinate> giveSpeedToCoordinate(JSONArray originalPoints, JSONArray aMapPoints) {
ArrayList<Coordinate> result = new ArrayList<>();
Double rate = originalPoints.size()/(aMapPoints.size()*1.0);
Double rate = originalPoints.size() / (aMapPoints.size() * 1.0);
for (int i = 0; i < aMapPoints.size(); i++) {
Integer speedIndex = Double.valueOf(i*rate).intValue();
Integer speedIndex = Double.valueOf(i * rate).intValue();
JSONObject jsonObject1 = JSONObject.parseObject(aMapPoints.get(i).toString());
List<Double> doubles = new ArrayList<>();
Coordinate coordinate = new Coordinate();
......
package com.yeejoin.equipmanage.thread;
import ch.qos.logback.core.joran.conditional.ElseAction;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yeejoin.equipmanage.common.entity.Car;
import com.yeejoin.equipmanage.common.entity.WlCarMileage;
import com.yeejoin.equipmanage.common.utils.CoordinateUtil;
import com.yeejoin.equipmanage.fegin.IotFeign;
import com.yeejoin.equipmanage.listener.CarIotNewListener;
import com.yeejoin.equipmanage.service.ICarService;
import com.yeejoin.equipmanage.service.IWlCarMileageService;
import com.yeejoin.equipmanage.utils.CarUtils;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.jfree.util.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ObjectUtils;
import org.typroject.tyboot.component.emq.EmqKeeper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.concurrent.TimeUnit;
public class
ThreadCar extends Thread {
Logger logger = LoggerFactory.getLogger(ThreadCar.class);
private IWlCarMileageService iWlCarMileageService;
private IotFeign iotFeign;
private String topic;
private Long clippingTime;
ICarService iCarService;
private JSONObject jsonObject;
public ThreadCar(String topic, JSONObject jsonObject, IWlCarMileageService iWlCarMileageService, IotFeign iotFeign, ICarService iCarService, Long clippingTime) {
this.topic = topic;
this.jsonObject = jsonObject;
this.iWlCarMileageService = iWlCarMileageService;
this.iotFeign = iotFeign;
this.iCarService = iCarService;
this.clippingTime = clippingTime;
}
@Override
public void run() {
//toDo
// 获取最后一个有坐标的数据
JSONObject lastObj = null;
WlCarMileage last = null;
String measurement = topic.split("/")[0];
String deviceName = topic.split("/")[1];
String iotCode = measurement + deviceName;
try {
Long startTime = System.currentTimeMillis();
logger.info("=============================================" + topic + "结束坐标开始计时=======================================");
this.sleep(clippingTime);
//业务处理
//如果十分钟没有坐标,则需要设置结束标记
// 获取结束坐标
last = iWlCarMileageService
.getOne(new LambdaQueryWrapper<WlCarMileage>().eq(WlCarMileage::getIotCode, iotCode)
.isNull(WlCarMileage::getEndLongitude).isNull(WlCarMileage::getEndLatitude)
.orderByDesc(WlCarMileage::getStartTime).last("limit 1"));
ResponseModel<List<Object>> result = iotFeign.getLiveData(measurement, deviceName,
last.getStartTime(), new Date(new Date().getTime() + 2000));
List<Object> list = result.getResult();
if (list != null && list.size() > 0) {
// 过滤空坐标
List<Object> filterList = new ArrayList<Object>();
for (int i = 0; i < list.size(); i++) {
JSONObject Obj = JSONObject.parseObject(JSONObject.toJSONString(list.get(i)));
if (Obj.get("FireCar_Longitude") != null && Obj.get("FireCar_Latitude") != null
&& Obj.getDoubleValue("FireCar_Longitude") != 0
&& Obj.getDoubleValue("FireCar_Latitude") != 0) {
filterList.add(list.get(i));
// 获取第一个不为空的坐标
if (lastObj == null) {
lastObj = Obj;
}
}
}
if (lastObj == null) {
lastObj = new JSONObject();
lastObj.put("FireCar_Longitude", last.getStartLongitude());
lastObj.put("FireCar_Latitude", last.getEndLatitude());
lastObj.put("time", 0);
lastObj.put("FireCar_Speed", 0);
logger.info("---过滤后last信息为null时的数据::" + JSONObject.toJSONString(last));
}
//里程结束时间设置为最后一次的上报时间
Date endTime = new Date(startTime/ 1000 * 1000);
//实时库中的时间虽然坐标与记录的一致,但是更新时间可能最新,故可能会有记录的结束时间早于开始时间
long takeTime = (endTime.getTime() / 1000 * 1000) - (last.getStartTime().getTime() / 1000 * 1000);
if (takeTime < 0) {
takeTime = 0 - takeTime;
}
double endLongitude = lastObj.getDoubleValue("FireCar_Longitude");
double endLatitude = lastObj.getDoubleValue("FireCar_Latitude");
last.setTakeTime(takeTime);
last.setEndLongitude(endLongitude);
last.setEndLatitude(endLatitude);
last.setEndTime(endTime);
last.setEndName(CarUtils.getAddress(endLongitude, endLatitude));
//原来的写法不够健壮,如果上报的数据为double写法则会直接报凑错
try {
Double.valueOf(jsonObject.getDoubleValue("FireCar_Speed")).intValue();
if (ObjectUtils.isEmpty(lastObj.containsKey("FireCar_Speed"))) {
last.setEndSpeed(0);
} else {
last.setEndSpeed(Double.valueOf(jsonObject.getString("FireCar_Speed")).intValue());
}
} catch (Exception exception) {
last.setEndSpeed(0);
}
double travel = 0.0;
// 获取里程
for (int i = 0; i < filterList.size() - 1; i++) {
JSONObject start = JSONObject.parseObject(JSONObject.toJSONString(filterList.get(i)));
JSONObject end = JSONObject.parseObject(JSONObject.toJSONString(filterList.get(i + 1)));
travel += CoordinateUtil.distance(start.getDoubleValue("FireCar_Latitude"),
start.getDoubleValue("FireCar_Longitude"), end.getDoubleValue("FireCar_Latitude"),
end.getDoubleValue("FireCar_Longitude"));
}
Double travle =new BigDecimal(travel / 1000).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
logger.info("---------------------本次里程::"+travle+"---------------------------------------");
last.setTravel(travle);
iWlCarMileageService.updateById(last);
Long lastTime = System.currentTimeMillis();
logger.info("---正常时获取到的获取last信息::" + JSONObject.toJSONString(last));
logger.info("--------------" + topic + "结束坐标成功::花费时间====" + String.valueOf((lastTime - startTime) / 60000) + "分钟-------------------------");
logger.info("============================================================更新结束坐标成功==============================================:" + topic);
//从缓存信息中移除运行完成的线程与坐标信息
CarIotNewListener.deviceInfo.remove(iotCode);
}
} catch (Exception exception) {
if (last != null) {
logger.info("---异常时获取到的获取last信息::" + JSONObject.toJSONString(last));
iWlCarMileageService.updateById(last);
}
} finally {
logger.info("销毁车辆倒计时线程::topic_" + topic);
}
}
}
//package com.yeejoin.equipmanage.thread;
//
//import ch.qos.logback.core.joran.conditional.ElseAction;
//import com.alibaba.fastjson.JSONArray;
//import com.alibaba.fastjson.JSONObject;
//import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
//import com.yeejoin.equipmanage.common.entity.Car;
//import com.yeejoin.equipmanage.common.entity.WlCarMileage;
//import com.yeejoin.equipmanage.common.utils.CoordinateUtil;
//import com.yeejoin.equipmanage.fegin.IotFeign;
//import com.yeejoin.equipmanage.listener.CarIotNewListener;
//import com.yeejoin.equipmanage.service.ICarService;
//import com.yeejoin.equipmanage.service.IWlCarMileageService;
//import com.yeejoin.equipmanage.service.impl.JxiopCarIotListerServiceImpl;
//import com.yeejoin.equipmanage.utils.CarUtils;
//import org.eclipse.paho.client.mqttv3.MqttException;
//import org.eclipse.paho.client.mqttv3.MqttMessage;
//import org.jfree.util.Log;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.util.ObjectUtils;
//import org.typroject.tyboot.component.emq.EmqKeeper;
//import org.typroject.tyboot.core.restful.utils.ResponseModel;
//
//import java.math.BigDecimal;
//import java.util.ArrayList;
//import java.util.Date;
//import java.util.List;
//import java.util.Timer;
//import java.util.concurrent.TimeUnit;
//
//public class
//ThreadCar extends Thread {
// Logger logger = LoggerFactory.getLogger(ThreadCar.class);
// private IWlCarMileageService iWlCarMileageService;
//
// private IotFeign iotFeign;
// private String topic;
// private Long clippingTime;
// ICarService iCarService;
// private JSONObject jsonObject;
//
// public ThreadCar(String topic, JSONObject jsonObject, IWlCarMileageService iWlCarMileageService, IotFeign iotFeign, ICarService iCarService, Long clippingTime) {
// this.topic = topic;
// this.jsonObject = jsonObject;
// this.iWlCarMileageService = iWlCarMileageService;
// this.iotFeign = iotFeign;
// this.iCarService = iCarService;
// this.clippingTime = clippingTime;
// }
//
// @Override
// public void run() {
// //toDo
// // 获取最后一个有坐标的数据
// JSONObject lastObj = null;
// WlCarMileage last = null;
// String measurement = topic.split("/")[0];
// String deviceName = topic.split("/")[1];
// String iotCode = measurement + deviceName;
// try {
// Long startTime = System.currentTimeMillis();
// logger.info("=============================================" + topic + "结束坐标开始计时=======================================");
// this.sleep(clippingTime);
// //业务处理
// //如果十分钟没有坐标,则需要设置结束标记
// // 获取结束坐标
// last = iWlCarMileageService
// .getOne(new LambdaQueryWrapper<WlCarMileage>().eq(WlCarMileage::getIotCode, iotCode)
// .isNull(WlCarMileage::getEndLongitude).isNull(WlCarMileage::getEndLatitude)
// .orderByDesc(WlCarMileage::getStartTime).last("limit 1"));
// ResponseModel<List<Object>> result = iotFeign.getLiveData(measurement, deviceName,
// last.getStartTime(), new Date(new Date().getTime() + 2000));
// List<Object> list = result.getResult();
// if (list != null && list.size() > 0) {
// // 过滤空坐标
// List<Object> filterList = new ArrayList<Object>();
// for (int i = 0; i < list.size(); i++) {
// JSONObject Obj = JSONObject.parseObject(JSONObject.toJSONString(list.get(i)));
// if (Obj.get("FireCar_Longitude") != null && Obj.get("FireCar_Latitude") != null
// && Obj.getDoubleValue("FireCar_Longitude") != 0
// && Obj.getDoubleValue("FireCar_Latitude") != 0) {
// filterList.add(list.get(i));
// // 获取第一个不为空的坐标
// if (lastObj == null) {
// lastObj = Obj;
// }
// }
// }
// if (lastObj == null) {
// lastObj = new JSONObject();
// lastObj.put("FireCar_Longitude", last.getStartLongitude());
// lastObj.put("FireCar_Latitude", last.getEndLatitude());
// lastObj.put("time", 0);
// lastObj.put("FireCar_Speed", 0);
// logger.info("---过滤后last信息为null时的数据::" + JSONObject.toJSONString(last));
// }
// //里程结束时间设置为最后一次的上报时间
// Date endTime = new Date();
// //实时库中的时间虽然坐标与记录的一致,但是更新时间可能最新,故可能会有记录的结束时间早于开始时间
// long takeTime = (endTime.getTime() / 1000 * 1000) - (last.getStartTime().getTime() / 1000 * 1000);
// if (takeTime < 0) {
// takeTime = 0 - takeTime;
// }
// double endLongitude = lastObj.getDoubleValue("FireCar_Longitude");
// double endLatitude = lastObj.getDoubleValue("FireCar_Latitude");
// last.setTakeTime(takeTime);
// last.setEndLongitude(endLongitude);
// last.setEndLatitude(endLatitude);
// last.setEndTime(endTime);
// last.setEndName(CarUtils.getAddress(endLongitude, endLatitude));
// //原来的写法不够健壮,如果上报的数据为double写法则会直接报凑错
// try {
// Double.valueOf(jsonObject.getDoubleValue("FireCar_Speed")).intValue();
// if (ObjectUtils.isEmpty(lastObj.containsKey("FireCar_Speed"))) {
// last.setEndSpeed(0);
// } else {
// last.setEndSpeed(Double.valueOf(jsonObject.getString("FireCar_Speed")).intValue());
// }
// } catch (Exception exception) {
// last.setEndSpeed(0);
// }
// double travel = 0.0;
// // 获取里程
// for (int i = 0; i < filterList.size() - 1; i++) {
// JSONObject start = JSONObject.parseObject(JSONObject.toJSONString(filterList.get(i)));
// JSONObject end = JSONObject.parseObject(JSONObject.toJSONString(filterList.get(i + 1)));
// travel += CoordinateUtil.distance(start.getDoubleValue("FireCar_Latitude"),
// start.getDoubleValue("FireCar_Longitude"), end.getDoubleValue("FireCar_Latitude"),
// end.getDoubleValue("FireCar_Longitude"));
// }
// Double travle =new BigDecimal(travel / 1000).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
// logger.info("---------------------本次里程::"+travle+"---------------------------------------");
// last.setTravel(travle);
//
// iWlCarMileageService.updateById(last);
// Long lastTime = System.currentTimeMillis();
// logger.info("---正常时获取到的获取last信息::" + JSONObject.toJSONString(last));
// logger.info("--------------" + topic + "结束坐标成功::花费时间====" + String.valueOf((lastTime - startTime) / 60000) + "分钟-------------------------");
// logger.info("============================================================更新结束坐标成功==============================================:" + topic);
// //从缓存信息中移除运行完成的线程与坐标信息
// JxiopCarIotListerServiceImpl.deviceInfo.remove(iotCode);
// }
// } catch (Exception exception) {
// if (last != null) {
// logger.info("---异常时获取到的获取last信息::" + JSONObject.toJSONString(last));
// iWlCarMileageService.updateById(last);
// }
// } finally {
// logger.info("销毁车辆倒计时线程::topic_" + topic);
// }
// }
//
//}
//
package com.yeejoin.equipmanage.thread;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yeejoin.equipmanage.common.entity.Car;
import com.yeejoin.equipmanage.common.entity.WlCarMileage;
import com.yeejoin.equipmanage.common.utils.CoordinateUtil;
import com.yeejoin.equipmanage.fegin.IotFeign;
import com.yeejoin.equipmanage.service.ICarService;
import com.yeejoin.equipmanage.service.impl.CarServiceImpl;
import com.yeejoin.equipmanage.service.impl.WlCarMileageServiceImpl;
import com.yeejoin.equipmanage.utils.CarUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.typroject.tyboot.core.restful.utils.ResponseModel;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
@Component
public class ThreadCarMileageTreatment extends Thread {
Logger logger = LoggerFactory.getLogger(ThreadCarMileageTreatment.class);
private final WlCarMileageServiceImpl wlCarMileageServiceImpl;
private final ICarService iCarService;
private final IotFeign iotFeign;
@Value("${mileage.clippingtime}")
private Long clipping_time;
public ThreadCarMileageTreatment(WlCarMileageServiceImpl wlCarMileageServiceImpl, ICarService iCarService, IotFeign iotFeign) {
this.wlCarMileageServiceImpl = wlCarMileageServiceImpl;
this.iCarService = iCarService;
this.iotFeign = iotFeign;
}
@Override
public void run() {
logger.info("----------------------------------------------------开始处理未结束里程---------------------------------");
HashMap<String, String> hashMap = new HashMap<>();
//toDo
WlCarMileage last = null;
JSONObject lastObj = null;
Car car =null;
List<WlCarMileage> wlCarMileageList = wlCarMileageServiceImpl.list(new QueryWrapper<WlCarMileage>().isNull("end_time"));
for (int i = 0; i < wlCarMileageList.size(); i++) {
car = iCarService.getOne(new QueryWrapper<Car>().eq("iot_code", wlCarMileageList.get(i).getIotCode()));
String coordinateSting = String.valueOf(car.getLongitude()) + String.valueOf(car.getLatitude());
hashMap.put(car.getIotCode(), coordinateSting);
}
logger.info("----------------获取到的未处理的车辆坐标信息::"+JSONObject.toJSONString(hashMap));
try {
Thread.sleep(clipping_time);
for (int i = 0; i < wlCarMileageList.size(); i++) {
WlCarMileage wlCarMileage =wlCarMileageList.get(i);
car = iCarService.getOne(new QueryWrapper<Car>().eq("iot_code", wlCarMileage.getIotCode()));
String coordinateSting = String.valueOf(car.getLongitude()) + String.valueOf(car.getLatitude());
//增加对于无效坐标的兼容处理,由于无效坐标的存储精度不一样 可能会导致0的位数发生差异从而到时无法判断生效
if (coordinateSting.equals(hashMap.get(car.getIotCode()))||(handlerUnActiveCoodinate(coordinateSting).equals(handlerUnActiveCoodinate(hashMap.get(car.getIotCode()))))) {
String iotCode = car.getIotCode();
String measurement = iotCode.substring(0,8);
String deviceName = iotCode.replace(measurement, "");
last = wlCarMileageServiceImpl
.getOne(new LambdaQueryWrapper<WlCarMileage>().eq(WlCarMileage::getIotCode, iotCode)
.isNull(WlCarMileage::getEndLongitude).isNull(WlCarMileage::getEndLatitude)
.orderByDesc(WlCarMileage::getStartTime).last("limit 1"));
ResponseModel<List<Object>> result = iotFeign.getLiveData(measurement, deviceName,
last.getStartTime(), new Date(new Date().getTime() + 2000));
List<Object> list = result.getResult();
if (list != null && list.size() > 0) {
// 过滤空坐标
List<Object> filterList = new ArrayList<Object>();
for (int j = 0; j < list.size(); j++) {
JSONObject Obj = JSONObject.parseObject(JSONObject.toJSONString(list.get(j)));
if (Obj.get("FireCar_Longitude") != null && Obj.get("FireCar_Latitude") != null
&& Obj.getDoubleValue("FireCar_Longitude") != 0
&& Obj.getDoubleValue("FireCar_Latitude") != 0) {
filterList.add(list.get(j));
// 获取第一个不为空的坐标
lastObj = Obj;
}
}
logger.info("----------------------------------------lastobj----------------------"+lastObj.toJSONString());
if (lastObj == null) {
lastObj = new JSONObject();
lastObj.put("FireCar_Longitude", last.getStartLongitude());
lastObj.put("FireCar_Latitude", last.getEndLatitude());
lastObj.put("time", 0);
lastObj.put("FireCar_Speed", 0);
}
double endLongitude = lastObj.getDoubleValue("FireCar_Longitude");
double endLatitude = lastObj.getDoubleValue("FireCar_Latitude");
Date endTime = new Date();
long takeTime = (endTime.getTime() / 1000 * 1000) - (last.getStartTime().getTime() / 1000 * 1000);
if(takeTime<0){
takeTime = 0-takeTime;
}
last.setTakeTime(takeTime);
last.setEndLongitude(endLongitude);
last.setEndLatitude(endLatitude);
last.setEndTime(endTime);
last.setEndName(CarUtils.getAddress(endLongitude, endLatitude));
//原来的写法不够健壮,如果上报的数据为double写法则会直接报凑错
try {
Double.valueOf(lastObj.getDoubleValue("FireCar_Speed")).intValue();
if (ObjectUtils.isEmpty(lastObj.containsKey("FireCar_Speed"))) {
last.setEndSpeed(0);
} else {
last.setEndSpeed(Double.valueOf(lastObj.getString("FireCar_Speed")).intValue());
}
} catch (Exception exception) {
last.setEndSpeed(0);
}
double travel = 0.0;
// 获取里程
for (int k = 0; k < filterList.size() - 1; k++) {
JSONObject start = JSONObject.parseObject(JSONObject.toJSONString(filterList.get(k)));
JSONObject end = JSONObject.parseObject(JSONObject.toJSONString(filterList.get(k + 1)));
travel += CoordinateUtil.distance(start.getDoubleValue("FireCar_Latitude"),
start.getDoubleValue("FireCar_Longitude"), end.getDoubleValue("FireCar_Latitude"),
end.getDoubleValue("FireCar_Longitude"));
}
Double travle =new BigDecimal(travel / 1000).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
logger.info("---------------------本次里程::"+travle+"---------------------------------------");
last.setTravel(travle);
logger.info("----------------------------------------last----------------------"+lastObj.toJSONString());
wlCarMileageServiceImpl.updateById(last);
}
}
}
} catch (Exception exception) {
logger.info(exception.getMessage());
wlCarMileageServiceImpl.updateById(last);
}
}
public String handlerUnActiveCoodinate(String coodeinateString){
return coodeinateString.replace("0","").replace(".","");
}
}
//package com.yeejoin.equipmanage.thread;
//
//import com.alibaba.fastjson.JSONObject;
//import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
//import com.yeejoin.equipmanage.common.entity.Car;
//import com.yeejoin.equipmanage.common.entity.WlCarMileage;
//import com.yeejoin.equipmanage.common.utils.CoordinateUtil;
//import com.yeejoin.equipmanage.fegin.IotFeign;
//import com.yeejoin.equipmanage.service.ICarService;
//import com.yeejoin.equipmanage.service.impl.CarServiceImpl;
//import com.yeejoin.equipmanage.service.impl.WlCarMileageServiceImpl;
//import com.yeejoin.equipmanage.utils.CarUtils;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.stereotype.Component;
//import org.springframework.util.ObjectUtils;
//import org.typroject.tyboot.core.restful.utils.ResponseModel;
//
//import java.math.BigDecimal;
//import java.util.ArrayList;
//import java.util.Date;
//import java.util.HashMap;
//import java.util.List;
//@Component
//public class ThreadCarMileageTreatment extends Thread {
// Logger logger = LoggerFactory.getLogger(ThreadCarMileageTreatment.class);
// private final WlCarMileageServiceImpl wlCarMileageServiceImpl;
// private final ICarService iCarService;
// private final IotFeign iotFeign;
// @Value("${mileage.clippingtime}")
// private Long clipping_time;
//
// public ThreadCarMileageTreatment(WlCarMileageServiceImpl wlCarMileageServiceImpl, ICarService iCarService, IotFeign iotFeign) {
// this.wlCarMileageServiceImpl = wlCarMileageServiceImpl;
// this.iCarService = iCarService;
// this.iotFeign = iotFeign;
// }
//
// @Override
// public void run() {
// logger.info("----------------------------------------------------开始处理未结束里程---------------------------------");
// HashMap<String, String> hashMap = new HashMap<>();
// //toDo
// WlCarMileage last = null;
// JSONObject lastObj = null;
// Car car =null;
// List<WlCarMileage> wlCarMileageList = wlCarMileageServiceImpl.list(new QueryWrapper<WlCarMileage>().isNull("end_time"));
// for (int i = 0; i < wlCarMileageList.size(); i++) {
// car = iCarService.getOne(new QueryWrapper<Car>().eq("iot_code", wlCarMileageList.get(i).getIotCode()));
// String coordinateSting = String.valueOf(car.getLongitude()), String,valueOf(car.getLatitude());
//// hashMap.put(car.getIotCode(), coordinateSting);
// }
//// logger.info("----------------获取到的未处理的车辆坐标信息::"+JSONObject.toJSONString(hashMap));
//// try {
//// Thread.sleep(clipping_time);
//// for (int i = 0; i < wlCarMileageList.size(); i++) {
//// WlCarMileage wlCarMileage =wlCarMileageList.get(i);
//// car = iCarService.getOne(new QueryWrapper<Car>().eq("iot_code", wlCarMileage.getIotCode()));
//// String coordinateSting = String.valueOf(car.getLongitude()) + String.valueOf(car.getLatitude());
//// //增加对于无效坐标的兼容处理,由于无效坐标的存储精度不一样 可能会导致0的位数发生差异从而到时无法判断生效
//// if (coordinateSting.equals(hashMap.get(car.getIotCode()))||(handlerUnActiveCoodinate(coordinateSting).equals(handlerUnActiveCoodinate(hashMap.get(car.getIotCode()))))) {
//// String iotCode = car.getIotCode();
//// String measurement = iotCode.substring(0,8);
//// String deviceName = iotCode.replace(measurement, "");
//// last = wlCarMileageServiceImpl
//// .getOne(new LambdaQueryWrapper<WlCarMileage>().eq(WlCarMileage::getIotCode, iotCode)
//// .isNull(WlCarMileage::getEndLongitude).isNull(WlCarMileage::getEndLatitude)
//// .orderByDesc(WlCarMileage::getStartTime).last("limit 1"));
//// ResponseModel<List<Object>> result = iotFeign.getLiveData(measurement, deviceName,
//// last.getStartTime(), new Date(new Date().getTime() + 2000));
//// List<Object> list = result.getResult();
//// if (list != null && list.size() > 0) {
//// // 过滤空坐标
//// List<Object> filterList = new ArrayList<Object>();
//// for (int j = 0; j < list.size(); j++) {
//// JSONObject Obj = JSONObject.parseObject(JSONObject.toJSONString(list.get(j)));
//// if (Obj.get("FireCar_Longitude") != null && Obj.get("FireCar_Latitude") != null
//// && Obj.getDoubleValue("FireCar_Longitude") != 0
//// && Obj.getDoubleValue("FireCar_Latitude") != 0) {
//// filterList.add(list.get(j));
//// // 获取第一个不为空的坐标
//// lastObj = Obj;
//// }
//// }
//// logger.info("----------------------------------------lastobj----------------------"+lastObj.toJSONString());
//// if (lastObj == null) {
//// lastObj = new JSONObject();
//// lastObj.put("FireCar_Longitude", last.getStartLongitude());
//// lastObj.put("FireCar_Latitude", last.getEndLatitude());
//// lastObj.put("time", 0);
//// lastObj.put("FireCar_Speed", 0);
//// }
//// double endLongitude = lastObj.getDoubleValue("FireCar_Longitude");
//// double endLatitude = lastObj.getDoubleValue("FireCar_Latitude");
//// Date endTime = new Date();
//// long takeTime = (endTime.getTime() / 1000 * 1000) - (last.getStartTime().getTime() / 1000 * 1000);
//// if(takeTime<0){
//// takeTime = 0-takeTime;
//// }
//// last.setTakeTime(takeTime);
//// last.setEndLongitude(endLongitude);
//// last.setEndLatitude(endLatitude);
//// last.setEndTime(endTime);
//// last.setEndName(CarUtils.getAddress(endLongitude, endLatitude));
//// //原来的写法不够健壮,如果上报的数据为double写法则会直接报凑错
//// try {
//// Double.valueOf(lastObj.getDoubleValue("FireCar_Speed")).intValue();
//// if (ObjectUtils.isEmpty(lastObj.containsKey("FireCar_Speed"))) {
//// last.setEndSpeed(0);
//// } else {
//// last.setEndSpeed(Double.valueOf(lastObj.getString("FireCar_Speed")).intValue());
//// }
//// } catch (Exception exception) {
//// last.setEndSpeed(0);
//// }
//// double travel = 0.0;
//// // 获取里程
//// for (int k = 0; k < filterList.size() - 1; k++) {
//// JSONObject start = JSONObject.parseObject(JSONObject.toJSONString(filterList.get(k)));
//// JSONObject end = JSONObject.parseObject(JSONObject.toJSONString(filterList.get(k + 1)));
//// travel += CoordinateUtil.distance(start.getDoubleValue("FireCar_Latitude"),
//// start.getDoubleValue("FireCar_Longitude"), end.getDoubleValue("FireCar_Latitude"),
//// end.getDoubleValue("FireCar_Longitude"));
//// }
//// Double travle =new BigDecimal(travel / 1000).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
//// logger.info("---------------------本次里程::"+travle+"---------------------------------------");
//// last.setTravel(travle);
//// logger.info("----------------------------------------last----------------------"+lastObj.toJSONString());
//// wlCarMileageServiceImpl.updateById(last);
//// }
//// }
//// }
//// } catch (Exception exception) {
//// logger.info(exception.getMessage());
//// wlCarMileageServiceImpl.updateById(last);
//// }
// }
// public String handlerUnActiveCoodinate(String coodeinateString){
// return coodeinateString.replace("0","").replace(".","");
// }
//}
//
......@@ -3,7 +3,6 @@ package com.yeejoin;
import com.yeejoin.amos.boot.biz.common.utils.oConvertUtils;
import com.yeejoin.equipmanage.listener.CarIotListener;
import com.yeejoin.equipmanage.listener.CarIotNewListener;
import com.yeejoin.equipmanage.thread.ThreadCarMileageTreatment;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
......@@ -59,8 +58,6 @@ public class AmostEquipApplication {
@Autowired
private CarIotNewListener carIotNewListener;
@Autowired
private ThreadCarMileageTreatment threadCarMileageTreatment;
......@@ -102,9 +99,4 @@ public class AmostEquipApplication {
}
}
// 江西电建服务重启后对于未计时且未结束的里程的进行处理
@Bean
void initCarMelige() {
threadCarMileageTreatment.start();
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment