From 26a8e0d38cfba80b5d44dd7196a0eb6ad2e43631 Mon Sep 17 00:00:00 2001 From: "Benjamin M. Hughes" Date: Sun, 9 Jun 2019 14:06:07 +0100 Subject: [PATCH] Add connection close option --- lib/tp_link_smartplug/device.rb | 16 ++++++++++------ tp_link_smartplug.gemspec | 2 +- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/lib/tp_link_smartplug/device.rb b/lib/tp_link_smartplug/device.rb index d7d4624..3ae000f 100644 --- a/lib/tp_link_smartplug/device.rb +++ b/lib/tp_link_smartplug/device.rb @@ -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) @@ -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 @@ -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 @@ -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 diff --git a/tp_link_smartplug.gemspec b/tp_link_smartplug.gemspec index 4e9ec3b..b5da212 100644 --- a/tp_link_smartplug.gemspec +++ b/tp_link_smartplug.gemspec @@ -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']