/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.ifish.socket.config; import com.ifish.bean.LoginRecord; import com.ifish.bean.Tbl_Device; import com.ifish.bean.Tbl_Device_Statistics; import com.ifish.bean.Tbl_Device_User; import com.ifish.bean.Tbl_Push_List; import com.ifish.bean.Tbl_User; import com.ifish.enums.PushTypeEnum; import com.ifish.helper.DeviceHelperI; import com.ifish.helper.JpushHelperI; import com.ifish.helper.UserHelperI; import com.ifish.socket.model.JobGroup; import com.ifish.socket.model.OrderModel; import com.ifish.socket.model.receive.APPLoginResponseLength26; import com.ifish.socket.model.receive.DeviceLoginResponseLength25; import com.ifish.socket.model.receive.ServerHeartbeatLength17; import com.ifish.socket.model.send.APPLoginContextLength25; import com.ifish.socket.model.send.DeviceLoginContextLength24; import com.ifish.socket.model.send.ModelVersionLength22; import com.ifish.socket.model.send.ModelVersionLength38; import com.ifish.socket.model.send.TemperatureAlarmLength22; import com.ifish.socket.model.send.TemperatureSwitchLength22; import com.ifish.socket.model.send.UpgradeVersionLength78; import com.ifish.util.ByteUtil; import com.ifish.util.IfishUtil; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArraySet; import org.apache.commons.lang3.StringUtils; import org.apache.mina.core.session.IoSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; /** * * @author Administrator */ public class SomeServer { @Autowired private UserHelperI userHelperI; @Autowired private DeviceHelperI deviceHelperI; @Autowired private ScheduleJob scheduleJob; // @Autowired // private NeteaseIM neteaseIM; @Autowired private JpushHelperI jpushHelperI; //是否回复心跳 public static boolean isReplay = true; private static Logger log = LoggerFactory.getLogger(SomeServer.class); public static ConcurrentHashMap remoteAddress = new ConcurrentHashMap(); public static ConcurrentHashMap sessions_cz = new ConcurrentHashMap(); private ConcurrentHashMap> sessions_sjs = new ConcurrentHashMap>(); /** * 过滤收到的数据 服务器收到数据,进行协议类型匹配,如果不匹配,则不执行相应操作。 * * @param session * @param message */ public void doSome(IoSession session, Object message) { //通配字符串 if (message instanceof byte[]) { byte[] bytes = (byte[]) message; //长度 int length = bytes[14] & 0xff; //mac地址 byte[] srcByte = new byte[6]; for (int i = 2; i < 8; i++) { srcByte[i - 2] = bytes[i]; } String strSrc = ByteUtil.bytesToHexString(srcByte); //心跳 if (length >= 28) { sendToApp(session, strSrc, message); } else { sendToDevice(session, strSrc, message); } } //设置设备温度报警 else if (message instanceof TemperatureSwitchLength22) { TemperatureSwitchLength22 receive = (TemperatureSwitchLength22) message; String strDest = ByteUtil.bytesToHexString(receive.getDest()); sendToDevice(session, strDest, message); try { Integer Onoff = receive.getOnoff() & 0xff; if (Onoff == 1 || Onoff == 0) { deviceHelperI.updateWarnOnoff(strDest, Onoff.toString()); } else { log.error("error Onoff:{},macAddress:{}", Onoff, strDest); } } catch (Exception e) { log.warn("set OrderSetWarnModel error:macAddress:{},error msg:{}", strDest, e.toString()); } } //设备温度报警 else if (message instanceof TemperatureAlarmLength22) { TemperatureAlarmLength22 receive = (TemperatureAlarmLength22) message; String strSrc = ByteUtil.bytesToHexString(receive.getSrc()); //推送类型 Integer warnType = receive.getWarn_type() & 0xff; if (warnType == 0) { pushNotifcation(strSrc, PushTypeEnum.wendu_warn.getValue(), "'s temperature is" + (float) receive.getWendu() / 10f + "℃,lower than" + (float) receive.getWarn_wendu() / 10f + "℃,"); } else if (warnType == 1) { pushNotifcation(strSrc, PushTypeEnum.wendu_warn.getValue(), "'s temperature is" + (float) receive.getWendu() / 10f + "℃,high than" + (float) receive.getWarn_wendu() / 10f + "℃,"); } else { log.error("error warn_type:{},macAddress:{}", warnType, strSrc); } } //设备登录服务器 else if (message instanceof DeviceLoginContextLength24) { DeviceLoginContextLength24 receive = (DeviceLoginContextLength24) message; byte[] srcBytes = receive.getSrc(); byte[] destBytes = receive.getDest(); String strSrc = ByteUtil.bytesToHexString(srcBytes); //服务器回复设备登录请求 DeviceLoginResponseLength25 model = OrderModel.DeviceLoginResponseLength25(destBytes, srcBytes); //直接往本次session写回去 session.write(model); //保存连接 sessions_cz.put(strSrc, session); remoteAddress.put(session.getRemoteAddress().toString(), strSrc); //设备重新连接上,则移除延时推送的任务 JobGroup jobGroup = new JobGroup(); jobGroup.setJobName(strSrc); jobGroup.setTriggerName(strSrc); scheduleJob.deleteJob(jobGroup); try { //更新设备信息 deviceHelperI.updateDeviceWhenLogin(receive); } catch (Exception e) { log.warn("save device login error:macAddress:{},error msg:{}", strSrc, e.toString()); } } //APP登录服务器 else if (message instanceof APPLoginContextLength25) { APPLoginContextLength25 receive = (APPLoginContextLength25) message; byte[] srcBytes = receive.getSrc(); byte[] destBytes = receive.getDest(); String strDest = ByteUtil.bytesToHexString(receive.getDest()); //设备是否在线 IoSession tmpSession = sessions_cz.get(strDest); //1表示在线,0表示离线 byte login_status = 0; if (tmpSession != null && tmpSession.getRemoteAddress() != null) { login_status = 1; } else { login_status = 0; } //服务器回复APP登录请求 APPLoginResponseLength26 model = OrderModel.APPLoginResponseLength26(destBytes, srcBytes, login_status); session.write(model); //保存APP连接 CopyOnWriteArraySet sessionSet = sessions_sjs.get(strDest); if (sessionSet == null) { sessionSet = new CopyOnWriteArraySet(); sessionSet.add(session); sessions_sjs.put(strDest, sessionSet); } else { for (IoSession ioSession : sessionSet) { if (ioSession == null || ioSession.getRemoteAddress() == null) { sessionSet.remove(ioSession); } } sessionSet.add(session); } } //模块版本号 else if (message instanceof ModelVersionLength22) { ModelVersionLength22 receive = (ModelVersionLength22) message; byte[] macBytes = receive.getSrc(); String strSrc = ByteUtil.bytesToHexString(macBytes); try { //查找设备 Tbl_Device device = deviceHelperI.getDeviceByMacAddress(strSrc); Tbl_Device_Statistics device_Statistics = deviceHelperI.getDeviceStatisticsByMacAddress(strSrc); if (device != null) { //是否升级 if (StringUtils.isNotBlank(device_Statistics.getIsUpgrade()) && device_Statistics.getIsUpgrade().equals("1")) { device_Statistics.setIsUpgrade("0"); device_Statistics.setUpgradeTime(new Date()); //升级版本 int upgradeVersion = Integer.valueOf(device_Statistics.getUpgradeVersion()); UpgradeVersionLength78 model = OrderModel.UpgradeVersionLength78(macBytes, upgradeVersion); session.write(model); } //记录参数 device_Statistics.setSdkVersion(String.valueOf(receive.getVersion() & 0xff)); device_Statistics.setSdkTime(IfishUtil.StrToDate(receive.getYear() + "-" + (receive.getMonth() & 0xff) + "-" + (receive.getDay() & 0xff))); deviceHelperI.updateDevice_Statistics(device_Statistics); } } catch (Exception e) { log.warn("save device sdk version16 error:macAddress:{},error msg:{}", strSrc, e.toString()); } } //模块版本号 else if (message instanceof ModelVersionLength38) { ModelVersionLength38 receive = (ModelVersionLength38) message; byte[] macBytes = receive.getSrc(); String strSrc = ByteUtil.bytesToHexString(macBytes); try { //查找设备 Tbl_Device device = deviceHelperI.getDeviceByMacAddress(strSrc); Tbl_Device_Statistics device_Statistics = deviceHelperI.getDeviceStatisticsByMacAddress(strSrc); if (device != null) { //是否升级 if (StringUtils.isNotBlank(device_Statistics.getIsUpgrade()) && device_Statistics.getIsUpgrade().equals("1")) { device_Statistics.setIsUpgrade("0"); device_Statistics.setUpgradeTime(new Date()); //升级版本 int upgradeVersion = Integer.parseInt(device_Statistics.getUpgradeVersion()); UpgradeVersionLength78 model = OrderModel.UpgradeVersionLength78(macBytes, upgradeVersion); session.write(model); } //记录参数 device_Statistics.setSdkVersion(String.valueOf(receive.getVersion() & 0xff)); device_Statistics.setSdkTime(IfishUtil.StrToDate(receive.getYear() + "-" + (receive.getMonth() & 0xff) + "-" + (receive.getDay() & 0xff))); device_Statistics.setMcuCount(receive.getNumber1()); device_Statistics.setModuleCount(receive.getNumber2()); device_Statistics.setRouterCount(receive.getNumber3()); device_Statistics.setServerCount(receive.getNumber4()); device_Statistics.setServerTryCount(receive.getNumber5()); deviceHelperI.updateDevice_Statistics(device_Statistics); } } catch (Exception e) { log.warn("save device sdk version17 error:macAddress:{},error msg:{}", strSrc, e.toString()); } } } /** * 发送数据APP * * @param dest 目的地 * @param message 发送对象 * @return */ public void sendToApp(IoSession session, String strDest, Object message) { //回复设备 if (isReplay) { ServerHeartbeatLength17 model = OrderModel.ServerHeartbeatLength17(strDest); session.write(model); } //转发给APP CopyOnWriteArraySet sessionSet = sessions_sjs.get(strDest); if (sessionSet != null && sessionSet.size() > 0) { for (IoSession sj_session : sessionSet) { if (sj_session != null && sj_session.getRemoteAddress() != null) { sj_session.write(message); } else { sessionSet.remove(sj_session); } } } } /** * 发送数据给设备 * * @param dest 目的地 * @param message 发送对象 * @return */ public void sendToDevice(IoSession session, String strDest, Object message) { IoSession cz_session = sessions_cz.get(strDest); if (cz_session != null && cz_session.getRemoteAddress() != null) { cz_session.write(message); } else { //设备离线 byte[] bytes = ByteUtil.hexStringToBytes2(strDest); APPLoginResponseLength26 model = OrderModel.APPLoginResponseLength26(bytes, bytes, (byte) 0); session.write(model); } } /** * 温度预警推送 * * @param strSrc * @param title * @param contont */ public void pushNotifcation(String strSrc, String title, String contont) { try { Tbl_Device device = deviceHelperI.getDeviceByMacAddress(strSrc); Tbl_Device_Statistics device_Statistics = null; if (device != null) { Integer deviceId = device.getDeviceId(); //是否开启预警 String onOff = device.getOnOff(); if (onOff != null && onOff.equals("1")) { //绑定设备的用户 List list = deviceHelperI.getTbl_Device_UsersListByDeviceId(device.getDeviceId()); for (Tbl_Device_User deviceUser : list) { Integer userId = deviceUser.getUserId(); String showName = deviceUser.getShowName(); String timestamp = IfishUtil.format(new Date()); String msg = "【" + title + "】Your aquarium “" + showName + "”" + contont + "at" + timestamp + ", please check it with out delay!"; Tbl_User user = userHelperI.findById(userId); if (user != null) { //极光推送 boolean result = false; String loginType = user.getLoginType(); if (StringUtils.isNotBlank(loginType) && userId != null) { //推送记录 Tbl_Push_List pushList = new Tbl_Push_List(); Map map = new HashMap(); map.put("device_id", deviceId.toString()); map.put("device_name", showName); map.put("timestamp", timestamp); map.put("msg_type", PushTypeEnum.wendu_warn.getKey()); if (loginType.equals("android")) { result = jpushHelperI.pushMessageByAndroid(title, msg, userId.toString(), map); } else if (loginType.equals("ios")) { result = jpushHelperI.pushMessageByIOS(title, msg, userId.toString(), map); } //记录推送 if (result) { pushList.setUserId(userId); pushList.setDeviceId(deviceId); pushList.setPhoneType(loginType.toLowerCase()); pushList.setShowName(showName); pushList.setPushType(PushTypeEnum.wendu_warn.getKey()); pushList.setPushTitle(title); pushList.setPushContext(msg); pushList.setJpushStatus(result ? "1" : "0"); pushList.setCreateTime(new Date()); pushList.setMcuCount(device_Statistics.getMcuCount()); pushList.setModularCount(device_Statistics.getModuleCount()); pushList.setRouterCount(device_Statistics.getRouterCount()); pushList.setServerCount(device_Statistics.getServerCount()); pushList.setServerTryCount(device_Statistics.getServerTryCount()); userHelperI.save(pushList); } } } } } } } catch (Exception e) { log.warn("pushNotifcation error:macAddress:{},error msg:{}", strSrc, e.toString()); } } }