huginn_switchbot_agent 0.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: c61dfcbbb7ade238483703ae33944853b86278d9bd5128569563b05c934f2af6
4
+ data.tar.gz: 7dadd802e2b7b9e48a954057b0491f649fbd9290afc223b143e087ff865f0637
5
+ SHA512:
6
+ metadata.gz: 9b61217b5227fd0bbb80e82794f0456e58c5652eb6d218bb95192b995e5c66c1417fd364907991772232118ec6533b0a50a226018108ce0c9a02528188c374d9
7
+ data.tar.gz: 789b021d80909522dce615bd320be352e12eb24c4ffe08ce3812030d6a15172826a56075bf112c6cde50c8e4a3b3258f263a0e6c5c2fd95dc077cf51c7fc2d74
data/LICENSE.txt ADDED
@@ -0,0 +1,7 @@
1
+ Copyright (c) 2022 Nicolas Germain
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,309 @@
1
+ module Agents
2
+ class SwitchbotAgent < Agent
3
+ include FormConfigurable
4
+ can_dry_run!
5
+ no_bulk_receive!
6
+ default_schedule 'every_1h'
7
+
8
+ description <<-MD
9
+ The Switchbot Agent interacts with Switchbot API and can create events / tasks if wanted / needed.
10
+
11
+ The `type` can be like checking the device's info.
12
+ MD
13
+
14
+ def default_options
15
+ {
16
+ 'type' => 'service_status',
17
+ 'token' => '',
18
+ 'secret' => '',
19
+ 'device' => '',
20
+ 'debug' => 'false',
21
+ 'expected_receive_period_in_days' => '2',
22
+ 'changes_only' => 'true'
23
+ }
24
+ end
25
+
26
+ form_configurable :debug, type: :boolean
27
+ form_configurable :token, type: :string
28
+ form_configurable :device, type: :string
29
+ form_configurable :secret, type: :string
30
+ form_configurable :expected_receive_period_in_days, type: :string
31
+ form_configurable :changes_only, type: :boolean
32
+ form_configurable :type, type: :array, values: ['get_devices_status', 'get_device_status', 'service_status', 'rate_limit_wometer']
33
+ def validate_options
34
+ errors.add(:base, "type has invalid value: should be 'get_device_status' 'get_devices_status' 'service_status' 'rate_limit_wometer'") if interpolated['type'].present? && !%w(get_device_status get_devices_status service_status rate_limit_wometer).include?(interpolated['type'])
35
+
36
+ unless options['token'].present? || !['get_devices_status', 'get_device_status'].include?(options['type'])
37
+ errors.add(:base, "token is a required field")
38
+ end
39
+
40
+ unless options['secret'].present? || !['get_devices_status', 'get_device_status'].include?(options['type'])
41
+ errors.add(:base, "secret is a required field")
42
+ end
43
+
44
+ if options.has_key?('changes_only') && boolify(options['changes_only']).nil?
45
+ errors.add(:base, "if provided, changes_only must be true or false")
46
+ end
47
+
48
+ if options.has_key?('debug') && boolify(options['debug']).nil?
49
+ errors.add(:base, "if provided, debug must be true or false")
50
+ end
51
+
52
+ unless options['expected_receive_period_in_days'].present? && options['expected_receive_period_in_days'].to_i > 0
53
+ errors.add(:base, "Please provide 'expected_receive_period_in_days' to indicate how many days can pass before this Agent is considered to be not working")
54
+ end
55
+ end
56
+
57
+ def working?
58
+ event_created_within?(options['expected_receive_period_in_days']) && !recent_error_logs?
59
+ end
60
+
61
+ def receive(incoming_events)
62
+ incoming_events.each do |event|
63
+ interpolate_with(event) do
64
+ log event
65
+ trigger_action(event)
66
+ end
67
+ end
68
+ end
69
+
70
+ def check
71
+ trigger_action
72
+ end
73
+
74
+ private
75
+
76
+ def log_curl_output(code,body)
77
+
78
+ log "request status : #{code}"
79
+
80
+ if interpolated['debug'] == 'true'
81
+ log "body"
82
+ log body
83
+ end
84
+
85
+ end
86
+
87
+ def rate_limit_wometer(event)
88
+ if !event.nil?
89
+ if event.payload.to_s != memory["#{event.payload['context']['deviceMac']}"]
90
+ if !memory["#{event.payload['context']['deviceMac']}"].nil?
91
+ if interpolated['debug'] == 'true'
92
+ log event.payload
93
+ end
94
+ last_status = memory["#{event.payload['context']['deviceMac']}"].gsub("=>", ": ")
95
+ last_status = JSON.parse(last_status)
96
+ if (event.payload['context']['timeOfSample'].to_i - last_status['context']['timeOfSample']) > 3600000
97
+ if interpolated['debug'] == 'true'
98
+ log "> 1H"
99
+ end
100
+ create_event payload: event.payload
101
+ memory["#{event.payload['context']['deviceMac']}"] = event.payload.to_s
102
+ else
103
+ if interpolated['debug'] == 'true'
104
+ log "< 1H"
105
+ end
106
+ end
107
+ else
108
+ if interpolated['debug'] == 'true'
109
+ log "last_status is empty"
110
+ end
111
+ create_event payload: event.payload
112
+ memory["#{event.payload['context']['deviceMac']}"] = event.payload.to_s
113
+ end
114
+ end
115
+ end
116
+ end
117
+
118
+ def service_status()
119
+
120
+ uri = URI.parse("https://status.switch-bot.com/api/v2/status.json")
121
+ response = Net::HTTP.get_response(uri)
122
+
123
+ log_curl_output(response.code,response.body)
124
+
125
+ payload = JSON.parse(response.body)
126
+ event = payload.dup
127
+ event = { :status => { :name => "#{payload['page']['name']}", :indicator => "#{payload['status']['indicator']}", :description => "#{payload['status']['description']}" } }
128
+
129
+ if interpolated['changes_only'] == 'true'
130
+ if payload != memory['last_status']
131
+ memory['last_status'] = payload
132
+ create_event payload: event
133
+ end
134
+ else
135
+ create_event payload: event
136
+ if payload != memory['last_status']
137
+ memory['last_status'] = payload
138
+ end
139
+ end
140
+ end
141
+
142
+ def generate_nonce
143
+ (Time.now.to_f * 1000).to_i
144
+ end
145
+
146
+ def get_sign(ts,nonce)
147
+ mixed_token = interpolated['token'].dup
148
+ mixed_token.concat("#{ts}")
149
+ mixed_token.concat("#{nonce}")
150
+ Base64.encode64(OpenSSL::HMAC.digest('sha256', interpolated['secret'], mixed_token)).gsub(/\n/, '')
151
+ end
152
+
153
+ def get_devices_status(ts)
154
+ nonce = generate_nonce
155
+ sign = get_sign(ts,nonce)
156
+ # url = 'https://api.switch-bot.com/v1.1/devices'
157
+ if interpolated['debug'] == 'true'
158
+ # log "url #{url}"
159
+ log "sign #{sign}"
160
+ log "ts #{ts}"
161
+ log "nonce #{nonce}"
162
+ log "token #{interpolated['token']}"
163
+ end
164
+ #quickanddirty test start
165
+ # command = %x{curl -s '#{url}' -H 'Authorization: #{interpolated['token']}' -H 'User-Agent: Switchbot (https://github.com/hihouhou/huginn_switchbot_agent)' -H 'sign: #{sign}' -H 'nonce: #{nonce}' -H 't: #{ts}' -H 'Content-type: application/json'}
166
+ # if interpolated['debug'] == 'true'
167
+ # log command
168
+ # end
169
+ # payload = JSON.parse(command)
170
+ #quickanddirty test stop
171
+ headers = {
172
+ 'Authorization' => interpolated['token'],
173
+ 't' => ts,
174
+ 'sign' => sign,
175
+ 'nonce' => nonce,
176
+ }
177
+
178
+ client = NetHttp2::Client.new("https://api.switch-bot.com")
179
+ response = client.call(:get, '/v1.1/devices', headers: headers)
180
+
181
+ # uri = URI.parse(url)
182
+ # request = Net::HTTP::Get.new(uri)
183
+ # request.content_type = "application/json"
184
+ # request["Authorization"] = interpolated['token']
185
+ # request["sign"] = sign
186
+ # request["t"] = ts.to_i
187
+ # request["User-Agent"] = " Switchbot (https://github.com/hihouhou/huginn_switchbot_agent)"
188
+ # request["nonce"] = nonce
189
+ #
190
+ # req_options = {
191
+ # use_ssl: uri.scheme == "https",
192
+ # }
193
+ #
194
+ # response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
195
+ # http.request(request)
196
+ # end
197
+ #
198
+ log_curl_output(response.status,response.body)
199
+ # log_curl_output(response.code,response.body)
200
+ payload = response.body
201
+
202
+ if payload['message'] == 'success'
203
+ if interpolated['changes_only'] == 'true'
204
+ if payload.to_s != memory['get_devices_status']
205
+ payload['body']['deviceList'].each do |device|
206
+ found = false
207
+ if !memory['get_devices_status'].nil?
208
+ last_status = memory['get_devices_status'].gsub("=>", ": ")
209
+ last_status = JSON.parse(last_status)
210
+ last_status['body']['deviceList'].each do |devicebis|
211
+ if device == devicebis
212
+ found = true
213
+ end
214
+ if interpolated['debug'] == 'true'
215
+ log "found is #{found}!"
216
+ end
217
+ end
218
+ end
219
+ if found == false
220
+ if interpolated['debug'] == 'true'
221
+ log "found is #{found}! so event created"
222
+ log device
223
+ end
224
+ create_event payload: device
225
+ end
226
+ end
227
+ memory['get_devices_status'] = payload.to_s
228
+ end
229
+ else
230
+ if payload.to_s != memory['get_devices_status']
231
+ memory['get_devices_status'] = payload.to_s
232
+ end
233
+ create_event payload: payload
234
+ end
235
+ end
236
+ end
237
+
238
+ def get_device_status(ts)
239
+ nonce = generate_nonce
240
+ sign = get_sign(ts,nonce)
241
+ url = 'https://api.switch-bot.com/v1.1/devices/' + interpolated['device'] + '/status'
242
+ if interpolated['debug'] == 'true'
243
+ log "url #{url}"
244
+ log "sign #{sign}"
245
+ log "ts #{ts}"
246
+ log "token #{interpolated['token']}"
247
+ end
248
+
249
+ # uri = URI.parse(url)
250
+ # request = Net::HTTP::Get.new(uri)
251
+ # request.content_type = "application/json"
252
+ # request["Authorization"] = interpolated['token']
253
+ # request["sign"] = sign
254
+ # request["t"] = ts.to_i
255
+ # request["nonce"] = nonce
256
+ #
257
+ # req_options = {
258
+ # use_ssl: uri.scheme == "https",
259
+ # }
260
+ #
261
+ # response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
262
+ # http.request(request)
263
+ # end
264
+ #
265
+ # log_curl_output(response.code,response.body)
266
+ #
267
+ # payload = JSON.parse(response.body)
268
+
269
+ #quickanddirty test start
270
+ command = %x{curl -s '#{url}' -H 'Authorization: #{interpolated['token']}' -H 'User-Agent: Switchbot (https://github.com/hihouhou/huginn_switchbot_agent)' -H 'sign: #{sign}' -H 'nonce: #{nonce}' -H 't: #{ts}' -H 'Content-type: application/json'}
271
+ if interpolated['debug'] == 'true'
272
+ log command
273
+ end
274
+ #quickanddirty test stop
275
+ payload = JSON.parse(command)
276
+ if payload['message'] == 'success'
277
+ if interpolated['changes_only'] == 'true'
278
+ if payload.to_s != memory['get_device_status']
279
+ memory['get_device_status'] = payload.to_s
280
+ create_event payload: payload
281
+ end
282
+ else
283
+ if payload.to_s != memory['get_device_status']
284
+ memory['get_device_status'] = payload.to_s
285
+ end
286
+ create_event payload: payload
287
+ end
288
+ end
289
+ end
290
+
291
+
292
+ def trigger_action(event=nil)
293
+
294
+ ts = Time.now.to_i * 1000
295
+ case interpolated['type']
296
+ when "get_device_status"
297
+ get_device_status(ts)
298
+ when "get_devices_status"
299
+ get_devices_status(ts)
300
+ when "service_status"
301
+ service_status()
302
+ when "rate_limit_wometer"
303
+ rate_limit_wometer(event)
304
+ else
305
+ log "Error: type has an invalid value (#{type})"
306
+ end
307
+ end
308
+ end
309
+ end
@@ -0,0 +1,4 @@
1
+ require 'huginn_agent'
2
+
3
+ #HuginnAgent.load 'huginn_switchbot_agent/concerns/my_agent_concern'
4
+ HuginnAgent.register 'huginn_switchbot_agent/switchbot_agent'
@@ -0,0 +1,13 @@
1
+ require 'rails_helper'
2
+ require 'huginn_agent/spec_helper'
3
+
4
+ describe Agents::SwitchbotAgent do
5
+ before(:each) do
6
+ @valid_options = Agents::SwitchbotAgent.new.default_options
7
+ @checker = Agents::SwitchbotAgent.new(:name => "SwitchbotAgent", :options => @valid_options)
8
+ @checker.user = users(:bob)
9
+ @checker.save!
10
+ end
11
+
12
+ pending "add specs here"
13
+ end
metadata ADDED
@@ -0,0 +1,90 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: huginn_switchbot_agent
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.10
5
+ platform: ruby
6
+ authors:
7
+ - Nicolas Germain
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2024-01-19 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: 2.1.0
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: 2.1.0
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: 12.3.3
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: 12.3.3
41
+ - !ruby/object:Gem::Dependency
42
+ name: huginn_agent
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '0'
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ description: Write a longer description or delete this line.
56
+ email:
57
+ - ngermain@hihouhou.com
58
+ executables: []
59
+ extensions: []
60
+ extra_rdoc_files: []
61
+ files:
62
+ - LICENSE.txt
63
+ - lib/huginn_switchbot_agent.rb
64
+ - lib/huginn_switchbot_agent/switchbot_agent.rb
65
+ - spec/switchbot_agent_spec.rb
66
+ homepage: https://github.com/hihouhou/huginn_switchbot_agent
67
+ licenses:
68
+ - MIT
69
+ metadata: {}
70
+ post_install_message:
71
+ rdoc_options: []
72
+ require_paths:
73
+ - lib
74
+ required_ruby_version: !ruby/object:Gem::Requirement
75
+ requirements:
76
+ - - ">="
77
+ - !ruby/object:Gem::Version
78
+ version: '0'
79
+ required_rubygems_version: !ruby/object:Gem::Requirement
80
+ requirements:
81
+ - - ">="
82
+ - !ruby/object:Gem::Version
83
+ version: '0'
84
+ requirements: []
85
+ rubygems_version: 3.3.3
86
+ signing_key:
87
+ specification_version: 4
88
+ summary: Write a short summary, because Rubygems requires one.
89
+ test_files:
90
+ - spec/switchbot_agent_spec.rb