-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdoor.go
84 lines (65 loc) · 1.55 KB
/
door.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package door
import (
"bytes"
cryptoRand "crypto/rand"
"fmt"
rpio "github.com/stianeikeland/go-rpio/v4"
"log"
"sync"
"time"
)
type Door struct {
pin rpio.Pin
mutex sync.Mutex
delayedUnlockNonce []byte
}
func New() Door {
pin := rpio.Pin(21)
pin.Output()
pin.Low()
return Door{pin: pin}
}
const maxDuration = time.Second * 30
func (c *Door) UnlockForDuration(duration time.Duration, authorizedBy string) error {
if duration > maxDuration {
return fmt.Errorf("duration (%.0f) is longer than maximum allowed (%.0f)", duration.Seconds(), maxDuration.Seconds())
}
if duration <= 0 {
return fmt.Errorf("duration (%.0f) must be greater than 0", duration.Seconds())
}
c.unlock(authorizedBy)
delayedUnlockNonce := make([]byte, 32)
cryptoRand.Read(delayedUnlockNonce)
c.mutex.Lock()
defer c.mutex.Unlock()
c.delayedUnlockNonce = delayedUnlockNonce
go func() {
time.Sleep(duration)
c.mutex.Lock()
defer c.mutex.Unlock()
if bytes.Equal(c.delayedUnlockNonce, delayedUnlockNonce) {
c.lock(authorizedBy)
}
}()
return nil
}
func (c *Door) unlock(authorizedBy string) {
c.pin.High()
log.Printf("door unlocked (%s)\n", authorizedBy)
}
func (c *Door) Unlock(authorizedBy string) {
c.unlock(authorizedBy)
c.mutex.Lock()
defer c.mutex.Unlock()
c.delayedUnlockNonce = nil
}
func (c *Door) lock(authorizedBy string) {
c.pin.Low()
log.Printf("door locked (%s)\n", authorizedBy)
}
func (c *Door) Lock(authorizedBy string) {
c.lock(authorizedBy)
c.mutex.Lock()
defer c.mutex.Unlock()
c.delayedUnlockNonce = nil
}