打开首页获取用户id和设备id、滑动开关浇花、浇水记录展示、调整sysuser为appuser、首页设备信息

This commit is contained in:
邱贞招 2023-12-13 09:35:29 +08:00
parent 77b6cc8175
commit 9e4f2146e9
15 changed files with 351 additions and 37 deletions

View File

@ -0,0 +1,133 @@
package com.ruoyi.web.controller.system;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.AsUser;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.device.service.IAsUserService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
/**
* 个人信息 业务处理
*
* @author ruoyi
*/
@RestController
@RequestMapping("/app")
public class AsProfileController extends BaseController
{
@Resource
private IAsUserService asUserService;
@Resource
private TokenService tokenService;
/**
* 个人信息
*/
@GetMapping("/profile")
public AjaxResult profile()
{
LoginUser loginUser = getLoginUser();
AsUser user = loginUser.getAsUser();
AjaxResult ajax = AjaxResult.success(user);
return ajax;
}
/**
* 修改用户
*/
@Log(title = "个人信息", businessType = BusinessType.UPDATE)
@PutMapping("/profile")
public AjaxResult updateProfile(@RequestBody AsUser user)
{
LoginUser loginUser = getLoginUser();
AsUser currentUser = loginUser.getAsUser();
currentUser.setNickName(user.getNickName());
currentUser.setEmail(user.getEmail());
currentUser.setPhonenumber(user.getPhonenumber());
currentUser.setSex(user.getSex());
if (StringUtils.isNotEmpty(user.getPhonenumber()) && !asUserService.checkPhoneUnique(currentUser))
{
return error("修改用户'" + user.getUserName() + "'失败,手机号码已存在");
}
if (StringUtils.isNotEmpty(user.getEmail()) && !asUserService.checkEmailUnique(currentUser))
{
return error("修改用户'" + user.getUserName() + "'失败,邮箱账号已存在");
}
if (asUserService.updateUserProfile(currentUser) > 0)
{
// 更新缓存用户信息
tokenService.setLoginUser(loginUser);
return success();
}
return error("修改个人信息异常,请联系管理员");
}
/**
* 重置密码
*/
@Log(title = "个人信息", businessType = BusinessType.UPDATE)
@PutMapping("/updatePwd")
public AjaxResult updatePwd(String oldPassword, String newPassword)
{
LoginUser loginUser = getLoginUser();
String userName = loginUser.getUsername();
String password = loginUser.getPassword();
if (!SecurityUtils.matchesPassword(oldPassword, password))
{
return error("修改密码失败,旧密码错误");
}
if (SecurityUtils.matchesPassword(newPassword, password))
{
return error("新密码不能与旧密码相同");
}
if (asUserService.resetUserPwd(userName, SecurityUtils.encryptPassword(newPassword)) > 0)
{
// 更新缓存用户密码
loginUser.getUser().setPassword(SecurityUtils.encryptPassword(newPassword));
tokenService.setLoginUser(loginUser);
return success();
}
return error("修改密码异常,请联系管理员");
}
/**
* 头像上传
*/
@Log(title = "用户头像", businessType = BusinessType.UPDATE)
@PostMapping("/avatar")
public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file) throws Exception
{
if (!file.isEmpty())
{
LoginUser loginUser = getLoginUser();
String avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file, MimeTypeUtils.IMAGE_EXTENSION);
if (asUserService.updateUserAvatar(loginUser.getUsername(), avatar))
{
AjaxResult ajax = AjaxResult.success();
ajax.put("imgUrl", avatar);
// 更新缓存用户头像
loginUser.getUser().setAvatar(avatar);
tokenService.setLoginUser(loginUser);
return ajax;
}
}
return error("上传图片异常,请联系管理员");
}
}

View File

@ -1,4 +1,4 @@
package com.ruoyi.device.controller; package com.ruoyi.web.controller.system;
import com.ruoyi.common.annotation.Log; import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController; import com.ruoyi.common.core.controller.BaseController;

View File

@ -90,6 +90,7 @@ public class SysLoginController
public AjaxResult getAppInfo() public AjaxResult getAppInfo()
{ {
AsUser user = SecurityUtils.getLoginUser().getAsUser(); AsUser user = SecurityUtils.getLoginUser().getAsUser();
user.setDeviceId(asUserService.selectDeviceInfoByUser(user.getUserId()).getDeviceId());
AjaxResult ajax = AjaxResult.success(); AjaxResult ajax = AjaxResult.success();
ajax.put("user", user); ajax.put("user", user);
return ajax; return ajax;

View File

@ -78,6 +78,10 @@ public class AsUser extends BaseEntity
@Excel(name = "绑定设备数量") @Excel(name = "绑定设备数量")
private Integer bindDeviceNum; private Integer bindDeviceNum;
/** 展示当前设备id */
private Long deviceId;
public AsUser() public AsUser()
{ {
@ -250,4 +254,12 @@ public class AsUser extends BaseEntity
public void setBindDeviceNum(Integer bindDeviceNum) { public void setBindDeviceNum(Integer bindDeviceNum) {
this.bindDeviceNum = bindDeviceNum; this.bindDeviceNum = bindDeviceNum;
} }
public Long getDeviceId() {
return deviceId;
}
public void setDeviceId(Long deviceId) {
this.deviceId = deviceId;
}
} }

View File

@ -1,10 +1,6 @@
package com.ruoyi.common.utils.http; package com.ruoyi.common.utils.http;
import java.io.BufferedReader; import java.io.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ConnectException; import java.net.ConnectException;
import java.net.SocketTimeoutException; import java.net.SocketTimeoutException;
import java.net.URL; import java.net.URL;
@ -203,6 +199,7 @@ public class HttpUtils
try try
{ {
log.info("sendPost - {}", url); log.info("sendPost - {}", url);
log.info("发送命令 - {}", param);
URL realUrl = new URL(url); URL realUrl = new URL(url);
URLConnection conn = realUrl.openConnection(); URLConnection conn = realUrl.openConnection();
conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("accept", "*/*");
@ -260,6 +257,68 @@ public class HttpUtils
} }
return result.toString(); return result.toString();
} }
/**
* 向指定 URL 发送GET方法的请求
*
* @param url 发送请求的 URL
* @param param 请求参数请求参数应该是 name1=value1&name2=value2 的形式
* @return 所代表远程资源的响应结果
*/
public static String sendGetWithToken(String url, String param, String token)
{
StringBuilder result = new StringBuilder();
BufferedReader in = null;
try
{
String urlNameString = StringUtils.isNotBlank(param) ? url + "?" + param : url;
log.info("sendGet - {}", urlNameString);
URL realUrl = new URL(urlNameString);
URLConnection connection = realUrl.openConnection();
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
connection.setRequestProperty("Authorization", token);
connection.connect();
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), Constants.UTF8));
String line;
while ((line = in.readLine()) != null)
{
result.append(line);
}
log.info("recv - {}", result);
}
catch (ConnectException e)
{
log.error("调用HttpUtils.sendGet ConnectException, url=" + url + ",param=" + param, e);
}
catch (SocketTimeoutException e)
{
log.error("调用HttpUtils.sendGet SocketTimeoutException, url=" + url + ",param=" + param, e);
}
catch (IOException e)
{
log.error("调用HttpUtils.sendGet IOException, url=" + url + ",param=" + param, e);
}
catch (Exception e)
{
log.error("调用HttpsUtil.sendGet Exception, url=" + url + ",param=" + param, e);
}
finally
{
try
{
if (in != null)
{
in.close();
}
}
catch (Exception ex)
{
log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
}
}
return result.toString();
}
public static String sendSSLPost(String url, String param) public static String sendSSLPost(String url, String param)
{ {

View File

@ -2,6 +2,8 @@ package com.ruoyi.framework.web.service;
import javax.annotation.Resource; import javax.annotation.Resource;
import com.ruoyi.common.core.domain.entity.AsUser;
import com.ruoyi.device.service.IAsUserService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.BadCredentialsException;
@ -50,6 +52,9 @@ public class SysLoginService
@Autowired @Autowired
private ISysUserService userService; private ISysUserService userService;
@Autowired
private IAsUserService asUserService;
@Autowired @Autowired
private ISysConfigService configService; private ISysConfigService configService;
@ -182,6 +187,20 @@ public class SysLoginService
userService.updateUserProfile(sysUser); userService.updateUserProfile(sysUser);
} }
/**
* 记录app登录信息
*
* @param userId 用户ID
*/
public void recordAppLoginInfo(Long userId)
{
AsUser asUser = new AsUser();
asUser.setUserId(userId);
asUser.setLoginIp(IpUtils.getIpAddr());
asUser.setLoginDate(DateUtils.getNowDate());
asUserService.updateUserProfile(asUser);
}
/** /**
* APP验证码登录方法 * APP验证码登录方法
* *
@ -212,7 +231,7 @@ public class SysLoginService
AuthenticationContextHolder.clearContext(); AuthenticationContextHolder.clearContext();
} }
LoginUser loginUser = (LoginUser) authentication.getPrincipal(); LoginUser loginUser = (LoginUser) authentication.getPrincipal();
recordLoginInfo(loginUser.getUserId()); //修改sys_user最近登录IP和登录时间 recordAppLoginInfo(loginUser.getUserId()); //修改sys_user最近登录IP和登录时间
// 生成token // 生成token
return tokenService.createToken(loginUser); return tokenService.createToken(loginUser);
} }

View File

@ -81,7 +81,7 @@ public class DatapointValue {
this.js_sec = js_sec; this.js_sec = js_sec;
} }
public boolean isKaiguan() { public boolean getKaiguan() {
return kaiguan; return kaiguan;
} }
@ -138,7 +138,7 @@ public class DatapointValue {
this.js_sec = js_sec; this.js_sec = js_sec;
} }
public boolean isKaiguan() { public boolean getKaiguan() {
return kaiguan; return kaiguan;
} }
@ -154,7 +154,7 @@ public class DatapointValue {
// getters and setters // getters and setters
public boolean isKaiguan() { public boolean getKaiguan() {
return kaiguan; return kaiguan;
} }
@ -191,7 +191,7 @@ public class DatapointValue {
this.end_sd = end_sd; this.end_sd = end_sd;
} }
public boolean isKaiguan() { public boolean getKaiguan() {
return kaiguan; return kaiguan;
} }

View File

@ -6,7 +6,7 @@ import java.util.List;
@Data @Data
public class Datastream { public class Datastream {
private List<Datapoint> datapoints; private List<Object> datapoints;
private String id; private String id;
} }

View File

@ -0,0 +1,29 @@
package com.ruoyi.quartz.domain;
import lombok.Data;
@Data
public class WateringLog {
/**浇水时间*/
private String water_time;
/**启动模式:0-手动模式1-定时模式2-土壤湿度低启动*/
private String start_mode;
/** 喷洒时间--电机转动时间*/
private String spraying_time;
/** 脉冲模式*/
private DatapointValue.Mc mc;
/** 水流强度*/
private int jiaoshui_qiangdu;
/** 开始浇水湿度*/
private int start_moisture;
/** 结束浇水湿度*/
private int end_moisture;
}

View File

@ -1,15 +1,18 @@
package com.ruoyi.quartz.task; package com.ruoyi.quartz.task;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject; import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.IotConstants; import com.ruoyi.common.constant.IotConstants;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.http.HttpUtils; import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.onenet.Token; import com.ruoyi.common.utils.onenet.Token;
import com.ruoyi.device.domain.AsDevice;
import com.ruoyi.device.domain.AsWateringRecord; import com.ruoyi.device.domain.AsWateringRecord;
import com.ruoyi.device.mapper.AsDeviceMapper;
import com.ruoyi.device.mapper.AsWateringRecordMapper; import com.ruoyi.device.mapper.AsWateringRecordMapper;
import com.ruoyi.quartz.domain.Data; import com.ruoyi.quartz.domain.Data;
import com.ruoyi.quartz.domain.DataPointRes; import com.ruoyi.quartz.domain.DataPointRes;
import com.ruoyi.quartz.domain.Datastream; import com.ruoyi.quartz.domain.Datastream;
import com.ruoyi.quartz.domain.WateringLog;
import lombok.SneakyThrows; import lombok.SneakyThrows;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -38,35 +41,86 @@ public class IotLogTask {
@Resource @Resource
private AsWateringRecordMapper asWateringRecordMapper; private AsWateringRecordMapper asWateringRecordMapper;
@Resource
private AsDeviceMapper asDeviceMapper;
@SneakyThrows @SneakyThrows
public void getDeviceLog() { public void getDeviceLog() {
logger.info("定时任务--获取浇花器日志"); logger.info("定时任务--获取浇花器日志");
/**1.请求url获取到浇花器日志*/ /**1.获取到所有的设备列表*/
// String deviceName = asDevice.getMac();//mac地址就是产品名称 List<AsDevice> asDevices = asDeviceMapper.selectAsDeviceList(null);
String param = "device_name=" + "4827E2945C54" + "&product_id=" + productId; for (AsDevice device : asDevices) {
String sendUrl = iotUrl+ IotConstants.ADDS_HISTORY_DATAPOINTS + "?"+param; /**1.请求url获取到浇花器日志*/
String param = "device_name=" + device.getMac() + "&product_id=" + productId;
String sendUrl = iotUrl+ IotConstants.ADDS_HISTORY_DATAPOINTS + "?"+param;
String token = Token.getToken(); String token = Token.getToken();
logger.info("IOT获取到Authorization:【{}】",token); logger.info("IOT获取到Authorization:【{}】",token);
String result = HttpUtils.sendPostWithToken(sendUrl, "command", token); String result = HttpUtils.sendGetWithToken(sendUrl, null, token);
/**2.处理返回的参数*/ logger.info("IOT返回的结果【{}】",result);
// JSONObject paramsObj = JSON.parseObject(result); /**2.处理返回的参数*/
DataPointRes dataPointRes = JSONObject.parseObject(result, DataPointRes.class); DataPointRes dataPointRes = JSONObject.parseObject(result, DataPointRes.class);
Data data = dataPointRes.getData(); Data data = dataPointRes.getData();
List<Datastream> datastreams = data.getDatastreams(); List<Datastream> datastreams = data.getDatastreams();
// String code = paramsObj.getString("code");
// String msg = paramsObj.getString("msg");
/**3.将DatapointValue对象转成*/ for (Datastream datastream: datastreams) {
asWateringRecordMapper.insertAsWateringRecord(AsWateringRecord.builder() if(datastream.getId().equals("jj")){
.userName("") List<Object> datapoints = datastream.getDatapoints();
.deviceId(1L) for (Object obj:datapoints) {
// .waterTime() // String s = JSON.toJSONString(obj);
// Datapoint datapoint = JSONObject.parseObject(s, Datapoint.class);
// DatapointValue value = datapoint.getValue();
// DatapointValue.Ds ds = value.getDs();//定时
// boolean kaiguan3 = ds.getKaiguan();//定时开关
// int js_sec1 = ds.getJs_sec();//喷洒时间
// int start_hour = ds.getStart_hour();//启动小时
// int start_min = ds.getStart_min();//启动分钟
//
// DatapointValue.Mc mc = value.getMc();//脉冲模式
// int jg_sec = mc.getJg_sec();//间隔时间
// int js_sec = mc.getJs_sec();//启动时间
// boolean kaiguan2 = mc.getKaiguan();//开关
//
//
// DatapointValue.Set set = value.getSet();//设置
// boolean kaiguan1 = set.getKaiguan();//开关
// int xp_min = set.getXp_min();//息屏分钟
//
// DatapointValue.Tr tr = value.getTr();//土壤
// int end_sd = tr.getEnd_sd();//结束湿度
// boolean kaiguan = tr.getKaiguan();//开关
// int start_sd = tr.getStart_sd();//启动湿度
//
// int turan_show = value.getTuran_show();//土壤当前湿度
// int jiaoshui_qiangdu = value.getJiaoshui_qiangdu();//浇水强度
.build()); String s ="{\"water_time\":\"2023-12-06\",\"start_mode\":\"1\",\"spraying_time\":60,\"mc\":{\"jg_sec\":10,\"js_sec\":5,\"kaiguan\":false},\"jiaoshui_qiangdu\":3,\"start_moisture\":10,\"end_moisture\":10}\n";
WateringLog wateringLog = JSONObject.parseObject(s, WateringLog.class);
/**3.将DatapointValue对象转成*/
AsWateringRecord build = AsWateringRecord.builder()
.deviceId(device.getDeviceId())
.waterTime(DateUtils.dateTime(DateUtils.YYYY_MM_DD, wateringLog.getWater_time()))
.startMode(wateringLog.getStart_mode())
.sprayingTime(Integer.parseInt(wateringLog.getSpraying_time()))
.pulseMode(wateringLog.getMc().getKaiguan() + "")
.pulseModeParam(wateringLog.getMc().toString())
.waterIntensity(wateringLog.getJiaoshui_qiangdu())
.startMoisture(wateringLog.getStart_moisture())
.endMoisture(wateringLog.getEnd_moisture())
.userName(device.getUserName())
.build();
build.setCreateTime(DateUtils.getNowDate());
int i = asWateringRecordMapper.insertAsWateringRecord(build);
/**3.根据最新时间保存数据*/
}
}
}
}
/**3.根据最新时间保存数据*/
} }
} }

View File

@ -7,6 +7,7 @@ import lombok.Builder;
import lombok.Data; import lombok.Data;
import com.ruoyi.common.annotation.Excel; import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.core.domain.BaseEntity; import com.ruoyi.common.core.domain.BaseEntity;
import lombok.experimental.SuperBuilder;
/** /**
* 浇水记录对象 as_watering_record * 浇水记录对象 as_watering_record

View File

@ -267,9 +267,10 @@ public class AsDeviceServiceImpl extends ServiceImpl<AsDeviceMapper, AsDevice> i
.deviceId(device.getDeviceId()) .deviceId(device.getDeviceId())
.waterTime(DateUtils.getNowDate()) .waterTime(DateUtils.getNowDate())
.startMode(IotConstants.START_MODE_MANUAL) .startMode(IotConstants.START_MODE_MANUAL)
.pulseMode(device.getPulseModeParam()) .pulseMode(device.getPulseMode())
.pulseModeParam(device.getPulseModeParam())
// .sprayingTime(device.getPulseModeParam()) //喷洒时间 // .sprayingTime(device.getPulseModeParam()) //喷洒时间
.userName(getUsername()) // .userName(getUsername())
.build(); .build();
int insert = wateringRecordMapper.insertAsWateringRecord(record); int insert = wateringRecordMapper.insertAsWateringRecord(record);
return AjaxResult.success(insert); return AjaxResult.success(insert);

View File

@ -397,7 +397,10 @@ public class AsUserServiceImpl implements IAsUserService
AsDevice asDevice = AsDevice.builder().userId(userId).build(); AsDevice asDevice = AsDevice.builder().userId(userId).build();
List<AsDevice> asDevices = asDeviceMapper.selectAsDeviceList(asDevice); List<AsDevice> asDevices = asDeviceMapper.selectAsDeviceList(asDevice);
if(ObjectUtils.isNotEmpty(asDevices) && asDevices.size() !=0 ){ if(ObjectUtils.isNotEmpty(asDevices) && asDevices.size() !=0 ){
return asDevices.get(0); AsDevice device = asDevices.get(0);
//请求
return device;
} }
return null; return null;
} }

View File

@ -50,6 +50,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<if test="mac != null and mac != ''"> and mac like concat('%', #{mac}, '%')</if> <if test="mac != null and mac != ''"> and mac like concat('%', #{mac}, '%')</if>
<if test="onlineStatus != null and onlineStatus != ''"> and online_status = #{onlineStatus}</if> <if test="onlineStatus != null and onlineStatus != ''"> and online_status = #{onlineStatus}</if>
<if test="nickName != null and nickName != ''"> and nick_name like concat('%', #{nickName}, '%')</if> <if test="nickName != null and nickName != ''"> and nick_name like concat('%', #{nickName}, '%')</if>
<if test="userId != null "> and user_id = #{userId}</if>
</where> </where>
</select> </select>

View File

@ -59,6 +59,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<if test="createTime != null">create_time,</if> <if test="createTime != null">create_time,</if>
</trim> </trim>
<trim prefix="values (" suffix=")" suffixOverrides=","> <trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="deviceId != null">#{deviceId},</if>
<if test="waterTime != null">#{waterTime},</if> <if test="waterTime != null">#{waterTime},</if>
<if test="startMode != null">#{startMode},</if> <if test="startMode != null">#{startMode},</if>
<if test="sprayingTime != null">#{sprayingTime},</if> <if test="sprayingTime != null">#{sprayingTime},</if>