ToolUtils.java 84 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132
  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.configuration.WifiMqttConfig;
  12. import com.welampiot.dto.*;
  13. import com.welampiot.handle.MqttHandler;
  14. import com.welampiot.service.*;
  15. import com.welampiot.vo.DevEnumVO;
  16. import org.apache.commons.httpclient.HttpClient;
  17. import org.apache.commons.httpclient.methods.PostMethod;
  18. import org.eclipse.paho.client.mqttv3.MqttClient;
  19. import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
  20. import org.eclipse.paho.client.mqttv3.MqttMessage;
  21. import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
  22. import org.gavaghan.geodesy.Ellipsoid;
  23. import org.gavaghan.geodesy.GeodeticCalculator;
  24. import org.gavaghan.geodesy.GeodeticCurve;
  25. import org.gavaghan.geodesy.GlobalCoordinates;
  26. import org.slf4j.Logger;
  27. import org.slf4j.LoggerFactory;
  28. import org.springframework.beans.factory.annotation.Autowired;
  29. import org.springframework.stereotype.Component;
  30. import org.springframework.web.multipart.MultipartFile;
  31. import javax.servlet.http.HttpServletRequest;
  32. import java.io.*;
  33. import java.lang.reflect.Field;
  34. import java.net.HttpURLConnection;
  35. import java.net.InetAddress;
  36. import java.net.URL;
  37. import java.net.URLConnection;
  38. import java.text.DecimalFormat;
  39. import java.text.SimpleDateFormat;
  40. import java.util.*;
  41. import java.util.regex.Pattern;
  42. import java.util.stream.Collectors;
  43. import java.util.zip.CRC32;
  44. import java.util.zip.GZIPInputStream;
  45. @Component
  46. public class ToolUtils {
  47. //http的编码
  48. public enum ContentTypeEnum {
  49. CONTENT_TYPE_JSON("application/json;charset=utf-8"),
  50. CONTENT_TYPE_FORM("application/x-www-form-urlencoded;charset=utf-8")
  51. ;
  52. private String contentType;
  53. ContentTypeEnum(String contentType) {
  54. this.contentType = contentType;
  55. }
  56. }
  57. //用户的权限
  58. final static public Integer SYSTEM_ADMIN = 1;
  59. final static public Integer COMPANY_ADMIN = 2;
  60. final static public Integer COMPANY_CUSTOMER = 3;
  61. //国标摄像头播放地址
  62. final static private String gbHost = "47.112.108.98";
  63. // 和风天气的key
  64. final static public String WEATHER_KEY = "2dca03c7d95c442ba8fbce9d7a96db78";
  65. private UserDTO user;
  66. @Autowired
  67. private UserService userService;
  68. @Autowired
  69. private SectionService sectionService;
  70. @Autowired
  71. private GlobalLocationService globalLocationService;
  72. @Autowired
  73. private MqttConfig mqttConfig;
  74. @Autowired
  75. private MqttHandler mqttHandler;
  76. @Autowired
  77. private LampPoleService lampPoleService;
  78. @Autowired
  79. private PlcMqttConfig plcMqttConfig;
  80. private static final String PATTERN = "^(?=.*[0-9])(?=.*[a-zA-Z]).{8,20}$";
  81. private static final String PATTERN_PHONE = "^1[3-9]\\d{9}$";
  82. private static final String PATTERN_EMAIL = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$";
  83. @Autowired
  84. private IpInfoService ipInfoService;
  85. @Autowired
  86. private OperationLogService operationLogService;
  87. @Autowired
  88. private GbPlayService gbPlayService;
  89. @Autowired
  90. private WifiMqttConfig wifiMqttConfig;
  91. /**
  92. * 获取用户所有路段 id
  93. * @param request
  94. * @return 如果返回列表为空,表示超管获取到全部路段信息,此时不需要做路段筛选
  95. */
  96. public List getSectionList(HttpServletRequest request){
  97. String username = request.getParameter("username");
  98. ArrayList<Object> sectionList = new ArrayList<>();
  99. if (username == null || username.toString().length() == 0) {
  100. sectionList.add(0);
  101. return sectionList;
  102. }
  103. user = userService.findUserByUserName(username);
  104. if (user == null) {
  105. sectionList.add(0);
  106. return sectionList;
  107. }
  108. String provinceid = request.getParameter("provinceId");
  109. provinceid = provinceid == null || provinceid.equals("0") ? request.getParameter("provinceId") : provinceid;
  110. String cityid = request.getParameter("cityId");
  111. cityid = cityid == null || cityid.equals("0") ? request.getParameter("cityId") : cityid;
  112. String areaid = request.getParameter("areaId");
  113. areaid = areaid == null || areaid.equals("0") ? request.getParameter("areaId") : areaid;
  114. String sectionid = request.getParameter("sectionId");
  115. sectionid = sectionid == null || sectionid.equals("0") ? request.getParameter("sectionId") : sectionid;
  116. if (sectionid != null && sectionid.length() != 0 && !sectionid.equals("0")){
  117. sectionList.add(sectionid);
  118. return sectionList;
  119. }
  120. String zone = user.getZoneList();
  121. int role = user.getRole();
  122. List<SectionDTO> maps;
  123. List<GlobalLocationDTO> globalLocationList;
  124. ArrayList areaList = new ArrayList<>();
  125. if ((cityid != null && !cityid.equals("0")) || (provinceid != null && !provinceid.equals("0")) || (areaid != null && !areaid.equals("0"))){
  126. if (areaid == null || areaid.equals("0")){
  127. ArrayList cityList = new ArrayList<>();
  128. if (cityid == null || cityid.equals("0")){
  129. globalLocationList = globalLocationService.getListByPid(Integer.valueOf(provinceid));
  130. if (globalLocationList.isEmpty()){
  131. cityid = provinceid;
  132. }else {
  133. for (GlobalLocationDTO m :globalLocationList) {
  134. cityList.add(m.getId());
  135. }
  136. }
  137. }
  138. if (cityList.isEmpty()){
  139. globalLocationList = globalLocationService.getListByPid(Integer.valueOf(cityid));
  140. }else {
  141. globalLocationList = globalLocationService.getListByPidList(cityList);
  142. }
  143. if (globalLocationList.isEmpty()){
  144. areaid = cityid;
  145. }else {
  146. for (GlobalLocationDTO m :globalLocationList) {
  147. areaList.add(m.getId());
  148. }
  149. }
  150. }
  151. }
  152. if ((areaid == null || areaid.length() == 0 || areaid.equals("0")) && areaList.isEmpty()){
  153. if (role != 1) {
  154. return Arrays.asList(zone.split(","));
  155. }else {
  156. return new ArrayList<>();
  157. }
  158. }else {
  159. if (areaid == null || areaid.equals("0")){
  160. maps = sectionService.getListByPidList(areaList);
  161. if (role != 1){
  162. return Arrays.asList(zone.split(","));
  163. }
  164. }else {
  165. System.out.println(areaid);
  166. int areaid2 = Integer.valueOf(areaid);
  167. maps = sectionService.getListByPid(areaid2);
  168. }
  169. }
  170. for (SectionDTO map:maps) {
  171. sectionList.add(map.getId());
  172. }
  173. if (sectionList.isEmpty()) sectionList.add("0");
  174. return sectionList;
  175. }
  176. public UserDTO getUser() {
  177. return user;
  178. }
  179. public UserDTO getUser(HttpServletRequest request) {
  180. String username = request.getParameter("username");
  181. ArrayList<Object> sectionList = new ArrayList<>();
  182. // if (user == null) {//若换了帐号,还是上次的帐号
  183. // user = userService.findUserByUserName(username);
  184. // }
  185. user = userService.findUserByUserName(username);
  186. return user;
  187. }
  188. /**
  189. * 返回接口信息,不带数据
  190. * @param code 状态码
  191. * @param version 语言类型 0 中文,1 英文,2 俄语
  192. * @return
  193. */
  194. public BaseResult response(InterfaceResultEnum resultEnum,Integer version){
  195. String msg;
  196. String code = resultEnum.getCode();
  197. if (version == 0){
  198. msg = resultEnum.getMsgCn();} else if (version == 1) {
  199. msg = resultEnum.getMsgEn();
  200. }else {
  201. msg = resultEnum.getMsgRu();
  202. }
  203. BaseResult<Object> objectBaseResult = new BaseResult<>(code, msg, new Object());
  204. Logger paramLog = LoggerFactory.getLogger("param_log");
  205. paramLog.info("reponse param== "+ JSON.toJSONString(objectBaseResult));
  206. return objectBaseResult;
  207. }
  208. /**
  209. * 返回接口信息,带数据
  210. * @param code 状态码
  211. * @param version 语言类型 0 中文,1 英文,2 俄语
  212. * @param obj 返回数据内容
  213. * @return
  214. */
  215. public BaseResult response(InterfaceResultEnum resultEnum,Integer version,Object obj){
  216. String msg;
  217. String code = resultEnum.getCode();
  218. if (version == 0){
  219. msg = resultEnum.getMsgCn();
  220. } else if (version == 1) {
  221. msg = resultEnum.getMsgEn();
  222. }else {
  223. msg = resultEnum.getMsgRu();
  224. }
  225. BaseResult<Object> objectBaseResult = new BaseResult<>(code, msg, obj);
  226. Logger paramLog = LoggerFactory.getLogger("param_log");
  227. paramLog.info("reponse param== "+ JSON.toJSONString(objectBaseResult));
  228. return objectBaseResult;
  229. }
  230. /**
  231. * 发送mqtt指令
  232. * @param sendTopic 发送的topic
  233. * @param cmdInfo 发送的指令内容
  234. * @param resTopic 接收指令返回的topic
  235. * @return
  236. */
  237. public String sendMqttCmd(String sendTopic,Object cmdInfo,String resTopic){
  238. MqttClient client;
  239. String res = "";
  240. try {
  241. try {
  242. client=new MqttClient(mqttConfig.getUrl(),mqttConfig.getClientId()+"_"+(new Date()).getTime(),new MemoryPersistence());
  243. MqttConnectOptions options=new MqttConnectOptions();
  244. options.setCleanSession(true);
  245. options.setUserName(mqttConfig.getUsername());
  246. options.setPassword(mqttConfig.getPassword().toCharArray());
  247. options.setConnectionTimeout(mqttConfig.getTimeout());
  248. options.setKeepAliveInterval(mqttConfig.getKeepalive());
  249. mqttHandler.setTopic(resTopic);
  250. // 设置回调
  251. client.setCallback(mqttHandler);
  252. // 建立连接
  253. client.connect(options);
  254. // MqttCustomerClient.setClient(client);
  255. client.subscribe(resTopic);
  256. // 消息发布所需参数
  257. MqttMessage message;
  258. if (cmdInfo instanceof String){
  259. message = new MqttMessage(((String) cmdInfo).getBytes());
  260. }else {
  261. message = new MqttMessage((byte[]) cmdInfo);
  262. }
  263. message.setQos(0);
  264. client.publish(sendTopic, message);
  265. int in = 0;
  266. while (true){
  267. Thread.sleep(1000);
  268. if (mqttHandler.getRes() != null && mqttHandler.getRes().length() != 0){
  269. res = mqttHandler.getRes();
  270. break;
  271. }
  272. in ++;
  273. if (in > 30) break;
  274. }
  275. client.disconnect();
  276. }catch (Exception e){
  277. e.printStackTrace();
  278. }
  279. }catch (Exception e){
  280. e.printStackTrace();
  281. }
  282. return res;
  283. }
  284. /**
  285. * 发送mqtt指令
  286. * @param sendTopic 发送的topic
  287. * @param cmdInfo 发送的指令内容
  288. * @param resTopic 接收指令返回的topic
  289. * @param timeout 指令超时时间
  290. * @return
  291. */
  292. public String sendMqttCmd(String sendTopic,Object cmdInfo,String resTopic,Integer timeout){
  293. MqttClient client;
  294. String res = "";
  295. try {
  296. try {
  297. client=new MqttClient(mqttConfig.getUrl(),mqttConfig.getClientId()+"_"+(new Date()).getTime(),new MemoryPersistence());
  298. MqttConnectOptions options=new MqttConnectOptions();
  299. options.setCleanSession(true);
  300. options.setUserName(mqttConfig.getUsername());
  301. options.setPassword(mqttConfig.getPassword().toCharArray());
  302. options.setConnectionTimeout(mqttConfig.getTimeout());
  303. options.setKeepAliveInterval(mqttConfig.getKeepalive());
  304. mqttHandler.setTopic(resTopic);
  305. // 设置回调
  306. client.setCallback(mqttHandler);
  307. // 建立连接
  308. client.connect(options);
  309. // MqttCustomerClient.setClient(client);
  310. client.subscribe(resTopic);
  311. // 消息发布所需参数
  312. MqttMessage message;
  313. if (cmdInfo instanceof String){
  314. message = new MqttMessage(((String) cmdInfo).getBytes());
  315. }else {
  316. message = new MqttMessage((byte[]) cmdInfo);
  317. }
  318. message.setQos(0);
  319. client.publish(sendTopic, message);
  320. int in = 0;
  321. if (timeout > 0){
  322. while (true){
  323. Thread.sleep(1000);
  324. if (mqttHandler.getRes() != null && mqttHandler.getRes().length() != 0){
  325. res = mqttHandler.getRes();
  326. break;
  327. }
  328. in ++;
  329. if (in > timeout) break;
  330. }
  331. }
  332. client.disconnect();
  333. }catch (Exception e){
  334. e.printStackTrace();
  335. }
  336. }catch (Exception e){
  337. e.printStackTrace();
  338. }
  339. return res;
  340. }
  341. /**
  342. * 发送plc的mqtt指令
  343. * @param sendTopic 发送的topic
  344. * @param cmdInfo 发送的指令内容
  345. * @param resTopic 接收指令返回的topic
  346. * @return
  347. */
  348. public String plcSendMqttCmd(String sendTopic,Object cmdInfo,String resTopic){
  349. MqttClient client;
  350. String res = "";
  351. try {
  352. try {
  353. client=new MqttClient(plcMqttConfig.getUrl(),plcMqttConfig.getClientId()+"_"+(new Date()).getTime(),new MemoryPersistence());
  354. MqttConnectOptions options=new MqttConnectOptions();
  355. options.setCleanSession(true);
  356. options.setUserName(plcMqttConfig.getUsername());
  357. options.setPassword(plcMqttConfig.getPassword().toCharArray());
  358. options.setConnectionTimeout(plcMqttConfig.getTimeout());
  359. options.setKeepAliveInterval(plcMqttConfig.getKeepalive());
  360. mqttHandler.setTopic(resTopic);
  361. // 设置回调
  362. client.setCallback(mqttHandler);
  363. // 建立连接
  364. client.connect(options);
  365. // MqttCustomerClient.setClient(client);
  366. client.subscribe(resTopic);
  367. // 消息发布所需参数
  368. MqttMessage message;
  369. if (cmdInfo instanceof String){
  370. message = new MqttMessage(((String) cmdInfo).getBytes());
  371. }else {
  372. message = new MqttMessage((byte[]) cmdInfo);
  373. }
  374. message.setQos(0);
  375. client.publish(sendTopic, message);
  376. int in = 0;
  377. while (true){
  378. Thread.sleep(1000);
  379. if (mqttHandler.getRes() != null && mqttHandler.getRes().length() != 0){
  380. res = mqttHandler.getRes();
  381. break;
  382. }
  383. in ++;
  384. if (in > 30) break;
  385. }
  386. client.disconnect();
  387. }catch (Exception e){
  388. e.printStackTrace();
  389. }
  390. }catch (Exception e){
  391. e.printStackTrace();
  392. }
  393. return res;
  394. }
  395. /**
  396. * 发送plc的mqtt指令
  397. * @param sendTopic 发送的topic
  398. * @param cmdInfo 发送的指令内容
  399. * @param resTopic 接收指令返回的topic
  400. * @param timeout 指令超时时间
  401. * @return
  402. */
  403. public String plcSendMqttCmd(String sendTopic,String cmdInfo, String resTopic, Integer timeout){
  404. MqttClient client;
  405. String res = "";
  406. try {
  407. try {
  408. client=new MqttClient(plcMqttConfig.getUrl(),plcMqttConfig.getClientId()+"_"+(new Date()).getTime(),new MemoryPersistence());
  409. MqttConnectOptions options=new MqttConnectOptions();
  410. options.setCleanSession(true);
  411. options.setUserName(plcMqttConfig.getUsername());
  412. options.setPassword(plcMqttConfig.getPassword().toCharArray());
  413. options.setConnectionTimeout(plcMqttConfig.getTimeout());
  414. options.setKeepAliveInterval(plcMqttConfig.getKeepalive());
  415. mqttHandler.setTopic(resTopic);
  416. // 设置回调
  417. client.setCallback(mqttHandler);
  418. // 建立连接
  419. client.connect(options);
  420. // MqttCustomerClient.setClient(client);
  421. client.subscribe(resTopic);
  422. // 消息发布所需参数
  423. MqttMessage message;
  424. message = new MqttMessage(cmdInfo.getBytes());
  425. message.setQos(0);
  426. client.publish(sendTopic, message);
  427. System.out.println("==send:"+sendTopic+"====res:"+resTopic);
  428. int in = 0;
  429. if (timeout > 0){
  430. while (true){
  431. System.out.println("==d====:"+in+"====");
  432. Thread.sleep(100);
  433. if (mqttHandler.getRes() != null && mqttHandler.getRes().length() != 0){
  434. res = mqttHandler.getRes();
  435. System.out.println(res);
  436. //原来的
  437. JSONObject oldObject = JSON.parseObject(cmdInfo);
  438. String oldDataType = oldObject.getObject("dataType", String.class);
  439. // String[] oldThirdIdArr = oldObject.getObject("thirdId",String.class).split("-");
  440. // String[] oldSnArr = oldThirdIdArr[0].split(":");
  441. // String oldSn = oldSnArr[1]; //设备地址
  442. // String[] oldNumberArr = oldThirdIdArr[1].split(":");
  443. // int oldNum = Integer.parseInt(oldNumberArr[1]); //设备灯序号
  444. //解析json
  445. JSONObject jsonObject = JSON.parseObject(res);
  446. String dataType = jsonObject.getObject("dataType", String.class);
  447. // String[] thirdIdArr = jsonObject.getObject("thirdId",String.class).split("-");
  448. // String[] snArr = thirdIdArr[0].split(":");
  449. // String sn = snArr[1]; //设备地址
  450. // String[] numberArr = thirdIdArr[1].split(":");
  451. // int num = Integer.parseInt(numberArr[1]); //设备灯序号
  452. //它是字符串
  453. if (dataType.equals("lightStatus") ){ //1.读取灯信息,2.调光的
  454. //原来的
  455. String[] oldThirdIdArr = oldObject.getObject("thirdId",String.class).split("-");
  456. String[] oldSnArr = oldThirdIdArr[0].split(":");
  457. String oldSn = oldSnArr[1]; //设备地址
  458. String[] oldNumberArr = oldThirdIdArr[1].split(":");
  459. int oldNum = Integer.parseInt(oldNumberArr[1]); //设备灯序号
  460. //解析json
  461. String[] thirdIdArr = jsonObject.getObject("thirdId",String.class).split("-");
  462. String[] snArr = thirdIdArr[0].split(":");
  463. String sn = snArr[1]; //设备地址
  464. String[] numberArr = thirdIdArr[1].split(":");
  465. int num = Integer.parseInt(numberArr[1]); //设备灯序号
  466. //类型相等
  467. System.out.println("====ddd:"+oldSn+"====sn:"+sn+"====ol:"+oldNum+"==nu:"+num);
  468. if ((oldDataType.equals("lightStatus") || oldDataType.equals("adjustLightController")) && oldSn.equals(sn) && (oldNum == num)){
  469. //查看灯的信息
  470. System.out.println("====ddd:"+res);
  471. return res;
  472. }
  473. }
  474. }
  475. in ++;
  476. if (in > timeout) return null;
  477. }
  478. }
  479. client.disconnect();
  480. }catch (Exception e){
  481. System.out.println("==dd=="+e);
  482. e.printStackTrace();
  483. }
  484. }catch (Exception e){
  485. System.out.println(e);
  486. e.printStackTrace();
  487. }
  488. return null;
  489. }
  490. /**
  491. * 字节数组转16进制字符串
  492. * @param b 字节数组
  493. * @return 16进制字符串
  494. * @throws
  495. */
  496. public String bytes2HexString(byte[] b) {
  497. StringBuffer result = new StringBuffer();
  498. String hex;
  499. for (int i = 0; i < b.length; i++) {
  500. hex = Integer.toHexString(b[i] & 0xFF);
  501. if (hex.length() == 1) {
  502. hex = '0' + hex;
  503. }
  504. result.append(hex.toUpperCase());
  505. }
  506. return result.toString();
  507. }
  508. /**
  509. * 16进制字符串转字节数组
  510. * @param src 16进制字符串
  511. * @return 字节数组
  512. * @throws
  513. */
  514. public byte[] hexString2Bytes(String src) {
  515. int l = src.length() / 2;
  516. byte[] ret = new byte[l];
  517. for (int i = 0; i < l; i++) {
  518. ret[i] = (byte) Integer
  519. .valueOf(src.substring(i * 2, i * 2 + 2), 16).byteValue();
  520. }
  521. return ret;
  522. }
  523. /**
  524. * 获取CRC32校验码
  525. * @param src 16进制字符串
  526. * @return CRC32校验码
  527. */
  528. public String getCRC32ByHexString2Bytes(String src) {
  529. CRC32 crc32 = new CRC32();
  530. crc32.update(this.hexString2Bytes(src));
  531. return Integer.toHexString((int) crc32.getValue());
  532. }
  533. /**
  534. * 计算modbus CRC16校验码
  535. * @param bytes 需要计算的数据
  536. * @return
  537. */
  538. public String getCRC(byte[] bytes) {
  539. // CRC寄存器全为1
  540. int CRC = 0x0000ffff;
  541. // 多项式校验值
  542. int POLYNOMIAL = 0x0000a001;
  543. int i, j;
  544. for (i = 0; i < bytes.length; i++) {
  545. CRC ^= ((int) bytes[i] & 0x000000ff);
  546. for (j = 0; j < 8; j++) {
  547. if ((CRC & 0x00000001) != 0) {
  548. CRC >>= 1;
  549. CRC ^= POLYNOMIAL;
  550. } else {
  551. CRC >>= 1;
  552. }
  553. }
  554. }
  555. // 结果转换为16进制
  556. String result = Integer.toHexString(CRC).toUpperCase();
  557. if (result.length() != 4) {
  558. StringBuffer sb = new StringBuffer("0000");
  559. result = sb.replace(4 - result.length(), 4, result).toString();
  560. }
  561. //高位在前地位在后
  562. //return result.substring(2, 4) + " " + result.substring(0, 2);
  563. // 交换高低位,低位在前高位在后
  564. return result.substring(2, 4)+result.substring(0, 2);
  565. }
  566. public String getCRC(String cmd) {
  567. byte[] bytes = this.hexString2Bytes(cmd);
  568. // CRC寄存器全为1
  569. int CRC = 0x0000ffff;
  570. // 多项式校验值
  571. int POLYNOMIAL = 0x0000a001;
  572. int i, j;
  573. for (i = 0; i < bytes.length; i++) {
  574. CRC ^= ((int) bytes[i] & 0x000000ff);
  575. for (j = 0; j < 8; j++) {
  576. if ((CRC & 0x00000001) != 0) {
  577. CRC >>= 1;
  578. CRC ^= POLYNOMIAL;
  579. } else {
  580. CRC >>= 1;
  581. }
  582. }
  583. }
  584. // 结果转换为16进制
  585. String result = Integer.toHexString(CRC).toUpperCase();
  586. if (result.length() != 4) {
  587. StringBuffer sb = new StringBuffer("0000");
  588. result = sb.replace(4 - result.length(), 4, result).toString();
  589. }
  590. //高位在前地位在后
  591. //return result.substring(2, 4) + " " + result.substring(0, 2);
  592. // 交换高低位,低位在前高位在后
  593. return result.substring(2, 4)+result.substring(0, 2);
  594. }
  595. public Object getRequestContent(HttpServletRequest request,String key){
  596. return request.getParameter(key);
  597. }
  598. /**
  599. * 获取请求参数
  600. * @param request 请求对象
  601. * @param key 参数值
  602. * @param type 参数类型 1 int 2 string
  603. * @return
  604. */
  605. public Object getRequestContent(HttpServletRequest request,String key,Integer type){
  606. if (type == 1){ // 获取 int 数据
  607. Integer keyId = request.getParameter(key) == null || request.getParameter(key).length() == 0? 0 : Integer.parseInt(request.getParameter(key));
  608. return keyId;
  609. }else if (type == 2){
  610. String keyStr = request.getParameter(key) == null ? "" : request.getParameter(key).toString();
  611. return keyStr.trim();
  612. }
  613. return request.getParameter(key);
  614. }
  615. /**
  616. * 发送post请求
  617. * @param url 请求地址
  618. * @param paraMap 请求参数
  619. * @return
  620. */
  621. public String httpPost(String url,Map paraMap){
  622. HttpClient httpClient = new HttpClient();
  623. httpClient.getHttpConnectionManager().getParams().setSoTimeout(30000);
  624. PostMethod postMethod = new PostMethod(url);
  625. postMethod.addRequestHeader("accept", "*/*");
  626. //设置Content-Type
  627. postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  628. //添加请求参数
  629. Set set = paraMap.keySet();
  630. for (Object s : set) {
  631. postMethod.addParameter((String) s, (String) paraMap.get(s));
  632. }
  633. String result = "";
  634. try {
  635. int code = httpClient.executeMethod(postMethod);
  636. if (code == 200){
  637. result = postMethod.getResponseBodyAsString();
  638. }
  639. } catch (IOException e) {
  640. // e.printStackTrace();
  641. }
  642. return result;
  643. }
  644. /**
  645. * 发送post请求
  646. * @param url 请求地址
  647. * @param paraMap 请求参数
  648. * @param timeout 超时时间
  649. * @return
  650. */
  651. public String httpPost(String url,Map paraMap,int timeout){
  652. HttpClient httpClient = new HttpClient();
  653. httpClient.getHttpConnectionManager().getParams().setSoTimeout(timeout);
  654. PostMethod postMethod = new PostMethod(url);
  655. postMethod.addRequestHeader("accept", "*/*");
  656. //设置Content-Type
  657. postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  658. //添加请求参数
  659. Set set = paraMap.keySet();
  660. for (Object s : set) {
  661. postMethod.addParameter((String) s, (String) paraMap.get(s));
  662. }
  663. String result = "";
  664. try {
  665. int code = httpClient.executeMethod(postMethod);
  666. if (code == 200){
  667. result = postMethod.getResponseBodyAsString();
  668. }
  669. } catch (IOException e) {
  670. // e.printStackTrace();
  671. }
  672. return result;
  673. }
  674. /**
  675. * 通过id获取控制器型号名称
  676. * @param id
  677. * @return
  678. */
  679. public String getLampControlNameById(Integer id){
  680. for (LampControlTypeEnum value : LampControlTypeEnum.values()) {
  681. if (value.getId().intValue() == id.intValue()){
  682. return value.getName();
  683. }
  684. }
  685. return "";
  686. }
  687. /**
  688. * 通过控制器型号名称获取型号id
  689. * @param name
  690. * @return
  691. */
  692. public Integer getLampControlIdByName(String name){
  693. for (LampControlTypeEnum value : LampControlTypeEnum.values()) {
  694. if (value.getName().equals(name)){
  695. return value.getId();
  696. }
  697. }
  698. return 0;
  699. }
  700. /**
  701. * 获取文件的大小
  702. * @param path 文件的路径
  703. * @return 返回文件的大小(四舍五入)
  704. */
  705. public String getFileSize(String path) throws IOException {
  706. String urlStr = path;
  707. if (!urlStr.contains("https://") && !urlStr.contains("http://")) {
  708. urlStr = "http://" + urlStr;
  709. }
  710. URL url = new URL(urlStr);
  711. URLConnection connection = url.openConnection();
  712. long fileSize = connection.getContentLengthLong();
  713. DecimalFormat decimalFormat = new DecimalFormat("0.00");
  714. if (fileSize != -1) {
  715. double fileSizeMB = (double) fileSize / (1024 * 1024);
  716. return decimalFormat.format(fileSizeMB);
  717. } else {
  718. return null;
  719. }
  720. }
  721. /**
  722. * 计算两个经纬度之间的距离
  723. * @param gpsFrom 第一个经纬度坐标点
  724. * @param gpsTo 第二个经纬度坐标点
  725. * @param ellipsoid 坐标系
  726. * @return 返回两者之间的距离
  727. */
  728. public static double getDistanceMeter(GlobalCoordinates gpsFrom, GlobalCoordinates gpsTo, Ellipsoid ellipsoid) {
  729. //创建GeodeticCalculator,调用计算方法,传入坐标系,经纬度用于计算距离
  730. GeodeticCurve geoCurve = new GeodeticCalculator().calculateGeodeticCurve(ellipsoid, gpsFrom, gpsTo);
  731. return geoCurve.getEllipsoidalDistance();
  732. }
  733. /**
  734. * 检查密码、手机号码、邮箱格式是否正确
  735. * @param dataFormat 0:密码,1:手机,2:邮箱
  736. * @return true、false
  737. */
  738. public static Boolean checkDataFormat(String dataFormat, Integer type) {
  739. boolean isFlag;
  740. if (type == 2) { // 邮箱
  741. isFlag = Pattern.matches(PATTERN_EMAIL, dataFormat);
  742. } else if (type == 1) { // 手机
  743. isFlag = Pattern.matches(PATTERN_PHONE, dataFormat);
  744. } else { // 密码
  745. isFlag = Pattern.matches(PATTERN, dataFormat);
  746. }
  747. return isFlag;
  748. }
  749. /**
  750. * 获取云盒气象站485设备列表
  751. * @param devInfoEnum 枚举类数组
  752. * @param version 语言版本
  753. * @return 云盒气象站485设备列表
  754. */
  755. public static List<DevEnumVO> getDevEnum(List<DevInfoEnum> devInfoEnum, Integer version) {
  756. List<DevEnumVO> list = new ArrayList<>();
  757. for (DevInfoEnum d : devInfoEnum) {
  758. String name;
  759. if (version == 0) {
  760. name = d.getNameCh();
  761. } else if (version == 1) {
  762. name = d.getNameEn();
  763. } else {
  764. name = d.getNameRu();
  765. }
  766. list.add(new DevEnumVO(d.getId(), name));
  767. }
  768. return list;
  769. }
  770. /**
  771. * 获取枚举类数组
  772. * @return 枚举类数组
  773. */
  774. public static List<DevInfoEnum> addAllEnum() {
  775. List<DevInfoEnum> list = new ArrayList<>();
  776. list.add(DevInfoEnum.LOUVER_BOX6);
  777. list.add(DevInfoEnum.WIND_DIRECTION);
  778. list.add(DevInfoEnum.WIND_SPEED);
  779. list.add(DevInfoEnum.RAINFALL);
  780. list.add(DevInfoEnum.SOLAR_RADIATION);
  781. list.add(DevInfoEnum.LOUVER_BOX10);
  782. list.add(DevInfoEnum.SOLAR_WIND_SPEED_DIRT);
  783. return list;
  784. }
  785. /**
  786. * 修改灯杆上绑定设备的设备类型
  787. * @param devType 灯杆绑定的设备类型
  788. * @param type 设备类型
  789. * @param lampPoleId 灯杆id
  790. */
  791. public void updateLampPoleDevType(String devType, Integer type, Integer lampPoleId) {
  792. String[] split = devType.split(",");
  793. String value = String.valueOf(type);
  794. StringJoiner joiner = new StringJoiner(",");
  795. for (String s : split) {
  796. if (!s.equals(value)) {
  797. joiner.add(s);
  798. }
  799. }
  800. String newDevType = joiner.toString();
  801. LampPoleDTO lampPoleDTO = new LampPoleDTO();
  802. lampPoleDTO.setId(lampPoleId);
  803. lampPoleDTO.setDevType(newDevType);
  804. lampPoleService.updateLampPoleDevType(lampPoleDTO);
  805. }
  806. /**
  807. * 获取策略内容描述
  808. * @param policyType 策略类型
  809. * @param cmd 指令内容
  810. * @return 策略内容描述
  811. */
  812. public static String getLightStripContent(String policyType, String cmd) {
  813. String content;
  814. switch (policyType) {
  815. case "0":
  816. content = ("常亮(颜色:" + cmd + ")");
  817. break;
  818. case "1":
  819. switch (cmd) {
  820. case "1":
  821. content = ("红灯呼吸");
  822. break;
  823. case "2":
  824. content = ("绿灯呼吸");
  825. break;
  826. case "3":
  827. content = ("蓝灯呼吸");
  828. break;
  829. case "4":
  830. content = ("RGB呼吸");
  831. break;
  832. case "5":
  833. content = ("黄灯呼吸");
  834. break;
  835. case "6":
  836. content = ("紫灯呼吸");
  837. break;
  838. default:
  839. content = "";
  840. break;
  841. }
  842. break;
  843. case "2":
  844. switch (cmd) {
  845. case "1":
  846. content = ("红灯爆闪");
  847. break;
  848. case "2":
  849. content = ("绿灯爆闪");
  850. break;
  851. case "3":
  852. content = ("蓝灯爆闪");
  853. break;
  854. case "4":
  855. content = ("白色爆闪");
  856. break;
  857. case "5":
  858. content = ("7色爆闪");
  859. break;
  860. case "6":
  861. content = ("黄灯爆闪");
  862. break;
  863. case "7":
  864. content = ("紫灯爆闪");
  865. break;
  866. default:
  867. content = "";
  868. break;
  869. }
  870. break;
  871. case "3":
  872. content = ("关灯");
  873. break;
  874. case "4":
  875. switch (cmd) {
  876. case "1":
  877. content = ("红灯闪烁");
  878. break;
  879. case "2":
  880. content = ("绿灯闪烁");
  881. break;
  882. case "3":
  883. content = ("蓝灯闪烁");
  884. break;
  885. case "4":
  886. content = ("白色闪烁");
  887. break;
  888. case "5":
  889. content = ("7色闪烁");
  890. break;
  891. case "6":
  892. content = ("黄灯闪烁");
  893. break;
  894. case "7":
  895. content = ("紫灯闪烁");
  896. break;
  897. default:
  898. content = "";
  899. break;
  900. }
  901. break;
  902. default:
  903. content = "";
  904. break;
  905. }
  906. return content;
  907. }
  908. /**
  909. * 获取plc策略内容
  910. * @param p plc策略内容对象
  911. * @return plc策略内容
  912. * @throws NoSuchFieldException 对象中没有该属性抛出的异常
  913. * @throws IllegalAccessException 类型非法转换抛出的异常
  914. */
  915. public static List<String> getPlcPolicyValue(PlcPolicyCmdDTO p) throws NoSuchFieldException, IllegalAccessException {
  916. List<String> value = new ArrayList<>();
  917. if (p.getBaseTimeType() == 0) { // 零点
  918. for (int i = 1; i <= 6; i ++) {
  919. Field fieldStartTime = p.getClass().getDeclaredField("startTime" + i);
  920. fieldStartTime.setAccessible(true);
  921. String startTime = (String) fieldStartTime.get(p);
  922. if (startTime == null || startTime.isEmpty()) break;
  923. Field fieldEndTime = p.getClass().getDeclaredField("endTime" + i);
  924. fieldEndTime.setAccessible(true);
  925. String endTime = (String) fieldEndTime.get(p);
  926. // 亮度
  927. Field fieldStartBright = p.getClass().getDeclaredField("bright" + i);
  928. fieldStartBright.setAccessible(true);
  929. Integer startBright = (Integer) fieldStartBright.get(p);
  930. // 色温
  931. Field fieldStartColor = p.getClass().getDeclaredField("color" + i);
  932. fieldStartColor.setAccessible(true);
  933. Integer startColor = (Integer) fieldStartColor.get(p);
  934. if (endTime != null && !endTime.isEmpty()) {
  935. String tips = startTime + " - " + endTime + " 亮度" + startBright + "% 色温" + startColor + "k";
  936. value.add(tips);
  937. Field fieldStartTime2 = p.getClass().getDeclaredField("startTime" + (i + 1));
  938. fieldStartTime2.setAccessible(true);
  939. String startTime2 = (String) fieldStartTime2.get(p);
  940. // 亮度
  941. Field fieldEndBright = p.getClass().getDeclaredField("endBright" + i);
  942. fieldEndBright.setAccessible(true);
  943. Integer endBright = (Integer) fieldEndBright.get(p);
  944. // 色温
  945. Field fieldEndColor = p.getClass().getDeclaredField("endColor" + i);
  946. fieldEndColor.setAccessible(true);
  947. Integer endColor = (Integer) fieldEndColor.get(p);
  948. if (startTime2 != null && !startTime2.isEmpty()) {
  949. String tips1 = endTime + " - " + startTime2 + " 亮度" + endBright + "% 色温" + endColor + "k";
  950. value.add(tips1);
  951. } else {
  952. String tips1 = endTime + " - " + " 亮度" + endBright + "% 色温" + endColor + "k";
  953. value.add(tips1);
  954. break;
  955. }
  956. } else {
  957. String tips = startTime + " - " + " 亮度" + startBright + "% 色温" + startColor + "k";
  958. value.add(tips);
  959. break;
  960. }
  961. }
  962. } else { // 日出日落
  963. String startDelayTime = p.getStartDelayTime();
  964. Integer startBright = p.getStartBright();
  965. Integer startColor = p.getStartColor();
  966. String tips1,tips2;
  967. int startTime = java.lang.Integer.parseInt(startDelayTime);
  968. if (startTime >= 0) {
  969. tips1 = "日出推迟" + startTime + "分钟 亮度" + startBright + "% 色温" + startColor + "k";
  970. } else {
  971. startTime = -startTime;
  972. tips1 = "日出提前" + startTime + "分钟 亮度" + startBright + "% 色温" + startColor + "k";
  973. }
  974. String endDelayTime = p.getEndDelayTime();
  975. Integer endBright = p.getEndBright();
  976. Integer endColor = p.getEndColor();
  977. int endTime = java.lang.Integer.parseInt(endDelayTime);
  978. if (endTime >= 0) {
  979. tips2 = "日落推迟" + endTime + "分钟 亮度" + endBright + "% 色温" + endColor + "k";
  980. } else {
  981. endTime = -endTime;
  982. tips2 = "日落提前" + endTime + "分钟 亮度" + endBright + "% 色温" + endColor + "k";
  983. }
  984. value.add(tips1);
  985. value.add(tips2);
  986. }
  987. return value;
  988. }
  989. /**
  990. * 获取协议类型字符串
  991. * @param protocolType 协议类型
  992. * @return 协议类型字符串
  993. */
  994. public static String getProtocolTypeStr(Integer protocolType) {
  995. String protocolTypeStr;
  996. switch (protocolType) {
  997. case 12 :
  998. protocolTypeStr = ("铂胜lora");
  999. break;
  1000. case 11 :
  1001. protocolTypeStr = ("PLC(有单灯,也有双灯控制器)");
  1002. break;
  1003. case 10 :
  1004. protocolTypeStr = ("WE-CON-4G20(双路控制)");
  1005. break;
  1006. case 9 :
  1007. protocolTypeStr = ("LC-6B11-J");
  1008. break;
  1009. case 8 :
  1010. protocolTypeStr = ("eMqtt");
  1011. break;
  1012. case 7 :
  1013. protocolTypeStr = ("oneNet");
  1014. break;
  1015. case 6 :
  1016. protocolTypeStr = ("LoraWAN");
  1017. break;
  1018. case 5 :
  1019. protocolTypeStr = ("zigbee");
  1020. break;
  1021. case 4 :
  1022. protocolTypeStr = ("gprs_direct");
  1023. break;
  1024. case 3 :
  1025. protocolTypeStr = ("nbIot");
  1026. break;
  1027. case 2 :
  1028. protocolTypeStr = ("rf mesh");
  1029. break;
  1030. case 1 :
  1031. protocolTypeStr = ("lora mesh");
  1032. break;
  1033. default :
  1034. protocolTypeStr = ("lorawan");
  1035. break;
  1036. }
  1037. return protocolTypeStr;
  1038. }
  1039. /** 向第三方请求post
  1040. *@param requestMethod:请求方式
  1041. * @param url:路径
  1042. * @param param:参数
  1043. * @param ContentTypeEnum: 编码类型
  1044. * @return 返回类型字符串
  1045. */
  1046. public String sendHttp(String requestMethod,String url, String param,Integer timeOut,ContentTypeEnum typeEnum,String cookie) throws IOException {
  1047. String result = "";
  1048. URL postUrl = new URL(url);
  1049. // 打开连接
  1050. HttpURLConnection connection = (HttpURLConnection)postUrl.openConnection();
  1051. // 设置是否向connection输出,因为这个是post请求,参数要放在
  1052. // http正文内,因此需要设为true
  1053. connection.setDoOutput(true);
  1054. connection.setDoInput(true);
  1055. if (timeOut == null || timeOut == 0){
  1056. connection.setConnectTimeout( 5000); //单位:毫秒
  1057. connection.setReadTimeout( 5000); //单位:毫秒
  1058. }else {
  1059. connection.setConnectTimeout(timeOut * 1000); //单位:毫秒
  1060. connection.setReadTimeout(timeOut * 1000); //单位:毫秒
  1061. }
  1062. // Set the post method. Default is GET
  1063. connection.setRequestMethod(requestMethod.toUpperCase());
  1064. // Post 请求不能使用缓存
  1065. connection.setUseCaches(false);
  1066. // URLConnection.setInstanceFollowRedirects是成员函数,仅作用于当前函数
  1067. connection.setInstanceFollowRedirects(true);
  1068. // 进行编码
  1069. if (typeEnum == null){
  1070. //默认是"application/json;charset=utf-8"
  1071. connection.setRequestProperty("Content-Type","application/json;charset=utf-8");
  1072. }else {
  1073. connection.setRequestProperty("Content-Type",typeEnum.contentType);
  1074. }
  1075. if (cookie != null){
  1076. connection.setRequestProperty("Cookie",cookie);
  1077. }
  1078. // 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,
  1079. // 要注意的是connection.getOutputStream会隐含的进行connect。
  1080. connection.connect();
  1081. if (!requestMethod.equals("GET") && !requestMethod.equals("get")){
  1082. DataOutputStream out = new DataOutputStream(connection.getOutputStream());
  1083. // 正文,正文内容其实跟get的URL中'?'后的参数字符串一致
  1084. // DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写道流里面
  1085. out.writeBytes(param);
  1086. out.flush();
  1087. out.close(); // flush and close
  1088. }
  1089. //读取服务器返回的数据
  1090. BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
  1091. String line;
  1092. while ((line = reader.readLine()) != null) {
  1093. result += line;
  1094. }
  1095. reader.close();
  1096. connection.disconnect();
  1097. return result;
  1098. }
  1099. /** 向第三方请求post
  1100. *@param request:请求方式
  1101. * @param url:路径
  1102. * @param param:参数
  1103. * @param token:令牌
  1104. * @param sessionId:会话id
  1105. * @param timeOut:超时
  1106. * @param mark:标记Authorization是传哪种方式
  1107. * @param typeEnum: 编码类型
  1108. * @return 返回类型字符串
  1109. */
  1110. public String sendHttp(String requestMethod,String url, String param,String token,String sessionId,Integer timeOut,String mark,ContentTypeEnum typeEnum,String cookie) throws IOException {
  1111. String result = "";
  1112. URL postUrl = new URL(url);
  1113. // 打开连接
  1114. HttpURLConnection connection = (HttpURLConnection)postUrl.openConnection();
  1115. // 设置是否向connection输出,因为这个是post请求,参数要放在
  1116. // http正文内,因此需要设为true
  1117. connection.setDoOutput(true);
  1118. connection.setDoInput(true);
  1119. // Set the post method. Default is GET
  1120. connection.setRequestMethod(requestMethod.toUpperCase());
  1121. // Post 请求不能使用缓存
  1122. connection.setUseCaches(false);
  1123. // URLConnection.setInstanceFollowRedirects是成员函数,仅作用于当前函数
  1124. connection.setInstanceFollowRedirects(true);
  1125. // 进行编码
  1126. //connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
  1127. if (typeEnum == null){
  1128. //默认是"application/json;charset=utf-8"
  1129. connection.setRequestProperty("Content-Type","application/json;charset=utf-8");
  1130. }else {
  1131. connection.setRequestProperty("Content-Type",typeEnum.contentType);
  1132. }
  1133. if (mark != null && mark.toLowerCase().equals("bearer")){
  1134. connection.setRequestProperty("Authorization","Bearer "+token);
  1135. }else if(mark != null && mark.equals("api-key")) {
  1136. connection.setRequestProperty("api-key"," "+token);
  1137. }else {
  1138. connection.setRequestProperty("Authorization",token);
  1139. }
  1140. if (cookie != null){
  1141. connection.setRequestProperty("Cookie",cookie);
  1142. }
  1143. if (sessionId != null){
  1144. connection.setRequestProperty("SessionId"," "+sessionId);
  1145. }
  1146. if (timeOut == null || timeOut == 0){
  1147. connection.setConnectTimeout( 5000); //单位:毫秒
  1148. connection.setReadTimeout( 5000); //单位:毫秒
  1149. }else {
  1150. connection.setConnectTimeout(timeOut * 1000); //单位:毫秒
  1151. connection.setReadTimeout(timeOut * 1000); //单位:毫秒
  1152. }
  1153. // 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,
  1154. // 要注意的是connection.getOutputStream会隐含的进行connect。
  1155. connection.connect();
  1156. if (!requestMethod.equals("GET") && !requestMethod.equals("get")){
  1157. DataOutputStream out = new DataOutputStream(connection.getOutputStream());
  1158. // 正文,正文内容其实跟get的URL中'?'后的参数字符串一致
  1159. // DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写道流里面
  1160. out.writeBytes(param);
  1161. out.flush();
  1162. out.close(); // flush and close
  1163. }
  1164. BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
  1165. String line;
  1166. while ((line = reader.readLine()) != null) {
  1167. result += line;
  1168. }
  1169. reader.close();
  1170. connection.disconnect();
  1171. return result;
  1172. }
  1173. /**
  1174. * 添加设备onenet
  1175. * @param deviceId
  1176. * @return
  1177. */
  1178. public String addDeviceOnenet(String deviceId){
  1179. JSONObject device = new JSONObject();
  1180. device.put("title",deviceId);
  1181. device.put("protocol","LWM2M");
  1182. JSONObject authInfo = new JSONObject();
  1183. authInfo.put(deviceId,deviceId);
  1184. device.put("auth_info",authInfo);
  1185. String url="http://api.heclouds.com/devices";
  1186. String token = "HpumrF3BKBo3mOFIhkyf5MtIIOc=";
  1187. String respone = null;
  1188. try {
  1189. respone = this.sendHttp("post", url, device.toString(), token, null, 5, "api-key", ContentTypeEnum.CONTENT_TYPE_JSON,null);
  1190. } catch (IOException e) {
  1191. throw new RuntimeException(e);
  1192. }
  1193. return respone;
  1194. }
  1195. // 修改灯杆类型
  1196. public void setPoleType(Integer poleId,Integer type){
  1197. if (poleId != 0 || poleId != null){
  1198. LampPoleDTO lampPoleDTO = lampPoleService.getLampPoleDTOById(poleId);
  1199. String[] devArr = new String[]{};
  1200. if(lampPoleDTO.getDevType() != null){
  1201. devArr = lampPoleDTO.getDevType().split(",");
  1202. }
  1203. //是否包含某个元素
  1204. boolean ifContain = Arrays.asList(devArr).contains(type);
  1205. if (ifContain == false){
  1206. //字符串数组转换list,再添加元素
  1207. List<String> list = new ArrayList<>(Arrays.asList(devArr));
  1208. list.add(type.toString());
  1209. //list数组按规定拼接成字符串
  1210. String newDevType = list.stream().collect(Collectors.joining(","));
  1211. lampPoleDTO.setId(poleId);
  1212. lampPoleDTO.setDevType(newDevType);
  1213. lampPoleService.updateById(lampPoleDTO);
  1214. }
  1215. }
  1216. }
  1217. /**
  1218. * 操作日志
  1219. * @param request HttpServletRequest类型
  1220. * @param operation 操作(添加/删除/编辑)
  1221. * @param remark 标记(中/英/俄,拼接设备的各种需要的信息)
  1222. * @param type 类型(0-中文,1-英语,2-俄文)
  1223. * @param operaType 操作类型(0 未定义操作,1 添加,2 删除,3 编辑,4 指令,5 退出登录
  1224. * @param devtype '设备类型(0 非设备,1 路灯,2 灯杆,3 回路,4 井盖,5 垃圾桶)
  1225. * @param deviceName 设备名称/或编号
  1226. * @param area 区域名
  1227. * @param section 路段名
  1228. * @param sn 设备sn码
  1229. * @param sectionId 路段id
  1230. * @param areaId 区域id
  1231. * @param id 设备id
  1232. * @param sql_log 最后一条sql语句
  1233. */
  1234. 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){
  1235. String ip = "";
  1236. if (request.getParameter("ip") != null){
  1237. ip = request.getParameter("ip");
  1238. }else {
  1239. ip = request.getServerName();
  1240. }
  1241. try {
  1242. String location = this.getLocationByIp(ip);
  1243. Date day = new Date();
  1244. SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  1245. String updateTime = sdf.format(day);
  1246. String username = request.getParameter("username");
  1247. Integer userId = this.getUser(request).getId();
  1248. Integer os = request.getParameter("os") == null ? 0 : Integer.parseInt(request.getParameter("os"));
  1249. OperationLogDTO operationLogDTO = new OperationLogDTO();
  1250. operationLogDTO.setTime(updateTime);
  1251. operationLogDTO.setAcount(username);
  1252. operationLogDTO.setOperation(operation);
  1253. operationLogDTO.setRemark(remark);
  1254. operationLogDTO.setOs(os);
  1255. operationLogDTO.setType(type);
  1256. operationLogDTO.setOperaType(operaType);
  1257. operationLogDTO.setUserId(userId);
  1258. operationLogDTO.setDeviceName(deviceName);
  1259. operationLogDTO.setArea(area);
  1260. operationLogDTO.setSection(section);
  1261. operationLogDTO.setSn(sn);
  1262. operationLogDTO.setAreaId(areaId);
  1263. operationLogDTO.setSectionId(sectionId);
  1264. operationLogDTO.setDevId(id);
  1265. operationLogDTO.setSqlLog(sql_log);
  1266. operationLogDTO.setIpAddr(ip);
  1267. operationLogDTO.setLocation(location);
  1268. operationLogService.add(operationLogDTO);
  1269. } catch (IOException e) {
  1270. throw new RuntimeException(e);
  1271. }
  1272. }
  1273. private String getLocationByIp(String ip) throws IOException {
  1274. //把域名都转换成ip地址
  1275. ip = InetAddress.getByName(ip).getHostAddress();
  1276. IpInfoDTO infoDTO = ipInfoService.getDataByIp(ip);
  1277. String location = "";
  1278. if (infoDTO == null){
  1279. IpInfoDTO newInfoDTO = new IpInfoDTO();
  1280. if (ip.equals("127.0.0.1")){
  1281. //本地添加
  1282. location = "服务器本地";
  1283. newInfoDTO.setLocation(location);
  1284. newInfoDTO.setIpAddr(ip);
  1285. ipInfoService.add(newInfoDTO);
  1286. }else {
  1287. String url = "https://opendata.baidu.com/api.php?query="+ip+"&co=&resource_id=6006&oe=utf8";
  1288. JSONObject jsonObject = new JSONObject();
  1289. jsonObject.put("query",ip);
  1290. jsonObject.put("co",null);
  1291. jsonObject.put("resource_id",600);
  1292. jsonObject.put("oe","utf8");
  1293. String respone = this.sendHttp("get", url, jsonObject.toString(), 4, ContentTypeEnum.CONTENT_TYPE_JSON,null);
  1294. if (respone != null){
  1295. JSONObject responeJson = JSON.parseObject(respone);
  1296. String status = responeJson.getString("status");
  1297. if (status.equals("0")){
  1298. //成功
  1299. //数组
  1300. JSONArray jsonArray = responeJson.getJSONArray("data");
  1301. JSONObject item = (JSONObject)(jsonArray.get(0));
  1302. location = item.getString("location");
  1303. newInfoDTO.setLocation(location);
  1304. newInfoDTO.setIpAddr(ip);
  1305. ipInfoService.add(newInfoDTO);
  1306. }
  1307. }
  1308. }
  1309. }else {
  1310. location = infoDTO.getLocation();
  1311. }
  1312. return location;
  1313. }
  1314. /**
  1315. * 翻译故障信息 - 中英
  1316. * @param alarmStr
  1317. * @return
  1318. */
  1319. public String changeAlarm(String alarmStr){
  1320. if (alarmStr == null || alarmStr.length() == 0) return "Unknown error";
  1321. HashMap<String, String> hashMap = new HashMap<>();
  1322. hashMap.put("供电异常","Power supply anomaly");
  1323. hashMap.put("灯闪","Light flicker");
  1324. hashMap.put("灯坏","Light bad");
  1325. hashMap.put("LED驱动故障","LED drive failure");
  1326. hashMap.put("灯坏或LED驱动故障","Light bad or LED drive failure");
  1327. hashMap.put("电压过低","Low voltage");
  1328. hashMap.put("电压过高","Overvoltage");
  1329. hashMap.put("开灯故障","Turn on the lights");
  1330. hashMap.put("离线故障","Offline fault");
  1331. String[] arr = alarmStr.split(",");//内容
  1332. List<String> stringList = new ArrayList<>();//存放
  1333. for (String item: arr) {
  1334. String value = hashMap.get(item);
  1335. if (value == null){
  1336. stringList.add("Unknown error");
  1337. }else {
  1338. stringList.add(value);
  1339. }
  1340. }
  1341. //字符串拼接
  1342. return String.join(".", stringList);
  1343. }
  1344. /**
  1345. * 翻译故障信息 - 中俄
  1346. * @param alarmStr
  1347. * @return
  1348. */
  1349. public String changeAlarmRu(String alarmStr){
  1350. if (alarmStr == null || alarmStr.length() == 0) return "ошибка";
  1351. HashMap<String, String> hashMap = new HashMap<>();
  1352. hashMap.put("供电异常","Аномальный источник питания");
  1353. hashMap.put("灯闪","вспышка лампы");
  1354. hashMap.put("灯坏","лампочка");
  1355. hashMap.put("LED驱动故障","Ошибка LED-драйвера");
  1356. hashMap.put("灯坏或LED驱动故障","неисправность лампы или привода светодиода");
  1357. hashMap.put("电压过低","понижение напряжения");
  1358. hashMap.put("电压过高","избыточное напряжение");
  1359. hashMap.put("开灯故障","неисправность зажигания");
  1360. hashMap.put("离线故障","автономный отказ");
  1361. String[] arr = alarmStr.split(",");//内容
  1362. List<String> stringList = new ArrayList<>();//存放
  1363. for (String item: arr) {
  1364. String value = hashMap.get(item);
  1365. if (value == null){
  1366. stringList.add("ошибка");
  1367. }else {
  1368. stringList.add(value);
  1369. }
  1370. }
  1371. //字符串拼接
  1372. return String.join(".", stringList);
  1373. }
  1374. /**
  1375. * 上传文件/图片/音频
  1376. * @param file 文件
  1377. * @param image 图片
  1378. * @param video 音频
  1379. * @param title 名称
  1380. * @return
  1381. * @throws Exception
  1382. */
  1383. public String uploadFile(MultipartFile file, MultipartFile image,MultipartFile video, String title) throws Exception {
  1384. String rootPath = System.getProperty("user.dir");
  1385. String systemName = System.getProperty("os.name");
  1386. if (systemName.toLowerCase().contains("windows")){
  1387. //windows
  1388. int lastedIndex = rootPath.lastIndexOf("\\");
  1389. rootPath = rootPath.substring(0,lastedIndex); //工程根目录
  1390. }else {
  1391. //os/linux
  1392. int lastedIndex = rootPath.lastIndexOf("/");
  1393. rootPath = rootPath.substring(0,lastedIndex); //工程根目录
  1394. }
  1395. File imagePath; //图⽚存放地址
  1396. File fileRealPath; //⽂件存放地址
  1397. File videoPath; //音视频存在地址
  1398. if (file == null && image == null && video == null) return "0001"; //文件\图片\音频不能都不传
  1399. //获取⽂件名称
  1400. if (file != null){
  1401. //判断文件的类型
  1402. boolean b = this.fileType(file,2);
  1403. if (b == false) return "0002"; //类型不对
  1404. String pathName = "/upload/files";
  1405. fileRealPath = new File(rootPath+pathName);
  1406. //判断⽂件夹是否存在
  1407. if(!fileRealPath.exists()){
  1408. //不存在,创建
  1409. fileRealPath.mkdirs();
  1410. }
  1411. String fileName = file.getOriginalFilename();
  1412. //创建⽂件存放地址
  1413. File resultPath = new File(fileRealPath+"/"+fileName);
  1414. file.transferTo(resultPath);
  1415. System.out.println("resultPath:"+resultPath.getCanonicalPath());
  1416. return pathName+"/"+fileName;
  1417. }
  1418. if (image != null){ //图片
  1419. //判断文件的类型
  1420. boolean b = this.fileType(image,1);
  1421. if (b == false) return "0002"; //类型不对
  1422. String pathName = "/upload/images";
  1423. imagePath = new File(rootPath+pathName);
  1424. if(!imagePath.exists()){
  1425. //不存在,创建
  1426. imagePath.mkdirs();
  1427. }
  1428. String imageName = image.getOriginalFilename();
  1429. //创建图⽚存放地址
  1430. File imageResultPath = new File(imagePath+"/"+imageName);
  1431. image.transferTo(imageResultPath);
  1432. System.out.println("imageResultPath:"+imageResultPath.getCanonicalPath());
  1433. return pathName+"/"+imageName;
  1434. }
  1435. if (video != null){ //音频
  1436. //判断文件的类型
  1437. boolean b = this.fileType(video,3);
  1438. if (b == false) return "0002"; //类型不对
  1439. String pathName = "/upload/videos";
  1440. videoPath = new File(rootPath+pathName);
  1441. if(!videoPath.exists()){
  1442. //不存在,创建
  1443. videoPath.mkdirs();
  1444. }
  1445. String videoName = video.getOriginalFilename();
  1446. //创建图⽚存放地址
  1447. File videoResultPath = new File(videoPath+"/"+videoName);
  1448. video.transferTo(videoResultPath);
  1449. return pathName+"/"+videoName;
  1450. }
  1451. return "0003"; //未知问题
  1452. }
  1453. private boolean fileType(MultipartFile tempFile,int type) throws IOException {
  1454. InputStream inputStream = tempFile.getInputStream();
  1455. byte[] buffer = new byte[8];
  1456. inputStream.read(buffer);
  1457. String magicNumber = bytes2HexString(buffer);
  1458. if (magicNumber.substring(0,4).equals("FFD8") && type == 1) {
  1459. // ⽂件是JPEG/jpg类型
  1460. } else if (magicNumber.substring(0,8).equals("89504E47") && type == 1) {
  1461. // ⽂件是PNG类型
  1462. } else if (magicNumber.substring(0,8).equals("47494638") && type == 1) {
  1463. // ⽂件是GIF类型
  1464. }else if (magicNumber.substring(0,8).equals("25504446") && type == 2) {
  1465. // ⽂件是PDF类型
  1466. } else if (magicNumber.substring(0,8).equals("504B0304") && type == 2) {
  1467. // ⽂件是DOCX类型
  1468. } else if (magicNumber.substring(0,8).equals("32303230") && type == 2){
  1469. //⽂件是txt类型
  1470. }else if (magicNumber.substring(0,6).equals("494433") && type == 3){//4944330400000000
  1471. // ⽂件是mp3类型
  1472. }else {
  1473. // ⽂件类型未知
  1474. return false; //文件类型不对
  1475. }
  1476. return true;
  1477. }
  1478. /**
  1479. * 生成日志,保存在本地
  1480. * @param fileName 文件名
  1481. * @param content 日志内容
  1482. * @throws IOException
  1483. */
  1484. public void setLog(String fileName,String content) throws IOException {
  1485. String rootPath = System.getProperty("user.dir");
  1486. int lastedIndex = rootPath.lastIndexOf("/");
  1487. rootPath = rootPath.substring(0,lastedIndex); //工程根目录
  1488. String logFilePath = rootPath+"/upload/log";
  1489. SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  1490. // 创建日志文件
  1491. File logFile = new File(logFilePath);
  1492. if (!logFile.exists()) {
  1493. logFile.mkdirs(); //创建文件夹
  1494. }
  1495. String record = String.format("%s", content+"===="+dateFormat.format(new Date()));
  1496. File file = new File(logFilePath +"/"+ fileName);
  1497. try (FileWriter writer = new FileWriter(file, true)) {
  1498. writer.write(record);
  1499. writer.flush();
  1500. writer.write("\n"); // 添加一个空行,以便下次写入时定位到下一行
  1501. } catch (IOException e) {
  1502. e.printStackTrace();
  1503. }
  1504. }
  1505. /**
  1506. * 获取国标摄像头播放地址
  1507. * @param gbAddress 国标摄像头地址
  1508. * @param res
  1509. * @param vType
  1510. * @param sectionId
  1511. * @return
  1512. * @throws IOException
  1513. */
  1514. public String getGbPlayAddress(String gbAddress,String res,String vType,Integer sectionId ) throws IOException {
  1515. //Integer gb_id = Integer.valueOf(gbAddress.substring(gbAddress.length() - 7));
  1516. String gbId = gbAddress.substring(gbAddress.length() - 7);
  1517. String url = "http://"+ToolUtils.gbHost+":8060/index/api/getMediaList?secret=weclouds123";
  1518. if (res == null) res = this.sendHttp("get",url,null,5,null,null);
  1519. JSONObject parseObject = JSON.parseObject(res);
  1520. int number = Integer.parseInt(gbId);
  1521. gbId = String.format("%08x", number);
  1522. String address = "";
  1523. if (gbAddress.equals("34020000001320000120")) gbId = "55667788";
  1524. if (parseObject != null && parseObject.getInteger("code") != null && parseObject.getInteger("code") == 0){
  1525. List<Object> list = parseObject.getJSONArray("data") == null ? new ArrayList<>() : parseObject.getJSONArray("data");
  1526. int flag = 0;
  1527. for (Object obj:list) {
  1528. JSONObject item = (JSONObject) obj;
  1529. String stream = (String) item.get("stream");
  1530. Integer bytesSpeed = item.getInteger("bytesSpeed");
  1531. if (stream.toLowerCase().equals(gbId.toLowerCase()) && bytesSpeed != 0){
  1532. flag = 1;
  1533. break;
  1534. }
  1535. }
  1536. if (flag == 1){
  1537. //this.setLog("get_gb_play_address.txt",gbAddress+" old address "+this.getUser().getUsername());
  1538. if (vType == null || vType.isEmpty()){
  1539. address = "https://gb.lampmind.com:8087/gb3/rtp/"+gbId.toUpperCase()+".live.flv";
  1540. }else {
  1541. address = "https://gb.lampmind.com:8087/gb3/rtp/"+gbId.toUpperCase()+"/hls.m3u8";
  1542. }
  1543. }else {
  1544. //this.setLog("get_gb_play_address.txt",gbAddress+" new address--- "+this.getUser().getUsername());
  1545. GbPlayDTO oneData = gbPlayService.getOneData(gbAddress);
  1546. long currentTimeMillis = System.currentTimeMillis();
  1547. long seconds = currentTimeMillis / 1000;
  1548. if (oneData == null || seconds - oneData.getTime() > 5){
  1549. Integer id = Integer.valueOf(gbAddress.substring(gbAddress.length() - 7));
  1550. String resUrl = "http://"+ToolUtils.gbHost+":8089/api/play/"+gbAddress+"/"+gbAddress+"/"+id;
  1551. String res2 = this.sendHttp("get", resUrl, null, 10, null, null);
  1552. JSONObject jsonObject = JSON.parseObject(res2);
  1553. if (oneData == null){
  1554. oneData.setGbAddress(gbAddress);
  1555. oneData.setTime(seconds);
  1556. gbPlayService.addData(oneData);
  1557. }else {
  1558. oneData.setTime(seconds);
  1559. gbPlayService.updataData(oneData);
  1560. }
  1561. }
  1562. if (vType == null || vType.isEmpty()){
  1563. address = "https://gb.lampmind.com:8087/gb3/rtp/"+gbId.toUpperCase()+".live.flv";
  1564. }else {
  1565. address = "https://gb.lampmind.com:8087/gb3/rtp/"+gbId.toUpperCase()+"/hls.m3u8";
  1566. }
  1567. }
  1568. if (gbAddress.equals("34020000001320001079") || gbAddress.equals("34020000001320000762") || gbAddress.equals("3402000000132000128")){
  1569. address = "https://gb.lampmind.com:8087/gb3/rtp/"+gbId.toUpperCase()+".live.mp4";
  1570. }else {
  1571. address = "https://gb.lampmind.com:8087/gb3/rtp/"+gbId.toUpperCase()+"/hls.m3u8";
  1572. }
  1573. if (sectionId.equals(739) || sectionId.equals(593)){
  1574. address = "https://gb.lampmind.com:8087/gb3/rtp/"+gbId.toUpperCase()+".live.flv";
  1575. }
  1576. if (gbAddress.equals("34020000001320000967")){
  1577. }
  1578. String sendTopic = "/welampiot/gb28181/getImage";
  1579. String backTopic = "/welampiot/gb28181/getImage";
  1580. JSONObject jsonObject = new JSONObject();
  1581. jsonObject.put("gb_address",gbAddress);
  1582. this.sendMqttCmd(sendTopic,jsonObject.toString(),backTopic,0);
  1583. }
  1584. return address;
  1585. }
  1586. /**
  1587. * 请求 compress.zlib://这压缩类型接口
  1588. * @param url 网址
  1589. * @return 返回请求后的json字符串
  1590. */
  1591. public String zlibNetwork(String url){
  1592. try {
  1593. // 使用URL类来创建URL对象
  1594. URL resourceUrl = new URL(url);
  1595. // 打开连接
  1596. GZIPInputStream gzipInputStream = new GZIPInputStream(resourceUrl.openStream());
  1597. // 创建BufferedReader来读取数据
  1598. BufferedReader reader = new BufferedReader(new InputStreamReader(gzipInputStream));
  1599. String line;
  1600. StringBuilder content = new StringBuilder();
  1601. // 读取每一行
  1602. while ((line = reader.readLine()) != null) {
  1603. content.append(line);
  1604. }
  1605. // 输出结果
  1606. return content.toString();
  1607. } catch (IOException e) {
  1608. e.printStackTrace();
  1609. }
  1610. return "";
  1611. }
  1612. // 天气信息翻译
  1613. public String weatherTranslateEn(String code){
  1614. HashMap<String, String> map = new HashMap<>();
  1615. map.put("100","Sunny/Clear");
  1616. map.put("101","Cloudy");
  1617. map.put("102","Few Clouds");
  1618. map.put("103","Partly Cloudy");
  1619. map.put("104","Overcast");
  1620. map.put("200","Windy");
  1621. map.put("201","Calm");
  1622. map.put("202","Light Breeze");
  1623. map.put("203","Moderate/Gentle Breeze");
  1624. map.put("204","Fresh Breeze");
  1625. map.put("205","Strong Breeze");
  1626. map.put("206","High Wind, Near Gale");
  1627. map.put("207","Gale");
  1628. map.put("208","Strong Gale");
  1629. map.put("209","Storm");
  1630. map.put("210","Violent Storm");
  1631. map.put("211","Hurricane");
  1632. map.put("212","Tornado");
  1633. map.put("213","Tropical Storm");
  1634. map.put("300","Shower Rain");
  1635. map.put("301","Heavy Shower Rain");
  1636. map.put("302","Thundershower");
  1637. map.put("303","Heavy Thunderstorm");
  1638. map.put("304","Thundershower with hail");
  1639. map.put("305","Light Rain");
  1640. map.put("306","Moderate Rain");
  1641. map.put("307","Heavy Rain");
  1642. map.put("308","Extreme Rain");
  1643. map.put("309","Drizzle Rain");
  1644. map.put("310","Storm");
  1645. map.put("311","Heavy Storm");
  1646. map.put("312","Severe Storm");
  1647. map.put("313","Freezing Rain");
  1648. map.put("314","Light to moderate rain");
  1649. map.put("315","Moderate to heavy rain");
  1650. map.put("316","Heavy rain to storm");
  1651. map.put("317","Storm to heavy storm");
  1652. map.put("318","Heavy to severe storm");
  1653. map.put("399","Rain");
  1654. map.put("400","Light Snow");
  1655. map.put("401","Moderate Snow");
  1656. map.put("402","Heavy Snow");
  1657. map.put("403","Snowstorm");
  1658. map.put("404","Sleet");
  1659. map.put("405","Rain And Snow");
  1660. map.put("406","Shower Snow");
  1661. map.put("407","Snow Flurry");
  1662. map.put("408","Light to moderate snow");
  1663. map.put("409","Moderate to heavy snow");
  1664. map.put("410","Heavy snow to snowstorm");
  1665. map.put("499","Snow");
  1666. map.put("500","Mist");
  1667. map.put("501","Foggy");
  1668. map.put("502","Haze");
  1669. map.put("503","Sand");
  1670. map.put("504","Dust");
  1671. map.put("507","Duststorm");
  1672. map.put("508","Sandstorm");
  1673. map.put("509","Dense fog");
  1674. map.put("510","Strong fog");
  1675. map.put("511","Moderate haze");
  1676. map.put("512","Heavy haze");
  1677. map.put("513","Severe haze");
  1678. map.put("514","Heavy fog");
  1679. map.put("515","Extra heavy fog");
  1680. map.put("900","Hot");
  1681. map.put("901","Cold");
  1682. map.put("999","Unknown");
  1683. return map.get(code) == null ? "":map.get(code);
  1684. }
  1685. public String weatherTranslateCn(String code){
  1686. HashMap<String, String> map = new HashMap<>();
  1687. map.put("100","晴");
  1688. map.put("101","多云");
  1689. map.put("102","少云");
  1690. map.put("103","晴间多云");
  1691. map.put("104","阴");
  1692. map.put("200","有风");
  1693. map.put("201","平静");
  1694. map.put("202","微风");
  1695. map.put("203","和风");
  1696. map.put("204","清风");
  1697. map.put("205","强风/劲风");
  1698. map.put("206","疾风");
  1699. map.put("207","大风");
  1700. map.put("208","烈风");
  1701. map.put("209","风暴");
  1702. map.put("210","狂爆风");
  1703. map.put("211","飓风");
  1704. map.put("212","龙卷风");
  1705. map.put("213","热带风暴");
  1706. map.put("300","阵雨");
  1707. map.put("301","强阵雨");
  1708. map.put("302","雷阵雨");
  1709. map.put("303","强雷阵雨");
  1710. map.put("304","雷阵雨伴有冰雹");
  1711. map.put("305","小雨");
  1712. map.put("306","中雨");
  1713. map.put("307","大雨");
  1714. map.put("308","极端降雨");
  1715. map.put("309","毛毛雨/细雨");
  1716. map.put("310","暴雨");
  1717. map.put("311","大暴雨");
  1718. map.put("312","特大暴雨");
  1719. map.put("313","冻雨");
  1720. map.put("314","小到中雨");
  1721. map.put("315","中到大雨");
  1722. map.put("316","大到暴雨");
  1723. map.put("317","暴雨到大暴雨");
  1724. map.put("318","大暴雨到特大暴雨");
  1725. map.put("399","雨");
  1726. map.put("400","小雪");
  1727. map.put("401","中雪");
  1728. map.put("402","大雪");
  1729. map.put("403","暴雪");
  1730. map.put("404","雨夹雪");
  1731. map.put("405","雨雪天气");
  1732. map.put("406","阵雨夹雪");
  1733. map.put("407","阵雪");
  1734. map.put("408","小到中雪");
  1735. map.put("409","中到大雪");
  1736. map.put("410","大到暴雪");
  1737. map.put("499","雪");
  1738. map.put("500","薄雾");
  1739. map.put("501","雾");
  1740. map.put("502","霾");
  1741. map.put("503","扬沙");
  1742. map.put("504","浮尘");
  1743. map.put("507","沙尘暴");
  1744. map.put("508","强沙尘暴");
  1745. map.put("509","浓雾");
  1746. map.put("510","强浓雾");
  1747. map.put("511","中度霾");
  1748. map.put("512","重度霾");
  1749. map.put("513","严重霾");
  1750. map.put("514","大雾");
  1751. map.put("515","特强浓雾");
  1752. map.put("900","热");
  1753. map.put("901","冷");
  1754. map.put("999","未知");
  1755. return map.get(code) == null ? "":map.get(code);
  1756. }
  1757. public String weatherTranslateRu(String code){
  1758. HashMap<String, String> map = new HashMap<>();
  1759. map.put("100","чинг");
  1760. map.put("101","облачно");
  1761. map.put("102","Меньше облако");
  1762. map.put("103","Ясная и облачная");
  1763. map.put("104","инь");
  1764. map.put("200","дует");
  1765. map.put("201","спокойствие");
  1766. map.put("202","ветерок");
  1767. map.put("203","зефир");
  1768. map.put("204","Свежий ветер");
  1769. map.put("205","Сильный ветер/сильный ветер");
  1770. map.put("206","шквал");
  1771. map.put("207","ветер");
  1772. map.put("208","шторм");
  1773. map.put("209","шторм");
  1774. map.put("210","Сильный ветер");
  1775. map.put("211","ураган");
  1776. map.put("212","Торнадо");
  1777. map.put("213","Тропический шторм");
  1778. map.put("300","ливень");
  1779. map.put("301","Сильный душ");
  1780. map.put("302","Грозовой дождь");
  1781. map.put("303","Сильный грозовой дождь");
  1782. map.put("304","Ливень сопровождается градом");
  1783. map.put("305","дождик");
  1784. map.put("306","Средний дождь");
  1785. map.put("307","дождь");
  1786. map.put("308","Экстремальный дождь");
  1787. map.put("309","Дождик/мелкий дождь");
  1788. map.put("310","Проливной дождь");
  1789. map.put("311","Сильный дождь");
  1790. map.put("312","Сильный ливень");
  1791. map.put("313","Ледяной дождь");
  1792. map.put("314","Немного дождя");
  1793. map.put("315","Под дождём");
  1794. map.put("316","Большой до грозы");
  1795. map.put("317","От грозы до грозы");
  1796. map.put("318","Сильные ливни, сильные ливни");
  1797. map.put("399","дождь");
  1798. map.put("400","Мелкий снежок");
  1799. map.put("401","средний снег");
  1800. map.put("402","снегопад");
  1801. map.put("403","Снежная буря");
  1802. map.put("404","Дождь и снег");
  1803. map.put("405","Дождливая и снежная погода");
  1804. map.put("406","Дождь и снег");
  1805. map.put("407","снежный");
  1806. map.put("408","Маленький до снега");
  1807. map.put("409","Прямо в снег");
  1808. map.put("410","От большой до снежной бури");
  1809. map.put("499","снег");
  1810. map.put("500","дымка");
  1811. map.put("501","туман");
  1812. map.put("502","мгла");
  1813. map.put("503","янша");
  1814. map.put("504","пыль");
  1815. map.put("507","Песчаная буря");
  1816. map.put("508","Сильная песчаная буря");
  1817. map.put("509","Густой туман");
  1818. map.put("510","Сильный густой туман");
  1819. map.put("511","Умеренный туман");
  1820. map.put("512","Тяжелая смола");
  1821. map.put("513","Туман");
  1822. map.put("514","Сильный туман");
  1823. map.put("515","Густой туман");
  1824. map.put("900","горячая");
  1825. map.put("901","холодно");
  1826. map.put("999","неизвестный");
  1827. return map.get(code) == null ? "":map.get(code);
  1828. }
  1829. /**
  1830. * 发送wifimqtt指令
  1831. * @param sendTopic 发送的topic
  1832. * @param cmdInfo 发送的指令内容
  1833. * @param resTopic 接收指令返回的topic
  1834. * @param timeout 指令超时时间,默认是4s
  1835. * @return
  1836. */
  1837. public String sendWifiMqttCmd(String sendTopic,Object cmdInfo,String resTopic,Integer timeout){
  1838. MqttClient client;
  1839. String res = "";
  1840. if (timeout == null || timeout == 0) timeout = 4;
  1841. try {
  1842. try {
  1843. client=new MqttClient(wifiMqttConfig.getUrl(),wifiMqttConfig.getClientId()+"_"+(new Date()).getTime(),new MemoryPersistence());
  1844. MqttConnectOptions options=new MqttConnectOptions();
  1845. options.setCleanSession(true);
  1846. options.setUserName(wifiMqttConfig.getUsername());
  1847. options.setPassword(wifiMqttConfig.getPassword().toCharArray());
  1848. options.setConnectionTimeout(wifiMqttConfig.getTimeout());
  1849. options.setKeepAliveInterval(wifiMqttConfig.getKeepalive());
  1850. mqttHandler.setTopic(resTopic);
  1851. // 设置回调
  1852. client.setCallback(mqttHandler);
  1853. // 建立连接
  1854. client.connect(options);
  1855. // MqttCustomerClient.setClient(client);
  1856. client.subscribe(resTopic);
  1857. // 消息发布所需参数
  1858. MqttMessage message;
  1859. if (cmdInfo instanceof String){
  1860. message = new MqttMessage(((String) cmdInfo).getBytes());
  1861. }else {
  1862. message = new MqttMessage((byte[]) cmdInfo);
  1863. }
  1864. message.setQos(0);
  1865. client.publish(sendTopic, message);
  1866. int in = 0;
  1867. while (true){
  1868. Thread.sleep(1000);
  1869. if (mqttHandler.getRes() != null && mqttHandler.getRes().length() != 0){
  1870. res = mqttHandler.getRes();
  1871. break;
  1872. }
  1873. in ++;
  1874. if (in > 30) break;
  1875. }
  1876. client.disconnect();
  1877. }catch (Exception e){
  1878. e.printStackTrace();
  1879. }
  1880. }catch (Exception e){
  1881. e.printStackTrace();
  1882. }
  1883. return res;
  1884. }
  1885. // 风向信息翻译
  1886. public String windTranslateEn(int code,int devType){
  1887. ArrayList<String> data = new ArrayList<>();
  1888. if (devType == 7){
  1889. data.add("North wind");
  1890. data.add("northeast wind");
  1891. data.add("East wind");
  1892. data.add("Southeast wind");
  1893. data.add("South wind");
  1894. data.add("Southwest wind");
  1895. data.add("West Wind");
  1896. data.add("Northwest wind");
  1897. }else {
  1898. data.add("North northeast");
  1899. data.add("Northeast");
  1900. data.add("East Northeast");
  1901. data.add("Due east");
  1902. data.add("Southeast to East");
  1903. data.add("Southeast");
  1904. data.add("Southeast to South");
  1905. data.add("Due south");
  1906. data.add("Southwest to South");
  1907. data.add("Southwest");
  1908. data.add("Southwest by West");
  1909. data.add("due west");
  1910. data.add("Northwest by West");
  1911. data.add("Northwest");
  1912. data.add("Northwest northwest");
  1913. data.add("Due north");
  1914. }
  1915. return data.get(code) == null ? "" : data.get(code);
  1916. }
  1917. // 风向信息翻译
  1918. public String windTranslateCn(int code,int devType){
  1919. ArrayList<String> data = new ArrayList<>();
  1920. if (devType == 7){
  1921. data.add("北风");
  1922. data.add("东北风");
  1923. data.add("东风");
  1924. data.add("东南风");
  1925. data.add("南风");
  1926. data.add("西南风");
  1927. data.add("西风");
  1928. data.add("西北风");
  1929. }else {
  1930. data.add("东北偏北");
  1931. data.add("东北");
  1932. data.add("东北偏东");
  1933. data.add("正东");
  1934. data.add("东南偏东");
  1935. data.add("东南");
  1936. data.add("东南偏南");
  1937. data.add("正南");
  1938. data.add("西南偏南");
  1939. data.add("西南");
  1940. data.add("西南偏西");
  1941. data.add("正西");
  1942. data.add("西北偏西");
  1943. data.add("西北");
  1944. data.add("西北偏北");
  1945. data.add("正北");
  1946. }
  1947. return data.get(code) == null ? "" : data.get(code);
  1948. }
  1949. // 风向信息翻译
  1950. public String windTranslateRn(int code,int devType){
  1951. ArrayList<String> data = new ArrayList<>();
  1952. if (devType == 7){
  1953. data.add("Северный ветер");
  1954. data.add("северо-восточный ветер");
  1955. data.add("Восточный ветер");
  1956. data.add("Юго-восточный ветер");
  1957. data.add("Южный ветер");
  1958. data.add("Юго-западный ветер");
  1959. data.add("Западный ветер");
  1960. data.add("Северо-западный ветер");
  1961. }else {
  1962. data.add("Северо-Восток, Север");
  1963. data.add("В северо-восточной");
  1964. data.add("Северо-Восток");
  1965. data.add("восток");
  1966. data.add("Юго-Восток, северо-Восток");
  1967. data.add("В юго-восточной");
  1968. data.add("Юго-Восток, юго-Запад");
  1969. data.add("юг");
  1970. data.add("Юго-Запад, юго-Запад");
  1971. data.add("Юго-западный");
  1972. data.add("Юго-Запад, Запад");
  1973. data.add("Западу от");
  1974. data.add("Северо-Запад");
  1975. data.add("Северо -");
  1976. data.add("Северо-Запад, Север");
  1977. data.add("северное");
  1978. }
  1979. return data.get(code) == null ? "" : data.get(code);
  1980. }
  1981. // 获取国标摄像头播放地址
  1982. public String getOnvifPlayAddress(String num,Integer model,String stream) throws IOException {
  1983. String url = "http://"+ToolUtils.gbHost+":8060/index/api/getMediaList?secret=weclouds123";
  1984. String res = this.sendHttp("get",url,null,5,null,null);
  1985. String address = "";
  1986. if (res != null){
  1987. JSONObject parseObject = JSON.parseObject(res);
  1988. Integer code = parseObject.getInteger("code");
  1989. if (code == 0){
  1990. //成功
  1991. int flag = 0;
  1992. JSONArray data = parseObject.getJSONArray("data");
  1993. for (Object obj:data) {
  1994. JSONObject temp = (JSONObject)obj;
  1995. String resStream = temp.getString("stream");
  1996. Integer bytesSpeed = temp.getInteger("bytesSpeed");
  1997. if (resStream.toLowerCase().equals(stream.toLowerCase()) && !bytesSpeed.equals(0)){
  1998. flag = 1;
  1999. break;
  2000. }
  2001. }
  2002. if (flag == 1){
  2003. address = "https://gb.lampmind.com:8087/gb3/live/"+stream+"/hls.m3u8";
  2004. }else {
  2005. String top = "";
  2006. if (model == 0){
  2007. top = "WEGW";
  2008. } else if (model == 1 || model == 5) {
  2009. top = "WEGW2";
  2010. }else {
  2011. top = "WEGW3";
  2012. }
  2013. JSONObject json = new JSONObject();
  2014. json.put("reqId", 20);
  2015. json.put("msgType", "startStream");
  2016. json.put("op", "W");
  2017. JSONObject jsonStream = new JSONObject();
  2018. jsonStream.put("uuid", stream);
  2019. json.put("prop", jsonStream);
  2020. String sendData = json.toString();
  2021. String sendTopic = "/"+top+"/DevManagerIn/"+num;
  2022. String backTopic = "/"+top+"/DevManagerIn/"+num;
  2023. String back = this.sendWifiMqttCmd(sendTopic, sendData, backTopic, 5);
  2024. address = "https://gb.lampmind.com:8087/gb3/live/"+stream+"/hls.m3u8";
  2025. }
  2026. return address;
  2027. }
  2028. }
  2029. return address;
  2030. }
  2031. }