DeviceServiceImpl.java 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692
  1. package com.genersoft.iot.vmp.service.impl;
  2. import com.genersoft.iot.vmp.common.InviteSessionType;
  3. import com.genersoft.iot.vmp.common.VideoManagerConstants;
  4. import com.genersoft.iot.vmp.conf.DynamicTask;
  5. import com.genersoft.iot.vmp.conf.UserSetting;
  6. import com.genersoft.iot.vmp.conf.exception.SsrcTransactionNotFoundException;
  7. import com.genersoft.iot.vmp.gb28181.bean.*;
  8. import com.genersoft.iot.vmp.gb28181.session.VideoStreamSessionManager;
  9. import com.genersoft.iot.vmp.gb28181.task.ISubscribeTask;
  10. import com.genersoft.iot.vmp.gb28181.task.impl.CatalogSubscribeTask;
  11. import com.genersoft.iot.vmp.gb28181.task.impl.MobilePositionSubscribeTask;
  12. import com.genersoft.iot.vmp.gb28181.transmit.cmd.ISIPCommander;
  13. import com.genersoft.iot.vmp.gb28181.transmit.cmd.impl.SIPCommander;
  14. import com.genersoft.iot.vmp.gb28181.transmit.event.request.impl.message.response.cmd.CatalogResponseMessageHandler;
  15. import com.genersoft.iot.vmp.service.IDeviceChannelService;
  16. import com.genersoft.iot.vmp.service.IDeviceService;
  17. import com.genersoft.iot.vmp.service.IInviteStreamService;
  18. import com.genersoft.iot.vmp.service.IMediaServerService;
  19. import com.genersoft.iot.vmp.storager.IRedisCatchStorage;
  20. import com.genersoft.iot.vmp.storager.dao.DeviceChannelMapper;
  21. import com.genersoft.iot.vmp.storager.dao.DeviceMapper;
  22. import com.genersoft.iot.vmp.storager.dao.PlatformChannelMapper;
  23. import com.genersoft.iot.vmp.utils.DateUtil;
  24. import com.genersoft.iot.vmp.vmanager.bean.BaseTree;
  25. import com.genersoft.iot.vmp.vmanager.bean.ResourceBaseInfo;
  26. import org.slf4j.Logger;
  27. import org.slf4j.LoggerFactory;
  28. import org.springframework.beans.factory.annotation.Autowired;
  29. import org.springframework.jdbc.datasource.DataSourceTransactionManager;
  30. import org.springframework.stereotype.Service;
  31. import org.springframework.transaction.TransactionDefinition;
  32. import org.springframework.transaction.TransactionStatus;
  33. import org.springframework.util.ObjectUtils;
  34. import javax.sip.InvalidArgumentException;
  35. import javax.sip.SipException;
  36. import java.text.ParseException;
  37. import java.time.Instant;
  38. import java.util.ArrayList;
  39. import java.util.Collections;
  40. import java.util.List;
  41. import java.util.concurrent.TimeUnit;
  42. /**
  43. * 设备业务(目录订阅)
  44. */
  45. @Service
  46. public class DeviceServiceImpl implements IDeviceService {
  47. private final static Logger logger = LoggerFactory.getLogger(DeviceServiceImpl.class);
  48. @Autowired
  49. private SIPCommander cmder;
  50. @Autowired
  51. private DynamicTask dynamicTask;
  52. @Autowired
  53. private ISIPCommander sipCommander;
  54. @Autowired
  55. private CatalogResponseMessageHandler catalogResponseMessageHandler;
  56. @Autowired
  57. private IRedisCatchStorage redisCatchStorage;
  58. @Autowired
  59. private IInviteStreamService inviteStreamService;
  60. @Autowired
  61. private DeviceMapper deviceMapper;
  62. @Autowired
  63. private PlatformChannelMapper platformChannelMapper;
  64. @Autowired
  65. private IDeviceChannelService deviceChannelService;
  66. @Autowired
  67. private DeviceChannelMapper deviceChannelMapper;
  68. @Autowired
  69. DataSourceTransactionManager dataSourceTransactionManager;
  70. @Autowired
  71. TransactionDefinition transactionDefinition;
  72. @Autowired
  73. private UserSetting userSetting;
  74. @Autowired
  75. private ISIPCommander commander;
  76. @Autowired
  77. private VideoStreamSessionManager streamSession;
  78. @Autowired
  79. private IMediaServerService mediaServerService;
  80. @Override
  81. public void online(Device device, SipTransactionInfo sipTransactionInfo) {
  82. logger.info("[设备上线] deviceId:{}->{}:{}", device.getDeviceId(), device.getIp(), device.getPort());
  83. Device deviceInRedis = redisCatchStorage.getDevice(device.getDeviceId());
  84. Device deviceInDb = deviceMapper.getDeviceByDeviceId(device.getDeviceId());
  85. String now = DateUtil.getNow();
  86. if (deviceInRedis != null && deviceInDb == null) {
  87. // redis 存在脏数据
  88. inviteStreamService.clearInviteInfo(device.getDeviceId());
  89. }
  90. device.setUpdateTime(now);
  91. if (device.getKeepaliveIntervalTime() == 0) {
  92. // 默认心跳间隔60
  93. device.setKeepaliveIntervalTime(60);
  94. }
  95. if (sipTransactionInfo != null) {
  96. device.setSipTransactionInfo(sipTransactionInfo);
  97. }else {
  98. if (deviceInRedis != null) {
  99. device.setSipTransactionInfo(deviceInRedis.getSipTransactionInfo());
  100. }
  101. }
  102. // 第一次上线 或则设备之前是离线状态--进行通道同步和设备信息查询
  103. if (device.getCreateTime() == null) {
  104. device.setOnLine(true);
  105. device.setCreateTime(now);
  106. logger.info("[设备上线,首次注册]: {},查询设备信息以及通道信息", device.getDeviceId());
  107. deviceMapper.add(device);
  108. redisCatchStorage.updateDevice(device);
  109. try {
  110. commander.deviceInfoQuery(device);
  111. } catch (InvalidArgumentException | SipException | ParseException e) {
  112. logger.error("[命令发送失败] 查询设备信息: {}", e.getMessage());
  113. }
  114. sync(device);
  115. }else {
  116. if (deviceInDb != null) {
  117. device.setSwitchPrimarySubStream(deviceInDb.isSwitchPrimarySubStream());
  118. }
  119. if(!device.isOnLine()){
  120. device.setOnLine(true);
  121. device.setCreateTime(now);
  122. deviceMapper.update(device);
  123. redisCatchStorage.updateDevice(device);
  124. if (userSetting.getSyncChannelOnDeviceOnline()) {
  125. logger.info("[设备上线,离线状态下重新注册]: {},查询设备信息以及通道信息", device.getDeviceId());
  126. try {
  127. commander.deviceInfoQuery(device);
  128. } catch (InvalidArgumentException | SipException | ParseException e) {
  129. logger.error("[命令发送失败] 查询设备信息: {}", e.getMessage());
  130. }
  131. sync(device);
  132. // TODO 如果设备下的通道级联到了其他平台,那么需要发送事件或者notify给上级平台
  133. }
  134. }else {
  135. if (deviceChannelMapper.queryAllChannels(device.getDeviceId()).size() == 0) {
  136. logger.info("[设备上线]: {},通道数为0,查询通道信息", device.getDeviceId());
  137. sync(device);
  138. }
  139. deviceMapper.update(device);
  140. redisCatchStorage.updateDevice(device);
  141. }
  142. }
  143. // 上线添加订阅
  144. if (device.getSubscribeCycleForCatalog() > 0) {
  145. // 查询在线设备那些开启了订阅,为设备开启定时的目录订阅
  146. addCatalogSubscribe(device);
  147. }
  148. if (device.getSubscribeCycleForMobilePosition() > 0) {
  149. addMobilePositionSubscribe(device);
  150. }
  151. // 刷新过期任务
  152. String registerExpireTaskKey = VideoManagerConstants.REGISTER_EXPIRE_TASK_KEY_PREFIX + device.getDeviceId();
  153. // 如果第一次注册那么必须在60 * 3时间内收到一个心跳,否则设备离线
  154. dynamicTask.startDelay(registerExpireTaskKey, ()-> offline(device.getDeviceId(), "首次注册后未能收到心跳"), device.getKeepaliveIntervalTime() * 1000 * 3);
  155. if (userSetting.getDeviceStatusNotify()) {
  156. // 发送redis消息
  157. redisCatchStorage.sendDeviceOrChannelStatus(device.getDeviceId(), null, true);
  158. }
  159. }
  160. @Override
  161. public void offline(String deviceId, String reason) {
  162. logger.warn("[设备离线],{}, device:{}", reason, deviceId);
  163. Device device = deviceMapper.getDeviceByDeviceId(deviceId);
  164. if (device == null) {
  165. return;
  166. }
  167. String registerExpireTaskKey = VideoManagerConstants.REGISTER_EXPIRE_TASK_KEY_PREFIX + deviceId;
  168. dynamicTask.stop(registerExpireTaskKey);
  169. device.setOnLine(false);
  170. redisCatchStorage.updateDevice(device);
  171. deviceMapper.update(device);
  172. //进行通道离线
  173. // deviceChannelMapper.offlineByDeviceId(deviceId);
  174. // 离线释放所有ssrc
  175. List<SsrcTransaction> ssrcTransactions = streamSession.getSsrcTransactionForAll(deviceId, null, null, null);
  176. if (ssrcTransactions != null && ssrcTransactions.size() > 0) {
  177. for (SsrcTransaction ssrcTransaction : ssrcTransactions) {
  178. mediaServerService.releaseSsrc(ssrcTransaction.getMediaServerId(), ssrcTransaction.getSsrc());
  179. mediaServerService.closeRTPServer(ssrcTransaction.getMediaServerId(), ssrcTransaction.getStream());
  180. streamSession.remove(deviceId, ssrcTransaction.getChannelId(), ssrcTransaction.getStream());
  181. }
  182. }
  183. // 移除订阅
  184. removeCatalogSubscribe(device);
  185. removeMobilePositionSubscribe(device);
  186. if (userSetting.getDeviceStatusNotify()) {
  187. // 发送redis消息
  188. redisCatchStorage.sendDeviceOrChannelStatus(device.getDeviceId(), null, false);
  189. }
  190. }
  191. @Override
  192. public boolean addCatalogSubscribe(Device device) {
  193. if (device == null || device.getSubscribeCycleForCatalog() < 0) {
  194. return false;
  195. }
  196. logger.info("[添加目录订阅] 设备{}", device.getDeviceId());
  197. // 添加目录订阅
  198. CatalogSubscribeTask catalogSubscribeTask = new CatalogSubscribeTask(device, sipCommander, dynamicTask);
  199. // 刷新订阅
  200. int subscribeCycleForCatalog = Math.max(device.getSubscribeCycleForCatalog(),30);
  201. // 设置最小值为30
  202. dynamicTask.startCron(device.getDeviceId() + "catalog", catalogSubscribeTask, (subscribeCycleForCatalog -1) * 1000);
  203. return true;
  204. }
  205. @Override
  206. public boolean removeCatalogSubscribe(Device device) {
  207. if (device == null || device.getSubscribeCycleForCatalog() < 0) {
  208. return false;
  209. }
  210. logger.info("[移除目录订阅]: {}", device.getDeviceId());
  211. String taskKey = device.getDeviceId() + "catalog";
  212. if (device.isOnLine()) {
  213. Runnable runnable = dynamicTask.get(taskKey);
  214. if (runnable instanceof ISubscribeTask) {
  215. ISubscribeTask subscribeTask = (ISubscribeTask) runnable;
  216. subscribeTask.stop();
  217. }
  218. }
  219. dynamicTask.stop(taskKey);
  220. return true;
  221. }
  222. @Override
  223. public boolean addMobilePositionSubscribe(Device device) {
  224. if (device == null || device.getSubscribeCycleForMobilePosition() < 0) {
  225. return false;
  226. }
  227. logger.info("[添加移动位置订阅] 设备{}", device.getDeviceId());
  228. // 添加目录订阅
  229. MobilePositionSubscribeTask mobilePositionSubscribeTask = new MobilePositionSubscribeTask(device, sipCommander, dynamicTask);
  230. // 设置最小值为30
  231. int subscribeCycleForCatalog = Math.max(device.getSubscribeCycleForMobilePosition(),30);
  232. // 刷新订阅
  233. dynamicTask.startCron(device.getDeviceId() + "mobile_position" , mobilePositionSubscribeTask, (subscribeCycleForCatalog) * 1000);
  234. return true;
  235. }
  236. @Override
  237. public boolean removeMobilePositionSubscribe(Device device) {
  238. if (device == null || device.getSubscribeCycleForCatalog() < 0) {
  239. return false;
  240. }
  241. logger.info("[移除移动位置订阅]: {}", device.getDeviceId());
  242. String taskKey = device.getDeviceId() + "mobile_position";
  243. if (device.isOnLine()) {
  244. Runnable runnable = dynamicTask.get(taskKey);
  245. if (runnable instanceof ISubscribeTask) {
  246. ISubscribeTask subscribeTask = (ISubscribeTask) runnable;
  247. subscribeTask.stop();
  248. }
  249. }
  250. dynamicTask.stop(taskKey);
  251. return true;
  252. }
  253. @Override
  254. public SyncStatus getChannelSyncStatus(String deviceId) {
  255. return catalogResponseMessageHandler.getChannelSyncProgress(deviceId);
  256. }
  257. @Override
  258. public Boolean isSyncRunning(String deviceId) {
  259. return catalogResponseMessageHandler.isSyncRunning(deviceId);
  260. }
  261. @Override
  262. public void sync(Device device) {
  263. if (catalogResponseMessageHandler.isSyncRunning(device.getDeviceId())) {
  264. logger.info("开启同步时发现同步已经存在");
  265. return;
  266. }
  267. int sn = (int)((Math.random()*9+1)*100000);
  268. catalogResponseMessageHandler.setChannelSyncReady(device, sn);
  269. try {
  270. sipCommander.catalogQuery(device, sn, event -> {
  271. String errorMsg = String.format("同步通道失败,错误码: %s, %s", event.statusCode, event.msg);
  272. catalogResponseMessageHandler.setChannelSyncEnd(device.getDeviceId(), errorMsg);
  273. });
  274. } catch (SipException | InvalidArgumentException | ParseException e) {
  275. logger.error("[同步通道], 信令发送失败:{}", e.getMessage() );
  276. String errorMsg = String.format("同步通道失败,信令发送失败: %s", e.getMessage());
  277. catalogResponseMessageHandler.setChannelSyncEnd(device.getDeviceId(), errorMsg);
  278. }
  279. }
  280. @Override
  281. public Device getDevice(String deviceId) {
  282. Device device = redisCatchStorage.getDevice(deviceId);
  283. if (device == null) {
  284. device = deviceMapper.getDeviceByDeviceId(deviceId);
  285. if (device != null) {
  286. redisCatchStorage.updateDevice(device);
  287. }
  288. }
  289. return device;
  290. }
  291. @Override
  292. public List<Device> getAllOnlineDevice() {
  293. return deviceMapper.getOnlineDevices();
  294. }
  295. @Override
  296. public boolean expire(Device device) {
  297. Instant registerTimeDate = Instant.from(DateUtil.formatter.parse(device.getRegisterTime()));
  298. Instant expireInstant = registerTimeDate.plusMillis(TimeUnit.SECONDS.toMillis(device.getExpires()));
  299. return expireInstant.isBefore(Instant.now());
  300. }
  301. @Override
  302. public void checkDeviceStatus(Device device) {
  303. if (device == null || !device.isOnLine()) {
  304. return;
  305. }
  306. try {
  307. sipCommander.deviceStatusQuery(device, null);
  308. } catch (InvalidArgumentException | SipException | ParseException e) {
  309. logger.error("[命令发送失败] 设备状态查询: {}", e.getMessage());
  310. }
  311. }
  312. @Override
  313. public Device getDeviceByHostAndPort(String host, int port) {
  314. return deviceMapper.getDeviceByHostAndPort(host, port);
  315. }
  316. @Override
  317. public void updateDevice(Device device) {
  318. String now = DateUtil.getNow();
  319. device.setUpdateTime(now);
  320. device.setCharset(device.getCharset().toUpperCase());
  321. device.setUpdateTime(DateUtil.getNow());
  322. if (deviceMapper.update(device) > 0) {
  323. redisCatchStorage.updateDevice(device);
  324. }
  325. }
  326. /**
  327. * 更新通道坐标系
  328. */
  329. private void updateDeviceChannelGeoCoordSys(Device device) {
  330. List<DeviceChannel> deviceChannels = deviceChannelMapper.getAllChannelWithCoordinate(device.getDeviceId());
  331. if (deviceChannels.size() > 0) {
  332. List<DeviceChannel> deviceChannelsForStore = new ArrayList<>();
  333. for (DeviceChannel deviceChannel : deviceChannels) {
  334. deviceChannelsForStore.add(deviceChannelService.updateGps(deviceChannel, device));
  335. }
  336. deviceChannelService.updateChannels(device.getDeviceId(), deviceChannelsForStore);
  337. }
  338. }
  339. @Override
  340. public List<BaseTree<DeviceChannel>> queryVideoDeviceTree(String deviceId, String parentId, boolean onlyCatalog) {
  341. Device device = deviceMapper.getDeviceByDeviceId(deviceId);
  342. if (device == null) {
  343. return null;
  344. }
  345. if (parentId == null || parentId.equals(deviceId)) {
  346. // 字根节点开始查询
  347. List<DeviceChannel> rootNodes = getRootNodes(deviceId, TreeType.CIVIL_CODE.equals(device.getTreeType()), true, !onlyCatalog);
  348. return transportChannelsToTree(rootNodes, "");
  349. }
  350. if (TreeType.CIVIL_CODE.equals(device.getTreeType())) {
  351. if (parentId.length()%2 != 0) {
  352. return null;
  353. }
  354. // 使用行政区划展示树
  355. // if (parentId.length() > 10) {
  356. // // TODO 可能是行政区划与业务分组混杂的情形
  357. // return null;
  358. // }
  359. if (parentId.length() == 10 ) {
  360. if (onlyCatalog) {
  361. return null;
  362. }
  363. // parentId为行业编码, 其下不会再有行政区划
  364. List<DeviceChannel> channels = deviceChannelMapper.getChannelsByCivilCode(deviceId, parentId);
  365. List<BaseTree<DeviceChannel>> trees = transportChannelsToTree(channels, parentId);
  366. return trees;
  367. }
  368. // 查询其下的行政区划和摄像机
  369. List<DeviceChannel> channelsForCivilCode = deviceChannelMapper.getChannelsWithCivilCodeAndLength(deviceId, parentId, parentId.length() + 2);
  370. if (!onlyCatalog) {
  371. List<DeviceChannel> channels = deviceChannelMapper.getChannelsByCivilCode(deviceId, parentId);
  372. for(DeviceChannel channel : channels) {
  373. boolean flag = false;
  374. for(DeviceChannel deviceChannel : channelsForCivilCode) {
  375. if(channel.getChannelId().equals(deviceChannel.getChannelId())) {
  376. flag = true;
  377. }
  378. }
  379. if(!flag) {
  380. channelsForCivilCode.add(channel);
  381. }
  382. }
  383. }
  384. List<BaseTree<DeviceChannel>> trees = transportChannelsToTree(channelsForCivilCode, parentId);
  385. return trees;
  386. }
  387. // 使用业务分组展示树
  388. if (TreeType.BUSINESS_GROUP.equals(device.getTreeType())) {
  389. if (parentId.length() < 14 ) {
  390. return null;
  391. }
  392. List<DeviceChannel> deviceChannels = deviceChannelMapper.queryChannels(deviceId, parentId, null, null, null,null);
  393. List<BaseTree<DeviceChannel>> trees = transportChannelsToTree(deviceChannels, parentId);
  394. return trees;
  395. }
  396. return null;
  397. }
  398. @Override
  399. public List<DeviceChannel> queryVideoDeviceInTreeNode(String deviceId, String parentId) {
  400. Device device = deviceMapper.getDeviceByDeviceId(deviceId);
  401. if (device == null) {
  402. return null;
  403. }
  404. if (parentId == null || parentId.equals(deviceId)) {
  405. // 字根节点开始查询
  406. List<DeviceChannel> rootNodes = getRootNodes(deviceId, TreeType.CIVIL_CODE.equals(device.getTreeType()), false, true);
  407. return rootNodes;
  408. }
  409. if (TreeType.CIVIL_CODE.equals(device.getTreeType())) {
  410. if (parentId.length()%2 != 0) {
  411. return null;
  412. }
  413. // 使用行政区划展示树
  414. if (parentId.length() > 10) {
  415. // TODO 可能是行政区划与业务分组混杂的情形
  416. return null;
  417. }
  418. if (parentId.length() == 10 ) {
  419. // parentId为行业编码, 其下不会再有行政区划
  420. List<DeviceChannel> channels = deviceChannelMapper.getChannelsByCivilCode(deviceId, parentId);
  421. return channels;
  422. }
  423. // 查询其下的行政区划和摄像机
  424. List<DeviceChannel> channels = deviceChannelMapper.getChannelsByCivilCode(deviceId, parentId);
  425. return channels;
  426. }
  427. // 使用业务分组展示树
  428. if (TreeType.BUSINESS_GROUP.equals(device.getTreeType())) {
  429. if (parentId.length() < 14 ) {
  430. return null;
  431. }
  432. List<DeviceChannel> deviceChannels = deviceChannelMapper.queryChannels(deviceId, parentId, null, null, null,null);
  433. return deviceChannels;
  434. }
  435. return null;
  436. }
  437. private List<BaseTree<DeviceChannel>> transportChannelsToTree(List<DeviceChannel> channels, String parentId) {
  438. if (channels == null) {
  439. return null;
  440. }
  441. List<BaseTree<DeviceChannel>> treeNotes = new ArrayList<>();
  442. if (channels.size() == 0) {
  443. return treeNotes;
  444. }
  445. for (DeviceChannel channel : channels) {
  446. BaseTree<DeviceChannel> node = new BaseTree<>();
  447. node.setId(channel.getChannelId());
  448. node.setDeviceId(channel.getDeviceId());
  449. node.setName(channel.getName());
  450. node.setPid(parentId);
  451. node.setBasicData(channel);
  452. node.setParent(false);
  453. if (channel.getChannelId().length() > 8) {
  454. if (channel.getChannelId().length() > 13) {
  455. String gbCodeType = channel.getChannelId().substring(10, 13);
  456. node.setParent(gbCodeType.equals(ChannelIdType.BUSINESS_GROUP) || gbCodeType.equals(ChannelIdType.VIRTUAL_ORGANIZATION) );
  457. }
  458. }else {
  459. node.setParent(true);
  460. }
  461. treeNotes.add(node);
  462. }
  463. Collections.sort(treeNotes);
  464. return treeNotes;
  465. }
  466. private List<DeviceChannel> getRootNodes(String deviceId, boolean isCivilCode, boolean haveCatalog, boolean haveChannel) {
  467. if (!haveCatalog && !haveChannel) {
  468. return null;
  469. }
  470. List<DeviceChannel> result = new ArrayList<>();
  471. if (isCivilCode) {
  472. // 使用行政区划
  473. Integer length= deviceChannelMapper.getChannelMinLength(deviceId);
  474. if (length == null) {
  475. return null;
  476. }
  477. if (length <= 10) {
  478. if (haveCatalog) {
  479. List<DeviceChannel> provinceNode = deviceChannelMapper.getChannelsWithCivilCodeAndLength(deviceId, null, length);
  480. if (provinceNode != null && provinceNode.size() > 0) {
  481. result.addAll(provinceNode);
  482. }
  483. }
  484. if (haveChannel) {
  485. // 查询那些civilCode不在通道中的不规范通道,放置在根目录
  486. List<DeviceChannel> nonstandardNode = deviceChannelMapper.getChannelWithoutCivilCode(deviceId);
  487. if (nonstandardNode != null && nonstandardNode.size() > 0) {
  488. result.addAll(nonstandardNode);
  489. }
  490. }
  491. }else {
  492. if (haveChannel) {
  493. List<DeviceChannel> deviceChannels = deviceChannelMapper.queryChannels(deviceId, null, null, null, null,null);
  494. if (deviceChannels != null && deviceChannels.size() > 0) {
  495. result.addAll(deviceChannels);
  496. }
  497. }
  498. }
  499. }else {
  500. // 使用业务分组+虚拟组织
  501. // 只获取业务分组
  502. List<DeviceChannel> deviceChannels = deviceChannelMapper.getBusinessGroups(deviceId, ChannelIdType.BUSINESS_GROUP);
  503. if (deviceChannels != null && deviceChannels.size() > 0) {
  504. result.addAll(deviceChannels);
  505. }
  506. }
  507. return result;
  508. }
  509. @Override
  510. public boolean isExist(String deviceId) {
  511. return deviceMapper.getDeviceByDeviceId(deviceId) != null;
  512. }
  513. @Override
  514. public void addDevice(Device device) {
  515. device.setOnLine(false);
  516. device.setCreateTime(DateUtil.getNow());
  517. device.setUpdateTime(DateUtil.getNow());
  518. deviceMapper.addCustomDevice(device);
  519. }
  520. @Override
  521. public void updateCustomDevice(Device device) {
  522. Device deviceInStore = deviceMapper.getDeviceByDeviceId(device.getDeviceId());
  523. if (deviceInStore == null) {
  524. logger.warn("更新设备时未找到设备信息");
  525. return;
  526. }
  527. if(deviceInStore.isSwitchPrimarySubStream() != device.isSwitchPrimarySubStream()){
  528. //当修改设备的主子码流开关时,需要校验是否存在流,如果存在流则直接关闭
  529. List<SsrcTransaction> ssrcTransactionForAll = streamSession.getSsrcTransactionForAll(device.getDeviceId(), null, null, null);
  530. if(ssrcTransactionForAll != null){
  531. for (SsrcTransaction ssrcTransaction: ssrcTransactionForAll) {
  532. try {
  533. cmder.streamByeCmd(device, ssrcTransaction.getChannelId(), ssrcTransaction.getStream(), null, null);
  534. } catch (InvalidArgumentException | SsrcTransactionNotFoundException | ParseException | SipException e) {
  535. throw new RuntimeException(e);
  536. }
  537. }
  538. }
  539. deviceChannelMapper.clearPlay(device.getDeviceId());
  540. inviteStreamService.clearInviteInfo(device.getDeviceId());
  541. }
  542. if (!ObjectUtils.isEmpty(device.getName())) {
  543. deviceInStore.setName(device.getName());
  544. }
  545. if (!ObjectUtils.isEmpty(device.getCharset())) {
  546. deviceInStore.setCharset(device.getCharset());
  547. }
  548. if (!ObjectUtils.isEmpty(device.getMediaServerId())) {
  549. deviceInStore.setMediaServerId(device.getMediaServerId());
  550. }
  551. deviceInStore.setSdpIp(device.getSdpIp());
  552. deviceInStore.setCharset(device.getCharset());
  553. deviceInStore.setTreeType(device.getTreeType());
  554. // 目录订阅相关的信息
  555. if (device.getSubscribeCycleForCatalog() > 0) {
  556. if (deviceInStore.getSubscribeCycleForCatalog() == 0 || deviceInStore.getSubscribeCycleForCatalog() != device.getSubscribeCycleForCatalog()) {
  557. deviceInStore.setSubscribeCycleForCatalog(device.getSubscribeCycleForCatalog());
  558. // 开启订阅
  559. addCatalogSubscribe(deviceInStore);
  560. }
  561. }else if (device.getSubscribeCycleForCatalog() == 0) {
  562. if (deviceInStore.getSubscribeCycleForCatalog() != 0) {
  563. deviceInStore.setSubscribeCycleForCatalog(device.getSubscribeCycleForCatalog());
  564. // 取消订阅
  565. removeCatalogSubscribe(deviceInStore);
  566. }
  567. }
  568. // 移动位置订阅相关的信息
  569. if (device.getSubscribeCycleForMobilePosition() > 0) {
  570. if (deviceInStore.getSubscribeCycleForMobilePosition() == 0 || deviceInStore.getSubscribeCycleForMobilePosition() != device.getSubscribeCycleForMobilePosition()) {
  571. deviceInStore.setMobilePositionSubmissionInterval(device.getMobilePositionSubmissionInterval());
  572. deviceInStore.setSubscribeCycleForMobilePosition(device.getSubscribeCycleForMobilePosition());
  573. // 开启订阅
  574. addMobilePositionSubscribe(deviceInStore);
  575. }
  576. }else if (device.getSubscribeCycleForMobilePosition() == 0) {
  577. if (deviceInStore.getSubscribeCycleForMobilePosition() != 0) {
  578. // 取消订阅
  579. removeMobilePositionSubscribe(deviceInStore);
  580. }
  581. }
  582. // 坐标系变化,需要重新计算GCJ02坐标和WGS84坐标
  583. if (!deviceInStore.getGeoCoordSys().equals(device.getGeoCoordSys())) {
  584. updateDeviceChannelGeoCoordSys(device);
  585. }
  586. // 更新redis
  587. redisCatchStorage.updateDevice(device);
  588. deviceMapper.updateCustom(device);
  589. }
  590. @Override
  591. public boolean delete(String deviceId) {
  592. TransactionStatus transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);
  593. boolean result = false;
  594. try {
  595. platformChannelMapper.delChannelForDeviceId(deviceId);
  596. deviceChannelMapper.cleanChannelsByDeviceId(deviceId);
  597. if ( deviceMapper.del(deviceId) < 0 ) {
  598. //事务回滚
  599. dataSourceTransactionManager.rollback(transactionStatus);
  600. }
  601. result = true;
  602. dataSourceTransactionManager.commit(transactionStatus); //手动提交
  603. }catch (Exception e) {
  604. dataSourceTransactionManager.rollback(transactionStatus);
  605. }
  606. return result;
  607. }
  608. @Override
  609. public ResourceBaseInfo getOverview() {
  610. List<Device> onlineDevices = deviceMapper.getOnlineDevices();
  611. List<Device> all = deviceMapper.getAll();
  612. return new ResourceBaseInfo(all.size(), onlineDevices.size());
  613. }
  614. @Override
  615. public List<Device> getAll() {
  616. return deviceMapper.getAll();
  617. }
  618. }