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();
|
}
|
}
|
}
|