DeviceServiceImpl.java 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. package com.genersoft.iot.vmp.service.impl;
  2. import com.genersoft.iot.vmp.conf.DynamicTask;
  3. import com.genersoft.iot.vmp.gb28181.bean.*;
  4. import com.genersoft.iot.vmp.gb28181.session.VideoStreamSessionManager;
  5. import com.genersoft.iot.vmp.gb28181.task.ISubscribeTask;
  6. import com.genersoft.iot.vmp.gb28181.transmit.cmd.ISIPCommander;
  7. import com.genersoft.iot.vmp.gb28181.transmit.event.request.impl.message.response.cmd.CatalogResponseMessageHandler;
  8. import com.genersoft.iot.vmp.gb28181.utils.Coordtransform;
  9. import com.genersoft.iot.vmp.service.IDeviceChannelService;
  10. import com.genersoft.iot.vmp.service.IDeviceService;
  11. import com.genersoft.iot.vmp.gb28181.task.impl.CatalogSubscribeTask;
  12. import com.genersoft.iot.vmp.gb28181.task.impl.MobilePositionSubscribeTask;
  13. import com.genersoft.iot.vmp.service.IMediaServerService;
  14. import com.genersoft.iot.vmp.storager.IRedisCatchStorage;
  15. import com.genersoft.iot.vmp.storager.IVideoManagerStorage;
  16. import com.genersoft.iot.vmp.storager.dao.DeviceChannelMapper;
  17. import com.genersoft.iot.vmp.storager.dao.DeviceMapper;
  18. import com.genersoft.iot.vmp.utils.DateUtil;
  19. import com.genersoft.iot.vmp.vmanager.bean.BaseTree;
  20. import org.slf4j.Logger;
  21. import org.slf4j.LoggerFactory;
  22. import org.springframework.beans.factory.annotation.Autowired;
  23. import org.springframework.jdbc.support.incrementer.AbstractIdentityColumnMaxValueIncrementer;
  24. import org.springframework.stereotype.Service;
  25. import org.springframework.util.StringUtils;
  26. import java.time.Instant;
  27. import java.util.ArrayList;
  28. import java.util.Collections;
  29. import java.util.List;
  30. import java.util.concurrent.TimeUnit;
  31. /**
  32. * 设备业务(目录订阅)
  33. */
  34. @Service
  35. public class DeviceServiceImpl implements IDeviceService {
  36. private final static Logger logger = LoggerFactory.getLogger(DeviceServiceImpl.class);
  37. private final String registerExpireTaskKeyPrefix = "device-register-expire-";
  38. @Autowired
  39. private DynamicTask dynamicTask;
  40. @Autowired
  41. private ISIPCommander sipCommander;
  42. @Autowired
  43. private CatalogResponseMessageHandler catalogResponseMessageHandler;
  44. @Autowired
  45. private IRedisCatchStorage redisCatchStorage;
  46. @Autowired
  47. private DeviceMapper deviceMapper;
  48. @Autowired
  49. private IDeviceChannelService deviceChannelService;
  50. @Autowired
  51. private DeviceChannelMapper deviceChannelMapper;
  52. @Autowired
  53. private IVideoManagerStorage storage;
  54. @Autowired
  55. private ISIPCommander commander;
  56. @Autowired
  57. private VideoStreamSessionManager streamSession;
  58. @Autowired
  59. private IMediaServerService mediaServerService;
  60. @Override
  61. public void online(Device device) {
  62. logger.info("[设备上线] deviceId:{}->{}:{}", device.getDeviceId(), device.getIp(), device.getPort());
  63. Device deviceInRedis = redisCatchStorage.getDevice(device.getDeviceId());
  64. Device deviceInDb = deviceMapper.getDeviceByDeviceId(device.getDeviceId());
  65. String now = DateUtil.getNow();
  66. if (deviceInRedis != null && deviceInDb == null) {
  67. // redis 存在脏数据
  68. redisCatchStorage.clearCatchByDeviceId(device.getDeviceId());
  69. }
  70. device.setUpdateTime(now);
  71. // 第一次上线 或则设备之前是离线状态--进行通道同步和设备信息查询
  72. if (device.getCreateTime() == null) {
  73. device.setOnline(1);
  74. device.setCreateTime(now);
  75. logger.info("[设备上线,首次注册]: {},查询设备信息以及通道信息", device.getDeviceId());
  76. deviceMapper.add(device);
  77. redisCatchStorage.updateDevice(device);
  78. commander.deviceInfoQuery(device);
  79. sync(device);
  80. }else {
  81. if(device.getOnline() == 0){
  82. device.setOnline(1);
  83. device.setCreateTime(now);
  84. logger.info("[设备上线,离线状态下重新注册]: {},查询设备信息以及通道信息", device.getDeviceId());
  85. deviceMapper.update(device);
  86. redisCatchStorage.updateDevice(device);
  87. commander.deviceInfoQuery(device);
  88. sync(device);
  89. // TODO 如果设备下的通道级联到了其他平台,那么需要发送事件或者notify给上级平台
  90. }else {
  91. deviceMapper.update(device);
  92. redisCatchStorage.updateDevice(device);
  93. }
  94. }
  95. // 上线添加订阅
  96. if (device.getSubscribeCycleForCatalog() > 0) {
  97. // 查询在线设备那些开启了订阅,为设备开启定时的目录订阅
  98. addCatalogSubscribe(device);
  99. }
  100. if (device.getSubscribeCycleForMobilePosition() > 0) {
  101. addMobilePositionSubscribe(device);
  102. }
  103. // 刷新过期任务
  104. String registerExpireTaskKey = registerExpireTaskKeyPrefix + device.getDeviceId();
  105. dynamicTask.startDelay(registerExpireTaskKey, ()-> offline(device.getDeviceId()), device.getExpires() * 1000);
  106. }
  107. @Override
  108. public void offline(String deviceId) {
  109. Device device = deviceMapper.getDeviceByDeviceId(deviceId);
  110. if (device == null) {
  111. return;
  112. }
  113. String registerExpireTaskKey = registerExpireTaskKeyPrefix + deviceId;
  114. dynamicTask.stop(registerExpireTaskKey);
  115. device.setOnline(0);
  116. redisCatchStorage.updateDevice(device);
  117. deviceMapper.update(device);
  118. //进行通道离线
  119. deviceChannelMapper.offlineByDeviceId(deviceId);
  120. // 离线释放所有ssrc
  121. List<SsrcTransaction> ssrcTransactions = streamSession.getSsrcTransactionForAll(deviceId, null, null, null);
  122. if (ssrcTransactions != null && ssrcTransactions.size() > 0) {
  123. for (SsrcTransaction ssrcTransaction : ssrcTransactions) {
  124. mediaServerService.releaseSsrc(ssrcTransaction.getMediaServerId(), ssrcTransaction.getSsrc());
  125. mediaServerService.closeRTPServer(deviceId, ssrcTransaction.getChannelId(), ssrcTransaction.getStream());
  126. streamSession.remove(deviceId, ssrcTransaction.getChannelId(), ssrcTransaction.getStream());
  127. }
  128. }
  129. // 移除订阅
  130. removeCatalogSubscribe(device);
  131. removeMobilePositionSubscribe(device);
  132. }
  133. @Override
  134. public boolean addCatalogSubscribe(Device device) {
  135. if (device == null || device.getSubscribeCycleForCatalog() < 0) {
  136. return false;
  137. }
  138. logger.info("[添加目录订阅] 设备{}", device.getDeviceId());
  139. // 添加目录订阅
  140. CatalogSubscribeTask catalogSubscribeTask = new CatalogSubscribeTask(device, sipCommander, dynamicTask);
  141. // 刷新订阅
  142. int subscribeCycleForCatalog = Math.max(device.getSubscribeCycleForCatalog(),30);
  143. // 设置最小值为30
  144. dynamicTask.startCron(device.getDeviceId() + "catalog", catalogSubscribeTask, (subscribeCycleForCatalog -1) * 1000);
  145. return true;
  146. }
  147. @Override
  148. public boolean removeCatalogSubscribe(Device device) {
  149. if (device == null || device.getSubscribeCycleForCatalog() < 0) {
  150. return false;
  151. }
  152. logger.info("[移除目录订阅]: {}", device.getDeviceId());
  153. String taskKey = device.getDeviceId() + "catalog";
  154. if (device.getOnline() == 1) {
  155. Runnable runnable = dynamicTask.get(taskKey);
  156. if (runnable instanceof ISubscribeTask) {
  157. ISubscribeTask subscribeTask = (ISubscribeTask) runnable;
  158. subscribeTask.stop();
  159. }
  160. }
  161. dynamicTask.stop(taskKey);
  162. return true;
  163. }
  164. @Override
  165. public boolean addMobilePositionSubscribe(Device device) {
  166. if (device == null || device.getSubscribeCycleForMobilePosition() < 0) {
  167. return false;
  168. }
  169. logger.info("[添加移动位置订阅] 设备{}", device.getDeviceId());
  170. // 添加目录订阅
  171. MobilePositionSubscribeTask mobilePositionSubscribeTask = new MobilePositionSubscribeTask(device, sipCommander, dynamicTask);
  172. // 设置最小值为30
  173. int subscribeCycleForCatalog = Math.max(device.getSubscribeCycleForMobilePosition(),30);
  174. // 刷新订阅
  175. dynamicTask.startCron(device.getDeviceId() + "mobile_position" , mobilePositionSubscribeTask, (subscribeCycleForCatalog) * 1000);
  176. return true;
  177. }
  178. @Override
  179. public boolean removeMobilePositionSubscribe(Device device) {
  180. if (device == null || device.getSubscribeCycleForCatalog() < 0) {
  181. return false;
  182. }
  183. logger.info("[移除移动位置订阅]: {}", device.getDeviceId());
  184. String taskKey = device.getDeviceId() + "mobile_position";
  185. if (device.getOnline() == 1) {
  186. Runnable runnable = dynamicTask.get(taskKey);
  187. if (runnable instanceof ISubscribeTask) {
  188. ISubscribeTask subscribeTask = (ISubscribeTask) runnable;
  189. subscribeTask.stop();
  190. }
  191. }
  192. dynamicTask.stop(taskKey);
  193. return true;
  194. }
  195. @Override
  196. public SyncStatus getChannelSyncStatus(String deviceId) {
  197. return catalogResponseMessageHandler.getChannelSyncProgress(deviceId);
  198. }
  199. @Override
  200. public Boolean isSyncRunning(String deviceId) {
  201. return catalogResponseMessageHandler.isSyncRunning(deviceId);
  202. }
  203. @Override
  204. public void sync(Device device) {
  205. if (catalogResponseMessageHandler.isSyncRunning(device.getDeviceId())) {
  206. logger.info("开启同步时发现同步已经存在");
  207. return;
  208. }
  209. int sn = (int)((Math.random()*9+1)*100000);
  210. catalogResponseMessageHandler.setChannelSyncReady(device, sn);
  211. sipCommander.catalogQuery(device, sn, event -> {
  212. String errorMsg = String.format("同步通道失败,错误码: %s, %s", event.statusCode, event.msg);
  213. catalogResponseMessageHandler.setChannelSyncEnd(device.getDeviceId(), errorMsg);
  214. });
  215. }
  216. @Override
  217. public Device queryDevice(String deviceId) {
  218. return deviceMapper.getDeviceByDeviceId(deviceId);
  219. }
  220. @Override
  221. public List<Device> getAllOnlineDevice() {
  222. return deviceMapper.getOnlineDevices();
  223. }
  224. @Override
  225. public boolean expire(Device device) {
  226. Instant registerTimeDate = Instant.from(DateUtil.formatter.parse(device.getRegisterTime()));
  227. Instant expireInstant = registerTimeDate.plusMillis(TimeUnit.SECONDS.toMillis(device.getExpires()));
  228. return expireInstant.isBefore(Instant.now());
  229. }
  230. @Override
  231. public void checkDeviceStatus(Device device) {
  232. if (device == null || device.getOnline() == 0) {
  233. return;
  234. }
  235. sipCommander.deviceStatusQuery(device, null);
  236. }
  237. @Override
  238. public Device getDeviceByHostAndPort(String host, int port) {
  239. return deviceMapper.getDeviceByHostAndPort(host, port);
  240. }
  241. @Override
  242. public void updateDevice(Device device) {
  243. Device deviceInStore = deviceMapper.getDeviceByDeviceId(device.getDeviceId());
  244. if (deviceInStore == null) {
  245. logger.warn("更新设备时未找到设备信息");
  246. return;
  247. }
  248. if (!StringUtils.isEmpty(device.getName())) {
  249. deviceInStore.setName(device.getName());
  250. }
  251. if (!StringUtils.isEmpty(device.getCharset())) {
  252. deviceInStore.setCharset(device.getCharset());
  253. }
  254. if (!StringUtils.isEmpty(device.getMediaServerId())) {
  255. deviceInStore.setMediaServerId(device.getMediaServerId());
  256. }
  257. // 目录订阅相关的信息
  258. if (device.getSubscribeCycleForCatalog() > 0) {
  259. if (deviceInStore.getSubscribeCycleForCatalog() == 0 || deviceInStore.getSubscribeCycleForCatalog() != device.getSubscribeCycleForCatalog()) {
  260. deviceInStore.setSubscribeCycleForCatalog(device.getSubscribeCycleForCatalog());
  261. // 开启订阅
  262. addCatalogSubscribe(deviceInStore);
  263. }
  264. }else if (device.getSubscribeCycleForCatalog() == 0) {
  265. if (deviceInStore.getSubscribeCycleForCatalog() != 0) {
  266. deviceInStore.setSubscribeCycleForCatalog(device.getSubscribeCycleForCatalog());
  267. // 取消订阅
  268. removeCatalogSubscribe(deviceInStore);
  269. }
  270. }
  271. // 移动位置订阅相关的信息
  272. if (device.getSubscribeCycleForMobilePosition() > 0) {
  273. if (deviceInStore.getSubscribeCycleForMobilePosition() == 0 || deviceInStore.getSubscribeCycleForMobilePosition() != device.getSubscribeCycleForMobilePosition()) {
  274. deviceInStore.setMobilePositionSubmissionInterval(device.getMobilePositionSubmissionInterval());
  275. deviceInStore.setSubscribeCycleForMobilePosition(device.getSubscribeCycleForMobilePosition());
  276. // 开启订阅
  277. addMobilePositionSubscribe(deviceInStore);
  278. }
  279. }else if (device.getSubscribeCycleForMobilePosition() == 0) {
  280. if (deviceInStore.getSubscribeCycleForMobilePosition() != 0) {
  281. // 取消订阅
  282. removeMobilePositionSubscribe(deviceInStore);
  283. }
  284. }
  285. // 坐标系变化,需要重新计算GCJ02坐标和WGS84坐标
  286. if (!deviceInStore.getGeoCoordSys().equals(device.getGeoCoordSys())) {
  287. updateDeviceChannelGeoCoordSys(device);
  288. }
  289. String now = DateUtil.getNow();
  290. device.setUpdateTime(now);
  291. device.setCharset(device.getCharset().toUpperCase());
  292. device.setUpdateTime(DateUtil.getNow());
  293. if (deviceMapper.update(device) > 0) {
  294. redisCatchStorage.updateDevice(device);
  295. }
  296. }
  297. /**
  298. * 更新通道坐标系
  299. */
  300. private void updateDeviceChannelGeoCoordSys(Device device) {
  301. List<DeviceChannel> deviceChannels = deviceChannelMapper.getAllChannelWithCoordinate(device.getDeviceId());
  302. if (deviceChannels.size() > 0) {
  303. List<DeviceChannel> deviceChannelsForStore = new ArrayList<>();
  304. for (DeviceChannel deviceChannel : deviceChannels) {
  305. deviceChannelsForStore.add(deviceChannelService.updateGps(deviceChannel, device));
  306. }
  307. deviceChannelService.updateChannels(device.getDeviceId(), deviceChannelsForStore);
  308. }
  309. }
  310. @Override
  311. public List<BaseTree<DeviceChannel>> queryVideoDeviceTree(String deviceId, String parentId, boolean onlyCatalog) {
  312. Device device = deviceMapper.getDeviceByDeviceId(deviceId);
  313. if (device == null) {
  314. return null;
  315. }
  316. if (parentId == null || parentId.equals(deviceId)) {
  317. // 字根节点开始查询
  318. List<DeviceChannel> rootNodes = getRootNodes(deviceId, TreeType.CIVIL_CODE.equals(device.getTreeType()), true, !onlyCatalog);
  319. return transportChannelsToTree(rootNodes, "");
  320. }
  321. if (TreeType.CIVIL_CODE.equals(device.getTreeType())) {
  322. if (parentId.length()%2 != 0) {
  323. return null;
  324. }
  325. // 使用行政区划展示树
  326. if (parentId.length() > 10) {
  327. // TODO 可能是行政区划与业务分组混杂的情形
  328. return null;
  329. }
  330. if (parentId.length() == 10 ) {
  331. if (onlyCatalog) {
  332. return null;
  333. }
  334. // parentId为行业编码, 其下不会再有行政区划
  335. List<DeviceChannel> channels = deviceChannelMapper.getChannelsByCivilCode(deviceId, parentId);
  336. List<BaseTree<DeviceChannel>> trees = transportChannelsToTree(channels, parentId);
  337. return trees;
  338. }
  339. // 查询其下的行政区划和摄像机
  340. List<DeviceChannel> channelsForCivilCode = deviceChannelMapper.getChannelsWithCivilCodeAndLength(deviceId, parentId, parentId.length() + 2);
  341. if (!onlyCatalog) {
  342. List<DeviceChannel> channels = deviceChannelMapper.getChannelsByCivilCode(deviceId, parentId);
  343. channelsForCivilCode.addAll(channels);
  344. }
  345. List<BaseTree<DeviceChannel>> trees = transportChannelsToTree(channelsForCivilCode, parentId);
  346. return trees;
  347. }
  348. // 使用业务分组展示树
  349. if (TreeType.BUSINESS_GROUP.equals(device.getTreeType())) {
  350. if (parentId.length() < 14 ) {
  351. return null;
  352. }
  353. List<DeviceChannel> deviceChannels = deviceChannelMapper.queryChannels(deviceId, parentId, null, null, null);
  354. List<BaseTree<DeviceChannel>> trees = transportChannelsToTree(deviceChannels, parentId);
  355. return trees;
  356. }
  357. return null;
  358. }
  359. @Override
  360. public List<DeviceChannel> queryVideoDeviceInTreeNode(String deviceId, String parentId) {
  361. Device device = deviceMapper.getDeviceByDeviceId(deviceId);
  362. if (device == null) {
  363. return null;
  364. }
  365. if (parentId == null || parentId.equals(deviceId)) {
  366. // 字根节点开始查询
  367. List<DeviceChannel> rootNodes = getRootNodes(deviceId, TreeType.CIVIL_CODE.equals(device.getTreeType()), false, true);
  368. return rootNodes;
  369. }
  370. if (TreeType.CIVIL_CODE.equals(device.getTreeType())) {
  371. if (parentId.length()%2 != 0) {
  372. return null;
  373. }
  374. // 使用行政区划展示树
  375. if (parentId.length() > 10) {
  376. // TODO 可能是行政区划与业务分组混杂的情形
  377. return null;
  378. }
  379. if (parentId.length() == 10 ) {
  380. // parentId为行业编码, 其下不会再有行政区划
  381. List<DeviceChannel> channels = deviceChannelMapper.getChannelsByCivilCode(deviceId, parentId);
  382. return channels;
  383. }
  384. // 查询其下的行政区划和摄像机
  385. List<DeviceChannel> channels = deviceChannelMapper.getChannelsByCivilCode(deviceId, parentId);
  386. return channels;
  387. }
  388. // 使用业务分组展示树
  389. if (TreeType.BUSINESS_GROUP.equals(device.getTreeType())) {
  390. if (parentId.length() < 14 ) {
  391. return null;
  392. }
  393. List<DeviceChannel> deviceChannels = deviceChannelMapper.queryChannels(deviceId, parentId, null, null, null);
  394. return deviceChannels;
  395. }
  396. return null;
  397. }
  398. private List<BaseTree<DeviceChannel>> transportChannelsToTree(List<DeviceChannel> channels, String parentId) {
  399. if (channels == null) {
  400. return null;
  401. }
  402. List<BaseTree<DeviceChannel>> treeNotes = new ArrayList<>();
  403. if (channels.size() == 0) {
  404. return treeNotes;
  405. }
  406. for (DeviceChannel channel : channels) {
  407. BaseTree<DeviceChannel> node = new BaseTree<>();
  408. node.setId(channel.getChannelId());
  409. node.setDeviceId(channel.getDeviceId());
  410. node.setName(channel.getName());
  411. node.setPid(parentId);
  412. node.setBasicData(channel);
  413. node.setParent(false);
  414. if (channel.getChannelId().length() > 8) {
  415. String gbCodeType = channel.getChannelId().substring(10, 13);
  416. node.setParent(gbCodeType.equals(ChannelIdType.BUSINESS_GROUP) || gbCodeType.equals(ChannelIdType.VIRTUAL_ORGANIZATION) );
  417. }else {
  418. node.setParent(true);
  419. }
  420. treeNotes.add(node);
  421. }
  422. Collections.sort(treeNotes);
  423. return treeNotes;
  424. }
  425. private List<DeviceChannel> getRootNodes(String deviceId, boolean isCivilCode, boolean haveCatalog, boolean haveChannel) {
  426. if (!haveCatalog && !haveChannel) {
  427. return null;
  428. }
  429. List<DeviceChannel> result = new ArrayList<>();
  430. if (isCivilCode) {
  431. // 使用行政区划
  432. Integer length= deviceChannelMapper.getChannelMinLength(deviceId);
  433. if (length == null) {
  434. return null;
  435. }
  436. if (length <= 10) {
  437. if (haveCatalog) {
  438. List<DeviceChannel> provinceNode = deviceChannelMapper.getChannelsWithCivilCodeAndLength(deviceId, null, length);
  439. if (provinceNode != null && provinceNode.size() > 0) {
  440. result.addAll(provinceNode);
  441. }
  442. }
  443. if (haveChannel) {
  444. // 查询那些civilCode不在通道中的不规范通道,放置在根目录
  445. List<DeviceChannel> nonstandardNode = deviceChannelMapper.getChannelWithoutCiviCode(deviceId);
  446. if (nonstandardNode != null && nonstandardNode.size() > 0) {
  447. result.addAll(nonstandardNode);
  448. }
  449. }
  450. }else {
  451. if (haveChannel) {
  452. List<DeviceChannel> deviceChannels = deviceChannelMapper.queryChannels(deviceId, null, null, null, null);
  453. if (deviceChannels != null && deviceChannels.size() > 0) {
  454. result.addAll(deviceChannels);
  455. }
  456. }
  457. }
  458. }else {
  459. // 使用业务分组+虚拟组织
  460. // 只获取业务分组
  461. List<DeviceChannel> deviceChannels = deviceChannelMapper.getBusinessGroups(deviceId, ChannelIdType.BUSINESS_GROUP);
  462. if (deviceChannels != null && deviceChannels.size() > 0) {
  463. result.addAll(deviceChannels);
  464. }
  465. }
  466. return result;
  467. }
  468. }