Skip to content

Commit

Permalink
Add connection close option
Browse files Browse the repository at this point in the history
  • Loading branch information
bmhughes committed Jun 9, 2019
1 parent efb4d51 commit 26a8e0d
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 7 deletions.
16 changes: 10 additions & 6 deletions lib/tp_link_smartplug/device.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ class Device
attr_accessor :address
attr_accessor :port
attr_accessor :timeout
attr_accessor :poll_auto_close
attr_accessor :debug

def initialize(address:, port: 9999)
Expand All @@ -30,6 +31,7 @@ def initialize(address:, port: 9999)
@debug = false
@sockaddr = Addrinfo.getaddrinfo(address.to_s, port, Socket::PF_INET, :STREAM, 6).first.to_sockaddr
@socket = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM)
@poll_auto_close = true
end

# Open connection to plug
Expand Down Expand Up @@ -68,21 +70,21 @@ def disconnect
@socket.close unless @socket.closed?
end

# Return connection state
# Return connection state open
#
# @return [True, False]
def open?
!@socket.closed?
end

# Return connection state
# Return connection state closed
#
# @return [True, False]
def closed?
@socket.closed?
end

# Polls a plug with a command
# Polls plug with a command
#
# @param command [String] the command to send to the plug
# @return [Hash] the output from the plug command
Expand All @@ -102,11 +104,13 @@ def poll(command:)
rescue IO::WaitReadable
IO.select([@socket])
retry
ensure
disconnect unless closed?
end

raise 'Error occured during disconnect' unless closed?
if @poll_auto_close && !closed?
disconnect
raise 'Error occured during disconnect' unless closed?
end

raise 'No data received' if data.nil? || data.empty?

debug_message("Received Raw: #{data}") if debug
Expand Down
2 changes: 1 addition & 1 deletion tp_link_smartplug.gemspec
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

Gem::Specification.new do |spec|
spec.name = 'tp_link_smartplug'
spec.version = '0.1.0.alpha1'
spec.version = '0.1.0.alpha2'
spec.summary = 'TP-Link HS100/110 Smart Plug interaction library'
spec.description = 'Control and retrieve data from a TP-Link HS100/110 (Metered) Smartplug'
spec.authors = ['Ben Hughes']
Expand Down

0 comments on commit 26a8e0d

Please sign in to comment.