Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: Packages refactor (minor cleanup to reduce duplication) #35

Merged
merged 1 commit into from
Dec 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 5 additions & 7 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,11 @@ func main() {
// Load configuration
cfg, err := config.LoadFile("config.toml")
if err != nil {
log.Fatal("[FATAL]: failed to load TOML configuration: " + err.Error())
log.Fatal(logger.Magenta+"[FATAL]" + logger.Reset + " [APP] failed to load TOML configuration: " + err.Error())
}

// Initialize logger
if _, err := logger.Initialize(cfg.App.LogLevel); err != nil {
log.Printf("[WARN]: logger initialization warning: %v", err)
}
logger.Initialize(cfg.App.LogLevel)

// Create contexts for managing goroutines and cancellations
rootCtx, rootCancel := context.WithCancel(context.Background())
Expand All @@ -54,7 +52,7 @@ func main() {
}

// Shutdown the application... buh bye!
logger.Info(logger.APP, "application shutdown complete... goodbye!")
log.Println("BLE Sync Cycle 0.6.2 shutdown complete. Goodbye!")
}

// setupAppControllers creates and initializes the application controllers
Expand Down Expand Up @@ -102,7 +100,7 @@ func startAppControllers(ctx context.Context, controllers appControllers) (logge
// Start component controllers concurrently
errs := make(chan componentErr, 1)

// Monitor BLE speed
// Monitor BLE speed (goroutine)
go func() {
if err := monitorBLESpeed(ctx, controllers, bleSpeedCharacter); err != nil {
errs <- componentErr{logger.BLE, err}
Expand All @@ -111,7 +109,7 @@ func startAppControllers(ctx context.Context, controllers appControllers) (logge
errs <- componentErr{logger.BLE, nil}
}()

// Play video
// Play video (goroutine)
go func() {
if err := playVideo(ctx, controllers); err != nil {
errs <- componentErr{logger.VIDEO, err}
Expand Down
45 changes: 24 additions & 21 deletions internal/ble/sensor_controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,23 @@ func controllersIntegrationTest() (*ble.BLEController, error) {
return controller, nil
}

// createTestContextWithTimeout creates a context with a predefined timeout
func createTestContextWithTimeout(t *testing.T) (context.Context, context.CancelFunc) {
ctx, cancel := context.WithTimeout(context.Background(), testTimeout)
t.Cleanup(cancel)
return ctx, cancel
}

// setupTestBLEController creates a test BLE controller and handles BLE adapter errors
func setupTestBLEController(t *testing.T) *ble.BLEController {
controller, err := controllersIntegrationTest()
if err != nil {
t.Skip(noBLEAdapterError)
return nil
}
return controller
}

// TestProcessBLESpeed tests the ProcessBLESpeed() function
func TestProcessBLESpeed(t *testing.T) {

Expand Down Expand Up @@ -167,11 +184,7 @@ func TestProcessBLESpeed(t *testing.T) {
func TestNewBLEControllerIntegration(t *testing.T) {

// Create test BLE controller
controller, err := controllersIntegrationTest()
if err != nil {
t.Skip(noBLEAdapterError)
return
}
controller := setupTestBLEController(t)

assert.NotNil(t, controller)
}
Expand All @@ -180,32 +193,22 @@ func TestNewBLEControllerIntegration(t *testing.T) {
func TestScanForBLEPeripheralIntegration(t *testing.T) {

// Create test BLE controller
controller, err := controllersIntegrationTest()
if err != nil {
t.Skip(noBLEAdapterError)
return
}
ctx, cancel := context.WithTimeout(context.Background(), testTimeout)
defer cancel()
controller := setupTestBLEController(t)
ctx, _ := createTestContextWithTimeout(t)

// Expect error since test UUID won't be found
_, err = controller.ScanForBLEPeripheral(ctx)
_, err := controller.ScanForBLEPeripheral(ctx)
assert.Error(t, err)
}

// TestGetBLECharacteristicIntegration tests the GetBLECharacteristic() function
func TestGetBLECharacteristicIntegration(t *testing.T) {

// Create test BLE controller
controller, err := controllersIntegrationTest()
if err != nil {
t.Skip(noBLEAdapterError)
return
}
ctx, cancel := context.WithTimeout(context.Background(), testTimeout)
defer cancel()
controller := setupTestBLEController(t)
ctx, _ := createTestContextWithTimeout(t)

// Expect error since test UUID won't be found
_, err = controller.GetBLECharacteristic(ctx, nil)
_, err := controller.GetBLECharacteristic(ctx, nil)
assert.Error(t, err)
}
2 changes: 1 addition & 1 deletion internal/configuration/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ func (ac *AppConfig) validate() error {

// Validate log level
switch ac.LogLevel {
case logLevelDebug, logLevelInfo, logLevelWarn, logLevelError, logLevelFatal:
case logLevelDebug, logLevelInfo, logLevelWarn, logLevelError:
return nil
default:
return errors.New("invalid log level: " + ac.LogLevel)
Expand Down
27 changes: 10 additions & 17 deletions internal/logging/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,17 +48,10 @@ const (
const LevelFatal slog.Level = slog.Level(12)

// Initialize sets up the logger
func Initialize(logLevel string) (*slog.Logger, error) {

level, err := parseLogLevel(logLevel)
if err != nil {
// Still create the logger but with the default level
logger = slog.New(NewCustomTextHandler(os.Stdout, &slog.HandlerOptions{Level: level}))
return logger, err
}

func Initialize(logLevel string) (*slog.Logger) {
level := parseLogLevel(logLevel)
logger = slog.New(NewCustomTextHandler(os.Stdout, &slog.HandlerOptions{Level: level}))
return logger, nil
return logger
}

// Info logs an info message
Expand Down Expand Up @@ -119,7 +112,7 @@ func (h *CustomTextHandler) Handle(ctx context.Context, r slog.Record) error {
timestamp := r.Time.Format("2006/01/02 15:04:05")
level := strings.TrimSpace("["+(r.Level.String())+"]")
if r.Level == LevelFatal {
level = "FATAL"
level = "[FATAL]"
}
msg := r.Message

Expand Down Expand Up @@ -197,20 +190,20 @@ func (h *CustomTextHandler) getComponentFromAttrs(r slog.Record) string {
}

// parseLogLevel converts a string log level to slog.Level
func parseLogLevel(level string) (slog.Level, error) {
func parseLogLevel(level string) (slog.Level) {

// Convert log level to slog.Level
switch strings.ToLower(level) {
case "debug":
return slog.LevelDebug, nil
return slog.LevelDebug
case "info":
return slog.LevelInfo, nil
return slog.LevelInfo
case "warn":
return slog.LevelWarn, nil
return slog.LevelWarn
case "error":
return slog.LevelError, nil
return slog.LevelError
default:
return slog.LevelInfo, fmt.Errorf("invalid log level: %s, defaulting to info", level)
return slog.LevelInfo // default to Info level
}
}

Expand Down
11 changes: 8 additions & 3 deletions internal/video-player/playback_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,11 @@ var (
ErrSpeedUpdate = errors.New("failed to update video speed")
)

// wrapError wraps an error with a specific error type for more context
func wrapError(baseErr error, contextErr error) error {
return fmt.Errorf("%w: %v", baseErr, contextErr)
}

// PlaybackController manages video playback using MPV media player
type PlaybackController struct {
config config.VideoConfig
Expand Down Expand Up @@ -148,7 +153,7 @@ func (p *PlaybackController) pausePlayback() error {
logger.Debug(logger.VIDEO, "no speed detected, so pausing video")

if err := p.updateMPVDisplay(0.0, 0.0); err != nil {
return fmt.Errorf("%w: %v", ErrOSDUpdate, err)
return wrapError(ErrOSDUpdate, err)
}

return p.setMPVPauseState(true)
Expand All @@ -161,13 +166,13 @@ func (p *PlaybackController) adjustPlayback(currentSpeed float64, lastSpeed *flo
logger.Info(logger.VIDEO, logger.Cyan+"updating video playback speed to "+strconv.FormatFloat(playbackSpeed, 'f', 2, 64))

if err := p.updateMPVPlaybackSpeed(playbackSpeed); err != nil {
return fmt.Errorf("%w: %v", ErrPlaybackSpeed, err)
return wrapError(ErrPlaybackSpeed, err)
}

*lastSpeed = currentSpeed

if err := p.updateMPVDisplay(currentSpeed, playbackSpeed); err != nil {
return fmt.Errorf("%w: %v", ErrOSDUpdate, err)
return wrapError(ErrOSDUpdate, err)
}

return p.setMPVPauseState(false)
Expand Down
Loading