liusuyi
6 天以前 307977cfb9fb88f845e36e4041c082ffdd691da5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package cn.org.hentai.jtt1078.server.audio;
 
import cn.org.hentai.jtt1078.entity.AudioSendData;
import cn.org.hentai.jtt1078.entity.enums.ProtocolVersion;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import lombok.extern.slf4j.Slf4j;
 
import javax.annotation.PreDestroy;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
 
@Slf4j
public class Jt1078AudioSenderService {
 
    // 设备通道缓存 (SIM -> Channel)
    public static Map<String, Channel> deviceChannels = new ConcurrentHashMap<>();
    
    // 音频发送线程池
    private static final ExecutorService audioSendExecutor = Executors.newFixedThreadPool(4);
 
    /**
     * 注册设备通道
     */
    public static void registerChannel(String sim, Channel channel) {
        if (!deviceChannels.containsKey(sim)) {
            deviceChannels.put(sim, channel);
            log.info("对讲通道注册: SIM={}", sim);
        }
    }
 
    /**
     * 移除设备通道
     */
    public static void removeChannel(String sim) {
        deviceChannels.remove(sim);
        log.info("对讲通道移除: SIM={}", sim);
    }
 
    /**
     * 发送音频到设备
     */
    public static void sendAudio(String sim, int channel, byte[] audioData,ProtocolVersion protocolVersion) {
        audioSendExecutor.execute(() -> {
            Channel deviceChannel = deviceChannels.get(sim);
            if (deviceChannel == null || !deviceChannel.isActive()) {
                log.warn("对讲通道未注册: SIM={}", sim);
                return;
            }
            AudioSendData sendData = new AudioSendData(sim, (byte)channel, audioData,protocolVersion);
            ChannelFuture future = deviceChannel.writeAndFlush(sendData);
 
            future.addListener(f -> {
                if (!f.isSuccess()) {
                    log.error("音频发送失败: SIM={}", sim, f.cause());
                }
            });
        });
    }
 
    @PreDestroy
    public void shutdown() {
        audioSendExecutor.shutdown();
        try {
            if (!audioSendExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
                audioSendExecutor.shutdownNow();
            }
        } catch (InterruptedException e) {
            audioSendExecutor.shutdownNow();
            Thread.currentThread().interrupt();
        }
    }
}