feat(iot): 为设备添加经度、纬度和图标信息

- 在 Device 和 DeviceVo 类中添加 longitude、latitude 和 icon 字段
- 更新 DeviceMapper.xml以支持新字段的映射- 修改数据库结构,在 iot_device 表中添加新字段
- 插入测试数据以验证新功能
This commit is contained in:
zhuangtianxiang 2025-02-28 17:23:22 +08:00
parent da24f15ca2
commit 8222b69e48
9 changed files with 560 additions and 10 deletions

10
pom.xml
View File

@ -152,11 +152,11 @@
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!--mqtt依赖-->
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-mqtt</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>

View File

@ -98,6 +98,21 @@ public class Device extends BaseEntity {
@TableField(value = "dept_id", fill = FieldFill.INSERT)
public Long deptId;
/**
* 设备经度
*/
public Double longitude;
/**
* 设备纬度
*/
public Double latitude;
/**
* 设备图标
*/
public String icon;
public enum Status implements IEnum<Integer>, IState<Status> {
UNACTIVATED(0, "未激活"),

View File

@ -96,6 +96,22 @@ public class DeviceVo {
*/
public String deviceUpdateBy;
/**
* 设备经度
*/
public Double longitude;
/**
* 设备纬度
*/
public Double latitude;
/**
* 设备图标
*/
public String icon;
/**
* 所属产品ID
*/

View File

@ -0,0 +1,303 @@
//package com.zsc.edu.gateway.modules.mqtt.config;
//
//import com.zsc.edu.gateway.modules.iot.device.vo.DeviceVo;
//import jakarta.annotation.Resource;
//import lombok.extern.slf4j.Slf4j;
//import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.boot.configurationprocessor.json.JSONObject;
//import org.springframework.context.ApplicationContext;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.integration.annotation.ServiceActivator;
//import org.springframework.integration.channel.DirectChannel;
//import org.springframework.integration.core.MessageProducer;
//import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
//import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
//import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
//import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
//import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
//import org.springframework.messaging.MessageChannel;
//import org.springframework.messaging.MessageHandler;
//import org.springframework.util.StringUtils;
//
//import java.io.IOException;
//import java.text.ParseException;
//import java.text.SimpleDateFormat;
//import java.util.Date;
//import java.util.TimeZone;
//import java.util.UUID;
//
//@Slf4j
//@Configuration
//public class MqttConfig {
//
// @Resource
// private ApplicationContext applicationContext;
// @Resource
// private UploadDataSocketProcessor uploadDataSocketProcessor;
//
//
// public static final String CHANNEL_OUT = "mqttOutboundChannel";
// public static final String CHANNEL_IN = "mqttInputChannel";
//
// private static final byte[] WILL_DATA;
//
// static {
// WILL_DATA = "offline".getBytes();
// }
//
// @Value("${gatherer.version}")
// private String gatherer;
// @Value("${mqtt.username}")
// private String username;
// @Value("${mqtt.password}")
// private String password;
// @Value("${mqtt.host}")
// private String host;
// @Value("${mqtt.port}")
// private String port;
// @Value("${mqtt.topic}")
// private String topic;
// @Value("${mqtt.qos}")
// private Integer qos;
//
// /**
// * 创建MqttPahoClientFactory设置MQTT Broker连接属性如果使用ssl验证也在这里设置
// * @return factory
// */
// @Bean
// public MqttPahoClientFactory mqttPahoClientFactory() {
// DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
// MqttConnectOptions options = new MqttConnectOptions();
//
// if(StringUtils.hasText(username)) {
// options.setUserName(username);
// }
//
// options.setPassword(password.toCharArray());
//
// options.setServerURIs(new String[]{host + ":" + port});
//
// options.setConnectionTimeout(10);
//
// options.setKeepAliveInterval(20);
//
// options.setWill("willTopic", WILL_DATA, 2, false);
// factory.setConnectionOptions(options);
//
// return factory;
// }
//
// /**
// * 入站通道
// */
// @Bean
// public MessageChannel mqttInputChannel() {
// return new DirectChannel();
// }
//
// /**
// * 入站
// */
// @Bean
// public MessageProducer inbound() {
// // Paho客户端消息驱动通道适配器主要用来订阅主题
// MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter(
// "clientId-" + UUID.randomUUID(),
// mqttPahoClientFactory(),
// "/v1/devices/+/datas"
// );
// adapter.setCompletionTimeout(5000);
//
// // Paho消息转换器
// DefaultPahoMessageConverter defaultPahoMessageConverter = new DefaultPahoMessageConverter();
//
// // 按字节接收消息
//// defaultPahoMessageConverter.setPayloadAsBytes(true);
// adapter.setConverter(defaultPahoMessageConverter);
// adapter.setQos(qos);
// adapter.setOutputChannel(mqttInputChannel());
// return adapter;
//
// }
//
// /**
// * ServiceActivator注解表明 当前方法用于处理MQTT消息inputChannel参数指定了用于消费的channel
// * @return
// */
// @Bean
// @ServiceActivator(inputChannel = CHANNEL_IN)
// public MessageHandler handler() {
// return message -> {
// String topic = message.getHeaders().get("mqtt_receivedTopic").toString();
// String deviceCode = topic.split("/")[3];
// String deviceGatherer = deviceCode.substring(0,3);
// if (topic.matches("/v1/devices/\\d{12}/datas") && deviceGatherer.equals(gatherer)) {
// JSONObject payload = JSONObject.parseObject(message.getPayload().toString());
// Integer deviceModel = Integer.valueOf(deviceCode.substring(3,5));
// log.info("获取设备编码:" + deviceCode);
// log.info("负载:" + payload);
// JSONObject data = (JSONObject) JSONPath.eval(payload, "$.devices[0].services[0].data");
// DeviceVo deviceVo = null;
// switch (deviceModel) {
// case 2:
// deviceVo = decodeSpike(data, deviceCode, deviceModel);
// break;
// case 5:
// deviceVo = decodeCirculation(data, deviceCode, deviceModel);
// break;
// default:
// break;
// }
// if (deviceVo == null) return; // 或者抛出异常根据你的需求处理
// try {
// uploadDataSocketProcessor.processDeviceV2(null, deviceVo);
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// } else {
// log.error("丢弃信息,主题["+ topic +"]");
// }
// };
// }
//
// private DeviceVo decodeCirculation(JSONObject data, String deviceCode, Integer deviceModel) {
//
//// "iccid": "89860818102381420337",
//// "imsi": "460088822108587",
//// "signal": 2,
//// "recordTime": "20241212T003246Z",
//// "battery": 100,
//// "current": 0,
//// "warning": 0
//
// String iccid = data.getString("iccid");
// String imsi = data.getString("imsi");
// Integer signal = data.getInteger("signal");
// String recordTimeString = data.getString("recordTime");
// // 使用 SimpleDateFormat 解析日期字符串
// SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
// Date recordTime;
// try {
// recordTime = dateFormat.parse(recordTimeString);
// } catch (ParseException e) {
// log.error("无法解析日期字符串: " + recordTimeString, e);
// return null;
// }
// Integer battery = data.getInteger("battery");
// Float current = data.getFloat("current");
// Integer warning = data.getInteger("warning");
//
// Record record = new Record();
// record.setWarn(warning);
//// record.setDeviceId(deviceId);
// record.setDeviceSignal(signal);
// record.setBattery(battery);
// record.setTemp1(current);
// record.setShakeWarn(warning & 1);
// record.setTemp1Warn(warning >> 1 & 1);
// record.setTemp2Warn(warning >> 2 & 1);
// record.setTemp3Warn(warning >> 3 & 1);
// record.setEarlyWarn(warning >> 4 & 1);
// record.setWarn(warning);
// record.setRecordTime(recordTime);
// DeviceVo deviceVo = new DeviceVo();
// deviceVo.setClientId(deviceCode);
// deviceVo.setSimCode(iccid);
// deviceVo.setImeiCode(imsi);
// deviceVo.setDeviceModel(deviceModel);
// deviceVo.setWarn(warning);
// deviceVo.setRecordList(Lists.newArrayList(record));
// return deviceVo;
// }
//
// private static DeviceVo decodeSpike(JSONObject data, String deviceCode, Integer deviceModel) {
//// "longitude": "31.2412402273",
//// "latitude": "121.473992206",
//// "iccid": "89860321047601121407",
//// "imsi": "460115009044492",
//// "signal": 1,
//// "recordTime": "20241205T124818Z",
//// "battery": 76,
//// "warning": 0
//
// String iccid = data.getString("iccid");
// String imsi = data.getString("imsi");
// Integer signal = data.getInteger("signal");
// String recordTimeString = data.getString("recordTime");
// // 使用 SimpleDateFormat 解析日期字符串
// SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
// Date recordTime;
// try {
// recordTime = dateFormat.parse(recordTimeString);
// } catch (ParseException e) {
// log.error("无法解析日期字符串: " + recordTimeString, e);
// return null;
// }
// Integer battery = data.getInteger("battery");
// Integer warning = data.getInteger("warning");
//
// int newWarn = 0;
// // 获取warn的最后三位
// int lastThreeBits = warning & 0b111;
// // 检查最后三位是否为011
// if (lastThreeBits == 0b011) {
// newWarn |= 1; // 设置newWarn的第一位为1
// }
// // 获取warn的第四位的值
// int fourthBit = (warning >> 3) & 1;
// // 将warn的第四位的值设置到newWarn的第八位
// if (fourthBit == 1) {
// newWarn |= (1 << 8); // 设置newWarn的第八位为1
// }
//
// Record record = new Record();
// record.setWarn(newWarn);
//// record.setDeviceId(deviceId);
// record.setDeviceSignal(signal);
// record.setBattery(battery);
// record.setShakeWarn(newWarn & 1);
// record.setTemp1Warn(newWarn >> 1 & 1);
// record.setTemp2Warn(newWarn >> 2 & 1);
// record.setTemp3Warn(newWarn >> 3 & 1);
// record.setEarlyWarn(newWarn >> 4 & 1);
// record.setWarn(newWarn);
// record.setRecordTime(recordTime);
// DeviceVo deviceVo = new DeviceVo();
// deviceVo.setClientId(deviceCode);
// deviceVo.setSimCode(iccid);
// deviceVo.setImeiCode(imsi);
// deviceVo.setDeviceModel(deviceModel);
// deviceVo.setWarn(newWarn);
// deviceVo.setRecordList(Lists.newArrayList(record));
// return deviceVo;
// }
//
//
// /**
// * 出站通道
// */
// @Bean
// public MessageChannel mqttOutboundChannel() {
// return new DirectChannel();
// }
//
// /**
// * 出站
// */
// @Bean
// @ServiceActivator(inputChannel = CHANNEL_OUT)
// public MessageHandler outbound() {
// MqttPahoMessageHandler messageHandler = new MqttPahoMessageHandler(
// "clientId" + UUID.randomUUID(),
// mqttPahoClientFactory()
// );
// messageHandler.setAsync(true);
// messageHandler.setDefaultTopic(topic);
// messageHandler.setConverter(new DefaultPahoMessageConverter());
// return messageHandler;
//
// }
//
//}

View File

@ -0,0 +1,49 @@
//package com.zsc.edu.gateway.modules.mqtt.config;
//
//import org.springframework.integration.annotation.MessagingGateway;
//import org.springframework.integration.mqtt.support.MqttHeaders;
//import org.springframework.messaging.handler.annotation.Header;
//import org.springframework.stereotype.Component;
//
//@Component
//@MessagingGateway(defaultRequestChannel = MqttConfig.CHANNEL_OUT)
//public interface MqttSender {
//
// /**
// * 定义重载方法用于消息发送
// * @param payload
// */
// void sendMsg(String payload);
//
// /**
// * 指定topic进行消息发送
// * @param topic
// * @param payload
// */
// void sendMsg(@Header(MqttHeaders.TOPIC) String topic, String payload);
//
// /**
// * 指定topic进行消息发送
// * @param topic
// * @param retain
// * @param payload
// */
// void sendMsg(@Header(MqttHeaders.TOPIC) String topic, @Header(MqttHeaders.RETAINED) boolean retain, String payload);
//
//
// /**
// * 指定topic进行消息发送
// * @param topic
// * @param qos
// * @param payload
// */
// void sendMsg(@Header(MqttHeaders.TOPIC) String topic, @Header(MqttHeaders.QOS) int qos, String payload);
//
// /**
// * 指定topic进行消息发送
// * @param topic
// * @param qos
// * @param payload
// */
// void sendMsg(@Header(MqttHeaders.TOPIC) String topic, @Header(MqttHeaders.QOS) int qos, byte[] payload);
//}

View File

@ -0,0 +1,73 @@
package com.zsc.edu.gateway.modules.mqtt.config;
import com.zsc.edu.gateway.modules.iot.device.vo.DeviceVo;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
@Slf4j
public class UploadDataSocketProcessor {
/**
* 处理设备数据并上传
*
* @param context 上下文对象这里传入的是null
* @param deviceVo 设备数据对象
* @throws IOException 如果上传过程中发生IO异常
*/
public void processDeviceV2(Object context, DeviceVo deviceVo) throws IOException {
// 这里可以添加具体的上传逻辑
// 例如将设备数据转换为JSON格式并通过网络发送到服务器
if (deviceVo == null) {
log.warn("尝试处理空的DeviceVo对象");
return;
}
// 示例将DeviceVo对象转换为JSON字符串
String deviceDataJson = convertDeviceVoToJson(deviceVo);
log.info("设备数据JSON: {}", deviceDataJson);
// 示例通过网络上传设备数据
// 注意这里需要替换为实际的上传逻辑
uploadDeviceData(deviceDataJson);
}
/**
* 将DeviceVo对象转换为JSON字符串
*
* @param deviceVo 设备数据对象
* @return JSON字符串
*/
private String convertDeviceVoToJson(DeviceVo deviceVo) {
// 这里可以使用Jackson或其他JSON库进行转换
// 示例使用Jackson库
try {
return new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(deviceVo);
} catch (Exception e) {
log.error("无法将DeviceVo对象转换为JSON", e);
return "{}";
}
}
/**
* 上传设备数据到服务器
*
* @param deviceDataJson 设备数据的JSON字符串
* @throws IOException 如果上传过程中发生IO异常
*/
private void uploadDeviceData(String deviceDataJson) throws IOException {
// 这里可以添加具体的上传逻辑
// 示例通过HTTP POST请求上传数据
// 注意这里需要替换为实际的上传逻辑
log.info("上传设备数据: {}", deviceDataJson);
// 示例使用HttpClient发送POST请求
// HttpClient httpClient = HttpClient.newHttpClient();
// HttpRequest request = HttpRequest.newBuilder()
// .uri(URI.create("http://example.com/upload"))
// .header("Content-Type", "application/json")
// .POST(HttpRequest.BodyPublishers.ofString(deviceDataJson))
// .build();
// HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
// log.info("上传响应: {}", response.body());
}
}

View File

@ -779,3 +779,86 @@ VALUES ('user', 'create', 'Created a new user', '2023-10-01 10:00:00'),
('property', 'update', 'Updated property value', '2023-10-01 12:00:00'),
('notice', 'create', 'Sent a notice', '2023-10-01 12:15:00');
INSERT INTO iot_device (name,
online,
state,
hardware_version,
firmware_version,
factory_id,
client_id,
product_id,
extend_params,
properties,
create_by,
create_time,
update_by,
update_time,
remark,
dept_id,
create_id,
longitude,
latitude,
icon)
VALUES ('Device1', TRUE, 2, 'HW1.0', 'FW1.0', 'FAC12345', 'CLI12345', 1, '{
"param1": "value1"
}', '{
"prop1": "value1"
}', 'admin', CURRENT_TIMESTAMP, 'admin', CURRENT_TIMESTAMP, 'Device 1 remark', 1, 1, 31.241240, 121.473992,
'icon1.png'),
('Device2', FALSE, 0, 'HW1.1', 'FW1.1', 'FAC12346', 'CLI12346', 2, '{
"param2": "value2"
}', '{
"prop2": "value2"
}', 'admin', CURRENT_TIMESTAMP, 'admin', CURRENT_TIMESTAMP, 'Device 2 remark', 2, 2, 31.241241, 121.473993,
'icon2.png'),
('Device3', TRUE, 2, 'HW1.2', 'FW1.2', 'FAC12347', 'CLI12347', 1, '{
"param3": "value3"
}', '{
"prop3": "value3"
}', 'admin', CURRENT_TIMESTAMP, 'admin', CURRENT_TIMESTAMP, 'Device 3 remark', 1, 3, 31.241242, 121.473994,
'icon3.png'),
('Device4', FALSE, 1, 'HW1.3', 'FW1.3', 'FAC12348', 'CLI12348', 2, '{
"param4": "value4"
}', '{
"prop4": "value4"
}', 'admin', CURRENT_TIMESTAMP, 'admin', CURRENT_TIMESTAMP, 'Device 4 remark', 2, 4, 31.241243, 121.473995,
'icon4.png'),
('Device5', TRUE, 2, 'HW1.4', 'FW1.4', 'FAC12349', 'CLI12349', 1, '{
"param5": "value5"
}', '{
"prop5": "value5"
}', 'admin', CURRENT_TIMESTAMP, 'admin', CURRENT_TIMESTAMP, 'Device 5 remark', 1, 5, 31.241244, 121.473996,
'icon5.png'),
('Device6', FALSE, 0, 'HW1.5', 'FW1.5', 'FAC12350', 'CLI12350', 2, '{
"param6": "value6"
}', '{
"prop6": "value6"
}', 'admin', CURRENT_TIMESTAMP, 'admin', CURRENT_TIMESTAMP, 'Device 6 remark', 2, 6, 31.241245, 121.473997,
'icon6.png'),
('Device7', TRUE, 2, 'HW1.6', 'FW1.6', 'FAC12351', 'CLI12351', 1, '{
"param7": "value7"
}', '{
"prop7": "value7"
}', 'admin', CURRENT_TIMESTAMP, 'admin', CURRENT_TIMESTAMP, 'Device 7 remark', 1, 7, 31.241246, 121.473998,
'icon7.png'),
('Device8', FALSE, 1, 'HW1.7', 'FW1.7', 'FAC12352', 'CLI12352', 2, '{
"param8": "value8"
}', '{
"prop8": "value8"
}', 'admin', CURRENT_TIMESTAMP, 'admin', CURRENT_TIMESTAMP, 'Device 8 remark', 2, 8, 31.241247, 121.473999,
'icon8.png'),
('Device9', TRUE, 2, 'HW1.8', 'FW1.8', 'FAC12353', 'CLI12353', 1, '{
"param9": "value9"
}', '{
"prop9": "value9"
}', 'admin', CURRENT_TIMESTAMP, 'admin', CURRENT_TIMESTAMP, 'Device 9 remark', 1, 9, 31.241248, 121.474000,
'icon9.png'),
('Device10', FALSE, 0, 'HW1.9', 'FW1.9', 'FAC12354', 'CLI12354', 2, '{
"param10": "value10"
}', '{
"prop10": "value10"
}', 'admin', CURRENT_TIMESTAMP, 'admin', CURRENT_TIMESTAMP, 'Device 10 remark', 2, 10, 31.241249, 121.474001,
'icon10.png');

View File

@ -18,7 +18,11 @@ create table iot_device
update_by varchar,
update_time timestamp,
remark varchar,
dept_id bigint
dept_id bigint,
create_id bigint,
longitude double precision,
latitude double precision,
icon varchar
);
comment on column iot_device.id is '主键';
@ -57,10 +61,14 @@ comment on column iot_device.remark is '备注';
comment on column iot_device.dept_id is '部门权限id';
comment on column iot_device.create_id is '创建者id';
comment on column iot_device.longitude is '设备经度';
comment on column iot_device.latitude is '设备纬度';
comment on column iot_device.icon is '设备图标';
alter table iot_device
owner to gitea;
r
table iot_device
owner to gitea;

View File

@ -22,6 +22,9 @@
<result column="create_time" jdbcType="DATE" property="deviceCreateTime"/>
<result column="update_time" jdbcType="DATE" property="deviceUpdateTime"/>
<result column="remark" jdbcType="VARCHAR" property="deviceRemark"/>
<result column="longitude" jdbcType="DOUBLE" property="longitude"/>
<result column="latitude" jdbcType="DOUBLE" property="latitude"/>
<result column="icon" jdbcType="VARCHAR" property="icon"/>
<result column="name" property="productName"/>
<result column="product_type" jdbcType="VARCHAR" property="productType"/>
<result column="model" property="model"/>