ToolUtils.java 59 KB

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