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