提交 2342f7dd authored 作者: 林业通's avatar 林业通

红外遥控

上级 5655fca4
package tech.glinfo.enbao.modules.infrared.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import tech.glinfo.enbao.common.annotation.ApiLog;
import tech.glinfo.enbao.common.annotation.Login;
import tech.glinfo.enbao.common.annotation.LoginUser;
import tech.glinfo.enbao.common.utils.MapUtils;
import tech.glinfo.enbao.common.utils.R;
import tech.glinfo.enbao.common.utils.StringUtils;
import tech.glinfo.enbao.common.validator.ValidatorUtils;
import tech.glinfo.enbao.modules.appuser.entity.AppUserEntity;
import tech.glinfo.enbao.modules.infrared.entity.InfraredControlEntity;
import tech.glinfo.enbao.modules.infrared.form.InfraredControlForm;
import tech.glinfo.enbao.modules.infrared.service.OtherInfraredControlService;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
/**
* 用户遥控器
*
* @author linzhenjie
* @email linzhenjie@gltech.com
* @date 2021-07-27 10:33:36
*/
@RestController
@RequestMapping("/infraredControl")
@Api(value = "用户遥控器")
public class InfraredControlController {
private final static Logger logger = LoggerFactory.getLogger(InfraredControlController.class);
@Autowired
private OtherInfraredControlService otherInfraredControlService;
@Login
@GetMapping("list")
@ApiOperation("查询用户遥控器")
@ApiLog("查询用户遥控器")
public R list(@RequestParam Map<String, Object> params, @LoginUser AppUserEntity user) {
String deviceId = (String) params.get("deviceId");
if (StringUtils.isNotBlank(deviceId)) {
return R.ok().put("list", otherInfraredControlService.list(new QueryWrapper<InfraredControlEntity>().eq("device_id", deviceId)));
}else {
return R.ok().put("list", otherInfraredControlService.list(new QueryWrapper<InfraredControlEntity>().eq("user_id", user.getId())));
}
}
@Login
@GetMapping("info/{id}")
@ApiOperation("遥控器信息")
@ApiLog("遥控器信息")
public R info(@PathVariable("id") Integer id) {
InfraredControlEntity entity = otherInfraredControlService.getById(id);
return R.ok().put("info", entity);
}
@Login
@PostMapping("save")
@ApiOperation("保存用户遥控器")
@ApiLog("保存用户遥控器")
public R save(@LoginUser AppUserEntity user, @RequestBody InfraredControlForm form) throws InvocationTargetException, IllegalAccessException {
//表单校验
ValidatorUtils.validateEntity(form);
InfraredControlEntity entity = new InfraredControlEntity();
BeanUtils.copyProperties(entity, form);
entity.setUserId(user.getId());
boolean save = otherInfraredControlService.save(entity);
//新增设备遥控==开关的
if(form.getDeviceId() != null) {
//空调
if("空调".equals(form.getDeviceType()) || "电视".equals(form.getDeviceType())) {
String deviceType = form.getDeviceType();
String model = form.getModel();
Integer deviceId = form.getDeviceId();
String rtype = form.getRtype();
new Thread(new Runnable() {
@Override
public void run() {
otherInfraredControlService.saveInfraredCode(deviceType, model, deviceId, rtype);
}
}).start();
}
}
return save ? R.ok(new MapUtils().put("id", entity.getId())) : R.error("新增失败");
}
@Login
@PostMapping("update")
@ApiOperation("修改用户遥控器")
@ApiLog("修改用户遥控器")
public R update(@RequestBody InfraredControlForm form) throws InvocationTargetException, IllegalAccessException {
//表单校验
// ValidatorUtils.validateEntity(form);
if(StringUtils.isBlank(form.getRemark())){
return R.error("遥控器名称必录!");
}
InfraredControlEntity entity = new InfraredControlEntity();
BeanUtils.copyProperties(entity, form);
return otherInfraredControlService.updateById(entity) ? R.ok() : R.error("更新失败");
}
@Login
@PostMapping("delete")
@ApiOperation("用户遥控器")
@ApiLog("用户遥控器")
public R delete(@RequestBody Map<String, Object> params) {
Integer id = (Integer) params.get("id");
InfraredControlEntity entity = otherInfraredControlService.getById(id);
//删除红外缓存
if(entity.getDeviceId() != null) {
otherInfraredControlService.deleteInfraredCode(entity.getDeviceId(), entity.getDeviceType());
}
return otherInfraredControlService.removeById(id)? R.ok() : R.error("删除失败");
}
}
package tech.glinfo.enbao.modules.infrared.form;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.NotBlank;
/**
* @author lyt
* @date 2021/7/27 10:44
*/
@Data
@ApiModel(value = "红外遥控")
public class InfraredControlForm {
@ApiModelProperty(value = "ID,保存不用传,修改则传")
private Integer id;
@ApiModelProperty(value = "设备ID")
private Integer deviceId;
@ApiModelProperty(value = "设备类型")
@NotBlank(message="设备类型不能为空")
private String deviceType;
@ApiModelProperty(value = "遥控类型")
// @NotBlank(message="遥控类型不能为空")
private String rtype;
@ApiModelProperty(value = "品牌")
@NotBlank(message="品牌不能为空")
private String brand;
@ApiModelProperty(value = "型号")
@NotBlank(message="型号不能为空")
private String model;
@ApiModelProperty(value = "备注")
private String remark;
}
package tech.glinfo.enbao.modules.infrared.service;
import com.baomidou.mybatisplus.extension.service.IService;
import tech.glinfo.enbao.modules.infrared.entity.InfraredControlEntity;
/**
* 红外遥控器
*
* @author linyetong
* @email linyetong@gltech.com
* @date 2020-06-18 14:04:03
*/
public interface OtherInfraredControlService extends IService<InfraredControlEntity> {
void saveInfraredCode(String deviceType, String model, Integer deviceId, String rtype);
void deleteInfraredCode(Integer deviceId, String deviceType);
}
package tech.glinfo.enbao.modules.infrared.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tech.glinfo.enbao.common.contants.AppContants;
import tech.glinfo.enbao.common.utils.ByteUtils;
import tech.glinfo.enbao.common.utils.HttpUtil;
import tech.glinfo.enbao.common.utils.RedisUtils;
import tech.glinfo.enbao.common.utils.StringUtils;
import tech.glinfo.enbao.modules.infrared.dao.InfraredControlDao;
import tech.glinfo.enbao.modules.infrared.entity.InfraredControlEntity;
import tech.glinfo.enbao.modules.infrared.service.OtherInfraredControlService;
import tech.glinfo.enbao.modules.infrared.util.ProtocolUtil;
import tech.glinfo.enbao.modules.sh.entity.ShDeviceEntity;
import tech.glinfo.enbao.modules.sh.form.ProtocolContent;
import tech.glinfo.enbao.modules.sh.service.ShDeviceService;
@Service("otherInfraredControlService")
public class OtherInfraredControlServiceImpl extends ServiceImpl<InfraredControlDao, InfraredControlEntity> implements OtherInfraredControlService {
private final static Logger logger = LoggerFactory.getLogger(OtherInfraredControlServiceImpl.class);
//红外码库接口地址
public static final String INFRAREDURL = "https://cir.zwgongxiang.com/";
@Autowired
private ShDeviceService shDeviceService;
@Autowired
private RedisUtils redisUtils;
@Override
public void saveInfraredCode(String deviceType, String model, Integer deviceId, String rtype) {
//电视==电视是根据按键索引来获取红外数据
if("电视".equals(deviceType)) {
getDataFormIndex("电源", true, model, deviceId);
} else if("空调".equals(deviceType)) {
if(!"1".equals(rtype) && !"2".equals(rtype)) {//rtype不等于1和2是根据键值来获取红外数据
getDataFormIndex("电源", false, model, deviceId);
} else {
String close = "&par=1-1-8-0-0-";//关机指令参数
String open = "&par=0-1-8-0-0-";//开机指令参数
if("1".equals(rtype)) {
close += '0';
open += '0';
} else {
open += 'X';
close += 'X';
}
String openData = HttpUtil.doGet(INFRAREDURL + "keyevent.php?mac=d6a5e6f31f794be0&kfid=" + model + open);
JSONObject openDataJson = JSON.parseObject(openData);
if(openDataJson.containsKey("irdata")) {
String irdata = openDataJson.getString("irdata");
int first = irdata.indexOf(",");
String frequency = irdata.substring(0, first);
String data = irdata.substring(first + 1, irdata.length() - 1);
//打开空调
packageData(AppContants.INFRARED_AIR_KEY + deviceId + "_1", deviceId, frequency, data);
}
String closeData = HttpUtil.doGet(INFRAREDURL + "keyevent.php?mac=d6a5e6f31f794be0&kfid=" + model + close);
JSONObject closeDataJson = JSON.parseObject(closeData);
if(closeDataJson.containsKey("irdata")) {
String irdata = closeDataJson.getString("irdata");
int first = irdata.indexOf(",");
String frequency = irdata.substring(0, first);
String data = irdata.substring(first + 1, irdata.length() - 1);
//关闭空调
packageData(AppContants.INFRARED_AIR_KEY + deviceId + "_2", deviceId, frequency, data);
}
}
}
}
@Override
public void deleteInfraredCode(Integer deviceId, String deviceType) {
if("电视".equals(deviceType)) {
redisUtils.delete(AppContants.INFRARED_TV_KEY + deviceId);
} else if("空调".equals(deviceType)) {
redisUtils.delete(AppContants.INFRARED_AIR_KEY + deviceId);
redisUtils.delete(AppContants.INFRARED_AIR_KEY + deviceId + "_1");
redisUtils.delete(AppContants.INFRARED_AIR_KEY + deviceId + "_2");
}
}
/**
* 根据键值索引来获取红外数据
* @param key 中文按键
* @param flag true为电视,false为空调
* @param model
* @param deviceId
*/
private void getDataFormIndex(String key, boolean flag, String model, Integer deviceId) {
String keys = HttpUtil.doGet(INFRAREDURL + "getkeylist.php?mac=d6a5e6f31f794be0&kfid=" + model);
if(keys != null) {
JSONObject json = JSON.parseObject(keys);
if(json.containsKey("keylist")) {
JSONArray keylist = json.getJSONArray("keylist");
int index = 0;
for(int i=0; i<keylist.size();i++) {
if(key.equals(keylist.getString(i))) {
index = flag ? i+1 : i;
break;
}
}
if(index > 0) {
String datas = HttpUtil.doGet(INFRAREDURL + "keyevent.php?mac=d6a5e6f31f794be0&keyid="+index+"&kfid=" + model);
JSONObject dataJson = JSON.parseObject(datas);
if(dataJson.containsKey("irdata")) {
String irdata = dataJson.getString("irdata");
int first = irdata.indexOf(",");
String frequency = irdata.substring(0, first);
String data = irdata.substring(first + 1, irdata.length() - 1);
packageData((flag?AppContants.INFRARED_TV_KEY : AppContants.INFRARED_AIR_KEY) + deviceId, deviceId, frequency, data);
}
}
}
}
}
private void packageData(String redisKey, Integer deviceId, String frequency, String datas) {
ShDeviceEntity device = shDeviceService.getById(deviceId);
//转换
StringBuilder sb = new StringBuilder();
StringBuilder sb1 = new StringBuilder();
String[] codes = datas.split(",");
ProtocolContent protocol = new ProtocolContent();
protocol.setReceiveId(device.getNumbering());
protocol.setDeviceType("02");
logger.info("######数据长度:{}", codes.length);
if(codes.length > 300) { //大于300需要走压缩
String cmds = ProtocolUtil.getCmds(codes, frequency);
logger.info("压缩后的数据:{}", cmds);
protocol.setCmd("1B");
protocol.setContent(cmds);
} else {
protocol.setCmd("19");
for (String in : codes) {
sb1.append(in).append(",");
sb.append(ByteUtils.int2Hex(Integer.parseInt(in), 4));
}
logger.info(sb1.toString());
logger.info(sb.toString());
String content = StringUtils.appendString(sb.toString(), 1200, false, "0");
logger.info(content);
// InfraredControlCodeEntity controlCodeEntity = infraredControlCodeService.getOne(new QueryWrapper<InfraredControlCodeEntity>().eq("brand_id", controlUserEntity.getBrandId()).eq("remark", name).last("LIMIT 1"));
// if (controlCodeEntity != null) {
String body = StringUtils.appendString(ByteUtils.int2Hex(Integer.parseInt(frequency)), 4, true, "0") +
StringUtils.appendString(ByteUtils.int2Hex((sb.length() / 2)), 4, true, "0") +
content;
protocol.setContent(body);
}
redisUtils.set(redisKey, JSON.toJSONString(protocol));
}
}
\ No newline at end of file
package tech.glinfo.enbao.modules.infrared.util;
import tech.glinfo.enbao.common.utils.ByteUtils;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ProtocolUtil {
/**
* 压缩数据
* @param datas
* @param frequency
* @return
*/
public static String getCmds(String[] datas, String frequency) {
List<String> samples = new ArrayList<>();
Map<String, String> samplesIndex = new HashMap<>();
for (String code : datas) {
if(!samplesIndex.containsKey(code)) {
int i = new BigDecimal(Integer.valueOf(code) / 4).setScale(0, RoundingMode.HALF_UP).intValue();
samples.add(ByteUtils.int2Hex(i, 4));
samplesIndex.put(code, Integer.toHexString(samples.size()));
}
}
while (samples.size()<16) {
samples.add("0000");
}
//样版
// StringBuffer samp = new StringBuffer("0324");
StringBuffer samp = new StringBuffer();
samp.append(ByteUtils.int2Hex(Integer.valueOf(frequency), 4));
for (String s : samples) {
samp.append(s);
}
int length1 = datas.length;
if(length1%2 != 0) {
length1++;
}
samp.append(ByteUtils.int2Hex(Integer.valueOf(length1), 4));
// System.out.print(splitT(samp.toString()));
//长度
StringBuffer sbdata = new StringBuffer(samp);
//循环查找数据所在位置
for (String code : datas) {
sbdata.append(samplesIndex.get(code));
}
int length = sbdata.length();
if(length%2 != 0) {
sbdata.append("0");
}
return sbdata.toString();
}
}
package tech.glinfo.enbao.modules.infrared.dao;
import tech.glinfo.enbao.modules.infrared.entity.InfraredControlEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 用户遥控器
*
* @author linyetong
* @email linyetong@glinfo.com
* @date 2022-02-23 10:03:36
*/
@Mapper
public interface InfraredControlDao extends BaseMapper<InfraredControlEntity> {
}
package tech.glinfo.enbao.modules.infrared.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
/**
* 用户遥控器
*
* @author linyetong
* @email linyetong@glinfo.com
* @date 2022-02-23 10:03:36
*/
@Data
@TableName("infrared_control")
public class InfraredControlEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
*
*/
@TableId
private Integer id;
/**
* 设备ID
*/
private Integer deviceId;
/**
* 用户ID
*/
private Integer userId;
/**
* 设备类型
*/
private String deviceType;
/**
* 遥控类型
*/
private String rtype;
/**
* 品牌
*/
private String brand;
/**
* 型号
*/
private String model;
/**
* 备注
*/
private String remark;
/**
* 创建时间
*/
private Date createTime;
}
package tech.glinfo.enbao.modules.infrared.service;
import com.baomidou.mybatisplus.extension.service.IService;
import tech.glinfo.enbao.common.utils.PageUtils;
import tech.glinfo.enbao.modules.infrared.entity.InfraredControlEntity;
import java.util.Map;
/**
* 用户遥控器
*
* @author linyetong
* @email linyetong@glinfo.com
* @date 2022-02-23 10:03:36
*/
public interface InfraredControlService extends IService<InfraredControlEntity> {
PageUtils queryPage(Map<String, Object> params);
}
package tech.glinfo.enbao.modules.infrared.service.impl;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import tech.glinfo.enbao.common.utils.PageUtils;
import tech.glinfo.enbao.common.utils.Query;
import tech.glinfo.enbao.modules.infrared.dao.InfraredControlDao;
import tech.glinfo.enbao.modules.infrared.entity.InfraredControlEntity;
import tech.glinfo.enbao.modules.infrared.service.InfraredControlService;
@Service("infraredControlService")
public class InfraredControlServiceImpl extends ServiceImpl<InfraredControlDao, InfraredControlEntity> implements InfraredControlService {
@Override
public PageUtils queryPage(Map<String, Object> params) {
IPage<InfraredControlEntity> page = this.page(
new Query<InfraredControlEntity>().getPage(params),
new QueryWrapper<InfraredControlEntity>()
);
return new PageUtils(page);
}
}
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="tech.glinfo.enbao.modules.infrared.dao.InfraredControlDao">
<!-- 可根据自己的需求,是否要使用 -->
<resultMap type="tech.glinfo.enbao.modules.infrared.entity.InfraredControlEntity" id="infraredControlMap">
<result property="id" column="id"/>
<result property="deviceId" column="device_id"/>
<result property="userId" column="user_id"/>
<result property="deviceType" column="device_type"/>
<result property="rtype" column="rtype"/>
<result property="brand" column="brand"/>
<result property="model" column="model"/>
<result property="remark" column="remark"/>
<result property="createTime" column="create_time"/>
</resultMap>
</mapper>
\ No newline at end of file
......@@ -299,3 +299,16 @@ alter table sh_family_member add `status` tinyint(2) DEFAULT '1' COMMENT '状态
alter table sh_family_member add `invite_id` int(11) DEFAULT NULL COMMENT '邀请人ID' after `status` ;
alter table sh_dlink add `status_o` tinyint(2) DEFAULT NULL COMMENT '开关发起状态1[1开启,2关闭]' after `status` ;
alter table sh_dlink add `status_t` tinyint(2) DEFAULT NULL COMMENT '开关发起状态2[1开启,2关闭]' after `status` ;
CREATE TABLE `infrared_control` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`device_id` int(11) DEFAULT NULL COMMENT '设备ID',
`user_id` int(11) NOT NULL COMMENT '用户ID',
`device_type` varchar(50) DEFAULT NULL COMMENT '设备类型',
`rtype` varchar(50) DEFAULT NULL COMMENT '遥控类型',
`brand` varchar(50) DEFAULT NULL COMMENT '品牌',
`model` varchar(50) DEFAULT NULL COMMENT '型号',
`remark` varchar(50) DEFAULT NULL COMMENT '备注',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户遥控器';
\ No newline at end of file
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论