Added sync. Cleaning.

This commit is contained in:
yotia 2024-08-06 20:58:15 +03:00
parent 7fbd64168c
commit 3d753e6916

View File

@ -3,11 +3,12 @@ package mpu
import ( import (
"fmt" "fmt"
"io" "io"
"sync"
"github.com/CGSG-2021-AE4/mpu-test/pkg/mpu6050" "github.com/CGSG-2021-AE4/mpu-test/pkg/mpu6050"
) )
type MpuData struct { type Data struct {
TempData float32 `json:"Temperature"` TempData float32 `json:"Temperature"`
AccelData [3]float32 `json:"Accelerometer"` AccelData [3]float32 `json:"Accelerometer"`
GyroData [3]float32 `json:"Gyroscope"` GyroData [3]float32 `json:"Gyroscope"`
@ -15,15 +16,17 @@ type MpuData struct {
type mpu struct { type mpu struct {
device mpu6050.Device device mpu6050.Device
mutex sync.Mutex
data MpuData data Data
} }
type Mpu interface { type Mpu interface {
Init() error Init() error
Update() error Update() error
Validate() bool
GetData() MpuData IsConnected() bool
GetData() Data
io.Closer io.Closer
} }
@ -34,6 +37,9 @@ func New() Mpu {
} }
func (m *mpu) Init() error { func (m *mpu) Init() error {
m.mutex.Lock()
defer m.mutex.Unlock()
d, err := mpu6050.Open() d, err := mpu6050.Open()
if err != nil { if err != nil {
return fmt.Errorf("open mpu connection: %w", err) return fmt.Errorf("open mpu connection: %w", err)
@ -43,6 +49,9 @@ func (m *mpu) Init() error {
} }
func (m *mpu) Update() (err error) { func (m *mpu) Update() (err error) {
m.mutex.Lock()
defer m.mutex.Unlock()
m.data.TempData, err = m.device.GetTemp() m.data.TempData, err = m.device.GetTemp()
if err != nil { if err != nil {
return fmt.Errorf("get temp data: %w", err) return fmt.Errorf("get temp data: %w", err)
@ -58,15 +67,21 @@ func (m *mpu) Update() (err error) {
return nil return nil
} }
func (m *mpu) Validate() bool { func (m *mpu) IsConnected() bool {
return m.device != nil return m.device != nil
} }
func (m *mpu) GetData() MpuData { func (m *mpu) GetData() Data {
m.mutex.Lock()
defer m.mutex.Unlock()
return m.data return m.data
} }
func (m *mpu) Close() error { func (m *mpu) Close() error {
m.mutex.Lock()
defer m.mutex.Unlock()
defer func() { defer func() {
m.device = nil m.device = nil
}() }()