使用Slf4j注解打印日志

This commit is contained in:
648540858 2024-07-03 17:24:35 +08:00
parent adf040ec4b
commit b98cfd1fed
66 changed files with 804 additions and 1039 deletions

View File

@ -5,9 +5,8 @@ import com.genersoft.iot.vmp.conf.security.SecurityUtils;
import com.genersoft.iot.vmp.service.ILogService; import com.genersoft.iot.vmp.service.ILogService;
import com.genersoft.iot.vmp.storager.dao.dto.LogDto; import com.genersoft.iot.vmp.storager.dao.dto.LogDto;
import com.genersoft.iot.vmp.utils.DateUtil; import com.genersoft.iot.vmp.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@ -24,13 +23,11 @@ import java.io.IOException;
/** /**
* @author lin * @author lin
*/ */
@Slf4j
@WebFilter(filterName = "ApiAccessFilter", urlPatterns = "/api/*", asyncSupported=true) @WebFilter(filterName = "ApiAccessFilter", urlPatterns = "/api/*", asyncSupported=true)
@Component @Component
public class ApiAccessFilter extends OncePerRequestFilter { public class ApiAccessFilter extends OncePerRequestFilter {
private final static Logger logger = LoggerFactory.getLogger(ApiAccessFilter.class);
@Autowired @Autowired
private UserSetting userSetting; private UserSetting userSetting;

View File

@ -1,8 +1,7 @@
package com.genersoft.iot.vmp.conf; package com.genersoft.iot.vmp.conf;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@ -20,11 +19,10 @@ import java.util.concurrent.TimeUnit;
* 动态定时任务 * 动态定时任务
* @author lin * @author lin
*/ */
@Slf4j
@Component @Component
public class DynamicTask { public class DynamicTask {
private final Logger logger = LoggerFactory.getLogger(DynamicTask.class);
private ThreadPoolTaskScheduler threadPoolTaskScheduler; private ThreadPoolTaskScheduler threadPoolTaskScheduler;
private final Map<String, ScheduledFuture<?>> futureMap = new ConcurrentHashMap<>(); private final Map<String, ScheduledFuture<?>> futureMap = new ConcurrentHashMap<>();
@ -53,9 +51,9 @@ public class DynamicTask {
ScheduledFuture<?> future = futureMap.get(key); ScheduledFuture<?> future = futureMap.get(key);
if (future != null) { if (future != null) {
if (future.isCancelled()) { if (future.isCancelled()) {
logger.debug("任务【{}】已存在但是关闭状态!!!", key); log.debug("任务【{}】已存在但是关闭状态!!!", key);
} else { } else {
logger.debug("任务【{}】已存在且已启动!!!", key); log.debug("任务【{}】已存在且已启动!!!", key);
return; return;
} }
} }
@ -65,9 +63,9 @@ public class DynamicTask {
if (future != null){ if (future != null){
futureMap.put(key, future); futureMap.put(key, future);
runnableMap.put(key, task); runnableMap.put(key, task);
logger.debug("任务【{}】启动成功!!!", key); log.debug("任务【{}】启动成功!!!", key);
}else { }else {
logger.debug("任务【{}】启动失败!!!", key); log.debug("任务【{}】启动失败!!!", key);
} }
} }
@ -90,9 +88,9 @@ public class DynamicTask {
ScheduledFuture future = futureMap.get(key); ScheduledFuture future = futureMap.get(key);
if (future != null) { if (future != null) {
if (future.isCancelled()) { if (future.isCancelled()) {
logger.debug("任务【{}】已存在但是关闭状态!!!", key); log.debug("任务【{}】已存在但是关闭状态!!!", key);
} else { } else {
logger.debug("任务【{}】已存在且已启动!!!", key); log.debug("任务【{}】已存在且已启动!!!", key);
return; return;
} }
} }
@ -101,9 +99,9 @@ public class DynamicTask {
if (future != null){ if (future != null){
futureMap.put(key, future); futureMap.put(key, future);
runnableMap.put(key, task); runnableMap.put(key, task);
logger.debug("任务【{}】启动成功!!!", key); log.debug("任务【{}】启动成功!!!", key);
}else { }else {
logger.debug("任务【{}】启动失败!!!", key); log.debug("任务【{}】启动失败!!!", key);
} }
} }

View File

@ -1,16 +1,14 @@
package com.genersoft.iot.vmp.conf; package com.genersoft.iot.vmp.conf;
import org.slf4j.Logger; import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.context.WebServerInitializedEvent; import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener; import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@Slf4j
@Component @Component
public class ServiceInfo implements ApplicationListener<WebServerInitializedEvent> { public class ServiceInfo implements ApplicationListener<WebServerInitializedEvent> {
private final Logger logger = LoggerFactory.getLogger(ServiceInfo.class);
private static int serverPort; private static int serverPort;
public static int getServerPort() { public static int getServerPort() {
@ -21,7 +19,7 @@ public class ServiceInfo implements ApplicationListener<WebServerInitializedEven
public void onApplicationEvent(WebServerInitializedEvent event) { public void onApplicationEvent(WebServerInitializedEvent event) {
// 项目启动获取启动的端口号 // 项目启动获取启动的端口号
ServiceInfo.serverPort = event.getWebServer().getPort(); ServiceInfo.serverPort = event.getWebServer().getPort();
logger.info("项目启动获取启动的端口号: " + ServiceInfo.serverPort); log.info("项目启动获取启动的端口号: " + ServiceInfo.serverPort);
} }
public void setServerPort(int serverPort) { public void setServerPort(int serverPort) {

View File

@ -1,10 +1,8 @@
package com.genersoft.iot.vmp.conf; package com.genersoft.iot.vmp.conf;
import com.genersoft.iot.vmp.gb28181.transmit.event.request.impl.message.query.cmd.AlarmQueryMessageHandler;
import com.genersoft.iot.vmp.storager.IRedisCatchStorage; import com.genersoft.iot.vmp.storager.IRedisCatchStorage;
import com.genersoft.iot.vmp.utils.SystemInfoUtils; import com.genersoft.iot.vmp.utils.SystemInfoUtils;
import org.slf4j.Logger; import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@ -15,11 +13,10 @@ import java.util.Map;
/** /**
* 获取系统信息写入redis * 获取系统信息写入redis
*/ */
@Slf4j
@Component @Component
public class SystemInfoTimerTask { public class SystemInfoTimerTask {
private Logger logger = LoggerFactory.getLogger(SystemInfoTimerTask.class);
@Autowired @Autowired
private IRedisCatchStorage redisCatchStorage; private IRedisCatchStorage redisCatchStorage;
@ -35,7 +32,7 @@ public class SystemInfoTimerTask {
List<Map<String, Object>> diskInfo =SystemInfoUtils.getDiskInfo(); List<Map<String, Object>> diskInfo =SystemInfoUtils.getDiskInfo();
redisCatchStorage.addDiskInfo(diskInfo); redisCatchStorage.addDiskInfo(diskInfo);
} catch (InterruptedException e) { } catch (InterruptedException e) {
logger.error("[获取系统信息失败] {}", e.getMessage()); log.error("[获取系统信息失败] {}", e.getMessage());
} }
} }

View File

@ -5,6 +5,7 @@ import com.genersoft.iot.vmp.service.IUserApiKeyService;
import com.genersoft.iot.vmp.service.IUserService; import com.genersoft.iot.vmp.service.IUserService;
import com.genersoft.iot.vmp.storager.dao.dto.User; import com.genersoft.iot.vmp.storager.dao.dto.User;
import com.genersoft.iot.vmp.storager.dao.dto.UserApiKey; import com.genersoft.iot.vmp.storager.dao.dto.UserApiKey;
import lombok.extern.slf4j.Slf4j;
import org.jose4j.jwk.JsonWebKey; import org.jose4j.jwk.JsonWebKey;
import org.jose4j.jwk.JsonWebKeySet; import org.jose4j.jwk.JsonWebKeySet;
import org.jose4j.jwk.RsaJsonWebKey; import org.jose4j.jwk.RsaJsonWebKey;
@ -18,8 +19,6 @@ import org.jose4j.jwt.consumer.InvalidJwtException;
import org.jose4j.jwt.consumer.JwtConsumer; import org.jose4j.jwt.consumer.JwtConsumer;
import org.jose4j.jwt.consumer.JwtConsumerBuilder; import org.jose4j.jwt.consumer.JwtConsumerBuilder;
import org.jose4j.lang.JoseException; import org.jose4j.lang.JoseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@ -32,11 +31,10 @@ import java.time.ZoneOffset;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@Slf4j
@Component @Component
public class JwtUtils implements InitializingBean { public class JwtUtils implements InitializingBean {
private static final Logger logger = LoggerFactory.getLogger(JwtUtils.class);
public static final String HEADER = "access-token"; public static final String HEADER = "access-token";
public static final String API_KEY_HEADER = "api-key"; public static final String API_KEY_HEADER = "api-key";
@ -75,7 +73,7 @@ public class JwtUtils implements InitializingBean {
try { try {
rsaJsonWebKey = generateRsaJsonWebKey(); rsaJsonWebKey = generateRsaJsonWebKey();
} catch (JoseException e) { } catch (JoseException e) {
logger.error("生成RsaJsonWebKey报错。", e); log.error("生成RsaJsonWebKey报错。", e);
} }
} }
@ -145,7 +143,7 @@ public class JwtUtils implements InitializingBean {
//get token //get token
return jws.getCompactSerialization(); return jws.getCompactSerialization();
} catch (JoseException e) { } catch (JoseException e) {
logger.error("[Token生成失败] {}", e.getMessage()); log.error("[Token生成失败] {}", e.getMessage());
} }
return null; return null;
} }
@ -217,7 +215,7 @@ public class JwtUtils implements InitializingBean {
} }
return jwtUser; return jwtUser;
} catch (Exception e) { } catch (Exception e) {
logger.error("[Token解析失败] {}", e.getMessage()); log.error("[Token解析失败] {}", e.getMessage());
jwtUser.setStatus(JwtUser.TokenStatus.EXPIRED); jwtUser.setStatus(JwtUser.TokenStatus.EXPIRED);
return jwtUser; return jwtUser;
} }

View File

@ -1,8 +1,7 @@
package com.genersoft.iot.vmp.conf.security; package com.genersoft.iot.vmp.conf.security;
import com.genersoft.iot.vmp.conf.UserSetting; import com.genersoft.iot.vmp.conf.UserSetting;
import org.slf4j.Logger; import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
@ -36,10 +35,9 @@ import java.util.Collections;
@EnableWebSecurity @EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) @EnableGlobalMethodSecurity(prePostEnabled = true)
@Order(1) @Order(1)
@Slf4j
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
private final static Logger logger = LoggerFactory.getLogger(WebSecurityConfig.class);
@Autowired @Autowired
private UserSetting userSetting; private UserSetting userSetting;

View File

@ -7,8 +7,7 @@ import com.genersoft.iot.vmp.gb28181.conf.DefaultProperties;
import com.genersoft.iot.vmp.gb28181.transmit.ISIPProcessorObserver; import com.genersoft.iot.vmp.gb28181.transmit.ISIPProcessorObserver;
import gov.nist.javax.sip.SipProviderImpl; import gov.nist.javax.sip.SipProviderImpl;
import gov.nist.javax.sip.SipStackImpl; import gov.nist.javax.sip.SipStackImpl;
import org.slf4j.Logger; import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner; import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order; import org.springframework.core.annotation.Order;
@ -22,12 +21,11 @@ import java.net.NetworkInterface;
import java.util.*; import java.util.*;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
@Slf4j
@Component @Component
@Order(value=10) @Order(value=10)
public class SipLayer implements CommandLineRunner { public class SipLayer implements CommandLineRunner {
private final static Logger logger = LoggerFactory.getLogger(SipLayer.class);
@Autowired @Autowired
private SipConfig sipConfig; private SipConfig sipConfig;
@ -60,16 +58,16 @@ public class SipLayer implements CommandLineRunner {
if (nif.getName().startsWith("docker")) { if (nif.getName().startsWith("docker")) {
continue; continue;
} }
logger.info("[自动配置SIP监听网卡] 网卡接口地址: {}", addr.getHostAddress());// 只关心 IPv4 地址 log.info("[自动配置SIP监听网卡] 网卡接口地址: {}", addr.getHostAddress());// 只关心 IPv4 地址
monitorIps.add(addr.getHostAddress()); monitorIps.add(addr.getHostAddress());
} }
} }
} }
}catch (Exception e) { }catch (Exception e) {
logger.error("[读取网卡信息失败]", e); log.error("[读取网卡信息失败]", e);
} }
if (monitorIps.isEmpty()) { if (monitorIps.isEmpty()) {
logger.error("[自动配置SIP监听网卡信息失败] 请手动配置SIP.IP后重新启动"); log.error("[自动配置SIP监听网卡信息失败] 请手动配置SIP.IP后重新启动");
System.exit(1); System.exit(1);
} }
}else { }else {
@ -100,7 +98,7 @@ public class SipLayer implements CommandLineRunner {
sipStack = (SipStackImpl)SipFactory.getInstance().createSipStack(DefaultProperties.getProperties("GB28181_SIP", userSetting.getSipLog())); sipStack = (SipStackImpl)SipFactory.getInstance().createSipStack(DefaultProperties.getProperties("GB28181_SIP", userSetting.getSipLog()));
sipStack.setMessageParserFactory(new GbStringMsgParserFactory()); sipStack.setMessageParserFactory(new GbStringMsgParserFactory());
} catch (PeerUnavailableException e) { } catch (PeerUnavailableException e) {
logger.error("[SIP SERVER] SIP服务启动失败 监听地址{}失败,请检查ip是否正确", monitorIp); log.error("[SIP SERVER] SIP服务启动失败 监听地址{}失败,请检查ip是否正确", monitorIp);
return; return;
} }
@ -111,12 +109,12 @@ public class SipLayer implements CommandLineRunner {
tcpSipProvider.setDialogErrorsAutomaticallyHandled(); tcpSipProvider.setDialogErrorsAutomaticallyHandled();
tcpSipProvider.addSipListener(sipProcessorObserver); tcpSipProvider.addSipListener(sipProcessorObserver);
tcpSipProviderMap.put(monitorIp, tcpSipProvider); tcpSipProviderMap.put(monitorIp, tcpSipProvider);
logger.info("[SIP SERVER] tcp://{}:{} 启动成功", monitorIp, port); log.info("[SIP SERVER] tcp://{}:{} 启动成功", monitorIp, port);
} catch (TransportNotSupportedException } catch (TransportNotSupportedException
| TooManyListenersException | TooManyListenersException
| ObjectInUseException | ObjectInUseException
| InvalidArgumentException e) { | InvalidArgumentException e) {
logger.error("[SIP SERVER] tcp://{}:{} SIP服务启动失败,请检查端口是否被占用或者ip是否正确" log.error("[SIP SERVER] tcp://{}:{} SIP服务启动失败,请检查端口是否被占用或者ip是否正确"
, monitorIp, port); , monitorIp, port);
} }
@ -128,12 +126,12 @@ public class SipLayer implements CommandLineRunner {
udpSipProviderMap.put(monitorIp, udpSipProvider); udpSipProviderMap.put(monitorIp, udpSipProvider);
logger.info("[SIP SERVER] udp://{}:{} 启动成功", monitorIp, port); log.info("[SIP SERVER] udp://{}:{} 启动成功", monitorIp, port);
} catch (TransportNotSupportedException } catch (TransportNotSupportedException
| TooManyListenersException | TooManyListenersException
| ObjectInUseException | ObjectInUseException
| InvalidArgumentException e) { | InvalidArgumentException e) {
logger.error("[SIP SERVER] udp://{}:{} SIP服务启动失败,请检查端口是否被占用或者ip是否正确" log.error("[SIP SERVER] udp://{}:{} SIP服务启动失败,请检查端口是否被占用或者ip是否正确"
, monitorIp, port); , monitorIp, port);
} }
} }

View File

@ -26,8 +26,7 @@
package com.genersoft.iot.vmp.gb28181.auth; package com.genersoft.iot.vmp.gb28181.auth;
import gov.nist.core.InternalErrorHandler; import gov.nist.core.InternalErrorHandler;
import org.slf4j.Logger; import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import javax.sip.address.URI; import javax.sip.address.URI;
import javax.sip.header.AuthorizationHeader; import javax.sip.header.AuthorizationHeader;
@ -46,19 +45,14 @@ import java.util.Random;
* @author M. Ranganathan * @author M. Ranganathan
* @author Marc Bednarek * @author Marc Bednarek
*/ */
@Slf4j
public class DigestServerAuthenticationHelper { public class DigestServerAuthenticationHelper {
private Logger logger = LoggerFactory.getLogger(DigestServerAuthenticationHelper.class);
private MessageDigest messageDigest; private MessageDigest messageDigest;
public static final String DEFAULT_ALGORITHM = "MD5"; public static final String DEFAULT_ALGORITHM = "MD5";
public static final String DEFAULT_SCHEME = "Digest"; public static final String DEFAULT_SCHEME = "Digest";
/** to hex converter */ /** to hex converter */
private static final char[] toHex = { '0', '1', '2', '3', '4', '5', '6', private static final char[] toHex = { '0', '1', '2', '3', '4', '5', '6',
'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
@ -205,17 +199,17 @@ public class DigestServerAuthenticationHelper {
byte mdbytes[] = messageDigest.digest(A1.getBytes()); byte mdbytes[] = messageDigest.digest(A1.getBytes());
String HA1 = toHexString(mdbytes); String HA1 = toHexString(mdbytes);
logger.debug("A1: " + A1); log.debug("A1: " + A1);
logger.debug("A2: " + A2); log.debug("A2: " + A2);
mdbytes = messageDigest.digest(A2.getBytes()); mdbytes = messageDigest.digest(A2.getBytes());
String HA2 = toHexString(mdbytes); String HA2 = toHexString(mdbytes);
logger.debug("HA1: " + HA1); log.debug("HA1: " + HA1);
logger.debug("HA2: " + HA2); log.debug("HA2: " + HA2);
// String cnonce = authHeader.getCNonce(); // String cnonce = authHeader.getCNonce();
logger.debug("nonce: " + nonce); log.debug("nonce: " + nonce);
logger.debug("nc: " + ncStr); log.debug("nc: " + ncStr);
logger.debug("cnonce: " + cnonce); log.debug("cnonce: " + cnonce);
logger.debug("qop: " + qop); log.debug("qop: " + qop);
String KD = HA1 + ":" + nonce; String KD = HA1 + ":" + nonce;
if (qop != null && qop.equalsIgnoreCase("auth") ) { if (qop != null && qop.equalsIgnoreCase("auth") ) {
@ -228,12 +222,12 @@ public class DigestServerAuthenticationHelper {
KD += ":" + qop; KD += ":" + qop;
} }
KD += ":" + HA2; KD += ":" + HA2;
logger.debug("KD: " + KD); log.debug("KD: " + KD);
mdbytes = messageDigest.digest(KD.getBytes()); mdbytes = messageDigest.digest(KD.getBytes());
String mdString = toHexString(mdbytes); String mdString = toHexString(mdbytes);
logger.debug("mdString: " + mdString); log.debug("mdString: " + mdString);
String response = authHeader.getResponse(); String response = authHeader.getResponse();
logger.debug("response: " + response); log.debug("response: " + response);
return mdString.equals(response); return mdString.equals(response);
} }

View File

@ -1,9 +1,7 @@
package com.genersoft.iot.vmp.gb28181.bean; package com.genersoft.iot.vmp.gb28181.bean;
import gov.nist.core.CommonLogger;
import gov.nist.core.Host; import gov.nist.core.Host;
import gov.nist.core.HostNameParser; import gov.nist.core.HostNameParser;
import gov.nist.core.StackLogger;
import gov.nist.javax.sip.SIPConstants; import gov.nist.javax.sip.SIPConstants;
import gov.nist.javax.sip.address.AddressImpl; import gov.nist.javax.sip.address.AddressImpl;
import gov.nist.javax.sip.address.GenericURI; import gov.nist.javax.sip.address.GenericURI;
@ -14,16 +12,16 @@ import gov.nist.javax.sip.message.SIPMessage;
import gov.nist.javax.sip.message.SIPRequest; import gov.nist.javax.sip.message.SIPRequest;
import gov.nist.javax.sip.message.SIPResponse; import gov.nist.javax.sip.message.SIPResponse;
import gov.nist.javax.sip.parser.*; import gov.nist.javax.sip.parser.*;
import lombok.extern.slf4j.Slf4j;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.text.ParseException; import java.text.ParseException;
@Slf4j
public class GBStringMsgParser implements MessageParser { public class GBStringMsgParser implements MessageParser {
protected static boolean computeContentLengthFromMessage = false; protected static boolean computeContentLengthFromMessage = false;
private static StackLogger logger = CommonLogger.getLogger(StringMsgParser.class);
/** /**
* @since v0.9 * @since v0.9
*/ */
@ -60,8 +58,8 @@ public class GBStringMsgParser implements MessageParser {
} }
catch (ArrayIndexOutOfBoundsException e) { catch (ArrayIndexOutOfBoundsException e) {
// Array contains only control char, return null. // Array contains only control char, return null.
if (logger.isLoggingEnabled(StackLogger.TRACE_DEBUG)) { if (log.isDebugEnabled()) {
logger.logDebug("handled only control char so returning null"); log.debug("handled only control char so returning null");
} }
return null; return null;
} }

View File

@ -49,14 +49,14 @@ public class DefaultProperties {
/** /**
* sip_server_log.log sip_debug_log.log ERROR, INFO, WARNING, OFF, DEBUG, TRACE * sip_server_log.log sip_debug_log.log ERROR, INFO, WARNING, OFF, DEBUG, TRACE
*/ */
Logger logger = LoggerFactory.getLogger(AlarmNotifyMessageHandler.class); Logger log = LoggerFactory.getLogger(AlarmNotifyMessageHandler.class);
if (sipLog) { if (sipLog) {
properties.setProperty("gov.nist.javax.sip.STACK_LOGGER", "com.genersoft.iot.vmp.gb28181.conf.StackLoggerImpl"); properties.setProperty("gov.nist.javax.sip.STACK_LOGGER", "com.genersoft.iot.vmp.gb28181.conf.StackLoggerImpl");
properties.setProperty("gov.nist.javax.sip.SERVER_LOGGER", "com.genersoft.iot.vmp.gb28181.conf.ServerLoggerImpl"); properties.setProperty("gov.nist.javax.sip.SERVER_LOGGER", "com.genersoft.iot.vmp.gb28181.conf.ServerLoggerImpl");
properties.setProperty("gov.nist.javax.sip.LOG_MESSAGE_CONTENT", "true"); properties.setProperty("gov.nist.javax.sip.LOG_MESSAGE_CONTENT", "true");
logger.info("[SIP日志]已开启"); log.info("[SIP日志]已开启");
}else { }else {
logger.info("[SIP日志]已关闭"); log.info("[SIP日志]已关闭");
} }
return properties; return properties;
} }

View File

@ -3,9 +3,8 @@ package com.genersoft.iot.vmp.gb28181.event;
import com.genersoft.iot.vmp.gb28181.bean.DeviceNotFoundEvent; import com.genersoft.iot.vmp.gb28181.bean.DeviceNotFoundEvent;
import gov.nist.javax.sip.message.SIPRequest; import gov.nist.javax.sip.message.SIPRequest;
import gov.nist.javax.sip.message.SIPResponse; import gov.nist.javax.sip.message.SIPResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@ -22,11 +21,10 @@ import java.util.concurrent.TimeUnit;
/** /**
* @author lin * @author lin
*/ */
@Slf4j
@Component @Component
public class SipSubscribe { public class SipSubscribe {
private final Logger logger = LoggerFactory.getLogger(SipSubscribe.class);
private final Map<String, SipSubscribe.Event> errorSubscribes = new ConcurrentHashMap<>(); private final Map<String, SipSubscribe.Event> errorSubscribes = new ConcurrentHashMap<>();
private final Map<String, SipSubscribe.Event> okSubscribes = new ConcurrentHashMap<>(); private final Map<String, SipSubscribe.Event> okSubscribes = new ConcurrentHashMap<>();
@ -39,7 +37,7 @@ public class SipSubscribe {
// @Scheduled(fixedRate= 100 * 60 * 60 ) // @Scheduled(fixedRate= 100 * 60 * 60 )
@Scheduled(cron="0 0/5 * * * ?") //每5分钟执行一次 @Scheduled(cron="0 0/5 * * * ?") //每5分钟执行一次
public void execute(){ public void execute(){
logger.info("[定时任务] 清理过期的SIP订阅信息"); log.info("[定时任务] 清理过期的SIP订阅信息");
Instant instant = Instant.now().minusMillis(TimeUnit.MINUTES.toMillis(5)); Instant instant = Instant.now().minusMillis(TimeUnit.MINUTES.toMillis(5));
@ -55,10 +53,10 @@ public class SipSubscribe {
errorTimeSubscribes.remove(key); errorTimeSubscribes.remove(key);
} }
} }
logger.debug("okTimeSubscribes.size:{}",okTimeSubscribes.size()); log.debug("okTimeSubscribes.size:{}",okTimeSubscribes.size());
logger.debug("okSubscribes.size:{}",okSubscribes.size()); log.debug("okSubscribes.size:{}",okSubscribes.size());
logger.debug("errorTimeSubscribes.size:{}",errorTimeSubscribes.size()); log.debug("errorTimeSubscribes.size:{}",errorTimeSubscribes.size());
logger.debug("errorSubscribes.size:{}",errorSubscribes.size()); log.debug("errorSubscribes.size:{}",errorSubscribes.size());
} }
public interface Event { void response(EventResult eventResult); public interface Event { void response(EventResult eventResult);

View File

@ -1,8 +1,7 @@
package com.genersoft.iot.vmp.gb28181.event.alarm; package com.genersoft.iot.vmp.gb28181.event.alarm;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener; import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@ -18,27 +17,26 @@ import java.util.concurrent.ConcurrentHashMap;
* @author <a href="mailto:xiaoQQya@126.com">xiaoQQya</a> * @author <a href="mailto:xiaoQQya@126.com">xiaoQQya</a>
* @since 2021/01/20 * @since 2021/01/20
*/ */
@Slf4j
@Component @Component
public class AlarmEventListener implements ApplicationListener<AlarmEvent> { public class AlarmEventListener implements ApplicationListener<AlarmEvent> {
private static final Logger logger = LoggerFactory.getLogger(AlarmEventListener.class);
private static final Map<String, PrintWriter> SSE_CACHE = new ConcurrentHashMap<>(); private static final Map<String, PrintWriter> SSE_CACHE = new ConcurrentHashMap<>();
public void addSseEmitter(String browserId, PrintWriter writer) { public void addSseEmitter(String browserId, PrintWriter writer) {
SSE_CACHE.put(browserId, writer); SSE_CACHE.put(browserId, writer);
logger.info("SSE 在线数量: {}", SSE_CACHE.size()); log.info("SSE 在线数量: {}", SSE_CACHE.size());
} }
public void removeSseEmitter(String browserId, PrintWriter writer) { public void removeSseEmitter(String browserId, PrintWriter writer) {
SSE_CACHE.remove(browserId, writer); SSE_CACHE.remove(browserId, writer);
logger.info("SSE 在线数量: {}", SSE_CACHE.size()); log.info("SSE 在线数量: {}", SSE_CACHE.size());
} }
@Override @Override
public void onApplicationEvent(@NotNull AlarmEvent event) { public void onApplicationEvent(@NotNull AlarmEvent event) {
if (logger.isDebugEnabled()) { if (log.isDebugEnabled()) {
logger.debug("设备报警事件触发, deviceId: {}, {}", event.getAlarmInfo().getDeviceId(), event.getAlarmInfo().getAlarmDescription()); log.debug("设备报警事件触发, deviceId: {}, {}", event.getAlarmInfo().getDeviceId(), event.getAlarmInfo().getAlarmDescription());
} }
String msg = "<strong>设备编号:</strong> <i>" + event.getAlarmInfo().getDeviceId() + "</i>" String msg = "<strong>设备编号:</strong> <i>" + event.getAlarmInfo().getDeviceId() + "</i>"
@ -48,7 +46,7 @@ public class AlarmEventListener implements ApplicationListener<AlarmEvent> {
for (Iterator<Map.Entry<String, PrintWriter>> it = SSE_CACHE.entrySet().iterator(); it.hasNext(); ) { for (Iterator<Map.Entry<String, PrintWriter>> it = SSE_CACHE.entrySet().iterator(); it.hasNext(); ) {
Map.Entry<String, PrintWriter> response = it.next(); Map.Entry<String, PrintWriter> response = it.next();
logger.info("推送到 SSE 连接, 浏览器 ID: {}", response.getKey()); log.info("推送到 SSE 连接, 浏览器 ID: {}", response.getKey());
try { try {
PrintWriter writer = response.getValue(); PrintWriter writer = response.getValue();

View File

@ -6,8 +6,7 @@ import com.genersoft.iot.vmp.gb28181.bean.SubscribeInfo;
import com.genersoft.iot.vmp.gb28181.transmit.cmd.impl.SIPCommanderFroPlatform; import com.genersoft.iot.vmp.gb28181.transmit.cmd.impl.SIPCommanderFroPlatform;
import com.genersoft.iot.vmp.service.bean.GPSMsgInfo; import com.genersoft.iot.vmp.service.bean.GPSMsgInfo;
import com.genersoft.iot.vmp.storager.IVideoManagerStorage; import com.genersoft.iot.vmp.storager.IVideoManagerStorage;
import org.slf4j.Logger; import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener; import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@ -20,11 +19,10 @@ import java.util.List;
/** /**
* 移动位置通知消息转发 * 移动位置通知消息转发
*/ */
@Slf4j
@Component @Component
public class MobilePositionEventLister implements ApplicationListener<MobilePositionEvent> { public class MobilePositionEventLister implements ApplicationListener<MobilePositionEvent> {
private final static Logger logger = LoggerFactory.getLogger(MobilePositionEventLister.class);
@Autowired @Autowired
private IVideoManagerStorage storager; private IVideoManagerStorage storager;
@ -44,7 +42,7 @@ public class MobilePositionEventLister implements ApplicationListener<MobilePosi
List<ParentPlatform> parentPlatformsForGB = storager.queryPlatFormListForGBWithGBId(event.getMobilePosition().getChannelId(), platforms); List<ParentPlatform> parentPlatformsForGB = storager.queryPlatFormListForGBWithGBId(event.getMobilePosition().getChannelId(), platforms);
for (ParentPlatform platform : parentPlatformsForGB) { for (ParentPlatform platform : parentPlatformsForGB) {
logger.info("[向上级发送MobilePosition] 通道:{},平台:{} 位置: {}:{}", event.getMobilePosition().getChannelId(), log.info("[向上级发送MobilePosition] 通道:{},平台:{} 位置: {}:{}", event.getMobilePosition().getChannelId(),
platform.getServerGBId(), event.getMobilePosition().getLongitude(), event.getMobilePosition().getLatitude()); platform.getServerGBId(), event.getMobilePosition().getLongitude(), event.getMobilePosition().getLatitude());
SubscribeInfo subscribe = subscribeHolder.getMobilePositionSubscribe(platform.getServerGBId()); SubscribeInfo subscribe = subscribeHolder.getMobilePositionSubscribe(platform.getServerGBId());
try { try {
@ -52,7 +50,7 @@ public class MobilePositionEventLister implements ApplicationListener<MobilePosi
subscribe); subscribe);
} catch (InvalidArgumentException | ParseException | NoSuchFieldException | SipException | } catch (InvalidArgumentException | ParseException | NoSuchFieldException | SipException |
IllegalAccessException e) { IllegalAccessException e) {
logger.error("[命令发送失败] 国标级联 Catalog通知: {}", e.getMessage()); log.error("[命令发送失败] 国标级联 Catalog通知: {}", e.getMessage());
} }
} }

View File

@ -3,8 +3,7 @@ package com.genersoft.iot.vmp.gb28181.session;
import com.genersoft.iot.vmp.conf.SipConfig; import com.genersoft.iot.vmp.conf.SipConfig;
import com.genersoft.iot.vmp.gb28181.bean.AudioBroadcastCatch; import com.genersoft.iot.vmp.gb28181.bean.AudioBroadcastCatch;
import com.genersoft.iot.vmp.gb28181.utils.SipUtils; import com.genersoft.iot.vmp.gb28181.utils.SipUtils;
import org.slf4j.Logger; import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@ -17,11 +16,10 @@ import java.util.stream.Stream;
* 语音广播消息管理类 * 语音广播消息管理类
* @author lin * @author lin
*/ */
@Slf4j
@Component @Component
public class AudioBroadcastManager { public class AudioBroadcastManager {
private final static Logger logger = LoggerFactory.getLogger(AudioBroadcastManager.class);
@Autowired @Autowired
private SipConfig config; private SipConfig config;

View File

@ -9,10 +9,8 @@ import com.genersoft.iot.vmp.media.bean.MediaServer;
import com.genersoft.iot.vmp.media.service.IMediaServerService; import com.genersoft.iot.vmp.media.service.IMediaServerService;
import com.genersoft.iot.vmp.service.IDeviceService; import com.genersoft.iot.vmp.service.IDeviceService;
import com.genersoft.iot.vmp.service.IPlatformService; import com.genersoft.iot.vmp.service.IPlatformService;
import com.genersoft.iot.vmp.service.impl.PlatformServiceImpl;
import com.genersoft.iot.vmp.storager.IRedisCatchStorage; import com.genersoft.iot.vmp.storager.IRedisCatchStorage;
import org.slf4j.Logger; import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner; import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order; import org.springframework.core.annotation.Order;
@ -30,6 +28,7 @@ import java.util.Map;
* 系统启动时控制设备 * 系统启动时控制设备
* @author lin * @author lin
*/ */
@Slf4j
@Component @Component
@Order(value=14) @Order(value=14)
public class SipRunner implements CommandLineRunner { public class SipRunner implements CommandLineRunner {
@ -52,8 +51,6 @@ public class SipRunner implements CommandLineRunner {
@Autowired @Autowired
private ISIPCommanderForPlatform commanderForPlatform; private ISIPCommanderForPlatform commanderForPlatform;
private final static Logger logger = LoggerFactory.getLogger(PlatformServiceImpl.class);
@Override @Override
public void run(String... args) throws Exception { public void run(String... args) throws Exception {
List<Device> deviceList = deviceService.getAllOnlineDevice(); List<Device> deviceList = deviceService.getAllOnlineDevice();
@ -103,7 +100,7 @@ public class SipRunner implements CommandLineRunner {
try { try {
commanderForPlatform.streamByeCmd(platform, sendRtpItem.getCallId()); commanderForPlatform.streamByeCmd(platform, sendRtpItem.getCallId());
} catch (InvalidArgumentException | ParseException | SipException e) { } catch (InvalidArgumentException | ParseException | SipException e) {
logger.error("[命令发送失败] 国标级联 发送BYE: {}", e.getMessage()); log.error("[命令发送失败] 国标级联 发送BYE: {}", e.getMessage());
} }
} }
} }

View File

@ -6,8 +6,7 @@ import com.genersoft.iot.vmp.gb28181.bean.Device;
import com.genersoft.iot.vmp.gb28181.task.ISubscribeTask; import com.genersoft.iot.vmp.gb28181.task.ISubscribeTask;
import com.genersoft.iot.vmp.gb28181.transmit.cmd.ISIPCommander; import com.genersoft.iot.vmp.gb28181.transmit.cmd.ISIPCommander;
import gov.nist.javax.sip.message.SIPRequest; import gov.nist.javax.sip.message.SIPRequest;
import org.slf4j.Logger; import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import javax.sip.DialogState; import javax.sip.DialogState;
import javax.sip.InvalidArgumentException; import javax.sip.InvalidArgumentException;
@ -20,8 +19,8 @@ import java.text.ParseException;
* 目录订阅任务 * 目录订阅任务
* @author lin * @author lin
*/ */
@Slf4j
public class CatalogSubscribeTask implements ISubscribeTask { public class CatalogSubscribeTask implements ISubscribeTask {
private final Logger logger = LoggerFactory.getLogger(CatalogSubscribeTask.class);
private final Device device; private final Device device;
private final ISIPCommander sipCommander; private final ISIPCommander sipCommander;
private SIPRequest request; private SIPRequest request;
@ -47,22 +46,22 @@ public class CatalogSubscribeTask implements ISubscribeTask {
sipRequest = sipCommander.catalogSubscribe(device, request, eventResult -> { sipRequest = sipCommander.catalogSubscribe(device, request, eventResult -> {
ResponseEvent event = (ResponseEvent) eventResult.event; ResponseEvent event = (ResponseEvent) eventResult.event;
// 成功 // 成功
logger.info("[目录订阅]成功: {}", device.getDeviceId()); log.info("[目录订阅]成功: {}", device.getDeviceId());
ToHeader toHeader = (ToHeader)event.getResponse().getHeader(ToHeader.NAME); ToHeader toHeader = (ToHeader)event.getResponse().getHeader(ToHeader.NAME);
try { try {
this.request.getToHeader().setTag(toHeader.getTag()); this.request.getToHeader().setTag(toHeader.getTag());
} catch (ParseException e) { } catch (ParseException e) {
logger.info("[目录订阅]成功: 但为request设置ToTag失败"); log.info("[目录订阅]成功: 但为request设置ToTag失败");
this.request = null; this.request = null;
} }
},eventResult -> { },eventResult -> {
this.request = null; this.request = null;
// 失败 // 失败
logger.warn("[目录订阅]失败,信令发送失败: {}-{} ", device.getDeviceId(), eventResult.msg); log.warn("[目录订阅]失败,信令发送失败: {}-{} ", device.getDeviceId(), eventResult.msg);
dynamicTask.startDelay(taskKey, CatalogSubscribeTask.this, 2000); dynamicTask.startDelay(taskKey, CatalogSubscribeTask.this, 2000);
}); });
} catch (InvalidArgumentException | SipException | ParseException e) { } catch (InvalidArgumentException | SipException | ParseException e) {
logger.error("[命令发送失败] 目录订阅: {}", e.getMessage()); log.error("[命令发送失败] 目录订阅: {}", e.getMessage());
} }
if (sipRequest != null) { if (sipRequest != null) {
@ -79,7 +78,7 @@ public class CatalogSubscribeTask implements ISubscribeTask {
* COMPLETED-> Completed Dialog状态-已完成 * COMPLETED-> Completed Dialog状态-已完成
* TERMINATED-> Terminated Dialog状态-终止 * TERMINATED-> Terminated Dialog状态-终止
*/ */
logger.info("取消目录订阅时dialog状态为{}", DialogState.CONFIRMED); log.info("取消目录订阅时dialog状态为{}", DialogState.CONFIRMED);
if (dynamicTask.get(taskKey) != null) { if (dynamicTask.get(taskKey) != null) {
dynamicTask.stop(taskKey); dynamicTask.stop(taskKey);
} }
@ -89,20 +88,20 @@ public class CatalogSubscribeTask implements ISubscribeTask {
ResponseEvent event = (ResponseEvent) eventResult.event; ResponseEvent event = (ResponseEvent) eventResult.event;
if (event.getResponse().getRawContent() != null) { if (event.getResponse().getRawContent() != null) {
// 成功 // 成功
logger.info("[取消目录订阅]成功: {}", device.getDeviceId()); log.info("[取消目录订阅]成功: {}", device.getDeviceId());
}else { }else {
// 成功 // 成功
logger.info("[取消目录订阅]成功: {}", device.getDeviceId()); log.info("[取消目录订阅]成功: {}", device.getDeviceId());
} }
if (callback != null) { if (callback != null) {
callback.run(event.getResponse().getRawContent() != null); callback.run(event.getResponse().getRawContent() != null);
} }
},eventResult -> { },eventResult -> {
// 失败 // 失败
logger.warn("[取消目录订阅]失败,信令发送失败: {}-{} ", device.getDeviceId(), eventResult.msg); log.warn("[取消目录订阅]失败,信令发送失败: {}-{} ", device.getDeviceId(), eventResult.msg);
}); });
} catch (InvalidArgumentException | SipException | ParseException e) { } catch (InvalidArgumentException | SipException | ParseException e) {
logger.error("[命令发送失败] 取消目录订阅: {}", e.getMessage()); log.error("[命令发送失败] 取消目录订阅: {}", e.getMessage());
} }
} }
} }

View File

@ -6,8 +6,7 @@ import com.genersoft.iot.vmp.gb28181.bean.Device;
import com.genersoft.iot.vmp.gb28181.task.ISubscribeTask; import com.genersoft.iot.vmp.gb28181.task.ISubscribeTask;
import com.genersoft.iot.vmp.gb28181.transmit.cmd.ISIPCommander; import com.genersoft.iot.vmp.gb28181.transmit.cmd.ISIPCommander;
import gov.nist.javax.sip.message.SIPRequest; import gov.nist.javax.sip.message.SIPRequest;
import org.slf4j.Logger; import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import javax.sip.InvalidArgumentException; import javax.sip.InvalidArgumentException;
import javax.sip.ResponseEvent; import javax.sip.ResponseEvent;
@ -19,8 +18,8 @@ import java.text.ParseException;
* 移动位置订阅的定时更新 * 移动位置订阅的定时更新
* @author lin * @author lin
*/ */
@Slf4j
public class MobilePositionSubscribeTask implements ISubscribeTask { public class MobilePositionSubscribeTask implements ISubscribeTask {
private final Logger logger = LoggerFactory.getLogger(MobilePositionSubscribeTask.class);
private final Device device; private final Device device;
private final ISIPCommander sipCommander; private final ISIPCommander sipCommander;
@ -43,23 +42,23 @@ public class MobilePositionSubscribeTask implements ISubscribeTask {
try { try {
sipRequest = sipCommander.mobilePositionSubscribe(device, request, eventResult -> { sipRequest = sipCommander.mobilePositionSubscribe(device, request, eventResult -> {
// 成功 // 成功
logger.info("[移动位置订阅]成功: {}", device.getDeviceId()); log.info("[移动位置订阅]成功: {}", device.getDeviceId());
ResponseEvent event = (ResponseEvent) eventResult.event; ResponseEvent event = (ResponseEvent) eventResult.event;
ToHeader toHeader = (ToHeader)event.getResponse().getHeader(ToHeader.NAME); ToHeader toHeader = (ToHeader)event.getResponse().getHeader(ToHeader.NAME);
try { try {
this.request.getToHeader().setTag(toHeader.getTag()); this.request.getToHeader().setTag(toHeader.getTag());
} catch (ParseException e) { } catch (ParseException e) {
logger.info("[移动位置订阅]成功: 为request设置ToTag失败"); log.info("[移动位置订阅]成功: 为request设置ToTag失败");
this.request = null; this.request = null;
} }
},eventResult -> { },eventResult -> {
this.request = null; this.request = null;
// 失败 // 失败
logger.warn("[移动位置订阅]失败,信令发送失败: {}-{} ", device.getDeviceId(), eventResult.msg); log.warn("[移动位置订阅]失败,信令发送失败: {}-{} ", device.getDeviceId(), eventResult.msg);
dynamicTask.startDelay(taskKey, MobilePositionSubscribeTask.this, 2000); dynamicTask.startDelay(taskKey, MobilePositionSubscribeTask.this, 2000);
}); });
} catch (InvalidArgumentException | SipException | ParseException e) { } catch (InvalidArgumentException | SipException | ParseException e) {
logger.error("[命令发送失败] 移动位置订阅: {}", e.getMessage()); log.error("[命令发送失败] 移动位置订阅: {}", e.getMessage());
} }
if (sipRequest != null) { if (sipRequest != null) {
this.request = sipRequest; this.request = sipRequest;
@ -85,20 +84,20 @@ public class MobilePositionSubscribeTask implements ISubscribeTask {
ResponseEvent event = (ResponseEvent) eventResult.event; ResponseEvent event = (ResponseEvent) eventResult.event;
if (event.getResponse().getRawContent() != null) { if (event.getResponse().getRawContent() != null) {
// 成功 // 成功
logger.info("[取消移动位置订阅]成功: {}", device.getDeviceId()); log.info("[取消移动位置订阅]成功: {}", device.getDeviceId());
}else { }else {
// 成功 // 成功
logger.info("[取消移动位置订阅]成功: {}", device.getDeviceId()); log.info("[取消移动位置订阅]成功: {}", device.getDeviceId());
} }
if (callback != null) { if (callback != null) {
callback.run(event.getResponse().getRawContent() != null); callback.run(event.getResponse().getRawContent() != null);
} }
},eventResult -> { },eventResult -> {
// 失败 // 失败
logger.warn("[取消移动位置订阅]失败,信令发送失败: {}-{} ", device.getDeviceId(), eventResult.msg); log.warn("[取消移动位置订阅]失败,信令发送失败: {}-{} ", device.getDeviceId(), eventResult.msg);
}); });
} catch (InvalidArgumentException | SipException | ParseException e) { } catch (InvalidArgumentException | SipException | ParseException e) {
logger.error("[命令发送失败] 取消移动位置订阅: {}", e.getMessage()); log.error("[命令发送失败] 取消移动位置订阅: {}", e.getMessage());
} }
} }
} }

View File

@ -27,8 +27,7 @@ import com.genersoft.iot.vmp.utils.GitUtil;
import gov.nist.javax.sip.message.MessageFactoryImpl; import gov.nist.javax.sip.message.MessageFactoryImpl;
import gov.nist.javax.sip.message.SIPRequest; import gov.nist.javax.sip.message.SIPRequest;
import gov.nist.javax.sip.message.SIPResponse; import gov.nist.javax.sip.message.SIPResponse;
import org.slf4j.Logger; import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn; import org.springframework.context.annotation.DependsOn;
import org.springframework.lang.Nullable; import org.springframework.lang.Nullable;
@ -46,12 +45,11 @@ import java.text.ParseException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@Slf4j
@Component @Component
@DependsOn("sipLayer") @DependsOn("sipLayer")
public class SIPCommanderFroPlatform implements ISIPCommanderForPlatform { public class SIPCommanderFroPlatform implements ISIPCommanderForPlatform {
private final Logger logger = LoggerFactory.getLogger(SIPCommanderFroPlatform.class);
@Autowired @Autowired
private SIPRequestHeaderPlarformProvider headerProviderPlatformProvider; private SIPRequestHeaderPlarformProvider headerProviderPlatformProvider;
@ -132,7 +130,7 @@ public class SIPCommanderFroPlatform implements ISIPCommanderForPlatform {
sipSubscribe.addErrorSubscribe(callIdHeader.getCallId(), (event)->{ sipSubscribe.addErrorSubscribe(callIdHeader.getCallId(), (event)->{
if (event != null) { if (event != null) {
logger.info("向上级平台 [ {} ] 注册发生错误: {} ", log.info("向上级平台 [ {} ] 注册发生错误: {} ",
parentPlatform.getServerGBId(), parentPlatform.getServerGBId(),
event.msg); event.msg);
} }
@ -247,9 +245,9 @@ public class SIPCommanderFroPlatform implements ISIPCommanderForPlatform {
String callId = request.getCallIdHeader().getCallId(); String callId = request.getCallIdHeader().getCallId();
logger.info("[命令发送] 国标级联{} 目录查询回复: 共{}条,已发送{}条", parentPlatform.getServerGBId(), log.info("[命令发送] 国标级联{} 目录查询回复: 共{}条,已发送{}条", parentPlatform.getServerGBId(),
channels.size(), Math.min(index + parentPlatform.getCatalogGroup(), channels.size())); channels.size(), Math.min(index + parentPlatform.getCatalogGroup(), channels.size()));
logger.debug(catalogXml); log.debug(catalogXml);
if (sendAfterResponse) { if (sendAfterResponse) {
// 默认按照收到200回复后发送下一条 如果超时收不到回复就以30毫秒的间隔直接发送 // 默认按照收到200回复后发送下一条 如果超时收不到回复就以30毫秒的间隔直接发送
dynamicTask.startDelay(timeoutTaskKey, ()->{ dynamicTask.startDelay(timeoutTaskKey, ()->{
@ -258,11 +256,11 @@ public class SIPCommanderFroPlatform implements ISIPCommanderForPlatform {
try { try {
sendCatalogResponse(channels, parentPlatform, sn, fromTag, indexNext, false); sendCatalogResponse(channels, parentPlatform, sn, fromTag, indexNext, false);
} catch (SipException | InvalidArgumentException | ParseException e) { } catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] 国标级联 目录查询回复: {}", e.getMessage()); log.error("[命令发送失败] 国标级联 目录查询回复: {}", e.getMessage());
} }
}, 3000); }, 3000);
sipSender.transmitRequest(parentPlatform.getDeviceIp(), request, eventResult -> { sipSender.transmitRequest(parentPlatform.getDeviceIp(), request, eventResult -> {
logger.error("[目录推送失败] 国标级联 platform : {}, code: {}, msg: {}, 停止发送", parentPlatform.getServerGBId(), eventResult.statusCode, eventResult.msg); log.error("[目录推送失败] 国标级联 platform : {}, code: {}, msg: {}, 停止发送", parentPlatform.getServerGBId(), eventResult.statusCode, eventResult.msg);
dynamicTask.stop(timeoutTaskKey); dynamicTask.stop(timeoutTaskKey);
}, eventResult -> { }, eventResult -> {
dynamicTask.stop(timeoutTaskKey); dynamicTask.stop(timeoutTaskKey);
@ -270,12 +268,12 @@ public class SIPCommanderFroPlatform implements ISIPCommanderForPlatform {
try { try {
sendCatalogResponse(channels, parentPlatform, sn, fromTag, indexNext, true); sendCatalogResponse(channels, parentPlatform, sn, fromTag, indexNext, true);
} catch (SipException | InvalidArgumentException | ParseException e) { } catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] 国标级联 目录查询回复: {}", e.getMessage()); log.error("[命令发送失败] 国标级联 目录查询回复: {}", e.getMessage());
} }
}); });
}else { }else {
sipSender.transmitRequest(parentPlatform.getDeviceIp(), request, eventResult -> { sipSender.transmitRequest(parentPlatform.getDeviceIp(), request, eventResult -> {
logger.error("[目录推送失败] 国标级联 platform : {}, code: {}, msg: {}, 停止发送", parentPlatform.getServerGBId(), eventResult.statusCode, eventResult.msg); log.error("[目录推送失败] 国标级联 platform : {}, code: {}, msg: {}, 停止发送", parentPlatform.getServerGBId(), eventResult.statusCode, eventResult.msg);
dynamicTask.stop(timeoutTaskKey); dynamicTask.stop(timeoutTaskKey);
}, null); }, null);
dynamicTask.startDelay(timeoutTaskKey, ()->{ dynamicTask.startDelay(timeoutTaskKey, ()->{
@ -283,7 +281,7 @@ public class SIPCommanderFroPlatform implements ISIPCommanderForPlatform {
try { try {
sendCatalogResponse(channels, parentPlatform, sn, fromTag, indexNext, false); sendCatalogResponse(channels, parentPlatform, sn, fromTag, indexNext, false);
} catch (SipException | InvalidArgumentException | ParseException e) { } catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] 国标级联 目录查询回复: {}", e.getMessage()); log.error("[命令发送失败] 国标级联 目录查询回复: {}", e.getMessage());
} }
}, 30); }, 30);
} }
@ -363,7 +361,7 @@ public class SIPCommanderFroPlatform implements ISIPCommanderForPlatform {
if (parentPlatform == null) { if (parentPlatform == null) {
return; return;
} }
logger.info("[发送 移动位置订阅] {}/{}->{},{}", parentPlatform.getServerGBId(), gpsMsgInfo.getId(), gpsMsgInfo.getLng(), gpsMsgInfo.getLat()); log.info("[发送 移动位置订阅] {}/{}->{},{}", parentPlatform.getServerGBId(), gpsMsgInfo.getId(), gpsMsgInfo.getLng(), gpsMsgInfo.getLat());
String characterSet = parentPlatform.getCharacterSet(); String characterSet = parentPlatform.getCharacterSet();
StringBuffer deviceStatusXml = new StringBuffer(600); StringBuffer deviceStatusXml = new StringBuffer(600);
@ -381,7 +379,7 @@ public class SIPCommanderFroPlatform implements ISIPCommanderForPlatform {
.append("</Notify>\r\n"); .append("</Notify>\r\n");
sendNotify(parentPlatform, deviceStatusXml.toString(), subscribeInfo, eventResult -> { sendNotify(parentPlatform, deviceStatusXml.toString(), subscribeInfo, eventResult -> {
logger.error("发送NOTIFY通知消息失败。错误{} {}", eventResult.statusCode, eventResult.msg); log.error("发送NOTIFY通知消息失败。错误{} {}", eventResult.statusCode, eventResult.msg);
}, null); }, null);
} }
@ -391,7 +389,7 @@ public class SIPCommanderFroPlatform implements ISIPCommanderForPlatform {
if (parentPlatform == null) { if (parentPlatform == null) {
return; return;
} }
logger.info("[发送报警通知]平台: {}/{}->{},{}: {}", parentPlatform.getServerGBId(), deviceAlarm.getChannelId(), log.info("[发送报警通知]平台: {}/{}->{},{}: {}", parentPlatform.getServerGBId(), deviceAlarm.getChannelId(),
deviceAlarm.getLongitude(), deviceAlarm.getLatitude(), JSON.toJSONString(deviceAlarm)); deviceAlarm.getLongitude(), deviceAlarm.getLatitude(), JSON.toJSONString(deviceAlarm));
String characterSet = parentPlatform.getCharacterSet(); String characterSet = parentPlatform.getCharacterSet();
StringBuffer deviceStatusXml = new StringBuffer(600); StringBuffer deviceStatusXml = new StringBuffer(600);
@ -439,16 +437,16 @@ public class SIPCommanderFroPlatform implements ISIPCommanderForPlatform {
String catalogXmlContent = getCatalogXmlContentForCatalogAddOrUpdate(parentPlatform, channels, String catalogXmlContent = getCatalogXmlContentForCatalogAddOrUpdate(parentPlatform, channels,
deviceChannels.size(), type, subscribeInfo); deviceChannels.size(), type, subscribeInfo);
System.out.println(catalogXmlContent); System.out.println(catalogXmlContent);
logger.info("[发送NOTIFY通知]类型: {},发送数量: {}", type, channels.size()); log.info("[发送NOTIFY通知]类型: {},发送数量: {}", type, channels.size());
sendNotify(parentPlatform, catalogXmlContent, subscribeInfo, eventResult -> { sendNotify(parentPlatform, catalogXmlContent, subscribeInfo, eventResult -> {
logger.error("发送NOTIFY通知消息失败。错误{} {}", eventResult.statusCode, eventResult.msg); log.error("发送NOTIFY通知消息失败。错误{} {}", eventResult.statusCode, eventResult.msg);
}, (eventResult -> { }, (eventResult -> {
try { try {
sendNotifyForCatalogAddOrUpdate(type, parentPlatform, deviceChannels, subscribeInfo, sendNotifyForCatalogAddOrUpdate(type, parentPlatform, deviceChannels, subscribeInfo,
finalIndex + parentPlatform.getCatalogGroup()); finalIndex + parentPlatform.getCatalogGroup());
} catch (InvalidArgumentException | ParseException | NoSuchFieldException | SipException | } catch (InvalidArgumentException | ParseException | NoSuchFieldException | SipException |
IllegalAccessException e) { IllegalAccessException e) {
logger.error("[命令发送失败] 国标级联 NOTIFY通知: {}", e.getMessage()); log.error("[命令发送失败] 国标级联 NOTIFY通知: {}", e.getMessage());
} }
})); }));
} }
@ -493,7 +491,7 @@ public class SIPCommanderFroPlatform implements ISIPCommanderForPlatform {
|| deviceChannels == null || deviceChannels == null
|| deviceChannels.size() == 0 || deviceChannels.size() == 0
|| subscribeInfo == null) { || subscribeInfo == null) {
logger.warn("[缺少必要参数]"); log.warn("[缺少必要参数]");
return; return;
} }
@ -509,18 +507,18 @@ public class SIPCommanderFroPlatform implements ISIPCommanderForPlatform {
}else { }else {
channels = deviceChannels.subList(index, deviceChannels.size()); channels = deviceChannels.subList(index, deviceChannels.size());
} }
logger.info("[发送NOTIFY通知]类型: {},发送数量: {}", type, channels.size()); log.info("[发送NOTIFY通知]类型: {},发送数量: {}", type, channels.size());
Integer finalIndex = index; Integer finalIndex = index;
String catalogXmlContent = getCatalogXmlContentForCatalogOther(parentPlatform, channels, type); String catalogXmlContent = getCatalogXmlContentForCatalogOther(parentPlatform, channels, type);
sendNotify(parentPlatform, catalogXmlContent, subscribeInfo, eventResult -> { sendNotify(parentPlatform, catalogXmlContent, subscribeInfo, eventResult -> {
logger.error("发送NOTIFY通知消息失败。错误{} {}", eventResult.statusCode, eventResult.msg); log.error("发送NOTIFY通知消息失败。错误{} {}", eventResult.statusCode, eventResult.msg);
}, eventResult -> { }, eventResult -> {
try { try {
sendNotifyForCatalogOther(type, parentPlatform, deviceChannels, subscribeInfo, sendNotifyForCatalogOther(type, parentPlatform, deviceChannels, subscribeInfo,
finalIndex + parentPlatform.getCatalogGroup()); finalIndex + parentPlatform.getCatalogGroup());
} catch (InvalidArgumentException | ParseException | NoSuchFieldException | SipException | } catch (InvalidArgumentException | ParseException | NoSuchFieldException | SipException |
IllegalAccessException e) { IllegalAccessException e) {
logger.error("[命令发送失败] 国标级联 NOTIFY通知: {}", e.getMessage()); log.error("[命令发送失败] 国标级联 NOTIFY通知: {}", e.getMessage());
} }
}); });
} }
@ -550,7 +548,7 @@ public class SIPCommanderFroPlatform implements ISIPCommanderForPlatform {
if ( parentPlatform ==null) { if ( parentPlatform ==null) {
return ; return ;
} }
logger.info("[国标级联] 发送录像数据通道: {}", recordInfo.getChannelId()); log.info("[国标级联] 发送录像数据通道: {}", recordInfo.getChannelId());
String characterSet = parentPlatform.getCharacterSet(); String characterSet = parentPlatform.getCharacterSet();
StringBuffer recordXml = new StringBuffer(600); StringBuffer recordXml = new StringBuffer(600);
recordXml.append("<?xml version=\"1.0\" encoding=\"" + characterSet + "\"?>\r\n") recordXml.append("<?xml version=\"1.0\" encoding=\"" + characterSet + "\"?>\r\n")
@ -587,13 +585,13 @@ public class SIPCommanderFroPlatform implements ISIPCommanderForPlatform {
recordXml.append("</RecordList>\r\n") recordXml.append("</RecordList>\r\n")
.append("</Response>\r\n"); .append("</Response>\r\n");
logger.info("[国标级联] 发送录像数据通道:{}, 内容: {}", recordInfo.getChannelId(), recordXml); log.info("[国标级联] 发送录像数据通道:{}, 内容: {}", recordInfo.getChannelId(), recordXml);
// callid // callid
CallIdHeader callIdHeader = sipSender.getNewCallIdHeader(parentPlatform.getDeviceIp(),parentPlatform.getTransport()); CallIdHeader callIdHeader = sipSender.getNewCallIdHeader(parentPlatform.getDeviceIp(),parentPlatform.getTransport());
Request request = headerProviderPlatformProvider.createMessageRequest(parentPlatform, recordXml.toString(), fromTag, SipUtils.getNewViaTag(), callIdHeader); Request request = headerProviderPlatformProvider.createMessageRequest(parentPlatform, recordXml.toString(), fromTag, SipUtils.getNewViaTag(), callIdHeader);
sipSender.transmitRequest(parentPlatform.getDeviceIp(), request, null, eventResult -> { sipSender.transmitRequest(parentPlatform.getDeviceIp(), request, null, eventResult -> {
logger.info("[国标级联] 发送录像数据通道:{}, 发送成功", recordInfo.getChannelId()); log.info("[国标级联] 发送录像数据通道:{}, 发送成功", recordInfo.getChannelId());
}); });
} }
@ -636,14 +634,14 @@ public class SIPCommanderFroPlatform implements ISIPCommanderForPlatform {
@Override @Override
public synchronized void streamByeCmd(ParentPlatform platform, SendRtpItem sendRtpItem) throws SipException, InvalidArgumentException, ParseException { public synchronized void streamByeCmd(ParentPlatform platform, SendRtpItem sendRtpItem) throws SipException, InvalidArgumentException, ParseException {
if (sendRtpItem == null ) { if (sendRtpItem == null ) {
logger.info("[向上级发送BYE] sendRtpItem 为NULL"); log.info("[向上级发送BYE] sendRtpItem 为NULL");
return; return;
} }
if (platform == null) { if (platform == null) {
logger.info("[向上级发送BYE] platform 为NULL"); log.info("[向上级发送BYE] platform 为NULL");
return; return;
} }
logger.info("[向上级发送BYE] {}/{}", platform.getServerGBId(), sendRtpItem.getChannelId()); log.info("[向上级发送BYE] {}/{}", platform.getServerGBId(), sendRtpItem.getChannelId());
String mediaServerId = sendRtpItem.getMediaServerId(); String mediaServerId = sendRtpItem.getMediaServerId();
MediaServer mediaServerItem = mediaServerService.getOne(mediaServerId); MediaServer mediaServerItem = mediaServerService.getOne(mediaServerId);
if (mediaServerItem != null) { if (mediaServerItem != null) {
@ -652,7 +650,7 @@ public class SIPCommanderFroPlatform implements ISIPCommanderForPlatform {
} }
SIPRequest byeRequest = headerProviderPlatformProvider.createByeRequest(platform, sendRtpItem); SIPRequest byeRequest = headerProviderPlatformProvider.createByeRequest(platform, sendRtpItem);
if (byeRequest == null) { if (byeRequest == null) {
logger.warn("[向上级发送bye]:无法创建 byeRequest"); log.warn("[向上级发送bye]:无法创建 byeRequest");
} }
sipSender.transmitRequest(platform.getDeviceIp(),byeRequest); sipSender.transmitRequest(platform.getDeviceIp(),byeRequest);
} }
@ -705,7 +703,7 @@ public class SIPCommanderFroPlatform implements ISIPCommanderForPlatform {
return; return;
} }
logger.info("{} 分配的ZLM为: {} [{}:{}]", stream, mediaServerItem.getId(), mediaServerItem.getIp(), ssrcInfo.getPort()); log.info("{} 分配的ZLM为: {} [{}:{}]", stream, mediaServerItem.getId(), mediaServerItem.getIp(), ssrcInfo.getPort());
Hook hook = Hook.getInstance(HookType.on_media_arrival, "rtp", stream, mediaServerItem.getId()); Hook hook = Hook.getInstance(HookType.on_media_arrival, "rtp", stream, mediaServerItem.getId());
subscribe.addSubscribe(hook, (hookData) -> { subscribe.addSubscribe(hook, (hookData) -> {
if (event != null) { if (event != null) {

View File

@ -17,9 +17,8 @@ import com.genersoft.iot.vmp.storager.IRedisCatchStorage;
import com.genersoft.iot.vmp.storager.IVideoManagerStorage; import com.genersoft.iot.vmp.storager.IVideoManagerStorage;
import com.genersoft.iot.vmp.utils.DateUtil; import com.genersoft.iot.vmp.utils.DateUtil;
import gov.nist.javax.sip.message.SIPRequest; import gov.nist.javax.sip.message.SIPRequest;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Element; import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Qualifier;
@ -39,10 +38,10 @@ import static com.genersoft.iot.vmp.gb28181.utils.XmlUtil.getText;
/** /**
* 报警事件的处理参考9.4 * 报警事件的处理参考9.4
*/ */
@Slf4j
@Component @Component
public class AlarmNotifyMessageHandler extends SIPRequestProcessorParent implements InitializingBean, IMessageHandler { public class AlarmNotifyMessageHandler extends SIPRequestProcessorParent implements InitializingBean, IMessageHandler {
private final Logger logger = LoggerFactory.getLogger(AlarmNotifyMessageHandler.class);
private final String cmdType = "Alarm"; private final String cmdType = "Alarm";
@Autowired @Autowired
@ -86,18 +85,18 @@ public class AlarmNotifyMessageHandler extends SIPRequestProcessorParent impleme
@Override @Override
public void handForDevice(RequestEvent evt, Device device, Element rootElement) { public void handForDevice(RequestEvent evt, Device device, Element rootElement) {
logger.info("[收到报警通知]设备:{}", device.getDeviceId()); log.info("[收到报警通知]设备:{}", device.getDeviceId());
boolean isEmpty = taskQueue.isEmpty(); boolean isEmpty = taskQueue.isEmpty();
taskQueue.offer(new SipMsgInfo(evt, device, rootElement)); taskQueue.offer(new SipMsgInfo(evt, device, rootElement));
// 回复200 OK // 回复200 OK
try { try {
responseAck((SIPRequest) evt.getRequest(), Response.OK); responseAck((SIPRequest) evt.getRequest(), Response.OK);
} catch (SipException | InvalidArgumentException | ParseException e) { } catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] 报警通知回复: {}", e.getMessage()); log.error("[命令发送失败] 报警通知回复: {}", e.getMessage());
} }
if (isEmpty) { if (isEmpty) {
taskExecutor.execute(() -> { taskExecutor.execute(() -> {
logger.info("[处理报警通知]待处理数量:{}", taskQueue.size() ); log.info("[处理报警通知]待处理数量:{}", taskQueue.size() );
while (!taskQueue.isEmpty()) { while (!taskQueue.isEmpty()) {
try { try {
SipMsgInfo sipMsgInfo = taskQueue.poll(); SipMsgInfo sipMsgInfo = taskQueue.poll();
@ -162,11 +161,11 @@ public class AlarmNotifyMessageHandler extends SIPRequestProcessorParent impleme
deviceAlarm.setAlarmType(getText(sipMsgInfo.getRootElement().element("Info"), "AlarmType")); deviceAlarm.setAlarmType(getText(sipMsgInfo.getRootElement().element("Info"), "AlarmType"));
} }
} }
logger.info("[收到报警通知]内容:{}", JSON.toJSONString(deviceAlarm)); log.info("[收到报警通知]内容:{}", JSON.toJSONString(deviceAlarm));
// 作者自用判断其他小伙伴需要此消息可以自行修改但是不要提在pr里 // 作者自用判断其他小伙伴需要此消息可以自行修改但是不要提在pr里
if (DeviceAlarmMethod.Other.getVal() == Integer.parseInt(deviceAlarm.getAlarmMethod())) { if (DeviceAlarmMethod.Other.getVal() == Integer.parseInt(deviceAlarm.getAlarmMethod())) {
// 发送给平台的报警信息 发送redis通知 // 发送给平台的报警信息 发送redis通知
logger.info("[发送给平台的报警信息]内容:{}", JSONObject.toJSONString(deviceAlarm)); log.info("[发送给平台的报警信息]内容:{}", JSONObject.toJSONString(deviceAlarm));
AlarmChannelMessage alarmChannelMessage = new AlarmChannelMessage(); AlarmChannelMessage alarmChannelMessage = new AlarmChannelMessage();
if (deviceAlarm.getAlarmMethod() != null) { if (deviceAlarm.getAlarmMethod() != null) {
alarmChannelMessage.setAlarmSn(Integer.parseInt(deviceAlarm.getAlarmMethod())); alarmChannelMessage.setAlarmSn(Integer.parseInt(deviceAlarm.getAlarmMethod()));
@ -180,7 +179,7 @@ public class AlarmNotifyMessageHandler extends SIPRequestProcessorParent impleme
continue; continue;
} }
logger.debug("存储报警信息、报警分类"); log.debug("存储报警信息、报警分类");
// 存储报警信息报警分类 // 存储报警信息报警分类
if (sipConfig.isAlarm()) { if (sipConfig.isAlarm()) {
deviceAlarmService.add(deviceAlarm); deviceAlarmService.add(deviceAlarm);
@ -190,8 +189,8 @@ public class AlarmNotifyMessageHandler extends SIPRequestProcessorParent impleme
publisher.deviceAlarmEventPublish(deviceAlarm); publisher.deviceAlarmEventPublish(deviceAlarm);
} }
}catch (Exception e) { }catch (Exception e) {
logger.error("未处理的异常 ", e); log.error("未处理的异常 ", e);
logger.warn("[收到报警通知] 发现未处理的异常, {}\r\n{}",e.getMessage(), evt.getRequest()); log.warn("[收到报警通知] 发现未处理的异常, {}\r\n{}",e.getMessage(), evt.getRequest());
} }
} }
}); });
@ -200,12 +199,12 @@ public class AlarmNotifyMessageHandler extends SIPRequestProcessorParent impleme
@Override @Override
public void handForPlatform(RequestEvent evt, ParentPlatform parentPlatform, Element rootElement) { public void handForPlatform(RequestEvent evt, ParentPlatform parentPlatform, Element rootElement) {
logger.info("收到来自平台[{}]的报警通知", parentPlatform.getServerGBId()); log.info("收到来自平台[{}]的报警通知", parentPlatform.getServerGBId());
// 回复200 OK // 回复200 OK
try { try {
responseAck((SIPRequest) evt.getRequest(), Response.OK); responseAck((SIPRequest) evt.getRequest(), Response.OK);
} catch (SipException | InvalidArgumentException | ParseException e) { } catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] 国标级联 报警通知回复: {}", e.getMessage()); log.error("[命令发送失败] 国标级联 报警通知回复: {}", e.getMessage());
} }
Element deviceIdElement = rootElement.element("DeviceID"); Element deviceIdElement = rootElement.element("DeviceID");
String channelId = deviceIdElement.getText().toString(); String channelId = deviceIdElement.getText().toString();

View File

@ -13,10 +13,9 @@ import com.genersoft.iot.vmp.storager.IRedisCatchStorage;
import com.genersoft.iot.vmp.storager.IVideoManagerStorage; import com.genersoft.iot.vmp.storager.IVideoManagerStorage;
import com.genersoft.iot.vmp.utils.DateUtil; import com.genersoft.iot.vmp.utils.DateUtil;
import gov.nist.javax.sip.message.SIPRequest; import gov.nist.javax.sip.message.SIPRequest;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.DocumentException; import org.dom4j.DocumentException;
import org.dom4j.Element; import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Qualifier;
@ -36,10 +35,10 @@ import static com.genersoft.iot.vmp.gb28181.utils.XmlUtil.getText;
/** /**
* 移动设备位置数据通知设备主动发起不需要上级订阅 * 移动设备位置数据通知设备主动发起不需要上级订阅
*/ */
@Slf4j
@Component @Component
public class MobilePositionNotifyMessageHandler extends SIPRequestProcessorParent implements InitializingBean, IMessageHandler { public class MobilePositionNotifyMessageHandler extends SIPRequestProcessorParent implements InitializingBean, IMessageHandler {
private Logger logger = LoggerFactory.getLogger(MobilePositionNotifyMessageHandler.class);
private final String cmdType = "MobilePosition"; private final String cmdType = "MobilePosition";
@Autowired @Autowired
@ -80,7 +79,7 @@ public class MobilePositionNotifyMessageHandler extends SIPRequestProcessorParen
try { try {
responseAck((SIPRequest) evt.getRequest(), Response.OK); responseAck((SIPRequest) evt.getRequest(), Response.OK);
} catch (SipException | InvalidArgumentException | ParseException e) { } catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] 移动位置通知回复: {}", e.getMessage()); log.error("[命令发送失败] 移动位置通知回复: {}", e.getMessage());
} }
if (isEmpty) { if (isEmpty) {
taskExecutor.execute(() -> { taskExecutor.execute(() -> {
@ -89,7 +88,7 @@ public class MobilePositionNotifyMessageHandler extends SIPRequestProcessorParen
try { try {
Element rootElementAfterCharset = getRootElement(sipMsgInfo.getEvt(), sipMsgInfo.getDevice().getCharset()); Element rootElementAfterCharset = getRootElement(sipMsgInfo.getEvt(), sipMsgInfo.getDevice().getCharset());
if (rootElementAfterCharset == null) { if (rootElementAfterCharset == null) {
logger.warn("[移动位置通知] {}处理失败,未识别到信息体", device.getDeviceId()); log.warn("[移动位置通知] {}处理失败,未识别到信息体", device.getDeviceId());
continue; continue;
} }
MobilePosition mobilePosition = new MobilePosition(); MobilePosition mobilePosition = new MobilePosition();
@ -136,10 +135,10 @@ public class MobilePositionNotifyMessageHandler extends SIPRequestProcessorParen
deviceChannelService.updateChannelGPS(device, deviceChannel, mobilePosition); deviceChannelService.updateChannelGPS(device, deviceChannel, mobilePosition);
} catch (DocumentException e) { } catch (DocumentException e) {
logger.error("未处理的异常 ", e); log.error("未处理的异常 ", e);
} catch (Exception e) { } catch (Exception e) {
logger.warn("[移动位置通知] 发现未处理的异常, \r\n{}", evt.getRequest()); log.warn("[移动位置通知] 发现未处理的异常, \r\n{}", evt.getRequest());
logger.error("[移动位置通知] 异常内容: ", e); log.error("[移动位置通知] 异常内容: ", e);
} }
} }
}); });

View File

@ -1,7 +1,6 @@
package com.genersoft.iot.vmp.jt1078.util; package com.genersoft.iot.vmp.jt1078.util;
import org.slf4j.Logger; import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource; import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternResolver;
@ -10,17 +9,15 @@ import java.lang.annotation.Annotation;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
@Slf4j
public class ClassUtil { public class ClassUtil {
private static final Logger logger = LoggerFactory.getLogger(ClassUtil.class);
public static Object getBean(Class<?> clazz) { public static Object getBean(Class<?> clazz) {
if (clazz != null) { if (clazz != null) {
try { try {
return clazz.getDeclaredConstructor().newInstance(); return clazz.getDeclaredConstructor().newInstance();
} catch (Exception ex) { } catch (Exception ex) {
logger.error("ClassUtil:找不到指定的类", ex); log.error("ClassUtil:找不到指定的类", ex);
} }
} }
return null; return null;
@ -32,14 +29,14 @@ public class ClassUtil {
try { try {
clazz = Class.forName(className); clazz = Class.forName(className);
} catch (Exception ex) { } catch (Exception ex) {
logger.error("ClassUtil:找不到指定的类"); log.error("ClassUtil:找不到指定的类");
} }
if (clazz != null) { if (clazz != null) {
try { try {
//获取声明的构造器--创建实例 //获取声明的构造器--创建实例
return clazz.getDeclaredConstructor().newInstance(); return clazz.getDeclaredConstructor().newInstance();
} catch (Exception ex) { } catch (Exception ex) {
logger.error("ClassUtil:找不到指定的类", ex); log.error("ClassUtil:找不到指定的类", ex);
} }
} }
return null; return null;

View File

@ -4,8 +4,7 @@ import com.genersoft.iot.vmp.conf.MediaConfig;
import com.genersoft.iot.vmp.media.bean.MediaServer; import com.genersoft.iot.vmp.media.bean.MediaServer;
import com.genersoft.iot.vmp.media.event.mediaServer.MediaServerChangeEvent; import com.genersoft.iot.vmp.media.event.mediaServer.MediaServerChangeEvent;
import com.genersoft.iot.vmp.media.service.IMediaServerService; import com.genersoft.iot.vmp.media.service.IMediaServerService;
import org.slf4j.Logger; import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner; import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationEventPublisher;
@ -17,12 +16,11 @@ import java.util.List;
/** /**
* 启动是从配置文件加载节点信息以及发送个节点状态管理去控制节点状态 * 启动是从配置文件加载节点信息以及发送个节点状态管理去控制节点状态
*/ */
@Slf4j
@Component @Component
@Order(value=12) @Order(value=12)
public class MediaServerConfig implements CommandLineRunner { public class MediaServerConfig implements CommandLineRunner {
private final static Logger logger = LoggerFactory.getLogger(MediaServerConfig.class);
@Autowired @Autowired
private ApplicationEventPublisher applicationEventPublisher; private ApplicationEventPublisher applicationEventPublisher;
@ -56,7 +54,7 @@ public class MediaServerConfig implements CommandLineRunner {
mediaServerService.syncCatchFromDatabase(); mediaServerService.syncCatchFromDatabase();
// 获取所有的zlm 并开启主动连接 // 获取所有的zlm 并开启主动连接
List<MediaServer> all = mediaServerService.getAllFromDatabase(); List<MediaServer> all = mediaServerService.getAllFromDatabase();
logger.info("[媒体节点] 加载节点列表, 共{}个节点", all.size()); log.info("[媒体节点] 加载节点列表, 共{}个节点", all.size());
MediaServerChangeEvent event = new MediaServerChangeEvent(this); MediaServerChangeEvent event = new MediaServerChangeEvent(this);
event.setMediaServerItemList(all); event.setMediaServerItemList(all);
applicationEventPublisher.publishEvent(event); applicationEventPublisher.publishEvent(event);

View File

@ -1,8 +1,7 @@
package com.genersoft.iot.vmp.media.event.mediaServer; package com.genersoft.iot.vmp.media.event.mediaServer;
import com.genersoft.iot.vmp.service.IPlayService; import com.genersoft.iot.vmp.service.IPlayService;
import org.slf4j.Logger; import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener; import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.Async;
@ -16,18 +15,17 @@ import org.springframework.stereotype.Component;
* @author: swwheihei * @author: swwheihei
* @date: 2020年5月6日 下午1:51:23 * @date: 2020年5月6日 下午1:51:23
*/ */
@Slf4j
@Component @Component
public class MediaServerStatusEventListener { public class MediaServerStatusEventListener {
private final static Logger logger = LoggerFactory.getLogger(MediaServerStatusEventListener.class);
@Autowired @Autowired
private IPlayService playService; private IPlayService playService;
@Async("taskExecutor") @Async("taskExecutor")
@EventListener @EventListener
public void onApplicationEvent(MediaServerOnlineEvent event) { public void onApplicationEvent(MediaServerOnlineEvent event) {
logger.info("[媒体节点] 上线 ID" + event.getMediaServerId()); log.info("[媒体节点] 上线 ID" + event.getMediaServerId());
playService.zlmServerOnline(event.getMediaServerId()); playService.zlmServerOnline(event.getMediaServerId());
} }
@ -35,7 +33,7 @@ public class MediaServerStatusEventListener {
@EventListener @EventListener
public void onApplicationEvent(MediaServerOfflineEvent event) { public void onApplicationEvent(MediaServerOfflineEvent event) {
logger.info("[媒体节点] 离线ID" + event.getMediaServerId()); log.info("[媒体节点] 离线ID" + event.getMediaServerId());
// 处理ZLM离线 // 处理ZLM离线
playService.zlmServerOffline(event.getMediaServerId()); playService.zlmServerOffline(event.getMediaServerId());
} }

View File

@ -31,11 +31,10 @@ import com.genersoft.iot.vmp.utils.JsonUtil;
import com.genersoft.iot.vmp.utils.redis.RedisUtil; import com.genersoft.iot.vmp.utils.redis.RedisUtil;
import com.genersoft.iot.vmp.vmanager.bean.ErrorCode; import com.genersoft.iot.vmp.vmanager.bean.ErrorCode;
import com.genersoft.iot.vmp.vmanager.bean.WVPResult; import com.genersoft.iot.vmp.vmanager.bean.WVPResult;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient; import okhttp3.OkHttpClient;
import okhttp3.Request; import okhttp3.Request;
import okhttp3.Response; import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.event.EventListener; import org.springframework.context.event.EventListener;
@ -50,12 +49,11 @@ import java.util.*;
/** /**
* 媒体服务器节点管理 * 媒体服务器节点管理
*/ */
@Slf4j
@Service @Service
@DS("master") @DS("master")
public class MediaServerServiceImpl implements IMediaServerService { public class MediaServerServiceImpl implements IMediaServerService {
private final static Logger logger = LoggerFactory.getLogger(MediaServerServiceImpl.class);
@Autowired @Autowired
private SSRCFactory ssrcFactory; private SSRCFactory ssrcFactory;
@ -95,7 +93,7 @@ public class MediaServerServiceImpl implements IMediaServerService {
@org.springframework.context.event.EventListener @org.springframework.context.event.EventListener
public void onApplicationEvent(MediaArrivalEvent event) { public void onApplicationEvent(MediaArrivalEvent event) {
if ("rtsp".equals(event.getSchema())) { if ("rtsp".equals(event.getSchema())) {
logger.info("流变化:注册 app->{}, stream->{}", event.getApp(), event.getStream()); log.info("流变化:注册 app->{}, stream->{}", event.getApp(), event.getStream());
addCount(event.getMediaServer().getId()); addCount(event.getMediaServer().getId());
String type = OriginType.values()[event.getMediaInfo().getOriginType()].getType(); String type = OriginType.values()[event.getMediaInfo().getOriginType()].getType();
redisCatchStorage.addStream(event.getMediaServer(), type, event.getApp(), event.getStream(), event.getMediaInfo()); redisCatchStorage.addStream(event.getMediaServer(), type, event.getApp(), event.getStream(), event.getMediaInfo());
@ -109,7 +107,7 @@ public class MediaServerServiceImpl implements IMediaServerService {
@EventListener @EventListener
public void onApplicationEvent(MediaDepartureEvent event) { public void onApplicationEvent(MediaDepartureEvent event) {
if ("rtsp".equals(event.getSchema())) { if ("rtsp".equals(event.getSchema())) {
logger.info("流变化:注销, app->{}, stream->{}", event.getApp(), event.getStream()); log.info("流变化:注销, app->{}, stream->{}", event.getApp(), event.getStream());
removeCount(event.getMediaServer().getId()); removeCount(event.getMediaServer().getId());
MediaInfo mediaInfo = redisCatchStorage.getStreamInfo( MediaInfo mediaInfo = redisCatchStorage.getStreamInfo(
event.getApp(), event.getStream(), event.getMediaServer().getId()); event.getApp(), event.getStream(), event.getMediaServer().getId());
@ -128,7 +126,7 @@ public class MediaServerServiceImpl implements IMediaServerService {
*/ */
@Override @Override
public void updateVmServer(List<MediaServer> mediaServerList) { public void updateVmServer(List<MediaServer> mediaServerList) {
logger.info("[媒体服务节点] 缓存初始化 "); log.info("[媒体服务节点] 缓存初始化 ");
for (MediaServer mediaServer : mediaServerList) { for (MediaServer mediaServer : mediaServerList) {
if (ObjectUtils.isEmpty(mediaServer.getId())) { if (ObjectUtils.isEmpty(mediaServer.getId())) {
continue; continue;
@ -151,7 +149,7 @@ public class MediaServerServiceImpl implements IMediaServerService {
public SSRCInfo openRTPServer(MediaServer mediaServer, String streamId, String presetSsrc, boolean ssrcCheck, public SSRCInfo openRTPServer(MediaServer mediaServer, String streamId, String presetSsrc, boolean ssrcCheck,
boolean isPlayback, Integer port, Boolean onlyAuto, Boolean disableAudio, Boolean reUsePort, Integer tcpMode) { boolean isPlayback, Integer port, Boolean onlyAuto, Boolean disableAudio, Boolean reUsePort, Integer tcpMode) {
if (mediaServer == null || mediaServer.getId() == null) { if (mediaServer == null || mediaServer.getId() == null) {
logger.info("[openRTPServer] 失败, mediaServer == null || mediaServer.getId() == null"); log.info("[openRTPServer] 失败, mediaServer == null || mediaServer.getId() == null");
return null; return null;
} }
// 获取mediaServer可用的ssrc // 获取mediaServer可用的ssrc
@ -171,13 +169,13 @@ public class MediaServerServiceImpl implements IMediaServerService {
} }
if (ssrcCheck && tcpMode > 0) { if (ssrcCheck && tcpMode > 0) {
// 目前zlm不支持 tcp模式更新ssrc暂时关闭ssrc校验 // 目前zlm不支持 tcp模式更新ssrc暂时关闭ssrc校验
logger.warn("[openRTPServer] 平台对接时下级可能自定义ssrc但是tcp模式zlm收流目前无法更新ssrc可能收流超时此时请使用udp收流或者关闭ssrc校验"); log.warn("[openRTPServer] 平台对接时下级可能自定义ssrc但是tcp模式zlm收流目前无法更新ssrc可能收流超时此时请使用udp收流或者关闭ssrc校验");
} }
int rtpServerPort; int rtpServerPort;
if (mediaServer.isRtpEnable()) { if (mediaServer.isRtpEnable()) {
IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType()); IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType());
if (mediaNodeServerService == null) { if (mediaNodeServerService == null) {
logger.info("[openRTPServer] 失败, mediaServer的类型 {},未找到对应的实现类", mediaServer.getType()); log.info("[openRTPServer] 失败, mediaServer的类型 {},未找到对应的实现类", mediaServer.getType());
return null; return null;
} }
rtpServerPort = mediaNodeServerService.createRTPServer(mediaServer, streamId, ssrcCheck ? Long.parseLong(ssrc) : 0, port, onlyAuto, disableAudio, reUsePort, tcpMode); rtpServerPort = mediaNodeServerService.createRTPServer(mediaServer, streamId, ssrcCheck ? Long.parseLong(ssrc) : 0, port, onlyAuto, disableAudio, reUsePort, tcpMode);
@ -194,7 +192,7 @@ public class MediaServerServiceImpl implements IMediaServerService {
} }
IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType()); IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType());
if (mediaNodeServerService == null) { if (mediaNodeServerService == null) {
logger.info("[closeRTPServer] 失败, mediaServer的类型 {},未找到对应的实现类", mediaServer.getType()); log.info("[closeRTPServer] 失败, mediaServer的类型 {},未找到对应的实现类", mediaServer.getType());
return; return;
} }
mediaNodeServerService.closeRtpServer(mediaServer, streamId); mediaNodeServerService.closeRtpServer(mediaServer, streamId);
@ -208,7 +206,7 @@ public class MediaServerServiceImpl implements IMediaServerService {
} }
IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType()); IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType());
if (mediaNodeServerService == null) { if (mediaNodeServerService == null) {
logger.info("[closeRTPServer] 失败, mediaServer的类型 {},未找到对应的实现类", mediaServer.getType()); log.info("[closeRTPServer] 失败, mediaServer的类型 {},未找到对应的实现类", mediaServer.getType());
return; return;
} }
mediaNodeServerService.closeRtpServer(mediaServer, streamId, callback); mediaNodeServerService.closeRtpServer(mediaServer, streamId, callback);
@ -225,7 +223,7 @@ public class MediaServerServiceImpl implements IMediaServerService {
} }
IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType()); IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType());
if (mediaNodeServerService == null) { if (mediaNodeServerService == null) {
logger.info("[closeRTPServer] 失败, mediaServer的类型 {},未找到对应的实现类", mediaServer.getType()); log.info("[closeRTPServer] 失败, mediaServer的类型 {},未找到对应的实现类", mediaServer.getType());
return; return;
} }
mediaNodeServerService.closeStreams(mediaServer, "rtp", streamId); mediaNodeServerService.closeStreams(mediaServer, "rtp", streamId);
@ -238,7 +236,7 @@ public class MediaServerServiceImpl implements IMediaServerService {
} }
IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType()); IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType());
if (mediaNodeServerService == null) { if (mediaNodeServerService == null) {
logger.info("[updateRtpServerSSRC] 失败, mediaServer的类型 {},未找到对应的实现类", mediaServer.getType()); log.info("[updateRtpServerSSRC] 失败, mediaServer的类型 {},未找到对应的实现类", mediaServer.getType());
return false; return false;
} }
return mediaNodeServerService.updateRtpServerSSRC(mediaServer, streamId, ssrc); return mediaNodeServerService.updateRtpServerSSRC(mediaServer, streamId, ssrc);
@ -388,16 +386,16 @@ public class MediaServerServiceImpl implements IMediaServerService {
mediaServer.setHookAliveInterval(10F); mediaServer.setHookAliveInterval(10F);
} }
if (mediaServer.getType() == null) { if (mediaServer.getType() == null) {
logger.info("[添加媒体节点] 失败, mediaServer的类型为空"); log.info("[添加媒体节点] 失败, mediaServer的类型为空");
return; return;
} }
if (mediaServerMapper.queryOne(mediaServer.getId()) != null) { if (mediaServerMapper.queryOne(mediaServer.getId()) != null) {
logger.info("[添加媒体节点] 失败, 媒体服务ID已存在请修改媒体服务器配置, {}", mediaServer.getId()); log.info("[添加媒体节点] 失败, 媒体服务ID已存在请修改媒体服务器配置, {}", mediaServer.getId());
throw new ControllerException(ErrorCode.ERROR100.getCode(),"保存失败媒体服务ID [ " + mediaServer.getId() + " ] 已存在,请修改媒体服务器配置"); throw new ControllerException(ErrorCode.ERROR100.getCode(),"保存失败媒体服务ID [ " + mediaServer.getId() + " ] 已存在,请修改媒体服务器配置");
} }
IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType()); IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType());
if (mediaNodeServerService == null) { if (mediaNodeServerService == null) {
logger.info("[添加媒体节点] 失败, mediaServer的类型 {},未找到对应的实现类", mediaServer.getType()); log.info("[添加媒体节点] 失败, mediaServer的类型 {},未找到对应的实现类", mediaServer.getType());
return; return;
} }
@ -458,7 +456,7 @@ public class MediaServerServiceImpl implements IMediaServerService {
String key = VideoManagerConstants.ONLINE_MEDIA_SERVERS_PREFIX + userSetting.getServerId(); String key = VideoManagerConstants.ONLINE_MEDIA_SERVERS_PREFIX + userSetting.getServerId();
Long size = redisTemplate.opsForZSet().zCard(key); Long size = redisTemplate.opsForZSet().zCard(key);
if (size == null || size == 0) { if (size == null || size == 0) {
logger.info("获取负载最低的节点时无在线节点"); log.info("获取负载最低的节点时无在线节点");
return null; return null;
} }
@ -500,7 +498,7 @@ public class MediaServerServiceImpl implements IMediaServerService {
IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(type); IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(type);
if (mediaNodeServerService == null) { if (mediaNodeServerService == null) {
logger.info("[closeRTPServer] 失败, mediaServer的类型 {},未找到对应的实现类", type); log.info("[closeRTPServer] 失败, mediaServer的类型 {},未找到对应的实现类", type);
return null; return null;
} }
MediaServer mediaServer = mediaNodeServerService.checkMediaServer(ip, port, secret); MediaServer mediaServer = mediaNodeServerService.checkMediaServer(ip, port, secret);
@ -587,7 +585,7 @@ public class MediaServerServiceImpl implements IMediaServerService {
public boolean stopSendRtp(MediaServer mediaInfo, String app, String stream, String ssrc) { public boolean stopSendRtp(MediaServer mediaInfo, String app, String stream, String ssrc) {
IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaInfo.getType()); IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaInfo.getType());
if (mediaNodeServerService == null) { if (mediaNodeServerService == null) {
logger.info("[stopSendRtp] 失败, mediaServer的类型 {},未找到对应的实现类", mediaInfo.getType()); log.info("[stopSendRtp] 失败, mediaServer的类型 {},未找到对应的实现类", mediaInfo.getType());
return false; return false;
} }
return mediaNodeServerService.stopSendRtp(mediaInfo, app, stream, ssrc); return mediaNodeServerService.stopSendRtp(mediaInfo, app, stream, ssrc);
@ -597,7 +595,7 @@ public class MediaServerServiceImpl implements IMediaServerService {
public boolean initStopSendRtp(MediaServer mediaInfo, String app, String stream, String ssrc) { public boolean initStopSendRtp(MediaServer mediaInfo, String app, String stream, String ssrc) {
IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaInfo.getType()); IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaInfo.getType());
if (mediaNodeServerService == null) { if (mediaNodeServerService == null) {
logger.info("[stopSendRtp] 失败, mediaServer的类型 {},未找到对应的实现类", mediaInfo.getType()); log.info("[stopSendRtp] 失败, mediaServer的类型 {},未找到对应的实现类", mediaInfo.getType());
return false; return false;
} }
return mediaNodeServerService.initStopSendRtp(mediaInfo, app, stream, ssrc); return mediaNodeServerService.initStopSendRtp(mediaInfo, app, stream, ssrc);
@ -607,7 +605,7 @@ public class MediaServerServiceImpl implements IMediaServerService {
public boolean deleteRecordDirectory(MediaServer mediaServer, String app, String stream, String date, String fileName) { public boolean deleteRecordDirectory(MediaServer mediaServer, String app, String stream, String date, String fileName) {
IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType()); IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType());
if (mediaNodeServerService == null) { if (mediaNodeServerService == null) {
logger.info("[stopSendRtp] 失败, mediaServer的类型 {},未找到对应的实现类", mediaServer.getType()); log.info("[stopSendRtp] 失败, mediaServer的类型 {},未找到对应的实现类", mediaServer.getType());
return false; return false;
} }
return mediaNodeServerService.deleteRecordDirectory(mediaServer, app, stream, date, fileName); return mediaNodeServerService.deleteRecordDirectory(mediaServer, app, stream, date, fileName);
@ -617,7 +615,7 @@ public class MediaServerServiceImpl implements IMediaServerService {
public List<StreamInfo> getMediaList(MediaServer mediaServer, String app, String stream, String callId) { public List<StreamInfo> getMediaList(MediaServer mediaServer, String app, String stream, String callId) {
IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType()); IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType());
if (mediaNodeServerService == null) { if (mediaNodeServerService == null) {
logger.info("[getMediaList] 失败, mediaServer的类型 {},未找到对应的实现类", mediaServer.getType()); log.info("[getMediaList] 失败, mediaServer的类型 {},未找到对应的实现类", mediaServer.getType());
return new ArrayList<>(); return new ArrayList<>();
} }
return mediaNodeServerService.getMediaList(mediaServer, app, stream, callId); return mediaNodeServerService.getMediaList(mediaServer, app, stream, callId);
@ -627,7 +625,7 @@ public class MediaServerServiceImpl implements IMediaServerService {
public Boolean connectRtpServer(MediaServer mediaServer, String address, int port, String stream) { public Boolean connectRtpServer(MediaServer mediaServer, String address, int port, String stream) {
IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType()); IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType());
if (mediaNodeServerService == null) { if (mediaNodeServerService == null) {
logger.info("[connectRtpServer] 失败, mediaServer的类型 {},未找到对应的实现类", mediaServer.getType()); log.info("[connectRtpServer] 失败, mediaServer的类型 {},未找到对应的实现类", mediaServer.getType());
return false; return false;
} }
return mediaNodeServerService.connectRtpServer(mediaServer, address, port, stream); return mediaNodeServerService.connectRtpServer(mediaServer, address, port, stream);
@ -637,7 +635,7 @@ public class MediaServerServiceImpl implements IMediaServerService {
public void getSnap(MediaServer mediaServer, String streamUrl, int timeoutSec, int expireSec, String path, String fileName) { public void getSnap(MediaServer mediaServer, String streamUrl, int timeoutSec, int expireSec, String path, String fileName) {
IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType()); IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType());
if (mediaNodeServerService == null) { if (mediaNodeServerService == null) {
logger.info("[getSnap] 失败, mediaServer的类型 {},未找到对应的实现类", mediaServer.getType()); log.info("[getSnap] 失败, mediaServer的类型 {},未找到对应的实现类", mediaServer.getType());
return; return;
} }
mediaNodeServerService.getSnap(mediaServer, streamUrl, timeoutSec, expireSec, path, fileName); mediaNodeServerService.getSnap(mediaServer, streamUrl, timeoutSec, expireSec, path, fileName);
@ -647,7 +645,7 @@ public class MediaServerServiceImpl implements IMediaServerService {
public MediaInfo getMediaInfo(MediaServer mediaServer, String app, String stream) { public MediaInfo getMediaInfo(MediaServer mediaServer, String app, String stream) {
IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType()); IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType());
if (mediaNodeServerService == null) { if (mediaNodeServerService == null) {
logger.info("[getMediaInfo] 失败, mediaServer的类型 {},未找到对应的实现类", mediaServer.getType()); log.info("[getMediaInfo] 失败, mediaServer的类型 {},未找到对应的实现类", mediaServer.getType());
return null; return null;
} }
return mediaNodeServerService.getMediaInfo(mediaServer, app, stream); return mediaNodeServerService.getMediaInfo(mediaServer, app, stream);
@ -657,7 +655,7 @@ public class MediaServerServiceImpl implements IMediaServerService {
public Boolean pauseRtpCheck(MediaServer mediaServer, String streamKey) { public Boolean pauseRtpCheck(MediaServer mediaServer, String streamKey) {
IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType()); IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType());
if (mediaNodeServerService == null) { if (mediaNodeServerService == null) {
logger.info("[pauseRtpCheck] 失败, mediaServer的类型 {},未找到对应的实现类", mediaServer.getType()); log.info("[pauseRtpCheck] 失败, mediaServer的类型 {},未找到对应的实现类", mediaServer.getType());
return false; return false;
} }
return mediaNodeServerService.pauseRtpCheck(mediaServer, streamKey); return mediaNodeServerService.pauseRtpCheck(mediaServer, streamKey);
@ -667,7 +665,7 @@ public class MediaServerServiceImpl implements IMediaServerService {
public boolean resumeRtpCheck(MediaServer mediaServer, String streamKey) { public boolean resumeRtpCheck(MediaServer mediaServer, String streamKey) {
IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType()); IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType());
if (mediaNodeServerService == null) { if (mediaNodeServerService == null) {
logger.info("[pauseRtpCheck] 失败, mediaServer的类型 {},未找到对应的实现类", mediaServer.getType()); log.info("[pauseRtpCheck] 失败, mediaServer的类型 {},未找到对应的实现类", mediaServer.getType());
return false; return false;
} }
return mediaNodeServerService.resumeRtpCheck(mediaServer, streamKey); return mediaNodeServerService.resumeRtpCheck(mediaServer, streamKey);
@ -677,7 +675,7 @@ public class MediaServerServiceImpl implements IMediaServerService {
public String getFfmpegCmd(MediaServer mediaServer, String cmdKey) { public String getFfmpegCmd(MediaServer mediaServer, String cmdKey) {
IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType()); IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType());
if (mediaNodeServerService == null) { if (mediaNodeServerService == null) {
logger.info("[getFfmpegCmd] 失败, mediaServer的类型 {},未找到对应的实现类", mediaServer.getType()); log.info("[getFfmpegCmd] 失败, mediaServer的类型 {},未找到对应的实现类", mediaServer.getType());
return null; return null;
} }
return mediaNodeServerService.getFfmpegCmd(mediaServer, cmdKey); return mediaNodeServerService.getFfmpegCmd(mediaServer, cmdKey);
@ -687,7 +685,7 @@ public class MediaServerServiceImpl implements IMediaServerService {
public void closeStreams(MediaServer mediaServer, String app, String stream) { public void closeStreams(MediaServer mediaServer, String app, String stream) {
IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType()); IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType());
if (mediaNodeServerService == null) { if (mediaNodeServerService == null) {
logger.info("[closeStreams] 失败, mediaServer的类型 {},未找到对应的实现类", mediaServer.getType()); log.info("[closeStreams] 失败, mediaServer的类型 {},未找到对应的实现类", mediaServer.getType());
return; return;
} }
mediaNodeServerService.closeStreams(mediaServer, app, stream); mediaNodeServerService.closeStreams(mediaServer, app, stream);
@ -697,7 +695,7 @@ public class MediaServerServiceImpl implements IMediaServerService {
public WVPResult<String> addFFmpegSource(MediaServer mediaServer, String srcUrl, String dstUrl, int timeoutMs, boolean enableAudio, boolean enableMp4, String ffmpegCmdKey) { public WVPResult<String> addFFmpegSource(MediaServer mediaServer, String srcUrl, String dstUrl, int timeoutMs, boolean enableAudio, boolean enableMp4, String ffmpegCmdKey) {
IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType()); IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType());
if (mediaNodeServerService == null) { if (mediaNodeServerService == null) {
logger.info("[addFFmpegSource] 失败, mediaServer的类型 {},未找到对应的实现类", mediaServer.getType()); log.info("[addFFmpegSource] 失败, mediaServer的类型 {},未找到对应的实现类", mediaServer.getType());
return WVPResult.fail(ErrorCode.ERROR400); return WVPResult.fail(ErrorCode.ERROR400);
} }
return mediaNodeServerService.addFFmpegSource(mediaServer, srcUrl, dstUrl, timeoutMs, enableAudio, enableMp4, ffmpegCmdKey); return mediaNodeServerService.addFFmpegSource(mediaServer, srcUrl, dstUrl, timeoutMs, enableAudio, enableMp4, ffmpegCmdKey);
@ -708,7 +706,7 @@ public class MediaServerServiceImpl implements IMediaServerService {
boolean enableAudio, boolean enableMp4, String rtpType, Integer timeout) { boolean enableAudio, boolean enableMp4, String rtpType, Integer timeout) {
IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType()); IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType());
if (mediaNodeServerService == null) { if (mediaNodeServerService == null) {
logger.info("[addStreamProxy] 失败, mediaServer的类型 {},未找到对应的实现类", mediaServer.getType()); log.info("[addStreamProxy] 失败, mediaServer的类型 {},未找到对应的实现类", mediaServer.getType());
return WVPResult.fail(ErrorCode.ERROR400); return WVPResult.fail(ErrorCode.ERROR400);
} }
return mediaNodeServerService.addStreamProxy(mediaServer, app, stream, url, enableAudio, enableMp4, rtpType, timeout); return mediaNodeServerService.addStreamProxy(mediaServer, app, stream, url, enableAudio, enableMp4, rtpType, timeout);
@ -718,7 +716,7 @@ public class MediaServerServiceImpl implements IMediaServerService {
public Boolean delFFmpegSource(MediaServer mediaServer, String streamKey) { public Boolean delFFmpegSource(MediaServer mediaServer, String streamKey) {
IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType()); IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType());
if (mediaNodeServerService == null) { if (mediaNodeServerService == null) {
logger.info("[delFFmpegSource] 失败, mediaServer的类型 {},未找到对应的实现类", mediaServer.getType()); log.info("[delFFmpegSource] 失败, mediaServer的类型 {},未找到对应的实现类", mediaServer.getType());
return false; return false;
} }
return mediaNodeServerService.delFFmpegSource(mediaServer, streamKey); return mediaNodeServerService.delFFmpegSource(mediaServer, streamKey);
@ -728,7 +726,7 @@ public class MediaServerServiceImpl implements IMediaServerService {
public Boolean delStreamProxy(MediaServer mediaServerItem, String streamKey) { public Boolean delStreamProxy(MediaServer mediaServerItem, String streamKey) {
IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServerItem.getType()); IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServerItem.getType());
if (mediaNodeServerService == null) { if (mediaNodeServerService == null) {
logger.info("[delStreamProxy] 失败, mediaServer的类型 {},未找到对应的实现类", mediaServerItem.getType()); log.info("[delStreamProxy] 失败, mediaServer的类型 {},未找到对应的实现类", mediaServerItem.getType());
return false; return false;
} }
return mediaNodeServerService.delStreamProxy(mediaServerItem, streamKey); return mediaNodeServerService.delStreamProxy(mediaServerItem, streamKey);
@ -738,7 +736,7 @@ public class MediaServerServiceImpl implements IMediaServerService {
public Map<String, String> getFFmpegCMDs(MediaServer mediaServer) { public Map<String, String> getFFmpegCMDs(MediaServer mediaServer) {
IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType()); IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType());
if (mediaNodeServerService == null) { if (mediaNodeServerService == null) {
logger.info("[getFFmpegCMDs] 失败, mediaServer的类型 {},未找到对应的实现类", mediaServer.getType()); log.info("[getFFmpegCMDs] 失败, mediaServer的类型 {},未找到对应的实现类", mediaServer.getType());
return new HashMap<>(); return new HashMap<>();
} }
return mediaNodeServerService.getFFmpegCMDs(mediaServer); return mediaNodeServerService.getFFmpegCMDs(mediaServer);
@ -825,7 +823,7 @@ public class MediaServerServiceImpl implements IMediaServerService {
public Boolean isStreamReady(MediaServer mediaServer, String app, String streamId) { public Boolean isStreamReady(MediaServer mediaServer, String app, String streamId) {
IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType()); IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType());
if (mediaNodeServerService == null) { if (mediaNodeServerService == null) {
logger.info("[isStreamReady] 失败, mediaServer的类型 {},未找到对应的实现类", mediaServer.getType()); log.info("[isStreamReady] 失败, mediaServer的类型 {},未找到对应的实现类", mediaServer.getType());
return false; return false;
} }
MediaInfo mediaInfo = mediaNodeServerService.getMediaInfo(mediaServer, app, streamId); MediaInfo mediaInfo = mediaNodeServerService.getMediaInfo(mediaServer, app, streamId);
@ -836,7 +834,7 @@ public class MediaServerServiceImpl implements IMediaServerService {
public void startSendRtpPassive(MediaServer mediaServer, SendRtpItem sendRtpItem, Integer timeout) { public void startSendRtpPassive(MediaServer mediaServer, SendRtpItem sendRtpItem, Integer timeout) {
IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType()); IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType());
if (mediaNodeServerService == null) { if (mediaNodeServerService == null) {
logger.info("[startSendRtpPassive] 失败, mediaServer的类型 {},未找到对应的实现类", mediaServer.getType()); log.info("[startSendRtpPassive] 失败, mediaServer的类型 {},未找到对应的实现类", mediaServer.getType());
throw new ControllerException(ErrorCode.ERROR100.getCode(), "未找到mediaServer对应的实现类"); throw new ControllerException(ErrorCode.ERROR100.getCode(), "未找到mediaServer对应的实现类");
} }
mediaNodeServerService.startSendRtpPassive(mediaServer, sendRtpItem, timeout); mediaNodeServerService.startSendRtpPassive(mediaServer, sendRtpItem, timeout);
@ -846,10 +844,10 @@ public class MediaServerServiceImpl implements IMediaServerService {
public void startSendRtp(MediaServer mediaServer, SendRtpItem sendRtpItem) { public void startSendRtp(MediaServer mediaServer, SendRtpItem sendRtpItem) {
IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType()); IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType());
if (mediaNodeServerService == null) { if (mediaNodeServerService == null) {
logger.info("[startSendRtpStream] 失败, mediaServer的类型 {},未找到对应的实现类", mediaServer.getType()); log.info("[startSendRtpStream] 失败, mediaServer的类型 {},未找到对应的实现类", mediaServer.getType());
throw new ControllerException(ErrorCode.ERROR100.getCode(), "未找到mediaServer对应的实现类"); throw new ControllerException(ErrorCode.ERROR100.getCode(), "未找到mediaServer对应的实现类");
} }
logger.info("[开始推流] rtp/{}, 目标={}:{}SSRC={}, RTCP={}", sendRtpItem.getStream(), log.info("[开始推流] rtp/{}, 目标={}:{}SSRC={}, RTCP={}", sendRtpItem.getStream(),
sendRtpItem.getIp(), sendRtpItem.getPort(), sendRtpItem.getSsrc(), sendRtpItem.isRtcp()); sendRtpItem.getIp(), sendRtpItem.getPort(), sendRtpItem.getSsrc(), sendRtpItem.isRtcp());
mediaNodeServerService.startSendRtpStream(mediaServer, sendRtpItem); mediaNodeServerService.startSendRtpStream(mediaServer, sendRtpItem);
} }
@ -916,7 +914,7 @@ public class MediaServerServiceImpl implements IMediaServerService {
public Long updateDownloadProcess(MediaServer mediaServer, String app, String stream) { public Long updateDownloadProcess(MediaServer mediaServer, String app, String stream) {
IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType()); IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType());
if (mediaNodeServerService == null) { if (mediaNodeServerService == null) {
logger.info("[updateDownloadProcess] 失败, mediaServer的类型 {},未找到对应的实现类", mediaServer.getType()); log.info("[updateDownloadProcess] 失败, mediaServer的类型 {},未找到对应的实现类", mediaServer.getType());
throw new ControllerException(ErrorCode.ERROR100.getCode(), "未找到mediaServer对应的实现类"); throw new ControllerException(ErrorCode.ERROR100.getCode(), "未找到mediaServer对应的实现类");
} }
return mediaNodeServerService.updateDownloadProcess(mediaServer, app, stream); return mediaNodeServerService.updateDownloadProcess(mediaServer, app, stream);
@ -926,7 +924,7 @@ public class MediaServerServiceImpl implements IMediaServerService {
public StreamInfo startProxy(MediaServer mediaServer, StreamProxy streamProxy) { public StreamInfo startProxy(MediaServer mediaServer, StreamProxy streamProxy) {
IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType()); IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType());
if (mediaNodeServerService == null) { if (mediaNodeServerService == null) {
logger.info("[startProxy] 失败, mediaServer的类型 {},未找到对应的实现类", mediaServer.getType()); log.info("[startProxy] 失败, mediaServer的类型 {},未找到对应的实现类", mediaServer.getType());
throw new ControllerException(ErrorCode.ERROR100.getCode(), "未找到mediaServer对应的实现类"); throw new ControllerException(ErrorCode.ERROR100.getCode(), "未找到mediaServer对应的实现类");
} }
return mediaNodeServerService.startProxy(mediaServer, streamProxy); return mediaNodeServerService.startProxy(mediaServer, streamProxy);
@ -936,7 +934,7 @@ public class MediaServerServiceImpl implements IMediaServerService {
public void stopProxy(MediaServer mediaServer, String streamKey) { public void stopProxy(MediaServer mediaServer, String streamKey) {
IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType()); IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType());
if (mediaNodeServerService == null) { if (mediaNodeServerService == null) {
logger.info("[stopProxy] 失败, mediaServer的类型 {},未找到对应的实现类", mediaServer.getType()); log.info("[stopProxy] 失败, mediaServer的类型 {},未找到对应的实现类", mediaServer.getType());
throw new ControllerException(ErrorCode.ERROR100.getCode(), "未找到mediaServer对应的实现类"); throw new ControllerException(ErrorCode.ERROR100.getCode(), "未找到mediaServer对应的实现类");
} }
mediaNodeServerService.stopProxy(mediaServer, streamKey); mediaNodeServerService.stopProxy(mediaServer, streamKey);

View File

@ -4,11 +4,10 @@ import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject; import com.alibaba.fastjson2.JSONObject;
import com.genersoft.iot.vmp.media.bean.MediaServer; import com.genersoft.iot.vmp.media.bean.MediaServer;
import com.genersoft.iot.vmp.utils.SSLSocketClientUtil; import com.genersoft.iot.vmp.utils.SSLSocketClientUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*; import okhttp3.*;
import okhttp3.logging.HttpLoggingInterceptor; import okhttp3.logging.HttpLoggingInterceptor;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils; import org.springframework.util.ObjectUtils;
@ -22,12 +21,10 @@ import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@Slf4j
@Component @Component
public class AssistRESTfulUtils { public class AssistRESTfulUtils {
private final static Logger logger = LoggerFactory.getLogger(AssistRESTfulUtils.class);
private OkHttpClient client; private OkHttpClient client;
@ -51,9 +48,9 @@ public class AssistRESTfulUtils {
httpClientBuilder.readTimeout(readTimeOut,TimeUnit.SECONDS); httpClientBuilder.readTimeout(readTimeOut,TimeUnit.SECONDS);
// 设置连接池 // 设置连接池
httpClientBuilder.connectionPool(new ConnectionPool(16, 5, TimeUnit.MINUTES)); httpClientBuilder.connectionPool(new ConnectionPool(16, 5, TimeUnit.MINUTES));
if (logger.isDebugEnabled()) { if (log.isDebugEnabled()) {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor(message -> { HttpLoggingInterceptor logging = new HttpLoggingInterceptor(message -> {
logger.debug("http请求参数" + message); log.debug("http请求参数" + message);
}); });
logging.setLevel(HttpLoggingInterceptor.Level.BASIC); logging.setLevel(HttpLoggingInterceptor.Level.BASIC);
// OkHttp進行添加攔截器loggingInterceptor // OkHttp進行添加攔截器loggingInterceptor
@ -77,7 +74,7 @@ public class AssistRESTfulUtils {
return null; return null;
} }
if (mediaServerItem.getRecordAssistPort() <= 0) { if (mediaServerItem.getRecordAssistPort() <= 0) {
logger.warn("未启用Assist服务"); log.warn("未启用Assist服务");
return null; return null;
} }
StringBuilder stringBuffer = new StringBuilder(); StringBuilder stringBuffer = new StringBuilder();
@ -99,7 +96,7 @@ public class AssistRESTfulUtils {
} }
String url = stringBuffer.toString(); String url = stringBuffer.toString();
logger.info("[访问assist] {}", url); log.info("[访问assist] {}", url);
Request request = new Request.Builder() Request request = new Request.Builder()
.get() .get()
.url(url) .url(url)
@ -118,10 +115,10 @@ public class AssistRESTfulUtils {
Objects.requireNonNull(response.body()).close(); Objects.requireNonNull(response.body()).close();
} }
} catch (ConnectException e) { } catch (ConnectException e) {
logger.error(String.format("连接Assist失败: %s, %s", e.getCause().getMessage(), e.getMessage())); log.error(String.format("连接Assist失败: %s, %s", e.getCause().getMessage(), e.getMessage()));
logger.info("请检查media配置并确认Assist已启动..."); log.info("请检查media配置并确认Assist已启动...");
}catch (IOException e) { }catch (IOException e) {
logger.error(String.format("[ %s ]请求失败: %s", url, e.getMessage())); log.error(String.format("[ %s ]请求失败: %s", url, e.getMessage()));
} }
}else { }else {
client.newCall(request).enqueue(new Callback(){ client.newCall(request).enqueue(new Callback(){
@ -133,7 +130,7 @@ public class AssistRESTfulUtils {
String responseStr = Objects.requireNonNull(response.body()).string(); String responseStr = Objects.requireNonNull(response.body()).string();
callback.run(JSON.parseObject(responseStr)); callback.run(JSON.parseObject(responseStr));
} catch (IOException e) { } catch (IOException e) {
logger.error(String.format("[ %s ]请求失败: %s", url, e.getMessage())); log.error(String.format("[ %s ]请求失败: %s", url, e.getMessage()));
} }
}else { }else {
@ -144,8 +141,8 @@ public class AssistRESTfulUtils {
@Override @Override
public void onFailure(@NotNull Call call, @NotNull IOException e) { public void onFailure(@NotNull Call call, @NotNull IOException e) {
logger.error(String.format("连接Assist失败: %s, %s", e.getCause().getMessage(), e.getMessage())); log.error(String.format("连接Assist失败: %s, %s", e.getCause().getMessage(), e.getMessage()));
logger.info("请检查media配置并确认Assist已启动..."); log.info("请检查media配置并确认Assist已启动...");
} }
}); });
} }
@ -163,7 +160,7 @@ public class AssistRESTfulUtils {
if (mediaServerItem == null) { if (mediaServerItem == null) {
return null; return null;
} }
logger.info("[访问assist] {}, 参数: {}", url, param); log.info("[访问assist] {}, 参数: {}", url, param);
JSONObject responseJSON = new JSONObject(); JSONObject responseJSON = new JSONObject();
//-2自定义流媒体 调用错误码 //-2自定义流媒体 调用错误码
responseJSON.put("code",-2); responseJSON.put("code",-2);
@ -190,19 +187,19 @@ public class AssistRESTfulUtils {
Objects.requireNonNull(response.body()).close(); Objects.requireNonNull(response.body()).close();
} }
}catch (IOException e) { }catch (IOException e) {
logger.error(String.format("[ %s ]ASSIST请求失败: %s", url, e.getMessage())); log.error(String.format("[ %s ]ASSIST请求失败: %s", url, e.getMessage()));
if(e instanceof SocketTimeoutException){ if(e instanceof SocketTimeoutException){
//读取超时超时异常 //读取超时超时异常
logger.error(String.format("读取ASSIST数据失败: %s, %s", url, e.getMessage())); log.error(String.format("读取ASSIST数据失败: %s, %s", url, e.getMessage()));
} }
if(e instanceof ConnectException){ if(e instanceof ConnectException){
//判断连接异常我这里是报Failed to connect to 10.7.5.144 //判断连接异常我这里是报Failed to connect to 10.7.5.144
logger.error(String.format("连接ASSIST失败: %s, %s", url, e.getMessage())); log.error(String.format("连接ASSIST失败: %s, %s", url, e.getMessage()));
} }
}catch (Exception e){ }catch (Exception e){
logger.error(String.format("访问ASSIST失败: %s, %s", url, e.getMessage())); log.error(String.format("访问ASSIST失败: %s, %s", url, e.getMessage()));
} }
}else { }else {
client.newCall(request).enqueue(new Callback(){ client.newCall(request).enqueue(new Callback(){
@ -214,7 +211,7 @@ public class AssistRESTfulUtils {
String responseStr = Objects.requireNonNull(response.body()).string(); String responseStr = Objects.requireNonNull(response.body()).string();
callback.run(JSON.parseObject(responseStr)); callback.run(JSON.parseObject(responseStr));
} catch (IOException e) { } catch (IOException e) {
logger.error(String.format("[ %s ]请求失败: %s", url, e.getMessage())); log.error(String.format("[ %s ]请求失败: %s", url, e.getMessage()));
} }
}else { }else {
@ -225,15 +222,15 @@ public class AssistRESTfulUtils {
@Override @Override
public void onFailure(@NotNull Call call, @NotNull IOException e) { public void onFailure(@NotNull Call call, @NotNull IOException e) {
logger.error(String.format("连接ZLM失败: %s, %s", call.request().toString(), e.getMessage())); log.error(String.format("连接ZLM失败: %s, %s", call.request().toString(), e.getMessage()));
if(e instanceof SocketTimeoutException){ if(e instanceof SocketTimeoutException){
//读取超时超时异常 //读取超时超时异常
logger.error(String.format("读取ZLM数据失败: %s, %s", call.request().toString(), e.getMessage())); log.error(String.format("读取ZLM数据失败: %s, %s", call.request().toString(), e.getMessage()));
} }
if(e instanceof ConnectException){ if(e instanceof ConnectException){
//判断连接异常我这里是报Failed to connect to 10.7.5.144 //判断连接异常我这里是报Failed to connect to 10.7.5.144
logger.error(String.format("连接ZLM失败: %s, %s", call.request().toString(), e.getMessage())); log.error(String.format("连接ZLM失败: %s, %s", call.request().toString(), e.getMessage()));
} }
} }
}); });

View File

@ -3,16 +3,8 @@ package com.genersoft.iot.vmp.media.zlm;
import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject; import com.alibaba.fastjson2.JSONObject;
import com.genersoft.iot.vmp.conf.UserSetting; import com.genersoft.iot.vmp.conf.UserSetting;
import com.genersoft.iot.vmp.gb28181.event.EventPublisher;
import com.genersoft.iot.vmp.gb28181.session.AudioBroadcastManager;
import com.genersoft.iot.vmp.gb28181.session.SSRCFactory;
import com.genersoft.iot.vmp.gb28181.session.VideoStreamSessionManager;
import com.genersoft.iot.vmp.gb28181.transmit.callback.DeferredResultHolder;
import com.genersoft.iot.vmp.gb28181.transmit.cmd.ISIPCommanderForPlatform;
import com.genersoft.iot.vmp.gb28181.transmit.cmd.impl.SIPCommander;
import com.genersoft.iot.vmp.media.bean.MediaServer; import com.genersoft.iot.vmp.media.bean.MediaServer;
import com.genersoft.iot.vmp.media.bean.ResultForOnPublish; import com.genersoft.iot.vmp.media.bean.ResultForOnPublish;
import com.genersoft.iot.vmp.media.event.hook.HookSubscribe;
import com.genersoft.iot.vmp.media.event.media.*; import com.genersoft.iot.vmp.media.event.media.*;
import com.genersoft.iot.vmp.media.event.mediaServer.MediaSendRtpStoppedEvent; import com.genersoft.iot.vmp.media.event.mediaServer.MediaSendRtpStoppedEvent;
import com.genersoft.iot.vmp.media.service.IMediaServerService; import com.genersoft.iot.vmp.media.service.IMediaServerService;
@ -20,20 +12,11 @@ import com.genersoft.iot.vmp.media.zlm.dto.ZLMServerConfig;
import com.genersoft.iot.vmp.media.zlm.dto.hook.*; import com.genersoft.iot.vmp.media.zlm.dto.hook.*;
import com.genersoft.iot.vmp.media.zlm.event.HookZlmServerKeepaliveEvent; import com.genersoft.iot.vmp.media.zlm.event.HookZlmServerKeepaliveEvent;
import com.genersoft.iot.vmp.media.zlm.event.HookZlmServerStartEvent; import com.genersoft.iot.vmp.media.zlm.event.HookZlmServerStartEvent;
import com.genersoft.iot.vmp.service.*; import com.genersoft.iot.vmp.service.IMediaService;
import com.genersoft.iot.vmp.service.redisMsg.IRedisRpcService;
import com.genersoft.iot.vmp.storager.IRedisCatchStorage;
import com.genersoft.iot.vmp.storager.IVideoManagerStorage;
import com.genersoft.iot.vmp.streamProxy.service.IStreamProxyService;
import com.genersoft.iot.vmp.streamPush.service.IStreamPushService;
import com.genersoft.iot.vmp.utils.MediaServerUtils; import com.genersoft.iot.vmp.utils.MediaServerUtils;
import org.slf4j.Logger; import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationEventPublisher;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.util.ObjectUtils; import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@ -45,85 +28,23 @@ import java.util.Map;
* @author: swwheihei * @author: swwheihei
* @date: 2020年5月8日 上午10:46:48 * @date: 2020年5月8日 上午10:46:48
*/ */
@Slf4j
@RestController @RestController
@RequestMapping("/index/hook") @RequestMapping("/index/hook")
public class ZLMHttpHookListener { public class ZLMHttpHookListener {
private final static Logger logger = LoggerFactory.getLogger(ZLMHttpHookListener.class);
@Autowired
private SIPCommander cmder;
@Autowired
private ISIPCommanderForPlatform commanderFroPlatform;
@Autowired
private AudioBroadcastManager audioBroadcastManager;
@Autowired
private IPlayService playService;
@Autowired
private IVideoManagerStorage storager;
@Autowired
private IRedisCatchStorage redisCatchStorage;
@Autowired
private IRedisRpcService redisRpcService;
@Autowired
private IInviteStreamService inviteStreamService;
@Autowired
private IDeviceService deviceService;
@Autowired @Autowired
private IMediaServerService mediaServerService; private IMediaServerService mediaServerService;
@Autowired
private IStreamProxyService streamProxyService;
@Autowired
private DeferredResultHolder resultHolder;
@Autowired @Autowired
private IMediaService mediaService; private IMediaService mediaService;
@Autowired
private EventPublisher eventPublisher;
@Autowired
private HookSubscribe subscribe;
@Autowired @Autowired
private UserSetting userSetting; private UserSetting userSetting;
@Autowired
private IUserService userService;
@Autowired
private ICloudRecordService cloudRecordService;
@Autowired
private VideoStreamSessionManager sessionManager;
@Autowired
private SSRCFactory ssrcFactory;
@Qualifier("taskExecutor")
@Autowired
private ThreadPoolTaskExecutor taskExecutor;
@Autowired
private RedisTemplate<Object, Object> redisTemplate;
@Autowired @Autowired
private ApplicationEventPublisher applicationEventPublisher; private ApplicationEventPublisher applicationEventPublisher;
@Autowired
private IStreamPushService streamPushService;
/** /**
* 服务器定时上报时间上报间隔可配置默认10s上报一次 * 服务器定时上报时间上报间隔可配置默认10s上报一次
@ -139,7 +60,7 @@ public class ZLMHttpHookListener {
applicationEventPublisher.publishEvent(event); applicationEventPublisher.publishEvent(event);
} }
}catch (Exception e) { }catch (Exception e) {
logger.info("[ZLM-HOOK-心跳] 发送通知失败 ", e); log.info("[ZLM-HOOK-心跳] 发送通知失败 ", e);
} }
return HookResult.SUCCESS(); return HookResult.SUCCESS();
} }
@ -155,10 +76,10 @@ public class ZLMHttpHookListener {
// 对于播放流进行鉴权 // 对于播放流进行鉴权
boolean authenticateResult = mediaService.authenticatePlay(param.getApp(), param.getStream(), paramMap.get("callId")); boolean authenticateResult = mediaService.authenticatePlay(param.getApp(), param.getStream(), paramMap.get("callId"));
if (!authenticateResult) { if (!authenticateResult) {
logger.info("[ZLM HOOK] 播放鉴权 失败:{}->{}", param.getMediaServerId(), param); log.info("[ZLM HOOK] 播放鉴权 失败:{}->{}", param.getMediaServerId(), param);
return new HookResult(401, "Unauthorized"); return new HookResult(401, "Unauthorized");
} }
logger.info("[ZLM HOOK] 播放鉴权成功:{}->{}", param.getMediaServerId(), param); log.info("[ZLM HOOK] 播放鉴权成功:{}->{}", param.getMediaServerId(), param);
return HookResult.SUCCESS(); return HookResult.SUCCESS();
} }
@ -171,7 +92,7 @@ public class ZLMHttpHookListener {
JSONObject json = (JSONObject) JSON.toJSON(param); JSONObject json = (JSONObject) JSON.toJSON(param);
logger.info("[ZLM HOOK]推流鉴权:{}->{}", param.getMediaServerId(), param); log.info("[ZLM HOOK]推流鉴权:{}->{}", param.getMediaServerId(), param);
// TODO 加快处理速度 // TODO 加快处理速度
String mediaServerId = json.getString("mediaServerId"); String mediaServerId = json.getString("mediaServerId");
@ -183,11 +104,11 @@ public class ZLMHttpHookListener {
ResultForOnPublish resultForOnPublish = mediaService.authenticatePublish(mediaServer, param.getApp(), param.getStream(), param.getParams()); ResultForOnPublish resultForOnPublish = mediaService.authenticatePublish(mediaServer, param.getApp(), param.getStream(), param.getParams());
if (resultForOnPublish != null) { if (resultForOnPublish != null) {
HookResultForOnPublish successResult = HookResultForOnPublish.getInstance(resultForOnPublish); HookResultForOnPublish successResult = HookResultForOnPublish.getInstance(resultForOnPublish);
logger.info("[ZLM HOOK]推流鉴权 响应:{}->{}->>>>{}", param.getMediaServerId(), param, successResult); log.info("[ZLM HOOK]推流鉴权 响应:{}->{}->>>>{}", param.getMediaServerId(), param, successResult);
return successResult; return successResult;
}else { }else {
HookResultForOnPublish fail = HookResultForOnPublish.Fail(); HookResultForOnPublish fail = HookResultForOnPublish.Fail();
logger.info("[ZLM HOOK]推流鉴权 响应:{}->{}->>>>{}", param.getMediaServerId(), param, fail); log.info("[ZLM HOOK]推流鉴权 响应:{}->{}->>>>{}", param.getMediaServerId(), param, fail);
return fail; return fail;
} }
} }
@ -219,11 +140,11 @@ public class ZLMHttpHookListener {
} }
if (param.getSchema().equalsIgnoreCase("rtsp")) { if (param.getSchema().equalsIgnoreCase("rtsp")) {
if (param.isRegist()) { if (param.isRegist()) {
logger.info("[ZLM HOOK] 流注册, {}->{}->{}/{}", param.getMediaServerId(), param.getSchema(), param.getApp(), param.getStream()); log.info("[ZLM HOOK] 流注册, {}->{}->{}/{}", param.getMediaServerId(), param.getSchema(), param.getApp(), param.getStream());
MediaArrivalEvent mediaArrivalEvent = MediaArrivalEvent.getInstance(this, param, mediaServer); MediaArrivalEvent mediaArrivalEvent = MediaArrivalEvent.getInstance(this, param, mediaServer);
applicationEventPublisher.publishEvent(mediaArrivalEvent); applicationEventPublisher.publishEvent(mediaArrivalEvent);
} else { } else {
logger.info("[ZLM HOOK] 流注销, {}->{}->{}/{}", param.getMediaServerId(), param.getSchema(), param.getApp(), param.getStream()); log.info("[ZLM HOOK] 流注销, {}->{}->{}/{}", param.getMediaServerId(), param.getSchema(), param.getApp(), param.getStream());
MediaDepartureEvent mediaDepartureEvent = MediaDepartureEvent.getInstance(this, param, mediaServer); MediaDepartureEvent mediaDepartureEvent = MediaDepartureEvent.getInstance(this, param, mediaServer);
applicationEventPublisher.publishEvent(mediaDepartureEvent); applicationEventPublisher.publishEvent(mediaDepartureEvent);
} }
@ -239,7 +160,7 @@ public class ZLMHttpHookListener {
@PostMapping(value = "/on_stream_none_reader", produces = "application/json;charset=UTF-8") @PostMapping(value = "/on_stream_none_reader", produces = "application/json;charset=UTF-8")
public JSONObject onStreamNoneReader(@RequestBody OnStreamNoneReaderHookParam param) { public JSONObject onStreamNoneReader(@RequestBody OnStreamNoneReaderHookParam param) {
logger.info("[ZLM HOOK]流无人观看:{}->{}->{}/{}", param.getMediaServerId(), param.getSchema(), log.info("[ZLM HOOK]流无人观看:{}->{}->{}/{}", param.getMediaServerId(), param.getSchema(),
param.getApp(), param.getStream()); param.getApp(), param.getStream());
MediaServer mediaInfo = mediaServerService.getOne(param.getMediaServerId()); MediaServer mediaInfo = mediaServerService.getOne(param.getMediaServerId());
@ -267,7 +188,7 @@ public class ZLMHttpHookListener {
@ResponseBody @ResponseBody
@PostMapping(value = "/on_stream_not_found", produces = "application/json;charset=UTF-8") @PostMapping(value = "/on_stream_not_found", produces = "application/json;charset=UTF-8")
public HookResult onStreamNotFound(@RequestBody OnStreamNotFoundHookParam param) { public HookResult onStreamNotFound(@RequestBody OnStreamNotFoundHookParam param) {
logger.info("[ZLM HOOK] 流未找到:{}->{}->{}/{}", param.getMediaServerId(), param.getSchema(), param.getApp(), param.getStream()); log.info("[ZLM HOOK] 流未找到:{}->{}->{}/{}", param.getMediaServerId(), param.getSchema(), param.getApp(), param.getStream());
MediaServer mediaServer = mediaServerService.getOne(param.getMediaServerId()); MediaServer mediaServer = mediaServerService.getOne(param.getMediaServerId());
@ -289,7 +210,7 @@ public class ZLMHttpHookListener {
jsonObject.put("ip", request.getRemoteAddr()); jsonObject.put("ip", request.getRemoteAddr());
ZLMServerConfig zlmServerConfig = JSON.to(ZLMServerConfig.class, jsonObject); ZLMServerConfig zlmServerConfig = JSON.to(ZLMServerConfig.class, jsonObject);
zlmServerConfig.setIp(request.getRemoteAddr()); zlmServerConfig.setIp(request.getRemoteAddr());
logger.info("[ZLM HOOK] zlm 启动 " + zlmServerConfig.getGeneralMediaServerId()); log.info("[ZLM HOOK] zlm 启动 " + zlmServerConfig.getGeneralMediaServerId());
try { try {
HookZlmServerStartEvent event = new HookZlmServerStartEvent(this); HookZlmServerStartEvent event = new HookZlmServerStartEvent(this);
MediaServer mediaServerItem = mediaServerService.getOne(zlmServerConfig.getMediaServerId()); MediaServer mediaServerItem = mediaServerService.getOne(zlmServerConfig.getMediaServerId());
@ -298,7 +219,7 @@ public class ZLMHttpHookListener {
applicationEventPublisher.publishEvent(event); applicationEventPublisher.publishEvent(event);
} }
}catch (Exception e) { }catch (Exception e) {
logger.info("[ZLM-HOOK-ZLM启动] 发送通知失败 ", e); log.info("[ZLM-HOOK-ZLM启动] 发送通知失败 ", e);
} }
return HookResult.SUCCESS(); return HookResult.SUCCESS();
@ -311,7 +232,7 @@ public class ZLMHttpHookListener {
@PostMapping(value = "/on_send_rtp_stopped", produces = "application/json;charset=UTF-8") @PostMapping(value = "/on_send_rtp_stopped", produces = "application/json;charset=UTF-8")
public HookResult onSendRtpStopped(HttpServletRequest request, @RequestBody OnSendRtpStoppedHookParam param) { public HookResult onSendRtpStopped(HttpServletRequest request, @RequestBody OnSendRtpStoppedHookParam param) {
logger.info("[ZLM HOOK] rtp发送关闭{}->{}/{}", param.getMediaServerId(), param.getApp(), param.getStream()); log.info("[ZLM HOOK] rtp发送关闭{}->{}/{}", param.getMediaServerId(), param.getApp(), param.getStream());
// 查找对应的上级推流发送停止 // 查找对应的上级推流发送停止
if (!"rtp".equals(param.getApp())) { if (!"rtp".equals(param.getApp())) {
@ -325,7 +246,7 @@ public class ZLMHttpHookListener {
applicationEventPublisher.publishEvent(event); applicationEventPublisher.publishEvent(event);
} }
}catch (Exception e) { }catch (Exception e) {
logger.info("[ZLM-HOOK-rtp发送关闭] 发送通知失败 ", e); log.info("[ZLM-HOOK-rtp发送关闭] 发送通知失败 ", e);
} }
return HookResult.SUCCESS(); return HookResult.SUCCESS();
@ -338,7 +259,7 @@ public class ZLMHttpHookListener {
@PostMapping(value = "/on_rtp_server_timeout", produces = "application/json;charset=UTF-8") @PostMapping(value = "/on_rtp_server_timeout", produces = "application/json;charset=UTF-8")
public HookResult onRtpServerTimeout(@RequestBody OnRtpServerTimeoutHookParam public HookResult onRtpServerTimeout(@RequestBody OnRtpServerTimeoutHookParam
param) { param) {
logger.info("[ZLM HOOK] rtpServer收流超时{}->{}({})", param.getMediaServerId(), param.getStream_id(), param.getSsrc()); log.info("[ZLM HOOK] rtpServer收流超时{}->{}({})", param.getMediaServerId(), param.getStream_id(), param.getSsrc());
try { try {
MediaRtpServerTimeoutEvent event = new MediaRtpServerTimeoutEvent(this); MediaRtpServerTimeoutEvent event = new MediaRtpServerTimeoutEvent(this);
@ -349,7 +270,7 @@ public class ZLMHttpHookListener {
applicationEventPublisher.publishEvent(event); applicationEventPublisher.publishEvent(event);
} }
}catch (Exception e) { }catch (Exception e) {
logger.info("[ZLM-HOOK-rtpServer收流超时] 发送通知失败 ", e); log.info("[ZLM-HOOK-rtpServer收流超时] 发送通知失败 ", e);
} }
return HookResult.SUCCESS(); return HookResult.SUCCESS();
@ -361,7 +282,7 @@ public class ZLMHttpHookListener {
@ResponseBody @ResponseBody
@PostMapping(value = "/on_record_mp4", produces = "application/json;charset=UTF-8") @PostMapping(value = "/on_record_mp4", produces = "application/json;charset=UTF-8")
public HookResult onRecordMp4(HttpServletRequest request, @RequestBody OnRecordMp4HookParam param) { public HookResult onRecordMp4(HttpServletRequest request, @RequestBody OnRecordMp4HookParam param) {
logger.info("[ZLM HOOK] 录像完成事件:{}->{}", param.getMediaServerId(), param.getFile_path()); log.info("[ZLM HOOK] 录像完成事件:{}->{}", param.getMediaServerId(), param.getFile_path());
try { try {
MediaServer mediaServerItem = mediaServerService.getOne(param.getMediaServerId()); MediaServer mediaServerItem = mediaServerService.getOne(param.getMediaServerId());
@ -371,7 +292,7 @@ public class ZLMHttpHookListener {
applicationEventPublisher.publishEvent(event); applicationEventPublisher.publishEvent(event);
} }
}catch (Exception e) { }catch (Exception e) {
logger.info("[ZLM-HOOK-rtpServer收流超时] 发送通知失败 ", e); log.info("[ZLM-HOOK-rtpServer收流超时] 发送通知失败 ", e);
} }
return HookResult.SUCCESS(); return HookResult.SUCCESS();

View File

@ -5,15 +5,14 @@ import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject; import com.alibaba.fastjson2.JSONObject;
import com.genersoft.iot.vmp.conf.DynamicTask; import com.genersoft.iot.vmp.conf.DynamicTask;
import com.genersoft.iot.vmp.conf.UserSetting; import com.genersoft.iot.vmp.conf.UserSetting;
import com.genersoft.iot.vmp.media.bean.MediaServer;
import com.genersoft.iot.vmp.media.event.mediaServer.MediaServerChangeEvent; import com.genersoft.iot.vmp.media.event.mediaServer.MediaServerChangeEvent;
import com.genersoft.iot.vmp.media.event.mediaServer.MediaServerDeleteEvent; import com.genersoft.iot.vmp.media.event.mediaServer.MediaServerDeleteEvent;
import com.genersoft.iot.vmp.media.service.IMediaServerService; import com.genersoft.iot.vmp.media.service.IMediaServerService;
import com.genersoft.iot.vmp.media.bean.MediaServer;
import com.genersoft.iot.vmp.media.zlm.dto.ZLMServerConfig; import com.genersoft.iot.vmp.media.zlm.dto.ZLMServerConfig;
import com.genersoft.iot.vmp.media.zlm.event.HookZlmServerKeepaliveEvent; import com.genersoft.iot.vmp.media.zlm.event.HookZlmServerKeepaliveEvent;
import com.genersoft.iot.vmp.media.zlm.event.HookZlmServerStartEvent; import com.genersoft.iot.vmp.media.zlm.event.HookZlmServerStartEvent;
import org.slf4j.Logger; import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.event.EventListener; import org.springframework.context.event.EventListener;
@ -31,11 +30,10 @@ import java.util.concurrent.ConcurrentHashMap;
/** /**
* 管理zlm流媒体节点的状态 * 管理zlm流媒体节点的状态
*/ */
@Slf4j
@Component @Component
public class ZLMMediaServerStatusManger { public class ZLMMediaServerStatusManger {
private final static Logger logger = LoggerFactory.getLogger(ZLMMediaServerStatusManger.class);
private final Map<Object, MediaServer> offlineZlmPrimaryMap = new ConcurrentHashMap<>(); private final Map<Object, MediaServer> offlineZlmPrimaryMap = new ConcurrentHashMap<>();
private final Map<Object, MediaServer> offlineZlmsecondaryMap = new ConcurrentHashMap<>(); private final Map<Object, MediaServer> offlineZlmsecondaryMap = new ConcurrentHashMap<>();
private final Map<Object, Long> offlineZlmTimeMap = new ConcurrentHashMap<>(); private final Map<Object, Long> offlineZlmTimeMap = new ConcurrentHashMap<>();
@ -74,7 +72,7 @@ public class ZLMMediaServerStatusManger {
if (!type.equals(mediaServerItem.getType())) { if (!type.equals(mediaServerItem.getType())) {
continue; continue;
} }
logger.info("[ZLM-添加待上线节点] ID" + mediaServerItem.getId()); log.info("[ZLM-添加待上线节点] ID" + mediaServerItem.getId());
offlineZlmPrimaryMap.put(mediaServerItem.getId(), mediaServerItem); offlineZlmPrimaryMap.put(mediaServerItem.getId(), mediaServerItem);
offlineZlmTimeMap.put(mediaServerItem.getId(), System.currentTimeMillis()); offlineZlmTimeMap.put(mediaServerItem.getId(), System.currentTimeMillis());
execute(); execute();
@ -93,7 +91,7 @@ public class ZLMMediaServerStatusManger {
if (serverItem == null) { if (serverItem == null) {
return; return;
} }
logger.info("[ZLM-HOOK事件-服务启动] ID" + event.getMediaServerItem().getId()); log.info("[ZLM-HOOK事件-服务启动] ID" + event.getMediaServerItem().getId());
online(serverItem, null); online(serverItem, null);
} }
@ -107,7 +105,7 @@ public class ZLMMediaServerStatusManger {
if (serverItem == null) { if (serverItem == null) {
return; return;
} }
logger.info("[ZLM-HOOK事件-心跳] ID" + event.getMediaServerItem().getId()); log.info("[ZLM-HOOK事件-心跳] ID" + event.getMediaServerItem().getId());
online(serverItem, null); online(serverItem, null);
} }
@ -117,7 +115,7 @@ public class ZLMMediaServerStatusManger {
if (event.getMediaServerId() == null) { if (event.getMediaServerId() == null) {
return; return;
} }
logger.info("[ZLM-节点被移除] ID" + event.getMediaServerId()); log.info("[ZLM-节点被移除] ID" + event.getMediaServerId());
offlineZlmPrimaryMap.remove(event.getMediaServerId()); offlineZlmPrimaryMap.remove(event.getMediaServerId());
offlineZlmsecondaryMap.remove(event.getMediaServerId()); offlineZlmsecondaryMap.remove(event.getMediaServerId());
offlineZlmTimeMap.remove(event.getMediaServerId()); offlineZlmTimeMap.remove(event.getMediaServerId());
@ -136,16 +134,16 @@ public class ZLMMediaServerStatusManger {
offlineZlmPrimaryMap.remove(mediaServerItem.getId()); offlineZlmPrimaryMap.remove(mediaServerItem.getId());
continue; continue;
} }
logger.info("[ZLM-尝试连接] ID{}, 地址: {}:{}", mediaServerItem.getId(), mediaServerItem.getIp(), mediaServerItem.getHttpPort()); log.info("[ZLM-尝试连接] ID{}, 地址: {}:{}", mediaServerItem.getId(), mediaServerItem.getIp(), mediaServerItem.getHttpPort());
JSONObject responseJson = zlmresTfulUtils.getMediaServerConfig(mediaServerItem); JSONObject responseJson = zlmresTfulUtils.getMediaServerConfig(mediaServerItem);
ZLMServerConfig zlmServerConfig = null; ZLMServerConfig zlmServerConfig = null;
if (responseJson == null) { if (responseJson == null) {
logger.info("[ZLM-尝试连接]失败, ID{}, 地址: {}:{}", mediaServerItem.getId(), mediaServerItem.getIp(), mediaServerItem.getHttpPort()); log.info("[ZLM-尝试连接]失败, ID{}, 地址: {}:{}", mediaServerItem.getId(), mediaServerItem.getIp(), mediaServerItem.getHttpPort());
continue; continue;
} }
JSONArray data = responseJson.getJSONArray("data"); JSONArray data = responseJson.getJSONArray("data");
if (data == null || data.isEmpty()) { if (data == null || data.isEmpty()) {
logger.info("[ZLM-尝试连接]失败, ID{}, 地址: {}:{}", mediaServerItem.getId(), mediaServerItem.getIp(), mediaServerItem.getHttpPort()); log.info("[ZLM-尝试连接]失败, ID{}, 地址: {}:{}", mediaServerItem.getId(), mediaServerItem.getIp(), mediaServerItem.getHttpPort());
}else { }else {
zlmServerConfig = JSON.parseObject(JSON.toJSONString(data.get(0)), ZLMServerConfig.class); zlmServerConfig = JSON.parseObject(JSON.toJSONString(data.get(0)), ZLMServerConfig.class);
initPort(mediaServerItem, zlmServerConfig); initPort(mediaServerItem, zlmServerConfig);
@ -158,17 +156,17 @@ public class ZLMMediaServerStatusManger {
if (offlineZlmTimeMap.get(mediaServerItem.getId()) < System.currentTimeMillis() - 30*60*1000) { if (offlineZlmTimeMap.get(mediaServerItem.getId()) < System.currentTimeMillis() - 30*60*1000) {
continue; continue;
} }
logger.info("[ZLM-尝试连接] ID{}, 地址: {}:{}", mediaServerItem.getId(), mediaServerItem.getIp(), mediaServerItem.getHttpPort()); log.info("[ZLM-尝试连接] ID{}, 地址: {}:{}", mediaServerItem.getId(), mediaServerItem.getIp(), mediaServerItem.getHttpPort());
JSONObject responseJson = zlmresTfulUtils.getMediaServerConfig(mediaServerItem); JSONObject responseJson = zlmresTfulUtils.getMediaServerConfig(mediaServerItem);
ZLMServerConfig zlmServerConfig = null; ZLMServerConfig zlmServerConfig = null;
if (responseJson == null) { if (responseJson == null) {
logger.info("[ZLM-尝试连接]失败, ID{}, 地址: {}:{}", mediaServerItem.getId(), mediaServerItem.getIp(), mediaServerItem.getHttpPort()); log.info("[ZLM-尝试连接]失败, ID{}, 地址: {}:{}", mediaServerItem.getId(), mediaServerItem.getIp(), mediaServerItem.getHttpPort());
offlineZlmTimeMap.put(mediaServerItem.getId(), System.currentTimeMillis()); offlineZlmTimeMap.put(mediaServerItem.getId(), System.currentTimeMillis());
continue; continue;
} }
JSONArray data = responseJson.getJSONArray("data"); JSONArray data = responseJson.getJSONArray("data");
if (data == null || data.isEmpty()) { if (data == null || data.isEmpty()) {
logger.info("[ZLM-尝试连接]失败, ID{}, 地址: {}:{}", mediaServerItem.getId(), mediaServerItem.getIp(), mediaServerItem.getHttpPort()); log.info("[ZLM-尝试连接]失败, ID{}, 地址: {}:{}", mediaServerItem.getId(), mediaServerItem.getIp(), mediaServerItem.getHttpPort());
offlineZlmTimeMap.put(mediaServerItem.getId(), System.currentTimeMillis()); offlineZlmTimeMap.put(mediaServerItem.getId(), System.currentTimeMillis());
}else { }else {
zlmServerConfig = JSON.parseObject(JSON.toJSONString(data.get(0)), ZLMServerConfig.class); zlmServerConfig = JSON.parseObject(JSON.toJSONString(data.get(0)), ZLMServerConfig.class);
@ -184,7 +182,7 @@ public class ZLMMediaServerStatusManger {
offlineZlmsecondaryMap.remove(mediaServerItem.getId()); offlineZlmsecondaryMap.remove(mediaServerItem.getId());
offlineZlmTimeMap.remove(mediaServerItem.getId()); offlineZlmTimeMap.remove(mediaServerItem.getId());
if (!mediaServerItem.isStatus()) { if (!mediaServerItem.isStatus()) {
logger.info("[ZLM-连接成功] ID{}, 地址: {}:{}", mediaServerItem.getId(), mediaServerItem.getIp(), mediaServerItem.getHttpPort()); log.info("[ZLM-连接成功] ID{}, 地址: {}:{}", mediaServerItem.getId(), mediaServerItem.getIp(), mediaServerItem.getHttpPort());
mediaServerItem.setStatus(true); mediaServerItem.setStatus(true);
mediaServerItem.setHookAliveInterval(10F); mediaServerItem.setHookAliveInterval(10F);
mediaServerService.update(mediaServerItem); mediaServerService.update(mediaServerItem);
@ -207,7 +205,7 @@ public class ZLMMediaServerStatusManger {
// 设置两次心跳未收到则认为zlm离线 // 设置两次心跳未收到则认为zlm离线
String key = "zlm-keepalive-" + mediaServerItem.getId(); String key = "zlm-keepalive-" + mediaServerItem.getId();
dynamicTask.startDelay(key, ()->{ dynamicTask.startDelay(key, ()->{
logger.warn("[ZLM-心跳超时] ID{}", mediaServerItem.getId()); log.warn("[ZLM-心跳超时] ID{}", mediaServerItem.getId());
mediaServerItem.setStatus(false); mediaServerItem.setStatus(false);
offlineZlmPrimaryMap.put(mediaServerItem.getId(), mediaServerItem); offlineZlmPrimaryMap.put(mediaServerItem.getId(), mediaServerItem);
offlineZlmTimeMap.put(mediaServerItem.getId(), System.currentTimeMillis()); offlineZlmTimeMap.put(mediaServerItem.getId(), System.currentTimeMillis());
@ -239,7 +237,7 @@ public class ZLMMediaServerStatusManger {
} }
public void setZLMConfig(MediaServer mediaServerItem, boolean restart) { public void setZLMConfig(MediaServer mediaServerItem, boolean restart) {
logger.info("[媒体服务节点] 正在设置 {} -> {}:{}", log.info("[媒体服务节点] 正在设置 {} -> {}:{}",
mediaServerItem.getId(), mediaServerItem.getIp(), mediaServerItem.getHttpPort()); mediaServerItem.getId(), mediaServerItem.getIp(), mediaServerItem.getHttpPort());
String protocol = sslEnabled ? "https" : "http"; String protocol = sslEnabled ? "https" : "http";
String hookPrefix = String.format("%s://%s:%s%s/index/hook", protocol, mediaServerItem.getHookIp(), serverPort, (serverServletContextPath == null || "/".equals(serverServletContextPath)) ? "" : serverServletContextPath); String hookPrefix = String.format("%s://%s:%s%s/index/hook", protocol, mediaServerItem.getHookIp(), serverPort, (serverServletContextPath == null || "/".equals(serverServletContextPath)) ? "" : serverServletContextPath);
@ -290,15 +288,15 @@ public class ZLMMediaServerStatusManger {
if (responseJSON != null && responseJSON.getInteger("code") == 0) { if (responseJSON != null && responseJSON.getInteger("code") == 0) {
if (restart) { if (restart) {
logger.info("[媒体服务节点] 设置成功,开始重启以保证配置生效 {} -> {}:{}", log.info("[媒体服务节点] 设置成功,开始重启以保证配置生效 {} -> {}:{}",
mediaServerItem.getId(), mediaServerItem.getIp(), mediaServerItem.getHttpPort()); mediaServerItem.getId(), mediaServerItem.getIp(), mediaServerItem.getHttpPort());
zlmresTfulUtils.restartServer(mediaServerItem); zlmresTfulUtils.restartServer(mediaServerItem);
}else { }else {
logger.info("[媒体服务节点] 设置成功 {} -> {}:{}", log.info("[媒体服务节点] 设置成功 {} -> {}:{}",
mediaServerItem.getId(), mediaServerItem.getIp(), mediaServerItem.getHttpPort()); mediaServerItem.getId(), mediaServerItem.getIp(), mediaServerItem.getHttpPort());
} }
}else { }else {
logger.info("[媒体服务节点] 设置媒体服务节点失败 {} -> {}:{}", log.info("[媒体服务节点] 设置媒体服务节点失败 {} -> {}:{}",
mediaServerItem.getId(), mediaServerItem.getIp(), mediaServerItem.getHttpPort()); mediaServerItem.getId(), mediaServerItem.getIp(), mediaServerItem.getHttpPort());
} }
} }

View File

@ -3,14 +3,15 @@ package com.genersoft.iot.vmp.media.zlm;
import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject; import com.alibaba.fastjson2.JSONObject;
import com.genersoft.iot.vmp.media.bean.MediaServer; import com.genersoft.iot.vmp.media.bean.MediaServer;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*; import okhttp3.*;
import okhttp3.logging.HttpLoggingInterceptor; import okhttp3.logging.HttpLoggingInterceptor;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.io.*; import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ConnectException; import java.net.ConnectException;
import java.net.SocketTimeoutException; import java.net.SocketTimeoutException;
import java.util.HashMap; import java.util.HashMap;
@ -18,11 +19,10 @@ import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@Slf4j
@Component @Component
public class ZLMRESTfulUtils { public class ZLMRESTfulUtils {
private final static Logger logger = LoggerFactory.getLogger(ZLMRESTfulUtils.class);
private OkHttpClient client; private OkHttpClient client;
public interface RequestCallback{ public interface RequestCallback{
@ -46,9 +46,9 @@ public class ZLMRESTfulUtils {
httpClientBuilder.readTimeout(readTimeOut,TimeUnit.SECONDS); httpClientBuilder.readTimeout(readTimeOut,TimeUnit.SECONDS);
// 设置连接池 // 设置连接池
httpClientBuilder.connectionPool(new ConnectionPool(16, 5, TimeUnit.MINUTES)); httpClientBuilder.connectionPool(new ConnectionPool(16, 5, TimeUnit.MINUTES));
if (logger.isDebugEnabled()) { if (log.isDebugEnabled()) {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor(message -> { HttpLoggingInterceptor logging = new HttpLoggingInterceptor(message -> {
logger.debug("http请求参数" + message); log.debug("http请求参数" + message);
}); });
logging.setLevel(HttpLoggingInterceptor.Level.BASIC); logging.setLevel(HttpLoggingInterceptor.Level.BASIC);
// OkHttp進行添加攔截器loggingInterceptor // OkHttp進行添加攔截器loggingInterceptor
@ -107,19 +107,19 @@ public class ZLMRESTfulUtils {
Objects.requireNonNull(response.body()).close(); Objects.requireNonNull(response.body()).close();
} }
}catch (IOException e) { }catch (IOException e) {
logger.error(String.format("[ %s ]请求失败: %s", url, e.getMessage())); log.error(String.format("[ %s ]请求失败: %s", url, e.getMessage()));
if(e instanceof SocketTimeoutException){ if(e instanceof SocketTimeoutException){
//读取超时超时异常 //读取超时超时异常
logger.error(String.format("读取ZLM数据超时失败: %s, %s", url, e.getMessage())); log.error(String.format("读取ZLM数据超时失败: %s, %s", url, e.getMessage()));
} }
if(e instanceof ConnectException){ if(e instanceof ConnectException){
//判断连接异常我这里是报Failed to connect to 10.7.5.144 //判断连接异常我这里是报Failed to connect to 10.7.5.144
logger.error(String.format("连接ZLM连接失败: %s, %s", url, e.getMessage())); log.error(String.format("连接ZLM连接失败: %s, %s", url, e.getMessage()));
} }
}catch (Exception e){ }catch (Exception e){
logger.error(String.format("访问ZLM失败: %s, %s", url, e.getMessage())); log.error(String.format("访问ZLM失败: %s, %s", url, e.getMessage()));
} }
}else { }else {
client.newCall(request).enqueue(new Callback(){ client.newCall(request).enqueue(new Callback(){
@ -131,7 +131,7 @@ public class ZLMRESTfulUtils {
String responseStr = Objects.requireNonNull(response.body()).string(); String responseStr = Objects.requireNonNull(response.body()).string();
callback.run(JSON.parseObject(responseStr)); callback.run(JSON.parseObject(responseStr));
} catch (IOException e) { } catch (IOException e) {
logger.error(String.format("[ %s ]请求失败: %s", url, e.getMessage())); log.error(String.format("[ %s ]请求失败: %s", url, e.getMessage()));
} }
}else { }else {
@ -142,15 +142,15 @@ public class ZLMRESTfulUtils {
@Override @Override
public void onFailure(@NotNull Call call, @NotNull IOException e) { public void onFailure(@NotNull Call call, @NotNull IOException e) {
logger.error(String.format("连接ZLM失败: %s, %s", call.request().toString(), e.getMessage())); log.error(String.format("连接ZLM失败: %s, %s", call.request().toString(), e.getMessage()));
if(e instanceof SocketTimeoutException){ if(e instanceof SocketTimeoutException){
//读取超时超时异常 //读取超时超时异常
logger.error(String.format("读取ZLM数据失败: %s, %s", call.request().toString(), e.getMessage())); log.error(String.format("读取ZLM数据失败: %s, %s", call.request().toString(), e.getMessage()));
} }
if(e instanceof ConnectException){ if(e instanceof ConnectException){
//判断连接异常我这里是报Failed to connect to 10.7.5.144 //判断连接异常我这里是报Failed to connect to 10.7.5.144
logger.error(String.format("连接ZLM失败: %s, %s", call.request().toString(), e.getMessage())); log.error(String.format("连接ZLM失败: %s, %s", call.request().toString(), e.getMessage()));
} }
} }
}); });
@ -179,7 +179,7 @@ public class ZLMRESTfulUtils {
Request request = new Request.Builder() Request request = new Request.Builder()
.url(httpBuilder.build()) .url(httpBuilder.build())
.build(); .build();
logger.info(request.toString()); log.info(request.toString());
try { try {
OkHttpClient client = getClient(); OkHttpClient client = getClient();
Response response = client.newCall(request).execute(); Response response = client.newCall(request).execute();
@ -188,7 +188,7 @@ public class ZLMRESTfulUtils {
File snapFolder = new File(targetPath); File snapFolder = new File(targetPath);
if (!snapFolder.exists()) { if (!snapFolder.exists()) {
if (!snapFolder.mkdirs()) { if (!snapFolder.mkdirs()) {
logger.warn("{}路径创建失败", snapFolder.getAbsolutePath()); log.warn("{}路径创建失败", snapFolder.getAbsolutePath());
} }
} }
@ -199,17 +199,17 @@ public class ZLMRESTfulUtils {
outStream.flush(); outStream.flush();
outStream.close(); outStream.close();
} else { } else {
logger.error(String.format("[ %s ]请求失败: %s %s", url, response.code(), response.message())); log.error(String.format("[ %s ]请求失败: %s %s", url, response.code(), response.message()));
} }
} else { } else {
logger.error(String.format("[ %s ]请求失败: %s %s", url, response.code(), response.message())); log.error(String.format("[ %s ]请求失败: %s %s", url, response.code(), response.message()));
} }
Objects.requireNonNull(response.body()).close(); Objects.requireNonNull(response.body()).close();
} catch (ConnectException e) { } catch (ConnectException e) {
logger.error(String.format("连接ZLM失败: %s, %s", e.getCause().getMessage(), e.getMessage())); log.error(String.format("连接ZLM失败: %s, %s", e.getCause().getMessage(), e.getMessage()));
logger.info("请检查media配置并确认ZLM已启动..."); log.info("请检查media配置并确认ZLM已启动...");
} catch (IOException e) { } catch (IOException e) {
logger.error(String.format("[ %s ]请求失败: %s", url, e.getMessage())); log.error(String.format("[ %s ]请求失败: %s", url, e.getMessage()));
} }
} }
@ -268,8 +268,8 @@ public class ZLMRESTfulUtils {
public JSONObject addFFmpegSource(MediaServer mediaServerItem, String src_url, String dst_url, Integer timeout_ms, public JSONObject addFFmpegSource(MediaServer mediaServerItem, String src_url, String dst_url, Integer timeout_ms,
boolean enable_audio, boolean enable_mp4, String ffmpeg_cmd_key){ boolean enable_audio, boolean enable_mp4, String ffmpeg_cmd_key){
logger.info(src_url); log.info(src_url);
logger.info(dst_url); log.info(dst_url);
Map<String, Object> param = new HashMap<>(); Map<String, Object> param = new HashMap<>();
param.put("src_url", src_url); param.put("src_url", src_url);
param.put("dst_url", dst_url); param.put("dst_url", dst_url);

View File

@ -6,19 +6,16 @@ import com.genersoft.iot.vmp.common.CommonCallback;
import com.genersoft.iot.vmp.conf.UserSetting; import com.genersoft.iot.vmp.conf.UserSetting;
import com.genersoft.iot.vmp.gb28181.bean.SendRtpItem; import com.genersoft.iot.vmp.gb28181.bean.SendRtpItem;
import com.genersoft.iot.vmp.media.bean.MediaServer; import com.genersoft.iot.vmp.media.bean.MediaServer;
import org.slf4j.Logger; import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@Slf4j
@Component @Component
public class ZLMServerFactory { public class ZLMServerFactory {
private Logger logger = LoggerFactory.getLogger("ZLMServerFactory");
@Autowired @Autowired
private ZLMRESTfulUtils zlmresTfulUtils; private ZLMRESTfulUtils zlmresTfulUtils;
@ -43,7 +40,7 @@ public class ZLMServerFactory {
int result = -1; int result = -1;
// 查询此rtp server 是否已经存在 // 查询此rtp server 是否已经存在
JSONObject rtpInfo = zlmresTfulUtils.getRtpInfo(mediaServerItem, streamId); JSONObject rtpInfo = zlmresTfulUtils.getRtpInfo(mediaServerItem, streamId);
logger.info(JSONObject.toJSONString(rtpInfo)); log.info(JSONObject.toJSONString(rtpInfo));
if(rtpInfo.getInteger("code") == 0){ if(rtpInfo.getInteger("code") == 0){
if (rtpInfo.getBoolean("exist")) { if (rtpInfo.getBoolean("exist")) {
result = rtpInfo.getInteger("local_port"); result = rtpInfo.getInteger("local_port");
@ -57,7 +54,7 @@ public class ZLMServerFactory {
if (jsonObject.getInteger("code") == 0) { if (jsonObject.getInteger("code") == 0) {
return createRTPServer(mediaServerItem, streamId, ssrc, port,onlyAuto, reUsePort, tcpMode); return createRTPServer(mediaServerItem, streamId, ssrc, port,onlyAuto, reUsePort, tcpMode);
}else { }else {
logger.warn("[开启rtpServer], 重启RtpServer错误"); log.warn("[开启rtpServer], 重启RtpServer错误");
} }
} }
} }
@ -91,16 +88,16 @@ public class ZLMServerFactory {
} }
JSONObject openRtpServerResultJson = zlmresTfulUtils.openRtpServer(mediaServerItem, param); JSONObject openRtpServerResultJson = zlmresTfulUtils.openRtpServer(mediaServerItem, param);
logger.info(JSONObject.toJSONString(openRtpServerResultJson)); log.info(JSONObject.toJSONString(openRtpServerResultJson));
if (openRtpServerResultJson != null) { if (openRtpServerResultJson != null) {
if (openRtpServerResultJson.getInteger("code") == 0) { if (openRtpServerResultJson.getInteger("code") == 0) {
result= openRtpServerResultJson.getInteger("port"); result= openRtpServerResultJson.getInteger("port");
}else { }else {
logger.error("创建RTP Server 失败 {}: ", openRtpServerResultJson.getString("msg")); log.error("创建RTP Server 失败 {}: ", openRtpServerResultJson.getString("msg"));
} }
}else { }else {
// 检查ZLM状态 // 检查ZLM状态
logger.error("创建RTP Server 失败 {}: 请检查ZLM服务", param.get("port")); log.error("创建RTP Server 失败 {}: 请检查ZLM服务", param.get("port"));
} }
return result; return result;
} }
@ -111,16 +108,16 @@ public class ZLMServerFactory {
Map<String, Object> param = new HashMap<>(); Map<String, Object> param = new HashMap<>();
param.put("stream_id", streamId); param.put("stream_id", streamId);
JSONObject jsonObject = zlmresTfulUtils.closeRtpServer(serverItem, param); JSONObject jsonObject = zlmresTfulUtils.closeRtpServer(serverItem, param);
logger.info("关闭RTP Server " + jsonObject); log.info("关闭RTP Server " + jsonObject);
if (jsonObject != null ) { if (jsonObject != null ) {
if (jsonObject.getInteger("code") == 0) { if (jsonObject.getInteger("code") == 0) {
result = jsonObject.getInteger("hit") >= 1; result = jsonObject.getInteger("hit") >= 1;
}else { }else {
logger.error("关闭RTP Server 失败: " + jsonObject.getString("msg")); log.error("关闭RTP Server 失败: " + jsonObject.getString("msg"));
} }
}else { }else {
// 检查ZLM状态 // 检查ZLM状态
logger.error("关闭RTP Server 失败: 请检查ZLM服务"); log.error("关闭RTP Server 失败: 请检查ZLM服务");
} }
} }
return result; return result;
@ -139,11 +136,11 @@ public class ZLMServerFactory {
callback.run(jsonObject.getInteger("hit") == 1); callback.run(jsonObject.getInteger("hit") == 1);
return; return;
}else { }else {
logger.error("关闭RTP Server 失败: " + jsonObject.getString("msg")); log.error("关闭RTP Server 失败: " + jsonObject.getString("msg"));
} }
}else { }else {
// 检查ZLM状态 // 检查ZLM状态
logger.error("关闭RTP Server 失败: 请检查ZLM服务"); log.error("关闭RTP Server 失败: 请检查ZLM服务");
} }
callback.run(false); callback.run(false);
}); });
@ -195,11 +192,11 @@ public class ZLMServerFactory {
} }
Integer code = mediaInfo.getInteger("code"); Integer code = mediaInfo.getInteger("code");
if (code < 0) { if (code < 0) {
logger.warn("查询流({}/{})是否有其它观看者时得到: {}", app, streamId, mediaInfo.getString("msg")); log.warn("查询流({}/{})是否有其它观看者时得到: {}", app, streamId, mediaInfo.getString("msg"));
return -1; return -1;
} }
if ( code == 0 && mediaInfo.getBoolean("online") != null && ! mediaInfo.getBoolean("online")) { if ( code == 0 && mediaInfo.getBoolean("online") != null && ! mediaInfo.getBoolean("online")) {
logger.warn("查询流({}/{})是否有其它观看者时得到: {}", app, streamId, mediaInfo.getString("msg")); log.warn("查询流({}/{})是否有其它观看者时得到: {}", app, streamId, mediaInfo.getString("msg"));
return -1; return -1;
} }
return mediaInfo.getInteger("totalReaderCount"); return mediaInfo.getInteger("totalReaderCount");
@ -207,7 +204,7 @@ public class ZLMServerFactory {
public JSONObject startSendRtp(MediaServer mediaInfo, SendRtpItem sendRtpItem) { public JSONObject startSendRtp(MediaServer mediaInfo, SendRtpItem sendRtpItem) {
String is_Udp = sendRtpItem.isTcp() ? "0" : "1"; String is_Udp = sendRtpItem.isTcp() ? "0" : "1";
logger.info("rtp/{}开始推流, 目标={}:{}SSRC={}", sendRtpItem.getStream(), sendRtpItem.getIp(), sendRtpItem.getPort(), sendRtpItem.getSsrc()); log.info("rtp/{}开始推流, 目标={}:{}SSRC={}", sendRtpItem.getStream(), sendRtpItem.getIp(), sendRtpItem.getPort(), sendRtpItem.getSsrc());
Map<String, Object> param = new HashMap<>(12); Map<String, Object> param = new HashMap<>(12);
param.put("vhost","__defaultVhost__"); param.put("vhost","__defaultVhost__");
param.put("app",sendRtpItem.getApp()); param.put("app",sendRtpItem.getApp());
@ -254,12 +251,12 @@ public class ZLMServerFactory {
boolean result = false; boolean result = false;
JSONObject jsonObject = zlmresTfulUtils.updateRtpServerSSRC(mediaServerItem, streamId, ssrc); JSONObject jsonObject = zlmresTfulUtils.updateRtpServerSSRC(mediaServerItem, streamId, ssrc);
if (jsonObject == null) { if (jsonObject == null) {
logger.error("[更新RTPServer] 失败: 请检查ZLM服务"); log.error("[更新RTPServer] 失败: 请检查ZLM服务");
} else if (jsonObject.getInteger("code") == 0) { } else if (jsonObject.getInteger("code") == 0) {
result= true; result= true;
logger.info("[更新RTPServer] 成功"); log.info("[更新RTPServer] 成功");
} else { } else {
logger.error("[更新RTPServer] 失败: {}, streamId{}ssrc{}->\r\n{}",jsonObject.getString("msg"), log.error("[更新RTPServer] 失败: {}, streamId{}ssrc{}->\r\n{}",jsonObject.getString("msg"),
streamId, ssrc, jsonObject); streamId, ssrc, jsonObject);
} }
return result; return result;

View File

@ -20,9 +20,8 @@ import com.genersoft.iot.vmp.utils.DateUtil;
import com.genersoft.iot.vmp.vmanager.bean.ErrorCode; import com.genersoft.iot.vmp.vmanager.bean.ErrorCode;
import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo; import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener; import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.Async;
@ -35,13 +34,11 @@ import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
@Slf4j
@Service @Service
@DS("share") @DS("share")
public class CloudRecordServiceImpl implements ICloudRecordService { public class CloudRecordServiceImpl implements ICloudRecordService {
private final static Logger logger = LoggerFactory.getLogger(CloudRecordServiceImpl.class);
@Autowired @Autowired
private CloudRecordServiceMapper cloudRecordServiceMapper; private CloudRecordServiceMapper cloudRecordServiceMapper;
@ -116,7 +113,7 @@ public class CloudRecordServiceImpl implements ICloudRecordService {
cloudRecordItem.setCallId(streamAuthorityInfo.getCallId()); cloudRecordItem.setCallId(streamAuthorityInfo.getCallId());
} }
} }
logger.info("[添加录像记录] {}/{}, callId: {}, 内容:{}", event.getApp(), event.getStream(), cloudRecordItem.getCallId(), event.getRecordInfo()); log.info("[添加录像记录] {}/{}, callId: {}, 内容:{}", event.getApp(), event.getStream(), cloudRecordItem.getCallId(), event.getRecordInfo());
cloudRecordServiceMapper.add(cloudRecordItem); cloudRecordServiceMapper.add(cloudRecordItem);
} }

View File

@ -20,8 +20,7 @@ import com.genersoft.iot.vmp.storager.dao.PlatformChannelMapper;
import com.genersoft.iot.vmp.utils.DateUtil; import com.genersoft.iot.vmp.utils.DateUtil;
import com.genersoft.iot.vmp.vmanager.bean.ResourceBaseInfo; import com.genersoft.iot.vmp.vmanager.bean.ResourceBaseInfo;
import com.genersoft.iot.vmp.vmanager.gb28181.platform.bean.ChannelReduce; import com.genersoft.iot.vmp.vmanager.gb28181.platform.bean.ChannelReduce;
import org.slf4j.Logger; import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
@ -35,12 +34,11 @@ import java.util.concurrent.CopyOnWriteArrayList;
/** /**
* @author lin * @author lin
*/ */
@Slf4j
@Service @Service
@DS("master") @DS("master")
public class DeviceChannelServiceImpl implements IDeviceChannelService { public class DeviceChannelServiceImpl implements IDeviceChannelService {
private final static Logger logger = LoggerFactory.getLogger(DeviceChannelServiceImpl.class);
@Autowired @Autowired
private EventPublisher eventPublisher; private EventPublisher eventPublisher;
@ -278,9 +276,9 @@ public class DeviceChannelServiceImpl implements IDeviceChannelService {
assert !ObjectUtils.isEmpty(channel.getDeviceId()); assert !ObjectUtils.isEmpty(channel.getDeviceId());
assert !ObjectUtils.isEmpty(channel.getStreamIdentification()); assert !ObjectUtils.isEmpty(channel.getStreamIdentification());
if (ObjectUtils.isEmpty(channel.getStreamIdentification())) { if (ObjectUtils.isEmpty(channel.getStreamIdentification())) {
logger.info("[重置通道码流类型] 设备: {}, 码流: {}", channel.getDeviceId(), channel.getStreamIdentification()); log.info("[重置通道码流类型] 设备: {}, 码流: {}", channel.getDeviceId(), channel.getStreamIdentification());
}else { }else {
logger.info("[更新通道码流类型] 设备: {}, 通道:{} 码流: {}", channel.getDeviceId(), channel.getDeviceId(), log.info("[更新通道码流类型] 设备: {}, 通道:{} 码流: {}", channel.getDeviceId(), channel.getDeviceId(),
channel.getStreamIdentification()); channel.getStreamIdentification());
} }
channelMapper.updateChannelStreamIdentification(channel); channelMapper.updateChannelStreamIdentification(channel);
@ -321,7 +319,7 @@ public class DeviceChannelServiceImpl implements IDeviceChannelService {
return; return;
} }
if (deviceChannels.size() > 100) { if (deviceChannels.size() > 100) {
logger.warn("[更新通道位置信息后发送通知] 设备可能是平台,上报的位置信息未标明通道编号," + log.warn("[更新通道位置信息后发送通知] 设备可能是平台,上报的位置信息未标明通道编号," +
"导致所有通道被更新位置, deviceId:{}", device.getDeviceId()); "导致所有通道被更新位置, deviceId:{}", device.getDeviceId());
} }
for (DeviceChannel channel : deviceChannels) { for (DeviceChannel channel : deviceChannels) {
@ -330,7 +328,7 @@ public class DeviceChannelServiceImpl implements IDeviceChannelService {
try { try {
eventPublisher.mobilePositionEventPublish(mobilePosition); eventPublisher.mobilePositionEventPublish(mobilePosition);
}catch (Exception e) { }catch (Exception e) {
logger.error("[向上级转发移动位置失败] ", e); log.error("[向上级转发移动位置失败] ", e);
} }
// 发送redis消息 通知位置信息的变化 // 发送redis消息 通知位置信息的变化
JSONObject jsonObject = new JSONObject(); JSONObject jsonObject = new JSONObject();
@ -473,10 +471,10 @@ public class DeviceChannelServiceImpl implements IDeviceChannelService {
} }
if (stringBuilder.length() > 0) { if (stringBuilder.length() > 0) {
logger.info("[目录查询]收到的数据存在重复: {}" , stringBuilder); log.info("[目录查询]收到的数据存在重复: {}" , stringBuilder);
} }
if(CollectionUtils.isEmpty(channels)){ if(CollectionUtils.isEmpty(channels)){
logger.info("通道重设,数据为空={}" , deviceChannelList); log.info("通道重设,数据为空={}" , deviceChannelList);
return false; return false;
} }
int limitCount = 50; int limitCount = 50;

View File

@ -25,8 +25,7 @@ import com.genersoft.iot.vmp.storager.dao.DeviceMapper;
import com.genersoft.iot.vmp.storager.dao.PlatformChannelMapper; import com.genersoft.iot.vmp.storager.dao.PlatformChannelMapper;
import com.genersoft.iot.vmp.utils.DateUtil; import com.genersoft.iot.vmp.utils.DateUtil;
import com.genersoft.iot.vmp.vmanager.bean.ResourceBaseInfo; import com.genersoft.iot.vmp.vmanager.bean.ResourceBaseInfo;
import org.slf4j.Logger; import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@ -45,12 +44,11 @@ import java.util.concurrent.TimeUnit;
/** /**
* 设备业务目录订阅 * 设备业务目录订阅
*/ */
@Slf4j
@Service @Service
@DS("master") @DS("master")
public class DeviceServiceImpl implements IDeviceService { public class DeviceServiceImpl implements IDeviceService {
private final static Logger logger = LoggerFactory.getLogger(DeviceServiceImpl.class);
@Autowired @Autowired
private SIPCommander cmder; private SIPCommander cmder;
@ -104,7 +102,7 @@ public class DeviceServiceImpl implements IDeviceService {
@Override @Override
public void online(Device device, SipTransactionInfo sipTransactionInfo) { public void online(Device device, SipTransactionInfo sipTransactionInfo) {
logger.info("[设备上线] deviceId{}->{}:{}", device.getDeviceId(), device.getIp(), device.getPort()); log.info("[设备上线] deviceId{}->{}:{}", device.getDeviceId(), device.getIp(), device.getPort());
Device deviceInRedis = redisCatchStorage.getDevice(device.getDeviceId()); Device deviceInRedis = redisCatchStorage.getDevice(device.getDeviceId());
Device deviceInDb = deviceMapper.getDeviceByDeviceId(device.getDeviceId()); Device deviceInDb = deviceMapper.getDeviceByDeviceId(device.getDeviceId());
@ -132,13 +130,13 @@ public class DeviceServiceImpl implements IDeviceService {
device.setOnLine(true); device.setOnLine(true);
device.setCreateTime(now); device.setCreateTime(now);
device.setUpdateTime(now); device.setUpdateTime(now);
logger.info("[设备上线,首次注册]: {},查询设备信息以及通道信息", device.getDeviceId()); log.info("[设备上线,首次注册]: {},查询设备信息以及通道信息", device.getDeviceId());
deviceMapper.add(device); deviceMapper.add(device);
redisCatchStorage.updateDevice(device); redisCatchStorage.updateDevice(device);
try { try {
commander.deviceInfoQuery(device); commander.deviceInfoQuery(device);
} catch (InvalidArgumentException | SipException | ParseException e) { } catch (InvalidArgumentException | SipException | ParseException e) {
logger.error("[命令发送失败] 查询设备信息: {}", e.getMessage()); log.error("[命令发送失败] 查询设备信息: {}", e.getMessage());
} }
sync(device); sync(device);
}else { }else {
@ -148,11 +146,11 @@ public class DeviceServiceImpl implements IDeviceService {
deviceMapper.update(device); deviceMapper.update(device);
redisCatchStorage.updateDevice(device); redisCatchStorage.updateDevice(device);
if (userSetting.getSyncChannelOnDeviceOnline()) { if (userSetting.getSyncChannelOnDeviceOnline()) {
logger.info("[设备上线,离线状态下重新注册]: {},查询设备信息以及通道信息", device.getDeviceId()); log.info("[设备上线,离线状态下重新注册]: {},查询设备信息以及通道信息", device.getDeviceId());
try { try {
commander.deviceInfoQuery(device); commander.deviceInfoQuery(device);
} catch (InvalidArgumentException | SipException | ParseException e) { } catch (InvalidArgumentException | SipException | ParseException e) {
logger.error("[命令发送失败] 查询设备信息: {}", e.getMessage()); log.error("[命令发送失败] 查询设备信息: {}", e.getMessage());
} }
sync(device); sync(device);
// TODO 如果设备下的通道级联到了其他平台那么需要发送事件或者notify给上级平台 // TODO 如果设备下的通道级联到了其他平台那么需要发送事件或者notify给上级平台
@ -172,7 +170,7 @@ public class DeviceServiceImpl implements IDeviceService {
}else { }else {
if (deviceChannelMapper.queryAllChannels(device.getDeviceId()).size() == 0) { if (deviceChannelMapper.queryAllChannels(device.getDeviceId()).size() == 0) {
logger.info("[设备上线]: {}通道数为0,查询通道信息", device.getDeviceId()); log.info("[设备上线]: {}通道数为0,查询通道信息", device.getDeviceId());
sync(device); sync(device);
} }
@ -202,7 +200,7 @@ public class DeviceServiceImpl implements IDeviceService {
@Override @Override
public void offline(String deviceId, String reason) { public void offline(String deviceId, String reason) {
logger.warn("[设备离线]{}, device{}", reason, deviceId); log.warn("[设备离线]{}, device{}", reason, deviceId);
Device device = deviceMapper.getDeviceByDeviceId(deviceId); Device device = deviceMapper.getDeviceByDeviceId(deviceId);
if (device == null) { if (device == null) {
return; return;
@ -255,7 +253,7 @@ public class DeviceServiceImpl implements IDeviceService {
if (device == null || device.getSubscribeCycleForCatalog() < 0) { if (device == null || device.getSubscribeCycleForCatalog() < 0) {
return false; return false;
} }
logger.info("[添加目录订阅] 设备{}", device.getDeviceId()); log.info("[添加目录订阅] 设备{}", device.getDeviceId());
// 添加目录订阅 // 添加目录订阅
CatalogSubscribeTask catalogSubscribeTask = new CatalogSubscribeTask(device, sipCommander, dynamicTask); CatalogSubscribeTask catalogSubscribeTask = new CatalogSubscribeTask(device, sipCommander, dynamicTask);
// 刷新订阅 // 刷新订阅
@ -272,7 +270,7 @@ public class DeviceServiceImpl implements IDeviceService {
if (device == null || device.getSubscribeCycleForCatalog() < 0) { if (device == null || device.getSubscribeCycleForCatalog() < 0) {
return false; return false;
} }
logger.info("[移除目录订阅]: {}", device.getDeviceId()); log.info("[移除目录订阅]: {}", device.getDeviceId());
String taskKey = device.getDeviceId() + "catalog"; String taskKey = device.getDeviceId() + "catalog";
if (device.isOnLine()) { if (device.isOnLine()) {
Runnable runnable = dynamicTask.get(taskKey); Runnable runnable = dynamicTask.get(taskKey);
@ -290,7 +288,7 @@ public class DeviceServiceImpl implements IDeviceService {
if (device == null || device.getSubscribeCycleForMobilePosition() < 0) { if (device == null || device.getSubscribeCycleForMobilePosition() < 0) {
return false; return false;
} }
logger.info("[添加移动位置订阅] 设备{}", device.getDeviceId()); log.info("[添加移动位置订阅] 设备{}", device.getDeviceId());
// 添加目录订阅 // 添加目录订阅
MobilePositionSubscribeTask mobilePositionSubscribeTask = new MobilePositionSubscribeTask(device, sipCommander, dynamicTask); MobilePositionSubscribeTask mobilePositionSubscribeTask = new MobilePositionSubscribeTask(device, sipCommander, dynamicTask);
// 设置最小值为30 // 设置最小值为30
@ -306,7 +304,7 @@ public class DeviceServiceImpl implements IDeviceService {
if (device == null || device.getSubscribeCycleForCatalog() < 0) { if (device == null || device.getSubscribeCycleForCatalog() < 0) {
return false; return false;
} }
logger.info("[移除移动位置订阅]: {}", device.getDeviceId()); log.info("[移除移动位置订阅]: {}", device.getDeviceId());
String taskKey = device.getDeviceId() + "mobile_position"; String taskKey = device.getDeviceId() + "mobile_position";
if (device.isOnLine()) { if (device.isOnLine()) {
Runnable runnable = dynamicTask.get(taskKey); Runnable runnable = dynamicTask.get(taskKey);
@ -332,7 +330,7 @@ public class DeviceServiceImpl implements IDeviceService {
@Override @Override
public void sync(Device device) { public void sync(Device device) {
if (catalogResponseMessageHandler.isSyncRunning(device.getDeviceId())) { if (catalogResponseMessageHandler.isSyncRunning(device.getDeviceId())) {
logger.info("开启同步时发现同步已经存在"); log.info("开启同步时发现同步已经存在");
return; return;
} }
int sn = (int)((Math.random()*9+1)*100000); int sn = (int)((Math.random()*9+1)*100000);
@ -343,7 +341,7 @@ public class DeviceServiceImpl implements IDeviceService {
catalogResponseMessageHandler.setChannelSyncEnd(device.getDeviceId(), errorMsg); catalogResponseMessageHandler.setChannelSyncEnd(device.getDeviceId(), errorMsg);
}); });
} catch (SipException | InvalidArgumentException | ParseException e) { } catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[同步通道], 信令发送失败:{}", e.getMessage() ); log.error("[同步通道], 信令发送失败:{}", e.getMessage() );
String errorMsg = String.format("同步通道失败,信令发送失败: %s", e.getMessage()); String errorMsg = String.format("同步通道失败,信令发送失败: %s", e.getMessage());
catalogResponseMessageHandler.setChannelSyncEnd(device.getDeviceId(), errorMsg); catalogResponseMessageHandler.setChannelSyncEnd(device.getDeviceId(), errorMsg);
} }
@ -381,7 +379,7 @@ public class DeviceServiceImpl implements IDeviceService {
try { try {
sipCommander.deviceStatusQuery(device, null); sipCommander.deviceStatusQuery(device, null);
} catch (InvalidArgumentException | SipException | ParseException e) { } catch (InvalidArgumentException | SipException | ParseException e) {
logger.error("[命令发送失败] 设备状态查询: {}", e.getMessage()); log.error("[命令发送失败] 设备状态查询: {}", e.getMessage());
} }
} }
@ -446,7 +444,7 @@ public class DeviceServiceImpl implements IDeviceService {
public void updateCustomDevice(Device device) { public void updateCustomDevice(Device device) {
Device deviceInStore = deviceMapper.getDeviceByDeviceId(device.getDeviceId()); Device deviceInStore = deviceMapper.getDeviceByDeviceId(device.getDeviceId());
if (deviceInStore == null) { if (deviceInStore == null) {
logger.warn("更新设备时未找到设备信息"); log.warn("更新设备时未找到设备信息");
return; return;
} }

View File

@ -12,8 +12,7 @@ import com.genersoft.iot.vmp.service.IInviteStreamService;
import com.genersoft.iot.vmp.service.bean.ErrorCallback; import com.genersoft.iot.vmp.service.bean.ErrorCallback;
import com.genersoft.iot.vmp.storager.IVideoManagerStorage; import com.genersoft.iot.vmp.storager.IVideoManagerStorage;
import com.genersoft.iot.vmp.utils.redis.RedisUtil; import com.genersoft.iot.vmp.utils.redis.RedisUtil;
import org.slf4j.Logger; import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener; import org.springframework.context.event.EventListener;
import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.RedisTemplate;
@ -26,12 +25,11 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@Slf4j
@Service @Service
@DS("master") @DS("master")
public class InviteStreamServiceImpl implements IInviteStreamService { public class InviteStreamServiceImpl implements IInviteStreamService {
private final Logger logger = LoggerFactory.getLogger(InviteStreamServiceImpl.class);
private final Map<String, List<ErrorCallback<Object>>> inviteErrorCallbackMap = new ConcurrentHashMap<>(); private final Map<String, List<ErrorCallback<Object>>> inviteErrorCallbackMap = new ConcurrentHashMap<>();
@Autowired @Autowired
@ -73,7 +71,7 @@ public class InviteStreamServiceImpl implements IInviteStreamService {
@Override @Override
public void updateInviteInfo(InviteInfo inviteInfo, Long time) { public void updateInviteInfo(InviteInfo inviteInfo, Long time) {
if (inviteInfo == null || (inviteInfo.getDeviceId() == null || inviteInfo.getChannelId() == null)) { if (inviteInfo == null || (inviteInfo.getDeviceId() == null || inviteInfo.getChannelId() == null)) {
logger.warn("[更新Invite信息],参数不全: {}", JSON.toJSON(inviteInfo)); log.warn("[更新Invite信息],参数不全: {}", JSON.toJSON(inviteInfo));
return; return;
} }
InviteInfo inviteInfoForUpdate = null; InviteInfo inviteInfoForUpdate = null;
@ -91,7 +89,7 @@ public class InviteStreamServiceImpl implements IInviteStreamService {
InviteInfo inviteInfoInRedis = getInviteInfo(inviteInfo.getType(), inviteInfo.getDeviceId(), InviteInfo inviteInfoInRedis = getInviteInfo(inviteInfo.getType(), inviteInfo.getDeviceId(),
inviteInfo.getChannelId(), inviteInfo.getStream()); inviteInfo.getChannelId(), inviteInfo.getStream());
if (inviteInfoInRedis == null) { if (inviteInfoInRedis == null) {
logger.warn("[更新Invite信息]未从缓存中读取到Invite信息 deviceId: {}, channel: {}, stream: {}", log.warn("[更新Invite信息]未从缓存中读取到Invite信息 deviceId: {}, channel: {}, stream: {}",
inviteInfo.getDeviceId(), inviteInfo.getChannelId(), inviteInfo.getStream()); inviteInfo.getDeviceId(), inviteInfo.getChannelId(), inviteInfo.getStream());
return; return;
} }
@ -165,7 +163,7 @@ public class InviteStreamServiceImpl implements IInviteStreamService {
return null; return null;
} }
if (scanResult.size() != 1) { if (scanResult.size() != 1) {
logger.warn("[获取InviteInfo] 发现 key: {}存在多条", key); log.warn("[获取InviteInfo] 发现 key: {}存在多条", key);
} }
return (InviteInfo) redisTemplate.opsForValue().get(scanResult.get(0)); return (InviteInfo) redisTemplate.opsForValue().get(scanResult.get(0));

View File

@ -13,18 +13,20 @@ import com.genersoft.iot.vmp.gb28181.transmit.cmd.ISIPCommanderForPlatform;
import com.genersoft.iot.vmp.media.bean.MediaServer; import com.genersoft.iot.vmp.media.bean.MediaServer;
import com.genersoft.iot.vmp.media.bean.ResultForOnPublish; import com.genersoft.iot.vmp.media.bean.ResultForOnPublish;
import com.genersoft.iot.vmp.media.zlm.dto.StreamAuthorityInfo; import com.genersoft.iot.vmp.media.zlm.dto.StreamAuthorityInfo;
import com.genersoft.iot.vmp.streamProxy.bean.StreamProxy; import com.genersoft.iot.vmp.service.IDeviceService;
import com.genersoft.iot.vmp.service.*; import com.genersoft.iot.vmp.service.IInviteStreamService;
import com.genersoft.iot.vmp.service.IMediaService;
import com.genersoft.iot.vmp.service.IUserService;
import com.genersoft.iot.vmp.storager.IRedisCatchStorage; import com.genersoft.iot.vmp.storager.IRedisCatchStorage;
import com.genersoft.iot.vmp.storager.IVideoManagerStorage; import com.genersoft.iot.vmp.storager.IVideoManagerStorage;
import com.genersoft.iot.vmp.streamProxy.bean.StreamProxy;
import com.genersoft.iot.vmp.streamProxy.service.IStreamProxyService; import com.genersoft.iot.vmp.streamProxy.service.IStreamProxyService;
import com.genersoft.iot.vmp.utils.DateUtil; import com.genersoft.iot.vmp.utils.DateUtil;
import com.genersoft.iot.vmp.utils.MediaServerUtils; import com.genersoft.iot.vmp.utils.MediaServerUtils;
import com.genersoft.iot.vmp.vmanager.bean.ErrorCode; import com.genersoft.iot.vmp.vmanager.bean.ErrorCode;
import com.genersoft.iot.vmp.vmanager.bean.OtherPsSendInfo; import com.genersoft.iot.vmp.vmanager.bean.OtherPsSendInfo;
import com.genersoft.iot.vmp.vmanager.bean.OtherRtpSendInfo; import com.genersoft.iot.vmp.vmanager.bean.OtherRtpSendInfo;
import org.slf4j.Logger; import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@ -35,11 +37,10 @@ import java.text.ParseException;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@Slf4j
@Service @Service
public class MediaServiceImpl implements IMediaService { public class MediaServiceImpl implements IMediaService {
private final static Logger logger = LoggerFactory.getLogger(MediaServiceImpl.class);
@Autowired @Autowired
private IRedisCatchStorage redisCatchStorage; private IRedisCatchStorage redisCatchStorage;
@ -104,13 +105,13 @@ public class MediaServiceImpl implements IMediaService {
Map<String, String> paramMap = MediaServerUtils.urlParamToMap(params); Map<String, String> paramMap = MediaServerUtils.urlParamToMap(params);
// 推流鉴权 // 推流鉴权
if (params == null) { if (params == null) {
logger.info("推流鉴权失败: 缺少必要参数sign=md5(user表的pushKey)"); log.info("推流鉴权失败: 缺少必要参数sign=md5(user表的pushKey)");
throw new ControllerException(ErrorCode.ERROR401.getCode(), "Unauthorized"); throw new ControllerException(ErrorCode.ERROR401.getCode(), "Unauthorized");
} }
String sign = paramMap.get("sign"); String sign = paramMap.get("sign");
if (sign == null) { if (sign == null) {
logger.info("推流鉴权失败: 缺少必要参数sign=md5(user表的pushKey)"); log.info("推流鉴权失败: 缺少必要参数sign=md5(user表的pushKey)");
throw new ControllerException(ErrorCode.ERROR401.getCode(), "Unauthorized"); throw new ControllerException(ErrorCode.ERROR401.getCode(), "Unauthorized");
} }
// 推流自定义播放鉴权码 // 推流自定义播放鉴权码
@ -118,7 +119,7 @@ public class MediaServiceImpl implements IMediaService {
// 鉴权配置 // 鉴权配置
boolean hasAuthority = userService.checkPushAuthority(callId, sign); boolean hasAuthority = userService.checkPushAuthority(callId, sign);
if (!hasAuthority) { if (!hasAuthority) {
logger.info("推流鉴权失败: sign 无权限: callId={}. sign={}", callId, sign); log.info("推流鉴权失败: sign 无权限: callId={}. sign={}", callId, sign);
throw new ControllerException(ErrorCode.ERROR401.getCode(), "Unauthorized"); throw new ControllerException(ErrorCode.ERROR401.getCode(), "Unauthorized");
} }
StreamAuthorityInfo streamAuthorityInfo = StreamAuthorityInfo.getInstanceByHook(app, stream, mediaServer.getId()); StreamAuthorityInfo streamAuthorityInfo = StreamAuthorityInfo.getInstanceByHook(app, stream, mediaServer.getId());
@ -150,7 +151,7 @@ public class MediaServiceImpl implements IMediaService {
inviteInfo = inviteStreamService.getInviteInfoBySSRC(ssrc); inviteInfo = inviteStreamService.getInviteInfoBySSRC(ssrc);
if (inviteInfo != null) { if (inviteInfo != null) {
result.setStream_replace(inviteInfo.getStream()); result.setStream_replace(inviteInfo.getStream());
logger.info("[ZLM HOOK]推流鉴权 stream: {} 替换为 {}", stream, inviteInfo.getStream()); log.info("[ZLM HOOK]推流鉴权 stream: {} 替换为 {}", stream, inviteInfo.getStream());
stream = inviteInfo.getStream(); stream = inviteInfo.getStream();
} }
} }
@ -234,7 +235,7 @@ public class MediaServiceImpl implements IMediaService {
try { try {
commanderForPlatform.streamByeCmd(parentPlatform, sendRtpItem.getCallId()); commanderForPlatform.streamByeCmd(parentPlatform, sendRtpItem.getCallId());
} catch (SipException | InvalidArgumentException | ParseException e) { } catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] 国标级联 发送BYE: {}", e.getMessage()); log.error("[命令发送失败] 国标级联 发送BYE: {}", e.getMessage());
} }
redisCatchStorage.deleteSendRTPServer(parentPlatform.getServerGBId(), sendRtpItem.getChannelId(), redisCatchStorage.deleteSendRTPServer(parentPlatform.getServerGBId(), sendRtpItem.getChannelId(),
sendRtpItem.getCallId(), sendRtpItem.getStream()); sendRtpItem.getCallId(), sendRtpItem.getStream());
@ -254,14 +255,14 @@ public class MediaServiceImpl implements IMediaService {
commander.streamByeCmd(device, inviteInfo.getChannelId(), commander.streamByeCmd(device, inviteInfo.getChannelId(),
inviteInfo.getStream(), null); inviteInfo.getStream(), null);
} else { } else {
logger.info("[无人观看] 未找到设备的点播信息: {} 流:{}", inviteInfo.getDeviceId(), stream); log.info("[无人观看] 未找到设备的点播信息: {} 流:{}", inviteInfo.getDeviceId(), stream);
} }
} catch (InvalidArgumentException | ParseException | SipException | } catch (InvalidArgumentException | ParseException | SipException |
SsrcTransactionNotFoundException e) { SsrcTransactionNotFoundException e) {
logger.error("[无人观看]点播, 发送BYE失败 {}", e.getMessage()); log.error("[无人观看]点播, 发送BYE失败 {}", e.getMessage());
} }
} else { } else {
logger.info("[无人观看] 未找到设备: {},流:{}", inviteInfo.getDeviceId(), stream); log.info("[无人观看] 未找到设备: {},流:{}", inviteInfo.getDeviceId(), stream);
} }
inviteStreamService.removeInviteInfo(inviteInfo.getType(), inviteInfo.getDeviceId(), inviteStreamService.removeInviteInfo(inviteInfo.getType(), inviteInfo.getDeviceId(),
@ -284,7 +285,7 @@ public class MediaServiceImpl implements IMediaService {
// 无人观看自动移除 // 无人观看自动移除
result = true; result = true;
streamProxyService.del(app, stream); streamProxyService.del(app, stream);
logger.info("[{}/{}]<-[{}] 拉流代理无人观看已经移除", app, stream, streamProxy.getSrcUrl()); log.info("[{}/{}]<-[{}] 拉流代理无人观看已经移除", app, stream, streamProxy.getSrcUrl());
} else if (streamProxy.isEnableDisableNoneReader()) { } else if (streamProxy.isEnableDisableNoneReader()) {
// 无人观看停用 // 无人观看停用
result = true; result = true;

View File

@ -6,8 +6,7 @@ import com.genersoft.iot.vmp.gb28181.bean.MobilePosition;
import com.genersoft.iot.vmp.service.IMobilePositionService; import com.genersoft.iot.vmp.service.IMobilePositionService;
import com.genersoft.iot.vmp.storager.dao.DeviceChannelMapper; import com.genersoft.iot.vmp.storager.dao.DeviceChannelMapper;
import com.genersoft.iot.vmp.storager.dao.DeviceMobilePositionMapper; import com.genersoft.iot.vmp.storager.dao.DeviceMobilePositionMapper;
import org.slf4j.Logger; import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.annotation.Scheduled;
@ -19,7 +18,7 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@Slf4j
@Service @Service
public class MobilePositionServiceImpl implements IMobilePositionService { public class MobilePositionServiceImpl implements IMobilePositionService {
@ -35,8 +34,6 @@ public class MobilePositionServiceImpl implements IMobilePositionService {
@Autowired @Autowired
private RedisTemplate<String, MobilePosition> redisTemplate; private RedisTemplate<String, MobilePosition> redisTemplate;
private final static Logger logger = LoggerFactory.getLogger(MobilePositionServiceImpl.class);
private final String REDIS_MOBILE_POSITION_LIST = "redis_mobile_position_list"; private final String REDIS_MOBILE_POSITION_LIST = "redis_mobile_position_list";
@Override @Override
@ -78,7 +75,7 @@ public class MobilePositionServiceImpl implements IMobilePositionService {
if (userSetting.getSavePositionHistory()) { if (userSetting.getSavePositionHistory()) {
mobilePositionMapper.batchadd(mobilePositions); mobilePositionMapper.batchadd(mobilePositions);
} }
logger.info("[移动位置订阅]更新通道位置: {}", mobilePositions.size()); log.info("[移动位置订阅]更新通道位置: {}", mobilePositions.size());
Map<String, DeviceChannel> updateChannelMap = new HashMap<>(); Map<String, DeviceChannel> updateChannelMap = new HashMap<>();
for (MobilePosition mobilePosition : mobilePositions) { for (MobilePosition mobilePosition : mobilePositions) {
DeviceChannel deviceChannel = new DeviceChannel(); DeviceChannel deviceChannel = new DeviceChannel();

View File

@ -10,8 +10,7 @@ import com.genersoft.iot.vmp.storager.dao.ParentPlatformMapper;
import com.genersoft.iot.vmp.storager.dao.PlatformCatalogMapper; import com.genersoft.iot.vmp.storager.dao.PlatformCatalogMapper;
import com.genersoft.iot.vmp.storager.dao.PlatformChannelMapper; import com.genersoft.iot.vmp.storager.dao.PlatformChannelMapper;
import com.genersoft.iot.vmp.vmanager.gb28181.platform.bean.ChannelReduce; import com.genersoft.iot.vmp.vmanager.gb28181.platform.bean.ChannelReduce;
import org.slf4j.Logger; import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@ -27,12 +26,11 @@ import java.util.Map;
/** /**
* @author lin * @author lin
*/ */
@Slf4j
@Service @Service
@DS("master") @DS("master")
public class PlatformChannelServiceImpl implements IPlatformChannelService { public class PlatformChannelServiceImpl implements IPlatformChannelService {
private final static Logger logger = LoggerFactory.getLogger(PlatformChannelServiceImpl.class);
@Autowired @Autowired
private PlatformChannelMapper platformChannelMapper; private PlatformChannelMapper platformChannelMapper;
@ -62,7 +60,7 @@ public class PlatformChannelServiceImpl implements IPlatformChannelService {
public int updateChannelForGB(String platformId, List<ChannelReduce> channelReduces, String catalogId) { public int updateChannelForGB(String platformId, List<ChannelReduce> channelReduces, String catalogId) {
ParentPlatform platform = platformMapper.getParentPlatByServerGBId(platformId); ParentPlatform platform = platformMapper.getParentPlatByServerGBId(platformId);
if (platform == null) { if (platform == null) {
logger.warn("更新级联通道信息时未找到平台{}的信息", platformId); log.warn("更新级联通道信息时未找到平台{}的信息", platformId);
return 0; return 0;
} }
Map<Integer, ChannelReduce> deviceAndChannels = new HashMap<>(); Map<Integer, ChannelReduce> deviceAndChannels = new HashMap<>();
@ -95,12 +93,12 @@ public class PlatformChannelServiceImpl implements IPlatformChannelService {
int count = platformChannelMapper.addChannels(platformId, channelReducesToAdd.subList(i, toIndex)); int count = platformChannelMapper.addChannels(platformId, channelReducesToAdd.subList(i, toIndex));
result = result || count < 0; result = result || count < 0;
allCount += count; allCount += count;
logger.info("[关联通道]国标通道 平台:{}, 共需关联通道数:{}, 已关联:{}", platformId, channelReducesToAdd.size(), toIndex); log.info("[关联通道]国标通道 平台:{}, 共需关联通道数:{}, 已关联:{}", platformId, channelReducesToAdd.size(), toIndex);
} }
}else { }else {
allCount = platformChannelMapper.addChannels(platformId, channelReducesToAdd); allCount = platformChannelMapper.addChannels(platformId, channelReducesToAdd);
result = result || allCount < 0; result = result || allCount < 0;
logger.info("[关联通道]国标通道 平台:{}, 关联通道数:{}", platformId, channelReducesToAdd.size()); log.info("[关联通道]国标通道 平台:{}, 关联通道数:{}", platformId, channelReducesToAdd.size());
} }
if (result) { if (result) {
@ -108,7 +106,7 @@ public class PlatformChannelServiceImpl implements IPlatformChannelService {
dataSourceTransactionManager.rollback(transactionStatus); dataSourceTransactionManager.rollback(transactionStatus);
allCount = 0; allCount = 0;
}else { }else {
logger.info("[关联通道]国标通道 平台:{}, 正在存入数据库", platformId); log.info("[关联通道]国标通道 平台:{}, 正在存入数据库", platformId);
dataSourceTransactionManager.commit(transactionStatus); dataSourceTransactionManager.commit(transactionStatus);
} }
@ -119,7 +117,7 @@ public class PlatformChannelServiceImpl implements IPlatformChannelService {
eventPublisher.catalogEventPublish(platformId, deviceChannelList, CatalogEvent.ADD); eventPublisher.catalogEventPublish(platformId, deviceChannelList, CatalogEvent.ADD);
} }
} }
logger.info("[关联通道]国标通道 平台:{}, 存入数据库成功", platformId); log.info("[关联通道]国标通道 平台:{}, 存入数据库成功", platformId);
} }
return allCount; return allCount;
} }
@ -137,7 +135,7 @@ public class PlatformChannelServiceImpl implements IPlatformChannelService {
} }
return deviceChannelList; return deviceChannelList;
} else if (catalog == null && !catalogId.equals(platform.getDeviceGBId())) { } else if (catalog == null && !catalogId.equals(platform.getDeviceGBId())) {
logger.warn("未查询到目录{}的信息", catalogId); log.warn("未查询到目录{}的信息", catalogId);
return null; return null;
} }
for (ChannelReduce channelReduce : channelReduces) { for (ChannelReduce channelReduce : channelReduces) {

View File

@ -30,8 +30,7 @@ import com.genersoft.iot.vmp.utils.DateUtil;
import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo; import com.github.pagehelper.PageInfo;
import gov.nist.javax.sip.message.SIPResponse; import gov.nist.javax.sip.message.SIPResponse;
import org.slf4j.Logger; import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener; import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.Async;
@ -49,6 +48,7 @@ import java.util.Vector;
/** /**
* @author lin * @author lin
*/ */
@Slf4j
@Service @Service
@DS("master") @DS("master")
public class PlatformServiceImpl implements IPlatformService { public class PlatformServiceImpl implements IPlatformService {
@ -58,8 +58,6 @@ public class PlatformServiceImpl implements IPlatformService {
private final static String REGISTER_FAIL_AGAIN_KEY_PREFIX = "platform_register_fail_again_"; private final static String REGISTER_FAIL_AGAIN_KEY_PREFIX = "platform_register_fail_again_";
private final static String KEEPALIVE_KEY_PREFIX = "platform_keepalive_"; private final static String KEEPALIVE_KEY_PREFIX = "platform_keepalive_";
private final static Logger logger = LoggerFactory.getLogger(PlatformServiceImpl.class);
@Autowired @Autowired
private ParentPlatformMapper platformMapper; private ParentPlatformMapper platformMapper;
@ -117,7 +115,7 @@ public class PlatformServiceImpl implements IPlatformService {
sendRtpItem.getCallId(), sendRtpItem.getStream()); sendRtpItem.getCallId(), sendRtpItem.getStream());
} }
} catch (SipException | InvalidArgumentException | ParseException e) { } catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] 发送BYE: {}", e.getMessage()); log.error("[命令发送失败] 发送BYE: {}", e.getMessage());
} }
} }
} }
@ -139,7 +137,7 @@ public class PlatformServiceImpl implements IPlatformService {
try { try {
commanderForPlatform.streamByeCmd(parentPlatform, sendRtpItem.getCallId()); commanderForPlatform.streamByeCmd(parentPlatform, sendRtpItem.getCallId());
} catch (SipException | InvalidArgumentException | ParseException e) { } catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] 国标级联 发送BYE: {}", e.getMessage()); log.error("[命令发送失败] 国标级联 发送BYE: {}", e.getMessage());
} }
redisCatchStorage.deleteSendRTPServer(parentPlatform.getServerGBId(), sendRtpItem.getChannelId(), redisCatchStorage.deleteSendRTPServer(parentPlatform.getServerGBId(), sendRtpItem.getChannelId(),
sendRtpItem.getCallId(), sendRtpItem.getStream()); sendRtpItem.getCallId(), sendRtpItem.getStream());
@ -184,10 +182,10 @@ public class PlatformServiceImpl implements IPlatformService {
// 注册成功时由程序直接调用了online方法 // 注册成功时由程序直接调用了online方法
try { try {
commanderForPlatform.register(parentPlatform, eventResult -> { commanderForPlatform.register(parentPlatform, eventResult -> {
logger.info("[国标级联] {},添加向上级注册失败,请确定上级平台可用时重新保存", parentPlatform.getServerGBId()); log.info("[国标级联] {},添加向上级注册失败,请确定上级平台可用时重新保存", parentPlatform.getServerGBId());
}, null); }, null);
} catch (InvalidArgumentException | ParseException | SipException e) { } catch (InvalidArgumentException | ParseException | SipException e) {
logger.error("[命令发送失败] 国标级联: {}", e.getMessage()); log.error("[命令发送失败] 国标级联: {}", e.getMessage());
} }
} }
return result > 0; return result > 0;
@ -195,7 +193,7 @@ public class PlatformServiceImpl implements IPlatformService {
@Override @Override
public boolean update(ParentPlatform parentPlatform) { public boolean update(ParentPlatform parentPlatform) {
logger.info("[国标级联]更新平台 {}", parentPlatform.getDeviceGBId()); log.info("[国标级联]更新平台 {}", parentPlatform.getDeviceGBId());
parentPlatform.setCharacterSet(parentPlatform.getCharacterSet().toUpperCase()); parentPlatform.setCharacterSet(parentPlatform.getCharacterSet().toUpperCase());
ParentPlatform parentPlatformOld = platformMapper.getParentPlatById(parentPlatform.getId()); ParentPlatform parentPlatformOld = platformMapper.getParentPlatById(parentPlatform.getId());
ParentPlatformCatch parentPlatformCatchOld = redisCatchStorage.queryPlatformCatchInfo(parentPlatformOld.getServerGBId()); ParentPlatformCatch parentPlatformCatchOld = redisCatchStorage.queryPlatformCatchInfo(parentPlatformOld.getServerGBId());
@ -210,13 +208,13 @@ public class PlatformServiceImpl implements IPlatformService {
// 注销旧的 // 注销旧的
try { try {
if (parentPlatformOld.isStatus() && parentPlatformCatchOld != null) { if (parentPlatformOld.isStatus() && parentPlatformCatchOld != null) {
logger.info("保存平台{}时发现旧平台在线,发送注销命令", parentPlatformOld.getServerGBId()); log.info("保存平台{}时发现旧平台在线,发送注销命令", parentPlatformOld.getServerGBId());
commanderForPlatform.unregister(parentPlatformOld, parentPlatformCatchOld.getSipTransactionInfo(), null, eventResult -> { commanderForPlatform.unregister(parentPlatformOld, parentPlatformCatchOld.getSipTransactionInfo(), null, eventResult -> {
logger.info("[国标级联] 注销成功, 平台:{}", parentPlatformOld.getServerGBId()); log.info("[国标级联] 注销成功, 平台:{}", parentPlatformOld.getServerGBId());
}); });
} }
} catch (InvalidArgumentException | ParseException | SipException e) { } catch (InvalidArgumentException | ParseException | SipException e) {
logger.error("[命令发送失败] 国标级联 注销: {}", e.getMessage()); log.error("[命令发送失败] 国标级联 注销: {}", e.getMessage());
} }
// 更新数据库 // 更新数据库
@ -239,12 +237,12 @@ public class PlatformServiceImpl implements IPlatformService {
// 保存时启用就发送注册 // 保存时启用就发送注册
// 注册成功时由程序直接调用了online方法 // 注册成功时由程序直接调用了online方法
try { try {
logger.info("[国标级联] 平台注册 {}", parentPlatform.getDeviceGBId()); log.info("[国标级联] 平台注册 {}", parentPlatform.getDeviceGBId());
commanderForPlatform.register(parentPlatform, eventResult -> { commanderForPlatform.register(parentPlatform, eventResult -> {
logger.info("[国标级联] {},添加向上级注册失败,请确定上级平台可用时重新保存", parentPlatform.getServerGBId()); log.info("[国标级联] {},添加向上级注册失败,请确定上级平台可用时重新保存", parentPlatform.getServerGBId());
}, null); }, null);
} catch (InvalidArgumentException | ParseException | SipException e) { } catch (InvalidArgumentException | ParseException | SipException e) {
logger.error("[命令发送失败] 国标级联: {}", e.getMessage()); log.error("[命令发送失败] 国标级联: {}", e.getMessage());
} }
} }
@ -255,7 +253,7 @@ public class PlatformServiceImpl implements IPlatformService {
@Override @Override
public void online(ParentPlatform parentPlatform, SipTransactionInfo sipTransactionInfo) { public void online(ParentPlatform parentPlatform, SipTransactionInfo sipTransactionInfo) {
logger.info("[国标级联]{}, 平台上线", parentPlatform.getServerGBId()); log.info("[国标级联]{}, 平台上线", parentPlatform.getServerGBId());
final String registerFailAgainTaskKey = REGISTER_FAIL_AGAIN_KEY_PREFIX + parentPlatform.getServerGBId(); final String registerFailAgainTaskKey = REGISTER_FAIL_AGAIN_KEY_PREFIX + parentPlatform.getServerGBId();
dynamicTask.stop(registerFailAgainTaskKey); dynamicTask.stop(registerFailAgainTaskKey);
@ -275,7 +273,7 @@ public class PlatformServiceImpl implements IPlatformService {
final String registerTaskKey = REGISTER_KEY_PREFIX + parentPlatform.getServerGBId(); final String registerTaskKey = REGISTER_KEY_PREFIX + parentPlatform.getServerGBId();
if (!dynamicTask.isAlive(registerTaskKey)) { if (!dynamicTask.isAlive(registerTaskKey)) {
logger.info("[国标级联]{}, 添加定时注册任务", parentPlatform.getServerGBId()); log.info("[国标级联]{}, 添加定时注册任务", parentPlatform.getServerGBId());
// 添加注册任务 // 添加注册任务
dynamicTask.startCron(registerTaskKey, dynamicTask.startCron(registerTaskKey,
// 注册失败注册成功时由程序直接调用了online方法 // 注册失败注册成功时由程序直接调用了online方法
@ -286,7 +284,7 @@ public class PlatformServiceImpl implements IPlatformService {
final String keepaliveTaskKey = KEEPALIVE_KEY_PREFIX + parentPlatform.getServerGBId(); final String keepaliveTaskKey = KEEPALIVE_KEY_PREFIX + parentPlatform.getServerGBId();
if (!dynamicTask.contains(keepaliveTaskKey)) { if (!dynamicTask.contains(keepaliveTaskKey)) {
logger.info("[国标级联]{}, 添加定时心跳任务", parentPlatform.getServerGBId()); log.info("[国标级联]{}, 添加定时心跳任务", parentPlatform.getServerGBId());
// 添加心跳任务 // 添加心跳任务
dynamicTask.startCron(keepaliveTaskKey, dynamicTask.startCron(keepaliveTaskKey,
()-> { ()-> {
@ -294,14 +292,14 @@ public class PlatformServiceImpl implements IPlatformService {
commanderForPlatform.keepalive(parentPlatform, eventResult -> { commanderForPlatform.keepalive(parentPlatform, eventResult -> {
// 心跳失败 // 心跳失败
if (eventResult.type != SipSubscribe.EventResultType.timeout) { if (eventResult.type != SipSubscribe.EventResultType.timeout) {
logger.warn("[国标级联]发送心跳收到错误code {}, msg: {}", eventResult.statusCode, eventResult.msg); log.warn("[国标级联]发送心跳收到错误code {}, msg: {}", eventResult.statusCode, eventResult.msg);
} }
// 心跳失败 // 心跳失败
ParentPlatformCatch platformCatch = redisCatchStorage.queryPlatformCatchInfo(parentPlatform.getServerGBId()); ParentPlatformCatch platformCatch = redisCatchStorage.queryPlatformCatchInfo(parentPlatform.getServerGBId());
// 此时是第三次心跳超时 平台离线 // 此时是第三次心跳超时 平台离线
if (platformCatch.getKeepAliveReply() == 2) { if (platformCatch.getKeepAliveReply() == 2) {
// 设置平台离线并重新注册 // 设置平台离线并重新注册
logger.info("[国标级联] 三次心跳失败, 平台{}({})离线", parentPlatform.getName(), parentPlatform.getServerGBId()); log.info("[国标级联] 三次心跳失败, 平台{}({})离线", parentPlatform.getName(), parentPlatform.getServerGBId());
offline(parentPlatform, false); offline(parentPlatform, false);
}else { }else {
platformCatch.setKeepAliveReply(platformCatch.getKeepAliveReply() + 1); platformCatch.setKeepAliveReply(platformCatch.getKeepAliveReply() + 1);
@ -316,17 +314,17 @@ public class PlatformServiceImpl implements IPlatformService {
platformCatch.setKeepAliveReply(0); platformCatch.setKeepAliveReply(0);
redisCatchStorage.updatePlatformCatchInfo(platformCatch); redisCatchStorage.updatePlatformCatchInfo(platformCatch);
} }
logger.info("[发送心跳] 国标级联 发送心跳, code {}, msg: {}", eventResult.statusCode, eventResult.msg); log.info("[发送心跳] 国标级联 发送心跳, code {}, msg: {}", eventResult.statusCode, eventResult.msg);
}); });
} catch (SipException | InvalidArgumentException | ParseException e) { } catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] 国标级联 发送心跳: {}", e.getMessage()); log.error("[命令发送失败] 国标级联 发送心跳: {}", e.getMessage());
} }
}, },
(parentPlatform.getKeepTimeout())*1000); (parentPlatform.getKeepTimeout())*1000);
} }
if (parentPlatform.isAutoPushChannel()) { if (parentPlatform.isAutoPushChannel()) {
if (subscribeHolder.getCatalogSubscribe(parentPlatform.getServerGBId()) == null) { if (subscribeHolder.getCatalogSubscribe(parentPlatform.getServerGBId()) == null) {
logger.info("[国标级联]{}, 添加自动通道推送模拟订阅信息", parentPlatform.getServerGBId()); log.info("[国标级联]{}, 添加自动通道推送模拟订阅信息", parentPlatform.getServerGBId());
addSimulatedSubscribeInfo(parentPlatform); addSimulatedSubscribeInfo(parentPlatform);
} }
}else { }else {
@ -360,24 +358,24 @@ public class PlatformServiceImpl implements IPlatformService {
} }
if (sipTransactionInfo == null) { if (sipTransactionInfo == null) {
logger.info("[国标级联] 平台:{}注册即将到期,开始重新注册", parentPlatform.getServerGBId()); log.info("[国标级联] 平台:{}注册即将到期,开始重新注册", parentPlatform.getServerGBId());
}else { }else {
logger.info("[国标级联] 平台:{}注册即将到期,开始续订", parentPlatform.getServerGBId()); log.info("[国标级联] 平台:{}注册即将到期,开始续订", parentPlatform.getServerGBId());
} }
commanderForPlatform.register(parentPlatform, sipTransactionInfo, eventResult -> { commanderForPlatform.register(parentPlatform, sipTransactionInfo, eventResult -> {
logger.info("[国标级联] 平台:{}注册失败,{}:{}", parentPlatform.getServerGBId(), log.info("[国标级联] 平台:{}注册失败,{}:{}", parentPlatform.getServerGBId(),
eventResult.statusCode, eventResult.msg); eventResult.statusCode, eventResult.msg);
offline(parentPlatform, false); offline(parentPlatform, false);
}, null); }, null);
} catch (Exception e) { } catch (Exception e) {
logger.error("[命令发送失败] 国标级联定时注册: {}", e.getMessage()); log.error("[命令发送失败] 国标级联定时注册: {}", e.getMessage());
} }
} }
@Override @Override
public void offline(ParentPlatform parentPlatform, boolean stopRegister) { public void offline(ParentPlatform parentPlatform, boolean stopRegister) {
logger.info("[平台离线]{}", parentPlatform.getServerGBId()); log.info("[平台离线]{}", parentPlatform.getServerGBId());
ParentPlatformCatch parentPlatformCatch = redisCatchStorage.queryPlatformCatchInfo(parentPlatform.getServerGBId()); ParentPlatformCatch parentPlatformCatch = redisCatchStorage.queryPlatformCatchInfo(parentPlatform.getServerGBId());
parentPlatformCatch.setKeepAliveReply(0); parentPlatformCatch.setKeepAliveReply(0);
parentPlatformCatch.setRegisterAliveReply(0); parentPlatformCatch.setRegisterAliveReply(0);
@ -388,17 +386,17 @@ public class PlatformServiceImpl implements IPlatformService {
platformMapper.updateParentPlatformStatus(parentPlatform.getServerGBId(), false); platformMapper.updateParentPlatformStatus(parentPlatform.getServerGBId(), false);
// 停止所有推流 // 停止所有推流
logger.info("[平台离线] {}, 停止所有推流", parentPlatform.getServerGBId()); log.info("[平台离线] {}, 停止所有推流", parentPlatform.getServerGBId());
stopAllPush(parentPlatform.getServerGBId()); stopAllPush(parentPlatform.getServerGBId());
// 清除注册定时 // 清除注册定时
logger.info("[平台离线] {}, 停止定时注册任务", parentPlatform.getServerGBId()); log.info("[平台离线] {}, 停止定时注册任务", parentPlatform.getServerGBId());
final String registerTaskKey = REGISTER_KEY_PREFIX + parentPlatform.getServerGBId(); final String registerTaskKey = REGISTER_KEY_PREFIX + parentPlatform.getServerGBId();
if (dynamicTask.contains(registerTaskKey)) { if (dynamicTask.contains(registerTaskKey)) {
dynamicTask.stop(registerTaskKey); dynamicTask.stop(registerTaskKey);
} }
// 清除心跳定时 // 清除心跳定时
logger.info("[平台离线] {}, 停止定时发送心跳任务", parentPlatform.getServerGBId()); log.info("[平台离线] {}, 停止定时发送心跳任务", parentPlatform.getServerGBId());
final String keepaliveTaskKey = KEEPALIVE_KEY_PREFIX + parentPlatform.getServerGBId(); final String keepaliveTaskKey = KEEPALIVE_KEY_PREFIX + parentPlatform.getServerGBId();
if (dynamicTask.contains(keepaliveTaskKey)) { if (dynamicTask.contains(keepaliveTaskKey)) {
// 清除心跳任务 // 清除心跳任务
@ -408,11 +406,11 @@ public class PlatformServiceImpl implements IPlatformService {
SubscribeInfo catalogSubscribe = subscribeHolder.getCatalogSubscribe(parentPlatform.getServerGBId()); SubscribeInfo catalogSubscribe = subscribeHolder.getCatalogSubscribe(parentPlatform.getServerGBId());
if (catalogSubscribe != null) { if (catalogSubscribe != null) {
if (catalogSubscribe.getExpires() > 0) { if (catalogSubscribe.getExpires() > 0) {
logger.info("[平台离线] {}, 停止目录订阅回复", parentPlatform.getServerGBId()); log.info("[平台离线] {}, 停止目录订阅回复", parentPlatform.getServerGBId());
subscribeHolder.removeCatalogSubscribe(parentPlatform.getServerGBId()); subscribeHolder.removeCatalogSubscribe(parentPlatform.getServerGBId());
} }
} }
logger.info("[平台离线] {}, 停止移动位置订阅回复", parentPlatform.getServerGBId()); log.info("[平台离线] {}, 停止移动位置订阅回复", parentPlatform.getServerGBId());
subscribeHolder.removeMobilePositionSubscribe(parentPlatform.getServerGBId()); subscribeHolder.removeMobilePositionSubscribe(parentPlatform.getServerGBId());
// 发起定时自动重新注册 // 发起定时自动重新注册
if (!stopRegister) { if (!stopRegister) {
@ -444,15 +442,15 @@ public class PlatformServiceImpl implements IPlatformService {
final String registerTaskKey = REGISTER_KEY_PREFIX + parentPlatform.getServerGBId(); final String registerTaskKey = REGISTER_KEY_PREFIX + parentPlatform.getServerGBId();
try { try {
commanderForPlatform.register(parentPlatform, eventResult1 -> { commanderForPlatform.register(parentPlatform, eventResult1 -> {
logger.info("[国标级联] {}开始定时发起注册间隔为1分钟", parentPlatform.getServerGBId()); log.info("[国标级联] {}开始定时发起注册间隔为1分钟", parentPlatform.getServerGBId());
// 添加注册任务 // 添加注册任务
dynamicTask.startCron(registerTaskKey, dynamicTask.startCron(registerTaskKey,
// 注册失败注册成功时由程序直接调用了online方法 // 注册失败注册成功时由程序直接调用了online方法
()->logger.info("[国标级联] {},平台离线后持续发起注册,失败", parentPlatform.getServerGBId()), ()-> log.info("[国标级联] {},平台离线后持续发起注册,失败", parentPlatform.getServerGBId()),
60*1000); 60*1000);
}, null); }, null);
} catch (InvalidArgumentException | ParseException | SipException e) { } catch (InvalidArgumentException | ParseException | SipException e) {
logger.error("[命令发送失败] 国标级联注册: {}", e.getMessage()); log.error("[命令发送失败] 国标级联注册: {}", e.getMessage());
} }
} }
@ -484,7 +482,7 @@ public class PlatformServiceImpl implements IPlatformService {
commanderForPlatform.sendNotifyMobilePosition(platform, gpsMsgInfo, subscribe); commanderForPlatform.sendNotifyMobilePosition(platform, gpsMsgInfo, subscribe);
} catch (InvalidArgumentException | ParseException | NoSuchFieldException | SipException | } catch (InvalidArgumentException | ParseException | NoSuchFieldException | SipException |
IllegalAccessException e) { IllegalAccessException e) {
logger.error("[命令发送失败] 国标级联 移动位置通知: {}", e.getMessage()); log.error("[命令发送失败] 国标级联 移动位置通知: {}", e.getMessage());
} }
} }
} }
@ -496,7 +494,7 @@ public class PlatformServiceImpl implements IPlatformService {
SipSubscribe.Event errorEvent, InviteTimeOutCallback timeoutCallback) throws InvalidArgumentException, ParseException, SipException { SipSubscribe.Event errorEvent, InviteTimeOutCallback timeoutCallback) throws InvalidArgumentException, ParseException, SipException {
if (mediaServerItem == null) { if (mediaServerItem == null) {
logger.info("[国标级联] 语音喊话未找到可用的zlm. platform: {}", platform.getServerGBId()); log.info("[国标级联] 语音喊话未找到可用的zlm. platform: {}", platform.getServerGBId());
return; return;
} }
InviteInfo inviteInfoForOld = inviteStreamService.getInviteInfoByDeviceAndChannel(InviteSessionType.PLAY, platform.getServerGBId(), channelId); InviteInfo inviteInfoForOld = inviteStreamService.getInviteInfoByDeviceAndChannel(InviteSessionType.PLAY, platform.getServerGBId(), channelId);
@ -537,7 +535,7 @@ public class PlatformServiceImpl implements IPlatformService {
} }
SSRCInfo ssrcInfo = mediaServerService.openRTPServer(mediaServerItem, streamId, null, ssrcCheck, false, null, true, false, false, tcpMode); SSRCInfo ssrcInfo = mediaServerService.openRTPServer(mediaServerItem, streamId, null, ssrcCheck, false, null, true, false, false, tcpMode);
if (ssrcInfo == null || ssrcInfo.getPort() < 0) { if (ssrcInfo == null || ssrcInfo.getPort() < 0) {
logger.info("[国标级联] 发起语音喊话 开启端口监听失败, platform: {}, channel {}", platform.getServerGBId(), channelId); log.info("[国标级联] 发起语音喊话 开启端口监听失败, platform: {}, channel {}", platform.getServerGBId(), channelId);
SipSubscribe.EventResult<Object> eventResult = new SipSubscribe.EventResult<>(); SipSubscribe.EventResult<Object> eventResult = new SipSubscribe.EventResult<>();
eventResult.statusCode = -1; eventResult.statusCode = -1;
eventResult.msg = "端口监听失败"; eventResult.msg = "端口监听失败";
@ -545,7 +543,7 @@ public class PlatformServiceImpl implements IPlatformService {
errorEvent.response(eventResult); errorEvent.response(eventResult);
return; return;
} }
logger.info("[国标级联] 语音喊话发起Invite消息 deviceId: {}, channelId: {},收流端口: {}, 收流模式:{}, SSRC: {}, SSRC校验{}", log.info("[国标级联] 语音喊话发起Invite消息 deviceId: {}, channelId: {},收流端口: {}, 收流模式:{}, SSRC: {}, SSRC校验{}",
platform.getServerGBId(), channelId, ssrcInfo.getPort(), userSetting.getBroadcastForPlatform(), ssrcInfo.getSsrc(), ssrcCheck); platform.getServerGBId(), channelId, ssrcInfo.getPort(), userSetting.getBroadcastForPlatform(), ssrcInfo.getSsrc(), ssrcCheck);
// 初始化redis中的invite消息状态 // 初始化redis中的invite消息状态
@ -558,12 +556,12 @@ public class PlatformServiceImpl implements IPlatformService {
// 执行超时任务时查询是否已经成功成功了则不执行超时任务防止超时任务取消失败的情况 // 执行超时任务时查询是否已经成功成功了则不执行超时任务防止超时任务取消失败的情况
InviteInfo inviteInfoForBroadcast = inviteStreamService.getInviteInfo(InviteSessionType.BROADCAST, platform.getServerGBId(), channelId, null); InviteInfo inviteInfoForBroadcast = inviteStreamService.getInviteInfo(InviteSessionType.BROADCAST, platform.getServerGBId(), channelId, null);
if (inviteInfoForBroadcast == null) { if (inviteInfoForBroadcast == null) {
logger.info("[国标级联] 发起语音喊话 收流超时 deviceId: {}, channelId: {},端口:{}, SSRC: {}", platform.getServerGBId(), channelId, ssrcInfo.getPort(), ssrcInfo.getSsrc()); log.info("[国标级联] 发起语音喊话 收流超时 deviceId: {}, channelId: {},端口:{}, SSRC: {}", platform.getServerGBId(), channelId, ssrcInfo.getPort(), ssrcInfo.getSsrc());
// 点播超时回复BYE 同时释放ssrc以及此次点播的资源 // 点播超时回复BYE 同时释放ssrc以及此次点播的资源
try { try {
commanderForPlatform.streamByeCmd(platform, channelId, ssrcInfo.getStream(), null, null); commanderForPlatform.streamByeCmd(platform, channelId, ssrcInfo.getStream(), null, null);
} catch (InvalidArgumentException | ParseException | SipException | SsrcTransactionNotFoundException e) { } catch (InvalidArgumentException | ParseException | SipException | SsrcTransactionNotFoundException e) {
logger.error("[点播超时] 发送BYE失败 {}", e.getMessage()); log.error("[点播超时] 发送BYE失败 {}", e.getMessage());
} finally { } finally {
timeoutCallback.run(1, "收流超时"); timeoutCallback.run(1, "收流超时");
mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc()); mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
@ -574,7 +572,7 @@ public class PlatformServiceImpl implements IPlatformService {
} }
}, userSetting.getPlayTimeout()); }, userSetting.getPlayTimeout());
commanderForPlatform.broadcastInviteCmd(platform, channelId, mediaServerItem, ssrcInfo, (hookData)->{ commanderForPlatform.broadcastInviteCmd(platform, channelId, mediaServerItem, ssrcInfo, (hookData)->{
logger.info("[国标级联] 发起语音喊话 收到上级推流 deviceId: {}, channelId: {}", platform.getServerGBId(), channelId); log.info("[国标级联] 发起语音喊话 收到上级推流 deviceId: {}, channelId: {}", platform.getServerGBId(), channelId);
dynamicTask.stop(timeOutTaskKey); dynamicTask.stop(timeOutTaskKey);
// hook响应 // hook响应
playService.onPublishHandlerForPlay(hookData.getMediaServer(), hookData.getMediaInfo(), platform.getServerGBId(), channelId); playService.onPublishHandlerForPlay(hookData.getMediaServer(), hookData.getMediaInfo(), platform.getServerGBId(), channelId);
@ -656,27 +654,27 @@ public class PlatformServiceImpl implements IPlatformService {
}else { }else {
// 单端口 // 单端口
if (tcpMode == 2) { if (tcpMode == 2) {
logger.warn("[Invite 200OK] 单端口收流模式不支持tcp主动模式收流"); log.warn("[Invite 200OK] 单端口收流模式不支持tcp主动模式收流");
} }
} }
}else { }else {
logger.info("[Invite 200OK] 收到invite 200, 发现下级自定义了ssrc: {}", ssrcInResponse); log.info("[Invite 200OK] 收到invite 200, 发现下级自定义了ssrc: {}", ssrcInResponse);
// ssrc 不一致 // ssrc 不一致
if (mediaServerItem.isRtpEnable()) { if (mediaServerItem.isRtpEnable()) {
// 多端口 // 多端口
if (ssrcCheck) { if (ssrcCheck) {
// ssrc检验 // ssrc检验
// 更新ssrc // 更新ssrc
logger.info("[Invite 200OK] SSRC修正 {}->{}", ssrcInfo.getSsrc(), ssrcInResponse); log.info("[Invite 200OK] SSRC修正 {}->{}", ssrcInfo.getSsrc(), ssrcInResponse);
// 释放ssrc // 释放ssrc
mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc()); mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
Boolean result = mediaServerService.updateRtpServerSSRC(mediaServerItem, ssrcInfo.getStream(), ssrcInResponse); Boolean result = mediaServerService.updateRtpServerSSRC(mediaServerItem, ssrcInfo.getStream(), ssrcInResponse);
if (!result) { if (!result) {
try { try {
logger.warn("[Invite 200OK] 更新ssrc失败停止喊话 {}/{}", platform.getServerGBId(), channelId); log.warn("[Invite 200OK] 更新ssrc失败停止喊话 {}/{}", platform.getServerGBId(), channelId);
commanderForPlatform.streamByeCmd(platform, channelId, ssrcInfo.getStream(), null, null); commanderForPlatform.streamByeCmd(platform, channelId, ssrcInfo.getStream(), null, null);
} catch (InvalidArgumentException | SipException | ParseException | SsrcTransactionNotFoundException e) { } catch (InvalidArgumentException | SipException | ParseException | SsrcTransactionNotFoundException e) {
logger.error("[命令发送失败] 停止播放, 发送BYE: {}", e.getMessage()); log.error("[命令发送失败] 停止播放, 发送BYE: {}", e.getMessage());
} }
dynamicTask.stop(timeOutTaskKey); dynamicTask.stop(timeOutTaskKey);
@ -700,7 +698,7 @@ public class PlatformServiceImpl implements IPlatformService {
tcpActiveHandler(platform, channelId, contentString, mediaServerItem, tcpMode, ssrcCheck, tcpActiveHandler(platform, channelId, contentString, mediaServerItem, tcpMode, ssrcCheck,
timeOutTaskKey, ssrcInfo, callback); timeOutTaskKey, ssrcInfo, callback);
}else { }else {
logger.warn("[Invite 200OK] 单端口收流模式不支持tcp主动模式收流"); log.warn("[Invite 200OK] 单端口收流模式不支持tcp主动模式收流");
} }
} }
inviteStreamService.updateInviteInfo(inviteInfo); inviteStreamService.updateInviteInfo(inviteInfo);
@ -714,7 +712,7 @@ public class PlatformServiceImpl implements IPlatformService {
tcpActiveHandler(platform, channelId, contentString, mediaServerItem, tcpMode, ssrcCheck, tcpActiveHandler(platform, channelId, contentString, mediaServerItem, tcpMode, ssrcCheck,
timeOutTaskKey, ssrcInfo, callback); timeOutTaskKey, ssrcInfo, callback);
}else { }else {
logger.warn("[Invite 200OK] 单端口收流模式不支持tcp主动模式收流"); log.warn("[Invite 200OK] 单端口收流模式不支持tcp主动模式收流");
} }
} }
inviteStreamService.updateInviteInfo(inviteInfo); inviteStreamService.updateInviteInfo(inviteInfo);
@ -763,12 +761,12 @@ public class PlatformServiceImpl implements IPlatformService {
break; break;
} }
} }
logger.info("[TCP主动连接对方] serverGbId: {}, channelId: {}, 连接对方的地址:{}:{}, SSRC: {}, SSRC校验{}", log.info("[TCP主动连接对方] serverGbId: {}, channelId: {}, 连接对方的地址:{}:{}, SSRC: {}, SSRC校验{}",
platform.getServerGBId(), channelId, sdp.getConnection().getAddress(), port, ssrcInfo.getSsrc(), ssrcCheck); platform.getServerGBId(), channelId, sdp.getConnection().getAddress(), port, ssrcInfo.getSsrc(), ssrcCheck);
Boolean result = mediaServerService.connectRtpServer(mediaServerItem, sdp.getConnection().getAddress(), port, ssrcInfo.getStream()); Boolean result = mediaServerService.connectRtpServer(mediaServerItem, sdp.getConnection().getAddress(), port, ssrcInfo.getStream());
logger.info("[TCP主动连接对方] 结果: {}", result); log.info("[TCP主动连接对方] 结果: {}", result);
} catch (SdpException e) { } catch (SdpException e) {
logger.error("[TCP主动连接对方] serverGbId: {}, channelId: {}, 解析200OK的SDP信息失败", platform.getServerGBId(), channelId, e); log.error("[TCP主动连接对方] serverGbId: {}, channelId: {}, 解析200OK的SDP信息失败", platform.getServerGBId(), channelId, e);
dynamicTask.stop(timeOutTaskKey); dynamicTask.stop(timeOutTaskKey);
mediaServerService.closeRTPServer(mediaServerItem, ssrcInfo.getStream()); mediaServerService.closeRTPServer(mediaServerItem, ssrcInfo.getStream());
// 释放ssrc // 释放ssrc
@ -792,7 +790,7 @@ public class PlatformServiceImpl implements IPlatformService {
commanderForPlatform.streamByeCmd(platform, channel.getDeviceId(), stream, null, null); commanderForPlatform.streamByeCmd(platform, channel.getDeviceId(), stream, null, null);
} }
} catch (InvalidArgumentException | SipException | ParseException | SsrcTransactionNotFoundException e) { } catch (InvalidArgumentException | SipException | ParseException | SsrcTransactionNotFoundException e) {
logger.warn("[消息发送失败] 停止语音对讲, 平台:{},通道:{}", platform.getId(), channel.getDeviceId() ); log.warn("[消息发送失败] 停止语音对讲, 平台:{},通道:{}", platform.getId(), channel.getDeviceId() );
} finally { } finally {
mediaServerService.closeRTPServer(mediaServerItem, stream); mediaServerService.closeRTPServer(mediaServerItem, stream);
InviteInfo inviteInfo = inviteStreamService.getInviteInfo(null, platform.getServerGBId(), channel.getDeviceId(), stream); InviteInfo inviteInfo = inviteStreamService.getInviteInfo(null, platform.getServerGBId(), channel.getDeviceId(), stream);

View File

@ -37,6 +37,7 @@ import com.genersoft.iot.vmp.vmanager.bean.ErrorCode;
import com.genersoft.iot.vmp.vmanager.bean.StreamContent; import com.genersoft.iot.vmp.vmanager.bean.StreamContent;
import com.genersoft.iot.vmp.vmanager.gb28181.play.bean.AudioBroadcastEvent; import com.genersoft.iot.vmp.vmanager.gb28181.play.bean.AudioBroadcastEvent;
import gov.nist.javax.sip.message.SIPResponse; import gov.nist.javax.sip.message.SIPResponse;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -57,12 +58,11 @@ import java.text.ParseException;
import java.util.*; import java.util.*;
@SuppressWarnings(value = {"rawtypes", "unchecked"}) @SuppressWarnings(value = {"rawtypes", "unchecked"})
@Slf4j
@Service @Service
@DS("master") @DS("master")
public class PlayServiceImpl implements IPlayService { public class PlayServiceImpl implements IPlayService {
private final static Logger logger = LoggerFactory.getLogger(PlayServiceImpl.class);
@Autowired @Autowired
private IVideoManagerStorage storager; private IVideoManagerStorage storager;
@ -125,7 +125,7 @@ public class PlayServiceImpl implements IPlayService {
String channelId = streamArray[1]; String channelId = streamArray[1];
Device device = deviceService.getDevice(deviceId); Device device = deviceService.getDevice(deviceId);
if (device == null) { if (device == null) {
logger.info("[语音对讲/喊话] 未找到设备:{}", deviceId); log.info("[语音对讲/喊话] 未找到设备:{}", deviceId);
return; return;
} }
if ("broadcast".equals(event.getApp())) { if ("broadcast".equals(event.getApp())) {
@ -136,15 +136,15 @@ public class PlayServiceImpl implements IPlayService {
try { try {
audioBroadcastCmd(device, channelId, event.getMediaServer(), audioBroadcastCmd(device, channelId, event.getMediaServer(),
event.getApp(), event.getStream(), 60, false, (msg) -> { event.getApp(), event.getStream(), 60, false, (msg) -> {
logger.info("[语音对讲] 通道建立成功, device: {}, channel: {}", deviceId, channelId); log.info("[语音对讲] 通道建立成功, device: {}, channel: {}", deviceId, channelId);
}); });
} catch (InvalidArgumentException | ParseException | SipException e) { } catch (InvalidArgumentException | ParseException | SipException e) {
logger.error("[命令发送失败] 语音对讲: {}", e.getMessage()); log.error("[命令发送失败] 语音对讲: {}", e.getMessage());
} }
}else if ("talk".equals(event.getApp())) { }else if ("talk".equals(event.getApp())) {
// 开启语音对讲通道 // 开启语音对讲通道
talkCmd(device, channelId, event.getMediaServer(), event.getStream(), (msg) -> { talkCmd(device, channelId, event.getMediaServer(), event.getStream(), (msg) -> {
logger.info("[语音对讲] 通道建立成功, device: {}, channel: {}", deviceId, channelId); log.info("[语音对讲] 通道建立成功, device: {}, channel: {}", deviceId, channelId);
}); });
} }
} }
@ -174,14 +174,14 @@ public class PlayServiceImpl implements IPlayService {
AudioBroadcastCatch audioBroadcastCatch = audioBroadcastManager.get(sendRtpItem.getDeviceId(), sendRtpItem.getChannelId()); AudioBroadcastCatch audioBroadcastCatch = audioBroadcastManager.get(sendRtpItem.getDeviceId(), sendRtpItem.getChannelId());
if (audioBroadcastCatch != null) { if (audioBroadcastCatch != null) {
// 来自上级平台的停止对讲 // 来自上级平台的停止对讲
logger.info("[停止对讲] 来自上级,平台:{}, 通道:{}", sendRtpItem.getDeviceId(), sendRtpItem.getChannelId()); log.info("[停止对讲] 来自上级,平台:{}, 通道:{}", sendRtpItem.getDeviceId(), sendRtpItem.getChannelId());
audioBroadcastManager.del(sendRtpItem.getDeviceId(), sendRtpItem.getChannelId()); audioBroadcastManager.del(sendRtpItem.getDeviceId(), sendRtpItem.getChannelId());
} }
} }
} }
} catch (SipException | InvalidArgumentException | ParseException | } catch (SipException | InvalidArgumentException | ParseException |
SsrcTransactionNotFoundException e) { SsrcTransactionNotFoundException e) {
logger.error("[命令发送失败] 发送BYE: {}", e.getMessage()); log.error("[命令发送失败] 发送BYE: {}", e.getMessage());
} }
} }
} }
@ -195,7 +195,7 @@ public class PlayServiceImpl implements IPlayService {
String channelId = streamArray[1]; String channelId = streamArray[1];
Device device = deviceService.getDevice(deviceId); Device device = deviceService.getDevice(deviceId);
if (device == null) { if (device == null) {
logger.info("[语音对讲/喊话] 未找到设备:{}", deviceId); log.info("[语音对讲/喊话] 未找到设备:{}", deviceId);
return; return;
} }
if ("broadcast".equals(event.getApp())) { if ("broadcast".equals(event.getApp())) {
@ -232,7 +232,7 @@ public class PlayServiceImpl implements IPlayService {
return; return;
} }
if (s.length == 2) { if (s.length == 2) {
logger.info("[ZLM HOOK] 预览流未找到, 发起自动点播:{}->{}->{}/{}", event.getMediaServer().getId(), event.getSchema(), event.getApp(), event.getStream()); log.info("[ZLM HOOK] 预览流未找到, 发起自动点播:{}->{}->{}/{}", event.getMediaServer().getId(), event.getSchema(), event.getApp(), event.getStream());
play(event.getMediaServer(), deviceId, channelId, null, null); play(event.getMediaServer(), deviceId, channelId, null, null);
} else if (s.length == 4) { } else if (s.length == 4) {
// 此时为录像回放 录像回放格式为> 设备ID_通道ID_开始时间_结束时间 // 此时为录像回放 录像回放格式为> 设备ID_通道ID_开始时间_结束时间
@ -243,7 +243,7 @@ public class PlayServiceImpl implements IPlayService {
} }
String startTime = DateUtil.urlToyyyy_MM_dd_HH_mm_ss(startTimeStr); String startTime = DateUtil.urlToyyyy_MM_dd_HH_mm_ss(startTimeStr);
String endTime = DateUtil.urlToyyyy_MM_dd_HH_mm_ss(endTimeStr); String endTime = DateUtil.urlToyyyy_MM_dd_HH_mm_ss(endTimeStr);
logger.info("[ZLM HOOK] 回放流未找到, 发起自动点播:{}->{}->{}/{}-{}-{}", log.info("[ZLM HOOK] 回放流未找到, 发起自动点播:{}->{}->{}/{}-{}-{}",
event.getMediaServer().getId(), event.getSchema(), event.getMediaServer().getId(), event.getSchema(),
event.getApp(), event.getStream(), event.getApp(), event.getStream(),
startTime, endTime startTime, endTime
@ -260,17 +260,17 @@ public class PlayServiceImpl implements IPlayService {
@Override @Override
public SSRCInfo play(MediaServer mediaServerItem, String deviceId, String channelId, String ssrc, ErrorCallback<Object> callback) { public SSRCInfo play(MediaServer mediaServerItem, String deviceId, String channelId, String ssrc, ErrorCallback<Object> callback) {
if (mediaServerItem == null) { if (mediaServerItem == null) {
logger.warn("[点播] 未找到可用的zlm deviceId: {},channelId:{}", deviceId, channelId); log.warn("[点播] 未找到可用的zlm deviceId: {},channelId:{}", deviceId, channelId);
throw new ControllerException(ErrorCode.ERROR100.getCode(), "未找到可用的zlm"); throw new ControllerException(ErrorCode.ERROR100.getCode(), "未找到可用的zlm");
} }
Device device = redisCatchStorage.getDevice(deviceId); Device device = redisCatchStorage.getDevice(deviceId);
if (device.getStreamMode().equalsIgnoreCase("TCP-ACTIVE") && !mediaServerItem.isRtpEnable()) { if (device.getStreamMode().equalsIgnoreCase("TCP-ACTIVE") && !mediaServerItem.isRtpEnable()) {
logger.warn("[点播] 单端口收流时不支持TCP主动方式收流 deviceId: {},channelId:{}", deviceId, channelId); log.warn("[点播] 单端口收流时不支持TCP主动方式收流 deviceId: {},channelId:{}", deviceId, channelId);
throw new ControllerException(ErrorCode.ERROR100.getCode(), "单端口收流时不支持TCP主动方式收流"); throw new ControllerException(ErrorCode.ERROR100.getCode(), "单端口收流时不支持TCP主动方式收流");
} }
DeviceChannel channel = channelService.getOne(deviceId, channelId); DeviceChannel channel = channelService.getOne(deviceId, channelId);
if (channel == null) { if (channel == null) {
logger.warn("[点播] 未找到通道 deviceId: {},channelId:{}", deviceId, channelId); log.warn("[点播] 未找到通道 deviceId: {},channelId:{}", deviceId, channelId);
throw new ControllerException(ErrorCode.ERROR100.getCode(), "未找到通道"); throw new ControllerException(ErrorCode.ERROR100.getCode(), "未找到通道");
} }
InviteInfo inviteInfo = inviteStreamService.getInviteInfoByDeviceAndChannel(InviteSessionType.PLAY, deviceId, channelId); InviteInfo inviteInfo = inviteStreamService.getInviteInfoByDeviceAndChannel(InviteSessionType.PLAY, deviceId, channelId);
@ -280,7 +280,7 @@ public class PlayServiceImpl implements IPlayService {
ssrcFactory.releaseSsrc(mediaServerItem.getId(), ssrc); ssrcFactory.releaseSsrc(mediaServerItem.getId(), ssrc);
// 点播发起了但是尚未成功, 仅注册回调等待结果即可 // 点播发起了但是尚未成功, 仅注册回调等待结果即可
inviteStreamService.once(InviteSessionType.PLAY, deviceId, channelId, null, callback); inviteStreamService.once(InviteSessionType.PLAY, deviceId, channelId, null, callback);
logger.info("[点播开始] 已经请求中,等待结果, deviceId: {}, channelId: {}", device.getDeviceId(), channelId); log.info("[点播开始] 已经请求中,等待结果, deviceId: {}, channelId: {}", device.getDeviceId(), channelId);
return inviteInfo.getSsrcInfo(); return inviteInfo.getSsrcInfo();
}else { }else {
StreamInfo streamInfo = inviteInfo.getStreamInfo(); StreamInfo streamInfo = inviteInfo.getStreamInfo();
@ -302,7 +302,7 @@ public class PlayServiceImpl implements IPlayService {
InviteErrorCode.SUCCESS.getCode(), InviteErrorCode.SUCCESS.getCode(),
InviteErrorCode.SUCCESS.getMsg(), InviteErrorCode.SUCCESS.getMsg(),
streamInfo); streamInfo);
logger.info("[点播已存在] 直接返回, deviceId: {}, channelId: {}", device.getDeviceId(), channelId); log.info("[点播已存在] 直接返回, deviceId: {}, channelId: {}", device.getDeviceId(), channelId);
return inviteInfo.getSsrcInfo(); return inviteInfo.getSsrcInfo();
}else { }else {
// 点播发起了但是尚未成功, 仅注册回调等待结果即可 // 点播发起了但是尚未成功, 仅注册回调等待结果即可
@ -359,24 +359,24 @@ public class PlayServiceImpl implements IPlayService {
int port = sendRtpPortManager.getNextPort(mediaServerItem); int port = sendRtpPortManager.getNextPort(mediaServerItem);
//端口获取失败的ssrcInfo 没有必要发送点播指令 //端口获取失败的ssrcInfo 没有必要发送点播指令
if (port <= 0) { if (port <= 0) {
logger.info("[语音对讲] 端口分配异常deviceId={},channelId={}", device.getDeviceId(), channelId); log.info("[语音对讲] 端口分配异常deviceId={},channelId={}", device.getDeviceId(), channelId);
audioEvent.call("端口分配异常"); audioEvent.call("端口分配异常");
return; return;
} }
sendRtpItem.setLocalPort(port); sendRtpItem.setLocalPort(port);
sendRtpItem.setPort(port); sendRtpItem.setPort(port);
logger.info("[语音对讲]开始 deviceId: {}, channelId: {},收流端口: {}, 收流模式:{}, SSRC: {}, SSRC校验{}", device.getDeviceId(), channelId, sendRtpItem.getLocalPort(), device.getStreamMode(), sendRtpItem.getSsrc(), false); log.info("[语音对讲]开始 deviceId: {}, channelId: {},收流端口: {}, 收流模式:{}, SSRC: {}, SSRC校验{}", device.getDeviceId(), channelId, sendRtpItem.getLocalPort(), device.getStreamMode(), sendRtpItem.getSsrc(), false);
// 超时处理 // 超时处理
String timeOutTaskKey = UUID.randomUUID().toString(); String timeOutTaskKey = UUID.randomUUID().toString();
dynamicTask.startDelay(timeOutTaskKey, () -> { dynamicTask.startDelay(timeOutTaskKey, () -> {
logger.info("[语音对讲] 收流超时 deviceId: {}, channelId: {},端口:{}, SSRC: {}", device.getDeviceId(), channelId, sendRtpItem.getPort(), sendRtpItem.getSsrc()); log.info("[语音对讲] 收流超时 deviceId: {}, channelId: {},端口:{}, SSRC: {}", device.getDeviceId(), channelId, sendRtpItem.getPort(), sendRtpItem.getSsrc());
timeoutCallback.run(); timeoutCallback.run();
// 点播超时回复BYE 同时释放ssrc以及此次点播的资源 // 点播超时回复BYE 同时释放ssrc以及此次点播的资源
try { try {
cmder.streamByeCmd(device, channelId, sendRtpItem.getStream(), null); cmder.streamByeCmd(device, channelId, sendRtpItem.getStream(), null);
} catch (InvalidArgumentException | ParseException | SipException | SsrcTransactionNotFoundException e) { } catch (InvalidArgumentException | ParseException | SipException | SsrcTransactionNotFoundException e) {
logger.error("[语音对讲]超时, 发送BYE失败 {}", e.getMessage()); log.error("[语音对讲]超时, 发送BYE失败 {}", e.getMessage());
} finally { } finally {
timeoutCallback.run(); timeoutCallback.run();
mediaServerService.releaseSsrc(mediaServerItem.getId(), sendRtpItem.getSsrc()); mediaServerService.releaseSsrc(mediaServerItem.getId(), sendRtpItem.getSsrc());
@ -388,7 +388,7 @@ public class PlayServiceImpl implements IPlayService {
mediaServerService.startSendRtpPassive(mediaServerItem, sendRtpItem, userSetting.getPlayTimeout() * 1000); mediaServerService.startSendRtpPassive(mediaServerItem, sendRtpItem, userSetting.getPlayTimeout() * 1000);
}catch (ControllerException e) { }catch (ControllerException e) {
mediaServerService.releaseSsrc(mediaServerItem.getId(), sendRtpItem.getSsrc()); mediaServerService.releaseSsrc(mediaServerItem.getId(), sendRtpItem.getSsrc());
logger.info("[语音对讲]失败 deviceId: {}, channelId: {}", device.getDeviceId(), channelId); log.info("[语音对讲]失败 deviceId: {}, channelId: {}", device.getDeviceId(), channelId);
audioEvent.call("失败, " + e.getMessage()); audioEvent.call("失败, " + e.getMessage());
// 查看是否已经建立了通道存在则发送bye // 查看是否已经建立了通道存在则发送bye
stopTalk(device, channelId); stopTalk(device, channelId);
@ -398,11 +398,11 @@ public class PlayServiceImpl implements IPlayService {
// 查看设备是否已经在推流 // 查看设备是否已经在推流
try { try {
cmder.talkStreamCmd(mediaServerItem, sendRtpItem, device, channelId, callId, (hookData) -> { cmder.talkStreamCmd(mediaServerItem, sendRtpItem, device, channelId, callId, (hookData) -> {
logger.info("[语音对讲] 流已生成, 开始推流: " + hookData); log.info("[语音对讲] 流已生成, 开始推流: " + hookData);
dynamicTask.stop(timeOutTaskKey); dynamicTask.stop(timeOutTaskKey);
// TODO 暂不做处理 // TODO 暂不做处理
}, (hookData) -> { }, (hookData) -> {
logger.info("[语音对讲] 设备开始推流: " + hookData); log.info("[语音对讲] 设备开始推流: " + hookData);
dynamicTask.stop(timeOutTaskKey); dynamicTask.stop(timeOutTaskKey);
}, (event) -> { }, (event) -> {
@ -421,10 +421,10 @@ public class PlayServiceImpl implements IPlayService {
sendRtpItem.getStream(), sendRtpItem.getSsrc(), sendRtpItem.getMediaServerId(), sendRtpItem.getStream(), sendRtpItem.getSsrc(), sendRtpItem.getMediaServerId(),
response, InviteSessionType.TALK); response, InviteSessionType.TALK);
} else { } else {
logger.error("[语音对讲]收到的消息错误response不是SIPResponse"); log.error("[语音对讲]收到的消息错误response不是SIPResponse");
} }
} else { } else {
logger.error("[语音对讲]收到的消息错误event不是ResponseEvent"); log.error("[语音对讲]收到的消息错误event不是ResponseEvent");
} }
}, (event) -> { }, (event) -> {
@ -437,7 +437,7 @@ public class PlayServiceImpl implements IPlayService {
}); });
} catch (InvalidArgumentException | SipException | ParseException e) { } catch (InvalidArgumentException | SipException | ParseException e) {
logger.error("[命令发送失败] 对讲消息: {}", e.getMessage()); log.error("[命令发送失败] 对讲消息: {}", e.getMessage());
dynamicTask.stop(timeOutTaskKey); dynamicTask.stop(timeOutTaskKey);
mediaServerService.closeRTPServer(mediaServerItem, sendRtpItem.getStream()); mediaServerService.closeRTPServer(mediaServerItem, sendRtpItem.getStream());
// 释放ssrc // 释放ssrc
@ -466,12 +466,12 @@ public class PlayServiceImpl implements IPlayService {
null); null);
return; return;
} }
logger.info("[点播开始] deviceId: {}, channelId: {},码流类型:{}, 收流端口: {}, 码流:{}, 收流模式:{}, SSRC: {}, SSRC校验{}", log.info("[点播开始] deviceId: {}, channelId: {},码流类型:{}, 收流端口: {}, 码流:{}, 收流模式:{}, SSRC: {}, SSRC校验{}",
device.getDeviceId(), channel.getDeviceId(), channel.getStreamIdentification(), ssrcInfo.getPort(), ssrcInfo.getStream(), device.getDeviceId(), channel.getDeviceId(), channel.getStreamIdentification(), ssrcInfo.getPort(), ssrcInfo.getStream(),
device.getStreamMode(), ssrcInfo.getSsrc(), device.isSsrcCheck()); device.getStreamMode(), ssrcInfo.getSsrc(), device.isSsrcCheck());
//端口获取失败的ssrcInfo 没有必要发送点播指令 //端口获取失败的ssrcInfo 没有必要发送点播指令
if (ssrcInfo.getPort() <= 0) { if (ssrcInfo.getPort() <= 0) {
logger.info("[点播端口分配异常]deviceId={},channelId={},ssrcInfo={}", device.getDeviceId(), channel.getDeviceId(), ssrcInfo); log.info("[点播端口分配异常]deviceId={},channelId={},ssrcInfo={}", device.getDeviceId(), channel.getDeviceId(), ssrcInfo);
// 释放ssrc // 释放ssrc
mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc()); mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
streamSession.remove(device.getDeviceId(), channel.getDeviceId(), ssrcInfo.getStream()); streamSession.remove(device.getDeviceId(), channel.getDeviceId(), ssrcInfo.getStream());
@ -493,7 +493,7 @@ public class PlayServiceImpl implements IPlayService {
// 执行超时任务时查询是否已经成功成功了则不执行超时任务防止超时任务取消失败的情况 // 执行超时任务时查询是否已经成功成功了则不执行超时任务防止超时任务取消失败的情况
InviteInfo inviteInfoForTimeOut = inviteStreamService.getInviteInfoByDeviceAndChannel(InviteSessionType.PLAY, device.getDeviceId(), channel.getDeviceId()); InviteInfo inviteInfoForTimeOut = inviteStreamService.getInviteInfoByDeviceAndChannel(InviteSessionType.PLAY, device.getDeviceId(), channel.getDeviceId());
if (inviteInfoForTimeOut == null || inviteInfoForTimeOut.getStreamInfo() == null) { if (inviteInfoForTimeOut == null || inviteInfoForTimeOut.getStreamInfo() == null) {
logger.info("[点播超时] 收流超时 deviceId: {}, channelId: {},码流:{},端口:{}, SSRC: {}", log.info("[点播超时] 收流超时 deviceId: {}, channelId: {},码流:{},端口:{}, SSRC: {}",
device.getDeviceId(), channel.getDeviceId(), channel.getStreamIdentification(), device.getDeviceId(), channel.getDeviceId(), channel.getStreamIdentification(),
ssrcInfo.getPort(), ssrcInfo.getSsrc()); ssrcInfo.getPort(), ssrcInfo.getSsrc());
@ -505,7 +505,7 @@ public class PlayServiceImpl implements IPlayService {
try { try {
cmder.streamByeCmd(device, channel.getDeviceId(), ssrcInfo.getStream(), null); cmder.streamByeCmd(device, channel.getDeviceId(), ssrcInfo.getStream(), null);
} catch (InvalidArgumentException | ParseException | SipException | SsrcTransactionNotFoundException e) { } catch (InvalidArgumentException | ParseException | SipException | SsrcTransactionNotFoundException e) {
logger.error("[点播超时] 发送BYE失败 {}", e.getMessage()); log.error("[点播超时] 发送BYE失败 {}", e.getMessage());
} finally { } finally {
mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc()); mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
mediaServerService.closeRTPServer(mediaServerItem, ssrcInfo.getStream()); mediaServerService.closeRTPServer(mediaServerItem, ssrcInfo.getStream());
@ -515,7 +515,7 @@ public class PlayServiceImpl implements IPlayService {
subscribe.removeSubscribe(Hook.getInstance(HookType.on_media_arrival, "rtp", ssrcInfo.getStream(), mediaServerItem.getId())); subscribe.removeSubscribe(Hook.getInstance(HookType.on_media_arrival, "rtp", ssrcInfo.getStream(), mediaServerItem.getId()));
} }
}else { }else {
logger.info("[点播超时] 收流超时 deviceId: {}, channelId: {},码流:{},端口:{}, SSRC: {}", log.info("[点播超时] 收流超时 deviceId: {}, channelId: {},码流:{},端口:{}, SSRC: {}",
device.getDeviceId(), channel.getDeviceId(), channel.getStreamIdentification(), device.getDeviceId(), channel.getDeviceId(), channel.getStreamIdentification(),
ssrcInfo.getPort(), ssrcInfo.getSsrc()); ssrcInfo.getPort(), ssrcInfo.getSsrc());
@ -528,7 +528,7 @@ public class PlayServiceImpl implements IPlayService {
try { try {
cmder.playStreamCmd(mediaServerItem, ssrcInfo, device, channel, (hookData ) -> { cmder.playStreamCmd(mediaServerItem, ssrcInfo, device, channel, (hookData ) -> {
logger.info("收到订阅消息: " + hookData); log.info("收到订阅消息: " + hookData);
dynamicTask.stop(timeOutTaskKey); dynamicTask.stop(timeOutTaskKey);
// hook响应 // hook响应
StreamInfo streamInfo = onPublishHandlerForPlay(hookData.getMediaServer(), hookData.getMediaInfo(), device.getDeviceId(), channel.getDeviceId()); StreamInfo streamInfo = onPublishHandlerForPlay(hookData.getMediaServer(), hookData.getMediaInfo(), device.getDeviceId(), channel.getDeviceId());
@ -545,7 +545,7 @@ public class PlayServiceImpl implements IPlayService {
InviteErrorCode.SUCCESS.getCode(), InviteErrorCode.SUCCESS.getCode(),
InviteErrorCode.SUCCESS.getMsg(), InviteErrorCode.SUCCESS.getMsg(),
streamInfo); streamInfo);
logger.info("[点播成功] deviceId: {}, channelId:{}, 码流类型:{}", device.getDeviceId(), channel.getDeviceId(), log.info("[点播成功] deviceId: {}, channelId:{}, 码流类型:{}", device.getDeviceId(), channel.getDeviceId(),
channel.getStreamIdentification()); channel.getStreamIdentification());
snapOnPlay(hookData.getMediaServer(), device.getDeviceId(), channel.getDeviceId(), ssrcInfo.getStream()); snapOnPlay(hookData.getMediaServer(), device.getDeviceId(), channel.getDeviceId(), ssrcInfo.getStream());
}, (eventResult) -> { }, (eventResult) -> {
@ -553,7 +553,7 @@ public class PlayServiceImpl implements IPlayService {
InviteOKHandler(eventResult, ssrcInfo, mediaServerItem, device, channel.getDeviceId(), InviteOKHandler(eventResult, ssrcInfo, mediaServerItem, device, channel.getDeviceId(),
timeOutTaskKey, callback, inviteInfo, InviteSessionType.PLAY); timeOutTaskKey, callback, inviteInfo, InviteSessionType.PLAY);
}, (event) -> { }, (event) -> {
logger.info("[点播失败] deviceId: {}, channelId:{}, {}: {}", device.getDeviceId(), channel.getDeviceId(), event.statusCode, event.msg); log.info("[点播失败] deviceId: {}, channelId:{}, {}: {}", device.getDeviceId(), channel.getDeviceId(), event.statusCode, event.msg);
dynamicTask.stop(timeOutTaskKey); dynamicTask.stop(timeOutTaskKey);
mediaServerService.closeRTPServer(mediaServerItem, ssrcInfo.getStream()); mediaServerService.closeRTPServer(mediaServerItem, ssrcInfo.getStream());
// 释放ssrc // 释放ssrc
@ -570,7 +570,7 @@ public class PlayServiceImpl implements IPlayService {
}); });
} catch (InvalidArgumentException | SipException | ParseException e) { } catch (InvalidArgumentException | SipException | ParseException e) {
logger.error("[命令发送失败] 点播消息: {}", e.getMessage()); log.error("[命令发送失败] 点播消息: {}", e.getMessage());
dynamicTask.stop(timeOutTaskKey); dynamicTask.stop(timeOutTaskKey);
mediaServerService.closeRTPServer(mediaServerItem, ssrcInfo.getStream()); mediaServerService.closeRTPServer(mediaServerItem, ssrcInfo.getStream());
// 释放ssrc // 释放ssrc
@ -615,9 +615,9 @@ public class PlayServiceImpl implements IPlayService {
break; break;
} }
} }
logger.info("[TCP主动连接对方] deviceId: {}, channelId: {}, 连接对方的地址:{}:{}, 收流模式:{}, SSRC: {}, SSRC校验{}", device.getDeviceId(), channelId, sdp.getConnection().getAddress(), port, device.getStreamMode(), ssrcInfo.getSsrc(), device.isSsrcCheck()); log.info("[TCP主动连接对方] deviceId: {}, channelId: {}, 连接对方的地址:{}:{}, 收流模式:{}, SSRC: {}, SSRC校验{}", device.getDeviceId(), channelId, sdp.getConnection().getAddress(), port, device.getStreamMode(), ssrcInfo.getSsrc(), device.isSsrcCheck());
Boolean result = mediaServerService.connectRtpServer(mediaServerItem, sdp.getConnection().getAddress(), port, ssrcInfo.getStream()); Boolean result = mediaServerService.connectRtpServer(mediaServerItem, sdp.getConnection().getAddress(), port, ssrcInfo.getStream());
logger.info("[TCP主动连接对方] 结果: {}" , result); log.info("[TCP主动连接对方] 结果: {}" , result);
if (!result) { if (!result) {
// 主动连接失败结束流程 清理数据 // 主动连接失败结束流程 清理数据
dynamicTask.stop(timeOutTaskKey); dynamicTask.stop(timeOutTaskKey);
@ -634,7 +634,7 @@ public class PlayServiceImpl implements IPlayService {
InviteErrorCode.ERROR_FOR_SDP_PARSING_EXCEPTIONS.getMsg(), null); InviteErrorCode.ERROR_FOR_SDP_PARSING_EXCEPTIONS.getMsg(), null);
} }
} catch (SdpException e) { } catch (SdpException e) {
logger.error("[TCP主动连接对方] deviceId: {}, channelId: {}, 解析200OK的SDP信息失败", device.getDeviceId(), channelId, e); log.error("[TCP主动连接对方] deviceId: {}, channelId: {}, 解析200OK的SDP信息失败", device.getDeviceId(), channelId, e);
dynamicTask.stop(timeOutTaskKey); dynamicTask.stop(timeOutTaskKey);
mediaServerService.closeRTPServer(mediaServerItem, ssrcInfo.getStream()); mediaServerService.closeRTPServer(mediaServerItem, ssrcInfo.getStream());
// 释放ssrc // 释放ssrc
@ -668,7 +668,7 @@ public class PlayServiceImpl implements IPlayService {
String path = "snap"; String path = "snap";
String fileName = deviceId + "_" + channelId + ".jpg"; String fileName = deviceId + "_" + channelId + ".jpg";
// 请求截图 // 请求截图
logger.info("[请求截图]: " + fileName); log.info("[请求截图]: " + fileName);
mediaServerService.getSnap(mediaServerItemInuse, streamUrl, 15, 1, path, fileName); mediaServerService.getSnap(mediaServerItemInuse, streamUrl, 15, 1, path, fileName);
} }
@ -727,7 +727,7 @@ public class PlayServiceImpl implements IPlayService {
mediaServerItem = mediaServerService.getOne(device.getMediaServerId()); mediaServerItem = mediaServerService.getOne(device.getMediaServerId());
} }
if (mediaServerItem == null) { if (mediaServerItem == null) {
logger.warn("点播时未找到可使用的ZLM..."); log.warn("点播时未找到可使用的ZLM...");
} }
return mediaServerItem; return mediaServerItem;
} }
@ -737,19 +737,19 @@ public class PlayServiceImpl implements IPlayService {
String endTime, ErrorCallback<Object> callback) { String endTime, ErrorCallback<Object> callback) {
Device device = storager.queryVideoDevice(deviceId); Device device = storager.queryVideoDevice(deviceId);
if (device == null) { if (device == null) {
logger.warn("[录像回放] 未找到设备 deviceId: {},channelId:{}", deviceId, channelId); log.warn("[录像回放] 未找到设备 deviceId: {},channelId:{}", deviceId, channelId);
throw new ControllerException(ErrorCode.ERROR100.getCode(), "未找到设备:" + deviceId); throw new ControllerException(ErrorCode.ERROR100.getCode(), "未找到设备:" + deviceId);
} }
DeviceChannel channel = channelService.getOne(deviceId, channelId); DeviceChannel channel = channelService.getOne(deviceId, channelId);
if (channel == null) { if (channel == null) {
logger.warn("[录像回放] 未找到通道 deviceId: {},channelId:{}", deviceId, channelId); log.warn("[录像回放] 未找到通道 deviceId: {},channelId:{}", deviceId, channelId);
throw new ControllerException(ErrorCode.ERROR100.getCode(), "未找到通道:" + channelId); throw new ControllerException(ErrorCode.ERROR100.getCode(), "未找到通道:" + channelId);
} }
MediaServer newMediaServerItem = getNewMediaServerItem(device); MediaServer newMediaServerItem = getNewMediaServerItem(device);
if (device.getStreamMode().equalsIgnoreCase("TCP-ACTIVE") && ! newMediaServerItem.isRtpEnable()) { if (device.getStreamMode().equalsIgnoreCase("TCP-ACTIVE") && ! newMediaServerItem.isRtpEnable()) {
logger.warn("[录像回放] 单端口收流时不支持TCP主动方式收流 deviceId: {},channelId:{}", deviceId, channelId); log.warn("[录像回放] 单端口收流时不支持TCP主动方式收流 deviceId: {},channelId:{}", deviceId, channelId);
throw new ControllerException(ErrorCode.ERROR100.getCode(), "单端口收流时不支持TCP主动方式收流"); throw new ControllerException(ErrorCode.ERROR100.getCode(), "单端口收流时不支持TCP主动方式收流");
} }
String startTimeStr = startTime.replace("-", "") String startTimeStr = startTime.replace("-", "")
@ -779,7 +779,7 @@ public class PlayServiceImpl implements IPlayService {
if (device == null) { if (device == null) {
throw new ControllerException(ErrorCode.ERROR100.getCode(), "设备: " + deviceId + "不存在"); throw new ControllerException(ErrorCode.ERROR100.getCode(), "设备: " + deviceId + "不存在");
} }
logger.info("[录像回放] deviceId: {}, channelId: {}, 开始时间: {}, 结束时间: {}, 收流端口:{}, 收流模式:{}, SSRC: {}, SSRC校验{}", log.info("[录像回放] deviceId: {}, channelId: {}, 开始时间: {}, 结束时间: {}, 收流端口:{}, 收流模式:{}, SSRC: {}, SSRC校验{}",
device.getDeviceId(), channelId, startTime, endTime, ssrcInfo.getPort(), device.getStreamMode(), device.getDeviceId(), channelId, startTime, endTime, ssrcInfo.getPort(), device.getStreamMode(),
ssrcInfo.getSsrc(), device.isSsrcCheck()); ssrcInfo.getSsrc(), device.isSsrcCheck());
// 初始化redis中的invite消息状态 // 初始化redis中的invite消息状态
@ -789,14 +789,14 @@ public class PlayServiceImpl implements IPlayService {
inviteStreamService.updateInviteInfo(inviteInfo); inviteStreamService.updateInviteInfo(inviteInfo);
String playBackTimeOutTaskKey = UUID.randomUUID().toString(); String playBackTimeOutTaskKey = UUID.randomUUID().toString();
dynamicTask.startDelay(playBackTimeOutTaskKey, () -> { dynamicTask.startDelay(playBackTimeOutTaskKey, () -> {
logger.warn("[录像回放] 超时deviceId{} channelId{}", deviceId, channelId); log.warn("[录像回放] 超时deviceId{} channelId{}", deviceId, channelId);
inviteStreamService.removeInviteInfo(inviteInfo); inviteStreamService.removeInviteInfo(inviteInfo);
callback.run(InviteErrorCode.ERROR_FOR_SIGNALLING_TIMEOUT.getCode(), InviteErrorCode.ERROR_FOR_SIGNALLING_TIMEOUT.getMsg(), null); callback.run(InviteErrorCode.ERROR_FOR_SIGNALLING_TIMEOUT.getCode(), InviteErrorCode.ERROR_FOR_SIGNALLING_TIMEOUT.getMsg(), null);
try { try {
cmder.streamByeCmd(device, channelId, ssrcInfo.getStream(), null); cmder.streamByeCmd(device, channelId, ssrcInfo.getStream(), null);
} catch (InvalidArgumentException | ParseException | SipException e) { } catch (InvalidArgumentException | ParseException | SipException e) {
logger.error("[录像回放] 超时 发送BYE失败 {}", e.getMessage()); log.error("[录像回放] 超时 发送BYE失败 {}", e.getMessage());
} catch (SsrcTransactionNotFoundException e) { } catch (SsrcTransactionNotFoundException e) {
// 点播超时回复BYE 同时释放ssrc以及此次点播的资源 // 点播超时回复BYE 同时释放ssrc以及此次点播的资源
mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc()); mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
@ -806,7 +806,7 @@ public class PlayServiceImpl implements IPlayService {
}, userSetting.getPlayTimeout()); }, userSetting.getPlayTimeout());
SipSubscribe.Event errorEvent = event -> { SipSubscribe.Event errorEvent = event -> {
logger.info("[录像回放] 失败,{} {}", event.statusCode, event.msg); log.info("[录像回放] 失败,{} {}", event.statusCode, event.msg);
dynamicTask.stop(playBackTimeOutTaskKey); dynamicTask.stop(playBackTimeOutTaskKey);
callback.run(InviteErrorCode.ERROR_FOR_SIGNALLING_ERROR.getCode(), callback.run(InviteErrorCode.ERROR_FOR_SIGNALLING_ERROR.getCode(),
String.format("回放失败, 错误码: %s, %s", event.statusCode, event.msg), null); String.format("回放失败, 错误码: %s, %s", event.statusCode, event.msg), null);
@ -817,17 +817,17 @@ public class PlayServiceImpl implements IPlayService {
}; };
HookSubscribe.Event hookEvent = (hookData) -> { HookSubscribe.Event hookEvent = (hookData) -> {
logger.info("收到回放订阅消息: " + hookData); log.info("收到回放订阅消息: " + hookData);
dynamicTask.stop(playBackTimeOutTaskKey); dynamicTask.stop(playBackTimeOutTaskKey);
StreamInfo streamInfo = onPublishHandlerForPlayback(hookData.getMediaServer(), hookData.getMediaInfo(), deviceId, channelId, startTime, endTime); StreamInfo streamInfo = onPublishHandlerForPlayback(hookData.getMediaServer(), hookData.getMediaInfo(), deviceId, channelId, startTime, endTime);
if (streamInfo == null) { if (streamInfo == null) {
logger.warn("设备回放API调用失败"); log.warn("设备回放API调用失败");
callback.run(InviteErrorCode.ERROR_FOR_STREAM_PARSING_EXCEPTIONS.getCode(), callback.run(InviteErrorCode.ERROR_FOR_STREAM_PARSING_EXCEPTIONS.getCode(),
InviteErrorCode.ERROR_FOR_STREAM_PARSING_EXCEPTIONS.getMsg(), null); InviteErrorCode.ERROR_FOR_STREAM_PARSING_EXCEPTIONS.getMsg(), null);
return; return;
} }
callback.run(InviteErrorCode.SUCCESS.getCode(), InviteErrorCode.SUCCESS.getMsg(), streamInfo); callback.run(InviteErrorCode.SUCCESS.getCode(), InviteErrorCode.SUCCESS.getMsg(), streamInfo);
logger.info("[录像回放] 成功 deviceId: {}, channelId: {}, 开始时间: {}, 结束时间: {}", device.getDeviceId(), channelId, startTime, endTime); log.info("[录像回放] 成功 deviceId: {}, channelId: {}, 开始时间: {}, 结束时间: {}", device.getDeviceId(), channelId, startTime, endTime);
}; };
try { try {
@ -838,7 +838,7 @@ public class PlayServiceImpl implements IPlayService {
playBackTimeOutTaskKey, callback, inviteInfo, InviteSessionType.PLAYBACK); playBackTimeOutTaskKey, callback, inviteInfo, InviteSessionType.PLAYBACK);
}, errorEvent); }, errorEvent);
} catch (InvalidArgumentException | SipException | ParseException e) { } catch (InvalidArgumentException | SipException | ParseException e) {
logger.error("[命令发送失败] 录像回放: {}", e.getMessage()); log.error("[命令发送失败] 录像回放: {}", e.getMessage());
SipSubscribe.EventResult eventResult = new SipSubscribe.EventResult(); SipSubscribe.EventResult eventResult = new SipSubscribe.EventResult();
eventResult.type = SipSubscribe.EventResultType.cmdSendFailEvent; eventResult.type = SipSubscribe.EventResultType.cmdSendFailEvent;
@ -870,28 +870,28 @@ public class PlayServiceImpl implements IPlayService {
}else { }else {
// 单端口 // 单端口
if (device.getStreamMode().equalsIgnoreCase("TCP-ACTIVE")) { if (device.getStreamMode().equalsIgnoreCase("TCP-ACTIVE")) {
logger.warn("[Invite 200OK] 单端口收流模式不支持tcp主动模式收流"); log.warn("[Invite 200OK] 单端口收流模式不支持tcp主动模式收流");
} }
} }
}else { }else {
logger.info("[Invite 200OK] 收到invite 200, 发现下级自定义了ssrc: {}", ssrcInResponse); log.info("[Invite 200OK] 收到invite 200, 发现下级自定义了ssrc: {}", ssrcInResponse);
// ssrc 不一致 // ssrc 不一致
if (mediaServerItem.isRtpEnable()) { if (mediaServerItem.isRtpEnable()) {
// 多端口 // 多端口
if (device.isSsrcCheck()) { if (device.isSsrcCheck()) {
// ssrc检验 // ssrc检验
// 更新ssrc // 更新ssrc
logger.info("[Invite 200OK] SSRC修正 {}->{}", ssrcInfo.getSsrc(), ssrcInResponse); log.info("[Invite 200OK] SSRC修正 {}->{}", ssrcInfo.getSsrc(), ssrcInResponse);
// 释放ssrc // 释放ssrc
mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc()); mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
Boolean result = mediaServerService.updateRtpServerSSRC(mediaServerItem, ssrcInfo.getStream(), ssrcInResponse); Boolean result = mediaServerService.updateRtpServerSSRC(mediaServerItem, ssrcInfo.getStream(), ssrcInResponse);
if (!result) { if (!result) {
try { try {
logger.warn("[Invite 200OK] 更新ssrc失败停止点播 {}/{}", device.getDeviceId(), channelId); log.warn("[Invite 200OK] 更新ssrc失败停止点播 {}/{}", device.getDeviceId(), channelId);
cmder.streamByeCmd(device, channelId, ssrcInfo.getStream(), null, null); cmder.streamByeCmd(device, channelId, ssrcInfo.getStream(), null, null);
} catch (InvalidArgumentException | SipException | ParseException | SsrcTransactionNotFoundException e) { } catch (InvalidArgumentException | SipException | ParseException | SsrcTransactionNotFoundException e) {
logger.error("[命令发送失败] 停止播放, 发送BYE: {}", e.getMessage()); log.error("[命令发送失败] 停止播放, 发送BYE: {}", e.getMessage());
} }
dynamicTask.stop(timeOutTaskKey); dynamicTask.stop(timeOutTaskKey);
@ -914,7 +914,7 @@ public class PlayServiceImpl implements IPlayService {
if (mediaServerItem.isRtpEnable()) { if (mediaServerItem.isRtpEnable()) {
tcpActiveHandler(device, channelId, contentString, mediaServerItem, timeOutTaskKey, ssrcInfo, callback); tcpActiveHandler(device, channelId, contentString, mediaServerItem, timeOutTaskKey, ssrcInfo, callback);
}else { }else {
logger.warn("[Invite 200OK] 单端口收流模式不支持tcp主动模式收流"); log.warn("[Invite 200OK] 单端口收流模式不支持tcp主动模式收流");
} }
} }
inviteStreamService.updateInviteInfo(inviteInfo); inviteStreamService.updateInviteInfo(inviteInfo);
@ -978,7 +978,7 @@ public class PlayServiceImpl implements IPlayService {
null); null);
return; return;
} }
logger.info("[录像下载] deviceId: {}, channelId: {}, 下载速度:{}, 收流端口:{}, 收流模式:{}, SSRC: {}, SSRC校验{}", device.getDeviceId(), channelId, downloadSpeed, ssrcInfo.getPort(), device.getStreamMode(), ssrcInfo.getSsrc(), device.isSsrcCheck()); log.info("[录像下载] deviceId: {}, channelId: {}, 下载速度:{}, 收流端口:{}, 收流模式:{}, SSRC: {}, SSRC校验{}", device.getDeviceId(), channelId, downloadSpeed, ssrcInfo.getPort(), device.getStreamMode(), ssrcInfo.getSsrc(), device.isSsrcCheck());
// 初始化redis中的invite消息状态 // 初始化redis中的invite消息状态
InviteInfo inviteInfo = InviteInfo.getInviteInfo(device.getDeviceId(), channelId, ssrcInfo.getStream(), ssrcInfo, InviteInfo inviteInfo = InviteInfo.getInviteInfo(device.getDeviceId(), channelId, ssrcInfo.getStream(), ssrcInfo,
mediaServerItem.getSdpIp(), ssrcInfo.getPort(), device.getStreamMode(), InviteSessionType.DOWNLOAD, mediaServerItem.getSdpIp(), ssrcInfo.getPort(), device.getStreamMode(), InviteSessionType.DOWNLOAD,
@ -986,7 +986,7 @@ public class PlayServiceImpl implements IPlayService {
inviteStreamService.updateInviteInfo(inviteInfo); inviteStreamService.updateInviteInfo(inviteInfo);
String downLoadTimeOutTaskKey = UUID.randomUUID().toString(); String downLoadTimeOutTaskKey = UUID.randomUUID().toString();
dynamicTask.startDelay(downLoadTimeOutTaskKey, () -> { dynamicTask.startDelay(downLoadTimeOutTaskKey, () -> {
logger.warn(String.format("录像下载请求超时deviceId%s channelId%s", deviceId, channelId)); log.warn(String.format("录像下载请求超时deviceId%s channelId%s", deviceId, channelId));
inviteStreamService.removeInviteInfo(inviteInfo); inviteStreamService.removeInviteInfo(inviteInfo);
callback.run(InviteErrorCode.ERROR_FOR_SIGNALLING_TIMEOUT.getCode(), callback.run(InviteErrorCode.ERROR_FOR_SIGNALLING_TIMEOUT.getCode(),
InviteErrorCode.ERROR_FOR_SIGNALLING_TIMEOUT.getMsg(), null); InviteErrorCode.ERROR_FOR_SIGNALLING_TIMEOUT.getMsg(), null);
@ -995,7 +995,7 @@ public class PlayServiceImpl implements IPlayService {
try { try {
cmder.streamByeCmd(device, channelId, ssrcInfo.getStream(), null); cmder.streamByeCmd(device, channelId, ssrcInfo.getStream(), null);
} catch (InvalidArgumentException | ParseException | SipException e) { } catch (InvalidArgumentException | ParseException | SipException e) {
logger.error("[录像流]录像下载请求超时, 发送BYE失败 {}", e.getMessage()); log.error("[录像流]录像下载请求超时, 发送BYE失败 {}", e.getMessage());
} catch (SsrcTransactionNotFoundException e) { } catch (SsrcTransactionNotFoundException e) {
mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc()); mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
mediaServerService.closeRTPServer(mediaServerItem, ssrcInfo.getStream()); mediaServerService.closeRTPServer(mediaServerItem, ssrcInfo.getStream());
@ -1012,17 +1012,17 @@ public class PlayServiceImpl implements IPlayService {
inviteStreamService.removeInviteInfo(inviteInfo); inviteStreamService.removeInviteInfo(inviteInfo);
}; };
HookSubscribe.Event hookEvent = (hookData) -> { HookSubscribe.Event hookEvent = (hookData) -> {
logger.info("[录像下载]收到订阅消息: " + hookData); log.info("[录像下载]收到订阅消息: " + hookData);
dynamicTask.stop(downLoadTimeOutTaskKey); dynamicTask.stop(downLoadTimeOutTaskKey);
StreamInfo streamInfo = onPublishHandlerForDownload(hookData.getMediaServer(), hookData.getMediaInfo(), deviceId, channelId, startTime, endTime); StreamInfo streamInfo = onPublishHandlerForDownload(hookData.getMediaServer(), hookData.getMediaInfo(), deviceId, channelId, startTime, endTime);
if (streamInfo == null) { if (streamInfo == null) {
logger.warn("[录像下载] 获取流地址信息失败"); log.warn("[录像下载] 获取流地址信息失败");
callback.run(InviteErrorCode.ERROR_FOR_STREAM_PARSING_EXCEPTIONS.getCode(), callback.run(InviteErrorCode.ERROR_FOR_STREAM_PARSING_EXCEPTIONS.getCode(),
InviteErrorCode.ERROR_FOR_STREAM_PARSING_EXCEPTIONS.getMsg(), null); InviteErrorCode.ERROR_FOR_STREAM_PARSING_EXCEPTIONS.getMsg(), null);
return; return;
} }
callback.run(InviteErrorCode.SUCCESS.getCode(), InviteErrorCode.SUCCESS.getMsg(), streamInfo); callback.run(InviteErrorCode.SUCCESS.getCode(), InviteErrorCode.SUCCESS.getMsg(), streamInfo);
logger.info("[录像下载] 调用成功 deviceId: {}, channelId: {}, 开始时间: {}, 结束时间: {}", device.getDeviceId(), channelId, startTime, endTime); log.info("[录像下载] 调用成功 deviceId: {}, channelId: {}, 开始时间: {}, 结束时间: {}", device.getDeviceId(), channelId, startTime, endTime);
}; };
try { try {
cmder.downloadStreamCmd(mediaServerItem, ssrcInfo, device, channelId, startTime, endTime, downloadSpeed, cmder.downloadStreamCmd(mediaServerItem, ssrcInfo, device, channelId, startTime, endTime, downloadSpeed,
@ -1033,9 +1033,9 @@ public class PlayServiceImpl implements IPlayService {
// 注册录像回调事件录像下载结束后写入下载地址 // 注册录像回调事件录像下载结束后写入下载地址
HookSubscribe.Event hookEventForRecord = (hookData) -> { HookSubscribe.Event hookEventForRecord = (hookData) -> {
logger.info("[录像下载] 收到录像写入磁盘消息: {}/{}-{}", log.info("[录像下载] 收到录像写入磁盘消息: {}/{}-{}",
inviteInfo.getDeviceId(), inviteInfo.getChannelId(), ssrcInfo.getStream()); inviteInfo.getDeviceId(), inviteInfo.getChannelId(), ssrcInfo.getStream());
logger.info("[录像下载] 收到录像写入磁盘消息内容: " + hookData); log.info("[录像下载] 收到录像写入磁盘消息内容: " + hookData);
RecordInfo recordInfo = hookData.getRecordInfo(); RecordInfo recordInfo = hookData.getRecordInfo();
String filePath = recordInfo.getFilePath(); String filePath = recordInfo.getFilePath();
DownloadFileInfo downloadFileInfo = CloudRecordUtils.getDownloadFilePath(mediaServerItem, filePath); DownloadFileInfo downloadFileInfo = CloudRecordUtils.getDownloadFilePath(mediaServerItem, filePath);
@ -1051,7 +1051,7 @@ public class PlayServiceImpl implements IPlayService {
subscribe.addSubscribe(hook, hookEventForRecord); subscribe.addSubscribe(hook, hookEventForRecord);
}); });
} catch (InvalidArgumentException | SipException | ParseException e) { } catch (InvalidArgumentException | SipException | ParseException e) {
logger.error("[命令发送失败] 录像下载: {}", e.getMessage()); log.error("[命令发送失败] 录像下载: {}", e.getMessage());
SipSubscribe.EventResult eventResult = new SipSubscribe.EventResult(); SipSubscribe.EventResult eventResult = new SipSubscribe.EventResult();
eventResult.type = SipSubscribe.EventResultType.cmdSendFailEvent; eventResult.type = SipSubscribe.EventResultType.cmdSendFailEvent;
@ -1065,7 +1065,7 @@ public class PlayServiceImpl implements IPlayService {
public StreamInfo getDownLoadInfo(String deviceId, String channelId, String stream) { public StreamInfo getDownLoadInfo(String deviceId, String channelId, String stream) {
InviteInfo inviteInfo = inviteStreamService.getInviteInfo(InviteSessionType.DOWNLOAD, deviceId, channelId, stream); InviteInfo inviteInfo = inviteStreamService.getInviteInfo(InviteSessionType.DOWNLOAD, deviceId, channelId, stream);
if (inviteInfo == null || inviteInfo.getStreamInfo() == null) { if (inviteInfo == null || inviteInfo.getStreamInfo() == null) {
logger.warn("[获取下载进度] 未查询到录像下载的信息"); log.warn("[获取下载进度] 未查询到录像下载的信息");
return null; return null;
} }
@ -1077,13 +1077,13 @@ public class PlayServiceImpl implements IPlayService {
String mediaServerId = inviteInfo.getStreamInfo().getMediaServerId(); String mediaServerId = inviteInfo.getStreamInfo().getMediaServerId();
MediaServer mediaServerItem = mediaServerService.getOne(mediaServerId); MediaServer mediaServerItem = mediaServerService.getOne(mediaServerId);
if (mediaServerItem == null) { if (mediaServerItem == null) {
logger.warn("[获取下载进度] 查询录像信息时发现节点不存在"); log.warn("[获取下载进度] 查询录像信息时发现节点不存在");
return null; return null;
} }
SsrcTransaction ssrcTransaction = streamSession.getSsrcTransaction(deviceId, channelId, null, stream); SsrcTransaction ssrcTransaction = streamSession.getSsrcTransaction(deviceId, channelId, null, stream);
if (ssrcTransaction == null) { if (ssrcTransaction == null) {
logger.warn("[获取下载进度] 下载已结束"); log.warn("[获取下载进度] 下载已结束");
return null; return null;
} }
String app = "rtp"; String app = "rtp";
@ -1118,7 +1118,7 @@ public class PlayServiceImpl implements IPlayService {
streamInfo.setEndTime(endTime); streamInfo.setEndTime(endTime);
InviteInfo inviteInfo = inviteStreamService.getInviteInfo(InviteSessionType.DOWNLOAD, deviceId, channelId, streamInfo.getStream()); InviteInfo inviteInfo = inviteStreamService.getInviteInfo(InviteSessionType.DOWNLOAD, deviceId, channelId, streamInfo.getStream());
if (inviteInfo != null) { if (inviteInfo != null) {
logger.info("[录像下载] 更新invite消息中的stream信息"); log.info("[录像下载] 更新invite消息中的stream信息");
inviteInfo.setStatus(InviteSessionStatus.ok); inviteInfo.setStatus(InviteSessionStatus.ok);
inviteInfo.setStreamInfo(streamInfo); inviteInfo.setStreamInfo(streamInfo);
inviteStreamService.updateInviteInfo(inviteInfo); inviteStreamService.updateInviteInfo(inviteInfo);
@ -1147,7 +1147,7 @@ public class PlayServiceImpl implements IPlayService {
try { try {
sipCommanderFroPlatform.streamByeCmd(platform, sendRtpItem.getCallId()); sipCommanderFroPlatform.streamByeCmd(platform, sendRtpItem.getCallId());
} catch (SipException | InvalidArgumentException | ParseException e) { } catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] 国标级联 发送BYE: {}", e.getMessage()); log.error("[命令发送失败] 国标级联 发送BYE: {}", e.getMessage());
} }
} }
} }
@ -1166,7 +1166,7 @@ public class PlayServiceImpl implements IPlayService {
ssrcTransaction.getStream(), null); ssrcTransaction.getStream(), null);
} catch (InvalidArgumentException | ParseException | SipException | } catch (InvalidArgumentException | ParseException | SipException |
SsrcTransactionNotFoundException e) { SsrcTransactionNotFoundException e) {
logger.error("[zlm离线]为正在使用此zlm的设备 发送BYE失败 {}", e.getMessage()); log.error("[zlm离线]为正在使用此zlm的设备 发送BYE失败 {}", e.getMessage());
} }
} }
} }
@ -1179,10 +1179,10 @@ public class PlayServiceImpl implements IPlayService {
if (device == null || channelId == null) { if (device == null || channelId == null) {
return null; return null;
} }
logger.info("[语音喊话] device {}, channel: {}", device.getDeviceId(), channelId); log.info("[语音喊话] device {}, channel: {}", device.getDeviceId(), channelId);
DeviceChannel deviceChannel = storager.queryChannel(device.getDeviceId(), channelId); DeviceChannel deviceChannel = storager.queryChannel(device.getDeviceId(), channelId);
if (deviceChannel == null) { if (deviceChannel == null) {
logger.warn("开启语音广播的时候未找到通道: {}", channelId); log.warn("开启语音广播的时候未找到通道: {}", channelId);
return null; return null;
} }
MediaServer mediaServerItem = mediaServerService.getMediaServerForMinimumLoad(null); MediaServer mediaServerItem = mediaServerService.getMediaServerForMinimumLoad(null);
@ -1204,10 +1204,10 @@ public class PlayServiceImpl implements IPlayService {
if (device == null || channelId == null) { if (device == null || channelId == null) {
return false; return false;
} }
logger.info("[语音喊话] device {}, channel: {}", device.getDeviceId(), channelId); log.info("[语音喊话] device {}, channel: {}", device.getDeviceId(), channelId);
DeviceChannel deviceChannel = storager.queryChannel(device.getDeviceId(), channelId); DeviceChannel deviceChannel = storager.queryChannel(device.getDeviceId(), channelId);
if (deviceChannel == null) { if (deviceChannel == null) {
logger.warn("开启语音广播的时候未找到通道: {}", channelId); log.warn("开启语音广播的时候未找到通道: {}", channelId);
event.call("开启语音广播的时候未找到通道"); event.call("开启语音广播的时候未找到通道");
return false; return false;
} }
@ -1218,7 +1218,7 @@ public class PlayServiceImpl implements IPlayService {
// 查询流是否存在不存在则认为是异常状态 // 查询流是否存在不存在则认为是异常状态
Boolean streamReady = mediaServerService.isStreamReady(mediaServerItem, sendRtpItem.getApp(), sendRtpItem.getStream()); Boolean streamReady = mediaServerService.isStreamReady(mediaServerItem, sendRtpItem.getApp(), sendRtpItem.getStream());
if (streamReady) { if (streamReady) {
logger.warn("语音广播已经开启: {}", channelId); log.warn("语音广播已经开启: {}", channelId);
event.call("语音广播已经开启"); event.call("语音广播已经开启");
return false; return false;
} else { } else {
@ -1238,12 +1238,12 @@ public class PlayServiceImpl implements IPlayService {
key += audioBroadcastCatch.getChannelId(); key += audioBroadcastCatch.getChannelId();
} }
dynamicTask.startDelay(key, ()->{ dynamicTask.startDelay(key, ()->{
logger.info("[语音广播]等待invite消息超时{}/{}", device.getDeviceId(), channelId); log.info("[语音广播]等待invite消息超时{}/{}", device.getDeviceId(), channelId);
stopAudioBroadcast(device.getDeviceId(), channelId); stopAudioBroadcast(device.getDeviceId(), channelId);
}, 10*1000); }, 10*1000);
}, eventResultForError -> { }, eventResultForError -> {
// 发送失败 // 发送失败
logger.error("语音广播发送失败: {}:{}", channelId, eventResultForError.msg); log.error("语音广播发送失败: {}:{}", channelId, eventResultForError.msg);
event.call("语音广播发送失败"); event.call("语音广播发送失败");
stopAudioBroadcast(device.getDeviceId(), channelId); stopAudioBroadcast(device.getDeviceId(), channelId);
}); });
@ -1259,7 +1259,7 @@ public class PlayServiceImpl implements IPlayService {
MediaServer mediaServerServiceOne = mediaServerService.getOne(sendRtpItem.getMediaServerId()); MediaServer mediaServerServiceOne = mediaServerService.getOne(sendRtpItem.getMediaServerId());
Boolean streamReady = mediaServerService.isStreamReady(mediaServerServiceOne, sendRtpItem.getApp(), sendRtpItem.getStream()); Boolean streamReady = mediaServerService.isStreamReady(mediaServerServiceOne, sendRtpItem.getApp(), sendRtpItem.getStream());
if (streamReady) { if (streamReady) {
logger.warn("语音广播通道使用中: {}", channelId); log.warn("语音广播通道使用中: {}", channelId);
return true; return true;
} }
} }
@ -1270,7 +1270,7 @@ public class PlayServiceImpl implements IPlayService {
@Override @Override
public void stopAudioBroadcast(String deviceId, String channelId) { public void stopAudioBroadcast(String deviceId, String channelId) {
logger.info("[停止对讲] 设备:{}, 通道:{}", deviceId, channelId); log.info("[停止对讲] 设备:{}, 通道:{}", deviceId, channelId);
List<AudioBroadcastCatch> audioBroadcastCatchList = new ArrayList<>(); List<AudioBroadcastCatch> audioBroadcastCatchList = new ArrayList<>();
if (channelId == null) { if (channelId == null) {
audioBroadcastCatchList.addAll(audioBroadcastManager.get(deviceId)); audioBroadcastCatchList.addAll(audioBroadcastManager.get(deviceId));
@ -1292,7 +1292,7 @@ public class PlayServiceImpl implements IPlayService {
cmder.streamByeCmdForDeviceInvite(device, sendRtpItem.getChannelId(), audioBroadcastCatch.getSipTransactionInfo(), null); cmder.streamByeCmdForDeviceInvite(device, sendRtpItem.getChannelId(), audioBroadcastCatch.getSipTransactionInfo(), null);
} catch (InvalidArgumentException | ParseException | SipException | } catch (InvalidArgumentException | ParseException | SipException |
SsrcTransactionNotFoundException e) { SsrcTransactionNotFoundException e) {
logger.error("[消息发送失败] 发送语音喊话BYE失败"); log.error("[消息发送失败] 发送语音喊话BYE失败");
} }
} }
@ -1358,14 +1358,14 @@ public class PlayServiceImpl implements IPlayService {
public void pauseRtp(String streamId) throws ServiceException, InvalidArgumentException, ParseException, SipException { public void pauseRtp(String streamId) throws ServiceException, InvalidArgumentException, ParseException, SipException {
InviteInfo inviteInfo = inviteStreamService.getInviteInfoByStream(InviteSessionType.PLAYBACK, streamId); InviteInfo inviteInfo = inviteStreamService.getInviteInfoByStream(InviteSessionType.PLAYBACK, streamId);
if (null == inviteInfo || inviteInfo.getStreamInfo() == null) { if (null == inviteInfo || inviteInfo.getStreamInfo() == null) {
logger.warn("streamId不存在!"); log.warn("streamId不存在!");
throw new ServiceException("streamId不存在"); throw new ServiceException("streamId不存在");
} }
inviteInfo.getStreamInfo().setPause(true); inviteInfo.getStreamInfo().setPause(true);
inviteStreamService.updateInviteInfo(inviteInfo); inviteStreamService.updateInviteInfo(inviteInfo);
MediaServer mediaServerItem = mediaServerService.getOne(inviteInfo.getStreamInfo().getMediaServerId()); MediaServer mediaServerItem = mediaServerService.getOne(inviteInfo.getStreamInfo().getMediaServerId());
if (null == mediaServerItem) { if (null == mediaServerItem) {
logger.warn("mediaServer 不存在!"); log.warn("mediaServer 不存在!");
throw new ServiceException("mediaServer不存在"); throw new ServiceException("mediaServer不存在");
} }
// zlm 暂停RTP超时检查 // zlm 暂停RTP超时检查
@ -1386,14 +1386,14 @@ public class PlayServiceImpl implements IPlayService {
public void resumeRtp(String streamId) throws ServiceException, InvalidArgumentException, ParseException, SipException { public void resumeRtp(String streamId) throws ServiceException, InvalidArgumentException, ParseException, SipException {
InviteInfo inviteInfo = inviteStreamService.getInviteInfoByStream(InviteSessionType.PLAYBACK, streamId); InviteInfo inviteInfo = inviteStreamService.getInviteInfoByStream(InviteSessionType.PLAYBACK, streamId);
if (null == inviteInfo || inviteInfo.getStreamInfo() == null) { if (null == inviteInfo || inviteInfo.getStreamInfo() == null) {
logger.warn("streamId不存在!"); log.warn("streamId不存在!");
throw new ServiceException("streamId不存在"); throw new ServiceException("streamId不存在");
} }
inviteInfo.getStreamInfo().setPause(false); inviteInfo.getStreamInfo().setPause(false);
inviteStreamService.updateInviteInfo(inviteInfo); inviteStreamService.updateInviteInfo(inviteInfo);
MediaServer mediaServerItem = mediaServerService.getOne(inviteInfo.getStreamInfo().getMediaServerId()); MediaServer mediaServerItem = mediaServerService.getOne(inviteInfo.getStreamInfo().getMediaServerId());
if (null == mediaServerItem) { if (null == mediaServerItem) {
logger.warn("mediaServer 不存在!"); log.warn("mediaServer 不存在!");
throw new ServiceException("mediaServer不存在"); throw new ServiceException("mediaServer不存在");
} }
// zlm 暂停RTP超时检查 // zlm 暂停RTP超时检查
@ -1424,12 +1424,12 @@ public class PlayServiceImpl implements IPlayService {
} }
redisCatchStorage.sendPlatformStartPlayMsg(sendRtpItem, platform); redisCatchStorage.sendPlatformStartPlayMsg(sendRtpItem, platform);
}catch (ControllerException e) { }catch (ControllerException e) {
logger.error("RTP推流失败: {}", e.getMessage()); log.error("RTP推流失败: {}", e.getMessage());
startSendRtpStreamFailHand(sendRtpItem, platform, callIdHeader); startSendRtpStreamFailHand(sendRtpItem, platform, callIdHeader);
return; return;
} }
logger.info("RTP推流成功[ {}/{} ]{}, ", sendRtpItem.getApp(), sendRtpItem.getStream(), log.info("RTP推流成功[ {}/{} ]{}, ", sendRtpItem.getApp(), sendRtpItem.getStream(),
sendRtpItem.isTcpActive()?"被动发流": sendRtpItem.getIp() + ":" + sendRtpItem.getPort()); sendRtpItem.isTcpActive()?"被动发流": sendRtpItem.getIp() + ":" + sendRtpItem.getPort());
} }
@ -1445,7 +1445,7 @@ public class PlayServiceImpl implements IPlayService {
cmder.streamByeCmd(device, sendRtpItem.getChannelId(), audioBroadcastCatch.getSipTransactionInfo(), null); cmder.streamByeCmd(device, sendRtpItem.getChannelId(), audioBroadcastCatch.getSipTransactionInfo(), null);
} catch (SipException | ParseException | InvalidArgumentException | } catch (SipException | ParseException | InvalidArgumentException |
SsrcTransactionNotFoundException exception) { SsrcTransactionNotFoundException exception) {
logger.error("[命令发送失败] 停止语音对讲: {}", exception.getMessage()); log.error("[命令发送失败] 停止语音对讲: {}", exception.getMessage());
} }
} }
} else { } else {
@ -1454,7 +1454,7 @@ public class PlayServiceImpl implements IPlayService {
try { try {
commanderForPlatform.streamByeCmd(platform, callIdHeader.getCallId()); commanderForPlatform.streamByeCmd(platform, callIdHeader.getCallId());
} catch (SipException | InvalidArgumentException | ParseException e) { } catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] 国标级联 发送BYE: {}", e.getMessage()); log.error("[命令发送失败] 国标级联 发送BYE: {}", e.getMessage());
} }
} }
@ -1467,10 +1467,10 @@ public class PlayServiceImpl implements IPlayService {
return; return;
} }
// TODO 必须多端口模式才支持语音喊话鹤语音对讲 // TODO 必须多端口模式才支持语音喊话鹤语音对讲
logger.info("[语音对讲] device {}, channel: {}", device.getDeviceId(), channelId); log.info("[语音对讲] device {}, channel: {}", device.getDeviceId(), channelId);
DeviceChannel deviceChannel = storager.queryChannel(device.getDeviceId(), channelId); DeviceChannel deviceChannel = storager.queryChannel(device.getDeviceId(), channelId);
if (deviceChannel == null) { if (deviceChannel == null) {
logger.warn("开启语音对讲的时候未找到通道: {}", channelId); log.warn("开启语音对讲的时候未找到通道: {}", channelId);
event.call("开启语音对讲的时候未找到通道"); event.call("开启语音对讲的时候未找到通道");
return; return;
} }
@ -1482,7 +1482,7 @@ public class PlayServiceImpl implements IPlayService {
MediaServer mediaServer = mediaServerService.getOne(sendRtpItem.getMediaServerId()); MediaServer mediaServer = mediaServerService.getOne(sendRtpItem.getMediaServerId());
Boolean streamReady = mediaServerService.isStreamReady(mediaServer, sendRtpItem.getApp(), sendRtpItem.getStream()); Boolean streamReady = mediaServerService.isStreamReady(mediaServer, sendRtpItem.getApp(), sendRtpItem.getStream());
if (streamReady) { if (streamReady) {
logger.warn("[语音对讲] 正在语音广播,无法开启语音通话: {}", channelId); log.warn("[语音对讲] 正在语音广播,无法开启语音通话: {}", channelId);
event.call("正在语音广播"); event.call("正在语音广播");
return; return;
} else { } else {
@ -1496,7 +1496,7 @@ public class PlayServiceImpl implements IPlayService {
MediaServer mediaServer = mediaServerService.getOne(sendRtpItem.getMediaServerId()); MediaServer mediaServer = mediaServerService.getOne(sendRtpItem.getMediaServerId());
Boolean streamReady = mediaServerService.isStreamReady(mediaServer, "rtp", sendRtpItem.getReceiveStream()); Boolean streamReady = mediaServerService.isStreamReady(mediaServer, "rtp", sendRtpItem.getReceiveStream());
if (streamReady) { if (streamReady) {
logger.warn("[语音对讲] 进行中: {}", channelId); log.warn("[语音对讲] 进行中: {}", channelId);
event.call("语音对讲进行中"); event.call("语音对讲进行中");
return; return;
} else { } else {
@ -1505,16 +1505,16 @@ public class PlayServiceImpl implements IPlayService {
} }
talk(mediaServerItem, device, channelId, stream, (hookData) -> { talk(mediaServerItem, device, channelId, stream, (hookData) -> {
logger.info("[语音对讲] 收到设备发来的流"); log.info("[语音对讲] 收到设备发来的流");
}, eventResult -> { }, eventResult -> {
logger.warn("[语音对讲] 失败,{}/{}, 错误码 {} {}", device.getDeviceId(), channelId, eventResult.statusCode, eventResult.msg); log.warn("[语音对讲] 失败,{}/{}, 错误码 {} {}", device.getDeviceId(), channelId, eventResult.statusCode, eventResult.msg);
event.call("失败,错误码 " + eventResult.statusCode + ", " + eventResult.msg); event.call("失败,错误码 " + eventResult.statusCode + ", " + eventResult.msg);
}, () -> { }, () -> {
logger.warn("[语音对讲] 失败,{}/{} 超时", device.getDeviceId(), channelId); log.warn("[语音对讲] 失败,{}/{} 超时", device.getDeviceId(), channelId);
event.call("失败,超时 "); event.call("失败,超时 ");
stopTalk(device, channelId); stopTalk(device, channelId);
}, errorMsg -> { }, errorMsg -> {
logger.warn("[语音对讲] 失败,{}/{} {}", device.getDeviceId(), channelId, errorMsg); log.warn("[语音对讲] 失败,{}/{} {}", device.getDeviceId(), channelId, errorMsg);
event.call(errorMsg); event.call(errorMsg);
stopTalk(device, channelId); stopTalk(device, channelId);
}); });
@ -1526,10 +1526,10 @@ public class PlayServiceImpl implements IPlayService {
@Override @Override
public void stopTalk(Device device, String channelId, Boolean streamIsReady) { public void stopTalk(Device device, String channelId, Boolean streamIsReady) {
logger.info("[语音对讲] 停止, {}/{}", device.getDeviceId(), channelId); log.info("[语音对讲] 停止, {}/{}", device.getDeviceId(), channelId);
SendRtpItem sendRtpItem = redisCatchStorage.querySendRTPServer(device.getDeviceId(), channelId, null, null); SendRtpItem sendRtpItem = redisCatchStorage.querySendRTPServer(device.getDeviceId(), channelId, null, null);
if (sendRtpItem == null) { if (sendRtpItem == null) {
logger.info("[语音对讲] 停止失败, 未找到发送信息,可能已经停止"); log.info("[语音对讲] 停止失败, 未找到发送信息,可能已经停止");
return; return;
} }
// 停止向设备推流 // 停止向设备推流
@ -1551,7 +1551,7 @@ public class PlayServiceImpl implements IPlayService {
try { try {
cmder.streamByeCmd(device, channelId, sendRtpItem.getStream(), null); cmder.streamByeCmd(device, channelId, sendRtpItem.getStream(), null);
} catch (InvalidArgumentException | ParseException | SipException | SsrcTransactionNotFoundException e) { } catch (InvalidArgumentException | ParseException | SipException | SsrcTransactionNotFoundException e) {
logger.info("[语音对讲] 停止消息发送失败,可能已经停止"); log.info("[语音对讲] 停止消息发送失败,可能已经停止");
} }
} }
redisCatchStorage.deleteSendRTPServer(device.getDeviceId(), channelId,null, null); redisCatchStorage.deleteSendRTPServer(device.getDeviceId(), channelId,null, null);
@ -1577,7 +1577,7 @@ public class PlayServiceImpl implements IPlayService {
} }
String path = "snap"; String path = "snap";
// 请求截图 // 请求截图
logger.info("[请求截图]: " + fileName); log.info("[请求截图]: " + fileName);
mediaServerService.getSnap(mediaServerItemInuse, streamUrl, 15, 1, path, fileName); mediaServerService.getSnap(mediaServerItemInuse, streamUrl, 15, 1, path, fileName);
File snapFile = new File(path + File.separator + fileName); File snapFile = new File(path + File.separator + fileName);
if (snapFile.exists()) { if (snapFile.exists()) {
@ -1612,10 +1612,10 @@ public class PlayServiceImpl implements IPlayService {
} }
if (InviteSessionStatus.ok == inviteInfo.getStatus()) { if (InviteSessionStatus.ok == inviteInfo.getStatus()) {
try { try {
logger.info("[停止点播] {}/{}", device.getDeviceId(), channelId); log.info("[停止点播] {}/{}", device.getDeviceId(), channelId);
cmder.streamByeCmd(device, channelId, inviteInfo.getStream(), null, null); cmder.streamByeCmd(device, channelId, inviteInfo.getStream(), null, null);
} catch (InvalidArgumentException | SipException | ParseException | SsrcTransactionNotFoundException e) { } catch (InvalidArgumentException | SipException | ParseException | SsrcTransactionNotFoundException e) {
logger.error("[命令发送失败] 停止点播, 发送BYE: {}", e.getMessage()); log.error("[命令发送失败] 停止点播, 发送BYE: {}", e.getMessage());
throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage()); throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage());
} }
} }

View File

@ -14,17 +14,15 @@ import com.genersoft.iot.vmp.media.event.hook.HookType;
import com.genersoft.iot.vmp.service.redisMsg.IRedisRpcService; import com.genersoft.iot.vmp.service.redisMsg.IRedisRpcService;
import com.genersoft.iot.vmp.vmanager.bean.ErrorCode; import com.genersoft.iot.vmp.vmanager.bean.ErrorCode;
import com.genersoft.iot.vmp.vmanager.bean.WVPResult; import com.genersoft.iot.vmp.vmanager.bean.WVPResult;
import org.slf4j.Logger; import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@Slf4j
@Service @Service
public class RedisRpcServiceImpl implements IRedisRpcService { public class RedisRpcServiceImpl implements IRedisRpcService {
private final static Logger logger = LoggerFactory.getLogger(RedisRpcServiceImpl.class);
@Autowired @Autowired
private RedisRpcConfig redisRpcConfig; private RedisRpcConfig redisRpcConfig;
@ -60,7 +58,7 @@ public class RedisRpcServiceImpl implements IRedisRpcService {
@Override @Override
public WVPResult startSendRtp(String sendRtpItemKey, SendRtpItem sendRtpItem) { public WVPResult startSendRtp(String sendRtpItemKey, SendRtpItem sendRtpItem) {
logger.info("[请求其他WVP] 开始推流wvp{} {}/{}", sendRtpItem.getServerId(), sendRtpItem.getApp(), sendRtpItem.getStream()); log.info("[请求其他WVP] 开始推流wvp{} {}/{}", sendRtpItem.getServerId(), sendRtpItem.getApp(), sendRtpItem.getStream());
RedisRpcRequest request = buildRequest("startSendRtp", sendRtpItemKey); RedisRpcRequest request = buildRequest("startSendRtp", sendRtpItemKey);
request.setToId(sendRtpItem.getServerId()); request.setToId(sendRtpItem.getServerId());
RedisRpcResponse response = redisRpcConfig.request(request, 10); RedisRpcResponse response = redisRpcConfig.request(request, 10);
@ -71,10 +69,10 @@ public class RedisRpcServiceImpl implements IRedisRpcService {
public WVPResult stopSendRtp(String sendRtpItemKey) { public WVPResult stopSendRtp(String sendRtpItemKey) {
SendRtpItem sendRtpItem = (SendRtpItem)redisTemplate.opsForValue().get(sendRtpItemKey); SendRtpItem sendRtpItem = (SendRtpItem)redisTemplate.opsForValue().get(sendRtpItemKey);
if (sendRtpItem == null) { if (sendRtpItem == null) {
logger.info("[请求其他WVP] 停止推流, 未找到redis中的发流信息 key{}", sendRtpItemKey); log.info("[请求其他WVP] 停止推流, 未找到redis中的发流信息 key{}", sendRtpItemKey);
return WVPResult.fail(ErrorCode.ERROR100.getCode(), "未找到发流信息"); return WVPResult.fail(ErrorCode.ERROR100.getCode(), "未找到发流信息");
} }
logger.info("[请求其他WVP] 停止推流wvp{} {}/{}", sendRtpItem.getServerId(), sendRtpItem.getApp(), sendRtpItem.getStream()); log.info("[请求其他WVP] 停止推流wvp{} {}/{}", sendRtpItem.getServerId(), sendRtpItem.getApp(), sendRtpItem.getStream());
RedisRpcRequest request = buildRequest("stopSendRtp", sendRtpItemKey); RedisRpcRequest request = buildRequest("stopSendRtp", sendRtpItemKey);
request.setToId(sendRtpItem.getServerId()); request.setToId(sendRtpItem.getServerId());
RedisRpcResponse response = redisRpcConfig.request(request, 10); RedisRpcResponse response = redisRpcConfig.request(request, 10);
@ -83,7 +81,7 @@ public class RedisRpcServiceImpl implements IRedisRpcService {
@Override @Override
public long waitePushStreamOnline(SendRtpItem sendRtpItem, CommonCallback<String> callback) { public long waitePushStreamOnline(SendRtpItem sendRtpItem, CommonCallback<String> callback) {
logger.info("[请求所有WVP监听流上线] {}/{}", sendRtpItem.getApp(), sendRtpItem.getStream()); log.info("[请求所有WVP监听流上线] {}/{}", sendRtpItem.getApp(), sendRtpItem.getStream());
// 监听流上线 流上线直接发送sendRtpItem消息给实际的信令处理者 // 监听流上线 流上线直接发送sendRtpItem消息给实际的信令处理者
Hook hook = Hook.getInstance(HookType.on_media_arrival, sendRtpItem.getApp(), sendRtpItem.getStream(), null); Hook hook = Hook.getInstance(HookType.on_media_arrival, sendRtpItem.getApp(), sendRtpItem.getStream(), null);
RedisRpcRequest request = buildRequest("waitePushStreamOnline", sendRtpItem); RedisRpcRequest request = buildRequest("waitePushStreamOnline", sendRtpItem);
@ -109,10 +107,10 @@ public class RedisRpcServiceImpl implements IRedisRpcService {
redisRpcConfig.request(request, response -> { redisRpcConfig.request(request, response -> {
if (response.getBody() == null) { if (response.getBody() == null) {
logger.info("[请求所有WVP监听流上线] 流上线,但是未找到发流信息:{}/{}", sendRtpItem.getApp(), sendRtpItem.getStream()); log.info("[请求所有WVP监听流上线] 流上线,但是未找到发流信息:{}/{}", sendRtpItem.getApp(), sendRtpItem.getStream());
return; return;
} }
logger.info("[请求所有WVP监听流上线] 流上线 {}/{}->{}", sendRtpItem.getApp(), sendRtpItem.getStream(), sendRtpItem.toString()); log.info("[请求所有WVP监听流上线] 流上线 {}/{}->{}", sendRtpItem.getApp(), sendRtpItem.getStream(), sendRtpItem.toString());
if (callback != null) { if (callback != null) {
callback.run(response.getBody().toString()); callback.run(response.getBody().toString());
@ -124,7 +122,7 @@ public class RedisRpcServiceImpl implements IRedisRpcService {
@Override @Override
public void stopWaitePushStreamOnline(SendRtpItem sendRtpItem) { public void stopWaitePushStreamOnline(SendRtpItem sendRtpItem) {
logger.info("[停止WVP监听流上线] {}/{}", sendRtpItem.getApp(), sendRtpItem.getStream()); log.info("[停止WVP监听流上线] {}/{}", sendRtpItem.getApp(), sendRtpItem.getStream());
Hook hook = Hook.getInstance(HookType.on_media_arrival, sendRtpItem.getApp(), sendRtpItem.getStream(), null); Hook hook = Hook.getInstance(HookType.on_media_arrival, sendRtpItem.getApp(), sendRtpItem.getStream(), null);
hookSubscribe.removeSubscribe(hook); hookSubscribe.removeSubscribe(hook);
RedisRpcRequest request = buildRequest("stopWaitePushStreamOnline", sendRtpItem); RedisRpcRequest request = buildRequest("stopWaitePushStreamOnline", sendRtpItem);
@ -136,7 +134,7 @@ public class RedisRpcServiceImpl implements IRedisRpcService {
public void rtpSendStopped(String sendRtpItemKey) { public void rtpSendStopped(String sendRtpItemKey) {
SendRtpItem sendRtpItem = (SendRtpItem)redisTemplate.opsForValue().get(sendRtpItemKey); SendRtpItem sendRtpItem = (SendRtpItem)redisTemplate.opsForValue().get(sendRtpItemKey);
if (sendRtpItem == null) { if (sendRtpItem == null) {
logger.info("[停止WVP监听流上线] 未找到redis中的发流信息 key{}", sendRtpItemKey); log.info("[停止WVP监听流上线] 未找到redis中的发流信息 key{}", sendRtpItemKey);
return; return;
} }
RedisRpcRequest request = buildRequest("rtpSendStopped", sendRtpItemKey); RedisRpcRequest request = buildRequest("rtpSendStopped", sendRtpItemKey);

View File

@ -11,19 +11,18 @@ import com.genersoft.iot.vmp.media.bean.MediaServer;
import com.genersoft.iot.vmp.media.event.media.MediaArrivalEvent; import com.genersoft.iot.vmp.media.event.media.MediaArrivalEvent;
import com.genersoft.iot.vmp.media.zlm.dto.StreamAuthorityInfo; import com.genersoft.iot.vmp.media.zlm.dto.StreamAuthorityInfo;
import com.genersoft.iot.vmp.media.zlm.dto.hook.OnStreamChangedHookParam; import com.genersoft.iot.vmp.media.zlm.dto.hook.OnStreamChangedHookParam;
import com.genersoft.iot.vmp.streamPush.bean.StreamPush;
import com.genersoft.iot.vmp.service.bean.GPSMsgInfo; import com.genersoft.iot.vmp.service.bean.GPSMsgInfo;
import com.genersoft.iot.vmp.service.bean.MessageForPushChannel; import com.genersoft.iot.vmp.service.bean.MessageForPushChannel;
import com.genersoft.iot.vmp.storager.IRedisCatchStorage; import com.genersoft.iot.vmp.storager.IRedisCatchStorage;
import com.genersoft.iot.vmp.storager.dao.DeviceChannelMapper; import com.genersoft.iot.vmp.storager.dao.DeviceChannelMapper;
import com.genersoft.iot.vmp.storager.dao.DeviceMapper; import com.genersoft.iot.vmp.storager.dao.DeviceMapper;
import com.genersoft.iot.vmp.storager.dao.dto.PlatformRegisterInfo; import com.genersoft.iot.vmp.storager.dao.dto.PlatformRegisterInfo;
import com.genersoft.iot.vmp.streamPush.bean.StreamPush;
import com.genersoft.iot.vmp.utils.DateUtil; import com.genersoft.iot.vmp.utils.DateUtil;
import com.genersoft.iot.vmp.utils.JsonUtil; import com.genersoft.iot.vmp.utils.JsonUtil;
import com.genersoft.iot.vmp.utils.SystemInfoUtils; import com.genersoft.iot.vmp.utils.SystemInfoUtils;
import com.genersoft.iot.vmp.utils.redis.RedisUtil; import com.genersoft.iot.vmp.utils.redis.RedisUtil;
import org.slf4j.Logger; import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate;
@ -33,11 +32,10 @@ import java.time.Duration;
import java.util.*; import java.util.*;
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
@Slf4j
@Component @Component
public class RedisCatchStorageImpl implements IRedisCatchStorage { public class RedisCatchStorageImpl implements IRedisCatchStorage {
private final Logger logger = LoggerFactory.getLogger(RedisCatchStorageImpl.class);
@Autowired @Autowired
private DeviceChannelMapper deviceChannelMapper; private DeviceChannelMapper deviceChannelMapper;
@ -273,7 +271,7 @@ public class RedisCatchStorageImpl implements IRedisCatchStorage {
List<Object> scan = RedisUtil.scan(redisTemplate, key); List<Object> scan = RedisUtil.scan(redisTemplate, key);
if (scan.size() > 0) { if (scan.size() > 0) {
for (Object keyStr : scan) { for (Object keyStr : scan) {
logger.info("[删除 redis的SendRTP] {}", keyStr.toString()); log.info("[删除 redis的SendRTP] {}", keyStr.toString());
redisTemplate.delete(keyStr); redisTemplate.delete(keyStr);
} }
} }
@ -324,7 +322,7 @@ public class RedisCatchStorageImpl implements IRedisCatchStorage {
@Override @Override
public void sendStreamChangeMsg(String type, JSONObject jsonObject) { public void sendStreamChangeMsg(String type, JSONObject jsonObject) {
String key = VideoManagerConstants.WVP_MSG_STREAM_CHANGE_PREFIX + type; String key = VideoManagerConstants.WVP_MSG_STREAM_CHANGE_PREFIX + type;
logger.info("[redis 流变化事件] 发送 {}: {}", key, jsonObject.toString()); log.info("[redis 流变化事件] 发送 {}: {}", key, jsonObject.toString());
redisTemplate.convertAndSend(key, jsonObject); redisTemplate.convertAndSend(key, jsonObject);
} }
@ -583,14 +581,14 @@ public class RedisCatchStorageImpl implements IRedisCatchStorage {
@Override @Override
public void sendMobilePositionMsg(JSONObject jsonObject) { public void sendMobilePositionMsg(JSONObject jsonObject) {
String key = VideoManagerConstants.VM_MSG_SUBSCRIBE_MOBILE_POSITION; String key = VideoManagerConstants.VM_MSG_SUBSCRIBE_MOBILE_POSITION;
logger.debug("[redis发送通知] 发送 移动位置 {}: {}", key, jsonObject.toString()); log.debug("[redis发送通知] 发送 移动位置 {}: {}", key, jsonObject.toString());
redisTemplate.convertAndSend(key, jsonObject); redisTemplate.convertAndSend(key, jsonObject);
} }
@Override @Override
public void sendStreamPushRequestedMsg(MessageForPushChannel msg) { public void sendStreamPushRequestedMsg(MessageForPushChannel msg) {
String key = VideoManagerConstants.VM_MSG_STREAM_PUSH_REQUESTED; String key = VideoManagerConstants.VM_MSG_STREAM_PUSH_REQUESTED;
logger.info("[redis发送通知] 发送 推流被请求 {}: {}/{}", key, msg.getApp(), msg.getStream()); log.info("[redis发送通知] 发送 推流被请求 {}: {}/{}", key, msg.getApp(), msg.getStream());
redisTemplate.convertAndSend(key, JSON.toJSON(msg)); redisTemplate.convertAndSend(key, JSON.toJSON(msg));
} }
@ -598,7 +596,7 @@ public class RedisCatchStorageImpl implements IRedisCatchStorage {
public void sendAlarmMsg(AlarmChannelMessage msg) { public void sendAlarmMsg(AlarmChannelMessage msg) {
// 此消息用于对接第三方服务下级来的消息内容 // 此消息用于对接第三方服务下级来的消息内容
String key = VideoManagerConstants.VM_MSG_SUBSCRIBE_ALARM; String key = VideoManagerConstants.VM_MSG_SUBSCRIBE_ALARM;
logger.info("[redis发送通知] 发送 报警{}: {}", key, JSON.toJSON(msg)); log.info("[redis发送通知] 发送 报警{}: {}", key, JSON.toJSON(msg));
redisTemplate.convertAndSend(key, JSON.toJSON(msg)); redisTemplate.convertAndSend(key, JSON.toJSON(msg));
} }
@ -611,7 +609,7 @@ public class RedisCatchStorageImpl implements IRedisCatchStorage {
@Override @Override
public void sendStreamPushRequestedMsgForStatus() { public void sendStreamPushRequestedMsgForStatus() {
String key = VideoManagerConstants.VM_MSG_GET_ALL_ONLINE_REQUESTED; String key = VideoManagerConstants.VM_MSG_GET_ALL_ONLINE_REQUESTED;
logger.info("[redis通知] 发送 获取所有推流设备的状态"); log.info("[redis通知] 发送 获取所有推流设备的状态");
JSONObject jsonObject = new JSONObject(); JSONObject jsonObject = new JSONObject();
jsonObject.put(key, key); jsonObject.put(key, key);
redisTemplate.convertAndSend(key, jsonObject); redisTemplate.convertAndSend(key, jsonObject);
@ -645,7 +643,7 @@ public class RedisCatchStorageImpl implements IRedisCatchStorage {
msg.append(":").append(channelId); msg.append(":").append(channelId);
} }
msg.append(" ").append(online? "ON":"OFF"); msg.append(" ").append(online? "ON":"OFF");
logger.info("[redis通知] 推送设备/通道状态-> {} ", msg); log.info("[redis通知] 推送设备/通道状态-> {} ", msg);
// 使用 RedisTemplate<Object, Object> 发送字符串消息会导致发送的消息多带了双引号 // 使用 RedisTemplate<Object, Object> 发送字符串消息会导致发送的消息多带了双引号
stringRedisTemplate.convertAndSend(key, msg.toString()); stringRedisTemplate.convertAndSend(key, msg.toString());
} }
@ -661,7 +659,7 @@ public class RedisCatchStorageImpl implements IRedisCatchStorage {
msg.append(":").append(channelId); msg.append(":").append(channelId);
} }
msg.append(" ").append(add? "ADD":"DELETE"); msg.append(" ").append(add? "ADD":"DELETE");
logger.info("[redis通知] 推送通道-> {}", msg); log.info("[redis通知] 推送通道-> {}", msg);
// 使用 RedisTemplate<Object, Object> 发送字符串消息会导致发送的消息多带了双引号 // 使用 RedisTemplate<Object, Object> 发送字符串消息会导致发送的消息多带了双引号
stringRedisTemplate.convertAndSend(key, msg.toString()); stringRedisTemplate.convertAndSend(key, msg.toString());
} }
@ -674,7 +672,7 @@ public class RedisCatchStorageImpl implements IRedisCatchStorage {
sendRtpItem.getMediaServerId()); sendRtpItem.getMediaServerId());
messageForPushChannel.setPlatFormIndex(platform.getId()); messageForPushChannel.setPlatFormIndex(platform.getId());
String key = VideoManagerConstants.VM_MSG_STREAM_START_PLAY_NOTIFY; String key = VideoManagerConstants.VM_MSG_STREAM_START_PLAY_NOTIFY;
logger.info("[redis发送通知] 发送 推流被上级平台观看 {}: {}/{}->{}", key, sendRtpItem.getApp(), sendRtpItem.getStream(), platform.getServerGBId()); log.info("[redis发送通知] 发送 推流被上级平台观看 {}: {}/{}->{}", key, sendRtpItem.getApp(), sendRtpItem.getStream(), platform.getServerGBId());
redisTemplate.convertAndSend(key, JSON.toJSON(messageForPushChannel)); redisTemplate.convertAndSend(key, JSON.toJSON(messageForPushChannel));
} }
} }
@ -688,7 +686,7 @@ public class RedisCatchStorageImpl implements IRedisCatchStorage {
msg.setPlatFormIndex(platform.getId()); msg.setPlatFormIndex(platform.getId());
String key = VideoManagerConstants.VM_MSG_STREAM_STOP_PLAY_NOTIFY; String key = VideoManagerConstants.VM_MSG_STREAM_STOP_PLAY_NOTIFY;
logger.info("[redis发送通知] 发送 上级平台停止观看 {}: {}/{}->{}", key, sendRtpItem.getApp(), sendRtpItem.getStream(), platform.getServerGBId()); log.info("[redis发送通知] 发送 上级平台停止观看 {}: {}/{}->{}", key, sendRtpItem.getApp(), sendRtpItem.getStream(), platform.getServerGBId());
redisTemplate.convertAndSend(key, JSON.toJSON(msg)); redisTemplate.convertAndSend(key, JSON.toJSON(msg));
} }
@ -717,7 +715,7 @@ public class RedisCatchStorageImpl implements IRedisCatchStorage {
@Override @Override
public void sendPushStreamClose(MessageForPushChannel msg) { public void sendPushStreamClose(MessageForPushChannel msg) {
String key = VideoManagerConstants.VM_MSG_STREAM_PUSH_CLOSE_REQUESTED; String key = VideoManagerConstants.VM_MSG_STREAM_PUSH_CLOSE_REQUESTED;
logger.info("[redis发送通知] 发送 停止向上级推流 {}: {}/{}->{}", key, msg.getApp(), msg.getStream(), msg.getPlatFormId()); log.info("[redis发送通知] 发送 停止向上级推流 {}: {}/{}->{}", key, msg.getApp(), msg.getStream(), msg.getPlatFormId());
redisTemplate.convertAndSend(key, JSON.toJSON(msg)); redisTemplate.convertAndSend(key, JSON.toJSON(msg));
} }
@ -736,14 +734,14 @@ public class RedisCatchStorageImpl implements IRedisCatchStorage {
@Override @Override
public void sendStartSendRtp(SendRtpItem sendRtpItem) { public void sendStartSendRtp(SendRtpItem sendRtpItem) {
String key = VideoManagerConstants.START_SEND_PUSH_STREAM + sendRtpItem.getApp() + "_" + sendRtpItem.getStream(); String key = VideoManagerConstants.START_SEND_PUSH_STREAM + sendRtpItem.getApp() + "_" + sendRtpItem.getStream();
logger.info("[redis发送通知] 通知其他WVP推流 {}: {}/{}->{}", key, sendRtpItem.getApp(), sendRtpItem.getStream(), sendRtpItem.getPlatformId()); log.info("[redis发送通知] 通知其他WVP推流 {}: {}/{}->{}", key, sendRtpItem.getApp(), sendRtpItem.getStream(), sendRtpItem.getPlatformId());
redisTemplate.convertAndSend(key, JSON.toJSON(sendRtpItem)); redisTemplate.convertAndSend(key, JSON.toJSON(sendRtpItem));
} }
@Override @Override
public void sendPushStreamOnline(SendRtpItem sendRtpItem) { public void sendPushStreamOnline(SendRtpItem sendRtpItem) {
String key = VideoManagerConstants.VM_MSG_STREAM_PUSH_CLOSE_REQUESTED; String key = VideoManagerConstants.VM_MSG_STREAM_PUSH_CLOSE_REQUESTED;
logger.info("[redis发送通知] 流上线 {}: {}/{}->{}", key, sendRtpItem.getApp(), sendRtpItem.getStream(), sendRtpItem.getPlatformId()); log.info("[redis发送通知] 流上线 {}: {}/{}->{}", key, sendRtpItem.getApp(), sendRtpItem.getStream(), sendRtpItem.getPlatformId());
redisTemplate.convertAndSend(key, JSON.toJSON(sendRtpItem)); redisTemplate.convertAndSend(key, JSON.toJSON(sendRtpItem));
} }
} }

View File

@ -18,8 +18,7 @@ import com.genersoft.iot.vmp.vmanager.gb28181.platform.bean.ChannelReduce;
import com.genersoft.iot.vmp.web.gb28181.dto.DeviceChannelExtend; import com.genersoft.iot.vmp.web.gb28181.dto.DeviceChannelExtend;
import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo; import com.github.pagehelper.PageInfo;
import org.slf4j.Logger; import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@ -35,12 +34,11 @@ import java.util.List;
* 2020年5月6日 下午2:31:42 * 2020年5月6日 下午2:31:42
*/ */
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
@Slf4j
@Component @Component
@DS("master") @DS("master")
public class VideoManagerStorageImpl implements IVideoManagerStorage { public class VideoManagerStorageImpl implements IVideoManagerStorage {
private final Logger logger = LoggerFactory.getLogger(VideoManagerStorageImpl.class);
@Autowired @Autowired
EventPublisher eventPublisher; EventPublisher eventPublisher;
@ -294,7 +292,7 @@ public class VideoManagerStorageImpl implements IVideoManagerStorage {
List<DeviceChannel> channels = platformChannelMapper.queryChannelInParentPlatform(platformId, channelId); List<DeviceChannel> channels = platformChannelMapper.queryChannelInParentPlatform(platformId, channelId);
if (channels.size() > 1) { if (channels.size() > 1) {
// 出现长度大于0的时候肯定是国标通道的ID重复了 // 出现长度大于0的时候肯定是国标通道的ID重复了
logger.warn("国标ID存在重复{}", channelId); log.warn("国标ID存在重复{}", channelId);
} }
if (channels.size() == 0) { if (channels.size() == 0) {
return null; return null;
@ -308,7 +306,7 @@ public class VideoManagerStorageImpl implements IVideoManagerStorage {
List<Device> devices = platformChannelMapper.queryVideoDeviceByPlatformIdAndChannelId(platformId, channelId); List<Device> devices = platformChannelMapper.queryVideoDeviceByPlatformIdAndChannelId(platformId, channelId);
if (devices.size() > 1) { if (devices.size() > 1) {
// 出现长度大于0的时候肯定是国标通道的ID重复了 // 出现长度大于0的时候肯定是国标通道的ID重复了
logger.warn("国标ID存在重复{}", channelId); log.warn("国标ID存在重复{}", channelId);
} }
if (devices.size() == 0) { if (devices.size() == 0) {
return null; return null;
@ -324,7 +322,7 @@ public class VideoManagerStorageImpl implements IVideoManagerStorage {
List<Device> devices = platformChannelMapper.queryDeviceInfoByPlatformIdAndChannelId(platformId, channelId); List<Device> devices = platformChannelMapper.queryDeviceInfoByPlatformIdAndChannelId(platformId, channelId);
if (devices.size() > 1) { if (devices.size() > 1) {
// 出现长度大于0的时候肯定是国标通道的ID重复了 // 出现长度大于0的时候肯定是国标通道的ID重复了
logger.warn("国标ID存在重复{}", channelId); log.warn("国标ID存在重复{}", channelId);
} }
if (devices.size() == 0) { if (devices.size() == 0) {
return null; return null;
@ -400,7 +398,7 @@ public class VideoManagerStorageImpl implements IVideoManagerStorage {
}else { }else {
PlatformCatalog catalog = catalogMapper.selectByPlatFormAndCatalogId(platformCatalog.getPlatformId(),platformCatalog.getParentId()); PlatformCatalog catalog = catalogMapper.selectByPlatFormAndCatalogId(platformCatalog.getPlatformId(),platformCatalog.getParentId());
if (catalog == null) { if (catalog == null) {
logger.warn("[添加目录] 无法获取目录{}的CivilCode和BusinessGroupId", platformCatalog.getPlatformId()); log.warn("[添加目录] 无法获取目录{}的CivilCode和BusinessGroupId", platformCatalog.getPlatformId());
break; break;
} }
platformCatalog.setCivilCode(catalog.getCivilCode()); platformCatalog.setCivilCode(catalog.getCivilCode());

View File

@ -2,10 +2,8 @@ package com.genersoft.iot.vmp.streamProxy.controller;
import com.alibaba.fastjson2.JSONObject; import com.alibaba.fastjson2.JSONObject;
import com.genersoft.iot.vmp.common.StreamInfo; import com.genersoft.iot.vmp.common.StreamInfo;
import com.genersoft.iot.vmp.conf.UserSetting;
import com.genersoft.iot.vmp.conf.exception.ControllerException; import com.genersoft.iot.vmp.conf.exception.ControllerException;
import com.genersoft.iot.vmp.conf.security.JwtUtils; import com.genersoft.iot.vmp.conf.security.JwtUtils;
import com.genersoft.iot.vmp.gb28181.transmit.callback.DeferredResultHolder;
import com.genersoft.iot.vmp.media.bean.MediaServer; import com.genersoft.iot.vmp.media.bean.MediaServer;
import com.genersoft.iot.vmp.media.service.IMediaServerService; import com.genersoft.iot.vmp.media.service.IMediaServerService;
import com.genersoft.iot.vmp.streamProxy.bean.StreamProxy; import com.genersoft.iot.vmp.streamProxy.bean.StreamProxy;
@ -17,8 +15,7 @@ import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger; import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils; import org.springframework.util.ObjectUtils;
@ -32,24 +29,16 @@ import java.util.Map;
*/ */
@Tag(name = "拉流代理", description = "") @Tag(name = "拉流代理", description = "")
@Controller @Controller
@Slf4j
@RequestMapping(value = "/api/proxy") @RequestMapping(value = "/api/proxy")
public class StreamProxyController { public class StreamProxyController {
private final static Logger logger = LoggerFactory.getLogger(StreamProxyController.class);
@Autowired @Autowired
private IMediaServerService mediaServerService; private IMediaServerService mediaServerService;
@Autowired @Autowired
private IStreamProxyService streamProxyService; private IStreamProxyService streamProxyService;
@Autowired
private DeferredResultHolder resultHolder;
@Autowired
private UserSetting userSetting;
@Operation(summary = "分页查询流代理", security = @SecurityRequirement(name = JwtUtils.HEADER)) @Operation(summary = "分页查询流代理", security = @SecurityRequirement(name = JwtUtils.HEADER))
@Parameter(name = "page", description = "当前页") @Parameter(name = "page", description = "当前页")
@ -82,7 +71,7 @@ public class StreamProxyController {
@PostMapping(value = "/save") @PostMapping(value = "/save")
@ResponseBody @ResponseBody
public StreamContent save(@RequestBody StreamProxy param){ public StreamContent save(@RequestBody StreamProxy param){
logger.info("添加代理: " + JSONObject.toJSONString(param)); log.info("添加代理: " + JSONObject.toJSONString(param));
if (ObjectUtils.isEmpty(param.getMediaServerId())) { if (ObjectUtils.isEmpty(param.getMediaServerId())) {
param.setMediaServerId("auto"); param.setMediaServerId("auto");
} }
@ -115,7 +104,7 @@ public class StreamProxyController {
@Operation(summary = "获取ffmpeg.cmd模板", security = @SecurityRequirement(name = JwtUtils.HEADER)) @Operation(summary = "获取ffmpeg.cmd模板", security = @SecurityRequirement(name = JwtUtils.HEADER))
@Parameter(name = "mediaServerId", description = "流媒体ID", required = true) @Parameter(name = "mediaServerId", description = "流媒体ID", required = true)
public Map<String, String> getFFmpegCMDs(@RequestParam String mediaServerId){ public Map<String, String> getFFmpegCMDs(@RequestParam String mediaServerId){
logger.debug("获取节点[ {} ]ffmpeg.cmd模板", mediaServerId ); log.debug("获取节点[ {} ]ffmpeg.cmd模板", mediaServerId );
MediaServer mediaServerItem = mediaServerService.getOne(mediaServerId); MediaServer mediaServerItem = mediaServerService.getOne(mediaServerId);
if (mediaServerItem == null) { if (mediaServerItem == null) {
@ -130,7 +119,7 @@ public class StreamProxyController {
@Parameter(name = "app", description = "应用名", required = true) @Parameter(name = "app", description = "应用名", required = true)
@Parameter(name = "stream", description = "流id", required = true) @Parameter(name = "stream", description = "流id", required = true)
public void del(@RequestParam String app, @RequestParam String stream){ public void del(@RequestParam String app, @RequestParam String stream){
logger.info("移除代理: " + app + "/" + stream); log.info("移除代理: " + app + "/" + stream);
if (app == null || stream == null) { if (app == null || stream == null) {
throw new ControllerException(ErrorCode.ERROR400.getCode(), app == null ?"app不能为null":"stream不能为null"); throw new ControllerException(ErrorCode.ERROR400.getCode(), app == null ?"app不能为null":"stream不能为null");
}else { }else {
@ -144,7 +133,7 @@ public class StreamProxyController {
@Parameter(name = "app", description = "应用名", required = true) @Parameter(name = "app", description = "应用名", required = true)
@Parameter(name = "stream", description = "流id", required = true) @Parameter(name = "stream", description = "流id", required = true)
public void start(String app, String stream){ public void start(String app, String stream){
logger.info("启用代理: " + app + "/" + stream); log.info("启用代理: " + app + "/" + stream);
boolean result = streamProxyService.start(app, stream); boolean result = streamProxyService.start(app, stream);
if (!result) { if (!result) {
throw new ControllerException(ErrorCode.ERROR100); throw new ControllerException(ErrorCode.ERROR100);
@ -157,7 +146,7 @@ public class StreamProxyController {
@Parameter(name = "app", description = "应用名", required = true) @Parameter(name = "app", description = "应用名", required = true)
@Parameter(name = "stream", description = "流id", required = true) @Parameter(name = "stream", description = "流id", required = true)
public void stop(String app, String stream){ public void stop(String app, String stream){
logger.info("停用代理: " + app + "/" + stream); log.info("停用代理: " + app + "/" + stream);
streamProxyService.stop(app, stream); streamProxyService.stop(app, stream);
} }
} }

View File

@ -11,20 +11,21 @@ import com.genersoft.iot.vmp.conf.security.SecurityUtils;
import com.genersoft.iot.vmp.conf.security.dto.LoginUser; import com.genersoft.iot.vmp.conf.security.dto.LoginUser;
import com.genersoft.iot.vmp.gb28181.transmit.callback.DeferredResultHolder; import com.genersoft.iot.vmp.gb28181.transmit.callback.DeferredResultHolder;
import com.genersoft.iot.vmp.gb28181.transmit.callback.RequestMessage; import com.genersoft.iot.vmp.gb28181.transmit.callback.RequestMessage;
import com.genersoft.iot.vmp.streamPush.bean.StreamPush;
import com.genersoft.iot.vmp.media.service.IMediaServerService; import com.genersoft.iot.vmp.media.service.IMediaServerService;
import com.genersoft.iot.vmp.service.IMediaService; import com.genersoft.iot.vmp.service.IMediaService;
import com.genersoft.iot.vmp.streamPush.bean.StreamPush;
import com.genersoft.iot.vmp.streamPush.bean.StreamPushExcelDto; import com.genersoft.iot.vmp.streamPush.bean.StreamPushExcelDto;
import com.genersoft.iot.vmp.streamPush.service.IStreamPushService;
import com.genersoft.iot.vmp.streamPush.enent.StreamPushUploadFileHandler; import com.genersoft.iot.vmp.streamPush.enent.StreamPushUploadFileHandler;
import com.genersoft.iot.vmp.vmanager.bean.*; import com.genersoft.iot.vmp.streamPush.service.IStreamPushService;
import com.genersoft.iot.vmp.vmanager.bean.ErrorCode;
import com.genersoft.iot.vmp.vmanager.bean.StreamContent;
import com.genersoft.iot.vmp.vmanager.bean.WVPResult;
import com.github.pagehelper.PageInfo; import com.github.pagehelper.PageInfo;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger; import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
@ -43,12 +44,10 @@ import java.util.UUID;
@Tag(name = "推流信息管理") @Tag(name = "推流信息管理")
@Controller @Controller
@Slf4j
@RequestMapping(value = "/api/push") @RequestMapping(value = "/api/push")
public class StreamPushController { public class StreamPushController {
private final static Logger logger = LoggerFactory.getLogger(StreamPushController.class);
@Autowired @Autowired
private IStreamPushService streamPushService; private IStreamPushService streamPushService;
@ -109,9 +108,9 @@ public class StreamPushController {
// 录像查询以channelId作为deviceId查询 // 录像查询以channelId作为deviceId查询
String key = DeferredResultHolder.UPLOAD_FILE_CHANNEL; String key = DeferredResultHolder.UPLOAD_FILE_CHANNEL;
String uuid = UUID.randomUUID().toString(); String uuid = UUID.randomUUID().toString();
logger.info("通道导入文件类型: {}",file.getContentType() ); log.info("通道导入文件类型: {}",file.getContentType() );
if (file.isEmpty()) { if (file.isEmpty()) {
logger.warn("通道导入文件为空"); log.warn("通道导入文件为空");
WVPResult<Object> wvpResult = new WVPResult<>(); WVPResult<Object> wvpResult = new WVPResult<>();
wvpResult.setCode(-1); wvpResult.setCode(-1);
wvpResult.setMsg("文件为空"); wvpResult.setMsg("文件为空");
@ -127,7 +126,7 @@ public class StreamPushController {
} }
// 同时只处理一个文件 // 同时只处理一个文件
if (resultHolder.exist(key, null)) { if (resultHolder.exist(key, null)) {
logger.warn("已有导入任务正在执行"); log.warn("已有导入任务正在执行");
WVPResult<Object> wvpResult = new WVPResult<>(); WVPResult<Object> wvpResult = new WVPResult<>();
wvpResult.setCode(-1); wvpResult.setCode(-1);
wvpResult.setMsg("已有导入任务正在执行"); wvpResult.setMsg("已有导入任务正在执行");
@ -137,7 +136,7 @@ public class StreamPushController {
resultHolder.put(key, uuid, result); resultHolder.put(key, uuid, result);
result.onTimeout(()->{ result.onTimeout(()->{
logger.warn("通道导入超时,可能文件过大"); log.warn("通道导入超时,可能文件过大");
RequestMessage msg = new RequestMessage(); RequestMessage msg = new RequestMessage();
msg.setKey(key); msg.setKey(key);
WVPResult<Object> wvpResult = new WVPResult<>(); WVPResult<Object> wvpResult = new WVPResult<>();
@ -152,13 +151,13 @@ public class StreamPushController {
String name = file.getName(); String name = file.getName();
inputStream = file.getInputStream(); inputStream = file.getInputStream();
} catch (IOException e) { } catch (IOException e) {
logger.error("未处理的异常 ", e); log.error("未处理的异常 ", e);
} }
try { try {
//传入参数 //传入参数
ExcelReader excelReader = EasyExcel.read(inputStream, StreamPushExcelDto.class, ExcelReader excelReader = EasyExcel.read(inputStream, StreamPushExcelDto.class,
new StreamPushUploadFileHandler(streamPushService, mediaServerService.getDefaultMediaServer().getId(), (errorStreams, errorGBs)->{ new StreamPushUploadFileHandler(streamPushService, mediaServerService.getDefaultMediaServer().getId(), (errorStreams, errorGBs)->{
logger.info("通道导入成功存在重复App+Stream为{}个存在国标ID为{}个", errorStreams.size(), errorGBs.size()); log.info("通道导入成功存在重复App+Stream为{}个存在国标ID为{}个", errorStreams.size(), errorGBs.size());
RequestMessage msg = new RequestMessage(); RequestMessage msg = new RequestMessage();
msg.setKey(key); msg.setKey(key);
WVPResult<Map<String, List<String>>> wvpResult = new WVPResult<>(); WVPResult<Map<String, List<String>>> wvpResult = new WVPResult<>();
@ -180,7 +179,7 @@ public class StreamPushController {
excelReader.read(readSheet); excelReader.read(readSheet);
excelReader.finish(); excelReader.finish();
}catch (Exception e) { }catch (Exception e) {
logger.warn("通道导入失败:", e); log.warn("通道导入失败:", e);
RequestMessage msg = new RequestMessage(); RequestMessage msg = new RequestMessage();
msg.setKey(key); msg.setKey(key);
WVPResult<Object> wvpResult = new WVPResult<>(); WVPResult<Object> wvpResult = new WVPResult<>();

View File

@ -1,18 +1,16 @@
package com.genersoft.iot.vmp.utils; package com.genersoft.iot.vmp.utils;
import com.genersoft.iot.vmp.common.CivilCodePo; import com.genersoft.iot.vmp.common.CivilCodePo;
import org.slf4j.Logger; import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
@Slf4j
public enum CivilCodeUtil { public enum CivilCodeUtil {
INSTANCE; INSTANCE;
private final static Logger logger = LoggerFactory.getLogger(CivilCodeUtil.class);
// 用与消息的缓存 // 用与消息的缓存
private final Map<String, CivilCodePo> civilCodeMap = new ConcurrentHashMap<>(); private final Map<String, CivilCodePo> civilCodeMap = new ConcurrentHashMap<>();

View File

@ -1,18 +1,13 @@
package com.genersoft.iot.vmp.utils; package com.genersoft.iot.vmp.utils;
import java.io.BufferedReader; import com.genersoft.iot.vmp.gb28181.bean.BaiduPoint;
import java.io.InputStreamReader; import lombok.extern.slf4j.Slf4j;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Base64; import java.util.Base64;
import com.genersoft.iot.vmp.gb28181.bean.BaiduPoint; @Slf4j
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class GpsUtil { public class GpsUtil {
private static Logger logger = LoggerFactory.getLogger(GpsUtil.class);
public static BaiduPoint Wgs84ToBd09(String xx, String yy) { public static BaiduPoint Wgs84ToBd09(String xx, String yy) {

View File

@ -1,16 +1,14 @@
package com.genersoft.iot.vmp.utils; package com.genersoft.iot.vmp.utils;
import com.genersoft.iot.vmp.media.zlm.ZLMHttpHookListener; import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ObjectUtils;
import oshi.SystemInfo; import oshi.SystemInfo;
import oshi.hardware.*; import oshi.hardware.CentralProcessor;
import oshi.hardware.GlobalMemory;
import oshi.hardware.HardwareAbstractionLayer;
import oshi.hardware.NetworkIF;
import oshi.software.os.OperatingSystem; import oshi.software.os.OperatingSystem;
import oshi.util.FormatUtil;
import java.io.File; import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@ -22,10 +20,9 @@ import java.util.concurrent.TimeUnit;
* 版权声明本文为xiaozhangnomoney原创文章遵循 CC 4.0 BY-SA 版权协议转载请附上原文出处链接和本声明 * 版权声明本文为xiaozhangnomoney原创文章遵循 CC 4.0 BY-SA 版权协议转载请附上原文出处链接和本声明
* 原文出处链接https://blog.csdn.net/xiaozhangnomoney/article/details/107769147 * 原文出处链接https://blog.csdn.net/xiaozhangnomoney/article/details/107769147
*/ */
@Slf4j
public class SystemInfoUtils { public class SystemInfoUtils {
private final static Logger logger = LoggerFactory.getLogger(SystemInfoUtils.class);
/** /**
* 获取cpu信息 * 获取cpu信息
* @return * @return
@ -78,7 +75,7 @@ public class SystemInfoUtils {
try { try {
Thread.sleep(1000); Thread.sleep(1000);
} catch (InterruptedException e) { } catch (InterruptedException e) {
logger.error("[线程休眠失败] : {}", e.getMessage()); log.error("[线程休眠失败] : {}", e.getMessage());
} }
List<NetworkIF> afterNetworkIFs = hal.getNetworkIFs(); List<NetworkIF> afterNetworkIFs = hal.getNetworkIFs();
NetworkIF afterNet = afterNetworkIFs.get(afterNetworkIFs.size() - 1); NetworkIF afterNet = afterNetworkIFs.get(afterNetworkIFs.size() - 1);

View File

@ -4,9 +4,8 @@ import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map; import java.util.Map;
@ -17,9 +16,9 @@ import java.util.Objects;
* @version 1.0 * @version 1.0
* @date 2022/3/11 10:17 * @date 2022/3/11 10:17
*/ */
@Slf4j
public class UJson { public class UJson {
private static Logger logger = LoggerFactory.getLogger(UJson.class);
public static final ObjectMapper JSON_MAPPER = new ObjectMapper(); public static final ObjectMapper JSON_MAPPER = new ObjectMapper();
static { static {
@ -39,7 +38,7 @@ public class UJson {
try { try {
this.node = JSON_MAPPER.readValue(json, ObjectNode.class); this.node = JSON_MAPPER.readValue(json, ObjectNode.class);
}catch (Exception e){ }catch (Exception e){
logger.error(e.getMessage(), e); log.error(e.getMessage(), e);
this.node = JSON_MAPPER.createObjectNode(); this.node = JSON_MAPPER.createObjectNode();
} }
} }
@ -90,7 +89,7 @@ public class UJson {
try { try {
return JSON_MAPPER.readValue(json, clazz); return JSON_MAPPER.readValue(json, clazz);
}catch (Exception e){ }catch (Exception e){
logger.error(e.getMessage(), e); log.error(e.getMessage(), e);
return null; return null;
} }
} }
@ -99,7 +98,7 @@ public class UJson {
try{ try{
return JSON_MAPPER.writeValueAsString(object); return JSON_MAPPER.writeValueAsString(object);
}catch (Exception e){ }catch (Exception e){
logger.error(e.getMessage(), e); log.error(e.getMessage(), e);
return ""; return "";
} }
} }

View File

@ -4,8 +4,8 @@ import com.alibaba.fastjson2.JSONArray;
import com.genersoft.iot.vmp.conf.exception.ControllerException; import com.genersoft.iot.vmp.conf.exception.ControllerException;
import com.genersoft.iot.vmp.conf.security.JwtUtils; import com.genersoft.iot.vmp.conf.security.JwtUtils;
import com.genersoft.iot.vmp.media.bean.MediaServer; import com.genersoft.iot.vmp.media.bean.MediaServer;
import com.genersoft.iot.vmp.service.ICloudRecordService;
import com.genersoft.iot.vmp.media.service.IMediaServerService; import com.genersoft.iot.vmp.media.service.IMediaServerService;
import com.genersoft.iot.vmp.service.ICloudRecordService;
import com.genersoft.iot.vmp.service.bean.CloudRecordItem; import com.genersoft.iot.vmp.service.bean.CloudRecordItem;
import com.genersoft.iot.vmp.service.bean.DownloadFileInfo; import com.genersoft.iot.vmp.service.bean.DownloadFileInfo;
import com.genersoft.iot.vmp.utils.DateUtil; import com.genersoft.iot.vmp.utils.DateUtil;
@ -16,9 +16,8 @@ import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@ -35,14 +34,12 @@ import java.util.zip.ZipOutputStream;
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
@Tag(name = "云端录像接口") @Tag(name = "云端录像接口")
@Slf4j
@RestController @RestController
@RequestMapping("/api/cloud/record") @RequestMapping("/api/cloud/record")
public class CloudRecordController { public class CloudRecordController {
private final static Logger logger = LoggerFactory.getLogger(CloudRecordController.class);
@Autowired @Autowired
private ICloudRecordService cloudRecordService; private ICloudRecordService cloudRecordService;
@ -66,7 +63,7 @@ public class CloudRecordController {
@RequestParam(required = false) String mediaServerId @RequestParam(required = false) String mediaServerId
) { ) {
logger.info("[云端录像] 查询存在云端录像的日期 app->{}, stream->{}, mediaServerId->{}, year->{}, month->{}", log.info("[云端录像] 查询存在云端录像的日期 app->{}, stream->{}, mediaServerId->{}, year->{}, month->{}",
app, stream, mediaServerId, year, month); app, stream, mediaServerId, year, month);
Calendar calendar = Calendar.getInstance(); Calendar calendar = Calendar.getInstance();
if (ObjectUtils.isEmpty(year)) { if (ObjectUtils.isEmpty(year)) {
@ -117,7 +114,7 @@ public class CloudRecordController {
@RequestParam(required = false) String callId @RequestParam(required = false) String callId
) { ) {
logger.info("[云端录像] 查询 app->{}, stream->{}, mediaServerId->{}, page->{}, count->{}, startTime->{}, endTime->{}, callId->{}", log.info("[云端录像] 查询 app->{}, stream->{}, mediaServerId->{}, page->{}, count->{}, startTime->{}, endTime->{}, callId->{}",
app, stream, mediaServerId, page, count, startTime, endTime, callId); app, stream, mediaServerId, page, count, startTime, endTime, callId);
List<MediaServer> mediaServers; List<MediaServer> mediaServers;
@ -232,7 +229,7 @@ public class CloudRecordController {
@RequestParam(required = false) String callId, @RequestParam(required = false) String callId,
@RequestParam(required = false) Integer recordId @RequestParam(required = false) Integer recordId
){ ){
logger.info("[云端录像] 添加收藏app={}stream={},mediaServerId={},startTime={},endTime={},callId={},recordId={}", log.info("[云端录像] 添加收藏app={}stream={},mediaServerId={},startTime={},endTime={},callId={},recordId={}",
app, stream, mediaServerId, startTime, endTime, callId, recordId); app, stream, mediaServerId, startTime, endTime, callId, recordId);
if (recordId != null) { if (recordId != null) {
return cloudRecordService.changeCollectById(recordId, true); return cloudRecordService.changeCollectById(recordId, true);
@ -260,7 +257,7 @@ public class CloudRecordController {
@RequestParam(required = false) String callId, @RequestParam(required = false) String callId,
@RequestParam(required = false) Integer recordId @RequestParam(required = false) Integer recordId
){ ){
logger.info("[云端录像] 移除收藏app={}stream={},mediaServerId={},startTime={},endTime={},callId={},recordId={}", log.info("[云端录像] 移除收藏app={}stream={},mediaServerId={},startTime={},endTime={},callId={},recordId={}",
app, stream, mediaServerId, startTime, endTime, callId, recordId); app, stream, mediaServerId, startTime, endTime, callId, recordId);
if (recordId != null) { if (recordId != null) {
return cloudRecordService.changeCollectById(recordId, false); return cloudRecordService.changeCollectById(recordId, false);
@ -306,7 +303,7 @@ public class CloudRecordController {
@RequestParam(required = false) List<Integer> ids @RequestParam(required = false) List<Integer> ids
) { ) {
logger.info("[下载指定录像文件的压缩包] 查询 app->{}, stream->{}, mediaServerId->{}, startTime->{}, endTime->{}, callId->{}", log.info("[下载指定录像文件的压缩包] 查询 app->{}, stream->{}, mediaServerId->{}, startTime->{}, endTime->{}, callId->{}",
app, stream, mediaServerId, startTime, endTime, callId); app, stream, mediaServerId, startTime, endTime, callId);
List<MediaServer> mediaServers; List<MediaServer> mediaServers;
@ -367,7 +364,7 @@ public class CloudRecordController {
} }
zos.close(); zos.close();
} catch (IOException e) { } catch (IOException e) {
logger.error("[下载指定录像文件的压缩包] 失败: 查询 app->{}, stream->{}, mediaServerId->{}, startTime->{}, endTime->{}, callId->{}", log.error("[下载指定录像文件的压缩包] 失败: 查询 app->{}, stream->{}, mediaServerId->{}, startTime->{}, endTime->{}, callId->{}",
app, stream, mediaServerId, startTime, endTime, callId, e); app, stream, mediaServerId, startTime, endTime, callId, e);
} }
} }
@ -409,7 +406,7 @@ public class CloudRecordController {
@RequestParam(required = false) String remoteHost @RequestParam(required = false) String remoteHost
) { ) {
logger.info("[云端录像] 查询URL app->{}, stream->{}, mediaServerId->{}, page->{}, count->{}, startTime->{}, endTime->{}, callId->{}", log.info("[云端录像] 查询URL app->{}, stream->{}, mediaServerId->{}, page->{}, count->{}, startTime->{}, endTime->{}, callId->{}",
app, stream, mediaServerId, page, count, startTime, endTime, callId); app, stream, mediaServerId, page, count, startTime, endTime, callId);
List<MediaServer> mediaServers; List<MediaServer> mediaServers;

View File

@ -16,8 +16,7 @@ import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger; import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.async.DeferredResult; import org.springframework.web.context.request.async.DeferredResult;
@ -32,13 +31,11 @@ import java.util.UUID;
* 位置信息管理 * 位置信息管理
*/ */
@Tag(name = "位置信息管理") @Tag(name = "位置信息管理")
@Slf4j
@RestController @RestController
@RequestMapping("/api/position") @RequestMapping("/api/position")
public class MobilePositionController { public class MobilePositionController {
private final static Logger logger = LoggerFactory.getLogger(MobilePositionController.class);
@Autowired @Autowired
private IVideoManagerStorage storager; private IVideoManagerStorage storager;
@ -114,12 +111,12 @@ public class MobilePositionController {
resultHolder.invokeResult(msg); resultHolder.invokeResult(msg);
}); });
} catch (InvalidArgumentException | SipException | ParseException e) { } catch (InvalidArgumentException | SipException | ParseException e) {
logger.error("[命令发送失败] 获取移动位置信息: {}", e.getMessage()); log.error("[命令发送失败] 获取移动位置信息: {}", e.getMessage());
throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage()); throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage());
} }
DeferredResult<MobilePosition> result = new DeferredResult<MobilePosition>(5*1000L); DeferredResult<MobilePosition> result = new DeferredResult<MobilePosition>(5*1000L);
result.onTimeout(()->{ result.onTimeout(()->{
logger.warn(String.format("获取移动位置信息超时")); log.warn(String.format("获取移动位置信息超时"));
// 释放rtpserver // 释放rtpserver
RequestMessage msg = new RequestMessage(); RequestMessage msg = new RequestMessage();
msg.setId(uuid); msg.setId(uuid);

View File

@ -16,8 +16,7 @@ import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger; import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils; import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@ -29,13 +28,11 @@ import java.util.Arrays;
import java.util.List; import java.util.List;
@Tag(name = "报警信息管理") @Tag(name = "报警信息管理")
@Slf4j
@RestController @RestController
@RequestMapping("/api/alarm") @RequestMapping("/api/alarm")
public class AlarmController { public class AlarmController {
private final static Logger logger = LoggerFactory.getLogger(AlarmController.class);
@Autowired @Autowired
private IDeviceAlarmService deviceAlarmService; private IDeviceAlarmService deviceAlarmService;
@ -121,7 +118,7 @@ public class AlarmController {
try { try {
commanderForPlatform.sendAlarmMessage(platform, deviceAlarm); commanderForPlatform.sendAlarmMessage(platform, deviceAlarm);
} catch (SipException | InvalidArgumentException | ParseException e) { } catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] 国标级联 发送BYE: {}", e.getMessage()); log.error("[命令发送失败] 国标级联 发送BYE: {}", e.getMessage());
throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage()); throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage());
} }
}else { }else {

View File

@ -20,8 +20,7 @@ import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger; import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils; import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@ -32,13 +31,12 @@ import javax.sip.SipException;
import java.text.ParseException; import java.text.ParseException;
import java.util.UUID; import java.util.UUID;
@Slf4j
@Tag(name = "国标设备配置") @Tag(name = "国标设备配置")
@RestController @RestController
@RequestMapping("/api/device/config") @RequestMapping("/api/device/config")
public class DeviceConfig { public class DeviceConfig {
private final static Logger logger = LoggerFactory.getLogger(DeviceQuery.class);
@Autowired @Autowired
private IVideoManagerStorage storager; private IVideoManagerStorage storager;
@ -72,8 +70,8 @@ public class DeviceConfig {
@RequestParam(required = false) String expiration, @RequestParam(required = false) String expiration,
@RequestParam(required = false) String heartBeatInterval, @RequestParam(required = false) String heartBeatInterval,
@RequestParam(required = false) String heartBeatCount) { @RequestParam(required = false) String heartBeatCount) {
if (logger.isDebugEnabled()) { if (log.isDebugEnabled()) {
logger.debug("报警复位API调用"); log.debug("报警复位API调用");
} }
Device device = storager.queryVideoDevice(deviceId); Device device = storager.queryVideoDevice(deviceId);
String uuid = UUID.randomUUID().toString(); String uuid = UUID.randomUUID().toString();
@ -87,12 +85,12 @@ public class DeviceConfig {
resultHolder.invokeResult(msg); resultHolder.invokeResult(msg);
}); });
} catch (InvalidArgumentException | SipException | ParseException e) { } catch (InvalidArgumentException | SipException | ParseException e) {
logger.error("[命令发送失败] 设备配置: {}", e.getMessage()); log.error("[命令发送失败] 设备配置: {}", e.getMessage());
throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage()); throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage());
} }
DeferredResult<String> result = new DeferredResult<String>(3 * 1000L); DeferredResult<String> result = new DeferredResult<String>(3 * 1000L);
result.onTimeout(() -> { result.onTimeout(() -> {
logger.warn(String.format("设备配置操作超时, 设备未返回应答指令")); log.warn(String.format("设备配置操作超时, 设备未返回应答指令"));
// 释放rtpserver // 释放rtpserver
RequestMessage msg = new RequestMessage(); RequestMessage msg = new RequestMessage();
msg.setId(uuid); msg.setId(uuid);
@ -123,8 +121,8 @@ public class DeviceConfig {
public DeferredResult<String> configDownloadApi(@PathVariable String deviceId, public DeferredResult<String> configDownloadApi(@PathVariable String deviceId,
@PathVariable String configType, @PathVariable String configType,
@RequestParam(required = false) String channelId) { @RequestParam(required = false) String channelId) {
if (logger.isDebugEnabled()) { if (log.isDebugEnabled()) {
logger.debug("设备状态查询API调用"); log.debug("设备状态查询API调用");
} }
String key = DeferredResultHolder.CALLBACK_CMD_CONFIGDOWNLOAD + (ObjectUtils.isEmpty(channelId) ? deviceId : channelId); String key = DeferredResultHolder.CALLBACK_CMD_CONFIGDOWNLOAD + (ObjectUtils.isEmpty(channelId) ? deviceId : channelId);
String uuid = UUID.randomUUID().toString(); String uuid = UUID.randomUUID().toString();
@ -138,12 +136,12 @@ public class DeviceConfig {
resultHolder.invokeResult(msg); resultHolder.invokeResult(msg);
}); });
} catch (InvalidArgumentException | SipException | ParseException e) { } catch (InvalidArgumentException | SipException | ParseException e) {
logger.error("[命令发送失败] 获取设备配置: {}", e.getMessage()); log.error("[命令发送失败] 获取设备配置: {}", e.getMessage());
throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage()); throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage());
} }
DeferredResult<String> result = new DeferredResult<String > (3 * 1000L); DeferredResult<String> result = new DeferredResult<String > (3 * 1000L);
result.onTimeout(()->{ result.onTimeout(()->{
logger.warn(String.format("获取设备配置超时")); log.warn(String.format("获取设备配置超时"));
// 释放rtpserver // 释放rtpserver
RequestMessage msg = new RequestMessage(); RequestMessage msg = new RequestMessage();
msg.setId(uuid); msg.setId(uuid);

View File

@ -20,8 +20,7 @@ import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger; import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.util.ObjectUtils; import org.springframework.util.ObjectUtils;
@ -34,13 +33,11 @@ import java.text.ParseException;
import java.util.UUID; import java.util.UUID;
@Tag(name = "国标设备控制") @Tag(name = "国标设备控制")
@Slf4j
@RestController @RestController
@RequestMapping("/api/device/control") @RequestMapping("/api/device/control")
public class DeviceControl { public class DeviceControl {
private final static Logger logger = LoggerFactory.getLogger(DeviceQuery.class);
@Autowired @Autowired
private IVideoManagerStorage storager; private IVideoManagerStorage storager;
@ -59,14 +56,14 @@ public class DeviceControl {
@Parameter(name = "deviceId", description = "设备国标编号", required = true) @Parameter(name = "deviceId", description = "设备国标编号", required = true)
@GetMapping("/teleboot/{deviceId}") @GetMapping("/teleboot/{deviceId}")
public void teleBootApi(@PathVariable String deviceId) { public void teleBootApi(@PathVariable String deviceId) {
if (logger.isDebugEnabled()) { if (log.isDebugEnabled()) {
logger.debug("设备远程启动API调用"); log.debug("设备远程启动API调用");
} }
Device device = storager.queryVideoDevice(deviceId); Device device = storager.queryVideoDevice(deviceId);
try { try {
cmder.teleBootCmd(device); cmder.teleBootCmd(device);
} catch (InvalidArgumentException | SipException | ParseException e) { } catch (InvalidArgumentException | SipException | ParseException e) {
logger.error("[命令发送失败] 远程启动: {}", e.getMessage()); log.error("[命令发送失败] 远程启动: {}", e.getMessage());
throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage()); throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage());
} }
} }
@ -85,15 +82,15 @@ public class DeviceControl {
@GetMapping("/record/{deviceId}/{recordCmdStr}") @GetMapping("/record/{deviceId}/{recordCmdStr}")
public DeferredResult<ResponseEntity<String>> recordApi(@PathVariable String deviceId, public DeferredResult<ResponseEntity<String>> recordApi(@PathVariable String deviceId,
@PathVariable String recordCmdStr, String channelId) { @PathVariable String recordCmdStr, String channelId) {
if (logger.isDebugEnabled()) { if (log.isDebugEnabled()) {
logger.debug("开始/停止录像API调用"); log.debug("开始/停止录像API调用");
} }
Device device = storager.queryVideoDevice(deviceId); Device device = storager.queryVideoDevice(deviceId);
String uuid = UUID.randomUUID().toString(); String uuid = UUID.randomUUID().toString();
String key = DeferredResultHolder.CALLBACK_CMD_DEVICECONTROL + deviceId + channelId; String key = DeferredResultHolder.CALLBACK_CMD_DEVICECONTROL + deviceId + channelId;
DeferredResult<ResponseEntity<String>> result = new DeferredResult<ResponseEntity<String>>(3 * 1000L); DeferredResult<ResponseEntity<String>> result = new DeferredResult<ResponseEntity<String>>(3 * 1000L);
result.onTimeout(() -> { result.onTimeout(() -> {
logger.warn(String.format("开始/停止录像操作超时, 设备未返回应答指令")); log.warn(String.format("开始/停止录像操作超时, 设备未返回应答指令"));
// 释放rtpserver // 释放rtpserver
RequestMessage msg = new RequestMessage(); RequestMessage msg = new RequestMessage();
msg.setKey(key); msg.setKey(key);
@ -114,7 +111,7 @@ public class DeviceControl {
resultHolder.invokeAllResult(msg); resultHolder.invokeAllResult(msg);
},null); },null);
} catch (InvalidArgumentException | SipException | ParseException e) { } catch (InvalidArgumentException | SipException | ParseException e) {
logger.error("[命令发送失败] 开始/停止录像: {}", e.getMessage()); log.error("[命令发送失败] 开始/停止录像: {}", e.getMessage());
throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage()); throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage());
} }
@ -132,8 +129,8 @@ public class DeviceControl {
@Parameter(name = "guardCmdStr", description = "命令, 可选值SetGuard布防ResetGuard撤防", required = true) @Parameter(name = "guardCmdStr", description = "命令, 可选值SetGuard布防ResetGuard撤防", required = true)
@GetMapping("/guard/{deviceId}/{guardCmdStr}") @GetMapping("/guard/{deviceId}/{guardCmdStr}")
public DeferredResult<String> guardApi(@PathVariable String deviceId, @PathVariable String guardCmdStr) { public DeferredResult<String> guardApi(@PathVariable String deviceId, @PathVariable String guardCmdStr) {
if (logger.isDebugEnabled()) { if (log.isDebugEnabled()) {
logger.debug("布防/撤防API调用"); log.debug("布防/撤防API调用");
} }
Device device = storager.queryVideoDevice(deviceId); Device device = storager.queryVideoDevice(deviceId);
String key = DeferredResultHolder.CALLBACK_CMD_DEVICECONTROL + deviceId + deviceId; String key = DeferredResultHolder.CALLBACK_CMD_DEVICECONTROL + deviceId + deviceId;
@ -147,13 +144,13 @@ public class DeviceControl {
resultHolder.invokeResult(msg); resultHolder.invokeResult(msg);
},null); },null);
} catch (InvalidArgumentException | SipException | ParseException e) { } catch (InvalidArgumentException | SipException | ParseException e) {
logger.error("[命令发送失败] 布防/撤防操作: {}", e.getMessage()); log.error("[命令发送失败] 布防/撤防操作: {}", e.getMessage());
throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送: " + e.getMessage()); throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送: " + e.getMessage());
} }
DeferredResult<String> result = new DeferredResult<>(3 * 1000L); DeferredResult<String> result = new DeferredResult<>(3 * 1000L);
resultHolder.put(key, uuid, result); resultHolder.put(key, uuid, result);
result.onTimeout(() -> { result.onTimeout(() -> {
logger.warn(String.format("布防/撤防操作超时, 设备未返回应答指令")); log.warn(String.format("布防/撤防操作超时, 设备未返回应答指令"));
// 释放rtpserver // 释放rtpserver
RequestMessage msg = new RequestMessage(); RequestMessage msg = new RequestMessage();
msg.setKey(key); msg.setKey(key);
@ -181,8 +178,8 @@ public class DeviceControl {
public DeferredResult<ResponseEntity<String>> resetAlarmApi(@PathVariable String deviceId, String channelId, public DeferredResult<ResponseEntity<String>> resetAlarmApi(@PathVariable String deviceId, String channelId,
@RequestParam(required = false) String alarmMethod, @RequestParam(required = false) String alarmMethod,
@RequestParam(required = false) String alarmType) { @RequestParam(required = false) String alarmType) {
if (logger.isDebugEnabled()) { if (log.isDebugEnabled()) {
logger.debug("报警复位API调用"); log.debug("报警复位API调用");
} }
Device device = storager.queryVideoDevice(deviceId); Device device = storager.queryVideoDevice(deviceId);
String uuid = UUID.randomUUID().toString(); String uuid = UUID.randomUUID().toString();
@ -196,12 +193,12 @@ public class DeviceControl {
resultHolder.invokeResult(msg); resultHolder.invokeResult(msg);
},null); },null);
} catch (InvalidArgumentException | SipException | ParseException e) { } catch (InvalidArgumentException | SipException | ParseException e) {
logger.error("[命令发送失败] 报警复位: {}", e.getMessage()); log.error("[命令发送失败] 报警复位: {}", e.getMessage());
throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage()); throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage());
} }
DeferredResult<ResponseEntity<String>> result = new DeferredResult<ResponseEntity<String>>(3 * 1000L); DeferredResult<ResponseEntity<String>> result = new DeferredResult<ResponseEntity<String>>(3 * 1000L);
result.onTimeout(() -> { result.onTimeout(() -> {
logger.warn(String.format("报警复位操作超时, 设备未返回应答指令")); log.warn(String.format("报警复位操作超时, 设备未返回应答指令"));
// 释放rtpserver // 释放rtpserver
RequestMessage msg = new RequestMessage(); RequestMessage msg = new RequestMessage();
msg.setId(uuid); msg.setId(uuid);
@ -225,14 +222,14 @@ public class DeviceControl {
@GetMapping("/i_frame/{deviceId}") @GetMapping("/i_frame/{deviceId}")
public JSONObject iFrame(@PathVariable String deviceId, public JSONObject iFrame(@PathVariable String deviceId,
@RequestParam(required = false) String channelId) { @RequestParam(required = false) String channelId) {
if (logger.isDebugEnabled()) { if (log.isDebugEnabled()) {
logger.debug("强制关键帧API调用"); log.debug("强制关键帧API调用");
} }
Device device = storager.queryVideoDevice(deviceId); Device device = storager.queryVideoDevice(deviceId);
try { try {
cmder.iFrameCmd(device, channelId); cmder.iFrameCmd(device, channelId);
} catch (InvalidArgumentException | SipException | ParseException e) { } catch (InvalidArgumentException | SipException | ParseException e) {
logger.error("[命令发送失败] 强制关键帧: {}", e.getMessage()); log.error("[命令发送失败] 强制关键帧: {}", e.getMessage());
throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage()); throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage());
} }
JSONObject json = new JSONObject(); JSONObject json = new JSONObject();
@ -261,8 +258,8 @@ public class DeviceControl {
public DeferredResult<String> homePositionApi(String deviceId, String channelId, Boolean enabled, public DeferredResult<String> homePositionApi(String deviceId, String channelId, Boolean enabled,
@RequestParam(required = false) Integer resetTime, @RequestParam(required = false) Integer resetTime,
@RequestParam(required = false) Integer presetIndex) { @RequestParam(required = false) Integer presetIndex) {
if (logger.isDebugEnabled()) { if (log.isDebugEnabled()) {
logger.debug("报警复位API调用"); log.debug("报警复位API调用");
} }
String key = DeferredResultHolder.CALLBACK_CMD_DEVICECONTROL + (ObjectUtils.isEmpty(channelId) ? deviceId : channelId); String key = DeferredResultHolder.CALLBACK_CMD_DEVICECONTROL + (ObjectUtils.isEmpty(channelId) ? deviceId : channelId);
String uuid = UUID.randomUUID().toString(); String uuid = UUID.randomUUID().toString();
@ -276,12 +273,12 @@ public class DeviceControl {
resultHolder.invokeResult(msg); resultHolder.invokeResult(msg);
},null); },null);
} catch (InvalidArgumentException | SipException | ParseException e) { } catch (InvalidArgumentException | SipException | ParseException e) {
logger.error("[命令发送失败] 看守位控制: {}", e.getMessage()); log.error("[命令发送失败] 看守位控制: {}", e.getMessage());
throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage()); throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage());
} }
DeferredResult<String> result = new DeferredResult<>(3 * 1000L); DeferredResult<String> result = new DeferredResult<>(3 * 1000L);
result.onTimeout(() -> { result.onTimeout(() -> {
logger.warn(String.format("看守位控制操作超时, 设备未返回应答指令")); log.warn(String.format("看守位控制操作超时, 设备未返回应答指令"));
// 释放rtpserver // 释放rtpserver
RequestMessage msg = new RequestMessage(); RequestMessage msg = new RequestMessage();
msg.setId(uuid); msg.setId(uuid);
@ -326,8 +323,8 @@ public class DeviceControl {
@RequestParam int midpointy, @RequestParam int midpointy,
@RequestParam int lengthx, @RequestParam int lengthx,
@RequestParam int lengthy) throws RuntimeException { @RequestParam int lengthy) throws RuntimeException {
if (logger.isDebugEnabled()) { if (log.isDebugEnabled()) {
logger.debug(String.format("设备拉框放大 API调用deviceId%s channelId%s length%d width%d midpointx%d midpointy%d lengthx%d lengthy%d",deviceId, channelId, length, width, midpointx, midpointy,lengthx, lengthy)); log.debug(String.format("设备拉框放大 API调用deviceId%s channelId%s length%d width%d midpointx%d midpointy%d lengthx%d lengthy%d",deviceId, channelId, length, width, midpointx, midpointy,lengthx, lengthy));
} }
Device device = storager.queryVideoDevice(deviceId); Device device = storager.queryVideoDevice(deviceId);
StringBuffer cmdXml = new StringBuffer(200); StringBuffer cmdXml = new StringBuffer(200);
@ -342,7 +339,7 @@ public class DeviceControl {
try { try {
cmder.dragZoomCmd(device, channelId, cmdXml.toString()); cmder.dragZoomCmd(device, channelId, cmdXml.toString());
} catch (InvalidArgumentException | SipException | ParseException e) { } catch (InvalidArgumentException | SipException | ParseException e) {
logger.error("[命令发送失败] 拉框放大: {}", e.getMessage()); log.error("[命令发送失败] 拉框放大: {}", e.getMessage());
throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage()); throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage());
} }
} }
@ -378,8 +375,8 @@ public class DeviceControl {
@RequestParam int lengthx, @RequestParam int lengthx,
@RequestParam int lengthy){ @RequestParam int lengthy){
if (logger.isDebugEnabled()) { if (log.isDebugEnabled()) {
logger.debug(String.format("设备拉框缩小 API调用deviceId%s channelId%s length%d width%d midpointx%d midpointy%d lengthx%d lengthy%d",deviceId, channelId, length, width, midpointx, midpointy,lengthx, lengthy)); log.debug(String.format("设备拉框缩小 API调用deviceId%s channelId%s length%d width%d midpointx%d midpointy%d lengthx%d lengthy%d",deviceId, channelId, length, width, midpointx, midpointy,lengthx, lengthy));
} }
Device device = storager.queryVideoDevice(deviceId); Device device = storager.queryVideoDevice(deviceId);
StringBuffer cmdXml = new StringBuffer(200); StringBuffer cmdXml = new StringBuffer(200);
@ -394,7 +391,7 @@ public class DeviceControl {
try { try {
cmder.dragZoomCmd(device, channelId, cmdXml.toString()); cmder.dragZoomCmd(device, channelId, cmdXml.toString());
} catch (InvalidArgumentException | SipException | ParseException e) { } catch (InvalidArgumentException | SipException | ParseException e) {
logger.error("[命令发送失败] 拉框缩小: {}", e.getMessage()); log.error("[命令发送失败] 拉框缩小: {}", e.getMessage());
throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage()); throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage());
} }
} }

View File

@ -25,10 +25,9 @@ import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.IOUtils; import org.apache.commons.compress.utils.IOUtils;
import org.apache.ibatis.annotations.Options; import org.apache.ibatis.annotations.Options;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
@ -53,13 +52,11 @@ import java.util.UUID;
@Tag(name = "国标设备查询", description = "国标设备查询") @Tag(name = "国标设备查询", description = "国标设备查询")
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
@Slf4j
@RestController @RestController
@RequestMapping("/api/device/query") @RequestMapping("/api/device/query")
public class DeviceQuery { public class DeviceQuery {
private final static Logger logger = LoggerFactory.getLogger(DeviceQuery.class);
@Autowired @Autowired
private IVideoManagerStorage storager; private IVideoManagerStorage storager;
@ -158,8 +155,8 @@ public class DeviceQuery {
@GetMapping("/devices/{deviceId}/sync") @GetMapping("/devices/{deviceId}/sync")
public WVPResult<SyncStatus> devicesSync(@PathVariable String deviceId){ public WVPResult<SyncStatus> devicesSync(@PathVariable String deviceId){
if (logger.isDebugEnabled()) { if (log.isDebugEnabled()) {
logger.debug("设备通道信息同步API调用deviceId" + deviceId); log.debug("设备通道信息同步API调用deviceId" + deviceId);
} }
Device device = storager.queryVideoDevice(deviceId); Device device = storager.queryVideoDevice(deviceId);
boolean status = deviceService.isSyncRunning(deviceId); boolean status = deviceService.isSyncRunning(deviceId);
@ -186,8 +183,8 @@ public class DeviceQuery {
@DeleteMapping("/devices/{deviceId}/delete") @DeleteMapping("/devices/{deviceId}/delete")
public String delete(@PathVariable String deviceId){ public String delete(@PathVariable String deviceId){
if (logger.isDebugEnabled()) { if (log.isDebugEnabled()) {
logger.debug("设备信息删除API调用deviceId" + deviceId); log.debug("设备信息删除API调用deviceId" + deviceId);
} }
// 清除redis记录 // 清除redis记录
@ -210,7 +207,7 @@ public class DeviceQuery {
json.put("deviceId", deviceId); json.put("deviceId", deviceId);
return json.toString(); return json.toString();
} else { } else {
logger.warn("设备信息删除API调用失败"); log.warn("设备信息删除API调用失败");
throw new ControllerException(ErrorCode.ERROR100.getCode(), "设备信息删除API调用失败"); throw new ControllerException(ErrorCode.ERROR100.getCode(), "设备信息删除API调用失败");
} }
} }
@ -340,8 +337,8 @@ public class DeviceQuery {
@Parameter(name = "deviceId", description = "设备国标编号", required = true) @Parameter(name = "deviceId", description = "设备国标编号", required = true)
@GetMapping("/devices/{deviceId}/status") @GetMapping("/devices/{deviceId}/status")
public DeferredResult<ResponseEntity<String>> deviceStatusApi(@PathVariable String deviceId) { public DeferredResult<ResponseEntity<String>> deviceStatusApi(@PathVariable String deviceId) {
if (logger.isDebugEnabled()) { if (log.isDebugEnabled()) {
logger.debug("设备状态查询API调用"); log.debug("设备状态查询API调用");
} }
Device device = storager.queryVideoDevice(deviceId); Device device = storager.queryVideoDevice(deviceId);
String uuid = UUID.randomUUID().toString(); String uuid = UUID.randomUUID().toString();
@ -360,11 +357,11 @@ public class DeviceQuery {
resultHolder.invokeResult(msg); resultHolder.invokeResult(msg);
}); });
} catch (InvalidArgumentException | SipException | ParseException e) { } catch (InvalidArgumentException | SipException | ParseException e) {
logger.error("[命令发送失败] 获取设备状态: {}", e.getMessage()); log.error("[命令发送失败] 获取设备状态: {}", e.getMessage());
throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage()); throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage());
} }
result.onTimeout(()->{ result.onTimeout(()->{
logger.warn(String.format("获取设备状态超时")); log.warn(String.format("获取设备状态超时"));
// 释放rtpserver // 释放rtpserver
RequestMessage msg = new RequestMessage(); RequestMessage msg = new RequestMessage();
msg.setId(uuid); msg.setId(uuid);
@ -403,8 +400,8 @@ public class DeviceQuery {
@RequestParam(required = false) String alarmType, @RequestParam(required = false) String alarmType,
@RequestParam(required = false) String startTime, @RequestParam(required = false) String startTime,
@RequestParam(required = false) String endTime) { @RequestParam(required = false) String endTime) {
if (logger.isDebugEnabled()) { if (log.isDebugEnabled()) {
logger.debug("设备报警查询API调用"); log.debug("设备报警查询API调用");
} }
Device device = storager.queryVideoDevice(deviceId); Device device = storager.queryVideoDevice(deviceId);
String key = DeferredResultHolder.CALLBACK_CMD_ALARM + deviceId; String key = DeferredResultHolder.CALLBACK_CMD_ALARM + deviceId;
@ -418,12 +415,12 @@ public class DeviceQuery {
resultHolder.invokeResult(msg); resultHolder.invokeResult(msg);
}); });
} catch (InvalidArgumentException | SipException | ParseException e) { } catch (InvalidArgumentException | SipException | ParseException e) {
logger.error("[命令发送失败] 设备报警查询: {}", e.getMessage()); log.error("[命令发送失败] 设备报警查询: {}", e.getMessage());
throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage()); throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage());
} }
DeferredResult<ResponseEntity<String>> result = new DeferredResult<ResponseEntity<String >> (3 * 1000L); DeferredResult<ResponseEntity<String>> result = new DeferredResult<ResponseEntity<String >> (3 * 1000L);
result.onTimeout(()->{ result.onTimeout(()->{
logger.warn(String.format("设备报警查询超时")); log.warn(String.format("设备报警查询超时"));
// 释放rtpserver // 释放rtpserver
RequestMessage msg = new RequestMessage(); RequestMessage msg = new RequestMessage();
msg.setId(uuid); msg.setId(uuid);

View File

@ -7,31 +7,31 @@ import com.genersoft.iot.vmp.conf.security.SecurityUtils;
import com.genersoft.iot.vmp.conf.security.dto.LoginUser; import com.genersoft.iot.vmp.conf.security.dto.LoginUser;
import com.genersoft.iot.vmp.media.service.IMediaServerService; import com.genersoft.iot.vmp.media.service.IMediaServerService;
import com.genersoft.iot.vmp.media.zlm.dto.StreamAuthorityInfo; import com.genersoft.iot.vmp.media.zlm.dto.StreamAuthorityInfo;
import com.genersoft.iot.vmp.streamProxy.service.IStreamProxyService;
import com.genersoft.iot.vmp.storager.IRedisCatchStorage; import com.genersoft.iot.vmp.storager.IRedisCatchStorage;
import com.genersoft.iot.vmp.streamProxy.service.IStreamProxyService;
import com.genersoft.iot.vmp.vmanager.bean.ErrorCode; import com.genersoft.iot.vmp.vmanager.bean.ErrorCode;
import com.genersoft.iot.vmp.vmanager.bean.StreamContent; import com.genersoft.iot.vmp.vmanager.bean.StreamContent;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger; import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
@Tag(name = "媒体流相关") @Tag(name = "媒体流相关")
@Controller @Controller
@Slf4j
@RequestMapping(value = "/api/media") @RequestMapping(value = "/api/media")
public class MediaController { public class MediaController {
private final static Logger logger = LoggerFactory.getLogger(MediaController.class);
@Autowired @Autowired
private IRedisCatchStorage redisCatchStorage; private IRedisCatchStorage redisCatchStorage;
@ -85,7 +85,7 @@ public class MediaController {
if (useSourceIpAsStreamIp != null && useSourceIpAsStreamIp) { if (useSourceIpAsStreamIp != null && useSourceIpAsStreamIp) {
String host = request.getHeader("Host"); String host = request.getHeader("Host");
String localAddr = host.split(":")[0]; String localAddr = host.split(":")[0];
logger.info("使用{}作为返回流的ip", localAddr); log.info("使用{}作为返回流的ip", localAddr);
streamInfo = mediaServerService.getStreamInfoByAppAndStreamWithCheck(app, stream, mediaServerId, localAddr, authority); streamInfo = mediaServerService.getStreamInfoByAppAndStreamWithCheck(app, stream, mediaServerId, localAddr, authority);
}else { }else {
streamInfo = mediaServerService.getStreamInfoByAppAndStreamWithCheck(app, stream, mediaServerId, authority); streamInfo = mediaServerService.getStreamInfoByAppAndStreamWithCheck(app, stream, mediaServerId, authority);
@ -100,12 +100,12 @@ public class MediaController {
try { try {
Thread.sleep(1000); Thread.sleep(1000);
} catch (InterruptedException e) { } catch (InterruptedException e) {
logger.error("[线程休眠失败] {}", e.getMessage()); log.error("[线程休眠失败] {}", e.getMessage());
} }
if (useSourceIpAsStreamIp != null && useSourceIpAsStreamIp) { if (useSourceIpAsStreamIp != null && useSourceIpAsStreamIp) {
String host = request.getHeader("Host"); String host = request.getHeader("Host");
String localAddr = host.split(":")[0]; String localAddr = host.split(":")[0];
logger.info("使用{}作为返回流的ip", localAddr); log.info("使用{}作为返回流的ip", localAddr);
streamInfo = mediaServerService.getStreamInfoByAppAndStreamWithCheck(app, stream, mediaServerId, localAddr, authority); streamInfo = mediaServerService.getStreamInfoByAppAndStreamWithCheck(app, stream, mediaServerId, localAddr, authority);
}else { }else {
streamInfo = mediaServerService.getStreamInfoByAppAndStreamWithCheck(app, stream, mediaServerId, authority); streamInfo = mediaServerService.getStreamInfoByAppAndStreamWithCheck(app, stream, mediaServerId, authority);

View File

@ -4,6 +4,7 @@ import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject; import com.alibaba.fastjson2.JSONObject;
import com.genersoft.iot.vmp.common.VideoManagerConstants; import com.genersoft.iot.vmp.common.VideoManagerConstants;
import com.genersoft.iot.vmp.conf.DynamicTask; import com.genersoft.iot.vmp.conf.DynamicTask;
import com.genersoft.iot.vmp.conf.SipConfig;
import com.genersoft.iot.vmp.conf.UserSetting; import com.genersoft.iot.vmp.conf.UserSetting;
import com.genersoft.iot.vmp.conf.exception.ControllerException; import com.genersoft.iot.vmp.conf.exception.ControllerException;
import com.genersoft.iot.vmp.conf.security.JwtUtils; import com.genersoft.iot.vmp.conf.security.JwtUtils;
@ -12,7 +13,9 @@ import com.genersoft.iot.vmp.gb28181.bean.ParentPlatformCatch;
import com.genersoft.iot.vmp.gb28181.bean.PlatformCatalog; import com.genersoft.iot.vmp.gb28181.bean.PlatformCatalog;
import com.genersoft.iot.vmp.gb28181.bean.SubscribeHolder; import com.genersoft.iot.vmp.gb28181.bean.SubscribeHolder;
import com.genersoft.iot.vmp.gb28181.transmit.cmd.ISIPCommanderForPlatform; import com.genersoft.iot.vmp.gb28181.transmit.cmd.ISIPCommanderForPlatform;
import com.genersoft.iot.vmp.service.*; import com.genersoft.iot.vmp.service.IDeviceChannelService;
import com.genersoft.iot.vmp.service.IPlatformChannelService;
import com.genersoft.iot.vmp.service.IPlatformService;
import com.genersoft.iot.vmp.storager.IRedisCatchStorage; import com.genersoft.iot.vmp.storager.IRedisCatchStorage;
import com.genersoft.iot.vmp.storager.IVideoManagerStorage; import com.genersoft.iot.vmp.storager.IVideoManagerStorage;
import com.genersoft.iot.vmp.utils.DateUtil; import com.genersoft.iot.vmp.utils.DateUtil;
@ -24,12 +27,10 @@ import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger; import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils; import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import com.genersoft.iot.vmp.conf.SipConfig;
import javax.sip.InvalidArgumentException; import javax.sip.InvalidArgumentException;
import javax.sip.SipException; import javax.sip.SipException;
@ -40,13 +41,11 @@ import java.util.List;
* 级联平台管理 * 级联平台管理
*/ */
@Tag(name = "级联平台管理") @Tag(name = "级联平台管理")
@Slf4j
@RestController @RestController
@RequestMapping("/api/platform") @RequestMapping("/api/platform")
public class PlatformController { public class PlatformController {
private final static Logger logger = LoggerFactory.getLogger(PlatformController.class);
@Autowired @Autowired
private UserSetting userSetting; private UserSetting userSetting;
@ -144,8 +143,8 @@ public class PlatformController {
@ResponseBody @ResponseBody
public void addPlatform(@RequestBody ParentPlatform parentPlatform) { public void addPlatform(@RequestBody ParentPlatform parentPlatform) {
if (logger.isDebugEnabled()) { if (log.isDebugEnabled()) {
logger.debug("保存上级平台信息API调用"); log.debug("保存上级平台信息API调用");
} }
if (ObjectUtils.isEmpty(parentPlatform.getName()) if (ObjectUtils.isEmpty(parentPlatform.getName())
|| ObjectUtils.isEmpty(parentPlatform.getServerGBId()) || ObjectUtils.isEmpty(parentPlatform.getServerGBId())
@ -189,8 +188,8 @@ public class PlatformController {
@ResponseBody @ResponseBody
public void savePlatform(@RequestBody ParentPlatform parentPlatform) { public void savePlatform(@RequestBody ParentPlatform parentPlatform) {
if (logger.isDebugEnabled()) { if (log.isDebugEnabled()) {
logger.debug("保存上级平台信息API调用"); log.debug("保存上级平台信息API调用");
} }
if (ObjectUtils.isEmpty(parentPlatform.getName()) if (ObjectUtils.isEmpty(parentPlatform.getName())
|| ObjectUtils.isEmpty(parentPlatform.getServerGBId()) || ObjectUtils.isEmpty(parentPlatform.getServerGBId())
@ -221,8 +220,8 @@ public class PlatformController {
@ResponseBody @ResponseBody
public void deletePlatform(@PathVariable String serverGBId) { public void deletePlatform(@PathVariable String serverGBId) {
if (logger.isDebugEnabled()) { if (log.isDebugEnabled()) {
logger.debug("删除上级平台API调用"); log.debug("删除上级平台API调用");
} }
if (ObjectUtils.isEmpty(serverGBId) if (ObjectUtils.isEmpty(serverGBId)
) { ) {
@ -252,7 +251,7 @@ public class PlatformController {
redisCatchStorage.delPlatformRegister(parentPlatform.getServerGBId()); redisCatchStorage.delPlatformRegister(parentPlatform.getServerGBId());
})); }));
} catch (InvalidArgumentException | ParseException | SipException e) { } catch (InvalidArgumentException | ParseException | SipException e) {
logger.error("[命令发送失败] 国标级联 注销: {}", e.getMessage()); log.error("[命令发送失败] 国标级联 注销: {}", e.getMessage());
} }
boolean deleteResult = storager.deleteParentPlatform(parentPlatform); boolean deleteResult = storager.deleteParentPlatform(parentPlatform);
@ -337,13 +336,13 @@ public class PlatformController {
@ResponseBody @ResponseBody
public void updateChannelForGB(@RequestBody UpdateChannelParam param) { public void updateChannelForGB(@RequestBody UpdateChannelParam param) {
if (logger.isDebugEnabled()) { if (log.isDebugEnabled()) {
logger.debug("给上级平台添加国标通道API调用"); log.debug("给上级平台添加国标通道API调用");
} }
int result = 0; int result = 0;
if (param.getChannelReduces() == null || param.getChannelReduces().size() == 0) { if (param.getChannelReduces() == null || param.getChannelReduces().size() == 0) {
if (param.isAll()) { if (param.isAll()) {
logger.info("[国标级联]添加所有通道到上级平台, {}", param.getPlatformId()); log.info("[国标级联]添加所有通道到上级平台, {}", param.getPlatformId());
List<ChannelReduce> allChannelForDevice = deviceChannelService.queryAllChannelList(param.getPlatformId()); List<ChannelReduce> allChannelForDevice = deviceChannelService.queryAllChannelList(param.getPlatformId());
result = platformChannelService.updateChannelForGB(param.getPlatformId(), allChannelForDevice, param.getCatalogId()); result = platformChannelService.updateChannelForGB(param.getPlatformId(), allChannelForDevice, param.getCatalogId());
} }
@ -366,13 +365,13 @@ public class PlatformController {
@ResponseBody @ResponseBody
public void delChannelForGB(@RequestBody UpdateChannelParam param) { public void delChannelForGB(@RequestBody UpdateChannelParam param) {
if (logger.isDebugEnabled()) { if (log.isDebugEnabled()) {
logger.debug("给上级平台删除国标通道API调用"); log.debug("给上级平台删除国标通道API调用");
} }
int result = 0; int result = 0;
if (param.getChannelReduces() == null || param.getChannelReduces().size() == 0) { if (param.getChannelReduces() == null || param.getChannelReduces().size() == 0) {
if (param.isAll()) { if (param.isAll()) {
logger.info("[国标级联]移除所有通道,上级平台, {}", param.getPlatformId()); log.info("[国标级联]移除所有通道,上级平台, {}", param.getPlatformId());
result = platformChannelService.delAllChannelForGB(param.getPlatformId(), param.getCatalogId()); result = platformChannelService.delAllChannelForGB(param.getPlatformId(), param.getCatalogId());
} }
}else { }else {
@ -397,8 +396,8 @@ public class PlatformController {
@ResponseBody @ResponseBody
public List<PlatformCatalog> getCatalogByPlatform(String platformId, String parentId) { public List<PlatformCatalog> getCatalogByPlatform(String platformId, String parentId) {
if (logger.isDebugEnabled()) { if (log.isDebugEnabled()) {
logger.debug("查询目录,platformId: {}, parentId: {}", platformId, parentId); log.debug("查询目录,platformId: {}, parentId: {}", platformId, parentId);
} }
ParentPlatform platform = storager.queryParentPlatByServerGBId(platformId); ParentPlatform platform = storager.queryParentPlatByServerGBId(platformId);
if (platform == null) { if (platform == null) {
@ -426,8 +425,8 @@ public class PlatformController {
@ResponseBody @ResponseBody
public void addCatalog(@RequestBody PlatformCatalog platformCatalog) { public void addCatalog(@RequestBody PlatformCatalog platformCatalog) {
if (logger.isDebugEnabled()) { if (log.isDebugEnabled()) {
logger.debug("添加目录,{}", JSON.toJSONString(platformCatalog)); log.debug("添加目录,{}", JSON.toJSONString(platformCatalog));
} }
PlatformCatalog platformCatalogInStore = storager.getCatalog(platformCatalog.getPlatformId(), platformCatalog.getId()); PlatformCatalog platformCatalogInStore = storager.getCatalog(platformCatalog.getPlatformId(), platformCatalog.getId());
@ -451,8 +450,8 @@ public class PlatformController {
@ResponseBody @ResponseBody
public void editCatalog(@RequestBody PlatformCatalog platformCatalog) { public void editCatalog(@RequestBody PlatformCatalog platformCatalog) {
if (logger.isDebugEnabled()) { if (log.isDebugEnabled()) {
logger.debug("编辑目录,{}", JSON.toJSONString(platformCatalog)); log.debug("编辑目录,{}", JSON.toJSONString(platformCatalog));
} }
PlatformCatalog platformCatalogInStore = storager.getCatalog(platformCatalog.getPlatformId(), platformCatalog.getId()); PlatformCatalog platformCatalogInStore = storager.getCatalog(platformCatalog.getPlatformId(), platformCatalog.getId());
@ -479,8 +478,8 @@ public class PlatformController {
@ResponseBody @ResponseBody
public void delCatalog(String id, String platformId) { public void delCatalog(String id, String platformId) {
if (logger.isDebugEnabled()) { if (log.isDebugEnabled()) {
logger.debug("删除目录,{}", id); log.debug("删除目录,{}", id);
} }
if (ObjectUtils.isEmpty(id) || ObjectUtils.isEmpty(platformId)) { if (ObjectUtils.isEmpty(id) || ObjectUtils.isEmpty(platformId)) {
@ -512,8 +511,8 @@ public class PlatformController {
@ResponseBody @ResponseBody
public void delRelation(@RequestBody PlatformCatalog platformCatalog) { public void delRelation(@RequestBody PlatformCatalog platformCatalog) {
if (logger.isDebugEnabled()) { if (log.isDebugEnabled()) {
logger.debug("删除关联,{}", JSON.toJSONString(platformCatalog)); log.debug("删除关联,{}", JSON.toJSONString(platformCatalog));
} }
int delResult = storager.delRelation(platformCatalog); int delResult = storager.delRelation(platformCatalog);
@ -537,8 +536,8 @@ public class PlatformController {
@ResponseBody @ResponseBody
public void setDefaultCatalog(String platformId, String catalogId) { public void setDefaultCatalog(String platformId, String catalogId) {
if (logger.isDebugEnabled()) { if (log.isDebugEnabled()) {
logger.debug("修改默认目录,{},{}", platformId, catalogId); log.debug("修改默认目录,{},{}", platformId, catalogId);
} }
int updateResult = storager.setDefaultCatalog(platformId, catalogId); int updateResult = storager.setDefaultCatalog(platformId, catalogId);

View File

@ -28,8 +28,7 @@ import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger; import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils; import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@ -46,13 +45,11 @@ import java.util.UUID;
* @author lin * @author lin
*/ */
@Tag(name = "国标设备点播") @Tag(name = "国标设备点播")
@Slf4j
@RestController @RestController
@RequestMapping("/api/play") @RequestMapping("/api/play")
public class PlayController { public class PlayController {
private final static Logger logger = LoggerFactory.getLogger(PlayController.class);
@Autowired @Autowired
private SIPCommander cmder; private SIPCommander cmder;
@ -84,7 +81,7 @@ public class PlayController {
public DeferredResult<WVPResult<StreamContent>> play(HttpServletRequest request, @PathVariable String deviceId, public DeferredResult<WVPResult<StreamContent>> play(HttpServletRequest request, @PathVariable String deviceId,
@PathVariable String channelId) { @PathVariable String channelId) {
logger.info("[开始点播] deviceId{}, channelId{}, ", deviceId, channelId); log.info("[开始点播] deviceId{}, channelId{}, ", deviceId, channelId);
// 获取可用的zlm // 获取可用的zlm
Device device = storager.queryVideoDevice(deviceId); Device device = storager.queryVideoDevice(deviceId);
MediaServer newMediaServerItem = playService.getNewMediaServerItem(device); MediaServer newMediaServerItem = playService.getNewMediaServerItem(device);
@ -97,7 +94,7 @@ public class PlayController {
DeferredResult<WVPResult<StreamContent>> result = new DeferredResult<>(userSetting.getPlayTimeout().longValue()); DeferredResult<WVPResult<StreamContent>> result = new DeferredResult<>(userSetting.getPlayTimeout().longValue());
result.onTimeout(()->{ result.onTimeout(()->{
logger.info("[点播等待超时] deviceId{}, channelId{}, ", deviceId, channelId); log.info("[点播等待超时] deviceId{}, channelId{}, ", deviceId, channelId);
// 释放rtpserver // 释放rtpserver
WVPResult<StreamInfo> wvpResult = new WVPResult<>(); WVPResult<StreamInfo> wvpResult = new WVPResult<>();
wvpResult.setCode(ErrorCode.ERROR100.getCode()); wvpResult.setCode(ErrorCode.ERROR100.getCode());
@ -155,7 +152,7 @@ public class PlayController {
@GetMapping("/stop/{deviceId}/{channelId}") @GetMapping("/stop/{deviceId}/{channelId}")
public JSONObject playStop(@PathVariable String deviceId, @PathVariable String channelId) { public JSONObject playStop(@PathVariable String deviceId, @PathVariable String channelId) {
logger.debug(String.format("设备预览/回放停止API调用streamId%s_%s", deviceId, channelId )); log.debug(String.format("设备预览/回放停止API调用streamId%s_%s", deviceId, channelId ));
if (deviceId == null || channelId == null) { if (deviceId == null || channelId == null) {
throw new ControllerException(ErrorCode.ERROR400); throw new ControllerException(ErrorCode.ERROR400);
@ -201,8 +198,8 @@ public class PlayController {
@GetMapping("/broadcast/{deviceId}/{channelId}") @GetMapping("/broadcast/{deviceId}/{channelId}")
@PostMapping("/broadcast/{deviceId}/{channelId}") @PostMapping("/broadcast/{deviceId}/{channelId}")
public AudioBroadcastResult broadcastApi(@PathVariable String deviceId, @PathVariable String channelId, Integer timeout, Boolean broadcastMode) { public AudioBroadcastResult broadcastApi(@PathVariable String deviceId, @PathVariable String channelId, Integer timeout, Boolean broadcastMode) {
if (logger.isDebugEnabled()) { if (log.isDebugEnabled()) {
logger.debug("语音广播API调用"); log.debug("语音广播API调用");
} }
Device device = storager.queryVideoDevice(deviceId); Device device = storager.queryVideoDevice(deviceId);
if (device == null) { if (device == null) {
@ -222,8 +219,8 @@ public class PlayController {
@GetMapping("/broadcast/stop/{deviceId}/{channelId}") @GetMapping("/broadcast/stop/{deviceId}/{channelId}")
@PostMapping("/broadcast/stop/{deviceId}/{channelId}") @PostMapping("/broadcast/stop/{deviceId}/{channelId}")
public void stopBroadcast(@PathVariable String deviceId, @PathVariable String channelId) { public void stopBroadcast(@PathVariable String deviceId, @PathVariable String channelId) {
if (logger.isDebugEnabled()) { if (log.isDebugEnabled()) {
logger.debug("停止语音广播API调用"); log.debug("停止语音广播API调用");
} }
// try { // try {
// playService.stopAudioBroadcast(deviceId, channelId); // playService.stopAudioBroadcast(deviceId, channelId);
@ -237,8 +234,8 @@ public class PlayController {
@Operation(summary = "获取所有的ssrc", security = @SecurityRequirement(name = JwtUtils.HEADER)) @Operation(summary = "获取所有的ssrc", security = @SecurityRequirement(name = JwtUtils.HEADER))
@GetMapping("/ssrc") @GetMapping("/ssrc")
public JSONObject getSSRC() { public JSONObject getSSRC() {
if (logger.isDebugEnabled()) { if (log.isDebugEnabled()) {
logger.debug("获取所有的ssrc"); log.debug("获取所有的ssrc");
} }
JSONArray objects = new JSONArray(); JSONArray objects = new JSONArray();
List<SsrcTransaction> allSsrc = streamSession.getAllSsrc(); List<SsrcTransaction> allSsrc = streamSession.getAllSsrc();
@ -263,8 +260,8 @@ public class PlayController {
@Parameter(name = "isSubStream", description = "是否子码流true-子码流false-主码流默认为false", required = true) @Parameter(name = "isSubStream", description = "是否子码流true-子码流false-主码流默认为false", required = true)
@GetMapping("/snap") @GetMapping("/snap")
public DeferredResult<String> getSnap(String deviceId, String channelId,boolean isSubStream) { public DeferredResult<String> getSnap(String deviceId, String channelId,boolean isSubStream) {
if (logger.isDebugEnabled()) { if (log.isDebugEnabled()) {
logger.debug("获取截图: {}/{}", deviceId, channelId); log.debug("获取截图: {}/{}", deviceId, channelId);
} }
DeferredResult<String> result = new DeferredResult<>(3 * 1000L); DeferredResult<String> result = new DeferredResult<>(3 * 1000L);

View File

@ -23,8 +23,7 @@ import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger; import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils; import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
@ -45,13 +44,11 @@ import java.util.UUID;
* @author lin * @author lin
*/ */
@Tag(name = "视频回放") @Tag(name = "视频回放")
@Slf4j
@RestController @RestController
@RequestMapping("/api/playback") @RequestMapping("/api/playback")
public class PlaybackController { public class PlaybackController {
private final static Logger logger = LoggerFactory.getLogger(PlaybackController.class);
@Autowired @Autowired
private SIPCommander cmder; private SIPCommander cmder;
@ -79,8 +76,8 @@ public class PlaybackController {
public DeferredResult<WVPResult<StreamContent>> start(HttpServletRequest request, @PathVariable String deviceId, @PathVariable String channelId, public DeferredResult<WVPResult<StreamContent>> start(HttpServletRequest request, @PathVariable String deviceId, @PathVariable String channelId,
String startTime, String endTime) { String startTime, String endTime) {
if (logger.isDebugEnabled()) { if (log.isDebugEnabled()) {
logger.debug(String.format("设备回放 API调用deviceId%s channelId%s", deviceId, channelId)); log.debug(String.format("设备回放 API调用deviceId%s channelId%s", deviceId, channelId));
} }
String uuid = UUID.randomUUID().toString(); String uuid = UUID.randomUUID().toString();
@ -155,7 +152,7 @@ public class PlaybackController {
@Parameter(name = "streamId", description = "回放流ID", required = true) @Parameter(name = "streamId", description = "回放流ID", required = true)
@GetMapping("/pause/{streamId}") @GetMapping("/pause/{streamId}")
public void playPause(@PathVariable String streamId) { public void playPause(@PathVariable String streamId) {
logger.info("playPause: "+streamId); log.info("playPause: "+streamId);
try { try {
playService.pauseRtp(streamId); playService.pauseRtp(streamId);
@ -171,7 +168,7 @@ public class PlaybackController {
@Parameter(name = "streamId", description = "回放流ID", required = true) @Parameter(name = "streamId", description = "回放流ID", required = true)
@GetMapping("/resume/{streamId}") @GetMapping("/resume/{streamId}")
public void playResume(@PathVariable String streamId) { public void playResume(@PathVariable String streamId) {
logger.info("playResume: "+streamId); log.info("playResume: "+streamId);
try { try {
playService.resumeRtp(streamId); playService.resumeRtp(streamId);
} catch (ServiceException e) { } catch (ServiceException e) {
@ -187,11 +184,11 @@ public class PlaybackController {
@Parameter(name = "seekTime", description = "拖动偏移量单位s", required = true) @Parameter(name = "seekTime", description = "拖动偏移量单位s", required = true)
@GetMapping("/seek/{streamId}/{seekTime}") @GetMapping("/seek/{streamId}/{seekTime}")
public void playSeek(@PathVariable String streamId, @PathVariable long seekTime) { public void playSeek(@PathVariable String streamId, @PathVariable long seekTime) {
logger.info("playSeek: "+streamId+", "+seekTime); log.info("playSeek: "+streamId+", "+seekTime);
InviteInfo inviteInfo = inviteStreamService.getInviteInfoByStream(InviteSessionType.PLAYBACK, streamId); InviteInfo inviteInfo = inviteStreamService.getInviteInfoByStream(InviteSessionType.PLAYBACK, streamId);
if (null == inviteInfo || inviteInfo.getStreamInfo() == null) { if (null == inviteInfo || inviteInfo.getStreamInfo() == null) {
logger.warn("streamId不存在!"); log.warn("streamId不存在!");
throw new ControllerException(ErrorCode.ERROR400.getCode(), "streamId不存在"); throw new ControllerException(ErrorCode.ERROR400.getCode(), "streamId不存在");
} }
Device device = storager.queryVideoDevice(inviteInfo.getDeviceId()); Device device = storager.queryVideoDevice(inviteInfo.getDeviceId());
@ -207,15 +204,15 @@ public class PlaybackController {
@Parameter(name = "speed", description = "倍速0.25 0.5 1、2、4", required = true) @Parameter(name = "speed", description = "倍速0.25 0.5 1、2、4", required = true)
@GetMapping("/speed/{streamId}/{speed}") @GetMapping("/speed/{streamId}/{speed}")
public void playSpeed(@PathVariable String streamId, @PathVariable Double speed) { public void playSpeed(@PathVariable String streamId, @PathVariable Double speed) {
logger.info("playSpeed: "+streamId+", "+speed); log.info("playSpeed: "+streamId+", "+speed);
InviteInfo inviteInfo = inviteStreamService.getInviteInfoByStream(InviteSessionType.PLAYBACK, streamId); InviteInfo inviteInfo = inviteStreamService.getInviteInfoByStream(InviteSessionType.PLAYBACK, streamId);
if (null == inviteInfo || inviteInfo.getStreamInfo() == null) { if (null == inviteInfo || inviteInfo.getStreamInfo() == null) {
logger.warn("streamId不存在!"); log.warn("streamId不存在!");
throw new ControllerException(ErrorCode.ERROR400.getCode(), "streamId不存在"); throw new ControllerException(ErrorCode.ERROR400.getCode(), "streamId不存在");
} }
if(speed != 0.25 && speed != 0.5 && speed != 1 && speed != 2.0 && speed != 4.0) { if(speed != 0.25 && speed != 0.5 && speed != 1 && speed != 2.0 && speed != 4.0) {
logger.warn("不支持的speed " + speed); log.warn("不支持的speed " + speed);
throw new ControllerException(ErrorCode.ERROR100.getCode(), "不支持的speed0.25 0.5 1、2、4"); throw new ControllerException(ErrorCode.ERROR100.getCode(), "不支持的speed0.25 0.5 1、2、4");
} }
Device device = storager.queryVideoDevice(inviteInfo.getDeviceId()); Device device = storager.queryVideoDevice(inviteInfo.getDeviceId());

View File

@ -13,8 +13,7 @@ import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger; import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils; import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@ -26,13 +25,11 @@ import java.text.ParseException;
import java.util.UUID; import java.util.UUID;
@Tag(name = "云台控制") @Tag(name = "云台控制")
@Slf4j
@RestController @RestController
@RequestMapping("/api/ptz") @RequestMapping("/api/ptz")
public class PtzController { public class PtzController {
private final static Logger logger = LoggerFactory.getLogger(PtzController.class);
@Autowired @Autowired
private SIPCommander cmder; private SIPCommander cmder;
@ -62,8 +59,8 @@ public class PtzController {
@PostMapping("/control/{deviceId}/{channelId}") @PostMapping("/control/{deviceId}/{channelId}")
public void ptz(@PathVariable String deviceId,@PathVariable String channelId, String command, int horizonSpeed, int verticalSpeed, int zoomSpeed){ public void ptz(@PathVariable String deviceId,@PathVariable String channelId, String command, int horizonSpeed, int verticalSpeed, int zoomSpeed){
if (logger.isDebugEnabled()) { if (log.isDebugEnabled()) {
logger.debug(String.format("设备云台控制 API调用deviceId%s channelId%s command%s horizonSpeed%d verticalSpeed%d zoomSpeed%d",deviceId, channelId, command, horizonSpeed, verticalSpeed, zoomSpeed)); log.debug(String.format("设备云台控制 API调用deviceId%s channelId%s command%s horizonSpeed%d verticalSpeed%d zoomSpeed%d",deviceId, channelId, command, horizonSpeed, verticalSpeed, zoomSpeed));
} }
Device device = storager.queryVideoDevice(deviceId); Device device = storager.queryVideoDevice(deviceId);
int cmdCode = 0; int cmdCode = 0;
@ -109,7 +106,7 @@ public class PtzController {
try { try {
cmder.frontEndCmd(device, channelId, cmdCode, horizonSpeed, verticalSpeed, zoomSpeed); cmder.frontEndCmd(device, channelId, cmdCode, horizonSpeed, verticalSpeed, zoomSpeed);
} catch (SipException | InvalidArgumentException | ParseException e) { } catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] 云台控制: {}", e.getMessage()); log.error("[命令发送失败] 云台控制: {}", e.getMessage());
throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage()); throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage());
} }
} }
@ -125,15 +122,15 @@ public class PtzController {
@PostMapping("/front_end_command/{deviceId}/{channelId}") @PostMapping("/front_end_command/{deviceId}/{channelId}")
public void frontEndCommand(@PathVariable String deviceId,@PathVariable String channelId,int cmdCode, int parameter1, int parameter2, int combindCode2){ public void frontEndCommand(@PathVariable String deviceId,@PathVariable String channelId,int cmdCode, int parameter1, int parameter2, int combindCode2){
if (logger.isDebugEnabled()) { if (log.isDebugEnabled()) {
logger.debug(String.format("设备云台控制 API调用deviceId%s channelId%s cmdCode%d parameter1%d parameter2%d",deviceId, channelId, cmdCode, parameter1, parameter2)); log.debug(String.format("设备云台控制 API调用deviceId%s channelId%s cmdCode%d parameter1%d parameter2%d",deviceId, channelId, cmdCode, parameter1, parameter2));
} }
Device device = storager.queryVideoDevice(deviceId); Device device = storager.queryVideoDevice(deviceId);
try { try {
cmder.frontEndCmd(device, channelId, cmdCode, parameter1, parameter2, combindCode2); cmder.frontEndCmd(device, channelId, cmdCode, parameter1, parameter2, combindCode2);
} catch (SipException | InvalidArgumentException | ParseException e) { } catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] 前端控制: {}", e.getMessage()); log.error("[命令发送失败] 前端控制: {}", e.getMessage());
throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage()); throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage());
} }
} }
@ -144,15 +141,15 @@ public class PtzController {
@Parameter(name = "channelId", description = "通道国标编号", required = true) @Parameter(name = "channelId", description = "通道国标编号", required = true)
@GetMapping("/preset/query/{deviceId}/{channelId}") @GetMapping("/preset/query/{deviceId}/{channelId}")
public DeferredResult<String> presetQueryApi(@PathVariable String deviceId, @PathVariable String channelId) { public DeferredResult<String> presetQueryApi(@PathVariable String deviceId, @PathVariable String channelId) {
if (logger.isDebugEnabled()) { if (log.isDebugEnabled()) {
logger.debug("设备预置位查询API调用"); log.debug("设备预置位查询API调用");
} }
Device device = storager.queryVideoDevice(deviceId); Device device = storager.queryVideoDevice(deviceId);
String uuid = UUID.randomUUID().toString(); String uuid = UUID.randomUUID().toString();
String key = DeferredResultHolder.CALLBACK_CMD_PRESETQUERY + (ObjectUtils.isEmpty(channelId) ? deviceId : channelId); String key = DeferredResultHolder.CALLBACK_CMD_PRESETQUERY + (ObjectUtils.isEmpty(channelId) ? deviceId : channelId);
DeferredResult<String> result = new DeferredResult<String> (3 * 1000L); DeferredResult<String> result = new DeferredResult<String> (3 * 1000L);
result.onTimeout(()->{ result.onTimeout(()->{
logger.warn(String.format("获取设备预置位超时")); log.warn(String.format("获取设备预置位超时"));
// 释放rtpserver // 释放rtpserver
RequestMessage msg = new RequestMessage(); RequestMessage msg = new RequestMessage();
msg.setId(uuid); msg.setId(uuid);
@ -173,7 +170,7 @@ public class PtzController {
resultHolder.invokeResult(msg); resultHolder.invokeResult(msg);
}); });
} catch (InvalidArgumentException | SipException | ParseException e) { } catch (InvalidArgumentException | SipException | ParseException e) {
logger.error("[命令发送失败] 获取设备预置位: {}", e.getMessage()); log.error("[命令发送失败] 获取设备预置位: {}", e.getMessage());
throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage()); throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage());
} }
return result; return result;

View File

@ -1,7 +1,5 @@
package com.genersoft.iot.vmp.vmanager.gb28181.record; package com.genersoft.iot.vmp.vmanager.gb28181.record;
import com.genersoft.iot.vmp.common.InviteInfo;
import com.genersoft.iot.vmp.common.InviteSessionType;
import com.genersoft.iot.vmp.common.StreamInfo; import com.genersoft.iot.vmp.common.StreamInfo;
import com.genersoft.iot.vmp.conf.UserSetting; import com.genersoft.iot.vmp.conf.UserSetting;
import com.genersoft.iot.vmp.conf.exception.ControllerException; import com.genersoft.iot.vmp.conf.exception.ControllerException;
@ -15,7 +13,6 @@ import com.genersoft.iot.vmp.gb28181.transmit.cmd.impl.SIPCommander;
import com.genersoft.iot.vmp.service.IDeviceService; import com.genersoft.iot.vmp.service.IDeviceService;
import com.genersoft.iot.vmp.service.IInviteStreamService; import com.genersoft.iot.vmp.service.IInviteStreamService;
import com.genersoft.iot.vmp.service.IPlayService; import com.genersoft.iot.vmp.service.IPlayService;
import com.genersoft.iot.vmp.service.bean.DownloadFileInfo;
import com.genersoft.iot.vmp.service.bean.InviteErrorCode; import com.genersoft.iot.vmp.service.bean.InviteErrorCode;
import com.genersoft.iot.vmp.storager.IVideoManagerStorage; import com.genersoft.iot.vmp.storager.IVideoManagerStorage;
import com.genersoft.iot.vmp.utils.DateUtil; import com.genersoft.iot.vmp.utils.DateUtil;
@ -26,10 +23,8 @@ import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger; import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
@ -43,13 +38,11 @@ import java.text.ParseException;
import java.util.UUID; import java.util.UUID;
@Tag(name = "国标录像") @Tag(name = "国标录像")
@Slf4j
@RestController @RestController
@RequestMapping("/api/gb_record") @RequestMapping("/api/gb_record")
public class GBRecordController { public class GBRecordController {
private final static Logger logger = LoggerFactory.getLogger(GBRecordController.class);
@Autowired @Autowired
private SIPCommander cmder; private SIPCommander cmder;
@ -79,8 +72,8 @@ public class GBRecordController {
@GetMapping("/query/{deviceId}/{channelId}") @GetMapping("/query/{deviceId}/{channelId}")
public DeferredResult<WVPResult<RecordInfo>> recordinfo(@PathVariable String deviceId, @PathVariable String channelId, String startTime, String endTime){ public DeferredResult<WVPResult<RecordInfo>> recordinfo(@PathVariable String deviceId, @PathVariable String channelId, String startTime, String endTime){
if (logger.isDebugEnabled()) { if (log.isDebugEnabled()) {
logger.debug(String.format("录像信息查询 API调用deviceId%s startTime%s endTime%s",deviceId, startTime, endTime)); log.debug(String.format("录像信息查询 API调用deviceId%s startTime%s endTime%s",deviceId, startTime, endTime));
} }
DeferredResult<WVPResult<RecordInfo>> result = new DeferredResult<>(); DeferredResult<WVPResult<RecordInfo>> result = new DeferredResult<>();
if (!DateUtil.verification(startTime, DateUtil.formatter)){ if (!DateUtil.verification(startTime, DateUtil.formatter)){
@ -107,7 +100,7 @@ public class GBRecordController {
resultHolder.invokeResult(msg); resultHolder.invokeResult(msg);
})); }));
} catch (InvalidArgumentException | SipException | ParseException e) { } catch (InvalidArgumentException | SipException | ParseException e) {
logger.error("[命令发送失败] 查询录像: {}", e.getMessage()); log.error("[命令发送失败] 查询录像: {}", e.getMessage());
throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage()); throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage());
} }
@ -135,8 +128,8 @@ public class GBRecordController {
public DeferredResult<WVPResult<StreamContent>> download(HttpServletRequest request, @PathVariable String deviceId, @PathVariable String channelId, public DeferredResult<WVPResult<StreamContent>> download(HttpServletRequest request, @PathVariable String deviceId, @PathVariable String channelId,
String startTime, String endTime, String downloadSpeed) { String startTime, String endTime, String downloadSpeed) {
if (logger.isDebugEnabled()) { if (log.isDebugEnabled()) {
logger.debug(String.format("历史媒体下载 API调用deviceId%schannelId%sdownloadSpeed%s", deviceId, channelId, downloadSpeed)); log.debug(String.format("历史媒体下载 API调用deviceId%schannelId%sdownloadSpeed%s", deviceId, channelId, downloadSpeed));
} }
String uuid = UUID.randomUUID().toString(); String uuid = UUID.randomUUID().toString();
@ -181,8 +174,8 @@ public class GBRecordController {
@GetMapping("/download/stop/{deviceId}/{channelId}/{stream}") @GetMapping("/download/stop/{deviceId}/{channelId}/{stream}")
public void playStop(@PathVariable String deviceId, @PathVariable String channelId, @PathVariable String stream) { public void playStop(@PathVariable String deviceId, @PathVariable String channelId, @PathVariable String stream) {
if (logger.isDebugEnabled()) { if (log.isDebugEnabled()) {
logger.debug(String.format("设备历史媒体下载停止 API调用deviceId/channelId%s_%s", deviceId, channelId)); log.debug(String.format("设备历史媒体下载停止 API调用deviceId/channelId%s_%s", deviceId, channelId));
} }
if (deviceId == null || channelId == null) { if (deviceId == null || channelId == null) {
@ -197,7 +190,7 @@ public class GBRecordController {
try { try {
cmder.streamByeCmd(device, channelId, stream, null); cmder.streamByeCmd(device, channelId, stream, null);
} catch (InvalidArgumentException | ParseException | SipException | SsrcTransactionNotFoundException e) { } catch (InvalidArgumentException | ParseException | SipException | SsrcTransactionNotFoundException e) {
logger.error("[停止历史媒体下载]停止历史媒体下载发送BYE失败 {}", e.getMessage()); log.error("[停止历史媒体下载]停止历史媒体下载发送BYE失败 {}", e.getMessage());
throw new ControllerException(ErrorCode.ERROR100.getCode(), e.getMessage()); throw new ControllerException(ErrorCode.ERROR100.getCode(), e.getMessage());
} }
} }

View File

@ -13,20 +13,17 @@ import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger; import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils; import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@Tag(name = "日志管理") @Tag(name = "日志管理")
@Slf4j
@RestController @RestController
@RequestMapping("/api/log") @RequestMapping("/api/log")
public class LogController { public class LogController {
private final static Logger logger = LoggerFactory.getLogger(LogController.class);
@Autowired @Autowired
private ILogService logService; private ILogService logService;
@ -65,7 +62,7 @@ public class LogController {
} }
if (!userSetting.getLogInDatabase()) { if (!userSetting.getLogInDatabase()) {
logger.warn("自动记录日志功能已关闭,查询结果可能不完整。"); log.warn("自动记录日志功能已关闭,查询结果可能不完整。");
} }
if (ObjectUtils.isEmpty(startTime)) { if (ObjectUtils.isEmpty(startTime)) {

View File

@ -20,10 +20,9 @@ import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient; import okhttp3.OkHttpClient;
import okhttp3.Request; import okhttp3.Request;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@ -37,13 +36,11 @@ import java.util.concurrent.TimeUnit;
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
@Tag(name = "第三方PS服务对接") @Tag(name = "第三方PS服务对接")
@Slf4j
@RestController @RestController
@RequestMapping("/api/ps") @RequestMapping("/api/ps")
public class PsController { public class PsController {
private final static Logger logger = LoggerFactory.getLogger(PsController.class);
@Autowired @Autowired
private HookSubscribe hookSubscribe; private HookSubscribe hookSubscribe;
@ -75,7 +72,7 @@ public class PsController {
@Parameter(name = "callBack", description = "回调地址如果收流超时会通道回调通知回调为get请求参数为callId", required = true) @Parameter(name = "callBack", description = "回调地址如果收流超时会通道回调通知回调为get请求参数为callId", required = true)
public OtherPsSendInfo openRtpServer(Boolean isSend, @RequestParam(required = false)String ssrc, String callId, String stream, Integer tcpMode, String callBack) { public OtherPsSendInfo openRtpServer(Boolean isSend, @RequestParam(required = false)String ssrc, String callId, String stream, Integer tcpMode, String callBack) {
logger.info("[第三方PS服务对接->开启收流和获取发流信息] isSend->{}, ssrc->{}, callId->{}, stream->{}, tcpMode->{}, callBack->{}", log.info("[第三方PS服务对接->开启收流和获取发流信息] isSend->{}, ssrc->{}, callId->{}, stream->{}, tcpMode->{}, callBack->{}",
isSend, ssrc, callId, stream, tcpMode==0?"UDP":"TCP被动", callBack); isSend, ssrc, callId, stream, tcpMode==0?"UDP":"TCP被动", callBack);
MediaServer mediaServer = mediaServerService.getDefaultMediaServer(); MediaServer mediaServer = mediaServerService.getDefaultMediaServer();
@ -109,7 +106,7 @@ public class PsController {
hookSubscribe.addSubscribe(hook, hookSubscribe.addSubscribe(hook,
(hookData)->{ (hookData)->{
if (stream.equals(hookData.getStream())) { if (stream.equals(hookData.getStream())) {
logger.info("[第三方PS服务对接->开启收流和获取发流信息] 等待收流超时 callId->{}, 发送回调", callId); log.info("[第三方PS服务对接->开启收流和获取发流信息] 等待收流超时 callId->{}, 发送回调", callId);
// 将信息写入redis中以备后用 // 将信息写入redis中以备后用
redisTemplate.delete(receiveKey); redisTemplate.delete(receiveKey);
OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder(); OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
@ -119,7 +116,7 @@ public class PsController {
try { try {
client.newCall(request).execute(); client.newCall(request).execute();
} catch (IOException e) { } catch (IOException e) {
logger.error("[第三方PS服务对接->开启收流和获取发流信息] 等待收流超时 callId->{}, 发送回调失败", callId, e); log.error("[第三方PS服务对接->开启收流和获取发流信息] 等待收流超时 callId->{}, 发送回调失败", callId, e);
} }
hookSubscribe.removeSubscribe(hook); hookSubscribe.removeSubscribe(hook);
} }
@ -142,7 +139,7 @@ public class PsController {
otherPsSendInfo.setSendLocalPort(port); otherPsSendInfo.setSendLocalPort(port);
// 将信息写入redis中以备后用 // 将信息写入redis中以备后用
redisTemplate.opsForValue().set(key, otherPsSendInfo, 300, TimeUnit.SECONDS); redisTemplate.opsForValue().set(key, otherPsSendInfo, 300, TimeUnit.SECONDS);
logger.info("[第三方PS服务对接->开启收流和获取发流信息] 结果callId->{} {}", callId, otherPsSendInfo); log.info("[第三方PS服务对接->开启收流和获取发流信息] 结果callId->{} {}", callId, otherPsSendInfo);
} }
return otherPsSendInfo; return otherPsSendInfo;
} }
@ -152,7 +149,7 @@ public class PsController {
@Operation(summary = "关闭收流", security = @SecurityRequirement(name = JwtUtils.HEADER)) @Operation(summary = "关闭收流", security = @SecurityRequirement(name = JwtUtils.HEADER))
@Parameter(name = "stream", description = "流的ID", required = true) @Parameter(name = "stream", description = "流的ID", required = true)
public void closeRtpServer(String stream) { public void closeRtpServer(String stream) {
logger.info("[第三方PS服务对接->关闭收流] stream->{}", stream); log.info("[第三方PS服务对接->关闭收流] stream->{}", stream);
MediaServer mediaServerItem = mediaServerService.getDefaultMediaServer(); MediaServer mediaServerItem = mediaServerService.getDefaultMediaServer();
mediaServerService.closeRTPServer(mediaServerItem, stream); mediaServerService.closeRTPServer(mediaServerItem, stream);
String receiveKey = VideoManagerConstants.WVP_OTHER_RECEIVE_PS_INFO + userSetting.getServerId() + "_*_" + stream; String receiveKey = VideoManagerConstants.WVP_OTHER_RECEIVE_PS_INFO + userSetting.getServerId() + "_*_" + stream;
@ -183,7 +180,7 @@ public class PsController {
String callId, String callId,
Boolean isUdp Boolean isUdp
) { ) {
logger.info("[第三方PS服务对接->发送流] " + log.info("[第三方PS服务对接->发送流] " +
"ssrc->{}, \r\n" + "ssrc->{}, \r\n" +
"dstIp->{}, \n" + "dstIp->{}, \n" +
"dstPort->{}, \n" + "dstPort->{}, \n" +
@ -209,14 +206,14 @@ public class PsController {
Boolean streamReady = mediaServerService.isStreamReady(mediaServer, app, stream); Boolean streamReady = mediaServerService.isStreamReady(mediaServer, app, stream);
if (streamReady) { if (streamReady) {
mediaServerService.startSendRtp(mediaServer, sendRtpItem); mediaServerService.startSendRtp(mediaServer, sendRtpItem);
logger.info("[第三方PS服务对接->发送流] 视频流发流成功callId->{}param->{}", callId, sendRtpItem); log.info("[第三方PS服务对接->发送流] 视频流发流成功callId->{}param->{}", callId, sendRtpItem);
redisTemplate.opsForValue().set(key, sendInfo); redisTemplate.opsForValue().set(key, sendInfo);
}else { }else {
logger.info("[第三方PS服务对接->发送流] 流不存在等待流上线callId->{}", callId); log.info("[第三方PS服务对接->发送流] 流不存在等待流上线callId->{}", callId);
String uuid = UUID.randomUUID().toString(); String uuid = UUID.randomUUID().toString();
Hook hook = Hook.getInstance(HookType.on_media_arrival, app, stream, mediaServer.getId()); Hook hook = Hook.getInstance(HookType.on_media_arrival, app, stream, mediaServer.getId());
dynamicTask.startDelay(uuid, ()->{ dynamicTask.startDelay(uuid, ()->{
logger.info("[第三方PS服务对接->发送流] 等待流上线超时 callId->{}", callId); log.info("[第三方PS服务对接->发送流] 等待流上线超时 callId->{}", callId);
redisTemplate.delete(key); redisTemplate.delete(key);
hookSubscribe.removeSubscribe(hook); hookSubscribe.removeSubscribe(hook);
}, 10000); }, 10000);
@ -227,14 +224,14 @@ public class PsController {
hookSubscribe.addSubscribe(hook, hookSubscribe.addSubscribe(hook,
(hookData)->{ (hookData)->{
dynamicTask.stop(uuid); dynamicTask.stop(uuid);
logger.info("[第三方PS服务对接->发送流] 流上线,开始发流 callId->{}", callId); log.info("[第三方PS服务对接->发送流] 流上线,开始发流 callId->{}", callId);
try { try {
Thread.sleep(400); Thread.sleep(400);
} catch (InterruptedException e) { } catch (InterruptedException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
mediaServerService.startSendRtp(mediaServer, sendRtpItem); mediaServerService.startSendRtp(mediaServer, sendRtpItem);
logger.info("[第三方PS服务对接->发送流] 视频流发流成功callId->{}param->{}", callId, sendRtpItem); log.info("[第三方PS服务对接->发送流] 视频流发流成功callId->{}param->{}", callId, sendRtpItem);
redisTemplate.opsForValue().set(key, finalSendInfo); redisTemplate.opsForValue().set(key, finalSendInfo);
hookSubscribe.removeSubscribe(hook); hookSubscribe.removeSubscribe(hook);
}); });
@ -246,7 +243,7 @@ public class PsController {
@Operation(summary = "关闭发送流") @Operation(summary = "关闭发送流")
@Parameter(name = "callId", description = "整个过程的唯一标识,不传则使用随机端口发流", required = true) @Parameter(name = "callId", description = "整个过程的唯一标识,不传则使用随机端口发流", required = true)
public void closeSendRTP(String callId) { public void closeSendRTP(String callId) {
logger.info("[第三方PS服务对接->关闭发送流] callId->{}", callId); log.info("[第三方PS服务对接->关闭发送流] callId->{}", callId);
String key = VideoManagerConstants.WVP_OTHER_SEND_PS_INFO + userSetting.getServerId() + "_" + callId; String key = VideoManagerConstants.WVP_OTHER_SEND_PS_INFO + userSetting.getServerId() + "_" + callId;
OtherPsSendInfo sendInfo = (OtherPsSendInfo)redisTemplate.opsForValue().get(key); OtherPsSendInfo sendInfo = (OtherPsSendInfo)redisTemplate.opsForValue().get(key);
if (sendInfo == null){ if (sendInfo == null){
@ -260,10 +257,10 @@ public class PsController {
MediaServer mediaServerItem = mediaServerService.getDefaultMediaServer(); MediaServer mediaServerItem = mediaServerService.getDefaultMediaServer();
boolean result = mediaServerService.stopSendRtp(mediaServerItem, sendInfo.getPushApp(), sendInfo.getStream(), sendInfo.getPushSSRC()); boolean result = mediaServerService.stopSendRtp(mediaServerItem, sendInfo.getPushApp(), sendInfo.getStream(), sendInfo.getPushSSRC());
if (!result) { if (!result) {
logger.info("[第三方PS服务对接->关闭发送流] 失败 callId->{}", callId); log.info("[第三方PS服务对接->关闭发送流] 失败 callId->{}", callId);
throw new ControllerException(ErrorCode.ERROR100.getCode(), "停止发流失败"); throw new ControllerException(ErrorCode.ERROR100.getCode(), "停止发流失败");
}else { }else {
logger.info("[第三方PS服务对接->关闭发送流] 成功 callId->{}", callId); log.info("[第三方PS服务对接->关闭发送流] 成功 callId->{}", callId);
} }
redisTemplate.delete(key); redisTemplate.delete(key);
} }

View File

@ -20,10 +20,9 @@ import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient; import okhttp3.OkHttpClient;
import okhttp3.Request; import okhttp3.Request;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.ObjectUtils; import org.springframework.util.ObjectUtils;
@ -36,7 +35,7 @@ import java.util.concurrent.TimeUnit;
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
@Tag(name = "第三方服务对接") @Tag(name = "第三方服务对接")
@Slf4j
@RestController @RestController
@RequestMapping("/api/rtp") @RequestMapping("/api/rtp")
public class RtpController { public class RtpController {
@ -44,8 +43,6 @@ public class RtpController {
@Autowired @Autowired
private SendRtpPortManager sendRtpPortManager; private SendRtpPortManager sendRtpPortManager;
private final static Logger logger = LoggerFactory.getLogger(RtpController.class);
@Autowired @Autowired
private HookSubscribe hookSubscribe; private HookSubscribe hookSubscribe;
@ -73,7 +70,7 @@ public class RtpController {
@Parameter(name = "callBack", description = "回调地址如果收流超时会通道回调通知回调为get请求参数为callId", required = true) @Parameter(name = "callBack", description = "回调地址如果收流超时会通道回调通知回调为get请求参数为callId", required = true)
public OtherRtpSendInfo openRtpServer(Boolean isSend, @RequestParam(required = false)String ssrc, String callId, String stream, Integer tcpMode, String callBack) { public OtherRtpSendInfo openRtpServer(Boolean isSend, @RequestParam(required = false)String ssrc, String callId, String stream, Integer tcpMode, String callBack) {
logger.info("[第三方服务对接->开启收流和获取发流信息] isSend->{}, ssrc->{}, callId->{}, stream->{}, tcpMode->{}, callBack->{}", log.info("[第三方服务对接->开启收流和获取发流信息] isSend->{}, ssrc->{}, callId->{}, stream->{}, tcpMode->{}, callBack->{}",
isSend, ssrc, callId, stream, tcpMode==0?"UDP":"TCP被动", callBack); isSend, ssrc, callId, stream, tcpMode==0?"UDP":"TCP被动", callBack);
MediaServer mediaServer = mediaServerService.getDefaultMediaServer(); MediaServer mediaServer = mediaServerService.getDefaultMediaServer();
@ -107,7 +104,7 @@ public class RtpController {
hookSubscribe.addSubscribe(hook, hookSubscribe.addSubscribe(hook,
(hookData)->{ (hookData)->{
if (stream.equals(hookData.getStream())) { if (stream.equals(hookData.getStream())) {
logger.info("[开启收流和获取发流信息] 等待收流超时 callId->{}, 发送回调", callId); log.info("[开启收流和获取发流信息] 等待收流超时 callId->{}, 发送回调", callId);
OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder(); OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
OkHttpClient client = httpClientBuilder.build(); OkHttpClient client = httpClientBuilder.build();
String url = callBack + "?callId=" + callId; String url = callBack + "?callId=" + callId;
@ -115,7 +112,7 @@ public class RtpController {
try { try {
client.newCall(request).execute(); client.newCall(request).execute();
} catch (IOException e) { } catch (IOException e) {
logger.error("[第三方服务对接->开启收流和获取发流信息] 等待收流超时 callId->{}, 发送回调失败", callId, e); log.error("[第三方服务对接->开启收流和获取发流信息] 等待收流超时 callId->{}, 发送回调失败", callId, e);
} }
hookSubscribe.removeSubscribe(hook); hookSubscribe.removeSubscribe(hook);
} }
@ -141,7 +138,7 @@ public class RtpController {
otherRtpSendInfo.setSendLocalPortForAudio(portForAudio); otherRtpSendInfo.setSendLocalPortForAudio(portForAudio);
// 将信息写入redis中以备后用 // 将信息写入redis中以备后用
redisTemplate.opsForValue().set(key, otherRtpSendInfo, 300, TimeUnit.SECONDS); redisTemplate.opsForValue().set(key, otherRtpSendInfo, 300, TimeUnit.SECONDS);
logger.info("[第三方服务对接->开启收流和获取发流信息] 结果callId->{} {}", callId, otherRtpSendInfo); log.info("[第三方服务对接->开启收流和获取发流信息] 结果callId->{} {}", callId, otherRtpSendInfo);
} }
// 将信息写入redis中以备后用 // 将信息写入redis中以备后用
redisTemplate.opsForValue().set(key, otherRtpSendInfo, 300, TimeUnit.SECONDS); redisTemplate.opsForValue().set(key, otherRtpSendInfo, 300, TimeUnit.SECONDS);
@ -153,7 +150,7 @@ public class RtpController {
@Operation(summary = "关闭收流", security = @SecurityRequirement(name = JwtUtils.HEADER)) @Operation(summary = "关闭收流", security = @SecurityRequirement(name = JwtUtils.HEADER))
@Parameter(name = "stream", description = "流的ID", required = true) @Parameter(name = "stream", description = "流的ID", required = true)
public void closeRtpServer(String stream) { public void closeRtpServer(String stream) {
logger.info("[第三方服务对接->关闭收流] stream->{}", stream); log.info("[第三方服务对接->关闭收流] stream->{}", stream);
MediaServer mediaServerItem = mediaServerService.getDefaultMediaServer(); MediaServer mediaServerItem = mediaServerService.getDefaultMediaServer();
mediaServerService.closeRTPServer(mediaServerItem, stream); mediaServerService.closeRTPServer(mediaServerItem, stream);
mediaServerService.closeRTPServer(mediaServerItem, stream+ "_a"); mediaServerService.closeRTPServer(mediaServerItem, stream+ "_a");
@ -193,7 +190,7 @@ public class RtpController {
@RequestParam(required = false)Integer ptForAudio, @RequestParam(required = false)Integer ptForAudio,
@RequestParam(required = false)Integer ptForVideo @RequestParam(required = false)Integer ptForVideo
) { ) {
logger.info("[第三方服务对接->发送流] " + log.info("[第三方服务对接->发送流] " +
"ssrc->{}, \r\n" + "ssrc->{}, \r\n" +
"dstIpForAudio->{}, \n" + "dstIpForAudio->{}, \n" +
"dstIpForAudio->{}, \n" + "dstIpForAudio->{}, \n" +
@ -245,20 +242,20 @@ public class RtpController {
if (streamReady) { if (streamReady) {
if (sendRtpItemForVideo != null) { if (sendRtpItemForVideo != null) {
mediaServerService.startSendRtp(mediaServer, sendRtpItemForVideo); mediaServerService.startSendRtp(mediaServer, sendRtpItemForVideo);
logger.info("[第三方服务对接->发送流] 视频流发流成功callId->{}param->{}", callId, sendRtpItemForVideo); log.info("[第三方服务对接->发送流] 视频流发流成功callId->{}param->{}", callId, sendRtpItemForVideo);
redisTemplate.opsForValue().set(key, sendInfo); redisTemplate.opsForValue().set(key, sendInfo);
} }
if(sendRtpItemForAudio != null) { if(sendRtpItemForAudio != null) {
mediaServerService.startSendRtp(mediaServer, sendRtpItemForAudio); mediaServerService.startSendRtp(mediaServer, sendRtpItemForAudio);
logger.info("[第三方服务对接->发送流] 音频流发流成功callId->{}param->{}", callId, sendRtpItemForAudio); log.info("[第三方服务对接->发送流] 音频流发流成功callId->{}param->{}", callId, sendRtpItemForAudio);
redisTemplate.opsForValue().set(key, sendInfo); redisTemplate.opsForValue().set(key, sendInfo);
} }
}else { }else {
logger.info("[第三方服务对接->发送流] 流不存在等待流上线callId->{}", callId); log.info("[第三方服务对接->发送流] 流不存在等待流上线callId->{}", callId);
String uuid = UUID.randomUUID().toString(); String uuid = UUID.randomUUID().toString();
Hook hook = Hook.getInstance(HookType.on_media_arrival, app, stream, mediaServer.getId()); Hook hook = Hook.getInstance(HookType.on_media_arrival, app, stream, mediaServer.getId());
dynamicTask.startDelay(uuid, ()->{ dynamicTask.startDelay(uuid, ()->{
logger.info("[第三方服务对接->发送流] 等待流上线超时 callId->{}", callId); log.info("[第三方服务对接->发送流] 等待流上线超时 callId->{}", callId);
redisTemplate.delete(key); redisTemplate.delete(key);
hookSubscribe.removeSubscribe(hook); hookSubscribe.removeSubscribe(hook);
}, 10000); }, 10000);
@ -269,7 +266,7 @@ public class RtpController {
hookSubscribe.addSubscribe(hook, hookSubscribe.addSubscribe(hook,
(hookData)->{ (hookData)->{
dynamicTask.stop(uuid); dynamicTask.stop(uuid);
logger.info("[第三方服务对接->发送流] 流上线,开始发流 callId->{}", callId); log.info("[第三方服务对接->发送流] 流上线,开始发流 callId->{}", callId);
try { try {
Thread.sleep(400); Thread.sleep(400);
} catch (InterruptedException e) { } catch (InterruptedException e) {
@ -277,12 +274,12 @@ public class RtpController {
} }
if (sendRtpItemForVideo != null) { if (sendRtpItemForVideo != null) {
mediaServerService.startSendRtp(mediaServer, sendRtpItemForVideo); mediaServerService.startSendRtp(mediaServer, sendRtpItemForVideo);
logger.info("[第三方服务对接->发送流] 视频流发流成功callId->{}param->{}", callId, sendRtpItemForVideo); log.info("[第三方服务对接->发送流] 视频流发流成功callId->{}param->{}", callId, sendRtpItemForVideo);
redisTemplate.opsForValue().set(key, finalSendInfo); redisTemplate.opsForValue().set(key, finalSendInfo);
} }
if(sendRtpItemForAudio != null) { if(sendRtpItemForAudio != null) {
mediaServerService.startSendRtp(mediaServer, sendRtpItemForAudio); mediaServerService.startSendRtp(mediaServer, sendRtpItemForAudio);
logger.info("[第三方服务对接->发送流] 音频流发流成功callId->{}param->{}", callId, sendRtpItemForAudio); log.info("[第三方服务对接->发送流] 音频流发流成功callId->{}param->{}", callId, sendRtpItemForAudio);
redisTemplate.opsForValue().set(key, finalSendInfo); redisTemplate.opsForValue().set(key, finalSendInfo);
} }
hookSubscribe.removeSubscribe(hook); hookSubscribe.removeSubscribe(hook);
@ -295,7 +292,7 @@ public class RtpController {
@Operation(summary = "关闭发送流", security = @SecurityRequirement(name = JwtUtils.HEADER)) @Operation(summary = "关闭发送流", security = @SecurityRequirement(name = JwtUtils.HEADER))
@Parameter(name = "callId", description = "整个过程的唯一标识,不传则使用随机端口发流", required = true) @Parameter(name = "callId", description = "整个过程的唯一标识,不传则使用随机端口发流", required = true)
public void closeSendRTP(String callId) { public void closeSendRTP(String callId) {
logger.info("[第三方服务对接->关闭发送流] callId->{}", callId); log.info("[第三方服务对接->关闭发送流] callId->{}", callId);
String key = VideoManagerConstants.WVP_OTHER_SEND_RTP_INFO + userSetting.getServerId() + "_" + callId; String key = VideoManagerConstants.WVP_OTHER_SEND_RTP_INFO + userSetting.getServerId() + "_" + callId;
OtherRtpSendInfo sendInfo = (OtherRtpSendInfo)redisTemplate.opsForValue().get(key); OtherRtpSendInfo sendInfo = (OtherRtpSendInfo)redisTemplate.opsForValue().get(key);
if (sendInfo == null){ if (sendInfo == null){
@ -303,7 +300,7 @@ public class RtpController {
} }
MediaServer mediaServerItem = mediaServerService.getDefaultMediaServer(); MediaServer mediaServerItem = mediaServerService.getDefaultMediaServer();
mediaServerService.stopSendRtp(mediaServerItem, sendInfo.getPushApp(), sendInfo.getPushStream(), sendInfo.getPushSSRC()); mediaServerService.stopSendRtp(mediaServerItem, sendInfo.getPushApp(), sendInfo.getPushStream(), sendInfo.getPushSSRC());
logger.info("[第三方服务对接->关闭发送流] 成功 callId->{}", callId); log.info("[第三方服务对接->关闭发送流] 成功 callId->{}", callId);
redisTemplate.delete(key); redisTemplate.delete(key);
} }

View File

@ -5,8 +5,7 @@ import com.genersoft.iot.vmp.gb28181.bean.Device;
import com.genersoft.iot.vmp.gb28181.transmit.cmd.impl.SIPCommander; import com.genersoft.iot.vmp.gb28181.transmit.cmd.impl.SIPCommander;
import com.genersoft.iot.vmp.storager.IVideoManagerStorage; import com.genersoft.iot.vmp.storager.IVideoManagerStorage;
import com.genersoft.iot.vmp.vmanager.bean.ErrorCode; import com.genersoft.iot.vmp.vmanager.bean.ErrorCode;
import org.slf4j.Logger; import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
@ -20,13 +19,11 @@ import java.text.ParseException;
/** /**
* API兼容设备控制 * API兼容设备控制
*/ */
@Slf4j
@RestController @RestController
@RequestMapping(value = "/api/v1/control") @RequestMapping(value = "/api/v1/control")
public class ApiControlController { public class ApiControlController {
private final static Logger logger = LoggerFactory.getLogger(ApiControlController.class);
@Autowired @Autowired
private SIPCommander cmder; private SIPCommander cmder;
@ -48,8 +45,8 @@ public class ApiControlController {
@RequestParam(required = false)String code, @RequestParam(required = false)String code,
@RequestParam(required = false)Integer speed){ @RequestParam(required = false)Integer speed){
if (logger.isDebugEnabled()) { if (log.isDebugEnabled()) {
logger.debug("模拟接口> 设备云台控制 API调用deviceId{} channelId{} command{} speed{} ", log.debug("模拟接口> 设备云台控制 API调用deviceId{} channelId{} command{} speed{} ",
serial, code, command, speed); serial, code, command, speed);
} }
if (channel == null) {channel = 0;} if (channel == null) {channel = 0;}
@ -100,7 +97,7 @@ public class ApiControlController {
try { try {
cmder.frontEndCmd(device, code, cmdCode, speed, speed, speed); cmder.frontEndCmd(device, code, cmdCode, speed, speed, speed);
} catch (SipException | InvalidArgumentException | ParseException e) { } catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] 云台控制: {}", e.getMessage()); log.error("[命令发送失败] 云台控制: {}", e.getMessage());
throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage()); throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage());
} }
} }
@ -122,8 +119,8 @@ public class ApiControlController {
@RequestParam(required = false)String name, @RequestParam(required = false)String name,
@RequestParam(required = false)Integer preset){ @RequestParam(required = false)Integer preset){
if (logger.isDebugEnabled()) { if (log.isDebugEnabled()) {
logger.debug("模拟接口> 预置位控制 API调用deviceId{} channelId{} command{} name{} preset{} ", log.debug("模拟接口> 预置位控制 API调用deviceId{} channelId{} command{} name{} preset{} ",
serial, code, command, name, preset); serial, code, command, name, preset);
} }
@ -149,7 +146,7 @@ public class ApiControlController {
try { try {
cmder.frontEndCmd(device, code, cmdCode, 0, preset, 0); cmder.frontEndCmd(device, code, cmdCode, 0, preset, 0);
} catch (SipException | InvalidArgumentException | ParseException e) { } catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] 预置位控制: {}", e.getMessage()); log.error("[命令发送失败] 预置位控制: {}", e.getMessage());
throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage()); throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage());
} }
} }

View File

@ -2,8 +2,7 @@ package com.genersoft.iot.vmp.web.gb28181;
import com.alibaba.fastjson2.JSONObject; import com.alibaba.fastjson2.JSONObject;
import com.genersoft.iot.vmp.conf.SipConfig; import com.genersoft.iot.vmp.conf.SipConfig;
import org.slf4j.Logger; import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
@ -14,12 +13,10 @@ import org.springframework.web.bind.annotation.ResponseBody;
* API兼容系统接口 * API兼容系统接口
*/ */
@Controller @Controller
@Slf4j
@RequestMapping(value = "/api/v1") @RequestMapping(value = "/api/v1")
public class ApiController { public class ApiController {
private final static Logger logger = LoggerFactory.getLogger(ApiController.class);
@Autowired @Autowired
private SipConfig sipConfig; private SipConfig sipConfig;
@ -87,8 +84,8 @@ public class ApiController {
@GetMapping(value = "/login") @GetMapping(value = "/login")
@ResponseBody @ResponseBody
private JSONObject login(String username,String password ){ private JSONObject login(String username,String password ){
if (logger.isDebugEnabled()) { if (log.isDebugEnabled()) {
logger.debug(String.format("模拟接口> 登录 API调用username%s password%s ", log.debug(String.format("模拟接口> 登录 API调用username%s password%s ",
username, password)); username, password));
} }

View File

@ -14,8 +14,7 @@ import com.genersoft.iot.vmp.vmanager.bean.DeferredResultEx;
import com.genersoft.iot.vmp.vmanager.bean.ErrorCode; import com.genersoft.iot.vmp.vmanager.bean.ErrorCode;
import com.genersoft.iot.vmp.web.gb28181.dto.DeviceChannelExtend; import com.genersoft.iot.vmp.web.gb28181.dto.DeviceChannelExtend;
import com.github.pagehelper.PageInfo; import com.github.pagehelper.PageInfo;
import org.slf4j.Logger; import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils; import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
@ -33,13 +32,11 @@ import java.util.*;
* API兼容设备信息 * API兼容设备信息
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Slf4j
@RestController @RestController
@RequestMapping(value = "/api/v1/device") @RequestMapping(value = "/api/v1/device")
public class ApiDeviceController { public class ApiDeviceController {
private final static Logger logger = LoggerFactory.getLogger(ApiDeviceController.class);
@Autowired @Autowired
private IVideoManagerStorage storager; private IVideoManagerStorage storager;
@ -194,8 +191,8 @@ public class ApiDeviceController {
@RequestParam(required = false)Boolean fill, @RequestParam(required = false)Boolean fill,
@RequestParam(required = false)Integer timeout){ @RequestParam(required = false)Integer timeout){
if (logger.isDebugEnabled()) { if (log.isDebugEnabled()) {
logger.debug("<模拟接口> 获取下级通道预置位 API调用deviceId{} channel{} code{} fill{} timeout{} ", log.debug("<模拟接口> 获取下级通道预置位 API调用deviceId{} channel{} code{} fill{} timeout{} ",
serial, channel, code, fill, timeout); serial, channel, code, fill, timeout);
} }
@ -205,7 +202,7 @@ public class ApiDeviceController {
DeferredResult<Object> result = new DeferredResult<> (timeout * 1000L); DeferredResult<Object> result = new DeferredResult<> (timeout * 1000L);
DeferredResultEx<Object> deferredResultEx = new DeferredResultEx<>(result); DeferredResultEx<Object> deferredResultEx = new DeferredResultEx<>(result);
result.onTimeout(()->{ result.onTimeout(()->{
logger.warn("<模拟接口> 获取设备预置位超时"); log.warn("<模拟接口> 获取设备预置位超时");
// 释放rtpserver // 释放rtpserver
RequestMessage msg = new RequestMessage(); RequestMessage msg = new RequestMessage();
msg.setId(uuid); msg.setId(uuid);
@ -246,7 +243,7 @@ public class ApiDeviceController {
resultHolder.invokeResult(msg); resultHolder.invokeResult(msg);
}); });
} catch (InvalidArgumentException | SipException | ParseException e) { } catch (InvalidArgumentException | SipException | ParseException e) {
logger.error("[命令发送失败] 获取设备预置位: {}", e.getMessage()); log.error("[命令发送失败] 获取设备预置位: {}", e.getMessage());
throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage()); throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage());
} }
return result; return result;

View File

@ -15,8 +15,7 @@ import com.genersoft.iot.vmp.service.IInviteStreamService;
import com.genersoft.iot.vmp.service.IPlayService; import com.genersoft.iot.vmp.service.IPlayService;
import com.genersoft.iot.vmp.service.bean.InviteErrorCode; import com.genersoft.iot.vmp.service.bean.InviteErrorCode;
import com.genersoft.iot.vmp.storager.IVideoManagerStorage; import com.genersoft.iot.vmp.storager.IVideoManagerStorage;
import org.slf4j.Logger; import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.async.DeferredResult; import org.springframework.web.context.request.async.DeferredResult;
@ -30,12 +29,11 @@ import java.text.ParseException;
*/ */
@SuppressWarnings(value = {"rawtypes", "unchecked"}) @SuppressWarnings(value = {"rawtypes", "unchecked"})
@Slf4j
@RestController @RestController
@RequestMapping(value = "/api/v1/stream") @RequestMapping(value = "/api/v1/stream")
public class ApiStreamController { public class ApiStreamController {
private final static Logger logger = LoggerFactory.getLogger(ApiStreamController.class);
@Autowired @Autowired
private SIPCommander cmder; private SIPCommander cmder;
@ -93,7 +91,7 @@ public class ApiStreamController {
return result; return result;
} }
result.onTimeout(()->{ result.onTimeout(()->{
logger.info("播放等待超时"); log.info("播放等待超时");
JSONObject resultJSON = new JSONObject(); JSONObject resultJSON = new JSONObject();
resultJSON.put("error","timeout"); resultJSON.put("error","timeout");
result.setResult(resultJSON); result.setResult(resultJSON);