-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.rb
108 lines (89 loc) · 2.08 KB
/
client.rb
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
module WeatherStation
class ContosoAnemometer
attr_reader :windSpeed, :temperature, :humidity
def initialize
@fanSpeed = 28
end
def quit(peyload)
puts "execute quit " + peyload
"{\"Message\":\"quit with Method\"}"
end
def turnFanOn(peyload)
puts "execute turnFanOn " + peyload
"{\"Message\":\"Turning fan on with Method\"}"
end
def turnFanOff(peyload)
puts "execute turnFanOff " + peyload
"{\"Message\":\"Turning fan off with Method\"}"
end
def get_temperature_alert
(@temperature > 30) ? 'true' : 'false'
end
def set_fan_speed(fanSpeed)
@fanSpeed = fanSpeed
puts "set fan speed " + fanSpeed.to_s
end
def recv_twin(peyload)
json = JSON.parse(peyload)
desired = json["desired"]
if desired == nil
desired = json
end
desired.each{|key, obj|
case key
when "fanSpeed"
value = obj["value"]
if value != nil
set_fan_speed(value)
desired[key] = {value: @fanSpeed, status: "success"}
else
desired[key] = nil
end
else
desired[key] = nil
end
}
desired.to_json
end
def get_message
data = {
windSpeed: @windSpeed,
temperature: @temperature,
humidity: @humidity,
}.to_json
message = AzureIoT::Message.new(data)
message.add_property('temperatureAlert', get_temperature_alert())
return message
end
def measure
@windSpeed = 10 + (rand() * 4) + 2
@temperature = 20 + (rand() * 15)
@humidity = 60 + (rand() * 20)
end
end
end
twin = WeatherStation::ContosoAnemometer.new
connectionString = AzureIoT.get_connection_string
protocol = AzureIoT::MQTT
client = AzureIoT::DeviceClient.new(connectionString, protocol)
client.set_twin(twin)
while true do
twin.measure
message = twin.get_message
done = false
client.send_event(message) do
puts "sent message"
done = true
end
count = 5000
while !done do
client.do_work
sleep(0.001)
if count > 0 then
count -= 1
end
end
if count > 0 then
sleep(0.001 * count)
end
end