├── .gitignore ├── LICENSE ├── MANIFEST.in ├── README.md ├── pykush ├── __init__.py └── pykush.py └── setup.py /.gitignore: -------------------------------------------------------------------------------- 1 | #### joe made this: http://goel.io/joe 2 | 3 | #####=== User ===##### 4 | 5 | # PyPI rst README can be ignored 6 | README 7 | 8 | # dist can be ignored 9 | /dist 10 | 11 | #####=== Autotools ===##### 12 | 13 | # http://www.gnu.org/software/automake 14 | 15 | Makefile.in 16 | 17 | # http://www.gnu.org/software/autoconf 18 | 19 | /autom4te.cache 20 | /aclocal.m4 21 | /compile 22 | /configure 23 | /depcomp 24 | /install-sh 25 | /missing 26 | /stamp-h1 27 | 28 | #####=== C ===##### 29 | 30 | # Object files 31 | *.o 32 | *.ko 33 | *.obj 34 | *.elf 35 | 36 | # Precompiled Headers 37 | *.gch 38 | *.pch 39 | 40 | # Libraries 41 | *.lib 42 | *.a 43 | *.la 44 | *.lo 45 | 46 | # Shared objects (inc. Windows DLLs) 47 | *.dll 48 | *.so 49 | *.so.* 50 | *.dylib 51 | 52 | # Executables 53 | *.exe 54 | *.out 55 | *.app 56 | *.i*86 57 | *.x86_64 58 | *.hex 59 | 60 | #####=== C++ ===##### 61 | 62 | # Compiled Object files 63 | *.slo 64 | *.lo 65 | *.o 66 | *.obj 67 | 68 | # Precompiled Headers 69 | *.gch 70 | *.pch 71 | 72 | # Compiled Dynamic libraries 73 | *.so 74 | *.dylib 75 | *.dll 76 | 77 | # Fortran module files 78 | *.mod 79 | 80 | # Compiled Static libraries 81 | *.lai 82 | *.la 83 | *.a 84 | *.lib 85 | 86 | # Executables 87 | *.exe 88 | *.out 89 | *.app 90 | 91 | #####=== CMake ===##### 92 | 93 | CMakeCache.txt 94 | CMakeFiles 95 | Makefile 96 | cmake_install.cmake 97 | install_manifest.txt 98 | 99 | #####=== IPythonNotebook ===##### 100 | # Temporary data 101 | .ipynb_checkpoints/ 102 | 103 | #####=== JetBrains ===##### 104 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm 105 | 106 | *.iml 107 | 108 | ## Directory-based project format: 109 | .idea/ 110 | # if you remove the above rule, at least ignore the following: 111 | 112 | # User-specific stuff: 113 | # .idea/workspace.xml 114 | # .idea/tasks.xml 115 | # .idea/dictionaries 116 | 117 | # Sensitive or high-churn files: 118 | # .idea/dataSources.ids 119 | # .idea/dataSources.xml 120 | # .idea/sqlDataSources.xml 121 | # .idea/dynamic.xml 122 | # .idea/uiDesigner.xml 123 | 124 | # Gradle: 125 | # .idea/gradle.xml 126 | # .idea/libraries 127 | 128 | # Mongo Explorer plugin: 129 | # .idea/mongoSettings.xml 130 | 131 | ## File-based project format: 132 | *.ipr 133 | *.iws 134 | 135 | ## Plugin-specific files: 136 | 137 | # IntelliJ 138 | out/ 139 | 140 | # mpeltonen/sbt-idea plugin 141 | .idea_modules/ 142 | 143 | # JIRA plugin 144 | atlassian-ide-plugin.xml 145 | 146 | # Crashlytics plugin (for Android Studio and IntelliJ) 147 | com_crashlytics_export_strings.xml 148 | crashlytics.properties 149 | crashlytics-build.properties 150 | 151 | #####=== Linux ===##### 152 | *~ 153 | 154 | # KDE directory preferences 155 | .directory 156 | 157 | # Linux trash folder which might appear on any partition or disk 158 | .Trash-* 159 | 160 | #####=== Python ===##### 161 | 162 | # Byte-compiled / optimized / DLL files 163 | __pycache__/ 164 | *.py[cod] 165 | 166 | # C extensions 167 | *.so 168 | 169 | # Distribution / packaging 170 | .Python 171 | env/ 172 | build/ 173 | develop-eggs/ 174 | dist/ 175 | downloads/ 176 | eggs/ 177 | lib/ 178 | lib64/ 179 | parts/ 180 | sdist/ 181 | var/ 182 | *.egg-info/ 183 | .installed.cfg 184 | *.egg 185 | 186 | # PyInstaller 187 | # Usually these files are written by a python script from a template 188 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 189 | *.manifest 190 | *.spec 191 | 192 | # Installer logs 193 | pip-log.txt 194 | pip-delete-this-directory.txt 195 | 196 | # Unit test / coverage reports 197 | htmlcov/ 198 | .tox/ 199 | .coverage 200 | .cache 201 | nosetests.xml 202 | coverage.xml 203 | 204 | # Translations 205 | *.mo 206 | *.pot 207 | 208 | # Django stuff: 209 | *.log 210 | 211 | # Sphinx documentation 212 | docs/_build/ 213 | 214 | # PyBuilder 215 | target/ 216 | 217 | #####=== SublimeText ===##### 218 | # cache files for sublime text 219 | *.tmlanguage.cache 220 | *.tmPreferences.cache 221 | *.stTheme.cache 222 | 223 | # workspace files are user-specific 224 | *.sublime-workspace 225 | 226 | # project files should be checked into the repository, unless a significant 227 | # proportion of contributors will probably not be using SublimeText 228 | # *.sublime-project 229 | 230 | # sftp configuration file 231 | sftp-config.json 232 | 233 | #####=== Vim ===##### 234 | [._]*.s[a-w][a-z] 235 | [._]s[a-w][a-z] 236 | *.un~ 237 | Session.vim 238 | .netrwhist 239 | *~ 240 | 241 | .python-version 242 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2013-2015 Yepkit Lda and other contributors 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include README.md 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # pykush 2 | ``` 3 | __ __ _ _ _ 4 | \ \ / /__ _ __ | | _(_) |_ 5 | \ V / _ \ '_ \| |/ / | __| 6 | | | __/ |_) | <| | |_ 7 | |_|\___| .__/|_|\_\_|\__| 8 | |_| 9 | ``` 10 | **[Yepkit](http://www.yepkit.com/) [YKUSH](https://www.yepkit.com/products/ykush) Python library and command line tool** 11 | 12 | Provides library and command line functionality for communicating with a [YKUSH](https://www.yepkit.com/products/ykush) device over USB. 13 | 14 | Thanks to the developers and maintainers of the following projects among others: 15 | - [HIDAPI](https://github.com/signal11/hidapi) multi-platform library 16 | - Python [hidapi](https://pypi.python.org/pypi/hidapi) wrapper module 17 | - Python [hidapi-cffi](https://pypi.python.org/pypi/hidapi-cffi) wrapper module 18 | Any of the above python wrappers are currently supported. 19 | 20 | ## Features 21 | 22 | - Easy to [use](https://github.com/Yepkit/pykush#usage) 23 | - Written to support [YKUSH]((https://www.yepkit.com/products/ykush)), the Yepkit USB Switchable Hub 24 | - Open-source, please be our guest to collaborate 25 | - Current development version supports both Python 2 and 3 26 | - Works on Linux, Windows and Mac 27 | 28 | ## Requirements 29 | 30 | - A Linux, Windows or Mac (OS X) system 31 | - A [YKUSH](https://www.yepkit.com/products/ykush) device 32 | - A recent [Python 2 >=2.7.9 or Python 3 >=3.4](https://www.python.org/downloads/) installed 33 | - [hidapi](https://pypi.python.org/pypi/hidapi) or [hidapi-cffi](https://pypi.python.org/pypi/hidapi-cffi) module installed 34 | 35 | ## Installation 36 | 37 | If you are in a hurry and just need a console application you can give our Pyinstaller bundled executable a try: 38 | - [Windows](https://github.com/Yepkit/pykush/releases/download/v0.3.6/windows.zip) executable, Windows XP or newer 39 | - [macOS](https://github.com/Yepkit/pykush/releases/download/v0.3.6/macos.zip) executable, El Capitan or newer 40 | - [Linux x86_64](https://github.com/Yepkit/pykush/releases/download/v0.3.6/linux64.zip), kernel 2.6 or newer 41 | - [Linux i386](https://github.com/Yepkit/pykush/releases/download/v0.3.6/linux32.zip), kernel 2.6 or newer 42 | 43 | Download the executable corresponding to your platform and run it from a terminal window. 44 | Also remember to authorize execution on Linux or macOS systems: 45 | ```bash 46 | $ chown u+x pykush 47 | $ ./pykush -l 48 | ``` 49 | 50 | ### From source 51 | 52 | Anonymous: 53 | ```bash 54 | $ git clone https://github.com/Yepkit/pykush 55 | $ cd pykush/ 56 | $ python setup.py install 57 | ``` 58 | 59 | Git: 60 | ```bash 61 | $ git clone git@github.com:Yepkit/pykush 62 | $ cd pykush/ 63 | $ python setup.py install 64 | ``` 65 | 66 | ### With python pip 67 | 68 | ```bash 69 | $ pip install yepkit-pykush 70 | ``` 71 | 72 | ## Usage 73 | 74 | ### Basic command line usage 75 | 76 | ```bash 77 | $ python pykush.py -h 78 | usage: pykush.py [-h] [-s SERIAL] 79 | (-l | -u [UP [UP ...]] | -d [DOWN [DOWN ...]] | -r READ | -w WRITE WRITE | -p) 80 | 81 | Yepkit YKUSH command line tool. 82 | 83 | optional arguments: 84 | -h, --help show this help message and exit 85 | -s SERIAL, --serial SERIAL 86 | specify the serial number string of the YKUSH to be 87 | listed or managed 88 | -l, --list list YKUSH devices 89 | -u [UP [UP ...]], --up [UP [UP ...]] 90 | the downstream port numbers to power up, none means 91 | all 92 | -d [DOWN [DOWN ...]], --down [DOWN [DOWN ...]] 93 | the downstream port numbers to power down, none means 94 | all 95 | -r READ, --read READ the GPIO pin to read from 96 | -w WRITE WRITE, --write WRITE WRITE 97 | the GPIO pin to write to 98 | -p, --persist make the current running configuration persistent 99 | across reboots (only supported on devices with 100 | firmware v2.0 and above) 101 | 102 | $ python pykush.py -l 103 | listing YKUSH family devices 104 | found a YKUSH release 2 device with serial number YK20001 105 | system device path 0001:000a:00, vendor id 0x04d8, product id 0xf2f7 106 | the device is running a v1.2 firmware and has 3 downstream ports 107 | downstream running power states, port 1 to 3: UP, UP, UP 108 | 109 | $ python pykush.py -d 1 2 110 | managing YKUSH family devices 111 | found a YKUSH release 2 device with serial number YK20001 112 | system device path 0001:000a:00, vendor id 0x04d8, product id 0xf2f7 113 | the device is running a v1.2 firmware and has 3 downstream ports 114 | powering DOWN port 1... done 115 | powering DOWN port 2... done 116 | ``` 117 | 118 | ### Basic module programming usage 119 | ```bash 120 | $ python 121 | >>> import pykush.pykush as pykush 122 | >>> yk = pykush.YKUSH() 123 | >>> yk.set_allports_state_up() 124 | True 125 | >>> yk.get_downstream_port_count() 126 | 3 127 | >>> yk.set_port_state(2, pykush.YKUSH_PORT_STATE_DOWN) 128 | True 129 | >>> yk.get_port_state(2) 130 | 0 131 | >>> yk.get_port_state(2) == pykush.YKUSH_PORT_STATE_DOWN 132 | True 133 | >>> 134 | ``` 135 | 136 | ## Disclaimer 137 | 138 | The module is already usable in the limited scope we tested but it is still in a alpha stage. 139 | 140 | ## Contributing 141 | 142 | ### Bug Reports 143 | 144 | If you find a problem, please submit a bug report on [issue tracker](https://github.com/Yepkit/pykush/issues). 145 | -------------------------------------------------------------------------------- /pykush/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Yepkit/pykush/de54f8f5519db76b7ec7dbe0ac4a60d840c8fc94/pykush/__init__.py -------------------------------------------------------------------------------- /pykush/pykush.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding: utf-8 3 | """ 4 | __ __ _ _ _ 5 | \ \ / /__ _ __ | | _(_) |_ 6 | \ V / _ \ '_ \| |/ / | __| 7 | | | __/ |_) | <| | |_ 8 | |_|\___| .__/|_|\_\_|\__| 9 | |_| http://yepkit.com/ 10 | 11 | Yepkit YKUSH Python API and command line tool 12 | 13 | This application supports hidapi and hidapi-cffi, please choose 14 | according to your preference: 15 | https://pypi.python.org/pypi/hidapi 16 | or 17 | https://pypi.python.org/pypi/hidapi-cffi 18 | 19 | We invite you to visit the YKUSH product page for more information: 20 | https://www.yepkit.com/products/ykush 21 | 22 | Copyright 2015, 2013 Yepkit Lda and other contributors 23 | Released under the MIT license, please read the file LICENSE.txt 24 | https://github.com/Yepkit/pykush/blob/master/LICENSE 25 | 26 | Date: 2016-10-01 27 | 28 | # added YKUSHXS By Alber Saber 29 | # Date: 2019-01-31 30 | 31 | Command line usage: 32 | 33 | usage: pykush_hidapi.py [-h] [-s SERIAL] 34 | (-l | -u [UP [UP ...]] | -d [DOWN [DOWN ...]] | -p) 35 | 36 | Yepkit YKUSH command line tool. 37 | 38 | optional arguments: 39 | -h, --help show this help message and exit 40 | -s SERIAL, --serial SERIAL 41 | specify the serial number string of the YKUSH to be 42 | listed or managed 43 | -l, --list list YKUSH devices 44 | -u [UP [UP ...]], --up [UP [UP ...]] 45 | the downstream port numbers to power up, none means 46 | all 47 | -d [DOWN [DOWN ...]], --down [DOWN [DOWN ...]] 48 | the downstream port numbers to power down, none 49 | means all 50 | -p, --persist make the current running configuration persistent 51 | across reboots (only supported on devices with 52 | firmware v2.0 and above) 53 | 54 | Command line sample usage: 55 | 56 | $ python pykush.py -l 57 | listing YKUSH family devices 58 | found a YKUSH release 2 device with serial number YK20001 59 | system device path 0001:000a:00, vendor id 0x04d8, product id 0xf2f7 60 | the device is running a v1.2 firmware and has 3 downstream ports 61 | downstream running power states, port 1 to 3: UP, UP, UP 62 | 63 | $ python pykush.py -d 1 2 64 | managing YKUSH family devices 65 | found a YKUSH release 2 device with serial number YK20001 66 | system device path 0001:000a:00, vendor id 0x04d8, product id 0xf2f7 67 | the device is running a v1.2 firmware and has 3 downstream ports 68 | powering DOWN port 1... done 69 | powering DOWN port 2... done 70 | 71 | Note: depending on your system you may need priviledge elevation to access 72 | the USB device: 73 | $ sudo python pykush.py -l 74 | this can be avoided if you configure your machine to allow the 75 | access, for more information please visit: 76 | https://github.com/Yepkit/pykush 77 | 78 | Module sample usage: 79 | 80 | $ python 81 | >>> import pykush 82 | >>> yk = pykush.YKUSH() 83 | >>> yk.set_allports_state_up() 84 | True 85 | >>> yk.get_downstream_port_count() 86 | 3 87 | >>> yk.set_port_state(2, pykush.YKUSH_PORT_STATE_DOWN) 88 | True 89 | >>> yk.get_port_state(2) 90 | 0 91 | >>> yk.get_port_state(2) == pykush.YKUSH_PORT_STATE_DOWN 92 | True 93 | >>> 94 | 95 | Notes: 96 | * None 97 | 98 | Alber 31-01-2019 00:45am 99 | 100 | YkushXs : 0xF0CD 101 | Ykush3 : 0xF11B 102 | Ykush2 : 0xEFED Legacy 0x0042 103 | Ykush : 0xF2F7 Legacy 0x0042 104 | 105 | Sugest : 106 | 1.1.Add 0xf0cd in YKUSH_USB_PID_LIST[] ,and YKUSHXS mode 107 | 2.1.Delete 0xf0cd in YKUSH_USB_PID_BL_LIST[] 108 | 2.2.Add PreValue 0xffff 109 | 3.1.Find YKUSH_USB_PID_BL_LIST[] then check it in or == 110 | -incase of YKUSH_USB_PID_BL_LIST[] have only one value for bootloader mode, i suggest to add a prevalue 111 | 3.2.Add device is 0xf0cd 112 | 3.3.check if 0xf0cd:YKUSHXS Make it have 1 port 113 | For 1.get_downstream_port_count() 114 | 2.’has %i downstream’ 115 | 3.get_allports_state() 116 | 4.’powering UP the downstream port’ 117 | 5.’powering DOWN the downstream port’ 118 | 4.test 119 | 4.1.test (3.2).Test and End… ;) 120 | 121 | New : 122 | YKUSHXS 123 | YKUSH_USB_PID_LIST = (0x0042, 0xf2f7, 0xf11b, 0xf0cd) 124 | # YKUSH PIDs when in bootloader mode: YKUSH3, PreValue!! 125 | YKUSH_USB_PID_BL_LIST = (0xf11c, 0xffff) 126 | 127 | """ 128 | 129 | from __future__ import unicode_literals 130 | from __future__ import print_function 131 | import sys 132 | import struct 133 | _usingHid = False 134 | try: 135 | import hid 136 | _usingHid = True 137 | except (ImportError, OSError): 138 | try: 139 | import hidapi 140 | except (ImportError, OSError): 141 | print('Please ensure that you have hidapi or hidapi-cffi installed,') 142 | print('any of them are supported.') 143 | print('If you are confortable with Python, it should be as simple as:') 144 | print('\tpip install --user hidapi') 145 | print('For more information please visit:') 146 | print('\thttps://github.com/Yepkit/pykush') 147 | raise 148 | 149 | __version__ = '0.3.6' 150 | 151 | # YKUSH device USB VID 152 | YKUSH_USB_VID = 0x04d8 153 | # YKUSH PIDs when in normal operation mode: YKUSH beta, YKUSH, YKUSH3, YKUSHXS (Alber1.1) 154 | YKUSH_USB_PID_LIST = (0x0042, 0xf2f7, 0xf11b, 0xf0cd) 155 | # YKUSH PIDs when in bootloader mode: YKUSH3!!, ABCD (Alber2.1.2) 156 | YKUSH_USB_PID_BL_LIST = (0xf11c, 0xffff) 157 | 158 | # YKUSH device USB comm declarations 159 | YKUSH_USB_TIMEOUT = 1000 # timeout in ms 160 | YKUSH_USB_PACKET_SIZE = 64 161 | YKUSH_USB_PACKET_PAYLOAD_SIZE = 20 162 | 163 | # YKUSH device protocol status declarations 164 | YKUSH_PROTO_OK_STATUS = 1 165 | 166 | # YKUSH port state meaning declarations 167 | YKUSH_PORT_STATE_UP = 1 168 | YKUSH_PORT_STATE_DOWN = 0 169 | YKUSH_PORT_STATE_ERROR = 255 170 | YKUSH_PORT_STATE_DICT = {0: "DOWN", 1: "UP", 255: "ERROR"} 171 | 172 | 173 | def hid_enumerate(vid=0, pid=0): 174 | '''HID enumerate wrapper function''' 175 | for info in hid.enumerate(vid, pid) if _usingHid else hidapi.enumerate(vid, pid): 176 | if _usingHid: 177 | ret = info 178 | else: 179 | # unfortunately there is no __dict__ attr in the cffi DeviceInfo object 180 | ret = dict([(p, getattr(info, p)) for p in info.__slots__]) 181 | yield ret 182 | 183 | 184 | class YKUSHNotFound(Exception): 185 | '''YKUSH not found exception''' 186 | 187 | def __str__(self): 188 | return 'YKUSH device not found' 189 | 190 | 191 | class YKUSH(object): 192 | 193 | '''YKUSH hidapi based interface class''' 194 | 195 | def __init__(self, serial=None, path=None): 196 | '''Constructor, the algorithm will connect to the first YKUSH found if a path or serial number is not provided''' 197 | self._devhandle = None 198 | self._firmware_major_version = None 199 | self._firmware_minor_version = None 200 | self._downstream_port_count = None 201 | #Alber3.2 add self._proudct_id 202 | self._proudct_id = None 203 | if path: 204 | # open the provided path 205 | if _usingHid: 206 | # blocking by default 207 | self._devhandle = hid.device() 208 | self._devhandle.open_path(path) 209 | else: 210 | # also blocking by default but ensure it is 211 | self._devhandle = hidapi.Device(path=path, blocking=True) 212 | else: 213 | # otherwise try to locate a device 214 | for device in hid_enumerate(0, 0): 215 | if device['vendor_id'] == YKUSH_USB_VID and device['product_id'] in YKUSH_USB_PID_LIST: 216 | if serial is None or serial == device['serial_number']: 217 | #Alber3.1 3.2 object attribute for YKUSHXS 218 | self._proudct_id = device['product_id'] 219 | return self.__init__(path=device['path']) 220 | if self._devhandle is None: 221 | raise YKUSHNotFound() 222 | 223 | def __del__(self): 224 | '''Destructor, release the device''' 225 | if self._devhandle: 226 | self._devhandle.close() 227 | 228 | def get_product_string(self): 229 | '''Returns the device product string''' 230 | return self._devhandle.get_product_string() 231 | 232 | def get_serial_number_string(self): 233 | '''Returns the device serial number string''' 234 | return self._devhandle.get_serial_number_string() 235 | 236 | def get_firmware_version(self): 237 | '''Returns a tuple with YKUSH firmware version in format (major, minor)''' 238 | if self._firmware_major_version is None: 239 | status, major, minor = self._raw_sendreceive([0xf0])[:3] 240 | if status == YKUSH_PROTO_OK_STATUS: 241 | self._firmware_major_version, self._firmware_minor_version = (major, minor) 242 | else: 243 | # early devices will not recognize it, figure it out from serial 244 | self._firmware_major_version = 1 245 | self._firmware_minor_version = 2 if 'YK2' in self.get_serial_number_string() else 255 if 'YKD2' in self.get_serial_number_string() else 0 246 | return self._firmware_major_version, self._firmware_minor_version 247 | 248 | 249 | def get_downstream_port_count(self): 250 | '''Returns the YKUSH downstream port count''' 251 | if self._downstream_port_count is None: 252 | status, count = self._raw_sendreceive([0xf1])[:2] 253 | # hardware identifier 1 devices will not recognize the operation 254 | if status == YKUSH_PROTO_OK_STATUS: 255 | # YKUSH recognized the request 256 | self._downstream_port_count = count 257 | else: 258 | # original YKUSH 1,3 port count 259 | self._downstream_port_count = 3 260 | #Alber3.3 check if 0xf0cd:YKUSHXS Make it have 1 port 261 | if self._proudct_id == 0xf0cd: 262 | self._downstream_port_count = 1 263 | 264 | return self._downstream_port_count 265 | 266 | def get_port_state(self, port_number): 267 | '''Returns a specific downstream port state; returns 0 (port down), 1 (port up) or 255 (error)''' 268 | if port_number in range(1, self.get_downstream_port_count() + 1): 269 | status, port_state = self._raw_sendreceive([0x20 | port_number])[:2] 270 | if status == YKUSH_PROTO_OK_STATUS: 271 | return YKUSH_PORT_STATE_UP if port_state > 0x10 else YKUSH_PORT_STATE_DOWN 272 | return YKUSH_PORT_STATE_ERROR 273 | 274 | def get_allports_state(self): 275 | '''Returns all downstream port states; an array filled with 1 (port up), 0 (port down) or 255 (port error) in port order''' 276 | if self.get_firmware_version()[0] > 1: 277 | recvbytes = self._raw_sendreceive([0x2a])[:self.get_downstream_port_count() + 1] 278 | if recvbytes[0] == YKUSH_PROTO_OK_STATUS: 279 | return [YKUSH_PORT_STATE_UP if p > 0x10 else YKUSH_PORT_STATE_DOWN for p in recvbytes[1:self.get_downstream_port_count() + 1]] 280 | else: 281 | return [YKUSH_PORT_STATE_ERROR] * self.get_downstream_port_count() 282 | else: 283 | # firmware glitch workaround 284 | return [self.get_port_state(p) for p in range(1, self.get_downstream_port_count() + 1)] 285 | 286 | def get_power_output_state(self): 287 | '''Returns the power output port state; returns 0 (port down), 1 (port up) or 255 (error)''' 288 | status, port_state = self._raw_sendreceive([0x24])[:2] 289 | if status == YKUSH_PROTO_OK_STATUS: 290 | return YKUSH_PORT_STATE_UP if port_state == 0x14 else YKUSH_PORT_STATE_DOWN 291 | return YKUSH_PORT_STATE_ERROR 292 | 293 | def get_allports_persistent_state(self): 294 | '''Returns all downstream persistent port states; an array filled with 1 (port up), 0 (port down) or 255 (port error) in port order''' 295 | recvbytes = self._raw_sendreceive([0x3a])[:self.get_downstream_port_count() + 1] 296 | if recvbytes[0] == YKUSH_PROTO_OK_STATUS: 297 | return [YKUSH_PORT_STATE_UP if p > 0x10 else YKUSH_PORT_STATE_DOWN for p in recvbytes[1:self.get_downstream_port_count() + 1]] 298 | elif self.get_firmware_version()[0] == 1: 299 | return [YKUSH_PORT_STATE_UP] * self.get_downstream_port_count() 300 | else: 301 | return [YKUSH_PORT_STATE_ERROR] * self.get_downstream_port_count() 302 | 303 | def set_port_state(self, port_number, new_state): 304 | '''Set a specific downstream port Up (1) or Down (0), returns True if the operation suceeded''' 305 | if port_number in range(1, self.get_downstream_port_count() + 1) and new_state in range(2): 306 | recvbytes = self._raw_sendreceive([(new_state == YKUSH_PORT_STATE_UP and 0x10 or 0x0) | port_number]) 307 | return recvbytes[0] == YKUSH_PROTO_OK_STATUS 308 | else: 309 | return False 310 | 311 | def set_allports_state_down(self): 312 | '''Power down all YKUSH downstreams ports, returns True if the operation suceeded''' 313 | return self._raw_sendreceive([0x0a])[0] == YKUSH_PROTO_OK_STATUS 314 | 315 | def set_allports_state_up(self): 316 | '''Power up all YKUSH downstreams ports, returns True if the operation suceeded''' 317 | return self._raw_sendreceive([0x1a])[0] == YKUSH_PROTO_OK_STATUS 318 | 319 | def set_power_output_on(self): 320 | '''Switch ON the 5V power output port, returns True if the operation suceeded''' 321 | return self._raw_sendreceive([0x14])[0] == YKUSH_PROTO_OK_STATUS 322 | 323 | def set_power_output_off(self): 324 | '''Switch OFF the 5V power output port, returns True if the operation suceeded''' 325 | return self._raw_sendreceive([0x04])[0] == YKUSH_PROTO_OK_STATUS 326 | 327 | def set_running_configuration_persistent(self): 328 | '''Make persistent the current device configuration, returns True if the operation suceeded''' 329 | if self.get_firmware_version()[0] > 1: 330 | return self._raw_sendreceive([0x3b])[0] == YKUSH_PROTO_OK_STATUS 331 | else: 332 | # unsupported on early firmware versions 333 | return False 334 | 335 | def _raw_sendreceive(self, packetarray): 336 | '''Internal method, submit a command and read the response from YKUSH''' 337 | # build the packet according to the report packet size 338 | # note: no buffer optimization was made for the sake of simplicity 339 | if _usingHid: 340 | packetarray = [0x00] + packetarray + [0x00] * (YKUSH_USB_PACKET_SIZE - len(packetarray)) 341 | self._devhandle.write(packetarray) 342 | recvpacket = self._devhandle.read(max_length=YKUSH_USB_PACKET_SIZE + 1, timeout_ms=YKUSH_USB_TIMEOUT) 343 | else: 344 | packetarray = packetarray + [0x00] * (YKUSH_USB_PACKET_SIZE - len(packetarray)) 345 | packet = struct.pack('<%dB' % YKUSH_USB_PACKET_SIZE, *packetarray) 346 | self._devhandle.write(packet) 347 | recvpacket = self._devhandle.read(length=YKUSH_USB_PACKET_SIZE + 1, timeout_ms=YKUSH_USB_TIMEOUT) 348 | # if not None return the bytes we actually need 349 | if recvpacket is None or len(recvpacket) < YKUSH_USB_PACKET_PAYLOAD_SIZE: 350 | return [0xff] * YKUSH_USB_PACKET_PAYLOAD_SIZE 351 | return recvpacket[:YKUSH_USB_PACKET_PAYLOAD_SIZE] if _usingHid else struct.unpack('<%iB' % YKUSH_USB_PACKET_PAYLOAD_SIZE, recvpacket[:YKUSH_USB_PACKET_PAYLOAD_SIZE]) 352 | 353 | 354 | def main(): 355 | '''Just in case all you need is a command line tool''' 356 | from argparse import ArgumentParser 357 | 358 | # argument parser description 359 | parser = ArgumentParser(description='Yepkit YKUSH command line tool.') 360 | parser.add_argument('-s', '--serial', default=None, help='specify the serial number string of the YKUSH to be listed or managed') 361 | group = parser.add_mutually_exclusive_group(required=True) 362 | group.add_argument('-l', '--list', help='list YKUSH devices', action='store_true') 363 | group.add_argument('-u', '--up', type=int, nargs='*', 364 | help='the downstream port numbers to power up, none means all') 365 | group.add_argument('-d', '--down', type=int, nargs='*', 366 | help='the downstream port numbers to power down, none means all') 367 | group.add_argument('-o', '--power_on', help='switch ON 5V power output', action='store_true') 368 | group.add_argument('-f', '--power_off', help='switch OFF 5V power output', action='store_true') 369 | group.add_argument('-p', '--persist', default=None, 370 | help='make the current running configuration persistent across reboots (only supported on devices with firmware v2.0 and above)', 371 | action='store_true') 372 | args = parser.parse_args() 373 | 374 | # say hello 375 | print('%s YKUSH family devices%s' % 376 | (args.list and 'listing' or 'managing', 377 | args.serial is None and ' ' or ' with serial number %s' % (args.serial))) 378 | try: 379 | ykush_found = False 380 | for device in hid_enumerate(0, 0): 381 | if device['vendor_id'] == YKUSH_USB_VID and device['product_id'] in YKUSH_USB_PID_LIST + YKUSH_USB_PID_BL_LIST: 382 | if args.serial is None or args.serial == device['serial_number']: 383 | ykush_found = True 384 | print(' found a %s release %s device with serial number %s' % 385 | (device['product_string'], device['release_number'], device['serial_number'])) 386 | print(' system device path %s, vendor id 0x%.4x, product id 0x%.4x' % (device['path'].decode(), device['vendor_id'], device['product_id'])) 387 | if device['product_id'] in YKUSH_USB_PID_BL_LIST: 388 | print(' control functions are not available, the device is working in bootloader mode') 389 | else: 390 | ykush = None 391 | try: 392 | ykush = YKUSH(path=device['path']) 393 | #Alber3.3 check if YKUSHXS make it 1 port 394 | if device['product_id'] == 0xf0cd: 395 | print(' the device has 1 downstream port') 396 | else: 397 | print(' the device is running a v%i.%i firmware and has %i downstream ports' % (ykush.get_firmware_version() + (ykush.get_downstream_port_count(),))) 398 | except IOError: 399 | if args.list: 400 | print(' warning: could not communicate, the device may be in use or') 401 | print(' your user do not have access rights to do so, in the latter') 402 | print(' case you may work around the by using sudo, for example:') 403 | print(' sudo python pykush.py -l') 404 | print(' if you are using the binary version:') 405 | print(' sudo pykush -l') 406 | else: 407 | raise 408 | if ykush: 409 | cmds = [] 410 | if args.list: 411 | # list requested, attempting to get all port states 412 | t = ykush.get_allports_state() 413 | #Alber3.3 check if YKUSHXS the make it 1 port-- 414 | if device['product_id'] == 0xf0cd: 415 | tt = t[0] 416 | print(' Checking running power state, port 1 : ' + YKUSH_PORT_STATE_DICT[tt]) 417 | else: 418 | print(' downstream running power states, port 1 to %i: %s' % 419 | (ykush.get_downstream_port_count(), ', '.join([YKUSH_PORT_STATE_DICT[s] for s in t]))) 420 | # YKUSH firmware below v2 does not support persistence functions 421 | if ykush.get_firmware_version()[0] > 1: 422 | t = ykush.get_allports_persistent_state() 423 | if t[0] != YKUSH_PORT_STATE_ERROR: 424 | print(' downstream startup/persistent power states, port 1 to %i: %s' % 425 | (ykush.get_downstream_port_count(), ', '.join([YKUSH_PORT_STATE_DICT[s] for s in t]))) 426 | if args.up is not None: 427 | if len(args.up) == 0: 428 | #Alber3.3 check if YKUSHXS the make it 1 port-- 429 | if device['product_id'] == 0xf0cd: 430 | print(' powering UP the downstream port... ', end='') 431 | print('done' if ykush.set_allports_state_up() else 'unexpected error') 432 | else: 433 | print(' powering UP all downstream ports... ', end='') 434 | print('done' if ykush.set_allports_state_up() else 'unexpected error') 435 | else: 436 | cmds += zip(args.up, [YKUSH_PORT_STATE_UP for _ in range(len(args.up))]) 437 | if args.down is not None: 438 | if len(args.down) == 0: 439 | #Alber3.3 check if YKUSHXS the make it 1 port-- 440 | if device['product_id'] == 0xf0cd: 441 | print(' powering DOWN the downstream port... ', end='') 442 | print('done' if ykush.set_allports_state_down() else 'unexpected error') 443 | else : 444 | print(' powering DOWN all downstream ports... ', end='') 445 | print('done' if ykush.set_allports_state_down() else 'unexpected error') 446 | else: 447 | cmds += zip(args.down, [YKUSH_PORT_STATE_DOWN for _ in range(len(args.down))]) 448 | for cfg in cmds: 449 | print(' powering %s port %i... ' % (YKUSH_PORT_STATE_DICT[cfg[1]], cfg[0]), end='') 450 | print('done' if ykush.set_port_state(cfg[0], cfg[1]) else 'error, could not configure the specified port number') 451 | if args.power_on: 452 | print(' powering ON 5V switchable power output... ', end='') 453 | print('done' if ykush.set_power_output_on() else 'unexpected error') 454 | if args.power_off: 455 | print(' powering OFF 5V switchable power output... ', end='') 456 | print('done' if ykush.set_power_output_off() else 'unexpected error') 457 | if args.persist: 458 | if ykush.get_firmware_version()[0] > 1: 459 | print(' making running device configuration persistent... ', end='') 460 | print('done' if ykush.set_running_configuration_persistent() else 'unexpected error') 461 | else: 462 | print(' error, command only supported on devices with firmware v2.0 and above') 463 | if not ykush_found: 464 | print('no YKUSH devices found') 465 | except (ValueError, IOError, OSError) as e: 466 | print('communication error, exception details:') 467 | print(' error "%s"' % e.message) 468 | sys.exit(1) 469 | 470 | 471 | if __name__ == '__main__': 472 | main() 473 | 474 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding: utf-8 3 | 4 | from __future__ import unicode_literals 5 | 6 | from setuptools import setup, find_packages 7 | 8 | version = '0.4.0' 9 | 10 | setup( 11 | name='pykush', 12 | version=version, 13 | description='Yepkit YKUSH Python API and command line tool', 14 | long_description=open('README.md').read(), 15 | author='ckuesters', 16 | author_email='ckuesters@yepkit.com', 17 | license='MIT', 18 | keywords=['yepkit', 'ykush', 'pykush'], 19 | url='https://github.com/yepkit/pykush', 20 | packages=find_packages(), 21 | install_requires=[ 22 | 'hidapi>=0.7.99', 23 | ], 24 | entry_points={ 25 | 'console_scripts': [ 26 | 'pykush=pykush.pykush:main' 27 | ], 28 | }, 29 | classifiers=[ 30 | "Development Status :: 3 - Alpha", 31 | "License :: OSI Approved :: MIT License", 32 | "Environment :: Console", 33 | "Intended Audience :: Developers", 34 | "Operating System :: POSIX :: Linux", 35 | "Operating System :: Microsoft :: Windows", 36 | "Operating System :: MacOS :: MacOS X", 37 | "Programming Language :: Python :: 2.7", 38 | "Programming Language :: Python :: 3.4", 39 | "Topic :: Utilities", 40 | "Topic :: System :: Hardware :: Hardware Drivers", 41 | ], 42 | ) 43 | --------------------------------------------------------------------------------