add data forwarding function include

1. data select
2. data forwadrding by email
This commit is contained in:
wty 2022-11-14 11:17:46 +08:00
parent 19277c2dd1
commit f3ebfe025f
15 changed files with 315 additions and 179 deletions

View File

@ -94,6 +94,12 @@
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<!-- 引入 redis 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>1.5.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
@ -102,6 +108,13 @@
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
</dependencies>

View File

@ -1,4 +1,100 @@
package com.aiit.xiuos.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
@Component
public class EmailUtil {
@Autowired
private JavaMailSender mailSender;
private String from ="419034340@qq.com";
/**
* 发送纯文本邮件信息
*
* @param to 接收方
* @param subject 邮件主题
* @param content 邮件内容发送内容
*/
public void sendMessage(String to, String subject, String content) {
// 创建一个邮件对象
SimpleMailMessage msg = new SimpleMailMessage();
msg.setFrom(from); // 设置发送发
msg.setTo(to); // 设置接收方
msg.setSubject(subject); // 设置邮件主题
msg.setText(content); // 设置邮件内容
// 发送邮件
mailSender.send(msg);
}
/**
* 发送带附件的邮件信息
*
* @param to 接收方
* @param subject 邮件主题
* @param content 邮件内容发送内容
* @param files 文件数组 // 可发送多个附件
*/
public void sendMessageCarryFiles(String to, String subject, String content, File[] files) {
MimeMessage mimeMessage = mailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
helper.setFrom(from); // 设置发送发
helper.setTo(to); // 设置接收方
helper.setSubject(subject); // 设置邮件主题
helper.setText(content); // 设置邮件内容
if (files != null && files.length > 0) { // 添加附件多个
for (File file : files) {
helper.addAttachment(file.getName(), file);
}
}
} catch (MessagingException e) {
e.printStackTrace();
}
// 发送邮件
mailSender.send(mimeMessage);
}
/**
* 发送带附件的邮件信息
*
* @param to 接收方
* @param subject 邮件主题
* @param content 邮件内容发送内容
* @param file 单个文件
*/
public void sendMessageCarryFile(String to, String subject, String content, File file) {
MimeMessage mimeMessage = mailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
helper.setFrom(from); // 设置发送发
helper.setTo(to); // 设置接收方
helper.setSubject(subject); // 设置邮件主题
helper.setText(content); // 设置邮件内容
helper.addAttachment(file.getName(), file); // 单个附件
} catch (MessagingException e) {
e.printStackTrace();
}
// 发送邮件
mailSender.send(mimeMessage);
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
}

View File

@ -1,150 +0,0 @@
package com.aiit.xiuos.Utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.taosdata.jdbc.TSDBDriver;
import lombok.extern.slf4j.Slf4j;
import java.sql.*;
import java.util.ArrayList;
import java.util.Properties;
@Slf4j
public class TDengineJDBCUtil {
public static Connection getConn() throws Exception{
Class.forName("com.taosdata.jdbc.TSDBDriver");
String jdbcUrl = "jdbc:TAOS://xiuosiot.taosnode1:6030/xiuosiot?user=root&password=taosdata";
Properties connProps = new Properties();
connProps.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
connProps.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8");
connProps.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");
connProps.setProperty("debugFlag", "135");
connProps.setProperty("maxSQLLength", "1048576");
Connection conn = DriverManager.getConnection(jdbcUrl, connProps);
return conn;
}
public static Connection getRestConn() throws Exception{
Class.forName("com.taosdata.jdbc.rs.RestfulDriver");
String jdbcUrl = "jdbc:TAOS-RS://10.0.30.23:6041/test?user=root&password=taosdata";
Properties connProps = new Properties();
connProps.setProperty(TSDBDriver.PROPERTY_KEY_BATCH_LOAD, "true");
Connection conn = DriverManager.getConnection(jdbcUrl, connProps);
return conn;
}
public static boolean createTable(String deviceno, String type, String org, String productname){
Connection connection = null;
try {
connection = TDengineJDBCUtil.getConn();
Statement stmt = connection.createStatement();
String devicetype=TDengineJDBCUtil.changeType(type);
if(devicetype==null){
return false;
}
// create table
String sql ="create table if not exists " + deviceno + " using "+devicetype+" tags("+"\""+org+"\","+"\"" + productname+"\")";
stmt.executeUpdate(sql);
return true;
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if(connection!=null){
connection.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
return false;
}
public static String changeType(String type){
if(type.equals("M168-LoRa-FM100")) return "M168type";
if(type.equals("RV400-NPU16T-5G-AR100")) return "RV400ARtype";
if(type.equals("RV400-NPU4T-5G-SR100")) return "RV400SRtype";
if(type.equals("M528-A800-5G-HM100")) return "M528type";
if(type.equals("RV400-4G-FR100")) return "RV400FRtype";
return null;
}
public static ArrayList<String> executeSql(String sql) throws Exception {
Connection connection = null;
ArrayList<String> arrayList =new ArrayList<>();
try {
connection = TDengineJDBCUtil.getConn();
Statement stmt = connection.createStatement();
ResultSet resultSet =stmt.executeQuery(sql);
log.info("tdengine executeQuery:"+sql);
ResultSetMetaData metaData = resultSet.getMetaData();
while (resultSet.next()) {
StringBuilder sb=new StringBuilder();
for (int i = 1; i <= metaData.getColumnCount(); i++) {
String columnLabel = metaData.getColumnLabel(i);
String value = resultSet.getString(i);
sb.append(columnLabel+":"+value+" ");
}
arrayList.add(sb.toString());
System.out.println(sb.toString());
}
return arrayList;
} catch (SQLException e) {
System.out.println("ERROR Message: " + e.getMessage());
System.out.println("ERROR Code: " + e.getErrorCode());
e.printStackTrace();
}finally {
try {
if(connection!=null){
connection.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
return null;
}
public static int getCount(String sql) throws Exception {
Connection connection = null;
int count =-1;
try {
connection = TDengineJDBCUtil.getConn();
Statement stmt = connection.createStatement();
ResultSet resultSet =stmt.executeQuery(sql);
log.info("tdengine executeQuery:"+sql);
ResultSetMetaData metaData = resultSet.getMetaData();
if (resultSet.next()) {
count = resultSet.getInt(1);
}
return count;
} catch (SQLException e) {
System.out.println("ERROR Message: " + e.getMessage());
System.out.println("ERROR Code: " + e.getErrorCode());
e.printStackTrace();
}finally {
try {
if(connection!=null){
connection.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
return count;
}
}

View File

@ -45,6 +45,16 @@ public class AlarmInfoController {
return new ResultRespons(Constant.ERROR_CODE,"更新告警信息失败!");
}
@PostMapping("/add")
public ResultRespons addAlarmInfo(@RequestBody AlarmInfo alarmInfo){
int res =alarmInfoService.addAlarmInfo(alarmInfo);
if(res==1){
return new ResultRespons(Constant.SUCCESS_CODE,"新增告警信息成功!");
}
return new ResultRespons(Constant.ERROR_CODE,"新增告警信息失败!");
}
@GetMapping("/getAlarmLevelCount")
public ResultRespons getAlarmLevelCount(HttpServletRequest request){
UserInfo userInfo =(UserInfo) request.getSession().getAttribute("user");

View File

@ -63,12 +63,5 @@ public class AlarmRuleController {
return new ResultRespons(Constant.ERROR_CODE,"删除告警规则失败");
}
@GetMapping("/executeAlarmTask")
public void executeTask(){
try {
taskScheduled.ExecuteRule();
} catch (Exception e) {
e.printStackTrace();
}
}
}

View File

@ -1,4 +1,99 @@
package com.aiit.xiuos.controller;
import com.aiit.xiuos.Utils.*;
import com.aiit.xiuos.model.DataForwarding;
import com.aiit.xiuos.model.UserInfo;
import com.aiit.xiuos.service.DataForwardService;
import com.aiit.xiuos.tdengine.TDengineJDBCUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/dataForward")
@Slf4j
public class DataForwardController {
@Autowired
DataForwardService dataForwardService;
@Autowired
EmailUtil emailUtil;
@PostMapping("/addRecord")
public ResultRespons addRecord(@RequestBody Map<String,Object> jsonMap) {
boolean flag =false;
List<String> dataList =(List<String>) jsonMap.get("datalist");
DataForwarding dataForwarding =new DataForwarding();
dataForwarding.setAddress((String)jsonMap.get("address"));
dataForwarding.setContent((String)jsonMap.get("content"));
dataForwarding.setOrg((String)jsonMap.get("org"));
dataForwarding.setSql((String)jsonMap.get("sql"));
dataForwarding.setTopic((String)jsonMap.get("topic"));
dataForwarding.setType((String)jsonMap.get("type"));
dataForwarding.setTime(MyUtils.getDateTime());
try {
BufferedWriter bufferedWriter = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream("/home/aiitadmin/email/data.txt"), "UTF-8"));
for (String s : dataList) {
bufferedWriter.write(s);
bufferedWriter.newLine();
bufferedWriter.flush();
}
emailUtil.sendMessageCarryFile(dataForwarding.getAddress(),dataForwarding.getTopic(),dataForwarding.getContent(),new File("/home/aiitadmin/email/data.txt"));
flag =true;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
log.info("邮件发送失败");
}
if(flag){
int res = dataForwardService.addRecord(dataForwarding);
if(res==1){
return new ResultRespons(Constant.SUCCESS_CODE,"邮件发送成功,记录已保存");
}else {
return new ResultRespons(Constant.ERROR_CODE, "邮件发送成功,记录保存失败");
}
}else {
return new ResultRespons(Constant.ERROR_CODE,"邮件发送失败");
}
}
@GetMapping("/executeSql")
public ResultRespons executeSql(@RequestParam String sql){
ArrayList resultData = null;
try {
resultData = TDengineJDBCUtil.executeSql(sql);
} catch (Exception e) {
e.printStackTrace();
}
if(resultData!=null){
return new ResultRespons(Constant.SUCCESS_CODE,"数据查询成功",resultData);
}
return new ResultRespons(Constant.ERROR_CODE,"数据查询失败,请检查查询语句");
}
@GetMapping("/getRecord")
public ResultRespons getRecord(HttpServletRequest request){
UserInfo userInfo =(UserInfo) request.getSession().getAttribute("user");
List<DataForwarding> lists = dataForwardService.selectRecord(userInfo.getOrg());
if(lists != null && lists.size()>=0){
return new ResultRespons(Constant.SUCCESS_CODE,"数据查询成功",lists);
}
return new ResultRespons(Constant.ERROR_CODE,"数据查询失败,请检查查询语句");
}
}

View File

@ -3,23 +3,25 @@ package com.aiit.xiuos.controller;
import com.aiit.xiuos.Utils.Constant;
import com.aiit.xiuos.Utils.HttpClientUtil;
import com.aiit.xiuos.Utils.ResultRespons;
import com.aiit.xiuos.dao.mappers.AvgDayDataMapper;
import com.aiit.xiuos.model.AvgDayData;
import com.aiit.xiuos.mqtt.MqttConfiguration;
import com.aiit.xiuos.mqtt.MyMqttClient;
import com.aiit.xiuos.service.AvgDayDataService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/data")
public class DeviceDataController {
@Autowired
AvgDayDataService avgDayDataService;
@Autowired
private MyMqttClient myMqttClient;
@GetMapping("/getAll")
public ResultRespons getAllDataFromDSD(HttpServletRequest request){
@ -38,4 +40,14 @@ public class DeviceDataController {
return new ResultRespons(Constant.ERROR_CODE,"查询数据失败");
}
@PostMapping("/publishData")
public ResultRespons publishData(@RequestBody Map<String, Object> jsonMap){
if(myMqttClient==null){
myMqttClient=new MqttConfiguration().getMqttPushClient();
}
myMqttClient.publish("xiuosiot/"+jsonMap.get("deviceno"), JSONObject.toJSONString(jsonMap));
return new ResultRespons(Constant.ERROR_CODE,"数据发送成功");
}
}

View File

@ -1,7 +1,13 @@
package com.aiit.xiuos.dao.mappers;
import com.aiit.xiuos.model.DataForwarding;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface DataForwardingMapper {
int deleteByPrimaryKey(Integer id);
@ -14,4 +20,7 @@ public interface DataForwardingMapper {
int updateByPrimaryKeySelective(DataForwarding record);
int updateByPrimaryKey(DataForwarding record);
@Select("select * from data_forwarding where org = #{org}")
List<DataForwarding> selectAll(@Param("org") String org);
}

View File

@ -1,6 +1,8 @@
package com.aiit.xiuos.model;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Builder;
import lombok.Data;
@ -14,7 +16,7 @@ public class DataForwarding {
private String content;
private String type;
@JsonFormat(pattern ="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private Date time;
private String address;

View File

@ -2,17 +2,13 @@ package com.aiit.xiuos.scheduled;
import com.aiit.xiuos.Utils.EmailUtil;
import com.aiit.xiuos.Utils.MyUtils;
import com.aiit.xiuos.Utils.TDengineJDBCUtil;
import com.aiit.xiuos.tdengine.TDengineJDBCUtil;
import com.aiit.xiuos.model.*;
import com.aiit.xiuos.service.*;
import com.aiit.xiuos.service.impl.AvgDayDataServiceImpl;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@ -134,16 +130,10 @@ public class TaskScheduled {
//保存告警信息告警级别高的插入,低的因主键冲突可自动排除
try{
alarmInfoService.addAlarmInfo(alarmInfo);
}catch (Exception e){
e.printStackTrace();
}
//发送邮件
try{
emailUtil.sendMessage(alarmRule.getNoticeAddress(),"设备告警",alarmRule.getNoticeContent());
log.info("邮件发送成功");
}catch (Exception e) {
log.error("邮件发送失败");
e.printStackTrace();
}catch (Exception e){
log.info(e.getMessage());
}
}

View File

@ -1,4 +1,11 @@
package com.aiit.xiuos.service;
public interface DataForward {
import com.aiit.xiuos.model.DataForwarding;
import java.util.List;
public interface DataForwardService {
int addRecord(DataForwarding dataForwarding);
List<DataForwarding> selectRecord(String org);
}

View File

@ -1,4 +1,23 @@
package com.aiit.xiuos.service.impl;
public class DataForwardServiceImpl {
import com.aiit.xiuos.dao.mappers.DataForwardingMapper;
import com.aiit.xiuos.model.DataForwarding;
import com.aiit.xiuos.service.DataForwardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class DataForwardServiceImpl implements DataForwardService {
@Autowired
DataForwardingMapper dataForwardingMapper;
@Override
public int addRecord(DataForwarding dataForwarding) {
return dataForwardingMapper.insertSelective(dataForwarding);
}
@Override
public List<DataForwarding> selectRecord(String org) {
return dataForwardingMapper.selectAll(org);
}
}

View File

@ -76,6 +76,9 @@ mqtt:
#默认主题
default-topic: xiuosiot/#
tdengine:
url: jdbc:TAOS://taosnode1:6030/xiuosiot?user=root&password=taosdata
logging:
file:
name: xiuosiot.log

View File

@ -69,7 +69,8 @@ mqtt:
keepalive: 100
#默认主题
default-topic: xiuosiot/#
tdengine:
url: jdbc:TAOS://xiuosiot.taosnode1:6030/xiuosiot?user=root&password=taosdata
logging:
file:
name: xiuosiot.log

View File

@ -0,0 +1,36 @@
package com.aiit.xiuos;
import com.aiit.xiuos.mqtt.MyMqttClient;
import com.alibaba.fastjson.JSONObject;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.Random;
@SpringBootTest(classes = XiuosApplication.class,webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class MqttTest {
@Autowired
private MyMqttClient myMqttClient;
@Test
void pushlish() {
Random random =new Random();
for (int i = 0; i < 1; i++) {
JSONObject jsonObject =new JSONObject();
jsonObject.put("co2",19);
jsonObject.put("so2",19);
jsonObject.put("temperature",30);
jsonObject.put("humidity",28);
jsonObject.put("deviceno","a000001");
myMqttClient.publish("xiuosiot/A000001", jsonObject.toJSONString());
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}