You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
58 lines
1.5 KiB
Go
58 lines
1.5 KiB
Go
package I2C
|
|
|
|
import (
|
|
"time"
|
|
"fmt"
|
|
)
|
|
|
|
func NewMonitor(b int) *I2CMonitor{
|
|
m := new(I2CMonitor)
|
|
m.Devices = make(map[int]I2Cdev)
|
|
m.Bus = b
|
|
m.Update() //ensure that devices get updated before it gets locked by connected
|
|
return m
|
|
}
|
|
|
|
func (m *I2CMonitor) Update() {
|
|
/*
|
|
gets newly connected sensors and updates any currently dead sensors
|
|
*/
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
// locking right away should be fine
|
|
fmt.Printf("Getting devices on bus %v\n",m.Bus)
|
|
connected := I2Cconnected(m.Bus)
|
|
// m.mu.Lock()
|
|
// defer m.mu.Unlock()
|
|
now := time.Now()
|
|
for k,v := range connected {
|
|
if _, ok := m.Devices[k]; ok { // if address existed
|
|
entry := m.Devices[k]
|
|
entry.Active = v // update the value
|
|
if v {
|
|
entry.LastSeen = now // if its active, update last seen time
|
|
}
|
|
m.Devices[k] = entry
|
|
} else if v { // else theres a chance its new
|
|
fmt.Printf("adding device %v\n",k)
|
|
m.Devices[k] = I2Cdev{Active:true, LastSeen:now} // add new sensors
|
|
}
|
|
}
|
|
}
|
|
|
|
func (m *I2CMonitor) Remove(addr int) {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
delete(m.Devices, addr)
|
|
}
|
|
|
|
func (m *I2CMonitor) Connected() []int {
|
|
// returns list of addresses of connected devices
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
connected := []int{}
|
|
for a,_ := range m.Devices {
|
|
connected = append(connected, a)
|
|
}
|
|
return connected
|