Selaa lähdekoodia

Merge branch 'tb-alipay' into test

hechunping 1 vuosi sitten
vanhempi
commit
1da0de196f

+ 2 - 0
device-api-service-merc-mini/src/main/java/com/xy/controller/MercMiniDeviceController.java

@@ -3,6 +3,7 @@ package com.xy.controller;
 import cn.hutool.core.collection.CollUtil;
 import cn.hutool.core.util.StrUtil;
 import com.baomidou.mybatisplus.core.toolkit.Wrappers;
+import com.xy.alipay.AliPay;
 import com.xy.annotate.RestMappingController;
 import com.xy.dto.DeviceBluetoothAuthDto;
 import com.xy.dto.DeviceInfoDto;
@@ -212,6 +213,7 @@ public class MercMiniDeviceController {
 
     @ApiOperation("运营状态修改")
     @PostMapping("modifyBusyStage")
+    @AliPay(AliPay.Type.BUSY_STATE)
     public R modifyBusyStage(@RequestBody @Validated MercMiniDeviceDto.BusySate busySate) {
         Long mercId = MercAuthUtils.getMercId();
         Long deviceId = busySate.getDeviceId();

+ 5 - 0
device-api-service/pom.xml

@@ -87,5 +87,10 @@
             <version>1.0</version>
             <scope>compile</scope>
         </dependency>
+        <dependency>
+            <groupId>com.xy</groupId>
+            <artifactId>xy-alipay</artifactId>
+            <version>1.0</version>
+        </dependency>
     </dependencies>
 </project>

+ 39 - 0
device-api-service/src/main/java/com/xy/alipay/AliPay.java

@@ -0,0 +1,39 @@
+package com.xy.alipay;
+
+import lombok.AllArgsConstructor;
+import lombok.Getter;
+
+import java.lang.annotation.*;
+
+/**
+ * 支付宝注解
+ *
+ * @author lijin
+ */
+@Target({ElementType.METHOD})
+@Retention(RetentionPolicy.RUNTIME)
+@Documented
+public @interface AliPay {
+
+    /**
+     * 类型
+     *
+     * @return
+     */
+    Type value();
+
+
+    @Getter
+    @AllArgsConstructor
+    enum Type {
+
+        RESTART("重启设备"),
+
+        BUSY_STATE("修改运营状态")
+
+        ;
+
+        private String type;
+    }
+
+}

+ 135 - 0
device-api-service/src/main/java/com/xy/alipay/AliPayAspet.java

@@ -0,0 +1,135 @@
+package com.xy.alipay;
+
+import cn.hutool.json.JSONObject;
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.xy.collections.list.JArrayList;
+import com.xy.collections.map.JMap;
+import com.xy.dto.CommandMqtt;
+import com.xy.dto.DeviceChangeStatusDTO;
+import com.xy.dto.MercMiniDeviceDto;
+import com.xy.entity.DeviceInfo;
+import com.xy.service.AlipayDeviceService;
+import com.xy.service.DeviceInfoServiceImpl;
+import com.xy.utils.AuthorizeUtils;
+import com.xy.utils.R;
+import com.xy.utils.enums.DictSonEnum;
+import lombok.AllArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.aspectj.lang.ProceedingJoinPoint;
+import org.aspectj.lang.annotation.Around;
+import org.aspectj.lang.annotation.Aspect;
+import org.springframework.stereotype.Component;
+
+import java.util.ArrayList;
+import java.util.List;
+
+@Slf4j
+@Aspect
+@Component
+@AllArgsConstructor
+public class AliPayAspet {
+
+    private DeviceInfoServiceImpl deviceInfoService;
+
+    private AlipayDeviceService alipayDeviceService;
+
+    /**
+     * 支付宝设备
+     *
+     * @param joinPoint
+     * @param aliPay
+     * @return
+     * @throws Throwable
+     */
+    @Around("@annotation(aliPay)")
+    public Object timer(ProceedingJoinPoint joinPoint, AliPay aliPay) throws Throwable {
+        String type = aliPay.value().getType();
+        Object[] args = joinPoint.getArgs();
+        Object result = R.ok();
+        try {
+            boolean fal = before(type, args);
+            if (fal) {
+                result = joinPoint.proceed(args);
+            }
+        } catch (Exception e) {
+            throw e;
+        }
+        return result;
+    }
+
+    public boolean before(String type, Object[] args) {
+        boolean fal = true;
+        //重启设备
+        if (type.equals(AliPay.Type.RESTART.getType())) {
+            List<CommandMqtt> restart = restart(args);
+            if (restart.size() > 0) {
+                args[0] = restart;
+            } else {
+                fal = false;
+            }
+        }
+        //修改运营状态
+        if (type.equals(AliPay.Type.BUSY_STATE.getType())) {
+            fal = busyState(args);
+        }
+        return fal;
+    }
+
+    /**
+     * 重启设备
+     *
+     * @param args
+     */
+    private List<CommandMqtt> restart(Object[] args) {
+        List<CommandMqtt> result = new ArrayList<>();
+        List<CommandMqtt> commandMqtts = (List<CommandMqtt>) args[0];
+        //查询支付宝设备信息
+        List<DeviceInfo> deviceInfos = deviceInfoService.list(new LambdaQueryWrapper<DeviceInfo>()
+                .in(DeviceInfo::getDeviceId, new JArrayList<>(commandMqtts).comparing(CommandMqtt::getDeviceId).getProperty(CommandMqtt::getDeviceId))
+                .eq(DeviceInfo::getDeviceType, DictSonEnum.DEVICE_TYPE_5.getKey())
+        );
+        if (deviceInfos.size() == 0) {
+            return commandMqtts;
+        }
+        JMap<Long, DeviceInfo> deviceInfosJMaps = new JArrayList<>(deviceInfos).toMap(DeviceInfo::getDeviceId).cover();
+        commandMqtts.forEach(commandMqtt -> {
+            JSONObject templet = commandMqtt.getTemplet();
+            JSONObject data = templet.getJSONObject("data");
+            DeviceInfo deviceInfo = deviceInfosJMaps.get(commandMqtt.getDeviceId());
+            if (deviceInfo == null) {
+                result.add(commandMqtt);
+                return;
+            }
+            //发送支付宝设备重启请求
+            if (data.getStr("type").equals("app") && data.getStr("task").equals("restart")) {
+                alipayDeviceService.deviceReboot(deviceInfo.getDistrictId().toString());
+            }
+        });
+        return result;
+    }
+
+    /**
+     * 修改运营状态
+     *
+     * @param args
+     * @return
+     */
+    private boolean busyState(Object[] args) {
+        MercMiniDeviceDto.BusySate busySate = (MercMiniDeviceDto.BusySate) args[0];
+        //查询支付宝设备信息
+        DeviceInfo deviceInfo = deviceInfoService.getOne(new LambdaQueryWrapper<DeviceInfo>()
+                .eq(DeviceInfo::getDeviceId, busySate.getDeviceId())
+                .eq(DeviceInfo::getDeviceType, DictSonEnum.DEVICE_TYPE_5.getKey())
+        );
+        if (deviceInfo == null) {
+            return true;
+        }
+        //发送支付宝设备修改运营状态请求
+        DeviceChangeStatusDTO deviceChangeStatusDTO = new DeviceChangeStatusDTO()
+                .setTerminalId(String.valueOf(busySate.getDeviceId()))
+                .setOperatorId(AuthorizeUtils.getLoginId(String.class))
+                .setStatus(busySate.getBusyState());
+        alipayDeviceService.changeStatus(deviceChangeStatusDTO);
+        return false;
+    }
+}

+ 96 - 0
device-api-service/src/main/java/com/xy/alipay/ApiDeviceServiceImpl.java

@@ -0,0 +1,96 @@
+package com.xy.alipay;
+
+import cn.hutool.json.JSONObject;
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.xxl.job.core.biz.model.ReturnT;
+import com.xxl.job.core.handler.annotation.XxlJob;
+import com.xy.config.DeviceThreadPoolConfig;
+import com.xy.consumer.connected.ConnectedMqttConfiguration;
+import com.xy.consumer.connected.ConnectedProducer;
+import com.xy.consumer.disconnect.DisconnectedMqttConfiguration;
+import com.xy.consumer.disconnect.DisconnectedProducer;
+import com.xy.dto.DeviceDetailDTO;
+import com.xy.entity.DeviceStatus;
+import com.xy.service.AlipayDeviceService;
+import com.xy.service.DeviceStatusServiceImpl;
+import com.xy.utils.R;
+import com.xy.utils.ThreadPoolUtils;
+import com.xy.vo.DeviceDetailVO;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import lombok.AllArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Component;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+
+import java.util.List;
+
+/**
+ * <p>
+ * 支付宝设备服务
+ * </p>
+ *
+ * @author lijin
+ * @since 2023-04-20
+ */
+@Slf4j
+@Component
+@AllArgsConstructor
+@Api(tags = "支付宝设备API")
+public class ApiDeviceServiceImpl {
+
+    private DeviceStatusServiceImpl deviceStatusService;
+
+    private AlipayDeviceService alipayDeviceService;
+
+    private ConnectedProducer connectedProducer;
+
+    private DisconnectedProducer disconnectedProducer;
+
+    /**
+     * 查询支付宝设备详情job
+     *
+     * @return
+     */
+    @XxlJob("alipayDeviceDetail")
+    public ReturnT<String> alipayDeviceDetail() {
+        //查询离线设备
+        List<DeviceStatus> deviceStatuses = deviceStatusService.list(new LambdaQueryWrapper<DeviceStatus>().eq(DeviceStatus::getNetState, 2));
+        if (deviceStatuses.size() == 0) {
+            return ReturnT.SUCCESS;
+        }
+        //查询支付宝设备详情
+        ThreadPoolUtils.Execute execute = ThreadPoolUtils.excPoll(DeviceThreadPoolConfig.ALIPAY_DEVICE_DETAIL, deviceStatuses.size());
+        deviceStatuses.forEach(deviceStatus -> execute.execute(() -> {
+            DeviceDetailVO deviceDetailVO = alipayDeviceService.queryDetail(new DeviceDetailDTO().setTerminalId(String.valueOf(deviceStatus.getDeviceId())));
+            //修改设备为在线
+            if (deviceDetailVO.getOnline()) {
+                JSONObject jsonObject = new JSONObject().set("clientid", deviceStatus.getDeviceId());
+                connectedProducer.sendToMqtt(jsonObject.toString(), ConnectedMqttConfiguration.TOPIC, 1);
+            }
+        }));
+        execute.end();
+        return ReturnT.SUCCESS;
+    }
+
+    @ApiOperation("刷新设备联网状态")
+    @PostMapping("refurbishDeviceNetWork")
+    public R refurbishDeviceNetWork(@RequestBody List<Long> deviceIds) {
+        ThreadPoolUtils.Execute execute = ThreadPoolUtils.excPoll(DeviceThreadPoolConfig.ALIPAY_DEVICE_DETAIL, deviceIds.size());
+        deviceIds.forEach(deviceId -> execute.execute(() -> {
+            DeviceDetailVO deviceDetailVO = alipayDeviceService.queryDetail(new DeviceDetailDTO().setTerminalId(String.valueOf(deviceId)));
+            JSONObject jsonObject = new JSONObject().set("clientid", deviceId);
+            if (deviceDetailVO.getOnline()) {
+                connectedProducer.sendToMqtt(jsonObject.toString(), ConnectedMqttConfiguration.TOPIC, 1);
+            } else {
+                disconnectedProducer.sendToMqtt(jsonObject.toString(), DisconnectedMqttConfiguration.TOPIC, 1);
+            }
+        }));
+        execute.end();
+        return R.ok();
+    }
+
+
+
+}

+ 110 - 0
device-api-service/src/main/java/com/xy/alipay/SpiDeviceServiceImpl.java

@@ -0,0 +1,110 @@
+package com.xy.alipay;
+
+import cn.hutool.json.JSONObject;
+import com.xy.consumer.disconnect.DisconnectedMqttConfiguration;
+import com.xy.consumer.disconnect.DisconnectedProducer;
+import com.xy.dto.DeviceErrorsRecordDto;
+import com.xy.dto.spi.DeviceAlarmNotifyDTO;
+import com.xy.dto.spi.DeviceStatusChangeNotifyDTO;
+import com.xy.entity.DeviceCharging;
+import com.xy.entity.DeviceInfo;
+import com.xy.entity.SysDictRedis;
+import com.xy.service.DeviceChargingServiceImpl;
+import com.xy.service.DeviceErrorsRecordServiceImpl;
+import com.xy.service.DeviceInfoServiceImpl;
+import com.xy.utils.SysDictUtils;
+import com.xy.utils.enums.DeviceErrorRecordTypesEnum;
+import com.xy.utils.enums.DictEnum;
+import com.xy.utils.enums.DictSonEnum;
+import com.xy.work.SpiDeviceService;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import lombok.AllArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+
+import java.time.LocalDateTime;
+import java.util.Map;
+
+
+/**
+ * spi 设备相关
+ *
+ * @author 谭斌
+ * @date 2023/04/16
+ */
+@Service
+@AllArgsConstructor
+@Slf4j
+@Api(tags = "支付宝设备相关SPI")
+public class SpiDeviceServiceImpl implements SpiDeviceService {
+
+    private DeviceInfoServiceImpl deviceInfoService;
+
+    private DeviceErrorsRecordServiceImpl deviceErrorsRecordService;
+
+    private DisconnectedProducer disconnectedProducer;
+
+    private DeviceChargingServiceImpl deviceChargingService;
+
+    @Override
+    @ApiOperation("设备告警通知")
+    public void deviceAlarmNotify(Map<String, String> params, DeviceAlarmNotifyDTO deviceAlarmNotifyDTO) {
+        //查询设备信息
+        DeviceInfo deviceInfo = deviceInfoService.getById(Long.valueOf(deviceAlarmNotifyDTO.getTerminalId()));
+        String faultCode = deviceAlarmNotifyDTO.getFaultCode();
+        DeviceErrorRecordTypesEnum deviceErrorRecordTypesEnum = faultCode.equals("DeviceOffline") ? DeviceErrorRecordTypesEnum.NET
+                : faultCode.equals("DoorOpenedOnNoTrade") ? DeviceErrorRecordTypesEnum.DOOR_LOCK
+                : null;
+        if (deviceErrorRecordTypesEnum == null) {
+            return;
+        }
+        //添加设备异常记录
+        DeviceErrorsRecordDto.Save save = new DeviceErrorsRecordDto.Save()
+                .setDeviceId(deviceInfo.getDeviceId());
+        save.setCode(deviceErrorRecordTypesEnum.getCode());
+        save.setErrorMsg(deviceAlarmNotifyDTO.getFaultMsg());
+        deviceErrorsRecordService.save(save);
+        //修改设备为离线
+        if (deviceErrorRecordTypesEnum.getCode() == DeviceErrorRecordTypesEnum.NET.getCode()) {
+            JSONObject jsonObject = new JSONObject().set("clientid", deviceInfo.getDeviceId());
+            disconnectedProducer.sendToMqtt(jsonObject.toString(), DisconnectedMqttConfiguration.TOPIC, 1);
+        }
+    }
+
+    @Override
+    @ApiOperation("设备状态变更通知")
+    public void deviceStatusChangeNotify(Map<String, String> params, DeviceStatusChangeNotifyDTO deviceStatusChangeNotifyDTO) {
+        //查询设备信息
+        DeviceInfo deviceInfo = deviceInfoService.getById(Long.valueOf(deviceStatusChangeNotifyDTO.getTerminalId()));
+        Integer status = deviceStatusChangeNotifyDTO.getStatus();
+        if (deviceInfo.getFreezeStatus().equals(status)) {
+            return;
+        }
+        //修改冻结状态、运营状态
+        DeviceInfo updateDeviceInfo = new DeviceInfo()
+                .setDeviceId(deviceInfo.getDeviceId())
+                .setBusyState(status)
+                .setFreezeStatus(status);
+        //修改激活状态
+        if (deviceStatusChangeNotifyDTO.getActiveStatus() != null && deviceStatusChangeNotifyDTO.getActiveStatus() == 1) {
+            if (deviceInfo == null || deviceInfo.getActiveState() != 1) {
+                LocalDateTime now = LocalDateTime.now();
+                updateDeviceInfo.setActiveState(deviceStatusChangeNotifyDTO.getActiveStatus());
+                updateDeviceInfo.setActiveTime(now);
+                //首次激活可试用x天
+                DeviceCharging deviceCharging = deviceChargingService.getById(deviceInfo.getDeviceId());
+                if (deviceCharging == null) {
+                    SysDictRedis sysDictRedis = SysDictUtils.get(DictEnum.DEVICE_CHARGING.getKey(), DictSonEnum.DEVICE_CHARGING_X.getKey());
+                    deviceChargingService.save(new DeviceCharging()
+                            .setDeviceId(deviceInfo.getDeviceId())
+                            .setChargingX(Integer.valueOf(sysDictRedis.getValue()))
+                            .setTimeout(now)
+                            .setCreateTime(now)
+                    );
+                }
+            }
+        }
+        deviceInfoService.updateById(updateDeviceInfo);
+    }
+}

+ 18 - 0
device-api-service/src/main/java/com/xy/config/DeviceThreadPoolConfig.java

@@ -15,6 +15,8 @@ public class DeviceThreadPoolConfig {
 
     public static final String DEVICE_NETWORK_POLL = "deviceNetWorkPoll";
 
+    public static final String ALIPAY_DEVICE_DETAIL = "alipayDeviceDetail";
+
     /**
      * 公用线程池
      */
@@ -62,4 +64,20 @@ public class DeviceThreadPoolConfig {
                 .queueSize(coreSize * 10)
                 .builder();
     }
+
+    /**
+     * 查询支付宝设备详情线程池
+     */
+    @DynamicTp
+    @Bean(ALIPAY_DEVICE_DETAIL)
+    public ThreadPoolTaskExecutor alipayDeviceDetail() {
+        int coreSize = 5;
+        return ThreadPoolUtils.newPoll()
+                .name(ALIPAY_DEVICE_DETAIL)
+                .coreSize(coreSize)
+                .maxSize(coreSize * 10)
+                .keepAlive(30)
+                .queueSize(coreSize * 10)
+                .builder();
+    }
 }

+ 2 - 0
device-api-service/src/main/java/com/xy/service/MqttServiceImpl.java

@@ -6,6 +6,7 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
 import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
 import com.baomidou.mybatisplus.core.metadata.IPage;
 import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import com.xy.alipay.AliPay;
 import com.xy.annotate.Runners;
 import com.xy.annotate.Timer;
 import com.xy.collections.map.JHashMap;
@@ -125,6 +126,7 @@ public class MqttServiceImpl extends ServiceImpl<MqttCommandMapper, MqttCommand>
 
     @Override
     @ApiOperation("指令发送")
+    @AliPay(AliPay.Type.RESTART)
     public R<List<Tuple.Tuple3<Long, Long, Boolean>>> senCommand(List<CommandMqtt> commandMqtts) {
         //发送指令
         List<MqttDto> mqttDtos = new ArrayList<>();

+ 2 - 2
device-start/src/main/resources/bootstrap.yml

@@ -10,11 +10,11 @@ cloud:
   center:
     url: 119.96.213.127:9007
     config:
-      shared-configs: redis.yaml,mysql.yaml,mqtt.yaml,xxl-job.yaml,xy-oss.yaml
+      shared-configs: redis.yaml,mysql.yaml,mqtt.yaml,xxl-job.yaml,xy-oss.yaml,alipay.yaml
       name: device
   service:
     name: dev-device
   feign:
     head:
       carr-heads:
-        - satoken
+        - satoken