Skip to content
This repository was archived by the owner on Mar 22, 2025. It is now read-only.

Commit bde8bef

Browse files
committed
Fixed some merge comments
1 parent 7e1a5ee commit bde8bef

File tree

3 files changed

+32
-63
lines changed

3 files changed

+32
-63
lines changed

ZigBeeValve/thing.go

Lines changed: 10 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,9 @@ func initTemplate() components.UnitAsset {
9595

9696
//-------------------------------------Instatiate the unit assets based on configuration
9797

98-
// newResource creates the Resource resource with its pointers and channels based on the configuration using the tConig structs
98+
// newResource creates the resource with its pointers and channels based on the configuration using the tConfig structs
99+
// This is a startup function that's used to initiate the unit assets declared in the systemconfig.json, the function
100+
// that is returned is later used to send a setpoint/start a goroutine depending on model of the unitasset
99101
func newResource(uac UnitAsset, sys *components.System, servs []components.Service) (components.UnitAsset, func()) {
100102
// deterimine the protocols that the system supports
101103
sProtocols := components.SProtocols(sys.Husk.ProtoPort)
@@ -106,7 +108,6 @@ func newResource(uac UnitAsset, sys *components.System, servs []components.Servi
106108
Protos: sProtocols,
107109
Url: make([]string, 0),
108110
}
109-
110111
// intantiate the unit asset
111112
ua := &UnitAsset{
112113
Name: uac.Name,
@@ -121,25 +122,23 @@ func newResource(uac UnitAsset, sys *components.System, servs []components.Servi
121122
t.Name: t,
122123
},
123124
}
124-
125125
var ref components.Service
126126
for _, s := range servs {
127127
if s.Definition == "setpoint" {
128128
ref = s
129129
}
130130
}
131-
132131
ua.CervicesMap["temperature"].Details = components.MergeDetails(ua.Details, ref.Details)
133-
134132
return ua, func() {
135133
if ua.Model == "SmartThermostat" {
136134
err := ua.sendSetPoint()
137135
if err != nil {
138136
log.Println("Error occured:", err)
139-
// TODO: Turn off system if this startup() fails
137+
// TODO: Turn off system if this startup() fails?
140138
}
141139
} else if ua.Model == "SmartPlug" {
142-
// start the unit asset(s)
140+
// start the unit assets feedbackloop, this fetches the temperature from ds18b20 and and toggles
141+
// between on/off depending on temperature in the room and a set temperature in the unitasset
143142
go ua.feedbackLoop(ua.Owner.Ctx)
144143
}
145144
}
@@ -149,7 +148,6 @@ func (ua *UnitAsset) feedbackLoop(ctx context.Context) {
149148
// Initialize a ticker for periodic execution
150149
ticker := time.NewTicker(ua.Period * time.Second)
151150
defer ticker.Stop()
152-
153151
// start the control loop
154152
for {
155153
select {
@@ -168,24 +166,22 @@ func (ua *UnitAsset) processFeedbackLoop() {
168166
log.Printf("\n unable to obtain a temperature reading error: %s\n", err)
169167
return
170168
}
171-
172169
// Perform a type assertion to convert the returned Form to SignalA_v1a
173170
tup, ok := tf.(*forms.SignalA_v1a)
174171
if !ok {
175172
log.Println("problem unpacking the temperature signal form")
176173
return
177174
}
178-
179175
// TODO: Check diff instead of a hard over/under value? meaning it'll only turn on/off if diff is over 0.5 degrees
180176
if tup.Value < ua.Setpt {
181177
err = ua.toggleState(true)
182178
if err != nil {
183-
log.Println("Error occured: ", err)
179+
log.Println("Error occured while toggling state to true: ", err)
184180
}
185181
} else {
186182
err = ua.toggleState(false)
187183
if err != nil {
188-
log.Println("Error occured: ", err)
184+
log.Println("Error occured while toggling state to false: ", err)
189185
}
190186
}
191187
}
@@ -246,17 +242,11 @@ func (ua *UnitAsset) getSetPoint() (f forms.SignalA_v1a) {
246242
// setSetPoint updates the thermal setpoint
247243
func (ua *UnitAsset) setSetPoint(f forms.SignalA_v1a) {
248244
ua.Setpt = f.Value
249-
/*
250-
log.Println("*---------------------*")
251-
log.Printf("New set point: %.1f\n", f.Value)
252-
log.Println("*---------------------*")
253-
*/
254245
}
255246

256247
func (ua *UnitAsset) sendSetPoint() (err error) {
257248
// API call to set desired temp in smart thermostat, PUT call should be sent to URL/api/apikey/sensors/sensor_id/config
258249
apiURL := "http://" + gateway + "/api/" + ua.Apikey + "/sensors/" + ua.Name + "/config"
259-
260250
// Create http friendly payload
261251
s := fmt.Sprintf(`{"heatsetpoint":%f}`, ua.Setpt*100) // Create payload
262252
req, err := createRequest(s, apiURL)
@@ -269,7 +259,6 @@ func (ua *UnitAsset) sendSetPoint() (err error) {
269259
func (ua *UnitAsset) toggleState(state bool) (err error) {
270260
// API call turn smart plug on/off, PUT call should be sent to URL/api/apikey/lights/sensor_id/config
271261
apiURL := "http://" + gateway + "/api/" + ua.Apikey + "/lights/" + ua.Name + "/state"
272-
273262
// Create http friendly payload
274263
s := fmt.Sprintf(`{"on":%t}`, state) // Create payload
275264
req, err := createRequest(s, apiURL)
@@ -285,19 +274,17 @@ func createRequest(data string, apiURL string) (req *http.Request, err error) {
285274
if err != nil {
286275
return nil, err
287276
}
288-
289277
req.Header.Set("Content-Type", "application/json") // Make sure it's JSON
290278
return req, err
291279
}
292280

293281
func sendRequest(req *http.Request) (err error) {
294-
resp, err := http.DefaultClient.Do(req)
282+
resp, err := http.DefaultClient.Do(req) // Perform the http request
295283
if err != nil {
296284
return err
297285
}
298-
299286
defer resp.Body.Close()
300-
_, err = io.ReadAll(resp.Body) // Read the payload into body variable
287+
_, err = io.ReadAll(resp.Body) // Read the response body, and check for errors/bad statuscodes
301288
if err != nil {
302289
return
303290
}

ZigBeeValve/thing_test.go

Lines changed: 14 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -72,60 +72,55 @@ func TestUnitAsset(t *testing.T) {
7272
f := forms.SignalA_v1a{
7373
Value: 27.0,
7474
}
75-
7675
// Creates a single UnitAsset and assert it changes
7776
ua := initTemplate().(*UnitAsset)
78-
7977
// Change Setpt
8078
ua.setSetPoint(f)
81-
8279
if ua.Setpt != 27.0 {
8380
t.Errorf("Expected Setpt to be 27.0, instead got %f", ua.Setpt)
8481
}
85-
8682
// Fetch Setpt w/ a form
8783
f2 := ua.getSetPoint()
88-
8984
if f2.Value != f.Value {
9085
t.Errorf("Expected %f, instead got %f", f.Value, f2.Value)
9186
}
9287
}
9388

9489
func TestGetters(t *testing.T) {
9590
ua := initTemplate().(*UnitAsset)
96-
91+
// Test GetName()
9792
name := ua.GetName()
9893
if name != "Template" {
9994
t.Errorf("Expected name to be 2, instead got %s", name)
10095
}
101-
96+
// Test GetServices()
10297
services := ua.GetServices()
10398
if services == nil {
10499
t.Fatalf("Expected services not to be nil")
105100
}
106101
if services["setpoint"].Definition != "setpoint" {
107102
t.Errorf("Expected definition to be setpoint")
108103
}
109-
104+
// Test GetDetails()
110105
details := ua.GetDetails()
111106
if details == nil {
112107
t.Fatalf("Details was nil, expected map")
113108
}
114109
if len(details["Location"]) == 0 {
115110
t.Fatalf("Location was nil, expected kitchen")
116111
}
117-
118112
if details["Location"][0] != "Kitchen" {
119113
t.Errorf("Expected location to be Kitchen")
120114
}
121-
115+
// Test GetCervices()
122116
cervices := ua.GetCervices()
123117
if cervices != nil {
124118
t.Errorf("Expected no cervices")
125119
}
126120
}
127121

128122
func TestNewResource(t *testing.T) {
123+
// Setup test context, system and unitasset
129124
ctx, cancel := context.WithCancel(context.Background())
130125
defer cancel()
131126
sys := components.NewSystem("testsys", ctx)
@@ -136,14 +131,12 @@ func TestNewResource(t *testing.T) {
136131
ProtoPort: map[string]int{"https": 0, "http": 8870, "coap": 0},
137132
InfoLink: "https://github.com/sdoque/systems/tree/master/ZigBeeValve",
138133
}
139-
140134
setPointService := components.Service{
141135
Definition: "setpoint",
142136
SubPath: "setpoint",
143137
Details: map[string][]string{"Unit": {"Celsius"}, "Forms": {"SignalA_v1a"}},
144138
Description: "provides the current thermal setpoint (GET) or sets it (PUT)",
145139
}
146-
147140
uac := UnitAsset{
148141
Name: "Template",
149142
Details: map[string][]string{"Location": {"Kitchen"}},
@@ -155,7 +148,7 @@ func TestNewResource(t *testing.T) {
155148
setPointService.SubPath: &setPointService,
156149
},
157150
}
158-
151+
// Test newResource function
159152
ua, _ := newResource(uac, &sys, nil)
160153
// Happy test case:
161154
name := ua.GetName()
@@ -176,13 +169,9 @@ func (errReader) Close() error {
176169
return nil
177170
}
178171

179-
func TestProcessFeedbackLoop(t *testing.T) {
180-
// TODO: Test as much of the code as possible?
181-
}
182-
183172
func TestFindGateway(t *testing.T) {
173+
// Create mock response for findGateway function
184174
fakeBody := fmt.Sprint(discoverExample)
185-
186175
resp := &http.Response{
187176
Status: "200 OK",
188177
StatusCode: 200,
@@ -192,21 +181,19 @@ func TestFindGateway(t *testing.T) {
192181

193182
// ---- All ok! ----
194183
err := findGateway()
195-
196184
if err != nil {
197-
t.Fatal("Gatewayn not found", err)
185+
t.Fatal("Gateway not found", err)
198186
}
199187
if gateway != "localhost:8080" {
200188
t.Fatalf("Expected gateway to be localhost:8080, was %s", gateway)
201189
}
202190

203191
// ---- Error cases ----
204-
205192
// Unmarshall error
206193
newMockTransport(resp, false, fmt.Errorf("Test error"))
207194
err = findGateway()
208195
if err == nil {
209-
t.Error("Error expcted, got nil instead", err)
196+
t.Error("Error expcted during unmarshalling, got nil instead", err)
210197
}
211198

212199
// Statuscode > 299, have to make changes to mockTransport to test this
@@ -223,35 +210,34 @@ func TestFindGateway(t *testing.T) {
223210
newMockTransport(resp, false, nil)
224211
err = findGateway()
225212
if err != errBodyRead {
226-
t.Error("Expected error")
213+
t.Error("Expected errBodyRead, got", err)
227214
}
228215

229216
// Actual http body is unmarshaled correctly
230217
resp.Body = io.NopCloser(strings.NewReader(fakeBody + "123"))
231218
newMockTransport(resp, false, nil)
232219
err = findGateway()
233220
if err == nil {
234-
t.Error("Expected error")
221+
t.Error("Expected error while unmarshalling body, error:", err)
235222
}
236223

237224
// Empty list of gateways
238225
resp.Body = io.NopCloser(strings.NewReader("[]"))
239226
newMockTransport(resp, false, nil)
240227
err = findGateway()
241228
if err != errMissingGateway {
242-
t.Error("Expected error", err)
229+
t.Error("Expected error when list of gateways is empty:", err)
243230
}
244231
}
245232

246233
func TestToggleState(t *testing.T) {
234+
// Create mock response and unitasset for toggleState() function
247235
fakeBody := fmt.Sprint(`{"on":true, "Version": "SignalA_v1a"}`)
248-
249236
resp := &http.Response{
250237
Status: "200 OK",
251238
StatusCode: 200,
252239
Body: io.NopCloser(strings.NewReader(fakeBody)),
253240
}
254-
255241
newMockTransport(resp, false, nil)
256242
ua := initTemplate().(*UnitAsset)
257243
// All ok!
@@ -264,14 +250,13 @@ func TestToggleState(t *testing.T) {
264250
}
265251

266252
func TestSendSetPoint(t *testing.T) {
253+
// Create mock response and unitasset for sendSetPoint() function
267254
fakeBody := fmt.Sprint(`{"Value": 12.4, "Version": "SignalA_v1a}`)
268-
269255
resp := &http.Response{
270256
Status: "200 OK",
271257
StatusCode: 200,
272258
Body: io.NopCloser(strings.NewReader(fakeBody)),
273259
}
274-
275260
newMockTransport(resp, false, nil)
276261
ua := initTemplate().(*UnitAsset)
277262
// All ok!

ZigBeeValve/zigbee_test.go

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,10 @@ func TestSetpt(t *testing.T) {
1717
r := httptest.NewRequest("GET", "http://localhost:8670/ZigBee/Template/setpoint", nil)
1818
good_code := 200
1919
ua.setpt(w, r)
20-
20+
// Read response to a string, and save it in stringBody
2121
resp := w.Result()
2222
body, _ := io.ReadAll(resp.Body)
2323
stringBody := string(body)
24-
// fmt.Println(stringBody)
2524

2625
value := strings.Contains(string(stringBody), `"value": 20`)
2726
unit := strings.Contains(string(stringBody), `"unit": "Celcius"`)
@@ -31,22 +30,20 @@ func TestSetpt(t *testing.T) {
3130
t.Errorf("Good GET: Expected good status code: %v, got %v", good_code, resp.StatusCode)
3231
}
3332
if value != true {
34-
t.Errorf("Good GET: The statment to be true!")
33+
t.Errorf("Good GET: The value statment should be true!")
3534
}
3635
if unit != true {
3736
t.Errorf("Good GET: Expected the unit statement to be true!")
3837
}
3938
if version != true {
4039
t.Errorf("Good GET: Expected the version statment to be true!")
4140
}
42-
// Bad test case: default part of code
41+
// Bad test case: Default part of code (faulty http method)
4342
w = httptest.NewRecorder()
4443
r = httptest.NewRequest("123", "http://localhost:8670/ZigBee/Template/setpoint", nil)
45-
4644
ua.setpt(w, r)
47-
45+
// Read response and check statuscode, expecting 404 (StatusNotFound)
4846
resp = w.Result()
49-
5047
if resp.StatusCode != http.StatusNotFound {
5148
t.Errorf("Expected the status to be bad but got: %v", resp.StatusCode)
5249
}
@@ -61,9 +58,9 @@ func TestSetpt(t *testing.T) {
6158
ua.setpt(w, r)
6259
resp = w.Result()
6360
good_code = 200
64-
// Check for errors
61+
// Check for errors, should not be 200
6562
if resp.StatusCode == good_code {
66-
t.Errorf("Bad PUT: Expected bad status code: %v, got %v", good_code, resp.StatusCode)
63+
t.Errorf("Bad PUT: Expected bad status code: got %v", resp.StatusCode)
6764
}
6865

6966
// Bad test case: PUT Failing @ HTTPProcessSetRequest
@@ -77,7 +74,7 @@ func TestSetpt(t *testing.T) {
7774
resp = w.Result()
7875
// Check for errors
7976
if resp.StatusCode == good_code {
80-
t.Errorf("Bad PUT: Expected an error")
77+
t.Errorf("Bad PUT: Expected an error during HTTPProcessSetRequest")
8178
}
8279

8380
// Good test case: PUT
@@ -86,7 +83,6 @@ func TestSetpt(t *testing.T) {
8683
fakebody = string(`{"value": 24, "version": "SignalA_v1.0"}`)
8784
sentBody = io.NopCloser(strings.NewReader(fakebody))
8885
r = httptest.NewRequest("PUT", "http://localhost:8870/ZigBee/Template/setpoint", sentBody)
89-
9086
// Mock the http response/traffic to zigbee
9187
zBeeResponse := `[{"success":{"/sensors/7/config/heatsetpoint":2400}}]`
9288
resp = &http.Response{
@@ -104,6 +100,7 @@ func TestSetpt(t *testing.T) {
104100
if resp.StatusCode != good_code {
105101
t.Errorf("Good PUT: Expected good status code: %v, got %v", good_code, resp.StatusCode)
106102
}
103+
// Convert body to a string and check that it's correct
107104
respBodyBytes, _ := io.ReadAll(resp.Body)
108105
respBody := string(respBodyBytes)
109106
if respBody != `[{"success":{"/sensors/7/config/heatsetpoint":2400}}]` {

0 commit comments

Comments
 (0)