/
OnOffLightService.cpp
78 lines (65 loc) · 1.72 KB
/
OnOffLightService.cpp
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
#include "OnOffLightService.h"
OnOffLightService::OnOffLightService(int pin) {
_type = 0x12;
_version = 0x00;
_pin = pin;
_subscription = new SubscriptionManager(_sender);
}
void OnOffLightService::processCall(uint16_t callType, XBeeAddress from, uint8_t* payload, uint8_t payload_length) {
switch (callType) {
case 0x0001: { //set on/off
bool on = payload[0] == 0x01;
#ifdef DEBUG_ASRVS
Serial.print("Turn light to ");
Serial.println(on);
#endif
setValue(on);
break;
}
default: break;
}
}
bool OnOffLightService::processRequest(uint16_t requestType, XBeeAddress from, uint8_t* payload, uint8_t payload_length) {
switch (requestType) {
case 0x0001: { //is on?
#ifdef DEBUG_ASRVS
Serial.println("Request for current status");
#endif
uint8_t value = currentValue() ? 0x01 : 0x00;
uint8_t data[] = { 0, 0, 0, 0, value };
fillResponseHeader(data, requestType);
_sender->send(from, data, 5);
return true;
}
default: return false;
}
}
bool OnOffLightService::addSubscription(XBeeAddress from, uint16_t subscriptionType) {
switch (subscriptionType) {
case 0x0001: // on/off changes
_subscription->add(from);
return true;
default: return false;
}
}
void OnOffLightService::removeSubscription(XBeeAddress from, uint16_t subscriptionType) {
switch (subscriptionType) {
case 0x0001: //on/off change
_subscription->remove(from);
break;
default: break;
}
}
void OnOffLightService::stateChanged() {
uint8_t data[5]; // 4 + 1
fillPublishHeader(data, 0x0001);
data[4] = currentValue() ? 0x1 : 0x0;
_subscription->publish(data, 5);
}
bool OnOffLightService::currentValue() {
return digitalRead(_pin) == HIGH;
}
void OnOffLightService::setValue(bool on) {
digitalWrite(_pin, on ? HIGH : LOW);
stateChanged();
}