netio230a-1.0.1/0000755000401300017500000000000011350362105013562 5ustar debalancedebalancenetio230a-1.0.1/example.setTime.py0000755000401300017500000000351211350245524017211 0ustar debalancedebalance#!/usr/bin/env python # -*- encoding: UTF8 -*- # Author: Philipp Klaus, philipp.l.klaus AT web.de # This file is part of netio230a. # # netio230a is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # netio230a is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with netio230a. If not, see . # example how to use the netio230a class ## import the netio230a class: import netio230a ## for sys.exit(1) import sys from datetime import datetime ### for timedelta() from datetime import timedelta ## for time.sleep() import time host = "192.168.1.2" pw = "your choosen password" tcp_port = 23 def main(): try: netio = netio230a.netio230a(host, "admin", pw, True, tcp_port) except StandardError: print("could not connect") sys.exit(1) systemTime = netio.getSystemTime() netio.setSystemTime(datetime.now()+timedelta(seconds=20)) time.sleep(0.9) # we have to wait (the new time has to be set first, which takes approx. 0.75 seconds) newSystemTime = netio.getSystemTime() netio = None # print response print "\n--------- successfully queried the Koukaam NETIO 230A ---------" print "system time: %s" % (systemTime) print "system time after update: %s" % (newSystemTime) print "--------------------------------------------------------------- \n" if __name__ == '__main__': main() netio230a-1.0.1/todo.txt0000644000401300017500000000115511350245524015277 0ustar debalancedebalancetodo - implement the login using connect button in the GUI - implement the use of a configuration file for the GUI: - remember multiple login credentials - remember program status (activated tab etc.) - set Portnames in GUI switchbox according to the name given to the port - implement the watchdog functionality (representation in port class) - implement the timer functionality (representation in port class) - maybe cleanup of the public methods of the netio230a class? - type safety!!! done - implemented all documented commands found in the manual up to command "port" on page 19. - much more ... netio230a-1.0.1/discoverNETIOsOnLAN.py0000755000401300017500000000375711350245524017610 0ustar debalancedebalance#!/usr/bin/env python # -*- encoding: UTF8 -*- # author: Philipp Klaus, philipp.l.klaus AT web.de # This file is part of netio230a. # # netio230a is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # netio230a is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with netio230a. If not, see . import netio230a import sys EXIT_SUCCESS=0 EXIT_FAILURE=1 # callback function for any found NETIO-230A device: def print_netio230a_device(device): deviceName = device[0] ip = device[1] sm = device[2] gw = device[3] mac = device[4] answer_time = device[5] print "\nUPD answer in %.2f ms" % answer_time print "Found a Koukaam NETIO-230A:" print "Name is:", deviceName print "IP address:", "%s.%s.%s.%s" % (ip[0], ip[1], ip[2], ip[3]) print "Subnet Mask:", "%s.%s.%s.%s" % (sm[0], sm[1], sm[2], sm[3]) print "Gateway address:", "%s.%s.%s.%s" % (gw[0], gw[1], gw[2], gw[3]) print "MAC address:", "%02X:%02X:%02X:%02X:%02X:%02X\n" % (mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]) global totalCount totalCount += 1 if __name__ == '__main__': print "Trying to discover any Koukaam NETIO-230A available on your LAN" totalCount = 0 netio230a.discover_netio230a_devices(print_netio230a_device) if totalCount == 0: print "No Koukaam NETIO-230A device found on your network." sys.exit(EXIT_FAILURE) else: print "Exiting after having found a number of %s Koukaam NETIO-230A devices." % totalCount sys.exit(EXIT_SUCCESS) netio230a-1.0.1/README.md0000644000401300017500000000342511350245524015052 0ustar debalancedebalance# netio230a: A Python class to interface the Koukaam NETIO 230A via TCP/IP. ## Project Information This software (netio230a) provides an interface via TCP to control the Koukaam NETIO 230A. The software consists of a class to represent the possibilities of the product and example code to show how to use it. It also provides a command line tool to switch on and off ports on the NETIO230A. ## Moving Forward I hope that someone will join the team as I have no time yet to complete the class. If you know Python and want to contribute, then please join the team! ## Required Python modules This project uses the python modules socket, hashlib, re, math, time, datetime, shlex and sys. The example.gui.py file needs pygtk installed. ## Installation and Usage The software is tested and known to work on Ubuntu Linux 9.04 Jaunty and on Microsoft Windows XP. It should, however, work on any operating system that supports python (and PyGTK for the GUI). Please refer to the Wiki site for information on how to install and use the software. ## License netio230a is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. netio230a is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with netio230a. If not, see . ## Author Philipp Klaus * philipp.l.klaus AT web.de netio230a-1.0.1/TODO.md0000644000401300017500000000403011350245524014653 0ustar debalancedebalanceTODO ==== Class ----- * switch on port for a configurable amount of time (to make coffee). (this can be done by setting the timer! SNTP should be however disabled for security reasons!) * implement the watchdog functionality (representation in port class) * implement the timer functionality (representation in port class) * maybe cleanup of the mixed use of mixedCase and lower_case_with_underscores (the later is preferred). * type safety (?!) GUI --- * show an error message when almost all requests fail (depending on the reason why they fail...). This may be: "The NETIO-230A seems to be unavailable at the moment. Disconnecting." * more threading (when changing from one tab to another, we want to do see status updates - YES. But first change to that tab and then do the update.) * save information in a configuration file: * remember program status (activated tab etc.) * preferences dialog: * automatic status updates (en-/disable, change frequency) * en-/disable logging * ability to change the names of the ports via the user interface * switch on a power socket for a configurable amount of time less important are: * ability to change the watchdog settings for each port * ability to change the time of the device, the DNS and IP settings, the system name. Allready Implemented -------------------- * save information in a configuration file: * remember multiple connection details and login credentials * login using connect button in the GUI * display socket name in GUI switchbox according to the name given in the webinterface * implemented all documented commands found in the manual up to command "port" on page 19. * automatic status updates (every 3 seconds) * logging capabilities for the class added (the GUI makes use of it) * link to open the devices website with a single click on the GUI * concurrent access to the netio230a library secured (by waiting for the other request or throwing an exception) * possibility to choose between persistent networking and loose coupled network sockets on the GUI connection dialog netio230a-1.0.1/netio230a_gui.py0000755000401300017500000007500611350245524016524 0ustar debalancedebalance#!/usr/bin/env python # -*- encoding: UTF8 -*- # author: Philipp Klaus, philipp.l.klaus AT web.de # This file is part of netio230a. # # netio230a is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # netio230a is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with netio230a. If not, see . # documentation on PyGTK: # http://library.gnome.org/devel/pygtk/stable/ # http://library.gnome.org/devel/pygobject/stable/ # # good pygtk tutorial: import sys import os # for os.path.abspath() and os.path.dirname() import gtk ## for debugging (set debug mark with pdb.set_trace() ) import pdb import netio230a # to store and retrieve recent connections: import configuration import gobject # for the timer import signal # for [Ctrl]-[c] catching PROGRAM_ICON = 'netio230a_icon.png' DEVICE_CONTROLLER_UI = "netio230aGUI.glade" CONNECTION_DETAIL_UI = "netio230aGUI_dialog.glade" POSSIBLE_RESOURCE_PATHS = [ os.path.abspath(os.path.dirname(sys.argv[0])) + '/resources/', # path relative to this script '/usr/share/netio230a-gui/', # debian resource path ] AUTO_UPDATE = 3 # auto update time seconds OVERWRITE_TELNET_SOCKET_TIMEOUT = 1 DEBUG_MODE = True MIN_DEBUG_LEVEL = 7 # constants do not touch: DBG_WARNING = 8 # remember position of window: # (x, y) = w.get_position() # (w, h) = w.get_size() # #restore position: # w = gtk.Window() # w.move(x, y) # w.resize(w, h) def getAbsoluteFilepath(filename): for path in POSSIBLE_RESOURCE_PATHS: if os.path.isfile(path + filename): return path + filename raise NameError('File ('+ filename +') not found in possible resource folders: '+str(POSSIBLE_RESOURCE_PATHS)) class AboutDialog: def __init__(self): self.builder = gtk.Builder() self.builder.add_from_file(getAbsoluteFilepath(DEVICE_CONTROLLER_UI)) self.about_dialog = self.builder.get_object( "aboutDialog" ) self.about_dialog.set_icon_from_file(getAbsoluteFilepath(PROGRAM_ICON)) def run(self): self.about_dialog.run() self.about_dialog.destroy() class DeviceController: def __init__(self,controller,connection_details): self.controller = controller self.__host = connection_details['host'] self.__tcp_port = connection_details['tcp_port'] self.__username = connection_details['username'] self.__pw = connection_details['password'] self.__persistent_connection = connection_details['persistent_network'] try: self.netio = netio230a.netio230a(self.__host, self.__username, self.__pw, True, self.__tcp_port) self.netio.enable_logging(open(configuration.LOG_FILE,'w')) except StandardError, error: print(str(error)) self.builder = gtk.Builder() self.builder.add_from_file(getAbsoluteFilepath(DEVICE_CONTROLLER_UI)) self.window = self.builder.get_object("mainWindow") self.window.set_icon_from_file(getAbsoluteFilepath(PROGRAM_ICON)) self.builder.get_object("link_button").set_uri('http://'+self.__host) self.updateLabels() self.updatePowerSocketStatus() self.builder.connect_signals(self) self.window.connect("window-state-event",self.handle_window_state_events) self.window.show() # a timer to update the UI automatically self.timer_id = gobject.timeout_add(1000, self.timer_tick) # use gobject.timeout_add_seconds() for longer periods self.timer_continue = True self.counter = 0 def timer_tick(self): if self.timer_id is not None and self.timer_continue: self.counter += 1 if self.counter%AUTO_UPDATE == 0: try: self.updatePowerSocketStatus() except StandardError, error: pass debug("The updatePowerSocketStatus action triggered by the timer failed: " + str(error), DBG_WARNING) self.counter = 0 return True # run again in one second return False # stop running again def handle_window_state_events(self, window, event): if event.changed_mask & gtk.gdk.WINDOW_STATE_ICONIFIED: if event.new_window_state & gtk.gdk.WINDOW_STATE_ICONIFIED: #print 'Window was minimized!' self.controller.toggle_visibility() #else: # print 'Window was unminimized!' def cb_disconnect(self, button, *args): self.controller.setNextStep("runDeviceSelector") gtk.main_quit() self.window.hide() return False def gtk_main_quit( self, window ): gtk.main_quit() def on_window_destroy(self, widget, data=None): gtk.main_quit() def cb_about(self, button): about = AboutDialog() about.run() def cb_updateDisplay(self, notebook, page, page_num): self.updateStatusBar() if page_num == 0: self.updatePowerSocketStatus() elif page_num == 1: self.updateSystemSetup() pass elif page_num == 2: self.updatePowerSocketStatus() else: return def cb_refresh(self, button): self.updatePowerSocketStatus() def updatePowerSocketStatus(self): try: power_sockets = self.netio.getAllPowerSockets() except StandardError, error: print(str(error)) return if not self.__persistent_connection: self.netio.disconnect() # update checkboxes on this GUI and on the status icon: i = 1 new_status = [] for power_socket in power_sockets: ## shorter form with builder.get_object(). cf. self.builder.get_object("socket"+str(i)).set_active(power_socket.getPowerOn()) new_status.append([power_socket.getName(),power_socket.getPowerOn()]) i += 1 self.controller.icon.update_checkboxes(new_status) # update the status text: tb = gtk.TextBuffer() tb.set_text("power status:\nsocket 1: %s\nsocket 2: %s\nsocket 3: %s\nsocket 4: %s" % (power_sockets[0].getPowerOn(),power_sockets[1].getPowerOn(),power_sockets[2].getPowerOn(),power_sockets[3].getPowerOn())) self.builder.get_object("status_output").set_buffer( tb ) self.updateStatusBar() def updateStatusBar(self): self.builder.get_object("status_label").set_text(u"ø %.1f ms/request (%d total)" % (self.netio.mean_request_time*1000, self.netio.number_of_sent_requests)) def updateLabels(self): try: power_sockets = self.netio.getAllPowerSockets() except StandardError, error: print(str(error)) return if not self.__persistent_connection: self.netio.disconnect() for i in range(4): label_name = "socket"+str(i+1)+"_label" self.builder.get_object(label_name).set_text(self.builder.get_object(label_name).get_text()+' ("'+power_sockets[i].getName()+'")') def updateSystemSetup(self): try: deviceAlias = self.netio.getDeviceAlias() version = self.netio.getFirmwareVersion() systemTime = self.netio.getSystemTime().isoformat(" ") timezoneOffset = self.netio.getSystemTimezone() sntpSettings = self.netio.getSntpSettings() except StandardError, error: print(str(error)) return if not self.__persistent_connection: self.netio.disconnect() self.builder.get_object("device_name").set_text( deviceAlias ) self.builder.get_object("firmware_version").set_text( version ) self.builder.get_object("system_time").set_text( systemTime ) self.builder.get_object("timezone_offset").set_text( str(timezoneOffset) + " hours" ) self.builder.get_object("sntp_settings").set_text( sntpSettings ) def cb_switch1On(self, togglebutton): self.__setPowerSocket(1,togglebutton.get_active()) def cb_switch2On(self, togglebutton): self.__setPowerSocket(2,togglebutton.get_active()) def cb_switch3On(self, togglebutton): self.__setPowerSocket(3,togglebutton.get_active()) def cb_switch4On(self, togglebutton): self.__setPowerSocket(4,togglebutton.get_active()) def __setPowerSocket(self,socket_nr,socket_power=True): try: self.netio.setPowerSocketPower(socket_nr,socket_power) except StandardError, error: print(str(error)) if not self.__persistent_connection: self.netio.disconnect() self.updatePowerSocketStatus() class ConnectionDetailDialog: def __init__(self,host='',username='admin',password='',port=1234, store_connection = True, store_password = False): self.builder = gtk.Builder() self.builder.add_from_file(getAbsoluteFilepath(CONNECTION_DETAIL_UI)) self.dialog = self.builder.get_object("ConnectionDetailDialog") self.dialog.set_title("Provide connection details...") self.dialog.set_icon_from_file(getAbsoluteFilepath(PROGRAM_ICON)) # pre-fill values of text entries self.builder.get_object("host_text").set_text(host) self.builder.get_object("port_text").set_text(str(port)) self.builder.get_object("username_text").set_text(username) self.builder.get_object("password_text").set_text(password) # focus the first empty text entry: entry_field_names = ['host','port','username','password'] for field_name in entry_field_names: if str(locals()[field_name]) == '': # this is nice trick to call the variable with the name stored in field_name self.builder.get_object(field_name+"_text").grab_focus() break self.builder.get_object("store_connection").set_active(store_connection) self.builder.get_object("store_password").set_active(store_password) self.builder.get_object("action_area").set_focus_chain([self.builder.get_object("connect_button"), self.builder.get_object("abort_button")]) def run(self): self.builder.connect_signals(self) self.builder.get_object("store_connection").connect("toggled", self.sensitivityUpdate) return self.dialog.run() def sensitivityUpdate(self, widget): self.builder.get_object("store_password").set_sensitive(self.builder.get_object("store_connection").get_active()) def updateData(self): self.__host = self.builder.get_object("host_text").get_text() self.__username = self.builder.get_object("username_text").get_text() self.__pw = self.builder.get_object("password_text").get_text() try: self.__tcp_port = int(self.builder.get_object("port_text").get_text()) except: self.__tcp_port = 0 self.builder.get_object("port_text").set_text("0") self.__store_connection = self.builder.get_object("store_connection").get_active() self.__store_password = self.builder.get_object("store_password").get_active() self.__persistent_network = self.builder.get_object("persistent_network").get_active() def enter_pressed(self, widget): self.builder.get_object("connect_button").activate() ## could also be done by setting the default response id: #self.dialog.set_default_response(response_id) # resp_id might be 1 def response_handler(self, widget, response_id): self.updateData() def getData(self): data = dict() data['host'] = self.__host data['username'] = self.__username data['password'] = self.__pw data['tcp_port'] = self.__tcp_port data['store_connection'] = self.__store_connection data['store_password'] = self.__store_password data['persistent_network'] = self.__persistent_network return data class DeviceSelector: # close the window and quit def delete_event(self, widget, event, data=None): gtk.main_quit() def __init__(self, controller): self.controller = controller # Create a new window self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.window.set_title("Select a Device") self.window.set_icon_from_file(getAbsoluteFilepath(PROGRAM_ICON)) self.window.set_size_request(470, 220) self.window.connect("delete_event", self.delete_event) # create a TreeStore with two string columns to use as the model self.treestore = gtk.TreeStore(str,str,str,str,str) devices = netio230a.get_all_detected_devices() if len(devices) > 0: self.auto_iter = self.treestore.append(None,['auto-detected devices','','','','']) else: if os.name == 'nt': self.treestore.append(None,['auto-detection is not working on Windows','','','','']) else: self.treestore.append(None,['no auto-detected devices','','','','']) for device in devices: # device name, IP, port, user, password self.treestore.append(self.auto_iter,[device[0],str(device[1][0])+'.'+str(device[1][1])+'.'+str(device[1][2])+'.'+str(device[1][3]),'','','']) # devices from configuration has the form [devicename, host, port, username, password] devices = configuration.getConfiguration() if len(devices) > 0: self.recently_iter = self.treestore.append(None,['previously used devices','','','','']) for device in devices: # device name, IP, port, user, password self.treestore.append(self.recently_iter,[device[0],device[1],str(device[2]),device[3],device[4]]) # more on TreeViews: # and # create the TreeView using treestore self.treeview = gtk.TreeView(self.treestore) # create the TreeViewColumn to display the data self.tvc_device_name = gtk.TreeViewColumn('Device Name') self.tvc_ip = gtk.TreeViewColumn('IP Address') self.tvc_tcp_port = gtk.TreeViewColumn('TCP Port') self.tvc_user_name = gtk.TreeViewColumn('User Name') # set alignment of the column titles to right #self.tvc_ip.set_alignment(1.0) #self.tvc_tcp_port.set_alignment(1.0) # add tvcolumn to treeview self.treeview.append_column(self.tvc_device_name) self.treeview.append_column(self.tvc_ip) self.treeview.append_column(self.tvc_tcp_port) self.treeview.append_column(self.tvc_user_name) # create a CellRendererText to render the data self.cell = gtk.CellRendererText() self.cell_right_align = gtk.CellRendererText() self.cell_right_align.set_property('xalign', 1.0) # add the cell to the tvcolumn and allow it to expand self.tvc_device_name.pack_start(self.cell, True) self.tvc_ip.pack_start(self.cell_right_align, True) self.tvc_tcp_port.pack_start(self.cell_right_align, True) self.tvc_user_name.pack_start(self.cell, True) # set the cell "text" attribute to column 0 - retrieve text from that column in treestore self.tvc_device_name.add_attribute(self.cell, 'text', 0) self.tvc_ip.add_attribute(self.cell_right_align, 'text', 1) self.tvc_tcp_port.add_attribute(self.cell_right_align, 'text', 2) self.tvc_user_name.add_attribute(self.cell, 'text', 3) # make it searchable self.treeview.set_search_column(0) # Allow sorting on the column self.tvc_device_name.set_sort_column_id(0) self.tvc_ip.set_sort_column_id(1) self.tvc_tcp_port.set_sort_column_id(2) self.tvc_user_name.set_sort_column_id(3) # Allow drag and drop reordering of rows self.treeview.set_reorderable(True) self.treeview.expand_all() self.treeview.set_size_request(-1,200) spacing, homogeneous, expand, fill, padding = 2, False, True, True, 2 # Create a new hbox with the appropriate homogeneous # and spacing settings box = gtk.HBox(homogeneous, spacing) # create the buttons button = gtk.Button("other device") box.pack_start(button, expand, fill, padding) button.connect("clicked",self.connect_clicked) button = gtk.Button("connect") box.pack_start(button, expand, fill, padding) button.connect("clicked",self.connect_clicked, self.treeview) scroll = gtk.ScrolledWindow() scroll.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC); scroll.add(self.treeview); spacing, homogeneous, expand, fill, padding = 1, False, False, True, 2 superbox = gtk.VBox(homogeneous, spacing) superbox.pack_start(scroll, True, True, 1) superbox.pack_start(box, False, False, 0) self.superbox = superbox self.window.add(self.superbox) self.window.show_all() def connect_clicked(self, button, *args): host = '' stored_connection = False for arg in args: if type(arg)==gtk.TreeView: (model, treeiter) = arg.get_selection().get_selected() host = model.get_value(treeiter,1) parent_iter = model.iter_parent(treeiter) # compare the text (of the 1st col) of the parent node with the text of the recently_iter node try: if model.get_value(self.recently_iter,0) == model.get_value(parent_iter,0): stored_connection = True tcp_port = model.get_value(treeiter,2) username = model.get_value(treeiter,3) password = model.get_value(treeiter,4) store_password = False if password=='' else True except: # we don't have recently used devices yet... pass if host == '': return #dlg = gtk.Dialog(title='Ein Dialog', # parent=self.window, # buttons=(gtk.STOCK_CANCEL, # gtk.RESPONSE_REJECT, # gtk.STOCK_OK, # gtk.RESPONSE_OK)) #result = dlg.run() #if result == gtk.RESPONSE_OK: # print 'Mach mal!' #else: # print 'Lieber nicht.' #dlg.destroy() if stored_connection: self.dl = ConnectionDetailDialog(host, username, password, tcp_port, stored_connection, store_password) else: self.dl = ConnectionDetailDialog(host) self.controller.deny_quit = True result = self.dl.run() self.controller.deny_quit = False while result == 1: data = self.dl.getData() try: netio = netio230a.netio230a(data['host'], data['username'], data['password'], True, data['tcp_port']) devicename = netio.getDeviceAlias() netio = None break except StandardError, error: print(str(error)) netio = None continue_abort = gtk.MessageDialog(parent=self.dl.dialog, flags=gtk.DIALOG_MODAL|gtk.DIALOG_DESTROY_WITH_PARENT, type=gtk.MESSAGE_INFO, buttons=gtk.BUTTONS_OK_CANCEL, message_format="Connection failed. \n\n"+str(error)+"\n\nChange connection details and try again?") response = continue_abort.run() continue_abort.destroy() if response == gtk.RESPONSE_OK: self.controller.deny_quit = True result = self.dl.run() self.controller.deny_quit = False else: result = 0 break self.dl.dialog.hide() del self.dl if result != 1: return # connection successful, do want to store the configuration? if data['store_connection'] == True: configuration.changeConfiguration(configuration.UPDATE, devicename, data['host'], data['tcp_port'], data['username'], data['password'] if data['store_password'] else '') else: configuration.changeConfiguration(configuration.REMOVE, devicename, data['host'], data['tcp_port'], data['username'], '') md = gtk.MessageDialog(self.window, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_INFO, gtk.BUTTONS_CLOSE, "Connection details removed from configuration file.") md.run() md.destroy() self.controller.setNextStep("runDeviceController", host = data['host'], tcp_port = data['tcp_port'], username=data['username'], password = data['password'], persistent_network = data['persistent_network']) #self.window.hide() self.window.destroy() gtk.main_quit() return False class TrayIcon(gtk.StatusIcon): # reely adapted from the tracker-applet: # one more resource: # please note that the context menu (just as any other menu in Gnome will not have icons unless you set the gconf key /desktop/gnome/interface/menus_have_icons to true. For further information see . def __init__(self,controller): gtk.StatusIcon.__init__(self) self.block_changes = True self.controller = controller self.set_disconnected_ui() self.set_from_file(getAbsoluteFilepath(PROGRAM_ICON)) self.set_tooltip('NETIO-230A control') self.set_visible(True) self.connect('activate', self.on_activate) self.connect('popup-menu', self.on_popup_menu) self.block_changes = False def set_disconnected_ui(self): self.connected_mode = False menu = ''' ''' # order of the elements in the action tuples: # The name of the action. Must be specified. # The stock id for the action. Optional with a default value of None if a label is specified. # The label for the action. This field should typically be marked for translation, see the set_translation_domain() method. Optional with a default value of None if a stock id is specified. # The accelerator for the action, in the format understood by the gtk.accelerator_parse() function. Optional with a default value of None. # The tooltip for the action. This field should typically be marked for translation, see the set_translation_domain() method. Optional with a default value of None. # The callback function invoked when the action is activated. Optional with a default value of None. actions = [ ('Menu', None, 'Menu'), #('Search', None, '_Search...', None, 'Search files with MetaTracker', self.on_activate), ('ConnectNote', None, ' - please connect first... - ', None, 'Please connect to a NETIO-230A device to be able to power on/off sockets.', self.on_toggle), ('About', gtk.STOCK_ABOUT, '_About...', None, 'About NETIO-230A control', self.on_about), ('Quit', gtk.STOCK_QUIT, '_Quit', None, 'Quit the program', self.quit),] ag = gtk.ActionGroup('Actions') ag.add_actions(actions) self.manager = gtk.UIManager() self.manager.insert_action_group(ag, 0) self.manager.add_ui_from_string(menu) self.menu = self.manager.get_widget('/Menubar/Menu/About').props.parent connect_note = self.manager.get_widget('/Menubar/Menu/ConnectNote') image = gtk.Image() image.set_from_file(getAbsoluteFilepath(PROGRAM_ICON)) connect_note.set_image(image) #search.get_children()[0].set_markup('_Search...') #search.get_children()[0].set_use_underline(True) #search.get_children()[0].set_use_markup(True) #search.get_children()[1].set_from_stock(gtk.STOCK_FIND, gtk.ICON_SIZE_MENU) def update_checkboxes(self,new_status): i = 1 self.block_changes = True for socket in new_status: menu_item = self.manager.get_widget('/Menubar/Menu/Socket' + str(i)) if menu_item == None: continue menu_item.set_label("_%d: %s" % (i, socket[0])) menu_item.set_active(socket[1]) i += 1 self.block_changes = False def set_connected_ui(self): self.connected_mode = True menu = ''' ''' actions = [ ('Menu', None, 'Menu'), #('Search', None, '_Search...', None, 'Search files with MetaTracker', self.on_activate), #('Preferences', gtk.STOCK_PREFERENCES, '_Preferences...', None, 'Change MetaTracker preferences', self.on_preferences), ('About', gtk.STOCK_ABOUT, '_About...', None, 'About NETIO-230A control', self.on_about), ('Quit', gtk.STOCK_QUIT, '_Quit', None, 'Quit the program', self.quit),] toggle_actions = [ ('Socket1', None, '_1: Toggle Socket 1', None, 'Switch power socket 1 on or off.', self.on_toggle,True), ('Socket2', None, '_2: Toggle Socket 2', None, 'Switch power socket 2 on or off.', self.on_toggle), ('Socket3', None, '_3: Toggle Socket 3', None, 'Switch power socket 3 on or off.', self.on_toggle), ('Socket4', None, '_4: Toggle Socket 4', None, 'Switch power socket 4 on or off.', self.on_toggle),] ag = gtk.ActionGroup('Actions') ag.add_actions(actions) ag.add_toggle_actions(toggle_actions) self.manager = gtk.UIManager() self.manager.insert_action_group(ag, 0) self.manager.add_ui_from_string(menu) self.menu = self.manager.get_widget('/Menubar/Menu/About').props.parent #search = self.manager.get_widget('/Menubar/Menu/Search') #search.get_children()[0].set_markup('_Search...') #search.get_children()[0].set_use_underline(True) #search.get_children()[0].set_use_markup(True) #search.get_children()[1].set_from_stock(gtk.STOCK_FIND, gtk.ICON_SIZE_MENU) def quit(self, widget): if self.controller.deny_quit: self.controller.quit_requested() else: gtk.main_quit() def on_activate(self, data): #print("ok, here we want to toggle the visibility of the program...") self.controller.toggle_visibility() def on_toggle(self, action): if self.block_changes == True: return try: socket_name = action.get_name() except: raise NameError("actions seems to be no gtk.Action! something went wrong") if socket_name.find("Socket") != -1: try: #print("toggeling " + socket_name[6]) self.controller.topical_window.netio.togglePowerSocketPower(int(socket_name[6])) #self.controller.topical_window.netio.disconnect() self.controller.topical_window.updatePowerSocketStatus() except: #print("sorry, log in first.") pass def on_popup_menu(self, status, button, time): if self.connected_mode: self.controller.topical_window.updatePowerSocketStatus() self.menu.popup(None, None, None, button, time) #def on_preferences(self, data): # print 'preferences' def on_about(self, data): about = AboutDialog() about.run() class Controller(object): def run(self): self.nextStep = "runDeviceSelector" self.visible = True self.deny_quit = False self.icon = TrayIcon(self) while self.nextStep != "": if self.nextStep == "runDeviceSelector": self.nextStep = "" self.runDeviceSelector() elif self.nextStep == "runDeviceController": self.nextStep = "" self.runDeviceController(self.nextStepKWArgs) def quit_requested(self): try: self.topical_window.dl.dialog.present() except: pass def toggle_visibility(self): if self.visible == True: self.topical_window.window.hide() self.visible = False else: self.topical_window.window.show() self.visible = True def setNextStep(self,what, **kwargs): self.nextStep = what self.nextStepKWArgs = kwargs def runDeviceSelector(self): self.icon.set_disconnected_ui() self.topical_window = DeviceSelector(self) gtk.main() del self.topical_window def runDeviceController(self, connection_details): self.icon.set_connected_ui() self.topical_window = DeviceController(self, connection_details) gtk.main() self.topical_window.timer_continue = False del self.topical_window.netio def debug(message, level): if DEBUG_MODE and level > DEBUG_LEVEL: print(message) def main(): controller = Controller() controller.run() if __name__ == "__main__": signal.signal(signal.SIGINT, signal.SIG_DFL) # ^C exits the application netio230a.TELNET_SOCKET_TIMEOUT = OVERWRITE_TELNET_SOCKET_TIMEOUT main() netio230a-1.0.1/example.interrupt.py0000755000401300017500000000302611350245524017633 0ustar debalancedebalance#!/usr/bin/env python # -*- encoding: UTF8 -*- # Author: Philipp Klaus, philipp.l.klaus AT web.de # This file is part of netio230a. # # netio230a is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # netio230a is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with netio230a. If not, see . # example how to use the netio230a class ## import the netio230a class: import netio230a ## for sys.exit(1) import sys host = "192.168.1.2" pw = "your choosen password" tcp_port = 23 interruptPowerSocket=2 def main(): try: netio = netio230a.netio230a(host, "admin", pw, True,tcp_port) except StandardError: print("could not connect") sys.exit(1) netio.setPowerSocketTempInterrupt(interruptPowerSocket) netio = None # print response print "\n--------- successfully queried the Koukaam NETIO 230A ---------" print "temporarily interrupted power socket %s" % (interruptPowerSocket) print "--------------------------------------------------------------- \n" if __name__ == '__main__': main() netio230a-1.0.1/netio230a_ctrl.py0000755000401300017500000001151511350245524016677 0ustar debalancedebalance#!/usr/bin/env python # -*- encoding: UTF8 -*- # Author: Philipp Klaus, philipp.l.klaus AT web.de # This file is part of netio230a. # # netio230a is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # netio230a is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with netio230a. If not, see . # Command Line Interface - CLI for the Koukaam NETIO 230A ## import the netio230a class: import netio230a ## for sys.exit(1) import sys EXIT_SUCCESS=0 EXIT_FAILURE=1 ## for ^C catching: import signal ## for optparse.OptionParser() import optparse NOT_SET="--not set--" def main(): #p = optparse.OptionParser(usage="usage: %prog [options] -i[source] -o[target]",add_help_option=False) p = optparse.OptionParser(usage="usage: %prog [--host HOST] [--port PORT] [--username USERNAME] [--password PASSWORD] -s SOCKET [--on]",add_help_option=False) p.add_option('-?', action="store_true", help="show this help message and exit", dest="show_help") p.add_option('--host', '-h', default=NOT_SET, help="Hostname for the device (defaults to the first one found by the discovery in your LAN)") p.add_option('--port', '-p', default="1234", help="TCP port (defaults to 1234)") p.add_option('--username', '-u', default="admin", help="username to use for login (defaults to admin)") p.add_option('--password', '-w', default="", help="password to use for login (will ask if left empty)") p.add_option('--socket', '-s', default=NOT_SET, metavar="SOCKET#", help="socketnumber (1-4) to switch on/off") p.add_option("--on", action="store_true", dest="switchOn", help='switch on when --on set, off if omitted') options, arguments = p.parse_args() if options.host == NOT_SET and options.socket == NOT_SET: options.show_help = True if options.show_help: p.print_help() sys.exit(1) if options.switchOn == None: options.switchOn = False if options.host is NOT_SET: netio230a_devices = netio230a.get_all_detected_devices() if len(netio230a_devices) == 0: p.error("Please specify a host you want to connect to") elif len(netio230a_devices) == 1: deviceName = netio230a_devices[0][0] ip = netio230a_devices[0][1] ip = "%s.%s.%s.%s" % (ip[0], ip[1], ip[2], ip[3]) print "We discovered a single NETIO-230A device on the LAN: (%s,%s)" % (deviceName, ip) print "Selecting this one as host." options.host = ip else: print netio230a_devices addresses = ", ".join([ ("%s: %d.%d.%d.%d" % (dev[0], dev[1][0], dev[1][1], dev[1][2], dev[1][3])) for dev in netio230a_devices]) print addresses p.error("%d devices found (%s).\nPlease specify which one you want to connect to using the --host parameter." % (len(netio230a_devices), addresses) ) if options.socket is "not set": p.error("Please specify the socket you want to switch.") try: options.port = int(options.port) except StandardError: p.error("Please specify the TCP port to connect to as an integer value.") try: options.socket = int(options.socket) except StandardError: p.error("Please specify the socket to switch as an integer value.") if len(options.password) == 0: options.password = raw_input("Please give a password (user "+options.username+"): ") try: netio = netio230a.netio230a(options.host, options.username, options.password, True, options.port) except NameError, error: print("Could not connect. "+str(error)) sys.exit(EXIT_FAILURE) #except StandardError, error: # print("Could not connect. Please inform the programmer of this error. "+str(error)) # sys.exit(EXIT_FAILURE) try: netio.setPowerSocketPower(options.socket, int(options.switchOn)) except StandardError, ne: print("Could not switch socket power. "+str(ne)) netio = None # print response print "\n--------- successfully interfaced the Koukaam NETIO 230A ---------" print "set socket %s to: \"%s\"" % (options.socket, int(options.switchOn)) print "---------------------------------------------------------------- \n" sys.exit(EXIT_SUCCESS) if __name__ == '__main__': signal.signal(signal.SIGINT, signal.SIG_DFL) # ^C exits the application main() netio230a-1.0.1/resources/0000755000401300017500000000000011350245524015601 5ustar debalancedebalancenetio230a-1.0.1/resources/netio230a_icon.png0000644000401300017500000000066011350245524021025 0ustar debalancedebalancePNG  IHDRasRGBbKGD pHYs  tIME )Iv-tEXtCommentCreated with GIMPW IDAT8͓jpJ U!- թ1t׌n.Zб%Z}* XpAfw:9ýד,<-( Uċ`yD#O QM;U qy*D wahq&.Sc| m&RMYr=DzTkh+|vs7::B+<<(D %ZۂzFSp?no}:$g$VUIENDB`netio230a-1.0.1/resources/netio230a_icon.svg0000644000401300017500000000714211350245524021042 0ustar debalancedebalance image/svg+xml IO netio230a-1.0.1/resources/netio230aGUI.glade0000644000401300017500000016204711350245524020662 0ustar debalancedebalance 450 300 NETIO-230A control False mouse True vertical True True _NETIO-230A True True gtk-disconnect True True True True gtk-quit True True True True _Help True True gtk-about True True True False 0 True True 4 True 3 vertical gtk-refresh True True True True 0 170 True False True False 1 True Status False True 10 vertical True True 0 Device Name False False 0 True False True False False False False 1 0 True True 0 Firmware Version False False 0 True False True False False False False 1 1 True True 0 System Time False False 0 True False True False False False False 1 2 True True 0 Timezone Offset False False 0 True False True False False False False 1 3 True True 0 Sntp Settings False False 0 True False True False False False False 1 4 1 True Device Setup 1 False True 4 vertical True True 0 Socket 1 0 True True False True False 1 0 True True 0 Socket 2 0 True True False True False 1 1 True True 0 Socket 3 0 True True False True False 1 2 True True 0 Socket 4 0 True True False True False 1 3 2 True Power Sockets' Status 2 False 1 True 2 Open NETIO-230A Website in Browser True True True This website is only going to be displayed if you are on the same (local) network as the NETIO-230A. Otherwise you would have to forward the webserver port (80) on your router to the NETIO-230A. none 0 http://koukaam.se False 0 True 1 4 1 2 5 normal netio230a control GUI v1.0 (c) 2009-2010 by Philipp Klaus Licensed under the GPL. This software helps you access and configure your Koukaam NETIO-230A. http://pklaus.github.com/netio230a/ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS Philipp Klaus <philipp.l.klaus@web.de> True vertical 2 True end False end 0 netio230a-1.0.1/resources/netio230aGUI_dialog.glade0000644000401300017500000002705611350245524022201 0ustar debalancedebalance 5 normal False True vertical 2 True vertical True True 0 host 0 True True The domain or IP address of the NETIO-230A you want to connect to. 25 False 1 0 True True 0 TCP port 0 True True The configured telnet TCP port of the machine. The default value on newer firmware releases is 1234 on oder ones the standard telnet port 23. 25 False 1 1 True True 0 username 0 True True Usually this is "admin" although basic user permissions exist on the device, so a "user" should also be fine. 25 False 1 2 True True 0 password 0 True True False 25 True True False 1 3 True True store connection True True False True True 0 store password True True False Whit this checkbox activated the software will store the password in cleartext in your home directory. This is not safe! Use it with care! True 1 4 keep network connection open True True False When you activate the persistent network connection mode the NETIO-230A will stay connected to the software. This makes it impossible for other telnet clients to connect to the box. Nevertheless it is faster and more stable. True True 5 1 True end abort True True True False False 0 connect True True True False False 1 False end 0 abort_button connect_button netio230a-1.0.1/example.switchPower.py0000755000401300017500000000377511350245524020130 0ustar debalancedebalance#!/usr/bin/env python # -*- encoding: UTF8 -*- # Author: Philipp Klaus, philipp.l.klaus AT web.de # This file is part of netio230a. # # netio230a is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # netio230a is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with netio230a. If not, see . # example how to use the netio230a class ## import the netio230a class: import netio230a ## for sys.exit(1) import sys host = "192.168.1.2" pw = "your choosen password" tcp_port = 23 power_socket_to_change=2 power_on=True def main(): try: netio = netio230a.netio230a(host, "admin", pw, True, tcp_port) except StandardError: print("could not connect") sys.exit(1) power_before = netio.getPowerSocketList() netio.setPowerSocketPower(power_socket_to_change,power_on) power_after = netio.getPowerSocketList() netio = None # print response print "\n--------- successfully queried the Koukaam NETIO 230A ---------" print "power status before change: power socket 1: %s, power socket 2: %s, power socket 3: %s, power socket 4: %s" % (power_before[0],power_before[1],power_before[2],power_before[3] ) print "set power socket %s to: \"%s\"" % (power_socket_to_change,power_on) print "power status after change: power socket 1: %s, power socket 2: %s, power socket 3: %s, power socket 4: %s" % (power_after[0],power_after[1],power_after[2],power_after[3] ) print "---------------------------------------------------------------- \n" if __name__ == '__main__': main() netio230a-1.0.1/example.querySystemStatus.py0000755000401300017500000000750611350245524021364 0ustar debalancedebalance#!/usr/bin/env python # -*- encoding: UTF8 -*- # Author: Philipp Klaus, philipp.l.klaus AT web.de # This file is part of netio230a. # # netio230a is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # netio230a is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with netio230a. If not, see . # example how to use the netio230a class ## import the netio230a class: import netio230a ## for debugging (set debug mark with pdb.set_trace() ) import pdb ## for sys.exit(1) import sys host = "192.168.1.2" pw = "your choosen password" tcp_port = 23 def main(): try: netio = netio230a.netio230a(host, "admin", pw, True, tcp_port) except StandardError: print("could not connect") sys.exit(1) version = netio.getFirmwareVersion() swDelay = netio.getSwitchDelay() power_sockets = netio.getAllPowerSockets() power_socket_1_status = netio.getPowerSocketSetup(0) deviceAlias = netio.getDeviceAlias() watchdogSettings1 = netio.getWatchdogSettings(1) networkSettings = netio.getNetworkSettings() dnsServer = netio.getDnsServer() systemDiscoverable = netio.getSystemDiscoverableUsingTool() sntpSettings = netio.getSntpSettings() systemTime = netio.getSystemTime() timezoneOffset = netio.getSystemTimezone() netio = None # print response print "\n--------- successfully queried the Koukaam NETIO 230A ---------" print "power status: power socket 1: %s, power socket 2: %s, power socket 3: %s, power socket 4: %s" % (power_sockets[0].getPowerOn(),power_sockets[1].getPowerOn(),power_sockets[2].getPowerOn(),power_sockets[3].getPowerOn()) print "power on after power loss: power socket 1: %s, power socket 2: %s, power socket 3: %s, power socket 4: %s" % (power_sockets[0].getPowerOnAfterPowerLoss(),power_sockets[1].getPowerOnAfterPowerLoss(),power_sockets[2].getPowerOnAfterPowerLoss(),power_sockets[3].getPowerOnAfterPowerLoss()) print "power socket names: power socket 1: \"%s\", power socket2: \"%s\", power socket 3: \"%s\", power socket 4: \"%s\"" % (power_sockets[0].getName(),power_sockets[1].getName(),power_sockets[2].getName(),power_sockets[3].getName()) print "manual mode: power socket 1: %s, power socket 2: %s, power socket 3: %s, power socket 4: %s" % (power_sockets[0].getManualMode(),power_sockets[1].getManualMode(),power_sockets[2].getManualMode(),power_sockets[3].getManualMode()) print "interrupt delay: power socket 1: %s seconds, power socket 2: %s seconds, power socket 3: %s seconds, power socket 4: %s seconds" % (power_sockets[0].getInterruptDelay(),power_sockets[1].getInterruptDelay(),power_sockets[2].getInterruptDelay(),power_sockets[3].getInterruptDelay()) print "Firmware Version: %s" % (version) print "switch delay: %s seconds" % (swDelay) print "status of power socket 1: %s" % (power_socket_1_status) print "device alias: %s" % (deviceAlias) print "watchdog settings for power socket 1: %s" % (watchdogSettings1) print "network settings: %s" % (networkSettings) print "system discoverable: %s" % (systemDiscoverable) print "DNS server: %s" % (dnsServer) print "SNTP settings: %s" % (sntpSettings) print "system time: %s" % (systemTime) print "timezone offset: %s hours" % (timezoneOffset) print "---------------------------------------------------------------- \n" if __name__ == '__main__': main() netio230a-1.0.1/netio230a.py0000644000401300017500000006122211350245524015650 0ustar debalancedebalance# # -*- encoding: UTF8 -*- # author: Philipp Klaus, philipp.l.klaus AT web.de # This file is part of netio230a. # # netio230a is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # netio230a is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with netio230a. If not, see . # This class represents the multiple plug hardware Koukaam NET-IO 230A # It can be configured using raw TCP communication. # The class aimes at providing complete coverage of the functionality of the box # but not every action is supported yet. ###--------- ToDo next ------------ # http://koukaam.se/koukaam/forum/viewthread.php?forum_id=18&thread_id=399 # Command for enable wd with 360s delay on output 2: # port wd 2 enable 192.168.10.101 10 360 1 3 enable enable # for the raw TCP socket connection: import socket # for md5 checksum: import hashlib # for RegularExpressions: import re ## for debugging (set debug mark with pdb.set_trace() ) #import pdb # for math.ceil() import math # for shlex.shlex() (to parse answers from the NETIO 230A) import shlex # for errno codes (cf. ) import errno import time ### for date.today() #from datetime import date from datetime import datetime TELNET_LINE_ENDING = "\r\n" TELNET_SOCKET_TIMEOUT = 5 INITIAL_WAIT_FOR_OTHER_REQUEST = 0.013 # 13 ms to wait for other requests to terminate (later requests use the mean request time) #ANTI_FLOODING_WAIT = 0.001 # wait 1 ms before sending the next request (after having received the last response) ANTI_FLOODING_WAIT = 0.0 MAX_NUMBER_OF_REQUESTS_BEFORE_RECONNECT = 500 class netio230a(object): """netio230a is the basic class that you want to instantiate when communicating with the Koukaam NETIO 230A. It can handle the raw TCP socket connection and helps you send the commands to switch on / off powerSockets etc.""" def __init__(self, host, username, password, secureLogin=False, customTCPPort=23): """netio230a constructor: set up an instance of netio230a by giving: host the hostname of the NETIO-230A (may be in the form of something.dyndns.org or 192.168.1.2) username the username you want to use to authenticate against the NETIO-230A password the password (that belongs to username) secureLogin bool value specifying whether to use a hashed or a cleartext login. True is hightly recommended for insecure networks! customTCPPort integer specifying which port to connect to, defaul: 23 (NETIO-230A must be reachable via KSHELL/telnet via hostname:customTCPPort) """ self.logging = False self.__pending_request = False self.__relogin_try = False self.mean_request_time = INITIAL_WAIT_FOR_OTHER_REQUEST self.number_of_sent_requests = 0 self.__last_request_received = time.time() self.__host = host self.__username = username self.__password = password self.__secureLogin = secureLogin self.__tcp_port = customTCPPort self.__bufsize = 1024 self.__power_sockets = [ PowerSocket() for i in range(4) ] self.__create_socket_and_login() def __create_socket_and_login(self, relogin_try=False): # create a TCP/IP socket self.__s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.__s.settimeout(TELNET_SOCKET_TIMEOUT) self.__login(relogin_try) def __login(self, relogin_try=False): """Login to the server using the credentials given to the constructor. Note that this is a private method called by the constructor (so all connection details are set already).""" # connect to the server try: self.__s.connect((self.__host, self.__tcp_port)) # wait for the answer data = self.__receive() except StandardError, error: if type(error) == socket.timeout: raise NameError("Timeout while connecting to " + self.__host) #print("There was a timeout") elif type(error) == socket.gaierror or type(error) == socket.error and error.errno == errno.ENETUNREACH: raise NameError("Unable to understand the host you gave: %s. Please provide a correct IP address or domain name." % self.__host) elif type(error) == socket.error: if error.errno == errno.ECONNREFUSED: raise NameError("The connection was refused by the remote host. Possible errors: wrong IP or wrong TCP port given or the telnet server on the NETIO-230A crashed.") elif error.errno == errno.EHOSTUNREACH: raise NameError("There is no route to the host given: " + self.__host) elif error.errno == errno.ECONNRESET: raise NameError("The connection was reset by the device. This is usually the case when you still have another network socket connected to the device. It may also be the case when the telnet server on the device crashed. In this case reboot the device (if possible & sensible).") # in any other case just hand on the risen error: raise error except Exception, error: raise error # The answer should be in the form "100 HELLO E675DDA5" # where the last eight letters are random hexcode used to hash the password if self.__reSearch("^100 HELLO [0-9A-F]{8}"+TELNET_LINE_ENDING+"$", data) == None and \ self.__reSearch("^100 HELLO [0-9A-F]{8} - KSHELL V1.1"+TELNET_LINE_ENDING+"$", data) == None and \ self.__reSearch("^100 HELLO [0-9A-F]{8} - KSHELL V1.2"+TELNET_LINE_ENDING+"$", data) == None : raise NameError("Error while connecting: Not received a \"100 HELLO ... signal from the remote device. Maybe not a NET-IO 230A?") if self.__secureLogin: m = hashlib.md5() hash=str(data).split(" ")[2] msg=self.__username + self.__password + hash m.update(msg.encode("ascii")) loginString = "clogin " + self.__username + " " + m.hexdigest() + TELNET_LINE_ENDING else: # use the password in cleartext loginString = "login " + self.__username + " " + self.__password + TELNET_LINE_ENDING try: # send login string and wait for the answer response = self.__sendRequest(loginString, True, relogin_try) except NameError, error: self.disconnect() try: problem = str(error).partition('\n\n')[2] except: problem = "?" if problem.find("502 UNKNOWN COMMAND") != -1: raise NameError("Error while connecting: Login failed with message 502 UNKNOWN COMMAND. This is usually the case when the telnet server crashed. Reboot the NETIO-230A device to get it up running again.") elif problem.find("501 INVALID PARAMETER") != -1: raise NameError("Error while connecting: Login failed with message 501 INVALID PARAMETER. This is usually the case when the telnet server crashed. Reboot the NETIO-230A device to get it up running again.") else: raise NameError("Error while connecting: Login failed; " + str(error).partition('\n\n')[2]) except StandardError, error: self.disconnect() raise NameError("Error while connecting: Login failed; " + str(error)) def __reSearch(self, regexp, data): return re.search(regexp.encode("ascii"), data) def enable_logging(self, log_file): self.logging = True self.log_file = log_file try: self.log("Logging started on %s." % datetime.now().isoformat()) except StandardError, error: self.logging = True raise error def log(self, message, line_break=True): if self.logging: self.log_file.write("%s %s%s" % (datetime.now().isoformat(), message, ("\n" if line_break else "" )) ) def getPowerSocketList(self): """Sends request to the NETIO 230A to ask for the power socket status. Returns string (4 chars long) specifying which power sockets are switched on/off. Each char is representing the power status of one power socket: 0/1 For example: "1001" (power socket 1 and power socket 4 are on, all others off)""" return self.__sendRequest("port list") def getPowerSocketSetup(self,power_socket): """Sends request to the NETIO 230A to ask for the setup of the power socket given as parameter. returns the "port setup" string as specifyed by Koukaam""" return self.__sendRequest("port setup " + str(power_socket+1)) def setPowerSocketPower(self,power_socket,switchOn=False): """setPowerSocketPower(power_socket,switchOn=False): method to set the power status of the power socket specified by the argument power_socket to the bool argument switchOn returns nothing""" # the type conversion of switchOn ensures that the values are either "0" or "1": self.__sendRequest("port " + str(power_socket) + " " + str(int(bool(int(switchOn)))) ) def togglePowerSocketPower(self,power_socket): """togglePowerSocketPower(power_socket): toggles the power status of power socket specified by the (one based) argument power_socket. returns a boolean indicating the new status""" previous_state = self.getPowerSocket(power_socket-1).getPowerOn() # the getPowerSocket() function has a zero based argument! therefore -1 self.setPowerSocketPower(power_socket, not previous_state) return not previous_state def setPowerSocketTempInterrupt(self,power_socket): self.__sendRequest("port " + str(int(power_socket)) + " int" ) def setPowerSocketManualMode(self,power_socket,manualMode=True): self.__sendRequest("port " + str(int(power_socket)) + " manual") def getFirmwareVersion(self): return self.__sendRequest("version") def getDeviceAlias(self): return self.__sendRequest("alias") def setDeviceAlias(self,alias = "netio230a"): self.__sendRequest("alias " + alias) # this command is operation-safe: it does not switch the power sockets on/off during reboot of the NETIO 230A def reboot(self): response = self.__sendRequest("reboot",False) if re.search("^120 Rebooting", response) != None: time.sleep(.05) # no reboot if disconnecting too soon def getWatchdogSettings(self,power_socket): return self.__sendRequest("port wd " + str(power_socket)) def getNetworkSettings(self): return self.__sendRequest("system eth") def setNetworkSettings(self,dhcpMode=False,deviceIP="192.168.1.2",subnetMask="255.255.255.0",gatewayIP="192.168.1.1"): if dhcpMode: self.__sendRequest("system eth dhcp") else: self.__sendRequest("system eth manual " + deviceIP + " " + subnetMask + " " + gatewayIP) def getDnsServer(self): return self.__sendRequest("system dns") def setDnsServer(self,dnsServer="192.168.1.1"): self.__sendRequest("system dns " + dnsServer) def getSystemDiscoverableUsingTool(self): if self.__sendRequest("system discover") == "enable": return True else: return False def setSystemDiscoverableUsingTool(self,setDiscoverable=True): if setDiscoverable: command = "enable" else: command = "disable" self.__sendRequest("system discover " + command) def setSwitchDelay(self,seconds): return self.__sendRequest("system swdelay " + str(int(math.ceil(seconds*10.0)))) def getSwitchDelay(self): return int(self.__sendRequest("system swdelay"))/10.0 def getSntpSettings(self): return self.__sendRequest("system sntp") def setSntpSettings(self,enable=True,sntpServer="time.nist.gov"): if enable: command = "enable" else: command = "disable" self.__sendRequest("system sntp " + " " + sntpServer) def setSystemTime(self,dt): self.__sendRequest("system time " + dt.strftime("%Y/%m/%d,%H:%M:%S") ) def getSystemTime(self): """getSystemTime() returns a datetime object""" formatedTimestring = self.__sendRequest("system time") date = formatedTimestring.partition(",")[0].split("/") time = formatedTimestring.partition(",")[2].split(":") return datetime(int(date[0]), int(date[1]), int(date[2]), int(time[0]), int(time[1]), int(time[2])) def getSystemTimezone(self): """getSystemTimezone() returns the timezone offset from UTC in hours of the NETIO-230A.""" return float(int(self.__sendRequest("system timezone")))/3600.0 def setSystemTimezone(self,hoursOffset): """setSystemTimezone(hoursOffset) sets the timezone offset from UTC in hours of the NETIO-230A.""" self.__sendRequest("system timezone " + str(math.ceil(hoursOffset*3600.0))) def setPowerSocket(self,number,power_socket): self.__power_sockets[number] = power_socket def getPowerSocket(self,number): self.updatePowerSocketsStatus() return self.__power_sockets[number] def getAllPowerSockets(self): self.updatePowerSocketsStatus() return self.__power_sockets def updatePowerSocketsStatus(self): power_sockets = [] powerOnStatus = self.getPowerSocketList() for i in range(4): status_splitter = shlex.shlex(self.getPowerSocketSetup(i).encode('ascii'), posix=True) status_splitter.whitespace_split = True power_sockets.append( list(status_splitter) ) self.__power_sockets[i].setName(power_sockets[i][0]) self.__power_sockets[i].setPowerOnAfterPowerLoss(bool(int(power_sockets[i][3]))) self.__power_sockets[i].setPowerOn(bool(int(powerOnStatus[i]))) self.__power_sockets[i].setManualMode(power_sockets[i][1]=="manual") self.__power_sockets[i].setInterruptDelay(int(power_sockets[i][2])) #still missing: setWatchdogOn # generic method to send requests to the NET-IO 230A and checking the response def __sendRequest(self,request,complainIfAnswerNot250=True, relogin_try=False): counter = 0 # in this loop we want to avoid errors for concurrent requests (from different threads etc.) while self.__pending_request and not relogin_try: wait_time = self.mean_request_time*.5 time.sleep(wait_time) counter += 1 print("concurrent action for request: %s" % request) self.log("Waiting for an other request to finish. Average time for processes to finish is %.6f after a total number of %d requests." % (self.mean_request_time, self.number_of_sent_requests) ) if counter * wait_time >= 3 * (self.mean_request_time + ANTI_FLOODING_WAIT): # If we waited long enough, we give up. raise NameError("Sorry, some other process is sending a request you cannot send yours now.") # set the lock for our request (and therefore block other requests for now) self.__pending_request = True if ANTI_FLOODING_WAIT > 0.0005 and time.time()-self.__last_request_received < ANTI_FLOODING_WAIT: time.sleep(ANTI_FLOODING_WAIT-(time.time()-self.__last_request_received)) if MAX_NUMBER_OF_REQUESTS_BEFORE_RECONNECT > 0 and (self.number_of_sent_requests+1) % MAX_NUMBER_OF_REQUESTS_BEFORE_RECONNECT == 0: print("%d requests made, reconnecting..." % MAX_NUMBER_OF_REQUESTS_BEFORE_RECONNECT) self.number_of_sent_requests += 1 self.disconnect() starting_time = time.time() try: self.__send(request.encode("ascii")+TELNET_LINE_ENDING.encode("ascii")) except Exception, error: self.log("first try to send the command failed: "+str(error)) try: self.__create_socket_and_login(True) self.__send(request.encode("ascii")+TELNET_LINE_ENDING.encode("ascii")) except StandardError, error: # handle Builtin exceptions self.__pending_request = False self.log("second try to send the command failed: "+str(error)) raise NameError("no connection possible or other exception: "+str(error)) except Exception, error: self.log("second try to send the command failed: "+str(error)) self.__pending_request = False try: data = self.__receive() except Exception, error: # maybe we should try to reconnect here too before giving up. self.log("trying to receive data failed: "+str(error)) self.__pending_request = False self.__s.close() if self.__reSearch("^250 ", data) == None and complainIfAnswerNot250: self.__pending_request = False raise NameError("Error while sending request: " + request + "\nresponse from NET-IO 230A is: " + data.replace(TELNET_LINE_ENDING,'')) else: data = data.decode("ascii") data = data.replace("250 ","").replace(TELNET_LINE_ENDING,"") self.mean_request_time = ( self.number_of_sent_requests*self.mean_request_time + (time.time()-starting_time) ) / (self.number_of_sent_requests + 1) self.number_of_sent_requests += 1 self.__last_request_received = time.time() self.__pending_request = False return data def disconnect(self): try: # send the quit command to the box (if we have an open connection): self.__send("quit".encode("ascii")+TELNET_LINE_ENDING.encode("ascii")) self.__receive() # should give 110 BYE except: pass # close the socket (if it is still open): self.__s.close() def __del__(self): self.disconnect() ### end of class netio230a ---------------- def __send(self, data): self.log(data, False) self.__s.send(data) def __receive(self): response = self.__s.recv(self.__bufsize) self.log(response, False) return response class PowerSocket(object): """ This is a class to represent the power sockets of the NETIO-230A. """ def __init__(self): self.__name = "" self.__manualMode = True # False means timer mode self.__powerOn = False self.__watchdogOn = False self.__interruptDelay = 2 def setManualMode(self,manualMode=True): self.__manualMode = manualMode def getManualMode(self): return self.__manualMode def setPowerOnAfterPowerLoss(self,powerOn=False): self.__powerOnAfterPowerLoss = powerOn def getPowerOnAfterPowerLoss(self): return self.__powerOnAfterPowerLoss def setTimerMode(self,timerMode): self.__manualMode = not timerMode def getTimerMode(self): return not self.__manualMode def setPowerOn(self,powerOn = False): self.__powerOn = powerOn def getPowerOn(self): return self.__powerOn def setName(self,newName): self.__name = newName def getName(self): return self.__name def setInterruptDelay(self,interruptDelay): self.__interruptDelay = interruptDelay def getInterruptDelay(self): return self.__interruptDelay def setWatchdogOn(self,watchdogOn): self.__watchdogOn = watchdogOn def getWatchdogOn(self): return self.__watchdogOn # ---------------------------------------------------------------- # logic and code to detect available NETIO-230A devices on the LAN import socket import threading import array import time import sys NETIO230A_UDP_DISCOVER_PORT = 4000 TIMEOUT=0.2 # should be enough. Usualy we get the answer in 4.6 ms DEVICE_NAME_TERMINATION = "\x00\x30\x30\x38\x30" # the request to ask for available NETIO-230A on the network (bytes sniffed using wireshark) DISCOVER_REQUEST = "PCEdit\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00" DISCOVER_REQUEST += "\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" DISCOVER_REQUEST += "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" # thread to run the UDP server that listens to answering NETIOs on your network class UDPintsockThread(threading.Thread): def __init__ (self,port,callback_for_found_devices): """ listens to answers from available NETIO-230A devices on the LAN and calls callback_for_found_devices([deviceName, ip, sm, gw, mac, answerTime]) """ threading.Thread.__init__(self) self.__port = port self.__callback = callback_for_found_devices self.__startTime = time.time() def run(self): addr = ('', self.__port) # Create socket and bind to address UDPinsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) UDPinsock.bind(addr) # will listen for three seconds to your network UDPinsock.settimeout(TIMEOUT) while True: try: # Receive messages data, addr = UDPinsock.recvfrom(1024) # keep timestamp of arriving package answerTime=time.time() except: #print "server timeout" break # check if we found a NETIO-230A if data.find("IPCam") == 0 and len(data)== 61: # documentation of data is found on http://wiki.github.com/pklaus/netio230a/netdiscover-protocol deviceName = data[38:data.find(DEVICE_NAME_TERMINATION)] data = array.array('B', data) ip = [] for n in range(0, 4): ip.append(data[10+n]) mac = [0,0,0,0,0,0] for n in range(0, 6): mac[n] = data[14+n] sm = [] for n in range(0, 4): sm.append(data[20+n]) gw = [] for n in range(0, 4): gw.append(data[27+n]) device = [deviceName, ip, sm, gw, mac, (answerTime-self.__startTime)*1000] self.__callback(device) UDPinsock.close() def discover_netio230a_devices(callback_for_found_devices): dest = ('',NETIO230A_UDP_DISCOVER_PORT) #dest = ('255.255.255.255',NETIO230A_UDP_DISCOVER_PORT) myUDPintsockThread = UDPintsockThread(NETIO230A_UDP_DISCOVER_PORT,callback_for_found_devices) myUDPintsockThread.start() # send on all interfaces of the computer: # cf. last lines of the comment for interface in all_interfaces(): UDPoutsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # to allow broadcast communication: UDPoutsock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) host = socket.inet_ntoa(interface[1]) UDPoutsock.bind((host, 0)) # send UDP broadcast: UDPoutsock.sendto(DISCOVER_REQUEST, dest) myUDPintsockThread.join() ## http://code.activestate.com/recipes/439093/#c1 try: import fcntl except: pass import struct import array def all_interfaces(): max_possible = 128 # arbitrary. raise if needed. bytes = max_possible * 32 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) names = array.array('B', '\0' * bytes) try: outbytes = struct.unpack('iL', fcntl.ioctl( s.fileno(), 0x8912, # SIOCGIFCONF struct.pack('iL', bytes, names.buffer_info()[0]) ))[0] except: return [] namestr = names.tostring() lst = [] for i in range(0, outbytes, 40): name = namestr[i:i+16].split('\0', 1)[0] ip = namestr[i+20:i+24] lst.append((name, ip)) return lst all_devices=[] def device_detected_callback(device): global all_devices all_devices.append(device) # if any software module wants to get all found devices with one call (blocking) then this function can be used: def get_all_detected_devices(): global all_devices all_devices = [] discover_netio230a_devices(device_detected_callback) return all_devices netio230a-1.0.1/configuration.py0000755000401300017500000000601611350245524017016 0ustar debalancedebalance#!/usr/bin/env python # -*- encoding: UTF8 -*- # author: Philipp Klaus, philipp.l.klaus AT web.de # This file is part of netio230a. # # netio230a is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # netio230a is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with netio230a. If not, see . """ This module is made to simplify the process of saving and retrieving saved credentials from previous connections for the other modules of the project. """ import json from datetime import datetime import os CONFIGURATION_FILE = os.path.expanduser("~/.netio230a/connections.json") LOG_FILE = os.path.expanduser("~/.netio230a/netio230a.py.log") REMOVE = -1 UPDATE = 2 def changeConfiguration(action, devicename, host, port, username, password): try: os.makedirs(os.path.split(CONFIGURATION_FILE)[0]) except StandardError, error: pass try: # try to get stored configuration (if it exists) configuration = getConfiguration() except StandardError, error: # or create an empty list for the new configuration configuration = [] try: old_device, new_device = None, None for device in configuration: if device[0] == devicename and device[1] == host and device[2] == port and device[3] == username: old_device = device new_device = [devicename, host, port, username, password, datetime.now().isoformat()] if action == UPDATE: if new_device == None and old_device == None: configuration.append([devicename, host, port, username, password, datetime.now().isoformat()]) else: configuration.remove(old_device) configuration.append(new_device) elif action == REMOVE: if old_device != None: configuration.remove(old_device) configuration.sort(key=sort_configuration) configuration.reverse() outfile = open(CONFIGURATION_FILE,'w') json.dump(configuration,outfile) outfile.close() return True except StandardError, error: print str(error) return False def sort_configuration(config_row): return config_row[5] def getConfiguration(): try: infile = open(CONFIGURATION_FILE,'r') configuration = json.load(infile) infile.close() return configuration except StandardError, error: return [] if __name__ == "__main__": print("You have %d connections stored in your configuration file." % len(getConfiguration()) ) netio230a-1.0.1/example.PyS60.py0000644000401300017500000000625411350245524016463 0ustar debalancedebalance#!/usr/bin/env python # -*- encoding: UTF8 -*- # Author: Philipp Klaus, philipp.l.klaus AT web.de # This file is part of netio230a. # # netio230a is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # netio230a is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with netio230a. If not, see . # This is a program written for the Python for # S60 platform (Nokia Symbian mobile phones). # It is tested on a Nokia N95. import sys sys.path.append('e:\\Python') import netio230a import appuifw import e32 host = "your.dyndns.org" tcp_port = 23 pw = "your chosen password" appuifw.app.title = u"NETIO 230A" appuifw.note(u"Welcome to the Koukaam NETIO 230A control.", 'info') app_lock = e32.Ao_lock() messagecanvas = appuifw.Text() try: netio = netio230a.netio230a(host, "admin", pw, True, tcp_port) except: netio=None messagecanvas.set(u"could not connect") def exit_key_handler(): app_lock.signal() def switch_power_socket(): global netio power_socket_to_change = 0 while int(power_socket_to_change) < 1 or power_socket_to_change > 4: power_socket_to_change = appuifw.query(u"Power socket to switch (between 1 and 4):", 'number') if power_socket_to_change == None: return states = [u"On", u"Off"] state = appuifw.popup_menu(states, u"new status for power socket %s:"% power_socket_to_change) if power_socket_to_change == None or state == None: return if state == 1: power_socket_on = False elif state == 0: power_socket_on = True netio.setPowerSocketPower(int(power_socket_to_change),power_socket_on) updateStatus() #def subitem1(): # messagecanvas.set(u'Now first subitem was selected') def update_status(): global netio power_sockets = netio.getPowerSocketList() messagecanvas.set( u"" ) messagecanvas.style = appuifw.STYLE_BOLD messagecanvas.add(u"Power Status:\n\n") messagecanvas.style = 0 messagecanvas.add(u"port 1: %s\nport 2: %s\nport 3: %s\nport 4: %s" % (power_sockets[0],power_sockets[1],power_sockets[2],power_sockets[3] )) def main(): global netio appuifw.app.screen='large' appuifw.app.body = messagecanvas if netio == None: # wait 3 seconds: e32.ao_sleep(3) #appuifw.app.set_exit() # this completely closes python return #appuifw.app.menu = [(u"Submenu 1", ((u"sub item 1", subitem1), (u"sub item 2", subitem2))), (u"Exit", exit_key_handler)] appuifw.app.menu = [(u"Switch Power Socket", switch_power_socket), (u"Refresh Status", update_status), (u"Exit", exit_key_handler)] updateStatus() appuifw.app.exit_key_handler = exit_key_handler app_lock.wait() netio = None if __name__ == '__main__': main() netio230a-1.0.1/COPYING0000644000401300017500000007733111350245524014635 0ustar debalancedebalance GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS netio230a-1.0.1/example.reboot.py0000755000401300017500000000264111350245524017073 0ustar debalancedebalance#!/usr/bin/env python # -*- encoding: UTF8 -*- # Author: Philipp Klaus, philipp.l.klaus AT web.de # This file is part of netio230a. # # netio230a is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # netio230a is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with netio230a. If not, see . # example how to use the netio230a class ## import the netio230a class: import netio230a ## for sys.exit(1) import sys host = "192.168.1.2" pw = "your choosen password" tcp_port = 23 def main(): try: netio = netio230a.netio230a(host, "admin", pw, True, tcp_port) except StandardError: print("could not connect") sys.exit(1) netio.reboot() netio = None # print response print "\n--------- successfully queried the Koukaam NETIO 230A ---------" print "rebooting" print "---------------------------------------------------------------- \n" if __name__ == '__main__': main()