WxxcxIndexController.java 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014
  1. package com.wxxcx.index;
  2. import java.io.*;
  3. import java.math.BigDecimal;
  4. import java.security.MessageDigest;
  5. import java.sql.Timestamp;
  6. import java.time.LocalDate;
  7. import java.util.*;
  8. import javax.annotation.Resource;
  9. import javax.servlet.http.HttpServletRequest;
  10. import javax.servlet.http.HttpServletResponse;
  11. import com.admin.alarm_event.AlarmEvent;
  12. import com.fasterxml.jackson.databind.JsonNode;
  13. import com.fasterxml.jackson.databind.ObjectMapper;
  14. import com.fasterxml.jackson.databind.node.ObjectNode;
  15. import io.swagger.annotations.Api;
  16. import io.swagger.annotations.ApiOperation;
  17. import org.apache.commons.lang.StringUtils;
  18. import org.springframework.beans.factory.annotation.Autowired;
  19. import org.springframework.dao.DataAccessException;
  20. import org.springframework.jdbc.core.BeanPropertyRowMapper;
  21. import org.springframework.jdbc.core.JdbcTemplate;
  22. import org.springframework.web.bind.annotation.GetMapping;
  23. import org.springframework.web.bind.annotation.PostMapping;
  24. import org.springframework.web.bind.annotation.RequestBody;
  25. import org.springframework.web.bind.annotation.RequestMapping;
  26. import org.springframework.web.bind.annotation.RequestParam;
  27. import org.springframework.web.bind.annotation.RestController;
  28. import org.springframework.web.multipart.MultipartFile;
  29. import com.admin.dev.DevVO;
  30. import com.admin.floorPlan.FloorPlanVO;
  31. import com.admin.group.GroupProVO;
  32. import com.admin.group.GroupVO;
  33. import com.admin.groupShare.GroupShareVO;
  34. import com.admin.lbt.LbtVO;
  35. import com.admin.map.GroupDevMapVO;
  36. import com.admin.sbgj.SbgjVO;
  37. import com.admin.areaBase.Base;
  38. import com.wxxcx.room.DevRoomVO;
  39. import com.wxxcx.room.RoomVO;
  40. import com.wxxcx.share.ShareVO;
  41. import com.wxxcx.targets.TargetVO;
  42. import com.wxxcx.user.MiniUserVO;
  43. import com.wxxcx.user.WxRelatiion;
  44. import com.alibaba.fastjson.JSON;
  45. import com.alibaba.fastjson.JSONArray;
  46. import com.alibaba.fastjson.JSONObject;
  47. import com.pub.constant.Constants;
  48. import com.pub.env.Environment;
  49. import com.pub.jdbc.BaseDAO;
  50. import com.pub.log.Log;
  51. import com.pub.page.PageRecord;
  52. import com.pub.util.HttpUtil;
  53. import com.pub.util.JSONUtil;
  54. import com.pub.util.MqttUtil;
  55. import com.pub.util.MsgUtil;
  56. import com.pub.util.PageUtil;
  57. import com.pub.util.R;
  58. import com.pub.upload.FileUploadController;
  59. import com.pub.util.ImageUtil;
  60. @RequestMapping("/s/wxxcx/index")
  61. @Api(tags = "小程序接口")
  62. @RestController
  63. public class WxxcxIndexController<AesException extends Throwable> {
  64. @Resource
  65. private JdbcTemplate jdbcTemplate;
  66. @Autowired
  67. private BaseDAO baseDAO;
  68. @GetMapping("/login")
  69. @ApiOperation(value = "登录接口")
  70. public R login(String code) {
  71. R r = JSONUtil.getSuccessMsg(null);
  72. String res = HttpUtil.request(
  73. "https://api.weixin.qq.com/sns/jscode2session?appid=" + Constants.WXXCXAPPID + "&secret="
  74. + Constants.WXXCXAPPSECRET + "&js_code=" + code + "&grant_type=authorization_code",
  75. null, false, null, null);
  76. JSONObject obj = JSONObject.parseObject(res);
  77. r.data.put("openid", obj.getString("openid"));
  78. r.data.put("unionid", obj.getString("unionid"));
  79. // 查询是否存在该 openid
  80. List<WxRelatiion> list = baseDAO.getJdbcTemplate().query(
  81. "SELECT * FROM wx_relation WHERE openid = ?",
  82. new Object[]{obj.getString("openid")},
  83. new BeanPropertyRowMapper<>(WxRelatiion.class)
  84. );
  85. if (list.size() <= 0) {
  86. String insertSql = "INSERT INTO wx_relation (openid, unionid,fwhopenid) VALUES (?, ?,?)";
  87. baseDAO.getJdbcTemplate().update(insertSql, obj.getString("openid"), obj.getString("unionid"), null);
  88. }
  89. return r;
  90. }
  91. /**
  92. * 小程序用户登录
  93. *
  94. * @param phonef
  95. * @param password
  96. * @return
  97. * @author wy
  98. */
  99. @GetMapping("/checkUser")
  100. @ApiOperation(value = "手机号登录")
  101. public R checkUser(String phone, String password, String openid) {
  102. R r = JSONUtil.getSuccessMsg(null);
  103. // 查询用户信息
  104. Object[] args = new Object[]{phone, password};
  105. List<MiniUserVO> users = baseDAO.getJdbcTemplate().query(
  106. "SELECT * FROM user_info WHERE IFNULL(delete_tag, 0) = 0 AND phone = ? AND password = ?", args,
  107. new BeanPropertyRowMapper<>(MiniUserVO.class));
  108. if (users.size() > 0) {
  109. MiniUserVO user = users.get(0);
  110. if (StringUtils.isEmpty(user.getOpenid())) {
  111. String updateSql = "UPDATE user_info SET openid = ? WHERE phone = ?";
  112. baseDAO.getJdbcTemplate().update(updateSql, openid, phone);
  113. user.setOpenid(openid);
  114. }
  115. r.data.put("user", user);
  116. } else {
  117. r = JSONUtil.getErrorMsg("手机号码或密码错误");
  118. }
  119. return r;
  120. }
  121. /**
  122. * 查找手机号
  123. *
  124. * @param phone
  125. * @return
  126. * @author wy
  127. */
  128. @GetMapping("/checkPhone")
  129. @ApiOperation(value = "查找手机号")
  130. public R checkPhone(String phone, String openid) {
  131. R r = JSONUtil.getSuccessMsg(null);
  132. Object[] args = new Object[]{phone};
  133. List<MiniUserVO> users = baseDAO.getJdbcTemplate().query(
  134. "SELECT * FROM user_info WHERE IFNULL(delete_tag, 0) = 0 AND phone = ?", args,
  135. new BeanPropertyRowMapper<>(MiniUserVO.class));
  136. if (users.size() > 0) {
  137. MiniUserVO user = users.get(0);
  138. if (StringUtils.isEmpty(user.getOpenid()) && StringUtils.isNotEmpty(openid)) {
  139. String updateSql = "UPDATE user_info SET openid = ? WHERE phone = ?";
  140. baseDAO.getJdbcTemplate().update(updateSql, openid, phone);
  141. user.setOpenid(openid);
  142. }
  143. r.data.put("user", user);
  144. } else {
  145. r = JSONUtil.getErrorMsg("该号码未注册");
  146. }
  147. return r;
  148. }
  149. /**
  150. * 记住用户
  151. *
  152. * @param openid
  153. * @return
  154. * @author wy
  155. */
  156. @GetMapping("/checkOpenid")
  157. @ApiOperation(value = "查询是否为新用户")
  158. public R checkOpenid(String openid) {
  159. if (StringUtils.isEmpty(openid)) {
  160. return JSONUtil.getErrorMsg("openid为空");
  161. }
  162. R r = JSONUtil.getSuccessMsg(null);
  163. Object[] args = new Object[]{openid};
  164. List<MiniUserVO> users = baseDAO.getJdbcTemplate().query(
  165. "select * from user_info where IFNULL(delete_tag,0)=0 and openid =?", args,
  166. new BeanPropertyRowMapper<>(MiniUserVO.class));
  167. if (!users.isEmpty()) {
  168. r.data.put("user", users.get(0));
  169. } else {
  170. r = JSONUtil.getErrorMsg("无信息");
  171. }
  172. return r;
  173. }
  174. /**
  175. * 发送登录验证码
  176. *
  177. * @param tel
  178. * @return
  179. * @throws IOException
  180. */
  181. @GetMapping("/sendLoginCaptcha")
  182. @ApiOperation(value = "发送登录验证码")
  183. public R sendLoginCaptcha(String tel) throws IOException {
  184. R r = JSONUtil.getSuccessMsg(null);
  185. int captcha = (int) ((Math.random() * 9 + 1) * 1000);
  186. MsgUtil.sendLoginMsg(tel, String.valueOf(captcha));
  187. r.data.put("captcha", captcha);
  188. return r;
  189. }
  190. /**
  191. * 发送注册验证码
  192. *
  193. * @param tel
  194. * @return
  195. * @throws IOException
  196. */
  197. @GetMapping("/sendRegisterCaptcha")
  198. @ApiOperation(value = "发送注册验证码")
  199. public R sendRegisterCaptcha(String tel) throws IOException {
  200. R r = JSONUtil.getSuccessMsg(null);
  201. int captcha = (int) ((Math.random() * 9 + 1) * 1000);
  202. MsgUtil.sendRegisterMsg(tel, String.valueOf(captcha));
  203. r.data.put("captcha", captcha);
  204. return r;
  205. }
  206. /**
  207. * 发送跌倒提示
  208. *
  209. * @param tel
  210. * @return
  211. * @throws IOException
  212. */
  213. @GetMapping("/sendFallMsg")
  214. @ApiOperation(value = "发送跌倒提示")
  215. public R sendFallMsg(String tel, String dev_name) throws IOException {
  216. R r = JSONUtil.getSuccessMsg(null);
  217. MsgUtil.sendNotifyMsg(tel, dev_name);
  218. return r;
  219. }
  220. public String getAccessToken() {
  221. String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + Constants.WXXCXAPPID + "&secret=" + Constants.WXXCXAPPSECRET;
  222. String response = HttpUtil.request(url, null, false, null, null);
  223. JSONObject jsonResponse = JSONObject.parseObject(response);
  224. return jsonResponse.getString("access_token");
  225. }
  226. @GetMapping("/getPhoneNumber")
  227. @ApiOperation(value = "一键获取手机号")
  228. public R getPhoneNumber(String code) {
  229. R r = JSONUtil.getSuccessMsg(null);
  230. if (StringUtils.isNotEmpty(code)) {
  231. String phoneNumber = "";
  232. // 获取 access_token
  233. String accessToken = getAccessToken();
  234. // 检查 access_token 是否有效
  235. if (StringUtils.isEmpty(accessToken)) {
  236. return JSONUtil.getErrorMsg("获取 access_token 失败,请检查配置");
  237. }
  238. // 请求参数
  239. JSONObject param = new JSONObject();
  240. param.put("code", code);
  241. // 请求获取手机号的接口
  242. String res = HttpUtil.request("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken, param.toJSONString(), false, null, null);
  243. // 处理返回的结果
  244. if (StringUtils.isNotEmpty(res)) {
  245. try {
  246. JSONObject resJson = JSONObject.parseObject(res);
  247. if (resJson.containsKey("phone_info") && resJson.getJSONObject("phone_info").containsKey("phoneNumber")) {
  248. phoneNumber = resJson.getJSONObject("phone_info").getString("phoneNumber");
  249. } else {
  250. phoneNumber = "未返回手机号";
  251. }
  252. } catch (Exception e) {
  253. phoneNumber = "解析失败,异常:" + e.getMessage();
  254. }
  255. } else {
  256. phoneNumber = "接口调用失败,未获取到手机号";
  257. }
  258. // 将获取到的手机号放入返回数据中
  259. r.data.put("phoneNumber", phoneNumber);
  260. } else {
  261. r.data.put("phoneNumber", "无效的 code 参数");
  262. }
  263. return r;
  264. }
  265. @GetMapping("/loginByPhone")
  266. @ApiOperation(value = "一键获取手机号登录")
  267. public R loginByPhone(String code, String openId, String unionId) {
  268. R r = JSONUtil.getSuccessMsg(null);
  269. if (StringUtils.isNotEmpty(code)) {
  270. String phoneNumber = "";
  271. // 获取 access_token
  272. String accessToken = getAccessToken();
  273. // 检查 access_token 是否有效
  274. if (StringUtils.isEmpty(accessToken)) {
  275. return JSONUtil.getErrorMsg("获取 access_token 失败,请检查配置");
  276. }
  277. // 请求参数
  278. JSONObject param = new JSONObject();
  279. param.put("code", code);
  280. // 请求获取手机号的接口
  281. String res = HttpUtil.request("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken, param.toJSONString(), false, null, null);
  282. // 处理返回的结果
  283. if (StringUtils.isNotEmpty(res)) {
  284. try {
  285. JSONObject resJson = JSONObject.parseObject(res);
  286. if (resJson.containsKey("phone_info") && resJson.getJSONObject("phone_info").containsKey("phoneNumber")) {
  287. phoneNumber = resJson.getJSONObject("phone_info").getString("phoneNumber");
  288. MiniUserVO user = new MiniUserVO();
  289. List<MiniUserVO> users = baseDAO.queryAllByCondition(MiniUserVO.class, " and phone='" + phoneNumber + "' ", null);
  290. if (users.size() == 0) {
  291. user.setOpenid(openId);
  292. user.setPhone(phoneNumber);
  293. user.setDelete_tag(0);
  294. baseDAO.insertAll(user);
  295. // 查询是否存在该 openid
  296. List<WxRelatiion> list = baseDAO.getJdbcTemplate().query(
  297. "SELECT * FROM wx_relation WHERE openid = ?",
  298. new Object[]{openId},
  299. new BeanPropertyRowMapper<>(WxRelatiion.class)
  300. );
  301. if (list.size() <= 0) {
  302. String insertSql = "INSERT INTO wx_relation (openid, unionid,fwhopenid) VALUES (?, ?,?)";
  303. baseDAO.getJdbcTemplate().update(insertSql, openId, unionId, null);
  304. }
  305. } else {
  306. r = JSONUtil.getErrorMsg("该号码已注册");
  307. }
  308. } else {
  309. phoneNumber = "未返回手机号";
  310. }
  311. } catch (Exception e) {
  312. phoneNumber = "解析失败,异常:" + e.getMessage();
  313. }
  314. } else {
  315. phoneNumber = "接口调用失败,未获取到手机号";
  316. }
  317. // 将获取到的手机号放入返回数据中
  318. r.data.put("phoneNumber", phoneNumber);
  319. } else {
  320. r.data.put("phoneNumber", "无效的 code 参数");
  321. }
  322. return r;
  323. }
  324. /**
  325. * 检测用户是否拥有设备
  326. *
  327. * @param openid
  328. * @param dev_id
  329. * @return
  330. */
  331. @GetMapping("/checkDev")
  332. @ApiOperation(value = "检测用户是否拥有设备")
  333. public R checkDev(String openid, String dev_id) {
  334. R r = JSONUtil.getSuccessMsg(null);
  335. List<DevVO> devs = baseDAO.queryAllByCondition(DevVO.class, " and ((user_openid ='" + openid + "' and dev_id='" + dev_id + "') or '"
  336. + dev_id + "' in (select dev_id from dev_share where delete_tag =0 and shared ='" + openid + "' and state =1))", null);
  337. if (devs != null && devs.size() > 0) {
  338. r = JSONUtil.getErrorMsg("");
  339. }
  340. return r;
  341. }
  342. /**
  343. * 小程序用户注册
  344. *
  345. * @param user
  346. * @return
  347. * @throws IOException
  348. * @author wy
  349. */
  350. @GetMapping("/userReg")
  351. @ApiOperation(value = "小程序用户注册")
  352. public R userReg(MiniUserVO user) throws IOException {
  353. R r = JSONUtil.getSuccessMsg(null);
  354. List<MiniUserVO> users = baseDAO.queryAllByCondition(MiniUserVO.class, " and phone='" + user.getPhone() + "' ", null);
  355. if (users.size() == 0) {
  356. user.setDelete_tag(0);
  357. baseDAO.insertAll(user);
  358. } else {
  359. r = JSONUtil.getErrorMsg("该号码已注册");
  360. }
  361. return r;
  362. }
  363. /**
  364. * 首页加载
  365. *
  366. * @param user_openid
  367. * @return
  368. * @throws IOException
  369. * @author wy
  370. */
  371. @GetMapping("/home")
  372. @ApiOperation(value = "获取个人首页信息")
  373. public R home(String user_openid) throws IOException {
  374. R r = JSONUtil.getSuccessMsg(null);
  375. List<LbtVO> lbts = baseDAO.queryByCondition(LbtVO.class, null, " create_time desc ");
  376. for (LbtVO v : lbts) {
  377. v.setLbt(Constants.DOMAIN + Environment.COMMON_FILE_UPLOAD_PATH + v.getLbt());
  378. }
  379. r.data.put("lbts", lbts);
  380. List<DevVO> devs = baseDAO.queryAllByCondition(DevVO.class, " and (user_openid='" + user_openid + "' or " +
  381. "dev_id in (select dev_id from dev_share where delete_tag =0 and shared ='" + user_openid + "' and state =1))", null);
  382. r.data.put("qb", devs.size());
  383. int bj = 0;
  384. for (DevVO v : devs) {
  385. if (v.getDev_warn() != null && v.getDev_warn() == 1) {
  386. bj++;
  387. }
  388. }
  389. r.data.put("bj", bj);
  390. // 群组数
  391. List<GroupVO> groups = baseDAO.queryAllByCondition(GroupVO.class, " and (user_openid='" + user_openid + "' or group_uuid in (select group_uuid"
  392. + " from group_share where delete_tag =0 and shared='" + user_openid + "' and state =1))", null);
  393. int qz = groups.size();
  394. r.data.put("qz", qz);
  395. // 待确认分享数
  396. Integer fxqr = baseDAO.getJdbcTemplate().queryForObject(
  397. "select count(dev_id) from dev_share where delete_tag=0 and shared='" + user_openid + "' and (state is null or state =0)", Integer.class);
  398. if (fxqr == null) {
  399. fxqr = 0;
  400. }
  401. r.data.put("fxqr", fxqr);
  402. return r;
  403. }
  404. /**
  405. * 修改密码
  406. *
  407. * @param user_openid
  408. * @param newPassword
  409. * @param oldPassword
  410. * @param phone
  411. * @return
  412. * @throws IOException
  413. */
  414. @GetMapping("/xgmm")
  415. @ApiOperation(value = "修改密码")
  416. public R xgmm(String user_openid, String newPassword, String oldPassword, String phone) throws IOException {
  417. R r = JSONUtil.getSuccessMsg(null);
  418. try {
  419. if (StringUtils.isNotEmpty(phone)) {
  420. MiniUserVO user = baseDAO.queryByKey(MiniUserVO.class, "openid", user_openid);
  421. if (!user.getPhone().equals(phone)) {
  422. throw new Exception("手机号码错误");
  423. }
  424. baseDAO.updateSQL("update user_info set password='" + newPassword + "',update_time ='"
  425. + new Timestamp(System.currentTimeMillis()) + "' where openid='" + user_openid + "'");
  426. } else {
  427. MiniUserVO user = baseDAO.queryByKey(MiniUserVO.class, "openid", user_openid);
  428. if (!user.getPassword().equals(oldPassword)) {
  429. throw new Exception("旧密码错误");
  430. }
  431. baseDAO.updateSQL("update user_info set password='" + newPassword + "',update_time ='"
  432. + new Timestamp(System.currentTimeMillis()) + "' where openid='" + user_openid + "'");
  433. }
  434. } catch (Exception e) {
  435. r = JSONUtil.getErrorMsg(e);
  436. }
  437. return r;
  438. }
  439. /**
  440. * 设备列表
  441. *
  442. * @param user_openid
  443. * @param keyword
  444. * @param zt
  445. * @return
  446. * @throws IOException
  447. */
  448. @GetMapping("/devList")
  449. @ApiOperation(value = "查询设备列表")
  450. public R devList(String user_openid, String keyword, Integer zt) throws IOException {
  451. R r = JSONUtil.getSuccessMsg(null);
  452. String con = "";
  453. if (StringUtils.isNotEmpty(keyword)) {
  454. con = con + " and (dev_name like '%" + keyword + "%' or dev_id like '%" + keyword + "%') ";
  455. }
  456. if (zt != null) {
  457. if (zt == 2) {
  458. con = con + " and online=0 ";
  459. }
  460. if (zt == 3) {
  461. con = con + " and online=1 ";
  462. }
  463. if (zt == 4) {
  464. con = con + " and dev_warn is not null and dev_warn =1";
  465. }
  466. }
  467. List<DevVO> devs = baseDAO.queryAllByCondition(DevVO.class, " and (user_openid='" + user_openid + "' or " +
  468. "dev_id in (select dev_id from dev_share where delete_tag =0 and shared ='" + user_openid + "' and state =1)) " + con, null);
  469. r.data.put("devs", devs);
  470. return r;
  471. }
  472. /**
  473. * 设备列表
  474. *
  475. * @param user_openid
  476. * @param keyword
  477. * @param zt
  478. * @return
  479. * @throws IOException
  480. */
  481. @GetMapping("/devListWithTimes")
  482. @ApiOperation(value = "查询设备列表")
  483. public R devListWithTimes(String user_openid, String keyword, Integer zt) throws IOException {
  484. R r = JSONUtil.getSuccessMsg(null);
  485. String con = "";
  486. if (StringUtils.isNotEmpty(keyword)) {
  487. con = con + " and (dev_name like '%" + keyword + "%' or dev_id like '%" + keyword + "%') ";
  488. }
  489. if (zt != null) {
  490. if (zt == 2) {
  491. con = con + " and online=0 ";
  492. }
  493. if (zt == 3) {
  494. con = con + " and online=1 ";
  495. }
  496. if (zt == 4) {
  497. con = con + " and dev_warn is not null and dev_warn =1";
  498. }
  499. }
  500. List<DevVO> devs = baseDAO.queryAllByCondition(DevVO.class, " and (user_openid='" + user_openid + "' or " +
  501. "dev_id in (select dev_id from dev_share where delete_tag =0 and shared ='" + user_openid + "' and state =1)) " + con, null);
  502. List<Map> res = new ArrayList<>();
  503. if (devs != null && devs.size() > 0) {
  504. ObjectMapper objectMapper = new ObjectMapper();
  505. for (DevVO dev : devs) {
  506. Map beanMap = objectMapper.convertValue(dev, Map.class);
  507. LocalDate previousDate = LocalDate.now().minusDays(1);
  508. String previousDateStr = previousDate.toString();
  509. // 判断查询结果并返回
  510. List<AlarmEvent> stayTimes = null;
  511. try {
  512. stayTimes = jdbcTemplate.query(
  513. "SELECT * FROM alarm_event WHERE dev_id = ? AND DATE(create_time) = ?",
  514. new Object[]{dev.getDev_id(), previousDateStr},
  515. new BeanPropertyRowMapper<>(AlarmEvent.class)
  516. );
  517. } catch (Exception e) {
  518. e.printStackTrace();
  519. }
  520. if (Objects.nonNull(stayTimes) && stayTimes.size() > 0) {
  521. beanMap.put("stayTimes", stayTimes);
  522. beanMap.put("count", stayTimes.size());
  523. } else {
  524. beanMap.put("stayTimes", null);
  525. beanMap.put("count", 0);
  526. }
  527. res.add(beanMap);
  528. }
  529. }
  530. r.data.put("devs", res);
  531. return r;
  532. }
  533. /**
  534. * 设备解绑
  535. *
  536. * @param dev_id
  537. * @param user_openid
  538. * @return
  539. * @throws IOException
  540. */
  541. @GetMapping("/sbjb")
  542. @ApiOperation(value = "解绑设备")
  543. public R sbjb(String dev_id, String user_openid) throws IOException {
  544. R r = JSONUtil.getSuccessMsg(null);
  545. List<DevVO> devs = baseDAO.queryAllByCondition(DevVO.class, " and dev_id='" + dev_id + "' and user_openid= '" + user_openid + "'", null);
  546. try {
  547. if (devs.size() > 0) {
  548. // 绑定人解绑
  549. baseDAO.updateSQL("update dev_info set user_openid=null where dev_id='" + dev_id + "'");
  550. baseDAO.updateSQL("update dev_share set state =0,delete_tag =1 where dev_id='" + dev_id + "'");
  551. } else {
  552. // 被分享者解绑
  553. baseDAO.updateSQL("update dev_share set state =0,delete_tag =1 where dev_id='" + dev_id + "' and shared ='" + user_openid + "' ");
  554. }
  555. } catch (DataAccessException e) {
  556. // 捕获数据库相关的异常,并记录日志
  557. Log.error("数据库操作失败: ", e);
  558. r = JSONUtil.getErrorMsg("数据库操作失败,请稍后再试");
  559. } catch (Exception e) {
  560. // 捕获其他未知的异常,并记录日志
  561. Log.error("解绑设备失败: ", e);
  562. r = JSONUtil.getErrorMsg("解绑设备失败,请稍后再试");
  563. }
  564. return r;
  565. }
  566. /**
  567. * 设备绑定
  568. *
  569. * @param dev
  570. * @return
  571. * @throws IOException
  572. */
  573. @GetMapping("/sbbd")
  574. @ApiOperation(value = "绑定设备")
  575. public R sbbd(DevVO dev) throws IOException {
  576. R r = JSONUtil.getSuccessMsg(null);
  577. try {
  578. List<DevVO> devs = baseDAO.queryAllByCondition(DevVO.class, " and dev_id='" + dev.getDev_id() + "' ", null);
  579. if (devs.size() == 0) {
  580. throw new Exception("设备ID错误");
  581. }
  582. if (StringUtils.isNotEmpty(devs.get(0).getUser_openid())) {
  583. throw new Exception("设备已被绑定");
  584. }
  585. dev.setUpdate_time(new Timestamp(System.currentTimeMillis()));
  586. baseDAO.updateSQL("update dev_info set user_openid='" + dev.getUser_openid() + "',dev_name ='" + dev.getDev_name() + "',length ="
  587. + dev.getLength() + ",width=" + dev.getWidth() + ",height=" + dev.getHeight() + ",update_time ='" + dev.getUpdate_time() + "',north_angle=" +
  588. dev.getNorth_angle() + ",online =1 where dev_id='" + dev.getDev_id() + "'");
  589. } catch (Exception e) {
  590. r = JSONUtil.getErrorMsg(e);
  591. }
  592. return r;
  593. }
  594. /**
  595. * 设备详情
  596. *
  597. * @param dev_id
  598. * @return
  599. * @throws IOException
  600. */
  601. @GetMapping("/sbxq")
  602. @ApiOperation(value = "设备详情")
  603. public R sbxq(String dev_id) throws IOException {
  604. R r = JSONUtil.getSuccessMsg(null);
  605. List<DevVO> devs = baseDAO.queryAllByCondition(DevVO.class, " and dev_id ='" + dev_id + "' ", null);
  606. if (devs.size() != 0) {
  607. r.data.put("dev", devs.get(0));
  608. }
  609. return r;
  610. }
  611. @GetMapping("/sbgj")
  612. @ApiOperation(value = "设备关系")
  613. public R sbgj(String sb_id, String s_date, String e_date) throws IOException {
  614. R r = JSONUtil.getSuccessMsg(null);
  615. List<SbgjVO> sbgjs = baseDAO.queryByCondition(SbgjVO.class, " and sb_id='" + sb_id + "' and create_time>='" + s_date + "' and create_time<='" + e_date + "' ", " create_time desc ");
  616. r.data.put("sbgjs", sbgjs);
  617. return r;
  618. }
  619. /**
  620. * 设备事件
  621. *
  622. * @param dev_id
  623. * @param s_date
  624. * @param e_date
  625. * @param req
  626. * @return
  627. * @throws IOException
  628. */
  629. @GetMapping("/sbsj")
  630. @ApiOperation(value = "设备事件")
  631. public R sbsj(String dev_id, String s_date, String e_date, HttpServletRequest req) throws IOException {
  632. R r = JSONUtil.getSuccessMsg(null);
  633. String con = "";
  634. if (StringUtils.isNotEmpty(s_date)) {
  635. con = con + " and create_time>='" + s_date + "' ";
  636. }
  637. if (StringUtils.isNotEmpty(e_date)) {
  638. con = con + " and create_time<='" + e_date + "' ";
  639. }
  640. PageRecord<TargetVO> targets = baseDAO.queryAllPaginateByCondition(TargetVO.class, " and dev_id='" + dev_id + "' and event=3 " + con, PageUtil.getPageSize(req), PageUtil.getPageNum(req), " create_time desc ");
  641. r.data.put("targets", targets);
  642. return r;
  643. }
  644. @GetMapping("/sbsjV2")
  645. @ApiOperation(value = "设备事件")
  646. public R sbsjV2(String dev_id, String s_date, String e_date, HttpServletRequest req) throws IOException {
  647. StringBuilder sql = new StringBuilder("SELECT * FROM event_list WHERE dev_id = ? AND event = 3");
  648. List<Object> params = new ArrayList<>();
  649. params.add(dev_id);
  650. // 根据传入的日期条件,动态拼接 SQL
  651. if (StringUtils.isNotEmpty(s_date)) {
  652. sql.append(" AND create_time >= ?");
  653. params.add(s_date);
  654. }
  655. if (StringUtils.isNotEmpty(e_date)) {
  656. sql.append(" AND create_time <= ?");
  657. params.add(e_date);
  658. }
  659. // 分页参数
  660. int pageSize = PageUtil.getPageSize(req);
  661. int pageNum = PageUtil.getPageNum(req);
  662. int offset = (pageNum - 1) * pageSize;
  663. sql.append(" ORDER BY create_time DESC LIMIT ? OFFSET ?");
  664. params.add(pageSize);
  665. params.add(offset);
  666. // 执行查询
  667. List<TargetVO> targets = jdbcTemplate.query(sql.toString(), params.toArray(), new BeanPropertyRowMapper<>(TargetVO.class));
  668. // 查询总数,重新初始化参数以避免分页参数干扰
  669. List<Object> countParams = new ArrayList<>();
  670. countParams.add(dev_id);
  671. if (StringUtils.isNotEmpty(s_date)) {
  672. countParams.add(s_date);
  673. }
  674. if (StringUtils.isNotEmpty(e_date)) {
  675. countParams.add(e_date);
  676. }
  677. String countSql = "SELECT COUNT(*) FROM event_list WHERE dev_id = ? AND event = 3";
  678. if (StringUtils.isNotEmpty(s_date)) {
  679. countSql += " AND create_time >= ?";
  680. }
  681. if (StringUtils.isNotEmpty(e_date)) {
  682. countSql += " AND create_time <= ?";
  683. }
  684. int total = jdbcTemplate.queryForObject(countSql, countParams.toArray(), Integer.class);
  685. // 封装分页数据
  686. PageRecord<TargetVO> pageRecord = new PageRecord<>();
  687. pageRecord.setRows(targets);
  688. pageRecord.setTotal((long) total);
  689. pageRecord.setPageSize(pageSize);
  690. pageRecord.setPageNum(pageNum);
  691. // 返回结果
  692. R r = new R();
  693. r.data.put("targets", pageRecord);
  694. return r;
  695. }
  696. /**
  697. * 处理设备事件
  698. *
  699. * @param id
  700. * @return
  701. * @throws IOException
  702. */
  703. @GetMapping("/handleMessage")
  704. @ApiOperation(value = "处理设备事件")
  705. public R handleMessage(int id) throws IOException {
  706. R r = JSONUtil.getSuccessMsg(null);
  707. try {
  708. String sql = "UPDATE event_list SET is_handle = 1 WHERE id = " + id;
  709. baseDAO.updateSQL(sql);
  710. } catch (Exception e) {
  711. r = JSONUtil.getErrorMsg(e);
  712. }
  713. return r;
  714. }
  715. /**
  716. * 设备修改保存
  717. *
  718. * @param vo
  719. * @return
  720. */
  721. @GetMapping("/devSave")
  722. @ApiOperation(value = "设备信息修改保存")
  723. public R devSave(DevVO vo) {
  724. R r = JSONUtil.getSuccessMsg(null);
  725. // 数据库更新
  726. baseDAO.updateSQL("update dev_info set dev_name ='" + vo.getDev_name() + "',north_angle=" + vo.getNorth_angle() + ",start_x=" + vo.getStart_x() + ",stop_x=" + vo.getStop_x() + ",start_y=" + vo.getStart_y() + ",stop_y=" + vo.getStop_y() + ",height=" + vo.getHeight() + ",start_z=" + vo.getStart_z() + ",stop_z=" + vo.getStop_z() + ",status_light=" + vo.getStatus_light() + " where dev_id ='" + vo.getDev_id() + "' ");
  727. DevVO devInfoVO = baseDAO.queryByKey(DevVO.class, "dev_id", vo.getDev_id());
  728. String software = devInfoVO.getSoftware();
  729. String result = "";
  730. if (software != null) {
  731. String[] parts = software.split("\\.");
  732. result = parts[0] + "." + parts[1];
  733. } else {
  734. result = "2.0";
  735. }
  736. if (Double.parseDouble(result) >= 2.0) {
  737. String topic = "/dev/" + devInfoVO.getDev_id() + "/set_device_param";
  738. Map<String, BigDecimal> base = new HashMap<>();
  739. Map<String, Map<String, BigDecimal>> baseParent = new HashMap<>();
  740. base.put("x_cm_start", vo.getStart_x());
  741. base.put("x_cm_stop", vo.getStop_x());
  742. base.put("y_cm_start", vo.getStart_y());
  743. base.put("y_cm_stop", vo.getStop_y());
  744. base.put("z_cm_start", vo.getStart_z());
  745. base.put("z_cm_stop", vo.getStop_z());
  746. baseParent.put("base", base);
  747. Map<String, BigDecimal> z_cm = new HashMap<>();
  748. z_cm.put("z_cm", vo.getHeight());
  749. JSONObject jsonObject = new JSONObject();
  750. jsonObject.put("sensor_location", z_cm);
  751. jsonObject.put("ext_region", baseParent);
  752. int indicator_led = 0;
  753. if (vo.getStatus_light() == 0) {
  754. indicator_led = 1;
  755. }
  756. if (vo.getStatus_light() == 1) {
  757. indicator_led = 0;
  758. }
  759. jsonObject.put("indicator_led", indicator_led);
  760. try {
  761. MqttUtil.pub(topic, jsonObject.toJSONString());
  762. } catch (Exception e) {
  763. // TODO: handle exception
  764. // r = JSONUtil.getErrorMsg(e);
  765. }
  766. } else {
  767. String topic = "/mps/set_device_param";
  768. JSONObject msg = new JSONObject();
  769. msg.put("dev_id", vo.getDev_id());
  770. msg.put("mounting_plain", vo.getMount_plain());
  771. msg.put("height", vo.getHeight());
  772. JSONObject area = new JSONObject();
  773. area.put("start_x", vo.getStart_x());
  774. area.put("stop_x", vo.getStop_x());
  775. area.put("start_y", vo.getStart_y());
  776. area.put("stop_y", vo.getStop_y());
  777. area.put("start_z", vo.getStart_z());
  778. area.put("stop_z", vo.getStop_z());
  779. msg.put("area", area);
  780. try {
  781. MqttUtil.pub(topic, msg.toJSONString());
  782. } catch (Exception e) {
  783. // TODO: handle exception
  784. r = JSONUtil.getErrorMsg(e);
  785. }
  786. }
  787. return r;
  788. }
  789. /**
  790. * 房间布局读取
  791. *
  792. * @param openid
  793. * @param dev_id
  794. * @return
  795. */
  796. @GetMapping("/readRoom")
  797. @ApiOperation(value = "读取房间信息")
  798. public R readRoom(String openid, String dev_id) {
  799. R r = JSONUtil.getSuccessMsg(null);
  800. DevRoomVO devRoomVO = baseDAO.queryByKey(DevRoomVO.class, "dev_id", dev_id);
  801. if (devRoomVO == null) {
  802. r = JSONUtil.getErrorMsg("房间信息不存在");
  803. return r;
  804. }
  805. JSONArray res = new JSONArray();
  806. if (devRoomVO.getFurnitures() != null && devRoomVO.getFurnitures().length() > 0) {
  807. res.addAll(JSON.parseArray(devRoomVO.getFurnitures()));
  808. }
  809. if (devRoomVO.getSub_regions() != null && devRoomVO.getSub_regions().length() > 0) {
  810. res.addAll(JSON.parseArray(devRoomVO.getSub_regions()));
  811. }
  812. // 向前端发送数据
  813. r.data.put("data", res);
  814. return r;
  815. }
  816. /**
  817. * 房间布局保存
  818. *
  819. * @param vo
  820. * @return
  821. */
  822. @PostMapping("/saveRoom")
  823. @ApiOperation(value = "房间布局保存")
  824. public R saveRoom(@RequestBody RoomVO vo) {
  825. R r = JSONUtil.getSuccessMsg(null);
  826. String dev_id = vo.getDev_id();
  827. try {
  828. String jsonString = JSON.toJSONString(vo);
  829. // 写入数据库
  830. JSONObject obj = JSONObject.parseObject(jsonString);
  831. JSONArray roomParams = obj.getJSONArray("roomParams");
  832. DevRoomVO devRoomVO = baseDAO.queryByKey(DevRoomVO.class, "dev_id", dev_id);
  833. if (devRoomVO == null) {
  834. DevRoomVO room = new DevRoomVO();
  835. room.setDelete_tag(0);
  836. room.setDev_id(dev_id);
  837. baseDAO.insertAll(room);
  838. }
  839. // StringBuffer sql = new StringBuffer("update dev_room set room_params= JSON_OBJECT(");
  840. StringBuffer sql = new StringBuffer("update dev_room set ");
  841. // sql.append("'openid','" + obj.getString("openid") + "',");
  842. // sql.append("'dev_id','" + obj.getString("dev_id") + "',");
  843. // sql.append("'start_x','" + obj.getString("start_x") + "',");
  844. // sql.append("'stop_x','" + obj.getString("stop_x") + "',");
  845. // sql.append("'start_y','" + obj.getString("start_y") + "',");
  846. // sql.append("'stop_y','" + obj.getString("stop_y") + "',");
  847. // sql.append("'roomParams'," + "JSON_ARRAY(");
  848. // 子区域插入sql
  849. StringBuffer subBuffer = new StringBuffer("sub_regions= JSON_ARRAY(");
  850. // 家具插入sql
  851. StringBuffer furBuffer = new StringBuffer("furnitures= JSON_ARRAY(");
  852. if (roomParams.size() > 0) {
  853. boolean hasSub = false;
  854. boolean hasFur = false;
  855. for (int i = 0; i < roomParams.size(); i++) {
  856. JSONObject itemObj = roomParams.getJSONObject(i);
  857. // sql.append("JSON_OBJECT('name','" + itemObj.getString("name") + "',");
  858. // sql.append("'type','" + itemObj.getString("type") + "',");
  859. // sql.append("'width'," + itemObj.getString("width") + ",");
  860. // sql.append("'height'," + itemObj.getString("height") + ",");
  861. // sql.append("'heightToM'," + itemObj.getString("heightToM") + ",");
  862. // sql.append("'left'," + itemObj.getString("left") + ",");
  863. // sql.append("'rotate'," + itemObj.getString("rotate") + ",");
  864. // sql.append("'top'," + itemObj.getString("top") + ",");
  865. // sql.append("'widthToM'," + itemObj.getString("widthToM") + ",");
  866. // sql.append("'x'," + itemObj.getString("x") + ",");
  867. // sql.append("'y'," + itemObj.getString("y") + ",");
  868. // sql.append("'yuanX'," + itemObj.getString("yuanX") + ",");
  869. // sql.append("'yuanY'," + itemObj.getString("yuanY") + "),");
  870. String type = itemObj.getString("type");
  871. if (type.contains("area") || type.contains("otherArea")) {
  872. // 子区域
  873. subBuffer.append("JSON_OBJECT('name','" + itemObj.getString("name") + "',");
  874. subBuffer.append("'type','" + itemObj.getString("type") + "',");
  875. subBuffer.append("'width'," + itemObj.getString("width") + ",");
  876. subBuffer.append("'height'," + itemObj.getString("height") + ",");
  877. // subBuffer.append("'heightToM'," + itemObj.getString("heightToM") + ",");
  878. subBuffer.append("'left'," + itemObj.getString("left") + ",");
  879. subBuffer.append("'rotate'," + itemObj.getString("rotate") + ",");
  880. subBuffer.append("'top'," + itemObj.getString("top") + ",");
  881. // subBuffer.append("'widthToM'," + itemObj.getString("widthToM") + ",");
  882. subBuffer.append("'x'," + itemObj.getString("x") + ",");
  883. subBuffer.append("'y'," + itemObj.getString("y") + ",");
  884. subBuffer.append("'yuanX'," + itemObj.getString("yuanX") + ",");
  885. subBuffer.append("'yuanY'," + itemObj.getString("yuanY") + "),");
  886. hasSub = true;
  887. } else {
  888. // 家具
  889. furBuffer.append("JSON_OBJECT('name','" + itemObj.getString("name") + "',");
  890. furBuffer.append("'type','" + itemObj.getString("type") + "',");
  891. furBuffer.append("'width'," + itemObj.getString("width") + ",");
  892. furBuffer.append("'height'," + itemObj.getString("height") + ",");
  893. // furBuffer.append("'heightToM'," + itemObj.getString("heightToM") + ",");
  894. furBuffer.append("'left'," + itemObj.getString("left") + ",");
  895. furBuffer.append("'rotate'," + itemObj.getString("rotate") + ",");
  896. furBuffer.append("'top'," + itemObj.getString("top") + ",");
  897. // furBuffer.append("'widthToM'," + itemObj.getString("widthToM") + ",");
  898. furBuffer.append("'x'," + itemObj.getString("x") + ",");
  899. furBuffer.append("'y'," + itemObj.getString("y") + ",");
  900. furBuffer.append("'yuanX'," + itemObj.getString("yuanX") + ",");
  901. furBuffer.append("'yuanY'," + itemObj.getString("yuanY") + "),");
  902. hasFur = true;
  903. }
  904. }
  905. // sql.setLength(sql.length() - 1);
  906. // sql.append("))" );
  907. if (hasSub) {
  908. subBuffer.setLength(subBuffer.length() - 1);
  909. sql.append(subBuffer).append(")");
  910. } else {
  911. sql.append(" sub_regions=null ");
  912. }
  913. sql.append(",");
  914. if (hasFur) {
  915. furBuffer.setLength(furBuffer.length() - 1);
  916. sql.append(furBuffer).append(")");
  917. } else {
  918. sql.append(" furnitures=null ");
  919. }
  920. sql.append(" where dev_id ='" + dev_id + "' ");
  921. System.out.println(sql.toString());
  922. // update dev_room set room_params= JSON_OBJECT('openid','oioMm7VtkWkvHFYBlzCR6couIENQ','dev_id','8CBFEA0B75D8','start_x','-200.0','stop_x','200.0','start_y','-200.0','stop_y','200.0',JSON_OBJECT('name','门','type','other','width',20,'height',80,'heightToM',80.0,'left',303,'rotate',false,'top',191,'widthToM',20.0,'x',-196.97,'y',198.09,'yuanX',0,'yuanY',0)) where dev_id ='8CBFEA0B75D8'
  923. baseDAO.updateSQL(sql.toString());
  924. //发送屏蔽区域的数据到服务器
  925. // 创建 ObjectMapper 实例
  926. ObjectMapper objectMapper = new ObjectMapper();
  927. // 将 JSON 字符串转换成 JsonNode 对象
  928. JsonNode rootNode = objectMapper.readTree(jsonString);
  929. // 获取 roomParams 数组
  930. JsonNode roomParamsNode = rootNode.path("roomParams");
  931. // 创建一个新的 List 用来存储 type 包含 "area" 的元素
  932. List<Base> ext_sub_regions = new ArrayList<>();
  933. for (JsonNode room : roomParamsNode) {
  934. // 遍历 roomParamsNode 数组
  935. String type = room.path("type").asText();
  936. if (type.contains("area") || type.contains("otherArea")) {
  937. Base base = new Base(0, 100, 0, 50, 1, 1);
  938. int x = room.path("x").asInt();
  939. int y = room.path("y").asInt();
  940. int width = room.path("width").asInt();
  941. int height = room.path("height").asInt();
  942. // 设置 base 对象的字段值
  943. base.setX_cm_start(x);
  944. base.setX_cm_stop(x + width);
  945. base.setY_cm_start(y);
  946. base.setY_cm_stop(y - height);
  947. // 设置固定值
  948. base.setTrack_presence(1);
  949. base.setExclude_falling(1);
  950. ext_sub_regions.add(base);
  951. }
  952. }
  953. ObjectMapper objectMapperOne = new ObjectMapper();
  954. List<ObjectNode> transformedList = new ArrayList<>();
  955. if (ext_sub_regions.size() > 0) {
  956. for (Base baseOne : ext_sub_regions) {
  957. ObjectNode newObject = objectMapperOne.createObjectNode();
  958. ObjectNode baseNode = objectMapperOne.createObjectNode();
  959. baseNode.put("x_cm_start", baseOne.getX_cm_start());
  960. baseNode.put("x_cm_stop", baseOne.getX_cm_stop());
  961. baseNode.put("y_cm_start", baseOne.getY_cm_start());
  962. baseNode.put("y_cm_stop", baseOne.getY_cm_stop());
  963. baseNode.put("presence_enter_duration", 0);
  964. baseNode.put("presence_exit_duration", 0);
  965. baseNode.put("track_presence", baseOne.getTrack_presence());
  966. baseNode.put("exclude_falling", baseOne.getExclude_falling());
  967. newObject.set("base", baseNode);
  968. newObject.put("z_cm_start", 0); // 固定为 0
  969. newObject.put("z_cm_stop", 0); // 固定为 0
  970. newObject.put("is_low_snr", 0); // 固定为 0
  971. newObject.put("is_door", 0); // 固定为 0
  972. transformedList.add(newObject);
  973. }
  974. ObjectNode resultNode = objectMapper.createObjectNode();
  975. resultNode.set("ext_sub_regions", objectMapper.valueToTree(transformedList));
  976. String jsonStringTwo = objectMapper.writeValueAsString(resultNode);
  977. try {
  978. StringBuffer getTopic = new StringBuffer("/dev/" + dev_id + "/set_device_param");
  979. MqttUtil.pub(getTopic.toString(), jsonStringTwo);
  980. } catch (Exception e) {
  981. r = JSONUtil.getErrorMsg(e);
  982. }
  983. } else {
  984. ObjectNode resultNode = objectMapper.createObjectNode();
  985. resultNode.set("ext_sub_regions", objectMapper.valueToTree(transformedList));
  986. String jsonStringTwo = objectMapper.writeValueAsString(resultNode);
  987. try {
  988. StringBuffer getTopic = new StringBuffer("/dev/" + dev_id + "/set_device_param");
  989. MqttUtil.pub(getTopic.toString(), jsonStringTwo);
  990. } catch (Exception e) {
  991. r = JSONUtil.getErrorMsg(e);
  992. }
  993. }
  994. } else {
  995. sql.append(" sub_regions=null , furnitures=null ");
  996. sql.append(" where dev_id ='" + dev_id + "' ");
  997. baseDAO.updateSQL(sql.toString());
  998. JSONObject jsonObject = new JSONObject();
  999. JSONArray extRegion = new JSONArray();
  1000. jsonObject.put("ext_sub_regions", extRegion);
  1001. try {
  1002. StringBuffer getTopic = new StringBuffer("/dev/" + dev_id + "/set_device_param");
  1003. MqttUtil.pub(getTopic.toString(), jsonObject.toJSONString());
  1004. } catch (Exception e) {
  1005. r = JSONUtil.getErrorMsg(e);
  1006. }
  1007. }
  1008. } catch (IOException e) {
  1009. e.printStackTrace();
  1010. r = JSONUtil.getErrorMsg(e);
  1011. }
  1012. return r;
  1013. }
  1014. /**
  1015. * 设备(修改)保存
  1016. *
  1017. * @param dev
  1018. * @return
  1019. * @throws IOException
  1020. */
  1021. @GetMapping("/sbbc")
  1022. @ApiOperation(value = "设备修改保存(第一次绑定)")
  1023. public R sbbc(DevVO vo) throws IOException {
  1024. R r = JSONUtil.getSuccessMsg(null);
  1025. double length = vo.getLength().doubleValue();
  1026. double width = vo.getWidth().doubleValue();
  1027. BigDecimal start_x = new BigDecimal(-length / 2);
  1028. BigDecimal stop_x = new BigDecimal(length / 2);
  1029. BigDecimal start_y = new BigDecimal(-width / 2);
  1030. BigDecimal stop_y = new BigDecimal(width / 2);
  1031. vo.setStart_x(start_x);
  1032. vo.setStop_x(stop_x);
  1033. vo.setStart_y(start_y);
  1034. vo.setStop_y(stop_y);
  1035. // 数据库更新
  1036. baseDAO.updateSQL("update dev_info set dev_name ='" + vo.getDev_name() + "',mount_plain='" + vo.getMount_plain() + "',length=" + vo.getLength() + ",width="
  1037. + vo.getWidth() + ",height=" + vo.getHeight() + ",start_x =" + vo.getStart_x() + ",stop_x =" + vo.getStop_x() + ",start_y =" + vo.getStart_y() + ",stop_y ="
  1038. + vo.getStop_y() + ",start_z =" + vo.getStart_z() + ",stop_z =" + vo.getStop_z() + " where dev_id ='" + vo.getDev_id() + "' ");
  1039. String topic = "/mps/set_device_param";
  1040. JSONObject msg = new JSONObject();
  1041. msg.put("dev_id", vo.getDev_id());
  1042. msg.put("mounting_plain", vo.getMount_plain());
  1043. msg.put("height", vo.getHeight());
  1044. JSONObject area = new JSONObject();
  1045. area.put("start_x", vo.getStart_x());
  1046. area.put("stop_x", vo.getStop_x());
  1047. area.put("start_y", vo.getStart_y());
  1048. area.put("stop_y", vo.getStop_y());
  1049. area.put("start_z", vo.getStart_z());
  1050. area.put("stop_z", vo.getStop_z());
  1051. msg.put("area", area);
  1052. try {
  1053. MqttUtil.pub(topic, msg.toJSONString());
  1054. } catch (Exception e) {
  1055. // TODO: handle exception
  1056. r = JSONUtil.getErrorMsg(e);
  1057. }
  1058. return r;
  1059. }
  1060. // 雷达位置更新
  1061. @GetMapping("/devPosUpdate")
  1062. @ApiOperation(value = "更新雷达位置")
  1063. public R devSave(String dev_id, float x, float y) {
  1064. R r = JSONUtil.getSuccessMsg(null);
  1065. DevVO vo = baseDAO.queryByKey(DevVO.class, "dev_id", dev_id);
  1066. if (vo == null) {
  1067. return JSONUtil.getErrorMsg("未查询到该设备,请退出重试");
  1068. }
  1069. baseDAO.updateSQL("update dev_info set x=" + x + ",y=" + y + " where dev_id ='" + dev_id + "' and delete_tag=0");
  1070. return r;
  1071. }
  1072. /**
  1073. * 设备分享
  1074. *
  1075. * @param share
  1076. * @return
  1077. * @throws IOException
  1078. */
  1079. @GetMapping("/sbfx")
  1080. @ApiOperation(value = "个人分享设备")
  1081. public R sbfx(ShareVO share) throws IOException {
  1082. R r = JSONUtil.getSuccessMsg(null);
  1083. List<MiniUserVO> users = baseDAO.queryAllByCondition(MiniUserVO.class, " and phone='" + share.getShared_phone() + "' ", null);
  1084. // 被分享者已注册
  1085. if (users.size() > 0) {
  1086. MiniUserVO user = users.get(0);
  1087. share.setShared(user.getOpenid());
  1088. share.setState(0);
  1089. // 检查当前设备是否存在未处理邀请
  1090. List<ShareVO> shares = baseDAO.queryAllByCondition(ShareVO.class, " and sharer='" + share.getSharer() + "' and shared='" + share.getShared() +
  1091. "' and dev_id='" + share.getDev_id() + "' and state=0", null);
  1092. // 已发送邀请未处理
  1093. if (shares.size() > 0) {
  1094. r = JSONUtil.getErrorMsg("请勿重复发送邀请");
  1095. }
  1096. // 未发送邀请
  1097. else {
  1098. baseDAO.insertAll(share);
  1099. }
  1100. } else {
  1101. r = JSONUtil.getErrorMsg("手机号码未注册");
  1102. }
  1103. return r;
  1104. }
  1105. /**
  1106. * 通过链接分享设备
  1107. *
  1108. * @return
  1109. */
  1110. @GetMapping("/sbfxByUrl")
  1111. @ApiOperation(value = "通过链接分享设备")
  1112. public R sbfxByUrl(ShareVO share) {
  1113. R r = JSONUtil.getSuccessMsg(null);
  1114. // 分享人手机号为空(链接分享)
  1115. if (share.getSharer_phone() == null || share.getSharer_phone().isEmpty()) {
  1116. List<MiniUserVO> sharers = baseDAO.queryAllByCondition(MiniUserVO.class, " and openid='" + share.getSharer() + "' ", null);
  1117. if (sharers.size() > 0) {
  1118. MiniUserVO userVO = sharers.get(0);
  1119. share.setSharer_phone(userVO.getPhone());
  1120. }
  1121. }
  1122. share.setState(1);
  1123. List<ShareVO> shares = baseDAO.queryAllByCondition(ShareVO.class, " and sharer='" + share.getSharer() + "' and shared='" + share.getShared() + "' "
  1124. + "and dev_id='" + share.getDev_id() + "' and state=0", null);
  1125. // 已发送邀请未处理
  1126. if (shares != null && shares.size() > 0) {
  1127. r = JSONUtil.getErrorMsg("存在未处理的邀请,请回主页查看");
  1128. }
  1129. // 未发送邀请
  1130. else {
  1131. baseDAO.insertAll(share);
  1132. }
  1133. Log.info("分享结果:" + r.getResult());
  1134. return r;
  1135. }
  1136. /**
  1137. * 设备分享记录
  1138. *
  1139. * @param user_openid
  1140. * @return
  1141. * @throws IOException
  1142. */
  1143. @GetMapping("/sbfxjl")
  1144. @ApiOperation(value = "查看设备分享记录")
  1145. public R sbfxjl(String user_openid) throws IOException {
  1146. R r = JSONUtil.getSuccessMsg(null);
  1147. List<ShareVO> shares = baseDAO.queryAllByCondition(ShareVO.class, " and shared='" + user_openid + "' ", null);
  1148. // ForeignKeyUtil.processForeignKey(fxjls, "tbl_sb", "sb_id", new String[] {"mc","bh"}, new String[] {"mc","bh"});
  1149. // ForeignKeyUtil.processForeignKey(fxjls, "tbl_hy", "fxr", new String[] {"sjhm"}, new String[] {"sjhm"});
  1150. r.data.put("shares", shares);
  1151. return r;
  1152. }
  1153. /**
  1154. * 设备分享确认
  1155. *
  1156. * @param dev_id
  1157. * @param state
  1158. * @return
  1159. * @throws IOException
  1160. */
  1161. @GetMapping("/sbfxqr")
  1162. @ApiOperation(value = "设备分享确认")
  1163. public R sbfx(String dev_id, Integer state, String user_openid) throws IOException {
  1164. R r = JSONUtil.getSuccessMsg(null);
  1165. baseDAO.updateSQL("update dev_share set state=" + state + " where dev_id='" + dev_id + "' and shared ='" +
  1166. user_openid + "' ");
  1167. return r;
  1168. }
  1169. /**
  1170. * 检查更新/获取版本
  1171. *
  1172. * @return
  1173. * @throws IOException
  1174. */
  1175. @GetMapping("/getVersion")
  1176. @ApiOperation(value = "获取设备新版本")
  1177. public R getVersion(String dev_id) throws IOException {
  1178. R r = JSONUtil.getSuccessMsg(null);
  1179. StringBuffer getTopic = new StringBuffer("/mps/" + dev_id + "/get_device_info ");
  1180. try {
  1181. JSONObject msg = new JSONObject();
  1182. msg.put("dev_id", dev_id);
  1183. MqttUtil.pub(getTopic.toString(), msg.toJSONString());
  1184. } catch (Exception e) {
  1185. // TODO: handle exception
  1186. r = JSONUtil.getErrorMsg(e);
  1187. }
  1188. return r;
  1189. }
  1190. /**
  1191. * 设备软重启
  1192. *
  1193. * @param dev_id
  1194. * @return
  1195. */
  1196. @GetMapping("/reboot")
  1197. @ApiOperation(value = "设备软重启")
  1198. public R reboot(String dev_id) {
  1199. R r = JSONUtil.getSuccessMsg(null);
  1200. StringBuffer topic = new StringBuffer("/dev/" + dev_id + "/reboot");
  1201. try {
  1202. MqttUtil.pub(topic.toString(), "1");
  1203. } catch (Exception e) {
  1204. // TODO: handle exception
  1205. r = JSONUtil.getErrorMsg(e);
  1206. }
  1207. return r;
  1208. }
  1209. /**
  1210. * OTA升级
  1211. *
  1212. * @param dev_id
  1213. * @return
  1214. */
  1215. @GetMapping("/updateOTA")
  1216. @ApiOperation(value = "OTA升级")
  1217. public R updateOTA(String dev_id) {
  1218. R r = JSONUtil.getSuccessMsg(null);
  1219. StringBuffer topic = new StringBuffer("/dev/" + dev_id + "/update_firmware");
  1220. try {
  1221. MqttUtil.pub(topic.toString(), "1");
  1222. } catch (Exception e) {
  1223. // TODO: handle exception
  1224. r = JSONUtil.getErrorMsg(e);
  1225. }
  1226. return r;
  1227. }
  1228. // 0:站 1:坐 2:躺 3:跌倒
  1229. @GetMapping("/startPoseFix")
  1230. @ApiOperation(value = "姿态修正")
  1231. public R startPoseFix(int poseIndex, String dev_id) {
  1232. R r = JSONUtil.getSuccessMsg(null);
  1233. Short pose;
  1234. switch (poseIndex) {
  1235. case 0:
  1236. pose = 4;
  1237. break;
  1238. case 1:
  1239. pose = 5;
  1240. break;
  1241. case 2:
  1242. pose = 0;
  1243. break;
  1244. case 3:
  1245. pose = 7;
  1246. break;
  1247. default:
  1248. pose = -1;
  1249. break;
  1250. }
  1251. MqttUtil.setMap(pose, dev_id);
  1252. return r;
  1253. }
  1254. @GetMapping("/stopPoseFix")
  1255. @ApiOperation(value = "停止姿态修正")
  1256. public R stopPoseFix(String dev_id) {
  1257. R r = JSONUtil.getSuccessMsg(null);
  1258. MqttUtil.deleteMap(dev_id);
  1259. return r;
  1260. }
  1261. @GetMapping("/getDeviceInfo")
  1262. @ApiOperation(value = "获取设备信息")
  1263. public R getDeviceInfo(String dev_id) {
  1264. R r = JSONUtil.getSuccessMsg(null);
  1265. String topic = "/mps/get_device_info";
  1266. JSONObject msg = new JSONObject();
  1267. msg.put("dev_id", dev_id);
  1268. try {
  1269. MqttUtil.pub(topic, msg.toJSONString());
  1270. } catch (Exception e) {
  1271. // TODO: handle exception
  1272. r = JSONUtil.getErrorMsg(e);
  1273. }
  1274. return r;
  1275. }
  1276. @GetMapping("/getDeviceParam")
  1277. @ApiOperation(value = "获取设备参数")
  1278. public R getDeviceParam(String dev_id) {
  1279. R r = JSONUtil.getSuccessMsg(null);
  1280. String topic = "/mps/get_device_param";
  1281. JSONObject msg = new JSONObject();
  1282. msg.put("dev_id", dev_id);
  1283. try {
  1284. MqttUtil.pub(topic, msg.toJSONString());
  1285. } catch (Exception e) {
  1286. // TODO: handle exception
  1287. r = JSONUtil.getErrorMsg(e);
  1288. }
  1289. return r;
  1290. }
  1291. // 添加群组
  1292. @GetMapping("/addGroup")
  1293. @ApiOperation(value = "添加群组")
  1294. public R addGroup(GroupVO vo) {
  1295. R r = JSONUtil.getSuccessMsg(null);
  1296. vo.setGroup_uuid((UUID.randomUUID()).toString());
  1297. vo.setDelete_tag(0);
  1298. baseDAO.insertAll(vo);
  1299. // MQTT
  1300. String topic = "/mps/add_group";
  1301. JSONObject msg = new JSONObject();
  1302. msg.put("group_uuid", vo.getGroup_uuid());
  1303. msg.put("north_angle", vo.getNorth_angle());
  1304. try {
  1305. MqttUtil.pub(topic, msg.toJSONString());
  1306. } catch (Exception e) {
  1307. Log.info("添加群组:MQTT消息发送失败");
  1308. }
  1309. return r;
  1310. }
  1311. // 删除群组
  1312. @GetMapping("/deleteGroup")
  1313. @ApiOperation(value = "删除群组")
  1314. public R deleteGroup(String group_uuid) {
  1315. R r = JSONUtil.getSuccessMsg(null);
  1316. baseDAO.updateSQL("update dev_group set delete_tag =1 where group_uuid ='" + group_uuid + "' ");
  1317. // MQTT
  1318. String topic = "/mps/del_group";
  1319. JSONObject msg = new JSONObject();
  1320. msg.put("group_uuid", group_uuid);
  1321. try {
  1322. MqttUtil.pub(topic, msg.toJSONString());
  1323. } catch (Exception e) {
  1324. Log.info("删除群组:MQTT消息发送失败");
  1325. }
  1326. return r;
  1327. }
  1328. // 更新群组
  1329. @GetMapping("/updateGroup")
  1330. @ApiOperation(value = "更新群组")
  1331. public R updateGroup(GroupVO vo) {
  1332. R r = JSONUtil.getSuccessMsg(null);
  1333. baseDAO.updateSQL("update dev_group set group_name ='" + vo.getGroup_name() + "',length=" + vo.getLength()
  1334. + ",width=" + vo.getWidth() + ",north_angle=" + vo.getNorth_angle() + " where group_uuid ='" + vo.getGroup_uuid() + "' ");
  1335. // MQTT
  1336. String topic = "/mps/update_group";
  1337. JSONObject msg = new JSONObject();
  1338. msg.put("group_uuid", vo.getGroup_uuid());
  1339. msg.put("north_angle", vo.getNorth_angle());
  1340. try {
  1341. MqttUtil.pub(topic, msg.toJSONString());
  1342. } catch (Exception e) {
  1343. Log.info("更新群组:MQTT消息发送失败");
  1344. }
  1345. return r;
  1346. }
  1347. // 群组列表
  1348. // @GetMapping("/groupList")
  1349. // public R groupList(String openid) {
  1350. // R r =JSONUtil.getSuccessMsg(null);
  1351. // List<GroupVO> groups = baseDAO.queryAllByCondition(GroupVO.class, " and (user_openid='" + openid + "' or group_uuid in (select group_uuid"
  1352. // + " from group_share where delete_tag =0 and shared='"+openid+"' and state =1))", null);
  1353. // List<GroupProVO> groupsPro =new ArrayList<>();
  1354. // for(int i=0;i<groups.size();i++) {
  1355. // GroupVO vo = groups.get(i);
  1356. // GroupProVO voPro =new GroupProVO();
  1357. // voPro.setGroup(vo);
  1358. // int total =0;
  1359. // int online =0;
  1360. // int warn =0;
  1361. // JSONArray devListArray =JSONArray.parseArray(vo.getDev_list());
  1362. // if(devListArray!=null && devListArray.size()>0) {
  1363. // total =devListArray.size();
  1364. // for(int j=0;j<devListArray.size();j++) {
  1365. // DevVO devVO =baseDAO.queryByKey(DevVO.class, "dev_id", devListArray.getString(j));
  1366. // if(devVO.getOnline() == 1) {
  1367. // online++;
  1368. // }
  1369. // if(devVO.getDev_warn()!=null && devVO.getDev_warn() ==1) {
  1370. // warn++;
  1371. // }
  1372. // }
  1373. // }
  1374. // voPro.setTotal(total);
  1375. // voPro.setOnline(online);
  1376. // voPro.setWarn(warn);
  1377. // groupsPro.add(voPro);
  1378. // }
  1379. // r.data.put("groups", groupsPro);
  1380. // return r;
  1381. // }
  1382. // 群组设备列表
  1383. // @GetMapping("/groupDevList")
  1384. // public R groupDevList(String group_uuid) {
  1385. // R r =JSONUtil.getSuccessMsg(null);
  1386. // List<GroupVO> groups = baseDAO.queryAllByCondition(GroupVO.class, " and group_uuid ='"+group_uuid+"' ", null);
  1387. // if(groups.size()>0) {
  1388. // GroupVO vo =groups.get(0);
  1389. // JSONArray devListArray =JSONArray.parseArray(vo.getDev_list());
  1390. // List<DevVO> dev_list =new ArrayList<>();
  1391. // if(devListArray!=null && devListArray.size()>0) {
  1392. // for(int i=0;i<devListArray.size();i++) {
  1393. // DevVO devVO =baseDAO.queryByKey(DevVO.class, "dev_id", devListArray.getString(i));
  1394. // dev_list.add(devVO);
  1395. // }
  1396. // }
  1397. // r.data.put("dev_list", dev_list);
  1398. // }
  1399. // return r;
  1400. // }
  1401. // 添加群组设备
  1402. // @GetMapping("/addGroupDev")
  1403. // public R addGroupDev(String dev_id,String group_uuid) {
  1404. // R r =JSONUtil.getSuccessMsg(null);
  1405. // List<GroupVO> groups = baseDAO.queryAllByCondition(GroupVO.class, " and group_uuid ='"+group_uuid+"' ", null);
  1406. // if(groups.size()>0) {
  1407. // GroupVO vo =groups.get(0);
  1408. // String jsonStr =vo.getDev_list();
  1409. // if(StringUtils.isEmpty(jsonStr)) {
  1410. // StringBuffer sql = new StringBuffer("update dev_group set dev_list =JSON_ARRAY('"+dev_id+"') where delete_tag =0 and group_uuid='"+group_uuid+"'");
  1411. // baseDAO.updateSQL(sql.toString());
  1412. // }
  1413. // else {
  1414. // JSONArray jsonArray =JSONArray.parseArray(jsonStr);
  1415. // jsonArray.add(dev_id);
  1416. // StringBuffer sql = new StringBuffer("update dev_group set dev_list =JSON_ARRAY(");
  1417. // for(int i=0;i<jsonArray.size();i++) {
  1418. // sql.append("'"+jsonArray.getString(i)+"',");
  1419. // }
  1420. // sql.setLength(sql.length() - 1);
  1421. // sql.append(") where delete_tag =0 and group_uuid='"+group_uuid+"' ");
  1422. // baseDAO.updateSQL(sql.toString());
  1423. // }
  1424. // }
  1425. // return r;
  1426. // }
  1427. // 删除群组设备
  1428. // @GetMapping("/removeGroupDev")
  1429. // public R removeGroupDev(String dev_id,String group_uuid) {
  1430. // R r =JSONUtil.getSuccessMsg(null);
  1431. // List<GroupVO> groups = baseDAO.queryAllByCondition(GroupVO.class, " and group_uuid ='"+group_uuid+"' ", null);
  1432. // if(groups.size()>0) {
  1433. // GroupVO vo =groups.get(0);
  1434. // String jsonStr =vo.getDev_list();
  1435. // // 原数组
  1436. // JSONArray jsonArray =JSONArray.parseArray(jsonStr);
  1437. // // 删除指定元素后的列表
  1438. // JSONArray updatedArray = new JSONArray();
  1439. // for(int i=0;i<jsonArray.size();i++) {
  1440. // if (!jsonArray.getString(i).equals(dev_id)) {
  1441. // updatedArray.add(jsonArray.getString(i));
  1442. // }
  1443. // }
  1444. // StringBuffer sql = new StringBuffer("update dev_group set dev_list =JSON_ARRAY(");
  1445. //
  1446. // // 列表不为空
  1447. // if(updatedArray.size()>0) {
  1448. // for(int i=0;i<updatedArray.size();i++) {
  1449. // sql.append("'"+updatedArray.getString(i)+"',");
  1450. // }
  1451. // sql.setLength(sql.length() - 1);
  1452. // }
  1453. // sql.append(") where delete_tag =0 and group_uuid='"+group_uuid+"' ");
  1454. // baseDAO.updateSQL(sql.toString());
  1455. // }
  1456. // return r;
  1457. // }
  1458. // 群组列表
  1459. @GetMapping("/groupList")
  1460. @ApiOperation(value = "群组列表")
  1461. public R groupList(String openid) {
  1462. R r = JSONUtil.getSuccessMsg(null);
  1463. List<GroupVO> groups = baseDAO.queryAllByCondition(GroupVO.class, " and (user_openid='" + openid + "' or group_uuid in (select group_uuid"
  1464. + " from group_share where delete_tag =0 and shared='" + openid + "' and state =1))", null);
  1465. List<GroupProVO> groupsPro = new ArrayList<>();
  1466. for (int i = 0; i < groups.size(); i++) {
  1467. GroupVO vo = groups.get(i);
  1468. GroupProVO voPro = new GroupProVO();
  1469. voPro.setGroup(vo);
  1470. int total = 0;
  1471. int online = 0;
  1472. int warn = 0;
  1473. List<GroupDevMapVO> maps = baseDAO.queryAllByCondition(GroupDevMapVO.class, " and group_uuid ='" + vo.getGroup_uuid() + "' and delete_tag =0 ", null);
  1474. for (int j = 0; j < maps.size(); j++) {
  1475. GroupDevMapVO mapVO = maps.get(j);
  1476. DevVO devVO = baseDAO.queryByKey(DevVO.class, "dev_id", mapVO.getDev_id());
  1477. // 设备存在且未删除
  1478. if (devVO != null && devVO.getDelete_tag() == 0) {
  1479. total++;
  1480. if (devVO.getOnline() == 1) {
  1481. online++;
  1482. }
  1483. if (devVO.getDev_warn() != null && devVO.getDev_warn() == 1) {
  1484. warn++;
  1485. }
  1486. }
  1487. }
  1488. voPro.setTotal(total);
  1489. voPro.setOnline(online);
  1490. voPro.setWarn(warn);
  1491. groupsPro.add(voPro);
  1492. }
  1493. r.data.put("groups", groupsPro);
  1494. return r;
  1495. }
  1496. // 群组设备列表
  1497. @GetMapping("/groupDevList")
  1498. @ApiOperation(value = "群组设备列表")
  1499. public R groupDevList(String group_uuid) {
  1500. R r = JSONUtil.getSuccessMsg(null);
  1501. List<GroupDevMapVO> maps = baseDAO.queryAllByCondition(GroupDevMapVO.class, " and group_uuid ='" + group_uuid + "' and delete_tag =0 ", null);
  1502. // 获取群组设备列表
  1503. List<DevVO> dev_list = new ArrayList<>();
  1504. for (int i = 0; i < maps.size(); i++) {
  1505. GroupDevMapVO mapVO = maps.get(i);
  1506. DevVO devVO = baseDAO.queryByKey(DevVO.class, "dev_id", mapVO.getDev_id());
  1507. // 设备存在且未删除
  1508. if (devVO != null && devVO.getDelete_tag() == 0) {
  1509. dev_list.add(devVO);
  1510. }
  1511. }
  1512. // 获取群组基本信息
  1513. GroupVO group = baseDAO.queryByKey(GroupVO.class, "group_uuid", group_uuid);
  1514. r.data.put("dev_list", dev_list);
  1515. r.data.put("group", group);
  1516. return r;
  1517. }
  1518. // 添加群组设备
  1519. @GetMapping("/addGroupDev")
  1520. @ApiOperation(value = "添加群组设备")
  1521. public R addGroupDev(String dev_id, String group_uuid) {
  1522. R r = JSONUtil.getSuccessMsg(null);
  1523. GroupVO groupVO = baseDAO.queryByKey(GroupVO.class, "group_uuid", group_uuid);
  1524. DevVO devVO = baseDAO.queryByKey(DevVO.class, "dev_id", dev_id);
  1525. if (groupVO != null && devVO != null) {
  1526. List<GroupDevMapVO> maps = baseDAO.queryAllByConditionNocare(GroupDevMapVO.class, " and dev_id='" + dev_id + "' and group_uuid ='" + group_uuid + "' ", null);
  1527. Log.info(String.valueOf(maps.size()));
  1528. if (maps.size() > 0) {
  1529. GroupDevMapVO vo = maps.get(0);
  1530. if (vo.getDelete_tag() == 1) {
  1531. baseDAO.updateSQL("update group_dev_map set delete_tag =0 where dev_id='" + dev_id + "' and group_uuid ='" + group_uuid + "' ");
  1532. return r;
  1533. }
  1534. r = JSONUtil.getErrorMsg("请勿重复添加同一设备");
  1535. return r;
  1536. }
  1537. GroupDevMapVO mapVO = new GroupDevMapVO();
  1538. mapVO.setDev_group_index(groupVO.getId());
  1539. mapVO.setGroup_uuid(group_uuid);
  1540. mapVO.setDev_info_index(devVO.getId());
  1541. mapVO.setDev_id(dev_id);
  1542. mapVO.setDelete_tag(0);
  1543. baseDAO.insertAll(mapVO);
  1544. } else {
  1545. r = JSONUtil.getErrorMsg("数据出现错误,请重新进入小程序");
  1546. }
  1547. return r;
  1548. }
  1549. // 删除群组设备
  1550. @GetMapping("/removeGroupDev")
  1551. @ApiOperation(value = "删除群组设备")
  1552. public R removeGroupDev(String dev_id, String group_uuid) {
  1553. R r = JSONUtil.getSuccessMsg(null);
  1554. List<GroupDevMapVO> maps = baseDAO.queryAllByCondition(GroupDevMapVO.class, " and group_uuid ='" + group_uuid + "' and dev_id ='" + dev_id + "' and "
  1555. + "delete_tag =0", null);
  1556. if (maps.size() > 0) {
  1557. baseDAO.updateSQL("update group_dev_map set delete_tag =1 where group_uuid ='" + group_uuid + "' and dev_id ='" + dev_id + "' ");
  1558. } else {
  1559. r = JSONUtil.getErrorMsg("删除群组设备失败,请重新进入小程序");
  1560. }
  1561. return r;
  1562. }
  1563. /**
  1564. * 通过链接分享群组
  1565. *
  1566. * @param vo
  1567. * @return
  1568. */
  1569. @GetMapping("/groupShare")
  1570. @ApiOperation(value = "通过链接分享群组")
  1571. public R groupShare(GroupShareVO groupShare) {
  1572. R r = JSONUtil.getSuccessMsg(null);
  1573. baseDAO.insertAll(groupShare);
  1574. return r;
  1575. }
  1576. /**
  1577. * 群组分享信息确认
  1578. *
  1579. * @param uuid
  1580. * @return
  1581. */
  1582. @GetMapping("/groupShareConfirm")
  1583. @ApiOperation(value = "群组分享信息确认")
  1584. public R groupShareConfirm(String uuid, String shared, String shared_phone) {
  1585. R r = JSONUtil.getSuccessMsg(null);
  1586. GroupShareVO vo = baseDAO.queryByKey(GroupShareVO.class, "uuid", uuid);
  1587. if (vo != null) {
  1588. if (vo.getState() == 0) {
  1589. vo.setState(3);
  1590. baseDAO.updateSQL("update group_share set state =3,shared='" + shared + "',shared_phone='" + shared_phone + "' where uuid='" + uuid + "' and delete_tag =0 ");
  1591. }
  1592. r.data.put("groupShare", vo);
  1593. } else {
  1594. r = JSONUtil.getErrorMsg("分享已过期");
  1595. }
  1596. return r;
  1597. }
  1598. /**
  1599. * 群组分享事件处理
  1600. *
  1601. * @param uuid
  1602. * @return
  1603. */
  1604. @GetMapping("/groupSharePro")
  1605. @ApiOperation(value = "群组分享事件处理")
  1606. public R groupSharePro(String uuid, int state) {
  1607. R r = JSONUtil.getSuccessMsg(null);
  1608. GroupShareVO vo = baseDAO.queryByKey(GroupShareVO.class, "uuid", uuid);
  1609. if (vo != null) {
  1610. vo.setState(state);
  1611. baseDAO.updateSQL("update group_share set state =" + state + " where uuid='" + uuid + "' and delete_tag =0 ");
  1612. r.data.put("groupShare", vo);
  1613. }
  1614. return r;
  1615. }
  1616. /**
  1617. * 生成uuid
  1618. *
  1619. * @return
  1620. */
  1621. @GetMapping("/generateUUID")
  1622. @ApiOperation(value = "生成uuid")
  1623. public R generateUUID() {
  1624. R r = JSONUtil.getSuccessMsg(null);
  1625. String uuid = UUID.randomUUID().toString();
  1626. r.data.put("uuid", uuid);
  1627. return r;
  1628. }
  1629. /**
  1630. * 用户注销
  1631. *
  1632. * @param openid
  1633. * @return
  1634. */
  1635. @GetMapping("userLogout")
  1636. @ApiOperation(value = "用户注销")
  1637. public R userLogout(String openid) {
  1638. R r = JSONUtil.getSuccessMsg(null);
  1639. // user_info
  1640. baseDAO.updateSQL("update user_info set delete_tag =1 where openid ='" + openid + "' ");
  1641. // dev_share
  1642. baseDAO.updateSQL("update dev_share set delete_tag =1 where sharer ='" + openid + "' or shared ='" + openid + "' ");
  1643. // dev_info
  1644. baseDAO.updateSQL("update dev_info set delete_tag =1 where user_openid ='" + openid + "' ");
  1645. // dev_group
  1646. baseDAO.updateSQL("update dev_group set delete_tag =1 where user_openid ='" + openid + "' ");
  1647. // group_share
  1648. baseDAO.updateSQL("update group_share set delete_tag =1 where sharer ='" + openid + "' or shared ='" + openid + "' ");
  1649. return r;
  1650. }
  1651. // 获取设备所属群组
  1652. @GetMapping("getDevGroup")
  1653. @ApiOperation(value = "获取设备所属群组")
  1654. public R getDevGroup(String dev_id) {
  1655. R r = JSONUtil.getSuccessMsg(null);
  1656. baseDAO.queryBySQL("");
  1657. return r;
  1658. }
  1659. // 上传户型图
  1660. @PostMapping("/uploadMap")
  1661. @ApiOperation(value = "上传户型图")
  1662. public R uploadMap(@RequestParam("file") MultipartFile file,
  1663. @RequestParam String group_uuid) throws IllegalStateException,
  1664. IOException {
  1665. // 校验文件非空
  1666. if (file.isEmpty()) {
  1667. return JSONUtil.getErrorMsg("文件为空");
  1668. }
  1669. // 校验文件类型
  1670. String contentType = file.getContentType();
  1671. if (contentType == null || (!contentType.equalsIgnoreCase("image/png") && !contentType.equalsIgnoreCase("image/jpeg"))) {
  1672. return JSONUtil.getErrorMsg("仅支持PNG或JPG 格式");
  1673. }
  1674. // 校验文件头
  1675. byte[] fileHeader = new byte[8];
  1676. try (InputStream is = file.getInputStream()) {
  1677. int readBytes = is.read(fileHeader);
  1678. if (readBytes < 8) {
  1679. return JSONUtil.getErrorMsg("文件格式不完整");
  1680. }
  1681. }
  1682. boolean isPng = ImageUtil.checkPngMagicNumber(fileHeader);
  1683. boolean isJpeg = ImageUtil.checkJpegMagicNumber(fileHeader);
  1684. if (!isPng && !isJpeg) {
  1685. return JSONUtil.getErrorMsg("文件实际格式与声明不符,仅支持 PNG/JPG");
  1686. }
  1687. // 生成安全路径
  1688. String dirPath = FileUploadController.getFilePath() + "map/" + group_uuid + "/";
  1689. File dir = new File(dirPath);
  1690. if (!dir.exists() && !dir.mkdirs()) {
  1691. Log.error("目录创建失败: " + dirPath);
  1692. return JSONUtil.getErrorMsg("服务器错误");
  1693. }
  1694. // 删除旧文件
  1695. File[] existingFiles = dir.listFiles();
  1696. if (existingFiles != null) {
  1697. for (File existingFile : existingFiles) {
  1698. if (existingFile.isFile()) {
  1699. if (!existingFile.delete()) {
  1700. Log.error("旧文件无法删除,上传中断");
  1701. return JSONUtil.getErrorMsg("旧文件无法删除,上传中断");
  1702. }
  1703. }
  1704. }
  1705. }
  1706. // 根据文件类型生成正确扩展名
  1707. String extension = isPng ? ".png" : ".jpg";
  1708. String fileName = System.currentTimeMillis() + extension;
  1709. // 上传服务器
  1710. file.transferTo(new File(dirPath, fileName));
  1711. Log.info("上传成功");
  1712. // 查询
  1713. FloorPlanVO vo = baseDAO.queryByKey(FloorPlanVO.class, "group_uuid", group_uuid);
  1714. // 上传数据库
  1715. String floorplan_addr = "map/" + group_uuid + "/" + fileName;
  1716. if (vo != null) {
  1717. StringBuffer buffer = new StringBuffer("update group_floorplan set ");
  1718. if (vo.getDelete_tag() == 1) {
  1719. buffer.append("delete_tag =0,");
  1720. }
  1721. buffer.append("floorplan_addr ='" + floorplan_addr + "',update_time ='" + new Timestamp(System.currentTimeMillis())
  1722. + "' where group_uuid ='" + group_uuid + "' ");
  1723. baseDAO.updateSQL(buffer.toString());
  1724. } else {
  1725. vo = new FloorPlanVO();
  1726. vo.setCreate_time(new Timestamp(System.currentTimeMillis()));
  1727. vo.setDelete_tag(0);
  1728. vo.setGroup_uuid(group_uuid);
  1729. vo.setFloorplan_addr(floorplan_addr);
  1730. baseDAO.insertAll(vo);
  1731. }
  1732. return JSONUtil.getSuccessMsg(null);
  1733. }
  1734. // 获取户型图(URL地址)
  1735. @GetMapping("/getFloorPlan")
  1736. @ApiOperation(value = "获取户型图")
  1737. public R getFloorPlan(String group_uuid) {
  1738. String dirPath = FileUploadController.getFilePath() + "map/" + group_uuid + "/";
  1739. File dir = new File(dirPath);
  1740. File[] existingFiles = dir.listFiles();
  1741. if (existingFiles != null) {
  1742. if (existingFiles.length > 1) {
  1743. // 存在多张户型图
  1744. return JSONUtil.getErrorMsg("存在多张户型图");
  1745. } else if (existingFiles.length == 1) {
  1746. // 存在且只有一张户型图
  1747. File existingFile = existingFiles[0];
  1748. // URL拼接
  1749. FloorPlanVO vo = baseDAO.queryByKey(FloorPlanVO.class, "group_uuid", group_uuid);
  1750. StringBuffer fileURL = new StringBuffer(Environment.COMMON_FILE_UPLOAD_PATH);
  1751. if (vo != null && vo.getDelete_tag() == 0) {
  1752. fileURL.append(vo.getFloorplan_addr());
  1753. } else {
  1754. fileURL.append("map/" + group_uuid + "/" + existingFile.getName());
  1755. }
  1756. // 返回成功信息,包含户型图的URL
  1757. R r = JSONUtil.getSuccessMsg("户型图获取成功");
  1758. r.customData.put("url", fileURL.toString());
  1759. return r;
  1760. }
  1761. }
  1762. // 无户型图
  1763. return JSONUtil.getErrorMsg("户型图未配置");
  1764. }
  1765. private final static String TOKEN = "lnServer";
  1766. /**
  1767. * 检测用户是否拥有设备
  1768. *
  1769. * @param time
  1770. * @param dev_id
  1771. * @return
  1772. */
  1773. @GetMapping("/getWcTimes")
  1774. @ApiOperation(value = "查询前一天上厕所的次数")
  1775. public R getWcTimes(String dev_id, String time) {
  1776. R r = JSONUtil.getSuccessMsg(null);
  1777. LocalDate inputDate = LocalDate.parse(time);
  1778. LocalDate previousDate = inputDate.minusDays(1);
  1779. String previousDateStr = previousDate.toString();
  1780. // 判断查询结果并返回
  1781. List<AlarmEvent> stayTimes = null;
  1782. try {
  1783. stayTimes = jdbcTemplate.query(
  1784. "SELECT * FROM alarm_event WHERE dev_id = ? AND DATE(create_time) = ?",
  1785. new Object[]{dev_id, previousDateStr},
  1786. new BeanPropertyRowMapper<>(AlarmEvent.class)
  1787. );
  1788. } catch (Exception e) {
  1789. e.printStackTrace();
  1790. }
  1791. if (Objects.nonNull(stayTimes) && stayTimes.size() > 0) {
  1792. r.data.put("stayTimes", stayTimes);
  1793. r.data.put("count", stayTimes.size());
  1794. } else {
  1795. r.data.put("stayTimes", null);
  1796. r.data.put("count", 0);
  1797. }
  1798. return r;
  1799. }
  1800. //公众号模块
  1801. @GetMapping("/getAccessTokenTwo")
  1802. @ApiOperation(value = "获取公众号token")
  1803. public R getAccessTokenTwo() {
  1804. R r = JSONUtil.getSuccessMsg(null);
  1805. // 发送模板消息
  1806. wxSendMessage.queryAccessToken("devId", "测试设备", "17356519496", "oWlo-6iXL0pQeYWZxEpwB8knv6D8", "test");
  1807. return r;
  1808. }
  1809. @GetMapping("/serverCheck")
  1810. @ApiOperation(value = "公众号发信息接口")
  1811. public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
  1812. String signature = request.getParameter("signature");
  1813. String timestamp = request.getParameter("timestamp");
  1814. String nonce = request.getParameter("nonce");
  1815. String echostr = request.getParameter("echostr");
  1816. String signatureCheck = getSHA1(TOKEN, timestamp, nonce);
  1817. if (signatureCheck != null && signatureCheck.equals(signature)) {
  1818. PrintWriter out = response.getWriter();
  1819. out.print(echostr);
  1820. out.flush();
  1821. out.close();
  1822. }
  1823. }
  1824. @PostMapping("/addOneDevice")
  1825. @ApiOperation(value = "单个添加设备")
  1826. public R addOneDevice(String dev_id, String dev_type, String software){
  1827. //比较dev_id是否在dev_info中存在
  1828. DevVO devVO = baseDAO.queryByKey(DevVO.class, "dev_id", dev_id);
  1829. if (devVO != null) {
  1830. return JSONUtil.getErrorMsg("设备已存在");
  1831. }
  1832. //拿到三个入参直接 插入在数据库dev_info表创建一条新数据,插入成功后返回成功信息
  1833. DevVO deviceVO = new DevVO();
  1834. deviceVO.setDev_id(dev_id);
  1835. deviceVO.setDev_type(dev_type);
  1836. deviceVO.setSoftware(software);
  1837. baseDAO.insertAll(deviceVO);
  1838. return JSONUtil.getSuccessMsg("添加成功");
  1839. }
  1840. public String getSHA1(String token, String timestamp, String nonce) {
  1841. try {
  1842. String[] array = new String[]{token, timestamp, nonce};
  1843. Arrays.sort(array);
  1844. StringBuilder sb = new StringBuilder();
  1845. for (String s : array) {
  1846. sb.append(s);
  1847. }
  1848. MessageDigest md = MessageDigest.getInstance("SHA-1");
  1849. md.update(sb.toString().getBytes());
  1850. byte[] digest = md.digest();
  1851. StringBuilder hexstr = new StringBuilder();
  1852. for (byte b : digest) {
  1853. String shaHex = Integer.toHexString(b & 0xFF);
  1854. if (shaHex.length() < 2) {
  1855. hexstr.append(0);
  1856. }
  1857. hexstr.append(shaHex);
  1858. }
  1859. return hexstr.toString();
  1860. } catch (Exception e) {
  1861. e.printStackTrace();
  1862. return null;
  1863. }
  1864. }
  1865. }