Class: Ewelink::Api

Inherits:
Object
  • Object
show all
Defined in:
lib/ewelink/api.rb

Constant Summary collapse

APP_ID =
'oeVkj2lYFGnJu5XUtWisfW4utiN4u9Mq'.freeze
APP_SECRET =
'6Nz4n0xA8s8qdxQf2GqurZj2Fs55FUvM'.freeze
DEFAULT_REGION =
'us'.freeze
REQUEST_TIMEOUT =
10.seconds
RF_BRIDGE_DEVICE_UIID =
28
SWITCH_DEVICES_UIIDS =
[1, 5, 6, 24].freeze
URL =
'https://#{region}-api.coolkit.cc:8080'.freeze
VERSION =
8
WEB_SOCKET_CHECK_AUTHENTICATION_TIMEOUT =
30.seconds
WEB_SOCKET_PING_TOLERANCE_FACTOR =
1.5
SWITCH_STATUS_CHANGE_CHECK_TIMEOUT =
2.seconds
WEB_SOCKET_WAIT_INTERVAL =
0.2.seconds

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(password:, async_actions: false, email: nil, phone_number: nil, update_devices_status_on_connect: false) ⇒ Api

Returns a new instance of Api.

Raises:



20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/ewelink/api.rb', line 20

def initialize(password:, async_actions: false, email: nil, phone_number: nil, update_devices_status_on_connect: false)
  @async_actions = async_actions.present?
  @email = email.presence.try(:strip)
  @mutexs = {}
  @password = password.presence || raise(Error.new(':password must be specified'))
  @phone_number = phone_number.presence.try(:strip)
  @update_devices_status_on_connect = update_devices_status_on_connect.present?
  @web_socket_authenticated = false
  @web_socket_switches_statuses = {}

  raise(Error.new(':email or :phone_number must be specified')) if email.blank? && phone_number.blank?

  start_web_socket_authentication_check_thread
end

Instance Attribute Details

#emailObject (readonly)

Returns the value of attribute email.



18
19
20
# File 'lib/ewelink/api.rb', line 18

def email
  @email
end

#passwordObject (readonly)

Returns the value of attribute password.



18
19
20
# File 'lib/ewelink/api.rb', line 18

def password
  @password
end

#phone_numberObject (readonly)

Returns the value of attribute phone_number.



18
19
20
# File 'lib/ewelink/api.rb', line 18

def phone_number
  @phone_number
end

Instance Method Details

#async_actions?Boolean

Returns:

  • (Boolean)


35
36
37
# File 'lib/ewelink/api.rb', line 35

def async_actions?
  @async_actions
end

#press_rf_bridge_button!(uuid) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/ewelink/api.rb', line 39

def press_rf_bridge_button!(uuid)
  process_action do
    synchronize(:press_rf_bridge_button) do
      button = find_rf_bridge_button!(uuid)
      web_socket_wait_for(-> { web_socket_authenticated? }, initialize_web_socket: true) do
        params = {
          'action' => 'update',
          'apikey' => button[:api_key],
          'deviceid' => button[:device_id],
          'params' => {
            'cmd' => 'transmit',
            'rfChl' => button[:channel],
          },
          'sequence' => web_socket_sequence,
          'ts' => 0,
          'userAgent' => 'app',
        }
        Ewelink.logger.debug(self.class.name) { "Pressing RF bridge button #{button[:uuid].inspect}" }
        send_to_web_socket(JSON.generate(params))
        true
      end
    end
  end
end

#reloadObject



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
# File 'lib/ewelink/api.rb', line 64

def reload
  Ewelink.logger.debug(self.class.name) { 'Reloading API (authentication token, api key, devices, region, connections,...)' }

  @web_socket_authenticated = false
  @web_socket_switches_statuses.clear

  [@web_socket_ping_thread, @web_socket_thread].each do |thread|
    next unless thread
    if Thread.current == thread
      thread[:stop] = true
    else
      thread.kill
    end
  end

  if @web_socket.present?
    begin
      @web_socket.close if @web_socket.open?
    rescue
      # Ignoring close errors
    end
  end

  %i(
    @authentication_infos
    @devices
    @last_web_socket_pong_at
    @region
    @rf_bridge_buttons
    @switches
    @web_socket_ping_interval
    @web_socket_ping_thread
    @web_socket_thread
    @web_socket_url
    @web_socket
  ).each do |variable|
    remove_instance_variable(variable) if instance_variable_defined?(variable)
  end
  self
end

#rf_bridge_buttonsObject



105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
# File 'lib/ewelink/api.rb', line 105

def rf_bridge_buttons
  synchronize(:rf_bridge_buttons) do
    @rf_bridge_buttons ||= [].tap do |buttons|
      rf_bridge_devices = devices.select { |device| device['uiid'] == RF_BRIDGE_DEVICE_UIID }.tap do |devices|
        Ewelink.logger.debug(self.class.name) { "Found #{devices.size} RF 433MHz bridge device(s)" }
      end
      rf_bridge_devices.each do |device|
        api_key = device['apikey'].presence || next
        device_id = device['deviceid'].presence || next
        device_name = device['name'].presence || next
        buttons = device['params']['rfList'].each do |rf|
          button = {
            api_key:,
            channel: rf['rfChl'],
            device_id:,
            device_name:,
          }
          remote_info = device['tags']['zyx_info'].find { |info| info['buttonName'].find { |data| data.key?(button[:channel].to_s) } }.presence || next
          remote_name = remote_info['name'].try(:squish).presence || next
          button_info = remote_info['buttonName'].find { |info| info.key?(button[:channel].to_s) }.presence || next
          button_name = button_info.values.first.try(:squish).presence || next
          button.merge!({
            name: button_name,
            remote_name:,
            remote_type: remote_info['remote_type'],
          })
          button[:uuid] = Digest::UUID.uuid_v5(Digest::UUID::DNS_NAMESPACE, "#{button[:device_id]}/#{button[:channel]}")
          buttons << button
        end
      end
    end.tap { |buttons| Ewelink.logger.debug(self.class.name) { "Found #{buttons.size} RF 433MHz bridge button(s)" } }
  end
end

#switch_on?(uuid) ⇒ Boolean

Returns:

  • (Boolean)


139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
# File 'lib/ewelink/api.rb', line 139

def switch_on?(uuid)
  switch = find_switch!(uuid)
  if @web_socket_switches_statuses[switch[:uuid]].nil?
    web_socket_wait_for(-> { web_socket_authenticated? }, initialize_web_socket: true) do
      Ewelink.logger.debug(self.class.name) { "Checking switch #{switch[:uuid].inspect} status" }
      params = {
        'action' => 'query',
        'apikey' => switch[:api_key],
        'deviceid' => switch[:device_id],
        'sequence' => web_socket_sequence,
        'ts' => 0,
        'userAgent' => 'app',
      }
      send_to_web_socket(JSON.generate(params))
    end
  end
  web_socket_wait_for(-> { !@web_socket_switches_statuses[switch[:uuid]].nil? }, initialize_web_socket: true) do
    @web_socket_switches_statuses[switch[:uuid]] == 'on'
  end
end

#switchesObject



160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
# File 'lib/ewelink/api.rb', line 160

def switches
  synchronize(:switches) do
    @switches ||= [].tap do |switches|
      switch_devices = devices.select { |device| SWITCH_DEVICES_UIIDS.include?(device['uiid']) }
      switch_devices.each do |device|
        api_key = device['apikey'].presence || next
        device_id = device['deviceid'].presence || next
        name = device['name'].presence || next
        switch = {
          api_key:,
          device_id:,
          name:,
        }
        switch[:uuid] = Digest::UUID.uuid_v5(Digest::UUID::DNS_NAMESPACE, switch[:device_id])
        switches << switch
      end
    end.tap { |switches| Ewelink.logger.debug(self.class.name) { "Found #{switches.size} switch(es)" } }
  end
end

#turn_switch!(uuid, on) ⇒ Object



180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
# File 'lib/ewelink/api.rb', line 180

def turn_switch!(uuid, on)
  process_action do
    if ['on', :on, 'true'].include?(on)
      on = true
    elsif ['off', :off, 'false'].include?(on)
      on = false
    end
    switch = find_switch!(uuid)
    @web_socket_switches_statuses[switch[:uuid]] = nil
    web_socket_wait_for(-> { web_socket_authenticated? }, initialize_web_socket: true) do
      params = {
        'action' => 'update',
        'apikey' => switch[:api_key],
        'deviceid' => switch[:device_id],
        'params' => {
          'switch' => on ? 'on' : 'off',
        },
        'sequence' => web_socket_sequence,
        'ts' => 0,
        'userAgent' => 'app',
      }
      Ewelink.logger.debug(self.class.name) { "Turning switch #{switch[:uuid].inspect} #{on ? 'on' : 'off'}" }
      send_to_web_socket(JSON.generate(params))
    end
    sleep(SWITCH_STATUS_CHANGE_CHECK_TIMEOUT)
    switch_on?(switch[:uuid]) # Waiting for switch status update
    true
  end
end

#update_devices_status_on_connect?Boolean

Returns:

  • (Boolean)


210
211
212
# File 'lib/ewelink/api.rb', line 210

def update_devices_status_on_connect?
  @update_devices_status_on_connect
end