SmartUserDeviceServiceImpl.java 7.96 KB
package com.glsx.smart.service.impl;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.glsx.plat.common.utils.HttpUtils;
import com.glsx.plat.common.utils.StringUtils;
import com.glsx.smart.constant.Constants;
import com.glsx.smart.dao.entity.SmartUserChannel;
import com.glsx.smart.dao.entity.SmartUserDevice;
import com.glsx.smart.dao.entity.SmartUserRelation;
import com.glsx.smart.dao.mapper.SmartProductMapper;
import com.glsx.smart.dao.mapper.SmartUserChannelMapper;
import com.glsx.smart.dao.mapper.SmartUserDeviceMapper;
import com.glsx.smart.dao.mapper.SmartUserRelationMapper;
import com.glsx.smart.exception.BusinessException;
import com.glsx.smart.exception.ResultEnum;
import com.glsx.smart.redis.RedisService;
import com.glsx.smart.service.BaseService;
import com.glsx.smart.service.SmartUserDeviceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * <p>Description: 用户设备业务
 * <p>Project: chejia-smart
 *
 * @author wbh
 * @date 2021-04-23
 */
@Slf4j
@Service
public class SmartUserDeviceServiceImpl extends BaseService implements SmartUserDeviceService {
    @Value("${device_remote_url}")
    private String remoteUrl;

    @Value("${user_bind_key}")
    private String userBindKeyApi;

    @Value("${user_send_command}")
    private String userSendCommandApi;

    @Value("${unbindUrl}")
    private String unbindUrl;

    @Value("${user_device_subscribe}")
    private String userDeviceSubscribeApi;

    @Resource
    private SmartUserDeviceMapper userDeviceMapper;

    @Resource
    private SmartUserRelationMapper userRelationMapper;

    @Resource
    private SmartUserChannelMapper userChannelMapper;

    @Resource
    private SmartProductMapper productMapper;

    @Autowired
    private RedisService redisService;

    @Override
    public List<SmartUserDevice> getList(SmartUserDevice req) {
        return userDeviceMapper.getList(req);
    }

    @Override
    public SmartUserDevice getByDeviceId(SmartUserDevice req) {
        SmartUserDevice userDevice = userDeviceMapper.getByDeviceId(req);
        if (userDevice == null) {
            throw BusinessException.create(ResultEnum.DEVICE_NOT_FOUND);
        }
        return userDevice;
    }

    @Override
    @Transactional
    public int save(SmartUserDevice req) {
        int rows;
        Date now = new Date();
        SmartUserDevice record = new SmartUserDevice();
        record.setDeviceId(req.getDeviceId());
        record.setChannel(req.getChannel());
        SmartUserDevice savedUserDevice = userDeviceMapper.selectOne(record);
        if (savedUserDevice == null) {
            if (StringUtils.isBlank(req.getUid())) {
                throw BusinessException.create(ResultEnum.PARAM_EMPTY, "uid");
            }
            // 根据第三方用户 id 查询用户绑定信息
            SmartUserChannel ucRecord = new SmartUserChannel();
            ucRecord.setThirdId(req.getUid());
            SmartUserChannel savedUserChannel = userChannelMapper.selectOne(ucRecord);
            if (savedUserChannel == null) {
                throw BusinessException.create(ResultEnum.USER_NOT_FOUND);
            }
            // 插入用户信息
            req.setUserId(savedUserChannel.getUserId());
            req.setCreateTime(now);
            req.setUpdateTime(now);
            rows = userDeviceMapper.insertSelective(req);
            // 订阅用户设备
            this.subscribeDevice(req);
        } else {
            if (StringUtils.isBlank(req.getDeviceName())) {
                throw BusinessException.create(ResultEnum.PARAM_EMPTY, "deviceName");
            }
            savedUserDevice.setDeviceName(req.getDeviceName());
            savedUserDevice.setUpdateTime(now);
            rows = userDeviceMapper.updateByPrimaryKeySelective(savedUserDevice);
        }
        return rows;
    }

    @Override
    public int deleteDevice(SmartUserDevice req) {
        int rows;
        rows = userDeviceMapper.deleteDevice(req);
        return rows;
    }

    @Override
    public String getUserBindKey(String token) {
        JSONObject reqObj = new JSONObject();
        reqObj.put("token", token);
        String url = remoteUrl + userBindKeyApi;
        log.info("$$$$ getUserBindKey url = {}, req = {}", url, reqObj.toJSONString());
        String respJson = HttpUtils.get(url, reqObj);
        log.info("$$$$ getUserBindKey resp = {}", respJson);
        JSONObject respObj = JSON.parseObject(respJson);
        String bindKey = "200".equals(respObj.getString("code"))
                ? respObj.getJSONObject("message").getString("bindKey") : null;
        return bindKey;
    }

    @Override
    public String sendCommand(JSONObject req) {
        String url = remoteUrl + userSendCommandApi;
        log.info("$$$$ sendCommand url = {}, param: {}", url, req.toJSONString());
        String respJson = HttpUtils.post(url, req.toJSONString());
        log.info("$$$$ sendCommand resp = {}", respJson);
        JSONObject respObj = JSON.parseObject(respJson);
        String result = "200".equals(respObj.getString("code"))
                ? respObj.getString("result") : null;
        return result;
    }

    @Override
    public String unbind(JSONObject req) {
        String url = remoteUrl + unbindUrl;
        log.info("$$$$ unbind url = {}, param: {}", url, req.toJSONString());
        String respJson = HttpUtils.get(url, req);
        log.info("$$$$ unbind resp = {}", respJson);
        JSONObject respObj = JSON.parseObject(respJson);
        String result = "200".equals(respObj.getString("code"))
                ? "true" : "false";
        return result;
    }

    /**
     * 订阅用户设备
     *
     * @param req 请求
     */
    private void subscribeDevice(SmartUserDevice req) {
        if (Constants.USER_CHANNEL_AQARA.equals(req.getChannel())) {
            // 只有绿米的设备需要订阅
            if (StringUtils.isBlank(req.getPlatformProductId())) {
                throw BusinessException.create(ResultEnum.PARAM_EMPTY, "platformProductId");
            }
            // 通过用户手机号获取用户 token
            SmartUserRelation userRelation = userRelationMapper.selectByPrimaryKey(req.getUserId());
            String token = (String) redisService.get(userRelation.getPhone() + "_aqara");
            // 查询支持的指令集
            List<String> commands = productMapper.getSupportedCommands(req.getPlatformProductId());
            log.info("$$$$ subscribeDevice commands = {}", JSON.toJSONString(commands));
            if (!commands.isEmpty()) {
                // 指令集不为空才订阅
                // 请求 url 参数
                Map<String, Object> reqParam = new HashMap<>();
                reqParam.put("token", token);
                // 请求 body
                JSONObject reqData = new JSONObject();
                reqData.put("did", req.getDeviceId());
                reqData.put("attrs", commands);
                JSONObject reqObj = new JSONObject();
                reqObj.put("data", reqData);
                String rawUrl = remoteUrl + userDeviceSubscribeApi;
                String url = HttpUtils.urlWithForm(rawUrl, reqParam, StandardCharsets.UTF_8,
                        true);
                log.info("$$$$ subscribeDevice url = {}, req = {}", url, reqObj.toJSONString());
                String respJson = HttpUtils.post(url, reqObj.toJSONString());
                log.info("$$$$ subscribeDevice resp = {}", respJson);
                JSONObject respObj = JSON.parseObject(respJson);
                if (!"200".equals(respObj.getString("code"))) {
                    throw BusinessException.create(ResultEnum.DEVICE_SUBSCRIBE_ERROR);
                }
            }
        }
    }
}