From 65591bb3f61a74aeca547730920a7986df1cdd79 Mon Sep 17 00:00:00 2001 From: 18650502300 <18650502300@163.com> Date: Fri, 23 Feb 2024 17:08:05 +0800 Subject: [PATCH] =?UTF-8?q?1.=20=E5=BF=AB=E9=80=9F=E7=99=BB=E5=BD=95=202.?= =?UTF-8?q?=20=E6=96=87=E7=AB=A0=E5=88=97=E8=A1=A8=203.=20=E8=AE=BE?= =?UTF-8?q?=E5=A4=87=E7=BB=91=E5=AE=9A=E7=94=A8=E6=88=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controller/system/SysLoginController.java | 28 +++++-- AutoSprout-common/pom.xml | 12 ++- .../com/ruoyi/common/constant/Constants.java | 7 +- .../ruoyi/common/utils/http/HttpUtils.java | 29 ++++++- .../common/utils/wx/AccessTokenUtil.java | 44 ++++++++++ .../ruoyi/common/utils/wx/vo/AccessToken.java | 83 +++++++++++++++++++ .../framework/config/SecurityConfig.java | 8 +- .../CustomLoginAuthenticationProvider.java | 2 +- .../web/service/SysLoginService.java | 74 +++++++++++++++++ .../src/assets/icons/svg/article.svg | 1 + .../com/ruoyi/device/app/AppController.java | 11 +++ .../ruoyi/device/mapper/AsDeviceMapper.java | 24 ++++-- .../device/service/IAsDeviceService.java | 24 ++++-- .../service/impl/AsDeviceServiceImpl.java | 26 +++++- .../service/impl/AsUserServiceImpl.java | 76 +++++++++++------ .../mapper/device/AsDeviceMapper.xml | 17 ++-- 16 files changed, 402 insertions(+), 64 deletions(-) create mode 100644 AutoSprout-common/src/main/java/com/ruoyi/common/utils/wx/AccessTokenUtil.java create mode 100644 AutoSprout-common/src/main/java/com/ruoyi/common/utils/wx/vo/AccessToken.java create mode 100644 AutoSprout-ui/src/assets/icons/svg/article.svg diff --git a/AutoSprout-admin/src/main/java/com/ruoyi/web/controller/system/SysLoginController.java b/AutoSprout-admin/src/main/java/com/ruoyi/web/controller/system/SysLoginController.java index bcefdf6..5abe88d 100644 --- a/AutoSprout-admin/src/main/java/com/ruoyi/web/controller/system/SysLoginController.java +++ b/AutoSprout-admin/src/main/java/com/ruoyi/web/controller/system/SysLoginController.java @@ -4,8 +4,11 @@ import java.util.List; import java.util.Set; import com.ruoyi.common.core.domain.entity.AsUser; +import com.ruoyi.common.exception.ServiceException; +import com.ruoyi.device.domain.AsDevice; import com.ruoyi.device.service.IAsUserService; import com.ruoyi.system.service.ISysUserService; +import org.apache.commons.lang3.ObjectUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; @@ -23,7 +26,7 @@ import com.ruoyi.system.service.ISysMenuService; /** * 登录验证 - * + * * @author ruoyi */ @RestController @@ -46,7 +49,7 @@ public class SysLoginController /** * 登录方法 - * + * * @param loginBody 登录信息 * @return 结果 */ @@ -63,7 +66,7 @@ public class SysLoginController /** * 获取用户信息 - * + * * @return 用户信息 */ @GetMapping("getInfo") @@ -90,7 +93,10 @@ public class SysLoginController public AjaxResult getAppInfo() { AsUser user = SecurityUtils.getLoginUser().getAsUser(); - user.setDeviceId(asUserService.selectDeviceInfoByUser(user.getUserId(),null).get(0).getDeviceId()); + List asDevices = asUserService.selectDeviceInfoByUser(user.getUserId(), null); + if(ObjectUtils.isNotEmpty(asDevices) && asDevices.size()!=0){ + user.setDeviceId(asDevices.get(0).getDeviceId()); + } AjaxResult ajax = AjaxResult.success(); ajax.put("user", user); return ajax; @@ -98,7 +104,7 @@ public class SysLoginController /** * 获取路由信息 - * + * * @return 路由信息 */ @GetMapping("getRouters") @@ -121,4 +127,16 @@ public class SysLoginController ajax.put(Constants.TOKEN, token); return ajax; } + + /** + * 微信登录 + */ + @PostMapping("/wxlogin") + public AjaxResult wxlogin(String mobileCode) { + AjaxResult ajax = AjaxResult.success(); + // 生成令牌 + String token = loginService.wxloing(mobileCode); + ajax.put(Constants.TOKEN, token); + return ajax; + } } diff --git a/AutoSprout-common/pom.xml b/AutoSprout-common/pom.xml index 0b1453c..83e9ae9 100644 --- a/AutoSprout-common/pom.xml +++ b/AutoSprout-common/pom.xml @@ -25,6 +25,12 @@ 3.1.284 + + com.github.binarywang + weixin-java-miniapp + 4.6.0 + + org.springframework @@ -60,13 +66,13 @@ org.apache.commons commons-lang3 - + com.fasterxml.jackson.core jackson-databind - + com.baomidou @@ -183,4 +189,4 @@ - \ No newline at end of file + diff --git a/AutoSprout-common/src/main/java/com/ruoyi/common/constant/Constants.java b/AutoSprout-common/src/main/java/com/ruoyi/common/constant/Constants.java index 06fccdf..1b25eaf 100644 --- a/AutoSprout-common/src/main/java/com/ruoyi/common/constant/Constants.java +++ b/AutoSprout-common/src/main/java/com/ruoyi/common/constant/Constants.java @@ -4,7 +4,7 @@ import io.jsonwebtoken.Claims; /** * 通用常量信息 - * + * * @author ruoyi */ public class Constants @@ -175,6 +175,11 @@ public class Constants */ public static final String CUSTOM_LOGIN_SMS = "sms_login"; + /** + * 微信登录 + */ + public static final String CUSTOM_LOGIN_WX = "wx_login"; + /** * 短信验证码有效期 10分钟 * */ diff --git a/AutoSprout-common/src/main/java/com/ruoyi/common/utils/http/HttpUtils.java b/AutoSprout-common/src/main/java/com/ruoyi/common/utils/http/HttpUtils.java index 59d7473..46bd86b 100644 --- a/AutoSprout-common/src/main/java/com/ruoyi/common/utils/http/HttpUtils.java +++ b/AutoSprout-common/src/main/java/com/ruoyi/common/utils/http/HttpUtils.java @@ -13,6 +13,9 @@ import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; + +import com.alibaba.fastjson2.JSON; +import com.squareup.okhttp.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ruoyi.common.constant.Constants; @@ -20,7 +23,7 @@ import com.ruoyi.common.utils.StringUtils; /** * 通用http发送方法 - * + * * @author ruoyi */ public class HttpUtils @@ -184,6 +187,26 @@ public class HttpUtils } return result.toString(); } +// +// public static String sendPostWithToken2(String url, String param, String token){ +// OkHttpClient client = new OkHttpClient(); +// +// MediaType mediaType = MediaType.parse("text/html"); +// RequestBody body = RequestBody.create(mediaType, "open"); +// Request request = new Request.Builder() +// .url("https://iot-api.heclouds.com/datapoint/synccmds?device_name=4827E2945C58&product_id=50dd83E8zQ&timeout=10") +// .post(body) +// .addHeader("Authorization", "version=2020-05-29&res=userid/143831&et=1710933295&method=sha256&sign=4NfxXMuNOa110dVTYjlJfOmlMiw7tiScwCxo5HQ/7g8=") +// .addHeader("content-type", "text/html") +// .build(); +// Response response = null; +// try { +// response = client.newCall(request).execute(); +// } catch (IOException e) { +// e.printStackTrace(); +// } +// return JSON.toJSONString(response); +// } /** * 向指定 URL 发送POST方法的请求 * @@ -206,7 +229,7 @@ public class HttpUtils conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); conn.setRequestProperty("Accept-Charset", "utf-8"); - conn.setRequestProperty("contentType", "utf-8"); + conn.setRequestProperty("content-type", "text/html"); conn.setRequestProperty("Authorization", token); conn.setDoOutput(true); conn.setDoInput(true); @@ -402,4 +425,4 @@ public class HttpUtils return true; } } -} \ No newline at end of file +} diff --git a/AutoSprout-common/src/main/java/com/ruoyi/common/utils/wx/AccessTokenUtil.java b/AutoSprout-common/src/main/java/com/ruoyi/common/utils/wx/AccessTokenUtil.java new file mode 100644 index 0000000..5954f13 --- /dev/null +++ b/AutoSprout-common/src/main/java/com/ruoyi/common/utils/wx/AccessTokenUtil.java @@ -0,0 +1,44 @@ +package com.ruoyi.common.utils.wx; + +import cn.binarywang.wx.miniapp.api.WxMaService; +import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl; +import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl; +import com.alibaba.fastjson2.JSONObject; +import com.ruoyi.common.utils.spring.SpringUtils; +import com.ruoyi.common.utils.wx.vo.AccessToken; +import lombok.SneakyThrows; + +import java.util.concurrent.TimeUnit; + +public class AccessTokenUtil { + + /** 缓存token */ + private static String cachedToken; + + /** token过期时间 */ + private static long tokenExpirationTime; + + @SneakyThrows + public static String getToken() { + if (isTokenExpired()) { + String APPID = SpringUtils.getRequiredProperty("wx.appid"); + String APPSECRET = SpringUtils.getRequiredProperty("wx.appSecret"); + WxMaService wxMaService = new WxMaServiceImpl(); + WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl(); + config.setAppid(APPID); + config.setSecret(APPSECRET); + wxMaService.setWxMaConfig(config); + String accessToken = wxMaService.getAccessToken(); + cachedToken = accessToken; + // 更新 token 过期时间 + tokenExpirationTime = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(7200L); + return cachedToken; + } + return cachedToken; + } + + /**判断token是否过期*/ + private static boolean isTokenExpired() { + return cachedToken == null || System.currentTimeMillis() > tokenExpirationTime; + } +} diff --git a/AutoSprout-common/src/main/java/com/ruoyi/common/utils/wx/vo/AccessToken.java b/AutoSprout-common/src/main/java/com/ruoyi/common/utils/wx/vo/AccessToken.java new file mode 100644 index 0000000..72a8188 --- /dev/null +++ b/AutoSprout-common/src/main/java/com/ruoyi/common/utils/wx/vo/AccessToken.java @@ -0,0 +1,83 @@ +package com.ruoyi.common.utils.wx.vo; + +public class AccessToken { + private String expires_in; //成功有效时间 + private String access_token; // 普通Token + private String refresh_token; // 普通Token + private String openid; + private String errcode; //失败ID + private String errmsg; //失败消息 + private long expiresIn; //过期时间 , 默认2小时 + + public long getExpiresIn() { + return expiresIn; + } + + public void setExpiresIn(long expiresIn) { + this.expiresIn = expiresIn; + } + + public String getExpires_in() { + return expires_in; + } + + public void setExpires_in(String expires_in) { + this.expires_in = expires_in; + } + + public String getAccess_token() { + return access_token; + } + + public void setAccess_token(String access_token) { + this.access_token = access_token; + } + + public String getErrcode() { + return errcode; + } + + public void setErrcode(String errcode) { + this.errcode = errcode; + } + + public String getErrmsg() { + return errmsg; + } + + public void setErrmsg(String errmsg) { + this.errmsg = errmsg; + } + + public String getOpenid() { + return openid; + } + + public void setOpenid(String openid) { + this.openid = openid; + } + + public String getRefresh_token() { + return refresh_token; + } + + public void setRefresh_token(String refresh_token) { + this.refresh_token = refresh_token; + } + + /** + * + * @param expires_in 从微信服务器获取到的过期时间 + * @param access_token 从微信服务器获取到的过期时间access-token + */ + public AccessToken(String expires_in, String access_token) { + this.access_token = access_token; + //当前系统时间+上过期时间 + expiresIn = System.currentTimeMillis() + Integer.parseInt(expires_in) * 1000; + } + + //判断token是否过期 + public boolean isExpired() { + return System.currentTimeMillis() > expiresIn; + } +} diff --git a/AutoSprout-framework/src/main/java/com/ruoyi/framework/config/SecurityConfig.java b/AutoSprout-framework/src/main/java/com/ruoyi/framework/config/SecurityConfig.java index eeb51bf..0d7a216 100644 --- a/AutoSprout-framework/src/main/java/com/ruoyi/framework/config/SecurityConfig.java +++ b/AutoSprout-framework/src/main/java/com/ruoyi/framework/config/SecurityConfig.java @@ -24,7 +24,7 @@ import com.ruoyi.framework.security.handle.LogoutSuccessHandlerImpl; /** * spring security配置 - * + * * @author ruoyi */ @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true) @@ -35,7 +35,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter */ @Autowired private UserDetailsService userDetailsService; - + /** * 认证失败处理类 */ @@ -53,7 +53,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter */ @Autowired private JwtAuthenticationTokenFilter authenticationTokenFilter; - + /** * 跨域过滤器 */ @@ -113,7 +113,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter // 过滤请求 .authorizeRequests() // 对于登录login 注册register 验证码captchaImage 允许匿名访问 - .antMatchers("/login", "/register", "/captchaImage","/common/receive","/appCaptcha","/appCodeLogin","/app/**","/common/upload").permitAll() + .antMatchers("/login","/wxlogin", "/register", "/captchaImage","/common/receive","/appCaptcha","/appCodeLogin","/app/**","/common/upload").permitAll() // 静态资源,可匿名访问 .antMatchers(HttpMethod.GET, "/", "/*.html", "/**/*.html", "/**/*.css", "/**/*.js", "/profile/**").permitAll() .antMatchers("/swagger-ui.html", "/swagger-resources/**", "/webjars/**", "/*/api-docs", "/druid/**").permitAll() diff --git a/AutoSprout-framework/src/main/java/com/ruoyi/framework/security/filter/CustomLoginAuthenticationProvider.java b/AutoSprout-framework/src/main/java/com/ruoyi/framework/security/filter/CustomLoginAuthenticationProvider.java index be8f012..7b7e047 100644 --- a/AutoSprout-framework/src/main/java/com/ruoyi/framework/security/filter/CustomLoginAuthenticationProvider.java +++ b/AutoSprout-framework/src/main/java/com/ruoyi/framework/security/filter/CustomLoginAuthenticationProvider.java @@ -26,7 +26,7 @@ public class CustomLoginAuthenticationProvider extends DaoAuthenticationProvider throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials")); } else { String password = authentication.getCredentials().toString(); - if(Constants.CUSTOM_LOGIN_SMS.equals(password)){ + if(Constants.CUSTOM_LOGIN_SMS.equals(password) || Constants.CUSTOM_LOGIN_WX.equals(password)){ //短信登录,不验证密码 }else{ BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); diff --git a/AutoSprout-framework/src/main/java/com/ruoyi/framework/web/service/SysLoginService.java b/AutoSprout-framework/src/main/java/com/ruoyi/framework/web/service/SysLoginService.java index 559b8bc..16edab3 100644 --- a/AutoSprout-framework/src/main/java/com/ruoyi/framework/web/service/SysLoginService.java +++ b/AutoSprout-framework/src/main/java/com/ruoyi/framework/web/service/SysLoginService.java @@ -2,9 +2,20 @@ package com.ruoyi.framework.web.service; import javax.annotation.Resource; +import cn.binarywang.wx.miniapp.api.WxMaService; +import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl; +import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo; +import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl; +import com.alibaba.fastjson2.JSONObject; import com.ruoyi.common.core.domain.entity.AsUser; +import com.ruoyi.common.utils.http.HttpUtils; +import com.ruoyi.common.utils.wx.AccessTokenUtil; +import com.ruoyi.common.utils.wx.vo.AccessToken; import com.ruoyi.device.service.IAsUserService; +import me.chanjar.weixin.common.error.WxErrorException; +import org.apache.commons.lang3.ObjectUtils; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; @@ -58,6 +69,13 @@ public class SysLoginService @Autowired private ISysConfigService configService; + @Value("${wx.appid}") + private String APPID; + + @Value("${wx.appSecret}") + private String APPSECRET; + + /** * 登录验证 * @@ -237,4 +255,60 @@ public class SysLoginService // 生成token return tokenService.createToken(loginUser); } + + /** + * 微信登录 + */ + public String wxloing(String mobileCode) { + String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token="; + String phoneNumber = null; + AsUser user = null; + + /** 根据手机号获取到用户名*/ + String token = AccessTokenUtil.getToken(); + url = url+token; + JSONObject jsonObject = new JSONObject(); + jsonObject.put("code",mobileCode); + String post = HttpUtils.sendPost(url,jsonObject.toString()); + + JSONObject jsonObject1 = JSONObject.parseObject(post); + String phoneInfo = jsonObject1.getString("phone_info"); + WxMaPhoneNumberInfo wxMaPhoneNumberInfo = JSONObject.parseObject(phoneInfo, WxMaPhoneNumberInfo.class); + phoneNumber = wxMaPhoneNumberInfo.getPhoneNumber(); + user = asUserService.selectUserByPhone(phoneNumber); + if(ObjectUtils.isEmpty(user)){ + AsUser asUser = new AsUser(); + asUser.setUserName(phoneNumber); + asUser.setPhonenumber(phoneNumber); + asUser.setLoginIp(IpUtils.getIpAddr()); + asUser.setLoginDate(DateUtils.getNowDate()); + asUser.setCreateTime(DateUtils.getNowDate()); + int i = asUserService.insertUser(asUser); + user = asUser; + } + Authentication authentication = null; // 用户验证 + try { + UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), Constants.CUSTOM_LOGIN_WX); + // 用户名和密码等信息保存在一个上下文中,只要是同一线程等会就能拿到用户名和密码,也就是能在loadUserByUsername(String username)方法中进行密码验证等 + AuthenticationContextHolder.setContext(authenticationToken); + // 把用户类型放在上下文中的details属性中,在UserDetailsServiceImpl.loadUserByUsername中获取 + authenticationToken.setDetails(Constants.USER_TYPE_APP); + // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername + authentication = authenticationManager.authenticate(authenticationToken); + } + catch (Exception e) { + if (e instanceof BadCredentialsException) { + throw new UserPasswordNotMatchException(); //抛出账号或者密码错误的异常 + } else { + throw new ServiceException(e.getMessage()); //抛出其他异常 + } + } finally { + AuthenticationContextHolder.clearContext(); + } + LoginUser loginUser = (LoginUser) authentication.getPrincipal(); + recordAppLoginInfo(loginUser.getUserId()); + return tokenService.createToken(loginUser); + } + + } diff --git a/AutoSprout-ui/src/assets/icons/svg/article.svg b/AutoSprout-ui/src/assets/icons/svg/article.svg new file mode 100644 index 0000000..a5d8996 --- /dev/null +++ b/AutoSprout-ui/src/assets/icons/svg/article.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/AutoSprout-watering/src/main/java/com/ruoyi/device/app/AppController.java b/AutoSprout-watering/src/main/java/com/ruoyi/device/app/AppController.java index 4e3278d..fb0e690 100644 --- a/AutoSprout-watering/src/main/java/com/ruoyi/device/app/AppController.java +++ b/AutoSprout-watering/src/main/java/com/ruoyi/device/app/AppController.java @@ -3,6 +3,7 @@ package com.ruoyi.device.app; import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.JSONObject; import com.ruoyi.common.annotation.Log; +import com.ruoyi.common.constant.Constants; import com.ruoyi.common.core.controller.BaseController; import com.ruoyi.common.core.domain.AjaxResult; import com.ruoyi.common.core.page.TableDataInfo; @@ -19,6 +20,7 @@ import com.ruoyi.device.service.IAsDeviceService; import com.ruoyi.device.service.IAsDeviceVersionService; import com.ruoyi.device.service.IAsUserService; import com.ruoyi.device.service.IAsWateringRecordService; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.*; @@ -118,6 +120,15 @@ public class AppController extends BaseController return success(asDeviceService.selectAsDeviceByDeviceId(deviceId)); } + /** + * 绑定设备 + */ + @GetMapping(value = "/bandDevice") + public AjaxResult getInfo(@RequestBody AsDevice asDevice) + { + return success(asDeviceService.bandDevice(asDevice)); + } + /** * 删除设备列表 */ diff --git a/AutoSprout-watering/src/main/java/com/ruoyi/device/mapper/AsDeviceMapper.java b/AutoSprout-watering/src/main/java/com/ruoyi/device/mapper/AsDeviceMapper.java index 1fd0763..d7295e6 100644 --- a/AutoSprout-watering/src/main/java/com/ruoyi/device/mapper/AsDeviceMapper.java +++ b/AutoSprout-watering/src/main/java/com/ruoyi/device/mapper/AsDeviceMapper.java @@ -8,23 +8,31 @@ import com.ruoyi.system.domain.SysStudent; /** * 设备列表Mapper接口 - * + * * @author 邱贞招 * @date 2023-11-11 */ public interface AsDeviceMapper extends BaseMapper { /** - * 查询设备列表 - * + * 查询设备详情 + * * @param deviceId 设备列表主键 * @return 设备列表 */ public AsDevice selectAsDeviceByDeviceId(Long deviceId); + /** + * 查询设备列表 + * + * @param mac 设备列表主键 + * @return 设备列表 + */ + public AsDevice selectAsDeviceByMac(String mac); + /** * 查询设备列表列表 - * + * * @param asDevice 设备列表 * @return 设备列表集合 */ @@ -32,7 +40,7 @@ public interface AsDeviceMapper extends BaseMapper /** * 新增设备列表 - * + * * @param asDevice 设备列表 * @return 结果 */ @@ -40,7 +48,7 @@ public interface AsDeviceMapper extends BaseMapper /** * 修改设备列表 - * + * * @param asDevice 设备列表 * @return 结果 */ @@ -48,7 +56,7 @@ public interface AsDeviceMapper extends BaseMapper /** * 删除设备列表 - * + * * @param deviceId 设备列表主键 * @return 结果 */ @@ -56,7 +64,7 @@ public interface AsDeviceMapper extends BaseMapper /** * 批量删除设备列表 - * + * * @param deviceIds 需要删除的数据主键集合 * @return 结果 */ diff --git a/AutoSprout-watering/src/main/java/com/ruoyi/device/service/IAsDeviceService.java b/AutoSprout-watering/src/main/java/com/ruoyi/device/service/IAsDeviceService.java index 6e3cc58..858b7e2 100644 --- a/AutoSprout-watering/src/main/java/com/ruoyi/device/service/IAsDeviceService.java +++ b/AutoSprout-watering/src/main/java/com/ruoyi/device/service/IAsDeviceService.java @@ -7,15 +7,15 @@ import com.ruoyi.device.domain.AsDevice; /** * 设备列表Service接口 - * + * * @author 邱贞招 * @date 2023-11-11 */ -public interface IAsDeviceService +public interface IAsDeviceService { /** * 查询设备列表 - * + * * @param deviceId 设备列表主键 * @return 设备列表 */ @@ -23,7 +23,7 @@ public interface IAsDeviceService /** * 查询设备列表列表 - * + * * @param asDevice 设备列表 * @return 设备列表集合 */ @@ -31,7 +31,7 @@ public interface IAsDeviceService /** * 新增设备列表 - * + * * @param asDevice 设备列表 * @return 结果 */ @@ -39,7 +39,7 @@ public interface IAsDeviceService /** * 修改设备列表 - * + * * @param asDevice 设备列表 * @return 结果 */ @@ -47,7 +47,7 @@ public interface IAsDeviceService /** * 批量删除设备列表 - * + * * @param deviceIds 需要删除的设备列表主键集合 * @return 结果 */ @@ -55,7 +55,7 @@ public interface IAsDeviceService /** * 删除设备列表信息 - * + * * @param deviceId 设备列表主键 * @return 结果 */ @@ -68,4 +68,12 @@ public interface IAsDeviceService * @return 结果 */ public AjaxResult watering(AsDevice device,Integer wateringSwitch); + + /** + * 绑定设备 + * + * @param asDevice 设备 + * @return 结果 + */ + int bandDevice(AsDevice asDevice); } diff --git a/AutoSprout-watering/src/main/java/com/ruoyi/device/service/impl/AsDeviceServiceImpl.java b/AutoSprout-watering/src/main/java/com/ruoyi/device/service/impl/AsDeviceServiceImpl.java index 49f0e6e..ca9bd6f 100644 --- a/AutoSprout-watering/src/main/java/com/ruoyi/device/service/impl/AsDeviceServiceImpl.java +++ b/AutoSprout-watering/src/main/java/com/ruoyi/device/service/impl/AsDeviceServiceImpl.java @@ -16,6 +16,7 @@ import com.ruoyi.device.mapper.*; import com.ruoyi.device.service.IAsDeviceService; import com.ruoyi.system.mapper.SysUserMapper; import lombok.SneakyThrows; +import org.apache.commons.lang3.ObjectUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; @@ -89,6 +90,9 @@ public class AsDeviceServiceImpl extends ServiceImpl i public AsDevice selectAsDeviceByDeviceId(Long deviceId) { AsDevice device = asDeviceMapper.selectAsDeviceByDeviceId(deviceId); + if(ObjectUtils.isEmpty(device)){ + throw new ServiceException("没有找到该设备"); + } device.setPicture(modelMapper.selectAsModelByModelId(device.getModelId()).getPicture()); return device; } @@ -111,9 +115,11 @@ public class AsDeviceServiceImpl extends ServiceImpl i asDevice1.setPicture(picture); // 查询onenet设备在线状态 String sendUrl = iotUrl+ IotConstants.ADDS_COMMAND; + String deviceName = asDevice1.getMac();//mac地址就是产品名称 + String param = "device_name=" + deviceName + "&product_id=" + productId +"&timeout=" + timeout; + sendUrl = sendUrl + "?"+param; String token = Token.getToken(); String result = HttpUtils.sendPostWithToken(sendUrl, "111", token); - JSONObject paramsObj = JSON.parseObject(result); String code = paramsObj.getString("code"); if (!HttpStatus.IOT_SUCCESS.equals(code)) { @@ -328,4 +334,22 @@ public class AsDeviceServiceImpl extends ServiceImpl i int insert = wateringRecordMapper.insertAsWateringRecord(record); return AjaxResult.success(insert); } + + /** + * 绑定设备 + * + * @param asDevice 设备对象 + * @return 结果 + */ + @Override + public int bandDevice(AsDevice asDevice) { + /** 根据mac号获取到设备详情*/ + String mac = asDevice.getMac(); + AsDevice device = asDeviceMapper.selectAsDeviceByMac(mac); + if(ObjectUtils.isNotEmpty(device.getUserId())){ + throw new ServiceException("该设备已经绑定用户,请先解绑!"); + } + device.setUserId(asDevice.getUserId()); + return asDeviceMapper.updateAsDevice(device); + } } diff --git a/AutoSprout-watering/src/main/java/com/ruoyi/device/service/impl/AsUserServiceImpl.java b/AutoSprout-watering/src/main/java/com/ruoyi/device/service/impl/AsUserServiceImpl.java index f67d132..cf8a795 100644 --- a/AutoSprout-watering/src/main/java/com/ruoyi/device/service/impl/AsUserServiceImpl.java +++ b/AutoSprout-watering/src/main/java/com/ruoyi/device/service/impl/AsUserServiceImpl.java @@ -1,23 +1,31 @@ package com.ruoyi.device.service.impl; +import com.alibaba.fastjson2.JSON; +import com.alibaba.fastjson2.JSONObject; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.ruoyi.common.annotation.DataScope; +import com.ruoyi.common.constant.HttpStatus; +import com.ruoyi.common.constant.IotConstants; import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.exception.ServiceException; import com.ruoyi.common.utils.SecurityUtils; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.common.utils.bean.BeanValidators; +import com.ruoyi.common.utils.http.HttpUtils; +import com.ruoyi.common.utils.onenet.Token; import com.ruoyi.device.domain.AsDevice; import com.ruoyi.common.core.domain.entity.AsUser; import com.ruoyi.device.mapper.AsDeviceMapper; import com.ruoyi.device.mapper.AsUserMapper; import com.ruoyi.device.service.IAsUserService; import com.ruoyi.system.service.ISysConfigService; +import lombok.SneakyThrows; import org.apache.commons.lang3.ObjectUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -27,7 +35,7 @@ import java.util.List; /** * 用户 业务层处理 - * + * * @author ruoyi */ @Service @@ -48,9 +56,18 @@ public class AsUserServiceImpl implements IAsUserService @Autowired protected Validator validator; + @Value(value = "${watering.iotUrl}") + private String iotUrl; + + @Value(value = "${watering.productId}") + private String productId; + + @Value(value = "${watering.timeout}") + private String timeout; + /** * 根据条件分页查询用户列表 - * + * * @param user 用户信息 * @return 用户信息集合信息 */ @@ -71,7 +88,7 @@ public class AsUserServiceImpl implements IAsUserService /** * 根据条件分页查询已分配用户角色列表 - * + * * @param user 用户信息 * @return 用户信息集合信息 */ @@ -84,7 +101,7 @@ public class AsUserServiceImpl implements IAsUserService /** * 根据条件分页查询未分配用户角色列表 - * + * * @param user 用户信息 * @return 用户信息集合信息 */ @@ -97,7 +114,7 @@ public class AsUserServiceImpl implements IAsUserService /** * 通过用户名查询用户 - * + * * @param userName 用户名 * @return 用户对象信息 */ @@ -109,7 +126,7 @@ public class AsUserServiceImpl implements IAsUserService /** * 通过用户ID查询用户 - * + * * @param userId 用户ID * @return 用户对象信息 */ @@ -122,7 +139,7 @@ public class AsUserServiceImpl implements IAsUserService /** * 校验用户名称是否唯一 - * + * * @param user 用户信息 * @return 结果 */ @@ -177,7 +194,7 @@ public class AsUserServiceImpl implements IAsUserService /** * 新增保存用户信息 - * + * * @param user 用户信息 * @return 结果 */ @@ -190,7 +207,7 @@ public class AsUserServiceImpl implements IAsUserService /** * 注册用户信息 - * + * * @param user 用户信息 * @return 结果 */ @@ -202,7 +219,7 @@ public class AsUserServiceImpl implements IAsUserService /** * 修改保存用户信息 - * + * * @param user 用户信息 * @return 结果 */ @@ -217,7 +234,7 @@ public class AsUserServiceImpl implements IAsUserService /** * 修改用户状态 - * + * * @param user 用户信息 * @return 结果 */ @@ -229,7 +246,7 @@ public class AsUserServiceImpl implements IAsUserService /** * 修改用户基本信息 - * + * * @param user 用户信息 * @return 结果 */ @@ -241,7 +258,7 @@ public class AsUserServiceImpl implements IAsUserService /** * 修改用户头像 - * + * * @param userName 用户名 * @param avatar 头像地址 * @return 结果 @@ -254,7 +271,7 @@ public class AsUserServiceImpl implements IAsUserService /** * 重置用户密码 - * + * * @param user 用户信息 * @return 结果 */ @@ -266,7 +283,7 @@ public class AsUserServiceImpl implements IAsUserService /** * 重置用户密码 - * + * * @param userName 用户名 * @param password 密码 * @return 结果 @@ -280,7 +297,7 @@ public class AsUserServiceImpl implements IAsUserService /** * 通过用户ID删除用户 - * + * * @param userId 用户ID * @return 结果 */ @@ -293,7 +310,7 @@ public class AsUserServiceImpl implements IAsUserService /** * 批量删除用户信息 - * + * * @param userIds 需要删除的用户ID * @return 结果 */ @@ -306,7 +323,7 @@ public class AsUserServiceImpl implements IAsUserService /** * 导入用户数据 - * + * * @param userList 用户数据列表 * @param isUpdateSupport 是否更新支持,如果已存在,则进行更新数据 * @param operName 操作用户 @@ -392,16 +409,27 @@ public class AsUserServiceImpl implements IAsUserService * @param userId 用户id * @return 用户设备信息 */ + @SneakyThrows @Override public List selectDeviceInfoByUser(Long userId,Long deviceId) { AsDevice asDevice = AsDevice.builder().userId(userId).deviceId(deviceId).build(); List asDevices = asDeviceMapper.selectAsDeviceList(asDevice); -// if(ObjectUtils.isNotEmpty(asDevices) && asDevices.size() !=0 ){ -// AsDevice device = asDevices.get(0); -// //请求 -// -// return device; -// } + // 查询onenet设备在线状态 + String sendUrl = iotUrl+ IotConstants.ADDS_COMMAND; + String token = Token.getToken(); + for(AsDevice asDevice1 : asDevices){ + String deviceName = asDevice1.getMac();//mac地址就是产品名称 + String param = "device_name=" + deviceName + "&product_id=" + productId +"&timeout=" + timeout; + sendUrl = sendUrl + "?"+param; + String result = HttpUtils.sendPostWithToken(sendUrl, "111", token); + JSONObject paramsObj = JSON.parseObject(result); + String code = paramsObj.getString("code"); + if (!HttpStatus.IOT_SUCCESS.equals(code)) { + asDevice1.setOnlineStatus("不在线"); + }else{ + asDevice1.setOnlineStatus("在线"); + } + } return asDevices; } } diff --git a/AutoSprout-watering/src/main/resources/mapper/device/AsDeviceMapper.xml b/AutoSprout-watering/src/main/resources/mapper/device/AsDeviceMapper.xml index 2e7d2b7..95b144f 100644 --- a/AutoSprout-watering/src/main/resources/mapper/device/AsDeviceMapper.xml +++ b/AutoSprout-watering/src/main/resources/mapper/device/AsDeviceMapper.xml @@ -3,7 +3,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> - + @@ -43,7 +43,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" - + - + + + insert into as_device @@ -167,9 +172,9 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" - delete from as_device where device_id in + delete from as_device where device_id in #{deviceId} - \ No newline at end of file +