ToolUtils.java 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349
  1. package com.welampiot.utils;
  2. import com.alibaba.druid.support.json.JSONUtils;
  3. import com.alibaba.fastjson.JSON;
  4. import com.alibaba.fastjson.JSONArray;
  5. import com.alibaba.fastjson.JSONObject;
  6. import com.welampiot.common.BaseResult;
  7. import com.welampiot.common.DevInfoEnum;
  8. import com.welampiot.common.InterfaceResultEnum;
  9. import com.welampiot.common.LampControlTypeEnum;
  10. import com.welampiot.configuration.MqttConfig;
  11. import com.welampiot.configuration.PlcMqttConfig;
  12. import com.welampiot.dto.*;
  13. import com.welampiot.handle.MqttHandler;
  14. import com.welampiot.service.*;
  15. import com.welampiot.vo.DevEnumVO;
  16. import com.welampiot.vo.LampPoleVO;
  17. import org.apache.commons.httpclient.HttpClient;
  18. import org.apache.commons.httpclient.methods.PostMethod;
  19. import org.apache.poi.ss.formula.functions.T;
  20. import org.eclipse.paho.client.mqttv3.MqttClient;
  21. import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
  22. import org.eclipse.paho.client.mqttv3.MqttMessage;
  23. import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
  24. import org.gavaghan.geodesy.Ellipsoid;
  25. import org.gavaghan.geodesy.GeodeticCalculator;
  26. import org.gavaghan.geodesy.GeodeticCurve;
  27. import org.gavaghan.geodesy.GlobalCoordinates;
  28. import org.slf4j.Logger;
  29. import org.slf4j.LoggerFactory;
  30. import org.springframework.beans.factory.annotation.Autowired;
  31. import org.springframework.stereotype.Component;
  32. import javax.servlet.http.HttpServletRequest;
  33. import java.io.*;
  34. import java.lang.reflect.Field;
  35. import java.net.*;
  36. import java.nio.charset.StandardCharsets;
  37. import java.text.DecimalFormat;
  38. import java.text.SimpleDateFormat;
  39. import java.util.*;
  40. import java.util.regex.Pattern;
  41. import java.util.stream.Collectors;
  42. import java.util.zip.CRC32;
  43. @Component
  44. public class ToolUtils {
  45. //http的编码
  46. public enum ContentTypeEnum {
  47. CONTENT_TYPE_JSON("application/json;charset=utf-8"),
  48. CONTENT_TYPE_FORM("application/x-www-form-urlencoded;charset=utf-8")
  49. ;
  50. private String contentType;
  51. ContentTypeEnum(String contentType) {
  52. this.contentType = contentType;
  53. }
  54. }
  55. private UserDTO user;
  56. @Autowired
  57. private UserService userService;
  58. @Autowired
  59. private SectionService sectionService;
  60. @Autowired
  61. private GlobalLocationService globalLocationService;
  62. @Autowired
  63. private MqttConfig mqttConfig;
  64. @Autowired
  65. private MqttHandler mqttHandler;
  66. @Autowired
  67. private LampPoleService lampPoleService;
  68. @Autowired
  69. private PlcMqttConfig plcMqttConfig;
  70. private static final String PATTERN = "^(?=.*[0-9])(?=.*[a-zA-Z]).{8,20}$";
  71. private static final String PATTERN_PHONE = "^1[3-9]\\d{9}$";
  72. private static final String PATTERN_EMAIL = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$";
  73. @Autowired
  74. private IpInfoService ipInfoService;
  75. @Autowired
  76. private OperationLogService operationLogService;
  77. /**
  78. * 获取用户所有路段 id
  79. * @param request
  80. * @return 如果返回列表为空,表示超管获取到全部路段信息,此时不需要做路段筛选
  81. */
  82. public List getSectionList(HttpServletRequest request){
  83. String username = request.getParameter("username");
  84. ArrayList<Object> sectionList = new ArrayList<>();
  85. if (username == null || username.toString().length() == 0) {
  86. sectionList.add(0);
  87. return sectionList;
  88. }
  89. user = userService.findUserByUserName(username);
  90. if (user == null) {
  91. sectionList.add(0);
  92. return sectionList;
  93. }
  94. String provinceid = request.getParameter("provinceid");
  95. provinceid = provinceid == null || provinceid.equals("0") ? request.getParameter("provinceId") : provinceid;
  96. String cityid = request.getParameter("cityid");
  97. cityid = cityid == null || cityid.equals("0") ? request.getParameter("cityId") : cityid;
  98. String areaid = request.getParameter("areaid");
  99. areaid = areaid == null || areaid.equals("0") ? request.getParameter("areaId") : areaid;
  100. String sectionid = request.getParameter("sectionid");
  101. sectionid = sectionid == null || sectionid.equals("0") ? request.getParameter("sectionId") : sectionid;
  102. if (sectionid != null && sectionid.length() != 0 && !sectionid.equals("0")){
  103. sectionList.add(sectionid);
  104. return sectionList;
  105. }
  106. String zone = user.getZoneList();
  107. int role = user.getRole();
  108. List<SectionDTO> maps;
  109. List<GlobalLocationDTO> globalLocationList;
  110. ArrayList areaList = new ArrayList<>();
  111. if ((cityid != null && !cityid.equals("0")) || (provinceid != null && !provinceid.equals("0")) || (areaid != null && !areaid.equals("0"))){
  112. if (areaid == null || areaid.equals("0")){
  113. ArrayList cityList = new ArrayList<>();
  114. if (cityid == null || cityid.equals("0")){
  115. globalLocationList = globalLocationService.getListByPid(Integer.valueOf(provinceid));
  116. if (globalLocationList.isEmpty()){
  117. cityid = provinceid;
  118. }else {
  119. for (GlobalLocationDTO m :globalLocationList) {
  120. cityList.add(m.getId());
  121. }
  122. }
  123. }
  124. if (cityList.isEmpty()){
  125. globalLocationList = globalLocationService.getListByPid(Integer.valueOf(cityid));
  126. }else {
  127. globalLocationList = globalLocationService.getListByPidList(cityList);
  128. }
  129. if (globalLocationList.isEmpty()){
  130. areaid = cityid;
  131. }else {
  132. for (GlobalLocationDTO m :globalLocationList) {
  133. areaList.add(m.getId());
  134. }
  135. }
  136. }
  137. }
  138. if ((areaid == null || areaid.length() == 0 || areaid.equals("0")) && areaList.isEmpty()){
  139. if (role != 1) {
  140. return Arrays.asList(zone.split(","));
  141. }else {
  142. return new ArrayList<>();
  143. }
  144. }else {
  145. if (areaid == null || areaid.equals("0")){
  146. maps = sectionService.getListByPidList(areaList);
  147. if (role != 1){
  148. return Arrays.asList(zone.split(","));
  149. }
  150. }else {
  151. System.out.println(areaid);
  152. int areaid2 = Integer.valueOf(areaid);
  153. maps = sectionService.getListByPid(areaid2);
  154. }
  155. }
  156. for (SectionDTO map:maps) {
  157. sectionList.add(map.getId());
  158. }
  159. if (sectionList.isEmpty()) sectionList.add("0");
  160. return sectionList;
  161. }
  162. public UserDTO getUser() {
  163. return user;
  164. }
  165. public UserDTO getUser(HttpServletRequest request) {
  166. String username = request.getParameter("username");
  167. ArrayList<Object> sectionList = new ArrayList<>();
  168. if (user == null) {
  169. user = userService.findUserByUserName(username);
  170. }
  171. return user;
  172. }
  173. /**
  174. * 返回接口信息,不带数据
  175. * @param code 状态码
  176. * @param version 语言类型 0 中文,1 英文,2 俄语
  177. * @return
  178. */
  179. public BaseResult response(InterfaceResultEnum resultEnum,Integer version){
  180. String msg;
  181. String code = resultEnum.getCode();
  182. if (version == 0){
  183. msg = resultEnum.getMsgCn();} else if (version == 1) {
  184. msg = resultEnum.getMsgEn();
  185. }else {
  186. msg = resultEnum.getMsgRu();
  187. }
  188. BaseResult<Object> objectBaseResult = new BaseResult<>(code, msg, new Object());
  189. Logger paramLog = LoggerFactory.getLogger("param_log");
  190. paramLog.info("reponse param== "+ JSON.toJSONString(objectBaseResult));
  191. return objectBaseResult;
  192. }
  193. /**
  194. * 返回接口信息,带数据
  195. * @param code 状态码
  196. * @param version 语言类型 0 中文,1 英文,2 俄语
  197. * @param obj 返回数据内容
  198. * @return
  199. */
  200. public BaseResult response(InterfaceResultEnum resultEnum,Integer version,Object obj){
  201. String msg;
  202. String code = resultEnum.getCode();
  203. if (version == 0){
  204. msg = resultEnum.getMsgCn();
  205. } else if (version == 1) {
  206. msg = resultEnum.getMsgEn();
  207. }else {
  208. msg = resultEnum.getMsgRu();
  209. }
  210. BaseResult<Object> objectBaseResult = new BaseResult<>(code, msg, obj);
  211. Logger paramLog = LoggerFactory.getLogger("param_log");
  212. paramLog.info("reponse param== "+ JSON.toJSONString(objectBaseResult));
  213. return objectBaseResult;
  214. }
  215. /**
  216. * 发送mqtt指令
  217. * @param sendTopic 发送的topic
  218. * @param cmdInfo 发送的指令内容
  219. * @param resTopic 接收指令返回的topic
  220. * @return
  221. */
  222. public String sendMqttCmd(String sendTopic,Object cmdInfo,String resTopic){
  223. MqttClient client;
  224. String res = "";
  225. try {
  226. try {
  227. client=new MqttClient(mqttConfig.getUrl(),mqttConfig.getClientId()+"_"+(new Date()).getTime(),new MemoryPersistence());
  228. MqttConnectOptions options=new MqttConnectOptions();
  229. options.setCleanSession(true);
  230. options.setUserName(mqttConfig.getUsername());
  231. options.setPassword(mqttConfig.getPassword().toCharArray());
  232. options.setConnectionTimeout(mqttConfig.getTimeout());
  233. options.setKeepAliveInterval(mqttConfig.getKeepalive());
  234. mqttHandler.setTopic(resTopic);
  235. // 设置回调
  236. client.setCallback(mqttHandler);
  237. // 建立连接
  238. client.connect(options);
  239. // MqttCustomerClient.setClient(client);
  240. client.subscribe(resTopic);
  241. // 消息发布所需参数
  242. MqttMessage message;
  243. if (cmdInfo instanceof String){
  244. message = new MqttMessage(((String) cmdInfo).getBytes());
  245. }else {
  246. message = new MqttMessage((byte[]) cmdInfo);
  247. }
  248. message.setQos(0);
  249. client.publish(sendTopic, message);
  250. int in = 0;
  251. while (true){
  252. Thread.sleep(1000);
  253. if (mqttHandler.getRes() != null && mqttHandler.getRes().length() != 0){
  254. res = mqttHandler.getRes();
  255. break;
  256. }
  257. in ++;
  258. if (in > 30) break;
  259. }
  260. client.disconnect();
  261. }catch (Exception e){
  262. e.printStackTrace();
  263. }
  264. }catch (Exception e){
  265. e.printStackTrace();
  266. }
  267. return res;
  268. }
  269. /**
  270. * 发送mqtt指令
  271. * @param sendTopic 发送的topic
  272. * @param cmdInfo 发送的指令内容
  273. * @param resTopic 接收指令返回的topic
  274. * @param timeout 指令超时时间
  275. * @return
  276. */
  277. public String sendMqttCmd(String sendTopic,Object cmdInfo,String resTopic,Integer timeout){
  278. MqttClient client;
  279. String res = "";
  280. try {
  281. try {
  282. client=new MqttClient(mqttConfig.getUrl(),mqttConfig.getClientId()+"_"+(new Date()).getTime(),new MemoryPersistence());
  283. MqttConnectOptions options=new MqttConnectOptions();
  284. options.setCleanSession(true);
  285. options.setUserName(mqttConfig.getUsername());
  286. options.setPassword(mqttConfig.getPassword().toCharArray());
  287. options.setConnectionTimeout(mqttConfig.getTimeout());
  288. options.setKeepAliveInterval(mqttConfig.getKeepalive());
  289. mqttHandler.setTopic(resTopic);
  290. // 设置回调
  291. client.setCallback(mqttHandler);
  292. // 建立连接
  293. client.connect(options);
  294. // MqttCustomerClient.setClient(client);
  295. client.subscribe(resTopic);
  296. // 消息发布所需参数
  297. MqttMessage message;
  298. if (cmdInfo instanceof String){
  299. message = new MqttMessage(((String) cmdInfo).getBytes());
  300. }else {
  301. message = new MqttMessage((byte[]) cmdInfo);
  302. }
  303. message.setQos(0);
  304. client.publish(sendTopic, message);
  305. int in = 0;
  306. if (timeout > 0){
  307. while (true){
  308. Thread.sleep(1000);
  309. if (mqttHandler.getRes() != null && mqttHandler.getRes().length() != 0){
  310. res = mqttHandler.getRes();
  311. break;
  312. }
  313. in ++;
  314. if (in > timeout) break;
  315. }
  316. }
  317. client.disconnect();
  318. }catch (Exception e){
  319. e.printStackTrace();
  320. }
  321. }catch (Exception e){
  322. e.printStackTrace();
  323. }
  324. return res;
  325. }
  326. /**
  327. * 发送mqtt指令
  328. * @param sendTopic 发送的topic
  329. * @param cmdInfo 发送的指令内容
  330. * @param resTopic 接收指令返回的topic
  331. * @return
  332. */
  333. public String plcSendMqttCmd(String sendTopic,Object cmdInfo,String resTopic){
  334. MqttClient client;
  335. String res = "";
  336. try {
  337. try {
  338. client=new MqttClient(plcMqttConfig.getUrl(),plcMqttConfig.getClientId()+"_"+(new Date()).getTime(),new MemoryPersistence());
  339. MqttConnectOptions options=new MqttConnectOptions();
  340. options.setCleanSession(true);
  341. options.setUserName(plcMqttConfig.getUsername());
  342. options.setPassword(plcMqttConfig.getPassword().toCharArray());
  343. options.setConnectionTimeout(plcMqttConfig.getTimeout());
  344. options.setKeepAliveInterval(plcMqttConfig.getKeepalive());
  345. mqttHandler.setTopic(resTopic);
  346. // 设置回调
  347. client.setCallback(mqttHandler);
  348. // 建立连接
  349. client.connect(options);
  350. // MqttCustomerClient.setClient(client);
  351. client.subscribe(resTopic);
  352. // 消息发布所需参数
  353. MqttMessage message;
  354. if (cmdInfo instanceof String){
  355. message = new MqttMessage(((String) cmdInfo).getBytes());
  356. }else {
  357. message = new MqttMessage((byte[]) cmdInfo);
  358. }
  359. message.setQos(0);
  360. client.publish(sendTopic, message);
  361. int in = 0;
  362. while (true){
  363. Thread.sleep(1000);
  364. if (mqttHandler.getRes() != null && mqttHandler.getRes().length() != 0){
  365. res = mqttHandler.getRes();
  366. break;
  367. }
  368. in ++;
  369. if (in > 30) break;
  370. }
  371. client.disconnect();
  372. }catch (Exception e){
  373. e.printStackTrace();
  374. }
  375. }catch (Exception e){
  376. e.printStackTrace();
  377. }
  378. return res;
  379. }
  380. /**
  381. * 发送mqtt指令
  382. * @param sendTopic 发送的topic
  383. * @param cmdInfo 发送的指令内容
  384. * @param resTopic 接收指令返回的topic
  385. * @param timeout 指令超时时间
  386. * @return
  387. */
  388. public String plcSendMqttCmd(String sendTopic,String cmdInfo, String resTopic, Integer timeout){
  389. MqttClient client;
  390. String res = "";
  391. try {
  392. try {
  393. client=new MqttClient(plcMqttConfig.getUrl(),plcMqttConfig.getClientId()+"_"+(new Date()).getTime(),new MemoryPersistence());
  394. MqttConnectOptions options=new MqttConnectOptions();
  395. options.setCleanSession(true);
  396. options.setUserName(plcMqttConfig.getUsername());
  397. options.setPassword(plcMqttConfig.getPassword().toCharArray());
  398. options.setConnectionTimeout(plcMqttConfig.getTimeout());
  399. options.setKeepAliveInterval(plcMqttConfig.getKeepalive());
  400. mqttHandler.setTopic(resTopic);
  401. // 设置回调
  402. client.setCallback(mqttHandler);
  403. // 建立连接
  404. client.connect(options);
  405. // MqttCustomerClient.setClient(client);
  406. client.subscribe(resTopic);
  407. // 消息发布所需参数
  408. MqttMessage message;
  409. message = new MqttMessage(cmdInfo.getBytes());
  410. message.setQos(0);
  411. client.publish(sendTopic, message);
  412. System.out.println("==send:"+sendTopic+"====res:"+resTopic);
  413. int in = 0;
  414. if (timeout > 0){
  415. while (true){
  416. System.out.println("==d====:"+in+"====");
  417. Thread.sleep(100);
  418. if (mqttHandler.getRes() != null && mqttHandler.getRes().length() != 0){
  419. res = mqttHandler.getRes();
  420. System.out.println(res);
  421. //原来的
  422. JSONObject oldObject = JSON.parseObject(cmdInfo);
  423. String oldDataType = oldObject.getObject("dataType", String.class);
  424. // String[] oldThirdIdArr = oldObject.getObject("thirdId",String.class).split("-");
  425. // String[] oldSnArr = oldThirdIdArr[0].split(":");
  426. // String oldSn = oldSnArr[1]; //设备地址
  427. // String[] oldNumberArr = oldThirdIdArr[1].split(":");
  428. // int oldNum = Integer.parseInt(oldNumberArr[1]); //设备灯序号
  429. //解析json
  430. JSONObject jsonObject = JSON.parseObject(res);
  431. String dataType = jsonObject.getObject("dataType", String.class);
  432. // String[] thirdIdArr = jsonObject.getObject("thirdId",String.class).split("-");
  433. // String[] snArr = thirdIdArr[0].split(":");
  434. // String sn = snArr[1]; //设备地址
  435. // String[] numberArr = thirdIdArr[1].split(":");
  436. // int num = Integer.parseInt(numberArr[1]); //设备灯序号
  437. //它是字符串
  438. if (dataType.equals("lightStatus") ){ //1.读取灯信息,2.调光的
  439. //原来的
  440. String[] oldThirdIdArr = oldObject.getObject("thirdId",String.class).split("-");
  441. String[] oldSnArr = oldThirdIdArr[0].split(":");
  442. String oldSn = oldSnArr[1]; //设备地址
  443. String[] oldNumberArr = oldThirdIdArr[1].split(":");
  444. int oldNum = Integer.parseInt(oldNumberArr[1]); //设备灯序号
  445. //解析json
  446. String[] thirdIdArr = jsonObject.getObject("thirdId",String.class).split("-");
  447. String[] snArr = thirdIdArr[0].split(":");
  448. String sn = snArr[1]; //设备地址
  449. String[] numberArr = thirdIdArr[1].split(":");
  450. int num = Integer.parseInt(numberArr[1]); //设备灯序号
  451. //类型相等
  452. System.out.println("====ddd:"+oldSn+"====sn:"+sn+"====ol:"+oldNum+"==nu:"+num);
  453. if ((oldDataType.equals("lightStatus") || oldDataType.equals("adjustLightController")) && oldSn.equals(sn) && (oldNum == num)){
  454. //查看灯的信息
  455. System.out.println("====ddd:"+res);
  456. return res;
  457. }
  458. }
  459. }
  460. in ++;
  461. if (in > timeout) return null;
  462. }
  463. }
  464. client.disconnect();
  465. }catch (Exception e){
  466. System.out.println("==dd=="+e);
  467. e.printStackTrace();
  468. }
  469. }catch (Exception e){
  470. System.out.println(e);
  471. e.printStackTrace();
  472. }
  473. return null;
  474. }
  475. /**
  476. * 字节数组转16进制字符串
  477. * @param b 字节数组
  478. * @return 16进制字符串
  479. * @throws
  480. */
  481. public String bytes2HexString(byte[] b) {
  482. StringBuffer result = new StringBuffer();
  483. String hex;
  484. for (int i = 0; i < b.length; i++) {
  485. hex = Integer.toHexString(b[i] & 0xFF);
  486. if (hex.length() == 1) {
  487. hex = '0' + hex;
  488. }
  489. result.append(hex.toUpperCase());
  490. }
  491. return result.toString();
  492. }
  493. /**
  494. * 16进制字符串转字节数组
  495. * @param src 16进制字符串
  496. * @return 字节数组
  497. * @throws
  498. */
  499. public byte[] hexString2Bytes(String src) {
  500. int l = src.length() / 2;
  501. byte[] ret = new byte[l];
  502. for (int i = 0; i < l; i++) {
  503. ret[i] = (byte) Integer
  504. .valueOf(src.substring(i * 2, i * 2 + 2), 16).byteValue();
  505. }
  506. return ret;
  507. }
  508. /**
  509. * 获取CRC32校验码
  510. * @param src 16进制字符串
  511. * @return CRC32校验码
  512. */
  513. public String getCRC32ByHexString2Bytes(String src) {
  514. CRC32 crc32 = new CRC32();
  515. crc32.update(this.hexString2Bytes(src));
  516. return Integer.toHexString((int) crc32.getValue());
  517. }
  518. /**
  519. * 计算modbus CRC16校验码
  520. * @param bytes 需要计算的数据
  521. * @return
  522. */
  523. public String getCRC(byte[] bytes) {
  524. // CRC寄存器全为1
  525. int CRC = 0x0000ffff;
  526. // 多项式校验值
  527. int POLYNOMIAL = 0x0000a001;
  528. int i, j;
  529. for (i = 0; i < bytes.length; i++) {
  530. CRC ^= ((int) bytes[i] & 0x000000ff);
  531. for (j = 0; j < 8; j++) {
  532. if ((CRC & 0x00000001) != 0) {
  533. CRC >>= 1;
  534. CRC ^= POLYNOMIAL;
  535. } else {
  536. CRC >>= 1;
  537. }
  538. }
  539. }
  540. // 结果转换为16进制
  541. String result = Integer.toHexString(CRC).toUpperCase();
  542. if (result.length() != 4) {
  543. StringBuffer sb = new StringBuffer("0000");
  544. result = sb.replace(4 - result.length(), 4, result).toString();
  545. }
  546. //高位在前地位在后
  547. //return result.substring(2, 4) + " " + result.substring(0, 2);
  548. // 交换高低位,低位在前高位在后
  549. return result.substring(2, 4)+result.substring(0, 2);
  550. }
  551. public String getCRC(String cmd) {
  552. byte[] bytes = this.hexString2Bytes(cmd);
  553. // CRC寄存器全为1
  554. int CRC = 0x0000ffff;
  555. // 多项式校验值
  556. int POLYNOMIAL = 0x0000a001;
  557. int i, j;
  558. for (i = 0; i < bytes.length; i++) {
  559. CRC ^= ((int) bytes[i] & 0x000000ff);
  560. for (j = 0; j < 8; j++) {
  561. if ((CRC & 0x00000001) != 0) {
  562. CRC >>= 1;
  563. CRC ^= POLYNOMIAL;
  564. } else {
  565. CRC >>= 1;
  566. }
  567. }
  568. }
  569. // 结果转换为16进制
  570. String result = Integer.toHexString(CRC).toUpperCase();
  571. if (result.length() != 4) {
  572. StringBuffer sb = new StringBuffer("0000");
  573. result = sb.replace(4 - result.length(), 4, result).toString();
  574. }
  575. //高位在前地位在后
  576. //return result.substring(2, 4) + " " + result.substring(0, 2);
  577. // 交换高低位,低位在前高位在后
  578. return result.substring(2, 4)+result.substring(0, 2);
  579. }
  580. public Object getRequestContent(HttpServletRequest request,String key){
  581. return request.getParameter(key);
  582. }
  583. /**
  584. * 获取请求参数
  585. * @param request 请求对象
  586. * @param key 参数值
  587. * @param type 参数类型 1 int 2 string
  588. * @return
  589. */
  590. public Object getRequestContent(HttpServletRequest request,String key,Integer type){
  591. if (type == 1){ // 获取 int 数据
  592. Integer keyId = request.getParameter(key) == null || request.getParameter(key).length() == 0? 0 : Integer.parseInt(request.getParameter(key));
  593. return keyId;
  594. }else if (type == 2){
  595. String keyStr = request.getParameter(key) == null ? "" : request.getParameter(key).toString();
  596. return keyStr.trim();
  597. }
  598. return request.getParameter(key);
  599. }
  600. /**
  601. * 发送post请求
  602. * @param url 请求地址
  603. * @param paraMap 请求参数
  604. * @return
  605. */
  606. public String httpPost(String url,Map paraMap){
  607. HttpClient httpClient = new HttpClient();
  608. httpClient.getHttpConnectionManager().getParams().setSoTimeout(30000);
  609. PostMethod postMethod = new PostMethod(url);
  610. postMethod.addRequestHeader("accept", "*/*");
  611. //设置Content-Type
  612. postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  613. //添加请求参数
  614. Set set = paraMap.keySet();
  615. for (Object s : set) {
  616. postMethod.addParameter((String) s, (String) paraMap.get(s));
  617. }
  618. String result = "";
  619. try {
  620. int code = httpClient.executeMethod(postMethod);
  621. if (code == 200){
  622. result = postMethod.getResponseBodyAsString();
  623. }
  624. } catch (IOException e) {
  625. // e.printStackTrace();
  626. }
  627. return result;
  628. }
  629. /**
  630. * 发送post请求
  631. * @param url 请求地址
  632. * @param paraMap 请求参数
  633. * @param timeout 超时时间
  634. * @return
  635. */
  636. public String httpPost(String url,Map paraMap,int timeout){
  637. HttpClient httpClient = new HttpClient();
  638. httpClient.getHttpConnectionManager().getParams().setSoTimeout(timeout);
  639. PostMethod postMethod = new PostMethod(url);
  640. postMethod.addRequestHeader("accept", "*/*");
  641. //设置Content-Type
  642. postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  643. //添加请求参数
  644. Set set = paraMap.keySet();
  645. for (Object s : set) {
  646. postMethod.addParameter((String) s, (String) paraMap.get(s));
  647. }
  648. String result = "";
  649. try {
  650. int code = httpClient.executeMethod(postMethod);
  651. if (code == 200){
  652. result = postMethod.getResponseBodyAsString();
  653. }
  654. } catch (IOException e) {
  655. // e.printStackTrace();
  656. }
  657. return result;
  658. }
  659. /**
  660. * 通过id获取控制器型号名称
  661. * @param id
  662. * @return
  663. */
  664. public String getLampControlNameById(Integer id){
  665. for (LampControlTypeEnum value : LampControlTypeEnum.values()) {
  666. if (value.getId().intValue() == id.intValue()){
  667. return value.getName();
  668. }
  669. }
  670. return "";
  671. }
  672. /**
  673. * 通过控制器型号名称获取型号id
  674. * @param name
  675. * @return
  676. */
  677. public Integer getLampControlIdByName(String name){
  678. for (LampControlTypeEnum value : LampControlTypeEnum.values()) {
  679. if (value.getName().equals(name)){
  680. return value.getId();
  681. }
  682. }
  683. return 0;
  684. }
  685. /**
  686. * 获取文件的大小
  687. * @param path 文件的路径
  688. * @return 返回文件的大小(四舍五入)
  689. */
  690. public String getFileSize(String path) throws IOException {
  691. String urlStr = path;
  692. if (!urlStr.contains("https://") && !urlStr.contains("http://")) {
  693. urlStr = "http://" + urlStr;
  694. }
  695. URL url = new URL(urlStr);
  696. URLConnection connection = url.openConnection();
  697. long fileSize = connection.getContentLengthLong();
  698. DecimalFormat decimalFormat = new DecimalFormat("0.00");
  699. if (fileSize != -1) {
  700. double fileSizeMB = (double) fileSize / (1024 * 1024);
  701. return decimalFormat.format(fileSizeMB);
  702. } else {
  703. return null;
  704. }
  705. }
  706. /**
  707. * 计算两个经纬度之间的距离
  708. * @param gpsFrom 第一个经纬度坐标点
  709. * @param gpsTo 第二个经纬度坐标点
  710. * @param ellipsoid 坐标系
  711. * @return 返回两者之间的距离
  712. */
  713. public static double getDistanceMeter(GlobalCoordinates gpsFrom, GlobalCoordinates gpsTo, Ellipsoid ellipsoid) {
  714. //创建GeodeticCalculator,调用计算方法,传入坐标系,经纬度用于计算距离
  715. GeodeticCurve geoCurve = new GeodeticCalculator().calculateGeodeticCurve(ellipsoid, gpsFrom, gpsTo);
  716. return geoCurve.getEllipsoidalDistance();
  717. }
  718. /**
  719. * 检查密码、手机号码、邮箱格式是否正确
  720. * @param dataFormat 0:密码,1:手机,2:邮箱
  721. * @return true、false
  722. */
  723. public static Boolean checkDataFormat(String dataFormat, Integer type) {
  724. boolean isFlag;
  725. if (type == 2) { // 邮箱
  726. isFlag = Pattern.matches(PATTERN_EMAIL, dataFormat);
  727. } else if (type == 1) { // 手机
  728. isFlag = Pattern.matches(PATTERN_PHONE, dataFormat);
  729. } else { // 密码
  730. isFlag = Pattern.matches(PATTERN, dataFormat);
  731. }
  732. return isFlag;
  733. }
  734. /**
  735. * 获取云盒气象站485设备列表
  736. * @param devInfoEnum 枚举类数组
  737. * @param version 语言版本
  738. * @return 云盒气象站485设备列表
  739. */
  740. public static List<DevEnumVO> getDevEnum(List<DevInfoEnum> devInfoEnum, Integer version) {
  741. List<DevEnumVO> list = new ArrayList<>();
  742. for (DevInfoEnum d : devInfoEnum) {
  743. String name;
  744. if (version == 0) {
  745. name = d.getNameCh();
  746. } else if (version == 1) {
  747. name = d.getNameEn();
  748. } else {
  749. name = d.getNameRu();
  750. }
  751. list.add(new DevEnumVO(d.getId(), name));
  752. }
  753. return list;
  754. }
  755. /**
  756. * 获取枚举类数组
  757. * @return 枚举类数组
  758. */
  759. public static List<DevInfoEnum> addAllEnum() {
  760. List<DevInfoEnum> list = new ArrayList<>();
  761. list.add(DevInfoEnum.LOUVER_BOX6);
  762. list.add(DevInfoEnum.WIND_DIRECTION);
  763. list.add(DevInfoEnum.WIND_SPEED);
  764. list.add(DevInfoEnum.RAINFALL);
  765. list.add(DevInfoEnum.SOLAR_RADIATION);
  766. list.add(DevInfoEnum.LOUVER_BOX10);
  767. list.add(DevInfoEnum.SOLAR_WIND_SPEED_DIRT);
  768. return list;
  769. }
  770. /**
  771. * 修改灯杆上绑定设备的设备类型
  772. * @param devType 灯杆绑定的设备类型
  773. * @param type 设备类型
  774. * @param lampPoleId 灯杆id
  775. */
  776. public void updateLampPoleDevType(String devType, Integer type, Integer lampPoleId) {
  777. String[] split = devType.split(",");
  778. String value = String.valueOf(type);
  779. StringJoiner joiner = new StringJoiner(",");
  780. for (String s : split) {
  781. if (!s.equals(value)) {
  782. joiner.add(s);
  783. }
  784. }
  785. String newDevType = joiner.toString();
  786. LampPoleDTO lampPoleDTO = new LampPoleDTO();
  787. lampPoleDTO.setId(lampPoleId);
  788. lampPoleDTO.setDevType(newDevType);
  789. lampPoleService.updateLampPoleDevType(lampPoleDTO);
  790. }
  791. /**
  792. * 获取策略内容描述
  793. * @param policyType 策略类型
  794. * @param cmd 指令内容
  795. * @return 策略内容描述
  796. */
  797. public static String getLightStripContent(String policyType, String cmd) {
  798. String content;
  799. switch (policyType) {
  800. case "0":
  801. content = ("常亮(颜色:" + cmd + ")");
  802. break;
  803. case "1":
  804. switch (cmd) {
  805. case "1":
  806. content = ("红灯呼吸");
  807. break;
  808. case "2":
  809. content = ("绿灯呼吸");
  810. break;
  811. case "3":
  812. content = ("蓝灯呼吸");
  813. break;
  814. case "4":
  815. content = ("RGB呼吸");
  816. break;
  817. case "5":
  818. content = ("黄灯呼吸");
  819. break;
  820. case "6":
  821. content = ("紫灯呼吸");
  822. break;
  823. default:
  824. content = "";
  825. break;
  826. }
  827. break;
  828. case "2":
  829. switch (cmd) {
  830. case "1":
  831. content = ("红灯爆闪");
  832. break;
  833. case "2":
  834. content = ("绿灯爆闪");
  835. break;
  836. case "3":
  837. content = ("蓝灯爆闪");
  838. break;
  839. case "4":
  840. content = ("白色爆闪");
  841. break;
  842. case "5":
  843. content = ("7色爆闪");
  844. break;
  845. case "6":
  846. content = ("黄灯爆闪");
  847. break;
  848. case "7":
  849. content = ("紫灯爆闪");
  850. break;
  851. default:
  852. content = "";
  853. break;
  854. }
  855. break;
  856. case "3":
  857. content = ("关灯");
  858. break;
  859. case "4":
  860. switch (cmd) {
  861. case "1":
  862. content = ("红灯闪烁");
  863. break;
  864. case "2":
  865. content = ("绿灯闪烁");
  866. break;
  867. case "3":
  868. content = ("蓝灯闪烁");
  869. break;
  870. case "4":
  871. content = ("白色闪烁");
  872. break;
  873. case "5":
  874. content = ("7色闪烁");
  875. break;
  876. case "6":
  877. content = ("黄灯闪烁");
  878. break;
  879. case "7":
  880. content = ("紫灯闪烁");
  881. break;
  882. default:
  883. content = "";
  884. break;
  885. }
  886. break;
  887. default:
  888. content = "";
  889. break;
  890. }
  891. return content;
  892. }
  893. /**
  894. * 获取plc策略内容
  895. * @param p plc策略内容对象
  896. * @return plc策略内容
  897. * @throws NoSuchFieldException 对象中没有该属性抛出的异常
  898. * @throws IllegalAccessException 类型非法转换抛出的异常
  899. */
  900. public static List<String> getPlcPolicyValue(PlcPolicyCmdDTO p) throws NoSuchFieldException, IllegalAccessException {
  901. List<String> value = new ArrayList<>();
  902. if (p.getBaseTimeType() == 0) { // 零点
  903. for (int i = 1; i <= 6; i ++) {
  904. Field fieldStartTime = p.getClass().getDeclaredField("startTime" + i);
  905. fieldStartTime.setAccessible(true);
  906. String startTime = (String) fieldStartTime.get(p);
  907. if (startTime == null || startTime.isEmpty()) break;
  908. Field fieldEndTime = p.getClass().getDeclaredField("endTime" + i);
  909. fieldEndTime.setAccessible(true);
  910. String endTime = (String) fieldEndTime.get(p);
  911. // 亮度
  912. Field fieldStartBright = p.getClass().getDeclaredField("bright" + i);
  913. fieldStartBright.setAccessible(true);
  914. Integer startBright = (Integer) fieldStartBright.get(p);
  915. // 色温
  916. Field fieldStartColor = p.getClass().getDeclaredField("color" + i);
  917. fieldStartColor.setAccessible(true);
  918. Integer startColor = (Integer) fieldStartColor.get(p);
  919. if (endTime != null && !endTime.isEmpty()) {
  920. String tips = startTime + " - " + endTime + " 亮度" + startBright + "% 色温" + startColor + "k";
  921. value.add(tips);
  922. Field fieldStartTime2 = p.getClass().getDeclaredField("startTime" + (i + 1));
  923. fieldStartTime2.setAccessible(true);
  924. String startTime2 = (String) fieldStartTime2.get(p);
  925. // 亮度
  926. Field fieldEndBright = p.getClass().getDeclaredField("endBright" + i);
  927. fieldEndBright.setAccessible(true);
  928. Integer endBright = (Integer) fieldEndBright.get(p);
  929. // 色温
  930. Field fieldEndColor = p.getClass().getDeclaredField("endColor" + i);
  931. fieldEndColor.setAccessible(true);
  932. Integer endColor = (Integer) fieldEndColor.get(p);
  933. if (startTime2 != null && !startTime2.isEmpty()) {
  934. String tips1 = endTime + " - " + startTime2 + " 亮度" + endBright + "% 色温" + endColor + "k";
  935. value.add(tips1);
  936. } else {
  937. String tips1 = endTime + " - " + " 亮度" + endBright + "% 色温" + endColor + "k";
  938. value.add(tips1);
  939. break;
  940. }
  941. } else {
  942. String tips = startTime + " - " + " 亮度" + startBright + "% 色温" + startColor + "k";
  943. value.add(tips);
  944. break;
  945. }
  946. }
  947. } else { // 日出日落
  948. String startDelayTime = p.getStartDelayTime();
  949. Integer startBright = p.getStartBright();
  950. Integer startColor = p.getStartColor();
  951. String tips1,tips2;
  952. int startTime = Integer.parseInt(startDelayTime);
  953. if (startTime >= 0) {
  954. tips1 = "日出推迟" + startTime + "分钟 亮度" + startBright + "% 色温" + startColor + "k";
  955. } else {
  956. startTime = -startTime;
  957. tips1 = "日出提前" + startTime + "分钟 亮度" + startBright + "% 色温" + startColor + "k";
  958. }
  959. String endDelayTime = p.getEndDelayTime();
  960. Integer endBright = p.getEndBright();
  961. Integer endColor = p.getEndColor();
  962. int endTime = Integer.parseInt(endDelayTime);
  963. if (endTime >= 0) {
  964. tips2 = "日落推迟" + endTime + "分钟 亮度" + endBright + "% 色温" + endColor + "k";
  965. } else {
  966. endTime = -endTime;
  967. tips2 = "日落提前" + endTime + "分钟 亮度" + endBright + "% 色温" + endColor + "k";
  968. }
  969. value.add(tips1);
  970. value.add(tips2);
  971. }
  972. return value;
  973. }
  974. /**
  975. * 获取协议类型字符串
  976. * @param protocolType 协议类型
  977. * @return 协议类型字符串
  978. */
  979. public static String getProtocolTypeStr(Integer protocolType) {
  980. String protocolTypeStr;
  981. switch (protocolType) {
  982. case 12 :
  983. protocolTypeStr = ("铂胜lora");
  984. break;
  985. case 11 :
  986. protocolTypeStr = ("PLC(有单灯,也有双灯控制器)");
  987. break;
  988. case 10 :
  989. protocolTypeStr = ("WE-CON-4G20(双路控制)");
  990. break;
  991. case 9 :
  992. protocolTypeStr = ("LC-6B11-J");
  993. break;
  994. case 8 :
  995. protocolTypeStr = ("eMqtt");
  996. break;
  997. case 7 :
  998. protocolTypeStr = ("oneNet");
  999. break;
  1000. case 6 :
  1001. protocolTypeStr = ("LoraWAN");
  1002. break;
  1003. case 5 :
  1004. protocolTypeStr = ("zigbee");
  1005. break;
  1006. case 4 :
  1007. protocolTypeStr = ("gprs_direct");
  1008. break;
  1009. case 3 :
  1010. protocolTypeStr = ("nbIot");
  1011. break;
  1012. case 2 :
  1013. protocolTypeStr = ("rf mesh");
  1014. break;
  1015. case 1 :
  1016. protocolTypeStr = ("lora mesh");
  1017. break;
  1018. default :
  1019. protocolTypeStr = ("lorawan");
  1020. break;
  1021. }
  1022. return protocolTypeStr;
  1023. }
  1024. /* 向第三方请求post
  1025. *@param requestMethod:请求方式
  1026. * @param url:路径
  1027. * @param param:参数
  1028. * @param ContentTypeEnum: 编码类型
  1029. * @return 返回类型字符串
  1030. */
  1031. public String sendHttp(String requestMethod,String url, String param,Integer timeOut,ContentTypeEnum typeEnum,String cookie) throws IOException {
  1032. String result = "";
  1033. URL postUrl = new URL(url);
  1034. // 打开连接
  1035. HttpURLConnection connection = (HttpURLConnection)postUrl.openConnection();
  1036. // 设置是否向connection输出,因为这个是post请求,参数要放在
  1037. // http正文内,因此需要设为true
  1038. connection.setDoOutput(true);
  1039. connection.setDoInput(true);
  1040. if (timeOut == null || timeOut == 0){
  1041. connection.setConnectTimeout( 5000); //单位:毫秒
  1042. connection.setReadTimeout( 5000); //单位:毫秒
  1043. }else {
  1044. connection.setConnectTimeout(timeOut * 1000); //单位:毫秒
  1045. connection.setReadTimeout(timeOut * 1000); //单位:毫秒
  1046. }
  1047. // Set the post method. Default is GET
  1048. connection.setRequestMethod(requestMethod.toUpperCase());
  1049. // Post 请求不能使用缓存
  1050. connection.setUseCaches(false);
  1051. // URLConnection.setInstanceFollowRedirects是成员函数,仅作用于当前函数
  1052. connection.setInstanceFollowRedirects(true);
  1053. // 进行编码
  1054. if (typeEnum == null){
  1055. //默认是"application/json;charset=utf-8"
  1056. connection.setRequestProperty("Content-Type","application/json;charset=utf-8");
  1057. }else {
  1058. connection.setRequestProperty("Content-Type",typeEnum.contentType);
  1059. }
  1060. if (cookie != null){
  1061. connection.setRequestProperty("Cookie",cookie);
  1062. }
  1063. // 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,
  1064. // 要注意的是connection.getOutputStream会隐含的进行connect。
  1065. connection.connect();
  1066. if (!requestMethod.equals("GET") && !requestMethod.equals("get")){
  1067. DataOutputStream out = new DataOutputStream(connection.getOutputStream());
  1068. // 正文,正文内容其实跟get的URL中'?'后的参数字符串一致
  1069. // DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写道流里面
  1070. out.writeBytes(param);
  1071. out.flush();
  1072. out.close(); // flush and close
  1073. }
  1074. //读取服务器返回的数据
  1075. BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
  1076. String line;
  1077. while ((line = reader.readLine()) != null) {
  1078. result += line;
  1079. }
  1080. reader.close();
  1081. connection.disconnect();
  1082. return result;
  1083. }
  1084. /* 向第三方请求post
  1085. *@param request:请求方式
  1086. * @param url:路径
  1087. * @param param:参数
  1088. * @param token:令牌
  1089. * @param sessionId:会话id
  1090. * @param timeOut:超时
  1091. * @param mark:标记Authorization是传哪种方式
  1092. * @param typeEnum: 编码类型
  1093. * @return 返回类型字符串
  1094. */
  1095. public String sendHttp(String requestMethod,String url, String param,String token,String sessionId,Integer timeOut,String mark,ContentTypeEnum typeEnum,String cookie) throws IOException {
  1096. String result = "";
  1097. URL postUrl = new URL(url);
  1098. // 打开连接
  1099. HttpURLConnection connection = (HttpURLConnection)postUrl.openConnection();
  1100. // 设置是否向connection输出,因为这个是post请求,参数要放在
  1101. // http正文内,因此需要设为true
  1102. connection.setDoOutput(true);
  1103. connection.setDoInput(true);
  1104. // Set the post method. Default is GET
  1105. connection.setRequestMethod(requestMethod.toUpperCase());
  1106. // Post 请求不能使用缓存
  1107. connection.setUseCaches(false);
  1108. // URLConnection.setInstanceFollowRedirects是成员函数,仅作用于当前函数
  1109. connection.setInstanceFollowRedirects(true);
  1110. // 进行编码
  1111. //connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
  1112. if (typeEnum == null){
  1113. //默认是"application/json;charset=utf-8"
  1114. connection.setRequestProperty("Content-Type","application/json;charset=utf-8");
  1115. }else {
  1116. connection.setRequestProperty("Content-Type",typeEnum.contentType);
  1117. }
  1118. if (mark != null && mark.toLowerCase().equals("bearer")){
  1119. connection.setRequestProperty("Authorization","Bearer "+token);
  1120. }else if(mark != null && mark.equals("api-key")) {
  1121. connection.setRequestProperty("api-key"," "+token);
  1122. }else {
  1123. connection.setRequestProperty("Authorization",token);
  1124. }
  1125. if (cookie != null){
  1126. connection.setRequestProperty("Cookie",cookie);
  1127. }
  1128. if (sessionId != null){
  1129. connection.setRequestProperty("SessionId"," "+sessionId);
  1130. }
  1131. if (timeOut == null || timeOut == 0){
  1132. connection.setConnectTimeout( 5000); //单位:毫秒
  1133. connection.setReadTimeout( 5000); //单位:毫秒
  1134. }else {
  1135. connection.setConnectTimeout(timeOut * 1000); //单位:毫秒
  1136. connection.setReadTimeout(timeOut * 1000); //单位:毫秒
  1137. }
  1138. // 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,
  1139. // 要注意的是connection.getOutputStream会隐含的进行connect。
  1140. connection.connect();
  1141. if (!requestMethod.equals("GET") && !requestMethod.equals("get")){
  1142. DataOutputStream out = new DataOutputStream(connection.getOutputStream());
  1143. // 正文,正文内容其实跟get的URL中'?'后的参数字符串一致
  1144. // DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写道流里面
  1145. out.writeBytes(param);
  1146. out.flush();
  1147. out.close(); // flush and close
  1148. }
  1149. BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
  1150. String line;
  1151. while ((line = reader.readLine()) != null) {
  1152. result += line;
  1153. }
  1154. reader.close();
  1155. connection.disconnect();
  1156. return result;
  1157. }
  1158. // 添加设备onenet
  1159. public String addDeviceOnenet(String deviceId){
  1160. JSONObject device = new JSONObject();
  1161. device.put("title",deviceId);
  1162. device.put("protocol","LWM2M");
  1163. JSONObject authInfo = new JSONObject();
  1164. authInfo.put(deviceId,deviceId);
  1165. device.put("auth_info",authInfo);
  1166. String url="http://api.heclouds.com/devices";
  1167. String token = "HpumrF3BKBo3mOFIhkyf5MtIIOc=";
  1168. String respone = null;
  1169. try {
  1170. respone = this.sendHttp("post", url, device.toString(), token, null, 5, "api-key", ContentTypeEnum.CONTENT_TYPE_JSON,null);
  1171. } catch (IOException e) {
  1172. throw new RuntimeException(e);
  1173. }
  1174. return respone;
  1175. }
  1176. // 修改灯杆类型
  1177. public void setPoleType(Integer poleId,Integer type){
  1178. if (poleId != 0 || poleId != null){
  1179. LampPoleDTO lampPoleDTO = lampPoleService.getLampPoleDTOById(poleId);
  1180. String[] devArr = new String[]{};
  1181. if(lampPoleDTO.getDevType() != null){
  1182. devArr = lampPoleDTO.getDevType().split(",");
  1183. }
  1184. //是否包含某个元素
  1185. boolean ifContain = Arrays.asList(devArr).contains(type);
  1186. if (ifContain == false){
  1187. //字符串数组转换list,再添加元素
  1188. List<String> list = new ArrayList<>(Arrays.asList(devArr));
  1189. list.add(type.toString());
  1190. //list数组按规定拼接成字符串
  1191. String newDevType = list.stream().collect(Collectors.joining(","));
  1192. lampPoleDTO.setId(poleId);
  1193. lampPoleDTO.setDevType(newDevType);
  1194. lampPoleService.updateById(lampPoleDTO);
  1195. }
  1196. }
  1197. }
  1198. //操作日志
  1199. public void addOpertaionLog(HttpServletRequest request,String operation, String remark,Integer type,Integer operaType,Integer devtype,String deviceName,String area,String section,String sn ,Integer sectionId ,Integer areaId ,Integer id,String sql_log){
  1200. String ip = "";
  1201. if (request.getParameter("ip") != null){
  1202. ip = request.getParameter("ip");
  1203. }else {
  1204. ip = request.getServerName();
  1205. }
  1206. try {
  1207. String location = this.getLocationByIp(ip);
  1208. Date day = new Date();
  1209. SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  1210. String updateTime = sdf.format(day);
  1211. String username = request.getParameter("username");
  1212. Integer userId = this.getUser(request).getId();
  1213. Integer os = request.getParameter("os") == null ? 0 : Integer.parseInt(request.getParameter("os"));
  1214. OperationLogDTO operationLogDTO = new OperationLogDTO();
  1215. operationLogDTO.setTime(updateTime);
  1216. operationLogDTO.setAcount(username);
  1217. operationLogDTO.setOperation(operation);
  1218. operationLogDTO.setRemark(remark);
  1219. operationLogDTO.setOs(os);
  1220. operationLogDTO.setType(type);
  1221. operationLogDTO.setOperaType(operaType);
  1222. operationLogDTO.setUserId(userId);
  1223. operationLogDTO.setDeviceName(deviceName);
  1224. operationLogDTO.setArea(area);
  1225. operationLogDTO.setSection(section);
  1226. operationLogDTO.setSn(sn);
  1227. operationLogDTO.setAreaId(areaId);
  1228. operationLogDTO.setSectionId(sectionId);
  1229. operationLogDTO.setDevId(id);
  1230. operationLogDTO.setSqlLog(sql_log);
  1231. operationLogDTO.setIpAddr(ip);
  1232. operationLogDTO.setLocation(location);
  1233. operationLogService.add(operationLogDTO);
  1234. } catch (IOException e) {
  1235. throw new RuntimeException(e);
  1236. }
  1237. }
  1238. public String getLocationByIp(String ip) throws IOException {
  1239. //把域名都转换成ip地址
  1240. ip = InetAddress.getByName(ip).getHostAddress();
  1241. IpInfoDTO infoDTO = ipInfoService.getDataByIp(ip);
  1242. String location = "";
  1243. if (infoDTO == null){
  1244. IpInfoDTO newInfoDTO = new IpInfoDTO();
  1245. if (ip.equals("127.0.0.1")){
  1246. //本地添加
  1247. location = "服务器本地";
  1248. newInfoDTO.setLocation(location);
  1249. newInfoDTO.setIpAddr(ip);
  1250. ipInfoService.add(newInfoDTO);
  1251. }else {
  1252. String url = "https://opendata.baidu.com/api.php?query="+ip+"&co=&resource_id=6006&oe=utf8";
  1253. JSONObject jsonObject = new JSONObject();
  1254. jsonObject.put("query",ip);
  1255. jsonObject.put("co",null);
  1256. jsonObject.put("resource_id",600);
  1257. jsonObject.put("oe","utf8");
  1258. String respone = this.sendHttp("get", url, jsonObject.toString(), 4, ContentTypeEnum.CONTENT_TYPE_JSON,null);
  1259. if (respone != null){
  1260. JSONObject responeJson = JSON.parseObject(respone);
  1261. String status = responeJson.getString("status");
  1262. if (status.equals("0")){
  1263. //成功
  1264. //数组
  1265. JSONArray jsonArray = responeJson.getJSONArray("data");
  1266. JSONObject item = (JSONObject)(jsonArray.get(0));
  1267. location = item.getString("location");
  1268. newInfoDTO.setLocation(location);
  1269. newInfoDTO.setIpAddr(ip);
  1270. ipInfoService.add(newInfoDTO);
  1271. }
  1272. }
  1273. }
  1274. }else {
  1275. location = infoDTO.getLocation();
  1276. }
  1277. return location;
  1278. }
  1279. }