12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349 |
- package com.welampiot.utils;
- import com.alibaba.druid.support.json.JSONUtils;
- import com.alibaba.fastjson.JSON;
- import com.alibaba.fastjson.JSONArray;
- import com.alibaba.fastjson.JSONObject;
- import com.welampiot.common.BaseResult;
- import com.welampiot.common.DevInfoEnum;
- import com.welampiot.common.InterfaceResultEnum;
- import com.welampiot.common.LampControlTypeEnum;
- import com.welampiot.configuration.MqttConfig;
- import com.welampiot.configuration.PlcMqttConfig;
- import com.welampiot.dto.*;
- import com.welampiot.handle.MqttHandler;
- import com.welampiot.service.*;
- import com.welampiot.vo.DevEnumVO;
- import com.welampiot.vo.LampPoleVO;
- import org.apache.commons.httpclient.HttpClient;
- import org.apache.commons.httpclient.methods.PostMethod;
- import org.apache.poi.ss.formula.functions.T;
- import org.eclipse.paho.client.mqttv3.MqttClient;
- import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
- import org.eclipse.paho.client.mqttv3.MqttMessage;
- import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
- import org.gavaghan.geodesy.Ellipsoid;
- import org.gavaghan.geodesy.GeodeticCalculator;
- import org.gavaghan.geodesy.GeodeticCurve;
- import org.gavaghan.geodesy.GlobalCoordinates;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Component;
- import javax.servlet.http.HttpServletRequest;
- import java.io.*;
- import java.lang.reflect.Field;
- import java.net.*;
- import java.nio.charset.StandardCharsets;
- import java.text.DecimalFormat;
- import java.text.SimpleDateFormat;
- import java.util.*;
- import java.util.regex.Pattern;
- import java.util.stream.Collectors;
- import java.util.zip.CRC32;
- @Component
- public class ToolUtils {
- //http的编码
- public enum ContentTypeEnum {
- CONTENT_TYPE_JSON("application/json;charset=utf-8"),
- CONTENT_TYPE_FORM("application/x-www-form-urlencoded;charset=utf-8")
- ;
- private String contentType;
- ContentTypeEnum(String contentType) {
- this.contentType = contentType;
- }
- }
- private UserDTO user;
- @Autowired
- private UserService userService;
- @Autowired
- private SectionService sectionService;
- @Autowired
- private GlobalLocationService globalLocationService;
- @Autowired
- private MqttConfig mqttConfig;
- @Autowired
- private MqttHandler mqttHandler;
- @Autowired
- private LampPoleService lampPoleService;
- @Autowired
- private PlcMqttConfig plcMqttConfig;
- private static final String PATTERN = "^(?=.*[0-9])(?=.*[a-zA-Z]).{8,20}$";
- private static final String PATTERN_PHONE = "^1[3-9]\\d{9}$";
- private static final String PATTERN_EMAIL = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$";
- @Autowired
- private IpInfoService ipInfoService;
- @Autowired
- private OperationLogService operationLogService;
- /**
- * 获取用户所有路段 id
- * @param request
- * @return 如果返回列表为空,表示超管获取到全部路段信息,此时不需要做路段筛选
- */
- public List getSectionList(HttpServletRequest request){
- String username = request.getParameter("username");
- ArrayList<Object> sectionList = new ArrayList<>();
- if (username == null || username.toString().length() == 0) {
- sectionList.add(0);
- return sectionList;
- }
- user = userService.findUserByUserName(username);
- if (user == null) {
- sectionList.add(0);
- return sectionList;
- }
- String provinceid = request.getParameter("provinceid");
- provinceid = provinceid == null || provinceid.equals("0") ? request.getParameter("provinceId") : provinceid;
- String cityid = request.getParameter("cityid");
- cityid = cityid == null || cityid.equals("0") ? request.getParameter("cityId") : cityid;
- String areaid = request.getParameter("areaid");
- areaid = areaid == null || areaid.equals("0") ? request.getParameter("areaId") : areaid;
- String sectionid = request.getParameter("sectionid");
- sectionid = sectionid == null || sectionid.equals("0") ? request.getParameter("sectionId") : sectionid;
- if (sectionid != null && sectionid.length() != 0 && !sectionid.equals("0")){
- sectionList.add(sectionid);
- return sectionList;
- }
- String zone = user.getZoneList();
- int role = user.getRole();
- List<SectionDTO> maps;
- List<GlobalLocationDTO> globalLocationList;
- ArrayList areaList = new ArrayList<>();
- if ((cityid != null && !cityid.equals("0")) || (provinceid != null && !provinceid.equals("0")) || (areaid != null && !areaid.equals("0"))){
- if (areaid == null || areaid.equals("0")){
- ArrayList cityList = new ArrayList<>();
- if (cityid == null || cityid.equals("0")){
- globalLocationList = globalLocationService.getListByPid(Integer.valueOf(provinceid));
- if (globalLocationList.isEmpty()){
- cityid = provinceid;
- }else {
- for (GlobalLocationDTO m :globalLocationList) {
- cityList.add(m.getId());
- }
- }
- }
- if (cityList.isEmpty()){
- globalLocationList = globalLocationService.getListByPid(Integer.valueOf(cityid));
- }else {
- globalLocationList = globalLocationService.getListByPidList(cityList);
- }
- if (globalLocationList.isEmpty()){
- areaid = cityid;
- }else {
- for (GlobalLocationDTO m :globalLocationList) {
- areaList.add(m.getId());
- }
- }
- }
- }
- if ((areaid == null || areaid.length() == 0 || areaid.equals("0")) && areaList.isEmpty()){
- if (role != 1) {
- return Arrays.asList(zone.split(","));
- }else {
- return new ArrayList<>();
- }
- }else {
- if (areaid == null || areaid.equals("0")){
- maps = sectionService.getListByPidList(areaList);
- if (role != 1){
- return Arrays.asList(zone.split(","));
- }
- }else {
- System.out.println(areaid);
- int areaid2 = Integer.valueOf(areaid);
- maps = sectionService.getListByPid(areaid2);
- }
- }
- for (SectionDTO map:maps) {
- sectionList.add(map.getId());
- }
- if (sectionList.isEmpty()) sectionList.add("0");
- return sectionList;
- }
- public UserDTO getUser() {
- return user;
- }
- public UserDTO getUser(HttpServletRequest request) {
- String username = request.getParameter("username");
- ArrayList<Object> sectionList = new ArrayList<>();
- if (user == null) {
- user = userService.findUserByUserName(username);
- }
- return user;
- }
- /**
- * 返回接口信息,不带数据
- * @param code 状态码
- * @param version 语言类型 0 中文,1 英文,2 俄语
- * @return
- */
- public BaseResult response(InterfaceResultEnum resultEnum,Integer version){
- String msg;
- String code = resultEnum.getCode();
- if (version == 0){
- msg = resultEnum.getMsgCn();} else if (version == 1) {
- msg = resultEnum.getMsgEn();
- }else {
- msg = resultEnum.getMsgRu();
- }
- BaseResult<Object> objectBaseResult = new BaseResult<>(code, msg, new Object());
- Logger paramLog = LoggerFactory.getLogger("param_log");
- paramLog.info("reponse param== "+ JSON.toJSONString(objectBaseResult));
- return objectBaseResult;
- }
- /**
- * 返回接口信息,带数据
- * @param code 状态码
- * @param version 语言类型 0 中文,1 英文,2 俄语
- * @param obj 返回数据内容
- * @return
- */
- public BaseResult response(InterfaceResultEnum resultEnum,Integer version,Object obj){
- String msg;
- String code = resultEnum.getCode();
- if (version == 0){
- msg = resultEnum.getMsgCn();
- } else if (version == 1) {
- msg = resultEnum.getMsgEn();
- }else {
- msg = resultEnum.getMsgRu();
- }
- BaseResult<Object> objectBaseResult = new BaseResult<>(code, msg, obj);
- Logger paramLog = LoggerFactory.getLogger("param_log");
- paramLog.info("reponse param== "+ JSON.toJSONString(objectBaseResult));
- return objectBaseResult;
- }
- /**
- * 发送mqtt指令
- * @param sendTopic 发送的topic
- * @param cmdInfo 发送的指令内容
- * @param resTopic 接收指令返回的topic
- * @return
- */
- public String sendMqttCmd(String sendTopic,Object cmdInfo,String resTopic){
- MqttClient client;
- String res = "";
- try {
- try {
- client=new MqttClient(mqttConfig.getUrl(),mqttConfig.getClientId()+"_"+(new Date()).getTime(),new MemoryPersistence());
- MqttConnectOptions options=new MqttConnectOptions();
- options.setCleanSession(true);
- options.setUserName(mqttConfig.getUsername());
- options.setPassword(mqttConfig.getPassword().toCharArray());
- options.setConnectionTimeout(mqttConfig.getTimeout());
- options.setKeepAliveInterval(mqttConfig.getKeepalive());
- mqttHandler.setTopic(resTopic);
- // 设置回调
- client.setCallback(mqttHandler);
- // 建立连接
- client.connect(options);
- // MqttCustomerClient.setClient(client);
- client.subscribe(resTopic);
- // 消息发布所需参数
- MqttMessage message;
- if (cmdInfo instanceof String){
- message = new MqttMessage(((String) cmdInfo).getBytes());
- }else {
- message = new MqttMessage((byte[]) cmdInfo);
- }
- message.setQos(0);
- client.publish(sendTopic, message);
- int in = 0;
- while (true){
- Thread.sleep(1000);
- if (mqttHandler.getRes() != null && mqttHandler.getRes().length() != 0){
- res = mqttHandler.getRes();
- break;
- }
- in ++;
- if (in > 30) break;
- }
- client.disconnect();
- }catch (Exception e){
- e.printStackTrace();
- }
- }catch (Exception e){
- e.printStackTrace();
- }
- return res;
- }
- /**
- * 发送mqtt指令
- * @param sendTopic 发送的topic
- * @param cmdInfo 发送的指令内容
- * @param resTopic 接收指令返回的topic
- * @param timeout 指令超时时间
- * @return
- */
- public String sendMqttCmd(String sendTopic,Object cmdInfo,String resTopic,Integer timeout){
- MqttClient client;
- String res = "";
- try {
- try {
- client=new MqttClient(mqttConfig.getUrl(),mqttConfig.getClientId()+"_"+(new Date()).getTime(),new MemoryPersistence());
- MqttConnectOptions options=new MqttConnectOptions();
- options.setCleanSession(true);
- options.setUserName(mqttConfig.getUsername());
- options.setPassword(mqttConfig.getPassword().toCharArray());
- options.setConnectionTimeout(mqttConfig.getTimeout());
- options.setKeepAliveInterval(mqttConfig.getKeepalive());
- mqttHandler.setTopic(resTopic);
- // 设置回调
- client.setCallback(mqttHandler);
- // 建立连接
- client.connect(options);
- // MqttCustomerClient.setClient(client);
- client.subscribe(resTopic);
- // 消息发布所需参数
- MqttMessage message;
- if (cmdInfo instanceof String){
- message = new MqttMessage(((String) cmdInfo).getBytes());
- }else {
- message = new MqttMessage((byte[]) cmdInfo);
- }
- message.setQos(0);
- client.publish(sendTopic, message);
- int in = 0;
- if (timeout > 0){
- while (true){
- Thread.sleep(1000);
- if (mqttHandler.getRes() != null && mqttHandler.getRes().length() != 0){
- res = mqttHandler.getRes();
- break;
- }
- in ++;
- if (in > timeout) break;
- }
- }
- client.disconnect();
- }catch (Exception e){
- e.printStackTrace();
- }
- }catch (Exception e){
- e.printStackTrace();
- }
- return res;
- }
- /**
- * 发送mqtt指令
- * @param sendTopic 发送的topic
- * @param cmdInfo 发送的指令内容
- * @param resTopic 接收指令返回的topic
- * @return
- */
- public String plcSendMqttCmd(String sendTopic,Object cmdInfo,String resTopic){
- MqttClient client;
- String res = "";
- try {
- try {
- client=new MqttClient(plcMqttConfig.getUrl(),plcMqttConfig.getClientId()+"_"+(new Date()).getTime(),new MemoryPersistence());
- MqttConnectOptions options=new MqttConnectOptions();
- options.setCleanSession(true);
- options.setUserName(plcMqttConfig.getUsername());
- options.setPassword(plcMqttConfig.getPassword().toCharArray());
- options.setConnectionTimeout(plcMqttConfig.getTimeout());
- options.setKeepAliveInterval(plcMqttConfig.getKeepalive());
- mqttHandler.setTopic(resTopic);
- // 设置回调
- client.setCallback(mqttHandler);
- // 建立连接
- client.connect(options);
- // MqttCustomerClient.setClient(client);
- client.subscribe(resTopic);
- // 消息发布所需参数
- MqttMessage message;
- if (cmdInfo instanceof String){
- message = new MqttMessage(((String) cmdInfo).getBytes());
- }else {
- message = new MqttMessage((byte[]) cmdInfo);
- }
- message.setQos(0);
- client.publish(sendTopic, message);
- int in = 0;
- while (true){
- Thread.sleep(1000);
- if (mqttHandler.getRes() != null && mqttHandler.getRes().length() != 0){
- res = mqttHandler.getRes();
- break;
- }
- in ++;
- if (in > 30) break;
- }
- client.disconnect();
- }catch (Exception e){
- e.printStackTrace();
- }
- }catch (Exception e){
- e.printStackTrace();
- }
- return res;
- }
- /**
- * 发送mqtt指令
- * @param sendTopic 发送的topic
- * @param cmdInfo 发送的指令内容
- * @param resTopic 接收指令返回的topic
- * @param timeout 指令超时时间
- * @return
- */
- public String plcSendMqttCmd(String sendTopic,String cmdInfo, String resTopic, Integer timeout){
- MqttClient client;
- String res = "";
- try {
- try {
- client=new MqttClient(plcMqttConfig.getUrl(),plcMqttConfig.getClientId()+"_"+(new Date()).getTime(),new MemoryPersistence());
- MqttConnectOptions options=new MqttConnectOptions();
- options.setCleanSession(true);
- options.setUserName(plcMqttConfig.getUsername());
- options.setPassword(plcMqttConfig.getPassword().toCharArray());
- options.setConnectionTimeout(plcMqttConfig.getTimeout());
- options.setKeepAliveInterval(plcMqttConfig.getKeepalive());
- mqttHandler.setTopic(resTopic);
- // 设置回调
- client.setCallback(mqttHandler);
- // 建立连接
- client.connect(options);
- // MqttCustomerClient.setClient(client);
- client.subscribe(resTopic);
- // 消息发布所需参数
- MqttMessage message;
- message = new MqttMessage(cmdInfo.getBytes());
- message.setQos(0);
- client.publish(sendTopic, message);
- System.out.println("==send:"+sendTopic+"====res:"+resTopic);
- int in = 0;
- if (timeout > 0){
- while (true){
- System.out.println("==d====:"+in+"====");
- Thread.sleep(100);
- if (mqttHandler.getRes() != null && mqttHandler.getRes().length() != 0){
- res = mqttHandler.getRes();
- System.out.println(res);
- //原来的
- JSONObject oldObject = JSON.parseObject(cmdInfo);
- String oldDataType = oldObject.getObject("dataType", String.class);
- // String[] oldThirdIdArr = oldObject.getObject("thirdId",String.class).split("-");
- // String[] oldSnArr = oldThirdIdArr[0].split(":");
- // String oldSn = oldSnArr[1]; //设备地址
- // String[] oldNumberArr = oldThirdIdArr[1].split(":");
- // int oldNum = Integer.parseInt(oldNumberArr[1]); //设备灯序号
- //解析json
- JSONObject jsonObject = JSON.parseObject(res);
- String dataType = jsonObject.getObject("dataType", String.class);
- // String[] thirdIdArr = jsonObject.getObject("thirdId",String.class).split("-");
- // String[] snArr = thirdIdArr[0].split(":");
- // String sn = snArr[1]; //设备地址
- // String[] numberArr = thirdIdArr[1].split(":");
- // int num = Integer.parseInt(numberArr[1]); //设备灯序号
- //它是字符串
- if (dataType.equals("lightStatus") ){ //1.读取灯信息,2.调光的
- //原来的
- String[] oldThirdIdArr = oldObject.getObject("thirdId",String.class).split("-");
- String[] oldSnArr = oldThirdIdArr[0].split(":");
- String oldSn = oldSnArr[1]; //设备地址
- String[] oldNumberArr = oldThirdIdArr[1].split(":");
- int oldNum = Integer.parseInt(oldNumberArr[1]); //设备灯序号
- //解析json
- String[] thirdIdArr = jsonObject.getObject("thirdId",String.class).split("-");
- String[] snArr = thirdIdArr[0].split(":");
- String sn = snArr[1]; //设备地址
- String[] numberArr = thirdIdArr[1].split(":");
- int num = Integer.parseInt(numberArr[1]); //设备灯序号
- //类型相等
- System.out.println("====ddd:"+oldSn+"====sn:"+sn+"====ol:"+oldNum+"==nu:"+num);
- if ((oldDataType.equals("lightStatus") || oldDataType.equals("adjustLightController")) && oldSn.equals(sn) && (oldNum == num)){
- //查看灯的信息
- System.out.println("====ddd:"+res);
- return res;
- }
- }
- }
- in ++;
- if (in > timeout) return null;
- }
- }
- client.disconnect();
- }catch (Exception e){
- System.out.println("==dd=="+e);
- e.printStackTrace();
- }
- }catch (Exception e){
- System.out.println(e);
- e.printStackTrace();
- }
- return null;
- }
- /**
- * 字节数组转16进制字符串
- * @param b 字节数组
- * @return 16进制字符串
- * @throws
- */
- public String bytes2HexString(byte[] b) {
- StringBuffer result = new StringBuffer();
- String hex;
- for (int i = 0; i < b.length; i++) {
- hex = Integer.toHexString(b[i] & 0xFF);
- if (hex.length() == 1) {
- hex = '0' + hex;
- }
- result.append(hex.toUpperCase());
- }
- return result.toString();
- }
- /**
- * 16进制字符串转字节数组
- * @param src 16进制字符串
- * @return 字节数组
- * @throws
- */
- public byte[] hexString2Bytes(String src) {
- int l = src.length() / 2;
- byte[] ret = new byte[l];
- for (int i = 0; i < l; i++) {
- ret[i] = (byte) Integer
- .valueOf(src.substring(i * 2, i * 2 + 2), 16).byteValue();
- }
- return ret;
- }
- /**
- * 获取CRC32校验码
- * @param src 16进制字符串
- * @return CRC32校验码
- */
- public String getCRC32ByHexString2Bytes(String src) {
- CRC32 crc32 = new CRC32();
- crc32.update(this.hexString2Bytes(src));
- return Integer.toHexString((int) crc32.getValue());
- }
- /**
- * 计算modbus CRC16校验码
- * @param bytes 需要计算的数据
- * @return
- */
- public String getCRC(byte[] bytes) {
- // CRC寄存器全为1
- int CRC = 0x0000ffff;
- // 多项式校验值
- int POLYNOMIAL = 0x0000a001;
- int i, j;
- for (i = 0; i < bytes.length; i++) {
- CRC ^= ((int) bytes[i] & 0x000000ff);
- for (j = 0; j < 8; j++) {
- if ((CRC & 0x00000001) != 0) {
- CRC >>= 1;
- CRC ^= POLYNOMIAL;
- } else {
- CRC >>= 1;
- }
- }
- }
- // 结果转换为16进制
- String result = Integer.toHexString(CRC).toUpperCase();
- if (result.length() != 4) {
- StringBuffer sb = new StringBuffer("0000");
- result = sb.replace(4 - result.length(), 4, result).toString();
- }
- //高位在前地位在后
- //return result.substring(2, 4) + " " + result.substring(0, 2);
- // 交换高低位,低位在前高位在后
- return result.substring(2, 4)+result.substring(0, 2);
- }
- public String getCRC(String cmd) {
- byte[] bytes = this.hexString2Bytes(cmd);
- // CRC寄存器全为1
- int CRC = 0x0000ffff;
- // 多项式校验值
- int POLYNOMIAL = 0x0000a001;
- int i, j;
- for (i = 0; i < bytes.length; i++) {
- CRC ^= ((int) bytes[i] & 0x000000ff);
- for (j = 0; j < 8; j++) {
- if ((CRC & 0x00000001) != 0) {
- CRC >>= 1;
- CRC ^= POLYNOMIAL;
- } else {
- CRC >>= 1;
- }
- }
- }
- // 结果转换为16进制
- String result = Integer.toHexString(CRC).toUpperCase();
- if (result.length() != 4) {
- StringBuffer sb = new StringBuffer("0000");
- result = sb.replace(4 - result.length(), 4, result).toString();
- }
- //高位在前地位在后
- //return result.substring(2, 4) + " " + result.substring(0, 2);
- // 交换高低位,低位在前高位在后
- return result.substring(2, 4)+result.substring(0, 2);
- }
- public Object getRequestContent(HttpServletRequest request,String key){
- return request.getParameter(key);
- }
- /**
- * 获取请求参数
- * @param request 请求对象
- * @param key 参数值
- * @param type 参数类型 1 int 2 string
- * @return
- */
- public Object getRequestContent(HttpServletRequest request,String key,Integer type){
- if (type == 1){ // 获取 int 数据
- Integer keyId = request.getParameter(key) == null || request.getParameter(key).length() == 0? 0 : Integer.parseInt(request.getParameter(key));
- return keyId;
- }else if (type == 2){
- String keyStr = request.getParameter(key) == null ? "" : request.getParameter(key).toString();
- return keyStr.trim();
- }
- return request.getParameter(key);
- }
- /**
- * 发送post请求
- * @param url 请求地址
- * @param paraMap 请求参数
- * @return
- */
- public String httpPost(String url,Map paraMap){
- HttpClient httpClient = new HttpClient();
- httpClient.getHttpConnectionManager().getParams().setSoTimeout(30000);
- PostMethod postMethod = new PostMethod(url);
- postMethod.addRequestHeader("accept", "*/*");
- //设置Content-Type
- postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
- //添加请求参数
- Set set = paraMap.keySet();
- for (Object s : set) {
- postMethod.addParameter((String) s, (String) paraMap.get(s));
- }
- String result = "";
- try {
- int code = httpClient.executeMethod(postMethod);
- if (code == 200){
- result = postMethod.getResponseBodyAsString();
- }
- } catch (IOException e) {
- // e.printStackTrace();
- }
- return result;
- }
- /**
- * 发送post请求
- * @param url 请求地址
- * @param paraMap 请求参数
- * @param timeout 超时时间
- * @return
- */
- public String httpPost(String url,Map paraMap,int timeout){
- HttpClient httpClient = new HttpClient();
- httpClient.getHttpConnectionManager().getParams().setSoTimeout(timeout);
- PostMethod postMethod = new PostMethod(url);
- postMethod.addRequestHeader("accept", "*/*");
- //设置Content-Type
- postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
- //添加请求参数
- Set set = paraMap.keySet();
- for (Object s : set) {
- postMethod.addParameter((String) s, (String) paraMap.get(s));
- }
- String result = "";
- try {
- int code = httpClient.executeMethod(postMethod);
- if (code == 200){
- result = postMethod.getResponseBodyAsString();
- }
- } catch (IOException e) {
- // e.printStackTrace();
- }
- return result;
- }
- /**
- * 通过id获取控制器型号名称
- * @param id
- * @return
- */
- public String getLampControlNameById(Integer id){
- for (LampControlTypeEnum value : LampControlTypeEnum.values()) {
- if (value.getId().intValue() == id.intValue()){
- return value.getName();
- }
- }
- return "";
- }
- /**
- * 通过控制器型号名称获取型号id
- * @param name
- * @return
- */
- public Integer getLampControlIdByName(String name){
- for (LampControlTypeEnum value : LampControlTypeEnum.values()) {
- if (value.getName().equals(name)){
- return value.getId();
- }
- }
- return 0;
- }
- /**
- * 获取文件的大小
- * @param path 文件的路径
- * @return 返回文件的大小(四舍五入)
- */
- public String getFileSize(String path) throws IOException {
- String urlStr = path;
- if (!urlStr.contains("https://") && !urlStr.contains("http://")) {
- urlStr = "http://" + urlStr;
- }
- URL url = new URL(urlStr);
- URLConnection connection = url.openConnection();
- long fileSize = connection.getContentLengthLong();
- DecimalFormat decimalFormat = new DecimalFormat("0.00");
- if (fileSize != -1) {
- double fileSizeMB = (double) fileSize / (1024 * 1024);
- return decimalFormat.format(fileSizeMB);
- } else {
- return null;
- }
- }
- /**
- * 计算两个经纬度之间的距离
- * @param gpsFrom 第一个经纬度坐标点
- * @param gpsTo 第二个经纬度坐标点
- * @param ellipsoid 坐标系
- * @return 返回两者之间的距离
- */
- public static double getDistanceMeter(GlobalCoordinates gpsFrom, GlobalCoordinates gpsTo, Ellipsoid ellipsoid) {
- //创建GeodeticCalculator,调用计算方法,传入坐标系,经纬度用于计算距离
- GeodeticCurve geoCurve = new GeodeticCalculator().calculateGeodeticCurve(ellipsoid, gpsFrom, gpsTo);
- return geoCurve.getEllipsoidalDistance();
- }
- /**
- * 检查密码、手机号码、邮箱格式是否正确
- * @param dataFormat 0:密码,1:手机,2:邮箱
- * @return true、false
- */
- public static Boolean checkDataFormat(String dataFormat, Integer type) {
- boolean isFlag;
- if (type == 2) { // 邮箱
- isFlag = Pattern.matches(PATTERN_EMAIL, dataFormat);
- } else if (type == 1) { // 手机
- isFlag = Pattern.matches(PATTERN_PHONE, dataFormat);
- } else { // 密码
- isFlag = Pattern.matches(PATTERN, dataFormat);
- }
- return isFlag;
- }
- /**
- * 获取云盒气象站485设备列表
- * @param devInfoEnum 枚举类数组
- * @param version 语言版本
- * @return 云盒气象站485设备列表
- */
- public static List<DevEnumVO> getDevEnum(List<DevInfoEnum> devInfoEnum, Integer version) {
- List<DevEnumVO> list = new ArrayList<>();
- for (DevInfoEnum d : devInfoEnum) {
- String name;
- if (version == 0) {
- name = d.getNameCh();
- } else if (version == 1) {
- name = d.getNameEn();
- } else {
- name = d.getNameRu();
- }
- list.add(new DevEnumVO(d.getId(), name));
- }
- return list;
- }
- /**
- * 获取枚举类数组
- * @return 枚举类数组
- */
- public static List<DevInfoEnum> addAllEnum() {
- List<DevInfoEnum> list = new ArrayList<>();
- list.add(DevInfoEnum.LOUVER_BOX6);
- list.add(DevInfoEnum.WIND_DIRECTION);
- list.add(DevInfoEnum.WIND_SPEED);
- list.add(DevInfoEnum.RAINFALL);
- list.add(DevInfoEnum.SOLAR_RADIATION);
- list.add(DevInfoEnum.LOUVER_BOX10);
- list.add(DevInfoEnum.SOLAR_WIND_SPEED_DIRT);
- return list;
- }
- /**
- * 修改灯杆上绑定设备的设备类型
- * @param devType 灯杆绑定的设备类型
- * @param type 设备类型
- * @param lampPoleId 灯杆id
- */
- public void updateLampPoleDevType(String devType, Integer type, Integer lampPoleId) {
- String[] split = devType.split(",");
- String value = String.valueOf(type);
- StringJoiner joiner = new StringJoiner(",");
- for (String s : split) {
- if (!s.equals(value)) {
- joiner.add(s);
- }
- }
- String newDevType = joiner.toString();
- LampPoleDTO lampPoleDTO = new LampPoleDTO();
- lampPoleDTO.setId(lampPoleId);
- lampPoleDTO.setDevType(newDevType);
- lampPoleService.updateLampPoleDevType(lampPoleDTO);
- }
- /**
- * 获取策略内容描述
- * @param policyType 策略类型
- * @param cmd 指令内容
- * @return 策略内容描述
- */
- public static String getLightStripContent(String policyType, String cmd) {
- String content;
- switch (policyType) {
- case "0":
- content = ("常亮(颜色:" + cmd + ")");
- break;
- case "1":
- switch (cmd) {
- case "1":
- content = ("红灯呼吸");
- break;
- case "2":
- content = ("绿灯呼吸");
- break;
- case "3":
- content = ("蓝灯呼吸");
- break;
- case "4":
- content = ("RGB呼吸");
- break;
- case "5":
- content = ("黄灯呼吸");
- break;
- case "6":
- content = ("紫灯呼吸");
- break;
- default:
- content = "";
- break;
- }
- break;
- case "2":
- switch (cmd) {
- case "1":
- content = ("红灯爆闪");
- break;
- case "2":
- content = ("绿灯爆闪");
- break;
- case "3":
- content = ("蓝灯爆闪");
- break;
- case "4":
- content = ("白色爆闪");
- break;
- case "5":
- content = ("7色爆闪");
- break;
- case "6":
- content = ("黄灯爆闪");
- break;
- case "7":
- content = ("紫灯爆闪");
- break;
- default:
- content = "";
- break;
- }
- break;
- case "3":
- content = ("关灯");
- break;
- case "4":
- switch (cmd) {
- case "1":
- content = ("红灯闪烁");
- break;
- case "2":
- content = ("绿灯闪烁");
- break;
- case "3":
- content = ("蓝灯闪烁");
- break;
- case "4":
- content = ("白色闪烁");
- break;
- case "5":
- content = ("7色闪烁");
- break;
- case "6":
- content = ("黄灯闪烁");
- break;
- case "7":
- content = ("紫灯闪烁");
- break;
- default:
- content = "";
- break;
- }
- break;
- default:
- content = "";
- break;
- }
- return content;
- }
- /**
- * 获取plc策略内容
- * @param p plc策略内容对象
- * @return plc策略内容
- * @throws NoSuchFieldException 对象中没有该属性抛出的异常
- * @throws IllegalAccessException 类型非法转换抛出的异常
- */
- public static List<String> getPlcPolicyValue(PlcPolicyCmdDTO p) throws NoSuchFieldException, IllegalAccessException {
- List<String> value = new ArrayList<>();
- if (p.getBaseTimeType() == 0) { // 零点
- for (int i = 1; i <= 6; i ++) {
- Field fieldStartTime = p.getClass().getDeclaredField("startTime" + i);
- fieldStartTime.setAccessible(true);
- String startTime = (String) fieldStartTime.get(p);
- if (startTime == null || startTime.isEmpty()) break;
- Field fieldEndTime = p.getClass().getDeclaredField("endTime" + i);
- fieldEndTime.setAccessible(true);
- String endTime = (String) fieldEndTime.get(p);
- // 亮度
- Field fieldStartBright = p.getClass().getDeclaredField("bright" + i);
- fieldStartBright.setAccessible(true);
- Integer startBright = (Integer) fieldStartBright.get(p);
- // 色温
- Field fieldStartColor = p.getClass().getDeclaredField("color" + i);
- fieldStartColor.setAccessible(true);
- Integer startColor = (Integer) fieldStartColor.get(p);
- if (endTime != null && !endTime.isEmpty()) {
- String tips = startTime + " - " + endTime + " 亮度" + startBright + "% 色温" + startColor + "k";
- value.add(tips);
- Field fieldStartTime2 = p.getClass().getDeclaredField("startTime" + (i + 1));
- fieldStartTime2.setAccessible(true);
- String startTime2 = (String) fieldStartTime2.get(p);
- // 亮度
- Field fieldEndBright = p.getClass().getDeclaredField("endBright" + i);
- fieldEndBright.setAccessible(true);
- Integer endBright = (Integer) fieldEndBright.get(p);
- // 色温
- Field fieldEndColor = p.getClass().getDeclaredField("endColor" + i);
- fieldEndColor.setAccessible(true);
- Integer endColor = (Integer) fieldEndColor.get(p);
- if (startTime2 != null && !startTime2.isEmpty()) {
- String tips1 = endTime + " - " + startTime2 + " 亮度" + endBright + "% 色温" + endColor + "k";
- value.add(tips1);
- } else {
- String tips1 = endTime + " - " + " 亮度" + endBright + "% 色温" + endColor + "k";
- value.add(tips1);
- break;
- }
- } else {
- String tips = startTime + " - " + " 亮度" + startBright + "% 色温" + startColor + "k";
- value.add(tips);
- break;
- }
- }
- } else { // 日出日落
- String startDelayTime = p.getStartDelayTime();
- Integer startBright = p.getStartBright();
- Integer startColor = p.getStartColor();
- String tips1,tips2;
- int startTime = Integer.parseInt(startDelayTime);
- if (startTime >= 0) {
- tips1 = "日出推迟" + startTime + "分钟 亮度" + startBright + "% 色温" + startColor + "k";
- } else {
- startTime = -startTime;
- tips1 = "日出提前" + startTime + "分钟 亮度" + startBright + "% 色温" + startColor + "k";
- }
- String endDelayTime = p.getEndDelayTime();
- Integer endBright = p.getEndBright();
- Integer endColor = p.getEndColor();
- int endTime = Integer.parseInt(endDelayTime);
- if (endTime >= 0) {
- tips2 = "日落推迟" + endTime + "分钟 亮度" + endBright + "% 色温" + endColor + "k";
- } else {
- endTime = -endTime;
- tips2 = "日落提前" + endTime + "分钟 亮度" + endBright + "% 色温" + endColor + "k";
- }
- value.add(tips1);
- value.add(tips2);
- }
- return value;
- }
- /**
- * 获取协议类型字符串
- * @param protocolType 协议类型
- * @return 协议类型字符串
- */
- public static String getProtocolTypeStr(Integer protocolType) {
- String protocolTypeStr;
- switch (protocolType) {
- case 12 :
- protocolTypeStr = ("铂胜lora");
- break;
- case 11 :
- protocolTypeStr = ("PLC(有单灯,也有双灯控制器)");
- break;
- case 10 :
- protocolTypeStr = ("WE-CON-4G20(双路控制)");
- break;
- case 9 :
- protocolTypeStr = ("LC-6B11-J");
- break;
- case 8 :
- protocolTypeStr = ("eMqtt");
- break;
- case 7 :
- protocolTypeStr = ("oneNet");
- break;
- case 6 :
- protocolTypeStr = ("LoraWAN");
- break;
- case 5 :
- protocolTypeStr = ("zigbee");
- break;
- case 4 :
- protocolTypeStr = ("gprs_direct");
- break;
- case 3 :
- protocolTypeStr = ("nbIot");
- break;
- case 2 :
- protocolTypeStr = ("rf mesh");
- break;
- case 1 :
- protocolTypeStr = ("lora mesh");
- break;
- default :
- protocolTypeStr = ("lorawan");
- break;
- }
- return protocolTypeStr;
- }
- /* 向第三方请求post
- *@param requestMethod:请求方式
- * @param url:路径
- * @param param:参数
- * @param ContentTypeEnum: 编码类型
- * @return 返回类型字符串
- */
- public String sendHttp(String requestMethod,String url, String param,Integer timeOut,ContentTypeEnum typeEnum,String cookie) throws IOException {
- String result = "";
- URL postUrl = new URL(url);
- // 打开连接
- HttpURLConnection connection = (HttpURLConnection)postUrl.openConnection();
- // 设置是否向connection输出,因为这个是post请求,参数要放在
- // http正文内,因此需要设为true
- connection.setDoOutput(true);
- connection.setDoInput(true);
- if (timeOut == null || timeOut == 0){
- connection.setConnectTimeout( 5000); //单位:毫秒
- connection.setReadTimeout( 5000); //单位:毫秒
- }else {
- connection.setConnectTimeout(timeOut * 1000); //单位:毫秒
- connection.setReadTimeout(timeOut * 1000); //单位:毫秒
- }
- // Set the post method. Default is GET
- connection.setRequestMethod(requestMethod.toUpperCase());
- // Post 请求不能使用缓存
- connection.setUseCaches(false);
- // URLConnection.setInstanceFollowRedirects是成员函数,仅作用于当前函数
- connection.setInstanceFollowRedirects(true);
- // 进行编码
- if (typeEnum == null){
- //默认是"application/json;charset=utf-8"
- connection.setRequestProperty("Content-Type","application/json;charset=utf-8");
- }else {
- connection.setRequestProperty("Content-Type",typeEnum.contentType);
- }
- if (cookie != null){
- connection.setRequestProperty("Cookie",cookie);
- }
- // 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,
- // 要注意的是connection.getOutputStream会隐含的进行connect。
- connection.connect();
- if (!requestMethod.equals("GET") && !requestMethod.equals("get")){
- DataOutputStream out = new DataOutputStream(connection.getOutputStream());
- // 正文,正文内容其实跟get的URL中'?'后的参数字符串一致
- // DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写道流里面
- out.writeBytes(param);
- out.flush();
- out.close(); // flush and close
- }
- //读取服务器返回的数据
- BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
- String line;
- while ((line = reader.readLine()) != null) {
- result += line;
- }
- reader.close();
- connection.disconnect();
- return result;
- }
- /* 向第三方请求post
- *@param request:请求方式
- * @param url:路径
- * @param param:参数
- * @param token:令牌
- * @param sessionId:会话id
- * @param timeOut:超时
- * @param mark:标记Authorization是传哪种方式
- * @param typeEnum: 编码类型
- * @return 返回类型字符串
- */
- public String sendHttp(String requestMethod,String url, String param,String token,String sessionId,Integer timeOut,String mark,ContentTypeEnum typeEnum,String cookie) throws IOException {
- String result = "";
- URL postUrl = new URL(url);
- // 打开连接
- HttpURLConnection connection = (HttpURLConnection)postUrl.openConnection();
- // 设置是否向connection输出,因为这个是post请求,参数要放在
- // http正文内,因此需要设为true
- connection.setDoOutput(true);
- connection.setDoInput(true);
- // Set the post method. Default is GET
- connection.setRequestMethod(requestMethod.toUpperCase());
- // Post 请求不能使用缓存
- connection.setUseCaches(false);
- // URLConnection.setInstanceFollowRedirects是成员函数,仅作用于当前函数
- connection.setInstanceFollowRedirects(true);
- // 进行编码
- //connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
- if (typeEnum == null){
- //默认是"application/json;charset=utf-8"
- connection.setRequestProperty("Content-Type","application/json;charset=utf-8");
- }else {
- connection.setRequestProperty("Content-Type",typeEnum.contentType);
- }
- if (mark != null && mark.toLowerCase().equals("bearer")){
- connection.setRequestProperty("Authorization","Bearer "+token);
- }else if(mark != null && mark.equals("api-key")) {
- connection.setRequestProperty("api-key"," "+token);
- }else {
- connection.setRequestProperty("Authorization",token);
- }
- if (cookie != null){
- connection.setRequestProperty("Cookie",cookie);
- }
- if (sessionId != null){
- connection.setRequestProperty("SessionId"," "+sessionId);
- }
- if (timeOut == null || timeOut == 0){
- connection.setConnectTimeout( 5000); //单位:毫秒
- connection.setReadTimeout( 5000); //单位:毫秒
- }else {
- connection.setConnectTimeout(timeOut * 1000); //单位:毫秒
- connection.setReadTimeout(timeOut * 1000); //单位:毫秒
- }
- // 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,
- // 要注意的是connection.getOutputStream会隐含的进行connect。
- connection.connect();
- if (!requestMethod.equals("GET") && !requestMethod.equals("get")){
- DataOutputStream out = new DataOutputStream(connection.getOutputStream());
- // 正文,正文内容其实跟get的URL中'?'后的参数字符串一致
- // DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写道流里面
- out.writeBytes(param);
- out.flush();
- out.close(); // flush and close
- }
- BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
- String line;
- while ((line = reader.readLine()) != null) {
- result += line;
- }
- reader.close();
- connection.disconnect();
- return result;
- }
- // 添加设备onenet
- public String addDeviceOnenet(String deviceId){
- JSONObject device = new JSONObject();
- device.put("title",deviceId);
- device.put("protocol","LWM2M");
- JSONObject authInfo = new JSONObject();
- authInfo.put(deviceId,deviceId);
- device.put("auth_info",authInfo);
- String url="http://api.heclouds.com/devices";
- String token = "HpumrF3BKBo3mOFIhkyf5MtIIOc=";
- String respone = null;
- try {
- respone = this.sendHttp("post", url, device.toString(), token, null, 5, "api-key", ContentTypeEnum.CONTENT_TYPE_JSON,null);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- return respone;
- }
- // 修改灯杆类型
- public void setPoleType(Integer poleId,Integer type){
- if (poleId != 0 || poleId != null){
- LampPoleDTO lampPoleDTO = lampPoleService.getLampPoleDTOById(poleId);
- String[] devArr = new String[]{};
- if(lampPoleDTO.getDevType() != null){
- devArr = lampPoleDTO.getDevType().split(",");
- }
- //是否包含某个元素
- boolean ifContain = Arrays.asList(devArr).contains(type);
- if (ifContain == false){
- //字符串数组转换list,再添加元素
- List<String> list = new ArrayList<>(Arrays.asList(devArr));
- list.add(type.toString());
- //list数组按规定拼接成字符串
- String newDevType = list.stream().collect(Collectors.joining(","));
- lampPoleDTO.setId(poleId);
- lampPoleDTO.setDevType(newDevType);
- lampPoleService.updateById(lampPoleDTO);
- }
- }
- }
- //操作日志
- 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){
- String ip = "";
- if (request.getParameter("ip") != null){
- ip = request.getParameter("ip");
- }else {
- ip = request.getServerName();
- }
- try {
- String location = this.getLocationByIp(ip);
- Date day = new Date();
- SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- String updateTime = sdf.format(day);
- String username = request.getParameter("username");
- Integer userId = this.getUser(request).getId();
- Integer os = request.getParameter("os") == null ? 0 : Integer.parseInt(request.getParameter("os"));
- OperationLogDTO operationLogDTO = new OperationLogDTO();
- operationLogDTO.setTime(updateTime);
- operationLogDTO.setAcount(username);
- operationLogDTO.setOperation(operation);
- operationLogDTO.setRemark(remark);
- operationLogDTO.setOs(os);
- operationLogDTO.setType(type);
- operationLogDTO.setOperaType(operaType);
- operationLogDTO.setUserId(userId);
- operationLogDTO.setDeviceName(deviceName);
- operationLogDTO.setArea(area);
- operationLogDTO.setSection(section);
- operationLogDTO.setSn(sn);
- operationLogDTO.setAreaId(areaId);
- operationLogDTO.setSectionId(sectionId);
- operationLogDTO.setDevId(id);
- operationLogDTO.setSqlLog(sql_log);
- operationLogDTO.setIpAddr(ip);
- operationLogDTO.setLocation(location);
- operationLogService.add(operationLogDTO);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
- public String getLocationByIp(String ip) throws IOException {
- //把域名都转换成ip地址
- ip = InetAddress.getByName(ip).getHostAddress();
- IpInfoDTO infoDTO = ipInfoService.getDataByIp(ip);
- String location = "";
- if (infoDTO == null){
- IpInfoDTO newInfoDTO = new IpInfoDTO();
- if (ip.equals("127.0.0.1")){
- //本地添加
- location = "服务器本地";
- newInfoDTO.setLocation(location);
- newInfoDTO.setIpAddr(ip);
- ipInfoService.add(newInfoDTO);
- }else {
- String url = "https://opendata.baidu.com/api.php?query="+ip+"&co=&resource_id=6006&oe=utf8";
- JSONObject jsonObject = new JSONObject();
- jsonObject.put("query",ip);
- jsonObject.put("co",null);
- jsonObject.put("resource_id",600);
- jsonObject.put("oe","utf8");
- String respone = this.sendHttp("get", url, jsonObject.toString(), 4, ContentTypeEnum.CONTENT_TYPE_JSON,null);
- if (respone != null){
- JSONObject responeJson = JSON.parseObject(respone);
- String status = responeJson.getString("status");
- if (status.equals("0")){
- //成功
- //数组
- JSONArray jsonArray = responeJson.getJSONArray("data");
- JSONObject item = (JSONObject)(jsonArray.get(0));
- location = item.getString("location");
- newInfoDTO.setLocation(location);
- newInfoDTO.setIpAddr(ip);
- ipInfoService.add(newInfoDTO);
- }
- }
- }
- }else {
- location = infoDTO.getLocation();
- }
- return location;
- }
- }
|