Files
wails-epic/internal/service/capture_service.go
hu xiaotong 0246bc7060 init
2025-07-02 16:12:52 +08:00

104 lines
2.3 KiB
Go

package service
import (
"context"
"fmt"
"sync"
"time"
"equipment-analyzer/internal/capture"
"equipment-analyzer/internal/config"
"equipment-analyzer/internal/model"
"equipment-analyzer/internal/utils"
)
type CaptureService struct {
config *config.Config
logger *utils.Logger
packetCapture *capture.PacketCapture
processor *capture.TCPProcessor
mutex sync.RWMutex
isCapturing bool
dataChan chan *model.CaptureResult
errorChan chan error
}
func NewCaptureService(cfg *config.Config, logger *utils.Logger) *CaptureService {
return &CaptureService{
config: cfg,
logger: logger,
packetCapture: capture.NewPacketCapture(),
processor: capture.NewTCPProcessor(),
dataChan: make(chan *model.CaptureResult, 100),
errorChan: make(chan error, 100),
}
}
// StartCapture 开始抓包
func (cs *CaptureService) StartCapture(ctx context.Context, config capture.Config) error {
cs.mutex.Lock()
defer cs.mutex.Unlock()
if cs.isCapturing {
return fmt.Errorf("capture already running")
}
if err := cs.packetCapture.Start(config); err != nil {
return fmt.Errorf("failed to start capture: %w", err)
}
cs.isCapturing = true
cs.logger.Info("Packet capture started", "interface", config.InterfaceName)
// 启动数据处理协程
go cs.processData(ctx)
return nil
}
// StopCapture 停止抓包
func (cs *CaptureService) StopCapture() error {
cs.mutex.Lock()
defer cs.mutex.Unlock()
if !cs.isCapturing {
return fmt.Errorf("capture not running")
}
cs.packetCapture.Stop()
cs.isCapturing = false
cs.logger.Info("Packet capture stopped")
return nil
}
// GetCapturedData 获取抓包数据
func (cs *CaptureService) GetCapturedData() []string {
return cs.packetCapture.GetCapturedData()
}
// ProcessAllData 处理所有数据
func (cs *CaptureService) ProcessAllData() {
cs.packetCapture.ProcessAllData()
}
// IsCapturing 检查是否正在抓包
func (cs *CaptureService) IsCapturing() bool {
cs.mutex.RLock()
defer cs.mutex.RUnlock()
return cs.isCapturing
}
// processData 处理抓包数据
func (cs *CaptureService) processData(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
default:
// 这里可以添加实时数据处理逻辑
time.Sleep(100 * time.Millisecond)
}
}
}